Datasets:
AI4M
/

text
stringlengths
0
3.34M
theory msucc imports mlt begin context Ordinal_Model begin theorem mzero_mord : "m0 : mOrd" unfolding mzero_def using mordI[OF zero_ord] . lemmas mzero_m = mord_m[OF mzero_mord] lemma mzero_mlt : assumes j:"j : mOrd" shows "\<not> (j \<lless> m0)" unfolding mzero_def proof (rule mordE[OF j], auto) fix j' assume "j' : Ord" "<ord, j'> \<lless> <ord, 0>" hence "j' < 0" using mltD by auto thus "False" using zero_lt[OF \<open>j' : Ord\<close>] by auto qed theorem mzero_ax : "m\<forall>b : mOrd. \<not> b \<lless> m0" unfolding mtall_def mall_def using mzero_mlt by auto lemma msucc'_mord : assumes j : "j : mOrd" shows "msucc' j : mOrd" unfolding msucc'_def using mordI[OF succ_ord[OF mord_snd_ord[OF j]]] . lemma msucc_mord : assumes j : "j : mOrd" shows "msucc j : mOrd" unfolding msucc_def using msucc'_mord[OF j] j by auto lemma msucc_m : "msucc j : M" unfolding msucc_def using mord_m[OF msucc'_mord] Ordinal_Model_mdefault_m by auto lemma msucc_eq : assumes j' : "j' : Ord" shows "msucc <ord, j'> = <ord, succ j'>" unfolding msucc_def msucc'_def using mordI[OF j'] mord_snd_eq by auto lemma msuccI : assumes i : "i : mOrd" and j : "j : mOrd" and ij:"i \<lless> j \<or> i = j" shows "i \<lless> msucc j" proof (rule mordE[OF i], rule mordE[OF j]) fix i' j' assume i': "i' : Ord" "i = <ord, i'>" and j': "j' : Ord" "j = <ord, j'>" from ij have "i' < succ j'" unfolding i' j' using leqI1[OF i'(1) j'(1) mltD] leqI2[OF i'(1) j'(1) mord_pair_inject[OF i'(1) j'(1)]] by auto thus "i \<lless> msucc j" unfolding i' j' msucc_eq[OF j'(1)] using mltI[OF i'(1) succ_ord[OF j'(1)]] by auto qed lemma msuccD : assumes i : "i : mOrd" and j : "j : mOrd" and ij: "i \<lless> msucc j" shows "i \<lless> j \<or> i = j" proof (rule mordE[OF i], rule mordE[OF j]) fix i' j' assume i': "i' : Ord" "i = <ord, i'>" and j': "j' : Ord" "j = <ord, j'>" from ij have "i' < succ j'" unfolding i' j' msucc_eq[OF j'(1)] using mltD by auto hence "i' < j' \<or> i' = j'" using leqE[OF i'(1) j'(1)] by auto thus "i \<lless> j \<or> i = j" unfolding i' j' using mltI[OF i'(1) j'(1)] by auto qed theorem msucc_ax : "m\<forall>i : mOrd. m\<forall>j : mOrd. i \<lless> msucc j \<longleftrightarrow> (i \<lless> j \<or> i = j)" unfolding mtall_def mall_def using msuccI msuccD by blast end end
{-# OPTIONS --safe --warning=error --without-K #-} open import LogicalFormulae open import Setoids.Setoids open import Rings.Definition open import Rings.IntegralDomains.Definition open import Agda.Primitive using (Level; lzero; lsuc; _⊔_) module Rings.Irreducibles.Definition {a b : _} {A : Set a} {S : Setoid {a} {b} A} {_+_ _*_ : A → A → A} {R : Ring S _+_ _*_} (intDom : IntegralDomain R) where open Setoid S open Ring R open import Rings.Units.Definition R record Irreducible (r : A) : Set (a ⊔ b) where field nonzero : (r ∼ 0R) → False nonunit : (Unit r) → False irreducible : (x y : A) → (x * y) ∼ r → (Unit x → False) → Unit y
[STATEMENT] lemma Ord_Inter [intro,simp]: "\<lbrakk> \<And>i. i\<^bold>\<in>A \<Longrightarrow> Ord(i) \<rbrakk> \<Longrightarrow> Ord(\<Sqinter> A)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<And>i. i \<^bold>\<in> A \<Longrightarrow> Ord i) \<Longrightarrow> Ord (\<Sqinter>A) [PROOF STEP] apply (case_tac "A=0", auto simp: Ord_def Transset_def) [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<And>y x ya. \<lbrakk>\<And>i. i \<^bold>\<in> A \<Longrightarrow> (\<forall>y. y \<^bold>\<in> i \<longrightarrow> y \<le> i) \<and> (\<forall>x\<^bold>\<in>i. \<forall>y. y \<^bold>\<in> x \<longrightarrow> y \<le> x); A \<noteq> 0; \<forall>ya. ya \<^bold>\<in> A \<longrightarrow> y \<^bold>\<in> ya; x \<^bold>\<in> y; ya \<^bold>\<in> A\<rbrakk> \<Longrightarrow> x \<^bold>\<in> ya 2. \<And>x y xa. \<lbrakk>\<And>i. i \<^bold>\<in> A \<Longrightarrow> (\<forall>y. y \<^bold>\<in> i \<longrightarrow> y \<le> i) \<and> (\<forall>x\<^bold>\<in>i. \<forall>y. y \<^bold>\<in> x \<longrightarrow> y \<le> x); A \<noteq> 0; \<forall>y. y \<^bold>\<in> A \<longrightarrow> x \<^bold>\<in> y; y \<^bold>\<in> x; xa \<^bold>\<in> y\<rbrakk> \<Longrightarrow> xa \<^bold>\<in> x [PROOF STEP] apply (force simp add: hf_ext)+ [PROOF STATE] proof (prove) goal: No subgoals! [PROOF STEP] done
[STATEMENT] lemma mk_exp_cupcake: "wellformed t \<Longrightarrow> is_cupcake_exp (mk_exp S t)" "wellformed t \<Longrightarrow> is_cupcake_exp (mk_con S t)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (pre_strong_term_class.wellformed t \<Longrightarrow> is_cupcake_exp (mk_exp S t)) &&& (pre_strong_term_class.wellformed t \<Longrightarrow> is_cupcake_exp (mk_con S t)) [PROOF STEP] by (metis mk_exp_cupcake0)+
Volunteers are given training and support to talk to their communities about how to save water. In the UK we use approximately 150 litres of water per person per day. Current groundwater supplies – water that exists beneath the earth's surface – are very low with levels more than 50% lower than they should be. Water Wardens play an important role in slowing down the loss of this water so helping to maintain water supplies for the whole community. The Water Warden's mission is to talk to at least 20 people in Luton about how they can do things a little bit differently in order to use less water, saving them energy and money. There are benefits for the volunteers, too: they're able to help their community and the environment; gain experience and training; boost their confidence and build links with their neighbourhood.
/- Copyright (c) 2021 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import ring_theory.polynomial.cyclotomic.basic /-! # Not all coefficients of cyclotomic polynomials are -1, 0, or 1 We show that not all coefficients of cyclotomic polynomials are equal to `0`, `-1` or `1`, in the theorem `not_forall_coeff_cyclotomic_neg_one_zero_one`. We prove this with the counterexample `coeff_cyclotomic_105 : coeff (cyclotomic 105 ℤ) 7 = -2`. -/ section computation lemma prime_3 : nat.prime 3 := by norm_num lemma prime_5 : nat.prime 5 := by norm_num lemma prime_7 : nat.prime 7 := by norm_num lemma proper_divisors_15 : nat.proper_divisors 15 = {1, 3, 5} := rfl lemma proper_divisors_21 : nat.proper_divisors 21 = {1, 3, 7} := rfl lemma proper_divisors_35 : nat.proper_divisors 35 = {1, 5, 7} := rfl lemma proper_divisors_105 : nat.proper_divisors 105 = {1, 3, 5, 7, 15, 21, 35} := rfl end computation open polynomial lemma cyclotomic_3 : cyclotomic 3 ℤ = 1 + X + X ^ 2 := begin refine ((eq_cyclotomic_iff (show 0 < 3, by norm_num) _).2 _).symm, rw nat.prime.proper_divisors prime_3, simp only [finset.prod_singleton, cyclotomic_one], ring end lemma cyclotomic_5 : cyclotomic 5 ℤ = 1 + X + X ^ 2 + X ^ 3 + X ^ 4 := begin refine ((eq_cyclotomic_iff (nat.prime.pos prime_5) _).2 _).symm, rw nat.prime.proper_divisors prime_5, simp only [finset.prod_singleton, cyclotomic_one], ring end lemma cyclotomic_7 : cyclotomic 7 ℤ = 1 + X + X ^ 2 + X ^ 3 + X ^ 4 + X ^ 5 + X ^ 6 := begin refine ((eq_cyclotomic_iff (nat.prime.pos prime_7) _).2 _).symm, rw nat.prime.proper_divisors prime_7, simp only [finset.prod_singleton, cyclotomic_one], ring end lemma cyclotomic_15 : cyclotomic 15 ℤ = 1 - X + X ^ 3 - X ^ 4 + X ^ 5 - X ^ 7 + X ^ 8 := begin refine ((eq_cyclotomic_iff (show 0 < 15, by norm_num) _).2 _).symm, rw [proper_divisors_15, finset.prod_insert _, finset.prod_insert _, finset.prod_singleton, cyclotomic_one, cyclotomic_3, cyclotomic_5], ring, repeat { norm_num } end lemma cyclotomic_21 : cyclotomic 21 ℤ = 1 - X + X ^ 3 - X ^ 4 + X ^ 6 - X ^ 8 + X ^ 9 - X ^ 11 + X ^ 12 := begin refine ((eq_cyclotomic_iff (show 0 < 21, by norm_num) _).2 _).symm, rw [proper_divisors_21, finset.prod_insert _, finset.prod_insert _, finset.prod_singleton, cyclotomic_one, cyclotomic_3, cyclotomic_7], ring, repeat { norm_num } end lemma cyclotomic_35 : cyclotomic 35 ℤ = 1 - X + X ^ 5 - X ^ 6 + X ^ 7 - X ^ 8 + X ^ 10 - X ^ 11 + X ^ 12 - X ^ 13 + X ^ 14 - X ^ 16 + X ^ 17 - X ^ 18 + X ^ 19 - X ^ 23 + X ^ 24 := begin refine ((eq_cyclotomic_iff (show 0 < 35, by norm_num) _).2 _).symm, rw [proper_divisors_35, finset.prod_insert _, finset.prod_insert _, finset.prod_singleton, cyclotomic_one, cyclotomic_5, cyclotomic_7], ring, repeat { norm_num } end lemma cyclotomic_105 : cyclotomic 105 ℤ = 1 + X + X ^ 2 - X ^ 5 - X ^ 6 - 2 * X ^ 7 - X ^ 8 - X ^ 9 + X ^ 12 + X ^ 13 + X ^ 14 + X ^ 15 + X ^ 16 + X ^ 17 - X ^ 20 - X ^ 22 - X ^ 24 - X ^ 26 - X ^ 28 + X ^ 31 + X ^ 32 + X ^ 33 + X ^ 34 + X ^ 35 + X ^ 36 - X ^ 39 - X ^ 40 - 2 * X ^ 41 - X ^ 42 - X ^ 43 + X ^ 46 + X ^ 47 + X ^ 48 := begin refine ((eq_cyclotomic_iff (show 0 < 105, by norm_num) _).2 _).symm, rw proper_divisors_105, repeat {rw finset.prod_insert _}, rw [finset.prod_singleton, cyclotomic_one, cyclotomic_3, cyclotomic_5, cyclotomic_7, cyclotomic_15, cyclotomic_21, cyclotomic_35], ring, repeat { norm_num } end lemma coeff_cyclotomic_105 : coeff (cyclotomic 105 ℤ) 7 = -2 := begin simp [cyclotomic_105, coeff_X_pow, coeff_one, coeff_X_of_ne_one, coeff_bit0_mul, coeff_bit1_mul] end lemma not_forall_coeff_cyclotomic_neg_one_zero_one : ¬∀ n i, coeff (cyclotomic n ℤ) i ∈ ({-1, 0, 1} : set ℤ) := begin intro h, replace h := h 105 7, rw coeff_cyclotomic_105 at h, norm_num at h end
module Network.Curl.Prim.Global ------------------------------------------------- -- Global ------------------------------------------------- -- curl_global_cleanup -- curl_global_init -- curl_global_init_mem -- not implemented -- curl_global_sslset -- not implemented ------------------------------------------------- import Network.Curl.Types import System.FFI import Derive.Prim %language ElabReflection export %foreign "C:curl_global_init,libcurl,curl/curl.h" prim_curl_global_init : Int -> PrimIO Int ||| We use CURL_GLOBAL_ALL since that's the only useful flag in this libcurl ||| version. CURL_GLOBAL_ALL = 3 on my system export curl_global_init : HasIO io => io CurlECode curl_global_init = unsafeFromCode <$> primIO (prim_curl_global_init 3) %runElab makeHasIO "curl_global_cleanup" Export `[ %foreign "C:curl_global_cleanup,libcurl,curl/curl.h" export prim_curl_global_cleanup : PrimIO () ] --`
Formal statement is: lemma continuous_inner[continuous_intros]: assumes "continuous F f" and "continuous F g" shows "continuous F (\<lambda>x. inner (f x) (g x))" Informal statement is: If $f$ and $g$ are continuous functions from a topological space $X$ to a normed vector space $V$, then the function $x \mapsto \langle f(x), g(x) \rangle$ is continuous.
""" phase_teleportation(zxd) Reducing T-count of `zxd` with the algorithms in [arXiv:1903.10477](https://arxiv.org/abs/1903.10477). """ function phase_teleportation(cir::ZXDiagram{T, P}) where {T, P} zxg = ZXGraph(cir) ncir = zxg.master simplify!(Rule{:lc}(), zxg) simplify!(Rule{:p1}(), zxg) simplify!(Rule{:p2}(), zxg) simplify!(Rule{:p3}(), zxg) simplify!(Rule{:p1}(), zxg) match_id = match(Rule{:id}(), zxg) match_gf = match(Rule{:gf}(), zxg) while length(match_id) + length(match_gf) > 0 rewrite!(Rule{:id}(), zxg, match_id) rewrite!(Rule{:gf}(), zxg, match_gf) simplify!(Rule{:lc}(), zxg) simplify!(Rule{:p1}(), zxg) simplify!(Rule{:p2}(), zxg) simplify!(Rule{:p3}(), zxg) simplify!(Rule{:p1}(), zxg) match_id = match(Rule{:id}(), zxg) match_gf = match(Rule{:gf}(), zxg) end simplify!(Rule{:i1}(), ncir) simplify!(Rule{:i2}(), ncir) return ncir end function phase_teleportation(bir::BlockIR) zxd = convert_to_zxd(bir) nzxd = phase_teleportation(zxd) chain = convert_to_chain(nzxd) return BlockIR(bir.parent, bir.nqubits, chain) end
State Before: n : ℕ ⊢ hyperoperation (n + 1) 2 2 = 4 State After: case zero ⊢ hyperoperation (Nat.zero + 1) 2 2 = 4 case succ nn : ℕ nih : hyperoperation (nn + 1) 2 2 = 4 ⊢ hyperoperation (Nat.succ nn + 1) 2 2 = 4 Tactic: induction' n with nn nih State Before: case zero ⊢ hyperoperation (Nat.zero + 1) 2 2 = 4 State After: no goals Tactic: rw [hyperoperation_one] State Before: case succ nn : ℕ nih : hyperoperation (nn + 1) 2 2 = 4 ⊢ hyperoperation (Nat.succ nn + 1) 2 2 = 4 State After: no goals Tactic: rw [hyperoperation_recursion, hyperoperation_ge_two_eq_self, nih]
lemma unit_factor_snd_quot_of_fract: "unit_factor (snd (quot_of_fract x)) = 1"
lemma convexI: assumes "\<And>x y u v. x \<in> s \<Longrightarrow> y \<in> s \<Longrightarrow> 0 \<le> u \<Longrightarrow> 0 \<le> v \<Longrightarrow> u + v = 1 \<Longrightarrow> u *\<^sub>R x + v *\<^sub>R y \<in> s" shows "convex s"
lemma lmeasurable_ball [simp]: "ball a r \<in> lmeasurable"
(* Title: FunctorCategory Author: Eugene W. Stark <[email protected]>, 2016 Maintainer: Eugene W. Stark <[email protected]> *) chapter FunctorCategory theory FunctorCategory imports ConcreteCategory BinaryFunctor begin text\<open> The functor category \<open>[A, B]\<close> is the category whose objects are functors from @{term A} to @{term B} and whose arrows correspond to natural transformations between these functors. \<close> section "Construction" text\<open> Since the arrows of a functor category cannot (in the context of the present development) be directly identified with natural transformations, but rather only with natural transformations that have been equipped with their domain and codomain functors, and since there is no natural value to serve as @{term null}, we use the general-purpose construction given by @{locale concrete_category} to define this category. \<close> locale functor_category = A: category A + B: category B for A :: "'a comp" (infixr "\<cdot>\<^sub>A" 55) and B :: "'b comp" (infixr "\<cdot>\<^sub>B" 55) begin notation A.in_hom ("\<guillemotleft>_ : _ \<rightarrow>\<^sub>A _\<guillemotright>") notation B.in_hom ("\<guillemotleft>_ : _ \<rightarrow>\<^sub>B _\<guillemotright>") type_synonym ('aa, 'bb) arr = "('aa \<Rightarrow> 'bb, 'aa \<Rightarrow> 'bb) concrete_category.arr" sublocale concrete_category \<open>Collect (functor A B)\<close> \<open>\<lambda>F G. Collect (natural_transformation A B F G)\<close> \<open>\<lambda>F. F\<close> \<open>\<lambda>F G H \<tau> \<sigma>. vertical_composite.map A B \<sigma> \<tau>\<close> using vcomp_assoc apply (unfold_locales, simp_all) proof - fix F G H \<sigma> \<tau> assume F: "functor (\<cdot>\<^sub>A) (\<cdot>\<^sub>B) F" assume G: "functor (\<cdot>\<^sub>A) (\<cdot>\<^sub>B) G" assume H: "functor (\<cdot>\<^sub>A) (\<cdot>\<^sub>B) H" assume \<sigma>: "natural_transformation (\<cdot>\<^sub>A) (\<cdot>\<^sub>B) F G \<sigma>" assume \<tau>: "natural_transformation (\<cdot>\<^sub>A) (\<cdot>\<^sub>B) G H \<tau>" interpret F: "functor" A B F using F by simp interpret G: "functor" A B G using G by simp interpret H: "functor" A B H using H by simp interpret \<sigma>: natural_transformation A B F G \<sigma> using \<sigma> by simp interpret \<tau>: natural_transformation A B G H \<tau> using \<tau> by simp interpret \<tau>\<sigma>: vertical_composite A B F G H \<sigma> \<tau> .. show "natural_transformation (\<cdot>\<^sub>A) (\<cdot>\<^sub>B) F H (vertical_composite.map (\<cdot>\<^sub>A) (\<cdot>\<^sub>B) \<sigma> \<tau>)" using \<tau>\<sigma>.map_def \<tau>\<sigma>.is_natural_transformation by simp qed abbreviation comp (infixr "\<cdot>" 55) where "comp \<equiv> COMP" notation in_hom ("\<guillemotleft>_ : _ \<rightarrow> _\<guillemotright>") lemma arrI [intro]: assumes "f \<noteq> null" and "natural_transformation A B (Dom f) (Cod f) (Map f)" shows "arr f" using assms arr_char null_char by (simp add: natural_transformation_def) lemma arrE [elim]: assumes "arr f" and "f \<noteq> null \<Longrightarrow> natural_transformation A B (Dom f) (Cod f) (Map f) \<Longrightarrow> T" shows T using assms arr_char null_char by simp lemma arr_MkArr [iff]: shows "arr (MkArr F G \<tau>) \<longleftrightarrow> natural_transformation A B F G \<tau>" using arr_char null_char arr_MkArr natural_transformation_def by fastforce lemma ide_char [iff]: shows "ide t \<longleftrightarrow> t \<noteq> null \<and> functor A B (Map t) \<and> Dom t = Map t \<and> Cod t = Map t" using ide_char null_char by fastforce end section "Additional Properties" text\<open> In this section some additional facts are proved, which make it easier to work with the @{term "functor_category"} locale. \<close> context functor_category begin lemma Map_comp [simp]: assumes "seq t' t" and "A.seq a' a" shows "Map (t' \<cdot> t) (a' \<cdot>\<^sub>A a) = Map t' a' \<cdot>\<^sub>B Map t a" proof - interpret t: natural_transformation A B \<open>Dom t\<close> \<open>Cod t\<close> \<open>Map t\<close> using assms(1) arr_char seq_char by blast interpret t': natural_transformation A B \<open>Cod t\<close> \<open>Cod t'\<close> \<open>Map t'\<close> using assms(1) arr_char seq_char by force interpret t'ot: vertical_composite A B \<open>Dom t\<close> \<open>Cod t\<close> \<open>Cod t'\<close> \<open>Map t\<close> \<open>Map t'\<close> .. show ?thesis proof - have "Map (t' \<cdot> t) = t'ot.map" using assms(1) seq_char t'ot.natural_transformation_axioms by simp thus ?thesis using assms(2) t'ot.map_simp_2 t'.preserves_comp_2 B.comp_assoc by auto qed qed lemma Map_comp': assumes "seq t' t" shows "Map (t' \<cdot> t) = vertical_composite.map A B (Map t) (Map t')" proof - interpret t: natural_transformation A B \<open>Dom t\<close> \<open>Cod t\<close> \<open>Map t\<close> using assms(1) arr_char seq_char by blast interpret t': natural_transformation A B \<open>Cod t\<close> \<open>Cod t'\<close> \<open>Map t'\<close> using assms(1) arr_char seq_char by force interpret t'ot: vertical_composite A B \<open>Dom t\<close> \<open>Cod t\<close> \<open>Cod t'\<close> \<open>Map t\<close> \<open>Map t'\<close> .. show ?thesis using assms(1) seq_char t'ot.natural_transformation_axioms by simp qed lemma MkArr_eqI [intro]: assumes "arr (MkArr F G \<tau>)" and "F = F'" and "G = G'" and "\<tau> = \<tau>'" shows "MkArr F G \<tau> = MkArr F' G' \<tau>'" using assms arr_eqI by simp lemma MkArr_eqI' [intro]: assumes "arr (MkArr F G \<tau>)" and "\<tau> = \<tau>'" shows "MkArr F G \<tau> = MkArr F G \<tau>'" using assms arr_eqI by simp lemma iso_char [iff]: shows "iso t \<longleftrightarrow> t \<noteq> null \<and> natural_isomorphism A B (Dom t) (Cod t) (Map t)" proof assume t: "iso t" show "t \<noteq> null \<and> natural_isomorphism A B (Dom t) (Cod t) (Map t)" proof show "t \<noteq> null" using t arr_char iso_is_arr by auto from t obtain t' where t': "inverse_arrows t t'" by blast interpret \<tau>: natural_transformation A B \<open>Dom t\<close> \<open>Cod t\<close> \<open>Map t\<close> using t arr_char iso_is_arr by auto interpret \<tau>': natural_transformation A B \<open>Cod t\<close> \<open>Dom t\<close> \<open>Map t'\<close> using t' arr_char dom_char seq_char by (metis arrE ide_compE inverse_arrowsE) interpret \<tau>'o\<tau>: vertical_composite A B \<open>Dom t\<close> \<open>Cod t\<close> \<open>Dom t\<close> \<open>Map t\<close> \<open>Map t'\<close> .. interpret \<tau>o\<tau>': vertical_composite A B \<open>Cod t\<close> \<open>Dom t\<close> \<open>Cod t\<close> \<open>Map t'\<close> \<open>Map t\<close> .. show "natural_isomorphism A B (Dom t) (Cod t) (Map t)" proof fix a assume a: "A.ide a" show "B.iso (Map t a)" proof have 1: "\<tau>'o\<tau>.map = Dom t \<and> \<tau>o\<tau>'.map = Cod t" using t t' by (metis (no_types, lifting) Map_dom concrete_category.Map_comp concrete_category_axioms ide_compE inverse_arrowsE seq_char) show "B.inverse_arrows (Map t a) (Map t' a)" using a 1 \<tau>o\<tau>'.map_simp_ide \<tau>'o\<tau>.map_simp_ide \<tau>.F.preserves_ide \<tau>.G.preserves_ide by auto qed qed qed next assume t: "t \<noteq> null \<and> natural_isomorphism A B (Dom t) (Cod t) (Map t)" show "iso t" proof interpret \<tau>: natural_isomorphism A B \<open>Dom t\<close> \<open>Cod t\<close> \<open>Map t\<close> using t by auto interpret \<tau>': inverse_transformation A B \<open>Dom t\<close> \<open>Cod t\<close> \<open>Map t\<close> .. have 1: "vertical_composite.map A B (Map t) \<tau>'.map = Dom t \<and> vertical_composite.map A B \<tau>'.map (Map t) = Cod t" using \<tau>.natural_isomorphism_axioms vertical_composite_inverse_iso vertical_composite_iso_inverse by blast show "inverse_arrows t (MkArr (Cod t) (Dom t) (\<tau>'.map))" proof show 2: "ide (MkArr (Cod t) (Dom t) \<tau>'.map \<cdot> t)" using t 1 by (metis (no_types, lifting) MkArr_Map MkIde_Dom \<tau>'.natural_transformation_axioms \<tau>.natural_transformation_axioms arrI arr_MkArr comp_MkArr ide_dom) show "ide (t \<cdot> MkArr (Cod t) (Dom t) \<tau>'.map)" using t 1 2 by (metis Map.simps(1) \<tau>'.natural_transformation_axioms arr_MkArr comp_char dom_MkArr dom_comp ide_char' ide_compE) qed qed qed end section "Evaluation Functor" text\<open> This section defines the evaluation map that applies an arrow of the functor category \<open>[A, B]\<close> to an arrow of @{term A} to obtain an arrow of @{term B} and shows that it is functorial. \<close> locale evaluation_functor = A: category A + B: category B + A_B: functor_category A B + A_BxA: product_category A_B.comp A for A :: "'a comp" (infixr "\<cdot>\<^sub>A" 55) and B :: "'b comp" (infixr "\<cdot>\<^sub>B" 55) begin notation A_B.comp (infixr "\<cdot>\<^sub>[\<^sub>A\<^sub>,\<^sub>B\<^sub>]" 55) notation A_BxA.comp (infixr "\<cdot>\<^sub>[\<^sub>A\<^sub>,\<^sub>B\<^sub>]\<^sub>x\<^sub>A" 55) notation A_B.in_hom ("\<guillemotleft>_ : _ \<rightarrow>\<^sub>[\<^sub>A\<^sub>,\<^sub>B\<^sub>] _\<guillemotright>") notation A_BxA.in_hom ("\<guillemotleft>_ : _ \<rightarrow>\<^sub>[\<^sub>A\<^sub>,\<^sub>B\<^sub>]\<^sub>x\<^sub>A _\<guillemotright>") definition map where "map Fg \<equiv> if A_BxA.arr Fg then A_B.Map (fst Fg) (snd Fg) else B.null" lemma map_simp: assumes "A_BxA.arr Fg" shows "map Fg = A_B.Map(fst Fg) (snd Fg)" using assms map_def by auto lemma is_functor: shows "functor A_BxA.comp B map" proof show "\<And>Fg. \<not> A_BxA.arr Fg \<Longrightarrow> map Fg = B.null" using map_def by auto fix Fg assume Fg: "A_BxA.arr Fg" let ?F = "fst Fg" and ?g = "snd Fg" have F: "A_B.arr ?F" using Fg by auto have g: "A.arr ?g" using Fg by auto have DomF: "A_B.Dom ?F = A_B.Map (A_B.dom ?F)" using F by simp have CodF: "A_B.Cod ?F = A_B.Map (A_B.cod ?F)" using F by simp interpret F: natural_transformation A B \<open>A_B.Dom ?F\<close> \<open>A_B.Cod ?F\<close> \<open>A_B.Map ?F\<close> using Fg A_B.arr_char [of ?F] by blast show "B.arr (map Fg)" using Fg map_def by auto show "B.dom (map Fg) = map (A_BxA.dom Fg)" using g Fg map_def DomF by (metis (no_types, lifting) A_BxA.arr_dom A_BxA.dom_simp F.preserves_dom fst_conv snd_conv) show "B.cod (map Fg) = map (A_BxA.cod Fg)" using g Fg map_def CodF by (metis (no_types, lifting) A_BxA.arr_cod A_BxA.cod_simp F.preserves_cod fst_conv snd_conv) next fix Fg Fg' assume 1: "A_BxA.seq Fg' Fg" let ?F = "fst Fg" and ?g = "snd Fg" let ?F' = "fst Fg'" and ?g' = "snd Fg'" have F': "A_B.arr ?F'" using 1 A_BxA.seqE by blast have CodF: "A_B.Cod ?F = A_B.Map (A_B.cod ?F)" using 1 by (metis A_B.Map_cod A_B.seqE A_BxA.seqE) have DomF': "A_B.Dom ?F' = A_B.Map (A_B.dom ?F')" using F' by simp have seq_F'F: "A_B.seq ?F' ?F" using 1 by blast have seq_g'g: "A.seq ?g' ?g" using 1 by blast interpret F: natural_transformation A B \<open>A_B.Dom ?F\<close> \<open>A_B.Cod ?F\<close> \<open>A_B.Map ?F\<close> using 1 A_B.arr_char by blast interpret F': natural_transformation A B \<open>A_B.Cod ?F\<close> \<open>A_B.Cod ?F'\<close> \<open>A_B.Map ?F'\<close> using 1 A_B.arr_char seq_F'F CodF DomF' A_B.seqE by (metis mem_Collect_eq) interpret F'oF: vertical_composite A B \<open>A_B.Dom ?F\<close> \<open>A_B.Cod ?F\<close> \<open>A_B.Cod ?F'\<close> \<open>A_B.Map ?F\<close> \<open>A_B.Map ?F'\<close> .. show "map (Fg' \<cdot>\<^sub>[\<^sub>A\<^sub>,\<^sub>B\<^sub>]\<^sub>x\<^sub>A Fg) = map Fg' \<cdot>\<^sub>B map Fg" unfolding map_def using 1 seq_F'F seq_g'g by auto qed end sublocale evaluation_functor \<subseteq> "functor" A_BxA.comp B map using is_functor by auto sublocale evaluation_functor \<subseteq> binary_functor A_B.comp A B map .. section "Currying" text\<open> This section defines the notion of currying of a natural transformation between binary functors, to obtain a natural transformation between functors into a functor category, along with the inverse operation of uncurrying. We have only proved here what is needed to establish the results in theory \<open>Limit\<close> about limits in functor categories and have not attempted to fully develop the functoriality and naturality properties of these notions. \<close> locale currying = A1: category A1 + A2: category A2 + B: category B for A1 :: "'a1 comp" (infixr "\<cdot>\<^sub>A\<^sub>1" 55) and A2 :: "'a2 comp" (infixr "\<cdot>\<^sub>A\<^sub>2" 55) and B :: "'b comp" (infixr "\<cdot>\<^sub>B" 55) begin interpretation A1xA2: product_category A1 A2 .. interpretation A2_B: functor_category A2 B .. interpretation A2_BxA2: product_category A2_B.comp A2 .. interpretation E: evaluation_functor A2 B .. notation A1xA2.comp (infixr "\<cdot>\<^sub>A\<^sub>1\<^sub>x\<^sub>A\<^sub>2" 55) notation A2_B.comp (infixr "\<cdot>\<^sub>[\<^sub>A\<^sub>2,\<^sub>B\<^sub>]" 55) notation A2_BxA2.comp (infixr "\<cdot>\<^sub>[\<^sub>A\<^sub>2\<^sub>,\<^sub>B\<^sub>]\<^sub>x\<^sub>A\<^sub>2" 55) notation A1xA2.in_hom ("\<guillemotleft>_ : _ \<rightarrow>\<^sub>A\<^sub>1\<^sub>x\<^sub>A\<^sub>2 _\<guillemotright>") notation A2_B.in_hom ("\<guillemotleft>_ : _ \<rightarrow>\<^sub>[\<^sub>A\<^sub>2\<^sub>,\<^sub>B\<^sub>] _\<guillemotright>") notation A2_BxA2.in_hom ("\<guillemotleft>_ : _ \<rightarrow>\<^sub>[\<^sub>A\<^sub>2\<^sub>,\<^sub>B\<^sub>]\<^sub>x\<^sub>A\<^sub>2 _\<guillemotright>") text\<open> A proper definition for @{term curry} requires that it be parametrized by binary functors @{term F} and @{term G} that are the domain and codomain of the natural transformations to which it is being applied. Similar parameters are not needed in the case of @{term uncurry}. \<close> definition curry :: "('a1 \<times> 'a2 \<Rightarrow> 'b) \<Rightarrow> ('a1 \<times> 'a2 \<Rightarrow> 'b) \<Rightarrow> ('a1 \<times> 'a2 \<Rightarrow> 'b) \<Rightarrow> 'a1 \<Rightarrow> ('a2, 'b) A2_B.arr" where "curry F G \<tau> f1 = (if A1.arr f1 then A2_B.MkArr (\<lambda>f2. F (A1.dom f1, f2)) (\<lambda>f2. G (A1.cod f1, f2)) (\<lambda>f2. \<tau> (f1, f2)) else A2_B.null)" definition uncurry :: "('a1 \<Rightarrow> ('a2, 'b) A2_B.arr) \<Rightarrow> 'a1 \<times> 'a2 \<Rightarrow> 'b" where "uncurry \<tau> f \<equiv> if A1xA2.arr f then E.map (\<tau> (fst f), snd f) else B.null" lemma curry_simp: assumes "A1.arr f1" shows "curry F G \<tau> f1 = A2_B.MkArr (\<lambda>f2. F (A1.dom f1, f2)) (\<lambda>f2. G (A1.cod f1, f2)) (\<lambda>f2. \<tau> (f1, f2))" using assms curry_def by auto lemma uncurry_simp: assumes "A1xA2.arr f" shows "uncurry \<tau> f = E.map (\<tau> (fst f), snd f)" using assms uncurry_def by auto lemma curry_in_hom: assumes f1: "A1.arr f1" and "natural_transformation A1xA2.comp B F G \<tau>" shows "\<guillemotleft>curry F G \<tau> f1 : curry F F F (A1.dom f1) \<rightarrow>\<^sub>[\<^sub>A\<^sub>2\<^sub>,\<^sub>B\<^sub>] curry G G G (A1.cod f1)\<guillemotright>" proof - interpret \<tau>: natural_transformation A1xA2.comp B F G \<tau> using assms by auto show ?thesis proof - interpret F_dom_f1: "functor" A2 B \<open>\<lambda>f2. F (A1.dom f1, f2)\<close> using f1 \<tau>.F.is_extensional apply (unfold_locales, simp_all) by (metis A1xA2.comp_char A1.arr_dom_iff_arr A1.comp_arr_dom A1.dom_dom A1xA2.seqI \<tau>.F.preserves_comp_2 fst_conv snd_conv) interpret G_cod_f1: "functor" A2 B \<open>\<lambda>f2. G (A1.cod f1, f2)\<close> using f1 \<tau>.G.is_extensional A1.arr_cod_iff_arr apply (unfold_locales, simp_all) using A1xA2.comp_char A1.arr_cod_iff_arr A1.comp_cod_arr by (metis A1.cod_cod A1xA2.seqI \<tau>.G.preserves_comp_2 fst_conv snd_conv) have "natural_transformation A2 B (\<lambda>f2. F (A1.dom f1, f2)) (\<lambda>f2. G (A1.cod f1, f2)) (\<lambda>f2. \<tau> (f1, f2))" using f1 \<tau>.is_extensional apply (unfold_locales, simp_all) proof - fix f2 assume f2: "A2.arr f2" show "G (A1.cod f1, f2) \<cdot>\<^sub>B \<tau> (f1, A2.dom f2) = \<tau> (f1, f2)" using f1 f2 \<tau>.preserves_comp_1 [of "(A1.cod f1, f2)" "(f1, A2.dom f2)"] A1.comp_cod_arr A2.comp_arr_dom by simp show "\<tau> (f1, A2.cod f2) \<cdot>\<^sub>B F (A1.dom f1, f2) = \<tau> (f1, f2)" using f1 f2 \<tau>.preserves_comp_2 [of "(f1, A2.cod f2)" "(A1.dom f1, f2)"] A1.comp_arr_dom A2.comp_cod_arr by simp qed thus ?thesis using f1 curry_simp by auto qed qed lemma curry_preserves_functors: assumes "functor A1xA2.comp B F" shows "functor A1 A2_B.comp (curry F F F)" proof - interpret F: "functor" A1xA2.comp B F using assms by auto interpret F: binary_functor A1 A2 B F .. show ?thesis using curry_def F.fixing_arr_gives_natural_transformation_1 A2_B.comp_char F.preserves_comp_1 curry_simp A2_B.seq_char apply unfold_locales by auto qed lemma curry_preserves_transformations: assumes "natural_transformation A1xA2.comp B F G \<tau>" shows "natural_transformation A1 A2_B.comp (curry F F F) (curry G G G) (curry F G \<tau>)" proof - interpret \<tau>: natural_transformation A1xA2.comp B F G \<tau> using assms by auto interpret \<tau>: binary_functor_transformation A1 A2 B F G \<tau> .. interpret curry_F: "functor" A1 A2_B.comp \<open>curry F F F\<close> using curry_preserves_functors \<tau>.F.functor_axioms by simp interpret curry_G: "functor" A1 A2_B.comp \<open>curry G G G\<close> using curry_preserves_functors \<tau>.G.functor_axioms by simp show ?thesis proof show "\<And>f2. \<not> A1.arr f2 \<Longrightarrow> curry F G \<tau> f2 = A2_B.null" using curry_def by simp fix f1 assume f1: "A1.arr f1" show "A2_B.dom (curry F G \<tau> f1) = curry F F F (A1.dom f1)" using assms f1 curry_in_hom by blast show "A2_B.cod (curry F G \<tau> f1) = curry G G G (A1.cod f1)" using assms f1 curry_in_hom by blast show "curry G G G f1 \<cdot>\<^sub>[\<^sub>A\<^sub>2,\<^sub>B\<^sub>] curry F G \<tau> (A1.dom f1) = curry F G \<tau> f1" proof - interpret \<tau>_dom_f1: natural_transformation A2 B \<open>\<lambda>f2. F (A1.dom f1, f2)\<close> \<open>\<lambda>f2. G (A1.dom f1, f2)\<close> \<open>\<lambda>f2. \<tau> (A1.dom f1, f2)\<close> using assms f1 curry_in_hom A1.ide_dom \<tau>.fixing_ide_gives_natural_transformation_1 by blast interpret G_f1: natural_transformation A2 B \<open>\<lambda>f2. G (A1.dom f1, f2)\<close> \<open>\<lambda>f2. G (A1.cod f1, f2)\<close> \<open>\<lambda>f2. G (f1, f2)\<close> using f1 \<tau>.G.fixing_arr_gives_natural_transformation_1 by simp interpret G_f1o\<tau>_dom_f1: vertical_composite A2 B \<open>\<lambda>f2. F (A1.dom f1, f2)\<close> \<open>\<lambda>f2. G (A1.dom f1, f2)\<close> \<open>\<lambda>f2. G (A1.cod f1, f2)\<close> \<open>\<lambda>f2. \<tau> (A1.dom f1, f2)\<close> \<open>\<lambda>f2. G (f1, f2)\<close> .. have "curry G G G f1 \<cdot>\<^sub>[\<^sub>A\<^sub>2,\<^sub>B\<^sub>] curry F G \<tau> (A1.dom f1) = A2_B.MkArr (\<lambda>f2. F (A1.dom f1, f2)) (\<lambda>f2. G (A1.cod f1, f2)) G_f1o\<tau>_dom_f1.map" proof - have "A2_B.seq (curry G G G f1) (curry F G \<tau> (A1.dom f1))" using f1 curry_in_hom [of "A1.dom f1"] \<tau>.natural_transformation_axioms by force thus ?thesis using f1 curry_simp A2_B.comp_char [of "curry G G G f1" "curry F G \<tau> (A1.dom f1)"] by simp qed also have "... = A2_B.MkArr (\<lambda>f2. F (A1.dom f1, f2)) (\<lambda>f2. G (A1.cod f1, f2)) (\<lambda>f2. \<tau> (f1, f2))" proof (intro A2_B.MkArr_eqI) show "(\<lambda>f2. F (A1.dom f1, f2)) = (\<lambda>f2. F (A1.dom f1, f2))" by simp show "(\<lambda>f2. G (A1.cod f1, f2)) = (\<lambda>f2. G (A1.cod f1, f2))" by simp show "A2_B.arr (A2_B.MkArr (\<lambda>f2. F (A1.dom f1, f2)) (\<lambda>f2. G (A1.cod f1, f2)) G_f1o\<tau>_dom_f1.map)" using G_f1o\<tau>_dom_f1.natural_transformation_axioms by blast show "G_f1o\<tau>_dom_f1.map = (\<lambda>f2. \<tau> (f1, f2))" proof fix f2 have "\<not>A2.arr f2 \<Longrightarrow> G_f1o\<tau>_dom_f1.map f2 = (\<lambda>f2. \<tau> (f1, f2)) f2" using f1 G_f1o\<tau>_dom_f1.is_extensional \<tau>.is_extensional by simp moreover have "A2.arr f2 \<Longrightarrow> G_f1o\<tau>_dom_f1.map f2 = (\<lambda>f2. \<tau> (f1, f2)) f2" proof - interpret \<tau>_f1: natural_transformation A2 B \<open>\<lambda>f2. F (A1.dom f1, f2)\<close> \<open>\<lambda>f2. G (A1.cod f1, f2)\<close> \<open>\<lambda>f2. \<tau> (f1, f2)\<close> using assms f1 curry_in_hom [of f1] curry_simp by auto fix f2 assume f2: "A2.arr f2" show "G_f1o\<tau>_dom_f1.map f2 = (\<lambda>f2. \<tau> (f1, f2)) f2" using f1 f2 G_f1o\<tau>_dom_f1.map_simp_2 B.comp_assoc \<tau>.is_natural_1 by fastforce qed ultimately show "G_f1o\<tau>_dom_f1.map f2 = (\<lambda>f2. \<tau> (f1, f2)) f2" by blast qed qed also have "... = curry F G \<tau> f1" using f1 curry_def by simp finally show ?thesis by blast qed show "curry F G \<tau> (A1.cod f1) \<cdot>\<^sub>[\<^sub>A\<^sub>2,\<^sub>B\<^sub>] curry F F F f1 = curry F G \<tau> f1" proof - interpret \<tau>_cod_f1: natural_transformation A2 B \<open>\<lambda>f2. F (A1.cod f1, f2)\<close> \<open>\<lambda>f2. G (A1.cod f1, f2)\<close> \<open>\<lambda>f2. \<tau> (A1.cod f1, f2)\<close> using assms f1 curry_in_hom A1.ide_cod \<tau>.fixing_ide_gives_natural_transformation_1 by blast interpret F_f1: natural_transformation A2 B \<open>\<lambda>f2. F (A1.dom f1, f2)\<close> \<open>\<lambda>f2. F (A1.cod f1, f2)\<close> \<open>\<lambda>f2. F (f1, f2)\<close> using f1 \<tau>.F.fixing_arr_gives_natural_transformation_1 by simp interpret \<tau>_cod_f1oF_f1: vertical_composite A2 B \<open>\<lambda>f2. F (A1.dom f1, f2)\<close> \<open>\<lambda>f2. F (A1.cod f1, f2)\<close> \<open>\<lambda>f2. G (A1.cod f1, f2)\<close> \<open>\<lambda>f2. F (f1, f2)\<close> \<open>\<lambda>f2. \<tau> (A1.cod f1, f2)\<close> .. have "curry F G \<tau> (A1.cod f1) \<cdot>\<^sub>[\<^sub>A\<^sub>2,\<^sub>B\<^sub>] curry F F F f1 = A2_B.MkArr (\<lambda>f2. F (A1.dom f1, f2)) (\<lambda>f2. G (A1.cod f1, f2)) \<tau>_cod_f1oF_f1.map" proof - have "curry F F F f1 = A2_B.MkArr (\<lambda>f2. F (A1.dom f1, f2)) (\<lambda>f2. F (A1.cod f1, f2)) (\<lambda>f2. F (f1, f2)) \<and> \<guillemotleft>curry F F F f1 : curry F F F (A1.dom f1) \<rightarrow>\<^sub>[\<^sub>A\<^sub>2\<^sub>,\<^sub>B\<^sub>] curry F F F (A1.cod f1)\<guillemotright>" using f1 curry_F.preserves_hom curry_simp by blast moreover have "curry F G \<tau> (A1.dom f1) = A2_B.MkArr (\<lambda>f2. F (A1.dom f1, f2)) (\<lambda>f2. G (A1.dom f1, f2)) (\<lambda>f2. \<tau> (A1.dom f1, f2)) \<and> \<guillemotleft>curry F G \<tau> (A1.cod f1) : curry F F F (A1.cod f1) \<rightarrow>\<^sub>[\<^sub>A\<^sub>2\<^sub>,\<^sub>B\<^sub>] curry G G G (A1.cod f1)\<guillemotright>" using assms f1 curry_in_hom [of "A1.cod f1"] curry_def A1.arr_cod_iff_arr by simp ultimately show ?thesis using f1 curry_def by fastforce qed also have "... = A2_B.MkArr (\<lambda>f2. F (A1.dom f1, f2)) (\<lambda>f2. G (A1.cod f1, f2)) (\<lambda>f2. \<tau> (f1, f2))" proof (intro A2_B.MkArr_eqI) show "(\<lambda>f2. F (A1.dom f1, f2)) = (\<lambda>f2. F (A1.dom f1, f2))" by simp show "(\<lambda>f2. G (A1.cod f1, f2)) = (\<lambda>f2. G (A1.cod f1, f2))" by simp show "A2_B.arr (A2_B.MkArr (\<lambda>f2. F (A1.dom f1, f2)) (\<lambda>f2. G (A1.cod f1, f2)) \<tau>_cod_f1oF_f1.map)" using \<tau>_cod_f1oF_f1.natural_transformation_axioms by blast show "\<tau>_cod_f1oF_f1.map = (\<lambda>f2. \<tau> (f1, f2))" proof fix f2 have "\<not>A2.arr f2 \<Longrightarrow> \<tau>_cod_f1oF_f1.map f2 = (\<lambda>f2. \<tau> (f1, f2)) f2" using f1 by (simp add: \<tau>.is_extensional \<tau>_cod_f1oF_f1.is_extensional) moreover have "A2.arr f2 \<Longrightarrow> \<tau>_cod_f1oF_f1.map f2 = (\<lambda>f2. \<tau> (f1, f2)) f2" proof - interpret \<tau>_f1: natural_transformation A2 B \<open>\<lambda>f2. F (A1.dom f1, f2)\<close> \<open>\<lambda>f2. G (A1.cod f1, f2)\<close> \<open>\<lambda>f2. \<tau> (f1, f2)\<close> using assms f1 curry_in_hom [of f1] curry_simp by auto fix f2 assume f2: "A2.arr f2" show "\<tau>_cod_f1oF_f1.map f2 = (\<lambda>f2. \<tau> (f1, f2)) f2" using f1 f2 \<tau>_cod_f1oF_f1.map_simp_1 B.comp_assoc \<tau>.is_natural_2 by fastforce qed ultimately show "\<tau>_cod_f1oF_f1.map f2 = (\<lambda>f2. \<tau> (f1, f2)) f2" by blast qed qed also have "... = curry F G \<tau> f1" using f1 curry_def by simp finally show ?thesis by blast qed qed qed lemma uncurry_preserves_functors: assumes "functor A1 A2_B.comp F" shows "functor A1xA2.comp B (uncurry F)" proof - interpret F: "functor" A1 A2_B.comp F using assms by auto show ?thesis using uncurry_def apply (unfold_locales) apply auto[4] proof - fix f g :: "'a1 * 'a2" let ?f1 = "fst f" let ?f2 = "snd f" let ?g1 = "fst g" let ?g2 = "snd g" assume fg: "A1xA2.seq g f" have f: "A1xA2.arr f" using fg A1xA2.seqE by blast have f1: "A1.arr ?f1" using f by auto have f2: "A2.arr ?f2" using f by auto have g: "\<guillemotleft>g : A1xA2.cod f \<rightarrow>\<^sub>A\<^sub>1\<^sub>x\<^sub>A\<^sub>2 A1xA2.cod g\<guillemotright>" using fg A1xA2.dom_char A1xA2.cod_char by (elim A1xA2.seqE, intro A1xA2.in_homI, auto) let ?g1 = "fst g" let ?g2 = "snd g" have g1: "\<guillemotleft>?g1 : A1.cod ?f1 \<rightarrow>\<^sub>A\<^sub>1 A1.cod ?g1\<guillemotright>" using f g by (intro A1.in_homI, auto) have g2: "\<guillemotleft>?g2 : A2.cod ?f2 \<rightarrow>\<^sub>A\<^sub>2 A2.cod ?g2\<guillemotright>" using f g by (intro A2.in_homI, auto) interpret Ff1: natural_transformation A2 B \<open>A2_B.Dom (F ?f1)\<close> \<open>A2_B.Cod (F ?f1)\<close> \<open>A2_B.Map (F ?f1)\<close> using f A2_B.arr_char [of "F ?f1"] by auto interpret Fg1: natural_transformation A2 B \<open>A2_B.Cod (F ?f1)\<close> \<open>A2_B.Cod (F ?g1)\<close> \<open>A2_B.Map (F ?g1)\<close> using f1 g1 A2_B.arr_char F.preserves_arr A2_B.Map_dom [of "F ?g1"] A2_B.Map_cod [of "F ?f1"] by fastforce interpret Fg1oFf1: vertical_composite A2 B \<open>A2_B.Dom (F ?f1)\<close> \<open>A2_B.Cod (F ?f1)\<close> \<open>A2_B.Cod (F ?g1)\<close> \<open>A2_B.Map (F ?f1)\<close> \<open>A2_B.Map (F ?g1)\<close> .. show "uncurry F (g \<cdot>\<^sub>A\<^sub>1\<^sub>x\<^sub>A\<^sub>2 f) = uncurry F g \<cdot>\<^sub>B uncurry F f" using f1 g1 g2 g2 f g fg E.map_simp uncurry_def by auto qed qed lemma uncurry_preserves_transformations: assumes "natural_transformation A1 A2_B.comp F G \<tau>" shows "natural_transformation A1xA2.comp B (uncurry F) (uncurry G) (uncurry \<tau>)" proof - interpret \<tau>: natural_transformation A1 A2_B.comp F G \<tau> using assms by auto interpret "functor" A1xA2.comp B \<open>uncurry F\<close> using \<tau>.F.functor_axioms uncurry_preserves_functors by blast interpret "functor" A1xA2.comp B \<open>uncurry G\<close> using \<tau>.G.functor_axioms uncurry_preserves_functors by blast show ?thesis proof fix f show "\<not> A1xA2.arr f \<Longrightarrow> uncurry \<tau> f = B.null" using uncurry_def by auto assume f: "A1xA2.arr f" let ?f1 = "fst f" let ?f2 = "snd f" show "B.dom (uncurry \<tau> f) = uncurry F (A1xA2.dom f)" using f uncurry_def by simp show "B.cod (uncurry \<tau> f) = uncurry G (A1xA2.cod f)" using f uncurry_def by simp show "uncurry G f \<cdot>\<^sub>B uncurry \<tau> (A1xA2.dom f) = uncurry \<tau> f" using f uncurry_def \<tau>.is_natural_1 A2_BxA2.seq_char A2.comp_arr_dom E.preserves_comp [of "(G (fst f), snd f)" "(\<tau> (A1.dom (fst f)), A2.dom (snd f))"] by auto show "uncurry \<tau> (A1xA2.cod f) \<cdot>\<^sub>B uncurry F f = uncurry \<tau> f" proof - have 1: "A1.arr ?f1 \<and> A1.arr (fst (A1.cod ?f1, A2.cod ?f2)) \<and> A1.cod ?f1 = A1.dom (fst (A1.cod ?f1, A2.cod ?f2)) \<and> A2.seq (snd (A1.cod ?f1, A2.cod ?f2)) ?f2" using f A1.arr_cod_iff_arr A2.arr_cod_iff_arr by auto hence 2: "?f2 = A2 (snd (\<tau> (fst (A1xA2.cod f)), snd (A1xA2.cod f))) (snd (F ?f1, ?f2))" using f A2.comp_cod_arr by simp have "A2_B.arr (\<tau> ?f1)" using 1 by force thus ?thesis unfolding uncurry_def E.map_def using f 1 2 apply simp by (metis (no_types, lifting) A2_B.Map_comp \<open>A2_B.arr (\<tau> (fst f))\<close> \<tau>.is_natural_2) qed qed qed lemma uncurry_curry: assumes "natural_transformation A1xA2.comp B F G \<tau>" shows "uncurry (curry F G \<tau>) = \<tau>" proof interpret \<tau>: natural_transformation A1xA2.comp B F G \<tau> using assms by auto interpret curry_\<tau>: natural_transformation A1 A2_B.comp \<open>curry F F F\<close> \<open>curry G G G\<close> \<open>curry F G \<tau>\<close> using assms curry_preserves_transformations by auto fix f have "\<not>A1xA2.arr f \<Longrightarrow> uncurry (curry F G \<tau>) f = \<tau> f" using curry_def uncurry_def \<tau>.is_extensional by auto moreover have "A1xA2.arr f \<Longrightarrow> uncurry (curry F G \<tau>) f = \<tau> f" proof - assume f: "A1xA2.arr f" have 1: "A2_B.Map (curry F G \<tau> (fst f)) (snd f) = \<tau> (fst f, snd f)" using f A1xA2.arr_char curry_def by simp thus "uncurry (curry F G \<tau>) f = \<tau> f" unfolding uncurry_def E.map_def using f 1 A1xA2.arr_char [of f] by simp qed ultimately show "uncurry (curry F G \<tau>) f = \<tau> f" by blast qed lemma curry_uncurry: assumes "functor A1 A2_B.comp F" and "functor A1 A2_B.comp G" and "natural_transformation A1 A2_B.comp F G \<tau>" shows "curry (uncurry F) (uncurry G) (uncurry \<tau>) = \<tau>" proof interpret F: "functor" A1 A2_B.comp F using assms(1) by auto interpret G: "functor" A1 A2_B.comp G using assms(2) by auto interpret \<tau>: natural_transformation A1 A2_B.comp F G \<tau> using assms(3) by auto interpret uncurry_F: "functor" A1xA2.comp B \<open>uncurry F\<close> using F.functor_axioms uncurry_preserves_functors by auto interpret uncurry_G: "functor" A1xA2.comp B \<open>uncurry G\<close> using G.functor_axioms uncurry_preserves_functors by auto fix f1 have "\<not>A1.arr f1 \<Longrightarrow> curry (uncurry F) (uncurry G) (uncurry \<tau>) f1 = \<tau> f1" using curry_def uncurry_def \<tau>.is_extensional by simp moreover have "A1.arr f1 \<Longrightarrow> curry (uncurry F) (uncurry G) (uncurry \<tau>) f1 = \<tau> f1" proof - assume f1: "A1.arr f1" interpret uncurry_\<tau>: natural_transformation A1xA2.comp B \<open>uncurry F\<close> \<open>uncurry G\<close> \<open>uncurry \<tau>\<close> using \<tau>.natural_transformation_axioms uncurry_preserves_transformations [of F G \<tau>] by simp have "curry (uncurry F) (uncurry G) (uncurry \<tau>) f1 = A2_B.MkArr (\<lambda>f2. uncurry F (A1.dom f1, f2)) (\<lambda>f2. uncurry G (A1.cod f1, f2)) (\<lambda>f2. uncurry \<tau> (f1, f2))" using f1 curry_def by simp also have "... = A2_B.MkArr (\<lambda>f2. uncurry F (A1.dom f1, f2)) (\<lambda>f2. uncurry G (A1.cod f1, f2)) (\<lambda>f2. E.map (\<tau> f1, f2))" proof - have "(\<lambda>f2. uncurry \<tau> (f1, f2)) = (\<lambda>f2. E.map (\<tau> f1, f2))" using f1 uncurry_def E.is_extensional by auto thus ?thesis by simp qed also have "... = \<tau> f1" proof - have "A2_B.Dom (\<tau> f1) = (\<lambda>f2. uncurry F (A1.dom f1, f2))" proof - have "A2_B.Dom (\<tau> f1) = A2_B.Map (A2_B.dom (\<tau> f1))" using f1 A2_B.ide_char A2_B.Map_dom A2_B.dom_char by auto also have "... = A2_B.Map (F (A1.dom f1))" using f1 by simp also have "... = (\<lambda>f2. uncurry F (A1.dom f1, f2))" proof fix f2 interpret F_dom_f1: "functor" A2 B \<open>A2_B.Map (F (A1.dom f1))\<close> using f1 A2_B.ide_char F.preserves_ide by simp show "A2_B.Map (F (A1.dom f1)) f2 = uncurry F (A1.dom f1, f2)" using f1 uncurry_def E.map_simp F_dom_f1.is_extensional by auto qed finally show ?thesis by auto qed moreover have "A2_B.Cod (\<tau> f1) = (\<lambda>f2. uncurry G (A1.cod f1, f2))" proof - have "A2_B.Cod (\<tau> f1) = A2_B.Map (A2_B.cod (\<tau> f1))" using f1 A2_B.ide_char A2_B.Map_cod A2_B.cod_char by auto also have "... = A2_B.Map (G (A1.cod f1))" using f1 by simp also have "... = (\<lambda>f2. uncurry G (A1.cod f1, f2))" proof fix f2 interpret G_cod_f1: "functor" A2 B \<open>A2_B.Map (G (A1.cod f1))\<close> using f1 A2_B.ide_char G.preserves_ide by simp show "A2_B.Map (G (A1.cod f1)) f2 = uncurry G (A1.cod f1, f2)" using f1 uncurry_def E.map_simp G_cod_f1.is_extensional by auto qed finally show ?thesis by auto qed moreover have "A2_B.Map (\<tau> f1) = (\<lambda>f2. E.map (\<tau> f1, f2))" proof fix f2 have "\<not>A2.arr f2 \<Longrightarrow> A2_B.Map (\<tau> f1) f2 = (\<lambda>f2. E.map (\<tau> f1, f2)) f2" using f1 A2_B.arrE \<tau>.preserves_reflects_arr natural_transformation.is_extensional by (metis (no_types, lifting) E.fixing_arr_gives_natural_transformation_1) moreover have "A2.arr f2 \<Longrightarrow> A2_B.Map (\<tau> f1) f2 = (\<lambda>f2. E.map (\<tau> f1, f2)) f2" using f1 E.map_simp by fastforce ultimately show "A2_B.Map (\<tau> f1) f2 = (\<lambda>f2. E.map (\<tau> f1, f2)) f2" by blast qed ultimately show ?thesis using f1 A2_B.MkArr_Map \<tau>.preserves_reflects_arr by metis qed finally show ?thesis by auto qed ultimately show "curry (uncurry F) (uncurry G) (uncurry \<tau>) f1 = \<tau> f1" by blast qed end locale curried_functor = currying A1 A2 B + A1xA2: product_category A1 A2 + A2_B: functor_category A2 B + F: binary_functor A1 A2 B F for A1 :: "'a1 comp" (infixr "\<cdot>\<^sub>A\<^sub>1" 55) and A2 :: "'a2 comp" (infixr "\<cdot>\<^sub>A\<^sub>2" 55) and B :: "'b comp" (infixr "\<cdot>\<^sub>B" 55) and F :: "'a1 * 'a2 \<Rightarrow> 'b" begin notation A1xA2.comp (infixr "\<cdot>\<^sub>A\<^sub>1\<^sub>x\<^sub>A\<^sub>2" 55) notation A2_B.comp (infixr "\<cdot>\<^sub>[\<^sub>A\<^sub>2,\<^sub>B\<^sub>]" 55) notation A1xA2.in_hom ("\<guillemotleft>_ : _ \<rightarrow>\<^sub>A\<^sub>1\<^sub>x\<^sub>A\<^sub>2 _\<guillemotright>") notation A2_B.in_hom ("\<guillemotleft>_ : _ \<rightarrow>\<^sub>[\<^sub>A\<^sub>2\<^sub>,\<^sub>B\<^sub>] _\<guillemotright>") definition map where "map \<equiv> curry F F F" lemma map_simp [simp]: assumes "A1.arr f1" shows "map f1 = A2_B.MkArr (\<lambda>f2. F (A1.dom f1, f2)) (\<lambda>f2. F (A1.cod f1, f2)) (\<lambda>f2. F (f1, f2))" using assms map_def curry_simp by auto lemma is_functor: shows "functor A1 A2_B.comp map" using F.functor_axioms map_def curry_preserves_functors by simp end sublocale curried_functor \<subseteq> "functor" A1 A2_B.comp map using is_functor by auto locale curried_functor' = A1: category A1 + A2: category A2 + A1xA2: product_category A1 A2 + currying A2 A1 B + F: binary_functor A1 A2 B F + A1_B: functor_category A1 B for A1 :: "'a1 comp" (infixr "\<cdot>\<^sub>A\<^sub>1" 55) and A2 :: "'a2 comp" (infixr "\<cdot>\<^sub>A\<^sub>2" 55) and B :: "'b comp" (infixr "\<cdot>\<^sub>B" 55) and F :: "'a1 * 'a2 \<Rightarrow> 'b" begin notation A1xA2.comp (infixr "\<cdot>\<^sub>A\<^sub>1\<^sub>x\<^sub>A\<^sub>2" 55) notation A1_B.comp (infixr "\<cdot>\<^sub>[\<^sub>A\<^sub>1,\<^sub>B\<^sub>]" 55) notation A1xA2.in_hom ("\<guillemotleft>_ : _ \<rightarrow>\<^sub>A\<^sub>1\<^sub>x\<^sub>A\<^sub>2 _\<guillemotright>") notation A1_B.in_hom ("\<guillemotleft>_ : _ \<rightarrow>\<^sub>[\<^sub>A\<^sub>1\<^sub>,\<^sub>B\<^sub>] _\<guillemotright>") definition map where "map \<equiv> curry F.sym F.sym F.sym" lemma map_simp [simp]: assumes "A2.arr f2" shows "map f2 = A1_B.MkArr (\<lambda>f1. F (f1, A2.dom f2)) (\<lambda>f1. F (f1, A2.cod f2)) (\<lambda>f1. F (f1, f2))" using assms map_def curry_simp by simp lemma is_functor: shows "functor A2 A1_B.comp map" proof - interpret A2xA1: product_category A2 A1 .. interpret F': binary_functor A2 A1 B F.sym using F.sym_is_binary_functor by simp have "functor A2xA1.comp B F.sym" .. thus ?thesis using map_def curry_preserves_functors by simp qed end sublocale curried_functor' \<subseteq> "functor" A2 A1_B.comp map using is_functor by auto end
import data.real.basic def converges_to (s : ℕ → ℝ) (a : ℝ) := ∀ ε > 0, ∃ N, ∀ n ≥ N, abs (s n - a) < ε -- BEGIN variables {s t : ℕ → ℝ} {a b : ℝ} #check sub_sub (a + b) theorem converges_to_add (cs : converges_to s a) (ct : converges_to t b): converges_to (λ n, s n + t n) (a + b) := begin intros ε εpos, dsimp, have ε2pos : 0 < ε / 2, { linarith }, cases cs (ε / 2) ε2pos with Ns hs, cases ct (ε / 2) ε2pos with Nt ht, use max Ns Nt, intros n hn, specialize hs n (le_trans (le_max_left Ns Nt) hn), specialize ht n (le_trans (le_max_right Ns Nt) hn), rw (by ring : s n + t n - (a + b) = (s n - a) + (t n - b)), rw ← add_halves ε, have triangle := abs_add (s n - a) (t n - b), have lt_two_half_ε := add_lt_add hs ht, exact lt_of_le_of_lt triangle lt_two_half_ε, end -- END
# Step 2 of 3: computer algebra improve := proc(lo :: LO(name, anything), {_ctx :: t_kb := empty}, opts := [], $) local r, `&context`; userinfo(5, improve, "input: ", print(lo &context _ctx)); _Env_HakaruSolve := true; r:= LO(op(1,lo), reduce(op(2,lo), op(1,lo), _ctx, opts)); userinfo(5, improve, "output: ", print(r)); r end proc; # Walk through integrals and simplify, recursing through grammar # h - name of the linear operator above us # kb - domain information reduce := proc(ee, h :: name, kb :: t_kb, opts := [], $) local e, elim, subintegral, w, ww, x, c, kb1, with_kb1, dom_specw, dom_specb , body, dom_spec, ed, mkDom, vars, rr , do_domain := evalb( not ( "no_domain" in {op(opts)} ) ) ; e := ee; if do_domain then rr := reduce_Integrals(e, h, kb, opts); if rr <> FAIL then return rr end if; end if; if e :: 'applyintegrand(anything, anything)' then map(simplify_assuming, e, kb) elif e :: `+` then map(reduce, e, h, kb, opts) elif e :: `*` then (subintegral, w) := selectremove(depends, e, h); if subintegral :: `*` then error "Nonlinear integral %1", e end if; subintegral := convert(reduce(subintegral, h, kb, opts), 'list', `*`); (subintegral, ww) := selectremove(depends, subintegral, h); simplify_factor_assuming(`*`(w, op(ww)), kb) * `*`(op(subintegral)); elif e :: Or(Partition,t_pw) then if e :: t_pw then e := PWToPartition(e); end if; e := Partition:-Simpl(e); e := kb_Partition(e, kb, simplify_assuming, ((rhs, kb) -> %reduce(rhs, h, kb, opts))); e := eval(e, %reduce=reduce); # big hammer: simplify knows about bound variables, amongst many # other things Testzero := x -> evalb(simplify(x) = 0); e := Partition:-Simpl(e); if ee::t_pw and e :: Partition then e := Partition:-PartitionToPW(e); end if; e; elif e :: t_case then subsop(2=map(proc(b :: Branch(anything, anything)) eval(subsop(2='reduce'(op(2,b),x,c,opts),b), {x=h, c=kb}) end proc, op(2,e)), e); elif e :: 'Context(anything, anything)' then kb1 := assert(op(1,e), kb); # A contradictory `Context' implies anything, so produce 'anything' # In particular, 42 :: t_Hakaru = false, so a term under a false # assumption should never be inspected in any way. if kb1 :: t_not_a_kb then return 42 end if; applyop(reduce, 2, e, h, kb1, opts); elif e :: 'toLO:-integrate(anything, Integrand(name, anything), list)' then x := gensym(op([2,1],e)); # If we had HType information for op(1,e), # then we could use it to tell kb about x. subsop(2=Integrand(x, reduce(subs(op([2,1],e)=x, op([2,2],e)), h, kb, opts)), e) else simplify_assuming(e, kb) end if; end proc; # "Integrals" refers to any types of "integrals" understood by domain (Int, # Sum currently) reduce_Integrals := module() export ModuleApply; local # The callbacks passed by reduce_Integrals to Domain:-Reduce reduce_Integrals_body, reduce_Integrals_into # tries to evaluate a RootOf , try_eval_Root # tries to evaluate Int/Sum/Ints/Sums , elim_intsum; reduce_Integrals_body := proc(h,opts,x,kb1) reduce(x,h,kb1,opts) end proc; reduce_Integrals_into := proc(h,opts,kind,e,vn,vt,kb,$) local rr; rr := elim_intsum(Domain:-Apply:-do_mk(args[3..-1]), h, kb,opts); rr := subsindets(rr, specfunc(RootOf), x->try_eval_Root(x,a->a)); return rr; end proc; ModuleApply := proc(expr, h, kb, opts, $) local rr; rr := Domain:-Reduce(expr, kb ,curry(reduce_Integrals_into,h,opts) ,curry(reduce_Integrals_body,h,opts) ,(_->:-DOM_FAIL)); rr := kb_assuming_mb(Partition:-Simpl)(rr, kb, x->x); if has(rr, :-DOM_FAIL) then return FAIL; elif has(rr, FAIL) then error "Something strange happened in reduce_Integral(%a, %a, %a, %a)\n%a" , expr, kb, kb, opts, rr; end if; rr; end proc; try_eval_Root := proc(e0::specfunc(`RootOf`),on_fail := (_->FAIL), $) local ix,e := e0; try if nops(e)=2 or nops(e)=3 and op(-1,e) :: `=`(identical(index),{specindex(real),nonnegint}) then ix := op([2,-1],e); if ix :: specindex(real) then ix := op(ix); end if; e := op(0,e)(op(1,e)); else ix := NULL; end if; e := convert(e, 'radical', ix); if e :: specfunc(RootOf) then return on_fail(e) end if; return e; catch: return on_fail(e0); end try; end proc; # Try to find an eliminate (by evaluation, or simplification) integrals which # are free of `applyintegrand`s. elim_intsum := module () export ModuleApply := proc(inert0, h :: name, kb :: t_kb, opts, $) local ex, e, inert := inert0; ex := extract_elim(inert, h, kb); e[0] := apply_elim(h, kb, ex); e[1] := check_elim(inert, e[0]); if e[1] = FAIL then inert else e[2] := reduce(e[1],h,kb,opts); if has(e[2], {csgn}) then WARNING("Throwing away an eliminated result result containing csgn (this " "could be a bug!):\n%1\n(while running %2)", e[2], ex); inert; else e[2] end if; end if end proc; local known_tys := table([Int=int_assuming,Sum=sum_assuming,Ints=ints,Sums=sums]); local extract_elim := proc(e, h::name, kb::t_kb,$) local t, intapps, var, f, e_k, e_args, vs, blo, bhi; vs := {op(KB:-kb_to_variables(kb))}; t := 'applyintegrand'('identical'(h), 'anything'); intapps := indets(op(1,e), t); if intapps = {} then return FAIL; end if; e_k := op(0,e); e_args := op([2..-1],e); if Domain:-Has:-Bound(e) and assigned(known_tys[e_k]) then var := Domain:-ExtBound[e_k]:-ExtractVar(e_args); ASSERT(var::DomBoundVar); blo, bhi := Domain:-ExtBound[e_k]:-SplitRange (Domain:-ExtBound[e_k]:-ExtractRange(e_args)); if ormap(b->op(1,b) in map((q-> (q,-q)), vs) and op(2,b)::SymbolicInfinity ,[[blo,bhi],[bhi,blo]]) then return FAIL end if; if var :: list then var := op(1,var) end if; if not depends(intapps, var) then f := known_tys[e_k]; else return FAIL; end if; end if; [ op(1,e), f, var, [e_args] ]; end proc; local apply_elim := proc(h::name,kb::t_kb,todo::{list,identical(FAIL)}) local body, f, var, rrest; if todo = FAIL then return FAIL; end if; body, f, var, rrest := op(todo); banish(body, h, kb, infinity, var, proc (kb1,g,$) do_elim_intsum(kb1, f, g, op(rrest)) end proc); end proc; local check_elim := proc(e, elim,$) if has(elim, {MeijerG, undefined, FAIL}) or e = elim or elim :: SymbolicInfinity then return FAIL; end if; return elim; end proc; local do_elim_intsum := proc(kb, f, ee, v::{name,name=anything}) local w, e, x, g, t, r; w, e := op(Domain:-Extract:-Shape(ee)); w := Domain:-Shape:-toConstraints(w); e := piecewise_And(w, e, 0); e := f(e,v,_rest,kb); x := `if`(v::name, v, lhs(v)); g := '{sum, sum_assuming, sums}'; if f in g then t := {'identical'(x), 'identical'(x) = 'Not(range(Not({SymbolicInfinity, undefined})))'}; else g := '{int, int_assuming, ints}'; t := {'identical'(x), 'identical'(x) = 'anything'}; if not f in g then g := {f} end if; end if; for r in indets(e, 'specfunc'(g)) do if 1<nops(r) and op(2,r)::t then return FAIL end if end do; e end proc; end module; # elim end module; # reduce_Integrals int_assuming := proc(e, v::name=anything, kb::t_kb, $) simplify_factor_assuming('int'(e, v), kb); end proc; sum_assuming := proc(e, v::name=anything, kb::t_kb) simplify_factor_assuming('sum'(e, v), kb); end proc; # Int( .., var=var_ty ) == var &X var_ty isBound_IntSum := kind -> module() option record; export MakeKB := (`if`(kind=Sum,KB:-genSummation,KB:-genLebesgue)); export ExtractVar := (e->op(1,e)); export ExtractRange := (e->op(2,e)); export MakeRange := `..`; export SplitRange := (e->op(e)); export Constrain := `if`(kind=Sum,`<=`,`<`); export DoMk := ((e,v,t)->kind(e,v=t)); export Min := `min`; export Max := `max`; export VarType := 'name'; export RangeType := 'range'; export MapleType := 'And'('specfunc'(kind), 'anyfunc(anything,name=range)'); export BoundType := `if`(kind=Sum,'integer','real'); export RecogBound := `if`(kind=Sum, (proc(k,b) if k = `<=` then (x->subsop(2=b,x)) elif k = `>=` then (x->subsop(1=b,x)) elif k = `<` then (x->subsop(2=(b-1),x)) elif k = `>` then (x->subsop(1=b+1,x)) end if; end proc), (proc(k,b) if k in {`<=`,`<`} then (x->subsop(2=b,x)) elif k in {`>=`,`>`} then (x->subsop(1=b,x)) end if; end proc)); end module; # Ints( .., var::name, var_ty::range, dims::list(name=range) ) == # [ var , map(lhs,dims) ] :: list(name) &X # [ var_ty, map(rhs,dims) ] :: list(range) isBound_IntsSums := kind -> module() option record; export MakeKB := proc(vars, lo, hi, kb, $) local var, dims, ty, rngs, x, kb1; var := op(1, vars); rngs := zip(`..`,lo,hi); ty := op(1, rngs); dims := subsop(1=NULL,zip(`=`,vars,rngs)); x, kb1 := genType(var, mk_HArray(`if`(kind=Ints, HReal(open_bounds(ty)), HInt(closed_bounds(ty))), dims),kb); if nops(dims) > 0 then kb1 := assert(size(x)=op([-1,2,2],dims)-op([-1,2,1],dims)+1, kb1); end if; x, kb1; end proc; export ExtractVar := ((v,t,d)->[v,map(lhs,d)[]]); export ExtractRange := ((v,t,d)->[t,map(rhs,d)[]]); export MakeRange := ((a,b)->zip(`..`,a,b)); export SplitRange := (rs->(map(x->op(1,x),rs), map(x->op(2,x),rs))); export Constrain := ((a,b)->zip(`if`(kind=Ints, `<`, `<=`),a,b)[]); export DoMk := ((e,v,t)->kind( e,op(1,v),op(1,t), subsop(1=NULL,zip(`=`,v,t)) )); export Min := ((a,b)->zip(`min`,a,b)); export Max := ((a,b)->zip(`max`,a,b)); export VarType := 'And(list(name),satisfies(x->x<>[]))'; export RangeType := 'And(list(range),satisfies(x->x<>[]))'; export MapleType := 'And'('specfunc'(kind),'anyfunc'('anything', 'name', 'range', 'list(name=range)')); export BoundType := TopProp; export RecogBound := (_->NULL); end module;
[STATEMENT] lemma lit_pbm_subst [usubst]: fixes x :: "(_ \<Longrightarrow> '\<alpha>)" shows "\<And> P Q M \<sigma>. \<sigma>($x \<mapsto>\<^sub>s \<guillemotleft>v\<guillemotright>) \<dagger> (P \<parallel>\<^bsub>M\<^esub> Q) = \<sigma> \<dagger> ((P\<lbrakk>\<guillemotleft>v\<guillemotright>/$x\<rbrakk>) \<parallel>\<^bsub>M\<lbrakk>\<guillemotleft>v\<guillemotright>/$x\<^sub><\<rbrakk>\<^esub> (Q\<lbrakk>\<guillemotleft>v\<guillemotright>/$x\<rbrakk>))" "\<And> P Q M \<sigma>. \<sigma>($x\<acute> \<mapsto>\<^sub>s \<guillemotleft>v\<guillemotright>) \<dagger> (P \<parallel>\<^bsub>M\<^esub> Q) = \<sigma> \<dagger> (P \<parallel>\<^bsub>M\<lbrakk>\<guillemotleft>v\<guillemotright>/$x\<acute>\<rbrakk>\<^esub> Q)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<And>P Q M \<sigma>. \<sigma>($x \<mapsto>\<^sub>s \<guillemotleft>v\<guillemotright>) \<dagger> P \<parallel>\<^bsub>M\<^esub> Q = \<sigma> \<dagger> P\<lbrakk>\<guillemotleft>v\<guillemotright>/$x\<rbrakk> \<parallel>\<^bsub>M\<lbrakk>\<guillemotleft>v\<guillemotright>/$x\<^sub><\<rbrakk>\<^esub> Q\<lbrakk>\<guillemotleft>v\<guillemotright>/$x\<rbrakk>) &&& (\<And>P Q M \<sigma>. \<sigma>($x\<acute> \<mapsto>\<^sub>s \<guillemotleft>v\<guillemotright>) \<dagger> P \<parallel>\<^bsub>M\<^esub> Q = \<sigma> \<dagger> P \<parallel>\<^bsub>M\<lbrakk>\<guillemotleft>v\<guillemotright>/$x\<acute>\<rbrakk>\<^esub> Q) [PROOF STEP] by (rel_auto)+
theory Proof_3_3 imports HandDryer VCTheoryLemmas Extra begin theorem proof_3_3: "VC3 inv3 s0 hands_value" apply(simp only: VC3_def inv3_def R3_def dryer_def) apply(rule impI) apply(rule conjI) apply(rule conjI) apply(simp) proof - define s:: state where "s = (toEnv (setVarBool (setVarAny s0 hands_value) (Suc (Suc 0)) OFF))" assume VC: " ((toEnvP s0 \<and> (\<forall>s1 s2. substate s1 s2 \<and> substate s2 s0 \<and> toEnvP s1 \<and> toEnvP s2 \<and> toEnvNum s1 s2 = hands \<and> 10 \<le> toEnvNum s2 s0 \<and> getVarBool s1 hands = ON \<and> getVarBool s1 (Suc (Suc 0)) = ON \<and> getVarBool s2 hands = OFF \<longrightarrow> (\<exists>s4. toEnvP s4 \<and> substate s2 s4 \<and> substate s4 s0 \<and> toEnvNum s2 s4 \<le> 10 \<and> (getVarBool s4 (Suc (Suc 0)) = OFF \<or> getVarBool s4 hands = ON) \<and> (\<forall>s3. toEnvP s3 \<and> substate s2 s3 \<and> substate s3 s4 \<and> s3 \<noteq> s4 \<longrightarrow> getVarBool s3 (Suc (Suc 0)) = ON \<and> getVarBool s3 hands = OFF)))) \<and> extraInv s0) \<and> env (setVarAny s0 hands_value) hands_value \<and> getPstate (setVarAny s0 hands_value) Ctrl = waiting \<and> getVarBool (setVarAny s0 hands_value) hands \<noteq> ON" show " \<forall>s1 s2. substate s1 s2 \<and> substate s2 (toEnv (setVarBool (setVarAny s0 hands_value) (Suc (Suc 0)) OFF)) \<and> toEnvP s1 \<and> toEnvP s2 \<and> toEnvNum s1 s2 = hands \<and> 10 \<le> toEnvNum s2 (toEnv (setVarBool (setVarAny s0 hands_value) (Suc (Suc 0)) OFF)) \<and> getVarBool s1 hands = ON \<and> getVarBool s1 (Suc (Suc 0)) = ON \<and> getVarBool s2 hands = OFF \<longrightarrow> (\<exists>s4. toEnvP s4 \<and> substate s2 s4 \<and> substate s4 (toEnv (setVarBool (setVarAny s0 hands_value) (Suc (Suc 0)) OFF)) \<and> toEnvNum s2 s4 \<le> 10 \<and> (getVarBool s4 (Suc (Suc 0)) = OFF \<or> getVarBool s4 hands = ON) \<and> (\<forall>s3. toEnvP s3 \<and> substate s2 s3 \<and> substate s3 s4 \<and> s3 \<noteq> s4 \<longrightarrow> getVarBool s3 (Suc (Suc 0)) = ON \<and> getVarBool s3 hands = OFF)) " apply(simp only: s_def[symmetric]) proof(rule allI; rule allI; rule impI) fix s1 s2 print_state assume req_prems: "substate s1 s2 \<and> substate s2 s \<and> toEnvP s1 \<and> toEnvP s2 \<and> toEnvNum s1 s2 = hands \<and> 10 \<le> toEnvNum s2 s \<and> getVarBool s1 hands = ON \<and> getVarBool s1 (Suc (Suc 0)) = ON \<and> getVarBool s2 hands = OFF" then obtain "10 \<le> toEnvNum s2 s" by auto from le_imp_less_or_eq[OF this] show " \<exists>s4. toEnvP s4 \<and> substate s2 s4 \<and> substate s4 s \<and> toEnvNum s2 s4 \<le> 10 \<and> (getVarBool s4 (Suc (Suc 0)) = OFF \<or> getVarBool s4 hands = ON) \<and> (\<forall>s3. toEnvP s3 \<and> substate s2 s3 \<and> substate s3 s4 \<and> s3 \<noteq> s4 \<longrightarrow> getVarBool s3 (Suc (Suc 0)) = ON \<and> getVarBool s3 hands = OFF)" proof assume 1: "10 < toEnvNum s2 s" with req_prems substate_eq_or_predEnv toEnvNum_id s_def have 2: "substate s2 s0" by (simp add: s_def split: if_splits) from VC obtain "\<forall>s1 s2. substate s1 s2 \<and> substate s2 s0 \<and> toEnvP s1 \<and> toEnvP s2 \<and> toEnvNum s1 s2 = hands \<and> 10 \<le> toEnvNum s2 s0 \<and> getVarBool s1 hands = ON \<and> getVarBool s1 (Suc (Suc 0)) = ON \<and> getVarBool s2 hands = OFF \<longrightarrow> (\<exists>s4. toEnvP s4 \<and> substate s2 s4 \<and> substate s4 s0 \<and> toEnvNum s2 s4 \<le> 10 \<and> (getVarBool s4 (Suc (Suc 0)) = OFF \<or> getVarBool s4 hands = ON) \<and> (\<forall>s3. toEnvP s3 \<and> substate s2 s3 \<and> substate s3 s4 \<and> s3 \<noteq> s4 \<longrightarrow> getVarBool s3 (Suc (Suc 0)) = ON \<and> getVarBool s3 hands = OFF))" by auto with req_prems 1 2 have "\<exists>s4. toEnvP s4 \<and> substate s2 s4 \<and> substate s4 s0 \<and> toEnvNum s2 s4 \<le> 10 \<and> (getVarBool s4 (Suc (Suc 0)) = OFF \<or> getVarBool s4 hands = ON) \<and> (\<forall>s3. toEnvP s3 \<and> substate s2 s3 \<and> substate s3 s4 \<and> s3 \<noteq> s4 \<longrightarrow> getVarBool s3 (Suc (Suc 0)) = ON \<and> getVarBool s3 hands = OFF)" by (auto simp add: s_def split: if_splits) then obtain s4 where 3: " toEnvP s4 \<and> substate s2 s4 \<and> substate s4 s0 \<and> toEnvNum s2 s4 \<le> 10 \<and> (getVarBool s4 (Suc (Suc 0)) = OFF \<or> getVarBool s4 hands = ON) \<and> (\<forall>s3. toEnvP s3 \<and> substate s2 s3 \<and> substate s3 s4 \<and> s3 \<noteq> s4 \<longrightarrow> getVarBool s3 (Suc (Suc 0)) = ON \<and> getVarBool s3 hands = OFF)" .. have "(toEnvP s4 \<and> substate s2 s4 \<and> substate s4 s \<and> toEnvNum s2 s4 \<le> 10 \<and> (getVarBool s4 (Suc (Suc 0)) = OFF \<or> getVarBool s4 hands = ON)) \<and> (\<forall>s3. toEnvP s3 \<and> substate s2 s3 \<and> substate s3 s4 \<and> s3 \<noteq> s4 \<longrightarrow> getVarBool s3 (Suc (Suc 0)) = ON \<and> getVarBool s3 hands = OFF)" proof from 3 show "toEnvP s4 \<and> substate s2 s4 \<and> substate s4 s \<and> toEnvNum s2 s4 \<le> 10 \<and> (getVarBool s4 (Suc (Suc 0)) = OFF \<or> getVarBool s4 hands = ON)" by (simp add: s_def) next from 3 show "\<forall>s3. toEnvP s3 \<and> substate s2 s3 \<and> substate s3 s4 \<and> s3 \<noteq> s4 \<longrightarrow> getVarBool s3 (Suc (Suc 0)) = ON \<and> getVarBool s3 hands = OFF" by simp qed thus ?thesis by auto next assume 4: "10 = toEnvNum s2 s" from substate_asym have 5: "\<forall>s3. toEnvP s3 \<and> substate s2 s3 \<and> substate s3 s2 \<and> s3 \<noteq> s2 \<longrightarrow> getVarBool s3 (Suc (Suc 0)) = ON \<and> getVarBool s3 hands = OFF" by auto show ?thesis proof - define s5:: state where "s5=s2" have "toEnvP s5 \<and> substate s2 s5 \<and> substate s5 s \<longrightarrow>pred3 s2 s s5" proof(induction rule: state_down_ind) case 1 then show ?case using req_prems s_def by auto next case 2 then show ?case apply(simp only: pred3_def) proof assume 6: " \<forall>s3. toEnvP s3 \<and> substate s2 s3 \<and> substate s3 s \<and> s3 \<noteq> s \<longrightarrow> getVarBool s3 (Suc (Suc 0)) = ON \<and> getVarBool s3 hands = OFF" have " (toEnvP s \<and> substate s s \<and> substate s s \<and> toEnvNum s2 s \<le> 10) \<and> (getVarBool s (Suc (Suc 0)) = OFF \<or> getVarBool s hands = ON) \<and> (\<forall>s3. toEnvP s3 \<and> substate s s3 \<and> substate s3 s \<and> s3 \<noteq> s \<longrightarrow> getVarBool s3 (Suc (Suc 0)) = ON \<and> getVarBool s3 hands = OFF)" proof from 4 substate_refl s_def req_prems show "(toEnvP s \<and> substate s s \<and> substate s s \<and> toEnvNum s2 s \<le> 10 )" by auto next from VC have " (getVarBool s (Suc (Suc 0)) = OFF \<or> getVarBool s hands = ON)" by (simp add: s_def) moreover from substate_asym have "\<forall>s3. toEnvP s3 \<and> substate s s3 \<and> substate s3 s \<and> s3 \<noteq> s \<longrightarrow> getVarBool s3 (Suc (Suc 0)) = ON \<and> getVarBool s3 hands = OFF" by auto ultimately show "(getVarBool s (Suc (Suc 0)) = OFF \<or> getVarBool s hands = ON) \<and> (\<forall>s3. toEnvP s3 \<and> substate s s3 \<and> substate s3 s \<and> s3 \<noteq> s \<longrightarrow> getVarBool s3 (Suc (Suc 0)) = ON \<and> getVarBool s3 hands = OFF)" .. qed thus "\<exists>s4. toEnvP s4 \<and> substate s s4 \<and> substate s4 s \<and> toEnvNum s2 s4 \<le> 10 \<and> (getVarBool s4 (Suc (Suc 0)) = OFF \<or> getVarBool s4 hands = ON) \<and> (\<forall>s3. toEnvP s3 \<and> substate s s3 \<and> substate s3 s4 \<and> s3 \<noteq> s4 \<longrightarrow> getVarBool s3 (Suc (Suc 0)) = ON \<and> getVarBool s3 hands = OFF)" by auto qed next case (3 s5) then show ?case apply(simp only: pred3_def) proof from 3(3) have 6: " (\<forall>s3. toEnvP s3 \<and> substate s2 s3 \<and> substate s3 s5 \<and> s3 \<noteq> s5 \<longrightarrow> getVarBool s3 (Suc (Suc 0)) = ON \<and> getVarBool s3 hands = OFF) \<Longrightarrow> (\<exists>s4. toEnvP s4 \<and> substate s5 s4 \<and> substate s4 s \<and> toEnvNum s2 s4 \<le> 10 \<and> (getVarBool s4 (Suc (Suc 0)) = OFF \<or> getVarBool s4 hands = ON) \<and> (\<forall>s3. toEnvP s3 \<and> substate s5 s3 \<and> substate s3 s4 \<and> s3 \<noteq> s4 \<longrightarrow> getVarBool s3 (Suc (Suc 0)) = ON \<and> getVarBool s3 hands = OFF)) " by (auto simp add: pred3_def) assume 7: " \<forall>s3. toEnvP s3 \<and> substate s2 s3 \<and> substate s3 (predEnv s5) \<and> s3 \<noteq> predEnv s5 \<longrightarrow> getVarBool s3 (Suc (Suc 0)) = ON \<and> getVarBool s3 hands = OFF" show "\<exists>s4. toEnvP s4 \<and> substate (predEnv s5) s4 \<and> substate s4 s \<and> toEnvNum s2 s4 \<le> 10 \<and> (getVarBool s4 (Suc (Suc 0)) = OFF \<or> getVarBool s4 hands = ON) \<and> (\<forall>s3. toEnvP s3 \<and> substate (predEnv s5) s3 \<and> substate s3 s4 \<and> s3 \<noteq> s4 \<longrightarrow> getVarBool s3 (Suc (Suc 0)) = ON \<and> getVarBool s3 hands = OFF)" proof cases assume 10: "(getVarBool (predEnv s5) (Suc (Suc 0)) = OFF \<or> getVarBool (predEnv s5) hands = ON)" from predEnv_substate 3 substate_trans have 8: "substate (predEnv s5) s" by blast from 3(2) substate_eq_or_predEnv req_prems have 9: "substate s2 (predEnv s5)" by auto have "toEnvP (predEnv s5) \<and> substate (predEnv s5) (predEnv s5) \<and> substate (predEnv s5) s \<and> toEnvNum s2 (predEnv s5) \<le> 10 \<and> (getVarBool (predEnv s5) (Suc (Suc 0)) = OFF \<or> getVarBool (predEnv s5) hands = ON) \<and> (\<forall>s3. toEnvP s3 \<and> substate (predEnv s5) s3 \<and> substate s3 (predEnv s5) \<and> s3 \<noteq> (predEnv s5) \<longrightarrow> getVarBool s3 (Suc (Suc 0)) = ON \<and> getVarBool s3 hands = OFF)" proof - from predEnvP_or_emptyState[of s5] have "toEnvP (predEnv s5)" proof assume "toEnvP (predEnv s5)" thus ?thesis by assumption next assume "predEnv s5 = emptyState" with 9 req_prems show ?thesis by (cases s2; auto) qed moreover from substate_refl have " substate (predEnv s5) (predEnv s5)" by auto moreover from 8 have "substate (predEnv s5) s" by assumption moreover from 4 8 9 toEnvNum3 have "toEnvNum s2 (predEnv s5) \<le> 10" by auto moreover from 10 have "(getVarBool (predEnv s5) (Suc (Suc 0)) = OFF \<or> getVarBool (predEnv s5) hands = ON)" by assumption moreover from substate_asym have "\<forall>s3. toEnvP s3 \<and> substate (predEnv s5) s3 \<and> substate s3 (predEnv s5) \<and> s3 \<noteq> predEnv s5 \<longrightarrow> getVarBool s3 (Suc (Suc 0)) = ON \<and> getVarBool s3 hands = OFF" by auto ultimately show ?thesis by auto qed thus ?thesis by auto next assume 10: "\<not> (getVarBool (predEnv s5) (Suc (Suc 0)) = OFF \<or> getVarBool (predEnv s5) hands = ON)" with substate_eq_or_predEnv 7 have " \<forall>s3. toEnvP s3 \<and> substate s2 s3 \<and> substate s3 s5 \<and> s3 \<noteq> s5 \<longrightarrow> getVarBool s3 (Suc (Suc 0)) = ON \<and> getVarBool s3 hands = OFF" by auto from 6[OF this] obtain s4 where 11: "toEnvP s4 \<and> substate s5 s4 \<and> substate s4 s \<and> toEnvNum s2 s4 \<le> 10 \<and> (getVarBool s4 (Suc (Suc 0)) = OFF \<or> getVarBool s4 hands = ON) \<and> (\<forall>s3. toEnvP s3 \<and> substate s5 s3 \<and> substate s3 s4 \<and> s3 \<noteq> s4 \<longrightarrow> getVarBool s3 (Suc (Suc 0)) = ON \<and> getVarBool s3 hands = OFF)" .. have "(toEnvP s4 \<and> substate (predEnv s5) s4 \<and> substate s4 s \<and> toEnvNum s2 s4 \<le> 10 \<and> (getVarBool s4 (Suc (Suc 0)) = OFF \<or> getVarBool s4 hands = ON)) \<and> (\<forall>s3. toEnvP s3 \<and> substate (predEnv s5) s3 \<and> substate s3 s4 \<and> s3 \<noteq> s4 \<longrightarrow> getVarBool s3 (Suc (Suc 0)) = ON \<and> getVarBool s3 hands = OFF)" proof from 11 predEnv_substate substate_trans show "toEnvP s4 \<and> substate (predEnv s5) s4 \<and> substate s4 s \<and> toEnvNum s2 s4 \<le> 10 \<and> (getVarBool s4 (Suc (Suc 0)) = OFF \<or> getVarBool s4 hands = ON)" by blast next show "\<forall>s3. toEnvP s3 \<and> substate (predEnv s5) s3 \<and> substate s3 s4 \<and> s3 \<noteq> s4 \<longrightarrow> getVarBool s3 (Suc (Suc 0)) = ON \<and> getVarBool s3 hands = OFF" proof(rule allI; rule impI) fix s3 assume 12: "toEnvP s3 \<and> substate (predEnv s5) s3 \<and> substate s3 s4 \<and> s3 \<noteq> s4" with 11 3(1) predEnv_substate_imp_eq_or_substate have "s3 = predEnv s5 \<or> substate s5 s3" by auto with 10 11 12 show "getVarBool s3 (Suc (Suc 0)) = ON \<and> getVarBool s3 hands = OFF" by auto qed qed thus ?thesis by auto qed qed qed with s5_def req_prems substate_refl pred3_def 5 show ?thesis by auto qed qed qed next assume "((toEnvP s0 \<and> (\<forall>s1 s2. substate s1 s2 \<and> substate s2 s0 \<and> toEnvP s1 \<and> toEnvP s2 \<and> toEnvNum s1 s2 = hands \<and> 10 \<le> toEnvNum s2 s0 \<and> getVarBool s1 hands = ON \<and> getVarBool s1 (Suc (Suc 0)) = ON \<and> getVarBool s2 hands = OFF \<longrightarrow> (\<exists>s4. toEnvP s4 \<and> substate s2 s4 \<and> substate s4 s0 \<and> toEnvNum s2 s4 \<le> 10 \<and> (getVarBool s4 (Suc (Suc 0)) = OFF \<or> getVarBool s4 hands = ON) \<and> (\<forall>s3. toEnvP s3 \<and> substate s2 s3 \<and> substate s3 s4 \<and> s3 \<noteq> s4 \<longrightarrow> getVarBool s3 (Suc (Suc 0)) = ON \<and> getVarBool s3 hands = OFF)))) \<and> extraInv s0) \<and> env (setVarAny s0 hands_value) hands_value \<and> getPstate (setVarAny s0 hands_value) Ctrl = waiting \<and> getVarBool (setVarAny s0 hands_value) hands \<noteq> ON" with extra3 show " extraInv (toEnv (setVarBool (setVarAny s0 hands_value) (Suc (Suc 0)) OFF))" by (auto simp add: VC3_def dryer_def) qed end
# Built-in LcmInt(12, 18); # 36
lemma compact_Un [intro]: assumes "compact s" and "compact t" shows " compact (s \<union> t)"
{-# LANGUAGE MultiParamTypeClasses #-} module ChaosBox.Geometry.Class ( Boundary(..) , HasP2(..) , Intersects(..) , getP2 , setP2 , modifyP2 ) where import ChaosBox.Geometry.P2 import Control.Lens (Lens', lens, (%~), (&), (.~), (^.)) import Data.Complex import Linear.V2 -- | Class of objects that can be queried for points class Boundary a where containsPoint :: a -> P2 -> Bool class HasP2 a where _V2 :: Lens' a P2 instance HasP2 P2 where _V2 = _xy instance HasP2 (Complex Double) where _V2 = lens (\(a :+ b) -> V2 a b) (\_ (V2 x y) -> x :+ y) getP2 :: HasP2 a => a -> P2 getP2 = (^. _V2) setP2 :: HasP2 a => a -> P2 -> a setP2 x p2 = x & _V2 .~ p2 modifyP2 :: HasP2 a => a -> (P2 -> P2) -> a modifyP2 x f = x & _V2 %~ f class Intersects a b where intersectionPoints :: a -> b -> [P2] intersects :: a -> b -> Bool intersects a b = null (intersectionPoints a b)
module Idris.Codegen.ExtSTG.Prelude namespace FilePath export FilePath : Type FilePath = String export getFilePath : FilePath -> String getFilePath = id export mkFilePath : String -> FilePath mkFilePath = id public export interface SemiDecEq t where semiDecEq : (x : t) -> (y : t) -> Maybe (x = y) export SemiDecEq Nat where semiDecEq Z Z = Just Refl semiDecEq (S n1) (S n2) = do Refl <- semiDecEq n1 n2 Just Refl semiDecEq _ _ = Nothing export SemiDecEq a => SemiDecEq (List a) where semiDecEq [] [] = Just Refl semiDecEq (x :: xs) (y :: ys) = do Refl <- semiDecEq x y Refl <- semiDecEq xs ys Just Refl semiDecEq _ _ = Nothing public export numberFrom : Nat -> List a -> List (Nat, a) numberFrom n xs = go xs n [] where go : List a -> Nat -> List (Nat, a) -> List (Nat, a) go [] k ys = ys go (x :: xs) k ys = (k, x) :: go xs (S k) ys
-- nonlinear least-squares fitting import Spinell.Fitting import Spinell.Graphing import Numeric.LinearAlgebra model [a,lambda,b] t = a * exp (-lambda * t)+b --the function we will be fitting jac [a,lambda,b] [t] = [[exp (-lambda * t), -t * a * exp(-lambda*t) , 1]] xs = [0..100] sigma = replicate (length xs) 0.1 -- will create an array of repeating '0.1': [0.1,0.1...] noise = toList $ scalar 0.1 * (randomVector 0 Gaussian (length xs)) --a list of random small values, that will play the role of the noise in the data ys = map (model [5,0.1,1]) xs --we plainly apply the model to the data ysNoisy = [ y + err | (y,err) <- zip ys noise] -- and then add the noise, just to make it look more realistic res = fit xs ys sigma model [1,1,1] defFitOpt{jacob = ManualJacob jac} main :: IO() main = plotFit xs ysNoisy sigma model (getParams res) defGraphOpt
Require Import Metalib.Metatheory. Require Import Coq.Program.Equality. Require Import Language Automations Subtyping LibTactics. Require Import Strings.String. (* aux lemma for tred_determinism *) Lemma tred_ord_toplike : forall (v v' : trm) (A : typ), ordinary A -> toplike A -> typedred v A v' -> v' = (trm_anno (trm_int 1) A). Proof. induction 3; eauto; try solve [inversion_toplike | inversion_ordinary]. Qed. Hint Resolve tred_ord_toplike : core. (* aux lemma for disjoint_value_consistent *) Lemma tred_sub : forall (A : typ) (v v' : trm), value v -> typedred v A v' -> forall (B : typ), typing nil nil v B -> sub B A. Proof. introv Hv Hred. dependent induction Hred; eauto; introv Htyp. - dependent destruction Htyp. dependent destruction Htyp; eauto. simpl_as; eauto. - dependent destruction Htyp; eauto. simpl_as; eauto. - dependent destruction Hv. dependent destruction Htyp; eapply sub_and_l; eapply IHHred; eauto. - dependent destruction Hv. dependent destruction Htyp; eapply sub_and_r; eapply IHHred; eauto. Qed. (* aux lemma for disjoint_value_consistent *) Lemma tred_determinism_toplike : forall (A : typ), toplike A -> forall (e1 e2 e1' e2' : trm), typedred e1 A e1' -> typedred e2 A e2' -> e1' = e2'. Proof. intros A Htop. dependent induction Htop; introv Hred1 Hred2. - eapply tred_ord_toplike in Hred1; eauto. eapply tred_ord_toplike in Hred2; eauto. congruence. - dependent destruction Hred1; eauto; try solve [inversion_ordinary]. dependent destruction Hred2; try solve [inversion_ordinary]. assert (v1 = v0). eapply IHHtop1; eauto 3. assert (v2 = v3). eapply IHHtop2; eauto 3. congruence. - assert (toplike (typ_arrow A B)); eauto. eapply tred_ord_toplike in Hred1; eauto. eapply tred_ord_toplike in Hred2; eauto. congruence. Qed. (* aux lemma for tred_determinism *) Lemma disjoint_value_consistent : forall (A B : typ) (v1 v2 : trm), disjoint_spec A B -> value v1 -> value v2 -> typing nil nil v1 A -> typing nil nil v2 B -> consistency_spec v1 v2. Proof. intros. unfold consistency_spec. intros. unfold disjoint_spec in *. assert (sub A A0). eapply tred_sub with (v:=v1); eauto. assert (sub B A0). eapply tred_sub with (v:=v2); eauto. assert (toplike A0); eauto. eapply tred_determinism_toplike; eauto. Qed. Hint Resolve disjoint_value_consistent : core. Theorem tred_determinism : forall (v v1 v2 : trm) (A : typ), value v -> (exists B, typing nil nil v B) -> typedred v A v1 -> typedred v A v2 -> v1 = v2. Proof. introv Hv Htyp Hred1. generalize dependent v2. dependent induction Hred1; eauto; introv Hred2. - dependent induction Hred2; try solve [inversion_toplike]; eauto. - dependent destruction Hred2; try solve [inversion_toplike | inversion_ordinary]; eauto. + symmetry. eapply tred_ord_toplike; eauto. + symmetry. eapply tred_ord_toplike; eauto. - dependent destruction Hred2; try solve [inversion_toplike]; eauto. - dependent destruction Hv. dependent destruction Htyp. dependent destruction Hred2; try solve [inversion_ordinary]; eauto. + dependent destruction H; eauto. + dependent destruction H; eauto. assert (consistency_spec v1 v2). eapply disjoint_value_consistent; eauto 3. eauto. - dependent destruction Hv. dependent destruction Htyp. dependent destruction Hred2; try solve [inversion_ordinary]; eauto. + dependent destruction H; eauto. * assert (consistency_spec v1 v2); eauto. symmetry. eauto. * symmetry. eauto. + dependent destruction H; eauto. - dependent destruction Hred2; try solve [inversion_ordinary]; eauto. assert (v1 = v0); eauto. assert (v2 = v3); eauto. congruence. Qed. Lemma tred_value : forall (v v' : trm) (A : typ), value v -> typedred v A v' -> value v'. Proof. intros. dependent induction H0; try solve [eauto | dependent destruction H; eauto]. Qed. Hint Resolve tred_value : core. Lemma tred_transitivity : forall (v1 v2 v3 : trm) (A B : typ), value v1 -> typedred v1 A v2 -> typedred v2 B v3 -> typedred v1 B v3. Proof. intros. generalize dependent v3. generalize dependent B. dependent induction H0; eauto; introv Hred2. - dependent induction Hred2; eauto. - dependent induction Hred2; try solve [inversion_toplike_sub]; eauto. - dependent induction Hred2; eauto 4. eapply tred_arrow_anno; eauto; eapply sub_transitivity; eauto. - dependent destruction H. dependent induction Hred2; eauto. - dependent destruction H. dependent induction Hred2; eauto. - generalize dependent v3. induction B0; intros v0 Hred2; try solve [eauto | dependent destruction Hred2; eauto]. Qed. Lemma tred_consistency : forall (v v1 v2 : trm) (A B C : typ), value v -> typing nil nil v C -> typedred v A v1 -> typedred v B v2 -> consistency_spec v1 v2. Proof. intros. unfold consistency_spec; intros. assert (typedred v A0 e1'). eapply tred_transitivity with (v1:=v) (v2:=v1) (v3:=e1'); eauto. assert (typedred v A0 e2'). eapply tred_transitivity with (v1:=v) (v2:=v2) (v3:=e2'); eauto. eapply tred_determinism; eauto. Qed. Theorem tred_preservation: forall (v v': trm) (A B: typ), value v -> typing nil nil v B -> typedred v A v' -> typing nil nil v' A. Proof. intros v v' A B Hv Htyp Hred. assert (Hsub: sub B A). eapply tred_sub; eauto. generalize dependent B. dependent induction Hred; eauto 3; intros. - eapply typing_anno; eauto. - dependent destruction Htyp. dependent destruction Htyp. eapply typing_anno; eauto. eapply sub_transitivity; eauto. - dependent destruction Hv. dependent destruction Htyp; eapply IHHred; eauto. + eapply tred_sub. apply Hv1. apply Hred. apply Htyp1. + eapply tred_sub. apply Hv1. apply Hred. apply Htyp1. - dependent destruction Hv. dependent destruction Htyp; eapply IHHred; eauto. + eapply tred_sub. apply Hv2. apply Hred. apply Htyp2. + eapply tred_sub. apply Hv2. apply Hred. apply Htyp2. - eapply typing_merge_value; eauto. + eapply tred_consistency; eauto. + eapply IHHred1; eauto. eapply tred_sub. apply Hv. apply Hred1. apply Htyp. + eapply IHHred2; eauto. eapply tred_sub. apply Hv. apply Hred2. apply Htyp. Qed. Theorem tred_progress : forall (v : trm) (A B : typ), value v -> typing nil nil v A -> sub A B -> exists v', typedred v B v'. Proof. introv Hv Htyp Hsub. generalize dependent A. induction B; introv Htyp Hsub; eauto. - dependent induction Htyp; try solve [inversion Hv]. + simpl_as. dependent destruction Hv. dependent destruction H. * clear IHHtyp. dependent destruction Htyp. exists (trm_anno (trm_int n) typ_int); eauto. * clear IHHtyp. dependent destruction Htyp. assert (sub (typ_arrow A0 B) typ_int). eapply sub_transitivity; eauto. inversion H1. + dependent destruction Hv. dependent destruction Hsub. * assert (exists v', typedred e1 typ_int v'); eauto. destruct H0; eauto. * assert (exists v', typedred e2 typ_int v'); eauto. destruct H0; eauto. + dependent destruction Hv. dependent destruction Hsub. * assert (exists v', typedred v1 typ_int v'); eauto. destruct H2; eauto. * assert (exists v', typedred v2 typ_int v'); eauto. destruct H2; eauto. - destruct (toplike_or_not_toplike B2). + exists (trm_anno (trm_int 1) (typ_arrow B1 B2)). eapply tred_top; eauto. + clear IHB1 IHB2. dependent induction Htyp; try solve [inversion Hv]. * simpl_as. dependent destruction Hv. dependent induction H. (* case 1 *) dependent destruction Htyp. assert (sub typ_int (typ_arrow B1 B2)). eapply sub_transitivity; eauto. dependent destruction H2. assert (toplike B2); eauto. (* case 2 *) dependent destruction Htyp. exists (trm_anno (trm_abs e A0 B) (typ_arrow B1 B2)); eauto. * dependent destruction Hv. eapply sub_and_inversion2 in Hsub. destruct Hsub. (* case 1 *) assert (exists v', typedred e1 (typ_arrow B1 B2) v'); eauto. destruct H2. exists x; eauto. destruct H1. (* case 2 *) assert (exists v', typedred e2 (typ_arrow B1 B2) v'); eauto. destruct H2. exists x; eauto. (* case 3 *) destruct H1. destruct H1. inversion H1. * dependent destruction Hv. eapply sub_and_inversion2 in Hsub. destruct Hsub. (* case 1 *) assert (exists v', typedred v1 (typ_arrow B1 B2) v'); eauto. destruct H4. exists x; eauto. destruct H3. (* case 2 *) assert (exists v', typedred v2 (typ_arrow B1 B2) v'); eauto. destruct H4. exists x; eauto. (* case 3 *) destruct H3. destruct H3. inversion H3. - eapply sub_and_inversion1 in Hsub. destruct Hsub. assert (exists v', typedred v B1 v'); eauto. assert (exists v', typedred v B2 v'); eauto. destruct H1. destruct H2. exists (trm_merge x x0); eauto. Qed.
using Test, QMPS, Yao, Random, Statistics using MSQR # Un-comment if testing GPU acceleration compatibility. # using CuYao @testset "SWAPtest(SWAPtrain.jl)" begin seedNum = 1234 m = 1 n = 3 Random.seed!(seedNum) cgen = dispatch!(DCbuilder(n,4).circuit, :random) reg1 = rand_state(n) reg2 = rand_state(n) reg3 = zero_state(n) |> cgen olp12m1 = SWAPtest(reg1, reg2, nMeasure=m) olp12m2 = SWAPtest(join(zero_state(1), reg1, reg2), nMeasure=m) olp23m1 = SWAPtest(reg2, cgen, nMeasure=m) olp23m2 = SWAPtest(cgen, regAll = join(zero_state(n+1), reg2), nMeasure=m) cST = chain(7, put(7, 7=>H), put(7, 7=>shift(0)), chain(7, control(7, 7, (6,3)=>SWAP), control(7, 7, (5,2)=>SWAP), control(7, 7, (4,1)=>SWAP)), put(7, 7=>H)) op = put(2n+1, 2n+1=>Z) reg12t = repeat(join(zero_state(1), reg1, reg2), m) |> cST reg23t = repeat(join(zero_state(1), reg3, reg2), m) |> cST olp12t = expect(op, reg12t) |> mean |> real olp23t = expect(op, reg23t) |> mean |> real @test olp12m1.reg ≈ olp12m2.reg @test olp23m1.reg ≈ olp23m2.reg @test olp12m1.reg ≈ reg12t @test olp23m1.reg ≈ reg23t @test olp12m2.witnessOp == op @test olp12m2.circuit == cST @test isapprox(olp12m1.overlap, olp12m2.overlap, atol=10e-12) @test isapprox(olp23m1.overlap, olp23m2.overlap, atol=10e-12) @test isapprox(olp12m1.overlap, olp12t, atol=10e-12) @test isapprox(olp23m1.overlap, olp23t, atol=10e-12) end @testset "MPSSwapTest.jl" begin seedNum = 1234 # MScircuit(nBitT::Int64, vBit::Int64, rBit::Int64, MPSblocks::Array{CompositeBlock,1}; ϕ::Float64=0.0) ## MPSblcoks = MPSC("CS", 4, 1, 1).mpsBlocks n0 = 4 v0 = 1 r0 = 1 Random.seed!(seedNum) mps0cs = MPSC("CS", n0, v0, r0) csMblocks = mps0cs.mpsBlocks CSc = MScircuit(n0, v0, r0, mps0cs.mpsBlocks) CSct = chain(7, put(7, 7=>H), chain(7, subroutine(7, csMblocks[1], 5:6), control(7, 7, (4,6)=>SWAP), Measure(7, locs=(6), resetto=0)), chain(7, subroutine(7, csMblocks[2], 5:6), control(7, 7, (3,6)=>SWAP), Measure(7, locs=(6), resetto=0)), chain(7, subroutine(7, csMblocks[3], 5:6), control(7, 7, (2,6)=>SWAP), Measure(7, locs=(6), resetto=0)), control(7, 7, (1,5)=>SWAP), put(7, 7=>H)) opx(n) = chain(n, [put(n, i=>X) for i=1:n]) opy(n) = chain(n, [put(n, i=>Y) for i=1:n]) opz(n) = chain(n, [put(n, i=>Z) for i=1:n]) function cr_test(reg::ArrayReg, cr::CompositeBlock, crt::CompositeBlock) n = nqubits(reg) Random.seed!(seedNum) reg1x = expect(opx(n), copy(reg) |> cr) |> mean |> real Random.seed!(seedNum) reg1y = expect(opy(n), copy(reg) |> cr) |> mean |> real Random.seed!(seedNum) reg1z = expect(opz(n), copy(reg) |> cr) |> mean |> real Random.seed!(seedNum) reg2x = expect(opx(n), copy(reg) |> crt) |> mean |> real Random.seed!(seedNum) reg2y = expect(opy(n), copy(reg) |> crt) |> mean |> real Random.seed!(seedNum) reg2z = expect(opz(n), copy(reg) |> crt) |> mean |> real @test reg1x ≈ reg2x @test reg1y ≈ reg2y @test reg1z ≈ reg2z end cr_test(repeat(join(zero_state(3),rand_state(4)),5000), CSc, CSct) ## MPSblcoks = MPSC(("DC",2), 8, 2, 2).mpsBlocks n1 = 8 v1 = 2 r1 = 2 d1 = 2 Random.seed!(seedNum) mps0dc = MPSC(("DC",d1), n1, v1, r1) dcMblocks = mps0dc.mpsBlocks DCc = MScircuit(n1, v1, r1, mps0dc.mpsBlocks) DCct = chain(13, put(13, 13=>H), chain(13, subroutine(13, dcMblocks[1], 9:12), control(13, 13, (12, 8)=>SWAP), control(13, 13, (11, 7)=>SWAP), Measure(13, locs=(11,12), resetto=0)), chain(13, subroutine(13, dcMblocks[2], 9:12), control(13, 13, (12, 6)=>SWAP), control(13, 13, (11, 5)=>SWAP), Measure(13, locs=(11,12), resetto=0)), chain(13, subroutine(13, dcMblocks[3], 9:12), control(13, 13, (12, 4)=>SWAP), control(13, 13, (11, 3)=>SWAP), Measure(13, locs=(11,12), resetto=0)), chain(13, control(13, 13, (10, 2)=>SWAP), control(13, 13, (9, 1)=>SWAP)), put(13, 13=>H)) cr_test(repeat(join(zero_state(5),rand_state(8)),5000), DCc, DCct) # MStest(regT::ArrayReg, MSCircuit::ChainBlock; nMeasure::Int64=1, useCuYao::Bool=CUDA_ON) # MStest(MSCircuit::ChainBlock; regAll::ArrayReg) # MSTtest(regT::ArrayReg, MSCircuit::ChainBlock, cExtend::ChainBlock; nMeasure::Int64=1, useCuYao::Bool=CUDA_ON) ## MPSblcoks = MPSC("CS", 4, 1, 1).mpsBlocks m = 500 n = 4 v = 1 r = 1 Random.seed!(seedNum) regT = rand_state(n) mps1 = MPSC("CS", n, v, r) c1 = MScircuit(n, v, r, mps1.mpsBlocks) Random.seed!(seedNum) t1_0_m1 = MStest(regT, c1, nMeasure=m) Random.seed!(seedNum) t1_0_m2 = MStest(c1, regAll=repeat(join(zero_state(nqubits(c1)-n),regT),m)) Random.seed!(seedNum) t1 = MSTtest(regT, c1, mps1.cExtend, nMeasure=m) @test t1_0_m1.reg ≈ t1_0_m2.reg @test t1_0_m1.witnessOp == t1_0_m2.witnessOp @test isapprox(t1_0_m1.overlap, t1_0_m2.overlap, atol=10e-12) @test isapprox(t1_0_m1.overlap, t1.Aoverlap, atol=10e-12) @test isapprox(t1.Eoverlap, t1.Aoverlap, atol=1.001abs(t1.error*t1.Eoverlap)) Ext_overlap = SWAPtest(zero_state(n)|>mps1.cExtend, regT, nMeasure=m).overlap @test isapprox.(t1.Eoverlap, Ext_overlap, atol=1.001abs(t1.error*t1.Eoverlap)) ## MPSblcoks = MPSC(("DC",2), 6, 2, 2).mpsBlocks n = 4 v = 2 r = 1 d = 3 Random.seed!(seedNum) regT = rand_state(n) mps2 = MPSC(("DC",d), n, v, r) c2 = MScircuit(n, v, r, mps2.mpsBlocks) p = MSCpar(c2) @test (p.nBitA, p.nBitT, p.vBit, p.rBit, p.depth) == (nqubits(c2), n, v, r, d) Random.seed!(seedNum) t2_0_m1 = MStest(regT, c2, nMeasure=m) Random.seed!(seedNum) t2_0_m2 = MStest(c2, regAll=repeat(join(zero_state(p.nBitA-n),regT),m)) Random.seed!(seedNum) t2 = MSTtest(regT, c2, mps2.cExtend, nMeasure=m) @test t2_0_m1.reg ≈ t2_0_m2.reg @test t2_0_m1.witnessOp == t2_0_m2.witnessOp @test isapprox(t2_0_m1.overlap, t2_0_m2.overlap, atol=10e-12) @test isapprox(t2_0_m1.overlap, t2.Aoverlap, atol=10e-12) @test isapprox(t2.Eoverlap, t2.Aoverlap, atol=1.001abs(t2.error*t2.Eoverlap)) Ext_overlap = SWAPtest(zero_state(n)|>mps2.cExtend, regT, nMeasure=m).overlap @test isapprox.(t2.Eoverlap, Ext_overlap, atol=1.001abs(t2.error*t2.Eoverlap)) end @testset "MSQRtrain!(MSQRtrain.jl) + SWAPtrain!(SWAPtrain.jl)" begin seedNum = 1234 n = 3 v = 1 r = 1 d = 2 Random.seed!(seedNum) regT = rand_state(n) Random.seed!(seedNum) mps = MPSC(("DC",d),n,v,r) c = MScircuit(n, v, r, mps.mpsBlocks) md1 = ("ADAM", 0.05) md2 = ("default", 0.2) m = 150 ## Testing function exceptions. @test_throws ErrorException GDescent("default") mps_m1q = deepcopy(mps) c_m1q = MScircuit(n, v, r, mps_m1q.mpsBlocks) mps_s1q = deepcopy(mps) c_s1q = mps_s1q.cExtend mps_m2q = deepcopy(mps) c_m2q = MScircuit(n, v, r, mps_m2q.mpsBlocks) mps_s2q = deepcopy(mps) c_s2q = mps_s2q.cExtend mps_m1n = deepcopy(mps) c_m1n = MScircuit(n, v, r, mps_m1n.mpsBlocks) mps_s1n = deepcopy(mps) c_s1n = mps_s1n.cExtend mps_m2n = deepcopy(mps) c_m2n = MScircuit(n, v, r, mps_m2n.mpsBlocks) mps_s2n = deepcopy(mps) c_s2n = mps_s2n.cExtend showON = false Random.seed!(seedNum) mres1q = MSQRtrain!(regT, c_m1q, 40, nMeasure=m, GDmethod = md1, show=true) # Test show option. Random.seed!(seedNum) mres2q = MSQRtrain!(regT, c_m2q, 50, nMeasure=m, GDmethod = md2, show=showON) Random.seed!(seedNum) sres1q = SWAPtrain!(regT, c_s1q, 40, nMeasure=m, GDmethod = md1, show=true) # Test show option. Random.seed!(seedNum) sres2q = SWAPtrain!(regT, c_s2q, 50, nMeasure=m, GDmethod = md2, show=showON) Random.seed!(seedNum) mres1n = MSQRtrain!(regT, c_m1n, 40, nMeasure=m, GDmethod = md1, Gmethod=("Ndiff", 0.05), show=showON) Random.seed!(seedNum) mres2n = MSQRtrain!(regT, c_m2n, 50, nMeasure=m, GDmethod = md2, Gmethod=("Ndiff", 0.05), show=showON) Random.seed!(seedNum) sres1n = SWAPtrain!(regT, c_s1n, 40, nMeasure=m, GDmethod = md1, Gmethod=("Ndiff", 0.05), show=showON) Random.seed!(seedNum) sres2n = SWAPtrain!(regT, c_s2n, 50, nMeasure=m, GDmethod = md2, Gmethod=("Ndiff", 0.05), show=showON) ## Test different methods / optional arguments of the functions. c_m1n_2 = MScircuit(n, v, r, deepcopy(mps).mpsBlocks) Random.seed!(seedNum) a = MSQRtrain!(regT, c_m1n_2, 150, nMeasure=200, GDmethod = ("ADAM", 0.05, (0.9, 0.999)), Gmethod="Ndiff", show=showON) mres1n_2 = MSQRtrain!(regT, c_m1n_2, :auto, nMeasure=m, GDmethod = md1, show=showON, ConvTh=(5e-3,1e-2)) c_s1n_2 = deepcopy(mps).cExtend Random.seed!(seedNum) b = SWAPtrain!(regT, c_s1n_2, 20, nMeasure=m, GDmethod = md1, show=showON) sres1n_2 = SWAPtrain!(regT, c_s1n_2, :auto, nMeasure=m, GDmethod = "ADAM", show=showON, ConvTh=(5e-3,1e-2)) # If all the trainings converge in the end. cuti = 9 tol = 0.06 mres1qConv = mres1q[end-cuti:end] # MSQR + ADAM + Qdiff mres2qConv = mres2q[end-cuti:end] # MSQR + CONS + Qdiff sres1qConv = sres1q[end-cuti:end] # SWAP + ADAM + Qdiff sres2qConv = sres2q[end-cuti:end] # SWAP + CONS + Qdiff mres1nConv = mres1n[end-cuti:end] # MSQR + ADAM + Ndiff mres2nConv = mres2n[end-cuti:end] # MSQR + CONS + Ndiff sres1nConv = sres1n[end-cuti:end] # SWAP + ADAM + Ndiff sres2nConv = sres2n[end-cuti:end] # SWAP + CONS + Ndiff # @show mres1n_2Conv = mres1n_2[end-cuti:end] # @show sres1n_2Conv = sres1n_2[end-cuti:end] mres1n_2Conv = mres1n_2[end-cuti:end] sres1n_2Conv = sres1n_2[end-cuti:end] mres1qMean = mres1qConv |> mean mres2qMean = mres2qConv |> mean sres1qMean = sres1qConv |> mean sres2qMean = sres2qConv |> mean mres1nMean = mres1nConv |> mean mres2nMean = mres2nConv |> mean sres1nMean = sres1nConv |> mean sres2nMean = sres2nConv |> mean mres1n_2Mean = mres1n_2Conv |> mean sres1n_2Mean = sres1n_2Conv |> mean @test std(mres1qConv) ≤ tol*mres1qMean @test std(mres2qConv) ≤ tol*mres2qMean @test std(sres1qConv) ≤ tol*sres1qMean @test std(sres2qConv) ≤ tol*sres2qMean @test std(mres1nConv) ≤ tol*mres1nMean @test std(mres2nConv) ≤ tol*mres2nMean @test std(sres1nConv) ≤ tol*sres1nMean @test std(sres2nConv) ≤ tol*sres2nMean # If ADAM and default SGD converge to the approximately same value. ## (Including Ndiff and Qdiff situations) tol2 = 0.06 @test isapprox(mres1qMean, mres2qMean, atol=tol2*max( mres1qMean, mres2qMean )) @test isapprox(sres1qMean, sres2qMean, atol=tol2*max( sres1qMean, sres2qMean )) @test isapprox(mres1nMean, mres2nMean, atol=tol2*max( mres1nMean, mres2nMean )) @test isapprox(sres1nMean, sres2nMean, atol=tol2*max( sres1nMean, sres2nMean )) # If MSQRtrain and SWAPtrain converge to the approximately same value. ## (Including Ndiff and Qdiff situations) tol3 = 0.06 @test isapprox(mres1qMean, sres1qMean, atol=tol3*max( mres1qMean, sres1qMean )) @test isapprox(mres2qMean, sres2qMean, atol=tol3*max( mres2qMean, sres2qMean )) @test isapprox(mres1nMean, sres1nMean, atol=tol3*max( mres1nMean, sres1nMean )) @test isapprox(mres2nMean, sres2nMean, atol=tol3*max( mres2nMean, sres2nMean )) # If the auto-train actually converges to theoretical maximum. @test isapprox(mres1n_2Mean, 1.0, atol = 1.5e-2) @test isapprox(sres1n_2Mean, 1.0, atol = 1.5e-2) # If the training curves monotonically rise. function trendCompr(res::Array{Float64, 1}) midv = middle(res) @test res[end] > midv > res[1] max = (2midv-res[1]) @test res[end] / max > 0.9 end trendCompr(mres1q) trendCompr(sres1q) trendCompr(mres2q) trendCompr(sres2q) trendCompr(mres1n) trendCompr(sres1n) trendCompr(mres2n) trendCompr(sres2n) # If the overlaps from MSQR have enough accuracy. function oltest(regT::ArrayReg, cGen::ChainBlock, nM::Int64, ol0::Float64) nq = nqubits(cGen) regG = zero_state(nq, nbatch=nM) |> cGen ol = ((regT.state'*regG.state)[1] |> abs)^2 @test isapprox(ol, ol0, atol=0.005) end oltest(regT, mps_m1q.cExtend, m, mres1q[end]) oltest(regT, c_s1q, m, sres1q[end]) oltest(regT, mps_m2q.cExtend, m, mres2q[end]) oltest(regT, c_s2q, m, sres2q[end]) oltest(regT, mps_m1n.cExtend, m, mres1n[end]) oltest(regT, c_s1n, m, sres1n[end]) oltest(regT, mps_m2n.cExtend, m, mres2n[end]) oltest(regT, c_s2n, m, sres2n[end]) end
maxdims["trg"] = 10:10:50 descriptions["trg"] = "TRG, 2D classical Ising model\nN → ∞, 20 iterations\nβ = 1.001 βc" function runbenchmark(::Val{:trg}; maxdim::Int, nsweeps::Int = 20, outputlevel::Int = 0, cutoff::Float64 = 0.0, β::Float64 = 1.001 * βc, splitblocks::Bool = false) if splitblocks println("Benchmark trg doesn't support splitblocks $splitblocks.") return nothing end # Make Ising model MPO s = Index(2) sₕ = addtags(s, "horiz") sᵥ = addtags(s, "vert") T = ising_mpo(sₕ, sᵥ, β) κ, T = trg(T; χmax = maxdim, cutoff = cutoff, nsteps = nsweeps) if outputlevel > 0 @show nsweeps @show β @show cutoff @show κ, exp(-β * ising_free_energy(β)) end return ITensors.maxdim(T) end
/* * @file * @author University of Warwick * @version 1.0 * * @section LICENSE * * @section DESCRIPTION * * Unit Tests for the LinearSolverConfig class */ #define BOOST_TEST_MODULE LinearSolverConfigPETSc #include <boost/test/unit_test.hpp> #include <boost/test/output_test_stream.hpp> #include <stdexcept> #include "LinearSolverConfigPETSc.h" #include "Error.h" using namespace cupcfd::linearsolvers; // === Constructors === BOOST_AUTO_TEST_CASE(constructor_test1) { LinearSolverConfigPETSc config; // Check Defaults }
""" This code reads in old and new information from IS simulations for the purposes of beta optimization. It saves the "new" information to a file, which can then be accessed in the future as "old" information. THIS CODE IS MEANT TO BE USED WITH THE SCRIPT "RUNSCRIPTIS" """ import csv import numpy as np import matplotlib.pyplot as plt import glob import os import itertools def readsvals(whichset): with open(whichset+'SpecialVals.txt') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') deltaf = next(csv_reader)[1] return deltaf def listdirNH(path): return sorted(glob.glob(os.path.join(path, '*'))) pullfrom = 'JulyData/' # This contains new error information from recent sims subdir = 'JulyData/' # This contains old error information from past sims #Access existing data xvector = np.array([]) errors = np.array([]) eerr = listdirNH(subdir+'IS Optimization Errors') i = 0 for e in eerr: print(e,i) data = np.transpose(np.loadtxt(e)) for d in range(len(data[0])): #if data[0][d]>-8700: if data[0][d]>-1000000000: xvector = np.append(xvector,data[0][d]) errors = np.append(errors,data[1][d]) i+=1 # Plot old data z= np.polyfit(xvector,errors,2) print(z) p = np.poly1d(z) px=np.linspace(0,6e9,2000) py = p(px) mn = np.where(py==min(py)) mnx = px[mn] print(mnx) plt.title(subdir[:-1]) plt.plot(xvector,errors,'k.',markersize = 10) plt.plot(px,py,'.',markersize = 5) plt.plot(mnx,min(py),'*',markersize = 7) # plt.show() # ##Get new information # pullfrom = 'JulyData/' # # subdir = pullfrom # newerror = np.array([]) # newxvector = np.array([]) # files = listdirNH(pullfrom) # # for test in files: # Test is a set of simulation runs # print(test) # if test.find('IS_optimization_bet') != -1: # if test[-11:].find('_') == -1: # This may need to be == # print('test',test[-11:]) # with open(test+'/Simulations/Errors/SidebandError.txt') as csv_file: # csv_reader = csv.reader(csv_file, delimiter=',') # for row in csv_reader: # newerror=np.append(newerror,float(row[1])) # newxvector = np.append(newxvector,float(test[-11:])) # # #newxvector = np.linspace(0,35000,100) # print(newerror) # #Plot the new error information # plt.plot(newxvector,newerror,'k.') # plt.show() # # # Save the new error information to the overall data directory # newset = np.vstack((newxvector,newerror)) # mn = min(newxvector) # mx = max(newxvector) # print(pullfrom,mn,mx) # print() # np.savetxt(subdir+'IS Optimization Errors/run_'+str(mn)+'_to_'+str(mx)+'.txt',np.transpose(newset)) # print('it saved')
import Lfea.Proofs.Set -- An alphabet is a finite set of symbols or letters -- A word is a finite sequence of letters with only one symbol -- being valid that is the ε that means empty -- A word over an alphabet α is a list of α? probably. -- A formal language over an alpha bet A is a: L ⊆ A* -- (The reflexive and transitive closure under A) -- Chomsky grammar is a 4-tuple G = (V, T, P, S) -- Where -- - V = Finite set of variable symbols or non terminals -- - T = Finite set of symbols disjoint of V -- - P = (V ∪ T)+ -> (V ∪ T)* finite relations of production rules -- - S = distinguished from V (initial symbol) -- Derivation rule ⟹ -- The transitive closure of the derivation rule makes it derive -- one or more symbols at once -- Generated language is the language that is derived from the language -- that we can achieve using Derivation rule from the start symbol -- Finite automatas are operational semantics -- Regular expressions are denotational semantics -- Regular grammar are axiomatic semantics -- Σ alphabet of input symbols -- Q possible states -- δ program (transition function) -- δ: Q × Σ → Q structure Dfa (sigma: Type) (n: Nat) where state : Fin n -- Initial State program : Fin n -> sigma -> Fin n -- Generating program final : Set (Fin n) -- Final states def Dfa.extendedProgram : Dfa σ n → Fin n → List σ → Fin n | dfa, q, [] => q | dfa, q, (x :: xs) => extendedProgram dfa (dfa.program q x) xs -- It is accepted if the final state is part of the DFA final set -- structure Dfa.Accepts (lang: List σ) (dfa: Dfa σ n) where proof : (Dfa.extendedProgram dfa dfa.state lang) ∈ dfa.final inductive Alpha where | a | b def prog : Fin 4 -> Alpha -> Fin 4 | 0, Alpha.a => 1 | 1, Alpha.b => 2 | 1, Alpha.a => 1 | 2, Alpha.a => 2 | _, _ => 3 example : Dfa.Accepts [Alpha.a, Alpha.b] { state := 0, program := prog, final := {x | x = 2}} := { proof := by simp [Dfa.extendedProgram, Set.in] } -- NFA -- Non deterministic returns a set structure Nfa (sigma: Type) (n: Nat) where state : Fin n -- Initial State program : Fin n -> sigma -> Set (Fin n) final : Set (Fin n) -- Final states def Nfa.extendedProgram : Nfa σ n → Set (Fin n) → List σ → Set (Fin n) | nfa, qs, [] => qs | nfa, qs, (x :: xs) => -- Its a confusing definition -- The result of the extended program is the -- Big union of all the Set.bigUnion { el | ∃q, q ∈ qs ∧ (el = extendedProgram nfa (nfa.program q x) xs) } structure Nfa.Accepts (lang: List σ) (nfa: Nfa σ n) where proof : ∃q, q ∈ (Nfa.extendedProgram nfa {x | x = nfa.state} lang) ∧ q ∈ nfa.final -- Denotational semantics of Regex inductive Regex (σ: Type) where | var : σ -> Regex σ | alt : Regex σ -> Regex σ -> Regex σ | conc : Regex σ -> Regex σ -> Regex σ | star : Regex σ -> Regex σ | empty : Regex σ def sizeOfRegex : Regex σ -> Nat | Regex.var _ => 1 | Regex.alt a b => sizeOfRegex a + sizeOfRegex b | Regex.conc a b => sizeOfRegex a + sizeOfRegex b | Regex.star _ => 1 | Regex.empty => 2 inductive Regex.Accepts : List σ → Regex σ → Type where | acceptsEmpty : Accepts [] Regex.empty | acceptsVar : Accepts [x] (Regex.var x) | acceptsAltL : Accepts x l → Accepts x (Regex.alt l r) | acceptsAltR : Accepts x r → Accepts x (Regex.alt l r) | acceptsConc : Accepts x a → Accepts y b → Accepts (x ++ y) (Regex.conc a b) | acceptsStar : Accepts [] (Regex.star a) | acceptsStar2 : Accepts x a → Accepts y (Regex.star a) → Accepts (x ++ y) (Regex.star a) theorem Regex.NotMatchesEmpty: ∀ {x : σ} {xs : List σ}, Regex.Accepts (x :: xs) Regex.empty → False | x, xs, accepts => accepts.casesOn (motive := λacc regex proof => (acc = (x :: xs) -> regex = Regex.empty -> False)) (λproof _ => List.noConfusion proof) -- acceptsEmpty (λproof ot => Regex.noConfusion ot) -- acceptsVar (λ_ _ ot => Regex.noConfusion ot) -- acceptsAltL (λ_ _ ot => Regex.noConfusion ot) -- acceptsAltR (λ_ _ _ ot => Regex.noConfusion ot) -- acceptsConc (λ _ ot => Regex.noConfusion ot) -- acceptsStar (λ_ _ _ ot => Regex.noConfusion ot) -- acceptsStar2 rfl rfl example : Regex.Accepts ['a', 'a', 'b'] (Regex.conc (Regex.star (Regex.var 'a')) (Regex.var 'b')) := Regex.Accepts.acceptsConc (Regex.Accepts.acceptsStar2 Regex.Accepts.acceptsVar (Regex.Accepts.acceptsStar2 Regex.Accepts.acceptsVar Regex.Accepts.acceptsStar)) Regex.Accepts.acceptsVar -- iff redefined lol structure IIff (a: Type u) (b: Type u) where to : a -> b mpr: b -> a notation:40 a "`↔" b:40 => IIff a b universe u axiom IIff.toEql : ∀ {a b: Type u} (_: IIff a b), a = b -- ENFA def Nfa.Nfa_ε.End: Set (Fin 2) := { x | x = 1 } def Nfa.Nfa_ε.Final: Fin 2 → Prop := { x | x = 0 } def Nfa.Nfa_ε : Nfa σ 2 := { state := 0, program := λ _ _ => Nfa.Nfa_ε.End, final := { x | x = 0 }} def Nfa.Nfa_ε.initial: ∀ {σ: Type}, Set (Fin 2) | x => {y | y = (@Nfa.state x 2 Nfa.Nfa_ε)} theorem Nfa.Nfa_ε.EverythingLeadToEnd : ∀ {q: (Fin 2)} {x: σ}, (Nfa.Nfa_ε.program q x) = Nfa.Nfa_ε.End := by simp; rfl theorem Nfa.Nfa_ε.EverythingToFinal : ∀ {xs: List σ}, (Nfa.extendedProgram Nfa.Nfa_ε Nfa.Nfa_ε.End xs) = Nfa.Nfa_ε.End | [] => by simp [Nfa.extendedProgram] | (x :: xs) => by simp [Nfa.extendedProgram, Set.bigUnion, Set.subset, Set.in] apply Set.Eq . intro x1 simp [Set.in] intro ex apply Exists.elim . assumption . intro state proof simp [Set.in] apply Exists.elim . exact (And.right proof) . intro ata rw [Nfa.Nfa_ε.EverythingLeadToEnd, EverythingToFinal] intro wot rw [←wot.right] exact proof.left . simp [Nfa.extendedProgram, Set.bigUnion, Set.subset, Set.in] intro x1 end_x1 exists End apply And.intro . assumption . exact ⟨1, by simp [End] rw [Nfa.Nfa_ε.EverythingLeadToEnd, EverythingToFinal] rfl⟩ theorem Nfa.Nfa_ε.LeadToFinal: ∀ {σ: Type} {x : σ} {xs: List σ}, (Nfa.extendedProgram Nfa.Nfa_ε (@Nfa.Nfa_ε.initial σ) (x :: xs)) = Nfa.Nfa_ε.End | sigm, x, xs => by simp [extendedProgram, Nfa.Nfa_ε.EverythingToFinal, Set.bigUnion, Set.in] apply Set.Eq . simp [Set.in, Set.subset] intro x ex apply Exists.elim . assumption . intro a p apply Exists.elim . exact p.right . intro b rw [Nfa.Nfa_ε.EverythingLeadToEnd, EverythingToFinal] intro f rw [←f.right] exact p.left . simp [Nfa.extendedProgram, Set.bigUnion, Set.subset, Set.in] intro x1 end_x1 exists End apply And.intro . assumption . exact ⟨0, And.intro rfl (by rw [Nfa.Nfa_ε.EverythingLeadToEnd, Nfa.Nfa_ε.EverythingToFinal])⟩ theorem Nfa.Nfa_ε.NotAcceptsEntries: ∀ {σ: Type} {x : σ} {xs: List σ}, Nfa.Accepts (x :: xs) Nfa.Nfa_ε → False | sig, x, xs, p => absurd p.proof $ by let f : fun y => y = (@Nfa.state sig 2 Nfa.Nfa_ε) = (@Nfa.Nfa_ε.initial sig) := rfl simp [Set.in, Nfa.Nfa_ε.LeadToFinal] intro x2 apply Exists.elim . assumption . intro a rw [f, Nfa.Nfa_ε.LeadToFinal] simp [End, Nfa_ε] intro and let f := Eq.trans (Eq.symm and.left) and.right contradiction def toNFA : ∀ (s: List σ), (r: Regex σ) → ∃ (n : Nat), ∃ (e: Nfa σ n), (Regex.Accepts s r) = (Nfa.Accepts s e) | s, Regex.empty => let iffRes : (s: List σ) → (Regex.Accepts s Regex.empty) `↔ (Nfa.Accepts s Nfa.Nfa_ε) | [] => { to := by intro a simp [Nfa.Nfa_ε, Nfa.Accepts] exact { proof := by simp [Nfa.extendedProgram]; exact ⟨0, rfl⟩ } mpr := λ _ => Regex.Accepts.acceptsEmpty } | (x :: xs) => { to := λ x => False.elim (Regex.NotMatchesEmpty x) mpr := λx => False.elim (Nfa.Nfa_ε.NotAcceptsEntries x) } ⟨2, ⟨Nfa.Nfa_ε, IIff.toEql (iffRes s)⟩⟩ | s, Regex.var a => sorry | s, Regex.star a => sorry | s, Regex.conc a b => sorry | s, Regex.alt a b => sorry -- Pumping lemma -- Assume q₀ as the initial state and qf the final state, then
State Before: b x y : ℝ hb : 1 < b ⊢ 0 < b State After: no goals Tactic: linarith
theory prop_28 imports Main "../../TestTheories/Listi" "../../TestTheories/Naturals" "$HIPSTER_HOME/IsaHipster" begin hipster rev app lemma lemma_a [thy_expl]: "app x2 NL.Nil = x2" by (hipster_induct_schemes Listi.rev.simps Listi.app.simps) lemma lemma_aa [thy_expl]: "app (app x1 y1) z1 = app x1 (app y1 z1)" by (hipster_induct_schemes Listi.rev.simps Listi.app.simps) lemma lemma_ab [thy_expl]: "app (Listi.rev x9) (Listi.rev y9) = Listi.rev (app y9 x9)" by (hipster_induct_schemes Listi.rev.simps Listi.app.simps) lemma lemma_ac [thy_expl]: "Listi.rev (Listi.rev x8) = x8" by (hipster_induct_schemes Listi.rev.simps Listi.app.simps) theorem palyn : "t = rev t \<Longrightarrow> rev (app t t) = app t t" by (hipster_induct_schemes rev.simps app.simps) end
<h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Chapter-2---Elements-of-Matrix-Theory" data-toc-modified-id="Chapter-2---Elements-of-Matrix-Theory-1">Chapter 2 - Elements of Matrix Theory</a></span><ul class="toc-item"><li><span><a href="#2.1.2-The-Jordan-Normal-Form" data-toc-modified-id="2.1.2-The-Jordan-Normal-Form-1.1">2.1.2 The Jordan Normal Form</a></span><ul class="toc-item"><li><span><a href="#Example-2.5-Revisiting-the-wireless-sensor-network-example" data-toc-modified-id="Example-2.5-Revisiting-the-wireless-sensor-network-example-1.1.1">Example 2.5 Revisiting the wireless sensor network example</a></span></li><li><span><a href="#NumPy/-SciPy-approach" data-toc-modified-id="NumPy/-SciPy-approach-1.1.2">NumPy/ SciPy approach</a></span></li><li><span><a href="#SymPy-approach" data-toc-modified-id="SymPy-approach-1.1.3">SymPy approach</a></span></li></ul></li><li><span><a href="#2.1.3-Semi-convergence-and-convergence-for-discrete-time-linear-systems" data-toc-modified-id="2.1.3-Semi-convergence-and-convergence-for-discrete-time-linear-systems-1.2">2.1.3 Semi-convergence and convergence for discrete-time linear systems</a></span><ul class="toc-item"><li><span><a href="#Definition-2.6-(Spectrum-and-spectral-radius-of-a-matrix)" data-toc-modified-id="Definition-2.6-(Spectrum-and-spectral-radius-of-a-matrix)-1.2.1">Definition 2.6 (Spectrum and spectral radius of a matrix)</a></span></li></ul></li><li><span><a href="#2.2.1-The-spectral-radius-for-row-stochastic-matrices" data-toc-modified-id="2.2.1-The-spectral-radius-for-row-stochastic-matrices-1.3">2.2.1 The spectral radius for row-stochastic matrices</a></span><ul class="toc-item"><li><span><a href="#Theorem-2.8-(Geršgorin-Disks-Theorem)" data-toc-modified-id="Theorem-2.8-(Geršgorin-Disks-Theorem)-1.3.1">Theorem 2.8 (Geršgorin Disks Theorem)</a></span></li></ul></li><li><span><a href="#2.3.3-Applications-to-matrix-powers-and-averaging-systems" data-toc-modified-id="2.3.3-Applications-to-matrix-powers-and-averaging-systems-1.4">2.3.3 Applications to matrix powers and averaging systems</a></span><ul class="toc-item"><li><span><a href="#Theorem-2.13-(Powers-of-non-negative-matrices-with-a-simple-and-strictly-dominant-eigenvalue)" data-toc-modified-id="Theorem-2.13-(Powers-of-non-negative-matrices-with-a-simple-and-strictly-dominant-eigenvalue)-1.4.1">Theorem 2.13 (Powers of non-negative matrices with a simple and strictly dominant eigenvalue)</a></span><ul class="toc-item"><li><span><a href="#Example-2.14-Wireless-sensor-network" data-toc-modified-id="Example-2.14-Wireless-sensor-network-1.4.1.1">Example 2.14 Wireless sensor network</a></span></li></ul></li></ul></li><li><span><a href="#Exercises-2.18" data-toc-modified-id="Exercises-2.18-1.5">Exercises 2.18</a></span></li><li><span><a href="#Exercises-2.19" data-toc-modified-id="Exercises-2.19-1.6">Exercises 2.19</a></span></li></ul></li></ul></div> ```python %matplotlib widget # Import packages import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl import networkx as nx import scipy.linalg as spla from sympy import Matrix # For interactive graphs import ipywidgets as widgets # Import self defined functions import lib # General library # Settings custom_figsize= (6, 4) # Might need to change this value to fit the figures to your screen custom_figsize_square = (5, 5) ``` # Chapter 2 - Elements of Matrix Theory These Jupyter Notebook scripts contain some examples, visualization and supplements accompanying the book "Lectures on Network Systems" by Francesco Bullo http://motion.me.ucsb.edu/book-lns/. These scripts are published with the MIT license. **Make sure to run the first cell above to import all necessary packages and functions and adapt settings in case.** In this script it is necessary to execute cell by cell chronologically due to reocurring examples (excepts for e.g. the Exercises in the end). (Tip: Use the shortcut Shift+Enter to execute each cell). Most of the functions are kept in separate files to keep this script neat. ## 2.1.2 The Jordan Normal Form ### Example 2.5 Revisiting the wireless sensor network example The following cells are showing the computation of the Jordan Normal Form $J$, the invertible transformation matrix $T$ and some of its dependencies. ```python # Defining the A matrix again A = np.array([[1/2, 1/2, 0., 0.], [1/4, 1/4, 1/4, 1/4], [0., 1/3, 1/3, 1/3], [0., 1/3, 1/3, 1/3] ]) ``` There is the possibility to calculate the Jordan Normal Form directly with the package SymPy https://docs.sympy.org/latest/index.html. However, we are determining the Jordan Normal Form via determining the generalized eigenvectors (read more for literature recommendations about generalized eigenvectors in the book) with the SciPy package first to discuss some possibilities and problems with non symbolic toolboxes. ### NumPy/ SciPy approach From the documentation of scipy.linalg.eig: *'Solve an ordinary or generalized eigenvalue problem of a square matrix.'* ```python # Right eigenvectors lambdas, eigv = spla.eig(A) # Left eigenvectors lambdas2, eigw = spla.eig(A.T) ``` Due to numerical instabilities, the zero values are not reflected and it can be seen, how the expected eigenvalue of 1 is not precise. The zeros can be fixed with: ```python def correct_close_to_zero(M, tol=1e-12): M.real[abs(M.real) < tol] = 0.0 if M.imag.any(): M.imag[abs(M.imag) < tol] = 0.0 return M eigv_cor = correct_close_to_zero(eigv) eigw_cor = correct_close_to_zero(eigw) lambdas_cor = correct_close_to_zero(lambdas) lambdas2_cor = correct_close_to_zero(lambdas2) print("Right eigenvectors:") lib.matprint(eigv_cor) print("\n") print("Left eigenvectors:") lib.matprint(eigw_cor) print("\n") print("Eigenvalues (right):") lib.matprint(lambdas_cor) print("\n") print("Eigenvalues (left) for matching later:") lib.matprint(lambdas2_cor) ``` There are two options now for $T^{-1}$: Taking the inverse of the right eigenvectors (which contains again numerical instabilities) or building it from the left eigenvectors, what would include some sorting to match the eigenvalue order from the right eigenvector (often it is the case, that they are already aligned since calling scipy.linalg.eig twice on a matrix with the same eigenvalues). ```python T = eigv_cor.copy()*-1 # Rescale the eigenvectors to match eigenvalues later # Sorting if necessary, remember to use transpose, since in T^-1 the rows represent the left eigenvectors. Tinv = eigw_cor.T.copy() ``` Now we can simply compute J, when compared, is fairly close to the solution in the book, however, due to numerical intabilities not precise. Further on, the order of the eigenvalues might be different than the on from the book. ```python J = correct_close_to_zero(Tinv@A@T) print("Jordan Normal Form via SciPy/Numpy:") lib.matprint(J) ``` ### SymPy approach Now we use a symbolic toolbox package SymPy from python as a blackbox. Note, that also here the order of the eigenvalues might be different! ```python Asym = Matrix(A) # Sympy Matrix toolbox object Tsym, Jsym = Asym.jordan_form() ``` Here we can compare them with our previous results: ```python print("Jordan Normal Form SymPy:") lib.matprint(np.array(Jsym).astype(np.float64)) print("Jordan Normal Form SciPy:") lib.matprint(J) ``` ## 2.1.3 Semi-convergence and convergence for discrete-time linear systems ### Definition 2.6 (Spectrum and spectral radius of a matrix) We display the spectrum of the previous A matrix with the spectrum radius for visualization purpose. Additionally, we also show how the spectrum of a randomly generated matrix. ```python fig, ax213 = plt.subplots(figsize=custom_figsize_square) lib.plot_spectrum(A, ax213); ``` ```python n_M1=8 # A unifornmly distributed, positive, row stochastic matrix vs not row stochastic M1 = np.random.uniform(0, 1,(n_M1,n_M1)) M1 = M1 / M1.sum(axis=1, keepdims=1) # Row-stochastic M2 = M1 - 0.05 # Not row-stochastic fig, (ax2131, ax2132) = plt.subplots(1,2, figsize=(custom_figsize_square[0]*2, custom_figsize_square[1])) lib.plot_spectrum(M1, ax2131); lib.plot_spectrum(M2, ax2132); ``` ## 2.2.1 The spectral radius for row-stochastic matrices ### Theorem 2.8 (Geršgorin Disks Theorem) Similar to before, the Geršgorin Disks are now visualized for a row-stochastic matrix and another matrix. ```python fig, (ax2211, ax2212) = plt.subplots(1,2, figsize=(custom_figsize_square[0]*2, custom_figsize_square[1])) lib.plot_gersgorin_disks(M1, ax2211) lib.plot_gersgorin_disks(M2, ax2212) ``` ## 2.3.3 Applications to matrix powers and averaging systems ### Theorem 2.13 (Powers of non-negative matrices with a simple and strictly dominant eigenvalue) Here is an example for Theorem 2.13, which shows, how the powers of primitive, row-stochastic matrices converges to rank 1. This is also done for the wireless sensor network example. #### Example 2.14 Wireless sensor network In the book it is shown, that the wireless sensor network matrix is primitive. Here, the eigenvectors and eigenvalues are printed again and compared for the semi convergence result $\lim_{k \to \infty} A^k = \mathbb{1}_n w^T$ to demonstrate Theorem 2.13 for a row-stochastic matrix. ```python print("Left eigenvectors of A:") lib.matprint(eigw_cor) print("\n") print("Eigenvalues (left) of A:") lib.matprint(lambdas2_cor) print("\n") print("Normalizing dominant eigenvector:") dom_eigv = eigw_cor[:, 0] / sum(eigw_cor[:, 0]) lib.matprint(dom_eigv) print("\n") print("Convergence result of A:") lib.matprint(np.linalg.matrix_power(A, 50)) print("\n") print("equals 1n*w^T") lib.matprint(np.ones((4,1))@dom_eigv[:, None].T) ``` Below is a randomly generated example to show, that primitive, row-stochastic matrices always converge to rank 1. *Note: The code is not robust for semisimple eigenvalue of 1* ```python # Creating a new random primitive (positiv), row stochastic matrix here n_M11=5 M11 = np.random.uniform(0, 1,(n_M11,n_M11)) M11 = M11 / M11.sum(axis=1, keepdims=1) # Row-stochastic print("Random primitive row-stochastic matrix M:") lib.matprint(M11) print("\n") print("Left eigenvectors of M:") l_M, m_eigv = spla.eig(M11.T) m_eigv = correct_close_to_zero(m_eigv) l_M = correct_close_to_zero(l_M) lib.matprint(m_eigv) print("\n") print("Eigenvalues (left) of M:") lib.matprint(l_M) print("\n") # Here we check the position with numerical unprecision of the eigenvalue 1 print("Normalizing dominant eigenvector:") idx_dom = np.where(abs(l_M - 1) < 0.005)[0][0] dom_eigv_M = m_eigv[:, 0] / sum(m_eigv[:, 0]) lib.matprint(dom_eigv_M) print("\n") print("Convergence result of M:") lib.matprint(np.linalg.matrix_power(M11, 500)) print("\n") print("equals 1n*w^T") lib.matprint(np.ones((n_M11,1))@dom_eigv_M[:, None].T) ``` ## Exercises 2.18 This section is similar to exercise 1.4, however, here we actually visualize the graph and its node values. Additionally, we show that the values converge to the initial values multiplied b the dominant left eigenvector as presented in Theorem 2.13 for row stochastic matrices. First, we define the graphs and their adjacency Matrix A and simulate the results. Then, for each graph a cell can be executed for the interactive visualization. A plot of the states is available in the Jupyter Notebook script for Chapter 1. ```python # Define x_0 xinitial = np.array([1., -1., 1., -1., 1.]) # Defining the 3 different systems. # Complete graph A_complete = np.ones((5,5)) / 5 # Cycle graph A_cycle = np.array([ [1/3, 1/3, 0, 0, 1/3], [1/3, 1/3, 1/3, 0, 0], [0, 1/3, 1/3, 1/3, 0], [0, 0, 1/3, 1/3, 1/3], [1/3, 0, 0, 1/3, 1/3] ] ) # Star topology. center = node 1 A_star = np.array([ [1/5, 1/5, 1/5, 1/5, 1/5], [1/2, 1/2, 0, 0, 0], [1/2, 0, 1/2, 0, 0], [1/2, 0, 0, 1/2, 0], [1/2, 0, 0, 0, 1/2] ]) # Defining simulation time ts = 15 # Defining graphs for plotting later n = 5 G_star = nx.star_graph(n-1) pos_star = {0:[0.5,0.8], 1:[0.2,0.6],2:[.4,.2],3:[.6,.2],4:[.8,.6]} G_cycle = nx.cycle_graph(n) pos_cycle = {0:[0.5,0.8], 1:[0.35,0.6],2:[.4,.3],3:[.6,.3],4:[.65,.6]} G_complete = nx.complete_graph(n) pos_complete = pos_cycle.copy() # Simulating and saving each network states_complete = lib.simulate_network(A_complete,xinitial, ts) states_star = lib.simulate_network(A_star,xinitial, ts) states_cycle = lib.simulate_network(A_cycle,xinitial, ts) ``` **Complete graph** Showing complete graph interactive simulation and Theorem 2.13 ```python fig, ax2181 = plt.subplots(figsize=custom_figsize) # If this cell is executed twice we are making sure in the following, that the previous widget instances are all closed try: [c.close() for c in widget2181.children] # Note: close_all() does also affect plot, thus list compr. except NameError: # Only want to except not defined variable error pass widget2181 = lib.interactive_network_plot(G_complete, states_complete, pos_complete, ts, fig, ax2181) display(widget2181) # Verifying the results eigval, eigvec = np.linalg.eig(A_complete.transpose()) idx_dom = np.argmax(eigval) dom_eigvec = eigvec[0:5,idx_dom]/eigvec[0:5,idx_dom].sum() print("Showing Theorem 2.13 for the complete graph") print("Dominant eigenvector: \n", dom_eigvec) print("Final values : \n", xinitial@dom_eigvec*np.ones(5)) ``` **Star graph** Showing star graph interactive simulation and Theorem 2.13 ```python fig, ax2182 = plt.subplots(figsize=custom_figsize) # If this cell is executed twice we are making sure in the following, that the previous widget instances are all closed try: [c.close() for c in widget2182.children] # Note: close_all() does also affect plot, thus list compr. except NameError: # Only want to except not defined variable error pass widget2182 = lib.interactive_network_plot(G_star, states_star, pos_star, ts, fig, ax2182) display(widget2182) # Verifying the results eigval, eigvec = np.linalg.eig(A_star.transpose() ) idx_dom = np.argmax(eigval) dom_eigvec = eigvec[0:5,idx_dom]/eigvec[0:5,idx_dom].sum() print("Showing Theorem 2.13 for the star graph") print("Dominant eigenvector: \n", dom_eigvec) print("Final values : \n", xinitial@dom_eigvec*np.ones(5)) ``` **Cycle graph** Showing cycle graph interactive simulation and Theorem 2.13 ```python fig, ax2183 = plt.subplots(figsize=custom_figsize) # If this cell is executed twice we are making sure in the following, that the previous widget instances are all closed try: [c.close() for c in widget2183.children] # Note: close_all() does also affect plot, thus list compr. except NameError: # Only want to except not defined variable error pass widget2183 = lib.interactive_network_plot(G_cycle, states_cycle, pos_cycle, ts, fig, ax2183) display(widget2183) # Verifying the results eigval, eigvec = np.linalg.eig(A_cycle.transpose()) idx_dom = np.argmax(eigval) dom_eigvec = eigvec[0:5,idx_dom]/eigvec[0:5,idx_dom].sum() print("Showing Theorem 2.13 for the cycle graph") print("Dominant eigenvector: \n", dom_eigvec) print("Final values : \n", xinitial@dom_eigvec*np.ones(5)) ``` ## Exercises 2.19 This exercise is about $n$ robots moving on the line trying to gather at a common location (i.e., reach rendezvous), where each robot heads for the centroid of its neighbors. The visualization of the algorithm deals with the discrete part of the task, where on can explore values of the sampling period $T$ for the Euler discretization. ```python # Setup - change these parameters if wanted n_robots = 8 # Number of timesteps and sampling period T (If T is too small, need very high n_dt) n_dt = 25 T = 0.3 # Play around with this value, something interesting is happening around (2(n_robots-1)/n_robots) #T = 2*(n_robots-1)/n_robots # Set up initial position matrix and further saving variables current_positions = 2*np.random.random((n_robots,1))-1 new_position = current_positions.copy() all_positions = np.zeros((n_dt, n_robots, 1)) all_positions[0] = current_positions.copy() for tt in range(1, n_dt): for index, own_pos in np.ndenumerate(current_positions): new_position[index] = own_pos + T*(1/(n_robots-1)*(np.sum(current_positions)-own_pos) - own_pos) all_positions[tt] = new_position.copy() current_positions = new_position.copy() ``` ```python fig, ax219 = plt.subplots(figsize=custom_figsize) # Set colors of robots for tracking all_colors = np.random.rand(n_robots,3) def plot_robot_pos(ax, pos): # Set xlim, ylim and aspect ratio ax219.set_xlim(-1.5, 1.5) ax219.set_ylim(-0.5, 0.5) ax219.set_aspect('equal') # Add horizontal line ax219.axhline(y=0.0, color='k', linestyle='-') for i in range(0, pos.shape[0]): # Add a robot as circle bug = mpl.patches.Circle((pos[i], 0), radius=0.06, ec='black', color=all_colors[i]) ax.add_patch(bug) def interactive_robots(timestep): ax219.clear() plot_robot_pos(ax219, all_positions[timestep['new'], :]) # Take the new value received from the slider dict return None # Plot initial configuration plot_robot_pos(ax219, all_positions[0, :]) # Widget # If this cell is executed twice we are making sure in the following, that the previous widget instances are all closed try: [c.close() for c in widget219.children] # Note: close_all() does also affect plot, thus list compr. except NameError: # Only want to except not defined variable error pass widget219 = lib.create_widgets_play_slider(fnc=interactive_robots, minv=0, maxv=n_dt-1, step=1, play_speed=500) display(widget219) ``` We can even compute the convergence solution in advance. Please refer and solve the given Excersice first to try to understand the following calculations. ```python A_robot = 1/(n_robots-1) * np.ones((n_robots, n_robots)) - n_robots/(n_robots-1)*np.identity(n_robots) eigval, eigvec = np.linalg.eig(A_robot) idx = np.argmin(abs(eigval)) z_eigvec = eigvec[:,idx]/np.sqrt(np.sum(eigvec[:,idx]**2)) final_values = z_eigvec[None, :] @ all_positions[0] @ z_eigvec[None, :] print("Final values :", final_values) ``` ```python ```
Require Import trees. Set Implicit Arguments. (* Deallocate one tree *) Definition dealloc_def := FunDef "deallocate" ["t"] (SIf ("t"=0) SReturnVoid {{SCall "deallocate" ["t"->>"left"] ;SCall "deallocate" ["t"->>"right"] ;HDealloc "t" ;SReturnVoid }}). (* Deallocate a whole list of trees *) Definition iter_dealloc_def := FunDef "iter_deallocate" ["l"] {{Decl "lt"; SWhile ("l" <> 0) {{SCall "deallocate" ["l"->>"val"] ;"lt" <- "l" ;"l" <- "l"->>"next" ;HDealloc "lt" }}; SReturnVoid}}. Inductive dealloc_spec : Spec kcfg := dealloc_claim : forall t p, heap_void_fun dealloc_spec nil dealloc_def [Int p] (rep_tree t p) emptyP |iter_dealloc_claim : forall l p, heap_void_fun dealloc_spec [dealloc_def] iter_dealloc_def [Int p] (rep_prop_list rep_tree l p) (emptyP) |iter_dealloc_loop_claim : forall v l p, heap_void_loop dealloc_spec [dealloc_def] iter_dealloc_def 0 ("l" s|-> KInt p :* "lt" s|-> v) (rep_prop_list rep_tree l p) (emptyP). Lemma dealloc_proof : sound kstep dealloc_spec. Proof. tree_solver. Qed.
using HTTP.Messages @testset "HTTP.Bodies" begin @test String(take!(Body("Hello!"))) == "Hello!" @test String(take!(Body(IOBuffer("Hello!")))) == "Hello!" @test String(take!(Body(Vector{UInt8}("Hello!")))) == "Hello!" @test String(take!(Body())) == "" io = BufferStream() @async begin write(io, "Hello") sleep(0.1) write(io, "!") sleep(0.1) close(io) end @test String(take!(Body(io))) == "5\r\nHello\r\n1\r\n!\r\n0\r\n\r\n" b = Body() write(b, "Hello") write(b, "!") @test String(take!(b)) == "Hello!" io = BufferStream() b = Body(io) write(b, "Hello") write(b, "!") @test String(readavailable(io)) == "Hello!" #display(b); println() buf = IOBuffer() show(buf, b) @test String(take!(buf)) == "Hello!\n⋮\nWaiting for BufferStream...\n" write(b, "\nWorld!") close(io) #display(b); println() buf = IOBuffer() show(buf, b) @test String(take!(buf)) == "Hello!\nWorld!\n" tmp = HTTP.Messages.Bodies.body_show_max HTTP.Messages.Bodies.set_show_max(12) b = Body("Hello World!xxx") #display(b); println() buf = IOBuffer() show(buf, b) @test String(take!(buf)) == "Hello World!\n⋮\n15-byte body\n" HTTP.Messages.Bodies.set_show_max(tmp) end
theory quasimax imports Main (* Quasi-maximality: C. Benzmüller & X. Parent, 2020 *) (* Quasi-maximality, Deb 1977, means maximal wrt transitive closure of the betterness relation restricted to the menu *) (* Quasi-maximality: ideally the transitive closure should be paramatrized by a context. It is restricted to the set of antecedent-worlds. The transitive closure should be recalculated each time each time the set of worlds in which the antecedent is true changes *) begin typedecl i (*Possible worlds.*) type_synonym \<sigma> = "(i\<Rightarrow>bool)" consts aw::i (*Actual world.*) abbreviation etrue :: "\<sigma>" ("\<^bold>\<top>") where "\<^bold>\<top> \<equiv> \<lambda>w. True" abbreviation efalse :: "\<sigma>" ("\<^bold>\<bottom>") where "\<^bold>\<bottom> \<equiv> \<lambda>w. False" abbreviation enot :: "\<sigma>\<Rightarrow>\<sigma>" ("\<^bold>\<not>_"[52]53) where "\<^bold>\<not>\<phi> \<equiv> \<lambda>w. \<not>\<phi>(w)" abbreviation eand :: "\<sigma>\<Rightarrow>\<sigma>\<Rightarrow>\<sigma>" (infixr"\<^bold>\<and>"51) where "\<phi>\<^bold>\<and>\<psi> \<equiv> \<lambda>w. \<phi>(w)\<and>\<psi>(w)" abbreviation eor :: "\<sigma>\<Rightarrow>\<sigma>\<Rightarrow>\<sigma>" (infixr"\<^bold>\<or>"50) where "\<phi>\<^bold>\<or>\<psi> \<equiv> \<lambda>w. \<phi>(w)\<or>\<psi>(w)" abbreviation eimp :: "\<sigma>\<Rightarrow>\<sigma>\<Rightarrow>\<sigma>" (infixr"\<^bold>\<rightarrow>"49) where "\<phi>\<^bold>\<rightarrow>\<psi> \<equiv> \<lambda>w. \<phi>(w)\<longrightarrow>\<psi>(w)" abbreviation eequ :: "\<sigma>\<Rightarrow>\<sigma>\<Rightarrow>\<sigma>" (infixr"\<^bold>\<leftrightarrow>"48) where "\<phi>\<^bold>\<leftrightarrow>\<psi> \<equiv> \<lambda>w. \<phi>(w)\<longleftrightarrow>\<psi>(w)" (*Possibilist--constant domain--quantification.*) abbreviation eforall ("\<^bold>\<forall>") where "\<^bold>\<forall>\<Phi> \<equiv> \<lambda>w.\<forall>x. (\<Phi> x w)" abbreviation eforallB (binder"\<^bold>\<forall>"[8]9) where "\<^bold>\<forall>x. \<phi>(x) \<equiv> \<^bold>\<forall>\<phi>" abbreviation eexists ("\<^bold>\<exists>") where "\<^bold>\<exists>\<Phi> \<equiv> \<lambda>w.\<exists>x. (\<Phi> x w)" abbreviation eexistsB (binder"\<^bold>\<exists>"[8]9) where "\<^bold>\<exists>x. \<phi>(x) \<equiv> \<^bold>\<exists>\<phi>" abbreviation ebox :: "\<sigma>\<Rightarrow>\<sigma>" ("\<box>") where "\<box> \<equiv> \<lambda>\<phi> w. \<forall>v. \<phi>(v)" (* Some useful relations for constraining accessibility relations*) type_synonym \<alpha> = "i\<Rightarrow>\<sigma>" (*Type of betterness relation between worlds.*) definition transitive :: "\<alpha>\<Rightarrow>bool" where "transitive R \<equiv> \<forall>x y z. R x y \<and> R y z \<longrightarrow> R x z" definition sub_rel :: "\<alpha>\<Rightarrow>\<alpha>\<Rightarrow>bool" where "sub_rel R Q \<equiv> \<forall>u v. R u v \<longrightarrow> Q u v" definition inverse_rel :: "\<alpha>\<Rightarrow>\<alpha>" where "inverse_rel R \<equiv> \<lambda>u v. R v u" (*In HOL the transitive closure of a relation can be defined in a single line.*) definition tc :: "\<alpha>\<Rightarrow>\<alpha>" where "tc R \<equiv> \<lambda>x y.\<forall>Q. transitive Q \<longrightarrow> (sub_rel R Q \<longrightarrow> Q x y)" consts R :: "i\<Rightarrow>\<sigma>" (infixr "R" 70) (*Betterness relation, cf. def. of \<circle><_|_>.*) abbreviation max :: "\<sigma>\<Rightarrow>\<sigma>" ("max<_>") where "max<\<phi>> \<equiv> (\<lambda>v. ( (\<phi>)(v) \<and> (\<forall>x. ((\<phi>)(x)\<and> x R v \<longrightarrow> v R x))) )" abbreviation tmax :: "\<sigma>\<Rightarrow>\<sigma>" ("tmax<_>") where "tmax<\<phi>> \<equiv> (\<lambda>v. ( (\<phi>)(v) \<and> (\<forall>x. ((\<phi>)(x)\<and> x tc R v \<longrightarrow> v tc R x))) )" abbreviation esubset :: "\<sigma>\<Rightarrow>\<sigma>\<Rightarrow>bool" (infix "\<^bold>\<subseteq>" 53) where "\<phi> \<^bold>\<subseteq> \<psi> \<equiv> \<forall>x. \<phi> x \<longrightarrow> \<psi> x" abbreviation econd :: "\<sigma>\<Rightarrow>\<sigma>\<Rightarrow>\<sigma>" ("\<circle><_|_>") where "\<circle><\<psi>|\<phi>> \<equiv> \<lambda>w. max<\<phi>> \<^bold>\<subseteq> \<psi>" abbreviation euncobl :: "\<sigma>\<Rightarrow>\<sigma>" ("\<^bold>\<circle><_>") where "\<^bold>\<circle><\<phi>> \<equiv> \<circle><\<phi>|\<^bold>\<top>>" abbreviation evalid :: "\<sigma>\<Rightarrow>bool" ("\<lfloor>_\<rfloor>"[8]109) (*Global validity.*) where "\<lfloor>p\<rfloor> \<equiv> \<forall>w. p w" abbreviation ecjactual :: "\<sigma>\<Rightarrow>bool" ("\<lfloor>_\<rfloor>\<^sub>l"[7]105) (*Local validity — in world aw.*) where "\<lfloor>p\<rfloor>\<^sub>l \<equiv> p(aw)" lemma True nitpick [satisfy,user_axioms,expect=genuine] oops (*Consistency conf.*) (*Correspondence theory.*) lemma assumes "\<forall>x y z. x R y \<and> y R z \<longrightarrow> x R z" shows "\<lfloor>((\<circle><\<psi>|\<phi>>) \<^bold>\<and> \<^bold>\<not>(\<circle><\<^bold>\<not>\<xi>|\<phi>>)) \<^bold>\<rightarrow> \<circle><\<psi>|\<phi>\<^bold>\<and>\<xi>>\<rfloor>" using assms by blast oops lemma assumes "\<lfloor>((\<circle><\<psi>|\<phi>>) \<^bold>\<and> \<^bold>\<not>(\<circle><\<^bold>\<not>\<xi>|\<phi>>)) \<^bold>\<rightarrow> \<circle><\<psi>|\<phi>\<^bold>\<and>\<xi>>\<rfloor>" shows "\<forall>x y z. x R y \<and> y R z \<longrightarrow> x R z" nitpick [show_all,format=2] oops (*Countermodel presented by Nitpick.*) end
f1 : Nat f1 = g1 where g1 : Nat g1 = 5 f2 : Nat f2 = g2 where namespace X export g2 : Nat g2 = 5 --f3 : Integer -> Nat --f3 x = g3 where -- namespace Y -- export -- g3 : Nat -- g3 = 4 f4 : Integer -> Nat f4 x = g4 x where namespace Z export g4 : Nat g4 _ = 4
/* * @file * @author University of Warwick * @version 1.0 * * @section LICENSE * * @section DESCRIPTION * */ #define BOOST_TEST_MODULE BarrierMPI #include <boost/test/unit_test.hpp> #include <boost/test/output_test_stream.hpp> #include <stdexcept> #include "BarrierMPI.h" #include "Communicator.h" using namespace cupcfd::comm::mpi; // Setup MPI BOOST_AUTO_TEST_CASE(setup) { int argc = boost::unit_test::framework::master_test_suite().argc; char ** argv = boost::unit_test::framework::master_test_suite().argv; MPI_Init(&argc, &argv); } // === BarrierMPI === // Test 1: Test call returns correctly BOOST_AUTO_TEST_CASE(BarrierMPI_test1) { cupcfd::comm::Communicator comm(MPI_COMM_WORLD); cupcfd::error::eCodes status; status = BarrierMPI(comm.comm); BOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS); } // Cleanup MPI BOOST_AUTO_TEST_CASE(cleanup) { // Cleanup MPI Environment MPI_Finalize(); }
(* Copyright (c) 2013, Louis Parlant and Robbert Krebbers. *) (* This file is distributed under the terms of the BSD license. *) Require Import prelude. Inductive R2 : relation (Stream Z) := | R2_base12 : R2 (Σ@{1,2} #1) nats | R2_base02 : R2 (Σ@{0,2} #1) nats | R2_base2132 : R2 (Σ@{1,2} Σ@{2,3} #1) (nats ^^ 2) | R2_base2031 : R2 (Σ@{0,2} Σ@{1,3} #1) (nats ⊙ (#1 ⊕ nats)) | R2_refl s : R2 s s | R2_plus s1 s2 t1 t2 : R2 s1 t1 → R2 s2 t2 → R2 (s1 ⊕ s2) (t1 ⊕ t2) | R2_eq s1 s2 t1 t2 : s1 ≡ s2 → t1 ≡ t2 → R2 s1 t1 → R2 s2 t2. Instance: Proper (equal ==> equal ==> iff) R2. Proof. now split; apply R2_eq. Qed. Lemma nats_pow_tail : (nats ^^ 2)` ≡ #1 ⊕ nats ⊕ nats ⊙ (#1 ⊕ nats). Proof. rewrite Spow_tail, Sfrom_tail, Spow_S, Spow_1; ring. Qed. Lemma nats_nats_pow_tail : (nats ⊙ (#1 ⊕ nats))` ≡ #1 ⊕ #1 ⊕ nats ⊕ nats ⊕ (nats ⊙ (#1 ⊕ nats)). Proof. rewrite !zip_with_tail, Sfrom_tail, repeat_tail; ring. Qed. Lemma Ssigma2132_tail : (Σ@{1,2} Σ@{2,3} #1)` ≡ #1 ⊕ Σ@{0,2} #1 ⊕ Σ@{0,2} Σ@{1,3} #1. Proof. rewrite !Ssigma_tail_S, Ssigma_head_S, Ssigma_plus, repeat_tail, repeat_head. ring. Qed. Lemma Ssigma2031_tail : (Σ@{0,2} Σ@{1,3}#1)` ≡ #1 ⊕ #1 ⊕ Σ@{0,2} #1 ⊕ Σ@{0,2} #1 ⊕ Σ@{0,2} Σ@{1,3} #1. Proof. rewrite Ssigma_tail_0, Ssigma_tail_S, zip_with_tail, zip_with_head; simpl. rewrite !repeat_head, repeat_tail, Ssigma_tail_0. rewrite !repeat_tail, repeat_head, !Ssigma_plus, repeat_2; simpl. ring. Qed. Lemma bisimulation_R2 : bisimulation R2. Proof. intros s t Hst. split. { induction Hst. * now rewrite Ssigma_head_S. * now rewrite Ssigma_head_0. * now rewrite !Ssigma_head_S. * now rewrite Ssigma_head_0, Ssigma_tail_S, zip_with_head, Ssigma_head_0. * easy. * rewrite !zip_with_head; congruence. * now rewrite <-H, <-H0. } induction Hst. * rewrite Ssigma_tail_S, Sfrom_tail. repeat constructor. * rewrite Ssigma_tail_0, Sfrom_tail. repeat constructor. * rewrite Ssigma2132_tail, nats_pow_tail. repeat constructor. * rewrite Ssigma2031_tail, nats_nats_pow_tail. repeat constructor. * constructor. * simpl. now repeat constructor. * now rewrite <-H, <-H0. Qed. Theorem Moessner_case2 : Σ@{1,2} Σ@{2,3} #1 ≡ nats ^^ 2. Proof. apply (bisimulation_equal _ _ _ bisimulation_R2). constructor. Qed.
C { dg-do compile } PARAMETER (Q=1) PARAMETER (P=10) INTEGER C(10),D(10),E(10),F(10) C TERMINAL NOT INTEGER DATA (C(I),I=1,P) /10*10/ ! { dg-error "End expression in DO loop" "" } C START NOT INTEGER DATA (D(I),I=Q,10) /10*10/ ! { dg-error "Start expression in DO loop" "" } C INCREMENT NOT INTEGER DATA (E(I),I=1,10,Q) /10*10/ ! { dg-error "Step expression in DO loop" "" } END
lemma Complex_divide: "(x / y) = Complex ((Re x * Re y + Im x * Im y) / ((Re y)\<^sup>2 + (Im y)\<^sup>2)) ((Im x * Re y - Re x * Im y) / ((Re y)\<^sup>2 + (Im y)\<^sup>2))"
Require Export CatSem.CAT.cat_TYPE_option. Set Implicit Arguments. Unset Strict Implicit. Unset Automatic Introduction. Notation "^ f" := (lift (M:= option_monad) f) (at level 5). Ltac fin := simpl in *; intros; autorewrite with fin; auto with fin. Hint Unfold lift : fin. Hint Extern 1 (_ = _) => f_equal : fin. Notation "V *" := (option V) (at level 4). Notation "'TT'" := TYPE. Lemma l_eq (V W : TT) (f g : V -> W): (forall v, f v = g v) -> (forall (v : option V), lift (M:=option_monad) f v = ^g v). Proof. intros. destruct v; unfold lift; simpl; auto. rewrite H. auto. Qed. (* Inductive ULC_ (V : Type) : Type := | Var : V -> ULC_ V | Abs : ULC_ (option V) -> ULC_ V | App : ULC_ V -> ULC_ V -> ULC_ V. Definition ULC_d (V : TT) : Type := ULC_ (V tt). Definition ULC (V : TT) : TT := fun _ => ULC_d V. *) Inductive ULC (V : TT) : TT := | Var : V -> ULC V | Abs : ULC V* -> ULC V | App : ULC V -> ULC V -> ULC V. Lemma App_eq V (M M' N N': ULC V) : M = M' -> N = N' -> App M N = App M' N'. Proof. intros. rewrite H. rewrite H0. auto. Qed. Fixpoint rename V W (f : V ---> W) (y : ULC V) : ULC W := match y in ULC _ return ULC W with | Var v => Var (f v) | Abs v => Abs (rename ^f v) | App s t => App (rename f s) (rename f t) end. Definition inj V := rename (V:=V) (W:= V*) (@Some V). (* Definition _shift_tac u (V W : TT) (f : V ---> ULC W) : opt u V ---> ULC (opt u W). simpl. intros. destruct X. apply (inj u). apply f. apply v. apply VAR. apply none. Defined. Print _shift_tac. *) Definition _shift (V W : TT) (f : V ---> ULC W) : V* ---> ULC (W*) := fun v => match v in (option _ ) return ULC (W *) with | Some p => inj (f p) | None => Var None end. Fixpoint _subst V W (f : V ---> ULC W) (y : ULC V) : ULC W := match y in ULC _ return ULC W with | Var v => f v | Abs v => Abs (_subst (_shift f) v) | App s t => App (_subst f s) (_subst f t) end. (* Definition subst_map_tac (u : unit) (V : TT) (M : ULC V u) : opt u V ---> ULC V. simpl. intros u V M t y. destruct y. apply (VAR v). apply M. Defined. Print subst_map_tac. Definition subst_map: forall (u : unit) (V : TT), ULC V u -> V * ---> ULC V := fun (u : unit) (V : unit -> Type) (M : ULC V u) (t : unit) (X : V * t) => match X in (opt _ _ y) return (ULC V y) with | some t0 v => match t0 as u0 return (V u0 -> ULC V u0) with | tt => fun v0 : V tt => Var (V:=V) v0 end v | none => M end. Definition substar (u : unit) (V : TT) (M : ULC V u) : ULC (opt u V) ---> ULC V := _subst (subst_map M). *) Definition substar (V : TT) (M : ULC V) : ULC V* ---> ULC V := _subst (fun y : V* => match y with | None => M | Some v => Var v end). Notation "M [*:= N ]" := (substar N M) (at level 50). (** Notations for functions *) Notation "y //- f" := (rename f y) (at level 42, left associativity). Notation "y >- f" := (_shift f y) (at level 40). Notation "y >>= f" := (_subst f y) (at level 42, left associativity). Lemma rename_eq : forall (V : TT) (v : ULC V) (W : TT) (f g : V ---> W), (forall y, f y = g y) -> v //- f = v //- g. Proof. intros V v. induction v; intros; simpl. rewrite H; auto. apply f_equal. apply IHv. simpl in *. intros. assert (H':= l_eq H y). simpl in *. rewrite <- H'. auto. rewrite (IHv1 _ _ _ H). rewrite (IHv2 _ _ _ H). auto. Qed. Hint Resolve rename_eq l_eq : fin. Hint Rewrite rename_eq l_eq : fin. Lemma rename_comp V (y : ULC V) W (f : V ---> W) Z (g : W ---> Z): y //- (fun y => g (f y)) = y //- f //- g. Proof. intros V y. induction y; simpl; intros; fin. apply f_equal. rewrite <- IHy. apply rename_eq. intros y0. destruct y0; fin. Qed. Lemma rename_id_eq V (y : ULC V) (f : V ---> V) (H : forall v, f v = v) : y //- f = y. Proof. intros V y. induction y; simpl; intros; fin. apply f_equal. apply IHy. intros v; destruct v; fin. unfold lift. fin. Qed. Lemma rename_id V (y : ULC V) : y //- id _ = y . Proof. intros V y. apply rename_id_eq. fin. Qed. Lemma _shift_eq V W (f g : V ---> ULC W) (H : forall v, f v = g v) (y : V*) : y >- f = y >- g. Proof. intros V W f g H v. destruct v; fin. Qed. Hint Resolve rename_id _shift_eq : fin. Hint Rewrite rename_id _shift_eq : fin. Lemma shift_var (V : TT) (y : V*) : y >- @Var V = Var y. Proof. intros V y. induction y; fin. Qed. Hint Resolve shift_var : fin. Hint Rewrite shift_var : fin. Lemma var_lift_shift V W (f : V ---> W) (y : V*) : Var (^f y) = y >- (f ;; @Var _ ). Proof. intros V W f y; induction y; fin. Qed. Hint Resolve var_lift_shift : fin. Lemma shift_lift V W Z (f : V ---> W) (g : W ---> ULC Z) (y : V*) : (^f y) >- g = y >- (f ;; g). Proof. intros V W Z f g y. induction y; fin. Qed. Hint Resolve shift_lift : fin. Hint Rewrite shift_lift : fin. Lemma subst_eq V (y : ULC V) W (f g : V ---> ULC W) (H : forall y, f y = g y): y >>= f = y >>= g. Proof. intros V y. induction y; fin. Qed. Hint Resolve subst_eq : fin. Hint Rewrite subst_eq : fin. Obligation Tactic := unfold Proper; red; fin. Program Instance subst_oid V W : Proper (equiv ==> equiv (Setoid:=mor_oid (ULC V) (ULC W))) (@_subst V W). Lemma subst_var (V : TT) : forall (v : ULC V), v >>= (@Var V) = v . Proof. intros V y. induction y; fin. apply f_equal. rewrite <- IHy at 2. apply subst_eq. fin. Qed. Lemma subst_eq_rename V (v : ULC V) W (f : V ---> W) : v //- f = v >>= (f ;; Var (V:=W)). Proof. intros V y. induction y; fin. apply f_equal. rewrite IHy. apply subst_eq. intros z; destruct z; fin. Qed. Lemma rename_shift V W Z (f : V ---> ULC W) (g : W ---> Z) (y : V*) : (y >- f) //- ^g = y >- (f ;; rename g). Proof. intros V W Z f g y. induction y; fin. unfold inj. rewrite <- rename_comp. rewrite <- rename_comp. fin. Qed. Hint Rewrite rename_shift : fin. Hint Resolve rename_shift : fin. Hint Unfold inj : fin. Lemma rename_subst V (v : ULC V) W Z (f : V ---> ULC W) (g : W ---> Z) : (v >>= f) //- g = v >>= (f ;; rename g). Proof. intros V y. induction y; fin. rewrite IHy. apply f_equal. apply subst_eq. intros z; destruct z; simpl; auto. unfold inj. rewrite <- rename_comp. rewrite <- rename_comp. apply rename_eq. fin. Qed. Lemma subst_rename V (v : ULC V) W Z (f : V ---> W) (g : W ---> ULC Z) : v //- f >>= g = v >>= (f ;; g). Proof. intros V y. induction y; fin. apply f_equal. rewrite IHy. apply subst_eq. intros z; destruct z; fin. Qed. Lemma rename_substar V (v : ULC V*) W (f : V ---> W) N: v [*:= N] //- f = (v //- ^f) [*:= N //- f ]. Proof. intros. unfold substar. rewrite rename_subst. rewrite subst_rename. apply subst_eq. intros z ; destruct z ; fin. Qed. Hint Rewrite subst_rename rename_subst : fin. Hint Rewrite rename_shift : fin. Hint Resolve rename_shift : fin. Lemma subst_shift_shift V (v : V*) W Z (f: V ---> ULC W) (g: W ---> ULC Z): (v >- f) >>= (_shift g) = v >- (f ;; _subst g). Proof. intros V v. induction v; simpl; intros; try apply subst_term_inj; auto. unfold inj. rewrite subst_rename. fin. Qed. Hint Resolve subst_shift_shift : fin. Hint Rewrite subst_shift_shift : fin. Lemma subst_subst V (v : ULC V) W Z (f : V ---> ULC W) (g : W ---> ULC Z) : v >>= f >>= g = v >>= (f;; _subst g). Proof. intros V y. induction y; fin. apply f_equal. rewrite IHy. apply subst_eq. intros z; destruct z; fin. unfold inj. fin. Qed. Lemma lift_rename V (s : ULC V) W (f : V ---> W) : s >>= (fun z => Var (f z)) = s //- f. Proof. intros V y. induction y; fin. apply f_equal. rewrite <- IHy. apply subst_eq. intros z; destruct z; fin. Qed. Lemma rename_rename V W Z (f : V ---> W) (g : W ---> Z) (v : ULC V) : v //- f //- g = v //- (f ;; g). Proof. intros. repeat rewrite <- lift_rename. rewrite subst_subst. fin. Qed. Lemma subst_var_eta (V:TT) (v:ULC V): v >>= (fun z => Var z) = v. Proof. induction v; intros; simpl; auto. rewrite <- IHv at 2. apply f_equal. apply subst_eq. intros; apply shift_var. rewrite IHv1. rewrite IHv2; auto. Qed. Lemma subst_substar (V W : TT) (M: ULC V*) (N:ULC V) (f : V ---> ULC W): M [*:=N] >>= f = (M >>= _shift f) [*:= (N >>= f)]. Proof. intros V W M N f. unfold substar. simpl. repeat rewrite subst_subst. apply subst_eq. intros y. simpl. destruct y. unfold _shift. unfold inj. simpl. rewrite subst_rename. simpl. assert (H:=subst_var_eta (f v)). simpl in *. rewrite <- H at 1. apply subst_eq. auto. auto. Qed. Hint Resolve subst_var subst_subst lift_rename : fin. Hint Rewrite subst_subst lift_rename: fin.
(* -*- mode: coq -*- *) (* Time-stamp: <2014/8/23 13:4:32> *) (* binsearch.v - mathink : Author *) (* SSReflect libraries *) Require Import Ssreflect.ssreflect Ssreflect.ssrbool Ssreflect.ssrfun Ssreflect.ssrnat Ssreflect.eqtype Ssreflect.seq. Require Import MathComp.path. Require Import Adlibssr.btree Adlibssr.sorted Adlibssr.order. (* Implicity *) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. (** ** Binary Search Tree *) (* Aux *) Definition flip {X Y Z: Type}(f: X -> Y -> Z): Y -> X -> Z := fun y x => f x y. Arguments flip X Y Z f / y x. Inductive btR {T}(R: T -> T -> Prop)(a: T): btree T -> Prop := | btR_bleaf: btR R a # | btR_bnode: forall x tl tr, R a x -> btR R a tl -> btR R a tr -> btR R a (tl -< x >- tr). Hint Constructors btR. Lemma btRP {T}(R: T -> T -> Prop) ord a t: (forall x y, reflect (R x y) (ord x y)) -> reflect (btR R a t) (all (ord a) t). Proof. move=> ordP. elim: t => [//=|/= x tl IHl tr IHr]; first by left. move: IHl IHr => [Hl | Hnl] /= [Hr | Hnr] /=; rewrite ?andbT ?andbF; try (right; move=> Hb). - case: (ordP a x) => [HR | HnR]; [left; apply btR_bnode=> //| right]. move=> Hb; apply HnR; inversion Hb => //. - apply Hnr; inversion Hb => //. - apply Hnl; inversion Hb => //. - apply Hnr; inversion Hb => //. Qed. Section BinarySearchTree. Variables (T: eqType) (le: T -> T -> Prop) (ord: totalOrder T). Notation "x <= y" := (le x y). Hypothesis (ordP: forall x y, reflect (x <= y) (ord x y)). Lemma ordP' x y: reflect (flip le x y) (ord^~ x y). Proof. simpl; apply ordP. Qed. Implicit Types (t: btree T)(s: seq T). Inductive isBst: btree T -> Prop := | isBst_bleaf: isBst # | isBst_bnode: forall x tl tr, isBst tl -> btR (flip le) x tl -> isBst tr -> btR le x tr -> isBst (tl -< x >- tr). Hint Constructors isBst. Fixpoint bst t: bool := if t is tl -< x >- tr then (bst tl) && (all (flip ord x) tl) && (bst tr) && (all (ord x) tr) else true. Functional Scheme bst_ind := Induction for bst Sort Prop. Lemma bstP t: reflect (isBst t) (bst t). Proof. elim: t => [//=|/= x tl IHl tr IHr]; first by left. move: IHl IHr => [Hbl | Hnbl] [Hbr | Hnbr] /=. - rewrite andbT. case: (btRP x tl ordP') => Hal /=; last by right; move=> Hb; apply Hal; inversion Hb. case: (btRP x tr ordP) => Har /=; last by right; move=> Hb; apply Har; inversion Hb. by left; apply isBst_bnode => //. - by rewrite andbF /=; right; move=> Hb; apply Hnbr; inversion Hb. - by right; move=> Hb; apply Hnbl; inversion Hb. - by right; move=> Hb; apply Hnbl; inversion Hb. Qed. Lemma bst_bnode x tl tr: bst (tl -< x >- tr) = (bst tl) && (all (flip ord x) tl) && (bst tr) && (all (ord x) tr). Proof. by []. Qed. Lemma all_revtree p t: all p (revtree t) = all p t. Proof. elim: t => [//=|/= x tl -> tr ->]. by rewrite andbAC. Qed. Lemma sorted_walk_bst t s: sorted ord (walk t s) = (bst t) && (sorted ord s) && (all (fun x => seq.all (ord x) s) t). Proof. elim/walk_ind: t s /(walk t s)=> t s; first by rewrite andbT. move=> x tl tr _ Heqr ->. rewrite sorted_cons1 // Heqr /= ?andbA /=. case (bst tl) => //=. case (bst tr) => //=; rewrite /= ?andbT ?andbF //. case (all (fun x0 : T => seq.all (ord x0) s) tr); rewrite /= ?andbT ?andbF //. case (sorted ord s) => //=; rewrite /= ?andbT ?andbF //. case Hta: (all (fun x0 : T => ord x0 x && seq.all (ord x0) (walk tr s)) tl). - move: Hta => /eqP; rewrite eqb_id andbT /= => /allP Hta. case Hsa: (seq.all (ord x) (walk tr s)). move: Hsa => /eqP; rewrite eqb_id => /seq.allP Hsa. + apply esym; apply/eqP; rewrite eqb_id -!andbA; apply/and4P; split. * by apply/allP=> y Hin; move: (Hta _ Hin) => /andP [] //. * by apply/allP=> y Hin; apply Hsa; rewrite mem_walk; apply/orP; left. * by apply/seq.allP=> y Hin; apply Hsa; rewrite mem_walk; apply/orP; right. * apply/allP=> y Hiny; apply/seq.allP=> z Hinz. move: (Hta _ Hiny) => /andP [] _ /seq.allP; apply. by rewrite mem_walk; apply/orP; right. + apply esym; apply/eqP; rewrite eqbF_neg; apply/negP => H. move: Hsa => /eqP; rewrite eqbF_neg => /negP; apply. move: H; rewrite -!andbA => /and4P [/allP Hal /allP Har /seq.allP Has /allP Hsal]. apply/seq.allP=> y; rewrite mem_walk => /orP [Hin | Hin]. * by apply Har. * by apply Has. - rewrite andbF /=; apply esym; apply/eqP; rewrite eqbF_neg -!andbA; apply/negP => /and4P [/allP Hal /allP Har /seq.allP Has /allP Hsal]. move: Hta => /eqP; rewrite eqbF_neg => /negP; apply. apply/allP=> y Hin; apply/andP; split; first by apply Hal. apply/seq.allP => z; rewrite mem_walk => /orP [Hinr | Hins]. + apply ord_transitive with x. * by apply Hal. * by apply Har. + by move: (Hsal _ Hin) => /seq.allP; apply. Qed. Lemma all_predT t: all predT t. Proof. by elim: t => [//=|/= x tl -> tr ->]. Qed. Lemma sorted_bst t: sorted ord (flatten t) = bst t. Proof. by rewrite sorted_walk_bst /= andbT all_predT andbT. Qed. Section Operations. Fixpoint search a t: bool := if t is tl -< x >- tr then if a == x then true else if ord! a x then search a tl else search a tr else false. Functional Scheme search_ind := Induction for search Sort Prop. Lemma bst_search_aux a t: (a \in t) && (bst t) -> search a t. Proof. elim: t => [//= |/= x tl IHl tr IHr]. rewrite in_bnode. case: (a =P x) => [<- | /eqP /negbTE Hneq] //=. rewrite -!andbA. move=> /andP [/orP [Hinl | Hinr] /and4P [Hbstl /allP Halll Hbstr /allP Hallr]]. - move: (Halll _ Hinl) => /=; rewrite /strict_ord Hneq andbT => ->. by apply IHl; apply/andP. - move: (Hallr _ Hinr) => /=; rewrite -ord_neg_sord => -> /=. by apply IHr; apply/andP. (* functional induction (search a t) => //=; *) (* rewrite in_bnode -!orbA -!andbA e0 /=; *) (* move=>/and4P [/orP [Hin | Hin] Hbl Hal /andP [Hbr Har]]; *) (* apply IHb; apply/andP; split=> //. *) (* - by move: Har => /allP Har; move: (Har a Hin); *) (* rewrite -sord_neg_ord e1 //. *) (* - by move: Hal => /allP Hal; move: e1 (Hal a Hin) =>/eqP; rewrite eqbF_neg /strict_ord negb_and e0 orbF/= -eqbF_neg => /eqP->//. *) Qed. Lemma bst_search a t: bst t -> (a \in t) = (search a t). Proof. move=> Hbst. case Hin: (a \in t). - by apply esym; apply bst_search_aux; apply/andP. - move: {Hbst} Hin; elim: t => [//=|/= x tl IHl tr IHr]. rewrite in_bnode. case: (a =P x) => [Heq | Hneq] //=. move/negbT; rewrite negb_or =>/andP [/negbTE/IHl<- /negbTE/IHr<-]. by rewrite if_same. Qed. Fixpoint insert a t: btree T := if t is tl -< x >- tr then if ord! a x then (insert a tl) -< x >- tr else tl -< x >- (insert a tr) else #-< a >-#. Functional Scheme insert_ind := Induction for insert Sort Prop. Lemma mem_insert a b t: b \in (insert a t) = (b == a) || (b \in t). Proof. by functional induction (insert a t) as [| _ x tl tr _ _ IH | _ x tl tr _ _ IH] => //; rewrite !in_bnode /= IH orbCA -!orbA. Qed. Lemma all_insert p a t: all p (insert a t) = p a && all p t. Proof. by functional induction (insert a t) as [| _ x tl tr _ Hord IH | _ x tl tr _ Hord IH] => //=; rewrite ?andbT // IH andbCA -!andbA. Qed. Lemma bst_bst_insert a t: bst t -> bst (insert a t). Proof. functional induction (insert a t) as [| _ x tl tr _ Hord IH | _ x tl tr _ Hord IH] => //=; rewrite -!andbA all_insert; [ move=> /and4P [/IH-> -> -> ->] | move=> /and4P [-> -> /IH-> ->]]; rewrite /= !andbT //. - by move: Hord=>/eqP; rewrite eqb_id=>/andP []//. - by rewrite -sord_neg_ord Hord. Qed. Lemma bst_insert_bst a t: bst (insert a t) -> bst t. Proof. by functional induction (insert a t) as [| _ x tl tr _ Hord IH | _ x tl tr _ Hord IH] => //=; rewrite -!andbA all_insert; [ move=> /and4P [/IH-> /andP [Ho ->] -> ->] | move=> /and4P [-> -> /IH-> /andP [Ho ->]]]. Qed. Lemma bst_insert a t: bst t = bst (insert a t). Proof. case H: (bst t). - by apply esym; apply bst_bst_insert. - apply esym; apply/negbTE; move: H => /negbT; apply contraL. by move=> Hbst; apply/negPn; apply bst_insert_bst with a. Qed. Lemma in_insert a t: a \in insert a t. Proof. by functional induction (insert a t) as [| _ x tl tr _ Hord IH | _ x tl tr _ Hord IH] => //=; rewrite ?mem_bnode1 ?in_bnode //= IH orbT //. Qed. Lemma search_insert a t: bst t -> search a (insert a t). Proof. by move=> Hbst; rewrite -bst_search; [apply: in_insert | apply: bst_bst_insert]. Qed. (* Sorting by using binary-search tree *) Fixpoint btsort_insert s t: btree T := if s is h :: s' then btsort_insert s' (insert h t) else t. Functional Scheme btsort_insert_ind := Induction for btsort_insert Sort Prop. Definition btsort s := flatten (btsort_insert s #). Lemma btsort_insert_bst s t: bst t -> bst (btsort_insert s t). Proof. by functional induction (btsort_insert s t) => //=; move=> Hbst; apply IHb; move: Hbst; apply bst_bst_insert. Qed. Lemma btsort_sorted s: sorted ord (btsort s). Proof. by rewrite /btsort sorted_bst; apply btsort_insert_bst. Qed. Lemma insert_count a t p: count p (insert a t) = (p a + count p t)%nat. Proof. by functional induction (insert a t) as [| _ x tl tr _ Hord IH | _ x tl tr _ Hord IH] => //=; rewrite IH addnCA -!addnA. Qed. Lemma btsort_insert_count s t p: (seq.count p s + count p t)%nat = count p (btsort_insert s t). Proof. by functional induction (btsort_insert s t) => //=; rewrite -IHb insert_count addnCA addnA. Qed. Lemma btsort_insert_perm s t: perm_eq (s ++ flatten t) (flatten (btsort_insert s t)). Proof. apply/perm_eqP=> p /=. by functional induction (btsort_insert s t) => //=; rewrite -IHb ?count_cat ?flatten_count insert_count addnCA. Qed. Lemma btsort_perm_eq s: perm_eq s (btsort s). Proof. by eapply perm_eq_trans; [| apply btsort_insert_perm]; rewrite cats0. Qed. Definition sorting f := forall s, perm_eq s (f s) /\ sorted ord (f s). Theorem btsort_sorting: sorting btsort. Proof. by split; [apply btsort_perm_eq | apply btsort_sorted]. Qed. (* lend & rend with bst *) Lemma bst_lend a t: bst t -> all (ord a) t -> all (ord (lend a t)) t. Proof. rewrite -!flatten_all -sorted_bst -head_flatten_lend. remember (flatten t) as l. clear Heql t. case: l a => [//=| h l] a. rewrite sorted_cons1 // => /=. move=> /andP [Hordah Hallal] /andP [Hallhl Hsorted]. by apply/andP; split; first apply ord_reflexive. Qed. Lemma bst_rend a t: all (flip ord a) t -> bst t -> all (flip ord (rend t a)) t. Proof. rewrite -!flatten_all -sorted_bst -rend_flatten_rhead. remember (flatten t) as l. clear Heql t. case: l a => [//=| h l] a. rewrite sorted_cons1 // => /=. move=> /andP [Hordah Hallal] /andP [Hallhl Hsorted]. apply/andP; split. - move: (mem_last h l); rewrite in_cons => /orP [/eqP->|Hin]; first by apply ord_reflexive. by move: Hallhl => /seq.allP Hallhl; apply Hallhl. - move: Hallhl Hsorted => {a} {Hordah} {Hallal}. elim: l h => [//=| h' l IHl] h. rewrite sorted_cons1 // => /=. move=> /andP [Hordhh' Hallhl] /andP [Hallh'l Hsorted]. apply/andP; split. + move: (mem_last h' l); rewrite in_cons => /orP [/eqP->|Hin]; first by apply ord_reflexive. by move: Hallh'l => /seq.allP Hallh'l; apply Hallh'l. + by apply IHl. Qed. Fixpoint delete_l a t: btree T := if t is tl -< x >- tr then if a == x then rem_root_r t else if ord! a x then (delete_l a tl) -< x >- tr else tl -< x >- (delete_l a tr) else #. Functional Scheme delete_l_ind := Induction for delete_l Sort Prop. Lemma bst_lend_remove a t: bst t -> bst (lend_remove a t).2. Proof. rewrite -!sorted_bst flatten_lend_remove_behead. remember (flatten t) as l. clear Heql t. case: l => [//=| h l] . by rewrite sorted_cons1 // /= => /andP [Hord Hsorted]. Qed. Lemma bst_rend_remove t a: bst t -> bst (rend_remove t a).1. Proof. rewrite -!sorted_bst flatten_rend_remove_rbehead. remember (flatten t) as l. clear Heql t. elim: l => [//=| h l] . rewrite sorted_cons1 //. elim: l => [//=| h' l IHl]. move=> IH /andP [Hall Hsorted]. rewrite rbehead_cons sorted_cons1 //. apply /andP; split. - move: Hall => {IHl Hsorted} /seq.allP H. apply /seq.allP => x Hin; apply H. by apply mem_rbehead. - by apply IH. Qed. Lemma bst_rem_root_r t: bst t -> bst (rem_root_r t). Proof. elim: t => [//=|/= x tl IHl tr IHr]. remember (rend_remove tl x). case: p Heqp => t node Heq /=. rewrite -!andbA => /and4P [Hbl Hal -> Har] /=. move: (bst_rend_remove x Hbl); rewrite -Heq/= => -> /=. apply/andP; split. - apply/allP => y Hin. move: (rend_remove_rend tl x); rewrite -Heq => /= ->. move: (bst_rend Hal Hbl) => /allP; apply. by move: (@mem_rend_remove _ y tl x); rewrite -Heq; apply. - apply/allP => y Hin. move: (rend_remove_rend tl x) (mem_rend tl x); rewrite -Heq => /= <- /orP [/eqP->|Hin']. + by move: Har => /allP; apply. + apply ord_transitive with x. * by move: Hal => /allP; apply. * by move: Har => /allP; apply. Qed. Lemma all_delete_l p a t: all p t -> all p (delete_l a t). Proof. functional induction (delete_l a t) => //=; rewrite -!andbA. - remember (rend_remove tl x) as tn. case: tn Heqtn => t node Heq /= /and3P [Hp /allP Hal ->]; rewrite andbT. + apply/andP; split. * by move: (rend_remove_rend tl x) (mem_rend tl x); rewrite -Heq/= => <- /orP [/eqP->//|Hin]; apply Hal. * by apply/allP=> y Hin; apply Hal; apply mem_rend_remove with x; rewrite -Heq. - by move=> /and3P [-> /IHb-> ->]. - by move=> /and3P [-> -> /IHb->]. Qed. Lemma bst_delete_l a t: bst t -> bst (delete_l a t). Proof. elim: t => [//=| x tl IHl tr IHr]. move=> Hbst; move: (Hbst) => /bst_rem_root_r H /=. case: (a =P x) => [Heq | Hneq]; first done. move: Hbst => /=; rewrite -!andbA => /and4P [Hbl Hal Hbr Har]. case Hord: (ord! a x) => /=. - rewrite -!andbA; apply/and4P; split; try done. + by apply: IHl. + by apply: all_delete_l. - rewrite -!andbA; apply/and4P; split; try done. + by apply: IHr. + by apply: all_delete_l. Qed. (* I want to prove them *) Lemma mem_delete_l x a t: x \in (delete_l a t) -> x \in t. Proof. elim: t x => [//=| y tl IHl tr IHr /=] x. case: (a =P y) => [<-{y} | /eqP Hneq]. - remember (rend_remove tl a). move: p Heqp => [tl' node] Heq. rewrite in_bnode -orbA => /or3P [/eqP-> | Hin | Hin]. + move: (mem_rend tl a); rewrite -rend_remove_rend -Heq /=. by move=> H; rewrite in_bnode; apply/orP; left. + rewrite in_bnode -orbA; apply/or3P; apply Or32. by move: (@mem_rend_remove _ x tl a); rewrite -Heq /=; apply. + by rewrite in_bnode -orbA; apply/or3P; apply Or33. - rewrite /strict_ord Hneq andbT. case Hord: (ord a y); rewrite !in_bnode -!orbA => /or3P [Heq | Hin | Hin]; apply/or3P; try (by apply Or33); try (by apply Or32); try (by apply Or31). + by apply Or32; apply: IHl. + by apply Or33; apply: IHr. Qed. Lemma delete_l_eq a t: (a \notin t) -> (delete_l a t == t). Proof. elim: t a => [//=|/= x tl IHl tr IHr] a. - rewrite in_bnode // !negb_or -!andbA => /and3P [/negbTE-> /IHl/eqP-> /IHr/eqP->]. by rewrite if_same. Qed. Lemma size_delete_l a t: (size (delete_l a t) < size t)%nat -> a \in t. Proof. apply contraTT => Hnin. move: (delete_l_eq Hnin) => /eqP->. by rewrite ltnn. Qed. Fixpoint delete_r t a: btree T := if t is tl -< x >- tr then if a == x then rem_root_l t else if ord! a x then (delete_r tl a) -< x >- tr else tl -< x >- (delete_r tr a) else #. Lemma mem_lend_remove x a t: x \in (lend_remove a t).2 -> x \in t. Proof. rewrite -{1}[t]revtree_involutive lend_remove_revtree swap_app_fst /= mem_revtree. by move=> /mem_rend_remove Hin; rewrite -mem_revtree. Qed. Lemma all_delete_r p t a: all p t -> all p (delete_r t a). Proof. elim: t => [//=|/= x tl IHl tr IHr]. case: (a =P x) => [<-{x}|Hneq]; rewrite -!andbA => /and3P [Hp Hal Har]. - remember (lend_remove a tr). case: p0 Heqp0 => t x Heq /=. rewrite -!andbA; apply/and3P; split; try done. + move: (lend_remove_lend a tr) (mem_lend a tr); rewrite -Heq /= => <- /orP [/eqP->//|Hin]. by move: Har => /allP; apply. + apply/allP => y Hin. move: Har => /allP; apply. by move: (@mem_lend_remove y a tr); rewrite -Heq; apply. - case: (ord! a x) => /=; rewrite -!andbA; apply/and3P; split; try done. + by apply IHl. + by apply IHr. Qed. Lemma bst_rem_root_l t: bst t -> bst (rem_root_l t). Proof. elim: t => [//=|/= x tl IHl tr IHr]. rewrite -!andbA => /and4P [Hbl Hal Hbr Har]. remember (lend_remove x tr). case: p Heqp => node t Heq /=. rewrite -!andbA; apply/and4P; split; try done. - apply/allP => y Hin. move: (lend_remove_lend x tr) (mem_lend x tr); rewrite -Heq => /= <- /orP [/eqP->|Hin']. + by move: Hal => /allP; apply. + apply ord_transitive with x. * by move: Hal => /allP; apply. * by move: Har => /allP; apply. - by move: (bst_lend_remove x Hbr); rewrite -Heq. - apply/allP => y Hin. move: (lend_remove_lend x tr); rewrite -Heq => /= ->. move: (bst_lend Hbr Har) => /allP; apply. by move: (@mem_lend_remove y x tr); rewrite -Heq; apply. Qed. Lemma bst_delete_r t a: bst t -> bst (delete_r t a). Proof. elim: t => [//=| x tl IHl tr IHr]. move=> Hbst; move: (Hbst) => /bst_rem_root_l H /=. case: (a =P x) => [Heq | Hneq]; first done. move: Hbst => /=; rewrite -!andbA => /and4P [Hbl Hal Hbr Har]. case Hord: (ord! a x) => /=. - rewrite -!andbA; apply/and4P; split; try done. + by apply: IHl. + by apply: all_delete_r. - rewrite -!andbA; apply/and4P; split; try done. + by apply: IHr. + by apply: all_delete_r. Qed. Lemma mem_delete_r x t a: x \in (delete_r t a) -> x \in t. Proof. elim: t x => [//=| y tl IHl tr IHr /=] x. case: (a =P y) => [<-{y} | /eqP Hneq]. - remember (lend_remove a tr). move: p Heqp => [node tr'] Heq. rewrite in_bnode -orbA => /or3P [/eqP-> | Hin | Hin]. + move: (mem_lend a tr); rewrite -lend_remove_lend -Heq /=. by move=> H; rewrite in_bnode -orbAC; apply/orP; left. + by rewrite in_bnode -orbA; apply/or3P; apply Or32. + rewrite in_bnode -orbA; apply/or3P; apply Or33. by move: (@mem_lend_remove x a tr); rewrite -Heq /=; apply. - rewrite /strict_ord Hneq andbT. case Hord: (ord a y); rewrite !in_bnode -!orbA => /or3P [Heq | Hin | Hin]; apply/or3P; try (by apply Or33); try (by apply Or32); try (by apply Or31). + by apply Or32; apply: IHl. + by apply Or33; apply: IHr. Qed. Lemma delete_r_eq t a: (a \notin t) -> (delete_r t a == t). Proof. elim: t a => [//=|/= x tl IHl tr IHr] a. - rewrite in_bnode // !negb_or -!andbA => /and3P [/negbTE-> /IHl/eqP-> /IHr/eqP->]. by rewrite if_same. Qed. Lemma size_delete_r t a: (size (delete_r t a) < size t)%nat -> a \in t. Proof. apply contraTT => Hnin. move: (delete_r_eq Hnin) => /eqP->. by rewrite ltnn. Qed. End Operations. End BinarySearchTree. (* Eval compute in (btsort (fun x y => x < y) [::3;1;4;1;5;9;2;6]). *) (* = [:: 1; 1; 2; 3; 4; 5; 6; 9] *) (* : seq nat_eqType *) (* Definition tb := ((# -< 1 >- # -< 2 >- (# -< 3 >- #)) -< 4 >- (# -< 5 >- #)). *) (* Eval compute in (delete (fun x y => x < y) 4 tb). *) (* Eval compute in (rend_remove 6 tb). *) (* Eval compute in (lend_remove 0 (lend_remove 0 tb).2). *)
function gh17797(f, y) result(r) external f integer(8) :: r, f integer(8), dimension(:) :: y r = f(0) r = r + sum(y) end function gh17797
function [h,g,a,info] = wfilt_oddevena(N) %WFILT_ODDEVENA Kingsbury's symmetric even filters % % Usage: [h,g,a] = wfilt_oddevena(N); % % `[h,g,a]=wfilt_oddevena(N)` with $N \in {1}$ returns Kingsbury's % even filters. % % Examples: % --------- % ::: % figure(1); % wfiltinfo('ana:oddevena1'); % % figure(2); % wfiltinfo('syn:oddevena1'); % % References: king02 % AUTHOR: Zdenek Prusa info.istight = 0; a = [2;2]; switch(N) case 1 % Example 1. from the reference. Symmetric near-orthogonal garr = [ 0 0 0 0 0 -0.0004645 0 0.0013349 -0.0058109 0.0022006 0.0166977 -0.0130127 -0.0000641 0.0015360 -0.0834914 0.0869008 0.0919537 0.0833552 0.4807151 -0.4885957 0.4807151 0.4885957 0.0919537 -0.0833552 -0.0834914 -0.0869008 -0.0000641 -0.0015360 0.0166977 0.0130127 -0.0058109 -0.0022006 0 -0.0013349 0 0.0004645 0 0 0 0 ]; % This scaling is not in the reference paper, but it is here to be % consistent garr = garr*sqrt(2); %garr = setnorm(garr,'energy'); offset = -10; otherwise error('%s: No such filters.',upper(mfilename)); end %garr = [garr(:,3:4),garr(:,1:2)]; modrange = (-1).^((0:size(garr,1)-1) + offset+1).'; modrange2 = (-1).^((0:size(garr,1)-1) + offset).'; harr = [garr(:,2).*modrange2,... garr(:,1).*modrange,... ]; % In the biorthogonal case, the filters do not get time reversed garr = flipud(garr); htmp=mat2cell(harr,size(harr,1),ones(1,size(harr,2))); h = cellfun(@(hEl)struct('h',hEl,'offset',offset),htmp(1:2),... 'UniformOutput',0); gtmp=mat2cell(garr,size(garr,1),ones(1,size(garr,2))); g = cellfun(@(gEl)struct('h',gEl,'offset',offset),gtmp(1:2),... 'UniformOutput',0);
lemma simply_connected_empty [iff]: "simply_connected {}"
function [img, nSamples] = ellipseInterior(varargin) % Return an image (matrix) marking the interior of an ellipse % % Syntax % [img, nSamples] = ellipseInterior(varargin) % % Inputs % N/A % % Optional key/value pairs % center - Center of the ellipse % sigma - Sigma major and minor as a 2-vector % theta - Angle of sigma major from the x-axis (counter clockwise) % % Returns % img: 1 in the interior and 0 in the exterior % nSamples: Number of interior samples % % Description % We start with an ellipse with its major axis aligned to the % x-axis. We then rotate (counter clockwise) by an amount theta. % % This is the equation for the contour of the ellipse % % 1 = A*(x-h)^2 + 2B*(x-h)*(y-k) + C*(y-k)^2 % % The quadratic form is Q = [A B; B C]; % We test that the parameters are valid (i.e., Q is positive-definite % (i.e., Q = M*M') by % % A > 0 % det(Q) > 0 % % We convert from sigma(1), sigma(2), theta to Q and inversely using % % Q = Rotate(theta)'*[diag(a^2,b^2)]*Rotate(theta) %{ % [U,S,V] = svd(Q) % Figure out theta from U and get a, b from sqrt(S) % Since % rotMat = [cos(theta) -sin(theta); -sin(theta) -cos(theta)]; % theta = acos(U(1,1)) % % Some experimenting % % It must be a > b for major/minor axes a = 3; b = 2; theta = pi/6; rotMat = [cos(theta) -sin(theta); -sin(theta) -cos(theta)]; Q = rotMat' * diag([a^2, b^2]) * rotMat; [U,S,V] = svd(Q); abs(U) - abs(rotMat) % Not sure why there can be a sign difference thetaEst = min(acos(U(1,1)),acos(-1*U(1,1))); theta - thetaEst %} % % Notes: % % https://math.stackexchange.com/questions/264446/the-fastest-way-to-obtain-orientation-%CE%B8-from-this-ellipse-formula % % Wandell, January 13 2020 % % See also % ellipsePlot() % Examples: %{ img = ellipseInterior; mrvNewGraphWin; imagesc(img); axis equal %} %{ samples = [-3:0.1:3]; [img, nSamples] = ellipseInterior('center',[1 2],'spatial samples',samples); [img2, nSamples] = ellipseInterior('center',[0.5 2],'spatial samples',samples); % mrvNewGraphWin; imagesc(img); axis image % mrvNewGraphWin; imagesc(img2); axis image overlap = dot(img(:), img2(:))/nSamples; fprintf('Overlap is %f\n',overlap); %} %{ samples = [-10:0.1:10]; sigma = [3,1]; [img, nSamples] = ellipseInterior('center',[0 0],'sigma',sigma,'spatial samples',samples); [img2, nSamples] = ellipseInterior('center',[-1 -4],'sigma',sigma,'spatial samples',samples); mrvNewGraphWin; imagesc(samples,samples,img); axis image mrvNewGraphWin; imagesc(samples,samples,img2); axis image overlap = dot(img(:), img2(:))/nSamples; fprintf('Overlap is %f\n',overlap); %} %{ img = ellipseInterior('center',[1 1],'quadratic',0.3*eye(2)); mrvNewGraphWin; imagesc(img); %} %% Input parameters varargin = mrvParamFormat(varargin); p = inputParser; p.addParameter('center',[0 0],@isvector); p.addParameter('spatialsamples',(-3:0.05:3),@isvector); vFunc = @(x)(length(x) == 2 && x(1) >= x(2) && isnumeric(x)); p.addParameter('sigma',[1 1],vFunc); % Length in degrees p.addParameter('theta',0,@isvector); % Radians p.parse(varargin{:}); c = p.Results.center; samples = p.Results.spatialsamples; sigma = p.Results.sigma; theta = p.Results.theta; %% Test that we have a true ellipse formula rotMat = [cos(theta) -sin(theta); -sin(theta) -cos(theta)]; Q = rotMat' * diag([1/sigma(1)^2, 1/sigma(2)^2]) * rotMat; if Q(1,1) <= 0 || det(Q) <= 0 || Q(1,2) ~= Q(2,1) error('Q is not positive definite'); end %% Create the spatial samples and compute the values [X,Y] = meshgrid(samples,samples); X = X - c(1); Y = Y - c(2); V = Q(1,1)*X.^2 + 2*Q(1,2)*X.*Y + Q(2,2)*Y.^2; % mrvNewGraphWin; mesh(V) %% Binarize img = zeros(size(X)); img(V<=1) = 1; % mrvNewGraphWin; imagesc(img) if nargout > 1 nSamples = sum(img(:)); end end
import random import math import numpy as np import torch import argparse import time import os from reformer_lib.reformer_pytorch import ReformerLM,ReformerLM_tune from reformer_lib.generative_tools import TrainingWrapper from torch.utils.tensorboard import SummaryWriter from torch.nn.parallel import DistributedDataParallel as DDP try: # from apex.parallel import DistributedDataParallel as DDP from apex.fp16_utils import * from apex import optimizers from apex.multi_tensor_apply import multi_tensor_applier except ImportError: raise ImportError("This code requires APEX") seed=17 torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # if you are using multi-GPU. np.random.seed(seed) # Numpy module. random.seed(seed) # Python random module. torch.manual_seed(seed) torch.backends.cudnn.benchmark = False torch.backends.cudnn.deterministic = True parser = argparse.ArgumentParser() parser.add_argument('--dataset', type=str, default="synthetic") parser.add_argument('--seq_len', type=int, default=1024) parser.add_argument('--min_seq_len', type=int, default=4) parser.add_argument('--ntokens', type=int, default=16) parser.add_argument('--emsize', type=int, default=256) parser.add_argument('--nhid', type=int, default=256) parser.add_argument('--nlayers', type=int, default=2) parser.add_argument('--nhead', type=int, default=4) parser.add_argument('--bucket_size_list', nargs='+', type=int, default=[64, 64]) parser.add_argument('--n_hashes_list', nargs='+', type=int, default=[1, 1]) parser.add_argument('--attn_type_list', nargs='+', default=['triplet', 'triplet']) parser.add_argument('--dropout', type=float, default=0.05) parser.add_argument('--batch_size', type=int, default=16) parser.add_argument('--full_attn_thres', type=int, default=0) parser.add_argument('--lr_main', type=float, default=1e-3) parser.add_argument('--lr_tri', type=float, default=1e-3) parser.add_argument('--tri_alpha', type=float, default=1.0) parser.add_argument('--use_full_attn', action='store_true') parser.add_argument('--log', action='store_false') parser.add_argument('--epochs', type=int, default=30) parser.add_argument('--train_batches', type=int, default=5000) parser.add_argument('--eval_batches', type=int, default=500) parser.add_argument('--print_loss', type=int, default=500) parser.add_argument('--note', type=str, default='') parser.add_argument('--scheduler_hashes', type=int, default=10) parser.add_argument('--thresh', type=float, default=0.01) parser.add_argument('--local_rank', type=int, default=0) GRADIENT_ACCUMULATE_EVERY = 1 args = parser.parse_args() args.distributed = False if 'WORLD_SIZE' in os.environ: args.distributed = int(os.environ['WORLD_SIZE']) > 1 args.gpu = 0 args.world_size = 1 if args.distributed: rank = int(os.environ['RANK']) num_gpus = torch.cuda.device_count() gpu_id = rank % num_gpus torch.cuda.set_device(gpu_id) # args.gpu = args.local_rank # torch.cuda.set_device(args.gpu) torch.distributed.init_process_group(backend='nccl') args.world_size = torch.distributed.get_world_size() # generating Tensorboard writer if args.log and args.local_rank==0: log_dir = "./log_paper/{}".format(args.dataset) log_file = log_dir + "/{}_bucket{}_hash{}_seq{}_bz{}_token{}_lr{}_alpha{}_layer{}_note{}.txt".format( '_'.join(args.attn_type_list), '_'.join(str(x) for x in args.bucket_size_list), '_'.join(str(x) for x in args.n_hashes_list), args.seq_len, args.batch_size, args.ntokens, args.lr_tri, args.tri_alpha, args.nlayers, args.note) os.makedirs(log_dir, exist_ok=True) print("args: ", args, file=open(log_file, "a")) print("args: ", args) run_file = "./run_paper/{}/{}_bucket{}_hash{}_seq{}_bz{}_token{}_lr{}_alpha{}_layer{}_note{}".format(args.dataset, '_'.join(args.attn_type_list),'_'.join(str(x) for x in args.bucket_size_list),'_'.join(str(x) for x in args.n_hashes_list), args.seq_len, args.batch_size, args.ntokens, args.lr_tri, args.tri_alpha, args.nlayers, args.note) writer = SummaryWriter(run_file) def save_model(model, optimizer, name, iteration): with open(os.path.join('synthetic', 'model_' + name + '_' + str(iteration) + '.pt'), 'wb') as f: torch.save(model.state_dict(), f) with open(os.path.join('synthetic', 'optimizer_' + name + '_' + str(iteration) + '.pt'), 'wb') as f: torch.save(optimizer.state_dict(), f) def _pad_to_multiple_of(x, y, axis): """Pads x to multiple of y on the given axis.""" pad_len = np.ceil(x.shape[axis] / float(y)) * y pad_widths = [(0, 0)] * len(x.shape) pad_widths[axis] = (0, int(pad_len - x.shape[axis])) return np.pad(x, pad_widths, mode='constant', constant_values=x.dtype.type(0)) def sequence_copy_inputs( vocab_size, batch_size, train_length, eval_min_length, eval_max_length, reverse=False, pad_to_multiple=32): """Inputs for the sequence copy problem: 0w0w for w in [1..vocab_size-1]*. Args: vocab_size: how many symbols to use. batch_size: how large are the batches. train_length: maximum length of w for training. eval_min_length: minimum length of w for eval. eval_max_length : maximum length of w for eval. reverse: bool (optional, false by default): reverse the second sequence. pad_to_multiple: int, pad length to be multiple of this number. Returns: trax.inputs.Inputs """ def random_minibatches(length_list): """Generate a stream of random mini-batches.""" while True: length = random.choice(length_list) assert length % 2 == 0 w_length = (length // 2) - 1 w = np.random.randint(low=1, high=vocab_size - 1, size=(batch_size, w_length)) zero = np.zeros([batch_size, 1], np.int32) loss_weights = np.concatenate([np.zeros((batch_size, w_length + 2)), np.ones((batch_size, w_length))], axis=1) if reverse: x = np.concatenate([zero, w, zero, np.flip(w, axis=1)], axis=1) else: x = np.concatenate([zero, w, zero, w], axis=1) x = torch.Tensor(_pad_to_multiple_of(x, pad_to_multiple, 1)).cuda().long() loss_weights = torch.Tensor(_pad_to_multiple_of(loss_weights, pad_to_multiple, 1)).cuda().long() yield (x,x,loss_weights) # Here inputs and targets are the same. train_lengths = [2 * (i + 2) for i in range(train_length - 1)] eval_lengths = [2 * (i + 1) for i in range(eval_min_length, eval_max_length)] train_stream = lambda _: random_minibatches(train_lengths) eval_stream = lambda _: random_minibatches(eval_lengths) return train_stream(None), eval_stream(None) def train(model, train_loader, epoch): model.train() # Turn on the train mode total_loss = 0. start_time = time.time() for batch in range(args.train_batches): for __ in range(GRADIENT_ACCUMULATE_EVERY): data, target, loss_mask = next(train_loader) if 'triplet' in args.attn_type_list: loss = model(data, loss_weight=loss_mask, return_loss=True, calc_triplet=True) tri_loss = model.net.net.get_triplet_loss() if tri_loss != 0.0: tri_loss.backward() model.net.net.clear_triplet_loss() else: loss = model(data, loss_weight=loss_mask, return_loss=True, calc_triplet=False) loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), 0.5) optimizer_main.step() optimizer_main.zero_grad() if 'triplet' in args.attn_type_list: optimizer_tri.step() optimizer_tri.zero_grad() total_loss += loss.item() log_interval = args.print_loss if batch % log_interval == 0 and batch > 0: cur_loss = total_loss / log_interval elapsed = time.time() - start_time if args.local_rank==0: print('| epoch {:3d} | {:5d}/{:5d} batches | ' 'lr {:02.5f} | ms/batch {:5.2f} | ' 'loss {:5.2f} | ppl {:8.2f}'.format( epoch, batch, args.train_batches , args.lr_main, elapsed * 1000 / log_interval, cur_loss, math.exp(cur_loss))) if args.log and args.local_rank==0: print('| epoch {:3d} | {:5d}/{:5d} batches | ' 'lr {:02.5f} | ms/batch {:5.2f} | ' 'loss {:5.2f} | ppl {:8.2f}'.format( epoch, batch, args.train_batches , args.lr_main, elapsed * 1000 / log_interval, cur_loss, math.exp(cur_loss)), file = open(log_file, "a")) total_loss = 0 if args.log and args.local_rank==0: writer.add_scalar('Loss/train', cur_loss, epoch*args.train_batches+batch) writer.add_scalar('Loss/train_pp', math.exp(cur_loss), epoch*args.train_batches+batch) start_time = time.time() def evaluate(eval_model, data_source, data_batches, epoch): eval_model.eval() # Turn on the evaluation mode total_loss = 0. counter = 0 with torch.no_grad(): for i in range(data_batches): data, target, loss_mask = next(data_source) loss = eval_model(data, loss_weight=loss_mask, return_loss=True, calc_triplet=False) valid_token = torch.sum(loss_mask) total_loss += valid_token*loss.item() counter += valid_token return total_loss / counter if __name__ == "__main__": train_loader, eval_loader = sequence_copy_inputs(args.ntokens, args.batch_size, args.seq_len//2, args.min_seq_len, args.seq_len//2) model = ReformerLM_tune( dim=args.nhid, emb_dim=args.emsize, depth=args.nlayers, max_seq_len=args.seq_len, num_tokens=args.ntokens, heads=args.nhead, bucket_size_list=args.bucket_size_list, fixed_position_emb=True, n_hashes_list=args.n_hashes_list, ff_chunks=1, ff_mult=1, attn_chunks=1, layer_dropout=0., ff_dropout=args.dropout, post_attn_dropout=args.dropout, lsh_dropout=args.dropout, weight_tie=False, causal=True, n_local_attn_heads=0, use_full_attn=args.use_full_attn, # set this to true for comparison with full attention reverse_thres=9999999999, full_attn_thres=args.full_attn_thres, num_mem_kv=0, attn_type_list=args.attn_type_list, store_stats=args.log, pkm_num_keys=0, ) model = TrainingWrapper(model) model.cuda() params_1 = [] params_2 = [] for name, p in model.named_parameters(): if 'rotation' in name: params_2.append(p) else: params_1.append(p) if 'triplet' in args.attn_type_list: optimizer_main = torch.optim.Adam(params_1, lr=args.lr_main) optimizer_tri = torch.optim.Adam(params_2, lr=args.lr_tri) else: optimizer_main = torch.optim.Adam(model.parameters(), lr=args.lr_main) if args.distributed: global ddp_model model = DDP(model, device_ids=[args.local_rank], output_device=args.local_rank) ddp_model = model for epoch in range(0, args.epochs): epoch_start_time = time.time() train(model, train_loader, epoch) val_loss = evaluate(model, eval_loader, args.print_loss, epoch) if args.log and args.local_rank==0: writer.add_scalar('Loss/val', val_loss, epoch) writer.add_scalar('Loss/val_pp', math.exp(val_loss), epoch) print('-' * 89) print('| end of epoch {:3d} | time: {:5.2f}s | valid loss {:5.2f} | ' 'valid ppl {:8.2f}'.format(epoch, (time.time() - epoch_start_time), val_loss, math.exp(val_loss))) print('-' * 89) if args.log and args.local_rank==0: print('| end of epoch {:3d} | time: {:5.2f}s | valid loss {:5.2f} | ' 'valid ppl {:8.2f}'.format(epoch, (time.time() - epoch_start_time), val_loss, math.exp(val_loss)), file=open(log_file, "a")) if args.log: writer.close()
import .algebra noncomputable theory set_option eqn_compiler.zeta true universes u v w u₁ v₁ w₁ infix ` ⊗ `:100 := tensor_product variables {R : Type u} {A : Type v} {B : Type w} {C : Type u₁} {D : Type v₁} variables [comm_ring R] [comm_ring A] [comm_ring B] [comm_ring C] [comm_ring D] variables (iA : algebra R A) (iB : algebra R B) (iC : algebra R C) (iD : algebra R D) namespace tensor_product open linear_map set_option class.instance_max_depth 200 def lmul : iA.mod ⊗ iB.mod →ₗ iA.mod ⊗ iB.mod →ₗ iA.mod ⊗ iB.mod := lift $ linear_map.compr₂ ((linear_map.lflip _ _ _ _).comp $ linear_map.compr₂ (curry $ curry $ map (lift iA.lmul) $ lift iB.lmul) (lcurry _ _ _)) (uncurry _ _ _) theorem lmul_tmul (p : iA.mod) (q : iB.mod) (r : iA.mod) (s : iB.mod) : lmul iA iB (p ⊗ₜ q) (r ⊗ₜ s) = (p * r) ⊗ₜ (q * s) := by rw [lmul, lift.tmul, compr₂_apply, uncurry_apply, comp_apply, lflip_apply, compr₂_apply, lcurry_apply, curry_apply, curry_apply, map_tmul, lift.tmul, lift.tmul]; refl instance : comm_ring (iA.mod ⊗ iB.mod) := { mul := λ x y, lmul iA iB x y, mul_assoc := begin intros x y z, show lmul iA iB (lmul iA iB x y) z = lmul iA iB x (lmul iA iB y z), refine tensor_product.induction_on _ _ z _ (λ z₁ z₂, _) (λ z₁ z₂ ih₁ ih₂, _), { simp only [map_zero] }, { refine tensor_product.induction_on _ _ y _ (λ y₁ y₂, _) (λ y₁ y₂ ih₁ ih₂, _), { rw [map_zero₂, map_zero, map_zero₂] }, { refine tensor_product.induction_on _ _ x _ (λ x₁ x₂, _) (λ x₁ x₂ ih₁ ih₂, _), { rw [map_zero₂, map_zero₂, map_zero₂] }, { iterate 4 { rw [lmul_tmul] }, iterate 2 { rw mul_assoc } }, { rw [map_add₂, map_add₂, map_add₂], congr' 1, exacts [ih₁, ih₂] } }, { rw [map_add₂, map_add, map_add₂, map_add], congr' 1, exacts [ih₁, ih₂] } }, { rw [map_add, map_add, map_add], congr' 1, exacts [ih₁, ih₂] } end, one := 1 ⊗ₜ 1, one_mul := λ x, show lmul iA iB (1 ⊗ₜ 1) x = x, from tensor_product.induction_on _ _ x (map_zero _) (λ x y, (lmul_tmul _ _ _ _ _ _).trans $ by rw [one_mul, one_mul]) (λ x y ihx ihy, (map_add _ _ _).trans $ by rw [ihx, ihy]), mul_one := λ x, show lmul iA iB x (1 ⊗ₜ 1) = x, from tensor_product.induction_on _ _ x (map_zero₂ _ _) (λ x y, (lmul_tmul _ _ _ _ _ _).trans $ by rw [mul_one, mul_one]) (λ x y ihx ihy, (map_add₂ _ _ _ _).trans $ by rw [ihx, ihy]), left_distrib := λ _, map_add _, right_distrib := map_add₂ _, mul_comm := λ x y, show lmul iA iB x y = lmul iA iB y x, from tensor_product.induction_on _ _ x (by rw [map_zero₂, map_zero]) (λ x₁ x₂, tensor_product.induction_on _ _ y (by rw [map_zero₂, map_zero]) (λ y₁ y₂, by rw [lmul_tmul, lmul_tmul, mul_comm x₁ y₁, mul_comm x₂ y₂]) (λ y₁ y₂ ih₁ ih₂, by rw [map_add₂, map_add, ih₁, ih₂])) (λ x₁ x₂ ih₁ ih₂, by rw [map_add₂, map_add, ih₁, ih₂]), .. tensor_product.add_comm_group _ _ } set_option class.instance_max_depth 32 theorem mul_def (p : iA.mod) (q : iB.mod) (r : iA.mod) (s : iB.mod) : (p ⊗ₜ q) * (r ⊗ₜ s) = (p * r) ⊗ₜ (q * s) := lmul_tmul _ _ _ _ _ _ theorem one_def : (1 : iA.mod ⊗ iB.mod) = 1 ⊗ₜ 1 := rfl end tensor_product namespace algebra open tensor_product linear_map def tensor_product : algebra R (iA.mod ⊗ iB.mod) := { to_fun := λ r, iA r ⊗ₜ 1, hom := ⟨by rw iA.map_one; refl, λ x y, by rw [iA.map_mul, mul_def, mul_one], λ x y, by rw [iA.map_add, add_tmul]⟩, smul_def' := λ r x, tensor_product.induction_on _ _ x (by rw [smul_zero, mul_zero]) (λ x y, by rw [← tmul_smul, ← smul_tmul, mul_def, iA.smul_def, one_mul]) (λ x y ihx ihy, by rw [smul_add, mul_add, ihx, ihy]) } def inl : iA →ₐ iA.tensor_product iB := { to_fun := λ x, x ⊗ₜ 1, hom := ⟨rfl, λ x y, by rw [mul_def, mul_one], λ x y, add_tmul _ _ _⟩, commutes' := λ r, rfl } theorem inl_def (p : iA.mod) : iA.inl iB p = p ⊗ₜ 1 := rfl def inr : iB →ₐ iA.tensor_product iB := { to_fun := λ x, 1 ⊗ₜ x, hom := ⟨rfl, λ x y, by rw [mul_def, mul_one], λ x y, tmul_add _ _ _⟩, commutes' := λ r, by rw [← mul_one (iB r), ← iB.smul_def, ← smul_tmul, iA.smul_def, mul_one]; refl } theorem inr_def (q : iB.mod) : iA.inr iB q = 1 ⊗ₜ q := rfl namespace tensor_product variables {iA iB iC} set_option class.instance_max_depth 100 @[elab_with_expected_type] def arec (f : iA →ₐ iC) (g : iB →ₐ iC) : iA.tensor_product iB →ₐ iC := { to_fun := (tensor_product.lift iC.lmul).comp $ map f.to_linear_map g.to_linear_map, hom := ⟨by rw [one_def, comp_apply, map_tmul, lift.tmul]; show f 1 * g 1 = 1; rw [f.map_one, g.map_one, mul_one], λ x y, tensor_product.induction_on _ _ x (by rw [zero_mul, linear_map.map_zero]; exact (zero_mul _).symm) (λ x₁ x₂, tensor_product.induction_on _ _ y (by rw [mul_zero, linear_map.map_zero]; exact (mul_zero _).symm) (λ y₁ y₂, by simp only [mul_def, comp_apply, map_tmul, lift.tmul]; change f _ * g _ = (f _ * g _) * (f _ * g _); rw [f.map_mul, g.map_mul, mul_assoc, mul_assoc, mul_left_comm (f y₁)]) (λ y₁ y₂ ih₁ ih₂, by simp only [mul_add, linear_map.map_add, ih₁, ih₂])) (λ x₁ x₂ ih₁ ih₂, by simp only [add_mul, linear_map.map_add, ih₁, ih₂]), linear_map.map_add _⟩, commutes' := λ r, show lift iC.lmul (map f.to_linear_map g.to_linear_map (iA r ⊗ₜ 1)) = _, by rw [map_tmul, lift.tmul]; change f _ * g 1 = _; rw [f.commutes, g.map_one, mul_one] } set_option class.instance_max_depth 32 theorem arec_tmul (f : iA →ₐ iC) (g : iB →ₐ iC) (p : iA.mod) (q : iB.mod) : arec f g (p ⊗ₜ q) = f p * g q := lift.tmul _ _ variables (iA iB iC) def UMP : ((iA →ₐ iC) × (iB →ₐ iC)) ≃ (iA.tensor_product iB →ₐ iC) := { to_fun := λ φ, arec φ.1 φ.2, inv_fun := λ φ, (φ.comp (iA.inl iB), φ.comp (iA.inr iB)), left_inv := λ ⟨φ₁, φ₂⟩, prod.ext (by ext p; change (arec φ₁ φ₂) (p ⊗ₜ 1) = φ₁ p; rw [arec_tmul, φ₂.map_one', mul_one]) (by ext q; change (arec φ₁ φ₂) (1 ⊗ₜ q) = φ₂ q; rw [arec_tmul, φ₁.map_one', one_mul]), right_inv := λ φ, alg_hom.to_linear_map_inj $ tensor_product.ext $ λ p q, by dsimp only [alg_hom.to_linear_map_apply]; rw [arec_tmul, alg_hom.comp_apply, alg_hom.comp_apply, inl_def, inr_def, ← φ.map_mul, mul_def, mul_one, one_mul] } variables {iA iB iC iD} def amap (f : iA →ₐ iC) (g : iB →ₐ iD) : (iA.tensor_product iB) →ₐ (iC.tensor_product iD) := arec ((iC.inl iD).comp f) ((iC.inr iD).comp g) variables (iA iB iC iD) @[simp] lemma amap_tmul (f : iA →ₐ iC) (g : iB →ₐ iD) (x : A) (y : B) : amap f g (x ⊗ₜ y) = f x ⊗ₜ g y := by rw amap; simp only [arec_tmul, alg_hom.comp_apply, inl_def, inr_def, mul_def, mul_one, one_mul] def aassoc : (iA.tensor_product iB).tensor_product iC →ₐ iA.tensor_product (iB.tensor_product iC) := arec (arec (iA.inl $ iB.tensor_product iC) ((iA.inr $ iB.tensor_product iC).comp $ iB.inl iC)) ((iA.inr $ iB.tensor_product iC).comp $ iB.inr iC) @[simp] lemma aassoc_tmul (x y z) : aassoc iA iB iC (x ⊗ₜ y ⊗ₜ z) = x ⊗ₜ (y ⊗ₜ z) := by rw aassoc; simp only [arec_tmul, inl_def, inr_def, alg_hom.comp_apply, mul_def, mul_one, one_mul] def id_tensor : (algebra.id R).tensor_product iA →ₐ iA := arec iA.of_id (alg_hom.id iA) @[simp] lemma id_tensor_tmul (r x) : id_tensor iA (r ⊗ₜ x) = ((r : R) • x : iA.mod) := by rw id_tensor; simp only [arec_tmul, alg_hom.id_apply, of_id_apply, iA.smul_def] def tensor_id : iA.tensor_product (algebra.id R) →ₐ iA := arec (alg_hom.id iA) iA.of_id @[simp] lemma tensor_id_tmul (r x) : tensor_id iA (x ⊗ₜ r) = ((r : R) • x : iA.mod) := by rw tensor_id; simp only [arec_tmul, alg_hom.id_apply, of_id_apply, iA.smul_def, mul_comm] def base_change_left : algebra iA.mod (iA.mod ⊗ iB.mod) := algebra.of_core { to_fun := iA.inl iB } theorem base_change_left_apply (r : iA.mod) : base_change_left iA iB r = r ⊗ₜ 1 := rfl set_option class.instance_max_depth 100 def base_change_left_rec {D : Type v₁} [comm_ring D] (iD : algebra iA.mod D) (φ : iB →ₐ iA.comap iD) : base_change_left iA iB →ₐ iD := { to_fun := (tensor_product.lift (iA.comap iD).lmul).comp (map (iA.to_comap iD).to_linear_map φ.to_linear_map), hom := ⟨by simp only [comp_apply, one_def, map_tmul, alg_hom.to_linear_map_apply, lmul_apply, lift.tmul, φ.map_one', (to_comap iA iD).map_one']; apply mul_one, λ x y, tensor_product.induction_on _ _ x (by rw [zero_mul, linear_map.map_zero]; exact (zero_mul _).symm) (λ x₁ x₂, tensor_product.induction_on _ _ y (by rw [mul_zero, linear_map.map_zero]; exact (mul_zero _).symm) (λ y₁ y₂, by simp only [mul_def, comp_apply, map_tmul, alg_hom.to_linear_map_apply, lmul_apply, lift.tmul, (iA.to_comap iD).map_mul, φ.map_mul, mul_assoc]; rw mul_left_comm ((iA.to_comap iD) y₁)) (λ y₁ y₂ ih₁ ih₂, by rw [mul_add, linear_map.map_add, ih₁, ih₂, linear_map.map_add, mul_add])) (λ x₁ x₂ ih₁ ih₂, by rw [add_mul, linear_map.map_add, ih₁, ih₂, linear_map.map_add, add_mul]), linear_map.map_add _⟩, commutes' := λ x, by rw [comp_apply, base_change_left_apply, map_tmul, alg_hom.to_linear_map_apply, alg_hom.to_linear_map_apply, to_comap_apply, lift.tmul, lmul_apply, φ.map_one']; exact mul_one _ } set_option class.instance_max_depth 32 def base_change_right : algebra B (iA.mod ⊗ iB.mod) := algebra.of_core { to_fun := iA.inr iB } end tensor_product end algebra
(* Proof Objects *) Require Export Logic. Inductive beautiful : nat -> Prop := b_0 : beautiful 0 | b_3 : beautiful 3 | b_5 : beautiful 5 | b_sum : forall n m : nat, beautiful n -> beautiful m -> beautiful (n + m). Print beautiful. Check (b_sum 3 5 b_3 b_5). Theorem eight_is_beautiful : beautiful 8. Proof. apply (b_sum 3 5 b_3 b_5). Qed. Theorem eight_is_beautiful'' : beautiful 8. Proof. Show Proof. apply b_sum with (n:=3) (m:=5). Show Proof. apply b_3. Show Proof. apply b_5. Show Proof. Qed. Definition eight_is_beautiful''' : beautiful 8 := b_sum 3 5 b_3 b_5. Print eight_is_beautiful. Print eight_is_beautiful''. Print eight_is_beautiful'''. (************************************************** Exercise: 1 star (six_is_beautiful) Give a tactic proof and a proof object showing that 6 is beautiful. **************************************************) Theorem six_is_beautiful : beautiful 6. Proof. apply b_sum with (n:=3) (m:=3). apply b_3. apply b_3. Qed. Definition six_is_beautiful' : beautiful 6 := b_sum 3 3 b_3 b_3. (************************************************** Exercise: 1 star (nine_is_beautiful) Give a tactic proof and a proof object showing that 9 is beautiful. **************************************************) Theorem nine_is_beautiful : beautiful 9. Proof. Definition nine_is_beautiful' : beautiful 9 := (* FILL IN HERE *) admit. ☐
/- Copyright (c) 2022 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import analysis.normed_space.star.basic import algebra.star.module import analysis.special_functions.exponential /-! # The exponential map from selfadjoint to unitary In this file, we establish various propreties related to the map `λ a, exp ℂ A (I • a)` between the subtypes `self_adjoint A` and `unitary A`. ## TODO * Show that any exponential unitary is path-connected in `unitary A` to `1 : unitary A`. * Prove any unitary whose distance to `1 : unitary A` is less than `1` can be expressed as an exponential unitary. * A unitary is in the path component of `1` if and only if it is a finite product of exponential unitaries. -/ section star variables {A : Type*} [normed_ring A] [normed_algebra ℂ A] [star_ring A] [cstar_ring A] [complete_space A] [star_module ℂ A] open complex lemma self_adjoint.exp_i_smul_unitary {a : A} (ha : a ∈ self_adjoint A) : exp ℂ A (I • a) ∈ unitary A := begin rw [unitary.mem_iff, star_exp], simp only [star_smul, is_R_or_C.star_def, self_adjoint.mem_iff.mp ha, conj_I, neg_smul], rw ←@exp_add_of_commute ℂ A _ _ _ _ _ _ ((commute.refl (I • a)).neg_left), rw ←@exp_add_of_commute ℂ A _ _ _ _ _ _ ((commute.refl (I • a)).neg_right), simpa only [add_right_neg, add_left_neg, and_self] using (exp_zero : exp ℂ A 0 = 1), end /-- The map from the selfadjoint real subspace to the unitary group. This map only makes sense over ℂ. -/ @[simps] noncomputable def self_adjoint.exp_unitary (a : self_adjoint A) : unitary A := ⟨exp ℂ A (I • a), self_adjoint.exp_i_smul_unitary (a.property)⟩ open self_adjoint lemma commute.exp_unitary_add {a b : self_adjoint A} (h : commute (a : A) (b : A)) : exp_unitary (a + b) = exp_unitary a * exp_unitary b := begin ext, have hcomm : commute (I • (a : A)) (I • (b : A)), calc _ = _ : by simp only [h.eq, algebra.smul_mul_assoc, algebra.mul_smul_comm], simpa only [exp_unitary_coe, add_subgroup.coe_add, smul_add] using exp_add_of_commute hcomm, end lemma commute.exp_unitary {a b : self_adjoint A} (h : commute (a : A) (b : A)) : commute (exp_unitary a) (exp_unitary b) := calc (exp_unitary a) * (exp_unitary b) = (exp_unitary b) * (exp_unitary a) : by rw [←h.exp_unitary_add, ←h.symm.exp_unitary_add, add_comm] end star
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura ! This file was ported from Lean 3 source module init.data.setoid ! leanprover-community/mathlib commit 9af482290ef68e8aaa5ead01aa7b09b7be7019fd ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ prelude import Leanbin.Init.Logic universe u #print Setoid /- class Setoid (α : Sort u) where r : α → α → Prop iseqv : Equivalence r #align setoid Setoid -/ instance (priority := 100) setoidHasEquiv {α : Sort u} [Setoid α] : HasEquiv α := ⟨Setoid.r⟩ #align setoid_has_equiv setoidHasEquiv namespace Setoid variable {α : Sort u} [Setoid α] #print Setoid.refl /- @[refl] theorem refl (a : α) : a ≈ a := match Setoid.iseqv with | ⟨h_refl, h_symm, h_trans⟩ => h_refl a #align setoid.refl Setoid.refl -/ #print Setoid.symm /- @[symm] theorem symm {a b : α} (hab : a ≈ b) : b ≈ a := match Setoid.iseqv with | ⟨h_refl, h_symm, h_trans⟩ => h_symm hab #align setoid.symm Setoid.symm -/ #print Setoid.trans /- @[trans] theorem trans {a b c : α} (hab : a ≈ b) (hbc : b ≈ c) : a ≈ c := match Setoid.iseqv with | ⟨h_refl, h_symm, h_trans⟩ => h_trans hab hbc #align setoid.trans Setoid.trans -/ end Setoid
The Friends representatives continued attempting to make the bill more favorable to the historic peace churches . The Burke @-@ Wadsworth Bill passed on September 14 , 1940 , becoming the Selective Training and Service Act of 1940 . The influence of the churches was evident in section 5 ( g ) , which says in part :
------------------------------------------------------------------------------ -- Test the consistency of PA.Axiomatic.Standard.Base ------------------------------------------------------------------------------ {-# OPTIONS --exact-split #-} {-# OPTIONS --no-sized-types #-} {-# OPTIONS --no-universe-polymorphism #-} {-# OPTIONS --without-K #-} -- In the module PA.Axiomatic.Standard.Base we declare Agda postulates -- as first-order logic axioms. We test if it is possible to prove an -- unprovable theorem from these axioms. module PA.Axiomatic.Standard.Base.Consistency.Axioms where open import PA.Axiomatic.Standard.Base ------------------------------------------------------------------------------ postulate impossible : (m n : ℕ) → m ≡ n {-# ATP prove impossible #-}
# Generated using bssn_4d_spher_matter.mw restx:=expand(simplify((-2*b1(t, x)*alpha(t, x)*(diff(a1(t, x), t))-2*x*alpha(t, x)*(diff(a1(t, x), t))*(diff(b1(t, x), x))+2*x*(diff(diff(b1(t, x), t), x))*alpha(t, x)*a1(t, x)+2*(diff(b1(t, x), t))*alpha(t, x)*a1(t, x)+2*beta(t, x)*alpha(t, x)*b1(t, x)*(diff(a1(t, x), x))+b1(t, x)*x*alpha(t, x)*a1(t, x)*(diff(rpsi(t, x), x))*(diff(rpsi(t, x), t))+b1(t, x)*x*alpha(t, x)*a1(t, x)*(diff(ipsi(t, x), x))*(diff(ipsi(t, x), t))-b1(t, x)*x*alpha(t, x)*a1(t, x)*beta(t, x)*(diff(rpsi(t, x), x))^2-b1(t, x)*x*alpha(t, x)*a1(t, x)*beta(t, x)*(diff(ipsi(t, x), x))^2-2*beta(t, x)*alpha(t, x)*a1(t, x)*x*(diff(diff(b1(t, x), x), x))+2*beta(t, x)*alpha(t, x)*x*(diff(a1(t, x), x))*(diff(b1(t, x), x))-4*beta(t, x)*(diff(b1(t, x), x))*alpha(t, x)*a1(t, x)-2*x*(diff(b1(t, x), t))*a1(t, x)*(diff(alpha(t, x), x))+2*beta(t, x)*a1(t, x)*x*(diff(alpha(t, x), x))*(diff(b1(t, x), x))+2*beta(t, x)*a1(t, x)*b1(t, x)*(diff(alpha(t, x), x)))/(alpha(t, x)^3*b1(t, x)*x*a1(t, x)))); ire_rpsi_direct:= -2*(diff(rpsi(t, x), x))*beta(t, x)*(diff(beta(t, x), x))/alpha(t, x)^2+(diff(rpsi(t, x), t))*beta(t, x)*(diff(a1(t, x), x))/(alpha(t, x)^2*a1(t, x))-(diff(rpsi(t, x), t))*beta(t, x)*(diff(alpha(t, x), x))/alpha(t, x)^3-(diff(rpsi(t, x), x))*beta(t, x)*(diff(alpha(t, x), t))/alpha(t, x)^3+(diff(rpsi(t, x), x))*beta(t, x)^2*(diff(alpha(t, x), x))/alpha(t, x)^3+2*(diff(rpsi(t, x), t))*beta(t, x)*(diff(b1(t, x), x))/(alpha(t, x)^2*b1(t, x))+2*(diff(rpsi(t, x), x))*beta(t, x)*(diff(b1(t, x), t))/(alpha(t, x)^2*b1(t, x))-2*(diff(rpsi(t, x), x))*beta(t, x)^2*(diff(b1(t, x), x))/(alpha(t, x)^2*b1(t, x))+(diff(rpsi(t, x), x))*beta(t, x)*(diff(a1(t, x), t))/(alpha(t, x)^2*a1(t, x))-(diff(rpsi(t, x), x))*beta(t, x)^2*(diff(a1(t, x), x))/(alpha(t, x)^2*a1(t, x))-2*(diff(rpsi(t, x), t))*(diff(b1(t, x), t))/(alpha(t, x)^2*b1(t, x))+2*(diff(rpsi(t, x), t))*beta(t, x)/(alpha(t, x)^2*x)-2*(diff(rpsi(t, x), x))*beta(t, x)^2/(alpha(t, x)^2*x)+(diff(rpsi(t, x), t))*(diff(alpha(t, x), t))/alpha(t, x)^3+2*beta(t, x)*(diff(diff(rpsi(t, x), t), x))/alpha(t, x)^2+(diff(rpsi(t, x), t))*(diff(beta(t, x), x))/alpha(t, x)^2-(diff(rpsi(t, x), t))*(diff(a1(t, x), t))/(alpha(t, x)^2*a1(t, x))-beta(t, x)^2*(diff(diff(rpsi(t, x), x), x))/alpha(t, x)^2+(diff(rpsi(t, x), x))*(diff(beta(t, x), t))/alpha(t, x)^2-(diff(diff(rpsi(t, x), t), t))/alpha(t, x)^2+2*(diff(rpsi(t, x), x))/(a1(t, x)^2*x)+(diff(diff(rpsi(t, x), x), x))/a1(t, x)^2-(diff(rpsi(t, x), x))*(diff(a1(t, x), x))/a1(t, x)^3+2*(diff(rpsi(t, x), x))*(diff(b1(t, x), x))/(b1(t, x)*a1(t, x)^2)-mass*rpsi(t, x)+(diff(rpsi(t, x), x))*(diff(alpha(t, x), x))/(alpha(t, x)*a1(t, x)^2); resxx:= (1/2)*(-alpha(t, x)^3*b1(t, x)^2*x^2*(diff(rpsi(t, x), x))^2-alpha(t, x)^3*b1(t, x)^2*x^2*(diff(ipsi(t, x), x))^2+alpha(t, x)*b1(t, x)^2*x^2*(diff(rpsi(t, x), x))^2*a1(t, x)^2*beta(t, x)^2+alpha(t, x)*b1(t, x)^2*x^2*(diff(ipsi(t, x), x))^2*a1(t, x)^2*beta(t, x)^2-2*b1(t, x)^2*a1(t, x)^2*alpha(t, x)*beta(t, x)^2-2*(diff(b1(t, x), t))^2*a1(t, x)^2*alpha(t, x)*x^2+4*b1(t, x)^2*x*alpha(t, x)^2*(diff(alpha(t, x), x))+4*(diff(b1(t, x), x))*alpha(t, x)^3*x*b1(t, x)+2*(diff(b1(t, x), x))^2*alpha(t, x)^3*x^2+2*alpha(t, x)^3*b1(t, x)^2-2*a1(t, x)^2*alpha(t, x)^3+alpha(t, x)^3*b1(t, x)^2*x^2*U(t, x)*a1(t, x)^2-alpha(t, x)*b1(t, x)^2*x^2*(diff(rpsi(t, x), t))^2*a1(t, x)^2-alpha(t, x)*b1(t, x)^2*x^2*(diff(ipsi(t, x), t))^2*a1(t, x)^2+4*a1(t, x)*beta(t, x)*b1(t, x)*x^2*alpha(t, x)*(diff(a1(t, x), t))*(diff(b1(t, x), x))-4*a1(t, x)*beta(t, x)^2*alpha(t, x)*b1(t, x)*x^2*(diff(a1(t, x), x))*(diff(b1(t, x), x))-4*a1(t, x)*beta(t, x)^2*alpha(t, x)*b1(t, x)^2*x*(diff(a1(t, x), x))+4*a1(t, x)*beta(t, x)*b1(t, x)^2*x*alpha(t, x)*(diff(a1(t, x), t))-4*b1(t, x)*x^2*a1(t, x)^2*alpha(t, x)*(diff(diff(b1(t, x), t), t))+4*b1(t, x)^2*x*a1(t, x)^2*alpha(t, x)*(diff(beta(t, x), t))-2*(diff(b1(t, x), x))^2*x^2*a1(t, x)^2*alpha(t, x)*beta(t, x)^2+4*b1(t, x)*x^2*(diff(alpha(t, x), t))*a1(t, x)^2*(diff(b1(t, x), t))-4*b1(t, x)^2*x*(diff(alpha(t, x), t))*a1(t, x)^2*beta(t, x)+4*b1(t, x)*x^2*alpha(t, x)^2*(diff(alpha(t, x), x))*(diff(b1(t, x), x))+4*b1(t, x)*x^2*a1(t, x)^2*alpha(t, x)*(diff(beta(t, x), t))*(diff(b1(t, x), x))+4*b1(t, x)*x^2*a1(t, x)^2*alpha(t, x)*beta(t, x)*(diff(diff(b1(t, x), t), x))+8*b1(t, x)*x*a1(t, x)^2*alpha(t, x)*beta(t, x)*(diff(b1(t, x), t))+4*(diff(b1(t, x), x))*x^2*a1(t, x)^2*alpha(t, x)*beta(t, x)*(diff(b1(t, x), t))-4*(diff(b1(t, x), x))*x*a1(t, x)^2*alpha(t, x)*beta(t, x)^2*b1(t, x)-4*alpha(t, x)*b1(t, x)^2*x*beta(t, x)*a1(t, x)^2*(diff(beta(t, x), x))-4*b1(t, x)*x^2*(diff(alpha(t, x), t))*a1(t, x)^2*beta(t, x)*(diff(b1(t, x), x))-4*alpha(t, x)*b1(t, x)*x^2*beta(t, x)*a1(t, x)^2*(diff(beta(t, x), x))*(diff(b1(t, x), x)))/(alpha(t, x)^3*a1(t, x)^2*b1(t, x)^2*x^2); restt:= (1/2)*(4*b1(t, x)^2*x*a1(t, x)^3*beta(t, x)^2*(diff(alpha(t, x), x))-2*(diff(b1(t, x), x))^2*x^2*a1(t, x)^3*alpha(t, x)*beta(t, x)^2+12*(diff(b1(t, x), x))*alpha(t, x)^3*a1(t, x)*x*b1(t, x)+4*alpha(t, x)^3*a1(t, x)*b1(t, x)*x^2*(diff(diff(b1(t, x), x), x))-4*alpha(t, x)^3*b1(t, x)*x^2*(diff(a1(t, x), x))*(diff(b1(t, x), x))-4*a1(t, x)^3*alpha(t, x)*b1(t, x)*x^2*beta(t, x)^2*(diff(diff(b1(t, x), x), x))+4*b1(t, x)*x^2*a1(t, x)^3*alpha(t, x)*beta(t, x)*(diff(diff(b1(t, x), t), x))+8*b1(t, x)*x*a1(t, x)^3*alpha(t, x)*beta(t, x)*(diff(b1(t, x), t))+4*(diff(b1(t, x), x))*x^2*a1(t, x)^3*alpha(t, x)*beta(t, x)*(diff(b1(t, x), t))-12*(diff(b1(t, x), x))*x*a1(t, x)^3*alpha(t, x)*beta(t, x)^2*b1(t, x)+4*a1(t, x)^3*(diff(b1(t, x), t))*alpha(t, x)*b1(t, x)*x^2*(diff(beta(t, x), x))-4*a1(t, x)^2*(diff(b1(t, x), t))*alpha(t, x)*b1(t, x)*x^2*(diff(a1(t, x), t))-4*alpha(t, x)*b1(t, x)^2*x*beta(t, x)*a1(t, x)^3*(diff(beta(t, x), x))-4*b1(t, x)*x^2*a1(t, x)^3*(diff(b1(t, x), t))*beta(t, x)*(diff(alpha(t, x), x))+4*b1(t, x)*x^2*a1(t, x)^3*beta(t, x)^2*(diff(b1(t, x), x))*(diff(alpha(t, x), x))+4*a1(t, x)^2*(diff(b1(t, x), t))*alpha(t, x)*b1(t, x)*x^2*beta(t, x)*(diff(a1(t, x), x))-4*alpha(t, x)*b1(t, x)*x^2*beta(t, x)*a1(t, x)^3*(diff(beta(t, x), x))*(diff(b1(t, x), x))-2*b1(t, x)^2*a1(t, x)^3*alpha(t, x)*beta(t, x)^2-2*(diff(b1(t, x), t))^2*a1(t, x)^3*alpha(t, x)*x^2+2*(diff(b1(t, x), x))^2*alpha(t, x)^3*a1(t, x)*x^2-4*alpha(t, x)^3*b1(t, x)^2*x*(diff(a1(t, x), x))+2*alpha(t, x)^3*a1(t, x)*b1(t, x)^2-2*a1(t, x)^3*alpha(t, x)^3+b1(t, x)^2*x^2*alpha(t, x)*a1(t, x)^3*(diff(rpsi(t, x), t))^2+b1(t, x)^2*x^2*alpha(t, x)*a1(t, x)^3*(diff(ipsi(t, x), t))^2+b1(t, x)^2*x^2*alpha(t, x)^3*a1(t, x)^3*U(t, x)+b1(t, x)^2*x^2*alpha(t, x)^3*a1(t, x)*(diff(rpsi(t, x), x))^2+b1(t, x)^2*x^2*alpha(t, x)^3*a1(t, x)*(diff(ipsi(t, x), x))^2-b1(t, x)^2*x^2*alpha(t, x)*a1(t, x)^3*(diff(rpsi(t, x), x))^2*beta(t, x)^2-b1(t, x)^2*x^2*alpha(t, x)*a1(t, x)^3*(diff(ipsi(t, x), x))^2*beta(t, x)^2)/(alpha(t, x)^3*b1(t, x)^2*x^2*a1(t, x)^3); resthth:= (1/2)*(-2*a1(t, x)^2*alpha(t, x)*b1(t, x)*x*(diff(diff(a1(t, x), t), t))+2*alpha(t, x)^2*a1(t, x)*b1(t, x)*x*(diff(diff(alpha(t, x), x), x))-2*alpha(t, x)*a1(t, x)^3*b1(t, x)*x*(diff(beta(t, x), x))^2-2*b1(t, x)*x*(diff(a1(t, x), x))*alpha(t, x)^2*(diff(alpha(t, x), x))+2*(diff(alpha(t, x), x))*a1(t, x)^2*b1(t, x)*x*beta(t, x)^2*(diff(a1(t, x), x))+2*(diff(alpha(t, x), x))*a1(t, x)^3*b1(t, x)*x*beta(t, x)*(diff(beta(t, x), x))-2*(diff(alpha(t, x), x))*a1(t, x)^2*b1(t, x)*x*beta(t, x)*(diff(a1(t, x), t))+2*a1(t, x)^2*(diff(b1(t, x), t))*alpha(t, x)*x*beta(t, x)*(diff(a1(t, x), x))-2*alpha(t, x)*x*beta(t, x)^2*a1(t, x)^2*(diff(a1(t, x), x))*(diff(b1(t, x), x))-4*alpha(t, x)*x*beta(t, x)*a1(t, x)^3*(diff(beta(t, x), x))*(diff(b1(t, x), x))+2*alpha(t, x)*x*beta(t, x)*a1(t, x)^2*(diff(a1(t, x), t))*(diff(b1(t, x), x))-2*a1(t, x)^2*(diff(alpha(t, x), t))*b1(t, x)*x*beta(t, x)*(diff(a1(t, x), x))+4*(diff(a1(t, x), t))*alpha(t, x)*a1(t, x)^2*b1(t, x)*x*(diff(beta(t, x), x))+2*a1(t, x)^2*alpha(t, x)*b1(t, x)*x*(diff(beta(t, x), t))*(diff(a1(t, x), x))+4*a1(t, x)^2*alpha(t, x)*b1(t, x)*x*beta(t, x)*(diff(diff(a1(t, x), t), x))-2*alpha(t, x)*a1(t, x)^2*b1(t, x)*x*beta(t, x)^2*(diff(diff(a1(t, x), x), x))-2*alpha(t, x)*a1(t, x)^3*b1(t, x)*x*beta(t, x)*(diff(diff(beta(t, x), x), x))-6*alpha(t, x)*a1(t, x)^2*b1(t, x)*x*beta(t, x)*(diff(a1(t, x), x))*(diff(beta(t, x), x))+2*b1(t, x)*a1(t, x)^3*beta(t, x)^2*(diff(alpha(t, x), x))+4*a1(t, x)^3*alpha(t, x)*beta(t, x)*(diff(b1(t, x), t))-4*(diff(b1(t, x), x))*a1(t, x)^3*alpha(t, x)*beta(t, x)^2-2*x*a1(t, x)^3*alpha(t, x)*(diff(diff(b1(t, x), t), t))+2*b1(t, x)*a1(t, x)^3*alpha(t, x)*(diff(beta(t, x), t))+2*a1(t, x)*b1(t, x)*alpha(t, x)^2*(diff(alpha(t, x), x))+2*x*(diff(alpha(t, x), t))*a1(t, x)^3*(diff(b1(t, x), t))-2*b1(t, x)*(diff(alpha(t, x), t))*a1(t, x)^3*beta(t, x)+2*alpha(t, x)^3*a1(t, x)*x*(diff(diff(b1(t, x), x), x))-2*alpha(t, x)^3*x*(diff(a1(t, x), x))*(diff(b1(t, x), x))+b1(t, x)*x*a1(t, x)^3*alpha(t, x)^3*U(t, x)-b1(t, x)*x*a1(t, x)^3*alpha(t, x)*(diff(rpsi(t, x), t))^2-b1(t, x)*x*a1(t, x)^3*alpha(t, x)*(diff(ipsi(t, x), t))^2+b1(t, x)*x*a1(t, x)*alpha(t, x)^3*(diff(rpsi(t, x), x))^2+b1(t, x)*x*a1(t, x)*alpha(t, x)^3*(diff(ipsi(t, x), x))^2-2*alpha(t, x)^3*b1(t, x)*(diff(a1(t, x), x))+4*(diff(b1(t, x), x))*alpha(t, x)^3*a1(t, x)+2*a1(t, x)^3*(diff(b1(t, x), t))*alpha(t, x)*x*(diff(beta(t, x), x))-2*a1(t, x)^2*(diff(b1(t, x), t))*alpha(t, x)*x*(diff(a1(t, x), t))-2*alpha(t, x)*b1(t, x)*beta(t, x)^2*a1(t, x)^2*(diff(a1(t, x), x))-4*alpha(t, x)*b1(t, x)*beta(t, x)*a1(t, x)^3*(diff(beta(t, x), x))+2*alpha(t, x)*b1(t, x)*beta(t, x)*a1(t, x)^2*(diff(a1(t, x), t))-2*a1(t, x)^3*(diff(alpha(t, x), t))*b1(t, x)*x*(diff(beta(t, x), x))+2*a1(t, x)^2*(diff(alpha(t, x), t))*b1(t, x)*x*(diff(a1(t, x), t))+2*a1(t, x)^3*alpha(t, x)*b1(t, x)*x*(diff(diff(beta(t, x), t), x))-2*a1(t, x)^3*alpha(t, x)*x*beta(t, x)^2*(diff(diff(b1(t, x), x), x))+2*x*a1(t, x)^3*alpha(t, x)*(diff(beta(t, x), t))*(diff(b1(t, x), x))+4*x*a1(t, x)^3*alpha(t, x)*beta(t, x)*(diff(diff(b1(t, x), t), x))+2*a1(t, x)*x*alpha(t, x)^2*(diff(alpha(t, x), x))*(diff(b1(t, x), x))-2*x*(diff(alpha(t, x), t))*a1(t, x)^3*beta(t, x)*(diff(b1(t, x), x))-2*x*a1(t, x)^3*(diff(b1(t, x), t))*beta(t, x)*(diff(alpha(t, x), x))+2*x*a1(t, x)^3*beta(t, x)^2*(diff(b1(t, x), x))*(diff(alpha(t, x), x))-b1(t, x)*x*a1(t, x)^3*alpha(t, x)*(diff(rpsi(t, x), x))^2*beta(t, x)^2-b1(t, x)*x*a1(t, x)^3*alpha(t, x)*(diff(ipsi(t, x), x))^2*beta(t, x)^2+2*b1(t, x)*x*a1(t, x)^3*alpha(t, x)*beta(t, x)*(diff(rpsi(t, x), t))*(diff(rpsi(t, x), x))+2*b1(t, x)*x*a1(t, x)^3*alpha(t, x)*beta(t, x)*(diff(ipsi(t, x), t))*(diff(ipsi(t, x), x)))/(b1(t, x)*x*alpha(t, x)^3*a1(t, x)^3);
{-| Copyright : (C) 2013-2016, University of Twente, 2016-2017, Myrtle Software Ltd License : BSD2 (see the file LICENSE) Maintainer : Christiaan Baaij <[email protected]> -} {-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE Trustworthy #-} {-# OPTIONS_GHC -fplugin=GHC.TypeLits.Extra.Solver #-} {-# OPTIONS_GHC -fplugin=GHC.TypeLits.Normalise #-} {-# OPTIONS_GHC -fplugin=GHC.TypeLits.KnownNat.Solver #-} {-# OPTIONS_HADDOCK show-extensions #-} #include "MachDeps.h" module Clash.Class.BitPack ( BitPack (..) , bitCoerce , bitCoerceMap , boolToBV , boolToBit , bitToBool , packXWith -- * Internals , GBitPack(..) ) where import Control.Exception (catch, evaluate) import Data.Binary.IEEE754 (doubleToWord, floatToWord, wordToDouble, wordToFloat) #if MIN_VERSION_base(4,12,0) import Data.Complex (Complex) import Data.Ord (Down) #endif import Data.Int import Data.Word import Foreign.C.Types (CUShort) import GHC.TypeLits (KnownNat, Nat, type (+), type (-)) import Numeric.Half (Half (..)) import GHC.Generics import GHC.TypeLits.Extra (CLog, Max) import Prelude hiding (map) import System.IO.Unsafe (unsafeDupablePerformIO) import Clash.Promoted.Nat (SNat(..), snatToNum) import Clash.Class.BitPack.Internal (deriveBitPackTuples) import Clash.Class.Resize (zeroExtend, resize) import Clash.Sized.BitVector (Bit, BitVector, (++#)) import Clash.Sized.Internal.BitVector (pack#, split#, checkUnpackUndef, undefined#, unpack#, unsafeToNatural) import Clash.XException {- $setup >>> :set -XDataKinds >>> import Clash.Prelude -} -- | Convert to and from a 'BitVector' class KnownNat (BitSize a) => BitPack a where -- | Number of 'Clash.Sized.BitVector.Bit's needed to represents elements -- of type @a@ -- -- Can be derived using `GHC.Generics`: -- -- > import Clash.Prelude -- > import GHC.Generics -- > -- > data MyProductType = MyProductType { a :: Int, b :: Bool } -- > deriving (Generic, BitPack) type BitSize a :: Nat type BitSize a = (CLog 2 (GConstructorCount (Rep a))) + (GFieldSize (Rep a)) -- | Convert element of type @a@ to a 'BitVector' -- -- >>> pack (-5 :: Signed 6) -- 11_1011 pack :: a -> BitVector (BitSize a) default pack :: ( Generic a , GBitPack (Rep a) , KnownNat (BitSize a) , KnownNat constrSize , KnownNat fieldSize , constrSize ~ CLog 2 (GConstructorCount (Rep a)) , fieldSize ~ GFieldSize (Rep a) , (constrSize + fieldSize) ~ BitSize a ) => a -> BitVector (BitSize a) pack = packXWith go where go a = resize (pack sc) ++# packedFields where (sc, packedFields) = gPackFields 0 (from a) -- | Convert a 'BitVector' to an element of type @a@ -- -- >>> pack (-5 :: Signed 6) -- 11_1011 -- >>> let x = pack (-5 :: Signed 6) -- >>> unpack x :: Unsigned 6 -- 59 -- >>> pack (59 :: Unsigned 6) -- 11_1011 unpack :: BitVector (BitSize a) -> a default unpack :: ( Generic a , GBitPack (Rep a) , KnownNat constrSize , KnownNat fieldSize , constrSize ~ CLog 2 (GConstructorCount (Rep a)) , fieldSize ~ GFieldSize (Rep a) , (constrSize + fieldSize) ~ BitSize a ) => BitVector (BitSize a) -> a unpack b = to (gUnpack sc 0 bFields) where (checkUnpackUndef unpack . resize -> sc, bFields) = split# b packXWith :: KnownNat n => (a -> BitVector n) -> a -> BitVector n packXWith f x = unsafeDupablePerformIO (catch (f <$> evaluate x) (\(XException _) -> return undefined#)) {-# NOINLINE packXWith #-} {-# INLINE[1] bitCoerce #-} -- | Coerce a value from one type to another through its bit representation. -- -- >>> pack (-5 :: Signed 6) -- 11_1011 -- >>> bitCoerce (-5 :: Signed 6) :: Unsigned 6 -- 59 -- >>> pack (59 :: Unsigned 6) -- 11_1011 bitCoerce :: (BitPack a, BitPack b, BitSize a ~ BitSize b) => a -> b bitCoerce = unpack . pack -- | Map a value by first coercing to another type through its bit representation. -- -- >>> pack (-5 :: Signed 32) -- 1111_1111_1111_1111_1111_1111_1111_1011 -- >>> bitCoerceMap @(Vec 4 (BitVector 8)) (replace 1 0) (-5 :: Signed 32) -- -16711685 -- >>> pack (-16711685 :: Signed 32) -- 1111_1111_0000_0000_1111_1111_1111_1011 bitCoerceMap :: forall a b . (BitPack a, BitPack b, BitSize a ~ BitSize b) => (a -> a) -> b -> b bitCoerceMap f = bitCoerce . f . bitCoerce instance BitPack Bool where type BitSize Bool = 1 pack = let go b = if b then 1 else 0 in packXWith go unpack = checkUnpackUndef $ \bv -> if bv == 1 then True else False instance KnownNat n => BitPack (BitVector n) where type BitSize (BitVector n) = n pack = packXWith id unpack v = v instance BitPack Bit where type BitSize Bit = 1 pack = packXWith pack# unpack = unpack# instance BitPack Int where type BitSize Int = WORD_SIZE_IN_BITS pack = packXWith fromIntegral unpack = checkUnpackUndef fromIntegral instance BitPack Int8 where type BitSize Int8 = 8 pack = packXWith fromIntegral unpack = checkUnpackUndef fromIntegral instance BitPack Int16 where type BitSize Int16 = 16 pack = packXWith fromIntegral unpack = checkUnpackUndef fromIntegral instance BitPack Int32 where type BitSize Int32 = 32 pack = packXWith fromIntegral unpack = checkUnpackUndef fromIntegral instance BitPack Int64 where type BitSize Int64 = 64 pack = packXWith fromIntegral unpack = checkUnpackUndef fromIntegral instance BitPack Word where type BitSize Word = WORD_SIZE_IN_BITS pack = packXWith fromIntegral unpack = checkUnpackUndef fromIntegral instance BitPack Word8 where type BitSize Word8 = 8 pack = packXWith fromIntegral unpack = checkUnpackUndef fromIntegral instance BitPack Word16 where type BitSize Word16 = 16 pack = packXWith fromIntegral unpack = checkUnpackUndef fromIntegral instance BitPack Word32 where type BitSize Word32 = 32 pack = packXWith fromIntegral unpack = checkUnpackUndef fromIntegral instance BitPack Word64 where type BitSize Word64 = 64 pack = packXWith fromIntegral unpack = checkUnpackUndef fromIntegral instance BitPack Float where type BitSize Float = 32 pack = packXWith packFloat# unpack = checkUnpackUndef unpackFloat# packFloat# :: Float -> BitVector 32 packFloat# = fromIntegral . floatToWord {-# NOINLINE packFloat# #-} unpackFloat# :: BitVector 32 -> Float unpackFloat# (unsafeToNatural -> w) = wordToFloat (fromIntegral w) {-# NOINLINE unpackFloat# #-} instance BitPack Double where type BitSize Double = 64 pack = packXWith packDouble# unpack = checkUnpackUndef unpackDouble# packDouble# :: Double -> BitVector 64 packDouble# = fromIntegral . doubleToWord {-# NOINLINE packDouble# #-} unpackDouble# :: BitVector 64 -> Double unpackDouble# (unsafeToNatural -> w) = wordToDouble (fromIntegral w) {-# NOINLINE unpackDouble# #-} instance BitPack CUShort where type BitSize CUShort = 16 pack = packXWith fromIntegral unpack = checkUnpackUndef fromIntegral instance BitPack Half where type BitSize Half = 16 pack (Half x) = pack x unpack = checkUnpackUndef $ \x -> Half (unpack x) instance BitPack () where type BitSize () = 0 pack _ = minBound unpack _ = () instance (BitPack a, BitPack b) => BitPack (a,b) where type BitSize (a,b) = BitSize a + BitSize b pack = let go (a,b) = pack a ++# pack b in packXWith go unpack ab = let (a,b) = split# ab in (unpack a, unpack b) class GBitPack f where -- | Size of fields. If multiple constructors exist, this is the maximum of -- the sum of each of the constructors fields. type GFieldSize f :: Nat -- | Number of constructors this type has. Indirectly indicates how many bits -- are needed to represent the constructor. type GConstructorCount f :: Nat -- | Pack fields of a type. Caller should pack and prepend the constructor bits. gPackFields :: Int -- ^ Current constructor -> f a -- ^ Data to pack -> (Int, BitVector (GFieldSize f)) -- ^ (Constructor number, Packed fields) -- | Unpack whole type. gUnpack :: Int -- ^ Construct with constructor /n/ -> Int -- ^ Current constructor -> BitVector (GFieldSize f) -- ^ BitVector containing fields -> f a -- ^ Unpacked result instance GBitPack a => GBitPack (M1 m d a) where type GFieldSize (M1 m d a) = GFieldSize a type GConstructorCount (M1 m d a) = GConstructorCount a gPackFields cc (M1 m1) = gPackFields cc m1 gUnpack c cc b = M1 (gUnpack c cc b) instance ( KnownNat (GFieldSize g) , KnownNat (GFieldSize f) , KnownNat (GConstructorCount f) , GBitPack f , GBitPack g ) => GBitPack (f :+: g) where type GFieldSize (f :+: g) = Max (GFieldSize f) (GFieldSize g) type GConstructorCount (f :+: g) = GConstructorCount f + GConstructorCount g gPackFields cc (L1 l) = let (sc, packed) = gPackFields cc l in let padding = undefined# :: BitVector (Max (GFieldSize f) (GFieldSize g) - GFieldSize f) in (sc, packed ++# padding) gPackFields cc (R1 r) = let cLeft = snatToNum (SNat @(GConstructorCount f)) in let (sc, packed) = gPackFields (cc + cLeft) r in let padding = undefined# :: BitVector (Max (GFieldSize f) (GFieldSize g) - GFieldSize g) in (sc, packed ++# padding) gUnpack c cc b = let cLeft = snatToNum (SNat @(GConstructorCount f)) in if c < cc + cLeft then L1 (gUnpack c cc f) else R1 (gUnpack c (cc + cLeft) g) where -- It's a thing of beauty, if I may say so myself! (f, _ :: BitVector (Max (GFieldSize f) (GFieldSize g) - GFieldSize f)) = split# b (g, _ :: BitVector (Max (GFieldSize f) (GFieldSize g) - GFieldSize g)) = split# b instance (KnownNat (GFieldSize g), KnownNat (GFieldSize f), GBitPack f, GBitPack g) => GBitPack (f :*: g) where type GFieldSize (f :*: g) = GFieldSize f + GFieldSize g type GConstructorCount (f :*: g) = 1 gPackFields cc fg = (cc, packXWith go fg) where go (l0 :*: r0) = let (_, l1) = gPackFields cc l0 in let (_, r1) = gPackFields cc r0 in l1 ++# r1 gUnpack c cc b = gUnpack c cc front :*: gUnpack c cc back where (front, back) = split# b instance BitPack c => GBitPack (K1 i c) where type GFieldSize (K1 i c) = BitSize c type GConstructorCount (K1 i c) = 1 gPackFields cc (K1 i) = (cc, pack i) gUnpack _c _cc b = K1 (unpack b) instance GBitPack U1 where type GFieldSize U1 = 0 type GConstructorCount U1 = 1 gPackFields cc U1 = (cc, 0) gUnpack _c _cc _b = U1 -- Instances derived using Generic instance ( BitPack a , BitPack b ) => BitPack (Either a b) instance BitPack a => BitPack (Maybe a) #if MIN_VERSION_base(4,12,0) instance BitPack a => BitPack (Complex a) instance BitPack a => BitPack (Down a) #endif -- | Zero-extend a 'Bool'ean value to a 'BitVector' of the appropriate size. -- -- >>> boolToBV True :: BitVector 6 -- 00_0001 -- >>> boolToBV False :: BitVector 6 -- 00_0000 boolToBV :: KnownNat n => Bool -> BitVector (n + 1) boolToBV = zeroExtend . pack -- | Convert a Bool to a Bit boolToBit :: Bool -> Bit boolToBit = bitCoerce -- | Convert a Bool to a Bit bitToBool :: Bit -> Bool bitToBool = bitCoerce -- Derive the BitPack instance for tuples of size 3 to 62 deriveBitPackTuples ''BitPack ''BitSize 'pack 'unpack
/- ----------------------------------------------------------------------- Basic properties of LeanCat. ----------------------------------------------------------------------- -/ import ..c1_basic import ..c2_limits import ..c3_wtypes import ..c4_topoi namespace qp open stdaux universe variables ℓ' ℓ ℓobj ℓhom /- ----------------------------------------------------------------------- Constant homs. ----------------------------------------------------------------------- -/ /-! #brief A constant hom in LeanCat. -/ definition LeanCat.const_hom {X Y : LeanCat.{ℓ}^.obj} (y : Y) : LeanCat^.hom X Y | x := y /- ----------------------------------------------------------------------- Limits and colimits. ----------------------------------------------------------------------- -/ /-! #brief LeanCat has all limits. -/ instance LeanCat.HasAllLimits : HasAllLimits.{ℓobj ℓhom} LeanCat.{max ℓ ℓobj} := { has_limit := λ X L , HasLimit.show { g : ∀ (x : X^.obj), L^.obj x // ∀ {x₁ x₂ : X^.obj} (f : X^.hom x₁ x₂) , g x₂ = L^.hom f (g x₁) } (λ x g, g^.val x) (λ x₁ x₂ f, funext (λ g, g^.property f)) (λ C hom ωhom c , { val := λ x, hom x c , property := λ x₁ x₂ f, begin rw ωhom f, trivial end }) (λ C hom ωhom x, rfl) (λ C hom ωhom f ωf , funext (λ c, subtype.eq (funext (λ x, eq.symm (by apply congr_fun (ωf x) c))))) } /-! #brief The equivalence relation underlying colimits in LeanCat. -/ definition LeanCat.HasAllCoLimits.prop {X : Cat.{ℓobj ℓhom}} (L : Fun X LeanCat.{max ℓ ℓobj}) (a b : (Σ (x : X^.obj), L^.obj x)) : Prop := ∃ (f : X^.hom a^.fst b^.fst), b^.snd = L^.hom f a^.snd /-! #brief LeanCat has all co-limits. -/ instance LeanCat.HasAllCoLimits : HasAllCoLimits.{ℓobj ℓhom} LeanCat.{max ℓ ℓobj} := { has_colimit := λ X L , HasCoLimit.show (quot (LeanCat.HasAllCoLimits.prop L)) (λ x Lx, quot.mk _ {fst := x, snd := Lx}) (λ x₁ x₂ f, funext (λ Lx, quot.sound (exists.intro f rfl))) (λ C hom ωhom , let f : (Σ (x : X^.obj), L^.obj x) → C := λ Lx, hom Lx^.fst Lx^.snd in let ωf : ∀ (a b : Σ (x : ⟦X⟧), L^.obj x) , LeanCat.HasAllCoLimits.prop L a b → f a = f b := λ a b ωab , begin dsimp, cases ωab with g ωg, rw [ωg, ωhom g], trivial end in quot.lift f ωf) (λ C hom ωhom x, rfl) (λ C hom ωhom f ωf , funext (quot.ind (begin intro Lx, cases Lx with x Lx, apply eq.symm (congr_fun (ωf x) Lx) end))) } /- ----------------------------------------------------------------------- Limits and colimits in over/under categories. ----------------------------------------------------------------------- -/ /-! #brief Structure hom for colimits in OverCat LeanCat. -/ definition LeanCat.Over.HasCoLimit.colim_hom (B : LeanCat.{max ℓ ℓobj}^.obj) {X : Cat.{ℓobj ℓhom}} (L : Fun X (OverCat LeanCat B)) : LeanCat^.hom (colimit (OverFun.out LeanCat B □□ L)) B := let f : (Σ (x : X^.obj), (L^.obj x)^.obj) → B := λ x, (L^.obj x^.fst)^.hom x^.snd in quot.lift f begin intros a b, cases a with xa a, cases b with xb b, intro ω, cases ω with h ωb, dsimp at h, dsimp at ωb, subst ωb, apply congr_fun (L^.hom h)^.triangle a end /-! #brief OverCat LeanCat has all co-limits. -/ instance LeanCat.Over.HasCoLimit (B : LeanCat.{max ℓ ℓobj}^.obj) {X : Cat.{ℓobj ℓhom}} (L : Fun X (OverCat LeanCat B)) : HasCoLimit L := HasCoLimit.show { obj := colimit (OverFun.out LeanCat B □□ L) , hom := LeanCat.Over.HasCoLimit.colim_hom B L } (λ x, { hom := λ Lx, quot.mk _ { fst := x, snd := Lx } , triangle := sorry }) (λ x₁ x₂ f, begin apply OverHom.eq, apply funext, intro Lx, apply quot.sound, apply exists.intro f, trivial end) sorry sorry sorry instance LeanCat.Over.HasAllCoLimits (B : LeanCat.{max ℓ ℓobj}^.obj) : HasAllCoLimits.{ℓobj ℓhom} (OverCat LeanCat.{max ℓ ℓobj} B) := { has_colimit := @LeanCat.Over.HasCoLimit B } /-! #brief Handy simplifier. -/ theorem LeanCat.Over.HasCoLimit.obj (B : LeanCat.{max ℓ ℓobj}^.obj) {X : Cat.{ℓobj ℓhom}} (L : Fun X (OverCat LeanCat B)) : (colimit L)^.obj = colimit (OverFun.out LeanCat B □□ L) := rfl /- ----------------------------------------------------------------------- Products. ----------------------------------------------------------------------- -/ /-! #brief LeanCat has all products. -/ instance LeanCat.HasProduct {A : Type ℓ'} (factor : A → LeanCat.{max ℓ ℓ'}^.obj) : HasProduct LeanCat.{max ℓ ℓ'} factor := HasProduct.show LeanCat factor (∀ (a : A), factor a) (λ a fa, fa a) (λ T f t a, f a t) (λ T f a, rfl) (λ T f h ωh , begin apply funext, intro t, apply funext, intro a, rw ωh, trivial end) /-! #brief LeanCat has all products. -/ instance LeanCat.HasAllProducts : HasAllProducts.{ℓ'} LeanCat.{max ℓ ℓ'} := { has_product := @LeanCat.HasProduct } /-! #brief Finite product type in LeanCat. -/ definition ListProd : ∀ (TT : list LeanCat.{ℓ}^.obj) , LeanCat.{ℓ}^.obj | [] := punit | [T] := T | (T :: TT) := T × ListProd TT /-! #brief A fancy way of mapping through a ListProd. -/ definition {ℓb ℓx ℓy} ListProd.map {Ba : Type ℓb} {Tx : Ba → Type ℓx} {Ty : Ba → Type ℓy} (f : ∀ (b : Ba), Tx b → Ty b) : ∀ (BB : list Ba) , ListProd (list.map Tx BB) → ListProd (list.map Ty BB) | [] _ := punit.star | [Ba] x := f Ba x | (Ba :: Ba₀ :: BB) (prod.mk x xx) := (f Ba x, @ListProd.map (Ba₀ :: BB) xx) /-! #brief Projection from finite product type in LeanCat. -/ definition ListProd.π : ∀ (TT : list LeanCat.{ℓ}^.obj) (n : fin (list.length TT)) (x : ListProd TT) , list.get TT n | [] n x := fin.zero_elim n | [T] (fin.mk 0 ω0) X := X | [T] (fin.mk (nat.succ n) ωn) X := false.rec _ begin cases ωn, cases a end | (T :: T₁ :: TT) (fin.mk 0 ω0) X := X^.fst | (T :: T₁ :: TT) (fin.mk (nat.succ n) ωn) X := ListProd.π (T₁ :: TT) { val := n, is_lt := nat.lt_of_succ_lt_succ ωn } X^.snd /-! #brief Enumerating a map into a finite product. -/ definition ListProd.univ : ∀ (TT : list LeanCat.{ℓ}^.obj) (S : LeanCat.{ℓ}^.obj) (f : ∀ (n : ℕ) (ωn : n < list.length TT) , S → list.get TT { val := n, is_lt := ωn }) , S → ListProd TT | [] S f s := punit.star | [T] S f s := f 0 (fin_of 0)^.is_lt s | (T :: T₁ :: TT) S f s := ( f 0 (fin_of 0)^.is_lt s , ListProd.univ (T₁ :: TT) S (λ n ωn s', f (nat.succ n) (nat.succ_lt_succ ωn) s') s ) /-! #brief Factoring property of the universal map. -/ definition ListProd.univ.factor : ∀ {TT : list LeanCat.{ℓ}^.obj} {S : LeanCat.{ℓ}^.obj} {f : ∀ (n : ℕ) (ωn : n < list.length TT) , S → list.get TT { val := n, is_lt := ωn }} {n : ℕ} {ωn : n < list.length TT} {s : S} , f n ωn s = ListProd.π TT { val := n, is_lt := ωn } (ListProd.univ TT S f s) | [] S f n ωn s := by cases ωn | [T] S f 0 ω0 s := rfl | [T] S f (nat.succ n) ωn s := false.rec _ begin cases ωn, cases a end | (T :: T₁ :: TT) S f 0 ω0 s := rfl | (T :: T₁ :: TT) S f (nat.succ n) ωn s := begin refine eq.trans _ (@ListProd.univ.factor (T₁ :: TT) S _ n _ s), trivial end /-! #brief LeanCat has all finite products. -/ instance LeanCat.HasFinProduct (factor : list LeanCat.{ℓ}^.obj) : HasFinProduct LeanCat factor := HasProduct.show LeanCat (list.get factor) (ListProd factor) (ListProd.π factor) (λ T f, ListProd.univ factor T (λ n ωn, f { val := n, is_lt := ωn })) (λ T f n , begin apply funext, intro t, cases n with n ωn, refine eq.trans _ (ListProd.univ.factor), trivial end) (λ T f h ωh , begin assert ωf : f = λ n t, ListProd.π factor n (h t), { apply funext @ωh }, subst ωf, apply funext, intro t, induction factor with T factor rec, { apply punit.uniq }, cases factor with T₁ factor, { trivial }, { apply prod.eq, { trivial }, { refine eq.trans _ (rec (λ t, (h t)^.snd) _), { trivial }, { intro n, trivial } } } end) /-! #brief LeanCat has all finite products. -/ instance LeanCat.HasAllFinProducts : HasAllFinProducts LeanCat.{ℓ} := { has_product := LeanCat.HasFinProduct } /- ----------------------------------------------------------------------- Co-products. ----------------------------------------------------------------------- -/ /-! #brief LeanCat has all co-products. -/ instance LeanCat.HasCoProduct {A : Type ℓ'} (factor : A → LeanCat.{max ℓ ℓ'}^.obj) : HasCoProduct LeanCat.{max ℓ ℓ'} factor := HasCoProduct.show LeanCat factor (Σ (a : A), factor a) (sigma.mk) (λ T f af, f af^.fst af^.snd) (λ T f a, rfl) (λ T f h ωh , begin apply funext, intro af, cases af with a f, rw ωh, trivial end) /-! #brief LeanCat has all co-products. -/ instance LeanCat.HasAllCoProducts : HasAllCoProducts.{ℓ'} LeanCat.{max ℓ ℓ'} := { has_coproduct := @LeanCat.HasCoProduct } /-! #brief Finite sum type in LeanCat. -/ definition ListSum : ∀ (TT : list LeanCat.{ℓ}^.obj) , LeanCat.{ℓ}^.obj | [] := pempty | [T] := T | (T :: TT) := sum T (ListSum TT) /-! #brief A fancy way of mapping through a ListSum. -/ definition {ℓb ℓx ℓy} ListSum.map {Ba : Type ℓb} {Tx : Ba → Type ℓx} {Ty : Ba → Type ℓy} : ∀ (BB : list Ba) (f : ∀ (n : ℕ) (ωn : n < list.length BB) , Tx (list.get BB {val := n, is_lt := ωn}) → Ty (list.get BB {val := n, is_lt := ωn})) , ListSum (list.map Tx BB) → ListSum (list.map Ty BB) | [] f e := by cases e | [Ba] f x := f 0 fin.zero^.is_lt x | (Ba :: Ba₀ :: BB) f (sum.inl x) := sum.inl (f 0 fin.zero^.is_lt x) | (Ba :: Ba₀ :: BB) f (sum.inr xx) := sum.inr (ListSum.map (Ba₀ :: BB) (λ n ωn, f (nat.succ n) (nat.succ_le_succ ωn)) xx) /-! #brief Inclusion into finite sum type in LeanCat. -/ definition ListSum.ι : ∀ (TT : list LeanCat.{ℓ}^.obj) (n : fin (list.length TT)) (x : list.get TT n) , ListSum TT | [] n x := fin.zero_elim n | [T] (fin.mk 0 ω0) x := x | [T] (fin.mk (nat.succ n) ωn) x := false.rec _ begin cases ωn, cases a end | (T :: T₁ :: TT) (fin.mk 0 ω0) x := sum.inl x | (T :: T₁ :: TT) (fin.mk (nat.succ n) ωn) x := sum.inr (ListSum.ι (T₁ :: TT) { val := n, is_lt := nat.lt_of_succ_lt_succ ωn } x) /-! #brief Enumerating a map out of a finite sum. -/ definition ListSum.univ : ∀ (TT : list LeanCat.{ℓ}^.obj) (S : LeanCat.{ℓ}^.obj) (f : ∀ (n : ℕ) (ωn : n < list.length TT) , list.get TT { val := n, is_lt := ωn } → S) , ListSum TT → S | [] S f e := by cases e | [T] S f s := f 0 (fin_of 0)^.is_lt s | (T :: T₁ :: TT) S f (sum.inl s) := f 0 (fin_of 0)^.is_lt s | (T :: T₁ :: TT) S f (sum.inr s) := ListSum.univ (T₁ :: TT) S (λ n ωn s', f (nat.succ n) (nat.succ_lt_succ ωn) s') s /-! #brief Factoring property of the universal map. -/ definition ListSum.univ.factor : ∀ {TT : list LeanCat.{ℓ}^.obj} {S : LeanCat.{ℓ}^.obj} {f : ∀ (n : ℕ) (ωn : n < list.length TT) , list.get TT { val := n, is_lt := ωn } → S} {n : ℕ} {ωn : n < list.length TT} {s : list.get TT { val := n, is_lt := ωn }} , f n ωn s = ListSum.univ TT S f (ListSum.ι TT { val := n, is_lt := ωn } s) | [] S f n ωn s := by cases ωn | [T] S f 0 ω0 s := rfl | [T] S f (nat.succ n) ωn s := false.rec _ begin cases ωn, cases a end | (T :: T₁ :: TT) S f 0 ω0 s := rfl | (T :: T₁ :: TT) S f (nat.succ n) ωn s := begin refine eq.trans _ (@ListSum.univ.factor (T₁ :: TT) S _ n _ s), trivial end /-! #brief LeanCat has all finite products. -/ instance LeanCat.HasFinCoProduct (factor : list LeanCat.{ℓ}^.obj) : HasFinCoProduct LeanCat factor := HasCoProduct.show LeanCat (list.get factor) (ListSum factor) (ListSum.ι factor) (λ T f, ListSum.univ factor T (λ n ωn, f { val := n, is_lt := ωn })) (λ T f n , begin apply funext, intro t, cases n with n ωn, refine eq.trans _ (ListSum.univ.factor), trivial end) (λ T f h ωh , begin assert ωf : f = λ n t, h (ListSum.ι factor n t), { apply funext @ωh }, subst ωf, apply funext, intro t, induction factor with T factor rec, { cases t }, cases factor with T₁ factor, { trivial }, { cases t, { trivial }, { refine eq.trans _ (rec (λ a, (h (sum.inr a))) _ _), { trivial }, { intro n, trivial } } } end) /-! #brief LeanCat has all finite products. -/ instance LeanCat.HasAllFinCoProducts : HasAllFinCoProducts LeanCat.{ℓ} := { has_coproduct := LeanCat.HasFinCoProduct } /- ----------------------------------------------------------------------- Pullbacks. ----------------------------------------------------------------------- -/ /-! #brief LeanCat has all pullbacks. -/ instance LeanCat.HasPullback {base : LeanCat.{ℓ}^.obj} {factor : list LeanCat.{ℓ}^.obj} {T : LeanCat.{ℓ}^.obj} (maps : @HomsIn LeanCat (base :: factor) T) : HasPullback LeanCat maps := HasPullback.show LeanCat.{ℓ} maps { p : finproduct LeanCat (base :: factor) // ∀ (n : fin (list.length (base :: factor))) , HomsIn.get maps (fin_of 0) (finproduct.π LeanCat (base :: factor) (fin_of 0) p) = HomsIn.get maps n (finproduct.π LeanCat (base :: factor) n p) } (λ p, HomsIn.get maps (fin_of 0) (finproduct.π LeanCat (base :: factor) (fin_of 0) p^.val)) (HomsOut.comp (finproduct.cone LeanCat (base :: factor))^.Proj (λ p, p^.val)) begin cases maps with _ m_base _ maps, -- apply HomsList.eq, -- { trivial }, -- induction maps with _ m₁ _ maps rec, -- { trivial }, exact sorry end sorry sorry sorry instance LeanCat.HasAllPullbacks : HasAllPullbacks LeanCat.{ℓ} := { has_pullback := λ base factor T maps , LeanCat.HasPullback maps } /-! #brief A handy wrapper. -/ definition LeanCat.BaseChangeFun {X Y : LeanCat.{ℓ}^.obj} (f : LeanCat.{ℓ}^.hom X Y) : Fun (OverCat LeanCat Y) (OverCat LeanCat X) := @BaseChangeFun LeanCat X Y f (HasAllPullbacks.HasPullbacksAlong LeanCat f) /- ----------------------------------------------------------------------- Products in OverCat LeanCat. ----------------------------------------------------------------------- -/ /-! #brief OverCat LeanCat has finite products. -/ instance LeanCat.Over.HasFinProduct (T₀ : LeanCat.{ℓ}^.obj) (factor : list (OverCat LeanCat T₀)^.obj) : HasFinProduct (OverCat LeanCat T₀) factor := OverCat.HasFinProduct LeanCat.{ℓ} T₀ factor /- ----------------------------------------------------------------------- Exponentials. ----------------------------------------------------------------------- -/ /-! #brief LeanCat has exponential objects. -/ instance LeanCat.HasExp (X Y : LeanCat.{ℓ}^.obj) : @HasExp LeanCat X Y := { exp := Y → X , ev := λ exp_Y_HasFinProduct p , let f := @finproduct.π _ _ exp_Y_HasFinProduct (@fin_of 1 0) in let y := @finproduct.π _ _ exp_Y_HasFinProduct (@fin_of 0 1) in f p (y p) , univ := λ Z Z_Y_HasFinProduct e z y , e (finproduct.iso (LeanCat.HasFinProduct [Z, Y]) Z_Y_HasFinProduct (z, y)) , factor := λ exp_Y_HasFinProduct Z Z_Y_HasFinProduct e , begin apply funext, intro zy, rw LeanCat.simp_circ, dsimp, exact sorry end , uniq := λ exp_Y_HasFinProduct Z Z_Y_HasFinProduct e u ωu , begin apply funext, intro z, apply funext, intro y, rw ωu, exact sorry end } /- ----------------------------------------------------------------------- Exponentials in OverCat LeanCat. ----------------------------------------------------------------------- -/ /-! #brief LeanCat has exponential objects. -/ definition LeanCat.Over.exp (T₀ : LeanCat.{ℓ}^.obj) (T S : (OverCat LeanCat T₀)^.obj) : OverObj LeanCat.{ℓ} T₀ := { obj := Σ (t₀ : T₀) , {s : S^.dom // S^.hom s = t₀} → {t : T^.obj // T^.hom t = t₀} , hom := sigma.fst } /-! #brief LeanCat has exponential objects. -/ instance LeanCat.Over.HasExp (T₀ : LeanCat.{ℓ}^.obj) (X Y : (OverCat LeanCat T₀)^.obj) : @HasExp (OverCat LeanCat T₀) X Y := { exp := LeanCat.Over.exp T₀ X Y , ev := λ p_HasProd , { hom := λ p, let f := (@finproduct.π (OverCat LeanCat T₀) [LeanCat.Over.exp T₀ X Y, Y] p_HasProd (@fin_of 1 0))^.hom p in let y := (@finproduct.π (OverCat LeanCat T₀) [LeanCat.Over.exp T₀ X Y, Y] p_HasProd (@fin_of 0 1))^.hom p in (f^.snd { val := y, property := sorry })^.val , triangle := sorry } , univ := λ A A_HasProd f , let a_y : ∀ (a : A^.obj) (y : {s // Y^.hom s = A^.hom a}) , OverObj.dom (finproduct (OverCat LeanCat T₀) [A, Y]) := λ a y , { val := (a, y^.val) , property := begin intro nωn, cases nωn with n ωn, cases n with n, { trivial }, cases n with n, { apply eq.symm y^.property }, apply nat.not_lt_add_right n 2 ωn end } in let a_y' := λ a y, ((finproduct.iso (LeanCat.Over.HasFinProduct T₀ [A, Y]) A_HasProd)^.hom (a_y a y)) in { hom := λ a , ⟨ A^.hom a , λ y, { val := f^.hom (a_y' a y) , property := begin refine eq.trans (congr_fun (eq.symm f^.triangle) (a_y' a y)) _, exact sorry end } ⟩ , triangle := sorry } , factor := λ A p_HasProd A_HasProd e , sorry , uniq := λ exp_Y_HasFinProduct Z Z_Y_HasFinProduct e u ωu , sorry } /-! #brief OverCat LeanCat has all exponentials. -/ instance LeanCat.Over.HasAllExp (T₀ : LeanCat.{ℓ}^.obj) : @HasAllExp (OverCat LeanCat T₀) := { has_exp := LeanCat.Over.HasExp T₀ } /-! #brief LeanCat has exponentials in all slices. -/ instance LeanCat.HasAllLocalExp : HasAllLocalExp LeanCat.{ℓ} := { has_exp := LeanCat.Over.HasExp } /- ----------------------------------------------------------------------- Subobject classifiers. ----------------------------------------------------------------------- -/ /-! #brief Axiom of choice gives LeanCat a subobject classifier. -/ noncomputable instance LeanCat.HasSubobjClass : HasSubobjClass LeanCat.{ℓ} := HasSubobjClass.show (λ LeanCat_HasFinal, Lean.LevelMax Prop) (λ LeanCat_HasFinal, λ u, Lean.LevelMax.lift true) (λ LeanCat_HasFinal U X m m_Monic, λ x, Lean.LevelMax.lift (∃ (u : U), m u = x)) (λ LeanCat_HasFinal U X V m m_Monic h ωh x , let u₀ : ∃ (u : U), m u = h x := begin apply of_iff_true, apply eq.to_iff, apply Lean.LevelMax.lift.inj, apply congr_fun ωh end in let u : ∃! (u : U), h x = m u := exists.elim u₀ (λ u ωu , exists_unique.intro u (eq.symm ωu) (λ u' ωu', LeanCat.Monic.inj m_Monic (eq.symm (eq.trans ωu ωu')))) in unique_choice u) (λ LeanCat_HasFinal U X m m_Monic , begin apply funext, intro u, apply congr_arg Lean.LevelMax.lift, apply iff.to_eq, apply iff_true_intro, apply exists.intro u, trivial end) (λ LeanCat_HasFinal U V X m m_Monic h ωh , begin apply funext, intro v, dsimp, unfold LeanCat SortCat, dsimp, generalize (of_iff_true (eq.to_iff (Lean.LevelMax.lift.inj (congr_fun ωh v)))) ω, intro ω, cases ω with u ωu, refine eq.trans (eq.symm _) (eq.symm (congr_arg m unique_choice.simp)), exact ωu end) (λ LeanCat_HasFinal U V X m m_Monic h ωh , begin apply funext, intro v, generalize (of_iff_true (eq.to_iff (Lean.LevelMax.lift.inj (congr_fun ωh v)))) ω, intro ω, cases ω with u ωu, refine eq.trans _ (eq.symm unique_choice.simp), apply LeanCat.Monic.inj m_Monic, exact eq.symm ωu end) (λ LeanCat_HasFinal U X m m_Monic char' char'_IsPullback , sorry) -- , char_uniq -- := λ LeanCat_HasFinal U X m m_Monic char' ωchar' -- , let char'' : X → Prop -- := λ x, Lean.LevelMax.cases_on (char' x) (λ P, P) -- in begin -- apply funext, intro x, -- assert ωchar'' : char' x = Lean.LevelMax.lift (Lean.LevelMax.cases_on (char' x) (λ P, P)), -- { generalize (char' x) char'_x, -- intro char'_x, cases char'_x, -- trivial, -- }, -- refine eq.trans ωchar'' (congr_arg Lean.LevelMax.lift _), -- apply iff.to_eq, -- apply iff.intro, -- { intro ωP_x, exact sorry -- }, -- { intro ωu, cases ωu with u ωu, -- subst ωu, -- -- true because ωchar' implies char' (m u) = Lean.LevelMax.lift true. -- exact sorry -- } -- end -- } /- ----------------------------------------------------------------------- Natural numbers object. ----------------------------------------------------------------------- -/ /-! #brief LeanCat has an NNO. -/ instance LeanCat.HasNNO : @HasNNO LeanCat.{ℓ} LeanCat.HasFinal := { nn := Lean.LevelMax ℕ , zero := λ u, Lean.LevelMax.lift 0 , succ := Lean.LevelMax.map nat.succ , univ := λ A z s n, nat.rec_on (Lean.LevelMax.unlift n) (z punit.star) (λ n' a, s a) , comm_zero := λ A z s , begin apply funext, intro u, cases u, trivial end , comm_succ := λ A z s , begin apply funext, intro n, cases n with n, induction n with n rec, { trivial }, { apply congr_arg s, apply rec } end , uniq := λ A z s u' ωzero ωsucc , begin apply funext, intro n, cases n with n, induction n with n rec, { rw ωzero, trivial }, { refine eq.trans (eq.symm (congr_fun ωsucc (Lean.LevelMax.lift n))) _, apply congr_arg s rec } end } end qp
%% Copyright (C) 2022 Alex Vong %% %% This file is part of OctSymPy. %% %% OctSymPy 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 3 of the License, %% or (at your option) any later version. %% %% This software 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 software; see the file COPYING. %% If not, see <https://www.gnu.org/licenses/>. %% -*- texinfo -*- %% @documentencoding UTF-8 %% @defmethod @@sym piecewise (@var{cond1}, @var{val1}, @var{cond2}, @var{val2}, @dots{}) %% @defmethodx @@sym piecewise (@var{cond1}, @var{val1}, @var{cond2}, @var{val2}, @dots{}, @var{else_val}) %% Construct piecewise function. %% %% The returned piecewise function evaluates to @var{val1} if @var{cond1} %% holds, @var{val2} if @var{cond2} holds, @dots{} etc. In the case where none %% of the conditions hold, it evaluates to @var{else_val} if provided. If %% @var{else_val} is not provided, it evaluates to @code{nan}. %% %% Examples: %% @example %% @group %% syms x real %% f = piecewise (abs (x) < 1, exp (- 1 / (1 - x^2)), abs (x) >= 1, 0) %% @result{} f = (sym) %% ⎧ -1 %% ⎪ ────── %% ⎪ 2 %% ⎨ 1 - x %% ⎪ℯ for │x│ < 1 %% ⎪ %% ⎩ 0 otherwise %% @end group %% @end example %% %% For this piecewise function, we can omit the redundant condition at the end: %% @example %% @group %% syms x real %% f = piecewise (abs (x) < 1, exp (- 1 / (1 - x^2)), 0) %% @result{} f = (sym) %% ⎧ -1 %% ⎪ ────── %% ⎪ 2 %% ⎨ 1 - x %% ⎪ℯ for │x│ < 1 %% ⎪ %% ⎩ 0 otherwise %% @end group %% @end example %% %% @seealso{if} %% @end defmethod function f = piecewise (varargin) if nargin < 1 print_usage (); end cmd = {'def pack_args_without_else(args):' ' return [(val, cond) for cond, val in unflatten(args, 2)]' 'def pack_args(args):' ' if len(args) % 2 == 0:' ' return pack_args_without_else(args)' ' else:' ' return pack_args_without_else(args[:-1]) + [(args[-1], True)]' 'return Piecewise(*pack_args(_ins))' }; args = cellfun (@sym, varargin, 'UniformOutput', false); f = pycall_sympy__ (cmd, args{:}); end %!test %! % basic %! syms x real %! f = piecewise (abs (x) < 1, 1); %! assert (isnan (subs (f, -1))); %! assert (isequal (subs (f, 0), 1)); %! assert (isnan (subs (f, 1))); %!test %! % heaviside %! syms x real %! f = rewrite (heaviside (x, 1 / sym (2)), 'Piecewise'); %! g = piecewise (x < 0, 0, x == 0, 1 / sym (2), x > 0, 1); %! assert (logical (simplify (f == g))); %% FIXME: expand test suite, add SMT compat tests, ...
module Main import IdrisJvm.FFI import IdrisJvm.IO -- Returning an additional Nat to test that `par` returns a complex type correctly fibonacci : Integer -> (Nat, Integer) fibonacci 0 = (0, 0) fibonacci 1 = (1, 1) fibonacci n = let (fibNat1, fib1) = par $ fibonacci (n - 1) -- Evaluate in parallel using Java's ForkJoin (fibNat2, fib2) = par $ fibonacci (n - 2) -- Evaluate in parallel fibNat = fibNat1 + fibNat2 in (fibNat * 2, fib1 + fib2) shutdownExecutor : JVM_IO () shutdownExecutor = javacall (Static clz "shutdownExecutor") (JVM_IO ()) where clz = Class "io/github/mmhelloworld/idrisjvm/runtime/Concurrent" main : JVM_IO () main = do fork $ printLn "a" -- Run in a new thread using Java's ExecutorService fork $ printLn "b" -- Run in another thread fork $ printLn $ fibonacci 10 fork $ printLn "cde" fork $ printLn "fg" printLn "h" shutdownExecutor
State Before: α : Type u_1 inst✝³ : DecidableEq α inst✝² : SemilatticeSup α inst✝¹ : OrderBot α inst✝ : DecidableRel Disjoint s s₁ s₂ t t₁ t₂ u : Finset α a b c : α ⊢ c ∈ s ○ t ↔ ∃ a, a ∈ s ∧ ∃ b, b ∈ t ∧ Disjoint a b ∧ a ⊔ b = c State After: no goals Tactic: simp [disjSups, and_assoc]
||| Interfaces of basic containers. ||| ||| Copyright 2021, HATTORI, Hiroki ||| This file is released under the MIT license, see LICENSE for more detail. ||| module Data.Container.Interfaces import Data.Maybe %default total -- -------------------------------------------------------------------------- namespace Immutable public export interface Container a where 0 KeyTy : Type null : a -> Bool count : a -> Nat contains : KeyTy -> a -> Bool delete : KeyTy -> a -> a namespace Set public export interface Container a => Set a where 0 KeyTy : Type insert : KeyTy -> a -> a namespace Map public export interface Container a => Map a where 0 KeyTy : Type 0 ValTy : Type lookup : KeyTy -> a -> Maybe ValTy insert : KeyTy -> ValTy -> a -> a -- -------------------------------------------------------------------------- namespace Mutable public export interface MutableContainer m a where 0 KeyTy : Type null : a -> m Bool count : a -> m Nat contains : KeyTy -> a -> m Bool delete : KeyTy -> a -> m () namespace Set public export interface MutableContainer m a => MutableSet m a where 0 KeyTy : Type insert : KeyTy -> a -> m () namespace Map public export interface MutableContainer m a => MutableMap m a where 0 KeyTy : Type 0 ValTy : Type lookup : KeyTy -> a -> m (Maybe ValTy) insert : KeyTy -> ValTy -> a -> m () -- -------------------------------------------------------------------------- -- vim: tw=80 sw=2 expandtab :
header {* Address Graph *} theory Graph imports Main begin text {* This theory introduces the graph to be marked as a relation next on nodes (addresses). We assume that we have a special node nil (the null address). We have a node root from which we start marking the graph. We also assume that nil is not related by next to any node and any node is not related by next to nil. *} locale node = fixes nil :: "'node" fixes root :: "'node" locale graph = node + fixes "next" :: "('node \<times> 'node) set" assumes next_not_nil_left: "(!! x . (nil, x) \<notin> next)" assumes next_not_nil_right: "(!! x . (x, nil) \<notin> next)" begin text {* On lists of nodes we introduce two operations similar to existing hd and tl for getting the head and the tail of a list. The new function head applied to a nonempty list returns the head of the list, and it reurns nil when applied to the empty list. The function tail returns the tail of the list when applied to a non-empty list, and it returns the empty list otherwise. *} definition "head S \<equiv> (if S = [] then nil else (hd S))" definition "tail (S::'a list) \<equiv> (if S = [] then [] else (tl S))" theorem head_not_nil [simp]: "(head S \<noteq> nil) = (head S = hd S \<and> tail S = tl S \<and> hd S \<noteq> nil \<and> S \<noteq> [])" by (simp add: head_def tail_def) theorem nonempty_head [simp]: "head (x # S) = x" by (simp add: head_def) theorem nonempty_tail [simp]: "tail (x # S) = S" by (simp add: tail_def) definition (in graph) "reach x \<equiv> {y . (x, y) \<in> next\<^sup>* \<and> y \<noteq> nil}" theorem (in graph) reach_nil [simp]: "reach nil = {}" apply (simp add: reach_def, safe) apply (drule rtrancl_induct) by auto theorem (in graph) reach_next: "b \<in> reach a \<Longrightarrow> (b, c) \<in> next \<Longrightarrow> c \<in> reach a" apply (simp add: reach_def) by auto definition (in graph) "path S mrk \<equiv> {x . (\<exists> s . s \<in> S \<and> (s, x) \<in> next O (next \<inter> ((-mrk)\<times>(-mrk)))\<^sup>* )}" end end
library(googlesheets4); library(tidyverse); library(data.table); intentions <- read_sheet("intentions_sheet_url") intentions <- select(intentions, "Farm Name", "Field", "Actual Variety", "PLANTED ACRES", "Planter Operator","Planting Date", "LOT NUMBER") data <- intentions %>% rename("farm"="Farm Name") %>% rename("field" = "Field") %>% rename("variety" = "Actual Variety") %>% rename("acres" = "PLANTED ACRES") %>% rename("operator" = "Planter Operator") %>% rename("plantdate" = "Planting Date") %>% rename("lot" = "LOT NUMBER") no_timestamp <- data %>% filter(acres>0 & is.na(plantdate)) no_variety <- data %>% filter(acres>0 & is.na(variety)) no_ponumber <- data %>% filter(acres>0 & is.null(lot)) errors <- bind_rows(no_timestamp, no_variety, no_ponumber) errors<-data.frame(lapply(errors, as.character), stringsAsFactors=FALSE) write.table(errors, file="errors.csv", row.names=FALSE, na="", col.names = TRUE, sep=",")
theory Proof_1_3 imports HandDryer VCTheoryLemmas Extra begin theorem proof_1_3: "VC3 inv1 s0 hands_value" apply(simp only: VC3_def inv1_def R1_def dryer_def) apply(rule impI; rule conjI) proof - assume VC: " ((toEnvP s0 \<and> (\<forall>s1 s2. substate s1 s2 \<and> substate s2 s0 \<and> toEnvP s1 \<and> toEnvP s2 \<and> toEnvNum s1 s2 = hands \<and> getVarBool s1 hands = OFF \<and> getVarBool s1 (Suc (Suc 0)) = OFF \<and> getVarBool s2 hands = ON \<longrightarrow> (\<exists>s4. toEnvP s4 \<and> substate s2 s4 \<and> substate s4 s0 \<and> toEnvNum s2 s4 \<le> hands \<and> getVarBool s4 (Suc (Suc 0)) = ON \<and> (\<forall>s3. toEnvP s3 \<and> substate s2 s3 \<and> substate s3 s4 \<and> s3 \<noteq> s4 \<longrightarrow> getVarBool s3 hands = ON)))) \<and> extraInv s0) \<and> env (setVarAny s0 hands_value) hands_value \<and> getPstate (setVarAny s0 hands_value) Ctrl = waiting \<and> getVarBool (setVarAny s0 hands_value) hands \<noteq> ON " show "toEnvP (toEnv (setVarBool (setVarAny s0 hands_value) (Suc (Suc 0)) OFF)) \<and> (\<forall>s1 s2. substate s1 s2 \<and> substate s2 (toEnv (setVarBool (setVarAny s0 hands_value) (Suc (Suc 0)) OFF)) \<and> toEnvP s1 \<and> toEnvP s2 \<and> toEnvNum s1 s2 = hands \<and> getVarBool s1 hands = OFF \<and> getVarBool s1 (Suc (Suc 0)) = OFF \<and> getVarBool s2 hands = ON \<longrightarrow> (\<exists>s4. toEnvP s4 \<and> substate s2 s4 \<and> substate s4 (toEnv (setVarBool (setVarAny s0 hands_value) (Suc (Suc 0)) OFF)) \<and> toEnvNum s2 s4 \<le> hands \<and> getVarBool s4 (Suc (Suc 0)) = ON \<and> (\<forall>s3. toEnvP s3 \<and> substate s2 s3 \<and> substate s3 s4 \<and> s3 \<noteq> s4 \<longrightarrow> getVarBool s3 hands = ON)))" apply(rule conjI) apply(simp) proof(rule allI; rule allI; rule impI) fix s1 s2 assume req_prems: " substate s1 s2 \<and> substate s2 (toEnv (setVarBool (setVarAny s0 hands_value) (Suc (Suc 0)) OFF)) \<and> toEnvP s1 \<and> toEnvP s2 \<and> toEnvNum s1 s2 = hands \<and> getVarBool s1 hands = OFF \<and> getVarBool s1 (Suc (Suc 0)) = OFF \<and> getVarBool s2 hands = ON " show " \<exists>s4. toEnvP s4 \<and> substate s2 s4 \<and> substate s4 (toEnv (setVarBool (setVarAny s0 hands_value) (Suc (Suc 0)) OFF)) \<and> toEnvNum s2 s4 \<le> hands \<and> getVarBool s4 (Suc (Suc 0)) = ON \<and> (\<forall>s3. toEnvP s3 \<and> substate s2 s3 \<and> substate s3 s4 \<and> s3 \<noteq> s4 \<longrightarrow> getVarBool s3 hands = ON)" proof cases assume 1: "s2 = (toEnv (setVarBool (setVarAny s0 hands_value) (Suc (Suc 0)) OFF))" have " (toEnvP s2 \<and> substate s2 s2 \<and> substate s2 (toEnv (setVarBool (setVarAny s0 hands_value) (Suc (Suc 0)) OFF)) \<and> toEnvNum s2 s2 \<le> hands \<and> getVarBool s2 (Suc (Suc 0)) = ON) \<and> (\<forall>s3. toEnvP s3 \<and> substate s2 s3 \<and> substate s3 s2 \<and> s3 \<noteq> s2 \<longrightarrow> getVarBool s3 hands = ON)" proof from 1 VC req_prems show "toEnvP s2 \<and> substate s2 s2 \<and> substate s2 (toEnv (setVarBool (setVarAny s0 hands_value) (Suc (Suc 0)) OFF)) \<and> toEnvNum s2 s2 \<le> hands \<and> getVarBool s2 (Suc (Suc 0)) = ON" by auto next from substate_asym show " \<forall>s3. toEnvP s3 \<and> substate s2 s3 \<and> substate s3 s2 \<and> s3 \<noteq> s2 \<longrightarrow> getVarBool s3 hands = ON" by auto qed thus ?thesis by blast next assume 1: "s2 \<noteq> (toEnv (setVarBool (setVarAny s0 hands_value) (Suc (Suc 0)) OFF))" with req_prems have 2: "substate s2 s0" by (simp split: if_splits) from VC req_prems 2 obtain "\<exists>s4. toEnvP s4 \<and> substate s2 s4 \<and> substate s4 s0 \<and> toEnvNum s2 s4 \<le> hands \<and> getVarBool s4 (Suc (Suc 0)) = ON \<and> (\<forall>s3. toEnvP s3 \<and> substate s2 s3 \<and> substate s3 s4 \<and> s3 \<noteq> s4 \<longrightarrow> getVarBool s3 hands = ON)"by auto then obtain s4 where 3: "toEnvP s4 \<and> substate s2 s4 \<and> substate s4 s0 \<and> toEnvNum s2 s4 \<le> hands \<and> getVarBool s4 (Suc (Suc 0)) = ON \<and> (\<forall>s3. toEnvP s3 \<and> substate s2 s3 \<and> substate s3 s4 \<and> s3 \<noteq> s4 \<longrightarrow> getVarBool s3 hands = ON)" .. have "toEnvP s4 \<and> substate s2 s4 \<and> substate s4 (toEnv (setVarBool (setVarAny s0 hands_value) (Suc (Suc 0)) OFF)) \<and> toEnvNum s2 s4 \<le> hands \<and> getVarBool s4 (Suc (Suc 0)) = ON \<and> (\<forall>s3. toEnvP s3 \<and> substate s2 s3 \<and> substate s3 s4 \<and> s3 \<noteq> s4 \<longrightarrow> getVarBool s3 hands = ON)" using 3 by auto thus ?thesis .. qed qed next assume VC: " ((toEnvP s0 \<and> (\<forall>s1 s2. substate s1 s2 \<and> substate s2 s0 \<and> toEnvP s1 \<and> toEnvP s2 \<and> toEnvNum s1 s2 = hands \<and> getVarBool s1 hands = OFF \<and> getVarBool s1 (Suc (Suc 0)) = OFF \<and> getVarBool s2 hands = ON \<longrightarrow> (\<exists>s4. toEnvP s4 \<and> substate s2 s4 \<and> substate s4 s0 \<and> toEnvNum s2 s4 \<le> hands \<and> getVarBool s4 (Suc (Suc 0)) = ON \<and> (\<forall>s3. toEnvP s3 \<and> substate s2 s3 \<and> substate s3 s4 \<and> s3 \<noteq> s4 \<longrightarrow> getVarBool s3 hands = ON)))) \<and> extraInv s0) \<and> env (setVarAny s0 hands_value) hands_value \<and> getPstate (setVarAny s0 hands_value) Ctrl = waiting \<and> getVarBool (setVarAny s0 hands_value) hands \<noteq> ON " print_state with extra3 show "extraInv (toEnv (setVarBool (setVarAny s0 hands_value) (Suc (Suc 0)) OFF))" by (auto simp add: VC3_def dryer_def) qed end
/- Copyright (c) 2022 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller ! This file was ported from Lean 3 source module combinatorics.simple_graph.trails ! leanprover-community/mathlib commit edaaaa4a5774e6623e0ddd919b2f2db49c65add4 ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathlib.Combinatorics.SimpleGraph.Connectivity import Mathlib.Data.Nat.Parity /-! # Trails and Eulerian trails This module contains additional theory about trails, including Eulerian trails (also known as Eulerian circuits). ## Main definitions * `SimpleGraph.Walk.IsEulerian` is the predicate that a trail is an Eulerian trail. * `SimpleGraph.Walk.IsTrail.even_countp_edges_iff` gives a condition on the number of edges in a trail that can be incident to a given vertex. * `SimpleGraph.Walk.IsEulerian.even_degree_iff` gives a condition on the degrees of vertices when there exists an Eulerian trail. * `SimpleGraph.Walk.IsEulerian.card_odd_degree` gives the possible numbers of odd-degree vertices when there exists an Eulerian trail. ## Todo * Prove that there exists an Eulerian trail when the conclusion to `SimpleGraph.Walk.IsEulerian.card_odd_degree` holds. ## Tags Eulerian trails -/ namespace SimpleGraph variable {V : Type _} {G : SimpleGraph V} namespace Walk /-- The edges of a trail as a finset, since each edge in a trail appears exactly once. -/ @[reducible] def IsTrail.edgesFinset {u v : V} {p : G.Walk u v} (h : p.IsTrail) : Finset (Sym2 V) := ⟨p.edges, h.edges_nodup⟩ #align simple_graph.walk.is_trail.edges_finset SimpleGraph.Walk.IsTrail.edgesFinset variable [DecidableEq V] theorem IsTrail.even_countp_edges_iff {u v : V} {p : G.Walk u v} (ht : p.IsTrail) (x : V) : Even (p.edges.countp fun e => x ∈ e) ↔ u ≠ v → x ≠ u ∧ x ≠ v := by induction' p with u u v w huv p ih · simp · rw [cons_isTrail_iff] at ht specialize ih ht.1 simp only [List.countp_cons, Ne.def, edges_cons, Sym2.mem_iff] split_ifs with h · rw [decide_eq_true_eq] at h obtain (rfl | rfl) := h · rw [Nat.even_add_one, ih] simp only [huv.ne, imp_false, Ne.def, not_false_iff, true_and_iff, not_forall, Classical.not_not, exists_prop, eq_self_iff_true, not_true, false_and_iff, and_iff_right_iff_imp] rintro rfl rfl exact G.loopless _ huv · rw [Nat.even_add_one, ih, ← not_iff_not] simp only [huv.ne.symm, Ne.def, eq_self_iff_true, not_true, false_and_iff, not_forall, not_false_iff, exists_prop, and_true_iff, Classical.not_not, true_and_iff, iff_and_self] rintro rfl exact huv.ne · rw [decide_eq_true_eq, not_or] at h simp only [h.1, h.2, not_false_iff, true_and_iff, add_zero, Ne.def] at ih⊢ rw [ih] constructor <;> · rintro h' h'' rfl simp only [imp_false, eq_self_iff_true, not_true, Classical.not_not] at h' cases h' simp only [not_true, and_false, false_and] at h #align simple_graph.walk.is_trail.even_countp_edges_iff SimpleGraph.Walk.IsTrail.even_countp_edges_iff /-- An *Eulerian trail* (also known as an "Eulerian path") is a walk `p` that visits every edge exactly once. The lemma `SimpleGraph.Walk.IsEulerian.IsTrail` shows that these are trails. Combine with `p.IsCircuit` to get an Eulerian circuit (also known as an "Eulerian cycle"). -/ def IsEulerian {u v : V} (p : G.Walk u v) : Prop := ∀ e, e ∈ G.edgeSet → p.edges.count e = 1 #align simple_graph.walk.is_eulerian SimpleGraph.Walk.IsEulerian theorem IsEulerian.isTrail {u v : V} {p : G.Walk u v} (h : p.IsEulerian) : p.IsTrail := by rw [isTrail_def, List.nodup_iff_count_le_one] intro e by_cases he : e ∈ p.edges · exact (h e (edges_subset_edgeSet _ he)).le · simp [he] #align simple_graph.walk.is_eulerian.is_trail SimpleGraph.Walk.IsEulerian.isTrail theorem IsEulerian.mem_edges_iff {u v : V} {p : G.Walk u v} (h : p.IsEulerian) {e : Sym2 V} : e ∈ p.edges ↔ e ∈ G.edgeSet := ⟨fun h => p.edges_subset_edgeSet h, fun he => by simpa using (h e he).ge⟩ #align simple_graph.walk.is_eulerian.mem_edges_iff SimpleGraph.Walk.IsEulerian.mem_edges_iff /-- The edge set of an Eulerian graph is finite. -/ def IsEulerian.fintypeEdgeSet {u v : V} {p : G.Walk u v} (h : p.IsEulerian) : Fintype G.edgeSet := Fintype.ofFinset h.isTrail.edgesFinset fun e => by simp only [Finset.mem_mk, Multiset.mem_coe, h.mem_edges_iff] #align simple_graph.walk.is_eulerian.fintype_edge_set SimpleGraph.Walk.IsEulerian.fintypeEdgeSet theorem IsTrail.isEulerian_of_forall_mem {u v : V} {p : G.Walk u v} (h : p.IsTrail) (hc : ∀ e, e ∈ G.edgeSet → e ∈ p.edges) : p.IsEulerian := fun e he => List.count_eq_one_of_mem h.edges_nodup (hc e he) #align simple_graph.walk.is_trail.is_eulerian_of_forall_mem SimpleGraph.Walk.IsTrail.isEulerian_of_forall_mem theorem isEulerian_iff {u v : V} (p : G.Walk u v) : p.IsEulerian ↔ p.IsTrail ∧ ∀ e, e ∈ G.edgeSet → e ∈ p.edges := by constructor · intro h exact ⟨h.isTrail, fun _ => h.mem_edges_iff.mpr⟩ · rintro ⟨h, hl⟩ exact h.isEulerian_of_forall_mem hl #align simple_graph.walk.is_eulerian_iff SimpleGraph.Walk.isEulerian_iff theorem IsEulerian.edgesFinset_eq [Fintype G.edgeSet] {u v : V} {p : G.Walk u v} (h : p.IsEulerian) : h.isTrail.edgesFinset = G.edgeFinset := by ext e simp [h.mem_edges_iff] #align simple_graph.walk.is_eulerian.edges_finset_eq SimpleGraph.Walk.IsEulerian.edgesFinset_eq theorem IsEulerian.even_degree_iff {x u v : V} {p : G.Walk u v} (ht : p.IsEulerian) [Fintype V] [DecidableRel G.Adj] : Even (G.degree x) ↔ u ≠ v → x ≠ u ∧ x ≠ v := by convert ht.isTrail.even_countp_edges_iff x rw [← Multiset.coe_countp, Multiset.countp_eq_card_filter, ← card_incidenceFinset_eq_degree] change Multiset.card _ = _ congr 1 convert_to _ = (ht.isTrail.edgesFinset.filter (Membership.mem x)).val have : Fintype G.edgeSet := fintypeEdgeSet ht rw [ht.edgesFinset_eq, G.incidenceFinset_eq_filter x] #align simple_graph.walk.is_eulerian.even_degree_iff SimpleGraph.Walk.IsEulerian.even_degree_iff theorem IsEulerian.card_filter_odd_degree [Fintype V] [DecidableRel G.Adj] {u v : V} {p : G.Walk u v} (ht : p.IsEulerian) {s} (h : s = (Finset.univ : Finset V).filter fun v => Odd (G.degree v)) : s.card = 0 ∨ s.card = 2 := by subst s simp only [Nat.odd_iff_not_even, Finset.card_eq_zero] simp only [ht.even_degree_iff, Ne.def, not_forall, not_and, Classical.not_not, exists_prop] obtain rfl | hn := eq_or_ne u v · left simp · right convert_to _ = ({u, v} : Finset V).card · simp [hn] · congr ext x simp [hn, imp_iff_not_or] #align simple_graph.walk.is_eulerian.card_filter_odd_degree SimpleGraph.Walk.IsEulerian.card_filter_odd_degree theorem IsEulerian.card_odd_degree [Fintype V] [DecidableRel G.Adj] {u v : V} {p : G.Walk u v} (ht : p.IsEulerian) : Fintype.card { v : V | Odd (G.degree v) } = 0 ∨ Fintype.card { v : V | Odd (G.degree v) } = 2 := by rw [← Set.toFinset_card] apply IsEulerian.card_filter_odd_degree ht ext v simp #align simple_graph.walk.is_eulerian.card_odd_degree SimpleGraph.Walk.IsEulerian.card_odd_degree end Walk end SimpleGraph
(**************************************************************** File: SR_MiniML_equi.v Author: Amy Felty original: March 2014 Feb 2021: Current Coq Version: V8.13.1 Subject Reduction for Call-by-Value Mini-ML using Hybrid Example showing why meta-level isterm1 cannot be used for equivalence proof of meval and eval (the exists/forall quantifier problem). Example from: [1] Amy Felty and Alberto Momigliano, Hybrid: A Definitional Two Level Approach to Reasoning with Higher-Order Abstract Syntax, In Journal of Automated Reasoning, 48(1):43-105, 2012. ***************************************************************) From HybridSys Require Export sl. From HybridSys Require Export MiniML. (**************************************************************** **************************************************************** Evaluation judgment defined as an inductive definition (meval), and associated properties as described in Section 3.3 of [1]. **************************************************************** ****************************************************************) (**************************************************************** Evaluation ****************************************************************) Section meval. Inductive meval: uexp -> uexp -> Prop := meval_App: forall E1':uexp -> uexp, forall E1 E2 V V2:uexp, abstr E1' -> meval E1 (Fun (fun x => E1' x)) -> meval E2 V2 -> meval (E1' V2) V -> meval (App E1 E2) V | meval_Fun: forall E:uexp -> uexp, abstr E -> isterm1 nil (Fun (fun x => E x)) -> meval (Fun (fun x => E x)) (Fun (fun x => E x)) | meval_Fix: forall E:uexp -> uexp, forall V:uexp, abstr E -> isterm1 nil (Fix (fun x => E x)) -> meval (E (Fix (fun x => E x))) V -> meval (Fix (fun x => E x)) V. End meval. (**************************************************************** **************************************************************** The two-level encoding of isterm, eval, and hastype judgments as in Figure 6 in [1]. **************************************************************** ****************************************************************) (**************************************************************** The atm type and instantiation of oo. ****************************************************************) Section encoding. Inductive atm : Set := typeof : uexp -> tp -> atm | eval : uexp -> uexp -> atm | isterm : uexp -> atm. Definition oo_ := oo atm Econ. Definition atom_ : atm -> oo_ := atom Econ. Definition T_ : oo_ := T atm Econ. Hint Unfold oo_ atom_ T_: hybrid. (**************************************************************** Definition of prog ****************************************************************) Inductive prog : atm -> oo_ -> Prop := | tabs : forall (T1 T2: tp) (E : uexp -> uexp), abstr E -> prog (typeof (Fun (fun x => E x)) (arrow T1 T2)) (All (fun x : uexp => Imp (typeof x T1) (atom_ (typeof (E x) T2)))) | tap : forall E1 E2: uexp, forall T T' : tp, prog (typeof (App E1 E2) T) (Conj (atom_ (typeof E1 (arrow T' T))) (atom_ (typeof E2 T'))) | tfix : forall (T: tp) (E : uexp -> uexp), abstr E -> prog (typeof (Fix (fun x => E x)) T) (All (fun x : uexp => Imp (typeof x T) (atom_ (typeof (E x) T)))) | eap : forall E1':uexp -> uexp, forall E1 E2 V V2:uexp, abstr E1' -> prog (eval (App E1 E2) V) (Conj (atom_ (eval E1 (Fun (fun x => E1' x)))) (Conj (atom_ (eval E2 V2)) (atom_ (eval (E1' V2) V)))) | eabs : forall E:uexp -> uexp, (abstr E) -> prog (eval (Fun (fun x => E x)) (Fun (fun x => E x))) (atom_ (isterm (Fun (fun x => E x)))) | efix : forall E:uexp -> uexp, forall V:uexp, abstr E -> prog (eval (Fix (fun x => E x)) V) (Conj (atom_ (eval (E (Fix (fun x => E x))) V)) (atom_ (isterm (Fix (fun x => E x))))) | exp_app : forall M N:uexp, prog (isterm (App M N)) (Conj (atom_ (isterm M)) (atom_ (isterm N))) | exp_lam : forall (E:uexp -> uexp), abstr E -> prog (isterm (Fun (fun x => (E x)))) (All (fun x:uexp => (Imp (isterm x) (atom_ (isterm (E x)))))) | exp_fix : forall (E:uexp -> uexp), abstr E -> prog (isterm (Fix (fun x => (E x)))) (All (fun x:uexp => (Imp (isterm x) (atom_ (isterm (E x)))))). (**************************************************************** Instantiation of seq ****************************************************************) Definition seq_ : nat -> list atm -> oo_ -> Prop := sl.seq prog. Definition seq'_ := seq' prog. Definition seq0 (B : oo_) : Prop := seq'_ nil B. Hint Unfold seq_ seq'_ seq0: hybrid. End encoding. #[global] Hint Unfold oo_ atom_ T_: hybrid. #[global] Hint Unfold seq_ seq'_ seq0: hybrid. #[global] Hint Unfold proper: hybrid. #[global] Hint Resolve proper_Var : hybrid. #[global] Hint Resolve tabs tap tfix eap eabs efix exp_app exp_lam exp_fix : hybrid. (**************************************************************** **************************************************************** Version of subject reduction with eval judgments defined as an inductive type (meval) as described in Section 4.4 of [1]. **************************************************************** ****************************************************************) Section meta_sr. Fixpoint uexp2atm_list (l:list uexp) : list atm := match l with | nil => nil | (e::l') => (isterm e::(uexp2atm_list l')) end. Lemma memb_isterm: forall (x:uexp) (Gamma: list uexp), In x Gamma -> In (isterm x) (uexp2atm_list Gamma). Proof. intro x; induction Gamma; simpl; auto. intros [h | h]; subst; auto. Qed. Hint Resolve memb_isterm : hybrid. Theorem isterm_equiv_isterm1 : forall (E:uexp)(Gamma:list uexp), isterm1 Gamma E <-> exists n:nat, seq_ n (uexp2atm_list Gamma) (atom_ (isterm E)). intros E Gamma; split. - induction 1; auto with hybrid. (* var case *) + generalize H; clear H; case G. * simpl; try tauto. * intros u l h. specialize memb_isterm with (1:=h); intro h'. exists 0; unfold seq_,atom_; apply s_init; eauto with hybrid. (* App case *) + destruct IHisterm1_1 as [i1 h1]. destruct IHisterm1_2 as [i2 h2]. exists (i1+i2+1+1+1). apply s_bc with (Conj (atom_ (isterm M)) (atom_ (isterm N))); eauto with hybrid. apply s_and; auto. * apply seq_mono with i1; auto; try lia. * apply seq_mono with i2; auto; try lia. (* Fun case *) (* exists/forall quantification problem *) + Abort. (* MC-Theorem 25 from [1] *) Theorem eval_equiv_meval : forall e v:uexp, (meval e v) <-> seq0 (atom_ (eval e v)). Proof. intros e v; split. - induction 1; auto with hybrid. (* App case *) + destruct IHmeval1 as [i1 h1]. destruct IHmeval2 as [i2 h2]. destruct IHmeval3 as [i3 h3]. exists (i1+i2+i3+1+1+1+1). unfold seq_,atom_; apply s_bc with (Conj (atom_ (eval E1 (Fun (fun x => E1' x)))) (Conj (atom_ (eval E2 V2)) (atom_ (eval (E1' V2) V)))); eauto with hybrid. apply s_and. * apply seq_mono with i1; try lia; auto. * apply s_and. -- apply seq_mono with i2; try lia; auto. -- apply seq_mono with i3; try lia; auto. (* Fun case *) + exists (0+1). unfold seq_,atom_; apply s_bc with (atom_ (isterm (Fun (fun x => E x)))); eauto with hybrid. (* need the above failed lemma to continue *) Abort. End meta_sr.
function X = cholsolve(A,B) % Solves (A'*A)*X=B with respect to X. % A should be an upper triangular matrix (Cholesky decomposition). opts.UT = true; opts.TRANSA = true; Z = linsolve(A, B, opts); opts.TRANSA = false; X = linsolve(A, Z, opts);
lemma eucl_rel_poly_add_left: assumes "eucl_rel_poly x y (q, r)" assumes "eucl_rel_poly x' y (q', r')" shows "eucl_rel_poly (x + x') y (q + q', r + r')"
library(readr) library(dplyr) library(ggplot2) library("cowplot") user <- read_csv('Users.csv') glimpse(user) table(user$ group) library(rlang) myplot <- function(mydf, myxcol, myycol, ymin=0,ymax=1) { ggplot2::ggplot(data = mydf, aes(x=reorder({{ myxcol }}, {{ myycol }}), y= {{ myycol }},col = factor(group))) + geom_jitter(height = 0.1, width = 0.5,alpha = .08, shape = 16,aes(colour = factor(group)))+ geom_violin(trim=TRUE,alpha=0.35, position = position_dodge(width = 1),colour=NA,aes( fill = factor(group)))+ geom_boxplot(notch = FALSE,width=.4, outlier.size = -1, lwd=.6,outlier.shape = NA,fill = NA, col=c('steelblue4','deeppink4'),lty=1)+ #,'','' ylim(ymin,ymax)+ scale_x_discrete(limits=c('NP',"CP"),label=c('Control', 'Experiment' ))+ coord_flip()+ stat_summary(fun.y=mean, geom="point", shape=18, size=4)+# color=c('orange4','darkolivegreen4','purple4','forestgreen'), fill=c('orange4','darkolivegreen4','purple4','forestgreen')) + # scale_colour_manual(limits=c('TR','AI',"NR", "SR",'SAI'),values = aes(colour = factor(Condition)))#c('darkkhaki','deeppink4','snow4','blue4','orchid4')) + # scale_fill_manual(limits=c('TR','AI',"NR", "SR",'SAI'),values = c('olivedrab4','maroon4','navajowhite4','steelblue4','violetred4')) + # scale_linetype_manual(limits=c('AI',"NR", "SR",'SAI'),values = c(1,1,1,1)) + theme(plot.title = element_text(hjust = 0.5),plot.margin = unit(c(0.1, 0.1, 0, 0), "cm"),axis.title.x=element_blank(), axis.title.y=element_blank(), panel.grid=element_line(colour="lightgrey", size = (.05)) ,panel.background =element_blank() ,legend.position="none") } bx1=myplot(user, group, words,0,max(user$words)) bx1 pdf("words.pdf", width=4, height=3) bx1 dev.off() bx1=myplot(user, group, likeRate ,0,max(user$likeRate )) bx1 pdf("likeRate.pdf", width=4, height=3) bx1 dev.off() bx1=myplot(user, group, Decision ,min(user$Decision ),max(user$Decision )) bx1 pdf("Decision.pdf", width=4, height=3) bx1 dev.off() bx1=myplot(user, group, Confidence ,min(user$Confidence ),max(user$Confidence )) bx1 pdf("Confidence.pdf", width=4, height=3) bx1 dev.off()
(** * 6.822 Formal Reasoning About Programs, Spring 2020 - Pset 1 *) Require Import Frap Pset1Sig. (* The first part of this assignment involves the [bool] datatype, * which has the following definition. * << Inductive bool := | true | false. >> * We will define logical negation and conjunction of Boolean values, * and prove some properties of these definitions. *) (* Define [Neg] so that it implements Boolean negation, which flips * the truth value of a Boolean value. *) Definition Neg (b : bool) : bool := match b with | true => false | false => true end. (* For instance, the negation of [true] should be [false]. * This proof should follow from reducing both sides of the equation * and observing that they are identical. *) Theorem Neg_true : Neg true = false. Proof. simplify. equality. Qed. (* Negation should be involutive, meaning that if we negate * any Boolean value twice, we should get the original value back. * To prove a fact like this that holds for all Booleans, it suffices * to prove the fact for both [true] and [false] by using the * [cases] tactic. *) Theorem Neg_involutive : forall b : bool, Neg (Neg b) = b. Proof. simplify. cases b; try (simplify; equality). Qed. (* Define [And] so that it implements Boolean conjunction. That is, * the result value should be [true] exactly when both inputs * are [true]. *) Definition And (x y : bool) : bool := match x,y with | true, true => true | _, _ => false end. (* Here are a couple of examples of how [And] should act on * concrete inputs. *) Theorem And_true_true : And true true = true. Proof. simplify. equality. Qed. Theorem And_false_true : And false true = false. Proof. simplify. equality. Qed. (* Prove that [And] is commutative, meaning that switching the order * of its arguments doesn't affect the result. *) Theorem And_comm : forall x y : bool, And x y = And y x. Proof. simplify. cases x; (cases y; simplify; equality). Qed. (* Prove that the conjunction of a Boolean value with [true] * doesn't change that value. *) Theorem And_true_r : forall x : bool, And x true = x. Proof. simplify. cases x; simplify; equality. Qed. (* In the second part of this assignment, we will work with a simple language * of imperative arithmetic programs that sequentially apply operations * to a natural-number-valued state. * The [Prog] datatype defines abstract syntax trees for this language. *) Print Prog. (* Define [run] such that [run p n] gives the final state * that running the program [p] should result in, when the * initial state is [n]. *) Fixpoint run (p : Prog) (initState : nat) : nat := match p with | Done => initState | AddThen e1 p1 => run p1 (initState + e1) | MulThen e2 p2 => run p2 (initState * e2) | DivThen e3 p3 => run p3 (initState / e3) | VidThen e4 p4 => run p4 (e4 / initState) | SetToThen e5 p5 => run p5 e5 end. Print Prog. Example test := (MulThen 5 (AddThen 2 Done)). Compute run test 2. Theorem run_Example1 : run Done 0 = 0. Proof. simplify. equality. Qed. Theorem run_Example2 : run (MulThen 5 (AddThen 2 Done)) 1 = 7. Proof. simplify. equality. Qed. Theorem run_Example3 : run (SetToThen 3 (MulThen 2 Done)) 10 = 6. Proof. simplify. equality. Qed. (* Define [numInstructions] to compute the number of instructions * in a program, not counting [Done] as an instruction. *) Fixpoint numInstructions (p : Prog) : nat := match p with | Done => 0 | AddThen e1 p1 => 1 + numInstructions (p1) | MulThen e1 p1 => 1 + numInstructions (p1) | DivThen e1 p1 => 1 + numInstructions (p1) | VidThen e1 p1 => 1 + numInstructions (p1) | SetToThen e1 p1 => 1 + numInstructions (p1) end. Theorem numInstructions_Example : numInstructions (MulThen 5 (AddThen 2 Done)) = 2. Proof. simplify. equality. Qed. (* Define [concatProg] such that [concatProg p1 p2] is the program * that first runs [p1] and then runs [p2]. *) Fixpoint concatProg (p1 p2 : Prog) : Prog := match p1 with | Done => p2 | AddThen e1 res => AddThen e1 (concatProg res p2) | MulThen e1 res => MulThen e1 ( concatProg res p2) | DivThen e1 res => DivThen e1 ( concatProg res p2) | VidThen e1 res => VidThen e1 ( concatProg res p2) | SetToThen e1 res => SetToThen e1 (concatProg res p2) end. Example a := concatProg (AddThen 1 Done) (MulThen 2 Done). Compute a. Theorem concatProg_Example : concatProg (AddThen 1 Done) (MulThen 2 Done) = AddThen 1 (MulThen 2 Done). Proof. simplify. equality. Qed. Theorem concat_base : forall (p1: Prog), concatProg p1 Done = p1. Proof. simplify. induct p1; simplify; equality. Qed. (* Prove that the number of instructions in the concatenation of * two programs is the sum of the number of instructions in each * program. *) Theorem concatProg_numInstructions : forall (p1 p2 : Prog), numInstructions (concatProg p1 p2) = numInstructions p1 + numInstructions p2. Proof. simplify. induction p1; simplify; equality; simplify; rewrite IHp1; equality. Qed. (* Prove that running the concatenation of [p1] with [p2] is equivalent to running [p1] and then running [p2] on the result. *) Theorem concatProg_run : forall (p1 p2 : Prog) (initState : nat), run (concatProg p1 p2) initState = run p2 (run p1 initState). Proof. induct p1; simplify; equality. Qed. (* Read this definition and understand how division by zero is handled. *) Fixpoint runPortable (p : Prog) (state : nat) : bool * nat := match p with | Done => (true, state) | AddThen n p => runPortable p (n+state) | MulThen n p => runPortable p (n*state) | DivThen n p => if n ==n 0 then (false, state) else runPortable p (state/n) | VidThen n p => if state ==n 0 then (false, 0) else runPortable p (n/state) | SetToThen n p => runPortable p n end. Arguments Nat.div : simpl never. (* you don't need to understand this line *) Lemma run_portable_helper: forall (p: Prog) (n: nat), runPortable (DivThen 0 p) n = (false, n). Proof. simplify. cases (n);simplify; equality. Qed. Lemma run_portable_helper_vid: forall (p: Prog) (n: nat), runPortable (VidThen n p) 0 = (false, 0). Proof. simplify. cases (n);simplify; equality. Qed. Lemma run_portable_helper2: forall (p: Prog) (n n2: nat), n <> 0 -> runPortable (DivThen n p) n2 = runPortable p (n2 / n). Proof. simplify. cases (n ==n 0). contradiction. equality. Qed. Lemma run_portable_helper_vid2: forall (p: Prog) (n n2: nat), n2 <> 0 -> runPortable (VidThen n p) n2 = runPortable p (n / n2). Proof. simplify. cases (n2 ==n 0). contradiction. equality. Qed. Lemma run_portable_helper3: forall(p: Prog) (n s0 s1: nat), (runPortable (DivThen n p) s0 = (true, s1)) -> n <> 0. Proof. intros. cases n. assert(H2: runPortable (DivThen 0 p) s0 = (false, s0)). apply run_portable_helper. rewrite H in H2. equality. linear_arithmetic. Qed. Lemma run_portable_helper_vid3: forall(p: Prog) (n s0 s1: nat), (runPortable (VidThen n p) s0 = (true, s1)) -> s0 <> 0. Proof. intros. cases s0. assert(H2: runPortable (VidThen n p) 0 = (false, 0)). apply run_portable_helper_vid. rewrite H in H2. equality. linear_arithmetic. Qed. (* Prove that running the concatenation [p] using [runPortable] coincides with using [run], as long as [runPortable] returns [true] to confirm that no divison by zero occurred. *) Lemma runPortable_run : forall p s0 s1, runPortable p s0 = (true, s1) -> run p s0 = s1. Proof. intros. induct p; try(simplify; equality); try(apply IHp in H; simplify; try(rewrite plus_comm); try(rewrite mult_comm); try apply H). apply IHp. rewrite <- H. rewrite run_portable_helper2. equality. assert(H2: runPortable (DivThen n p) s0 = (true, s1) -> n <> 0). apply run_portable_helper3. apply H2. apply H. apply IHp. rewrite <- H. rewrite run_portable_helper_vid2. equality. assert(H2: runPortable (VidThen n p) s0 = (true, s1) -> s0 <> 0). apply run_portable_helper_vid3. apply H2. apply H. Qed. Fixpoint validate_helper p (b : bool) := match p with | Done => true | AddThen n p => if n ==n 0 then validate_helper p b else validate_helper p true | MulThen n p => if n ==n 0 then validate_helper p false else validate_helper p b | DivThen n p => if n ==n 0 then false else (if b then validate_helper p (Nat.eqb n 1) else validate_helper p false) | VidThen n p => if b then validate_helper p false else false | SetToThen n p => if n ==n 0 then validate_helper p false else validate_helper p true end. Definition validate (p : Prog) : bool := validate_helper p false. (*Lemma validate_sound_helper: forall (p: Prog), validate p = true -> forall s, fst(runPortable p s) = true -> fst(runPortable p 0) = true. induct p; simplify; try(apply IHp); try(equality). unfold validate in IHp. apply IHp. Qed.*) (*Lemma b : forall (p: Prog)(n: nat), fst (runPortable p (n)) = true <-> (runPortable p n = (true, run p n)). Proof. induct p; simplify; try (apply IHp in H); try(rewrite <- plus_comm); try(rewrite <- mult_comm); try(equality); try(rewrite plus_comm in H); try(rewrite mult_comm in H); try(assumption); try(cases(n ==n 0); cases (n0 ==n 0));simplify; try(equality); try(rewrite IHp); try(equality). Qed. Lemma concat_portable : forall p1 p2 n, runPortable (concatProg p1 p2) n = (let (x, answer) := runPortable p1 n in if x then runPortable p2 answer else (x,answer)). Proof. induct p1; try equality; simplify; try apply IHp1; try equality; try( cases (n ==n 0); cases (n0 ==n 0); try equality; simplify; apply IHp1). Qed. *) (* If a clear plan hasn't emerged in 10 minutes (or if you get stuck later), * take a look at the hints for this pset on the course web site. * It is not expected that this pset is doable for everyone without the hints, * but some planning is required for successful proof. * In particular, repeatedly trying out different combinations of tactics * and ideas from hints until something sticks can go on for arbitrarily long * with little insight and no success; just guessing a solution is unlikely. * Thus, we encourage you to take your time thinking, look at the hints when * necessary, and only jump into coding when you have some idea why it should * succeed. Some may call Coq a video game, but it is not a grinding contest. *) (* The final goal of this pset is to implement [validate : Prog -> bool] such that if this function returns [true], the program would not trigger division by zero regardless of what state it starts out in. [validate] is allowed to return [false] for some perfectly good programs that never cause division by zero, but it must recognize as good the examples given below. In jargon, [validate] is required to be sound but not complete, but "complete enough" for the use cases defined by the examples given here: *) Definition goodProgram1 := AddThen 1 (VidThen 10 Done). Example runPortable_good : forall n, runPortable goodProgram1 n = (true, 10/(1+n)). Proof. simplify. equality. Qed. Definition badProgram1 := AddThen 0 (VidThen 10 Done). Example runPortable_bad : let n := 0 in runPortable badProgram1 n = (false, 0). Proof. simplify. equality. Qed. Definition badProgram2 := AddThen 1 (DivThen 0 Done). Example runPortable_bad2 : forall n, runPortable badProgram2 n = (false, 1+n). Proof. simplify. equality. Qed. Definition goodProgram2 := AddThen 0 (MulThen 10 (AddThen 0 (DivThen 1 Done))). Definition goodProgram3 := AddThen 1 (MulThen 10 (AddThen 0 (VidThen 1 Done))). Definition goodProgram4 := Done. Definition goodProgram5 := SetToThen 0 (DivThen 1 Done). Definition goodProgram6 := SetToThen 1 (VidThen 1 Done). Definition goodProgram7 := AddThen 1 (DivThen 1 (DivThen 1 (VidThen 1 Done))). (* If you already see a way to build [validate] that meets the * requirements above, _and have a plan for how to prove it correct_, * feel free to just code away. Our solution uses one intermediate definition * and one intermediate lemma in the soundness proof -- both of which are more * sophisticated than the top-level versions given here. *) Example validate1 : validate goodProgram1 = true. Proof. equality. Qed. Example validate2 : validate goodProgram2 = true. Proof. equality. Qed. Example validate3 : validate goodProgram3 = true. Proof. equality. Qed. Example validate4 : validate goodProgram4 = true. Proof. equality. Qed. Example validate5 : validate goodProgram5 = true. Proof. equality. Qed. Example validate6 : validate goodProgram6 = true. Proof. equality. Qed. Example validate7 : validate goodProgram7 = true. Proof. equality. Qed. Example validate8 : validate badProgram1 = false. Proof. equality. Qed. Example validate9 : validate badProgram2 = false. Proof. equality. Qed. Lemma validate_sound_helper: forall p b, validate_helper p b = true -> forall s : nat, (b = true -> s <> 0) -> runPortable p s = (true, run p s). induct p; try(simplify); try(equality). rewrite plus_comm. simplify. cases (n ==n 0). apply IHp with (b:=b). assumption. rewrite e. simplify. apply H0 in H1. linear_arithmetic. apply IHp with (b:=true). assumption. simplify. linear_arithmetic. rewrite mult_comm. simplify. cases (n ==n 0). apply IHp with (b:=false). assumption. propositional. equality. apply IHp with (b:=b). assumption. simplify. apply H0 in H1. simplify. apply Nat.neq_mul_0. propositional. cases (n ==n 0). equality. cases b. apply IHp with (b:= Nat.eqb n 1). assumption. cases(Nat.eqb n 1). intros. apply Nat.eqb_eq in Heq. rewrite Heq. apply H0 in H1. rewrite Nat.div_1_r. assumption. propositional. equality. apply IHp with (b := false) (s := s/n). assumption. propositional. equality. cases (s ==n 0). cases b. propositional. equality. cases b. apply IHp with (b := false) (s := n/s). assumption. propositional. equality. equality. cases (n ==n 0). apply IHp with (b := false) (s := n). assumption. propositional. equality. apply IHp with (b := true) (s := n). assumption. propositional. Qed. Hint Rewrite Nat.add_0_r. Lemma validate_sound : forall p, validate p = true -> forall s, runPortable p s = (true, run p s). Proof. induct p; try(simplify); try(equality); try(rewrite plus_comm). unfold validate in IHp. apply validate_sound_helper with (s:=s) in H. simplify. assert(ejre: n + s = s + n). linear_arithmetic. rewrite <- ejre. rewrite <- ejre in H. trivial. propositional. equality. apply validate_sound_helper with (s:=s) in H. simplify. assumption. propositional. equality. cases (n ==n 0). apply validate_sound_helper with (s:=s) in H. simplify. rewrite e in H. simplify. rewrite e. apply H. propositional. equality. apply validate_sound_helper with (s:=s) in H. simplify. cases (n ==n 0). equality. apply H. propositional. equality. apply validate_sound_helper with (s:= s) in H. simplify. apply H. propositional. equality. apply validate_sound_helper with (s:= s) in H. simplify. apply H. propositional. equality. Qed. (* Here is the complete list of commands used in one possible solution: - Search, for example Search (_ + 0). - induct, for example induct x - simplify - propositional - equality - linear_arithmetic - cases, for example cases (X ==n Y) - apply, for example apply H - apply in, for example apply H1 in H2 or apply somelemma in H1 - apply with, for example apply H1 with (x:=2) - apply in with, for example apply H1 with (x:=2) in H2 - rewrite, for example rewrite H - rewrite in, for example rewrite H1 in H2 or rewrite somelemma in H1 - ;, for example simplify; propositional *)
[GOAL] A✝ : Type u_1 ι✝ : Type u_2 inst✝¹ : Ring A✝ A : Type u_3 ι : Type u_4 inst✝ : CommRing A B : ι → AddSubgroup A inter : ∀ (i j : ι), ∃ k, B k ≤ B i ⊓ B j mul : ∀ (i : ι), ∃ j, ↑(B j) * ↑(B j) ⊆ ↑(B i) leftMul : ∀ (x : A) (i : ι), ∃ j, ↑(B j) ⊆ (fun y => x * y) ⁻¹' ↑(B i) ⊢ ∀ (x : A) (i : ι), ∃ j, ↑(B j) ⊆ (fun x_1 => x_1 * x) ⁻¹' ↑(B i) [PROOFSTEP] intro x i [GOAL] A✝ : Type u_1 ι✝ : Type u_2 inst✝¹ : Ring A✝ A : Type u_3 ι : Type u_4 inst✝ : CommRing A B : ι → AddSubgroup A inter : ∀ (i j : ι), ∃ k, B k ≤ B i ⊓ B j mul : ∀ (i : ι), ∃ j, ↑(B j) * ↑(B j) ⊆ ↑(B i) leftMul : ∀ (x : A) (i : ι), ∃ j, ↑(B j) ⊆ (fun y => x * y) ⁻¹' ↑(B i) x : A i : ι ⊢ ∃ j, ↑(B j) ⊆ (fun x_1 => x_1 * x) ⁻¹' ↑(B i) [PROOFSTEP] cases' leftMul x i with j hj [GOAL] case intro A✝ : Type u_1 ι✝ : Type u_2 inst✝¹ : Ring A✝ A : Type u_3 ι : Type u_4 inst✝ : CommRing A B : ι → AddSubgroup A inter : ∀ (i j : ι), ∃ k, B k ≤ B i ⊓ B j mul : ∀ (i : ι), ∃ j, ↑(B j) * ↑(B j) ⊆ ↑(B i) leftMul : ∀ (x : A) (i : ι), ∃ j, ↑(B j) ⊆ (fun y => x * y) ⁻¹' ↑(B i) x : A i j : ι hj : ↑(B j) ⊆ (fun y => x * y) ⁻¹' ↑(B i) ⊢ ∃ j, ↑(B j) ⊆ (fun x_1 => x_1 * x) ⁻¹' ↑(B i) [PROOFSTEP] use j [GOAL] case h A✝ : Type u_1 ι✝ : Type u_2 inst✝¹ : Ring A✝ A : Type u_3 ι : Type u_4 inst✝ : CommRing A B : ι → AddSubgroup A inter : ∀ (i j : ι), ∃ k, B k ≤ B i ⊓ B j mul : ∀ (i : ι), ∃ j, ↑(B j) * ↑(B j) ⊆ ↑(B i) leftMul : ∀ (x : A) (i : ι), ∃ j, ↑(B j) ⊆ (fun y => x * y) ⁻¹' ↑(B i) x : A i j : ι hj : ↑(B j) ⊆ (fun y => x * y) ⁻¹' ↑(B i) ⊢ ↑(B j) ⊆ (fun x_1 => x_1 * x) ⁻¹' ↑(B i) [PROOFSTEP] simpa [mul_comm] using hj [GOAL] A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B ⊢ Set.Nonempty {U | ∃ i, U = ↑(B i)} [PROOFSTEP] inhabit ι [GOAL] A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B inhabited_h : Inhabited ι ⊢ Set.Nonempty {U | ∃ i, U = ↑(B i)} [PROOFSTEP] exact ⟨B default, default, rfl⟩ [GOAL] A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B ⊢ ∀ {x y : Set A}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y [PROOFSTEP] rintro _ _ ⟨i, rfl⟩ ⟨j, rfl⟩ [GOAL] case intro.intro A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B i j : ι ⊢ ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ ↑(B i) ∩ ↑(B j) [PROOFSTEP] cases' hB.inter i j with k hk [GOAL] case intro.intro.intro A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B i j k : ι hk : B k ≤ B i ⊓ B j ⊢ ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ ↑(B i) ∩ ↑(B j) [PROOFSTEP] use B k [GOAL] case h A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B i j k : ι hk : B k ≤ B i ⊓ B j ⊢ ↑(B k) ∈ {U | ∃ i, U = ↑(B i)} ∧ ↑(B k) ⊆ ↑(B i) ∩ ↑(B j) [PROOFSTEP] constructor [GOAL] case h.left A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B i j k : ι hk : B k ≤ B i ⊓ B j ⊢ ↑(B k) ∈ {U | ∃ i, U = ↑(B i)} [PROOFSTEP] use k [GOAL] case h.right A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B i j k : ι hk : B k ≤ B i ⊓ B j ⊢ ↑(B k) ⊆ ↑(B i) ∩ ↑(B j) [PROOFSTEP] exact hk [GOAL] A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B ⊢ ∀ {U : Set A}, U ∈ { sets := {U | ∃ i, U = ↑(B i)}, nonempty := (_ : ∃ x, x ∈ {U | ∃ i, U = ↑(B i)}), inter_sets := (_ : ∀ {x y : Set A}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y) }.sets → 0 ∈ U [PROOFSTEP] rintro _ ⟨i, rfl⟩ [GOAL] case intro A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B i : ι ⊢ 0 ∈ ↑(B i) [PROOFSTEP] exact (B i).zero_mem [GOAL] A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B ⊢ ∀ {U : Set A}, U ∈ { sets := {U | ∃ i, U = ↑(B i)}, nonempty := (_ : ∃ x, x ∈ {U | ∃ i, U = ↑(B i)}), inter_sets := (_ : ∀ {x y : Set A}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y) }.sets → ∃ V, V ∈ { sets := {U | ∃ i, U = ↑(B i)}, nonempty := (_ : ∃ x, x ∈ {U | ∃ i, U = ↑(B i)}), inter_sets := (_ : ∀ {x y : Set A}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y) }.sets ∧ V + V ⊆ U [PROOFSTEP] rintro _ ⟨i, rfl⟩ [GOAL] case intro A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B i : ι ⊢ ∃ V, V ∈ { sets := {U | ∃ i, U = ↑(B i)}, nonempty := (_ : ∃ x, x ∈ {U | ∃ i, U = ↑(B i)}), inter_sets := (_ : ∀ {x y : Set A}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y) }.sets ∧ V + V ⊆ ↑(B i) [PROOFSTEP] use B i [GOAL] case h A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B i : ι ⊢ ↑(B i) ∈ { sets := {U | ∃ i, U = ↑(B i)}, nonempty := (_ : ∃ x, x ∈ {U | ∃ i, U = ↑(B i)}), inter_sets := (_ : ∀ {x y : Set A}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y) }.sets ∧ ↑(B i) + ↑(B i) ⊆ ↑(B i) [PROOFSTEP] constructor [GOAL] case h.left A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B i : ι ⊢ ↑(B i) ∈ { sets := {U | ∃ i, U = ↑(B i)}, nonempty := (_ : ∃ x, x ∈ {U | ∃ i, U = ↑(B i)}), inter_sets := (_ : ∀ {x y : Set A}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y) }.sets [PROOFSTEP] use i [GOAL] case h.right A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B i : ι ⊢ ↑(B i) + ↑(B i) ⊆ ↑(B i) [PROOFSTEP] rintro x ⟨y, z, y_in, z_in, rfl⟩ [GOAL] case h.right.intro.intro.intro.intro A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B i : ι y z : A y_in : y ∈ ↑(B i) z_in : z ∈ ↑(B i) ⊢ (fun x x_1 => x + x_1) y z ∈ ↑(B i) [PROOFSTEP] exact (B i).add_mem y_in z_in [GOAL] A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B ⊢ ∀ {U : Set A}, U ∈ { sets := {U | ∃ i, U = ↑(B i)}, nonempty := (_ : ∃ x, x ∈ {U | ∃ i, U = ↑(B i)}), inter_sets := (_ : ∀ {x y : Set A}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y) }.sets → ∃ V, V ∈ { sets := {U | ∃ i, U = ↑(B i)}, nonempty := (_ : ∃ x, x ∈ {U | ∃ i, U = ↑(B i)}), inter_sets := (_ : ∀ {x y : Set A}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y) }.sets ∧ V ⊆ (fun x => -x) ⁻¹' U [PROOFSTEP] rintro _ ⟨i, rfl⟩ [GOAL] case intro A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B i : ι ⊢ ∃ V, V ∈ { sets := {U | ∃ i, U = ↑(B i)}, nonempty := (_ : ∃ x, x ∈ {U | ∃ i, U = ↑(B i)}), inter_sets := (_ : ∀ {x y : Set A}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y) }.sets ∧ V ⊆ (fun x => -x) ⁻¹' ↑(B i) [PROOFSTEP] use B i [GOAL] case h A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B i : ι ⊢ ↑(B i) ∈ { sets := {U | ∃ i, U = ↑(B i)}, nonempty := (_ : ∃ x, x ∈ {U | ∃ i, U = ↑(B i)}), inter_sets := (_ : ∀ {x y : Set A}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y) }.sets ∧ ↑(B i) ⊆ (fun x => -x) ⁻¹' ↑(B i) [PROOFSTEP] constructor [GOAL] case h.left A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B i : ι ⊢ ↑(B i) ∈ { sets := {U | ∃ i, U = ↑(B i)}, nonempty := (_ : ∃ x, x ∈ {U | ∃ i, U = ↑(B i)}), inter_sets := (_ : ∀ {x y : Set A}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y) }.sets [PROOFSTEP] use i [GOAL] case h.right A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B i : ι ⊢ ↑(B i) ⊆ (fun x => -x) ⁻¹' ↑(B i) [PROOFSTEP] intro x x_in [GOAL] case h.right A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B i : ι x : A x_in : x ∈ ↑(B i) ⊢ x ∈ (fun x => -x) ⁻¹' ↑(B i) [PROOFSTEP] exact (B i).neg_mem x_in [GOAL] A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B ⊢ ∀ (x₀ : A) {U : Set A}, U ∈ { sets := {U | ∃ i, U = ↑(B i)}, nonempty := (_ : ∃ x, x ∈ {U | ∃ i, U = ↑(B i)}), inter_sets := (_ : ∀ {x y : Set A}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y) }.sets → ∃ V, V ∈ { sets := {U | ∃ i, U = ↑(B i)}, nonempty := (_ : ∃ x, x ∈ {U | ∃ i, U = ↑(B i)}), inter_sets := (_ : ∀ {x y : Set A}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y) }.sets ∧ V ⊆ (fun x => x₀ + x + -x₀) ⁻¹' U [PROOFSTEP] rintro x₀ _ ⟨i, rfl⟩ [GOAL] case intro A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B x₀ : A i : ι ⊢ ∃ V, V ∈ { sets := {U | ∃ i, U = ↑(B i)}, nonempty := (_ : ∃ x, x ∈ {U | ∃ i, U = ↑(B i)}), inter_sets := (_ : ∀ {x y : Set A}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y) }.sets ∧ V ⊆ (fun x => x₀ + x + -x₀) ⁻¹' ↑(B i) [PROOFSTEP] use B i [GOAL] case h A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B x₀ : A i : ι ⊢ ↑(B i) ∈ { sets := {U | ∃ i, U = ↑(B i)}, nonempty := (_ : ∃ x, x ∈ {U | ∃ i, U = ↑(B i)}), inter_sets := (_ : ∀ {x y : Set A}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y) }.sets ∧ ↑(B i) ⊆ (fun x => x₀ + x + -x₀) ⁻¹' ↑(B i) [PROOFSTEP] constructor [GOAL] case h.left A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B x₀ : A i : ι ⊢ ↑(B i) ∈ { sets := {U | ∃ i, U = ↑(B i)}, nonempty := (_ : ∃ x, x ∈ {U | ∃ i, U = ↑(B i)}), inter_sets := (_ : ∀ {x y : Set A}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y) }.sets [PROOFSTEP] use i [GOAL] case h.right A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B x₀ : A i : ι ⊢ ↑(B i) ⊆ (fun x => x₀ + x + -x₀) ⁻¹' ↑(B i) [PROOFSTEP] simp [GOAL] A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B ⊢ ∀ {U : Set A}, U ∈ AddGroupFilterBasis.toFilterBasis.sets → ∃ V, V ∈ AddGroupFilterBasis.toFilterBasis.sets ∧ V * V ⊆ U [PROOFSTEP] rintro _ ⟨i, rfl⟩ [GOAL] case intro A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B i : ι ⊢ ∃ V, V ∈ AddGroupFilterBasis.toFilterBasis.sets ∧ V * V ⊆ ↑(B i) [PROOFSTEP] cases' hB.mul i with k hk [GOAL] case intro.intro A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B i k : ι hk : ↑(B k) * ↑(B k) ⊆ ↑(B i) ⊢ ∃ V, V ∈ AddGroupFilterBasis.toFilterBasis.sets ∧ V * V ⊆ ↑(B i) [PROOFSTEP] use B k [GOAL] case h A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B i k : ι hk : ↑(B k) * ↑(B k) ⊆ ↑(B i) ⊢ ↑(B k) ∈ AddGroupFilterBasis.toFilterBasis.sets ∧ ↑(B k) * ↑(B k) ⊆ ↑(B i) [PROOFSTEP] constructor [GOAL] case h.left A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B i k : ι hk : ↑(B k) * ↑(B k) ⊆ ↑(B i) ⊢ ↑(B k) ∈ AddGroupFilterBasis.toFilterBasis.sets [PROOFSTEP] use k [GOAL] case h.right A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B i k : ι hk : ↑(B k) * ↑(B k) ⊆ ↑(B i) ⊢ ↑(B k) * ↑(B k) ⊆ ↑(B i) [PROOFSTEP] exact hk [GOAL] A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B ⊢ ∀ (x₀ : A) {U : Set A}, U ∈ AddGroupFilterBasis.toFilterBasis.sets → ∃ V, V ∈ AddGroupFilterBasis.toFilterBasis.sets ∧ V ⊆ (fun x => x₀ * x) ⁻¹' U [PROOFSTEP] rintro x₀ _ ⟨i, rfl⟩ [GOAL] case intro A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B x₀ : A i : ι ⊢ ∃ V, V ∈ AddGroupFilterBasis.toFilterBasis.sets ∧ V ⊆ (fun x => x₀ * x) ⁻¹' ↑(B i) [PROOFSTEP] cases' hB.leftMul x₀ i with k hk [GOAL] case intro.intro A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B x₀ : A i k : ι hk : ↑(B k) ⊆ (fun x => x₀ * x) ⁻¹' ↑(B i) ⊢ ∃ V, V ∈ AddGroupFilterBasis.toFilterBasis.sets ∧ V ⊆ (fun x => x₀ * x) ⁻¹' ↑(B i) [PROOFSTEP] use B k [GOAL] case h A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B x₀ : A i k : ι hk : ↑(B k) ⊆ (fun x => x₀ * x) ⁻¹' ↑(B i) ⊢ ↑(B k) ∈ AddGroupFilterBasis.toFilterBasis.sets ∧ ↑(B k) ⊆ (fun x => x₀ * x) ⁻¹' ↑(B i) [PROOFSTEP] constructor [GOAL] case h.left A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B x₀ : A i k : ι hk : ↑(B k) ⊆ (fun x => x₀ * x) ⁻¹' ↑(B i) ⊢ ↑(B k) ∈ AddGroupFilterBasis.toFilterBasis.sets [PROOFSTEP] use k [GOAL] case h.right A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B x₀ : A i k : ι hk : ↑(B k) ⊆ (fun x => x₀ * x) ⁻¹' ↑(B i) ⊢ ↑(B k) ⊆ (fun x => x₀ * x) ⁻¹' ↑(B i) [PROOFSTEP] exact hk [GOAL] A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B ⊢ ∀ (x₀ : A) {U : Set A}, U ∈ AddGroupFilterBasis.toFilterBasis.sets → ∃ V, V ∈ AddGroupFilterBasis.toFilterBasis.sets ∧ V ⊆ (fun x => x * x₀) ⁻¹' U [PROOFSTEP] rintro x₀ _ ⟨i, rfl⟩ [GOAL] case intro A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B x₀ : A i : ι ⊢ ∃ V, V ∈ AddGroupFilterBasis.toFilterBasis.sets ∧ V ⊆ (fun x => x * x₀) ⁻¹' ↑(B i) [PROOFSTEP] cases' hB.rightMul x₀ i with k hk [GOAL] case intro.intro A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B x₀ : A i k : ι hk : ↑(B k) ⊆ (fun x => x * x₀) ⁻¹' ↑(B i) ⊢ ∃ V, V ∈ AddGroupFilterBasis.toFilterBasis.sets ∧ V ⊆ (fun x => x * x₀) ⁻¹' ↑(B i) [PROOFSTEP] use B k [GOAL] case h A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B x₀ : A i k : ι hk : ↑(B k) ⊆ (fun x => x * x₀) ⁻¹' ↑(B i) ⊢ ↑(B k) ∈ AddGroupFilterBasis.toFilterBasis.sets ∧ ↑(B k) ⊆ (fun x => x * x₀) ⁻¹' ↑(B i) [PROOFSTEP] constructor [GOAL] case h.left A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B x₀ : A i k : ι hk : ↑(B k) ⊆ (fun x => x * x₀) ⁻¹' ↑(B i) ⊢ ↑(B k) ∈ AddGroupFilterBasis.toFilterBasis.sets [PROOFSTEP] use k [GOAL] case h.right A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B x₀ : A i k : ι hk : ↑(B k) ⊆ (fun x => x * x₀) ⁻¹' ↑(B i) ⊢ ↑(B k) ⊆ (fun x => x * x₀) ⁻¹' ↑(B i) [PROOFSTEP] exact hk [GOAL] A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B ⊢ ∀ (t : Set A), t ∈ 𝓝 0 ↔ ∃ i, True ∧ ↑(B i) ⊆ t [PROOFSTEP] intro s [GOAL] A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B s : Set A ⊢ s ∈ 𝓝 0 ↔ ∃ i, True ∧ ↑(B i) ⊆ s [PROOFSTEP] rw [hB.toRingFilterBasis.toAddGroupFilterBasis.nhds_zero_hasBasis.mem_iff] [GOAL] A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B s : Set A ⊢ (∃ i, i ∈ RingFilterBasis.toAddGroupFilterBasis ∧ id i ⊆ s) ↔ ∃ i, True ∧ ↑(B i) ⊆ s [PROOFSTEP] constructor [GOAL] case mp A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B s : Set A ⊢ (∃ i, i ∈ RingFilterBasis.toAddGroupFilterBasis ∧ id i ⊆ s) → ∃ i, True ∧ ↑(B i) ⊆ s [PROOFSTEP] rintro ⟨-, ⟨i, rfl⟩, hi⟩ [GOAL] case mp.intro.intro.intro A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B s : Set A i : ι hi : id ↑(B i) ⊆ s ⊢ ∃ i, True ∧ ↑(B i) ⊆ s [PROOFSTEP] exact ⟨i, trivial, hi⟩ [GOAL] case mpr A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B s : Set A ⊢ (∃ i, True ∧ ↑(B i) ⊆ s) → ∃ i, i ∈ RingFilterBasis.toAddGroupFilterBasis ∧ id i ⊆ s [PROOFSTEP] rintro ⟨i, -, hi⟩ [GOAL] case mpr.intro.intro A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B s : Set A i : ι hi : ↑(B i) ⊆ s ⊢ ∃ i, i ∈ RingFilterBasis.toAddGroupFilterBasis ∧ id i ⊆ s [PROOFSTEP] exact ⟨B i, ⟨i, rfl⟩, hi⟩ [GOAL] A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B a : A ⊢ ∀ (t : Set A), t ∈ 𝓝 a ↔ ∃ i, True ∧ {b | b - a ∈ B i} ⊆ t [PROOFSTEP] intro s [GOAL] A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B a : A s : Set A ⊢ s ∈ 𝓝 a ↔ ∃ i, True ∧ {b | b - a ∈ B i} ⊆ s [PROOFSTEP] rw [(hB.toRingFilterBasis.toAddGroupFilterBasis.nhds_hasBasis a).mem_iff] [GOAL] A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B a : A s : Set A ⊢ (∃ i, i ∈ RingFilterBasis.toAddGroupFilterBasis ∧ (fun y => a + y) '' i ⊆ s) ↔ ∃ i, True ∧ {b | b - a ∈ B i} ⊆ s [PROOFSTEP] simp only [true_and] [GOAL] A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B a : A s : Set A ⊢ (∃ i, i ∈ RingFilterBasis.toAddGroupFilterBasis ∧ (fun y => a + y) '' i ⊆ s) ↔ ∃ i, {b | b - a ∈ B i} ⊆ s [PROOFSTEP] constructor [GOAL] case mp A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B a : A s : Set A ⊢ (∃ i, i ∈ RingFilterBasis.toAddGroupFilterBasis ∧ (fun y => a + y) '' i ⊆ s) → ∃ i, {b | b - a ∈ B i} ⊆ s [PROOFSTEP] rintro ⟨-, ⟨i, rfl⟩, hi⟩ [GOAL] case mp.intro.intro.intro A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B a : A s : Set A i : ι hi : (fun y => a + y) '' ↑(B i) ⊆ s ⊢ ∃ i, {b | b - a ∈ B i} ⊆ s [PROOFSTEP] use i [GOAL] case h A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B a : A s : Set A i : ι hi : (fun y => a + y) '' ↑(B i) ⊆ s ⊢ {b | b - a ∈ B i} ⊆ s [PROOFSTEP] suffices h : {b : A | b - a ∈ B i} = (fun y => a + y) '' ↑(B i) [GOAL] case h A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B a : A s : Set A i : ι hi : (fun y => a + y) '' ↑(B i) ⊆ s h : {b | b - a ∈ B i} = (fun y => a + y) '' ↑(B i) ⊢ {b | b - a ∈ B i} ⊆ s [PROOFSTEP] rw [h] [GOAL] case h A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B a : A s : Set A i : ι hi : (fun y => a + y) '' ↑(B i) ⊆ s h : {b | b - a ∈ B i} = (fun y => a + y) '' ↑(B i) ⊢ (fun y => a + y) '' ↑(B i) ⊆ s [PROOFSTEP] assumption [GOAL] case h A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B a : A s : Set A i : ι hi : (fun y => a + y) '' ↑(B i) ⊆ s ⊢ {b | b - a ∈ B i} = (fun y => a + y) '' ↑(B i) [PROOFSTEP] simp only [image_add_left, neg_add_eq_sub] [GOAL] case h A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B a : A s : Set A i : ι hi : (fun y => a + y) '' ↑(B i) ⊆ s ⊢ {b | b - a ∈ B i} = (fun x => x - a) ⁻¹' ↑(B i) [PROOFSTEP] ext b [GOAL] case h.h A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B a : A s : Set A i : ι hi : (fun y => a + y) '' ↑(B i) ⊆ s b : A ⊢ b ∈ {b | b - a ∈ B i} ↔ b ∈ (fun x => x - a) ⁻¹' ↑(B i) [PROOFSTEP] simp [GOAL] case mpr A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B a : A s : Set A ⊢ (∃ i, {b | b - a ∈ B i} ⊆ s) → ∃ i, i ∈ RingFilterBasis.toAddGroupFilterBasis ∧ (fun y => a + y) '' i ⊆ s [PROOFSTEP] rintro ⟨i, hi⟩ [GOAL] case mpr.intro A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B a : A s : Set A i : ι hi : {b | b - a ∈ B i} ⊆ s ⊢ ∃ i, i ∈ RingFilterBasis.toAddGroupFilterBasis ∧ (fun y => a + y) '' i ⊆ s [PROOFSTEP] use B i [GOAL] case h A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B a : A s : Set A i : ι hi : {b | b - a ∈ B i} ⊆ s ⊢ ↑(B i) ∈ RingFilterBasis.toAddGroupFilterBasis ∧ (fun y => a + y) '' ↑(B i) ⊆ s [PROOFSTEP] constructor [GOAL] case h.left A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B a : A s : Set A i : ι hi : {b | b - a ∈ B i} ⊆ s ⊢ ↑(B i) ∈ RingFilterBasis.toAddGroupFilterBasis [PROOFSTEP] use i [GOAL] case h.right A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B a : A s : Set A i : ι hi : {b | b - a ∈ B i} ⊆ s ⊢ (fun y => a + y) '' ↑(B i) ⊆ s [PROOFSTEP] rw [image_subset_iff] [GOAL] case h.right A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B a : A s : Set A i : ι hi : {b | b - a ∈ B i} ⊆ s ⊢ ↑(B i) ⊆ (fun y => a + y) ⁻¹' s [PROOFSTEP] rintro b b_in [GOAL] case h.right A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B a : A s : Set A i : ι hi : {b | b - a ∈ B i} ⊆ s b : A b_in : b ∈ ↑(B i) ⊢ b ∈ (fun y => a + y) ⁻¹' s [PROOFSTEP] apply hi [GOAL] case h.right.a A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B a : A s : Set A i : ι hi : {b | b - a ∈ B i} ⊆ s b : A b_in : b ∈ ↑(B i) ⊢ (fun y => a + y) b ∈ {b | b - a ∈ B i} [PROOFSTEP] simpa using b_in [GOAL] A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B i : ι x✝ : TopologicalSpace A := topology hB src✝ : AddSubgroup A := B i ⊢ IsOpen { toAddSubmonoid := src✝.toAddSubmonoid, neg_mem' := (_ : ∀ {x : A}, x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toAddSubmonoid.toAddSubsemigroup.carrier [PROOFSTEP] rw [isOpen_iff_mem_nhds] [GOAL] A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B i : ι x✝ : TopologicalSpace A := topology hB src✝ : AddSubgroup A := B i ⊢ ∀ (a : A), a ∈ { toAddSubmonoid := src✝.toAddSubmonoid, neg_mem' := (_ : ∀ {x : A}, x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toAddSubmonoid.toAddSubsemigroup.carrier → { toAddSubmonoid := src✝.toAddSubmonoid, neg_mem' := (_ : ∀ {x : A}, x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toAddSubmonoid.toAddSubsemigroup.carrier ∈ 𝓝 a [PROOFSTEP] intro a a_in [GOAL] A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B i : ι x✝ : TopologicalSpace A := topology hB src✝ : AddSubgroup A := B i a : A a_in : a ∈ { toAddSubmonoid := src✝.toAddSubmonoid, neg_mem' := (_ : ∀ {x : A}, x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toAddSubmonoid.toAddSubsemigroup.carrier ⊢ { toAddSubmonoid := src✝.toAddSubmonoid, neg_mem' := (_ : ∀ {x : A}, x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toAddSubmonoid.toAddSubsemigroup.carrier ∈ 𝓝 a [PROOFSTEP] rw [(hB.hasBasis_nhds a).mem_iff] [GOAL] A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B i : ι x✝ : TopologicalSpace A := topology hB src✝ : AddSubgroup A := B i a : A a_in : a ∈ { toAddSubmonoid := src✝.toAddSubmonoid, neg_mem' := (_ : ∀ {x : A}, x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toAddSubmonoid.toAddSubsemigroup.carrier ⊢ ∃ i, True ∧ {b | b - a ∈ B i} ⊆ { toAddSubmonoid := src✝.toAddSubmonoid, neg_mem' := (_ : ∀ {x : A}, x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toAddSubmonoid.toAddSubsemigroup.carrier [PROOFSTEP] use i, trivial [GOAL] case right A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B i : ι x✝ : TopologicalSpace A := topology hB src✝ : AddSubgroup A := B i a : A a_in : a ∈ { toAddSubmonoid := src✝.toAddSubmonoid, neg_mem' := (_ : ∀ {x : A}, x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toAddSubmonoid.toAddSubsemigroup.carrier ⊢ {b | b - a ∈ B i} ⊆ { toAddSubmonoid := src✝.toAddSubmonoid, neg_mem' := (_ : ∀ {x : A}, x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toAddSubmonoid.toAddSubsemigroup.carrier [PROOFSTEP] rintro b b_in [GOAL] case right A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B i : ι x✝ : TopologicalSpace A := topology hB src✝ : AddSubgroup A := B i a : A a_in : a ∈ { toAddSubmonoid := src✝.toAddSubmonoid, neg_mem' := (_ : ∀ {x : A}, x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toAddSubmonoid.toAddSubsemigroup.carrier b : A b_in : b ∈ {b | b - a ∈ B i} ⊢ b ∈ { toAddSubmonoid := src✝.toAddSubmonoid, neg_mem' := (_ : ∀ {x : A}, x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toAddSubmonoid.toAddSubsemigroup.carrier [PROOFSTEP] simpa using (B i).add_mem a_in b_in [GOAL] A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B ⊢ NonarchimedeanRing A [PROOFSTEP] letI := hB.topology [GOAL] A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B this : TopologicalSpace A := topology hB ⊢ NonarchimedeanRing A [PROOFSTEP] constructor [GOAL] case is_nonarchimedean A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B this : TopologicalSpace A := topology hB ⊢ ∀ (U : Set A), U ∈ 𝓝 0 → ∃ V, ↑V ⊆ U [PROOFSTEP] intro U hU [GOAL] case is_nonarchimedean A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B this : TopologicalSpace A := topology hB U : Set A hU : U ∈ 𝓝 0 ⊢ ∃ V, ↑V ⊆ U [PROOFSTEP] obtain ⟨i, -, hi : (B i : Set A) ⊆ U⟩ := hB.hasBasis_nhds_zero.mem_iff.mp hU [GOAL] case is_nonarchimedean.intro.intro A : Type u_1 ι : Type u_2 inst✝¹ : Ring A inst✝ : Nonempty ι B : ι → AddSubgroup A hB : RingSubgroupsBasis B this : TopologicalSpace A := topology hB U : Set A hU : U ∈ 𝓝 0 i : ι hi : ↑(B i) ⊆ U ⊢ ∃ V, ↑V ⊆ U [PROOFSTEP] exact ⟨hB.openAddSubgroup i, hi⟩ [GOAL] ι : Type u_1 R : Type u_2 A : Type u_3 inst✝² : CommRing R inst✝¹ : CommRing A inst✝ : Algebra R A B : ι → Submodule R A hB✝ hB : SubmodulesRingBasis B ⊢ RingSubgroupsBasis fun i => Submodule.toAddSubgroup (B i) [PROOFSTEP] apply RingSubgroupsBasis.of_comm (fun i => (B i).toAddSubgroup) hB.inter hB.mul [GOAL] ι : Type u_1 R : Type u_2 A : Type u_3 inst✝² : CommRing R inst✝¹ : CommRing A inst✝ : Algebra R A B : ι → Submodule R A hB✝ hB : SubmodulesRingBasis B ⊢ ∀ (x : A) (i : ι), ∃ j, ↑(Submodule.toAddSubgroup (B j)) ⊆ (fun y => x * y) ⁻¹' ↑(Submodule.toAddSubgroup (B i)) [PROOFSTEP] intro a i [GOAL] ι : Type u_1 R : Type u_2 A : Type u_3 inst✝² : CommRing R inst✝¹ : CommRing A inst✝ : Algebra R A B : ι → Submodule R A hB✝ hB : SubmodulesRingBasis B a : A i : ι ⊢ ∃ j, ↑(Submodule.toAddSubgroup (B j)) ⊆ (fun y => a * y) ⁻¹' ↑(Submodule.toAddSubgroup (B i)) [PROOFSTEP] rcases hB.leftMul a i with ⟨j, hj⟩ [GOAL] case intro ι : Type u_1 R : Type u_2 A : Type u_3 inst✝² : CommRing R inst✝¹ : CommRing A inst✝ : Algebra R A B : ι → Submodule R A hB✝ hB : SubmodulesRingBasis B a : A i j : ι hj : a • B j ≤ B i ⊢ ∃ j, ↑(Submodule.toAddSubgroup (B j)) ⊆ (fun y => a * y) ⁻¹' ↑(Submodule.toAddSubgroup (B i)) [PROOFSTEP] use j [GOAL] case h ι : Type u_1 R : Type u_2 A : Type u_3 inst✝² : CommRing R inst✝¹ : CommRing A inst✝ : Algebra R A B : ι → Submodule R A hB✝ hB : SubmodulesRingBasis B a : A i j : ι hj : a • B j ≤ B i ⊢ ↑(Submodule.toAddSubgroup (B j)) ⊆ (fun y => a * y) ⁻¹' ↑(Submodule.toAddSubgroup (B i)) [PROOFSTEP] rintro b (b_in : b ∈ B j) [GOAL] case h ι : Type u_1 R : Type u_2 A : Type u_3 inst✝² : CommRing R inst✝¹ : CommRing A inst✝ : Algebra R A B : ι → Submodule R A hB✝ hB : SubmodulesRingBasis B a : A i j : ι hj : a • B j ≤ B i b : A b_in : b ∈ B j ⊢ b ∈ (fun y => a * y) ⁻¹' ↑(Submodule.toAddSubgroup (B i)) [PROOFSTEP] exact hj ⟨b, b_in, rfl⟩ [GOAL] ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B ⊢ Set.Nonempty {U | ∃ i, U = ↑(B i)} [PROOFSTEP] inhabit ι [GOAL] ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B inhabited_h : Inhabited ι ⊢ Set.Nonempty {U | ∃ i, U = ↑(B i)} [PROOFSTEP] exact ⟨B default, default, rfl⟩ [GOAL] ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B ⊢ ∀ {x y : Set M}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y [PROOFSTEP] rintro _ _ ⟨i, rfl⟩ ⟨j, rfl⟩ [GOAL] case intro.intro ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B i j : ι ⊢ ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ ↑(B i) ∩ ↑(B j) [PROOFSTEP] cases' hB.inter i j with k hk [GOAL] case intro.intro.intro ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B i j k : ι hk : B k ≤ B i ⊓ B j ⊢ ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ ↑(B i) ∩ ↑(B j) [PROOFSTEP] use B k [GOAL] case h ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B i j k : ι hk : B k ≤ B i ⊓ B j ⊢ ↑(B k) ∈ {U | ∃ i, U = ↑(B i)} ∧ ↑(B k) ⊆ ↑(B i) ∩ ↑(B j) [PROOFSTEP] constructor [GOAL] case h.left ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B i j k : ι hk : B k ≤ B i ⊓ B j ⊢ ↑(B k) ∈ {U | ∃ i, U = ↑(B i)} [PROOFSTEP] use k [GOAL] case h.right ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B i j k : ι hk : B k ≤ B i ⊓ B j ⊢ ↑(B k) ⊆ ↑(B i) ∩ ↑(B j) [PROOFSTEP] exact hk [GOAL] ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B ⊢ ∀ {U : Set M}, U ∈ { sets := {U | ∃ i, U = ↑(B i)}, nonempty := (_ : ∃ x, x ∈ {U | ∃ i, U = ↑(B i)}), inter_sets := (_ : ∀ {x y : Set M}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y) }.sets → 0 ∈ U [PROOFSTEP] rintro _ ⟨i, rfl⟩ [GOAL] case intro ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B i : ι ⊢ 0 ∈ ↑(B i) [PROOFSTEP] exact (B i).zero_mem [GOAL] ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B ⊢ ∀ {U : Set M}, U ∈ { sets := {U | ∃ i, U = ↑(B i)}, nonempty := (_ : ∃ x, x ∈ {U | ∃ i, U = ↑(B i)}), inter_sets := (_ : ∀ {x y : Set M}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y) }.sets → ∃ V, V ∈ { sets := {U | ∃ i, U = ↑(B i)}, nonempty := (_ : ∃ x, x ∈ {U | ∃ i, U = ↑(B i)}), inter_sets := (_ : ∀ {x y : Set M}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y) }.sets ∧ V + V ⊆ U [PROOFSTEP] rintro _ ⟨i, rfl⟩ [GOAL] case intro ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B i : ι ⊢ ∃ V, V ∈ { sets := {U | ∃ i, U = ↑(B i)}, nonempty := (_ : ∃ x, x ∈ {U | ∃ i, U = ↑(B i)}), inter_sets := (_ : ∀ {x y : Set M}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y) }.sets ∧ V + V ⊆ ↑(B i) [PROOFSTEP] use B i [GOAL] case h ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B i : ι ⊢ ↑(B i) ∈ { sets := {U | ∃ i, U = ↑(B i)}, nonempty := (_ : ∃ x, x ∈ {U | ∃ i, U = ↑(B i)}), inter_sets := (_ : ∀ {x y : Set M}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y) }.sets ∧ ↑(B i) + ↑(B i) ⊆ ↑(B i) [PROOFSTEP] constructor [GOAL] case h.left ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B i : ι ⊢ ↑(B i) ∈ { sets := {U | ∃ i, U = ↑(B i)}, nonempty := (_ : ∃ x, x ∈ {U | ∃ i, U = ↑(B i)}), inter_sets := (_ : ∀ {x y : Set M}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y) }.sets [PROOFSTEP] use i [GOAL] case h.right ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B i : ι ⊢ ↑(B i) + ↑(B i) ⊆ ↑(B i) [PROOFSTEP] rintro x ⟨y, z, y_in, z_in, rfl⟩ [GOAL] case h.right.intro.intro.intro.intro ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B i : ι y z : M y_in : y ∈ ↑(B i) z_in : z ∈ ↑(B i) ⊢ (fun x x_1 => x + x_1) y z ∈ ↑(B i) [PROOFSTEP] exact (B i).add_mem y_in z_in [GOAL] ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B ⊢ ∀ {U : Set M}, U ∈ { sets := {U | ∃ i, U = ↑(B i)}, nonempty := (_ : ∃ x, x ∈ {U | ∃ i, U = ↑(B i)}), inter_sets := (_ : ∀ {x y : Set M}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y) }.sets → ∃ V, V ∈ { sets := {U | ∃ i, U = ↑(B i)}, nonempty := (_ : ∃ x, x ∈ {U | ∃ i, U = ↑(B i)}), inter_sets := (_ : ∀ {x y : Set M}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y) }.sets ∧ V ⊆ (fun x => -x) ⁻¹' U [PROOFSTEP] rintro _ ⟨i, rfl⟩ [GOAL] case intro ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B i : ι ⊢ ∃ V, V ∈ { sets := {U | ∃ i, U = ↑(B i)}, nonempty := (_ : ∃ x, x ∈ {U | ∃ i, U = ↑(B i)}), inter_sets := (_ : ∀ {x y : Set M}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y) }.sets ∧ V ⊆ (fun x => -x) ⁻¹' ↑(B i) [PROOFSTEP] use B i [GOAL] case h ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B i : ι ⊢ ↑(B i) ∈ { sets := {U | ∃ i, U = ↑(B i)}, nonempty := (_ : ∃ x, x ∈ {U | ∃ i, U = ↑(B i)}), inter_sets := (_ : ∀ {x y : Set M}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y) }.sets ∧ ↑(B i) ⊆ (fun x => -x) ⁻¹' ↑(B i) [PROOFSTEP] constructor [GOAL] case h.left ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B i : ι ⊢ ↑(B i) ∈ { sets := {U | ∃ i, U = ↑(B i)}, nonempty := (_ : ∃ x, x ∈ {U | ∃ i, U = ↑(B i)}), inter_sets := (_ : ∀ {x y : Set M}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y) }.sets [PROOFSTEP] use i [GOAL] case h.right ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B i : ι ⊢ ↑(B i) ⊆ (fun x => -x) ⁻¹' ↑(B i) [PROOFSTEP] intro x x_in [GOAL] case h.right ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B i : ι x : M x_in : x ∈ ↑(B i) ⊢ x ∈ (fun x => -x) ⁻¹' ↑(B i) [PROOFSTEP] exact (B i).neg_mem x_in [GOAL] ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B ⊢ ∀ (x₀ : M) {U : Set M}, U ∈ { sets := {U | ∃ i, U = ↑(B i)}, nonempty := (_ : ∃ x, x ∈ {U | ∃ i, U = ↑(B i)}), inter_sets := (_ : ∀ {x y : Set M}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y) }.sets → ∃ V, V ∈ { sets := {U | ∃ i, U = ↑(B i)}, nonempty := (_ : ∃ x, x ∈ {U | ∃ i, U = ↑(B i)}), inter_sets := (_ : ∀ {x y : Set M}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y) }.sets ∧ V ⊆ (fun x => x₀ + x + -x₀) ⁻¹' U [PROOFSTEP] rintro x₀ _ ⟨i, rfl⟩ [GOAL] case intro ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B x₀ : M i : ι ⊢ ∃ V, V ∈ { sets := {U | ∃ i, U = ↑(B i)}, nonempty := (_ : ∃ x, x ∈ {U | ∃ i, U = ↑(B i)}), inter_sets := (_ : ∀ {x y : Set M}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y) }.sets ∧ V ⊆ (fun x => x₀ + x + -x₀) ⁻¹' ↑(B i) [PROOFSTEP] use B i [GOAL] case h ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B x₀ : M i : ι ⊢ ↑(B i) ∈ { sets := {U | ∃ i, U = ↑(B i)}, nonempty := (_ : ∃ x, x ∈ {U | ∃ i, U = ↑(B i)}), inter_sets := (_ : ∀ {x y : Set M}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y) }.sets ∧ ↑(B i) ⊆ (fun x => x₀ + x + -x₀) ⁻¹' ↑(B i) [PROOFSTEP] constructor [GOAL] case h.left ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B x₀ : M i : ι ⊢ ↑(B i) ∈ { sets := {U | ∃ i, U = ↑(B i)}, nonempty := (_ : ∃ x, x ∈ {U | ∃ i, U = ↑(B i)}), inter_sets := (_ : ∀ {x y : Set M}, x ∈ {U | ∃ i, U = ↑(B i)} → y ∈ {U | ∃ i, U = ↑(B i)} → ∃ z, z ∈ {U | ∃ i, U = ↑(B i)} ∧ z ⊆ x ∩ y) }.sets [PROOFSTEP] use i [GOAL] case h.right ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B x₀ : M i : ι ⊢ ↑(B i) ⊆ (fun x => x₀ + x + -x₀) ⁻¹' ↑(B i) [PROOFSTEP] simp [GOAL] ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B ⊢ ∀ {U : Set M}, U ∈ AddGroupFilterBasis.toFilterBasis.sets → ∃ V, V ∈ 𝓝 0 ∧ ∃ W, W ∈ AddGroupFilterBasis.toFilterBasis.sets ∧ V • W ⊆ U [PROOFSTEP] rintro _ ⟨i, rfl⟩ [GOAL] case intro ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B i : ι ⊢ ∃ V, V ∈ 𝓝 0 ∧ ∃ W, W ∈ AddGroupFilterBasis.toFilterBasis.sets ∧ V • W ⊆ ↑(B i) [PROOFSTEP] use univ [GOAL] case h ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B i : ι ⊢ univ ∈ 𝓝 0 ∧ ∃ W, W ∈ AddGroupFilterBasis.toFilterBasis.sets ∧ univ • W ⊆ ↑(B i) [PROOFSTEP] constructor [GOAL] case h.left ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B i : ι ⊢ univ ∈ 𝓝 0 [PROOFSTEP] exact univ_mem [GOAL] case h.right ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B i : ι ⊢ ∃ W, W ∈ AddGroupFilterBasis.toFilterBasis.sets ∧ univ • W ⊆ ↑(B i) [PROOFSTEP] use B i [GOAL] case h ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B i : ι ⊢ ↑(B i) ∈ AddGroupFilterBasis.toFilterBasis.sets ∧ univ • ↑(B i) ⊆ ↑(B i) [PROOFSTEP] constructor [GOAL] case h.left ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B i : ι ⊢ ↑(B i) ∈ AddGroupFilterBasis.toFilterBasis.sets [PROOFSTEP] use i [GOAL] case h.right ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B i : ι ⊢ univ • ↑(B i) ⊆ ↑(B i) [PROOFSTEP] rintro _ ⟨a, m, -, hm, rfl⟩ [GOAL] case h.right.intro.intro.intro.intro ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B i : ι a : R m : M hm : m ∈ ↑(B i) ⊢ (fun x x_1 => x • x_1) a m ∈ ↑(B i) [PROOFSTEP] exact (B i).smul_mem _ hm [GOAL] ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B ⊢ ∀ (x₀ : R) {U : Set M}, U ∈ AddGroupFilterBasis.toFilterBasis.sets → ∃ V, V ∈ AddGroupFilterBasis.toFilterBasis.sets ∧ V ⊆ (fun x => x₀ • x) ⁻¹' U [PROOFSTEP] rintro x₀ _ ⟨i, rfl⟩ [GOAL] case intro ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B x₀ : R i : ι ⊢ ∃ V, V ∈ AddGroupFilterBasis.toFilterBasis.sets ∧ V ⊆ (fun x => x₀ • x) ⁻¹' ↑(B i) [PROOFSTEP] use B i [GOAL] case h ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B x₀ : R i : ι ⊢ ↑(B i) ∈ AddGroupFilterBasis.toFilterBasis.sets ∧ ↑(B i) ⊆ (fun x => x₀ • x) ⁻¹' ↑(B i) [PROOFSTEP] constructor [GOAL] case h.left ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B x₀ : R i : ι ⊢ ↑(B i) ∈ AddGroupFilterBasis.toFilterBasis.sets [PROOFSTEP] use i [GOAL] case h.right ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B x₀ : R i : ι ⊢ ↑(B i) ⊆ (fun x => x₀ • x) ⁻¹' ↑(B i) [PROOFSTEP] intro m [GOAL] case h.right ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B x₀ : R i : ι m : M ⊢ m ∈ ↑(B i) → m ∈ (fun x => x₀ • x) ⁻¹' ↑(B i) [PROOFSTEP] exact (B i).smul_mem _ [GOAL] ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B ⊢ ∀ (m₀ : M) {U : Set M}, U ∈ AddGroupFilterBasis.toFilterBasis.sets → ∀ᶠ (x : R) in 𝓝 0, x • m₀ ∈ U [PROOFSTEP] rintro m₀ _ ⟨i, rfl⟩ [GOAL] case intro ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B m₀ : M i : ι ⊢ ∀ᶠ (x : R) in 𝓝 0, x • m₀ ∈ ↑(B i) [PROOFSTEP] exact hB.smul m₀ i [GOAL] ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B i : ι x✝ : TopologicalSpace M := topology hB src✝ : AddSubgroup M := Submodule.toAddSubgroup (B i) ⊢ IsOpen { toAddSubmonoid := src✝.toAddSubmonoid, neg_mem' := (_ : ∀ {x : M}, x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toAddSubmonoid.toAddSubsemigroup.carrier [PROOFSTEP] letI := hB.topology [GOAL] ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B i : ι x✝ : TopologicalSpace M := topology hB src✝ : AddSubgroup M := Submodule.toAddSubgroup (B i) this : TopologicalSpace M := topology hB ⊢ IsOpen { toAddSubmonoid := src✝.toAddSubmonoid, neg_mem' := (_ : ∀ {x : M}, x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toAddSubmonoid.toAddSubsemigroup.carrier [PROOFSTEP] rw [isOpen_iff_mem_nhds] [GOAL] ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B i : ι x✝ : TopologicalSpace M := topology hB src✝ : AddSubgroup M := Submodule.toAddSubgroup (B i) this : TopologicalSpace M := topology hB ⊢ ∀ (a : M), a ∈ { toAddSubmonoid := src✝.toAddSubmonoid, neg_mem' := (_ : ∀ {x : M}, x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toAddSubmonoid.toAddSubsemigroup.carrier → { toAddSubmonoid := src✝.toAddSubmonoid, neg_mem' := (_ : ∀ {x : M}, x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toAddSubmonoid.toAddSubsemigroup.carrier ∈ 𝓝 a [PROOFSTEP] intro a a_in [GOAL] ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B i : ι x✝ : TopologicalSpace M := topology hB src✝ : AddSubgroup M := Submodule.toAddSubgroup (B i) this : TopologicalSpace M := topology hB a : M a_in : a ∈ { toAddSubmonoid := src✝.toAddSubmonoid, neg_mem' := (_ : ∀ {x : M}, x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toAddSubmonoid.toAddSubsemigroup.carrier ⊢ { toAddSubmonoid := src✝.toAddSubmonoid, neg_mem' := (_ : ∀ {x : M}, x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toAddSubmonoid.toAddSubsemigroup.carrier ∈ 𝓝 a [PROOFSTEP] rw [(hB.toModuleFilterBasis.toAddGroupFilterBasis.nhds_hasBasis a).mem_iff] [GOAL] ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B i : ι x✝ : TopologicalSpace M := topology hB src✝ : AddSubgroup M := Submodule.toAddSubgroup (B i) this : TopologicalSpace M := topology hB a : M a_in : a ∈ { toAddSubmonoid := src✝.toAddSubmonoid, neg_mem' := (_ : ∀ {x : M}, x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toAddSubmonoid.toAddSubsemigroup.carrier ⊢ ∃ i, i ∈ (toModuleFilterBasis hB).toAddGroupFilterBasis ∧ (fun y => a + y) '' i ⊆ { toAddSubmonoid := src✝.toAddSubmonoid, neg_mem' := (_ : ∀ {x : M}, x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toAddSubmonoid.toAddSubsemigroup.carrier [PROOFSTEP] use B i [GOAL] case h ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B i : ι x✝ : TopologicalSpace M := topology hB src✝ : AddSubgroup M := Submodule.toAddSubgroup (B i) this : TopologicalSpace M := topology hB a : M a_in : a ∈ { toAddSubmonoid := src✝.toAddSubmonoid, neg_mem' := (_ : ∀ {x : M}, x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toAddSubmonoid.toAddSubsemigroup.carrier ⊢ ↑(B i) ∈ (toModuleFilterBasis hB).toAddGroupFilterBasis ∧ (fun y => a + y) '' ↑(B i) ⊆ { toAddSubmonoid := src✝.toAddSubmonoid, neg_mem' := (_ : ∀ {x : M}, x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toAddSubmonoid.toAddSubsemigroup.carrier [PROOFSTEP] constructor [GOAL] case h.left ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B i : ι x✝ : TopologicalSpace M := topology hB src✝ : AddSubgroup M := Submodule.toAddSubgroup (B i) this : TopologicalSpace M := topology hB a : M a_in : a ∈ { toAddSubmonoid := src✝.toAddSubmonoid, neg_mem' := (_ : ∀ {x : M}, x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toAddSubmonoid.toAddSubsemigroup.carrier ⊢ ↑(B i) ∈ (toModuleFilterBasis hB).toAddGroupFilterBasis [PROOFSTEP] use i [GOAL] case h.right ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B i : ι x✝ : TopologicalSpace M := topology hB src✝ : AddSubgroup M := Submodule.toAddSubgroup (B i) this : TopologicalSpace M := topology hB a : M a_in : a ∈ { toAddSubmonoid := src✝.toAddSubmonoid, neg_mem' := (_ : ∀ {x : M}, x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toAddSubmonoid.toAddSubsemigroup.carrier ⊢ (fun y => a + y) '' ↑(B i) ⊆ { toAddSubmonoid := src✝.toAddSubmonoid, neg_mem' := (_ : ∀ {x : M}, x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toAddSubmonoid.toAddSubsemigroup.carrier [PROOFSTEP] rintro - ⟨b, b_in, rfl⟩ [GOAL] case h.right.intro.intro ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB : SubmodulesBasis B i : ι x✝ : TopologicalSpace M := topology hB src✝ : AddSubgroup M := Submodule.toAddSubgroup (B i) this : TopologicalSpace M := topology hB a : M a_in : a ∈ { toAddSubmonoid := src✝.toAddSubmonoid, neg_mem' := (_ : ∀ {x : M}, x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toAddSubmonoid.toAddSubsemigroup.carrier b : M b_in : b ∈ ↑(B i) ⊢ (fun y => a + y) b ∈ { toAddSubmonoid := src✝.toAddSubmonoid, neg_mem' := (_ : ∀ {x : M}, x ∈ src✝.carrier → -x ∈ src✝.carrier) }.toAddSubmonoid.toAddSubsemigroup.carrier [PROOFSTEP] exact (B i).add_mem a_in b_in [GOAL] ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB✝ hB : SubmodulesBasis B ⊢ NonarchimedeanAddGroup M [PROOFSTEP] letI := hB.topology [GOAL] ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB✝ hB : SubmodulesBasis B this : TopologicalSpace M := topology hB ⊢ NonarchimedeanAddGroup M [PROOFSTEP] constructor [GOAL] case is_nonarchimedean ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB✝ hB : SubmodulesBasis B this : TopologicalSpace M := topology hB ⊢ ∀ (U : Set M), U ∈ 𝓝 0 → ∃ V, ↑V ⊆ U [PROOFSTEP] intro U hU [GOAL] case is_nonarchimedean ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB✝ hB : SubmodulesBasis B this : TopologicalSpace M := topology hB U : Set M hU : U ∈ 𝓝 0 ⊢ ∃ V, ↑V ⊆ U [PROOFSTEP] obtain ⟨-, ⟨i, rfl⟩, hi : (B i : Set M) ⊆ U⟩ := hB.toModuleFilterBasis.toAddGroupFilterBasis.nhds_zero_hasBasis.mem_iff.mp hU [GOAL] case is_nonarchimedean.intro.intro.intro ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁶ : CommRing R inst✝⁵ : CommRing A inst✝⁴ : Algebra R A M : Type u_4 inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : TopologicalSpace R inst✝ : Nonempty ι B : ι → Submodule R M hB✝ hB : SubmodulesBasis B this : TopologicalSpace M := topology hB U : Set M hU : U ∈ 𝓝 0 i : ι hi : ↑(B i) ⊆ U ⊢ ∃ V, ↑V ⊆ U [PROOFSTEP] exact ⟨hB.openAddSubgroup i, hi⟩ [GOAL] ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁴ : CommRing R inst✝³ : CommRing A inst✝² : Algebra R A M : Type u_4 inst✝¹ : AddCommGroup M inst✝ : Module R M BR : RingFilterBasis R B : ι → Submodule R M hB : SubmodulesBasis BR B x✝ : TopologicalSpace R := topology BR ⊢ ∀ (m : M) (i : ι), ∀ᶠ (a : R) in 𝓝 0, a • m ∈ B i [PROOFSTEP] letI := BR.topology [GOAL] ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁴ : CommRing R inst✝³ : CommRing A inst✝² : Algebra R A M : Type u_4 inst✝¹ : AddCommGroup M inst✝ : Module R M BR : RingFilterBasis R B : ι → Submodule R M hB : SubmodulesBasis BR B x✝ : TopologicalSpace R := topology BR this : TopologicalSpace R := topology BR ⊢ ∀ (m : M) (i : ι), ∀ᶠ (a : R) in 𝓝 0, a • m ∈ B i [PROOFSTEP] intro m i [GOAL] ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁴ : CommRing R inst✝³ : CommRing A inst✝² : Algebra R A M : Type u_4 inst✝¹ : AddCommGroup M inst✝ : Module R M BR : RingFilterBasis R B : ι → Submodule R M hB : SubmodulesBasis BR B x✝ : TopologicalSpace R := topology BR this : TopologicalSpace R := topology BR m : M i : ι ⊢ ∀ᶠ (a : R) in 𝓝 0, a • m ∈ B i [PROOFSTEP] rcases hB.smul m i with ⟨V, V_in, hV⟩ [GOAL] case intro.intro ι : Type u_1 R : Type u_2 A : Type u_3 inst✝⁴ : CommRing R inst✝³ : CommRing A inst✝² : Algebra R A M : Type u_4 inst✝¹ : AddCommGroup M inst✝ : Module R M BR : RingFilterBasis R B : ι → Submodule R M hB : SubmodulesBasis BR B x✝ : TopologicalSpace R := topology BR this : TopologicalSpace R := topology BR m : M i : ι V : Set R V_in : V ∈ BR hV : V ⊆ (fun x => x • m) ⁻¹' ↑(B i) ⊢ ∀ᶠ (a : R) in 𝓝 0, a • m ∈ B i [PROOFSTEP] exact mem_of_superset (BR.toAddGroupFilterBasis.mem_nhds_zero V_in) hV
Formal statement is: lemmas eucl_rel_poly_unique_div = eucl_rel_poly_unique [THEN conjunct1] Informal statement is: If $p$ is a polynomial over a Euclidean domain $R$, then $p$ has a unique factorization into irreducible polynomials.
[STATEMENT] lemma lemma_2_9_i: "b \<in> supremum A \<Longrightarrow> a * b \<in> supremum ((*) a ` A)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. b \<in> supremum A \<Longrightarrow> a * b \<in> supremum ((*) a ` A) [PROOF STEP] apply (simp add: supremum_def upper_bound_def) [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<forall>x\<in>A. x \<le> b) \<and> (\<forall>x. (\<forall>xa\<in>A. xa \<le> x) \<longrightarrow> b \<le> x) \<Longrightarrow> (\<forall>x\<in>A. a * x \<le> a * b) \<and> (\<forall>x. (\<forall>xa\<in>A. a * xa \<le> x) \<longrightarrow> a * b \<le> x) [PROOF STEP] apply safe [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<And>x. \<lbrakk>\<forall>x\<in>A. x \<le> b; \<forall>x. (\<forall>xa\<in>A. xa \<le> x) \<longrightarrow> b \<le> x; x \<in> A\<rbrakk> \<Longrightarrow> a * x \<le> a * b 2. \<And>x. \<lbrakk>\<forall>x\<in>A. x \<le> b; \<forall>x. (\<forall>xa\<in>A. xa \<le> x) \<longrightarrow> b \<le> x; \<forall>xa\<in>A. a * xa \<le> x\<rbrakk> \<Longrightarrow> a * b \<le> x [PROOF STEP] apply (simp add: mult_left_mono) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>x. \<lbrakk>\<forall>x\<in>A. x \<le> b; \<forall>x. (\<forall>xa\<in>A. xa \<le> x) \<longrightarrow> b \<le> x; \<forall>xa\<in>A. a * xa \<le> x\<rbrakk> \<Longrightarrow> a * b \<le> x [PROOF STEP] by (simp add: right_residual)
Require Import GHC.Num. (* Characters *) Require Import NArith. Definition Char := N. Bind Scope char_scope with N. (* Notation for literal characters in Coq source. *) Require Import Coq.Strings.Ascii. Definition hs_char__ : Ascii.ascii -> Char := N_of_ascii. Notation "'&#' c" := (hs_char__ c) (at level 1, format "'&#' c"). Definition chr : Int -> Char := Z.to_N. (* newline character *) Definition newline := hs_char__ "010".
Require Import CoqRefinements.Types. Require Import ProofIrrelevance. Require Import ZArith. Require Import Lia. Require Import CoqRefinements.Common. Require Import CoqRefinements.Tactics. Require Import PLF.LibTactics. Require Import Program.Utils. (* for 'dec' *) Open Scope Z_scope. Section nat_lt_ind_principle. Variable P : Nat -> Prop. Hypothesis ind_n : forall n:Nat, (forall k:{v:Z | v >= 0 /\ v < `n}, P ltac:(upcast k)) -> P n. Theorem nat_lt_ind (n: Nat) : P n. (* enough (H0: forall p, p <= n -> P p). - apply H0, le_n. *) case n; intros n_val n_ref. generalize n_ref. pattern n_val. apply Z_lt_induction. + intros; apply ind_n; intros; destruct k. apply H. simpl in *. lia. + lia. Qed. End nat_lt_ind_principle. Section natZ_lex_ind_principle. Variable P : Nat -> Nat -> Prop. Hypothesis true_for_lzero : forall m n:Nat, `m = 0 -> P m n. Hypothesis ind_m : forall m n, `m > 0 -> (forall p q, lex_lt p q m n -> P p q) -> P m n. Theorem nat_lex_ind (m n: Nat) : P m n. Proof. (* destruct (splitZ_zero_pos m) as [ m_zero | m_pos]. *) revert n; induction m as [m IHm] using nat_lt_ind. destruct (dec (`m =? 0)). + intro; apply true_for_lzero; lia. + induction n as [n IHn] using nat_lt_ind. apply ind_m. * destruct m; simpl in *; try lia. * intros p q [ lt_p_m | [eq_p_m lt_q_n] ]. ++ applys_eq (IHm ltac:(infer p) q); reft_eq. ++ enough (p = m) as -> by (applys_eq (IHn ltac:(infer q)); reft_eq); reft_eq. Qed. End natZ_lex_ind_principle.
[STATEMENT] lemma (in finite_field) exist_irred: assumes "n > 0" obtains f where "monic_irreducible_poly R f" "degree f = n" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<And>f. \<lbrakk>m_i_p R f; Polynomials.degree f = n\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. (\<And>f. \<lbrakk>m_i_p R f; Polynomials.degree f = n\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] consider (i) "n = 1" | (ii) "n = 2" | (iii) "n>2" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>n = 1 \<Longrightarrow> thesis; n = 2 \<Longrightarrow> thesis; 2 < n \<Longrightarrow> thesis\<rbrakk> \<Longrightarrow> thesis [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: 0 < n goal (1 subgoal): 1. \<lbrakk>n = 1 \<Longrightarrow> thesis; n = 2 \<Longrightarrow> thesis; 2 < n \<Longrightarrow> thesis\<rbrakk> \<Longrightarrow> thesis [PROOF STEP] by linarith [PROOF STATE] proof (state) this: \<lbrakk>n = 1 \<Longrightarrow> ?thesis; n = 2 \<Longrightarrow> ?thesis; 2 < n \<Longrightarrow> ?thesis\<rbrakk> \<Longrightarrow> ?thesis goal (1 subgoal): 1. (\<And>f. \<lbrakk>m_i_p R f; Polynomials.degree f = n\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] then [PROOF STATE] proof (chain) picking this: \<lbrakk>n = 1 \<Longrightarrow> ?thesis; n = 2 \<Longrightarrow> ?thesis; 2 < n \<Longrightarrow> ?thesis\<rbrakk> \<Longrightarrow> ?thesis [PROOF STEP] have "card {f. monic_irreducible_poly R f \<and> degree f = n} > 0" (is "card ?A > 0") [PROOF STATE] proof (prove) using this: \<lbrakk>n = 1 \<Longrightarrow> ?thesis; n = 2 \<Longrightarrow> ?thesis; 2 < n \<Longrightarrow> ?thesis\<rbrakk> \<Longrightarrow> ?thesis goal (1 subgoal): 1. 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} [PROOF STEP] proof (cases) [PROOF STATE] proof (state) goal (3 subgoals): 1. n = 1 \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} 2. n = 2 \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} 3. 2 < n \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} [PROOF STEP] case i [PROOF STATE] proof (state) this: n = 1 goal (3 subgoals): 1. n = 1 \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} 2. n = 2 \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} 3. 2 < n \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} [PROOF STEP] hence "card ?A = order R" [PROOF STATE] proof (prove) using this: n = 1 goal (1 subgoal): 1. card {f. m_i_p R f \<and> Polynomials.degree f = n} = order R [PROOF STEP] using card_irred_1 [PROOF STATE] proof (prove) using this: n = 1 card {f. m_i_p R f \<and> Polynomials.degree f = 1} = order R goal (1 subgoal): 1. card {f. m_i_p R f \<and> Polynomials.degree f = n} = order R [PROOF STEP] by simp [PROOF STATE] proof (state) this: card {f. m_i_p R f \<and> Polynomials.degree f = n} = order R goal (3 subgoals): 1. n = 1 \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} 2. n = 2 \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} 3. 2 < n \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} [PROOF STEP] also [PROOF STATE] proof (state) this: card {f. m_i_p R f \<and> Polynomials.degree f = n} = order R goal (3 subgoals): 1. n = 1 \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} 2. n = 2 \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} 3. 2 < n \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} [PROOF STEP] have "... > 0" [PROOF STATE] proof (prove) goal (1 subgoal): 1. 0 < order R [PROOF STEP] using finite_field_min_order [PROOF STATE] proof (prove) using this: 1 < order R goal (1 subgoal): 1. 0 < order R [PROOF STEP] by simp [PROOF STATE] proof (state) this: 0 < order R goal (3 subgoals): 1. n = 1 \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} 2. n = 2 \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} 3. 2 < n \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} [PROOF STEP] finally [PROOF STATE] proof (chain) picking this: 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} goal (1 subgoal): 1. 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} [PROOF STEP] by simp [PROOF STATE] proof (state) this: 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} goal (2 subgoals): 1. n = 2 \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} 2. 2 < n \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} [PROOF STEP] next [PROOF STATE] proof (state) goal (2 subgoals): 1. n = 2 \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} 2. 2 < n \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} [PROOF STEP] case ii [PROOF STATE] proof (state) this: n = 2 goal (2 subgoals): 1. n = 2 \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} 2. 2 < n \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} [PROOF STEP] have "0 < (real (order R) * (real (order R) - 1)) / 2" [PROOF STATE] proof (prove) goal (1 subgoal): 1. 0 < real (order R) * (real (order R) - 1) / 2 [PROOF STEP] using finite_field_min_order [PROOF STATE] proof (prove) using this: 1 < order R goal (1 subgoal): 1. 0 < real (order R) * (real (order R) - 1) / 2 [PROOF STEP] by simp [PROOF STATE] proof (state) this: 0 < real (order R) * (real (order R) - 1) / 2 goal (2 subgoals): 1. n = 2 \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} 2. 2 < n \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} [PROOF STEP] also [PROOF STATE] proof (state) this: 0 < real (order R) * (real (order R) - 1) / 2 goal (2 subgoals): 1. n = 2 \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} 2. 2 < n \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} [PROOF STEP] have "... = (real (order R)^2 - order R) / 2" [PROOF STATE] proof (prove) goal (1 subgoal): 1. real (order R) * (real (order R) - 1) / 2 = ((real (order R))\<^sup>2 - real (order R)) / 2 [PROOF STEP] by (simp add:power2_eq_square algebra_simps) [PROOF STATE] proof (state) this: real (order R) * (real (order R) - 1) / 2 = ((real (order R))\<^sup>2 - real (order R)) / 2 goal (2 subgoals): 1. n = 2 \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} 2. 2 < n \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} [PROOF STEP] also [PROOF STATE] proof (state) this: real (order R) * (real (order R) - 1) / 2 = ((real (order R))\<^sup>2 - real (order R)) / 2 goal (2 subgoals): 1. n = 2 \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} 2. 2 < n \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} [PROOF STEP] have "... = real (card ?A)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. ((real (order R))\<^sup>2 - real (order R)) / 2 = real (card {f. m_i_p R f \<and> Polynomials.degree f = n}) [PROOF STEP] using ii [PROOF STATE] proof (prove) using this: n = 2 goal (1 subgoal): 1. ((real (order R))\<^sup>2 - real (order R)) / 2 = real (card {f. m_i_p R f \<and> Polynomials.degree f = n}) [PROOF STEP] by (subst card_irred_2[symmetric], simp) [PROOF STATE] proof (state) this: ((real (order R))\<^sup>2 - real (order R)) / 2 = real (card {f. m_i_p R f \<and> Polynomials.degree f = n}) goal (2 subgoals): 1. n = 2 \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} 2. 2 < n \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} [PROOF STEP] finally [PROOF STATE] proof (chain) picking this: 0 < real (card {f. m_i_p R f \<and> Polynomials.degree f = n}) [PROOF STEP] have " 0 < real (card ?A)" [PROOF STATE] proof (prove) using this: 0 < real (card {f. m_i_p R f \<and> Polynomials.degree f = n}) goal (1 subgoal): 1. 0 < real (card {f. m_i_p R f \<and> Polynomials.degree f = n}) [PROOF STEP] by simp [PROOF STATE] proof (state) this: 0 < real (card {f. m_i_p R f \<and> Polynomials.degree f = n}) goal (2 subgoals): 1. n = 2 \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} 2. 2 < n \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} [PROOF STEP] then [PROOF STATE] proof (chain) picking this: 0 < real (card {f. m_i_p R f \<and> Polynomials.degree f = n}) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: 0 < real (card {f. m_i_p R f \<and> Polynomials.degree f = n}) goal (1 subgoal): 1. 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} [PROOF STEP] by simp [PROOF STATE] proof (state) this: 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} goal (1 subgoal): 1. 2 < n \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. 2 < n \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} [PROOF STEP] case iii [PROOF STATE] proof (state) this: 2 < n goal (1 subgoal): 1. 2 < n \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} [PROOF STEP] have "0 < real (order R)^n / (2*real n)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. 0 < real (order R) ^ n / (2 * real n) [PROOF STEP] using finite_field_min_order assms [PROOF STATE] proof (prove) using this: 1 < order R 0 < n goal (1 subgoal): 1. 0 < real (order R) ^ n / (2 * real n) [PROOF STEP] by simp [PROOF STATE] proof (state) this: 0 < real (order R) ^ n / (2 * real n) goal (1 subgoal): 1. 2 < n \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} [PROOF STEP] also [PROOF STATE] proof (state) this: 0 < real (order R) ^ n / (2 * real n) goal (1 subgoal): 1. 2 < n \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} [PROOF STEP] have "... \<le> real (card ?A)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. real (order R) ^ n / (2 * real n) \<le> real (card {f. m_i_p R f \<and> Polynomials.degree f = n}) [PROOF STEP] using iii card_irred_gt_2 [PROOF STATE] proof (prove) using this: 2 < n 2 < ?n \<Longrightarrow> real (order R) ^ ?n / (2 * real ?n) \<le> real (card {f. m_i_p R f \<and> Polynomials.degree f = ?n}) goal (1 subgoal): 1. real (order R) ^ n / (2 * real n) \<le> real (card {f. m_i_p R f \<and> Polynomials.degree f = n}) [PROOF STEP] by simp [PROOF STATE] proof (state) this: real (order R) ^ n / (2 * real n) \<le> real (card {f. m_i_p R f \<and> Polynomials.degree f = n}) goal (1 subgoal): 1. 2 < n \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} [PROOF STEP] finally [PROOF STATE] proof (chain) picking this: 0 < real (card {f. m_i_p R f \<and> Polynomials.degree f = n}) [PROOF STEP] have "0 < real (card ?A)" [PROOF STATE] proof (prove) using this: 0 < real (card {f. m_i_p R f \<and> Polynomials.degree f = n}) goal (1 subgoal): 1. 0 < real (card {f. m_i_p R f \<and> Polynomials.degree f = n}) [PROOF STEP] by simp [PROOF STATE] proof (state) this: 0 < real (card {f. m_i_p R f \<and> Polynomials.degree f = n}) goal (1 subgoal): 1. 2 < n \<Longrightarrow> 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} [PROOF STEP] then [PROOF STATE] proof (chain) picking this: 0 < real (card {f. m_i_p R f \<and> Polynomials.degree f = n}) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: 0 < real (card {f. m_i_p R f \<and> Polynomials.degree f = n}) goal (1 subgoal): 1. 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} [PROOF STEP] by simp [PROOF STATE] proof (state) this: 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} goal (1 subgoal): 1. (\<And>f. \<lbrakk>m_i_p R f; Polynomials.degree f = n\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] hence "?A \<noteq> {}" [PROOF STATE] proof (prove) using this: 0 < card {f. m_i_p R f \<and> Polynomials.degree f = n} goal (1 subgoal): 1. {f. m_i_p R f \<and> Polynomials.degree f = n} \<noteq> {} [PROOF STEP] by (metis card.empty nless_le) [PROOF STATE] proof (state) this: {f. m_i_p R f \<and> Polynomials.degree f = n} \<noteq> {} goal (1 subgoal): 1. (\<And>f. \<lbrakk>m_i_p R f; Polynomials.degree f = n\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] then [PROOF STATE] proof (chain) picking this: {f. m_i_p R f \<and> Polynomials.degree f = n} \<noteq> {} [PROOF STEP] obtain f where "monic_irreducible_poly R f" "degree f = n" [PROOF STATE] proof (prove) using this: {f. m_i_p R f \<and> Polynomials.degree f = n} \<noteq> {} goal (1 subgoal): 1. (\<And>f. \<lbrakk>m_i_p R f; Polynomials.degree f = n\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by auto [PROOF STATE] proof (state) this: m_i_p R f Polynomials.degree f = n goal (1 subgoal): 1. (\<And>f. \<lbrakk>m_i_p R f; Polynomials.degree f = n\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] thus ?thesis [PROOF STATE] proof (prove) using this: m_i_p R f Polynomials.degree f = n goal (1 subgoal): 1. thesis [PROOF STEP] using that [PROOF STATE] proof (prove) using this: m_i_p R f Polynomials.degree f = n \<lbrakk>m_i_p R ?f; Polynomials.degree ?f = n\<rbrakk> \<Longrightarrow> thesis goal (1 subgoal): 1. thesis [PROOF STEP] by simp [PROOF STATE] proof (state) this: thesis goal: No subgoals! [PROOF STEP] qed
Require Import Tactical.SimplMatch. Module SimplMatchTests. (** test simpl_match failure when match does not go away *) Theorem fails_if_match_not_removed : forall (vd m: nat -> option nat) a, vd a = m a -> vd a = match (m a) with | Some v => Some v | None => None end. Proof. intros. (simpl_match; fail "should not work here") || idtac. rewrite H. destruct (m a); auto. Qed. Theorem removes_match : forall (vd m: nat -> option nat) a v v', vd a = Some v -> m a = Some v' -> vd a = match (m a) with | Some _ => Some v | None => None end. Proof. intros. simpl_match; now auto. Qed. (** hypothesis replacement should remove the match or fail *) Theorem fails_on_hyp_if_match_not_removed : forall (vd m: nat -> option nat) a, vd a = m a -> m a = match (m a) with | Some v => Some v | None => None end -> True. Proof. intros. (simpl_match; fail "should not work here") || idtac. trivial. Qed. End SimplMatchTests. Module DestructMatchesTests. Theorem removes_absurdities : forall b1 b2, b1 = b2 -> match b1 with | true => match b2 with | true => True | false => False end | false => match b2 with | true => False | false => True end end. Proof. intros. destruct_all_matches. Qed. Theorem destructs_innermost_match : forall b1 b2, match (match b2 with | true => b1 | false => false end) with | true => b1 = true | false => b1 = false \/ b2 = false end. Proof. intros. destruct_goal_matches. Qed. End DestructMatchesTests.
Formal statement is: lemma contour_integral_subpath_refl [simp]: "contour_integral (subpath u u g) f = 0" Informal statement is: The contour integral of a function $f$ along a subpath of a path $g$ from $u$ to $u$ is zero.
(* Title: HOL/Limits.thy Author: Brian Huffman Author: Jacques D. Fleuriot, University of Cambridge Author: Lawrence C Paulson Author: Jeremy Avigad *) section \<open>Limits on Real Vector Spaces\<close> theory Limits imports Real_Vector_Spaces begin lemma range_mult [simp]: fixes a::"real" shows "range ((*) a) = (if a=0 then {0} else UNIV)" by (simp add: surj_def) (meson dvdE dvd_field_iff) subsection \<open>Filter going to infinity norm\<close> definition at_infinity :: "'a::real_normed_vector filter" where "at_infinity = (INF r. principal {x. r \<le> norm x})" lemma eventually_at_infinity: "eventually P at_infinity \<longleftrightarrow> (\<exists>b. \<forall>x. b \<le> norm x \<longrightarrow> P x)" unfolding at_infinity_def by (subst eventually_INF_base) (auto simp: subset_eq eventually_principal intro!: exI[of _ "max a b" for a b]) corollary eventually_at_infinity_pos: "eventually p at_infinity \<longleftrightarrow> (\<exists>b. 0 < b \<and> (\<forall>x. norm x \<ge> b \<longrightarrow> p x))" unfolding eventually_at_infinity by (meson le_less_trans norm_ge_zero not_le zero_less_one) lemma at_infinity_eq_at_top_bot: "(at_infinity :: real filter) = sup at_top at_bot" proof - have 1: "\<lbrakk>\<forall>n\<ge>u. A n; \<forall>n\<le>v. A n\<rbrakk> \<Longrightarrow> \<exists>b. \<forall>x. b \<le> \<bar>x\<bar> \<longrightarrow> A x" for A and u v::real by (rule_tac x="max (- v) u" in exI) (auto simp: abs_real_def) have 2: "\<forall>x. u \<le> \<bar>x\<bar> \<longrightarrow> A x \<Longrightarrow> \<exists>N. \<forall>n\<ge>N. A n" for A and u::real by (meson abs_less_iff le_cases less_le_not_le) have 3: "\<forall>x. u \<le> \<bar>x\<bar> \<longrightarrow> A x \<Longrightarrow> \<exists>N. \<forall>n\<le>N. A n" for A and u::real by (metis (full_types) abs_ge_self abs_minus_cancel le_minus_iff order_trans) show ?thesis by (auto simp: filter_eq_iff eventually_sup eventually_at_infinity eventually_at_top_linorder eventually_at_bot_linorder intro: 1 2 3) qed lemma at_top_le_at_infinity: "at_top \<le> (at_infinity :: real filter)" unfolding at_infinity_eq_at_top_bot by simp lemma at_bot_le_at_infinity: "at_bot \<le> (at_infinity :: real filter)" unfolding at_infinity_eq_at_top_bot by simp lemma filterlim_at_top_imp_at_infinity: "filterlim f at_top F \<Longrightarrow> filterlim f at_infinity F" for f :: "_ \<Rightarrow> real" by (rule filterlim_mono[OF _ at_top_le_at_infinity order_refl]) lemma filterlim_real_at_infinity_sequentially: "filterlim real at_infinity sequentially" by (simp add: filterlim_at_top_imp_at_infinity filterlim_real_sequentially) lemma lim_infinity_imp_sequentially: "(f \<longlongrightarrow> l) at_infinity \<Longrightarrow> ((\<lambda>n. f(n)) \<longlongrightarrow> l) sequentially" by (simp add: filterlim_at_top_imp_at_infinity filterlim_compose filterlim_real_sequentially) subsubsection \<open>Boundedness\<close> definition Bfun :: "('a \<Rightarrow> 'b::metric_space) \<Rightarrow> 'a filter \<Rightarrow> bool" where Bfun_metric_def: "Bfun f F = (\<exists>y. \<exists>K>0. eventually (\<lambda>x. dist (f x) y \<le> K) F)" abbreviation Bseq :: "(nat \<Rightarrow> 'a::metric_space) \<Rightarrow> bool" where "Bseq X \<equiv> Bfun X sequentially" lemma Bseq_conv_Bfun: "Bseq X \<longleftrightarrow> Bfun X sequentially" .. lemma Bseq_ignore_initial_segment: "Bseq X \<Longrightarrow> Bseq (\<lambda>n. X (n + k))" unfolding Bfun_metric_def by (subst eventually_sequentially_seg) lemma Bseq_offset: "Bseq (\<lambda>n. X (n + k)) \<Longrightarrow> Bseq X" unfolding Bfun_metric_def by (subst (asm) eventually_sequentially_seg) lemma Bfun_def: "Bfun f F \<longleftrightarrow> (\<exists>K>0. eventually (\<lambda>x. norm (f x) \<le> K) F)" unfolding Bfun_metric_def norm_conv_dist proof safe fix y K assume K: "0 < K" and *: "eventually (\<lambda>x. dist (f x) y \<le> K) F" moreover have "eventually (\<lambda>x. dist (f x) 0 \<le> dist (f x) y + dist 0 y) F" by (intro always_eventually) (metis dist_commute dist_triangle) with * have "eventually (\<lambda>x. dist (f x) 0 \<le> K + dist 0 y) F" by eventually_elim auto with \<open>0 < K\<close> show "\<exists>K>0. eventually (\<lambda>x. dist (f x) 0 \<le> K) F" by (intro exI[of _ "K + dist 0 y"] add_pos_nonneg conjI zero_le_dist) auto qed (force simp del: norm_conv_dist [symmetric]) lemma BfunI: assumes K: "eventually (\<lambda>x. norm (f x) \<le> K) F" shows "Bfun f F" unfolding Bfun_def proof (intro exI conjI allI) show "0 < max K 1" by simp show "eventually (\<lambda>x. norm (f x) \<le> max K 1) F" using K by (rule eventually_mono) simp qed lemma BfunE: assumes "Bfun f F" obtains B where "0 < B" and "eventually (\<lambda>x. norm (f x) \<le> B) F" using assms unfolding Bfun_def by blast lemma Cauchy_Bseq: assumes "Cauchy X" shows "Bseq X" proof - have "\<exists>y K. 0 < K \<and> (\<exists>N. \<forall>n\<ge>N. dist (X n) y \<le> K)" if "\<And>m n. \<lbrakk>m \<ge> M; n \<ge> M\<rbrakk> \<Longrightarrow> dist (X m) (X n) < 1" for M by (meson order.order_iff_strict that zero_less_one) with assms show ?thesis by (force simp: Cauchy_def Bfun_metric_def eventually_sequentially) qed subsubsection \<open>Bounded Sequences\<close> lemma BseqI': "(\<And>n. norm (X n) \<le> K) \<Longrightarrow> Bseq X" by (intro BfunI) (auto simp: eventually_sequentially) lemma Bseq_def: "Bseq X \<longleftrightarrow> (\<exists>K>0. \<forall>n. norm (X n) \<le> K)" unfolding Bfun_def eventually_sequentially proof safe fix N K assume "0 < K" "\<forall>n\<ge>N. norm (X n) \<le> K" then show "\<exists>K>0. \<forall>n. norm (X n) \<le> K" by (intro exI[of _ "max (Max (norm ` X ` {..N})) K"] max.strict_coboundedI2) (auto intro!: imageI not_less[where 'a=nat, THEN iffD1] Max_ge simp: le_max_iff_disj) qed auto lemma BseqE: "Bseq X \<Longrightarrow> (\<And>K. 0 < K \<Longrightarrow> \<forall>n. norm (X n) \<le> K \<Longrightarrow> Q) \<Longrightarrow> Q" unfolding Bseq_def by auto lemma BseqD: "Bseq X \<Longrightarrow> \<exists>K. 0 < K \<and> (\<forall>n. norm (X n) \<le> K)" by (simp add: Bseq_def) lemma BseqI: "0 < K \<Longrightarrow> \<forall>n. norm (X n) \<le> K \<Longrightarrow> Bseq X" by (auto simp: Bseq_def) lemma Bseq_bdd_above: "Bseq X \<Longrightarrow> bdd_above (range X)" for X :: "nat \<Rightarrow> real" proof (elim BseqE, intro bdd_aboveI2) fix K n assume "0 < K" "\<forall>n. norm (X n) \<le> K" then show "X n \<le> K" by (auto elim!: allE[of _ n]) qed lemma Bseq_bdd_above': "Bseq X \<Longrightarrow> bdd_above (range (\<lambda>n. norm (X n)))" for X :: "nat \<Rightarrow> 'a :: real_normed_vector" proof (elim BseqE, intro bdd_aboveI2) fix K n assume "0 < K" "\<forall>n. norm (X n) \<le> K" then show "norm (X n) \<le> K" by (auto elim!: allE[of _ n]) qed lemma Bseq_bdd_below: "Bseq X \<Longrightarrow> bdd_below (range X)" for X :: "nat \<Rightarrow> real" proof (elim BseqE, intro bdd_belowI2) fix K n assume "0 < K" "\<forall>n. norm (X n) \<le> K" then show "- K \<le> X n" by (auto elim!: allE[of _ n]) qed lemma Bseq_eventually_mono: assumes "eventually (\<lambda>n. norm (f n) \<le> norm (g n)) sequentially" "Bseq g" shows "Bseq f" proof - from assms(2) obtain K where "0 < K" and "eventually (\<lambda>n. norm (g n) \<le> K) sequentially" unfolding Bfun_def by fast with assms(1) have "eventually (\<lambda>n. norm (f n) \<le> K) sequentially" by (fast elim: eventually_elim2 order_trans) with \<open>0 < K\<close> show "Bseq f" unfolding Bfun_def by fast qed lemma lemma_NBseq_def: "(\<exists>K > 0. \<forall>n. norm (X n) \<le> K) \<longleftrightarrow> (\<exists>N. \<forall>n. norm (X n) \<le> real(Suc N))" proof safe fix K :: real from reals_Archimedean2 obtain n :: nat where "K < real n" .. then have "K \<le> real (Suc n)" by auto moreover assume "\<forall>m. norm (X m) \<le> K" ultimately have "\<forall>m. norm (X m) \<le> real (Suc n)" by (blast intro: order_trans) then show "\<exists>N. \<forall>n. norm (X n) \<le> real (Suc N)" .. next show "\<And>N. \<forall>n. norm (X n) \<le> real (Suc N) \<Longrightarrow> \<exists>K>0. \<forall>n. norm (X n) \<le> K" using of_nat_0_less_iff by blast qed text \<open>Alternative definition for \<open>Bseq\<close>.\<close> lemma Bseq_iff: "Bseq X \<longleftrightarrow> (\<exists>N. \<forall>n. norm (X n) \<le> real(Suc N))" by (simp add: Bseq_def) (simp add: lemma_NBseq_def) lemma lemma_NBseq_def2: "(\<exists>K > 0. \<forall>n. norm (X n) \<le> K) = (\<exists>N. \<forall>n. norm (X n) < real(Suc N))" proof - have *: "\<And>N. \<forall>n. norm (X n) \<le> 1 + real N \<Longrightarrow> \<exists>N. \<forall>n. norm (X n) < 1 + real N" by (metis add.commute le_less_trans less_add_one of_nat_Suc) then show ?thesis unfolding lemma_NBseq_def by (metis less_le_not_le not_less_iff_gr_or_eq of_nat_Suc) qed text \<open>Yet another definition for Bseq.\<close> lemma Bseq_iff1a: "Bseq X \<longleftrightarrow> (\<exists>N. \<forall>n. norm (X n) < real (Suc N))" by (simp add: Bseq_def lemma_NBseq_def2) subsubsection \<open>A Few More Equivalence Theorems for Boundedness\<close> text \<open>Alternative formulation for boundedness.\<close> lemma Bseq_iff2: "Bseq X \<longleftrightarrow> (\<exists>k > 0. \<exists>x. \<forall>n. norm (X n + - x) \<le> k)" by (metis BseqE BseqI' add.commute add_cancel_right_left add_uminus_conv_diff norm_add_leD norm_minus_cancel norm_minus_commute) text \<open>Alternative formulation for boundedness.\<close> lemma Bseq_iff3: "Bseq X \<longleftrightarrow> (\<exists>k>0. \<exists>N. \<forall>n. norm (X n + - X N) \<le> k)" (is "?P \<longleftrightarrow> ?Q") proof assume ?P then obtain K where *: "0 < K" and **: "\<And>n. norm (X n) \<le> K" by (auto simp: Bseq_def) from * have "0 < K + norm (X 0)" by (rule order_less_le_trans) simp from ** have "\<forall>n. norm (X n - X 0) \<le> K + norm (X 0)" by (auto intro: order_trans norm_triangle_ineq4) then have "\<forall>n. norm (X n + - X 0) \<le> K + norm (X 0)" by simp with \<open>0 < K + norm (X 0)\<close> show ?Q by blast next assume ?Q then show ?P by (auto simp: Bseq_iff2) qed subsubsection \<open>Upper Bounds and Lubs of Bounded Sequences\<close> lemma Bseq_minus_iff: "Bseq (\<lambda>n. - (X n) :: 'a::real_normed_vector) \<longleftrightarrow> Bseq X" by (simp add: Bseq_def) lemma Bseq_add: fixes f :: "nat \<Rightarrow> 'a::real_normed_vector" assumes "Bseq f" shows "Bseq (\<lambda>x. f x + c)" proof - from assms obtain K where K: "\<And>x. norm (f x) \<le> K" unfolding Bseq_def by blast { fix x :: nat have "norm (f x + c) \<le> norm (f x) + norm c" by (rule norm_triangle_ineq) also have "norm (f x) \<le> K" by (rule K) finally have "norm (f x + c) \<le> K + norm c" by simp } then show ?thesis by (rule BseqI') qed lemma Bseq_add_iff: "Bseq (\<lambda>x. f x + c) \<longleftrightarrow> Bseq f" for f :: "nat \<Rightarrow> 'a::real_normed_vector" using Bseq_add[of f c] Bseq_add[of "\<lambda>x. f x + c" "-c"] by auto lemma Bseq_mult: fixes f g :: "nat \<Rightarrow> 'a::real_normed_field" assumes "Bseq f" and "Bseq g" shows "Bseq (\<lambda>x. f x * g x)" proof - from assms obtain K1 K2 where K: "norm (f x) \<le> K1" "K1 > 0" "norm (g x) \<le> K2" "K2 > 0" for x unfolding Bseq_def by blast then have "norm (f x * g x) \<le> K1 * K2" for x by (auto simp: norm_mult intro!: mult_mono) then show ?thesis by (rule BseqI') qed lemma Bfun_const [simp]: "Bfun (\<lambda>_. c) F" unfolding Bfun_metric_def by (auto intro!: exI[of _ c] exI[of _ "1::real"]) lemma Bseq_cmult_iff: fixes c :: "'a::real_normed_field" assumes "c \<noteq> 0" shows "Bseq (\<lambda>x. c * f x) \<longleftrightarrow> Bseq f" proof assume "Bseq (\<lambda>x. c * f x)" with Bfun_const have "Bseq (\<lambda>x. inverse c * (c * f x))" by (rule Bseq_mult) with \<open>c \<noteq> 0\<close> show "Bseq f" by (simp add: field_split_simps) qed (intro Bseq_mult Bfun_const) lemma Bseq_subseq: "Bseq f \<Longrightarrow> Bseq (\<lambda>x. f (g x))" for f :: "nat \<Rightarrow> 'a::real_normed_vector" unfolding Bseq_def by auto lemma Bseq_Suc_iff: "Bseq (\<lambda>n. f (Suc n)) \<longleftrightarrow> Bseq f" for f :: "nat \<Rightarrow> 'a::real_normed_vector" using Bseq_offset[of f 1] by (auto intro: Bseq_subseq) lemma increasing_Bseq_subseq_iff: assumes "\<And>x y. x \<le> y \<Longrightarrow> norm (f x :: 'a::real_normed_vector) \<le> norm (f y)" "strict_mono g" shows "Bseq (\<lambda>x. f (g x)) \<longleftrightarrow> Bseq f" proof assume "Bseq (\<lambda>x. f (g x))" then obtain K where K: "\<And>x. norm (f (g x)) \<le> K" unfolding Bseq_def by auto { fix x :: nat from filterlim_subseq[OF assms(2)] obtain y where "g y \<ge> x" by (auto simp: filterlim_at_top eventually_at_top_linorder) then have "norm (f x) \<le> norm (f (g y))" using assms(1) by blast also have "norm (f (g y)) \<le> K" by (rule K) finally have "norm (f x) \<le> K" . } then show "Bseq f" by (rule BseqI') qed (use Bseq_subseq[of f g] in simp_all) lemma nonneg_incseq_Bseq_subseq_iff: fixes f :: "nat \<Rightarrow> real" and g :: "nat \<Rightarrow> nat" assumes "\<And>x. f x \<ge> 0" "incseq f" "strict_mono g" shows "Bseq (\<lambda>x. f (g x)) \<longleftrightarrow> Bseq f" using assms by (intro increasing_Bseq_subseq_iff) (auto simp: incseq_def) lemma Bseq_eq_bounded: "range f \<subseteq> {a..b} \<Longrightarrow> Bseq f" for a b :: real proof (rule BseqI'[where K="max (norm a) (norm b)"]) fix n assume "range f \<subseteq> {a..b}" then have "f n \<in> {a..b}" by blast then show "norm (f n) \<le> max (norm a) (norm b)" by auto qed lemma incseq_bounded: "incseq X \<Longrightarrow> \<forall>i. X i \<le> B \<Longrightarrow> Bseq X" for B :: real by (intro Bseq_eq_bounded[of X "X 0" B]) (auto simp: incseq_def) lemma decseq_bounded: "decseq X \<Longrightarrow> \<forall>i. B \<le> X i \<Longrightarrow> Bseq X" for B :: real by (intro Bseq_eq_bounded[of X B "X 0"]) (auto simp: decseq_def) subsubsection\<^marker>\<open>tag unimportant\<close> \<open>Polynomal function extremal theorem, from HOL Light\<close> lemma polyfun_extremal_lemma: fixes c :: "nat \<Rightarrow> 'a::real_normed_div_algebra" assumes "0 < e" shows "\<exists>M. \<forall>z. M \<le> norm(z) \<longrightarrow> norm (\<Sum>i\<le>n. c(i) * z^i) \<le> e * norm(z) ^ (Suc n)" proof (induct n) case 0 with assms show ?case apply (rule_tac x="norm (c 0) / e" in exI) apply (auto simp: field_simps) done next case (Suc n) obtain M where M: "\<And>z. M \<le> norm z \<Longrightarrow> norm (\<Sum>i\<le>n. c i * z^i) \<le> e * norm z ^ Suc n" using Suc assms by blast show ?case proof (rule exI [where x= "max M (1 + norm(c(Suc n)) / e)"], clarsimp simp del: power_Suc) fix z::'a assume z1: "M \<le> norm z" and "1 + norm (c (Suc n)) / e \<le> norm z" then have z2: "e + norm (c (Suc n)) \<le> e * norm z" using assms by (simp add: field_simps) have "norm (\<Sum>i\<le>n. c i * z^i) \<le> e * norm z ^ Suc n" using M [OF z1] by simp then have "norm (\<Sum>i\<le>n. c i * z^i) + norm (c (Suc n) * z ^ Suc n) \<le> e * norm z ^ Suc n + norm (c (Suc n) * z ^ Suc n)" by simp then have "norm ((\<Sum>i\<le>n. c i * z^i) + c (Suc n) * z ^ Suc n) \<le> e * norm z ^ Suc n + norm (c (Suc n) * z ^ Suc n)" by (blast intro: norm_triangle_le elim: ) also have "... \<le> (e + norm (c (Suc n))) * norm z ^ Suc n" by (simp add: norm_power norm_mult algebra_simps) also have "... \<le> (e * norm z) * norm z ^ Suc n" by (metis z2 mult.commute mult_left_mono norm_ge_zero norm_power) finally show "norm ((\<Sum>i\<le>n. c i * z^i) + c (Suc n) * z ^ Suc n) \<le> e * norm z ^ Suc (Suc n)" by simp qed qed lemma polyfun_extremal: (*COMPLEX_POLYFUN_EXTREMAL in HOL Light*) fixes c :: "nat \<Rightarrow> 'a::real_normed_div_algebra" assumes k: "c k \<noteq> 0" "1\<le>k" and kn: "k\<le>n" shows "eventually (\<lambda>z. norm (\<Sum>i\<le>n. c(i) * z^i) \<ge> B) at_infinity" using kn proof (induction n) case 0 then show ?case using k by simp next case (Suc m) show ?case proof (cases "c (Suc m) = 0") case True then show ?thesis using Suc k by auto (metis antisym_conv less_eq_Suc_le not_le) next case False then obtain M where M: "\<And>z. M \<le> norm z \<Longrightarrow> norm (\<Sum>i\<le>m. c i * z^i) \<le> norm (c (Suc m)) / 2 * norm z ^ Suc m" using polyfun_extremal_lemma [of "norm(c (Suc m)) / 2" c m] Suc by auto have "\<exists>b. \<forall>z. b \<le> norm z \<longrightarrow> B \<le> norm (\<Sum>i\<le>Suc m. c i * z^i)" proof (rule exI [where x="max M (max 1 (\<bar>B\<bar> / (norm(c (Suc m)) / 2)))"], clarsimp simp del: power_Suc) fix z::'a assume z1: "M \<le> norm z" "1 \<le> norm z" and "\<bar>B\<bar> * 2 / norm (c (Suc m)) \<le> norm z" then have z2: "\<bar>B\<bar> \<le> norm (c (Suc m)) * norm z / 2" using False by (simp add: field_simps) have nz: "norm z \<le> norm z ^ Suc m" by (metis \<open>1 \<le> norm z\<close> One_nat_def less_eq_Suc_le power_increasing power_one_right zero_less_Suc) have *: "\<And>y x. norm (c (Suc m)) * norm z / 2 \<le> norm y - norm x \<Longrightarrow> B \<le> norm (x + y)" by (metis abs_le_iff add.commute norm_diff_ineq order_trans z2) have "norm z * norm (c (Suc m)) + 2 * norm (\<Sum>i\<le>m. c i * z^i) \<le> norm (c (Suc m)) * norm z + norm (c (Suc m)) * norm z ^ Suc m" using M [of z] Suc z1 by auto also have "... \<le> 2 * (norm (c (Suc m)) * norm z ^ Suc m)" using nz by (simp add: mult_mono del: power_Suc) finally show "B \<le> norm ((\<Sum>i\<le>m. c i * z^i) + c (Suc m) * z ^ Suc m)" using Suc.IH apply (auto simp: eventually_at_infinity) apply (rule *) apply (simp add: field_simps norm_mult norm_power) done qed then show ?thesis by (simp add: eventually_at_infinity) qed qed subsection \<open>Convergence to Zero\<close> definition Zfun :: "('a \<Rightarrow> 'b::real_normed_vector) \<Rightarrow> 'a filter \<Rightarrow> bool" where "Zfun f F = (\<forall>r>0. eventually (\<lambda>x. norm (f x) < r) F)" lemma ZfunI: "(\<And>r. 0 < r \<Longrightarrow> eventually (\<lambda>x. norm (f x) < r) F) \<Longrightarrow> Zfun f F" by (simp add: Zfun_def) lemma ZfunD: "Zfun f F \<Longrightarrow> 0 < r \<Longrightarrow> eventually (\<lambda>x. norm (f x) < r) F" by (simp add: Zfun_def) lemma Zfun_ssubst: "eventually (\<lambda>x. f x = g x) F \<Longrightarrow> Zfun g F \<Longrightarrow> Zfun f F" unfolding Zfun_def by (auto elim!: eventually_rev_mp) lemma Zfun_zero: "Zfun (\<lambda>x. 0) F" unfolding Zfun_def by simp lemma Zfun_norm_iff: "Zfun (\<lambda>x. norm (f x)) F = Zfun (\<lambda>x. f x) F" unfolding Zfun_def by simp lemma Zfun_imp_Zfun: assumes f: "Zfun f F" and g: "eventually (\<lambda>x. norm (g x) \<le> norm (f x) * K) F" shows "Zfun (\<lambda>x. g x) F" proof (cases "0 < K") case K: True show ?thesis proof (rule ZfunI) fix r :: real assume "0 < r" then have "0 < r / K" using K by simp then have "eventually (\<lambda>x. norm (f x) < r / K) F" using ZfunD [OF f] by blast with g show "eventually (\<lambda>x. norm (g x) < r) F" proof eventually_elim case (elim x) then have "norm (f x) * K < r" by (simp add: pos_less_divide_eq K) then show ?case by (simp add: order_le_less_trans [OF elim(1)]) qed qed next case False then have K: "K \<le> 0" by (simp only: not_less) show ?thesis proof (rule ZfunI) fix r :: real assume "0 < r" from g show "eventually (\<lambda>x. norm (g x) < r) F" proof eventually_elim case (elim x) also have "norm (f x) * K \<le> norm (f x) * 0" using K norm_ge_zero by (rule mult_left_mono) finally show ?case using \<open>0 < r\<close> by simp qed qed qed lemma Zfun_le: "Zfun g F \<Longrightarrow> \<forall>x. norm (f x) \<le> norm (g x) \<Longrightarrow> Zfun f F" by (erule Zfun_imp_Zfun [where K = 1]) simp lemma Zfun_add: assumes f: "Zfun f F" and g: "Zfun g F" shows "Zfun (\<lambda>x. f x + g x) F" proof (rule ZfunI) fix r :: real assume "0 < r" then have r: "0 < r / 2" by simp have "eventually (\<lambda>x. norm (f x) < r/2) F" using f r by (rule ZfunD) moreover have "eventually (\<lambda>x. norm (g x) < r/2) F" using g r by (rule ZfunD) ultimately show "eventually (\<lambda>x. norm (f x + g x) < r) F" proof eventually_elim case (elim x) have "norm (f x + g x) \<le> norm (f x) + norm (g x)" by (rule norm_triangle_ineq) also have "\<dots> < r/2 + r/2" using elim by (rule add_strict_mono) finally show ?case by simp qed qed lemma Zfun_minus: "Zfun f F \<Longrightarrow> Zfun (\<lambda>x. - f x) F" unfolding Zfun_def by simp lemma Zfun_diff: "Zfun f F \<Longrightarrow> Zfun g F \<Longrightarrow> Zfun (\<lambda>x. f x - g x) F" using Zfun_add [of f F "\<lambda>x. - g x"] by (simp add: Zfun_minus) lemma (in bounded_linear) Zfun: assumes g: "Zfun g F" shows "Zfun (\<lambda>x. f (g x)) F" proof - obtain K where "norm (f x) \<le> norm x * K" for x using bounded by blast then have "eventually (\<lambda>x. norm (f (g x)) \<le> norm (g x) * K) F" by simp with g show ?thesis by (rule Zfun_imp_Zfun) qed lemma (in bounded_bilinear) Zfun: assumes f: "Zfun f F" and g: "Zfun g F" shows "Zfun (\<lambda>x. f x ** g x) F" proof (rule ZfunI) fix r :: real assume r: "0 < r" obtain K where K: "0 < K" and norm_le: "norm (x ** y) \<le> norm x * norm y * K" for x y using pos_bounded by blast from K have K': "0 < inverse K" by (rule positive_imp_inverse_positive) have "eventually (\<lambda>x. norm (f x) < r) F" using f r by (rule ZfunD) moreover have "eventually (\<lambda>x. norm (g x) < inverse K) F" using g K' by (rule ZfunD) ultimately show "eventually (\<lambda>x. norm (f x ** g x) < r) F" proof eventually_elim case (elim x) have "norm (f x ** g x) \<le> norm (f x) * norm (g x) * K" by (rule norm_le) also have "norm (f x) * norm (g x) * K < r * inverse K * K" by (intro mult_strict_right_mono mult_strict_mono' norm_ge_zero elim K) also from K have "r * inverse K * K = r" by simp finally show ?case . qed qed lemma (in bounded_bilinear) Zfun_left: "Zfun f F \<Longrightarrow> Zfun (\<lambda>x. f x ** a) F" by (rule bounded_linear_left [THEN bounded_linear.Zfun]) lemma (in bounded_bilinear) Zfun_right: "Zfun f F \<Longrightarrow> Zfun (\<lambda>x. a ** f x) F" by (rule bounded_linear_right [THEN bounded_linear.Zfun]) lemmas Zfun_mult = bounded_bilinear.Zfun [OF bounded_bilinear_mult] lemmas Zfun_mult_right = bounded_bilinear.Zfun_right [OF bounded_bilinear_mult] lemmas Zfun_mult_left = bounded_bilinear.Zfun_left [OF bounded_bilinear_mult] lemma tendsto_Zfun_iff: "(f \<longlongrightarrow> a) F = Zfun (\<lambda>x. f x - a) F" by (simp only: tendsto_iff Zfun_def dist_norm) lemma tendsto_0_le: "(f \<longlongrightarrow> 0) F \<Longrightarrow> eventually (\<lambda>x. norm (g x) \<le> norm (f x) * K) F \<Longrightarrow> (g \<longlongrightarrow> 0) F" by (simp add: Zfun_imp_Zfun tendsto_Zfun_iff) subsubsection \<open>Distance and norms\<close> lemma tendsto_dist [tendsto_intros]: fixes l m :: "'a::metric_space" assumes f: "(f \<longlongrightarrow> l) F" and g: "(g \<longlongrightarrow> m) F" shows "((\<lambda>x. dist (f x) (g x)) \<longlongrightarrow> dist l m) F" proof (rule tendstoI) fix e :: real assume "0 < e" then have e2: "0 < e/2" by simp from tendstoD [OF f e2] tendstoD [OF g e2] show "eventually (\<lambda>x. dist (dist (f x) (g x)) (dist l m) < e) F" proof (eventually_elim) case (elim x) then show "dist (dist (f x) (g x)) (dist l m) < e" unfolding dist_real_def using dist_triangle2 [of "f x" "g x" "l"] and dist_triangle2 [of "g x" "l" "m"] and dist_triangle3 [of "l" "m" "f x"] and dist_triangle [of "f x" "m" "g x"] by arith qed qed lemma continuous_dist[continuous_intros]: fixes f g :: "_ \<Rightarrow> 'a :: metric_space" shows "continuous F f \<Longrightarrow> continuous F g \<Longrightarrow> continuous F (\<lambda>x. dist (f x) (g x))" unfolding continuous_def by (rule tendsto_dist) lemma continuous_on_dist[continuous_intros]: fixes f g :: "_ \<Rightarrow> 'a :: metric_space" shows "continuous_on s f \<Longrightarrow> continuous_on s g \<Longrightarrow> continuous_on s (\<lambda>x. dist (f x) (g x))" unfolding continuous_on_def by (auto intro: tendsto_dist) lemma continuous_at_dist: "isCont (dist a) b" using continuous_on_dist [OF continuous_on_const continuous_on_id] continuous_on_eq_continuous_within by blast lemma tendsto_norm [tendsto_intros]: "(f \<longlongrightarrow> a) F \<Longrightarrow> ((\<lambda>x. norm (f x)) \<longlongrightarrow> norm a) F" unfolding norm_conv_dist by (intro tendsto_intros) lemma continuous_norm [continuous_intros]: "continuous F f \<Longrightarrow> continuous F (\<lambda>x. norm (f x))" unfolding continuous_def by (rule tendsto_norm) lemma continuous_on_norm [continuous_intros]: "continuous_on s f \<Longrightarrow> continuous_on s (\<lambda>x. norm (f x))" unfolding continuous_on_def by (auto intro: tendsto_norm) lemma continuous_on_norm_id [continuous_intros]: "continuous_on S norm" by (intro continuous_on_id continuous_on_norm) lemma tendsto_norm_zero: "(f \<longlongrightarrow> 0) F \<Longrightarrow> ((\<lambda>x. norm (f x)) \<longlongrightarrow> 0) F" by (drule tendsto_norm) simp lemma tendsto_norm_zero_cancel: "((\<lambda>x. norm (f x)) \<longlongrightarrow> 0) F \<Longrightarrow> (f \<longlongrightarrow> 0) F" unfolding tendsto_iff dist_norm by simp lemma tendsto_norm_zero_iff: "((\<lambda>x. norm (f x)) \<longlongrightarrow> 0) F \<longleftrightarrow> (f \<longlongrightarrow> 0) F" unfolding tendsto_iff dist_norm by simp lemma tendsto_rabs [tendsto_intros]: "(f \<longlongrightarrow> l) F \<Longrightarrow> ((\<lambda>x. \<bar>f x\<bar>) \<longlongrightarrow> \<bar>l\<bar>) F" for l :: real by (fold real_norm_def) (rule tendsto_norm) lemma continuous_rabs [continuous_intros]: "continuous F f \<Longrightarrow> continuous F (\<lambda>x. \<bar>f x :: real\<bar>)" unfolding real_norm_def[symmetric] by (rule continuous_norm) lemma continuous_on_rabs [continuous_intros]: "continuous_on s f \<Longrightarrow> continuous_on s (\<lambda>x. \<bar>f x :: real\<bar>)" unfolding real_norm_def[symmetric] by (rule continuous_on_norm) lemma tendsto_rabs_zero: "(f \<longlongrightarrow> (0::real)) F \<Longrightarrow> ((\<lambda>x. \<bar>f x\<bar>) \<longlongrightarrow> 0) F" by (fold real_norm_def) (rule tendsto_norm_zero) lemma tendsto_rabs_zero_cancel: "((\<lambda>x. \<bar>f x\<bar>) \<longlongrightarrow> (0::real)) F \<Longrightarrow> (f \<longlongrightarrow> 0) F" by (fold real_norm_def) (rule tendsto_norm_zero_cancel) lemma tendsto_rabs_zero_iff: "((\<lambda>x. \<bar>f x\<bar>) \<longlongrightarrow> (0::real)) F \<longleftrightarrow> (f \<longlongrightarrow> 0) F" by (fold real_norm_def) (rule tendsto_norm_zero_iff) subsection \<open>Topological Monoid\<close> class topological_monoid_add = topological_space + monoid_add + assumes tendsto_add_Pair: "LIM x (nhds a \<times>\<^sub>F nhds b). fst x + snd x :> nhds (a + b)" class topological_comm_monoid_add = topological_monoid_add + comm_monoid_add lemma tendsto_add [tendsto_intros]: fixes a b :: "'a::topological_monoid_add" shows "(f \<longlongrightarrow> a) F \<Longrightarrow> (g \<longlongrightarrow> b) F \<Longrightarrow> ((\<lambda>x. f x + g x) \<longlongrightarrow> a + b) F" using filterlim_compose[OF tendsto_add_Pair, of "\<lambda>x. (f x, g x)" a b F] by (simp add: nhds_prod[symmetric] tendsto_Pair) lemma continuous_add [continuous_intros]: fixes f g :: "_ \<Rightarrow> 'b::topological_monoid_add" shows "continuous F f \<Longrightarrow> continuous F g \<Longrightarrow> continuous F (\<lambda>x. f x + g x)" unfolding continuous_def by (rule tendsto_add) lemma continuous_on_add [continuous_intros]: fixes f g :: "_ \<Rightarrow> 'b::topological_monoid_add" shows "continuous_on s f \<Longrightarrow> continuous_on s g \<Longrightarrow> continuous_on s (\<lambda>x. f x + g x)" unfolding continuous_on_def by (auto intro: tendsto_add) lemma tendsto_add_zero: fixes f g :: "_ \<Rightarrow> 'b::topological_monoid_add" shows "(f \<longlongrightarrow> 0) F \<Longrightarrow> (g \<longlongrightarrow> 0) F \<Longrightarrow> ((\<lambda>x. f x + g x) \<longlongrightarrow> 0) F" by (drule (1) tendsto_add) simp lemma tendsto_sum [tendsto_intros]: fixes f :: "'a \<Rightarrow> 'b \<Rightarrow> 'c::topological_comm_monoid_add" shows "(\<And>i. i \<in> I \<Longrightarrow> (f i \<longlongrightarrow> a i) F) \<Longrightarrow> ((\<lambda>x. \<Sum>i\<in>I. f i x) \<longlongrightarrow> (\<Sum>i\<in>I. a i)) F" by (induct I rule: infinite_finite_induct) (simp_all add: tendsto_add) lemma tendsto_null_sum: fixes f :: "'a \<Rightarrow> 'b \<Rightarrow> 'c::topological_comm_monoid_add" assumes "\<And>i. i \<in> I \<Longrightarrow> ((\<lambda>x. f x i) \<longlongrightarrow> 0) F" shows "((\<lambda>i. sum (f i) I) \<longlongrightarrow> 0) F" using tendsto_sum [of I "\<lambda>x y. f y x" "\<lambda>x. 0"] assms by simp lemma continuous_sum [continuous_intros]: fixes f :: "'a \<Rightarrow> 'b::t2_space \<Rightarrow> 'c::topological_comm_monoid_add" shows "(\<And>i. i \<in> I \<Longrightarrow> continuous F (f i)) \<Longrightarrow> continuous F (\<lambda>x. \<Sum>i\<in>I. f i x)" unfolding continuous_def by (rule tendsto_sum) lemma continuous_on_sum [continuous_intros]: fixes f :: "'a \<Rightarrow> 'b::topological_space \<Rightarrow> 'c::topological_comm_monoid_add" shows "(\<And>i. i \<in> I \<Longrightarrow> continuous_on S (f i)) \<Longrightarrow> continuous_on S (\<lambda>x. \<Sum>i\<in>I. f i x)" unfolding continuous_on_def by (auto intro: tendsto_sum) instance nat :: topological_comm_monoid_add by standard (simp add: nhds_discrete principal_prod_principal filterlim_principal eventually_principal) instance int :: topological_comm_monoid_add by standard (simp add: nhds_discrete principal_prod_principal filterlim_principal eventually_principal) subsubsection \<open>Topological group\<close> class topological_group_add = topological_monoid_add + group_add + assumes tendsto_uminus_nhds: "(uminus \<longlongrightarrow> - a) (nhds a)" begin lemma tendsto_minus [tendsto_intros]: "(f \<longlongrightarrow> a) F \<Longrightarrow> ((\<lambda>x. - f x) \<longlongrightarrow> - a) F" by (rule filterlim_compose[OF tendsto_uminus_nhds]) end class topological_ab_group_add = topological_group_add + ab_group_add instance topological_ab_group_add < topological_comm_monoid_add .. lemma continuous_minus [continuous_intros]: "continuous F f \<Longrightarrow> continuous F (\<lambda>x. - f x)" for f :: "'a::t2_space \<Rightarrow> 'b::topological_group_add" unfolding continuous_def by (rule tendsto_minus) lemma continuous_on_minus [continuous_intros]: "continuous_on s f \<Longrightarrow> continuous_on s (\<lambda>x. - f x)" for f :: "_ \<Rightarrow> 'b::topological_group_add" unfolding continuous_on_def by (auto intro: tendsto_minus) lemma tendsto_minus_cancel: "((\<lambda>x. - f x) \<longlongrightarrow> - a) F \<Longrightarrow> (f \<longlongrightarrow> a) F" for a :: "'a::topological_group_add" by (drule tendsto_minus) simp lemma tendsto_minus_cancel_left: "(f \<longlongrightarrow> - (y::_::topological_group_add)) F \<longleftrightarrow> ((\<lambda>x. - f x) \<longlongrightarrow> y) F" using tendsto_minus_cancel[of f "- y" F] tendsto_minus[of f "- y" F] by auto lemma tendsto_diff [tendsto_intros]: fixes a b :: "'a::topological_group_add" shows "(f \<longlongrightarrow> a) F \<Longrightarrow> (g \<longlongrightarrow> b) F \<Longrightarrow> ((\<lambda>x. f x - g x) \<longlongrightarrow> a - b) F" using tendsto_add [of f a F "\<lambda>x. - g x" "- b"] by (simp add: tendsto_minus) lemma continuous_diff [continuous_intros]: fixes f g :: "'a::t2_space \<Rightarrow> 'b::topological_group_add" shows "continuous F f \<Longrightarrow> continuous F g \<Longrightarrow> continuous F (\<lambda>x. f x - g x)" unfolding continuous_def by (rule tendsto_diff) lemma continuous_on_diff [continuous_intros]: fixes f g :: "_ \<Rightarrow> 'b::topological_group_add" shows "continuous_on s f \<Longrightarrow> continuous_on s g \<Longrightarrow> continuous_on s (\<lambda>x. f x - g x)" unfolding continuous_on_def by (auto intro: tendsto_diff) lemma continuous_on_op_minus: "continuous_on (s::'a::topological_group_add set) ((-) x)" by (rule continuous_intros | simp)+ instance real_normed_vector < topological_ab_group_add proof fix a b :: 'a show "((\<lambda>x. fst x + snd x) \<longlongrightarrow> a + b) (nhds a \<times>\<^sub>F nhds b)" unfolding tendsto_Zfun_iff add_diff_add using tendsto_fst[OF filterlim_ident, of "(a,b)"] tendsto_snd[OF filterlim_ident, of "(a,b)"] by (intro Zfun_add) (auto simp: tendsto_Zfun_iff[symmetric] nhds_prod[symmetric] intro!: tendsto_fst) show "(uminus \<longlongrightarrow> - a) (nhds a)" unfolding tendsto_Zfun_iff minus_diff_minus using filterlim_ident[of "nhds a"] by (intro Zfun_minus) (simp add: tendsto_Zfun_iff) qed lemmas real_tendsto_sandwich = tendsto_sandwich[where 'a=real] subsubsection \<open>Linear operators and multiplication\<close> lemma linear_times [simp]: "linear (\<lambda>x. c * x)" for c :: "'a::real_algebra" by (auto simp: linearI distrib_left) lemma (in bounded_linear) tendsto: "(g \<longlongrightarrow> a) F \<Longrightarrow> ((\<lambda>x. f (g x)) \<longlongrightarrow> f a) F" by (simp only: tendsto_Zfun_iff diff [symmetric] Zfun) lemma (in bounded_linear) continuous: "continuous F g \<Longrightarrow> continuous F (\<lambda>x. f (g x))" using tendsto[of g _ F] by (auto simp: continuous_def) lemma (in bounded_linear) continuous_on: "continuous_on s g \<Longrightarrow> continuous_on s (\<lambda>x. f (g x))" using tendsto[of g] by (auto simp: continuous_on_def) lemma (in bounded_linear) tendsto_zero: "(g \<longlongrightarrow> 0) F \<Longrightarrow> ((\<lambda>x. f (g x)) \<longlongrightarrow> 0) F" by (drule tendsto) (simp only: zero) lemma (in bounded_bilinear) tendsto: "(f \<longlongrightarrow> a) F \<Longrightarrow> (g \<longlongrightarrow> b) F \<Longrightarrow> ((\<lambda>x. f x ** g x) \<longlongrightarrow> a ** b) F" by (simp only: tendsto_Zfun_iff prod_diff_prod Zfun_add Zfun Zfun_left Zfun_right) lemma (in bounded_bilinear) continuous: "continuous F f \<Longrightarrow> continuous F g \<Longrightarrow> continuous F (\<lambda>x. f x ** g x)" using tendsto[of f _ F g] by (auto simp: continuous_def) lemma (in bounded_bilinear) continuous_on: "continuous_on s f \<Longrightarrow> continuous_on s g \<Longrightarrow> continuous_on s (\<lambda>x. f x ** g x)" using tendsto[of f _ _ g] by (auto simp: continuous_on_def) lemma (in bounded_bilinear) tendsto_zero: assumes f: "(f \<longlongrightarrow> 0) F" and g: "(g \<longlongrightarrow> 0) F" shows "((\<lambda>x. f x ** g x) \<longlongrightarrow> 0) F" using tendsto [OF f g] by (simp add: zero_left) lemma (in bounded_bilinear) tendsto_left_zero: "(f \<longlongrightarrow> 0) F \<Longrightarrow> ((\<lambda>x. f x ** c) \<longlongrightarrow> 0) F" by (rule bounded_linear.tendsto_zero [OF bounded_linear_left]) lemma (in bounded_bilinear) tendsto_right_zero: "(f \<longlongrightarrow> 0) F \<Longrightarrow> ((\<lambda>x. c ** f x) \<longlongrightarrow> 0) F" by (rule bounded_linear.tendsto_zero [OF bounded_linear_right]) lemmas tendsto_of_real [tendsto_intros] = bounded_linear.tendsto [OF bounded_linear_of_real] lemmas tendsto_scaleR [tendsto_intros] = bounded_bilinear.tendsto [OF bounded_bilinear_scaleR] text\<open>Analogous type class for multiplication\<close> class topological_semigroup_mult = topological_space + semigroup_mult + assumes tendsto_mult_Pair: "LIM x (nhds a \<times>\<^sub>F nhds b). fst x * snd x :> nhds (a * b)" instance real_normed_algebra < topological_semigroup_mult proof fix a b :: 'a show "((\<lambda>x. fst x * snd x) \<longlongrightarrow> a * b) (nhds a \<times>\<^sub>F nhds b)" unfolding nhds_prod[symmetric] using tendsto_fst[OF filterlim_ident, of "(a,b)"] tendsto_snd[OF filterlim_ident, of "(a,b)"] by (simp add: bounded_bilinear.tendsto [OF bounded_bilinear_mult]) qed lemma tendsto_mult [tendsto_intros]: fixes a b :: "'a::topological_semigroup_mult" shows "(f \<longlongrightarrow> a) F \<Longrightarrow> (g \<longlongrightarrow> b) F \<Longrightarrow> ((\<lambda>x. f x * g x) \<longlongrightarrow> a * b) F" using filterlim_compose[OF tendsto_mult_Pair, of "\<lambda>x. (f x, g x)" a b F] by (simp add: nhds_prod[symmetric] tendsto_Pair) lemma tendsto_mult_left: "(f \<longlongrightarrow> l) F \<Longrightarrow> ((\<lambda>x. c * (f x)) \<longlongrightarrow> c * l) F" for c :: "'a::topological_semigroup_mult" by (rule tendsto_mult [OF tendsto_const]) lemma tendsto_mult_right: "(f \<longlongrightarrow> l) F \<Longrightarrow> ((\<lambda>x. (f x) * c) \<longlongrightarrow> l * c) F" for c :: "'a::topological_semigroup_mult" by (rule tendsto_mult [OF _ tendsto_const]) lemma tendsto_mult_left_iff [simp]: "c \<noteq> 0 \<Longrightarrow> tendsto(\<lambda>x. c * f x) (c * l) F \<longleftrightarrow> tendsto f l F" for c :: "'a::{topological_semigroup_mult,field}" by (auto simp: tendsto_mult_left dest: tendsto_mult_left [where c = "1/c"]) lemma tendsto_mult_right_iff [simp]: "c \<noteq> 0 \<Longrightarrow> tendsto(\<lambda>x. f x * c) (l * c) F \<longleftrightarrow> tendsto f l F" for c :: "'a::{topological_semigroup_mult,field}" by (auto simp: tendsto_mult_right dest: tendsto_mult_left [where c = "1/c"]) lemma tendsto_zero_mult_left_iff [simp]: fixes c::"'a::{topological_semigroup_mult,field}" assumes "c \<noteq> 0" shows "(\<lambda>n. c * a n)\<longlonglongrightarrow> 0 \<longleftrightarrow> a \<longlonglongrightarrow> 0" using assms tendsto_mult_left tendsto_mult_left_iff by fastforce lemma tendsto_zero_mult_right_iff [simp]: fixes c::"'a::{topological_semigroup_mult,field}" assumes "c \<noteq> 0" shows "(\<lambda>n. a n * c)\<longlonglongrightarrow> 0 \<longleftrightarrow> a \<longlonglongrightarrow> 0" using assms tendsto_mult_right tendsto_mult_right_iff by fastforce lemma tendsto_zero_divide_iff [simp]: fixes c::"'a::{topological_semigroup_mult,field}" assumes "c \<noteq> 0" shows "(\<lambda>n. a n / c)\<longlonglongrightarrow> 0 \<longleftrightarrow> a \<longlonglongrightarrow> 0" using tendsto_zero_mult_right_iff [of "1/c" a] assms by (simp add: field_simps) lemma lim_const_over_n [tendsto_intros]: fixes a :: "'a::real_normed_field" shows "(\<lambda>n. a / of_nat n) \<longlonglongrightarrow> 0" using tendsto_mult [OF tendsto_const [of a] lim_1_over_n] by simp lemmas continuous_of_real [continuous_intros] = bounded_linear.continuous [OF bounded_linear_of_real] lemmas continuous_scaleR [continuous_intros] = bounded_bilinear.continuous [OF bounded_bilinear_scaleR] lemmas continuous_mult [continuous_intros] = bounded_bilinear.continuous [OF bounded_bilinear_mult] lemmas continuous_on_of_real [continuous_intros] = bounded_linear.continuous_on [OF bounded_linear_of_real] lemmas continuous_on_scaleR [continuous_intros] = bounded_bilinear.continuous_on [OF bounded_bilinear_scaleR] lemmas continuous_on_mult [continuous_intros] = bounded_bilinear.continuous_on [OF bounded_bilinear_mult] lemmas tendsto_mult_zero = bounded_bilinear.tendsto_zero [OF bounded_bilinear_mult] lemmas tendsto_mult_left_zero = bounded_bilinear.tendsto_left_zero [OF bounded_bilinear_mult] lemmas tendsto_mult_right_zero = bounded_bilinear.tendsto_right_zero [OF bounded_bilinear_mult] lemma continuous_mult_left: fixes c::"'a::real_normed_algebra" shows "continuous F f \<Longrightarrow> continuous F (\<lambda>x. c * f x)" by (rule continuous_mult [OF continuous_const]) lemma continuous_mult_right: fixes c::"'a::real_normed_algebra" shows "continuous F f \<Longrightarrow> continuous F (\<lambda>x. f x * c)" by (rule continuous_mult [OF _ continuous_const]) lemma continuous_on_mult_left: fixes c::"'a::real_normed_algebra" shows "continuous_on s f \<Longrightarrow> continuous_on s (\<lambda>x. c * f x)" by (rule continuous_on_mult [OF continuous_on_const]) lemma continuous_on_mult_right: fixes c::"'a::real_normed_algebra" shows "continuous_on s f \<Longrightarrow> continuous_on s (\<lambda>x. f x * c)" by (rule continuous_on_mult [OF _ continuous_on_const]) lemma continuous_on_mult_const [simp]: fixes c::"'a::real_normed_algebra" shows "continuous_on s ((*) c)" by (intro continuous_on_mult_left continuous_on_id) lemma tendsto_divide_zero: fixes c :: "'a::real_normed_field" shows "(f \<longlongrightarrow> 0) F \<Longrightarrow> ((\<lambda>x. f x / c) \<longlongrightarrow> 0) F" by (cases "c=0") (simp_all add: divide_inverse tendsto_mult_left_zero) lemma tendsto_power [tendsto_intros]: "(f \<longlongrightarrow> a) F \<Longrightarrow> ((\<lambda>x. f x ^ n) \<longlongrightarrow> a ^ n) F" for f :: "'a \<Rightarrow> 'b::{power,real_normed_algebra}" by (induct n) (simp_all add: tendsto_mult) lemma tendsto_null_power: "\<lbrakk>(f \<longlongrightarrow> 0) F; 0 < n\<rbrakk> \<Longrightarrow> ((\<lambda>x. f x ^ n) \<longlongrightarrow> 0) F" for f :: "'a \<Rightarrow> 'b::{power,real_normed_algebra_1}" using tendsto_power [of f 0 F n] by (simp add: power_0_left) lemma continuous_power [continuous_intros]: "continuous F f \<Longrightarrow> continuous F (\<lambda>x. (f x)^n)" for f :: "'a::t2_space \<Rightarrow> 'b::{power,real_normed_algebra}" unfolding continuous_def by (rule tendsto_power) lemma continuous_on_power [continuous_intros]: fixes f :: "_ \<Rightarrow> 'b::{power,real_normed_algebra}" shows "continuous_on s f \<Longrightarrow> continuous_on s (\<lambda>x. (f x)^n)" unfolding continuous_on_def by (auto intro: tendsto_power) lemma tendsto_prod [tendsto_intros]: fixes f :: "'a \<Rightarrow> 'b \<Rightarrow> 'c::{real_normed_algebra,comm_ring_1}" shows "(\<And>i. i \<in> S \<Longrightarrow> (f i \<longlongrightarrow> L i) F) \<Longrightarrow> ((\<lambda>x. \<Prod>i\<in>S. f i x) \<longlongrightarrow> (\<Prod>i\<in>S. L i)) F" by (induct S rule: infinite_finite_induct) (simp_all add: tendsto_mult) lemma continuous_prod [continuous_intros]: fixes f :: "'a \<Rightarrow> 'b::t2_space \<Rightarrow> 'c::{real_normed_algebra,comm_ring_1}" shows "(\<And>i. i \<in> S \<Longrightarrow> continuous F (f i)) \<Longrightarrow> continuous F (\<lambda>x. \<Prod>i\<in>S. f i x)" unfolding continuous_def by (rule tendsto_prod) lemma continuous_on_prod [continuous_intros]: fixes f :: "'a \<Rightarrow> _ \<Rightarrow> 'c::{real_normed_algebra,comm_ring_1}" shows "(\<And>i. i \<in> S \<Longrightarrow> continuous_on s (f i)) \<Longrightarrow> continuous_on s (\<lambda>x. \<Prod>i\<in>S. f i x)" unfolding continuous_on_def by (auto intro: tendsto_prod) lemma tendsto_of_real_iff: "((\<lambda>x. of_real (f x) :: 'a::real_normed_div_algebra) \<longlongrightarrow> of_real c) F \<longleftrightarrow> (f \<longlongrightarrow> c) F" unfolding tendsto_iff by simp lemma tendsto_add_const_iff: "((\<lambda>x. c + f x :: 'a::topological_group_add) \<longlongrightarrow> c + d) F \<longleftrightarrow> (f \<longlongrightarrow> d) F" using tendsto_add[OF tendsto_const[of c], of f d] and tendsto_add[OF tendsto_const[of "-c"], of "\<lambda>x. c + f x" "c + d"] by auto class topological_monoid_mult = topological_semigroup_mult + monoid_mult class topological_comm_monoid_mult = topological_monoid_mult + comm_monoid_mult lemma tendsto_power_strong [tendsto_intros]: fixes f :: "_ \<Rightarrow> 'b :: topological_monoid_mult" assumes "(f \<longlongrightarrow> a) F" "(g \<longlongrightarrow> b) F" shows "((\<lambda>x. f x ^ g x) \<longlongrightarrow> a ^ b) F" proof - have "((\<lambda>x. f x ^ b) \<longlongrightarrow> a ^ b) F" by (induction b) (auto intro: tendsto_intros assms) also from assms(2) have "eventually (\<lambda>x. g x = b) F" by (simp add: nhds_discrete filterlim_principal) hence "eventually (\<lambda>x. f x ^ b = f x ^ g x) F" by eventually_elim simp hence "((\<lambda>x. f x ^ b) \<longlongrightarrow> a ^ b) F \<longleftrightarrow> ((\<lambda>x. f x ^ g x) \<longlongrightarrow> a ^ b) F" by (intro filterlim_cong refl) finally show ?thesis . qed lemma continuous_mult' [continuous_intros]: fixes f g :: "_ \<Rightarrow> 'b::topological_semigroup_mult" shows "continuous F f \<Longrightarrow> continuous F g \<Longrightarrow> continuous F (\<lambda>x. f x * g x)" unfolding continuous_def by (rule tendsto_mult) lemma continuous_power' [continuous_intros]: fixes f :: "_ \<Rightarrow> 'b::topological_monoid_mult" shows "continuous F f \<Longrightarrow> continuous F g \<Longrightarrow> continuous F (\<lambda>x. f x ^ g x)" unfolding continuous_def by (rule tendsto_power_strong) auto lemma continuous_on_mult' [continuous_intros]: fixes f g :: "_ \<Rightarrow> 'b::topological_semigroup_mult" shows "continuous_on A f \<Longrightarrow> continuous_on A g \<Longrightarrow> continuous_on A (\<lambda>x. f x * g x)" unfolding continuous_on_def by (auto intro: tendsto_mult) lemma continuous_on_power' [continuous_intros]: fixes f :: "_ \<Rightarrow> 'b::topological_monoid_mult" shows "continuous_on A f \<Longrightarrow> continuous_on A g \<Longrightarrow> continuous_on A (\<lambda>x. f x ^ g x)" unfolding continuous_on_def by (auto intro: tendsto_power_strong) lemma tendsto_mult_one: fixes f g :: "_ \<Rightarrow> 'b::topological_monoid_mult" shows "(f \<longlongrightarrow> 1) F \<Longrightarrow> (g \<longlongrightarrow> 1) F \<Longrightarrow> ((\<lambda>x. f x * g x) \<longlongrightarrow> 1) F" by (drule (1) tendsto_mult) simp lemma tendsto_prod' [tendsto_intros]: fixes f :: "'a \<Rightarrow> 'b \<Rightarrow> 'c::topological_comm_monoid_mult" shows "(\<And>i. i \<in> I \<Longrightarrow> (f i \<longlongrightarrow> a i) F) \<Longrightarrow> ((\<lambda>x. \<Prod>i\<in>I. f i x) \<longlongrightarrow> (\<Prod>i\<in>I. a i)) F" by (induct I rule: infinite_finite_induct) (simp_all add: tendsto_mult) lemma tendsto_one_prod': fixes f :: "'a \<Rightarrow> 'b \<Rightarrow> 'c::topological_comm_monoid_mult" assumes "\<And>i. i \<in> I \<Longrightarrow> ((\<lambda>x. f x i) \<longlongrightarrow> 1) F" shows "((\<lambda>i. prod (f i) I) \<longlongrightarrow> 1) F" using tendsto_prod' [of I "\<lambda>x y. f y x" "\<lambda>x. 1"] assms by simp lemma LIMSEQ_prod_0: fixes f :: "nat \<Rightarrow> 'a::{semidom,topological_space}" assumes "f i = 0" shows "(\<lambda>n. prod f {..n}) \<longlonglongrightarrow> 0" proof (subst tendsto_cong) show "\<forall>\<^sub>F n in sequentially. prod f {..n} = 0" using assms eventually_at_top_linorder by auto qed auto lemma LIMSEQ_prod_nonneg: fixes f :: "nat \<Rightarrow> 'a::{linordered_semidom,linorder_topology}" assumes 0: "\<And>n. 0 \<le> f n" and a: "(\<lambda>n. prod f {..n}) \<longlonglongrightarrow> a" shows "a \<ge> 0" by (simp add: "0" prod_nonneg LIMSEQ_le_const [OF a]) lemma continuous_prod' [continuous_intros]: fixes f :: "'a \<Rightarrow> 'b::t2_space \<Rightarrow> 'c::topological_comm_monoid_mult" shows "(\<And>i. i \<in> I \<Longrightarrow> continuous F (f i)) \<Longrightarrow> continuous F (\<lambda>x. \<Prod>i\<in>I. f i x)" unfolding continuous_def by (rule tendsto_prod') lemma continuous_on_prod' [continuous_intros]: fixes f :: "'a \<Rightarrow> 'b::topological_space \<Rightarrow> 'c::topological_comm_monoid_mult" shows "(\<And>i. i \<in> I \<Longrightarrow> continuous_on S (f i)) \<Longrightarrow> continuous_on S (\<lambda>x. \<Prod>i\<in>I. f i x)" unfolding continuous_on_def by (auto intro: tendsto_prod') instance nat :: topological_comm_monoid_mult by standard (simp add: nhds_discrete principal_prod_principal filterlim_principal eventually_principal) instance int :: topological_comm_monoid_mult by standard (simp add: nhds_discrete principal_prod_principal filterlim_principal eventually_principal) class comm_real_normed_algebra_1 = real_normed_algebra_1 + comm_monoid_mult context real_normed_field begin subclass comm_real_normed_algebra_1 proof from norm_mult[of "1 :: 'a" 1] show "norm 1 = 1" by simp qed (simp_all add: norm_mult) end subsubsection \<open>Inverse and division\<close> lemma (in bounded_bilinear) Zfun_prod_Bfun: assumes f: "Zfun f F" and g: "Bfun g F" shows "Zfun (\<lambda>x. f x ** g x) F" proof - obtain K where K: "0 \<le> K" and norm_le: "\<And>x y. norm (x ** y) \<le> norm x * norm y * K" using nonneg_bounded by blast obtain B where B: "0 < B" and norm_g: "eventually (\<lambda>x. norm (g x) \<le> B) F" using g by (rule BfunE) have "eventually (\<lambda>x. norm (f x ** g x) \<le> norm (f x) * (B * K)) F" using norm_g proof eventually_elim case (elim x) have "norm (f x ** g x) \<le> norm (f x) * norm (g x) * K" by (rule norm_le) also have "\<dots> \<le> norm (f x) * B * K" by (intro mult_mono' order_refl norm_g norm_ge_zero mult_nonneg_nonneg K elim) also have "\<dots> = norm (f x) * (B * K)" by (rule mult.assoc) finally show "norm (f x ** g x) \<le> norm (f x) * (B * K)" . qed with f show ?thesis by (rule Zfun_imp_Zfun) qed lemma (in bounded_bilinear) Bfun_prod_Zfun: assumes f: "Bfun f F" and g: "Zfun g F" shows "Zfun (\<lambda>x. f x ** g x) F" using flip g f by (rule bounded_bilinear.Zfun_prod_Bfun) lemma Bfun_inverse: fixes a :: "'a::real_normed_div_algebra" assumes f: "(f \<longlongrightarrow> a) F" assumes a: "a \<noteq> 0" shows "Bfun (\<lambda>x. inverse (f x)) F" proof - from a have "0 < norm a" by simp then have "\<exists>r>0. r < norm a" by (rule dense) then obtain r where r1: "0 < r" and r2: "r < norm a" by blast have "eventually (\<lambda>x. dist (f x) a < r) F" using tendstoD [OF f r1] by blast then have "eventually (\<lambda>x. norm (inverse (f x)) \<le> inverse (norm a - r)) F" proof eventually_elim case (elim x) then have 1: "norm (f x - a) < r" by (simp add: dist_norm) then have 2: "f x \<noteq> 0" using r2 by auto then have "norm (inverse (f x)) = inverse (norm (f x))" by (rule nonzero_norm_inverse) also have "\<dots> \<le> inverse (norm a - r)" proof (rule le_imp_inverse_le) show "0 < norm a - r" using r2 by simp have "norm a - norm (f x) \<le> norm (a - f x)" by (rule norm_triangle_ineq2) also have "\<dots> = norm (f x - a)" by (rule norm_minus_commute) also have "\<dots> < r" using 1 . finally show "norm a - r \<le> norm (f x)" by simp qed finally show "norm (inverse (f x)) \<le> inverse (norm a - r)" . qed then show ?thesis by (rule BfunI) qed lemma tendsto_inverse [tendsto_intros]: fixes a :: "'a::real_normed_div_algebra" assumes f: "(f \<longlongrightarrow> a) F" and a: "a \<noteq> 0" shows "((\<lambda>x. inverse (f x)) \<longlongrightarrow> inverse a) F" proof - from a have "0 < norm a" by simp with f have "eventually (\<lambda>x. dist (f x) a < norm a) F" by (rule tendstoD) then have "eventually (\<lambda>x. f x \<noteq> 0) F" unfolding dist_norm by (auto elim!: eventually_mono) with a have "eventually (\<lambda>x. inverse (f x) - inverse a = - (inverse (f x) * (f x - a) * inverse a)) F" by (auto elim!: eventually_mono simp: inverse_diff_inverse) moreover have "Zfun (\<lambda>x. - (inverse (f x) * (f x - a) * inverse a)) F" by (intro Zfun_minus Zfun_mult_left bounded_bilinear.Bfun_prod_Zfun [OF bounded_bilinear_mult] Bfun_inverse [OF f a] f [unfolded tendsto_Zfun_iff]) ultimately show ?thesis unfolding tendsto_Zfun_iff by (rule Zfun_ssubst) qed lemma continuous_inverse: fixes f :: "'a::t2_space \<Rightarrow> 'b::real_normed_div_algebra" assumes "continuous F f" and "f (Lim F (\<lambda>x. x)) \<noteq> 0" shows "continuous F (\<lambda>x. inverse (f x))" using assms unfolding continuous_def by (rule tendsto_inverse) lemma continuous_at_within_inverse[continuous_intros]: fixes f :: "'a::t2_space \<Rightarrow> 'b::real_normed_div_algebra" assumes "continuous (at a within s) f" and "f a \<noteq> 0" shows "continuous (at a within s) (\<lambda>x. inverse (f x))" using assms unfolding continuous_within by (rule tendsto_inverse) lemma continuous_on_inverse[continuous_intros]: fixes f :: "'a::topological_space \<Rightarrow> 'b::real_normed_div_algebra" assumes "continuous_on s f" and "\<forall>x\<in>s. f x \<noteq> 0" shows "continuous_on s (\<lambda>x. inverse (f x))" using assms unfolding continuous_on_def by (blast intro: tendsto_inverse) lemma tendsto_divide [tendsto_intros]: fixes a b :: "'a::real_normed_field" shows "(f \<longlongrightarrow> a) F \<Longrightarrow> (g \<longlongrightarrow> b) F \<Longrightarrow> b \<noteq> 0 \<Longrightarrow> ((\<lambda>x. f x / g x) \<longlongrightarrow> a / b) F" by (simp add: tendsto_mult tendsto_inverse divide_inverse) lemma continuous_divide: fixes f g :: "'a::t2_space \<Rightarrow> 'b::real_normed_field" assumes "continuous F f" and "continuous F g" and "g (Lim F (\<lambda>x. x)) \<noteq> 0" shows "continuous F (\<lambda>x. (f x) / (g x))" using assms unfolding continuous_def by (rule tendsto_divide) lemma continuous_at_within_divide[continuous_intros]: fixes f g :: "'a::t2_space \<Rightarrow> 'b::real_normed_field" assumes "continuous (at a within s) f" "continuous (at a within s) g" and "g a \<noteq> 0" shows "continuous (at a within s) (\<lambda>x. (f x) / (g x))" using assms unfolding continuous_within by (rule tendsto_divide) lemma isCont_divide[continuous_intros, simp]: fixes f g :: "'a::t2_space \<Rightarrow> 'b::real_normed_field" assumes "isCont f a" "isCont g a" "g a \<noteq> 0" shows "isCont (\<lambda>x. (f x) / g x) a" using assms unfolding continuous_at by (rule tendsto_divide) lemma continuous_on_divide[continuous_intros]: fixes f :: "'a::topological_space \<Rightarrow> 'b::real_normed_field" assumes "continuous_on s f" "continuous_on s g" and "\<forall>x\<in>s. g x \<noteq> 0" shows "continuous_on s (\<lambda>x. (f x) / (g x))" using assms unfolding continuous_on_def by (blast intro: tendsto_divide) lemma tendsto_power_int [tendsto_intros]: fixes a :: "'a::real_normed_div_algebra" assumes f: "(f \<longlongrightarrow> a) F" and a: "a \<noteq> 0" shows "((\<lambda>x. power_int (f x) n) \<longlongrightarrow> power_int a n) F" using assms by (cases n rule: int_cases4) (auto intro!: tendsto_intros simp: power_int_minus) lemma continuous_power_int: fixes f :: "'a::t2_space \<Rightarrow> 'b::real_normed_div_algebra" assumes "continuous F f" and "f (Lim F (\<lambda>x. x)) \<noteq> 0" shows "continuous F (\<lambda>x. power_int (f x) n)" using assms unfolding continuous_def by (rule tendsto_power_int) lemma continuous_at_within_power_int[continuous_intros]: fixes f :: "'a::t2_space \<Rightarrow> 'b::real_normed_div_algebra" assumes "continuous (at a within s) f" and "f a \<noteq> 0" shows "continuous (at a within s) (\<lambda>x. power_int (f x) n)" using assms unfolding continuous_within by (rule tendsto_power_int) lemma continuous_on_power_int [continuous_intros]: fixes f :: "'a::topological_space \<Rightarrow> 'b::real_normed_div_algebra" assumes "continuous_on s f" and "\<forall>x\<in>s. f x \<noteq> 0" shows "continuous_on s (\<lambda>x. power_int (f x) n)" using assms unfolding continuous_on_def by (blast intro: tendsto_power_int) lemma tendsto_power_int' [tendsto_intros]: fixes a :: "'a::real_normed_div_algebra" assumes f: "(f \<longlongrightarrow> a) F" and a: "a \<noteq> 0 \<or> n \<ge> 0" shows "((\<lambda>x. power_int (f x) n) \<longlongrightarrow> power_int a n) F" using assms by (cases n rule: int_cases4) (auto intro!: tendsto_intros simp: power_int_minus) lemma tendsto_sgn [tendsto_intros]: "(f \<longlongrightarrow> l) F \<Longrightarrow> l \<noteq> 0 \<Longrightarrow> ((\<lambda>x. sgn (f x)) \<longlongrightarrow> sgn l) F" for l :: "'a::real_normed_vector" unfolding sgn_div_norm by (simp add: tendsto_intros) lemma continuous_sgn: fixes f :: "'a::t2_space \<Rightarrow> 'b::real_normed_vector" assumes "continuous F f" and "f (Lim F (\<lambda>x. x)) \<noteq> 0" shows "continuous F (\<lambda>x. sgn (f x))" using assms unfolding continuous_def by (rule tendsto_sgn) lemma continuous_at_within_sgn[continuous_intros]: fixes f :: "'a::t2_space \<Rightarrow> 'b::real_normed_vector" assumes "continuous (at a within s) f" and "f a \<noteq> 0" shows "continuous (at a within s) (\<lambda>x. sgn (f x))" using assms unfolding continuous_within by (rule tendsto_sgn) lemma isCont_sgn[continuous_intros]: fixes f :: "'a::t2_space \<Rightarrow> 'b::real_normed_vector" assumes "isCont f a" and "f a \<noteq> 0" shows "isCont (\<lambda>x. sgn (f x)) a" using assms unfolding continuous_at by (rule tendsto_sgn) lemma continuous_on_sgn[continuous_intros]: fixes f :: "'a::topological_space \<Rightarrow> 'b::real_normed_vector" assumes "continuous_on s f" and "\<forall>x\<in>s. f x \<noteq> 0" shows "continuous_on s (\<lambda>x. sgn (f x))" using assms unfolding continuous_on_def by (blast intro: tendsto_sgn) lemma filterlim_at_infinity: fixes f :: "_ \<Rightarrow> 'a::real_normed_vector" assumes "0 \<le> c" shows "(LIM x F. f x :> at_infinity) \<longleftrightarrow> (\<forall>r>c. eventually (\<lambda>x. r \<le> norm (f x)) F)" unfolding filterlim_iff eventually_at_infinity proof safe fix P :: "'a \<Rightarrow> bool" fix b assume *: "\<forall>r>c. eventually (\<lambda>x. r \<le> norm (f x)) F" assume P: "\<forall>x. b \<le> norm x \<longrightarrow> P x" have "max b (c + 1) > c" by auto with * have "eventually (\<lambda>x. max b (c + 1) \<le> norm (f x)) F" by auto then show "eventually (\<lambda>x. P (f x)) F" proof eventually_elim case (elim x) with P show "P (f x)" by auto qed qed force lemma filterlim_at_infinity_imp_norm_at_top: fixes F assumes "filterlim f at_infinity F" shows "filterlim (\<lambda>x. norm (f x)) at_top F" proof - { fix r :: real have "\<forall>\<^sub>F x in F. r \<le> norm (f x)" using filterlim_at_infinity[of 0 f F] assms by (cases "r > 0") (auto simp: not_less intro: always_eventually order.trans[OF _ norm_ge_zero]) } thus ?thesis by (auto simp: filterlim_at_top) qed lemma filterlim_norm_at_top_imp_at_infinity: fixes F assumes "filterlim (\<lambda>x. norm (f x)) at_top F" shows "filterlim f at_infinity F" using filterlim_at_infinity[of 0 f F] assms by (auto simp: filterlim_at_top) lemma filterlim_norm_at_top: "filterlim norm at_top at_infinity" by (rule filterlim_at_infinity_imp_norm_at_top) (rule filterlim_ident) lemma filterlim_at_infinity_conv_norm_at_top: "filterlim f at_infinity G \<longleftrightarrow> filterlim (\<lambda>x. norm (f x)) at_top G" by (auto simp: filterlim_at_infinity[OF order.refl] filterlim_at_top_gt[of _ _ 0]) lemma eventually_not_equal_at_infinity: "eventually (\<lambda>x. x \<noteq> (a :: 'a :: {real_normed_vector})) at_infinity" proof - from filterlim_norm_at_top[where 'a = 'a] have "\<forall>\<^sub>F x in at_infinity. norm a < norm (x::'a)" by (auto simp: filterlim_at_top_dense) thus ?thesis by eventually_elim auto qed lemma filterlim_int_of_nat_at_topD: fixes F assumes "filterlim (\<lambda>x. f (int x)) F at_top" shows "filterlim f F at_top" proof - have "filterlim (\<lambda>x. f (int (nat x))) F at_top" by (rule filterlim_compose[OF assms filterlim_nat_sequentially]) also have "?this \<longleftrightarrow> filterlim f F at_top" by (intro filterlim_cong refl eventually_mono [OF eventually_ge_at_top[of "0::int"]]) auto finally show ?thesis . qed lemma filterlim_int_sequentially [tendsto_intros]: "filterlim int at_top sequentially" unfolding filterlim_at_top proof fix C :: int show "eventually (\<lambda>n. int n \<ge> C) at_top" using eventually_ge_at_top[of "nat \<lceil>C\<rceil>"] by eventually_elim linarith qed lemma filterlim_real_of_int_at_top [tendsto_intros]: "filterlim real_of_int at_top at_top" unfolding filterlim_at_top proof fix C :: real show "eventually (\<lambda>n. real_of_int n \<ge> C) at_top" using eventually_ge_at_top[of "\<lceil>C\<rceil>"] by eventually_elim linarith qed lemma filterlim_abs_real: "filterlim (abs::real \<Rightarrow> real) at_top at_top" proof (subst filterlim_cong[OF refl refl]) from eventually_ge_at_top[of "0::real"] show "eventually (\<lambda>x::real. \<bar>x\<bar> = x) at_top" by eventually_elim simp qed (simp_all add: filterlim_ident) lemma filterlim_of_real_at_infinity [tendsto_intros]: "filterlim (of_real :: real \<Rightarrow> 'a :: real_normed_algebra_1) at_infinity at_top" by (intro filterlim_norm_at_top_imp_at_infinity) (auto simp: filterlim_abs_real) lemma not_tendsto_and_filterlim_at_infinity: fixes c :: "'a::real_normed_vector" assumes "F \<noteq> bot" and "(f \<longlongrightarrow> c) F" and "filterlim f at_infinity F" shows False proof - from tendstoD[OF assms(2), of "1/2"] have "eventually (\<lambda>x. dist (f x) c < 1/2) F" by simp moreover from filterlim_at_infinity[of "norm c" f F] assms(3) have "eventually (\<lambda>x. norm (f x) \<ge> norm c + 1) F" by simp ultimately have "eventually (\<lambda>x. False) F" proof eventually_elim fix x assume A: "dist (f x) c < 1/2" assume "norm (f x) \<ge> norm c + 1" also have "norm (f x) = dist (f x) 0" by simp also have "\<dots> \<le> dist (f x) c + dist c 0" by (rule dist_triangle) finally show False using A by simp qed with assms show False by simp qed lemma filterlim_at_infinity_imp_not_convergent: assumes "filterlim f at_infinity sequentially" shows "\<not> convergent f" by (rule notI, rule not_tendsto_and_filterlim_at_infinity[OF _ _ assms]) (simp_all add: convergent_LIMSEQ_iff) lemma filterlim_at_infinity_imp_eventually_ne: assumes "filterlim f at_infinity F" shows "eventually (\<lambda>z. f z \<noteq> c) F" proof - have "norm c + 1 > 0" by (intro add_nonneg_pos) simp_all with filterlim_at_infinity[OF order.refl, of f F] assms have "eventually (\<lambda>z. norm (f z) \<ge> norm c + 1) F" by blast then show ?thesis by eventually_elim auto qed lemma tendsto_of_nat [tendsto_intros]: "filterlim (of_nat :: nat \<Rightarrow> 'a::real_normed_algebra_1) at_infinity sequentially" proof (subst filterlim_at_infinity[OF order.refl], intro allI impI) fix r :: real assume r: "r > 0" define n where "n = nat \<lceil>r\<rceil>" from r have n: "\<forall>m\<ge>n. of_nat m \<ge> r" unfolding n_def by linarith from eventually_ge_at_top[of n] show "eventually (\<lambda>m. norm (of_nat m :: 'a) \<ge> r) sequentially" by eventually_elim (use n in simp_all) qed subsection \<open>Relate \<^const>\<open>at\<close>, \<^const>\<open>at_left\<close> and \<^const>\<open>at_right\<close>\<close> text \<open> This lemmas are useful for conversion between \<^term>\<open>at x\<close> to \<^term>\<open>at_left x\<close> and \<^term>\<open>at_right x\<close> and also \<^term>\<open>at_right 0\<close>. \<close> lemmas filterlim_split_at_real = filterlim_split_at[where 'a=real] lemma filtermap_nhds_shift: "filtermap (\<lambda>x. x - d) (nhds a) = nhds (a - d)" for a d :: "'a::real_normed_vector" by (rule filtermap_fun_inverse[where g="\<lambda>x. x + d"]) (auto intro!: tendsto_eq_intros filterlim_ident) lemma filtermap_nhds_minus: "filtermap (\<lambda>x. - x) (nhds a) = nhds (- a)" for a :: "'a::real_normed_vector" by (rule filtermap_fun_inverse[where g=uminus]) (auto intro!: tendsto_eq_intros filterlim_ident) lemma filtermap_at_shift: "filtermap (\<lambda>x. x - d) (at a) = at (a - d)" for a d :: "'a::real_normed_vector" by (simp add: filter_eq_iff eventually_filtermap eventually_at_filter filtermap_nhds_shift[symmetric]) lemma filtermap_at_right_shift: "filtermap (\<lambda>x. x - d) (at_right a) = at_right (a - d)" for a d :: "real" by (simp add: filter_eq_iff eventually_filtermap eventually_at_filter filtermap_nhds_shift[symmetric]) lemma filterlim_shift: fixes d :: "'a::real_normed_vector" assumes "filterlim f F (at a)" shows "filterlim (f \<circ> (+) d) F (at (a - d))" unfolding filterlim_iff proof (intro strip) fix P assume "eventually P F" then have "\<forall>\<^sub>F x in filtermap (\<lambda>y. y - d) (at a). P (f (d + x))" using assms by (force simp add: filterlim_iff eventually_filtermap) then show "(\<forall>\<^sub>F x in at (a - d). P ((f \<circ> (+) d) x))" by (force simp add: filtermap_at_shift) qed lemma filterlim_shift_iff: fixes d :: "'a::real_normed_vector" shows "filterlim (f \<circ> (+) d) F (at (a - d)) = filterlim f F (at a)" (is "?lhs = ?rhs") proof assume L: ?lhs show ?rhs using filterlim_shift [OF L, of "-d"] by (simp add: filterlim_iff) qed (metis filterlim_shift) lemma at_right_to_0: "at_right a = filtermap (\<lambda>x. x + a) (at_right 0)" for a :: real using filtermap_at_right_shift[of "-a" 0] by simp lemma filterlim_at_right_to_0: "filterlim f F (at_right a) \<longleftrightarrow> filterlim (\<lambda>x. f (x + a)) F (at_right 0)" for a :: real unfolding filterlim_def filtermap_filtermap at_right_to_0[of a] .. lemma eventually_at_right_to_0: "eventually P (at_right a) \<longleftrightarrow> eventually (\<lambda>x. P (x + a)) (at_right 0)" for a :: real unfolding at_right_to_0[of a] by (simp add: eventually_filtermap) lemma at_to_0: "at a = filtermap (\<lambda>x. x + a) (at 0)" for a :: "'a::real_normed_vector" using filtermap_at_shift[of "-a" 0] by simp lemma filterlim_at_to_0: "filterlim f F (at a) \<longleftrightarrow> filterlim (\<lambda>x. f (x + a)) F (at 0)" for a :: "'a::real_normed_vector" unfolding filterlim_def filtermap_filtermap at_to_0[of a] .. lemma eventually_at_to_0: "eventually P (at a) \<longleftrightarrow> eventually (\<lambda>x. P (x + a)) (at 0)" for a :: "'a::real_normed_vector" unfolding at_to_0[of a] by (simp add: eventually_filtermap) lemma filtermap_at_minus: "filtermap (\<lambda>x. - x) (at a) = at (- a)" for a :: "'a::real_normed_vector" by (simp add: filter_eq_iff eventually_filtermap eventually_at_filter filtermap_nhds_minus[symmetric]) lemma at_left_minus: "at_left a = filtermap (\<lambda>x. - x) (at_right (- a))" for a :: real by (simp add: filter_eq_iff eventually_filtermap eventually_at_filter filtermap_nhds_minus[symmetric]) lemma at_right_minus: "at_right a = filtermap (\<lambda>x. - x) (at_left (- a))" for a :: real by (simp add: filter_eq_iff eventually_filtermap eventually_at_filter filtermap_nhds_minus[symmetric]) lemma filterlim_at_left_to_right: "filterlim f F (at_left a) \<longleftrightarrow> filterlim (\<lambda>x. f (- x)) F (at_right (-a))" for a :: real unfolding filterlim_def filtermap_filtermap at_left_minus[of a] .. lemma eventually_at_left_to_right: "eventually P (at_left a) \<longleftrightarrow> eventually (\<lambda>x. P (- x)) (at_right (-a))" for a :: real unfolding at_left_minus[of a] by (simp add: eventually_filtermap) lemma filterlim_uminus_at_top_at_bot: "LIM x at_bot. - x :: real :> at_top" unfolding filterlim_at_top eventually_at_bot_dense by (metis leI minus_less_iff order_less_asym) lemma filterlim_uminus_at_bot_at_top: "LIM x at_top. - x :: real :> at_bot" unfolding filterlim_at_bot eventually_at_top_dense by (metis leI less_minus_iff order_less_asym) lemma at_bot_mirror : shows "(at_bot::('a::{ordered_ab_group_add,linorder} filter)) = filtermap uminus at_top" proof (rule filtermap_fun_inverse[symmetric]) show "filterlim uminus at_top (at_bot::'a filter)" using eventually_at_bot_linorder filterlim_at_top le_minus_iff by force show "filterlim uminus (at_bot::'a filter) at_top" by (simp add: filterlim_at_bot minus_le_iff) qed auto lemma at_top_mirror : shows "(at_top::('a::{ordered_ab_group_add,linorder} filter)) = filtermap uminus at_bot" apply (subst at_bot_mirror) by (auto simp: filtermap_filtermap) lemma filterlim_at_top_mirror: "(LIM x at_top. f x :> F) \<longleftrightarrow> (LIM x at_bot. f (-x::real) :> F)" unfolding filterlim_def at_top_mirror filtermap_filtermap .. lemma filterlim_at_bot_mirror: "(LIM x at_bot. f x :> F) \<longleftrightarrow> (LIM x at_top. f (-x::real) :> F)" unfolding filterlim_def at_bot_mirror filtermap_filtermap .. lemma filterlim_uminus_at_top: "(LIM x F. f x :> at_top) \<longleftrightarrow> (LIM x F. - (f x) :: real :> at_bot)" using filterlim_compose[OF filterlim_uminus_at_bot_at_top, of f F] and filterlim_compose[OF filterlim_uminus_at_top_at_bot, of "\<lambda>x. - f x" F] by auto lemma tendsto_at_botI_sequentially: fixes f :: "real \<Rightarrow> 'b::first_countable_topology" assumes *: "\<And>X. filterlim X at_bot sequentially \<Longrightarrow> (\<lambda>n. f (X n)) \<longlonglongrightarrow> y" shows "(f \<longlongrightarrow> y) at_bot" unfolding filterlim_at_bot_mirror proof (rule tendsto_at_topI_sequentially) fix X :: "nat \<Rightarrow> real" assume "filterlim X at_top sequentially" thus "(\<lambda>n. f (-X n)) \<longlonglongrightarrow> y" by (intro *) (auto simp: filterlim_uminus_at_top) qed lemma filterlim_at_infinity_imp_filterlim_at_top: assumes "filterlim (f :: 'a \<Rightarrow> real) at_infinity F" assumes "eventually (\<lambda>x. f x > 0) F" shows "filterlim f at_top F" proof - from assms(2) have *: "eventually (\<lambda>x. norm (f x) = f x) F" by eventually_elim simp from assms(1) show ?thesis unfolding filterlim_at_infinity_conv_norm_at_top by (subst (asm) filterlim_cong[OF refl refl *]) qed lemma filterlim_at_infinity_imp_filterlim_at_bot: assumes "filterlim (f :: 'a \<Rightarrow> real) at_infinity F" assumes "eventually (\<lambda>x. f x < 0) F" shows "filterlim f at_bot F" proof - from assms(2) have *: "eventually (\<lambda>x. norm (f x) = -f x) F" by eventually_elim simp from assms(1) have "filterlim (\<lambda>x. - f x) at_top F" unfolding filterlim_at_infinity_conv_norm_at_top by (subst (asm) filterlim_cong[OF refl refl *]) thus ?thesis by (simp add: filterlim_uminus_at_top) qed lemma filterlim_uminus_at_bot: "(LIM x F. f x :> at_bot) \<longleftrightarrow> (LIM x F. - (f x) :: real :> at_top)" unfolding filterlim_uminus_at_top by simp lemma filterlim_inverse_at_top_right: "LIM x at_right (0::real). inverse x :> at_top" unfolding filterlim_at_top_gt[where c=0] eventually_at_filter proof safe fix Z :: real assume [arith]: "0 < Z" then have "eventually (\<lambda>x. x < inverse Z) (nhds 0)" by (auto simp: eventually_nhds_metric dist_real_def intro!: exI[of _ "\<bar>inverse Z\<bar>"]) then show "eventually (\<lambda>x. x \<noteq> 0 \<longrightarrow> x \<in> {0<..} \<longrightarrow> Z \<le> inverse x) (nhds 0)" by (auto elim!: eventually_mono simp: inverse_eq_divide field_simps) qed lemma tendsto_inverse_0: fixes x :: "_ \<Rightarrow> 'a::real_normed_div_algebra" shows "(inverse \<longlongrightarrow> (0::'a)) at_infinity" unfolding tendsto_Zfun_iff diff_0_right Zfun_def eventually_at_infinity proof safe fix r :: real assume "0 < r" show "\<exists>b. \<forall>x. b \<le> norm x \<longrightarrow> norm (inverse x :: 'a) < r" proof (intro exI[of _ "inverse (r / 2)"] allI impI) fix x :: 'a from \<open>0 < r\<close> have "0 < inverse (r / 2)" by simp also assume *: "inverse (r / 2) \<le> norm x" finally show "norm (inverse x) < r" using * \<open>0 < r\<close> by (subst nonzero_norm_inverse) (simp_all add: inverse_eq_divide field_simps) qed qed lemma tendsto_add_filterlim_at_infinity: fixes c :: "'b::real_normed_vector" and F :: "'a filter" assumes "(f \<longlongrightarrow> c) F" and "filterlim g at_infinity F" shows "filterlim (\<lambda>x. f x + g x) at_infinity F" proof (subst filterlim_at_infinity[OF order_refl], safe) fix r :: real assume r: "r > 0" from assms(1) have "((\<lambda>x. norm (f x)) \<longlongrightarrow> norm c) F" by (rule tendsto_norm) then have "eventually (\<lambda>x. norm (f x) < norm c + 1) F" by (rule order_tendstoD) simp_all moreover from r have "r + norm c + 1 > 0" by (intro add_pos_nonneg) simp_all with assms(2) have "eventually (\<lambda>x. norm (g x) \<ge> r + norm c + 1) F" unfolding filterlim_at_infinity[OF order_refl] by (elim allE[of _ "r + norm c + 1"]) simp_all ultimately show "eventually (\<lambda>x. norm (f x + g x) \<ge> r) F" proof eventually_elim fix x :: 'a assume A: "norm (f x) < norm c + 1" and B: "r + norm c + 1 \<le> norm (g x)" from A B have "r \<le> norm (g x) - norm (f x)" by simp also have "norm (g x) - norm (f x) \<le> norm (g x + f x)" by (rule norm_diff_ineq) finally show "r \<le> norm (f x + g x)" by (simp add: add_ac) qed qed lemma tendsto_add_filterlim_at_infinity': fixes c :: "'b::real_normed_vector" and F :: "'a filter" assumes "filterlim f at_infinity F" and "(g \<longlongrightarrow> c) F" shows "filterlim (\<lambda>x. f x + g x) at_infinity F" by (subst add.commute) (rule tendsto_add_filterlim_at_infinity assms)+ lemma filterlim_inverse_at_right_top: "LIM x at_top. inverse x :> at_right (0::real)" unfolding filterlim_at by (auto simp: eventually_at_top_dense) (metis tendsto_inverse_0 filterlim_mono at_top_le_at_infinity order_refl) lemma filterlim_inverse_at_top: "(f \<longlongrightarrow> (0 :: real)) F \<Longrightarrow> eventually (\<lambda>x. 0 < f x) F \<Longrightarrow> LIM x F. inverse (f x) :> at_top" by (intro filterlim_compose[OF filterlim_inverse_at_top_right]) (simp add: filterlim_def eventually_filtermap eventually_mono at_within_def le_principal) lemma filterlim_inverse_at_bot_neg: "LIM x (at_left (0::real)). inverse x :> at_bot" by (simp add: filterlim_inverse_at_top_right filterlim_uminus_at_bot filterlim_at_left_to_right) lemma filterlim_inverse_at_bot: "(f \<longlongrightarrow> (0 :: real)) F \<Longrightarrow> eventually (\<lambda>x. f x < 0) F \<Longrightarrow> LIM x F. inverse (f x) :> at_bot" unfolding filterlim_uminus_at_bot inverse_minus_eq[symmetric] by (rule filterlim_inverse_at_top) (simp_all add: tendsto_minus_cancel_left[symmetric]) lemma at_right_to_top: "(at_right (0::real)) = filtermap inverse at_top" by (intro filtermap_fun_inverse[symmetric, where g=inverse]) (auto intro: filterlim_inverse_at_top_right filterlim_inverse_at_right_top) lemma eventually_at_right_to_top: "eventually P (at_right (0::real)) \<longleftrightarrow> eventually (\<lambda>x. P (inverse x)) at_top" unfolding at_right_to_top eventually_filtermap .. lemma filterlim_at_right_to_top: "filterlim f F (at_right (0::real)) \<longleftrightarrow> (LIM x at_top. f (inverse x) :> F)" unfolding filterlim_def at_right_to_top filtermap_filtermap .. lemma at_top_to_right: "at_top = filtermap inverse (at_right (0::real))" unfolding at_right_to_top filtermap_filtermap inverse_inverse_eq filtermap_ident .. lemma eventually_at_top_to_right: "eventually P at_top \<longleftrightarrow> eventually (\<lambda>x. P (inverse x)) (at_right (0::real))" unfolding at_top_to_right eventually_filtermap .. lemma filterlim_at_top_to_right: "filterlim f F at_top \<longleftrightarrow> (LIM x (at_right (0::real)). f (inverse x) :> F)" unfolding filterlim_def at_top_to_right filtermap_filtermap .. lemma filterlim_inverse_at_infinity: fixes x :: "_ \<Rightarrow> 'a::{real_normed_div_algebra, division_ring}" shows "filterlim inverse at_infinity (at (0::'a))" unfolding filterlim_at_infinity[OF order_refl] proof safe fix r :: real assume "0 < r" then show "eventually (\<lambda>x::'a. r \<le> norm (inverse x)) (at 0)" unfolding eventually_at norm_inverse by (intro exI[of _ "inverse r"]) (auto simp: norm_conv_dist[symmetric] field_simps inverse_eq_divide) qed lemma filterlim_inverse_at_iff: fixes g :: "'a \<Rightarrow> 'b::{real_normed_div_algebra, division_ring}" shows "(LIM x F. inverse (g x) :> at 0) \<longleftrightarrow> (LIM x F. g x :> at_infinity)" unfolding filterlim_def filtermap_filtermap[symmetric] proof assume "filtermap g F \<le> at_infinity" then have "filtermap inverse (filtermap g F) \<le> filtermap inverse at_infinity" by (rule filtermap_mono) also have "\<dots> \<le> at 0" using tendsto_inverse_0[where 'a='b] by (auto intro!: exI[of _ 1] simp: le_principal eventually_filtermap filterlim_def at_within_def eventually_at_infinity) finally show "filtermap inverse (filtermap g F) \<le> at 0" . next assume "filtermap inverse (filtermap g F) \<le> at 0" then have "filtermap inverse (filtermap inverse (filtermap g F)) \<le> filtermap inverse (at 0)" by (rule filtermap_mono) with filterlim_inverse_at_infinity show "filtermap g F \<le> at_infinity" by (auto intro: order_trans simp: filterlim_def filtermap_filtermap) qed lemma tendsto_mult_filterlim_at_infinity: fixes c :: "'a::real_normed_field" assumes "(f \<longlongrightarrow> c) F" "c \<noteq> 0" assumes "filterlim g at_infinity F" shows "filterlim (\<lambda>x. f x * g x) at_infinity F" proof - have "((\<lambda>x. inverse (f x) * inverse (g x)) \<longlongrightarrow> inverse c * 0) F" by (intro tendsto_mult tendsto_inverse assms filterlim_compose[OF tendsto_inverse_0]) then have "filterlim (\<lambda>x. inverse (f x) * inverse (g x)) (at (inverse c * 0)) F" unfolding filterlim_at using assms by (auto intro: filterlim_at_infinity_imp_eventually_ne tendsto_imp_eventually_ne eventually_conj) then show ?thesis by (subst filterlim_inverse_at_iff[symmetric]) simp_all qed lemma filterlim_power_int_neg_at_infinity: fixes f :: "_ \<Rightarrow> 'a::{real_normed_div_algebra, division_ring}" assumes "n < 0" and lim: "(f \<longlongrightarrow> 0) F" and ev: "eventually (\<lambda>x. f x \<noteq> 0) F" shows "filterlim (\<lambda>x. f x powi n) at_infinity F" proof - have lim': "((\<lambda>x. f x ^ nat (- n)) \<longlongrightarrow> 0) F" by (rule tendsto_eq_intros lim)+ (use \<open>n < 0\<close> in auto) have ev': "eventually (\<lambda>x. f x ^ nat (-n) \<noteq> 0) F" using ev by eventually_elim (use \<open>n < 0\<close> in auto) have "filterlim (\<lambda>x. inverse (f x ^ nat (-n))) at_infinity F" by (intro filterlim_compose[OF filterlim_inverse_at_infinity]) (use lim' ev' in \<open>auto simp: filterlim_at\<close>) thus ?thesis using \<open>n < 0\<close> by (simp add: power_int_def power_inverse) qed lemma tendsto_inverse_0_at_top: "LIM x F. f x :> at_top \<Longrightarrow> ((\<lambda>x. inverse (f x) :: real) \<longlongrightarrow> 0) F" by (metis filterlim_at filterlim_mono[OF _ at_top_le_at_infinity order_refl] filterlim_inverse_at_iff) lemma filterlim_inverse_at_top_iff: "eventually (\<lambda>x. 0 < f x) F \<Longrightarrow> (LIM x F. inverse (f x) :> at_top) \<longleftrightarrow> (f \<longlongrightarrow> (0 :: real)) F" by (auto dest: tendsto_inverse_0_at_top filterlim_inverse_at_top) lemma filterlim_at_top_iff_inverse_0: "eventually (\<lambda>x. 0 < f x) F \<Longrightarrow> (LIM x F. f x :> at_top) \<longleftrightarrow> ((inverse \<circ> f) \<longlongrightarrow> (0 :: real)) F" using filterlim_inverse_at_top_iff [of "inverse \<circ> f"] by auto lemma real_tendsto_divide_at_top: fixes c::"real" assumes "(f \<longlongrightarrow> c) F" assumes "filterlim g at_top F" shows "((\<lambda>x. f x / g x) \<longlongrightarrow> 0) F" by (auto simp: divide_inverse_commute intro!: tendsto_mult[THEN tendsto_eq_rhs] tendsto_inverse_0_at_top assms) lemma mult_nat_left_at_top: "c > 0 \<Longrightarrow> filterlim (\<lambda>x. c * x) at_top sequentially" for c :: nat by (rule filterlim_subseq) (auto simp: strict_mono_def) lemma mult_nat_right_at_top: "c > 0 \<Longrightarrow> filterlim (\<lambda>x. x * c) at_top sequentially" for c :: nat by (rule filterlim_subseq) (auto simp: strict_mono_def) lemma filterlim_times_pos: "LIM x F1. c * f x :> at_right l" if "filterlim f (at_right p) F1" "0 < c" "l = c * p" for c::"'a::{linordered_field, linorder_topology}" unfolding filterlim_iff proof safe fix P assume "\<forall>\<^sub>F x in at_right l. P x" then obtain d where "c * p < d" "\<And>y. y > c * p \<Longrightarrow> y < d \<Longrightarrow> P y" unfolding \<open>l = _ \<close> eventually_at_right_field by auto then have "\<forall>\<^sub>F a in at_right p. P (c * a)" by (auto simp: eventually_at_right_field \<open>0 < c\<close> field_simps intro!: exI[where x="d/c"]) from that(1)[unfolded filterlim_iff, rule_format, OF this] show "\<forall>\<^sub>F x in F1. P (c * f x)" . qed lemma filtermap_nhds_times: "c \<noteq> 0 \<Longrightarrow> filtermap (times c) (nhds a) = nhds (c * a)" for a c :: "'a::real_normed_field" by (rule filtermap_fun_inverse[where g="\<lambda>x. inverse c * x"]) (auto intro!: tendsto_eq_intros filterlim_ident) lemma filtermap_times_pos_at_right: fixes c::"'a::{linordered_field, linorder_topology}" assumes "c > 0" shows "filtermap (times c) (at_right p) = at_right (c * p)" using assms by (intro filtermap_fun_inverse[where g="\<lambda>x. inverse c * x"]) (auto intro!: filterlim_ident filterlim_times_pos) lemma at_to_infinity: "(at (0::'a::{real_normed_field,field})) = filtermap inverse at_infinity" proof (rule antisym) have "(inverse \<longlongrightarrow> (0::'a)) at_infinity" by (fact tendsto_inverse_0) then show "filtermap inverse at_infinity \<le> at (0::'a)" using filterlim_def filterlim_ident filterlim_inverse_at_iff by fastforce next have "filtermap inverse (filtermap inverse (at (0::'a))) \<le> filtermap inverse at_infinity" using filterlim_inverse_at_infinity unfolding filterlim_def by (rule filtermap_mono) then show "at (0::'a) \<le> filtermap inverse at_infinity" by (simp add: filtermap_ident filtermap_filtermap) qed lemma lim_at_infinity_0: fixes l :: "'a::{real_normed_field,field}" shows "(f \<longlongrightarrow> l) at_infinity \<longleftrightarrow> ((f \<circ> inverse) \<longlongrightarrow> l) (at (0::'a))" by (simp add: tendsto_compose_filtermap at_to_infinity filtermap_filtermap) lemma lim_zero_infinity: fixes l :: "'a::{real_normed_field,field}" shows "((\<lambda>x. f(1 / x)) \<longlongrightarrow> l) (at (0::'a)) \<Longrightarrow> (f \<longlongrightarrow> l) at_infinity" by (simp add: inverse_eq_divide lim_at_infinity_0 comp_def) text \<open> We only show rules for multiplication and addition when the functions are either against a real value or against infinity. Further rules are easy to derive by using @{thm filterlim_uminus_at_top}. \<close> lemma filterlim_tendsto_pos_mult_at_top: assumes f: "(f \<longlongrightarrow> c) F" and c: "0 < c" and g: "LIM x F. g x :> at_top" shows "LIM x F. (f x * g x :: real) :> at_top" unfolding filterlim_at_top_gt[where c=0] proof safe fix Z :: real assume "0 < Z" from f \<open>0 < c\<close> have "eventually (\<lambda>x. c / 2 < f x) F" by (auto dest!: tendstoD[where e="c / 2"] elim!: eventually_mono simp: dist_real_def abs_real_def split: if_split_asm) moreover from g have "eventually (\<lambda>x. (Z / c * 2) \<le> g x) F" unfolding filterlim_at_top by auto ultimately show "eventually (\<lambda>x. Z \<le> f x * g x) F" proof eventually_elim case (elim x) with \<open>0 < Z\<close> \<open>0 < c\<close> have "c / 2 * (Z / c * 2) \<le> f x * g x" by (intro mult_mono) (auto simp: zero_le_divide_iff) with \<open>0 < c\<close> show "Z \<le> f x * g x" by simp qed qed lemma filterlim_at_top_mult_at_top: assumes f: "LIM x F. f x :> at_top" and g: "LIM x F. g x :> at_top" shows "LIM x F. (f x * g x :: real) :> at_top" unfolding filterlim_at_top_gt[where c=0] proof safe fix Z :: real assume "0 < Z" from f have "eventually (\<lambda>x. 1 \<le> f x) F" unfolding filterlim_at_top by auto moreover from g have "eventually (\<lambda>x. Z \<le> g x) F" unfolding filterlim_at_top by auto ultimately show "eventually (\<lambda>x. Z \<le> f x * g x) F" proof eventually_elim case (elim x) with \<open>0 < Z\<close> have "1 * Z \<le> f x * g x" by (intro mult_mono) (auto simp: zero_le_divide_iff) then show "Z \<le> f x * g x" by simp qed qed lemma filterlim_at_top_mult_tendsto_pos: assumes f: "(f \<longlongrightarrow> c) F" and c: "0 < c" and g: "LIM x F. g x :> at_top" shows "LIM x F. (g x * f x:: real) :> at_top" by (auto simp: mult.commute intro!: filterlim_tendsto_pos_mult_at_top f c g) lemma filterlim_tendsto_pos_mult_at_bot: fixes c :: real assumes "(f \<longlongrightarrow> c) F" "0 < c" "filterlim g at_bot F" shows "LIM x F. f x * g x :> at_bot" using filterlim_tendsto_pos_mult_at_top[OF assms(1,2), of "\<lambda>x. - g x"] assms(3) unfolding filterlim_uminus_at_bot by simp lemma filterlim_tendsto_neg_mult_at_bot: fixes c :: real assumes c: "(f \<longlongrightarrow> c) F" "c < 0" and g: "filterlim g at_top F" shows "LIM x F. f x * g x :> at_bot" using c filterlim_tendsto_pos_mult_at_top[of "\<lambda>x. - f x" "- c" F, OF _ _ g] unfolding filterlim_uminus_at_bot tendsto_minus_cancel_left by simp lemma filterlim_cmult_at_bot_at_top: assumes "filterlim (h :: _ \<Rightarrow> real) at_top F" "c \<noteq> 0" "G = (if c > 0 then at_top else at_bot)" shows "filterlim (\<lambda>x. c * h x) G F" using assms filterlim_tendsto_pos_mult_at_top[OF tendsto_const[of c], of h F] filterlim_tendsto_neg_mult_at_bot[OF tendsto_const[of c], of h F] by simp lemma filterlim_pow_at_top: fixes f :: "'a \<Rightarrow> real" assumes "0 < n" and f: "LIM x F. f x :> at_top" shows "LIM x F. (f x)^n :: real :> at_top" using \<open>0 < n\<close> proof (induct n) case 0 then show ?case by simp next case (Suc n) with f show ?case by (cases "n = 0") (auto intro!: filterlim_at_top_mult_at_top) qed lemma filterlim_pow_at_bot_even: fixes f :: "real \<Rightarrow> real" shows "0 < n \<Longrightarrow> LIM x F. f x :> at_bot \<Longrightarrow> even n \<Longrightarrow> LIM x F. (f x)^n :> at_top" using filterlim_pow_at_top[of n "\<lambda>x. - f x" F] by (simp add: filterlim_uminus_at_top) lemma filterlim_pow_at_bot_odd: fixes f :: "real \<Rightarrow> real" shows "0 < n \<Longrightarrow> LIM x F. f x :> at_bot \<Longrightarrow> odd n \<Longrightarrow> LIM x F. (f x)^n :> at_bot" using filterlim_pow_at_top[of n "\<lambda>x. - f x" F] by (simp add: filterlim_uminus_at_bot) lemma filterlim_power_at_infinity [tendsto_intros]: fixes F and f :: "'a \<Rightarrow> 'b :: real_normed_div_algebra" assumes "filterlim f at_infinity F" "n > 0" shows "filterlim (\<lambda>x. f x ^ n) at_infinity F" by (rule filterlim_norm_at_top_imp_at_infinity) (auto simp: norm_power intro!: filterlim_pow_at_top assms intro: filterlim_at_infinity_imp_norm_at_top) lemma filterlim_tendsto_add_at_top: assumes f: "(f \<longlongrightarrow> c) F" and g: "LIM x F. g x :> at_top" shows "LIM x F. (f x + g x :: real) :> at_top" unfolding filterlim_at_top_gt[where c=0] proof safe fix Z :: real assume "0 < Z" from f have "eventually (\<lambda>x. c - 1 < f x) F" by (auto dest!: tendstoD[where e=1] elim!: eventually_mono simp: dist_real_def) moreover from g have "eventually (\<lambda>x. Z - (c - 1) \<le> g x) F" unfolding filterlim_at_top by auto ultimately show "eventually (\<lambda>x. Z \<le> f x + g x) F" by eventually_elim simp qed lemma LIM_at_top_divide: fixes f g :: "'a \<Rightarrow> real" assumes f: "(f \<longlongrightarrow> a) F" "0 < a" and g: "(g \<longlongrightarrow> 0) F" "eventually (\<lambda>x. 0 < g x) F" shows "LIM x F. f x / g x :> at_top" unfolding divide_inverse by (rule filterlim_tendsto_pos_mult_at_top[OF f]) (rule filterlim_inverse_at_top[OF g]) lemma filterlim_at_top_add_at_top: assumes f: "LIM x F. f x :> at_top" and g: "LIM x F. g x :> at_top" shows "LIM x F. (f x + g x :: real) :> at_top" unfolding filterlim_at_top_gt[where c=0] proof safe fix Z :: real assume "0 < Z" from f have "eventually (\<lambda>x. 0 \<le> f x) F" unfolding filterlim_at_top by auto moreover from g have "eventually (\<lambda>x. Z \<le> g x) F" unfolding filterlim_at_top by auto ultimately show "eventually (\<lambda>x. Z \<le> f x + g x) F" by eventually_elim simp qed lemma tendsto_divide_0: fixes f :: "_ \<Rightarrow> 'a::{real_normed_div_algebra, division_ring}" assumes f: "(f \<longlongrightarrow> c) F" and g: "LIM x F. g x :> at_infinity" shows "((\<lambda>x. f x / g x) \<longlongrightarrow> 0) F" using tendsto_mult[OF f filterlim_compose[OF tendsto_inverse_0 g]] by (simp add: divide_inverse) lemma linear_plus_1_le_power: fixes x :: real assumes x: "0 \<le> x" shows "real n * x + 1 \<le> (x + 1) ^ n" proof (induct n) case 0 then show ?case by simp next case (Suc n) from x have "real (Suc n) * x + 1 \<le> (x + 1) * (real n * x + 1)" by (simp add: field_simps) also have "\<dots> \<le> (x + 1)^Suc n" using Suc x by (simp add: mult_left_mono) finally show ?case . qed lemma filterlim_realpow_sequentially_gt1: fixes x :: "'a :: real_normed_div_algebra" assumes x[arith]: "1 < norm x" shows "LIM n sequentially. x ^ n :> at_infinity" proof (intro filterlim_at_infinity[THEN iffD2] allI impI) fix y :: real assume "0 < y" obtain N :: nat where "y < real N * (norm x - 1)" by (meson diff_gt_0_iff_gt reals_Archimedean3 x) also have "\<dots> \<le> real N * (norm x - 1) + 1" by simp also have "\<dots> \<le> (norm x - 1 + 1) ^ N" by (rule linear_plus_1_le_power) simp also have "\<dots> = norm x ^ N" by simp finally have "\<forall>n\<ge>N. y \<le> norm x ^ n" by (metis order_less_le_trans power_increasing order_less_imp_le x) then show "eventually (\<lambda>n. y \<le> norm (x ^ n)) sequentially" unfolding eventually_sequentially by (auto simp: norm_power) qed simp lemma filterlim_divide_at_infinity: fixes f g :: "'a \<Rightarrow> 'a :: real_normed_field" assumes "filterlim f (nhds c) F" "filterlim g (at 0) F" "c \<noteq> 0" shows "filterlim (\<lambda>x. f x / g x) at_infinity F" proof - have "filterlim (\<lambda>x. f x * inverse (g x)) at_infinity F" by (intro tendsto_mult_filterlim_at_infinity[OF assms(1,3)] filterlim_compose [OF filterlim_inverse_at_infinity assms(2)]) thus ?thesis by (simp add: field_simps) qed subsection \<open>Floor and Ceiling\<close> lemma eventually_floor_less: fixes f :: "'a \<Rightarrow> 'b::{order_topology,floor_ceiling}" assumes f: "(f \<longlongrightarrow> l) F" and l: "l \<notin> \<int>" shows "\<forall>\<^sub>F x in F. of_int (floor l) < f x" by (intro order_tendstoD[OF f]) (metis Ints_of_int antisym_conv2 floor_correct l) lemma eventually_less_ceiling: fixes f :: "'a \<Rightarrow> 'b::{order_topology,floor_ceiling}" assumes f: "(f \<longlongrightarrow> l) F" and l: "l \<notin> \<int>" shows "\<forall>\<^sub>F x in F. f x < of_int (ceiling l)" by (intro order_tendstoD[OF f]) (metis Ints_of_int l le_of_int_ceiling less_le) lemma eventually_floor_eq: fixes f::"'a \<Rightarrow> 'b::{order_topology,floor_ceiling}" assumes f: "(f \<longlongrightarrow> l) F" and l: "l \<notin> \<int>" shows "\<forall>\<^sub>F x in F. floor (f x) = floor l" using eventually_floor_less[OF assms] eventually_less_ceiling[OF assms] by eventually_elim (meson floor_less_iff less_ceiling_iff not_less_iff_gr_or_eq) lemma eventually_ceiling_eq: fixes f::"'a \<Rightarrow> 'b::{order_topology,floor_ceiling}" assumes f: "(f \<longlongrightarrow> l) F" and l: "l \<notin> \<int>" shows "\<forall>\<^sub>F x in F. ceiling (f x) = ceiling l" using eventually_floor_less[OF assms] eventually_less_ceiling[OF assms] by eventually_elim (meson floor_less_iff less_ceiling_iff not_less_iff_gr_or_eq) lemma tendsto_of_int_floor: fixes f::"'a \<Rightarrow> 'b::{order_topology,floor_ceiling}" assumes "(f \<longlongrightarrow> l) F" and "l \<notin> \<int>" shows "((\<lambda>x. of_int (floor (f x)) :: 'c::{ring_1,topological_space}) \<longlongrightarrow> of_int (floor l)) F" using eventually_floor_eq[OF assms] by (simp add: eventually_mono topological_tendstoI) lemma tendsto_of_int_ceiling: fixes f::"'a \<Rightarrow> 'b::{order_topology,floor_ceiling}" assumes "(f \<longlongrightarrow> l) F" and "l \<notin> \<int>" shows "((\<lambda>x. of_int (ceiling (f x)):: 'c::{ring_1,topological_space}) \<longlongrightarrow> of_int (ceiling l)) F" using eventually_ceiling_eq[OF assms] by (simp add: eventually_mono topological_tendstoI) lemma continuous_on_of_int_floor: "continuous_on (UNIV - \<int>::'a::{order_topology, floor_ceiling} set) (\<lambda>x. of_int (floor x)::'b::{ring_1, topological_space})" unfolding continuous_on_def by (auto intro!: tendsto_of_int_floor) lemma continuous_on_of_int_ceiling: "continuous_on (UNIV - \<int>::'a::{order_topology, floor_ceiling} set) (\<lambda>x. of_int (ceiling x)::'b::{ring_1, topological_space})" unfolding continuous_on_def by (auto intro!: tendsto_of_int_ceiling) subsection \<open>Limits of Sequences\<close> lemma [trans]: "X = Y \<Longrightarrow> Y \<longlonglongrightarrow> z \<Longrightarrow> X \<longlonglongrightarrow> z" by simp lemma LIMSEQ_iff: fixes L :: "'a::real_normed_vector" shows "(X \<longlonglongrightarrow> L) = (\<forall>r>0. \<exists>no. \<forall>n \<ge> no. norm (X n - L) < r)" unfolding lim_sequentially dist_norm .. lemma LIMSEQ_I: "(\<And>r. 0 < r \<Longrightarrow> \<exists>no. \<forall>n\<ge>no. norm (X n - L) < r) \<Longrightarrow> X \<longlonglongrightarrow> L" for L :: "'a::real_normed_vector" by (simp add: LIMSEQ_iff) lemma LIMSEQ_D: "X \<longlonglongrightarrow> L \<Longrightarrow> 0 < r \<Longrightarrow> \<exists>no. \<forall>n\<ge>no. norm (X n - L) < r" for L :: "'a::real_normed_vector" by (simp add: LIMSEQ_iff) lemma LIMSEQ_linear: "X \<longlonglongrightarrow> x \<Longrightarrow> l > 0 \<Longrightarrow> (\<lambda> n. X (n * l)) \<longlonglongrightarrow> x" unfolding tendsto_def eventually_sequentially by (metis div_le_dividend div_mult_self1_is_m le_trans mult.commute) text \<open>Transformation of limit.\<close> lemma Lim_transform: "(g \<longlongrightarrow> a) F \<Longrightarrow> ((\<lambda>x. f x - g x) \<longlongrightarrow> 0) F \<Longrightarrow> (f \<longlongrightarrow> a) F" for a b :: "'a::real_normed_vector" using tendsto_add [of g a F "\<lambda>x. f x - g x" 0] by simp lemma Lim_transform2: "(f \<longlongrightarrow> a) F \<Longrightarrow> ((\<lambda>x. f x - g x) \<longlongrightarrow> 0) F \<Longrightarrow> (g \<longlongrightarrow> a) F" for a b :: "'a::real_normed_vector" by (erule Lim_transform) (simp add: tendsto_minus_cancel) proposition Lim_transform_eq: "((\<lambda>x. f x - g x) \<longlongrightarrow> 0) F \<Longrightarrow> (f \<longlongrightarrow> a) F \<longleftrightarrow> (g \<longlongrightarrow> a) F" for a :: "'a::real_normed_vector" using Lim_transform Lim_transform2 by blast lemma Lim_transform_eventually: "\<lbrakk>(f \<longlongrightarrow> l) F; eventually (\<lambda>x. f x = g x) F\<rbrakk> \<Longrightarrow> (g \<longlongrightarrow> l) F" using eventually_elim2 by (fastforce simp add: tendsto_def) lemma Lim_transform_within: assumes "(f \<longlongrightarrow> l) (at x within S)" and "0 < d" and "\<And>x'. x'\<in>S \<Longrightarrow> 0 < dist x' x \<Longrightarrow> dist x' x < d \<Longrightarrow> f x' = g x'" shows "(g \<longlongrightarrow> l) (at x within S)" proof (rule Lim_transform_eventually) show "eventually (\<lambda>x. f x = g x) (at x within S)" using assms by (auto simp: eventually_at) show "(f \<longlongrightarrow> l) (at x within S)" by fact qed lemma filterlim_transform_within: assumes "filterlim g G (at x within S)" assumes "G \<le> F" "0<d" "(\<And>x'. x' \<in> S \<Longrightarrow> 0 < dist x' x \<Longrightarrow> dist x' x < d \<Longrightarrow> f x' = g x') " shows "filterlim f F (at x within S)" using assms apply (elim filterlim_mono_eventually) unfolding eventually_at by auto text \<open>Common case assuming being away from some crucial point like 0.\<close> lemma Lim_transform_away_within: fixes a b :: "'a::t1_space" assumes "a \<noteq> b" and "\<forall>x\<in>S. x \<noteq> a \<and> x \<noteq> b \<longrightarrow> f x = g x" and "(f \<longlongrightarrow> l) (at a within S)" shows "(g \<longlongrightarrow> l) (at a within S)" proof (rule Lim_transform_eventually) show "(f \<longlongrightarrow> l) (at a within S)" by fact show "eventually (\<lambda>x. f x = g x) (at a within S)" unfolding eventually_at_topological by (rule exI [where x="- {b}"]) (simp add: open_Compl assms) qed lemma Lim_transform_away_at: fixes a b :: "'a::t1_space" assumes ab: "a \<noteq> b" and fg: "\<forall>x. x \<noteq> a \<and> x \<noteq> b \<longrightarrow> f x = g x" and fl: "(f \<longlongrightarrow> l) (at a)" shows "(g \<longlongrightarrow> l) (at a)" using Lim_transform_away_within[OF ab, of UNIV f g l] fg fl by simp text \<open>Alternatively, within an open set.\<close> lemma Lim_transform_within_open: assumes "(f \<longlongrightarrow> l) (at a within T)" and "open s" and "a \<in> s" and "\<And>x. x\<in>s \<Longrightarrow> x \<noteq> a \<Longrightarrow> f x = g x" shows "(g \<longlongrightarrow> l) (at a within T)" proof (rule Lim_transform_eventually) show "eventually (\<lambda>x. f x = g x) (at a within T)" unfolding eventually_at_topological using assms by auto show "(f \<longlongrightarrow> l) (at a within T)" by fact qed text \<open>A congruence rule allowing us to transform limits assuming not at point.\<close> lemma Lim_cong_within: assumes "a = b" and "x = y" and "S = T" and "\<And>x. x \<noteq> b \<Longrightarrow> x \<in> T \<Longrightarrow> f x = g x" shows "(f \<longlongrightarrow> x) (at a within S) \<longleftrightarrow> (g \<longlongrightarrow> y) (at b within T)" unfolding tendsto_def eventually_at_topological using assms by simp text \<open>An unbounded sequence's inverse tends to 0.\<close> lemma LIMSEQ_inverse_zero: assumes "\<And>r::real. \<exists>N. \<forall>n\<ge>N. r < X n" shows "(\<lambda>n. inverse (X n)) \<longlonglongrightarrow> 0" apply (rule filterlim_compose[OF tendsto_inverse_0]) by (metis assms eventually_at_top_linorderI filterlim_at_top_dense filterlim_at_top_imp_at_infinity) text \<open>The sequence \<^term>\<open>1/n\<close> tends to 0 as \<^term>\<open>n\<close> tends to infinity.\<close> lemma LIMSEQ_inverse_real_of_nat: "(\<lambda>n. inverse (real (Suc n))) \<longlonglongrightarrow> 0" by (metis filterlim_compose tendsto_inverse_0 filterlim_mono order_refl filterlim_Suc filterlim_compose[OF filterlim_real_sequentially] at_top_le_at_infinity) text \<open> The sequence \<^term>\<open>r + 1/n\<close> tends to \<^term>\<open>r\<close> as \<^term>\<open>n\<close> tends to infinity is now easily proved. \<close> lemma LIMSEQ_inverse_real_of_nat_add: "(\<lambda>n. r + inverse (real (Suc n))) \<longlonglongrightarrow> r" using tendsto_add [OF tendsto_const LIMSEQ_inverse_real_of_nat] by auto lemma LIMSEQ_inverse_real_of_nat_add_minus: "(\<lambda>n. r + -inverse (real (Suc n))) \<longlonglongrightarrow> r" using tendsto_add [OF tendsto_const tendsto_minus [OF LIMSEQ_inverse_real_of_nat]] by auto lemma LIMSEQ_inverse_real_of_nat_add_minus_mult: "(\<lambda>n. r * (1 + - inverse (real (Suc n)))) \<longlonglongrightarrow> r" using tendsto_mult [OF tendsto_const LIMSEQ_inverse_real_of_nat_add_minus [of 1]] by auto lemma lim_inverse_n: "((\<lambda>n. inverse(of_nat n)) \<longlongrightarrow> (0::'a::real_normed_field)) sequentially" using lim_1_over_n by (simp add: inverse_eq_divide) lemma lim_inverse_n': "((\<lambda>n. 1 / n) \<longlongrightarrow> 0) sequentially" using lim_inverse_n by (simp add: inverse_eq_divide) lemma LIMSEQ_Suc_n_over_n: "(\<lambda>n. of_nat (Suc n) / of_nat n :: 'a :: real_normed_field) \<longlonglongrightarrow> 1" proof (rule Lim_transform_eventually) show "eventually (\<lambda>n. 1 + inverse (of_nat n :: 'a) = of_nat (Suc n) / of_nat n) sequentially" using eventually_gt_at_top[of "0::nat"] by eventually_elim (simp add: field_simps) have "(\<lambda>n. 1 + inverse (of_nat n) :: 'a) \<longlonglongrightarrow> 1 + 0" by (intro tendsto_add tendsto_const lim_inverse_n) then show "(\<lambda>n. 1 + inverse (of_nat n) :: 'a) \<longlonglongrightarrow> 1" by simp qed lemma LIMSEQ_n_over_Suc_n: "(\<lambda>n. of_nat n / of_nat (Suc n) :: 'a :: real_normed_field) \<longlonglongrightarrow> 1" proof (rule Lim_transform_eventually) show "eventually (\<lambda>n. inverse (of_nat (Suc n) / of_nat n :: 'a) = of_nat n / of_nat (Suc n)) sequentially" using eventually_gt_at_top[of "0::nat"] by eventually_elim (simp add: field_simps del: of_nat_Suc) have "(\<lambda>n. inverse (of_nat (Suc n) / of_nat n :: 'a)) \<longlonglongrightarrow> inverse 1" by (intro tendsto_inverse LIMSEQ_Suc_n_over_n) simp_all then show "(\<lambda>n. inverse (of_nat (Suc n) / of_nat n :: 'a)) \<longlonglongrightarrow> 1" by simp qed subsection \<open>Convergence on sequences\<close> lemma convergent_cong: assumes "eventually (\<lambda>x. f x = g x) sequentially" shows "convergent f \<longleftrightarrow> convergent g" unfolding convergent_def by (subst filterlim_cong[OF refl refl assms]) (rule refl) lemma convergent_Suc_iff: "convergent (\<lambda>n. f (Suc n)) \<longleftrightarrow> convergent f" by (auto simp: convergent_def filterlim_sequentially_Suc) lemma convergent_ignore_initial_segment: "convergent (\<lambda>n. f (n + m)) = convergent f" proof (induct m arbitrary: f) case 0 then show ?case by simp next case (Suc m) have "convergent (\<lambda>n. f (n + Suc m)) \<longleftrightarrow> convergent (\<lambda>n. f (Suc n + m))" by simp also have "\<dots> \<longleftrightarrow> convergent (\<lambda>n. f (n + m))" by (rule convergent_Suc_iff) also have "\<dots> \<longleftrightarrow> convergent f" by (rule Suc) finally show ?case . qed lemma convergent_add: fixes X Y :: "nat \<Rightarrow> 'a::topological_monoid_add" assumes "convergent (\<lambda>n. X n)" and "convergent (\<lambda>n. Y n)" shows "convergent (\<lambda>n. X n + Y n)" using assms unfolding convergent_def by (blast intro: tendsto_add) lemma convergent_sum: fixes X :: "'a \<Rightarrow> nat \<Rightarrow> 'b::topological_comm_monoid_add" shows "(\<And>i. i \<in> A \<Longrightarrow> convergent (\<lambda>n. X i n)) \<Longrightarrow> convergent (\<lambda>n. \<Sum>i\<in>A. X i n)" by (induct A rule: infinite_finite_induct) (simp_all add: convergent_const convergent_add) lemma (in bounded_linear) convergent: assumes "convergent (\<lambda>n. X n)" shows "convergent (\<lambda>n. f (X n))" using assms unfolding convergent_def by (blast intro: tendsto) lemma (in bounded_bilinear) convergent: assumes "convergent (\<lambda>n. X n)" and "convergent (\<lambda>n. Y n)" shows "convergent (\<lambda>n. X n ** Y n)" using assms unfolding convergent_def by (blast intro: tendsto) lemma convergent_minus_iff: fixes X :: "nat \<Rightarrow> 'a::topological_group_add" shows "convergent X \<longleftrightarrow> convergent (\<lambda>n. - X n)" unfolding convergent_def by (force dest: tendsto_minus) lemma convergent_diff: fixes X Y :: "nat \<Rightarrow> 'a::topological_group_add" assumes "convergent (\<lambda>n. X n)" assumes "convergent (\<lambda>n. Y n)" shows "convergent (\<lambda>n. X n - Y n)" using assms unfolding convergent_def by (blast intro: tendsto_diff) lemma convergent_norm: assumes "convergent f" shows "convergent (\<lambda>n. norm (f n))" proof - from assms have "f \<longlonglongrightarrow> lim f" by (simp add: convergent_LIMSEQ_iff) then have "(\<lambda>n. norm (f n)) \<longlonglongrightarrow> norm (lim f)" by (rule tendsto_norm) then show ?thesis by (auto simp: convergent_def) qed lemma convergent_of_real: "convergent f \<Longrightarrow> convergent (\<lambda>n. of_real (f n) :: 'a::real_normed_algebra_1)" unfolding convergent_def by (blast intro!: tendsto_of_real) lemma convergent_add_const_iff: "convergent (\<lambda>n. c + f n :: 'a::topological_ab_group_add) \<longleftrightarrow> convergent f" proof assume "convergent (\<lambda>n. c + f n)" from convergent_diff[OF this convergent_const[of c]] show "convergent f" by simp next assume "convergent f" from convergent_add[OF convergent_const[of c] this] show "convergent (\<lambda>n. c + f n)" by simp qed lemma convergent_add_const_right_iff: "convergent (\<lambda>n. f n + c :: 'a::topological_ab_group_add) \<longleftrightarrow> convergent f" using convergent_add_const_iff[of c f] by (simp add: add_ac) lemma convergent_diff_const_right_iff: "convergent (\<lambda>n. f n - c :: 'a::topological_ab_group_add) \<longleftrightarrow> convergent f" using convergent_add_const_right_iff[of f "-c"] by (simp add: add_ac) lemma convergent_mult: fixes X Y :: "nat \<Rightarrow> 'a::topological_semigroup_mult" assumes "convergent (\<lambda>n. X n)" and "convergent (\<lambda>n. Y n)" shows "convergent (\<lambda>n. X n * Y n)" using assms unfolding convergent_def by (blast intro: tendsto_mult) lemma convergent_mult_const_iff: assumes "c \<noteq> 0" shows "convergent (\<lambda>n. c * f n :: 'a::{field,topological_semigroup_mult}) \<longleftrightarrow> convergent f" proof assume "convergent (\<lambda>n. c * f n)" from assms convergent_mult[OF this convergent_const[of "inverse c"]] show "convergent f" by (simp add: field_simps) next assume "convergent f" from convergent_mult[OF convergent_const[of c] this] show "convergent (\<lambda>n. c * f n)" by simp qed lemma convergent_mult_const_right_iff: fixes c :: "'a::{field,topological_semigroup_mult}" assumes "c \<noteq> 0" shows "convergent (\<lambda>n. f n * c) \<longleftrightarrow> convergent f" using convergent_mult_const_iff[OF assms, of f] by (simp add: mult_ac) lemma convergent_imp_Bseq: "convergent f \<Longrightarrow> Bseq f" by (simp add: Cauchy_Bseq convergent_Cauchy) text \<open>A monotone sequence converges to its least upper bound.\<close> lemma LIMSEQ_incseq_SUP: fixes X :: "nat \<Rightarrow> 'a::{conditionally_complete_linorder,linorder_topology}" assumes u: "bdd_above (range X)" and X: "incseq X" shows "X \<longlonglongrightarrow> (SUP i. X i)" by (rule order_tendstoI) (auto simp: eventually_sequentially u less_cSUP_iff intro: X[THEN incseqD] less_le_trans cSUP_lessD[OF u]) lemma LIMSEQ_decseq_INF: fixes X :: "nat \<Rightarrow> 'a::{conditionally_complete_linorder, linorder_topology}" assumes u: "bdd_below (range X)" and X: "decseq X" shows "X \<longlonglongrightarrow> (INF i. X i)" by (rule order_tendstoI) (auto simp: eventually_sequentially u cINF_less_iff intro: X[THEN decseqD] le_less_trans less_cINF_D[OF u]) text \<open>Main monotonicity theorem.\<close> lemma Bseq_monoseq_convergent: "Bseq X \<Longrightarrow> monoseq X \<Longrightarrow> convergent X" for X :: "nat \<Rightarrow> real" by (auto simp: monoseq_iff convergent_def intro: LIMSEQ_decseq_INF LIMSEQ_incseq_SUP dest: Bseq_bdd_above Bseq_bdd_below) lemma Bseq_mono_convergent: "Bseq X \<Longrightarrow> (\<forall>m n. m \<le> n \<longrightarrow> X m \<le> X n) \<Longrightarrow> convergent X" for X :: "nat \<Rightarrow> real" by (auto intro!: Bseq_monoseq_convergent incseq_imp_monoseq simp: incseq_def) lemma monoseq_imp_convergent_iff_Bseq: "monoseq f \<Longrightarrow> convergent f \<longleftrightarrow> Bseq f" for f :: "nat \<Rightarrow> real" using Bseq_monoseq_convergent[of f] convergent_imp_Bseq[of f] by blast lemma Bseq_monoseq_convergent'_inc: fixes f :: "nat \<Rightarrow> real" shows "Bseq (\<lambda>n. f (n + M)) \<Longrightarrow> (\<And>m n. M \<le> m \<Longrightarrow> m \<le> n \<Longrightarrow> f m \<le> f n) \<Longrightarrow> convergent f" by (subst convergent_ignore_initial_segment [symmetric, of _ M]) (auto intro!: Bseq_monoseq_convergent simp: monoseq_def) lemma Bseq_monoseq_convergent'_dec: fixes f :: "nat \<Rightarrow> real" shows "Bseq (\<lambda>n. f (n + M)) \<Longrightarrow> (\<And>m n. M \<le> m \<Longrightarrow> m \<le> n \<Longrightarrow> f m \<ge> f n) \<Longrightarrow> convergent f" by (subst convergent_ignore_initial_segment [symmetric, of _ M]) (auto intro!: Bseq_monoseq_convergent simp: monoseq_def) lemma Cauchy_iff: "Cauchy X \<longleftrightarrow> (\<forall>e>0. \<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. norm (X m - X n) < e)" for X :: "nat \<Rightarrow> 'a::real_normed_vector" unfolding Cauchy_def dist_norm .. lemma CauchyI: "(\<And>e. 0 < e \<Longrightarrow> \<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. norm (X m - X n) < e) \<Longrightarrow> Cauchy X" for X :: "nat \<Rightarrow> 'a::real_normed_vector" by (simp add: Cauchy_iff) lemma CauchyD: "Cauchy X \<Longrightarrow> 0 < e \<Longrightarrow> \<exists>M. \<forall>m\<ge>M. \<forall>n\<ge>M. norm (X m - X n) < e" for X :: "nat \<Rightarrow> 'a::real_normed_vector" by (simp add: Cauchy_iff) lemma incseq_convergent: fixes X :: "nat \<Rightarrow> real" assumes "incseq X" and "\<forall>i. X i \<le> B" obtains L where "X \<longlonglongrightarrow> L" "\<forall>i. X i \<le> L" proof atomize_elim from incseq_bounded[OF assms] \<open>incseq X\<close> Bseq_monoseq_convergent[of X] obtain L where "X \<longlonglongrightarrow> L" by (auto simp: convergent_def monoseq_def incseq_def) with \<open>incseq X\<close> show "\<exists>L. X \<longlonglongrightarrow> L \<and> (\<forall>i. X i \<le> L)" by (auto intro!: exI[of _ L] incseq_le) qed lemma decseq_convergent: fixes X :: "nat \<Rightarrow> real" assumes "decseq X" and "\<forall>i. B \<le> X i" obtains L where "X \<longlonglongrightarrow> L" "\<forall>i. L \<le> X i" proof atomize_elim from decseq_bounded[OF assms] \<open>decseq X\<close> Bseq_monoseq_convergent[of X] obtain L where "X \<longlonglongrightarrow> L" by (auto simp: convergent_def monoseq_def decseq_def) with \<open>decseq X\<close> show "\<exists>L. X \<longlonglongrightarrow> L \<and> (\<forall>i. L \<le> X i)" by (auto intro!: exI[of _ L] decseq_ge) qed lemma monoseq_convergent: fixes X :: "nat \<Rightarrow> real" assumes X: "monoseq X" and B: "\<And>i. \<bar>X i\<bar> \<le> B" obtains L where "X \<longlonglongrightarrow> L" using X unfolding monoseq_iff proof assume "incseq X" show thesis using abs_le_D1 [OF B] incseq_convergent [OF \<open>incseq X\<close>] that by meson next assume "decseq X" show thesis using decseq_convergent [OF \<open>decseq X\<close>] that by (metis B abs_le_iff add.inverse_inverse neg_le_iff_le) qed subsection \<open>More about @{term filterlim} (thanks to Wenda Li)\<close> lemma filterlim_at_infinity_times: fixes f :: "'a \<Rightarrow> 'b::real_normed_field" assumes "filterlim f at_infinity F" "filterlim g at_infinity F" shows "filterlim (\<lambda>x. f x * g x) at_infinity F" proof - have "((\<lambda>x. inverse (f x) * inverse (g x)) \<longlongrightarrow> 0 * 0) F" by (intro tendsto_mult tendsto_inverse assms filterlim_compose[OF tendsto_inverse_0]) then have "filterlim (\<lambda>x. inverse (f x) * inverse (g x)) (at 0) F" unfolding filterlim_at using assms by (auto intro: filterlim_at_infinity_imp_eventually_ne tendsto_imp_eventually_ne eventually_conj) then show ?thesis by (subst filterlim_inverse_at_iff[symmetric]) simp_all qed lemma filterlim_at_top_at_bot[elim]: fixes f::"'a \<Rightarrow> 'b::unbounded_dense_linorder" and F::"'a filter" assumes top:"filterlim f at_top F" and bot: "filterlim f at_bot F" and "F\<noteq>bot" shows False proof - obtain c::'b where True by auto have "\<forall>\<^sub>F x in F. c < f x" using top unfolding filterlim_at_top_dense by auto moreover have "\<forall>\<^sub>F x in F. f x < c" using bot unfolding filterlim_at_bot_dense by auto ultimately have "\<forall>\<^sub>F x in F. c < f x \<and> f x < c" using eventually_conj by auto then have "\<forall>\<^sub>F x in F. False" by (auto elim:eventually_mono) then show False using \<open>F\<noteq>bot\<close> by auto qed lemma filterlim_at_top_nhds[elim]: fixes f::"'a \<Rightarrow> 'b::{unbounded_dense_linorder,order_topology}" and F::"'a filter" assumes top:"filterlim f at_top F" and tendsto: "(f \<longlongrightarrow> c) F" and "F\<noteq>bot" shows False proof - obtain c'::'b where "c'>c" using gt_ex by blast have "\<forall>\<^sub>F x in F. c' < f x" using top unfolding filterlim_at_top_dense by auto moreover have "\<forall>\<^sub>F x in F. f x < c'" using order_tendstoD[OF tendsto,of c'] \<open>c'>c\<close> by auto ultimately have "\<forall>\<^sub>F x in F. c' < f x \<and> f x < c'" using eventually_conj by auto then have "\<forall>\<^sub>F x in F. False" by (auto elim:eventually_mono) then show False using \<open>F\<noteq>bot\<close> by auto qed lemma filterlim_at_bot_nhds[elim]: fixes f::"'a \<Rightarrow> 'b::{unbounded_dense_linorder,order_topology}" and F::"'a filter" assumes top:"filterlim f at_bot F" and tendsto: "(f \<longlongrightarrow> c) F" and "F\<noteq>bot" shows False proof - obtain c'::'b where "c'<c" using lt_ex by blast have "\<forall>\<^sub>F x in F. c' > f x" using top unfolding filterlim_at_bot_dense by auto moreover have "\<forall>\<^sub>F x in F. f x > c'" using order_tendstoD[OF tendsto,of c'] \<open>c'<c\<close> by auto ultimately have "\<forall>\<^sub>F x in F. c' < f x \<and> f x < c'" using eventually_conj by auto then have "\<forall>\<^sub>F x in F. False" by (auto elim:eventually_mono) then show False using \<open>F\<noteq>bot\<close> by auto qed lemma eventually_times_inverse_1: fixes f::"'a \<Rightarrow> 'b::{field,t2_space}" assumes "(f \<longlongrightarrow> c) F" "c\<noteq>0" shows "\<forall>\<^sub>F x in F. inverse (f x) * f x = 1" by (smt (verit) assms eventually_mono mult.commute right_inverse tendsto_imp_eventually_ne) lemma filterlim_at_infinity_divide_iff: fixes f::"'a \<Rightarrow> 'b::real_normed_field" assumes "(f \<longlongrightarrow> c) F" "c\<noteq>0" shows "(LIM x F. f x / g x :> at_infinity) \<longleftrightarrow> (LIM x F. g x :> at 0)" proof assume "LIM x F. f x / g x :> at_infinity" then have "LIM x F. inverse (f x) * (f x / g x) :> at_infinity" using assms tendsto_inverse tendsto_mult_filterlim_at_infinity by fastforce then have "LIM x F. inverse (g x) :> at_infinity" apply (elim filterlim_mono_eventually) using eventually_times_inverse_1[OF assms] by (auto elim:eventually_mono simp add:field_simps) then show "filterlim g (at 0) F" using filterlim_inverse_at_iff[symmetric] by force next assume "filterlim g (at 0) F" then have "filterlim (\<lambda>x. inverse (g x)) at_infinity F" using filterlim_compose filterlim_inverse_at_infinity by blast then have "LIM x F. f x * inverse (g x) :> at_infinity" using tendsto_mult_filterlim_at_infinity[OF assms, of "\<lambda>x. inverse(g x)"] by simp then show "LIM x F. f x / g x :> at_infinity" by (simp add: divide_inverse) qed lemma filterlim_tendsto_pos_mult_at_top_iff: fixes f::"'a \<Rightarrow> real" assumes "(f \<longlongrightarrow> c) F" and "0 < c" shows "(LIM x F. (f x * g x) :> at_top) \<longleftrightarrow> (LIM x F. g x :> at_top)" proof assume "filterlim g at_top F" then show "LIM x F. f x * g x :> at_top" using filterlim_tendsto_pos_mult_at_top[OF assms] by auto next assume asm:"LIM x F. f x * g x :> at_top" have "((\<lambda>x. inverse (f x)) \<longlongrightarrow> inverse c) F" using tendsto_inverse[OF assms(1)] \<open>0<c\<close> by auto moreover have "inverse c >0" using assms(2) by auto ultimately have "LIM x F. inverse (f x) * (f x * g x) :> at_top" using filterlim_tendsto_pos_mult_at_top[OF _ _ asm,of "\<lambda>x. inverse (f x)" "inverse c"] by auto then show "LIM x F. g x :> at_top" apply (elim filterlim_mono_eventually) apply simp_all[2] using eventually_times_inverse_1[OF assms(1)] \<open>c>0\<close> eventually_mono by fastforce qed lemma filterlim_tendsto_pos_mult_at_bot_iff: fixes c :: real assumes "(f \<longlongrightarrow> c) F" "0 < c" shows "(LIM x F. f x * g x :> at_bot) \<longleftrightarrow> filterlim g at_bot F" using filterlim_tendsto_pos_mult_at_top_iff[OF assms(1,2), of "\<lambda>x. - g x"] unfolding filterlim_uminus_at_bot by simp lemma filterlim_tendsto_neg_mult_at_top_iff: fixes f::"'a \<Rightarrow> real" assumes "(f \<longlongrightarrow> c) F" and "c < 0" shows "(LIM x F. (f x * g x) :> at_top) \<longleftrightarrow> (LIM x F. g x :> at_bot)" proof - have "(LIM x F. f x * g x :> at_top) = (LIM x F. - g x :> at_top)" apply (rule filterlim_tendsto_pos_mult_at_top_iff[of "\<lambda>x. - f x" "-c" F "\<lambda>x. - g x", simplified]) using assms by (auto intro: tendsto_intros ) also have "... = (LIM x F. g x :> at_bot)" using filterlim_uminus_at_bot[symmetric] by auto finally show ?thesis . qed lemma filterlim_tendsto_neg_mult_at_bot_iff: fixes c :: real assumes "(f \<longlongrightarrow> c) F" "0 > c" shows "(LIM x F. f x * g x :> at_bot) \<longleftrightarrow> filterlim g at_top F" using filterlim_tendsto_neg_mult_at_top_iff[OF assms(1,2), of "\<lambda>x. - g x"] unfolding filterlim_uminus_at_top by simp subsection \<open>Power Sequences\<close> lemma Bseq_realpow: "0 \<le> x \<Longrightarrow> x \<le> 1 \<Longrightarrow> Bseq (\<lambda>n. x ^ n)" for x :: real by (metis decseq_bounded decseq_def power_decreasing zero_le_power) lemma monoseq_realpow: "0 \<le> x \<Longrightarrow> x \<le> 1 \<Longrightarrow> monoseq (\<lambda>n. x ^ n)" for x :: real using monoseq_def power_decreasing by blast lemma convergent_realpow: "0 \<le> x \<Longrightarrow> x \<le> 1 \<Longrightarrow> convergent (\<lambda>n. x ^ n)" for x :: real by (blast intro!: Bseq_monoseq_convergent Bseq_realpow monoseq_realpow) lemma LIMSEQ_inverse_realpow_zero: "1 < x \<Longrightarrow> (\<lambda>n. inverse (x ^ n)) \<longlonglongrightarrow> 0" for x :: real by (rule filterlim_compose[OF tendsto_inverse_0 filterlim_realpow_sequentially_gt1]) simp lemma LIMSEQ_realpow_zero: fixes x :: real assumes "0 \<le> x" "x < 1" shows "(\<lambda>n. x ^ n) \<longlonglongrightarrow> 0" proof (cases "x = 0") case False with \<open>0 \<le> x\<close> have "1 < inverse x" using \<open>x < 1\<close> by (simp add: one_less_inverse) then have "(\<lambda>n. inverse (inverse x ^ n)) \<longlonglongrightarrow> 0" by (rule LIMSEQ_inverse_realpow_zero) then show ?thesis by (simp add: power_inverse) next case True show ?thesis by (rule LIMSEQ_imp_Suc) (simp add: True) qed lemma LIMSEQ_power_zero [tendsto_intros]: "norm x < 1 \<Longrightarrow> (\<lambda>n. x ^ n) \<longlonglongrightarrow> 0" for x :: "'a::real_normed_algebra_1" apply (drule LIMSEQ_realpow_zero [OF norm_ge_zero]) by (simp add: Zfun_le norm_power_ineq tendsto_Zfun_iff) lemma LIMSEQ_divide_realpow_zero: "1 < x \<Longrightarrow> (\<lambda>n. a / (x ^ n) :: real) \<longlonglongrightarrow> 0" by (rule tendsto_divide_0 [OF tendsto_const filterlim_realpow_sequentially_gt1]) simp lemma tendsto_power_zero: fixes x::"'a::real_normed_algebra_1" assumes "filterlim f at_top F" assumes "norm x < 1" shows "((\<lambda>y. x ^ (f y)) \<longlongrightarrow> 0) F" proof (rule tendstoI) fix e::real assume "0 < e" from tendstoD[OF LIMSEQ_power_zero[OF \<open>norm x < 1\<close>] \<open>0 < e\<close>] have "\<forall>\<^sub>F xa in sequentially. norm (x ^ xa) < e" by simp then obtain N where N: "norm (x ^ n) < e" if "n \<ge> N" for n by (auto simp: eventually_sequentially) have "\<forall>\<^sub>F i in F. f i \<ge> N" using \<open>filterlim f sequentially F\<close> by (simp add: filterlim_at_top) then show "\<forall>\<^sub>F i in F. dist (x ^ f i) 0 < e" by eventually_elim (auto simp: N) qed text \<open>Limit of \<^term>\<open>c^n\<close> for \<^term>\<open>\<bar>c\<bar> < 1\<close>.\<close> lemma LIMSEQ_abs_realpow_zero: "\<bar>c\<bar> < 1 \<Longrightarrow> (\<lambda>n. \<bar>c\<bar> ^ n :: real) \<longlonglongrightarrow> 0" by (rule LIMSEQ_realpow_zero [OF abs_ge_zero]) lemma LIMSEQ_abs_realpow_zero2: "\<bar>c\<bar> < 1 \<Longrightarrow> (\<lambda>n. c ^ n :: real) \<longlonglongrightarrow> 0" by (rule LIMSEQ_power_zero) simp subsection \<open>Limits of Functions\<close> lemma LIM_eq: "f \<midarrow>a\<rightarrow> L = (\<forall>r>0. \<exists>s>0. \<forall>x. x \<noteq> a \<and> norm (x - a) < s \<longrightarrow> norm (f x - L) < r)" for a :: "'a::real_normed_vector" and L :: "'b::real_normed_vector" by (simp add: LIM_def dist_norm) lemma LIM_I: "(\<And>r. 0 < r \<Longrightarrow> \<exists>s>0. \<forall>x. x \<noteq> a \<and> norm (x - a) < s \<longrightarrow> norm (f x - L) < r) \<Longrightarrow> f \<midarrow>a\<rightarrow> L" for a :: "'a::real_normed_vector" and L :: "'b::real_normed_vector" by (simp add: LIM_eq) lemma LIM_D: "f \<midarrow>a\<rightarrow> L \<Longrightarrow> 0 < r \<Longrightarrow> \<exists>s>0.\<forall>x. x \<noteq> a \<and> norm (x - a) < s \<longrightarrow> norm (f x - L) < r" for a :: "'a::real_normed_vector" and L :: "'b::real_normed_vector" by (simp add: LIM_eq) lemma LIM_offset: "f \<midarrow>a\<rightarrow> L \<Longrightarrow> (\<lambda>x. f (x + k)) \<midarrow>(a - k)\<rightarrow> L" for a :: "'a::real_normed_vector" by (simp add: filtermap_at_shift[symmetric, of a k] filterlim_def filtermap_filtermap) lemma LIM_offset_zero: "f \<midarrow>a\<rightarrow> L \<Longrightarrow> (\<lambda>h. f (a + h)) \<midarrow>0\<rightarrow> L" for a :: "'a::real_normed_vector" by (drule LIM_offset [where k = a]) (simp add: add.commute) lemma LIM_offset_zero_cancel: "(\<lambda>h. f (a + h)) \<midarrow>0\<rightarrow> L \<Longrightarrow> f \<midarrow>a\<rightarrow> L" for a :: "'a::real_normed_vector" by (drule LIM_offset [where k = "- a"]) simp lemma LIM_offset_zero_iff: "NO_MATCH 0 a \<Longrightarrow> f \<midarrow>a\<rightarrow> L \<longleftrightarrow> (\<lambda>h. f (a + h)) \<midarrow>0\<rightarrow> L" for f :: "'a :: real_normed_vector \<Rightarrow> _" using LIM_offset_zero_cancel[of f a L] LIM_offset_zero[of f L a] by auto lemma tendsto_offset_zero_iff: fixes f :: "'a :: real_normed_vector \<Rightarrow> _" assumes " NO_MATCH 0 a" "a \<in> S" "open S" shows "(f \<longlongrightarrow> L) (at a within S) \<longleftrightarrow> ((\<lambda>h. f (a + h)) \<longlongrightarrow> L) (at 0)" using assms by (simp add: tendsto_within_open_NO_MATCH LIM_offset_zero_iff) lemma LIM_zero: "(f \<longlongrightarrow> l) F \<Longrightarrow> ((\<lambda>x. f x - l) \<longlongrightarrow> 0) F" for f :: "'a \<Rightarrow> 'b::real_normed_vector" unfolding tendsto_iff dist_norm by simp lemma LIM_zero_cancel: fixes f :: "'a \<Rightarrow> 'b::real_normed_vector" shows "((\<lambda>x. f x - l) \<longlongrightarrow> 0) F \<Longrightarrow> (f \<longlongrightarrow> l) F" unfolding tendsto_iff dist_norm by simp lemma LIM_zero_iff: "((\<lambda>x. f x - l) \<longlongrightarrow> 0) F = (f \<longlongrightarrow> l) F" for f :: "'a \<Rightarrow> 'b::real_normed_vector" unfolding tendsto_iff dist_norm by simp lemma LIM_imp_LIM: fixes f :: "'a::topological_space \<Rightarrow> 'b::real_normed_vector" fixes g :: "'a::topological_space \<Rightarrow> 'c::real_normed_vector" assumes f: "f \<midarrow>a\<rightarrow> l" and le: "\<And>x. x \<noteq> a \<Longrightarrow> norm (g x - m) \<le> norm (f x - l)" shows "g \<midarrow>a\<rightarrow> m" by (rule metric_LIM_imp_LIM [OF f]) (simp add: dist_norm le) lemma LIM_equal2: fixes f g :: "'a::real_normed_vector \<Rightarrow> 'b::topological_space" assumes "0 < R" and "\<And>x. x \<noteq> a \<Longrightarrow> norm (x - a) < R \<Longrightarrow> f x = g x" shows "g \<midarrow>a\<rightarrow> l \<Longrightarrow> f \<midarrow>a\<rightarrow> l" by (rule metric_LIM_equal2 [OF _ assms]) (simp_all add: dist_norm) lemma LIM_compose2: fixes a :: "'a::real_normed_vector" assumes f: "f \<midarrow>a\<rightarrow> b" and g: "g \<midarrow>b\<rightarrow> c" and inj: "\<exists>d>0. \<forall>x. x \<noteq> a \<and> norm (x - a) < d \<longrightarrow> f x \<noteq> b" shows "(\<lambda>x. g (f x)) \<midarrow>a\<rightarrow> c" by (rule metric_LIM_compose2 [OF f g inj [folded dist_norm]]) lemma real_LIM_sandwich_zero: fixes f g :: "'a::topological_space \<Rightarrow> real" assumes f: "f \<midarrow>a\<rightarrow> 0" and 1: "\<And>x. x \<noteq> a \<Longrightarrow> 0 \<le> g x" and 2: "\<And>x. x \<noteq> a \<Longrightarrow> g x \<le> f x" shows "g \<midarrow>a\<rightarrow> 0" proof (rule LIM_imp_LIM [OF f]) (* FIXME: use tendsto_sandwich *) fix x assume x: "x \<noteq> a" with 1 have "norm (g x - 0) = g x" by simp also have "g x \<le> f x" by (rule 2 [OF x]) also have "f x \<le> \<bar>f x\<bar>" by (rule abs_ge_self) also have "\<bar>f x\<bar> = norm (f x - 0)" by simp finally show "norm (g x - 0) \<le> norm (f x - 0)" . qed subsection \<open>Continuity\<close> lemma LIM_isCont_iff: "(f \<midarrow>a\<rightarrow> f a) = ((\<lambda>h. f (a + h)) \<midarrow>0\<rightarrow> f a)" for f :: "'a::real_normed_vector \<Rightarrow> 'b::topological_space" by (rule iffI [OF LIM_offset_zero LIM_offset_zero_cancel]) lemma isCont_iff: "isCont f x = (\<lambda>h. f (x + h)) \<midarrow>0\<rightarrow> f x" for f :: "'a::real_normed_vector \<Rightarrow> 'b::topological_space" by (simp add: isCont_def LIM_isCont_iff) lemma isCont_LIM_compose2: fixes a :: "'a::real_normed_vector" assumes f [unfolded isCont_def]: "isCont f a" and g: "g \<midarrow>f a\<rightarrow> l" and inj: "\<exists>d>0. \<forall>x. x \<noteq> a \<and> norm (x - a) < d \<longrightarrow> f x \<noteq> f a" shows "(\<lambda>x. g (f x)) \<midarrow>a\<rightarrow> l" by (rule LIM_compose2 [OF f g inj]) lemma isCont_norm [simp]: "isCont f a \<Longrightarrow> isCont (\<lambda>x. norm (f x)) a" for f :: "'a::t2_space \<Rightarrow> 'b::real_normed_vector" by (fact continuous_norm) lemma isCont_rabs [simp]: "isCont f a \<Longrightarrow> isCont (\<lambda>x. \<bar>f x\<bar>) a" for f :: "'a::t2_space \<Rightarrow> real" by (fact continuous_rabs) lemma isCont_add [simp]: "isCont f a \<Longrightarrow> isCont g a \<Longrightarrow> isCont (\<lambda>x. f x + g x) a" for f :: "'a::t2_space \<Rightarrow> 'b::topological_monoid_add" by (fact continuous_add) lemma isCont_minus [simp]: "isCont f a \<Longrightarrow> isCont (\<lambda>x. - f x) a" for f :: "'a::t2_space \<Rightarrow> 'b::real_normed_vector" by (fact continuous_minus) lemma isCont_diff [simp]: "isCont f a \<Longrightarrow> isCont g a \<Longrightarrow> isCont (\<lambda>x. f x - g x) a" for f :: "'a::t2_space \<Rightarrow> 'b::real_normed_vector" by (fact continuous_diff) lemma isCont_mult [simp]: "isCont f a \<Longrightarrow> isCont g a \<Longrightarrow> isCont (\<lambda>x. f x * g x) a" for f g :: "'a::t2_space \<Rightarrow> 'b::real_normed_algebra" by (fact continuous_mult) lemma (in bounded_linear) isCont: "isCont g a \<Longrightarrow> isCont (\<lambda>x. f (g x)) a" by (fact continuous) lemma (in bounded_bilinear) isCont: "isCont f a \<Longrightarrow> isCont g a \<Longrightarrow> isCont (\<lambda>x. f x ** g x) a" by (fact continuous) lemmas isCont_scaleR [simp] = bounded_bilinear.isCont [OF bounded_bilinear_scaleR] lemmas isCont_of_real [simp] = bounded_linear.isCont [OF bounded_linear_of_real] lemma isCont_power [simp]: "isCont f a \<Longrightarrow> isCont (\<lambda>x. f x ^ n) a" for f :: "'a::t2_space \<Rightarrow> 'b::{power,real_normed_algebra}" by (fact continuous_power) lemma isCont_sum [simp]: "\<forall>i\<in>A. isCont (f i) a \<Longrightarrow> isCont (\<lambda>x. \<Sum>i\<in>A. f i x) a" for f :: "'a \<Rightarrow> 'b::t2_space \<Rightarrow> 'c::topological_comm_monoid_add" by (auto intro: continuous_sum) subsection \<open>Uniform Continuity\<close> lemma uniformly_continuous_on_def: fixes f :: "'a::metric_space \<Rightarrow> 'b::metric_space" shows "uniformly_continuous_on s f \<longleftrightarrow> (\<forall>e>0. \<exists>d>0. \<forall>x\<in>s. \<forall>x'\<in>s. dist x' x < d \<longrightarrow> dist (f x') (f x) < e)" unfolding uniformly_continuous_on_uniformity uniformity_dist filterlim_INF filterlim_principal eventually_inf_principal by (force simp: Ball_def uniformity_dist[symmetric] eventually_uniformity_metric) abbreviation isUCont :: "['a::metric_space \<Rightarrow> 'b::metric_space] \<Rightarrow> bool" where "isUCont f \<equiv> uniformly_continuous_on UNIV f" lemma isUCont_def: "isUCont f \<longleftrightarrow> (\<forall>r>0. \<exists>s>0. \<forall>x y. dist x y < s \<longrightarrow> dist (f x) (f y) < r)" by (auto simp: uniformly_continuous_on_def dist_commute) lemma isUCont_isCont: "isUCont f \<Longrightarrow> isCont f x" by (drule uniformly_continuous_imp_continuous) (simp add: continuous_on_eq_continuous_at) lemma uniformly_continuous_on_Cauchy: fixes f :: "'a::metric_space \<Rightarrow> 'b::metric_space" assumes "uniformly_continuous_on S f" "Cauchy X" "\<And>n. X n \<in> S" shows "Cauchy (\<lambda>n. f (X n))" using assms unfolding uniformly_continuous_on_def by (meson Cauchy_def) lemma isUCont_Cauchy: "isUCont f \<Longrightarrow> Cauchy X \<Longrightarrow> Cauchy (\<lambda>n. f (X n))" by (rule uniformly_continuous_on_Cauchy[where S=UNIV and f=f]) simp_all lemma uniformly_continuous_imp_Cauchy_continuous: fixes f :: "'a::metric_space \<Rightarrow> 'b::metric_space" shows "\<lbrakk>uniformly_continuous_on S f; Cauchy \<sigma>; \<And>n. (\<sigma> n) \<in> S\<rbrakk> \<Longrightarrow> Cauchy(f \<circ> \<sigma>)" by (simp add: uniformly_continuous_on_def Cauchy_def) meson lemma (in bounded_linear) isUCont: "isUCont f" unfolding isUCont_def dist_norm proof (intro allI impI) fix r :: real assume r: "0 < r" obtain K where K: "0 < K" and norm_le: "norm (f x) \<le> norm x * K" for x using pos_bounded by blast show "\<exists>s>0. \<forall>x y. norm (x - y) < s \<longrightarrow> norm (f x - f y) < r" proof (rule exI, safe) from r K show "0 < r / K" by simp next fix x y :: 'a assume xy: "norm (x - y) < r / K" have "norm (f x - f y) = norm (f (x - y))" by (simp only: diff) also have "\<dots> \<le> norm (x - y) * K" by (rule norm_le) also from K xy have "\<dots> < r" by (simp only: pos_less_divide_eq) finally show "norm (f x - f y) < r" . qed qed lemma (in bounded_linear) Cauchy: "Cauchy X \<Longrightarrow> Cauchy (\<lambda>n. f (X n))" by (rule isUCont [THEN isUCont_Cauchy]) lemma LIM_less_bound: fixes f :: "real \<Rightarrow> real" assumes ev: "b < x" "\<forall> x' \<in> { b <..< x}. 0 \<le> f x'" and "isCont f x" shows "0 \<le> f x" proof (rule tendsto_lowerbound) show "(f \<longlongrightarrow> f x) (at_left x)" using \<open>isCont f x\<close> by (simp add: filterlim_at_split isCont_def) show "eventually (\<lambda>x. 0 \<le> f x) (at_left x)" using ev by (auto simp: eventually_at dist_real_def intro!: exI[of _ "x - b"]) qed simp subsection \<open>Nested Intervals and Bisection -- Needed for Compactness\<close> lemma nested_sequence_unique: assumes "\<forall>n. f n \<le> f (Suc n)" "\<forall>n. g (Suc n) \<le> g n" "\<forall>n. f n \<le> g n" "(\<lambda>n. f n - g n) \<longlonglongrightarrow> 0" shows "\<exists>l::real. ((\<forall>n. f n \<le> l) \<and> f \<longlonglongrightarrow> l) \<and> ((\<forall>n. l \<le> g n) \<and> g \<longlonglongrightarrow> l)" proof - have "incseq f" unfolding incseq_Suc_iff by fact have "decseq g" unfolding decseq_Suc_iff by fact have "f n \<le> g 0" for n proof - from \<open>decseq g\<close> have "g n \<le> g 0" by (rule decseqD) simp with \<open>\<forall>n. f n \<le> g n\<close>[THEN spec, of n] show ?thesis by auto qed then obtain u where "f \<longlonglongrightarrow> u" "\<forall>i. f i \<le> u" using incseq_convergent[OF \<open>incseq f\<close>] by auto moreover have "f 0 \<le> g n" for n proof - from \<open>incseq f\<close> have "f 0 \<le> f n" by (rule incseqD) simp with \<open>\<forall>n. f n \<le> g n\<close>[THEN spec, of n] show ?thesis by simp qed then obtain l where "g \<longlonglongrightarrow> l" "\<forall>i. l \<le> g i" using decseq_convergent[OF \<open>decseq g\<close>] by auto moreover note LIMSEQ_unique[OF assms(4) tendsto_diff[OF \<open>f \<longlonglongrightarrow> u\<close> \<open>g \<longlonglongrightarrow> l\<close>]] ultimately show ?thesis by auto qed lemma Bolzano[consumes 1, case_names trans local]: fixes P :: "real \<Rightarrow> real \<Rightarrow> bool" assumes [arith]: "a \<le> b" and trans: "\<And>a b c. P a b \<Longrightarrow> P b c \<Longrightarrow> a \<le> b \<Longrightarrow> b \<le> c \<Longrightarrow> P a c" and local: "\<And>x. a \<le> x \<Longrightarrow> x \<le> b \<Longrightarrow> \<exists>d>0. \<forall>a b. a \<le> x \<and> x \<le> b \<and> b - a < d \<longrightarrow> P a b" shows "P a b" proof - define bisect where "bisect \<equiv> \<lambda>(x,y). if P x ((x+y) / 2) then ((x+y)/2, y) else (x, (x+y)/2)" define l u where "l n \<equiv> fst ((bisect^^n)(a,b))" and "u n \<equiv> snd ((bisect^^n)(a,b))" for n have l[simp]: "l 0 = a" "\<And>n. l (Suc n) = (if P (l n) ((l n + u n) / 2) then (l n + u n) / 2 else l n)" and u[simp]: "u 0 = b" "\<And>n. u (Suc n) = (if P (l n) ((l n + u n) / 2) then u n else (l n + u n) / 2)" by (simp_all add: l_def u_def bisect_def split: prod.split) have [simp]: "l n \<le> u n" for n by (induct n) auto have "\<exists>x. ((\<forall>n. l n \<le> x) \<and> l \<longlonglongrightarrow> x) \<and> ((\<forall>n. x \<le> u n) \<and> u \<longlonglongrightarrow> x)" proof (safe intro!: nested_sequence_unique) show "l n \<le> l (Suc n)" "u (Suc n) \<le> u n" for n by (induct n) auto next have "l n - u n = (a - b) / 2^n" for n by (induct n) (auto simp: field_simps) then show "(\<lambda>n. l n - u n) \<longlonglongrightarrow> 0" by (simp add: LIMSEQ_divide_realpow_zero) qed fact then obtain x where x: "\<And>n. l n \<le> x" "\<And>n. x \<le> u n" and "l \<longlonglongrightarrow> x" "u \<longlonglongrightarrow> x" by auto obtain d where "0 < d" and d: "a \<le> x \<Longrightarrow> x \<le> b \<Longrightarrow> b - a < d \<Longrightarrow> P a b" for a b using \<open>l 0 \<le> x\<close> \<open>x \<le> u 0\<close> local[of x] by auto show "P a b" proof (rule ccontr) assume "\<not> P a b" have "\<not> P (l n) (u n)" for n proof (induct n) case 0 then show ?case by (simp add: \<open>\<not> P a b\<close>) next case (Suc n) with trans[of "l n" "(l n + u n) / 2" "u n"] show ?case by auto qed moreover { have "eventually (\<lambda>n. x - d / 2 < l n) sequentially" using \<open>0 < d\<close> \<open>l \<longlonglongrightarrow> x\<close> by (intro order_tendstoD[of _ x]) auto moreover have "eventually (\<lambda>n. u n < x + d / 2) sequentially" using \<open>0 < d\<close> \<open>u \<longlonglongrightarrow> x\<close> by (intro order_tendstoD[of _ x]) auto ultimately have "eventually (\<lambda>n. P (l n) (u n)) sequentially" proof eventually_elim case (elim n) from add_strict_mono[OF this] have "u n - l n < d" by simp with x show "P (l n) (u n)" by (rule d) qed } ultimately show False by simp qed qed lemma compact_Icc[simp, intro]: "compact {a .. b::real}" proof (cases "a \<le> b", rule compactI) fix C assume C: "a \<le> b" "\<forall>t\<in>C. open t" "{a..b} \<subseteq> \<Union>C" define T where "T = {a .. b}" from C(1,3) show "\<exists>C'\<subseteq>C. finite C' \<and> {a..b} \<subseteq> \<Union>C'" proof (induct rule: Bolzano) case (trans a b c) then have *: "{a..c} = {a..b} \<union> {b..c}" by auto with trans obtain C1 C2 where "C1\<subseteq>C" "finite C1" "{a..b} \<subseteq> \<Union>C1" "C2\<subseteq>C" "finite C2" "{b..c} \<subseteq> \<Union>C2" by auto with trans show ?case unfolding * by (intro exI[of _ "C1 \<union> C2"]) auto next case (local x) with C have "x \<in> \<Union>C" by auto with C(2) obtain c where "x \<in> c" "open c" "c \<in> C" by auto then obtain e where "0 < e" "{x - e <..< x + e} \<subseteq> c" by (auto simp: open_dist dist_real_def subset_eq Ball_def abs_less_iff) with \<open>c \<in> C\<close> show ?case by (safe intro!: exI[of _ "e/2"] exI[of _ "{c}"]) auto qed qed simp lemma continuous_image_closed_interval: fixes a b and f :: "real \<Rightarrow> real" defines "S \<equiv> {a..b}" assumes "a \<le> b" and f: "continuous_on S f" shows "\<exists>c d. f`S = {c..d} \<and> c \<le> d" proof - have S: "compact S" "S \<noteq> {}" using \<open>a \<le> b\<close> by (auto simp: S_def) obtain c where "c \<in> S" "\<forall>d\<in>S. f d \<le> f c" using continuous_attains_sup[OF S f] by auto moreover obtain d where "d \<in> S" "\<forall>c\<in>S. f d \<le> f c" using continuous_attains_inf[OF S f] by auto moreover have "connected (f`S)" using connected_continuous_image[OF f] connected_Icc by (auto simp: S_def) ultimately have "f ` S = {f d .. f c} \<and> f d \<le> f c" by (auto simp: connected_iff_interval) then show ?thesis by auto qed lemma open_Collect_positive: fixes f :: "'a::topological_space \<Rightarrow> real" assumes f: "continuous_on s f" shows "\<exists>A. open A \<and> A \<inter> s = {x\<in>s. 0 < f x}" using continuous_on_open_invariant[THEN iffD1, OF f, rule_format, of "{0 <..}"] by (auto simp: Int_def field_simps) lemma open_Collect_less_Int: fixes f g :: "'a::topological_space \<Rightarrow> real" assumes f: "continuous_on s f" and g: "continuous_on s g" shows "\<exists>A. open A \<and> A \<inter> s = {x\<in>s. f x < g x}" using open_Collect_positive[OF continuous_on_diff[OF g f]] by (simp add: field_simps) subsection \<open>Boundedness of continuous functions\<close> text\<open>By bisection, function continuous on closed interval is bounded above\<close> lemma isCont_eq_Ub: fixes f :: "real \<Rightarrow> 'a::linorder_topology" shows "a \<le> b \<Longrightarrow> \<forall>x::real. a \<le> x \<and> x \<le> b \<longrightarrow> isCont f x \<Longrightarrow> \<exists>M. (\<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> f x \<le> M) \<and> (\<exists>x. a \<le> x \<and> x \<le> b \<and> f x = M)" using continuous_attains_sup[of "{a..b}" f] by (auto simp: continuous_at_imp_continuous_on Ball_def Bex_def) lemma isCont_eq_Lb: fixes f :: "real \<Rightarrow> 'a::linorder_topology" shows "a \<le> b \<Longrightarrow> \<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> isCont f x \<Longrightarrow> \<exists>M. (\<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> M \<le> f x) \<and> (\<exists>x. a \<le> x \<and> x \<le> b \<and> f x = M)" using continuous_attains_inf[of "{a..b}" f] by (auto simp: continuous_at_imp_continuous_on Ball_def Bex_def) lemma isCont_bounded: fixes f :: "real \<Rightarrow> 'a::linorder_topology" shows "a \<le> b \<Longrightarrow> \<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> isCont f x \<Longrightarrow> \<exists>M. \<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> f x \<le> M" using isCont_eq_Ub[of a b f] by auto lemma isCont_has_Ub: fixes f :: "real \<Rightarrow> 'a::linorder_topology" shows "a \<le> b \<Longrightarrow> \<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> isCont f x \<Longrightarrow> \<exists>M. (\<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> f x \<le> M) \<and> (\<forall>N. N < M \<longrightarrow> (\<exists>x. a \<le> x \<and> x \<le> b \<and> N < f x))" using isCont_eq_Ub[of a b f] by auto lemma isCont_Lb_Ub: fixes f :: "real \<Rightarrow> real" assumes "a \<le> b" "\<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> isCont f x" shows "\<exists>L M. (\<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> L \<le> f x \<and> f x \<le> M) \<and> (\<forall>y. L \<le> y \<and> y \<le> M \<longrightarrow> (\<exists>x. a \<le> x \<and> x \<le> b \<and> (f x = y)))" proof - obtain M where M: "a \<le> M" "M \<le> b" "\<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> f x \<le> f M" using isCont_eq_Ub[OF assms] by auto obtain L where L: "a \<le> L" "L \<le> b" "\<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> f L \<le> f x" using isCont_eq_Lb[OF assms] by auto have "(\<forall>x. a \<le> x \<and> x \<le> b \<longrightarrow> f L \<le> f x \<and> f x \<le> f M)" using M L by simp moreover have "(\<forall>y. f L \<le> y \<and> y \<le> f M \<longrightarrow> (\<exists>x\<ge>a. x \<le> b \<and> f x = y))" proof (cases "L \<le> M") case True then show ?thesis using IVT[of f L _ M] M L assms by (metis order.trans) next case False then show ?thesis using IVT2[of f L _ M] by (metis L(2) M(1) assms(2) le_cases order.trans) qed ultimately show ?thesis by blast qed text \<open>Continuity of inverse function.\<close> lemma isCont_inverse_function: fixes f g :: "real \<Rightarrow> real" assumes d: "0 < d" and inj: "\<And>z. \<bar>z-x\<bar> \<le> d \<Longrightarrow> g (f z) = z" and cont: "\<And>z. \<bar>z-x\<bar> \<le> d \<Longrightarrow> isCont f z" shows "isCont g (f x)" proof - let ?A = "f (x - d)" let ?B = "f (x + d)" let ?D = "{x - d..x + d}" have f: "continuous_on ?D f" using cont by (intro continuous_at_imp_continuous_on ballI) auto then have g: "continuous_on (f`?D) g" using inj by (intro continuous_on_inv) auto from d f have "{min ?A ?B <..< max ?A ?B} \<subseteq> f ` ?D" by (intro connected_contains_Ioo connected_continuous_image) (auto split: split_min split_max) with g have "continuous_on {min ?A ?B <..< max ?A ?B} g" by (rule continuous_on_subset) moreover have "(?A < f x \<and> f x < ?B) \<or> (?B < f x \<and> f x < ?A)" using d inj by (intro continuous_inj_imp_mono[OF _ _ f] inj_on_imageI2[of g, OF inj_onI]) auto then have "f x \<in> {min ?A ?B <..< max ?A ?B}" by auto ultimately show ?thesis by (simp add: continuous_on_eq_continuous_at) qed lemma isCont_inverse_function2: fixes f g :: "real \<Rightarrow> real" shows "\<lbrakk>a < x; x < b; \<And>z. \<lbrakk>a \<le> z; z \<le> b\<rbrakk> \<Longrightarrow> g (f z) = z; \<And>z. \<lbrakk>a \<le> z; z \<le> b\<rbrakk> \<Longrightarrow> isCont f z\<rbrakk> \<Longrightarrow> isCont g (f x)" apply (rule isCont_inverse_function [where f=f and d="min (x - a) (b - x)"]) apply (simp_all add: abs_le_iff) done text \<open>Bartle/Sherbert: Introduction to Real Analysis, Theorem 4.2.9, p. 110.\<close> lemma LIM_fun_gt_zero: "f \<midarrow>c\<rightarrow> l \<Longrightarrow> 0 < l \<Longrightarrow> \<exists>r. 0 < r \<and> (\<forall>x. x \<noteq> c \<and> \<bar>c - x\<bar> < r \<longrightarrow> 0 < f x)" for f :: "real \<Rightarrow> real" by (force simp: dest: LIM_D) lemma LIM_fun_less_zero: "f \<midarrow>c\<rightarrow> l \<Longrightarrow> l < 0 \<Longrightarrow> \<exists>r. 0 < r \<and> (\<forall>x. x \<noteq> c \<and> \<bar>c - x\<bar> < r \<longrightarrow> f x < 0)" for f :: "real \<Rightarrow> real" by (drule LIM_D [where r="-l"]) force+ lemma LIM_fun_not_zero: "f \<midarrow>c\<rightarrow> l \<Longrightarrow> l \<noteq> 0 \<Longrightarrow> \<exists>r. 0 < r \<and> (\<forall>x. x \<noteq> c \<and> \<bar>c - x\<bar> < r \<longrightarrow> f x \<noteq> 0)" for f :: "real \<Rightarrow> real" using LIM_fun_gt_zero[of f l c] LIM_fun_less_zero[of f l c] by (auto simp: neq_iff) end
The specific epithet indigo is derived from the Latin word meaning " indigo blue " . Its names in the English vernacular include the " indigo milk cap " , the " indigo Lactarius " , the " blue milk mushroom " , and the " blue Lactarius " . In central Mexico , it is known as <unk> , <unk> , hongo <unk> , <unk> , and <unk> ; it is also called <unk> ( meaning " blue " ) in Veracruz and Puebla .
/- Copyright (c) 2023 Tian Chen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tian Chen -/ import analysis.mean_inequalities import matrix.doubly_stochastic.birkhoff import ineq.symm_sum import ineq.doubly_stochastic open_locale big_operators open finset lemma real.prod_pow {ι : Type*} {a : ℝ} {s : finset ι} {f : ι → ℝ} (h : ∀ x ∈ s, 0 ≤ f x) : (∏ x in s, f x) ^ a = ∏ x in s, f x ^ a := begin induction s using finset.cons_induction with i s his hs, { exact real.one_rpow _ }, rw finset.forall_mem_cons at h, rw [prod_cons, prod_cons, real.mul_rpow h.1 (prod_nonneg h.2), hs h.2] end variables {ι : Type*} [fintype ι] [decidable_eq ι] private lemma symm_mean_right_sum_le {ι' : Type*} [fintype ι'] (c : ι' → ℝ) (hc0 : ∀ i, 0 ≤ c i) (hc1 : ∑ i, c i = 1) (v : ι' → ι → ℝ) (z : ι → ℝ) (hz : ∀ i, 0 < z i) : symm_mean z (∑ i, c i • v i) ≤ ∑ i, c i * symm_mean z (v i) := begin simp_rw [symm_mean_def, mul_sum, sum_apply, pi.smul_apply, smul_eq_mul], rw sum_comm, apply sum_le_sum, intros σ _, calc ∏ i, z i ^ ∑ j, c j * v j (σ i) = ∏ i, ∏ j, z i ^ (c j * v j (σ i)) : prod_congr rfl $ λ i _, real.rpow_sum_of_pos (hz _) _ _ ... = ∏ i, ∏ j, (z i ^ v j (σ i)) ^ c j : prod_congr rfl $ λ i _, prod_congr rfl $ λ j _, by rw mul_comm; exact real.rpow_mul (hz _).le _ _ ... = ∏ j, (∏ i, z i ^ v j (σ i)) ^ c j : by rw prod_comm; apply prod_congr rfl; intros j _; rw real.prod_pow; intros; exact (real.rpow_pos_of_pos (hz _) _).le ... ≤ ∑ j, c j * ∏ i, z i ^ v j (σ i) : real.geom_mean_le_arith_mean_weighted _ c _ (λ _ _, hc0 _) hc1 $ λ _ _, prod_nonneg $ λ _ _, (real.rpow_pos_of_pos (hz _) _).le end /-- **Muirhead's Inequality** -/ theorem majorize.symm_mean_le_symm_mean {p q : ι → ℝ} (hpq : majorize q p) (z : ι → ℝ) (hz : ∀ i, 0 < z i) : symm_mean z q ≤ symm_mean z p := begin obtain ⟨M, hM, hM'⟩ := hpq.exists_doubly_stochastic, rcases hM.mem_convex_hull' with ⟨w, hw0, hw1, hMw⟩, rw [show q = matrix.mul_vec.add_monoid_hom_left p M, from hM', hMw, map_sum], rw [matrix.mul_vec.add_monoid_hom_left, add_monoid_hom.coe_mk], simp_rw [matrix.smul_mul_vec_assoc], convert symm_mean_right_sum_le w hw0 hw1 _ z hz, have : ∀ σ : ι ≃ ι, σ.to_pequiv.to_matrix.mul_vec p = p ∘ σ, { intro σ, ext i, rw [function.comp_app, matrix.mul_vec, matrix.dot_product], simp_rw [pequiv.equiv_to_pequiv_to_matrix, matrix.one_apply, boole_mul], rw [sum_ite_eq, if_pos (mem_univ _)] }, simp_rw [this, symm_mean_equiv_right], rw [← sum_mul, hw1, one_mul] end
chapter \<open>Addition, Sequences and their Concatenation\<close> theory OrdArith imports Rank begin section \<open>Generalised Addition --- Also for Ordinals\<close> text \<open>Source: Laurence Kirby, Addition and multiplication of sets Math. Log. Quart. 53, No. 1, 52-65 (2007) / DOI 10.1002/malq.200610026 @{url "http://faculty.baruch.cuny.edu/lkirby/mlqarticlejan2007.pdf"}\<close> definition hadd :: "hf \<Rightarrow> hf \<Rightarrow> hf" (infixl "@+" 65) where "hadd x \<equiv> hmemrec (\<lambda>f z. x \<squnion> RepFun z f)" lemma hadd: "x @+ y = x \<squnion> RepFun y (\<lambda>z. x @+ z)" by (metis def_hmemrec RepFun_ecut hadd_def order_refl) lemma hmem_hadd_E: assumes l: "l \<^bold>\<in> x @+ y" obtains "l \<^bold>\<in> x" | z where "z \<^bold>\<in> y" "l = x @+ z" using l by (auto simp: hadd [of x y]) lemma hadd_0_right [simp]: "x @+ 0 = x" by (subst hadd) simp lemma hadd_hinsert_right: "x @+ hinsert y z = hinsert (x @+ y) (x @+ z)" by (metis hadd hunion_hinsert_right RepFun_hinsert) lemma hadd_succ_right [simp]: "x @+ succ y = succ (x @+ y)" by (metis hadd_hinsert_right succ_def) lemma not_add_less_right: "\<not> (x @+ y < x)" apply (induct y, auto) apply (metis less_supI1 hadd order_less_le) done lemma not_add_mem_right: "\<not> (x @+ y \<^bold>\<in> x)" by (metis hadd hmem_not_refl hunion_iff) lemma hadd_0_left [simp]: "0 @+ x = x" by (induct x) (auto simp: hadd_hinsert_right) lemma hadd_succ_left [simp]: "Ord y \<Longrightarrow> succ x @+ y = succ (x @+ y)" by (induct y rule: Ord_induct2) auto lemma hadd_assoc: "(x @+ y) @+ z = x @+ (y @+ z)" by (induct z) (auto simp: hadd_hinsert_right) lemma RepFun_hadd_disjoint: "x \<sqinter> RepFun y ((@+) x) = 0" by (metis hf_equalityI RepFun_iff hinter_iff not_add_mem_right hmem_hempty) subsection \<open>Cancellation laws for addition\<close> lemma Rep_le_Cancel: "x \<squnion> RepFun y ((@+) x) \<le> x \<squnion> RepFun z ((@+) x) \<Longrightarrow> RepFun y ((@+) x) \<le> RepFun z ((@+) x)" by (auto simp add: not_add_mem_right) lemma hadd_cancel_right [simp]: "x @+ y = x @+ z \<longleftrightarrow> y=z" proof (induct y arbitrary: z rule: hmem_induct) case (step y z) show ?case proof auto assume eq: "x @+ y = x @+ z" hence "RepFun y ((@+) x) = RepFun z ((@+) x)" by (metis hadd Rep_le_Cancel order_antisym order_refl) thus "y = z" by (metis hf_equalityI RepFun_iff step) qed qed lemma RepFun_hadd_cancel: "RepFun y (\<lambda>z. x @+ z) = RepFun z (\<lambda>z. x @+ z) \<longleftrightarrow> y=z" by (metis hadd hadd_cancel_right) lemma hadd_hmem_cancel [simp]: "x @+ y \<^bold>\<in> x @+ z \<longleftrightarrow> y \<^bold>\<in> z" apply (auto simp: hadd [of _ y] hadd [of _ z] not_add_mem_right) apply (metis hmem_not_refl hunion_iff) apply (metis hadd hadd_cancel_right) done lemma ord_of_add: "ord_of (i+j) = ord_of i @+ ord_of j" by (induct j) auto lemma Ord_hadd: "Ord x \<Longrightarrow> Ord y \<Longrightarrow> Ord (x @+ y)" by (induct x rule: Ord_induct2) auto lemma hmem_self_hadd [simp]: "k1 \<^bold>\<in> k1 @+ k2 \<longleftrightarrow> 0 \<^bold>\<in> k2" by (metis hadd_0_right hadd_hmem_cancel) lemma hadd_commute: "Ord x \<Longrightarrow> Ord y \<Longrightarrow> x @+ y = y @+ x" by (induct x rule: Ord_induct2) auto lemma hadd_cancel_left [simp]: "Ord x \<Longrightarrow> y @+ x = z @+ x \<longleftrightarrow> y=z" by (induct x rule: Ord_induct2) auto subsection \<open>The predecessor function\<close> definition pred :: "hf \<Rightarrow> hf" where "pred x \<equiv> (THE y. succ y = x \<or> x=0 \<and> y=0)" lemma pred_succ [simp]: "pred (succ x) = x" by (simp add: pred_def) lemma pred_0 [simp]: "pred 0 = 0" by (simp add: pred_def) lemma succ_pred [simp]: "Ord x \<Longrightarrow> x \<noteq> 0 \<Longrightarrow> succ (pred x) = x" by (metis Ord_cases pred_succ) lemma pred_mem [simp]: "Ord x \<Longrightarrow> x \<noteq> 0 \<Longrightarrow> pred x \<^bold>\<in> x" by (metis succ_iff succ_pred) lemma Ord_pred [simp]: "Ord x \<Longrightarrow> Ord (pred x)" by (metis Ord_in_Ord pred_0 pred_mem) lemma hadd_pred_right: "Ord y \<Longrightarrow> y \<noteq> 0 \<Longrightarrow> x @+ pred y = pred (x @+ y)" by (metis hadd_succ_right pred_succ succ_pred) lemma Ord_pred_HUnion: "Ord(k) \<Longrightarrow> pred k = \<Squnion>k" by (metis HUnion_hempty Ordinal.Ord_pred pred_0 pred_succ) section \<open>A Concatentation Operation for Sequences\<close> definition shift :: "hf \<Rightarrow> hf \<Rightarrow> hf" where "shift f delta = \<lbrace>v . u \<^bold>\<in> f, \<exists>n y. u = \<langle>n, y\<rangle> \<and> v = \<langle>delta @+ n, y\<rangle>\<rbrace>" lemma shiftD: "x \<^bold>\<in> shift f delta \<Longrightarrow> \<exists>u. u \<^bold>\<in> f \<and> x = \<langle>delta @+ hfst u, hsnd u\<rangle>" by (auto simp: shift_def hsplit_def) lemma hmem_shift_iff: "\<langle>m, y\<rangle> \<^bold>\<in> shift f delta \<longleftrightarrow> (\<exists>n. m = delta @+ n \<and> \<langle>n, y\<rangle> \<^bold>\<in> f)" by (auto simp: shift_def hrelation_def is_hpair_def) lemma hmem_shift_add_iff [simp]: "\<langle>delta @+ n, y\<rangle> \<^bold>\<in> shift f delta \<longleftrightarrow> \<langle>n, y\<rangle> \<^bold>\<in> f" by (metis hadd_cancel_right hmem_shift_iff) lemma hrelation_shift [simp]: "hrelation (shift f delta)" by (auto simp: shift_def hrelation_def hsplit_def) lemma app_shift [simp]: "app (shift f k) (k @+ j) = app f j" by (simp add: app_def) lemma hfunction_shift_iff [simp]: "hfunction (shift f delta) = hfunction f" by (auto simp: hfunction_def hmem_shift_iff) lemma hdomain_shift_add: "hdomain (shift f delta) = \<lbrace>delta @+ n . n \<^bold>\<in> hdomain f\<rbrace>" by (rule hf_equalityI) (force simp add: hdomain_def hmem_shift_iff) definition seq_append :: "hf \<Rightarrow> hf \<Rightarrow> hf \<Rightarrow> hf" where "seq_append k f g \<equiv> hrestrict f k \<squnion> shift g k" lemma hrelation_seq_append [simp]: "hrelation (seq_append k f g)" by (simp add: seq_append_def) lemma Seq_append: "Seq s1 k1 \<Longrightarrow> Seq s2 k2 \<Longrightarrow> Seq (seq_append k1 s1 s2) (k1 @+ k2)" apply (auto simp: Seq_def seq_append_def) apply (metis hdomain_restr hdomain_shift_disjoint hfunction_hunion hfunction_restr hfunction_shift_iff inf_absorb2 seq_append_def) apply (simp add: hdomain_shift_add) apply (metis hmem_hadd_E rev_hsubsetD) apply (erule hmem_hadd_E, assumption, auto) apply (metis Seq_def Seq_iff_app hdomainI hmem_shift_add_iff) done lemma app_hunion1: "x \<^bold>\<notin> hdomain g \<Longrightarrow> app (f \<squnion> g) x = app f x" by (auto simp: app_def) (metis hdomainI) lemma app_hunion2: "x \<^bold>\<notin> hdomain f \<Longrightarrow> app (f \<squnion> g) x = app g x" by (auto simp: app_def) (metis hdomainI) lemma Seq_append_app1: "Seq s k \<Longrightarrow> l \<^bold>\<in> k \<Longrightarrow> app (seq_append k s s') l = app s l" apply (auto simp: Seq_def seq_append_def) apply (metis app_hunion1 hdomain_shift_disjoint hemptyE hinter_iff app_hrestrict) done lemma Seq_append_app2: "Seq s1 k1 \<Longrightarrow> Seq s2 k2 \<Longrightarrow> l = k1 @+ j \<Longrightarrow> app (seq_append k1 s1 s2) l = app s2 j" by (metis seq_append_def app_hunion2 app_shift hdomain_restr hinter_iff not_add_mem_right) section \<open>Nonempty sequences indexed by ordinals\<close> definition OrdDom where "OrdDom r \<equiv> \<forall>x y. \<langle>x,y\<rangle> \<^bold>\<in> r \<longrightarrow> Ord x" lemma OrdDom_insf: "\<lbrakk>OrdDom s; Ord k\<rbrakk> \<Longrightarrow> OrdDom (insf s (succ k) y)" by (auto simp: insf_def OrdDom_def) lemma OrdDom_hunion [simp]: "OrdDom (s1 \<squnion> s2) \<longleftrightarrow> OrdDom s1 \<and> OrdDom s2" by (auto simp: OrdDom_def) lemma OrdDom_hrestrict: "OrdDom s \<Longrightarrow> OrdDom (hrestrict s A)" by (auto simp: OrdDom_def) lemma OrdDom_shift: "\<lbrakk>OrdDom s; Ord k\<rbrakk> \<Longrightarrow> OrdDom (shift s k)" by (auto simp: OrdDom_def shift_def Ord_hadd) text \<open>A sequence of positive length ending with @{term y}\<close> definition LstSeq :: "hf \<Rightarrow> hf \<Rightarrow> hf \<Rightarrow> bool" where "LstSeq s k y \<equiv> Seq s (succ k) \<and> Ord k \<and> \<langle>k,y\<rangle> \<^bold>\<in> s \<and> OrdDom s" lemma LstSeq_imp_Seq_same: "LstSeq s k y \<Longrightarrow> Seq s k" by (metis LstSeq_imp_Seq_succ Seq_succ_D) lemma LstSeq_imp_Ord: "LstSeq s k y \<Longrightarrow> Ord k" by (metis LstSeq_def) lemma LstSeq_trunc: "LstSeq s k y \<Longrightarrow> l \<^bold>\<in> k \<Longrightarrow> LstSeq s l (app s l)" apply (auto simp: LstSeq_def Seq_iff_app) apply (metis Ord_succ Seq_Ord_D mem_succ_iff) apply (metis Ord_in_Ord) done lemma LstSeq_insf: "LstSeq s k z \<Longrightarrow> LstSeq (insf s (succ k) y) (succ k) y" by (metis OrdDom_insf LstSeq_def Ord_succ_iff Seq_imp_eq_app Seq_insf Seq_succ_iff app_insf_Seq) lemma app_insf_LstSeq: "LstSeq s k z \<Longrightarrow> app (insf s (succ k) y) (succ k) = y" by (metis LstSeq_imp_Seq_succ app_insf_Seq) lemma app_insf2_LstSeq: "LstSeq s k z \<Longrightarrow> k' \<noteq> succ k \<Longrightarrow> app (insf s (succ k) y) k' = app s k'" by (metis LstSeq_imp_Seq_succ app_insf2_Seq) lemma app_insf_LstSeq_if: "LstSeq s k z \<Longrightarrow> app (insf s (succ k) y) k' = (if k' = succ k then y else app s k')" by (metis app_insf2_LstSeq app_insf_LstSeq) lemma LstSeq_append_app1: "LstSeq s k y \<Longrightarrow> l \<^bold>\<in> succ k \<Longrightarrow> app (seq_append (succ k) s s') l = app s l" by (metis LstSeq_imp_Seq_succ Seq_append_app1) lemma LstSeq_append_app2: "\<lbrakk>LstSeq s1 k1 y1; LstSeq s2 k2 y2; l = succ k1 @+ j\<rbrakk> \<Longrightarrow> app (seq_append (succ k1) s1 s2) l = app s2 j" by (metis LstSeq_imp_Seq_succ Seq_append_app2) lemma Seq_append_pair: "\<lbrakk>Seq s1 k1; Seq s2 (succ n); \<langle>n, y\<rangle> \<^bold>\<in> s2; Ord n\<rbrakk> \<Longrightarrow> \<langle>k1 @+ n, y\<rangle> \<^bold>\<in> (seq_append k1 s1 s2)" by (metis hmem_shift_add_iff hunion_iff seq_append_def) lemma Seq_append_OrdDom: "\<lbrakk>Ord k; OrdDom s1; OrdDom s2\<rbrakk> \<Longrightarrow> OrdDom (seq_append k s1 s2)" by (auto simp: seq_append_def OrdDom_hrestrict OrdDom_shift) lemma LstSeq_append: "\<lbrakk>LstSeq s1 k1 y1; LstSeq s2 k2 y2\<rbrakk> \<Longrightarrow> LstSeq (seq_append (succ k1) s1 s2) (succ (k1 @+ k2)) y2" apply (auto simp: LstSeq_def Seq_append Ord_hadd Seq_append_pair) apply (metis Seq_append hadd_succ_left hadd_succ_right) apply (metis Seq_append_pair hadd_succ_left) apply (metis Ord_succ Seq_append_OrdDom) done lemma LstSeq_app [simp]: "LstSeq s k y \<Longrightarrow> app s k = y" by (metis LstSeq_def Seq_imp_eq_app) subsection \<open>Sequence-building operators\<close> definition Builds :: "(hf \<Rightarrow> bool) \<Rightarrow> (hf \<Rightarrow> hf \<Rightarrow> hf \<Rightarrow> bool) \<Rightarrow> hf \<Rightarrow> hf \<Rightarrow> bool" where "Builds B C s l \<equiv> B (app s l) \<or> (\<exists>m \<^bold>\<in> l. \<exists>n \<^bold>\<in> l. C (app s l) (app s m) (app s n))" definition BuildSeq :: "(hf \<Rightarrow> bool) \<Rightarrow> (hf \<Rightarrow> hf \<Rightarrow> hf \<Rightarrow> bool) \<Rightarrow> hf \<Rightarrow> hf \<Rightarrow> hf \<Rightarrow> bool" where "BuildSeq B C s k y \<equiv> LstSeq s k y \<and> (\<forall>l \<^bold>\<in> succ k. Builds B C s l)" lemma BuildSeqI: "LstSeq s k y \<Longrightarrow> (\<And>l. l \<^bold>\<in> succ k \<Longrightarrow> Builds B C s l) \<Longrightarrow> BuildSeq B C s k y" by (simp add: BuildSeq_def) lemma BuildSeq_imp_LstSeq: "BuildSeq B C s k y \<Longrightarrow> LstSeq s k y" by (metis BuildSeq_def) lemma BuildSeq_imp_Seq: "BuildSeq B C s k y \<Longrightarrow> Seq s (succ k)" by (metis LstSeq_imp_Seq_succ BuildSeq_imp_LstSeq) lemma BuildSeq_conj_distrib: "BuildSeq (\<lambda>x. B x \<and> P x) (\<lambda>x y z. C x y z \<and> P x) s k y \<longleftrightarrow> BuildSeq B C s k y \<and> (\<forall>l \<^bold>\<in> succ k. P (app s l))" by (auto simp: BuildSeq_def Builds_def) lemma BuildSeq_mono: assumes y: "BuildSeq B C s k y" and B: "\<And>x. B x \<Longrightarrow> B' x" and C: "\<And>x y z. C x y z \<Longrightarrow> C' x y z" shows "BuildSeq B' C' s k y" using y by (auto simp: BuildSeq_def Builds_def intro!: B C) lemma BuildSeq_trunc: assumes b: "BuildSeq B C s k y" and l: "l \<^bold>\<in> k" shows "BuildSeq B C s l (app s l)" proof - { fix j assume j: "j \<^bold>\<in> succ l" have k: "Ord k" by (metis BuildSeq_imp_LstSeq LstSeq_def b) hence "Builds B C s j" by (metis BuildSeq_def OrdmemD b hballE hsubsetD j l succ_iff) } thus ?thesis using b l by (auto simp: BuildSeq_def LstSeq_trunc) qed subsection \<open>Showing that Sequences can be Constructed\<close> lemma Builds_insf: "Builds B C s l \<Longrightarrow> LstSeq s k z \<Longrightarrow> l \<^bold>\<in> succ k \<Longrightarrow> Builds B C (insf s (succ k) y) l" by (auto simp: HBall_def hmem_not_refl Builds_def app_insf_LstSeq_if simp del: succ_iff) (metis hmem_not_sym) lemma BuildSeq_insf: assumes b: "BuildSeq B C s k z" and m: "m \<^bold>\<in> succ k" and n: "n \<^bold>\<in> succ k" and y: "B y \<or> C y (app s m) (app s n)" shows "BuildSeq B C (insf s (succ k) y) (succ k) y" proof (rule BuildSeqI) show "LstSeq (insf s (succ k) y) (succ k) y" by (metis BuildSeq_imp_LstSeq LstSeq_insf b) next fix l assume l: "l \<^bold>\<in> succ (succ k)" thus "Builds B C (insf s (succ k) y) l" proof assume l: "l = succ k" have "B (app (insf s l y) l) \<or> C (app (insf s l y) l) (app (insf s l y) m) (app (insf s l y) n)" by (metis BuildSeq_imp_Seq app_insf_Seq_if b hmem_not_refl l m n y) thus "Builds B C (insf s (succ k) y) l" using m n by (auto simp: Builds_def l) next assume l: "l \<^bold>\<in> succ k" have "LstSeq s k z" by (metis BuildSeq_imp_LstSeq b) thus "Builds B C (insf s (succ k) y) l" using b l by (metis hballE Builds_insf BuildSeq_def) qed qed lemma BuildSeq_insf1: assumes b: "BuildSeq B C s k z" and y: "B y" shows "BuildSeq B C (insf s (succ k) y) (succ k) y" by (metis BuildSeq_insf b succ_iff y) lemma BuildSeq_insf2: assumes b: "BuildSeq B C s k z" and m: "m \<^bold>\<in> k" and n: "n \<^bold>\<in> k" and y: "C y (app s m) (app s n)" shows "BuildSeq B C (insf s (succ k) y) (succ k) y" by (metis BuildSeq_insf b m n succ_iff y) lemma BuildSeq_append: assumes s1: "BuildSeq B C s1 k1 y1" and s2: "BuildSeq B C s2 k2 y2" shows "BuildSeq B C (seq_append (succ k1) s1 s2) (succ (k1 @+ k2)) y2" proof (rule BuildSeqI) show "LstSeq (seq_append (succ k1) s1 s2) (succ (k1 @+ k2)) y2" using assms by (metis BuildSeq_imp_LstSeq LstSeq_append) next fix l have s1L: "LstSeq s1 k1 y1" and s1BC: "\<And>l. l \<^bold>\<in> succ k1 \<Longrightarrow> Builds B C s1 l" and s2L: "LstSeq s2 k2 y2" and s2BC: "\<And>l. l \<^bold>\<in> succ k2 \<Longrightarrow> Builds B C s2 l" using s1 s2 by (auto simp: BuildSeq_def) assume l: "l \<^bold>\<in> succ (succ (k1 @+ k2))" hence "l \<^bold>\<in> succ k1 @+ succ k2" by (metis LstSeq_imp_Ord hadd_succ_left hadd_succ_right s2L) thus "Builds B C (seq_append (succ k1) s1 s2) l" proof (rule hmem_hadd_E) assume l1: "l \<^bold>\<in> succ k1" hence "B (app s1 l) \<or> (\<exists>m\<^bold>\<in>l. \<exists>n\<^bold>\<in>l. C (app s1 l) (app s1 m) (app s1 n))" using s1BC by (simp add: Builds_def) thus ?thesis proof assume "B (app s1 l)" thus ?thesis by (metis Builds_def LstSeq_append_app1 l1 s1L) next assume "\<exists>m\<^bold>\<in>l. \<exists>n\<^bold>\<in>l. C (app s1 l) (app s1 m) (app s1 n)" then obtain m n where mn: "m \<^bold>\<in> l" "n \<^bold>\<in> l" and C: "C (app s1 l) (app s1 m) (app s1 n)" by blast also have "m \<^bold>\<in> succ k1" "n \<^bold>\<in> succ k1" by (metis LstSeq_def Ord_trans l1 mn s1L succ_iff)+ ultimately have "C (app (seq_append (succ k1) s1 s2) l) (app (seq_append (succ k1) s1 s2) m) (app (seq_append (succ k1) s1 s2) n)" using s1L l1 by (simp add: LstSeq_append_app1) thus "Builds B C (seq_append (succ k1) s1 s2) l" using mn by (auto simp: Builds_def) qed next fix z assume z: "z \<^bold>\<in> succ k2" and l2: "l = succ k1 @+ z" hence "B (app s2 z) \<or> (\<exists>m\<^bold>\<in>z. \<exists>n\<^bold>\<in>z. C (app s2 z) (app s2 m) (app s2 n))" using s2BC by (simp add: Builds_def) thus ?thesis proof assume "B (app s2 z)" thus ?thesis by (metis Builds_def LstSeq_append_app2 l2 s1L s2L) next assume "\<exists>m\<^bold>\<in>z. \<exists>n\<^bold>\<in>z. C (app s2 z) (app s2 m) (app s2 n)" then obtain m n where mn: "m \<^bold>\<in> z" "n \<^bold>\<in> z" and C: "C (app s2 z) (app s2 m) (app s2 n)" by blast also have "m \<^bold>\<in> succ k2" "n \<^bold>\<in> succ k2" using mn by (metis LstSeq_def Ord_trans z s2L succ_iff)+ ultimately have "C (app (seq_append (succ k1) s1 s2) l) (app (seq_append (succ k1) s1 s2) (succ k1 @+ m)) (app (seq_append (succ k1) s1 s2) (succ k1 @+ n))" using s1L s2L l2 z by (simp add: LstSeq_append_app2) thus "Builds B C (seq_append (succ k1) s1 s2) l" using mn l2 by (auto simp: Builds_def HBall_def) qed qed qed lemma BuildSeq_combine: assumes b1: "BuildSeq B C s1 k1 y1" and b2: "BuildSeq B C s2 k2 y2" and y: "C y y1 y2" shows "BuildSeq B C (insf (seq_append (succ k1) s1 s2) (succ (succ (k1 @+ k2))) y) (succ (succ (k1 @+ k2))) y" proof - have k2: "Ord k2" using b2 by (auto simp: BuildSeq_def LstSeq_def) show ?thesis proof (rule BuildSeq_insf [where m=k1 and n="succ(k1@+k2)"]) show "BuildSeq B C (seq_append (succ k1) s1 s2) (succ (k1 @+ k2)) y2" by (rule BuildSeq_append [OF b1 b2]) next show "k1 \<^bold>\<in> succ (succ (k1 @+ k2))" using k2 by (metis hadd_0_right hmem_0_Ord hmem_self_hadd succ_iff) next show "succ (k1 @+ k2) \<^bold>\<in> succ (succ (k1 @+ k2))" by (metis succ_iff) next have [simp]: "app (seq_append (succ k1) s1 s2) k1 = y1" by (metis b1 BuildSeq_imp_LstSeq LstSeq_app LstSeq_append_app1 succ_iff) have [simp]: "app (seq_append (succ k1) s1 s2) (succ (k1 @+ k2)) = y2" by (metis b1 b2 k2 BuildSeq_imp_LstSeq LstSeq_app LstSeq_append_app2 hadd_succ_left) show "B y \<or> C y (app (seq_append (succ k1) s1 s2) k1) (app (seq_append (succ k1) s1 s2) (succ (k1 @+ k2)))" using y by simp qed qed lemma LstSeq_1: "LstSeq \<lbrace>\<langle>0, y\<rangle>\<rbrace> 0 y" by (auto simp: LstSeq_def One_hf_eq_succ Seq_ins OrdDom_def) lemma BuildSeq_1: "B y \<Longrightarrow> BuildSeq B C \<lbrace>\<langle>0, y\<rangle>\<rbrace> 0 y" by (auto simp: BuildSeq_def Builds_def LstSeq_1) lemma BuildSeq_exI: "B t \<Longrightarrow> \<exists>s k. BuildSeq B C s k t" by (metis BuildSeq_1) subsection \<open>Proving Properties of Given Sequences\<close> lemma BuildSeq_induct [consumes 1, case_names B C]: assumes major: "BuildSeq B C s k a" and B: "\<And>x. B x \<Longrightarrow> P x" and C: "\<And>x y z. C x y z \<Longrightarrow> P y \<Longrightarrow> P z \<Longrightarrow> P x" shows "P a" proof - have "Ord k" using assms by (auto simp: BuildSeq_def LstSeq_def) hence "\<And>a s. BuildSeq B C s k a \<Longrightarrow> P a" by (induction k rule: Ord_induct) (metis BuildSeq_trunc BuildSeq_succ_E B C) thus ?thesis by (metis major) qed definition BuildSeq2 :: "[[hf,hf] \<Rightarrow> bool, [hf,hf,hf,hf,hf,hf] \<Rightarrow> bool, hf, hf, hf, hf] \<Rightarrow> bool" where "BuildSeq2 B C s k y y' \<equiv> BuildSeq (\<lambda>p. \<exists>x x'. p = \<langle>x,x'\<rangle> \<and> B x x') (\<lambda>p q r. \<exists>x x' y y' z z'. p = \<langle>x,x'\<rangle> \<and> q = \<langle>y,y'\<rangle> \<and> r = \<langle>z,z'\<rangle> \<and> C x x' y y' z z') s k \<langle>y,y'\<rangle>" lemma BuildSeq2_combine: assumes b1: "BuildSeq2 B C s1 k1 y1 y1'" and b2: "BuildSeq2 B C s2 k2 y2 y2'" and y: "C y y' y1 y1' y2 y2'" shows "BuildSeq2 B C (insf (seq_append (succ k1) s1 s2) (succ (succ (k1 @+ k2))) \<langle>y, y'\<rangle>) (succ (succ (k1 @+ k2))) y y'" using assms apply (unfold BuildSeq2_def) apply (blast intro: BuildSeq_combine) done lemma BuildSeq2_1: "B y y' \<Longrightarrow> BuildSeq2 B C \<lbrace>\<langle>0, y, y'\<rangle>\<rbrace> 0 y y'" by (auto simp: BuildSeq2_def BuildSeq_1) lemma BuildSeq2_induct [consumes 1, case_names B C]: assumes "BuildSeq2 B C s k a a'" and B: "\<And>x x'. B x x' \<Longrightarrow> P x x'" and C: "\<And>x x' y y' z z'. C x x' y y' z z' \<Longrightarrow> P y y' \<Longrightarrow> P z z' \<Longrightarrow> P x x'" shows "P a a'" using assms apply (simp add: BuildSeq2_def) apply (drule BuildSeq_induct [where P = "\<lambda>\<langle>x,x'\<rangle>. P x x'"]) apply (auto intro: B C) done definition BuildSeq3 :: "[[hf,hf,hf] \<Rightarrow> bool, [hf,hf,hf,hf,hf,hf,hf,hf,hf] \<Rightarrow> bool, hf, hf, hf, hf, hf] \<Rightarrow> bool" where "BuildSeq3 B C s k y y' y'' \<equiv> BuildSeq (\<lambda>p. \<exists>x x' x''. p = \<langle>x,x',x''\<rangle> \<and> B x x' x'') (\<lambda>p q r. \<exists>x x' x'' y y' y'' z z' z''. p = \<langle>x,x',x''\<rangle> \<and> q = \<langle>y,y',y''\<rangle> \<and> r = \<langle>z,z',z''\<rangle> \<and> C x x' x'' y y' y'' z z' z'') s k \<langle>y,y',y''\<rangle>" lemma BuildSeq3_combine: assumes b1: "BuildSeq3 B C s1 k1 y1 y1' y1''" and b2: "BuildSeq3 B C s2 k2 y2 y2' y2''" and y: "C y y' y'' y1 y1' y1'' y2 y2' y2''" shows "BuildSeq3 B C (insf (seq_append (succ k1) s1 s2) (succ (succ (k1 @+ k2))) \<langle>y, y', y''\<rangle>) (succ (succ (k1 @+ k2))) y y' y''" using assms apply (unfold BuildSeq3_def) apply (blast intro: BuildSeq_combine) done lemma BuildSeq3_1: "B y y' y'' \<Longrightarrow> BuildSeq3 B C \<lbrace>\<langle>0, y, y', y''\<rangle>\<rbrace> 0 y y' y''" by (auto simp: BuildSeq3_def BuildSeq_1) lemma BuildSeq3_exI: "B t t' t'' \<Longrightarrow> \<exists>s k. BuildSeq3 B C s k t t' t''" by (metis BuildSeq3_1) lemma BuildSeq3_induct [consumes 1, case_names B C]: assumes "BuildSeq3 B C s k a a' a''" and B: "\<And>x x' x''. B x x' x'' \<Longrightarrow> P x x' x''" and C: "\<And>x x' x'' y y' y'' z z' z''. C x x' x'' y y' y'' z z' z'' \<Longrightarrow> P y y' y'' \<Longrightarrow> P z z' z'' \<Longrightarrow> P x x' x''" shows "P a a' a''" using assms apply (simp add: BuildSeq3_def) apply (drule BuildSeq_induct [where P = "\<lambda>\<langle>x,x',x''\<rangle>. P x x' x''"]) apply (auto intro: B C) done section \<open>A Unique Predecessor for every non-empty set\<close> lemma Rep_hf_0 [simp]: "Rep_hf 0 = 0" by (metis Abs_hf_inverse HF.HF_def UNIV_I Zero_hf_def image_empty set_encode_empty) lemma hmem_imp_less: "x \<^bold>\<in> y \<Longrightarrow> Rep_hf x < Rep_hf y" apply (auto simp: hmem_def hfset_def set_decode_def Abs_hf_inverse) apply (metis div_less even_zero le_less_trans less_two_power not_less) done lemma hsubset_imp_le: "x \<le> y \<Longrightarrow> Rep_hf x \<le> Rep_hf y" apply (auto simp: less_eq_hf_def hmem_def hfset_def Abs_hf_inverse) apply (cases x rule: Abs_hf_cases) apply (cases y rule: Abs_hf_cases, auto) apply (rule subset_decode_imp_le) apply (auto simp: Abs_hf_inverse [OF UNIV_I]) apply (metis Abs_hf_inverse UNIV_I imageE imageI) done lemma diff_hmem_imp_less: assumes "x \<^bold>\<in> y" shows "Rep_hf (y - \<lbrace>x\<rbrace>) < Rep_hf y" proof - have "Rep_hf (y - \<lbrace>x\<rbrace>) \<le> Rep_hf y" by (metis hdiff_iff hsubsetI hsubset_imp_le) moreover have "Rep_hf (y - \<lbrace>x\<rbrace>) \<noteq> Rep_hf y" using assms by (metis Rep_hf_inject hdiff_iff hinsert_iff) ultimately show ?thesis by (metis le_neq_implies_less) qed definition least :: "hf \<Rightarrow> hf" where "least a \<equiv> (THE x. x \<^bold>\<in> a \<and> (\<forall>y. y \<^bold>\<in> a \<longrightarrow> Rep_hf x \<le> Rep_hf y))" lemma least_equality: assumes "x \<^bold>\<in> a" and "\<And>y. y \<^bold>\<in> a \<Longrightarrow> Rep_hf x \<le> Rep_hf y" shows "least a = x" unfolding least_def apply (rule the_equality) apply (metis assms) apply (metis Rep_hf_inverse assms eq_iff) done lemma nonempty_imp_ex_least: "a \<noteq> 0 \<Longrightarrow> \<exists>x. x \<^bold>\<in> a \<and> (\<forall>y. y \<^bold>\<in> a \<longrightarrow> Rep_hf x \<le> Rep_hf y)" proof (induction a rule: hf_induct) case 0 thus ?case by simp next case (hinsert u v) show ?case proof (cases "v=0") case True thus ?thesis by (rule_tac x=u in exI, simp) next case False thus ?thesis by (metis dual_order.trans eq_iff hinsert.IH(2) hmem_hinsert less_eq_insert1_iff linear) qed qed lemma least_hmem: "a \<noteq> 0 \<Longrightarrow> least a \<^bold>\<in> a" apply (frule nonempty_imp_ex_least, clarify) apply (rule leastI2_order, auto) done end
import measure_theory.integral.interval_integral import analysis.calculus.parametric_integral import algebra.module.ulift import to_mathlib.analysis.calculus open topological_space measure_theory filter first_countable_topology metric set function open_locale topology filter nnreal big_operators interval lemma ae_strongly_measurable_uIoc_iff {α β : Type*} [measurable_space α] [linear_order α] [topological_space β] [metrizable_space β] {μ : measure α} {f : α → β} {a b : α} : (ae_strongly_measurable f $ μ.restrict $ Ι a b) ↔ (ae_strongly_measurable f $ μ.restrict $ Ioc a b) ∧ (ae_strongly_measurable f $ μ.restrict $ Ioc b a) := by rw [uIoc_eq_union, ae_strongly_measurable_union_iff] section variables {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [complete_space E] {H : Type*} [normed_add_comm_group H] [normed_space ℝ H] (ν : measure ℝ) /-- Interval version of `has_fderiv_at_of_dominated_of_fderiv_le` -/ lemma has_fderiv_at_of_dominated_of_fderiv_le'' {F : H → ℝ → E} {F' : H → ℝ → (H →L[ℝ] E)} {x₀ : H} {a b : ℝ} {bound : ℝ → ℝ} {ε : ℝ} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_strongly_measurable (F x) $ ν.restrict (Ι a b)) (hF_int : interval_integrable (F x₀) ν a b) (hF'_meas : ae_strongly_measurable (F' x₀) $ ν.restrict (Ι a b)) (h_bound : ∀ᵐ t ∂ν.restrict (Ι a b), ∀ x ∈ ball x₀ ε, ‖F' x t‖ ≤ bound t) (bound_integrable : interval_integrable bound ν a b) (h_diff : ∀ᵐ t ∂ν.restrict (Ι a b), ∀ x ∈ ball x₀ ε, has_fderiv_at (λ x, F x t) (F' x t) x) : has_fderiv_at (λ x, ∫ t in a..b, F x t ∂ν) (∫ t in a..b, F' x₀ t ∂ν) x₀ := begin erw ae_restrict_uIoc_iff at h_diff h_bound, simp_rw [ae_strongly_measurable_uIoc_iff, eventually_and] at hF_meas hF'_meas, exact (has_fderiv_at_integral_of_dominated_of_fderiv_le ε_pos hF_meas.1 hF_int.1 hF'_meas.1 h_bound.1 bound_integrable.1 h_diff.1).sub (has_fderiv_at_integral_of_dominated_of_fderiv_le ε_pos hF_meas.2 hF_int.2 hF'_meas.2 h_bound.2 bound_integrable.2 h_diff.2) end /-- Interval version of `has_fderiv_at_of_dominated_loc_of_lip` -/ lemma has_fderiv_at_of_dominated_loc_of_lip_interval {F : H → ℝ → E} {F' : ℝ → (H →L[ℝ] E)} {x₀ : H} {a b : ℝ} {bound : ℝ → ℝ} {ε : ℝ} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_strongly_measurable (F x) $ ν.restrict (Ι a b)) (hF_int : interval_integrable (F x₀) ν a b) (hF'_meas : ae_strongly_measurable F' $ ν.restrict (Ι a b)) (h_lip : ∀ᵐ t ∂(ν.restrict (Ι a b)), lipschitz_on_with (real.nnabs $ bound t) (λ x, F x t) (ball x₀ ε)) (bound_integrable : interval_integrable bound ν a b) (h_diff : ∀ᵐ t ∂(ν.restrict (Ι a b)), has_fderiv_at (λ x, F x t) (F' t) x₀) : interval_integrable F' ν a b ∧ has_fderiv_at (λ x, ∫ t in a..b, F x t ∂ν) (∫ t in a..b, F' t ∂ν) x₀ := begin simp_rw [ae_strongly_measurable_uIoc_iff, eventually_and] at hF_meas hF'_meas, rw ae_restrict_uIoc_iff at h_lip h_diff, have H₁ := has_fderiv_at_integral_of_dominated_loc_of_lip ε_pos hF_meas.1 hF_int.1 hF'_meas.1 h_lip.1 bound_integrable.1 h_diff.1, have H₂ := has_fderiv_at_integral_of_dominated_loc_of_lip ε_pos hF_meas.2 hF_int.2 hF'_meas.2 h_lip.2 bound_integrable.2 h_diff.2, exact ⟨⟨H₁.1, H₂.1⟩, H₁.2.sub H₂.2⟩ end end section open function theorem continuous_parametric_integral_of_continuous {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [complete_space E] {α : Type*} [topological_space α] [measurable_space α] [opens_measurable_space α] [second_countable_topology_either α E] {μ : measure_theory.measure α} [is_locally_finite_measure μ] {X : Type*} [topological_space X] [first_countable_topology X] [locally_compact_space X] {F : X → α → E} (hF : continuous (λ p : X × α, F p.1 p.2)) {s : set α} (hs : is_compact s) : continuous (λ x, ∫ a in s, F x a ∂μ) := begin rw continuous_iff_continuous_at, intros x₀, rcases exists_compact_mem_nhds x₀ with ⟨U, U_cpct, U_nhds⟩, rcases (U_cpct.prod hs).bdd_above_image hF.norm.continuous_on with ⟨M, hM⟩, apply continuous_at_of_dominated, { exact eventually_of_forall (λ x, (hF.comp (continuous.prod.mk x)).ae_strongly_measurable) }, { apply eventually.mono U_nhds (λ x x_in, _), rw [ae_restrict_iff], exact eventually_of_forall (λ t t_in, hM (mem_image_of_mem _ $ mk_mem_prod x_in t_in)), exact (is_closed_le (hF.comp $ continuous.prod.mk x).norm continuous_const).measurable_set }, { exact integrable_on_const.mpr (or.inr hs.measure_lt_top), }, { apply ae_of_all, intros a, apply (hF.comp₂ continuous_id continuous_const).continuous_at } end end section open measure_theory variables {μ : measure ℝ} {X : Type*} [topological_space X] [first_countable_topology X] {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [complete_space E] lemma continuous_at_parametric_primitive_of_dominated {F : X → ℝ → E} (bound : ℝ → ℝ) (a b : ℝ) {a₀ b₀ : ℝ} {x₀ : X} (hF_meas : ∀ x, ae_strongly_measurable (F x) (μ.restrict $ Ι a b)) (h_bound : ∀ᶠ x in 𝓝 x₀, ∀ᵐ t ∂(μ.restrict $ Ι a b), ‖F x t‖ ≤ bound t) (bound_integrable : interval_integrable bound μ a b) (h_cont : ∀ᵐ t ∂(μ.restrict $ Ι a b), continuous_at (λ x, F x t) x₀) (ha₀ : a₀ ∈ Ioo a b) (hb₀ : b₀ ∈ Ioo a b) (hμb₀ : μ {b₀} = 0) : continuous_at (λ p : X × ℝ, ∫ (t : ℝ) in a₀..p.2, F p.1 t ∂μ) (x₀, b₀) := begin have hsub : ∀ {a₀ b₀}, a₀ ∈ Ioo a b → b₀ ∈ Ioo a b → Ι a₀ b₀ ⊆ Ι a b := λ a₀ b₀ ha₀ hb₀, (ord_connected_Ioo.uIoc_subset ha₀ hb₀).trans (Ioo_subset_Ioc_self.trans Ioc_subset_uIoc), have Ioo_nhds : Ioo a b ∈ 𝓝 b₀ := Ioo_mem_nhds hb₀.1 hb₀.2, have Icc_nhds : Icc a b ∈ 𝓝 b₀ := Icc_mem_nhds hb₀.1 hb₀.2, have hx₀ : ∀ᵐ (t : ℝ) ∂μ.restrict (Ι a b), ‖F x₀ t‖ ≤ bound t := h_bound.self_of_nhds, have : ∀ᶠ (p : X × ℝ) in 𝓝 (x₀, b₀), ∫ s in a₀..p.2, F p.1 s ∂μ = ∫ s in a₀..b₀, F p.1 s ∂μ + ∫ s in b₀..p.2, F x₀ s ∂μ + ∫ s in b₀..p.2, (F p.1 s - F x₀ s) ∂μ, { rw nhds_prod_eq, refine (h_bound.prod_mk Ioo_nhds).mono _, rintros ⟨x, t⟩ ⟨hx : ∀ᵐ (t : ℝ) ∂μ.restrict (Ι a b), ‖F x t‖ ≤ bound t, ht : t ∈ Ioo a b⟩, dsimp {eta := ff}, have hiF : ∀ {x a₀ b₀}, (∀ᵐ (t : ℝ) ∂μ.restrict (Ι a b), ‖F x t‖ ≤ bound t) → a₀ ∈ Ioo a b → b₀ ∈ Ioo a b → interval_integrable (F x) μ a₀ b₀ := λ x a₀ b₀ hx ha₀ hb₀, (bound_integrable.mono_set_ae $ eventually_of_forall $ hsub ha₀ hb₀).mono_fun' ((hF_meas x).mono_set $ hsub ha₀ hb₀) (ae_restrict_of_ae_restrict_of_subset (hsub ha₀ hb₀) hx), rw [interval_integral.integral_sub, add_assoc, add_sub_cancel'_right, interval_integral.integral_add_adjacent_intervals], { exact hiF hx ha₀ hb₀ }, { exact hiF hx hb₀ ht }, { exact hiF hx hb₀ ht }, { exact hiF hx₀ hb₀ ht } }, rw continuous_at_congr this, clear this, refine (continuous_at.add _ _).add _, { exact (interval_integral.continuous_at_of_dominated_interval (eventually_of_forall $ λ x, (hF_meas x).mono_set $ hsub ha₀ hb₀) (h_bound.mono $ λ x hx, ae_imp_of_ae_restrict $ ae_restrict_of_ae_restrict_of_subset (hsub ha₀ hb₀) hx) (bound_integrable.mono_set_ae $ eventually_of_forall $ hsub ha₀ hb₀) $ ae_imp_of_ae_restrict $ ae_restrict_of_ae_restrict_of_subset (hsub ha₀ hb₀) h_cont).fst' }, { refine (_ : continuous_at (λ t, ∫ s in b₀..t, F x₀ s ∂μ) b₀).snd', apply continuous_within_at.continuous_at _ (Icc_mem_nhds hb₀.1 hb₀.2), apply interval_integral.continuous_within_at_primitive hμb₀, rw [min_eq_right hb₀.1.le, max_eq_right hb₀.2.le], exact bound_integrable.mono_fun' (hF_meas x₀) hx₀ }, { suffices : tendsto (λ (x : X × ℝ), ∫ s in b₀..x.2, F x.1 s - F x₀ s ∂μ) (𝓝 (x₀, b₀)) (𝓝 0), by simpa [continuous_at], have : ∀ᶠ p : X × ℝ in 𝓝 (x₀, b₀), ‖∫ s in b₀..p.2, F p.1 s - F x₀ s ∂μ‖ ≤ |∫ s in b₀..p.2, 2 * bound s ∂μ|, { rw nhds_prod_eq, refine (h_bound.prod_mk Ioo_nhds).mono _, rintros ⟨x, t⟩ ⟨hx : ∀ᵐ t ∂μ.restrict (Ι a b), ‖F x t‖ ≤ bound t, ht : t ∈ Ioo a b⟩, have H : ∀ᵐ (t : ℝ) ∂μ.restrict (Ι b₀ t), ‖F x t - F x₀ t‖ ≤ 2 * bound t, { apply (ae_restrict_of_ae_restrict_of_subset (hsub hb₀ ht) (hx.and hx₀)).mono, rintros s ⟨hs₁, hs₂⟩, calc ‖F x s - F x₀ s‖ ≤ ‖F x s‖ + ‖F x₀ s‖ : norm_sub_le _ _ ... ≤ 2 * bound s : by linarith only [hs₁, hs₂] }, exact interval_integral.norm_integral_le_of_norm_le H ((bound_integrable.mono_set' $ hsub hb₀ ht).const_mul 2) }, apply squeeze_zero_norm' this, have : tendsto (λ t, ∫ s in b₀..t, 2 * bound s ∂μ) (𝓝 b₀) (𝓝 0), { suffices : continuous_at (λ t, ∫ s in b₀..t, 2 * bound s ∂μ) b₀, { convert this, simp }, apply continuous_within_at.continuous_at _ Icc_nhds, apply interval_integral.continuous_within_at_primitive hμb₀, apply interval_integrable.const_mul, apply bound_integrable.mono_set', rw [min_eq_right hb₀.1.le, max_eq_right hb₀.2.le] }, rw nhds_prod_eq, exact (continuous_abs.tendsto' _ _ abs_zero).comp (this.comp tendsto_snd) }, end end section variables {μ : measure ℝ} [is_locally_finite_measure μ] [has_no_atoms μ] {X : Type*} [topological_space X] [first_countable_topology X] {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [complete_space E] lemma continuous_parametric_primitive_of_continuous [locally_compact_space X] {F : X → ℝ → E} {a₀ : ℝ} (hF : continuous (λ p : X × ℝ, F p.1 p.2)) : continuous (λ p : X × ℝ, ∫ t in a₀..p.2, F p.1 t ∂μ) := begin rw continuous_iff_continuous_at, rintros ⟨x₀, b₀⟩, rcases exists_compact_mem_nhds x₀ with ⟨U, U_cpct, U_nhds⟩, cases exists_lt (min a₀ b₀) with a a_lt, cases exists_gt (max a₀ b₀) with b lt_b, rw lt_min_iff at a_lt, rw max_lt_iff at lt_b, have a₀_in : a₀ ∈ Ioo a b := ⟨a_lt.1, lt_b.1⟩, have b₀_in : b₀ ∈ Ioo a b := ⟨a_lt.2, lt_b.2⟩, obtain ⟨M, hM⟩ := (U_cpct.prod (is_compact_Icc : is_compact $ Icc a b)).bdd_above_image hF.norm.continuous_on, refine continuous_at_parametric_primitive_of_dominated (λ t, M) a b _ _ _ _ a₀_in b₀_in (measure_singleton b₀), { exact λ x, (hF.comp (continuous.prod.mk x)).ae_strongly_measurable }, { apply eventually.mono U_nhds (λ x (x_in : x ∈ U), _), simp_rw [ae_restrict_iff' measurable_set_uIoc], refine eventually_of_forall (λ t t_in, _), refine hM (mem_image_of_mem _ $ mk_mem_prod x_in _), rw uIoc_of_le (a_lt.1.trans lt_b.1).le at t_in, exact mem_Icc_of_Ioc t_in }, { apply interval_integrable_const }, { apply ae_of_all, intros a, apply (hF.comp₂ continuous_id continuous_const).continuous_at } end theorem continuous_parametric_interval_integral_of_continuous [locally_compact_space X] {a₀ : ℝ} {F : X → ℝ → E} (hF : continuous (λ p : X × ℝ, F p.1 p.2)) {s : X → ℝ} (hs : continuous s) : continuous (λ x, ∫ t in a₀..s x, F x t ∂μ) := show continuous ((λ p : X × ℝ, ∫ t in a₀..p.2, F p.1 t ∂μ) ∘ (λ x, (x, s x))), from (continuous_parametric_primitive_of_continuous hF).comp₂ continuous_id hs theorem continuous_parametric_interval_integral_of_continuous' [locally_compact_space X] {F : X → ℝ → E} (hF : continuous (λ p : X × ℝ, F p.1 p.2)) (a₀ b₀ : ℝ) : continuous (λ x, ∫ t in a₀..b₀, F x t ∂μ) := continuous_parametric_interval_integral_of_continuous hF continuous_const end section variables {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [complete_space E] {H : Type*} [normed_add_comm_group H] [normed_space ℝ H] /-! We could weaken `finite_dimensional ℝ H` with `second_countable (H →L[ℝ] E)` if needed, but that is less convenient to work with. -/ open real continuous_linear_map asymptotics /-- This statement is a new version using the continuity note in mathlib. See commit `39e3f3f` for an older version Maybe todo: let `a` depend on `x`. -/ lemma has_fderiv_at_parametric_primitive_of_lip' (F : H → ℝ → E) (F' : ℝ → (H →L[ℝ] E)) {x₀ : H} {G' : H →L[ℝ] E} {bound : ℝ → ℝ} {s : H → ℝ} {ε : ℝ} (ε_pos : 0 < ε) {a a₀ b₀ : ℝ} {s' : H →L[ℝ] ℝ} (ha : a ∈ Ioo a₀ b₀) (hsx₀ : s x₀ ∈ Ioo a₀ b₀) (hF_meas : ∀ x ∈ ball x₀ ε, ae_strongly_measurable (F x) (volume.restrict (Ioo a₀ b₀))) (hF_int : integrable_on (F x₀) (Ioo a₀ b₀)) (hF_cont : continuous_at (F x₀) (s x₀)) (hF'_meas : ae_strongly_measurable F' (volume.restrict $ Ι a (s x₀))) (h_lipsch : ∀ᵐ t ∂(volume.restrict $ Ioo a₀ b₀), lipschitz_on_with (nnabs $ bound t) (λ x, F x t) (ball x₀ ε)) (bound_integrable : integrable_on bound (Ioo a₀ b₀)) (bound_cont : continuous_at bound (s x₀)) (bound_nonneg : ∀ t, 0 ≤ bound t) -- this is not really needed, but much more convenient (h_diff : ∀ᵐ a ∂volume.restrict (Ι a (s x₀)), has_fderiv_at (λ x, F x a) (F' a) x₀) (s_diff : has_fderiv_at s s' x₀) (hG' : (∫ t in a..s x₀, F' t) + (to_span_singleton ℝ (F x₀ (s x₀))).comp s' = G') : interval_integrable F' volume a (s x₀) ∧ has_fderiv_at (λ x : H, ∫ t in a..s x, F x t) G' x₀ := begin subst hG', let φ : H → ℝ → E := λ x t, ∫ s in a..t, F x s, let ψ : H →L[ℝ] E := ∫ t in a..s x₀, F' t, have Ioo_nhds : Ioo a₀ b₀ ∈ 𝓝 (s x₀) := Ioo_mem_nhds hsx₀.1 hsx₀.2, have bound_int : ∀ {s u}, s ∈ Ioo a₀ b₀ → u ∈ Ioo a₀ b₀ → interval_integrable bound volume s u, { intros s u hs hu, exact (bound_integrable.mono_set $ ord_connected_Ioo.uIcc_subset hs hu).interval_integrable }, have mem_nhds : ball x₀ ε ∩ (s ⁻¹' Ioo a₀ b₀) ∈ 𝓝 x₀ := filter.inter_mem (ball_mem_nhds x₀ ε_pos) (s_diff.continuous_at.preimage_mem_nhds Ioo_nhds), have x₀_in : x₀ ∈ ball x₀ ε := mem_ball_self ε_pos, have hF_meas_ball : ∀ {x}, x ∈ ball x₀ ε → ∀ {s u}, s ∈ Ioo a₀ b₀ → u ∈ Ioo a₀ b₀ → ae_strongly_measurable (F x) (volume.restrict $ Ι s u), { intros x hx s u hs hu, exact (hF_meas x hx).mono_set (ord_connected_Ioo.uIoc_subset hs hu) }, have hF_int_ball : ∀ x ∈ ball x₀ ε, ∀ {s u}, s ∈ Ioo a₀ b₀ → u ∈ Ioo a₀ b₀ → interval_integrable (F x) volume s u, { intros x hx s u hs hu, have : integrable_on (F x) (Ioo a₀ b₀), { apply integrable_of_norm_sub_le (hF_meas x hx) hF_int (bound_integrable.mul_const (‖x - x₀‖)), apply h_lipsch.mono, intros t ht, rw norm_sub_rev, rw lipschitz_on_with_iff_norm_sub_le at ht, simpa [bound_nonneg t] using ht hx x₀_in }, exact (this.mono_set $ ord_connected_Ioo.uIcc_subset hs hu).interval_integrable }, split, { apply (bound_int ha hsx₀).mono_fun' hF'_meas _, replace h_lipsch : ∀ᵐ t ∂volume.restrict (Ι a (s x₀)), lipschitz_on_with (nnabs (bound t)) (λ (x : H), F x t) (ball x₀ ε), from ae_restrict_of_ae_restrict_of_subset (ord_connected_Ioo.uIoc_subset ha hsx₀) h_lipsch, filter_upwards [h_lipsch, h_diff], intros t ht_lip ht_diff, rw show bound t = nnabs (bound t), by simp [bound_nonneg t], exact ht_diff.le_of_lip (ball_mem_nhds x₀ ε_pos) ht_lip }, { have D₁ : has_fderiv_at (λ x, φ x (s x₀)) (∫ t in a..s x₀, F' t) x₀, { replace hF_meas : ∀ᶠ x in 𝓝 x₀, ae_strongly_measurable (F x) (volume.restrict (Ι a (s x₀))), from eventually.mono (ball_mem_nhds x₀ ε_pos) (λ x hx, hF_meas_ball hx ha hsx₀), replace hF_int : interval_integrable (F x₀) volume a (s x₀) := hF_int_ball x₀ x₀_in ha hsx₀, exact (has_fderiv_at_of_dominated_loc_of_lip_interval _ ε_pos hF_meas hF_int hF'_meas (ae_restrict_of_ae_restrict_of_subset (ord_connected_Ioo.uIoc_subset ha hsx₀) h_lipsch) (bound_int ha hsx₀) h_diff).2 }, have D₂ : has_fderiv_at (λ x, φ x₀ (s x)) ((to_span_singleton ℝ (F x₀ (s x₀))).comp s') x₀, { refine has_fderiv_at.comp _ _ s_diff, rw [has_fderiv_at_iff_has_deriv_at, to_span_singleton_apply, one_smul], exact interval_integral.integral_has_deriv_at_right (hF_int_ball x₀ x₀_in ha hsx₀) ⟨Ioo a₀ b₀, Ioo_nhds, (hF_meas x₀ x₀_in)⟩ hF_cont }, have D₃ : has_fderiv_at (λ x, ∫ t in s x₀..s x, F x t - F x₀ t) 0 x₀, { apply is_O.has_fderiv_at _ one_lt_two, have O₁ : (λ x, ∫ s in s x₀..s x, bound s) =O[𝓝 x₀] λ x, ‖x - x₀‖, { have : (λ x, s x - s x₀) =O[𝓝 x₀] λ x, ‖x - x₀‖ := s_diff.is_O_sub.norm_right, refine is_O.trans _ this, show ((λ t, ∫ s in s x₀..t, bound s) ∘ s) =O[𝓝 x₀] ((λ t, t - s x₀) ∘ s), refine is_O.comp_tendsto _ s_diff.continuous_at, have M : strongly_measurable_at_filter bound (𝓝 (s x₀)) volume, { use [Ioo a₀ b₀, Ioo_nhds, bound_integrable.1] }, refine (interval_integral.integral_has_deriv_at_right (bound_int ha hsx₀) M bound_cont) .has_fderiv_at.is_O.congr' _ eventually_eq.rfl, apply eventually.mono Ioo_nhds, rintros t ht, dsimp only {eta := false}, rw interval_integral.integral_interval_sub_left (bound_int ha ht) (bound_int ha hsx₀) }, have O₂ : (λ x, ‖x - x₀‖) =O[𝓝 x₀] λ x, ‖x - x₀‖ := is_O_refl _ _, have O₃ : (λ x, ∫ (t : ℝ) in s x₀..s x, F x t - F x₀ t) =O[𝓝 x₀] λ x, (∫ t' in s x₀..s x, bound t') * ‖x - x₀‖, { have bdd : ∀ᶠ x in 𝓝 x₀, ‖∫ s in s x₀..s x, F x s - F x₀ s‖ ≤ |∫ s in s x₀..s x, bound s |* ‖x - x₀‖, { apply eventually.mono mem_nhds, rintros x ⟨hx : x ∈ ball x₀ ε, hsx : s x ∈ Ioo a₀ b₀⟩, rw [← abs_of_nonneg (norm_nonneg $ x - x₀), ← abs_mul, ← interval_integral.integral_mul_const], apply interval_integral.norm_integral_le_of_norm_le _ ((bound_int hsx₀ hsx).mul_const _), apply ae_restrict_of_ae_restrict_of_subset (ord_connected_Ioo.uIoc_subset hsx₀ hsx), apply h_lipsch.mono, intros t ht, rw lipschitz_on_with_iff_norm_sub_le at ht, simp only [coe_nnabs] at ht, rw ← abs_of_nonneg (bound_nonneg t), exact ht hx (mem_ball_self ε_pos) }, rw ← is_O_norm_right, simp only [norm_eq_abs, abs_mul, abs_norm_eq_norm], exact bdd.is_O }, simp_rw pow_two, exact O₃.trans (O₁.mul O₂) }, have : ∀ᶠ x in 𝓝 x₀, ∫ t in a..s x, F x t = φ x (s x₀) + φ x₀ (s x) + (∫ t in s x₀..s x, F x t - F x₀ t) - φ x₀ (s x₀), { apply eventually.mono mem_nhds, rintros x ⟨hx : x ∈ ball x₀ ε, hsx : s x ∈ Ioo a₀ b₀⟩, have int₁ : interval_integrable (F x₀) volume a (s x₀) := hF_int_ball x₀ x₀_in ha hsx₀, have int₂ : interval_integrable (F x₀) volume (s x₀) (s x) := hF_int_ball x₀ x₀_in hsx₀ hsx, have int₃ : interval_integrable (F x) volume a (s x₀) := hF_int_ball x hx ha hsx₀, have int₄ : interval_integrable (F x) volume (s x₀) (s x) := hF_int_ball x hx hsx₀ hsx, dsimp [φ] {eta := ff}, rw [interval_integral.integral_sub int₄ int₂, add_sub, add_right_comm, sub_sub, interval_integral.integral_add_adjacent_intervals int₃ int₄], conv_rhs { congr, skip, rw add_comm }, rw interval_integral.integral_add_adjacent_intervals int₁ int₂, abel }, apply has_fderiv_at.congr_of_eventually_eq _ this, simpa using ((D₁.add D₂).add D₃).sub (has_fderiv_at_const (φ x₀ (s x₀)) x₀) } end local notation u ` ⬝ `:70 φ := continuous_linear_map.comp (continuous_linear_map.to_span_singleton ℝ u) φ variable [finite_dimensional ℝ H] /- A version of the above lemma using Floris' style statement. This does not reuse the above lemma, but copies the proof. -/ lemma has_fderiv_at_parametric_primitive_of_cont_diff' {F : H → ℝ → E} (hF : cont_diff ℝ 1 ↿F) {s : H → ℝ} (hs : cont_diff ℝ 1 s) (x₀ : H) (a : ℝ) : (interval_integrable (λ t, fderiv ℝ (λ x, F x t) x₀) volume a $ s x₀) ∧ has_fderiv_at (λ x : H, ∫ t in a..s x, F x t) ((∫ t in a..s x₀, fderiv ℝ (λ x, F x t) x₀) + F x₀ (s x₀) ⬝ fderiv ℝ s x₀) x₀ := begin set a₀ := min a (s x₀) - 1, set b₀ := max a (s x₀) + 1, have ha : a ∈ Ioo a₀ b₀, { dsimp [a₀, b₀], split, linarith [min_le_left a (s x₀)], linarith [le_max_left a (s x₀)] }, have ht₀ : s x₀ ∈ Ioo a₀ b₀, { dsimp [a₀, b₀], split, linarith [min_le_right a (s x₀)], linarith [le_max_right a (s x₀)] }, have cpct : is_compact (closed_ball x₀ 1 ×ˢ Icc a₀ b₀), from (proper_space.is_compact_closed_ball x₀ 1).prod is_compact_Icc, obtain ⟨M, F_bound⟩ : ∃ M : ℝ, ∀ x ∈ ball x₀ 1, ∀ t ∈ Ioo a₀ b₀, ‖F x t‖ ≤ M, { rcases cpct.bdd_above_image hF.continuous.norm.continuous_on with ⟨M, hM⟩, refine ⟨M, _⟩, exact λ x x_in t t_in, hM (mem_image_of_mem _ $ mk_mem_prod (ball_subset_closed_ball x_in) $ mem_Icc_of_Ioo t_in) }, obtain ⟨K, F_lip⟩ : ∃ K, ∀ t ∈ Ioo a₀ b₀, lipschitz_on_with K (λ x, F x t) (ball x₀ 1), { have conv : convex ℝ (closed_ball x₀ 1 ×ˢ Icc a₀ b₀), from (convex_closed_ball x₀ 1).prod (convex_Icc a₀ b₀), rcases hF.lipschitz_on_with le_rfl conv cpct with ⟨K, hK⟩, use K, intros t t_in, rw [show (λ (x : H), F x t) = (uncurry F) ∘ (λ x : H, (x, t)), by { ext, simp }, ← mul_one K], apply hK.comp ((lipschitz_with.prod_mk_right t).lipschitz_on_with $ ball x₀ 1), rw maps_to', rintros ⟨x, s⟩ ⟨x', hx, h⟩, cases h, refine ⟨ball_subset_closed_ball hx, mem_Icc_of_Ioo t_in⟩ }, have cont_x : ∀ x, continuous (F x), from λ x, hF.continuous.comp (continuous.prod.mk x), have int_Icc : ∀ x, integrable_on (F x) (Icc a₀ b₀), from λ x, (cont_x x).continuous_on.integrable_on_Icc, have int_Ioo : ∀ x, integrable_on (F x) (Ioo a₀ b₀), from λ x, (int_Icc x).mono_set Ioo_subset_Icc_self, apply has_fderiv_at_parametric_primitive_of_lip' _ _ zero_lt_one ha ht₀ (λ x hx, (cont_x x).ae_strongly_measurable) (int_Ioo x₀) (cont_x x₀).continuous_at _ _ _ (continuous_at_const : continuous_at (λ (t : ℝ), (K : ℝ)) $ s x₀) (λ t, nnreal.coe_nonneg K), { apply ae_of_all, intro t, apply (cont_diff.has_strict_fderiv_at _ le_rfl).has_fderiv_at, rw show (λ x, F x t) = (uncurry F) ∘ (λ x, (x, t)), by { ext, simp }, exact hF.comp ((cont_diff_prod_mk_left t).of_le le_top) }, { exact (cont_diff.has_strict_fderiv_at hs le_rfl).has_fderiv_at }, { refl }, { apply continuous.ae_strongly_measurable, have : (λ t, fderiv ℝ (λ (x : H), F x t) x₀) = ((λ φ : H × ℝ →L[ℝ] E, φ.comp (inl ℝ H ℝ)) ∘ (fderiv ℝ $ uncurry F) ∘ (λ t, (x₀, t))), { ext t, have : has_fderiv_at (λ e, F e t) ((fderiv ℝ (uncurry F) (x₀, t)).comp (inl ℝ H ℝ)) x₀ := (hF.has_strict_fderiv_at le_rfl).has_fderiv_at.comp _ (has_fderiv_at_prod_mk_left _ _), rw [this.fderiv] }, rw this, clear this, exact (inl ℝ H ℝ).comp_rightL.continuous.comp ((hF.continuous_fderiv le_rfl).comp $ continuous.prod.mk x₀) }, { simp_rw [ae_restrict_iff' measurable_set_Ioo], refine eventually_of_forall (λ t t_in, _), rw nnabs_coe K, exact F_lip t t_in }, { exact integrable_on_const.mpr (or.inr measure_Ioo_lt_top) } end end section variables {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [complete_space E] {H : Type*} [normed_add_comm_group H] [normed_space ℝ H] [finite_dimensional ℝ H] open real continuous_linear_map asymptotics local notation u ` ⬝ `:70 φ := continuous_linear_map.comp (continuous_linear_map.to_span_singleton ℝ u) φ lemma cont_diff_parametric_primitive_of_cont_diff' {F : H → ℝ → E} {n : ℕ} (hF : cont_diff ℝ n ↿F) {s : H → ℝ} (hs : cont_diff ℝ n s) (a : ℝ) : cont_diff ℝ n (λ x : H, ∫ t in a..s x, F x t) := begin induction n with n ih generalizing F, { rw [with_top.coe_zero, cont_diff_zero] at *, exact continuous_parametric_interval_integral_of_continuous hF hs }, { have hF₁ : cont_diff ℝ 1 (↿F) := hF.one_of_succ, have hs₁ : cont_diff ℝ 1 s := hs.one_of_succ, have h : ∀ x, has_fderiv_at (λ x, ∫ t in a..s x, F x t) ((∫ t in a..s x, fderiv ℝ (λ x', F x' t) x) + F x (s x) ⬝ fderiv ℝ s x) x := λ x, (has_fderiv_at_parametric_primitive_of_cont_diff' hF₁ hs₁ x a).2, rw cont_diff_succ_iff_fderiv_apply, split, { exact λ x₀, ⟨_, h x₀⟩ }, { intro x, rw fderiv_eq h, apply cont_diff.add, { simp only [continuous_linear_map.coe_coe], have hD' : cont_diff ℝ n ↿(λ x₀ t, fderiv ℝ (λ x, F x t) x₀) := cont_diff.fderiv (hF.comp₂ cont_diff_snd cont_diff_fst.snd) cont_diff_fst le_rfl, have hD : cont_diff ℝ n ↿(λ x' a, (fderiv ℝ (λ e, F e a) x') x) := hD'.clm_apply cont_diff_const, convert ih hs.of_succ hD, ext x', refine continuous_linear_map.interval_integral_apply _ x, exact (continuous_curry x' hD'.continuous).interval_integrable _ _, }, { exact ((cont_diff_succ_iff_fderiv.mp hs).2.smul_right (hF.of_succ.comp $ cont_diff_id.prod hs.of_succ)).clm_apply cont_diff_const } } } end end section universe variables v u variables {E : Type u} variables [normed_add_comm_group E] [normed_space ℝ E] [complete_space E] {H : Type v} [normed_add_comm_group H] [normed_space ℝ H] [finite_dimensional ℝ H] /- Should we directly prove the version below?-/ lemma cont_diff_parametric_primitive_of_cont_diff {F : H → ℝ → E} {n : ℕ∞} (hF : cont_diff ℝ n ↿F) {s : H → ℝ} (hs : cont_diff ℝ n s) (a : ℝ) : cont_diff ℝ n (λ x : H, ∫ t in a..s x, F x t) := begin induction n using with_top.rec_top_coe, { rw cont_diff_top at *, exact λ n, cont_diff_parametric_primitive_of_cont_diff' (hF n) (hs n) a }, { exact cont_diff_parametric_primitive_of_cont_diff' hF hs a }, end lemma cont_diff_parametric_primitive_of_cont_diff'' {F : H → ℝ → E} {n : ℕ∞} (hF : cont_diff ℝ n ↿F) (a : ℝ) : cont_diff ℝ n (λ x : H × ℝ, ∫ t in a..x.2, F x.1 t) := cont_diff_parametric_primitive_of_cont_diff (hF.comp (cont_diff_fst.prod_map cont_diff_id)) cont_diff_snd a lemma cont_diff_parametric_integral_of_cont_diff {F : H → ℝ → E} {n : ℕ∞} (hF : cont_diff ℝ n ↿F) (a b : ℝ) : cont_diff ℝ n (λ x : H, ∫ t in a..b, F x t) := cont_diff_parametric_primitive_of_cont_diff hF cont_diff_const a lemma cont_diff.fderiv_parametric_integral {F : H → ℝ → E} (hF : cont_diff ℝ 1 ↿F) (a b : ℝ) : fderiv ℝ (λ x : H, ∫ t in a..b, F x t) = λ x : H, (∫ t in a..b, fderiv ℝ (λ x', F x' t) x) := begin ext x₀, cases has_fderiv_at_parametric_primitive_of_cont_diff' hF cont_diff_const x₀ a with int h, rw [h.fderiv, fderiv_const], simp only [continuous_linear_map.comp_zero, add_zero, pi.zero_apply] end end
From iris_logrel.F_mu_ref Require Export fundamental_binary. Inductive ctx_item := | CTX_Lam | CTX_AppL (e2 : expr) | CTX_AppR (e1 : expr) (* Products *) | CTX_PairL (e2 : expr) | CTX_PairR (e1 : expr) | CTX_Fst | CTX_Snd (* Sums *) | CTX_InjL | CTX_InjR | CTX_CaseL (e1 : expr) (e2 : expr) | CTX_CaseM (e0 : expr) (e2 : expr) | CTX_CaseR (e0 : expr) (e1 : expr) (* Recursive Types *) | CTX_Fold | CTX_Unfold (* Polymorphic Types *) | CTX_TLam | CTX_TApp (* Reference Types *) | CTX_Alloc | CTX_Load | CTX_StoreL (e2 : expr) | CTX_StoreR (e1 : expr). Fixpoint fill_ctx_item (ctx : ctx_item) (e : expr) : expr := match ctx with | CTX_Lam => Lam e | CTX_AppL e2 => App e e2 | CTX_AppR e1 => App e1 e | CTX_PairL e2 => Pair e e2 | CTX_PairR e1 => Pair e1 e | CTX_Fst => Fst e | CTX_Snd => Snd e | CTX_InjL => InjL e | CTX_InjR => InjR e | CTX_CaseL e1 e2 => Case e e1 e2 | CTX_CaseM e0 e2 => Case e0 e e2 | CTX_CaseR e0 e1 => Case e0 e1 e | CTX_Fold => Fold e | CTX_Unfold => Unfold e | CTX_TLam => TLam e | CTX_TApp => TApp e | CTX_Alloc => Alloc e | CTX_Load => Load e | CTX_StoreL e2 => Store e e2 | CTX_StoreR e1 => Store e1 e end. Definition ctx := list ctx_item. Definition fill_ctx (K : ctx) (e : expr) : expr := foldr fill_ctx_item e K. (** typed ctx *) Inductive typed_ctx_item : ctx_item → list type → type → list type → type → Prop := | TP_CTX_Lam Γ τ τ' : typed_ctx_item CTX_Lam (τ :: Γ) τ' Γ (TArrow τ τ') | TP_CTX_AppL Γ e2 τ τ' : typed Γ e2 τ → typed_ctx_item (CTX_AppL e2) Γ (TArrow τ τ') Γ τ' | TP_CTX_AppR Γ e1 τ τ' : typed Γ e1 (TArrow τ τ') → typed_ctx_item (CTX_AppR e1) Γ τ Γ τ' | TP_CTX_PairL Γ e2 τ τ' : typed Γ e2 τ' → typed_ctx_item (CTX_PairL e2) Γ τ Γ (TProd τ τ') | TP_CTX_PairR Γ e1 τ τ' : typed Γ e1 τ → typed_ctx_item (CTX_PairR e1) Γ τ' Γ (TProd τ τ') | TP_CTX_Fst Γ τ τ' : typed_ctx_item CTX_Fst Γ (TProd τ τ') Γ τ | TP_CTX_Snd Γ τ τ' : typed_ctx_item CTX_Snd Γ (TProd τ τ') Γ τ' | TP_CTX_InjL Γ τ τ' : typed_ctx_item CTX_InjL Γ τ Γ (TSum τ τ') | TP_CTX_InjR Γ τ τ' : typed_ctx_item CTX_InjR Γ τ' Γ (TSum τ τ') | TP_CTX_CaseL Γ e1 e2 τ1 τ2 τ' : typed (τ1 :: Γ) e1 τ' → typed (τ2 :: Γ) e2 τ' → typed_ctx_item (CTX_CaseL e1 e2) Γ (TSum τ1 τ2) Γ τ' | TP_CTX_CaseM Γ e0 e2 τ1 τ2 τ' : typed Γ e0 (TSum τ1 τ2) → typed (τ2 :: Γ) e2 τ' → typed_ctx_item (CTX_CaseM e0 e2) (τ1 :: Γ) τ' Γ τ' | TP_CTX_CaseR Γ e0 e1 τ1 τ2 τ' : typed Γ e0 (TSum τ1 τ2) → typed (τ1 :: Γ) e1 τ' → typed_ctx_item (CTX_CaseR e0 e1) (τ2 :: Γ) τ' Γ τ' | TP_CTX_Fold Γ τ : typed_ctx_item CTX_Fold Γ τ.[(TRec τ)/] Γ (TRec τ) | TP_CTX_Unfold Γ τ : typed_ctx_item CTX_Unfold Γ (TRec τ) Γ τ.[(TRec τ)/] | TP_CTX_TLam Γ τ : typed_ctx_item CTX_TLam (subst (ren (+1)) <$> Γ) τ Γ (TForall τ) | TP_CTX_TApp Γ τ τ' : typed_ctx_item CTX_TApp Γ (TForall τ) Γ τ.[τ'/] | TPCTX_Alloc Γ τ : typed_ctx_item CTX_Alloc Γ τ Γ (Tref τ) | TP_CTX_Load Γ τ : typed_ctx_item CTX_Load Γ (Tref τ) Γ τ | TP_CTX_StoreL Γ e2 τ : typed Γ e2 τ → typed_ctx_item (CTX_StoreL e2) Γ (Tref τ) Γ TUnit | TP_CTX_StoreR Γ e1 τ : typed Γ e1 (Tref τ) → typed_ctx_item (CTX_StoreR e1) Γ τ Γ TUnit. Lemma typed_ctx_item_typed k Γ τ Γ' τ' e : typed Γ e τ → typed_ctx_item k Γ τ Γ' τ' → typed Γ' (fill_ctx_item k e) τ'. Proof. induction 2; simpl; eauto using typed. Qed. Inductive typed_ctx: ctx → list type → type → list type → type → Prop := | TPCTX_nil Γ τ : typed_ctx nil Γ τ Γ τ | TPCTX_cons Γ1 τ1 Γ2 τ2 Γ3 τ3 k K : typed_ctx_item k Γ2 τ2 Γ3 τ3 → typed_ctx K Γ1 τ1 Γ2 τ2 → typed_ctx (k :: K) Γ1 τ1 Γ3 τ3. Lemma typed_ctx_typed K Γ τ Γ' τ' e : typed Γ e τ → typed_ctx K Γ τ Γ' τ' → typed Γ' (fill_ctx K e) τ'. Proof. induction 2; simpl; eauto using typed_ctx_item_typed. Qed. Lemma typed_ctx_n_closed K Γ τ Γ' τ' e : (∀ f, e.[upn (length Γ) f] = e) → typed_ctx K Γ τ Γ' τ' → ∀ f, (fill_ctx K e).[upn (length Γ') f] = (fill_ctx K e). Proof. intros H1 H2; induction H2; simpl; auto. induction H => f; asimpl; simpl in *; repeat match goal with H : _ |- _ => rewrite fmap_length in H end; try f_equal; eauto using typed_n_closed; try match goal with H : _ |- _ => eapply (typed_n_closed _ _ _ H) end. Qed. Definition ctx_refines (Γ : list type) (e e' : expr) (τ : type) := ∀ K thp σ v, typed_ctx K Γ τ [] TUnit → rtc step ([fill_ctx K e], ∅) (of_val v :: thp, σ) → ∃ thp' σ' v', rtc step ([fill_ctx K e'], ∅) (of_val v' :: thp', σ'). Notation "Γ ⊨ e '≤ctx≤' e' : τ" := (ctx_refines Γ e e' τ) (at level 74, e, e', τ at next level). Ltac fold_interp := match goal with | |- context [ interp_expr (interp_arrow (interp ?A) (interp ?A')) ?B (?C, ?D) ] => change (interp_expr (interp_arrow (interp A) (interp A')) B (C, D)) with (interp_expr (interp (TArrow A A')) B (C, D)) | |- context [ interp_expr (interp_prod (interp ?A) (interp ?A')) ?B (?C, ?D) ] => change (interp_expr (interp_prod (interp A) (interp A')) B (C, D)) with (interp_expr (interp (TProd A A')) B (C, D)) | |- context [ interp_expr (interp_prod (interp ?A) (interp ?A')) ?B (?C, ?D) ] => change (interp_expr (interp_prod (interp A) (interp A')) B (C, D)) with (interp_expr (interp (TProd A A')) B (C, D)) | |- context [ interp_expr (interp_sum (interp ?A) (interp ?A')) ?B (?C, ?D) ] => change (interp_expr (interp_sum (interp A) (interp A')) B (C, D)) with (interp_expr (interp (TSum A A')) B (C, D)) | |- context [ interp_expr (interp_rec (interp ?A)) ?B (?C, ?D) ] => change (interp_expr (interp_rec (interp A)) B (C, D)) with (interp_expr (interp (TRec A)) B (C, D)) | |- context [ interp_expr (interp_forall (interp ?A)) ?B (?C, ?D) ] => change (interp_expr (interp_forall (interp A)) B (C, D)) with (interp_expr (interp (TForall A)) B (C, D)) | |- context [ interp_expr (interp_ref (interp ?A)) ?B (?C, ?D) ] => change (interp_expr (interp_ref (interp A)) B (C, D)) with (interp_expr (interp (Tref A)) B (C, D)) end. Section bin_log_related_under_typed_ctx. Context `{heapG Σ, cfgSG Σ}. Lemma bin_log_related_under_typed_ctx Γ e e' τ Γ' τ' K : (∀ f, e.[upn (length Γ) f] = e) → (∀ f, e'.[upn (length Γ) f] = e') → typed_ctx K Γ τ Γ' τ' → Γ ⊨ e ≤log≤ e' : τ → Γ' ⊨ fill_ctx K e ≤log≤ fill_ctx K e' : τ'. Proof. revert Γ τ Γ' τ' e e'. induction K as [|k K]=> Γ τ Γ' τ' e e' H1 H2; simpl. - inversion_clear 1; trivial. - inversion_clear 1 as [|? ? ? ? ? ? ? ? Hx1 Hx2]. intros H3. specialize (IHK _ _ _ _ e e' H1 H2 Hx2 H3). inversion Hx1; subst; simpl; try fold_interp. + eapply bin_log_related_lam; eauto; match goal with H : _ |- _ => eapply (typed_ctx_n_closed _ _ _ _ _ _ _ H) end. + eapply bin_log_related_app; eauto using binary_fundamental. + eapply bin_log_related_app; eauto using binary_fundamental. + eapply bin_log_related_pair; eauto using binary_fundamental. + eapply bin_log_related_pair; eauto using binary_fundamental. + eapply bin_log_related_fst; eauto. + eapply bin_log_related_snd; eauto. + eapply bin_log_related_injl; eauto. + eapply bin_log_related_injr; eauto. + match goal with H : typed_ctx_item _ _ _ _ _ |- _ => inversion H; subst end. eapply bin_log_related_case; eauto using binary_fundamental; match goal with H : _ |- _ => eapply (typed_n_closed _ _ _ H) end. + match goal with H : typed_ctx_item _ _ _ _ _ |- _ => inversion H; subst end. eapply bin_log_related_case; eauto using binary_fundamental; try match goal with H : _ |- _ => eapply (typed_n_closed _ _ _ H) end; match goal with H : _ |- _ => eapply (typed_ctx_n_closed _ _ _ _ _ _ _ H) end. + match goal with H : typed_ctx_item _ _ _ _ _ |- _ => inversion H; subst end. eapply bin_log_related_case; eauto using binary_fundamental; try match goal with H : _ |- _ => eapply (typed_n_closed _ _ _ H) end; match goal with H : _ |- _ => eapply (typed_ctx_n_closed _ _ _ _ _ _ _ H) end. + eapply bin_log_related_fold; eauto. + eapply bin_log_related_unfold; eauto. + eapply bin_log_related_tlam; eauto with typeclass_instances. + eapply bin_log_related_tapp; eauto. + eapply bin_log_related_alloc; eauto. + eapply bin_log_related_load; eauto. + eapply bin_log_related_store; eauto using binary_fundamental. + eapply bin_log_related_store; eauto using binary_fundamental. Unshelve. all: trivial. Qed. End bin_log_related_under_typed_ctx.
{-# OPTIONS --warning=error #-} module UselessPrivatePrivate where private private postulate A : Set
[STATEMENT] lemma BIT_a: assumes "x \<noteq> y" " init \<in> {[x,y],[y,x]}" "qs \<in> lang (seq [Plus (Atom x) One, Atom y, Atom y])" shows "config'_rand BIT (type0 init x y) qs = (type0 init y x)" (is ?C) and b: "T\<^sub>p_on_rand' BIT (type0 init x y) qs = 1.5" (is ?T) [PROOF STATE] proof (prove) goal (1 subgoal): 1. Partial_Cost_Model.config'_rand BIT (type0 init x y) qs = type0 init y x &&& T\<^sub>p_on_rand' BIT (type0 init x y) qs = 15 / 10 [PROOF STEP] proof - [PROOF STATE] proof (state) goal (2 subgoals): 1. Partial_Cost_Model.config'_rand BIT (type0 init x y) qs = type0 init y x 2. T\<^sub>p_on_rand' BIT (type0 init x y) qs = 15 / 10 [PROOF STEP] from assms(3) [PROOF STATE] proof (chain) picking this: qs \<in> lang (seq [question (Atom x), Atom y, Atom y]) [PROOF STEP] have alt: "qs = [x,y,y] \<or> qs = [y,y]" [PROOF STATE] proof (prove) using this: qs \<in> lang (seq [question (Atom x), Atom y, Atom y]) goal (1 subgoal): 1. qs = [x, y, y] \<or> qs = [y, y] [PROOF STEP] apply(simp) [PROOF STATE] proof (prove) goal (1 subgoal): 1. qs \<in> {[], [x]} @@ {[y]} @@ {[y]} \<Longrightarrow> qs = [x, y, y] \<or> qs = [y, y] [PROOF STEP] by fastforce [PROOF STATE] proof (state) this: qs = [x, y, y] \<or> qs = [y, y] goal (2 subgoals): 1. Partial_Cost_Model.config'_rand BIT (type0 init x y) qs = type0 init y x 2. T\<^sub>p_on_rand' BIT (type0 init x y) qs = 15 / 10 [PROOF STEP] show ?C [PROOF STATE] proof (prove) goal (1 subgoal): 1. Partial_Cost_Model.config'_rand BIT (type0 init x y) qs = type0 init y x [PROOF STEP] using assms(1,2) alt [PROOF STATE] proof (prove) using this: x \<noteq> y init \<in> {[x, y], [y, x]} qs = [x, y, y] \<or> qs = [y, y] goal (1 subgoal): 1. Partial_Cost_Model.config'_rand BIT (type0 init x y) qs = type0 init y x [PROOF STEP] by (auto simp add: oneBIT_step) [PROOF STATE] proof (state) this: Partial_Cost_Model.config'_rand BIT (type0 init x y) qs = type0 init y x goal (1 subgoal): 1. T\<^sub>p_on_rand' BIT (type0 init x y) qs = 15 / 10 [PROOF STEP] show ?T [PROOF STATE] proof (prove) goal (1 subgoal): 1. T\<^sub>p_on_rand' BIT (type0 init x y) qs = 15 / 10 [PROOF STEP] using assms(1,2) alt [PROOF STATE] proof (prove) using this: x \<noteq> y init \<in> {[x, y], [y, x]} qs = [x, y, y] \<or> qs = [y, y] goal (1 subgoal): 1. T\<^sub>p_on_rand' BIT (type0 init x y) qs = 15 / 10 [PROOF STEP] by(auto simp add: oneBIT_step costBIT) [PROOF STATE] proof (state) this: T\<^sub>p_on_rand' BIT (type0 init x y) qs = 15 / 10 goal: No subgoals! [PROOF STEP] qed
From iris.proofmode Require Import tactics. From mwp Require Import mwp_adequacy. From logrel_ifc.lambda_sec Require Export lang typing fundamental_binary. From logrel_ifc.lambda_sec Require Import lattice. Section soundness. Class lambdasecPreG Σ := LambdaSecPreG { lambdasec_preG_iris :> invPreG Σ; secGpre_gen_heapG_left :> gen_heapPreG loc val Σ; secGpre_gen_heapG_right :> gen_heapPreG loc val Σ; }. Context `{SecurityLattice label}. Definition secΣ : gFunctors := #[invΣ; gen_heapΣ loc val; gen_heapΣ loc val]. Definition SI_init Σ (x : gen_heapG loc val Σ) := gen_heap_interp (hG := x) ∅. Instance SI_left_init_data `{!gen_heapPreG loc val Σ} : InitData (SI_init Σ). Proof. rewrite /InitData; iMod gen_heap_init as (?) "(?&?)"; eauto. Qed. Definition SI Σ (x : gen_heapG loc val Σ) (σ : state) := gen_heap_interp σ. Theorem soundness_semantic Σ `{lambdasecPreG Σ} e (b1 b2 : bool) (ℓ ℓ' : label) (rd : Reds (e.[# (BoolV b1)/]) ∅) (rd' : Reds (e.[# (BoolV b2)/]) ∅) (flow1 : ℓ' ⋢ ζ) (flow2 : ℓ ⊑ ζ) : (∀ (Hcnd : secG Σ), [ TBool @ (LLabel ℓ') ] ⊨ e ≤ₗ e : TBool @ (LLabel ℓ)) → end_val rd = end_val rd'. Proof. intros Hlog. eapply (mwp_left_adequacy (SI Σ) (SI Σ) (SI_init Σ) (SI_init Σ) _ _ _ _ _ (λ x _ y _, x = y)). iIntros ([? [leftG rightG]]). rewrite /SI_init /SI /=. iIntros "[Hl Hr]". iModIntro. iFrame. iApply (mwp_wand_r with "[-]"); iSplitL. { iApply (Hlog (SecG _ _ leftG rightG) [] [] [(BoolV b1, BoolV b2)] with "[]"). iSplit; first rewrite /env_coherent //. iApply interp_env_cons. iSplit; last by iApply interp_env_nil. rewrite interp_sec_def interp_bool_def /=. rewrite bool_decide_eq_false_2 //. rewrite !interp_un_sec_def !interp_un_bool_def; auto. } iIntros (? ? ?) "H /=". rewrite interp_sec_def interp_bool_def bool_decide_eq_true_2 //=. by iDestruct "H" as (c1 c2) "(->&->&->)". Qed. Theorem soundness_tini (e : expr) v1 v2 v1' v2' ℓ ℓ' : ℓ' ⋢ ζ → ℓ ⊑ ζ → [TBool @ (LLabel ℓ')] # (LLabel ℓ) ⊢ₜ e : TBool @ (LLabel ℓ) → [] # (LLabel ℓ) ⊢ₜ #v1 : TBool @ (LLabel ℓ') → [] # (LLabel ℓ) ⊢ₜ #v2 : TBool @ (LLabel ℓ') → ((∃ σ1, rtc pstep (e.[# v1/], ∅) (# v1', σ1)) ∧ (∃ σ2, rtc pstep (e.[# v2/], ∅) (# v2', σ2))) → v1' = v2'. Proof. intros Hflow1 Hflow2 Htpe Htp1 Htp2 [Hrd1 Hrd2]. destruct (bool_val_typed _ _ _ _ v1 _ Htp1); eauto using to_of_val; [simplify_eq]. destruct (bool_val_typed _ _ _ _ v2 _ Htp2); eauto using to_of_val; [simplify_eq]. destruct Hrd1 as [σ1 Hrd1]. destruct Hrd2 as [σ2 Hrd2]. destruct (rtc_nsteps _ _ Hrd1) as [n1 Hrd1']. destruct (rtc_nsteps _ _ Hrd2) as [n2 Hrd2']. assert (lambdasecPreG #[secΣ]) as HPG. { constructor; apply _. } set (Hrd1'' := {| reds := Hrd1' |}). set (Hrd2'' := {| reds := Hrd2' |}). apply (soundness_semantic #[secΣ] _ _ _ ℓ ℓ' Hrd1'' Hrd2''); [done..|]. intros ?. by eapply binary_fundamental. Qed. End soundness. Section soundness_tp. Instance tpSecurityLattice : SecurityLattice tplabel := { ζ := L }. Notation H := (LLabel H). Notation L := (LLabel L). Theorem soundness_tini_tp (e : expr) v1 v2 v1' v2' : [TBool @ H] # L ⊢ₜ e : TBool @ L → [] # L ⊢ₜ #v1 : TBool @ H → [] # L ⊢ₜ #v2 : TBool @ H → ((∃ σ1, rtc pstep (e.[# v1/], ∅) (# v1', σ1)) ∧ (∃ σ2, rtc pstep (e.[# v2/], ∅) (# v2', σ2))) → v1' = v2'. Proof. by apply soundness_tini. Qed. End soundness_tp.
Require Import Coq.Lists.List. Require Import Coq.micromega.Lia. Require Import Coq.Arith.Peano_dec. Require Import Coq.ZArith.ZArith. Require Import Coq.Arith.Arith. Require Import Coq.Classes.Morphisms. Require Import Coq.Numbers.Natural.Peano.NPeano. Require Import Crypto.Util.NatUtil. Require Import Crypto.Util.Pointed. Require Import Crypto.Util.Prod. Require Import Crypto.Util.Decidable. Require Crypto.Util.Option. Require Export Crypto.Util.FixCoqMistakes. Require Export Crypto.Util.Tactics.BreakMatch. Require Export Crypto.Util.Tactics.DestructHead. Require Import Crypto.Util.Tactics.SpecializeBy. Require Import Crypto.Util.Tactics.RewriteHyp. Require Import Crypto.Util.Tactics.ConstrFail. Require Import Crypto.Util.Tactics.SplitInContext. Import ListNotations. Local Open Scope list_scope. Scheme Equality for list. Definition list_case {A} (P : list A -> Type) (N : P nil) (C : forall x xs, P (cons x xs)) (ls : list A) : P ls := match ls return P ls with | nil => N | cons x xs => C x xs end. Definition list_case_nodep {A} (P : Type) (N : P) (C : A -> list A -> P) (ls : list A) : P := match ls with | nil => N | cons x xs => C x xs end. Global Instance list_rect_Proper_dep_gen {A P} (RP : forall x : list A, P x -> P x -> Prop) : Proper (RP nil ==> forall_relation (fun x => forall_relation (fun xs => RP xs ==> RP (cons x xs))) ==> forall_relation RP) (@list_rect A P) | 10. Proof. cbv [forall_relation respectful]; intros N N' HN C C' HC ls. induction ls as [|l ls IHls]; cbn [list_rect]; repeat first [ apply IHls | apply HC | apply HN | progress intros | reflexivity ]. Qed. Global Instance list_rect_Proper_dep {A P} : Proper (eq ==> forall_relation (fun _ => forall_relation (fun _ => forall_relation (fun _ => eq))) ==> forall_relation (fun _ => eq)) (@list_rect A P) | 1. Proof. cbv [forall_relation respectful Proper]; intros; eapply (@list_rect_Proper_dep_gen A P (fun _ => eq)); cbv [forall_relation respectful]; intros; subst; eauto. Qed. Global Instance list_rect_arrow_Proper_dep {A P Q} : Proper ((eq ==> eq) ==> forall_relation (fun _ => forall_relation (fun _ => (eq ==> eq) ==> (eq ==> eq))) ==> forall_relation (fun _ => eq ==> eq)) (@list_rect A (fun x => P x -> Q x)) | 10. Proof. cbv [forall_relation respectful Proper]; intros; eapply (@list_rect_Proper_dep_gen A (fun x => P x -> Q x) (fun _ => eq ==> eq)%signature); intros; subst; eauto. Qed. Global Instance list_case_Proper_dep {A P} : Proper (eq ==> forall_relation (fun _ => forall_relation (fun _ => eq)) ==> forall_relation (fun _ => eq)) (@list_case A P) | 1. Proof. cbv [forall_relation]; intros N N' ? C C' HC ls; subst N'; revert N; destruct ls; eauto. Qed. Global Instance list_rect_Proper_gen {A P} R : Proper (R ==> (eq ==> eq ==> R ==> R) ==> eq ==> R) (@list_rect A (fun _ => P)) | 10. Proof. repeat intro; subst; apply (@list_rect_Proper_dep_gen A (fun _ => P) (fun _ => R)); cbv [forall_relation respectful] in *; eauto. Qed. Global Instance list_rect_Proper {A P} : Proper (eq ==> pointwise_relation _ (pointwise_relation _ (pointwise_relation _ eq)) ==> eq ==> eq) (@list_rect A (fun _ => P)). Proof. repeat intro; subst; apply (@list_rect_Proper_dep A (fun _ => P)); eauto. Qed. Global Instance list_rect_arrow_Proper {A P Q} : Proper ((eq ==> eq) ==> (eq ==> eq ==> (eq ==> eq) ==> eq ==> eq) ==> eq ==> eq ==> eq) (@list_rect A (fun _ => P -> Q)) | 10. Proof. eapply list_rect_Proper_gen. Qed. Global Instance list_case_Proper {A P} : Proper (eq ==> pointwise_relation _ (pointwise_relation _ eq) ==> eq ==> eq) (@list_case A (fun _ => P)). Proof. repeat intro; subst; apply (@list_case_Proper_dep A (fun _ => P)); eauto. Qed. Create HintDb distr_length discriminated. Create HintDb simpl_set_nth discriminated. Create HintDb simpl_update_nth discriminated. Create HintDb simpl_nth_default discriminated. Create HintDb simpl_nth_error discriminated. Create HintDb simpl_firstn discriminated. Create HintDb simpl_skipn discriminated. Create HintDb simpl_fold_right discriminated. Create HintDb simpl_sum_firstn discriminated. Create HintDb push_map discriminated. Create HintDb push_combine discriminated. Create HintDb push_flat_map discriminated. Create HintDb push_fold_right discriminated. Create HintDb push_partition discriminated. Create HintDb pull_nth_error discriminated. Create HintDb push_nth_error discriminated. Create HintDb pull_nth_default discriminated. Create HintDb push_nth_default discriminated. Create HintDb pull_firstn discriminated. Create HintDb push_firstn discriminated. Create HintDb pull_skipn discriminated. Create HintDb push_skipn discriminated. Create HintDb push_sum discriminated. Create HintDb pull_update_nth discriminated. Create HintDb push_update_nth discriminated. Create HintDb znonzero discriminated. Hint Rewrite @app_length @rev_length @map_length @seq_length @fold_left_length @split_length_l @split_length_r @firstn_length @combine_length @prod_length : distr_length. Global Hint Extern 1 => progress autorewrite with distr_length in * : distr_length. Ltac distr_length := autorewrite with distr_length in *; try solve [simpl in *; intros; (idtac + exfalso); lia]. Module Export List. Local Set Implicit Arguments. Import ListNotations. (** From the 8.6 Standard Library *) Section Elts. Variable A : Type. (** Results about [nth_error] *) Lemma nth_error_In l n (x : A) : nth_error l n = Some x -> In x l. Proof using Type. revert n. induction l as [|a l IH]; intros [|n]; simpl; try easy. - injection 1; auto. - eauto. Qed. End Elts. Section Map. Variables (A : Type) (B : Type). Variable f : A -> B. Lemma map_nil : forall A B (f : A -> B), map f nil = nil. Proof. reflexivity. Qed. Lemma map_cons (x:A)(l:list A) : map f (x::l) = (f x) :: (map f l). Proof using Type. reflexivity. Qed. Lemma map_repeat x n : map f (List.repeat x n) = List.repeat (f x) n. Proof. induction n; simpl List.repeat; simpl map; congruence. Qed. End Map. Hint Rewrite @map_cons @map_nil @map_repeat : push_map. Hint Rewrite @map_app : push_map. Section FlatMap. Lemma flat_map_nil {A B} (f:A->list B) : List.flat_map f (@nil A) = nil. Proof. reflexivity. Qed. Lemma flat_map_cons {A B} (f:A->list B) x xs : (List.flat_map f (x::xs) = (f x++List.flat_map f xs))%list. Proof. reflexivity. Qed. End FlatMap. Hint Rewrite @flat_map_cons @flat_map_nil : push_flat_map. Lemma rev_cons {A} x ls : @rev A (x :: ls) = rev ls ++ [x]. Proof. reflexivity. Qed. Hint Rewrite @rev_cons : list. Section FoldRight. Context {A B} (f:B->A->A). Lemma fold_right_nil : forall {A B} (f:B->A->A) a, List.fold_right f a nil = a. Proof. reflexivity. Qed. Lemma fold_right_cons : forall a b bs, fold_right f a (b::bs) = f b (fold_right f a bs). Proof. reflexivity. Qed. Lemma fold_right_snoc a x ls: @fold_right A B f a (ls ++ [x]) = fold_right f (f x a) ls. Proof. rewrite <-(rev_involutive ls), <-rev_cons. rewrite !fold_left_rev_right; reflexivity. Qed. End FoldRight. Hint Rewrite @fold_right_nil @fold_right_cons @fold_right_snoc : simpl_fold_right push_fold_right. Section Partition. Lemma partition_nil {A} (f:A->_) : partition f nil = (nil, nil). Proof. reflexivity. Qed. Lemma partition_cons {A} (f:A->_) x xs : partition f (x::xs) = if f x then (x :: (fst (partition f xs)), (snd (partition f xs))) else ((fst (partition f xs)), x :: (snd (partition f xs))). Proof. cbv [partition]; break_match; reflexivity. Qed. End Partition. Hint Rewrite @partition_nil @partition_cons : push_partition. Lemma in_seq len start n : In n (seq start len) <-> start <= n < start+len. Proof. revert start. induction len as [|len IHlen]; simpl; intros. - rewrite <- plus_n_O. split;[easy|]. intros (H,H'). apply (Lt.lt_irrefl _ (Lt.le_lt_trans _ _ _ H H')). - rewrite IHlen, <- plus_n_Sm; simpl; split. * intros [H|H]; subst; intuition auto with arith. * intros (H,H'). destruct (Lt.le_lt_or_eq _ _ H); intuition. Qed. Section Facts. Variable A : Type. Theorem length_zero_iff_nil (l : list A): length l = 0 <-> l=[]. Proof using Type. split; [now destruct l | now intros ->]. Qed. End Facts. Section Cutting. Variable A : Type. Local Notation firstn := (@firstn A). Lemma firstn_nil n: firstn n [] = []. Proof using Type. induction n; now simpl. Qed. Lemma firstn_cons n a l: firstn (S n) (a::l) = a :: (firstn n l). Proof using Type. now simpl. Qed. Lemma firstn_all l: firstn (length l) l = l. Proof. induction l as [| ? ? H]; simpl; [reflexivity | now rewrite H]. Qed. Lemma firstn_all2 n: forall (l:list A), (length l) <= n -> firstn n l = l. Proof using Type. induction n as [|k iHk]. - intro l. inversion 1 as [H1|?]. rewrite (length_zero_iff_nil l) in H1. subst. now simpl. - destruct l as [|x xs]; simpl. * now reflexivity. * simpl. intro H. apply Peano.le_S_n in H. f_equal. apply iHk, H. Qed. Lemma firstn_O l: firstn 0 l = []. Proof using Type. now simpl. Qed. Lemma firstn_le_length n: forall l:list A, length (firstn n l) <= n. Proof using Type. induction n as [|k iHk]; simpl; [auto | destruct l as [|x xs]; simpl]. - auto with arith. - apply le_n_S, iHk. Qed. Lemma firstn_length_le: forall l:list A, forall n:nat, n <= length l -> length (firstn n l) = n. Proof using Type. induction l as [|x xs Hrec]. - simpl. intros n H. apply le_n_0_eq in H. rewrite <- H. now simpl. - destruct n as [|n]. * now simpl. * simpl. intro H. apply le_S_n in H. now rewrite (Hrec n H). Qed. Lemma firstn_app n: forall l1 l2, firstn n (l1 ++ l2) = (firstn n l1) ++ (firstn (n - length l1) l2). Proof using Type. induction n as [|k iHk]; intros l1 l2. - now simpl. - destruct l1 as [|x xs]. * unfold List.firstn at 2, length. now rewrite 2!app_nil_l, <- minus_n_O. * rewrite <- app_comm_cons. simpl. f_equal. apply iHk. Qed. Lemma firstn_app_2 n: forall l1 l2, firstn ((length l1) + n) (l1 ++ l2) = l1 ++ firstn n l2. Proof using Type. induction n as [| k iHk];intros l1 l2. - unfold List.firstn at 2. rewrite <- plus_n_O, app_nil_r. rewrite firstn_app. rewrite <- minus_diag_reverse. unfold List.firstn at 2. rewrite app_nil_r. apply firstn_all. - destruct l2 as [|x xs]. * simpl. rewrite app_nil_r. apply firstn_all2. auto with arith. * rewrite firstn_app. assert (H0 : (length l1 + S k - length l1) = S k). auto with arith. rewrite H0, firstn_all2; [reflexivity | auto with arith]. Qed. Lemma firstn_firstn: forall l:list A, forall i j : nat, firstn i (firstn j l) = firstn (min i j) l. Proof. induction l as [|x xs Hl]. - intros. simpl. now rewrite ?firstn_nil. - destruct i. * intro. now simpl. * destruct j. + now simpl. + simpl. f_equal. apply Hl. Qed. End Cutting. (** new operations *) Definition enumerate {A} (ls : list A) : list (nat * A) := combine (seq 0 (length ls)) ls. End List. Hint Rewrite @firstn_skipn : simpl_firstn. Hint Rewrite @firstn_skipn : simpl_skipn. Hint Rewrite @firstn_nil @firstn_cons @List.firstn_all @firstn_O @firstn_app_2 @List.firstn_firstn : push_firstn. Hint Rewrite @firstn_nil @firstn_cons @List.firstn_all @firstn_O @firstn_app_2 @List.firstn_firstn : simpl_firstn. Hint Rewrite @firstn_app : push_firstn. Hint Rewrite <- @firstn_cons @firstn_app @List.firstn_firstn : pull_firstn. Hint Rewrite @firstn_all2 @removelast_firstn @firstn_removelast using lia : push_firstn. Hint Rewrite @firstn_all2 @removelast_firstn @firstn_removelast using lia : simpl_firstn. Local Arguments value / _ _. Local Arguments error / _. Definition sum_firstn l n := fold_right Z.add 0%Z (firstn n l). Definition sum xs := sum_firstn xs (length xs). Section map2. Context {A B C} (f : A -> B -> C). Fixpoint map2 (la : list A) (lb : list B) : list C := match la, lb with | nil, _ => nil | _, nil => nil | a :: la', b :: lb' => f a b :: map2 la' lb' end. End map2. (* xs[n] := f xs[n] *) Fixpoint update_nth {T} n f (xs:list T) {struct n} := match n with | O => match xs with | nil => nil | x'::xs' => f x'::xs' end | S n' => match xs with | nil => nil | x'::xs' => x'::update_nth n' f xs' end end. (* xs[n] := x *) Definition set_nth {T} n x (xs:list T) := update_nth n (fun _ => x) xs. Definition splice_nth {T} n (x:T) xs := firstn n xs ++ x :: skipn (S n) xs. Hint Unfold splice_nth : core. Fixpoint take_while {T} (f : T -> bool) (ls : list T) : list T := match ls with | nil => nil | cons x xs => if f x then x :: @take_while T f xs else nil end. Fixpoint drop_while {T} (f : T -> bool) (ls : list T) : list T := match ls with | nil => nil | cons x xs => if f x then @drop_while T f xs else x :: xs end. Ltac boring := simpl; intuition auto with zarith datatypes; repeat match goal with | [ H : _ |- _ ] => rewrite H; clear H | [ |- context[match ?pf with end] ] => solve [ case pf ] | _ => progress autounfold in * | _ => progress autorewrite with core | _ => progress simpl in * | _ => progress intuition auto with zarith datatypes end; eauto. Ltac boring_list := repeat match goal with | _ => progress boring | _ => progress autorewrite with distr_length simpl_nth_default simpl_update_nth simpl_set_nth simpl_nth_error in * end. Lemma nth_default_cons : forall {T} (x u0 : T) us, nth_default x (u0 :: us) 0 = u0. Proof. auto. Qed. Hint Rewrite @nth_default_cons : simpl_nth_default. Hint Rewrite @nth_default_cons : push_nth_default. Lemma nth_default_cons_S : forall {A} us (u0 : A) n d, nth_default d (u0 :: us) (S n) = nth_default d us n. Proof. boring. Qed. Hint Rewrite @nth_default_cons_S : simpl_nth_default. Hint Rewrite @nth_default_cons_S : push_nth_default. Lemma nth_default_nil : forall {T} n (d : T), nth_default d nil n = d. Proof. induction n; boring. Qed. Hint Rewrite @nth_default_nil : simpl_nth_default. Hint Rewrite @nth_default_nil : push_nth_default. Lemma nth_error_nil_error : forall {A} n, nth_error (@nil A) n = None. Proof. induction n; boring. Qed. Hint Rewrite @nth_error_nil_error : simpl_nth_error. Ltac nth_tac' := intros; simpl in *; unfold error,value in *; repeat progress (match goal with | [ |- context[nth_error nil ?n] ] => rewrite nth_error_nil_error | [ H: ?x = Some _ |- context[match ?x with Some _ => ?a | None => ?a end ] ] => destruct x | [ H: ?x = None _ |- context[match ?x with Some _ => ?a | None => ?a end ] ] => destruct x | [ |- context[match ?x with Some _ => ?a | None => ?a end ] ] => destruct x | [ |- context[match nth_error ?xs ?i with Some _ => _ | None => _ end ] ] => case_eq (nth_error xs i); intros | [ |- context[(if lt_dec ?a ?b then _ else _) = _] ] => destruct (lt_dec a b) | [ |- context[_ = (if lt_dec ?a ?b then _ else _)] ] => destruct (lt_dec a b) | [ H: context[(if lt_dec ?a ?b then _ else _) = _] |- _ ] => destruct (lt_dec a b) | [ H: context[_ = (if lt_dec ?a ?b then _ else _)] |- _ ] => destruct (lt_dec a b) | [ H: _ /\ _ |- _ ] => destruct H | [ H: Some _ = Some _ |- _ ] => injection H; clear H; intros; subst | [ H: None = Some _ |- _ ] => inversion H | [ H: Some _ = None |- _ ] => inversion H | [ |- Some _ = Some _ ] => apply f_equal end); eauto; try (autorewrite with list in *); try lia; eauto. Lemma nth_error_map {A B f n l} : nth_error (@map A B f l) n = option_map f (nth_error l n). Proof. revert n; induction l, n; nth_tac'. Qed. Lemma nth_error_map_ex : forall A B (f:A->B) i xs y, nth_error (map f xs) i = Some y -> exists x, nth_error xs i = Some x /\ f x = y. Proof. intros *; rewrite nth_error_map; edestruct nth_error; nth_tac'. Qed. Lemma nth_error_seq : forall i start len, nth_error (seq start len) i = if lt_dec i len then Some (start + i) else None. induction i as [|? IHi]; destruct len; nth_tac'; erewrite IHi; nth_tac'. Qed. Lemma nth_error_error_length : forall A i (xs:list A), nth_error xs i = None -> i >= length xs. Proof. induction i as [|? IHi]; destruct xs; nth_tac'; try match goal with H : _ |- _ => specialize (IHi _ H) end; lia. Qed. Lemma nth_error_value_length : forall A i (xs:list A) x, nth_error xs i = Some x -> i < length xs. Proof. induction i as [|? IHi]; destruct xs; nth_tac'; try match goal with H : _ |- _ => specialize (IHi _ _ H) end; lia. Qed. Lemma nth_error_length_error : forall A i (xs:list A), i >= length xs -> nth_error xs i = None. Proof. induction i as [|? IHi]; destruct xs; nth_tac'; rewrite IHi by lia; auto. Qed. Global Hint Resolve nth_error_length_error : core. Hint Rewrite @nth_error_length_error using lia : simpl_nth_error. Lemma map_nth_default : forall (A B : Type) (f : A -> B) n x y l, (n < length l) -> nth_default y (map f l) n = f (nth_default x l n). Proof. intros A B f n x y l H. unfold nth_default. erewrite map_nth_error. reflexivity. nth_tac'. let H0 := match goal with H0 : _ = None |- _ => H0 end in pose proof (nth_error_error_length A n l H0). lia. Qed. Hint Rewrite @map_nth_default using lia : push_nth_default. Ltac nth_tac := repeat progress (try nth_tac'; try (match goal with | [ H: nth_error (map _ _) _ = Some _ |- _ ] => destruct (nth_error_map_ex _ _ _ _ _ _ H); clear H | [ H: nth_error (seq _ _) _ = Some _ |- _ ] => rewrite nth_error_seq in H | [H: nth_error _ _ = None |- _ ] => specialize (nth_error_error_length _ _ _ H); intro; clear H end)). Lemma app_cons_app_app : forall T xs (y:T) ys, xs ++ y :: ys = (xs ++ (y::nil)) ++ ys. Proof. induction xs; boring. Qed. Lemma unfold_set_nth {T} n x : forall xs, @set_nth T n x xs = match n with | O => match xs with | nil => nil | x'::xs' => x::xs' end | S n' => match xs with | nil => nil | x'::xs' => x'::set_nth n' x xs' end end. Proof. induction n; destruct xs; reflexivity. Qed. Lemma simpl_set_nth_0 {T} x : forall xs, @set_nth T 0 x xs = match xs with | nil => nil | x'::xs' => x::xs' end. Proof. intro; rewrite unfold_set_nth; reflexivity. Qed. Lemma simpl_set_nth_S {T} x n : forall xs, @set_nth T (S n) x xs = match xs with | nil => nil | x'::xs' => x'::set_nth n x xs' end. Proof. intro; rewrite unfold_set_nth; reflexivity. Qed. Hint Rewrite @simpl_set_nth_S @simpl_set_nth_0 : simpl_set_nth. Lemma update_nth_ext {T} f g n : forall xs, (forall x, nth_error xs n = Some x -> f x = g x) -> @update_nth T n f xs = @update_nth T n g xs. Proof. induction n as [|n IHn]; destruct xs; simpl; intros H; try rewrite IHn; try rewrite H; try congruence; trivial. Qed. Global Instance update_nth_Proper {T} : Proper (eq ==> pointwise_relation _ eq ==> eq ==> eq) (@update_nth T). Proof. repeat intro; subst; apply update_nth_ext; trivial. Qed. Global Instance update_nth_Proper_eq {A} : Proper (eq ==> (eq ==> eq) ==> eq ==> eq) (@update_nth A) | 1. Proof. repeat intro; subst; apply update_nth_Proper; repeat intro; eauto. Qed. Lemma update_nth_id_eq_specific {T} f n : forall (xs : list T) (H : forall x, nth_error xs n = Some x -> f x = x), update_nth n f xs = xs. Proof. induction n as [|n IHn]; destruct xs; simpl; intros H; try rewrite IHn; try rewrite H; unfold value in *; try congruence; assumption. Qed. Hint Rewrite @update_nth_id_eq_specific using congruence : simpl_update_nth. Lemma update_nth_id_eq : forall {T} f (H : forall x, f x = x) n (xs : list T), update_nth n f xs = xs. Proof. intros; apply update_nth_id_eq_specific; trivial. Qed. Hint Rewrite @update_nth_id_eq using congruence : simpl_update_nth. Lemma update_nth_id : forall {T} n (xs : list T), update_nth n (fun x => x) xs = xs. Proof. intros; apply update_nth_id_eq; trivial. Qed. Hint Rewrite @update_nth_id : simpl_update_nth. Lemma nth_update_nth : forall m {T} (xs:list T) (n:nat) (f:T -> T), nth_error (update_nth m f xs) n = if eq_nat_dec n m then option_map f (nth_error xs n) else nth_error xs n. Proof. induction m as [|? IHm]. { destruct n, xs; auto. } { destruct xs, n; intros; simpl; auto; [ | rewrite IHm ]; clear IHm; edestruct eq_nat_dec; reflexivity. } Qed. Hint Rewrite @nth_update_nth : push_nth_error. Hint Rewrite <- @nth_update_nth : pull_nth_error. Lemma length_update_nth : forall {T} i f (xs:list T), length (update_nth i f xs) = length xs. Proof. induction i, xs; boring. Qed. Hint Rewrite @length_update_nth : distr_length. Lemma nth_set_nth : forall m {T} (xs:list T) (n:nat) x, nth_error (set_nth m x xs) n = if eq_nat_dec n m then (if lt_dec n (length xs) then Some x else None) else nth_error xs n. Proof. intros m T xs n x; unfold set_nth; rewrite nth_update_nth. destruct (nth_error xs n) eqn:?, (lt_dec n (length xs)) as [p|p]; rewrite <- nth_error_Some in p; solve [ reflexivity | exfalso; apply p; congruence ]. Qed. Hint Rewrite @nth_set_nth : push_nth_error. Lemma length_set_nth : forall {T} i x (xs:list T), length (set_nth i x xs) = length xs. Proof. intros; apply length_update_nth. Qed. Hint Rewrite @length_set_nth : distr_length. Lemma nth_error_length_exists_value : forall {A} (i : nat) (xs : list A), (i < length xs)%nat -> exists x, nth_error xs i = Some x. Proof. induction i, xs; boring; try lia. Qed. Lemma nth_error_length_not_error : forall {A} (i : nat) (xs : list A), nth_error xs i = None -> (i < length xs)%nat -> False. Proof. intros A i xs H H0. destruct (nth_error_length_exists_value i xs); intuition; congruence. Qed. Lemma nth_error_value_eq_nth_default : forall {T} i (x : T) xs, nth_error xs i = Some x -> forall d, nth_default d xs i = x. Proof. unfold nth_default; boring. Qed. Hint Rewrite @nth_error_value_eq_nth_default using eassumption : simpl_nth_default. Lemma skipn0 : forall {T} (xs:list T), skipn 0 xs = xs. Proof. auto. Qed. Lemma destruct_repeat : forall {A} xs y, (forall x : A, In x xs -> x = y) -> xs = nil \/ exists xs', xs = y :: xs' /\ (forall x : A, In x xs' -> x = y). Proof. destruct xs as [|? xs]; intros; try tauto. right. exists xs; split. + f_equal; auto using in_eq. + intros; auto using in_cons. Qed. Lemma splice_nth_equiv_update_nth : forall {T} n f d (xs:list T), splice_nth n (f (nth_default d xs n)) xs = if lt_dec n (length xs) then update_nth n f xs else xs ++ (f d)::nil. Proof. induction n, xs; boring_list; break_match; auto; lia. Qed. Lemma splice_nth_equiv_update_nth_update : forall {T} n f d (xs:list T), n < length xs -> splice_nth n (f (nth_default d xs n)) xs = update_nth n f xs. Proof. intros. rewrite splice_nth_equiv_update_nth; break_match; auto; lia. Qed. Lemma splice_nth_equiv_update_nth_snoc : forall {T} n f d (xs:list T), n >= length xs -> splice_nth n (f (nth_default d xs n)) xs = xs ++ (f d)::nil. Proof. intros. rewrite splice_nth_equiv_update_nth; break_match; auto; lia. Qed. Definition IMPOSSIBLE {T} : list T. exact nil. Qed. Ltac remove_nth_error := repeat match goal with | _ => exfalso; solve [ eauto using @nth_error_length_not_error ] | [ |- context[match nth_error ?ls ?n with _ => _ end] ] => destruct (nth_error ls n) eqn:? end. Lemma update_nth_equiv_splice_nth: forall {T} n f (xs:list T), update_nth n f xs = if lt_dec n (length xs) then match nth_error xs n with | Some v => splice_nth n (f v) xs | None => IMPOSSIBLE end else xs. Proof. induction n as [|? IHn]; destruct xs; intros; autorewrite with simpl_update_nth simpl_nth_default in *; simpl in *; try (erewrite IHn; clear IHn); auto. repeat break_match; remove_nth_error; try reflexivity; try lia. Qed. Lemma splice_nth_equiv_set_nth : forall {T} n x (xs:list T), splice_nth n x xs = if lt_dec n (length xs) then set_nth n x xs else xs ++ x::nil. Proof. intros T n x xs; rewrite splice_nth_equiv_update_nth with (f := fun _ => x); auto. Qed. Lemma splice_nth_equiv_set_nth_set : forall {T} n x (xs:list T), n < length xs -> splice_nth n x xs = set_nth n x xs. Proof. intros T n x xs H; rewrite splice_nth_equiv_update_nth_update with (f := fun _ => x); auto. Qed. Lemma splice_nth_equiv_set_nth_snoc : forall {T} n x (xs:list T), n >= length xs -> splice_nth n x xs = xs ++ x::nil. Proof. intros T n x xs H; rewrite splice_nth_equiv_update_nth_snoc with (f := fun _ => x); auto. Qed. Lemma set_nth_equiv_splice_nth: forall {T} n x (xs:list T), set_nth n x xs = if lt_dec n (length xs) then splice_nth n x xs else xs. Proof. intros T n x xs; unfold set_nth; rewrite update_nth_equiv_splice_nth with (f := fun _ => x); auto. repeat break_match; remove_nth_error; trivial. Qed. Lemma combine_update_nth : forall {A B} n f g (xs:list A) (ys:list B), combine (update_nth n f xs) (update_nth n g ys) = update_nth n (fun xy => (f (fst xy), g (snd xy))) (combine xs ys). Proof. induction n as [|? IHn]; destruct xs, ys; simpl; try rewrite IHn; reflexivity. Qed. (* grumble, grumble, [rewrite] is bad at inferring the identity function, and constant functions *) Ltac rewrite_rev_combine_update_nth := let lem := match goal with | [ |- context[update_nth ?n (fun xy => (@?f xy, @?g xy)) (combine ?xs ?ys)] ] => let f := match (eval cbv [fst] in (fun y x => f (x, y))) with | fun _ => ?f => f end in let g := match (eval cbv [snd] in (fun x y => g (x, y))) with | fun _ => ?g => g end in constr:(@combine_update_nth _ _ n f g xs ys) end in rewrite <- lem. Lemma combine_update_nth_l : forall {A B} n (f : A -> A) xs (ys:list B), combine (update_nth n f xs) ys = update_nth n (fun xy => (f (fst xy), snd xy)) (combine xs ys). Proof. intros ??? f xs ys. etransitivity; [ | apply combine_update_nth with (g := fun x => x) ]. rewrite update_nth_id; reflexivity. Qed. Lemma combine_update_nth_r : forall {A B} n (g : B -> B) (xs:list A) (ys:list B), combine xs (update_nth n g ys) = update_nth n (fun xy => (fst xy, g (snd xy))) (combine xs ys). Proof. intros ??? g xs ys. etransitivity; [ | apply combine_update_nth with (f := fun x => x) ]. rewrite update_nth_id; reflexivity. Qed. Lemma combine_set_nth : forall {A B} n (x:A) xs (ys:list B), combine (set_nth n x xs) ys = match nth_error ys n with | None => combine xs ys | Some y => set_nth n (x,y) (combine xs ys) end. Proof. intros A B n x xs ys; unfold set_nth; rewrite combine_update_nth_l. nth_tac; [ repeat rewrite_rev_combine_update_nth; apply f_equal2 | assert (nth_error (combine xs ys) n = None) by (apply nth_error_None; rewrite combine_length; lia * ) ]; autorewrite with simpl_update_nth; reflexivity. Qed. Lemma nth_error_value_In : forall {T} n xs (x:T), nth_error xs n = Some x -> In x xs. Proof. induction n; destruct xs; nth_tac. Qed. Lemma In_nth_error_value : forall {T} xs (x:T), In x xs -> exists n, nth_error xs n = Some x. Proof. induction xs as [|?? IHxs]; nth_tac; destruct_head or; subst. - exists 0; reflexivity. - edestruct IHxs as [x0]; eauto. exists (S x0). eauto. Qed. Lemma nth_value_index : forall {T} i xs (x:T), nth_error xs i = Some x -> In i (seq 0 (length xs)). Proof. induction i as [|? IHi]; destruct xs; nth_tac; right. rewrite <- seq_shift; apply in_map; eapply IHi; eauto. Qed. Lemma nth_error_app : forall {T} n (xs ys:list T), nth_error (xs ++ ys) n = if lt_dec n (length xs) then nth_error xs n else nth_error ys (n - length xs). Proof. induction n as [|n IHn]; destruct xs as [|? xs]; nth_tac; rewrite IHn; destruct (lt_dec n (length xs)); trivial; lia. Qed. Lemma nth_default_app : forall {T} n x (xs ys:list T), nth_default x (xs ++ ys) n = if lt_dec n (length xs) then nth_default x xs n else nth_default x ys (n - length xs). Proof. intros T n x xs ys. unfold nth_default. rewrite nth_error_app. destruct (lt_dec n (length xs)); auto. Qed. Hint Rewrite @nth_default_app : push_nth_default. Lemma combine_truncate_r : forall {A B} (xs : list A) (ys : list B), combine xs ys = combine xs (firstn (length xs) ys). Proof. induction xs; destruct ys; boring. Qed. Lemma combine_truncate_l : forall {A B} (xs : list A) (ys : list B), combine xs ys = combine (firstn (length ys) xs) ys. Proof. induction xs; destruct ys; boring. Qed. Lemma combine_app_samelength : forall {A B} (xs xs':list A) (ys ys':list B), length xs = length ys -> combine (xs ++ xs') (ys ++ ys') = combine xs ys ++ combine xs' ys'. Proof. induction xs, xs', ys, ys'; boring; lia. Qed. Lemma map_fst_combine {A B} (xs:list A) (ys:list B) : List.map fst (List.combine xs ys) = List.firstn (length ys) xs. Proof. revert xs; induction ys; destruct xs; simpl; solve [ trivial | congruence ]. Qed. Lemma map_snd_combine {A B} (xs:list A) (ys:list B) : List.map snd (List.combine xs ys) = List.firstn (length xs) ys. Proof. revert xs; induction ys; destruct xs; simpl; solve [ trivial | congruence ]. Qed. Hint Rewrite @map_fst_combine @map_snd_combine : push_map. Lemma skipn_nil : forall {A} n, skipn n nil = @nil A. Proof. destruct n; auto. Qed. Hint Rewrite @skipn_nil : simpl_skipn. Hint Rewrite @skipn_nil : push_skipn. Lemma skipn_0 : forall {A} xs, @skipn A 0 xs = xs. Proof. reflexivity. Qed. Hint Rewrite @skipn_0 : simpl_skipn. Hint Rewrite @skipn_0 : push_skipn. Lemma skipn_cons_S : forall {A} n x xs, @skipn A (S n) (x::xs) = @skipn A n xs. Proof. reflexivity. Qed. Hint Rewrite @skipn_cons_S : simpl_skipn. Hint Rewrite @skipn_cons_S : push_skipn. Lemma skipn_app : forall {A} n (xs ys : list A), skipn n (xs ++ ys) = skipn n xs ++ skipn (n - length xs) ys. Proof. induction n, xs, ys; boring. Qed. Hint Rewrite @skipn_app : push_skipn. Lemma skipn_skipn {A} n1 n2 (ls : list A) : skipn n2 (skipn n1 ls) = skipn (n1 + n2) ls. Proof. revert n2 ls; induction n1, ls; simpl; autorewrite with simpl_skipn; boring. Qed. Hint Rewrite @skipn_skipn : simpl_skipn. Hint Rewrite <- @skipn_skipn : push_skipn. Hint Rewrite @skipn_skipn : pull_skipn. Lemma skipn_firstn {A} (ls : list A) n m : skipn n (firstn m ls) = firstn (m - n) (skipn n ls). Proof. revert n m; induction ls, m, n; simpl; autorewrite with simpl_skipn simpl_firstn; boring_list. Qed. Lemma firstn_skipn_add {A} (ls : list A) n m : firstn n (skipn m ls) = skipn m (firstn (m + n) ls). Proof. revert n m; induction ls, m; simpl; autorewrite with simpl_skipn simpl_firstn; boring_list. Qed. Lemma firstn_skipn_add' {A} (ls : list A) n m : firstn n (skipn m ls) = skipn m (firstn (n + m) ls). Proof. rewrite firstn_skipn_add; do 2 f_equal; auto with arith. Qed. Hint Rewrite <- @firstn_skipn_add @firstn_skipn_add' : simpl_firstn. Hint Rewrite <- @firstn_skipn_add @firstn_skipn_add' : simpl_skipn. Lemma firstn_app_inleft : forall {A} n (xs ys : list A), (n <= length xs)%nat -> firstn n (xs ++ ys) = firstn n xs. Proof. induction n, xs, ys; boring; try lia. Qed. Hint Rewrite @firstn_app_inleft using solve [ distr_length ] : simpl_firstn. Hint Rewrite @firstn_app_inleft using solve [ distr_length ] : push_firstn. Lemma skipn_app_inleft : forall {A} n (xs ys : list A), (n <= length xs)%nat -> skipn n (xs ++ ys) = skipn n xs ++ ys. Proof. induction n, xs, ys; boring; try lia. Qed. Hint Rewrite @skipn_app_inleft using solve [ distr_length ] : push_skipn. Lemma firstn_map : forall {A B} (f : A -> B) n (xs : list A), firstn n (map f xs) = map f (firstn n xs). Proof. induction n, xs; boring. Qed. Hint Rewrite @firstn_map : push_firstn. Hint Rewrite <- @firstn_map : pull_firstn. Lemma skipn_map : forall {A B} (f : A -> B) n (xs : list A), skipn n (map f xs) = map f (skipn n xs). Proof. induction n, xs; boring. Qed. Hint Rewrite @skipn_map : push_skipn. Hint Rewrite <- @skipn_map : pull_skipn. Lemma firstn_all : forall {A} n (xs:list A), n = length xs -> firstn n xs = xs. Proof. induction n, xs; boring; lia. Qed. Hint Rewrite @firstn_all using solve [ distr_length ] : simpl_firstn. Hint Rewrite @firstn_all using solve [ distr_length ] : push_firstn. Lemma skipn_all : forall {T} n (xs:list T), (n >= length xs)%nat -> skipn n xs = nil. Proof. induction n, xs; boring; lia. Qed. Hint Rewrite @skipn_all using solve [ distr_length ] : simpl_skipn. Hint Rewrite @skipn_all using solve [ distr_length ] : push_skipn. Lemma firstn_app_sharp : forall {A} n (l l': list A), length l = n -> firstn n (l ++ l') = l. Proof. intros. rewrite firstn_app_inleft; auto using firstn_all; lia. Qed. Hint Rewrite @firstn_app_sharp using solve [ distr_length ] : simpl_firstn. Hint Rewrite @firstn_app_sharp using solve [ distr_length ] : push_firstn. Lemma skipn_app_sharp : forall {A} n (l l': list A), length l = n -> skipn n (l ++ l') = l'. Proof. intros. rewrite skipn_app_inleft; try rewrite skipn_all; auto; lia. Qed. Hint Rewrite @skipn_app_sharp using solve [ distr_length ] : simpl_skipn. Hint Rewrite @skipn_app_sharp using solve [ distr_length ] : push_skipn. Lemma skipn_length : forall {A} n (xs : list A), length (skipn n xs) = (length xs - n)%nat. Proof. induction n, xs; boring. Qed. Hint Rewrite @skipn_length : distr_length. Lemma length_cons : forall {T} (x:T) xs, length (x::xs) = S (length xs). reflexivity. Qed. Hint Rewrite @length_cons : distr_length. Lemma length_cons_full {T} n (x:list T) (t:T) (H: length (t :: x) = S n) : length x = n. Proof. distr_length. Qed. Lemma cons_length : forall A (xs : list A) a, length (a :: xs) = S (length xs). Proof. auto. Qed. Lemma length0_nil : forall {A} (xs : list A), length xs = 0%nat -> xs = nil. Proof. induction xs; boring; discriminate. Qed. Lemma length_tl {A} ls : length (@tl A ls) = (length ls - 1)%nat. Proof. destruct ls; cbn [tl length]; lia. Qed. Hint Rewrite @length_tl : distr_length. Lemma length_snoc {A : Type} (l : list A) a : length (l ++ [a]) = S (length l). Proof. simpl_list; boring. Qed. Hint Rewrite @length_snoc : distr_length. Lemma combine_cons : forall {A B} a b (xs:list A) (ys:list B), combine (a :: xs) (b :: ys) = (a,b) :: combine xs ys. Proof. reflexivity. Qed. Hint Rewrite @combine_cons : push_combine. Lemma firstn_combine : forall {A B} n (xs:list A) (ys:list B), firstn n (combine xs ys) = combine (firstn n xs) (firstn n ys). Proof. induction n, xs, ys; boring. Qed. Hint Rewrite @firstn_combine : push_firstn. Hint Rewrite <- @firstn_combine : pull_firstn. Lemma combine_nil_r : forall {A B} (xs:list A), combine xs (@nil B) = nil. Proof. induction xs; boring. Qed. Hint Rewrite @combine_nil_r : push_combine. Lemma combine_snoc {A B} xs : forall ys x y, length xs = length ys -> @combine A B (xs ++ (x :: nil)) (ys ++ (y :: nil)) = combine xs ys ++ ((x, y) :: nil). Proof. induction xs; intros; destruct ys; distr_length; cbn; try rewrite IHxs by lia; reflexivity. Qed. Hint Rewrite @combine_snoc using (solve [distr_length]) : push_combine. Lemma skipn_combine : forall {A B} n (xs:list A) (ys:list B), skipn n (combine xs ys) = combine (skipn n xs) (skipn n ys). Proof. induction n, xs, ys; boring. rewrite combine_nil_r; reflexivity. Qed. Hint Rewrite @skipn_combine : push_skipn. Hint Rewrite <- @skipn_combine : pull_skipn. Lemma break_list_last: forall {T} (xs:list T), xs = nil \/ exists xs' y, xs = xs' ++ y :: nil. Proof. destruct xs using rev_ind; auto. right; do 2 eexists; auto. Qed. Lemma break_list_first: forall {T} (xs:list T), xs = nil \/ exists x xs', xs = x :: xs'. Proof. destruct xs; auto. right; do 2 eexists; auto. Qed. Lemma list012 : forall {T} (xs:list T), xs = nil \/ (exists x, xs = x::nil) \/ (exists x xs' y, xs = x::xs'++y::nil). Proof. destruct xs as [|? xs]; auto. right. destruct xs using rev_ind. { left; eexists; auto. } { right; repeat eexists; auto. } Qed. Lemma nil_length0 : forall {T}, length (@nil T) = 0%nat. Proof. auto. Qed. Hint Rewrite @nil_length0 : distr_length. Lemma nth_error_Some_nth_default : forall {T} i x (l : list T), (i < length l)%nat -> nth_error l i = Some (nth_default x l i). Proof. intros ? ? ? ? i_lt_length. destruct (nth_error_length_exists_value _ _ i_lt_length) as [k nth_err_k]. unfold nth_default. rewrite nth_err_k. reflexivity. Qed. Lemma update_nth_cons : forall {T} f (u0 : T) us, update_nth 0 f (u0 :: us) = (f u0) :: us. Proof. reflexivity. Qed. Hint Rewrite @update_nth_cons : simpl_update_nth. Lemma set_nth_cons : forall {T} (x u0 : T) us, set_nth 0 x (u0 :: us) = x :: us. Proof. intros; apply update_nth_cons. Qed. Hint Rewrite @set_nth_cons : simpl_set_nth. Lemma cons_update_nth : forall {T} n f (y : T) us, y :: update_nth n f us = update_nth (S n) f (y :: us). Proof. induction n; boring. Qed. Hint Rewrite <- @cons_update_nth : simpl_update_nth. Lemma update_nth_nil : forall {T} n f, update_nth n f (@nil T) = @nil T. Proof. induction n; boring. Qed. Hint Rewrite @update_nth_nil : simpl_update_nth. Lemma cons_set_nth : forall {T} n (x y : T) us, y :: set_nth n x us = set_nth (S n) x (y :: us). Proof. intros; apply cons_update_nth. Qed. Hint Rewrite <- @cons_set_nth : simpl_set_nth. Lemma set_nth_nil : forall {T} n (x : T), set_nth n x nil = nil. Proof. intros; apply update_nth_nil. Qed. Hint Rewrite @set_nth_nil : simpl_set_nth. Lemma skipn_nth_default : forall {T} n us (d : T), (n < length us)%nat -> skipn n us = nth_default d us n :: skipn (S n) us. Proof. induction n as [|n IHn]; destruct us as [|? us]; intros d H; nth_tac. rewrite (IHn us d) at 1 by lia. nth_tac. Qed. Lemma nth_default_out_of_bounds : forall {T} n us (d : T), (n >= length us)%nat -> nth_default d us n = d. Proof. induction n as [|n IHn]; unfold nth_default; nth_tac; let us' := match goal with us : list _ |- _ => us end in destruct us' as [|? us]; nth_tac. assert (n >= length us)%nat by lia. pose proof (nth_error_length_error _ n us). specialize_by_assumption. rewrite_hyp * in *. congruence. Qed. Hint Rewrite @nth_default_out_of_bounds using lia : simpl_nth_default. Ltac nth_error_inbounds := match goal with | [ |- context[match nth_error ?xs ?i with Some _ => _ | None => _ end ] ] => case_eq (nth_error xs i); match goal with | [ |- forall _, nth_error xs i = Some _ -> _ ] => let x := fresh "x" in let H := fresh "H" in intros x H; repeat progress erewrite H; repeat progress erewrite (nth_error_value_eq_nth_default i xs x); auto | [ |- nth_error xs i = None -> _ ] => let H := fresh "H" in intros H; destruct (nth_error_length_not_error _ _ H); try solve [distr_length] end; idtac end. Ltac set_nth_inbounds := match goal with | [ |- context[set_nth ?i ?x ?xs] ] => rewrite (set_nth_equiv_splice_nth i x xs); destruct (lt_dec i (length xs)); match goal with | [ H : ~ (i < (length xs))%nat |- _ ] => destruct H | [ H : (i < (length xs))%nat |- _ ] => try solve [distr_length] end end. Ltac update_nth_inbounds := match goal with | [ |- context[update_nth ?i ?f ?xs] ] => rewrite (update_nth_equiv_splice_nth i f xs); destruct (lt_dec i (length xs)); match goal with | [ H : ~ (i < (length xs))%nat |- _ ] => destruct H | [ H : (i < (length xs))%nat |- _ ] => remove_nth_error; try solve [distr_length] end end. Ltac nth_inbounds := nth_error_inbounds || set_nth_inbounds || update_nth_inbounds. Definition nth_dep {A} (ls : list A) (n : nat) (pf : n < length ls) : A. Proof. refine (match nth_error ls n as v return nth_error ls n = v -> A with | Some v => fun _ => v | None => fun bad => match _ : False with end end eq_refl). apply (proj1 (@nth_error_None _ _ _)) in bad; instantiate; generalize dependent (length ls); clear. abstract (intros; lia). Defined. Lemma nth_error_nth_dep {A} ls n pf : nth_error ls n = Some (@nth_dep A ls n pf). Proof. unfold nth_dep. generalize dependent (@nth_error_None A ls n). edestruct nth_error; boring. Qed. Lemma nth_default_nth_dep {A} d ls n pf : nth_default d ls n = @nth_dep A ls n pf. Proof. unfold nth_dep. generalize dependent (@nth_error_None A ls n). destruct (nth_error ls n) eqn:?; boring. erewrite nth_error_value_eq_nth_default by eassumption; reflexivity. Qed. Lemma nth_default_in_bounds : forall {T} (d' d : T) n us, (n < length us)%nat -> nth_default d us n = nth_default d' us n. Proof. intros; erewrite !nth_default_nth_dep; reflexivity. Grab Existential Variables. assumption. Qed. Global Hint Resolve nth_default_in_bounds : simpl_nth_default. Lemma cons_eq_head : forall {T} (x y:T) xs ys, x::xs = y::ys -> x=y. Proof. intros; congruence. Qed. Lemma cons_eq_tail : forall {T} (x y:T) xs ys, x::xs = y::ys -> xs=ys. Proof. intros; congruence. Qed. Lemma map_nth_default_always {A B} (f : A -> B) (n : nat) (x : A) (l : list A) : nth_default (f x) (map f l) n = f (nth_default x l n). Proof. revert n; induction l; simpl; intro n; destruct n; [ try reflexivity.. ]. nth_tac. Qed. Hint Rewrite @map_nth_default_always : push_nth_default. Lemma map_S_seq {A} (f:nat->A) len : forall start, List.map (fun i => f (S i)) (seq start len) = List.map f (seq (S start) len). Proof. induction len as [|len IHlen]; intros; simpl; rewrite ?IHlen; reflexivity. Qed. Lemma seq_snoc len : forall start, seq start (S len) = seq start len ++ ((start + len)%nat :: nil). Proof. induction len; intros. { cbv [seq app]. autorewrite with natsimplify; reflexivity. } { remember (S len); simpl seq. rewrite (IHlen (S start)); subst; simpl seq. rewrite Nat.add_succ_r; reflexivity. } Qed. Lemma seq_len_0 a : seq a 0 = nil. Proof. reflexivity. Qed. Lemma seq_add start a b : seq start (a + b) = seq start a ++ seq (start + a) b. Proof. revert start b; induction a as [|a IHa]; cbn; intros start b. { f_equal; lia. } { rewrite IHa; do 3 f_equal; lia. } Qed. Lemma map_seq_ext {A} (f g : nat -> A) (n m k : nat) (H : forall i : nat, n <= i <= m + k -> f i = g (i + (m - n))%nat) (Hnm : n <= m) : map f (seq n k) = map g (seq m k). Proof. generalize dependent m; generalize dependent n; induction k as [|k IHk]; intros; simpl. - reflexivity. - simpl; rewrite H by lia; replace (n + (m - n))%nat with m by lia. rewrite (IHk (S n) (S m)); [reflexivity| |lia]. intros; rewrite Nat.sub_succ; apply H; lia. Qed. Lemma map_seq_pred n m : seq n m = map (fun i => (i - 1)%nat) (seq (S n) m). Proof. rewrite <- map_id at 1; apply map_seq_ext; intros; lia. Qed. Lemma map_seq_succ n m : seq (S n) m = map (fun i => (i + 1)%nat) (seq n m). Proof. rewrite <- map_id at 1; symmetry; apply map_seq_ext; intros; lia. Qed. Lemma fold_right_and_True_forall_In_iff : forall {T} (l : list T) (P : T -> Prop), (forall x, In x l -> P x) <-> fold_right and True (map P l). Proof. induction l as [|?? IHl]; intros; simpl; try tauto. rewrite <- IHl. intuition (subst; auto). Qed. Lemma fold_right_invariant : forall {A B} P (f: A -> B -> B) l x, P x -> (forall y, In y l -> forall z, P z -> P (f y z)) -> P (fold_right f x l). Proof. induction l as [|a l IHl]; intros ? ? step; auto. simpl. apply step; try apply in_eq. apply IHl; auto. intros y in_y_l. apply (in_cons a) in in_y_l. auto. Qed. Lemma In_firstn : forall {T} n l (x : T), In x (firstn n l) -> In x l. Proof. induction n; destruct l; boring. Qed. Lemma In_skipn : forall {T} n l (x : T), In x (skipn n l) -> In x l. Proof. induction n; destruct l; boring. Qed. Lemma In_firstn_skipn_split {T} n (x : T) : forall l, In x l <-> In x (firstn n l) \/ In x (skipn n l). Proof. intro l; split; revert l; induction n; destruct l; boring. match goal with | [ IH : forall l, In ?x l -> _ \/ _, H' : In ?x ?ls |- _ ] => destruct (IH _ H') end; auto. Qed. Lemma firstn_firstn_min : forall {A} m n (l : list A), firstn n (firstn m l) = firstn (min n m) l. Proof. induction m as [|? IHm]; destruct n; intros l; try lia; auto. destruct l; auto. simpl. f_equal. apply IHm; lia. Qed. Lemma firstn_firstn : forall {A} m n (l : list A), (n <= m)%nat -> firstn n (firstn m l) = firstn n l. Proof. intros A m n l H; rewrite firstn_firstn_min. apply Min.min_case_strong; intro; [ reflexivity | ]. assert (n = m) by lia; subst; reflexivity. Qed. Hint Rewrite @firstn_firstn using lia : push_firstn. Lemma firstn_succ : forall {A} (d : A) n l, (n < length l)%nat -> firstn (S n) l = (firstn n l) ++ nth_default d l n :: nil. Proof. intros A d; induction n as [|? IHn]; destruct l; rewrite ?(@nil_length0 A); intros; try lia. + rewrite nth_default_cons; auto. + simpl. rewrite nth_default_cons_S. rewrite <-IHn by (rewrite cons_length in *; lia). reflexivity. Qed. Lemma firstn_seq k a b : firstn k (seq a b) = seq a (min k b). Proof. revert k a; induction b as [|? IHb], k; simpl; try reflexivity. intros; rewrite IHb; reflexivity. Qed. Hint Rewrite @firstn_seq : push_firstn. Lemma skipn_seq k a b : skipn k (seq a b) = seq (k + a) (b - k). Proof. revert k a; induction b as [|? IHb], k; simpl; try reflexivity. intros; rewrite IHb; simpl; f_equal; lia. Qed. Lemma update_nth_out_of_bounds : forall {A} n f xs, n >= length xs -> @update_nth A n f xs = xs. Proof. induction n as [|n IHn]; destruct xs; simpl; try congruence; try lia; intros. rewrite IHn by lia; reflexivity. Qed. Hint Rewrite @update_nth_out_of_bounds using lia : simpl_update_nth. Lemma update_nth_nth_default_full : forall {A} (d:A) n f l i, nth_default d (update_nth n f l) i = if lt_dec i (length l) then if (eq_nat_dec i n) then f (nth_default d l i) else nth_default d l i else d. Proof. induction n as [|n IHn]; (destruct l; simpl in *; [ intros i **; destruct i; simpl; try reflexivity; lia | ]); intros i **; repeat break_match; subst; try destruct i; repeat first [ progress break_match | progress subst | progress boring | progress autorewrite with simpl_nth_default | lia ]. Qed. Hint Rewrite @update_nth_nth_default_full : push_nth_default. Lemma update_nth_nth_default : forall {A} (d:A) n f l i, (0 <= i < length l)%nat -> nth_default d (update_nth n f l) i = if (eq_nat_dec i n) then f (nth_default d l i) else nth_default d l i. Proof. intros; rewrite update_nth_nth_default_full; repeat break_match; boring. Qed. Hint Rewrite @update_nth_nth_default using (lia || distr_length; lia) : push_nth_default. Lemma set_nth_nth_default_full : forall {A} (d:A) n v l i, nth_default d (set_nth n v l) i = if lt_dec i (length l) then if (eq_nat_dec i n) then v else nth_default d l i else d. Proof. intros; apply update_nth_nth_default_full; assumption. Qed. Hint Rewrite @set_nth_nth_default_full : push_nth_default. Lemma set_nth_nth_default : forall {A} (d:A) n x l i, (0 <= i < length l)%nat -> nth_default d (set_nth n x l) i = if (eq_nat_dec i n) then x else nth_default d l i. Proof. intros; apply update_nth_nth_default; assumption. Qed. Hint Rewrite @set_nth_nth_default using (lia || distr_length; lia) : push_nth_default. Lemma nth_default_preserves_properties : forall {A} (P : A -> Prop) l n d, (forall x, In x l -> P x) -> P d -> P (nth_default d l n). Proof. intros A P l n d H H0; rewrite nth_default_eq. destruct (nth_in_or_default n l d); auto. congruence. Qed. Lemma nth_default_preserves_properties_length_dep : forall {A} (P : A -> Prop) l n d, (forall x, In x l -> n < (length l) -> P x) -> ((~ n < length l) -> P d) -> P (nth_default d l n). Proof. intros A P l n d H H0. destruct (lt_dec n (length l)). + rewrite nth_default_eq; auto using nth_In. + rewrite nth_default_out_of_bounds by lia. auto. Qed. Lemma nth_error_first : forall {T} (a b : T) l, nth_error (a :: l) 0 = Some b -> a = b. Proof. intros; simpl in *. unfold value in *. congruence. Qed. Lemma nth_error_exists_first : forall {T} l (x : T) (H : nth_error l 0 = Some x), exists l', l = x :: l'. Proof. induction l; try discriminate; intros x H; eexists. apply nth_error_first in H. subst; eauto. Qed. Lemma list_elementwise_eq : forall {T} (l1 l2 : list T), (forall i, nth_error l1 i = nth_error l2 i) -> l1 = l2. Proof. induction l1, l2; intros H; try reflexivity; pose proof (H 0%nat) as Hfirst; simpl in Hfirst; inversion Hfirst. f_equal. apply IHl1. intros i; specialize (H (S i)). boring. Qed. Lemma sum_firstn_all_succ : forall n l, (length l <= n)%nat -> sum_firstn l (S n) = sum_firstn l n. Proof. unfold sum_firstn; intros. autorewrite with push_firstn; reflexivity. Qed. Hint Rewrite @sum_firstn_all_succ using lia : simpl_sum_firstn. Lemma sum_firstn_all : forall n l, (length l <= n)%nat -> sum_firstn l n = sum_firstn l (length l). Proof. unfold sum_firstn; intros. autorewrite with push_firstn; reflexivity. Qed. Hint Rewrite @sum_firstn_all using lia : simpl_sum_firstn. Lemma sum_firstn_succ_default : forall l i, sum_firstn l (S i) = (nth_default 0 l i + sum_firstn l i)%Z. Proof. unfold sum_firstn; induction l as [|a l IHl], i; intros; autorewrite with simpl_nth_default simpl_firstn simpl_fold_right in *; try reflexivity. rewrite IHl; lia. Qed. Hint Rewrite @sum_firstn_succ_default : simpl_sum_firstn. Lemma sum_firstn_0 : forall xs, sum_firstn xs 0 = 0%Z. Proof. destruct xs; reflexivity. Qed. Hint Rewrite @sum_firstn_0 : simpl_sum_firstn. Lemma sum_firstn_succ : forall l i x, nth_error l i = Some x -> sum_firstn l (S i) = (x + sum_firstn l i)%Z. Proof. intros; rewrite sum_firstn_succ_default. erewrite nth_error_value_eq_nth_default by eassumption; reflexivity. Qed. Hint Rewrite @sum_firstn_succ using congruence : simpl_sum_firstn. Lemma sum_firstn_succ_cons : forall x xs i, sum_firstn (x :: xs) (S i) = (x + sum_firstn xs i)%Z. Proof. unfold sum_firstn; simpl; reflexivity. Qed. Hint Rewrite @sum_firstn_succ_cons : simpl_sum_firstn. Lemma sum_firstn_nil : forall i, sum_firstn nil i = 0%Z. Proof. destruct i; reflexivity. Qed. Hint Rewrite @sum_firstn_nil : simpl_sum_firstn. Lemma sum_firstn_succ_default_rev : forall l i, sum_firstn l i = (sum_firstn l (S i) - nth_default 0 l i)%Z. Proof. intros; rewrite sum_firstn_succ_default; lia. Qed. Lemma sum_firstn_succ_rev : forall l i x, nth_error l i = Some x -> sum_firstn l i = (sum_firstn l (S i) - x)%Z. Proof. intros; erewrite sum_firstn_succ by eassumption; lia. Qed. Lemma sum_firstn_nonnegative : forall n l, (forall x, In x l -> 0 <= x)%Z -> (0 <= sum_firstn l n)%Z. Proof. induction n as [|n IHn]; destruct l as [|? l]; autorewrite with simpl_sum_firstn; simpl; try lia. { specialize (IHn l). destruct n; simpl; autorewrite with simpl_sum_firstn simpl_nth_default in *; intuition auto with zarith. } Qed. Global Hint Resolve sum_firstn_nonnegative : znonzero. Lemma sum_firstn_app : forall xs ys n, sum_firstn (xs ++ ys) n = (sum_firstn xs n + sum_firstn ys (n - length xs))%Z. Proof. induction xs as [|a xs IHxs]; simpl. { intros ys n; autorewrite with simpl_sum_firstn; simpl. f_equal; lia. } { intros ys [|n]; autorewrite with simpl_sum_firstn; simpl; [ reflexivity | ]. rewrite IHxs; lia. } Qed. Lemma sum_firstn_app_sum : forall xs ys n, sum_firstn (xs ++ ys) (length xs + n) = (sum_firstn xs (length xs) + sum_firstn ys n)%Z. Proof. intros; rewrite sum_firstn_app; autorewrite with simpl_sum_firstn. do 2 f_equal; lia. Qed. Hint Rewrite @sum_firstn_app_sum : simpl_sum_firstn. Lemma sum_cons xs x : sum (x :: xs) = (x + sum xs)%Z. Proof. reflexivity. Qed. Hint Rewrite sum_cons : push_sum. Lemma sum_nil : sum nil = 0%Z. Proof. reflexivity. Qed. Hint Rewrite sum_nil : push_sum. Lemma sum_app x y : sum (x ++ y) = (sum x + sum y)%Z. Proof. induction x; rewrite ?app_nil_l, <-?app_comm_cons; autorewrite with push_sum; lia. Qed. Hint Rewrite sum_app : push_sum. Lemma sum_rev x : sum (rev x) = sum x. Proof. induction x; cbn [rev]; autorewrite with push_sum; lia. Qed. Hint Rewrite sum_rev : push_sum. Lemma nth_error_skipn : forall {A} n (l : list A) m, nth_error (skipn n l) m = nth_error l (n + m). Proof. induction n as [|n IHn]; destruct l; boring. apply nth_error_nil_error. Qed. Hint Rewrite @nth_error_skipn : push_nth_error. Lemma nth_default_skipn : forall {A} (l : list A) d n m, nth_default d (skipn n l) m = nth_default d l (n + m). Proof. cbv [nth_default]; intros. rewrite nth_error_skipn. reflexivity. Qed. Hint Rewrite @nth_default_skipn : push_nth_default. Lemma sum_firstn_skipn : forall l n m, sum_firstn l (n + m) = (sum_firstn l n + sum_firstn (skipn n l) m)%Z. Proof. induction m; intros. + rewrite sum_firstn_0. autorewrite with natsimplify. lia. + rewrite <-plus_n_Sm, !sum_firstn_succ_default. rewrite nth_default_skipn. lia. Qed. Lemma nth_default_seq_inbounds d s n i (H:(i < n)%nat) : List.nth_default d (List.seq s n) i = (s+i)%nat. Proof. progress cbv [List.nth_default]. rewrite nth_error_seq. break_innermost_match; solve [ trivial | lia ]. Qed. Hint Rewrite @nth_default_seq_inbounds using lia : push_nth_default. Lemma sum_firstn_prefix_le' : forall l n m, (forall x, In x l -> (0 <= x)%Z) -> (sum_firstn l n <= sum_firstn l (n + m))%Z. Proof. intros l n m H. rewrite sum_firstn_skipn. pose proof (sum_firstn_nonnegative m (skipn n l)) as Hskipn_nonneg. match type of Hskipn_nonneg with ?P -> _ => assert P as Q; [ | specialize (Hskipn_nonneg Q); lia ] end. intros x HIn_skipn. apply In_skipn in HIn_skipn. auto. Qed. Lemma sum_firstn_prefix_le : forall l n m, (forall x, In x l -> (0 <= x)%Z) -> (n <= m)%nat -> (sum_firstn l n <= sum_firstn l m)%Z. Proof. intros l n m H H0. replace m with (n + (m - n))%nat by lia. auto using sum_firstn_prefix_le'. Qed. Lemma sum_firstn_pos_lt_succ : forall l n m, (forall x, In x l -> (0 <= x)%Z) -> (n < length l)%nat -> (sum_firstn l n < sum_firstn l (S m))%Z -> (n <= m)%nat. Proof. intros l n m H H0 H1. destruct (le_dec n m); auto. replace n with (m + (n - m))%nat in H1 by lia. rewrite sum_firstn_skipn in H1. rewrite sum_firstn_succ_default in *. match goal with H : (?a + ?b < ?c + ?a)%Z |- _ => assert (H2 : (b < c)%Z) by lia end. destruct (lt_dec m (length l)). { rewrite skipn_nth_default with (d := 0%Z) in H2 by assumption. replace (n - m)%nat with (S (n - S m))%nat in H2 by lia. rewrite sum_firstn_succ_cons in H2. pose proof (sum_firstn_nonnegative (n - S m) (skipn (S m) l)) as H3. match type of H3 with ?P -> _ => assert P as Q; [ | specialize (H3 Q); lia ] end. intros ? A. apply In_skipn in A. apply H in A. lia. } { rewrite skipn_all, nth_default_out_of_bounds in H2 by lia. rewrite sum_firstn_nil in H2; lia. } Qed. Definition NotSum {T} (xs : list T) (v : nat) := True. Ltac NotSum := lazymatch goal with | [ |- NotSum ?xs (length ?xs + _)%nat ] => fail | [ |- NotSum _ _ ] => exact I end. Lemma sum_firstn_app_hint : forall xs ys n, NotSum xs n -> sum_firstn (xs ++ ys) n = (sum_firstn xs n + sum_firstn ys (n - length xs))%Z. Proof. auto using sum_firstn_app. Qed. Hint Rewrite sum_firstn_app_hint using solve [ NotSum ] : simpl_sum_firstn. Lemma nth_default_map2 : forall {A B C} (f : A -> B -> C) ls1 ls2 i d d1 d2, nth_default d (map2 f ls1 ls2) i = if lt_dec i (min (length ls1) (length ls2)) then f (nth_default d1 ls1 i) (nth_default d2 ls2 i) else d. Proof. induction ls1 as [|a ls1 IHls1], ls2. + cbv [map2 length min]. intros. break_match; try lia. apply nth_default_nil. + cbv [map2 length min]. intros. break_match; try lia. apply nth_default_nil. + cbv [map2 length min]. intros. break_match; try lia. apply nth_default_nil. + simpl. destruct i. - intros. rewrite !nth_default_cons. break_match; auto; lia. - intros d d1 d2. rewrite !nth_default_cons_S. rewrite IHls1 with (d1 := d1) (d2 := d2). repeat break_match; auto; lia. Qed. Lemma map2_cons : forall A B C (f : A -> B -> C) ls1 ls2 a b, map2 f (a :: ls1) (b :: ls2) = f a b :: map2 f ls1 ls2. Proof. reflexivity. Qed. Lemma map2_nil_l : forall A B C (f : A -> B -> C) ls2, map2 f nil ls2 = nil. Proof. reflexivity. Qed. Lemma map2_nil_r : forall A B C (f : A -> B -> C) ls1, map2 f ls1 nil = nil. Proof. destruct ls1; reflexivity. Qed. Local Hint Resolve map2_nil_r map2_nil_l : core. Ltac simpl_list_lengths := repeat match goal with | H : context[length (@nil ?A)] |- _ => rewrite (@nil_length0 A) in H | H : context[length (_ :: _)] |- _ => rewrite length_cons in H | |- context[length (@nil ?A)] => rewrite (@nil_length0 A) | |- context[length (_ :: _)] => rewrite length_cons end. Section OpaqueMap2. Local Opaque map2. Lemma map2_length : forall A B C (f : A -> B -> C) ls1 ls2, length (map2 f ls1 ls2) = min (length ls1) (length ls2). Proof. induction ls1 as [|a ls1 IHls1], ls2; intros; try solve [cbv; auto]. rewrite map2_cons, !length_cons, IHls1. auto. Qed. Hint Rewrite @map2_length : distr_length. Lemma map2_app : forall A B C (f : A -> B -> C) ls1 ls2 ls1' ls2', (length ls1 = length ls2) -> map2 f (ls1 ++ ls1') (ls2 ++ ls2') = map2 f ls1 ls2 ++ map2 f ls1' ls2'. Proof. induction ls1 as [|a ls1 IHls1], ls2; intros; rewrite ?map2_nil_r, ?app_nil_l; try congruence; simpl_list_lengths; try lia. rewrite <-!app_comm_cons, !map2_cons. rewrite IHls1; auto. Qed. End OpaqueMap2. Hint Rewrite @map2_length : distr_length. Lemma firstn_update_nth {A} : forall f m n (xs : list A), firstn m (update_nth n f xs) = update_nth n f (firstn m xs). Proof. induction m; destruct n, xs; autorewrite with simpl_firstn simpl_update_nth; congruence. Qed. Hint Rewrite @firstn_update_nth : push_firstn. Hint Rewrite @firstn_update_nth : pull_update_nth. Hint Rewrite <- @firstn_update_nth : pull_firstn. Hint Rewrite <- @firstn_update_nth : push_update_nth. Require Import Coq.Lists.SetoidList. Global Instance Proper_nth_default : forall A eq, Proper (eq==>eqlistA eq==>Logic.eq==>eq) (nth_default (A:=A)). Proof. intros A ee x y H; subst; induction 1. + repeat intro; rewrite !nth_default_nil; assumption. + intros x1 y0 H2; subst; destruct y0; rewrite ?nth_default_cons, ?nth_default_cons_S; auto. Qed. Lemma fold_right_andb_true_map_iff A (ls : list A) f : List.fold_right andb true (List.map f ls) = true <-> forall i, List.In i ls -> f i = true. Proof. induction ls as [|a ls IHls]; simpl; [ | rewrite Bool.andb_true_iff, IHls ]; try tauto. intuition (congruence || eauto). Qed. Lemma fold_right_andb_true_iff_fold_right_and_True (ls : list bool) : List.fold_right andb true ls = true <-> List.fold_right and True (List.map (fun b => b = true) ls). Proof. rewrite <- (map_id ls) at 1. rewrite fold_right_andb_true_map_iff, fold_right_and_True_forall_In_iff; reflexivity. Qed. Lemma Forall2_forall_iff : forall {A B} (R : A -> B -> Prop) (xs : list A) (ys : list B) d1 d2, length xs = length ys -> (Forall2 R xs ys <-> (forall i, (i < length xs)%nat -> R (nth_default d1 xs i) (nth_default d2 ys i))). Proof. intros A B R xs ys d1 d2 H; split; [ intros H0 i H1 | intros H0 ]. + revert xs ys H H0 H1. induction i as [|i IHi]; intros xs ys H H0 H1; destruct H0; distr_length; autorewrite with push_nth_default; auto. eapply IHi; auto. lia. + revert xs ys H H0; induction xs as [|a xs IHxs]; intros ys H H0; destruct ys; distr_length; econstructor. - specialize (H0 0%nat). autorewrite with push_nth_default in *; auto. apply H0; lia. - apply IHxs; try lia. intros i H1. specialize (H0 (S i)). autorewrite with push_nth_default in *; auto. apply H0; lia. Qed. Lemma Forall2_forall_iff' : forall {A} R (xs ys : list A) d, length xs = length ys -> (Forall2 R xs ys <-> (forall i, (i < length xs)%nat -> R (nth_default d xs i) (nth_default d ys i))). Proof. intros; apply Forall2_forall_iff; assumption. Qed. Lemma nth_default_firstn : forall {A} (d : A) l i n, nth_default d (firstn n l) i = if le_dec n (length l) then if lt_dec i n then nth_default d l i else d else nth_default d l i. Proof. intros A d l i; induction n as [|n IHn]; break_match; autorewrite with push_nth_default; auto; try lia. + rewrite (firstn_succ d) by lia. autorewrite with push_nth_default; repeat (break_match_hyps; break_match; distr_length); rewrite Min.min_l in * by lia; try lia. - apply IHn; lia. - replace i with n in * by lia. rewrite Nat.sub_diag. autorewrite with push_nth_default; auto. + rewrite nth_default_out_of_bounds; break_match_hyps; distr_length; auto; lia. + rewrite firstn_all2 by lia. auto. Qed. Hint Rewrite @nth_default_firstn : push_nth_default. Lemma nth_error_repeat {T} x n i v : nth_error (@repeat T x n) i = Some v -> v = x. Proof. revert n x v; induction i as [|i IHi]; destruct n; simpl in *; eauto; congruence. Qed. Hint Rewrite repeat_length : distr_length. Lemma repeat_spec_iff : forall {A} (ls : list A) x n, (length ls = n /\ forall y, In y ls -> y = x) <-> ls = repeat x n. Proof. intros A ls x n; split; [ revert A ls x n | intro; subst; eauto using repeat_length, repeat_spec ]. induction ls as [|a ls IHls], n; simpl; intros; intuition try congruence. f_equal; auto. Qed. Lemma repeat_spec_eq : forall {A} (ls : list A) x n, length ls = n -> (forall y, In y ls -> y = x) -> ls = repeat x n. Proof. intros; apply repeat_spec_iff; auto. Qed. Lemma tl_repeat {A} x n : tl (@repeat A x n) = repeat x (pred n). Proof. destruct n; reflexivity. Qed. Lemma firstn_repeat : forall {A} x n k, firstn k (@repeat A x n) = repeat x (min k n). Proof. induction n, k; boring. Qed. Hint Rewrite @firstn_repeat : push_firstn. Lemma skipn_repeat : forall {A} x n k, skipn k (@repeat A x n) = repeat x (n - k). Proof. induction n, k; boring. Qed. Hint Rewrite @skipn_repeat : push_skipn. Global Instance Proper_map {A B} {RA RB} {Equivalence_RB:Equivalence RB} : Proper ((RA==>RB) ==> eqlistA RA ==> eqlistA RB) (@List.map A B). Proof. repeat intro. match goal with [H:eqlistA _ _ _ |- _ ] => induction H end; [reflexivity|]. cbv [respectful] in *; econstructor; eauto. Qed. Lemma pointwise_map {A B} : Proper ((pointwise_relation _ eq) ==> eq ==> eq) (@List.map A B). Proof. repeat intro; cbv [pointwise_relation] in *; subst. match goal with [H:list _ |- _ ] => induction H as [|? IH IHIH] end; [reflexivity|]. simpl. rewrite IHIH. congruence. Qed. Lemma map_map2 {A B C D} (f:A -> B -> C) (g:C -> D) (xs:list A) (ys:list B) : List.map g (map2 f xs ys) = map2 (fun (a : A) (b : B) => g (f a b)) xs ys. Proof. revert ys; induction xs as [|a xs IHxs]; intros ys; [reflexivity|]. destruct ys; [reflexivity|]. simpl. rewrite IHxs. reflexivity. Qed. Lemma map2_fst {A B C} (f:A -> C) (xs:list A) : forall (ys:list B), length xs = length ys -> map2 (fun (a : A) (_ : B) => f a) xs ys = List.map f xs. Proof. induction xs as [|a xs IHxs]; intros ys **; [reflexivity|]. destruct ys; [simpl in *; discriminate|]. simpl. rewrite IHxs by eauto. reflexivity. Qed. Lemma map2_flip {A B C} (f:A -> B -> C) (xs:list A) : forall (ys: list B), map2 (fun b a => f a b) ys xs = map2 f xs ys. Proof. induction xs as [|a xs IHxs]; destruct ys; try reflexivity; []. simpl. rewrite IHxs. reflexivity. Qed. Lemma map2_snd {A B C} (f:B -> C) (xs:list A) : forall (ys:list B), length xs = length ys -> map2 (fun (_ : A) (b : B) => f b) xs ys = List.map f ys. Proof. intros. rewrite map2_flip. eauto using map2_fst. Qed. Lemma map2_map {A B C A' B'} (f:A -> B -> C) (g:A' -> A) (h:B' -> B) (xs:list A') (ys:list B') : map2 f (List.map g xs) (List.map h ys) = map2 (fun a b => f (g a) (h b)) xs ys. Proof. revert ys; induction xs as [|a xs IHxs]; destruct ys; intros; try reflexivity; []. simpl. rewrite IHxs. reflexivity. Qed. Definition expand_list_helper {A} (default : A) (ls : list A) (n : nat) (idx : nat) : list A := nat_rect (fun _ => nat -> list A) (fun _ => nil) (fun n' rec_call idx => cons (List.nth_default default ls idx) (rec_call (S idx))) n idx. Definition expand_list {A} (default : A) (ls : list A) (n : nat) : list A := expand_list_helper default ls n 0. Lemma expand_list_helper_correct {A} (default : A) (ls : list A) (n idx : nat) (H : (idx + n <= length ls)%nat) : expand_list_helper default ls n idx = List.firstn n (List.skipn idx ls). Proof. cbv [expand_list_helper]; revert idx H. induction n as [|n IHn]; cbn; intros. { reflexivity. } { rewrite IHn by lia. erewrite (@skipn_nth_default _ idx ls) by lia. reflexivity. } Qed. Lemma expand_list_correct (n : nat) {A} (default : A) (ls : list A) (H : List.length ls = n) : expand_list default ls n = ls. Proof. subst; cbv [expand_list]; rewrite expand_list_helper_correct by reflexivity. rewrite skipn_0, firstn_all; reflexivity. Qed. Ltac expand_lists _ := let default_for A := match goal with | _ => (eval lazy in (_ : pointed A)) | _ => constr_fail_with ltac:(fun _ => idtac "Warning: could not infer a default value for list type" A) end in let T := lazymatch goal with |- _ = _ :> ?T => T end in let v := fresh in evar (v : T); transitivity v; [ subst v | repeat match goal with | [ H : @List.length ?A ?f = ?n |- context[?f] ] => let v := default_for A in rewrite <- (@expand_list_correct n A v f H); clear H end; lazymatch goal with | [ H : List.length ?f = _ |- context[?f] ] => fail 0 "Could not expand list" f | _ => idtac end; subst v; reflexivity ]. Lemma single_list_rect_to_match A (P:list A -> Type) (Pnil: P nil) (PS: forall a tl, P (a :: tl)) ls : @list_rect A P Pnil (fun a tl _ => PS a tl) ls = match ls with | cons a tl => PS a tl | nil => Pnil end. Proof. destruct ls; reflexivity. Qed. Lemma partition_app A (f : A -> bool) (a b : list A) : partition f (a ++ b) = (fst (partition f a) ++ fst (partition f b), snd (partition f a) ++ snd (partition f b)). Proof. revert b; induction a, b; cbn; rewrite ?app_nil_r; eta_expand; try reflexivity. rewrite !IHa; cbn; break_match; reflexivity. Qed. Lemma flat_map_map A B C (f : A -> B) (g : B -> list C) (xs : list A) : flat_map g (map f xs) = flat_map (fun x => g (f x)) xs. Proof. induction xs; cbn; congruence. Qed. Lemma flat_map_singleton A B (f : A -> B) (xs : list A) : flat_map (fun x => cons (f x) nil) xs = map f xs. Proof. induction xs; cbn; congruence. Qed. Lemma flat_map_ext A B (f g : A -> list B) xs (H : forall x, In x xs -> f x = g x) : flat_map f xs = flat_map g xs. Proof. induction xs; cbn in *; [ reflexivity | rewrite IHxs; f_equal ]; intros; intuition auto. Qed. Global Instance flat_map_Proper A B : Proper (pointwise_relation _ eq ==> eq ==> eq) (@flat_map A B). Proof. repeat intro; subst; apply flat_map_ext; auto. Qed. Global Instance map_Proper_eq {A B} : Proper ((eq ==> eq) ==> eq ==> eq) (@List.map A B) | 1. Proof. repeat intro; subst; apply pointwise_map; repeat intro; eauto. Qed. Global Instance flat_map_Proper_eq {A B} : Proper ((eq ==> eq) ==> eq ==> eq) (@List.flat_map A B) | 1. Proof. repeat intro; subst; apply flat_map_Proper; repeat intro; eauto. Qed. Global Instance partition_Proper {A} : Proper (pointwise_relation _ eq ==> eq ==> eq) (@List.partition A). Proof. cbv [pointwise_relation]; intros f g Hfg ls ls' ?; subst ls'. induction ls as [|l ls IHls]; cbn [partition]; rewrite ?IHls, ?Hfg; reflexivity. Qed. Global Instance partition_Proper_eq {A} : Proper ((eq ==> eq) ==> eq ==> eq) (@List.partition A) | 1. Proof. repeat intro; subst; apply partition_Proper; repeat intro; eauto. Qed. Global Instance fold_right_Proper {A B} : Proper (pointwise_relation _ (pointwise_relation _ eq) ==> eq ==> eq ==> eq) (@fold_right A B) | 1. Proof. cbv [pointwise_relation]; intros f g Hfg x y ? ls ls' ?; subst y ls'; revert x. induction ls as [|l ls IHls]; cbn [fold_right]; intro; rewrite ?IHls, ?Hfg; reflexivity. Qed. Global Instance fold_right_Proper_eq {A B} : Proper ((eq ==> eq ==> eq) ==> eq ==> eq ==> eq) (@fold_right A B) | 1. Proof. cbv [respectful]; repeat intro; subst; apply fold_right_Proper; repeat intro; eauto. Qed. Lemma partition_map A B (f : B -> bool) (g : A -> B) xs : partition f (map g xs) = (map g (fst (partition (fun x => f (g x)) xs)), map g (snd (partition (fun x => f (g x)) xs))). Proof. induction xs; cbn; [ | rewrite !IHxs ]; break_match; reflexivity. Qed. Lemma map_fst_partition A B (f : B -> bool) (g : A -> B) xs : map g (fst (partition (fun x => f (g x)) xs)) = fst (partition f (map g xs)). Proof. rewrite partition_map; reflexivity. Qed. Lemma map_snd_partition A B (f : B -> bool) (g : A -> B) xs : map g (snd (partition (fun x => f (g x)) xs)) = snd (partition f (map g xs)). Proof. rewrite partition_map; reflexivity. Qed. Lemma partition_In A (f:A -> bool) xs : forall x, @In A x xs <-> @In A x (if f x then fst (partition f xs) else snd (partition f xs)). Proof. intro x; destruct (f x) eqn:?; split; intros; repeat apply conj; revert dependent x; (induction xs as [|x' xs IHxs]; cbn; [ | destruct (f x') eqn:?, (partition f xs) ]; cbn in *; subst; intuition (subst; auto)); congruence. Qed. Lemma fst_partition_In A f xs : forall x, @In A x (fst (partition f xs)) <-> f x = true /\ @In A x xs. Proof. intro x; split; intros; repeat apply conj; revert dependent x; (induction xs as [|x' xs IHxs]; cbn; [ | destruct (f x') eqn:?, (partition f xs) ]; cbn in *; subst; intuition (subst; auto)); congruence. Qed. Lemma snd_partition_In A f xs : forall x, @In A x (snd (partition f xs)) <-> f x = false /\ @In A x xs. Proof. intro x; split; intros; repeat apply conj; revert dependent x; (induction xs as [|x' xs IHxs]; cbn; [ | destruct (f x') eqn:?, (partition f xs) ]; cbn in *; subst; intuition (subst; auto)); congruence. Qed. Lemma list_rect_map A B P (f : A -> B) N C ls : @list_rect B P N C (map f ls) = @list_rect A (fun ls => P (map f ls)) N (fun x xs rest => C (f x) (map f xs) rest) ls. Proof. induction ls as [|x xs IHxs]; cbn; [ | rewrite IHxs ]; reflexivity. Qed. Lemma flat_map_app A B (f : A -> list B) xs ys : flat_map f (xs ++ ys) = flat_map f xs ++ flat_map f ys. Proof. induction xs as [|x xs IHxs]; cbn; rewrite ?IHxs, <- ?app_assoc; reflexivity. Qed. Hint Rewrite flat_map_app : push_flat_map. Lemma map_flat_map A B C (f : A -> list B) (g : B -> C) xs : map g (flat_map f xs) = flat_map (fun x => map g (f x)) xs. Proof. induction xs as [|x xs IHxs]; cbn; rewrite ?map_app; congruence. Qed. Lemma combine_map_map A B C D (f : A -> B) (g : C -> D) xs ys : combine (map f xs) (map g ys) = map (fun ab => (f (fst ab), g (snd ab))) (combine xs ys). Proof. revert ys; induction xs, ys; cbn; congruence. Qed. Lemma combine_map_l A B C (f : A -> B) xs ys : @combine B C (map f xs) ys = map (fun ab => (f (fst ab), snd ab)) (combine xs ys). Proof. rewrite <- combine_map_map with (f:=f) (g:=fun x => x), map_id; reflexivity. Qed. Lemma combine_map_r A B C (f : B -> C) xs ys : @combine A C xs (map f ys) = map (fun ab => (fst ab, f (snd ab))) (combine xs ys). Proof. rewrite <- combine_map_map with (g:=f) (f:=fun x => x), map_id; reflexivity. Qed. Lemma combine_same A xs : @combine A A xs xs = map (fun x => (x, x)) xs. Proof. induction xs; cbn; congruence. Qed. Lemma if_singleton A (b:bool) (x y : A) : (if b then x::nil else y::nil) = (if b then x else y)::nil. Proof. now case b. Qed. Lemma flat_map_if_In A B (b : A -> bool) (f g : A -> list B) xs (b' : bool) : (forall v, In v xs -> b v = b') -> flat_map (fun x => if b x then f x else g x) xs = if b' then flat_map f xs else flat_map g xs. Proof. induction xs as [|x xs IHxs]; cbn; [ | intro H; rewrite IHxs, H by eauto ]; case b'; reflexivity. Qed. Lemma flat_map_if_In_sumbool A B X Y (b : forall a : A, sumbool (X a) (Y a)) (f g : A -> list B) xs (b' : bool) : (forall v, In v xs -> (if b v then true else false) = b') -> flat_map (fun x => if b x then f x else g x) xs = if b' then flat_map f xs else flat_map g xs. Proof. intro H; erewrite <- flat_map_if_In by refine H. apply flat_map_Proper; [ intro | reflexivity ]; break_innermost_match; reflexivity. Qed. Lemma map_if_In A B (b : A -> bool) (f g : A -> B) xs (b' : bool) : (forall v, In v xs -> b v = b') -> map (fun x => if b x then f x else g x) xs = if b' then map f xs else map g xs. Proof. induction xs as [|x xs IHxs]; cbn; [ | intro H; rewrite IHxs, H by eauto ]; case b'; reflexivity. Qed. Lemma map_if_In_sumbool A B X Y (b : forall a : A, sumbool (X a) (Y a)) (f g : A -> B) xs (b' : bool) : (forall v, In v xs -> (if b v then true else false) = b') -> map (fun x => if b x then f x else g x) xs = if b' then map f xs else map g xs. Proof. intro H; erewrite <- map_if_In by refine H. apply map_ext_in; intro; break_innermost_match; reflexivity. Qed. Lemma fold_right_map A B C (f : A -> B) xs (F : _ -> _ -> C) v : fold_right F v (map f xs) = fold_right (fun x y => F (f x) y) v xs. Proof. revert v; induction xs; cbn; intros; congruence. Qed. Lemma fold_right_flat_map A B C (f : A -> list B) xs (F : _ -> _ -> C) v : fold_right F v (flat_map f xs) = fold_right (fun x y => fold_right F y (f x)) v xs. Proof. revert v; induction xs; cbn; intros; rewrite ?fold_right_app; congruence. Qed. Lemma fold_right_ext A B f g v xs : (forall x y, f x y = g x y) -> @fold_right A B f v xs = fold_right g v xs. Proof. induction xs; cbn; intro H; rewrite ?H, ?IHxs; auto. Qed. Lemma fold_right_id_ext A B f v xs : (forall x y, f x y = y) -> @fold_right A B f v xs = v. Proof. induction xs; cbn; intro H; rewrite ?H; auto. Qed. Lemma nth_error_repeat_alt {A} (v : A) n i : nth_error (repeat v n) i = if dec (i < n)%nat then Some v else None. Proof. revert i; induction n as [|n IHn], i; cbn; try reflexivity. cbn [nth_error]; rewrite IHn; do 2 edestruct dec; try reflexivity; lia. Qed. Lemma nth_default_repeat A (v:A) n (d:A) i : nth_default d (repeat v n) i = if dec (i < n)%nat then v else d. Proof. cbv [nth_default]; rewrite nth_error_repeat_alt; now break_innermost_match. Qed. Hint Rewrite nth_default_repeat : push_nth_default simpl_nth_default. Lemma fold_right_if_dec_eq_seq A start len i f (x v : A) : ((start <= i < start + len)%nat -> f i v = x) -> (forall j v, (i <> j)%nat -> f j v = v) -> fold_right f v (seq start len) = if dec (start <= i < start + len)%nat then x else v. Proof. revert start v; induction len as [|len IHlen]; intros start v H H'; [ | rewrite seq_snoc, fold_right_app; cbn [fold_right] ]. { edestruct dec; try reflexivity; lia. } { destruct (dec (i = (start + len)%nat)); subst; [ | rewrite H' by lia ]; rewrite IHlen; eauto; intros; clear IHlen; repeat match goal with | _ => reflexivity | _ => lia | _ => progress subst | _ => progress specialize_by lia | [ H : context[dec ?P] |- _ ] => destruct (dec P) | [ |- context[dec ?P] ] => destruct (dec P) | [ H : f _ _ = _ |- _ ] => rewrite H | [ H : forall j, f j ?v = _ |- context[f _ ?v] ] => rewrite H end. } Qed. Lemma fold_left_push A (x y : A) (f : A -> A -> A) (f_assoc : forall x y z, f (f x y) z = f x (f y z)) ls : f x (fold_left f ls y) = fold_left f ls (f x y). Proof. revert x y; induction ls as [|l ls IHls]; cbn; [ reflexivity | ]. intros; rewrite IHls; f_equal; auto. Qed. Lemma fold_right_push A (x y : A) (f : A -> A -> A) (f_assoc : forall x y z, f (f x y) z = f x (f y z)) ls : f (fold_right f x ls) y = fold_right f (f x y) ls. Proof. rewrite <- (rev_involutive ls), !fold_left_rev_right, fold_left_push with (f:=fun x y => f y x); auto. Qed. Lemma nth_error_combine {A B} n (ls1 : list A) (ls2 : list B) : nth_error (combine ls1 ls2) n = match nth_error ls1 n, nth_error ls2 n with | Some v1, Some v2 => Some (v1, v2) | _, _ => None end. Proof. revert ls2 n; induction ls1 as [|l1 ls1 IHls1], ls2, n; cbn [combine nth_error]; try reflexivity; auto. edestruct nth_error; reflexivity. Qed. Lemma combine_repeat {A B} (a : A) (b : B) n : combine (repeat a n) (repeat b n) = repeat (a, b) n. Proof. induction n; cbn; congruence. Qed. Lemma combine_rev_rev_samelength {A B} ls1 ls2 : length ls1 = length ls2 -> @combine A B (rev ls1) (rev ls2) = rev (combine ls1 ls2). Proof. revert ls2; induction ls1 as [|? ? IHls1], ls2; cbn in *; try congruence; intros. rewrite combine_app_samelength, IHls1 by (rewrite ?rev_length; congruence); cbn [combine]. reflexivity. Qed. Lemma map_nth_default_seq {A} (d:A) n ls : length ls = n -> List.map (List.nth_default d ls) (List.seq 0 n) = ls. Proof. intro; subst. rewrite <- (List.rev_involutive ls); generalize (List.rev ls); clear ls; intro ls. rewrite List.rev_length. induction ls; cbn [length List.rev]; [ reflexivity | ]. rewrite seq_snoc, List.map_app. apply f_equal2; [ | cbn; rewrite nth_default_app, List.rev_length, Nat.sub_diag ]; [ etransitivity; [ | eassumption ]; apply List.map_ext_in; intro; rewrite Lists.List.in_seq; rewrite nth_default_app, List.rev_length; intros | ]. all: edestruct lt_dec; try (exfalso; lia). all: reflexivity. Qed. Lemma nth_error_firstn A ls n i : List.nth_error (@List.firstn A n ls) i = if lt_dec i n then List.nth_error ls i else None. Proof. revert ls i; induction n, ls, i; cbn; try reflexivity; destruct lt_dec; try reflexivity; rewrite IHn. all: destruct lt_dec; try reflexivity; lia. Qed. Lemma nth_error_rev A n ls : List.nth_error (@List.rev A ls) n = if lt_dec n (length ls) then List.nth_error ls (length ls - S n) else None. Proof. destruct lt_dec; [ | rewrite nth_error_length_error; rewrite ?List.rev_length; try reflexivity; lia ]. revert dependent n; induction ls as [|x xs IHxs]; cbn [length List.rev]; try reflexivity; intros; try lia. { rewrite nth_error_app, List.rev_length, Nat.sub_succ. destruct lt_dec. { rewrite IHxs by lia. rewrite <- (Nat.succ_pred_pos (length xs - n)) by lia. cbn [List.nth_error]. f_equal; lia. } { assert (n = length xs) by lia; subst. rewrite Nat.sub_diag. reflexivity. } } Qed. Lemma concat_fold_right_app A ls : @List.concat A ls = List.fold_right (@List.app A) nil ls. Proof. induction ls; cbn; eauto. Qed. Lemma map_update_nth_ext {A B n} f1 f2 f3 ls1 ls2 : map f3 ls1 = ls2 -> (forall x, List.In x ls1 -> f3 (f2 x) = f1 (f3 x)) -> map f3 (@update_nth A n f2 ls1) = @update_nth B n f1 ls2. Proof. revert ls1 ls2; induction n as [|n IHn], ls1 as [|x1 xs1], ls2 as [|x2 xs2]; cbn; intros H0 H1; try discriminate; try reflexivity. all: inversion H0; clear H0; subst. all: f_equal; eauto using or_introl. Qed. Lemma push_f_list_rect {P P'} (f : P -> P') {A} Pnil Pcons Pcons' ls (Hcons : forall x xs rec, f (Pcons x xs rec) = Pcons' x xs (f rec)) : f (list_rect (fun _ : list A => P) Pnil Pcons ls) = list_rect (fun _ => _) (f Pnil) Pcons' ls. Proof. induction ls as [|x xs IHxs]; cbn [list_rect]; [ reflexivity | ]. rewrite Hcons, IHxs; reflexivity. Qed. Lemma eq_app_list_rect {A} (ls1 ls2 : list A) : List.app ls1 ls2 = list_rect _ ls2 (fun x _ rec => x :: rec) ls1. Proof. revert ls2; induction ls1, ls2; cbn; f_equal; eauto. Qed. Lemma eq_flat_map_list_rect {A B} f (ls : list A) : @flat_map A B f ls = list_rect _ nil (fun x _ rec => f x ++ rec) ls. Proof. induction ls; cbn; eauto. Qed. Lemma eq_partition_list_rect {A} f (ls : list A) : @partition A f ls = list_rect _ (nil, nil) (fun x _ '(a, b) => bool_rect (fun _ => _) (x :: a, b) (a, x :: b) (f x)) ls. Proof. induction ls; cbn; eauto. Qed. Lemma eq_fold_right_list_rect {A B} f v (ls : list _) : @fold_right A B f v ls = list_rect _ v (fun x _ rec => f x rec) ls. Proof. induction ls; cbn; eauto. Qed. Lemma eq_map_list_rect {A B} f (ls : list _) : @List.map A B f ls = list_rect _ nil (fun x _ rec => f x :: rec) ls. Proof. induction ls; cbn; eauto. Qed. Lemma map_repeat {A B} (f : A -> B) v k : List.map f (List.repeat v k) = List.repeat (f v) k. Proof. induction k; cbn; f_equal; assumption. Qed. Lemma map_const {A B} (v : B) (ls : list A) : List.map (fun _ => v) ls = List.repeat v (List.length ls). Proof. induction ls; cbn; f_equal; assumption. Qed. Lemma Forall2_rev {A B R ls1 ls2} : @List.Forall2 A B R ls1 ls2 -> List.Forall2 R (rev ls1) (rev ls2). Proof using Type. induction 1; cbn [rev]; [ constructor | ]. apply Forall2_app; auto. Qed. Lemma Forall2_update_nth {A B f g n R ls1 ls2} : @List.Forall2 A B R ls1 ls2 -> (forall v1, nth_error ls1 n = Some v1 -> forall v2, nth_error ls2 n = Some v2 -> R v1 v2 -> R (f v1) (g v2)) -> @List.Forall2 A B R (update_nth n f ls1) (update_nth n g ls2). Proof using Type. intro H; revert n; induction H, n; cbn [nth_error update_nth]. all: repeat first [ progress intros | progress specialize_by_assumption | assumption | match goal with | [ |- List.Forall2 _ _ _ ] => constructor | [ H : forall x, Some _ = Some x -> _ |- _ ] => specialize (H _ eq_refl) | [ IH : forall n : nat, _, H : forall v1, nth_error ?l ?n = Some v1 -> _ |- _ ] => specialize (IH n H) end ]. Qed. Fixpoint remove_duplicates' {A} (beq : A -> A -> bool) (ls : list A) : list A := match ls with | nil => nil | cons x xs => if existsb (beq x) xs then @remove_duplicates' A beq xs else x :: @remove_duplicates' A beq xs end. Definition remove_duplicates {A} (beq : A -> A -> bool) (ls : list A) : list A := List.rev (remove_duplicates' beq (List.rev ls)). Lemma InA_remove_duplicates' {A} (A_beq : A -> A -> bool) (R : A -> A -> Prop) {R_Transitive : Transitive R} (A_bl : forall x y, A_beq x y = true -> R x y) (ls : list A) : forall x, InA R x (remove_duplicates' A_beq ls) <-> InA R x ls. Proof using Type. induction ls as [|x xs IHxs]; intro y; [ reflexivity | ]. cbn [remove_duplicates']; break_innermost_match; rewrite ?InA_cons, IHxs; [ | reflexivity ]. split; [ now auto | ]. intros [?|?]; subst; auto; []. rewrite existsb_exists in *. destruct_head'_ex; destruct_head'_and. match goal with H : _ |- _ => apply A_bl in H end. rewrite InA_alt. eexists; split; [ | eassumption ]. etransitivity; eassumption. Qed. Lemma InA_remove_duplicates {A} (A_beq : A -> A -> bool) (R : A -> A -> Prop) {R_Transitive : Transitive R} (A_bl : forall x y, A_beq x y = true -> R x y) (ls : list A) : forall x, InA R x (remove_duplicates A_beq ls) <-> InA R x ls. Proof using Type. cbv [remove_duplicates]; intro. rewrite InA_rev, InA_remove_duplicates', InA_rev; auto; reflexivity. Qed. Lemma InA_eq_In_iff {A} x ls : InA eq x ls <-> @List.In A x ls. Proof using Type. rewrite InA_alt. repeat first [ progress destruct_head'_and | progress destruct_head'_ex | progress subst | solve [ eauto ] | apply conj | progress intros ]. Qed. Lemma NoDupA_eq_NoDup {A} ls : @NoDupA A eq ls <-> NoDup ls. Proof using Type. split; intro H; induction H; constructor; eauto; (idtac + rewrite <- InA_eq_In_iff + rewrite InA_eq_In_iff); assumption. Qed. Lemma in_remove_duplicates' {A} (A_beq : A -> A -> bool) (A_bl : forall x y, A_beq x y = true -> x = y) (ls : list A) : forall x, List.In x (remove_duplicates' A_beq ls) <-> List.In x ls. Proof using Type. intro x; rewrite <- !InA_eq_In_iff; apply InA_remove_duplicates'; eauto; exact _. Qed. Lemma in_remove_duplicates {A} (A_beq : A -> A -> bool) (A_bl : forall x y, A_beq x y = true -> x = y) (ls : list A) : forall x, List.In x (remove_duplicates A_beq ls) <-> List.In x ls. Proof using Type. intro x; rewrite <- !InA_eq_In_iff; apply InA_remove_duplicates; eauto; exact _. Qed. Lemma NoDupA_remove_duplicates' {A} (A_beq : A -> A -> bool) (R : A -> A -> Prop) {R_Transitive : Transitive R} (A_lb : forall x y, A_beq x y = true -> R x y) (A_bl : forall x y, R x y -> A_beq x y = true) (ls : list A) : NoDupA R (remove_duplicates' A_beq ls). Proof using Type. induction ls as [|x xs IHxs]; [ now constructor | ]. cbn [remove_duplicates']; break_innermost_match; [ assumption | constructor; auto ]; []. intro H'. cut (false = true); [ discriminate | ]. match goal with H : _ = false |- _ => rewrite <- H end. rewrite existsb_exists in *. rewrite InA_remove_duplicates' in H' by eauto. rewrite InA_alt in H'. destruct_head'_ex; destruct_head'_and. eauto. Qed. Lemma NoDupA_remove_duplicates {A} (A_beq : A -> A -> bool) (R : A -> A -> Prop) {R_Equivalence : Equivalence R} (A_lb : forall x y, A_beq x y = true -> R x y) (A_bl : forall x y, R x y -> A_beq x y = true) (ls : list A) : NoDupA R (remove_duplicates A_beq ls). Proof using Type. cbv [remove_duplicates]. apply NoDupA_rev; [ assumption | ]. apply NoDupA_remove_duplicates'; auto; exact _. Qed. Lemma NoDup_remove_duplicates' {A} (A_beq : A -> A -> bool) (R : A -> A -> Prop) (A_lb : forall x y, A_beq x y = true -> x = y) (A_bl : forall x y, x = y -> A_beq x y = true) (ls : list A) : NoDup (remove_duplicates' A_beq ls). Proof using Type. apply NoDupA_eq_NoDup, NoDupA_remove_duplicates'; auto; exact _. Qed. Lemma NoDup_remove_duplicates {A} (A_beq : A -> A -> bool) (A_lb : forall x y, A_beq x y = true -> x = y) (A_bl : forall x y, x = y -> A_beq x y = true) (ls : list A) : NoDup (remove_duplicates A_beq ls). Proof using Type. apply NoDupA_eq_NoDup, NoDupA_remove_duplicates; auto; exact _. Qed. Lemma remove_duplicates'_eq_NoDupA {A} (A_beq : A -> A -> bool) (R : A -> A -> Prop) (A_lb : forall x y, A_beq x y = true -> R x y) (ls : list A) : NoDupA R ls -> remove_duplicates' A_beq ls = ls. Proof using Type. intro H; induction H as [|x xs H0 H1 IHxs]; [ reflexivity | ]. cbn [remove_duplicates']. rewrite IHxs. repeat first [ break_innermost_match_step | reflexivity | progress destruct_head'_ex | progress destruct_head'_and | progress rewrite existsb_exists in * | progress rewrite InA_alt in * | match goal with | [ H : ~(exists x, and _ _) |- _ ] => specialize (fun x H0 H1 => H (ex_intro _ x (conj H0 H1))) end | solve [ exfalso; eauto ] ]. Qed. Lemma remove_duplicates_eq_NoDupA {A} (A_beq : A -> A -> bool) (R : A -> A -> Prop) {R_equiv : Equivalence R} (A_lb : forall x y, A_beq x y = true -> R x y) (ls : list A) : NoDupA R ls -> remove_duplicates A_beq ls = ls. Proof using Type. cbv [remove_duplicates]; intro. erewrite remove_duplicates'_eq_NoDupA by (eauto + apply NoDupA_rev; eauto). rewrite rev_involutive; reflexivity. Qed. Lemma remove_duplicates'_eq_NoDup {A} (A_beq : A -> A -> bool) (A_lb : forall x y, A_beq x y = true -> x = y) (ls : list A) : NoDup ls -> remove_duplicates' A_beq ls = ls. Proof using Type. intro H; apply remove_duplicates'_eq_NoDupA with (R:=eq); eauto. now apply NoDupA_eq_NoDup. Qed. Lemma remove_duplicates_eq_NoDup {A} (A_beq : A -> A -> bool) (A_lb : forall x y, A_beq x y = true -> x = y) (ls : list A) : NoDup ls -> remove_duplicates A_beq ls = ls. Proof using Type. intro H; apply remove_duplicates_eq_NoDupA with (R:=eq); eauto; try exact _. now apply NoDupA_eq_NoDup. Qed. Lemma eq_repeat_nat_rect {A} x n : @List.repeat A x n = nat_rect _ nil (fun k repeat_k => x :: repeat_k) n. Proof using Type. induction n; cbn; f_equal; assumption. Qed. Lemma eq_firstn_nat_rect {A} n ls : @List.firstn A n ls = nat_rect _ (fun _ => nil) (fun n' firstn_n' ls => match ls with | nil => nil | cons x xs => x :: firstn_n' xs end) n ls. Proof using Type. revert ls; induction n, ls; cbn; f_equal; auto. Qed. Lemma eq_skipn_nat_rect {A} n ls : @List.skipn A n ls = nat_rect _ (fun ls => ls) (fun n' skipn_n' ls => match ls with | nil => nil | cons x xs => skipn_n' xs end) n ls. Proof using Type. revert ls; induction n, ls; cbn; f_equal; auto. Qed. Lemma eq_combine_list_rect {A B} xs ys : @List.combine A B xs ys = list_rect _ (fun _ => nil) (fun x xs combine_xs ys => match ys with | nil => nil | y :: ys => (x, y) :: combine_xs ys end) xs ys. Proof using Type. revert ys; induction xs, ys; cbn; f_equal; auto. Qed. Lemma eq_length_list_rect {A} xs : @List.length A xs = (list_rect _) 0%nat (fun _ xs length_xs => S length_xs) xs. Proof using Type. induction xs; cbn; f_equal; auto. Qed. Lemma eq_rev_list_rect {A} xs : @List.rev A xs = (list_rect _) nil (fun x xs rev_xs => rev_xs ++ [x]) xs. Proof using Type. induction xs; cbn; f_equal; auto. Qed. Lemma eq_update_nth_nat_rect {A} n f xs : @update_nth A n f xs = (nat_rect _) (fun xs => match xs with | nil => nil | x' :: xs' => f x' :: xs' end) (fun n' update_nth_n' xs => match xs with | nil => nil | x' :: xs' => x' :: update_nth_n' xs' end) n xs. Proof using Type. revert xs; induction n, xs; cbn; f_equal; auto. Qed. Lemma flat_map_const_nil {A B} ls : @flat_map A B (fun _ => nil) ls = nil. Proof using Type. induction ls; cbn; auto. Qed. Lemma fold_left_map A B C f f' l a : @fold_left A B f (@List.map C _ f' l) a = fold_left (fun x y => f x (f' y)) l a. Proof using Type. revert a; induction l; cbn [List.map List.fold_left]; auto. Qed. Lemma Forall_map_iff {A B} (f : A -> B) ls P : Forall P (List.map f ls) <-> Forall (fun x => P (f x)) ls. Proof. induction ls as [|?? IH]; cbn [List.map]; split; intro H; inversion_clear H; constructor; split_iff; auto. Qed. Lemma ForallOrdPairs_map_iff {A B} (f : A -> B) ls P : ForallOrdPairs P (List.map f ls) <-> ForallOrdPairs (fun x y => P (f x) (f y)) ls. Proof. pose proof (@Forall_map_iff A B f) as HF. induction ls as [|?? IH]; cbn [List.map]; split; intro H; inversion_clear H; constructor; split_iff; auto. Qed. Lemma HdRel_map_iff {A B} (f : A -> B) R x xs : HdRel R (f x) (List.map f xs) <-> HdRel (fun x y => R (f x) (f y)) x xs. Proof. destruct xs; split; intro H; inversion_clear H; constructor; auto. Qed. Lemma Sorted_map_iff {A B} (f : A -> B) R ls : Sorted R (List.map f ls) <-> Sorted (fun x y => R (f x) (f y)) ls. Proof. induction ls as [|?? IH]; cbn [List.map]; split; intro H; inversion_clear H; constructor; split_iff; auto; now apply HdRel_map_iff. Qed. Lemma In_nth_error_iff {A l x} : In x l <-> exists n : nat, @nth_error A l n = Some x. Proof. split; [ now apply In_nth_error | intros [? ?]; eapply nth_error_In; eassumption ]. Qed. Lemma fold_right_fun_apply {A B C} (ls : list B) (f : B -> C -> (A -> C)) init x : fold_right (fun b F a => f b (F a) a) init ls x = fold_right (fun b c => f b c x) (init x) ls. Proof. induction ls as [|?? IH]; cbn; now f_equal. Qed. Ltac make_fold_right_fun_apply ty := multimatch ty with | context[@fold_right ?AC ?B ?f ?init ?ls ?x] => let fv := fresh in let b := fresh "b" in let F := fresh "F" in let a := fresh "a" in let f := lazymatch constr:( fun b F a => match f b F a return _ with | fv => ltac:(let fv := (eval cbv [fv] in fv) in lazymatch (eval pattern a, (F a), b in fv) with | ?f _ _ _ => refine (fun x y z => f z y x) end) end) with | fun _ _ _ => ?f => (eval cbv beta in f) | ?f => idtac "failed to eliminate the functional dependencies of" f; fail 0 "failed to eliminate the functional dependencies of" f end in constr:(@fold_right_fun_apply _ _ _ ls f init x) end. Ltac rewrite_fold_right_fun_apply := match goal with | [ H : ?T |- _ ] => let pf := make_fold_right_fun_apply T in rewrite pf in H | [ |- ?T ] => let pf := make_fold_right_fun_apply T in rewrite pf end. Lemma fold_left_fun_apply {A B C} (ls : list B) (f : C -> B -> (A -> C)) init x : fold_left (fun F b a => f (F a) b a) ls init x = fold_left (fun b c => f b c x) ls (init x). Proof. rewrite <- !fold_left_rev_right; now rewrite_fold_right_fun_apply. Qed. Ltac make_fold_left_fun_apply ty := multimatch ty with | context[@fold_left ?AC ?B ?f ?ls ?init ?x] => let fv := fresh in let b := fresh "b" in let F := fresh "F" in let a := fresh "a" in let f := lazymatch constr:( fun F b a => match f F b a return _ with | fv => ltac:(let fv := (eval cbv [fv] in fv) in lazymatch (eval pattern a, b, (F a) in fv) with | ?f _ _ _ => refine (fun x y z => f z y x) end) end) with | fun _ _ _ => ?f => (eval cbv beta in f) | ?f => idtac "failed to eliminate the functional dependencies of" f; fail 0 "failed to eliminate the functional dependencies of" f end in constr:(@fold_left_fun_apply _ _ _ ls f init x) end. Ltac rewrite_fold_left_fun_apply := match goal with | [ H : ?T |- _ ] => let pf := make_fold_left_fun_apply T in rewrite pf in H | [ |- ?T ] => let pf := make_fold_left_fun_apply T in rewrite pf end. Fixpoint takeWhile {A} (f : A -> bool) (ls : list A) : list A := match ls with | nil => nil | x :: xs => if f x then x :: takeWhile f xs else nil end. Fixpoint dropWhile {A} (f : A -> bool) (ls : list A) : list A := match ls with | nil => nil | x :: xs => if f x then dropWhile f xs else ls end. Lemma takeWhile_app_dropWhile {A} f xs : @takeWhile A f xs ++ @dropWhile A f xs = xs. Proof. induction xs; cbn; break_innermost_match; boring. Qed. Lemma filter_takeWhile {A} f xs : filter f (@takeWhile A f xs) = @takeWhile A f xs. Proof. induction xs; cbn; break_innermost_match; boring. Qed. Definition is_nil {A} (x : list A) : bool := match x with | nil => true | _ => false end. Lemma is_nil_eq_nil_iff {A x} : @is_nil A x = true <-> x = nil. Proof. destruct x; cbv; split; congruence. Qed. Lemma find_none_iff {A} (f : A -> bool) (xs : list A) : find f xs = None <-> forall x, In x xs -> f x = false. Proof. split; try apply find_none. pose proof (find_some f xs) as H. edestruct find; [ specialize (H _ eq_refl) | reflexivity ]. destruct H as [H1 H2]. intro H'; specialize (H' _ H1); congruence. Qed. Lemma find_none_iff_nth_error {A} (f : A -> bool) (xs : list A) : find f xs = None <-> forall n a, nth_error xs n = Some a -> f a = false. Proof. rewrite find_none_iff. setoid_rewrite In_nth_error_iff. intuition (destruct_head'_ex; eauto). Qed. Lemma find_some_iff {A} (f : A -> bool) (xs : list A) x : find f xs = Some x <-> exists n, nth_error xs n = Some x /\ f x = true /\ forall n', n' < n -> forall a, nth_error xs n' = Some a -> f a = false. Proof. induction xs as [|y xs IHxs]; cbn [find]. all: repeat first [ apply conj | progress intros | progress destruct_head'_ex | progress destruct_head'_and | progress Option.inversion_option | progress break_innermost_match_hyps | progress subst | progress cbn in * | assumption | exists 0; cbn; repeat split; try assumption; (idtac + (intros; exfalso)); lia | progress break_innermost_match | reflexivity | congruence | match goal with | [ H : nth_error nil ?i = _ |- _ ] => is_var i; destruct i | [ H : nth_error (cons _ _) ?i = _ |- _ ] => is_var i; destruct i | [ H : ?T <-> _, H' : ?T |- _ ] => destruct H as [H _]; specialize (H H') | [ H : S ?x < S ?y |- _ ] => assert (x < y) by lia; clear H | [ H : forall a, Some _ = Some a -> _ |- _ ] => specialize (H _ eq_refl) | [ H : forall a, Some a = Some _ -> _ |- _ ] => specialize (H _ eq_refl) | [ H : forall n, n < S ?v -> @?P n |- _ ] => assert (forall n, n < v -> P (S n)) by (intros ? ?; apply H; lia); specialize (H 0 ltac:(lia)) end | eexists (S _); cbn; repeat apply conj; [ eassumption | .. ]; try assumption; intros [|?] | progress split_iff | solve [ eauto with nocore ] | progress specialize_by eauto ]. Qed. Section find_index. Context {A} (f : A -> bool). Definition find_index (xs : list A) : option nat := option_map (@fst _ _) (find (fun v => f (snd v)) (enumerate xs)). Lemma find_index_none_iff xs : find_index xs = None <-> forall i a, nth_error xs i = Some a -> f a = false. Proof. cbv [find_index enumerate]. edestruct find eqn:H; cbn; [ split; [ congruence | ] | split; [ intros _ | reflexivity ] ]. { rewrite find_some_iff in H. destruct H as [n H]; intro H'; specialize (H' n). rewrite nth_error_combine, nth_error_seq in H. break_innermost_match_hyps; destruct_head'_and; Option.inversion_option; subst; cbn in *. specialize (H' _ eq_refl); congruence. } { rewrite find_none_iff_nth_error in H. intros n a; specialize (H n (n, a)). rewrite nth_error_combine, nth_error_seq in H. edestruct lt_dec; [ | rewrite nth_error_length_error by lia; congruence ]. edestruct nth_error eqn:?; intros; Option.inversion_option; subst; specialize (H eq_refl); assumption. } Qed. Lemma find_index_some_iff xs n : find_index xs = Some n <-> ((exists x, nth_error xs n = Some x /\ f x = true) /\ forall n', n' < n -> forall a, nth_error xs n' = Some a -> f a = false). Proof. cbv [find_index enumerate]. edestruct find eqn:H; cbn; [ | split; [ congruence | ] ]. { rewrite find_some_iff in H. destruct H as [n' H]. rewrite nth_error_combine, nth_error_seq in H. setoid_rewrite nth_error_combine in H. setoid_rewrite nth_error_seq in H. break_innermost_match_hyps; split; intro H'; destruct_head'_and; Option.inversion_option; subst; cbn in *. all: repeat apply conj; eauto. { let H := match goal with H : forall n, n < _ -> _ |- _ => H end in intros i H' a' H''; specialize (H i H' (i, a')); rewrite H'' in H; break_innermost_match_hyps; [ specialize (H eq_refl); assumption | ]. rewrite nth_error_length_error in H'' by lia; congruence. } { match goal with |- Some ?n = Some ?m => destruct (lt_eq_lt_dec n m) end; destruct_head' sumbool; subst; try reflexivity. all: match goal with H : forall n', n' < _ -> _ |- _ => specialize (H _ ltac:(eassumption)) end. { match goal with H : forall a, nth_error _ _ = Some _ -> _ |- _ => specialize (H _ ltac:(eassumption)); congruence end. } { destruct_head'_ex; destruct_head'_and. break_innermost_match_hyps; try congruence; try lia. Option.inversion_option; subst. match goal with H : forall x, Some _ = Some x -> _ |- _ => specialize (H _ eq_refl) end. cbn in *. congruence. } } } { rewrite find_none_iff_nth_error in H. intros [ [a [H0 H1]] ?]; specialize (H n (n, a)). rewrite nth_error_combine, nth_error_seq, H0 in H. break_innermost_match_hyps; [ | rewrite nth_error_length_error in H0 by lia; congruence ]. specialize (H eq_refl); cbn in *. congruence. } Qed. End find_index.
import Numeric.GSL.Polynomials import Data.Complex *Main> mapM_ print $ polySolve [0,2,-3,1] (-5.421010862427522e-20) :+ 0.0 2.000000000000001 :+ 0.0 0.9999999999999996 :+ 0.0
import data.nat.basic -- The next lemma won't be used, it's a warming up exercise for the one below. -- It could go to mathlib. lemma exists_by_induction {α : Type*} {P : ℕ → α → Prop} (h₀ : ∃ a, P 0 a) (ih : ∀ n a, P n a → ∃ a', P (n+1) a') : ∃ f : ℕ → α, ∀ n, P n (f n) := begin choose f₀ hf₀ using h₀, choose! F hF using ih, exact ⟨λ n, nat.rec_on n f₀ F, λ n, nat.rec hf₀ (λ n ih, hF n _ ih) n⟩ end -- We make `P` and `Q` explicit to help the elaborator when applying the lemma -- (elab_as_eliminator isn't enough). lemma exists_by_induction' {α : Type*} (P : ℕ → α → Prop) (Q : ℕ → α → α → Prop) (h₀ : ∃ a, P 0 a) (ih : ∀ n a, P n a → ∃ a', P (n+1) a' ∧ Q n a a') : ∃ f : ℕ → α, ∀ n, P n (f n) ∧ Q n (f n) (f $ n+1) := begin choose f₀ hf₀ using h₀, choose! F hF hF' using ih, have key : ∀ n, P n (nat.rec_on n f₀ F), from λ n, nat.rec hf₀ (λ n ih, hF n _ ih) n, exact ⟨λ n, nat.rec_on n f₀ F, λ n, ⟨key n, hF' n _ (key n)⟩⟩ end
import dyck.basic open list universe u variables {α : Type u} {L L₁ : list (α × bool)} namespace list lemma append_singleton_iff {L L₁ : list α} {x : α} : L ++ L₁ = [x] ↔ (L = [] ∧ L₁ = [x]) ∨ (L₁ = [] ∧ L = [x]) := begin split, { intro h, induction L, left, simp at *, exact h, simp at *, subst_vars, exact ⟨h.2.2, h.1, h.2.1⟩, }, { intro h, induction h, { rw [h.1, h.2], simp, }, { rw [h.1, h.2], simp, } } end end list namespace group.basic theorem mul_mul_mul_eq_one_iff {G : Type*} [group G]: ∀ {x y z : G}, x*y*z = 1 ↔ y*z*x = 1 := begin intros x y z, conv_lhs { rw [← mul_right_inj (x⁻¹), ← mul_assoc, ← mul_assoc, inv_mul_self, one_mul, mul_one, ← mul_left_inj x, inv_mul_self] } end theorem mul_mul_mul_eq_one_iff' {G : Type*} [group G]: ∀ (x y z : G), x*y*z = 1 ↔ z*x*y = 1 := begin intros x y z, conv_lhs { rw [mul_mul_mul_eq_one_iff, ← mul_right_inj (y⁻¹), ← mul_assoc, ← mul_assoc, inv_mul_self, one_mul, mul_one, ← mul_left_inj y, inv_mul_self] }, end end group.basic -------------------------------------------------------------------------------------------------------- namespace free_group lemma red.step.reverse (L L₁ : list (α × bool)) : red.step L L₁ ↔ red.step (L.reverse) (L₁.reverse) := begin split, { intro h; induction h; simp }, { intro h, generalize eq₁ : (L.reverse = L'), generalize eq₂ : (L₁.reverse = L₁), rw eq₁ at *, rw eq₂ at *, induction h, rw list.reverse_eq_iff at *, simp only [bnot, list.reverse_append, list.reverse_cons, list.append_assoc, list.singleton_append, list.cons_append] at *, rw [eq₁, eq₂], simp only [list.nil_append, red.step.bnot_rev]} end lemma red.reverse (L L₁ : list (α × bool)) : red L L₁ → red (L.reverse) (L₁.reverse) := begin intro h, apply relation.refl_trans_gen.head_induction_on h, fconstructor, intros a c hac hcL₁ hcL₁rev, rw ← red at *, rw red.step.reverse at hac, have h₁ := red.step.to_red hac, exact red.trans h₁ hcL₁rev, end lemma red.reverse_iff (L L₁ : list (α × bool)) : red (L.reverse) (L₁.reverse) ↔ red L L₁ := begin split, intro h, have h₁ := @red.reverse α (L.reverse) (L₁.reverse) h, rw [list.reverse_reverse, list.reverse_reverse] at *, exacts [h₁, @red.reverse α L L₁], end lemma red.append_singleton_nil_iff (L : list (α × bool)) : ∀ {x : α} {b : bool}, red (L ++ [(x, b)]) [] ↔ red L [(x, !b)] := begin intros x b, rw ← red.reverse_iff, split, { intro h, simp only [list.reverse_append, list.reverse_singleton, list.singleton_append, list.reverse_nil] at *, rw red.cons_nil_iff_singleton at *, rw ← red.reverse_iff, simp only [list.reverse_singleton], exact h }, { intro h, simp only [list.reverse_append, list.reverse_singleton, list.singleton_append, list.reverse_nil], rw red.cons_nil_iff_singleton at *, rw ← red.reverse_iff, simp only [list.reverse_reverse, list.reverse_singleton], exact h } end lemma mk_bnot : ∀ {x : α} {b : bool}, mk ([(x, b), (x, !b)]) = 1 := begin intros x b, rw [one_eq_mk, red.exact, relation.join], use ([]), exact ⟨red.cons_nil_iff_singleton.mpr red.refl, red.refl⟩, end lemma mk_one_iff {L : list (α × bool)}: mk L = 1 ↔ red L [] := begin split, { intro h, rw [one_eq_mk, red.exact] at h, rcases h with ⟨c, hl, hr⟩, rw red.nil_iff at hr, rw hr at hl, exact hl }, { intro h, rw [one_eq_mk, red.exact], use ([]), exact ⟨h, red.refl⟩ } end theorem cons_one_exists_prefix_eq_one {L : list (α × bool)} {x : α} {b : bool} : free_group.mk ((x, b) :: L ) = 1 → (∃ e : list (α × bool), list.is_prefix (e ++ [(x, !b)]) L ∧ free_group.mk e = 1) := begin intro h, rw [one_eq_mk, red.exact, relation.join] at h, rcases h with ⟨L₁, hl, hr⟩, rw red.nil_iff at hr, rw [hr, red.cons_nil_iff_singleton] at hl, induction hl using relation.refl_trans_gen.head_induction_on with w w' hww' hw' ih, { use ([]), simp only [list.nil_append], exact ⟨list.prefix_rfl, rfl⟩ }, { clear hr, induction hww' with p s a b', rcases ih with ⟨e, ihl, ihr⟩, rw list.is_prefix at ihl, cases ihl with t, simp only [list.append_assoc, list.singleton_append] at *, rw list.append_eq_append_iff at ihl_h, induction ihl_h, { rcases ihl_h with ⟨a', ihl_hl,ihl_hr⟩, rw list.cons_eq_append_iff at ihl_hr, induction ihl_hr, { use (e ++ (a, b') :: [(a, !b')]), split, { cases ihl_hr with h₁ h₂, rw [h₂, ihl_hl, h₁, list.is_prefix], use t, simp only [list.append_assoc, list.cons_append, list.singleton_append, list.append_nil] }, { rw [← mul_mk, ihr, one_mul, free_group.mk_bnot] } }, { rcases ihl_hr with ⟨a₁, h₁, h₂⟩, use e, rw h₁ at ihl_hl, rw [ihl_hl, list.is_prefix], split, use (a₁ ++ (a, b') :: (a, !b') :: s), simp only [bnot, list.append_assoc, list.singleton_append, list.cons_append, eq_self_iff_true, list.nil_append], exact ihr } }, { rcases ihl_h with ⟨c', h₁, h₂⟩, use (p ++ (a, b')::(a, !b')::c'), split, { rw [h₂, list.is_prefix], use t, simp only [list.append_assoc, list.cons_append, list.singleton_append] }, { rw ← mul_mk, have h : (a, b') :: (a, !b') :: c' = [(a, b'),(a, !b')] ++ c', { simp only [list.cons_append, list.singleton_append, eq_self_iff_true, and_self] }, rw [h, ← mul_mk, mk_bnot, one_mul, mul_mk, ← h₁, ihr] } } } end theorem append_singleton_one_exists_suffix_eq_one {L : list (α × bool)} {x : α} {b : bool} : free_group.mk (L ++ [(x, b)]) = 1 → (∃ e : list (α × bool), list.is_suffix ((x, !b) :: e) L ∧ free_group.mk e = 1) := begin intro h, rw [one_eq_mk, red.exact, relation.join] at h, rcases h with ⟨L₁, hl, hr⟩, rw red.nil_iff at hr, rw hr at hl, rw ← red.reverse_iff at hl, simp only [list.reverse_append, list.reverse_singleton, list.singleton_append, list.reverse_nil] at hl, have h₁ : mk ((x, b)::L.reverse) = 1, { rw [one_eq_mk, red.exact], use ([]), exact ⟨hl, red.refl⟩ }, have h₂ := cons_one_exists_prefix_eq_one h₁, rcases h₂ with ⟨e, _, _⟩, use (e.reverse), split, { refine list.reverse_prefix.mp _, simp only [list.reverse_cons, list.reverse_reverse], exact h₂_h_left } , { rw [one_eq_mk, red.exact], use ([]), rw [one_eq_mk, red.exact, relation.join] at h₂_h_right, rcases h₂_h_right with ⟨c, _, _⟩, rw red.nil_iff at h₂_h_right_h_right, rw [h₂_h_right_h_right, ← red.reverse_iff ] at h₂_h_right_h_left, simp only [list.reverse_nil] at *, exact ⟨h₂_h_right_h_left, red.refl⟩ } end theorem append_cons_one_exists_suffix_or_prefix_eq_one {L L₁ : list (α × bool)} {x : α} {b : bool} : free_group.mk (L ++ (x, b) :: L₁ ) = 1 → (∃ e : list (α × bool), list.is_suffix ((x, !b) :: e) L ∧ free_group.mk e = 1) ∨ (∃ e : list (α × bool), list.is_prefix (e ++ [(x, !b)]) L₁ ∧ free_group.mk e = 1) := begin intro h, { have h₁ : mk ((x, b)::(L₁ ++ L)) = 1, { rw [← mul_mk, ← list.singleton_append, ← mul_mk, ← mul_assoc, group.basic.mul_mul_mul_eq_one_iff] at h, repeat { rw mul_mk at h }, simp only [list.singleton_append, list.cons_append] at h, exact h }, have h₂ : mk (L₁ ++ L ++ [(x, b)]) = 1, by { rw [← mul_mk, ← list.singleton_append, ← mul_mk, ← mul_assoc, group.basic.mul_mul_mul_eq_one_iff'] at h, repeat { rw mul_mk at h }, simp only [list.append_assoc] at h, rw ← list.append_assoc at h, exact h }, have h₃ := cons_one_exists_prefix_eq_one h₁, rcases h₃ with ⟨e, h₄, h₅⟩, rw list.is_prefix at h₄, cases h₄ with t h₄, simp only [list.append_assoc, list.singleton_append] at *, rw list.append_eq_append_iff at h₄, induction h₄, { rcases h₄ with ⟨a, h₆, h₇⟩, rw list.cons_eq_append_iff at h₇, induction h₇, { rw h₇.1 at h₆, simp only [list.append_nil] at *, have h₈ : mk (L ++ [(x,b)]) = 1, { rw ← list.singleton_append at h₁, rw [← mul_mk, ← mul_mk, h₆, h₅, one_mul, mul_mk] at h₂, exact h₂ }, left, exact append_singleton_one_exists_suffix_eq_one h₈ }, { rcases h₇ with ⟨a', h₈, h₉⟩, right, use e, rw h₆, split, { rw h₈, use a', simp only [list.append_assoc, list.singleton_append] }, { exact h₅ } } }, { rcases h₄ with ⟨c, h₆, h₇⟩, rw [h₇, ← list.append_assoc, ← h₆] at h₁, left, use t, split, { rw list.is_suffix, use c, exact h₇.symm }, { have h₈ : (x, b) :: (e ++ (x, !b) :: t) = [(x, b)] ++ e ++ [(x, !b)] ++ t, { simp only [bnot, list.singleton_append, list.cons_append, list.append_assoc, prod.mk.inj_iff, eq_self_iff_true, and_self], split, exact trivial, simp only [list.nil_append] }, rw h₈ at h₁, repeat { rw ← mul_mk at h₁ }, rw [h₅, mul_one, mul_mk, list.singleton_append, mk_bnot, one_mul] at h₁, exact h₁ } } } end end free_group -------------------------------------------------------------------------------------------------------- namespace free_group def positive (L : list (α × bool)) := ∃ L₁ : list (α × bool), L₁ ≠ [] ∧ mk L = mk L₁ ∧ (∀ (x : α × bool), x ∈ L₁ → x.2 = tt) def negative (L : list (α × bool)) := ∃ L₁ : list (α × bool), L₁ ≠ [] ∧ mk L = mk L₁ ∧ (∀ (x : α × bool), x ∈ L₁ → x.2 = ff) lemma red.all_pos_iff {L L₁ : list (α × bool)} {H : ∀ x' : α × bool, x' ∈ L → x'.snd = tt} : red L L₁ ↔ L = L₁ := begin split, { intro h, induction h with L₂ L₃ h ih, refl, subst_vars, rw ← red at *, simp at *, induction ih, induction ih_b, simp, specialize H ih_x ff (by simp), simp at *, contradiction, simp, specialize H ih_x ff (by simp), simp at *, contradiction }, intro h, rw h, end lemma red.all_neg_iff {L L₁ : list (α × bool)} {H : ∀ x' : α × bool, x' ∈ L → x'.snd = ff} : red L L₁ ↔ L = L₁ := begin split, { intro h, induction h with L₂ L₃ h ih, refl, subst_vars, rw ← red at *, simp at *, induction ih, induction ih_b, simp, specialize H ih_x tt (by simp), simp at *, contradiction, simp, specialize H ih_x tt (by simp), simp at *, contradiction }, intro h, rw h, end lemma one_not_positive : mk L = 1 → ¬ positive L := begin rintro h ⟨L', hnil, hmk, hpos⟩, rw h at hmk, have := eq.symm hmk, rw mk_one_iff at this, rw red.all_pos_iff at this, contradiction, exact hpos, end lemma one_not_negative : mk L = 1 → ¬ negative L := begin rintro h ⟨L', hnil, hmk, hneg⟩, rw h at hmk, have := eq.symm hmk, rw mk_one_iff at this, rw red.all_neg_iff at this, contradiction, exact hneg, end lemma positive_append {L₁ L₂ : list (α × bool)} : positive L₁ → positive L₂ → positive (L₁ ++ L₂) := begin intros h h₁, rw positive at *, rcases h with ⟨L', hnil, hmk, hpos⟩, rcases h₁ with ⟨L₁', hnil', hmk', hpos'⟩, use (L' ++ L₁'), split, { assume h', simp only [ne.def, prod.forall, list.append_eq_nil] at *, cases h', contradiction }, { split, { rw [← mul_mk, ← mul_mk, hmk, hmk']}, { intros x hx, rw list.mem_append at *, induction hx, specialize hpos x hx, exact hpos, specialize hpos' x hx, exact hpos' } } end lemma negative_cons {x} : negative L → negative ((x, ff) :: L) := begin rintros ⟨L', hnil, hmk, hneg⟩, use (x, ff) :: L', split, simp, split, rw [← list.singleton_append, ← mul_mk, hmk, mul_mk, list.singleton_append], intros x hx, simp at hx, cases hx, rw hx, specialize hneg x hx, exact hneg end lemma negative_singleton_iff {x : α × bool} : negative [x] ↔ x.snd = ff := begin split, intro h, rcases h with ⟨L', hnil, hmk, hneg⟩, induction x with x b, induction b, refl, rw [← mul_left_inj (mk L')⁻¹, mul_inv_self, inv_mk, mul_mk, list.singleton_append, mk_one_iff, red.cons_nil_iff_singleton] at hmk, simp at *, have h₁ := red.sublist hmk, simp at *, specialize hneg x tt h₁, contradiction, intro h, induction x with x b, use ([(x, b)]), simp, intros a b' h₁ h₂, simp at *, rw h₂, exact h, end lemma positive_singleton_iff {x : α × bool} : positive [x] ↔ x.snd = tt := begin split, intro h, rcases h with ⟨L', hnil, hmk, hpos⟩, induction x with x b, induction b, rw [← mul_left_inj (mk L')⁻¹, mul_inv_self, inv_mk, mul_mk, list.singleton_append, mk_one_iff, red.cons_nil_iff_singleton] at hmk, simp at *, have h₁ := red.sublist hmk, simp at *, specialize hpos x ff h₁, contradiction, refl, intro h, induction x with x b, use ([(x, b)]), simp, intros a b' h₁ h₂, simp at *, rw h₂, exact h, end lemma positive_append_exists_suffix {L : list (α × bool)} {x} : positive (L ++ [(x, ff)]) → ∃ e, list.is_suffix ((x, tt)::e) L ∧ mk e = 1 := begin rintros ⟨L', hnil, hmk, hpos⟩, rw ← mul_left_inj ((mk L')⁻¹) at hmk, rw mul_inv_self at hmk, simp at *, have := append_cons_one_exists_suffix_or_prefix_eq_one hmk, cases this, { exact this, }, { rcases this with ⟨e, hl, hr⟩, generalize eq₁ : (list.map (λ (x : α × bool), (x.fst, !x.snd)) L').reverse = LL, rw eq₁ at *, have : ∀ x : α × bool, x ∈ LL → x.snd = ff, { rintros ⟨x, b⟩ hx, rw ← eq₁ at hx, cases b, refl, simp at hx, specialize hpos x ff hx, contradiction, }, simp at *, specialize this x tt _, cases hl with t hl, rw ← hl, simp at *, simp at *, contradiction, } end lemma negative_exists_prefix {L : list (α × bool)} : free_group.negative L → ∃ e (x : α), list.is_prefix (e ++ [(x, ff)]) L ∧ free_group.mk e = 1 := begin rintros ⟨L', hnil, hmk, hneg⟩, rw [← mul_right_inj (free_group.mk L')⁻¹, inv_mul_self, free_group.inv_mk, free_group.mul_mk] at hmk, cases L', contradiction, induction L'_hd with a b, cases b, { simp at hmk, have h₁ := free_group.append_cons_one_exists_suffix_or_prefix_eq_one hmk, cases h₁, { generalize eq₁ : (list.map (λ (x : α × bool), (x.fst, !x.snd)) L'_tl).reverse = LL, have h₂ : ∀ x : α × bool, x ∈ LL → x.snd = tt, { intros x hx, rw ← eq₁ at hx, induction x with x b, cases b, simp at hx, specialize hneg (x, tt) _, simp, exact hx, contradiction, refl, }, rcases h₁ with ⟨e, ⟨t, ht⟩, he⟩, rw eq₁ at ht, simp at ht, specialize h₂ (a, ff) _, rw ← ht, simp, contradiction, }, { rcases h₁ with ⟨e, h₂, h₃⟩, use [e, a], simp at h₂, exact ⟨h₂, h₃⟩, }, }, { specialize hneg (a, tt) (by simp), contradiction, } end lemma all_neg_iff_dyck_neg {L L₁ : list (α × bool)} (H : ∀ x' : α × bool, x' ∈ L → x'.snd = ff) (H' : ∀ x' : α × bool, x' ∈ L₁ → x'.snd = ff) : mk L = mk L₁ ↔ dyck.mk L = dyck.mk L₁ := begin split, { intro h, rw red.exact at h, rcases h with ⟨c, hl, hr⟩, rw red.all_neg_iff at *, subst_vars, exact H', exact H, }, exact dyck.mk_free_group, end lemma all_pos_iff_dyck_all_pos {L L₁ : list (α × bool)} (H : ∀ x' : α × bool, x' ∈ L → x'.snd = tt) (H' : ∀ x' : α × bool, x' ∈ L₁ → x'.snd = tt) : mk L = mk L₁ ↔ dyck.mk L = dyck.mk L₁ := begin split, { intro h, rw red.exact at h, rcases h with ⟨c, hl, hr⟩, rw red.all_pos_iff at *, subst_vars, exact H', exact H, }, exact dyck.mk_free_group, end lemma all_pos_append_eq_all_pos_exists_pos {L L₁ : list (α × bool)} {x} (H : ∀ x' : α × bool, x' ∈ L → x'.snd = tt) (H' : ∀ x' : α × bool, x' ∈ L₁ → x'.snd = tt) : free_group.mk (L ++ [(x, ff)]) = free_group.mk L₁ → ∃ L₂, L = L₂ ++ [(x, tt)] ∧ (∀ x' : α × bool, x' ∈ L₂ → x'.snd = tt) := begin intro h, { rw [← mul_left_inj ((free_group.mk L₁)⁻¹), mul_inv_self] at h, simp at *, have h₁ := append_cons_one_exists_suffix_or_prefix_eq_one h, induction h₁, { rcases h₁ with ⟨e, ⟨t, ht⟩, he⟩, have h₂ : e = [], { cases e, refl, induction e_hd with a b, induction b, { have h₃ : (a, ff) ∈ L, { rw ← ht, simp, }, specialize H a ff h₃, simp at *, exact H, }, { have h₃ := cons_one_exists_prefix_eq_one he, rcases h₃ with ⟨e', ⟨t', ht'⟩, he'⟩, simp at *, rw ← ht' at ht, have h₄ : (a, ff) ∈ L, { rw ← ht, simp, }, specialize H a ff h₄, simp at *, exact H, }, }, use t, split, subst_vars, simp at *, intros a b hab, specialize H a b _, rw ← ht, simp, left, exact hab, exact H }, { rcases h₁ with ⟨e, ⟨t, ht⟩, he⟩, simp at *, generalize eq₁ : ((list.map (λ (x : α × bool), (x.fst, !x.snd)) L₁).reverse = LL), rw eq₁ at *, have h₂ : ∀ x' : α × bool, x' ∈ LL → x'.snd = ff, { intros x hx, rw ← eq₁ at *, simp at *, cases hx with a h₃, induction h₃, { cases h₃ with hl hr, specialize H' a ff hl, simp at *, contradiction, }, { induction x with x b, cases h₃ with hl hr, simp at *, exact hr.2.symm, }, }, specialize h₂ (x, tt) _, {rw ← ht; simp,}, simp at *, contradiction, } }, end lemma all_positive_append_eq_one_iff {L : list (α × bool)} {x} {H : ∀ x' : α × bool, x' ∈ L → x'.snd = tt} : mk (L ++ [(x, ff)]) = 1 ↔ L = [(x, tt)] := begin split, { intro h, have h₁ := append_singleton_one_exists_suffix_eq_one h, rcases h₁ with ⟨e, h₂, h₃⟩, have : e = [], { cases e, refl, induction e_hd with a b, induction b, have h₄ : (a, ff) ∈ L, { rw list.is_suffix at *, cases h₂ with t h₂, simp at *, rw ← h₂, simp, }, specialize H (a, ff) h₄, simp at *, exact H, rw mk_one_iff at *, rw red.cons_nil_iff_singleton at *, simp at *, have := red.sublist h₃, simp at *, have h₄ : (a, ff) ∈ L, { rw list.is_suffix at *, cases h₂ with t h₂, rw ← h₂, simp, right, exact this, }, specialize H a ff h₄, simp at *, exact H, }, subst_vars, simp at *, rw list.is_suffix at *, cases h₂ with t ht, have : t = [], { cases t, refl, induction t_hd with a b, induction b, have h₄ : (a, ff) ∈ L, { rw ← ht, simp, }, specialize H a ff h₄, simp at *, exact H, subst_vars, have : (a, tt) :: t_tl ++ [(x, tt)] ++ [(x, ff)] = (a, tt) :: t_tl ++ [(x, tt), (x, !tt)] := by simp, rw this at *, clear this, rw ← mul_mk at h, rw mk_bnot at h, rw mul_one at h, rw mk_one_iff at h, rw red.cons_nil_iff_singleton at h, have := red.sublist h, simp at *, specialize H a ff _, right, left, exact this, simp at *, exact H, }, rw this at *, simp at *, exact ht.symm, }, { intro h, rw h, simp, rw ← bool.bnot_true, exact mk_bnot, } end end free_group -------------------------------------------------------------------------------------------------------- namespace dyck def positive (L : list (α × bool)) := ∃ L₁ : list (α × bool), L₁ ≠ [] ∧ mk L = mk L₁ ∧ (∀ (x : α × bool), x ∈ L₁ → x.2 = tt) def negative (L : list (α × bool)) := ∃ L₁ : list (α × bool), L₁ ≠ [] ∧ mk L = mk L₁ ∧ (∀ (x : α × bool), x ∈ L₁ → x.2 = ff) lemma red.all_pos_iff {L L₁ : list (α × bool)} {H : ∀ x' : α × bool, x' ∈ L → x'.snd = tt} : red L L₁ ↔ L = L₁ := begin split, { intro h, induction h with L₂ L₃ h ih, refl, subst_vars, rw ← red at *, simp at *, induction ih, specialize H ih_x ff (by simp), simp at *, contradiction }, intro h, rw h, end lemma red.all_neg_iff {L L₁ : list (α × bool)} {H : ∀ x' : α × bool, x' ∈ L → x'.snd = ff} : red L L₁ ↔ L = L₁ := begin split, { intro h, induction h with L₂ L₃ h ih, refl, subst_vars, rw ← red at *, simp at *, induction ih, specialize H ih_x tt (by simp), simp at *, contradiction }, intro h, rw h, end lemma one_not_positive : mk L = 1 → ¬ positive L := begin rintros h ⟨L', hnil, hmk, hpos⟩, rw h at hmk, have h₁ := eq.symm hmk, rw mk_one_iff at h₁, cases L', contradiction, cases L'_hd with a b, cases b, { specialize hpos (a, ff) (by simp), contradiction, }, { rw red.cons_nil_iff_singleton at h₁, have h₂ := red.sublist h₁, simp at h₂, specialize hpos (a, ff) (by simp; exact h₂), contradiction } end lemma one_not_negative : mk L = 1 → ¬ negative L := begin rintros h ⟨L', hnil, hmk, hneg⟩, rw h at hmk, have h₁ := mk_free_group (eq.symm hmk), rw [← free_group.one_eq_mk, free_group.mk_one_iff] at h₁, cases L', contradiction, cases L'_hd with a b, cases b, { rw free_group.red.cons_nil_iff_singleton at h₁, have h₂ := free_group.red.sublist h₁, simp at h₂, specialize hneg (a, tt) (by simp; exact h₂), contradiction }, { specialize hneg (a, tt) (by simp), contradiction } end lemma positive_not_negative : positive L → ¬ negative L := begin rintros ⟨L', hnil, hmk, hpos⟩ ⟨LL', hnil', hmk', hneg⟩, rw [hmk, red.exact] at hmk', rcases hmk' with ⟨c, hl, hr⟩, rw red.all_pos_iff at hl, rw red.all_neg_iff at hr, rw ← hl at hr, cases L', contradiction, cases L'_hd with a b, cases b, { specialize hpos (a, ff) (by simp), contradiction }, { specialize hneg (a, tt) _, rw hr; simp, contradiction }, exacts [hneg, hpos], end lemma negative_not_positive : negative L → ¬ positive L := begin rintros ⟨L', hnil, hmk, hneg⟩ ⟨LL', hnil', hmk', hpos⟩, rw [hmk, red.exact] at hmk', rcases hmk' with ⟨c, hl, hr⟩, rw red.all_pos_iff at hr, rw red.all_neg_iff at hl, rw ← hl at hr, cases L', contradiction, cases L'_hd with a b, cases b, { specialize hpos (a, ff) _, rw hr; simp, contradiction }, { specialize hneg (a, tt) (by simp), contradiction}, exacts [hneg, hpos], end lemma positive_append : positive L → positive L₁ → positive (L ++ L₁) | ⟨L', hnil, hmk, hpos⟩ ⟨LL', hnil', hmk', hpos'⟩ := begin use (L' ++ LL'), split, simp, intro h, contradiction, split, repeat {rw ← mul_mk}, rw [hmk, hmk'], intros x hx, simp at hx, cases hx, specialize hpos x hx, exact hpos, specialize hpos' x hx, exact hpos', end lemma positive_singleton_iff {x : α × bool} : positive [x] ↔ x.snd = tt := begin split, rintro ⟨L', hnil, hmk, hpos⟩, have hmk' := mk_free_group hmk, induction x with x b, induction b, rw [← mul_left_inj (free_group.mk L')⁻¹, mul_inv_self, free_group.inv_mk, free_group.mul_mk, list.singleton_append, free_group.mk_one_iff, free_group.red.cons_nil_iff_singleton] at hmk', simp at *, have h₁ := free_group.red.sublist hmk', simp at *, specialize hpos x ff h₁, contradiction, refl, intro h, induction x with x b, use ([(x, b)]), simp, intros a b' h₁ h₂, simp at *, rw h₂, exact h, end lemma negative_singleton_iff {x : α × bool} : negative [x] ↔ x.snd = ff := begin split, rintro ⟨L', hnil, hmk, hneg⟩, have hmk' := mk_free_group hmk, induction x with x b, induction b, refl, rw [← mul_left_inj (free_group.mk L')⁻¹, mul_inv_self, free_group.inv_mk, free_group.mul_mk, list.singleton_append, free_group.mk_one_iff, free_group.red.cons_nil_iff_singleton] at hmk', simp at *, have h₁ := free_group.red.sublist hmk', simp at *, specialize hneg x tt h₁, contradiction, intro h, induction x with x b, use ([(x, b)]), simp, intros a b' h₁ h₂, simp at *, rw h₂, exact h, end lemma negative_append : negative L → negative L₁ → negative (L ++ L₁) | ⟨L', hnil, hmk, hneg⟩ ⟨LL', hnil', hmk', hneg'⟩ := begin use (L' ++ LL'), split, simp, intro h, contradiction, split, repeat {rw ← mul_mk}, rw [hmk, hmk'], intros x hx, simp at hx, cases hx, specialize hneg x hx, exact hneg, specialize hneg' x hx, exact hneg', end lemma negative_cons {x} : negative L → negative ((x, ff) :: L) | ⟨L', hnil, hmk, hneg⟩ := begin use ((x, ff) :: L'), split, simp, split, rw [← list.singleton_append, ← mul_mk, hmk, mul_mk, list.singleton_append], intros x hx, simp at hx, cases hx, rw hx, specialize hneg x hx, exact hneg, end end dyck -------------------------------------------------------------------------------------------------------- namespace free_group lemma one_prefix_pos_or_one_suffix_neg_or_one {L : list (α × bool)} (H : free_group.mk L = 1) : (∀ p, list.is_prefix p L → positive p ∨ mk p = 1) → (∀ s, list.is_suffix s L → negative s ∨ mk s = 1) := begin rw mk_one_iff at H, apply H.head_induction_on, { intros h s hs, simp at *, subst_vars, cases h, { rcases h with ⟨L', hnil, hmk, hpos⟩, rw ← one_eq_mk at hmk, have := one_not_positive (eq.symm hmk), have : positive L' := ⟨L', hnil, rfl, hpos⟩, contradiction, }, { right, exact h, }, }, intros a c h h₁ h₂ h₃, induction h with L₁ L₂ x b, specialize h₂ _, { intros p hp, cases hp with t hp, rw list.append_eq_append_iff at hp, cases hp, { rcases hp with ⟨a', hl, hr⟩, specialize h₃ p _, use (a' ++ (x, b) :: (x, !b) :: L₂), subst_vars, simp, exact h₃, }, { rcases hp with ⟨c', hl, hr⟩, specialize h₃ (L₁ ++ (x, b) :: (x, !b) :: c') _, use t, subst_vars, simp, cases h₃, { left, rcases h₃ with ⟨L', hnil, hmk, hpos⟩, have : mk (L₁ ++ (x, b) :: (x, !b) :: c') = mk (L₁ ++ c'), { have : L₁ ++ (x, b) :: (x, !b) :: c' = L₁ ++ [(x, b), (x, !b)] ++ c' := by simp, rw [this, ← mul_mk, ← mul_mk, mk_bnot, mul_one, mul_mk], }, rw this at hmk, subst p, exact ⟨L', hnil, hmk, hpos⟩, }, { have : mk (L₁ ++ (x, b) :: (x, !b) :: c') = mk (L₁ ++ c'), { have : L₁ ++ (x, b) :: (x, !b) :: c' = L₁ ++ [(x, b), (x, !b)] ++ c' := by simp, rw [this, ← mul_mk, ← mul_mk, mk_bnot, mul_one, mul_mk], }, rw this at h₃, subst p, right, exact h₃, } } }, intros s hs, cases hs with t hs, rw list.append_eq_append_iff at hs, cases hs, { rcases hs with ⟨a', hl, hr⟩, specialize h₂ (a' ++ L₂) _, use t, subst_vars, simp, cases h₂, { left, have : mk (a' ++ (x, b) :: (x, !b) :: L₂) = mk (a' ++ L₂), { have : a' ++ (x, b) :: (x, !b) :: L₂ = a' ++ [(x, b), (x, !b)] ++ L₂ := by simp, rw [this, ← mul_mk, ← mul_mk, mk_bnot, mul_one, mul_mk], }, subst s, rcases h₂ with ⟨L', hnil, hmk, hneg⟩, rw ← this at hmk, exact ⟨L', hnil, hmk, hneg⟩, }, { right, have : mk (a' ++ (x, b) :: (x, !b) :: L₂) = mk (a' ++ L₂), { have : a' ++ (x, b) :: (x, !b) :: L₂ = a' ++ [(x, b), (x, !b)] ++ L₂ := by simp, rw [this, ← mul_mk, ← mul_mk, mk_bnot, mul_one, mul_mk], }, subst s, rw this, exact h₂, }, }, { rcases hs with ⟨c', hl, hr⟩, rw list.cons_eq_append_iff at hr, cases hr, { cases hr with hrl hrr, specialize h₂ L₂ _, use L₁, cases h₂, { left, rcases h₂ with ⟨L', hnil, hmk, hneg⟩, use L', split, exact hnil, split, subst s, have : (x, b) :: (x, !b) :: L₂ = [(x, b), (x, !b)] ++ L₂ := by simp, rw [this, ← mul_mk, mk_bnot, one_mul], exacts [hmk, hneg], }, { right, subst s, have : (x, b) :: (x, !b) :: L₂ = [(x, b), (x, !b)] ++ L₂ := by simp, rw [this, ← mul_mk, mk_bnot, one_mul], exact h₂, } }, { rcases hr with ⟨a', hl, hr⟩, rw list.cons_eq_append_iff at hr, cases hr, { cases hr with hrl hrr, specialize h₂ L₂ _, use L₁, cases h₂, { specialize h₃ (L₁ ++ [(x, b)]) _, use (x, !b) :: L₂, simp, induction b, { cases h₃, { have h₄ := positive_append_exists_suffix h₃, rcases h₄ with ⟨e, hl, hr⟩, rw ← red at *, rw ← mk_one_iff at h₁, have h₅ : mk (L₁ ++ [(x, ff), (x, tt)] ++ L₂) = 1, { rw [← mul_mk, ← mul_mk, ← bool.bnot_false, mk_bnot, mul_one, mul_mk], exact h₁, }, cases hl with t ht, rw ← ht at h₅, have h₆ : mk (t ++ (x, tt) :: e ++ [(x, ff), (x, tt)] ++ L₂) = mk (t ++ (x, tt) :: L₂), { have : t ++ (x, tt) :: e ++ [(x, ff), (x, tt)] ++ L₂ = t ++ [(x, tt)] ++ e ++ [(x, ff), (x, tt)] ++ L₂ := by simp, rw this, repeat {rw ← mul_mk}, rw [← bool.bnot_false, mk_bnot, mul_one, hr, mul_one], simp, }, rw h₆ at h₅, clear h₆, rcases h₃ with ⟨L', hnil, hmk, hpos⟩, rw ← ht at hmk, have h₇ : mk (t ++ (x, tt) :: e ++ [(x, ff)]) = mk t, { rw ← list.singleton_append, repeat {rw ← mul_mk}, rw [hr, mul_one, mul_mk, mul_mk], simp, rw [← mul_mk, ← bool.bnot_true, mk_bnot, mul_one], }, rw h₇ at hmk, clear h₇, rw ← mul_mk at h₅, rw hmk at h₅, rw mul_mk at h₅, have h₆ := append_cons_one_exists_suffix_or_prefix_eq_one h₅, cases h₆, { simp at *, rcases h₆ with ⟨e', ⟨t', ht⟩, he'⟩, specialize hpos x ff _, rw ← ht, simp, simp at *, contradiction, }, { rcases h₆ with ⟨e', ⟨t', ht⟩, he'⟩, left, subst_vars, simp, rename h₅ h₃, have h₄ : mk (t ++ (x, tt) :: e ++ (e' ++ [(x, !tt)] ++ t')) = mk (t ++ t'), { have : t ++ (x, tt) :: e ++ (e' ++ [(x, !tt)] ++ t') = t ++ [(x, tt)] ++ e ++ e' ++ [(x, !tt)] ++ t' := by simp, rw this, clear this, repeat {rw ← mul_mk}, rw [hr, he', mul_one, mul_one], have : mk ([(x, tt)]) * mk [(x, !tt)] = 1, { rw [mul_mk, list.singleton_append, mk_bnot], }, assoc_rw this, rw mul_one, }, rw h₄ at h₁, have h₅ : negative t', { generalize eq₂ : ((list.map (λ (x : α × bool), (x.fst, !x.snd)) L').reverse) = t_inv, use t_inv, split, { rw ← eq₂, simp at *, exact hnil, }, { split, rw [← mul_mk, hmk, ← mul_right_inj (mk L')⁻¹, ← mul_assoc, inv_mul_self, one_mul, mul_one] at h₁, simp at h₁, rw ← eq₂, exact h₁, rintros ⟨x, b⟩ hx, rw ← eq₂ at hx, cases b, refl, simp at hx, specialize hpos (x, ff) hx, contradiction, }, }, rcases h₅ with ⟨L₁, hnil, hmk, hneg⟩, use L₁, split, exact hnil, split, { have h₅ : (x, tt) :: (e' ++ (x, ff) :: t') = [(x, tt)] ++ e' ++ [(x, !tt)] ++ t' := by simp, rw h₅, repeat {rw ← mul_mk}, rw [he', mul_one, mul_mk], have : mk ([(x, tt)] ++ [(x, !tt)]) = 1, { simp, rw [ ← bool.bnot_true, mk_bnot], }, rw [this, one_mul, hmk], }, exact hneg, } }, { right, rw [← red, ← mk_one_iff] at h₁, have h₄ : mk (L₁ ++ (x, ff) :: (x, !ff) :: L₂) = 1, { have : L₁ ++ (x, ff) :: (x, !ff) :: L₂ = L₁ ++ [(x, ff), (x, !ff)] ++ L₂ := by simp, rw [this, ← mul_mk, ← mul_mk, mk_bnot, mul_one, mul_mk, h₁], }, have h₅ : mk (L₁ ++ (x, ff) :: (x, !ff) :: L₂) = mk ((x, !ff) :: L₂), { have : L₁ ++ (x, ff) :: (x, !ff) :: L₂ = L₁ ++ [(x, ff)] ++ (x, !ff) :: L₂ := by simp, rw [this, ← mul_mk, h₃, one_mul], }, rw h₅ at h₄, rw hrr, exact h₄, } }, { simp at *, left, rw hrr, exact negative_cons h₂, } }, { induction b, have h₄ : mk L₁ = 1, { rw [← red, ← mk_one_iff, ← mul_mk, h₂, mul_one] at h₁, exact h₁, }, { specialize h₃ (L₁ ++ [(x, ff)]) _, use (x, !ff) :: L₂, simp, cases h₃, { rcases h₃ with ⟨L', hnil, hmk, hpos⟩, rw [← mul_mk, h₄, one_mul] at hmk, have h₅ : positive [(x, ff)] := ⟨L', hnil, hmk, hpos⟩, rw positive_singleton_iff at h₅, contradiction, }, { rw [← mul_mk, h₄, one_mul, mk_one_iff, red.singleton_iff] at h₃, simp at h₃, contradiction, } }, { left, use ([(x, ff)]), split, simp, split, rw [hrr, ← list.singleton_append, ← mul_mk, h₂, mul_one, bool.bnot_true], intros x hx, simp at hx, rw hx, } }, }, { rcases hr with ⟨b', hl, hr⟩, specialize h₂ s _, use (L₁ ++ b'), rw hr, rw ← list.append_assoc, exact h₂, } } } end end free_group namespace dyck lemma free_group_suffix_neg_or_one_dyck_suffix_neg_or_one {L : list (α × bool)} : (∀ s, list.is_suffix s L → free_group.negative s ∨ free_group.mk s = 1) → (∀ s, list.is_suffix s L → negative s ∨ mk s = 1) := begin intro h, induction L with hd tl ih, { intros s hs, simp at *, subst_vars, right, rw one_eq_mk, }, { specialize ih _, { intros s hs, specialize h s _, cases hs with t ht, use (hd::t), rw ← ht, simp, exact h, }, rintros s ⟨t, ht⟩, have h₁ := eq.symm ht, rw list.cons_eq_append_iff at h₁, cases h₁, { cases h₁ with h₂ h₃, subst_vars, simp at *, specialize ih tl list.suffix_rfl, specialize h (hd :: tl) list.suffix_rfl, cases h, { cases ih, { left, induction hd with a b, cases b, exact negative_cons ih, rcases h with ⟨L', hnil, hmk, hneg⟩, rcases ih with ⟨LL', hnil', hmk', hneg'⟩, have h₁ := mk_free_group hmk', rw [← list.singleton_append, ← free_group.mul_mk, h₁, free_group.mul_mk, list.singleton_append, ← mul_right_inj (free_group.mk L')⁻¹, inv_mul_self, free_group.inv_mk, free_group.mul_mk] at hmk, have h₂ := free_group.append_cons_one_exists_suffix_or_prefix_eq_one hmk, cases h₂, generalize eq₁ : (list.map (λ (x : α × bool), (x.fst, !x.snd)) L').reverse = L_inv, rw eq₁ at *, { rcases h₂ with ⟨e, ⟨t, h₃⟩, h₄⟩, have h₅ : (a, !tt) ∈ L_inv := by rw ← h₃; simp, have h₆ : ∀ x : α × bool, x ∈ L_inv → x.snd = tt, { rintros ⟨x, b⟩ hx, rw ← eq₁ at hx, cases b, simp at hx, specialize hneg (x, tt) hx, contradiction, refl, }, specialize h₆ (a, ff) _, simp at h₅, exact h₅, contradiction, }, { rcases h₂ with ⟨e, ⟨t, h₃⟩, h₄⟩, have h₇ : e = [], { cases e, refl, induction e_hd with x b, rw [free_group.mk_one_iff, free_group.red.cons_nil_iff_singleton] at h₄, have h₅ := free_group.red.sublist h₄, simp at h₅, cases b, { specialize hneg' (x, !ff) _, rw ← h₃, simp, left, simp at h₅, exact h₅, simp at *, contradiction, }, { specialize hneg' (x, tt) _, rw ← h₃, simp, contradiction, }, }, subst e, simp at *, generalize eq₁ : (list.map (λ (x : α × bool), (x.fst, !x.snd)) L').reverse = L_inv, rw [eq₁, ← mul_right_inj (free_group.mk L_inv)⁻¹, ← free_group.mul_mk, ← mul_assoc, inv_mul_self, one_mul, mul_one, ← eq₁, ← free_group.inv_mk, inv_inv, ← list.singleton_append] at hmk, rw [← h₃, ← list.singleton_append, ← free_group.mul_mk, ← mul_right_inj (free_group.mk ([(a, ff)]))⁻¹, ← mul_assoc, inv_mul_self, one_mul] at h₁, simp at h₁, rw ← h₃ at hmk, have h₆ : free_group.mk ([(a, tt)] ++ (a, ff) :: t) = free_group.mk t, { have : [(a, tt)] ++ (a, ff) :: t = [(a, tt), (a, !tt)] ++ t := by simp, rw [this, ← free_group.mul_mk, free_group.mk_bnot, one_mul], }, rw h₆ at hmk, rw free_group.all_neg_iff_dyck_neg at hmk, use L', split, simp, exact hnil, split, rw [← list.singleton_append, ← mul_mk, hmk', ← h₃], have : mk [(a, tt)] * mk ((a, ff) :: t) = mk t, { rw mul_mk, have : [(a, tt)] ++ (a, ff) :: t = [(a, tt), (a, ff)] ++ t := by simp, rw [this, ← mul_mk, mk_mul_inv, one_mul], }, rw this, exact hmk, simp, exact hneg, intros x hx, have : x ∈ LL', { rw ← h₃, simp, right, exact hx, }, induction x with x b, specialize hneg' x b this, subst_vars, simp, exact hneg, } }, { left, have h₁ := mk_free_group ih, rw ← free_group.one_eq_mk at h₁, rcases h with ⟨L', hnil, hmk, hneg⟩, rw [← list.singleton_append, ← free_group.mul_mk, h₁, mul_one] at hmk, have h₂ : free_group.negative [hd] := ⟨L', hnil, hmk, hneg⟩, rw free_group.negative_singleton_iff at h₂, use ([hd]), split, simp, split, rw [← list.singleton_append, ← mul_mk, ih, mul_one], intros x hx, simp at hx, rw hx, exact h₂, } }, { induction hd with x b, cases ih, { rcases ih with ⟨L', hnil, hmk, hneg⟩, right, cases b, { have h₁ := mk_free_group hmk, rw [← list.singleton_append, ← free_group.mul_mk, h₁, free_group.mul_mk, list.singleton_append, free_group.mk_one_iff, free_group.red.all_neg_iff] at h, simp at h, contradiction, intros x hx, simp at hx, cases hx, rw hx, exact (hneg x hx), }, { have h₁ := mk_free_group hmk, rw [← list.singleton_append, ← free_group.mul_mk, h₁, free_group.mul_mk, list.singleton_append, free_group.mk_one_iff, free_group.red.cons_nil_iff_singleton, free_group.red.all_neg_iff] at h, rw [← list.singleton_append, ← mul_mk, hmk, h, bool.bnot_true, mul_mk, list.singleton_append, mk_mul_inv], exact hneg, } }, { have h₁ := mk_free_group ih, rw ← free_group.one_eq_mk at h₁, rw [← list.singleton_append, ← free_group.mul_mk, h₁, mul_one, free_group.mk_one_iff, free_group.red.singleton_iff] at h, simp at h, contradiction, } } }, { rcases h₁ with ⟨a', hl, hr⟩, specialize ih s _, use a', rw hr, exact ih, } } end lemma free_group_prefix_pos_or_one_dyck_prefix_pos_or_one {L : list (α × bool)} : (∀ p, list.is_prefix p L → free_group.positive p ∨ free_group.mk p = 1) ↔ (∀ p, list.is_prefix p L → dyck.positive p ∨ dyck.mk p = 1) := begin split, intro h, induction L using list.reverse_rec_on with l a ih, { intros p hp, simp at *, right, rw hp, rw dyck.one_eq_mk, }, specialize ih _, { intros p hp, specialize h p _, { rw list.is_prefix at *, cases hp with t hp, use (t ++ [a]), rw ← list.append_assoc, rw ← hp, }, exact h, }, intros p hp, cases hp with t hp, rw append_eq_append_iff at hp, induction hp, { rcases hp with ⟨a', hl, hr⟩, specialize ih p (by use a'; exact hl.symm), exact ih, }, { rcases hp with ⟨c', hl, hr⟩, have heq : c' ++ t = [a], { exact hr.symm, }, have : (c' = [] ∧ t = [a]) ∨ (c' = [a] ∧ t = []), { rw list.append_singleton_iff at heq, induction heq, left, exact heq, right, exact ⟨heq.2, heq.1⟩, }, induction this, { cases this with hl₁ hl₂, subst_vars, simp at *, specialize ih l prefix_rfl, exact ih, }, { cases this with hl₁ hl₂, subst_vars, simp at *, clear hr, induction a with a b, induction b, { specialize ih l prefix_rfl, specialize h (l ++ [(a,ff)]) prefix_rfl, induction ih, { induction h, { left, rcases ih with ⟨L, hnil, hmk, hpos⟩, rcases h with ⟨L', hnil', hmk', hpos'⟩, use L', split, exact hnil', split, rw ← mul_mk, rw hmk, rw ← free_group.mul_mk at hmk', have h₁ := dyck.mk_free_group hmk, rw h₁ at hmk', rw free_group.mul_mk at hmk', have := free_group.all_pos_append_eq_all_pos_exists_pos hpos hpos' hmk', rcases this with ⟨L₂, hl, hr⟩, rw hl at *, have h₂ : free_group.mk (L₂ ++ [(a, tt)] ++ [(a, ff)]) = free_group.mk L₂, { rw list.append_assoc, rw singleton_append, rw ← bool.bnot_true, rw ← free_group.mul_mk, rw free_group.mk_bnot, rw mul_one, }, rw h₂ at hmk', rw free_group.all_pos_iff_dyck_all_pos at hmk', rw mul_mk, rw list.append_assoc, rw list.singleton_append, rw ← mul_mk, rw mk_mul_inv, rw mul_one, exact hmk', intros x hx, specialize hpos x _, simp, left, exact hx, exact hpos, exact hpos', exact hpos', }, { right, rcases ih with ⟨L, hnil, hmk, hpos⟩, rw ← mul_mk, rw hmk, rw ← free_group.mul_mk at h, have := mk_free_group hmk, rw this at h, rw free_group.mul_mk at h, rw free_group.all_positive_append_eq_one_iff at h, rw h, rw mul_mk, simp, exact mk_mul_inv, exact hpos, }, }, { induction h, { rcases h with ⟨L, hnil, hmk, hpos⟩, rw ← free_group.mul_mk at hmk, have := mk_free_group ih, rw ← free_group.one_eq_mk at this, rw [this, one_mul, free_group.red.exact] at hmk, clear this, rcases hmk with ⟨c, hl, hr⟩, rw free_group.red.singleton_iff at hl, rw hl at hr, have := free_group.red.sublist hr, simp at *, specialize hpos a ff this, simp at *, contradiction, }, { rw ← free_group.mul_mk at h, have := mk_free_group ih, rw ← free_group.one_eq_mk at this, rw [this, one_mul] at h, rw [free_group.mk_one_iff, free_group.red.singleton_iff] at h, simp at *, contradiction, }, } }, { left, specialize ih l prefix_rfl, induction ih, { rcases ih with ⟨L, hnil, hmk, hpos⟩, use (L ++ [(a, tt)]), split, simp, split, rw ← mul_mk, rw hmk, rw mul_mk, intros x hx, simp at *, induction hx, { induction x with x b, specialize hpos x b hx, simp, exact hpos, }, { induction x with x b, simp at *, exact hx.2, } }, { use ([(a, tt)]), split, simp, split, rw ← mul_mk, rw ih, rw one_mul, intros x hx, simp at *, induction x with x b, simp at *, exact hx.2, } } } }, { intros h p hp, specialize h p hp, cases h, { left, rcases h with ⟨L', hnil, hmk, hpos⟩, use L', split, { exact hnil, }, { split, have := mk_free_group hmk, exact this, exact hpos, } }, { right, exact mk_free_group h, } } end lemma dyck_one_prefix_pos_or_one {L : list (α × bool)} : dyck.mk L = 1 → (∀ p, list.is_prefix p L → positive p ∨ mk p = 1) := begin intro h, rw [dyck.one_eq_mk, dyck.red.exact] at *, induction h with c h, cases h with hl hr, rw dyck.red.nil_iff at hr, rw hr at hl, clear hr, rename hl h, apply relation.refl_trans_gen.head_induction_on h, intros p hp, simp only [prefix_nil_iff] at *, right, { rw [hp, one_eq_mk] }, { intros a c h₁ h₂ h₃, rw ← dyck.red at *, clear h, induction h₁ with L L₁ x, intros p hp, rw list.is_prefix at *, rcases hp with ⟨s, hp⟩, rw list.append_eq_append_iff at *, induction hp, { rcases hp with ⟨a', hpl, hpr⟩, have h₄ : p <+: L ++ L₁, { rw list.is_prefix, use (a' ++ L₁), rw [← list.append_assoc, hpl] }, specialize h₃ p h₄, exact h₃ }, { rcases hp with ⟨c', hpl, hpr⟩, rw list.cons_eq_append_iff at *, induction hpr, cases hpr with hprl hprr, rw hprl at *, simp only [append_nil] at *, have h₄ : p <+: L ++ L₁, { rw list.is_prefix, use (L₁), exact congr_fun (congr_arg append hpl) L₁ }, specialize h₃ p h₄, exact h₃, { rcases hpr with ⟨a', hprl, hprr⟩, rw list.cons_eq_append_iff at *, induction hprr, cases hprr with hprrl hprrr, rw hprrl at *, specialize h₃ L (by simp), induction h₃, have h₄ : positive p, { rw hpl, refine dyck.positive_append h₃ _, rw hprl, exact positive_singleton_iff.mpr rfl }, left, exact h₄, left, { use (c'), split, rw hprl, simp only [ne.def, not_false_iff], split, { rw [hpl, ← mul_mk, h₃, one_mul] }, { intros x hx, subst_vars, simp only [mem_singleton] at *, rw hx } }, rcases hprr with ⟨b, hprrl, hprrr⟩, rw hprrl at hprl, rw hprl at hpl, clear hprl hprrl, have h₄ : L ++ b <+: L ++ L₁, by { use s, rw [append_assoc, hprrr] }, specialize h₃ (L ++ b) h₄, induction h₃, left, { rw positive at *, rcases h₃ with ⟨LL, hn, h₃l, h₃r⟩, use LL, split, { exact hn }, { rw [← h₃l, hpl, ← mul_mk], split, have h₅ : (x, tt) :: (x, ff) :: b = [(x, tt), (x, ff)] ++ b , { simp only [cons_append, singleton_append, eq_self_iff_true, and_self] }, rw [h₅, ← mul_mk, ← mul_mk, mk_mul_inv, one_mul, mul_mk], exact h₃r } }, right, { rw hpl, have h₅ : (x, tt) :: (x, ff) :: b = [(x, tt), (x, ff)] ++ b , { simp only [cons_append, singleton_append, eq_self_iff_true, and_self] }, rw [h₅, ← mul_mk, ← mul_mk, mk_mul_inv, one_mul, mul_mk], exact h₃ } } } } end lemma dyck_one_suffix_neg_or_one {L : list (α × bool)} : dyck.mk L = 1 → (∀ p, list.is_suffix p L → negative p ∨ mk p = 1) := begin intro h, rw mk_one_iff at h, apply h.head_induction_on, { intros p hp, simp at *, subst_vars, right, rw one_eq_mk, }, { intros a c h₁ h₂ h₃, induction h₁ with L₁ L₂ x, intros p hp, cases hp with t ht, rw append_eq_append_iff at ht, induction ht, { rcases ht with ⟨a', hl, hr⟩, specialize h₃ (a' ++ L₂) _, use t, rw ← list.append_assoc, subst_vars, cases h₃, { left, subst_vars, rcases h₃ with ⟨L', hnil, hmk, hneg⟩, use L', split, {exact hnil}, { split, have : a' ++ (x, tt) :: (x, ff) :: L₂ = a' ++ [(x, tt), (x, ff)] ++ L₂ := by simp, rw [this, ← mul_mk, ← mul_mk, mk_mul_inv, mul_one, mul_mk], exact hmk, exact hneg, }, }, { right, subst_vars, have : a' ++ (x, tt) :: (x, ff) :: L₂ = a' ++ [(x, tt), (x, ff)] ++ L₂ := by simp, rw [this, ← mul_mk, ← mul_mk, mk_mul_inv, mul_one, mul_mk], exact h₃, } }, { rcases ht with ⟨c', hl, hr⟩, rw cons_eq_append_iff at hr, cases hr, { cases hr with hrl hrr, subst_vars, specialize h₃ L₂ (by simp), cases h₃, { left, rcases h₃ with ⟨L', hnil, hmk, hneg⟩, use L', split, exact hnil, split, have : (x, tt) :: (x, ff) :: L₂ = [(x, tt), (x, ff)] ++ L₂ := by simp, rw [this, ← mul_mk, mk_mul_inv, one_mul], exact hmk, exact hneg, }, { right, have : (x, tt) :: (x, ff) :: L₂ = [(x, tt), (x, ff)] ++ L₂ := by simp, rw [this, ← mul_mk, mk_mul_inv, one_mul], exact h₃, } }, { rcases hr with ⟨a', hl, hr⟩, rw cons_eq_append_iff at hr, cases hr, { cases hr with hrl hrr, subst_vars, specialize h₃ L₂ (by simp), cases h₃, { rcases h₃ with ⟨L', hnil, hmk, hneg⟩, left, use ((x, ff) :: L'), split, simp, split, rw [← list.singleton_append, ← mul_mk, hmk, mul_mk], simp, intros x1 hx1, simp at *, cases hx1, induction x1 with x b, simp at *, exact hx1.2, induction x1 with x b, specialize hneg x b hx1, simp, exact hneg, }, { left, use ([(x,ff)]), split, simp, split, rw [← list.singleton_append, ← mul_mk, h₃, mul_one], intros x hx, simp at *, induction x with _ _, simp at *, exact hx.2, } }, { rcases hr with ⟨b', hrl, hrr⟩, subst_vars, specialize h₃ p _, use (L₁ ++ b'), simp, exact h₃, } } } } end lemma dyck_one_iff : dyck.mk L = 1 ↔ (∀ s, list.is_suffix s L → negative s ∨ mk s = 1) ∧ (∀ p, list.is_prefix p L → positive p ∨ mk p = 1) := begin split, intro h, split, exact dyck_one_suffix_neg_or_one h, exact dyck_one_prefix_pos_or_one h, rintros ⟨h, h₁⟩, specialize h L suffix_rfl, specialize h₁ L prefix_rfl, cases h, cases h₁, { have := positive_not_negative h₁, contradiction, }, exact h₁, exact h, end def append_mul_inv_cons_eq {L L₁ : list (α × bool)} {x} : mk (L ++ (x, tt) :: (x, ff) :: L₁) = mk (L ++ L₁) := begin have : L ++ (x, tt) :: (x, ff) :: L₁ = L ++ [(x, tt), (x, ff)] ++ L₁ := by simp, rw [this, ← mul_mk, ← mul_mk, mk_mul_inv, mul_one, mul_mk], end lemma mul_inv_all_neg_eq_one {L : list (α × bool)} (H : ∀ x : α × bool, x ∈ L → x.snd = ff) : dyck.mk (((list.map (prod.map id bnot)) L).reverse ++ L) = 1 := begin induction L, simp, rw dyck.one_eq_mk, { specialize L_ih _, { intros x hx, specialize H x _, { simp, right, exact hx}, exact H }, simp, induction L_hd with a b, simp, cases b, { simp, rw dyck.append_mul_inv_cons_eq, exact L_ih }, { specialize H (a, tt) (by simp), contradiction } } end lemma cons_eq_one_exists_prefix_eq_one {L : list (α × bool)} {x : α} : dyck.mk ((x, tt) :: L) = 1 → ∃ e, list.is_prefix (e ++ [(x, ff)]) L ∧ mk e = 1 := by sorry lemma append_cons_eq_one_exists_prefix_eq_one {L L₁ : list (α × bool)} {x : α}: dyck.mk (L ++ (x, tt) :: L₁) = 1 → ∃ e, list.is_prefix (e ++ [(x, ff)]) L₁ ∧ mk e = 1 := begin intro h, have h₁ := dyck_one_prefix_pos_or_one h, specialize h₁ L (by simp), cases h₁, rcases h₁ with ⟨L', hnil, hmk, hpos⟩, rw [← mul_mk, hmk, mul_mk] at h, sorry, sorry, end end dyck namespace free_group def append_bnot_cons_eq {L L₁ : list (α × bool)} {x b} : mk (L ++ (x, b) :: (x, !b) :: L₁) = mk (L ++ L₁) := begin have : L ++ (x, b) :: (x, !b) :: L₁ = L ++ [(x, b), (x, !b)] ++ L₁ := by simp, rw [this, ← mul_mk, ← mul_mk, mk_bnot, mul_one, mul_mk], end end free_group /- lemma negative_cons_one_or_negative {L : list (α × bool)} {x} : negative ((x, ff) :: L) → mk L = 1 ∨ negative L ∨ (∃ e L₁, L = e ++ (x, tt) :: L₁ ∧ mk e = 1 ∧ negative L₁):= begin rintros ⟨L', hnil, hmk, hneg⟩, rw [← mul_right_inj ((mk L')⁻¹), inv_mul_self] at hmk, simp only [inv_mk, mul_mk] at hmk, generalize eq₁ : (list.map (λ (x : α × bool), (x.fst, !x.snd)) L').reverse = LL, rw eq₁ at *, have h₁ : ∀ x : α × bool, x ∈ LL → x.snd = tt, { rintros ⟨x, b⟩ hx, cases b, { rw ← eq₁ at hx, simp at hx, specialize hneg (x, tt) hx, contradiction, }, { refl, }, }, have h₂ := append_cons_one_exists_suffix_or_prefix_eq_one hmk, cases h₂, { rcases h₂ with ⟨e, ⟨t, ht⟩, he⟩, rw ← ht at hmk, have h₃ : e = [], { cases e, refl, cases e_hd with a b, have h₄ : (a, b) ∈ LL := by {rw ← ht, simp}, cases b, rw ← eq₁ at h₄, simp at h₄, specialize hneg (a, tt) h₄, contradiction, { rw [mk_one_iff, red.cons_nil_iff_singleton] at he, have := red.sublist he, simp at *, specialize h₁ a ff _, rw ← ht, simp, right, exact this, contradiction, }, }, rw h₃ at *, have h₄ : mk (t ++ [(x, !ff)] ++ (x, ff) :: L) = mk (t ++ L), { have : t ++ [(x, !ff)] ++ (x, ff) :: L = t ++ [(x, tt), (x, !tt)] ++ L := by simp, rw [this, ← mul_mk, ← mul_mk, mk_bnot, mul_one, mul_mk], }, rw h₄ at hmk, cases t, left, simp at *, exact hmk, right, generalize eq₂ : ((list.map (λ (x : α × bool), (x.fst, !x.snd)) (t_hd :: t_tl)).reverse) = t_inv, use t_inv, split, { rw ← eq₂, simp, }, { split, rw [← mul_mk, ← mul_right_inj ((mk (t_hd :: t_tl))⁻¹), ← mul_assoc, inv_mul_self, one_mul, mul_one, inv_mk, eq₂] at hmk, exact hmk, { rintros ⟨x, b⟩ hx, rw ← eq₂ at hx, cases b, refl, generalize eq₃ : (t_hd :: t_tl = t), rw eq₃ at *, simp at hx, specialize h₁ (x, ff) _, rw ← ht, simp, exact hx, contradiction, }, }, }, { rcases h₂ with ⟨e, ⟨t, ht⟩, he⟩, left, sorry, } end -/ /- have h₇ : e = [], { cases e, refl, induction e_hd with x b, rw [free_group.mk_one_iff, free_group.red.cons_nil_iff_singleton] at h₄, have h₅ := free_group.red.sublist h₄, simp at h₅, cases b, { specialize h₆ (x, ff) _, rw ← h₃, simp, contradiction, }, { specialize h₆ (x, ff) _, simp at h₅, rw ← h₃, simp, right, right, exact h₅, contradiction, }, }, subst e, rw ← h₃ at hmk, lemma negative_exists_prefix {α} {L : list (α × bool)} : dyck.negative L → ∃ e x, list.is_prefix (e ++ [(x, ff)]) L ∧ dyck.mk e = 1:= begin rintros ⟨L', hnil, hmk, hneg⟩, have h₁ := dyck.mk_free_group hmk, rw [← mul_right_inj (free_group.mk L')⁻¹, inv_mul_self, free_group.inv_mk, free_group.mul_mk] at h₁, cases L' with hd tl, { sorry, }, { cases hd with x b, cases b, { simp at h₁, have h₂ := free_group.append_cons_one_exists_suffix_or_prefix_eq_one h₁, cases h₂, { sorry, }, { rcases h₂ with ⟨e, ht, he⟩, sorry, }, }, { sorry, } } end example (L L₁ : list ((α ⊕ unit) × bool)) : dyck.mk (L ++ L₁) = 1 → ∃ L₂ L₃, L₁ = L₂ ++ L₃ ∧ (L₃ = [] ∨ ∃ L₄ x, L₃ = (x, ff) :: L₄) ∧ (dyck.mk (L ++ (inr (), tt) :: (L₂ ++ ((inr (), ff)) :: L₃ )) = 1) := begin intro h, have h₁ := dyck.dyck_one_prefix_pos_or_one h, specialize h₁ L (by simp), cases h₁, { have h₂ := dyck.dyck_one_suffix_neg_or_one h, specialize h₂ L₁ (by simp), cases h₂, { have h₃ := negative_exists_prefix h₂, rcases h₃ with ⟨e, x, ⟨t, ht⟩, he⟩, use [e, (x, ff) :: t], simp at ht, split, exact ht.symm, split, right, use [t, x], sorry, }, { sorry, } }, { /- use L₁, use ([]), split, simp, split, left, refl, rw [← dyck.mul_mk, h₁, one_mul] at h, have h₂ : L ++ (inr (), tt) :: (L₁ ++ [(inr (), ff)]) = L ++ [((inr (), tt))] ++ L₁ ++ [(inr (), ff)] := by simp, rw h₂, repeat {rw ← dyck.mul_mk}, rw [h, h₁, one_mul, mul_one, dyck.mul_mk, list.singleton_append, dyck.mk_mul_inv], -/ sorry, } end -/
{-# LANGUAGE Rank2Types #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} ----------------------------------------------------------------------------- -- | -- Copyright : (c) Edward Kmett 2010-2014 -- License : BSD3 -- Maintainer : [email protected] -- Stability : experimental -- Portability : GHC only -- ----------------------------------------------------------------------------- module Numeric.AD.Newton ( -- * Newton's Method (Forward AD) findZero , inverse , fixedPoint , extremum -- * Gradient Ascent/Descent (Reverse AD) , gradientDescent , gradientAscent , conjugateGradientDescent , conjugateGradientAscent ) where import Data.Foldable (all, sum) import Data.Reflection (Reifies) import Data.Traversable import Numeric.AD.Internal.Combinators import Numeric.AD.Internal.Forward (Forward) import Numeric.AD.Internal.On import Numeric.AD.Internal.Or import Numeric.AD.Internal.Reverse (Reverse, Tape) import Numeric.AD.Internal.Type (AD(..)) import Numeric.AD.Mode import Numeric.AD.Mode.Reverse as Reverse (gradWith') import Numeric.AD.Rank1.Kahn as Kahn (Kahn, grad) import qualified Numeric.AD.Rank1.Newton as Rank1 import Prelude hiding (all, mapM, sum) -- $setup -- >>> import Data.Complex -- | The 'findZero' function finds a zero of a scalar function using -- Newton's method; its output is a stream of increasingly accurate -- results. (Modulo the usual caveats.) If the stream becomes constant -- ("it converges"), no further elements are returned. -- -- Examples: -- -- >>> take 10 $ findZero (\x->x^2-4) 1 -- [1.0,2.5,2.05,2.000609756097561,2.0000000929222947,2.000000000000002,2.0] -- -- >>> last $ take 10 $ findZero ((+1).(^2)) (1 :+ 1) -- 0.0 :+ 1.0 findZero :: (Fractional a, Eq a) => (forall s. AD s (Forward a) -> AD s (Forward a)) -> a -> [a] findZero f = Rank1.findZero (runAD.f.AD) {-# INLINE findZero #-} -- | The 'inverse' function inverts a scalar function using -- Newton's method; its output is a stream of increasingly accurate -- results. (Modulo the usual caveats.) If the stream becomes -- constant ("it converges"), no further elements are returned. -- -- Example: -- -- >>> last $ take 10 $ inverse sqrt 1 (sqrt 10) -- 10.0 inverse :: (Fractional a, Eq a) => (forall s. AD s (Forward a) -> AD s (Forward a)) -> a -> a -> [a] inverse f = Rank1.inverse (runAD.f.AD) {-# INLINE inverse #-} -- | The 'fixedPoint' function find a fixedpoint of a scalar -- function using Newton's method; its output is a stream of -- increasingly accurate results. (Modulo the usual caveats.) -- -- If the stream becomes constant ("it converges"), no further -- elements are returned. -- -- >>> last $ take 10 $ fixedPoint cos 1 -- 0.7390851332151607 fixedPoint :: (Fractional a, Eq a) => (forall s. AD s (Forward a) -> AD s (Forward a)) -> a -> [a] fixedPoint f = Rank1.fixedPoint (runAD.f.AD) {-# INLINE fixedPoint #-} -- | The 'extremum' function finds an extremum of a scalar -- function using Newton's method; produces a stream of increasingly -- accurate results. (Modulo the usual caveats.) If the stream -- becomes constant ("it converges"), no further elements are returned. -- -- >>> last $ take 10 $ extremum cos 1 -- 0.0 extremum :: (Fractional a, Eq a) => (forall s. AD s (On (Forward (Forward a))) -> AD s (On (Forward (Forward a)))) -> a -> [a] extremum f = Rank1.extremum (runAD.f.AD) {-# INLINE extremum #-} -- | The 'gradientDescent' function performs a multivariate -- optimization, based on the naive-gradient-descent in the file -- @stalingrad\/examples\/flow-tests\/pre-saddle-1a.vlad@ from the -- VLAD compiler Stalingrad sources. Its output is a stream of -- increasingly accurate results. (Modulo the usual caveats.) -- -- It uses reverse mode automatic differentiation to compute the gradient. gradientDescent :: (Traversable f, Fractional a, Ord a) => (forall s. Reifies s Tape => f (Reverse s a) -> Reverse s a) -> f a -> [f a] gradientDescent f x0 = go x0 fx0 xgx0 0.1 (0 :: Int) where (fx0, xgx0) = Reverse.gradWith' (,) f x0 go x fx xgx !eta !i | eta == 0 = [] -- step size is 0 | fx1 > fx = go x fx xgx (eta/2) 0 -- we stepped too far | zeroGrad xgx = [] -- gradient is 0 | otherwise = x1 : if i == 10 then go x1 fx1 xgx1 (eta*2) 0 else go x1 fx1 xgx1 eta (i+1) where zeroGrad = all (\(_,g) -> g == 0) x1 = fmap (\(xi,gxi) -> xi - eta * gxi) xgx (fx1, xgx1) = Reverse.gradWith' (,) f x1 {-# INLINE gradientDescent #-} -- | Perform a gradient descent using reverse mode automatic differentiation to compute the gradient. gradientAscent :: (Traversable f, Fractional a, Ord a) => (forall s. Reifies s Tape => f (Reverse s a) -> Reverse s a) -> f a -> [f a] gradientAscent f = gradientDescent (negate . f) {-# INLINE gradientAscent #-} -- | Perform a conjugate gradient descent using reverse mode automatic differentiation to compute the gradient, and using forward-on-forward mode for computing extrema. -- -- >>> let sq x = x * x -- >>> let rosenbrock [x,y] = sq (1 - x) + 100 * sq (y - sq x) -- >>> rosenbrock [0,0] -- 1 -- >>> rosenbrock (conjugateGradientDescent rosenbrock [0, 0] !! 5) < 0.1 -- True conjugateGradientDescent :: (Traversable f, Ord a, Fractional a) => (forall s. Chosen s => f (Or s (On (Forward (Forward a))) (Kahn a)) -> Or s (On (Forward (Forward a))) (Kahn a)) -> f a -> [f a] conjugateGradientDescent f = conjugateGradientAscent (negate . f) {-# INLINE conjugateGradientDescent #-} lfu :: Functor f => (f (Or F a b) -> Or F a b) -> f a -> a lfu f = runL . f . fmap L rfu :: Functor f => (f (Or T a b) -> Or T a b) -> f b -> b rfu f = runR . f . fmap R -- | Perform a conjugate gradient ascent using reverse mode automatic differentiation to compute the gradient. conjugateGradientAscent :: (Traversable f, Ord a, Fractional a) => (forall s. Chosen s => f (Or s (On (Forward (Forward a))) (Kahn a)) -> Or s (On (Forward (Forward a))) (Kahn a)) -> f a -> [f a] conjugateGradientAscent f x0 = takeWhile (all (\a -> a == a)) (go x0 d0 d0 delta0) where dot x y = sum $ zipWithT (*) x y d0 = Kahn.grad (rfu f) x0 delta0 = dot d0 d0 go xi _ri di deltai = xi : go xi1 ri1 di1 deltai1 where ai = last $ take 20 $ Rank1.extremum (\a -> lfu f $ zipWithT (\x d -> auto x + a * auto d) xi di) 0 xi1 = zipWithT (\x d -> x + ai*d) xi di ri1 = Kahn.grad (rfu f) xi1 deltai1 = dot ri1 ri1 bi1 = deltai1 / deltai di1 = zipWithT (\r d -> r + bi1 * d) ri1 di {-# INLINE conjugateGradientAscent #-}
module timing contains function get_time() implicit none integer(kind=8) :: cnt, cnt_rate, cnt_max real*8 get_time call system_clock(cnt, cnt_rate, cnt_max) get_time = cnt get_time = get_time/cnt_rate end function end module
/** @file */ #ifndef __STL_CONCEPT_CONVERTIBLE_TO_HPP__ #define __STL_CONCEPT_CONVERTIBLE_TO_HPP__ #include <type_traits> #include <boost/concept/usage.hpp> #include <boost/concept/detail/concept_def.hpp> #include "concept/detail/unuse.hpp" #if (defined _MSC_VER) #pragma warning(push) #pragma warning(disable : 4197) // topmost volatile ignored #pragma warning(disable : 4510) // default constructor could not be generated #pragma warning(disable : 4610) // object 'class' can never be instantiated - user-defined constructor required #endif namespace stl_concept { /** * @addtogroup core_group Core Language Concepts * @class stl_concept::ConvertibleTo * @brief Specifies that an expression of the type and value category specified by From can be implicitly and explicitly * converted to the type To, and the two forms of conversion are equivalent. * * <p> * Specifically, <i>ConvertibleTo</i> is satisfied only if, given the invented function * ``` * To test(From (&f)()) * { * return f(); * } * ``` * and a function f of type From () such that the expression f() is equality-preserving, * The type T satisfies <i>ConvertibleTo</i> if * <ul style="list-style-type:disc"> * <li>Either</li> * <ul style="list-style-type:disc"> * <li>To is neither an object type nor a reference-to-object type, or</li> * <li>static_cast<To>(f()) is equal to test(f), and</li> * </ul> * </ul> * <ul style="list-style-type:disc"> * <li>One of the following is true:</li> * <ul style="list-style-type:disc"> * <li>From is not a reference-to-object type, or</li> * <li>From is an rvalue reference to a non-const-qualified type, and the resulting state of the object referenced * by f() is valid but unspecified after either expression above; or</li> * <li>the object referred to by f() is not modified by either expression above.</li> * </ul> * </ul> * </p> * @tparam From - type to be converted from * @tparam To - type to be converted to * @see https://en.cppreference.com/w/cpp/concepts/ConvertibleTo */ #ifdef DOXYGEN_WORKING template <typename From, typename To> struct ConvertibleTo {}; #else // DOXYGEN_WORKING BOOST_concept(ConvertibleTo, (From)(To)) { BOOST_CONCEPT_USAGE(ConvertibleTo) { static_assert(std::is_convertible<From, To>::value, ""); convertible_constraints(func_); } private: ConvertibleTo(); using __ConvertibleFuncRef = From (&)(); void convertible_constraints(__ConvertibleFuncRef f) { __detail::__unuse(static_cast<To>(f())); } __ConvertibleFuncRef func_; }; #endif // DOXYGEN_WORKING } // namespace stl_concept #if (defined _MSC_VER) #pragma warning(pop) #endif #include <boost/concept/detail/concept_undef.hpp> #endif // __STL_CONCEPT_CONVERTIBLE_TO_HPP__
State Before: a : Rat ⊢ 1 * a = a State After: no goals Tactic: simp [mul_def, normalize_self]
State Before: α : Type u_1 M : Type u_3 N : Type ?u.294176 P : Type ?u.294179 R : Type u_2 S : Type ?u.294185 inst✝¹² : Semiring R inst✝¹¹ : Semiring S inst✝¹⁰ : AddCommMonoid M inst✝⁹ : Module R M inst✝⁸ : AddCommMonoid N inst✝⁷ : Module R N inst✝⁶ : AddCommMonoid P inst✝⁵ : Module R P α' : Type ?u.294277 M' : Type ?u.294280 inst✝⁴ : Semiring R inst✝³ : AddCommMonoid M' inst✝² : AddCommMonoid M inst✝¹ : Module R M' inst✝ : Module R M v : α → M v' : α' → M' x : α →₀ R ⊢ ↑(Finsupp.total α M R 0) x = 0 State After: no goals Tactic: simp [Finsupp.total_apply]
[GOAL] m n k : ℕ ⊢ gcd m (n + k * m) = gcd m n [PROOFSTEP] simp [gcd_rec m (n + k * m), gcd_rec m n] [GOAL] m n k : ℕ ⊢ gcd m (n + m * k) = gcd m n [PROOFSTEP] simp [gcd_rec m (n + m * k), gcd_rec m n] [GOAL] m n k : ℕ ⊢ gcd m (k * m + n) = gcd m n [PROOFSTEP] simp [add_comm _ n] [GOAL] m n k : ℕ ⊢ gcd m (m * k + n) = gcd m n [PROOFSTEP] simp [add_comm _ n] [GOAL] m n k : ℕ ⊢ gcd (m + k * n) n = gcd m n [PROOFSTEP] rw [gcd_comm, gcd_add_mul_right_right, gcd_comm] [GOAL] m n k : ℕ ⊢ gcd (m + n * k) n = gcd m n [PROOFSTEP] rw [gcd_comm, gcd_add_mul_left_right, gcd_comm] [GOAL] m n k : ℕ ⊢ gcd (k * n + m) n = gcd m n [PROOFSTEP] rw [gcd_comm, gcd_mul_right_add_right, gcd_comm] [GOAL] m n k : ℕ ⊢ gcd (n * k + m) n = gcd m n [PROOFSTEP] rw [gcd_comm, gcd_mul_left_add_right, gcd_comm] [GOAL] m n : ℕ ⊢ gcd m (n + m) = gcd m (n + 1 * m) [PROOFSTEP] rw [one_mul] [GOAL] m n : ℕ ⊢ gcd (m + n) n = gcd m n [PROOFSTEP] rw [gcd_comm, gcd_add_self_right, gcd_comm] [GOAL] m n : ℕ ⊢ gcd (m + n) m = gcd n m [PROOFSTEP] rw [add_comm, gcd_add_self_left] [GOAL] m n : ℕ ⊢ gcd m (m + n) = gcd m n [PROOFSTEP] rw [add_comm, gcd_add_self_right] [GOAL] m n : ℕ ⊢ 0 < m → 0 < n → 0 < lcm m n [PROOFSTEP] simp_rw [pos_iff_ne_zero] [GOAL] m n : ℕ ⊢ m ≠ 0 → n ≠ 0 → lcm m n ≠ 0 [PROOFSTEP] exact lcm_ne_zero [GOAL] m n : ℕ h : coprime m n ⊢ lcm m n = m * n [PROOFSTEP] rw [← one_mul (lcm m n), ← h.gcd_eq_one, gcd_mul_lcm] [GOAL] m n : ℕ ⊢ coprime m (n + m) ↔ coprime m n [PROOFSTEP] rw [coprime, coprime, gcd_add_self_right] [GOAL] m n : ℕ ⊢ coprime m (m + n) ↔ coprime m n [PROOFSTEP] rw [add_comm, coprime_add_self_right] [GOAL] m n : ℕ ⊢ coprime (m + n) n ↔ coprime m n [PROOFSTEP] rw [coprime, coprime, gcd_add_self_left] [GOAL] m n : ℕ ⊢ coprime (m + n) m ↔ coprime n m [PROOFSTEP] rw [coprime, coprime, gcd_self_add_left] [GOAL] m n k : ℕ ⊢ coprime m (n + k * m) ↔ coprime m n [PROOFSTEP] rw [coprime, coprime, gcd_add_mul_right_right] [GOAL] m n k : ℕ ⊢ coprime m (n + m * k) ↔ coprime m n [PROOFSTEP] rw [coprime, coprime, gcd_add_mul_left_right] [GOAL] m n k : ℕ ⊢ coprime m (k * m + n) ↔ coprime m n [PROOFSTEP] rw [coprime, coprime, gcd_mul_right_add_right] [GOAL] m n k : ℕ ⊢ coprime m (m * k + n) ↔ coprime m n [PROOFSTEP] rw [coprime, coprime, gcd_mul_left_add_right] [GOAL] m n k : ℕ ⊢ coprime (m + k * n) n ↔ coprime m n [PROOFSTEP] rw [coprime, coprime, gcd_add_mul_right_left] [GOAL] m n k : ℕ ⊢ coprime (m + n * k) n ↔ coprime m n [PROOFSTEP] rw [coprime, coprime, gcd_add_mul_left_left] [GOAL] m n k : ℕ ⊢ coprime (k * n + m) n ↔ coprime m n [PROOFSTEP] rw [coprime, coprime, gcd_mul_right_add_left] [GOAL] m n k : ℕ ⊢ coprime (n * k + m) n ↔ coprime m n [PROOFSTEP] rw [coprime, coprime, gcd_mul_left_add_left] [GOAL] n : ℕ hn : 0 < n a b : ℕ ⊢ coprime (a ^ n) b ↔ coprime a b [PROOFSTEP] obtain ⟨n, rfl⟩ := exists_eq_succ_of_ne_zero hn.ne' [GOAL] case intro a b n : ℕ hn : 0 < succ n ⊢ coprime (a ^ succ n) b ↔ coprime a b [PROOFSTEP] rw [pow_succ, Nat.coprime_mul_iff_left] [GOAL] case intro a b n : ℕ hn : 0 < succ n ⊢ coprime (a ^ n) b ∧ coprime a b ↔ coprime a b [PROOFSTEP] exact ⟨And.right, fun hab => ⟨hab.pow_left _, hab⟩⟩ [GOAL] n : ℕ hn : 0 < n a b : ℕ ⊢ coprime a (b ^ n) ↔ coprime a b [PROOFSTEP] rw [Nat.coprime_comm, coprime_pow_left_iff hn, Nat.coprime_comm] [GOAL] ⊢ ¬coprime 0 0 [PROOFSTEP] simp [GOAL] n : ℕ ⊢ coprime 1 n ↔ True [PROOFSTEP] simp [coprime] [GOAL] n : ℕ ⊢ coprime n 1 ↔ True [PROOFSTEP] simp [coprime] [GOAL] a b c : ℕ hac : coprime a c b_dvd_c : b ∣ c ⊢ gcd (a * b) c = b [PROOFSTEP] rcases exists_eq_mul_left_of_dvd b_dvd_c with ⟨d, rfl⟩ [GOAL] case intro a b d : ℕ hac : coprime a (d * b) b_dvd_c : b ∣ d * b ⊢ gcd (a * b) (d * b) = b [PROOFSTEP] rw [gcd_mul_right] [GOAL] case intro a b d : ℕ hac : coprime a (d * b) b_dvd_c : b ∣ d * b ⊢ gcd a d * b = b [PROOFSTEP] convert one_mul b [GOAL] case h.e'_2.h.e'_5 a b d : ℕ hac : coprime a (d * b) b_dvd_c : b ∣ d * b ⊢ gcd a d = 1 [PROOFSTEP] exact coprime.coprime_mul_right_right hac [GOAL] m n k : ℕ H : k ∣ m * n ⊢ { d // k = ↑d.fst * ↑d.snd } [PROOFSTEP] cases h0 : gcd k m [GOAL] case zero m n k : ℕ H : k ∣ m * n h0 : gcd k m = zero ⊢ { d // k = ↑d.fst * ↑d.snd } case succ m n k : ℕ H : k ∣ m * n n✝ : ℕ h0 : gcd k m = succ n✝ ⊢ { d // k = ↑d.fst * ↑d.snd } [PROOFSTEP] case zero => obtain rfl : k = 0 := eq_zero_of_gcd_eq_zero_left h0 obtain rfl : m = 0 := eq_zero_of_gcd_eq_zero_right h0 exact ⟨⟨⟨0, dvd_refl 0⟩, ⟨n, dvd_refl n⟩⟩, (zero_mul n).symm⟩ [GOAL] m n k : ℕ H : k ∣ m * n h0 : gcd k m = zero ⊢ { d // k = ↑d.fst * ↑d.snd } [PROOFSTEP] case zero => obtain rfl : k = 0 := eq_zero_of_gcd_eq_zero_left h0 obtain rfl : m = 0 := eq_zero_of_gcd_eq_zero_right h0 exact ⟨⟨⟨0, dvd_refl 0⟩, ⟨n, dvd_refl n⟩⟩, (zero_mul n).symm⟩ [GOAL] m n k : ℕ H : k ∣ m * n h0 : gcd k m = zero ⊢ { d // k = ↑d.fst * ↑d.snd } [PROOFSTEP] obtain rfl : k = 0 := eq_zero_of_gcd_eq_zero_left h0 [GOAL] m n : ℕ H : 0 ∣ m * n h0 : gcd 0 m = zero ⊢ { d // 0 = ↑d.fst * ↑d.snd } [PROOFSTEP] obtain rfl : m = 0 := eq_zero_of_gcd_eq_zero_right h0 [GOAL] n : ℕ H : 0 ∣ 0 * n h0 : gcd 0 0 = zero ⊢ { d // 0 = ↑d.fst * ↑d.snd } [PROOFSTEP] exact ⟨⟨⟨0, dvd_refl 0⟩, ⟨n, dvd_refl n⟩⟩, (zero_mul n).symm⟩ [GOAL] case succ m n k : ℕ H : k ∣ m * n n✝ : ℕ h0 : gcd k m = succ n✝ ⊢ { d // k = ↑d.fst * ↑d.snd } [PROOFSTEP] case succ tmp => have hpos : 0 < gcd k m := h0.symm ▸ Nat.zero_lt_succ _; clear h0 tmp have hd : gcd k m * (k / gcd k m) = k := Nat.mul_div_cancel' (gcd_dvd_left k m) refine' ⟨⟨⟨gcd k m, gcd_dvd_right k m⟩, ⟨k / gcd k m, _⟩⟩, hd.symm⟩ apply Nat.dvd_of_mul_dvd_mul_left hpos rw [hd, ← gcd_mul_right] exact dvd_gcd (dvd_mul_right _ _) H [GOAL] m n k : ℕ H : k ∣ m * n tmp : ℕ h0 : gcd k m = succ tmp ⊢ { d // k = ↑d.fst * ↑d.snd } [PROOFSTEP] case succ tmp => have hpos : 0 < gcd k m := h0.symm ▸ Nat.zero_lt_succ _; clear h0 tmp have hd : gcd k m * (k / gcd k m) = k := Nat.mul_div_cancel' (gcd_dvd_left k m) refine' ⟨⟨⟨gcd k m, gcd_dvd_right k m⟩, ⟨k / gcd k m, _⟩⟩, hd.symm⟩ apply Nat.dvd_of_mul_dvd_mul_left hpos rw [hd, ← gcd_mul_right] exact dvd_gcd (dvd_mul_right _ _) H [GOAL] m n k : ℕ H : k ∣ m * n tmp : ℕ h0 : gcd k m = succ tmp ⊢ { d // k = ↑d.fst * ↑d.snd } [PROOFSTEP] have hpos : 0 < gcd k m := h0.symm ▸ Nat.zero_lt_succ _ [GOAL] m n k : ℕ H : k ∣ m * n tmp : ℕ h0 : gcd k m = succ tmp hpos : 0 < gcd k m ⊢ { d // k = ↑d.fst * ↑d.snd } [PROOFSTEP] clear h0 tmp [GOAL] m n k : ℕ H : k ∣ m * n hpos : 0 < gcd k m ⊢ { d // k = ↑d.fst * ↑d.snd } [PROOFSTEP] have hd : gcd k m * (k / gcd k m) = k := Nat.mul_div_cancel' (gcd_dvd_left k m) [GOAL] m n k : ℕ H : k ∣ m * n hpos : 0 < gcd k m hd : gcd k m * (k / gcd k m) = k ⊢ { d // k = ↑d.fst * ↑d.snd } [PROOFSTEP] refine' ⟨⟨⟨gcd k m, gcd_dvd_right k m⟩, ⟨k / gcd k m, _⟩⟩, hd.symm⟩ [GOAL] m n k : ℕ H : k ∣ m * n hpos : 0 < gcd k m hd : gcd k m * (k / gcd k m) = k ⊢ k / gcd k m ∣ n [PROOFSTEP] apply Nat.dvd_of_mul_dvd_mul_left hpos [GOAL] m n k : ℕ H : k ∣ m * n hpos : 0 < gcd k m hd : gcd k m * (k / gcd k m) = k ⊢ gcd k m * (k / gcd k m) ∣ gcd k m * n [PROOFSTEP] rw [hd, ← gcd_mul_right] [GOAL] m n k : ℕ H : k ∣ m * n hpos : 0 < gcd k m hd : gcd k m * (k / gcd k m) = k ⊢ k ∣ gcd (k * n) (m * n) [PROOFSTEP] exact dvd_gcd (dvd_mul_right _ _) H [GOAL] x m n : ℕ ⊢ x ∣ m * n ↔ ∃ y z, y ∣ m ∧ z ∣ n ∧ y * z = x [PROOFSTEP] constructor [GOAL] case mp x m n : ℕ ⊢ x ∣ m * n → ∃ y z, y ∣ m ∧ z ∣ n ∧ y * z = x [PROOFSTEP] intro h [GOAL] case mp x m n : ℕ h : x ∣ m * n ⊢ ∃ y z, y ∣ m ∧ z ∣ n ∧ y * z = x [PROOFSTEP] obtain ⟨⟨⟨y, hy⟩, ⟨z, hz⟩⟩, rfl⟩ := prod_dvd_and_dvd_of_dvd_prod h [GOAL] case mp.mk.mk.mk.mk m n y : ℕ hy : y ∣ m z : ℕ hz : z ∣ n h : ↑({ val := y, property := hy }, { val := z, property := hz }).fst * ↑({ val := y, property := hy }, { val := z, property := hz }).snd ∣ m * n ⊢ ∃ y_1 z_1, y_1 ∣ m ∧ z_1 ∣ n ∧ y_1 * z_1 = ↑({ val := y, property := hy }, { val := z, property := hz }).fst * ↑({ val := y, property := hy }, { val := z, property := hz }).snd [PROOFSTEP] exact ⟨y, z, hy, hz, rfl⟩ [GOAL] case mpr x m n : ℕ ⊢ (∃ y z, y ∣ m ∧ z ∣ n ∧ y * z = x) → x ∣ m * n [PROOFSTEP] rintro ⟨y, z, hy, hz, rfl⟩ [GOAL] case mpr.intro.intro.intro.intro m n y z : ℕ hy : y ∣ m hz : z ∣ n ⊢ y * z ∣ m * n [PROOFSTEP] exact mul_dvd_mul hy hz [GOAL] a b n : ℕ n0 : 0 < n ⊢ a ^ n ∣ b ^ n ↔ a ∣ b [PROOFSTEP] refine' ⟨fun h => _, fun h => pow_dvd_pow_of_dvd h _⟩ [GOAL] a b n : ℕ n0 : 0 < n h : a ^ n ∣ b ^ n ⊢ a ∣ b [PROOFSTEP] cases' Nat.eq_zero_or_pos (gcd a b) with g0 g0 [GOAL] case inl a b n : ℕ n0 : 0 < n h : a ^ n ∣ b ^ n g0 : gcd a b = 0 ⊢ a ∣ b [PROOFSTEP] simp [eq_zero_of_gcd_eq_zero_right g0] [GOAL] case inr a b n : ℕ n0 : 0 < n h : a ^ n ∣ b ^ n g0 : gcd a b > 0 ⊢ a ∣ b [PROOFSTEP] rcases exists_coprime' g0 with ⟨g, a', b', g0', co, rfl, rfl⟩ [GOAL] case inr.intro.intro.intro.intro.intro.intro n : ℕ n0 : 0 < n g : ℕ a' b' : ℕ g0' : 0 < g co : coprime a' b' h : (a' * g) ^ n ∣ (b' * g) ^ n g0 : gcd (a' * g) (b' * g) > 0 ⊢ a' * g ∣ b' * g [PROOFSTEP] rw [mul_pow, mul_pow] at h [GOAL] case inr.intro.intro.intro.intro.intro.intro n : ℕ n0 : 0 < n g : ℕ a' b' : ℕ g0' : 0 < g co : coprime a' b' h : a' ^ n * g ^ n ∣ b' ^ n * g ^ n g0 : gcd (a' * g) (b' * g) > 0 ⊢ a' * g ∣ b' * g [PROOFSTEP] replace h := Nat.dvd_of_mul_dvd_mul_right (pow_pos g0' _) h [GOAL] case inr.intro.intro.intro.intro.intro.intro n : ℕ n0 : 0 < n g : ℕ a' b' : ℕ g0' : 0 < g co : coprime a' b' g0 : gcd (a' * g) (b' * g) > 0 h : a' ^ n ∣ b' ^ n ⊢ a' * g ∣ b' * g [PROOFSTEP] have := pow_dvd_pow a' n0 [GOAL] case inr.intro.intro.intro.intro.intro.intro n : ℕ n0 : 0 < n g : ℕ a' b' : ℕ g0' : 0 < g co : coprime a' b' g0 : gcd (a' * g) (b' * g) > 0 h : a' ^ n ∣ b' ^ n this : a' ^ succ 0 ∣ a' ^ n ⊢ a' * g ∣ b' * g [PROOFSTEP] rw [pow_one, (co.pow n n).eq_one_of_dvd h] at this [GOAL] case inr.intro.intro.intro.intro.intro.intro n : ℕ n0 : 0 < n g : ℕ a' b' : ℕ g0' : 0 < g co : coprime a' b' g0 : gcd (a' * g) (b' * g) > 0 h : a' ^ n ∣ b' ^ n this : a' ∣ 1 ⊢ a' * g ∣ b' * g [PROOFSTEP] simp [eq_one_of_dvd_one this] [GOAL] a b k : ℕ h_ab_coprime : coprime a b hka : k ∣ a hkb : k ∣ b ⊢ k = 1 [PROOFSTEP] rw [coprime_iff_gcd_eq_one] at h_ab_coprime [GOAL] a b k : ℕ h_ab_coprime : gcd a b = 1 hka : k ∣ a hkb : k ∣ b ⊢ k = 1 [PROOFSTEP] have h1 := dvd_gcd hka hkb [GOAL] a b k : ℕ h_ab_coprime : gcd a b = 1 hka : k ∣ a hkb : k ∣ b h1 : k ∣ gcd a b ⊢ k = 1 [PROOFSTEP] rw [h_ab_coprime] at h1 [GOAL] a b k : ℕ h_ab_coprime : gcd a b = 1 hka : k ∣ a hkb : k ∣ b h1 : k ∣ 1 ⊢ k = 1 [PROOFSTEP] exact Nat.dvd_one.mp h1 [GOAL] m n a b : ℕ cop : coprime m n ha : a ≠ 0 hb : b ≠ 0 ⊢ a * m + b * n ≠ m * n [PROOFSTEP] intro h [GOAL] m n a b : ℕ cop : coprime m n ha : a ≠ 0 hb : b ≠ 0 h : a * m + b * n = m * n ⊢ False [PROOFSTEP] obtain ⟨x, rfl⟩ : n ∣ a := cop.symm.dvd_of_dvd_mul_right ((Nat.dvd_add_iff_left (Nat.dvd_mul_left n b)).mpr ((congr_arg _ h).mpr (Nat.dvd_mul_left n m))) [GOAL] case intro m n b : ℕ cop : coprime m n hb : b ≠ 0 x : ℕ ha : n * x ≠ 0 h : n * x * m + b * n = m * n ⊢ False [PROOFSTEP] obtain ⟨y, rfl⟩ : m ∣ b := cop.dvd_of_dvd_mul_right ((Nat.dvd_add_iff_right (Nat.dvd_mul_left m (n * x))).mpr ((congr_arg _ h).mpr (Nat.dvd_mul_right m n))) [GOAL] case intro.intro m n : ℕ cop : coprime m n x : ℕ ha : n * x ≠ 0 y : ℕ hb : m * y ≠ 0 h : n * x * m + m * y * n = m * n ⊢ False [PROOFSTEP] rw [mul_comm, mul_ne_zero_iff, ← one_le_iff_ne_zero] at ha hb [GOAL] case intro.intro m n : ℕ cop : coprime m n x : ℕ ha : 1 ≤ x ∧ n ≠ 0 y : ℕ hb : 1 ≤ y ∧ m ≠ 0 h : n * x * m + m * y * n = m * n ⊢ False [PROOFSTEP] refine' mul_ne_zero hb.2 ha.2 (eq_zero_of_mul_eq_self_left (ne_of_gt (add_le_add ha.1 hb.1)) _) [GOAL] case intro.intro m n : ℕ cop : coprime m n x : ℕ ha : 1 ≤ x ∧ n ≠ 0 y : ℕ hb : 1 ≤ y ∧ m ≠ 0 h : n * x * m + m * y * n = m * n ⊢ (x + y) * (m * n) = m * n [PROOFSTEP] rw [← mul_assoc, ← h, add_mul, add_mul, mul_comm _ n, ← mul_assoc, mul_comm y]
function setM(OCP,M) setM@DynamicSystem(OCP,M); end
import topology.instances.real namespace real theorem Inf_le_Sup (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) (h₃ : ∃ x, ∀ y ∈ S, x ≤ y) : Inf S ≤ Sup S := begin cases h₁ with k hk, exact le_trans (real.Inf_le _ h₃ hk) (real.le_Sup _ h₂ hk), end end real lemma exists_of_range_eq_range {α : Type*} [linear_order α] {f g : ℕ → α} (hfg : set.range f = set.range g) (n : ℕ) : ∃ k, f n = g k := begin have h₁ : f n ∈ set.range g, { simp [←hfg] }, rcases h₁ with ⟨t, ht⟩, use t, rw ht end lemma eq_of_strict_mono_of_range_eq {α : Type*} [linear_order α] {f g : ℕ → α} (hf : strict_mono f) (hg : strict_mono g) (hfg : set.range f = set.range g) : f = g := begin ext i, apply nat.strong_induction_on i, clear i, intros i ih, by_contra h, cases ne.lt_or_lt h with h₁ h₁, { cases exists_of_range_eq_range hfg i with m hm, have hmi : m < i, { rwa [hm, hg.lt_iff_lt] at h₁ }, specialize ih m hmi, rwa [←hf.lt_iff_lt, hm, ih] at hmi, exact lt_irrefl _ hmi }, { cases exists_of_range_eq_range hfg.symm i with m hm, have hmi : m < i, { rwa [hm, hf.lt_iff_lt] at h₁ }, specialize ih m hmi, rwa [←hg.lt_iff_lt, hm, ih] at hmi, exact lt_irrefl _ hmi } end def bounded_within (f : ℝ → ℝ) (a b : ℝ) := ∃ k, ∀ x ∈ set.Icc a b, abs (f x) < k
program yeval use omp_lib implicit none integer(kind=8), parameter :: n = 2**16 integer(kind=4) :: i, nthreads real(kind=8), dimension(n) :: y real(kind=8) :: dx, x ! Specify number of threads to use: !$ print *, "How many threads to use? " !$ read *, nthreads !$ call omp_set_num_threads(nthreads) !$ print "('Using OpenMP with ',i3,' threads')", nthreads dx = 1.d0 / (n+1.d0) !$omp parallel do private(x) do i=1, n x = i * dx y(i) = exp(x) * cos(x) * sin(x) * sqrt(5.d0 * x + 6.d0) enddo !$omp end parallel do print *, "Filled vector y of length", n end program yeval
import numpy as np # ax A = np.array([0, 1, 2]).reshape(-1, 1) b = np.array([-1, -2, -3]).reshape(-1, 1) x = np.linalg.inv(A.T.dot(A)).dot(A.T).dot(b) print(x) # ax + b A = np.array([[0, 1], [1, 1], [2, 1]]).reshape(-1, 2) b = np.array([-1, -2, -3]).reshape(-1, 1) x = np.linalg.inv(A.T.dot(A)).dot(A.T).dot(b) print(x) # Correlation Coefficient A = np.array([0, 1, 8]) B = np.array([0, 2, -1]) print(np.corrcoef(A, B)[0, 1])