Datasets:
AI4M
/

text
stringlengths
0
3.34M
[STATEMENT] lemma tree_chop_den: "tree_chop den = num + den - 2 * (num mod den)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. tree_chop den = num + den - 2 * (num mod den) [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. tree_chop den = num + den - 2 * (num mod den) [PROOF STEP] have le: "0 < y \<Longrightarrow> 2 * (x mod y) \<le> x + y" for x y :: nat [PROOF STATE] proof (prove) goal (1 subgoal): 1. 0 < y \<Longrightarrow> 2 * (x mod y) \<le> x + y [PROOF STEP] by (simp add: mult_2 add_mono) [PROOF STATE] proof (state) this: 0 < ?y \<Longrightarrow> 2 * (?x mod ?y) \<le> ?x + ?y goal (1 subgoal): 1. tree_chop den = num + den - 2 * (num mod den) [PROOF STEP] text \<open>We switch to @{typ int} such that all cancellation laws are available.\<close> [PROOF STATE] proof (state) this: 0 < ?y \<Longrightarrow> 2 * (?x mod ?y) \<le> ?x + ?y goal (1 subgoal): 1. tree_chop den = num + den - 2 * (num mod den) [PROOF STEP] define den' where "den' = pure int \<diamondop> den" [PROOF STATE] proof (state) this: den' = pure int \<diamondop> den goal (1 subgoal): 1. tree_chop den = num + den - 2 * (num mod den) [PROOF STEP] define num' where "num' = pure int \<diamondop> num" [PROOF STATE] proof (state) this: num' = pure int \<diamondop> num goal (1 subgoal): 1. tree_chop den = num + den - 2 * (num mod den) [PROOF STEP] define num_mod_den' where "num_mod_den' = pure int \<diamondop> num_mod_den" [PROOF STATE] proof (state) this: num_mod_den' = pure int \<diamondop> num_mod_den goal (1 subgoal): 1. tree_chop den = num + den - 2 * (num mod den) [PROOF STEP] have [simp]: "root num' = 1" "left num' = num'" [PROOF STATE] proof (prove) goal (1 subgoal): 1. root num' = 1 &&& left num' = num' [PROOF STEP] unfolding den'_def num'_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. root (pure int \<diamondop> num) = 1 &&& left (pure int \<diamondop> num) = pure int \<diamondop> num [PROOF STEP] by simp_all [PROOF STATE] proof (state) this: root num' = 1 left num' = num' goal (1 subgoal): 1. tree_chop den = num + den - 2 * (num mod den) [PROOF STEP] have [simp]: "right num' = num' + den'" [PROOF STATE] proof (prove) goal (1 subgoal): 1. right num' = num' + den' [PROOF STEP] unfolding den'_def num'_def ap_tree.sel pure_tree_simps num_simps [PROOF STATE] proof (prove) goal (1 subgoal): 1. pure int \<diamondop> (num + den) = pure int \<diamondop> num + pure int \<diamondop> den [PROOF STEP] by applicative_lifting simp [PROOF STATE] proof (state) this: right num' = num' + den' goal (1 subgoal): 1. tree_chop den = num + den - 2 * (num mod den) [PROOF STEP] have num_mod_den'_simps [simp]: "root num_mod_den' = 0" "left num_mod_den' = num'" "right num_mod_den' = num_mod_den'" [PROOF STATE] proof (prove) goal (1 subgoal): 1. root num_mod_den' = 0 &&& left num_mod_den' = num' &&& right num_mod_den' = num_mod_den' [PROOF STEP] by(simp_all add: num_mod_den'_def num'_def) [PROOF STATE] proof (state) this: root num_mod_den' = 0 left num_mod_den' = num' right num_mod_den' = num_mod_den' goal (1 subgoal): 1. tree_chop den = num + den - 2 * (num mod den) [PROOF STEP] have den'_eq_chop_num': "den' = tree_chop num'" [PROOF STATE] proof (prove) goal (1 subgoal): 1. den' = tree_chop num' [PROOF STEP] by(simp add: den'_def num'_def den_eq_chop_num) [PROOF STATE] proof (state) this: den' = tree_chop num' goal (1 subgoal): 1. tree_chop den = num + den - 2 * (num mod den) [PROOF STEP] have num_mod_den'2_unique: "\<And>x. x = Node 0 (2 * num') x \<Longrightarrow> x = 2 * num_mod_den'" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>x. x = Node 0 (2 * num') x \<Longrightarrow> x = 2 * num_mod_den' [PROOF STEP] by(corec_unique)(rule tree.expand; simp) [PROOF STATE] proof (state) this: ?x = Node 0 (2 * num') ?x \<Longrightarrow> ?x = 2 * num_mod_den' goal (1 subgoal): 1. tree_chop den = num + den - 2 * (num mod den) [PROOF STEP] have num'_plus_den'_minus_chop_den': "num' + den' - tree_chop den' = 2 * num_mod_den'" [PROOF STATE] proof (prove) goal (1 subgoal): 1. num' + den' - tree_chop den' = 2 * num_mod_den' [PROOF STEP] by(rule num_mod_den'2_unique)(rule tree.expand, simp add: tree_chop_plus den'_eq_chop_num') [PROOF STATE] proof (state) this: num' + den' - tree_chop den' = 2 * num_mod_den' goal (1 subgoal): 1. tree_chop den = num + den - 2 * (num mod den) [PROOF STEP] have "tree_chop den = pure nat \<diamondop> (tree_chop den')" [PROOF STATE] proof (prove) goal (1 subgoal): 1. tree_chop den = pure nat \<diamondop> tree_chop den' [PROOF STEP] unfolding den_conv tree_chop_ap_tree tree_chop_pure_tree den'_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. pure snd \<diamondop> tree_chop stern_brocot_recurse = pure nat \<diamondop> (pure int \<diamondop> (pure snd \<diamondop> tree_chop stern_brocot_recurse)) [PROOF STEP] by applicative_nf simp [PROOF STATE] proof (state) this: tree_chop den = pure nat \<diamondop> tree_chop den' goal (1 subgoal): 1. tree_chop den = num + den - 2 * (num mod den) [PROOF STEP] also [PROOF STATE] proof (state) this: tree_chop den = pure nat \<diamondop> tree_chop den' goal (1 subgoal): 1. tree_chop den = num + den - 2 * (num mod den) [PROOF STEP] have "tree_chop den' = num' + den' - tree_chop den' + tree_chop den' - 2 * num_mod_den'" [PROOF STATE] proof (prove) goal (1 subgoal): 1. tree_chop den' = num' + den' - tree_chop den' + tree_chop den' - 2 * num_mod_den' [PROOF STEP] by(subst num'_plus_den'_minus_chop_den') simp [PROOF STATE] proof (state) this: tree_chop den' = num' + den' - tree_chop den' + tree_chop den' - 2 * num_mod_den' goal (1 subgoal): 1. tree_chop den = num + den - 2 * (num mod den) [PROOF STEP] also [PROOF STATE] proof (state) this: tree_chop den' = num' + den' - tree_chop den' + tree_chop den' - 2 * num_mod_den' goal (1 subgoal): 1. tree_chop den = num + den - 2 * (num mod den) [PROOF STEP] have "\<dots> = num' + den' - 2 * (num' mod den')" [PROOF STATE] proof (prove) goal (1 subgoal): 1. num' + den' - tree_chop den' + tree_chop den' - 2 * num_mod_den' = num' + den' - 2 * (num' mod den') [PROOF STEP] unfolding num_mod_den'_def num'_def den'_def num_mod_den[symmetric] [PROOF STATE] proof (prove) goal (1 subgoal): 1. pure int \<diamondop> num + pure int \<diamondop> den - tree_chop (pure int \<diamondop> den) + tree_chop (pure int \<diamondop> den) - 2 * (pure int \<diamondop> (num mod den)) = pure int \<diamondop> num + pure int \<diamondop> den - 2 * (pure int \<diamondop> num mod (pure int \<diamondop> den)) [PROOF STEP] by applicative_lifting(simp add: zmod_int) [PROOF STATE] proof (state) this: num' + den' - tree_chop den' + tree_chop den' - 2 * num_mod_den' = num' + den' - 2 * (num' mod den') goal (1 subgoal): 1. tree_chop den = num + den - 2 * (num mod den) [PROOF STEP] also [PROOF STATE] proof (state) this: num' + den' - tree_chop den' + tree_chop den' - 2 * num_mod_den' = num' + den' - 2 * (num' mod den') goal (1 subgoal): 1. tree_chop den = num + den - 2 * (num mod den) [PROOF STEP] have [unfolded tree.rel_eq]: "rel_tree (=) \<dots> (pure int \<diamondop> (num + den - 2 * (num mod den)))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. rel_tree (=) (num' + den' - 2 * (num' mod den')) (pure int \<diamondop> (num + den - 2 * (num mod den))) [PROOF STEP] unfolding num'_def den'_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. rel_tree (=) (pure int \<diamondop> num + pure int \<diamondop> den - 2 * (pure int \<diamondop> num mod (pure int \<diamondop> den))) (pure int \<diamondop> (num + den - 2 * (num mod den))) [PROOF STEP] by(applicative_lifting)(simp add: of_nat_diff zmod_int le den_gt_0) [PROOF STATE] proof (state) this: num' + den' - 2 * (num' mod den') = pure int \<diamondop> (num + den - 2 * (num mod den)) goal (1 subgoal): 1. tree_chop den = num + den - 2 * (num mod den) [PROOF STEP] also [PROOF STATE] proof (state) this: num' + den' - 2 * (num' mod den') = pure int \<diamondop> (num + den - 2 * (num mod den)) goal (1 subgoal): 1. tree_chop den = num + den - 2 * (num mod den) [PROOF STEP] have "pure nat \<diamondop> (pure int \<diamondop> (num + den - 2 * (num mod den))) = num + den - 2 * (num mod den)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. pure nat \<diamondop> (pure int \<diamondop> (num + den - 2 * (num mod den))) = num + den - 2 * (num mod den) [PROOF STEP] by(applicative_nf) simp [PROOF STATE] proof (state) this: pure nat \<diamondop> (pure int \<diamondop> (num + den - 2 * (num mod den))) = num + den - 2 * (num mod den) goal (1 subgoal): 1. tree_chop den = num + den - 2 * (num mod den) [PROOF STEP] finally [PROOF STATE] proof (chain) picking this: tree_chop den = num + den - 2 * (num mod den) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: tree_chop den = num + den - 2 * (num mod den) goal (1 subgoal): 1. tree_chop den = num + den - 2 * (num mod den) [PROOF STEP] . [PROOF STATE] proof (state) this: tree_chop den = num + den - 2 * (num mod den) goal: No subgoals! [PROOF STEP] qed
from __future__ import print_function import numpy as np import os import scipy.misc as misc import tensorflow as tf beijing = [0,0,0] yuanzhuxiechilunzhou = [239,235,143] zhou = [243,0,193] yuanzhuxiechilun = [100,50,100] xiangti = [255,0,0] zhouchengduangai = [194,243,0] guayouban = [64,191,175] taotong = [0,243,97] wolun = [96,255,223] wogan = [43,0,215] luoshuan= [96,128,255] xiangjiaoquan = [0,188,0] zhoucheng = [243,113,165] yuanzhuixiechilun = [13,113,243] zhoutao = [188,75,0] yuanzhuzhichichilunzhou = [255,159,15] yuanzhuzhichilun = [0,0,243] classes = [ '箱体', '圆柱直齿轮', '轴承', '轴承端盖', '轴', '圆柱直齿齿轮轴', '圆锥斜齿轮', '轴套', '橡胶圈', '圆柱斜齿轮', '螺栓', '套筒', '蜗杆', '蜗轮', '刮油板', '圆柱斜齿轮轴','background'] colormap = [[255,0,0], [0, 0, 243], [243, 113, 165], [194, 243, 0], [243, 0, 193], [255, 159, 15], [13, 113, 243], [188, 75, 0], [0, 188, 0], [100, 50, 100], [96, 128, 255], [0, 243, 97], [43, 0, 215], [96, 255, 223], [64, 191, 175], [239, 235, 143],[0, 0, 0]] COLOR_DICT = np.array([[255,0,0], [0, 0, 243], [243, 113, 165], [194, 243, 0], [243, 0, 193], [255, 159, 15], [13, 113, 243], [188, 75, 0], [0, 188, 0], [100, 50, 100], [96, 128, 255], [0, 243, 97], [43, 0, 215], [96, 255, 223], [64, 191, 175], [239, 235, 143],[0, 0, 0]]) def labelVisualize(num_class,color_dict,img): img_out = np.zeros(img.shape + (3,)) for i in range(num_class): img_out[img == i,:] = color_dict[i] return img_out def saveResult(save_path,item,flag_multi_class = True,num_class = 17,i= None): img = labelVisualize(num_class,COLOR_DICT,item) if flag_multi_class else item[:,:,0] misc.imsave(os.path.join(save_path,"%d_predict.png" % i), img)
Both the managing partners and our in-house language team are trained and qualified translators with many years of professional experience and specialist knowledge of the localization industry. We work constantly to improve our processes and our effectiveness in order to achieve the best results. We are rewarded for the high standards we demand of ourselves and our staff by a growing number of satisfied customers. LinguaPoint uses only technically qualified professionals translating into their mother tongue. A project manager assigned at the beginning of the project will remain your personal and sole contact throughout the entire project, paying scrupulous attention to budget and time frame. With our expert knowledge of your projects, our project manager can react quickly and flexibly to potential changes you may require, thereby ensuring that all your needs are met. We understand the consequences that delays can have on our clients' market share and bottom line. That's why we remain dedicated to a fast turnaround for our clients. Our motto: "On time, every time". Excellent project management is the secret of localization success. As a reliable and quality-oriented partner, we react quickly and flexibly in order to assure the success of your project. Fair and open relations as well as mutual respect characterize our working routine both within and outside our company. Our key areas of competence cover a wide range of other services, such as memory revision and alignment, compiling and testing, screenshot generation and graphics editing. LinguaPoint - your single source point for comprehensive services. All current computer-aided translation tools, word processing, and QA applications are available. We make sure that our customers get the full benefit of leading-edge technology.
{-# OPTIONS --without-K --safe #-} open import Definition.Typed.EqualityRelation module Definition.LogicalRelation.Substitution.Reflexivity {{eqrel : EqRelSet}} where open EqRelSet {{...}} open import Definition.LogicalRelation.Properties open import Definition.LogicalRelation.Substitution open import Definition.Untyped using (Con ; Term) open import Tools.Nat open import Tools.Product private variable n : Nat Γ : Con Term n -- Reflexivity of valid types. reflᵛ : ∀ {A l} ([Γ] : ⊩ᵛ Γ) ([A] : Γ ⊩ᵛ⟨ l ⟩ A / [Γ]) → Γ ⊩ᵛ⟨ l ⟩ A ≡ A / [Γ] / [A] reflᵛ [Γ] [A] ⊢Δ [σ] = reflEq (proj₁ ([A] ⊢Δ [σ])) -- Reflexivity of valid terms. reflᵗᵛ : ∀ {A t l} ([Γ] : ⊩ᵛ Γ) ([A] : Γ ⊩ᵛ⟨ l ⟩ A / [Γ]) ([t] : Γ ⊩ᵛ⟨ l ⟩ t ∷ A / [Γ] / [A]) → Γ ⊩ᵛ⟨ l ⟩ t ≡ t ∷ A / [Γ] / [A] reflᵗᵛ [Γ] [A] [t] ⊢Δ [σ] = reflEqTerm (proj₁ ([A] ⊢Δ [σ])) (proj₁ ([t] ⊢Δ [σ]))
(* Title: Instances of Schneider's generalized protocol of clock synchronization Author: Damián Barsotti <damian at hal.famaf.unc.edu.ar>, 2006 Maintainer: Damián Barsotti <damian at hal.famaf.unc.edu.ar> *) section \<open>Fault-tolerant Midpoint algorithm\<close> theory LynchInstance imports Complex_Main begin text \<open>This algorithm is presented in \<^cite>\<open>"lynch_cs"\<close>.\<close> subsection \<open>Model of the system\<close> text \<open>The main ideas for the formalization of the system were obtained from \<^cite>\<open>"shankar92mechanical"\<close>.\<close> subsubsection \<open>Types in the formalization\<close> text \<open>The election of the basics types was based on \<^cite>\<open>"shankar92mechanical"\<close>. There, the process are natural numbers and the real time and the clock readings are reals.\<close> type_synonym process = nat type_synonym time = real \<comment> \<open>real time\<close> type_synonym Clocktime = real \<comment> \<open>time of the clock readings (clock time)\<close> subsubsection \<open>Some constants\<close> text\<open>Here we define some parameters of the algorithm that we use: the number of process and the number of lowest and highest readed values that the algorithm discards. The defined constants must satisfy this axiom. If not, the algorithm cannot obtain the maximum and minimum value, because it will have discarded all the values.\<close> axiomatization np :: nat \<comment> \<open>Number of processes\<close> and khl :: nat \<comment> \<open>Number of lowest and highest values\<close> where constants_ax: "2 * khl < np" text \<open>We define also the set of process that the algorithm manage. This definition exist only for readability matters.\<close> definition PR :: "process set" where [simp]: "PR = {..<np}" subsubsection \<open>Convergence function\<close> text \<open>This functions is called ``Fault-tolerant Midpoint'' (\<^cite>\<open>"schneider87understanding"\<close>)\<close> text \<open>In this algorithm each process has an array where it store the clocks readings from the others processes (including itself). We formalise that as a function from processes to clock time as \<^cite>\<open>"shankar92mechanical"\<close>.\<close> text \<open>First we define two functions. They take a function of clock readings and a set of processes and they return a set of @{term khl} processes which has the greater (smaller) clock readings. They were defined with the Hilbert's $\varepsilon$-operator (the indefinite description operator \<open>SOME\<close> in Isabelle) because in this way the formalization is not fixed to a particular eleccion of the processes's readings to discards and then the modelization is more general.\<close> definition kmax :: "(process \<Rightarrow> Clocktime) \<Rightarrow> process set \<Rightarrow> process set" where "kmax f P = (SOME S. S \<subseteq> P \<and> card S = khl \<and> (\<forall> i\<in>S. \<forall> j\<in>(P-S). f j <= f i))" definition kmin :: "(process \<Rightarrow> Clocktime) \<Rightarrow> process set \<Rightarrow> process set" where "kmin f P = (SOME S. S \<subseteq> P \<and> card S = khl \<and> (\<forall> i\<in>S. \<forall> j\<in>(P-S). f i <= f j))" text \<open>With the previus functions we define a new one @{term reduce}\footnote{The name of this function was taken from \<^cite>\<open>"lynch_cs"\<close>.}. This take a function of clock readings and a set of processes and return de set of readings of the not dicarded processes. In order to define this function we use the image operator (@{term "(`)"}) of Isabelle.\<close> definition reduce :: "(process \<Rightarrow> Clocktime) \<Rightarrow> process set \<Rightarrow> Clocktime set" where "reduce f P = f ` (P - (kmax f P \<union> kmin f P))" text \<open>And finally the convergence function. This is defined with the builtin @{term Max} and @{term Min} functions of Isabelle. \<close> definition cfnl :: "process \<Rightarrow> (process \<Rightarrow> Clocktime) \<Rightarrow> Clocktime" where "cfnl p f = (Max (reduce f PR) + Min (reduce f PR)) / 2" subsection \<open>Translation Invariance property.\<close> subsubsection \<open>Auxiliary lemmas\<close> text \<open>These lemmas proves the existence of the maximum and minimum of the image of a set, if the set is finite and not empty.\<close> (* The proofs are almost the same one that those of the lemmas @{thm *) (* [source] ex_Max} and @{thm [source] ex_Min} in the Isabelle's standard *) (* theories. *) lemma ex_Maxf: fixes S and f :: "'a \<Rightarrow> ('b::linorder)" assumes fin: "finite S" shows "S \<noteq> {} ==> \<exists>m\<in>S. \<forall>s \<in> S. f s \<le> f m" using fin proof (induct) case empty thus ?case by simp next case (insert x S) show ?case proof (cases) assume "S = {}" thus ?thesis by simp next assume nonempty: "S \<noteq> {}" then obtain m where m: "m\<in>S" "\<forall>s\<in>S. f s \<le> f m" using insert by blast show ?thesis proof (cases) assume "f x \<le> f m" thus ?thesis using m by blast next assume "~ f x \<le> f m" thus ?thesis using m by(simp add:linorder_not_le order_less_le) (blast intro: order_trans) qed qed qed lemma ex_Minf: fixes S and f :: "'a \<Rightarrow> ('b::linorder)" assumes fin: "finite S" shows "S \<noteq> {} ==> \<exists>m\<in>S. \<forall>s \<in> S. f m \<le> f s" using fin proof (induct) case empty thus ?case by simp next case (insert x S) show ?case proof (cases) assume "S = {}" thus ?thesis by simp next assume nonempty: "S \<noteq> {}" then obtain m where m: "m\<in>S" "\<forall>s\<in>S. f m \<le> f s" using insert by blast show ?thesis proof (cases) assume "f m \<le> f x" thus ?thesis using m by blast next assume "~ f m \<le> f x" thus ?thesis using m by(simp add:linorder_not_le order_less_le) (blast intro: order_trans) qed qed qed text \<open>This trivial lemma is needed by the next two.\<close> lemma khl_bound: "khl < np" using constants_ax by arith text \<open>The next two lemmas prove that de functions kmin and kmax return some values that satisfy their definition. This is not trivial because we need to prove the existence of these values, according to the rule of the Hilbert's operator. We will need this lemma many times because is the only thing that we know about these functions.\<close> lemma kmax_prop: fixes f :: "nat \<Rightarrow> Clocktime" shows "(kmax f PR) \<subseteq> PR \<and> card (kmax f PR) = khl \<and> (\<forall>i\<in>(kmax f PR). \<forall>j\<in>PR - (kmax f PR). f j \<le> f i)" proof- have "khl <= np \<longrightarrow> (\<exists> S. S \<subseteq> PR \<and> card S = khl \<and> (\<forall>i\<in>S. \<forall>j\<in>PR - S. f j \<le> f i))" ( is "khl <= np \<longrightarrow> ?P khl" ) proof(induct (khl)) have "?P 0" by force thus "0 <= np \<longrightarrow> ?P 0" .. next fix n assume asm: "n <= np \<longrightarrow> ?P n" show "Suc n <= np \<longrightarrow> ?P (Suc n)" proof assume asm2: "Suc n <= np" with asm have "?P n" by simp then obtain S where SinPR : "S\<subseteq>PR" and cardS: "card S = n" and HI: "(\<forall>i\<in>S. \<forall>j\<in>PR - S. f j \<le> f i)" by blast let ?e = "SOME i. i\<in>PR-S \<and> (\<forall>j\<in>PR-S. f j \<le> f i)" let ?S = "insert ?e S" have "\<exists>i. i\<in>PR-S \<and> (\<forall>j\<in>PR-S. f j \<le> f i)" proof- from SinPR and finite_subset have "finite (PR-S)" by auto moreover from cardS and asm2 SinPR have "S\<subset>PR" by auto hence "PR-S \<noteq> {}" by auto ultimately show ?thesis using ex_Maxf by blast qed hence ePRS: "?e \<in> PR-S" and maxH: "(\<forall>j \<in> PR-S. f j \<le> f ?e)" by (auto dest!: someI_ex) from maxH and HI have "(\<forall>i\<in>?S. \<forall>j\<in>PR - ?S. f j \<le> f i)" by blast moreover from SinPR and finite_subset cardS and ePRS have "card ?S = Suc n" by (auto dest: card_insert_disjoint) moreover have "?S \<subseteq> PR" using SinPR and ePRS by auto ultimately show "?P (Suc n)" by blast qed qed hence "?P khl" using khl_bound by auto then obtain S where "S\<le>PR \<and> card S = khl \<and> (\<forall>i\<in>S. \<forall>j\<in>PR - S. f j \<le> f i)" .. thus ?thesis by (unfold kmax_def) (rule someI [where P="\<lambda>S. S \<subseteq> PR \<and> card S = khl \<and> (\<forall>i\<in>S. \<forall>j\<in>PR - S. f j \<le> f i)"]) qed lemma kmin_prop: fixes f :: "nat \<Rightarrow> Clocktime" shows "(kmin f PR) \<subseteq> PR \<and> card (kmin f PR) = khl \<and> (\<forall>i\<in>(kmin f PR). \<forall>j\<in>PR - (kmin f PR). f i \<le> f j)" proof- have "khl <= np \<longrightarrow> (\<exists> S. S \<subseteq> PR \<and> card S = khl \<and> (\<forall>i\<in>S. \<forall>j\<in>PR - S. f i \<le> f j))" ( is "khl <= np \<longrightarrow> ?P khl" ) proof(induct (khl)) have "?P 0" by force thus "0 <= np \<longrightarrow> ?P 0" .. next fix n assume asm: "n <= np \<longrightarrow> ?P n" show "Suc n <= np \<longrightarrow> ?P (Suc n)" proof assume asm2: "Suc n <= np" with asm have "?P n" by simp then obtain S where SinPR : "S\<subseteq>PR" and cardS: "card S = n" and HI: "(\<forall>i\<in>S. \<forall>j\<in>PR - S. f i \<le> f j)" by blast let ?e = "SOME i. i\<in>PR-S \<and> (\<forall>j\<in>PR-S. f i \<le> f j)" let ?S = "insert ?e S" have "\<exists>i. i\<in>PR-S \<and> (\<forall>j\<in>PR-S. f i \<le> f j)" proof- from SinPR and finite_subset have "finite (PR-S)" by auto moreover from cardS and asm2 SinPR have "S\<subset>PR" by auto hence "PR-S \<noteq> {}" by auto ultimately show ?thesis using ex_Minf by blast qed hence ePRS: "?e \<in> PR-S" and minH: "(\<forall>j \<in> PR-S. f ?e \<le> f j)" by (auto dest!: someI_ex) from minH and HI have "(\<forall>i\<in>?S. \<forall>j\<in>PR - ?S. f i \<le> f j)" by blast moreover from SinPR and finite_subset and cardS and ePRS have "card ?S = Suc n" by (auto dest: card_insert_disjoint) moreover have "?S \<subseteq> PR" using SinPR and ePRS by auto ultimately show "?P (Suc n)" by blast qed qed hence "?P khl" using khl_bound by auto then obtain S where "S\<le>PR \<and> card S = khl \<and> (\<forall>i\<in>S. \<forall>j\<in>PR - S. f i \<le> f j)" .. thus ?thesis by (unfold kmin_def) (rule someI [where P="\<lambda>S. S \<subseteq> PR \<and> card S = khl \<and> (\<forall>i\<in>S. \<forall>j\<in>PR - S. f i \<le> f j)"]) qed text \<open>The next two lemmas are trivial from the previous ones\<close> lemma finite_kmax: "finite (kmax f PR)" proof- have "finite PR" by auto with kmax_prop and finite_subset show ?thesis by blast qed lemma finite_kmin: "finite (kmin f PR)" proof- have "finite PR" by auto with kmin_prop and finite_subset show ?thesis by blast qed text \<open>This lemma is necesary because the definition of the convergence function use the builtin Max and Min.\<close> lemma reduce_not_empty: "reduce f PR \<noteq> {}" proof- from constants_ax have "0 < (np - 2 * khl)" by arith also { from kmax_prop kmin_prop have "card (kmax f PR) = khl \<and> card (kmin f PR) = khl" by blast hence "card (kmax f PR \<union> kmin f PR) <= 2 * khl" using card_Un_le[of "kmax f PR" "kmin f PR"] by simp } hence "... <= card PR - card (kmax f PR \<union> kmin f PR)" by simp also { from kmax_prop and kmin_prop have "(kmax f PR \<union> kmin f PR) \<subseteq> PR" by blast } hence "... = card (PR-(kmax f PR \<union> kmin f PR))" apply (intro card_Diff_subset[THEN sym]) apply (rule finite_subset) by auto (* by (intro card_Diff_subset,auto) *) finally have "0 < card (PR-(kmax f PR \<union> kmin f PR))" . hence "(PR-(kmax f PR \<union> kmin f PR)) \<noteq> {}" by (intro notI, simp only: card_0_eq, simp) thus ?thesis by (auto simp add: reduce_def) qed text \<open>The next three are the main lemmas necessary for prove the Translation Invariance property.\<close> lemma reduce_shift: fixes f :: "nat \<Rightarrow> Clocktime" shows "f ` (PR - (kmax f PR \<union> kmin f PR)) = f ` (PR - (kmax (\<lambda> p. f p + c) PR \<union> kmin (\<lambda> p. f p + c) PR))" apply (unfold kmin_def kmax_def) by simp lemma max_shift: fixes f :: "nat \<Rightarrow> Clocktime" and S assumes notEmpFin: "S \<noteq> {}" "finite S" shows "Max (f`S) + x = Max ( (\<lambda> p. f p + x) ` S) " proof- from notEmpFin have "f`S \<noteq> {}" and "(\<lambda> p. f p + x) ` S \<noteq> {}" by auto with notEmpFin have "Max (f`S) \<in> f ` S " "Max ((\<lambda> p. f p + x)`S) \<in> (\<lambda> p. f p + x) ` S " "(\<forall>fs \<in> (f`S). fs \<le> Max (f`S))" "(\<forall>fs \<in> ((\<lambda> p. f p + x)`S). fs \<le> Max ((\<lambda> p. f p + x)`S))" by auto thus ?thesis by force qed lemma min_shift: fixes f :: "nat \<Rightarrow> Clocktime" and S assumes notEmpFin: "S \<noteq> {}" "finite S" shows "Min (f`S) + x = Min ( (\<lambda> p. f p + x) ` S) " proof- from notEmpFin have "f`S \<noteq> {}" and "(\<lambda> p. f p + x) ` S \<noteq> {}" by auto with notEmpFin have "Min (f`S) \<in> f ` S " "Min ((\<lambda> p. f p + x)`S) \<in> (\<lambda> p. f p + x) ` S " "(\<forall>fs \<in> (f`S). Min (f`S) <= fs)" "(\<forall>fs \<in> ((\<lambda> p. f p + x)`S). Min ((\<lambda> p. f p + x)`S) <= fs)" by auto thus ?thesis by force qed subsubsection \<open>Main theorem\<close> theorem trans_inv: fixes f :: "nat \<Rightarrow> Clocktime" shows "cfnl p f + x = cfnl p (\<lambda> p. f p + x)" proof- have "cfnl p (\<lambda> p. f p + x) = (Max (reduce (\<lambda> p. f p + x) PR) + Min (reduce (\<lambda> p. f p + x) PR)) / 2" by (unfold cfnl_def, simp) also have "... = (Max ((\<lambda> p. f p + x) ` (PR - (kmax (\<lambda> p. f p + x) PR \<union> kmin (\<lambda> p. f p + x) PR))) + Min ((\<lambda> p. f p + x) ` (PR - (kmax (\<lambda> p. f p + x) PR \<union> kmin (\<lambda> p. f p + x) PR)))) / 2" by (unfold reduce_def, simp) also have "... = (Max (f ` (PR - (kmax (\<lambda> p. f p + x) PR \<union> kmin (\<lambda> p. f p + x) PR))) + x + Min (f ` (PR - (kmax (\<lambda> p. f p + x) PR \<union> kmin (\<lambda> p. f p + x) PR))) + x ) / 2" proof- have "finite (PR - (kmax (\<lambda> p. f p + x) PR \<union> kmin (\<lambda> p. f p + x) PR))" by auto moreover from reduce_not_empty have "PR - (kmax (\<lambda> p. f p + x) PR \<union> kmin (\<lambda> p. f p + x) PR) \<noteq> {}" by (auto simp add: reduce_def) ultimately have "Max ((\<lambda> p. f p + x) ` (PR - (kmax (\<lambda> p. f p + x) PR \<union> kmin (\<lambda> p. f p + x) PR))) = Max (f ` (PR - (kmax (\<lambda> p. f p + x) PR \<union> kmin (\<lambda> p. f p + x) PR))) + x" and "Min ((\<lambda> p. f p + x) ` (PR - (kmax (\<lambda> p. f p + x) PR \<union> kmin (\<lambda> p. f p + x) PR))) = Min (f ` (PR - (kmax (\<lambda> p. f p + x) PR \<union> kmin (\<lambda> p. f p + x) PR))) + x" using max_shift and min_shift by auto thus ?thesis by auto qed also from reduce_shift have "... = (Max (f ` (PR - (kmax f PR \<union> kmin f PR))) + x + Min (f ` (PR - (kmax f PR \<union> kmin f PR))) + x ) / 2" by auto also have "... = ((Max (reduce f PR)+ x) + (Min (reduce f PR) + x)) / 2" by (auto simp add: reduce_def) also have "... = (Max (reduce f PR) + Min (reduce f PR)) / 2 + x" by auto finally show ?thesis by (auto simp add: cfnl_def) qed subsection \<open>Precision Enhancement property\<close> text \<open>An informal proof of this theorem can be found in \<^cite>\<open>"miner93"\<close>\<close> subsubsection \<open>Auxiliary lemmas\<close> text \<open>This first lemma is most important for prove the property. This is a consecuence of the @{thm [source] card_Un_Int} lemma\<close> lemma pigeonhole: assumes finitA: "finite A" and Bss: "B \<subseteq> A" and Css: "C \<subseteq> A" and cardH: "card A + k <= card B + card C" shows "k <= card (B \<inter> C)" proof- from Bss Css have "B \<union> C \<subseteq> A" by blast with finitA have "card (B \<union> C) <= card A" by (simp add: card_mono) with cardH have h: "k <= card B + card C - card (B \<union> C)" by arith from finitA Bss Css and finite_subset have "finite B \<and> finite C" by auto thus ?thesis using card_Un_Int and h by force qed text \<open>This lemma is a trivial consecuence of the previous one. With only this lemma we can prove the Precision Enhancement property with the bound $\pi(x,y) = x + y$. But this bound not satisfy the property \[ \pi(2\Lambda + 2 \beta\rho, \delta_S + 2\rho(r_{max}+\beta) + 2\Lambda) \leq \delta_S \] that is used in \<^cite>\<open>"shankar92mechanical"\<close> for prove the Schneider's schema.\<close> lemma subsets_int: assumes finitA: "finite A" and Bss: "B \<subseteq> A" and Css: "C \<subseteq> A" and cardH: "card A < card B + card C" shows "B \<inter> C \<noteq> {}" proof- from finitA Bss Css cardH have "1 <= card (B \<inter> C)" by (auto intro!: pigeonhole) thus ?thesis by auto qed text \<open>This lemma is true because @{term "reduce f PR"} is the image of @{term "PR-(kmax f PR \<union> kmin f PR)"} by the function @{term f}.\<close> lemma exist_reduce: "\<forall> c \<in> reduce f PR. \<exists> i\<in> PR-(kmax f PR \<union> kmin f PR). f i = c" proof fix c assume asm: "c \<in> reduce f PR" thus "\<exists> i\<in> PR-(kmax f PR \<union> kmin f PR). f i = c" by (auto simp add: reduce_def kmax_def kmin_def) qed text \<open>The next three lemmas are consequence of the definition of @{term reduce}, @{term kmax} and @{term kmin}\<close> lemma finite_reduce: "finite (reduce f PR)" proof(unfold reduce_def) show "finite (f ` (PR - (kmax f PR \<union> kmin f PR)))" by auto qed lemma kmax_ge: "\<forall> i\<in> (kmax f PR). \<forall> r \<in> (reduce f PR). r <= f i " proof fix i assume asm: "i \<in> kmax f PR" show "\<forall>r\<in>reduce f PR. r \<le> f i" proof fix r assume asm2: "r \<in> reduce f PR" show "r \<le> f i" proof- from asm2 and exist_reduce have "\<exists> j \<in> PR-(kmax f PR \<union> kmin f PR). f j = r" by blast then obtain j where fjr:"j \<in> PR-(kmax f PR \<union> kmin f PR) \<and> f j = r" by blast hence "j \<in> (PR - kmax f PR)" by blast from this fjr asm show ?thesis using kmax_prop by auto qed qed qed lemma kmin_le: "\<forall> i\<in> (kmin f PR). \<forall> r \<in> (reduce f PR). f i <= r " proof fix i assume asm: "i \<in> kmin f PR" show "\<forall>r\<in>reduce f PR. f i \<le> r" proof fix r assume asm2: "r \<in> reduce f PR" show "f i <= r" proof- from asm2 and exist_reduce have "\<exists> j\<in> PR-(kmax f PR \<union> kmin f PR). f j = r" by blast then obtain j where fjr:"j \<in> PR-(kmax f PR \<union> kmin f PR) \<and> f j = r" by blast hence "j \<in> (PR - kmin f PR)" by blast from this fjr asm show ?thesis using kmin_prop by auto qed qed qed text \<open>The next lemma is used for prove the Precision Enhancement property. This has been proved in ICS. The proof is in the appendix \ref{sec:abs_distrib_mult}. This cannot be prove by a simple \<open>arith\<close> or \<open>auto\<close> tactic.\<close> text\<open>This lemma is true also with \<open>0 <= c\<close> !!\<close> lemma abs_distrib_div: "0 < (c::real) \<Longrightarrow> \<bar>a / c - b / c\<bar> = \<bar>a - b\<bar> / c" proof- assume ch: "0<c" { fix d :: real assume dh: "0<=d" have "a * d - b * d = (a - b) * d " by (simp add: algebra_simps) hence "\<bar>a * d - b * d\<bar> = \<bar>(a - b) * d\<bar>" by simp also with dh have "... = \<bar>a - b\<bar> * d" by (simp add: abs_mult) finally have "\<bar>a * d - b * d\<bar> = \<bar>a - b\<bar> * d" . (* This sublemma is solved by ICS, file: abs_distrib_mult.ics *) (* It is not solved nor by (auto simp add: distrib_right diff_minus)(arith) in Isabelle *) } with ch and divide_inverse show ?thesis by (auto simp add: divide_inverse) qed text \<open>The next three lemmas are about the existence of bounds of the values @{term "Max (reduce f PR)"} and @{term "Min (reduce f PR)"}. These are used in the proof of the main property.\<close> lemma uboundmax: assumes hC: "C \<subseteq> PR" and hCk: "np <= card C + khl" shows "\<exists> i\<in>C. Max (reduce f PR) <= f i" proof- from reduce_not_empty and finite_reduce have maxrinr: "Max (reduce f PR) \<in> reduce f PR" by simp with exist_reduce have "\<exists> i\<in> PR-(kmax f PR \<union> kmin f PR). f i = Max (reduce f PR)" by simp then obtain pmax where pmax_in_reduc: "pmax \<in> PR-(kmax f PR \<union> kmin f PR)" and fpmax_ismax: "f pmax = Max (reduce f PR)" .. hence "C \<inter> insert pmax (kmax f PR) \<noteq> {}" proof- from kmax_prop and pmax_in_reduc and finite_kmax and hCk have "card PR < card C + card (insert pmax (kmax f PR))" by simp moreover from pmax_in_reduc and kmax_prop have "insert pmax (kmax f PR) \<subseteq> PR" by blast moreover note hC ultimately show ?thesis using subsets_int[of PR C "insert pmax (kmax f PR)"] by simp qed hence res: "\<exists> i\<in>C. i=pmax \<or> i \<in> kmax f PR" by blast then obtain i where iinC: "i\<in>C" and altern: "i=pmax \<or> i \<in> kmax f PR" .. thus ?thesis proof(cases "i=pmax") case True with iinC fpmax_ismax show ?thesis by force next case False with altern maxrinr fpmax_ismax kmax_ge have "f pmax <= f i" by simp with iinC fpmax_ismax show ?thesis by auto qed qed lemma lboundmin: assumes hC: "C \<subseteq> PR" and hCk: "np <= card C + khl" shows "\<exists> i\<in>C. f i <= Min (reduce f PR)" proof- from reduce_not_empty and finite_reduce have minrinr: "Min (reduce f PR) \<in> reduce f PR" by simp with exist_reduce have "\<exists> i\<in> PR-(kmax f PR \<union> kmin f PR). f i = Min (reduce f PR)" by simp then obtain pmin where pmin_in_reduc: "pmin \<in> PR-(kmax f PR \<union> kmin f PR)" and fpmin_ismin: "f pmin = Min (reduce f PR)" .. hence "C \<inter> insert pmin (kmin f PR) \<noteq> {}" proof- from kmin_prop and pmin_in_reduc and finite_kmin and hCk have "card PR < card C + card (insert pmin (kmin f PR))" by simp moreover from pmin_in_reduc and kmin_prop have "insert pmin (kmin f PR) \<subseteq> PR" by blast moreover note hC ultimately show ?thesis using subsets_int[of PR C "insert pmin (kmin f PR)"] by simp qed hence res: "\<exists> i\<in>C. i=pmin \<or> i \<in> kmin f PR" by blast then obtain i where iinC: "i\<in>C" and altern: "i=pmin \<or> i \<in> kmin f PR" .. thus ?thesis proof(cases "i=pmin") case True with iinC fpmin_ismin show ?thesis by force next case False with altern minrinr fpmin_ismin kmin_le have "f i <= f pmin" by simp with iinC fpmin_ismin show ?thesis by auto qed qed lemma same_bound: assumes hC: "C \<subseteq> PR" and hCk: "np <= card C + khl" and hnk: "3 * khl < np" shows "\<exists> i\<in>C. Min (reduce f PR) <= f i \<and> g i <= Max (reduce g PR) " proof- have b1: "khl + 1 <= card (C \<inter> (PR - kmin f PR))" proof(rule pigeonhole) show "finite PR" by simp next show "C \<subseteq> PR" by fact next show "PR - kmin f PR \<subseteq> PR" by blast next show "card PR + (khl + 1) \<le> card C + card (PR - kmin f PR)" proof- from hnk and hCk have "np + khl < np + card C - khl" by arith also from kmin_prop have "... = np + card C - card (kmin f PR)" by auto also have "... = card C + (card PR - card (kmin f PR))" proof- from kmin_prop have "card (kmin f PR) <= card PR" by (intro card_mono, auto) thus ?thesis by (simp) qed also from kmin_prop have "... = card C + card (PR - kmin f PR)" proof- from kmin_prop and finite_kmin have "card PR - card (kmin f PR) = card (PR - kmin f PR)" by (intro card_Diff_subset[THEN sym])(auto) thus ?thesis by auto qed finally show ?thesis by (simp) qed qed have "C \<inter> (PR - kmin f PR) \<inter> (PR - kmax g PR) \<noteq> {}" proof(intro subsets_int) show "finite PR" by simp next show "C \<inter> (PR - kmin f PR) \<subseteq> PR" by blast next show "PR - kmax g PR \<subseteq> PR" by blast next show "card PR < card (C \<inter> (PR - kmin f PR)) + card (PR - kmax g PR)" proof- from kmax_prop and finite_kmax have "card (PR - kmax g PR)= card PR - card (kmax g PR) " by (intro card_Diff_subset, auto) with kmax_prop have "card (PR - kmax g PR) = card PR - khl" by simp with b1 show ?thesis by arith qed qed hence "\<exists> i. i \<in> C \<and> i \<in> (PR - kmin f PR) \<and> i \<in> (PR - kmax g PR)" by blast then obtain i where in_C: "i \<in> C" and not_in_kmin: "i \<in> (PR - kmin f PR)" and not_in_kmax: "i \<in> (PR - kmax g PR)" by blast have "Min (reduce f PR) <= f i" proof(cases "i \<in> kmax f PR") case True from reduce_not_empty and finite_reduce have " Min (reduce f PR) \<in> reduce f PR" by auto with True show ?thesis using kmax_ge by blast next case False with not_in_kmin have "i \<in> PR - (kmax f PR \<union> kmin f PR)" by blast with reduce_def have "f i \<in> reduce f PR" by auto with reduce_not_empty and finite_reduce show ?thesis by auto qed moreover have "g i <= Max (reduce g PR)" proof(cases "i \<in> kmin g PR") case True from reduce_not_empty and finite_reduce have " Max (reduce g PR) \<in> reduce g PR" by auto with True show ?thesis using kmin_le by blast next case False with not_in_kmax have "i \<in> PR - (kmax g PR \<union> kmin g PR)" by blast with reduce_def have "g i \<in> reduce g PR" by auto with reduce_not_empty and finite_reduce show ?thesis by auto qed moreover note in_C ultimately show ?thesis by blast qed subsubsection \<open>Main theorem\<close> text \<open>The most part of this theorem can be proved with CVC-lite using the three previous lemmas (appendix \ref{sec:bound_prec_enh}).\<close> theorem prec_enh: assumes hC: "C \<subseteq> PR" and hCF: "np - nF <= card C" and hFn: "3 * nF < np" and hFk: "nF = khl" and hbx: "\<forall> l\<in>C. \<bar>f l - g l\<bar> <= x" and hby1: "\<forall> l\<in>C. \<forall> m\<in>C. \<bar>f l - f m\<bar> <= y" and hby2: "\<forall> l\<in>C. \<forall> m\<in>C. \<bar>g l - g m\<bar> <= y" and hpC: "p\<in>C" and hqC: "q\<in>C" shows "\<bar> cfnl p f - cfnl q g \<bar> <= y / 2 + x" proof- from hCF and hFk have hCk: "np <= card C + khl" by arith from hFn and hFk have hnk: "3 * khl < np" by arith let ?maxf = "Max (reduce f PR)" and ?minf = "Min (reduce f PR)" and ?maxg = "Max (reduce g PR)" and ?ming = "Min (reduce g PR)" from abs_distrib_div have "\<bar>cfnl p f - cfnl q g\<bar> = \<bar>?maxf + ?minf + - ?maxg + - ?ming\<bar> / 2" by (unfold cfnl_def) simp moreover have "\<bar>?maxf + ?minf + - ?maxg + - ?ming\<bar> <= y + 2 * x" \<comment> \<open>The rest of the property can be proved by CVC-lite (see appendix \ref{sec:bound_prec_enh})\<close> proof ( cases "0 <= ?maxf + ?minf + - ?maxg + - ?ming") case True hence "\<bar>?maxf + ?minf + - ?maxg + - ?ming\<bar> = ?maxf + ?minf + - ?maxg + - ?ming" by arith moreover from uboundmax hC hCk obtain mxf where mxfinC: "mxf\<in>C" and maxf: "?maxf <= f mxf" by blast moreover from lboundmin hC hCk obtain mng where mnginC: "mng\<in>C" and ming: "g mng <= ?ming" by blast moreover from same_bound hC hCk hnk obtain mxn where mxninC: "mxn\<in>C" and mxnf: "?minf \<le> f mxn" and mxng: "g mxn \<le> ?maxg" by blast ultimately have "\<bar> ?maxf + ?minf + - ?maxg + - ?ming\<bar> <= (f mxf + - g mng) + (f mxn + - g mxn)" by arith also from mxninC hbx abs_le_D1 have "... <= (f mxf + - g mng) + x" by auto also have "... = (f mxf + - f mng ) + ( f mng + - g mng) + x" by arith also have "... <= y + ( f mng + - g mng) + x" proof- from mxfinC mnginC hby1 abs_le_D1 have "f mxf + - f mng <= y" by auto thus ?thesis by auto qed also from mnginC hbx abs_le_D1 have "... <= y + 2 * x" by auto finally show ?thesis . next case False hence "\<bar>?maxf + ?minf + - ?maxg + - ?ming\<bar> = ?maxg + ?ming + - ?maxf + - ?minf" by arith moreover from uboundmax hC hCk obtain mxg where mxginC: "mxg\<in>C" and maxg: "?maxg <= g mxg" by blast moreover from lboundmin hC hCk obtain mnf where mnfinC: "mnf\<in>C" and minf: "f mnf <= ?minf" by blast moreover from same_bound hC hCk hnk obtain mxn where mxninC: "mxn\<in>C" and mxnf: "?ming \<le> g mxn" and mxng: "f mxn \<le> ?maxf" by blast ultimately have "\<bar> ?maxf + ?minf + - ?maxg + - ?ming\<bar> <= (g mxg + - f mnf) + (g mxn + - f mxn)" by arith also from mxninC hbx have "... <= (g mxg + - f mnf) + x" by (auto dest!: abs_le_D2) also have "... = (g mxg + - g mnf ) + ( g mnf + - f mnf) + x" by arith also have "... <= y + ( g mnf + - f mnf) + x" proof- from mxginC mnfinC hby2 abs_le_D1 have "g mxg + - g mnf <= y" by auto thus ?thesis by auto qed also from mnfinC hbx have "... <= y + 2 * x" by (auto dest!: abs_le_D2) finally show ?thesis . qed ultimately show ?thesis by simp qed subsection \<open>Accuracy Preservation property\<close> text \<open>No new lemmas are needed for prove this property. The bound has been found using the lemmas @{thm [source] uboundmax} and @{thm [source] lboundmin}\<close> text \<open>This theorem can be proved with ICS and CVC-lite assuming those lemmas (see appendix \ref{sec:accur_pres}).\<close> theorem accur_pres: assumes hC: "C \<subseteq> PR" and hCF: "np - nF <= card C" and hFk: "nF = khl" and hby: "\<forall> l\<in>C. \<forall> m\<in>C. \<bar>f l - f m\<bar> <= y" and hqC: "q\<in>C" shows "\<bar> cfnl p f - f q \<bar> <= y" proof- from hCF and hFk have npleCk: "np <= card C + khl" by arith show ?thesis proof(cases "f q <= cfnl p f") case True from npleCk hC and uboundmax have "\<exists> i\<in>C. Max (reduce f PR) <= f i" by auto then obtain pi where hpiC: "pi \<in> C" and fpiGeMax: "Max (reduce f PR) <= f pi" by blast from reduce_not_empty have "Min (reduce f PR) <= Max (reduce f PR)" by (auto simp add: reduce_def) with fpiGeMax have cfnlLefpi: "cfnl p f <= f pi" by (auto simp add: cfnl_def) with True have "\<bar> cfnl p f - f q \<bar> <= \<bar> f pi - f q \<bar>" by arith with hpiC and hqC and hby show ?thesis by force next case False from npleCk hC and lboundmin have "\<exists> i\<in>C. f i <= Min (reduce f PR)" by auto then obtain qi where hqiC: "qi \<in> C" and fqiLeMax: "f qi <= Min (reduce f PR)" by blast from reduce_not_empty have "Min (reduce f PR) <= Max (reduce f PR)" by (auto simp add: reduce_def) with fqiLeMax have "f qi <= cfnl p f" by (auto simp add: cfnl_def) with False have "\<bar> cfnl p f - f q \<bar> <= \<bar> f qi - f q \<bar>" by arith with hqiC and hqC and hby show ?thesis by force qed qed end
(* Author: Mnacho Echenim, Université Grenoble Alpes *) theory Commuting_Hermitian imports Spectral_Theory_Complements Commuting_Hermitian_Misc "Projective_Measurements.Linear_Algebra_Complements" "Projective_Measurements.Projective_Measurements" begin section \<open>Additional results on block decompositions of matrices\<close> subsection \<open>Split block results\<close> lemma split_block_diag_carrier: assumes "D \<in> carrier_mat n n" and "a \<le> n" and "split_block D a a = (D1, D2, D3, D4)" shows "D1\<in> carrier_mat a a" "D4\<in> carrier_mat (n-a) (n-a)" proof - show "D1\<in> carrier_mat a a" using assms unfolding split_block_def by (metis Pair_inject mat_carrier) show "D4 \<in> carrier_mat (n-a) (n-a)" using assms unfolding split_block_def by (metis Pair_inject carrier_matD(1) carrier_matD(2) mat_carrier) qed lemma split_block_diagonal: assumes "diagonal_mat D" and "D \<in> carrier_mat n n" and "a \<le> n" and "split_block D a a = (D1, D2, D3, D4)" shows "diagonal_mat D1 \<and> diagonal_mat D4" unfolding diagonal_mat_def proof (intro allI conjI impI) have "D1 \<in> carrier_mat a a" using assms unfolding split_block_def Let_def by fastforce fix i j assume "i < dim_row D1" and "j < dim_col D1" and "i \<noteq> j" have "D1 $$ (i,j) = D $$(i,j)" using assms unfolding split_block_def Let_def using \<open>i < dim_row D1\<close> \<open>j < dim_col D1\<close> by fastforce also have "... = 0" using assms \<open>i \<noteq> j\<close> \<open>D1 \<in> carrier_mat a a\<close> \<open>i < dim_row D1\<close> \<open>j < dim_col D1\<close> unfolding diagonal_mat_def by fastforce finally show "D1 $$(i,j) = 0" . next have "D4 \<in> carrier_mat (n-a) (n-a)" using assms unfolding split_block_def Let_def by fastforce fix i j assume "i < dim_row D4" and "j < dim_col D4" and "i \<noteq> j" have "D4 $$ (i,j) = D $$(i + a,j + a)" using assms unfolding split_block_def Let_def using \<open>i < dim_row D4\<close> \<open>j < dim_col D4\<close> by fastforce also have "... = 0" using assms \<open>i \<noteq> j\<close> \<open>D4 \<in> carrier_mat (n-a) (n-a)\<close> \<open>i < dim_row D4\<close> \<open>j < dim_col D4\<close> unfolding diagonal_mat_def by fastforce finally show "D4 $$(i,j) = 0" . qed lemma split_block_times_diag_index: fixes B::"'a::comm_ring Matrix.mat" assumes "diagonal_mat D" and "D\<in> carrier_mat n n" and "B\<in> carrier_mat n n" and "a \<le> n" and "split_block B a a = (B1, B2, B3, B4)" and "split_block D a a = (D1, D2, D3, D4)" and "i < dim_row (D4 * B4)" and "j < dim_col (D4 * B4)" shows "(B4 * D4) $$ (i, j) = (B*D) $$ (i+a, j+a)" "(D4 * B4) $$ (i, j) = (D*B) $$ (i+a, j+a)" proof - have d4: "D4 \<in> carrier_mat (n-a) (n-a)" using assms split_block(4)[of D] by simp have b4: "B4 \<in> carrier_mat (n-a) (n-a)" using assms split_block(4)[of B] by simp have "diagonal_mat D4" using assms split_block_diagonal[of D] by blast have "i < n-a" using \<open>i < dim_row (D4 * B4)\<close> b4 d4 by simp have "j < n-a" using \<open>j < dim_col (D4 * B4)\<close> b4 d4 by simp have "(B4 * D4) $$ (i, j) = D4 $$ (j,j) * B4 $$ (i,j)" proof (rule diagonal_mat_mult_index') show "diagonal_mat D4" using \<open>diagonal_mat D4\<close> . show "B4 \<in> carrier_mat (n-a) (n-a)" using b4 . show "D4 \<in> carrier_mat (n - a) (n - a)" using d4 . show "i < n-a" using \<open>i < n-a\<close> . show "j < n-a" using \<open>j < n-a\<close> . qed also have "... = D $$ (j+a, j+a) * B $$ (i+a, j+a)" using assms \<open>i < n-a\<close> \<open>j < n-a\<close> unfolding split_block_def Let_def by fastforce also have "... = (B*D) $$ (i+a, j+a)" using diagonal_mat_mult_index' assms by (metis \<open>i < n - a\<close> \<open>j < n - a\<close> less_diff_conv) finally show "(B4 * D4) $$ (i, j) = (B*D) $$ (i+a, j+a)" . have "(D4 * B4) $$ (i, j) = D4 $$ (i,i) * B4 $$ (i,j)" using diagonal_mat_mult_index \<open>diagonal_mat D4\<close> \<open>i < n - a\<close> \<open>j < n - a\<close> b4 d4 by blast also have "... = D $$ (i+a, i+a) * B $$ (i+a, j+a)" using assms \<open>i < n-a\<close> \<open>j < n-a\<close> unfolding split_block_def Let_def by fastforce also have "... = (D*B) $$ (i+a, j+a)" using diagonal_mat_mult_index assms by (metis \<open>i < n - a\<close> \<open>j < n - a\<close> less_diff_conv) finally show "(D4 * B4) $$ (i, j) = (D*B) $$ (i+a, j+a)" . qed lemma split_block_commute_subblock: fixes B::"'a::comm_ring Matrix.mat" assumes "diagonal_mat D" and "D\<in> carrier_mat n n" and "B\<in> carrier_mat n n" and "a \<le> n" and "split_block B a a = (B1, B2, B3, B4)" and "split_block D a a = (D1, D2, D3, D4)" and "B * D = D * B" shows "B4 * D4 = D4 * B4" proof have d4: "D4 \<in> carrier_mat (n-a) (n-a)" using assms split_block(4)[of D] by simp have b4: "B4 \<in> carrier_mat (n-a) (n-a)" using assms split_block(4)[of B] by simp have "diagonal_mat D4" using assms split_block_diagonal[of D] by blast show "dim_row (B4 * D4) = dim_row (D4 * B4)" using d4 b4 by simp show "dim_col (B4 * D4) = dim_col (D4 * B4)" using d4 b4 by simp fix i j assume "i < dim_row (D4 * B4)" and "j < dim_col (D4 * B4)" have "(B4*D4) $$(i,j) = (B*D) $$(i+a, j+a)" using split_block_times_diag_index[of D n B a] assms \<open>i < dim_row (D4 * B4)\<close> \<open>j < dim_col (D4 * B4)\<close> by blast also have "... = (D*B) $$ (i+a, j+a)" using assms by simp also have "... = (D4*B4) $$ (i, j)" using split_block_times_diag_index[of D n B a] assms by (metis \<open>i < dim_row (D4 * B4)\<close> \<open>j < dim_col (D4 * B4)\<close>) finally show "(B4*D4) $$(i,j) = (D4*B4) $$ (i, j)" . qed lemma commute_diag_mat_zero_comp: fixes D::"'a::{field} Matrix.mat" assumes "diagonal_mat D" and "D\<in> carrier_mat n n" and "B\<in> carrier_mat n n" and" B* D = D * B" and "i < n" and "j < n" and "D$$(i,i) \<noteq> D$$(j,j)" shows "B $$(i,j) = 0" proof - have "B$$(i,j) * D$$(j,j) = (B*D) $$(i,j)" using diagonal_mat_mult_index'[of B n D] assms by simp also have "... = (D*B) $$ (i,j)" using assms by simp also have "... = B$$(i,j) * D$$(i,i)" using diagonal_mat_mult_index assms by (metis Groups.mult_ac(2)) finally have "B$$(i,j) * D$$(j,j) = B$$(i,j) * D$$(i,i)" . hence "B$$(i,j) * (D$$(j,j) - D$$(i,i)) = 0" by auto thus "B$$(i,j) = 0" using assms by simp qed lemma commute_diag_mat_split_block: fixes D::"'a::{field} Matrix.mat" assumes "diagonal_mat D" and "D\<in> carrier_mat n n" and "B\<in> carrier_mat n n" and" B* D = D * B" and "k \<le> n" and "\<forall>i j. (i < k \<and> k \<le> j \<and> j < n) \<longrightarrow> D$$(i,i) \<noteq> D$$(j,j)" and "(B1, B2, B3, B4) = split_block B k k" shows "B2 = 0\<^sub>m k (n-k)" "B3 = 0\<^sub>m (n-k) k" proof (intro eq_matI) show "dim_row B2 = dim_row (0\<^sub>m k (n - k))" using assms unfolding split_block_def Let_def by simp show "dim_col B2 = dim_col (0\<^sub>m k (n - k))" using assms unfolding split_block_def Let_def by simp fix i j assume "i < dim_row (0\<^sub>m k (n - k))" and "j < dim_col (0\<^sub>m k (n - k))" note ijprop = this have "B2 $$ (i, j) = B $$ (i, j+k)" using assms ijprop unfolding split_block_def Let_def by simp also have "... = 0" proof (rule commute_diag_mat_zero_comp[of D n], (auto simp add: assms)) show "i < n" using ijprop assms by simp show "j + k < n" using ijprop assms by simp show "D $$ (i, i) = D $$ (j + k, j + k) \<Longrightarrow> False" using ijprop assms by (metis \<open>j + k < n\<close> index_zero_mat(2) le_add2) qed finally show "B2 $$ (i, j) = 0\<^sub>m k (n - k) $$ (i, j)" using ijprop by simp next show "B3 = 0\<^sub>m (n-k) k" proof (intro eq_matI) show "dim_row B3 = dim_row (0\<^sub>m (n - k) k)" using assms unfolding split_block_def Let_def by simp show "dim_col B3 = dim_col (0\<^sub>m (n - k) k)" using assms unfolding split_block_def Let_def by simp fix i j assume "i < dim_row (0\<^sub>m (n - k) k)" and "j < dim_col (0\<^sub>m (n - k) k)" note ijprop = this have "B3 $$ (i, j) = B $$ (i+k, j)" using assms ijprop unfolding split_block_def Let_def by simp also have "... = 0" proof (rule commute_diag_mat_zero_comp[of D n], (auto simp add: assms)) show "i + k < n" using ijprop assms by simp show "j < n" using ijprop assms by simp show "D $$ (i+k, i+k) = D $$ (j, j) \<Longrightarrow> False" using ijprop assms by (metis \<open>i + k < n\<close> index_zero_mat(3) le_add2) qed finally show "B3 $$ (i, j) = 0\<^sub>m (n - k) k $$ (i, j)" using ijprop by simp qed qed lemma split_block_hermitian_1: assumes "hermitian A" and "n \<le> dim_row A" and "(A1, A2, A3, A4) = split_block A n n" shows "hermitian A1" unfolding hermitian_def proof (rule eq_matI, auto) have "dim_row A = dim_col A" using assms by (metis carrier_matD(2) hermitian_square) show "dim_col A1 = dim_row A1" using assms unfolding split_block_def Let_def by simp thus "dim_row A1 = dim_col A1" by simp show "\<And>i j. i < dim_row A1 \<Longrightarrow> j < dim_col A1 \<Longrightarrow> Complex_Matrix.adjoint A1 $$ (i, j) = A1 $$ (i, j)" proof - fix i j assume "i < dim_row A1" and "j < dim_col A1" note ij = this have r: "dim_row A1 = n" using assms unfolding split_block_def Let_def by simp have c: "dim_col A1 = n" using assms unfolding split_block_def Let_def by simp have "Complex_Matrix.adjoint A1 $$ (i, j) = conjugate (A1 $$ (j,i))" using ij r c unfolding Complex_Matrix.adjoint_def by simp also have "... = conjugate (A $$ (j,i))" using assms ij r c unfolding split_block_def Let_def by simp also have "... = A $$ (i,j)" using assms ij r c \<open>dim_row A = dim_col A\<close> unfolding hermitian_def Complex_Matrix.adjoint_def by (metis adjoint_eval assms(1) hermitian_def order_less_le_trans) also have "... = A1 $$(i,j)" using assms ij r c unfolding split_block_def Let_def by simp finally show "Complex_Matrix.adjoint A1 $$ (i, j) = A1 $$ (i, j)" . qed qed lemma split_block_hermitian_4: assumes "hermitian A" and "n \<le> dim_row A" and "(A1, A2, A3, A4) = split_block A n n" shows "hermitian A4" unfolding hermitian_def proof (rule eq_matI, auto) have arc: "dim_row A = dim_col A" using assms by (metis carrier_matD(2) hermitian_square) thus "dim_col A4 = dim_row A4" using assms unfolding split_block_def Let_def by simp thus "dim_row A4 = dim_col A4" by simp show "\<And>i j. i < dim_row A4 \<Longrightarrow> j < dim_col A4 \<Longrightarrow> Complex_Matrix.adjoint A4 $$ (i, j) = A4 $$ (i, j)" proof - fix i j assume "i < dim_row A4" and "j < dim_col A4" note ij = this have r: "dim_row A4 = dim_row A - n" using assms unfolding split_block_def Let_def by simp have c: "dim_col A4 = dim_col A - n" using assms unfolding split_block_def Let_def by simp have "Complex_Matrix.adjoint A4 $$ (i, j) = conjugate (A4 $$ (j,i))" using ij r c arc unfolding Complex_Matrix.adjoint_def by simp also have "... = conjugate (A $$ (j +n ,i+n))" using assms ij r c arc unfolding split_block_def Let_def by simp also have "... = A $$ (i+n,j+n)" using assms ij r c arc unfolding hermitian_def Complex_Matrix.adjoint_def by (metis index_mat(1) less_diff_conv split_conv) also have "... = A4 $$(i,j)" using assms ij r c unfolding split_block_def Let_def by simp finally show "Complex_Matrix.adjoint A4 $$ (i, j) = A4 $$ (i, j)" . qed qed lemma diag_block_split_block: assumes "B\<in> carrier_mat n n" and "k < n" and "(B1, B2, B3, B4) = split_block B k k" and "B2 = 0\<^sub>m k (n-k)" and "B3 = 0\<^sub>m (n-k) k" shows "B = diag_block_mat [B1,B4]" proof - have dr: "dim_row B = k + (n-k)" using assms by simp have dc: "dim_col B = k + (n-k)" using assms by simp have c1: "B1 \<in> carrier_mat k k" using assms split_block(1)[of B, OF _ dr dc] by metis have c4: "B4 \<in> carrier_mat (n-k) (n-k)" using assms split_block(4)[of B, OF _ dr dc] by metis have d4: "diag_block_mat [B4] = B4" using diag_block_mat_singleton[of B4] by simp have "B = four_block_mat B1 B2 B3 B4" using assms split_block(3)[of B k ] by (metis carrier_matD(1) carrier_matD(2) diff_is_0_eq le_add_diff_inverse nat_le_linear semiring_norm(137) split_block(5) zero_less_diff) also have "... = four_block_mat B1 (0\<^sub>m k (n-k)) (0\<^sub>m (n-k) k) B4" using assms by simp also have "... = four_block_mat B1 (0\<^sub>m k (n-k)) (0\<^sub>m (n-k) k) (diag_block_mat [B4])" using diag_block_mat_singleton[of B4] by simp also have "... = diag_block_mat [B1, B4]" using diag_block_mat.simps(2)[of B1 "[B4]"] c1 c4 unfolding Let_def by auto finally show ?thesis . qed subsection \<open>Diagonal block matrices\<close> abbreviation four_block_diag where "four_block_diag B1 B2 \<equiv> (four_block_mat B1 (0\<^sub>m (dim_row B1) (dim_col B2)) (0\<^sub>m (dim_row B2) (dim_col B1)) B2)" lemma four_block_diag_cong_comp: assumes "dim_row A1 = dim_row B1" and "dim_col A1 = dim_col B1" and "four_block_diag A1 A2 = four_block_diag B1 B2" shows "A1 = B1" proof (rule eq_matI, auto simp:assms) define A where "A = four_block_diag A1 A2" define B where "B = four_block_diag B1 B2" fix i j assume "i < dim_row B1" and "j<dim_col B1" note ij=this hence "i <dim_row A1" "j<dim_col A1" using assms by auto hence "A1$$(i,j) = A$$(i, j)" unfolding A_def four_block_mat_def Let_def by force also have "... = B$$(i, j)" using assms unfolding A_def B_def by simp also have "... = B1$$(i,j)" using ij unfolding B_def four_block_mat_def Let_def by force finally show "A1$$(i,j) = B1$$(i,j)" . qed lemma four_block_diag_cong_comp': assumes "dim_row A1 = dim_row B1" and "dim_col A1 = dim_col B1" and "four_block_diag A1 A2 = four_block_diag B1 B2" shows "A2 = B2" proof (rule eq_matI) define n where "n=dim_row A1" define m where "m = dim_col A1" define A where "A = four_block_diag A1 A2" define B where "B = four_block_diag B1 B2" show "dim_row A2 = dim_row B2" using assms unfolding four_block_mat_def Let_def by (metis assms(3) diff_add_inverse index_mat_four_block(2)) show "dim_col A2 = dim_col B2" using assms unfolding four_block_mat_def Let_def by (metis assms(3) diff_add_inverse index_mat_four_block(3)) fix i j assume "i < dim_row B2" and "j<dim_col B2" note ij=this hence "i+n < dim_row A" unfolding A_def n_def m_def four_block_mat_def Let_def by (simp add: \<open>dim_row A2 = dim_row B2\<close>) have "j+m < dim_col A" unfolding A_def n_def m_def four_block_mat_def Let_def by (simp add: \<open>dim_col A2 = dim_col B2\<close> ij) { have "n \<le> i+n" by simp have "m\<le> j+m" by simp have "i + n - n = i" by simp have "j + m - m = j" by simp } note ijeq = this have "A2$$(i,j) = A$$(i+n, j+m)" using ijeq using A_def \<open>i + n < dim_row A\<close> \<open>j + m < dim_col A\<close> m_def n_def by force also have "... = B$$(i+n, j+m)" using assms unfolding A_def B_def by simp also have "... = B2$$(i,j)" using ijeq by (metis A_def B_def \<open>i + n < dim_row A\<close> \<open>j + m < dim_col A\<close> add_implies_diff assms(1) assms(2) assms(3) index_mat_four_block(1) index_mat_four_block(2) index_mat_four_block(3) m_def n_def not_add_less2) finally show "A2$$(i,j) = B2$$(i,j)" . qed lemma four_block_mat_real_diag: assumes "\<forall>i < dim_row B1. B1$$(i,i) \<in> Reals" and "\<forall>i < dim_row B2. B2$$(i,i) \<in> Reals" and "dim_row B1 = dim_col B1" and "dim_row B2 = dim_col B2" and "i < dim_row (four_block_diag B1 B2)" shows "(four_block_diag B1 B2) $$ (i,i) \<in> Reals" proof (cases "i < dim_row B1") case True then show ?thesis using assms by simp next case False then show ?thesis using assms by force qed lemma four_block_diagonal: assumes "dim_row B1 = dim_col B1" and "dim_row B2 = dim_col B2" and "diagonal_mat B1" and "diagonal_mat B2" shows "diagonal_mat (four_block_diag B1 B2)" unfolding diagonal_mat_def proof (intro allI impI) fix i j assume "i < dim_row (four_block_diag B1 B2)" and "j < dim_col (four_block_diag B1 B2)" and "i \<noteq> j" note ijprops = this show "(four_block_diag B1 B2) $$ (i,j) = 0" proof (cases "i < dim_row B1") case True then show ?thesis using assms(3) diagonal_mat_def ijprops(2) ijprops(3) by (metis add_less_imp_less_left ijprops(1) index_mat_four_block(1) index_mat_four_block(2) index_mat_four_block(3) index_zero_mat(1) linordered_semidom_class.add_diff_inverse) next case False then show ?thesis using ijprops by (metis (no_types, lifting) add_less_cancel_left assms(1) assms(4) diagonal_mat_def index_mat_four_block(1) index_mat_four_block(2) index_mat_four_block(3) index_zero_mat(1) linordered_semidom_class.add_diff_inverse) qed qed lemma four_block_diag_zero: assumes "B\<in> carrier_mat 0 0" shows "four_block_diag A B = A" proof (rule eq_matI, auto) show "dim_row B = 0" using assms by simp show "dim_col B = 0" using assms by simp qed lemma four_block_diag_zero': assumes "B\<in> carrier_mat 0 0" shows "four_block_diag B A = A" proof (rule eq_matI) show "dim_row (four_block_diag B A) = dim_row A" using assms by simp show "dim_col (four_block_diag B A) = dim_col A" using assms by simp fix i j assume "i < dim_row A" and "j < dim_col A" thus "four_block_diag B A $$ (i, j) = A $$ (i, j)" using \<open>dim_col (four_block_diag B A) = dim_col A\<close> \<open>dim_row (four_block_diag B A) = dim_row A\<close> by auto qed lemma mult_four_block_diag: assumes "A1 \<in> carrier_mat nr1 n1" "D1 \<in> carrier_mat nr2 n2" and "A2 \<in> carrier_mat n1 nc1" "D2 \<in> carrier_mat n2 nc2" shows "four_block_diag A1 D1 * four_block_diag A2 D2 = four_block_diag (A1 * A2) (D1 * D2)" proof - define fb1 where "fb1 = four_block_mat A1 (0\<^sub>m nr1 n2) (0\<^sub>m nr2 n1) D1" define fb2 where "fb2 = four_block_mat A2 (0\<^sub>m n1 nc2) (0\<^sub>m n2 nc1) D2" have "fb1 * fb2 = four_block_mat (A1 * A2 + 0\<^sub>m nr1 n2 * 0\<^sub>m n2 nc1) (A1 * 0\<^sub>m n1 nc2 + 0\<^sub>m nr1 n2 * D2) (0\<^sub>m nr2 n1 * A2 + D1 * 0\<^sub>m n2 nc1) (0\<^sub>m nr2 n1 * 0\<^sub>m n1 nc2 + D1 * D2)" unfolding fb1_def fb2_def proof (rule mult_four_block_mat) show "A1 \<in> carrier_mat nr1 n1" using assms by simp show "D1 \<in> carrier_mat nr2 n2" using assms by simp show "A2 \<in> carrier_mat n1 nc1" "D2 \<in> carrier_mat n2 nc2" using assms by auto qed auto also have "... = four_block_mat (A1 * A2) (0\<^sub>m nr1 nc2) (0\<^sub>m nr2 nc1) (D1 * D2)" using assms by simp finally show ?thesis unfolding fb1_def fb2_def using assms by simp qed lemma four_block_diag_adjoint: shows "(Complex_Matrix.adjoint (four_block_diag A1 A2)) = (four_block_diag (Complex_Matrix.adjoint A1) (Complex_Matrix.adjoint A2))" by (rule eq_matI, auto simp: four_block_mat_adjoint zero_adjoint adjoint_eval) lemma four_block_diag_unitary: assumes "unitary U1" and "unitary U2" shows "unitary (four_block_diag U1 U2)" (is "unitary ?fU") unfolding unitary_def proof show "?fU \<in> carrier_mat (dim_row ?fU) (dim_row ?fU)" by (metis Complex_Matrix.unitary_def assms(1) assms(2) four_block_carrier_mat index_mat_four_block(2)) define n where "n = dim_row ?fU" show "inverts_mat ?fU (Complex_Matrix.adjoint ?fU)" proof - have "(Complex_Matrix.adjoint ?fU) = (four_block_mat (Complex_Matrix.adjoint U1) (0\<^sub>m (dim_col U1) (dim_row U2)) (0\<^sub>m (dim_col U2) (dim_row U1)) (Complex_Matrix.adjoint U2))" by (rule eq_matI, auto simp: four_block_mat_adjoint zero_adjoint adjoint_eval) hence "?fU * (Complex_Matrix.adjoint ?fU) = ?fU * (four_block_diag (Complex_Matrix.adjoint U1) (Complex_Matrix.adjoint U2))" by simp also have "... = four_block_diag (U1 * (Complex_Matrix.adjoint U1)) (U2 * (Complex_Matrix.adjoint U2))" by (rule mult_four_block_diag, (auto simp add: assms)) also have "... = four_block_mat (1\<^sub>m (dim_row U1)) (0\<^sub>m (dim_row U1) (dim_row U2)) (0\<^sub>m (dim_row U2) (dim_row U1)) (1\<^sub>m (dim_row U2))" using assms unfolding unitary_def inverts_mat_def by simp also have "... = 1\<^sub>m (dim_row U1 + dim_row U2)" by simp finally show ?thesis unfolding inverts_mat_def by simp qed qed lemma four_block_diag_similar: assumes "unitarily_equiv A1 B1 U1" and "unitarily_equiv A2 B2 U2" and "dim_row A1 = dim_col A1" and "dim_row A2 = dim_col A2" shows "similar_mat_wit (four_block_diag A1 A2) (four_block_diag B1 B2) (four_block_diag U1 U2) (Complex_Matrix.adjoint (four_block_diag U1 U2))" unfolding similar_mat_wit_def proof (simp add: Let_def, intro conjI) define n where "n = dim_row A1 + dim_row A2" show "four_block_diag A1 A2 \<in> carrier_mat n n" unfolding n_def using assms by auto show "four_block_diag B1 B2 \<in> carrier_mat n n" unfolding n_def using assms by (metis carrier_matI four_block_carrier_mat unitarily_equiv_carrier(1)) show u: "four_block_diag U1 U2 \<in> carrier_mat n n" unfolding n_def using assms by (metis carrier_matI four_block_carrier_mat unitarily_equiv_carrier(2)) thus cu: "Complex_Matrix.adjoint (four_block_diag U1 U2) \<in> carrier_mat n n" unfolding n_def using adjoint_dim' by blast show "four_block_diag U1 U2*Complex_Matrix.adjoint (four_block_diag U1 U2) = 1\<^sub>m n" unfolding n_def using u assms four_block_diag_unitary n_def unitarily_equiv_def unitary_simps(2) by blast thus "Complex_Matrix.adjoint (four_block_diag U1 U2)*four_block_diag U1 U2 = 1\<^sub>m n" using cu mat_mult_left_right_inverse u by blast have "four_block_diag A1 A2 = four_block_diag (U1 * B1 * (Complex_Matrix.adjoint U1)) (U2 * B2 * (Complex_Matrix.adjoint U2))" using assms unitarily_equiv_eq by blast also have "... = (four_block_diag (U1*B1) (U2*B2)) * (four_block_diag (Complex_Matrix.adjoint U1) (Complex_Matrix.adjoint U2))" proof (rule mult_four_block_diag[symmetric]) show "U1 * B1 \<in> carrier_mat (dim_row A1) (dim_row A1)" by (metis assms(1) assms(3) carrier_mat_triv mult_carrier_mat unitarily_equiv_carrier(1) unitarily_equiv_carrier(2)) show "U2 * B2 \<in> carrier_mat (dim_row A2) (dim_row A2)" by (metis assms(2) assms(4) carrier_mat_triv mult_carrier_mat unitarily_equiv_carrier(1) unitarily_equiv_carrier(2)) show "Complex_Matrix.adjoint U1 \<in> carrier_mat (dim_row A1) (dim_row A1)" by (metis Complex_Matrix.unitary_def adjoint_dim assms(1) index_mult_mat(2) unitarily_equivD(1) unitarily_equiv_eq) show "Complex_Matrix.adjoint U2 \<in> carrier_mat (dim_row A2) (dim_row A2)" by (meson assms(2) carrier_mat_triv similar_mat_witD2(7) unitarily_equiv_def) qed also have "... = four_block_diag U1 U2 * four_block_diag B1 B2 * Complex_Matrix.adjoint (four_block_diag U1 U2)" proof - have "four_block_diag (U1*B1) (U2*B2) = four_block_diag U1 U2 * four_block_diag B1 B2" proof (rule mult_four_block_diag[symmetric]) show "U1 \<in> carrier_mat (dim_row A1) (dim_row A1)" by (metis assms(1) assms(3) carrier_mat_triv unitarily_equiv_carrier(2)) show "B1 \<in> carrier_mat (dim_row A1) (dim_row A1)" by (metis assms(1) assms(3) carrier_mat_triv unitarily_equiv_carrier(1)) show "U2 \<in> carrier_mat (dim_row A2) (dim_row A2)" by (metis assms(2) assms(4) carrier_mat_triv unitarily_equiv_carrier(2)) show "B2 \<in> carrier_mat (dim_row A2) (dim_row A2)" by (metis assms(2) assms(4) carrier_mat_triv unitarily_equiv_carrier(1)) qed moreover have "four_block_diag (Complex_Matrix.adjoint U1) (Complex_Matrix.adjoint U2) = Complex_Matrix.adjoint (four_block_diag U1 U2)" by (rule four_block_diag_adjoint[symmetric]) ultimately show ?thesis by simp qed finally show "four_block_diag A1 A2 = four_block_diag U1 U2 * four_block_diag B1 B2 * Complex_Matrix.adjoint (four_block_diag U1 U2)" . qed lemma four_block_unitarily_equiv: assumes "unitarily_equiv A1 B1 U1" and "unitarily_equiv A2 B2 U2" and "dim_row A1 = dim_col A1" and "dim_row A2 = dim_col A2" shows "unitarily_equiv (four_block_diag A1 A2) (four_block_diag B1 B2) (four_block_diag U1 U2)" (is "unitarily_equiv ?fA ?fB ?fU") unfolding unitarily_equiv_def proof show "unitary ?fU" using four_block_diag_unitary assms unitarily_equivD(1) by blast show "similar_mat_wit ?fA ?fB ?fU (Complex_Matrix.adjoint ?fU)" using assms four_block_diag_similar[of A1] by simp qed lemma four_block_unitary_diag: assumes "unitary_diag A1 B1 U1" and "unitary_diag A2 B2 U2" and "dim_row A1 = dim_col A1" and "dim_row A2 = dim_col A2" shows "unitary_diag (four_block_diag A1 A2) (four_block_diag B1 B2) (four_block_diag U1 U2)" (is "unitary_diag ?fA ?fB ?fU") unfolding unitary_diag_def proof show "unitarily_equiv ?fA ?fB ?fU" using four_block_unitarily_equiv[of A1] assms by simp have "dim_row B1 = dim_col B1" unfolding unitary_diag_def by (metis assms(1) assms(3) carrier_matD(1) carrier_matD(2) carrier_mat_triv unitary_diag_carrier(1)) moreover have "dim_row B2 = dim_col B2" unfolding unitary_diag_def by (metis assms(2) assms(4) carrier_matD(1) carrier_matD(2) carrier_mat_triv unitary_diag_carrier(1)) ultimately show "diagonal_mat ?fB" using four_block_diagonal assms unfolding unitary_diag_def by blast qed lemma four_block_real_diag_decomp: assumes "real_diag_decomp A1 B1 U1" and "real_diag_decomp A2 B2 U2" and "dim_row A1 = dim_col A1" and "dim_row A2 = dim_col A2" shows "real_diag_decomp (four_block_diag A1 A2) (four_block_diag B1 B2) (four_block_diag U1 U2)" (is "real_diag_decomp ?fA ?fB ?fU") unfolding real_diag_decomp_def proof (intro conjI allI impI) show "unitary_diag ?fA ?fB ?fU" using four_block_unitary_diag assms unfolding real_diag_decomp_def by blast fix i assume "i < dim_row ?fB" show "?fB $$ (i,i) \<in> Reals" proof (rule four_block_mat_real_diag) show "i < dim_row ?fB" using \<open>i < dim_row ?fB\<close> . show "\<forall>i<dim_row B1. B1 $$ (i, i) \<in> \<real>" using assms unfolding real_diag_decomp_def by simp show "\<forall>i<dim_row B2. B2 $$ (i, i) \<in> \<real>" using assms unfolding real_diag_decomp_def by simp show "dim_row B1 = dim_col B1" unfolding unitary_diag_def by (metis assms(1) assms(3) carrier_matD(1) carrier_matD(2) carrier_mat_triv real_diag_decompD(1) unitary_diag_carrier(1)) show "dim_row B2 = dim_col B2" unfolding unitary_diag_def by (metis assms(2) assms(4) carrier_matD(1) carrier_matD(2) carrier_mat_triv real_diag_decompD(1) unitary_diag_carrier(1)) qed qed lemma diag_block_mat_mult: assumes "length Al = length Bl" and "\<forall>i < length Al. dim_col (Al!i) = dim_row (Bl!i)" shows "diag_block_mat Al * (diag_block_mat Bl) = (diag_block_mat (map2 (*) Al Bl))" using assms proof (induct Al arbitrary: Bl) case Nil then show ?case by simp next case (Cons a Al) define A where "A = diag_block_mat Al" define B where "B = diag_block_mat (tl Bl)" have "0 < length Bl" using Cons by auto hence "Bl = hd Bl # (tl Bl)" by simp have "length (tl Bl) = length Al" using Cons by simp have dim: "\<forall>i<length Al. dim_col (Al ! i) = dim_row (tl Bl ! i)" proof (intro allI impI) fix i assume "i < length Al" hence "dim_col (Al ! i) = dim_col ((a#Al)!(Suc i))" by simp also have "... = dim_row (Bl!(Suc i))" using Cons by (metis Suc_lessI \<open>i < length Al\<close> length_Cons less_Suc_eq) also have "... = dim_row (tl Bl!i)" by (metis \<open>Bl = hd Bl # tl Bl\<close> nth_Cons_Suc) finally show "dim_col (Al ! i) = dim_row (tl Bl!i)" . qed define C where "C = map2 (*) (a # Al) Bl" have "hd C = a * hd Bl" using \<open>Bl = hd Bl # tl Bl\<close> unfolding C_def by (metis list.map(2) list.sel(1) prod.simps(2) zip_Cons_Cons) have "tl C = map2 (*) Al (tl Bl)" by (metis (no_types, lifting) C_def \<open>Bl = hd Bl # tl Bl\<close> list.sel(3) map_tl zip_Cons_Cons) have "C = hd C # (tl C)" unfolding C_def by (metis Nil_eq_zip_iff Nil_is_map_conv \<open>Bl = hd Bl # tl Bl\<close> list.exhaust_sel list.simps(3)) have "dim_row B = sum_list (map dim_row (tl Bl))" unfolding B_def by (simp add: dim_diag_block_mat(1)) also have "... = sum_list (map dim_col Al)" proof (rule sum_list_cong) show "length (map dim_row (tl Bl)) = length (map dim_col Al)" using \<open>length (tl Bl) = length Al\<close> by simp show "\<forall>i<length (map dim_row (tl Bl)). map dim_row (tl Bl) ! i = map dim_col Al ! i" by (metis \<open>length (tl Bl) = length Al\<close> dim length_map nth_map) qed also have "... = dim_col A" unfolding A_def by (simp add: dim_diag_block_mat(2)) finally have ba: "dim_row B = dim_col A" . have "diag_block_mat (a#Al) * (diag_block_mat Bl) = four_block_diag a A * (four_block_diag (hd Bl) B)" using diag_block_mat.simps(2) \<open>Bl = hd Bl # (tl Bl)\<close> unfolding Let_def A_def B_def by metis also have "... = four_block_diag (a * hd Bl) (A * B)" proof (rule mult_four_block_diag) show "a\<in> carrier_mat (dim_row a) (dim_col a)" by simp show "hd Bl \<in> carrier_mat (dim_col a) (dim_col (hd Bl))" using Cons by (metis \<open>0 < length Bl\<close> \<open>Bl = hd Bl # tl Bl\<close> carrier_mat_triv nth_Cons_0) show "A \<in> carrier_mat (dim_row A) (dim_col A)" by simp show " B \<in> carrier_mat (dim_col A) (dim_col B)" using ba by auto qed also have "... = four_block_diag (hd C) (diag_block_mat (tl C))" unfolding A_def B_def using C_def \<open>hd C = a * hd Bl\<close> \<open>length (tl Bl) = length Al\<close> \<open>tl C = map2 (*) Al (tl Bl)\<close> dim local.Cons(1) by presburger also have "... = diag_block_mat C" using \<open>C = hd C#(tl C)\<close> diag_block_mat.simps(2) unfolding Let_def by metis finally show ?case unfolding C_def . qed lemma real_diag_decomp_block: fixes Al::"complex Matrix.mat list" assumes "Al \<noteq> []" and "list_all (\<lambda>A. 0 < dim_row A \<and> hermitian A) Al" shows "\<exists> Bl Ul. length Ul = length Al \<and> (\<forall>i < length Al. Ul!i \<in> carrier_mat (dim_row (Al!i)) (dim_col (Al!i)) \<and> unitary (Ul!i) \<and> Bl!i \<in> carrier_mat (dim_row (Al!i)) (dim_col (Al!i))) \<and> real_diag_decomp (diag_block_mat Al) (diag_block_mat Bl) (diag_block_mat Ul)" using assms proof (induct Al) case Nil then show ?case by simp next case (Cons A Al) hence "hermitian A" "0 < dim_row A" by auto hence "A \<in> carrier_mat (dim_row A) (dim_row A)" by (simp add: hermitian_square) from this obtain B U where r: "real_diag_decomp A B U" using hermitian_real_diag_decomp \<open>hermitian A\<close> \<open>0 < dim_row A\<close> by blast have bcar: "B \<in> carrier_mat (dim_row A) (dim_col A)" using real_diag_decompD(1) by (metis \<open>A \<in> carrier_mat (dim_row A) (dim_row A)\<close> carrier_matD(2) r unitary_diag_carrier(1)) have ucar: "U \<in> carrier_mat (dim_row A) (dim_col A)" using real_diag_decompD(1) by (metis \<open>A \<in> carrier_mat (dim_row A) (dim_row A)\<close> carrier_matD(2) r unitary_diag_carrier(2)) have unit: "unitary U" by (meson r real_diag_decompD(1) unitary_diagD(3)) show ?case proof (cases "Al = []") case True hence "diag_block_mat (Cons A Al) = A" by auto moreover have "diag_block_mat [B] = B" by auto moreover have "diag_block_mat [U] = U" by auto moreover have "unitary U" using r real_diag_decompD(1) unitary_diagD(3) by blast ultimately have "real_diag_decomp (diag_block_mat (Cons A Al)) (diag_block_mat [B]) (diag_block_mat [U])" using \<open>real_diag_decomp A B U\<close> by auto moreover have "(\<forall>i<length (A # Al). [U]!i \<in> carrier_mat (dim_row ((A # Al) ! i)) (dim_col ((A # Al) ! i)) \<and> Complex_Matrix.unitary ([U] ! i) \<and> [B] ! i \<in> carrier_mat (dim_row ((A # Al) ! i)) (dim_col ((A # Al) ! i)))" using True by (simp add: bcar ucar unit) ultimately show ?thesis using True \<open>Complex_Matrix.unitary U\<close> bcar less_one ucar by (metis length_list_update list_update_code(2)) next case False have "list_all (\<lambda>A. 0 < dim_row A \<and> hermitian A) Al" using Cons by auto hence "\<exists>Bl Ul. length Ul = length Al \<and> (\<forall>i<length Al. Ul ! i \<in> carrier_mat (dim_row (Al ! i)) (dim_col (Al ! i)) \<and> unitary (Ul!i) \<and> Bl ! i \<in> carrier_mat (dim_row (Al ! i)) (dim_col (Al ! i))) \<and> real_diag_decomp (diag_block_mat Al) (diag_block_mat Bl) (diag_block_mat Ul)" using Cons False by simp from this obtain Bl Ul where "length Ul =length Al" and rl: "real_diag_decomp (diag_block_mat Al) (diag_block_mat Bl) (diag_block_mat Ul)" and "\<forall>i<length Al. Ul ! i \<in> carrier_mat (dim_row (Al ! i)) (dim_col (Al ! i)) \<and> unitary (Ul!i) \<and> Bl ! i \<in> carrier_mat (dim_row (Al ! i)) (dim_col (Al ! i))" by auto note bu = this have "real_diag_decomp (diag_block_mat (A # Al)) (diag_block_mat (B # Bl)) (diag_block_mat (U # Ul))" using four_block_real_diag_decomp[OF r rl] by (metis \<open>A \<in> carrier_mat (dim_row A) (dim_row A)\<close> carrier_matD(2) diag_block_mat.simps(2) hermitian_square real_diag_decomp_hermitian rl) moreover have "length (U#Ul) = length (A#Al)" using bu by simp moreover have "\<forall>i<length (A # Al). (U#Ul) ! i \<in> carrier_mat (dim_row ((A # Al) ! i)) (dim_col ((A # Al) ! i)) \<and> unitary ((U#Ul)!i) \<and> (B#Bl) ! i \<in> carrier_mat (dim_row ((A # Al) ! i)) (dim_col ((A # Al) ! i))" proof (intro allI impI) fix i assume "i < length (A#Al)" show "(U # Ul) ! i \<in> carrier_mat (dim_row ((A # Al) ! i)) (dim_col ((A # Al) ! i)) \<and> unitary ((U#Ul)!i) \<and> (B # Bl) ! i \<in> carrier_mat (dim_row ((A # Al) ! i)) (dim_col ((A # Al) ! i))" proof (cases "i = 0") case True then show ?thesis by (simp add: bcar ucar unit) next case False hence "\<exists>j. i = Suc j" by (simp add: not0_implies_Suc) from this obtain j where j: "i = Suc j" by auto hence "j < length Al" using \<open>i < length (A#Al)\<close> by simp have "(A#Al)!i = Al!j" "(U # Ul) ! i = Ul!j" "(B#Bl) ! i = Bl!j" using j by auto then show ?thesis using Cons \<open>j < length Al\<close> bu(3) by presburger qed qed ultimately show ?thesis by blast qed qed lemma diag_block_mat_adjoint: shows "Complex_Matrix.adjoint (diag_block_mat Al) = diag_block_mat (map Complex_Matrix.adjoint Al)" proof (induct Al) case Nil then show ?case using zero_adjoint by simp next case (Cons a Al) have "Complex_Matrix.adjoint (diag_block_mat (a # Al)) = Complex_Matrix.adjoint (four_block_diag a (diag_block_mat Al))" using diag_block_mat.simps(2)[of a] unfolding Let_def by simp also have "... = four_block_diag (Complex_Matrix.adjoint a) (Complex_Matrix.adjoint (diag_block_mat Al))" using four_block_diag_adjoint[of a] by simp also have "... = four_block_diag (Complex_Matrix.adjoint a) (diag_block_mat (map Complex_Matrix.adjoint Al))" using Cons by simp also have "... = diag_block_mat (map Complex_Matrix.adjoint (a#Al))" using diag_block_mat.simps(2) unfolding Let_def by (metis (no_types) diag_block_mat.simps(2) list.map(2)) finally show ?case . qed lemma diag_block_mat_mat_conj: assumes "length Al = length Bl" and "\<forall>i < length Al. dim_col (Al!i) = dim_row (Bl!i)" and "\<forall>i < length Al. dim_row (Bl!i) = dim_col (Bl!i)" shows "mat_conj (diag_block_mat Al) (diag_block_mat Bl) = diag_block_mat (map2 mat_conj Al Bl)" proof - have "mat_conj (diag_block_mat Al) (diag_block_mat Bl) = diag_block_mat Al * diag_block_mat Bl * diag_block_mat (map Complex_Matrix.adjoint Al)" using diag_block_mat_adjoint[of Al] unfolding mat_conj_def by simp also have "... = diag_block_mat (map2 (*) Al Bl) * diag_block_mat (map Complex_Matrix.adjoint Al)" using diag_block_mat_mult[OF assms(1) assms(2)] by simp also have "... = diag_block_mat (map2 (*) (map2 (*) Al Bl) (map Complex_Matrix.adjoint Al))" proof (rule diag_block_mat_mult) show "length (map2 (*) Al Bl) = length (map Complex_Matrix.adjoint Al)" by (simp add: assms(1)) show "\<forall>i<length (map2 (*) Al Bl). dim_col (map2 (*) Al Bl ! i) = dim_row (map Complex_Matrix.adjoint Al ! i)" by (simp add: assms(2) assms(3)) qed also have "... = diag_block_mat (map2 mat_conj Al Bl)" using map2_mat_conj_exp[OF assms(1)] by simp finally show ?thesis . qed lemma diag_block_mat_commute: assumes "length Al = length Bl" and "\<forall>i < length Al. Al!i * (Bl!i) = Bl!i * (Al!i)" and "\<forall>i<length Al. dim_col (Al ! i) = dim_row (Bl ! i)" and "\<forall>i<length Al. dim_col (Bl ! i) = dim_row (Al ! i)" shows "diag_block_mat Al * (diag_block_mat Bl) = diag_block_mat Bl * (diag_block_mat Al)" proof - have "diag_block_mat Al * diag_block_mat Bl = diag_block_mat (map2 (*) Al Bl)" using diag_block_mat_mult[of Al Bl] assms by simp also have "... = diag_block_mat (map2 (*) Bl Al)" proof - have "map2 (*) Al Bl = map2 (*) Bl Al" by (rule map2_commute, auto simp add: assms) thus ?thesis by simp qed also have "... = diag_block_mat Bl * (diag_block_mat Al)" using diag_block_mat_mult[of Bl Al] assms by simp finally show ?thesis . qed lemma diag_block_mat_length_1: assumes "length Al = 1" shows "diag_block_mat Al = Al!0" proof - have "Al = [Al!0]" using assms by (metis One_nat_def length_0_conv length_Suc_conv nth_Cons_0) thus ?thesis by (metis diag_block_mat_singleton) qed lemma diag_block_mat_cong_hd: assumes "0 < length Al" and "length Al = length Bl" and "dim_row (hd Al) = dim_row (hd Bl)" and "dim_col (hd Al) = dim_col (hd Bl)" and "diag_block_mat Al = diag_block_mat Bl" shows "hd Al = hd Bl" proof - have "Al \<noteq> []" using assms by blast hence "Al = hd Al#(tl Al)" by simp hence da:"diag_block_mat Al = four_block_diag (hd Al) (diag_block_mat (tl Al))" using diag_block_mat.simps(2)[of "hd Al" "tl Al"] unfolding Let_def by simp have "Bl \<noteq> []" using assms by simp hence "Bl = hd Bl#(tl Bl)" by simp hence "diag_block_mat Bl = four_block_diag (hd Bl) (diag_block_mat (tl Bl))" using diag_block_mat.simps(2)[of "hd Bl" "tl Bl"] unfolding Let_def by simp hence "four_block_diag (hd Al) (diag_block_mat (tl Al)) = four_block_diag (hd Bl) (diag_block_mat (tl Bl))" using da assms by simp thus ?thesis using four_block_diag_cong_comp assms by metis qed lemma diag_block_mat_cong_tl: assumes "0 < length Al" and "length Al = length Bl" and "dim_row (hd Al) = dim_row (hd Bl)" and "dim_col (hd Al) = dim_col (hd Bl)" and "diag_block_mat Al = diag_block_mat Bl" shows "diag_block_mat (tl Al) = diag_block_mat (tl Bl)" proof - have "Al \<noteq> []" using assms by blast hence "Al = hd Al#(tl Al)" by simp hence da:"diag_block_mat Al = four_block_diag (hd Al) (diag_block_mat (tl Al))" using diag_block_mat.simps(2)[of "hd Al" "tl Al"] unfolding Let_def by simp have "Bl \<noteq> []" using assms by simp hence "Bl = hd Bl#(tl Bl)" by simp hence "diag_block_mat Bl = four_block_diag (hd Bl) (diag_block_mat (tl Bl))" using diag_block_mat.simps(2)[of "hd Bl" "tl Bl"] unfolding Let_def by simp hence "four_block_diag (hd Al) (diag_block_mat (tl Al)) = four_block_diag (hd Bl) (diag_block_mat (tl Bl))" using da assms by simp thus ?thesis using four_block_diag_cong_comp' assms by metis qed lemma diag_block_mat_cong_comp: assumes "length Al = length Bl" and "\<forall>i<length Al. dim_row (Al ! i) = dim_row (Bl ! i)" and "\<forall>i<length Al. dim_col (Al ! i) = dim_col (Bl ! i)" and "diag_block_mat Al = diag_block_mat Bl" and "j < length Al" shows "Al!j = Bl!j" using assms proof (induct Al arbitrary: Bl j) case Nil then show ?case by simp next case (Cons a Al) hence "0 <length Bl" by linarith hence "Bl = hd Bl#(tl Bl)" by simp then show ?case proof (cases "j = 0") case True hence "(a#Al)!j = hd(a#Al)" by simp have "Bl!j= hd Bl" using \<open>j = 0\<close> by (metis \<open>Bl = hd Bl # tl Bl\<close> nth_Cons_0) have da: "diag_block_mat (a#Al) = four_block_diag a (diag_block_mat Al)" using diag_block_mat.simps(2)[of a Al] unfolding Let_def by simp have db: "diag_block_mat (hd Bl#(tl Bl)) = four_block_diag (hd Bl) (diag_block_mat (tl Bl))" using diag_block_mat.simps(2)[of "hd Bl" "tl Bl"] unfolding Let_def by simp have "hd (a#Al) = hd Bl" proof (rule diag_block_mat_cong_hd) show "0 < length (a # Al)" by simp show "length (a # Al) = length Bl" using Cons by simp show "diag_block_mat (a # Al) = diag_block_mat Bl" using Cons by simp show "dim_row (hd (a # Al)) = dim_row (hd Bl)" by (metis True \<open>0 < length Bl\<close> \<open>Bl ! j = hd Bl\<close> list.sel(1) Cons(2) Cons(3) nth_Cons_0) show "dim_col (hd (a # Al)) = dim_col (hd Bl)" by (metis True \<open>0 < length Bl\<close> \<open>Bl ! j = hd Bl\<close> list.sel(1) Cons(2) Cons(4) nth_Cons_0) qed thus "(a # Al) ! j = Bl ! j" using \<open>j = 0\<close> \<open>Bl ! j = hd Bl\<close> by fastforce next case False hence "\<exists>k. j = Suc k" by (simp add: not0_implies_Suc) from this obtain k where "j = Suc k" by auto hence "(a#Al)!j = Al!k" by simp have "Bl!j = (tl Bl)!k" using \<open>j = Suc k\<close> \<open>Bl = hd Bl#(tl Bl)\<close> by (metis nth_Cons_Suc) have "Al!k = (tl Bl)!k" proof (rule Cons(1)) show "length Al = length (tl Bl)" using Cons by (metis diff_Suc_1 length_Cons length_tl) show "k < length Al" by (metis Cons.prems(5) Suc_less_SucD \<open>j = Suc k\<close> length_Cons) show "\<forall>i<length Al. dim_row (Al ! i) = dim_row (tl Bl ! i)" by (metis Suc_less_eq \<open>length Al = length (tl Bl)\<close> length_Cons local.Cons(3) nth_Cons_Suc nth_tl) show "\<forall>i<length Al. dim_col (Al ! i) = dim_col (tl Bl ! i)" by (metis Suc_mono \<open>Bl = hd Bl # tl Bl\<close> length_Cons local.Cons(4) nth_Cons_Suc) have "diag_block_mat (tl (a#Al)) = diag_block_mat (tl Bl)" proof (rule diag_block_mat_cong_tl) show "length (a # Al) = length Bl" using Cons by simp show "dim_row (hd (a # Al)) = dim_row (hd Bl)" by (metis \<open>Bl = hd Bl # tl Bl\<close> length_Cons list.sel(1) local.Cons(3) nth_Cons_0 zero_less_Suc) show "dim_col (hd (a # Al)) = dim_col (hd Bl)" by (metis \<open>0 < length Bl\<close> \<open>Bl = hd Bl # tl Bl\<close> list.sel(1) local.Cons(2) local.Cons(4) nth_Cons_0) show "diag_block_mat (a # Al) = diag_block_mat Bl" using Cons by simp show "0 < length (a#Al)" by simp qed thus "diag_block_mat Al = diag_block_mat (tl Bl)" by simp qed then show ?thesis by (simp add: \<open>(a # Al) ! j = Al ! k\<close> \<open>Bl ! j = tl Bl ! k\<close>) qed qed lemma diag_block_mat_commute_comp: assumes "length Al = length Bl" and "\<forall>i<length Al. dim_row (Al ! i) = dim_col (Al ! i)" and "\<forall>i<length Al. dim_row (Al ! i) = dim_row (Bl ! i)" and "\<forall>i<length Al. dim_col (Al ! i) = dim_col (Bl ! i)" and "diag_block_mat Al * (diag_block_mat Bl) = diag_block_mat Bl * (diag_block_mat Al)" and "i < length Al" shows "Al!i * Bl!i = Bl!i * Al!i" proof - have "diag_block_mat (map2 (*) Al Bl)=diag_block_mat Al * diag_block_mat Bl" using diag_block_mat_mult[of Al] assms by simp also have "... = diag_block_mat Bl * diag_block_mat Al" using assms by simp also have "... = diag_block_mat (map2 (*) Bl Al)" using diag_block_mat_mult[of Bl] assms by simp finally have eq: "diag_block_mat (map2 (*) Al Bl) = diag_block_mat (map2 (*) Bl Al)" . have "(map2 (*) Al Bl)!i = (map2 (*) Bl Al)!i" proof (rule diag_block_mat_cong_comp) show "length (map2 (*) Al Bl) = length (map2 (*) Bl Al)" using map2_length assms by metis show "i < length (map2 (*) Al Bl)" using map2_length assms by metis show "diag_block_mat (map2 (*) Al Bl) = diag_block_mat (map2 (*) Bl Al)" using eq . show "\<forall>i<length (map2 (*) Al Bl). dim_row (map2 (*) Al Bl ! i) = dim_row (map2 (*) Bl Al ! i)" by (simp add: assms(3)) show "\<forall>i<length (map2 (*) Al Bl). dim_col (map2 (*) Al Bl ! i) = dim_col (map2 (*) Bl Al ! i)" by (simp add: assms(4)) qed moreover have "(map2 (*) Al Bl)!i = Al!i * Bl!i" using assms by simp moreover have "(map2 (*) Bl Al)!i = Bl!i * Al!i" using assms by simp ultimately show ?thesis by simp qed lemma diag_block_mat_dim_row_cong: assumes "length Ul = length Bl" and "\<forall>i < length Bl. dim_row (Bl!i) = dim_row (Ul!i)" shows "dim_row (diag_block_mat Ul) = dim_row (diag_block_mat Bl)" proof - have "dim_row (diag_block_mat Ul) = sum_list (map dim_row Ul)" by (simp add: dim_diag_block_mat(1)) also have "... = sum_list (map dim_row Bl)" using assms by (metis nth_map_conv) also have "... = dim_row (diag_block_mat Bl)" by (simp add: dim_diag_block_mat(1)) finally show ?thesis . qed lemma diag_block_mat_dim_col_cong: assumes "length Ul = length Bl" and "\<forall>i < length Bl. dim_col (Bl!i) = dim_col (Ul!i)" shows "dim_col (diag_block_mat Ul) = dim_col (diag_block_mat Bl)" proof - have "dim_col (diag_block_mat Ul) = sum_list (map dim_col Ul)" by (simp add: dim_diag_block_mat(2)) also have "... = sum_list (map dim_col Bl)" using assms by (metis nth_map_conv) also have "... = dim_col (diag_block_mat Bl)" by (simp add: dim_diag_block_mat(2)) finally show ?thesis . qed lemma diag_block_mat_dim_row_col_eq: assumes "\<forall>i < length Al. dim_row (Al!i) = dim_col (Al!i)" shows "dim_row (diag_block_mat Al) = dim_col (diag_block_mat Al)" proof - have "dim_row (diag_block_mat Al) = sum_list (map dim_row Al)" by (simp add:dim_diag_block_mat(1)) also have "... = sum_list (map dim_col Al)" using assms by (metis nth_map_conv) also have "... = dim_col (diag_block_mat Al)" by (simp add:dim_diag_block_mat(2)) finally show ?thesis . qed section \<open>Block matrix decomposition\<close> subsection \<open>Subdiagonal extraction\<close> text \<open>\verb+extract_subdiags+ returns a list of diagonal sub-blocks, the sizes of which are specified by the list of integers provided as parameters.\<close> fun extract_subdiags where "extract_subdiags B [] = []" | "extract_subdiags B (x#xs) = (let (B1, B2, B3, B4) = (split_block B x x) in B1 # (extract_subdiags B4 xs))" lemma extract_subdiags_not_emp: fixes x::nat and l::"nat list" assumes "(B1, B2, B3, B4) = (split_block B x x)" shows "hd (extract_subdiags B (x#l)) = B1" "tl (extract_subdiags B (x#l)) = extract_subdiags B4 l" proof - show "hd (extract_subdiags B (x#l)) = B1" unfolding Let_def by (metis (no_types) assms extract_subdiags.simps(2) list.sel(1) split_conv) show "tl (extract_subdiags B (x # l)) = extract_subdiags B4 l" using assms extract_subdiags.simps(2) unfolding Let_def by (metis (no_types, lifting) list.sel(3) split_conv) qed lemma extract_subdiags_neq_Nil: shows "extract_subdiags B (a#l) \<noteq> []" using extract_subdiags.simps(2)[of B] unfolding Let_def split_block_def by simp lemma extract_subdiags_length: shows "length (extract_subdiags B l) = length l" proof (induct l arbitrary: B) case Nil then show ?case by simp next case (Cons a l) define B1 where "B1 = fst (split_block B a a)" define B2 where "B2 = fst (snd (split_block B a a))" define B3 where "B3 = fst (snd (snd (split_block B a a)))" define B4 where "B4 = snd (snd (snd (split_block B a a)))" have sp: "split_block B a a = (B1, B2, B3, B4)" using fst_conv snd_conv unfolding B1_def B2_def B3_def B4_def by simp then show ?case using Cons extract_subdiags.simps(2)[of B a l] unfolding Let_def by simp qed lemma extract_subdiags_carrier: assumes "i < length l" shows "(extract_subdiags B l)!i \<in> carrier_mat (l!i) (l!i)" using assms proof (induct i arbitrary: l B) case 0 define B1 where "B1 = fst (split_block B (hd l) (hd l))" define B2 where "B2 = fst (snd (split_block B (hd l) (hd l)))" define B3 where "B3 = fst (snd (snd (split_block B (hd l) (hd l))))" define B4 where "B4 = snd (snd (snd (split_block B (hd l) (hd l))))" have sp: "split_block B (hd l) (hd l) = (B1, B2, B3, B4)" using fst_conv snd_conv unfolding B1_def B2_def B3_def B4_def by simp have "l = hd l # (tl l)" using 0 by auto have "(extract_subdiags B l)!0 = B1" using extract_subdiags.simps(2)[of B "hd l" "tl l"] \<open>l = hd l # tl l\<close> sp unfolding Let_def by auto also have "... \<in> carrier_mat (hd l) (hd l)" unfolding B1_def split_block_def Let_def by simp finally show ?case by (metis \<open>l = hd l # tl l\<close> hd_conv_nth list.sel(2) not_Cons_self) next case (Suc i) define B1 where "B1 = fst (split_block B (hd l) (hd l))" define B2 where "B2 = fst (snd (split_block B (hd l) (hd l)))" define B3 where "B3 = fst (snd (snd (split_block B (hd l) (hd l))))" define B4 where "B4 = snd (snd (snd (split_block B (hd l) (hd l))))" have sp: "split_block B (hd l) (hd l) = (B1, B2, B3, B4)" using fst_conv snd_conv unfolding B1_def B2_def B3_def B4_def by simp have "l = hd l # (tl l)" using Suc by (metis Cons_nth_drop_Suc drop_Nil list.exhaust_sel not_Cons_self) hence "l! Suc i = (tl l)!i" by (metis nth_Cons_Suc) have "tl (extract_subdiags B l) = extract_subdiags B4 (tl l)" using extract_subdiags_not_emp(2)[OF sp[symmetric]] \<open>l = hd l # (tl l)\<close> by metis hence "extract_subdiags B l = B1 # extract_subdiags B4 (tl l)" using extract_subdiags_not_emp(1)[OF sp[symmetric]] by (metis \<open>l = hd l # tl l\<close> extract_subdiags_neq_Nil list.exhaust_sel) hence "extract_subdiags B l ! Suc i = (extract_subdiags B4 (tl l))!i" using nth_Cons_Suc by simp also have "... \<in> carrier_mat (tl l!i) (tl l!i)" using Suc by (metis \<open>l = hd l # tl l\<close> length_Cons not_less_eq) also have "... = carrier_mat (l!Suc i) (l! Suc i)" using nth_Cons_Suc[of "hd l" "tl l" i] \<open>l = hd l # tl l\<close> by simp finally show ?case . qed lemma extract_subdiags_diagonal: assumes "diagonal_mat B" and "B \<in> carrier_mat n n" and "l \<noteq> []" and "sum_list l \<le> n" and "i < length l" shows "diagonal_mat ((extract_subdiags B l)!i)" using assms proof (induct i arbitrary: l B n) case 0 define a where "a = hd l" have "l = a#(tl l)" unfolding a_def using 0 by simp have "a \<le> n" using 0 unfolding a_def by (metis a_def dual_order.strict_trans2 elem_le_sum_list hd_conv_nth less_le_not_le nat_le_linear) define B1 where "B1 = fst (split_block B a a)" define B2 where "B2 = fst (snd (split_block B a a))" define B3 where "B3 = fst (snd (snd (split_block B a a)))" define B4 where "B4 = snd (snd (snd (split_block B a a)))" have sp: "split_block B a a = (B1, B2, B3, B4)" using fst_conv snd_conv unfolding B1_def B2_def B3_def B4_def by simp hence "extract_subdiags B l!0 = B1" unfolding a_def using hd_conv_nth 0 by (metis \<open>l = a # tl l\<close> sp extract_subdiags_neq_Nil extract_subdiags_not_emp(1)) moreover have "diagonal_mat B1" using sp split_block_diagonal assms \<open>a \<le> n\<close> 0 by blast ultimately show ?case by simp next case (Suc i) show ?case proof (cases "length l = 1") case True hence "Suc i = 0" using Suc by presburger then show ?thesis by simp next case False define a where "a = hd l" have "l = a#(tl l)" unfolding a_def using Suc by simp have "a \<le> n" using Suc unfolding a_def by (metis dual_order.trans elem_le_sum_list hd_conv_nth length_greater_0_conv) define B1 where "B1 = fst (split_block B a a)" define B2 where "B2 = fst (snd (split_block B a a))" define B3 where "B3 = fst (snd (snd (split_block B a a)))" define B4 where "B4 = snd (snd (snd (split_block B a a)))" have sp: "split_block B a a = (B1, B2, B3, B4)" using fst_conv snd_conv unfolding B1_def B2_def B3_def B4_def by simp have "extract_subdiags B l ! Suc i = extract_subdiags B4 (tl l)! i" using sp by (metis Suc(6) Suc_less_SucD \<open>l = a # tl l\<close> length_Cons nth_tl extract_subdiags_length extract_subdiags_not_emp(2)) moreover have "diagonal_mat (extract_subdiags B4 (tl l)! i)" proof (rule Suc(1)) show "tl l \<noteq> []" using False Suc by (metis \<open>l = a # tl l\<close> length_Cons list.size(3) numeral_nat(7)) show "i < length (tl l)" using False Suc by (metis Suc_lessD \<open>l = a # tl l\<close> le_neq_implies_less length_Cons less_Suc_eq_le) show "B4 \<in> carrier_mat (n-a) (n-a)" using sp split_block_diag_carrier(2) Suc(3) \<open>a \<le> n\<close> by blast show "diagonal_mat B4" using split_block_diagonal sp Suc \<open>a \<le> n\<close> by blast show "sum_list (tl l) \<le> n - a" using Suc(5) \<open>a \<le> n\<close> sum_list_tl_leq by (simp add: Suc(4) a_def) qed ultimately show ?thesis by simp qed qed lemma extract_subdiags_diag_elem: fixes B::"complex Matrix.mat" assumes "B\<in> carrier_mat n n" and "0 < n" and "l \<noteq> []" and "i < length l" and "j< l!i" and "sum_list l \<le> n" and "\<forall>j < length l. 0 < l!j" shows "extract_subdiags B l!i $$ (j,j) = diag_mat B!(n_sum i l + j)" using assms proof (induct i arbitrary: l B n) case 0 define a where "a = hd l" have "l = a#(tl l)" unfolding a_def using 0 by simp have "a \<le> n" using 0 unfolding a_def by (metis a_def dual_order.strict_trans2 elem_le_sum_list hd_conv_nth less_le_not_le nat_le_linear) define B1 where "B1 = fst (split_block B a a)" define B2 where "B2 = fst (snd (split_block B a a))" define B3 where "B3 = fst (snd (snd (split_block B a a)))" define B4 where "B4 = snd (snd (snd (split_block B a a)))" have sp: "split_block B a a = (B1, B2, B3, B4)" using fst_conv snd_conv unfolding B1_def B2_def B3_def B4_def by simp hence "extract_subdiags B l!0 = B1" using hd_conv_nth unfolding Let_def by (metis \<open>l = a # tl l\<close> extract_subdiags_neq_Nil extract_subdiags_not_emp(1)) hence "extract_subdiags B l!0 $$ (j,j) = B$$ (j,j)" using sp 0 unfolding split_block_def by (metis (no_types, lifting) carrier_matD(2) dim_col_mat(1) index_mat(1) prod.sel(1) extract_subdiags_carrier) also have "... = diag_mat B!j" using 0 \<open>a \<le> n\<close> hd_conv_nth unfolding diag_mat_def a_def by fastforce also have "... = diag_mat B!(n_sum 0 l + j)" by simp finally show ?case . next case (Suc i) show ?case proof (cases "length l = 1") case True hence "Suc i < 0" using Suc by simp then show ?thesis by simp next case False hence "1 < length l" using Suc by presburger define a where "a = hd l" have "l = a#(tl l)" unfolding a_def using Suc by simp have "a \<le> n" using Suc unfolding a_def by (metis add_le_same_cancel1 elem_le_sum_list hd_conv_nth le_add2 le_trans verit_comp_simplify1(3)) define B1 where "B1 = fst (split_block B a a)" define B2 where "B2 = fst (snd (split_block B a a))" define B3 where "B3 = fst (snd (snd (split_block B a a)))" define B4 where "B4 = snd (snd (snd (split_block B a a)))" have sp: "split_block B a a = (B1, B2, B3, B4)" using fst_conv snd_conv unfolding B1_def B2_def B3_def B4_def by simp have "B4 \<in> carrier_mat (n-a) (n-a)" using sp split_block_diag_carrier(2) Suc \<open>a \<le> n\<close> by blast have "B1 \<in> carrier_mat a a" using sp split_block_diag_carrier(1) Suc \<open>a \<le> n\<close> by blast have "n_sum (Suc i) l + j < n_sum (Suc (Suc i)) l" using Suc n_sum_last_lt by metis hence "a + n_sum i (tl l) + j < n_sum (Suc (Suc i)) l" unfolding a_def by simp also have "... \<le> sum_list l" proof (rule n_sum_sum_list) show "\<forall>j<length l. 0 \<le> l ! j" using Suc by simp show "Suc (Suc i) \<le> length l" using Suc by simp qed also have "... \<le> n" using Suc by simp finally have "a + n_sum i (tl l) + j < n" . hence "n_sum i (tl l) +j < n - a" by simp have "extract_subdiags B l!(Suc i) = extract_subdiags B4 (tl l)!i" using sp \<open>l = a#(tl l)\<close> unfolding Let_def by (metis list.exhaust_sel nth_Cons_Suc extract_subdiags_neq_Nil extract_subdiags_not_emp(2)) hence "extract_subdiags B l!(Suc i) $$(j,j) = extract_subdiags B4 (tl l)!i $$(j,j)" by simp also have "... = diag_mat B4!(n_sum i (tl l) + j)" proof (rule Suc(1)) show "tl l \<noteq> []" using False Suc by (metis \<open>l = a # tl l\<close> length_Cons list.size(3) numeral_nat(7)) show "i < length (tl l)" using False Suc by (metis Suc_lessD \<open>l = a # tl l\<close> le_neq_implies_less length_Cons less_Suc_eq_le) show "B4 \<in> carrier_mat (n-a) (n-a)" using \<open>B4 \<in> carrier_mat (n-a) (n-a)\<close> . show "sum_list (tl l) \<le> n - a" using Suc(5) \<open>a \<le> n\<close> sum_list_tl_leq by (simp add: Suc a_def) show "0 < n - a" by (metis Suc.prems(4) Suc.prems(7) \<open>i < length (tl l)\<close> \<open>l = a # tl l\<close> \<open>sum_list (tl l) \<le> n - a\<close> bot_nat_0.extremum_uniqueI elem_le_sum_list gr_zeroI nth_Cons_Suc) show "\<forall>j<length (tl l). 0 < tl l ! j" by (simp add: Suc(8) nth_tl) show "j < tl l ! i" by (metis Suc(6) \<open>i < length (tl l)\<close> nth_tl) qed also have "... = B4$$(n_sum i (tl l)+j, n_sum i (tl l)+j)" proof - have "n_sum i (tl l) +j < n - a" using \<open>n_sum i (tl l) +j < n - a\<close> . thus ?thesis using \<open>B4 \<in> carrier_mat (n-a) (n-a)\<close> unfolding diag_mat_def by simp qed also have "... = B$$(n_sum i (tl l) + j + a, n_sum i (tl l) + j + a)" using sp \<open>B1 \<in> carrier_mat a a\<close> \<open>n_sum i (tl l) +j < n - a\<close> \<open>B4 \<in> carrier_mat (n-a) (n-a)\<close> carrier_matD(2) dim_col_mat(1) Suc index_mat(1) prod.sel unfolding split_block_def Let_def by force also have "... = diag_mat B!(n_sum i (tl l) + j + a)" proof - have "n_sum i (tl l) + j + a < n" using \<open>n_sum i (tl l) +j < n - a\<close> by simp thus ?thesis using Suc unfolding diag_mat_def by simp qed also have "... = diag_mat B ! (n_sum (Suc i) l + j)" proof - have "n_sum i (tl l) + a = n_sum (Suc i) l" unfolding a_def by simp thus ?thesis by (simp add: add.commute add.left_commute) qed finally show ?thesis . qed qed lemma hermitian_extract_subdiags: assumes "hermitian A" and "sum_list l \<le> dim_row A" and "list_all (\<lambda>a. 0 < a) l" shows "list_all (\<lambda>B. 0 < dim_row B \<and> hermitian B) (extract_subdiags A l)" using assms proof (induct l arbitrary: A) case Nil then show ?case by simp next case (Cons a l) define es where "es = extract_subdiags A (a#l)" define B1 where "B1 = fst (split_block A a a)" define B2 where "B2 = fst (snd (split_block A a a))" define B3 where "B3 = fst (snd (snd (split_block A a a)))" define B4 where "B4 = snd (snd (snd (split_block A a a)))" have sp: "split_block A a a = (B1, B2, B3, B4)" using fst_conv snd_conv unfolding B1_def B2_def B3_def B4_def by simp have "0 < a" using Cons by simp have "es \<noteq> []" using extract_subdiags_neq_Nil[of A] unfolding es_def by simp hence "es = hd es # (tl es)" by simp have "hd es = B1" unfolding es_def using extract_subdiags_not_emp(1)[OF sp[symmetric]] by simp have "dim_row B1 = a" unfolding B1_def split_block_def Let_def by simp have "tl es = extract_subdiags B4 l" unfolding es_def using extract_subdiags_not_emp(2)[OF sp[symmetric]] by simp have "list_all (\<lambda>B. 0 < dim_row B \<and> hermitian B) (hd es # (tl es))" proof (rule list_all_simps(1)[THEN iffD2], intro conjI) show "hermitian (hd es)" proof (rule split_block_hermitian_1) show "hermitian A" using Cons by simp show "(hd es, B2, B3, B4) = split_block A a a" using sp \<open>hd es = B1\<close> by simp show "a \<le> dim_row A" using Cons by simp qed have "list_all (\<lambda>B. 0 < dim_row B \<and> hermitian B) (extract_subdiags B4 l)" proof (rule Cons(1)) show "hermitian B4" proof (rule split_block_hermitian_4) show "hermitian A" using Cons by simp show "a \<le> dim_row A" using Cons by simp show "(B1, B2, B3, B4) = split_block A a a" using sp by simp qed show "sum_list l \<le> dim_row B4" using Cons sp unfolding split_block_def Let_def by force show "list_all ((<) 0) l" using Cons(4) by auto qed thus "list_all (\<lambda>B. 0 < dim_row B \<and> hermitian B) (tl es)" using \<open>tl es = extract_subdiags B4 l\<close> by simp show "0 < dim_row (hd es)" using \<open>hd es = B1\<close> \<open>0 < a\<close> \<open>dim_row B1 = a\<close> by simp qed thus ?case using \<open>es = hd es # (tl es)\<close> unfolding es_def by metis qed subsection \<open>Predicates on diagonal block matrices\<close> text \<open>The predicate \verb+diag_compat+ ensures that the provided matrix, when decomposed according to the list of integers provided as an input, is indeed a diagonal block matrix.\<close> fun diag_compat where "diag_compat B [] = (dim_row B = 0 \<and> dim_col B = 0)" | "diag_compat B (x#xs) = (x \<le> dim_row B \<and> (let n = dim_row B; (B1, B2, B3, B4) = (split_block B x x) in B2 = (0\<^sub>m x (n - x)) \<and> B3 = (0\<^sub>m (n - x) x) \<and> diag_compat B4 xs))" text \<open>When this is the case, the decomposition of a matrix leaves it unchanged.\<close> lemma diag_compat_extract_subdiag: assumes "B\<in> carrier_mat n n" and "diag_compat B l" shows "B = diag_block_mat (extract_subdiags B l)" using assms proof (induct l arbitrary:B n) case Nil have "extract_subdiags B Nil = []" by simp have "B = 0\<^sub>m 0 0" proof (rule eq_matI, auto simp add: assms) show "dim_row B = 0" using Nil by simp show "dim_col B = 0" using Nil by simp qed then show ?case using diag_block_mat_singleton[of B] by simp next case (Cons a l) define B1 where "B1 = fst (split_block B a a)" define B2 where "B2 = fst (snd (split_block B a a))" define B3 where "B3 = fst (snd (snd (split_block B a a)))" define B4 where "B4 = snd (snd (snd (split_block B a a)))" have sp: "split_block B a a = (B1, B2, B3, B4)" using fst_conv snd_conv unfolding B1_def B2_def B3_def B4_def by simp have "a \<le> n" using assms Cons by simp have "diag_compat B4 l" using sp Cons by (simp add: Let_def) have "B1 \<in> carrier_mat a a" using sp Cons split_block(1)[OF sp] by (metis \<open>a \<le> n\<close> carrier_matD(1) carrier_matD(2) le_add_diff_inverse) have "B2 \<in> carrier_mat a (n-a)" using sp Cons by (simp add: Let_def) have "B3 \<in> carrier_mat (n-a) a" using sp Cons by (simp add: Let_def) have "B4 \<in> carrier_mat (n-a) (n-a)" using assms \<open>a \<le> n\<close> Cons split_block(4)[OF sp] by simp have b2: "0\<^sub>m (dim_row B1) (dim_col B4) = B2" using diag_compat.simps(2)[THEN iffD1, OF \<open>diag_compat B (a#l)\<close>] \<open>B4 \<in> carrier_mat (n-a) (n-a)\<close> \<open>B1 \<in> carrier_mat a a\<close> \<open>B2 \<in> carrier_mat a (n-a)\<close> sp unfolding Let_def Cons(2) by force have b3: "0\<^sub>m (dim_row B4) (dim_col B1) = B3" using diag_compat.simps(2)[THEN iffD1, OF \<open>diag_compat B (a#l)\<close>] \<open>B4 \<in> carrier_mat (n-a) (n-a)\<close> \<open>B1 \<in> carrier_mat a a\<close> \<open>B2 \<in> carrier_mat a (n-a)\<close> sp unfolding Let_def Cons(2) by force have "extract_subdiags B (a#l) = B1 # (extract_subdiags B4 l)" using fst_conv snd_conv extract_subdiags.simps(2)[of B] unfolding B1_def B4_def Let_def by (simp add: split_def) also have "diag_block_mat ... = (let C = diag_block_mat (extract_subdiags B4 l) in four_block_mat B1 (0\<^sub>m (dim_row B1) (dim_col C)) (0\<^sub>m (dim_row C) (dim_col B1)) C)" by simp also have "... = four_block_mat B1 (0\<^sub>m (dim_row B1) (dim_col B4)) (0\<^sub>m (dim_row B4) (dim_col B1)) B4" using Cons \<open>diag_compat B4 l\<close> \<open>B4 \<in> carrier_mat (n-a) (n-a)\<close> by (simp add:Let_def) also have "... = four_block_mat B1 B2 B3 B4" using b2 b3 by simp also have "... = B" using split_block(5)[OF sp, of "n-a" "n-a"] Cons by simp finally show ?case by simp qed text \<open>Predicate \verb+diag_diff+ holds when the decomposition of the considered matrix based on the list of integers provided as a parameter, is such that the diagonal elements of separate components are pairwise distinct.\<close> fun diag_diff where "diag_diff D [] = (dim_row D = 0 \<and> dim_col D = 0)" | "diag_diff D (x#xs) = (x \<le> dim_row D \<and> (let (D1, D2, D3, D4) = (split_block D x x) in (\<forall>i j. i < dim_row D1 \<and> j < dim_row D4 \<longrightarrow> D1$$(i,i) \<noteq> D4 $$ (j,j)) \<and> diag_diff D4 xs))" lemma diag_diff_hd_diff: assumes "diag_diff D (a#xs)" and "D\<in> carrier_mat n n" and "i < a" and "a \<le> j" and "j < n" shows "D$$(i,i) \<noteq> D $$ (j,j)" proof - define D1 where "D1 = fst (split_block D a a)" define D2 where "D2 = fst (snd (split_block D a a))" define D3 where "D3 = fst (snd (snd (split_block D a a)))" define D4 where "D4 = snd (snd (snd (split_block D a a)))" have spd: "split_block D a a = (D1, D2, D3, D4)" using fst_conv snd_conv unfolding D1_def D2_def D3_def D4_def by simp have c1: "D1 \<in> carrier_mat a a" using split_block(1)[OF spd, of "n-a" "n-a"] assms by simp have c4: "D4 \<in> carrier_mat (n-a) (n-a)" using assms split_block(4)[OF spd] by simp hence "j - a < dim_row D4" using assms by simp have "D $$ (i,i) = D1 $$ (i,i)" using assms spd unfolding split_block_def Let_def by force moreover have "D $$ (j,j) = D4 $$ (j-a, j - a)" using assms spd unfolding split_block_def Let_def by force moreover have "D1 $$ (i,i) \<noteq> D4 $$ (j-a, j - a)" using assms \<open>j - a < dim_row D4\<close> spd c1 c4 diag_diff.simps(2)[THEN iffD1, OF assms(1)] unfolding Let_def by simp ultimately show ?thesis by simp qed lemma diag_compat_diagonal: assumes "B\<in> carrier_mat (dim_row B) (dim_row B)" and "diagonal_mat B" and "dim_row B = sum_list l" shows "diag_compat B l" using assms proof (induct l arbitrary: B) case Nil then show ?case by simp next case (Cons a l) define B1 where "B1 = fst (split_block B a a)" define B2 where "B2 = fst (snd (split_block B a a))" define B3 where "B3 = fst (snd (snd (split_block B a a)))" define B4 where "B4 = snd (snd (snd (split_block B a a)))" have sp: "split_block B a a = (B1, B2, B3, B4)" using fst_conv snd_conv unfolding B1_def B2_def B3_def B4_def by simp have "diagonal_mat B1 \<and> diagonal_mat B4" proof (rule split_block_diagonal) show "split_block B a a = (B1, B2, B3, B4)" using sp . show "diagonal_mat B" using Cons by simp show "B\<in> carrier_mat (dim_row B) (dim_row B)" using Cons by simp show "a \<le> dim_row B" using Cons by simp qed define n where "n = dim_row B" have "diag_compat B4 l" proof (rule Cons(1)) show "diagonal_mat B4" using \<open>diagonal_mat B1 \<and> diagonal_mat B4\<close> by simp show "B4 \<in> carrier_mat (dim_row B4) (dim_row B4)" using sp Cons unfolding split_block_def Let_def by auto show "dim_row B4 = sum_list l" using Cons sp unfolding split_block_def Let_def by auto qed have "B2 = 0\<^sub>m a (n - a)" proof (rule eq_matI, auto) show "dim_row B2 = a" using sp unfolding split_block_def Let_def n_def by auto show "dim_col B2 = n-a" using sp Cons unfolding split_block_def Let_def n_def by auto fix i j assume "i < a" and "j < n-a" thus "B2 $$(i,j) = 0" using sp Cons unfolding split_block_def Let_def n_def diagonal_mat_def by force qed have "B3 = 0\<^sub>m (n - a) a" proof (rule eq_matI, auto) show "dim_row B3 = n-a" using sp Cons unfolding split_block_def Let_def n_def by auto show "dim_col B3 = a" using sp Cons unfolding split_block_def Let_def n_def by auto fix i j assume "i < n-a" and "j < a" thus "B3 $$(i,j) = 0" using sp Cons unfolding split_block_def Let_def n_def diagonal_mat_def by force qed show ?case proof (rule diag_compat.simps(2)[THEN iffD2], intro conjI) show "a \<le> dim_row B" using Cons by simp show "let n = dim_row B; (B1, B2, B3, B4) = split_block B a a in B2 = 0\<^sub>m a (n - a) \<and> B3 = 0\<^sub>m (n - a) a \<and> diag_compat B4 l" using sp \<open>B3 = 0\<^sub>m (n - a) a\<close> \<open>B2 = 0\<^sub>m a (n - a)\<close> \<open>diag_compat B4 l\<close> unfolding Let_def n_def by auto qed qed text \<open>The following lemma provides a sufficient condition for the \verb+diag_compat+ predicate to hold.\<close> lemma commute_diag_compat: fixes D::"'a::{field} Matrix.mat" assumes "diagonal_mat D" and "D\<in> carrier_mat n n" and "B\<in> carrier_mat n n" and "B* D = D * B" and "diag_diff D l" shows "diag_compat B l" using assms proof (induct l arbitrary: B D n) case Nil hence "D \<in> carrier_mat 0 0" using assms by simp hence "n = 0" using assms using Nil(2) by auto hence "B \<in> carrier_mat 0 0" using Nil by simp then show ?case by simp next case (Cons a l) define B1 where "B1 = fst (split_block B a a)" define B2 where "B2 = fst (snd (split_block B a a))" define B3 where "B3 = fst (snd (snd (split_block B a a)))" define B4 where "B4 = snd (snd (snd (split_block B a a)))" have spb: "split_block B a a = (B1, B2, B3, B4)" using fst_conv snd_conv unfolding B1_def B2_def B3_def B4_def by simp define D1 where "D1 = fst (split_block D a a)" define D2 where "D2 = fst (snd (split_block D a a))" define D3 where "D3 = fst (snd (snd (split_block D a a)))" define D4 where "D4 = snd (snd (snd (split_block D a a)))" have spd: "split_block D a a = (D1, D2, D3, D4)" using fst_conv snd_conv unfolding D1_def D2_def D3_def D4_def by simp have "a \<le> n" using Cons by simp moreover have "diag_compat B4 l" proof (rule Cons(1)) show "diagonal_mat D4" using spd Cons \<open>a \<le> n\<close> split_block_diagonal[of D n a] by blast show "D4\<in> carrier_mat (n-a) (n-a)" using spd Cons(3) unfolding split_block_def Let_def by fastforce show "diag_diff D4 l" using spd Cons by simp show "B4 \<in> carrier_mat (n - a) (n - a)" using spb Cons(4) unfolding split_block_def Let_def by fastforce show "B4 * D4 = D4 * B4" using spb Cons \<open>a \<le> n\<close> split_block_commute_subblock[of D] by (meson spd) qed moreover have "B2 = 0\<^sub>m a (n - a)" proof (rule commute_diag_mat_split_block(1)[of D n B a B1 B2 B3 B4], (auto simp add: spb Cons \<open>a \<le> n\<close>)) fix i j assume "i < a" and "a \<le> j" and "j < n" thus "D $$ (i, i) = D $$ (j, j) \<Longrightarrow> False" using diag_diff_hd_diff[OF Cons(6) Cons(3), of i j] by simp qed moreover have "B3 = 0\<^sub>m (n - a) a" proof (rule commute_diag_mat_split_block(2)[of D n B a B1 B2 B3 B4], (auto simp add: spb Cons \<open>a \<le> n\<close>)) fix i j assume "i < a" and "a \<le> j" and "j < n" thus "D $$ (i, i) = D $$ (j, j) \<Longrightarrow> False" using diag_diff_hd_diff[OF Cons(6) Cons(3), of i j] by simp qed ultimately show ?case using spb diag_compat.simps(2)[THEN iffD2, of a B l] Cons unfolding Let_def by force qed subsection \<open>Counting similar neighbours in a list\<close> text \<open>The function \verb+eq_comps+ takes a list as an input and counts the number of adjacent elements that are identical.\<close> fun eq_comps where "eq_comps [] = []" | "eq_comps [x] = [1]" | "eq_comps (x#y#l) = (let tmp = (eq_comps (y#l)) in if x = y then Suc (hd tmp) # (tl tmp) else 1 # tmp)" lemma eq_comps_not_empty: assumes "l\<noteq> []" shows "eq_comps l \<noteq> []" using assms proof (induct l rule: eq_comps.induct) case 1 then show ?case by simp next case (2 x) then show ?case by simp next case (3 x y l) then show ?case by (cases "x = y", (auto simp add: Let_def)) qed lemma eq_comps_empty_if: assumes "eq_comps l = []" shows "l = []" proof (rule ccontr) assume "l\<noteq> []" hence "eq_comps l \<noteq> []" using eq_comps_not_empty[of l] by simp thus False using assms by simp qed lemma eq_comps_hd_eq_tl: assumes "x = y" shows "tl (eq_comps (x#y#l)) = tl (eq_comps (y#l))" using assms by (simp add: Let_def) lemma eq_comps_hd_neq_tl: assumes "x \<noteq> y" shows "tl (eq_comps (x#y#l)) = eq_comps (y#l)" using assms by (simp add:Let_def) lemma eq_comps_drop: assumes "x#xs = eq_comps l" shows "xs = eq_comps (drop x l)" using assms proof (induct l arbitrary:x xs rule: eq_comps.induct) case 1 then show ?case by simp next case (2 u) hence "x = 1" by simp hence "drop x [u] = []" by simp then show ?case using "2" by fastforce next case (3 u v l) define ec where "ec = eq_comps (v#l)" have "ec = hd ec # (tl ec)" using eq_comps_not_empty[of "v#l"] unfolding ec_def by simp show ?case proof (cases "u = v") case True have "xs = tl ec" using 3 eq_comps_hd_eq_tl[OF True] ec_def by (metis list.sel(3)) moreover have "x = Suc (hd ec)" using True 3 eq_comps.simps(3)[of u v ] unfolding ec_def Let_def by simp hence "drop (hd ec) (v#l) = drop x (u#v#l)" by simp moreover have "tl ec = eq_comps (drop (hd ec) (v#l))" using 3 ec_def \<open>ec = hd ec # (tl ec)\<close> by simp ultimately show ?thesis using 3 by simp next case False hence "x = 1" using 3 unfolding Let_def by simp moreover have "xs = ec" using 3 eq_comps_hd_neq_tl[OF False] ec_def by (metis list.sel(3)) ultimately show ?thesis unfolding ec_def by simp qed qed lemma eq_comps_neq_0: assumes "a#m = eq_comps l" shows "a \<noteq> 0" using assms proof (induct l rule:eq_comps.induct) case 1 then show ?case by simp next case (2 x) then show ?case by simp next case (3 x y l) then show ?case by (cases "x = y", (auto simp add: Let_def)) qed lemma eq_comps_gt_0: assumes "l \<noteq> []" shows "list_all (\<lambda>a. 0 < a) (eq_comps l)" proof (induct l rule:eq_comps.induct) case 1 then show ?case by simp next case (2 x) then show ?case by simp next case (3 x y l) then show ?case proof (cases "x = y") case True then show ?thesis using 3 eq_comps.simps(3)[of x y l] list_all_simps(1) unfolding Let_def by (metis eq_comps_not_empty hd_Cons_tl list.discI zero_less_Suc) next case False then show ?thesis using 3 eq_comps.simps(3)[of x y l] list_all_simps(1) unfolding Let_def by auto qed qed lemma eq_comps_elem_le_length: assumes "a#m = eq_comps l" shows "a \<le> length l" using assms proof (induct l arbitrary: a rule:eq_comps.induct) case 1 then show ?case by simp next case (2 x) then show ?case by auto next case (3 x y l) then show ?case proof (cases "x = y") case True define ec where "ec = eq_comps (y#l)" have "ec = hd ec # (tl ec)" using eq_comps_not_empty[of "y#l"] unfolding ec_def by simp have "a = Suc (hd ec)" using True 3 eq_comps.simps(3)[of x y] unfolding ec_def Let_def by simp then show ?thesis using 3 by (metis True \<open>ec = hd ec # tl ec\<close> ec_def eq_comps_hd_eq_tl length_Cons list.sel(3) not_less_eq_eq) next case False hence "a = 1" using 3 by (simp add: Let_def) then show ?thesis by simp qed qed lemma eq_comps_length: shows "length (eq_comps l) \<le> length l" proof (induct l rule:eq_comps.induct) case 1 then show ?case by simp next case (2 x) then show ?case by auto next case (3 x y l) define ec where "ec = eq_comps (y#l)" have ec: "ec = hd ec # (tl ec)" using eq_comps_not_empty[of "y#l"] unfolding ec_def by simp then show ?case proof (cases "x = y") case True then show ?thesis using ec 3 eq_comps.simps(3) True unfolding Let_def by (metis ec_def le_SucI length_Cons) next case False then show ?thesis using ec 3 by simp qed qed lemma eq_comps_eq: assumes "a#m = eq_comps l" and "i < a" shows "nth l i = hd l" using assms proof (induct l arbitrary: a m i rule: eq_comps.induct) case 1 then show ?case by simp next case (2 u) then show ?case by simp next case (3 u v l) show ?case proof (cases "u = v") case False thus ?thesis using 3 by (simp add: Let_def) next case True define ec where "ec = eq_comps (v#l)" have "ec = hd ec # (tl ec)" using eq_comps_not_empty[of "v#l"] unfolding ec_def by simp have "a = Suc (hd ec)" using True 3 eq_comps.simps(3)[of u v] unfolding ec_def Let_def by simp hence "i \<le> hd ec" using 3 by simp show ?thesis proof (cases "i = 0") case True thus ?thesis by simp next case False hence "\<exists>i'. i = Suc i'" by (simp add: not0_implies_Suc) from this obtain i' where "i = Suc i'" by auto hence "i' < hd ec" using \<open>i \<le> hd ec\<close> by simp have "(u # v # l) ! i = (v#l) ! i'" using \<open>i = Suc i'\<close> by simp also have "... = v" using 3 \<open>ec = eq_comps (v#l)\<close> \<open>ec = hd ec # (tl ec)\<close> by (metis \<open>i' < hd ec\<close> list.sel(1)) also have "... = hd (u#v#l)" using \<open>u = v\<close> by simp finally show ?thesis . qed qed qed lemma eq_comps_singleton: assumes "[a] = eq_comps l" shows "a = length l" using assms proof (induct l arbitrary: a rule: eq_comps.induct) case 1 then show ?case by simp next case (2 x) then show ?case by simp next case (3 x y l) define ec where "ec = eq_comps (y#l)" have "ec = hd ec # (tl ec)" using eq_comps_not_empty[of "y#l"] unfolding ec_def by simp show ?case proof (cases "x = y") case True hence "a = Suc (hd ec)" using 3 eq_comps.simps(3)[of x y] unfolding ec_def Let_def by simp have "tl ec = []" using 3 True eq_comps.simps(3)[of x y] unfolding ec_def Let_def by simp hence "ec = [hd ec]" using \<open>ec = hd ec # tl ec\<close> by simp hence "hd ec = length (y#l)" using 3 ec_def by simp then show ?thesis using \<open>a = Suc (hd ec)\<close> by simp next case False then show ?thesis using eq_comps_hd_neq_tl 3 \<open>ec = hd ec # tl ec\<close> ec_def by fastforce qed qed lemma eq_comps_leq: assumes "a#b#m = eq_comps l" and "sorted l" shows "hd l < hd (drop a l)" using assms proof (induct l arbitrary: a b m rule: eq_comps.induct) case 1 then show ?case by simp next case (2 x) then show ?case by simp next case (3 x y l) show ?case proof (cases "x = y") case True hence "hd (x#y#l) = y" by simp define ec where "ec = eq_comps (y#l)" have "a = Suc (hd (ec))" using True ec_def 3 eq_comps.simps(3)[of x y] unfolding Let_def by simp have "b#m = tl ec" using True ec_def 3 eq_comps.simps(3)[of x y] unfolding Let_def by simp hence eceq: "ec = hd ec # (hd (tl ec)) # (tl (tl ec))" unfolding ec_def by (metis eq_comps_not_empty list.exhaust_sel list.simps(3)) have dra: "drop a (x#y#l) = drop (hd ec) (y#l)" using \<open>a = Suc (hd (ec))\<close> by simp have "sorted (y#l)" using 3 by simp hence "y < hd (drop (hd ec) (y#l))" using 3(1) eceq unfolding ec_def by (metis list.sel(1)) thus ?thesis using True dra by simp next case False hence "a = 1" using 3 by (simp add: Let_def) have "hd (x#y#l) = x" by simp moreover have "hd (drop a (x # y # l)) = y" using \<open>a = 1\<close> by simp ultimately show ?thesis using False 3 by (metis order_le_imp_less_or_eq sorted2_simps(2)) qed qed lemma eq_comps_compare: assumes "sorted l" and "a#m = eq_comps l" and "i < a" and "a \<le> j" and "j < length l" shows "nth l i < nth l j" using assms proof (cases "m =[]") case True hence "[a] = eq_comps l" using assms by simp hence "a = length l" using eq_comps_singleton[of a "l"] by simp then show ?thesis using assms by simp next case False hence "m = hd m # (tl m)" by simp have "l!i = hd l" using assms eq_comps_eq by metis also have "... < hd (drop a l)" using eq_comps_leq assms \<open>m = hd m # (tl m)\<close> by metis also have "... \<le> l!j" using assms by (metis hd_drop_conv_nth le_less_trans sorted_nth_mono) finally show ?thesis . qed lemma eq_comps_singleton_elems: assumes "eq_comps l = [a]" shows "\<forall>i < length l. l!i = l!0" using eq_comps_eq eq_comps_singleton by (metis assms bot_nat_0.not_eq_extremum eq_comps_neq_0) lemma eq_comp_Re: assumes "\<forall> z \<in> set l. z \<in> Reals" and "m = eq_comps l" shows "m = eq_comps (map Re l)" using assms proof (induct l arbitrary:m rule:eq_comps.induct) case 1 then show ?case by simp next case (2 x) then show ?case by simp next case (3 x y l) define ec where "ec = eq_comps (y#l)" have ecr: "ec = eq_comps (map Re (y # l))" using ec_def 3 by simp show ?case proof (cases "x = y") case True hence "Re x = Re y" by simp have "m = Suc (hd ec) # (tl ec)" using ec_def 3 True by (simp add: Let_def) also have "... = eq_comps (map Re (x#y # l))" using ecr \<open>Re x = Re y\<close> by (simp add: Let_def) finally show ?thesis . next case False hence "Re x \<noteq> Re y" using 3 by (metis list.set_intros(1) list.set_intros(2) of_real_Re) have "m = 1#ec" using ec_def 3 False by (simp add: Let_def) also have "... = eq_comps (map Re (x#y # l))" using ecr \<open>Re x \<noteq> Re y\<close> by (simp add: Let_def) finally show ?thesis using ecr unfolding Let_def by simp qed qed lemma eq_comps_sum_list: shows "sum_list (eq_comps l) = length l" proof (induct l rule: eq_comps.induct) case 1 then show ?case unfolding diag_mat_def by simp next case (2 x) have "eq_comps [x] = [1]" using eq_comps.simps(2)[of x] by simp then show ?case by simp next case (3 x y l) then show ?case proof (cases "x = y") case True then show ?thesis using eq_comps.simps(3)[of x y l] 3 by (cases \<open>eq_comps (y # l)\<close>) simp_all next case False then show ?thesis using eq_comps.simps(3)[of x y l] 3 unfolding Let_def by simp qed qed lemma eq_comps_elem_lt: assumes "1 < length (eq_comps l)" shows "hd (eq_comps l) < length l" proof - define a where "a = hd (eq_comps l)" define b where "b = hd (tl (eq_comps l))" define c where "c = tl (tl (eq_comps l))" have "eq_comps l = a#b#c" using assms unfolding a_def b_def c_def by (metis eq_comps.simps(2) eq_comps_singleton length_0_conv less_irrefl_nat less_nat_zero_code list.exhaust_sel) hence "b#c = eq_comps (drop a l)" using eq_comps_drop by metis hence "0 < b" using eq_comps_neq_0 by auto moreover have "0 < a" using \<open>eq_comps l = a#b#c\<close> eq_comps_neq_0 by (metis gr0I) moreover have "a+b \<le> length l" using eq_comps_sum_list by (metis \<open>eq_comps l = a # b # c\<close> le_add1 nat_add_left_cancel_le sum_list_simps(2)) ultimately show ?thesis unfolding a_def by auto qed lemma eq_comp_sum_diag_mat: shows "sum_list (eq_comps (diag_mat A)) = dim_row A" using eq_comps_sum_list[of "diag_mat A"] diag_mat_length by simp lemma nsum_Suc_elem: assumes "1 < length (eq_comps l)" shows "l!(n_sum (Suc i) (eq_comps l)) = (drop (hd (eq_comps l)) l)!(n_sum i (tl (eq_comps l)))" using assms proof (induct i arbitrary: l) case 0 hence "1 < length l" using eq_comps_length[of l] by presburger hence "l \<noteq> []" by fastforce hence "l ! n_sum (Suc 0) (eq_comps l) = l ! hd (eq_comps l)" by (simp add: "0.prems" eq_comps_not_empty hd_conv_nth) also have "... = hd (drop (hd (eq_comps l)) l)" by (metis "0.prems" eq_comps_elem_lt hd_drop_conv_nth) finally show ?case using 0 by (metis (no_types, opaque_lifting) \<open>l ! hd (eq_comps l) = hd (drop (hd (eq_comps l)) l)\<close> \<open>l \<noteq> []\<close> append_Nil2 eq_comps.simps(1) eq_comps_drop eq_comps_empty_if eq_comps_singleton hd_conv_nth list.exhaust_sel n_sum.simps(1) nat_arith.rule0 nth_append_length_plus) next case (Suc i) have "l!(n_sum (Suc (Suc i)) (eq_comps l)) = l!(hd (eq_comps l) + (n_sum (Suc i) (tl (eq_comps l))))" by simp also have "... = (drop (hd (eq_comps l)) l)! (n_sum (Suc i) (tl (eq_comps l)))" using less_or_eq_imp_le by (metis Suc.prems eq_comps_elem_lt nth_drop) finally show ?case . qed lemma eq_comps_elems_eq: assumes "l\<noteq>[]" and "i < length (eq_comps l)" and "j < (eq_comps l)!i" shows "l!(n_sum i (eq_comps l)) = l!(n_sum i (eq_comps l) + j)" using assms proof (induct i arbitrary: l) case 0 hence "eq_comps l = hd (eq_comps l)#(tl (eq_comps l))" by simp have "l ! n_sum 0 (eq_comps l) = hd l" by (simp add: "0"(1) hd_conv_nth) also have "... = l!j" using 0 eq_comps_eq by (metis \<open>eq_comps l = hd (eq_comps l) # tl (eq_comps l)\<close> nth_Cons_0) finally show ?case by simp next case (Suc i) show ?case proof (cases "length (eq_comps l) = 1") case True hence "Suc i = 0" using Suc.prems(2) by fastforce then show ?thesis by simp next case False hence "1 < length (eq_comps l)" using Suc eq_comps_not_empty[of l] by presburger hence "l!(n_sum (Suc i) (eq_comps l)) = (drop (hd (eq_comps l)) l)!(n_sum i (tl (eq_comps l)))" using nsum_Suc_elem by simp also have "... = (drop (hd (eq_comps l)) l)! (n_sum i (eq_comps (drop (hd (eq_comps l)) l)))" using eq_comps_drop[of "hd (eq_comps l)"] eq_comps_empty_if list.collapse by fastforce also have "... = (drop (hd (eq_comps l)) l)! (n_sum i (eq_comps (drop (hd (eq_comps l)) l)) + j)" proof (rule Suc(1)) show "drop (hd (eq_comps l)) l \<noteq> []" by (metis Cons_nth_drop_Suc \<open>1 < length (eq_comps l)\<close> eq_comps_elem_lt list.distinct(1)) show "i < length (eq_comps (drop (hd (eq_comps l)) l))" using Suc by (metis (no_types, lifting) Suc_lessD eq_comps_drop eq_comps_not_empty length_Suc_conv list.collapse not_less_less_Suc_eq) show "j < eq_comps (drop (hd (eq_comps l)) l) ! i" using Suc by (metis eq_comps_drop length_Suc_conv less_natE list.exhaust_sel list.simps(3) nth_Cons_Suc) qed also have "... = (drop (hd (eq_comps l)) l)! (n_sum i (tl (eq_comps l)) + j)" by (metis Suc(2) eq_comps_drop eq_comps_not_empty hd_Cons_tl) also have "... = l!(n_sum (Suc i) (eq_comps l) + j)" by (metis (no_types, opaque_lifting) Groups.add_ac(2) Groups.add_ac(3) \<open>1 < length (eq_comps l)\<close> eq_comps_elem_lt less_or_eq_imp_le n_sum.simps(2) nth_drop) finally show ?thesis . qed qed text \<open>When the diagonal block matrices are extracted using \verb+eq_comp+, each extracted matrix is a multiple of the identity.\<close> lemma extract_subdiags_eq_comp: fixes A::"complex Matrix.mat" assumes "diagonal_mat A" and "A\<in> carrier_mat n n" and "0 < n" and "i < length (eq_comps (diag_mat A))" shows "\<exists>k. (extract_subdiags A (eq_comps (diag_mat A)))!i = k \<cdot>\<^sub>m (1\<^sub>m ((eq_comps (diag_mat A))!i))" proof define l where "l = diag_mat A" define k where "k = l!(n_sum i (eq_comps l))" show "extract_subdiags A (eq_comps (diag_mat A)) ! i = k \<cdot>\<^sub>m 1\<^sub>m (eq_comps (diag_mat A) ! i)" proof (rule eq_matI, auto simp add: assms) show dr: "dim_row (extract_subdiags A (eq_comps (diag_mat A)) ! i) = eq_comps (diag_mat A) ! i" using extract_subdiags_carrier assms carrier_matD(1) by blast show dc: "dim_col (extract_subdiags A (eq_comps (diag_mat A)) ! i) = eq_comps (diag_mat A) ! i" using extract_subdiags_carrier assms carrier_matD by blast fix m np assume "m < eq_comps (diag_mat A)!i" and "np < eq_comps (diag_mat A)!i" and "m\<noteq> np" note mnp=this have "diagonal_mat (extract_subdiags A (eq_comps (diag_mat A)) !i)" proof (rule extract_subdiags_diagonal) show "diagonal_mat A" using assms by simp show "A\<in> carrier_mat n n" using assms by simp show "eq_comps (diag_mat A) \<noteq> []" using assms unfolding diag_mat_def by auto show "sum_list (eq_comps (diag_mat A)) \<le> n" using assms eq_comps_sum_list unfolding diag_mat_def by (metis carrier_matD(1) carrier_matD(2) length_cols_mat_to_cols_list length_map order.eq_iff) show "i < length (eq_comps (diag_mat A))" using assms by simp qed thus "extract_subdiags A (eq_comps (diag_mat A)) ! i $$ (m, np) = 0" using mnp dr dc by (metis diagonal_mat_def) next fix p assume "p < eq_comps (diag_mat A) ! i" have "extract_subdiags A (eq_comps (diag_mat A)) ! i $$ (p, p) = diag_mat A! (n_sum i (eq_comps (diag_mat A)) + p)" proof (rule extract_subdiags_diag_elem) show "A\<in> carrier_mat n n" "0 < n" "i < length (eq_comps (diag_mat A))" using assms by auto show ne: "eq_comps (diag_mat A) \<noteq> []" using assms by auto show "p < eq_comps (diag_mat A) ! i" using \<open>p < eq_comps (diag_mat A) ! i\<close> . show "sum_list (eq_comps (diag_mat A)) \<le> n" using assms eq_comps_sum_list[of "diag_mat A"] unfolding diag_mat_def by simp show "\<forall>j<length (eq_comps (diag_mat A)). 0 < eq_comps (diag_mat A) ! j" using eq_comps_gt_0 ne by (metis eq_comps.simps(1) list_all_length) qed also have "... = k" unfolding k_def l_def proof (rule eq_comps_elems_eq[symmetric]) show "diag_mat A \<noteq> []" using assms unfolding diag_mat_def by simp show "p < eq_comps (diag_mat A) ! i" using \<open>p < eq_comps (diag_mat A) ! i\<close> . show "i < length (eq_comps (diag_mat A))" using assms by simp qed finally show "extract_subdiags A (eq_comps (diag_mat A)) ! i $$ (p, p) = k" . qed qed lemma extract_subdiags_comp_commute: fixes A::"complex Matrix.mat" assumes "diagonal_mat A" and "A\<in> carrier_mat n n" and "0 < n" and "i < length (eq_comps (diag_mat A))" and "B \<in> carrier_mat ((eq_comps (diag_mat A))!i) ((eq_comps (diag_mat A))!i)" shows "(extract_subdiags A (eq_comps (diag_mat A)))!i * B = B * (extract_subdiags A (eq_comps (diag_mat A)))!i" proof - define m where "m = (eq_comps (diag_mat A))!i" have "\<exists>k. (extract_subdiags A (eq_comps (diag_mat A)))!i = k \<cdot>\<^sub>m (1\<^sub>m ((eq_comps (diag_mat A))!i))" using assms extract_subdiags_eq_comp by simp from this obtain k where "(extract_subdiags A (eq_comps (diag_mat A)))!i = k \<cdot>\<^sub>m (1\<^sub>m m)" unfolding m_def by auto note kprop = this hence "(extract_subdiags A (eq_comps (diag_mat A)))!i * B = k \<cdot>\<^sub>m (1\<^sub>m m) * B" by simp also have "... = B * (k \<cdot>\<^sub>m (1\<^sub>m m))" using assms m_def by (metis left_mult_one_mat mult_smult_assoc_mat mult_smult_distrib one_carrier_mat right_mult_one_mat) finally show ?thesis using kprop by simp qed text \<open>In particular, extracting the diagonal sub-blocks of a diagonal matrix leaves it unchanged. \<close> lemma diagonal_extract_eq: assumes "B\<in> carrier_mat n n" and "diagonal_mat B" shows "B = diag_block_mat (extract_subdiags B (eq_comps (diag_mat B)))" proof (rule diag_compat_extract_subdiag) define eqcl where "eqcl= eq_comps (diag_mat B)" show "B \<in> carrier_mat n n" using assms by simp show "diag_compat B eqcl" proof (rule diag_compat_diagonal) show "B \<in> carrier_mat (dim_row B) (dim_row B)" using assms by simp show "diagonal_mat B" using assms by simp have "dim_row B = length (diag_mat B)" unfolding diag_mat_def by simp also have "... = sum_list eqcl" using eq_comps_sum_list[of "diag_mat B"] unfolding eqcl_def by simp finally show "dim_row B = sum_list eqcl". qed qed fun lst_diff where "lst_diff l [] = (l = [])" | "lst_diff l (x#xs) = (x \<le> length l \<and> (\<forall>i j. i < x \<and> x \<le> j \<and> j < length l \<longrightarrow> nth l i < nth l j) \<and> lst_diff (drop x l) xs)" lemma sorted_lst_diff: assumes "sorted l" and "m = eq_comps l" shows "lst_diff l m" using assms proof (induct m arbitrary: l) case Nil hence "l = []" using eq_comps_empty_if[of l] by simp then show ?case by simp next case (Cons a m) have "sorted (drop a l)" using Cons sorted_wrt_drop by simp moreover have "m = eq_comps (drop a l)" using eq_comps_drop Cons by simp ultimately have "lst_diff (drop a l) m" using Cons by simp have "a \<le> length l" using eq_comps_elem_le_length Cons by simp have "(\<forall>i j. i < a \<and> a \<le> j \<and> j < length l \<longrightarrow> nth l i < nth l j)" using Cons eq_comps_compare by blast then show ?case using \<open>a \<le> length l\<close> \<open>lst_diff (drop a l) m\<close> by fastforce qed lemma lst_diff_imp_diag_diff: fixes D::"'a::preorder Matrix.mat" assumes "D\<in> carrier_mat n n" and "lst_diff (diag_mat D) m" shows "diag_diff D m" using assms proof (induct arbitrary: n rule:diag_diff.induct) case (1 D) hence "diag_mat D = []" by simp hence "dim_row D = 0" unfolding diag_mat_def by simp hence "n= 0" using 1 by simp hence "dim_col D = 0" using 1 by simp then show ?case using \<open>dim_row D = 0\<close> by simp next case (2 D a xs) define D1 where "D1 = fst (split_block D a a)" define D2 where "D2 = fst (snd (split_block D a a))" define D3 where "D3 = fst (snd (snd (split_block D a a)))" define D4 where "D4 = snd (snd (snd (split_block D a a)))" have spd: "split_block D a a = (D1, D2, D3, D4)" using fst_conv snd_conv unfolding D1_def D2_def D3_def D4_def by simp have "length (diag_mat D) = n" using 2 unfolding diag_mat_def by simp hence "a \<le> n" using 2 by simp hence c1: "D1 \<in> carrier_mat a a" using split_block(1)[OF spd, of "n-a" "n-a"] 2 by simp have c4: "D4 \<in> carrier_mat (n-a) (n-a)" using 2 split_block(4)[OF spd] \<open>a \<le> n\<close> by simp have "diag_mat D = diag_mat D1 @ (diag_mat D4)" using diag_four_block_mat split_block(5) by (metis "2"(2) \<open>a \<le> n\<close> c1 c4 carrier_matD(1) carrier_matD(2) le_Suc_ex spd) have "length (diag_mat D1) = a" using c1 unfolding diag_mat_def by simp hence "diag_mat D4 = drop a (diag_mat D)" using \<open>diag_mat D = diag_mat D1 @ (diag_mat D4)\<close> by simp hence "lst_diff (diag_mat D4) xs" using 2 by simp hence "diag_diff D4 xs" using 2(1)[OF spd[symmetric]] spd c4 by blast have "(\<forall>i j. i < dim_row D1 \<and> j < dim_row D4 \<longrightarrow> D1$$(i,i) < D4 $$ (j,j))" proof (intro allI impI) fix i j assume ijp: "i < dim_row D1 \<and> j < dim_row D4" hence "i < a" using c1 by simp have "j+a < n" using c4 ijp by (metis carrier_matD(1) less_diff_conv) have "D1 $$ (i,i) = D $$ (i,i)" using spd \<open>i < a\<close> unfolding split_block_def Let_def by force also have "... = (diag_mat D)!i" using \<open>i < a\<close> \<open>a \<le> n\<close> 2 unfolding diag_mat_def by simp also have "... < (diag_mat D)!(j+a)" using 2 \<open>j+a < n\<close> by (metis \<open>i < a\<close> \<open>length (diag_mat D) = n\<close> le_add2 lst_diff.simps(2)) also have "... = D $$ (j+a, j+a)" using \<open>j+a < n\<close> 2 unfolding diag_mat_def by simp also have "... = D4 $$ (j,j)" using spd ijp 2 unfolding split_block_def Let_def by force finally show "D1$$(i,i) < D4 $$ (j,j)" . qed hence "(\<forall>i j. i < dim_row D1 \<and> j < dim_row D4 \<longrightarrow> D1$$(i,i) \<noteq> D4 $$ (j,j))" by (metis order_less_irrefl) thus ?case using \<open>diag_diff D4 xs\<close> \<open>a \<le> n\<close> 2 spd by simp qed lemma sorted_diag_diff: fixes D::"'a::linorder Matrix.mat" assumes "D\<in> carrier_mat n n" and "sorted (diag_mat D)" shows "diag_diff D (eq_comps (diag_mat D))" proof (rule lst_diff_imp_diag_diff) show "D \<in> carrier_mat n n" using assms by simp show "lst_diff (diag_mat D) (eq_comps (diag_mat D))" using sorted_lst_diff[of "diag_mat D"] assms by simp qed lemma Re_sorted_lst_diff: fixes l::"complex list" assumes "\<forall> z \<in> set l. z \<in> Reals" and "sorted (map Re l)" and "m = eq_comps l" shows "lst_diff l m" using assms proof (induct m arbitrary: l) case Nil hence "l = []" using eq_comps_empty_if[of l] by simp then show ?case by simp next case (Cons a m) have "sorted (map Re (drop a l))" using Cons sorted_wrt_drop by (metis drop_map) moreover have "m = eq_comps (drop a l)" using eq_comps_drop Cons by simp ultimately have "lst_diff (drop a l) m" using Cons by (metis in_set_dropD) have "a \<le> length l" using eq_comps_elem_le_length Cons by simp have "(\<forall>i j. i < a \<and> a \<le> j \<and> j < length l \<longrightarrow> nth l i < nth l j)" proof (intro allI impI) fix i j assume asm: "i < a \<and> a \<le> j \<and> j < length l" hence "Re (l!i) < Re (l!j)" using Cons eq_comps_compare eq_comp_Re by (smt (z3) dual_order.strict_trans dual_order.strict_trans1 length_map nth_map) moreover have "l!i \<in> Reals" using asm Cons by simp moreover have "l!j \<in> Reals" using asm Cons by simp ultimately show "nth l i < nth l j" using less_complex_def by (simp add: complex_is_Real_iff) qed then show ?case using \<open>a \<le> length l\<close> \<open>lst_diff (drop a l) m\<close> by fastforce qed text \<open>The following lemma states a sufficient condition for the \verb+diag_diff+ predicate to hold.\<close> lemma cpx_sorted_diag_diff: fixes D::"complex Matrix.mat" assumes "D\<in> carrier_mat n n" and "\<forall> i < n. D$$(i,i) \<in> Reals" and "sorted (map Re (diag_mat D))" shows "diag_diff D (eq_comps (diag_mat D))" proof (rule lst_diff_imp_diag_diff) show "D \<in> carrier_mat n n" using assms by simp have "\<forall>z\<in>set (diag_mat D). z \<in> \<real>" using assms unfolding diag_mat_def by auto thus "lst_diff (diag_mat D) (eq_comps (diag_mat D))" using Re_sorted_lst_diff[of "diag_mat D"] assms by simp qed section \<open>Sorted hermitian decomposition\<close> text \<open>We prove that any Hermitian matrix $A$ can be decomposed into a product $U^\dagger \cdot B \cdot U$, where $U$ is a unitary matrix and $B$ is a diagonal matrix containing only real components which are ordered along the diagonal.\<close> definition per_col where "per_col A f = Matrix.mat (dim_row A) (dim_col A) (\<lambda> (i,j). A $$(i, (f j)))" lemma per_col_carrier: assumes "A \<in> carrier_mat n m" shows "per_col A f \<in> carrier_mat n m" using assms unfolding per_col_def by simp lemma per_col_col: assumes "A \<in> carrier_mat n m" and "j < m" shows "Matrix.col (per_col A f) j = Matrix.col A (f j)" proof show dim: "dim_vec (Matrix.col (per_col A f) j) = dim_vec (Matrix.col A (f j))" using per_col_carrier by (metis assms(1) carrier_matD(1) dim_col) fix i assume "i < dim_vec (Matrix.col A (f j))" hence "i < dim_vec (Matrix.col (per_col A f) j)" using dim by simp hence "vec_index (Matrix.col (per_col A f) j) i = (per_col A f)$$(i,j)" unfolding Matrix.col_def by simp also have "... = A $$(i, (f j))" unfolding per_col_def using \<open>i < dim_vec (Matrix.col A (f j))\<close> assms by fastforce also have "... = vec_index (Matrix.col A (f j)) i" unfolding Matrix.col_def using \<open>i < dim_vec (Matrix.col A (f j))\<close> by auto finally show "vec_index (Matrix.col (per_col A f) j) i = vec_index (Matrix.col A (f j)) i" . qed lemma per_col_adjoint_row: assumes "A \<in> carrier_mat n n" and "i < n" and "f i < n" shows "Matrix.row (Complex_Matrix.adjoint (per_col A f)) i = Matrix.row (Complex_Matrix.adjoint A) (f i)" proof - have "per_col A f \<in> carrier_mat n n" using assms per_col_carrier[of A] by simp hence "Matrix.row (Complex_Matrix.adjoint (per_col A f)) i = conjugate (Matrix.col (per_col A f) i)" using assms adjoint_row[of i "per_col A f"] by simp also have "... = conjugate (Matrix.col A (f i))" using assms per_col_col by simp also have "... = Matrix.row (Complex_Matrix.adjoint A) (f i)" using assms adjoint_row[of "f i" A] by simp finally show ?thesis . qed lemma per_col_mult_adjoint: assumes "A \<in> carrier_mat n n" and "i < n" and "j < n" and "f i < n" and "f j < n" shows "((Complex_Matrix.adjoint (per_col A f)) * (per_col A f))$$(i,j) = ((Complex_Matrix.adjoint A) * A)$$(f i, f j)" proof - have "((Complex_Matrix.adjoint (per_col A f)) * (per_col A f))$$(i,j) = Matrix.scalar_prod (Matrix.row (Complex_Matrix.adjoint (per_col A f)) i) (Matrix.col A (f j))" using assms per_col_col unfolding times_mat_def by (metis adjoint_dim_row carrier_matD(2) dim_col_mat(1) index_mat(1) old.prod.case per_col_def) also have "... = Matrix.scalar_prod (Matrix.row (Complex_Matrix.adjoint A) (f i)) (Matrix.col A (f j))" using assms per_col_adjoint_row by metis also have "... = ((Complex_Matrix.adjoint A) * A)$$(f i, f j)" using assms unfolding times_mat_def by simp finally show ?thesis . qed lemma idty_index: assumes "bij_betw f {..< n} {..< n}" and "i < n" and "j < n" shows "(1\<^sub>m n)$$(i,j) = (1\<^sub>m n)$$(f i, f j)" proof - have "f i < n" "f j < n" using assms bij_betwE by auto show ?thesis proof (cases "i = j") case True then show ?thesis using \<open>f i < n\<close> assms by simp next case False hence "f i \<noteq> f j" using assms by (metis bij_betw_iff_bijections lessThan_iff) then show ?thesis by (metis \<open>f i < n\<close> \<open>f j < n\<close> assms(2) assms(3) index_one_mat(1)) qed qed lemma per_col_unitary: assumes "A\<in> carrier_mat n n" and "unitary A" and "bij_betw f {..< n} {..< n}" shows "unitary (per_col A f)" unfolding unitary_def proof show pc: "per_col A f \<in> carrier_mat (dim_row (per_col A f)) (dim_row (per_col A f))" using assms per_col_carrier by (metis carrier_matD(1)) have "dim_row (per_col A f) = n" using assms per_col_carrier by (metis carrier_matD(1)) moreover have "(Complex_Matrix.adjoint (per_col A f)) * (per_col A f) = 1\<^sub>m n" proof (rule eq_matI) show "dim_row (Complex_Matrix.adjoint (per_col A f) * per_col A f) = dim_row (1\<^sub>m n)" using pc by (metis adjoint_dim_row calculation carrier_matD(2) index_mult_mat(2) index_one_mat(2)) thus "dim_col (Complex_Matrix.adjoint (per_col A f) * per_col A f) = dim_col (1\<^sub>m n)" by auto fix i j assume "i < dim_row (1\<^sub>m n)" and "j < dim_col (1\<^sub>m n)" note ij = this have "(Complex_Matrix.adjoint (per_col A f) * per_col A f) $$ (i, j) = (Complex_Matrix.adjoint A * A) $$ (f i, f j)" proof (rule per_col_mult_adjoint) show "A\<in> carrier_mat n n" using assms by simp show "i < n" "j < n" using ij by auto thus "f i < n" using assms by (meson bij_betw_apply lessThan_iff) show "f j < n" using \<open>j < n\<close> assms by (meson bij_betw_apply lessThan_iff) qed also have "... = (1\<^sub>m n) $$ (f i, f j)" using assms unfolding Complex_Matrix.unitary_def by (metis assms(2) unitary_simps(1)) also have "... = (1\<^sub>m n) $$ (i,j)" using idty_index[of f n i j] assms ij by auto finally show "(Complex_Matrix.adjoint (per_col A f) * per_col A f) $$ (i, j) = 1\<^sub>m n $$ (i, j)" . qed ultimately show "inverts_mat (per_col A f) (Complex_Matrix.adjoint (per_col A f))" using inverts_mat_symm inverts_mat_def by (metis (no_types, lifting) adjoint_dim_col adjoint_dim_row carrier_mat_triv index_mult_mat(3) index_one_mat(3)) qed definition per_diag where "per_diag A f = Matrix.mat (dim_row A) (dim_col A) (\<lambda> (i,j). A $$(f i, (f j)))" lemma per_diag_carrier: shows "per_diag A f \<in> carrier_mat (dim_row A) (dim_col A)" unfolding per_diag_def by simp lemma per_diag_diagonal: assumes "D\<in> carrier_mat n n" and "diagonal_mat D" and "bij_betw f {..< n} {..< n}" shows "diagonal_mat (per_diag D f)" unfolding diagonal_mat_def proof (intro allI impI) fix i j assume "i < dim_row (per_diag D f)" and "j < dim_col (per_diag D f)" and "i\<noteq> j" note asm = this hence "f i \<noteq> f j" using assms by (metis bij_betw_iff_bijections carrier_matD(1) carrier_matD(2) lessThan_iff per_diag_carrier) moreover have "f i < n" using assms asm by (metis bij_betwE carrier_matD(1) lessThan_iff per_diag_carrier) moreover have "f j < n" using assms asm by (metis bij_betwE carrier_matD(2) lessThan_iff per_diag_carrier) ultimately show "per_diag D f $$ (i, j) = 0" using assms unfolding per_diag_def diagonal_mat_def by (metis asm(1) asm(2) carrier_matD(1) carrier_matD(2) dim_col_mat(1) dim_row_mat(1) index_mat(1) old.prod.case per_diag_def) qed lemma per_diag_diag_mat: assumes "A \<in> carrier_mat n n" and "i < n" and "f i < n" shows "diag_mat (per_diag A f)!i = diag_mat A ! (f i)" using assms unfolding diag_mat_def per_diag_def by auto lemma per_diag_diag_mat_Re: assumes "A \<in> carrier_mat n n" and "i < n" and "f i < n" shows "map Re (diag_mat (per_diag A f))!i = map Re (diag_mat A) ! (f i)" proof - have "map Re (diag_mat (per_diag A f))!i = Re (diag_mat (per_diag A f)!i)" proof (rule nth_map) show "i < length (diag_mat (per_diag A f))" using assms unfolding diag_mat_def by (metis carrier_matD(1) carrier_matD(2) length_cols_mat_to_cols_list length_map per_diag_carrier) qed also have "... = Re (diag_mat A ! (f i))" using assms per_diag_diag_mat by metis also have "... = map Re (diag_mat A) ! (f i)" unfolding diag_mat_def using assms by auto finally show ?thesis . qed lemma per_diag_real: fixes B::"complex Matrix.mat" assumes "B\<in> carrier_mat n n" and "\<forall>i< n. B$$(i,i) \<in> Reals" and "bij_betw f {..<n} {..<n}" shows "\<forall>j<n. (per_diag B f)$$(j,j) \<in> Reals" proof (intro allI impI) fix j assume "j < n" hence "per_diag B f $$ (j,j) = B $$ (f j, f j)" using assms unfolding per_diag_def by simp also have "... \<in> Reals" using assms \<open>j < n\<close> bij_betwE by blast finally show "per_diag B f $$ (j,j) \<in> Reals" . qed lemma per_col_mult_unitary: fixes A::"complex Matrix.mat" assumes "A \<in> carrier_mat n n" and "unitary A" and "D\<in> carrier_mat n n" and "diagonal_mat D" and "0 < n" and "bij_betw f {..< n} {..< n}" shows "A * D * (Complex_Matrix.adjoint A) = (per_col A f) * (per_diag D f) * (Complex_Matrix.adjoint (per_col A f))" (is "?L = ?R") proof - have row: "dim_row ?L = dim_row ?R" using per_col_carrier assms by (metis carrier_matD(1) index_mult_mat(2)) have col: "dim_col ?L = dim_col ?R" using per_col_carrier assms by (metis adjoint_dim carrier_matD(2) index_mult_mat(3)) define fc::"complex Matrix.mat set" where "fc = carrier_mat n n" interpret cpx_sq_mat n n fc proof show "0 < n" using assms by simp qed (auto simp add: fc_def) define h where "h = (\<lambda>i. (if i < n then diag_mat D ! i \<cdot>\<^sub>m rank_1_proj (Matrix.col A i) else (0\<^sub>m n n)))" define g where "g = (\<lambda>i. (if i < n then diag_mat D ! (f i) \<cdot>\<^sub>m rank_1_proj (Matrix.col A (f i)) else (0\<^sub>m n n)))" have "f ` {..<n} = {..<n}" using assms by (simp add: bij_betw_imp_surj_on) have g: "\<forall>i. g i \<in> fc" unfolding g_def fc_def by (metis adjoint_dim_col assms(1) carrier_matD(1) carrier_matI dim_col fc_mats_carrier rank_1_proj_adjoint rank_1_proj_dim smult_carrier_mat zero_mem) moreover have h:"\<forall>i. h i \<in> fc" unfolding h_def fc_def by (metis assms(1) carrier_matD(1) dim_col fc_mats_carrier rank_1_proj_carrier smult_carrier_mat zero_mem) moreover have "inj_on f {..<n}" using assms(6) bij_betw_def by auto moreover have "\<And>x. x \<in> {..<n} \<Longrightarrow> h (f x) = g x" unfolding h_def g_def by (meson assms(6) bij_betwE lessThan_iff) ultimately have "sum_mat g {..<n} = sum_mat h (f`{..<n})" using sum_with_reindex_cong[of h g f "{..<n}"] unfolding sum_mat_def by simp also have "... = sum_mat h {..<n}" using \<open>f ` {..<n} = {..<n}\<close> by simp also have "... =sum_mat (\<lambda>i. diag_mat D ! i \<cdot>\<^sub>m rank_1_proj (Matrix.col A i)) {..<n}" proof (rule sum_mat_cong, (auto simp add:h h_def)) show "\<And>i. i < n \<Longrightarrow> diag_mat D ! i \<cdot>\<^sub>m rank_1_proj (Matrix.col A i) \<in> fc" using assms unfolding fc_def by (metis fc_mats_carrier h h_def) show "\<And>i. i < n \<Longrightarrow> diag_mat D ! i \<cdot>\<^sub>m rank_1_proj (Matrix.col A i) \<in> fc" using assms unfolding fc_def by (metis fc_mats_carrier h h_def) qed also have "... = A * D * (Complex_Matrix.adjoint A)" using weighted_sum_rank_1_proj_unitary assms unfolding fc_def by simp finally have sg: "sum_mat g {..<n} = A * D * (Complex_Matrix.adjoint A)" . have "(per_col A f) * (per_diag D f) * (Complex_Matrix.adjoint (per_col A f)) = sum_mat (\<lambda>i. diag_mat (per_diag D f) ! i \<cdot>\<^sub>m rank_1_proj (Matrix.col (per_col A f) i)) {..<n}" proof (rule weighted_sum_rank_1_proj_unitary[symmetric]) show "per_col A f \<in> fc" using per_col_carrier[of A] assms unfolding fc_def by simp show "per_diag D f \<in> fc" using per_diag_carrier[of D] assms unfolding fc_def by simp show "diagonal_mat (per_diag D f)" using assms per_diag_diagonal[of D] by simp show "unitary (per_col A f)" using per_col_unitary[of A] assms by simp qed also have "... = sum_mat g {..<n}" proof (rule sum_mat_cong, (auto simp add: g_def)) show "\<And>i. i < n \<Longrightarrow> diag_mat (per_diag D f) ! i \<cdot>\<^sub>m rank_1_proj (Matrix.col (per_col A f) i) \<in> fc" proof - fix i assume "i < n" have "dim_vec (Matrix.col (per_col A f) i) = n" using assms per_col_col by (metis carrier_matD(1) dim_col) hence "rank_1_proj (Matrix.col (per_col A f) i) \<in> fc" unfolding fc_def using rank_1_proj_carrier by blast thus "diag_mat (per_diag D f) ! i \<cdot>\<^sub>m rank_1_proj (Matrix.col (per_col A f) i) \<in> fc" unfolding fc_def by simp qed show "\<And>i. i < n \<Longrightarrow> diag_mat D ! f i \<cdot>\<^sub>m rank_1_proj (Matrix.col A (f i)) \<in> fc" proof - fix i assume "i < n" hence "f i < n" using \<open>f ` {..<n} = {..<n}\<close> by auto hence "dim_vec (Matrix.col A (f i)) = n" using assms by (metis carrier_matD(1) dim_col) hence "rank_1_proj (Matrix.col A (f i)) \<in> fc" unfolding fc_def using rank_1_proj_carrier by blast thus "diag_mat D ! f i \<cdot>\<^sub>m rank_1_proj (Matrix.col A (f i)) \<in> fc" unfolding fc_def by simp qed show "\<And>i. i < n \<Longrightarrow> diag_mat (per_diag D f) ! i \<cdot>\<^sub>m rank_1_proj (Matrix.col (per_col A f) i) = diag_mat D ! f i \<cdot>\<^sub>m rank_1_proj (Matrix.col A (f i))" proof- fix i assume "i < n" hence "f i < n" using \<open>f ` {..<n} = {..<n}\<close> by auto have "Matrix.col (per_col A f) i = Matrix.col A (f i)" using per_col_col assms \<open>i < n\<close> by simp hence "rank_1_proj (Matrix.col (per_col A f) i) = rank_1_proj (Matrix.col A (f i))" by simp thus "diag_mat (per_diag D f) ! i \<cdot>\<^sub>m rank_1_proj (Matrix.col (per_col A f) i) = diag_mat D ! f i \<cdot>\<^sub>m rank_1_proj (Matrix.col A (f i))" using assms per_diag_diag_mat[of D] \<open>i < n\<close> \<open>f i < n\<close> by simp qed qed also have "... = A * D * (Complex_Matrix.adjoint A)" using sg by simp finally have "(per_col A f) * (per_diag D f) * (Complex_Matrix.adjoint (per_col A f)) = A * D * (Complex_Matrix.adjoint A)" . thus ?thesis by simp qed lemma sort_permutation: assumes "m = sort l" obtains f where "bij_betw f {..<length l} {..<length l} \<and> (\<forall>i<length l. l ! f i = m ! i)" proof - have "length l = length m" using assms by simp have "mset l = mset m" using assms by simp from this obtain p where "p permutes {..<length m}" "permute_list p l = m" by (metis \<open>length l = length m\<close> mset_eq_permutation) note pprop = this have "bij_betw p {..<length l} {..<length l}" using pprop \<open>length l = length m\<close> by (simp add: permutes_imp_bij) moreover have "\<forall>i<length l. l ! p i = m ! i" using pprop by (metis \<open>length l = length m\<close> permute_list_nth) ultimately have "\<exists>f. bij_betw f {..<length l} {..<length l} \<and> (\<forall>i<length l. l ! f i = m ! i)" by auto thus ?thesis using that by auto qed lemma per_diag_sorted_Re: fixes B::"complex Matrix.mat" assumes "B\<in> carrier_mat n n" obtains f where "bij_betw f {..< n} {..< n} \<and> map Re (diag_mat (per_diag B f)) = sort (map Re (diag_mat B))" proof - define m where "m = sort (map Re (diag_mat B))" have "length m = length (map Re (diag_mat B))" unfolding m_def by simp also have "... = length (diag_mat B)" by simp also have "... = n" using assms unfolding diag_mat_def by simp finally have "length m = n" . from this obtain f where "bij_betw f {..<n} {..<n} \<and> (\<forall>i<n. (map Re (diag_mat B)) ! f i = m ! i)" using sort_permutation[of m "map Re (diag_mat B)"] m_def by auto note fprop = this have l: "length (diag_mat (per_diag B f)) = length m" using per_diag_carrier assms \<open>length m = n\<close> unfolding diag_mat_def by (metis carrier_matD(1) length_map map_nth) have "map Re (diag_mat (per_diag B f)) = m" proof (rule list_eq_iff_nth_eq[THEN iffD2], intro conjI) show "length (map Re (diag_mat (per_diag B f))) = length m" using l by simp have "\<forall>i<n. (map Re (diag_mat (per_diag B f)))!i = m!i" proof (intro allI impI) fix i assume "i< n" have "(map Re (diag_mat (per_diag B f)))!i = (map Re (diag_mat B))!(f i)" proof (rule per_diag_diag_mat_Re) show "B\<in> carrier_mat n n" using assms by simp show "i < n" using \<open>i < n\<close> . thus "f i < n" using fprop bij_betwE by blast qed also have "... = m!i" using fprop \<open>i < n\<close> by simp finally show "(map Re (diag_mat (per_diag B f)))!i = m!i" . qed thus "\<forall>i<length (map Re (diag_mat (per_diag B f))). (map Re (diag_mat (per_diag B f)))!i = m ! i" using l \<open>length m = n\<close> by simp qed thus ?thesis using that fprop unfolding m_def by auto qed lemma bij_unitary_diag: fixes A::"complex Matrix.mat" assumes "unitary_diag A B U" and "A \<in> carrier_mat n n" and "bij_betw f {..<n} {..<n}" and "0 < n" shows "unitary_diag A (per_diag B f) (per_col U f)" proof (intro unitary_diagI) show "unitary (per_col U f)" using assms unitary_diagD(1) unitary_diagD(3) per_col_unitary by (metis similar_mat_witD2(6)) show "diagonal_mat (per_diag B f)" using assms unitary_diagD(2) per_diag_diagonal by (metis similar_mat_witD2(5) unitary_diagD(1)) have "A = U * B * (Complex_Matrix.adjoint U)" using assms unitary_diagD similar_mat_witD2(3) unitary_diagD(1) by blast also have "... = (per_col U f) * (per_diag B f) * (Complex_Matrix.adjoint (per_col U f))" using assms per_col_mult_unitary by (meson similar_mat_witD2(5) similar_mat_witD2(6) unitary_diagD(1) unitary_diagD(2) unitary_diagD(3)) finally have eq: "A = per_col U f * per_diag B f * Complex_Matrix.adjoint (per_col U f)" . show "similar_mat_wit A (per_diag B f) (per_col U f) (Complex_Matrix.adjoint (per_col U f))" unfolding similar_mat_wit_def Let_def proof (intro conjI) have "A\<in> carrier_mat n n" using assms by simp moreover have "per_diag B f \<in> carrier_mat n n" using assms unitary_diagD(1) per_diag_carrier[of B] by (metis carrier_matD(1) carrier_matD(2) similar_mat_witD2(5)) moreover have "per_col U f \<in> carrier_mat n n" using assms unitary_diagD(1) per_col_carrier[of U] by (metis similar_mat_witD2(6)) moreover hence "Complex_Matrix.adjoint (per_col U f) \<in> carrier_mat n n" by (simp add: adjoint_dim) ultimately show "{A, per_diag B f, per_col U f, Complex_Matrix.adjoint (per_col U f)} \<subseteq> carrier_mat (dim_row A) (dim_row A)" by auto show "per_col U f * Complex_Matrix.adjoint (per_col U f) = 1\<^sub>m (dim_row A)" using \<open>Complex_Matrix.unitary (per_col U f)\<close> assms(2) \<open>per_col U f \<in> carrier_mat n n\<close> by auto show "Complex_Matrix.adjoint (per_col U f) * per_col U f = 1\<^sub>m (dim_row A)" using \<open>Complex_Matrix.unitary (per_col U f)\<close> assms \<open>per_col U f \<in> carrier_mat n n\<close> by auto qed (simp add: eq) qed lemma hermitian_real_diag_sorted: assumes "A \<in> carrier_mat n n" and "0 < n" and "hermitian A" obtains Bs Us where "real_diag_decomp A Bs Us \<and> sorted (map Re (diag_mat Bs))" proof - obtain U1 B1 where "real_diag_decomp A B1 U1" using hermitian_real_diag_decomp[of A] assms by auto note ubprop = this hence "B1 \<in> carrier_mat n n" using assms unfolding real_diag_decomp_def by (meson unitary_diag_carrier(1)) from this obtain f where "bij_betw f {..< n} {..< n} \<and> map Re (diag_mat (per_diag B1 f)) = sort (map Re (diag_mat B1))" using per_diag_sorted_Re by auto note fprop = this define Bs where "Bs = per_diag B1 f" define Us where "Us = per_col U1 f" have "unitary_diag A Bs Us" unfolding Bs_def Us_def proof (rule bij_unitary_diag) show "unitary_diag A B1 U1" using ubprop unfolding real_diag_decomp_def by simp show "A \<in> carrier_mat n n" using assms by simp show "bij_betw f {..<n} {..<n}" using fprop by simp show "0 < n" using assms by simp qed have "real_diag_decomp A Bs Us" unfolding real_diag_decomp_def proof (simp add: \<open>unitary_diag A Bs Us\<close>) show "\<forall>i<dim_row Bs. Bs $$ (i, i) \<in> \<real>" unfolding Bs_def proof (rule per_diag_real) show br: "B1 \<in> carrier_mat (dim_row (per_diag B1 f)) (dim_row (per_diag B1 f))" by (metis \<open>B1 \<in> carrier_mat n n\<close> carrier_matD(1) per_diag_carrier) thus "\<forall>i<dim_row (per_diag B1 f). B1 $$ (i, i) \<in> \<real>" using ubprop by auto show "bij_betw f {..<dim_row (per_diag B1 f)} {..<dim_row (per_diag B1 f)}" using fprop by (metis br \<open>B1 \<in> carrier_mat n n\<close> carrier_matD(1)) qed qed moreover have "sorted (map Re (diag_mat Bs))" using fprop unfolding Bs_def by simp ultimately show ?thesis using that by simp qed section \<open>Commuting Hermitian families\<close> text \<open>This part is devoted to the proof that a finite family of commuting Hermitian matrices is simultaneously diagonalizable.\<close> subsection \<open>Intermediate properties\<close> lemma real_diag_decomp_mult_dbm_unit: assumes "A \<in> carrier_mat n n" and "real_diag_decomp A B U" and "B = diag_block_mat Bl" and "length Ul = length Bl" and "\<forall>i < length Bl. dim_col (Bl!i) = dim_row (Bl!i)" and "\<forall>i < length Bl. dim_row (Bl!i) = dim_row (Ul!i)" and "\<forall>i < length Bl. dim_col (Bl!i) = dim_col (Ul!i)" and "unitary (diag_block_mat Ul)" and "\<forall>i<length Ul. Ul ! i * Bl ! i = Bl ! i * Ul ! i" shows "real_diag_decomp A B (U * (diag_block_mat Ul))" unfolding real_diag_decomp_def proof (intro conjI allI impI) have "B\<in> carrier_mat n n" by (meson assms(1) assms(2) real_diag_decompD(1) unitary_diag_carrier(1)) have "dim_row (diag_block_mat Ul) = dim_row B" using diag_block_mat_dim_row_cong assms by blast moreover have "dim_col (diag_block_mat Ul) = dim_col B" using diag_block_mat_dim_col_cong assms by blast ultimately have "diag_block_mat Ul \<in> carrier_mat n n" using assms by (metis \<open>B \<in> carrier_mat n n\<close> carrier_matD(1) carrier_matD(2) carrier_mat_triv) define Uf where "Uf = U * (diag_block_mat Ul)" show "\<And>i. i < dim_row B \<Longrightarrow> B $$ (i, i) \<in> \<real>" using assms real_diag_decompD(2) \<open>B \<in> carrier_mat n n\<close> by auto show "unitary_diag A B Uf" unfolding unitary_diag_def proof show "diagonal_mat B" using assms real_diag_decompD(2) real_diag_decompD(1) unitary_diagD(2) by blast show "unitarily_equiv A B Uf" unfolding Uf_def proof (rule conjugate_eq_unitarily_equiv) show "A\<in> carrier_mat n n" using assms by simp show "unitarily_equiv A B U" using assms real_diag_decompD(1) unfolding unitary_diag_def by simp show "diag_block_mat Ul \<in> carrier_mat n n" using \<open>diag_block_mat Ul \<in> carrier_mat n n\<close> . show "unitary (diag_block_mat Ul)" using assms by simp have "mat_conj (diag_block_mat Ul) (diag_block_mat Bl) = diag_block_mat Bl" proof (rule mat_conj_unit_commute) show "unitary (diag_block_mat Ul)" using \<open>unitary (diag_block_mat Ul)\<close> . show "diag_block_mat Bl \<in> carrier_mat n n" using assms \<open>B \<in> carrier_mat n n\<close> by simp show "diag_block_mat Ul \<in> carrier_mat n n" using \<open>diag_block_mat Ul \<in> carrier_mat n n\<close> . show "diag_block_mat Ul * diag_block_mat Bl = diag_block_mat Bl * diag_block_mat Ul" proof (rule diag_block_mat_commute) show "length Ul = length Bl" using assms by simp show comm: "\<forall>i<length Ul. Ul ! i * Bl ! i = Bl ! i * Ul ! i" using assms by simp show "\<forall>i<length Ul. dim_col (Ul ! i) = dim_row (Bl ! i)" using assms by presburger thus "\<forall>i<length Ul. dim_col (Bl ! i) = dim_row (Ul ! i)" by (metis comm index_mult_mat(2) index_mult_mat(3)) qed qed thus "diag_block_mat Ul * B * Complex_Matrix.adjoint (diag_block_mat Ul) = B" using \<open>B = diag_block_mat Bl\<close> unfolding mat_conj_def by simp qed qed qed lemma real_diag_decomp_block_set: assumes "Als \<noteq> {}" and "0 < n" and "\<forall> Al \<in> Als. length Al = n" and "\<forall>i < n. \<forall> Al \<in> Als. dim_row (Al!i) = dim_col (Al!i)" and "\<forall>i < n. \<exists>U. \<forall> Al \<in> Als. \<exists>B. real_diag_decomp (Al!i) B U" shows "\<exists>Ul. (length Ul = n \<and> (\<forall>i <n. \<forall>Al \<in> Als. (dim_row (Ul!i) = dim_row (Al!i) \<and> dim_col (Ul!i) = dim_col (Al!i)))\<and> (\<forall> Al \<in> Als. \<exists>Bl. (length Bl = n \<and> real_diag_decomp (diag_block_mat Al) (diag_block_mat Bl) (diag_block_mat Ul))))" using assms proof (induct n arbitrary: Als) case 0 then show ?case by simp next case (Suc n) hence "\<exists>U. \<forall> Al \<in> Als. \<exists>B. real_diag_decomp (Al!0) B U" by simp from this obtain U0 where "\<forall> Al \<in> Als. \<exists>B. real_diag_decomp (Al!0) B U0" by auto note u0 = this have u0_dim: "\<forall>Al\<in>Als. dim_row ([U0] ! 0) = dim_row (Al ! 0) \<and> dim_col ([U0] ! 0) = dim_col (Al ! 0)" proof (intro allI impI ballI) fix Al assume "Al \<in> Als" have "[U0]!0 = U0" by simp have "\<exists>B. real_diag_decomp (Al!0) B U0" using u0 \<open>Al \<in> Als\<close> by simp from this obtain B where "real_diag_decomp (Al!0) B U0" by auto moreover have "dim_row (Al!0) = dim_col (Al!0)" using \<open>Al\<in> Als\<close> Suc by simp ultimately have "dim_row U0 = dim_row (Al!0)" using unitary_diag_carrier(2) by (metis carrier_matD(1) carrier_matI real_diag_decompD(1)) moreover have "dim_col U0 = dim_col (Al!0)" using \<open>real_diag_decomp (Al!0) B U0\<close> \<open>dim_row (Al!0) = dim_col (Al!0)\<close> using real_diag_decompD(1) unitary_diag_carrier(2) by (metis carrier_matD(2) carrier_mat_triv) ultimately show "dim_row ([U0] ! 0) = dim_row (Al ! 0) \<and> dim_col ([U0] ! 0) = dim_col (Al ! 0)" by simp qed show ?case proof (cases "n = 0") case True hence "\<forall> Al \<in> Als. diag_block_mat Al = Al!0" using Suc by (simp add: diag_block_mat_length_1) have "\<forall> Al \<in> Als. \<exists>Bl. (length Bl = 1 \<and> real_diag_decomp (diag_block_mat Al) (diag_block_mat Bl) (diag_block_mat [U0]))" proof fix Al assume "Al \<in> Als" hence "\<exists>B. real_diag_decomp (Al!0) B U0" using u0 by simp from this obtain B where "real_diag_decomp (Al!0) B U0" by auto hence "real_diag_decomp (diag_block_mat Al) (diag_block_mat [B]) (diag_block_mat [U0])" by (metis \<open>Al \<in> Als\<close> \<open>\<forall>Al\<in>Als. diag_block_mat Al = Al ! 0\<close> diag_block_mat_singleton) moreover have "length [B] = 1" by simp ultimately show "\<exists>Bl. (length Bl = 1 \<and> real_diag_decomp (diag_block_mat Al) (diag_block_mat Bl) (diag_block_mat [U0]))" by blast qed moreover have "length [U0] = 1" by simp moreover have "\<forall>i<Suc n. \<forall>Al\<in>Als. dim_row ([U0] ! i) = dim_row (Al ! i) \<and> dim_col ([U0] ! i) = dim_col (Al ! i)" using u0_dim \<open>n = 0\<close> by simp ultimately have "length [U0] = Suc 0 \<and> (\<forall>i<Suc n. \<forall>Al\<in>Als. dim_row ([U0] ! i) = dim_row (Al ! i) \<and> dim_col ([U0] ! i) = dim_col (Al ! i)) \<and> (\<forall>Al\<in>Als. \<exists>Bl. length Bl = Suc n \<and> real_diag_decomp (diag_block_mat Al) (diag_block_mat Bl) (diag_block_mat [U0]))" using \<open>n=0\<close> One_nat_def by metis thus ?thesis by (metis True) next case False hence "0 < n" by simp define tAls where "tAls = tl `Als" have tex: "\<forall>tAl\<in> tAls. \<exists>Al \<in> Als. tAl = tl Al" unfolding tAls_def by auto have "\<exists>Ul. length Ul = n \<and> (\<forall>i <n. \<forall>Al \<in> tAls. (dim_row (Ul!i) = dim_row (Al!i) \<and> dim_col (Ul!i) = dim_col (Al!i)))\<and> (\<forall>Al\<in>tAls. \<exists>Bl. length Bl = n \<and> real_diag_decomp (diag_block_mat Al) (diag_block_mat Bl) (diag_block_mat Ul))" proof (rule Suc(1)) show "tAls \<noteq> {}" "0 < n" unfolding tAls_def by (auto simp add: \<open>0 < n\<close> Suc) show "\<forall>tAl\<in>tAls. length tAl = n" using Suc(4) tex by fastforce show "\<forall>i<n. \<exists>U. \<forall>Al\<in>tAls. \<exists>B. real_diag_decomp (Al ! i) B U" proof (intro allI impI) fix i assume "i < n" hence "\<exists>U. \<forall>Al\<in>Als. \<exists>B. real_diag_decomp (Al ! (Suc i)) B U" using Suc Suc_mono by presburger from this obtain U where tu: "\<forall>Al\<in>Als. \<exists>B. real_diag_decomp (Al ! (Suc i)) B U" by auto have "\<forall>tAl\<in>tAls. \<exists>B. real_diag_decomp (tAl ! i) B U" proof fix tAl assume "tAl \<in> tAls" hence "\<exists>Al \<in> Als. tAl = tl Al" using tex by simp from this obtain Al where "Al \<in> Als" and "tAl = tl Al" by auto hence "tAl!i = Al!(Suc i)" by (simp add: Suc(4) \<open>i < n\<close> nth_tl) moreover have "\<exists>B. real_diag_decomp (Al!(Suc i)) B U" using tu \<open>Al \<in> Als\<close> by simp ultimately show "\<exists>B. real_diag_decomp (tAl ! i) B U" by simp qed thus "\<exists>U. \<forall>Al\<in>tAls. \<exists>B. real_diag_decomp (Al ! i) B U" by auto qed show "\<forall>i < n. \<forall>Al\<in>tAls. dim_row (Al!i) = dim_col (Al!i)" by (metis Suc(5) \<open>\<forall>tAl\<in>tAls. length tAl = n\<close> not_less_eq nth_tl tex) qed from this obtain Ul where "length Ul = n" and "\<forall>i <n. \<forall>Al \<in> tAls. (dim_row (Ul!i) = dim_row (Al!i) \<and> dim_col (Ul!i) = dim_col (Al!i))" "(\<forall>Al\<in>tAls. \<exists>Bl. length Bl = n \<and> real_diag_decomp (diag_block_mat Al) (diag_block_mat Bl) (diag_block_mat Ul))" by auto note ulprop = this have "\<forall>Al\<in>Als. \<exists>Bl. length Bl = Suc n \<and> real_diag_decomp (diag_block_mat Al) (diag_block_mat Bl) (diag_block_mat (U0#Ul))" proof fix Al assume "Al \<in> Als" hence "0 < length Al" using Suc by simp hence "Al = hd Al # (tl Al)" by simp have "\<exists>B. real_diag_decomp (Al!0) B U0" using u0 \<open>Al\<in> Als\<close> by simp from this obtain B0 where b0: "real_diag_decomp (Al!0) B0 U0" by auto hence "real_diag_decomp (hd Al) B0 U0" by (metis \<open>Al = hd Al # tl Al\<close> nth_Cons_0) have "tl Al \<in> tAls" using \<open>Al \<in> Als\<close> unfolding tAls_def by simp hence "\<exists>Bl. length Bl = n \<and> real_diag_decomp (diag_block_mat (tl Al)) (diag_block_mat Bl) (diag_block_mat Ul)" using ulprop by simp from this obtain Bl where "length Bl = n" and rl: "real_diag_decomp (diag_block_mat (tl Al)) (diag_block_mat Bl) (diag_block_mat Ul)" by auto have "dim_row (diag_block_mat (tl Al)) = dim_col (diag_block_mat (tl Al))" using Suc \<open>Al \<in> Als\<close> diag_block_mat_dim_row_col_eq by (metis (no_types, lifting) \<open>Al = hd Al # tl Al\<close> length_Cons lessI less_trans_Suc nth_tl) moreover have "dim_row (Al ! 0) = dim_col (Al ! 0)" using Suc \<open>Al \<in> Als\<close> by simp ultimately have "real_diag_decomp (diag_block_mat ((hd Al)#(tl Al))) (diag_block_mat (B0#Bl)) (diag_block_mat (U0#Ul))" using four_block_real_diag_decomp[OF rl b0] diag_block_mat.simps(2) real_diag_decomp_hermitian by (metis \<open>Al = hd Al # tl Al\<close> b0 four_block_real_diag_decomp nth_Cons_0 rl) moreover have "length (B0#Bl) = Suc n" using \<open>length Bl = n\<close> by simp ultimately show "\<exists>Bl. length Bl = Suc n \<and> real_diag_decomp (diag_block_mat Al) (diag_block_mat Bl) (diag_block_mat (U0#Ul))" using \<open>Al = hd Al # tl Al\<close> by metis qed moreover have "length (U0#Ul) = Suc n" using ulprop by simp moreover have "\<forall>i<Suc n. \<forall>Al\<in>Als. dim_row ((U0#Ul) ! i) = dim_row (Al ! i) \<and> dim_col ((U0#Ul) ! i) = dim_col (Al ! i)" proof (intro allI impI ballI) fix i Al assume "i < Suc n" and "Al \<in> Als" show "dim_row ((U0 # Ul) ! i) = dim_row (Al ! i) \<and> dim_col ((U0 # Ul) ! i) = dim_col (Al ! i)" proof (cases "i = 0") case True then show ?thesis using \<open>Al \<in> Als\<close> u0_dim by simp next case False hence "\<exists>j. i = Suc j" by (simp add: not0_implies_Suc) from this obtain j where "i = Suc j" by auto hence "(U0#Ul)!i = Ul!j" by simp have "tl Al \<in> tAls" using \<open>Al \<in> Als\<close> unfolding tAls_def by simp moreover have "Al!i = (tl Al)!j" using \<open>i = Suc j\<close> by (metis Suc.prems(3) Zero_not_Suc \<open>Al \<in> Als\<close> diag_block_mat.cases list.sel(3) list.size(3) nth_Cons_Suc) ultimately show ?thesis using \<open>(U0#Ul)!i = Ul!j\<close> by (metis Suc_less_SucD \<open>i < Suc n\<close> \<open>i = Suc j\<close> ulprop(2)) qed qed ultimately show ?thesis by blast qed qed lemma real_diag_decomp_eq_comps_props: assumes "Ap\<in> carrier_mat n n" and "0 < n" and "real_diag_decomp Ap Bs Us \<and> sorted (map Re (diag_mat Bs))" shows "Bs \<in> carrier_mat n n" "diagonal_mat Bs" "unitary Us" "Us \<in> carrier_mat n n" "diag_diff Bs (eq_comps (diag_mat Bs))" "eq_comps (diag_mat Bs) \<noteq> []" "diag_mat Bs \<noteq> []" proof - show "Bs \<in> carrier_mat n n" using assms real_diag_decompD(1) unitary_diag_carrier(1) by blast thus "diag_mat Bs \<noteq> []" using \<open>0 < n\<close> unfolding diag_mat_def by simp show "diagonal_mat Bs" using assms using real_diag_decompD(1) unitary_diagD(2) by blast show "unitary Us" using unitary_diagD(3) assms unfolding real_diag_decomp_def by auto show "Us \<in> carrier_mat n n" using assms real_diag_decompD(1) unitary_diag_carrier(2) by blast define eqcl where "eqcl = eq_comps (diag_mat Bs)" show "diag_diff Bs eqcl" unfolding eqcl_def proof (rule cpx_sorted_diag_diff) show "Bs \<in> carrier_mat n n" using \<open>Bs \<in> carrier_mat n n\<close> . show "sorted (map Re (diag_mat Bs))" using assms by simp show "\<forall>i<n. Bs $$ (i, i) \<in> \<real>" using assms real_diag_decompD(2) \<open>Bs \<in> carrier_mat n n\<close> by auto qed show "eqcl \<noteq> []" using eq_comps_not_empty[of "diag_mat Bs"] \<open>Bs \<in> carrier_mat n n\<close> assms unfolding eqcl_def diag_mat_def by (simp add: assms) qed lemma commuting_conj_mat_set_props: fixes As::"'a::conjugatable_field Matrix.mat set" and U::"'a Matrix.mat" assumes "finite As" and "card As \<le> i" and "\<forall>A\<in> As. hermitian A \<and> A\<in> carrier_mat n n" and "\<forall> A\<in> As. \<forall> B \<in> As. A*B = B*A" and "unitary U" and "U \<in> carrier_mat n n" and "CjA = (\<lambda>A2. mat_conj (Complex_Matrix.adjoint U) A2)`As" shows "finite CjA" "card CjA \<le> i" "\<forall>A\<in> CjA. A\<in> carrier_mat n n \<and> hermitian A" "\<forall> C1\<in> CjA. \<forall>C2\<in> CjA. C1*C2 = C2*C1" proof - define Cj where "Cj = (\<lambda>A2. mat_conj (Complex_Matrix.adjoint U) A2)" have "CjA = Cj`As" using assms unfolding Cj_def by simp show "finite CjA" using assms by simp show "card CjA \<le> i" using \<open>card As \<le> i\<close> \<open>finite As\<close> card_image_le dual_order.trans assms by blast show "\<forall>A\<in> CjA. A\<in> carrier_mat n n \<and> hermitian A" proof(intro ballI conjI) fix A assume "A\<in> CjA" hence "\<exists>nA \<in> As. A = Cj nA" using assms unfolding Cj_def by auto from this obtain nA where "nA\<in> As" and "A = Cj nA" by auto have "hermitian nA" using assms \<open>nA \<in> As\<close> by auto thus "hermitian A" using assms \<open>A = Cj nA\<close> hermitian_mat_conj'[of nA n U] \<open>nA\<in> As\<close> Cj_def mat_conj_adjoint by fastforce show "A\<in> carrier_mat n n" using \<open>nA\<in> As\<close> \<open>A = Cj nA\<close> unfolding Cj_def by (metis \<open>hermitian A\<close> adjoint_dim_row assms(6) carrier_matD(2) hermitian_square index_mult_mat(2) mat_conj_adjoint) qed show "\<forall> C1\<in> CjA. \<forall>C2\<in> CjA. C1*C2 = C2*C1" proof (intro ballI) fix C1 C2 assume "C1 \<in> CjA" and "C2\<in> CjA" hence "\<exists> A1\<in> As. C1 = mat_conj (Complex_Matrix.adjoint U) A1" using assms unfolding Cj_def by auto from this obtain A1 where "A1\<in> As" and "C1 = mat_conj (Complex_Matrix.adjoint U) A1" by auto have "\<exists> A2\<in> As. C2 = mat_conj (Complex_Matrix.adjoint U) A2" using \<open>C2\<in> CjA\<close> assms unfolding Cj_def by auto from this obtain A2 where "A2\<in> As" and "C2 = mat_conj (Complex_Matrix.adjoint U) A2" by auto have "mat_conj (Complex_Matrix.adjoint U) A1 * mat_conj (Complex_Matrix.adjoint U) A2 = mat_conj (Complex_Matrix.adjoint U) A2 * mat_conj (Complex_Matrix.adjoint U) A1" proof (rule mat_conj_commute) show "unitary U" using \<open>unitary U\<close> . show "A1\<in> carrier_mat n n" using \<open>A1\<in> As\<close> assms by simp show "A2\<in> carrier_mat n n" using \<open>A2\<in> As\<close> assms by simp show "U \<in> carrier_mat n n" using \<open>U \<in> carrier_mat n n\<close> . show "A1 * A2 = A2 * A1" using \<open>A1\<in> As\<close> \<open>A2\<in> As\<close> assms by simp qed thus "C1 * C2 = C2 * C1" using \<open>C1 = mat_conj (Complex_Matrix.adjoint U) A1\<close> \<open>C2 = mat_conj (Complex_Matrix.adjoint U) A2\<close> by simp qed qed lemma commute_extract_diag_block_eq: fixes Ap::"complex Matrix.mat" assumes "Ap\<in> carrier_mat n n" and "0 < n" and "real_diag_decomp Ap Bs Us \<and> sorted (map Re (diag_mat Bs))" and "finite Afp" and "card Afp \<le> i" and "\<forall>A\<in>Afp. hermitian A \<and> A \<in> carrier_mat n n" and "\<forall>A\<in>Afp. \<forall>B\<in>Afp. A * B = B * A" and "\<forall>A\<in> Afp. Ap * A = A * Ap" and "CjA = (\<lambda>A2. mat_conj (Complex_Matrix.adjoint Us) A2)`Afp" and "eqcl = eq_comps (diag_mat Bs)" shows "\<forall>C \<in> CjA. C = diag_block_mat (extract_subdiags C eqcl)" proof note ubprops = real_diag_decomp_eq_comps_props[OF assms(1) assms(2) assms(3)] note cjprops = commuting_conj_mat_set_props[OF assms(4) assms(5) assms(6) assms(7) ubprops(3) ubprops(4) assms(9)] fix C assume "C\<in> CjA" hence "\<exists>Ac \<in> Afp. C = mat_conj (Complex_Matrix.adjoint Us) Ac" using assms by auto from this obtain Ac where "Ac \<in> Afp" and "C = mat_conj (Complex_Matrix.adjoint Us) Ac" by auto show "C = diag_block_mat (extract_subdiags C eqcl)" proof (rule diag_compat_extract_subdiag) show "C \<in> carrier_mat n n" using cjprops \<open>C\<in> CjA\<close> by simp show "diag_compat C eqcl" proof (rule commute_diag_compat) show "Bs \<in> carrier_mat n n" using \<open>Bs \<in> carrier_mat n n\<close> . show "diag_diff Bs eqcl" using ubprops assms by simp show "diagonal_mat Bs" using \<open>diagonal_mat Bs\<close> . show "C \<in> carrier_mat n n" using \<open>C \<in> carrier_mat n n\<close> . have "Bs * (Complex_Matrix.adjoint Us * Ac * Us) = Complex_Matrix.adjoint Us * Ac * Us * Bs" proof (rule unitarily_equiv_commute) show "unitarily_equiv Ap Bs Us" using assms real_diag_decompD(1) by simp show "Ap * Ac = Ac * Ap" using assms \<open>Ac \<in> Afp\<close> by simp qed thus "C * Bs = Bs * C" using \<open>C = mat_conj (Complex_Matrix.adjoint Us) Ac\<close> by (metis mat_conj_adjoint) qed qed qed lemma extract_dbm_eq_component_commute: assumes "\<forall>C\<in>Cs. C = diag_block_mat (extract_subdiags C l)" and "\<forall>C1\<in>Cs. \<forall>C2\<in>Cs. C1 * C2 = C2 * C1" and "ExC = (\<lambda>A. extract_subdiags A l)`Cs" and "j < length l" and "Exi = (\<lambda>A. (A!j))` ExC" and "Al \<in> Exi" and "Bl\<in> Exi" shows "Al * Bl = Bl * Al" proof - define ncl where "ncl = length l" have "\<forall>Al\<in>ExC. length Al = ncl" by (simp add: assms extract_subdiags_length ncl_def) have "\<exists>Ea \<in> ExC. Al = Ea!j" using assms by auto from this obtain Ea where "Ea\<in> ExC" and "Al = Ea!j" by auto have "\<exists>Eb \<in> ExC. Bl = Eb!j" using assms by auto from this obtain Eb where "Eb\<in> ExC" and "Bl = Eb!j" by auto have "\<forall>j<ncl. \<forall>E\<in>ExC. E ! j \<in> carrier_mat (l ! j) (l ! j)" by (metis (no_types, lifting) assms(3) extract_subdiags_carrier imageE ncl_def) hence "\<forall>i < ncl. \<forall>Al\<in>ExC. dim_row (Al ! i) = dim_col (Al ! i)" by (metis carrier_matD(1) carrier_matD(2)) have "Ea!j * Eb!j = Eb!j * Ea!j" proof (rule diag_block_mat_commute_comp) show "length Ea = length Eb" by (simp add: \<open>Ea \<in> ExC\<close> \<open>Eb \<in> ExC\<close> \<open>\<forall>Al\<in>ExC. length Al = ncl\<close>) show "j < length Ea" by (metis \<open>Eb \<in> ExC\<close> \<open>\<forall>Al\<in>ExC. length Al = ncl\<close> \<open>j < length l\<close> ncl_def \<open>length Ea = length Eb\<close>) show "\<forall>i<length Ea. dim_row (Ea ! i) = dim_col (Ea ! i)" by (simp add: \<open>Ea \<in> ExC\<close> \<open>\<forall>Al\<in>ExC. length Al = ncl\<close> \<open>\<forall>i < ncl. \<forall>Al\<in>ExC. dim_row (Al ! i) = dim_col (Al ! i)\<close>) show "\<forall>i<length Ea. dim_row (Ea ! i) = dim_row (Eb ! i)" by (metis \<open>Ea \<in> ExC\<close> \<open>Eb \<in> ExC\<close> \<open>\<forall>Al\<in>ExC. length Al = ncl\<close> \<open>\<forall>j<ncl. \<forall>E\<in>ExC. E ! j \<in> carrier_mat (l ! j) (l ! j)\<close> carrier_matD(1)) show "\<forall>i<length Ea. dim_col (Ea ! i) = dim_col (Eb ! i)" using \<open>Ea \<in> ExC\<close> \<open>Eb \<in> ExC\<close> \<open>\<forall>Al\<in>ExC. length Al = ncl\<close> \<open>\<forall>i<length Ea. dim_row (Ea ! i) = dim_row (Eb ! i)\<close> \<open>\<forall>i<ncl. \<forall>Al\<in>ExC. dim_row (Al ! i) = dim_col (Al ! i)\<close> by auto have "\<exists>Cea \<in> Cs. Ea = extract_subdiags Cea l" using \<open>Ea \<in> ExC\<close> assms by auto from this obtain Cea where "Cea\<in> Cs" and "Ea = extract_subdiags Cea l" by auto hence cea: "Cea = diag_block_mat Ea" by (simp add: \<open>\<forall>C\<in>Cs. C = diag_block_mat (extract_subdiags C l)\<close>) have "\<exists>Ceb \<in> Cs. Eb = extract_subdiags Ceb l" using \<open>Eb \<in> ExC\<close> assms by auto from this obtain Ceb where "Ceb\<in> Cs" and "Eb = extract_subdiags Ceb l" by auto hence "Ceb = diag_block_mat Eb" by (simp add: \<open>\<forall>C\<in>Cs. C = diag_block_mat (extract_subdiags C l)\<close>) moreover have "Cea * Ceb = Ceb * Cea" by (simp add: \<open>Cea \<in> Cs\<close> \<open>Ceb \<in> Cs\<close> \<open>\<forall>C1\<in>Cs. \<forall>C2\<in>Cs. C1 * C2 = C2 * C1\<close>) ultimately show "diag_block_mat Ea * diag_block_mat Eb = diag_block_mat Eb * diag_block_mat Ea" using cea by simp qed thus "Al * Bl = Bl * Al" using \<open>Al = Ea!j\<close> \<open>Bl = Eb!j\<close> by simp qed lemma extract_comm_real_diag_decomp: fixes CjA::"complex Matrix.mat set" assumes "\<And>(Af::complex Matrix.mat set) n . finite Af \<Longrightarrow> card Af \<le> i \<Longrightarrow> Af \<noteq> {} \<Longrightarrow> (\<And>A. A \<in> Af \<Longrightarrow> A \<in> carrier_mat n n) \<Longrightarrow> 0 < n \<Longrightarrow> (\<And>A. A \<in> Af \<Longrightarrow> hermitian A) \<Longrightarrow> (\<And>A B. A \<in> Af \<Longrightarrow> B \<in> Af \<Longrightarrow> A * B = B * A) \<Longrightarrow> \<exists>U. \<forall>A\<in>Af. \<exists>B. real_diag_decomp A B U" and "finite CjA" and "CjA \<noteq> {}" and "card CjA \<le> i" and "\<forall>C\<in>CjA. C = diag_block_mat (extract_subdiags C eqcl)" and "\<forall>C1\<in>CjA. \<forall>C2\<in>CjA. C1 * C2 = C2 * C1" and "Exc = (\<lambda>A. extract_subdiags A eqcl)`CjA" and "\<forall> E\<in> Exc. list_all (\<lambda>B. 0 < dim_row B \<and> hermitian B) E" and "\<forall>i < length eqcl. 0 < eqcl!i" shows "\<forall>i<length eqcl. \<exists>U. \<forall>Al\<in>Exc. \<exists>B. real_diag_decomp (Al ! i) B U" proof (intro allI impI) define ncl where "ncl = length eqcl" fix j assume "j < ncl" define Exi where "Exi = (\<lambda>l. l!j)`Exc" have "finite Exi" using assms unfolding Exi_def by simp have "card Exi \<le> i" using assms unfolding Exi_def by (metis card_image_le image_image le_trans) have exfl: "\<forall>Ej \<in> Exi. \<exists>Fj \<in> CjA. Ej = (extract_subdiags Fj eqcl)!j" proof fix Ej assume "Ej \<in> Exi" hence "\<exists>El \<in> Exc. Ej = El!j" unfolding Exi_def by auto from this obtain El where "El \<in> Exc" and "Ej = El!j" by auto hence "\<exists>Fl \<in> CjA. El = extract_subdiags Fl eqcl" using assms by auto from this obtain Fl where "Fl \<in> CjA" and "El = extract_subdiags Fl eqcl" by auto thus "\<exists>Fj \<in> CjA. Ej = (extract_subdiags Fj eqcl)!j" using \<open>Ej = El!j\<close> by auto qed have "\<exists>U. \<forall>Al\<in>Exi. \<exists>B. real_diag_decomp (Al) B U" proof (rule assms(1)) show "finite Exi" using \<open>finite Exi\<close> . show "card Exi \<le> i" using \<open>card Exi <= i\<close> . show "Exi \<noteq> {}" using \<open>CjA \<noteq> {}\<close> using assms unfolding Exi_def by auto show "0 < eqcl!j" using \<open>j < ncl\<close> ncl_def assms by simp show "\<And>Al. Al \<in> Exi \<Longrightarrow> Al \<in> carrier_mat (eqcl ! j) (eqcl ! j)" proof - fix Al assume "Al \<in> Exi" hence "\<exists>Fl \<in> CjA. Al = (extract_subdiags Fl eqcl)!j" using exfl by simp from this obtain Fl where "Fl \<in> CjA" and "Al = (extract_subdiags Fl eqcl)!j" by auto thus "Al \<in> carrier_mat (eqcl ! j) (eqcl ! j)" using extract_subdiags_carrier[of j eqcl] \<open>j < ncl\<close> unfolding Exi_def ncl_def by simp qed show "\<And>Al. Al \<in> Exi \<Longrightarrow> hermitian Al" proof - fix Al assume "Al\<in> Exi" hence "\<exists>El \<in> Exc. Al = El!j" unfolding Exi_def by auto from this obtain El where "El \<in> Exc" and "Al = El!j" by auto thus "hermitian Al" using assms \<open>j < ncl\<close> ncl_def by (metis (no_types, lifting) extract_subdiags_length image_iff list_all_length) qed show "\<And>Al Bl. Al \<in> Exi \<Longrightarrow> Bl \<in> Exi \<Longrightarrow> Al * Bl = Bl * Al" proof - fix Al Bl assume "Al \<in> Exi" and "Bl \<in> Exi" show "Al*Bl = Bl * Al" proof (rule extract_dbm_eq_component_commute[of CjA eqcl]) show "Al \<in> Exi" using \<open>Al \<in> Exi\<close> . show "Bl \<in> Exi" using \<open>Bl \<in> Exi\<close> . show "\<forall>C\<in>CjA. C = diag_block_mat (extract_subdiags C eqcl)" using \<open>\<forall>C\<in>CjA. C = diag_block_mat (extract_subdiags C eqcl)\<close> . show "\<forall>C1\<in>CjA. \<forall>C2\<in>CjA. C1 * C2 = C2 * C1" using \<open>\<forall>C1\<in>CjA. \<forall>C2\<in>CjA. C1 * C2 = C2 * C1\<close> . show "j < length eqcl" using \<open>j < ncl\<close> ncl_def by simp show "Exi = (\<lambda>A. A ! j) ` Exc" using Exi_def by simp show "Exc = (\<lambda>A. extract_subdiags A eqcl) ` CjA" using assms by simp qed qed qed thus "\<exists>U. \<forall>Al\<in>Exc. \<exists>B. real_diag_decomp (Al ! j) B U" unfolding Exi_def by simp qed subsection \<open>The main result\<close> theorem commuting_hermitian_family_diag: fixes Af::"complex Matrix.mat set" assumes "finite Af" and "Af \<noteq> {}" and "\<And>A. A\<in> Af \<Longrightarrow> A\<in> carrier_mat n n" and "0 < n" and "\<And>A. A \<in> Af \<Longrightarrow> hermitian A" and "\<And>A B. A \<in> Af \<Longrightarrow> B\<in> Af \<Longrightarrow> A * B = B * A" shows "\<exists> U. \<forall> A\<in> Af. \<exists>B. real_diag_decomp A B U" using assms proof - define i where "i = card Af" have "card Af \<le> i" by (simp add: i_def) from assms(1) this assms(2-) show ?thesis proof (induct i arbitrary: Af n) case 0 then have "Af = {}" by simp then show ?case using 0 by simp next case (Suc i) hence "\<exists> A. A\<in> Af" by blast from this obtain Ap where "Ap \<in> Af" by auto define Afp where "Afp = Af - {Ap}" have "finite Afp" using Suc unfolding Afp_def by simp have "card Afp \<le> i" using \<open>card Af \<le> Suc i\<close> \<open>Ap \<in> Af\<close> unfolding Afp_def by simp have "\<forall>A\<in>Afp. hermitian A \<and> A \<in> carrier_mat n n" using Suc by (metis Afp_def Diff_subset subset_iff) have "\<forall>A\<in>Afp. \<forall>B\<in>Afp. A * B = B * A" using Suc by (metis Afp_def Diff_subset subset_iff) have "\<forall>A\<in> Afp. Ap * A = A * Ap" using Suc by (simp add: Afp_def \<open>Ap \<in> Af\<close>) have "hermitian Ap" "Ap\<in> carrier_mat n n" "0 < n" using \<open>Ap \<in> Af\<close> Suc by auto from this obtain Bs Us where rd: "real_diag_decomp Ap Bs Us \<and> sorted (map Re (diag_mat Bs))" using hermitian_real_diag_sorted[of Ap] by auto note ub = this note ubprops = real_diag_decomp_eq_comps_props[OF \<open>Ap \<in> carrier_mat n n\<close> \<open>0 < n\<close> ub] define eqcl where "eqcl = eq_comps (diag_mat Bs)" have "diag_diff Bs eqcl" using ubprops unfolding eqcl_def by simp have "eqcl \<noteq> []" using ubprops unfolding eqcl_def by simp hence "eqcl = hd eqcl # (tl eqcl)" by simp define esubB where "esubB = extract_subdiags Bs eqcl" have ebcar: "\<forall>i < length esubB. esubB ! i \<in> carrier_mat (eqcl!i) (eqcl!i)" using extract_subdiags_carrier[of _ eqcl Bs] by (simp add: esubB_def extract_subdiags_length) have "Bs = diag_block_mat esubB" unfolding esubB_def eqcl_def proof (rule diagonal_extract_eq) show "Bs \<in> carrier_mat n n" using \<open>Bs \<in> carrier_mat n n\<close> . show "diagonal_mat Bs" using ubprops real_diag_decompD(2) real_diag_decompD(1) unitary_diagD(2) by blast qed show ?case proof (cases "Afp = {}") case True hence "Af = {Ap}" using \<open>Afp = Af - {Ap}\<close> by (simp add: Suc(4) subset_singleton_iff) then show ?thesis using rd \<open>Af = {Ap}\<close> by auto next case False define Cj where "Cj = (\<lambda>A2. mat_conj (Complex_Matrix.adjoint Us) A2)" define CjA where "CjA = Cj`Afp" have "CjA = (\<lambda>A2. (mat_conj (Complex_Matrix.adjoint Us) A2)) ` Afp" using CjA_def Cj_def by simp note cjprops = commuting_conj_mat_set_props[OF \<open>finite Afp\<close> \<open>card Afp \<le> i\<close> \<open>\<forall>A\<in>Afp. hermitian A \<and> A \<in> carrier_mat n n\<close> \<open>\<forall>A\<in>Afp. \<forall>B\<in>Afp. A * B = B * A\<close> \<open>unitary Us\<close> \<open>Us \<in> carrier_mat n n\<close> \<open>CjA = (\<lambda>A2. mat_conj (Complex_Matrix.adjoint Us) A2) ` Afp\<close>] have "\<forall>C \<in> CjA. C = diag_block_mat (extract_subdiags C eqcl)" proof (rule commute_extract_diag_block_eq[OF \<open>Ap\<in> carrier_mat n n\<close> \<open>0 < n\<close> rd \<open>finite Afp\<close> _ \<open>\<forall>A\<in>Afp. hermitian A \<and> A \<in> carrier_mat n n\<close>], auto simp add: eqcl_def CjA_def Cj_def) show "\<And>A B. A \<in> Afp \<Longrightarrow> B \<in> Afp \<Longrightarrow> A * B = B * A" by (simp add: \<open>\<forall>A\<in>Afp. \<forall>B\<in>Afp. A * B = B * A\<close>) show "\<And>A. A \<in> Afp \<Longrightarrow> Ap * A = A * Ap" using \<open>\<forall> A \<in> Afp. Ap * A = A * Ap\<close> by simp qed define Ex where "Ex = (\<lambda>A. extract_subdiags A eqcl)`CjA" have "finite Ex" using \<open>finite CjA\<close> unfolding Ex_def by simp have "Ex \<noteq> {}" using False unfolding Ex_def CjA_def by simp have "card Ex \<le> i" using \<open>card CjA \<le> i\<close> unfolding Ex_def by (metis \<open>finite CjA\<close> basic_trans_rules(23) card_image_le) have exall: "\<forall> E\<in> Ex. list_all (\<lambda>B. 0 < dim_row B \<and> hermitian B) E" proof fix E assume "E\<in> Ex" hence "\<exists>nA \<in> CjA. E = extract_subdiags nA eqcl" unfolding Ex_def by auto from this obtain nA where "nA\<in> CjA" and "E = extract_subdiags nA eqcl" by auto have "list_all (\<lambda>B. 0 < dim_row B \<and> hermitian B) (extract_subdiags nA eqcl)" proof (rule hermitian_extract_subdiags) show "hermitian nA" using \<open>\<forall>A\<in> CjA. A \<in> carrier_mat n n \<and> hermitian A\<close> \<open>nA\<in> CjA\<close> by simp show "list_all ((<) 0) eqcl" unfolding eqcl_def by (metis \<open>eqcl \<noteq> []\<close> eq_comps.simps(1) eq_comps_gt_0 eqcl_def) show "sum_list eqcl \<le> dim_row nA" using \<open>\<forall>A\<in> CjA. A \<in> carrier_mat n n \<and> hermitian A\<close> \<open>nA\<in> CjA\<close> unfolding eqcl_def by (metis \<open>Bs \<in> carrier_mat n n\<close> carrier_matD(1) eq_comp_sum_diag_mat le_refl) qed thus "list_all (\<lambda>B. 0 < dim_row B \<and> hermitian B) E" using \<open>E = extract_subdiags nA eqcl\<close> by simp qed define ncl where "ncl = length eqcl" have "\<forall>j < ncl. \<forall>E \<in> Ex. E!j \<in> carrier_mat (eqcl!j) (eqcl!j)" proof (intro allI impI ballI) fix E j assume "j < ncl" and "E \<in> Ex" thus "E ! j \<in> carrier_mat (eqcl ! j) (eqcl ! j)" unfolding Ex_def using extract_subdiags_carrier ncl_def by blast qed have "\<exists>Ul. (length Ul = ncl \<and> (\<forall>i <ncl. \<forall>Al \<in> Ex. (dim_row (Ul!i) = dim_row (Al!i) \<and> dim_col (Ul!i) = dim_col (Al!i)))\<and> (\<forall> Al \<in> Ex. \<exists>Bl. (length Bl = ncl \<and> real_diag_decomp (diag_block_mat Al) (diag_block_mat Bl) (diag_block_mat Ul))))" proof (rule real_diag_decomp_block_set) show "Ex \<noteq> {}" using \<open>Afp \<noteq> {}\<close> unfolding Ex_def CjA_def by auto show "0 < ncl" unfolding ncl_def using \<open>eqcl \<noteq>[]\<close> by simp show "\<forall>Al\<in>Ex. length Al = ncl" unfolding ncl_def Ex_def by (simp add: extract_subdiags_length) show "\<forall>i<ncl. \<forall>Al\<in>Ex. dim_row (Al ! i) = dim_col (Al ! i)" proof (intro allI impI ballI) fix i Al assume "i < ncl" and "Al \<in> Ex" thus "dim_row (Al ! i) = dim_col (Al ! i)" using exall by (metis (mono_tags, lifting) \<open>\<forall>Al\<in>Ex. length Al = ncl\<close> carrier_matD(2) hermitian_square list_all_length) qed show " \<forall>i<ncl. \<exists>U. \<forall>Al\<in>Ex. \<exists>B. real_diag_decomp (Al ! i) B U" unfolding ncl_def proof (rule extract_comm_real_diag_decomp[of i CjA, OF Suc(1)], auto simp add: exall Ex_def) show "finite CjA" using \<open>finite CjA\<close> . show "card CjA \<le> i" using \<open>card CjA \<le> i\<close> . show "\<And>C. C \<in> CjA \<Longrightarrow> C = diag_block_mat (extract_subdiags C eqcl)" using \<open>\<forall>C \<in> CjA. C = diag_block_mat (extract_subdiags C eqcl)\<close> by simp show "\<And>C1 C2. C1 \<in> CjA \<Longrightarrow> C2 \<in> CjA \<Longrightarrow> C1 * C2 = C2 * C1" using cjprops by simp show "\<And>i. i < length eqcl \<Longrightarrow> 0 < eqcl!i" proof - fix il assume "il < length eqcl" thus "0 < eqcl!il" using eq_comps_gt_0[OF \<open>diag_mat Bs \<noteq> []\<close>] list_all_length[of "(<) 0" "eq_comps (diag_mat Bs)"] unfolding eqcl_def by simp qed show "CjA = {} \<Longrightarrow> False" by (simp add: CjA_def False) qed qed from this obtain Ul where "length Ul = ncl" and dimul: "(\<forall>i <ncl. \<forall>Al \<in> Ex. (dim_row (Ul!i) = dim_row (Al!i) \<and> dim_col (Ul!i) = dim_col (Al!i)))" and ul: "\<forall> Al \<in> Ex. \<exists>Bl. (length Bl = ncl \<and> real_diag_decomp (diag_block_mat Al) (diag_block_mat Bl) (diag_block_mat Ul))" by auto define Uf where "Uf = Us * (diag_block_mat Ul)" have afp:"\<forall>A \<in> Afp. \<exists>Bl. real_diag_decomp A (diag_block_mat Bl) Uf" proof fix A assume "A\<in> Afp" define Ca where "Ca = mat_conj (Complex_Matrix.adjoint Us) A" define Eca where "Eca = extract_subdiags Ca eqcl" have "Ca \<in> CjA" using \<open>A\<in> Afp\<close> unfolding Ca_def CjA_def Cj_def by simp hence "Ca = diag_block_mat Eca" unfolding Eca_def using \<open>\<forall>C\<in> CjA. C = diag_block_mat (extract_subdiags C eqcl)\<close> by simp have "Eca \<in> Ex" unfolding Ex_def Eca_def using \<open>Ca \<in> CjA\<close> by simp hence "\<exists>Bl. (length Bl = ncl \<and> real_diag_decomp (diag_block_mat Eca) (diag_block_mat Bl) (diag_block_mat Ul))" using ul by simp from this obtain Ecb where "length Ecb = ncl" and "real_diag_decomp (diag_block_mat Eca) (diag_block_mat Ecb) (diag_block_mat Ul)" by auto hence "real_diag_decomp Ca (diag_block_mat Ecb) (diag_block_mat Ul)" using \<open>Ca = diag_block_mat Eca\<close> by simp have "real_diag_decomp A (diag_block_mat Ecb) Uf" unfolding Uf_def proof (rule unitary_conjugate_real_diag_decomp) show "A\<in> carrier_mat n n" using \<open>A\<in> Afp\<close> unfolding Afp_def by (simp add: Suc(5)) show "Us \<in> carrier_mat n n" using \<open>Us \<in> carrier_mat n n\<close> . show "unitary Us" using \<open>unitary Us\<close> . show "real_diag_decomp (mat_conj (Complex_Matrix.adjoint Us) A) (diag_block_mat Ecb) (diag_block_mat Ul)" using \<open>real_diag_decomp Ca (diag_block_mat Ecb) (diag_block_mat Ul)\<close> unfolding Ca_def by simp qed thus "\<exists>Bl. real_diag_decomp A (diag_block_mat Bl) Uf" by blast qed have "real_diag_decomp Ap Bs Uf" unfolding Uf_def proof (rule real_diag_decomp_mult_dbm_unit) show "Ap\<in> carrier_mat n n" using \<open>Ap\<in> carrier_mat n n\<close> . show "real_diag_decomp Ap Bs Us" using ub by simp show "Bs = diag_block_mat esubB" using \<open>Bs = diag_block_mat esubB\<close> . show "length Ul = length esubB" using \<open>length Ul = ncl\<close> by (simp add: esubB_def extract_subdiags_length ncl_def) show "\<forall>i<length esubB. dim_col (esubB ! i) = dim_row (esubB ! i)" by (metis carrier_matD(1) carrier_matD(2) ebcar) have "length esubB = ncl" using \<open>length Ul = length esubB\<close> \<open>length Ul = ncl\<close> ncl_def by auto show roweq:"\<forall>i<length esubB. dim_row (esubB ! i) = dim_row (Ul ! i)" using ebcar dimul \<open>length esubB = ncl\<close> \<open>Ex\<noteq> {}\<close> \<open>\<forall>j < ncl. \<forall>E \<in> Ex. E!j \<in> carrier_mat (eqcl!j) (eqcl!j)\<close> by (metis all_not_in_conv carrier_matD(1)) show coleq:"\<forall>i<length esubB. dim_col (esubB ! i) = dim_col (Ul ! i)" using ebcar dimul \<open>length esubB = ncl\<close> \<open>Ex\<noteq> {}\<close> \<open>\<forall>j < ncl. \<forall>E \<in> Ex. E!j \<in> carrier_mat (eqcl!j) (eqcl!j)\<close> by (metis all_not_in_conv carrier_matD(2)) show "unitary (diag_block_mat Ul)" using ul by (metis CjA_def False all_not_in_conv image_is_empty Ex_def real_diag_decompD(1) unitary_diagD(3)) show "\<forall>i<length Ul. Ul ! i * esubB ! i = esubB ! i * Ul ! i" proof (intro allI impI) fix i assume "i < length Ul" show "Ul ! i * esubB ! i = esubB ! i * Ul ! i" unfolding esubB_def eqcl_def proof (rule extract_subdiags_comp_commute[symmetric]) show "diagonal_mat Bs" using \<open>diagonal_mat Bs\<close> . show "Bs\<in> carrier_mat n n" using \<open>Bs \<in> carrier_mat n n\<close> . show "0 < n" using \<open>0 < n\<close> . show "i < length (eq_comps (diag_mat Bs))" using \<open>i < length Ul\<close> \<open>length Ul = length esubB\<close> extract_subdiags_length unfolding esubB_def eqcl_def by metis show "Ul ! i \<in> carrier_mat (eq_comps (diag_mat Bs) ! i) (eq_comps (diag_mat Bs) ! i)" using dimul \<open>\<forall>j < ncl. \<forall>E \<in> Ex. E!j \<in> carrier_mat (eqcl!j) (eqcl!j)\<close> \<open>Ex\<noteq> {}\<close> unfolding ncl_def eqcl_def by (metis coleq roweq \<open>\<forall>i<length esubB. dim_col (esubB ! i) = dim_row (esubB ! i)\<close> \<open>i < length Ul\<close> \<open>length Ul = length esubB\<close> carrier_matD(2) carrier_matI ebcar eqcl_def) qed qed qed hence "\<exists>B. real_diag_decomp Ap B Uf" by blast hence "\<forall> A\<in> Af. \<exists>B. real_diag_decomp A B Uf" using afp unfolding Afp_def by auto thus "\<exists>U. \<forall>A\<in>Af. \<exists>B. real_diag_decomp A B U" by blast qed qed qed end
The castle sits atop a 650 @-@ metre @-@ high ( 2 @,@ 130 ft ) hill east of Tartus , Syria , in the Homs Gap . On the other side of the gap , 27 kilometres ( 17 mi ) away , was the 12th @-@ century <unk> Castle . The route through the strategically important Homs Gap connects the cities of Tripoli and Homs . To the north of the castle lies the Jebel <unk> , and to the south Lebanon . The surrounding area is fertile , benefiting from streams and abundant rainfall . Compared to the Kingdom of Jerusalem , the other Crusader states had less land suitable for farming ; however , the limestone peaks of Tripoli were well @-@ suited to defensive sites .
[STATEMENT] lemma pair_o_assoc'[simp]: assumes [simp]: \<open>compatible F G\<close> \<open>compatible G H\<close> \<open>compatible F H\<close> shows \<open>((F; G); H) \<circ> assoc' = (F; (G; H))\<close> [PROOF STATE] proof (prove) goal (1 subgoal): 1. ((F;G);H) \<circ> assoc' = (F;(G;H)) [PROOF STEP] proof (rule tensor_extensionality3) [PROOF STATE] proof (state) goal (3 subgoals): 1. register (((F;G);H) \<circ> assoc') 2. register (F;(G;H)) 3. \<And>f g h. (((F;G);H) \<circ> assoc') (f \<otimes>\<^sub>u g \<otimes>\<^sub>u h) = (F;(G;H)) (f \<otimes>\<^sub>u g \<otimes>\<^sub>u h) [PROOF STEP] show \<open>register (((F; G); H) \<circ> assoc')\<close> [PROOF STATE] proof (prove) goal (1 subgoal): 1. register (((F;G);H) \<circ> assoc') [PROOF STEP] by simp [PROOF STATE] proof (state) this: register (((F;G);H) \<circ> assoc') goal (2 subgoals): 1. register (F;(G;H)) 2. \<And>f g h. (((F;G);H) \<circ> assoc') (f \<otimes>\<^sub>u g \<otimes>\<^sub>u h) = (F;(G;H)) (f \<otimes>\<^sub>u g \<otimes>\<^sub>u h) [PROOF STEP] show \<open>register (F; (G; H))\<close> [PROOF STATE] proof (prove) goal (1 subgoal): 1. register (F;(G;H)) [PROOF STEP] by simp [PROOF STATE] proof (state) this: register (F;(G;H)) goal (1 subgoal): 1. \<And>f g h. (((F;G);H) \<circ> assoc') (f \<otimes>\<^sub>u g \<otimes>\<^sub>u h) = (F;(G;H)) (f \<otimes>\<^sub>u g \<otimes>\<^sub>u h) [PROOF STEP] show \<open>(((F; G); H) \<circ> assoc') (f \<otimes>\<^sub>u g \<otimes>\<^sub>u h) = (F; (G; H)) (f \<otimes>\<^sub>u g \<otimes>\<^sub>u h)\<close> for f g h [PROOF STATE] proof (prove) goal (1 subgoal): 1. (((F;G);H) \<circ> assoc') (f \<otimes>\<^sub>u g \<otimes>\<^sub>u h) = (F;(G;H)) (f \<otimes>\<^sub>u g \<otimes>\<^sub>u h) [PROOF STEP] by (simp add: register_pair_apply assoc'_apply comp_update_assoc) [PROOF STATE] proof (state) this: (((F;G);H) \<circ> assoc') (?f \<otimes>\<^sub>u ?g \<otimes>\<^sub>u ?h) = (F;(G;H)) (?f \<otimes>\<^sub>u ?g \<otimes>\<^sub>u ?h) goal: No subgoals! [PROOF STEP] qed
import data.nat.order.basic data.set.image /-! # IMO 2010 A6 -/ namespace IMOSL namespace IMO2010A6 open_locale classical def good (f g : ℕ → ℕ) := ∀ n : ℕ, f (g n) = (f n).succ private lemma lem1 {f g : ℕ → ℕ} (h : good f g) : ∃ a : ℕ, ∀ k : ℕ, k ∈ set.range f ↔ a ≤ k := begin have h0 : ∃ n, n ∈ set.range f := ⟨f 0, set.mem_range_self 0⟩, use nat.find h0; refine λ k, ⟨nat.find_min' h0, _⟩, apply nat.le_induction; clear k, exact nat.find_spec h0, rintros n - ⟨k, h1⟩, use g k; rw [h, h1] end private lemma lem2 {f g : ℕ → ℕ} (h : good f g) {x y : ℕ} (h0 : g x = g y) : f x = f y := by rw [← nat.succ_inj', ← h, ← h, h0] private lemma lem3 {f g : ℕ → ℕ} (h : good f g) (h0 : good g f) {x y : ℕ} : f x = f y ↔ g x = g y := ⟨lem2 h0, lem2 h⟩ private lemma lem4 {f g : ℕ → ℕ} (h : good g f) {a : ℕ} (ha : ∀ k : ℕ, k ∈ set.range f ↔ a ≤ k) : a.succ ≤ f a := begin have h1 : a ≤ f a := by rw ← ha; use a, rw [le_iff_eq_or_lt, or_comm] at h1, cases h1 with h1 h1, rwa nat.succ_le_iff, replace h := h a, rw [← h1, nat.succ_eq_add_one] at h, exfalso; exact nat.succ_ne_self (g a) h.symm end private lemma lem5 {f g : ℕ → ℕ} (h : good f g) (h0 : good g f) {a b : ℕ} (h1 : a ≤ b) (ha : ∀ k : ℕ, k ∈ set.range f ↔ a ≤ k) (hb : ∀ k : ℕ, k ∈ set.range g ↔ b ≤ k) : a = b := begin obtain ⟨x, h2⟩ : ∃ x : ℕ, f a = f x + 1 := begin have h2 := lem4 h0 ha, rw [nat.succ_eq_add_one, le_iff_exists_add] at h2, cases h2 with c h2, obtain ⟨x, h3⟩ : a + c ∈ set.range f := (ha (a + c)).mpr le_self_add, use x; rw [h2, h3, add_right_comm] end, obtain ⟨c, h3⟩ := (ha a).mpr (le_refl a), obtain ⟨d, h4⟩ := (ha (g x)).mpr (le_trans h1 (by rw ← hb; use x)), rw [← nat.succ_eq_add_one, ← h, ← h3, ← h4, lem3 h h0, h0, h0, nat.succ_inj', lem3 h0 h] at h2, refine le_antisymm h1 _, rw [← h3, h2, h4, ← hb]; use x end private lemma lem6 {f g : ℕ → ℕ} (h : good f g) (h0 : good g f) {a b : ℕ} (ha : ∀ k : ℕ, k ∈ set.range f ↔ a ≤ k) (hb : ∀ k : ℕ, k ∈ set.range g ↔ b ≤ k) : a = b := begin cases le_total a b with h1 h1, exact lem5 h h0 h1 ha hb, rw lem5 h0 h h1 hb ha end private lemma lem7 {f g : ℕ → ℕ} (h : good f g) (h0 : good g f) {a : ℕ} (ha : ∀ k : ℕ, k ∈ set.range f ↔ a ≤ k) (ha' : ∀ k : ℕ, k ∈ set.range g ↔ a ≤ k) : f a = a.succ := begin have h1 := lem4 h0 ha, rw [le_iff_eq_or_lt, ← nat.succ_le_iff] at h1, cases h1 with h1 h1, rw h1, obtain ⟨x, h2⟩ : ∃ x : ℕ, f a = f x + 1 + 1 := begin rw [nat.succ_eq_add_one, nat.succ_eq_add_one, add_assoc, le_iff_exists_add] at h1, cases h1 with c h1, obtain ⟨x, h2⟩ : a + c ∈ set.range f := (ha (a + c)).mpr le_self_add, use x; rw [h1, h2, add_right_comm] end, rw [← nat.succ_eq_add_one, ← nat.succ_eq_add_one, ← h, ← h] at h2, obtain ⟨c, h3⟩ := (ha a).mpr (le_refl a), obtain ⟨d, h4⟩ := (ha (g (g x))).mpr (by rw ← ha'; use (g x)), rw [← h3, ← h4, lem3 h h0, h0, h0, nat.succ_inj', lem3 h0 h] at h2, obtain ⟨e, h5⟩ := (ha (g x)).mpr (by rw ← ha'; use x), rw [h3, h4, ← h5, h0, eq_comm] at h2, replace h2 := le_of_le_of_eq (nat.succ_le_succ_iff.mpr (by rw ← ha'; use e)) h2, rw [nat.succ_eq_add_one, add_le_iff_nonpos_right, ← not_lt] at h2, exfalso; exact h2 one_pos end /-- Final solution -/ theorem final_solution {f g : ℕ → ℕ} (h : good f g) (h0 : good g f) : f = g := begin cases lem1 h with a h1, cases lem1 h0 with b h2, have h3 := lem6 h h0 h1 h2; subst h3, suffices : ∀ n : ℕ, a ≤ n → (f n = n.succ ∧ g n = n.succ), ext n; rw [← nat.succ_inj', ← h, (this (g n) (by rw ← h2; use n)).left], intros n; apply nat.le_induction; clear n, exact ⟨lem7 h h0 h1 h2, lem7 h0 h h2 h1⟩, rintros n h3 ⟨h4, h5⟩; split, rw [← nat.succ_eq_add_one, ← h5, h, h4, h5], rw [← nat.succ_eq_add_one, ← h4, h0, h5, h4] end end IMO2010A6 end IMOSL
Require Export Lib.Monads. Require Import Coq.Strings.String. Require Import FunctionalExtensionality. Require Import Common.Either. Require Import TargetSFI.ExecutionError. Module StateMonad. Section Def. Variable st: Type. Definition t (res: Type) := st -> (@Either res ExecutionError) * st. Definition ret (A:Type) (x:A) : (t A) := fun (s:st) => (Right x,s). Definition bind A B (s: t A) (f: A -> t B) := fun x => match s x with | (Right x',s') => (f x') s' | (Left msg err, s') => (Left msg err, s') end. Definition get : t st := fun s => (Right s, s). Definition put (s: st) : t unit := fun _ => (Right tt, s). Definition modify (f: st -> st) : t unit := fun s => (Right tt, f s). Definition lift {A} (x: option A) (msg : string) (err : ExecutionError): t A := fun s => match x with | None => (Left msg err, s) | Some v => (Right v, s) end. Definition fail {A} (msg : string) (err : ExecutionError) : t A := fun s => (Left msg err, s). Definition run {A} (s: st) (m: t A) : (@Either A ExecutionError) := match m s with | (Left msg err,_) => Left msg err | (Right v,s') => Right v end. End Def. End StateMonad. Instance state_monad {st} : Monad (StateMonad.t st) := { ret := StateMonad.ret st; bind := StateMonad.bind st }. Section StateMonadLaws. Variable st: Type. Lemma state_monad_left_id: forall res1 res2 (e: res1) (f: res1 -> StateMonad.t st res2), bind (ret e) f = f e. Proof. auto. Qed. Lemma state_monad_right_id: forall res (m: StateMonad.t st res), bind m ret = m. Proof. intros. unfold ret, bind. simpl. unfold StateMonad.ret, StateMonad.bind. extensionality x. destruct (m x); auto. destruct e. auto. reflexivity. Qed. Lemma state_monad_associativity: forall res1 res2 res3 (m: StateMonad.t st res1) (f: res1 -> StateMonad.t st res2) (g: res2 -> StateMonad.t st res3), bind (bind m f) g = bind m (fun x => bind (f x) g). Proof. intros. unfold ret, bind. simpl. unfold StateMonad.ret, StateMonad.bind. extensionality x. destruct m; auto. destruct e. destruct (f r s); auto. reflexivity. Qed. End StateMonadLaws. Instance state_monad_laws {st} : MonadLaws (StateMonad.t st) := { m_left_identity := state_monad_left_id st; m_right_identity := state_monad_right_id st; m_associativity := state_monad_associativity st }.
module GRIN.Error import System.File import GRIN.AST public export data Error = FileErr String FileError | MissingVar Var export Show Error where show (FileErr f err) = "File error with file " ++ show f ++ "\n" ++ show err ++ "\n\n" show (MissingVar (MkVar v)) = "Missing variable from VarMap (v" ++ show v ++ ")\n\n"
HeadModelPath = [hlp_getSiftRoot filesep 'resources' filesep 'headmodels' filesep 'standard-Colin27-385ch.mat']; hmObj = hlp_validateHeadModelObject(HeadModelPath); %% Simulate VAR model [EEGsim] = pop_sim_varmodel([]); if length(EEGsim)>1 EEGtrue = EEGsim(2); EEGsim = EEGsim(1); end %% Simulate scalp activity using forward model % these are the source locations sourceRois = {'Cingulum_Mid_L','Occipital_Mid_L','Parietal_Sup_L','Frontal_Sup_Medial_R','Precentral_R'}; cfg = arg_guipanel('Function',@sim_simulateSources, ... 'Parameters',{ ... 'hmObj',HeadModelPath, ... 'sourceAtlasLabels', setdiff_bc(hmObj.atlas.label,{'Thalamus_L','Thalamus_R'}), ... 'Channels',hmObj.label, ... 'sourceShape' {'gausspatch' 'roiOrdered' sourceRois, 'sigma', 10}, ... 'addNoise', {'SignalToNoise' 20} ... },'PanelOnly',false); [scalpData srcData LFM] = sim_simulateSources('sourceAmps',EEGsim.data,cfg); %% chanlabels = hmObj.getChannelLabels(); elocs = hmObj.channelSpace; EEG = EEGsim; EEG.data = scalpData; EEG.nbchan = size(EEG.data,1); EEG.setname = 'VAR Simulation'; EEG.condition = 'VAR Simulation'; EEG.srcpot_all = srcData; EEG = rmfield(EEG,'chanlocs'); for k=1:EEG.nbchan EEG.chanlocs(k) = struct(... 'X',elocs(k,1), ... 'Y',elocs(k,2), ... 'Z',elocs(k,3), ... 'labels',chanlabels{k}, ... 'type','EEG', ... 'theta',[], ... 'radius',0.5, ... 'sph_theta',[],... 'sph_phi',[],... 'sph_radius',[],... 'urchan',k, ... 'ref',''); end EEG.chanlocs = convertlocs(EEG.chanlocs,'cart2all'); %% visualize latency = []; gobj=vis_csd('hmObj',HeadModelPath, ... 'signal',EEG, ... 'cortexMesh',[], ... 'times',latency, ... 'avgtimes',false, ... 'frameskip',10, ... 'cortexlims',99, ... 'scalplims',[99], ... 'showpower',false, ... 'title','True');
If $f$ is a continuous function from a set $S$ to a Euclidean space and $g$ is a linear function from a Euclidean space to a normed vector space, then the composition $g \circ f$ is continuous.
Require Import Coq.Vectors.Vector. Require Import Coq.Program.Equality. Theorem vector_forall_append {A: Type}(P: A -> Prop): forall (m n: nat)(u: t A m)(v: t A n), Forall P (append u v) <-> Forall P u /\ Forall P v. Proof. intros m n u. generalize dependent n. induction u as [| x m u]; simpl; intros n v; split. { intros Hv; split; [constructor | assumption]. } { intros [Hnil Hv]; assumption. } { intros Happ. inversion Happ. inversion_sigma. subst. split. { constructor; [assumption |]. let H := match goal with H : m + n = m + n |- _ => H end in pose proof (Eqdep_dec.UIP_refl_nat _ H); subst H; simpl in *; subst. apply IHu in H3. inversion_clear H3 as [Hu Hv]. assumption. } { let H := match goal with H : m + n = m + n |- _ => H end in pose proof (Eqdep_dec.UIP_refl_nat _ H); subst H; simpl in *; subst. apply IHu in H3. inversion_clear H3 as [Hu Hv]. assumption. } } { intros [Hxu Hv]. inversion Hxu; subst. inversion_sigma. let H := match goal with H : m = m |- _ => H end in pose proof (Eqdep_dec.UIP_refl_nat _ H); subst H; simpl in *; subst. constructor; [assumption |]. apply IHu. split; assumption. } Qed. Definition vector_ind2 {A B: Type} (P: forall {n}, t A n -> t B n -> Prop) (base: P (nil A) (nil B)) (ind: forall {n v1 v2}, P v1 v2 -> forall a b, P (cons A a _ v1) (cons B b _ v2)) := fix vector_ind2_fix {n} (v1: t A n): forall (v2: t B n), P v1 v2 := match v1 with | nil _ => fun v2 => case0 _ base v2 | @cons _ hd1 n' tl1 => fun v2 => caseS' v2 (fun v2' => P (cons A hd1 _ tl1) v2') (fun hd2 tl2 => ind (vector_ind2_fix tl1 tl2) hd1 hd2) end. Theorem vector_fold_right2_append {A B C: Type}(g: A -> B -> C -> C)(c: C): forall {n: nat}(u2: t A n)(v2: t B n){m: nat}(u1: t A m)(v1: t B m), fold_right2 g c _ (append u1 u2) (append v1 v2) = fold_right2 g (fold_right2 g c _ u2 v2) _ u1 v1. Proof. intros n u2 v2. apply vector_ind2; simpl; [reflexivity |]. intros m u1 v1 IH. intros a b. rewrite IH. reflexivity. Qed. Lemma vector_forall_map {A: Type}(P: A -> Prop)(f: A -> A): (forall (a: A), P a -> P (f a)) -> forall {n: nat}(v: t A n), Forall P v -> Forall P (map f v). Proof. intros Hclosed n. induction v; simpl. { constructor. } { intros Hcons. inversion Hcons. subst. inversion_sigma. let H := match goal with H: n = n |- _ => H end in pose proof (Eqdep_dec.UIP_refl_nat _ H); subst H; simpl in *; subst. constructor. { apply Hclosed. assumption. } { apply IHv. assumption. } } Qed. Lemma vector_forall_map_spec {A B: Type}(P: B -> Prop)(f: A -> B): (forall (a: A), P (f a)) -> forall {n: nat}(v: t A n), Forall P (map f v). Proof. intros Hspec. intros n. induction v as [| a n v]; simpl; constructor. { apply Hspec. } { assumption. } Qed. Fixpoint const_seq {A: Type}(a: A)(n: nat): t A n := match n with | 0 => nil A | S n' => cons _ a _ (const_seq a n') end. Lemma vector_forall_const_seq {A: Type}(a: A){n: nat}(P: A -> Prop): Forall P (const_seq a n) <-> n = 0 \/ P a. Proof. split; [intros Hforall |]. { destruct n as [| n']. { left; reflexivity. } { right. simpl in Hforall. inversion_clear Hforall. assumption. } } { induction n as [| n']. { left; reflexivity. } { simpl. intros [Hcontra | Ha]; [inversion Hcontra |]. constructor; [assumption |]. apply IHn'. right. assumption. } } Qed. Definition zipWith {A B C: Type} (f: A -> B -> C){n: nat}(u: t A n)(v: t B n): t C n := rect2 (fun n _ _ => t C n) (nil C) (fun n _ _ accum a b => cons C (f a b) n accum) u v. Theorem vector_forall_zipwith_binary_op {A: Type} (f: A -> A -> A)(P: A -> Prop): (forall (a0 a1: A), P a0 -> P a1 -> P (f a0 a1)) -> forall {n: nat}(v0: t A n)(v1: t A n), Forall P v0 -> Forall P v1 -> Forall P (zipWith f v0 v1). Proof. intros Hclosed n v0 v1. induction v0 as [| a0 n v0]. { dependent destruction v1. intros _ _. simpl. constructor. } { dependent destruction v1. rename h into a1. intros Hv0 Hv1. simpl. inversion Hv0. subst. inversion_sigma. let H := match goal with H: n = n |- _ => H end in pose proof (Eqdep_dec.UIP_refl_nat _ H); subst H; simpl in *; subst v. inversion Hv1. subst. inversion_sigma. let H := match goal with H: n = n |- _ => H end in pose proof (Eqdep_dec.UIP_refl_nat _ H); subst H; simpl in *; subst v. constructor. { apply Hclosed; assumption. } { apply IHv0; assumption. } } Qed. Theorem vector_map_composed {A B C: Type}(f: A -> B)(g: B -> C): forall {n: nat}(v: t A n), map (fun x => g (f x)) v = map g (map f v). Proof. intros n. induction v; simpl; [| rewrite IHv]; reflexivity. Qed.
#include <iostream> #include <cstdio> #include <boost/format.hpp> void clear (void) { while ( getchar() != '\n' ); } int index_menu() { int op = 0; std::cout << " **********************************\n" " 欢迎使用图书管理系统\n" " 1 管理员模式\n" " 2 读者模式\n" " 3 退出\n" << std::flush; while (op == 0) { std::cout << "请输入选项:" << std::flush; std::cin >> op; if (op == 1 || op == 2 || op == 3) { return op; } else{ std::cout << "您的指令有误,请重新输入" << std::endl; clear(); op = 0; } } } int admin_menu() { int op = 0; std::cout << " **********************************\n" " 1 建立图书库存信息\n" " 2 增加图书信息\n" " 3 修改图书信息\n" " 4 删除图书信息\n" " 5 创建读者信息\n" " 6 增加读者信息\n" " 7 删除读者信息\n" " 8 修改读者信息\n" " 9 修改管理员密码\n" " 0 返回上一层目录\n" " **********************************\n" << std::flush; while (op == 0) { std::cout << "请输入选项:" << std::flush; std::cin >> op; if (op >= 0 && op <= 9) { return op; }else{ clear(); std::cout << "您的指令有误,请重新输入" << std::endl; op = 0; } } } int reader_menu() { int op = 0; std::cout << " **********************************\n" " 1 借阅图书\n" " 2 归还图书\n" " 3 查询图书\n" " 4 修改密码\n" " 5 查看借阅图书信息\n" " 0 返回上一层目录\n" " **********************************\n" << std::flush; while (op == 0) { std::cout << "请输入选项:" << std::flush; std::cin >> op; if (op >= 0 && op <= 5) { return op; }else{ std::cout << "您的指令有误,请重新输入" << std::endl; clear(); op = 0; } } }
/- Copyright (c) 2021 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import topology.algebra.filter_basis import topology.algebra.uniform_group /-! # Uniform properties of neighborhood bases in topological algebra This files contains properties of filter bases on algebraic structures that also require the theory of uniform spaces. The only result so far is a characterization of Cauchy filters in topological groups. -/ open_locale uniformity filter open filter namespace add_group_filter_basis variables {G : Type*} [add_comm_group G] (B : add_group_filter_basis G) /-- The uniform space structure associated to an abelian group filter basis via the associated topological abelian group structure. -/ protected def uniform_space : uniform_space G := @topological_add_group.to_uniform_space G _ B.topology B.is_topological_add_group /-- The uniform space structure associated to an abelian group filter basis via the associated topological abelian group structure is compatible with its group structure. -/ protected lemma uniform_add_group : @uniform_add_group G B.uniform_space _:= @topological_add_comm_group_is_uniform G _ B.topology B.is_topological_add_group lemma cauchy_iff {F : filter G} : @cauchy G B.uniform_space F ↔ F.ne_bot ∧ ∀ U ∈ B, ∃ M ∈ F, ∀ x y ∈ M, y - x ∈ U := begin letI := B.uniform_space, haveI := B.uniform_add_group, suffices : F ×ᶠ F ≤ 𝓤 G ↔ ∀ U ∈ B, ∃ M ∈ F, ∀ x y ∈ M, y - x ∈ U, by split ; rintros ⟨h', h⟩ ; refine ⟨h', _⟩ ; [rwa ← this, rwa this], rw [uniformity_eq_comap_nhds_zero G, ← map_le_iff_le_comap], change tendsto _ _ _ ↔ _, simp [(basis_sets F).prod_self.tendsto_iff B.nhds_zero_has_basis, @forall_swap (_ ∈ _) G] end end add_group_filter_basis
Formal statement is: lemma measure_eq_sum_singleton: "finite S \<Longrightarrow> (\<And>x. x \<in> S \<Longrightarrow> {x} \<in> sets M) \<Longrightarrow> (\<And>x. x \<in> S \<Longrightarrow> emeasure M {x} \<noteq> \<infinity>) \<Longrightarrow> measure M S = (\<Sum>x\<in>S. measure M {x})" Informal statement is: If $S$ is a finite set and $M$ is a measure space, then the measure of $S$ is the sum of the measures of the singletons in $S$.
Formal statement is: lemma algebraic_int_minus [intro]: assumes "algebraic_int x" shows "algebraic_int (-x)" Informal statement is: If $x$ is an algebraic integer, then so is $-x$.
module Physics.Box2D.Defaults %access public export density : Double density = 0 friction : Double friction = 0.3 restitution : Double restitution = 0.15
import numpy as np from sklearn import neighbors, datasets, tree, linear_model from sklearn.model_selection import cross_val_score from sklearn.externals import joblib import classsol #load input data words = [] with open("words.txt", encoding = "ISO-8859-1") as file: for line in file: line = line.split(' ') #or some other preprocessing words.append(line) #storing everything in memory! X = words[0] for test in ["wordsclass.npy", "wordsclass2.npy"]: print("Testing " + test) #load output data Y=np.load(test) f = classsol.features(X) clf = classsol.mytraining(f,Y) Ypred = classsol.myprediction(f, clf) print(np.sum(Y^Ypred)/len(X)); if (np.sum(Y^Ypred)/len(X))<.05: print("Erro bastante baixo. PERFECT!\n") elif (np.sum(Y^Ypred)/len(X))<.3: print("Erro nos Q dentro dos limites de tolerância. OK\n") else: print("Erro nos Q acima dos limites de tolerância. FAILED\n")
(*<*) theory Isar imports LaTeXsugar begin declare [[quick_and_dirty]] (*>*) text{* Apply-scripts are unreadable and hard to maintain. The language of choice for larger proofs is \concept{Isar}. The two key features of Isar are: \begin{itemize} \item It is structured, not linear. \item It is readable without its being run because you need to state what you are proving at any given point. \end{itemize} Whereas apply-scripts are like assembly language programs, Isar proofs are like structured programs with comments. A typical Isar proof looks like this: *}text{* \begin{tabular}{@ {}l} \isacom{proof}\\ \quad\isacom{assume} @{text"\""}$\mathit{formula}_0$@{text"\""}\\ \quad\isacom{have} @{text"\""}$\mathit{formula}_1$@{text"\""} \quad\isacom{by} @{text simp}\\ \quad\vdots\\ \quad\isacom{have} @{text"\""}$\mathit{formula}_n$@{text"\""} \quad\isacom{by} @{text blast}\\ \quad\isacom{show} @{text"\""}$\mathit{formula}_{n+1}$@{text"\""} \quad\isacom{by} @{text \<dots>}\\ \isacom{qed} \end{tabular} *}text{* It proves $\mathit{formula}_0 \Longrightarrow \mathit{formula}_{n+1}$ (provided each proof step succeeds). The intermediate \isacom{have} statements are merely stepping stones on the way towards the \isacom{show} statement that proves the actual goal. In more detail, this is the Isar core syntax: \medskip \begin{tabular}{@ {}lcl@ {}} \textit{proof} &=& \indexed{\isacom{by}}{by} \textit{method}\\ &$\mid$& \indexed{\isacom{proof}}{proof} [\textit{method}] \ \textit{step}$^*$ \ \indexed{\isacom{qed}}{qed} \end{tabular} \medskip \begin{tabular}{@ {}lcl@ {}} \textit{step} &=& \indexed{\isacom{fix}}{fix} \textit{variables} \\ &$\mid$& \indexed{\isacom{assume}}{assume} \textit{proposition} \\ &$\mid$& [\indexed{\isacom{from}}{from} \textit{fact}$^+$] (\indexed{\isacom{have}}{have} $\mid$ \indexed{\isacom{show}}{show}) \ \textit{proposition} \ \textit{proof} \end{tabular} \medskip \begin{tabular}{@ {}lcl@ {}} \textit{proposition} &=& [\textit{name}:] @{text"\""}\textit{formula}@{text"\""} \end{tabular} \medskip \begin{tabular}{@ {}lcl@ {}} \textit{fact} &=& \textit{name} \ $\mid$ \ \dots \end{tabular} \medskip \noindent A proof can either be an atomic \isacom{by} with a single proof method which must finish off the statement being proved, for example @{text auto}, or it can be a \isacom{proof}--\isacom{qed} block of multiple steps. Such a block can optionally begin with a proof method that indicates how to start off the proof, e.g., \mbox{@{text"(induction xs)"}}. A step either assumes a proposition or states a proposition together with its proof. The optional \isacom{from} clause indicates which facts are to be used in the proof. Intermediate propositions are stated with \isacom{have}, the overall goal is stated with \isacom{show}. A step can also introduce new local variables with \isacom{fix}. Logically, \isacom{fix} introduces @{text"\<And>"}-quantified variables, \isacom{assume} introduces the assumption of an implication (@{text"\<Longrightarrow>"}) and \isacom{have}/\isacom{show} introduce the conclusion. Propositions are optionally named formulas. These names can be referred to in later \isacom{from} clauses. In the simplest case, a fact is such a name. But facts can also be composed with @{text OF} and @{text of} as shown in \autoref{sec:forward-proof} --- hence the \dots\ in the above grammar. Note that assumptions, intermediate \isacom{have} statements and global lemmas all have the same status and are thus collectively referred to as \conceptidx{facts}{fact}. Fact names can stand for whole lists of facts. For example, if @{text f} is defined by command \isacom{fun}, @{text"f.simps"} refers to the whole list of recursion equations defining @{text f}. Individual facts can be selected by writing @{text"f.simps(2)"}, whole sublists by writing @{text"f.simps(2-4)"}. \section{Isar by Example} We show a number of proofs of Cantor's theorem that a function from a set to its powerset cannot be surjective, illustrating various features of Isar. The constant @{const surj} is predefined. *} lemma "\<not> surj(f :: 'a \<Rightarrow> 'a set)" proof assume 0: "surj f" from 0 have 1: "\<forall>A. \<exists>a. A = f a" by(simp add: surj_def) from 1 have 2: "\<exists>a. {x. x \<notin> f x} = f a" by blast from 2 show "False" by blast qed text{* The \isacom{proof} command lacks an explicit method by which to perform the proof. In such cases Isabelle tries to use some standard introduction rule, in the above case for @{text"\<not>"}: \[ \inferrule{ \mbox{@{thm (prem 1) notI}}} {\mbox{@{thm (concl) notI}}} \] In order to prove @{prop"~ P"}, assume @{text P} and show @{text False}. Thus we may assume @{prop"surj f"}. The proof shows that names of propositions may be (single!) digits --- meaningful names are hard to invent and are often not necessary. Both \isacom{have} steps are obvious. The second one introduces the diagonal set @{term"{x. x \<notin> f x}"}, the key idea in the proof. If you wonder why @{text 2} directly implies @{text False}: from @{text 2} it follows that @{prop"a \<notin> f a \<longleftrightarrow> a \<in> f a"}. \subsection{\indexed{@{text this}}{this}, \indexed{\isacom{then}}{then}, \indexed{\isacom{hence}}{hence} and \indexed{\isacom{thus}}{thus}} Labels should be avoided. They interrupt the flow of the reader who has to scan the context for the point where the label was introduced. Ideally, the proof is a linear flow, where the output of one step becomes the input of the next step, piping the previously proved fact into the next proof, like in a UNIX pipe. In such cases the predefined name @{text this} can be used to refer to the proposition proved in the previous step. This allows us to eliminate all labels from our proof (we suppress the \isacom{lemma} statement): *} (*<*) lemma "\<not> surj(f :: 'a \<Rightarrow> 'a set)" (*>*) proof assume "surj f" from this have "\<exists>a. {x. x \<notin> f x} = f a" by(auto simp: surj_def) from this show "False" by blast qed text{* We have also taken the opportunity to compress the two \isacom{have} steps into one. To compact the text further, Isar has a few convenient abbreviations: \medskip \begin{tabular}{r@ {\quad=\quad}l} \isacom{then} & \isacom{from} @{text this}\\ \isacom{thus} & \isacom{then} \isacom{show}\\ \isacom{hence} & \isacom{then} \isacom{have} \end{tabular} \medskip \noindent With the help of these abbreviations the proof becomes *} (*<*) lemma "\<not> surj(f :: 'a \<Rightarrow> 'a set)" (*>*) proof assume "surj f" hence "\<exists>a. {x. x \<notin> f x} = f a" by(auto simp: surj_def) thus "False" by blast qed text{* There are two further linguistic variations: \medskip \begin{tabular}{r@ {\quad=\quad}l} (\isacom{have}$\mid$\isacom{show}) \ \textit{prop} \ \indexed{\isacom{using}}{using} \ \textit{facts} & \isacom{from} \ \textit{facts} \ (\isacom{have}$\mid$\isacom{show}) \ \textit{prop}\\ \indexed{\isacom{with}}{with} \ \textit{facts} & \isacom{from} \ \textit{facts} \isa{this} \end{tabular} \medskip \noindent The \isacom{using} idiom de-emphasizes the used facts by moving them behind the proposition. \subsection{Structured Lemma Statements: \indexed{\isacom{fixes}}{fixes}, \indexed{\isacom{assumes}}{assumes}, \indexed{\isacom{shows}}{shows}} \index{lemma@\isacom{lemma}} Lemmas can also be stated in a more structured fashion. To demonstrate this feature with Cantor's theorem, we rephrase @{prop"\<not> surj f"} a little: *} lemma fixes f :: "'a \<Rightarrow> 'a set" assumes s: "surj f" shows "False" txt{* The optional \isacom{fixes} part allows you to state the types of variables up front rather than by decorating one of their occurrences in the formula with a type constraint. The key advantage of the structured format is the \isacom{assumes} part that allows you to name each assumption; multiple assumptions can be separated by \isacom{and}. The \isacom{shows} part gives the goal. The actual theorem that will come out of the proof is @{prop"surj f \<Longrightarrow> False"}, but during the proof the assumption @{prop"surj f"} is available under the name @{text s} like any other fact. *} proof - have "\<exists> a. {x. x \<notin> f x} = f a" using s by(auto simp: surj_def) thus "False" by blast qed text{* \begin{warn} Note the hyphen after the \isacom{proof} command. It is the null method that does nothing to the goal. Leaving it out would be asking Isabelle to try some suitable introduction rule on the goal @{const False} --- but there is no such rule and \isacom{proof} would fail. \end{warn} In the \isacom{have} step the assumption @{prop"surj f"} is now referenced by its name @{text s}. The duplication of @{prop"surj f"} in the above proofs (once in the statement of the lemma, once in its proof) has been eliminated. Stating a lemma with \isacom{assumes}-\isacom{shows} implicitly introduces the name \indexed{@{text assms}}{assms} that stands for the list of all assumptions. You can refer to individual assumptions by @{text"assms(1)"}, @{text"assms(2)"}, etc., thus obviating the need to name them individually. \section{Proof Patterns} We show a number of important basic proof patterns. Many of them arise from the rules of natural deduction that are applied by \isacom{proof} by default. The patterns are phrased in terms of \isacom{show} but work for \isacom{have} and \isacom{lemma}, too. We start with two forms of \concept{case analysis}: starting from a formula @{text P} we have the two cases @{text P} and @{prop"~P"}, and starting from a fact @{prop"P \<or> Q"} we have the two cases @{text P} and @{text Q}: *}text_raw{* \begin{tabular}{@ {}ll@ {}} \begin{minipage}[t]{.4\textwidth} \isa{% *} (*<*)lemma "R" proof-(*>*) show "R" proof cases assume "P" text_raw{*\\\mbox{}\quad$\vdots$\\\mbox{}\hspace{-1.4ex}*} show "R" (*<*)sorry(*>*)text_raw{*\ $\dots$\\*} next assume "\<not> P" text_raw{*\\\mbox{}\quad$\vdots$\\\mbox{}\hspace{-1.4ex}*} show "R" (*<*)sorry(*>*)text_raw{*\ $\dots$\\*} qed(*<*)oops(*>*) text_raw {* } \end{minipage}\index{cases@@{text cases}} & \begin{minipage}[t]{.4\textwidth} \isa{% *} (*<*)lemma "R" proof-(*>*) have "P \<or> Q" (*<*)sorry(*>*)text_raw{*\ $\dots$\\*} then show "R" proof assume "P" text_raw{*\\\mbox{}\quad$\vdots$\\\mbox{}\hspace{-1.4ex}*} show "R" (*<*)sorry(*>*)text_raw{*\ $\dots$\\*} next assume "Q" text_raw{*\\\mbox{}\quad$\vdots$\\\mbox{}\hspace{-1.4ex}*} show "R" (*<*)sorry(*>*)text_raw{*\ $\dots$\\*} qed(*<*)oops(*>*) text_raw {* } \end{minipage} \end{tabular} \medskip \begin{isamarkuptext}% How to prove a logical equivalence: \end{isamarkuptext}% \isa{% *} (*<*)lemma "P\<longleftrightarrow>Q" proof-(*>*) show "P \<longleftrightarrow> Q" proof assume "P" text_raw{*\\\mbox{}\quad$\vdots$\\\mbox{}\hspace{-1.4ex}*} show "Q" (*<*)sorry(*>*) text_raw{*\ $\dots$\\*} next assume "Q" text_raw{*\\\mbox{}\quad$\vdots$\\\mbox{}\hspace{-1.4ex}*} show "P" (*<*)sorry(*>*) text_raw{*\ $\dots$\\*} qed(*<*)qed(*>*) text_raw {* } \medskip \begin{isamarkuptext}% Proofs by contradiction (@{thm[source] ccontr} stands for ``classical contradiction''): \end{isamarkuptext}% \begin{tabular}{@ {}ll@ {}} \begin{minipage}[t]{.4\textwidth} \isa{% *} (*<*)lemma "\<not> P" proof-(*>*) show "\<not> P" proof assume "P" text_raw{*\\\mbox{}\quad$\vdots$\\\mbox{}\hspace{-1.4ex}*} show "False" (*<*)sorry(*>*)text_raw{*\ $\dots$\\*} qed(*<*)oops(*>*) text_raw {* } \end{minipage} & \begin{minipage}[t]{.4\textwidth} \isa{% *} (*<*)lemma "P" proof-(*>*) show "P" proof (rule ccontr) assume "\<not>P" text_raw{*\\\mbox{}\quad$\vdots$\\\mbox{}\hspace{-1.4ex}*} show "False" (*<*)sorry(*>*)text_raw{*\ $\dots$\\*} qed(*<*)oops(*>*) text_raw {* } \end{minipage} \end{tabular} \medskip \begin{isamarkuptext}% How to prove quantified formulas: \end{isamarkuptext}% \begin{tabular}{@ {}ll@ {}} \begin{minipage}[t]{.4\textwidth} \isa{% *} (*<*)lemma "ALL x. P x" proof-(*>*) show "\<forall>x. P(x)" proof fix x text_raw{*\\\mbox{}\quad$\vdots$\\\mbox{}\hspace{-1.4ex}*} show "P(x)" (*<*)sorry(*>*)text_raw{*\ $\dots$\\*} qed(*<*)oops(*>*) text_raw {* } \end{minipage} & \begin{minipage}[t]{.4\textwidth} \isa{% *} (*<*)lemma "EX x. P(x)" proof-(*>*) show "\<exists>x. P(x)" proof text_raw{*\\\mbox{}\quad$\vdots$\\\mbox{}\hspace{-1.4ex}*} show "P(witness)" (*<*)sorry(*>*)text_raw{*\ $\dots$\\*} qed (*<*)oops(*>*) text_raw {* } \end{minipage} \end{tabular} \medskip \begin{isamarkuptext}% In the proof of \noquotes{@{prop[source]"\<forall>x. P(x)"}}, the step \indexed{\isacom{fix}}{fix}~@{text x} introduces a locally fixed variable @{text x} into the subproof, the proverbial ``arbitrary but fixed value''. Instead of @{text x} we could have chosen any name in the subproof. In the proof of \noquotes{@{prop[source]"\<exists>x. P(x)"}}, @{text witness} is some arbitrary term for which we can prove that it satisfies @{text P}. How to reason forward from \noquotes{@{prop[source] "\<exists>x. P(x)"}}: \end{isamarkuptext}% *} (*<*)lemma True proof- assume 1: "EX x. P x"(*>*) have "\<exists>x. P(x)" (*<*)by(rule 1)(*>*)text_raw{*\ $\dots$\\*} then obtain x where p: "P(x)" by blast (*<*)oops(*>*) text{* After the \indexed{\isacom{obtain}}{obtain} step, @{text x} (we could have chosen any name) is a fixed local variable, and @{text p} is the name of the fact \noquotes{@{prop[source] "P(x)"}}. This pattern works for one or more @{text x}. As an example of the \isacom{obtain} command, here is the proof of Cantor's theorem in more detail: *} lemma "\<not> surj(f :: 'a \<Rightarrow> 'a set)" proof assume "surj f" hence "\<exists>a. {x. x \<notin> f x} = f a" by(auto simp: surj_def) then obtain a where "{x. x \<notin> f x} = f a" by blast hence "a \<notin> f a \<longleftrightarrow> a \<in> f a" by blast thus "False" by blast qed text_raw{* \begin{isamarkuptext}% Finally, how to prove set equality and subset relationship: \end{isamarkuptext}% \begin{tabular}{@ {}ll@ {}} \begin{minipage}[t]{.4\textwidth} \isa{% *} (*<*)lemma "A = (B::'a set)" proof-(*>*) show "A = B" proof show "A \<subseteq> B" (*<*)sorry(*>*)text_raw{*\ $\dots$\\*} next show "B \<subseteq> A" (*<*)sorry(*>*)text_raw{*\ $\dots$\\*} qed(*<*)qed(*>*) text_raw {* } \end{minipage} & \begin{minipage}[t]{.4\textwidth} \isa{% *} (*<*)lemma "A <= (B::'a set)" proof-(*>*) show "A \<subseteq> B" proof fix x assume "x \<in> A" text_raw{*\\\mbox{}\quad$\vdots$\\\mbox{}\hspace{-1.4ex}*} show "x \<in> B" (*<*)sorry(*>*)text_raw{*\ $\dots$\\*} qed(*<*)qed(*>*) text_raw {* } \end{minipage} \end{tabular} \begin{isamarkuptext}% \section{Streamlining Proofs} \subsection{Pattern Matching and Quotations} In the proof patterns shown above, formulas are often duplicated. This can make the text harder to read, write and maintain. Pattern matching is an abbreviation mechanism to avoid such duplication. Writing \begin{quote} \isacom{show} \ \textit{formula} @{text"("}\indexed{\isacom{is}}{is} \textit{pattern}@{text")"} \end{quote} matches the pattern against the formula, thus instantiating the unknowns in the pattern for later use. As an example, consider the proof pattern for @{text"\<longleftrightarrow>"}: \end{isamarkuptext}% *} (*<*)lemma "formula\<^sub>1 \<longleftrightarrow> formula\<^sub>2" proof-(*>*) show "formula\<^sub>1 \<longleftrightarrow> formula\<^sub>2" (is "?L \<longleftrightarrow> ?R") proof assume "?L" text_raw{*\\\mbox{}\quad$\vdots$\\\mbox{}\hspace{-1.4ex}*} show "?R" (*<*)sorry(*>*) text_raw{*\ $\dots$\\*} next assume "?R" text_raw{*\\\mbox{}\quad$\vdots$\\\mbox{}\hspace{-1.4ex}*} show "?L" (*<*)sorry(*>*) text_raw{*\ $\dots$\\*} qed(*<*)qed(*>*) text{* Instead of duplicating @{text"formula\<^sub>i"} in the text, we introduce the two abbreviations @{text"?L"} and @{text"?R"} by pattern matching. Pattern matching works wherever a formula is stated, in particular with \isacom{have} and \isacom{lemma}. The unknown \indexed{@{text"?thesis"}}{thesis} is implicitly matched against any goal stated by \isacom{lemma} or \isacom{show}. Here is a typical example: *} lemma "formula" proof - text_raw{*\\\mbox{}\quad$\vdots$\\\mbox{}\hspace{-1.4ex}*} show ?thesis (*<*)sorry(*>*) text_raw{*\ $\dots$\\*} qed text{* Unknowns can also be instantiated with \indexed{\isacom{let}}{let} commands \begin{quote} \isacom{let} @{text"?t"} = @{text"\""}\textit{some-big-term}@{text"\""} \end{quote} Later proof steps can refer to @{text"?t"}: \begin{quote} \isacom{have} @{text"\""}\dots @{text"?t"} \dots@{text"\""} \end{quote} \begin{warn} Names of facts are introduced with @{text"name:"} and refer to proved theorems. Unknowns @{text"?X"} refer to terms or formulas. \end{warn} Although abbreviations shorten the text, the reader needs to remember what they stand for. Similarly for names of facts. Names like @{text 1}, @{text 2} and @{text 3} are not helpful and should only be used in short proofs. For longer proofs, descriptive names are better. But look at this example: \begin{quote} \isacom{have} \ @{text"x_gr_0: \"x > 0\""}\\ $\vdots$\\ \isacom{from} @{text "x_gr_0"} \dots \end{quote} The name is longer than the fact it stands for! Short facts do not need names; one can refer to them easily by quoting them: \begin{quote} \isacom{have} \ @{text"\"x > 0\""}\\ $\vdots$\\ \isacom{from} @{text "`x>0`"} \dots\index{$IMP053@@{text"`...`"}} \end{quote} Note that the quotes around @{text"x>0"} are \conceptnoidx{back quotes}. They refer to the fact not by name but by value. \subsection{\indexed{\isacom{moreover}}{moreover}} \index{ultimately@\isacom{ultimately}} Sometimes one needs a number of facts to enable some deduction. Of course one can name these facts individually, as shown on the right, but one can also combine them with \isacom{moreover}, as shown on the left: *}text_raw{* \begin{tabular}{@ {}ll@ {}} \begin{minipage}[t]{.4\textwidth} \isa{% *} (*<*)lemma "P" proof-(*>*) have "P\<^sub>1" (*<*)sorry(*>*)text_raw{*\ $\dots$\\*} moreover have "P\<^sub>2" (*<*)sorry(*>*)text_raw{*\ $\dots$\\*} moreover text_raw{*\\$\vdots$\\\hspace{-1.4ex}*}(*<*)have "True" ..(*>*) moreover have "P\<^sub>n" (*<*)sorry(*>*)text_raw{*\ $\dots$\\*} ultimately have "P" (*<*)sorry(*>*)text_raw{*\ $\dots$\\*} (*<*)oops(*>*) text_raw {* } \end{minipage} & \qquad \begin{minipage}[t]{.4\textwidth} \isa{% *} (*<*)lemma "P" proof-(*>*) have lab\<^sub>1: "P\<^sub>1" (*<*)sorry(*>*)text_raw{*\ $\dots$\\*} have lab\<^sub>2: "P\<^sub>2" (*<*)sorry(*>*)text_raw{*\ $\dots$*} text_raw{*\\$\vdots$\\\hspace{-1.4ex}*} have lab\<^sub>n: "P\<^sub>n" (*<*)sorry(*>*)text_raw{*\ $\dots$\\*} from lab\<^sub>1 lab\<^sub>2 text_raw{*\ $\dots$\\*} have "P" (*<*)sorry(*>*)text_raw{*\ $\dots$\\*} (*<*)oops(*>*) text_raw {* } \end{minipage} \end{tabular} \begin{isamarkuptext}% The \isacom{moreover} version is no shorter but expresses the structure more clearly and avoids new names. \subsection{Raw Proof Blocks} Sometimes one would like to prove some lemma locally within a proof, a lemma that shares the current context of assumptions but that has its own assumptions and is generalized over its locally fixed variables at the end. This is what a \concept{raw proof block} does: \begin{quote}\index{$IMP053@@{text"{ ... }"} (proof block)} @{text"{"} \isacom{fix} @{text"x\<^sub>1 \<dots> x\<^sub>n"}\\ \mbox{}\ \ \ \isacom{assume} @{text"A\<^sub>1 \<dots> A\<^sub>m"}\\ \mbox{}\ \ \ $\vdots$\\ \mbox{}\ \ \ \isacom{have} @{text"B"}\\ @{text"}"} \end{quote} proves @{text"\<lbrakk> A\<^sub>1; \<dots> ; A\<^sub>m \<rbrakk> \<Longrightarrow> B"} where all @{text"x\<^sub>i"} have been replaced by unknowns @{text"?x\<^sub>i"}. \begin{warn} The conclusion of a raw proof block is \emph{not} indicated by \isacom{show} but is simply the final \isacom{have}. \end{warn} As an example we prove a simple fact about divisibility on integers. The definition of @{text "dvd"} is @{thm dvd_def}. \end{isamarkuptext}% *} lemma fixes a b :: int assumes "b dvd (a+b)" shows "b dvd a" proof - { fix k assume k: "a+b = b*k" have "\<exists>k'. a = b*k'" proof show "a = b*(k - 1)" using k by(simp add: algebra_simps) qed } then show ?thesis using assms by(auto simp add: dvd_def) qed text{* Note that the result of a raw proof block has no name. In this example it was directly piped (via \isacom{then}) into the final proof, but it can also be named for later reference: you simply follow the block directly by a \isacom{note} command: \begin{quote} \indexed{\isacom{note}}{note} \ @{text"name = this"} \end{quote} This introduces a new name @{text name} that refers to @{text this}, the fact just proved, in this case the preceding block. In general, \isacom{note} introduces a new name for one or more facts. \subsection*{Exercises} \exercise Give a readable, structured proof of the following lemma: *} lemma assumes T: "\<forall>x y. T x y \<or> T y x" and A: "\<forall>x y. A x y \<and> A y x \<longrightarrow> x = y" and TA: "\<forall>x y. T x y \<longrightarrow> A x y" and "A x y" shows "T x y" (*<*)oops(*>*) text{* \endexercise \exercise Give a readable, structured proof of the following lemma: *} lemma "(\<exists>ys zs. xs = ys @ zs \<and> length ys = length zs) \<or> (\<exists>ys zs. xs = ys @ zs \<and> length ys = length zs + 1)" (*<*)oops(*>*) text{* Hint: There are predefined functions @{const_typ take} and @{const_typ drop} such that @{text"take k [x\<^sub>1,\<dots>] = [x\<^sub>1,\<dots>,x\<^sub>k]"} and @{text"drop k [x\<^sub>1,\<dots>] = [x\<^bsub>k+1\<^esub>,\<dots>]"}. Let sledgehammer find and apply the relevant @{const take} and @{const drop} lemmas for you. \endexercise \section{Case Analysis and Induction} \subsection{Datatype Case Analysis} \index{case analysis|(} We have seen case analysis on formulas. Now we want to distinguish which form some term takes: is it @{text 0} or of the form @{term"Suc n"}, is it @{term"[]"} or of the form @{term"x#xs"}, etc. Here is a typical example proof by case analysis on the form of @{text xs}: *} lemma "length(tl xs) = length xs - 1" proof (cases xs) assume "xs = []" thus ?thesis by simp next fix y ys assume "xs = y#ys" thus ?thesis by simp qed text{*\index{cases@@{text"cases"}|(}Function @{text tl} (''tail'') is defined by @{thm list.sel(2)} and @{thm list.sel(3)}. Note that the result type of @{const length} is @{typ nat} and @{prop"0 - 1 = (0::nat)"}. This proof pattern works for any term @{text t} whose type is a datatype. The goal has to be proved for each constructor @{text C}: \begin{quote} \isacom{fix} \ @{text"x\<^sub>1 \<dots> x\<^sub>n"} \isacom{assume} @{text"\"t = C x\<^sub>1 \<dots> x\<^sub>n\""} \end{quote}\index{case@\isacom{case}|(} Each case can be written in a more compact form by means of the \isacom{case} command: \begin{quote} \isacom{case} @{text "(C x\<^sub>1 \<dots> x\<^sub>n)"} \end{quote} This is equivalent to the explicit \isacom{fix}-\isacom{assume} line but also gives the assumption @{text"\"t = C x\<^sub>1 \<dots> x\<^sub>n\""} a name: @{text C}, like the constructor. Here is the \isacom{case} version of the proof above: *} (*<*)lemma "length(tl xs) = length xs - 1"(*>*) proof (cases xs) case Nil thus ?thesis by simp next case (Cons y ys) thus ?thesis by simp qed text{* Remember that @{text Nil} and @{text Cons} are the alphanumeric names for @{text"[]"} and @{text"#"}. The names of the assumptions are not used because they are directly piped (via \isacom{thus}) into the proof of the claim. \index{case analysis|)} \subsection{Structural Induction} \index{induction|(} \index{structural induction|(} We illustrate structural induction with an example based on natural numbers: the sum (@{text"\<Sum>"}) of the first @{text n} natural numbers (@{text"{0..n::nat}"}) is equal to \mbox{@{term"n*(n+1) div 2::nat"}}. Never mind the details, just focus on the pattern: *} lemma "\<Sum>{0..n::nat} = n*(n+1) div 2" proof (induction n) show "\<Sum>{0..0::nat} = 0*(0+1) div 2" by simp next fix n assume "\<Sum>{0..n::nat} = n*(n+1) div 2" thus "\<Sum>{0..Suc n} = Suc n*(Suc n+1) div 2" by simp qed text{* Except for the rewrite steps, everything is explicitly given. This makes the proof easily readable, but the duplication means it is tedious to write and maintain. Here is how pattern matching can completely avoid any duplication: *} lemma "\<Sum>{0..n::nat} = n*(n+1) div 2" (is "?P n") proof (induction n) show "?P 0" by simp next fix n assume "?P n" thus "?P(Suc n)" by simp qed text{* The first line introduces an abbreviation @{text"?P n"} for the goal. Pattern matching @{text"?P n"} with the goal instantiates @{text"?P"} to the function @{term"\<lambda>n. \<Sum>{0..n::nat} = n*(n+1) div 2"}. Now the proposition to be proved in the base case can be written as @{text"?P 0"}, the induction hypothesis as @{text"?P n"}, and the conclusion of the induction step as @{text"?P(Suc n)"}. Induction also provides the \isacom{case} idiom that abbreviates the \isacom{fix}-\isacom{assume} step. The above proof becomes *} (*<*)lemma "\<Sum>{0..n::nat} = n*(n+1) div 2"(*>*) proof (induction n) case 0 show ?case by simp next case (Suc n) thus ?case by simp qed text{* The unknown @{text"?case"}\index{case?@@{text"?case"}|(} is set in each case to the required claim, i.e., @{text"?P 0"} and \mbox{@{text"?P(Suc n)"}} in the above proof, without requiring the user to define a @{text "?P"}. The general pattern for induction over @{typ nat} is shown on the left-hand side: *}text_raw{* \begin{tabular}{@ {}ll@ {}} \begin{minipage}[t]{.4\textwidth} \isa{% *} (*<*)lemma "P(n::nat)" proof -(*>*) show "P(n)" proof (induction n) case 0 text_raw{*\\\mbox{}\ \ $\vdots$\\\mbox{}\hspace{-1ex}*} show ?case (*<*)sorry(*>*) text_raw{*\ $\dots$\\*} next case (Suc n) text_raw{*\\\mbox{}\ \ $\vdots$\\\mbox{}\hspace{-1ex}*} show ?case (*<*)sorry(*>*) text_raw{*\ $\dots$\\*} qed(*<*)qed(*>*) text_raw {* } \end{minipage} & \begin{minipage}[t]{.4\textwidth} ~\\ ~\\ \isacom{let} @{text"?case = \"P(0)\""}\\ ~\\ ~\\ ~\\[1ex] \isacom{fix} @{text n} \isacom{assume} @{text"Suc: \"P(n)\""}\\ \isacom{let} @{text"?case = \"P(Suc n)\""}\\ \end{minipage} \end{tabular} \medskip *} text{* On the right side you can see what the \isacom{case} command on the left stands for. In case the goal is an implication, induction does one more thing: the proposition to be proved in each case is not the whole implication but only its conclusion; the premises of the implication are immediately made assumptions of that case. That is, if in the above proof we replace \isacom{show}~@{text"\"P(n)\""} by \mbox{\isacom{show}~@{text"\"A(n) \<Longrightarrow> P(n)\""}} then \isacom{case}~@{text 0} stands for \begin{quote} \isacom{assume} \ @{text"0: \"A(0)\""}\\ \isacom{let} @{text"?case = \"P(0)\""} \end{quote} and \isacom{case}~@{text"(Suc n)"} stands for \begin{quote} \isacom{fix} @{text n}\\ \isacom{assume} @{text"Suc:"} \begin{tabular}[t]{l}@{text"\"A(n) \<Longrightarrow> P(n)\""}\\@{text"\"A(Suc n)\""}\end{tabular}\\ \isacom{let} @{text"?case = \"P(Suc n)\""} \end{quote} The list of assumptions @{text Suc} is actually subdivided into @{text"Suc.IH"}, the induction hypotheses (here @{text"A(n) \<Longrightarrow> P(n)"}), and @{text"Suc.prems"}, the premises of the goal being proved (here @{text"A(Suc n)"}). Induction works for any datatype. Proving a goal @{text"\<lbrakk> A\<^sub>1(x); \<dots>; A\<^sub>k(x) \<rbrakk> \<Longrightarrow> P(x)"} by induction on @{text x} generates a proof obligation for each constructor @{text C} of the datatype. The command \isacom{case}~@{text"(C x\<^sub>1 \<dots> x\<^sub>n)"} performs the following steps: \begin{enumerate} \item \isacom{fix} @{text"x\<^sub>1 \<dots> x\<^sub>n"} \item \isacom{assume} the induction hypotheses (calling them @{text C.IH}\index{IH@@{text".IH"}}) and the premises \mbox{@{text"A\<^sub>i(C x\<^sub>1 \<dots> x\<^sub>n)"}} (calling them @{text"C.prems"}\index{prems@@{text".prems"}}) and calling the whole list @{text C} \item \isacom{let} @{text"?case = \"P(C x\<^sub>1 \<dots> x\<^sub>n)\""} \end{enumerate} \index{structural induction|)} \subsection{Rule Induction} \index{rule induction|(} Recall the inductive and recursive definitions of even numbers in \autoref{sec:inductive-defs}: *} inductive ev :: "nat \<Rightarrow> bool" where ev0: "ev 0" | evSS: "ev n \<Longrightarrow> ev(Suc(Suc n))" fun evn :: "nat \<Rightarrow> bool" where "evn 0 = True" | "evn (Suc 0) = False" | "evn (Suc(Suc n)) = evn n" text{* We recast the proof of @{prop"ev n \<Longrightarrow> evn n"} in Isar. The left column shows the actual proof text, the right column shows the implicit effect of the two \isacom{case} commands:*}text_raw{* \begin{tabular}{@ {}l@ {\qquad}l@ {}} \begin{minipage}[t]{.5\textwidth} \isa{% *} lemma "ev n \<Longrightarrow> evn n" proof(induction rule: ev.induct) case ev0 show ?case by simp next case evSS thus ?case by simp qed text_raw {* } \end{minipage} & \begin{minipage}[t]{.5\textwidth} ~\\ ~\\ \isacom{let} @{text"?case = \"evn 0\""}\\ ~\\ ~\\ \isacom{fix} @{text n}\\ \isacom{assume} @{text"evSS:"} \begin{tabular}[t]{l} @{text"\"ev n\""}\\@{text"\"evn n\""}\end{tabular}\\ \isacom{let} @{text"?case = \"evn(Suc(Suc n))\""}\\ \end{minipage} \end{tabular} \medskip *} text{* The proof resembles structural induction, but the induction rule is given explicitly and the names of the cases are the names of the rules in the inductive definition. Let us examine the two assumptions named @{thm[source]evSS}: @{prop "ev n"} is the premise of rule @{thm[source]evSS}, which we may assume because we are in the case where that rule was used; @{prop"evn n"} is the induction hypothesis. \begin{warn} Because each \isacom{case} command introduces a list of assumptions named like the case name, which is the name of a rule of the inductive definition, those rules now need to be accessed with a qualified name, here @{thm[source] ev.ev0} and @{thm[source] ev.evSS}. \end{warn} In the case @{thm[source]evSS} of the proof above we have pretended that the system fixes a variable @{text n}. But unless the user provides the name @{text n}, the system will just invent its own name that cannot be referred to. In the above proof, we do not need to refer to it, hence we do not give it a specific name. In case one needs to refer to it one writes \begin{quote} \isacom{case} @{text"(evSS m)"} \end{quote} like \isacom{case}~@{text"(Suc n)"} in earlier structural inductions. The name @{text m} is an arbitrary choice. As a result, case @{thm[source] evSS} is derived from a renamed version of rule @{thm[source] evSS}: @{text"ev m \<Longrightarrow> ev(Suc(Suc m))"}. Here is an example with a (contrived) intermediate step that refers to @{text m}: *} lemma "ev n \<Longrightarrow> evn n" proof(induction rule: ev.induct) case ev0 show ?case by simp next case (evSS m) have "evn(Suc(Suc m)) = evn m" by simp thus ?case using `evn m` by blast qed text{* \indent In general, let @{text I} be a (for simplicity unary) inductively defined predicate and let the rules in the definition of @{text I} be called @{text "rule\<^sub>1"}, \dots, @{text "rule\<^sub>n"}. A proof by rule induction follows this pattern:\index{inductionrule@@{text"induction ... rule:"}} *} (*<*) inductive I where rule\<^sub>1: "I()" | rule\<^sub>2: "I()" | rule\<^sub>n: "I()" lemma "I x \<Longrightarrow> P x" proof-(*>*) show "I x \<Longrightarrow> P x" proof(induction rule: I.induct) case rule\<^sub>1 text_raw{*\\[-.4ex]\mbox{}\ \ $\vdots$\\[-.4ex]\mbox{}\hspace{-1ex}*} show ?case (*<*)sorry(*>*)text_raw{*\ $\dots$\\*} next text_raw{*\\[-.4ex]$\vdots$\\[-.4ex]\mbox{}\hspace{-1ex}*} (*<*) case rule\<^sub>2 show ?case sorry (*>*) next case rule\<^sub>n text_raw{*\\[-.4ex]\mbox{}\ \ $\vdots$\\[-.4ex]\mbox{}\hspace{-1ex}*} show ?case (*<*)sorry(*>*)text_raw{*\ $\dots$\\*} qed(*<*)qed(*>*) text{* One can provide explicit variable names by writing \isacom{case}~@{text"(rule\<^sub>i x\<^sub>1 \<dots> x\<^sub>k)"}, thus renaming the first @{text k} free variables in rule @{text i} to @{text"x\<^sub>1 \<dots> x\<^sub>k"}, going through rule @{text i} from left to right. \subsection{Assumption Naming} \label{sec:assm-naming} In any induction, \isacom{case}~@{text name} sets up a list of assumptions also called @{text name}, which is subdivided into three parts: \begin{description} \item[@{text name.IH}]\index{IH@@{text".IH"}} contains the induction hypotheses. \item[@{text name.hyps}]\index{hyps@@{text".hyps"}} contains all the other hypotheses of this case in the induction rule. For rule inductions these are the hypotheses of rule @{text name}, for structural inductions these are empty. \item[@{text name.prems}]\index{prems@@{text".prems"}} contains the (suitably instantiated) premises of the statement being proved, i.e., the @{text A\<^sub>i} when proving @{text"\<lbrakk> A\<^sub>1; \<dots>; A\<^sub>n \<rbrakk> \<Longrightarrow> A"}. \end{description} \begin{warn} Proof method @{text induct} differs from @{text induction} only in this naming policy: @{text induct} does not distinguish @{text IH} from @{text hyps} but subsumes @{text IH} under @{text hyps}. \end{warn} More complicated inductive proofs than the ones we have seen so far often need to refer to specific assumptions --- just @{text name} or even @{text name.prems} and @{text name.IH} can be too unspecific. This is where the indexing of fact lists comes in handy, e.g., @{text"name.IH(2)"} or @{text"name.prems(1-2)"}. \subsection{Rule Inversion} \label{sec:rule-inversion} \index{rule inversion|(} Rule inversion is case analysis of which rule could have been used to derive some fact. The name \conceptnoidx{rule inversion} emphasizes that we are reasoning backwards: by which rules could some given fact have been proved? For the inductive definition of @{const ev}, rule inversion can be summarized like this: @{prop[display]"ev n \<Longrightarrow> n = 0 \<or> (EX k. n = Suc(Suc k) \<and> ev k)"} The realisation in Isabelle is a case analysis. A simple example is the proof that @{prop"ev n \<Longrightarrow> ev (n - 2)"}. We already went through the details informally in \autoref{sec:Logic:even}. This is the Isar proof: *} (*<*) notepad begin fix n (*>*) assume "ev n" from this have "ev(n - 2)" proof cases case ev0 thus "ev(n - 2)" by (simp add: ev.ev0) next case (evSS k) thus "ev(n - 2)" by (simp add: ev.evSS) qed (*<*) end (*>*) text{* The key point here is that a case analysis over some inductively defined predicate is triggered by piping the given fact (here: \isacom{from}~@{text this}) into a proof by @{text cases}. Let us examine the assumptions available in each case. In case @{text ev0} we have @{text"n = 0"} and in case @{text evSS} we have @{prop"n = Suc(Suc k)"} and @{prop"ev k"}. In each case the assumptions are available under the name of the case; there is no fine-grained naming schema like there is for induction. Sometimes some rules could not have been used to derive the given fact because constructors clash. As an extreme example consider rule inversion applied to @{prop"ev(Suc 0)"}: neither rule @{text ev0} nor rule @{text evSS} can yield @{prop"ev(Suc 0)"} because @{text"Suc 0"} unifies neither with @{text 0} nor with @{term"Suc(Suc n)"}. Impossible cases do not have to be proved. Hence we can prove anything from @{prop"ev(Suc 0)"}: *} (*<*) notepad begin fix P (*>*) assume "ev(Suc 0)" then have P by cases (*<*) end (*>*) text{* That is, @{prop"ev(Suc 0)"} is simply not provable: *} lemma "\<not> ev(Suc 0)" proof assume "ev(Suc 0)" then show False by cases qed text{* Normally not all cases will be impossible. As a simple exercise, prove that \mbox{@{prop"\<not> ev(Suc(Suc(Suc 0)))"}.} \subsection{Advanced Rule Induction} \label{sec:advanced-rule-induction} So far, rule induction was always applied to goals of the form @{text"I x y z \<Longrightarrow> \<dots>"} where @{text I} is some inductively defined predicate and @{text x}, @{text y}, @{text z} are variables. In some rare situations one needs to deal with an assumption where not all arguments @{text r}, @{text s}, @{text t} are variables: \begin{isabelle} \isacom{lemma} @{text"\"I r s t \<Longrightarrow> \<dots>\""} \end{isabelle} Applying the standard form of rule induction in such a situation will lead to strange and typically unprovable goals. We can easily reduce this situation to the standard one by introducing new variables @{text x}, @{text y}, @{text z} and reformulating the goal like this: \begin{isabelle} \isacom{lemma} @{text"\"I x y z \<Longrightarrow> x = r \<Longrightarrow> y = s \<Longrightarrow> z = t \<Longrightarrow> \<dots>\""} \end{isabelle} Standard rule induction will work fine now, provided the free variables in @{text r}, @{text s}, @{text t} are generalized via @{text"arbitrary"}. However, induction can do the above transformation for us, behind the curtains, so we never need to see the expanded version of the lemma. This is what we need to write: \begin{isabelle} \isacom{lemma} @{text"\"I r s t \<Longrightarrow> \<dots>\""}\isanewline \isacom{proof}@{text"(induction \"r\" \"s\" \"t\" arbitrary: \<dots> rule: I.induct)"}\index{inductionrule@@{text"induction ... rule:"}}\index{arbitrary@@{text"arbitrary:"}} \end{isabelle} Like for rule inversion, cases that are impossible because of constructor clashes will not show up at all. Here is a concrete example: *} lemma "ev (Suc m) \<Longrightarrow> \<not> ev m" proof(induction "Suc m" arbitrary: m rule: ev.induct) fix n assume IH: "\<And>m. n = Suc m \<Longrightarrow> \<not> ev m" show "\<not> ev (Suc n)" proof --"contradiction" assume "ev(Suc n)" thus False proof cases --"rule inversion" fix k assume "n = Suc k" "ev k" thus False using IH by auto qed qed qed text{* Remarks: \begin{itemize} \item Instead of the \isacom{case} and @{text ?case} magic we have spelled all formulas out. This is merely for greater clarity. \item We only need to deal with one case because the @{thm[source] ev0} case is impossible. \item The form of the @{text IH} shows us that internally the lemma was expanded as explained above: \noquotes{@{prop[source]"ev x \<Longrightarrow> x = Suc m \<Longrightarrow> \<not> ev m"}}. \item The goal @{prop"\<not> ev (Suc n)"} may surprise. The expanded version of the lemma would suggest that we have a \isacom{fix} @{text m} \isacom{assume} @{prop"Suc(Suc n) = Suc m"} and need to show @{prop"\<not> ev m"}. What happened is that Isabelle immediately simplified @{prop"Suc(Suc n) = Suc m"} to @{prop"Suc n = m"} and could then eliminate @{text m}. Beware of such nice surprises with this advanced form of induction. \end{itemize} \begin{warn} This advanced form of induction does not support the @{text IH} naming schema explained in \autoref{sec:assm-naming}: the induction hypotheses are instead found under the name @{text hyps}, as they are for the simpler @{text induct} method. \end{warn} \index{induction|)} \index{cases@@{text"cases"}|)} \index{case@\isacom{case}|)} \index{case?@@{text"?case"}|)} \index{rule induction|)} \index{rule inversion|)} \subsection*{Exercises} \exercise Give a structured proof by rule inversion: *} lemma assumes a: "ev(Suc(Suc n))" shows "ev n" (*<*)oops(*>*) text{* \endexercise \begin{exercise} Give a structured proof of @{prop "\<not> ev(Suc(Suc(Suc 0)))"} by rule inversions. If there are no cases to be proved you can close a proof immediately with \isacom{qed}. \end{exercise} \begin{exercise} Recall predicate @{text star} from \autoref{sec:star} and @{text iter} from Exercise~\ref{exe:iter}. Prove @{prop "iter r n x y \<Longrightarrow> star r x y"} in a structured style; do not just sledgehammer each case of the required induction. \end{exercise} \begin{exercise} Define a recursive function @{text "elems ::"} @{typ"'a list \<Rightarrow> 'a set"} and prove @{prop "x : elems xs \<Longrightarrow> \<exists>ys zs. xs = ys @ x # zs \<and> x \<notin> elems ys"}. \end{exercise} \begin{exercise} Extend Exercise~\ref{exe:cfg} with a function that checks if some \mbox{@{text "alpha list"}} is a balanced string of parentheses. More precisely, define a \mbox{recursive} function @{text "balanced :: nat \<Rightarrow> alpha list \<Rightarrow> bool"} such that @{term"balanced n w"} is true iff (informally) @{text"S (a\<^sup>n @ w)"}. Formally, prove that @{prop "balanced n w \<longleftrightarrow> S (replicate n a @ w)"} where @{const replicate} @{text"::"} @{typ"nat \<Rightarrow> 'a \<Rightarrow> 'a list"} is predefined and @{term"replicate n x"} yields the list @{text"[x, \<dots>, x]"} of length @{text n}. \end{exercise} *} (*<*) end (*>*)
# Decision Lens API # # No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # # OpenAPI spec version: 1.0 # # Generated by: https://github.com/swagger-api/swagger-codegen.git #' CommentAddedEvent Class #' #' @field id #' @field portfolioId #' @field userId #' @field projectId #' @field projectName #' @field portfolioPlan #' @field value #' #' @importFrom R6 R6Class #' @importFrom jsonlite fromJSON toJSON #' @export CommentAddedEvent <- R6::R6Class( 'CommentAddedEvent', public = list( `id` = NULL, `portfolioId` = NULL, `userId` = NULL, `projectId` = NULL, `projectName` = NULL, `portfolioPlan` = NULL, `value` = NULL, initialize = function(`id`, `portfolioId`, `userId`, `projectId`, `projectName`, `portfolioPlan`, `value`){ if (!missing(`id`)) { stopifnot(is.character(`id`), length(`id`) == 1) self$`id` <- `id` } if (!missing(`portfolioId`)) { stopifnot(is.character(`portfolioId`), length(`portfolioId`) == 1) self$`portfolioId` <- `portfolioId` } if (!missing(`userId`)) { stopifnot(is.character(`userId`), length(`userId`) == 1) self$`userId` <- `userId` } if (!missing(`projectId`)) { stopifnot(is.character(`projectId`), length(`projectId`) == 1) self$`projectId` <- `projectId` } if (!missing(`projectName`)) { stopifnot(is.character(`projectName`), length(`projectName`) == 1) self$`projectName` <- `projectName` } if (!missing(`portfolioPlan`)) { stopifnot(R6::is.R6(`portfolioPlan`)) self$`portfolioPlan` <- `portfolioPlan` } if (!missing(`value`)) { stopifnot(is.character(`value`), length(`value`) == 1) self$`value` <- `value` } }, toJSON = function() { CommentAddedEventObject <- list() if (!is.null(self$`id`)) { CommentAddedEventObject[['id']] <- self$`id` } if (!is.null(self$`portfolioId`)) { CommentAddedEventObject[['portfolioId']] <- self$`portfolioId` } if (!is.null(self$`userId`)) { CommentAddedEventObject[['userId']] <- self$`userId` } if (!is.null(self$`projectId`)) { CommentAddedEventObject[['projectId']] <- self$`projectId` } if (!is.null(self$`projectName`)) { CommentAddedEventObject[['projectName']] <- self$`projectName` } if (!is.null(self$`portfolioPlan`)) { CommentAddedEventObject[['portfolioPlan']] <- self$`portfolioPlan`$toJSON() } if (!is.null(self$`value`)) { CommentAddedEventObject[['value']] <- self$`value` } CommentAddedEventObject }, fromJSON = function(CommentAddedEventJson) { CommentAddedEventObject <- dlensFromJSON(CommentAddedEventJson) if (!is.null(CommentAddedEventObject$`id`)) { self$`id` <- CommentAddedEventObject$`id` } if (!is.null(CommentAddedEventObject$`portfolioId`)) { self$`portfolioId` <- CommentAddedEventObject$`portfolioId` } if (!is.null(CommentAddedEventObject$`userId`)) { self$`userId` <- CommentAddedEventObject$`userId` } if (!is.null(CommentAddedEventObject$`projectId`)) { self$`projectId` <- CommentAddedEventObject$`projectId` } if (!is.null(CommentAddedEventObject$`projectName`)) { self$`projectName` <- CommentAddedEventObject$`projectName` } if (!is.null(CommentAddedEventObject$`portfolioPlan`)) { portfolioPlanObject <- PortfolioPlan$new() portfolioPlanObject$fromJSON(jsonlite::toJSON(CommentAddedEventObject$portfolioPlan, auto_unbox = TRUE)) self$`portfolioPlan` <- portfolioPlanObject } if (!is.null(CommentAddedEventObject$`value`)) { self$`value` <- CommentAddedEventObject$`value` } }, toJSONString = function() { sprintf( '{ "id": %s, "portfolioId": %s, "userId": %s, "projectId": %s, "projectName": %s, "portfolioPlan": %s, "value": %s }', self$`id`, self$`portfolioId`, self$`userId`, self$`projectId`, self$`projectName`, self$`portfolioPlan`$toJSON(), self$`value` ) }, fromJSONString = function(CommentAddedEventJson) { CommentAddedEventObject <- dlensFromJSON(CommentAddedEventJson) self$`id` <- CommentAddedEventObject$`id` self$`portfolioId` <- CommentAddedEventObject$`portfolioId` self$`userId` <- CommentAddedEventObject$`userId` self$`projectId` <- CommentAddedEventObject$`projectId` self$`projectName` <- CommentAddedEventObject$`projectName` PortfolioPlanObject <- PortfolioPlan$new() self$`portfolioPlan` <- PortfolioPlanObject$fromJSON(jsonlite::toJSON(CommentAddedEventObject$portfolioPlan, auto_unbox = TRUE)) self$`value` <- CommentAddedEventObject$`value` } ) )
#ifndef COMPUTE_SIGNAL_H #define COMPUTE_SIGNAL_H #include <gsl/gsl_rng.h> #include <gsl/gsl_histogram.h> void compute_signal(double * signal, const size_t length, const double delta, gsl_rng * r, gsl_histogram * hist); #endif
function volCoords = functional2volXformCoords(inplane, gray, preserveExactValues) % Return coords from Volume view that correspond to coords in % mrVista functional inplane coords % % volCoords = functional2volXformCoords(inplane, gray, preserveExactValues) % % We first get a 3xn matrix of functional view coordinates, then find the % corresponding inplane anatomical coordinates, and finally find the % corresponding volume coordinates. We use this transform when % we want to convert functional data (e.g., a parameter map, coranal, or % time series) from the volume view to the inplane view. % % INPUTS % inplane: mrVista view structure (must be an inplane view) % gray: mrVista view structure (must be a gray view) % preserveExactValues: boolean. If false, return integer coordinates. If % true, return the calculated (non-integer values). If % non-integer values are returned, then the parent % function will have to deal with these, e.g., via % interpolation. % OUTPUTS % volCoords: 3xn matrix of coordinates in Volume space % corresponding to 3xn matrix of inplane functional coords % % Example: % volCoords = ip2volXformCoords(inplane, gray) % % % CO & JW 2016.01.14 % Don't do this unless inplane is really an inplane and volume is really a volume if ~strcmp(viewGet(inplane, 'viewType'),'Inplane') myErrorDlg('ip2volParMap can only be used to transform from inplane to volume/gray.'); end if ~strcmp(viewGet(gray, 'viewType'),'Volume') &&~strcmp(viewGet(gray, 'viewType'),'Gray') myErrorDlg('ip2volParMap can only be used to transform from inplane to volume/gray.'); end % check inputs if ~exist('preserveExactValues', 'var'), preserveExactValues = false; end % we need mrSESSION for the alignment matrix mrGlobals; % The gray coords are the integer-valued (y,x,z) volume % coordinates that correspond to the inplanes. Convert to % homogeneous form by adding a row of ones. preserveCoords = true; functionalCoords = ip2functionalCoords(inplane, viewGet(inplane, 'coords'), ... [], preserveCoords, preserveExactValues); nVoxels = size(functionalCoords, 2); functionalCoords = double([functionalCoords; ones(1,nVoxels)]); % inplane2VolXform is the 4x4 homogeneous transform matrix that % takes inplane (y',x',z',1) coordinates into Volume (y,x,z,1) % coordinates. inplane2VolXform = sessionGet(mrSESSION,'alignment'); % We don't care about the last coordinate in (y,x,z,1), so we % toss the fourth row of Xform. Then our outputs will be (y,x,z). % inplane2VolXform = inplane2VolXform(1:3,:); % Transform coord positions to the volume. Hence, grayCoords % contains the volume position of each of the inplane voxels. These % will generally not fall on integer-valued coordinates, rather they will % fall between voxels. Other functions that rely on the output of this % function will require interpolation to get the data at these % between-voxel positions. % volCoords = inplane2VolXform*functionalCoords; % % Convert coords from inplane anatomical space to inplane functional space. % % We do this because the anatomical inplane is often higher resolution than % % the functional data. We preserve the number of coords so that the number % % of output functional voxels is identical to the number of gray or volume % % voxels. If requested, we preserve the exact (non-integer) values, which % % means that the functional coordinates will lie in locations between the % % actual functional data points. % preserveCoords = true; % volCoords = ip2functionalCoords(inplane, ipAnatomicalCoords, ... % [], preserveCoords, preserveExactValues); % Some confusion about zeros in the output coordinates. It seems best to % leave the calculations as they are unless there is a problem that someone % understands. See below. % HH, 6/16/2012: If we use the code below, we elimintate some voxels % and then nVoxels is different from the size of ipCoords, leading to a % mismatch in the size of the expected time series (tSeries) and the % size of interpolated tSeries, causing an error in the line, % tSeries(frame,:) = interp3(subData, ... % ipFuncCoords(2,:), ... % ipFuncCoords(1,:), ... % ipFuncCoords(3,:), ... % method); % % Hence we comment out the lines below. Leaving in the values with 0 % did not produce an error, at least for the function we tested it on, % ip2volTSeries. % % % ras 12/20/04: % % occasionally the xformed grayCoords will include a 0 % % coordinate. While it seems this should not happen, % % I'm applying this band-aid for the time being: % [badRows badCols] = find(ipFuncCoords==0); %#ok<ASGLU> % goodCols = setdiff(1:nVoxels, badCols); % ipFuncCoords = ipFuncCoords(:,goodCols); % if length(badCols)>1 % fprintf('%i voxels mapped to slice 0...\n',length(badCols)); % end return
{-# OPTIONS --warning=error --safe --without-K #-} open import LogicalFormulae open import Orders.WellFounded.Definition open import Numbers.Naturals.Semiring open import Numbers.Naturals.Order open import Semirings.Definition module Numbers.Naturals.Order.WellFounded where open Semiring ℕSemiring <NWellfounded : WellFounded _<N_ <NWellfounded = λ x → access (go x) where lemma : {a b c : ℕ} → a <N b → b <N succ c → a <N c lemma {a} {b} {c} (le y succYAeqB) (le z zbEqC') = le (y +N z) p where zbEqC : z +N b ≡ c zSuccYAEqC : z +N (succ y +N a) ≡ c zSuccYAEqC' : z +N (succ (y +N a)) ≡ c zSuccYAEqC'' : succ (z +N (y +N a)) ≡ c zSuccYAEqC''' : succ ((z +N y) +N a) ≡ c p : succ ((y +N z) +N a) ≡ c p = identityOfIndiscernablesLeft _≡_ zSuccYAEqC''' (applyEquality (λ n → succ (n +N a)) (commutative z y)) zSuccYAEqC''' = identityOfIndiscernablesLeft _≡_ zSuccYAEqC'' (applyEquality succ (+Associative z y a)) zSuccYAEqC'' = identityOfIndiscernablesLeft _≡_ zSuccYAEqC' (succExtracts z (y +N a)) zSuccYAEqC' = identityOfIndiscernablesLeft _≡_ zSuccYAEqC (applyEquality (λ r → z +N r) refl) zbEqC = succInjective zbEqC' zSuccYAEqC = identityOfIndiscernablesLeft _≡_ zbEqC (applyEquality (λ r → z +N r) (equalityCommutative succYAeqB)) go : ∀ n m → m <N n → Accessible _<N_ m go zero m (le x ()) go (succ n) zero mLessN = access (λ y ()) go (succ n) (succ m) smLessSN = access (λ o (oLessSM : o <N succ m) → go n o (lemma oLessSM smLessSN))
import ..lectures.love07_metaprogramming_alt_demo /-! # LoVe Exercise 7: Metaprogramming -/ set_option pp.beta true set_option pp.generalized_field_notation false namespace LoVe /-! ## Question 1: A Term Exploder In this question, we develop a string format for the `expr` metatype. By default, there is no `has_repr` instance to print a nice string. For example: -/ #eval (expr.app (expr.var 0) (expr.var 1) : expr) -- result: `[external]` #eval (`(λx : ℕ, x + x) : expr) -- result: `[external]` /-! 1.1. Define a metafunction `expr.repr` that converts an `expr` into a `string`. It is acceptable to leave out some fields from the `expr` constructors, such as the level `l` of a sort, the binder information `bi` of a `λ` or `∀` binder, and the arguments of the `macro` constructor. Hint: Use `name.to_string` to convert a name to a string, and `repr` for other types that belong to the `has_repr` type class. -/ meta def expr.repr : expr → string | (expr.var n) := "(var " ++ repr n ++ ")" -- fill in the remaining cases! /-! We register `expr.repr` in the `has_repr` type class, so that we can use `repr` without qualification in the future, and so that it is available to `#eval`. We need the `meta` keyword in front of the command we enter. -/ meta instance expr.has_repr : has_repr expr := { repr := expr.repr } /-! 1.2. Test your setup. -/ #eval (expr.app (expr.var 0) (expr.var 1) : expr) #eval (`(λx : ℕ, x + x) : expr) /-! ## Question 2: `destruct_and` on Steroids Recall from the lecture that `destruct_and` fails on easy goals such as -/ lemma abc_ac₂ (a b c : Prop) (h : a ∧ b ∧ c) : a ∧ c := sorry /-! We will now address this by developing a new tactic called `destro_and`, which applies both **des**truction and in**tro**duction rules for conjunction. It will also go automatically through the hypotheses instead of taking an argument. We will develop it in three steps. 2.1. Develop a tactic `intro_ands` that replaces all goals of the form `a ∧ b` with two new goals `a` and `b` systematically, until all top-level conjunctions are gone. For this, we can use tactics such as `tactic.repeat` (which repeatedly applies a tactic on all goals and subgoals until the tactic fails on each of the goal) and `tactic.applyc` (which can be used to apply a rule, in connection with backtick quoting). -/ #check tactic.repeat #check tactic.applyc meta def intro_ands : tactic unit := sorry lemma abcd_bd (a b c d : Prop) (h : a ∧ (b ∧ c) ∧ d) : b ∧ d := begin intro_ands, /- The proof state should be as follows: 2 goals a b c d : Prop, h : a ∧ (b ∧ c) ∧ d ⊢ b a b c d : Prop, h : a ∧ (b ∧ c) ∧ d ⊢ d -/ repeat { sorry } end lemma abcd_bacb (a b c d : Prop) (h : a ∧ (b ∧ c) ∧ d) : b ∧ (a ∧ (c ∧ b)) := begin intro_ands, /- The proof state should be as follows: 4 goals a b c d : Prop, h : a ∧ (b ∧ c) ∧ d ⊢ b a b c d : Prop, h : a ∧ (b ∧ c) ∧ d ⊢ a a b c d : Prop, h : a ∧ (b ∧ c) ∧ d ⊢ c a b c d : Prop, h : a ∧ (b ∧ c) ∧ d ⊢ b -/ repeat { sorry } end /-! 2.2. Develop a tactic `destruct_ands` that replaces hypotheses of the form `h : a ∧ b` by two new hypotheses `h_left : a` and `h_right : b` systematically, until all top-level conjunctions are gone. Here is some pseudocode that you can follow: 1. Retrieve the list of hypotheses from the context. This is provided by the metaconstant `tactic.local_context`. 2. Find the first hypothesis (= term) with a type (= proposition) of the form `_ ∧ _`. Here, you can use the `list.mfirst` function, in conjunction with pattern matching. You can use `tactic.infer_type` to query the type of a term. 3. Perform a case split on the first found hypothesis. This can be achieved using `tactic.cases`, a metaprogram that corresponds roughly to `cases'`. 4. Repeat. The above procedure might fail if there exists no hypotheses of the required form. Make sure to handle this failure gracefully, for example using `tactic.try` or `<|> pure ()`. -/ meta def destruct_ands : tactic unit := sorry lemma abcd_bd₂ (a b c d : Prop) (h : a ∧ (b ∧ c) ∧ d) : b ∧ d := begin destruct_ands, /- The proof state should be as follows: a b c d : Prop, h_left : a, h_right_right : d, h_right_left_left : b, h_right_left_right : c ⊢ b ∧ d -/ sorry end /-! 2.3. Combine the two tactics developed above and `tactic.assumption` to implement the desired `destro_and` tactic. -/ meta def destro_and : tactic unit := sorry lemma abcd_bd₃ (a b c d : Prop) (h : a ∧ (b ∧ c) ∧ d) : b ∧ d := by destro_and lemma abcd_bacb₂ (a b c d : Prop) (h : a ∧ (b ∧ c) ∧ d) : b ∧ (a ∧ (c ∧ b)) := by destro_and lemma abd_bacb (a b c d : Prop) (h : a ∧ b ∧ d) : b ∧ (a ∧ (c ∧ b)) := begin destro_and, /- The proof state should be roughly as follows: a b c d : Prop, h_left : a, h_right_left : b, h_right_right : d ⊢ c -/ sorry -- unprovable end /-! 2.4. Provide some more examples for `destro_and` to convince yourself that it works as expected also on more complicated examples. -/ /-! ## Question 3 (**optional**): A Theorem Finder We will implement a function that allows us to find theorems by constants appearing in their statements. So given a list of constant names, the function will list all theorems in which all these constants appear. You can use the following metaconstants: * `declaration` contains all data (name, type, value) associated with a declaration understood broadly (e.g., axiom, lemma, constant, etc.). * `tactic.get_env` gives us access to the `environment`, a metatype that lists all `declaration`s (including all theorems). * `environment.fold` allows us to walk through the environment and collect data. * `expr.fold` allows us to walk through an expression and collect data. 3.1 (**optional**). Write a metafunction that checks whether an expression contains a specific constant. You can use `expr.fold` to walk through the expression, `||` and `ff` for Booleans, and `expr.is_constant_of` to check whether an expression is a constant. -/ meta def term_contains (e : expr) (nam : name) : bool := sorry /-! 3.2 (**optional**). Write a metafunction that checks whether an expression contains **all** constants in a list. You can use `list.band` (Boolean and). -/ meta def term_contains_all (nams : list name) (e : expr) : bool := sorry /-! 3.3 (**optional**). Produce the list of all theorems that contain all constants `nams` in their statement. `environment.fold` allows you to walk over the list of declarations. With `declaration.type`, you get the type of a theorem, and with `declaration.to_name` you get the name. -/ meta def list_constants (nams : list name) (e : environment) : list name := sorry /-! Finally, we develop a tactic that uses the above metafunctions to log all found theorems: -/ meta def find_constants (nams : list name) : tactic unit := do env ← tactic.get_env, list.mmap' tactic.trace (list_constants nams env) /-! We test the solution. -/ run_cmd find_constants [] -- lists all theorems run_cmd find_constants [`list.map, `function.comp] end LoVe
function [varargout] = stdDevDose(planC, varargin) %Calculate the std dev of the dose (non-variance corrected). %Stand alone metric : stdDevDose(planC, structNum, doseNum); %Request m object : stdDevDose(planC, 'getnewmetric'); %Evaluate m object : stdDevDose(planC, m, 'evaluate'); %LM: 6 Oct 06, JOD: new metric. % % Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team. % % This file is part of The Computational Environment for Radiotherapy Research (CERR). % % CERR development has been led by: Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy. % % CERR has been financially supported by the US National Institutes of Health under multiple grants. % % CERR is distributed under the terms of the Lesser GNU Public License. % % This version of CERR 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. % % CERR 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 CERR. If not, see <http://www.gnu.org/licenses/>. indexS = planC{end}; optS = planC{indexS.CERROptions}; if(nargin > 1) call = varargin{end}; else warning('Incorrect Usage, try: stdDevDose(planC, structNum, doseNum);'); return; end switch upper(call) case 'GETNEWMETRIC' m.name = 'stdDevDose'; m.valueV = []; m.description = 'Returns the standard deviation (non-variance corrected) dose in specified structure'; m.functionName = @stdDevDose; m.note = ''; m.params(1).name = 'Structure'; m.params(1).type = 'DropDown'; m.params(1).list = {planC{indexS.structures}.structureName}; m.params(1).value = 1; m.params(2).name = 'IsTarget?'; m.params(2).type = 'DropDown'; m.params(2).list ={'Target', 'Not Target'}; m.params(2).value = 2; m.units = []; m.range = [0 inf]; m.doseSets = [1]; varargout = {planC,m}; return; case 'EVALUATE' m = varargin{1}; structName = planC{indexS.structures}(m.params(1).value).structureName; m.note = structName; m.valueV = []; maxD = -inf; for i=1:length(m.doseSets) [planC, doseBinsV, volsHistV] = getDVHMatrix(planC, m.params(1).value, m.doseSets(i)); ans = calc_stdDevDose(doseBinsV, volsHistV); m.valueV = [m.valueV ans]; maxD = max(maxD, max(planC{indexS.dose}(m.doseSets(i)).doseArray(:))); end if m.params(2).value == 1 %Is target, high dose is best. m.range = [0 max(m.valueV)]; elseif m.params(2).value == 2 m.range = [maxD min(m.valueV)]; end m.units = getDoseUnitsStr(i,planC); varargout = {planC,m}; return; otherwise %No specific call has been made, assume user just wants raw metric. if(nargin == 3) structNum = varargin{1}; doseNum = varargin{2}; [planC, doseBinsV, volsHistV] = getDVHMatrix(planC, structNum, doseNum); varargout = {calc_stdDevDose(doseBinsV, volsHistV)}; else error('Not enough parameters, try: stdDevDose(planC, structNum, doseNum);') return; end end
module Universe where import Graphics.Rendering.OpenGL as OpenGL import AObject import Politics import Statistics import Tree import OpenGLUtils aobjs :: AObjTree aobjs = Node (0.0, 0.0) [ Leaf $ AObject "Star" 0 (Color4 0.9 0.0 0.0 1.0) 6.0 1.0 0 glVector3Null Nothing , Leaf $ AObject "Murphy's" 10 (Color4 0.5 0.5 1.0 1.0) 2.0 1.0 28 glVector3Null (Just "Murphy") , Leaf $ AObject "Loki" 250 (Color4 0.0 0.4 0.5 1.0) 4.0 1.0 55 glVector3Null (Just "Harju") , Node (30, 115) $ [Leaf $ AObject "Harju" 30 (Color4 0.6 0.6 0.6 1.0) 9.0 1.0 0 glVector3Null (Just "Harju") , Leaf $ AObject "Harju's Moon" 30 (Color4 0.2 0.9 0.6 1.0) 0.8 1.0 25 glVector3Null (Just "Harju")] , Leaf $ AObject "Riesenland" 80 (Color4 0.1 0.8 0.8 1.0) 2.0 1.0 230 glVector3Null (Just "Riesenland") , Leaf $ AObject "Riesenland" 80 (Color4 0.1 0.8 0.8 1.0) 2.0 1.0 230 glVector3Null (Just "Riesenland") , Node (180, 480) $ [Leaf $ AObject "Natail" 180 (Color4 0.2 0.2 0.9 1.0) 1.0 1.5 60 glVector3Null (Just "Natail") , Leaf $ AObject "Mammoth" 0 (Color4 0.3 0.0 0.6 1.0) 1.5 1.0 40 glVector3Null (Just "Natail")] ] relations = mkRelationshipMap relationsList relationsList = [(("Murphy", "Harju"), (Peace, -5)), (("Murphy", "Riesenland"), (Peace, 1)), (("Murphy", "Natail"), (Peace, -3)), (("Harju", "Riesenland"), (Peace, -1)), (("Harju", "Natail"), (Peace, 2)), (("Riesenland", "Natail"), (Peace, 0)), (("Murphy", "Murphy"), (Peace, 10)), (("Harju", "Harju"), (Peace, 10)), (("Riesenland", "Riesenland"), (Peace, 10)), (("Natail", "Natail"), (Peace, 10))] randomAllegiance :: IO String randomAllegiance = chooseIO allegiances allegiances = ["Murphy", "Harju", "Riesenland", "Natail"] plalleg :: String plalleg = "" initialAttitudes :: AttitudeMap initialAttitudes = nullAttitudes allegiances
data Input = Answer Int | QuitCmd data Command : Type -> Type where PutStr : String -> Command () GetLine : Command String Pure : ty -> Command ty Bind : Command a -> (a -> Command b) -> Command b data ConsoleIO : Type -> Type where Quit : a -> ConsoleIO a Do : Command a -> (a -> Inf (ConsoleIO b)) -> ConsoleIO b runCommand : Command a -> IO a runCommand (PutStr x) = putStr x runCommand GetLine = getLine runCommand (Pure val) = pure val runCommand (Bind c f) = do res <- runCommand c runCommand (f res) namespace CommandDo (>>=) : Command a -> (a -> Command b) -> Command b (>>=) = Bind namespace ConsoleDo (>>=) : Command a -> (a -> Inf (ConsoleIO b)) -> ConsoleIO b (>>=) = Do readInput : (prompt : String) -> Command Input readInput prompt = do PutStr prompt answer <- GetLine if toLower answer == "quit" then Pure QuitCmd else Pure (Answer (cast answer)) mutual correct : Stream Int -> (score : Nat) -> (questions : Nat) -> ConsoleIO Nat correct nums score questions = do PutStr "Correct!\n" quiz nums (score + 1) (questions + 1) wrong : Stream Int -> Int -> (score : Nat) -> (questions : Nat) -> ConsoleIO Nat wrong nums ans score questions = do PutStr ("Wrong the answer is " ++ show ans ++ "\n") quiz nums score (questions + 1) quiz : Stream Int -> (score : Nat) -> (questions : Nat) -> ConsoleIO Nat quiz (num1 :: num2 :: nums) score questions = do PutStr ("Score so far: " ++ show score ++ "\n") input <- readInput (show num1 ++ " * " ++ show num2 ++ "? ") case input of Answer answer => if answer == num1 * num2 then correct nums score questions else wrong nums (num1 * num2) score questions QuitCmd => Quit score
import data.real.irrational import topology.basic import algebra.order.floor --OUTPUT 1 theorem irrational_orbit_dense {α : ℝ} (hα_irrat : irrational α) : closure ((λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ)) = set.Icc 0 1 := begin -- Let $\alpha$ be an irrational number. Then for distinct $i, j \in \mathbb{Z}$, we must have $\{i \alpha\} \neq\{j \alpha\}$. If this were not true, then have h1 : ∀ i j : ℤ, i ≠ j → int.fract (α * ↑i) ≠ int.fract (α * ↑j), from by auto [int.fract_eq_iff_of_irrational hα_irrat], -- Hence, $S:=\{\{i \alpha\} \mid i \in \mathbb{Z}\}$ is an infinite subset of $\left[0,1\right]$. have h2 : (λ (m : ℤ), int.fract (α * ↑m)) '' (@set.univ ℤ) ⊆ set.Icc 0 1, from by auto [int.fract_nonneg, int.fract_lt_one], -- By the Bolzano-Weierstrass theorem, $S$ has a limit point in $[0, 1]$. One can thus find pairs of elements of $S$ that are arbitrarily close. Since (the absolute value of) the difference of any two elements of $S$ is also an element of $S$, it follows that $0$ is a limit point of $S$. have h3 : ∃ (x : ℤ), x ∈ set.univ ∧ ∃ (y : ℤ), y ∈ set.univ ∧ int.fract (α * ↑x) ≠ int.fract (α * ↑y) ∧ int.fract (α * ↑x) - int.fract (α * ↑y) < 1, from by auto [h1, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set.finite_univ, set. end --Needs more than 2000 tokens! --OUTPUT 2 theorem irrational_orbit_dense {α : ℝ} (hα_irrat : irrational α) : closure ((λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ)) = set.Icc 0 1 := begin -- Let $\alpha$ be an irrational number. Then for distinct $i, j \in \mathbb{Z}$, we must have $\{i \alpha\} \neq\{j \alpha\}$. If this were not true, then have h1 : ∀ (i j : ℤ), i ≠ j → int.fract (α * ↑i) ≠ int.fract (α * ↑j), from by auto [int.fract_eq_iff, int.fract_mul, hα_irrat, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul, int.fract_eq_iff, int.fract_mul end --Needs more than 2000 tokens! --OUTPUT 3 theorem irrational_orbit_dense {α : ℝ} (hα_irrat : irrational α) : closure ((λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ)) = set.Icc 0 1 := begin -- Let $\alpha$ be an irrational number. Then for distinct $i, j \in \mathbb{Z}$, we must have $\{i \alpha\} \neq\{j \alpha\}$. have h1 : ∀ i j : ℤ, i ≠ j → int.fract (α * ↑i) ≠ int.fract (α * ↑j), from by auto [int.fract_eq_iff_eq_or_eq_neg_one, int.fract_neg_one_eq_neg_one, int.fract_eq_zero_iff, int.fract_eq_one_iff, int.fract_eq_neg_one_iff, int.fract_eq_one_iff_eq_neg_one, int.fract_eq_zero_iff_eq_one, int.fract_eq_zero_iff_eq_neg_one, int.fract_eq_one_iff_eq_zero, int.fract_eq_neg_one_iff_eq_zero, int.fract_eq_neg_one_iff_eq_one, int.fract_eq_one_iff_eq_one, int.fract_eq_neg_one_iff_eq_neg_one, int.fract_eq_zero_iff_eq_zero, int.fract_eq_zero_iff_eq_one, int.fract_eq_zero_iff_eq_neg_one, int.fract_eq_one_iff_eq_zero, int.fract_eq_neg_one_iff_eq_zero, int.fract_eq_one_iff_eq_one, int.fract_eq_neg_one_iff_eq_neg_one, int.fract_eq_zero_iff_eq_zero, int.fract_eq_zero_iff_eq_one, int.fract_eq_zero_iff_eq_neg_one, int.fract_eq_one_iff_eq_zero, int.fract_eq_neg_one_iff_eq_zero, int.fract_eq_one_iff_eq_one, int.fract_eq_neg_one_iff_eq_neg_one, int.fract_eq_zero_iff_eq_zero, int.fract_eq_zero_iff_eq_one, int.fract_eq_zero_iff_eq_neg_one, int.fract_eq_one_iff_eq_zero, int.fract_eq_neg_one_iff_eq_zero, int.fract_eq_one_iff_eq_one, int.fract_eq_neg_one_iff_eq_neg_one, int.fract_eq_zero_iff_eq_zero, int.fract_eq_zero_iff_eq_one, int.fract_eq_zero_iff_eq_neg_one, int.fract_eq_one_iff_eq_zero, int.fract_eq_neg_one_iff_eq_zero, int.fract_eq_one_iff_eq_one, int.fract_eq_neg_one_iff_eq_neg_one, int.fract_eq_zero_iff_eq_zero, int.fract_eq_zero_iff_eq_one, int.fract_eq_zero_iff_eq_neg_one, int.fract_eq_one_iff_eq_zero, int.fract_eq_neg_one_iff_eq_zero, int.fract_eq_one_iff_eq_one, int.fract_eq_neg_one_iff_eq_neg_one, int.fract_eq_zero_iff_eq_zero, int.fract_eq_zero_iff_eq_one, int.fract_eq_zero_iff_eq_neg_one, int.fract_eq_one_iff_eq_zero, int.fract_eq_neg_one_iff_eq_zero, int.fract_eq_one_iff_eq_one, int.fract_eq_neg_one_iff_eq_neg_one, int.fract_eq_zero_iff_eq_zero, int.fract_eq_zero_iff_eq_one, int.fract_eq_zero_iff_eq_neg_one, int.fract_eq_one_iff_eq_zero, int.fract_eq_neg_one_iff_eq_zero, int.fract_eq_one_iff_eq_one, int.fract_eq_neg_one_iff_eq_neg_one, int.fract_eq_zero_iff_eq_zero, int.fract_eq_zero_iff_eq_one, int.fract_eq_zero_iff_eq_neg_one, int.fract_eq_one_iff_eq_zero, int.fract_eq_neg_one_iff_eq_zero, int.fract_eq_one_iff_eq_one, int.fract_eq_neg_one_iff_eq_neg_one, int.fract_eq_zero_iff_eq_zero, int.fract_eq_zero_iff_eq_one, int.fract_eq_zero_iff_eq_neg_one, int.fract_eq_one_iff_eq_zero, int.fract_eq_neg_one_iff_eq_zero, int.fract_eq_one_iff_eq_one, int.fract_eq_neg_one_iff_eq_neg_one, int.fract_eq_zero_iff_eq_zero, int.fract_eq_zero_iff_eq_one, int.fract_eq_zero_iff_eq_neg_one, int.fract_eq_one_iff_eq_zero, int.fract_eq_neg_one_iff_eq_zero, int.fract_eq_one_iff_eq_one, int.fract_eq_neg_one_iff_eq_neg_one, int.fract_eq_zero_iff_eq_zero, int.fract_eq_zero_iff_eq_one, int.fract_eq_zero_iff_eq_neg_one, int.fract_eq_one_iff_eq_zero, int.fract_eq_neg_one_iff_eq_zero, int.fract_eq_one_iff_eq_one, int.fract_eq_neg_one_iff_eq_neg_one, int.fract_eq_zero_iff_eq_zero, int.fract_eq_zero_iff_eq_one, int.fract_eq_zero_iff_eq_neg_one, int.fract_eq_one_iff_eq_zero, int.fract_eq_neg_one_iff_eq_zero, int.fract_eq_one_iff_eq_one, int.fract_eq_neg_one_iff_eq_neg_one, int.fract_eq_zero_iff_eq_zero, int.fract_eq_zero_iff_eq_one, int.fract_eq_zero_iff_eq_neg_one, int.fract_eq_one_iff_eq_zero, int.fract_eq_neg_one_iff_eq_zero, int.fract_eq_one_iff_eq_one, int.fract_eq_neg_one_iff_eq_neg_one, int.fract_eq_zero_iff_eq_zero, int.fract_eq_zero_iff_eq_one, int.fract_eq_zero_iff_eq_neg_one, int.fract_eq_one_iff_eq_zero, int.fract_eq_neg_one_iff_eq_zero, int.fract_eq_one_iff_eq_one, int.fract_eq_neg_one_iff_eq_neg_one, int.fract_eq_zero_iff_eq_zero, int.fract_eq_zero_iff_eq_one, int.fract_eq_zero_iff_eq_neg_one, int.fract_eq_one_iff_eq_zero, int.fract_eq_neg_one_iff_eq_zero, int.fract_eq_one_iff_eq_one, int.fract_eq_neg_one_iff_eq_neg_one, int.fract end --Needs more than 2000 tokens! /- FEW SHOT PROMPTS TO CODEX(START) /--`theorem` Power Set is Closed under Intersection Let $S$ be a set. Let $\powerset S$ be the power set of $S$. Then: :$\forall A, B \in \powerset S: A \cap B \in \powerset S$ `proof` Let $A, B \in \powerset S$. Then by the definition of power set, $A \subseteq S$ and $B \subseteq S$. From Intersection is Subset we have that $A \cap B \subseteq A$. It follows from Subset Relation is Transitive that $A \cap B \subseteq S$. Thus $A \cap B \in \powerset S$ and closure is proved. {{qed}} -/ theorem power_set_intersection_closed {α : Type*} (S : set α) : ∀ A B ∈ 𝒫 S, (A ∩ B) ∈ 𝒫 S := begin -- $A$ and $B$ are sets. $A$ and $B$ belong to power set of $S$ assume (A : set α) (hA : A ∈ 𝒫 S) (B : set α) (hB : B ∈ 𝒫 S), -- Then $A ⊆ S$ and $B ⊆ S$, by power set definition have h1 : (A ⊆ S) ∧ (B ⊆ S), from by auto [set.subset_of_mem_powerset, set.subset_of_mem_powerset], -- Then $(A ∩ B) ⊆ A$, by intersection of set is a subset have h2 : (A ∩ B) ⊆ A, from by auto [set.inter_subset_left], -- Then $(A ∩ B) ⊆ S$, by subset relation is transitive have h3 : (A ∩ B) ⊆ S, from by auto [set.subset.trans], -- Hence $(A ∩ B) ∈ 𝒫 S$, by power set definition show (A ∩ B) ∈ 𝒫 S, from by auto [set.mem_powerset], end /--`theorem` Square of Sum :$\forall x, y \in \R: \paren {x + y}^2 = x^2 + 2 x y + y^2$ `proof` Follows from the distribution of multiplication over addition: {{begin-eqn}} {{eqn | l = \left({x + y}\right)^2 | r = \left({x + y}\right) \cdot \left({x + y}\right) }} {{eqn | r = x \cdot \left({x + y}\right) + y \cdot \left({x + y}\right) | c = Real Multiplication Distributes over Addition }} {{eqn | r = x \cdot x + x \cdot y + y \cdot x + y \cdot y | c = Real Multiplication Distributes over Addition }} {{eqn | r = x^2 + 2xy + y^2 | c = }} {{end-eqn}} {{qed}} -/ theorem square_of_sum (x y : ℝ) : (x + y)^2 = (x^2 + 2*x*y + y^2) := begin -- expand the power calc (x + y)^2 = (x+y)*(x+y) : by auto [sq] -- distributive property of multiplication over addition gives: ... = x*(x+y) + y*(x+y) : by auto [add_mul] -- applying the above property further gives: ... = x*x + x*y + y*x + y*y : by auto [mul_comm, add_mul] using [ring] -- rearranging the terms using commutativity and adding gives: ... = x^2 + 2*x*y + y^2 : by auto [sq, mul_comm] using [ring] end /--`theorem` Identity of Group is Unique Let $\struct {G, \circ}$ be a group. Then there is a unique identity element $e \in G$. `proof` From Group has Latin Square Property, there exists a unique $x \in G$ such that: :$a x = b$ and there exists a unique $y \in G$ such that: :$y a = b$ Setting $b = a$, this becomes: There exists a unique $x \in G$ such that: :$a x = a$ and there exists a unique $y \in G$ such that: :$y a = a$ These $x$ and $y$ are both $e$, by definition of identity element. {{qed}} -/ theorem group_identity_unique {G : Type*} [group G] : ∃! e : G, ∀ a : G, e * a = a ∧ a * e = a := begin -- Group has Latin Square Property have h1 : ∀ a b : G, ∃! x : G, a * x = b, from by auto using [use (a⁻¹ * b)], have h2 : ∀ a b : G, ∃! y : G, y * a = b, from by auto using [use b * a⁻¹], -- Setting $b = a$, this becomes: have h3 : ∀ a : G, ∃! x : G, a * x = a, from by auto [h1], have h4 : ∀ a : G, ∃! y : G, y * a = a, from by auto [h2], -- These $x$ and $y$ are both $(1 : G)$, by definition of identity element have h5 : ∀ a : G, classical.some (h3 a).exists = (1 : G), from by auto [exists_unique.unique, h3, classical.some_spec, exists_unique.exists, mul_one], have h6 : ∀ a : G, classical.some (h4 a).exists = (1 : G), from by auto [exists_unique.unique, h4, classical.some_spec, exists_unique.exists, one_mul], show ∃! e : G, ∀ a : G, e * a = a ∧ a * e = a, from by auto [h3, h4, exists_unique.unique, classical.some_spec, exists_unique.exists] using [use (1 : G)], end /--`theorem` Squeeze Theorem for Real Numbers Let $\sequence {x_n}$, $\sequence {y_n}$ and $\sequence {z_n}$ be sequences in $\R$. Let $\sequence {y_n}$ and $\sequence {z_n}$ both be convergent to the following limit: :$\ds \lim_{n \mathop \to \infty} y_n = l, \lim_{n \mathop \to \infty} z_n = l$ Suppose that: :$\forall n \in \N: y_n \le x_n \le z_n$ Then: :$x_n \to l$ as $n \to \infty$ that is: :$\ds \lim_{n \mathop \to \infty} x_n = l$ `proof` From Negative of Absolute Value: :$\size {x - l} < \epsilon \iff l - \epsilon < x < l + \epsilon$ Let $\epsilon > 0$. We need to prove that: :$\exists N: \forall n > N: \size {x_n - l} < \epsilon$ As $\ds \lim_{n \mathop \to \infty} y_n = l$ we know that: :$\exists N_1: \forall n > N_1: \size {y_n - l} < \epsilon$ As $\ds \lim_{n \mathop \to \infty} z_n = l$ we know that: :$\exists N_2: \forall n > N_2: \size {z_n - l} < \epsilon$ Let $N = \max \set {N_1, N_2}$. Then if $n > N$, it follows that $n > N_1$ and $n > N_2$. So: :$\forall n > N: l - \epsilon < y_n < l + \epsilon$ :$\forall n > N: l - \epsilon < z_n < l + \epsilon$ But: :$\forall n \in \N: y_n \le x_n \le z_n$ So: :$\forall n > N: l - \epsilon < y_n \le x_n \le z_n < l + \epsilon$ and so: :$\forall n > N: l - \epsilon < x_n < l + \epsilon$ So: :$\forall n > N: \size {x_n - l} < \epsilon$ Hence the result. {{qed}} -/ theorem squeeze_theorem_real_numbers (x y z : ℕ → ℝ) (l : ℝ) : let seq_limit : (ℕ → ℝ) → ℝ → Prop := λ (u : ℕ → ℝ) (l : ℝ), ∀ ε > 0, ∃ N, ∀ n > N, |u n - l| < ε in seq_limit y l → seq_limit z l → (∀ n : ℕ, (y n) ≤ (x n) ∧ (x n) ≤ (z n)) → seq_limit x l := begin assume seq_limit (h2 : seq_limit y l) (h3 : seq_limit z l) (h4 : ∀ (n : ℕ), y n ≤ x n ∧ x n ≤ z n) (ε), --From Negative of Absolute Value: $\size {x - l} < \epsilon \iff l - \epsilon < x < l + \epsilon$ have h5 : ∀ x, |x - l| < ε ↔ (((l - ε) < x) ∧ (x < (l + ε))), from by auto [abs_sub_lt_iff] using [linarith], --Let $\epsilon > 0$. assume (h7 : ε > 0), --As $\ds \lim_{n \mathop \to \infty} y_n = l$ we know that $\exists N_1: \forall n > N_1: \size {y_n - l} < \epsilon$ cases h2 ε h7 with N1 h8, --As $\ds \lim_{n \mathop \to \infty} z_n = l$ we know that $\exists N_2: \forall n > N_2: \size {z_n - l} < \epsilon$ cases h3 ε h7 with N2 h9, --Let $N = \max \set {N_1, N_2}$. let N := max N1 N2, use N, --Then if $n > N$, it follows that $n > N_1$ and $n > N_2$. have h10 : ∀ n > N, n > N1 ∧ n > N2 := by auto [lt_of_le_of_lt, le_max_left, le_max_right], --$\forall n > N: l - \epsilon < y_n < l + \epsilon$ --$\forall n > N: l - \epsilon < z_n < l + \epsilon$ --$\forall n \in \N: y_n \le x_n \le z_n$ --So $\forall n > N: l - \epsilon < y_n \le x_n \le z_n < l + \epsilon$ have h11 : ∀ n > N, (((l - ε) < (y n)) ∧ ((y n) ≤ (x n))) ∧ (((x n) ≤ (z n)) ∧ ((z n) < l+ε)), from by auto [h8, h10, h5, h9], --$\forall n > N: l - \epsilon < x_n < l + \epsilon$ have h15 : ∀ n > N, ((l - ε) < (x n)) ∧ ((x n) < (l+ε)), from by auto [h11] using [linarith], --So $\forall n > N: \size {x_n - l} < \epsilon$ --Hence the result show ∀ (n : ℕ), n > N → |x n - l| < ε, from by auto [h5, h15], end /--`theorem` Density of irrational orbit The fractional parts of the integer multiples of an irrational number form a dense subset of the unit interval `proof` Let $\alpha$ be an irrational number. Then for distinct $i, j \in \mathbb{Z}$, we must have $\{i \alpha\} \neq\{j \alpha\}$. If this were not true, then $$ i \alpha-\lfloor i \alpha\rfloor=\{i \alpha\}=\{j \alpha\}=j \alpha-\lfloor j \alpha\rfloor, $$ which yields the false statement $\alpha=\frac{\lfloor i \alpha\rfloor-\lfloor j \alpha\rfloor}{i-j} \in \mathbb{Q}$. Hence, $$ S:=\{\{i \alpha\} \mid i \in \mathbb{Z}\} $$ is an infinite subset of $\left[0,1\right]$. By the Bolzano-Weierstrass theorem, $S$ has a limit point in $[0, 1]$. One can thus find pairs of elements of $S$ that are arbitrarily close. Since (the absolute value of) the difference of any two elements of $S$ is also an element of $S$, it follows that $0$ is a limit point of $S$. To show that $S$ is dense in $[0, 1]$, consider $y \in[0,1]$, and $\epsilon>0$. Then by selecting $x \in S$ such that $\{x\}<\epsilon$ (which exists as $0$ is a limit point), and $N$ such that $N \cdot\{x\} \leq y<(N+1) \cdot\{x\}$, we get: $|y-\{N x\}|<\epsilon$. QED -/ theorem irrational_orbit_dense {α : ℝ} (hα_irrat : irrational α) : closure ((λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ)) = set.Icc 0 1 := FEW SHOT PROMPTS TO CODEX(END)-/
section \<open>Comprehensive Complex Theory\<close> theory Complex_MainRLT imports Complex MacLaurin begin local_setup \<open>RLTHM @{binding Cantors_paradox_rlt} @{thm Cantors_paradox}\<close> thm Cantors_paradox thm Cantors_paradox_rlt local_setup \<open>RLTHM @{binding binomial_ring_rlt} @{thm binomial_ring}\<close> thm binomial_ring thm binomial_ring_rlt local_setup \<open>RLTHM @{binding hull_redundant_rlt} @{thm hull_redundant}\<close> thm hull_redundant thm hull_redundant_rlt local_setup \<open>RLTHM @{binding Complex_in_Reals_rlt} @{thm Complex_in_Reals}\<close> thm Complex_in_Reals thm Complex_in_Reals_rlt local_setup \<open>RLTHM @{binding Maclaurin_lemma_rlt} @{thm Maclaurin_lemma}\<close> thm Maclaurin_lemma thm Maclaurin_lemma_rlt (* Relativization of the is_filter predicate *) lemma aux_is_filter: "is_filter = is_filter" .. local_setup \<open>RLTHM @{binding aux_is_filter_rlt} @{thm aux_is_filter}\<close> find_theorems is_filter_def_rlt lemma is_filter_rlt_simp[simp]: "neper R \<Longrightarrow> is_filter_rlt R F \<longleftrightarrow> (F (\<lambda>x. True) \<and> (\<forall>p pa. rel_fun R (=) p p \<and> rel_fun R (=) pa pa \<and> F p \<and> F pa \<longrightarrow> F (\<lambda>x. p x \<and> pa x)) \<and> (\<forall>p pa. rel_fun R (=) p p \<and> rel_fun R (=) pa pa \<and> (\<forall>xb. R xb xb \<and> p xb \<longrightarrow> pa xb) \<and> F p \<longrightarrow> F pa))" unfolding is_filter_rlt_def rlt_eq by simp meson (*********************) lemma neper_rel_filter: "neper R \<Longrightarrow> neper (rel_filter R)" apply (simp add: neper_def per_def) apply safe apply (metis rel_filter_conversep symp_conv_conversep_eq symp_def) apply (rule rel_filter_mono[THEN predicate2D]) apply (rule transp_relcompp_less_eq) apply (metis transpI) apply (rule rel_filter_distr[of R R, THEN predicate2_eqD, THEN iffD1]) apply (erule (1) relcomppI) using bot_filter_parametric by blast (* More palatable definition of rel_filter: *) lemma rel_filter_iff: "rel_filter R F G \<longleftrightarrow> (\<exists>H. Rep_filter H (\<lambda>(x, y). R x y) \<and> (F = Abs_filter (\<lambda>p. Rep_filter H (\<lambda>(x,y). p x \<and> R x y))) \<and> (G = Abs_filter (\<lambda>q. Rep_filter H (\<lambda>(x,y). q y \<and> R x y))))" proof- have aux: "\<And>P. ((\<lambda>x. P (fst x) \<and> x \<in> {(x, y). R x y})) = (\<lambda>(x,y). P x \<and> R x y)" "\<And>P. ((\<lambda>x. P (snd x) \<and> x \<in> {(x, y). R x y})) = (\<lambda>(x,y). P y \<and> R x y)" by auto show ?thesis unfolding rel_filter.simps map_filter_on_def eventually_def unfolding aux by blast qed lemma is_filter_conjL: assumes H: "is_filter H" and HR: "H (\<lambda>(x, y). R x y)" shows "is_filter (\<lambda>p. H (\<lambda>(x,y). p x \<and> R x y))" unfolding is_filter_def apply safe subgoal using assms unfolding is_filter_def by auto subgoal premises prems for P Q using H[unfolded is_filter_def, THEN conjunct2, THEN conjunct1, rule_format, of "\<lambda>(x, y). P x \<and> R x y" "\<lambda>(x, y). Q x \<and> R x y"] apply (rule is_filter.mono[OF H, rotated]) apply (rule prems) apply (rule prems) apply auto done subgoal for P Q apply (rule is_filter.mono[OF H, rotated]) apply auto done . lemma is_filter_conjR: assumes H: "is_filter H" and HR: "H (\<lambda>(x, y). R x y)" shows "is_filter (\<lambda>q. H (\<lambda>(x,y). q y \<and> R x y))" unfolding is_filter_def apply safe subgoal using assms unfolding is_filter_def by auto subgoal premises prems for P Q using H[unfolded is_filter_def, THEN conjunct2, THEN conjunct1, rule_format, of "\<lambda>(x, y). P y \<and> R x y" "\<lambda>(x, y). Q y \<and> R x y"] apply (rule is_filter.mono[OF H, rotated]) apply (rule prems) apply (rule prems) apply auto done subgoal for P Q apply (rule is_filter.mono[OF H, rotated]) apply auto done . lemma Rep_filter_Abs_filter_conjL: assumes HR: "Rep_filter Z (\<lambda>(x, y). R x y)" shows "Rep_filter (Abs_filter (\<lambda>p. Rep_filter Z (\<lambda>(x,y). p x \<and> R x y))) = (\<lambda>p. Rep_filter Z (\<lambda>(x,y). p x \<and> R x y))" using Abs_filter_inverse' assms is_filter_Rep_filter is_filter_conjL by blast lemma Rep_filter_Abs_filter_conjR: assumes HR: "Rep_filter Z (\<lambda>(x, y). R x y)" shows "Rep_filter (Abs_filter (\<lambda>q. Rep_filter Z (\<lambda>(x,y). q y \<and> R x y))) = (\<lambda>q. Rep_filter Z (\<lambda>(x,y). q y \<and> R x y))" using Abs_filter_inverse' assms is_filter_Rep_filter is_filter_conjR by blast lemma rel_filter_def2: "rel_filter R F G \<longleftrightarrow> (\<exists>H. Rep_filter H (\<lambda>(x, y). R x y) \<and> Rep_filter F = (\<lambda>p. Rep_filter H (\<lambda>(x, y). p x \<and> R x y)) \<and> Rep_filter G = (\<lambda>q. Rep_filter H (\<lambda>(x, y). q y \<and> R x y)))" unfolding rel_filter_iff apply safe subgoal for H apply(rule exI[of _ H]) apply safe using Rep_filter_Abs_filter_conjL Rep_filter_Abs_filter_conjR by blast+ subgoal for H apply(rule exI[of _ H]) apply safe by (metis Rep_filter_inverse)+ . (* *) (* Counterpart of rel_filter on the raw type: *) definition rrel_filter :: "('a \<Rightarrow> 'b \<Rightarrow> bool) \<Rightarrow> (('a \<Rightarrow> bool) \<Rightarrow> bool) \<Rightarrow> (('b \<Rightarrow> bool) \<Rightarrow> bool) \<Rightarrow> bool" where "rrel_filter R F G \<equiv> (\<exists>H. is_filter H \<and> H (\<lambda>(x, y). R x y) \<and> F = (\<lambda>p. H (\<lambda>(x, y). p x \<and> R x y)) \<and> G = (\<lambda>q. H (\<lambda>(x, y). q y \<and> R x y)))" lemma rel_filter_rrel_filter: "rel_filter R = inv_imagep (rrel_filter R) Rep_filter" unfolding rrel_filter_def rel_filter_def2 inv_imagep_def fun_eq_iff apply safe subgoal for _ _ H apply(rule exI[of _ "Rep_filter H"]) using is_filter_Rep_filter by blast subgoal for _ _ H apply(rule exI[of _ "Abs_filter H"]) by (simp add: eventually_Abs_filter) . (* The above alternative definition makes the neper properties trivial: *) lemmas filter.Rep_filter_inject[simp] lemmas is_filter_Rep_filter[simp] lemma inj_Rep_filter[simp,intro]: "inj Rep_filter" unfolding inj_on_def by auto lemma neper_inv_imagep2: "neper (inv_imagep R f) \<Longrightarrow> inj f \<Longrightarrow> Collect t = range f \<Longrightarrow> neper (restr R t)" unfolding inv_imagep_def neper_def per_def inj_on_def restr_def set_eq_iff mem_Collect_eq image_iff apply safe subgoal by metis subgoal by (metis (full_types)) subgoal by blast . lemma neper_restr_rrel_filter_is_filter: "neper R \<Longrightarrow> neper (restr (rrel_filter R) is_filter)" apply(frule neper_rel_filter) unfolding rel_filter_rrel_filter apply(rule neper_inv_imagep2[where f = Rep_filter]) by auto (metis Abs_filter_inverse' range_eqI) (* More elementary characterisation of rrel_filter *) lemma rrel_filter_def2: assumes iF: "is_filter F" and iG: "is_filter G" shows "rrel_filter R F G \<longleftrightarrow> (\<forall>p q p'. F p \<and> G q \<and> (\<forall>x y. p x \<and> R x y \<and> q y \<longrightarrow> p' x) \<longrightarrow> F p') \<and> (\<forall>p q q'. F p \<and> G q \<and> (\<forall>x y. p x \<and> R x y \<and> q y \<longrightarrow> q' y) \<longrightarrow> G q')" proof safe fix p q p' q' assume "rrel_filter R F G" and Fp: "F p" and Gq: "G q" then obtain H where H: "is_filter H" "H (\<lambda>(x, y). R x y)" and FH: "F = (\<lambda>p. H (\<lambda>(x, y). p x \<and> R x y))" and GH: "G = (\<lambda>q. H (\<lambda>(x, y). q y \<and> R x y))" unfolding rrel_filter_def by auto have 1: "H (\<lambda>(x, y). p x \<and> R x y)" "H (\<lambda>(x, y). q y \<and> R x y)" using Fp FH Gq GH by auto {assume 0: "\<forall>x y. p x \<and> R x y \<and> q y \<longrightarrow> p' x" have "H (\<lambda>(x, y). p x \<and> R x y \<and> q y)" using is_filter.conj[OF H(1), of "\<lambda>(x, y). p x \<and> R x y", OF 1] by (auto elim!: is_filter.mono[OF H(1), rotated]) hence "H (\<lambda>(x, y). p' x \<and> R x y)" using 0 by (auto elim!: is_filter.mono[OF H(1), rotated]) with FH show "F p'" unfolding fun_eq_iff by auto } {assume 0: "\<forall>x y. p x \<and> R x y \<and> q y \<longrightarrow> q' y" have "H (\<lambda>(x, y). p x \<and> R x y \<and> q y)" using is_filter.conj[OF H(1), of "\<lambda>(x, y). p x \<and> R x y", OF 1] by (auto elim!: is_filter.mono[OF H(1), rotated]) hence "H (\<lambda>(x, y). q' y \<and> R x y)" using is_filter.mono[OF H(1)] using 0 by (auto elim!: is_filter.mono[OF H(1), rotated]) with GH show "G q'" unfolding fun_eq_iff by auto } next assume F: "\<forall>p q p'. F p \<and> G q \<and> (\<forall>x y. p x \<and> R x y \<and> q y \<longrightarrow> p' x) \<longrightarrow> F p'" and G: "\<forall>p q q'. F p \<and> G q \<and> (\<forall>x y. p x \<and> R x y \<and> q y \<longrightarrow> q' y) \<longrightarrow> G q'" (* This is the filter generated by the desired projections: *) define H where "H \<equiv> \<lambda>pq. \<exists>p q. F p \<and> G q \<and> (\<forall>x y. p x \<and> R x y \<and> q y \<longrightarrow> pq (x,y))" show "rrel_filter R F G" unfolding rrel_filter_def proof(rule exI[of _ H], safe) show "is_filter H" unfolding is_filter_def proof safe show "H (\<lambda>x. True)" using iF iG unfolding H_def apply(intro exI[of _ "\<lambda>_.True"]) by (auto intro: is_filter.True) next fix P Q assume "H P" "H Q" thus "H (\<lambda>x. P x \<and> Q x)" unfolding H_def apply safe subgoal for p pa q qa apply(rule exI[of _ "\<lambda>x. p x \<and> pa x"]) apply(rule exI[of _ "\<lambda>y. q y \<and> qa y"]) using iF iG by (auto intro: is_filter.conj) . next fix pq pq' assume "\<forall>x. pq x \<longrightarrow> pq' x" and "H pq" thus "H pq'" unfolding H_def apply safe subgoal for p q apply(rule exI[of _ p]) apply(rule exI[of _ q]) by auto . qed next show "H (\<lambda>(x, y). R x y)" unfolding H_def apply(intro exI[of _ "\<lambda>_.True"]) using iF iG by (auto intro: is_filter.True) next show "F = (\<lambda>p. H (\<lambda>(x, y). p x \<and> R x y))" unfolding fun_eq_iff apply safe subgoal for p unfolding H_def apply(rule exI[of _ p]) apply(rule exI[of _ "\<lambda>_.True"]) using iG by (auto intro: is_filter.True) subgoal for p unfolding H_def apply safe using F by auto . next show "G = (\<lambda>q. H (\<lambda>(x, y). q y \<and> R x y))" unfolding fun_eq_iff apply safe subgoal for q unfolding H_def apply(rule exI[of _ "\<lambda>_.True"]) apply(rule exI[of _ q]) using iF by (auto intro: is_filter.True) subgoal for q unfolding H_def apply safe using G by auto . qed qed (* *) definition ff where "ff R F \<equiv> \<lambda>p. F (\<lambda>x. \<forall>x'. R x x' \<longrightarrow> p x')" lemma rel_fun_ff: "neper R \<Longrightarrow> rrel_filter R F G \<Longrightarrow> rel_fun (rel_fun R (=)) (=) (ff R F) (ff R G)" unfolding inv_imagep_def unfolding rrel_filter_def ff_def apply safe subgoal premises prems for H unfolding rel_fun_def fun_eq_iff using prems(1) apply (auto elim!: is_filter.mono[rotated 2, of H] simp: prems(2)) apply (metis neper_sym) . done lemma is_filter_ff: "neper R \<Longrightarrow> is_filter F \<Longrightarrow> is_filter (ff R F)" unfolding is_filter_def[of "ff R F"] unfolding ff_def by (auto intro: is_filter.True simp: eventually_Abs_filter[of F, symmetric] elim: eventually_elim2 eventually_mono) lemma is_filter_rlt_ff: "neper R \<Longrightarrow> is_filter F \<Longrightarrow> is_filter_rlt R (ff R F)" unfolding is_filter_def[of "ff R F"] unfolding ff_def apply (auto intro: is_filter.True simp: eventually_Abs_filter[of F, symmetric] elim: eventually_elim2) apply (erule eventually_mono) by (metis neper_sym neper_trans) lemma rrel_filter_upwards: assumes R: "neper R" and F: "is_filter F" and FF: "rrel_filter R F F" and Fp: "F p" and 0: "\<forall>x. R x x \<and> p x \<longrightarrow> p' x" shows "F p'" apply(rule FF[unfolded rrel_filter_def2[OF F F], THEN conjunct1, rule_format, folded atomize_conjL, OF Fp Fp]) using 0 R by (metis neper_per per_def) lemma ff_rrel_filter: assumes R: "neper R" and F: "is_filter F" and G: "is_filter G" and rFF: "rrel_filter R F F" and rGG: "rrel_filter R G G" and FG: "rel_fun (rel_fun R (=)) (=) (ff R F) (ff R G)" shows "rrel_filter R F G" unfolding rrel_filter_def2[OF F G] proof safe fix p q p' assume Fp: "F p" and Gq: "G q" and 0: "\<forall>x y. p x \<and> R x y \<and> q y \<longrightarrow> p' x" have FF: "rel_fun (rel_fun R (=)) (=) (ff R F) (ff R F)" using FG R rFF rel_fun_ff by blast have "G (\<lambda>x. \<exists>y. R x y \<and> q y)" apply(rule rGG[unfolded rrel_filter_def2[OF G G], THEN conjunct1, rule_format, folded atomize_conjL, OF Gq Gq]) by auto hence 1: "G (\<lambda>x. \<forall>x'. R x x' \<longrightarrow> (\<exists>y. R x' y \<and> q y))" by (rule is_filter.mono[OF G, rotated]) (metis R neper_sym_eq neper_trans) have "F (\<lambda>x. \<forall>x'. R x x' \<longrightarrow> (\<exists>y. R x' y \<and> q y))" using FG[unfolded rel_fun_def[of "rel_fun R (=)"] ff_def, rule_format, of "\<lambda>x. \<exists>y. R x y \<and> q y" "\<lambda>x. \<exists>y. R x y \<and> q y"] using 1 unfolding rel_fun_def by (metis R neper_def per_def) hence 2: "F (\<lambda>x. \<exists>y. R x y \<and> q y)" using F R rFF rrel_filter_upwards by fastforce show "F p'" using 2 Fp unfolding eventually_Abs_filter[OF F, symmetric, of p] eventually_Abs_filter[OF F, symmetric, of p'] eventually_Abs_filter[OF F, symmetric, of "\<lambda>x. \<exists>y. R x y \<and> q y"] by (rule eventually_elim2) (blast intro: 0[rule_format]) next fix p q q' assume Fp: "F p" and Gq: "G q" and 0: "\<forall>x y. p x \<and> R x y \<and> q y \<longrightarrow> q' y" have GG: "rel_fun (rel_fun R (=)) (=) (ff R G) (ff R G)" by (simp add: R rGG rel_fun_ff) have "F (\<lambda>y. \<exists>x. p x \<and> R x y)" apply(rule rFF[unfolded rrel_filter_def2[OF F F], THEN conjunct1, rule_format, folded atomize_conjL, OF Fp Fp]) by (meson R neper_per per_def) hence 1: "F (\<lambda>y. \<forall>y'. R y y' \<longrightarrow> (\<exists>x. p x \<and> R x y'))" by (rule is_filter.mono[OF F, rotated]) (meson R neper_trans) have "G (\<lambda>y. \<forall>y'. R y y' \<longrightarrow> (\<exists>x. p x \<and> R x y'))" using FG[unfolded rel_fun_def[of "rel_fun R (=)"] ff_def, rule_format, of "\<lambda>y. \<exists>x. p x \<and> R x y" "\<lambda>y. \<exists>x. p x \<and> R x y"] using 1 unfolding rel_fun_def by (metis R neper_def per_def) hence 2: "G (\<lambda>y. \<exists>x. p x \<and> R x y)" using G R rGG rrel_filter_upwards by fastforce show "G q'" using 2 Gq unfolding eventually_Abs_filter[OF G, symmetric, of q] eventually_Abs_filter[OF G, symmetric, of q'] eventually_Abs_filter[OF G, symmetric, of "\<lambda>y. \<exists>x. p x \<and> R x y"] by (rule eventually_elim2) (blast intro: 0[rule_format]) qed (* *) definition Rep_filter' where "Rep_filter' R F \<equiv> (\<lambda>p. Rep_filter F (\<lambda>x. \<forall>y. R x y \<longrightarrow> p y))" lemma ex_ff_rrel_filter_rel_fun: assumes R: "neper R" and rFF: "is_filter_rlt R FF" and FF: "rel_fun (rel_fun R (=)) (=) FF FF" shows "\<exists> F. is_filter F \<and> rrel_filter R F F \<and> rel_fun (rel_fun R (=)) (=) FF (ff R F)" proof- have FF1: "FF (\<lambda>x. True)" and FF2: "\<And>p pa. rel_fun R (=) p p \<Longrightarrow> rel_fun R (=) pa pa \<Longrightarrow> FF p \<Longrightarrow> FF pa \<Longrightarrow> FF (\<lambda>x. p x \<and> pa x)" and FF3: "\<And>p pa. rel_fun R (=) p p \<Longrightarrow> rel_fun R (=) pa pa \<Longrightarrow> (\<forall>xb. R xb xb \<and> p xb \<longrightarrow> pa xb) \<Longrightarrow> FF p \<Longrightarrow> FF pa" using rFF[unfolded is_filter_rlt_simp[OF R]] by auto define F where "F \<equiv> \<lambda>p. FF (\<lambda>x. \<forall>y. R x y \<longrightarrow> p y)" show ?thesis proof(rule exI[of _ F], safe) show iF: "is_filter F" unfolding is_filter_def proof safe show "F (\<lambda>x. True)" unfolding F_def using FF1 by auto next fix P Q assume 1: "F P" "F Q" have 2: "FF (\<lambda>x. (\<forall>y. R x y \<longrightarrow> P y) \<and> (\<forall>y. R x y \<longrightarrow> Q y))" apply(rule FF2) using 1 unfolding rel_fun_def F_def by (meson R neper_per per_def)+ show "F (\<lambda>x. P x \<and> Q x)" unfolding F_def apply(rule FF3[OF _ _ _ 2]) unfolding rel_fun_def by (meson R neper_per per_def)+ next fix P Q assume 1: "\<forall>x. P x \<longrightarrow> Q x" and FP: "F P" show "F Q" unfolding F_def apply(rule FF3[OF _ _ _ FP[unfolded F_def]]) using 1 unfolding rel_fun_def by (metis R neper_per per_def)+ qed (* *) show "rrel_filter R F F" unfolding rrel_filter_def2[OF iF iF] proof safe fix p q p' assume Fp: "F p" and Fq: "F q" and 0: "\<forall>x y. p x \<and> R x y \<and> q y \<longrightarrow> p' x" have 1: "FF (\<lambda>x. (\<forall>y. R x y \<longrightarrow> p y) \<and> (\<forall>y. R x y \<longrightarrow> q y))" apply(rule FF2) using Fp Fq unfolding rel_fun_def F_def by (meson R neper_per per_def)+ show "F p'" unfolding F_def apply(rule FF3[OF _ _ _ 1]) using 0 unfolding rel_fun_def by (meson R neper_per per_def)+ next fix p q q' assume Fp: "F p" and Fq: "F q" and 0: "\<forall>x y. p x \<and> R x y \<and> q y \<longrightarrow> q' y" have 1: "FF (\<lambda>x. (\<forall>y. R x y \<longrightarrow> p y) \<and> (\<forall>y. R x y \<longrightarrow> q y))" apply(rule FF2) using Fp Fq unfolding rel_fun_def F_def by (meson R neper_per per_def)+ show "F q'" unfolding F_def apply(rule FF3[OF _ _ _ 1]) using 0 unfolding rel_fun_def by (meson R neper_per per_def)+ qed (* *) show "rel_fun (rel_fun R (=)) (=) FF (ff R F)" unfolding rel_fun_def[of "rel_fun R (=)"] proof clarify fix p q :: "'a \<Rightarrow> bool" assume pq: "rel_fun R (=) p q" show "FF p = ff R F q" unfolding ff_def F_def apply(rule FF[unfolded rel_fun_def[of "rel_fun R (=)"], rule_format]) using pq unfolding rel_fun_def by (metis R neper_per per_def) qed qed qed lemma bij_upto_ff: "neper R \<Longrightarrow> bij_upto (restr (rrel_filter R) is_filter) (restr (rel_fun (rel_fun R (=)) (=)) (is_filter_rlt R)) (ff R)" apply(intro bij_uptoI) subgoal apply(rule neper_restr) subgoal by auto subgoal apply(rule exI[of _ "\<lambda>_. True"]) by auto . subgoal for F F' unfolding restr_def using is_filter_rlt_ff rel_fun_ff by blast subgoal for F F' unfolding restr_def using ff_rrel_filter by blast subgoal unfolding restr_def using ex_ff_rrel_filter_rel_fun is_filter_rlt_ff by blast . lemma bij_upto_ff_Rep_filter: "neper R \<Longrightarrow> bij_upto (rel_filter R) (restr (rel_fun (rel_fun R (=)) (=)) (is_filter_rlt R)) (ff R o Rep_filter)" apply(rule bij_upto_transportFromRaw[OF filter.type_definition_filter rel_filter_rrel_filter]) using bij_upto_ff . lemma ff_eq[simp]: "ff (=) = id" unfolding ff_def by auto wide_typedef filter rel: rel_filter rep: "\<lambda>R. ff R o Rep_filter" subgoal using neper_rel_filter . subgoal using rel_filter_eq . subgoal using bij_upto_ff_Rep_filter . subgoal using ff_eq by simp . (* *) local_setup \<open>RLTHM @{binding Maclaurin_lemma2_rlt} @{thm Maclaurin_lemma2}\<close> thm Maclaurin_lemma2 thm Maclaurin_lemma2_rlt thm Maclaurin_lemma2_rlt[simplified rlt_eq rrel_eq, OF refl refl refl refl refl] local_setup \<open>RLTHM @{binding Taylor_rlt} @{thm Taylor}\<close> thm Taylor thm Taylor_rlt thm Taylor_rlt[simplified rlt_eq rrel_eq, OF refl refl refl refl refl refl refl] (*****************) (* Default relativization applied to the type "filter" (I keep it here just for documentation: *) definition fff :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> (('a \<Rightarrow> bool) \<Rightarrow> bool) \<Rightarrow> ('a \<Rightarrow> bool) \<Rightarrow> bool" where "fff R F \<equiv> (\<lambda>p. F (\<lambda>x. \<forall>y. R x y \<longrightarrow> p y))" lemma fff_eq[simp]: "fff (=) = id" unfolding fff_def by auto lemma is_filter_rlt_fff: assumes R: "neper R" and F: "is_filter F" shows "is_filter_rlt R (fff R F)" proof- define FF where "FF = Abs_filter F" have 0: "F = Rep_filter FF" by (simp add: Abs_filter_inverse' F FF_def) show ?thesis unfolding fff_def 0 unfolding is_filter_rlt_simp[OF R] apply auto unfolding eventually_def using R apply (auto elim: eventually_elim2) [] apply (unfold 0[symmetric]) apply (erule is_filter.mono[OF F, rotated]) by (metis R neper_sym_eq neper_trans) qed lemma rel_fun_fff: assumes R: "neper R" and F: "is_filter F" shows "rel_fun (rel_fun R (=)) (=) (fff R F) (fff R F)" unfolding fff_def rel_fun_def by (auto elim!: is_filter.mono[OF F, rotated]) (metis R neper_sym_eq neper_trans)+ lemma fff_surj_upto: assumes R: "neper R" and FF: "is_filter_rlt R FF" "rel_fun (rel_fun R (=)) (=) FF FF" shows "\<exists>F. is_filter F \<and> rel_fun (rel_fun R (=)) (=) FF (fff R F)" proof- define F where "F \<equiv> (\<lambda>p. \<exists>p'\<le>p. rel_fun R (=) p' p' \<and> FF p')" show ?thesis proof(rule exI[of _ F], safe) show "is_filter F" unfolding is_filter_def proof safe show "F (\<lambda>x. True)" unfolding F_def using R assms(2) by auto next fix P Q assume "F P" "F Q" then obtain P' Q' where P': "P'\<le>P \<and> rel_fun R (=) P' P' \<and> FF P'" and Q': "Q'\<le>Q \<and> rel_fun R (=) Q' Q' \<and> FF Q'" unfolding F_def by auto hence "FF (\<lambda>x. P' x \<and> Q' x)" using R assms(2) by auto moreover have "rel_fun R (=) (\<lambda>x. P' x \<and> Q' x) (\<lambda>x. P' x \<and> Q' x)" using P' Q' unfolding rel_fun_def by auto moreover have "(\<lambda>x. P' x \<and> Q' x) \<le> (\<lambda>x. P x \<and> Q x)" using P' Q' by auto ultimately show "F (\<lambda>x. P x \<and> Q x)" unfolding F_def by blast next fix P Q assume 0: "\<forall>x. P x \<longrightarrow> Q x" and FP: "F P" then obtain P' where P': "P'\<le>P \<and> rel_fun R (=) P' P' \<and> FF P'" unfolding F_def by auto thus "F Q" using 0 unfolding F_def by auto qed next show "rel_fun (rel_fun R (=)) (=) FF (fff R F)" unfolding rel_fun_def[of "rel_fun R (=)"] proof clarify fix P Q :: "'a \<Rightarrow> bool" assume PQ: "rel_fun R (=) P Q" hence PP: "rel_fun R (=) P P" and QQ: "rel_fun R (=) Q Q" by (metis R neper_eq neper_rel_fun neper_sym_eq neper_trans)+ show "FF P = fff R F Q" unfolding fff_def F_def apply safe subgoal apply(rule exI[of _ "\<lambda>x. \<forall>y. R x y \<longrightarrow> Q y"], safe) subgoal using QQ unfolding rel_fun_def by (metis R mem_Collect_eq neper_classes_eq) subgoal using is_filter_rlt_simp[OF R, THEN iffD1, OF assms(2), THEN conjunct2, THEN conjunct2, rule_format, of P "(\<lambda>p'. \<forall>y. R p' y \<longrightarrow> Q y)"] PP PQ \<open>FF P \<Longrightarrow> rel_fun R (=) (\<lambda>p'. \<forall>y. R p' y \<longrightarrow> Q y) (\<lambda>p'. \<forall>y. R p' y \<longrightarrow> Q y)\<close> rel_funD[of "R" "(=)"] by blast . subgoal for P' using is_filter_rlt_simp[OF R, THEN iffD1, OF assms(2), THEN conjunct2, THEN conjunct2, rule_format, of P' P] PP PQ rel_funD2 by fastforce . qed qed qed context fixes R :: "'a\<Rightarrow>'a\<Rightarrow>bool" begin definition "rrrel_filter \<equiv> inv_imagep (restr (inv_imagep (restr (rel_fun (rel_fun R (=)) (=)) (is_filter_rlt R)) (fff R)) is_filter) Rep_filter" definition "ggg \<equiv> fff R \<circ> Rep_filter" lemmas bij_uptoC = bij_upto_criterion[OF type_definition_filter, of "rel_fun (rel_fun R (=)) (=)" "is_filter_rlt R" "fff R", unfolded rrel_filter_def[symmetric] ggg_def[symmetric]] lemmas neperC = neper_criterion[OF type_definition_filter, of "rel_fun (rel_fun R (=)) (=)" "is_filter_rlt R" "fff R", unfolded rrel_filter_def[symmetric] ggg_def[symmetric]] end lemmas eqC = eq_criterion[OF type_definition_filter, of "is_filter", unfolded rrel_filter_def[symmetric, of "(=)", simplified] ] (* The below fail now because the type is already registered as wide, but would work if one comments away the previous wide_typedef *) (* wide_typedef filter rel: rrrel_filter rep: ggg unfolding rrrel_filter_def rrel_eq rlt_eq fff_eq subgoal for R apply(rule neperC) apply force using is_filter_Rep_filter apply blast using is_filter_rlt_fff rel_fun_fff by blast subgoal apply(rule eqC) by auto subgoal for R apply(rule bij_uptoC) apply force using is_filter_rlt_fff rel_fun_fff apply blast using fff_surj_upto by blast subgoal unfolding ggg_def by auto . *) (* The type of bijections: *) (* Prefer this to the bij abbreviation: *) definition "biject (f::'a\<Rightarrow>'a) \<equiv> (\<forall>a a'. f a = f a' \<longrightarrow> a = a') \<and> (\<forall>b. \<exists>a. f a = b)" local_setup \<open> RLCST @{term biject} \<close> lemma biject_rlt_simp[simp]: "neper R \<Longrightarrow> biject_rlt R f \<longleftrightarrow> (\<forall>x xa. R x x \<and> R xa xa \<and> R (f x) (f xa) \<longrightarrow> R x xa) \<and> (\<forall>x. R x x \<longrightarrow> (\<exists>xa. R xa xa \<and> R (f xa) x))" unfolding biject_rlt_def by auto lemma biject_rlt_eq[simp]: "biject_rlt (=) = biject" unfolding biject_rlt_def biject_def by auto typedef 'a biject = "{f::'a\<Rightarrow>'a. biject f}" unfolding biject_def by auto definition makeCompat :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> ('a \<Rightarrow> 'a) \<Rightarrow> ('a \<Rightarrow> 'a)" where "makeCompat R f \<equiv> if biject_rlt R (\<lambda>a. f (getRepr R a)) then (\<lambda>a. f (getRepr R a)) else id" lemma biject_rlt_id: "neper R \<Longrightarrow> biject_rlt R id" by auto lemma makeCompat_biject_biject_rlt: assumes R: "neper R" and f: "biject f" shows "biject_rlt R (makeCompat R f)" apply(cases "biject_rlt R (\<lambda>a. f (getRepr R a))") apply (simp add: makeCompat_def) by (metis R biject_rlt_id makeCompat_def) definition makeCompat1 :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> 'a biject \<Rightarrow> ('a \<Rightarrow> 'a)" where "makeCompat1 R f \<equiv> makeCompat R (Rep_biject f)" lemma makeCompat1_biject_biject_rlt: assumes R: "neper R" shows "biject_rlt R (makeCompat1 R f)" by (metis assms biject_rlt_id makeCompat1_def makeCompat_def) term "inv_imagep (rel_fun R R) (makeCompat1 R)" lemma Abs_biject_inverse_id[simp]: "Rep_biject (Abs_biject id) = id" by (simp add: Abs_biject_inverse biject_def) lemma biject_rlt_getRepr: "neper R \<Longrightarrow> biject_rlt R (getRepr R)" by simp (metis getRepr_neper neper_def per_def) lemma rel_fun_getRepr: "neper R \<Longrightarrow> rel_fun R R (getRepr R) (getRepr R)" unfolding rel_fun_def by (metis geterRepr_related neper_sym neper_trans) lemma makeCompat_eq[simp]: "makeCompat (=) f = (if biject f then f else id)" unfolding makeCompat_def by simp lemma makeCompat1_eq[simp]: "makeCompat1 (=) = Rep_biject" unfolding makeCompat1_def using Rep_biject by force lemma rel_fun_makeCompat1_id: "neper R \<Longrightarrow> rel_fun R R (makeCompat1 R (Abs_biject id)) (makeCompat1 R (Abs_biject id))" unfolding makeCompat1_def by (auto simp: biject_rlt_getRepr makeCompat_def rel_fun_getRepr) lemma rel_fun_makeCompat: "neper R \<Longrightarrow> rel_fun R R f f \<Longrightarrow> rel_fun R R (makeCompat R f) (makeCompat R f)" unfolding makeCompat_def using rel_fun_getRepr[of R] by (auto simp only: rel_fun_def simp_thms id_apply split: if_splits) context includes cardinal_syntax begin lemma card_eq_minus: assumes "{a,a'} \<subseteq> A" shows "|A - {a}| =o |A - {a'}|" using assms by (intro card_of_ordIsoI[where f="if a = a' then id else (\<lambda>x. if x = a' then a else if x = a then a' else x)"]) (auto simp: bij_betw_def inj_on_def) lemma bij_betw_combine3: "bij_betw f A1 B1 \<Longrightarrow> bij_betw f A2 B2 \<Longrightarrow> bij_betw f A3 B3 \<Longrightarrow> B1 \<inter> B2 = {} \<Longrightarrow> B1 \<inter> B3 = {} \<Longrightarrow> B2 \<inter> B3 = {} \<Longrightarrow> bij_betw f (A1 \<union> A2 \<union> A3) (B1 \<union> B2 \<union> B3)" by (simp add: bij_betw_combine inf_sup_distrib2) lemma biject_rlt_ex_getRepr: assumes R: "neper R" and f: "biject_rlt R f" "rel_fun R R f f" shows "\<exists>g. biject g \<and> (\<forall>a. R a a \<longrightarrow> g (getRepr R a) = f (getRepr R a)) \<and> biject_rlt R (\<lambda>a. g (getRepr R a))" proof- define A where A: "A \<equiv> {a. R a a \<and> a = getRepr R a}" have "inj_on f A" unfolding inj_on_def A proof safe fix a b assume a: "R a a" "a = getRepr R a" and b: "R b b" "b = getRepr R b" and fab: "f a = f b" have "R (f a) (f b)" unfolding fab using R f by (simp add: b(1) rel_funD2) hence "R a b" using R a(1) b(1) biject_rlt_simp f(1) by blast show "a = b" by (metis R \<open>R a b\<close> a(2) b(2) neper_getRepr_eq) qed have "|A| =o |f ` A|" by (metis \<open>inj_on f A\<close> card_of_image ordIso_iff_ordLeq the_inv_into_onto) define K11 where K11: "K11 \<equiv> \<lambda>a. {a'. R a a'} - {a}" define K1 where K1: "K1 \<equiv> (\<Union> {K11 a | a. a \<in> A})" have 1: "UNIV = {a. \<not> R a a} \<union> A \<union> K1" unfolding K1 K11 using A by auto (metis (no_types, lifting) CollectI R getRepr_neper geterRepr_related insertE insert_Diff neper_getRepr_eq neper_trans) have 21: "f ` A \<subseteq> {a. R a a}" using A f(2) rel_funE by fastforce have f0: "(\<forall>x xa. R x x \<and> R xa xa \<and> R (f x) (f xa) \<longrightarrow> R x xa) \<and> (\<forall>x. R x x \<longrightarrow> (\<exists>xa. R xa xa \<and> R (f xa) x))" using R f(1) by (metis biject_rlt_simp) have 22: "{a'. R a' a'} \<subseteq> {a'. \<exists>a\<in>f ` A. R a a'}" proof auto fix x assume "R x x" then obtain a' where "R a' a'" and "R (f a') x" using f0 by blast thus "\<exists>a\<in>A. R (f a) x" apply(intro bexI[of _ "getRepr R a'"]) apply (metis R f(2) geterRepr_related neper_per per_def rel_funE) unfolding A mem_Collect_eq by (metis R getRepr_inject getRepr_neper rel_funE rel_fun_getRepr) qed have 2: "UNIV = {a. \<not> R a a} \<union> f ` A \<union> (\<Union> {{a'. R a a' \<and> a' \<noteq> a} | a. a \<in> f ` A})" using 21 22 apply auto using imageI by blast have "\<forall>a\<in>A. \<exists>aa\<in>A. R a (f aa)" unfolding A Ball_def Bex_def mem_Collect_eq apply safe subgoal for x apply (frule f0[THEN conjunct2, rule_format, of x]) apply (erule exE conjE)+ subgoal for y apply (rule exI[of _ "getRepr R y"]) apply safe apply (metis R rel_funD rel_fun_getRepr) apply (meson R getRepr_neper neper_getRepr_eq) apply (metis R f(2) getRepr_neper neper_sym_eq neper_trans rel_funE) done done done then obtain hh where hh: "\<forall>a\<in>A. hh a \<in> A \<and> R a (f (hh a))" by metis have getRepr_hh: "\<forall>a\<in>A. hh a = getRepr R (hh a)" using A hh by blast define K22 where K22: "K22 \<equiv> \<lambda>a. {a'. R a a'} - {f (hh a)}" define K2 where K2: "K2 \<equiv> (\<Union> {K22 a | a. a \<in> A})" have K2': "(\<Union> {{a'. R a a' \<and> a' \<noteq> a} | a. a \<in> f ` A}) = K2" unfolding K2 K22 apply(rule arg_cong[of _ _ Union], safe) subgoal for _ _ b apply(rule exI[of _ "getRepr R (f b)"]) using hh f(2) unfolding A mem_Collect_eq Ball_def rel_fun_def apply - apply (drule spec[of _ "getRepr R (f b)"]) apply auto apply (metis R rel_funE rel_fun_getRepr) apply (metis R rel_funE rel_fun_getRepr) apply (metis R rel_funE rel_fun_getRepr) apply (metis R rel_funE rel_fun_getRepr) apply (metis R rel_funE rel_fun_getRepr) apply (metis R getRepr_neper neper_getRepr_eq) apply (metis R getRepr_neper neper_getRepr_eq) apply (metis R getRepr_neper neper_getRepr_eq) apply (metis R getRepr_neper neper_getRepr_eq) apply (metis R neper_getRepr_eq) apply (metis R getRepr_neper neper_getRepr_eq) apply (metis R getRepr_neper neper_getRepr_eq) apply (metis R geterRepr_related neper_sym neper_trans) apply (metis R f0 neper_getRepr_eq) apply (metis R getRepr_neper neper_trans) apply (metis R f0 neper_getRepr_eq neper_sym neper_trans) apply (metis R neper_sym neper_trans) apply (metis R getRepr_neper neper_getRepr_eq) done subgoal for _ a apply(rule exI[of _ "f (hh a)"]) using R hh neper_classes_eq by fastforce+ . hence 2: "UNIV = {a. \<not> R a a} \<union> f ` A \<union> K2" using 2 by auto {fix a assume "a \<in> A" have "|K11 a| =o |K22 a|" unfolding K11 K22 by (metis (no_types, lifting) A \<open>a \<in> A\<close> bot.extremum card_eq_minus hh insert_subset mem_Collect_eq) hence "\<exists>uu. bij_betw uu (K11 a) (K22 a)" using card_of_ordIso by blast } then obtain uu where uu: "\<And>a. a\<in>A \<Longrightarrow> bij_betw (uu a) (K11 a) (K22 a)" by metis hence uu': "\<And>a. a\<in>A \<Longrightarrow> uu a ` (K11 a) = K22 a" unfolding bij_betw_def by auto define u where "u \<equiv> \<lambda>a'. uu (getRepr R a') a'" have u: "bij_betw u K1 K2" unfolding bij_betw_def inj_on_def proof safe fix x y assume x: "x \<in> K1" and y: "y \<in> K1" and "u x = u y" hence uuxy: "uu (getRepr R x) x = uu (getRepr R y) y" unfolding u_def K1 using R neper_classes_eq by auto have Rxy: "R x x" "R y y" using x y unfolding K1 K11 A using R neper_classes_eq by fastforce+ hence xA: "getRepr R x \<in> A" unfolding A apply auto apply (metis R rel_funE rel_fun_getRepr) by (meson R getRepr_neper neper_getRepr_eq) have xy: "x \<in> K11 (getRepr R x)" "y \<in> K11 (getRepr R y)" using x y unfolding K1 A by (simp,metis Diff_iff K11 R mem_Collect_eq neper_getRepr_eq)+ show "x = y" proof(cases "R x y") case True hence 0: "getRepr R x = getRepr R y" by (simp add: R neper_getRepr_eq) thus ?thesis using uu[of "getRepr R x"] uuxy xA xy unfolding bij_betw_def inj_on_def by auto next case False hence False using uuxy xy R uu'[of "getRepr R x"] uu'[of "getRepr R y"] unfolding K11 K22 A mem_Collect_eq by (metis (no_types, opaque_lifting) Diff_iff image_eqI mem_Collect_eq neper_classes_eq neper_getRepr_eq neper_sym) thus ?thesis by simp qed next fix a assume "a \<in> K1" thus "u a \<in> K2" unfolding u_def K1 K2 using uu[of "getRepr R a"] unfolding bij_betw_def by simp (metis (mono_tags, lifting) A DiffE K11 R image_eqI mem_Collect_eq neper_getRepr_eq) next fix b2 assume "b2 \<in> K2" then obtain a2 where "b2 \<in> K22 a2" and "a2 \<in> A" unfolding K2 by auto then obtain a1 where "a1 \<in> K11 a2" and "uu a2 a1 = b2" by (metis imageE uu') thus "b2 \<in> u ` K1" unfolding K1 image_def u_def by simp (metis (mono_tags, lifting) A DiffE K11 R \<open>a2 \<in> A\<close> mem_Collect_eq neper_getRepr_eq) qed define g where "g \<equiv> \<lambda>a. if \<not> R a a then a else if a \<in> A then f a else u a" have g[simp]: "\<And>a. \<not> R a a \<Longrightarrow> g a = a" "\<And>a. a \<in> A \<Longrightarrow> g a = f a" "\<And>a. a \<in> K1 \<Longrightarrow> g a = u a" unfolding g_def unfolding A K1 K11 apply auto apply (simp add: R neper_getRepr_eq) apply (metis R neper_getRepr_eq) using R neper_classes_eq by fastforce have g: "bij_betw g UNIV UNIV" apply(subst 1) apply(subst 2) apply(rule bij_betw_combine3) subgoal unfolding bij_betw_def inj_on_def by auto subgoal using \<open>inj_on f A\<close> unfolding bij_betw_def inj_on_def by auto subgoal using u unfolding bij_betw_def inj_on_def by auto subgoal using "21" by auto subgoal unfolding K2 K22 by auto (metis R mem_Collect_eq neper_classes_eq) subgoal unfolding K2'[symmetric] by auto (metis (mono_tags, lifting) A R f0 mem_Collect_eq neper_getRepr_eq) . have gf_getRepr: "\<And>x. R x x \<Longrightarrow> g (getRepr R x) = f (getRepr R x)" using A R g_def getRepr_inject getRepr_neper rel_funD rel_fun_getRepr by fastforce show ?thesis apply(rule exI[of _ g]) using g unfolding bij_betw_def biject_def apply auto apply (meson inj_eq) apply (metis surjD) using gf_getRepr apply blast using R apply simp apply safe apply (metis (full_types) biject_rlt_getRepr biject_rlt_simp f(1) gf_getRepr rel_funE rel_fun_getRepr) proof - fix x :: 'a assume a1: "neper R" assume a2: "R x x" have f3: "per R" using a1 neper_per by blast have f4: "R x (getRepr R x)" using a2 a1 by (simp add: getRepr_neper) then have f5: "getRepr R (getRepr R x) = getRepr R x" using a1 by (metis (no_types) neper_getRepr_eq) have f6: "R (getRepr R x) x" using f4 f3 by (meson per_def) have f7: "\<And>a. \<not> R a x \<or> R a (getRepr R x)" using f4 f3 by (metis (no_types) per_def) obtain aa :: "'a \<Rightarrow> 'a" where f8: "\<And>a. (a \<notin> A \<or> aa a \<in> A) \<and> (a \<notin> A \<or> R a (f (aa a)))" using \<open>\<forall>a\<in>A. \<exists>aa\<in>A. R a (f aa)\<close> by moura then have "getRepr R x \<notin> A \<or> R (f (aa (getRepr R x))) x" using f6 f3 by (metis (no_types) per_def) then show "\<exists>a. R a a \<and> R (g (getRepr R a)) x" using f8 f7 f6 f5 A by fastforce qed qed end lemma biject_rlt_ex_makeCompat: assumes R: "neper R" and f: "biject_rlt R f" "rel_fun R R f f" shows "\<exists>g. biject g \<and> rel_fun R R f (makeCompat R g)" proof- from biject_rlt_ex_getRepr[OF R f] obtain g where bg: "biject g" and g: "\<forall>a. R a a \<longrightarrow> g (getRepr R a) = f (getRepr R a)" and b: "biject_rlt R (\<lambda>a. g (getRepr R a))" by auto have "rel_fun R R f (makeCompat R g)" unfolding makeCompat_def using b apply simp using g R unfolding rel_fun_def by (metis (no_types, lifting) f(2) getRepr_neper neper_per per_def rel_fun_def) thus ?thesis using bg by auto qed wide_typedef biject rel: "\<lambda>R. inv_imagep (rel_fun R R) (makeCompat1 R)" rep: makeCompat1 via type_definition_biject subgoal for R apply(rule neper_inv_imagep[of _ _ "Abs_biject id"]) by (auto simp: rel_fun_makeCompat1_id) subgoal apply simp unfolding inv_imagep_def by (simp add: Rep_biject_inject) subgoal for R unfolding bij_upto_def restr_def apply safe subgoal unfolding inv_imagep_def . subgoal using makeCompat1_biject_biject_rlt by blast subgoal using makeCompat1_biject_biject_rlt by blast subgoal unfolding inv_imagep_def . subgoal for f unfolding inv_imagep_def makeCompat1_def by (metis (no_types, lifting) Abs_biject_inverse biject_rlt_ex_makeCompat makeCompat_biject_biject_rlt mem_Collect_eq neper_per per_def per_rel_fun) subgoal by (metis neper_def per_def per_rel_fun) . subgoal by simp done end
function acv= autocov(x,maxlag) % % autocov computes the sample autocovariance of a time series x for lags % from 0 to maxlag, returning a column vector of length maxlag+1. x must % be a column vector having length m not less than maxlag+1. If no value % is supplied for maxlag, the default is the minimum of m-1 and 100. % % Dr. Phillip M. Feldman % Last update 21 June 2008 % % Based on equations on p. 19 of "Introduction to Time Series and % Forecasting" 2nd Edition by Brockwell and Davis. % Section 1: Check input arguments and supply default value for maxlag % if needed. if nargin < 1, error('Missing input vector.'); end [m n]= size(x); if (n ~= 1) error('x must be a column vector.') end if (m <= maxlag) error('The length of the input vector x must be at least maxlag+1.'); end if nargin < 2, maxlag= min(m-1,100); end % Section 2: Compute autocovariance. % Remove mean from x: x= x - mean(x); % For faster running time, we pre-allocate the output array: acv= zeros(maxlag+1,1); % Compute autocovariance: for h= 0 : maxlag % Take matrix product of row vector and column vector to obtain a % scalar. The row vector contains the first n-h elements of x; the % column vector contains the last n-h elements of x. acv(h+1)= x(1:m-h)' * x(1+h:m); end acv= acv / m;
import Data.Vect import Data.Vect.Views total mergeSort : Ord a => Vect n a -> Vect n a mergeSort xs with (splitRec xs) mergeSort [] | SplitRecNil = [] mergeSort [x] | SplitRecOne = [x] mergeSort (ys ++ zs) | SplitRecPair ysrec zsrec = merge (mergeSort ys | ysrec) (mergeSort zs | zsrec) testList : Int -> Int -> List Int -> List Int testList 0 seed acc = acc -- Need to explicitly mod since different back ends overflow differently testList x seed acc = let seed' = (seed * 12345 + 768) `mod` 65536 in testList (x - 1) seed' ((seed' `mod` 100) :: acc) myhead : List a -> a myhead (x :: xs) = x main : IO () main = do let list = fromList (testList 100 12345 []) putStrLn "Sorting list" let list' = mergeSort list printLn list'
\chapter{Data formats} \label{sec:dataformat} %\section{Level1B data} %\section{Climatological \textit{apriori} data} %\section{ZPT data} %\section{Sensor characteristic data} %\section{Spectroscopic data} %\section{Configuration} %\subsection{Definition of settings} %\includepdf[pages={1,2,3,4}]{q_fields_test.pdf} \includepdf[pages={1,2,3,4}]{q_fields.pdf} %\includepdf[pages={{},-}]{q_fields.pdf} %\subsection{The actual setting?} %The Matlab function displayed below describes common %and frequency mode specific configuration of %the Level2 processor\dots\todo{? this is not complete, but should this description be included %5at all.}\ %\input{q_std} %\section{Level2 data} %\section{Level2 Auxiliary data} %%% Local Variables: %%% mode: latex %%% TeX-master: "L1_ATBD" %%% End:
lemma complex_cnj_add [simp]: "cnj (x + y) = cnj x + cnj y"
Formal statement is: lemma frontier_halfspace_gt: assumes "a \<noteq> 0 \<or> b \<noteq> 0" shows "frontier {x. a \<bullet> x > b} = {x. a \<bullet> x = b}" Informal statement is: If $a \neq 0$ or $b \neq 0$, then the frontier of the halfspace $\{x \in \mathbb{R}^n \mid a \cdot x > b\}$ is the hyperplane $\{x \in \mathbb{R}^n \mid a \cdot x = b\}$.
## This file autogenerated by BinaryProvider.write_deps_file(). ## Do not edit. ## ## Include this file within your main top-level source, and call ## `check_deps()` from within your module's `__init__()` method if isdefined((@static VERSION < v"0.7.0-DEV.484" ? current_module() : @__MODULE__), :Compat) import Compat.Libdl elseif VERSION >= v"0.7.0-DEV.3382" import Libdl end const cclipper = joinpath(dirname(@__FILE__), "usr/lib/cclipper.so") function check_deps() global cclipper if !isfile(cclipper) error("$(cclipper) does not exist, Please re-run Pkg.build(\"Clipper\"), and restart Julia.") end if Libdl.dlopen_e(cclipper) == C_NULL error("$(cclipper) cannot be opened, Please re-run Pkg.build(\"Clipper\"), and restart Julia.") end end
[STATEMENT] lemma sound_and_compltete_mat_leqb_eqc [iff]: assumes "dim_row A\<^sup>T = dim_vec c" assumes "dim_col A\<^sup>T = dim_vec b" shows "(\<exists>x. [A *\<^sub>v x]\<le>b) \<and> (\<exists>y. [y \<^sub>v* A]=c) \<longleftrightarrow> (\<exists>X. simplex (mat_leqb_eqc A b c) = Sat X)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. ((\<exists>x. [A*\<^sub>vx]\<le>b) \<and> (\<exists>y. [y\<^sub>v*A]=c)) = (\<exists>X. simplex (mat_leqb_eqc A b c) = Inr X) [PROOF STEP] by (metis assms(1) assms(2) completeness_mat_leqb_eqc index_transpose_mat(3) soundness_mat_leqb_eqc1 soundness_mat_leqb_eqc2)
############################################################# # # Friends & Followers Functions # ############################################################# function post_friendships_create(; options=Dict{AbstractString, AbstractString}()) r = post_oauth("https://api.twitter.com/1.1/friendships/create.json", options) #Return array of type USERS return r.status == 200 ? to_USERS(Requests.json(r)) : r end function post_friendships_destroy(; options=Dict{AbstractString, AbstractString}()) r = post_oauth("https://api.twitter.com/1.1/friendships/destroy.json", options) #Return array of type USERS return r.status == 200 ? to_USERS(Requests.json(r)) : r end function post_friendships_update(; options=Dict{AbstractString, AbstractString}()) r = post_oauth("https://api.twitter.com/1.1/friendships/destroy.json", options) return r.status == 200 ? Requests.json(r) : r end function get_friends_list(; options=Dict{AbstractString, AbstractString}()) r = get_oauth("https://api.twitter.com/1.1/friends/list.json", options) #Return users array return r.status == 200 ? to_USERS(Requests.json(r)["users"]) : r end function get_followers_list(; options=Dict{AbstractString, AbstractString}()) r = get_oauth("https://api.twitter.com/1.1/followers/list.json", options) #Return users array return r.status == 200 ? to_USERS(Requests.json(r)["users"]) : r end
Formal statement is: lemma frontier_complement [simp]: "frontier (- S) = frontier S" Informal statement is: The frontier of the complement of a set is the same as the frontier of the set.
C LAST UPDATE 28/11/95 C+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ C PROGRAM FDSCALE IMPLICIT NONE C C Purpose: Scales intensity output from LSQINT, either for common C reflections or just on the weighted sums of the intensities. C C Calls 6: RDCOMF , RECCEL , DCAL , SVDCMP , SVBKSB , SVDVAR C Called by: C C-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- C Parameters: C INTEGER NLLPX,MAXBIN,MAXFIL,NPARS PARAMETER(NLLPX=2048,MAXBIN=20,MAXFIL=20,NPARS=2) C C Local arrays: C REAL VALS(10),RINT(MAXFIL,NLLPX),SIG(MAXFIL,NLLPX), & RL(2,NLLPX,MAXFIL),CELL(6),RS(NLLPX), & RCELL(6),DELR(MAXFIL),D(MAXFIL,NLLPX),SUM(MAXFIL,MAXBIN), & SSG(MAXFIL,MAXBIN),K(MAXFIL), & B(MAXFIL),A(MAXBIN,NPARS),W(NPARS),V(NPARS,NPARS),P(MAXBIN), & X(NPARS),CVM(NPARS,NPARS),SK(MAXFIL),SB(MAXFIL) INTEGER ITEM(MAXBIN),HKM(3,NLLPX,MAXFIL),NR(MAXFIL,MAXBIN), & NREF(MAXFIL),ITAG(MAXFIL,NLLPX),NI(NLLPX,2),IND(NLLPX) CHARACTER*40 WORD(10),FILES(MAXFIL) C C Local variables: C REAL RESMIN,RESLIM,DMAX,COMSUM,COMDEN,DR,SI,SSI,SIGS,SIGO,DFM,TMP INTEGER NW,NV,IRC,NFILE,NBIN,IREF,I,J,IB,N,M,L,LMIN,LMAX,IL,NS,IS INTEGER NRG,KG,NRT,IW REAL AV(MAXFIL),AVS,RSNUM,RSDEN,RSYM LOGICAL NEXT,SUMS,COMM,BRAG,CONT,MERG,FEX,SYMM CHARACTER*40 OUTFIL INTEGER IJUNK,IUNIQ,ISCAL,IOUTP,IRESO,IMERG,NLAST C C External functions: C REAL DCAL EXTERNAL DCAL C C----------------------------------------------------------------------- C C========Open log file C OPEN(UNIT=4,FILE='FDSCALE.LOG',STATUS='UNKNOWN') WRITE(6,1000) WRITE(4,1000) C C========Set up defaults C NEXT = .TRUE. COMM = .TRUE. SUMS = .FALSE. BRAG = .FALSE. CONT = .FALSE. MERG = .FALSE. NBIN = 1 NFILE = 0 RESLIM = 0.0 RESMIN = 0.0 DMAX = 0.0 SIGS = 3.0 SIGO = 1.5 C C=======Read keyworded input C 10 WRITE(6,'(A9,$)')'FDSCALE> ' CALL RDCOMF(5,WORD,NW,VALS,NV,ITEM,10,10,40,IRC) IF(IRC.EQ.2)GOTO 10 IF(IRC.EQ.1)GOTO 9999 CALL WRTLOG(4,WORD,NW,VALS,NV,ITEM,10,10,IRC) IF(ITEM(1).EQ.0)GOTO 10 IF(ITEM(1).NE.2)THEN WRITE(6,1010) WRITE(4,1010) GOTO 10 ENDIF DO 15 IW=1,NW CALL UPPER(WORD(IW),40) 15 CONTINUE C IF(WORD(1)(1:3).EQ.'RUN')THEN NEXT = .FALSE. ELSEIF(WORD(1)(1:4).EQ.'SUMS')THEN SUMS = .TRUE. COMM = .FALSE. ELSEIF(WORD(1)(1:4).EQ.'COMM')THEN COMM = .TRUE. ELSEIF(WORD(1)(1:4).EQ.'RSYM')THEN SYMM = .TRUE. COMM = .FALSE. ELSEIF(WORD(1)(1:4).EQ.'MERG')THEN MERG = .TRUE. C C========Read output filename C WRITE(6,1040) WRITE(4,1040) READ(5,'(A)',END=9999)OUTFIL WRITE(4,'(A)')OUTFIL ELSEIF(WORD(1)(1:4).EQ.'BINS')THEN IF(ITEM(2).NE.1)THEN WRITE(6,1020) WRITE(4,1020) ELSE NBIN = NINT(VALS(1)) IF(NBIN.GT.20)THEN WRITE(6,1026)MAXBIN WRITE(4,1026)MAXBIN NBIN = MAXBIN ENDIF ENDIF ELSEIF(WORD(1)(1:4).EQ.'FILE')THEN C C========Read input filenames C WRITE(6,1030) WRITE(4,1030) NFILE = 1 20 CONTINUE IF(NFILE.GT.MAXFIL)THEN WRITE(6,1035)MAXFIL WRITE(4,1035)MAXFIL GOTO 10 ENDIF CALL RDCOMF(5,WORD,NW,VALS,NV,ITEM,10,10,40,IRC) IF(IRC.EQ.2)GOTO 10 IF(IRC.EQ.1)GOTO 10 CALL WRTLOG(4,WORD,NW,VALS,NV,ITEM,10,10,IRC) IF(ITEM(1).EQ.0)GOTO 10 IF(ITEM(1).NE.2)THEN WRITE(6,1010) WRITE(4,1010) GOTO 10 ENDIF FILES(NFILE) = WORD(1) INQUIRE(FILE=FILES(NFILE),EXIST=FEX) IF(.NOT.FEX)THEN WRITE(6,1036)FILES(NFILE) WRITE(4,1036)FILES(NFILE) ELSE NFILE = NFILE + 1 ENDIF GOTO 20 ELSEIF(WORD(1)(1:4).EQ.'RESO')THEN IF(ITEM(2).NE.1)THEN WRITE(6,1020) WRITE(4,1020) ELSE RESMIN = VALS(1) RESLIM = VALS(2) ENDIF ELSEIF(WORD(1)(1:4).EQ.'SIGM')THEN IF(ITEM(2).NE.2)THEN WRITE(6,1010) WRITE(4,1010) ELSE DO 25 I=2,NW IF(WORD(I)(1:4).EQ.'SCAL')THEN IF(ITEM(2*I-1).NE.1)THEN WRITE(6,1020) WRITE(4,1020) ELSE SIGS = VALS(I-1) ENDIF ELSEIF(WORD(I)(1:4).EQ.'OUTP')THEN IF(ITEM(2*I-1).NE.1)THEN WRITE(6,1020) WRITE(4,1020) ELSE SIGO = VALS(I-1) ENDIF ELSE WRITE(6,1025) WRITE(4,1025) ENDIF 25 CONTINUE ENDIF ELSE WRITE(6,1025) WRITE(4,1025) ENDIF C IF(NEXT)GOTO 10 C C========Loop over input files to determine Bragg/continuous etc C NFILE = NFILE - 1 DO 50 I=1,NFILE IREF = 0 DFM = 0.0 CALL FILEOPEN(10,FILES(I),40,IRC) IF(IRC.NE.0)THEN WRITE(6,1045) WRITE(4,1045) GOTO 50 ENDIF 30 CALL RDCOMF(10,WORD,NW,VALS,NV,ITEM,10,10,40,IRC) IF(IRC.EQ.2)THEN WRITE(6,1050) WRITE(4,1050) ELSEIF(IRC.EQ.1)THEN GOTO 45 ENDIF DO 35 IW=1,NW CALL UPPER(WORD(IW),40) 35 CONTINUE IF(ITEM(1).EQ.2)THEN IF(WORD(1)(1:4).EQ.'BRAG')THEN BRAG = .TRUE. CONT = .FALSE. ELSEIF(WORD(1)(1:4).EQ.'CONT')THEN CONT = .TRUE. BRAG = .FALSE. ELSEIF(WORD(1)(1:4).EQ.'CELL')THEN DO 40 J=1,NV CELL(J) = VALS(J) 40 CONTINUE write(6,*)' Cell: ',cell DO 41 J=4,6 CELL(J) = CELL(J)*ATAN(1.0)/45.0 41 CONTINUE ELSEIF(WORD(1)(1:4).EQ.'DELT')THEN DELR(I) = VALS(1) ENDIF ELSEIF(ITEM(1).EQ.1)THEN IF(IREF.EQ.0.AND.BRAG)then CALL RECCEL(CELL,RCELL) write(6,*)' Reciprocal cell: ',rcell endif IREF = IREF + 1 IF(IREF.GT.NLLPX)THEN WRITE(6,1055)I,NLLPX WRITE(4,1055)I,NLLPX GOTO 45 ENDIF HKM(1,IREF,I) = NINT(VALS(1)) HKM(2,IREF,I) = NINT(VALS(2)) RL(2,IREF,I) = VALS(3) RL(1,IREF,I) = VALS(4) HKM(3,IREF,I) = NINT(VALS(5)) RINT(I,IREF) = VALS(6) SIG(I,IREF) = VALS(7) IF(BRAG)THEN D(I,IREF) = DCAL(RCELL,HKM(1,IREF,I),HKM(2,IREF,I), & NINT(RL(2,IREF,I))) ELSEIF(CONT)THEN D(I,IREF) = SQRT((RL(2,IREF,I)/CELL(1))**2 & +RL(1,IREF,I)**2) ENDIF IF(D(I,IREF).GT.DFM)DFM = D(I,IREF) IF(D(I,IREF).GT.DMAX)DMAX = D(I,IREF) ITAG(I,IREF) = 0 ENDIF GOTO 30 45 NREF(I) = IREF WRITE(6,1060)I,NREF(I),DFM WRITE(4,1060)I,NREF(I),DFM CALL FILECLOSE(10) 50 CONTINUE WRITE(6,1070)DMAX WRITE(4,1070)DMAX IF(RESLIM.EQ.0.0)RESLIM = DMAX C C========Calculate weights and average intensities if required C DO 70 I=1,NFILE DO 55 IB=1,NBIN SSG(I,IB) = 0.0 SUM(I,IB) = 0.0 NR(I,IB) = 0 55 CONTINUE DO 60 N=1,NREF(I) IF(SIG(I,N).EQ.0.0)THEN ITAG(I,N) = 16 ENDIF IF(D(I,N).LT.RESMIN.OR.D(I,N).GT.RESLIM)THEN ITAG(I,N) = ITAG(I,N) + 8 ENDIF IF(MOD(ITAG(I,N)/16,2).EQ.0)THEN IF(RINT(I,N)/SIG(I,N).LT.SIGO)THEN ITAG(I,N) = ITAG(I,N) + 4 ENDIF IF(RINT(I,N)/SIG(I,N).LT.SIGS)THEN ITAG(I,N) = ITAG(I,N) + 2 ENDIF ENDIF IF(ITAG(I,N).LT.7)THEN IF(MOD(ITAG(I,N)/2,2).EQ.0)THEN IB = INT(FLOAT(NBIN-1)* & (D(I,N)-RESMIN)/(RESLIM-RESMIN)) + 1 NR(I,IB) = NR(I,IB) + 1 SUM(I,IB) = SUM(I,IB) + RINT(I,N) SSG(I,IB) = SSG(I,IB) + SIG(I,N)*SIG(I,N) ENDIF ENDIF 60 CONTINUE WRITE(6,1080)I WRITE(4,1080)I DO 65 IB=1,NBIN IF(NR(I,IB).GT.0)THEN SUM(I,IB) = SUM(I,IB)/FLOAT(NR(I,IB)) SSG(I,IB) = SSG(I,IB)/FLOAT(NR(I,IB)) SSG(I,IB) = SQRT(SSG(I,IB)) ENDIF WRITE(6,1090)IB,NR(I,IB),SUM(I,IB),SSG(I,IB) WRITE(4,1090)IB,NR(I,IB),SUM(I,IB),SSG(I,IB) 65 CONTINUE 70 CONTINUE C C========Calculate scale factors and relative temperature factors C IF(SUMS)THEN I = 1 K(1) = 1.0 B(1) = 0.0 SK(I) = 0.0 SB(I) = 0.0 WRITE(6,1100) WRITE(4,1100) WRITE(6,1110)I,K(I),B(I),SK(I),SB(I) WRITE(4,1110)I,K(I),B(I),SK(I),SB(I) IF(NBIN.GT.1)THEN DO 90 I=2,NFILE IB = 0 DO 80 M=1,NBIN IF(NR(1,M).GT.0.AND.NR(I,M).GT.0)THEN IF(SSG(I,M).GT.0.0.AND.SUM(I,M).GT.0.0.AND. & SSG(1,M).GT.0.0.AND.SUM(1,M).GT.0.0)THEN IB = IB + 1 TMP = SSG(I,M)/SUM(I,M) + SSG(1,M)/SUM(1,M) A(IB,1) = 1.0/TMP A(IB,2) = 0.5*(RESMIN+(FLOAT(M)-0.5) & *(RESLIM-RESMIN)/FLOAT(NBIN))**2 & /TMP P(IB) = LOG(SUM(1,M)/SUM(I,M))/TMP ENDIF ENDIF 80 CONTINUE CALL SVDCMP(A,IB,2,MAXBIN,NPARS,W,V) IF(1.0E+05*ABS(W(2)).LT.ABS(W(1)))THEN W(2) = 0.0 ELSEIF(1.0E+05*ABS(W(1)).LT.ABS(W(2)))THEN W(1) = 0.0 ENDIF CALL SVBKSB(A,W,V,IB,2,MAXBIN,NPARS,P,X) K(I) = EXP(X(1)) B(I) = X(2) CALL SVDVAR(V,2,2,W,CVM,NPARS) SK(I) = K(I)*SQRT(CVM(1,1)) SB(I) = SQRT(CVM(2,2)) WRITE(6,1110)I,K(I),B(I),SK(I),SB(I) WRITE(4,1110)I,K(I),B(I),SK(I),SB(I) 90 CONTINUE ELSE DO 100 I=2,NFILE K(I) = SUM(1,1)/SUM(I,1) B(I) = 0.0 SK(I) = K(I)*(SSG(1,1)/SUM(1,1)+SSG(I,1)/SUM(I,1)) SB(I) = 0.0 WRITE(6,1110)I,K(I),B(I),SK(I),SB(I) WRITE(4,1110)I,K(I),B(I),SK(I),SB(I) 100 CONTINUE ENDIF ENDIF C C========Calculate a scale factor on common reflections if required C COMSUM = 0.0 COMDEN = 0.0 RSNUM = 0.0 RSDEN = 0.0 NRT = 0 DO 150 I=1,NFILE DO 140 N=1,NREF(I) NRG = 0 IF(ITAG(I,N).GT.7)GOTO 140 IF(MOD(ITAG(I,N),2).EQ.0)THEN IF(SYMM)THEN IF(MOD(ITAG(I,N)/2,2).EQ.0)THEN AV(1) = RINT(I,N) AVS = RINT(I,N) NRG = 1 ENDIF ENDIF ENDIF DO 130 J=I+1,NFILE IF(BRAG)THEN DR = AMAX1(DELR(I),DELR(J))/2.0 ELSE DR = AMIN1(DELR(I),DELR(J))/2.0 ENDIF DO 120 M=1,NREF(J) IF(NINT(RL(2,N,I)).EQ.NINT(RL(2,M,J)))THEN IF(ABS(RL(1,N,I)-RL(1,M,J)).LT.DR)THEN IF(MOD(ITAG(J,M),2).EQ.0)THEN ITAG(J,M) = ITAG(J,M) + 1 ENDIF IF(ITAG(J,M).LT.7.AND.(COMM.OR.SYMM))THEN IF(MOD(ITAG(I,N)/2,2).EQ.0.AND. & MOD(ITAG(J,M)/2,2).EQ.0)THEN COMSUM = COMSUM + FLOAT(J-I)* & LOG(RINT(I,N)/RINT(J,M))/ & (SIG(I,N)/RINT(I,N)+SIG(J,M)/ & RINT(J,M))**2 COMDEN = COMDEN + (FLOAT(J-I)/ & (SIG(I,N)/RINT(I,N)+SIG(J,M)/ & RINT(J,M)))**2 IF(SYMM)THEN IF(MOD(ITAG(I,N),2).EQ.0)THEN NRG = NRG + 1 AV(NRG) = RINT(J,M) AVS = AVS + RINT(J,M) ENDIF ENDIF ENDIF ENDIF ENDIF ENDIF 120 CONTINUE 130 CONTINUE IF(SYMM)THEN IF(MOD(ITAG(I,N),2).EQ.0.AND. & MOD(ITAG(I,N)/2,2).EQ.0)THEN AVS = AVS/FLOAT(NRG) DO 135 KG=1,NRG RSNUM = RSNUM + ABS(AV(KG)-AVS) RSDEN = RSDEN + AV(KG) NRT = NRT + 1 135 CONTINUE ENDIF ENDIF 140 CONTINUE C C========See what's what C IJUNK = 0 IRESO = 0 IOUTP = 0 ISCAL = 0 IUNIQ = 0 DO 145 N=1,NREF(I) IF(ITAG(I,N).GE.16)THEN IJUNK = IJUNK + 1 ELSE IF(MOD(ITAG(I,N)/8,2).EQ.0)THEN IRESO = IRESO + 1 ENDIF IF(MOD(ITAG(I,N)/4,2).EQ.0)THEN IOUTP = IOUTP + 1 ENDIF IF(MOD(ITAG(I,N)/2,2).EQ.0)THEN ISCAL = ISCAL + 1 ENDIF IF(MOD(ITAG(I,N),2).EQ.0)THEN IUNIQ = IUNIQ + 1 ENDIF ENDIF 145 CONTINUE WRITE(6,1150)I,NREF(I),IJUNK,IRESO,RESMIN,RESLIM,IUNIQ,ISCAL, & SIGS,IOUTP,SIGO WRITE(4,1150)I,NREF(I),IJUNK,IRESO,RESMIN,RESLIM,IUNIQ,ISCAL, & SIGS,IOUTP,SIGO 150 CONTINUE IF(COMM)THEN K(1) = EXP(COMSUM/COMDEN) B(1) = 0.0 SK(1) = K(1)/SQRT(COMDEN) SB(1) = 0.0 WRITE(6,1120)K(1),SK(1) WRITE(4,1120)K(1),SK(1) DO 160 I=2,NFILE K(I) = K(I-1)*K(1) B(I) = 0.0 160 CONTINUE ELSEIF(SYMM)THEN RSYM = RSNUM/RSDEN WRITE(6,1125)RSYM,NRT DO 165 I=1,NFILE K(I) = 1.0 B(I) = 0.0 165 CONTINUE ENDIF C C========Merge data if required C IF(MERG)THEN IMERG = 0 DO 200 I=1,NFILE DO 190 N=1,NREF(I) IF(MOD(ITAG(I,N),2).EQ.0.AND. & MOD(ITAG(I,N)/4,2).EQ.0)THEN IMERG = IMERG + 1 SI = K(I)*RINT(I,N)*EXP(B(I)*D(I,N)**2/2.0) SSI = (SK(I)+K(I))*(SIG(I,N)+RINT(I,N)) & *EXP((SB(I)+B(I))*D(I,N)*D(I,N)/2.0) SSI = SSI - SI COMSUM = SI/(SSI*SSI) COMDEN = 1.0/(SSI*SSI) SIG(I,N) = SSI DO 180 J=I+1,NFILE IF(BRAG)THEN DR = AMAX1(DELR(I),DELR(J))/2.0 ELSE DR = AMIN1(DELR(I),DELR(J))/2.0 ENDIF DO 170 M=1,NREF(J) IF(NINT(RL(2,N,I)).EQ.NINT(RL(2,M,J)))THEN IF(ABS(RL(1,N,I)-RL(1,M,J)).LT.DR)THEN IF(MOD(ITAG(J,M)/4,2).EQ.0)THEN SI = K(J)*RINT(J,M)*EXP(B(J)* & D(J,M)**2/2.0) SSI = (SK(J)+K(J))*(SIG(J,M)+ & RINT(J,M))*EXP((SB(J)+B(J)) & *D(J,M)*D(J,M)/2.0) SSI = SSI - SI COMSUM = COMSUM + SI/(SSI*SSI) COMDEN = COMDEN + 1.0/(SSI*SSI) ENDIF ENDIF ENDIF 170 CONTINUE IF(J.EQ.NFILE)THEN RINT(I,N) = COMSUM/COMDEN SIG(I,N) = 1.0/SQRT(COMDEN) ENDIF 180 CONTINUE ENDIF 190 CONTINUE 200 CONTINUE WRITE(6,1180)IMERG C C========Write header information C OPEN(UNIT=10,FILE=OUTFIL,STATUS='UNKNOWN') IF(BRAG)THEN DO 205 I=4,6 CELL(I) = CELL(I)*45.0/ATAN(1.0) 205 CONTINUE WRITE(10,2000)CELL LMIN = NINT(RESMIN/RCELL(3)) LMAX = NINT(RESLIM/RCELL(3)) ELSE WRITE(10,2010)CELL(1) LMIN = NINT(RESMIN*CELL(1)) LMAX = NINT(RESLIM*CELL(1)) ENDIF C C========Sort output C IREF = 0 DO 240 L=LMIN,LMAX IL = 0 DO 220 I=1,NFILE DO 210 N=1,NREF(I) IF(MOD(ITAG(I,N)/8,2).EQ.0)THEN IF(NINT(RL(2,N,I)).EQ.L)THEN IL = IL + 1 RS(IL) = RL(1,N,I) NI(IL,1) = N NI(IL,2) = I ENDIF ENDIF 210 CONTINUE 220 CONTINUE IF(IL.GT.0)CALL SORT(RS,IL,IND) NLAST = 1 DO 230 N=1,IL NS = NI(IND(N),1) IS = NI(IND(N),2) DR = DELR(IS)/2.0 DO 225 M=NLAST,NS-1 IF(NINT(RL(2,M,IS)).EQ.L.AND. & HKM(3,M,IS).EQ.0.AND. & ABS(RL(1,NS,IS)-RL(1,M,IS)).LT.DR)THEN WRITE(10,1130)HKM(1,M,IS),HKM(2,M,IS), & NINT(RL(2,M,IS)),RL(1,M,IS), & HKM(3,M,IS),RINT(IS,M),SIG(IS,M) IREF = IREF + 1 ENDIF 225 CONTINUE NLAST = NS + 1 WRITE(10,1130)HKM(1,NS,IS),HKM(2,NS,IS), & NINT(RL(2,NS,IS)),RL(1,NS,IS), & HKM(3,NS,IS),RINT(IS,NS),SIG(IS,NS) IREF = IREF + 1 230 CONTINUE 240 CONTINUE CLOSE(10) WRITE(6,1140)IREF WRITE(4,1140)IREF ENDIF STOP 'Normal stop' 9999 STOP 'USER STOP' C 1000 FORMAT(1X,'FDSCALE: Fibre diffraction intensity scaling program'/ & 1X,'Last update 28/11/95'/) 1010 FORMAT(1X,'***Keyword expected') 1020 FORMAT(1X,'***Value expected') 1025 FORMAT(1X,'***Unrecognised keyword') 1026 FORMAT(1X,'Too many bins, resetting to ',I3) 1030 FORMAT(1X,'Enter input filenames') 1035 FORMAT(1X,'Maximum number of input files = ',I3) 1036 FORMAT(1X,'***Input file does not exist: ',A40) 1040 FORMAT(1X,'Enter output filename ') 1045 FORMAT(1X,'***Error opening input file: ',A40) 1050 FORMAT(1X,'FDSCALE: Error reading input file') 1055 FORMAT(1X,'Number of reflections in file ',I2,' exceeds ',I4) 1060 FORMAT(1X,'Number of reflections read from file ',I2,':',I5/ & 1X,'d*max = ',F8.6) 1070 FORMAT(1X,'Maximum d* ',F8.6) 1080 FORMAT(/1X,'File number ',I2 & /1X,'Bin No. Refs. <I> Sigma(<I>)') 1090 FORMAT(1X,I2,10X,I6,4X,G12.5,4X,G12.5) 1100 FORMAT(/1X,'File Scale factor Temp factor') 1110 FORMAT(1X,I3,10X,2(E12.4,8X)/14X,2(E12.4,8X)) 1120 FORMAT(1X,'Film pack scale factor ',F8.4,2X,'std ',F8.4) 1125 FORMAT(/1X,'Rsym = ', G12.5, ' from ',I6,' reflections') 1130 FORMAT(1X,3I4,E12.4,I4,2E12.4) 1140 FORMAT(1X,'Number of reflections written = ',I8) 1150 FORMAT(/1X,'File ',I2,3X,I8,' reflections'/ & 11X,I8,' unmeasured'/ & 11X,I8,' inside resolution limits', & 5X,'(',F7.5,' < d* < ',F7.5,')'/ & 11X,I8,' unique to this dataset'/ & 11X,I8,' used for scaling',5X,'(I/sigma(I) > ',F5.1,')'/ & 11X,I8,' used for output ',5X,'(I/sigma(I) > ',F5.1,')') 1180 FORMAT(/1X,'Total number of reflections merged = ',I8) 2000 FORMAT('BRAGG'/'CELL ',6F8.3) 2010 FORMAT('CONTINUOUS'/'CELL ',F8.3) END
! { dg-do compile } module binding_label_tests_6 use, intrinsic :: iso_c_binding integer(c_int), bind(c, name='my_int') :: my_f90_int_1 ! { dg-error "collides" } integer(c_int), bind(c, name='my_int') :: my_f90_int_2 ! { dg-error "collides" } end module binding_label_tests_6
! { dg-do compile } ! { dg-options "-std=f2003" } ! ! Test our conformance to item 4.9 ("Kind type parameters of integer ! specifiers") of the Fortran 2003 status document at ! ftp://ftp.nag.co.uk/sc22wg5/N1551-N1600/N1579.pdf ! ! The non-default integer variables are allowed since Fortran 2003. ! The non-default logical variables are allowed since Fortran 2008. integer(kind=8) :: i, j, k, n logical(kind=8) :: l1, l2, l3 open(10, status="scratch", iostat=i) backspace(10, iostat=i) endfile(10, iostat=i) rewind(10, iostat=i) read(*, '(I2)', iostat=i) k read(*, '(I2)', advance='no', size=j) k inquire(iolength=i) "42" inquire(10, iostat=i) inquire(10, number=j) inquire(10, recl=k) inquire(10, nextrec=n) inquire(10, exist=l1) ! { dg-error "Non-default LOGICAL kind" } inquire(10, named=l3) ! { dg-error "Non-default LOGICAL kind" } inquire(10, opened=l2) ! { dg-error "Non-default LOGICAL kind" } inquire(10, pending=l2) ! { dg-error "Non-default LOGICAL kind" } close(10, iostat=i) end
If $k > 0$, then the set of all $m \in \mathbb{N}$ such that $m^k \leq n$ is a subset of the set $\{0, 1, \ldots, n\}$.
<h1> Validation Measures </h1> #### Read the data ```python import pickle as pkl with open('../data/titanic_tansformed.pkl', 'rb') as f: df_data = pkl.load(f) ``` ```python df_data.head(8) ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>Survived</th> <th>Age</th> <th>SibSp</th> <th>Parch</th> <th>Fare</th> <th>1</th> <th>2</th> <th>3</th> <th>female</th> <th>male</th> <th>C</th> <th>Q</th> <th>S</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>0</td> <td>22.0</td> <td>1</td> <td>0</td> <td>7.2500</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>1</td> </tr> <tr> <th>1</th> <td>1</td> <td>38.0</td> <td>1</td> <td>0</td> <td>71.2833</td> <td>1</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> </tr> <tr> <th>2</th> <td>1</td> <td>26.0</td> <td>0</td> <td>0</td> <td>7.9250</td> <td>0</td> <td>0</td> <td>1</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> </tr> <tr> <th>3</th> <td>1</td> <td>35.0</td> <td>1</td> <td>0</td> <td>53.1000</td> <td>1</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> </tr> <tr> <th>4</th> <td>0</td> <td>35.0</td> <td>0</td> <td>0</td> <td>8.0500</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>1</td> </tr> <tr> <th>5</th> <td>0</td> <td>25.0</td> <td>0</td> <td>0</td> <td>8.4583</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>1</td> <td>0</td> <td>1</td> <td>0</td> </tr> <tr> <th>6</th> <td>0</td> <td>54.0</td> <td>0</td> <td>0</td> <td>51.8625</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>1</td> </tr> <tr> <th>7</th> <td>0</td> <td>2.0</td> <td>3</td> <td>1</td> <td>21.0750</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>1</td> </tr> </tbody> </table> </div> ## Logistic Regression ```python data = df_data.drop("Survived",axis=1) label = df_data["Survived"] ``` ```python data.head() ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>Age</th> <th>SibSp</th> <th>Parch</th> <th>Fare</th> <th>1</th> <th>2</th> <th>3</th> <th>female</th> <th>male</th> <th>C</th> <th>Q</th> <th>S</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>22.0</td> <td>1</td> <td>0</td> <td>7.2500</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>1</td> </tr> <tr> <th>1</th> <td>38.0</td> <td>1</td> <td>0</td> <td>71.2833</td> <td>1</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> </tr> <tr> <th>2</th> <td>26.0</td> <td>0</td> <td>0</td> <td>7.9250</td> <td>0</td> <td>0</td> <td>1</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> </tr> <tr> <th>3</th> <td>35.0</td> <td>1</td> <td>0</td> <td>53.1000</td> <td>1</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> </tr> <tr> <th>4</th> <td>35.0</td> <td>0</td> <td>0</td> <td>8.0500</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>1</td> </tr> </tbody> </table> </div> ```python from sklearn.cross_validation import train_test_split data_train, data_test, label_train, label_test = train_test_split(data, label, test_size = 0.3, random_state = 101) ``` /Users/talat/anaconda3/lib/python3.6/site-packages/sklearn/cross_validation.py:41: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20. "This module will be removed in 0.20.", DeprecationWarning) ```python from sklearn.linear_model import LogisticRegression # Run Logistic Regression log_regr = LogisticRegression() log_regr.fit(data_train, label_train) predictions = log_regr.predict(data_test) ``` ### Accuracy \begin{align} Accuracy = \frac{TP + TN}{TP + TN + FP + FN} \end{align} ```python print('Accuracy', log_regr.score(data_test, label_test)) ``` Accuracy 0.8277153558052435 ### Precision Recall \begin{align} Precision = \frac{TP}{TP + FP} \end{align} \begin{align} Recall = \frac{TP}{TP + FN} \end{align} \begin{align} F1 Score = 2 * \frac{Recall * Precision}{Recall + Precision} \end{align} ```python from sklearn.metrics import classification_report print(classification_report(label_test, predictions)) ``` precision recall f1-score support 0 0.82 0.92 0.87 163 1 0.85 0.68 0.76 104 avg / total 0.83 0.83 0.82 267 ## Cross Validation ```python from sklearn.model_selection import StratifiedKFold from sklearn.linear_model import LogisticRegression from sklearn.model_selection import cross_val_score # skf = StratifiedKFold(n_splits=5) log_regr = LogisticRegression() log_regr.fit(data_train, label_train) score = log_regr.score(data_train, label_train) print('Train accuracy score', score) score_cv = cross_val_score(log_regr, data_train, label_train, cv=10, scoring='accuracy') print('Cross Val Accuracy for each run', score_cv) print('CrossVal Accuracy', score_cv.mean()) ``` Train accuracy score 0.8086816720257235 Cross Val Accuracy for each run [0.76190476 0.6984127 0.79365079 0.87301587 0.80952381 0.77777778 0.78688525 0.81967213 0.91803279 0.7704918 ] CrossVal Accuracy 0.8009367681498828 ## AUC - Receiver Operating Characteristics - How much a model is capable of distinguishing between classes - Higher the AUC, better the model is $ \begin{align} True Positive Rate = \frac{TP}{TP + FN} \end{align} $ <br> $ \begin{align} \ False Positive Rate = 1 - \frac{TN}{TN + FP} = \frac{FP}{TN + FP} \end{align} $ ```python from sklearn import metrics fpr, tpr, threshold = metrics.roc_curve(label_test, log_regr.predict(data_test)) roc_auc = metrics.auc(fpr, tpr) print('AUCROC Stage1 vs Healthy: ' , roc_auc) ``` AUCROC Stage1 vs Healthy: 0.8014688532326569 ```python import matplotlib.pyplot as plt plt.title('Receiver Operating Characteristic') plt.plot(fpr, tpr, 'b', label = 'AUC = %0.2f' % roc_auc) plt.legend(loc = 'lower right') plt.plot([0, 1], [0, 1],'r--') plt.xlim([0, 1]) plt.ylim([0, 1]) plt.ylabel('True Positive Rate') plt.xlabel('False Positive Rate') plt.show() ``` A really good material for understanding [AUC-ROC](https://towardsdatascience.com/understanding-auc-roc-curve-68b2303cc9c5) visually ```python ```
The St Nazaire Raid or Operation Chariot was a successful British amphibious attack on the heavily defended Normandie dry dock at St Nazaire in German @-@ occupied France during the Second World War . The operation was undertaken by the Royal Navy and British Commandos under the auspices of Combined Operations Headquarters on 28 March 1942 . St Nazaire was targeted because the loss of its dry dock would force any large German warship in need of repairs , such as the Tirpitz , to return to home waters via either the English Channel or the <unk> gap , both of which were heavily defended by British units including the Royal Navy 's Home Fleet , rather than having a haven available on the Atlantic coast .
module Issue802b where data I : Set where i : I f : I → I f i = i mutual data P : I → Set where p : (x : I) → Q x x → P (f x) Q : I → I → Set Q i = P g : (x y : I) → Q x y → P y g i _ q = q data R : (x : I) → P x → Set where r : (x : I) (q : Q x x) → R _ (g x _ q) → R (f x) (p x q)
[STATEMENT] lemma suicide_aux_l: "\<lbrakk> (\<forall>w\<in>Y. 0\<le>length w); (\<forall>w\<in>X\<^bsup>Suc n\<^esup>. n \<le> length w) \<rbrakk> \<Longrightarrow> (\<forall>w\<in>X\<^bsup>Suc n \<^esup>\<cdot> Y. n \<le> length w)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>\<forall>w\<in>Y. 0 \<le> |w|; \<forall>w\<in>X\<^bsup>Suc n\<^esup>. n \<le> |w|\<rbrakk> \<Longrightarrow> \<forall>w\<in>X\<^bsup>Suc n\<^esup> \<cdot> Y. n \<le> |w| [PROOF STEP] apply (auto simp: l_prod_elim) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>v ua va. \<lbrakk>\<forall>w\<in>X \<cdot> X\<^bsup>n\<^esup>. n \<le> |w|; v \<in> Y; ua \<in> X; va \<in> X\<^bsup>n\<^esup>\<rbrakk> \<Longrightarrow> n \<le> |ua| + (|va| + |v|) [PROOF STEP] apply (drule_tac x="ua @ va" in bspec) [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<And>v ua va. \<lbrakk>v \<in> Y; ua \<in> X; va \<in> X\<^bsup>n\<^esup>\<rbrakk> \<Longrightarrow> ua @ va \<in> X \<cdot> X\<^bsup>n\<^esup> 2. \<And>v ua va. \<lbrakk>v \<in> Y; ua \<in> X; va \<in> X\<^bsup>n\<^esup>; n \<le> |ua @ va|\<rbrakk> \<Longrightarrow> n \<le> |ua| + (|va| + |v|) [PROOF STEP] apply (auto simp add: l_prod_elim) [PROOF STATE] proof (prove) goal: No subgoals! [PROOF STEP] done
[STATEMENT] lemma quotient_of_int [simp]: "quotient_of (of_int n) = (n, 1)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. quotient_of (rat_of_int n) = (n, 1) [PROOF STEP] using Rat.of_int_def quotient_of_int [PROOF STATE] proof (prove) using this: Rat.of_int = rat_of_int quotient_of (Rat.of_int ?a) = (?a, 1) goal (1 subgoal): 1. quotient_of (rat_of_int n) = (n, 1) [PROOF STEP] by auto
Seeking a dedicated individual to conduct rights and clearances for independent documentaries. This position is ideal for IP lawyers, law students or journalists with an interest in film or television, and aspiring entertainment lawyers. Legal experience or special counsel experience & excellent writing skills, good communication skills and contracts know how. Interlock Media, Inc. located in Kendall Square, MA, is an activist film company that points to solutions for environmental, human rights and public health challenges. We support informed policy by producing entertaining documentary and dramatic media works.
import ..prooflab import lectures.lec1_def_lem_thm /-! # Homework 1: ... Homework must be done individually. Replace the placeholders (e.g., `:= sorry`) with your solutions. -/ set_option pp.beta true set_option pp.generalized_field_notation false namespace PROOFS /-! ## Question 1 (10 points): Use the lemma `mul_one` together with `rw` tactic to complete the proof below: -/ #check (mul_one : ∀ (a : ℚ), a * 1 = a) example (x y z : ℚ) (h₁ : x * 1 = y) (h₂ : y = z) : x = z := begin sorry, end /-! ## Question 2 (10 points): Use the tactic `exact` together with the lemma `symm_of_eq`, which we proved in `lec1_def_lem_thm` to complete the following proof. -/ #check symm_of_eq example (x : ℕ) (h : x = 2) : 2 = x := begin sorry, end /-! ## Question 3 (20 points) Use `rw` and the lemma `mul_assoc` to prove the `example` below. -/ #check ( mul_assoc : ∀ (a b c : ℝ), a * b * c = a * (b * c) ) example (a b c : ℝ) : 3 * a * b * c = 3 * a * (b * c) := begin sorry, end /-! ## Question 4 (20 points) Complete the next proof using the following lemma: `sub_self x : x - x = 0` -/ section variable x : ℝ #check sub_self x end -- end of section example (a b c d : ℝ) (h₁ : c = 1 + b * a - d) (h₂ : d = 1 + a * b) : c = 0 := begin rw mul_comm at h₂, rw h₂ at h₁, sorry, end /-! ## Question 5 (20 points) Complete the next proof using lemmas `mul_assoc` and `mul_comm`: -/ #check ( mul_assoc : ∀ (a b c : ℝ), a * b * c = a * (b * c) ) #check ( mul_comm : ∀ (a b : ℝ), a * b = b * a ) example (a b c : ℝ) : (c * b) * a = b * (a * c) := begin sorry, end /-! ## Question 6 (20 points) Next exercises shows that the negation flips the strict order on real numbers. Complete the next proof using lemmas `neg_neg` and `neg_lt`: -/ section variables x y : ℝ #check (neg_neg : ∀ a : ℝ, - -a = a) #check (neg_lt.mpr : -x < y → -y < x) #check (neg_lt : -x < y ↔ -y < x) end /- -/ example {x y : ℝ} (h : x < y) : - y < - x := begin sorry, end end PROOFS
State Before: α : Type u_1 𝕜 : Type u_2 inst✝¹ : Fintype α inst✝ : LinearOrderedField 𝕜 G H : SimpleGraph α ε δ : 𝕜 n : ℕ s : Finset α hε : FarFromTriangleFree G ε h : δ ≤ ε ⊢ δ * ↑(Fintype.card α ^ 2) ≤ ε * ↑(Fintype.card α ^ 2) State After: no goals Tactic: gcongr
State Before: a b c : Int H1 : b ≠ 0 H2 : a = c * b ⊢ a = b * c State After: no goals Tactic: rw [Int.mul_comm, H2]
#!/usr/bin/env python import os import re import numpy as np import pandas as pd import collections import matplotlib.pyplot as plt from sklearn.pipeline import Pipeline from sklearn.pipeline import FeatureUnion from sklearn.preprocessing import LabelEncoder from sklearn.metrics import classification_report as clsr from sklearn.model_selection import train_test_split as tts from sklearn.svm import LinearSVC from sklearn.linear_model import SGDClassifier from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.decomposition import PCA from sklearn.decomposition import TruncatedSVD from sklearn.preprocessing import StandardScaler from nltk.corpus.reader.plaintext import CategorizedPlaintextCorpusReader from feature_extractors import MeasureLexDiv, GetSpeechFeatures, NLTKPreprocessor, GetpreBoundary, GetspeechRate CORPUS = "/ExamplePath/" DOC_PATTERN = r'[A-Z]\d/\w+/.*\.txt' CAT_PATTERN = r'[A-Z]\d/(\w+)/.*\.txt' def identity(arg): """ Simple identity function works as a passthrough. """ return arg def build_and_evaluate(X, y, clf, speech_feats, verbose=True): labels = LabelEncoder() y = labels.fit_transform(y) X_train, X_test, y_train, y_test = tts( X, y, test_size=0.2, random_state=42) model = Pipeline([ ('features', FeatureUnion([ ('word_ngram_tf-idf', Pipeline([ ('preprocessor', NLTKPreprocessor(feats='WordNgram')), ('vectorizer', TfidfVectorizer(tokenizer=identity, preprocessor=None, lowercase=False)), ('best', TruncatedSVD(n_components=50)), ])), ('char_ngram_tf-idf', Pipeline([ ('preprocessor', NLTKPreprocessor(feats='CharNgram')), ('vectorizer', TfidfVectorizer(tokenizer=identity, preprocessor=None, lowercase=False)), ('best', TruncatedSVD(n_components=50)), ])), ('POS-Ngrams', Pipeline([ ('preprocessor', NLTKPreprocessor(feats='PosNgram')), ('vectorizer', TfidfVectorizer(tokenizer=identity, preprocessor=None, lowercase=False)), ('best', TruncatedSVD(n_components=50)), ])), ('PreBoundarySpeech', GetpreBoundary(speech_feats)), ('speechRate', GetspeechRate(speech_feats)), # ('SpeechFeatures', GetSpeechFeatures(speech_feats)), ])), ('Scaler', StandardScaler()), ('classifier', clf)]) #mo.fit(X_train, y_train) X_r = model.fit(X_train).transform(X) pca = model.named_steps['classifier'] print('explained variance ratio (first two components): %s' % str(pca.explained_variance_ratio_)) plt.figure() colors = ['navy', 'turquoise', 'darkorange', 'red', 'green', 'purple'] lw = 2 for color, i, target_name in zip(colors, range(0, 6), labels.classes_): plt.scatter(X_r[y == i, 0], X_r[y == i, 1], color=color, alpha=.8, lw=lw, label=target_name) plt.legend(loc='best', shadow=False, scatterpoints=1) plt.title('PCA of BULATS dataset') plt.show() return model if __name__ == "__main__": PATH = "model.pickle" # Loading speech features speech = pd.read_csv("/ExamplePath.csv") if not os.path.exists(PATH): nli = CategorizedPlaintextCorpusReader(CORPUS, DOC_PATTERN, cat_pattern=CAT_PATTERN) # since `nli` already has all the information (text and ids) # you don't need to iterate over it multiple times so # construct `X` and `y` in one go. X = [] y = [] for fileid in nli.fileids(): X.append({'text': nli.raw(fileid), 'id': fileid.split('/')[-1].split('.')[0]}) y.append(nli.categories(fileid)[0]) clf = PCA(n_components=2) model = build_and_evaluate(X, y, clf, speech)
[STATEMENT] lemma ipurge_tr_rev_aux_first [rule_format]: "ipurge_tr_rev_aux I D U xs = x # ws \<longrightarrow> (\<exists>ys zs. xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v \<in> sources_aux I D U zs. (D x, v) \<in> I))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. ipurge_tr_rev_aux I D U xs = x # ws \<longrightarrow> (\<exists>ys zs. xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I)) [PROOF STEP] proof (induction xs, simp, rule impI) [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>a xs. \<lbrakk>ipurge_tr_rev_aux I D U xs = x # ws \<longrightarrow> (\<exists>ys zs. xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I)); ipurge_tr_rev_aux I D U (a # xs) = x # ws\<rbrakk> \<Longrightarrow> \<exists>ys zs. a # xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) [PROOF STEP] fix x' xs [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>a xs. \<lbrakk>ipurge_tr_rev_aux I D U xs = x # ws \<longrightarrow> (\<exists>ys zs. xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I)); ipurge_tr_rev_aux I D U (a # xs) = x # ws\<rbrakk> \<Longrightarrow> \<exists>ys zs. a # xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) [PROOF STEP] assume A: "ipurge_tr_rev_aux I D U xs = x # ws \<longrightarrow> (\<exists>ys zs. xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v \<in> sources_aux I D U zs. (D x, v) \<in> I))" and B: "ipurge_tr_rev_aux I D U (x' # xs) = x # ws" [PROOF STATE] proof (state) this: ipurge_tr_rev_aux I D U xs = x # ws \<longrightarrow> (\<exists>ys zs. xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I)) ipurge_tr_rev_aux I D U (x' # xs) = x # ws goal (1 subgoal): 1. \<And>a xs. \<lbrakk>ipurge_tr_rev_aux I D U xs = x # ws \<longrightarrow> (\<exists>ys zs. xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I)); ipurge_tr_rev_aux I D U (a # xs) = x # ws\<rbrakk> \<Longrightarrow> \<exists>ys zs. a # xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) [PROOF STEP] show "\<exists>ys zs. x' # xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v \<in> sources_aux I D U zs. (D x, v) \<in> I)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<exists>ys zs. x' # xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) [PROOF STEP] proof (cases "\<exists>v \<in> sources_aux I D U xs. (D x', v) \<in> I") [PROOF STATE] proof (state) goal (2 subgoals): 1. \<exists>v\<in>sources_aux I D U xs. (D x', v) \<in> I \<Longrightarrow> \<exists>ys zs. x' # xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) 2. \<not> (\<exists>v\<in>sources_aux I D U xs. (D x', v) \<in> I) \<Longrightarrow> \<exists>ys zs. x' # xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) [PROOF STEP] case True [PROOF STATE] proof (state) this: \<exists>v\<in>sources_aux I D U xs. (D x', v) \<in> I goal (2 subgoals): 1. \<exists>v\<in>sources_aux I D U xs. (D x', v) \<in> I \<Longrightarrow> \<exists>ys zs. x' # xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) 2. \<not> (\<exists>v\<in>sources_aux I D U xs. (D x', v) \<in> I) \<Longrightarrow> \<exists>ys zs. x' # xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: \<exists>v\<in>sources_aux I D U xs. (D x', v) \<in> I [PROOF STEP] have "x' = x" [PROOF STATE] proof (prove) using this: \<exists>v\<in>sources_aux I D U xs. (D x', v) \<in> I goal (1 subgoal): 1. x' = x [PROOF STEP] using B [PROOF STATE] proof (prove) using this: \<exists>v\<in>sources_aux I D U xs. (D x', v) \<in> I ipurge_tr_rev_aux I D U (x' # xs) = x # ws goal (1 subgoal): 1. x' = x [PROOF STEP] by simp [PROOF STATE] proof (state) this: x' = x goal (2 subgoals): 1. \<exists>v\<in>sources_aux I D U xs. (D x', v) \<in> I \<Longrightarrow> \<exists>ys zs. x' # xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) 2. \<not> (\<exists>v\<in>sources_aux I D U xs. (D x', v) \<in> I) \<Longrightarrow> \<exists>ys zs. x' # xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) [PROOF STEP] with True [PROOF STATE] proof (chain) picking this: \<exists>v\<in>sources_aux I D U xs. (D x', v) \<in> I x' = x [PROOF STEP] have "x' # xs = x # xs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # xs)) [] = [] \<and> (\<exists>v \<in> sources_aux I D U xs. (D x, v) \<in> I)" [PROOF STATE] proof (prove) using this: \<exists>v\<in>sources_aux I D U xs. (D x', v) \<in> I x' = x goal (1 subgoal): 1. x' # xs = x # xs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # xs)) [] = [] \<and> (\<exists>v\<in>sources_aux I D U xs. (D x, v) \<in> I) [PROOF STEP] by simp [PROOF STATE] proof (state) this: x' # xs = x # xs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # xs)) [] = [] \<and> (\<exists>v\<in>sources_aux I D U xs. (D x, v) \<in> I) goal (2 subgoals): 1. \<exists>v\<in>sources_aux I D U xs. (D x', v) \<in> I \<Longrightarrow> \<exists>ys zs. x' # xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) 2. \<not> (\<exists>v\<in>sources_aux I D U xs. (D x', v) \<in> I) \<Longrightarrow> \<exists>ys zs. x' # xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) [PROOF STEP] thus ?thesis [PROOF STATE] proof (prove) using this: x' # xs = x # xs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # xs)) [] = [] \<and> (\<exists>v\<in>sources_aux I D U xs. (D x, v) \<in> I) goal (1 subgoal): 1. \<exists>ys zs. x' # xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) [PROOF STEP] by blast [PROOF STATE] proof (state) this: \<exists>ys zs. x' # xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) goal (1 subgoal): 1. \<not> (\<exists>v\<in>sources_aux I D U xs. (D x', v) \<in> I) \<Longrightarrow> \<exists>ys zs. x' # xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. \<not> (\<exists>v\<in>sources_aux I D U xs. (D x', v) \<in> I) \<Longrightarrow> \<exists>ys zs. x' # xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) [PROOF STEP] case False [PROOF STATE] proof (state) this: \<not> (\<exists>v\<in>sources_aux I D U xs. (D x', v) \<in> I) goal (1 subgoal): 1. \<not> (\<exists>v\<in>sources_aux I D U xs. (D x', v) \<in> I) \<Longrightarrow> \<exists>ys zs. x' # xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) [PROOF STEP] hence "ipurge_tr_rev_aux I D U xs = x # ws" [PROOF STATE] proof (prove) using this: \<not> (\<exists>v\<in>sources_aux I D U xs. (D x', v) \<in> I) goal (1 subgoal): 1. ipurge_tr_rev_aux I D U xs = x # ws [PROOF STEP] using B [PROOF STATE] proof (prove) using this: \<not> (\<exists>v\<in>sources_aux I D U xs. (D x', v) \<in> I) ipurge_tr_rev_aux I D U (x' # xs) = x # ws goal (1 subgoal): 1. ipurge_tr_rev_aux I D U xs = x # ws [PROOF STEP] by simp [PROOF STATE] proof (state) this: ipurge_tr_rev_aux I D U xs = x # ws goal (1 subgoal): 1. \<not> (\<exists>v\<in>sources_aux I D U xs. (D x', v) \<in> I) \<Longrightarrow> \<exists>ys zs. x' # xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) [PROOF STEP] with A [PROOF STATE] proof (chain) picking this: ipurge_tr_rev_aux I D U xs = x # ws \<longrightarrow> (\<exists>ys zs. xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I)) ipurge_tr_rev_aux I D U xs = x # ws [PROOF STEP] have "\<exists>ys zs. xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v \<in> sources_aux I D U zs. (D x, v) \<in> I)" [PROOF STATE] proof (prove) using this: ipurge_tr_rev_aux I D U xs = x # ws \<longrightarrow> (\<exists>ys zs. xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I)) ipurge_tr_rev_aux I D U xs = x # ws goal (1 subgoal): 1. \<exists>ys zs. xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) [PROOF STEP] .. [PROOF STATE] proof (state) this: \<exists>ys zs. xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) goal (1 subgoal): 1. \<not> (\<exists>v\<in>sources_aux I D U xs. (D x', v) \<in> I) \<Longrightarrow> \<exists>ys zs. x' # xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: \<exists>ys zs. xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) [PROOF STEP] obtain ys and zs where xs: "xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v \<in> sources_aux I D U zs. (D x, v) \<in> I)" [PROOF STATE] proof (prove) using this: \<exists>ys zs. xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) goal (1 subgoal): 1. (\<And>ys zs. xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by blast [PROOF STATE] proof (state) this: xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) goal (1 subgoal): 1. \<not> (\<exists>v\<in>sources_aux I D U xs. (D x', v) \<in> I) \<Longrightarrow> \<exists>ys zs. x' # xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) [PROOF STEP] have "\<not> (\<exists>v \<in> sources_aux I D (sources_aux I D U (x # zs)) ys. (D x', v) \<in> I)" [PROOF STATE] proof (prove) using this: xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) goal (1 subgoal): 1. \<not> (\<exists>v\<in>sources_aux I D (sources_aux I D U (x # zs)) ys. (D x', v) \<in> I) [PROOF STEP] using False [PROOF STATE] proof (prove) using this: xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) \<not> (\<exists>v\<in>sources_aux I D U xs. (D x', v) \<in> I) goal (1 subgoal): 1. \<not> (\<exists>v\<in>sources_aux I D (sources_aux I D U (x # zs)) ys. (D x', v) \<in> I) [PROOF STEP] by (simp add: sources_aux_append) [PROOF STATE] proof (state) this: \<not> (\<exists>v\<in>sources_aux I D (sources_aux I D U (x # zs)) ys. (D x', v) \<in> I) goal (1 subgoal): 1. \<not> (\<exists>v\<in>sources_aux I D U xs. (D x', v) \<in> I) \<Longrightarrow> \<exists>ys zs. x' # xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) [PROOF STEP] hence "ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) (x' # ys) = ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys" [PROOF STATE] proof (prove) using this: \<not> (\<exists>v\<in>sources_aux I D (sources_aux I D U (x # zs)) ys. (D x', v) \<in> I) goal (1 subgoal): 1. ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) (x' # ys) = ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys [PROOF STEP] by simp [PROOF STATE] proof (state) this: ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) (x' # ys) = ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys goal (1 subgoal): 1. \<not> (\<exists>v\<in>sources_aux I D U xs. (D x', v) \<in> I) \<Longrightarrow> \<exists>ys zs. x' # xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) [PROOF STEP] with xs [PROOF STATE] proof (chain) picking this: xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) (x' # ys) = ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys [PROOF STEP] have "x' # xs = (x' # ys) @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) (x' # ys) = [] \<and> (\<exists>v \<in> sources_aux I D U zs. (D x, v) \<in> I)" [PROOF STATE] proof (prove) using this: xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) (x' # ys) = ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys goal (1 subgoal): 1. x' # xs = (x' # ys) @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) (x' # ys) = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) [PROOF STEP] by (simp del: sources_aux.simps) [PROOF STATE] proof (state) this: x' # xs = (x' # ys) @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) (x' # ys) = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) goal (1 subgoal): 1. \<not> (\<exists>v\<in>sources_aux I D U xs. (D x', v) \<in> I) \<Longrightarrow> \<exists>ys zs. x' # xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) [PROOF STEP] thus ?thesis [PROOF STATE] proof (prove) using this: x' # xs = (x' # ys) @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) (x' # ys) = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) goal (1 subgoal): 1. \<exists>ys zs. x' # xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) [PROOF STEP] by blast [PROOF STATE] proof (state) this: \<exists>ys zs. x' # xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: \<exists>ys zs. x' # xs = ys @ x # zs \<and> ipurge_tr_rev_aux I D (sources_aux I D U (x # zs)) ys = [] \<and> (\<exists>v\<in>sources_aux I D U zs. (D x, v) \<in> I) goal: No subgoals! [PROOF STEP] qed
[STATEMENT] lemma DBM_reset_sound'': fixes M v c n d defines "M' \<equiv> reset M n (v c) d" assumes "clock_numbering' v n" "v c \<le> n" "DBM_val_bounded v u M' n" "DBM_val_bounded v u'' M n" obtains d' where "DBM_val_bounded v (u(c := d')) M n" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<And>d'. u(c := d') \<turnstile>\<^bsub>v,n\<^esub> M \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. (\<And>d'. u(c := d') \<turnstile>\<^bsub>v,n\<^esub> M \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] assume A:"\<And>d'. DBM_val_bounded v (u(c := d')) M n \<Longrightarrow> thesis" [PROOF STATE] proof (state) this: u(c := ?d') \<turnstile>\<^bsub>v,n\<^esub> M \<Longrightarrow> thesis goal (1 subgoal): 1. (\<And>d'. u(c := d') \<turnstile>\<^bsub>v,n\<^esub> M \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] from assms DBM_reset_reset[of "v c" n M d] [PROOF STATE] proof (chain) picking this: M' \<equiv> reset M n (v c) d \<forall>c. 0 < v c \<and> (\<forall>x y. v x \<le> n \<and> v y \<le> n \<and> v x = v y \<longrightarrow> x = y) v c \<le> n u \<turnstile>\<^bsub>v,n\<^esub> M' u'' \<turnstile>\<^bsub>v,n\<^esub> M \<lbrakk>0 < v c; v c \<le> n\<rbrakk> \<Longrightarrow> DBM_reset M n (v c) d (reset M n (v c) d) [PROOF STEP] have *:"DBM_reset M n (v c) d M'" [PROOF STATE] proof (prove) using this: M' \<equiv> reset M n (v c) d \<forall>c. 0 < v c \<and> (\<forall>x y. v x \<le> n \<and> v y \<le> n \<and> v x = v y \<longrightarrow> x = y) v c \<le> n u \<turnstile>\<^bsub>v,n\<^esub> M' u'' \<turnstile>\<^bsub>v,n\<^esub> M \<lbrakk>0 < v c; v c \<le> n\<rbrakk> \<Longrightarrow> DBM_reset M n (v c) d (reset M n (v c) d) goal (1 subgoal): 1. DBM_reset M n (v c) d M' [PROOF STEP] by (auto simp add: M'_def) [PROOF STATE] proof (state) this: DBM_reset M n (v c) d M' goal (1 subgoal): 1. (\<And>d'. u(c := d') \<turnstile>\<^bsub>v,n\<^esub> M \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] with DBM_reset_sound'[of v n c M d M', OF _ _ this] assms [PROOF STATE] proof (chain) picking this: \<lbrakk>\<forall>c. 0 < v c \<and> (\<forall>x y. v x \<le> n \<and> v y \<le> n \<and> v x = v y \<longrightarrow> x = y); v c \<le> n; ?u \<turnstile>\<^bsub>v,n\<^esub> M'; ?u'' \<turnstile>\<^bsub>v,n\<^esub> M; \<And>d'. ?u(c := d') \<turnstile>\<^bsub>v,n\<^esub> M \<Longrightarrow> ?thesis\<rbrakk> \<Longrightarrow> ?thesis M' \<equiv> reset M n (v c) d \<forall>c. 0 < v c \<and> (\<forall>x y. v x \<le> n \<and> v y \<le> n \<and> v x = v y \<longrightarrow> x = y) v c \<le> n u \<turnstile>\<^bsub>v,n\<^esub> M' u'' \<turnstile>\<^bsub>v,n\<^esub> M DBM_reset M n (v c) d M' [PROOF STEP] obtain d' where "DBM_val_bounded v (u(c := d')) M n" [PROOF STATE] proof (prove) using this: \<lbrakk>\<forall>c. 0 < v c \<and> (\<forall>x y. v x \<le> n \<and> v y \<le> n \<and> v x = v y \<longrightarrow> x = y); v c \<le> n; ?u \<turnstile>\<^bsub>v,n\<^esub> M'; ?u'' \<turnstile>\<^bsub>v,n\<^esub> M; \<And>d'. ?u(c := d') \<turnstile>\<^bsub>v,n\<^esub> M \<Longrightarrow> ?thesis\<rbrakk> \<Longrightarrow> ?thesis M' \<equiv> reset M n (v c) d \<forall>c. 0 < v c \<and> (\<forall>x y. v x \<le> n \<and> v y \<le> n \<and> v x = v y \<longrightarrow> x = y) v c \<le> n u \<turnstile>\<^bsub>v,n\<^esub> M' u'' \<turnstile>\<^bsub>v,n\<^esub> M DBM_reset M n (v c) d M' goal (1 subgoal): 1. (\<And>d'. u(c := d') \<turnstile>\<^bsub>v,n\<^esub> M \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by auto [PROOF STATE] proof (state) this: u(c := d') \<turnstile>\<^bsub>v,n\<^esub> M goal (1 subgoal): 1. (\<And>d'. u(c := d') \<turnstile>\<^bsub>v,n\<^esub> M \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] with A [PROOF STATE] proof (chain) picking this: u(c := ?d') \<turnstile>\<^bsub>v,n\<^esub> M \<Longrightarrow> thesis u(c := d') \<turnstile>\<^bsub>v,n\<^esub> M [PROOF STEP] show thesis [PROOF STATE] proof (prove) using this: u(c := ?d') \<turnstile>\<^bsub>v,n\<^esub> M \<Longrightarrow> thesis u(c := d') \<turnstile>\<^bsub>v,n\<^esub> M goal (1 subgoal): 1. thesis [PROOF STEP] by auto [PROOF STATE] proof (state) this: thesis goal: No subgoals! [PROOF STEP] qed
""" ExtensionDifferentialOperator(x̄, method::DiscretizationMethod) Returns a discretized differential operator of `length(interiornodes(x̄))` by `length(x̄)` matrix under no boundary condition using a discretization method specified by `method`. # Examples ```jldoctest; setup = :(using SimpleDifferentialOperators) julia> x̄ = 0:5 0:5 julia> ExtensionDifferentialOperator(x̄, BackwardFirstDifference()) 4×6 SparseArrays.SparseMatrixCSC{Float64,Int64} with 8 stored entries: [1, 1] = -1.0 [1, 2] = 1.0 [2, 2] = -1.0 [2, 3] = 1.0 [3, 3] = -1.0 [3, 4] = 1.0 [4, 4] = -1.0 [4, 5] = 1.0 julia> ExtensionDifferentialOperator(x̄, ForwardFirstDifference()) 4×6 SparseArrays.SparseMatrixCSC{Float64,Int64} with 8 stored entries: [1, 2] = -1.0 [1, 3] = 1.0 [2, 3] = -1.0 [2, 4] = 1.0 [3, 4] = -1.0 [3, 5] = 1.0 [4, 5] = -1.0 [4, 6] = 1.0 julia> ExtensionDifferentialOperator(x̄, CentralSecondDifference()) 4×6 SparseArrays.SparseMatrixCSC{Float64,Int64} with 12 stored entries: [1, 1] = 1.0 [1, 2] = -2.0 [2, 2] = 1.0 [1, 3] = 1.0 [2, 3] = -2.0 [3, 3] = 1.0 [2, 4] = 1.0 [3, 4] = -2.0 [4, 4] = 1.0 [3, 5] = 1.0 [4, 5] = -2.0 [4, 6] = 1.0 julia> ExtensionDifferentialOperator(x̄, JumpProcess(x̄, -1.0)) 4×6 BandedMatrices.BandedMatrix{Float64,Array{Float64,2},Base.OneTo{Int64}}: 0.0 0.0 ⋅ ⋅ ⋅ ⋅ ⋅ 1.0 -1.0 ⋅ ⋅ ⋅ ⋅ ⋅ 1.0 -1.0 ⋅ ⋅ ⋅ ⋅ ⋅ 1.0 -1.0 ⋅ ``` """ function ExtensionDifferentialOperator(x̄::AbstractRange, method::BackwardFirstDifference) T = eltype(x̄) M = length(x̄) - 2 Δ = step(x̄) return spdiagm(0 => -ones(T, M), 1 => ones(T, M), 2 => zeros(T, M))[1:M,:] / Δ end function ExtensionDifferentialOperator(x̄::AbstractRange, method::ForwardFirstDifference) T = eltype(x̄) M = length(x̄) - 2 Δ = step(x̄) return spdiagm(0 => zeros(T, M), 1 => -ones(T, M), 2 => ones(T, M))[1:M,:] / Δ end function ExtensionDifferentialOperator(x̄::AbstractRange, method::CentralSecondDifference) T = eltype(x̄) M = length(x̄) - 2 Δ = step(x̄) return spdiagm(0 => ones(T, M), 1 => -2*ones(T, M), 2 => ones(T, M))[1:M,:] / Δ^2 end function ExtensionDifferentialOperator(x̄::AbstractArray, method::BackwardFirstDifference) T = eltype(x̄) M = length(x̄) - 2 d = diff(x̄) Δ₋⁻¹ = 1 ./ d[1:end-1] return spdiagm(0 => -Δ₋⁻¹, 1 => Δ₋⁻¹, 2 => zeros(T, M))[1:M,:] end function ExtensionDifferentialOperator(x̄::AbstractArray, method::ForwardFirstDifference) T = eltype(x̄) M = length(x̄) - 2 d = diff(x̄) Δ₊⁻¹ = 1 ./ d[2:end] return spdiagm(0 => zeros(T, M), 1 => -Δ₊⁻¹, 2 => Δ₊⁻¹)[1:M,:] end function ExtensionDifferentialOperator(x̄::AbstractArray, method::CentralSecondDifference) T = eltype(x̄) M = length(x̄) - 2 d = diff(x̄) Δ₋⁻¹ = 1 ./ d[1:end-1] # 1 ./ Δ₋ Δ₊⁻¹ = 1 ./ d[2:end] # 1 ./ Δ₊ Δ⁻¹ = 1 ./ (d[1:end-1] + d[2:end]) # 1 ./ (Δ₋ + Δ₊) return 2*spdiagm(0 => Δ⁻¹.*Δ₋⁻¹, 1 => -Δ₋⁻¹ .* Δ₊⁻¹, 2 => Δ⁻¹.*Δ₊⁻¹)[1:M,:] end function ExtensionDifferentialOperator(x̄::AbstractArray, method::JumpProcess) T = eltype(x̄) M = length(x̄) - 2 jumps = method.jumps L̄ = BandedMatrix((0=>zeros(M), 1=>-ones(M)), (M,M+2), (max(abs(minimum(jumps))-1, 0), max(abs(maximum(jumps)+1), 1))) for i in 1:length(jumps) L̄[i,(i+1+jumps[i])] += 1 end return (L̄) end
"""Test normalizing gesture recording data.""" import os import numpy as np from iotai_sensor_classification.recording import read_recordings from iotai_sensor_classification.normalization import normalize_mean_std_dict from data.gestures import linear_accelerometer from iotai_sensor_classification.plot_util import column_histograms, plot_columns, \ plot_lines, histogram_overlay SAMPLES_PER_RECORDING = 160 def test_normalize_gesture_data(): recordings_dir = os.path.dirname(linear_accelerometer.__file__) raw_gestures = read_recordings(recordings_dir=recordings_dir) normalized_gestures = normalize_mean_std_dict(raw_gestures) test_output = os.path.join("test_output", "gestures", "normalized") os.makedirs(test_output, exist_ok=True) for gesture in normalized_gestures.keys(): normalized = normalized_gestures[gesture] column_histograms(normalized, name=f"{gesture} gesture normalized", filepath=os.path.join(test_output, f"{gesture}-norm-histograms.png")) plot_columns(normalized, name=f"{gesture} gesture normalized", filepath=os.path.join(test_output, f"{gesture}-norm-plots.png")) motion_measures = normalized.drop(columns=['time', 'label']) plot_lines(motion_measures, name=f"{gesture} normalized measurements", filepath=os.path.join(test_output, f"{gesture}-norm-lines.png")) plot_lines(motion_measures, name=f"{gesture} normalized window={SAMPLES_PER_RECORDING}", filepath=os.path.join(test_output, f"{gesture}-norm-lines-window{SAMPLES_PER_RECORDING}.png"), vertical_tick_spacing=SAMPLES_PER_RECORDING) histogram_overlay(motion_measures, name=f"{gesture} normalized measurements", filepath=os.path.join(test_output, f"{gesture}-norm-over-hist.png")) # https://numpy.org/doc/stable/reference/generated/numpy.allclose.html assert np.allclose(normalized.mean(), 0.0) assert np.allclose(normalized.std(), 1.0)
function build_indvar_dict(ex,depvar) indvar_dict = OrderedDict{Symbol,Int}() cur_sym = 0 for i in 2:2:length(ex.args) #Every odd line is line number arg = ex.args[i].args[1] #Get the first thing, should be dsomething firstarg = Symbol(first(string(arg))) # Check for d if firstarg == :d nodarg = Symbol(join(Base.Iterators.drop(string(arg), 1))) if nodarg == depvar warn("$depvar is fixed as the independent variable but is also used as a dependent variable. Results my be incorrect.") end if !haskey(indvar_dict,nodarg) cur_sym += 1 indvar_dict[nodarg] = cur_sym else error("The derivative term for $nodarg is repeated. This is not allowed.") end end end syms = indvar_dict.keys indvar_dict,syms end function build_param_list(params) param_list = Vector{Symbol}(); for i in 1:length(params) if typeof(params[i]) <: Symbol push!(param_list,params[i]) elseif params[i].head == :call || params[i].head == :(=) warn("p=>val and p=val are deprecated. Simply list the parameters. See the DifferentialEquations.jl documentation for more information on the syntax change.") end end param_dict end
import data.real.basic tactic.ring example (a b l m : ℝ) : abs(a + (b + (-l - m))) = abs(a + (-l + (b - m))) := -- by ring -- I think this used to work but now it doesn't by congr' 1; ring
import data.fin.basic import data.fintype.basic import data.list import ..automata_typeclass variables {Sigma : Type} [decidable_eq Sigma] def lit_lang (x : Sigma) : lang Sigma := λ w, w = x :: [] def single_ε_nfa {Sigma : Type*} [decidable_eq Sigma] (lit : Sigma) : ε_nfa Sigma := { Q := fin 2, finQ := by apply_instance, decQ := by apply_instance, inits := λ x , x.val = 0, decI := by apply_instance, final := λ x , x.val = 1, decF := by apply_instance, δ := λ q0 x q1 , q0.val = 0 ∧ x = lit ∧ q1.val = 1, decD := begin assume x, dsimp [sigma.uncurry], apply_instance, end } lemma single_ε_nfa_lang : ∀ x : Sigma, ∀ w : word Sigma, ε_nfa_lang (single_ε_nfa x) w ↔ lit_lang x w := begin assume x w, dsimp [ε_nfa_lang, lit_lang], constructor, { assume h, cases h with q0 h, cases h with q1 h, cases (and.elim_left (and.elim_right h)), { cases h with h1 h, cases h with h2 h3, have z : q0.val = 0, exact h1, have f : false, have o : q0.val = 1, exact h3, finish, cases f, }, { cases ᾰ with a b, cases b with b c, cases b, have t: w_1 = [], { cases ᾰ_1, refl, cases ᾰ_1_ᾰ, have f : false, rw c at ᾰ_1_ᾰ_left, injection ᾰ_1_ᾰ_left, cases f, cases ᾰ_1_ᾰ, cases (and.elim_left ᾰ_1_ᾰ_right), }, solve_by_elim, }, { cases ᾰ, cases and.elim_left ᾰ_right, } }, { assume h, let z : fin 2, exact 0, let o : fin 2, exact 1, existsi z, existsi o, constructor, solve_by_elim, constructor, dsimp [single_ε_nfa], rw h, fconstructor, exact o, finish, constructor, solve_by_elim, } end
Formal statement is: lemma pred_less_const[measurable (raw generic)]: assumes f: "f \<in> measurable M N" and c: "{..< c} \<in> sets N" shows "pred M (\<lambda>x. f x < c)" Informal statement is: If $f$ is a measurable function from $M$ to $N$ and $c$ is a constant such that the set $\{x \in N \mid x < c\}$ is measurable, then the set $\{x \in M \mid f(x) < c\}$ is measurable.
#include "moja/flint/configuration/operationmanager.h" #include <boost/algorithm/string.hpp> namespace moja { namespace flint { namespace configuration { OperationManager::OperationManager() : _name("Simple") {} OperationManager::OperationManager(const std::string& name, DynamicObject& settings) : _name(name), _settings(settings) { if (name.length() == 0 || all(name, boost::algorithm::is_space())) { _name = "Simple"; } } } // namespace configuration } // namespace flint } // namespace moja
[GOAL] R : Type u_1 inst✝¹ : EuclideanDomain R inst✝ : GCDMonoid R p✝ q✝ p q : R hp : p ≠ 0 ⊢ p / GCDMonoid.gcd p q ≠ 0 [PROOFSTEP] obtain ⟨r, hr⟩ := GCDMonoid.gcd_dvd_left p q [GOAL] case intro R : Type u_1 inst✝¹ : EuclideanDomain R inst✝ : GCDMonoid R p✝ q✝ p q : R hp : p ≠ 0 r : R hr : p = GCDMonoid.gcd p q * r ⊢ p / GCDMonoid.gcd p q ≠ 0 [PROOFSTEP] obtain ⟨pq0, r0⟩ : GCDMonoid.gcd p q ≠ 0 ∧ r ≠ 0 := mul_ne_zero_iff.mp (hr ▸ hp) [GOAL] case intro.intro R : Type u_1 inst✝¹ : EuclideanDomain R inst✝ : GCDMonoid R p✝ q✝ p q : R hp : p ≠ 0 r : R hr : p = GCDMonoid.gcd p q * r pq0 : GCDMonoid.gcd p q ≠ 0 r0 : r ≠ 0 ⊢ p / GCDMonoid.gcd p q ≠ 0 [PROOFSTEP] nth_rw 1 [hr] [GOAL] case intro.intro R : Type u_1 inst✝¹ : EuclideanDomain R inst✝ : GCDMonoid R p✝ q✝ p q : R hp : p ≠ 0 r : R hr : p = GCDMonoid.gcd p q * r pq0 : GCDMonoid.gcd p q ≠ 0 r0 : r ≠ 0 ⊢ GCDMonoid.gcd p q * r / GCDMonoid.gcd p q ≠ 0 [PROOFSTEP] rw [mul_comm, EuclideanDomain.mul_div_cancel _ pq0] [GOAL] case intro.intro R : Type u_1 inst✝¹ : EuclideanDomain R inst✝ : GCDMonoid R p✝ q✝ p q : R hp : p ≠ 0 r : R hr : p = GCDMonoid.gcd p q * r pq0 : GCDMonoid.gcd p q ≠ 0 r0 : r ≠ 0 ⊢ r ≠ 0 [PROOFSTEP] exact r0 [GOAL] R : Type u_1 inst✝¹ : EuclideanDomain R inst✝ : GCDMonoid R p✝ q✝ p q : R hq : q ≠ 0 ⊢ q / GCDMonoid.gcd p q ≠ 0 [PROOFSTEP] obtain ⟨r, hr⟩ := GCDMonoid.gcd_dvd_right p q [GOAL] case intro R : Type u_1 inst✝¹ : EuclideanDomain R inst✝ : GCDMonoid R p✝ q✝ p q : R hq : q ≠ 0 r : R hr : q = GCDMonoid.gcd p q * r ⊢ q / GCDMonoid.gcd p q ≠ 0 [PROOFSTEP] obtain ⟨pq0, r0⟩ : GCDMonoid.gcd p q ≠ 0 ∧ r ≠ 0 := mul_ne_zero_iff.mp (hr ▸ hq) [GOAL] case intro.intro R : Type u_1 inst✝¹ : EuclideanDomain R inst✝ : GCDMonoid R p✝ q✝ p q : R hq : q ≠ 0 r : R hr : q = GCDMonoid.gcd p q * r pq0 : GCDMonoid.gcd p q ≠ 0 r0 : r ≠ 0 ⊢ q / GCDMonoid.gcd p q ≠ 0 [PROOFSTEP] nth_rw 1 [hr] [GOAL] case intro.intro R : Type u_1 inst✝¹ : EuclideanDomain R inst✝ : GCDMonoid R p✝ q✝ p q : R hq : q ≠ 0 r : R hr : q = GCDMonoid.gcd p q * r pq0 : GCDMonoid.gcd p q ≠ 0 r0 : r ≠ 0 ⊢ GCDMonoid.gcd p q * r / GCDMonoid.gcd p q ≠ 0 [PROOFSTEP] rw [mul_comm, EuclideanDomain.mul_div_cancel _ pq0] [GOAL] case intro.intro R : Type u_1 inst✝¹ : EuclideanDomain R inst✝ : GCDMonoid R p✝ q✝ p q : R hq : q ≠ 0 r : R hr : q = GCDMonoid.gcd p q * r pq0 : GCDMonoid.gcd p q ≠ 0 r0 : r ≠ 0 ⊢ r ≠ 0 [PROOFSTEP] exact r0 [GOAL] R : Type ?u.6736 inst✝¹ : EuclideanDomain R inst✝ : DecidableEq R a b : R ⊢ Associated (gcd a b * lcm a b) (a * b) [PROOFSTEP] rw [EuclideanDomain.gcd_mul_lcm]
\documentclass[12pt, twocolumn]{aastex62} % The geometry package allows for easy page formatting. \usepackage{geometry} \geometry{letterpaper} % Load up special logo commands. \usepackage{doc} % Package for formatting URLs. \usepackage{url} % Packages and definitions for graphics files. \usepackage{graphicx} % for managing images %% Tells LaTeX to search for image files in the %% current directory as well as in the figures/ folder. \graphicspath{{./}{figures/}} %\renewcommand{\arraystretch}{1.4} % The height of each row is set to 1.5 relative to its default height. \usepackage{wrapfig} % wrapping text around images \usepackage{epstopdf} \DeclareGraphicsRule{.tif}{png}{.png}{`convert #1 `dirname #1`/`basename #1 .tif`.png} %math packages \usepackage{braket} \usepackage{bbold} \usepackage{amsmath, amsfonts, amsthm} \usepackage{amssymb} \usepackage{pgfplots} %% Command to document which AAS Journal the manuscript was submitted to. %% Adds "Submitted to " the arguement. \submitjournal{ApJ} % % Set the title, author, and date. % \title{Distance and Ages of Star Clusters} \author{Karoki Anthony Mugambi} \date{} % % The document proper. % \begin{document} \onecolumn % Add the title section. \maketitle % Add an abstract. \begin{abstract} Study of star clusters. Using data to show how clusters can be used to measure the relative distances and ages of stars in the cluster. Using optical and infrared data to generate a CMD plotting. In this exercise, you will determine the colour of many cluster members and plot them on a Colour-Magnitude diagram. This is just a type of Hertzsprung-Russell (HR) diagram in which we plot Colour Index rather than Spectral Class on the horizontal axis; and use the apparent visual magnitude, V, for the vertical axis. \end{abstract} % Add various lists on new pages. %\pagebreak \tableofcontents %\pagebreak %\listoffigures %\pagebreak %\listoftables % Start the paper on a new page. \pagebreak %\twocolumn % % Body text. % \section{General Introduction on Star Clusters} \label{introduction} Most stars in the universe form in clusters. By fact that the star clusters are formed from a common gas cloud, they thus have similar age and common distance. The common age and distance makes stellar clusters particularly important in studies of stellar ages and luminosities.\\ Photometric measurements can be used to determine the age of a cluster and its distance. \subsection{Open Cluster} Open clusters are diffuse star clusters hosting a few hundreds or thousands of stars. \subsection{Globular Cluster} Globular clusters are very dense, hosting millions of stars in the space of only a few parsecs. \section{Background, Preliminary, and Related Work} \subsection{Messier 7 Open Cluster} \textbf{M7} also goes by the designations \textbf{NGC 6475} and \textbf{Ptolemy's Cluster}. M7 was known as early as the year 130 CE when it was mentioned by Ptolemy. It si a large bright star cluster visible to the naked eye in the constellation Scorpius.\\ It is part of the Milky Way galaxy. \subsection{Messier 54 Globular Cluster} \textbf{M54} also goes by the designation \textbf{NGC 6715}. It is a compact globular cluster.\\ It was the first extragalactic cluster ever discovered and is recognized as part of the Sagittarius Dwarf Galaxy (SDG). It is located in the constellation Sagittarius. %Perhaps the most important functionality to learn for the paper is \LaTeX\ bibliography support. Citations and references are handled automatically by \LaTeX\ through its companion program, \BibTeX. All you have to do is provide a bibliography file that provides the reference information and internal keys (very much like variable names) that you use in your document.\footnote{And always remember to run \LaTeX\ \emph{at least twice} after running \BibTeX.} %\BibTeX\ supports virtually all kinds of references, including books \cite{dui,sgg,iokit,palmos}, parts of books \cite{userModeLinux}, articles \cite{nielsen:dui-review,heer-shneiderman,stackableThreads,xpkernel}, and conference proceedings \cite{ux-3d,iring,contextFileSearch,osHaskell,hibernator}, to name a few. If not already included in your \LaTeX\ distribution, download and install the \texttt{url} package to support formatting of URLs; you can usually mention these in the \emph{note} or \emph{howpublished} fields of your \BibTeX\ file. %Like Section~\ref{introduction}, a background, preliminary, and related work section is also almost certainly needed for your paper. In this section, describe any history, work, or projects that serve as direct contributors to the subject of your research paper. Look at other papers in the literature to see how they organized, presented, and discussed prior work. %The Shneiderman/Plaisant text \cite{dui} provide some pointers to seminal or key works; because they made it into the textbook they aren't necessarily ``bleeding edge,'' but they likely provide the foundation for your chosen subject matter. %\section{Main Content Sections} %The outline after the introductory and background, preliminary, and related work sections is more dependent on the specific subject of your research. Remember to cite references where appropriate, organize the material so that it flows well and is clear to the reader. %\subsection{Multiple Outline Levels} %\LaTeX\ has support for up to three outline levels (\verb!\section!, \verb!\subsection!, and \verb!\subsubsection!). It also recognizes \verb!\paragraph! and \verb!\subparagraph! directives, though those don't show up in the table of contents. All of these directives expect a title. %Note also the use of the \verb!\verb! directive for inserting code-like labels or symbols. It was particularly needed here so that we can include the backslash character in the text. %\subsection{Tables and Figures} %\LaTeX\ has full support for tables and figures. Table~\ref{table-sample} shows a sample table and Figure~\ref{figure-sample} shows a sample figure. Note the built-in support for captions and the automated numbering functionality. Lists of tables and figures can also be automatically generated, as seen at the beginning of this document. % \begin{table} % \centering % \begin{tabular}{|c|c|c|}\hline % Column 1 & Column 2 & Column 3 \\\hline\hline % a & b & c \\ % d & e & f \\ % g & h & i \\\hline % \end{tabular} % % \caption{A sample table} % \label{table-sample} % \end{table} % % \begin{figure} % \centering % %\includegraphics[width=2in]{space.jpg} % % \caption{A sample figure} % \label{figure-sample} % \end{figure} %One very important thing to remember about how \LaTeX\ handles tables and figures by default: you don't have to worry about where they go exactly. The general rule is that you insert them in the source after your first reference to them, and \LaTeX\ determines their final position. It also makes decisions on how much page space to devote to them. This all follows \LaTeX's overall theme of focusing on the content of your paper, and not its format. %Just so you can see a second table, Table~\ref{table-sample2} is provided. % \begin{table} % \centering % \begin{tabular}{|c|c|c|}\hline % Column 1 & Column 2 & Column 3 \\\hline\hline % a & b & c \\ % d & e & f \\ % g & h & i \\\hline % \end{tabular} % % \caption{Another sample table} % \label{table-sample2} % \end{table} %\section{Another Section} %We're adding another section just so you can see how that looks. Plus there are a few more \LaTeX\ features to illustrate. %\subsection{Bulleted and Numbered Lists} % \LaTeX\ is very good at providing clean lists. Examples are shown below. % \begin{itemize} % \item Bulleted items come out properly indented and spaced, every time. % % \begin{itemize} % \item Sub-bullets are a virtual no-brainer: just nest another \verb!itemize! block. % \item Note how the bullet character automatically changes too. % \end{itemize} % % \item Just keep on adding \verb!\item!s\ldots % % \item \ldots until you're done. % \end{itemize} % % Numbered lists are almost identical, except that you specify \verb!enumerate! instead of \verb!itemize!. List items are specified in exactly the same way (thus making it easy to change list types). % % \begin{enumerate} % \item A list item % \item Another list item % \item A list item with multiple nested lists % % \begin{itemize} % \item Nested lists can be of mixed types. % \item That's a lot of power and flexibility for the price of learning a handful of directives. % % \begin{enumerate} % \item Like nested bullet lists, nested numbered lists also ``intelligently'' change their numbering schemes. % \item Meanwhile, all \emph{you} have to write is \verb!\item!. \LaTeX\ does the rest. % \end{enumerate} % \end{itemize} % % \item Back to your regularly scheduled list item % % \end{enumerate} % % \subsection{Subsection with Another Figure} % % We may as well include a second figure also, shown in Figure~\ref{figure-sample2}. The same image file is used, but note how it can be resized. Again, observe how the positions of the tables and figures do not necessarily match their positions in the source file, reiterating the aforementioned \LaTeX\ functionality for deciding where these items go in the final document. You provide an approximate location, and \LaTeX\ does the rest. % % \begin{figure} % \centering % %\includegraphics[width=1in]{space.jpg} % % \caption{Another sample figure} % \label{figure-sample2} % \end{figure} \section{Analysis and Results} \section{Conclusion} % Wrap up your paper with an ``executive summary'' of the paper itself, reiterating its subject and its major points. If you want examples, just look at the conclusions from the literature. % Generate the bibliography. \bibliography{latex-sample} \bibliographystyle{unsrt} \end{document}
import data.fintype.basic import data.int.interval def mod_two (a : ℤ) : bool := a % 2 = 1 structure propagate_struc (arity : Type) : Type 1 := ( init_carry : ℤ ) ( max_carry : ℤ ) ( min_carry : ℤ ) ( carry : (arity → bool) → bool → ℤ ) ( carry_le : ∀ x b, carry x b ≤ max_carry ) ( le_carry : ∀ x b, min_carry ≤ carry x b ) ( init_carry_le : init_carry ≤ max_carry ) ( le_init_carry : min_carry ≤ init_carry ) ( output : (arity → bool) → bool → bool ) variables {arity : Type} (p : propagate_struc arity) {p₁ p₂ : propagate_struc arity} namespace propagate_struc def next_carry (x : arity → bool) (c : ℤ) : ℤ := (c + p.carry x (mod_two c)) / 2 @[simp] def nth_carry (x : ℕ → arity → bool) : ℕ → ℤ | 0 := p.init_carry | (n+1) := next_carry p (x n) (nth_carry n) lemma nth_carry_le (x : ℕ → arity → bool) (n : ℕ) : p.nth_carry x n ≤ p.max_carry := begin induction n with n ih, { exact p.init_carry_le }, { have h₁ : p.nth_carry x n ≤ p.max_carry, { exact ih }, have h₂ : p.carry (x n) (mod_two (p.nth_carry x n)) ≤ p.max_carry, { exact p.carry_le (x n) (mod_two (p.nth_carry x n)) }, have h₃ : p.nth_carry x n + p.carry (x n) (mod_two (p.nth_carry x n)) ≤ p.max_carry + p.max_carry, { exact add_le_add h₁ h₂ }, rw nth_carry, exact int.div_le_of_le_mul (by norm_num) (by rwa mul_two) } end lemma le_nth_carry (x : ℕ → arity → bool) (n : ℕ) : p.min_carry ≤ p.nth_carry x n := begin induction n with n ih, { exact p.le_init_carry }, { have h₁ : p.min_carry ≤ p.nth_carry x n, { exact ih }, have h₂ : p.min_carry ≤ p.carry (x n) (mod_two (p.nth_carry x n)), { exact p.le_carry (x n) (mod_two (p.nth_carry x n)) }, have h₃ : p.min_carry + p.min_carry ≤ p.nth_carry x n + p.carry (x n) (mod_two (p.nth_carry x n)), { exact add_le_add h₁ h₂ }, rw nth_carry, exact int.le_div_of_mul_le (by norm_num) (by rwa [mul_two]) } end @[simp] def nth_output (x : ℕ → arity → bool) (n : ℕ) : bool := p.output (x n) (mod_two (p.nth_carry x n)) lemma nth_carry_eq_of_nth_carry_eq {m n : ℕ} {x₁ x₂ : ℕ → arity → bool} : ∀ (i : ℕ) (hs : p₁.nth_carry x₁ m = p₂.nth_carry x₂ n) (hc : p₁.carry = p₂.carry) (hx : ∀ (j), j ≤ i → x₁ (m + j) = x₂ (n + j)), p₁.nth_carry x₁ (m + i) = p₂.nth_carry x₂ (n + i) | 0 hs ht hx := hs | (i+1) hs hc hx := begin rw [← add_assoc, ← add_assoc, nth_carry, nth_carry, next_carry, next_carry, hc, hx _ (nat.le_succ _), nth_carry_eq_of_nth_carry_eq _ _ hc (λ j hj, hx j (nat.le_succ_of_le hj))], { simpa [add_comm, add_assoc, add_left_comm] using hs } end lemma nth_output_eq_of_nth_carry_eq {m n : ℕ} {x₁ x₂ : ℕ → arity → bool} (i : ℕ) (hs : p₁.nth_carry x₁ m = p₂.nth_carry x₂ n) (hc : p₁.carry = p₂.carry) (ho : p₁.output = p₂.output) (hx : ∀ (j), j ≤ i → x₁ (m + j) = x₂ (n + j)) : p₁.nth_output x₁ (m + i) = p₂.nth_output x₂ (n + i) := begin have := nth_carry_eq_of_nth_carry_eq i (by simpa using hs) hc hx, rw [nth_output, nth_output, ho, this, hx _ (le_refl _)] end inductive reachable_in : ℕ → ℤ → ℤ → Prop | init (i : ℤ) : reachable_in 0 i i | succ {n i j} (x : arity → bool) (h : reachable_in n i j) : reachable_in (n + 1) i ((j + p.carry x (mod_two j)) / 2) def reachable_from (b : bool) : ∀ (n : ℕ), set (finset.Icc p.min_carry p.max_carry) | 0 := (mod_two ∘ coe) ⁻¹' {b} | (n+1) := ⋃ (x : arity → bool), (p.next_carry x ∘ coe) ⁻¹' (coe '' reachable_from n) #print set.image_union end propagate_struc
function distance = word_distance(word1, word2, model) % Shows the L2 distance between word1 and word2 in the word_embedding_weights. % Inputs: % word1: The first word as a string. % word2: The second word as a string. % model: Model returned by the training script. % Example usage: % word_distance('school', 'university', model); word_embedding_weights = model.word_embedding_weights; vocab = model.vocab; id1 = strmatch(word1, vocab, 'exact'); id2 = strmatch(word2, vocab, 'exact'); if ~any(id1) fprintf(1, 'Word ''%s\'' not in vocabulary.\n', word1); return; end if ~any(id2) fprintf(1, 'Word ''%s\'' not in vocabulary.\n', word2); return; end word_rep1 = word_embedding_weights(id1, :); word_rep2 = word_embedding_weights(id2, :); diff = word_rep1 - word_rep2; distance = sqrt(sum(diff .* diff));
section propositional variables P Q R : Prop ------------------------------------------------ -- Proposições de dupla negaço: ------------------------------------------------ theorem doubleneg_intro : P → ¬¬P := begin intro h, intro hnp, contradiction, end theorem doubleneg_elim : ¬¬P → P := begin intro nnp, by_contradiction hboom, contradiction, end theorem doubleneg_law : ¬¬P ↔ P := begin split, { intro h, by_contradiction hboom, contradiction, }, { intro h, intro hnp, contradiction, } end ------------------------------------------------ -- Comutatividade dos ∨,∧: ------------------------------------------------ theorem disj_comm : (P ∨ Q) → (Q ∨ P) := begin intro hpq, cases hpq with hp hq, { right, assumption }, { left, assumption, } end theorem conj_comm : (P ∧ Q) → (Q ∧ P) := begin intro h, split, { cases h, assumption }, { cases h, assumption } end ------------------------------------------------ -- Proposições de interdefinabilidade dos →,∨: ------------------------------------------------ theorem impl_as_disj_converse : (¬P ∨ Q) → (P → Q) := begin intro h, intro hp, cases h with hnp hq, { contradiction, }, { assumption, } end theorem disj_as_impl : (P ∨ Q) → (¬P → Q) := begin intro h, intro hnp, cases h with hp hq, { contradiction, }, { assumption, } end ------------------------------------------------ -- Proposições de contraposição: ------------------------------------------------ theorem impl_as_contrapositive : (P → Q) → (¬Q → ¬P) := begin intro h, intro hq, by_cases r : P, { have hq: Q := h r, contradiction, }, { assumption, } end theorem impl_as_contrapositive_converse : (¬Q → ¬P) → (P → Q) := begin intro h, intro p, by_cases r : Q, { assumption, }, { have hnp:¬P := h r, contradiction, } end theorem contrapositive_law : (P → Q) ↔ (¬Q → ¬P) := begin split, { intro h, intro hnq, by_contradiction hboom, have hq:Q := h hboom, contradiction, }, { intro h, intro hp, by_cases r: Q, { assumption, }, { have hnp:¬P := h r, contradiction, } } end ------------------------------------------------ -- A irrefutabilidade do LEM: ------------------------------------------------ theorem lem_irrefutable : ¬¬(P∨¬P) := begin intro h, by_cases x:P, { apply h, left, assumption }, { apply h, right, assumption, } end ------------------------------------------------ -- A lei de Peirce ------------------------------------------------ theorem peirce_law_weak : ((P → Q) → P) → ¬¬P := begin intro h, intro np, apply np, apply h, intro p, contradiction, end ------------------------------------------------ -- Proposições de interdefinabilidade dos ∨,∧: ------------------------------------------------ theorem disj_as_negconj : P∨Q → ¬(¬P∧¬Q) := begin intro hpq, intro npq, cases npq with np nq, cases hpq with hp hq, { contradiction, }, { contradiction, } end theorem conj_as_negdisj : P∧Q → ¬(¬P∨¬Q) := begin intro hpq, intro norpq, cases hpq with p q, cases norpq with np nq, { contradiction, }, { contradiction, } end ------------------------------------------------ -- As leis de De Morgan para ∨,∧: ------------------------------------------------ theorem demorgan_disj : ¬(P∨Q) → (¬P ∧ ¬Q) := begin intro nhpq, split, { intro np, apply nhpq, left, assumption }, { intro nq, apply nhpq, right, assumption, } end theorem demorgan_disj_converse : (¬P ∧ ¬Q) → ¬(P∨Q) := begin intro cnpq, intro porq, cases cnpq with np nq, cases porq with hp hq, { contradiction, }, { contradiction, } end theorem demorgan_conj : ¬(P∧Q) → (¬Q ∨ ¬P) := begin intro nepq, by_cases h:P, { left, intro q, apply nepq, split, { assumption, }, { assumption, } }, { right, assumption, } end theorem demorgan_conj_converse : (¬Q ∨ ¬P) → ¬(P∧Q) := begin intro nopq, intro peq, cases peq with p q, cases nopq with nq np, { contradiction, }, { contradiction, } end theorem demorgan_conj_law : ¬(P∧Q) ↔ (¬Q ∨ ¬P) := begin split, { intro npeq, by_cases h:P, { left, intro q, apply npeq, split, { assumption, }, { assumption, } }, { right, assumption, }, }, { intro norpq, intro peq, cases peq with p q, cases norpq with np nq, { contradiction, }, { contradiction, } } end theorem demorgan_disj_law : ¬(P∨Q) ↔ (¬P ∧ ¬Q) := begin split, { intro nopq, split, { intro p, apply nopq, left, assumption, }, { intro q, apply nopq, right, assumption, }, }, { intro nepq, intro pouq, cases nepq with np nq, cases pouq with p q, { contradiction, }, { contradiction, } } end ------------------------------------------------ -- Proposições de distributividade dos ∨,∧: ------------------------------------------------ theorem distr_conj_disj : P∧(Q∨R) → (P∧Q)∨(P∧R) := begin intro peqor, cases peqor with p qr, cases qr with q r, { left, split, { assumption }, { assumption, }, }, { right, split, { assumption, }, { assumption, } } end theorem distr_conj_disj_converse : (P∧Q)∨(P∧R) → P∧(Q∨R) := begin intro peqoper, split, { cases peqoper with peq per, { cases peq with p q, assumption, }, { cases per with p r, assumption, }, }, { cases peqoper with peq per, { cases peq with p q, left, assumption, }, { cases per with p r, right, assumption, } } end theorem distr_disj_conj : P∨(Q∧R) → (P∨Q)∧(P∨R) := begin intro poqer, split, { cases poqer with p qer, { left, assumption, }, { cases qer with q r, right, assumption, }, }, { cases poqer with p qer, { left, assumption, }, { cases qer with q r, right, assumption, } } end theorem distr_disj_conj_converse : (P∨Q)∧(P∨R) → P∨(Q∧R) := begin intro hpoqepor, cases hpoqepor with hpoq por, cases hpoq with p q, { left, assumption, }, { cases por with p r, { left, assumption, }, { right, split, { assumption, }, { assumption, }, } } end ------------------------------------------------ -- Currificação ------------------------------------------------ theorem curry_prop : ((P∧Q)→R) → (P→(Q→R)) := begin intro peq_tor, intro p, intro q, apply peq_tor, split, { assumption, }, { assumption, } end theorem uncurry_prop : (P→(Q→R)) → ((P∧Q)→R) := begin intro p_to_q_to_r, intro peq, cases peq with p q, apply p_to_q_to_r, { assumption, }, { assumption, }, end ------------------------------------------------ -- Reflexividade da →: ------------------------------------------------ theorem impl_refl : P → P := begin intro p, assumption, end ------------------------------------------------ -- Weakening and contraction: ------------------------------------------------ theorem weaken_disj_right : P → (P∨Q) := begin intro p, left, assumption, end theorem weaken_disj_left : Q → (P∨Q) := begin intro q, right, assumption, end theorem weaken_conj_right : (P∧Q) → P := begin intro peq, cases peq with p q, assumption, end theorem weaken_conj_left : (P∧Q) → Q := begin intro peq, cases peq with p q, assumption, end theorem conj_idempot : (P∧P) ↔ P := begin split, { intro pep, cases pep with p p', { assumption, }, }, { intro p, split, { assumption, }, { assumption, }, } end theorem disj_idempot : (P∨P) ↔ P := begin split, { intro pop, cases pop with p p', { assumption }, { assumption, }, }, { intro p, left, assumption, } end end propositional ---------------------------------------------------------------- section predicate variable U : Type variables P Q : U -> Prop ------------------------------------------------ -- As leis de De Morgan para ∃,∀: ------------------------------------------------ theorem demorgan_exists : ¬(∃x, P x) → (∀x, ¬P x) := begin intro epx, intro x, by_contradiction hboom, apply epx, existsi x, assumption, end theorem demorgan_exists_converse : (∀x, ¬P x) → ¬(∃x, P x) := begin intro napx, intro nepx, cases nepx with t ht, exact(napx t) ht, end theorem demorgan_forall : ¬(∀x, P x) → (∃x, ¬P x) := begin rw contrapositive_law, rw doubleneg_law, intro epx, intro x, by_contradiction nPx, apply epx, existsi x, exact nPx, end theorem demorgan_forall_converse : (∃x, ¬P x) → ¬(∀x, P x) := begin intro epx, intro apx, cases epx with x npx, apply npx, apply apx, end theorem demorgan_forall_law : ¬(∀x, P x) ↔ (∃x, ¬P x) := begin split, { rw contrapositive_law, rw doubleneg_law, intro epx, intro x, by_contradiction nPx, apply epx, existsi x, exact nPx, }, { intro epx, intro apx, cases epx with x npx, apply npx, apply apx, } end theorem demorgan_exists_law : ¬(∃x, P x) ↔ (∀x, ¬P x) := begin split, { intro epx, intro x, by_contradiction hboom, apply epx, existsi x, assumption, }, { intro napx, intro nepx, cases nepx with t ht, exact(napx t) ht, } end ------------------------------------------------ -- Proposições de interdefinabilidade dos ∃,∀: ------------------------------------------------ theorem exists_as_neg_forall : (∃x, P x) → ¬(∀x, ¬P x) := begin intro epx, intro apx, cases epx with x Px, exact(apx x) Px, end theorem forall_as_neg_exists : (∀x, P x) → ¬(∃x, ¬P x) := begin intro apx, intro nepx, cases nepx with x npx, apply npx, apply apx, end theorem forall_as_neg_exists_converse : ¬(∃x, ¬P x) → (∀x, P x) := begin intro nepx, intro x, by_contradiction hboom, apply nepx, existsi x, exact hboom, end theorem exists_as_neg_forall_converse : ¬(∀x, ¬P x) → (∃x, P x) := begin rw contrapositive_law, rw doubleneg_law, intro nepx, intro x, by_contradiction pboom, apply nepx, existsi x, exact pboom, end theorem forall_as_neg_exists_law : (∀x, P x) ↔ ¬(∃x, ¬P x) := begin split, { intro apx, intro nepx, cases nepx with x npx, apply npx, apply apx, }, { intro nepx, intro x, by_contradiction hboom, apply nepx, existsi x, exact hboom, } end theorem exists_as_neg_forall_law : (∃x, P x) ↔ ¬(∀x, ¬P x) := begin split, { intro epx, intro apx, cases epx with x Px, exact(apx x) Px, }, { rw contrapositive_law, rw doubleneg_law, intro nepx, intro x, by_contradiction pboom, apply nepx, existsi x, exact pboom, } end ------------------------------------------------ -- Proposições de distributividade de quantificadores: ------------------------------------------------ theorem exists_conj_as_conj_exists : (∃x, P x ∧ Q x) → (∃x, P x) ∧ (∃x, Q x) := begin intro epq, split, { sorry, } end theorem exists_disj_as_disj_exists : (∃x, P x ∨ Q x) → (∃x, P x) ∨ (∃x, Q x) := begin sorry, end theorem exists_disj_as_disj_exists_converse : (∃x, P x) ∨ (∃x, Q x) → (∃x, P x ∨ Q x) := begin sorry, end theorem forall_conj_as_conj_forall : (∀x, P x ∧ Q x) → (∀x, P x) ∧ (∀x, Q x) := begin sorry, end theorem forall_conj_as_conj_forall_converse : (∀x, P x) ∧ (∀x, Q x) → (∀x, P x ∧ Q x) := begin sorry, end theorem forall_disj_as_disj_forall_converse : (∀x, P x) ∨ (∀x, Q x) → (∀x, P x ∨ Q x) := begin sorry, end /- NOT THEOREMS -------------------------------- theorem forall_disj_as_disj_forall : (∀x, P x ∨ Q x) → (∀x, P x) ∨ (∀x, Q x) := begin end theorem exists_conj_as_conj_exists_converse : (∃x, P x) ∧ (∃x, Q x) → (∃x, P x ∧ Q x) := begin end ---------------------------------------------- -/ end predicate
module Dbcritic.Check.TimeZone import Control.IOExcept import Data.Vect import Dbcritic.Check import Dbcritic.Libpq export issueLocaltime : Issue issueLocaltime = let identifier = [ "localtime" ] description = "The client receives timestamps in the time zone of the server." problems = [ "Changing the server time zone causes the client to receive different timestamps." ] solutions = [ "Set the ‘TimeZone’ configuration parameter to a concrete time zone, such as UTC." ] in MkIssue identifier description problems solutions IsNonEmpty IsNonEmpty IsNonEmpty export checkTimeZone : Check checkTimeZone = MkCheck name help inspect where name = "time_zone" help = "Check that the ‘TimeZone’ parameter is set to a sensible value." inspect : PgConnection -> IOExcept String (List Issue) inspect conn = do res <- pgExecute conn """ SHOW "TimeZone" """ case pgCell res 0 0 of Just "localtime" => pure [issueLocaltime] Just _ => pure [] Nothing => ioe_fail "checkTimeZone: Bad result"
program matrix_expression_do_loop use, intrinsic :: iso_fortran_env, only : dp => REAL64 implicit none integer, parameter :: m = 20000, n = 3000 integer :: i, j real(kind=dp), dimension(m, n) :: A, B, C, D A = 1.0_dp B = 1.0_dp C = 1.0_dp do j = 1, n do i = 1, m D(i, j) = 5.0_dp*A(i, j)*B(i, j) + C(i, j)/1.5_dp + 8.0_dp end do end do print *, sum(D) end program matrix_expression_do_loop
#data preprocess #Importing the dataset dataset = read.csv('Data.csv') # Replacing missing value in Age column with AVG of entire column dataset$Age = ifelse(is.na(dataset$Age), ave(dataset$Age, FUN = function(x) mean(x, na.rm = TRUE)), dataset$Age) # Replacing missing value in Salary column with AVG of entire column dataset$Salary = ifelse(is.na(dataset$Salary), ave(dataset$Salary, FUN = function(x) mean(x, na.rm = TRUE)), dataset$Salary) # Encoding categorical data dataset$Country = factor(dataset$Country, levels = c('France', 'Spain', 'Germany'), labels = c(1, 2, 3)) dataset$Purchased= factor(dataset$Purchased, levels = c('No', 'Yes'), labels = c(0,1)) # Split the dataset into the Training set and test set library(caTools) set.seed(123) split = sample.split(dataset$Purchased, SplitRatio = 0.8) training_set = subset(dataset, split==TRUE) test_set = subset(dataset, split==FALSE) # Featured Scaling training_set[, 2:3] = scale(training_set[, 2:3]) test_set[, 2:3] = scale(test_set[, 2:3])
# two arg clamp: # takes a Type arg, and uses typemin and typemax to get the limits # AND ALSO converts to this type since after clamping, this is safe # since I'm effectively adding to Base here, get warnings after reloading # see https://github.com/JuliaLang/julia/issues/7860#issuecomment-51340412 import Base.clamp clamp{T}( x, ::Type{T} ) = clamp( x, typemin(T), typemax(T) ) % T # copied and modified from base/math.jl # this makes two arg clamp work with arrays clamp{T,T2}(x::AbstractArray{T,1}, ::Type{T2} ) = [clamp(xx, T2 ) for xx in x] clamp{T,T2}(x::AbstractArray{T,2}, ::Type{T2}) = [clamp(x[i,j], T2) for i in 1:size(x,1), j in 1:size(x,2)] # fixme (iter): change to `eachindex` when #15459 is ready clamp{T,T2}(x::AbstractArray{T}, ::Type{T2}) = reshape([clamp(xx, T2) for xx in x], size(x)) function clamp!{T,T2}(x::AbstractArray{T}, ::Type{T2}) @inbounds for i in eachindex(x) x[i] = clamp(x[i], T2 ) end x end import Base.clamp # make two arg clamp more efficient for BInt RHS @generated function Base.clamp{Tx<:Integer,R}( x::Tx, ::Type{BInt{R}} ) l = typemin(BInt{R}) u = typemax(BInt{R}) Tw = default_int_type( range_union( R, Tx ) ) # converting x to Tw makes this work for Tx being either # an ordinary Int, or a Bint :( UncheckedBInt{R}( Base.clamp( x % $Tw, $l , $u ) ) ) end @generated function Base.clamp{Tx<:Integer,R,T}( x::Tx, ::Type{BInt{R,T}} ) l = typemin(BInt{R,T}) u = typemax(BInt{R,T}) Tw = default_int_type( range_union( R, Tx ) ) :( UncheckedBInt{R,T}( Base.clamp( x % $Tw, $l , $u ) ) ) end # this works for arrays # clamp( BInt{Int16}[ 10, 2000, 30 ], BInt{Int8} ) # ideally by adding Base.clamp( n, T ) and associated Array code
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE OverloadedStrings #-} -- | Main entry point for executable, mainly for tests module Main (main) where import AI.Network.RNN import AI.GeneticAlgorithm.Simple import Control.Monad import Control.Monad.Random hiding (fromList) import qualified Data.Text as T import qualified Data.Text.IO as T import Data.IORef import System.Directory --import Debug.Trace import System.Environment import Data.Binary import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BSL import Numeric.LinearAlgebra.HMatrix --main::IO() --main = do -- let m :: [Expr Double] = map (\n->Var ("m" ++ show n)) [1..400] -- v :: [Expr Double] = map (\n->Var ("v" ++ show n)) [1..4] -- mycost v m = sum $ listMProd m v -- mygrad = grad (mycost (map auto v)) m -- --mygrads = gradientDescent (mycost (map auto v)) m -- print $ mygrad main :: IO() main = do --txt <- liftM (T.take 100) $ T.readFile "data/tinyshakespeare.txt" let txt= "hello world!" trainData = train txt fn = "output/lstm.one.helloworld" generateLength = min 50 (T.length txt) print "Text:" print txt args <- getArgs when (length args<2) $ error "rnn gradient <maxgen> | rmsprop <maxgen> | generic <maxgen>" let fn2=fn++"."++head args ex <- return False -- doesFileExist fn2 rnn<-case args of ("gradient":mg:_) -> do let maxGen = read mg rd <- readEx fn2 ex trainData gradient fn2 rd generateLength maxGen ("rmsprop":mg:_) -> do let maxGen = read mg rd <- readEx fn2 ex trainData rmsprop fn2 rd generateLength maxGen ("genetic":mg:_) -> do let maxGen = read mg b <- if ex then do rnn1::LSTMNetwork <- fromVector (tdRecSize trainData) <$> decodeFile fn2 return $ buildExisting rnn1 trainData else return $ buildTD trainData -- let b = buildTDs trainData genetic fn2 b generateLength maxGen _ -> error "rnn gradient <maxgen> | rmsprop <maxgen> | generic <maxgen>" encodeFile fn2 $ toVector rnn print rnn where readEx fn ex trainData = if ex then do r::LSTMNetwork <- fromVector (tdRecSize trainData) <$> decodeFile fn return $ RNNData r trainData (fromIntegral $ length $ tdInputs trainData) else evalRandIO $ buildTD trainData (train, gener) = (textToTrainDataS,generateS) genStep maxGen = max 1 $ maxGen `div` 10 gradient fn (RNNData r td _) generateLength maxGen = learnGradientDescent r td $ test fn generateLength maxGen rmsprop fn (RNNData r td _) generateLength maxGen = learnRMSProp r td $ test fn generateLength maxGen genetic fn r generateLength maxGen = do fitnessList <- newIORef [] (RNNData rnn _ _) <- runGAIO 64 0.2 r $ stopf2 fn generateLength maxGen fitnessList return rnn test fn generateLength maxGen rnn td gen= do when (mod gen (genStep maxGen) == 0) $ do let c= cost rnn td print (show gen ++ ":" ++ show c) t <- evalRandIO $ gener (tdData td) generateLength (size $ head $ tdInputs td) rnn print t let fn2 = fn ++ "." ++ (show gen) let bs= BSL.toStrict $ encode $ toVector rnn BS.writeFile fn2 bs return $ gen < maxGen stopf2 fn generateLength maxGen fs rd@((RNNData rnn td _),_) gen = do _ <- test fn generateLength maxGen rnn td gen stopf fs maxGen rd gen -- | Build LSTM network buildTD ::(Monad m,RandomGen g) => TrainData a -> RandT g m (RNNData LSTMNetwork a) buildTD td = buildNetworkData td (tdRecSize td) lstmFullSize buildTDIO ::(Monad m,RandomGen g) => TrainData a -> RandT g m (RNNData LSTMIO a) buildTDIO td = let layers = 2 sz = 40 -- tds = TrainData (tdInputs td) (tdOutputs td) (tdRecSize td,sz,layers,tdRecSize td) (tdData td) in buildNetworkData td (tdRecSize td,sz,layers,tdRecSize td) lstmioFullSize -- | Build LSTM network buildTDs ::(Monad m,RandomGen g) => TrainData a -> RandT g m (RNNData [LSTMNetwork] a) buildTDs td = let layers = 2 -- tds = TrainData (tdInputs td) (tdOutputs td) (replicate layers $ tdRecSize td) (tdData td) in buildNetworkData td (replicate layers $ tdRecSize td)(sum . map lstmFullSize) -- | Build from existing data for genetic algorithm, to restart from where we were buildExisting :: (Monad m,RandomGen g) => LSTMNetwork -> TrainData a -> RandT g m (RNNData LSTMNetwork a) buildExisting rnn1 td@(TrainData is _ _ _) = do -- g <- getSplit --let rnn2 = evalRand (mutateNetwork rnn1) g return $ RNNData rnn1 td (fromIntegral $ length is) -- | Build from existing data for genetic algorithm, to restart from where we were buildExistings :: (Monad m,RandomGen g) => [LSTMNetwork] -> TrainData a -> RandT g m (RNNData [LSTMNetwork] a) buildExistings rnns td@(TrainData is _ _ _) = do -- g <- getSplit --let tds = TrainData (tdInputs td) (tdOutputs td) (replicate (length rnns) $ tdRecSize td) (tdData td) --let rnn2 = evalRand (mutateNetwork rnn1) g return $ RNNData rnns td (fromIntegral $ length is) -- | Build from existing data for genetic algorithm, to restart from where we were buildExistingIO :: (Monad m,RandomGen g) => LSTMIO -> TrainData a -> RandT g m (RNNData LSTMIO a) buildExistingIO rnn1 td@(TrainData is _ _ _) = do -- g <- getSplit --let tds = TrainData (tdInputs td) (tdOutputs td) (rnnsize rnn1) (tdData td) --let rnn2 = evalRand (mutateNetwork rnn1) g return $ RNNData rnn1 td (fromIntegral $ length is) -- DRAGONS -- --main :: IO() --main = do -- -- txt <- T.readFile "data/tinyshakespeare.txt" -- let txt= "hello world!" -- (is,os,m) = textToTrainData txt -- sz = DM.size m -- fn = "lstm.learn1.helloworld" -- print sz -- print $ length is -- print $ length os -- ex <- doesFileExist fn -- (RNNData r _ _ _) <- if ex -- then do -- r <- read <$> readFile fn -- return $ RNNData r [] [] 0 -- else -- evalRandIO $ build sz is os -- let ls = toList $ toVector r -- --print ls -- --print $ toList $ chead ocs -- --print ls -- --print is -- --print $ lstmList sz ls (toList $ head is) -- --print $ mapAccumL (lstmList sz) ls (map toList is) -- --headJet $ tailJet $ jet $ grads ---- let c= cost sz (fromIntegral $ length is) (map (toList) is) (map (toList) os) ls ---- print c ---- let gs= grad (cost sz (auto $ fromIntegral $ length is) (map (map auto . toList) is) (map (map auto . toList) os)) ls ---- --let gs=jacobian (lstmList (lstmFullSize sz) (map auto ls)) (toList $ head os) ---- -- print gs ---- let ls2 = zipWith (\l g->l-g*0.1) ls gs ---- let c2= cost sz (fromIntegral $ length is) (map (toList) is) (map (toList) os) ls2 ---- print c2 ---- where ---- gFun :: [AD s (Sparse Double)] ---- -> AD s (Sparse Double) ---- gFun = map sigmoid -- let (l,lis,los)=((fromIntegral $ length is),(map toList is),(map toList os)) -- -- lsf <- learn sz ls l lis los 0 -- let myl= length ls -- print myl -- -- let adCost = cost sz (auto l) (map (map auto) lis) (map (map auto) los) -- -- lsf <- learn2 sz ls (replicate myl 0) (replicate myl 0) (replicate myl 0) l lis los 0 (m,(min 50 (T.length txt))) -- lsf <- learn sz ls l lis los 0 (m,(min 50 (T.length txt))) -- --print lsf -- let rnn::LSTMNetwork = fromVector sz (fromList lsf) -- writeFile fn $ show rnn -- --print rnn -- -- print $ length is -- let s = size $ head is ---- -- print s ---- let tl= T.length txt ---- -- print tl ---- -- print m ---- let c= cost sz l lis los ls ---- print c ---- let c2= cost sz l lis los lsf ---- print c2 -- t <- evalRandIO $ generate m (min 50 (T.length txt)) s rnn -- print t -- return () -- where -- test sz ls l is os gen (m,gl) = when ((mod gen 500) == 0) $ do -- let c= cost sz l is os ls -- print (show gen ++ ":" ++ show c) -- let rnn::LSTMNetwork = fromVector sz (fromList ls) -- t <- evalRandIO $ generate m gl (length $ head is) rnn -- print t -- learn sz ls l is os gen testInfo = do -- test sz ls l is os gen testInfo -- if gen < 10000 -- then do -- let ls2 = learnGradientDescent (cost sz (auto l) (map (map auto) is) (map (map auto) os)) ls -- --let gs= grad (cost sz (auto l) (map (map auto) is) (map (map auto) os)) ls -- -- ls2 = zipWith (\o g->o-g*0.1) ls gs -- learn sz ls2 l is os (gen + 1) testInfo -- else return ls -- learn2 sz ls rgs rgs2 ugs l is os gen testInfo= do -- test sz ls l is os gen testInfo -- if gen < 10000 -- then do -- let gs= force $ grad (cost sz (auto l) (map (map auto) is) (map (map auto) os)) ls -- rgup = force $ zipWith (\rg g-> 0.95 * rg + 0.05 * g) rgs ls -- rg2up = force $ zipWith (\rg2 g-> 0.95 * rg2 + 0.05 * (g ** 2)) rgs2 ls -- ugup = force $ zipWith4 (\ud zg rg rg2 -> 0.9 * ud - 1e-4 * zg / sqrt(rg2 - rg ** 2 + 1e-4)) ugs gs rgup rg2up -- -- ls2 = zipWith (\o g->o-g*0.1) ls gs -- ls2 = force $ zipWith (+) ls ugup -- learn2 sz ls2 rgup rg2up ugup l is os (gen + 1) testInfo -- else return ls -- learn3 _ ls _ _ _ _ [] [] _ = return ls -- learn3 sz ls rgs rgs2 ugs l is os gen = do -- let batchSize = 100 -- (is1,is2) = splitAt batchSize is -- (os1,os2) = splitAt batchSize os -- when ((mod gen 100) == 0) $ do -- let c= cost sz l is1 os1 ls -- print (show gen ++ ":" ++ show c) -- --if gen < 1 -- -- then do -- let gs= force $ grad (cost sz (auto l) (map (map auto) is1) (map (map auto) os1)) ls -- rgup = force $ zipWith (\rg g-> 0.95 * rg + 0.05 * g) rgs ls -- rg2up = force $ zipWith (\rg2 g-> 0.95 * rg2 + 0.05 * (g ** 2)) rgs2 ls -- ugup = force $ zipWith4 (\ud zg rg rg2 -> 0.9 * ud - 1e-4 * zg / sqrt(rg2 - rg ** 2 + 1e-4)) ugs gs rgup rg2up -- -- ls2 = zipWith (\o g->o-g*0.1) ls gs -- ls2 = force $ zipWith (+) ls ugup -- learn3 sz ls2 rgup rg2up ugup l is2 os2 (gen + 1) -- -- else return ls --main1 :: IO () --main1 = do ---- n<-createRandomNetwork (RNNDimensions 1 2 3 True) ---- let (n2,out)=evalStep n [1] ---- (n3,out1)=evalStep n2 [3] ---- (n4,out2)=evalSteps n [[1],[3]] ---- print $ n3==n4 ---- print $ out1 == (last out2) ---- txt <- liftM (T.take 100) $ T.readFile "data/tinyshakespeare.txt" -- let -- dim = (RNNDimensions 4 6 4 True) -- --is = [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]] -- --os = [[0,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1],[0,0,0,0]] -- txt= "hello world!" -- (is,os,m) = textToTrainData txt -- sz = DM.size m -- fn = "out.lstm.h" -- -- dim = RNNDimensions sz (sz) sz True -- print sz -- fitnessList <- newIORef [] ---- rnn1::LSTMNetwork <- read <$> readFile fn -- ex <- doesFileExist fn -- b <- if ex -- then do -- rnn1::LSTMNetwork <- read <$> readFile fn -- return $ buildExisting rnn1 sz is os -- else return $ build sz is os -- r@(RNNData rnn _ _ _) <- runGAIO 64 0.1 b $ stopf fitnessList 100 ---- -- (RNNData rnn _ _) <- evalRandIO $ buildNetworkData dim is os ---- print $ fitness r -- -- print rnn -- --let real = snd $ evalSteps rnn is -- --print $ dataToText m real -- t <- evalRandIO $ generate m (min 50 (T.length txt)) (size $ head is) rnn -- print t -- -- writeFile fn $ show rnn -- build ::(Monad m,RandomGen g) => Int -> [Vector Double] -> [Vector Double] -> RandT g m (RNNData RNNetwork RNNDimensions) -- build sz is os = buildNetworkData (RNNDimensions sz (sz) sz True) totalDataLength is os --build ::(Monad m,RandomGen g) => TrainData a Int -> RandT g m (RNNData LSTMNetwork Int) --build sz td = buildNetworkData sz lstmFullSize is os
If $f$ is a function from a set $S$ to a finite set, then $f$ is discrete.
lemma emeasure_sup_measure'_le2: assumes [simp]: "sets B = sets C" "sets A = sets C" and [measurable]: "X \<in> sets C" assumes A: "\<And>Y. Y \<subseteq> X \<Longrightarrow> Y \<in> sets A \<Longrightarrow> emeasure A Y \<le> emeasure C Y" assumes B: "\<And>Y. Y \<subseteq> X \<Longrightarrow> Y \<in> sets A \<Longrightarrow> emeasure B Y \<le> emeasure C Y" shows "emeasure (sup_measure' A B) X \<le> emeasure C X"
[STATEMENT] lemma fun_of_list_Cons [simp]: "fun_of_list i (x # xs) g = fun_of_list (i + 1) xs (g(i:=x))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. fun_of_list i (x # xs) g = fun_of_list (i + 1) xs (g(i := x)) [PROOF STEP] by (auto simp add: fun_eq_iff fun_of_list_def nth_Cons' nat_diff_distrib [of "int (Suc 0)", simplified, symmetric] diff_diff_eq)
lemma Sup_lexord_rel: assumes "\<And>i. i \<in> I \<Longrightarrow> k (A i) = k (B i)" "R (c (A ` {a \<in> I. k (B a) = (SUP x\<in>I. k (B x))})) (c (B ` {a \<in> I. k (B a) = (SUP x\<in>I. k (B x))}))" "R (s (A`I)) (s (B`I))" shows "R (Sup_lexord k c s (A`I)) (Sup_lexord k c s (B`I))"
theory exercise_2_3 imports Main begin (*count the number of different elements*) fun count::"'a\<Rightarrow>'a list\<Rightarrow>nat" where "count x []=0"| "count x (y # xs) =If(x=y)(Suc(count x xs))(count x xs)"(*if x==y,then the count++,else count unchange*) value "count(1::nat) [1,1,2,3,1,3,1]" lemma count_e :"count x xs \<le> length xs" apply(induction xs) apply(auto) done end
module Instructions import Hardware
(* Title: HOL/Analysis/Gamma_Function.thy Author: Manuel Eberl, TU München *) section \<open>The Gamma Function\<close> theory Gamma_Function imports Equivalence_Lebesgue_Henstock_Integration Summation_Tests Harmonic_Numbers "HOL-Library.Nonpos_Ints" "HOL-Library.Periodic_Fun" begin text \<open> Several equivalent definitions of the Gamma function and its most important properties. Also contains the definition and some properties of the log-Gamma function and the Digamma function and the other Polygamma functions. Based on the Gamma function, we also prove the Weierstra{\ss} product form of the sin function and, based on this, the solution of the Basel problem (the sum over all \<^term>\<open>1 / (n::nat)^2\<close>. \<close> lemma pochhammer_eq_0_imp_nonpos_Int: "pochhammer (x::'a::field_char_0) n = 0 \<Longrightarrow> x \<in> \<int>\<^sub>\<le>\<^sub>0" by (auto simp: pochhammer_eq_0_iff) lemma closed_nonpos_Ints [simp]: "closed (\<int>\<^sub>\<le>\<^sub>0 :: 'a :: real_normed_algebra_1 set)" proof - have "\<int>\<^sub>\<le>\<^sub>0 = (of_int ` {n. n \<le> 0} :: 'a set)" by (auto elim!: nonpos_Ints_cases intro!: nonpos_Ints_of_int) also have "closed \<dots>" by (rule closed_of_int_image) finally show ?thesis . qed lemma plus_one_in_nonpos_Ints_imp: "z + 1 \<in> \<int>\<^sub>\<le>\<^sub>0 \<Longrightarrow> z \<in> \<int>\<^sub>\<le>\<^sub>0" using nonpos_Ints_diff_Nats[of "z+1" "1"] by simp_all lemma of_int_in_nonpos_Ints_iff: "(of_int n :: 'a :: ring_char_0) \<in> \<int>\<^sub>\<le>\<^sub>0 \<longleftrightarrow> n \<le> 0" by (auto simp: nonpos_Ints_def) lemma one_plus_of_int_in_nonpos_Ints_iff: "(1 + of_int n :: 'a :: ring_char_0) \<in> \<int>\<^sub>\<le>\<^sub>0 \<longleftrightarrow> n \<le> -1" proof - have "1 + of_int n = (of_int (n + 1) :: 'a)" by simp also have "\<dots> \<in> \<int>\<^sub>\<le>\<^sub>0 \<longleftrightarrow> n + 1 \<le> 0" by (subst of_int_in_nonpos_Ints_iff) simp_all also have "\<dots> \<longleftrightarrow> n \<le> -1" by presburger finally show ?thesis . qed lemma one_minus_of_nat_in_nonpos_Ints_iff: "(1 - of_nat n :: 'a :: ring_char_0) \<in> \<int>\<^sub>\<le>\<^sub>0 \<longleftrightarrow> n > 0" proof - have "(1 - of_nat n :: 'a) = of_int (1 - int n)" by simp also have "\<dots> \<in> \<int>\<^sub>\<le>\<^sub>0 \<longleftrightarrow> n > 0" by (subst of_int_in_nonpos_Ints_iff) presburger finally show ?thesis . qed lemma fraction_not_in_ints: assumes "\<not>(n dvd m)" "n \<noteq> 0" shows "of_int m / of_int n \<notin> (\<int> :: 'a :: {division_ring,ring_char_0} set)" proof assume "of_int m / (of_int n :: 'a) \<in> \<int>" then obtain k where "of_int m / of_int n = (of_int k :: 'a)" by (elim Ints_cases) with assms have "of_int m = (of_int (k * n) :: 'a)" by (auto simp add: field_split_simps) hence "m = k * n" by (subst (asm) of_int_eq_iff) hence "n dvd m" by simp with assms(1) show False by contradiction qed lemma fraction_not_in_nats: assumes "\<not>n dvd m" "n \<noteq> 0" shows "of_int m / of_int n \<notin> (\<nat> :: 'a :: {division_ring,ring_char_0} set)" proof assume "of_int m / of_int n \<in> (\<nat> :: 'a set)" also note Nats_subset_Ints finally have "of_int m / of_int n \<in> (\<int> :: 'a set)" . moreover have "of_int m / of_int n \<notin> (\<int> :: 'a set)" using assms by (intro fraction_not_in_ints) ultimately show False by contradiction qed lemma not_in_Ints_imp_not_in_nonpos_Ints: "z \<notin> \<int> \<Longrightarrow> z \<notin> \<int>\<^sub>\<le>\<^sub>0" by (auto simp: Ints_def nonpos_Ints_def) lemma double_in_nonpos_Ints_imp: assumes "2 * (z :: 'a :: field_char_0) \<in> \<int>\<^sub>\<le>\<^sub>0" shows "z \<in> \<int>\<^sub>\<le>\<^sub>0 \<or> z + 1/2 \<in> \<int>\<^sub>\<le>\<^sub>0" proof- from assms obtain k where k: "2 * z = - of_nat k" by (elim nonpos_Ints_cases') thus ?thesis by (cases "even k") (auto elim!: evenE oddE simp: field_simps) qed lemma sin_series: "(\<lambda>n. ((-1)^n / fact (2*n+1)) *\<^sub>R z^(2*n+1)) sums sin z" proof - from sin_converges[of z] have "(\<lambda>n. sin_coeff n *\<^sub>R z^n) sums sin z" . also have "(\<lambda>n. sin_coeff n *\<^sub>R z^n) sums sin z \<longleftrightarrow> (\<lambda>n. ((-1)^n / fact (2*n+1)) *\<^sub>R z^(2*n+1)) sums sin z" by (subst sums_mono_reindex[of "\<lambda>n. 2*n+1", symmetric]) (auto simp: sin_coeff_def strict_mono_def ac_simps elim!: oddE) finally show ?thesis . qed lemma cos_series: "(\<lambda>n. ((-1)^n / fact (2*n)) *\<^sub>R z^(2*n)) sums cos z" proof - from cos_converges[of z] have "(\<lambda>n. cos_coeff n *\<^sub>R z^n) sums cos z" . also have "(\<lambda>n. cos_coeff n *\<^sub>R z^n) sums cos z \<longleftrightarrow> (\<lambda>n. ((-1)^n / fact (2*n)) *\<^sub>R z^(2*n)) sums cos z" by (subst sums_mono_reindex[of "\<lambda>n. 2*n", symmetric]) (auto simp: cos_coeff_def strict_mono_def ac_simps elim!: evenE) finally show ?thesis . qed lemma sin_z_over_z_series: fixes z :: "'a :: {real_normed_field,banach}" assumes "z \<noteq> 0" shows "(\<lambda>n. (-1)^n / fact (2*n+1) * z^(2*n)) sums (sin z / z)" proof - from sin_series[of z] have "(\<lambda>n. z * ((-1)^n / fact (2*n+1)) * z^(2*n)) sums sin z" by (simp add: field_simps scaleR_conv_of_real) from sums_mult[OF this, of "inverse z"] and assms show ?thesis by (simp add: field_simps) qed lemma sin_z_over_z_series': fixes z :: "'a :: {real_normed_field,banach}" assumes "z \<noteq> 0" shows "(\<lambda>n. sin_coeff (n+1) *\<^sub>R z^n) sums (sin z / z)" proof - from sums_split_initial_segment[OF sin_converges[of z], of 1] have "(\<lambda>n. z * (sin_coeff (n+1) *\<^sub>R z ^ n)) sums sin z" by simp from sums_mult[OF this, of "inverse z"] assms show ?thesis by (simp add: field_simps) qed lemma has_field_derivative_sin_z_over_z: fixes A :: "'a :: {real_normed_field,banach} set" shows "((\<lambda>z. if z = 0 then 1 else sin z / z) has_field_derivative 0) (at 0 within A)" (is "(?f has_field_derivative ?f') _") proof (rule has_field_derivative_at_within) have "((\<lambda>z::'a. \<Sum>n. of_real (sin_coeff (n+1)) * z^n) has_field_derivative (\<Sum>n. diffs (\<lambda>n. of_real (sin_coeff (n+1))) n * 0^n)) (at 0)" proof (rule termdiffs_strong) from summable_ignore_initial_segment[OF sums_summable[OF sin_converges[of "1::'a"]], of 1] show "summable (\<lambda>n. of_real (sin_coeff (n+1)) * (1::'a)^n)" by (simp add: of_real_def) qed simp also have "(\<lambda>z::'a. \<Sum>n. of_real (sin_coeff (n+1)) * z^n) = ?f" proof fix z show "(\<Sum>n. of_real (sin_coeff (n+1)) * z^n) = ?f z" by (cases "z = 0") (insert sin_z_over_z_series'[of z], simp_all add: scaleR_conv_of_real sums_iff sin_coeff_def) qed also have "(\<Sum>n. diffs (\<lambda>n. of_real (sin_coeff (n + 1))) n * (0::'a) ^ n) = diffs (\<lambda>n. of_real (sin_coeff (Suc n))) 0" by simp also have "\<dots> = 0" by (simp add: sin_coeff_def diffs_def) finally show "((\<lambda>z::'a. if z = 0 then 1 else sin z / z) has_field_derivative 0) (at 0)" . qed lemma round_Re_minimises_norm: "norm ((z::complex) - of_int m) \<ge> norm (z - of_int (round (Re z)))" proof - let ?n = "round (Re z)" have "norm (z - of_int ?n) = sqrt ((Re z - of_int ?n)\<^sup>2 + (Im z)\<^sup>2)" by (simp add: cmod_def) also have "\<bar>Re z - of_int ?n\<bar> \<le> \<bar>Re z - of_int m\<bar>" by (rule round_diff_minimal) hence "sqrt ((Re z - of_int ?n)\<^sup>2 + (Im z)\<^sup>2) \<le> sqrt ((Re z - of_int m)\<^sup>2 + (Im z)\<^sup>2)" by (intro real_sqrt_le_mono add_mono) (simp_all add: abs_le_square_iff) also have "\<dots> = norm (z - of_int m)" by (simp add: cmod_def) finally show ?thesis . qed lemma Re_pos_in_ball: assumes "Re z > 0" "t \<in> ball z (Re z/2)" shows "Re t > 0" proof - have "Re (z - t) \<le> norm (z - t)" by (rule complex_Re_le_cmod) also from assms have "\<dots> < Re z / 2" by (simp add: dist_complex_def) finally show "Re t > 0" using assms by simp qed lemma no_nonpos_Int_in_ball_complex: assumes "Re z > 0" "t \<in> ball z (Re z/2)" shows "t \<notin> \<int>\<^sub>\<le>\<^sub>0" using Re_pos_in_ball[OF assms] by (force elim!: nonpos_Ints_cases) lemma no_nonpos_Int_in_ball: assumes "t \<in> ball z (dist z (round (Re z)))" shows "t \<notin> \<int>\<^sub>\<le>\<^sub>0" proof assume "t \<in> \<int>\<^sub>\<le>\<^sub>0" then obtain n where "t = of_int n" by (auto elim!: nonpos_Ints_cases) have "dist z (of_int n) \<le> dist z t + dist t (of_int n)" by (rule dist_triangle) also from assms have "dist z t < dist z (round (Re z))" by simp also have "\<dots> \<le> dist z (of_int n)" using round_Re_minimises_norm[of z] by (simp add: dist_complex_def) finally have "dist t (of_int n) > 0" by simp with \<open>t = of_int n\<close> show False by simp qed lemma no_nonpos_Int_in_ball': assumes "(z :: 'a :: {euclidean_space,real_normed_algebra_1}) \<notin> \<int>\<^sub>\<le>\<^sub>0" obtains d where "d > 0" "\<And>t. t \<in> ball z d \<Longrightarrow> t \<notin> \<int>\<^sub>\<le>\<^sub>0" proof (rule that) from assms show "setdist {z} \<int>\<^sub>\<le>\<^sub>0 > 0" by (subst setdist_gt_0_compact_closed) auto next fix t assume "t \<in> ball z (setdist {z} \<int>\<^sub>\<le>\<^sub>0)" thus "t \<notin> \<int>\<^sub>\<le>\<^sub>0" using setdist_le_dist[of z "{z}" t "\<int>\<^sub>\<le>\<^sub>0"] by force qed lemma no_nonpos_Real_in_ball: assumes z: "z \<notin> \<real>\<^sub>\<le>\<^sub>0" and t: "t \<in> ball z (if Im z = 0 then Re z / 2 else abs (Im z) / 2)" shows "t \<notin> \<real>\<^sub>\<le>\<^sub>0" using z proof (cases "Im z = 0") assume A: "Im z = 0" with z have "Re z > 0" by (force simp add: complex_nonpos_Reals_iff) with t A Re_pos_in_ball[of z t] show ?thesis by (force simp add: complex_nonpos_Reals_iff) next assume A: "Im z \<noteq> 0" have "abs (Im z) - abs (Im t) \<le> abs (Im z - Im t)" by linarith also have "\<dots> = abs (Im (z - t))" by simp also have "\<dots> \<le> norm (z - t)" by (rule abs_Im_le_cmod) also from A t have "\<dots> \<le> abs (Im z) / 2" by (simp add: dist_complex_def) finally have "abs (Im t) > 0" using A by simp thus ?thesis by (force simp add: complex_nonpos_Reals_iff) qed subsection \<open>The Euler form and the logarithmic Gamma function\<close> text \<open> We define the Gamma function by first defining its multiplicative inverse \<open>rGamma\<close>. This is more convenient because \<open>rGamma\<close> is entire, which makes proofs of its properties more convenient because one does not have to watch out for discontinuities. (e.g. \<open>rGamma\<close> fulfils \<open>rGamma z = z * rGamma (z + 1)\<close> everywhere, whereas the \<open>\<Gamma>\<close> function does not fulfil the analogous equation on the non-positive integers) We define the \<open>\<Gamma>\<close> function (resp.\ its reciprocale) in the Euler form. This form has the advantage that it is a relatively simple limit that converges everywhere. The limit at the poles is 0 (due to division by 0). The functional equation \<open>Gamma (z + 1) = z * Gamma z\<close> follows immediately from the definition. \<close> definition\<^marker>\<open>tag important\<close> Gamma_series :: "('a :: {banach,real_normed_field}) \<Rightarrow> nat \<Rightarrow> 'a" where "Gamma_series z n = fact n * exp (z * of_real (ln (of_nat n))) / pochhammer z (n+1)" definition Gamma_series' :: "('a :: {banach,real_normed_field}) \<Rightarrow> nat \<Rightarrow> 'a" where "Gamma_series' z n = fact (n - 1) * exp (z * of_real (ln (of_nat n))) / pochhammer z n" definition rGamma_series :: "('a :: {banach,real_normed_field}) \<Rightarrow> nat \<Rightarrow> 'a" where "rGamma_series z n = pochhammer z (n+1) / (fact n * exp (z * of_real (ln (of_nat n))))" lemma Gamma_series_altdef: "Gamma_series z n = inverse (rGamma_series z n)" and rGamma_series_altdef: "rGamma_series z n = inverse (Gamma_series z n)" unfolding Gamma_series_def rGamma_series_def by simp_all lemma rGamma_series_minus_of_nat: "eventually (\<lambda>n. rGamma_series (- of_nat k) n = 0) sequentially" using eventually_ge_at_top[of k] by eventually_elim (auto simp: rGamma_series_def pochhammer_of_nat_eq_0_iff) lemma Gamma_series_minus_of_nat: "eventually (\<lambda>n. Gamma_series (- of_nat k) n = 0) sequentially" using eventually_ge_at_top[of k] by eventually_elim (auto simp: Gamma_series_def pochhammer_of_nat_eq_0_iff) lemma Gamma_series'_minus_of_nat: "eventually (\<lambda>n. Gamma_series' (- of_nat k) n = 0) sequentially" using eventually_gt_at_top[of k] by eventually_elim (auto simp: Gamma_series'_def pochhammer_of_nat_eq_0_iff) lemma rGamma_series_nonpos_Ints_LIMSEQ: "z \<in> \<int>\<^sub>\<le>\<^sub>0 \<Longrightarrow> rGamma_series z \<longlonglongrightarrow> 0" by (elim nonpos_Ints_cases', hypsubst, subst tendsto_cong, rule rGamma_series_minus_of_nat, simp) lemma Gamma_series_nonpos_Ints_LIMSEQ: "z \<in> \<int>\<^sub>\<le>\<^sub>0 \<Longrightarrow> Gamma_series z \<longlonglongrightarrow> 0" by (elim nonpos_Ints_cases', hypsubst, subst tendsto_cong, rule Gamma_series_minus_of_nat, simp) lemma Gamma_series'_nonpos_Ints_LIMSEQ: "z \<in> \<int>\<^sub>\<le>\<^sub>0 \<Longrightarrow> Gamma_series' z \<longlonglongrightarrow> 0" by (elim nonpos_Ints_cases', hypsubst, subst tendsto_cong, rule Gamma_series'_minus_of_nat, simp) lemma Gamma_series_Gamma_series': assumes z: "z \<notin> \<int>\<^sub>\<le>\<^sub>0" shows "(\<lambda>n. Gamma_series' z n / Gamma_series z n) \<longlonglongrightarrow> 1" proof (rule Lim_transform_eventually) from eventually_gt_at_top[of "0::nat"] show "eventually (\<lambda>n. z / of_nat n + 1 = Gamma_series' z n / Gamma_series z n) sequentially" proof eventually_elim fix n :: nat assume n: "n > 0" from n z have "Gamma_series' z n / Gamma_series z n = (z + of_nat n) / of_nat n" by (cases n, simp) (auto simp add: Gamma_series_def Gamma_series'_def pochhammer_rec' dest: pochhammer_eq_0_imp_nonpos_Int plus_of_nat_eq_0_imp) also from n have "\<dots> = z / of_nat n + 1" by (simp add: field_split_simps) finally show "z / of_nat n + 1 = Gamma_series' z n / Gamma_series z n" .. qed have "(\<lambda>x. z / of_nat x) \<longlonglongrightarrow> 0" by (rule tendsto_norm_zero_cancel) (insert tendsto_mult[OF tendsto_const[of "norm z"] lim_inverse_n], simp add: norm_divide inverse_eq_divide) from tendsto_add[OF this tendsto_const[of 1]] show "(\<lambda>n. z / of_nat n + 1) \<longlonglongrightarrow> 1" by simp qed text \<open> We now show that the series that defines the \<open>\<Gamma>\<close> function in the Euler form converges and that the function defined by it is continuous on the complex halfspace with positive real part. We do this by showing that the logarithm of the Euler series is continuous and converges locally uniformly, which means that the log-Gamma function defined by its limit is also continuous. This will later allow us to lift holomorphicity and continuity from the log-Gamma function to the inverse of the Gamma function, and from that to the Gamma function itself. \<close> definition\<^marker>\<open>tag important\<close> ln_Gamma_series :: "('a :: {banach,real_normed_field,ln}) \<Rightarrow> nat \<Rightarrow> 'a" where "ln_Gamma_series z n = z * ln (of_nat n) - ln z - (\<Sum>k=1..n. ln (z / of_nat k + 1))" definition\<^marker>\<open>tag unimportant\<close> ln_Gamma_series' :: "('a :: {banach,real_normed_field,ln}) \<Rightarrow> nat \<Rightarrow> 'a" where "ln_Gamma_series' z n = - euler_mascheroni*z - ln z + (\<Sum>k=1..n. z / of_nat n - ln (z / of_nat k + 1))" definition ln_Gamma :: "('a :: {banach,real_normed_field,ln}) \<Rightarrow> 'a" where "ln_Gamma z = lim (ln_Gamma_series z)" text \<open> We now show that the log-Gamma series converges locally uniformly for all complex numbers except the non-positive integers. We do this by proving that the series is locally Cauchy. \<close> context begin private lemma ln_Gamma_series_complex_converges_aux: fixes z :: complex and k :: nat assumes z: "z \<noteq> 0" and k: "of_nat k \<ge> 2*norm z" "k \<ge> 2" shows "norm (z * ln (1 - 1/of_nat k) + ln (z/of_nat k + 1)) \<le> 2*(norm z + norm z^2) / of_nat k^2" proof - let ?k = "of_nat k :: complex" and ?z = "norm z" have "z *ln (1 - 1/?k) + ln (z/?k+1) = z*(ln (1 - 1/?k :: complex) + 1/?k) + (ln (1+z/?k) - z/?k)" by (simp add: algebra_simps) also have "norm ... \<le> ?z * norm (ln (1-1/?k) + 1/?k :: complex) + norm (ln (1+z/?k) - z/?k)" by (subst norm_mult [symmetric], rule norm_triangle_ineq) also have "norm (Ln (1 + -1/?k) - (-1/?k)) \<le> (norm (-1/?k))\<^sup>2 / (1 - norm(-1/?k))" using k by (intro Ln_approx_linear) (simp add: norm_divide) hence "?z * norm (ln (1-1/?k) + 1/?k) \<le> ?z * ((norm (1/?k))^2 / (1 - norm (1/?k)))" by (intro mult_left_mono) simp_all also have "... \<le> (?z * (of_nat k / (of_nat k - 1))) / of_nat k^2" using k by (simp add: field_simps power2_eq_square norm_divide) also have "... \<le> (?z * 2) / of_nat k^2" using k by (intro divide_right_mono mult_left_mono) (simp_all add: field_simps) also have "norm (ln (1+z/?k) - z/?k) \<le> norm (z/?k)^2 / (1 - norm (z/?k))" using k by (intro Ln_approx_linear) (simp add: norm_divide) hence "norm (ln (1+z/?k) - z/?k) \<le> ?z^2 / of_nat k^2 / (1 - ?z / of_nat k)" by (simp add: field_simps norm_divide) also have "... \<le> (?z^2 * (of_nat k / (of_nat k - ?z))) / of_nat k^2" using k by (simp add: field_simps power2_eq_square) also have "... \<le> (?z^2 * 2) / of_nat k^2" using k by (intro divide_right_mono mult_left_mono) (simp_all add: field_simps) also note add_divide_distrib [symmetric] finally show ?thesis by (simp only: distrib_left mult.commute) qed lemma ln_Gamma_series_complex_converges: assumes z: "z \<notin> \<int>\<^sub>\<le>\<^sub>0" assumes d: "d > 0" "\<And>n. n \<in> \<int>\<^sub>\<le>\<^sub>0 \<Longrightarrow> norm (z - of_int n) > d" shows "uniformly_convergent_on (ball z d) (\<lambda>n z. ln_Gamma_series z n :: complex)" proof (intro Cauchy_uniformly_convergent uniformly_Cauchy_onI') fix e :: real assume e: "e > 0" define e'' where "e'' = (SUP t\<in>ball z d. norm t + norm t^2)" define e' where "e' = e / (2*e'')" have "bounded ((\<lambda>t. norm t + norm t^2) ` cball z d)" by (intro compact_imp_bounded compact_continuous_image) (auto intro!: continuous_intros) hence "bounded ((\<lambda>t. norm t + norm t^2) ` ball z d)" by (rule bounded_subset) auto hence bdd: "bdd_above ((\<lambda>t. norm t + norm t^2) ` ball z d)" by (rule bounded_imp_bdd_above) with z d(1) d(2)[of "-1"] have e''_pos: "e'' > 0" unfolding e''_def by (subst less_cSUP_iff) (auto intro!: add_pos_nonneg bexI[of _ z]) have e'': "norm t + norm t^2 \<le> e''" if "t \<in> ball z d" for t unfolding e''_def using that by (rule cSUP_upper[OF _ bdd]) from e z e''_pos have e': "e' > 0" unfolding e'_def by (intro divide_pos_pos mult_pos_pos add_pos_pos) (simp_all add: field_simps) have "summable (\<lambda>k. inverse ((real_of_nat k)^2))" by (rule inverse_power_summable) simp from summable_partial_sum_bound[OF this e'] obtain M where M: "\<And>m n. M \<le> m \<Longrightarrow> norm (\<Sum>k = m..n. inverse ((real k)\<^sup>2)) < e'" by auto define N where "N = max 2 (max (nat \<lceil>2 * (norm z + d)\<rceil>) M)" { from d have "\<lceil>2 * (cmod z + d)\<rceil> \<ge> \<lceil>0::real\<rceil>" by (intro ceiling_mono mult_nonneg_nonneg add_nonneg_nonneg) simp_all hence "2 * (norm z + d) \<le> of_nat (nat \<lceil>2 * (norm z + d)\<rceil>)" unfolding N_def by (simp_all) also have "... \<le> of_nat N" unfolding N_def by (subst of_nat_le_iff) (rule max.coboundedI2, rule max.cobounded1) finally have "of_nat N \<ge> 2 * (norm z + d)" . moreover have "N \<ge> 2" "N \<ge> M" unfolding N_def by simp_all moreover have "(\<Sum>k=m..n. 1/(of_nat k)\<^sup>2) < e'" if "m \<ge> N" for m n using M[OF order.trans[OF \<open>N \<ge> M\<close> that]] unfolding real_norm_def by (subst (asm) abs_of_nonneg) (auto intro: sum_nonneg simp: field_split_simps) moreover note calculation } note N = this show "\<exists>M. \<forall>t\<in>ball z d. \<forall>m\<ge>M. \<forall>n>m. dist (ln_Gamma_series t m) (ln_Gamma_series t n) < e" unfolding dist_complex_def proof (intro exI[of _ N] ballI allI impI) fix t m n assume t: "t \<in> ball z d" and mn: "m \<ge> N" "n > m" from d(2)[of 0] t have "0 < dist z 0 - dist z t" by (simp add: field_simps dist_complex_def) also have "dist z 0 - dist z t \<le> dist 0 t" using dist_triangle[of 0 z t] by (simp add: dist_commute) finally have t_nz: "t \<noteq> 0" by auto have "norm t \<le> norm z + norm (t - z)" by (rule norm_triangle_sub) also from t have "norm (t - z) < d" by (simp add: dist_complex_def norm_minus_commute) also have "2 * (norm z + d) \<le> of_nat N" by (rule N) also have "N \<le> m" by (rule mn) finally have norm_t: "2 * norm t < of_nat m" by simp have "ln_Gamma_series t m - ln_Gamma_series t n = (-(t * Ln (of_nat n)) - (-(t * Ln (of_nat m)))) + ((\<Sum>k=1..n. Ln (t / of_nat k + 1)) - (\<Sum>k=1..m. Ln (t / of_nat k + 1)))" by (simp add: ln_Gamma_series_def algebra_simps) also have "(\<Sum>k=1..n. Ln (t / of_nat k + 1)) - (\<Sum>k=1..m. Ln (t / of_nat k + 1)) = (\<Sum>k\<in>{1..n}-{1..m}. Ln (t / of_nat k + 1))" using mn by (simp add: sum_diff) also from mn have "{1..n}-{1..m} = {Suc m..n}" by fastforce also have "-(t * Ln (of_nat n)) - (-(t * Ln (of_nat m))) = (\<Sum>k = Suc m..n. t * Ln (of_nat (k - 1)) - t * Ln (of_nat k))" using mn by (subst sum_telescope'' [symmetric]) simp_all also have "... = (\<Sum>k = Suc m..n. t * Ln (of_nat (k - 1) / of_nat k))" using mn N by (intro sum_cong_Suc) (simp_all del: of_nat_Suc add: field_simps Ln_of_nat Ln_of_nat_over_of_nat) also have "of_nat (k - 1) / of_nat k = 1 - 1 / (of_nat k :: complex)" if "k \<in> {Suc m..n}" for k using that of_nat_eq_0_iff[of "Suc i" for i] by (cases k) (simp_all add: field_split_simps) hence "(\<Sum>k = Suc m..n. t * Ln (of_nat (k - 1) / of_nat k)) = (\<Sum>k = Suc m..n. t * Ln (1 - 1 / of_nat k))" using mn N by (intro sum.cong) simp_all also note sum.distrib [symmetric] also have "norm (\<Sum>k=Suc m..n. t * Ln (1 - 1/of_nat k) + Ln (t/of_nat k + 1)) \<le> (\<Sum>k=Suc m..n. 2 * (norm t + (norm t)\<^sup>2) / (real_of_nat k)\<^sup>2)" using t_nz N(2) mn norm_t by (intro order.trans[OF norm_sum sum_mono[OF ln_Gamma_series_complex_converges_aux]]) simp_all also have "... \<le> 2 * (norm t + norm t^2) * (\<Sum>k=Suc m..n. 1 / (of_nat k)\<^sup>2)" by (simp add: sum_distrib_left) also have "... < 2 * (norm t + norm t^2) * e'" using mn z t_nz by (intro mult_strict_left_mono N mult_pos_pos add_pos_pos) simp_all also from e''_pos have "... = e * ((cmod t + (cmod t)\<^sup>2) / e'')" by (simp add: e'_def field_simps power2_eq_square) also from e''[OF t] e''_pos e have "\<dots> \<le> e * 1" by (intro mult_left_mono) (simp_all add: field_simps) finally show "norm (ln_Gamma_series t m - ln_Gamma_series t n) < e" by simp qed qed end lemma ln_Gamma_series_complex_converges': assumes z: "(z :: complex) \<notin> \<int>\<^sub>\<le>\<^sub>0" shows "\<exists>d>0. uniformly_convergent_on (ball z d) (\<lambda>n z. ln_Gamma_series z n)" proof - define d' where "d' = Re z" define d where "d = (if d' > 0 then d' / 2 else norm (z - of_int (round d')) / 2)" have "of_int (round d') \<in> \<int>\<^sub>\<le>\<^sub>0" if "d' \<le> 0" using that by (intro nonpos_Ints_of_int) (simp_all add: round_def) with assms have d_pos: "d > 0" unfolding d_def by (force simp: not_less) have "d < cmod (z - of_int n)" if "n \<in> \<int>\<^sub>\<le>\<^sub>0" for n proof (cases "Re z > 0") case True from nonpos_Ints_nonpos[OF that] have n: "n \<le> 0" by simp from True have "d = Re z/2" by (simp add: d_def d'_def) also from n True have "\<dots> < Re (z - of_int n)" by simp also have "\<dots> \<le> norm (z - of_int n)" by (rule complex_Re_le_cmod) finally show ?thesis . next case False with assms nonpos_Ints_of_int[of "round (Re z)"] have "z \<noteq> of_int (round d')" by (auto simp: not_less) with False have "d < norm (z - of_int (round d'))" by (simp add: d_def d'_def) also have "\<dots> \<le> norm (z - of_int n)" unfolding d'_def by (rule round_Re_minimises_norm) finally show ?thesis . qed hence conv: "uniformly_convergent_on (ball z d) (\<lambda>n z. ln_Gamma_series z n)" by (intro ln_Gamma_series_complex_converges d_pos z) simp_all from d_pos conv show ?thesis by blast qed lemma ln_Gamma_series_complex_converges'': "(z :: complex) \<notin> \<int>\<^sub>\<le>\<^sub>0 \<Longrightarrow> convergent (ln_Gamma_series z)" by (drule ln_Gamma_series_complex_converges') (auto intro: uniformly_convergent_imp_convergent) theorem ln_Gamma_complex_LIMSEQ: "(z :: complex) \<notin> \<int>\<^sub>\<le>\<^sub>0 \<Longrightarrow> ln_Gamma_series z \<longlonglongrightarrow> ln_Gamma z" using ln_Gamma_series_complex_converges'' by (simp add: convergent_LIMSEQ_iff ln_Gamma_def) lemma exp_ln_Gamma_series_complex: assumes "n > 0" "z \<notin> \<int>\<^sub>\<le>\<^sub>0" shows "exp (ln_Gamma_series z n :: complex) = Gamma_series z n" proof - from assms obtain m where m: "n = Suc m" by (cases n) blast from assms have "z \<noteq> 0" by (intro notI) auto with assms have "exp (ln_Gamma_series z n) = (of_nat n) powr z / (z * (\<Prod>k=1..n. exp (Ln (z / of_nat k + 1))))" unfolding ln_Gamma_series_def powr_def by (simp add: exp_diff exp_sum) also from assms have "(\<Prod>k=1..n. exp (Ln (z / of_nat k + 1))) = (\<Prod>k=1..n. z / of_nat k + 1)" by (intro prod.cong[OF refl], subst exp_Ln) (auto simp: field_simps plus_of_nat_eq_0_imp) also have "... = (\<Prod>k=1..n. z + k) / fact n" by (simp add: fact_prod) (subst prod_dividef [symmetric], simp_all add: field_simps) also from m have "z * ... = (\<Prod>k=0..n. z + k) / fact n" by (simp add: prod.atLeast0_atMost_Suc_shift prod.atLeast_Suc_atMost_Suc_shift del: prod.cl_ivl_Suc) also have "(\<Prod>k=0..n. z + k) = pochhammer z (Suc n)" unfolding pochhammer_prod by (simp add: prod.atLeast0_atMost_Suc atLeastLessThanSuc_atLeastAtMost) also have "of_nat n powr z / (pochhammer z (Suc n) / fact n) = Gamma_series z n" unfolding Gamma_series_def using assms by (simp add: field_split_simps powr_def) finally show ?thesis . qed lemma ln_Gamma_series'_aux: assumes "(z::complex) \<notin> \<int>\<^sub>\<le>\<^sub>0" shows "(\<lambda>k. z / of_nat (Suc k) - ln (1 + z / of_nat (Suc k))) sums (ln_Gamma z + euler_mascheroni * z + ln z)" (is "?f sums ?s") unfolding sums_def proof (rule Lim_transform) show "(\<lambda>n. ln_Gamma_series z n + of_real (harm n - ln (of_nat n)) * z + ln z) \<longlonglongrightarrow> ?s" (is "?g \<longlonglongrightarrow> _") by (intro tendsto_intros ln_Gamma_complex_LIMSEQ euler_mascheroni_LIMSEQ_of_real assms) have A: "eventually (\<lambda>n. (\<Sum>k<n. ?f k) - ?g n = 0) sequentially" using eventually_gt_at_top[of "0::nat"] proof eventually_elim fix n :: nat assume n: "n > 0" have "(\<Sum>k<n. ?f k) = (\<Sum>k=1..n. z / of_nat k - ln (1 + z / of_nat k))" by (subst atLeast0LessThan [symmetric], subst sum.shift_bounds_Suc_ivl [symmetric], subst atLeastLessThanSuc_atLeastAtMost) simp_all also have "\<dots> = z * of_real (harm n) - (\<Sum>k=1..n. ln (1 + z / of_nat k))" by (simp add: harm_def sum_subtractf sum_distrib_left divide_inverse) also from n have "\<dots> - ?g n = 0" by (simp add: ln_Gamma_series_def sum_subtractf algebra_simps) finally show "(\<Sum>k<n. ?f k) - ?g n = 0" . qed show "(\<lambda>n. (\<Sum>k<n. ?f k) - ?g n) \<longlonglongrightarrow> 0" by (subst tendsto_cong[OF A]) simp_all qed lemma uniformly_summable_deriv_ln_Gamma: assumes z: "(z :: 'a :: {real_normed_field,banach}) \<noteq> 0" and d: "d > 0" "d \<le> norm z/2" shows "uniformly_convergent_on (ball z d) (\<lambda>k z. \<Sum>i<k. inverse (of_nat (Suc i)) - inverse (z + of_nat (Suc i)))" (is "uniformly_convergent_on _ (\<lambda>k z. \<Sum>i<k. ?f i z)") proof (rule Weierstrass_m_test'_ev) { fix t assume t: "t \<in> ball z d" have "norm z = norm (t + (z - t))" by simp have "norm (t + (z - t)) \<le> norm t + norm (z - t)" by (rule norm_triangle_ineq) also from t d have "norm (z - t) < norm z / 2" by (simp add: dist_norm) finally have A: "norm t > norm z / 2" using z by (simp add: field_simps) have "norm t = norm (z + (t - z))" by simp also have "\<dots> \<le> norm z + norm (t - z)" by (rule norm_triangle_ineq) also from t d have "norm (t - z) \<le> norm z / 2" by (simp add: dist_norm norm_minus_commute) also from z have "\<dots> < norm z" by simp finally have B: "norm t < 2 * norm z" by simp note A B } note ball = this show "eventually (\<lambda>n. \<forall>t\<in>ball z d. norm (?f n t) \<le> 4 * norm z * inverse (of_nat (Suc n)^2)) sequentially" using eventually_gt_at_top apply eventually_elim proof safe fix t :: 'a assume t: "t \<in> ball z d" from z ball[OF t] have t_nz: "t \<noteq> 0" by auto fix n :: nat assume n: "n > nat \<lceil>4 * norm z\<rceil>" from ball[OF t] t_nz have "4 * norm z > 2 * norm t" by simp also from n have "\<dots> < of_nat n" by linarith finally have n: "of_nat n > 2 * norm t" . hence "of_nat n > norm t" by simp hence t': "t \<noteq> -of_nat (Suc n)" by (intro notI) (simp del: of_nat_Suc) with t_nz have "?f n t = 1 / (of_nat (Suc n) * (1 + of_nat (Suc n)/t))" by (simp add: field_split_simps eq_neg_iff_add_eq_0 del: of_nat_Suc) also have "norm \<dots> = inverse (of_nat (Suc n)) * inverse (norm (of_nat (Suc n)/t + 1))" by (simp add: norm_divide norm_mult field_split_simps del: of_nat_Suc) also { from z t_nz ball[OF t] have "of_nat (Suc n) / (4 * norm z) \<le> of_nat (Suc n) / (2 * norm t)" by (intro divide_left_mono mult_pos_pos) simp_all also have "\<dots> < norm (of_nat (Suc n) / t) - norm (1 :: 'a)" using t_nz n by (simp add: field_simps norm_divide del: of_nat_Suc) also have "\<dots> \<le> norm (of_nat (Suc n)/t + 1)" by (rule norm_diff_ineq) finally have "inverse (norm (of_nat (Suc n)/t + 1)) \<le> 4 * norm z / of_nat (Suc n)" using z by (simp add: field_split_simps norm_divide mult_ac del: of_nat_Suc) } also have "inverse (real_of_nat (Suc n)) * (4 * norm z / real_of_nat (Suc n)) = 4 * norm z * inverse (of_nat (Suc n)^2)" by (simp add: field_split_simps power2_eq_square del: of_nat_Suc) finally show "norm (?f n t) \<le> 4 * norm z * inverse (of_nat (Suc n)^2)" by (simp del: of_nat_Suc) qed next show "summable (\<lambda>n. 4 * norm z * inverse ((of_nat (Suc n))^2))" by (subst summable_Suc_iff) (simp add: summable_mult inverse_power_summable) qed subsection \<open>The Polygamma functions\<close> lemma summable_deriv_ln_Gamma: "z \<noteq> (0 :: 'a :: {real_normed_field,banach}) \<Longrightarrow> summable (\<lambda>n. inverse (of_nat (Suc n)) - inverse (z + of_nat (Suc n)))" unfolding summable_iff_convergent by (rule uniformly_convergent_imp_convergent, rule uniformly_summable_deriv_ln_Gamma[of z "norm z/2"]) simp_all definition\<^marker>\<open>tag important\<close> Polygamma :: "nat \<Rightarrow> ('a :: {real_normed_field,banach}) \<Rightarrow> 'a" where "Polygamma n z = (if n = 0 then (\<Sum>k. inverse (of_nat (Suc k)) - inverse (z + of_nat k)) - euler_mascheroni else (-1)^Suc n * fact n * (\<Sum>k. inverse ((z + of_nat k)^Suc n)))" abbreviation\<^marker>\<open>tag important\<close> Digamma :: "('a :: {real_normed_field,banach}) \<Rightarrow> 'a" where "Digamma \<equiv> Polygamma 0" lemma Digamma_def: "Digamma z = (\<Sum>k. inverse (of_nat (Suc k)) - inverse (z + of_nat k)) - euler_mascheroni" by (simp add: Polygamma_def) lemma summable_Digamma: assumes "(z :: 'a :: {real_normed_field,banach}) \<noteq> 0" shows "summable (\<lambda>n. inverse (of_nat (Suc n)) - inverse (z + of_nat n))" proof - have sums: "(\<lambda>n. inverse (z + of_nat (Suc n)) - inverse (z + of_nat n)) sums (0 - inverse (z + of_nat 0))" by (intro telescope_sums filterlim_compose[OF tendsto_inverse_0] tendsto_add_filterlim_at_infinity[OF tendsto_const] tendsto_of_nat) from summable_add[OF summable_deriv_ln_Gamma[OF assms] sums_summable[OF sums]] show "summable (\<lambda>n. inverse (of_nat (Suc n)) - inverse (z + of_nat n))" by simp qed lemma summable_offset: assumes "summable (\<lambda>n. f (n + k) :: 'a :: real_normed_vector)" shows "summable f" proof - from assms have "convergent (\<lambda>m. \<Sum>n<m. f (n + k))" using summable_iff_convergent by blast hence "convergent (\<lambda>m. (\<Sum>n<k. f n) + (\<Sum>n<m. f (n + k)))" by (intro convergent_add convergent_const) also have "(\<lambda>m. (\<Sum>n<k. f n) + (\<Sum>n<m. f (n + k))) = (\<lambda>m. \<Sum>n<m+k. f n)" proof fix m :: nat have "{..<m+k} = {..<k} \<union> {k..<m+k}" by auto also have "(\<Sum>n\<in>\<dots>. f n) = (\<Sum>n<k. f n) + (\<Sum>n=k..<m+k. f n)" by (rule sum.union_disjoint) auto also have "(\<Sum>n=k..<m+k. f n) = (\<Sum>n=0..<m+k-k. f (n + k))" using sum.shift_bounds_nat_ivl [of f 0 k m] by simp finally show "(\<Sum>n<k. f n) + (\<Sum>n<m. f (n + k)) = (\<Sum>n<m+k. f n)" by (simp add: atLeast0LessThan) qed finally have "(\<lambda>a. sum f {..<a}) \<longlonglongrightarrow> lim (\<lambda>m. sum f {..<m + k})" by (auto simp: convergent_LIMSEQ_iff dest: LIMSEQ_offset) thus ?thesis by (auto simp: summable_iff_convergent convergent_def) qed lemma Polygamma_converges: fixes z :: "'a :: {real_normed_field,banach}" assumes z: "z \<noteq> 0" and n: "n \<ge> 2" shows "uniformly_convergent_on (ball z d) (\<lambda>k z. \<Sum>i<k. inverse ((z + of_nat i)^n))" proof (rule Weierstrass_m_test'_ev) define e where "e = (1 + d / norm z)" define m where "m = nat \<lceil>norm z * e\<rceil>" { fix t assume t: "t \<in> ball z d" have "norm t = norm (z + (t - z))" by simp also have "\<dots> \<le> norm z + norm (t - z)" by (rule norm_triangle_ineq) also from t have "norm (t - z) < d" by (simp add: dist_norm norm_minus_commute) finally have "norm t < norm z * e" using z by (simp add: divide_simps e_def) } note ball = this show "eventually (\<lambda>k. \<forall>t\<in>ball z d. norm (inverse ((t + of_nat k)^n)) \<le> inverse (of_nat (k - m)^n)) sequentially" using eventually_gt_at_top[of m] apply eventually_elim proof (intro ballI) fix k :: nat and t :: 'a assume k: "k > m" and t: "t \<in> ball z d" from k have "real_of_nat (k - m) = of_nat k - of_nat m" by (simp add: of_nat_diff) also have "\<dots> \<le> norm (of_nat k :: 'a) - norm z * e" unfolding m_def by (subst norm_of_nat) linarith also from ball[OF t] have "\<dots> \<le> norm (of_nat k :: 'a) - norm t" by simp also have "\<dots> \<le> norm (of_nat k + t)" by (rule norm_diff_ineq) finally have "inverse ((norm (t + of_nat k))^n) \<le> inverse (real_of_nat (k - m)^n)" using k n by (intro le_imp_inverse_le power_mono) (simp_all add: add_ac del: of_nat_Suc) thus "norm (inverse ((t + of_nat k)^n)) \<le> inverse (of_nat (k - m)^n)" by (simp add: norm_inverse norm_power power_inverse) qed have "summable (\<lambda>k. inverse ((real_of_nat k)^n))" using inverse_power_summable[of n] n by simp hence "summable (\<lambda>k. inverse ((real_of_nat (k + m - m))^n))" by simp thus "summable (\<lambda>k. inverse ((real_of_nat (k - m))^n))" by (rule summable_offset) qed lemma Polygamma_converges': fixes z :: "'a :: {real_normed_field,banach}" assumes z: "z \<noteq> 0" and n: "n \<ge> 2" shows "summable (\<lambda>k. inverse ((z + of_nat k)^n))" using uniformly_convergent_imp_convergent[OF Polygamma_converges[OF assms, of 1], of z] by (simp add: summable_iff_convergent) theorem Digamma_LIMSEQ: fixes z :: "'a :: {banach,real_normed_field}" assumes z: "z \<noteq> 0" shows "(\<lambda>m. of_real (ln (real m)) - (\<Sum>n<m. inverse (z + of_nat n))) \<longlonglongrightarrow> Digamma z" proof - have "(\<lambda>n. of_real (ln (real n / (real (Suc n))))) \<longlonglongrightarrow> (of_real (ln 1) :: 'a)" by (intro tendsto_intros LIMSEQ_n_over_Suc_n) simp_all hence "(\<lambda>n. of_real (ln (real n / (real n + 1)))) \<longlonglongrightarrow> (0 :: 'a)" by (simp add: add_ac) hence lim: "(\<lambda>n. of_real (ln (real n)) - of_real (ln (real n + 1))) \<longlonglongrightarrow> (0::'a)" proof (rule Lim_transform_eventually) show "eventually (\<lambda>n. of_real (ln (real n / (real n + 1))) = of_real (ln (real n)) - (of_real (ln (real n + 1)) :: 'a)) at_top" using eventually_gt_at_top[of "0::nat"] by eventually_elim (simp add: ln_div) qed from summable_Digamma[OF z] have "(\<lambda>n. inverse (of_nat (n+1)) - inverse (z + of_nat n)) sums (Digamma z + euler_mascheroni)" by (simp add: Digamma_def summable_sums) from sums_diff[OF this euler_mascheroni_sum] have "(\<lambda>n. of_real (ln (real (Suc n) + 1)) - of_real (ln (real n + 1)) - inverse (z + of_nat n)) sums Digamma z" by (simp add: add_ac) hence "(\<lambda>m. (\<Sum>n<m. of_real (ln (real (Suc n) + 1)) - of_real (ln (real n + 1))) - (\<Sum>n<m. inverse (z + of_nat n))) \<longlonglongrightarrow> Digamma z" by (simp add: sums_def sum_subtractf) also have "(\<lambda>m. (\<Sum>n<m. of_real (ln (real (Suc n) + 1)) - of_real (ln (real n + 1)))) = (\<lambda>m. of_real (ln (m + 1)) :: 'a)" by (subst sum_lessThan_telescope) simp_all finally show ?thesis by (rule Lim_transform) (insert lim, simp) qed theorem Polygamma_LIMSEQ: fixes z :: "'a :: {banach,real_normed_field}" assumes "z \<noteq> 0" and "n > 0" shows "(\<lambda>k. inverse ((z + of_nat k)^Suc n)) sums ((-1) ^ Suc n * Polygamma n z / fact n)" using Polygamma_converges'[OF assms(1), of "Suc n"] assms(2) by (simp add: sums_iff Polygamma_def) theorem has_field_derivative_ln_Gamma_complex [derivative_intros]: fixes z :: complex assumes z: "z \<notin> \<real>\<^sub>\<le>\<^sub>0" shows "(ln_Gamma has_field_derivative Digamma z) (at z)" proof - have not_nonpos_Int [simp]: "t \<notin> \<int>\<^sub>\<le>\<^sub>0" if "Re t > 0" for t using that by (auto elim!: nonpos_Ints_cases') from z have z': "z \<notin> \<int>\<^sub>\<le>\<^sub>0" and z'': "z \<noteq> 0" using nonpos_Ints_subset_nonpos_Reals nonpos_Reals_zero_I by blast+ let ?f' = "\<lambda>z k. inverse (of_nat (Suc k)) - inverse (z + of_nat (Suc k))" let ?f = "\<lambda>z k. z / of_nat (Suc k) - ln (1 + z / of_nat (Suc k))" and ?F' = "\<lambda>z. \<Sum>n. ?f' z n" define d where "d = min (norm z/2) (if Im z = 0 then Re z / 2 else abs (Im z) / 2)" from z have d: "d > 0" "norm z/2 \<ge> d" by (auto simp add: complex_nonpos_Reals_iff d_def) have ball: "Im t = 0 \<longrightarrow> Re t > 0" if "dist z t < d" for t using no_nonpos_Real_in_ball[OF z, of t] that unfolding d_def by (force simp add: complex_nonpos_Reals_iff) have sums: "(\<lambda>n. inverse (z + of_nat (Suc n)) - inverse (z + of_nat n)) sums (0 - inverse (z + of_nat 0))" by (intro telescope_sums filterlim_compose[OF tendsto_inverse_0] tendsto_add_filterlim_at_infinity[OF tendsto_const] tendsto_of_nat) have "((\<lambda>z. \<Sum>n. ?f z n) has_field_derivative ?F' z) (at z)" using d z ln_Gamma_series'_aux[OF z'] apply (intro has_field_derivative_series'(2)[of "ball z d" _ _ z] uniformly_summable_deriv_ln_Gamma) apply (auto intro!: derivative_eq_intros add_pos_pos mult_pos_pos dest!: ball simp: field_simps sums_iff nonpos_Reals_divide_of_nat_iff simp del: of_nat_Suc) apply (auto simp add: complex_nonpos_Reals_iff) done with z have "((\<lambda>z. (\<Sum>k. ?f z k) - euler_mascheroni * z - Ln z) has_field_derivative ?F' z - euler_mascheroni - inverse z) (at z)" by (force intro!: derivative_eq_intros simp: Digamma_def) also have "?F' z - euler_mascheroni - inverse z = (?F' z + -inverse z) - euler_mascheroni" by simp also from sums have "-inverse z = (\<Sum>n. inverse (z + of_nat (Suc n)) - inverse (z + of_nat n))" by (simp add: sums_iff) also from sums summable_deriv_ln_Gamma[OF z''] have "?F' z + \<dots> = (\<Sum>n. inverse (of_nat (Suc n)) - inverse (z + of_nat n))" by (subst suminf_add) (simp_all add: add_ac sums_iff) also have "\<dots> - euler_mascheroni = Digamma z" by (simp add: Digamma_def) finally have "((\<lambda>z. (\<Sum>k. ?f z k) - euler_mascheroni * z - Ln z) has_field_derivative Digamma z) (at z)" . moreover from eventually_nhds_ball[OF d(1), of z] have "eventually (\<lambda>z. ln_Gamma z = (\<Sum>k. ?f z k) - euler_mascheroni * z - Ln z) (nhds z)" proof eventually_elim fix t assume "t \<in> ball z d" hence "t \<notin> \<int>\<^sub>\<le>\<^sub>0" by (auto dest!: ball elim!: nonpos_Ints_cases) from ln_Gamma_series'_aux[OF this] show "ln_Gamma t = (\<Sum>k. ?f t k) - euler_mascheroni * t - Ln t" by (simp add: sums_iff) qed ultimately show ?thesis by (subst DERIV_cong_ev[OF refl _ refl]) qed declare has_field_derivative_ln_Gamma_complex[THEN DERIV_chain2, derivative_intros] lemma Digamma_1 [simp]: "Digamma (1 :: 'a :: {real_normed_field,banach}) = - euler_mascheroni" by (simp add: Digamma_def) lemma Digamma_plus1: assumes "z \<noteq> 0" shows "Digamma (z+1) = Digamma z + 1/z" proof - have sums: "(\<lambda>k. inverse (z + of_nat k) - inverse (z + of_nat (Suc k))) sums (inverse (z + of_nat 0) - 0)" by (intro telescope_sums'[OF filterlim_compose[OF tendsto_inverse_0]] tendsto_add_filterlim_at_infinity[OF tendsto_const] tendsto_of_nat) have "Digamma (z+1) = (\<Sum>k. inverse (of_nat (Suc k)) - inverse (z + of_nat (Suc k))) - euler_mascheroni" (is "_ = suminf ?f - _") by (simp add: Digamma_def add_ac) also have "suminf ?f = (\<Sum>k. inverse (of_nat (Suc k)) - inverse (z + of_nat k)) + (\<Sum>k. inverse (z + of_nat k) - inverse (z + of_nat (Suc k)))" using summable_Digamma[OF assms] sums by (subst suminf_add) (simp_all add: add_ac sums_iff) also have "(\<Sum>k. inverse (z + of_nat k) - inverse (z + of_nat (Suc k))) = 1/z" using sums by (simp add: sums_iff inverse_eq_divide) finally show ?thesis by (simp add: Digamma_def[of z]) qed theorem Polygamma_plus1: assumes "z \<noteq> 0" shows "Polygamma n (z + 1) = Polygamma n z + (-1)^n * fact n / (z ^ Suc n)" proof (cases "n = 0") assume n: "n \<noteq> 0" let ?f = "\<lambda>k. inverse ((z + of_nat k) ^ Suc n)" have "Polygamma n (z + 1) = (-1) ^ Suc n * fact n * (\<Sum>k. ?f (k+1))" using n by (simp add: Polygamma_def add_ac) also have "(\<Sum>k. ?f (k+1)) + (\<Sum>k<1. ?f k) = (\<Sum>k. ?f k)" using Polygamma_converges'[OF assms, of "Suc n"] n by (subst suminf_split_initial_segment [symmetric]) simp_all hence "(\<Sum>k. ?f (k+1)) = (\<Sum>k. ?f k) - inverse (z ^ Suc n)" by (simp add: algebra_simps) also have "(-1) ^ Suc n * fact n * ((\<Sum>k. ?f k) - inverse (z ^ Suc n)) = Polygamma n z + (-1)^n * fact n / (z ^ Suc n)" using n by (simp add: inverse_eq_divide algebra_simps Polygamma_def) finally show ?thesis . qed (insert assms, simp add: Digamma_plus1 inverse_eq_divide) theorem Digamma_of_nat: "Digamma (of_nat (Suc n) :: 'a :: {real_normed_field,banach}) = harm n - euler_mascheroni" proof (induction n) case (Suc n) have "Digamma (of_nat (Suc (Suc n)) :: 'a) = Digamma (of_nat (Suc n) + 1)" by simp also have "\<dots> = Digamma (of_nat (Suc n)) + inverse (of_nat (Suc n))" by (subst Digamma_plus1) (simp_all add: inverse_eq_divide del: of_nat_Suc) also have "Digamma (of_nat (Suc n) :: 'a) = harm n - euler_mascheroni " by (rule Suc) also have "\<dots> + inverse (of_nat (Suc n)) = harm (Suc n) - euler_mascheroni" by (simp add: harm_Suc) finally show ?case . qed (simp add: harm_def) lemma Digamma_numeral: "Digamma (numeral n) = harm (pred_numeral n) - euler_mascheroni" by (subst of_nat_numeral[symmetric], subst numeral_eq_Suc, subst Digamma_of_nat) (rule refl) lemma Polygamma_of_real: "x \<noteq> 0 \<Longrightarrow> Polygamma n (of_real x) = of_real (Polygamma n x)" unfolding Polygamma_def using summable_Digamma[of x] Polygamma_converges'[of x "Suc n"] by (simp_all add: suminf_of_real) lemma Polygamma_Real: "z \<in> \<real> \<Longrightarrow> z \<noteq> 0 \<Longrightarrow> Polygamma n z \<in> \<real>" by (elim Reals_cases, hypsubst, subst Polygamma_of_real) simp_all lemma Digamma_half_integer: "Digamma (of_nat n + 1/2 :: 'a :: {real_normed_field,banach}) = (\<Sum>k<n. 2 / (of_nat (2*k+1))) - euler_mascheroni - of_real (2 * ln 2)" proof (induction n) case 0 have "Digamma (1/2 :: 'a) = of_real (Digamma (1/2))" by (simp add: Polygamma_of_real [symmetric]) also have "Digamma (1/2::real) = (\<Sum>k. inverse (of_nat (Suc k)) - inverse (of_nat k + 1/2)) - euler_mascheroni" by (simp add: Digamma_def add_ac) also have "(\<Sum>k. inverse (of_nat (Suc k) :: real) - inverse (of_nat k + 1/2)) = (\<Sum>k. inverse (1/2) * (inverse (2 * of_nat (Suc k)) - inverse (2 * of_nat k + 1)))" by (simp_all add: add_ac inverse_mult_distrib[symmetric] ring_distribs del: inverse_divide) also have "\<dots> = - 2 * ln 2" using sums_minus[OF alternating_harmonic_series_sums'] by (subst suminf_mult) (simp_all add: algebra_simps sums_iff) finally show ?case by simp next case (Suc n) have nz: "2 * of_nat n + (1:: 'a) \<noteq> 0" using of_nat_neq_0[of "2*n"] by (simp only: of_nat_Suc) (simp add: add_ac) hence nz': "of_nat n + (1/2::'a) \<noteq> 0" by (simp add: field_simps) have "Digamma (of_nat (Suc n) + 1/2 :: 'a) = Digamma (of_nat n + 1/2 + 1)" by simp also from nz' have "\<dots> = Digamma (of_nat n + 1/2) + 1 / (of_nat n + 1/2)" by (rule Digamma_plus1) also from nz nz' have "1 / (of_nat n + 1/2 :: 'a) = 2 / (2 * of_nat n + 1)" by (subst divide_eq_eq) simp_all also note Suc finally show ?case by (simp add: add_ac) qed lemma Digamma_one_half: "Digamma (1/2) = - euler_mascheroni - of_real (2 * ln 2)" using Digamma_half_integer[of 0] by simp lemma Digamma_real_three_halves_pos: "Digamma (3/2 :: real) > 0" proof - have "-Digamma (3/2 :: real) = -Digamma (of_nat 1 + 1/2)" by simp also have "\<dots> = 2 * ln 2 + euler_mascheroni - 2" by (subst Digamma_half_integer) simp also note euler_mascheroni_less_13_over_22 also note ln2_le_25_over_36 finally show ?thesis by simp qed theorem has_field_derivative_Polygamma [derivative_intros]: fixes z :: "'a :: {real_normed_field,euclidean_space}" assumes z: "z \<notin> \<int>\<^sub>\<le>\<^sub>0" shows "(Polygamma n has_field_derivative Polygamma (Suc n) z) (at z within A)" proof (rule has_field_derivative_at_within, cases "n = 0") assume n: "n = 0" let ?f = "\<lambda>k z. inverse (of_nat (Suc k)) - inverse (z + of_nat k)" let ?F = "\<lambda>z. \<Sum>k. ?f k z" and ?f' = "\<lambda>k z. inverse ((z + of_nat k)\<^sup>2)" from no_nonpos_Int_in_ball'[OF z] obtain d where d: "0 < d" "\<And>t. t \<in> ball z d \<Longrightarrow> t \<notin> \<int>\<^sub>\<le>\<^sub>0" by auto from z have summable: "summable (\<lambda>k. inverse (of_nat (Suc k)) - inverse (z + of_nat k))" by (intro summable_Digamma) force from z have conv: "uniformly_convergent_on (ball z d) (\<lambda>k z. \<Sum>i<k. inverse ((z + of_nat i)\<^sup>2))" by (intro Polygamma_converges) auto with d have "summable (\<lambda>k. inverse ((z + of_nat k)\<^sup>2))" unfolding summable_iff_convergent by (auto dest!: uniformly_convergent_imp_convergent simp: summable_iff_convergent ) have "(?F has_field_derivative (\<Sum>k. ?f' k z)) (at z)" proof (rule has_field_derivative_series'[of "ball z d" _ _ z]) fix k :: nat and t :: 'a assume t: "t \<in> ball z d" from t d(2)[of t] show "((\<lambda>z. ?f k z) has_field_derivative ?f' k t) (at t within ball z d)" by (auto intro!: derivative_eq_intros simp: power2_eq_square simp del: of_nat_Suc dest!: plus_of_nat_eq_0_imp elim!: nonpos_Ints_cases) qed (insert d(1) summable conv, (assumption|simp)+) with z show "(Polygamma n has_field_derivative Polygamma (Suc n) z) (at z)" unfolding Digamma_def [abs_def] Polygamma_def [abs_def] using n by (force simp: power2_eq_square intro!: derivative_eq_intros) next assume n: "n \<noteq> 0" from z have z': "z \<noteq> 0" by auto from no_nonpos_Int_in_ball'[OF z] obtain d where d: "0 < d" "\<And>t. t \<in> ball z d \<Longrightarrow> t \<notin> \<int>\<^sub>\<le>\<^sub>0" by auto define n' where "n' = Suc n" from n have n': "n' \<ge> 2" by (simp add: n'_def) have "((\<lambda>z. \<Sum>k. inverse ((z + of_nat k) ^ n')) has_field_derivative (\<Sum>k. - of_nat n' * inverse ((z + of_nat k) ^ (n'+1)))) (at z)" proof (rule has_field_derivative_series'[of "ball z d" _ _ z]) fix k :: nat and t :: 'a assume t: "t \<in> ball z d" with d have t': "t \<notin> \<int>\<^sub>\<le>\<^sub>0" "t \<noteq> 0" by auto show "((\<lambda>a. inverse ((a + of_nat k) ^ n')) has_field_derivative - of_nat n' * inverse ((t + of_nat k) ^ (n'+1))) (at t within ball z d)" using t' by (fastforce intro!: derivative_eq_intros simp: divide_simps power_diff dest: plus_of_nat_eq_0_imp) next have "uniformly_convergent_on (ball z d) (\<lambda>k z. (- of_nat n' :: 'a) * (\<Sum>i<k. inverse ((z + of_nat i) ^ (n'+1))))" using z' n by (intro uniformly_convergent_mult Polygamma_converges) (simp_all add: n'_def) thus "uniformly_convergent_on (ball z d) (\<lambda>k z. \<Sum>i<k. - of_nat n' * inverse ((z + of_nat i :: 'a) ^ (n'+1)))" by (subst (asm) sum_distrib_left) simp qed (insert Polygamma_converges'[OF z' n'] d, simp_all) also have "(\<Sum>k. - of_nat n' * inverse ((z + of_nat k) ^ (n' + 1))) = (- of_nat n') * (\<Sum>k. inverse ((z + of_nat k) ^ (n' + 1)))" using Polygamma_converges'[OF z', of "n'+1"] n' by (subst suminf_mult) simp_all finally have "((\<lambda>z. \<Sum>k. inverse ((z + of_nat k) ^ n')) has_field_derivative - of_nat n' * (\<Sum>k. inverse ((z + of_nat k) ^ (n' + 1)))) (at z)" . from DERIV_cmult[OF this, of "(-1)^Suc n * fact n :: 'a"] show "(Polygamma n has_field_derivative Polygamma (Suc n) z) (at z)" unfolding n'_def Polygamma_def[abs_def] using n by (simp add: algebra_simps) qed declare has_field_derivative_Polygamma[THEN DERIV_chain2, derivative_intros] lemma isCont_Polygamma [continuous_intros]: fixes f :: "_ \<Rightarrow> 'a :: {real_normed_field,euclidean_space}" shows "isCont f z \<Longrightarrow> f z \<notin> \<int>\<^sub>\<le>\<^sub>0 \<Longrightarrow> isCont (\<lambda>x. Polygamma n (f x)) z" by (rule isCont_o2[OF _ DERIV_isCont[OF has_field_derivative_Polygamma]]) lemma continuous_on_Polygamma: "A \<inter> \<int>\<^sub>\<le>\<^sub>0 = {} \<Longrightarrow> continuous_on A (Polygamma n :: _ \<Rightarrow> 'a :: {real_normed_field,euclidean_space})" by (intro continuous_at_imp_continuous_on isCont_Polygamma[OF continuous_ident] ballI) blast lemma isCont_ln_Gamma_complex [continuous_intros]: fixes f :: "'a::t2_space \<Rightarrow> complex" shows "isCont f z \<Longrightarrow> f z \<notin> \<real>\<^sub>\<le>\<^sub>0 \<Longrightarrow> isCont (\<lambda>z. ln_Gamma (f z)) z" by (rule isCont_o2[OF _ DERIV_isCont[OF has_field_derivative_ln_Gamma_complex]]) lemma continuous_on_ln_Gamma_complex [continuous_intros]: fixes A :: "complex set" shows "A \<inter> \<real>\<^sub>\<le>\<^sub>0 = {} \<Longrightarrow> continuous_on A ln_Gamma" by (intro continuous_at_imp_continuous_on ballI isCont_ln_Gamma_complex[OF continuous_ident]) fastforce lemma deriv_Polygamma: assumes "z \<notin> \<int>\<^sub>\<le>\<^sub>0" shows "deriv (Polygamma m) z = Polygamma (Suc m) (z :: 'a :: {real_normed_field,euclidean_space})" by (intro DERIV_imp_deriv has_field_derivative_Polygamma assms) thm has_field_derivative_Polygamma lemma higher_deriv_Polygamma: assumes "z \<notin> \<int>\<^sub>\<le>\<^sub>0" shows "(deriv ^^ n) (Polygamma m) z = Polygamma (m + n) (z :: 'a :: {real_normed_field,euclidean_space})" proof - have "eventually (\<lambda>u. (deriv ^^ n) (Polygamma m) u = Polygamma (m + n) u) (nhds z)" proof (induction n) case (Suc n) from Suc.IH have "eventually (\<lambda>z. eventually (\<lambda>u. (deriv ^^ n) (Polygamma m) u = Polygamma (m + n) u) (nhds z)) (nhds z)" by (simp add: eventually_eventually) hence "eventually (\<lambda>z. deriv ((deriv ^^ n) (Polygamma m)) z = deriv (Polygamma (m + n)) z) (nhds z)" by eventually_elim (intro deriv_cong_ev refl) moreover have "eventually (\<lambda>z. z \<in> UNIV - \<int>\<^sub>\<le>\<^sub>0) (nhds z)" using assms by (intro eventually_nhds_in_open open_Diff open_UNIV) auto ultimately show ?case by eventually_elim (simp_all add: deriv_Polygamma) qed simp_all thus ?thesis by (rule eventually_nhds_x_imp_x) qed lemma deriv_ln_Gamma_complex: assumes "z \<notin> \<real>\<^sub>\<le>\<^sub>0" shows "deriv ln_Gamma z = Digamma (z :: complex)" by (intro DERIV_imp_deriv has_field_derivative_ln_Gamma_complex assms) lemma higher_deriv_ln_Gamma_complex: assumes "(x::complex) \<notin> \<real>\<^sub>\<le>\<^sub>0" shows "(deriv ^^ j) ln_Gamma x = (if j = 0 then ln_Gamma x else Polygamma (j - 1) x)" proof (cases j) case (Suc j') have "(deriv ^^ j') (deriv ln_Gamma) x = (deriv ^^ j') Digamma x" using eventually_nhds_in_open[of "UNIV - \<real>\<^sub>\<le>\<^sub>0" x] assms by (intro higher_deriv_cong_ev refl) (auto elim!: eventually_mono simp: open_Diff deriv_ln_Gamma_complex) also have "\<dots> = Polygamma j' x" using assms by (subst higher_deriv_Polygamma) (auto elim!: nonpos_Ints_cases simp: complex_nonpos_Reals_iff) finally show ?thesis using Suc by (simp del: funpow.simps add: funpow_Suc_right) qed simp_all text \<open> We define a type class that captures all the fundamental properties of the inverse of the Gamma function and defines the Gamma function upon that. This allows us to instantiate the type class both for the reals and for the complex numbers with a minimal amount of proof duplication. \<close> class\<^marker>\<open>tag unimportant\<close> Gamma = real_normed_field + complete_space + fixes rGamma :: "'a \<Rightarrow> 'a" assumes rGamma_eq_zero_iff_aux: "rGamma z = 0 \<longleftrightarrow> (\<exists>n. z = - of_nat n)" assumes differentiable_rGamma_aux1: "(\<And>n. z \<noteq> - of_nat n) \<Longrightarrow> let d = (THE d. (\<lambda>n. \<Sum>k<n. inverse (of_nat (Suc k)) - inverse (z + of_nat k)) \<longlonglongrightarrow> d) - scaleR euler_mascheroni 1 in filterlim (\<lambda>y. (rGamma y - rGamma z + rGamma z * d * (y - z)) /\<^sub>R norm (y - z)) (nhds 0) (at z)" assumes differentiable_rGamma_aux2: "let z = - of_nat n in filterlim (\<lambda>y. (rGamma y - rGamma z - (-1)^n * (prod of_nat {1..n}) * (y - z)) /\<^sub>R norm (y - z)) (nhds 0) (at z)" assumes rGamma_series_aux: "(\<And>n. z \<noteq> - of_nat n) \<Longrightarrow> let fact' = (\<lambda>n. prod of_nat {1..n}); exp = (\<lambda>x. THE e. (\<lambda>n. \<Sum>k<n. x^k /\<^sub>R fact k) \<longlonglongrightarrow> e); pochhammer' = (\<lambda>a n. (\<Prod>n = 0..n. a + of_nat n)) in filterlim (\<lambda>n. pochhammer' z n / (fact' n * exp (z * (ln (of_nat n) *\<^sub>R 1)))) (nhds (rGamma z)) sequentially" begin subclass banach .. end definition "Gamma z = inverse (rGamma z)" subsection \<open>Basic properties\<close> lemma Gamma_nonpos_Int: "z \<in> \<int>\<^sub>\<le>\<^sub>0 \<Longrightarrow> Gamma z = 0" and rGamma_nonpos_Int: "z \<in> \<int>\<^sub>\<le>\<^sub>0 \<Longrightarrow> rGamma z = 0" using rGamma_eq_zero_iff_aux[of z] unfolding Gamma_def by (auto elim!: nonpos_Ints_cases') lemma Gamma_nonzero: "z \<notin> \<int>\<^sub>\<le>\<^sub>0 \<Longrightarrow> Gamma z \<noteq> 0" and rGamma_nonzero: "z \<notin> \<int>\<^sub>\<le>\<^sub>0 \<Longrightarrow> rGamma z \<noteq> 0" using rGamma_eq_zero_iff_aux[of z] unfolding Gamma_def by (auto elim!: nonpos_Ints_cases') lemma Gamma_eq_zero_iff: "Gamma z = 0 \<longleftrightarrow> z \<in> \<int>\<^sub>\<le>\<^sub>0" and rGamma_eq_zero_iff: "rGamma z = 0 \<longleftrightarrow> z \<in> \<int>\<^sub>\<le>\<^sub>0" using rGamma_eq_zero_iff_aux[of z] unfolding Gamma_def by (auto elim!: nonpos_Ints_cases') lemma rGamma_inverse_Gamma: "rGamma z = inverse (Gamma z)" unfolding Gamma_def by simp lemma rGamma_series_LIMSEQ [tendsto_intros]: "rGamma_series z \<longlonglongrightarrow> rGamma z" proof (cases "z \<in> \<int>\<^sub>\<le>\<^sub>0") case False hence "z \<noteq> - of_nat n" for n by auto from rGamma_series_aux[OF this] show ?thesis by (simp add: rGamma_series_def[abs_def] fact_prod pochhammer_Suc_prod exp_def of_real_def[symmetric] suminf_def sums_def[abs_def] atLeast0AtMost) qed (insert rGamma_eq_zero_iff[of z], simp_all add: rGamma_series_nonpos_Ints_LIMSEQ) theorem Gamma_series_LIMSEQ [tendsto_intros]: "Gamma_series z \<longlonglongrightarrow> Gamma z" proof (cases "z \<in> \<int>\<^sub>\<le>\<^sub>0") case False hence "(\<lambda>n. inverse (rGamma_series z n)) \<longlonglongrightarrow> inverse (rGamma z)" by (intro tendsto_intros) (simp_all add: rGamma_eq_zero_iff) also have "(\<lambda>n. inverse (rGamma_series z n)) = Gamma_series z" by (simp add: rGamma_series_def Gamma_series_def[abs_def]) finally show ?thesis by (simp add: Gamma_def) qed (insert Gamma_eq_zero_iff[of z], simp_all add: Gamma_series_nonpos_Ints_LIMSEQ) lemma Gamma_altdef: "Gamma z = lim (Gamma_series z)" using Gamma_series_LIMSEQ[of z] by (simp add: limI) lemma rGamma_1 [simp]: "rGamma 1 = 1" proof - have A: "eventually (\<lambda>n. rGamma_series 1 n = of_nat (Suc n) / of_nat n) sequentially" using eventually_gt_at_top[of "0::nat"] by (force elim!: eventually_mono simp: rGamma_series_def exp_of_real pochhammer_fact field_split_simps pochhammer_rec' dest!: pochhammer_eq_0_imp_nonpos_Int) have "rGamma_series 1 \<longlonglongrightarrow> 1" by (subst tendsto_cong[OF A]) (rule LIMSEQ_Suc_n_over_n) moreover have "rGamma_series 1 \<longlonglongrightarrow> rGamma 1" by (rule tendsto_intros) ultimately show ?thesis by (intro LIMSEQ_unique) qed lemma rGamma_plus1: "z * rGamma (z + 1) = rGamma z" proof - let ?f = "\<lambda>n. (z + 1) * inverse (of_nat n) + 1" have "eventually (\<lambda>n. ?f n * rGamma_series z n = z * rGamma_series (z + 1) n) sequentially" using eventually_gt_at_top[of "0::nat"] proof eventually_elim fix n :: nat assume n: "n > 0" hence "z * rGamma_series (z + 1) n = inverse (of_nat n) * pochhammer z (Suc (Suc n)) / (fact n * exp (z * of_real (ln (of_nat n))))" by (subst pochhammer_rec) (simp add: rGamma_series_def field_simps exp_add exp_of_real) also from n have "\<dots> = ?f n * rGamma_series z n" by (subst pochhammer_rec') (simp_all add: field_split_simps rGamma_series_def) finally show "?f n * rGamma_series z n = z * rGamma_series (z + 1) n" .. qed moreover have "(\<lambda>n. ?f n * rGamma_series z n) \<longlonglongrightarrow> ((z+1) * 0 + 1) * rGamma z" by (intro tendsto_intros lim_inverse_n) hence "(\<lambda>n. ?f n * rGamma_series z n) \<longlonglongrightarrow> rGamma z" by simp ultimately have "(\<lambda>n. z * rGamma_series (z + 1) n) \<longlonglongrightarrow> rGamma z" by (blast intro: Lim_transform_eventually) moreover have "(\<lambda>n. z * rGamma_series (z + 1) n) \<longlonglongrightarrow> z * rGamma (z + 1)" by (intro tendsto_intros) ultimately show "z * rGamma (z + 1) = rGamma z" using LIMSEQ_unique by blast qed lemma pochhammer_rGamma: "rGamma z = pochhammer z n * rGamma (z + of_nat n)" proof (induction n arbitrary: z) case (Suc n z) have "rGamma z = pochhammer z n * rGamma (z + of_nat n)" by (rule Suc.IH) also note rGamma_plus1 [symmetric] finally show ?case by (simp add: add_ac pochhammer_rec') qed simp_all theorem Gamma_plus1: "z \<notin> \<int>\<^sub>\<le>\<^sub>0 \<Longrightarrow> Gamma (z + 1) = z * Gamma z" using rGamma_plus1[of z] by (simp add: rGamma_inverse_Gamma field_simps Gamma_eq_zero_iff) theorem pochhammer_Gamma: "z \<notin> \<int>\<^sub>\<le>\<^sub>0 \<Longrightarrow> pochhammer z n = Gamma (z + of_nat n) / Gamma z" using pochhammer_rGamma[of z] by (simp add: rGamma_inverse_Gamma Gamma_eq_zero_iff field_simps) lemma Gamma_0 [simp]: "Gamma 0 = 0" and rGamma_0 [simp]: "rGamma 0 = 0" and Gamma_neg_1 [simp]: "Gamma (- 1) = 0" and rGamma_neg_1 [simp]: "rGamma (- 1) = 0" and Gamma_neg_numeral [simp]: "Gamma (- numeral n) = 0" and rGamma_neg_numeral [simp]: "rGamma (- numeral n) = 0" and Gamma_neg_of_nat [simp]: "Gamma (- of_nat m) = 0" and rGamma_neg_of_nat [simp]: "rGamma (- of_nat m) = 0" by (simp_all add: rGamma_eq_zero_iff Gamma_eq_zero_iff) lemma Gamma_1 [simp]: "Gamma 1 = 1" unfolding Gamma_def by simp theorem Gamma_fact: "Gamma (1 + of_nat n) = fact n" by (simp add: pochhammer_fact pochhammer_Gamma of_nat_in_nonpos_Ints_iff flip: of_nat_Suc) lemma Gamma_numeral: "Gamma (numeral n) = fact (pred_numeral n)" by (subst of_nat_numeral[symmetric], subst numeral_eq_Suc, subst of_nat_Suc, subst Gamma_fact) (rule refl) lemma Gamma_of_int: "Gamma (of_int n) = (if n > 0 then fact (nat (n - 1)) else 0)" proof (cases "n > 0") case True hence "Gamma (of_int n) = Gamma (of_nat (Suc (nat (n - 1))))" by (subst of_nat_Suc) simp_all with True show ?thesis by (subst (asm) of_nat_Suc, subst (asm) Gamma_fact) simp qed (simp_all add: Gamma_eq_zero_iff nonpos_Ints_of_int) lemma rGamma_of_int: "rGamma (of_int n) = (if n > 0 then inverse (fact (nat (n - 1))) else 0)" by (simp add: Gamma_of_int rGamma_inverse_Gamma) lemma Gamma_seriesI: assumes "(\<lambda>n. g n / Gamma_series z n) \<longlonglongrightarrow> 1" shows "g \<longlonglongrightarrow> Gamma z" proof (rule Lim_transform_eventually) have "1/2 > (0::real)" by simp from tendstoD[OF assms, OF this] show "eventually (\<lambda>n. g n / Gamma_series z n * Gamma_series z n = g n) sequentially" by (force elim!: eventually_mono simp: dist_real_def) from assms have "(\<lambda>n. g n / Gamma_series z n * Gamma_series z n) \<longlonglongrightarrow> 1 * Gamma z" by (intro tendsto_intros) thus "(\<lambda>n. g n / Gamma_series z n * Gamma_series z n) \<longlonglongrightarrow> Gamma z" by simp qed lemma Gamma_seriesI': assumes "f \<longlonglongrightarrow> rGamma z" assumes "(\<lambda>n. g n * f n) \<longlonglongrightarrow> 1" assumes "z \<notin> \<int>\<^sub>\<le>\<^sub>0" shows "g \<longlonglongrightarrow> Gamma z" proof (rule Lim_transform_eventually) have "1/2 > (0::real)" by simp from tendstoD[OF assms(2), OF this] show "eventually (\<lambda>n. g n * f n / f n = g n) sequentially" by (force elim!: eventually_mono simp: dist_real_def) from assms have "(\<lambda>n. g n * f n / f n) \<longlonglongrightarrow> 1 / rGamma z" by (intro tendsto_divide assms) (simp_all add: rGamma_eq_zero_iff) thus "(\<lambda>n. g n * f n / f n) \<longlonglongrightarrow> Gamma z" by (simp add: Gamma_def divide_inverse) qed lemma Gamma_series'_LIMSEQ: "Gamma_series' z \<longlonglongrightarrow> Gamma z" by (cases "z \<in> \<int>\<^sub>\<le>\<^sub>0") (simp_all add: Gamma_nonpos_Int Gamma_seriesI[OF Gamma_series_Gamma_series'] Gamma_series'_nonpos_Ints_LIMSEQ[of z]) subsection \<open>Differentiability\<close> lemma has_field_derivative_rGamma_no_nonpos_int: assumes "z \<notin> \<int>\<^sub>\<le>\<^sub>0" shows "(rGamma has_field_derivative -rGamma z * Digamma z) (at z within A)" proof (rule has_field_derivative_at_within) from assms have "z \<noteq> - of_nat n" for n by auto from differentiable_rGamma_aux1[OF this] show "(rGamma has_field_derivative -rGamma z * Digamma z) (at z)" unfolding Digamma_def suminf_def sums_def[abs_def] has_field_derivative_def has_derivative_def netlimit_at by (simp add: Let_def bounded_linear_mult_right mult_ac of_real_def [symmetric]) qed lemma has_field_derivative_rGamma_nonpos_int: "(rGamma has_field_derivative (-1)^n * fact n) (at (- of_nat n) within A)" apply (rule has_field_derivative_at_within) using differentiable_rGamma_aux2[of n] unfolding Let_def has_field_derivative_def has_derivative_def netlimit_at by (simp only: bounded_linear_mult_right mult_ac of_real_def [symmetric] fact_prod) simp lemma has_field_derivative_rGamma [derivative_intros]: "(rGamma has_field_derivative (if z \<in> \<int>\<^sub>\<le>\<^sub>0 then (-1)^(nat \<lfloor>norm z\<rfloor>) * fact (nat \<lfloor>norm z\<rfloor>) else -rGamma z * Digamma z)) (at z within A)" using has_field_derivative_rGamma_no_nonpos_int[of z A] has_field_derivative_rGamma_nonpos_int[of "nat \<lfloor>norm z\<rfloor>" A] by (auto elim!: nonpos_Ints_cases') declare has_field_derivative_rGamma_no_nonpos_int [THEN DERIV_chain2, derivative_intros] declare has_field_derivative_rGamma [THEN DERIV_chain2, derivative_intros] declare has_field_derivative_rGamma_nonpos_int [derivative_intros] declare has_field_derivative_rGamma_no_nonpos_int [derivative_intros] declare has_field_derivative_rGamma [derivative_intros] theorem has_field_derivative_Gamma [derivative_intros]: "z \<notin> \<int>\<^sub>\<le>\<^sub>0 \<Longrightarrow> (Gamma has_field_derivative Gamma z * Digamma z) (at z within A)" unfolding Gamma_def [abs_def] by (fastforce intro!: derivative_eq_intros simp: rGamma_eq_zero_iff) declare has_field_derivative_Gamma[THEN DERIV_chain2, derivative_intros] (* TODO: Hide ugly facts properly *) hide_fact rGamma_eq_zero_iff_aux differentiable_rGamma_aux1 differentiable_rGamma_aux2 differentiable_rGamma_aux2 rGamma_series_aux Gamma_class.rGamma_eq_zero_iff_aux lemma continuous_on_rGamma [continuous_intros]: "continuous_on A rGamma" by (rule DERIV_continuous_on has_field_derivative_rGamma)+ lemma continuous_on_Gamma [continuous_intros]: "A \<inter> \<int>\<^sub>\<le>\<^sub>0 = {} \<Longrightarrow> continuous_on A Gamma" by (rule DERIV_continuous_on has_field_derivative_Gamma)+ blast lemma isCont_rGamma [continuous_intros]: "isCont f z \<Longrightarrow> isCont (\<lambda>x. rGamma (f x)) z" by (rule isCont_o2[OF _ DERIV_isCont[OF has_field_derivative_rGamma]]) lemma isCont_Gamma [continuous_intros]: "isCont f z \<Longrightarrow> f z \<notin> \<int>\<^sub>\<le>\<^sub>0 \<Longrightarrow> isCont (\<lambda>x. Gamma (f x)) z" by (rule isCont_o2[OF _ DERIV_isCont[OF has_field_derivative_Gamma]]) subsection\<^marker>\<open>tag unimportant\<close> \<open>The complex Gamma function\<close> instantiation\<^marker>\<open>tag unimportant\<close> complex :: Gamma begin definition\<^marker>\<open>tag unimportant\<close> rGamma_complex :: "complex \<Rightarrow> complex" where "rGamma_complex z = lim (rGamma_series z)" lemma rGamma_series_complex_converges: "convergent (rGamma_series (z :: complex))" (is "?thesis1") and rGamma_complex_altdef: "rGamma z = (if z \<in> \<int>\<^sub>\<le>\<^sub>0 then 0 else exp (-ln_Gamma z))" (is "?thesis2") proof - have "?thesis1 \<and> ?thesis2" proof (cases "z \<in> \<int>\<^sub>\<le>\<^sub>0") case False have "rGamma_series z \<longlonglongrightarrow> exp (- ln_Gamma z)" proof (rule Lim_transform_eventually) from ln_Gamma_series_complex_converges'[OF False] obtain d where "0 < d" "uniformly_convergent_on (ball z d) (\<lambda>n z. ln_Gamma_series z n)" by auto from this(1) uniformly_convergent_imp_convergent[OF this(2), of z] have "ln_Gamma_series z \<longlonglongrightarrow> lim (ln_Gamma_series z)" by (simp add: convergent_LIMSEQ_iff) thus "(\<lambda>n. exp (-ln_Gamma_series z n)) \<longlonglongrightarrow> exp (- ln_Gamma z)" unfolding convergent_def ln_Gamma_def by (intro tendsto_exp tendsto_minus) from eventually_gt_at_top[of "0::nat"] exp_ln_Gamma_series_complex False show "eventually (\<lambda>n. exp (-ln_Gamma_series z n) = rGamma_series z n) sequentially" by (force elim!: eventually_mono simp: exp_minus Gamma_series_def rGamma_series_def) qed with False show ?thesis by (auto simp: convergent_def rGamma_complex_def intro!: limI) next case True then obtain k where "z = - of_nat k" by (erule nonpos_Ints_cases') also have "rGamma_series \<dots> \<longlonglongrightarrow> 0" by (subst tendsto_cong[OF rGamma_series_minus_of_nat]) (simp_all add: convergent_const) finally show ?thesis using True by (auto simp: rGamma_complex_def convergent_def intro!: limI) qed thus "?thesis1" "?thesis2" by blast+ qed context\<^marker>\<open>tag unimportant\<close> begin (* TODO: duplication *) private lemma rGamma_complex_plus1: "z * rGamma (z + 1) = rGamma (z :: complex)" proof - let ?f = "\<lambda>n. (z + 1) * inverse (of_nat n) + 1" have "eventually (\<lambda>n. ?f n * rGamma_series z n = z * rGamma_series (z + 1) n) sequentially" using eventually_gt_at_top[of "0::nat"] proof eventually_elim fix n :: nat assume n: "n > 0" hence "z * rGamma_series (z + 1) n = inverse (of_nat n) * pochhammer z (Suc (Suc n)) / (fact n * exp (z * of_real (ln (of_nat n))))" by (subst pochhammer_rec) (simp add: rGamma_series_def field_simps exp_add exp_of_real) also from n have "\<dots> = ?f n * rGamma_series z n" by (subst pochhammer_rec') (simp_all add: field_split_simps rGamma_series_def add_ac) finally show "?f n * rGamma_series z n = z * rGamma_series (z + 1) n" .. qed moreover have "(\<lambda>n. ?f n * rGamma_series z n) \<longlonglongrightarrow> ((z+1) * 0 + 1) * rGamma z" using rGamma_series_complex_converges by (intro tendsto_intros lim_inverse_n) (simp_all add: convergent_LIMSEQ_iff rGamma_complex_def) hence "(\<lambda>n. ?f n * rGamma_series z n) \<longlonglongrightarrow> rGamma z" by simp ultimately have "(\<lambda>n. z * rGamma_series (z + 1) n) \<longlonglongrightarrow> rGamma z" by (blast intro: Lim_transform_eventually) moreover have "(\<lambda>n. z * rGamma_series (z + 1) n) \<longlonglongrightarrow> z * rGamma (z + 1)" using rGamma_series_complex_converges by (auto intro!: tendsto_mult simp: rGamma_complex_def convergent_LIMSEQ_iff) ultimately show "z * rGamma (z + 1) = rGamma z" using LIMSEQ_unique by blast qed private lemma has_field_derivative_rGamma_complex_no_nonpos_Int: assumes "(z :: complex) \<notin> \<int>\<^sub>\<le>\<^sub>0" shows "(rGamma has_field_derivative - rGamma z * Digamma z) (at z)" proof - have diff: "(rGamma has_field_derivative - rGamma z * Digamma z) (at z)" if "Re z > 0" for z proof (subst DERIV_cong_ev[OF refl _ refl]) from that have "eventually (\<lambda>t. t \<in> ball z (Re z/2)) (nhds z)" by (intro eventually_nhds_in_nhd) simp_all thus "eventually (\<lambda>t. rGamma t = exp (- ln_Gamma t)) (nhds z)" using no_nonpos_Int_in_ball_complex[OF that] by (auto elim!: eventually_mono simp: rGamma_complex_altdef) next have "z \<notin> \<real>\<^sub>\<le>\<^sub>0" using that by (simp add: complex_nonpos_Reals_iff) with that show "((\<lambda>t. exp (- ln_Gamma t)) has_field_derivative (-rGamma z * Digamma z)) (at z)" by (force elim!: nonpos_Ints_cases intro!: derivative_eq_intros simp: rGamma_complex_altdef) qed from assms show "(rGamma has_field_derivative - rGamma z * Digamma z) (at z)" proof (induction "nat \<lfloor>1 - Re z\<rfloor>" arbitrary: z) case (Suc n z) from Suc.prems have z: "z \<noteq> 0" by auto from Suc.hyps have "n = nat \<lfloor>- Re z\<rfloor>" by linarith hence A: "n = nat \<lfloor>1 - Re (z + 1)\<rfloor>" by simp from Suc.prems have B: "z + 1 \<notin> \<int>\<^sub>\<le>\<^sub>0" by (force dest: plus_one_in_nonpos_Ints_imp) have "((\<lambda>z. z * (rGamma \<circ> (\<lambda>z. z + 1)) z) has_field_derivative -rGamma (z + 1) * (Digamma (z + 1) * z - 1)) (at z)" by (rule derivative_eq_intros DERIV_chain Suc refl A B)+ (simp add: algebra_simps) also have "(\<lambda>z. z * (rGamma \<circ> (\<lambda>z. z + 1 :: complex)) z) = rGamma" by (simp add: rGamma_complex_plus1) also from z have "Digamma (z + 1) * z - 1 = z * Digamma z" by (subst Digamma_plus1) (simp_all add: field_simps) also have "-rGamma (z + 1) * (z * Digamma z) = -rGamma z * Digamma z" by (simp add: rGamma_complex_plus1[of z, symmetric]) finally show ?case . qed (intro diff, simp) qed private lemma rGamma_complex_1: "rGamma (1 :: complex) = 1" proof - have A: "eventually (\<lambda>n. rGamma_series 1 n = of_nat (Suc n) / of_nat n) sequentially" using eventually_gt_at_top[of "0::nat"] by (force elim!: eventually_mono simp: rGamma_series_def exp_of_real pochhammer_fact field_split_simps pochhammer_rec' dest!: pochhammer_eq_0_imp_nonpos_Int) have "rGamma_series 1 \<longlonglongrightarrow> 1" by (subst tendsto_cong[OF A]) (rule LIMSEQ_Suc_n_over_n) thus "rGamma 1 = (1 :: complex)" unfolding rGamma_complex_def by (rule limI) qed private lemma has_field_derivative_rGamma_complex_nonpos_Int: "(rGamma has_field_derivative (-1)^n * fact n) (at (- of_nat n :: complex))" proof (induction n) case 0 have A: "(0::complex) + 1 \<notin> \<int>\<^sub>\<le>\<^sub>0" by simp have "((\<lambda>z. z * (rGamma \<circ> (\<lambda>z. z + 1 :: complex)) z) has_field_derivative 1) (at 0)" by (rule derivative_eq_intros DERIV_chain refl has_field_derivative_rGamma_complex_no_nonpos_Int A)+ (simp add: rGamma_complex_1) thus ?case by (simp add: rGamma_complex_plus1) next case (Suc n) hence A: "(rGamma has_field_derivative (-1)^n * fact n) (at (- of_nat (Suc n) + 1 :: complex))" by simp have "((\<lambda>z. z * (rGamma \<circ> (\<lambda>z. z + 1 :: complex)) z) has_field_derivative (- 1) ^ Suc n * fact (Suc n)) (at (- of_nat (Suc n)))" by (rule derivative_eq_intros refl A DERIV_chain)+ (simp add: algebra_simps rGamma_complex_altdef) thus ?case by (simp add: rGamma_complex_plus1) qed instance proof fix z :: complex show "(rGamma z = 0) \<longleftrightarrow> (\<exists>n. z = - of_nat n)" by (auto simp: rGamma_complex_altdef elim!: nonpos_Ints_cases') next fix z :: complex assume "\<And>n. z \<noteq> - of_nat n" hence "z \<notin> \<int>\<^sub>\<le>\<^sub>0" by (auto elim!: nonpos_Ints_cases') from has_field_derivative_rGamma_complex_no_nonpos_Int[OF this] show "let d = (THE d. (\<lambda>n. \<Sum>k<n. inverse (of_nat (Suc k)) - inverse (z + of_nat k)) \<longlonglongrightarrow> d) - euler_mascheroni *\<^sub>R 1 in (\<lambda>y. (rGamma y - rGamma z + rGamma z * d * (y - z)) /\<^sub>R cmod (y - z)) \<midarrow>z\<rightarrow> 0" by (simp add: has_field_derivative_def has_derivative_def Digamma_def sums_def [abs_def] of_real_def[symmetric] suminf_def) next fix n :: nat from has_field_derivative_rGamma_complex_nonpos_Int[of n] show "let z = - of_nat n in (\<lambda>y. (rGamma y - rGamma z - (- 1) ^ n * prod of_nat {1..n} * (y - z)) /\<^sub>R cmod (y - z)) \<midarrow>z\<rightarrow> 0" by (simp add: has_field_derivative_def has_derivative_def fact_prod Let_def) next fix z :: complex from rGamma_series_complex_converges[of z] have "rGamma_series z \<longlonglongrightarrow> rGamma z" by (simp add: convergent_LIMSEQ_iff rGamma_complex_def) thus "let fact' = \<lambda>n. prod of_nat {1..n}; exp = \<lambda>x. THE e. (\<lambda>n. \<Sum>k<n. x ^ k /\<^sub>R fact k) \<longlonglongrightarrow> e; pochhammer' = \<lambda>a n. \<Prod>n = 0..n. a + of_nat n in (\<lambda>n. pochhammer' z n / (fact' n * exp (z * ln (real_of_nat n) *\<^sub>R 1))) \<longlonglongrightarrow> rGamma z" by (simp add: fact_prod pochhammer_Suc_prod rGamma_series_def [abs_def] exp_def of_real_def [symmetric] suminf_def sums_def [abs_def] atLeast0AtMost) qed end end lemma Gamma_complex_altdef: "Gamma z = (if z \<in> \<int>\<^sub>\<le>\<^sub>0 then 0 else exp (ln_Gamma (z :: complex)))" unfolding Gamma_def rGamma_complex_altdef by (simp add: exp_minus) lemma cnj_rGamma: "cnj (rGamma z) = rGamma (cnj z)" proof - have "rGamma_series (cnj z) = (\<lambda>n. cnj (rGamma_series z n))" by (intro ext) (simp_all add: rGamma_series_def exp_cnj) also have "... \<longlonglongrightarrow> cnj (rGamma z)" by (intro tendsto_cnj tendsto_intros) finally show ?thesis unfolding rGamma_complex_def by (intro sym[OF limI]) qed lemma cnj_Gamma: "cnj (Gamma z) = Gamma (cnj z)" unfolding Gamma_def by (simp add: cnj_rGamma) lemma Gamma_complex_real: "z \<in> \<real> \<Longrightarrow> Gamma z \<in> (\<real> :: complex set)" and rGamma_complex_real: "z \<in> \<real> \<Longrightarrow> rGamma z \<in> \<real>" by (simp_all add: Reals_cnj_iff cnj_Gamma cnj_rGamma) lemma field_differentiable_rGamma: "rGamma field_differentiable (at z within A)" using has_field_derivative_rGamma[of z] unfolding field_differentiable_def by blast lemma holomorphic_rGamma [holomorphic_intros]: "rGamma holomorphic_on A" unfolding holomorphic_on_def by (auto intro!: field_differentiable_rGamma) lemma holomorphic_rGamma' [holomorphic_intros]: assumes "f holomorphic_on A" shows "(\<lambda>x. rGamma (f x)) holomorphic_on A" proof - have "rGamma \<circ> f holomorphic_on A" using assms by (intro holomorphic_on_compose assms holomorphic_rGamma) thus ?thesis by (simp only: o_def) qed lemma analytic_rGamma: "rGamma analytic_on A" unfolding analytic_on_def by (auto intro!: exI[of _ 1] holomorphic_rGamma) lemma field_differentiable_Gamma: "z \<notin> \<int>\<^sub>\<le>\<^sub>0 \<Longrightarrow> Gamma field_differentiable (at z within A)" using has_field_derivative_Gamma[of z] unfolding field_differentiable_def by auto lemma holomorphic_Gamma [holomorphic_intros]: "A \<inter> \<int>\<^sub>\<le>\<^sub>0 = {} \<Longrightarrow> Gamma holomorphic_on A" unfolding holomorphic_on_def by (auto intro!: field_differentiable_Gamma) lemma holomorphic_Gamma' [holomorphic_intros]: assumes "f holomorphic_on A" and "\<And>x. x \<in> A \<Longrightarrow> f x \<notin> \<int>\<^sub>\<le>\<^sub>0" shows "(\<lambda>x. Gamma (f x)) holomorphic_on A" proof - have "Gamma \<circ> f holomorphic_on A" using assms by (intro holomorphic_on_compose assms holomorphic_Gamma) auto thus ?thesis by (simp only: o_def) qed lemma analytic_Gamma: "A \<inter> \<int>\<^sub>\<le>\<^sub>0 = {} \<Longrightarrow> Gamma analytic_on A" by (rule analytic_on_subset[of _ "UNIV - \<int>\<^sub>\<le>\<^sub>0"], subst analytic_on_open) (auto intro!: holomorphic_Gamma) lemma field_differentiable_ln_Gamma_complex: "z \<notin> \<real>\<^sub>\<le>\<^sub>0 \<Longrightarrow> ln_Gamma field_differentiable (at (z::complex) within A)" by (rule field_differentiable_within_subset[of _ _ UNIV]) (force simp: field_differentiable_def intro!: derivative_intros)+ lemma holomorphic_ln_Gamma [holomorphic_intros]: "A \<inter> \<real>\<^sub>\<le>\<^sub>0 = {} \<Longrightarrow> ln_Gamma holomorphic_on A" unfolding holomorphic_on_def by (auto intro!: field_differentiable_ln_Gamma_complex) lemma analytic_ln_Gamma: "A \<inter> \<real>\<^sub>\<le>\<^sub>0 = {} \<Longrightarrow> ln_Gamma analytic_on A" by (rule analytic_on_subset[of _ "UNIV - \<real>\<^sub>\<le>\<^sub>0"], subst analytic_on_open) (auto intro!: holomorphic_ln_Gamma) lemma has_field_derivative_rGamma_complex' [derivative_intros]: "(rGamma has_field_derivative (if z \<in> \<int>\<^sub>\<le>\<^sub>0 then (-1)^(nat \<lfloor>-Re z\<rfloor>) * fact (nat \<lfloor>-Re z\<rfloor>) else -rGamma z * Digamma z)) (at z within A)" using has_field_derivative_rGamma[of z] by (auto elim!: nonpos_Ints_cases') declare has_field_derivative_rGamma_complex'[THEN DERIV_chain2, derivative_intros] lemma field_differentiable_Polygamma: fixes z :: complex shows "z \<notin> \<int>\<^sub>\<le>\<^sub>0 \<Longrightarrow> Polygamma n field_differentiable (at z within A)" using has_field_derivative_Polygamma[of z n] unfolding field_differentiable_def by auto lemma holomorphic_on_Polygamma [holomorphic_intros]: "A \<inter> \<int>\<^sub>\<le>\<^sub>0 = {} \<Longrightarrow> Polygamma n holomorphic_on A" unfolding holomorphic_on_def by (auto intro!: field_differentiable_Polygamma) lemma analytic_on_Polygamma: "A \<inter> \<int>\<^sub>\<le>\<^sub>0 = {} \<Longrightarrow> Polygamma n analytic_on A" by (rule analytic_on_subset[of _ "UNIV - \<int>\<^sub>\<le>\<^sub>0"], subst analytic_on_open) (auto intro!: holomorphic_on_Polygamma) subsection\<^marker>\<open>tag unimportant\<close> \<open>The real Gamma function\<close> lemma rGamma_series_real: "eventually (\<lambda>n. rGamma_series x n = Re (rGamma_series (of_real x) n)) sequentially" using eventually_gt_at_top[of "0 :: nat"] proof eventually_elim fix n :: nat assume n: "n > 0" have "Re (rGamma_series (of_real x) n) = Re (of_real (pochhammer x (Suc n)) / (fact n * exp (of_real (x * ln (real_of_nat n)))))" using n by (simp add: rGamma_series_def powr_def pochhammer_of_real) also from n have "\<dots> = Re (of_real ((pochhammer x (Suc n)) / (fact n * (exp (x * ln (real_of_nat n))))))" by (subst exp_of_real) simp also from n have "\<dots> = rGamma_series x n" by (subst Re_complex_of_real) (simp add: rGamma_series_def powr_def) finally show "rGamma_series x n = Re (rGamma_series (of_real x) n)" .. qed instantiation\<^marker>\<open>tag unimportant\<close> real :: Gamma begin definition "rGamma_real x = Re (rGamma (of_real x :: complex))" instance proof fix x :: real have "rGamma x = Re (rGamma (of_real x))" by (simp add: rGamma_real_def) also have "of_real \<dots> = rGamma (of_real x :: complex)" by (intro of_real_Re rGamma_complex_real) simp_all also have "\<dots> = 0 \<longleftrightarrow> x \<in> \<int>\<^sub>\<le>\<^sub>0" by (simp add: rGamma_eq_zero_iff of_real_in_nonpos_Ints_iff) also have "\<dots> \<longleftrightarrow> (\<exists>n. x = - of_nat n)" by (auto elim!: nonpos_Ints_cases') finally show "(rGamma x) = 0 \<longleftrightarrow> (\<exists>n. x = - real_of_nat n)" by simp next fix x :: real assume "\<And>n. x \<noteq> - of_nat n" hence x: "complex_of_real x \<notin> \<int>\<^sub>\<le>\<^sub>0" by (subst of_real_in_nonpos_Ints_iff) (auto elim!: nonpos_Ints_cases') then have "x \<noteq> 0" by auto with x have "(rGamma has_field_derivative - rGamma x * Digamma x) (at x)" by (fastforce intro!: derivative_eq_intros has_vector_derivative_real_field simp: Polygamma_of_real rGamma_real_def [abs_def]) thus "let d = (THE d. (\<lambda>n. \<Sum>k<n. inverse (of_nat (Suc k)) - inverse (x + of_nat k)) \<longlonglongrightarrow> d) - euler_mascheroni *\<^sub>R 1 in (\<lambda>y. (rGamma y - rGamma x + rGamma x * d * (y - x)) /\<^sub>R norm (y - x)) \<midarrow>x\<rightarrow> 0" by (simp add: has_field_derivative_def has_derivative_def Digamma_def sums_def [abs_def] of_real_def[symmetric] suminf_def) next fix n :: nat have "(rGamma has_field_derivative (-1)^n * fact n) (at (- of_nat n :: real))" by (fastforce intro!: derivative_eq_intros has_vector_derivative_real_field simp: Polygamma_of_real rGamma_real_def [abs_def]) thus "let x = - of_nat n in (\<lambda>y. (rGamma y - rGamma x - (- 1) ^ n * prod of_nat {1..n} * (y - x)) /\<^sub>R norm (y - x)) \<midarrow>x::real\<rightarrow> 0" by (simp add: has_field_derivative_def has_derivative_def fact_prod Let_def) next fix x :: real have "rGamma_series x \<longlonglongrightarrow> rGamma x" proof (rule Lim_transform_eventually) show "(\<lambda>n. Re (rGamma_series (of_real x) n)) \<longlonglongrightarrow> rGamma x" unfolding rGamma_real_def by (intro tendsto_intros) qed (insert rGamma_series_real, simp add: eq_commute) thus "let fact' = \<lambda>n. prod of_nat {1..n}; exp = \<lambda>x. THE e. (\<lambda>n. \<Sum>k<n. x ^ k /\<^sub>R fact k) \<longlonglongrightarrow> e; pochhammer' = \<lambda>a n. \<Prod>n = 0..n. a + of_nat n in (\<lambda>n. pochhammer' x n / (fact' n * exp (x * ln (real_of_nat n) *\<^sub>R 1))) \<longlonglongrightarrow> rGamma x" by (simp add: fact_prod pochhammer_Suc_prod rGamma_series_def [abs_def] exp_def of_real_def [symmetric] suminf_def sums_def [abs_def] atLeast0AtMost) qed end lemma rGamma_complex_of_real: "rGamma (complex_of_real x) = complex_of_real (rGamma x)" unfolding rGamma_real_def using rGamma_complex_real by simp lemma Gamma_complex_of_real: "Gamma (complex_of_real x) = complex_of_real (Gamma x)" unfolding Gamma_def by (simp add: rGamma_complex_of_real) lemma rGamma_real_altdef: "rGamma x = lim (rGamma_series (x :: real))" by (rule sym, rule limI, rule tendsto_intros) lemma Gamma_real_altdef1: "Gamma x = lim (Gamma_series (x :: real))" by (rule sym, rule limI, rule tendsto_intros) lemma Gamma_real_altdef2: "Gamma x = Re (Gamma (of_real x))" using rGamma_complex_real[OF Reals_of_real[of x]] by (elim Reals_cases) (simp only: Gamma_def rGamma_real_def of_real_inverse[symmetric] Re_complex_of_real) lemma ln_Gamma_series_complex_of_real: "x > 0 \<Longrightarrow> n > 0 \<Longrightarrow> ln_Gamma_series (complex_of_real x) n = of_real (ln_Gamma_series x n)" proof - assume xn: "x > 0" "n > 0" have "Ln (complex_of_real x / of_nat k + 1) = of_real (ln (x / of_nat k + 1))" if "k \<ge> 1" for k using that xn by (subst Ln_of_real [symmetric]) (auto intro!: add_nonneg_pos simp: field_simps) with xn show ?thesis by (simp add: ln_Gamma_series_def Ln_of_real) qed lemma ln_Gamma_real_converges: assumes "(x::real) > 0" shows "convergent (ln_Gamma_series x)" proof - have "(\<lambda>n. ln_Gamma_series (complex_of_real x) n) \<longlonglongrightarrow> ln_Gamma (of_real x)" using assms by (intro ln_Gamma_complex_LIMSEQ) (auto simp: of_real_in_nonpos_Ints_iff) moreover from eventually_gt_at_top[of "0::nat"] have "eventually (\<lambda>n. complex_of_real (ln_Gamma_series x n) = ln_Gamma_series (complex_of_real x) n) sequentially" by eventually_elim (simp add: ln_Gamma_series_complex_of_real assms) ultimately have "(\<lambda>n. complex_of_real (ln_Gamma_series x n)) \<longlonglongrightarrow> ln_Gamma (of_real x)" by (subst tendsto_cong) assumption+ from tendsto_Re[OF this] show ?thesis by (auto simp: convergent_def) qed lemma ln_Gamma_real_LIMSEQ: "(x::real) > 0 \<Longrightarrow> ln_Gamma_series x \<longlonglongrightarrow> ln_Gamma x" using ln_Gamma_real_converges[of x] unfolding ln_Gamma_def by (simp add: convergent_LIMSEQ_iff) lemma ln_Gamma_complex_of_real: "x > 0 \<Longrightarrow> ln_Gamma (complex_of_real x) = of_real (ln_Gamma x)" proof (unfold ln_Gamma_def, rule limI, rule Lim_transform_eventually) assume x: "x > 0" show "eventually (\<lambda>n. of_real (ln_Gamma_series x n) = ln_Gamma_series (complex_of_real x) n) sequentially" using eventually_gt_at_top[of "0::nat"] by eventually_elim (simp add: ln_Gamma_series_complex_of_real x) qed (intro tendsto_of_real, insert ln_Gamma_real_LIMSEQ[of x], simp add: ln_Gamma_def) lemma Gamma_real_pos_exp: "x > (0 :: real) \<Longrightarrow> Gamma x = exp (ln_Gamma x)" by (auto simp: Gamma_real_altdef2 Gamma_complex_altdef of_real_in_nonpos_Ints_iff ln_Gamma_complex_of_real exp_of_real) lemma ln_Gamma_real_pos: "x > 0 \<Longrightarrow> ln_Gamma x = ln (Gamma x :: real)" unfolding Gamma_real_pos_exp by simp lemma ln_Gamma_complex_conv_fact: "n > 0 \<Longrightarrow> ln_Gamma (of_nat n :: complex) = ln (fact (n - 1))" using ln_Gamma_complex_of_real[of "real n"] Gamma_fact[of "n - 1", where 'a = real] by (simp add: ln_Gamma_real_pos of_nat_diff Ln_of_real [symmetric]) lemma ln_Gamma_real_conv_fact: "n > 0 \<Longrightarrow> ln_Gamma (real n) = ln (fact (n - 1))" using Gamma_fact[of "n - 1", where 'a = real] by (simp add: ln_Gamma_real_pos of_nat_diff Ln_of_real [symmetric]) lemma Gamma_real_pos [simp, intro]: "x > (0::real) \<Longrightarrow> Gamma x > 0" by (simp add: Gamma_real_pos_exp) lemma Gamma_real_nonneg [simp, intro]: "x > (0::real) \<Longrightarrow> Gamma x \<ge> 0" by (simp add: Gamma_real_pos_exp) lemma has_field_derivative_ln_Gamma_real [derivative_intros]: assumes x: "x > (0::real)" shows "(ln_Gamma has_field_derivative Digamma x) (at x)" proof (subst DERIV_cong_ev[OF refl _ refl]) from assms show "((Re \<circ> ln_Gamma \<circ> complex_of_real) has_field_derivative Digamma x) (at x)" by (auto intro!: derivative_eq_intros has_vector_derivative_real_field simp: Polygamma_of_real o_def) from eventually_nhds_in_nhd[of x "{0<..}"] assms show "eventually (\<lambda>y. ln_Gamma y = (Re \<circ> ln_Gamma \<circ> of_real) y) (nhds x)" by (auto elim!: eventually_mono simp: ln_Gamma_complex_of_real interior_open) qed lemma field_differentiable_ln_Gamma_real: "x > 0 \<Longrightarrow> ln_Gamma field_differentiable (at (x::real) within A)" by (rule field_differentiable_within_subset[of _ _ UNIV]) (auto simp: field_differentiable_def intro!: derivative_intros)+ declare has_field_derivative_ln_Gamma_real[THEN DERIV_chain2, derivative_intros] lemma deriv_ln_Gamma_real: assumes "z > 0" shows "deriv ln_Gamma z = Digamma (z :: real)" by (intro DERIV_imp_deriv has_field_derivative_ln_Gamma_real assms) lemma higher_deriv_ln_Gamma_real: assumes "(x::real) > 0" shows "(deriv ^^ j) ln_Gamma x = (if j = 0 then ln_Gamma x else Polygamma (j - 1) x)" proof (cases j) case (Suc j') have "(deriv ^^ j') (deriv ln_Gamma) x = (deriv ^^ j') Digamma x" using eventually_nhds_in_open[of "{0<..}" x] assms by (intro higher_deriv_cong_ev refl) (auto elim!: eventually_mono simp: open_Diff deriv_ln_Gamma_real) also have "\<dots> = Polygamma j' x" using assms by (subst higher_deriv_Polygamma) (auto elim!: nonpos_Ints_cases simp: complex_nonpos_Reals_iff) finally show ?thesis using Suc by (simp del: funpow.simps add: funpow_Suc_right) qed simp_all lemma higher_deriv_ln_Gamma_complex_of_real: assumes "(x :: real) > 0" shows "(deriv ^^ j) ln_Gamma (complex_of_real x) = of_real ((deriv ^^ j) ln_Gamma x)" using assms by (auto simp: higher_deriv_ln_Gamma_real higher_deriv_ln_Gamma_complex ln_Gamma_complex_of_real Polygamma_of_real) lemma has_field_derivative_rGamma_real' [derivative_intros]: "(rGamma has_field_derivative (if x \<in> \<int>\<^sub>\<le>\<^sub>0 then (-1)^(nat \<lfloor>-x\<rfloor>) * fact (nat \<lfloor>-x\<rfloor>) else -rGamma x * Digamma x)) (at x within A)" using has_field_derivative_rGamma[of x] by (force elim!: nonpos_Ints_cases') declare has_field_derivative_rGamma_real'[THEN DERIV_chain2, derivative_intros] lemma Polygamma_real_odd_pos: assumes "(x::real) \<notin> \<int>\<^sub>\<le>\<^sub>0" "odd n" shows "Polygamma n x > 0" proof - from assms have "x \<noteq> 0" by auto with assms show ?thesis unfolding Polygamma_def using Polygamma_converges'[of x "Suc n"] by (auto simp: zero_less_power_eq simp del: power_Suc dest: plus_of_nat_eq_0_imp intro!: mult_pos_pos suminf_pos) qed lemma Polygamma_real_even_neg: assumes "(x::real) > 0" "n > 0" "even n" shows "Polygamma n x < 0" using assms unfolding Polygamma_def using Polygamma_converges'[of x "Suc n"] by (auto intro!: mult_pos_pos suminf_pos) lemma Polygamma_real_strict_mono: assumes "x > 0" "x < (y::real)" "even n" shows "Polygamma n x < Polygamma n y" proof - have "\<exists>\<xi>. x < \<xi> \<and> \<xi> < y \<and> Polygamma n y - Polygamma n x = (y - x) * Polygamma (Suc n) \<xi>" using assms by (intro MVT2 derivative_intros impI allI) (auto elim!: nonpos_Ints_cases) then obtain \<xi> where \<xi>: "x < \<xi>" "\<xi> < y" and Polygamma: "Polygamma n y - Polygamma n x = (y - x) * Polygamma (Suc n) \<xi>" by auto note Polygamma also from \<xi> assms have "(y - x) * Polygamma (Suc n) \<xi> > 0" by (intro mult_pos_pos Polygamma_real_odd_pos) (auto elim!: nonpos_Ints_cases) finally show ?thesis by simp qed lemma Polygamma_real_strict_antimono: assumes "x > 0" "x < (y::real)" "odd n" shows "Polygamma n x > Polygamma n y" proof - have "\<exists>\<xi>. x < \<xi> \<and> \<xi> < y \<and> Polygamma n y - Polygamma n x = (y - x) * Polygamma (Suc n) \<xi>" using assms by (intro MVT2 derivative_intros impI allI) (auto elim!: nonpos_Ints_cases) then obtain \<xi> where \<xi>: "x < \<xi>" "\<xi> < y" and Polygamma: "Polygamma n y - Polygamma n x = (y - x) * Polygamma (Suc n) \<xi>" by auto note Polygamma also from \<xi> assms have "(y - x) * Polygamma (Suc n) \<xi> < 0" by (intro mult_pos_neg Polygamma_real_even_neg) simp_all finally show ?thesis by simp qed lemma Polygamma_real_mono: assumes "x > 0" "x \<le> (y::real)" "even n" shows "Polygamma n x \<le> Polygamma n y" using Polygamma_real_strict_mono[OF assms(1) _ assms(3), of y] assms(2) by (cases "x = y") simp_all lemma Digamma_real_strict_mono: "(0::real) < x \<Longrightarrow> x < y \<Longrightarrow> Digamma x < Digamma y" by (rule Polygamma_real_strict_mono) simp_all lemma Digamma_real_mono: "(0::real) < x \<Longrightarrow> x \<le> y \<Longrightarrow> Digamma x \<le> Digamma y" by (rule Polygamma_real_mono) simp_all lemma Digamma_real_ge_three_halves_pos: assumes "x \<ge> 3/2" shows "Digamma (x :: real) > 0" proof - have "0 < Digamma (3/2 :: real)" by (fact Digamma_real_three_halves_pos) also from assms have "\<dots> \<le> Digamma x" by (intro Polygamma_real_mono) simp_all finally show ?thesis . qed lemma ln_Gamma_real_strict_mono: assumes "x \<ge> 3/2" "x < y" shows "ln_Gamma (x :: real) < ln_Gamma y" proof - have "\<exists>\<xi>. x < \<xi> \<and> \<xi> < y \<and> ln_Gamma y - ln_Gamma x = (y - x) * Digamma \<xi>" using assms by (intro MVT2 derivative_intros impI allI) (auto elim!: nonpos_Ints_cases) then obtain \<xi> where \<xi>: "x < \<xi>" "\<xi> < y" and ln_Gamma: "ln_Gamma y - ln_Gamma x = (y - x) * Digamma \<xi>" by auto note ln_Gamma also from \<xi> assms have "(y - x) * Digamma \<xi> > 0" by (intro mult_pos_pos Digamma_real_ge_three_halves_pos) simp_all finally show ?thesis by simp qed lemma Gamma_real_strict_mono: assumes "x \<ge> 3/2" "x < y" shows "Gamma (x :: real) < Gamma y" proof - from Gamma_real_pos_exp[of x] assms have "Gamma x = exp (ln_Gamma x)" by simp also have "\<dots> < exp (ln_Gamma y)" by (intro exp_less_mono ln_Gamma_real_strict_mono assms) also from Gamma_real_pos_exp[of y] assms have "\<dots> = Gamma y" by simp finally show ?thesis . qed theorem log_convex_Gamma_real: "convex_on {0<..} (ln \<circ> Gamma :: real \<Rightarrow> real)" by (rule convex_on_realI[of _ _ Digamma]) (auto intro!: derivative_eq_intros Polygamma_real_mono Gamma_real_pos simp: o_def Gamma_eq_zero_iff elim!: nonpos_Ints_cases') subsection \<open>The uniqueness of the real Gamma function\<close> text \<open> The following is a proof of the Bohr--Mollerup theorem, which states that any log-convex function \<open>G\<close> on the positive reals that fulfils \<open>G(1) = 1\<close> and satisfies the functional equation \<open>G(x + 1) = x G(x)\<close> must be equal to the Gamma function. In principle, if \<open>G\<close> is a holomorphic complex function, one could then extend this from the positive reals to the entire complex plane (minus the non-positive integers, where the Gamma function is not defined). \<close> context\<^marker>\<open>tag unimportant\<close> fixes G :: "real \<Rightarrow> real" assumes G_1: "G 1 = 1" assumes G_plus1: "x > 0 \<Longrightarrow> G (x + 1) = x * G x" assumes G_pos: "x > 0 \<Longrightarrow> G x > 0" assumes log_convex_G: "convex_on {0<..} (ln \<circ> G)" begin private lemma G_fact: "G (of_nat n + 1) = fact n" using G_plus1[of "real n + 1" for n] by (induction n) (simp_all add: G_1 G_plus1) private definition S :: "real \<Rightarrow> real \<Rightarrow> real" where "S x y = (ln (G y) - ln (G x)) / (y - x)" private lemma S_eq: "n \<ge> 2 \<Longrightarrow> S (of_nat n) (of_nat n + x) = (ln (G (real n + x)) - ln (fact (n - 1))) / x" by (subst G_fact [symmetric]) (simp add: S_def add_ac of_nat_diff) private lemma G_lower: assumes x: "x > 0" and n: "n \<ge> 1" shows "Gamma_series x n \<le> G x" proof - have "(ln \<circ> G) (real (Suc n)) \<le> ((ln \<circ> G) (real (Suc n) + x) - (ln \<circ> G) (real (Suc n) - 1)) / (real (Suc n) + x - (real (Suc n) - 1)) * (real (Suc n) - (real (Suc n) - 1)) + (ln \<circ> G) (real (Suc n) - 1)" using x n by (intro convex_onD_Icc' convex_on_subset[OF log_convex_G]) auto hence "S (of_nat n) (of_nat (Suc n)) \<le> S (of_nat (Suc n)) (of_nat (Suc n) + x)" unfolding S_def using x by (simp add: field_simps) also have "S (of_nat n) (of_nat (Suc n)) = ln (fact n) - ln (fact (n-1))" unfolding S_def using n by (subst (1 2) G_fact [symmetric]) (simp_all add: add_ac of_nat_diff) also have "\<dots> = ln (fact n / fact (n-1))" by (subst ln_div) simp_all also from n have "fact n / fact (n - 1) = n" by (cases n) simp_all finally have "x * ln (real n) + ln (fact n) \<le> ln (G (real (Suc n) + x))" using x n by (subst (asm) S_eq) (simp_all add: field_simps) also have "x * ln (real n) + ln (fact n) = ln (exp (x * ln (real n)) * fact n)" using x by (simp add: ln_mult) finally have "exp (x * ln (real n)) * fact n \<le> G (real (Suc n) + x)" using x by (subst (asm) ln_le_cancel_iff) (simp_all add: G_pos) also have "G (real (Suc n) + x) = pochhammer x (Suc n) * G x" using G_plus1[of "real (Suc n) + x" for n] G_plus1[of x] x by (induction n) (simp_all add: pochhammer_Suc add_ac) finally show "Gamma_series x n \<le> G x" using x by (simp add: field_simps pochhammer_pos Gamma_series_def) qed private lemma G_upper: assumes x: "x > 0" "x \<le> 1" and n: "n \<ge> 2" shows "G x \<le> Gamma_series x n * (1 + x / real n)" proof - have "(ln \<circ> G) (real n + x) \<le> ((ln \<circ> G) (real n + 1) - (ln \<circ> G) (real n)) / (real n + 1 - (real n)) * ((real n + x) - real n) + (ln \<circ> G) (real n)" using x n by (intro convex_onD_Icc' convex_on_subset[OF log_convex_G]) auto hence "S (of_nat n) (of_nat n + x) \<le> S (of_nat n) (of_nat n + 1)" unfolding S_def using x by (simp add: field_simps) also from n have "S (of_nat n) (of_nat n + 1) = ln (fact n) - ln (fact (n-1))" by (subst (1 2) G_fact [symmetric]) (simp add: S_def add_ac of_nat_diff) also have "\<dots> = ln (fact n / (fact (n-1)))" using n by (subst ln_div) simp_all also from n have "fact n / fact (n - 1) = n" by (cases n) simp_all finally have "ln (G (real n + x)) \<le> x * ln (real n) + ln (fact (n - 1))" using x n by (subst (asm) S_eq) (simp_all add: field_simps) also have "\<dots> = ln (exp (x * ln (real n)) * fact (n - 1))" using x by (simp add: ln_mult) finally have "G (real n + x) \<le> exp (x * ln (real n)) * fact (n - 1)" using x by (subst (asm) ln_le_cancel_iff) (simp_all add: G_pos) also have "G (real n + x) = pochhammer x n * G x" using G_plus1[of "real n + x" for n] x by (induction n) (simp_all add: pochhammer_Suc add_ac) finally have "G x \<le> exp (x * ln (real n)) * fact (n- 1) / pochhammer x n" using x by (simp add: field_simps pochhammer_pos) also from n have "fact (n - 1) = fact n / n" by (cases n) simp_all also have "exp (x * ln (real n)) * \<dots> / pochhammer x n = Gamma_series x n * (1 + x / real n)" using n x by (simp add: Gamma_series_def divide_simps pochhammer_Suc) finally show ?thesis . qed private lemma G_eq_Gamma_aux: assumes x: "x > 0" "x \<le> 1" shows "G x = Gamma x" proof (rule antisym) show "G x \<ge> Gamma x" proof (rule tendsto_upperbound) from G_lower[of x] show "eventually (\<lambda>n. Gamma_series x n \<le> G x) sequentially" using x by (auto intro: eventually_mono[OF eventually_ge_at_top[of "1::nat"]]) qed (simp_all add: Gamma_series_LIMSEQ) next show "G x \<le> Gamma x" proof (rule tendsto_lowerbound) have "(\<lambda>n. Gamma_series x n * (1 + x / real n)) \<longlonglongrightarrow> Gamma x * (1 + 0)" by (rule tendsto_intros real_tendsto_divide_at_top Gamma_series_LIMSEQ filterlim_real_sequentially)+ thus "(\<lambda>n. Gamma_series x n * (1 + x / real n)) \<longlonglongrightarrow> Gamma x" by simp next from G_upper[of x] show "eventually (\<lambda>n. Gamma_series x n * (1 + x / real n) \<ge> G x) sequentially" using x by (auto intro: eventually_mono[OF eventually_ge_at_top[of "2::nat"]]) qed simp_all qed theorem Gamma_pos_real_unique: assumes x: "x > 0" shows "G x = Gamma x" proof - have G_eq: "G (real n + x) = Gamma (real n + x)" if "x \<in> {0<..1}" for n x using that proof (induction n) case (Suc n) from Suc have "x + real n > 0" by simp hence "x + real n \<notin> \<int>\<^sub>\<le>\<^sub>0" by auto with Suc show ?case using G_plus1[of "real n + x"] Gamma_plus1[of "real n + x"] by (auto simp: add_ac) qed (simp_all add: G_eq_Gamma_aux) show ?thesis proof (cases "frac x = 0") case True hence "x = of_int (floor x)" by (simp add: frac_def) with x have x_eq: "x = of_nat (nat (floor x) - 1) + 1" by simp show ?thesis by (subst (1 2) x_eq, rule G_eq) simp_all next case False from assms have x_eq: "x = of_nat (nat (floor x)) + frac x" by (simp add: frac_def) have frac_le_1: "frac x \<le> 1" unfolding frac_def by linarith show ?thesis by (subst (1 2) x_eq, rule G_eq, insert False frac_le_1) simp_all qed qed end subsection \<open>The Beta function\<close> definition Beta where "Beta a b = Gamma a * Gamma b / Gamma (a + b)" lemma Beta_altdef: "Beta a b = Gamma a * Gamma b * rGamma (a + b)" by (simp add: inverse_eq_divide Beta_def Gamma_def) lemma Beta_commute: "Beta a b = Beta b a" unfolding Beta_def by (simp add: ac_simps) lemma has_field_derivative_Beta1 [derivative_intros]: assumes "x \<notin> \<int>\<^sub>\<le>\<^sub>0" "x + y \<notin> \<int>\<^sub>\<le>\<^sub>0" shows "((\<lambda>x. Beta x y) has_field_derivative (Beta x y * (Digamma x - Digamma (x + y)))) (at x within A)" unfolding Beta_altdef by (rule DERIV_cong, (rule derivative_intros assms)+) (simp add: algebra_simps) lemma Beta_pole1: "x \<in> \<int>\<^sub>\<le>\<^sub>0 \<Longrightarrow> Beta x y = 0" by (auto simp add: Beta_def elim!: nonpos_Ints_cases') lemma Beta_pole2: "y \<in> \<int>\<^sub>\<le>\<^sub>0 \<Longrightarrow> Beta x y = 0" by (auto simp add: Beta_def elim!: nonpos_Ints_cases') lemma Beta_zero: "x + y \<in> \<int>\<^sub>\<le>\<^sub>0 \<Longrightarrow> Beta x y = 0" by (auto simp add: Beta_def elim!: nonpos_Ints_cases') lemma has_field_derivative_Beta2 [derivative_intros]: assumes "y \<notin> \<int>\<^sub>\<le>\<^sub>0" "x + y \<notin> \<int>\<^sub>\<le>\<^sub>0" shows "((\<lambda>y. Beta x y) has_field_derivative (Beta x y * (Digamma y - Digamma (x + y)))) (at y within A)" using has_field_derivative_Beta1[of y x A] assms by (simp add: Beta_commute add_ac) theorem Beta_plus1_plus1: assumes "x \<notin> \<int>\<^sub>\<le>\<^sub>0" "y \<notin> \<int>\<^sub>\<le>\<^sub>0" shows "Beta (x + 1) y + Beta x (y + 1) = Beta x y" proof - have "Beta (x + 1) y + Beta x (y + 1) = (Gamma (x + 1) * Gamma y + Gamma x * Gamma (y + 1)) * rGamma ((x + y) + 1)" by (simp add: Beta_altdef add_divide_distrib algebra_simps) also have "\<dots> = (Gamma x * Gamma y) * ((x + y) * rGamma ((x + y) + 1))" by (subst assms[THEN Gamma_plus1])+ (simp add: algebra_simps) also from assms have "\<dots> = Beta x y" unfolding Beta_altdef by (subst rGamma_plus1) simp finally show ?thesis . qed theorem Beta_plus1_left: assumes "x \<notin> \<int>\<^sub>\<le>\<^sub>0" shows "(x + y) * Beta (x + 1) y = x * Beta x y" proof - have "(x + y) * Beta (x + 1) y = Gamma (x + 1) * Gamma y * ((x + y) * rGamma ((x + y) + 1))" unfolding Beta_altdef by (simp only: ac_simps) also have "\<dots> = x * Beta x y" unfolding Beta_altdef by (subst assms[THEN Gamma_plus1] rGamma_plus1)+ (simp only: ac_simps) finally show ?thesis . qed theorem Beta_plus1_right: assumes "y \<notin> \<int>\<^sub>\<le>\<^sub>0" shows "(x + y) * Beta x (y + 1) = y * Beta x y" using Beta_plus1_left[of y x] assms by (simp_all add: Beta_commute add.commute) lemma Gamma_Gamma_Beta: assumes "x + y \<notin> \<int>\<^sub>\<le>\<^sub>0" shows "Gamma x * Gamma y = Beta x y * Gamma (x + y)" unfolding Beta_altdef using assms Gamma_eq_zero_iff[of "x+y"] by (simp add: rGamma_inverse_Gamma) subsection \<open>Legendre duplication theorem\<close> context begin private lemma Gamma_legendre_duplication_aux: fixes z :: "'a :: Gamma" assumes "z \<notin> \<int>\<^sub>\<le>\<^sub>0" "z + 1/2 \<notin> \<int>\<^sub>\<le>\<^sub>0" shows "Gamma z * Gamma (z + 1/2) = exp ((1 - 2*z) * of_real (ln 2)) * Gamma (1/2) * Gamma (2*z)" proof - let ?powr = "\<lambda>b a. exp (a * of_real (ln (of_nat b)))" let ?h = "\<lambda>n. (fact (n-1))\<^sup>2 / fact (2*n-1) * of_nat (2^(2*n)) * exp (1/2 * of_real (ln (real_of_nat n)))" { fix z :: 'a assume z: "z \<notin> \<int>\<^sub>\<le>\<^sub>0" "z + 1/2 \<notin> \<int>\<^sub>\<le>\<^sub>0" let ?g = "\<lambda>n. ?powr 2 (2*z) * Gamma_series' z n * Gamma_series' (z + 1/2) n / Gamma_series' (2*z) (2*n)" have "eventually (\<lambda>n. ?g n = ?h n) sequentially" using eventually_gt_at_top proof eventually_elim fix n :: nat assume n: "n > 0" let ?f = "fact (n - 1) :: 'a" and ?f' = "fact (2*n - 1) :: 'a" have A: "exp t * exp t = exp (2*t :: 'a)" for t by (subst exp_add [symmetric]) simp have A: "Gamma_series' z n * Gamma_series' (z + 1/2) n = ?f^2 * ?powr n (2*z + 1/2) / (pochhammer z n * pochhammer (z + 1/2) n)" by (simp add: Gamma_series'_def exp_add ring_distribs power2_eq_square A mult_ac) have B: "Gamma_series' (2*z) (2*n) = ?f' * ?powr 2 (2*z) * ?powr n (2*z) / (of_nat (2^(2*n)) * pochhammer z n * pochhammer (z+1/2) n)" using n by (simp add: Gamma_series'_def ln_mult exp_add ring_distribs pochhammer_double) from z have "pochhammer z n \<noteq> 0" by (auto dest: pochhammer_eq_0_imp_nonpos_Int) moreover from z have "pochhammer (z + 1/2) n \<noteq> 0" by (auto dest: pochhammer_eq_0_imp_nonpos_Int) ultimately have "?powr 2 (2*z) * (Gamma_series' z n * Gamma_series' (z + 1/2) n) / Gamma_series' (2*z) (2*n) = ?f^2 / ?f' * of_nat (2^(2*n)) * (?powr n ((4*z + 1)/2) * ?powr n (-2*z))" using n unfolding A B by (simp add: field_split_simps exp_minus) also have "?powr n ((4*z + 1)/2) * ?powr n (-2*z) = ?powr n (1/2)" by (simp add: algebra_simps exp_add[symmetric] add_divide_distrib) finally show "?g n = ?h n" by (simp only: mult_ac) qed moreover from z double_in_nonpos_Ints_imp[of z] have "2 * z \<notin> \<int>\<^sub>\<le>\<^sub>0" by auto hence "?g \<longlonglongrightarrow> ?powr 2 (2*z) * Gamma z * Gamma (z+1/2) / Gamma (2*z)" using LIMSEQ_subseq_LIMSEQ[OF Gamma_series'_LIMSEQ, of "(*)2" "2*z"] by (intro tendsto_intros Gamma_series'_LIMSEQ) (simp_all add: o_def strict_mono_def Gamma_eq_zero_iff) ultimately have "?h \<longlonglongrightarrow> ?powr 2 (2*z) * Gamma z * Gamma (z+1/2) / Gamma (2*z)" by (blast intro: Lim_transform_eventually) } note lim = this from assms double_in_nonpos_Ints_imp[of z] have z': "2 * z \<notin> \<int>\<^sub>\<le>\<^sub>0" by auto from fraction_not_in_ints[of 2 1] have "(1/2 :: 'a) \<notin> \<int>\<^sub>\<le>\<^sub>0" by (intro not_in_Ints_imp_not_in_nonpos_Ints) simp_all with lim[of "1/2 :: 'a"] have "?h \<longlonglongrightarrow> 2 * Gamma (1/2 :: 'a)" by (simp add: exp_of_real) from LIMSEQ_unique[OF this lim[OF assms]] z' show ?thesis by (simp add: field_split_simps Gamma_eq_zero_iff ring_distribs exp_diff exp_of_real) qed text \<open> The following lemma is somewhat annoying. With a little bit of complex analysis (Cauchy's integral theorem, to be exact), this would be completely trivial. However, we want to avoid depending on the complex analysis session at this point, so we prove it the hard way. \<close> private lemma Gamma_reflection_aux: defines "h \<equiv> \<lambda>z::complex. if z \<in> \<int> then 0 else (of_real pi * cot (of_real pi*z) + Digamma z - Digamma (1 - z))" defines "a \<equiv> complex_of_real pi" obtains h' where "continuous_on UNIV h'" "\<And>z. (h has_field_derivative (h' z)) (at z)" proof - define f where "f n = a * of_real (cos_coeff (n+1) - sin_coeff (n+2))" for n define F where "F z = (if z = 0 then 0 else (cos (a*z) - sin (a*z)/(a*z)) / z)" for z define g where "g n = complex_of_real (sin_coeff (n+1))" for n define G where "G z = (if z = 0 then 1 else sin (a*z)/(a*z))" for z have a_nz: "a \<noteq> 0" unfolding a_def by simp have "(\<lambda>n. f n * (a*z)^n) sums (F z) \<and> (\<lambda>n. g n * (a*z)^n) sums (G z)" if "abs (Re z) < 1" for z proof (cases "z = 0"; rule conjI) assume "z \<noteq> 0" note z = this that from z have sin_nz: "sin (a*z) \<noteq> 0" unfolding a_def by (auto simp: sin_eq_0) have "(\<lambda>n. of_real (sin_coeff n) * (a*z)^n) sums (sin (a*z))" using sin_converges[of "a*z"] by (simp add: scaleR_conv_of_real) from sums_split_initial_segment[OF this, of 1] have "(\<lambda>n. (a*z) * of_real (sin_coeff (n+1)) * (a*z)^n) sums (sin (a*z))" by (simp add: mult_ac) from sums_mult[OF this, of "inverse (a*z)"] z a_nz have A: "(\<lambda>n. g n * (a*z)^n) sums (sin (a*z)/(a*z))" by (simp add: field_simps g_def) with z show "(\<lambda>n. g n * (a*z)^n) sums (G z)" by (simp add: G_def) from A z a_nz sin_nz have g_nz: "(\<Sum>n. g n * (a*z)^n) \<noteq> 0" by (simp add: sums_iff g_def) have [simp]: "sin_coeff (Suc 0) = 1" by (simp add: sin_coeff_def) from sums_split_initial_segment[OF sums_diff[OF cos_converges[of "a*z"] A], of 1] have "(\<lambda>n. z * f n * (a*z)^n) sums (cos (a*z) - sin (a*z) / (a*z))" by (simp add: mult_ac scaleR_conv_of_real ring_distribs f_def g_def) from sums_mult[OF this, of "inverse z"] z assms show "(\<lambda>n. f n * (a*z)^n) sums (F z)" by (simp add: divide_simps mult_ac f_def F_def) next assume z: "z = 0" have "(\<lambda>n. f n * (a * z) ^ n) sums f 0" using powser_sums_zero[of f] z by simp with z show "(\<lambda>n. f n * (a * z) ^ n) sums (F z)" by (simp add: f_def F_def sin_coeff_def cos_coeff_def) have "(\<lambda>n. g n * (a * z) ^ n) sums g 0" using powser_sums_zero[of g] z by simp with z show "(\<lambda>n. g n * (a * z) ^ n) sums (G z)" by (simp add: g_def G_def sin_coeff_def cos_coeff_def) qed note sums = conjunct1[OF this] conjunct2[OF this] define h2 where [abs_def]: "h2 z = (\<Sum>n. f n * (a*z)^n) / (\<Sum>n. g n * (a*z)^n) + Digamma (1 + z) - Digamma (1 - z)" for z define POWSER where [abs_def]: "POWSER f z = (\<Sum>n. f n * (z^n :: complex))" for f z define POWSER' where [abs_def]: "POWSER' f z = (\<Sum>n. diffs f n * (z^n))" for f and z :: complex define h2' where [abs_def]: "h2' z = a * (POWSER g (a*z) * POWSER' f (a*z) - POWSER f (a*z) * POWSER' g (a*z)) / (POWSER g (a*z))^2 + Polygamma 1 (1 + z) + Polygamma 1 (1 - z)" for z have h_eq: "h t = h2 t" if "abs (Re t) < 1" for t proof - from that have t: "t \<in> \<int> \<longleftrightarrow> t = 0" by (auto elim!: Ints_cases) hence "h t = a*cot (a*t) - 1/t + Digamma (1 + t) - Digamma (1 - t)" unfolding h_def using Digamma_plus1[of t] by (force simp: field_simps a_def) also have "a*cot (a*t) - 1/t = (F t) / (G t)" using t by (auto simp add: divide_simps sin_eq_0 cot_def a_def F_def G_def) also have "\<dots> = (\<Sum>n. f n * (a*t)^n) / (\<Sum>n. g n * (a*t)^n)" using sums[of t] that by (simp add: sums_iff) finally show "h t = h2 t" by (simp only: h2_def) qed let ?A = "{z. abs (Re z) < 1}" have "open ({z. Re z < 1} \<inter> {z. Re z > -1})" using open_halfspace_Re_gt open_halfspace_Re_lt by auto also have "({z. Re z < 1} \<inter> {z. Re z > -1}) = {z. abs (Re z) < 1}" by auto finally have open_A: "open ?A" . hence [simp]: "interior ?A = ?A" by (simp add: interior_open) have summable_f: "summable (\<lambda>n. f n * z^n)" for z by (rule powser_inside, rule sums_summable, rule sums[of "\<i> * of_real (norm z + 1) / a"]) (simp_all add: norm_mult a_def del: of_real_add) have summable_g: "summable (\<lambda>n. g n * z^n)" for z by (rule powser_inside, rule sums_summable, rule sums[of "\<i> * of_real (norm z + 1) / a"]) (simp_all add: norm_mult a_def del: of_real_add) have summable_fg': "summable (\<lambda>n. diffs f n * z^n)" "summable (\<lambda>n. diffs g n * z^n)" for z by (intro termdiff_converges_all summable_f summable_g)+ have "(POWSER f has_field_derivative (POWSER' f z)) (at z)" "(POWSER g has_field_derivative (POWSER' g z)) (at z)" for z unfolding POWSER_def POWSER'_def by (intro termdiffs_strong_converges_everywhere summable_f summable_g)+ note derivs = this[THEN DERIV_chain2[OF _ DERIV_cmult[OF DERIV_ident]], unfolded POWSER_def] have "isCont (POWSER f) z" "isCont (POWSER g) z" "isCont (POWSER' f) z" "isCont (POWSER' g) z" for z unfolding POWSER_def POWSER'_def by (intro isCont_powser_converges_everywhere summable_f summable_g summable_fg')+ note cont = this[THEN isCont_o2[rotated], unfolded POWSER_def POWSER'_def] { fix z :: complex assume z: "abs (Re z) < 1" define d where "d = \<i> * of_real (norm z + 1)" have d: "abs (Re d) < 1" "norm z < norm d" by (simp_all add: d_def norm_mult del: of_real_add) have "eventually (\<lambda>z. h z = h2 z) (nhds z)" using eventually_nhds_in_nhd[of z ?A] using h_eq z by (auto elim!: eventually_mono) moreover from sums(2)[OF z] z have nz: "(\<Sum>n. g n * (a * z) ^ n) \<noteq> 0" unfolding G_def by (auto simp: sums_iff sin_eq_0 a_def) have A: "z \<in> \<int> \<longleftrightarrow> z = 0" using z by (auto elim!: Ints_cases) have no_int: "1 + z \<in> \<int> \<longleftrightarrow> z = 0" using z Ints_diff[of "1+z" 1] A by (auto elim!: nonpos_Ints_cases) have no_int': "1 - z \<in> \<int> \<longleftrightarrow> z = 0" using z Ints_diff[of 1 "1-z"] A by (auto elim!: nonpos_Ints_cases) from no_int no_int' have no_int: "1 - z \<notin> \<int>\<^sub>\<le>\<^sub>0" "1 + z \<notin> \<int>\<^sub>\<le>\<^sub>0" by auto have "(h2 has_field_derivative h2' z) (at z)" unfolding h2_def by (rule DERIV_cong, (rule derivative_intros refl derivs[unfolded POWSER_def] nz no_int)+) (auto simp: h2'_def POWSER_def field_simps power2_eq_square) ultimately have deriv: "(h has_field_derivative h2' z) (at z)" by (subst DERIV_cong_ev[OF refl _ refl]) from sums(2)[OF z] z have "(\<Sum>n. g n * (a * z) ^ n) \<noteq> 0" unfolding G_def by (auto simp: sums_iff a_def sin_eq_0) hence "isCont h2' z" using no_int unfolding h2'_def[abs_def] POWSER_def POWSER'_def by (intro continuous_intros cont continuous_on_compose2[OF _ continuous_on_Polygamma[of "{z. Re z > 0}"]]) auto note deriv and this } note A = this interpret h: periodic_fun_simple' h proof fix z :: complex show "h (z + 1) = h z" proof (cases "z \<in> \<int>") assume z: "z \<notin> \<int>" hence A: "z + 1 \<notin> \<int>" "z \<noteq> 0" using Ints_diff[of "z+1" 1] by auto hence "Digamma (z + 1) - Digamma (-z) = Digamma z - Digamma (-z + 1)" by (subst (1 2) Digamma_plus1) simp_all with A z show "h (z + 1) = h z" by (simp add: h_def sin_plus_pi cos_plus_pi ring_distribs cot_def) qed (simp add: h_def) qed have h2'_eq: "h2' (z - 1) = h2' z" if z: "Re z > 0" "Re z < 1" for z proof - have "((\<lambda>z. h (z - 1)) has_field_derivative h2' (z - 1)) (at z)" by (rule DERIV_cong, rule DERIV_chain'[OF _ A(1)]) (insert z, auto intro!: derivative_eq_intros) hence "(h has_field_derivative h2' (z - 1)) (at z)" by (subst (asm) h.minus_1) moreover from z have "(h has_field_derivative h2' z) (at z)" by (intro A) simp_all ultimately show "h2' (z - 1) = h2' z" by (rule DERIV_unique) qed define h2'' where "h2'' z = h2' (z - of_int \<lfloor>Re z\<rfloor>)" for z have deriv: "(h has_field_derivative h2'' z) (at z)" for z proof - fix z :: complex have B: "\<bar>Re z - real_of_int \<lfloor>Re z\<rfloor>\<bar> < 1" by linarith have "((\<lambda>t. h (t - of_int \<lfloor>Re z\<rfloor>)) has_field_derivative h2'' z) (at z)" unfolding h2''_def by (rule DERIV_cong, rule DERIV_chain'[OF _ A(1)]) (insert B, auto intro!: derivative_intros) thus "(h has_field_derivative h2'' z) (at z)" by (simp add: h.minus_of_int) qed have cont: "continuous_on UNIV h2''" proof (intro continuous_at_imp_continuous_on ballI) fix z :: complex define r where "r = \<lfloor>Re z\<rfloor>" define A where "A = {t. of_int r - 1 < Re t \<and> Re t < of_int r + 1}" have "continuous_on A (\<lambda>t. h2' (t - of_int r))" unfolding A_def by (intro continuous_at_imp_continuous_on isCont_o2[OF _ A(2)] ballI continuous_intros) (simp_all add: abs_real_def) moreover have "h2'' t = h2' (t - of_int r)" if t: "t \<in> A" for t proof (cases "Re t \<ge> of_int r") case True from t have "of_int r - 1 < Re t" "Re t < of_int r + 1" by (simp_all add: A_def) with True have "\<lfloor>Re t\<rfloor> = \<lfloor>Re z\<rfloor>" unfolding r_def by linarith thus ?thesis by (auto simp: r_def h2''_def) next case False from t have t: "of_int r - 1 < Re t" "Re t < of_int r + 1" by (simp_all add: A_def) with False have t': "\<lfloor>Re t\<rfloor> = \<lfloor>Re z\<rfloor> - 1" unfolding r_def by linarith moreover from t False have "h2' (t - of_int r + 1 - 1) = h2' (t - of_int r + 1)" by (intro h2'_eq) simp_all ultimately show ?thesis by (auto simp: r_def h2''_def algebra_simps t') qed ultimately have "continuous_on A h2''" by (subst continuous_on_cong[OF refl]) moreover { have "open ({t. of_int r - 1 < Re t} \<inter> {t. of_int r + 1 > Re t})" by (intro open_Int open_halfspace_Re_gt open_halfspace_Re_lt) also have "{t. of_int r - 1 < Re t} \<inter> {t. of_int r + 1 > Re t} = A" unfolding A_def by blast finally have "open A" . } ultimately have C: "isCont h2'' t" if "t \<in> A" for t using that by (subst (asm) continuous_on_eq_continuous_at) auto have "of_int r - 1 < Re z" "Re z < of_int r + 1" unfolding r_def by linarith+ thus "isCont h2'' z" by (intro C) (simp_all add: A_def) qed from that[OF cont deriv] show ?thesis . qed lemma Gamma_reflection_complex: fixes z :: complex shows "Gamma z * Gamma (1 - z) = of_real pi / sin (of_real pi * z)" proof - let ?g = "\<lambda>z::complex. Gamma z * Gamma (1 - z) * sin (of_real pi * z)" define g where [abs_def]: "g z = (if z \<in> \<int> then of_real pi else ?g z)" for z :: complex let ?h = "\<lambda>z::complex. (of_real pi * cot (of_real pi*z) + Digamma z - Digamma (1 - z))" define h where [abs_def]: "h z = (if z \<in> \<int> then 0 else ?h z)" for z :: complex \<comment> \<open>@{term g} is periodic with period 1.\<close> interpret g: periodic_fun_simple' g proof fix z :: complex show "g (z + 1) = g z" proof (cases "z \<in> \<int>") case False hence "z * g z = z * Beta z (- z + 1) * sin (of_real pi * z)" by (simp add: g_def Beta_def) also have "z * Beta z (- z + 1) = (z + 1 + -z) * Beta (z + 1) (- z + 1)" using False Ints_diff[of 1 "1 - z"] nonpos_Ints_subset_Ints by (subst Beta_plus1_left [symmetric]) auto also have "\<dots> * sin (of_real pi * z) = z * (Beta (z + 1) (-z) * sin (of_real pi * (z + 1)))" using False Ints_diff[of "z+1" 1] Ints_minus[of "-z"] nonpos_Ints_subset_Ints by (subst Beta_plus1_right) (auto simp: ring_distribs sin_plus_pi) also from False have "Beta (z + 1) (-z) * sin (of_real pi * (z + 1)) = g (z + 1)" using Ints_diff[of "z+1" 1] by (auto simp: g_def Beta_def) finally show "g (z + 1) = g z" using False by (subst (asm) mult_left_cancel) auto qed (simp add: g_def) qed \<comment> \<open>@{term g} is entire.\<close> have g_g': "(g has_field_derivative (h z * g z)) (at z)" for z :: complex proof (cases "z \<in> \<int>") let ?h' = "\<lambda>z. Beta z (1 - z) * ((Digamma z - Digamma (1 - z)) * sin (z * of_real pi) + of_real pi * cos (z * of_real pi))" case False from False have "eventually (\<lambda>t. t \<in> UNIV - \<int>) (nhds z)" by (intro eventually_nhds_in_open) (auto simp: open_Diff) hence "eventually (\<lambda>t. g t = ?g t) (nhds z)" by eventually_elim (simp add: g_def) moreover { from False Ints_diff[of 1 "1-z"] have "1 - z \<notin> \<int>" by auto hence "(?g has_field_derivative ?h' z) (at z)" using nonpos_Ints_subset_Ints by (auto intro!: derivative_eq_intros simp: algebra_simps Beta_def) also from False have "sin (of_real pi * z) \<noteq> 0" by (subst sin_eq_0) auto hence "?h' z = h z * g z" using False unfolding g_def h_def cot_def by (simp add: field_simps Beta_def) finally have "(?g has_field_derivative (h z * g z)) (at z)" . } ultimately show ?thesis by (subst DERIV_cong_ev[OF refl _ refl]) next case True then obtain n where z: "z = of_int n" by (auto elim!: Ints_cases) let ?t = "(\<lambda>z::complex. if z = 0 then 1 else sin z / z) \<circ> (\<lambda>z. of_real pi * z)" have deriv_0: "(g has_field_derivative 0) (at 0)" proof (subst DERIV_cong_ev[OF refl _ refl]) show "eventually (\<lambda>z. g z = of_real pi * Gamma (1 + z) * Gamma (1 - z) * ?t z) (nhds 0)" using eventually_nhds_ball[OF zero_less_one, of "0::complex"] proof eventually_elim fix z :: complex assume z: "z \<in> ball 0 1" show "g z = of_real pi * Gamma (1 + z) * Gamma (1 - z) * ?t z" proof (cases "z = 0") assume z': "z \<noteq> 0" with z have z'': "z \<notin> \<int>\<^sub>\<le>\<^sub>0" "z \<notin> \<int>" by (auto elim!: Ints_cases) from Gamma_plus1[OF this(1)] have "Gamma z = Gamma (z + 1) / z" by simp with z'' z' show ?thesis by (simp add: g_def ac_simps) qed (simp add: g_def) qed have "(?t has_field_derivative (0 * of_real pi)) (at 0)" using has_field_derivative_sin_z_over_z[of "UNIV :: complex set"] by (intro DERIV_chain) simp_all thus "((\<lambda>z. of_real pi * Gamma (1 + z) * Gamma (1 - z) * ?t z) has_field_derivative 0) (at 0)" by (auto intro!: derivative_eq_intros simp: o_def) qed have "((g \<circ> (\<lambda>x. x - of_int n)) has_field_derivative 0 * 1) (at (of_int n))" using deriv_0 by (intro DERIV_chain) (auto intro!: derivative_eq_intros) also have "g \<circ> (\<lambda>x. x - of_int n) = g" by (intro ext) (simp add: g.minus_of_int) finally show "(g has_field_derivative (h z * g z)) (at z)" by (simp add: z h_def) qed have g_eq: "g (z/2) * g ((z+1)/2) = Gamma (1/2)^2 * g z" if "Re z > -1" "Re z < 2" for z proof (cases "z \<in> \<int>") case True with that have "z = 0 \<or> z = 1" by (force elim!: Ints_cases) moreover have "g 0 * g (1/2) = Gamma (1/2)^2 * g 0" using fraction_not_in_ints[where 'a = complex, of 2 1] by (simp add: g_def power2_eq_square) moreover have "g (1/2) * g 1 = Gamma (1/2)^2 * g 1" using fraction_not_in_ints[where 'a = complex, of 2 1] by (simp add: g_def power2_eq_square Beta_def algebra_simps) ultimately show ?thesis by force next case False hence z: "z/2 \<notin> \<int>" "(z+1)/2 \<notin> \<int>" using Ints_diff[of "z+1" 1] by (auto elim!: Ints_cases) hence z': "z/2 \<notin> \<int>\<^sub>\<le>\<^sub>0" "(z+1)/2 \<notin> \<int>\<^sub>\<le>\<^sub>0" by (auto elim!: nonpos_Ints_cases) from z have "1-z/2 \<notin> \<int>" "1-((z+1)/2) \<notin> \<int>" using Ints_diff[of 1 "1-z/2"] Ints_diff[of 1 "1-((z+1)/2)"] by auto hence z'': "1-z/2 \<notin> \<int>\<^sub>\<le>\<^sub>0" "1-((z+1)/2) \<notin> \<int>\<^sub>\<le>\<^sub>0" by (auto elim!: nonpos_Ints_cases) from z have "g (z/2) * g ((z+1)/2) = (Gamma (z/2) * Gamma ((z+1)/2)) * (Gamma (1-z/2) * Gamma (1-((z+1)/2))) * (sin (of_real pi * z/2) * sin (of_real pi * (z+1)/2))" by (simp add: g_def) also from z' Gamma_legendre_duplication_aux[of "z/2"] have "Gamma (z/2) * Gamma ((z+1)/2) = exp ((1-z) * of_real (ln 2)) * Gamma (1/2) * Gamma z" by (simp add: add_divide_distrib) also from z'' Gamma_legendre_duplication_aux[of "1-(z+1)/2"] have "Gamma (1-z/2) * Gamma (1-(z+1)/2) = Gamma (1-z) * Gamma (1/2) * exp (z * of_real (ln 2))" by (simp add: add_divide_distrib ac_simps) finally have "g (z/2) * g ((z+1)/2) = Gamma (1/2)^2 * (Gamma z * Gamma (1-z) * (2 * (sin (of_real pi*z/2) * sin (of_real pi*(z+1)/2))))" by (simp add: add_ac power2_eq_square exp_add ring_distribs exp_diff exp_of_real) also have "sin (of_real pi*(z+1)/2) = cos (of_real pi*z/2)" using cos_sin_eq[of "- of_real pi * z/2", symmetric] by (simp add: ring_distribs add_divide_distrib ac_simps) also have "2 * (sin (of_real pi*z/2) * cos (of_real pi*z/2)) = sin (of_real pi * z)" by (subst sin_times_cos) (simp add: field_simps) also have "Gamma z * Gamma (1 - z) * sin (complex_of_real pi * z) = g z" using \<open>z \<notin> \<int>\<close> by (simp add: g_def) finally show ?thesis . qed have g_eq: "g (z/2) * g ((z+1)/2) = Gamma (1/2)^2 * g z" for z proof - define r where "r = \<lfloor>Re z / 2\<rfloor>" have "Gamma (1/2)^2 * g z = Gamma (1/2)^2 * g (z - of_int (2*r))" by (simp only: g.minus_of_int) also have "of_int (2*r) = 2 * of_int r" by simp also have "Re z - 2 * of_int r > -1" "Re z - 2 * of_int r < 2" unfolding r_def by linarith+ hence "Gamma (1/2)^2 * g (z - 2 * of_int r) = g ((z - 2 * of_int r)/2) * g ((z - 2 * of_int r + 1)/2)" unfolding r_def by (intro g_eq[symmetric]) simp_all also have "(z - 2 * of_int r) / 2 = z/2 - of_int r" by simp also have "g \<dots> = g (z/2)" by (rule g.minus_of_int) also have "(z - 2 * of_int r + 1) / 2 = (z + 1)/2 - of_int r" by simp also have "g \<dots> = g ((z+1)/2)" by (rule g.minus_of_int) finally show ?thesis .. qed have g_nz [simp]: "g z \<noteq> 0" for z :: complex unfolding g_def using Ints_diff[of 1 "1 - z"] by (auto simp: Gamma_eq_zero_iff sin_eq_0 dest!: nonpos_Ints_Int) have h_eq: "h z = (h (z/2) + h ((z+1)/2)) / 2" for z proof - have "((\<lambda>t. g (t/2) * g ((t+1)/2)) has_field_derivative (g (z/2) * g ((z+1)/2)) * ((h (z/2) + h ((z+1)/2)) / 2)) (at z)" by (auto intro!: derivative_eq_intros g_g'[THEN DERIV_chain2] simp: field_simps) hence "((\<lambda>t. Gamma (1/2)^2 * g t) has_field_derivative Gamma (1/2)^2 * g z * ((h (z/2) + h ((z+1)/2)) / 2)) (at z)" by (subst (1 2) g_eq[symmetric]) simp from DERIV_cmult[OF this, of "inverse ((Gamma (1/2))^2)"] have "(g has_field_derivative (g z * ((h (z/2) + h ((z+1)/2))/2))) (at z)" using fraction_not_in_ints[where 'a = complex, of 2 1] by (simp add: divide_simps Gamma_eq_zero_iff not_in_Ints_imp_not_in_nonpos_Ints) moreover have "(g has_field_derivative (g z * h z)) (at z)" using g_g'[of z] by (simp add: ac_simps) ultimately have "g z * h z = g z * ((h (z/2) + h ((z+1)/2))/2)" by (intro DERIV_unique) thus "h z = (h (z/2) + h ((z+1)/2)) / 2" by simp qed obtain h' where h'_cont: "continuous_on UNIV h'" and h_h': "\<And>z. (h has_field_derivative h' z) (at z)" unfolding h_def by (erule Gamma_reflection_aux) have h'_eq: "h' z = (h' (z/2) + h' ((z+1)/2)) / 4" for z proof - have "((\<lambda>t. (h (t/2) + h ((t+1)/2)) / 2) has_field_derivative ((h' (z/2) + h' ((z+1)/2)) / 4)) (at z)" by (fastforce intro!: derivative_eq_intros h_h'[THEN DERIV_chain2]) hence "(h has_field_derivative ((h' (z/2) + h' ((z+1)/2))/4)) (at z)" by (subst (asm) h_eq[symmetric]) from h_h' and this show "h' z = (h' (z/2) + h' ((z+1)/2)) / 4" by (rule DERIV_unique) qed have h'_zero: "h' z = 0" for z proof - define m where "m = max 1 \<bar>Re z\<bar>" define B where "B = {t. abs (Re t) \<le> m \<and> abs (Im t) \<le> abs (Im z)}" have "closed ({t. Re t \<ge> -m} \<inter> {t. Re t \<le> m} \<inter> {t. Im t \<ge> -\<bar>Im z\<bar>} \<inter> {t. Im t \<le> \<bar>Im z\<bar>})" (is "closed ?B") by (intro closed_Int closed_halfspace_Re_ge closed_halfspace_Re_le closed_halfspace_Im_ge closed_halfspace_Im_le) also have "?B = B" unfolding B_def by fastforce finally have "closed B" . moreover have "bounded B" unfolding bounded_iff proof (intro ballI exI) fix t assume t: "t \<in> B" have "norm t \<le> \<bar>Re t\<bar> + \<bar>Im t\<bar>" by (rule cmod_le) also from t have "\<bar>Re t\<bar> \<le> m" unfolding B_def by blast also from t have "\<bar>Im t\<bar> \<le> \<bar>Im z\<bar>" unfolding B_def by blast finally show "norm t \<le> m + \<bar>Im z\<bar>" by - simp qed ultimately have compact: "compact B" by (subst compact_eq_bounded_closed) blast define M where "M = (SUP z\<in>B. norm (h' z))" have "compact (h' ` B)" by (intro compact_continuous_image continuous_on_subset[OF h'_cont] compact) blast+ hence bdd: "bdd_above ((\<lambda>z. norm (h' z)) ` B)" using bdd_above_norm[of "h' ` B"] by (simp add: image_comp o_def compact_imp_bounded) have "norm (h' z) \<le> M" unfolding M_def by (intro cSUP_upper bdd) (simp_all add: B_def m_def) also have "M \<le> M/2" proof (subst M_def, subst cSUP_le_iff) have "z \<in> B" unfolding B_def m_def by simp thus "B \<noteq> {}" by auto next show "\<forall>z\<in>B. norm (h' z) \<le> M/2" proof fix t :: complex assume t: "t \<in> B" from h'_eq[of t] t have "h' t = (h' (t/2) + h' ((t+1)/2)) / 4" by (simp) also have "norm \<dots> = norm (h' (t/2) + h' ((t+1)/2)) / 4" by simp also have "norm (h' (t/2) + h' ((t+1)/2)) \<le> norm (h' (t/2)) + norm (h' ((t+1)/2))" by (rule norm_triangle_ineq) also from t have "abs (Re ((t + 1)/2)) \<le> m" unfolding m_def B_def by auto with t have "t/2 \<in> B" "(t+1)/2 \<in> B" unfolding B_def by auto hence "norm (h' (t/2)) + norm (h' ((t+1)/2)) \<le> M + M" unfolding M_def by (intro add_mono cSUP_upper bdd) (auto simp: B_def) also have "(M + M) / 4 = M / 2" by simp finally show "norm (h' t) \<le> M/2" by - simp_all qed qed (insert bdd, auto) hence "M \<le> 0" by simp finally show "h' z = 0" by simp qed have h_h'_2: "(h has_field_derivative 0) (at z)" for z using h_h'[of z] h'_zero[of z] by simp have g_real: "g z \<in> \<real>" if "z \<in> \<real>" for z unfolding g_def using that by (auto intro!: Reals_mult Gamma_complex_real) have h_real: "h z \<in> \<real>" if "z \<in> \<real>" for z unfolding h_def using that by (auto intro!: Reals_mult Reals_add Reals_diff Polygamma_Real) have g_nz: "g z \<noteq> 0" for z unfolding g_def using Ints_diff[of 1 "1-z"] by (auto simp: Gamma_eq_zero_iff sin_eq_0) from h'_zero h_h'_2 have "\<exists>c. \<forall>z\<in>UNIV. h z = c" by (intro has_field_derivative_zero_constant) (simp_all add: dist_0_norm) then obtain c where c: "\<And>z. h z = c" by auto have "\<exists>u. u \<in> closed_segment 0 1 \<and> Re (g 1) - Re (g 0) = Re (h u * g u * (1 - 0))" by (intro complex_mvt_line g_g') then obtain u where u: "u \<in> closed_segment 0 1" "Re (g 1) - Re (g 0) = Re (h u * g u)" by auto from u(1) have u': "u \<in> \<real>" unfolding closed_segment_def by (auto simp: scaleR_conv_of_real) from u' g_real[of u] g_nz[of u] have "Re (g u) \<noteq> 0" by (auto elim!: Reals_cases) with u(2) c[of u] g_real[of u] g_nz[of u] u' have "Re c = 0" by (simp add: complex_is_Real_iff g.of_1) with h_real[of 0] c[of 0] have "c = 0" by (auto elim!: Reals_cases) with c have A: "h z * g z = 0" for z by simp hence "(g has_field_derivative 0) (at z)" for z using g_g'[of z] by simp hence "\<exists>c'. \<forall>z\<in>UNIV. g z = c'" by (intro has_field_derivative_zero_constant) simp_all then obtain c' where c: "\<And>z. g z = c'" by (force) from this[of 0] have "c' = pi" unfolding g_def by simp with c have "g z = pi" by simp show ?thesis proof (cases "z \<in> \<int>") case False with \<open>g z = pi\<close> show ?thesis by (auto simp: g_def divide_simps) next case True then obtain n where n: "z = of_int n" by (elim Ints_cases) with sin_eq_0[of "of_real pi * z"] have "sin (of_real pi * z) = 0" by force moreover have "of_int (1 - n) \<in> \<int>\<^sub>\<le>\<^sub>0" if "n > 0" using that by (intro nonpos_Ints_of_int) simp ultimately show ?thesis using n by (cases "n \<le> 0") (auto simp: Gamma_eq_zero_iff nonpos_Ints_of_int) qed qed lemma rGamma_reflection_complex: "rGamma z * rGamma (1 - z :: complex) = sin (of_real pi * z) / of_real pi" using Gamma_reflection_complex[of z] by (simp add: Gamma_def field_split_simps split: if_split_asm) lemma rGamma_reflection_complex': "rGamma z * rGamma (- z :: complex) = -z * sin (of_real pi * z) / of_real pi" proof - have "rGamma z * rGamma (-z) = -z * (rGamma z * rGamma (1 - z))" using rGamma_plus1[of "-z", symmetric] by simp also have "rGamma z * rGamma (1 - z) = sin (of_real pi * z) / of_real pi" by (rule rGamma_reflection_complex) finally show ?thesis by simp qed lemma Gamma_reflection_complex': "Gamma z * Gamma (- z :: complex) = - of_real pi / (z * sin (of_real pi * z))" using rGamma_reflection_complex'[of z] by (force simp add: Gamma_def field_split_simps) lemma Gamma_one_half_real: "Gamma (1/2 :: real) = sqrt pi" proof - from Gamma_reflection_complex[of "1/2"] fraction_not_in_ints[where 'a = complex, of 2 1] have "Gamma (1/2 :: complex)^2 = of_real pi" by (simp add: power2_eq_square) hence "of_real pi = Gamma (complex_of_real (1/2))^2" by simp also have "\<dots> = of_real ((Gamma (1/2))^2)" by (subst Gamma_complex_of_real) simp_all finally have "Gamma (1/2)^2 = pi" by (subst (asm) of_real_eq_iff) simp_all moreover have "Gamma (1/2 :: real) \<ge> 0" using Gamma_real_pos[of "1/2"] by simp ultimately show ?thesis by (rule real_sqrt_unique [symmetric]) qed lemma Gamma_one_half_complex: "Gamma (1/2 :: complex) = of_real (sqrt pi)" proof - have "Gamma (1/2 :: complex) = Gamma (of_real (1/2))" by simp also have "\<dots> = of_real (sqrt pi)" by (simp only: Gamma_complex_of_real Gamma_one_half_real) finally show ?thesis . qed theorem Gamma_legendre_duplication: fixes z :: complex assumes "z \<notin> \<int>\<^sub>\<le>\<^sub>0" "z + 1/2 \<notin> \<int>\<^sub>\<le>\<^sub>0" shows "Gamma z * Gamma (z + 1/2) = exp ((1 - 2*z) * of_real (ln 2)) * of_real (sqrt pi) * Gamma (2*z)" using Gamma_legendre_duplication_aux[OF assms] by (simp add: Gamma_one_half_complex) end subsection\<^marker>\<open>tag unimportant\<close> \<open>Limits and residues\<close> text \<open> The inverse of the Gamma function has simple zeros: \<close> lemma rGamma_zeros: "(\<lambda>z. rGamma z / (z + of_nat n)) \<midarrow> (- of_nat n) \<rightarrow> ((-1)^n * fact n :: 'a :: Gamma)" proof (subst tendsto_cong) let ?f = "\<lambda>z. pochhammer z n * rGamma (z + of_nat (Suc n)) :: 'a" from eventually_at_ball'[OF zero_less_one, of "- of_nat n :: 'a" UNIV] show "eventually (\<lambda>z. rGamma z / (z + of_nat n) = ?f z) (at (- of_nat n))" by (subst pochhammer_rGamma[of _ "Suc n"]) (auto elim!: eventually_mono simp: field_split_simps pochhammer_rec' eq_neg_iff_add_eq_0) have "isCont ?f (- of_nat n)" by (intro continuous_intros) thus "?f \<midarrow> (- of_nat n) \<rightarrow> (- 1) ^ n * fact n" unfolding isCont_def by (simp add: pochhammer_same) qed text \<open> The simple zeros of the inverse of the Gamma function correspond to simple poles of the Gamma function, and their residues can easily be computed from the limit we have just proven: \<close> lemma Gamma_poles: "filterlim Gamma at_infinity (at (- of_nat n :: 'a :: Gamma))" proof - from eventually_at_ball'[OF zero_less_one, of "- of_nat n :: 'a" UNIV] have "eventually (\<lambda>z. rGamma z \<noteq> (0 :: 'a)) (at (- of_nat n))" by (auto elim!: eventually_mono nonpos_Ints_cases' simp: rGamma_eq_zero_iff dist_of_nat dist_minus) with isCont_rGamma[of "- of_nat n :: 'a", OF continuous_ident] have "filterlim (\<lambda>z. inverse (rGamma z) :: 'a) at_infinity (at (- of_nat n))" unfolding isCont_def by (intro filterlim_compose[OF filterlim_inverse_at_infinity]) (simp_all add: filterlim_at) moreover have "(\<lambda>z. inverse (rGamma z) :: 'a) = Gamma" by (intro ext) (simp add: rGamma_inverse_Gamma) ultimately show ?thesis by (simp only: ) qed lemma Gamma_residues: "(\<lambda>z. Gamma z * (z + of_nat n)) \<midarrow> (- of_nat n) \<rightarrow> ((-1)^n / fact n :: 'a :: Gamma)" proof (subst tendsto_cong) let ?c = "(- 1) ^ n / fact n :: 'a" from eventually_at_ball'[OF zero_less_one, of "- of_nat n :: 'a" UNIV] show "eventually (\<lambda>z. Gamma z * (z + of_nat n) = inverse (rGamma z / (z + of_nat n))) (at (- of_nat n))" by (auto elim!: eventually_mono simp: field_split_simps rGamma_inverse_Gamma) have "(\<lambda>z. inverse (rGamma z / (z + of_nat n))) \<midarrow> (- of_nat n) \<rightarrow> inverse ((- 1) ^ n * fact n :: 'a)" by (intro tendsto_intros rGamma_zeros) simp_all also have "inverse ((- 1) ^ n * fact n) = ?c" by (simp_all add: field_simps flip: power_mult_distrib) finally show "(\<lambda>z. inverse (rGamma z / (z + of_nat n))) \<midarrow> (- of_nat n) \<rightarrow> ?c" . qed subsection \<open>Alternative definitions\<close> subsubsection \<open>Variant of the Euler form\<close> definition Gamma_series_euler' where "Gamma_series_euler' z n = inverse z * (\<Prod>k=1..n. exp (z * of_real (ln (1 + inverse (of_nat k)))) / (1 + z / of_nat k))" context begin private lemma Gamma_euler'_aux1: fixes z :: "'a :: {real_normed_field,banach}" assumes n: "n > 0" shows "exp (z * of_real (ln (of_nat n + 1))) = (\<Prod>k=1..n. exp (z * of_real (ln (1 + 1 / of_nat k))))" proof - have "(\<Prod>k=1..n. exp (z * of_real (ln (1 + 1 / of_nat k)))) = exp (z * of_real (\<Sum>k = 1..n. ln (1 + 1 / real_of_nat k)))" by (subst exp_sum [symmetric]) (simp_all add: sum_distrib_left) also have "(\<Sum>k=1..n. ln (1 + 1 / of_nat k) :: real) = ln (\<Prod>k=1..n. 1 + 1 / real_of_nat k)" by (subst ln_prod [symmetric]) (auto intro!: add_pos_nonneg) also have "(\<Prod>k=1..n. 1 + 1 / of_nat k :: real) = (\<Prod>k=1..n. (of_nat k + 1) / of_nat k)" by (intro prod.cong) (simp_all add: field_split_simps) also have "(\<Prod>k=1..n. (of_nat k + 1) / of_nat k :: real) = of_nat n + 1" by (induction n) (simp_all add: prod.nat_ivl_Suc' field_split_simps) finally show ?thesis .. qed theorem Gamma_series_euler': assumes z: "(z :: 'a :: Gamma) \<notin> \<int>\<^sub>\<le>\<^sub>0" shows "(\<lambda>n. Gamma_series_euler' z n) \<longlonglongrightarrow> Gamma z" proof (rule Gamma_seriesI, rule Lim_transform_eventually) let ?f = "\<lambda>n. fact n * exp (z * of_real (ln (of_nat n + 1))) / pochhammer z (n + 1)" let ?r = "\<lambda>n. ?f n / Gamma_series z n" let ?r' = "\<lambda>n. exp (z * of_real (ln (of_nat (Suc n) / of_nat n)))" from z have z': "z \<noteq> 0" by auto have "eventually (\<lambda>n. ?r' n = ?r n) sequentially" using z by (auto simp: field_split_simps Gamma_series_def ring_distribs exp_diff ln_div intro: eventually_mono eventually_gt_at_top[of "0::nat"] dest: pochhammer_eq_0_imp_nonpos_Int) moreover have "?r' \<longlonglongrightarrow> exp (z * of_real (ln 1))" by (intro tendsto_intros LIMSEQ_Suc_n_over_n) simp_all ultimately show "?r \<longlonglongrightarrow> 1" by (force intro: Lim_transform_eventually) from eventually_gt_at_top[of "0::nat"] show "eventually (\<lambda>n. ?r n = Gamma_series_euler' z n / Gamma_series z n) sequentially" proof eventually_elim fix n :: nat assume n: "n > 0" from n z' have "Gamma_series_euler' z n = exp (z * of_real (ln (of_nat n + 1))) / (z * (\<Prod>k=1..n. (1 + z / of_nat k)))" by (subst Gamma_euler'_aux1) (simp_all add: Gamma_series_euler'_def prod.distrib prod_inversef[symmetric] divide_inverse) also have "(\<Prod>k=1..n. (1 + z / of_nat k)) = pochhammer (z + 1) n / fact n" proof (cases n) case (Suc n') then show ?thesis unfolding pochhammer_prod fact_prod by (simp add: atLeastLessThanSuc_atLeastAtMost field_simps prod_dividef prod.atLeast_Suc_atMost_Suc_shift del: prod.cl_ivl_Suc) qed auto also have "z * \<dots> = pochhammer z (Suc n) / fact n" by (simp add: pochhammer_rec) finally show "?r n = Gamma_series_euler' z n / Gamma_series z n" by simp qed qed end subsubsection \<open>Weierstrass form\<close> definition Gamma_series_Weierstrass :: "'a :: {banach,real_normed_field} \<Rightarrow> nat \<Rightarrow> 'a" where "Gamma_series_Weierstrass z n = exp (-euler_mascheroni * z) / z * (\<Prod>k=1..n. exp (z / of_nat k) / (1 + z / of_nat k))" definition\<^marker>\<open>tag unimportant\<close> rGamma_series_Weierstrass :: "'a :: {banach,real_normed_field} \<Rightarrow> nat \<Rightarrow> 'a" where "rGamma_series_Weierstrass z n = exp (euler_mascheroni * z) * z * (\<Prod>k=1..n. (1 + z / of_nat k) * exp (-z / of_nat k))" lemma Gamma_series_Weierstrass_nonpos_Ints: "eventually (\<lambda>k. Gamma_series_Weierstrass (- of_nat n) k = 0) sequentially" using eventually_ge_at_top[of n] by eventually_elim (auto simp: Gamma_series_Weierstrass_def) lemma rGamma_series_Weierstrass_nonpos_Ints: "eventually (\<lambda>k. rGamma_series_Weierstrass (- of_nat n) k = 0) sequentially" using eventually_ge_at_top[of n] by eventually_elim (auto simp: rGamma_series_Weierstrass_def) theorem Gamma_Weierstrass_complex: "Gamma_series_Weierstrass z \<longlonglongrightarrow> Gamma (z :: complex)" proof (cases "z \<in> \<int>\<^sub>\<le>\<^sub>0") case True then obtain n where "z = - of_nat n" by (elim nonpos_Ints_cases') also from True have "Gamma_series_Weierstrass \<dots> \<longlonglongrightarrow> Gamma z" by (simp add: tendsto_cong[OF Gamma_series_Weierstrass_nonpos_Ints] Gamma_nonpos_Int) finally show ?thesis . next case False hence z: "z \<noteq> 0" by auto let ?f = "(\<lambda>x. \<Prod>x = Suc 0..x. exp (z / of_nat x) / (1 + z / of_nat x))" have A: "exp (ln (1 + z / of_nat n)) = (1 + z / of_nat n)" if "n \<ge> 1" for n :: nat using False that by (subst exp_Ln) (auto simp: field_simps dest!: plus_of_nat_eq_0_imp) have "(\<lambda>n. \<Sum>k=1..n. z / of_nat k - ln (1 + z / of_nat k)) \<longlonglongrightarrow> ln_Gamma z + euler_mascheroni * z + ln z" using ln_Gamma_series'_aux[OF False] by (simp only: atLeastLessThanSuc_atLeastAtMost [symmetric] One_nat_def sum.shift_bounds_Suc_ivl sums_def atLeast0LessThan) from tendsto_exp[OF this] False z have "?f \<longlonglongrightarrow> z * exp (euler_mascheroni * z) * Gamma z" by (simp add: exp_add exp_sum exp_diff mult_ac Gamma_complex_altdef A) from tendsto_mult[OF tendsto_const[of "exp (-euler_mascheroni * z) / z"] this] z show "Gamma_series_Weierstrass z \<longlonglongrightarrow> Gamma z" by (simp add: exp_minus field_split_simps Gamma_series_Weierstrass_def [abs_def]) qed lemma tendsto_complex_of_real_iff: "((\<lambda>x. complex_of_real (f x)) \<longlongrightarrow> of_real c) F = (f \<longlongrightarrow> c) F" by (rule tendsto_of_real_iff) lemma Gamma_Weierstrass_real: "Gamma_series_Weierstrass x \<longlonglongrightarrow> Gamma (x :: real)" using Gamma_Weierstrass_complex[of "of_real x"] unfolding Gamma_series_Weierstrass_def[abs_def] by (subst tendsto_complex_of_real_iff [symmetric]) (simp_all add: exp_of_real[symmetric] Gamma_complex_of_real) lemma rGamma_Weierstrass_complex: "rGamma_series_Weierstrass z \<longlonglongrightarrow> rGamma (z :: complex)" proof (cases "z \<in> \<int>\<^sub>\<le>\<^sub>0") case True then obtain n where "z = - of_nat n" by (elim nonpos_Ints_cases') also from True have "rGamma_series_Weierstrass \<dots> \<longlonglongrightarrow> rGamma z" by (simp add: tendsto_cong[OF rGamma_series_Weierstrass_nonpos_Ints] rGamma_nonpos_Int) finally show ?thesis . next case False have "rGamma_series_Weierstrass z = (\<lambda>n. inverse (Gamma_series_Weierstrass z n))" by (simp add: rGamma_series_Weierstrass_def[abs_def] Gamma_series_Weierstrass_def exp_minus divide_inverse prod_inversef[symmetric] mult_ac) also from False have "\<dots> \<longlonglongrightarrow> inverse (Gamma z)" by (intro tendsto_intros Gamma_Weierstrass_complex) (simp add: Gamma_eq_zero_iff) finally show ?thesis by (simp add: Gamma_def) qed subsubsection \<open>Binomial coefficient form\<close> lemma Gamma_gbinomial: "(\<lambda>n. ((z + of_nat n) gchoose n) * exp (-z * of_real (ln (of_nat n)))) \<longlonglongrightarrow> rGamma (z+1)" proof (cases "z = 0") case False show ?thesis proof (rule Lim_transform_eventually) let ?powr = "\<lambda>a b. exp (b * of_real (ln (of_nat a)))" show "eventually (\<lambda>n. rGamma_series z n / z = ((z + of_nat n) gchoose n) * ?powr n (-z)) sequentially" proof (intro always_eventually allI) fix n :: nat from False have "((z + of_nat n) gchoose n) = pochhammer z (Suc n) / z / fact n" by (simp add: gbinomial_pochhammer' pochhammer_rec) also have "pochhammer z (Suc n) / z / fact n * ?powr n (-z) = rGamma_series z n / z" by (simp add: rGamma_series_def field_split_simps exp_minus) finally show "rGamma_series z n / z = ((z + of_nat n) gchoose n) * ?powr n (-z)" .. qed from False have "(\<lambda>n. rGamma_series z n / z) \<longlonglongrightarrow> rGamma z / z" by (intro tendsto_intros) also from False have "rGamma z / z = rGamma (z + 1)" using rGamma_plus1[of z] by (simp add: field_simps) finally show "(\<lambda>n. rGamma_series z n / z) \<longlonglongrightarrow> rGamma (z+1)" . qed qed (simp_all add: binomial_gbinomial [symmetric]) lemma gbinomial_minus': "(a + of_nat b) gchoose b = (- 1) ^ b * (- (a + 1) gchoose b)" by (subst gbinomial_minus) (simp add: power_mult_distrib [symmetric]) lemma gbinomial_asymptotic: fixes z :: "'a :: Gamma" shows "(\<lambda>n. (z gchoose n) / ((-1)^n / exp ((z+1) * of_real (ln (real n))))) \<longlonglongrightarrow> inverse (Gamma (- z))" unfolding rGamma_inverse_Gamma [symmetric] using Gamma_gbinomial[of "-z-1"] by (subst (asm) gbinomial_minus') (simp add: add_ac mult_ac divide_inverse power_inverse [symmetric]) lemma fact_binomial_limit: "(\<lambda>n. of_nat ((k + n) choose n) / of_nat (n ^ k) :: 'a :: Gamma) \<longlonglongrightarrow> 1 / fact k" proof (rule Lim_transform_eventually) have "(\<lambda>n. of_nat ((k + n) choose n) / of_real (exp (of_nat k * ln (real_of_nat n)))) \<longlonglongrightarrow> 1 / Gamma (of_nat (Suc k) :: 'a)" (is "?f \<longlonglongrightarrow> _") using Gamma_gbinomial[of "of_nat k :: 'a"] by (simp add: binomial_gbinomial Gamma_def field_split_simps exp_of_real [symmetric] exp_minus) also have "Gamma (of_nat (Suc k)) = fact k" by (simp add: Gamma_fact) finally show "?f \<longlonglongrightarrow> 1 / fact k" . show "eventually (\<lambda>n. ?f n = of_nat ((k + n) choose n) / of_nat (n ^ k)) sequentially" using eventually_gt_at_top[of "0::nat"] proof eventually_elim fix n :: nat assume n: "n > 0" from n have "exp (real_of_nat k * ln (real_of_nat n)) = real_of_nat (n^k)" by (simp add: exp_of_nat_mult) thus "?f n = of_nat ((k + n) choose n) / of_nat (n ^ k)" by simp qed qed lemma binomial_asymptotic': "(\<lambda>n. of_nat ((k + n) choose n) / (of_nat (n ^ k) / fact k) :: 'a :: Gamma) \<longlonglongrightarrow> 1" using tendsto_mult[OF fact_binomial_limit[of k] tendsto_const[of "fact k :: 'a"]] by simp lemma gbinomial_Beta: assumes "z + 1 \<notin> \<int>\<^sub>\<le>\<^sub>0" shows "((z::'a::Gamma) gchoose n) = inverse ((z + 1) * Beta (z - of_nat n + 1) (of_nat n + 1))" using assms proof (induction n arbitrary: z) case 0 hence "z + 2 \<notin> \<int>\<^sub>\<le>\<^sub>0" using plus_one_in_nonpos_Ints_imp[of "z+1"] by (auto simp: add.commute) with 0 show ?case by (auto simp: Beta_def Gamma_eq_zero_iff Gamma_plus1 [symmetric] add.commute) next case (Suc n z) show ?case proof (cases "z \<in> \<int>\<^sub>\<le>\<^sub>0") case True with Suc.prems have "z = 0" by (auto elim!: nonpos_Ints_cases simp: algebra_simps one_plus_of_int_in_nonpos_Ints_iff) show ?thesis proof (cases "n = 0") case True with \<open>z = 0\<close> show ?thesis by (simp add: Beta_def Gamma_eq_zero_iff Gamma_plus1 [symmetric]) next case False with \<open>z = 0\<close> show ?thesis by (simp_all add: Beta_pole1 one_minus_of_nat_in_nonpos_Ints_iff) qed next case False have "(z gchoose (Suc n)) = ((z - 1 + 1) gchoose (Suc n))" by simp also have "\<dots> = (z - 1 gchoose n) * ((z - 1) + 1) / of_nat (Suc n)" by (subst gbinomial_factors) (simp add: field_simps) also from False have "\<dots> = inverse (of_nat (Suc n) * Beta (z - of_nat n) (of_nat (Suc n)))" (is "_ = inverse ?x") by (subst Suc.IH) (simp_all add: field_simps Beta_pole1) also have "of_nat (Suc n) \<notin> (\<int>\<^sub>\<le>\<^sub>0 :: 'a set)" by (subst of_nat_in_nonpos_Ints_iff) simp_all hence "?x = (z + 1) * Beta (z - of_nat (Suc n) + 1) (of_nat (Suc n) + 1)" by (subst Beta_plus1_right [symmetric]) simp_all finally show ?thesis . qed qed theorem gbinomial_Gamma: assumes "z + 1 \<notin> \<int>\<^sub>\<le>\<^sub>0" shows "(z gchoose n) = Gamma (z + 1) / (fact n * Gamma (z - of_nat n + 1))" proof - have "(z gchoose n) = Gamma (z + 2) / (z + 1) / (fact n * Gamma (z - of_nat n + 1))" by (subst gbinomial_Beta[OF assms]) (simp_all add: Beta_def Gamma_fact [symmetric] add_ac) also from assms have "Gamma (z + 2) / (z + 1) = Gamma (z + 1)" using Gamma_plus1[of "z+1"] by (auto simp add: field_split_simps) finally show ?thesis . qed subsubsection \<open>Integral form\<close> lemma integrable_on_powr_from_0': assumes a: "a > (-1::real)" and c: "c \<ge> 0" shows "(\<lambda>x. x powr a) integrable_on {0<..c}" proof - from c have *: "{0<..c} - {0..c} = {}" "{0..c} - {0<..c} = {0}" by auto show ?thesis by (rule integrable_spike_set [OF integrable_on_powr_from_0[OF a c]]) (simp_all add: *) qed lemma absolutely_integrable_Gamma_integral: assumes "Re z > 0" "a > 0" shows "(\<lambda>t. complex_of_real t powr (z - 1) / of_real (exp (a * t))) absolutely_integrable_on {0<..}" (is "?f absolutely_integrable_on _") proof - have "((\<lambda>x. (Re z - 1) * (ln x / x)) \<longlongrightarrow> (Re z - 1) * 0) at_top" by (intro tendsto_intros ln_x_over_x_tendsto_0) hence "((\<lambda>x. ((Re z - 1) * ln x) / x) \<longlongrightarrow> 0) at_top" by simp from order_tendstoD(2)[OF this, of "a/2"] and \<open>a > 0\<close> have "eventually (\<lambda>x. (Re z - 1) * ln x / x < a/2) at_top" by simp from eventually_conj[OF this eventually_gt_at_top[of 0]] obtain x0 where "\<forall>x\<ge>x0. (Re z - 1) * ln x / x < a/2 \<and> x > 0" by (auto simp: eventually_at_top_linorder) hence "x0 > 0" by simp have "x powr (Re z - 1) / exp (a * x) < exp (-(a/2) * x)" if "x \<ge> x0" for x proof - from that and \<open>\<forall>x\<ge>x0. _\<close> have x: "(Re z - 1) * ln x / x < a / 2" "x > 0" by auto have "x powr (Re z - 1) = exp ((Re z - 1) * ln x)" using \<open>x > 0\<close> by (simp add: powr_def) also from x have "(Re z - 1) * ln x < (a * x) / 2" by (simp add: field_simps) finally show ?thesis by (simp add: field_simps exp_add [symmetric]) qed note x0 = \<open>x0 > 0\<close> this have "?f absolutely_integrable_on ({0<..x0} \<union> {x0..})" proof (rule set_integrable_Un) show "?f absolutely_integrable_on {0<..x0}" unfolding set_integrable_def proof (rule Bochner_Integration.integrable_bound [OF _ _ AE_I2]) show "integrable lebesgue (\<lambda>x. indicat_real {0<..x0} x *\<^sub>R x powr (Re z - 1))" using x0(1) assms by (intro nonnegative_absolutely_integrable_1 [unfolded set_integrable_def] integrable_on_powr_from_0') auto show "(\<lambda>x. indicat_real {0<..x0} x *\<^sub>R (x powr (z - 1) / exp (a * x))) \<in> borel_measurable lebesgue" by (intro measurable_completion) (auto intro!: borel_measurable_continuous_on_indicator continuous_intros) fix x :: real have "x powr (Re z - 1) / exp (a * x) \<le> x powr (Re z - 1) / 1" if "x \<ge> 0" using that assms by (intro divide_left_mono) auto thus "norm (indicator {0<..x0} x *\<^sub>R ?f x) \<le> norm (indicator {0<..x0} x *\<^sub>R x powr (Re z - 1))" by (simp_all add: norm_divide norm_powr_real_powr indicator_def) qed next show "?f absolutely_integrable_on {x0..}" unfolding set_integrable_def proof (rule Bochner_Integration.integrable_bound [OF _ _ AE_I2]) show "integrable lebesgue (\<lambda>x. indicat_real {x0..} x *\<^sub>R exp (- (a / 2) * x))" using assms by (intro nonnegative_absolutely_integrable_1 [unfolded set_integrable_def] integrable_on_exp_minus_to_infinity) auto show "(\<lambda>x. indicat_real {x0..} x *\<^sub>R (x powr (z - 1) / exp (a * x))) \<in> borel_measurable lebesgue" using x0(1) by (intro measurable_completion) (auto intro!: borel_measurable_continuous_on_indicator continuous_intros) fix x :: real show "norm (indicator {x0..} x *\<^sub>R ?f x) \<le> norm (indicator {x0..} x *\<^sub>R exp (-(a/2) * x))" using x0 by (auto simp: norm_divide norm_powr_real_powr indicator_def less_imp_le) qed qed auto also have "{0<..x0} \<union> {x0..} = {0<..}" using x0(1) by auto finally show ?thesis . qed lemma integrable_Gamma_integral_bound: fixes a c :: real assumes a: "a > -1" and c: "c \<ge> 0" defines "f \<equiv> \<lambda>x. if x \<in> {0..c} then x powr a else exp (-x/2)" shows "f integrable_on {0..}" proof - have "f integrable_on {0..c}" by (rule integrable_spike_finite[of "{}", OF _ _ integrable_on_powr_from_0[of a c]]) (insert a c, simp_all add: f_def) moreover have A: "(\<lambda>x. exp (-x/2)) integrable_on {c..}" using integrable_on_exp_minus_to_infinity[of "1/2"] by simp have "f integrable_on {c..}" by (rule integrable_spike_finite[of "{c}", OF _ _ A]) (simp_all add: f_def) ultimately show "f integrable_on {0..}" by (rule integrable_Un') (insert c, auto simp: max_def) qed theorem Gamma_integral_complex: assumes z: "Re z > 0" shows "((\<lambda>t. of_real t powr (z - 1) / of_real (exp t)) has_integral Gamma z) {0..}" proof - have A: "((\<lambda>t. (of_real t) powr (z - 1) * of_real ((1 - t) ^ n)) has_integral (fact n / pochhammer z (n+1))) {0..1}" if "Re z > 0" for n z using that proof (induction n arbitrary: z) case 0 have "((\<lambda>t. complex_of_real t powr (z - 1)) has_integral (of_real 1 powr z / z - of_real 0 powr z / z)) {0..1}" using 0 by (intro fundamental_theorem_of_calculus_interior) (auto intro!: continuous_intros derivative_eq_intros has_vector_derivative_real_field) thus ?case by simp next case (Suc n) let ?f = "\<lambda>t. complex_of_real t powr z / z" let ?f' = "\<lambda>t. complex_of_real t powr (z - 1)" let ?g = "\<lambda>t. (1 - complex_of_real t) ^ Suc n" let ?g' = "\<lambda>t. - ((1 - complex_of_real t) ^ n) * of_nat (Suc n)" have "((\<lambda>t. ?f' t * ?g t) has_integral (of_nat (Suc n)) * fact n / pochhammer z (n+2)) {0..1}" (is "(_ has_integral ?I) _") proof (rule integration_by_parts_interior[where f' = ?f' and g = ?g]) from Suc.prems show "continuous_on {0..1} ?f" "continuous_on {0..1} ?g" by (auto intro!: continuous_intros) next fix t :: real assume t: "t \<in> {0<..<1}" show "(?f has_vector_derivative ?f' t) (at t)" using t Suc.prems by (auto intro!: derivative_eq_intros has_vector_derivative_real_field) show "(?g has_vector_derivative ?g' t) (at t)" by (rule has_vector_derivative_real_field derivative_eq_intros refl)+ simp_all next from Suc.prems have [simp]: "z \<noteq> 0" by auto from Suc.prems have A: "Re (z + of_nat n) > 0" for n by simp have [simp]: "z + of_nat n \<noteq> 0" "z + 1 + of_nat n \<noteq> 0" for n using A[of n] A[of "Suc n"] by (auto simp add: add.assoc simp del: plus_complex.sel) have "((\<lambda>x. of_real x powr z * of_real ((1 - x) ^ n) * (- of_nat (Suc n) / z)) has_integral fact n / pochhammer (z+1) (n+1) * (- of_nat (Suc n) / z)) {0..1}" (is "(?A has_integral ?B) _") using Suc.IH[of "z+1"] Suc.prems by (intro has_integral_mult_left) (simp_all add: add_ac pochhammer_rec) also have "?A = (\<lambda>t. ?f t * ?g' t)" by (intro ext) (simp_all add: field_simps) also have "?B = - (of_nat (Suc n) * fact n / pochhammer z (n+2))" by (simp add: field_split_simps pochhammer_rec prod.shift_bounds_cl_Suc_ivl del: of_nat_Suc) finally show "((\<lambda>t. ?f t * ?g' t) has_integral (?f 1 * ?g 1 - ?f 0 * ?g 0 - ?I)) {0..1}" by simp qed (simp_all add: bounded_bilinear_mult) thus ?case by simp qed have B: "((\<lambda>t. if t \<in> {0..of_nat n} then of_real t powr (z - 1) * (1 - of_real t / of_nat n) ^ n else 0) has_integral (of_nat n powr z * fact n / pochhammer z (n+1))) {0..}" for n proof (cases "n > 0") case [simp]: True hence [simp]: "n \<noteq> 0" by auto with has_integral_affinity01[OF A[OF z, of n], of "inverse (of_nat n)" 0] have "((\<lambda>x. (of_nat n - of_real x) ^ n * (of_real x / of_nat n) powr (z - 1) / of_nat n ^ n) has_integral fact n * of_nat n / pochhammer z (n+1)) ((\<lambda>x. real n * x)`{0..1})" (is "(?f has_integral ?I) ?ivl") by (simp add: field_simps scaleR_conv_of_real) also from True have "((\<lambda>x. real n*x)`{0..1}) = {0..real n}" by (subst image_mult_atLeastAtMost) simp_all also have "?f = (\<lambda>x. (of_real x / of_nat n) powr (z - 1) * (1 - of_real x / of_nat n) ^ n)" using True by (intro ext) (simp add: field_simps) finally have "((\<lambda>x. (of_real x / of_nat n) powr (z - 1) * (1 - of_real x / of_nat n) ^ n) has_integral ?I) {0..real n}" (is ?P) . also have "?P \<longleftrightarrow> ((\<lambda>x. exp ((z - 1) * of_real (ln (x / of_nat n))) * (1 - of_real x / of_nat n) ^ n) has_integral ?I) {0..real n}" by (intro has_integral_spike_finite_eq[of "{0}"]) (auto simp: powr_def Ln_of_real [symmetric]) also have "\<dots> \<longleftrightarrow> ((\<lambda>x. exp ((z - 1) * of_real (ln x - ln (of_nat n))) * (1 - of_real x / of_nat n) ^ n) has_integral ?I) {0..real n}" by (intro has_integral_spike_finite_eq[of "{0}"]) (simp_all add: ln_div) finally have \<dots> . note B = has_integral_mult_right[OF this, of "exp ((z - 1) * ln (of_nat n))"] have "((\<lambda>x. exp ((z - 1) * of_real (ln x)) * (1 - of_real x / of_nat n) ^ n) has_integral (?I * exp ((z - 1) * ln (of_nat n)))) {0..real n}" (is ?P) by (insert B, subst (asm) mult.assoc [symmetric], subst (asm) exp_add [symmetric]) (simp add: algebra_simps) also have "?P \<longleftrightarrow> ((\<lambda>x. of_real x powr (z - 1) * (1 - of_real x / of_nat n) ^ n) has_integral (?I * exp ((z - 1) * ln (of_nat n)))) {0..real n}" by (intro has_integral_spike_finite_eq[of "{0}"]) (simp_all add: powr_def Ln_of_real) also have "fact n * of_nat n / pochhammer z (n+1) * exp ((z - 1) * Ln (of_nat n)) = (of_nat n powr z * fact n / pochhammer z (n+1))" by (auto simp add: powr_def algebra_simps exp_diff exp_of_real) finally show ?thesis by (subst has_integral_restrict) simp_all next case False thus ?thesis by (subst has_integral_restrict) (simp_all add: has_integral_refl) qed have "eventually (\<lambda>n. Gamma_series z n = of_nat n powr z * fact n / pochhammer z (n+1)) sequentially" using eventually_gt_at_top[of "0::nat"] by eventually_elim (simp add: powr_def algebra_simps Gamma_series_def) from this and Gamma_series_LIMSEQ[of z] have C: "(\<lambda>k. of_nat k powr z * fact k / pochhammer z (k+1)) \<longlonglongrightarrow> Gamma z" by (blast intro: Lim_transform_eventually) { fix x :: real assume x: "x \<ge> 0" have lim_exp: "(\<lambda>k. (1 - x / real k) ^ k) \<longlonglongrightarrow> exp (-x)" using tendsto_exp_limit_sequentially[of "-x"] by simp have "(\<lambda>k. of_real x powr (z - 1) * of_real ((1 - x / of_nat k) ^ k)) \<longlonglongrightarrow> of_real x powr (z - 1) * of_real (exp (-x))" (is ?P) by (intro tendsto_intros lim_exp) also from eventually_gt_at_top[of "nat \<lceil>x\<rceil>"] have "eventually (\<lambda>k. of_nat k > x) sequentially" by eventually_elim linarith hence "?P \<longleftrightarrow> (\<lambda>k. if x \<le> of_nat k then of_real x powr (z - 1) * of_real ((1 - x / of_nat k) ^ k) else 0) \<longlonglongrightarrow> of_real x powr (z - 1) * of_real (exp (-x))" by (intro tendsto_cong) (auto elim!: eventually_mono) finally have \<dots> . } hence D: "\<forall>x\<in>{0..}. (\<lambda>k. if x \<in> {0..real k} then of_real x powr (z - 1) * (1 - of_real x / of_nat k) ^ k else 0) \<longlonglongrightarrow> of_real x powr (z - 1) / of_real (exp x)" by (simp add: exp_minus field_simps cong: if_cong) have "((\<lambda>x. (Re z - 1) * (ln x / x)) \<longlongrightarrow> (Re z - 1) * 0) at_top" by (intro tendsto_intros ln_x_over_x_tendsto_0) hence "((\<lambda>x. ((Re z - 1) * ln x) / x) \<longlongrightarrow> 0) at_top" by simp from order_tendstoD(2)[OF this, of "1/2"] have "eventually (\<lambda>x. (Re z - 1) * ln x / x < 1/2) at_top" by simp from eventually_conj[OF this eventually_gt_at_top[of 0]] obtain x0 where "\<forall>x\<ge>x0. (Re z - 1) * ln x / x < 1/2 \<and> x > 0" by (auto simp: eventually_at_top_linorder) hence x0: "x0 > 0" "\<And>x. x \<ge> x0 \<Longrightarrow> (Re z - 1) * ln x < x / 2" by auto define h where "h = (\<lambda>x. if x \<in> {0..x0} then x powr (Re z - 1) else exp (-x/2))" have le_h: "x powr (Re z - 1) * exp (-x) \<le> h x" if x: "x \<ge> 0" for x proof (cases "x > x0") case True from True x0(1) have "x powr (Re z - 1) * exp (-x) = exp ((Re z - 1) * ln x - x)" by (simp add: powr_def exp_diff exp_minus field_simps exp_add) also from x0(2)[of x] True have "\<dots> < exp (-x/2)" by (simp add: field_simps) finally show ?thesis using True by (auto simp add: h_def) next case False from x have "x powr (Re z - 1) * exp (- x) \<le> x powr (Re z - 1) * 1" by (intro mult_left_mono) simp_all with False show ?thesis by (auto simp add: h_def) qed have E: "\<forall>x\<in>{0..}. cmod (if x \<in> {0..real k} then of_real x powr (z - 1) * (1 - complex_of_real x / of_nat k) ^ k else 0) \<le> h x" (is "\<forall>x\<in>_. ?f x \<le> _") for k proof safe fix x :: real assume x: "x \<ge> 0" { fix x :: real and n :: nat assume x: "x \<le> of_nat n" have "(1 - complex_of_real x / of_nat n) = complex_of_real ((1 - x / of_nat n))" by simp also have "norm \<dots> = \<bar>(1 - x / real n)\<bar>" by (subst norm_of_real) (rule refl) also from x have "\<dots> = (1 - x / real n)" by (intro abs_of_nonneg) (simp_all add: field_split_simps) finally have "cmod (1 - complex_of_real x / of_nat n) = 1 - x / real n" . } note D = this from D[of x k] x have "?f x \<le> (if of_nat k \<ge> x \<and> k > 0 then x powr (Re z - 1) * (1 - x / real k) ^ k else 0)" by (auto simp: norm_mult norm_powr_real_powr norm_power intro!: mult_nonneg_nonneg) also have "\<dots> \<le> x powr (Re z - 1) * exp (-x)" by (auto intro!: mult_left_mono exp_ge_one_minus_x_over_n_power_n) also from x have "\<dots> \<le> h x" by (rule le_h) finally show "?f x \<le> h x" . qed have F: "h integrable_on {0..}" unfolding h_def by (rule integrable_Gamma_integral_bound) (insert assms x0(1), simp_all) show ?thesis by (rule has_integral_dominated_convergence[OF B F E D C]) qed lemma Gamma_integral_real: assumes x: "x > (0 :: real)" shows "((\<lambda>t. t powr (x - 1) / exp t) has_integral Gamma x) {0..}" proof - have A: "((\<lambda>t. complex_of_real t powr (complex_of_real x - 1) / complex_of_real (exp t)) has_integral complex_of_real (Gamma x)) {0..}" using Gamma_integral_complex[of x] assms by (simp_all add: Gamma_complex_of_real powr_of_real) have "((\<lambda>t. complex_of_real (t powr (x - 1) / exp t)) has_integral of_real (Gamma x)) {0..}" by (rule has_integral_eq[OF _ A]) (simp_all add: powr_of_real [symmetric]) from has_integral_linear[OF this bounded_linear_Re] show ?thesis by (simp add: o_def) qed lemma absolutely_integrable_Gamma_integral': assumes "Re z > 0" shows "(\<lambda>t. complex_of_real t powr (z - 1) / of_real (exp t)) absolutely_integrable_on {0<..}" using absolutely_integrable_Gamma_integral [OF assms zero_less_one] by simp lemma Gamma_integral_complex': assumes z: "Re z > 0" shows "((\<lambda>t. of_real t powr (z - 1) / of_real (exp t)) has_integral Gamma z) {0<..}" proof - have "((\<lambda>t. of_real t powr (z - 1) / of_real (exp t)) has_integral Gamma z) {0..}" by (rule Gamma_integral_complex) fact+ hence "((\<lambda>t. if t \<in> {0<..} then of_real t powr (z - 1) / of_real (exp t) else 0) has_integral Gamma z) {0..}" by (rule has_integral_spike [of "{0}", rotated 2]) auto also have "?this = ?thesis" by (subst has_integral_restrict) auto finally show ?thesis . qed lemma Gamma_conv_nn_integral_real: assumes "s > (0::real)" shows "Gamma s = nn_integral lborel (\<lambda>t. ennreal (indicator {0..} t * t powr (s - 1) / exp t))" using nn_integral_has_integral_lebesgue[OF _ Gamma_integral_real[OF assms]] by simp lemma integrable_Beta: assumes "a > 0" "b > (0::real)" shows "set_integrable lborel {0..1} (\<lambda>t. t powr (a - 1) * (1 - t) powr (b - 1))" proof - define C where "C = max 1 ((1/2) powr (b - 1))" define D where "D = max 1 ((1/2) powr (a - 1))" have C: "(1 - x) powr (b - 1) \<le> C" if "x \<in> {0..1/2}" for x proof (cases "b < 1") case False with that have "(1 - x) powr (b - 1) \<le> (1 powr (b - 1))" by (intro powr_mono2) auto thus ?thesis by (auto simp: C_def) qed (insert that, auto simp: max.coboundedI1 max.coboundedI2 powr_mono2' powr_mono2 C_def) have D: "x powr (a - 1) \<le> D" if "x \<in> {1/2..1}" for x proof (cases "a < 1") case False with that have "x powr (a - 1) \<le> (1 powr (a - 1))" by (intro powr_mono2) auto thus ?thesis by (auto simp: D_def) next case True qed (insert that, auto simp: max.coboundedI1 max.coboundedI2 powr_mono2' powr_mono2 D_def) have [simp]: "C \<ge> 0" "D \<ge> 0" by (simp_all add: C_def D_def) have I1: "set_integrable lborel {0..1/2} (\<lambda>t. t powr (a - 1) * (1 - t) powr (b - 1))" unfolding set_integrable_def proof (rule Bochner_Integration.integrable_bound[OF _ _ AE_I2]) have "(\<lambda>t. t powr (a - 1)) integrable_on {0..1/2}" by (rule integrable_on_powr_from_0) (use assms in auto) hence "(\<lambda>t. t powr (a - 1)) absolutely_integrable_on {0..1/2}" by (subst absolutely_integrable_on_iff_nonneg) auto from integrable_mult_right[OF this [unfolded set_integrable_def], of C] show "integrable lborel (\<lambda>x. indicat_real {0..1/2} x *\<^sub>R (C * x powr (a - 1)))" by (subst (asm) integrable_completion) (auto simp: mult_ac) next fix x :: real have "x powr (a - 1) * (1 - x) powr (b - 1) \<le> x powr (a - 1) * C" if "x \<in> {0..1/2}" using that by (intro mult_left_mono powr_mono2 C) auto thus "norm (indicator {0..1/2} x *\<^sub>R (x powr (a - 1) * (1 - x) powr (b - 1))) \<le> norm (indicator {0..1/2} x *\<^sub>R (C * x powr (a - 1)))" by (auto simp: indicator_def abs_mult mult_ac) qed (auto intro!: AE_I2 simp: indicator_def) have I2: "set_integrable lborel {1/2..1} (\<lambda>t. t powr (a - 1) * (1 - t) powr (b - 1))" unfolding set_integrable_def proof (rule Bochner_Integration.integrable_bound[OF _ _ AE_I2]) have "(\<lambda>t. t powr (b - 1)) integrable_on {0..1/2}" by (rule integrable_on_powr_from_0) (use assms in auto) hence "(\<lambda>t. t powr (b - 1)) integrable_on (cbox 0 (1/2))" by simp from integrable_affinity[OF this, of "-1" 1] have "(\<lambda>t. (1 - t) powr (b - 1)) integrable_on {1/2..1}" by simp hence "(\<lambda>t. (1 - t) powr (b - 1)) absolutely_integrable_on {1/2..1}" by (subst absolutely_integrable_on_iff_nonneg) auto from integrable_mult_right[OF this [unfolded set_integrable_def], of D] show "integrable lborel (\<lambda>x. indicat_real {1/2..1} x *\<^sub>R (D * (1 - x) powr (b - 1)))" by (subst (asm) integrable_completion) (auto simp: mult_ac) next fix x :: real have "x powr (a - 1) * (1 - x) powr (b - 1) \<le> D * (1 - x) powr (b - 1)" if "x \<in> {1/2..1}" using that by (intro mult_right_mono powr_mono2 D) auto thus "norm (indicator {1/2..1} x *\<^sub>R (x powr (a - 1) * (1 - x) powr (b - 1))) \<le> norm (indicator {1/2..1} x *\<^sub>R (D * (1 - x) powr (b - 1)))" by (auto simp: indicator_def abs_mult mult_ac) qed (auto intro!: AE_I2 simp: indicator_def) have "set_integrable lborel ({0..1/2} \<union> {1/2..1}) (\<lambda>t. t powr (a - 1) * (1 - t) powr (b - 1))" by (intro set_integrable_Un I1 I2) auto also have "{0..1/2} \<union> {1/2..1} = {0..(1::real)}" by auto finally show ?thesis . qed lemma integrable_Beta': assumes "a > 0" "b > (0::real)" shows "(\<lambda>t. t powr (a - 1) * (1 - t) powr (b - 1)) integrable_on {0..1}" using integrable_Beta[OF assms] by (rule set_borel_integral_eq_integral) theorem has_integral_Beta_real: assumes a: "a > 0" and b: "b > (0 :: real)" shows "((\<lambda>t. t powr (a - 1) * (1 - t) powr (b - 1)) has_integral Beta a b) {0..1}" proof - define B where "B = integral {0..1} (\<lambda>x. x powr (a - 1) * (1 - x) powr (b - 1))" have [simp]: "B \<ge> 0" unfolding B_def using a b by (intro integral_nonneg integrable_Beta') auto from a b have "ennreal (Gamma a * Gamma b) = (\<integral>\<^sup>+ t. ennreal (indicator {0..} t * t powr (a - 1) / exp t) \<partial>lborel) * (\<integral>\<^sup>+ t. ennreal (indicator {0..} t * t powr (b - 1) / exp t) \<partial>lborel)" by (subst ennreal_mult') (simp_all add: Gamma_conv_nn_integral_real) also have "\<dots> = (\<integral>\<^sup>+t. \<integral>\<^sup>+u. ennreal (indicator {0..} t * t powr (a - 1) / exp t) * ennreal (indicator {0..} u * u powr (b - 1) / exp u) \<partial>lborel \<partial>lborel)" by (simp add: nn_integral_cmult nn_integral_multc) also have "\<dots> = (\<integral>\<^sup>+t. \<integral>\<^sup>+u. ennreal (indicator ({0..}\<times>{0..}) (t,u) * t powr (a - 1) * u powr (b - 1) / exp (t + u)) \<partial>lborel \<partial>lborel)" by (intro nn_integral_cong) (auto simp: indicator_def divide_ennreal ennreal_mult' [symmetric] exp_add) also have "\<dots> = (\<integral>\<^sup>+t. \<integral>\<^sup>+u. ennreal (indicator ({0..}\<times>{t..}) (t,u) * t powr (a - 1) * (u - t) powr (b - 1) / exp u) \<partial>lborel \<partial>lborel)" proof (rule nn_integral_cong, goal_cases) case (1 t) have "(\<integral>\<^sup>+u. ennreal (indicator ({0..}\<times>{0..}) (t,u) * t powr (a - 1) * u powr (b - 1) / exp (t + u)) \<partial>distr lborel borel ((+) (-t))) = (\<integral>\<^sup>+u. ennreal (indicator ({0..}\<times>{t..}) (t,u) * t powr (a - 1) * (u - t) powr (b - 1) / exp u) \<partial>lborel)" by (subst nn_integral_distr) (auto intro!: nn_integral_cong simp: indicator_def) thus ?case by (subst (asm) lborel_distr_plus) qed also have "\<dots> = (\<integral>\<^sup>+u. \<integral>\<^sup>+t. ennreal (indicator ({0..}\<times>{t..}) (t,u) * t powr (a - 1) * (u - t) powr (b - 1) / exp u) \<partial>lborel \<partial>lborel)" by (subst lborel_pair.Fubini') (auto simp: case_prod_unfold indicator_def cong: measurable_cong_sets) also have "\<dots> = (\<integral>\<^sup>+u. \<integral>\<^sup>+t. ennreal (indicator {0..u} t * t powr (a - 1) * (u - t) powr (b - 1)) * ennreal (indicator {0..} u / exp u) \<partial>lborel \<partial>lborel)" by (intro nn_integral_cong) (auto simp: indicator_def ennreal_mult' [symmetric]) also have "\<dots> = (\<integral>\<^sup>+u. (\<integral>\<^sup>+t. ennreal (indicator {0..u} t * t powr (a - 1) * (u - t) powr (b - 1)) \<partial>lborel) * ennreal (indicator {0..} u / exp u) \<partial>lborel)" by (subst nn_integral_multc [symmetric]) auto also have "\<dots> = (\<integral>\<^sup>+u. (\<integral>\<^sup>+t. ennreal (indicator {0..u} t * t powr (a - 1) * (u - t) powr (b - 1)) \<partial>lborel) * ennreal (indicator {0<..} u / exp u) \<partial>lborel)" by (intro nn_integral_cong_AE eventually_mono[OF AE_lborel_singleton[of 0]]) (auto simp: indicator_def) also have "\<dots> = (\<integral>\<^sup>+u. ennreal B * ennreal (indicator {0..} u / exp u * u powr (a + b - 1)) \<partial>lborel)" proof (intro nn_integral_cong, goal_cases) case (1 u) show ?case proof (cases "u > 0") case True have "(\<integral>\<^sup>+t. ennreal (indicator {0..u} t * t powr (a - 1) * (u - t) powr (b - 1)) \<partial>lborel) = (\<integral>\<^sup>+t. ennreal (indicator {0..1} t * (u * t) powr (a - 1) * (u - u * t) powr (b - 1)) \<partial>distr lborel borel ((*) (1 / u)))" (is "_ = nn_integral _ ?f") using True by (subst nn_integral_distr) (auto simp: indicator_def field_simps intro!: nn_integral_cong) also have "distr lborel borel ((*) (1 / u)) = density lborel (\<lambda>_. u)" using \<open>u > 0\<close> by (subst lborel_distr_mult) auto also have "nn_integral \<dots> ?f = (\<integral>\<^sup>+x. ennreal (indicator {0..1} x * (u * (u * x) powr (a - 1) * (u * (1 - x)) powr (b - 1))) \<partial>lborel)" using \<open>u > 0\<close> by (subst nn_integral_density) (auto simp: ennreal_mult' [symmetric] algebra_simps) also have "\<dots> = (\<integral>\<^sup>+x. ennreal (u powr (a + b - 1)) * ennreal (indicator {0..1} x * x powr (a - 1) * (1 - x) powr (b - 1)) \<partial>lborel)" using \<open>u > 0\<close> a b by (intro nn_integral_cong) (auto simp: indicator_def powr_mult powr_add powr_diff mult_ac ennreal_mult' [symmetric]) also have "\<dots> = ennreal (u powr (a + b - 1)) * (\<integral>\<^sup>+x. ennreal (indicator {0..1} x * x powr (a - 1) * (1 - x) powr (b - 1)) \<partial>lborel)" by (subst nn_integral_cmult) auto also have "((\<lambda>x. x powr (a - 1) * (1 - x) powr (b - 1)) has_integral integral {0..1} (\<lambda>x. x powr (a - 1) * (1 - x) powr (b - 1))) {0..1}" using a b by (intro integrable_integral integrable_Beta') from nn_integral_has_integral_lebesgue[OF _ this] a b have "(\<integral>\<^sup>+x. ennreal (indicator {0..1} x * x powr (a - 1) * (1 - x) powr (b - 1)) \<partial>lborel) = B" by (simp add: mult_ac B_def) finally show ?thesis using \<open>u > 0\<close> by (simp add: ennreal_mult' [symmetric] mult_ac) qed auto qed also have "\<dots> = ennreal B * ennreal (Gamma (a + b))" using a b by (subst nn_integral_cmult) (auto simp: Gamma_conv_nn_integral_real) also have "\<dots> = ennreal (B * Gamma (a + b))" by (subst (1 2) mult.commute, intro ennreal_mult' [symmetric]) (use a b in auto) finally have "B = Beta a b" using a b Gamma_real_pos[of "a + b"] by (subst (asm) ennreal_inj) (auto simp: field_simps Beta_def Gamma_eq_zero_iff) moreover have "(\<lambda>t. t powr (a - 1) * (1 - t) powr (b - 1)) integrable_on {0..1}" by (intro integrable_Beta' a b) ultimately show ?thesis by (simp add: has_integral_iff B_def) qed subsection \<open>The Weierstra{\ss} product formula for the sine\<close> theorem sin_product_formula_complex: fixes z :: complex shows "(\<lambda>n. of_real pi * z * (\<Prod>k=1..n. 1 - z^2 / of_nat k^2)) \<longlonglongrightarrow> sin (of_real pi * z)" proof - let ?f = "rGamma_series_Weierstrass" have "(\<lambda>n. (- of_real pi * inverse z) * (?f z n * ?f (- z) n)) \<longlonglongrightarrow> (- of_real pi * inverse z) * (rGamma z * rGamma (- z))" by (intro tendsto_intros rGamma_Weierstrass_complex) also have "(\<lambda>n. (- of_real pi * inverse z) * (?f z n * ?f (-z) n)) = (\<lambda>n. of_real pi * z * (\<Prod>k=1..n. 1 - z^2 / of_nat k ^ 2))" proof fix n :: nat have "(- of_real pi * inverse z) * (?f z n * ?f (-z) n) = of_real pi * z * (\<Prod>k=1..n. (of_nat k - z) * (of_nat k + z) / of_nat k ^ 2)" by (simp add: rGamma_series_Weierstrass_def mult_ac exp_minus divide_simps prod.distrib[symmetric] power2_eq_square) also have "(\<Prod>k=1..n. (of_nat k - z) * (of_nat k + z) / of_nat k ^ 2) = (\<Prod>k=1..n. 1 - z^2 / of_nat k ^ 2)" by (intro prod.cong) (simp_all add: power2_eq_square field_simps) finally show "(- of_real pi * inverse z) * (?f z n * ?f (-z) n) = of_real pi * z * \<dots>" by (simp add: field_split_simps) qed also have "(- of_real pi * inverse z) * (rGamma z * rGamma (- z)) = sin (of_real pi * z)" by (subst rGamma_reflection_complex') (simp add: field_split_simps) finally show ?thesis . qed lemma sin_product_formula_real: "(\<lambda>n. pi * (x::real) * (\<Prod>k=1..n. 1 - x^2 / of_nat k^2)) \<longlonglongrightarrow> sin (pi * x)" proof - from sin_product_formula_complex[of "of_real x"] have "(\<lambda>n. of_real pi * of_real x * (\<Prod>k=1..n. 1 - (of_real x)^2 / (of_nat k)^2)) \<longlonglongrightarrow> sin (of_real pi * of_real x :: complex)" (is "?f \<longlonglongrightarrow> ?y") . also have "?f = (\<lambda>n. of_real (pi * x * (\<Prod>k=1..n. 1 - x^2 / (of_nat k^2))))" by simp also have "?y = of_real (sin (pi * x))" by (simp only: sin_of_real [symmetric] of_real_mult) finally show ?thesis by (subst (asm) tendsto_of_real_iff) qed lemma sin_product_formula_real': assumes "x \<noteq> (0::real)" shows "(\<lambda>n. (\<Prod>k=1..n. 1 - x^2 / of_nat k^2)) \<longlonglongrightarrow> sin (pi * x) / (pi * x)" using tendsto_divide[OF sin_product_formula_real[of x] tendsto_const[of "pi * x"]] assms by simp theorem wallis: "(\<lambda>n. \<Prod>k=1..n. (4*real k^2) / (4*real k^2 - 1)) \<longlonglongrightarrow> pi / 2" proof - from tendsto_inverse[OF tendsto_mult[OF sin_product_formula_real[of "1/2"] tendsto_const[of "2/pi"]]] have "(\<lambda>n. (\<Prod>k=1..n. inverse (1 - (1/2)\<^sup>2 / (real k)\<^sup>2))) \<longlonglongrightarrow> pi/2" by (simp add: prod_inversef [symmetric]) also have "(\<lambda>n. (\<Prod>k=1..n. inverse (1 - (1/2)\<^sup>2 / (real k)\<^sup>2))) = (\<lambda>n. (\<Prod>k=1..n. (4*real k^2)/(4*real k^2 - 1)))" by (intro ext prod.cong refl) (simp add: field_split_simps) finally show ?thesis . qed subsection \<open>The Solution to the Basel problem\<close> theorem inverse_squares_sums: "(\<lambda>n. 1 / (n + 1)\<^sup>2) sums (pi\<^sup>2 / 6)" proof - define P where "P x n = (\<Prod>k=1..n. 1 - x^2 / of_nat k^2)" for x :: real and n define K where "K = (\<Sum>n. inverse (real_of_nat (Suc n))^2)" define f where [abs_def]: "f x = (\<Sum>n. P x n / of_nat (Suc n)^2)" for x define g where [abs_def]: "g x = (1 - sin (pi * x) / (pi * x))" for x have sums: "(\<lambda>n. P x n / of_nat (Suc n)^2) sums (if x = 0 then K else g x / x^2)" for x proof (cases "x = 0") assume x: "x = 0" have "summable (\<lambda>n. inverse ((real_of_nat (Suc n))\<^sup>2))" using inverse_power_summable[of 2] by (subst summable_Suc_iff) simp thus ?thesis by (simp add: x g_def P_def K_def inverse_eq_divide power_divide summable_sums) next assume x: "x \<noteq> 0" have "(\<lambda>n. P x n - P x (Suc n)) sums (P x 0 - sin (pi * x) / (pi * x))" unfolding P_def using x by (intro telescope_sums' sin_product_formula_real') also have "(\<lambda>n. P x n - P x (Suc n)) = (\<lambda>n. (x^2 / of_nat (Suc n)^2) * P x n)" unfolding P_def by (simp add: prod.nat_ivl_Suc' algebra_simps) also have "P x 0 = 1" by (simp add: P_def) finally have "(\<lambda>n. x\<^sup>2 / (of_nat (Suc n))\<^sup>2 * P x n) sums (1 - sin (pi * x) / (pi * x))" . from sums_divide[OF this, of "x^2"] x show ?thesis unfolding g_def by simp qed have "continuous_on (ball 0 1) f" proof (rule uniform_limit_theorem; (intro always_eventually allI)?) show "uniform_limit (ball 0 1) (\<lambda>n x. \<Sum>k<n. P x k / of_nat (Suc k)^2) f sequentially" proof (unfold f_def, rule Weierstrass_m_test) fix n :: nat and x :: real assume x: "x \<in> ball 0 1" { fix k :: nat assume k: "k \<ge> 1" from x have "x^2 < 1" by (auto simp: abs_square_less_1) also from k have "\<dots> \<le> of_nat k^2" by simp finally have "(1 - x^2 / of_nat k^2) \<in> {0..1}" using k by (simp_all add: field_simps del: of_nat_Suc) } hence "(\<Prod>k=1..n. abs (1 - x^2 / of_nat k^2)) \<le> (\<Prod>k=1..n. 1)" by (intro prod_mono) simp thus "norm (P x n / (of_nat (Suc n)^2)) \<le> 1 / of_nat (Suc n)^2" unfolding P_def by (simp add: field_simps abs_prod del: of_nat_Suc) qed (subst summable_Suc_iff, insert inverse_power_summable[of 2], simp add: inverse_eq_divide) qed (auto simp: P_def intro!: continuous_intros) hence "isCont f 0" by (subst (asm) continuous_on_eq_continuous_at) simp_all hence "(f \<midarrow> 0 \<rightarrow> f 0)" by (simp add: isCont_def) also have "f 0 = K" unfolding f_def P_def K_def by (simp add: inverse_eq_divide power_divide) finally have "f \<midarrow> 0 \<rightarrow> K" . moreover have "f \<midarrow> 0 \<rightarrow> pi^2 / 6" proof (rule Lim_transform_eventually) define f' where [abs_def]: "f' x = (\<Sum>n. - sin_coeff (n+3) * pi ^ (n+2) * x^n)" for x have "eventually (\<lambda>x. x \<noteq> (0::real)) (at 0)" by (auto simp add: eventually_at intro!: exI[of _ 1]) thus "eventually (\<lambda>x. f' x = f x) (at 0)" proof eventually_elim fix x :: real assume x: "x \<noteq> 0" have "sin_coeff 1 = (1 :: real)" "sin_coeff 2 = (0::real)" by (simp_all add: sin_coeff_def) with sums_split_initial_segment[OF sums_minus[OF sin_converges], of 3 "pi*x"] have "(\<lambda>n. - (sin_coeff (n+3) * (pi*x)^(n+3))) sums (pi * x - sin (pi*x))" by (simp add: eval_nat_numeral) from sums_divide[OF this, of "x^3 * pi"] x have "(\<lambda>n. - (sin_coeff (n+3) * pi^(n+2) * x^n)) sums ((1 - sin (pi*x) / (pi*x)) / x^2)" by (simp add: field_split_simps eval_nat_numeral) with x have "(\<lambda>n. - (sin_coeff (n+3) * pi^(n+2) * x^n)) sums (g x / x^2)" by (simp add: g_def) hence "f' x = g x / x^2" by (simp add: sums_iff f'_def) also have "\<dots> = f x" using sums[of x] x by (simp add: sums_iff g_def f_def) finally show "f' x = f x" . qed have "isCont f' 0" unfolding f'_def proof (intro isCont_powser_converges_everywhere) fix x :: real show "summable (\<lambda>n. -sin_coeff (n+3) * pi^(n+2) * x^n)" proof (cases "x = 0") assume x: "x \<noteq> 0" from summable_divide[OF sums_summable[OF sums_split_initial_segment[OF sin_converges[of "pi*x"]], of 3], of "-pi*x^3"] x show ?thesis by (simp add: field_split_simps eval_nat_numeral) qed (simp only: summable_0_powser) qed hence "f' \<midarrow> 0 \<rightarrow> f' 0" by (simp add: isCont_def) also have "f' 0 = pi * pi / fact 3" unfolding f'_def by (subst powser_zero) (simp add: sin_coeff_def) finally show "f' \<midarrow> 0 \<rightarrow> pi^2 / 6" by (simp add: eval_nat_numeral) qed ultimately have "K = pi^2 / 6" by (rule LIM_unique) moreover from inverse_power_summable[of 2] have "summable (\<lambda>n. (inverse (real_of_nat (Suc n)))\<^sup>2)" by (subst summable_Suc_iff) (simp add: power_inverse) ultimately show ?thesis unfolding K_def by (auto simp add: sums_iff power_divide inverse_eq_divide) qed end
//======================================================================= // Copyright Baptiste Wicht 2011-2016. // Distributed under the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef AST_WHILE_H #define AST_WHILE_H #include <vector> #include <memory> #include <boost/fusion/include/adapt_struct.hpp> #include "ast/Value.hpp" namespace eddic { class Context; namespace ast { /*! * \class While * \brief The AST node for a while loop. */ struct While { std::shared_ptr<Context> context; Value condition; std::vector<Instruction> instructions; }; } //end of ast } //end of eddic //Adapt the struct for the AST BOOST_FUSION_ADAPT_STRUCT( eddic::ast::While, (eddic::ast::Value, condition) (std::vector<eddic::ast::Instruction>, instructions) ) #endif
(* ========================================================================== *] PROVING THINGS WE KNOW [* ========================================================================== *) Require Import Nat List Lia. (* -------------------------------------------------------------------------- *] Let's prove things we consider true in our everyday programming life. We start by defining some common functions for lists. [* -------------------------------------------------------------------------- *) (* Calculate length of list. *) Fixpoint length {A} (lst : list A) := match lst with | nil => 0 | x :: xs => 1 + length xs end. (* Concatenate two lists. *) Fixpoint concat {A} (lst1 lst2 : list A) := match lst1 with | nil => lst2 | x :: xs => x :: (concat xs lst2) end. (* Reverse a list. *) Fixpoint reverse {A} (lst : list A) := match lst with | nil => nil | x :: xs => concat (reverse xs) (x :: nil) end. (* Apply function on all elements of list. *) Fixpoint map {A B} (f : A -> B) (lst : list A) := match lst with | nil => nil | x :: xs => f x :: map f xs end. (* Compose two functions into a single one. *) Definition compose {A B C} (f : B -> C) (g : A -> B) := fun x => f (g x). (* -------------------------------------------------------------------------- *] Most often we need properties that describe how different functions interact. [* -------------------------------------------------------------------------- *) Lemma length_concat {A} (lst1 lst2 : list A): length (concat lst1 lst2) = length lst1 + length lst2. Proof. induction lst1. - simpl. auto. - simpl. rewrite IHlst1. auto. Qed. Lemma length_map {A B} (lst : list A) (f : A -> B): length (map f lst) = length lst. Proof. induction lst. - simpl. auto. - simpl. rewrite IHlst. auto. Qed. Lemma map_compose {A B C} (lst : list A) (f : B -> C) (g : A -> B): map f (map g lst) = map (compose f g) lst. Proof. induction lst. - simpl. auto. - simpl. rewrite IHlst. unfold compose. auto. Qed. (* -------------------------------------------------------------------------- *] Sometimes we need to prove some auxiliary lemmas. [* -------------------------------------------------------------------------- *) (* These two seem obvious but must be shown. *) Lemma concat_nil {A} (lst1 : list A): concat lst1 nil = lst1. Proof. induction lst1. - simpl. auto. - simpl. rewrite IHlst1. auto. Qed. Lemma concat_assoc {A} (lst1 lst2 lst3 : list A): concat (concat lst1 lst2) lst3 = concat lst1 (concat lst2 lst3). Proof. induction lst1. - simpl. auto. - simpl. rewrite IHlst1. auto. Qed. (* This is what we actually want. *) Lemma reverse_concat {A} (lst1 lst2 : list A): reverse (concat lst1 lst2) = concat (reverse lst2) (reverse lst1). Proof. induction lst1. simpl. - rewrite concat_nil. auto. - simpl. rewrite IHlst1. rewrite concat_assoc. auto. Qed. (* -------------------------------------------------------------------------- *] Induction needs to be performed at a general enough level in order to complete the following proof. If we try to first introduce all hypotheses, we get an induction hypothesis that is too weak. [* -------------------------------------------------------------------------- *) Fixpoint get_el {A} n (lst : list A) := match lst, n with | nil, _ => None | x :: xs, 0 => Some x | x :: xs, S m => get_el m xs end. Lemma get_fails {A} n (lst : list A) : length lst < n -> get_el n lst = None. Proof. revert n. induction lst. - intros. destruct n. + simpl. auto. + simpl. auto. - intros. destruct n. + simpl. simpl in H. lia. + simpl. apply IHlst. simpl in H. lia. Qed. (* -------------------------------------------------------------------------- *] By defining an inductive data type, Coq already know precisely what the appropriate induction principle is. [* -------------------------------------------------------------------------- *) Inductive tree {A} := | Empty : tree | Node : tree -> A -> tree -> tree . Fixpoint mirror {A} (t : @tree A) := match t with | Empty => Empty | Node l_t x r_t => Node (mirror r_t) x (mirror l_t) end. Fixpoint height {A} (t : @tree A) := match t with | Empty => 0 | Node l_t x r_t => 1 + max (height l_t) (height r_t) end. Lemma height_mirror {A} (t : @tree A) : height (mirror t) = height t. Proof. induction t. - simpl. auto. - simpl. rewrite IHt1, IHt2. lia. Qed. Lemma mirror_mirror {A} (t : @tree A) : mirror (mirror t) = t. Proof. induction t. - simpl. auto. - simpl. rewrite IHt1, IHt2. auto. Qed.
```python import sympy as sy from sympy import pi, cos, sin, tan from IPython.display import display from sympy.printing.pycode import pycode a,b,c,d,e = sy.symbols("a,b,c,d,e") #x = sy.Symbol("x") def f(x): return a*x**4 + b*x**3 + c*x**2 + d*x + e def df(x): return 4*a*x**3 + 3*b*x**2 + 2*c*x + d p1, p2, p3 = sy.symbols("p1, p2, p3") x1, x2, x3 = sy.symbols("x1, x2, x3") sol = sy.solve( [ df(x1), df(x2), f(x1) - p1, f(x2) - p2, f(x3), - p3, ], [a, b, c, d, e] ) ``` ```python import sympy as sy from sympy import pi, cos, sin, tan from IPython.display import display from sympy.printing.pycode import pycode a,b,c,d,e,f = sy.symbols("a,b,c,d,e,f") #x = sy.Symbol("x") def p(x): return a*x**5 + b*x**4 + c*x**3 + d*x**2 + e*x + f def dp(x): return 5*a*x**4 + 4*b*x**3 + 3*c*x**2 + d*x + e def ddp(x): return 20*a*x**3 + 12*b*x**2 + 6*c*x + d p2 = sy.symbols("p2") x1, x2, x3 = sy.symbols("x1, x2, x3") sol = sy.solve( [ ddp(x1), ddp(x2), ddp(x3), dp(0), p(0), p(x2) - p2, ], [a, b, c, d, e, f] ) sol ``` {a: 3*p2/(5*x1*x2**4 - 50*x1*x2**3*x3 - 2*x2**5 + 5*x2**4*x3), b: (-5*p2*x1 - 5*p2*x2 - 5*p2*x3)/(5*x1*x2**4 - 50*x1*x2**3*x3 - 2*x2**5 + 5*x2**4*x3), c: (10*p2*x1*x2 + 10*p2*x1*x3 + 10*p2*x2*x3)/(5*x1*x2**4 - 50*x1*x2**3*x3 - 2*x2**5 + 5*x2**4*x3), d: -60*p2*x1*x3/(5*x1*x2**3 - 50*x1*x2**2*x3 - 2*x2**4 + 5*x2**3*x3), e: 0, f: 0} ```python # グラフ化 ```
(* Copyright 2014 Cornell University Copyright 2015 Cornell University Copyright 2016 Cornell University Copyright 2017 Cornell University This file is part of VPrl (the Verified Nuprl project). VPrl 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. VPrl 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 VPrl. If not, see <http://www.gnu.org/licenses/>. Websites: http://nuprl.org/html/verification/ http://nuprl.org/html/Nuprl2Coq https://github.com/vrahli/NuprlInCoq Authors: Vincent Rahli *) Require Export psquash. Definition mk_usquash_per {o} v1 v2 (t : @NTerm o) := mk_lam v1 (mk_lam v2 t). Definition mk_usquash {o} (t : @NTerm o) := match newvars2 [t] with | (v1,v2) => mk_pertype (mk_usquash_per v1 v2 t) end. Definition mkc_usquash_per {o} v1 v2 (t : @CTerm o) := mkc_lam v1 (mkcv_lam _ v2 (mk_cv _ t)). Lemma wf_mk_usquash {o} : forall (t : @NTerm o), wf_term (mk_usquash t) <=> wf_term t. Proof. introv. unfold mk_usquash. remember (newvars2 [t]) as v; destruct v. rw <- @wf_pertype_iff. unfold mk_usquash_per. allrw <- @wf_lam_iff; tcsp. Qed. Lemma cover_vars_usquash {o} : forall (t : @NTerm o) s, cover_vars (mk_usquash t) s <=> cover_vars t s. Proof. introv. unfold mk_usquash. remember (newvars2 [t]) as v; destruct v. rw @cover_vars_pertype. unfold mk_usquash_per. rw @cover_vars_lam. rw @cover_vars_upto_lam. allrw <- @csub_filter_app_r; simpl. apply newvars2_prop2 in Heqv; allsimpl; allrw app_nil_r; allrw in_app_iff; allrw not_over_or; repnd. pose proof (cover_vars_upto_csub_filter_disjoint t s [n, n0] [n, n0]) as h1. allrw disjoint_cons_r. repeat (autodimp h1 hyp); allsimpl; tcsp. pose proof (cover_vars_upto_eqvars t (csub_filter s [n, n0]) [n,n0] [n0,n]) as e1. autodimp e1 hyp. { rw eqvars_prop; simpl; introv; split; sp. } rw <- e1; rw h1; clear h1 e1. split; intro k; repnd; dands; tcsp. Qed. Lemma lsubstc_mk_usquash_ex {o} : forall (t : @NTerm o) w s c, {w' : wf_term t & {c' : cover_vars t s & alphaeqc (lsubstc (mk_usquash t) w s c) (mkc_pertype (mkc_usquash_per nvarx nvary (lsubstc t w' s c')))}}. Proof. introv. dup w as w'. rw @wf_mk_usquash in w'. exists w'. dup c as c'. rw @cover_vars_usquash in c'. exists c'. unfold alphaeqc; simpl. unfold csubst. rw @cl_lsubst_lsubst_aux; eauto 3 with slow;simpl. autorewrite with slow list in *. pose proof (newvarlst_prop [t]) as nvp1. remember (newvarlst [t]) as v1; clear Heqv1. pose proof (newvarlst_prop [t,mk_var v1]) as nvp2. remember (newvarlst [t, mk_var v1]) as v2; clear Heqv2. allsimpl; autorewrite with list in *. repeat (allrw in_app_iff; allsimpl). allrw not_over_or; repnd; GC. allrw <- @sub_filter_app_r; allsimpl. repeat prove_alpha_eq4. pose proof (ex_fresh_var (v1 :: v2 :: nvarx :: nvary :: (allvars_op (oterm (Can NLambda) [bterm [v2] (lsubst_aux t (sub_filter (csub2sub s) [v1, v2]))])) ++ (allvars_op (oterm (Can NLambda) [bterm [nvary] (lsubst t (csub2sub s))])))) as fv. exrepnd; allsimpl. rw in_app_iff in fv0. allrw not_over_or; repnd. apply (al_bterm_aux [v]); simpl; auto. { unfold all_vars; allrw @all_vars_eq_op. apply disjoint_singleton_l. rw in_app_iff; sp. } autorewrite with slow; boolvar; tcsp; GC. repeat (prove_alpha_eq4). fold_terms. pose proof (ex_fresh_var (v :: v1 :: v2 :: nvarx :: nvary :: (allvars_op (lsubst_aux (lsubst_aux t (sub_filter (csub2sub s) [v1, v2])) [(v1, mk_var v)])) ++ (allvars_op (lsubst_aux (lsubst t (csub2sub s)) [(nvarx, mk_var v)])))) as fv'. exrepnd; allsimpl. rw in_app_iff in fv'0. allrw not_over_or; repnd. apply (al_bterm_aux [v0]); allsimpl; fold_terms; auto. { unfold all_vars; allrw @all_vars_eq_op. apply disjoint_singleton_l. rw in_app_iff; sp. } applydup @cover_vars_iff_closed_lsubst_aux in c'. rw @cl_lsubst_lsubst_aux; eauto 3 with slow;[]. rw @lsubst_aux_sub_filter;[|repeat (rw disjoint_cons_r); dands; complete auto]. repeat (rw (lsubst_aux_trivial_cl_term2 (lsubst_aux t (csub2sub s))); auto;[]). rw (lsubst_aux_trivial_cl_term2 (lsubst_aux t (csub2sub s))); auto. Qed. Definition mkc_usquash {o} (t : @CTerm o) := mkc_pertype (mkc_usquash_per nvarx nvary t). Lemma lsubstc_mk_usquash_ex2 {o} : forall (t : @NTerm o) w s c, {w' : wf_term t & {c' : cover_vars t s & alphaeqc (lsubstc (mk_usquash t) w s c) (mkc_usquash (lsubstc t w' s c')) }}. Proof. introv. apply lsubstc_mk_usquash_ex. Qed.
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kenny Lau, Scott Morrison ! This file was ported from Lean 3 source module data.list.fin_range ! leanprover-community/mathlib commit 9003f28797c0664a49e4179487267c494477d853 ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathlib.Data.List.OfFn import Mathlib.Data.List.Perm /-! # Lists of elements of `Fin n` This file develops some results on `finRange n`. -/ universe u namespace List variable {α : Type u} @[simp] theorem map_coe_finRange (n : ℕ) : ((finRange n) : List (Fin n)).map (Fin.val) = List.range n := by simp_rw [finRange, map_pmap, Fin.val_mk, pmap_eq_map] exact List.map_id _ #align list.map_coe_fin_range List.map_coe_finRange theorem finRange_succ_eq_map (n : ℕ) : finRange n.succ = 0 :: (finRange n).map Fin.succ := by apply map_injective_iff.mpr Fin.val_injective rw [map_cons, map_coe_finRange, range_succ_eq_map, Fin.val_zero, ← map_coe_finRange, map_map, map_map] simp only [Function.comp, Fin.val_succ] #align list.fin_range_succ_eq_map List.finRange_succ_eq_map -- Porting note : `map_nth_le` moved to `List.finRange_map_get` in Data.List.Range theorem ofFn_eq_pmap {α n} {f : Fin n → α} : ofFn f = pmap (fun i hi => f ⟨i, hi⟩) (range n) fun _ => mem_range.1 := by (rw [pmap_eq_map_attach]; exact ext_get (by simp) fun i hi1 hi2 => by simp [get_ofFn f ⟨i, hi1⟩]) #align list.of_fn_eq_pmap List.ofFn_eq_pmap theorem ofFn_id (n) : ofFn id = finRange n := ofFn_eq_pmap #align list.of_fn_id List.ofFn_id theorem ofFn_eq_map {α n} {f : Fin n → α} : ofFn f = (finRange n).map f := by rw [← ofFn_id, map_ofFn, Function.right_id] #align list.of_fn_eq_map List.ofFn_eq_map theorem nodup_ofFn_ofInjective {α n} {f : Fin n → α} (hf : Function.Injective f) : Nodup (ofFn f) := by rw [ofFn_eq_pmap] exact (nodup_range n).pmap fun _ _ _ _ H => Fin.veq_of_eq <| hf H #align list.nodup_of_fn_of_injective List.nodup_ofFn_ofInjective theorem nodup_ofFn {α n} {f : Fin n → α} : Nodup (ofFn f) ↔ Function.Injective f := by refine' ⟨_, nodup_ofFn_ofInjective⟩ refine' Fin.consInduction _ (fun x₀ xs ih => _) f · intro _ exact Function.injective_of_subsingleton _ · intro h rw [Fin.cons_injective_iff] simp_rw [ofFn_succ, Fin.cons_succ, nodup_cons, Fin.cons_zero, mem_ofFn] at h exact h.imp_right ih #align list.nodup_of_fn List.nodup_ofFn end List open List theorem Equiv.Perm.map_finRange_perm {n : ℕ} (σ : Equiv.Perm (Fin n)) : map σ (finRange n) ~ finRange n := by rw [perm_ext ((nodup_finRange n).map σ.injective) <| nodup_finRange n] simpa [mem_map, mem_finRange, true_and_iff, iff_true_iff] using σ.surjective #align equiv.perm.map_fin_range_perm Equiv.Perm.map_finRange_perm /-- The list obtained from a permutation of a tuple `f` is permutation equivalent to the list obtained from `f`. -/ theorem Equiv.Perm.ofFn_comp_perm {n : ℕ} {α : Type u} (σ : Equiv.Perm (Fin n)) (f : Fin n → α) : ofFn (f ∘ σ) ~ ofFn f := by rw [ofFn_eq_map, ofFn_eq_map, ← map_map] exact σ.map_finRange_perm.map f #align equiv.perm.of_fn_comp_perm Equiv.Perm.ofFn_comp_perm
" Crazy in Love " was lauded by contemporary music critics , who complimented the horn lines and the guest appearance of Jay @-@ Z. Many of them called it the Summer Anthem of 2003 . Tim Sendra of AllMusic described the song as a " stunning pop masterpiece " , while Stephen Thomas Erlewine of the same website called it " deliriously catchy " . Darryl Sterdan of Jam ! noted the " Crazy in Love " is " instantly addictive horn lines " . Anthony DeCurtis of Rolling Stone wrote : " ' Crazy in Love ' ... roars out of the speakers on the strength of a propulsive horn sample and the charged presence of her pal , Jay @-@ Z. " Ben Ratliff of Blender magazine called the song an " itchy [ and ] eager @-@ to @-@ please " one . Marc Anthony Neal of PopMatters called the " uh @-@ oh , uh @-@ oh " phrase catchy . MTV News considered " Crazy in Love " to be the " proudest moment " of Dangerously in Love . Similarly , Allison Stewart of The Washington Post called it the best song on the album , praising its instrumentation , harmonies , and the rap verse of Jay Z. This was echoed by Kelefa Sanneh of The New York Times who wrote that " Crazy in Love " is the best one on the album thanks to its " simplicity , irresistible combination of triumphant horns and a wicked hip @-@ hop beat " . She added that " [ Beyoncé ’ s ] vocals - as deft and accurate as ever - convey none of the giddy rush that the lyrics describe . " Likewise , Sal Cinquemani of Slant Magazine wrote the lyrical arrangement , the music structure and the guest vocals by Jay Z all contributed in making " Crazy in Love " a wonderful resume for Beyoncé .
/- Copyright (c) 2021 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import data.set.finite import data.finset import group_theory.submonoid.operations import group_theory.subgroup.basic /-! # Finitely generated monoids and groups We define finitely generated monoids and groups. See also `submodule.fg` and `module.finite` for finitely-generated modules. ## Main definition * `submonoid.fg S`, `add_submonoid.fg S` : A submonoid `S` is finitely generated. * `monoid.fg M`, `add_monoid.fg M` : A typeclass indicating a type `M` is finitely generated as a monoid. * `subgroup.fg S`, `add_subgroup.fg S` : A subgroup `S` is finitely generated. * `group.fg M`, `add_group.fg M` : A typeclass indicating a type `M` is finitely generated as a group. -/ /-! ### Monoids and submonoids -/ open_locale pointwise variables {M N : Type*} [monoid M] [add_monoid N] section submonoid /-- A submonoid of `M` is finitely generated if it is the closure of a finite subset of `M`. -/ @[to_additive] def submonoid.fg (P : submonoid M) : Prop := ∃ S : finset M, submonoid.closure ↑S = P /-- An additive submonoid of `N` is finitely generated if it is the closure of a finite subset of `M`. -/ add_decl_doc add_submonoid.fg /-- An equivalent expression of `submonoid.fg` in terms of `set.finite` instead of `finset`. -/ @[to_additive "An equivalent expression of `add_submonoid.fg` in terms of `set.finite` instead of `finset`."] lemma submonoid.fg_iff (P : submonoid M) : submonoid.fg P ↔ ∃ S : set M, submonoid.closure S = P ∧ S.finite := ⟨λ ⟨S, hS⟩, ⟨S, hS, finset.finite_to_set S⟩, λ ⟨S, hS, hf⟩, ⟨set.finite.to_finset hf, by simp [hS]⟩⟩ lemma submonoid.fg_iff_add_fg (P : submonoid M) : P.fg ↔ P.to_add_submonoid.fg := ⟨λ h, let ⟨S, hS, hf⟩ := (submonoid.fg_iff _).1 h in (add_submonoid.fg_iff _).mpr ⟨additive.to_mul ⁻¹' S, by simp [← submonoid.to_add_submonoid_closure, hS], hf⟩, λ h, let ⟨T, hT, hf⟩ := (add_submonoid.fg_iff _).1 h in (submonoid.fg_iff _).mpr ⟨multiplicative.of_add ⁻¹' T, by simp [← add_submonoid.to_submonoid'_closure, hT], hf⟩⟩ lemma add_submonoid.fg_iff_mul_fg (P : add_submonoid N) : P.fg ↔ P.to_submonoid.fg := begin convert (submonoid.fg_iff_add_fg P.to_submonoid).symm, exact set_like.ext' rfl end end submonoid section monoid variables (M N) /-- A monoid is finitely generated if it is finitely generated as a submonoid of itself. -/ class monoid.fg : Prop := (out : (⊤ : submonoid M).fg) /-- An additive monoid is finitely generated if it is finitely generated as an additive submonoid of itself. -/ class add_monoid.fg : Prop := (out : (⊤ : add_submonoid N).fg) attribute [to_additive] monoid.fg variables {M N} lemma monoid.fg_def : monoid.fg M ↔ (⊤ : submonoid M).fg := ⟨λ h, h.1, λ h, ⟨h⟩⟩ lemma add_monoid.fg_def : add_monoid.fg N ↔ (⊤ : add_submonoid N).fg := ⟨λ h, h.1, λ h, ⟨h⟩⟩ /-- An equivalent expression of `monoid.fg` in terms of `set.finite` instead of `finset`. -/ @[to_additive "An equivalent expression of `add_monoid.fg` in terms of `set.finite` instead of `finset`."] lemma monoid.fg_iff : monoid.fg M ↔ ∃ S : set M, submonoid.closure S = (⊤ : submonoid M) ∧ S.finite := ⟨λ h, (submonoid.fg_iff ⊤).1 h.out, λ h, ⟨(submonoid.fg_iff ⊤).2 h⟩⟩ lemma monoid.fg_iff_add_fg : monoid.fg M ↔ add_monoid.fg (additive M) := ⟨λ h, ⟨(submonoid.fg_iff_add_fg ⊤).1 h.out⟩, λ h, ⟨(submonoid.fg_iff_add_fg ⊤).2 h.out⟩⟩ lemma add_monoid.fg_iff_mul_fg : add_monoid.fg N ↔ monoid.fg (multiplicative N) := ⟨λ h, ⟨(add_submonoid.fg_iff_mul_fg ⊤).1 h.out⟩, λ h, ⟨(add_submonoid.fg_iff_mul_fg ⊤).2 h.out⟩⟩ instance add_monoid.fg_of_monoid_fg [monoid.fg M] : add_monoid.fg (additive M) := monoid.fg_iff_add_fg.1 ‹_› instance monoid.fg_of_add_monoid_fg [add_monoid.fg N] : monoid.fg (multiplicative N) := add_monoid.fg_iff_mul_fg.1 ‹_› end monoid @[to_additive] lemma submonoid.fg.map {M' : Type*} [monoid M'] {P : submonoid M} (h : P.fg) (e : M →* M') : (P.map e).fg := begin classical, obtain ⟨s, rfl⟩ := h, exact ⟨s.image e, by rw [finset.coe_image, monoid_hom.map_mclosure]⟩ end @[to_additive] lemma submonoid.fg.map_injective {M' : Type*} [monoid M'] {P : submonoid M} (e : M →* M') (he : function.injective e) (h : (P.map e).fg) : P.fg := begin obtain ⟨s, hs⟩ := h, use s.preimage e (he.inj_on _), apply submonoid.map_injective_of_injective he, rw [← hs, e.map_mclosure, finset.coe_preimage], congr, rw [set.image_preimage_eq_iff, ← e.coe_mrange, ← submonoid.closure_le, hs, e.mrange_eq_map], exact submonoid.monotone_map le_top end @[simp, to_additive] lemma monoid.fg_iff_submonoid_fg (N : submonoid M) : monoid.fg N ↔ N.fg := begin conv_rhs { rw [← N.range_subtype, monoid_hom.mrange_eq_map] }, exact ⟨λ h, h.out.map N.subtype, λ h, ⟨h.map_injective N.subtype subtype.coe_injective⟩⟩ end @[to_additive] lemma monoid.fg_of_surjective {M' : Type*} [monoid M'] [monoid.fg M] (f : M →* M') (hf : function.surjective f) : monoid.fg M' := begin classical, obtain ⟨s, hs⟩ := monoid.fg_def.mp ‹_›, use s.image f, rwa [finset.coe_image, ← monoid_hom.map_mclosure, hs, ← monoid_hom.mrange_eq_map, monoid_hom.mrange_top_iff_surjective], end @[to_additive] lemma submonoid.powers_fg (r : M) : (submonoid.powers r).fg := ⟨{r}, (finset.coe_singleton r).symm ▸ (submonoid.powers_eq_closure r).symm⟩ @[to_additive] instance (r : M) : monoid.fg (submonoid.powers r) := (monoid.fg_iff_submonoid_fg _).mpr (submonoid.powers_fg r) /-! ### Groups and subgroups -/ variables {G H : Type*} [group G] [add_group H] section subgroup /-- A subgroup of `G` is finitely generated if it is the closure of a finite subset of `G`. -/ @[to_additive] def subgroup.fg (P : subgroup G) : Prop := ∃ S : finset G, subgroup.closure ↑S = P /-- An additive subgroup of `H` is finitely generated if it is the closure of a finite subset of `H`. -/ add_decl_doc add_subgroup.fg /-- An equivalent expression of `subgroup.fg` in terms of `set.finite` instead of `finset`. -/ @[to_additive "An equivalent expression of `add_subgroup.fg` in terms of `set.finite` instead of `finset`."] lemma subgroup.fg_iff (P : subgroup G) : subgroup.fg P ↔ ∃ S : set G, subgroup.closure S = P ∧ S.finite := ⟨λ⟨S, hS⟩, ⟨S, hS, finset.finite_to_set S⟩, λ⟨S, hS, hf⟩, ⟨set.finite.to_finset hf, by simp [hS]⟩⟩ /-- A subgroup is finitely generated if and only if it is finitely generated as a submonoid. -/ @[to_additive add_subgroup.fg_iff_add_submonoid.fg "An additive subgroup is finitely generated if and only if it is finitely generated as an additive submonoid."] lemma subgroup.fg_iff_submonoid_fg (P : subgroup G) : P.fg ↔ P.to_submonoid.fg := begin split, { rintro ⟨S, rfl⟩, rw submonoid.fg_iff, refine ⟨S ∪ S⁻¹, _, S.finite_to_set.union S.finite_to_set.inv⟩, exact (subgroup.closure_to_submonoid _).symm }, { rintro ⟨S, hS⟩, refine ⟨S, le_antisymm _ _⟩, { rw [subgroup.closure_le, ←subgroup.coe_to_submonoid, ←hS], exact submonoid.subset_closure }, { rw [← subgroup.to_submonoid_le, ← hS, submonoid.closure_le], exact subgroup.subset_closure } } end lemma subgroup.fg_iff_add_fg (P : subgroup G) : P.fg ↔ P.to_add_subgroup.fg := begin rw [subgroup.fg_iff_submonoid_fg, add_subgroup.fg_iff_add_submonoid.fg], exact (subgroup.to_submonoid P).fg_iff_add_fg end lemma add_subgroup.fg_iff_mul_fg (P : add_subgroup H) : P.fg ↔ P.to_subgroup.fg := begin rw [add_subgroup.fg_iff_add_submonoid.fg, subgroup.fg_iff_submonoid_fg], exact add_submonoid.fg_iff_mul_fg (add_subgroup.to_add_submonoid P) end end subgroup section group variables (G H) /-- A group is finitely generated if it is finitely generated as a submonoid of itself. -/ class group.fg : Prop := (out : (⊤ : subgroup G).fg) /-- An additive group is finitely generated if it is finitely generated as an additive submonoid of itself. -/ class add_group.fg : Prop := (out : (⊤ : add_subgroup H).fg) attribute [to_additive] group.fg variables {G H} lemma group.fg_def : group.fg G ↔ (⊤ : subgroup G).fg := ⟨λ h, h.1, λ h, ⟨h⟩⟩ lemma add_group.fg_def : add_group.fg H ↔ (⊤ : add_subgroup H).fg := ⟨λ h, h.1, λ h, ⟨h⟩⟩ /-- An equivalent expression of `group.fg` in terms of `set.finite` instead of `finset`. -/ @[to_additive "An equivalent expression of `add_group.fg` in terms of `set.finite` instead of `finset`."] lemma group.fg_iff : group.fg G ↔ ∃ S : set G, subgroup.closure S = (⊤ : subgroup G) ∧ S.finite := ⟨λ h, (subgroup.fg_iff ⊤).1 h.out, λ h, ⟨(subgroup.fg_iff ⊤).2 h⟩⟩ /-- A group is finitely generated if and only if it is finitely generated as a monoid. -/ @[to_additive add_group.fg_iff_add_monoid.fg "An additive group is finitely generated if and only if it is finitely generated as an additive monoid."] lemma group.fg_iff_monoid.fg : group.fg G ↔ monoid.fg G := ⟨λ h, monoid.fg_def.2 $ (subgroup.fg_iff_submonoid_fg ⊤).1 (group.fg_def.1 h), λ h, group.fg_def.2 $ (subgroup.fg_iff_submonoid_fg ⊤).2 (monoid.fg_def.1 h)⟩ lemma group_fg.iff_add_fg : group.fg G ↔ add_group.fg (additive G) := ⟨λ h, ⟨(subgroup.fg_iff_add_fg ⊤).1 h.out⟩, λ h, ⟨(subgroup.fg_iff_add_fg ⊤).2 h.out⟩⟩ lemma add_group.fg_iff_mul_fg : add_group.fg H ↔ group.fg (multiplicative H) := ⟨λ h, ⟨(add_subgroup.fg_iff_mul_fg ⊤).1 h.out⟩, λ h, ⟨(add_subgroup.fg_iff_mul_fg ⊤).2 h.out⟩⟩ instance add_group.fg_of_group_fg [group.fg G] : add_group.fg (additive G) := group_fg.iff_add_fg.1 ‹_› instance group.fg_of_mul_group_fg [add_group.fg H] : group.fg (multiplicative H) := add_group.fg_iff_mul_fg.1 ‹_› end group
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #include <string> #include <gsl/gsl> #include "onnx/onnx_pb.h" #include "core/graph/basic_types.h" namespace onnxruntime::utils { // keep these signatures in sync with DECLARE_MAKE_ATTRIBUTE_FNS below /** Creates an AttributeProto with the specified name and value. */ ONNX_NAMESPACE::AttributeProto MakeAttribute(std::string attr_name, int64_t value); /** Creates an AttributeProto with the specified name and values. */ ONNX_NAMESPACE::AttributeProto MakeAttribute(std::string attr_name, gsl::span<const int64_t> values); #define DECLARE_MAKE_ATTRIBUTE_FNS(type) \ ONNX_NAMESPACE::AttributeProto MakeAttribute(std::string attr_name, type value); \ ONNX_NAMESPACE::AttributeProto MakeAttribute(std::string attr_name, gsl::span<const type> values) DECLARE_MAKE_ATTRIBUTE_FNS(float); DECLARE_MAKE_ATTRIBUTE_FNS(std::string); DECLARE_MAKE_ATTRIBUTE_FNS(ONNX_NAMESPACE::TensorProto); #if !defined(DISABLE_SPARSE_TENSORS) DECLARE_MAKE_ATTRIBUTE_FNS(ONNX_NAMESPACE::SparseTensorProto); #endif DECLARE_MAKE_ATTRIBUTE_FNS(ONNX_NAMESPACE::TypeProto); DECLARE_MAKE_ATTRIBUTE_FNS(ONNX_NAMESPACE::GraphProto); #undef DECLARE_MAKE_ATTRIBUTE_FNS // The below overload is made so the compiler does not attempt to resolve // string literals with the gsl::span overload inline ONNX_NAMESPACE::AttributeProto MakeAttribute(std::string attr_name, const char* value) { return MakeAttribute(std::move(attr_name), std::string{value}); } /** * Sets an attribute in `node_attributes` with key `attribute.name()` and value `attribute`. * If an attribute with the same name exists, it will be overwritten. * @return Pair of (iterator to attribute, whether attribute was added (true) or updated (false)). */ std::pair<NodeAttributes::iterator, bool> SetNodeAttribute(ONNX_NAMESPACE::AttributeProto attribute, NodeAttributes& node_attributes); } // namespace onnxruntime::utils
function dist_signed = line_exp_point_dist_signed_2d ( p1, p2, p ) %*****************************************************************************80 % %% LINE_EXP_POINT_DIST_SIGNED_2D: signed distance ( explicit line, point ) in 2D. % % Discussion: % % The explicit form of a line in 2D is: % % ( P1, P2 ) = ( (X1,Y1), (X2,Y2) ). % % The signed distance has two interesting properties: % % * The absolute value of the signed distance is the % usual (Euclidean) distance. % % * Points with signed distance 0 lie on the line, % points with a negative signed distance lie on one side % of the line, % points with a positive signed distance lie on the % other side of the line. % % Assuming that C is nonnegative, then if a point is a positive % distance away from the line, it is on the same side of the % line as the point (0,0), and if it is a negative distance % from the line, it is on the opposite side from (0,0). % % Licensing: % % This code is distributed under the GNU LGPL license. % % Modified: % % 04 December 2010 % % Author: % % John Burkardt % % Parameters: % % Input, real P1(2,1), P2(2,1), two points on the line. % % Input, real P(2,1), the point whose signed distance is desired. % % Output, real DIST_SIGNED, the signed distance from the % point to the line. % % % If the explicit line degenerates to a point, the computation is easy. % if ( p1(1:2,1) == p2(1:2,1) ) dist_signed = sqrt ( sum ( ( p1(1:2,1) - p(1:2,1) ).^2 ) ); % % Convert the explicit line to the implicit form A * X + B * Y + C = 0. % This makes the computation of the signed distance to (X,Y) easy. % else a = p2(2,1) - p1(2,1); b = p1(1,1) - p2(1,1); c = p2(1,1) * p1(2,1) - p1(1,1) * p2(2,1); dist_signed = ( a * p(1,1) + b * p(2,1) + c ) / sqrt ( a * a + b * b ); end return end
[STATEMENT] lemma listrel_iff_zip [code_unfold]: "(xs,ys) \<in> listrel r \<longleftrightarrow> length xs = length ys \<and> (\<forall>(x,y) \<in> set(zip xs ys). (x,y) \<in> r)" (is "?L \<longleftrightarrow> ?R") [PROOF STATE] proof (prove) goal (1 subgoal): 1. ((xs, ys) \<in> listrel r) = (length xs = length ys \<and> (\<forall>(x, y)\<in>set (zip xs ys). (x, y) \<in> r)) [PROOF STEP] proof [PROOF STATE] proof (state) goal (2 subgoals): 1. (xs, ys) \<in> listrel r \<Longrightarrow> length xs = length ys \<and> (\<forall>(x, y)\<in>set (zip xs ys). (x, y) \<in> r) 2. length xs = length ys \<and> (\<forall>(x, y)\<in>set (zip xs ys). (x, y) \<in> r) \<Longrightarrow> (xs, ys) \<in> listrel r [PROOF STEP] assume ?L [PROOF STATE] proof (state) this: (xs, ys) \<in> listrel r goal (2 subgoals): 1. (xs, ys) \<in> listrel r \<Longrightarrow> length xs = length ys \<and> (\<forall>(x, y)\<in>set (zip xs ys). (x, y) \<in> r) 2. length xs = length ys \<and> (\<forall>(x, y)\<in>set (zip xs ys). (x, y) \<in> r) \<Longrightarrow> (xs, ys) \<in> listrel r [PROOF STEP] thus ?R [PROOF STATE] proof (prove) using this: (xs, ys) \<in> listrel r goal (1 subgoal): 1. length xs = length ys \<and> (\<forall>(x, y)\<in>set (zip xs ys). (x, y) \<in> r) [PROOF STEP] by induct (auto intro: listrel_eq_len) [PROOF STATE] proof (state) this: length xs = length ys \<and> (\<forall>(x, y)\<in>set (zip xs ys). (x, y) \<in> r) goal (1 subgoal): 1. length xs = length ys \<and> (\<forall>(x, y)\<in>set (zip xs ys). (x, y) \<in> r) \<Longrightarrow> (xs, ys) \<in> listrel r [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. length xs = length ys \<and> (\<forall>(x, y)\<in>set (zip xs ys). (x, y) \<in> r) \<Longrightarrow> (xs, ys) \<in> listrel r [PROOF STEP] assume ?R [PROOF STATE] proof (state) this: length xs = length ys \<and> (\<forall>(x, y)\<in>set (zip xs ys). (x, y) \<in> r) goal (1 subgoal): 1. length xs = length ys \<and> (\<forall>(x, y)\<in>set (zip xs ys). (x, y) \<in> r) \<Longrightarrow> (xs, ys) \<in> listrel r [PROOF STEP] thus ?L [PROOF STATE] proof (prove) using this: length xs = length ys \<and> (\<forall>(x, y)\<in>set (zip xs ys). (x, y) \<in> r) goal (1 subgoal): 1. (xs, ys) \<in> listrel r [PROOF STEP] apply (clarify) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>length xs = length ys; \<forall>(x, y)\<in>set (zip xs ys). (x, y) \<in> r\<rbrakk> \<Longrightarrow> (xs, ys) \<in> listrel r [PROOF STEP] by (induct rule: list_induct2) (auto intro: listrel.intros) [PROOF STATE] proof (state) this: (xs, ys) \<in> listrel r goal: No subgoals! [PROOF STEP] qed
proj <- function(sunelev) { .Call('biometeoR_proj', PACKAGE = 'biometeoR', sunelev) }
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !! !! Copyright (c) 2022 Neil N. Carlson !! !! Permission is hereby granted, free of charge, to any person obtaining a !! copy of this software and associated documentation files (the "Software"), !! to deal in the Software without restriction, including without limitation !! the rights to use, copy, modify, merge, publish, distribute, sublicense, !! and/or sell copies of the Software, and to permit persons to whom the !! Software is furnished to do so, subject to the following conditions: !! !! The above copyright notice and this permission notice shall be included !! in all copies or substantial portions of the Software. !! !! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR !! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, !! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL !! THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER !! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING !! FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER !! DEALINGS IN THE SOFTWARE. !! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! module index_map_type use coarray_collectives implicit none private type box integer, pointer :: data(:) end type type, public :: index_map integer :: onp_size = 0 ! number of indices assigned to this process (on-process) integer :: offp_size = 0 ! number of off-process indices referenced from this process integer :: local_size = 0 ! number of local indices (on and off-process) integer :: global_size = 0 ! size of the global index set integer :: first ! first global index of the range assigned to this process integer :: last ! last global index of the range assigned to this process integer, allocatable :: offp_index(:) integer, allocatable :: src_image(:), src_index(:) type(box), allocatable :: src[:] ! persistent coarray temporary for gather_aux contains procedure :: init procedure :: gather procedure :: global_index end type contains subroutine init(this, bsize, offp_index) class(index_map), intent(inout) :: this ! intent(out) not allowed because of %SRC integer, intent(in) :: bsize, offp_index(:) integer :: nproc nproc = num_images() this%onp_size = bsize this%offp_size = 0 this%local_size = this%onp_size + this%offp_size call co_sum_scan(bsize, this%last) this%first = this%last - this%onp_size + 1 this%global_size = this%last call co_broadcast(this%global_size, nproc) call add_offp_index(this, offp_index) end subroutine init subroutine add_offp_index(this, offp_index) class(index_map), intent(inout) :: this integer, intent(in) :: offp_index(:) integer :: nproc, i, j integer, allocatable :: last(:)[:] !TODO: ensure offp_index is strictly increasing this%offp_index = offp_index this%offp_size = size(this%offp_index) this%local_size = this%onp_size + this%offp_size nproc = num_images() !! Gather the last global index owned by each image allocate(last(0:nproc)[*]) if (this_image() == 1) last(0) = 0 last(this_image())[1] = this%last sync all call co_broadcast(last, 1) !! Determine the image that owns each off-process index (SRC_IMAGE) !! and the corresponding local index in that image (SRC_INDEX). allocate(this%src_image(this%offp_size), this%src_index(this%offp_size)) i = 1 do j = 1, size(this%offp_index) do while (this%offp_index(j) > last(i)) i = i + 1 !ASSERT(i <= nproc) end do if (i == this_image()) stop 1 !TODO: replace by assertion this%src_image(j) = i this%src_index(j) = this%offp_index(j) - last(i-1) end do allocate(this%src[*]) end subroutine add_offp_index elemental function global_index(this, n) result(gid) class(index_map), intent(in) :: this integer, intent(in) :: n integer :: gid gid = -1 if (n < 1) return if (n <= this%onp_size) then gid = this%first + n - 1 else if (n <= this%local_size) then gid = this%offp_index(n-this%onp_size) end if end function subroutine gather(this, local_data) class(index_map), intent(inout) :: this integer, intent(inout) :: local_data(:) call gather_aux(this, local_data(:this%onp_size), local_data(this%onp_size+1:)) end subroutine subroutine gather_aux(this, onp_data, offp_data) class(index_map), intent(inout) :: this integer, intent(in), target :: onp_data(:) integer, intent(out) :: offp_data(:) integer :: j this%src%data => onp_data sync all do j = 1, this%offp_size offp_data(j) = this%src[this%src_image(j)]%data(this%src_index(j)) end do end subroutine gather_aux end module index_map_type
[STATEMENT] lemma llist_of_stream_transfer [transfer_rule]: "(pcr_stream (=) ===> (=)) id llist_of_stream" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (pcr_stream (=) ===> (=)) id llist_of_stream [PROOF STEP] by(simp add: rel_fun_def stream.pcr_cr_eq cr_stream_def)
foo : (pf : Nat -> Either (S Z = Z) (Z = S Z)) -> Z = S Z foo pf = let baz : Z = S Z baz with (pf 0) baz | (Left Refl) impossible baz | (Right pf') = pf' in baz
(* This program is free software; you can redistribute it and/or *) (* modify it under the terms of the GNU Lesser General Public License *) (* as published by the Free Software Foundation; either version 2.1 *) (* of the License, or (at your option) any later version. *) (* *) (* This program is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU General Public License for more details. *) (* *) (* You should have received a copy of the GNU Lesser General Public *) (* License along with this program; if not, write to the Free *) (* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *) (* 02110-1301 USA *) (* Different definitions of pathes in a graph, directed or not. *) (* The following notions are defined : *) (* - Walk : defined by 2 ends, *) (* a list of vertices and a list of edges *) (* constructors : W_null, W_step; *) (* - Trail : walk without repetition of edge, *) (* constructors : T_null, T_step; *) (* - Path : trail without repetition of inner vertex, *) (* constructors : P_null, P_step; *) (* - Closed_walk, Closed_trail, Cycle. *) Require Export Graphs. Require Export Degrees. Section PATH. Variable A:Type. Variable v : @V_set A. Variable a : @A_set A. Inductive Walk : @Vertex A -> @Vertex A -> @V_list A -> @E_list A -> Type := | W_null : forall x : Vertex, v x -> Walk x x V_nil E_nil | W_step : forall (x y z : Vertex) (vl : V_list) (el : E_list), Walk y z vl el -> v x -> a (A_ends x y) -> Walk x z (y :: vl) (E_ends x y :: el). Definition Closed_walk (x y : Vertex) (vl : V_list) (el : E_list) (w : Walk x y vl el) := x = y. Inductive Trail : @Vertex A -> @Vertex A -> @V_list A -> @E_list A -> Type := | T_null : forall x : Vertex, v x -> Trail x x V_nil E_nil | T_step : forall (x y z : Vertex) (vl : V_list) (el : E_list), Trail y z vl el -> v x -> a (A_ends x y) -> (forall u : Edge, In u el -> ~ E_eq u (E_ends x y)) -> Trail x z (y :: vl) (E_ends x y :: el). Definition Closed_trail (x y : Vertex) (vl : V_list) (el : E_list) (t : Trail x y vl el) := x = y. Inductive Path : @Vertex A -> @Vertex A -> @V_list A -> @E_list A -> Type := | P_null : forall x : Vertex, v x -> Path x x V_nil E_nil | P_step : forall (x y z : Vertex) (vl : V_list) (el : E_list), Path y z vl el -> v x -> a (A_ends x y) -> x <> y -> ~ In y vl -> (In x vl -> x = z) -> (forall u : Edge, In u el -> ~ E_eq u (E_ends x y)) -> Path x z (y :: vl) (E_ends x y :: el). Definition Cycle (x y : Vertex) (vl : V_list) (el : E_list) (p : Path x y vl el) := x = y. Lemma P_iny_vl : forall (x y : Vertex) (vl : V_list) (el : E_list), Path x y vl el -> vl <> V_nil -> In y vl. Proof. intros x y vl el p; elim p; intros. absurd (V_nil = @V_nil A); auto. inversion p0. simpl in |- *; auto. rewrite H9; simpl in |- *; right. apply H; rewrite <- H9; discriminate. Qed. Lemma P_endx_inv : forall (x y : Vertex) (vl : V_list) (el : E_list), Path x y vl el -> v x. Proof. intros x y vl el p; elim p; auto. Qed. Lemma P_endy_inv : forall (x y : Vertex) (vl : V_list) (el : E_list), Path x y vl el -> v y. Proof. intros x y vl el p; elim p; auto. Qed. Lemma P_invl_inv : forall (x y : Vertex) (vl : V_list) (el : E_list), Path x y vl el -> forall z : Vertex, In z vl -> v z. Proof. intros x y vl el p; elim p; intros. inversion H. inversion H0. rewrite <- H1; apply (P_endx_inv _ _ _ _ p0). auto. Qed. Lemma P_inel_ina : forall (x y : Vertex) (vl : V_list) (el : E_list), Path x y vl el -> forall x' y' : Vertex, In (E_ends x' y') el -> a (A_ends x' y'). Proof. intros x y vl el p; elim p; intros. inversion H. inversion H0. inversion H1. rewrite <- H3; rewrite <- H4; trivial. auto. Qed. Lemma P_inxyel_inxvl : forall (x y : Vertex) (vl : V_list) (el : E_list), Path x y vl el -> forall x' y' : Vertex, In (E_ends x' y') el -> In x' (x :: vl). Proof. intros x y vl el p; elim p; intros. inversion H. inversion H0. inversion H1. simpl in |- *; auto. simpl in |- *; right. apply (H x' y'); auto. Qed. Lemma P_inxyel_inyvl : forall (x y : Vertex) (vl : V_list) (el : E_list), Path x y vl el -> forall x' y' : Vertex, In (E_ends x' y') el -> In y' (x :: vl). Proof. intros x y vl el p; elim p; intros. inversion H. inversion H0. inversion H1. simpl in |- *; auto. simpl in |- *; right. apply (H x' y'); auto. Qed. Lemma P_backstep : forall (x y z : Vertex) (vl : V_list) (el : E_list), Path x z (y :: vl) el -> {el' : E_list & Path y z vl el'}. Proof. intros; inversion X. split with el0; trivial. Qed. Lemma Trail_isa_walk : forall (x y : Vertex) (vl : V_list) (el : E_list), Trail x y vl el -> Walk x y vl el. Proof. intros x y vl el t; elim t; intros. apply W_null; trivial. apply W_step; trivial. Qed. Lemma Path_isa_trail : forall (x y : Vertex) (vl : V_list) (el : E_list), Path x y vl el -> Trail x y vl el. Proof. intros x y vl el t; elim t; intros. apply T_null; trivial. apply T_step; trivial. Qed. Lemma Path_isa_walk : forall (x y : Vertex) (vl : V_list) (el : E_list) (Hp: Path x y vl el), Walk x y vl el. Proof. intros. apply Path_isa_trail in Hp. apply Trail_isa_walk; auto. Qed. End PATH. Implicit Arguments Path [A]. Implicit Arguments Walk [A]. Implicit Arguments P_backstep [A]. Implicit Arguments P_endx_inv [A]. Implicit Arguments P_inxyel_inxvl [A]. Implicit Arguments P_inxyel_inyvl [A]. Section EXTRACTED. Variable A:Type. Variable eq_a_dec: forall x y : A, {x = y} + {x <> y}. Variable v : @V_set A. Variable a : @A_set A. Fixpoint V_extract (x : Vertex) (vl : V_list) {struct vl} : V_list := match vl with | nil => V_nil | y :: vl' => if V_in_dec eq_a_dec x vl' then V_extract x vl' else vl' end. Lemma V_extract_spec: forall v1 v2 vl, In v1 (V_extract v2 vl) -> v1 <> v2 -> In v1 vl. Proof. induction vl; simpl; intros; auto. destruct (V_in_dec eq_a_dec v2 vl); auto. Qed. Lemma V_extract_spec': forall v1 v2 vl, In v1 (V_extract v2 (v1::vl)) -> v1 <> v2 -> In v1 vl. Proof. induction vl; simpl; intros. destruct (V_in_dec eq_a_dec v2 nil); auto. destruct (V_in_dec eq_a_dec v2 (a0::vl)); auto. Qed. Lemma V_extract_spec'': forall v1 v2 vl, In v1 (V_extract v2 vl) -> In v1 vl. Proof. induction vl; simpl; intros; auto. destruct (V_in_dec eq_a_dec v2 vl); auto. Qed. Lemma P_extract : forall (x y z : Vertex) (vl : V_list) (el : E_list), Path v a y z vl el -> In x (y :: vl) -> {el' : E_list & Path v a x z (V_extract x (y :: vl)) el'}. Proof. intros x y z vl; generalize y; elim vl; simpl in |- *; intros. split with el. replace x with y0; auto. case (V_in_dec eq_a_dec y0 nil); auto. tauto. elim (P_backstep _ _ _ _ _ _ _ X0); intros. case (V_in_dec eq_a_dec x (a0 :: l)). intros. apply (X a0 x0); auto. simpl in |- *. intros. split with el. replace x with y0. trivial. tauto. Qed. Remark P_when_cycle : forall (x y : Vertex) (vl : V_list) (el : E_list), Path v a x y vl el -> In x vl -> x = y. Proof. intros x y vl el H; inversion H; intros. trivial. inversion H10. absurd (x = y0); auto. auto. Qed. Lemma Walk_to_path : forall (x y : Vertex) (vl : V_list) (el : E_list), Walk v a x y vl el -> {vl0 : V_list & {el0 : E_list & Path v a x y vl0 el0}}. Proof. intros x y vl el w; elim w; intros. split with V_nil; split with E_nil; apply P_null; trivial. elim X; clear X; intros vl' X. elim X; clear X; intros el' X. case (V_in_dec eq_a_dec x0 (y0 :: vl')); intros. elim (P_extract _ _ _ _ _ X i); intros. split with (V_extract x0 (y0 :: vl')); split with x1; auto. case (V_in_dec eq_a_dec y0 vl'); intros. split with (y0 :: V_nil); split with (E_ends x0 y0 :: E_nil). apply P_step. replace z with y0. apply P_null; apply (P_endx_inv _ _ _ _ _ _ X). apply (P_when_cycle _ _ _ _ X); auto. trivial. trivial. red in |- *; intros; elim n; rewrite H; simpl in |- *; auto. tauto. simpl in |- *. tauto. tauto. split with (y0 :: vl'); split with (E_ends x0 y0 :: el'). apply P_step. trivial. trivial. trivial. red in |- *; intros; elim n; rewrite H; simpl in |- *; auto. trivial. intros; absurd (In x0 vl'). red in |- *; intros; elim n; simpl in |- *; auto. trivial. red in |- *; intros. elim n; inversion H0. apply (P_inxyel_inxvl _ _ _ _ _ _ X x0 y0). rewrite <- H2; auto. apply (P_inxyel_inyvl _ _ _ _ _ _ X y0 x0). rewrite <- H3; rewrite <- H4; rewrite H1; trivial. Qed. End EXTRACTED. Implicit Arguments Cycle [A]. Implicit Arguments P_inel_ina [A]. Implicit Arguments P_iny_vl [A]. Section PATH_AND_DEGREE. Variable A:Type. Variable eq_a_dec: forall x y : A, {x = y} + {x <> y}. Variable v : (@V_set A). Variable a : (@A_set A). Variable g : Graph v a. Lemma Path_degree_one : forall (x y : Vertex) (vl : V_list) (el : E_list), Path v a x y vl el -> forall z : Vertex, In z vl -> degree eq_a_dec z v a g > 0. Proof. intros x y vl el p; elim p; intros. inversion H. inversion H0. rewrite <- H1; apply Degree_not_isolated. split with x0; apply (G_non_directed v a g); trivial. apply H; auto. Qed. Lemma Path_consx_degree_one : forall (x y : Vertex) (vl : V_list) (el : E_list), Path v a x y vl el -> vl <> V_nil -> forall z : Vertex, In z (x :: vl) -> degree eq_a_dec z v a g > 0. Proof. simple destruct vl; intros. absurd (nil = @V_nil A); auto. inversion H0. rewrite <- H1; apply Degree_not_isolated. inversion X; split with v0; trivial. apply (Path_degree_one x y (v0 :: l) el X); auto. Qed. Lemma Path_degree_two : forall (x y : Vertex) (vl : V_list) (el : E_list), Path v a x y vl el -> forall z : Vertex, In z vl -> z <> y -> degree eq_a_dec z v a g > 1. Proof. intros x y vl el p; elim p; intros. inversion H. inversion H0. inversion p0. absurd (z0 = z). trivial. rewrite <- H2; auto. rewrite <- H2; apply Degree_not_pendant. split with x0. apply (G_non_directed v a g); trivial. split with y1. trivial. red in |- *; intros. elim (n1 (E_ends y0 y1)). rewrite <- H12; simpl in |- *; auto. rewrite H13; apply E_rev. apply H; trivial. Qed. Lemma Path_last_step : forall (x y : Vertex) (vl : V_list) (el : E_list) (p : Path v a x y vl el), el <> E_nil -> exists z : Vertex, In (E_ends z y) el. Proof. intros x y vl el p; elim p. intros; elim H; trivial. simple destruct el0; intros. split with x0. inversion p0. simpl in |- *; left; trivial. elim H; intros. split with x1. simpl in |- *; auto. discriminate. Qed. Lemma Cycle_degree_two : forall (x y : Vertex) (vl : V_list) (el : E_list) (p : Path v a x y vl el), Cycle v a x y vl el p -> forall z : Vertex, In z vl -> degree eq_a_dec z v a g > 1. Proof. intros; case (V_eq_dec eq_a_dec z y); intros. rewrite e; apply Degree_not_pendant. inversion p. rewrite <- H4 in H0; inversion H0. inversion H. split with y0. rewrite <- H11; trivial. elim (Path_last_step y0 y vl0 el0 X); intros. split with x1. apply (G_non_directed v a g); apply (P_inel_ina v a y0 y vl0 el0 X); trivial. red in |- *; intros; elim (H6 (E_ends x1 y)). trivial. rewrite H11; rewrite H13; apply E_rev. inversion X. absurd (x = y0). trivial. rewrite H14; trivial. discriminate. apply (Path_degree_two x y vl el p); trivial. Qed. Lemma Cycle_consx_degree_two : forall (x y : Vertex) (vl : V_list) (el : E_list) (p : Path v a x y vl el), vl <> V_nil -> Cycle v a x y vl el p -> forall z : Vertex, In z (x :: vl) -> degree eq_a_dec z v a g > 1. Proof. intros; inversion H1. rewrite <- H2; inversion H0. apply (Cycle_degree_two x y vl el p H0 y). apply (P_iny_vl v a x y vl el p); trivial. apply (Cycle_degree_two x y vl el p H0); trivial. Qed. Lemma Path_degree_zero_nil : forall (x y : Vertex) (vl : V_list) (el : E_list), Path v a x y vl el -> (exists2 z : Vertex, In z (x :: vl) & degree eq_a_dec z v a g = 0) -> vl = V_nil. Proof. simple destruct vl; intros. trivial. elim H; intros. absurd (degree eq_a_dec x0 v a g > 0). omega. apply (Path_consx_degree_one _ _ _ _ X). discriminate. trivial. Qed. Lemma Cycle_degree_one_nil : forall (x y : Vertex) (vl : V_list) (el : E_list) (p : Path v a x y vl el), Cycle v a x y vl el p -> (exists2 z : Vertex, In z (x :: vl) & degree eq_a_dec z v a g <= 1) -> vl = V_nil. Proof. simple destruct vl; intros. trivial. elim H0; intros. absurd (degree eq_a_dec x0 v a g > 1). omega. apply (Cycle_consx_degree_two _ _ _ _ p). discriminate. trivial. trivial. Qed. End PATH_AND_DEGREE. Implicit Arguments Trail [A]. Section PATH_EQ. Variable A:Type. Lemma Walk_eq : forall (v v' : V_set) (a a' : @A_set A) (x y : Vertex) (vl : V_list) (el : E_list), Walk v a x y vl el -> v = v' -> a = a' -> Walk v' a' x y vl el. Proof. intros; elim X; intros. apply W_null. rewrite <- H; trivial. apply W_step. trivial. rewrite <- H; trivial. rewrite <- H0; trivial. Qed. Lemma Trail_eq : forall (v v' : V_set) (a a' : @A_set A) (x y : Vertex) (vl : V_list) (el : E_list), Trail v a x y vl el -> v = v' -> a = a' -> Trail v' a' x y vl el. Proof. intros; elim X; intros. apply T_null. rewrite <- H; trivial. intros; apply T_step. trivial. rewrite <- H; trivial. rewrite <- H0; trivial. trivial. Qed. Lemma Path_eq : forall (v v' : V_set) (a a' : @A_set A) (x y : Vertex) (vl : V_list) (el : E_list), Path v a x y vl el -> v = v' -> a = a' -> Path v' a' x y vl el. Proof. intros; elim X; intros. apply P_null. rewrite <- H; trivial. intros; apply P_step. trivial. rewrite <- H; trivial. rewrite <- H0; trivial. trivial. trivial. trivial. trivial. Qed. End PATH_EQ. Section PATH_IN_A_SUBGRAPH. Variable A:Type. Lemma Walk_subgraph : forall (v v' : V_set) (a a' : @A_set A) (x y : Vertex) (vl : V_list) (el : E_list), Walk v a x y vl el -> V_included v v' -> A_included a a' -> Walk v' a' x y vl el. Proof. intros; elim X; intros. apply W_null; apply (H x0); trivial. apply W_step. trivial. apply (H x0); trivial. apply (H0 (A_ends x0 y0)); trivial. Qed. Lemma Trail_subgraph : forall (v v' : V_set) (a a' : @A_set A) (x y : Vertex) (vl : V_list) (el : E_list), Trail v a x y vl el -> V_included v v' -> A_included a a' -> Trail v' a' x y vl el. Proof. intros; elim X; intros. apply T_null; apply (H x0); trivial. apply T_step. trivial. apply (H x0); trivial. apply (H0 (A_ends x0 y0)); trivial. trivial. Qed. Lemma Path_subgraph : forall (v v' : V_set) (a a' : @A_set A) (x y : Vertex) (vl : V_list) (el : E_list), Path v a x y vl el -> V_included v v' -> A_included a a' -> Path v' a' x y vl el. Proof. intros; elim X; intros. apply P_null; apply (H x0); trivial. apply P_step. trivial. apply (H x0); trivial. apply (H0 (A_ends x0 y0)); trivial. trivial. trivial. trivial. trivial. Qed. Lemma Path_supergraph_vertex : forall (v v' : V_set) (a : A_set) (x y : Vertex) (vl : V_list) (el : @E_list A), Path v a x y vl el -> v' x -> (forall z : Vertex, In z vl -> v' z) -> Path v' a x y vl el. Proof. intros v v' a x y vl el p; elim p; intros. apply P_null; trivial. apply P_step. apply X. apply H0; simpl in |- *; auto. intros; apply H0; simpl in |- *; auto. trivial. trivial. trivial. trivial. trivial. trivial. Qed. Lemma Path_supergraph_cons_vertex : forall (v : V_set) (a : A_set) (x y z : Vertex) (vl : V_list) (el : @E_list A), Path (V_union (V_single z) v) a x y vl el -> z <> x -> ~ In z vl -> Path v a x y vl el. Proof. intros v a x y z vl el p; elim p; intros. apply P_null. inversion v0. inversion H1; absurd (z = x0); auto. trivial. apply P_step. apply X. red in |- *; intros; elim H0. rewrite H1; simpl in |- *; auto. red in |- *; intros; elim H0; simpl in |- *; auto. inversion v0. inversion H1; absurd (z = x0); auto. trivial. trivial. trivial. trivial. trivial. trivial. Qed. Lemma Path_supergraph_arc : forall (v v' : V_set) (a a' : A_set) (x y : Vertex) (vl : V_list) (el : @E_list A), Path v a x y vl el -> Graph v' a' -> v' x -> (forall x' y' : Vertex, In (E_ends x' y') el -> a' (A_ends x' y')) -> Path v' a' x y vl el. Proof. intros v v' a a' x y vl el p; elim p; intros. apply P_null; trivial. apply P_step. apply X. trivial. apply (G_ina_inv2 v' a' X0 x0 y0). apply H0; simpl in |- *; auto. intros; apply H0; simpl in |- *; auto. trivial. apply H0; simpl in |- *; auto. trivial. trivial. trivial. trivial. Qed. Lemma Path_supergraph_cons_arc : forall (v : V_set) (a : A_set) (x y x' y' : Vertex) (vl : V_list) (el : @E_list A), Path v (A_union (E_set x' y') a) x y vl el -> ~ In (E_ends x' y') el -> ~ In (E_ends y' x') el -> Path v a x y vl el. Proof. intros v a x y x' y' vl el p; elim p; intros. apply P_null; trivial. apply P_step. apply X. red in |- *; intros; elim H. simpl in |- *; auto. red in |- *; intros; elim H0; simpl in |- *; auto. trivial. inversion a0. inversion H1. absurd (In (E_ends x' y') (E_ends x0 y0 :: el0)). trivial. rewrite H4; rewrite H5; simpl in |- *; auto. absurd (In (E_ends y' x') (E_ends x0 y0 :: el0)). trivial. rewrite H4; rewrite H5; simpl in |- *; auto. trivial. trivial. trivial. trivial. trivial. Qed. End PATH_IN_A_SUBGRAPH. Section APPEND_WALKS. Variable A:Type. Variable v : @V_set A. Variable a : @A_set A. Lemma Walk_append : forall (x y z : Vertex) (vl vl' : V_list) (el el' : E_list), Walk v a x y vl el -> Walk v a y z vl' el' -> Walk v a x z (vl ++ vl') (el ++ el'). Proof. intros x y z vl vl' el el' Hw; elim Hw; simpl in |- *; intros. trivial. apply W_step; auto. Qed. End APPEND_WALKS. Implicit Arguments Walk_append [A]. Section REVERSE_WALK. Variable A:Type. Variable eq_a_dec: forall x y : A, {x = y} + {x <> y}. Variable v : @V_set A. Variable a : @A_set A. Variable g : Graph v a. Definition cdr (vl : @V_list A) : V_list := match vl with | nil => V_nil | x :: vl' => vl' end. Lemma cdr_app : forall vl vl' : V_list, vl <> V_nil -> cdr (vl ++ vl') = cdr vl ++ vl'. Proof. simple induction vl; simpl in |- *; intros. absurd (V_nil = @V_nil A); auto. trivial. Qed. Fixpoint E_reverse (el : E_list) : E_list := match el with | nil => E_nil | E_ends x y :: el' => E_reverse el' ++ E_ends y x :: @E_nil A end. Lemma G_ends_in : forall x y : Vertex, a (A_ends x y) -> v x. Proof. elim g; intros. inversion H. case (V_eq_dec eq_a_dec x x0); intros. rewrite e; apply V_in_left; apply V_in_single. apply V_in_right; apply (H x0 y); trivial. inversion H0. inversion H1; rewrite <- H4; trivial. apply (H x0 y0); trivial. rewrite <- e; apply (H x y); rewrite e0; trivial. Qed. Lemma Walk_reverse : forall (x y : Vertex) (vl : V_list) (el : E_list), Walk v a x y vl el -> Walk v a y x (cdr (rev (x :: vl))) (E_reverse el). Proof. intros; elim X; simpl in |- *; intros. apply W_null; trivial. rewrite cdr_app. apply (Walk_append v a z y0 x0). trivial. apply W_step. apply W_null; trivial. apply (G_ina_inv2 v a g x0 y0); trivial. apply (G_non_directed v a g); trivial. case (rev vl0); intros; simpl in |- *; discriminate. Qed. End REVERSE_WALK. Implicit Arguments Path_degree_zero_nil [A]. Implicit Arguments Cycle_degree_one_nil [A]. Implicit Arguments Walk_subgraph [A]. Implicit Arguments Walk_to_path [A]. Implicit Arguments V_extract [A].
import csv import os.path as osp import pickle import numpy as np import pandas as pd from configs import DATA_DIR class DataUtils: """ Helper class to load and prepared data for training. """ @staticmethod def save_tokenizer(tokenizer, path): try: with open(path, "wb") as f: pickle.dump(tokenizer, f) except: print("Saving tokenizer on path {} was unsuccessful!".format(path)) @staticmethod def load_tokenizer(path): try: with open(path, "rb") as f: tokenizer = pickle.load(f) tokenizer.oov_token = None return tokenizer except: print("Couldn't load tokenizer from path `{}`!".format(path)) return None @staticmethod def save_embedding_matrix(embedding_matrix, path): try: np.save(path, embedding_matrix) except: print("Saving embedding matrix was unsuccessful!") @staticmethod def load_embedding_matrix(emb_matrix_path=None, tokenizer=None): """ Firstly tries to load embedding matrix if the file is available. If it's not, build new embedding matrix from vocabulary and save it for further use. Parameters ---------- emb_matrix_path : str tokenizer : keras.Tokenizer Returns ------- embedding_matrix : np.array Numpy 2D-array (matrix) containing pre-trained vectors for words in vocabulary. """ embedding_matrix = None if emb_matrix_path: try: embedding_matrix = np.load(emb_matrix_path) except: print("Couldn't load embedding matrix on local path: {}.".format(emb_matrix_path)) if tokenizer: try: embedding_matrix = Glove().build_embedding_matrix(word2idx=tokenizer.word_index) except: print("Couldn't build embedding matrix with tokenizer") return embedding_matrix class Glove: def __init__(self, glove_file='glove.6B.300d.txt'): self.glove_path = osp.join(DATA_DIR, glove_file) self.glove = self.read_glove() self.embedding_dim = self.get_embedding_dim() def read_glove(self): """ Reads pre-trained glove vectors from `glove.6B.300d.txt`. This file is required! Returns ------- pandas.DataFrame Glove pre-trained weights """ try: glove = pd.read_table(self.glove_path, sep=" ", header=None, quoting=csv.QUOTE_NONE) except FileNotFoundError: print("Glove file not found, please make sure you have it downloaded and placed in " "`DATA_DIR` directory!") glove = None return glove def get_embedding_dim(self): """ Calculate embedding dimension (equals to number of columns) Returns ------- embedding_dim : int """ embedding_dim = None if self.glove is None else self.glove.shape[1] - 1 return embedding_dim def build_embedding_matrix(self, word2idx): """ Create embedding weights for Keras Embedding layer. Parameters ---------- word2idx : dict Words in vocabulary for which to look up weight vectors. Returns ------- numpy array Embedding matrix where each row/index correspond to word in `word2idx` and its vector weights. """ if self.glove is not None: words = self.glove.rename(columns={self.glove.columns[0]: "words"}) words['words'].apply(str) # Convert to dictionary embedding_index = words.set_index('words').T.to_dict('list') # i=0 -> PAD; i=len(word2idx)+1 -> UNK; embedding_matrix = np.zeros((len(word2idx) + 2, self.embedding_dim)) # Create embedding matrix for word, i in word2idx.items(): embedding_vector = embedding_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector else: print("Trying to build embedding matrix build glove is not loaded!") embedding_matrix = None return embedding_matrix
lemma sum: "\<lbrakk>finite I; \<And>i. i \<in> I \<Longrightarrow> f i \<in> R\<rbrakk> \<Longrightarrow> (\<lambda>x. \<Sum>i \<in> I. f i x) \<in> R"
# PerfForesightConsumerType ```python # Initial imports and notebook setup, click arrow to show from HARK.ConsumptionSaving.ConsIndShockModel import PerfForesightConsumerType from HARK.utilities import plotFuncs from time import clock import matplotlib.pyplot as plt import numpy as np mystr = lambda number : "{:.4f}".format(number) ``` The module $\texttt{HARK.ConsumptionSaving.ConsIndShockModel}$ concerns consumption-saving models with idiosyncratic shocks to (non-capital) income. All of the models assume CRRA utility with geometric discounting, no bequest motive, and income shocks that are either fully transitory or fully permanent. $\texttt{ConsIndShockModel}$ currently includes three models: 1. A very basic "perfect foresight" model with no uncertainty (shocks are zero). 2. A model with risk over transitory and permanent income shocks. 3. The model described in (2), with an interest rate for debt that differs from the interest rate for savings. This notebook provides documentation for the first of these three models. $\newcommand{\CRRA}{\rho}$ $\newcommand{\DiePrb}{\mathsf{D}}$ $\newcommand{\PermGroFac}{\Gamma}$ $\newcommand{\Rfree}{\mathsf{R}}$ $\newcommand{\DiscFac}{\beta}$ ## Statement of the model The $\texttt{PerfForesightConsumerType}$ class solves the problem of a consumer with Constant Relative Risk Aversion utility ${\CRRA}$ \begin{equation} U(C) = \frac{C^{1-\CRRA}}{1-\rho}, \end{equation} who has perfect foresight about everything except whether he will die between the end of period $t$ and the beginning of period $t+1$. Permanent labor income $P_t$ grows from period $t$ to period $t+1$ by factor $\PermGroFac_{t+1}$. The consumer faces no artificial borrowing constraint: He is able to borrow against his entire future stream of income. At the beginning of period $t$, the consumer has market resources $M_t$ (which includes both market wealth and currrent income) and must choose how much to consume $C_t$ and how much to retain in a riskless asset $A_t$, which will earn return factor $\Rfree$. The agent's flow of future utility $U(C_{t+n})$ from consumption is geometrically discounted by factor $\DiscFac$ per period. The consumer only experiences future value if he survives, which occurs with probability $1-\DiePrb_{t+1}$. For parallelism with the treatment of more complicated problems, we write the problem rather elaborately in Bellman form as: \begin{eqnarray*} V_t(M_t,P_t) &=& \max_{C_t}~U(C_t) ~+ \DiscFac (1 - \DiePrb_{t+1}) V_{t+1}(M_{t+1},P_{t+1}), \\ & s.t. & \\ A_t &=& M_t - C_t, \\ M_{t+1} &=& \Rfree A_t + Y_{t+1}, \\ Y_{t+1} &=& P_{t+1}, \\ P_{t+1} &=& \PermGroFac_{t+1} P_t. \end{eqnarray*} The parameters of the consumer's problem are the coefficient of relative risk aversion $\CRRA$, the intertemporal discount factor $\DiscFac$, an interest factor $\Rfree$, and age-varying sequences of the permanent income growth factor $\PermGroFac_t$ and survival probability $(1 - \DiePrb_t)$. [These lecture notes](http://econ.jhu.edu/people/ccarroll/public/lecturenotes/consumption/PerfForesightCRRA) show that under these assumptions the problem can be transformed into an equivalent problem stated in terms of *normalized* variables (represented in lower case); all real variables are divided by permanent income $P_t$ and value is divided by $P_t^{1-\CRRA}$. The Bellman form of the normalized model (see the lecture notes for details) is: \begin{eqnarray*} v_t(m_t) &=& \max_{c_t}~U(c_t) ~+ \DiscFac (1 - \DiePrb_{t+1}) \PermGroFac_{t+1}^{1-\CRRA} v_{t+1}(m_{t+1}), \\ & s.t. & \\ a_t &=& m_t - c_t, \\ m_{t+1} &=& a_t (\Rfree/\PermGroFac_{t+1} )+ 1. \end{eqnarray*} ## Solution method for PerfForesightConsumerType Because of the assumptions of CRRA utility, no risk other than mortality, and no artificial borrowing constraint, the problem has a closed form solution in which consumption is a linear function of resources, and the utility-inverse of the value function is also linear (that is, $u^{-1}(v)$ is linear in $m$). Details of the mathematical solution of this model can be found in the lecture notes [PerfForesightCRRA](http://econ.jhu.edu/people/ccarroll/public/lecturenotes/consumption/PerfForesightCRRA). The one period problem for this model is solved by the function $\texttt{solveConsPerfForesight}$, which creates an instance of the class $\texttt{ConsPerfForesightSolver}$. To construct an instance of the class $\texttt{PerfForesightConsumerType}$, several parameters must be passed to this constructor. ## Example parameter values | Parameter | Description | Code | Example value | Time-varying? | | :---: | --- | --- | --- | --- | | $\DiscFac$ |Intertemporal discount factor | $\texttt{DiscFac}$ | $0.96$ | | | $\CRRA $ |Coefficient of relative risk aversion | $\texttt{CRRA}$ | $2.0$ | | | $\Rfree$ | Risk free interest factor | $\texttt{Rfree}$ | $1.03$ | | | $1 - \DiePrb_{t+1}$ |Survival probability | $\texttt{LivPrb}$ | $[0.98]$ | $\surd$ | |$\PermGroFac_{t+1}$|Permanent income growth factor|$\texttt{PermGroFac}$| $[1.01]$ | $\surd$ | |$T$| Number of periods in this type's "cycle" |$\texttt{T_cycle}$| $1$ | | |(none)| Number of times the "cycle" occurs |$\texttt{cycles}$| $0$ | | Note that the survival probability and income growth factor have time subscripts; likewise, the example values for these parameters are *lists* rather than simply single floats. This is because those parameters are in principle *time-varying*: their values can depend on which period of the problem the agent is in (for example, mortality probability depends on age). All time-varying parameters *must* be specified as lists, even when the model is being solved for an infinite horizon case where in practice the parameter takes the same value in every period. The last two parameters in the table specify the "nature of time" for this type: the number of (non-terminal) periods in this type's "cycle", and the number of times that the "cycle" occurs. *Every* subclass of $\texttt{AgentType}$ uses these two code parameters to define the nature of time. Here, $\texttt{T_cycle}$ has the value $1$, indicating that there is exactly one period in the cycle, while $\texttt{cycles}$ is $0$, indicating that the cycle is repeated in *infinite* number of times-- it is an infinite horizon model, with the same "kind" of period repeated over and over. In contrast, we could instead specify a life-cycle model by setting $\texttt{T_cycle}$ to $1$, and specifying age-varying sequences of income growth and survival probability. In all cases, the number of elements in each time-varying parameter should exactly equal $\texttt{T_cycle}$. The parameter $\texttt{AgentCount}$ specifies how many consumers there are of this *type*-- how many individuals have these exact parameter values and are *ex ante* homogeneous. This information is not relevant for solving the model, but is needed in order to simulate a population of agents, introducing *ex post* heterogeneity through idiosyncratic shocks. Of course, simulating a perfect foresight model is quite boring, as there are *no* idiosyncratic shocks other than death! The cell below defines a dictionary that can be passed to the constructor method for $\texttt{PerfForesightConsumerType}$, with the values from the table here. ```python PerfForesightDict = { # Parameters actually used in the solution method "CRRA" : 2.0, # Coefficient of relative risk aversion "Rfree" : 1.03, # Interest factor on assets "DiscFac" : 0.96, # Default intertemporal discount factor "LivPrb" : [0.98], # Survival probability "PermGroFac" :[1.01], # Permanent income growth factor # Parameters that characterize the nature of time "T_cycle" : 1, # Number of periods in the cycle for this agent type "cycles" : 0 # Number of times the cycle occurs (0 --> infinitely repeated) } ``` ## Inspecting the solution With the dictionary we have just defined, we can create an instance of $\texttt{PerfForesightConsumerType}$ by passing the dictionary to the class (as if the class were a function). This instance can then be solved by invoking its $\texttt{solve}$ method. ```python PFexample = PerfForesightConsumerType(**PerfForesightDict) PFexample.cycles = 0 PFexample.solve() ``` The $\texttt{solve}$ method fills in the instance's attribute $\texttt{solution}$ as a time-varying list of solutions to each period of the consumer's problem. In this case, $\texttt{solution}$ will be a list with exactly one instance of the class $\texttt{ConsumerSolution}$, representing the solution to the infinite horizon model we specified. ```python print(PFexample.solution) ``` [<HARK.ConsumptionSaving.ConsIndShockModel.ConsumerSolution object at 0x1c196a6f98>] Each element of $\texttt{solution}$ has a few attributes. To see all of them, we can use the $\texttt{vars}$ built in function: the consumption functions are instantiated in the attribute $\texttt{cFunc}$ of each element of $\texttt{ConsumerType.solution}$. This method creates a (time varying) attribute $\texttt{cFunc}$ that contains a list of consumption functions by age. ```python print(vars(PFexample.solution[0])) ``` {'cFunc': <HARK.interpolation.LinearInterp object at 0x1c196a4550>, 'vFunc': <HARK.ConsumptionSaving.ConsIndShockModel.ValueFunc object at 0x1c196a6fd0>, 'vPfunc': <HARK.ConsumptionSaving.ConsIndShockModel.MargValueFunc object at 0x1c196a6d68>, 'vPPfunc': <HARK.utilities.NullFunc object at 0x1c196a6da0>, 'mNrmMin': -50.49994992551661, 'hNrm': 50.49994992551661, 'MPCmin': 0.04428139169919579, 'MPCmax': 0.04428139169919579} The two most important attributes of a single period solution are the (normalized) consumption function $\texttt{cFunc}$ and the (normalized) value function $\texttt{vFunc}$; the marginal value function $\texttt{vPfunc}$ is also constructed. Let's plot those functions near the lower bound of the permissible state space (the attribute $\texttt{mNrmMin}$ tells us the lower bound of $m_t$ where the consumption function is defined). ```python print('Linear perfect foresight consumption function:') mMin = PFexample.solution[0].mNrmMin plotFuncs(PFexample.solution[0].cFunc,mMin,mMin+10.) ``` ```python print('Perfect foresight value function:') plotFuncs(PFexample.solution[0].vFunc,mMin+0.1,mMin+10.1) ``` ## Solution Method ### Recursive Formula for $\kappa_{t}$ The paper [BufferStockTheory](https://www.econ2.jhu.edu/people/ccarroll/papers/BufferStockTheory/) has a few other results that are used in the solution code. One is [the recursive formula for the MPC](https://www.econ2.jhu.edu/people/ccarroll/papers/BufferStockTheory/#MPCnvrs). Starting with the last period, in which $\kappa_{T}=1$, the inverse MPC's (and therefore the MPC's themselves) can be constructed using the recursive formula: \begin{align} \kappa_{t}^{-1} & = & 1 + \kappa_{t+1}^{-1}(\Rfree \beta)^{1/\rho}/G \end{align} ### Consumption Function For the perfect foresight problem, there is a well-known [analytical solution]( http://econ.jhu.edu/people/ccarroll/public/lecturenotes/consumption/PerfForesightCRRA/#cFuncAnalytical) for the consumption function: Calling $o_{t}$ 'overall wealth' (including market wealth plus human wealth $h_{t}$) and designating the marginal propensity to consume in period $t$ by $\kappa_{t}$: \begin{align} \mathrm{c}_{t} & = o_{t}\kappa_{t} \end{align} and in our normalized model $o_{t} = m_{t}-1+h_{t}$ (the '-1' term subtracts off the normalized current income of 1 from market resources $m$ which were market wealth plus current income). ### Value Function A convenient feature of the perfect foresight problem is that the value function has a simple [analytical form](http://econ.jhu.edu/people/ccarroll/public/lecturenotes/consumption/PerfForesightCRRA/#vFuncAnalytical): \begin{align} \mathrm{v}_{t} & = \mathrm{u}(\mathrm{c}_{t}(m))\kappa_{t}^{-1}\\ &= \mathrm{u}(o_{t} \kappa_{t}) \kappa_{t}^{-1} \\ &= \mathrm{u}(o_{t})\kappa_{t}^{1-\rho} \kappa_{t}^{-1} \\ &= \mathrm{u}(o_{t})\kappa_{t}^{-\rho} \end{align} This means that the utility-inverse of the value function, ${\scriptsize \Lambda} \equiv \mathrm{u}^{-1}(\mathrm{v})$, is linear: \begin{align} \scriptsize \Lambda_{t} & = o_{t} \kappa_{t}^{-\rho/(1-\rho)} \end{align} When uncertainty or liquidity constraints are added to the problem, the ${\scriptsize \Lambda}$ function is no longer linear. But even in these cases, the utility-inverse of the value function is much better behaved (e.g., closer to linear; bounded over any feasible finite range of $m$) than the uninverted function (which, for example, approaches $-\infty$ as $m$ approaches its lower bound). Our procedure will therefore generically be to construct the inverse value function, and to obtain the value function from it by uninverting. That is, we construct an interpolating approximation of $\scriptsize \Lambda_{t}$ and compute value on-the-fly from \begin{align} \mathrm{v}_{t}(m) & = \mathrm{u}({\scriptsize \Lambda_{t}}(m)) \end{align} In this case, the interpolation is exact, not an approximation: We need only two points to construct a line, so we choose the minimum possible value of normalized market resources, $\texttt{mNrmMin}$, where $o_{t}=0$ so that $c_{t}=0$, and that minimum plus 1, where the inverted value function will have the value $\kappa_{t}^{-\rho/(1-\rho)}$. From these we construct $vFuncNvrs$ as a linear interpolating function (which automatically extrapolates to the whole number line). ## Checking Solution Conditions The code performs tests for whether the supplied parameter values meet various conditions that determine the properties of the solution. Some conditions (like the Finite Human Wealth Condition) are required for the model to have a sensible solution, and if these conditions are violated the code generates a warning message. Other conditions govern characteristics of the model like whether consumption is falling (whether the consumer is 'absolutely impatient'). All conditions can manually be performed using the syntax below. The function returns "False" if none of the key conditions has been violated. ```python PFexample.checkConditions(verbose=True,public_call=True) ``` The value of the absolute impatience factor for the supplied parameter values satisfies the Absolute Impatience Condition. Therefore, the absolute amount of consumption is expected to fall over time. The value of the growth impatience factor for the supplied parameter values satisfies the Growth Impatience Condition. Therefore, the ratio of individual wealth to permanent income will fall indefinitely. The return impatience factor value for the supplied parameter values satisfies the Return Impatience Condition. Therefore, the limiting consumption function is not c(m)=0 The Finite Human wealth factor value for the supplied parameter values satisfies the Finite Human Wealth Condition. Therefore, the limiting consumption function is not c(m)=Infinity and human wealth normalized by permanent income is 51.50000 and the PDV of future consumption growth is 22.58285 False An element of $\texttt{solution}$ also includes the (normalized) marginal value function $\texttt{vPfunc}$, and the lower and upper bounds of the marginal propensity to consume (MPC) $\texttt{MPCmin}$ and $\texttt{MPCmax}$. Note that with a linear consumption function, the MPC is constant, so its lower and upper bound are identical. ## Simulating the model Suppose we wanted to simulate many consumers who share the parameter values that we passed to $\texttt{PerfForesightConsumerType}$-- an *ex ante* homogeneous *type* of consumers. To do this, our instance would have to know *how many* agents there are of this type, as well as their initial levels of assets $a_t$ and permanent income $P_t$. ### Setting Parameters Let's fill in this information by passing another dictionary to $\texttt{PFexample}$ with simulation parameters. The table below lists the parameters that an instance of $\texttt{PerfForesightConsumerType}$ needs in order to successfully simulate its model using the $\texttt{simulate}$ method. | Description | Code | Example value | | :---: | --- | --- | | Number of consumers of this type | $\texttt{AgentCount}$ | $10000$ | | Number of periods to simulate | $\texttt{T_sim}$ | $120$ | | Mean of initial log (normalized) assets | $\texttt{aNrmInitMean}$ | $-6.0$ | | Stdev of initial log (normalized) assets | $\texttt{aNrmInitStd}$ | $1.0$ | | Mean of initial log permanent income | $\texttt{pLvlInitMean}$ | $0.0$ | | Stdev of initial log permanent income | $\texttt{pLvlInitStd}$ | $0.0$ | | Aggregrate productivity growth factor | $\texttt{PermGroFacAgg}$ | $1.0$ | | Age after which consumers are automatically killed | $\texttt{T_age}$ | $None$ | We have specified the model so that initial assets and permanent income are both distributed lognormally, with mean and standard deviation of the underlying normal distributions provided by the user. The parameter $\texttt{PermGroFacAgg}$ exists for compatibility with more advanced models that employ aggregate productivity shocks; it can simply be set to 1. In infinite horizon models, it might be useful to prevent agents from living extraordinarily long lives through a fortuitous sequence of mortality shocks. We have thus provided the option of setting $\texttt{T_age}$ to specify the maximum number of periods that a consumer can live before they are automatically killed (and replaced with a new consumer with initial state drawn from the specified distributions). This can be turned off by setting it to $\texttt{None}$. The cell below puts these parameters into a dictionary, then gives them to $\texttt{PFexample}$. Note that all of these parameters *could* have been passed as part of the original dictionary; we omitted them above for simplicity. ```python # Create parameter values necessary for simulation SimulationParams = { "AgentCount" : 10000, # Number of agents of this type "T_sim" : 120, # Number of periods to simulate "aNrmInitMean" : -6.0, # Mean of log initial assets "aNrmInitStd" : 1.0, # Standard deviation of log initial assets "pLvlInitMean" : 0.0, # Mean of log initial permanent income "pLvlInitStd" : 0.0, # Standard deviation of log initial permanent income "PermGroFacAgg" : 1.0, # Aggregate permanent income growth factor "T_age" : None, # Age after which simulated agents are automatically killed } PFexample(**SimulationParams) # This implicitly uses the assignParameters method of AgentType ``` To generate simulated data, we need to specify which variables we want to track the "history" of for this instance. To do so, we set the $\texttt{track_vars}$ attribute of our $\texttt{PerfForesightConsumerType}$ instance to be a list of strings with the simulation variables we want to track. In this model, valid elments of $\texttt{track_vars}$ include $\texttt{mNrmNow}$, $\texttt{cNrmNow}$, $\texttt{aNrmNow}$, and $\texttt{pLvlNow}$. Because this model has no idiosyncratic shocks, our simulated data will be quite boring. ### Generating simulated data Before simulating, the $\texttt{initializeSim}$ method must be invoked. This resets our instance back to its initial state, drawing a set of initial $\texttt{aNrmNow}$ and $\texttt{pLvlNow}$ values from the specified distributions and storing them in the attributes $\texttt{aNrmNow_init}$ and $\texttt{pLvlNow_init}$. It also resets this instance's internal random number generator, so that the same initial states will be set every time $\texttt{initializeSim}$ is called. In models with non-trivial shocks, this also ensures that the same sequence of shocks will be generated on every simulation run. Finally, the $\texttt{simulate}$ method can be called. ```python # Create PFexample object PFexample.track_vars = ['mNrmNow'] PFexample.initializeSim() PFexample.simulate() ``` Each simulation variable $\texttt{X}$ named in $\texttt{track_vars}$ will have the *history* of that variable for each agent stored in the attribute $\texttt{X_hist}$ as an array of shape $(\texttt{T_sim},\texttt{AgentCount})$. To see that the simulation worked as intended, we can plot the mean of $m_t$ in each simulated period: ```python # Plot market resources over time plt.plot(np.mean(PFexample.mNrmNow_hist,axis=1)) plt.xlabel('Time') plt.ylabel('Mean normalized market resources') plt.show() ``` A perfect foresight consumer can borrow against the PDV of his future income-- his human wealth-- and thus as time goes on, our simulated impatient agents approach the (very negative) steady state level of $m_t$ while being steadily replaced with consumers with roughly $m_t=1$. The slight wiggles in the plotted curve are due to consumers randomly dying and being replaced; their replacement will have an initial state drawn from the distributions specified by the user. To see the current distribution of ages, we can look at the attribute $\texttt{t_age}$. ```python # Plot the CDF N = PFexample.AgentCount F = np.linspace(0.,1.,N) plt.plot(np.sort(PFexample.t_age),F) plt.xlabel('Current age of consumers') plt.ylabel('Cumulative distribution') plt.show() ``` The distribution is (discretely) exponential, with a point mass at 120 with consumers who have survived since the beginning of the simulation. One might wonder why HARK requires users to call $\texttt{initializeSim}$ before calling $\texttt{simulate}$: Why doesn't $\texttt{simulate}$ just call $\texttt{initializeSim}$ as its first step? We have broken up these two steps so that users can simulate some number of periods, change something in the environment, and then resume the simulation. When called with no argument, $\texttt{simulate}$ will simulate the model for $\texttt{T_sim}$ periods. The user can optionally pass an integer specifying the number of periods to simulate (which should not exceed $\texttt{T_sim}$). In the cell below, we simulate our perfect foresight consumers for 80 periods, then seize a bunch of their assets (dragging their wealth even more negative), then simulate for the reamining 40 periods. ```python # The final resulting distribution is reasonably coherent PFexample.initializeSim() PFexample.simulate(80) PFexample.aNrmNow += -5. # Adjust all simulated consumers' assets downward by 5 PFexample.simulate(40) plt.plot(np.mean(PFexample.mNrmNow_hist,axis=1)) plt.xlabel('Time') plt.ylabel('Mean normalized market resources') plt.show() ```
! ! Copyright 2017 SALMON developers ! ! Licensed under the Apache License, Version 2.0 (the "License"); ! you may not use this file except in compliance with the License. ! You may obtain a copy of the License at ! ! http://www.apache.org/licenses/LICENSE-2.0 ! ! Unless required by applicable law or agreed to in writing, software ! distributed under the License is distributed on an "AS IS" BASIS, ! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ! See the License for the specific language governing permissions and ! limitations under the License. ! !--------10--------20--------30--------40--------50--------60--------70--------80--------90--------100-------110-------120-------130 subroutine print_optimize_message implicit none print *, 'Preprocessor: ' #ifdef ARTED_USE_TLOG print *, ' ARTED_USE_TLOG' #endif #ifdef ARTED_CURRENT_PREPROCESSING print *, ' ARTED_CURRENT_PREPROCESSING' #endif #ifdef ARTED_STENCIL_ORIGIN print *, ' ARTED_STENCIL_ORIGIN' #endif #ifdef ARTED_STENCIL_OPTIMIZED print *, ' ARTED_STENCIL_OPTIMIZED' #endif #ifdef ARTED_STENCIL_PADDING print *, ' ARTED_STENCIL_PADDING' #endif #ifdef ARTED_STENCIL_ENABLE_LOOP_BLOCKING print *, ' ARTED_STENCIL_ENABLE_LOOP_BLOCKING' #endif #ifdef ARTED_DOMAIN_POWER_OF_TWO print *, ' ARTED_DOMAIN_POWER_OF_TWO' #endif #ifdef ARTED_EXPLICIT_VECTORIZATION print *, ' ARTED_EXPLICIT_VECTORIZATION' #endif #ifdef ARTED_ENABLE_SOFTWARE_PREFETCH print *, ' ARTED_ENABLE_SOFTWARE_PREFETCH' #endif end subroutine
function sVF = grad(sF, varargin) % calculates the gradient of a spherical harmonic % % Syntax % sVF = grad(sF) % returns the gradient as a spherical vector field % g = grad(sF, v) % return the gradient in point v as vector3d % % Input % sF - @S2FunHarmonic % v - @vector3d % % Output % sVF - @sphericalVectorFieldHarmonic % g - @vector3d % if nargin > 1 sF = [sF.drho; sF.dthetasin]; v = varargin{1}; y = eval(sF, v); sVF = ... y(:, 1)./sin(v.theta).^2.*S2VectorField.rho(v)+ ... y(:, 2) .* S2VectorField.theta(v); sVF(isnan(sVF)) = vector3d([0 0 0]); else sF = [sF.drho; sF.dtheta]; sVF = S2VectorFieldHarmonic(sF); end end