Datasets:
AI4M
/

text
stringlengths
0
3.34M
If $a$ and $b$ are non-positive real numbers, then $ab$ is non-negative.
theory Datatype_Selectors imports Main begin text\<open> Running Example: @{text "datatype_new iptrule_match = is_Src: Src (src_range: ipt_iprange)"} A discriminator @{text disc} tells whether a value is of a certain constructor. Example: @{text "is_Src"} A selector @{text sel} select the inner value. Example: @{text "src_range"} A constructor @{text C} constructs a value Example: @{text "Src"} The are well-formed if the belong together. \<close> fun wf_disc_sel :: "(('a \<Rightarrow> bool) \<times> ('a \<Rightarrow> 'b)) \<Rightarrow> ('b \<Rightarrow> 'a) \<Rightarrow> bool" where "wf_disc_sel (disc, sel) C \<longleftrightarrow> (\<forall>a. disc a \<longrightarrow> C (sel a) = a) \<and> (\<forall>a. (*disc (C a) \<longrightarrow>*) sel (C a) = a)" (* should the following be added to the definition? the discriminator is true for all C independent of the a for example: is_Src_IP is true for all Src_IPs, independent of the numberic value of the ip. lemma "wf_disc_sel (disc, sel) C \<Longrightarrow> (\<exists>a. disc (C a)) \<longrightarrow> (\<forall>a. disc (C a))" *) declare wf_disc_sel.simps[simp del] end
If $f$ is continuous on the closed interval $[a,b]$, then $f$ has a supremum on $[a,b]$.
[STATEMENT] lemma step_symb_set_mono: "R \<subseteq> S \<Longrightarrow> step_symb_set R \<subseteq> step_symb_set S" [PROOF STATE] proof (prove) goal (1 subgoal): 1. R \<subseteq> S \<Longrightarrow> step_symb_set R \<subseteq> step_symb_set S [PROOF STEP] by (auto simp add: step_symb_set_def)
{-# OPTIONS --without-K --safe #-} open import Level open import Categories.Category open import Categories.Monad module Categories.Monad.Morphism {o ℓ e} {C D : Category o ℓ e} where open import Categories.NaturalTransformation open import Categories.Functor open NaturalTransformation -- monad morphism in the sense of the nLab -- https://ncatlab.org/nlab/show/monad#the_bicategory_of_monads -- between generic monads t : a -> a & s : b -> b record Monad⇒ (M : Monad C) (N : Monad D) : Set (o ⊔ ℓ ⊔ e) where private module M = Monad M module N = Monad N open module D = Category D using (_∘_; _≈_) field X : Functor C D α : NaturalTransformation (N.F ∘F X) (X ∘F M.F) module X = Functor X module α = NaturalTransformation α field unit-comp : ∀ {U} → α.η U ∘ (N.η.η (X.₀ U)) ≈ X.₁ (M.η.η U) mult-comp : ∀ {U} → α.η U ∘ (N.μ.η (X.₀ U)) ≈ X.₁ (M.μ.η U) ∘ α.η (M.F.₀ U) ∘ N.F.₁ (α.η U) -- monad morphism in a different sense: -- monads are on the same category, X is the identity record Monad⇒-id (M N : Monad C) : Set (o ⊔ ℓ ⊔ e) where private module M = Monad M module N = Monad N field α : NaturalTransformation N.F M.F module α = NaturalTransformation α open module C = Category C using (_∘_; _≈_) field unit-comp : ∀ {U} → α.η U ∘ N.η.η U ≈ M.η.η U mult-comp : ∀ {U} → α.η U ∘ (N.μ.η U) ≈ M.μ.η U ∘ α.η (M.F.₀ U) ∘ N.F.₁ (α.η U) -- monad 2-cell in the sense of https://ncatlab.org/nlab/show/monad#the_bicategory_of_monads record Monad²⇒ {M : Monad C} {N : Monad D} (Γ Δ : Monad⇒ M N) : Set (o ⊔ ℓ ⊔ e) where private module M = Monad M module N = Monad N module Γ = Monad⇒ Γ module Δ = Monad⇒ Δ field m : NaturalTransformation Γ.X Δ.X module m = NaturalTransformation m open module D = Category D using (_∘_; _≈_) field comm : ∀ {U} → Δ.α.η U ∘ N.F.₁ (m.η U) ≈ m.η (M.F.₀ U) ∘ Γ.α.η U
Formal statement is: lemma has_contour_integral_newpath: "\<lbrakk>(f has_contour_integral y) h; f contour_integrable_on g; contour_integral g f = contour_integral h f\<rbrakk> \<Longrightarrow> (f has_contour_integral y) g" Informal statement is: If $f$ has a contour integral along a path $h$, and $f$ is contour integrable along a path $g$, and the contour integrals of $f$ along $g$ and $h$ are equal, then $f$ has a contour integral along $g$.
[STATEMENT] lemma d_commutative: "d(x) * d(y) = d(y) * d(x)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. d x * d y = d y * d x [PROOF STEP] by (metis sup_commute order.antisym d_sup_left_absorb_mult d_below_one d_export d_mult_left_absorb_sup mult_assoc mult_left_isotone mult_left_one)
From RecordUpdate Require Import RecordSet. Record X := mkX { A: nat; B: nat; C: bool; }. (* all you need to do is provide something like this, listing out the fields of your record: *) Instance etaX : Settable _ := settable! mkX <A; B; C>. (* and now you can update fields! *) Definition setAB a b x := set B b (set A a x). (* you can also use a notation for the same thing: *) Import RecordSetNotations. Definition setAB' a b x := x <|A := a|> <|B := b|>.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \section{Before we begin} \label{sec:bwb} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \input{bwb/prerequisites} \newpage \input{bwb/conventions} \newpage \input{bwb/help} %\newpage \input{bwb/gridpp}
State Before: ι : Type u_1 V : Type u inst✝¹ : Category V inst✝ : Preadditive V c : ComplexShape ι C D E : HomologicalComplex V c f✝ g : C ⟶ D h k : D ⟶ E i✝ : ι f : (i j : ι) → X C i ⟶ X D j i i' : ι w : ComplexShape.Rel c i i' ⊢ ↑(dNext i) f = d C i i' ≫ f i' i State After: ι : Type u_1 V : Type u inst✝¹ : Category V inst✝ : Preadditive V c : ComplexShape ι C D E : HomologicalComplex V c f✝ g : C ⟶ D h k : D ⟶ E i✝ : ι f : (i j : ι) → X C i ⟶ X D j i : ι w : ComplexShape.Rel c i (ComplexShape.next c i) ⊢ ↑(dNext i) f = d C i (ComplexShape.next c i) ≫ f (ComplexShape.next c i) i Tactic: obtain rfl := c.next_eq' w State Before: ι : Type u_1 V : Type u inst✝¹ : Category V inst✝ : Preadditive V c : ComplexShape ι C D E : HomologicalComplex V c f✝ g : C ⟶ D h k : D ⟶ E i✝ : ι f : (i j : ι) → X C i ⟶ X D j i : ι w : ComplexShape.Rel c i (ComplexShape.next c i) ⊢ ↑(dNext i) f = d C i (ComplexShape.next c i) ≫ f (ComplexShape.next c i) i State After: no goals Tactic: rfl
(* Author: Norbert Schirmer Maintainer: Norbert Schirmer, norbert.schirmer at web de License: LGPL *) (* Title: HoareTotalDef.thy Author: Norbert Schirmer, TU Muenchen Copyright (C) 2004-2008 Norbert Schirmer Some rights reserved, TU Muenchen This library 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 library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) header {* Hoare Logic for Total Correctness *} theory HoareTotalDef imports HoarePartialDef Termination begin subsection {* Validity of Hoare Tuples: @{text "\<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A"} *} definition validt :: "[('s,'p,'f) body,'f set,'s assn,('s,'p,'f) com,'s assn,'s assn] \<Rightarrow> bool" ("_\<Turnstile>\<^sub>t\<^bsub>'/_\<^esub>/ _ _ _,_" [61,60,1000, 20, 1000,1000] 60) where "\<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A \<equiv> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A \<and> (\<forall>s \<in> Normal ` P. \<Gamma>\<turnstile>c\<down>s)" definition cvalidt:: "[('s,'p,'f) body,('s,'p) quadruple set,'f set, 's assn,('s,'p,'f) com,'s assn,'s assn] \<Rightarrow> bool" ("_,_\<Turnstile>\<^sub>t\<^bsub>'/_\<^esub>/ _ _ _,_" [61,60, 60,1000, 20, 1000,1000] 60) where "\<Gamma>,\<Theta>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A \<equiv> (\<forall>(P,p,Q,A)\<in>\<Theta>. \<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P (Call p) Q,A) \<longrightarrow> \<Gamma> \<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" notation (ascii) validt ("_|=t'/_/ _ _ _,_" [61,60,1000, 20, 1000,1000] 60) and cvalidt ("_,_|=t'/_ / _ _ _,_" [61,60,60,1000, 20, 1000,1000] 60) subsection {* Properties of Validity *} lemma validtI: "\<lbrakk>\<And>s t. \<lbrakk>\<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> \<Rightarrow> t;s \<in> P;t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A; \<And>s. s \<in> P \<Longrightarrow> \<Gamma>\<turnstile> c\<down>(Normal s) \<rbrakk> \<Longrightarrow> \<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" by (auto simp add: validt_def valid_def) lemma cvalidtI: "\<lbrakk>\<And>s t. \<lbrakk>\<forall>(P,p,Q,A)\<in>\<Theta>. \<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P (Call p) Q,A;\<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> \<Rightarrow> t;s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A; \<And>s. \<lbrakk>\<forall>(P,p,Q,A)\<in>\<Theta>. \<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P (Call p) Q,A; s\<in>P\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>c\<down>(Normal s)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" by (auto simp add: cvalidt_def validt_def valid_def) lemma cvalidt_postD: "\<lbrakk>\<Gamma>,\<Theta>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A; \<forall>(P,p,Q,A)\<in>\<Theta>. \<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P (Call p) Q,A;\<Gamma>\<turnstile>\<langle>c,Normal s \<rangle> \<Rightarrow> t; s \<in> P;t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A" by (simp add: cvalidt_def validt_def valid_def) lemma cvalidt_termD: "\<lbrakk>\<Gamma>,\<Theta>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A; \<forall>(P,p,Q,A)\<in>\<Theta>. \<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P (Call p) Q,A;s \<in> P\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>c\<down>(Normal s)" by (simp add: cvalidt_def validt_def valid_def) lemma validt_augment_Faults: assumes valid:"\<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" assumes F': "F \<subseteq> F'" shows "\<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F'\<^esub> P c Q,A" using valid F' by (auto intro: valid_augment_Faults simp add: validt_def) subsection {* The Hoare Rules: @{text "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" } *} inductive "hoaret"::"[('s,'p,'f) body,('s,'p) quadruple set,'f set, 's assn,('s,'p,'f) com,'s assn,'s assn] => bool" ("(3_,_/\<turnstile>\<^sub>t\<^bsub>'/_\<^esub> (_/ (_)/ _,_))" [61,60,60,1000,20,1000,1000]60) for \<Gamma>::"('s,'p,'f) body" where Skip: "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> Q Skip Q,A" | Basic: "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> {s. f s \<in> Q} (Basic f) Q,A" | Spec: "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> {s. (\<forall>t. (s,t) \<in> r \<longrightarrow> t \<in> Q) \<and> (\<exists>t. (s,t) \<in> r)} (Spec r) Q,A" | Seq: "\<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c\<^sub>1 R,A; \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P Seq c\<^sub>1 c\<^sub>2 Q,A" | Cond: "\<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> (P \<inter> b) c\<^sub>1 Q,A; \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> (P \<inter> - b) c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P (Cond b c\<^sub>1 c\<^sub>2) Q,A" | While: "\<lbrakk>wf r; \<forall>\<sigma>. \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> ({\<sigma>} \<inter> P \<inter> b) c ({t. (t,\<sigma>)\<in>r} \<inter> P),A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P (While b c) (P \<inter> - b),A" | Guard: "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> (g \<inter> P) c Q,A \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> (g \<inter> P) Guard f g c Q,A" | Guarantee: "\<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P (Guard f g c) Q,A" | CallRec: "\<lbrakk>(P,p,Q,A) \<in> Specs; wf r; Specs_wf = (\<lambda>p \<sigma>. (\<lambda>(P,q,Q,A). (P \<inter> {s. ((s,q),(\<sigma>,p)) \<in> r},q,Q,A)) ` Specs); \<forall>(P,p,Q,A)\<in> Specs. p \<in> dom \<Gamma> \<and> (\<forall>\<sigma>. \<Gamma>,\<Theta> \<union> Specs_wf p \<sigma>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> ({\<sigma>} \<inter> P) (the (\<Gamma> p)) Q,A) \<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P (Call p) Q,A" | DynCom: "\<forall>s \<in> P. \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P (c s) Q,A \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P (DynCom c) Q,A" | Throw: "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> A Throw Q,A" | Catch: "\<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A" | Conseq: "\<forall>s \<in> P. \<exists>P' Q' A'. \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P' c Q',A' \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" | Asm: "(P,p,Q,A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P (Call p) Q,A" | ExFalso: "\<lbrakk>\<Gamma>,\<Theta>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" -- {* This is a hack rule that enables us to derive completeness for an arbitrary context @{text "\<Theta>"}, from completeness for an empty context.*} text {* Does not work, because of rule ExFalso, the context @{text \<Theta>} is to blame. A weaker version with empty context can be derived from soundness later on. *} lemma hoaret_to_hoarep: assumes hoaret: "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P p Q,A" shows "\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F\<^esub> P p Q,A" using hoaret proof (induct) case Skip thus ?case by (rule hoarep.intros) next case Basic thus ?case by (rule hoarep.intros) next case Seq thus ?case by - (rule hoarep.intros) next case Cond thus ?case by - (rule hoarep.intros) next case (While r \<Theta> F P b c A) hence "\<forall>\<sigma>. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F\<^esub> ({\<sigma>} \<inter> P \<inter> b) c ({t. (t, \<sigma>) \<in> r} \<inter> P),A" by iprover hence "\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F\<^esub> (P \<inter> b) c P,A" by (rule HoarePartialDef.conseq) blast then show "\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F\<^esub> P While b c (P \<inter> - b),A" by (rule hoarep.While) next case Guard thus ?case by - (rule hoarep.intros) (*next case (CallRec A F P Procs Q Z \<Theta> p r) hence hyp: "\<forall>p\<in>Procs. \<forall>\<tau> Z. \<Gamma>,\<Theta> \<union> (\<Union>q\<in>Procs. \<Union>Z. {(P q Z \<inter> {s. ((s, q), \<tau>, p) \<in> r}, Call q, Q q Z,A q Z)})\<turnstile>\<^bsub>/F\<^esub> ({\<tau>} \<inter> P p Z) (the (\<Gamma> p)) (Q p Z),(A p Z)" by blast have "\<forall>p\<in>Procs. \<forall>Z. \<Gamma>,\<Theta> \<union> (\<Union>q\<in>Procs. \<Union>Z. {(P q Z, Call q, Q q Z,A q Z)})\<turnstile>\<^bsub>/F\<^esub> (P p Z) (the (\<Gamma> p)) (Q p Z),(A p Z)" proof (intro ballI allI) fix p Z assume "p \<in> Procs" with hyp have hyp': "\<And> \<tau>. \<Gamma>,\<Theta> \<union> (\<Union>q\<in>Procs. \<Union>Z. {(P q Z \<inter> {s. ((s, q), \<tau>, p) \<in> r}, Call q, Q q Z, A q Z)})\<turnstile>\<^bsub>/F\<^esub> ({\<tau>} \<inter> P p Z) (the (\<Gamma> p)) (Q p Z),(A p Z)" by blast have "\<forall>\<tau>. \<Gamma>,\<Theta> \<union> (\<Union>q\<in>Procs. \<Union>Z. {(P q Z, Call q, Q q Z,A q Z)})\<turnstile>\<^bsub>/F\<^esub> ({\<tau>} \<inter> P p Z) (the (\<Gamma> p)) (Q p Z),(A p Z)" (is "\<forall>\<tau>. \<Gamma>,?\<Theta>'\<turnstile>\<^bsub>/F\<^esub> ({\<tau>} \<inter> P p Z) (the (\<Gamma> p)) (Q p Z),(A p Z)") proof (rule allI, rule WeakenContext [OF hyp'],clarify) fix \<tau> P' c Q' A' assume "(P', c, Q', A') \<in> \<Theta> \<union> (\<Union>q\<in>Procs. \<Union>Z. {(P q Z \<inter> {s. ((s, q), \<tau>, p) \<in> r}, Call q, Q q Z, A q Z)})" (is "(P', c, Q', A') \<in> \<Theta> \<union> ?Spec") then show "\<Gamma>,?\<Theta>'\<turnstile>\<^bsub>/F\<^esub> P' c Q',A'" proof (cases rule: UnE [consumes 1]) assume "(P',c,Q',A') \<in> \<Theta>" then show ?thesis by (blast intro: HoarePartialDef.Asm) next assume "(P',c,Q',A') \<in> ?Spec" then show ?thesis proof (clarify) fix q Z assume q: "q \<in> Procs" show "\<Gamma>,?\<Theta>'\<turnstile>\<^bsub>/F\<^esub> (P q Z \<inter> {s. ((s, q), \<tau>, p) \<in> r}) Call q (Q q Z),(A q Z)" proof - from q have "\<Gamma>,?\<Theta>'\<turnstile>\<^bsub>/F\<^esub> (P q Z) Call q (Q q Z),(A q Z)" by - (rule HoarePartialDef.Asm,blast) thus ?thesis by (rule HoarePartialDef.conseqPre) blast qed qed qed qed then show "\<Gamma>,\<Theta> \<union> (\<Union>q\<in>Procs. \<Union>Z. {(P q Z, Call q, Q q Z,A q Z)}) \<turnstile>\<^bsub>/F\<^esub> (P p Z) (the (\<Gamma> p)) (Q p Z),(A p Z)" by (rule HoarePartialDef.conseq) blast qed thus ?case by - (rule hoarep.CallRec)*) next case DynCom thus ?case by (blast intro: hoarep.DynCom) next case Throw thus ?case by - (rule hoarep.Throw) next case Catch thus ?case by - (rule hoarep.Catch) next case Conseq thus ?case by - (rule hoarep.Conseq,blast) next case Asm thus ?case by (rule HoarePartialDef.Asm) next case (ExFalso \<Theta> F P c Q A) assume "\<Gamma>,\<Theta>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" hence "\<Gamma>,\<Theta>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A" oops lemma hoaret_augment_context: assumes deriv: "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P p Q,A" shows "\<And>\<Theta>'. \<Theta> \<subseteq> \<Theta>' \<Longrightarrow> \<Gamma>,\<Theta>'\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P p Q,A" using deriv proof (induct) case (CallRec P p Q A Specs r Specs_wf \<Theta> F \<Theta>') have aug: "\<Theta> \<subseteq> \<Theta>'" by fact then have h: "\<And>\<tau> p. \<Theta> \<union> Specs_wf p \<tau> \<subseteq> \<Theta>' \<union> Specs_wf p \<tau>" by blast have "\<forall>(P,p,Q,A)\<in>Specs. p \<in> dom \<Gamma> \<and> (\<forall>\<tau>. \<Gamma>,\<Theta> \<union> Specs_wf p \<tau>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> ({\<tau>} \<inter> P) (the (\<Gamma> p)) Q,A \<and> (\<forall>x. \<Theta> \<union> Specs_wf p \<tau> \<subseteq> x \<longrightarrow> \<Gamma>,x\<turnstile>\<^sub>t\<^bsub>/F\<^esub> ({\<tau>} \<inter> P) (the (\<Gamma> p)) Q,A))" by fact hence "\<forall>(P,p,Q,A)\<in>Specs. p \<in> dom \<Gamma> \<and> (\<forall>\<tau>. \<Gamma>,\<Theta>'\<union> Specs_wf p \<tau> \<turnstile>\<^sub>t\<^bsub>/F\<^esub> ({\<tau>} \<inter> P) (the (\<Gamma> p)) Q,A)" apply (clarify) apply (rename_tac P p Q A) apply (drule (1) bspec) apply (clarsimp) apply (erule_tac x=\<tau> in allE) apply clarify apply (erule_tac x="\<Theta>' \<union> Specs_wf p \<tau>" in allE) apply (insert aug) apply auto done with CallRec show ?case by - (rule hoaret.CallRec) next case DynCom thus ?case by (blast intro: hoaret.DynCom) next case (Conseq P \<Theta> F c Q A \<Theta>') from Conseq have "\<forall>s \<in> P. (\<exists>P' Q' A'. (\<Gamma>,\<Theta>' \<turnstile>\<^sub>t\<^bsub>/F\<^esub> P' c Q',A') \<and> s \<in> P'\<and> Q' \<subseteq> Q \<and> A' \<subseteq> A)" by blast with Conseq show ?case by - (rule hoaret.Conseq) next case (ExFalso \<Theta> F P c Q A \<Theta>') have "\<Gamma>,\<Theta>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" "\<not> \<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" "\<Theta> \<subseteq> \<Theta>'" by fact+ then show ?case by (fastforce intro: hoaret.ExFalso simp add: cvalidt_def) qed (blast intro: hoaret.intros)+ subsection {* Some Derived Rules *} lemma Conseq': "\<forall>s. s \<in> P \<longrightarrow> (\<exists>P' Q' A'. (\<forall> Z. \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> (P' Z) c (Q' Z),(A' Z)) \<and> (\<exists>Z. s \<in> P' Z \<and> (Q' Z \<subseteq> Q) \<and> (A' Z \<subseteq> A))) \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" apply (rule Conseq) apply (rule ballI) apply (erule_tac x=s in allE) apply (clarify) apply (rule_tac x="P' Z" in exI) apply (rule_tac x="Q' Z" in exI) apply (rule_tac x="A' Z" in exI) apply blast done lemma conseq:"\<lbrakk>\<forall>Z. \<Gamma>,\<Theta> \<turnstile>\<^sub>t\<^bsub>/F\<^esub> (P' Z) c (Q' Z),(A' Z); \<forall>s. s \<in> P \<longrightarrow> (\<exists> Z. s\<in>P' Z \<and> (Q' Z \<subseteq> Q)\<and> (A' Z \<subseteq> A))\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" by (rule Conseq) blast theorem conseqPrePost: "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P' c Q',A' \<Longrightarrow> P \<subseteq> P' \<Longrightarrow> Q' \<subseteq> Q \<Longrightarrow> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" by (rule conseq [where ?P'="\<lambda>Z. P'" and ?Q'="\<lambda>Z. Q'"]) auto lemma conseqPre: "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P' c Q,A \<Longrightarrow> P \<subseteq> P' \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" by (rule conseq) auto lemma conseqPost: "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q',A'\<Longrightarrow> Q' \<subseteq> Q \<Longrightarrow> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" by (rule conseq) auto lemma Spec_wf_conv: "(\<lambda>(P, q, Q, A). (P \<inter> {s. ((s, q), \<tau>, p) \<in> r}, q, Q, A)) ` (\<Union>p\<in>Procs. \<Union>Z. {(P p Z, p, Q p Z, A p Z)}) = (\<Union>q\<in>Procs. \<Union>Z. {(P q Z \<inter> {s. ((s, q), \<tau>, p) \<in> r}, q, Q q Z, A q Z)})" apply (rule) apply fastforce apply (fastforce simp add: image_def) done lemma CallRec': "\<lbrakk>p\<in>Procs; Procs \<subseteq> dom \<Gamma>; wf r; \<forall>p\<in>Procs. \<forall>\<tau> Z. \<Gamma>,\<Theta>\<union>(\<Union>q\<in>Procs. \<Union>Z. {((P q Z) \<inter> {s. ((s,q),(\<tau>,p)) \<in> r},q,Q q Z,(A q Z))}) \<turnstile>\<^sub>t\<^bsub>/F\<^esub> ({\<tau>} \<inter> (P p Z)) (the (\<Gamma> p)) (Q p Z),(A p Z)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> (P p Z) (Call p) (Q p Z),(A p Z)" apply (rule CallRec [where Specs="\<Union>p\<in>Procs. \<Union>Z. {((P p Z),p,Q p Z,A p Z)}" and r=r]) apply blast apply assumption apply (rule refl) apply (clarsimp) apply (rename_tac p') apply (rule conjI) apply blast apply (intro allI) apply (rename_tac Z \<tau>) apply (drule_tac x=p' in bspec, assumption) apply (erule_tac x=\<tau> in allE) apply (erule_tac x=Z in allE) apply (fastforce simp add: Spec_wf_conv) done end
lemma setdist_le_dist: "\<lbrakk>x \<in> s; y \<in> t\<rbrakk> \<Longrightarrow> setdist s t \<le> dist x y"
import tactic.basic import tactic.linarith import data.set.basic import data.set.lattice import data.real.basic import data.set.finite import .sets --import topology.basic namespace topology open set universes u w -- Copied from mathlib structure topological_space (α : Type u) := (is_open : set α → Prop) (is_open_univ : is_open set.univ) (is_open_inter : ∀s t, is_open s → is_open t → is_open (s ∩ t)) (is_open_sUnion : ∀s:(set (set α)), (∀t∈s, is_open t) → is_open (⋃₀ s)) attribute [class] topological_space variables {α : Type*} {β : Type*} variables [topo: topological_space α] include topo def is_open (s : set α) : Prop := topological_space.is_open topo s def is_closed (s : set α) : Prop := is_open sᶜ lemma is_open_sUnion {s : set (set α)} (h : ∀t ∈ s, is_open t) : is_open (⋃₀ s) := topological_space.is_open_sUnion topo s h lemma is_open_Union {ι : Sort w} {f : ι → set α} (h : ∀i, is_open (f i)) : is_open (⋃i, f i) := is_open_sUnion $ by rintro _ ⟨i, rfl⟩; exact h i lemma is_open_bUnion {s : set β} {f : β → set α} (h : ∀i∈s, is_open (f i)) : is_open (⋃i∈s, f i) := is_open_Union $ assume i, is_open_Union $ assume hi, h i hi @[simp] lemma is_open_empty : topo.is_open ∅ := begin have h : is_open (⋃₀ ∅) := topo.is_open_sUnion _ (ball_empty_iff.mpr true.intro), rw sUnion_empty at h, exact h, end @[simp] lemma open_iff_closed_compl {s: set α} : is_open s ↔ is_closed sᶜ := begin unfold is_closed, rw compl_compl, end -- page 5 def neighborhood (s : set α) (x : α) := ∃ V, is_open V ∧ (x ∈ V) ∧ (V ⊆ s) def interior_point (x : α) (s : set α) := neighborhood s x def exterior_point (x : α) (s : set α) := neighborhood sᶜ x def interior (s : set α) := {x | interior_point x s} def closure (s : set α) := {x | ¬ exterior_point x s} lemma nhb_of_open {x:α} {s : set α} (o : is_open s) (h : x ∈ s) : neighborhood s x := ⟨ s, o, h, subset.rfl ⟩ lemma set_in_closure (s : set α) : s ⊆ closure s := begin intros x xin, unfold closure, unfold exterior_point, unfold neighborhood, intros ex, rcases ex with ⟨ _, _, xint, tincomp⟩, have : x ∈ sᶜ := tincomp xint, contradiction, end lemma closure_mono {s t : set α} (h : s ⊆ t) : closure s ⊆ closure t := begin unfold closure exterior_point neighborhood, simp, intros x hx O Oopen xinO Ointc, rw ← compl_subset_compl at h, exact (hx O Oopen xinO) (subset.trans Ointc h) end lemma closed_inter_of_closed (ss: set (set α)) (h: ∀ s ∈ ss, is_closed s) : is_closed ⋂₀ ss := begin unfold is_closed, rw compl_sInter, apply is_open_sUnion, intros s hs, simp at hs, rcases hs with ⟨t, tinss, scomp ⟩, have : is_closed t := h t tinss, rw ← scomp, exact this, end theorem closure_is_intersection (s : set α) : closure s = ⋂₀ {t | is_closed t ∧ s ⊆ t} := begin ext, split, { intros xincl, unfold closure at xincl, unfold exterior_point at xincl, unfold neighborhood at xincl, simp at xincl, let U := ⋂₀ {t | is_closed t ∧ s ⊆ t}, change x ∈ U, have closed_u : is_closed U, { apply closed_inter_of_closed, intros t tinU, rw mem_set_of_eq at tinU, exact tinU.1 }, have inSC : Uᶜ ⊆ sᶜ, { rw compl_subset_compl, intros a ha, rw mem_sInter, intros t tinU, rw mem_set_of_eq at tinU, exact tinU.2 ha, }, rw ← compl_compl U at closed_u, have baz := mt (xincl Uᶜ closed_u) (not_not.mpr inSC), have baz' : x ∈ U := set.not_not_mem.mp baz, exact baz', }, { simp, intros H, unfold closure, unfold exterior_point, unfold neighborhood, simp, intros t t_open x_in_t, rw not_subset, have := mt(H tᶜ t_open) (not_not.mpr x_in_t), cases (nonempty_of_not_subset this) with a ain, use a, simp, exact ⟨ set.not_not_mem.mp (not_mem_of_mem_diff ain), mem_of_mem_diff ain ⟩, } end lemma closure_closed {s : set α} : is_closed (closure s) := begin rw closure_is_intersection, apply closed_inter_of_closed, intros _ h, exact h.1 end -- page 6 -- a set is open iff all its points are interior theorem open_iff_all_int (s: set α) : is_open s ↔ ∀ x ∈ s, interior_point x s := begin split, { show is_open s → ∀ x ∈ s, interior_point x s, intros op x hx, exact ⟨ s, op, hx, by refl ⟩ }, { show (∀ x ∈ s, interior_point x s) → is_open s, intros h, choose! V isOpen xinV Vins using h, rw union_of_sub s V (λ x xin, ⟨ xinV x xin , Vins x xin⟩), apply is_open_sUnion, intros s', intros hs', simp at hs', rcases hs' with ⟨ x, hx, vxs⟩ , rw ← vxs, exact isOpen x hx, } end theorem interior_is_union_of_open (s : set α) : interior s = ⋃₀ {s' | is_open s' ∧ s' ⊆ s} := begin ext, simp, split, { show x ∈ interior s → ∃ t, (is_closed tᶜ ∧ t ⊆ s) ∧ x ∈ t, intros xint, rcases xint with ⟨ V, isOpen, xin, Vin⟩, exact ⟨ V, ⟨open_iff_closed_compl.mp isOpen, Vin⟩, xin⟩, }, { show (∃ t, (is_closed tᶜ ∧ t ⊆ s) ∧ x ∈ t) → x ∈ interior s, simp, intros s' isOpen sin' xin, exact ⟨ s', open_iff_closed_compl.mpr isOpen, xin, sin' ⟩, } end lemma interior_is_open (s : set α) : is_open (interior s) := begin rw interior_is_union_of_open _, apply is_open_sUnion, simp, intros t topen _, exact topen end lemma closed_iff_equal_to_closure {s : set α} : is_closed s ↔ s = closure s := begin rw closure_is_intersection, split, { show is_closed s → s = ⋂₀{t | is_closed t ∧ s ⊆ t}, intros closed, ext, split, { show x ∈ s → x ∈ ⋂₀{t | is_closed t ∧ s ⊆ t}, intros xin t tin, exact tin.2 xin, }, { show x ∈ ⋂₀{t | is_closed t ∧ s ⊆ t} → x ∈ s, intros xin, simp at xin, exact xin s closed subset.rfl, }, }, { show s = ⋂₀{t | is_closed t ∧ s ⊆ t} → is_closed s, intros sint, rw sint, apply closed_inter_of_closed, intros t tin, exact tin.1, } end lemma open_iff_compl_eq_closure (s : set α) : is_open s ↔ sᶜ = closure sᶜ := begin rw ← closed_iff_equal_to_closure, simp, end lemma closure_idempotent {s : set α} : closure (closure s) = closure s := (closed_iff_equal_to_closure.mp closure_closed).symm omit topo structure metric_space (α : Type u) := (metric : α → α → ℝ) (positive : ∀ x y, x ≠ y → metric x y > 0) (zero_self : ∀ x, metric x x = 0) (symm : ∀ x y, metric x y = metric y x) (triangle : ∀ x y z, metric x z ≤ metric x y + metric y z) attribute [class] metric_space variable [ms : metric_space α] include ms def εBall (x : α) (ε : ℝ) := { y : α | ms.metric x y < ε} lemma smaller_ball_subset {x : α} (a b : ℝ) (h : a ≤ b) : εBall x a ⊆ εBall x b := begin intros y yina, unfold εBall, have H : ms.metric x y < b := calc ms.metric x y < a : yina ... ≤ b : h, simp [H], end instance metric_topology : topological_space α := { is_open := λ s, ∀ x ∈ s, ∃ ε > 0, εBall x ε ⊆ s, is_open_univ := λ _ _, ⟨ 1, by linarith, by simp ⟩, is_open_inter := by { intros s t sball tball x xin, rcases sball x xin.1 with ⟨εs,εspos,hεs⟩, rcases tball x xin.2 with ⟨εt,εtpos,hεt⟩, use min εs εt, split, {exact lt_min εspos εtpos,}, { apply subset_inter, { have : εBall x (min εs εt) ⊆ εBall x εs, { apply smaller_ball_subset, apply min_le_left }, exact subset.trans this hεs, }, { have : εBall x (min εs εt) ⊆ εBall x εt, { apply smaller_ball_subset, apply min_le_right }, exact subset.trans this hεt, } } }, is_open_sUnion := by { intros ss h x xin, rw mem_sUnion at xin, rcases xin with ⟨ t, tinss, xint ⟩, rcases h t tinss x xint with ⟨ ε, εpos, ball_in_t ⟩, exact ⟨ ε, εpos, subset_sUnion_of_subset ss t ball_in_t tinss ⟩ } } lemma εBall_open {ε : ℝ} (x : α) (h: ε > 0) : is_open (εBall x ε) := begin intros y xinball, use ε - ms.metric x y, split, { show 0 < ε - ms.metric x y, exact sub_pos.mpr xinball, }, { show εBall y (ε - ms.metric x y) ⊆ εBall x ε, intros z zin, exact calc ms.metric x z ≤ ms.metric x y + ms.metric y z : by apply ms.triangle ... < ms.metric x y + (ε - ms.metric x y) : add_lt_add_left zin _ ... = ε : by {ring}, } end lemma center_in_ball {ε : ℝ} (x : α) (h: ε > 0) : x ∈ εBall x ε := begin change ms.metric x x < ε, rw ms.zero_self, exact h end omit ms def subspace (U : set α) (ts : topological_space α) : topological_space U := { is_open := λ s, ∃ (V : set α), is_open V ∧ (V ∩ U) = subtype.val '' s, is_open_univ := ⟨univ, ts.is_open_univ, by {simp [univ_inter]}⟩, is_open_inter := by { rintros s t ⟨V,OV,VU⟩ ⟨W,OW,WU⟩, use V ∩ W, split, {exact ts.is_open_inter V W OV OW,}, { rw ← image_inter, { suffices : V ∩ W ∩ U = V ∩ U ∩ W ∩ U, { rw this, rw VU, rw inter_assoc, rw WU, }, show V ∩ W ∩ U = V ∩ U ∩ W ∩ U, tidy, }, {exact subtype.val_injective} } }, is_open_sUnion := by { intros ss h, choose! s op eq using h, use ⋃i:ss, s i, split, { refine is_open_Union _, finish, }, { rw Union_inter, rw sUnion_eq_Union, finish [image_Union], } }, } def disjoint_union (s: topological_space α) (t: topological_space β) : topological_space (α ⊕ β) := { is_open := λ s:set (α ⊕ β), ∃ (u: set α) (v: set β), (u ⊕ v) = s, is_open_univ := sorry, is_open_inter := sorry, is_open_sUnion := sorry, } noncomputable def reals_metric_space : metric_space ℝ := { metric := λ x y, abs (x - y), positive := λ x y ne, by { apply abs_pos_of_ne_zero, exact sub_ne_zero_of_ne ne }, zero_self := by simp, symm := λ x y, by { have arg : abs (x-y) = abs (y-x), by { calc abs (x-y) = abs (- (y - x)) : by simp ... = abs (y-x) : abs_neg _, }, rw arg, }, triangle := λ x y z, by apply abs_sub_le, } noncomputable instance : metric_space ℝ := reals_metric_space --noncomputable def reals_metric_topology : topological_space ℝ := topology.metric_topology _ --noncomputable instance : topological_space ℝ := reals_metric_topology structure basis [topological_space α] (sets : set (set α)) (sets_open : ∀ s ∈ sets, is_open s) (union_of_open : ∀ s, is_open s → ∃ ss ⊆ sets, ⋃₀ ss = s) structure is_subbasis (ts: topological_space α) := (sets : set (set α)) (sets_open : ∀ s ∈ sets, ts.is_open s) -- infinite union of finite intersections of sets in sets (union_of_fin_inter : ∀ (s:set α), is_open s → ∃ sss : set (set (set α)), (∀ (ss ∈ sss), set.finite ss ∧ ∀ s ∈ ss, s ∈ sets) ∧ ⋃₀ ((λ i, ⋂₀ i) '' sss) = s ) def subbasis_generated (basis : set (set α)) : topological_space α := { is_open := λ s, ∃ sss : set (set (set α)), (∀ ss ∈ sss, set.finite ss ∧ ∀ s ∈ ss, s ∈ basis) ∧ ⋃₀ ((λ i, ⋂₀ i) '' sss) = s, is_open_univ := ⟨ {{}}, by simp ⟩ , is_open_inter := λ s t, by { intros os ot, choose! scomp scond sexp using os, choose! tcomp tcond texp using ot, have bar := (⋃p ∈ scomp.prod tcomp, (p : (set (set α)) × (set (set α ))).1 ∩ p.2), have baz := { ss | ss ∈ (scomp.prod tcomp) }, have baz' := (λ (ss : (set (set α)) × (set (set α ))), (ss.1) ∩ (ss.2)) '' baz, --use baz', use (λ (ss : (set (set α)) × (set (set α ))), (ss.1) ∩ (ss.2)) '' { ss | ss ∈ (scomp.prod tcomp) }, sorry }, is_open_sUnion := sorry } section continuity variables [ta: topological_space α] [tb: topological_space β] include ta tb def continuous (f: α → β) := ∀ V, (is_open V) → is_open (f⁻¹' V) lemma preimage_closed_iff_cont {f: α → β} : continuous f ↔ ∀ V, (is_closed V) → is_closed (f⁻¹' V) := begin split, { intros fcont V Vclosed, rw ← compl_compl V, have vcomp_open : is_open Vᶜ, {unfold is_closed at Vclosed, exact Vclosed}, rw preimage_compl, rw is_closed, rw compl_compl, exact fcont Vᶜ vcomp_open, }, { intro h, intros V Vopen, rw ← compl_compl V, have vcomp_closed : is_closed Vᶜ, {unfold is_closed, rw compl_compl, exact Vopen}, rw preimage_compl, exact h Vᶜ vcomp_closed, } end lemma preimage_nhb_nhb_iff_cont (f : α → β) : continuous f ↔ ∀ (x: α) (N : set β), neighborhood N (f x) → neighborhood (f⁻¹' N) x := begin split, { intros cont x N Nfx, rcases Nfx with ⟨O, oOpen, fxin, OsubN⟩, have h1 : is_open (f⁻¹' O) := cont O oOpen, have h2 : (f⁻¹' O) ⊆ f⁻¹' N := preimage_mono OsubN, exact ⟨ f⁻¹' O, h1, fxin, h2 ⟩, }, { intros h O Oopen, apply (open_iff_all_int (f⁻¹' O)).mpr, intros x xin, exact h x O (nhb_of_open Oopen xin), }, end lemma closure_preimage_sub_preimage_of_closure_iff_cont (f : α → β) : continuous f ↔ ∀ B, closure (f⁻¹' B) ⊆ f⁻¹' (closure B) := begin split, { intros cont B, have : B ⊆ closure B := set_in_closure B, have : f⁻¹' B ⊆ f⁻¹' (closure B) := preimage_mono this, have h : closure (f⁻¹' B) ⊆ closure (f⁻¹' (closure B)) := closure_mono this, have : is_closed (f⁻¹' (closure B)) := preimage_closed_iff_cont.mp cont (closure B) closure_closed, rw ← closed_iff_equal_to_closure.mp this at h, exact h, }, { intros h, apply preimage_closed_iff_cont.mpr, intros V Vclosed, have h1 : f⁻¹' V ⊆ closure (f⁻¹' V) := set_in_closure _, have h2 : closure (f⁻¹' V) ⊆ f⁻¹' V, { have w : f⁻¹' V = f⁻¹' (closure V), {rw ← closed_iff_equal_to_closure.mp Vclosed,}, have z := h V, rw w at z |-, exact z, }, rw subset.antisymm h1 h2, apply closure_closed, } end -- page 13 example (f : ℝ → ℝ) (cont: continuous f) : ∀ (x0 : ℝ) (ε > 0), ∃ δ > 0, ∀ (x : ℝ), abs(x - x0) < δ → abs (f x - f x0) < ε := begin intros x0 e epos, have open_x := cont (εBall (f x0) e) (εBall_open (f x0) epos), have : ∃ (ε > 0), εBall x0 ε ⊆ f ⁻¹' εBall (f x0) e := open_x x0 (center_in_ball (f x0) epos), rcases this with ⟨ δ, δpos, ball_in ⟩, use δ, split, {exact δpos,}, { intros x xin, have : x ∈ εBall x0 δ := by {rw abs_sub at xin, exact xin}, have : x ∈ f ⁻¹' εBall (f x0) e := ball_in this, simp at this, rw ← neg_sub, rw abs_neg, exact this, } end class homeomorphism (f : α → β) := (inv : β → α) (left_inv : inv ∘ f = id) (right_inv : f ∘ inv = id) (cont: continuous f) (invcont: continuous inv) def has_homeomorphism (f : α → β) := nonempty (homeomorphism f) @[simp] lemma left_inverse_hom (f : α → β) (h: homeomorphism f) : function.left_inverse h.inv f := begin intros x, change (h.inv ∘ f) x = x, rw h.left_inv, refl end @[simp] lemma right_inverse_hom (f : α → β) (h: homeomorphism f) : function.right_inverse h.inv f := begin intros x, change (f ∘ h.inv) x = x, rw h.right_inv, refl end lemma homeo_of_open_iff_to_open (f : α → β) (b: function.bijective f) : has_homeomorphism f ↔ (∀ U, is_open U ↔ is_open (f '' U)) := begin split, { intros has, have h := has.some, intros U, split, { show is_open U → is_open (f '' U), intro Uopen, have : f '' U = (h.inv)⁻¹' U, { rw image_eq_preimage_of_inverse, simp, simp, }, have bar := h.invcont, have baz := bar U Uopen, rw ← this at baz, exact baz, }, { show is_open (f '' U) → is_open U, intros imgopen, have : U = f⁻¹' (f '' U), { rw preimage_image_eq, apply function.left_inverse.injective, exact left_inverse_hom f h, }, have bar := h.cont, have baz := bar (f '' U) imgopen, rw ← this at baz, exact baz, } }, { intros h, exact nonempty.intro { inv := sorry, left_inv := sorry, right_inv := sorry, cont := sorry, invcont := sorry, }, } end end continuity section caracterization def connected (ts: topological_space α) := ¬ ∃ U V, ts.is_open U ∧ ts.is_open V ∧ U ∪ V = univ ∧ U ∩ V = ∅ ∧ U.nonempty ∧ V.nonempty lemma connected_no_open_close [topo : topological_space α] (h: connected topo) : ∀ (s: set α), is_open s → is_closed s → s = univ ∨ s = ∅ := begin intros s opens closeds, have h1 : is_open sᶜ := closeds, have h2 : s ∪ sᶜ = univ := union_compl_self _, have h3 : s ∩ sᶜ = ∅ := inter_compl_self _, have := forall_not_of_not_exists h s , push_neg at this, have : s.nonempty → ¬ sᶜ.nonempty := this sᶜ opens h1 h2 h3, rw not_nonempty_iff_eq_empty at this, rw compl_empty_iff at this, by_cases H : s.nonempty, {exact or.inl (this H)}, {exact or.inr (not_nonempty_iff_eq_empty.mp H)} end def unit_interval : set ℝ := {x | 0 ≤ x ∧ x ≤ 1} def unit_interval_t := { x:ℝ // 0 ≤ x ∧ x ≤ 1} instance : has_zero unit_interval_t := { zero := ⟨0, and.intro rfl.ge zero_le_one ⟩ } instance : has_one unit_interval_t := { one := ⟨1, and.intro zero_le_one rfl.ge ⟩ } noncomputable instance unit_interval_topology : topological_space unit_interval_t := subspace unit_interval (topology.metric_topology) def path_connected (ts: topological_space α) := ∀ (a b : α), ∃ (f: unit_interval_t → α), continuous f ∧ f 0 = a ∧ f 1 = b variables [ta: topological_space α] [tb: topological_space β] theorem connected_of_image {f : α → β} (cont: continuous f): connected ta → connected (subspace (range f) tb) := begin intros fcontinuous, show connected (subspace (range f) tb), unfold connected, by_contradiction H, rcases H with ⟨ U, V, openU, openV, union_univ, disjoint, nonemptyU, nonemptyV⟩, have containing : ∀ (W : set ↥(range f)), W.nonempty → (subspace (range f) tb).is_open W → ∃ (s: set β), is_open s ∧ nonempty s ∧ s ∩ (range f) = coe '' W ∧ is_open (f⁻¹' s) ∧ (f ⁻¹' s).nonempty , { intros W nonemptyW openW, rcases openW with ⟨ s, closeds, BintRange ⟩ , have nonemptys : nonempty ↥s, { have := nonempty_image_iff.mpr nonemptyW , rw ← BintRange at this, exact nonempty.to_subtype (nonempty_inter_iff_nonempty this).left, }, have openpre : is_open (f⁻¹' s), { apply cont, exact closeds, }, have nepre : (f ⁻¹' s).nonempty , { apply preimage_nonempty_of_inter_range, rw BintRange, apply set.nonempty.image, exact nonemptyW, }, exact ⟨ s, closeds, nonemptys, BintRange, openpre, nepre ⟩, }, rcases containing U nonemptyU openU with ⟨ U', openU', nonemptyU', U'inter, hu, neu_pre ⟩, rcases containing V nonemptyV openV with ⟨ V', openV', nonemptyV', V'inter, hv, nev_pre ⟩, have hinter : (f⁻¹' U') ∩ (f⁻¹' V') = ∅ := calc (f⁻¹' U') ∩ (f⁻¹' V') = f⁻¹' (U' ∩ V') : by rw preimage_inter ... = f⁻¹' ((U' ∩ range f) ∩ (V' ∩ range f)) : by simp [preimage_range_inter] ... = f⁻¹' ((coe '' U) ∩ (coe '' V)) : by simp [U'inter, V'inter] ... = f⁻¹' (coe '' (U ∩ V)) : by simp [image_inter, subtype.coe_injective] ... = f⁻¹' (coe '' ∅) : by rw disjoint ... = ∅ : by {rw image_empty, rw preimage_empty}, have hunion : (f⁻¹' U') ∪ (f⁻¹' V') = univ := calc (f⁻¹' U') ∪ (f⁻¹' V') = f⁻¹' (U' ∩ range f) ∪ f⁻¹' (V' ∩ range f) : by simp [preimage_range_inter] ... = f⁻¹' (coe '' U) ∪ f⁻¹' (coe '' V) : by rw [U'inter, V'inter] ... = f⁻¹' ( (coe '' U) ∪ (coe '' V) ) : by rw preimage_union ... = f⁻¹' (coe '' (U ∪ V)) : by rw image_union ... = f⁻¹' (coe '' univ) : by rw union_univ ... = f⁻¹' univ : by simp [subtype.coe_image_univ] ... = univ : by rw preimage_univ, show false, unfold connected at fcontinuous, push_neg at fcontinuous, exact fcontinuous (f⁻¹' U') (f⁻¹' V') hu hv hunion hinter neu_pre nev_pre, end def hausdorff (ts: topological_space α) := ∀ x y : α, x ≠ y → ∃ U V : set α, neighborhood U x ∧ neighborhood V y ∧ U ∩ V = ∅ end caracterization def sequence {α : Type*} := ℕ → α include topo def limit (seq: sequence) (l: α) := ∀ (U : set α), (neighborhood U l) → ∃ n0, ∀ n, n ≥ n0 → seq n ∈ U theorem unique_limit_of_hausdorff (haus: hausdorff topo) (seq: sequence) (l m : α) : (limit seq l) → (limit seq m) → l = m := begin intros ll lm, by_cases H: l = m, exact H, rcases haus l m H with ⟨ U, V, neiU, neiV, uvinter ⟩ , rcases ll U neiU with ⟨ n0u, hnu ⟩ , rcases lm V neiV with ⟨ n0v, hnv ⟩ , let n := max n0u n0v, have h1 : seq n ∈ U := hnu n (le_max_left _ _), have h2 : seq n ∈ V := hnv n (le_max_right _ _), have : seq n ∈ U ∩ V := mem_inter h1 h2, exfalso, rw uvinter at this, rw mem_empty_eq at this, exact this end lemma subset_hausdorff {s : set α} (haus: hausdorff topo) : hausdorff (subspace s topo) := begin intros x y nexy, have : ↑x ≠ ↑y := λ eq, nexy (set_coe.ext eq), rcases haus x y this with ⟨ U, V, nU, nV, intuv ⟩, rcases nU with ⟨ opu, open_opu, xin , opuinu ⟩ , rcases nV with ⟨ opv, open_opv, yin , opvinv ⟩ , use { a | ↑ a ∈ s ∩ opu }, use { a | ↑ a ∈ s ∩ opv }, have aux : ∀ (a b : set α), a ∩ b = b ∩ a ∩ b := λ a b, calc a ∩ b = a ∩ (b ∩ b) : by simp [inter_self] ... = (a ∩ b) ∩ b : by simp [inter_assoc] ... = (b ∩ a) ∩ b : by simp [inter_comm] ... = b ∩ a ∩ b : by simp, split, { use { a | ↑ a ∈ s ∩ opu }, split, { use opu, rw ← inter_of_subtype, split, exact open_opu, apply aux, }, { simp at *, exact xin, } }, { use { a | ↑ a ∈ s ∩ opv }, split, { use opv, rw ← inter_of_subtype, split, exact open_opv, apply aux, }, { simp at *, exact yin, }, simp, change {a : ↥s | ↑a ∈ opu ∩ opv } = ∅, have : opu ∩ opv = ∅ := by { have := inter_subset_inter opuinu opvinv, rw intuv at this, exact eq_empty_of_subset_empty this, }, simp [this], } end end topology
State Before: R✝ : Type u S : Type v a b : R✝ n m : ℕ inst✝¹ : Semiring R✝ p q r : R✝[X] i : ℤ R : Type u_1 inst✝ : Ring R ⊢ coeff (↑i) 0 = ↑i State After: no goals Tactic: cases i <;> simp
† Denotes player spent time with another team before joining Blue Jackets . Stats reflect time with the Blue Jackets only . ‡ Traded mid @-@ season
-- @@stderr -- dtrace: failed to compile script test/unittest/funcs/substr/err.D_PROTO_LEN.substr_missing_arg.d: [D_PROTO_LEN] line 16: substr( ) prototype mismatch: 0 args passed, at least 2 expected
{- Constant structure: _ ↦ A -} {-# OPTIONS --cubical --no-import-sorts --safe #-} module Cubical.Structures.Relational.Constant where open import Cubical.Foundations.Prelude open import Cubical.Foundations.Equiv open import Cubical.Foundations.HLevels open import Cubical.Foundations.Structure open import Cubical.Foundations.RelationalStructure open import Cubical.Structures.Constant private variable ℓ ℓ' : Level -- Structured relations module _ (A : hSet ℓ') where preservesSetsConstant : preservesSets {ℓ = ℓ} (ConstantStructure (A .fst)) preservesSetsConstant _ = A .snd ConstantRelStr : StrRel {ℓ = ℓ} (ConstantStructure (A .fst)) ℓ' ConstantRelStr _ a₀ a₁ = a₀ ≡ a₁ open SuitableStrRel constantSuitableRel : SuitableStrRel {ℓ = ℓ} (ConstantStructure (A .fst)) ConstantRelStr constantSuitableRel .quo _ _ _ = isContrSingl _ constantSuitableRel .symmetric _ = sym constantSuitableRel .transitive _ _ = _∙_ constantSuitableRel .prop _ = A .snd constantRelMatchesEquiv : StrRelMatchesEquiv {ℓ = ℓ} ConstantRelStr (ConstantEquivStr (A .fst)) constantRelMatchesEquiv _ _ _ = idEquiv _
theory T31 imports Main begin lemma "( (\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) & (\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, meet(y, z)) = meet(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) & (\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) & (\<forall> x::nat. invo(invo(x)) = x) ) \<longrightarrow> (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(meet(x, y), z) = meet(mult(x, z), mult(y, z))) " nitpick[card nat=4,timeout=86400] oops end
lemma open_neg_translation: fixes S :: "'a::real_normed_vector set" assumes "open S" shows "open((\<lambda>x. a - x) ` S)"
#### TELEPERFORMANCE (TP) - Prueba Técnica - Científico de Datos (Por: Andrés Felipe Escallón Portilla, 22-24 / Feb / 2021) # CASO DE CONSULTORIA ###### **Requerimiento:** Una de las operaciones de cobranzas de la compañía quiere generar estrategias diferenciadas para el proceso de gestión de recuperación de cartera de clientes de acuerdo con el riesgo de no pago de la primera factura. La estrategia se divide en 3 grupos de intervención: 1. Alto riesgo: Llamarlos al 5 día de mora. 2. Medio riesgo: Enviar mensaje de texto al 5 día de mora. 3. Bajo riesgo: Enviar mensaje de texto al día 15 de mora. Los costos por cada tipo de contacto son los siguientes: - Llamada asesor de cobranza 1700 pesos - Mensaje de texto 40 pesos #### **Instrucciones** 1. Muestre un análisis descriptivo y/o diagnóstico inicial de la información insumo para el modelo. 2. Construya un modelo estadístico que calcule la probabilidad de que un cliente no pague la primera factura. Explique por qué escogió las variables con las que va a trabajar y si debió hacer modificaciones de estas. 3. Defina los puntos de corte que determinen a que grupo de estrategia pertenece cada cliente. 4. Describa el perfil de los clientes con un alto riesgo de no pago. 5. ¿Qué sugerencias haría usted al equipo de cobranzas de acuerdo con el análisis de la información del modelo? 6. Explique el modelo y sustente su validez estadística, así como los puntos de corte, la cantidad de clientes que pertenecen a cada estrategia, los perfiles de riesgo y sus sugerencias y conclusiones. 7. Adjunte la base de datos con la probabilidad de riesgo de cada cliente. Todos los puntos anteriores deben evidenciarse en un notebook de Python o un Markdown de R que se deben compartir a través de GitHub. # Solución del Caso: Responderé a este caso en Español aclarando que lo ideal hubiese sido hacerlo en Inglés (algunos comentarios si están en Inglés). 1. **Muestre un análisis descriptivo y/o diagnóstico inicial de la información insumo para el modelo:** #### Análisis de Datos Exploratorio (EDA): ```python from google.colab import drive drive.mount('/content/drive') ``` Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount("/content/drive", force_remount=True). ```python !pip install -r '/content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt' ``` Requirement already satisfied: beautifulsoup4 in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 1)) (4.6.3) Requirement already satisfied: boto3 in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 2)) (1.17.14) Requirement already satisfied: branca in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 3)) (0.4.2) Requirement already satisfied: folium in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 4)) (0.8.3) Requirement already satisfied: geopandas in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 5)) (0.8.2) Requirement already satisfied: graphviz in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 6)) (0.10.1) Requirement already satisfied: ipython in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 7)) (5.5.0) Requirement already satisfied: ipywidgets in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (7.6.3) Requirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 9)) (3.2.2) Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 10)) (1.19.5) Requirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 11)) (1.1.5) Requirement already satisfied: pillow in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 12)) (7.0.0) Requirement already satisfied: pingouin in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 13)) (0.3.10) Requirement already satisfied: pydotplus in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 14)) (2.0.2) Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 15)) (2.23.0) Requirement already satisfied: s3transfer in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 16)) (0.3.4) Requirement already satisfied: scikit-learn in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 17)) (0.22.2.post1) Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 18)) (1.4.1) Requirement already satisfied: seaborn in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 19)) (0.11.1) Requirement already satisfied: shapely in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 20)) (1.7.1) Requirement already satisfied: statsmodels in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 21)) (0.10.2) Requirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 22)) (1.1.1) Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 23)) (4.41.1) Requirement already satisfied: urllib3 in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 24)) (1.24.3) Requirement already satisfied: wordcloud in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 25)) (1.5.0) Requirement already satisfied: xlrd in /usr/local/lib/python3.7/dist-packages (from -r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 26)) (1.1.0) Requirement already satisfied: botocore<1.21.0,>=1.20.14 in /usr/local/lib/python3.7/dist-packages (from boto3->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 2)) (1.20.14) Requirement already satisfied: jmespath<1.0.0,>=0.7.1 in /usr/local/lib/python3.7/dist-packages (from boto3->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 2)) (0.10.0) Requirement already satisfied: jinja2 in /usr/local/lib/python3.7/dist-packages (from branca->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 3)) (2.11.3) Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from folium->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 4)) (1.15.0) Requirement already satisfied: pyproj>=2.2.0 in /usr/local/lib/python3.7/dist-packages (from geopandas->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 5)) (3.0.0.post1) Requirement already satisfied: fiona in /usr/local/lib/python3.7/dist-packages (from geopandas->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 5)) (1.8.18) Requirement already satisfied: simplegeneric>0.8 in /usr/local/lib/python3.7/dist-packages (from ipython->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 7)) (0.8.1) Requirement already satisfied: pexpect; sys_platform != "win32" in /usr/local/lib/python3.7/dist-packages (from ipython->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 7)) (4.8.0) Requirement already satisfied: pygments in /usr/local/lib/python3.7/dist-packages (from ipython->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 7)) (2.6.1) Requirement already satisfied: setuptools>=18.5 in /usr/local/lib/python3.7/dist-packages (from ipython->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 7)) (53.0.0) Requirement already satisfied: prompt-toolkit<2.0.0,>=1.0.4 in /usr/local/lib/python3.7/dist-packages (from ipython->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 7)) (1.0.18) Requirement already satisfied: pickleshare in /usr/local/lib/python3.7/dist-packages (from ipython->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 7)) (0.7.5) Requirement already satisfied: traitlets>=4.2 in /usr/local/lib/python3.7/dist-packages (from ipython->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 7)) (4.3.3) Requirement already satisfied: decorator in /usr/local/lib/python3.7/dist-packages (from ipython->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 7)) (4.4.2) Requirement already satisfied: jupyterlab-widgets>=1.0.0; python_version >= "3.6" in /usr/local/lib/python3.7/dist-packages (from ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (1.0.0) Requirement already satisfied: nbformat>=4.2.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (5.1.2) Requirement already satisfied: widgetsnbextension~=3.5.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (3.5.1) Requirement already satisfied: ipykernel>=4.5.1 in /usr/local/lib/python3.7/dist-packages (from ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (4.10.1) Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 9)) (2.8.1) Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 9)) (0.10.0) Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 9)) (1.3.1) Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 9)) (2.4.7) Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 11)) (2018.9) Requirement already satisfied: outdated in /usr/local/lib/python3.7/dist-packages (from pingouin->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 13)) (0.2.0) Requirement already satisfied: tabulate in /usr/local/lib/python3.7/dist-packages (from pingouin->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 13)) (0.8.8) Requirement already satisfied: pandas-flavor>=0.1.2 in /usr/local/lib/python3.7/dist-packages (from pingouin->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 13)) (0.2.0) Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 15)) (3.0.4) Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 15)) (2.10) Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 15)) (2020.12.5) Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 17)) (1.0.1) Requirement already satisfied: patsy>=0.4.0 in /usr/local/lib/python3.7/dist-packages (from statsmodels->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 21)) (0.5.1) Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 22)) (1.2.1) Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/dist-packages (from jinja2->branca->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 3)) (1.1.1) Requirement already satisfied: cligj>=0.5 in /usr/local/lib/python3.7/dist-packages (from fiona->geopandas->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 5)) (0.7.1) Requirement already satisfied: attrs>=17 in /usr/local/lib/python3.7/dist-packages (from fiona->geopandas->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 5)) (20.3.0) Requirement already satisfied: click<8,>=4.0 in /usr/local/lib/python3.7/dist-packages (from fiona->geopandas->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 5)) (7.1.2) Requirement already satisfied: click-plugins>=1.0 in /usr/local/lib/python3.7/dist-packages (from fiona->geopandas->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 5)) (1.1.1) Requirement already satisfied: munch in /usr/local/lib/python3.7/dist-packages (from fiona->geopandas->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 5)) (2.5.0) Requirement already satisfied: ptyprocess>=0.5 in /usr/local/lib/python3.7/dist-packages (from pexpect; sys_platform != "win32"->ipython->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 7)) (0.7.0) Requirement already satisfied: wcwidth in /usr/local/lib/python3.7/dist-packages (from prompt-toolkit<2.0.0,>=1.0.4->ipython->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 7)) (0.2.5) Requirement already satisfied: ipython-genutils in /usr/local/lib/python3.7/dist-packages (from traitlets>=4.2->ipython->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 7)) (0.2.0) Requirement already satisfied: jsonschema!=2.5.0,>=2.4 in /usr/local/lib/python3.7/dist-packages (from nbformat>=4.2.0->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (2.6.0) Requirement already satisfied: jupyter-core in /usr/local/lib/python3.7/dist-packages (from nbformat>=4.2.0->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (4.7.1) Requirement already satisfied: notebook>=4.4.1 in /usr/local/lib/python3.7/dist-packages (from widgetsnbextension~=3.5.0->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (5.3.1) Requirement already satisfied: tornado>=4.0 in /usr/local/lib/python3.7/dist-packages (from ipykernel>=4.5.1->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (5.1.1) Requirement already satisfied: jupyter-client in /usr/local/lib/python3.7/dist-packages (from ipykernel>=4.5.1->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (5.3.5) Requirement already satisfied: littleutils in /usr/local/lib/python3.7/dist-packages (from outdated->pingouin->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 13)) (0.2.2) Requirement already satisfied: xarray in /usr/local/lib/python3.7/dist-packages (from pandas-flavor>=0.1.2->pingouin->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 13)) (0.15.1) Requirement already satisfied: Send2Trash in /usr/local/lib/python3.7/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (1.5.0) Requirement already satisfied: terminado>=0.8.1 in /usr/local/lib/python3.7/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (0.9.2) Requirement already satisfied: nbconvert in /usr/local/lib/python3.7/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (5.6.1) Requirement already satisfied: pyzmq>=13 in /usr/local/lib/python3.7/dist-packages (from jupyter-client->ipykernel>=4.5.1->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (22.0.3) Requirement already satisfied: bleach in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (3.3.0) Requirement already satisfied: testpath in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (0.4.4) Requirement already satisfied: pandocfilters>=1.4.1 in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (1.4.3) Requirement already satisfied: entrypoints>=0.2.2 in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (0.3) Requirement already satisfied: defusedxml in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (0.6.0) Requirement already satisfied: mistune<2,>=0.8.1 in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (0.8.4) Requirement already satisfied: webencodings in /usr/local/lib/python3.7/dist-packages (from bleach->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (0.5.1) Requirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from bleach->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets->-r /content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/requirements.txt (line 8)) (20.9) ```python # Importing all the required packages import pandas as pd # The gold standard of Python data analysis, to create and manipulate tables of data import numpy as np # The Python module for processing arrays which/Pandas is based on import seaborn as sns; sns.set() # A package to make Matplotlib visualizations more aesthetic import branca import geopandas import matplotlib.pyplot as plt # The gold standard of Python data visualization, but can be complex to use from matplotlib import cm from matplotlib.colors import ListedColormap, LinearSegmentedColormap from matplotlib.patches import Patch from matplotlib.widgets import Slider, Button, RadioButtons import statsmodels.api as sm import statsmodels.formula.api as sfm from statsmodels.formula.api import ols import scipy from scipy import stats from scipy import interp from scipy.optimize import fsolve from scipy.stats import chi2_contingency, ttest_ind, norm # A module for Python machine learning--we'll stick to T-Tests here import sklearn from sklearn.metrics import roc_curve, auc from sklearn.model_selection import StratifiedKFold from sklearn.cluster import KMeans from sklearn.preprocessing import MinMaxScaler, MaxAbsScaler, RobustScaler, StandardScaler from sklearn.tree import export_graphviz from sklearn import tree from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import roc_curve, auc, accuracy_score from sklearn.model_selection import StratifiedKFold, train_test_split from statsmodels.formula.api import ols from IPython.display import display from IPython.display import display_html from IPython.display import Image, SVG import folium # package for making maps, please make sure to use a version older than 1.0.0. from folium.plugins import TimeSliderChoropleth # from time_slider_choropleth import TimeSliderChoropleth import json import requests from bs4 import BeautifulSoup import os import pydotplus from io import StringIO from sympy import var, plot_implicit, Eq from graphviz import Source from wordcloud import WordCloud # A package that will allow us to make a wordcloud # when executing, the plot will be done %matplotlib inline plt.style.use('ggplot') plt.rcParams["figure.figsize"] = (8,5) import warnings warnings.filterwarnings('ignore') # ignore log(0) and divide by 0 warning np.seterr(divide='ignore'); ``` ```python #leyendo los archivos de la base de datos (guardados previamente como csv) y asignándolos a dataframes: df_var=pd.read_csv('/content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/data/base_de_datos_prueba_tecnica_csv_vars.csv') df=pd.read_csv('/content/drive/MyDrive/Teleperformance_PruebaTecnica_CientificoDatos/data/base_de_datos_prueba_tecnica_csv_db.csv') ``` ```python #visualizando los dataframes: #Para una base de datos, las variables y su descripción es fundamental df_var ``` <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>VARIABLE</th> <th>DESCRIPCIÓN</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>REGIONAL</td> <td>regional de instalación del servicio</td> </tr> <tr> <th>1</th> <td>DEPARTAMENTO</td> <td>Departamento de instalación del servicio</td> </tr> <tr> <th>2</th> <td>TECNOL</td> <td>Tipo de tecnología del servicio</td> </tr> <tr> <th>3</th> <td>GERENCIA</td> <td>Gerencia de venta del servicio</td> </tr> <tr> <th>4</th> <td>CANAL_HOMOLOGADO_MILLICON</td> <td>Canal de venta del servicio</td> </tr> <tr> <th>5</th> <td>tipo_fuerza_venta</td> <td>Tipo de fuerza o equipo que realizó la venta</td> </tr> <tr> <th>6</th> <td>estrato</td> <td>Estrato donde fue instalado el servicio</td> </tr> <tr> <th>7</th> <td>antiguedad_meses</td> <td>Antigüedad del cliente al momento de solicitar...</td> </tr> <tr> <th>8</th> <td>productos</td> <td>Productos solicitados TV= televisión, TO=Telef...</td> </tr> <tr> <th>9</th> <td>portafolio</td> <td>cantidad de productos adquiridos</td> </tr> <tr> <th>10</th> <td>no_serv_tecnicos</td> <td>Servicios técnicos solicitados en los últimos ...</td> </tr> <tr> <th>11</th> <td>fallo</td> <td>Tipo de fallo por elq ue solicitó el servicio ...</td> </tr> <tr> <th>12</th> <td>asesoria_factura</td> <td>Si la variable asume el valor de 1 es que el c...</td> </tr> <tr> <th>13</th> <td>pedidos_peticiones</td> <td>Si la variable asume el valor de 1 es que el c...</td> </tr> <tr> <th>14</th> <td>reagendamiento</td> <td>Si la variable asume el valor de 1 es que el c...</td> </tr> <tr> <th>15</th> <td>asesoria_servicios</td> <td>Si la variable asume el valor de 1 es que el c...</td> </tr> <tr> <th>16</th> <td>retencion</td> <td>Si la variable asume el valor de 1 es que el c...</td> </tr> <tr> <th>17</th> <td>Otras</td> <td>Si la variable asume el valor de 1 es que el c...</td> </tr> <tr> <th>18</th> <td>quejas_fraude</td> <td>El cliente presentó una queja de posible fraud...</td> </tr> <tr> <th>19</th> <td>traslado</td> <td>El cliente solicitó un traslado del servicio</td> </tr> <tr> <th>20</th> <td>Incumplimiento_pago</td> <td>Variable objetivo, el 1 indica que el cliente ...</td> </tr> <tr> <th>21</th> <td>cliente_id</td> <td>Identificador del cliente</td> </tr> </tbody> </table> </div> ```python #visualizando la info completa de la DESCRIPCIÓN: descripcion=[] for row in range(len(df_var)): descripcion.append(df_var['DESCRIPCIÓN'][row]) descripcion ``` ['regional de instalación del servicio', 'Departamento de instalación del servicio', 'Tipo de tecnología del servicio', 'Gerencia de venta del servicio', 'Canal de venta del servicio', 'Tipo de fuerza o equipo que realizó la venta', 'Estrato donde fue instalado el servicio', 'Antigüedad del cliente al momento de solicitar el servicio', 'Productos solicitados TV= televisión, TO=Telefonía, BA = Internet', 'cantidad de productos adquiridos', 'Servicios técnicos solicitados en los últimos 3 meses', 'Tipo de fallo por elq ue solicitó el servicio técnico', 'Si la variable asume el valor de 1 es que el cliente llamo a pedir una asesoría en factura', 'Si la variable asume el valor de 1 es que el cliente llamo a hacer una petición queja o reclamo', 'Si la variable asume el valor de 1 es que el cliente llamo a reagendar un servicio', 'Si la variable asume el valor de 1 es que el cliente llamo a pedir una asesoría en el uso del servicio', 'Si la variable asume el valor de 1 es que el cliente llamo a cancelar voluntariamente el servicio', 'Si la variable asume el valor de 1 es que el cliente llamo por otros motivos', 'El cliente presentó una queja de posible fraude por suplantación de identidad', 'El cliente solicitó un traslado del servicio', 'Variable objetivo, el 1 indica que el cliente no pago la primera factura', 'Identificador del cliente'] ```python #Esta es la base de datos como tal con la cual se va a trabajar: pd.options.display.max_columns = None # para visualizar todas las columnas (variables) de interés df ``` <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>REGIONAL</th> <th>DEPARTAMENTO</th> <th>TECNOL</th> <th>GERENCIA</th> <th>CANAL_HOMOLOGADO_MILLICON</th> <th>tipo_fuerza_venta</th> <th>estrato</th> <th>antiguedad_meses</th> <th>productos</th> <th>portafolio</th> <th>no_serv_tecnicos</th> <th>fallo</th> <th>asesoria_factura</th> <th>pedidos_peticiones</th> <th>reagendamiento</th> <th>asesoria_servicios</th> <th>retencion</th> <th>Otras</th> <th>quejas_fraude</th> <th>traslado</th> <th>Incumplimiento_pago</th> <th>cliente_id</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>COSTA</td> <td>MAGDALENA</td> <td>HFC</td> <td>CONTACT</td> <td>SAC</td> <td>INDIRECTA</td> <td>3</td> <td>19.0</td> <td>TV+BA</td> <td>Duo</td> <td>1.0</td> <td>No funciona línea telefónica</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1004369760</td> </tr> <tr> <th>1</th> <td>COSTA</td> <td>MAGDALENA</td> <td>HFC</td> <td>CONTACT</td> <td>SAC</td> <td>INDIRECTA</td> <td>3</td> <td>19.0</td> <td>TV+BA</td> <td>Duo</td> <td>1.0</td> <td>No funciona línea telefónica</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1004369760</td> </tr> <tr> <th>2</th> <td>NOROCCIDENTE</td> <td>ANTIOQUIA</td> <td>HFC</td> <td>CONTACT</td> <td>SAC</td> <td>INDIRECTA</td> <td>1</td> <td>1.0</td> <td>TV</td> <td>Individual</td> <td>1.0</td> <td>No navega</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1004371304</td> </tr> <tr> <th>3</th> <td>COSTA</td> <td>MAGDALENA</td> <td>HFC</td> <td>CONTACT</td> <td>IN BOUND</td> <td>INDIRECTA</td> <td>3</td> <td>7.0</td> <td>TO+TV+BA</td> <td>Trio</td> <td>NaN</td> <td>NaN</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> <td>1004382867</td> </tr> <tr> <th>4</th> <td>COSTA</td> <td>MAGDALENA</td> <td>HFC</td> <td>CONTACT</td> <td>IN BOUND</td> <td>INDIRECTA</td> <td>3</td> <td>7.0</td> <td>TO+TV+BA</td> <td>Trio</td> <td>NaN</td> <td>NaN</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> <td>1004382867</td> </tr> <tr> <th>...</th> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> </tr> <tr> <th>19937</th> <td>NOROCCIDENTE</td> <td>ANTIOQUIA</td> <td>REDCO</td> <td>CONTACT</td> <td>IN BOUND</td> <td>INDIRECTA</td> <td>2</td> <td>NaN</td> <td>TO+BA</td> <td>Duo</td> <td>NaN</td> <td>NaN</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> <td>98589757</td> </tr> <tr> <th>19938</th> <td>NOROCCIDENTE</td> <td>ANTIOQUIA</td> <td>REDCO</td> <td>CONTACT</td> <td>IN BOUND</td> <td>INDIRECTA</td> <td>2</td> <td>NaN</td> <td>TO+BA</td> <td>Duo</td> <td>NaN</td> <td>NaN</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> <td>98589757</td> </tr> <tr> <th>19939</th> <td>NOROCCIDENTE</td> <td>ANTIOQUIA</td> <td>REDCO</td> <td>TIENDAS</td> <td>TIENDAS</td> <td>INDIRECTA</td> <td>2</td> <td>89.0</td> <td>BA</td> <td>Individual</td> <td>1.0</td> <td>Sin señal</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>98590638</td> </tr> <tr> <th>19940</th> <td>NOROCCIDENTE</td> <td>ANTIOQUIA</td> <td>HFC</td> <td>CONTACT</td> <td>SAC</td> <td>INDIRECTA</td> <td>2</td> <td>36.0</td> <td>TV</td> <td>Individual</td> <td>NaN</td> <td>NaN</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>98591843</td> </tr> <tr> <th>19941</th> <td>NOROCCIDENTE</td> <td>ANTIOQUIA</td> <td>REDCO</td> <td>CONTACT</td> <td>OUT BOUND</td> <td>INDIRECTA</td> <td>2</td> <td>203.0</td> <td>TV</td> <td>Individual</td> <td>NaN</td> <td>NaN</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>98594003</td> </tr> </tbody> </table> <p>19942 rows × 22 columns</p> </div> ```python #Panorama general de los datos: df.shape # (num_filas, num_cols) ``` (19942, 22) ```python list(df.columns) ``` ['REGIONAL', 'DEPARTAMENTO', 'TECNOL', 'GERENCIA', 'CANAL_HOMOLOGADO_MILLICON', 'tipo_fuerza_venta', 'estrato', 'antiguedad_meses', 'productos', 'portafolio', 'no_serv_tecnicos', 'fallo', 'asesoria_factura', 'pedidos_peticiones', 'reagendamiento', 'asesoria_servicios', 'retencion', 'Otras', 'quejas_fraude', 'traslado', 'Incumplimiento_pago', 'cliente_id'] ¡Efectivamente son 22 columnas (variables) que ya se han mostrado anteriormente con su descripción, recordando que la **Variable objetivo** es `Incumplimiento_pago` (donde el 1 indica que el cliente no pago la primera factura)! ```python # Data types and amount of no-null values in dataset df.info() ``` <class 'pandas.core.frame.DataFrame'> RangeIndex: 19942 entries, 0 to 19941 Data columns (total 22 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 REGIONAL 19942 non-null object 1 DEPARTAMENTO 19942 non-null object 2 TECNOL 19942 non-null object 3 GERENCIA 19942 non-null object 4 CANAL_HOMOLOGADO_MILLICON 19942 non-null object 5 tipo_fuerza_venta 19942 non-null object 6 estrato 19942 non-null object 7 antiguedad_meses 18264 non-null float64 8 productos 19942 non-null object 9 portafolio 19942 non-null object 10 no_serv_tecnicos 6909 non-null float64 11 fallo 6909 non-null object 12 asesoria_factura 19942 non-null int64 13 pedidos_peticiones 19942 non-null int64 14 reagendamiento 19942 non-null int64 15 asesoria_servicios 19942 non-null int64 16 retencion 19942 non-null int64 17 Otras 19942 non-null int64 18 quejas_fraude 19942 non-null int64 19 traslado 19942 non-null int64 20 Incumplimiento_pago 19942 non-null int64 21 cliente_id 19942 non-null int64 dtypes: float64(2), int64(10), object(10) memory usage: 3.3+ MB Los registros de las variables numericas como `antiguedad_meses` y `no_serv_tecnicos` que no tienen información deben ser reemplazados por NaN **(The most prudent option which will not alter subsequent summary statistics calculations and not skew the distribution of the non-missing data would be to replace all missing values with a standard NaN)** Sin embargo, los registros sin información de la variable categórica `fallo` pueden reemplazarse por SE ("Sin Especificar"), similarmente a como lo tiene ya establecido la variable categórica `estrato` ```python # Another way to see null values per column df.isnull().sum() ``` REGIONAL 0 DEPARTAMENTO 0 TECNOL 0 GERENCIA 0 CANAL_HOMOLOGADO_MILLICON 0 tipo_fuerza_venta 0 estrato 0 antiguedad_meses 1678 productos 0 portafolio 0 no_serv_tecnicos 13033 fallo 13033 asesoria_factura 0 pedidos_peticiones 0 reagendamiento 0 asesoria_servicios 0 retencion 0 Otras 0 quejas_fraude 0 traslado 0 Incumplimiento_pago 0 cliente_id 0 dtype: int64 ```python # Information about numerical columns (descriptive statistics) df.describe() ``` <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>antiguedad_meses</th> <th>no_serv_tecnicos</th> <th>asesoria_factura</th> <th>pedidos_peticiones</th> <th>reagendamiento</th> <th>asesoria_servicios</th> <th>retencion</th> <th>Otras</th> <th>quejas_fraude</th> <th>traslado</th> <th>Incumplimiento_pago</th> <th>cliente_id</th> </tr> </thead> <tbody> <tr> <th>count</th> <td>18264.000000</td> <td>6909.0</td> <td>19942.000000</td> <td>19942.00000</td> <td>19942.000000</td> <td>19942.000000</td> <td>19942.000000</td> <td>19942.000000</td> <td>19942.000000</td> <td>19942.000000</td> <td>19942.000000</td> <td>1.994200e+04</td> </tr> <tr> <th>mean</th> <td>43.136060</td> <td>1.0</td> <td>0.056564</td> <td>0.05185</td> <td>0.022515</td> <td>0.025975</td> <td>0.013690</td> <td>0.006168</td> <td>0.025524</td> <td>0.048240</td> <td>0.143165</td> <td>4.124402e+08</td> </tr> <tr> <th>std</th> <td>60.379264</td> <td>0.0</td> <td>0.231013</td> <td>0.22173</td> <td>0.148356</td> <td>0.159066</td> <td>0.116202</td> <td>0.078295</td> <td>0.157714</td> <td>0.214278</td> <td>0.350250</td> <td>4.993182e+08</td> </tr> <tr> <th>min</th> <td>0.000000</td> <td>1.0</td> <td>0.000000</td> <td>0.00000</td> <td>0.000000</td> <td>0.000000</td> <td>0.000000</td> <td>0.000000</td> <td>0.000000</td> <td>0.000000</td> <td>0.000000</td> <td>3.978700e+04</td> </tr> <tr> <th>25%</th> <td>4.000000</td> <td>1.0</td> <td>0.000000</td> <td>0.00000</td> <td>0.000000</td> <td>0.000000</td> <td>0.000000</td> <td>0.000000</td> <td>0.000000</td> <td>0.000000</td> <td>0.000000</td> <td>3.225958e+07</td> </tr> <tr> <th>50%</th> <td>16.000000</td> <td>1.0</td> <td>0.000000</td> <td>0.00000</td> <td>0.000000</td> <td>0.000000</td> <td>0.000000</td> <td>0.000000</td> <td>0.000000</td> <td>0.000000</td> <td>0.000000</td> <td>6.697511e+07</td> </tr> <tr> <th>75%</th> <td>52.000000</td> <td>1.0</td> <td>0.000000</td> <td>0.00000</td> <td>0.000000</td> <td>0.000000</td> <td>0.000000</td> <td>0.000000</td> <td>0.000000</td> <td>0.000000</td> <td>0.000000</td> <td>1.036623e+09</td> </tr> <tr> <th>max</th> <td>337.000000</td> <td>1.0</td> <td>1.000000</td> <td>1.00000</td> <td>1.000000</td> <td>1.000000</td> <td>1.000000</td> <td>1.000000</td> <td>1.000000</td> <td>1.000000</td> <td>1.000000</td> <td>8.160082e+09</td> </tr> </tbody> </table> </div> De la anterior tabla se concluye que **aproximadamente el 14% (exactamnente 14.3165%)** de los clientes (**aprox 2855 de 19942 clientes en total**) está incumpliendo el pago (no ha pagado la primera factura) ```python 0.143165*19942 ``` 2854.9964299999997 ```python # Information about categorical columns df.describe(include = ['O']) ``` <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>REGIONAL</th> <th>DEPARTAMENTO</th> <th>TECNOL</th> <th>GERENCIA</th> <th>CANAL_HOMOLOGADO_MILLICON</th> <th>tipo_fuerza_venta</th> <th>estrato</th> <th>productos</th> <th>portafolio</th> <th>fallo</th> </tr> </thead> <tbody> <tr> <th>count</th> <td>19942</td> <td>19942</td> <td>19942</td> <td>19942</td> <td>19942</td> <td>19942</td> <td>19942</td> <td>19942</td> <td>19942</td> <td>6909</td> </tr> <tr> <th>unique</th> <td>6</td> <td>22</td> <td>4</td> <td>6</td> <td>11</td> <td>2</td> <td>7</td> <td>7</td> <td>3</td> <td>20</td> </tr> <tr> <th>top</th> <td>NOROCCIDENTE</td> <td>ANTIOQUIA</td> <td>HFC</td> <td>CONTACT</td> <td>SAC</td> <td>INDIRECTA</td> <td>2</td> <td>TO+TV+BA</td> <td>Trio</td> <td>No navega</td> </tr> <tr> <th>freq</th> <td>11640</td> <td>11655</td> <td>15628</td> <td>10075</td> <td>4768</td> <td>18893</td> <td>6413</td> <td>7933</td> <td>7933</td> <td>2845</td> </tr> </tbody> </table> </div> ```python df['fallo'].value_counts() #SE= Sin Especificar ``` No navega 2845 Sin señal 1307 Servicio intermitente 1238 No funciona línea telefónica 573 Mala calidad en la imagen 206 Navegacion Lenta 184 Problemas Control Remoto 160 Falla Masiva 76 Línea con ruido 70 Problemas wifi 67 Solicitud configuracion tecni 63 Fallas en audio/subtitulos 30 Problemas paquetes adicionales 23 No salen llamadas a X destino 20 Problemas con el portal 16 Problemas Servicios Especiales 9 Ingresa llamada de otra línea 9 Mala calidad en la voz 5 Problemas de correo remoto 5 Retención Clientes 3 Name: fallo, dtype: int64 El fallo reportado mas común es "No navega". ```python #Contemos por ejemplo los fallos asociados a un tipo de tecnología por departamento: df.groupby(["TECNOL","fallo","DEPARTAMENTO"])["DEPARTAMENTO"].count().reset_index(name="count").sort_values(by="count", ascending = False).reset_index(drop=True) ``` <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>TECNOL</th> <th>fallo</th> <th>DEPARTAMENTO</th> <th>count</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>HFC</td> <td>No navega</td> <td>ANTIOQUIA</td> <td>1222</td> </tr> <tr> <th>1</th> <td>HFC</td> <td>Sin señal</td> <td>ANTIOQUIA</td> <td>694</td> </tr> <tr> <th>2</th> <td>REDCO</td> <td>No navega</td> <td>ANTIOQUIA</td> <td>625</td> </tr> <tr> <th>3</th> <td>HFC</td> <td>Servicio intermitente</td> <td>ANTIOQUIA</td> <td>569</td> </tr> <tr> <th>4</th> <td>HFC</td> <td>No funciona línea telefónica</td> <td>ANTIOQUIA</td> <td>353</td> </tr> <tr> <th>...</th> <td>...</td> <td>...</td> <td>...</td> <td>...</td> </tr> <tr> <th>184</th> <td>HFC</td> <td>Problemas con el portal</td> <td>SANTANDER</td> <td>1</td> </tr> <tr> <th>185</th> <td>GPON</td> <td>Línea con ruido</td> <td>ANTIOQUIA</td> <td>1</td> </tr> <tr> <th>186</th> <td>HFC</td> <td>Problemas Control Remoto</td> <td>ATLANTICO</td> <td>1</td> </tr> <tr> <th>187</th> <td>GPON</td> <td>Falla Masiva</td> <td>ANTIOQUIA</td> <td>1</td> </tr> <tr> <th>188</th> <td>REDCO</td> <td>Mala calidad en la voz</td> <td>ANTIOQUIA</td> <td>1</td> </tr> </tbody> </table> <p>189 rows × 4 columns</p> </div> ```python #Generemos una tabla de contingencia entre las variables categoricas DEPARTAMENTO y fallo (permite una visualización de la distribución geográfica de los fallos): pd.crosstab(df["DEPARTAMENTO"],df["fallo"]) ``` <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>fallo</th> <th>Falla Masiva</th> <th>Fallas en audio/subtitulos</th> <th>Ingresa llamada de otra línea</th> <th>Línea con ruido</th> <th>Mala calidad en la imagen</th> <th>Mala calidad en la voz</th> <th>Navegacion Lenta</th> <th>No funciona línea telefónica</th> <th>No navega</th> <th>No salen llamadas a X destino</th> <th>Problemas Control Remoto</th> <th>Problemas Servicios Especiales</th> <th>Problemas con el portal</th> <th>Problemas de correo remoto</th> <th>Problemas paquetes adicionales</th> <th>Problemas wifi</th> <th>Retención Clientes</th> <th>Servicio intermitente</th> <th>Sin señal</th> <th>Solicitud configuracion tecni</th> </tr> <tr> <th>DEPARTAMENTO</th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <th>ANTIOQUIA</th> <td>44</td> <td>14</td> <td>9</td> <td>56</td> <td>141</td> <td>5</td> <td>124</td> <td>476</td> <td>1862</td> <td>9</td> <td>123</td> <td>7</td> <td>6</td> <td>0</td> <td>16</td> <td>35</td> <td>3</td> <td>800</td> <td>935</td> <td>49</td> </tr> <tr> <th>ATLANTICO</th> <td>3</td> <td>3</td> <td>0</td> <td>1</td> <td>1</td> <td>0</td> <td>5</td> <td>1</td> <td>60</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>2</td> <td>0</td> <td>19</td> <td>16</td> <td>0</td> </tr> <tr> <th>ATLÁNTICO</th> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>3</td> <td>0</td> <td>0</td> <td>7</td> <td>46</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>2</td> <td>0</td> <td>24</td> <td>13</td> <td>1</td> </tr> <tr> <th>BOLIVAR</th> <td>6</td> <td>2</td> <td>0</td> <td>2</td> <td>6</td> <td>0</td> <td>4</td> <td>17</td> <td>129</td> <td>2</td> <td>2</td> <td>0</td> <td>0</td> <td>2</td> <td>0</td> <td>3</td> <td>0</td> <td>48</td> <td>53</td> <td>5</td> </tr> <tr> <th>CALDAS</th> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <th>CAUCA</th> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>5</td> <td>0</td> <td>0</td> <td>0</td> <td>6</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>3</td> <td>0</td> </tr> <tr> <th>CESAR</th> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>3</td> <td>0</td> <td>6</td> <td>3</td> <td>31</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>2</td> <td>0</td> <td>9</td> <td>18</td> <td>0</td> </tr> <tr> <th>CORDOBA</th> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> <td>9</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>5</td> <td>7</td> <td>0</td> </tr> <tr> <th>CUNDINAMARCA</th> <td>12</td> <td>0</td> <td>0</td> <td>8</td> <td>13</td> <td>0</td> <td>11</td> <td>24</td> <td>333</td> <td>2</td> <td>10</td> <td>0</td> <td>4</td> <td>0</td> <td>3</td> <td>5</td> <td>0</td> <td>125</td> <td>102</td> <td>6</td> </tr> <tr> <th>HUILA</th> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> </tr> <tr> <th>LA GUAJIRA</th> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> </tr> <tr> <th>MAGDALENA</th> <td>0</td> <td>2</td> <td>0</td> <td>0</td> <td>4</td> <td>0</td> <td>3</td> <td>2</td> <td>14</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>17</td> <td>16</td> <td>0</td> </tr> <tr> <th>META</th> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>3</td> <td>6</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>3</td> <td>0</td> <td>3</td> <td>7</td> <td>0</td> </tr> <tr> <th>NORTE DE SANTANDER</th> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>2</td> <td>0</td> <td>9</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>5</td> <td>10</td> <td>0</td> </tr> <tr> <th>RISARALDA</th> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> <td>2</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <th>SANTANDER</th> <td>7</td> <td>5</td> <td>0</td> <td>3</td> <td>14</td> <td>0</td> <td>7</td> <td>17</td> <td>168</td> <td>2</td> <td>11</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>5</td> <td>0</td> <td>85</td> <td>49</td> <td>2</td> </tr> <tr> <th>SUCRE</th> <td>0</td> <td>2</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>3</td> <td>11</td> <td>3</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>2</td> <td>2</td> <td>0</td> </tr> <tr> <th>TOLIMA</th> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> </tr> <tr> <th>VALLE DEL CAUCA</th> <td>3</td> <td>2</td> <td>0</td> <td>0</td> <td>20</td> <td>0</td> <td>16</td> <td>17</td> <td>166</td> <td>2</td> <td>7</td> <td>2</td> <td>4</td> <td>3</td> <td>3</td> <td>10</td> <td>0</td> <td>96</td> <td>73</td> <td>0</td> </tr> </tbody> </table> </div> ```python #numerical variables num_vars=list(df.describe().columns) num_vars ``` ['antiguedad_meses', 'no_serv_tecnicos', 'asesoria_factura', 'pedidos_peticiones', 'reagendamiento', 'asesoria_servicios', 'retencion', 'Otras', 'quejas_fraude', 'traslado', 'Incumplimiento_pago', 'cliente_id'] ```python #de las num_vars hay que remover cliente_id que no aporta al análisis pues es solo un dato para etiquetar a cada cliente con un número identificador: num_vars=num_vars.copy()[:-1] print(num_vars) ``` ['antiguedad_meses', 'no_serv_tecnicos', 'asesoria_factura', 'pedidos_peticiones', 'reagendamiento', 'asesoria_servicios', 'retencion', 'Otras', 'quejas_fraude', 'traslado', 'Incumplimiento_pago'] ```python #categorical variables cat_vars=list(df.describe(include = ['O']).columns) cat_vars ``` ['REGIONAL', 'DEPARTAMENTO', 'TECNOL', 'GERENCIA', 'CANAL_HOMOLOGADO_MILLICON', 'tipo_fuerza_venta', 'estrato', 'productos', 'portafolio', 'fallo'] ```python # Unique values per column excluding null df.nunique() ``` REGIONAL 6 DEPARTAMENTO 22 TECNOL 4 GERENCIA 6 CANAL_HOMOLOGADO_MILLICON 11 tipo_fuerza_venta 2 estrato 7 antiguedad_meses 232 productos 7 portafolio 3 no_serv_tecnicos 1 fallo 20 asesoria_factura 2 pedidos_peticiones 2 reagendamiento 2 asesoria_servicios 2 retencion 2 Otras 2 quejas_fraude 2 traslado 2 Incumplimiento_pago 2 cliente_id 12106 dtype: int64 ```python # Unique values per column including null df.nunique(dropna=False) ``` REGIONAL 6 DEPARTAMENTO 22 TECNOL 4 GERENCIA 6 CANAL_HOMOLOGADO_MILLICON 11 tipo_fuerza_venta 2 estrato 7 antiguedad_meses 233 productos 7 portafolio 3 no_serv_tecnicos 2 fallo 21 asesoria_factura 2 pedidos_peticiones 2 reagendamiento 2 asesoria_servicios 2 retencion 2 Otras 2 quejas_fraude 2 traslado 2 Incumplimiento_pago 2 cliente_id 12106 dtype: int64 ### Generando algunas graficas estadísticas de algunas variables independientes (X) frente a la variable objetico o de interés (Y): ```python #plotting the histogram of the numerical variables: sns.histplot(df[num_vars[10]]) plt.title('Histograma de la variable objetivo (Inclumplimiento_pago: binaria 0 no, 1 si)') plt.show() ``` Con el anterior histograma se comprueba que el **14.3165% de los clientes (aprox 2855 de 19942 clientes en total** está incumpliendo el pago (no ha pagado la primera factura) Now that we have looked at the variables of interest in isolation, it makes sense to look at them in relation to `Inclumplimiento_pago`: ```python #Inspecting Inclumplimiento_pago against another variable of interest (e.g antiguedad_meses): plt.figure(figsize=(50, 10)) sns.boxplot(x = num_vars[0], y=num_vars[10], data = df) title_string = "Boxplot of " + num_vars[10] + " vs. " + num_vars[0] plt.ylabel(num_vars[10]) plt.title(title_string) ``` ```python # We can look out for trends using a line plot plt.figure(figsize=(15, 8)) ax = sns.lineplot( x=num_vars[0], y=num_vars[10], data=df, ) ``` ```python plt.figure(figsize=(15, 8)) ax = sns.lineplot( x=cat_vars[6], y=num_vars[10], data=df, ) ``` ```python plt.figure(figsize=(15, 8)) ax = sns.lineplot( x=cat_vars[8], y=num_vars[10], data=df, ) ``` ## Pre-processing our data Now that we have an idea of what our dataset consists of, let's transform it so that we can display phase. The types of activities we may engage in during **pre-processing** include: 1. **Deleting columns** 2. **Enriching (or Transforming)** a data set, adding newly calculated columns in the indices 3. **Filtering** a subset of the rows or columns of a dataset according to some criteria 4. **Indexing** a dataset 5. **Aggregating** data 6. **Sorting** the rows of a data set according to some criteria 7. **Merging** the data 8. **Pivoting** so that data that was originally laid out vertically is laid out horizontally (increasing the number of columns) or vice versa (increasing the number of rows) among others. ## What is data transformation? Many times in real life, you will be working with imperfect datasets with quality issues. **Data transformation** is the process of modifying a dataset in appropriate ways in order to eliminate these quality issues. Some of these activities include: - Splitting columns - Converting dates to `datetime` objects, which are far more easily manipulable using `pandas` libraries - Encoding categorical variables - Dealing with and replacing null or missing values - Creating unique identifiers The `pandas` library has many functions which can help with this task. In addition, you will also be using some other standard libraries like `String`, `base64`, and `sklearn`. ```python #Let's create a copy of our dataframe before we start changing it so we can refer back to the original values if necessary. df_orig = df.copy() df_orig.head(1) ``` <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>REGIONAL</th> <th>DEPARTAMENTO</th> <th>TECNOL</th> <th>GERENCIA</th> <th>CANAL_HOMOLOGADO_MILLICON</th> <th>tipo_fuerza_venta</th> <th>estrato</th> <th>antiguedad_meses</th> <th>productos</th> <th>portafolio</th> <th>no_serv_tecnicos</th> <th>fallo</th> <th>asesoria_factura</th> <th>pedidos_peticiones</th> <th>reagendamiento</th> <th>asesoria_servicios</th> <th>retencion</th> <th>Otras</th> <th>quejas_fraude</th> <th>traslado</th> <th>Incumplimiento_pago</th> <th>cliente_id</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>COSTA</td> <td>MAGDALENA</td> <td>HFC</td> <td>CONTACT</td> <td>SAC</td> <td>INDIRECTA</td> <td>3</td> <td>19.0</td> <td>TV+BA</td> <td>Duo</td> <td>1.0</td> <td>No funciona línea telefónica</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1004369760</td> </tr> </tbody> </table> </div> Los registros de las variables numericas como `antiguedad_meses` y `no_serv_tecnicos` que no tienen información deben ser reemplazados por NaN **(The most prudent option which will not alter subsequent summary statistics calculations and not skew the distribution of the non-missing data would be to replace all missing values with a standard NaN)** Sin embargo, los registros sin información de la variable categórica `fallo` pueden reemplazarse por SE ("Sin Especificar"), similarmente a como lo tiene ya establecido la variable categórica `estrato` ```python df['antiguedad_meses'].fillna(np.nan, inplace=True) ``` ```python df['no_serv_tecnicos'].fillna(np.nan, inplace=True) ``` ```python df['fallo'].fillna('SE', inplace=True) #SE=Sin Especificar (similar a cuando no hay info de Estrato) ``` ```python df.isnull().sum() ``` REGIONAL 0 DEPARTAMENTO 0 TECNOL 0 GERENCIA 0 CANAL_HOMOLOGADO_MILLICON 0 tipo_fuerza_venta 0 estrato 0 antiguedad_meses 1678 productos 0 portafolio 0 no_serv_tecnicos 13033 fallo 0 asesoria_factura 0 pedidos_peticiones 0 reagendamiento 0 asesoria_servicios 0 retencion 0 Otras 0 quejas_fraude 0 traslado 0 Incumplimiento_pago 0 cliente_id 0 dtype: int64 Una vez finalizado el tratamiento de valores faltantes y/o nulos, procedemos con los siguientes pasos del EDA: Exploremos las **correlaciones** de las variables numericas con la variable objetivo (num_vars[10]=`Incumplimiento_pago`): ```python # Create a correlation matrix corr = df[num_vars].corr() pos_cor = corr[num_vars[10]] >0 neg_cor = corr[num_vars[10]] <0 corr[num_vars[10]][pos_cor].sort_values(ascending = False) #This prints out the coefficients that are positively correlated with Incumplimiento_pago: ``` Incumplimiento_pago 1.000000 Otras 0.011687 quejas_fraude 0.010103 Name: Incumplimiento_pago, dtype: float64 ```python corr[num_vars[10]][neg_cor].sort_values(ascending = False) #This prints out the coefficients that are negatively correlated with Incumplimiento_pago: ``` pedidos_peticiones -0.000021 traslado -0.006498 reagendamiento -0.008957 retencion -0.012425 asesoria_servicios -0.019946 asesoria_factura -0.021996 antiguedad_meses -0.150507 Name: Incumplimiento_pago, dtype: float64 De las resultados anteriores se concluye que: - Hay **mas** incumplimiento de pago cuando los clientes llaman por otros motivos y hay quejas de fraude - Existe **menos** incumplimiento de pago a medida que aumenta la antiguedad en meses ```python # subdividiendo la columna producto en tres para trabajar los servicios de forma diferenciada: df[['productoTO','productoTV','productoBA']] = df.productos.str.split('+',expand=True,) ``` ```python df[['productoTO','productoTV','productoBA']] ``` <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>productoTO</th> <th>productoTV</th> <th>productoBA</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>TV</td> <td>BA</td> <td>None</td> </tr> <tr> <th>1</th> <td>TV</td> <td>BA</td> <td>None</td> </tr> <tr> <th>2</th> <td>TV</td> <td>None</td> <td>None</td> </tr> <tr> <th>3</th> <td>TO</td> <td>TV</td> <td>BA</td> </tr> <tr> <th>4</th> <td>TO</td> <td>TV</td> <td>BA</td> </tr> <tr> <th>...</th> <td>...</td> <td>...</td> <td>...</td> </tr> <tr> <th>19937</th> <td>TO</td> <td>BA</td> <td>None</td> </tr> <tr> <th>19938</th> <td>TO</td> <td>BA</td> <td>None</td> </tr> <tr> <th>19939</th> <td>BA</td> <td>None</td> <td>None</td> </tr> <tr> <th>19940</th> <td>TV</td> <td>None</td> <td>None</td> </tr> <tr> <th>19941</th> <td>TV</td> <td>None</td> <td>None</td> </tr> </tbody> </table> <p>19942 rows × 3 columns</p> </div> ```python df['productoTO'][19939] ``` 'BA' ```python df.loc[19939,'productoTO']='valor' ``` ```python df['productoTO'][19939] ``` 'valor' Con lo anterior, se procede a hacer un proceso similar a una **codificación one-hot** de las tres variables categóricas (`productoTO`,`productoTV`,`productoBA`) que se extrajeron de la columna `productos`. Solo queda repartir el valor adecuado en la correspondiente columna (TO, TV, BA) y asignar para cada columna ya organizada, el valor de 1 en caso de que haya producto y 0 cuando no haya: ```python #usando unas columnas auxiliares en primera instancia: df['O']='' df['V']='' df['A']='' ``` ```python #organizando los productos así: TO, TV, BA (tipo one-hot-encoding) cols=['productoTO','productoTV','productoBA'] for row in range(0, len(df)): for col in cols: if df[col][row]=='TO': df.loc[row,'O']=1 elif df[col][row]=='TV': df.loc[row,'V']=1 elif df[col][row]=='BA': df.loc[row,'A']=1 ``` ```python df[['O','V','A']] ``` <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>O</th> <th>V</th> <th>A</th> </tr> </thead> <tbody> <tr> <th>0</th> <td></td> <td>1</td> <td>1</td> </tr> <tr> <th>1</th> <td></td> <td>1</td> <td>1</td> </tr> <tr> <th>2</th> <td></td> <td>1</td> <td></td> </tr> <tr> <th>3</th> <td>1</td> <td>1</td> <td>1</td> </tr> <tr> <th>4</th> <td>1</td> <td>1</td> <td>1</td> </tr> <tr> <th>...</th> <td>...</td> <td>...</td> <td>...</td> </tr> <tr> <th>19937</th> <td>1</td> <td></td> <td>1</td> </tr> <tr> <th>19938</th> <td>1</td> <td></td> <td>1</td> </tr> <tr> <th>19939</th> <td></td> <td></td> <td></td> </tr> <tr> <th>19940</th> <td></td> <td>1</td> <td></td> </tr> <tr> <th>19941</th> <td></td> <td>1</td> <td></td> </tr> </tbody> </table> <p>19942 rows × 3 columns</p> </div> ```python df[['productoTO','productoTV','productoBA']] = df[['O','V','A']] df[['productoTO','productoTV','productoBA']] ``` <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>productoTO</th> <th>productoTV</th> <th>productoBA</th> </tr> </thead> <tbody> <tr> <th>0</th> <td></td> <td>1</td> <td>1</td> </tr> <tr> <th>1</th> <td></td> <td>1</td> <td>1</td> </tr> <tr> <th>2</th> <td></td> <td>1</td> <td></td> </tr> <tr> <th>3</th> <td>1</td> <td>1</td> <td>1</td> </tr> <tr> <th>4</th> <td>1</td> <td>1</td> <td>1</td> </tr> <tr> <th>...</th> <td>...</td> <td>...</td> <td>...</td> </tr> <tr> <th>19937</th> <td>1</td> <td></td> <td>1</td> </tr> <tr> <th>19938</th> <td>1</td> <td></td> <td>1</td> </tr> <tr> <th>19939</th> <td></td> <td></td> <td></td> </tr> <tr> <th>19940</th> <td></td> <td>1</td> <td></td> </tr> <tr> <th>19941</th> <td></td> <td>1</td> <td></td> </tr> </tbody> </table> <p>19942 rows × 3 columns</p> </div> ```python df['productoTO'][0] ``` '' ```python #ya tenemos los valores de 1, ahora falta poner 0 donde esté vacío (''): cols=['productoTO','productoTV','productoBA'] for row in range(0, len(df)): for col in cols: if df[col][row]=='': df.loc[row,col]=0 ``` ```python df[['productoTO','productoTV','productoBA']] #esta es la versión final tipo one-hot-encoding ``` <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>productoTO</th> <th>productoTV</th> <th>productoBA</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>0</td> <td>1</td> <td>1</td> </tr> <tr> <th>1</th> <td>0</td> <td>1</td> <td>1</td> </tr> <tr> <th>2</th> <td>0</td> <td>1</td> <td>0</td> </tr> <tr> <th>3</th> <td>1</td> <td>1</td> <td>1</td> </tr> <tr> <th>4</th> <td>1</td> <td>1</td> <td>1</td> </tr> <tr> <th>...</th> <td>...</td> <td>...</td> <td>...</td> </tr> <tr> <th>19937</th> <td>1</td> <td>0</td> <td>1</td> </tr> <tr> <th>19938</th> <td>1</td> <td>0</td> <td>1</td> </tr> <tr> <th>19939</th> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <th>19940</th> <td>0</td> <td>1</td> <td>0</td> </tr> <tr> <th>19941</th> <td>0</td> <td>1</td> <td>0</td> </tr> </tbody> </table> <p>19942 rows × 3 columns</p> </div> ```python df.head(1) ``` <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>REGIONAL</th> <th>DEPARTAMENTO</th> <th>TECNOL</th> <th>GERENCIA</th> <th>CANAL_HOMOLOGADO_MILLICON</th> <th>tipo_fuerza_venta</th> <th>estrato</th> <th>antiguedad_meses</th> <th>productos</th> <th>portafolio</th> <th>no_serv_tecnicos</th> <th>fallo</th> <th>asesoria_factura</th> <th>pedidos_peticiones</th> <th>reagendamiento</th> <th>asesoria_servicios</th> <th>retencion</th> <th>Otras</th> <th>quejas_fraude</th> <th>traslado</th> <th>Incumplimiento_pago</th> <th>cliente_id</th> <th>productoTO</th> <th>productoTV</th> <th>productoBA</th> <th>O</th> <th>V</th> <th>A</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>COSTA</td> <td>MAGDALENA</td> <td>HFC</td> <td>CONTACT</td> <td>SAC</td> <td>INDIRECTA</td> <td>3</td> <td>19.0</td> <td>TV+BA</td> <td>Duo</td> <td>1.0</td> <td>No funciona línea telefónica</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1004369760</td> <td>0</td> <td>1</td> <td>1</td> <td></td> <td>1</td> <td>1</td> </tr> </tbody> </table> </div> ```python df.columns ``` Index(['REGIONAL', 'DEPARTAMENTO', 'TECNOL', 'GERENCIA', 'CANAL_HOMOLOGADO_MILLICON', 'tipo_fuerza_venta', 'estrato', 'antiguedad_meses', 'productos', 'portafolio', 'no_serv_tecnicos', 'fallo', 'asesoria_factura', 'pedidos_peticiones', 'reagendamiento', 'asesoria_servicios', 'retencion', 'Otras', 'quejas_fraude', 'traslado', 'Incumplimiento_pago', 'cliente_id', 'productoTO', 'productoTV', 'productoBA', 'O', 'V', 'A'], dtype='object') ```python new_cols=['REGIONAL', 'DEPARTAMENTO', 'TECNOL', 'GERENCIA', 'CANAL_HOMOLOGADO_MILLICON', 'tipo_fuerza_venta', 'estrato', 'antiguedad_meses', 'productos', 'portafolio', 'no_serv_tecnicos', 'fallo', 'asesoria_factura', 'pedidos_peticiones', 'reagendamiento', 'asesoria_servicios', 'retencion', 'Otras', 'quejas_fraude', 'traslado', 'Incumplimiento_pago', 'cliente_id', 'productoTO', 'productoTV', 'productoBA'] ``` ```python df=df[new_cols].copy() #finalmente nos quedamos con las columnas necesarias para el posterior análisis sin tener en cuenta las auxiliares (repetidas) df.head(1) ``` <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>REGIONAL</th> <th>DEPARTAMENTO</th> <th>TECNOL</th> <th>GERENCIA</th> <th>CANAL_HOMOLOGADO_MILLICON</th> <th>tipo_fuerza_venta</th> <th>estrato</th> <th>antiguedad_meses</th> <th>productos</th> <th>portafolio</th> <th>no_serv_tecnicos</th> <th>fallo</th> <th>asesoria_factura</th> <th>pedidos_peticiones</th> <th>reagendamiento</th> <th>asesoria_servicios</th> <th>retencion</th> <th>Otras</th> <th>quejas_fraude</th> <th>traslado</th> <th>Incumplimiento_pago</th> <th>cliente_id</th> <th>productoTO</th> <th>productoTV</th> <th>productoBA</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>COSTA</td> <td>MAGDALENA</td> <td>HFC</td> <td>CONTACT</td> <td>SAC</td> <td>INDIRECTA</td> <td>3</td> <td>19.0</td> <td>TV+BA</td> <td>Duo</td> <td>1.0</td> <td>No funciona línea telefónica</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1004369760</td> <td>0</td> <td>1</td> <td>1</td> </tr> </tbody> </table> </div> ```python print(num_vars) ``` ['antiguedad_meses', 'no_serv_tecnicos', 'asesoria_factura', 'pedidos_peticiones', 'reagendamiento', 'asesoria_servicios', 'retencion', 'Otras', 'quejas_fraude', 'traslado', 'Incumplimiento_pago'] ```python print(cat_vars) ``` ['REGIONAL', 'DEPARTAMENTO', 'TECNOL', 'GERENCIA', 'CANAL_HOMOLOGADO_MILLICON', 'tipo_fuerza_venta', 'estrato', 'productos', 'portafolio', 'fallo'] ```python #redefiniendo las nuevas vars categoricas (no considerar productos como un todo sino las tres tipo one-hot encoding) new_cat_vars=['REGIONAL', 'DEPARTAMENTO', 'TECNOL', 'GERENCIA', 'CANAL_HOMOLOGADO_MILLICON', 'tipo_fuerza_venta', 'estrato', 'portafolio', 'fallo', 'productoTO', 'productoTV', 'productoBA'] print(new_cat_vars) ``` ['REGIONAL', 'DEPARTAMENTO', 'TECNOL', 'GERENCIA', 'CANAL_HOMOLOGADO_MILLICON', 'tipo_fuerza_venta', 'estrato', 'portafolio', 'fallo', 'productoTO', 'productoTV', 'productoBA'] # Observación: Para mi caso personal, por motivos de tiempo limitado y dado que el tratamiento de la información se está haciendo con las herramientas proporcionadas por Python (pandas, numpy, etc.) en este cuaderno de Jupyter y usando los recursos de Google Collab, no es necesario que la base de datos quede por ejemplo con todas sus variables y valores en minúsculas, sin tildes, sin caracterés especiales, etc, ya que no se va a usar SQL (tampoco se está trabajando en este caso con procesamiento de texto - si dispongo de tiempo, aunque lo dudo, trabajaré en NLP con Tweets de Teleperformance). Sin embargo, es deseable e importante que la base de datos quede de forma apropiada para poner los modelos de ML en producción con el fin de que consuma info de la base de datos y finalmente se muestren los resultados en un Front End específico como Dash o PowerBI, entre otros. 2. **Construya un modelo estadístico que calcule la probabilidad de que un cliente no pague la primera factura. Explique por qué escogió las variables con las que va a trabajar y si debió hacer modificaciones de estas.** Teniendo en cuenta los resultados del análisis anterior (punto 1), procederé a construir el modelo estadístico que será **Regresión Logística**. Para referencia, en estos dos trabajos hay información interesante y pernitente para este caso: [1]https://bibdigital.epn.edu.ec/bitstream/15000/9194/3/CD-6105.pdf [2]https://repository.eafit.edu.co/bitstream/handle/10784/12870/Adriana_SalamancaArias_JohnAlejandro_BenitezUrrea_2018.pdf?sequence=2 Según [2], *"los modelos logísticos son apropiados para medir la probabilidad de incumplimiento que enfrentan las empresas del sector real, al tener en cuenta su versatilidad para determinar rangos múltiples de la variable dependiente de manera ordenada, porque trabaja con distribución probabilística que permite que con poca información se puedan obtener resultados interesantes con respecto a la probabilidad de incumplimiento"* ```python df.index ``` RangeIndex(start=0, stop=19942, step=1) ```python 100*(13033/19942) ``` 65.35452813158159 ```python #para facilitar el análisis, no consideraré la columna no_serv_tecnicos debido a la poca información que tiene (solo el 35% puesto que el 65% son NULL) reemplazando los NaN por su valor promedio en 'antiguedad_meses' df['antiguedad_meses'].fillna(df['antiguedad_meses'].mean(), inplace=True) df['no_serv_tecnicos'].fillna(df['no_serv_tecnicos'].mean(), inplace=True) #lo hago solo por llenarla de la misma manera pero esa columna no se considerará df.info() ``` <class 'pandas.core.frame.DataFrame'> RangeIndex: 19942 entries, 0 to 19941 Data columns (total 25 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 REGIONAL 19942 non-null object 1 DEPARTAMENTO 19942 non-null object 2 TECNOL 19942 non-null object 3 GERENCIA 19942 non-null object 4 CANAL_HOMOLOGADO_MILLICON 19942 non-null object 5 tipo_fuerza_venta 19942 non-null object 6 estrato 19942 non-null object 7 antiguedad_meses 19942 non-null float64 8 productos 19942 non-null object 9 portafolio 19942 non-null object 10 no_serv_tecnicos 19942 non-null float64 11 fallo 19942 non-null object 12 asesoria_factura 19942 non-null int64 13 pedidos_peticiones 19942 non-null int64 14 reagendamiento 19942 non-null int64 15 asesoria_servicios 19942 non-null int64 16 retencion 19942 non-null int64 17 Otras 19942 non-null int64 18 quejas_fraude 19942 non-null int64 19 traslado 19942 non-null int64 20 Incumplimiento_pago 19942 non-null int64 21 cliente_id 19942 non-null int64 22 productoTO 19942 non-null object 23 productoTV 19942 non-null object 24 productoBA 19942 non-null object dtypes: float64(2), int64(10), object(13) memory usage: 3.8+ MB ```python df['estrato'].head(20) ``` 0 3 1 3 2 1 3 3 4 3 5 3 6 SE 7 SE 8 3 9 SE 10 SE 11 SE 12 SE 13 SE 14 SE 15 4 16 4 17 4 18 2 19 SE Name: estrato, dtype: object ```python #similarmente en 'estrato' cambio 'SE' por 0 (para luego hacerlo por la parte entera de su valor promedio): for i in df.index: if df['estrato'][i]=='SE': df['estrato'][i]=0 ``` ```python df['estrato'].head(20) ``` 0 3 1 3 2 1 3 3 4 3 5 3 6 0 7 0 8 3 9 0 10 0 11 0 12 0 13 0 14 0 15 4 16 4 17 4 18 2 19 0 Name: estrato, dtype: object ```python df['estrato']=pd.to_numeric(df['estrato']) df.info() ``` <class 'pandas.core.frame.DataFrame'> RangeIndex: 19942 entries, 0 to 19941 Data columns (total 25 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 REGIONAL 19942 non-null object 1 DEPARTAMENTO 19942 non-null object 2 TECNOL 19942 non-null object 3 GERENCIA 19942 non-null object 4 CANAL_HOMOLOGADO_MILLICON 19942 non-null object 5 tipo_fuerza_venta 19942 non-null object 6 estrato 19942 non-null int64 7 antiguedad_meses 19942 non-null float64 8 productos 19942 non-null object 9 portafolio 19942 non-null object 10 no_serv_tecnicos 19942 non-null float64 11 fallo 19942 non-null object 12 asesoria_factura 19942 non-null int64 13 pedidos_peticiones 19942 non-null int64 14 reagendamiento 19942 non-null int64 15 asesoria_servicios 19942 non-null int64 16 retencion 19942 non-null int64 17 Otras 19942 non-null int64 18 quejas_fraude 19942 non-null int64 19 traslado 19942 non-null int64 20 Incumplimiento_pago 19942 non-null int64 21 cliente_id 19942 non-null int64 22 productoTO 19942 non-null object 23 productoTV 19942 non-null object 24 productoBA 19942 non-null object dtypes: float64(2), int64(11), object(12) memory usage: 3.8+ MB ```python int(df['estrato'].mean()) ``` 2 ```python #similarmente en 'estrato' cambio 'SE' por la parte entera de su valor promedio: for i in df.index: if df['estrato'][i]==0: df['estrato'][i]=int(df['estrato'].mean()) df['estrato'].head(20) ``` 0 3 1 3 2 1 3 3 4 3 5 3 6 2 7 2 8 3 9 2 10 2 11 2 12 2 13 2 14 2 15 4 16 4 17 4 18 2 19 2 Name: estrato, dtype: int64 ```python #recordemos el conteo de la var objetivo: sns.countplot(x='Incumplimiento_pago', data = df) plt.title("Incumplimiento_pago") ``` ```python #Relación: Incumplimiento_pago (Y) vs antiguedad_meses(X) sns.jointplot(df.antiguedad_meses, df.Incumplimiento_pago, kind="hex") ``` ```python print(num_vars) ``` ['antiguedad_meses', 'no_serv_tecnicos', 'asesoria_factura', 'pedidos_peticiones', 'reagendamiento', 'asesoria_servicios', 'retencion', 'Otras', 'quejas_fraude', 'traslado', 'Incumplimiento_pago'] ```python #Y='Incumplimiento_pago' (var DEPENDIENTE) #redefiniendo las var INDEPENDIENTES verdaderamente numericas (porque las binarias serían categóricas) y que serán insumo para el modelo: num_vars_def=['antiguedad_meses', 'estrato'] #SOLO QUEDAN 2 ``` ```python print(new_cat_vars) ``` ['REGIONAL', 'DEPARTAMENTO', 'TECNOL', 'GERENCIA', 'CANAL_HOMOLOGADO_MILLICON', 'tipo_fuerza_venta', 'estrato', 'portafolio', 'fallo', 'productoTO', 'productoTV', 'productoBA'] NOTA: Por simplicidad, las siguientes var cat no se consideran relevantes para el modelo: 'REGIONAL', 'DEPARTAMENTO', 'TECNOL', 'GERENCIA', 'CANAL_HOMOLOGADO_MILLICON', 'tipo_fuerza_venta', 'portafolio' (está correlacionada con 'productos' que tampoco se considera pues se separó en tres var cat binarias que si se van a considerar en su reemplazo) ```python #en consecuencia, redefiniendo las var verdaderamente categóricas y que serán insumo para el modelo: cat_vars_def=['productoTO', 'productoTV', 'productoBA', 'asesoria_factura', 'pedidos_peticiones', 'reagendamiento', 'asesoria_servicios', 'retencion', 'Otras', 'quejas_fraude', 'traslado']#QUEDAN 11 ``` Veamos la matriz de correlación entre las var numericas definitivas (covariables) y la variable objetivo: ```python num_vars_def=['antiguedad_meses', 'estrato'] ``` ```python cols=num_vars_def.copy() cols.append('Incumplimiento_pago') print(cols) ``` ['antiguedad_meses', 'estrato', 'Incumplimiento_pago'] ```python #Visualize the correlation matrix across all numerical features by using the sns.heatmap() command: #compute correlation matrix Data=df[cols].copy() df_correlations = Data.corr() #mask the upper half for visualization purposes mask = np.zeros_like(df_correlations, dtype=np.bool) mask[np.triu_indices_from(mask)] = True # Draw the heatmap with the mask and correct aspect ratio plt.figure(figsize= (10,10)) cmap = sns.diverging_palette(220, 10, as_cmap=True) sns.heatmap(df_correlations,mask=mask, vmax=1, vmin=-1, cmap=cmap, center=0, square=True, linewidths=.5, cbar_kws={"shrink": .5}); ``` Construyendo el modelo predictivo: ...iniciando con un modelo de regresión logística estándard... Using the `LogisticRegression()` function from `scikit-learn`, let me write a function named `fit_logistic_regression(X,y)` that fits a logistic regression on the array of covariates `X` and associated response variable `y`. ```python from sklearn.linear_model import LogisticRegression def fit_logistic_regression(X,y): """ fit a logistic regression with feature matrix X and binary output y """ clf = LogisticRegression(solver='lbfgs', tol=10**-4, fit_intercept=True, multi_class='multinomial').fit(X,y) return clf ``` Let me create a basic [logistic regression model](https://towardsdatascience.com/logistic-regression-detailed-overview-46c4da4303bc) for predicting `Incumplimiento_pago` with only one feature: `antiguedad_meses`. I will call this model `model1`, using a 70/30 train-test split of the data. ```python # we will use a 70%/30% split for training/validation Data=df.copy() n_total = len(Data) n_train = int(0.7*n_total) X, y = Data[["antiguedad_meses"]], Data.Incumplimiento_pago X_train, y_train = X[:n_train], y[:n_train] X_test, y_test = X[n_train:], y[n_train:] ``` ```python model1 = fit_logistic_regression(X_train, y_train) # fit a logistic regression y_test_pred = model1.predict_proba(X_test)[:,1] # make probabilistic predictions on test set ``` Plotting the [ROC curve](https://towardsdatascience.com/understanding-auc-roc-curve-68b2303cc9c5) of `model1` and finding the area under the curve: ```python from sklearn.metrics import roc_curve, auc from sklearn.model_selection import StratifiedKFold ``` ```python fpr, tpr, _ = roc_curve(y_test, y_test_pred) #compute FPR/TPR auc_baseline = auc(fpr, tpr) # compute AUC plt.plot(fpr, tpr, "b-", label="AUC(basline)={:2.2f}".format(auc_baseline)) plt.xlabel("False Positive Rate") plt.ylabel("True Positive Rate") plt.legend(fontsize=15) plt.plot([0,1], [0,1], "r--") plt.title("ROC curve -- Baseline Model"); ``` Of course this should not be the final model. This is because I have not explored the contribution from other variables, which in addition to containing valuable information could also be confounding the perceived effect of `antiguedad_meses` on the response variable `Incumplimiento_pago`. This under-exploitation of information is called [**underfitting**](https://towardsdatascience.com/what-are-overfitting-and-underfitting-in-machine-learning-a96b30864690). On the other hand: Let's instead put all the variables available in the model, so that we are maximally leveraging our available info. This is also a bad idea. If we *blindly* use all of the variables in our model fitting, a phenomenon called [**overfitting**](https://towardsdatascience.com/what-are-overfitting-and-underfitting-in-machine-learning-a96b30864690) occurs. This is when a statistical model "fits" too closely to a particular set of data, which may well be noisy and exhibit randomness and therefore fail to predict future, different observations reliably. In most cases, you will be working with datasets with many features that each have their own distribution. Generally, a large amount of time is spent on feature selection with many models being trained during this time. It is extremely rare that you simply plug all the features in and tune it once to get the optimal model. There are many different techniques associated with feature selection and a comprehensive look into all of them is outside the scope of this case. For simplicity, I will demonstrate model training and testing on single-feature models and then directly move into multi-feature models to show the numerous possible cases you may encounter. In reality, I would apply cross-validation on numerous subsets of features based on domain knowledge of the dataset to see which set of features truly optimizes the model I am trying to create. [**Cross-validation**](https://towardsdatascience.com/why-and-how-to-cross-validate-a-model-d6424b45261f) is a set of techniques for assessing how well the results of a model will generalize to an out-of-sample dataset; i.e. in practice or production. It is chiefly used to flag overfitting. ```python skf = StratifiedKFold(n_splits=5) for k, (train_index, test_index) in enumerate( skf.split(X, y) ): plt.plot(train_index, [k+1 for _ in train_index], ".") plt.ylim(0,6) plt.ylabel("FOLD") plt.title("CROSS VALIDATION FOLDS") ``` The following code defines a function `compute_AUC(X, y, train_index, test_index)` that computes the AUC of a model trained on "train_index" and tested in "test_index". ```python def compute_AUC(X, y, train_index, test_index): """ feature/output: X, y dataset split: train_index, test_index """ X_train, y_train = X.iloc[train_index], y.iloc[train_index] X_test, y_test = X.iloc[test_index], y.iloc[test_index] clf = fit_logistic_regression(X_train, y_train) default_proba_test = clf.predict_proba(X_test)[:,1] fpr, tpr, _ = roc_curve(y_test, default_proba_test) auc_score = auc(fpr, tpr) return auc_score, fpr, tpr ``` With the help of the `compute_AUC` function defined above, let me write a function `cross_validation_AUC(X,y,nfold)` that carries out a 10-fold cross-validation and returns a list which contains the area under the curve for each fold of the cross-validation: ```python def cross_validation_AUC(X,y, nfold=10): """ use a n-fold cross-validation for computing AUC estimates """ skf = StratifiedKFold(n_splits=nfold) #create a cross-validation splitting auc_list = [] #this list will contain the AUC estimates associated with each fold for k, (train_index, test_index) in enumerate( skf.split(X, y) ): auc_score, _, _ = compute_AUC(X, y, train_index, test_index) auc_list.append(auc_score) return auc_list ``` I will now estimate and compare, through cross-validation analysis, the performance of all the "simple models" that only use one numerical features as input. ```python print(num_vars_def) ``` ['antiguedad_meses', 'estrato'] Let's compute cross-validation estimates of the AUC for each single-feature model: ```python model_perf = pd.DataFrame({}) #this data-frame will contain the AUC estimates for key in num_vars_def: X_full, y_full = Data[[key]], Data.Incumplimiento_pago auc_list = cross_validation_AUC(X_full, y_full, nfold=10) model_perf["SIMPLE:" + key] = auc_list ``` Let me construct a [boxplot](https://towardsdatascience.com/understanding-boxplots-5e2df7bcbd51) which shows the distribution of cross-validation scores of each variable (remember, each variable has 10 total scores): ```python def plot_boxplot_ordered(df_model): """ display a list of boxplot, ordered by the media values """ df = df_model[df_model.median().sort_values().index] sns.boxplot(x="variable", y="value", data=pd.melt(df), showfliers=False) plt.xticks(rotation=90) ``` ```python plt.figure(figsize= (10,5)) plot_boxplot_ordered(model_perf) plt.xlabel("Predictive Model with a Single Predictive Feature") plt.ylabel("AUC") ``` According to what have been done so far, from the above picture I can conclude: - The feature that has the highest predictive power is `antiguedad_meses` - The feature that has the lowest predictive power is `estrato` Let me consider the model that consists of using *all* the numerical features (and none of the categorical features). Carrying out a 10-fold cross-validation analysis to determine whether this model has better predictive performance than the best single-feature model. Using the boxplot method again as I did before: ```python X_full, y_full = Data[num_vars_def], Data.Incumplimiento_pago auc_list = cross_validation_AUC(X_full, y_full) model_perf["ALL_NUMERICAL"] = auc_list model_perf ``` <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>SIMPLE:antiguedad_meses</th> <th>SIMPLE:estrato</th> <th>ALL_NUMERICAL</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>0.625454</td> <td>0.429581</td> <td>0.612515</td> </tr> <tr> <th>1</th> <td>0.592383</td> <td>0.462943</td> <td>0.580514</td> </tr> <tr> <th>2</th> <td>0.559453</td> <td>0.495811</td> <td>0.547094</td> </tr> <tr> <th>3</th> <td>0.674187</td> <td>0.497961</td> <td>0.669534</td> </tr> <tr> <th>4</th> <td>0.690632</td> <td>0.521252</td> <td>0.694829</td> </tr> <tr> <th>5</th> <td>0.581867</td> <td>0.494196</td> <td>0.575197</td> </tr> <tr> <th>6</th> <td>0.659101</td> <td>0.552888</td> <td>0.650529</td> </tr> <tr> <th>7</th> <td>0.671121</td> <td>0.533505</td> <td>0.672244</td> </tr> <tr> <th>8</th> <td>0.680397</td> <td>0.504706</td> <td>0.677434</td> </tr> <tr> <th>9</th> <td>0.642052</td> <td>0.509290</td> <td>0.644907</td> </tr> </tbody> </table> </div> ```python plt.figure(figsize= (10,5)) plot_boxplot_ordered(model_perf) plt.xlabel("Predictive Model with a Single Predictive Feature") plt.ylabel("AUC") ``` I see that the combined model does perform better than the best single-feature model. Thus, I will move forward with it for the rest of this case. Note, however, that best practice would entail iteratively adding features to the best single-feature model until I reach a point where there is no significant improvement, as opposed to throwing all the features in at once. Let me advise and consider to take this more cautious approach when building models (it is a matter of time) ## Incorporating categorical variables: ```python cat_vars_def # se podría decir que estas vars ya están codificadas tipo one-hot para irse añadiendo al modelo numérico anterior ``` ['productoTO', 'productoTV', 'productoBA', 'asesoria_factura', 'pedidos_peticiones', 'reagendamiento', 'asesoria_servicios', 'retencion', 'Otras', 'quejas_fraude', 'traslado'] ```python Data.value_counts() sns.countplot(x='productoTO', data = Data) plt.xticks(rotation=90) ``` Let me investigate whether the categorical variable `productoTO` brings any predictive value when added to the current best model (remember again that the encoding scheme of one-hot type is already there: ```python plt.figure(figsize= (20,5)) df_TO_incump = Data[["Incumplimiento_pago", "productoTO"]].groupby("productoTO").mean() df_TO_incump = df_TO_incump.sort_values(by="Incumplimiento_pago",axis=0, ascending=False) sns.barplot(x=df_TO_incump.index[:50], y=df_TO_incump["Incumplimiento_pago"][:50].values, orient="v") plt.xticks(rotation=90) plt.ylabel("Probabilidad de Incumplimiento_pago") plt.title("Incumplimiento_pago por productoTO", fontsize=20, verticalalignment='bottom') ``` ```python print(num_vars_def) ``` ['antiguedad_meses', 'estrato'] ```python new_cols=['antiguedad_meses', 'estrato','productoTO','productoTV','productoBA'] X_full_productos, y_full = Data[new_cols], Data.Incumplimiento_pago auc_list = cross_validation_AUC(X_full_productos, y_full) model_perf["ALL_NUMERICAL_WITH_productos"] = auc_list model_perf ``` <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>SIMPLE:antiguedad_meses</th> <th>SIMPLE:estrato</th> <th>ALL_NUMERICAL</th> <th>ALL_NUMERICAL_WITH_productos</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>0.625454</td> <td>0.429581</td> <td>0.612515</td> <td>0.694596</td> </tr> <tr> <th>1</th> <td>0.592383</td> <td>0.462943</td> <td>0.580514</td> <td>0.627549</td> </tr> <tr> <th>2</th> <td>0.559453</td> <td>0.495811</td> <td>0.547094</td> <td>0.587298</td> </tr> <tr> <th>3</th> <td>0.674187</td> <td>0.497961</td> <td>0.669534</td> <td>0.706750</td> </tr> <tr> <th>4</th> <td>0.690632</td> <td>0.521252</td> <td>0.694829</td> <td>0.727204</td> </tr> <tr> <th>5</th> <td>0.581867</td> <td>0.494196</td> <td>0.575197</td> <td>0.706316</td> </tr> <tr> <th>6</th> <td>0.659101</td> <td>0.552888</td> <td>0.650529</td> <td>0.745785</td> </tr> <tr> <th>7</th> <td>0.671121</td> <td>0.533505</td> <td>0.672244</td> <td>0.728415</td> </tr> <tr> <th>8</th> <td>0.680397</td> <td>0.504706</td> <td>0.677434</td> <td>0.778226</td> </tr> <tr> <th>9</th> <td>0.642052</td> <td>0.509290</td> <td>0.644907</td> <td>0.724648</td> </tr> </tbody> </table> </div> ```python plt.figure(figsize= (10,5)) plot_boxplot_ordered(model_perf) plt.xlabel("Predictive Model with a Single Predictive Feature") plt.ylabel("AUC") ``` The difference appears significant as the boxplot for the updated model is almost completely non-overlapping with that of the previous model. #To finish: Let me use the rest of the "cat_vars" (they are indeed numerical: binary): ```python print(cat_vars_def) ``` ['productoTO', 'productoTV', 'productoBA', 'asesoria_factura', 'pedidos_peticiones', 'reagendamiento', 'asesoria_servicios', 'retencion', 'Otras', 'quejas_fraude', 'traslado'] ```python pqrs=['asesoria_factura', 'pedidos_peticiones', 'reagendamiento', 'asesoria_servicios', 'retencion', 'Otras', 'quejas_fraude', 'traslado'] ``` ```python new_cols_def=['antiguedad_meses', 'estrato','productoTO','productoTV','productoBA', 'asesoria_factura', 'pedidos_peticiones', 'reagendamiento', 'asesoria_servicios', 'retencion', 'Otras', 'quejas_fraude', 'traslado'] X_full_productos_pqrs, y_full = Data[new_cols_def], Data.Incumplimiento_pago auc_list = cross_validation_AUC(X_full_productos_pqrs, y_full) model_perf["ALL_NUMERICAL_WITH_productos_pqrs"] = auc_list model_perf ``` <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>SIMPLE:antiguedad_meses</th> <th>SIMPLE:estrato</th> <th>ALL_NUMERICAL</th> <th>ALL_NUMERICAL_WITH_productos</th> <th>ALL_NUMERICAL_WITH_productos_pqrs</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>0.625454</td> <td>0.429581</td> <td>0.612515</td> <td>0.694596</td> <td>0.695431</td> </tr> <tr> <th>1</th> <td>0.592383</td> <td>0.462943</td> <td>0.580514</td> <td>0.627549</td> <td>0.624117</td> </tr> <tr> <th>2</th> <td>0.559453</td> <td>0.495811</td> <td>0.547094</td> <td>0.587298</td> <td>0.588349</td> </tr> <tr> <th>3</th> <td>0.674187</td> <td>0.497961</td> <td>0.669534</td> <td>0.706750</td> <td>0.706378</td> </tr> <tr> <th>4</th> <td>0.690632</td> <td>0.521252</td> <td>0.694829</td> <td>0.727204</td> <td>0.722031</td> </tr> <tr> <th>5</th> <td>0.581867</td> <td>0.494196</td> <td>0.575197</td> <td>0.706316</td> <td>0.706624</td> </tr> <tr> <th>6</th> <td>0.659101</td> <td>0.552888</td> <td>0.650529</td> <td>0.745785</td> <td>0.745685</td> </tr> <tr> <th>7</th> <td>0.671121</td> <td>0.533505</td> <td>0.672244</td> <td>0.728415</td> <td>0.723830</td> </tr> <tr> <th>8</th> <td>0.680397</td> <td>0.504706</td> <td>0.677434</td> <td>0.778226</td> <td>0.781072</td> </tr> <tr> <th>9</th> <td>0.642052</td> <td>0.509290</td> <td>0.644907</td> <td>0.724648</td> <td>0.730572</td> </tr> </tbody> </table> </div> ```python plt.figure(figsize= (10,5)) plot_boxplot_ordered(model_perf) plt.xlabel("Predictive Model with a Single Predictive Feature") plt.ylabel("AUC") ``` ## Conclusions Once I started building models, I started with very simple logistic regressions approaches – these baseline models were useful for quickly evaluating the predictive power of each individual variable. Next, I employed cross-validation approaches for building more complex models, often exploiting the interactions between the different features. Since the dataset contains a large number of covariates, using cross-validation was revealed to be crucial for avoiding overfitting, choosing the correct number of features and ultimately choosing an appropriate model that balanced complexity with accuracy. Cross-validation is a robust and flexible technique for evaluating the predictive performance of statistical models. It is especially useful in big data settings where the number of features is large compared to the number of observations. When used appropriately, cross-validation is a powerful method for choosing a model with the correct complexity and best predictive performance. Remember that logistic regression is only one of many classification algorithms and the principles behind cross-validation are not limited to this case alone. *Quiero finalmente comentar que 2 días para mi no son suficientes para terminar completa y exitosamente este caso. Con mas tiempo, seguro lo terminaría, aunque voy a seguir trabajando en el caso apesar de que el tiempo para entregarlo ya se terminó. Muchas gracias por la oprtunidad y también deseo seguir trabajando en el caso opcional donde tenía pensado trabajar con NLP (Tweets-TP)* **Observación:** Todo lo trabajado aquí está referenciado al *programa de Ciencia de Datos (DS4A-Colombia 3.0) ofertado por el Ministerio TIC de Colombia en convenio con la Compañía Correlation One.* Todo el material puede ser encontrado aquí: https://drive.google.com/drive/folders/1mGiM3lWtdkszSIrv-wpJjftZ_2qWbMNt?usp=sharing
(* PUBLIC DOMAIN *) Require Export Coq.Vectors.Vector. Require Export Coq.Lists.List. Require Import Bool.Bool. Require Import Logic.FunctionalExtensionality. Require Import Coq.Program.Wf. (* AIM 1) PROVE transitivity 1.1) DEFINE relation as Type. *) Definition SetVars := nat. Definition FuncSymb := nat. Definition PredSymb := nat. Record FSV := { fs : FuncSymb; fsv : nat; }. Record PSV := MPSV{ ps : PredSymb; psv : nat; }. Inductive Terms : Type := | FVC :> SetVars -> Terms | FSC (f:FSV) : (Vector.t Terms (fsv f)) -> Terms. Definition rela : forall (x y:Terms), Prop. Proof. fix rela 2. intros x y. destruct y as [s|f t]. + exact False. + refine (or _ _). exact (Vector.In x t). simple refine (@Vector.fold_left Terms Prop _ False (fsv f) t). intros Q e. exact (or Q (rela x e)). Defined. (*Definition rela : forall (x y:Terms), Type. Proof. fix rela 2. intros x y. destruct y as [s|f t]. + exact False. + refine (or _ _). exact (Vector.In x t). simple refine (@Vector.fold_left Terms Type _ False (fsv f) t). intros Q e. exact (or Q (rela x e)). Defined.*) Definition snglV {A} (a:A) := Vector.cons A a 0 (Vector.nil A). Fixpoint Tra (a b c:Terms) (Hc : rela c b) (Hb : rela b a) {struct a}: rela c a. destruct a. + simpl in * |- *. exact Hb. + simpl in * |- *. destruct Hb. destruct H. * apply or_introl. constructor 1. - apply Tra with b. trivial. simpl in * |- *. destruct H. * apply or_introl. constructor 1. * apply or_introl. constructor 2. assumption. - apply Tra with b. trivial. simpl in * |- *. apply or_intror. assumption. Defined. destruct H. * apply or_introl. constructor 1. * apply or_introl. constructor 2. assumption. @Vector.In contructor. unfold Vector.In. simpl. * apply or_intror. simpl in * |- *. apply or_intror. simpl in * |- *. Admitted. Definition wfr : @well_founded Terms rela. Proof. clear. unfold well_founded. assert (H : forall (n:Terms) (a:Terms), (rela a n) -> Acc rela a). { fix iHn 1. destruct n. + simpl. intros a b. exfalso. exact b. + simpl. intros a Q. destruct Q as [L|R]. * destruct L. (*pose (G:= iHn m).*) apply Acc_intro. intros q Hq. apply Acc_intro. intros m Hm. apply Acc_intro. intros q Hq. apply (iHn a). apply Tra with m; assumption. * apply Acc_intro. intros m Hm. apply Acc_intro. intros q Hq. apply (iHn a). apply Tra with m; assumption. (* simpl in * |- *. exact Hm. admit. (*apply Acc_intro. intros m Hm. apply (iHn a). exact Hm. *) * admit. (* like in /Arith/Wf_nat.v *)*) } intros a. simple refine (H _ _ _). exact (FSC (Build_FSV 0 1) (snglV a)). simpl. apply or_introl. constructor. Defined.
||| Fibonacci but in linear time module Main import Cairo -- O(n) version fibl : Felt -> Felt fibl n = go n 0 1 where go : Felt -> Felt -> Felt -> Felt go n a b = if n == 0 then a else go (n-1) b (a+b) %noinline main : Cairo () main = output (fibl 10)
(* Title: The pi-calculus Author/Maintainer: Jesper Bengtson (jebe.dk), 2012 *) theory Weak_Early_Bisim_SC imports Weak_Early_Bisim Strong_Early_Bisim_SC begin (******** Structural Congruence **********) lemma weakBisimStructCong: fixes P :: pi and Q :: pi assumes "P \<equiv>\<^sub>s Q" shows "P \<approx> Q" using assms by(metis earlyBisimStructCong strongBisimWeakBisim) lemma matchId: fixes a :: name and P :: pi shows "[a\<frown>a]P \<approx> P" proof - have "[a\<frown>a]P \<sim>\<^sub>e P" by(rule Strong_Early_Bisim_SC.matchId) thus ?thesis by(rule strongBisimWeakBisim) qed lemma mismatchId: fixes a :: name and b :: name and P :: pi assumes "a \<noteq> b" shows "[a\<noteq>b]P \<approx> P" proof - from \<open>a \<noteq> b\<close> have "[a\<noteq>b]P \<sim>\<^sub>e P" by(rule Strong_Early_Bisim_SC.mismatchId) thus ?thesis by(rule strongBisimWeakBisim) qed shows "[a\<noteq>a]P \<approx> \<zero>" proof - have "[a\<noteq>a]P \<sim>\<^sub>e \<zero>" by(rule Strong_Early_Bisim_SC.mismatchNil) thus ?thesis by(rule strongBisimWeakBisim) qed (******** The \<nu>-operator *****************) lemma resComm: fixes P :: pi shows "<\<nu>a><\<nu>b>P \<approx> <\<nu>b><\<nu>a>P" proof - have "<\<nu>a><\<nu>b>P \<sim>\<^sub>e <\<nu>b><\<nu>a>P" by(rule Strong_Early_Bisim_SC.resComm) thus ?thesis by(rule strongBisimWeakBisim) qed (******** The +-operator *********) lemma sumSym: fixes P :: pi and Q :: pi shows "P \<oplus> Q \<approx> Q \<oplus> P" proof - have "P \<oplus> Q \<sim>\<^sub>e Q \<oplus> P" by(rule Strong_Early_Bisim_SC.sumSym) thus ?thesis by(rule strongBisimWeakBisim) qed (******** The |-operator *********) lemma parZero: fixes P :: pi shows "P \<parallel> \<zero> \<approx> P" proof - have "P \<parallel> \<zero> \<sim>\<^sub>e P" by(rule Strong_Early_Bisim_SC.parZero) thus ?thesis by(rule strongBisimWeakBisim) qed lemma parSym: fixes P :: pi and Q :: pi shows "P \<parallel> Q \<approx> Q \<parallel> P" proof - have "P \<parallel> Q \<sim>\<^sub>e Q \<parallel> P" by(rule Strong_Early_Bisim_SC.parSym) thus ?thesis by(rule strongBisimWeakBisim) qed assumes "x \<sharp> P" shows "<\<nu>x>(P \<parallel> Q) \<approx> P \<parallel> <\<nu>x>Q" proof - from \<open>x \<sharp> P\<close> have "<\<nu>x>(P \<parallel> Q) \<sim>\<^sub>e P \<parallel> <\<nu>x>Q" by(rule Strong_Early_Bisim_SC.scopeExtPar) thus ?thesis by(rule strongBisimWeakBisim) qed lemma scopeExtPar': fixes P :: pi and Q :: pi and x :: name assumes "x \<sharp> Q" shows "<\<nu>x>(P \<parallel> Q) \<approx> (<\<nu>x>P) \<parallel> Q" proof - from \<open>x \<sharp> Q\<close> have "<\<nu>x>(P \<parallel> Q) \<sim>\<^sub>e (<\<nu>x>P) \<parallel> Q" by(rule Strong_Early_Bisim_SC.scopeExtPar') thus ?thesis by(rule strongBisimWeakBisim) qed shows "(P \<parallel> Q) \<parallel> R \<approx> P \<parallel> (Q \<parallel> R)" proof - have "(P \<parallel> Q) \<parallel> R \<sim>\<^sub>e P \<parallel> (Q \<parallel> R)" by(rule Strong_Early_Bisim_SC.parAssoc) thus ?thesis by(rule strongBisimWeakBisim) qed lemma freshRes: fixes P :: pi and a :: name assumes "a \<sharp> P" shows "<\<nu>a>P \<approx> P" proof - from \<open>a \<sharp> P\<close> have "<\<nu>a>P \<sim>\<^sub>e P" by(rule Strong_Early_Bisim_SC.freshRes) thus ?thesis by(rule strongBisimWeakBisim) qed lemma scopeExtSum: fixes P :: pi and Q :: pi and x :: name assumes "x \<sharp> P" shows "<\<nu>x>(P \<oplus> Q) \<approx> P \<oplus> <\<nu>x>Q" proof - from \<open>x \<sharp> P\<close> have "<\<nu>x>(P \<oplus> Q) \<sim>\<^sub>e P \<oplus> <\<nu>x>Q" by(rule Strong_Early_Bisim_SC.scopeExtSum) thus ?thesis by(rule strongBisimWeakBisim) qed lemma bangSC: fixes P shows "!P \<approx> P \<parallel> !P" proof - have "!P \<sim>\<^sub>e P \<parallel> !P" by(rule Strong_Early_Bisim_SC.bangSC) thus ?thesis by(rule strongBisimWeakBisim) qed end
module Main import System ---------------------------------------------------------------------- -- Hilffunktionen readNumber : IO (Maybe Nat) readNumber = do input <- getLine if all isDigit (unpack input) then pure (Just (cast input)) else pure Nothing ---------------------------------------------------------------------- -- Projekt -- Gesucht ist eine zufällige Zahl Z zwischen 1 und 100 -- (Hinweis: `System.time : IO Integer`) -- Der Spieler hat n Versuche (Vorschlag: n=7) -- Zunächst gibt das Spiel die Anzahl der verbliebenen Versuche aus -- Dann wird der Spieler aufgefordert eine Zahl zu nennen -- Hat er keine Zahl eingegeben wiederholt sich der letzt Schritt -- (nach Ausgabe einer Warnung) -- Hat der Spieler Z eraten hat er gewonnen -- eine entsprechende Meldung wird ausgegeben und das Spiel ist beendet -- Sonst erhält der Spieler eine Meldung (zu klein/zu groß) und das Spiel -- geht mit einem Versuch weniger (n-1) oben weiter -- Implementiere dazu diese Funktionen entsprechend: rate : (ziel : Nat) -> (versuche : Nat) -> IO () zufallsZahl : IO Nat main : IO () main = do ziel <- zufallsZahl rate ziel 7
! A recursive version of Fibonacci ! Note that while this works OK as a recursive program ! it actually does far, far more work that it needs to, much ! more than double (actually 2^n -1) fold ! Fpr instance, to calculate Fib(3), it will calculate ! Fib(1) twice, and Fib(2) once. For Fib(4) it calculates ! Fib(3) once, Fib(2) twice, and Fib(1) three times. This is ! actually the Fibonacci sequence all over again, so it grows FAST! PROGRAM MAIN IMPLICIT NONE ! Loop counter and maximum value INTEGER :: i, max_val ! Variables for previous sequence vals, and current one INTEGER :: fib_first, fib_second, fib_current ! Do the first 20 terms max_val = 20 ! Optional last but to add- sanity check on max_val IF(max_val < 3 .OR. max_val > 46) THEN PRINT*, "Sequence is too short or long. max_val should be between 3 and 46" END IF ! f(1) = 1 and f(2) = 1 fib_first = 1 fib_second = 1 ! Print the initial 2 values so we see the whole sequence up to max_val PRINT*, fib_first PRINT*, fib_second ! Loop from the third value to max_value, calculating and printing the term DO i = 3, max_val ! This is the current term fib_current = fib(i) ! Print the calculated value PRINT*, fib_current END DO ! A slightly old-fashioned way to define a function, putting it inside the main program like this. ! It is available inside MAIN, but not outside. But one function here can call another. CONTAINS ! We have to use a 'RESULT' here because otherwise there is an ! ambiguity about where we are setting the result variable and ! where we are calling the function. So we have e.g.: RECURSIVE FUNCTION fib(n) RESULT(fib_n) INTEGER:: fib_n, n IF (n < 3) THEN fib_n = 1 ELSE fib_n = fib(n-1) + fib(n-2) END IF END FUNCTION END PROGRAM
Formal statement is: lemma dist_triangle: "dist x z \<le> dist x y + dist y z" Informal statement is: The distance between $x$ and $z$ is less than or equal to the distance between $x$ and $y$ plus the distance between $y$ and $z$.
module Algebra.Solver.Semiring import public Algebra.Semiring import public Algebra.Solver.Semiring.Expr import public Algebra.Solver.Semiring.Prod import public Algebra.Solver.Semiring.SolvableSemiring import public Algebra.Solver.Semiring.Sum %default total
section \<open>A collection of lemmas, definitions and tactics that aid the certification of the Passification phase\<close> theory Passification imports Semantics Util "HOL-Eisbach.Eisbach" "HOL-Eisbach.Eisbach_Tools" begin subsection \<open>Dependence and set command reduction\<close> definition lookup_var_ty_match :: "'a absval_ty_fun \<Rightarrow> var_context \<Rightarrow> rtype_env \<Rightarrow> 'a nstate \<Rightarrow> vname \<Rightarrow> ty \<Rightarrow> bool" where "lookup_var_ty_match A \<Lambda> \<Omega> ns x \<tau> = (Option.map_option (type_of_val A) (lookup_var \<Lambda> ns x) = Some (instantiate \<Omega> \<tau>))" definition closed_set_ty :: "'a absval_ty_fun \<Rightarrow> var_context \<Rightarrow> rtype_env \<Rightarrow> ('a nstate) set \<Rightarrow> 'a nstate \<Rightarrow> vname \<Rightarrow> ty \<Rightarrow> bool" where "closed_set_ty A \<Lambda> \<Omega> U ns x \<tau> = (\<forall>v :: 'a val. type_of_val A v = instantiate \<Omega> \<tau> \<longrightarrow> update_var \<Lambda> ns x v \<in> U)" text \<open>Dependence of a set of normal states U on variables D\<close> definition dependent :: "'a absval_ty_fun \<Rightarrow> var_context \<Rightarrow> rtype_env \<Rightarrow> ('a nstate) set \<Rightarrow> vname set \<Rightarrow> bool" where "dependent A \<Lambda> \<Omega> U D = (\<forall>u \<in> U. (\<forall>d \<tau>. lookup_var_ty \<Lambda> d = Some \<tau> \<longrightarrow> (lookup_var_ty_match A \<Lambda> \<Omega> u d \<tau>) \<and> (d \<notin> D \<longrightarrow> closed_set_ty A \<Lambda> \<Omega> U u d \<tau>)))" lemma dependent_ext: assumes "D \<subseteq> D'" and "dependent A \<Lambda> \<Omega> U D" shows "dependent A \<Lambda> \<Omega> U D'" using assms unfolding dependent_def by blast definition set_red_cmd :: "'a absval_ty_fun \<Rightarrow> proc_context \<Rightarrow> var_context \<Rightarrow> 'a fun_interp \<Rightarrow> rtype_env \<Rightarrow> cmd \<Rightarrow> 'a nstate set \<Rightarrow> 'a state set" where "set_red_cmd A M \<Lambda> \<Gamma> \<Omega> c N = {s. \<exists>n_s. n_s \<in> N \<and> A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>c, Normal n_s\<rangle> \<rightarrow> s}" text \<open>\<^term>\<open>set_red_cmd\<close> lifts the command reduction to the reduction of a a set of input states \<close> subsection \<open>Variable relation\<close> text \<open>One of the main components of relating a non-passified with a passified expression is a variable relatiion that is a mapping between variables in the non-passified and in the passified program (which evolves as two corresponding executions proceed in both programs). Since Boogie performs constant propagation as part of the passification, a variable in the non-passified program may correspond to a literal value (integer or boolean) in the passified program\<close> type_synonym passive_rel = "vname \<rightharpoonup> (vname + lit)" text \<open>\<^typ>\<open>passive_rel\<close> models the type of a variable relation\<close> text \<open>In the following we define some properties on variable relations that we use in our proofs.\<close> definition rel_const_correct :: "var_context \<Rightarrow> rtype_env \<Rightarrow> passive_rel \<Rightarrow> 'a nstate \<Rightarrow> bool" where "rel_const_correct \<Lambda> \<Omega> R ns = (\<forall> x l. R x = Some (Inr l) \<longrightarrow> (lookup_var \<Lambda> ns x = Some (LitV l) \<and> (\<exists> \<tau>. lookup_var_ty \<Lambda> x = Some \<tau> \<and> (TPrim (type_of_lit l)) = instantiate \<Omega> \<tau>)))" definition rel_const_correct_value :: "var_context \<Rightarrow> passive_rel \<Rightarrow> 'a nstate \<Rightarrow> bool" where "rel_const_correct_value \<Lambda> R ns = (\<forall> x l. R x = Some (Inr l) \<longrightarrow> (lookup_var \<Lambda> ns x = Some (LitV l)))" definition rel_well_typed :: "'a absval_ty_fun \<Rightarrow> var_context \<Rightarrow> rtype_env \<Rightarrow> passive_rel \<Rightarrow> 'a nstate \<Rightarrow> bool" where "rel_well_typed A \<Lambda> \<Omega> R ns = ( (\<forall> x y. R x = Some (Inl y) \<longrightarrow> (\<exists>v \<tau>. lookup_var \<Lambda> ns x = Some v \<and> lookup_var_ty \<Lambda> x = Some \<tau> \<and> type_of_val A v = instantiate \<Omega> \<tau>)) \<and> (rel_const_correct \<Lambda> \<Omega> R ns))" lemma rel_well_typed_update: assumes "rel_well_typed A \<Lambda> \<Omega> R ns" and "lookup_var_ty \<Lambda> x = Some \<tau>" and "type_of_val A v = instantiate \<Omega> \<tau>" shows "rel_well_typed A \<Lambda> \<Omega> (R(x \<mapsto> (Inl x'))) (update_var \<Lambda> ns x v)" using assms unfolding rel_well_typed_def rel_const_correct_def by simp lemma rel_well_typed_update_const: assumes "rel_well_typed A \<Lambda> \<Omega> R ns" and "lookup_var_ty \<Lambda> x = Some \<tau>" and "TPrim (type_of_lit l) = instantiate \<Omega> \<tau>" shows "rel_well_typed A \<Lambda> \<Omega> (R(x \<mapsto> Inr l)) (update_var \<Lambda> ns x (LitV l))" using assms unfolding rel_well_typed_def rel_const_correct_def by simp lemma rel_well_typed_update_general: assumes "rel_well_typed A \<Lambda> \<Omega> R ns" and "lookup_var_ty \<Lambda> x = Some \<tau>" and "type_of_val A v = instantiate \<Omega> \<tau>" and "\<And>l. a = Inr l \<Longrightarrow> v = LitV l" shows "rel_well_typed A \<Lambda> \<Omega> (R(x \<mapsto> a)) (update_var \<Lambda> ns x v)" proof (cases a) case (Inl x) then show ?thesis using rel_well_typed_update assms by blast next case (Inr l) thus ?thesis using assms rel_well_typed_update_const by (simp add: rel_well_typed_update_const) qed subsection \<open>Normal state relation\<close> text \<open>In the following, we introduce definitions that relate non-passive states (usually \<^term>\<open>ns1\<close>) and passive states (usually \<^term>\<open>ns2\<close>) that are parametrized by variable relations.\<close> definition nstate_old_rel :: "var_context \<Rightarrow> var_context \<Rightarrow> passive_rel \<Rightarrow> 'a nstate \<Rightarrow> 'a nstate \<Rightarrow> bool" where "nstate_old_rel \<Lambda> \<Lambda>' R ns1 ns2 = (\<forall>x y. R x = Some (Inl y) \<longrightarrow> (map_of (fst \<Lambda>) x \<noteq> None \<and> map_of (snd \<Lambda>) x = None) \<and> (\<exists>v. (old_global_state ns1) x = Some v \<and> lookup_var \<Lambda>' ns2 y = Some v))" definition nstate_rel :: "var_context \<Rightarrow> var_context \<Rightarrow> passive_rel \<Rightarrow> 'a nstate \<Rightarrow> 'a nstate \<Rightarrow> bool" where "nstate_rel \<Lambda> \<Lambda>' R ns1 ns2 = ((\<forall>x y. R x = Some (Inl y) \<longrightarrow> (lookup_var \<Lambda> ns1 x = lookup_var \<Lambda>' ns2 y)) \<and> binder_state ns1 = binder_state ns2)" definition nstate_rel_states :: "var_context \<Rightarrow> var_context \<Rightarrow> passive_rel \<Rightarrow> 'a nstate \<Rightarrow> 'a nstate set \<Rightarrow> bool" where "nstate_rel_states \<Lambda> \<Lambda>' R ns U \<equiv> \<forall>u \<in> U. nstate_rel \<Lambda> \<Lambda>' R ns u" definition nstate_old_rel_states :: "var_context \<Rightarrow> var_context \<Rightarrow> passive_rel \<Rightarrow> 'a nstate \<Rightarrow> 'a nstate set \<Rightarrow> bool" where "nstate_old_rel_states \<Lambda> \<Lambda>' R ns U \<equiv> \<forall>u \<in> U. nstate_old_rel \<Lambda> \<Lambda>' R ns u" lemma nstate_rel_update: "nstate_rel \<Lambda> \<Lambda>' R ns1 ns2 \<Longrightarrow> lookup_var \<Lambda>' ns2 x' = Some v \<Longrightarrow> nstate_rel \<Lambda> \<Lambda>' (R(x \<mapsto> Inl x')) (update_var \<Lambda> ns1 x v) ns2" unfolding nstate_rel_def by (simp add: update_var_binder_same) lemma nstate_rel_update_2: assumes "nstate_rel \<Lambda> \<Lambda>' R ns1 ns2" and "R x' = Some a" and "lookup_var \<Lambda> ns1 x' = Some v" shows "nstate_rel \<Lambda> \<Lambda>' (R(x \<mapsto> a)) (update_var \<Lambda> ns1 x v) ns2" using assms unfolding nstate_rel_def using update_var_binder_same by (metis fun_upd_apply update_var_opt_apply update_var_update_var_opt) lemma nstate_rel_states_update_2: assumes "nstate_rel_states \<Lambda> \<Lambda>' R ns1 U" and "R x' = Some a" and "lookup_var \<Lambda> ns1 x' = Some v" shows "nstate_rel_states \<Lambda> \<Lambda>' (R(x \<mapsto> a)) (update_var \<Lambda> ns1 x v) U" using assms unfolding nstate_rel_states_def by (simp add: nstate_rel_update_2) lemma nstate_rel_update_const: "nstate_rel \<Lambda> \<Lambda>' R ns1 ns2 \<Longrightarrow> nstate_rel \<Lambda> \<Lambda>' (R(x \<mapsto> Inr l)) (update_var \<Lambda> ns1 x v) ns2" unfolding nstate_rel_def by (simp add: update_var_binder_same) lemma nstate_rel_states_update_const: "nstate_rel_states \<Lambda> \<Lambda>' R ns1 U \<Longrightarrow> nstate_rel_states \<Lambda> \<Lambda>' (R(x \<mapsto> Inr l)) (update_var \<Lambda> ns1 x v) U" unfolding nstate_rel_states_def by (simp add: nstate_rel_update_const) lemma nstate_old_rel_update: "nstate_old_rel \<Lambda> \<Lambda>' R ns1 ns2 \<Longrightarrow> nstate_old_rel \<Lambda> \<Lambda>' R (update_var \<Lambda> ns1 x v) ns2" unfolding nstate_old_rel_def update_var_def by (simp split: option.split) lemma nstate_old_rel_states_update: "nstate_old_rel_states \<Lambda> \<Lambda>' R ns1 U \<Longrightarrow> nstate_old_rel_states \<Lambda> \<Lambda>' R (update_var \<Lambda> ns1 x v) U" unfolding nstate_old_rel_states_def by (simp add: nstate_old_rel_update) lemma nstate_old_rel_states_subset: "U' \<subseteq> U \<Longrightarrow> nstate_old_rel_states \<Lambda> \<Lambda>' R ns1 U \<Longrightarrow> nstate_old_rel_states \<Lambda> \<Lambda>' R ns1 U'" by (auto simp add: nstate_old_rel_states_def) definition update_nstate_rel where "update_nstate_rel R upds = R ((map fst upds) [\<mapsto>] (map snd upds))" lemma lookup_nstate_rel: "R x = Some (Inl y) \<Longrightarrow> nstate_rel \<Lambda> \<Lambda>' R ns u \<Longrightarrow> rel_well_typed A \<Lambda> \<Omega> R ns \<Longrightarrow> lookup_var \<Lambda>' u y = Some (the (lookup_var \<Lambda> ns x))" unfolding nstate_rel_def rel_well_typed_def using option.exhaust_sel by force lemma lookup_nstates_rel: "u \<in> U \<Longrightarrow> nstate_rel_states \<Lambda> \<Lambda>' R ns U \<Longrightarrow> rel_well_typed A \<Lambda> \<Omega> R ns \<Longrightarrow> R x = Some (Inl y) \<Longrightarrow> lookup_var \<Lambda>' u y = Some (the (lookup_var \<Lambda> ns x))" unfolding nstate_rel_states_def using lookup_nstate_rel by blast lemma update_var_nstate_rel: assumes Srel:"nstate_rel \<Lambda> \<Lambda>' R ns1 ns2" and "lookup_var \<Lambda>' ns2 x = Some v" shows "nstate_rel \<Lambda> \<Lambda>' (R(y \<mapsto> (Inl x))) (update_var \<Lambda> ns1 y v) ns2" proof (simp only: nstate_rel_def, rule conjI, rule allI, rule allI, rule impI) fix z1 z2 assume Map:"(R(y \<mapsto> (Inl x))) z1 = Some (Inl z2)" show "lookup_var \<Lambda> (update_var \<Lambda> ns1 y v) z1 = lookup_var \<Lambda>' ns2 z2" proof (cases "z1 = y") case True then show ?thesis using Map \<open>lookup_var \<Lambda>' ns2 x = Some v\<close> by simp next case False then show ?thesis using Map Srel by (metis map_upd_Some_unfold nstate_rel_def update_var_other) qed next show "binder_state (update_var \<Lambda> ns1 y v) = binder_state ns2" using Srel by (simp add: update_var_binder_same nstate_rel_def) qed lemma update_nstate_rel_cons: "update_nstate_rel (R(x \<mapsto> x2)) Q = update_nstate_rel R ((x,x2)#Q)" unfolding update_nstate_rel_def by simp lemma update_nstate_rel_nil: "update_nstate_rel R [] = R" by (simp add: update_nstate_rel_def) lemma update_rel_nstate_same_state: assumes Srel: "nstate_rel \<Lambda> \<Lambda>' R ns1 ns2" and "R x = Some (Inl x1)" and LookupEq:"lookup_var \<Lambda>' ns2 x1 = lookup_var \<Lambda>' ns2 x2" shows "nstate_rel \<Lambda> \<Lambda>' (R(x \<mapsto> (Inl x2))) ns1 ns2" proof (unfold nstate_rel_def, rule+) fix arg y assume "(R(x \<mapsto> (Inl x2))) arg = Some (Inl y)" thus "lookup_var \<Lambda> ns1 arg = lookup_var \<Lambda>' ns2 y" using Srel \<open>R x = Some (Inl x1)\<close> LookupEq by (metis fun_upd_apply nstate_rel_def option.sel sum.inject(1)) next from Srel show "binder_state ns1 = binder_state ns2" by (simp add: nstate_rel_def) qed lemma update_rel_nstate_same_state_const: assumes Srel: "nstate_rel \<Lambda> \<Lambda>' R ns1 ns2" and Lookup1:"lookup_var \<Lambda> ns1 x = Some (LitV l)" and Lookup2:"lookup_var \<Lambda>' ns2 x2 = Some (LitV l)" shows "nstate_rel \<Lambda> \<Lambda>' (R(x \<mapsto> (Inl x2))) ns1 ns2" proof (unfold nstate_rel_def, rule+) fix arg y assume "(R(x \<mapsto> (Inl x2))) arg = Some (Inl y)" thus "lookup_var \<Lambda> ns1 arg = lookup_var \<Lambda>' ns2 y" using Srel Lookup1 Lookup2 by (metis (no_types, lifting) map_upd_Some_unfold nstate_rel_def sum.inject(1)) next from Srel show "binder_state ns1 = binder_state ns2" by (simp add: nstate_rel_def) qed lemma binder_update_nstate_rel: "nstate_rel \<Lambda> \<Lambda>' R ns1 ns2 \<Longrightarrow> (\<And>v. nstate_rel \<Lambda> \<Lambda>' R (full_ext_env ns1 v) (full_ext_env ns2 v))" unfolding nstate_rel_def apply (simp only: lookup_full_ext_env_same) by (simp add: binder_full_ext_env_same) lemma binder_update_nstate_old_rel: "nstate_old_rel \<Lambda> \<Lambda>' R ns1 ns2 \<Longrightarrow> (\<And>v. nstate_old_rel \<Lambda> \<Lambda>' R (full_ext_env ns1 v) (full_ext_env ns2 v))" unfolding nstate_old_rel_def apply (simp only: lookup_full_ext_env_same) by (simp add: binder_full_ext_env_same) lemma binder_update_rel_const: "rel_const_correct \<Lambda> \<Omega> R ns \<Longrightarrow> (\<And>v. rel_const_correct \<Lambda> \<Omega> R (full_ext_env ns v))" unfolding rel_const_correct_def by (simp only: lookup_full_ext_env_same) auto lemma binder_update_rel_const_value: "rel_const_correct_value \<Lambda> R ns \<Longrightarrow> (\<And>v. rel_const_correct_value \<Lambda> R (full_ext_env ns v))" unfolding rel_const_correct_value_def by (simp only: lookup_full_ext_env_same) auto subsection \<open>Expression relation\<close> text \<open>In the following, we define definitions and lemmas to help relate expressions in the non-passified and passified programs. \<^term>\<open>e1\<close> and \<^term>\<open>e2\<close> usually represent non-passive and passive expressions respectively.\<close> fun push_old_expr :: "bool \<Rightarrow> expr \<Rightarrow> expr" where "push_old_expr True (Var x) = Old (Var x)" | "push_old_expr False (Var x) = (Var x)" | "push_old_expr _ (BVar i) = BVar i" | "push_old_expr _ (Lit l) = Lit l" | "push_old_expr b (UnOp unop e) = UnOp unop (push_old_expr b e)" | "push_old_expr b (e1 \<guillemotleft>bop\<guillemotright> e2) = (push_old_expr b e1) \<guillemotleft>bop\<guillemotright> (push_old_expr b e2)" | "push_old_expr b (FunExp f ts args) = FunExp f ts (map (push_old_expr b) args)" | "push_old_expr b (CondExp cond thn els) = CondExp (push_old_expr b cond) (push_old_expr b thn) (push_old_expr b els)" | "push_old_expr b (Old e) = push_old_expr True e" | "push_old_expr b (Forall ty e) = Forall ty (push_old_expr b e)" | "push_old_expr b (Exists ty e) = Exists ty (push_old_expr b e)" | "push_old_expr b (ForallT e) = ForallT (push_old_expr b e)" | "push_old_expr b (ExistsT e) = ExistsT (push_old_expr b e)" text \<open>\<^term>\<open>push_old_expr\<close> pushes "Old" as far as possible inside. We will use this later to relate an expression in the non-passified program (which may contain old expressions) with a passified expression. It will allow us to only have to relate expressions of the form "Old(Var x)" with "Var y".\<close> lemma push_old_true_same: "A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>e, ns\<rangle> \<Down> v \<Longrightarrow> ns = ns'\<lparr>global_state := old_global_state ns'\<rparr> \<Longrightarrow> A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>push_old_expr True e, ns'\<rangle> \<Down> v" and "A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>es, ns\<rangle> [\<Down>] vs \<Longrightarrow> ns = ns'\<lparr>global_state := old_global_state ns'\<rparr> \<Longrightarrow> A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>map (push_old_expr True) es, ns'\<rangle> [\<Down>] vs" by (induction arbitrary: ns' and ns' rule: red_expr_red_exprs.inducts, auto intro: red_expr_red_exprs.intros) lemma push_old_false_same: "A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>e, ns\<rangle> \<Down> v \<Longrightarrow> A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>push_old_expr False e, ns\<rangle> \<Down> v" and "A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>es, ns\<rangle> [\<Down>] vs \<Longrightarrow> A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>map (push_old_expr False) es, ns\<rangle> [\<Down>] vs" proof (induction rule: red_expr_red_exprs.inducts) case (RedOld \<Omega> e n_s v) thus ?case apply simp apply (erule push_old_true_same) by simp qed (auto intro: red_expr_red_exprs.intros) fun is_not_var :: "expr \<Rightarrow> bool" where "is_not_var (Var _) = False" | "is_not_var _ = True" text \<open>The following inductive definition is used to relate non-passified with passified expressions. We mainly require a relationship between the variables.\<close> text \<open> R: active variable relation, R_old: old global variable to passive variable relation, loc_vars: parameters and locals \<close> inductive expr_rel :: "passive_rel \<Rightarrow> passive_rel \<Rightarrow> vdecls \<Rightarrow> expr \<Rightarrow> expr \<Rightarrow> bool" and expr_list_rel :: "passive_rel \<Rightarrow> passive_rel \<Rightarrow> vdecls \<Rightarrow> expr list \<Rightarrow> expr list \<Rightarrow> bool" for R :: passive_rel and R_old :: passive_rel and loc_vars :: vdecls where Var_Rel: "R x1 = Some (Inl x2) \<Longrightarrow> expr_rel R R_old loc_vars (Var x1) (Var x2)" | Var_Const_Rel: "R x1 = Some (Inr l) \<Longrightarrow> expr_rel R R_old loc_vars (Var x1) (Lit l)" | BVar_Rel: "expr_rel R R_old loc_vars (BVar i) (BVar i)" | Lit_Rel: "expr_rel R R_old loc_vars (Lit lit) (Lit lit)" | UnOp_Rel: "expr_rel R R_old loc_vars e1 e2 \<Longrightarrow> expr_rel R R_old loc_vars (UnOp uop e1) (UnOp uop e2)" | BinOp_Rel: "\<lbrakk> expr_rel R R_old loc_vars e11 e21; expr_rel R R_old loc_vars e12 e22 \<rbrakk> \<Longrightarrow> expr_rel R R_old loc_vars (e11 \<guillemotleft>bop\<guillemotright> e12) (e21 \<guillemotleft>bop\<guillemotright> e22)" | FunExp_Rel: "\<lbrakk> expr_list_rel R R_old loc_vars args1 args2 \<rbrakk> \<Longrightarrow> expr_rel R R_old loc_vars (FunExp f ts args1) (FunExp f ts args2)" | CondExp_rel: "\<lbrakk> expr_rel R R_old loc_vars cond1 cond2; expr_rel R R_old loc_vars thn1 thn2; expr_rel R R_old loc_vars els1 els2 \<rbrakk> \<Longrightarrow> expr_rel R R_old loc_vars (CondExp cond1 thn1 els1) (CondExp cond2 thn2 els2)" | OldGlobalVar_Rel: "\<lbrakk>R_old x = Some (Inl y)\<rbrakk> \<Longrightarrow> expr_rel R R_old loc_vars (Old (Var x)) (Var y)" | OldLocalVar_Rel: "\<lbrakk>map_of loc_vars x = Some v; expr_rel R R_old loc_vars (Var x) (Var y)\<rbrakk> \<Longrightarrow> expr_rel R R_old loc_vars (Old (Var x)) (Var y)" | OldExp_Rel: "\<lbrakk> is_not_var e1; expr_rel R R_old loc_vars (push_old_expr False (Old e1)) e2 \<rbrakk> \<Longrightarrow> expr_rel R R_old loc_vars (Old e1) e2" | Forall_Rel: "\<lbrakk> expr_rel R R_old loc_vars e1 e2 \<rbrakk> \<Longrightarrow> expr_rel R R_old loc_vars (Forall ty e1) (Forall ty e2)" | Exists_Rel: "\<lbrakk> expr_rel R R_old loc_vars e1 e2 \<rbrakk> \<Longrightarrow> expr_rel R R_old loc_vars (Exists ty e1) (Exists ty e2)" | ForallT_Rel: "\<lbrakk> expr_rel R R_old loc_vars e1 e2 \<rbrakk> \<Longrightarrow> expr_rel R R_old loc_vars (ForallT e1) (ForallT e2)" | ExistsT_Rel: "\<lbrakk> expr_rel R R_old loc_vars e1 e2 \<rbrakk> \<Longrightarrow> expr_rel R R_old loc_vars (ExistsT e1) (ExistsT e2)" | Nil_Rel: "expr_list_rel R R_old loc_vars [] []" | Cons_Rel: "\<lbrakk>expr_rel R R_old loc_vars x y; expr_list_rel R R_old loc_vars xs ys\<rbrakk> \<Longrightarrow> expr_list_rel R R_old loc_vars (x#xs) (y#ys)" text \<open>Eisbach tactic to prove two expressions are in the expression relation\<close> method expr_rel_tac uses R_def R_old_def LocVar_assms = (match conclusion in "expr_rel ?R ?R_old ?loc_vars (Var ?x1) (Var ?x2)" \<Rightarrow> \<open>rule Var_Rel, solves \<open>simp add: R_def\<close>\<close> \<bar> "expr_rel ?R ?R_old ?loc_vars (Var ?x1) (Lit ?l)" \<Rightarrow> \<open>rule Var_Const_Rel, solves \<open>simp add: R_def\<close>\<close> \<bar> "expr_rel ?R ?R_old ?loc_vars (Old (Var ?x1)) ?e2" \<Rightarrow> \<open>rule OldGlobalVar_Rel, solves \<open>simp add: R_old_def\<close> | rule OldLocalVar_Rel, solves \<open>simp only: snd_conv LocVar_assms\<close>\<close> \<bar> "expr_rel ?R ?R_old ?loc_vars (Old ?e1) ?e2" \<Rightarrow> \<open>rule OldExp_Rel, solves \<open>simp\<close>, simp\<close> \<bar> "expr_rel ?R ?R_old ?loc_vars ?e1 ?e2" \<Rightarrow> rule \<bar> "expr_list_rel ?R ?R_old ?loc_vars ?es1 ?es2" \<Rightarrow> rule \<bar> "_" \<Rightarrow> fail)+ lemma old_global_var_red: assumes "A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>Old (Var x),ns\<rangle> \<Down> v" and "map_of (snd \<Lambda>) x = None" shows "v = the (old_global_state ns x)" using assms apply cases by (auto split: option.split simp: lookup_var_def) lemma old_local_var_red_2: assumes "A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>Old (Var x),ns\<rangle> \<Down> v" and A2:"map_of (snd \<Lambda>) x \<noteq> None" shows "v = the (local_state ns x)" using assms apply cases apply (erule RedVar_case) by (auto split: option.split simp: lookup_var_def) lemma old_local_var_red: assumes "A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>Old (Var x),ns\<rangle> \<Down> v" and A2:"map_of (snd \<Lambda>) x \<noteq> None" shows "A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>Var x,ns\<rangle> \<Down> v" (* using old_local_var_red[OF assms] *) using assms apply cases apply (erule RedVar_case) by (metis RedVar lookup_var_def nstate.ext_inject nstate.surjective nstate.update_convs(2) option.case_eq_if) text \<open>The following lemma proves that if we can show two expressions are related by \<^term>\<open>expr_rel\<close> (the non-passive and passive versions) w.r.t. some variable relation R and one has two states that are related also related to R, then the two expression evaluate to the same value.\<close> lemma expr_rel_same: shows "expr_rel R R_old (snd \<Lambda>) e1 e2 \<Longrightarrow> rel_const_correct_value \<Lambda> R ns1 \<Longrightarrow> nstate_rel \<Lambda> \<Lambda>' R ns1 ns2 \<Longrightarrow> nstate_old_rel \<Lambda> \<Lambda>' R_old ns1 ns2 \<Longrightarrow> A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>e1, ns1\<rangle> \<Down> v \<Longrightarrow> A,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>e2, ns2\<rangle> \<Down> v" and "expr_list_rel R R_old (snd \<Lambda>) es1 es2 \<Longrightarrow> rel_const_correct_value \<Lambda> R ns1 \<Longrightarrow> nstate_rel \<Lambda> \<Lambda>' R ns1 ns2 \<Longrightarrow> nstate_old_rel \<Lambda> \<Lambda>' R_old ns1 ns2 \<Longrightarrow> A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>es1, ns1\<rangle> [\<Down>] vs \<Longrightarrow> A,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>es2, ns2\<rangle> [\<Down>] vs" proof (induction arbitrary: v ns1 ns2 \<Omega> and vs ns1 ns2 \<Omega> rule: expr_rel_expr_list_rel.inducts) next case (OldGlobalVar_Rel x y) from \<open>R_old x = Some (Inl y)\<close> and \<open>nstate_old_rel \<Lambda> \<Lambda>' R_old ns1 ns2\<close> show ?case using old_global_var_red[OF \<open>A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>Old (Var x),ns1\<rangle> \<Down> v\<close>] by (metis RedVar nstate_old_rel_def option.sel) next case (OldLocalVar_Rel x v') thus ?case using old_local_var_red[OF \<open> A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>Old (Var x),ns1\<rangle> \<Down> v\<close>] \<open>map_of (snd \<Lambda>) x = Some v'\<close> by auto next case (OldExp_Rel e1 e2) thus ?case using push_old_false_same by (metis (full_types)) next case (Var_Rel x1 x2) thus ?case by (auto intro: red_expr_red_exprs.intros simp: nstate_rel_def) next case (Var_Const_Rel x1 l) then show ?case by (auto intro: red_expr_red_exprs.intros simp: rel_const_correct_value_def) next case (BVar_Rel x1 x2) thus ?case by (auto intro: red_expr_red_exprs.intros simp: nstate_rel_def) next case (Lit_Rel lit) then show ?case by (blast intro: red_expr_red_exprs.intros ) next case (UnOp_Rel e1 e2 uop) then show ?case by (blast intro: red_expr_red_exprs.intros) next case (BinOp_Rel e11 e21 e12 e22 bop) then show ?case by (blast intro: red_expr_red_exprs.intros) next case (FunExp_Rel args1 args2 f ts) then show ?case by (blast intro: red_expr_red_exprs.intros) next case (CondExp_rel cond1 cond2 thn1 thn2 els1 els2) then show ?case by (blast intro: red_expr_red_exprs.intros) next case (Forall_Rel e1 e2 ty) hence RelExt:"\<And>v. nstate_rel \<Lambda> \<Lambda>' R (full_ext_env ns1 v) (full_ext_env ns2 v)" using binder_update_nstate_rel by blast from Forall_Rel have RelOldExt: "\<And>v. nstate_old_rel \<Lambda> \<Lambda>' R_old (full_ext_env ns1 v) (full_ext_env ns2 v)" using binder_update_nstate_old_rel by blast from Forall_Rel have RelWtExt:"\<And>v. rel_const_correct_value \<Lambda> R (full_ext_env ns1 v)" using binder_update_rel_const_value by blast from \<open>A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>Forall ty e1,ns1\<rangle> \<Down> v\<close> show ?case by (cases; blast intro: red_expr_red_exprs.intros dest:Forall_Rel.IH(2)[OF RelWtExt RelExt RelOldExt]) next case (Exists_Rel e1 e2 ty) hence RelExt:"\<And>v. nstate_rel \<Lambda> \<Lambda>' R (full_ext_env ns1 v) (full_ext_env ns2 v)" using binder_update_nstate_rel by blast from Exists_Rel have RelOldExt: "\<And>v. nstate_old_rel \<Lambda> \<Lambda>' R_old (full_ext_env ns1 v) (full_ext_env ns2 v)" using binder_update_nstate_old_rel by blast from Exists_Rel have RelWtExt:"\<And>v. rel_const_correct_value \<Lambda> R (full_ext_env ns1 v)" using binder_update_rel_const_value by blast from \<open>A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>Exists ty e1,ns1\<rangle> \<Down> v\<close> show ?case by (cases; blast intro: red_expr_red_exprs.intros dest:Exists_Rel.IH(2)[OF RelWtExt RelExt RelOldExt]) next case (ForallT_Rel e1 e2) from \<open>A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>ForallT e1,ns1\<rangle> \<Down> v\<close> show ?case by cases (auto intro: red_expr_red_exprs.intros dest:ForallT_Rel.IH(2)[OF \<open>rel_const_correct_value \<Lambda> R ns1\<close> \<open>nstate_rel \<Lambda> \<Lambda>' R ns1 ns2\<close> \<open>nstate_old_rel \<Lambda> \<Lambda>' R_old ns1 ns2\<close>]) next case (ExistsT_Rel e1 e2) from \<open>A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>ExistsT e1,ns1\<rangle> \<Down> v\<close> show ?case by cases (auto intro: red_expr_red_exprs.intros dest: ExistsT_Rel.IH(2)[OF \<open>rel_const_correct_value \<Lambda> R ns1\<close> \<open>nstate_rel \<Lambda> \<Lambda>' R ns1 ns2\<close> \<open>nstate_old_rel \<Lambda> \<Lambda>' R_old ns1 ns2\<close>]) next case Nil_Rel then show ?case using RedExpListNil by blast next case (Cons_Rel x y xs ys) thus ?case by (blast elim: cons_exp_elim2 intro: red_expr_red_exprs.intros) qed lemma rel_const_correct_to_value:"rel_const_correct \<Lambda> \<Omega> R ns1 \<Longrightarrow> rel_const_correct_value \<Lambda> R ns1" unfolding rel_const_correct_def rel_const_correct_value_def by simp lemma expr_rel_same_set: assumes "expr_rel R R_old (snd \<Lambda>) e1 e2" and "A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>e1, ns1\<rangle> \<Down> v" and "rel_const_correct \<Lambda> \<Omega> R ns1" and "nstate_rel_states \<Lambda> \<Lambda>' R ns1 U" and "nstate_old_rel_states \<Lambda> \<Lambda>' R_old ns1 U" shows "\<forall>u \<in> U. A,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>e2, u\<rangle> \<Down> v" using assms expr_rel_same(1) unfolding nstate_rel_states_def nstate_old_rel_states_def by (metis rel_const_correct_to_value) subsection \<open>Properties on command reduction lifted to sets\<close> fun isPassive :: "cmd \<Rightarrow> bool" where "isPassive (Assign _ _) = False" | "isPassive (Havoc _) = False" | "isPassive (ProcCall _ _ _) = False" | "isPassive _ = True" lemma passive_state_same: assumes Apassive:"isPassive c" and Ared:"A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>c, Normal ns\<rangle> \<rightarrow> Normal ns'" shows "ns' = ns" using Ared Apassive by (cases, auto) lemma passive_states_propagate: assumes "isPassive c" shows "\<forall>ns' \<in> {ns'. Normal ns' \<in> (set_red_cmd A M \<Lambda> \<Gamma> \<Omega> c U)}. A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>c, Normal ns'\<rangle> \<rightarrow> Normal ns'" proof fix ns' assume "ns' \<in> {ns''. Normal ns'' \<in> (set_red_cmd A M \<Lambda> \<Gamma> \<Omega> c U)}" hence "Normal ns' \<in> (set_red_cmd A M \<Lambda> \<Gamma> \<Omega> c U)" by simp from this obtain ns where "A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>c, Normal ns\<rangle> \<rightarrow> Normal ns'" by (auto simp add: set_red_cmd_def) moreover from this have "ns' = ns" by (rule passive_state_same[OF \<open>isPassive c\<close>]) ultimately show "A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>c,Normal ns'\<rangle> \<rightarrow> Normal ns'" by simp qed lemma passive_states_propagate_2: assumes "isPassive c" and "ns \<in> {ns'. Normal ns' \<in> (set_red_cmd A M \<Lambda> \<Gamma> \<Omega> c U)}" shows "A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>c, Normal ns\<rangle> \<rightarrow> Normal ns" using assms by (simp add: passive_states_propagate) lemma passive_states_subset: assumes "isPassive c" shows "{ns'. Normal ns' \<in> (set_red_cmd A M \<Lambda> \<Gamma> \<Omega> c U)} \<subseteq> U" proof fix ns assume "ns \<in> {ns'. Normal ns' \<in> (set_red_cmd A M \<Lambda> \<Gamma> \<Omega> c U)}" from this obtain ns0 where "ns0 \<in> U" and "A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>c, Normal ns0\<rangle> \<rightarrow> Normal ns" unfolding set_red_cmd_def by auto moreover from this have "ns0 = ns" using passive_state_same[OF \<open>isPassive c\<close>] by blast ultimately show "ns \<in> U" by simp qed lemma assume_assign_dependent: assumes DepU:"dependent A \<Lambda> \<Omega> U D" and "x \<notin> D" and Ared:"\<forall>ns' \<in> U. A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>e2, ns'\<rangle> \<Down> v" shows "dependent A \<Lambda> \<Omega> {ns'. Normal ns' \<in> (set_red_cmd A M \<Lambda> \<Gamma> \<Omega> (Assume ((Var x) \<guillemotleft>Eq\<guillemotright> e2)) U)} (D \<union> {x})" (is "dependent A \<Lambda> \<Omega> ?U' (D \<union> {x})") using assms proof - have Apassive:"isPassive (Assume ((Var x) \<guillemotleft>Eq\<guillemotright> e2))" by simp show "dependent A \<Lambda> \<Omega> ?U' (D \<union> {x})" unfolding dependent_def closed_set_ty_def proof (rule ballI, rule allI, rule allI, rule impI, rule conjI[OF _ impI[OF allI[OF impI]]]) fix u' d \<tau> assume "u' \<in> ?U'" assume LookupD:"lookup_var_ty \<Lambda> d = Some \<tau>" assume "u' \<in> ?U'" hence "u' \<in> U" using passive_states_subset isPassive.simps by blast thus "lookup_var_ty_match A \<Lambda> \<Omega> u' d \<tau>" using DepU LookupD unfolding dependent_def lookup_var_ty_match_def by simp next fix u' y \<tau> w assume "u' \<in> ?U'" hence "u' \<in> U" using passive_states_subset isPassive.simps by blast from this have "A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>e2, u'\<rangle> \<Down> v" using Ared by auto from \<open>u' \<in> ?U'\<close> have "A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>Assume (Var x \<guillemotleft>Eq\<guillemotright> e2), Normal u'\<rangle> \<rightarrow> Normal u'" using passive_states_propagate_2[OF Apassive] by blast from this obtain v' where "A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>Var x, u'\<rangle> \<Down> v'" and "A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>e2, u'\<rangle> \<Down> v'" apply cases apply (erule RedBinOp_case) by auto hence "A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>Var x, u'\<rangle> \<Down> v" using expr_eval_determ(1)[OF \<open>A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>e2, u'\<rangle> \<Down> v\<close>] by auto hence "lookup_var \<Lambda> u' x = Some v" by auto moreover assume "y \<notin> (D \<union> {x})" ultimately have "A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>Var x, (update_var \<Lambda> u' y w)\<rangle> \<Down> v" by (auto intro: RedVar) assume \<open>lookup_var_ty \<Lambda> y = Some \<tau>\<close> and \<open>type_of_val A w = instantiate \<Omega> \<tau>\<close> with \<open>u' \<in> U\<close> \<open>y \<notin> (D \<union> {x})\<close> have "(update_var \<Lambda> u' y w) \<in> U" using DepU by (simp add: dependent_def closed_set_ty_def) hence "A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>e2, update_var \<Lambda> u' y w\<rangle> \<Down> v" using Ared by auto with \<open>update_var \<Lambda> u' y w \<in> U\<close> \<open>A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>Var x, (update_var \<Lambda> u' y w)\<rangle> \<Down> v\<close> show "update_var \<Lambda> u' y w \<in> ?U'" by (auto intro!: red_cmd.intros red_expr_red_exprs.intros simp: set_red_cmd_def) qed qed lemma assume_assign_non_empty: assumes Ared:"\<forall>ns' \<in> U. A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>e2, ns'\<rangle> \<Down> v" and TypeVal: "type_of_val A v = instantiate \<Omega> \<tau>" and LookupTy:"lookup_var_ty \<Lambda> x = Some \<tau>" "U \<noteq> {}" and DepU:"dependent A \<Lambda> \<Omega> U D" and "x \<notin> D" shows "{ns'. Normal ns' \<in> (set_red_cmd A M \<Lambda> \<Gamma> \<Omega> (Assume ((Var x) \<guillemotleft>Eq\<guillemotright> e2)) U)} \<noteq> {}" (is "?U' \<noteq> {}") proof - from Ared \<open>U \<noteq> {}\<close> obtain u where "u \<in> U" and "A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>e2, u\<rangle> \<Down> v" by auto with \<open>x \<notin> D\<close> DepU TypeVal LookupTy have "update_var \<Lambda> u x v \<in> U" by (auto simp: dependent_def lookup_var_ty_match_def closed_set_ty_def) moreover from this have "A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>e2,update_var \<Lambda> u x v\<rangle> \<Down> v" by (auto simp: Ared) ultimately have "update_var \<Lambda> u x v \<in> ?U'" by (auto intro!: red_cmd.intros red_expr_red_exprs.intros simp: set_red_cmd_def) thus ?thesis by auto qed lemma assume_reduction_args: assumes "ns'\<in> {ns'. Normal ns' \<in> (set_red_cmd A M \<Lambda> \<Gamma> \<Omega> (Assume ((Var x) \<guillemotleft>Eq\<guillemotright> e2)) U)}" (is "ns' \<in> ?U'") shows "\<exists>v. (A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>Var x, ns'\<rangle> \<Down> v) \<and> (A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>e2, ns'\<rangle> \<Down> v)" proof - have Apassive:"isPassive (Assume ((Var x) \<guillemotleft>Eq\<guillemotright> e2))" by simp from \<open>ns' \<in> ?U'\<close> have "A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>Assume (Var x \<guillemotleft>Eq\<guillemotright> e2), Normal ns'\<rangle> \<rightarrow> Normal ns'" using passive_states_propagate_2[OF Apassive] by blast thus ?thesis apply (cases) apply (erule RedBinOp_case, rule, auto) done qed lemma assume_sync_nstate_rel: assumes "R x_orig = Some (Inl x1)" and Srel:"nstate_rel_states \<Lambda> \<Lambda>' R ns U" and Rel_wt: "rel_well_typed A \<Lambda> \<Omega> R ns" shows "nstate_rel_states \<Lambda> \<Lambda>' (R(x_orig \<mapsto> (Inl x2))) ns {ns'. Normal ns' \<in> (set_red_cmd A M \<Lambda>' \<Gamma> \<Omega> (Assume ((Var x2) \<guillemotleft>Eq\<guillemotright> (Var x1))) U)}" (is "nstate_rel_states \<Lambda> \<Lambda>' (R(x_orig \<mapsto> (Inl x2))) ns ?U'") proof (unfold nstate_rel_states_def, rule ballI) have Apassive:"isPassive (Assume ((Var x2) \<guillemotleft>Eq\<guillemotright> (Var x1)))" by simp fix u' assume "u' \<in> ?U'" hence "u' \<in> U" using passive_states_subset[OF Apassive] by blast with Srel have "nstate_rel \<Lambda> \<Lambda>' R ns u'" by (simp add: nstate_rel_states_def) let ?v = "(the (lookup_var \<Lambda> ns x_orig))" have "A,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>Var x1, u'\<rangle> \<Down> ?v" using lookup_nstate_rel[OF \<open>R x_orig = Some (Inl x1)\<close> \<open>nstate_rel \<Lambda> \<Lambda>' R ns u'\<close> Rel_wt] by (auto intro: RedVar) hence Lookup1:"lookup_var \<Lambda>' u' x1 = Some ?v" by auto from \<open>u' \<in> ?U'\<close> have "A,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>Var x2, u'\<rangle> \<Down> ?v" using expr_eval_determ(1)[OF \<open>A,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>Var x1, u'\<rangle> \<Down> ?v\<close>] assume_reduction_args by metis hence "lookup_var \<Lambda>' u' x2 = Some ?v" by auto thus "nstate_rel \<Lambda> \<Lambda>' (R(x_orig \<mapsto> (Inl x2))) ns u'" using Lookup1 update_rel_nstate_same_state[OF \<open>nstate_rel \<Lambda> \<Lambda>' R ns u'\<close> \<open>R x_orig = Some (Inl x1)\<close>] by simp qed lemma assume_sync_const_nstate_rel: assumes "R x_orig = Some (Inr l)" and Srel:"nstate_rel_states \<Lambda> \<Lambda>' R ns U" and Rel_wt: "rel_well_typed A \<Lambda> \<Omega> R ns" shows "nstate_rel_states \<Lambda> \<Lambda>' (R(x_orig \<mapsto> (Inl x2))) ns {ns'. Normal ns' \<in> (set_red_cmd A M \<Lambda>' \<Gamma> \<Omega> (Assume ((Var x2) \<guillemotleft>Eq\<guillemotright> (Lit l))) U)}" (is "nstate_rel_states \<Lambda> \<Lambda>' (R(x_orig \<mapsto> (Inl x2))) ns ?U'") proof (unfold nstate_rel_states_def, rule ballI) have Apassive:"isPassive (Assume ((Var x2) \<guillemotleft>Eq\<guillemotright> (Lit l)))" by simp fix u' assume "u' \<in> ?U'" hence "u' \<in> U" using passive_states_subset[OF Apassive] by blast with Srel have "nstate_rel \<Lambda> \<Lambda>' R ns u'" by (simp add: nstate_rel_states_def) have "A,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>Lit l, u'\<rangle> \<Down> (LitV l)" by (rule RedLit) from \<open>u' \<in> ?U'\<close> have "A,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>Var x2, u'\<rangle> \<Down> (LitV l)" using expr_eval_determ(1)[OF \<open>A,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>Lit l, u'\<rangle> \<Down> LitV l\<close>] assume_reduction_args by metis hence LookupX2:"lookup_var \<Lambda>' u' x2 = Some (LitV l)" by auto from Rel_wt and \<open>R x_orig = Some (Inr l)\<close> have LookupOrig:"lookup_var \<Lambda> ns x_orig = Some (LitV l)" unfolding rel_well_typed_def rel_const_correct_def by simp thus "nstate_rel \<Lambda> \<Lambda>' (R(x_orig \<mapsto> (Inl x2))) ns u'" using update_rel_nstate_same_state_const[OF \<open>nstate_rel \<Lambda> \<Lambda>' R ns u'\<close>] LookupOrig LookupX2 by blast qed lemma assume_assign_nstate_rel: assumes Erel:"expr_rel R R_old (snd \<Lambda>) e1 e2" and "A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>e1, ns\<rangle> \<Down> v" and Rel:"nstate_rel_states \<Lambda> \<Lambda>' R ns U" and OldRel: "nstate_old_rel_states \<Lambda> \<Lambda>' R_old ns U" and CRel:"rel_const_correct \<Lambda> \<Omega> R ns" shows "nstate_rel_states \<Lambda> \<Lambda>' (R(x_orig \<mapsto> (Inl x))) (update_var \<Lambda> ns x_orig v) {ns'. Normal ns' \<in> (set_red_cmd A M \<Lambda>' \<Gamma> \<Omega> (Assume ((Var x) \<guillemotleft>Eq\<guillemotright> e2)) U)}" (is "nstate_rel_states \<Lambda> \<Lambda>' (R(x_orig \<mapsto> (Inl x))) (update_var \<Lambda> ns x_orig v) ?U'") proof (unfold nstate_rel_states_def, rule ballI) have Apassive:"isPassive (Assume ((Var x) \<guillemotleft>Eq\<guillemotright> e2))" by simp fix u' assume "u' \<in> ?U'" hence "u' \<in> U" using passive_states_subset[OF Apassive] by blast with Rel have Rel2:"nstate_rel \<Lambda> \<Lambda>' R ns u'" by (simp add: nstate_rel_states_def) from \<open>u' \<in> U\<close> and OldRel have OldRel2:"nstate_old_rel \<Lambda> \<Lambda>' R_old ns u'" by (simp add: nstate_old_rel_states_def) have "A,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>e2, u'\<rangle> \<Down> v" using expr_rel_same(1)[OF Erel _ Rel2 OldRel2 \<open>A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>e1, ns\<rangle> \<Down> v\<close>] using CRel using rel_const_correct_to_value by blast from \<open>u' \<in> ?U'\<close> have "A,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>Var x, u'\<rangle> \<Down> v" using expr_eval_determ(1)[OF \<open>A,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>e2, u'\<rangle> \<Down> v\<close>] assume_reduction_args by metis hence "lookup_var \<Lambda>' u' x = Some v" by auto from this show "nstate_rel \<Lambda> \<Lambda>' (R(x_orig \<mapsto> (Inl x))) (update_var \<Lambda> ns x_orig v) u'" by (rule update_var_nstate_rel[OF \<open>nstate_rel \<Lambda> \<Lambda>' R ns u'\<close>]) qed lemma single_assign_reduce: "A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>Assign x e, Normal n_s\<rangle> \<rightarrow> s' \<Longrightarrow> \<exists>v. A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>e, n_s\<rangle> \<Down> v" by (erule red_cmd.cases; auto) lemma single_assign_reduce_2: "A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>Assign x e, Normal n_s\<rangle> \<rightarrow> s' \<Longrightarrow> (\<exists>v \<tau>. (lookup_var_ty \<Lambda> x = Some \<tau>) \<and> (A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>e, n_s\<rangle> \<Down> v) \<and> type_of_val A v = instantiate \<Omega> \<tau>)" by (erule red_cmd.cases) auto lemma single_assign_reduce_lit: "A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>Assign x (Lit l), Normal n_s\<rangle> \<rightarrow> s' \<Longrightarrow> \<exists>\<tau>. lookup_var_ty \<Lambda> x = Some \<tau> \<and> (TPrim (type_of_lit l)) = instantiate \<Omega> \<tau>" by (erule red_cmd.cases) auto lemma assume_rel_normal: assumes Ared:"A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>e1, ns\<rangle> \<Down> (BoolV True)" and Srel:"nstate_rel_states \<Lambda> \<Lambda>' R ns U" and OldRel: "nstate_old_rel_states \<Lambda> \<Lambda>' R_old ns U" and Crel:"rel_const_correct \<Lambda> \<Omega> R ns" and Erel:"expr_rel R R_old (snd \<Lambda>) e1 e2" shows "\<And>u. u \<in> U \<Longrightarrow> A,M,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>Assume e2, Normal u\<rangle> \<rightarrow> Normal u" proof - fix u assume "u \<in> U" with Srel OldRel have "nstate_rel \<Lambda> \<Lambda>' R ns u" and "nstate_old_rel \<Lambda> \<Lambda>' R_old ns u" by (auto simp: nstate_rel_states_def nstate_old_rel_states_def) with Ared Erel have "A,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>e2, u\<rangle> \<Down> (BoolV True)" using expr_rel_same(1) Crel rel_const_correct_to_value by metis thus "A,M,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>Assume e2,Normal u\<rangle> \<rightarrow> Normal u" by (auto intro: RedAssumeOk) qed lemma assume_rel_magic: assumes Ared:"A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>e1, ns\<rangle> \<Down> (BoolV False)" and Srel:"nstate_rel_states \<Lambda> \<Lambda>' R ns U" and OldRel: "nstate_old_rel_states \<Lambda> \<Lambda>' R_old ns U" and Crel:"rel_const_correct \<Lambda> \<Omega> R ns" and Erel:"expr_rel R R_old (snd \<Lambda>) e1 e2" shows "\<And>u. u \<in> U \<Longrightarrow> A,M,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>Assume e2, Normal u\<rangle> \<rightarrow> Magic" proof - fix u assume "u \<in> U" with Srel OldRel have "nstate_rel \<Lambda> \<Lambda>' R ns u" and "nstate_old_rel \<Lambda> \<Lambda>' R_old ns u" by (auto simp: nstate_rel_states_def nstate_old_rel_states_def) with Ared Erel have "A,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>e2, u\<rangle> \<Down> (BoolV False)" using expr_rel_same(1) Crel rel_const_correct_to_value by metis thus "A,M,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>Assume e2,Normal u\<rangle> \<rightarrow> Magic" by (auto intro: RedAssumeMagic) qed lemma assert_rel_normal: assumes Ared:"A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>e1, ns\<rangle> \<Down> (BoolV True)" and Srel:"nstate_rel_states \<Lambda> \<Lambda>' R ns U" and OldRel: "nstate_old_rel_states \<Lambda> \<Lambda>' R_old ns U" and Crel:"rel_const_correct \<Lambda> \<Omega> R ns" and Erel:"expr_rel R R_old (snd \<Lambda>) e1 e2" shows "{ns'. Normal ns' \<in> (set_red_cmd A M \<Lambda>' \<Gamma> \<Omega> (Assert e2) U)} = U" (is "?U' = U") proof have Apassive:"isPassive (Assert e2)" by simp show "?U' \<subseteq> U" by (rule passive_states_subset[OF Apassive]) next show "U \<subseteq> ?U'" proof fix u assume "u \<in> U" with Srel OldRel have "nstate_rel \<Lambda> \<Lambda>' R ns u" and "nstate_old_rel \<Lambda> \<Lambda>' R_old ns u" by (auto simp: nstate_rel_states_def nstate_old_rel_states_def) with Ared Erel have "A,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>e2, u\<rangle> \<Down> (BoolV True)" using expr_rel_same(1) Crel rel_const_correct_to_value by metis with \<open>u \<in> U\<close> show "u \<in> ?U'" by (auto intro!: red_cmd.intros simp: set_red_cmd_def) qed qed lemma assert_rel_normal_2: assumes Ared:"A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>e1, ns\<rangle> \<Down> (BoolV True)" and Srel:"nstate_rel_states \<Lambda> \<Lambda>' R ns U" and OldRel: "nstate_old_rel_states \<Lambda> \<Lambda>' R_old ns U" and Crel:"rel_const_correct \<Lambda> \<Omega> R ns" and Erel:"expr_rel R R_old (snd \<Lambda>) e1 e2" shows "\<And>u. u \<in> U \<Longrightarrow> A,M,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>Assert e2, Normal u\<rangle> \<rightarrow> Normal u" proof - fix u assume "u \<in> U" with Srel OldRel have "nstate_rel \<Lambda> \<Lambda>' R ns u" and "nstate_old_rel \<Lambda> \<Lambda>' R_old ns u" by (auto simp: nstate_rel_states_def nstate_old_rel_states_def) with Ared Erel have "A,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>e2, u\<rangle> \<Down> (BoolV True)" using expr_rel_same(1) Crel rel_const_correct_to_value by metis thus "A,M,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>Assert e2,Normal u\<rangle> \<rightarrow> Normal u" by (auto intro: RedAssertOk) qed lemma assert_rel_failure: assumes Ared:"A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>e1, ns\<rangle> \<Down> (BoolV False)" and Srel:"nstate_rel_states \<Lambda> \<Lambda>' R ns U" and OldRel: "nstate_old_rel_states \<Lambda> \<Lambda>' R_old ns U" and Crel:"rel_const_correct \<Lambda> \<Omega> R ns" and Erel:"expr_rel R R_old (snd \<Lambda>) e1 e2" shows "\<And>u. u \<in> U \<Longrightarrow> A,M,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>Assert e2, Normal u\<rangle> \<rightarrow> Failure" proof - fix u assume "u \<in> U" with Srel OldRel have "nstate_rel \<Lambda> \<Lambda>' R ns u" and "nstate_old_rel \<Lambda> \<Lambda>' R_old ns u" by (auto simp: nstate_rel_states_def nstate_old_rel_states_def) with Ared Erel have "A,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>e2, u\<rangle> \<Down> (BoolV False)" using expr_rel_same(1) Crel rel_const_correct_to_value by metis thus "A,M,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>Assert e2,Normal u\<rangle> \<rightarrow> Failure" by (auto intro: RedAssertFail) qed lemma havoc_nstate_rel: assumes Srel:"nstate_rel_states \<Lambda> \<Lambda>' R ns U" shows "nstate_rel_states \<Lambda> \<Lambda>' (R(x_orig \<mapsto> (Inl x2))) (update_var \<Lambda> ns x_orig v) {u' \<in> U. lookup_var \<Lambda>' u' x2 = Some v}" (is "nstate_rel_states \<Lambda> \<Lambda>' (R(x_orig \<mapsto> (Inl x2))) (update_var \<Lambda> ns x_orig v) ?U'") using assms unfolding nstate_rel_states_def by (simp add: update_var_nstate_rel) lemma havoc_dependent: assumes Dep: "dependent A \<Lambda> \<Omega> U D" and "x2 \<notin> D" shows "dependent A \<Lambda> \<Omega> {u' \<in> U. lookup_var \<Lambda> u' x2 = Some v} (D \<union> {x2})" using assms by (simp add: dependent_def lookup_var_ty_match_def closed_set_ty_def) lemma havoc_non_empty: assumes Dep: "dependent A \<Lambda> \<Omega> U D" and "U \<noteq> {}" and "x2 \<notin> D" and "lookup_var_ty \<Lambda> x2 = Some \<tau>" and "type_of_val A v = instantiate \<Omega> \<tau>" shows "{u' \<in> U. lookup_var \<Lambda> u' x2 = Some v} \<noteq> {}" using assms by (metis (mono_tags, lifting) dependent_def closed_set_ty_def empty_iff equals0I mem_Collect_eq update_var_same) subsection \<open>Command relation\<close> definition passive_sim where "passive_sim A M \<Lambda> \<Lambda>' \<Gamma> \<Omega> cs s' R R_old U \<equiv> (\<forall>u \<in> U. \<exists>su. (A,M,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>cs, Normal u\<rangle> [\<rightarrow>] su) \<and> (s' = Failure \<longrightarrow> su = Failure) \<and> (\<forall>ns'. s' = Normal ns' \<longrightarrow> (su = Normal u \<and> nstate_rel \<Lambda> \<Lambda>' R ns' u \<and> nstate_old_rel \<Lambda> \<Lambda>' R_old ns' u \<and> rel_well_typed A \<Lambda> \<Omega> R ns')))" text \<open>The following inductive definition relates non-passive with passive commands\<close> inductive passive_cmds_rel :: "vdecls \<Rightarrow> passive_rel \<Rightarrow> vname list \<Rightarrow> passive_rel \<Rightarrow> (vname \<times> (vname + lit)) list \<Rightarrow> cmd list \<Rightarrow> cmd list \<Rightarrow> bool" for loc_vars :: vdecls and R_old :: passive_rel where PAssignNormal: "\<lbrakk> expr_rel R R_old loc_vars e1 e2; passive_cmds_rel loc_vars R_old W (R(x1 \<mapsto> (Inl x2))) Q cs1 cs2 \<rbrakk> \<Longrightarrow> passive_cmds_rel loc_vars R_old (x2#W) R ((x1,(Inl x2))#Q) ((Assign x1 e1) # cs1) ((Assume ((Var x2) \<guillemotleft>Eq\<guillemotright> e2)) # cs2)" | PConst: " \<lbrakk> passive_cmds_rel loc_vars R_old W (R(x1 \<mapsto> (Inr l))) Q cs1 cs2 \<rbrakk> \<Longrightarrow> passive_cmds_rel loc_vars R_old W R ((x1, (Inr l))#Q) ((Assign x1 (Lit l))#cs1) cs2" | PConstVar: " \<lbrakk> R x1' = Some a; passive_cmds_rel loc_vars R_old W (R(x1 \<mapsto> a)) Q cs1 cs2 \<rbrakk> \<Longrightarrow> passive_cmds_rel loc_vars R_old W R ((x1, a)#Q) ((Assign x1 (Var x1'))#cs1) cs2" | PAssert: "\<lbrakk> expr_rel R R_old loc_vars e1 e2; passive_cmds_rel loc_vars R_old W R Q cs1 cs2 \<rbrakk> \<Longrightarrow> passive_cmds_rel loc_vars R_old W R Q ((Assert e1) # cs1) ((Assert e2) # cs2)" | PAssumeNormal: "\<lbrakk> expr_rel R R_old loc_vars e1 e2; passive_cmds_rel loc_vars R_old W R Q cs1 cs2 \<rbrakk> \<Longrightarrow> passive_cmds_rel loc_vars R_old W R Q ((Assume e1) # cs1) ((Assume e2) # cs2)" | PHavoc: "\<lbrakk> passive_cmds_rel loc_vars R_old W (R(x \<mapsto> (Inl x'))) Q cs1 cs2\<rbrakk> \<Longrightarrow> passive_cmds_rel loc_vars R_old (x'#W) R ((x,(Inl x'))#Q) ((Havoc x) # cs1) cs2" | PSync: "\<lbrakk> R x = Some (Inl x1); passive_cmds_rel loc_vars R_old W (R(x \<mapsto> (Inl x2))) Q [] cs \<rbrakk> \<Longrightarrow> passive_cmds_rel loc_vars R_old (x2#W) R ((x,(Inl x2))#Q) [] ((Assume ( (Var x2) \<guillemotleft>Eq\<guillemotright> (Var x1))) # cs)" | PSyncConst: "\<lbrakk> R x = Some (Inr l); passive_cmds_rel loc_vars R_old W (R(x \<mapsto> (Inl x2))) Q [] cs \<rbrakk> \<Longrightarrow> passive_cmds_rel loc_vars R_old (x2#W) R ((x,(Inl x2))#Q) [] ((Assume ( (Var x2) \<guillemotleft>Eq\<guillemotright> (Lit l))) # cs)" | PNil: "passive_cmds_rel loc_vars R_old [] R [] [] []" text \<open>Eisbach tactic for command relation\<close> method passive_rel_tac_single uses R_def R_old_def LocVar_assms = (match conclusion in "passive_cmds_rel ?loc_vars ?R_old ?W ?R ?Q ((Assign ?x1 (Lit ?l))#?cs1) ?cs2" \<Rightarrow> \<open>rule PConst\<close> \<bar> "passive_cmds_rel ?loc_vars ?R_old ?W ?R ?Q ((Assign ?x1 (Var ?x1'))#?cs1) ?cs2" \<Rightarrow> \<open>rule PConstVar,solves \<open>simp add: R_def\<close>\<close> \<bar> "passive_cmds_rel ?loc_vars ?R_old ?W ?R ?Q ((Havoc ?x1)#?cs1) ?cs2" \<Rightarrow> \<open>rule PHavoc\<close> \<bar> "passive_cmds_rel ?loc_vars ?R_old ?W ?R ?Q [] []" \<Rightarrow> \<open>rule PNil\<close> \<bar> "passive_cmds_rel ?loc_vars ?R_old ?W ?R ?Q [] ?cs2" \<Rightarrow> \<open>(rule PSync | rule PSyncConst), solves \<open>simp add: R_def\<close>\<close> \<bar> "passive_cmds_rel ?loc_vars ?R_old ?W ?R ?Q ?cs1 ?cs2" \<Rightarrow> \<open>rule, solves \<open>expr_rel_tac R_def: R_def R_old_def: R_old_def LocVar_assms: LocVar_assms\<close>\<close> \<bar> "_" \<Rightarrow> fail) method passive_rel_tac uses R_def R_old_def LocVar_assms = (passive_rel_tac_single R_def: R_def R_old_def: R_old_def LocVar_assms: LocVar_assms)+ definition type_rel :: "var_context \<Rightarrow> var_context \<Rightarrow> (vname \<times> (vname + lit)) list \<Rightarrow> bool" where "type_rel \<Lambda> \<Lambda>' Q = list_all (\<lambda> t. case (snd t) of (Inl y) \<Rightarrow> lookup_var_ty \<Lambda> (fst t) = lookup_var_ty \<Lambda>' y | (Inr _) \<Rightarrow> True ) Q" text \<open>The following lemma is the key lemma that we use to prove a local block lemma in the passification phase.\<close> lemma passification_block_lemma_aux: assumes "passive_cmds_rel (snd \<Lambda>) R_old W R Q cs1 cs2" and "A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>cs1, Normal ns\<rangle> [\<rightarrow>] s'" and "dependent A \<Lambda>' \<Omega> U0 D0" and "nstate_rel_states \<Lambda> \<Lambda>' R ns U0" and "nstate_old_rel_states \<Lambda> \<Lambda>' R_old ns U0" and "rel_well_typed A \<Lambda> \<Omega> R ns" and "(set W) \<inter> D0 = {}" and "U0 \<noteq> {}" and "type_rel \<Lambda> \<Lambda>' Q" and "distinct W" and "s' \<noteq> Magic" shows "\<exists> U1 \<subseteq> U0. U1 \<noteq> {} \<and> dependent A \<Lambda>' \<Omega> U1 (D0 \<union> (set W)) \<and> passive_sim A M \<Lambda> \<Lambda>' \<Gamma> \<Omega> cs2 s' (update_nstate_rel R Q) R_old U1" unfolding passive_sim_def using assms proof (induction arbitrary: ns U0 D0) case (PAssignNormal R e1 e2 W x1 x2 Q cs1 cs2) (* TODO: share proof with case PSync *) hence "x2 \<notin> D0" and "rel_const_correct \<Lambda> \<Omega> R ns" by (auto simp: rel_well_typed_def) from \<open>A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>Assign x1 e1 # cs1,Normal ns\<rangle> [\<rightarrow>] s'\<close> obtain v1 \<tau> where RedE1:"A,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>e1,ns\<rangle> \<Down> v1" and LookupX1:"lookup_var_ty \<Lambda> x1 = Some \<tau>" and TyV1:"type_of_val A v1 = instantiate \<Omega> \<tau>" by (meson RedCmdListCons_case single_assign_reduce_2) with expr_rel_same_set[OF \<open>expr_rel R R_old (snd \<Lambda>) e1 e2\<close> _ \<open>rel_const_correct \<Lambda> \<Omega> R ns\<close> \<open>nstate_rel_states \<Lambda> \<Lambda>' R ns U0\<close> \<open>nstate_old_rel_states \<Lambda> \<Lambda>' R_old ns U0\<close>] have RedE2:"\<forall>u\<in>U0. A, \<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>e2,u\<rangle> \<Down> v1" by blast from LookupX1 have LookupX2:"lookup_var_ty \<Lambda>' x2 = Some \<tau>" using \<open>type_rel \<Lambda> \<Lambda>' ((x1, (Inl x2)) # Q)\<close> by (simp add: type_rel_def) let ?U1 = "(set_red_cmd A M \<Lambda>' \<Gamma> \<Omega> (Assume ((Var x2) \<guillemotleft>Eq\<guillemotright> e2)) U0)" let ?U1Normal = "{ns. Normal ns \<in> ?U1}" have U1Sub:"?U1Normal \<subseteq> U0" by (simp add: passive_states_subset) have U1NonEmpty: "?U1Normal \<noteq> {}" using \<open>U0 \<noteq> {}\<close> \<open>x2 \<notin> D0\<close> \<open>dependent A \<Lambda>' \<Omega> U0 D0\<close> RedE2 TyV1 LookupX2 by (blast dest: assume_assign_non_empty) have U1Dep: "dependent A \<Lambda>' \<Omega> ?U1Normal (D0 \<union> {x2})" using \<open>x2 \<notin> D0\<close> \<open>dependent A \<Lambda>' \<Omega> U0 D0\<close> RedE2 by (blast dest: assume_assign_dependent) have RelStates: "nstate_rel_states \<Lambda> \<Lambda>' (R(x1 \<mapsto> (Inl x2))) (update_var \<Lambda> ns x1 v1) ?U1Normal" using \<open>nstate_rel_states \<Lambda> \<Lambda>' R ns U0\<close> \<open>nstate_old_rel_states \<Lambda> \<Lambda>' R_old ns U0\<close> \<open>expr_rel R R_old (snd \<Lambda>) e1 e2\<close> \<open>rel_const_correct \<Lambda> \<Omega> R ns\<close> RedE1 by (blast dest: assume_assign_nstate_rel) have RelOldStates: "nstate_old_rel_states \<Lambda> \<Lambda>' R_old (update_var \<Lambda> ns x1 v1) ?U1Normal" using \<open>nstate_old_rel_states \<Lambda> \<Lambda>' R_old ns U0\<close> U1Sub nstate_old_rel_states_update nstate_old_rel_states_subset by blast from \<open>distinct (x2 # W)\<close> \<open>set (x2 # W) \<inter> D0 = {}\<close> have "distinct W" and "set W \<inter> (D0 \<union> {x2}) = {}" by auto from \<open>A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>Assign x1 e1 # cs1,Normal ns\<rangle> [\<rightarrow>] s'\<close> have RedCs1:\<open>A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>cs1, Normal (update_var \<Lambda> ns x1 v1)\<rangle> [\<rightarrow>] s'\<close> by (metis RedCmdListCons_case RedE1 expr_eval_determ(1) single_assign_cases) have RedAssume: "\<And>u. u \<in> ?U1Normal \<Longrightarrow> A,M,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>Assume ((Var x2) \<guillemotleft>Eq\<guillemotright> e2),Normal u\<rangle> \<rightarrow> Normal u" by (rule passive_states_propagate_2) simp from \<open>type_rel \<Lambda> \<Lambda>' ((x1, (Inl x2)) # Q)\<close> have QTyRel:"type_rel \<Lambda> \<Lambda>' Q" by (simp add: type_rel_def) from \<open>rel_well_typed A \<Lambda> \<Omega> R ns\<close> have Rel_wt:\<open>rel_well_typed A \<Lambda> \<Omega> (R(x1 \<mapsto> (Inl x2))) (update_var \<Lambda> ns x1 v1)\<close> using LookupX1 TyV1 by (blast dest: rel_well_typed_update) from PAssignNormal.IH[OF RedCs1 U1Dep RelStates RelOldStates Rel_wt \<open>set W \<inter> (D0 \<union> {x2}) = {}\<close> U1NonEmpty QTyRel \<open>distinct W\<close> \<open>s' \<noteq> Magic\<close>] obtain U2 where U2Sub:"U2 \<subseteq> ?U1Normal" and "U2 \<noteq> {}" and U2Dep:"dependent A \<Lambda>' \<Omega> U2 (D0 \<union> {x2} \<union> set W)" and U2Rel:"(\<forall>u\<in>U2. \<exists>su. (A,M,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>cs2,Normal u\<rangle> [\<rightarrow>] su) \<and> (s' = Failure \<longrightarrow> su = Failure) \<and> (\<forall>ns'. s' = Normal ns' \<longrightarrow> su = Normal u \<and> nstate_rel \<Lambda> \<Lambda>' (update_nstate_rel (R(x1 \<mapsto> (Inl x2))) Q) ns' u \<and> nstate_old_rel \<Lambda> \<Lambda>' R_old ns' u \<and> rel_well_typed A \<Lambda> \<Omega> (update_nstate_rel (R(x1 \<mapsto> (Inl x2))) Q) ns'))" by blast hence U2Sub':"U2 \<subseteq> U0" and U2Dep':"dependent A \<Lambda>' \<Omega> U2 (D0 \<union> set (x2 # W))" and RedAssume2:"\<And>u. u \<in> U2 \<Longrightarrow> A,M,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>Assume ((Var x2) \<guillemotleft>Eq\<guillemotright> e2),Normal u\<rangle> \<rightarrow> Normal u" using U1Sub RedAssume by auto show ?case apply (rule exI, intro conjI, rule U2Sub', rule \<open>U2 \<noteq> {}\<close>, rule U2Dep', rule ballI) using U2Rel RedAssume2 update_nstate_rel_cons by (metis RedCmdListCons) next case (PConst W R x1 l Q cs1 cs2) let ?ns' = "(update_var \<Lambda> ns x1 (LitV l))" from \<open>A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>Assign x1 (Lit l) # cs1,Normal ns\<rangle> [\<rightarrow>] s'\<close> obtain \<tau> where RedCs1:\<open>A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>cs1,Normal ?ns'\<rangle> [\<rightarrow>] s'\<close> and "lookup_var_ty \<Lambda> x1 = Some \<tau>" and TypeLit:"TPrim (type_of_lit l) = instantiate \<Omega> \<tau>" by (metis RedCmdListCons_case single_assign_cases single_assign_reduce_lit val_elim) from \<open>nstate_rel_states \<Lambda> \<Lambda>' R ns U0\<close> have RelStates:"nstate_rel_states \<Lambda> \<Lambda>' (R(x1 \<mapsto> Inr l)) ?ns' U0" by (simp add: nstate_rel_states_update_const) from \<open>nstate_old_rel_states \<Lambda> \<Lambda>' R_old ns U0\<close> have RelOldStates:"nstate_old_rel_states \<Lambda> \<Lambda>' R_old ?ns' U0" by (simp add: nstate_old_rel_states_update) from \<open>rel_well_typed A \<Lambda> \<Omega> R ns\<close> have Rel_wt:"rel_well_typed A \<Lambda> \<Omega> (R(x1 \<mapsto> Inr l)) ?ns'" using \<open>lookup_var_ty \<Lambda> x1 = Some \<tau>\<close> TypeLit by (simp add: rel_well_typed_update_const) from \<open>type_rel \<Lambda> \<Lambda>' ((x1, Inr l) # Q)\<close> have QTyRel:"type_rel \<Lambda> \<Lambda>' Q" by (simp add: type_rel_def) from PConst.IH[OF RedCs1 \<open>dependent A \<Lambda>' \<Omega> U0 D0\<close> RelStates RelOldStates Rel_wt _ _ QTyRel] obtain U1 where "U1 \<subseteq> U0" and "U1 \<noteq> {}" and "dependent A \<Lambda>' \<Omega> U1 (D0 \<union> set W)" and "(\<forall>u\<in>U1. \<exists>su. (A,M,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>cs2,Normal u\<rangle> [\<rightarrow>] su) \<and> (s' = Failure \<longrightarrow> su = Failure) \<and> (\<forall>ns'. s' = Normal ns' \<longrightarrow> su = Normal u \<and> nstate_rel \<Lambda> \<Lambda>' (update_nstate_rel (R(x1 \<mapsto> Inr l)) Q) ns' u \<and> nstate_old_rel \<Lambda> \<Lambda>' R_old ns' u \<and> rel_well_typed A \<Lambda> \<Omega> (update_nstate_rel (R(x1 \<mapsto> Inr l)) Q) ns'))" using PConst by blast then show ?case using update_nstate_rel_cons by metis next case (PConstVar R x1' a W x1 Q cs1 cs2) from \<open>A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>Assign x1 (Var x1') # cs1,Normal ns\<rangle> [\<rightarrow>] s'\<close> obtain v \<tau> where LookupX1':"lookup_var \<Lambda> ns x1' = Some v" and RedCs1:"A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>cs1,Normal (update_var \<Lambda> ns x1 v)\<rangle> [\<rightarrow>] s'" and LookupTyX1:"lookup_var_ty \<Lambda> x1 = Some \<tau>" and TyV:"type_of_val A v = instantiate \<Omega> \<tau>" by (metis RedCmdListCons_case RedVar_case option.sel single_assign_cases single_assign_reduce_2) let ?ns' = "(update_var \<Lambda> ns x1 v)" from LookupX1' have RelStates:"nstate_rel_states \<Lambda> \<Lambda>' (R(x1 \<mapsto> a)) ?ns' U0" using \<open>nstate_rel_states \<Lambda> \<Lambda>' R ns U0\<close> \<open>R x1' = Some a\<close> by (simp add: nstate_rel_states_update_2) from \<open>nstate_old_rel_states \<Lambda> \<Lambda>' R_old ns U0\<close> have RelOldStates:"nstate_old_rel_states \<Lambda> \<Lambda>' R_old ?ns' U0" by (simp add: nstate_old_rel_states_update) from \<open>rel_well_typed A \<Lambda> \<Omega> R ns\<close> have Rel_wt:"rel_well_typed A \<Lambda> \<Omega> (R(x1 \<mapsto> a)) ?ns'" using LookupTyX1 TyV by (metis (no_types, lifting) LookupX1' PConstVar.hyps(1) option.inject rel_const_correct_def rel_well_typed_def rel_well_typed_update_general) from \<open>type_rel \<Lambda> \<Lambda>' ((x1, a) # Q)\<close> have QTyRel:"type_rel \<Lambda> \<Lambda>' Q" by (simp add: type_rel_def) from PConstVar.IH[OF RedCs1 \<open>dependent A \<Lambda>' \<Omega> U0 D0\<close> RelStates RelOldStates Rel_wt _ _ QTyRel] obtain U1 where "U1 \<subseteq> U0" and "U1 \<noteq> {}" and "dependent A \<Lambda>' \<Omega> U1 (D0 \<union> set W)" and "(\<forall>u\<in>U1. \<exists>su. (A,M,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>cs2,Normal u\<rangle> [\<rightarrow>] su) \<and> (s' = Failure \<longrightarrow> su = Failure) \<and> (\<forall>ns'. s' = Normal ns' \<longrightarrow> su = Normal u \<and> nstate_rel \<Lambda> \<Lambda>' (update_nstate_rel (R(x1 \<mapsto> a)) Q) ns' u \<and> nstate_old_rel \<Lambda> \<Lambda>' R_old ns' u \<and> rel_well_typed A \<Lambda> \<Omega> (update_nstate_rel (R(x1 \<mapsto> a)) Q) ns'))" using PConstVar by blast then show ?case using update_nstate_rel_cons by metis next case (PAssert R e1 e2 W Q cs1 cs2) hence "rel_const_correct \<Lambda> \<Omega> R ns" by (simp add: rel_well_typed_def) from \<open>A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>Assert e1 # cs1,Normal ns\<rangle> [\<rightarrow>] s'\<close> obtain s'' where RedAssert:"A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>Assert e1,Normal ns\<rangle> \<rightarrow> s''" and RedCs1:"A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>cs1, s''\<rangle> [\<rightarrow>] s'" by blast from RedAssert show ?case proof cases case RedAssertOk hence RedE2:"\<And>u. u\<in>U0 \<Longrightarrow> A,M,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>Assert e2,Normal u\<rangle> \<rightarrow> Normal u" using assert_rel_normal_2 \<open>nstate_rel_states \<Lambda> \<Lambda>' R ns U0\<close> \<open>nstate_old_rel_states \<Lambda> \<Lambda>' R_old ns U0\<close> \<open>expr_rel R R_old (snd \<Lambda>) e1 e2\<close> \<open>rel_const_correct \<Lambda> \<Omega> R ns\<close> by blast from \<open>s'' = Normal ns\<close> RedCs1 have RedCs1Normal:"A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>cs1, Normal ns\<rangle> [\<rightarrow>] s'" by simp from PAssert.IH[OF RedCs1Normal \<open>dependent A \<Lambda>' \<Omega> U0 D0\<close>] obtain U1 where U1Sub: "U1 \<subseteq> U0" and "U1 \<noteq> {}" and U1Dep:"dependent A \<Lambda>' \<Omega> U1 (D0 \<union> set W)" and U1Rel:"(\<forall>u\<in>U1. \<exists>su. (A,M,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>cs2,Normal u\<rangle> [\<rightarrow>] su) \<and> (s' = Failure \<longrightarrow> su = Failure) \<and> (\<forall>ns'. s' = Normal ns' \<longrightarrow> su = Normal u \<and> nstate_rel \<Lambda> \<Lambda>' (update_nstate_rel R Q) ns' u \<and> nstate_old_rel \<Lambda> \<Lambda>' R_old ns' u \<and> rel_well_typed A \<Lambda> \<Omega> (update_nstate_rel R Q) ns') )" using PAssert.prems by auto show ?thesis apply (rule exI, intro conjI) apply (rule U1Sub) apply (rule \<open>U1 \<noteq> {}\<close>) apply (rule U1Dep) using U1Sub RedE2 U1Rel by (meson RedCmdListCons subsetD) next case RedAssertFail hence RedE2:"\<And>u. u\<in>U0 \<Longrightarrow> A,M,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>Assert e2,Normal u\<rangle> \<rightarrow> Failure" using assert_rel_failure \<open>nstate_rel_states \<Lambda> \<Lambda>' R ns U0\<close> \<open>nstate_old_rel_states \<Lambda> \<Lambda>' R_old ns U0\<close> \<open>expr_rel R R_old (snd \<Lambda>) e1 e2\<close> \<open>rel_const_correct \<Lambda> \<Omega> R ns\<close> by blast from \<open>s'' = Failure\<close> have "s' = Failure" using RedCs1 by (simp add: failure_stays_cmd_list) show ?thesis apply (rule exI, intro conjI, rule subset_refl) apply (rule \<open>U0 \<noteq> {}\<close>) apply (rule dependent_ext[OF _ \<open>dependent A \<Lambda>' \<Omega> U0 D0\<close>]) apply simp using RedE2 \<open>s' = Failure\<close> failure_red_cmd_list RedCmdListCons by blast qed next case (PAssumeNormal R e1 e2 W Q cs1 cs2) hence "rel_const_correct \<Lambda> \<Omega> R ns" by (simp add: rel_well_typed_def) from \<open>A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>Assume e1 # cs1,Normal ns\<rangle> [\<rightarrow>] s'\<close> obtain s'' where RedAssume:"A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>Assume e1,Normal ns\<rangle> \<rightarrow> s''" and RedCs1:"A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>cs1, s''\<rangle> [\<rightarrow>] s'" by blast from RedAssume show ?case proof cases case RedAssumeOk hence RedE2:"\<And>u. u\<in>U0 \<Longrightarrow> A,M,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>Assume e2,Normal u\<rangle> \<rightarrow> Normal u" using assume_rel_normal \<open>nstate_rel_states \<Lambda> \<Lambda>' R ns U0\<close> \<open>nstate_old_rel_states \<Lambda> \<Lambda>' R_old ns U0\<close> \<open>expr_rel R R_old (snd \<Lambda>) e1 e2\<close> \<open>rel_const_correct \<Lambda> \<Omega> R ns\<close> by blast from \<open>s'' = Normal ns\<close> RedCs1 have RedCs1Normal:"A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>cs1, Normal ns\<rangle> [\<rightarrow>] s'" by simp from PAssumeNormal.IH[OF RedCs1Normal \<open>dependent A \<Lambda>' \<Omega> U0 D0\<close>] obtain U1 where U1Sub: "U1 \<subseteq> U0" and "U1 \<noteq> {}" and U1Dep:"dependent A \<Lambda>' \<Omega> U1 (D0 \<union> set W)" and U1Rel:"(\<forall>u\<in>U1. \<exists>su. (A,M,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>cs2,Normal u\<rangle> [\<rightarrow>] su) \<and> (s' = Failure \<longrightarrow> su = Failure) \<and> (\<forall>ns'. s' = Normal ns' \<longrightarrow> su = Normal u \<and> nstate_rel \<Lambda> \<Lambda>' (update_nstate_rel R Q) ns' u \<and> nstate_old_rel \<Lambda> \<Lambda>' R_old ns' u \<and> rel_well_typed A \<Lambda> \<Omega> (update_nstate_rel R Q) ns'))" using PAssumeNormal.prems by auto show ?thesis apply (rule exI, intro conjI) apply (rule U1Sub) apply (rule \<open>U1 \<noteq> {}\<close>) apply (rule U1Dep) using U1Sub RedE2 U1Rel by (meson RedCmdListCons subsetD) next case RedAssumeMagic hence RedE2:"\<And>u. u\<in>U0 \<Longrightarrow> A,M,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>Assume e2,Normal u\<rangle> \<rightarrow> Magic" using assume_rel_magic \<open>nstate_rel_states \<Lambda> \<Lambda>' R ns U0\<close> \<open>nstate_old_rel_states \<Lambda> \<Lambda>' R_old ns U0\<close> \<open>expr_rel R R_old (snd \<Lambda>) e1 e2\<close> \<open>rel_const_correct \<Lambda> \<Omega> R ns\<close> by blast from \<open>s'' = Magic\<close> have "s' = Magic" using RedCs1 by (simp add: magic_stays_cmd_list) show ?thesis apply (rule exI, intro conjI, rule subset_refl) apply (rule \<open>U0 \<noteq> {}\<close>) apply (rule dependent_ext[OF _ \<open>dependent A \<Lambda>' \<Omega> U0 D0\<close>], simp) using RedE2 RedCmdListCons \<open>s' = Magic\<close> magic_red_cmd_list by blast qed next case (PHavoc W R x x' Q cs1 cs2) hence "x' \<notin> D0" and Disj:"set W \<inter> (D0 \<union> {x'}) = {}" and "distinct W" by auto from \<open>A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>Havoc x # cs1,Normal ns\<rangle> [\<rightarrow>] s'\<close> obtain s'' where RedH:"A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>Havoc x,Normal ns\<rangle> \<rightarrow> s''" and RedCs1:"A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>cs1,s''\<rangle> [\<rightarrow>] s'" by auto from RedH show ?case proof cases case (RedHavocNormal \<tau> w v) hence LookupX':"lookup_var_ty \<Lambda>' x' = Some \<tau>" using \<open>type_rel \<Lambda> \<Lambda>' ((x, (Inl x')) # Q)\<close> by (simp add: lookup_var_decl_ty_Some type_rel_def) let ?U1 = "{u' \<in> U0. lookup_var \<Lambda>' u' x' = Some v}" have DepU1:"dependent A \<Lambda>' \<Omega> ?U1 (D0 \<union> {x'})" and "?U1 \<noteq> {}" using \<open>dependent A \<Lambda>' \<Omega> U0 D0\<close> \<open>x' \<notin> D0\<close> \<open>U0 \<noteq> {}\<close> LookupX' RedHavocNormal by (blast dest: havoc_dependent havoc_non_empty)+ have RelU1:"nstate_rel_states \<Lambda> \<Lambda>' (R(x \<mapsto> (Inl x'))) (update_var \<Lambda> ns x v) ?U1" using \<open>nstate_rel_states \<Lambda> \<Lambda>' R ns U0\<close> by (blast dest: havoc_nstate_rel) have U1Sub: "?U1 \<subseteq> U0" by auto have RelOldU1:"nstate_old_rel_states \<Lambda> \<Lambda>' R_old (update_var \<Lambda> ns x v) ?U1" using \<open>nstate_old_rel_states \<Lambda> \<Lambda>' R_old ns U0\<close> U1Sub nstate_old_rel_states_update nstate_old_rel_states_subset by blast from \<open>type_rel \<Lambda> \<Lambda>' ((x, Inl x') # Q)\<close> have QTyRel:"type_rel \<Lambda> \<Lambda>' Q" by (simp add: type_rel_def) from \<open>rel_well_typed A \<Lambda> \<Omega> R ns\<close> have Rel_wt:\<open>rel_well_typed A \<Lambda> \<Omega> (R(x \<mapsto> Inl x')) (update_var \<Lambda> ns x v)\<close> using RedHavocNormal lookup_var_decl_ty_Some by (blast dest: rel_well_typed_update) from RedCs1 have RedCs1Subst:"A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>cs1,Normal (update_var \<Lambda> ns x v)\<rangle> [\<rightarrow>] s'" using RedHavocNormal by simp from PHavoc.IH[OF RedCs1Subst DepU1 RelU1 RelOldU1 Rel_wt Disj \<open>?U1 \<noteq> {}\<close> QTyRel \<open>distinct W\<close> \<open>s' \<noteq> Magic\<close>] obtain U2 where "U2 \<subseteq> ?U1" and "U2 \<noteq> {}" and "dependent A \<Lambda>' \<Omega> U2 (D0 \<union> {x'} \<union> set W)" and "(\<forall>u\<in>U2. \<exists>su. (A,M,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>cs2,Normal u\<rangle> [\<rightarrow>] su) \<and> (s' = Failure \<longrightarrow> su = Failure) \<and> (\<forall>ns'. s' = Normal ns' \<longrightarrow> su = Normal u \<and> nstate_rel \<Lambda> \<Lambda>' (update_nstate_rel (R(x \<mapsto> Inl x')) Q) ns' u \<and> nstate_old_rel \<Lambda> \<Lambda>' R_old ns' u \<and> rel_well_typed A \<Lambda> \<Omega> (update_nstate_rel (R(x \<mapsto> Inl x')) Q) ns'))" by blast thus ?thesis apply (simp) apply (rule exI[where ?x=U2], intro conjI) apply fastforce apply fastforce apply fastforce using update_nstate_rel_cons by (simp add: update_nstate_rel_cons) next case (RedHavocMagic ty cond v) thus ?thesis by (metis RedCs1 \<open>s' \<noteq> Magic\<close> magic_stays_cmd_list_aux) qed next case (PSync R x x1 W x2 Q cs) hence "x2 \<notin> D0" by simp let ?U1 = "(set_red_cmd A M \<Lambda>' \<Gamma> \<Omega> (Assume ((Var x2) \<guillemotleft>Eq\<guillemotright> (Var x1))) U0)" let ?U1Normal = "{ns. Normal ns \<in> ?U1}" have U1Sub:"?U1Normal \<subseteq> U0" by (simp add: passive_states_subset) from \<open>R x = Some (Inl x1)\<close> \<open>rel_well_typed A \<Lambda> \<Omega> R ns\<close> obtain v \<tau> where LookupX:"lookup_var \<Lambda> ns x = Some v" and LookupTy:"lookup_var_ty \<Lambda> x = Some \<tau>" and TyV:"type_of_val A v = instantiate \<Omega> \<tau>" by (auto simp: rel_well_typed_def) hence RedX1:"\<forall>u\<in>U0. A,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>Var x1,u\<rangle> \<Down> v" using \<open>nstate_rel_states \<Lambda> \<Lambda>' R ns U0\<close> \<open>R x = Some (Inl x1)\<close> \<open>rel_well_typed A \<Lambda> \<Omega> R ns\<close> by (fastforce dest: lookup_nstates_rel intro: RedVar) from LookupTy have "lookup_var_ty \<Lambda>' x2 = Some \<tau>" using \<open>type_rel \<Lambda> \<Lambda>' ((x, Inl x2) # Q)\<close> by (simp add: type_rel_def) hence U1NonEmpty: "?U1Normal \<noteq> {}" using RedX1 \<open>U0 \<noteq> {}\<close> \<open>dependent A \<Lambda>' \<Omega> U0 D0\<close> \<open>x2 \<notin> D0\<close> TyV by (blast dest: assume_assign_non_empty) have U1Dep: "dependent A \<Lambda>' \<Omega> ?U1Normal (D0 \<union> {x2})" using \<open>dependent A \<Lambda>' \<Omega> U0 D0\<close> \<open>x2 \<notin> D0\<close> RedX1 by (blast dest: assume_assign_dependent) have RelStates: "nstate_rel_states \<Lambda> \<Lambda>' (R(x \<mapsto> Inl x2)) ns ?U1Normal" using \<open>nstate_rel_states \<Lambda> \<Lambda>' R ns U0\<close> \<open>R x = Some (Inl x1)\<close> \<open>rel_well_typed A \<Lambda> \<Omega> R ns\<close> by (blast dest: assume_sync_nstate_rel) have RelOldStates: "nstate_old_rel_states \<Lambda> \<Lambda>' R_old ns ?U1Normal" using \<open>nstate_old_rel_states \<Lambda> \<Lambda>' R_old ns U0\<close> U1Sub nstate_old_rel_states_update nstate_old_rel_states_subset by blast have RedAssume: "\<And>u. u \<in> ?U1Normal \<Longrightarrow> A,M,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>Assume ((Var x2) \<guillemotleft>Eq\<guillemotright> (Var x1)),Normal u\<rangle> \<rightarrow> Normal u" by (rule passive_states_propagate_2) simp from \<open>distinct (x2 # W)\<close> \<open>set (x2 # W) \<inter> D0 = {}\<close> have "distinct W" and "set W \<inter> (D0 \<union> {x2}) = {}" by auto from \<open>type_rel \<Lambda> \<Lambda>' ((x, (Inl x2)) # Q)\<close> have QTyRel:"type_rel \<Lambda> \<Lambda>' Q" by (simp add: type_rel_def) from \<open>rel_well_typed A \<Lambda> \<Omega> R ns\<close> have Rel_wt:\<open>rel_well_typed A \<Lambda> \<Omega> (R(x \<mapsto> (Inl x2))) ns\<close> using \<open>R x = Some (Inl x1)\<close> by (simp add: rel_well_typed_def rel_const_correct_def) from PSync.IH[OF \<open>A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>[],Normal ns\<rangle> [\<rightarrow>] s'\<close> U1Dep RelStates RelOldStates Rel_wt \<open>set W \<inter> (D0 \<union> {x2}) = {}\<close> U1NonEmpty QTyRel \<open>distinct W\<close> \<open>s' \<noteq> Magic\<close>] obtain U2 where U2Sub:"U2 \<subseteq> ?U1Normal" and "U2 \<noteq> {}" and U2Dep:"dependent A \<Lambda>' \<Omega> U2 (D0 \<union> {x2} \<union> set W)" and U2Rel: "\<forall>u\<in>U2. \<exists>su. (A,M,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>cs,Normal u\<rangle> [\<rightarrow>] su) \<and> (s' = Failure \<longrightarrow> su = Failure) \<and> (\<forall>ns'. s' = Normal ns' \<longrightarrow> su = Normal u \<and> nstate_rel \<Lambda> \<Lambda>' (update_nstate_rel (R(x \<mapsto> Inl x2)) Q) ns' u \<and> nstate_old_rel \<Lambda> \<Lambda>' R_old ns' u \<and> rel_well_typed A \<Lambda> \<Omega> (update_nstate_rel (R(x \<mapsto> Inl x2)) Q) ns')" by blast hence U2Sub':"U2 \<subseteq> U0" and U2Dep':"dependent A \<Lambda>' \<Omega> U2 (D0 \<union> set (x2 # W))" and RedAssume2:"\<And>u. u \<in> U2 \<Longrightarrow> A,M,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>Assume ((Var x2) \<guillemotleft>Eq\<guillemotright> (Var x1)),Normal u\<rangle> \<rightarrow> Normal u" using U1Sub RedAssume by auto show ?case apply (rule exI, intro conjI, rule U2Sub', rule \<open>U2 \<noteq> {}\<close>, rule U2Dep', rule ballI) using U2Rel RedAssume2 update_nstate_rel_cons by (metis RedCmdListCons) next case (PSyncConst R x l W x2 Q cs) hence "x2 \<notin> D0" by simp let ?U1 = "(set_red_cmd A M \<Lambda>' \<Gamma> \<Omega> (Assume ((Var x2) \<guillemotleft>Eq\<guillemotright> (Lit l))) U0)" let ?U1Normal = "{ns. Normal ns \<in> ?U1}" have U1Sub:"?U1Normal \<subseteq> U0" by (simp add: passive_states_subset) have RedLit:"\<forall>u\<in>U0. A,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>Lit l,u\<rangle> \<Down> (LitV l)" by (blast intro: RedLit) from \<open>R x = Some (Inr l)\<close> \<open>rel_well_typed A \<Lambda> \<Omega> R ns\<close> obtain \<tau> where "lookup_var \<Lambda> ns x = Some (LitV l)" and LookupTy:"lookup_var_ty \<Lambda> x = Some \<tau>" and TyV:"TPrim (type_of_lit l) = instantiate \<Omega> \<tau>" unfolding rel_well_typed_def rel_const_correct_def by blast hence TypLit:"type_of_val A (LitV l) = instantiate \<Omega> \<tau>" by simp from LookupTy have "lookup_var_ty \<Lambda>' x2 = Some \<tau>" using \<open>type_rel \<Lambda> \<Lambda>' ((x, Inl x2) # Q)\<close> unfolding type_rel_def by simp hence U1NonEmpty: "?U1Normal \<noteq> {}" using RedLit \<open>U0 \<noteq> {}\<close> \<open>dependent A \<Lambda>' \<Omega> U0 D0\<close> \<open>x2 \<notin> D0\<close> TyV using assume_assign_non_empty[OF RedLit TypLit] by blast have U1Dep: "dependent A \<Lambda>' \<Omega> ?U1Normal (D0 \<union> {x2})" using \<open>dependent A \<Lambda>' \<Omega> U0 D0\<close> \<open>x2 \<notin> D0\<close> RedLit by (blast dest: assume_assign_dependent) have RelStates: "nstate_rel_states \<Lambda> \<Lambda>' (R(x \<mapsto> Inl x2)) ns ?U1Normal" using \<open>nstate_rel_states \<Lambda> \<Lambda>' R ns U0\<close> \<open>rel_well_typed A \<Lambda> \<Omega> R ns\<close> \<open>R x = Some (Inr l)\<close> by (blast dest: assume_sync_const_nstate_rel) have RelOldStates: "nstate_old_rel_states \<Lambda> \<Lambda>' R_old ns ?U1Normal" using \<open>nstate_old_rel_states \<Lambda> \<Lambda>' R_old ns U0\<close> U1Sub nstate_old_rel_states_update nstate_old_rel_states_subset by blast have RedAssume: "\<And>u. u \<in> ?U1Normal \<Longrightarrow> A,M,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>Assume ((Var x2) \<guillemotleft>Eq\<guillemotright> (Lit l)),Normal u\<rangle> \<rightarrow> Normal u" by (rule passive_states_propagate_2) simp from \<open>distinct (x2 # W)\<close> \<open>set (x2 # W) \<inter> D0 = {}\<close> have "distinct W" and "set W \<inter> (D0 \<union> {x2}) = {}" by auto from \<open>type_rel \<Lambda> \<Lambda>' ((x, (Inl x2)) # Q)\<close> have QTyRel:"type_rel \<Lambda> \<Lambda>' Q" by (simp add: type_rel_def) from \<open>rel_well_typed A \<Lambda> \<Omega> R ns\<close> have Rel_wt:\<open>rel_well_typed A \<Lambda> \<Omega> (R(x \<mapsto> (Inl x2))) ns\<close> using \<open>R x = Some (Inr l)\<close> by (simp add: rel_well_typed_def rel_const_correct_def) from PSyncConst.IH[OF \<open>A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>[],Normal ns\<rangle> [\<rightarrow>] s'\<close> U1Dep RelStates RelOldStates Rel_wt \<open>set W \<inter> (D0 \<union> {x2}) = {}\<close> U1NonEmpty QTyRel \<open>distinct W\<close> \<open>s' \<noteq> Magic\<close>] obtain U2 where U2Sub:"U2 \<subseteq> ?U1Normal" and "U2 \<noteq> {}" and U2Dep:"dependent A \<Lambda>' \<Omega> U2 (D0 \<union> {x2} \<union> set W)" and U2Rel: "\<forall>u\<in>U2. \<exists>su. (A,M,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>cs,Normal u\<rangle> [\<rightarrow>] su) \<and> (s' = Failure \<longrightarrow> su = Failure) \<and> (\<forall>ns'. s' = Normal ns' \<longrightarrow> su = Normal u \<and> nstate_rel \<Lambda> \<Lambda>' (update_nstate_rel (R(x \<mapsto> Inl x2)) Q) ns' u \<and> nstate_old_rel \<Lambda> \<Lambda>' R_old ns' u \<and> rel_well_typed A \<Lambda> \<Omega> (update_nstate_rel (R(x \<mapsto> Inl x2)) Q) ns')" by blast hence U2Sub':"U2 \<subseteq> U0" and U2Dep':"dependent A \<Lambda>' \<Omega> U2 (D0 \<union> set (x2 # W))" and RedAssume2:"\<And>u. u \<in> U2 \<Longrightarrow> A,M,\<Lambda>',\<Gamma>,\<Omega> \<turnstile> \<langle>Assume ((Var x2) \<guillemotleft>Eq\<guillemotright> (Lit l)),Normal u\<rangle> \<rightarrow> Normal u" using U1Sub RedAssume by auto show ?case apply (rule exI, intro conjI, rule U2Sub', rule \<open>U2 \<noteq> {}\<close>, rule U2Dep', rule ballI) using U2Rel RedAssume2 update_nstate_rel_cons by (metis RedCmdListCons) next case (PNil R) thus ?case by (metis RedCmdListNil empty_set nstate_rel_states_def nstate_old_rel_states_def state.distinct(1) state.inject step_nil_same subset_refl sup_bot.right_neutral update_nstate_rel_nil) qed definition passive_block_conclusion where "passive_block_conclusion A M \<Lambda> \<Lambda>' \<Gamma> \<Omega> U0 D1 R R_old cs2 s' = (s' \<noteq> Magic \<longrightarrow> (\<exists> U1 \<subseteq> U0. U1 \<noteq> {} \<and> dependent A \<Lambda>' \<Omega> U1 D1 \<and> passive_sim A M \<Lambda> \<Lambda>' \<Gamma> \<Omega> cs2 s' R R_old U1))" definition passive_lemma_assms :: "'a absval_ty_fun \<Rightarrow> proc_context \<Rightarrow> var_context \<Rightarrow> var_context \<Rightarrow> 'a fun_interp \<Rightarrow> rtype_env \<Rightarrow> vname list \<Rightarrow> passive_rel \<Rightarrow> passive_rel \<Rightarrow> ('a nstate) set \<Rightarrow> vname set \<Rightarrow> 'a nstate \<Rightarrow> bool" where "passive_lemma_assms A M \<Lambda> \<Lambda>' \<Gamma> \<Omega> W R R_old U0 D0 ns = (nstate_rel_states \<Lambda> \<Lambda>' R ns U0 \<and> nstate_old_rel_states \<Lambda> \<Lambda>' R_old ns U0 \<and> rel_well_typed A \<Lambda> \<Omega> R ns \<and> dependent A \<Lambda>' \<Omega> U0 D0 \<and> (set W) \<inter> D0 = {} \<and> U0 \<noteq> {})" lemma passification_block_lemma_compact: assumes "A,M,\<Lambda>,\<Gamma>,\<Omega> \<turnstile> \<langle>cs1, Normal ns\<rangle> [\<rightarrow>] s'" "passive_lemma_assms A M \<Lambda> \<Lambda>' \<Gamma> \<Omega> W R R_old U0 D0 ns" and "passive_cmds_rel (snd \<Lambda>) R_old W R Q cs1 cs2" and "type_rel \<Lambda> \<Lambda>' Q" and "distinct W" shows "passive_block_conclusion A M \<Lambda> \<Lambda>' \<Gamma> \<Omega> U0 (D0 \<union> (set W)) (update_nstate_rel R Q) R_old cs2 s'" using assms unfolding passive_lemma_assms_def passive_block_conclusion_def using passification_block_lemma_aux by meson subsection \<open>Helper lemmas for global block theorems\<close> definition passive_cfg_assms where "passive_cfg_assms A M \<Lambda> \<Lambda>' \<Gamma> \<Omega> G W R U0 D0 m m' ns s' = ( (A,M,\<Lambda>,\<Gamma>,\<Omega>,G \<turnstile> (m, Normal ns) -n\<rightarrow>* (m',s')) \<and> nstate_rel_states \<Lambda> \<Lambda>' R ns U0 \<and> rel_well_typed A \<Lambda> \<Omega> R ns \<and> dependent A \<Lambda>' \<Omega> U0 D0 \<and> (set W) \<inter> D0 = {} \<and> U0 \<noteq> {})" definition passive_sim_cfg where "passive_sim_cfg A M \<Lambda>' \<Gamma> \<Omega> G U m_p s' \<equiv> (\<forall>u \<in> U. \<exists> m_p' su. (A,M,\<Lambda>',\<Gamma>,\<Omega>, G \<turnstile> (m_p, Normal u) -n\<rightarrow>* (m_p',su)) \<and> (s' = Failure \<longrightarrow> su = Failure))" definition passive_sim_cfg_fail where "passive_sim_cfg_fail A M \<Lambda>' \<Gamma> \<Omega> G u m_p \<equiv> (\<exists> m_p'. (A,M,\<Lambda>',\<Gamma>,\<Omega>, G \<turnstile> (m_p, Normal u) -n\<rightarrow>* (m_p', Failure)))" definition dependent_2 where "dependent_2 A \<Lambda>' \<Omega> U0 m = dependent A \<Lambda>' \<Omega> U0 {y. y \<le> m}" definition passive_lemma_assms_2 :: "'a absval_ty_fun \<Rightarrow> proc_context \<Rightarrow> var_context \<Rightarrow> var_context \<Rightarrow> 'a fun_interp \<Rightarrow> rtype_env \<Rightarrow> vname \<Rightarrow> passive_rel \<Rightarrow> passive_rel \<Rightarrow> ('a nstate) set \<Rightarrow> vname set \<Rightarrow> 'a nstate \<Rightarrow> bool" where "passive_lemma_assms_2 A M \<Lambda> \<Lambda>' \<Gamma> \<Omega> w_min R R_old U0 D0 ns = (nstate_rel_states \<Lambda> \<Lambda>' R ns U0 \<and> nstate_old_rel_states \<Lambda> \<Lambda>' R_old ns U0 \<and> rel_well_typed A \<Lambda> \<Omega> R ns \<and> dependent A \<Lambda>' \<Omega> U0 D0 \<and> {w. w \<ge> w_min} \<inter> D0 = {} \<and> U0 \<noteq> {})" lemma passive_assms_convert: assumes "passive_lemma_assms_2 A M \<Lambda> \<Lambda>' \<Gamma> \<Omega> w_min R R_old U0 D0 ns" and "W \<noteq> [] \<Longrightarrow> w_min \<le> Min (set W)" shows "passive_lemma_assms A M \<Lambda> \<Lambda>' \<Gamma> \<Omega> W R R_old U0 D0 ns" using assms unfolding passive_lemma_assms_2_def passive_lemma_assms_def by force lemma passive_assms_convert_2: assumes "passive_lemma_assms A M \<Lambda> \<Lambda>' \<Gamma> \<Omega> W R R_old U0 D0 ns" and "Max (set W) < w_min" and "D0 \<inter> {w. w \<ge> w_min} = {}" shows "passive_lemma_assms_2 A M \<Lambda> \<Lambda>' \<Gamma> \<Omega> w_min R R_old U0 D0 ns" using assms unfolding passive_lemma_assms_2_def passive_lemma_assms_def by (simp add: inf_commute) lemma passive_assms_2_ext: assumes "passive_lemma_assms_2 A M \<Lambda> \<Lambda>' \<Gamma> \<Omega> w_min R R_old U0 D0 ns" and "w_min \<le> w'" shows "passive_lemma_assms_2 A M \<Lambda> \<Lambda>' \<Gamma> \<Omega> w' R R_old U0 D0 ns" using assms unfolding passive_lemma_assms_2_def using order.trans by fastforce lemma set_helper: assumes "(w1 :: nat) \<le> w2" shows "{w. w \<ge> w2} \<subseteq> {w. w \<ge> w1}" using assms by auto lemma set_helper_2: assumes "W \<noteq> []" shows "{w::nat. w \<ge> (Max (set W))+1} \<inter> (set W) = {}" proof (rule, rule) fix x assume "x \<in> {w. Max (set W) + 1 \<le> w} \<inter> set W" hence Elem1:"x \<in> {w. Max (set W) + 1 \<le> w}" and "x \<in> (set W)" by auto from \<open>x \<in> (set W)\<close> \<open>W \<noteq> []\<close> have "x \<le> Max (set W)" by force thus "x \<in> {}" using Elem1 by simp next show "{} \<subseteq> {w. Max (set W) + 1 \<le> w} \<inter> set W" by simp qed text \<open>The following lemma is the key lemma that we use to prove the global block theorems in the passification phase.\<close> lemma passification_cfg_helper: assumes "A,M,\<Lambda>1,\<Gamma>,\<Omega>,G1 \<turnstile> ((Inl m), Normal ns) -n\<rightarrow>* (m',s')" and PassiveAssms: "passive_lemma_assms_2 A M \<Lambda>1 \<Lambda>2 \<Gamma> \<Omega> w_min R R_old U0 D0 ns" and Block: "node_to_block G1 ! m = cs" and BlockPassive: "node_to_block G2 ! m = cs2" and (* Requiring that G1 and G2 have the same edges as well as same node identifiers makes the successor assumption easier. For Boogie's passification this property is satisfied. *) SameEdges:"(out_edges G1) ! m = (out_edges G2) ! m" and BlockCorrect: "\<And> s''. A,M,\<Lambda>1,\<Gamma>,\<Omega> \<turnstile> \<langle>cs,Normal ns\<rangle> [\<rightarrow>] s'' \<Longrightarrow> passive_lemma_assms A M \<Lambda>1 \<Lambda>2 \<Gamma> \<Omega> W R R_old U0 D0 ns \<Longrightarrow> passive_block_conclusion A M \<Lambda>1 \<Lambda>2 \<Gamma> \<Omega> U0 (D0 \<union> (set W)) (update_nstate_rel R Q) R_old cs2 s''" and BlockFree: "W \<noteq> [] \<Longrightarrow> w_min \<le> Min (set W)" and MaxAssm: "W \<noteq> [] \<Longrightarrow> w_max_suc = 1+Max (set W) \<and> w_min < w_max_suc" and MaxAssm2: "W = [] \<Longrightarrow> w_min = w_max_suc" and SuccCorrect: "\<And> U0 D0 msuc s' ns'. List.member (out_edges(G1) ! m) msuc \<Longrightarrow> A,M,\<Lambda>1,\<Gamma>,\<Omega>,G1 \<turnstile> ((Inl msuc), Normal ns') -n\<rightarrow>* (m',s') \<Longrightarrow> passive_lemma_assms_2 A M \<Lambda>1 \<Lambda>2 \<Gamma> \<Omega> w_max_suc (update_nstate_rel R Q) R_old U0 D0 ns' \<Longrightarrow> s' = Failure \<longrightarrow> (\<exists> u. u \<in> U0 \<and> passive_sim_cfg_fail A M \<Lambda>2 \<Gamma> \<Omega> G2 u (Inl msuc))" shows "s' = Failure \<longrightarrow> (\<exists> u. u \<in> U0 \<and> passive_sim_cfg_fail A M \<Lambda>2 \<Gamma> \<Omega> G2 u (Inl m))" proof (cases rule: converse_rtranclpE2[OF assms(1)]) case 1 then show ?thesis by auto next case (2 a b) then show ?thesis proof cases case (RedNormalSucc csTemp ns' n') let ?R' = "update_nstate_rel R Q" let ?D1 = "D0 \<union> (set W)" from RedNormalSucc have "csTemp = cs" using Block by simp with RedNormalSucc BlockCorrect have "passive_block_conclusion A M \<Lambda>1 \<Lambda>2 \<Gamma> \<Omega> U0 ?D1 ?R' R_old cs2 (Normal ns')" using passive_assms_convert[OF PassiveAssms BlockFree] by blast from this obtain U1 where "U1 \<subseteq> U0" and"U1 \<noteq> {}" and DepU1:"dependent A \<Lambda>2 \<Omega> U1 ?D1" and SimU1:"passive_sim A M \<Lambda>1 \<Lambda>2 \<Gamma> \<Omega> cs2 (Normal ns') ?R' R_old U1" unfolding passive_block_conclusion_def by blast from PassiveAssms have "D0 \<inter> {w. w \<ge> w_min} = {}" unfolding passive_lemma_assms_2_def by blast hence "D0 \<inter> {w. w \<ge> w_max_suc} = {}" using MaxAssm BlockFree set_helper MaxAssm2 by force moreover have "W \<noteq> [] \<Longrightarrow> (set W) \<inter> {w. w \<ge> w_max_suc} = {}" using MaxAssm set_helper_2 by (simp add: Int_commute) ultimately have Disj:"(D0 \<union> (set W)) \<inter> {w. w \<ge> w_max_suc} = {}" by (cases "W = []") auto have SucResult:"s' = Failure \<longrightarrow> (\<exists>u. u \<in> U1 \<and> passive_sim_cfg_fail A M \<Lambda>2 \<Gamma> \<Omega> G2 u (Inl n'))" apply (rule SuccCorrect) apply (simp add: RedNormalSucc) using RedNormalSucc 2 apply fastforce unfolding passive_lemma_assms_2_def apply (intro conjI) using SimU1 apply (simp add: passive_sim_def nstate_rel_states_def) using SimU1 apply (simp add: passive_sim_def nstate_old_rel_states_def) using SimU1 \<open>U1 \<noteq> {}\<close> apply (simp add: passive_sim_def) apply blast apply (rule DepU1) using Disj apply (simp add: inf_commute) apply (rule \<open>U1 \<noteq> {}\<close>) done show ?thesis proof assume "s' = Failure" with SucResult obtain u m_p' where "u \<in> U1" and RedPassiveRemaining:"(A,M,\<Lambda>2,\<Gamma>,\<Omega>, G2 \<turnstile> ((Inl n'), Normal u) -n\<rightarrow>* (m_p', Failure))" unfolding passive_sim_cfg_fail_def using \<open>U1 \<subseteq> U0\<close> by auto hence "u \<in> U0" using \<open>U1 \<subseteq> U0\<close> by auto (* simulation of passive block *) from SimU1 have RedCs2:" A,M,\<Lambda>2,\<Gamma>,\<Omega> \<turnstile> \<langle>cs2,Normal u\<rangle> [\<rightarrow>] Normal u" unfolding passive_sim_def using \<open>u \<in> U1\<close> by simp show "\<exists>u. u \<in> U0 \<and> passive_sim_cfg_fail A M \<Lambda>2 \<Gamma> \<Omega> G2 u (Inl m)" apply (rule exI, rule conjI[OF \<open>u \<in> U0\<close>], (unfold passive_sim_cfg_fail_def), rule exI[where ?x=m_p']) apply (rule converse_rtranclp_into_rtranclp) apply (rule red_cfg.RedNormalSucc) apply (rule BlockPassive) apply (rule RedCs2) using \<open>List.member (out_edges G1 ! m) n'\<close> SameEdges apply simp apply (rule RedPassiveRemaining) done qed next case (RedNormalReturn cs ns') with \<open>A,M,\<Lambda>1,\<Gamma>,\<Omega>,G1 \<turnstile>(a, b) -n\<rightarrow>* (m', s')\<close> have "s' = Normal ns'" using finished_remains by blast thus ?thesis by simp next case (RedFailure csTemp) let ?R' = "update_nstate_rel R Q" let ?D1 = "D0 \<union> (set W)" from RedFailure have "csTemp = cs" using Block by simp with RedFailure BlockCorrect have "passive_block_conclusion A M \<Lambda>1 \<Lambda>2 \<Gamma> \<Omega> U0 ?D1 ?R' R_old cs2 Failure" using passive_assms_convert[OF PassiveAssms BlockFree] by simp from this obtain U1 where "U1 \<subseteq> U0" and "U1 \<noteq> {}" and SimU1:"passive_sim A M \<Lambda>1 \<Lambda>2 \<Gamma> \<Omega> cs2 Failure ?R' R_old U1" unfolding passive_block_conclusion_def by blast from this obtain u where "u \<in> U0" and RedCs2:"A,M,\<Lambda>2,\<Gamma>,\<Omega> \<turnstile> \<langle>cs2, Normal u\<rangle> [\<rightarrow>] Failure" unfolding passive_sim_def by blast show ?thesis apply (rule impI) apply (rule exI, rule conjI[OF \<open>u \<in> U0\<close>]) unfolding passive_sim_cfg_fail_def apply (rule exI[where ?x="Inr ()"]) apply (rule converse_rtranclp_into_rtranclp) apply (rule red_cfg.RedFailure) apply (rule BlockPassive) apply (rule RedCs2) apply (blast dest: finished_remains) done next case (RedMagic cs) then show ?thesis using finished_remains 2 by blast qed qed end
[STATEMENT] lemma preorder_rel_prodI [cont_intro, simp]: assumes "class.preorder orda (mk_less orda)" and "class.preorder ordb (mk_less ordb)" shows "class.preorder (rel_prod orda ordb) (mk_less (rel_prod orda ordb))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. class.preorder (rel_prod orda ordb) (mk_less (rel_prod orda ordb)) [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. class.preorder (rel_prod orda ordb) (mk_less (rel_prod orda ordb)) [PROOF STEP] interpret a: preorder orda "mk_less orda" [PROOF STATE] proof (prove) goal (1 subgoal): 1. class.preorder orda (mk_less orda) [PROOF STEP] by fact [PROOF STATE] proof (state) goal (1 subgoal): 1. class.preorder (rel_prod orda ordb) (mk_less (rel_prod orda ordb)) [PROOF STEP] interpret b: preorder ordb "mk_less ordb" [PROOF STATE] proof (prove) goal (1 subgoal): 1. class.preorder ordb (mk_less ordb) [PROOF STEP] by fact [PROOF STATE] proof (state) goal (1 subgoal): 1. class.preorder (rel_prod orda ordb) (mk_less (rel_prod orda ordb)) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) goal (1 subgoal): 1. class.preorder (rel_prod orda ordb) (mk_less (rel_prod orda ordb)) [PROOF STEP] by(unfold_locales)(auto simp add: mk_less_def intro: a.order_trans b.order_trans) [PROOF STATE] proof (state) this: class.preorder (rel_prod orda ordb) (mk_less (rel_prod orda ordb)) goal: No subgoals! [PROOF STEP] qed
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Anne Baanen -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.invertible import Mathlib.linear_algebra.bilinear_form import Mathlib.linear_algebra.determinant import Mathlib.linear_algebra.special_linear_group import Mathlib.PostPort universes u v l u_1 w u_2 u_3 namespace Mathlib /-! # Quadratic forms This file defines quadratic forms over a `R`-module `M`. A quadratic form is a map `Q : M → R` such that (`to_fun_smul`) `Q (a • x) = a * a * Q x` (`polar_...`) The map `polar Q := λ x y, Q (x + y) - Q x - Q y` is bilinear. They come with a scalar multiplication, `(a • Q) x = Q (a • x) = a * a * Q x`, and composition with linear maps `f`, `Q.comp f x = Q (f x)`. ## Main definitions * `quadratic_form.associated`: associated bilinear form * `quadratic_form.pos_def`: positive definite quadratic forms * `quadratic_form.anisotropic`: anisotropic quadratic forms * `quadratic_form.discr`: discriminant of a quadratic form ## Main statements * `quadratic_form.associated_left_inverse`, * `quadratic_form.associated_right_inverse`: in a commutative ring where 2 has an inverse, there is a correspondence between quadratic forms and symmetric bilinear forms ## Notation In this file, the variable `R` is used when a `ring` structure is sufficient and `R₁` is used when specifically a `comm_ring` is required. This allows us to keep `[module R M]` and `[module R₁ M]` assumptions in the variables without confusion between `*` from `ring` and `*` from `comm_ring`. ## References * https://en.wikipedia.org/wiki/Quadratic_form * https://en.wikipedia.org/wiki/Discriminant#Quadratic_forms ## Tags quadratic form, homogeneous polynomial, quadratic polynomial -/ namespace quadratic_form /-- Up to a factor 2, `Q.polar` is the associated bilinear form for a quadratic form `Q`.d Source of this name: https://en.wikipedia.org/wiki/Quadratic_form#Generalization -/ def polar {R : Type u} {M : Type v} [add_comm_group M] [ring R] (f : M → R) (x : M) (y : M) : R := f (x + y) - f x - f y theorem polar_add {R : Type u} {M : Type v} [add_comm_group M] [ring R] (f : M → R) (g : M → R) (x : M) (y : M) : polar (f + g) x y = polar f x y + polar g x y := sorry theorem polar_neg {R : Type u} {M : Type v} [add_comm_group M] [ring R] (f : M → R) (x : M) (y : M) : polar (-f) x y = -polar f x y := sorry theorem polar_smul {R : Type u} {M : Type v} [add_comm_group M] [ring R] (f : M → R) (s : R) (x : M) (y : M) : polar (s • f) x y = s * polar f x y := sorry theorem polar_comm {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] (f : M → R₁) (x : M) (y : M) : polar f x y = polar f y x := sorry end quadratic_form /-- A quadratic form over a module. -/ structure quadratic_form (R : Type u) (M : Type v) [ring R] [add_comm_group M] [module R M] extends quadratic_form.to_fun #1 #0 R M _inst_6 _inst_7 (_inst_8 • to_fun) = _inst_8 * _inst_8 * quadratic_form.to_fun #1 #0 R M _inst_6 _inst_7 to_fun where to_fun : M → R to_fun_smul : ∀ (a : R) (x : M), to_fun (a • x) = a * a * to_fun x polar_add_left' : ∀ (x x' y : M), quadratic_form.polar to_fun (x + x') y = quadratic_form.polar to_fun x y + quadratic_form.polar to_fun x' y polar_smul_left' : ∀ (a : R) (x y : M), quadratic_form.polar to_fun (a • x) y = a • quadratic_form.polar to_fun x y polar_add_right' : ∀ (x y y' : M), quadratic_form.polar to_fun x (y + y') = quadratic_form.polar to_fun x y + quadratic_form.polar to_fun x y' polar_smul_right' : ∀ (a : R) (x y : M), quadratic_form.polar to_fun x (a • y) = a • quadratic_form.polar to_fun x y namespace quadratic_form protected instance has_coe_to_fun {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] : has_coe_to_fun (quadratic_form R M) := has_coe_to_fun.mk (fun (B : quadratic_form R M) => M → R) fun (B : quadratic_form R M) => to_fun B /-- The `simp` normal form for a quadratic form is `coe_fn`, not `to_fun`. -/ @[simp] theorem to_fun_eq_apply {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {Q : quadratic_form R M} : to_fun Q = ⇑Q := rfl @[simp] theorem polar_add_left {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {Q : quadratic_form R M} (x : M) (x' : M) (y : M) : polar (⇑Q) (x + x') y = polar (⇑Q) x y + polar (⇑Q) x' y := polar_add_left' Q x x' y @[simp] theorem polar_smul_left {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {Q : quadratic_form R M} (a : R) (x : M) (y : M) : polar (⇑Q) (a • x) y = a * polar (⇑Q) x y := polar_smul_left' Q a x y @[simp] theorem polar_neg_left {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {Q : quadratic_form R M} (x : M) (y : M) : polar (⇑Q) (-x) y = -polar (⇑Q) x y := sorry @[simp] theorem polar_sub_left {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {Q : quadratic_form R M} (x : M) (x' : M) (y : M) : polar (⇑Q) (x - x') y = polar (⇑Q) x y - polar (⇑Q) x' y := sorry @[simp] theorem polar_add_right {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {Q : quadratic_form R M} (x : M) (y : M) (y' : M) : polar (⇑Q) x (y + y') = polar (⇑Q) x y + polar (⇑Q) x y' := polar_add_right' Q x y y' @[simp] theorem polar_smul_right {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {Q : quadratic_form R M} (a : R) (x : M) (y : M) : polar (⇑Q) x (a • y) = a * polar (⇑Q) x y := polar_smul_right' Q a x y @[simp] theorem polar_neg_right {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {Q : quadratic_form R M} (x : M) (y : M) : polar (⇑Q) x (-y) = -polar (⇑Q) x y := sorry @[simp] theorem polar_sub_right {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {Q : quadratic_form R M} (x : M) (y : M) (y' : M) : polar (⇑Q) x (y - y') = polar (⇑Q) x y - polar (⇑Q) x y' := sorry theorem map_smul {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {Q : quadratic_form R M} (a : R) (x : M) : coe_fn Q (a • x) = a * a * coe_fn Q x := to_fun_smul Q a x theorem map_add_self {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {Q : quadratic_form R M} (x : M) : coe_fn Q (x + x) = bit0 (bit0 1) * coe_fn Q x := sorry @[simp] theorem map_zero {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {Q : quadratic_form R M} : coe_fn Q 0 = 0 := sorry @[simp] theorem map_neg {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {Q : quadratic_form R M} (x : M) : coe_fn Q (-x) = coe_fn Q x := sorry theorem map_sub {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {Q : quadratic_form R M} (x : M) (y : M) : coe_fn Q (x - y) = coe_fn Q (y - x) := eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn Q (x - y) = coe_fn Q (y - x))) (Eq.symm (neg_sub y x)))) (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn Q (-(y - x)) = coe_fn Q (y - x))) (map_neg (y - x)))) (Eq.refl (coe_fn Q (y - x)))) theorem ext {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {Q : quadratic_form R M} {Q' : quadratic_form R M} (H : ∀ (x : M), coe_fn Q x = coe_fn Q' x) : Q = Q' := sorry protected instance has_zero {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] : HasZero (quadratic_form R M) := { zero := mk (fun (x : M) => 0) sorry sorry sorry sorry sorry } @[simp] theorem zero_apply {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] (x : M) : coe_fn 0 x = 0 := rfl protected instance inhabited {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] : Inhabited (quadratic_form R M) := { default := 0 } protected instance has_add {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] : Add (quadratic_form R M) := { add := fun (Q Q' : quadratic_form R M) => mk (⇑Q + ⇑Q') sorry sorry sorry sorry sorry } @[simp] theorem coe_fn_add {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] (Q : quadratic_form R M) (Q' : quadratic_form R M) : ⇑(Q + Q') = ⇑Q + ⇑Q' := rfl @[simp] theorem add_apply {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] (Q : quadratic_form R M) (Q' : quadratic_form R M) (x : M) : coe_fn (Q + Q') x = coe_fn Q x + coe_fn Q' x := rfl protected instance has_neg {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] : Neg (quadratic_form R M) := { neg := fun (Q : quadratic_form R M) => mk (-⇑Q) sorry sorry sorry sorry sorry } @[simp] theorem coe_fn_neg {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] (Q : quadratic_form R M) : ⇑(-Q) = -⇑Q := rfl @[simp] theorem neg_apply {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] (Q : quadratic_form R M) (x : M) : coe_fn (-Q) x = -coe_fn Q x := rfl protected instance has_scalar {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] : has_scalar R₁ (quadratic_form R₁ M) := has_scalar.mk fun (a : R₁) (Q : quadratic_form R₁ M) => mk (a • ⇑Q) sorry sorry sorry sorry sorry @[simp] theorem coe_fn_smul {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] (a : R₁) (Q : quadratic_form R₁ M) : ⇑(a • Q) = a • ⇑Q := rfl @[simp] theorem smul_apply {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] (a : R₁) (Q : quadratic_form R₁ M) (x : M) : coe_fn (a • Q) x = a * coe_fn Q x := rfl protected instance add_comm_group {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] : add_comm_group (quadratic_form R M) := add_comm_group.mk Add.add sorry 0 sorry sorry Neg.neg (add_group.sub._default Add.add sorry 0 sorry sorry Neg.neg) sorry sorry protected instance module {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] : module R₁ (quadratic_form R₁ M) := semimodule.mk sorry sorry /-- Compose the quadratic form with a linear function. -/ def comp {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {N : Type v} [add_comm_group N] [module R N] (Q : quadratic_form R N) (f : linear_map R M N) : quadratic_form R M := mk (fun (x : M) => coe_fn Q (coe_fn f x)) sorry sorry sorry sorry sorry @[simp] theorem comp_apply {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {N : Type v} [add_comm_group N] [module R N] (Q : quadratic_form R N) (f : linear_map R M N) (x : M) : coe_fn (comp Q f) x = coe_fn Q (coe_fn f x) := rfl /-- Create a quadratic form in a commutative ring by proving only one side of the bilinearity. -/ def mk_left {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] (f : M → R₁) (to_fun_smul : ∀ (a : R₁) (x : M), f (a • x) = a * a * f x) (polar_add_left : ∀ (x x' y : M), polar f (x + x') y = polar f x y + polar f x' y) (polar_smul_left : ∀ (a : R₁) (x y : M), polar f (a • x) y = a * polar f x y) : quadratic_form R₁ M := mk f to_fun_smul polar_add_left polar_smul_left sorry sorry /-- The product of linear forms is a quadratic form. -/ def lin_mul_lin {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] (f : linear_map R₁ M R₁) (g : linear_map R₁ M R₁) : quadratic_form R₁ M := mk_left (⇑f * ⇑g) sorry sorry sorry @[simp] theorem lin_mul_lin_apply {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] (f : linear_map R₁ M R₁) (g : linear_map R₁ M R₁) (x : M) : coe_fn (lin_mul_lin f g) x = coe_fn f x * coe_fn g x := rfl @[simp] theorem add_lin_mul_lin {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] (f : linear_map R₁ M R₁) (g : linear_map R₁ M R₁) (h : linear_map R₁ M R₁) : lin_mul_lin (f + g) h = lin_mul_lin f h + lin_mul_lin g h := ext fun (x : M) => add_mul (coe_fn f x) (coe_fn g x) (coe_fn h x) @[simp] theorem lin_mul_lin_add {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] (f : linear_map R₁ M R₁) (g : linear_map R₁ M R₁) (h : linear_map R₁ M R₁) : lin_mul_lin f (g + h) = lin_mul_lin f g + lin_mul_lin f h := ext fun (x : M) => mul_add (coe_fn f x) (coe_fn g x) (coe_fn h x) @[simp] theorem lin_mul_lin_comp {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] {N : Type v} [add_comm_group N] [module R₁ N] (f : linear_map R₁ M R₁) (g : linear_map R₁ M R₁) (h : linear_map R₁ N M) : comp (lin_mul_lin f g) h = lin_mul_lin (linear_map.comp f h) (linear_map.comp g h) := rfl /-- `proj i j` is the quadratic form mapping the vector `x : n → R₁` to `x i * x j` -/ def proj {R₁ : Type u} [comm_ring R₁] {n : Type u_1} (i : n) (j : n) : quadratic_form R₁ (n → R₁) := lin_mul_lin (linear_map.proj i) (linear_map.proj j) @[simp] theorem proj_apply {R₁ : Type u} [comm_ring R₁] {n : Type u_1} (i : n) (j : n) (x : n → R₁) : coe_fn (proj i j) x = x i * x j := rfl end quadratic_form /-! ### Associated bilinear forms Over a commutative ring with an inverse of 2, the theory of quadratic forms is basically identical to that of symmetric bilinear forms. The map from quadratic forms to bilinear forms giving this identification is called the `associated` quadratic form. -/ namespace bilin_form theorem polar_to_quadratic_form {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {B : bilin_form R M} (x : M) (y : M) : quadratic_form.polar (fun (x : M) => coe_fn B x x) x y = coe_fn B x y + coe_fn B y x := sorry /-- A bilinear form gives a quadratic form by applying the argument twice. -/ def to_quadratic_form {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] (B : bilin_form R M) : quadratic_form R M := quadratic_form.mk (fun (x : M) => coe_fn B x x) sorry sorry sorry sorry sorry @[simp] theorem to_quadratic_form_apply {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] (B : bilin_form R M) (x : M) : coe_fn (to_quadratic_form B) x = coe_fn B x x := rfl end bilin_form namespace quadratic_form /-- `associated` is the linear map that sends a quadratic form to its associated symmetric bilinear form -/ def associated {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] [invertible (bit0 1)] : linear_map R₁ (quadratic_form R₁ M) (bilin_form R₁ M) := linear_map.mk (fun (Q : quadratic_form R₁ M) => bilin_form.mk (fun (x y : M) => ⅟ * polar (⇑Q) x y) sorry sorry sorry sorry) sorry sorry @[simp] theorem associated_apply {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] [invertible (bit0 1)] {Q : quadratic_form R₁ M} (x : M) (y : M) : coe_fn (coe_fn associated Q) x y = ⅟ * (coe_fn Q (x + y) - coe_fn Q x - coe_fn Q y) := rfl theorem associated_is_sym {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] [invertible (bit0 1)] {Q : quadratic_form R₁ M} : sym_bilin_form.is_sym (coe_fn associated Q) := sorry @[simp] theorem associated_comp {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] [invertible (bit0 1)] {Q : quadratic_form R₁ M} {N : Type v} [add_comm_group N] [module R₁ N] (f : linear_map R₁ N M) : coe_fn associated (comp Q f) = bilin_form.comp (coe_fn associated Q) f f := sorry @[simp] theorem associated_lin_mul_lin {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] [invertible (bit0 1)] (f : linear_map R₁ M R₁) (g : linear_map R₁ M R₁) : coe_fn associated (lin_mul_lin f g) = ⅟ • (bilin_form.lin_mul_lin f g + bilin_form.lin_mul_lin g f) := sorry theorem associated_to_quadratic_form {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] [invertible (bit0 1)] (B : bilin_form R₁ M) (x : M) (y : M) : coe_fn (coe_fn associated (bilin_form.to_quadratic_form B)) x y = ⅟ * (coe_fn B x y + coe_fn B y x) := sorry theorem associated_left_inverse {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] [invertible (bit0 1)] {B₁ : bilin_form R₁ M} (h : sym_bilin_form.is_sym B₁) : coe_fn associated (bilin_form.to_quadratic_form B₁) = B₁ := sorry theorem associated_right_inverse {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] [invertible (bit0 1)] {Q : quadratic_form R₁ M} : bilin_form.to_quadratic_form (coe_fn associated Q) = Q := sorry /-- An anisotropic quadratic form is zero only on zero vectors. -/ def anisotropic {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] (Q : quadratic_form R M) := ∀ (x : M), coe_fn Q x = 0 → x = 0 theorem not_anisotropic_iff_exists {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] (Q : quadratic_form R M) : ¬anisotropic Q ↔ ∃ (x : M), ∃ (H : x ≠ 0), coe_fn Q x = 0 := sorry /-- A positive definite quadratic form is positive on nonzero vectors. -/ def pos_def {M : Type v} [add_comm_group M] {R₂ : Type u} [ordered_ring R₂] [module R₂ M] (Q₂ : quadratic_form R₂ M) := ∀ (x : M), x ≠ 0 → 0 < coe_fn Q₂ x theorem pos_def.smul {M : Type v} [add_comm_group M] {R : Type u_1} [linear_ordered_comm_ring R] [module R M] {Q : quadratic_form R M} (h : pos_def Q) {a : R} (a_pos : 0 < a) : pos_def (a • Q) := fun (x : M) (hx : x ≠ 0) => mul_pos a_pos (h x hx) theorem pos_def.add {M : Type v} [add_comm_group M] {R₂ : Type u} [ordered_ring R₂] [module R₂ M] (Q : quadratic_form R₂ M) (Q' : quadratic_form R₂ M) (hQ : pos_def Q) (hQ' : pos_def Q') : pos_def (Q + Q') := fun (x : M) (hx : x ≠ 0) => add_pos (hQ x hx) (hQ' x hx) theorem lin_mul_lin_self_pos_def {M : Type v} [add_comm_group M] {R : Type u_1} [linear_ordered_comm_ring R] [module R M] (f : linear_map R M R) (hf : linear_map.ker f = ⊥) : pos_def (lin_mul_lin f f) := sorry end quadratic_form /-! ### Quadratic forms and matrices Connect quadratic forms and matrices, in order to explicitly compute with them. The convention is twos out, so there might be a factor 2⁻¹ in the entries of the matrix. The determinant of the matrix is the discriminant of the quadratic form. -/ /-- `M.to_quadratic_form` is the map `λ x, col x ⬝ M ⬝ row x` as a quadratic form. -/ def matrix.to_quadratic_form' {R₁ : Type u} [comm_ring R₁] {n : Type w} [fintype n] [DecidableEq n] (M : matrix n n R₁) : quadratic_form R₁ (n → R₁) := bilin_form.to_quadratic_form (coe_fn matrix.to_bilin' M) /-- A matrix representation of the quadratic form. -/ def quadratic_form.to_matrix' {R₁ : Type u} [comm_ring R₁] {n : Type w} [fintype n] [DecidableEq n] [invertible (bit0 1)] (Q : quadratic_form R₁ (n → R₁)) : matrix n n R₁ := coe_fn bilin_form.to_matrix' (coe_fn quadratic_form.associated Q) theorem quadratic_form.to_matrix'_smul {R₁ : Type u} [comm_ring R₁] {n : Type w} [fintype n] [DecidableEq n] [invertible (bit0 1)] (a : R₁) (Q : quadratic_form R₁ (n → R₁)) : quadratic_form.to_matrix' (a • Q) = a • quadratic_form.to_matrix' Q := sorry namespace quadratic_form @[simp] theorem to_matrix'_comp {R₁ : Type u} [comm_ring R₁] {n : Type w} [fintype n] [DecidableEq n] [invertible (bit0 1)] {m : Type w} [DecidableEq m] [fintype m] (Q : quadratic_form R₁ (m → R₁)) (f : linear_map R₁ (n → R₁) (m → R₁)) : to_matrix' (comp Q f) = matrix.mul (matrix.mul (matrix.transpose (coe_fn linear_map.to_matrix' f)) (to_matrix' Q)) (coe_fn linear_map.to_matrix' f) := sorry /-- The discriminant of a quadratic form generalizes the discriminant of a quadratic polynomial. -/ def discr {R₁ : Type u} [comm_ring R₁] {n : Type w} [fintype n] [DecidableEq n] [invertible (bit0 1)] (Q : quadratic_form R₁ (n → R₁)) : R₁ := matrix.det (to_matrix' Q) theorem discr_smul {R₁ : Type u} [comm_ring R₁] {n : Type w} [fintype n] [DecidableEq n] [invertible (bit0 1)] {Q : quadratic_form R₁ (n → R₁)} (a : R₁) : discr (a • Q) = a ^ fintype.card n * discr Q := sorry theorem discr_comp {R₁ : Type u} [comm_ring R₁] {n : Type w} [fintype n] [DecidableEq n] [invertible (bit0 1)] {Q : quadratic_form R₁ (n → R₁)} (f : linear_map R₁ (n → R₁) (n → R₁)) : discr (comp Q f) = matrix.det (coe_fn linear_map.to_matrix' f) * matrix.det (coe_fn linear_map.to_matrix' f) * discr Q := sorry end quadratic_form namespace quadratic_form /-- An isometry between two quadratic spaces `M₁, Q₁` and `M₂, Q₂` over a ring `R`, is a linear equivalence between `M₁` and `M₂` that commutes with the quadratic forms. -/ structure isometry {R : Type u} [ring R] {M₁ : Type u_1} {M₂ : Type u_2} [add_comm_group M₁] [add_comm_group M₂] [module R M₁] [module R M₂] (Q₁ : quadratic_form R M₁) (Q₂ : quadratic_form R M₂) extends linear_equiv R M₁ M₂ where map_app' : ∀ (m : M₁), coe_fn Q₂ (linear_equiv.to_fun _to_linear_equiv m) = coe_fn Q₁ m /-- Two quadratic forms over a ring `R` are equivalent if there exists an isometry between them: a linear equivalence that transforms one quadratic form into the other. -/ def equivalent {R : Type u} [ring R] {M₁ : Type u_1} {M₂ : Type u_2} [add_comm_group M₁] [add_comm_group M₂] [module R M₁] [module R M₂] (Q₁ : quadratic_form R M₁) (Q₂ : quadratic_form R M₂) := Nonempty (isometry Q₁ Q₂) namespace isometry protected instance linear_equiv.has_coe {R : Type u} [ring R] {M₁ : Type u_1} {M₂ : Type u_2} [add_comm_group M₁] [add_comm_group M₂] [module R M₁] [module R M₂] {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} : has_coe (isometry Q₁ Q₂) (linear_equiv R M₁ M₂) := has_coe.mk to_linear_equiv protected instance has_coe_to_fun {R : Type u} [ring R] {M₁ : Type u_1} {M₂ : Type u_2} [add_comm_group M₁] [add_comm_group M₂] [module R M₁] [module R M₂] {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} : has_coe_to_fun (isometry Q₁ Q₂) := has_coe_to_fun.mk (fun (_x : isometry Q₁ Q₂) => M₁ → M₂) fun (f : isometry Q₁ Q₂) => ⇑↑f @[simp] theorem map_app {R : Type u} [ring R] {M₁ : Type u_1} {M₂ : Type u_2} [add_comm_group M₁] [add_comm_group M₂] [module R M₁] [module R M₂] {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} (f : isometry Q₁ Q₂) (m : M₁) : coe_fn Q₂ (coe_fn f m) = coe_fn Q₁ m := map_app' f m /-- The identity isometry from a quadratic form to itself. -/ def refl {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] (Q : quadratic_form R M) : isometry Q Q := mk (linear_equiv.mk (linear_equiv.to_fun (linear_equiv.refl R M)) sorry sorry (linear_equiv.inv_fun (linear_equiv.refl R M)) sorry sorry) sorry /-- The inverse isometry of an isometry between two quadratic forms. -/ def symm {R : Type u} [ring R] {M₁ : Type u_1} {M₂ : Type u_2} [add_comm_group M₁] [add_comm_group M₂] [module R M₁] [module R M₂] {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} (f : isometry Q₁ Q₂) : isometry Q₂ Q₁ := mk (linear_equiv.mk (linear_equiv.to_fun (linear_equiv.symm ↑f)) sorry sorry (linear_equiv.inv_fun (linear_equiv.symm ↑f)) sorry sorry) sorry /-- The composition of two isometries between quadratic forms. -/ def trans {R : Type u} [ring R] {M₁ : Type u_1} {M₂ : Type u_2} {M₃ : Type u_3} [add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₃] [module R M₁] [module R M₂] [module R M₃] {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} {Q₃ : quadratic_form R M₃} (f : isometry Q₁ Q₂) (g : isometry Q₂ Q₃) : isometry Q₁ Q₃ := mk (linear_equiv.mk (linear_equiv.to_fun (linear_equiv.trans ↑f ↑g)) sorry sorry (linear_equiv.inv_fun (linear_equiv.trans ↑f ↑g)) sorry sorry) sorry end isometry namespace equivalent theorem refl {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] (Q : quadratic_form R M) : equivalent Q Q := Nonempty.intro (isometry.refl Q) theorem symm {R : Type u} [ring R] {M₁ : Type u_1} {M₂ : Type u_2} [add_comm_group M₁] [add_comm_group M₂] [module R M₁] [module R M₂] {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} (h : equivalent Q₁ Q₂) : equivalent Q₂ Q₁ := nonempty.elim h fun (f : isometry Q₁ Q₂) => Nonempty.intro (isometry.symm f) theorem trans {R : Type u} [ring R] {M₁ : Type u_1} {M₂ : Type u_2} {M₃ : Type u_3} [add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₃] [module R M₁] [module R M₂] [module R M₃] {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} {Q₃ : quadratic_form R M₃} (h : equivalent Q₁ Q₂) (h' : equivalent Q₂ Q₃) : equivalent Q₁ Q₃ := nonempty.elim h' (nonempty.elim h fun (f : isometry Q₁ Q₂) (g : isometry Q₂ Q₃) => Nonempty.intro (isometry.trans f g))
Formal statement is: lemma locally_compact_delete: fixes S :: "'a :: t1_space set" shows "locally compact S \<Longrightarrow> locally compact (S - {a})" Informal statement is: If $S$ is a locally compact space, then $S - \{a\}$ is also locally compact.
(* Author: Tobias Nipkow *) theory Abs_Int_den1_ivl imports Abs_Int_den1 begin subsection "Interval Analysis" datatype ivl = I "int option" "int option" text{* We assume an important invariant: arithmetic operations are never applied to empty intervals @{term"I (Some i) (Some j)"} with @{term"j < i"}. This avoids special cases. Why can we assume this? Because an empty interval of values for a variable means that the current program point is unreachable. But this should actually translate into the bottom state, not a state where some variables have empty intervals. *} definition "rep_ivl i = (case i of I (Some l) (Some h) \<Rightarrow> {l..h} | I (Some l) None \<Rightarrow> {l..} | I None (Some h) \<Rightarrow> {..h} | I None None \<Rightarrow> UNIV)" definition "num_ivl n = I (Some n) (Some n)" definition [code_abbrev]: "contained_in i k \<longleftrightarrow> k \<in> rep_ivl i" lemma contained_in_simps [code]: "contained_in (I (Some l) (Some h)) k \<longleftrightarrow> l \<le> k \<and> k \<le> h" "contained_in (I (Some l) None) k \<longleftrightarrow> l \<le> k" "contained_in (I None (Some h)) k \<longleftrightarrow> k \<le> h" "contained_in (I None None) k \<longleftrightarrow> True" by (simp_all add: contained_in_def rep_ivl_def) instantiation option :: (plus)plus begin fun plus_option where "Some x + Some y = Some(x+y)" | "_ + _ = None" instance proof qed end definition empty where "empty = I (Some 1) (Some 0)" fun is_empty where "is_empty(I (Some l) (Some h)) = (h<l)" | "is_empty _ = False" lemma [simp]: "is_empty i \<Longrightarrow> rep_ivl i = {}" by(auto simp add: rep_ivl_def split: ivl.split option.split) definition "plus_ivl i1 i2 = ((*if is_empty i1 | is_empty i2 then empty else*) case (i1,i2) of (I l1 h1, I l2 h2) \<Rightarrow> I (l1+l2) (h1+h2))" instantiation ivl :: SL_top begin definition le_option :: "bool \<Rightarrow> int option \<Rightarrow> int option \<Rightarrow> bool" where "le_option pos x y = (case x of (Some i) \<Rightarrow> (case y of Some j \<Rightarrow> i\<le>j | None \<Rightarrow> pos) | None \<Rightarrow> (case y of Some j \<Rightarrow> \<not>pos | None \<Rightarrow> True))" fun le_aux where "le_aux (I l1 h1) (I l2 h2) = (le_option False l2 l1 & le_option True h1 h2)" definition le_ivl where "i1 \<sqsubseteq> i2 = (if is_empty i1 then True else if is_empty i2 then False else le_aux i1 i2)" definition min_option :: "bool \<Rightarrow> int option \<Rightarrow> int option \<Rightarrow> int option" where "min_option pos o1 o2 = (if le_option pos o1 o2 then o1 else o2)" definition max_option :: "bool \<Rightarrow> int option \<Rightarrow> int option \<Rightarrow> int option" where "max_option pos o1 o2 = (if le_option pos o1 o2 then o2 else o1)" definition "i1 \<squnion> i2 = (if is_empty i1 then i2 else if is_empty i2 then i1 else case (i1,i2) of (I l1 h1, I l2 h2) \<Rightarrow> I (min_option False l1 l2) (max_option True h1 h2))" definition "Top = I None None" instance proof case goal1 thus ?case by(cases x, simp add: le_ivl_def le_option_def split: option.split) next case goal2 thus ?case by(cases x, cases y, cases z, auto simp: le_ivl_def le_option_def split: option.splits if_splits) next case goal3 thus ?case by(cases x, cases y, simp add: le_ivl_def join_ivl_def le_option_def min_option_def max_option_def split: option.splits) next case goal4 thus ?case by(cases x, cases y, simp add: le_ivl_def join_ivl_def le_option_def min_option_def max_option_def split: option.splits) next case goal5 thus ?case by(cases x, cases y, cases z, auto simp add: le_ivl_def join_ivl_def le_option_def min_option_def max_option_def split: option.splits if_splits) next case goal6 thus ?case by(cases x, simp add: Top_ivl_def le_ivl_def le_option_def split: option.split) qed end instantiation ivl :: L_top_bot begin definition "i1 \<sqinter> i2 = (if is_empty i1 \<or> is_empty i2 then empty else case (i1,i2) of (I l1 h1, I l2 h2) \<Rightarrow> I (max_option False l1 l2) (min_option True h1 h2))" definition "Bot = empty" instance proof case goal1 thus ?case by (simp add:meet_ivl_def empty_def meet_ivl_def le_ivl_def le_option_def max_option_def min_option_def split: ivl.splits option.splits) next case goal2 thus ?case by (simp add:meet_ivl_def empty_def meet_ivl_def le_ivl_def le_option_def max_option_def min_option_def split: ivl.splits option.splits) next case goal3 thus ?case by (cases x, cases y, cases z, auto simp add: le_ivl_def meet_ivl_def empty_def le_option_def max_option_def min_option_def split: option.splits if_splits) next case goal4 show ?case by(cases x, simp add: Bot_ivl_def empty_def le_ivl_def) qed end instantiation option :: (minus)minus begin fun minus_option where "Some x - Some y = Some(x-y)" | "_ - _ = None" instance proof qed end definition "minus_ivl i1 i2 = ((*if is_empty i1 | is_empty i2 then empty else*) case (i1,i2) of (I l1 h1, I l2 h2) \<Rightarrow> I (l1-h2) (h1-l2))" lemma rep_minus_ivl: "n1 : rep_ivl i1 \<Longrightarrow> n2 : rep_ivl i2 \<Longrightarrow> n1-n2 : rep_ivl(minus_ivl i1 i2)" by(auto simp add: minus_ivl_def rep_ivl_def split: ivl.splits option.splits) definition "filter_plus_ivl i i1 i2 = ((*if is_empty i then empty else*) i1 \<sqinter> minus_ivl i i2, i2 \<sqinter> minus_ivl i i1)" fun filter_less_ivl :: "bool \<Rightarrow> ivl \<Rightarrow> ivl \<Rightarrow> ivl * ivl" where "filter_less_ivl res (I l1 h1) (I l2 h2) = ((*if is_empty(I l1 h1) \<or> is_empty(I l2 h2) then (empty, empty) else*) if res then (I l1 (min_option True h1 (h2 - Some 1)), I (max_option False (l1 + Some 1) l2) h2) else (I (max_option False l1 l2) h1, I l2 (min_option True h1 h2)))" permanent_interpretation Rep rep_ivl proof case goal1 thus ?case by(auto simp: rep_ivl_def le_ivl_def le_option_def split: ivl.split option.split if_splits) qed permanent_interpretation Val_abs rep_ivl num_ivl plus_ivl proof case goal1 thus ?case by(simp add: rep_ivl_def num_ivl_def) next case goal2 thus ?case by(auto simp add: rep_ivl_def plus_ivl_def split: ivl.split option.splits) qed permanent_interpretation Rep1 rep_ivl proof case goal1 thus ?case by(auto simp add: rep_ivl_def meet_ivl_def empty_def min_option_def max_option_def split: ivl.split option.split) next case goal2 show ?case by(auto simp add: Bot_ivl_def rep_ivl_def empty_def) qed permanent_interpretation Val_abs1 rep_ivl num_ivl plus_ivl filter_plus_ivl filter_less_ivl proof case goal1 thus ?case by(auto simp add: filter_plus_ivl_def) (metis rep_minus_ivl add_diff_cancel add.commute)+ next case goal2 thus ?case by(cases a1, cases a2, auto simp: rep_ivl_def min_option_def max_option_def le_option_def split: if_splits option.splits) qed permanent_interpretation Abs_Int1 rep_ivl num_ivl plus_ivl filter_plus_ivl filter_less_ivl "(iter' 3)" defining afilter_ivl = afilter and bfilter_ivl = bfilter and AI_ivl = AI and aval_ivl = aval' proof qed (auto simp: iter'_pfp_above) fun list_up where "list_up bot = bot" | "list_up (Up x) = Up(list x)" value "list_up(afilter_ivl (N 5) (I (Some 4) (Some 5)) Top)" value "list_up(afilter_ivl (N 5) (I (Some 4) (Some 4)) Top)" value "list_up(afilter_ivl (V ''x'') (I (Some 4) (Some 4)) (Up(FunDom(Top(''x'':=I (Some 5) (Some 6))) [''x''])))" value "list_up(afilter_ivl (V ''x'') (I (Some 4) (Some 5)) (Up(FunDom(Top(''x'':=I (Some 5) (Some 6))) [''x''])))" value "list_up(afilter_ivl (Plus (V ''x'') (V ''x'')) (I (Some 0) (Some 10)) (Up(FunDom(Top(''x'':= I (Some 0) (Some 100)))[''x''])))" value "list_up(afilter_ivl (Plus (V ''x'') (N 7)) (I (Some 0) (Some 10)) (Up(FunDom(Top(''x'':= I (Some 0) (Some 100)))[''x''])))" value "list_up(bfilter_ivl (Less (V ''x'') (V ''x'')) True (Up(FunDom(Top(''x'':= I (Some 0) (Some 0)))[''x''])))" value "list_up(bfilter_ivl (Less (V ''x'') (V ''x'')) True (Up(FunDom(Top(''x'':= I (Some 0) (Some 2)))[''x''])))" value "list_up(bfilter_ivl (Less (V ''x'') (Plus (N 10) (V ''y''))) True (Up(FunDom(Top(''x'':= I (Some 15) (Some 20),''y'':= I (Some 5) (Some 7)))[''x'', ''y''])))" definition "test_ivl1 = ''y'' ::= N 7;; IF Less (V ''x'') (V ''y'') THEN ''y'' ::= Plus (V ''y'') (V ''x'') ELSE ''x'' ::= Plus (V ''x'') (V ''y'')" value "list_up(AI_ivl test_ivl1 Top)" value "list_up (AI_ivl test3_const Top)" value "list_up (AI_ivl test5_const Top)" value "list_up (AI_ivl test6_const Top)" definition "test2_ivl = ''y'' ::= N 7;; WHILE Less (V ''x'') (N 100) DO ''y'' ::= Plus (V ''y'') (N 1)" value "list_up(AI_ivl test2_ivl Top)" definition "test3_ivl = ''x'' ::= N 0;; ''y'' ::= N 100;; ''z'' ::= Plus (V ''x'') (V ''y'');; WHILE Less (V ''x'') (N 11) DO (''x'' ::= Plus (V ''x'') (N 1);; ''y'' ::= Plus (V ''y'') (N (- 1)))" value "list_up(AI_ivl test3_ivl Top)" definition "test4_ivl = ''x'' ::= N 0;; ''y'' ::= N 0;; WHILE Less (V ''x'') (N 1001) DO (''y'' ::= V ''x'';; ''x'' ::= Plus (V ''x'') (N 1))" value "list_up(AI_ivl test4_ivl Top)" text{* Nontermination not detected: *} definition "test5_ivl = ''x'' ::= N 0;; WHILE Less (V ''x'') (N 1) DO ''x'' ::= Plus (V ''x'') (N (- 1))" value "list_up(AI_ivl test5_ivl Top)" end
[STATEMENT] lemma known_ptrs_preserved: "object_ptr_kinds h = object_ptr_kinds h' \<Longrightarrow> a_known_ptrs h = a_known_ptrs h'" [PROOF STATE] proof (prove) goal (1 subgoal): 1. object_ptr_kinds h = object_ptr_kinds h' \<Longrightarrow> local.a_known_ptrs h = local.a_known_ptrs h' [PROOF STEP] by(auto simp add: a_known_ptrs_def)
module OCaml.Lwt import OCaml.IO %default total %access public export %lib malfunction "lwt" Lwt : Type -> Type Lwt = Abstr1 lwtReturn : {auto ta : OCaml_Types a} -> a -> OCaml_IO (Lwt a) lwtReturn {a} x = ocamlCall "Lwt.return" (a -> OCaml_IO (Lwt a)) x lwtBind : {auto ta : OCaml_Types a} -> Lwt a -> (a -> OCaml_IO (Lwt b)) -> OCaml_IO (Lwt b) lwtBind {a}{b} p f = ocamlCall "Lwt.bind" (Lwt a -> (a -> OCaml_IO (Lwt b)) -> OCaml_IO (Lwt b)) p f
(* Title: HOL/Auth/n_mutualExOnI_on_inis.thy Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences *) header{*The n_mutualExOnI Protocol Case Study*} theory n_mutualExOnI_on_inis imports n_mutualExOnI_on_ini begin lemma on_inis: assumes b1: "f \<in> (invariants N)" and b2: "ini \<in> {andList (allInitSpecs N)}" and b3: "formEval ini s" shows "formEval f s" proof - have c1: "(\<exists> p__Inv0 p__Inv1. p__Inv0\<le>N\<and>p__Inv1\<le>N\<and>p__Inv0~=p__Inv1\<and>f=inv__1 p__Inv0 p__Inv1)\<or> (\<exists> p__Inv0 p__Inv1. p__Inv0\<le>N\<and>p__Inv1\<le>N\<and>p__Inv0~=p__Inv1\<and>f=inv__2 p__Inv0 p__Inv1)\<or> (\<exists> p__Inv0 p__Inv1. p__Inv0\<le>N\<and>p__Inv1\<le>N\<and>p__Inv0~=p__Inv1\<and>f=inv__3 p__Inv0 p__Inv1)\<or> (\<exists> p__Inv0 p__Inv1. p__Inv0\<le>N\<and>p__Inv1\<le>N\<and>p__Inv0~=p__Inv1\<and>f=inv__4 p__Inv0 p__Inv1)" apply (cut_tac b1, simp) done moreover { assume d1: "(\<exists> p__Inv0 p__Inv1. p__Inv0\<le>N\<and>p__Inv1\<le>N\<and>p__Inv0~=p__Inv1\<and>f=inv__1 p__Inv0 p__Inv1)" have "formEval f s" apply (rule iniImply_inv__1) apply (cut_tac d1, assumption) apply (cut_tac b2 b3, blast) done } moreover { assume d1: "(\<exists> p__Inv0 p__Inv1. p__Inv0\<le>N\<and>p__Inv1\<le>N\<and>p__Inv0~=p__Inv1\<and>f=inv__2 p__Inv0 p__Inv1)" have "formEval f s" apply (rule iniImply_inv__2) apply (cut_tac d1, assumption) apply (cut_tac b2 b3, blast) done } moreover { assume d1: "(\<exists> p__Inv0 p__Inv1. p__Inv0\<le>N\<and>p__Inv1\<le>N\<and>p__Inv0~=p__Inv1\<and>f=inv__3 p__Inv0 p__Inv1)" have "formEval f s" apply (rule iniImply_inv__3) apply (cut_tac d1, assumption) apply (cut_tac b2 b3, blast) done } moreover { assume d1: "(\<exists> p__Inv0 p__Inv1. p__Inv0\<le>N\<and>p__Inv1\<le>N\<and>p__Inv0~=p__Inv1\<and>f=inv__4 p__Inv0 p__Inv1)" have "formEval f s" apply (rule iniImply_inv__4) apply (cut_tac d1, assumption) apply (cut_tac b2 b3, blast) done } ultimately show "formEval f s" by satx qed end
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import control.uliftable import data.bitvec.basic import data.stream.defs import tactic.norm_num /-! # Rand Monad and Random Class This module provides tools for formulating computations guided by randomness and for defining objects that can be created randomly. ## Main definitions * `rand` monad for computations guided by randomness; * `random` class for objects that can be generated randomly; * `random` to generate one object; * `random_r` to generate one object inside a range; * `random_series` to generate an infinite series of objects; * `random_series_r` to generate an infinite series of objects inside a range; * `io.mk_generator` to create a new random number generator; * `io.run_rand` to run a randomized computation inside the `io` monad; * `tactic.run_rand` to run a randomized computation inside the `tactic` monad ## Local notation * `i .. j` : `Icc i j`, the set of values between `i` and `j` inclusively; ## Tags random monad io ## References * Similar library in Haskell: https://hackage.haskell.org/package/MonadRandom -/ open list io applicative universes u v w /-- A monad to generate random objects using the generator type `g` -/ @[reducible] def rand_g (g : Type) (α : Type u) : Type u := state (ulift.{u} g) α /-- A monad to generate random objects using the generator type `std_gen` -/ @[reducible] def rand := rand_g std_gen instance (g : Type) : uliftable (rand_g.{u} g) (rand_g.{v} g) := @state_t.uliftable' _ _ _ _ _ (equiv.ulift.trans.{u u u u u} equiv.ulift.symm) open ulift (hiding inhabited) /-- Generate one more `ℕ` -/ def rand_g.next {g : Type} [random_gen g] : rand_g g ℕ := ⟨ prod.map id up ∘ random_gen.next ∘ down ⟩ local infix ` .. `:41 := set.Icc open stream /-- `bounded_random α` gives us machinery to generate values of type `α` between certain bounds -/ class bounded_random (α : Type u) [preorder α] := (random_r : Π g [random_gen g] (x y : α), (x ≤ y) → rand_g g (x .. y)) /-- `random α` gives us machinery to generate values of type `α` -/ class random (α : Type u) := (random [] : Π (g : Type) [random_gen g], rand_g g α) /-- shift_31_left = 2^31; multiplying by it shifts the binary representation of a number left by 31 bits, dividing by it shifts it right by 31 bits -/ def shift_31_left : ℕ := by apply_normed 2^31 namespace rand open stream variables (α : Type u) variables (g : Type) [random_gen g] /-- create a new random number generator distinct from the one stored in the state -/ def split : rand_g g g := ⟨ prod.map id up ∘ random_gen.split ∘ down ⟩ variables {g} section random variables [random α] export random (random) /-- Generate a random value of type `α`. -/ def random : rand_g g α := random.random α g /-- generate an infinite series of random values of type `α` -/ def random_series : rand_g g (stream α) := do gen ← uliftable.up (split g), pure $ stream.corec_state (random.random α g) gen end random variables {α} /-- Generate a random value between `x` and `y` inclusive. -/ def random_r [preorder α] [bounded_random α] (x y : α) (h : x ≤ y) : rand_g g (x .. y) := bounded_random.random_r g x y h /-- generate an infinite series of random values of type `α` between `x` and `y` inclusive. -/ def random_series_r [preorder α] [bounded_random α] (x y : α) (h : x ≤ y) : rand_g g (stream (x .. y)) := do gen ← uliftable.up (split g), pure $ corec_state (bounded_random.random_r g x y h) gen end rand namespace io private def accum_char (w : ℕ) (c : char) : ℕ := c.to_nat + 256 * w /-- create and seed a random number generator -/ def mk_generator : io std_gen := do seed ← io.rand 0 shift_31_left, return $ mk_std_gen seed variables {α : Type} /-- Run `cmd` using a randomly seeded random number generator -/ def run_rand (cmd : _root_.rand α) : io α := do g ← io.mk_generator, return $ (cmd.run ⟨g⟩).1 /-- Run `cmd` using the provided seed. -/ def run_rand_with (seed : ℕ) (cmd : _root_.rand α) : io α := return $ (cmd.run ⟨mk_std_gen seed⟩).1 section random variables [random α] /-- randomly generate a value of type α -/ def random : io α := io.run_rand (rand.random α) /-- randomly generate an infinite series of value of type α -/ def random_series : io (stream α) := io.run_rand (rand.random_series α) end random section bounded_random variables [preorder α] [bounded_random α] /-- randomly generate a value of type α between `x` and `y` -/ def random_r (x y : α) (p : x ≤ y) : io (x .. y) := io.run_rand (bounded_random.random_r _ x y p) /-- randomly generate an infinite series of value of type α between `x` and `y` -/ def random_series_r (x y : α) (h : x ≤ y) : io (stream $ x .. y) := io.run_rand (rand.random_series_r x y h) end bounded_random end io namespace tactic /-- create a seeded random number generator in the `tactic` monad -/ meta def mk_generator : tactic std_gen := do tactic.unsafe_run_io @io.mk_generator /-- run `cmd` using the a randomly seeded random number generator in the tactic monad -/ meta def run_rand {α : Type u} (cmd : rand α) : tactic α := do ⟨g⟩ ← tactic.up mk_generator, return (cmd.run ⟨g⟩).1 variables {α : Type u} section bounded_random variables [preorder α] [bounded_random α] /-- Generate a random value between `x` and `y` inclusive. -/ meta def random_r (x y : α) (h : x ≤ y) : tactic (x .. y) := run_rand (rand.random_r x y h) /-- Generate an infinite series of random values of type `α` between `x` and `y` inclusive. -/ meta def random_series_r (x y : α) (h : x ≤ y) : tactic (stream $ x .. y) := run_rand (rand.random_series_r x y h) end bounded_random section random variables [random α] /-- randomly generate a value of type α -/ meta def random : tactic α := run_rand (rand.random α) /-- randomly generate an infinite series of value of type α -/ meta def random_series : tactic (stream α) := run_rand (rand.random_series α) end random end tactic open nat (succ one_add mod_eq_of_lt zero_lt_succ add_one succ_le_succ) variables {g : Type} [random_gen g] open nat namespace fin variables {n : ℕ} [ne_zero n] /-- generate a `fin` randomly -/ protected def random : rand_g g (fin n) := ⟨ λ ⟨g⟩, prod.map of_nat' up $ rand_nat g 0 n ⟩ end fin open nat instance nat_bounded_random : bounded_random ℕ := { random_r := λ g inst x y hxy, do z ← @fin.random g inst (succ $ y - x) _, pure ⟨z.val + x, nat.le_add_left _ _, by rw ← le_tsub_iff_right hxy; apply le_of_succ_le_succ z.is_lt⟩ } /-- This `bounded_random` interval generates integers between `x` and `y` by first generating a natural number between `0` and `y - x` and shifting the result appropriately. -/ instance int_bounded_random : bounded_random ℤ := { random_r := λ g inst x y hxy, do ⟨z,h₀,h₁⟩ ← @bounded_random.random_r ℕ _ _ g inst 0 (int.nat_abs $ y - x) dec_trivial, pure ⟨z + x, int.le_add_of_nonneg_left (int.coe_nat_nonneg _), int.add_le_of_le_sub_right $ le_trans (int.coe_nat_le_coe_nat_of_le h₁) (le_of_eq $ int.of_nat_nat_abs_eq_of_nonneg (int.sub_nonneg_of_le hxy)) ⟩ } instance fin_random (n : ℕ) [ne_zero n] : random (fin n) := { random := λ g inst, @fin.random g inst _ _ } instance fin_bounded_random (n : ℕ) : bounded_random (fin n) := { random_r := λ g inst (x y : fin n) p, do ⟨r, h, h'⟩ ← @rand.random_r ℕ g inst _ _ x.val y.val p, pure ⟨⟨r,lt_of_le_of_lt h' y.is_lt⟩, h, h'⟩ } /-- A shortcut for creating a `random (fin n)` instance from a proof that `0 < n` rather than on matching on `fin (succ n)` -/ def random_fin_of_pos : ∀ {n : ℕ} (h : 0 < n), random (fin n) | (succ n) _ := fin_random _ | 0 h := false.elim (nat.not_lt_zero _ h) lemma bool_of_nat_mem_Icc_of_mem_Icc_to_nat (x y : bool) (n : ℕ) : n ∈ (x.to_nat .. y.to_nat) → bool.of_nat n ∈ (x .. y) := begin simp only [and_imp, set.mem_Icc], intros h₀ h₁, split; [ have h₂ := bool.of_nat_le_of_nat h₀, have h₂ := bool.of_nat_le_of_nat h₁ ]; rw bool.of_nat_to_nat at h₂; exact h₂, end instance : random bool := { random := λ g inst, (bool.of_nat ∘ subtype.val) <$> @bounded_random.random_r ℕ _ _ g inst 0 1 (nat.zero_le _) } instance : bounded_random bool := { random_r := λ g _inst x y p, subtype.map bool.of_nat (bool_of_nat_mem_Icc_of_mem_Icc_to_nat x y) <$> @bounded_random.random_r ℕ _ _ g _inst x.to_nat y.to_nat (bool.to_nat_le_to_nat p) } /-- generate a random bit vector of length `n` -/ def bitvec.random (n : ℕ) : rand_g g (bitvec n) := bitvec.of_fin <$> rand.random (fin $ 2^n) /-- generate a random bit vector of length `n` -/ def bitvec.random_r {n : ℕ} (x y : bitvec n) (h : x ≤ y) : rand_g g (x .. y) := have h' : ∀ (a : fin (2 ^ n)), a ∈ (x.to_fin .. y.to_fin) → bitvec.of_fin a ∈ (x .. y), begin simp only [and_imp, set.mem_Icc], intros z h₀ h₁, replace h₀ := bitvec.of_fin_le_of_fin_of_le h₀, replace h₁ := bitvec.of_fin_le_of_fin_of_le h₁, rw bitvec.of_fin_to_fin at h₀ h₁, split; assumption, end, subtype.map bitvec.of_fin h' <$> rand.random_r x.to_fin y.to_fin (bitvec.to_fin_le_to_fin_of_le h) open nat instance random_bitvec (n : ℕ) : random (bitvec n) := { random := λ _ inst, @bitvec.random _ inst n } instance bounded_random_bitvec (n : ℕ) : bounded_random (bitvec n) := { random_r := λ _ inst x y p, @bitvec.random_r _ inst _ _ _ p }
(* generated by Ott 0.31, locally-nameless from: stlc.ott *) Require Import Bool. Require Import Metalib.Metatheory. Require Import List. Require Import Ott.ott_list_core. (** syntax *) Definition tvar : Set := var. (*r term variable *) Definition Tvar : Set := var. (*r type variable *) Inductive type : Set := (*r type *) | type_int : type (*r int *) | type_top : type (*r top *) | type_arrow (A:type) (B:type) (*r function *). Inductive term : Set := (*r term *) | term_int : term (*r int *) | term_var_b (_:nat) (*r variable *) | term_var_f (x:tvar) (*r variable *) | term_abs (e:term) (*r abstraction *) | term_app (e1:term) (e2:term) (*r application *) | term_annotation (e:term) (A:type) (*r type annotation *). (* EXPERIMENTAL *) (** auxiliary functions on the new list types *) (** library functions *) (** subrules *) (** arities *) (** opening up abstractions *) Fixpoint open_term_wrt_term_rec (k:nat) (e_5:term) (e__6:term) {struct e__6}: term := match e__6 with | term_int => term_int | (term_var_b nat) => if (k === nat) then e_5 else (term_var_b nat) | (term_var_f x) => term_var_f x | (term_abs e) => term_abs (open_term_wrt_term_rec (S k) e_5 e) | (term_app e1 e2) => term_app (open_term_wrt_term_rec k e_5 e1) (open_term_wrt_term_rec k e_5 e2) | (term_annotation e A) => term_annotation (open_term_wrt_term_rec k e_5 e) A end. Definition open_term_wrt_term e_5 e__6 := open_term_wrt_term_rec 0 e__6 e_5. (** terms are locally-closed pre-terms *) (** definitions *) (* defns LC_term *) Inductive lc_term : term -> Prop := (* defn lc_term *) | lc_term_int : (lc_term term_int) | lc_term_var_f : forall (x:tvar), (lc_term (term_var_f x)) | lc_term_abs : forall (L:vars) (e:term), ( forall x , x \notin L -> lc_term ( open_term_wrt_term e (term_var_f x) ) ) -> (lc_term (term_abs e)) | lc_term_app : forall (e1 e2:term), (lc_term e1) -> (lc_term e2) -> (lc_term (term_app e1 e2)) | lc_term_annotation : forall (e:term) (A:type), (lc_term e) -> (lc_term (term_annotation e A)). (** free variables *) (** substitutions *) (** definitions *) (* defns subtyping *) Inductive sub : type -> type -> Prop := (* defn sub *) | sub_S_Int : sub type_int type_int | sub_S_Top : forall (A:type), sub A type_top | sub_S_Arrow : forall (A B C D:type), sub C A -> sub B D -> sub (type_arrow A B) (type_arrow C D). (** infrastructure *) Hint Constructors sub lc_term : core. Theorem sub_transitivity: forall t2 t1 t3, sub t1 t2 -> sub t2 t3 -> sub t1 t3. Proof. induction t2; intros. - induction t1; eauto. inversion H. inversion H. - induction t1; auto. inversion H0. constructor. induction t3. inversion H0. constructor. inversion H0. - generalize dependent t1. generalize dependent t3. induction t1; intros. + inversion H. + inversion H. + induction t3; subst. * inversion H0. * constructor. * inversion H0; subst. inversion H; subst. constructor. apply IHt2_1 with (t1:=t3_1) (t3:=t1_1) in H4. assumption. assumption. apply IHt2_2 with (t1:=t1_2) (t3:=t3_2) in H8. assumption. assumption. Qed.
open import Agda.Builtin.Reflection open import Agda.Builtin.Equality open import Agda.Builtin.Int open import Agda.Builtin.String open import Common.Prelude getFixity = primQNameFixity infixl -1729 _to_ _to_ : Set → Set → Set A to B = A → B data Check : Set₁ where equal : {A : Set} (x y : A) → x ≡ y → Check pattern _==_ x y = equal x y refl check-cons = getFixity (quote _∷_) == fixity right-assoc (related (pos 5)) check-to = getFixity (quote _to_) == fixity left-assoc (related (negsuc 1728)) check-eq = getFixity (quote _≡_) == fixity non-assoc (related (pos 4)) check-list = getFixity (quote List) == fixity non-assoc unrelated showAssoc : Associativity → String showAssoc left-assoc = "infixl" showAssoc right-assoc = "infixr" showAssoc non-assoc = "infix" showFixity : Fixity → String showFixity (fixity a unrelated) = "(no fixity)" showFixity (fixity a (related p)) = showAssoc a +S+ " " +S+ intToString p showFix : Name → String showFix x = showFixity (getFixity x) main : IO Unit main = putStrLn (showFix (quote _∷_)) >>= λ _ → putStrLn (showFix (quote _to_)) >>= λ _ → putStrLn (showFix (quote _≡_)) >>= λ _ → putStrLn (showFix (quote List)) >>= λ _ → return unit
Nina and Tom is now GreenStar Design+Production. They are still making their cute tshirts under the brands of Butterbean and Made in Davis. You can purchase their shirts most Saturdays at the Davis Farmers Market and also online through ButterBean and Made in Davis. Products Organic cotton Tshirts for infants to adults Designed and printed in Davis, Butterbeans shirts are printed on highquality, supersoft cotton. Custom printing Silkscreening with waterbased inks. Talk to them and theyll give you an information sheet and explain the process. History Nina & Tom started selling political shirts at the Davis Farmers Market in the spring of 2004. They quickly expanded their business to include a whole line of clothing for kids with organic cotton shirts and onesies proclaiming I eat my vegetables and Im the big sister. All of their products were made in the USA. They sold local, handcrafted, and/or lowproduction goods, supporting small and independent businesses throughout the United States. There were purses, dolls, books, wallets, jewelery, and many other unique items. Their stores Grand Opening took place October 10th, 2008. Consignment goods Haute Again is a new venture for the Nina & Tom storefront as of September 2009. They now accept and sell http://en.wikipedia.org/wiki/Consignment consigned clothes and accessories. No Target Big Box items are accepted. The upscale consignment area, located in the upper area of the store, offers only current or vintage brand name, boutique and designer items, while also offering reasonable prices. Check out their http://hauteagain.blogspot.com/ blog. 20081111 21:16:23 nbsp These guys are really great. Great product, great message, genuine local coolness. Soft cotton. Mmmmmmmmmmmm.... Users/bhdjtd 20090706 16:27:10 nbsp How would one go about getting a job here? Its such a cute store! Users/ShaynaLesovoy 20090914 08:55:09 nbsp Excellent service and cute, quality tshirts. Ive bought several adultsized shirts as well as two superhero capes for my sonwhich he lovesand theyve all been highquality. Highly recommended! Users/LeslieMadsenBrooks
module InfList public export data InfList : Type -> Type where (::) : (value: elem) -> Inf (InfList elem) -> InfList elem %name InfList xs, ys, zs public export total countFrom : Integer -> InfList Integer countFrom x = x :: countFrom (x + 1) public export total labelFrom : InfList k -> List a -> List (k, a) labelFrom (key :: xs) [] = [] labelFrom (key :: xs) (y :: ys) = (key, y) :: labelFrom xs ys public export total labelWith : Stream labelType -> List a -> List (labelType, a) labelWith xs [] = [] labelWith (lbl :: lbls) (x :: xs) = (lbl, x) :: labelWith lbls xs public export total label : List a -> List (Integer, a) label = labelWith (iterate (+1) 0) public export total getPrefix : (count: Nat) -> InfList ty -> List ty getPrefix Z (value :: xs) = [] getPrefix (S k) (value :: xs) = value :: (getPrefix k xs)
[STATEMENT] lemma A2': "\<lbrakk>a b \<congruent> p q; a b \<congruent> r s\<rbrakk> \<Longrightarrow> p q \<congruent> r s" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>a b \<equiv> p q; a b \<equiv> r s\<rbrakk> \<Longrightarrow> p q \<equiv> r s [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. \<lbrakk>a b \<equiv> p q; a b \<equiv> r s\<rbrakk> \<Longrightarrow> p q \<equiv> r s [PROOF STEP] assume "a b \<congruent> p q" and "a b \<congruent> r s" [PROOF STATE] proof (state) this: a b \<equiv> p q a b \<equiv> r s goal (1 subgoal): 1. \<lbrakk>a b \<equiv> p q; a b \<equiv> r s\<rbrakk> \<Longrightarrow> p q \<equiv> r s [PROOF STEP] with A2 [PROOF STATE] proof (chain) picking this: \<forall>a b p q r s. a b \<equiv> p q \<and> a b \<equiv> r s \<longrightarrow> p q \<equiv> r s a b \<equiv> p q a b \<equiv> r s [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: \<forall>a b p q r s. a b \<equiv> p q \<and> a b \<equiv> r s \<longrightarrow> p q \<equiv> r s a b \<equiv> p q a b \<equiv> r s goal (1 subgoal): 1. p q \<equiv> r s [PROOF STEP] by blast [PROOF STATE] proof (state) this: p q \<equiv> r s goal: No subgoals! [PROOF STEP] qed
{-# LANGUAGE DataKinds #-} import GHC.TypeLits import Numeric.LinearAlgebra.Static import qualified Numeric.LinearAlgebra.HMatrix as LA a = row (vec4 1 2 3 4) u = vec4 10 20 30 40 v = vec2 5 0 & 0 & 3 & 7
#include "PrecHeader.h" #include <eco/test/Timing.h> //////////////////////////////////////////////////////////////////////////////// #include <boost/date_time/posix_time/ptime.hpp> #include <boost/date_time/posix_time/posix_time_types.hpp> ECO_NS_BEGIN(eco); ECO_NS_BEGIN(test); //////////////////////////////////////////////////////////////////////////////// class Timing::Impl { ECO_IMPL_INIT(Timing); public: boost::posix_time::ptime m_start; boost::posix_time::time_duration m_td; }; ECO_OBJECT_IMPL(Timing); //////////////////////////////////////////////////////////////////////////////// void Timing::start() { impl().m_start = boost::posix_time::microsec_clock::universal_time(); } Timing& Timing::timeup() { boost::posix_time::ptime time_end = boost::posix_time::microsec_clock::universal_time(); impl().m_td = time_end - impl().m_start; impl().m_start = time_end; return *this; } int64_t Timing::seconds() const { return impl().m_td.total_seconds(); } int64_t Timing::milliseconds() const { return impl().m_td.total_milliseconds(); } int64_t Timing::microseconds() const { return impl().m_td.total_microseconds(); } //////////////////////////////////////////////////////////////////////////////// ECO_NS_END(test); ECO_NS_END(eco);
Formal statement is: lemma continuous_on_open_vimage: "open s \<Longrightarrow> continuous_on s f \<longleftrightarrow> (\<forall>B. open B \<longrightarrow> open (f -` B \<inter> s))" Informal statement is: A function $f$ is continuous on an open set $S$ if and only if the preimage of every open set is open.
{-# OPTIONS --with-K #-} open import Level using (Level) open import Axiom.UniquenessOfIdentityProofs.WithK using (uip) open import Relation.Binary.PropositionalEquality open ≡-Reasoning open import Data.Nat using (ℕ) open import Data.Vec using (Vec) open import FLA.Axiom.Extensionality.Propositional open import FLA.Algebra.Structures open import FLA.Algebra.LinearAlgebra open import FLA.Algebra.LinearAlgebra.Properties open import FLA.Algebra.LinearMap module FLA.Algebra.LinearMap.Properties where private variable ℓ : Level A : Set ℓ m n p q : ℕ ⦃ F ⦄ : Field A ------------------------------------------------------------------------------- -- LinearMap without the proofs: LinearMap↓ -- ------------------------------------------------------------------------------- private data _⊸↓_ {A : Set ℓ} ⦃ F : Field A ⦄ (m n : ℕ) : Set ℓ where LM↓ : (Vec A m → Vec A n) → m ⊸↓ n _·ˡᵐ↓_ : ⦃ F : Field A ⦄ → m ⊸↓ n → Vec A m → Vec A n _·ˡᵐ↓_ (LM↓ f) = f -- Choose 20 since function application is assumed higher than almost anything infixr 20 _·ˡᵐ↓_ L→L↓ : ⦃ F : Field A ⦄ → m ⊸ n → m ⊸↓ n L→L↓ record { f = f } = LM↓ f L↓→L : ⦃ F : Field A ⦄ → (L↓ : m ⊸↓ n) → (f[u+v]≡f[u]+f[v] : (u v : Vec A m) → L↓ ·ˡᵐ↓ (u +ⱽ v) ≡ L↓ ·ˡᵐ↓ u +ⱽ L↓ ·ˡᵐ↓ v) → (f[c*v]≡c*f[v] : (c : A) → (v : Vec A m) → L↓ ·ˡᵐ↓ (c ∘ⱽ v) ≡ c ∘ⱽ (L↓ ·ˡᵐ↓ v)) → m ⊸ n L↓→L (LM↓ f) f[u+v]≡f[u]+f[v] f[c*v]≡c*f[v] = record { f = f ; f[u+v]≡f[u]+f[v] = f[u+v]≡f[u]+f[v] ; f[c*v]≡c*f[v] = f[c*v]≡c*f[v] } f[u+v]≡f[u]+f[v]-UIP : {ℓ : Level} {A : Set ℓ} {m n : ℕ} → ⦃ F : Field A ⦄ → (f : Vec A m → Vec A n) → (p q : (u v : Vec A m) → f (u +ⱽ v) ≡ f u +ⱽ f v) → p ≡ q f[u+v]≡f[u]+f[v]-UIP f p q = extensionality (λ u → extensionality (λ v → t f p q u v)) where t : {ℓ : Level} {A : Set ℓ} {m n : ℕ} → ⦃ F : Field A ⦄ → (f : Vec A m → Vec A n) → (p q : (u v : Vec A m) → f (u +ⱽ v) ≡ f u +ⱽ f v) → (u v : Vec A m) → p u v ≡ q u v t f p q u v = uip (p u v) (q u v) f[c*v]≡c*f[v]-UIP : {ℓ : Level} {A : Set ℓ} {m n : ℕ} → ⦃ F : Field A ⦄ → (f : Vec A m → Vec A n) → (p q : (c : A) (v : Vec A m) → f (c ∘ⱽ v) ≡ c ∘ⱽ (f v)) → p ≡ q f[c*v]≡c*f[v]-UIP f p q = extensionality (λ c → extensionality (λ v → t f p q c v)) where t : {ℓ : Level} {A : Set ℓ} {m n : ℕ} → ⦃ F : Field A ⦄ → (f : Vec A m → Vec A n) → (p q : (c : A) (v : Vec A m) → f (c ∘ⱽ v) ≡ c ∘ⱽ (f v)) → (c : A) (v : Vec A m) → p c v ≡ q c v t f p q c v = uip (p c v) (q c v) L↓≡→L≡ : ⦃ F : Field A ⦄ → (C D : m ⊸ n) → (L→L↓ C ≡ L→L↓ D) → C ≡ D L↓≡→L≡ record { f = f ; f[u+v]≡f[u]+f[v] = f[u+v]≡f[u]+f[v]ᶜ ; f[c*v]≡c*f[v] = f[c*v]≡c*f[v]ᶜ } record { f = .f ; f[u+v]≡f[u]+f[v] = f[u+v]≡f[u]+f[v]ᵈ ; f[c*v]≡c*f[v] = f[c*v]≡c*f[v]ᵈ } refl rewrite f[u+v]≡f[u]+f[v]-UIP f f[u+v]≡f[u]+f[v]ᶜ f[u+v]≡f[u]+f[v]ᵈ | f[c*v]≡c*f[v]-UIP f f[c*v]≡c*f[v]ᶜ f[c*v]≡c*f[v]ᵈ = refl ------------------------------------------------------------------------------- -- LinearMap Proofs via LinearMap↓ Proofs -- ------------------------------------------------------------------------------- module _ {ℓ : Level} {A : Set ℓ} ⦃ F : Field A ⦄ where open Field F open _⊸_ +ˡᵐ-comm : (L R : m ⊸ n) → L +ˡᵐ R ≡ R +ˡᵐ L +ˡᵐ-comm L R = L↓≡→L≡ (L +ˡᵐ R) (R +ˡᵐ L) (+ˡᵐ-comm↓ L R) where +ⱽ-comm-ext : (f g : Vec A m → Vec A n) → (λ v → f v +ⱽ g v) ≡ (λ v → g v +ⱽ f v) +ⱽ-comm-ext f g = extensionality (λ v → +ⱽ-comm (f v) (g v)) +ˡᵐ-comm↓ : (L R : m ⊸ n) → L→L↓ (L +ˡᵐ R) ≡ L→L↓ (R +ˡᵐ L) +ˡᵐ-comm↓ L R = cong LM↓ (+ⱽ-comm-ext (L ·ˡᵐ_) (R ·ˡᵐ_)) *ˡᵐ-distr-+ˡᵐₗ : (X : n ⊸ m) → (Y Z : p ⊸ n) → (X *ˡᵐ (Y +ˡᵐ Z)) ≡ (X *ˡᵐ Y +ˡᵐ X *ˡᵐ Z) *ˡᵐ-distr-+ˡᵐₗ X Y Z = L↓≡→L≡ (X *ˡᵐ (Y +ˡᵐ Z)) ((X *ˡᵐ Y +ˡᵐ X *ˡᵐ Z)) (*ˡᵐ-distr-+ˡᵐₗ↓ X Y Z) where *-distr-+ⱽ : (X : n ⊸ m) → (Y Z : p ⊸ n) → (λ v → X ·ˡᵐ (Y ·ˡᵐ v +ⱽ Z ·ˡᵐ v)) ≡ (λ v → X ·ˡᵐ (Y ·ˡᵐ v) +ⱽ X ·ˡᵐ (Z ·ˡᵐ v)) *-distr-+ⱽ X Y Z = extensionality (λ v → f[u+v]≡f[u]+f[v] X (Y ·ˡᵐ v) (Z ·ˡᵐ v)) *ˡᵐ-distr-+ˡᵐₗ↓ : (X : n ⊸ m) → (Y Z : p ⊸ n) → L→L↓ (X *ˡᵐ (Y +ˡᵐ Z)) ≡ L→L↓ (X *ˡᵐ Y +ˡᵐ X *ˡᵐ Z) *ˡᵐ-distr-+ˡᵐₗ↓ X Y Z = cong LM↓ (*-distr-+ⱽ X Y Z) *ˡᵐ-distr-+ˡᵐᵣ : (X Y : n ⊸ m) → (Z : p ⊸ n) → (X +ˡᵐ Y) *ˡᵐ Z ≡ X *ˡᵐ Z +ˡᵐ Y *ˡᵐ Z *ˡᵐ-distr-+ˡᵐᵣ X Y Z = L↓≡→L≡ ((X +ˡᵐ Y) *ˡᵐ Z) (X *ˡᵐ Z +ˡᵐ Y *ˡᵐ Z) (*ˡᵐ-distr-+ˡᵐᵣ↓ X Y Z) where *ˡᵐ-distr-+ˡᵐᵣ↓ : (X Y : n ⊸ m) → (Z : p ⊸ n) → L→L↓ ((X +ˡᵐ Y) *ˡᵐ Z) ≡ L→L↓ (X *ˡᵐ Z +ˡᵐ Y *ˡᵐ Z) *ˡᵐ-distr-+ˡᵐᵣ↓ X Y Z = cong LM↓ refl
FUNCTION RAN1_b(IDUM) implicit none integer idum,ia,im,iq,ir,ntab,ndiv real ran1_b,am,eps,rnmx parameter(ia=16807,im=2147483647,am=1./im,iq=127773,ir=2836, & ntab=32,ndiv=1+(im-1)/ntab,eps=1.2e-7,rnmx=1.-eps) ! Minimal random number generator of Park and Miller with Bays-Durham ! shuffle and added safeguards. Returns a uniform random deviate between ! 0.0 and 1.0 (exclusive of the endpoint values.) Call with idum a negative ! integer to initialize; thereafter, do not alter idum between successive ! deviates in a sequence. tnmx should approximate the largest floating ! value that is less than 1. From Numerical Recipes. integer j,k,iv(ntab),iy save iv,iy data iv /ntab*0/, iy /0/ if(idum.le.0.or.iy.eq.0)then idum=max(-idum,1) do j=ntab+8,1,-1 k=idum/iq idum=ia*(idum-k*iq)-ir*k if(idum.lt.0) idum=idum+im if(j.le.ntab) iv(j)=idum end do iy=iv(1) end if k=idum/iq idum=ia*(idum-k*iq)-ir*k if(idum.lt.0) idum=idum+im j=1+iy/ndiv iy=iv(j) iv(j)=idum ran1_b=min(am*iy,rnmx) return END FUNCTION RAN1_B
-- @@stderr -- dtrace: failed to compile script test/unittest/arrays/err.D_ARR_BOUNDS.declared-assignment.d: [D_ARR_BOUNDS] line 19: index outside array bounds: 5, max is 5
[STATEMENT] lemma in_graphI: "m k = Some v \<Longrightarrow> (k, v) \<in> graph m" [PROOF STATE] proof (prove) goal (1 subgoal): 1. m k = Some v \<Longrightarrow> (k, v) \<in> graph m [PROOF STEP] unfolding graph_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. m k = Some v \<Longrightarrow> (k, v) \<in> {(a, b) |a b. m a = Some b} [PROOF STEP] by blast
(* Title: Kleene Algebra Author: Alasdair Armstrong, Georg Struth, Tjark Weber Maintainer: Georg Struth <g.struth at sheffield.ac.uk> Tjark Weber <tjark.weber at it.uu.se> *) section \<open>Models of Omega Algebras\<close> theory Omega_Algebra_Models imports Omega_Algebra Kleene_Algebra_Models begin text \<open>The trace, path and language model are not really interesting in this setting.\<close> subsection \<open>Relation Omega Algebras\<close> text \<open>In the relational model, the omega of a relation relates all those elements in the domain of the relation, from which an infinite chain starts, with all other elements; all other elements are not related to anything~\cite{hofnerstruth10nontermination}. Thus, the omega of a relation is most naturally defined coinductively.\<close> coinductive_set omega :: "('a \<times> 'a) set \<Rightarrow> ('a \<times> 'a) set" for R where "\<lbrakk> (x, y) \<in> R; (y, z) \<in> omega R \<rbrakk> \<Longrightarrow> (x, z) \<in> omega R" (* FIXME: The equivalent, but perhaps more elegant point-free version "x \<in> R O omega R \<Longrightarrow> x \<in> omega R" fails due to missing monotonicity lemmas. *) text \<open>Isabelle automatically derives a case rule and a coinduction theorem for @{const omega}. We prove slightly more elegant variants.\<close> lemma omega_cases: "(x, z) \<in> omega R \<Longrightarrow> (\<And>y. (x, y) \<in> R \<Longrightarrow> (y, z) \<in> omega R \<Longrightarrow> P) \<Longrightarrow> P" by (metis omega.cases) lemma omega_coinduct: "X x z \<Longrightarrow> (\<And>x z. X x z \<Longrightarrow> \<exists>y. (x, y) \<in> R \<and> (X y z \<or> (y, z) \<in> omega R)) \<Longrightarrow> (x, z) \<in> omega R" by (metis (full_types) omega.coinduct) lemma omega_weak_coinduct: "X x z \<Longrightarrow> (\<And>x z. X x z \<Longrightarrow> \<exists>y. (x, y) \<in> R \<and> X y z) \<Longrightarrow> (x, z) \<in> omega R" by (metis omega.coinduct) interpretation rel_omega_algebra: omega_algebra "(\<union>)" "(O)" Id "{}" "(\<subseteq>)" "(\<subset>)" rtrancl omega proof fix x :: "'a rel" show "omega x \<subseteq> x O omega x" by (auto elim: omega_cases) next fix x y z :: "'a rel" assume *: "y \<subseteq> z \<union> x O y" { fix a b assume 1: "(a,b) \<in> y" and 2: "(a,b) \<notin> x\<^sup>* O z" have "(a,b) \<in> omega x" proof (rule omega_weak_coinduct[where X="\<lambda>a b. (a,b) \<in> x O y \<and> (a,b) \<notin> x\<^sup>* O z"]) show "(a,b) \<in> x O y \<and> (a,b) \<notin> x\<^sup>* O z" using "*" "1" "2" by auto next fix a c assume 1: "(a,c) \<in> x O y \<and> (a,c) \<notin> x\<^sup>* O z" then obtain b where 2: "(a,b) \<in> x" and "(b,c) \<in> y" by auto then have "(b,c) \<in> x O y" using "*" "1" by blast moreover have "(b,c) \<notin> x\<^sup>* O z" using "1" "2" by (meson relcomp.cases relcomp.intros converse_rtrancl_into_rtrancl) ultimately show "\<exists>b. (a,b) \<in> x \<and> (b,c) \<in> x O y \<and> (b,c) \<notin> x\<^sup>* O z" using "2" by blast qed } then show "y \<subseteq> omega x \<union> x\<^sup>* O z" by auto qed end
{-# OPTIONS --cubical --safe #-} -- Free join semilattice module Algebra.Construct.Free.Semilattice where open import Algebra.Construct.Free.Semilattice.Definition public open import Algebra.Construct.Free.Semilattice.Eliminators public open import Algebra.Construct.Free.Semilattice.Union public using (_∪_; 𝒦-semilattice) open import Algebra.Construct.Free.Semilattice.Homomorphism public using (μ; ∙-hom)
If two topological spaces are homotopy equivalent, then a map from a third space to the first space is homotopic to a map to the second space if and only if the two maps are homotopic.
function test_suite=test_assert_exception_thrown() try % assignment of 'localfunctions' is necessary in Matlab >= 2016 test_functions=localfunctions(); catch % no problem; early Matlab versions can use initTestSuite fine end initTestSuite; % Test cases where exceptions are thrown and that is OK function test_assert_exception_thrown_passes assertExceptionThrown(@()error('Throw w/o ID')); assertExceptionThrown(@()error('moxunit:error','msg'),... 'moxunit:error'); assertExceptionThrown(@()error('moxunit:error','msg'),... 'moxunit:error','message'); assertExceptionThrown(@()error('moxunit:error','msg'),... 'moxunit:error'); assertExceptionThrown(@()error('moxunit:error','msg'),... '*','message'); % Same as above assertExceptionThrown(@()error('Throw w/o ID'),... '*','message'); % Same as above assertExceptionThrown(@()error('moxunit:error','msg'),... '*'); % Any error OK assertExceptionThrown(@()error('Throw w/o ID'),... '*'); % Same as above % Explicitly assert that an error is thrown without an ID assertExceptionThrown(@()error('Throw w/o ID'),... ''); % Allow id to be a cellstr assertExceptionThrown(@()error('moxunit:error','msg'),... {'moxunit:error'},'message'); assertExceptionThrown(@()error('Throw w/o ID'),... '*','message'); assertExceptionThrown(@()error('moxunit:error','msg'),... {'moxunit:foo','moxunit:error','moxunit:foo'}); assertExceptionThrown(@()error('Throw w/o ID'),... {'','moxunit:baz'}); function test_assert_exception_thrown_illegal_arguments args_cell={ ... {@()error('foo'),'message'},... {@()error('foo'),'not:id:_entifier','message'},... {@()error('foo'),struct},... {@()error('foo'),9},... {@()error('foo'),'error:id',9},... {@()error('foo'),'error:id',struct},... {@()error('foo'),'error_id','message'},... {'foo'},... }; for k=1:numel(args_cell) args=args_cell{k}; try assertExceptionThrown(args{:}) error_exception_not_thrown('moxunit:illegalParameter'); catch [unused,error_id]=lasterr(); error_if_wrong_id_thrown('moxunit:illegalParameter',error_id); end end % Test cases where func throws exceptions and we need to throw as well function test_assert_exception_thrown_wrong_exception % Verify that when func throws but the wrong exception comes out, we respond % with the correct exception (assertExceptionThrown:wrongException) exception_id_cell = {'moxunit:failed',... '',... {'','moxunit:failed'},... }; for k=1:numel(exception_id_cell) exception_id=exception_id_cell{k}; try assertExceptionThrown(@()error('moxunit:error','msg'),... exception_id,'msg'); error_exception_not_thrown('moxunit:wrongExceptionRaised'); catch [unused,error_id]=lasterr(); error_if_wrong_id_thrown('moxunit:wrongExceptionRaised',... error_id); end end % Test cases where func does not throw but was expected to do so function test_assert_exception_thrown_exceptions_not_thrown % For all combination of optional arguments we expect the same % behavior. We will loop, testing all combinations here args_cell = {... {@do_nothing},... % No arguments {@do_nothing,'moxunit:failed'},... % Identifier only {@do_nothing,'*','message'},... % Wildcard {@do_nothing,'a:b','msg'},... % All arguments {@do_nothing,{'a:b','c:d'},'msg'} % Cell str }; for k=1:numel(args_cell) args=args_cell{k}; % Run the test try assertExceptionThrown(args{:}); error_exception_not_thrown('moxunit:exceptionNotRaised'); catch [unused,error_id]=lasterr(); error_if_wrong_id_thrown('moxunit:exceptionNotRaised',... error_id); end end function error_exception_not_thrown(error_id) error('moxunit:exceptionNotRaised', 'Exception ''%s'' not thrown', error_id); function error_if_wrong_id_thrown(expected_error_id, thrown_error_id) if ~strcmp(thrown_error_id, expected_error_id) error('moxunit:wrongExceptionRaised',... 'Exception raised with id ''%s'' expected id ''%s''',... thrown_error_id,expected_error_id); end function do_nothing % do nothing
function [beta_gibbs,sigma_gibbs]=ndgibbstotal(It,Bu,X,Y,y,Bhat,n,T,q) % modified ndgibbs sampler: insensitive to hyperparameters, total diffuse, "flat" prior in spirit of Uhlig (2005) % function [beta_gibbs sigma_gibbs]=bear.ndgibbs(It,Bu,beta0,omega0,X,Y,y,Bhat,n,T,q) % performs the Gibbs algorithm 1.5.2 for the normal-diffuse prior, and returns draws from posterior distribution % inputs: - integer 'It': total number of iterations of the Gibbs sampler (defined p 28 of technical guide) % - integer 'Bu': number of burn-in iterations of the Gibbs sampler (defined p 28 of technical guide) % - vector 'beta0': vector of prior values for beta (defined in 1.3.4) % - matrix 'omega0': prior covariance matrix for the VAR coefficients (defined in 1.3.8) % - matrix 'X': matrix of regressors for the VAR model (defined in 1.1.8) % - matrix 'Y': matrix of regressands for the VAR model (defined in 1.1.8) % - vector 'y': vectorised regressands for the VAR model (defined in 1.1.12) % - matrix 'Bhat': OLS VAR coefficients, in non vectorised form (defined in 1.1.9) % - integer 'n': number of endogenous variables in the BVAR model (defined p 7 of technical guide) % - integer 'T': number of sample time periods (defined p 7 of technical guide) % - integer 'q': total number of coefficients to estimate for the BVAR model (defined p 7 of technical guide) % outputs: - matrix 'beta_gibbs': record of the gibbs sampler draws for the beta vector % - matrix'sigma_gibbs': record of the gibbs sampler draws for the sigma matrix (vectorised) % preliminary tasks % % invert omega0, as it will be used repeatedly during step 4 % invomega0=diag(1./diag(omega0)); % set initial values for B (step 2); use OLS estimates B=Bhat; % create the progress bar hbar = bear.parfor_progressbar(It,'Progress of the Gibbs sampler.'); % start iterations for ii=1:It % Step 3: at iteration ii, first draw sigma from IW, conditional on beta from previous iteration % obtain first Shat, defined in (1.6.10) Shat=(Y-X*B)'*(Y-X*B); % Correct potential asymmetries due to rounding errors from Matlab C=chol(bear.nspd(Shat)); Shat=C'*C; % next draw from IW(Shat,T) sigma=bear.iwdraw(Shat,T); % step 4: with sigma drawn, continue iteration ii by drawing beta from a multivariate Normal, conditional on sigma obtained in current iteration % first invert sigma C=chol(bear.nspd(sigma)); invC=C\speye(n); invsigma=invC*invC'; % then obtain the omegabar matrix invomegabar=kron(invsigma,X'*X); C=chol(bear.nspd(invomegabar)); invC=C\speye(q); omegabar=invC*invC'; % following, obtain betabar betabar=omegabar*(kron(invsigma,X')*y); % draw from N(betabar,omegabar); beta=betabar+chol(bear.nspd(omegabar),'lower')*mvnrnd(zeros(q,1),eye(q))'; % % update matrix B with each draw % B=reshape(beta,size(B)); % record the values if the number of burn-in iterations is exceeded if ii>Bu % values of vector beta beta_gibbs(:,ii-Bu)=beta; % values of sigma (in vectorized form) sigma_gibbs(:,ii-Bu)=sigma(:); % if current iteration is still a burn iteration, do not record the result else end % update progress by one iteration hbar.iterate(1); % go for next iteration end % close progress bar close(hbar);
{-# OPTIONS --without-K --safe #-} module Data.Binary.Definitions where open import Function open import Data.Binary.Bits public open import Data.List using (_∷_) renaming ([] to 1ᵇ) public open import Data.Maybe open import Data.Product 𝔹⁺ : Set 𝔹⁺ = Data.List.List Bit 𝔹 : Set 𝔹 = Maybe 𝔹⁺ infixr 5 0<_ pattern 0ᵇ = nothing pattern 0<_ x = just x 𝔹± : Set 𝔹± = Maybe (Bit × 𝔹⁺)
//============================================================================== // Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef BOOST_DISPATCH_META_SIGN_OF_HPP_INCLUDED #define BOOST_DISPATCH_META_SIGN_OF_HPP_INCLUDED #include <boost/utility/enable_if.hpp> #include <boost/type_traits/is_signed.hpp> #include <boost/type_traits/is_unsigned.hpp> #include <boost/dispatch/meta/primitive_of.hpp> #include <boost/type_traits/is_floating_point.hpp> namespace boost { namespace dispatch { namespace meta { //============================================================================ /*! Computes the signedness of a given type. * * \tparam T Type to compute signedness from. * \return If \c T is signed, \c sign_of<T>::type is \c signed, otherwsie, it * is \c unsigned. **/ //============================================================================ template<class T> struct sign_of; } } } namespace boost { namespace dispatch { namespace ext { template<class T, class Enable = void> struct sign_of : sign_of< typename meta::primitive_of<T>::type > {}; template<class T> struct sign_of<T, typename enable_if< boost::is_signed<T> >::type> { typedef signed type; }; template<class T> struct sign_of<T, typename enable_if< boost::is_unsigned<T> >::type> { typedef unsigned type; }; template<class T> struct sign_of<T, typename enable_if< boost::is_floating_point<T> >::type> { typedef signed type; }; } } } namespace boost { namespace dispatch { namespace meta { template<class T> struct sign_of : ext::sign_of<T> {}; template<class T> struct sign_of<T&> : sign_of <T> {}; template<class T> struct sign_of<T const> : sign_of <T> {}; } } } #endif
[STATEMENT] lemma F1in_alt: "F1in A2 A3 = Fin UNIV A2 A3" [PROOF STATE] proof (prove) goal (1 subgoal): 1. {x. F1set1 x \<subseteq> A2 \<and> F2set x \<subseteq> A3} = {x. Fset1 x \<subseteq> UNIV \<and> F1set1 x \<subseteq> A2 \<and> F2set x \<subseteq> A3} [PROOF STEP] by (tactic \<open>BNF_Comp_Tactics.kill_in_alt_tac @{context}\<close>)
lemma LIMSEQ_const_iff: "(\<lambda>n. k) \<longlonglongrightarrow> l \<longleftrightarrow> k = l" for k l :: "'a::t2_space"
{- This file contains a summary of the proof that π₄(S³) ≡ ℤ/2ℤ The --experimental-lossy-unification flag is used to speed up type checking. The file still type checks without it, but it's a lot slower (about 10 times). -} {-# OPTIONS --safe --experimental-lossy-unification #-} module Cubical.Homotopy.Group.Pi4S3.Summary where open import Cubical.Foundations.Prelude open import Cubical.Foundations.Pointed open import Cubical.Data.Nat.Base open import Cubical.Data.Sigma.Base open import Cubical.HITs.Sn open import Cubical.HITs.SetTruncation open import Cubical.Homotopy.HopfInvariant.Base open import Cubical.Homotopy.HopfInvariant.Homomorphism open import Cubical.Homotopy.HopfInvariant.HopfMap open import Cubical.Homotopy.HopfInvariant.Brunerie open import Cubical.Homotopy.Whitehead open import Cubical.Homotopy.Group.Base hiding (π) open import Cubical.Homotopy.Group.Pi3S2 open import Cubical.Homotopy.Group.Pi4S3.BrunerieNumber open import Cubical.Algebra.Group.Base open import Cubical.Algebra.Group.Instances.Bool open import Cubical.Algebra.Group.Morphisms open import Cubical.Algebra.Group.GroupPath open import Cubical.Algebra.Group.MorphismProperties open import Cubical.Algebra.Group.Instances.Int open import Cubical.Algebra.Group.Instances.IntMod open import Cubical.Algebra.Group.ZAction -- Homotopy groups (shifted version of π'Gr to get nicer numbering) π : ℕ → Pointed₀ → Group₀ π n X = π'Gr (predℕ n) X -- Nicer notation for the spheres (as pointed types) 𝕊² 𝕊³ : Pointed₀ 𝕊² = S₊∙ 2 𝕊³ = S₊∙ 3 -- The Brunerie number; defined in Cubical.Homotopy.Group.Pi4S3.BrunerieNumber -- as "abs (HopfInvariant-π' 0 ([ (∣ idfun∙ _ ∣₂ , ∣ idfun∙ _ ∣₂) ]×))" β : ℕ β = Brunerie -- The connection to π₄(S³) is then also proved in the BrunerieNumber -- file following Corollary 3.4.5 in Guillaume Brunerie's PhD thesis. βSpec : GroupEquiv (π 4 𝕊³) (ℤGroup/ β) βSpec = BrunerieIso -- Ideally one could prove that β is 2 by normalization, but this does -- not seem to terminate before we run out of memory. To try normalize -- this use "C-u C-c C-n β≡2" (which normalizes the term, ignoring -- abstract's). So instead we prove this by hand as in the second half -- of Guillaume's thesis. β≡2 : β ≡ 2 β≡2 = Brunerie≡2 -- This involves a lot of theory, for example that π₃(S²) ≃ ℤGroup where -- the underlying map is induced by the Hopf invariant (which involves -- the cup product on cohomology). _ : GroupEquiv (π 3 𝕊²) ℤGroup _ = hopfInvariantEquiv -- Which is a consequence of the fact that π₃(S²) is generated by the -- Hopf map. _ : gen₁-by (π 3 𝕊²) ∣ HopfMap ∣₂ _ = π₂S³-gen-by-HopfMap -- etc. For more details see the proof of "Brunerie≡2". -- Combining all of this gives us the desired equivalence of groups: π₄S³≃ℤ/2ℤ : GroupEquiv (π 4 𝕊³) (ℤGroup/ 2) π₄S³≃ℤ/2ℤ = subst (GroupEquiv (π 4 𝕊³)) (cong ℤGroup/_ β≡2) βSpec -- By the SIP this induces an equality of groups: π₄S³≡ℤ/2ℤ : π 4 𝕊³ ≡ ℤGroup/ 2 π₄S³≡ℤ/2ℤ = GroupPath _ _ .fst π₄S³≃ℤ/2ℤ -- As a sanity check we also establish the equality with Bool: π₄S³≡Bool : π 4 𝕊³ ≡ BoolGroup π₄S³≡Bool = π₄S³≡ℤ/2ℤ ∙ GroupPath _ _ .fst (GroupIso→GroupEquiv ℤGroup/2≅Bool)
||| Utilities for Language.Reflection.Refined module Language.Reflection.Refined.Util import public Data.Maybe import public Data.So %default total -------------------------------------------------------------------------------- -- Utilities -------------------------------------------------------------------------------- public export maybeSo : (b : Bool) -> Maybe (So b) maybeSo True = Just Oh maybeSo False = Nothing public export refineSo : {f : a -> Bool} -> (make : (v : a) -> (0 prf : So $ f v) -> b) -> (val : a) -> Maybe b refineSo make val = case maybeSo (f val) of Just oh => Just $ make val oh Nothing => Nothing
PISubstatus <- function(substatus = NULL, message = NULL, webException = NULL) { if (is.null(substatus) == FALSE) { if (check.integer(substatus) == FALSE) { return (print(paste0("Error: substatus must be an integer."))) } } if (is.null(message) == FALSE) { if (is.character(message) == FALSE) { return (print(paste0("Error: message must be a string."))) } } if (is.null(webException) == FALSE) { className <- attr(webException, "className") if ((is.null(className)) || (className != "PIWebException")) { return (print(paste0("Error: the class from the parameter webException should be PIWebException."))) } } value <- list( Substatus = substatus, Message = message, WebException = webException) valueCleaned <- rmNullObs(value) attr(valueCleaned, "className") <- "PISubstatus" return(valueCleaned) }
module Java.IO import IdrisJvm.IO import Java.Lang %access public export namespace File fileClass : String fileClass = "java/io/File" FileClass : JVM_NativeTy FileClass = Class fileClass File : Type File = JVM_Native FileClass namespace IOException IOException : Type IOException = JVM_Native (Class "java/io/IOException") new : String -> JVM_IO IOException new = FFI.new (String -> JVM_IO IOException) namespace OutputStream OutputStream : Type OutputStream = JVM_Native (Class "java/io/OutputStream") Inherits Closeable OutputStream where {} Inherits Flushable OutputStream where {} namespace BufferedReader BufferedReader : Type BufferedReader = JVM_Native (Class "java/io/BufferedReader")
[STATEMENT] lemma minimal_set: "{} \<sqsubseteq> S" [PROOF STATE] proof (prove) goal (1 subgoal): 1. {} \<sqsubseteq> S [PROOF STEP] unfolding below_set_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. {} \<subseteq> S [PROOF STEP] by simp
Around 04 : 00 on June 25 , the KPA 's 5th Division began its first attacks on the ROK 10th Regiment 's forward positions . Three hours later , the 766th Regiment 's two battalions landed at the village of Imwonjin , using motor and sail boats to land troops and mustering South Korean villagers to assist in setting up supplies . The two battalions separated ; one headed into the T <unk> Mountains and the second advanced north toward <unk> . At this point , the ROK 8th Division , under heavy attack from the front and aware of attacks in the rear , urgently requested reinforcements . It was denied these reinforcements , as ROK higher commanders informed the division commander that the ROK Army was under heavy attack across the entirety of the 38th parallel and had no reinforcements to spare .
If $c \neq 0$, then the Lebesgue integral of $c$ times a function $f$ is equal to the Lebesgue integral of $f$.
[STATEMENT] lemma in_graphD: "(k, v) \<in> graph m \<Longrightarrow> m k = Some v" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (k, v) \<in> graph m \<Longrightarrow> m k = Some v [PROOF STEP] unfolding graph_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. (k, v) \<in> {(a, b) |a b. m a = Some b} \<Longrightarrow> m k = Some v [PROOF STEP] by blast
theory T16 imports Main begin lemma "( (\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) & (\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(meet(x, y), z) = meet(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(x, join(y, z)) = join(undr(x, y), undr(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(x, meet(y, z)) = join(over(x, y), over(x, z))) & (\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) & (\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) & (\<forall> x::nat. invo(invo(x)) = x) ) \<longrightarrow> (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, meet(y, z)) = meet(mult(x, y), mult(x, z))) " nitpick[card nat=7,timeout=86400] oops end
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.full_subcategory import category_theory.limits.shapes.equalizers import category_theory.limits.shapes.products import topology.sheaves.presheaf /-! # The sheaf condition in terms of an equalizer of products Here we set up the machinery for the "usual" definition of the sheaf condition, e.g. as in https://stacks.math.columbia.edu/tag/0072 in terms of an equalizer diagram where the two objects are `∏ F.obj (U i)` and `∏ F.obj (U i) ⊓ (U j)`. -/ universes v u noncomputable theory open category_theory open category_theory.limits open topological_space open opposite open topological_space.opens namespace Top variables {C : Type u} [category.{v} C] [has_products C] variables {X : Top.{v}} (F : presheaf C X) {ι : Type v} (U : ι → opens X) namespace presheaf namespace sheaf_condition_equalizer_products /-- The product of the sections of a presheaf over a family of open sets. -/ def pi_opens : C := ∏ (λ i : ι, F.obj (op (U i))) /-- The product of the sections of a presheaf over the pairwise intersections of a family of open sets. -/ def pi_inters : C := ∏ (λ p : ι × ι, F.obj (op (U p.1 ⊓ U p.2))) /-- The morphism `Π F.obj (U i) ⟶ Π F.obj (U i) ⊓ (U j)` whose components are given by the restriction maps from `U i` to `U i ⊓ U j`. -/ def left_res : pi_opens F U ⟶ pi_inters F U := pi.lift (λ p : ι × ι, pi.π _ p.1 ≫ F.map (inf_le_left (U p.1) (U p.2)).op) /-- The morphism `Π F.obj (U i) ⟶ Π F.obj (U i) ⊓ (U j)` whose components are given by the restriction maps from `U j` to `U i ⊓ U j`. -/ def right_res : pi_opens F U ⟶ pi_inters F U := pi.lift (λ p : ι × ι, pi.π _ p.2 ≫ F.map (inf_le_right (U p.1) (U p.2)).op) /-- The morphism `F.obj U ⟶ Π F.obj (U i)` whose components are given by the restriction maps from `U j` to `U i ⊓ U j`. -/ def res : F.obj (op (supr U)) ⟶ pi_opens F U := pi.lift (λ i : ι, F.map (topological_space.opens.le_supr U i).op) @[simp, elementwise] lemma res_π (i : ι) : res F U ≫ limit.π _ ⟨i⟩ = F.map (opens.le_supr U i).op := by rw [res, limit.lift_π, fan.mk_π_app] @[elementwise] lemma w : res F U ≫ left_res F U = res F U ≫ right_res F U := begin dsimp [res, left_res, right_res], ext, simp only [limit.lift_π, limit.lift_π_assoc, fan.mk_π_app, category.assoc], rw [←F.map_comp], rw [←F.map_comp], congr, end /-- The equalizer diagram for the sheaf condition. -/ @[reducible] def diagram : walking_parallel_pair.{v} ⥤ C := parallel_pair (left_res F U) (right_res F U) /-- The restriction map `F.obj U ⟶ Π F.obj (U i)` gives a cone over the equalizer diagram for the sheaf condition. The sheaf condition asserts this cone is a limit cone. -/ def fork : fork.{v} (left_res F U) (right_res F U) := fork.of_ι _ (w F U) @[simp] lemma fork_X : (fork F U).X = F.obj (op (supr U)) := rfl @[simp] lemma fork_ι : (fork F U).ι = res F U := rfl @[simp] lemma fork_π_app_walking_parallel_pair_zero : (fork F U).π.app walking_parallel_pair.zero = res F U := rfl @[simp] lemma fork_π_app_walking_parallel_pair_one : (fork F U).π.app walking_parallel_pair.one = res F U ≫ left_res F U := rfl variables {F} {G : presheaf C X} /-- Isomorphic presheaves have isomorphic `pi_opens` for any cover `U`. -/ @[simp] def pi_opens.iso_of_iso (α : F ≅ G) : pi_opens F U ≅ pi_opens G U := pi.map_iso (λ X, α.app _) /-- Isomorphic presheaves have isomorphic `pi_inters` for any cover `U`. -/ @[simp] def pi_inters.iso_of_iso (α : F ≅ G) : pi_inters F U ≅ pi_inters G U := pi.map_iso (λ X, α.app _) /-- Isomorphic presheaves have isomorphic sheaf condition diagrams. -/ def diagram.iso_of_iso (α : F ≅ G) : diagram F U ≅ diagram G U := nat_iso.of_components begin rintro ⟨⟩, exact pi_opens.iso_of_iso U α, exact pi_inters.iso_of_iso U α end begin rintro ⟨⟩ ⟨⟩ ⟨⟩, { simp, }, { ext, simp [left_res], }, { ext, simp [right_res], }, { simp, }, end. /-- If `F G : presheaf C X` are isomorphic presheaves, then the `fork F U`, the canonical cone of the sheaf condition diagram for `F`, is isomorphic to `fork F G` postcomposed with the corresponding isomorphism between sheaf condition diagrams. -/ def fork.iso_of_iso (α : F ≅ G) : fork F U ≅ (cones.postcompose (diagram.iso_of_iso U α).inv).obj (fork G U) := begin fapply fork.ext, { apply α.app, }, { ext, dunfold fork.ι, -- Ugh, `simp` can't unfold abbreviations. simp [res, diagram.iso_of_iso], } end section open_embedding variables {V : Top.{v}} {j : V ⟶ X} (oe : open_embedding j) variables (𝒰 : ι → opens V) /-- Push forward a cover along an open embedding. -/ @[simp] def cover.of_open_embedding : ι → opens X := (λ i, oe.is_open_map.functor.obj (𝒰 i)) /-- The isomorphism between `pi_opens` corresponding to an open embedding. -/ @[simp] def pi_opens.iso_of_open_embedding : pi_opens (oe.is_open_map.functor.op ⋙ F) 𝒰 ≅ pi_opens F (cover.of_open_embedding oe 𝒰) := pi.map_iso (λ X, F.map_iso (iso.refl _)) /-- The isomorphism between `pi_inters` corresponding to an open embedding. -/ @[simp] def pi_inters.iso_of_open_embedding : pi_inters (oe.is_open_map.functor.op ⋙ F) 𝒰 ≅ pi_inters F (cover.of_open_embedding oe 𝒰) := pi.map_iso (λ X, F.map_iso begin dsimp [is_open_map.functor], exact iso.op { hom := hom_of_le (by { simp only [oe.to_embedding.inj, set.image_inter], exact le_rfl, }), inv := hom_of_le (by { simp only [oe.to_embedding.inj, set.image_inter], exact le_rfl, }), }, end) /-- The isomorphism of sheaf condition diagrams corresponding to an open embedding. -/ def diagram.iso_of_open_embedding : diagram (oe.is_open_map.functor.op ⋙ F) 𝒰 ≅ diagram F (cover.of_open_embedding oe 𝒰) := nat_iso.of_components begin rintro ⟨⟩, exact pi_opens.iso_of_open_embedding oe 𝒰, exact pi_inters.iso_of_open_embedding oe 𝒰 end begin rintro ⟨⟩ ⟨⟩ ⟨⟩, { simp, }, { ext, dsimp [left_res, is_open_map.functor], simp only [limit.lift_π, cones.postcompose_obj_π, iso.op_hom, discrete.nat_iso_hom_app, functor.map_iso_refl, functor.map_iso_hom, lim_map_π_assoc, limit.lift_map, fan.mk_π_app, nat_trans.comp_app, category.assoc], dsimp, rw [category.id_comp, ←F.map_comp], refl, }, { ext, dsimp [right_res, is_open_map.functor], simp only [limit.lift_π, cones.postcompose_obj_π, iso.op_hom, discrete.nat_iso_hom_app, functor.map_iso_refl, functor.map_iso_hom, lim_map_π_assoc, limit.lift_map, fan.mk_π_app, nat_trans.comp_app, category.assoc], dsimp, rw [category.id_comp, ←F.map_comp], refl, }, { simp, }, end. /-- If `F : presheaf C X` is a presheaf, and `oe : U ⟶ X` is an open embedding, then the sheaf condition fork for a cover `𝒰` in `U` for the composition of `oe` and `F` is isomorphic to sheaf condition fork for `oe '' 𝒰`, precomposed with the isomorphism of indexing diagrams `diagram.iso_of_open_embedding`. We use this to show that the restriction of sheaf along an open embedding is still a sheaf. -/ def fork.iso_of_open_embedding : fork (oe.is_open_map.functor.op ⋙ F) 𝒰 ≅ (cones.postcompose (diagram.iso_of_open_embedding oe 𝒰).inv).obj (fork F (cover.of_open_embedding oe 𝒰)) := begin fapply fork.ext, { dsimp [is_open_map.functor], exact F.map_iso (iso.op { hom := hom_of_le (by simp only [supr_s, supr_mk, le_def, subtype.coe_mk, set.le_eq_subset, set.image_Union]), inv := hom_of_le (by simp only [supr_s, supr_mk, le_def, subtype.coe_mk, set.le_eq_subset, set.image_Union]) }), }, { ext ⟨j⟩, dunfold fork.ι, -- Ugh, it is unpleasant that we need this. simp only [res, diagram.iso_of_open_embedding, discrete.nat_iso_inv_app, functor.map_iso_inv, limit.lift_π, cones.postcompose_obj_π, functor.comp_map, fork_π_app_walking_parallel_pair_zero, pi_opens.iso_of_open_embedding, nat_iso.of_components.inv_app, functor.map_iso_refl, functor.op_map, limit.lift_map, fan.mk_π_app, nat_trans.comp_app, quiver.hom.unop_op, category.assoc, lim_map_eq_lim_map], dsimp, rw [category.comp_id, ←F.map_comp], refl, }, end end open_embedding end sheaf_condition_equalizer_products end presheaf end Top
From Coq Require Import Arith ZArith OrderedType. From mathcomp Require Import ssreflect ssrfun ssrbool ssrnat eqtype seq. From nbits Require Import NBits. From ssrlib Require Import Types SsrOrder Var Nats ZAriths Tactics. From BitBlasting Require Import Typ TypEnv State QFBV CNF BBExport AdhereConform. From BBCache Require Import CompCache BitBlastingCCacheDef. Set Implicit Arguments. Unset Strict Implicit. Import Prenex Implicits. Ltac auto_prove_neq_by_len := match goal with | Hlen : is_true (QFBV.len_exp ?e1 < QFBV.len_exp ?e2) |- ~ is_true (?e2 == ?e1) => let Heq := fresh in move/eqP=> Heq; rewrite Heq /= ltnn in Hlen; done | Hlen : is_true (QFBV.len_bexp ?e1 < QFBV.len_bexp ?e2) |- ~ is_true (?e2 == ?e1) => let Heq := fresh in move/eqP=> Heq; rewrite Heq /= ltnn in Hlen; done end. Ltac auto_prove_lt := match goal with | H : is_true (?a.+1 < ?p) |- is_true (?a < ?p) => by apply: (ltn_trans (ltnSn a)) | H : is_true ((?a + ?b).+1 < ?p) |- is_true (?a < ?p) => let Haux := fresh in (have Haux : a < (a + b).+1 by apply leq_addr); exact: (ltn_trans Haux H) | H : is_true ((?b + ?a).+1 < ?p) |- is_true (?a < ?p) => let Haux := fresh in (have Haux : a < (b + a).+1 by apply leq_addl); exact: (ltn_trans Haux H) | H : is_true ((?a + ?b + ?c).+1 < ?p) |- is_true (?a < ?p) => let Haux := fresh in (have Haux : a < (a + b + c).+1 by rewrite -addnA; exact: leq_addr); exact: (ltn_trans Haux H) | H : is_true ((?b + ?a + ?c).+1 < ?p) |- is_true (?a < ?p) => let Haux := fresh in (have Haux : a < (b + a + c).+1 by rewrite (addnC b) -addnA; exact: leq_addr); exact: (ltn_trans Haux H) | |- is_true (?a < ?a.+1) => exact: leqnn | |- is_true (?a < (?a + _).+1) => exact: leq_addr | |- is_true (?a < (_ + ?a).+1) => exact: leq_addl | |- is_true (?a < (?a + _ + _).+1) => rewrite -addnA; exact: leq_addr | |- is_true (?a < (?b + ?a + _).+1) => rewrite (addnC b) -addnA; exact: leq_addr end. Ltac auto_prove_len_lt := match goal with | H : is_true (QFBV.len_exp ?e0 < QFBV.len_exp ?e) |- is_true (QFBV.len_exp ?e1 < QFBV.len_exp ?e) => match e0 with | context [e1] => rewrite /= in H; by auto_prove_lt end | H : is_true (QFBV.len_exp ?e0 < QFBV.len_exp ?e) |- is_true (QFBV.len_bexp ?e1 < QFBV.len_exp ?e) => match e0 with | context [e1] => rewrite /= in H; by auto_prove_lt end | H : is_true (QFBV.len_bexp ?e0 < QFBV.len_exp ?e) |- is_true (QFBV.len_exp ?e1 < QFBV.len_exp ?e) => match e0 with | context [e1] => rewrite /= in H; by auto_prove_lt end | H : is_true (QFBV.len_bexp ?e0 < QFBV.len_exp ?e) |- is_true (QFBV.len_bexp ?e1 < QFBV.len_exp ?e) => match e0 with | context [e1] => rewrite /= in H; by auto_prove_lt end | H : is_true (QFBV.len_exp ?e0 < QFBV.len_bexp ?e) |- is_true (QFBV.len_exp ?e1 < QFBV.len_bexp ?e) => match e0 with | context [e1] => rewrite /= in H; by auto_prove_lt end | H : is_true (QFBV.len_exp ?e0 < QFBV.len_bexp ?e) |- is_true (QFBV.len_bexp ?e1 < QFBV.len_bexp ?e) => match e0 with | context [e1] => rewrite /= in H; by auto_prove_lt end | H : is_true (QFBV.len_bexp ?e0 < QFBV.len_bexp ?e) |- is_true (QFBV.len_exp ?e1 < QFBV.len_bexp ?e) => match e0 with | context [e1] => rewrite /= in H; by auto_prove_lt end | H : is_true (QFBV.len_bexp ?e0 < QFBV.len_bexp ?e) |- is_true (QFBV.len_bexp ?e1 < QFBV.len_bexp ?e) => match e0 with | context [e1] => rewrite /= in H; by auto_prove_lt end | |- is_true (QFBV.len_exp ?e0 < QFBV.len_exp ?e) => match e with | context [e0] => rewrite /=; by auto_prove_lt end | |- is_true (QFBV.len_bexp ?e0 < QFBV.len_bexp ?e) => match e with | context [e0] => rewrite /=; by auto_prove_lt end | |- is_true (QFBV.len_bexp ?e0 < QFBV.len_exp ?e) => match e with | context [e0] => rewrite /=; by auto_prove_lt end | |- is_true (QFBV.len_exp ?e0 < QFBV.len_bexp ?e) => match e with | context [e0] => rewrite /=; by auto_prove_lt end end. (* = bit_blast_exp_ccache_find_cet and bit_blast_bexp_ccache_find_cet = *) Lemma bit_blast_exp_ccache_find_cet : forall e0 e te m c g m' c' g' cs ls, QFBV.len_exp e0 < QFBV.len_exp e -> bit_blast_exp_ccache te m c g e0 = (m', c', g', cs, ls) -> find_cet e c' = find_cet e c with bit_blast_bexp_ccache_find_cet : forall e0 e te m c g m' c' g' cs l, QFBV.len_bexp e0 < QFBV.len_exp e -> bit_blast_bexp_ccache te m c g e0 = (m', c', g', cs, l) -> find_cet e c' = find_cet e c. Proof. (* bit_blast_exp_ccache_find_cet *) set IHe := bit_blast_exp_ccache_find_cet. set IHb := bit_blast_bexp_ccache_find_cet. move=> e0 e te m c g m' c' g' cs ls. case Hfcet: (find_cet e0 c) => [[cs0 ls0] | ]. - move=> _. rewrite bit_blast_exp_ccache_equation Hfcet /=. case=> _ <- _ _ _. done. - move: Hfcet. case e0 => [v | bs | op e1 | op e1 e2 | b e1 e2] Hfcet Hlen. + rewrite /= Hfcet. case Hfhet : (find_het (QFBV.Evar v) c) => [[csh lsh] | ]. * case=> _ <- _ _ _; apply find_cet_add_cet_neq; by auto_prove_neq_by_len. * case Hfind: (SSAVM.find v m) => [rs | ]; last case Hblast : (bit_blast_var te g v) => [[vg vcs] vls]; case=> _ <- _ _ _; rewrite find_cet_add_cet_neq; (try by auto_prove_neq_by_len); by apply find_cet_add_het. + rewrite /= Hfcet. case Hfhet : (find_het (QFBV.Econst bs) c) => [[csh lsh] | ]; case=> _ <- _ _ _; rewrite find_cet_add_cet_neq; (try done); (try by auto_prove_neq_by_len); by apply find_cet_add_het. + rewrite /= Hfcet. case Hbb1: (bit_blast_exp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] ls1]. have He1e : QFBV.len_exp e1 < QFBV.len_exp e by auto_prove_len_lt. move: (IHe _ _ _ _ _ _ _ _ _ _ _ He1e Hbb1) => Hc1c. rewrite -Hc1c. case Hfhet : (find_het (QFBV.Eunop op e1) c1) => [[csop lsop] | ]; last case Hbbop : (bit_blast_eunop op g1 ls1) => [[gop csop] lsop]; case=> _ <- _ _ _; rewrite find_cet_add_cet_neq; (try done); (try by auto_prove_neq_by_len); by apply find_cet_add_het. + rewrite /= Hfcet. case Hbb1: (bit_blast_exp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] ls1]. have He1e : QFBV.len_exp e1 < QFBV.len_exp e by auto_prove_len_lt. move: (IHe _ _ _ _ _ _ _ _ _ _ _ He1e Hbb1) => Hc1c. case Hbb2: (bit_blast_exp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] ls2]. have He2e : QFBV.len_exp e2 < QFBV.len_exp e by auto_prove_len_lt. move: (IHe _ _ _ _ _ _ _ _ _ _ _ He2e Hbb2) => Hc2c1. rewrite -Hc1c -Hc2c1. case Hfhet : (find_het (QFBV.Ebinop op e1 e2) c2) => [[csop lsop] | ]; last case Hbbop : (bit_blast_ebinop op g2 ls1 ls2) => [[gop csop] lsop]; case=> _ <- _ _ _; rewrite find_cet_add_cet_neq; (try done); (try by auto_prove_neq_by_len); by apply find_cet_add_het. + rewrite /= Hfcet. case Hbbb: (bit_blast_bexp_ccache te m c g b) => [[[[mb cb] gb] csb] lb]. have Hbe : QFBV.len_bexp b < QFBV.len_exp e by auto_prove_len_lt. move: (IHb _ _ _ _ _ _ _ _ _ _ _ Hbe Hbbb) => Hcbc. case Hbb1: (bit_blast_exp_ccache te mb cb gb e1) => [[[[m1 c1] g1] cs1] ls1]. have He1e : QFBV.len_exp e1 < QFBV.len_exp e by auto_prove_len_lt. move: (IHe _ _ _ _ _ _ _ _ _ _ _ He1e Hbb1) => Hc1cb. case Hbb2: (bit_blast_exp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] ls2]. have He2e : QFBV.len_exp e2 < QFBV.len_exp e by auto_prove_len_lt. move: (IHe _ _ _ _ _ _ _ _ _ _ _ He2e Hbb2) => Hc2c1. rewrite -Hcbc -Hc1cb -Hc2c1. case Hfhet : (find_het (QFBV.Eite b e1 e2) c2) => [[csop lsop] | ]; last case Hbbop : (bit_blast_ite g2 lb ls1 ls2) => [[gop csop] lsop]; case=> _ <- _ _ _; rewrite find_cet_add_cet_neq; (try done); (try by auto_prove_neq_by_len); by apply find_cet_add_het. (* bit_blast_bexp_ccache_find_cet *) set IHe := bit_blast_exp_ccache_find_cet. set IHb := bit_blast_bexp_ccache_find_cet. move=> e0 e te m c g m' c' g' cs l. case Hfcbt: (find_cbt e0 c) => [[cs0 l0] | ]. - move=> _. rewrite bit_blast_bexp_ccache_equation Hfcbt /=. case=> _ <- _ _ _. done. - move: Hfcbt. case e0 => [ | | op e1 e2 | e1 | e1 e2 | e1 e2] Hfcbt Hlen. + rewrite /= Hfcbt. case Hfhet : (find_hbt QFBV.Bfalse c) => [[csh lh] | ]; case=> _ <- _ _ _; rewrite find_cet_add_cbt; (try rewrite find_cet_add_hbt); done. + rewrite /= Hfcbt. case Hfhet : (find_hbt QFBV.Btrue c) => [[csh lh] | ]; case=> _ <- _ _ _; rewrite find_cet_add_cbt; (try rewrite find_cet_add_hbt); done. + rewrite /= Hfcbt. case Hbb1: (bit_blast_exp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] ls1]. have He1e : QFBV.len_exp e1 < QFBV.len_exp e by auto_prove_len_lt. move: (IHe _ _ _ _ _ _ _ _ _ _ _ He1e Hbb1) => Hc1c. case Hbb2: (bit_blast_exp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] ls2]. have He2e : QFBV.len_exp e2 < QFBV.len_exp e by auto_prove_len_lt. move: (IHe _ _ _ _ _ _ _ _ _ _ _ He2e Hbb2) => Hc2c1. rewrite -Hc1c -Hc2c1. case Hfhbt : (find_hbt (QFBV.Bbinop op e1 e2) c2) => [[csop lop] | ]; last case Hbbop : (bit_blast_bbinop op g2 ls1 ls2) => [[gop csop] lsop]; case=> _ <- _ _ _; rewrite find_cet_add_cbt; (try rewrite find_cet_add_hbt); done. + rewrite /= Hfcbt. case Hbb1: (bit_blast_bexp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] l1]. have He1e : QFBV.len_bexp e1 < QFBV.len_exp e by auto_prove_len_lt. move: (IHb _ _ _ _ _ _ _ _ _ _ _ He1e Hbb1) => Hc1c. rewrite -Hc1c. case Hfhbt : (find_hbt (QFBV.Blneg e1) c1) => [[csop lop] | ]; case=> _ <- _ _ _; rewrite find_cet_add_cbt; (try rewrite find_cet_add_hbt); done. + rewrite /= Hfcbt. case Hbb1: (bit_blast_bexp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] l1]. have He1e : QFBV.len_bexp e1 < QFBV.len_exp e by auto_prove_len_lt. move: (IHb _ _ _ _ _ _ _ _ _ _ _ He1e Hbb1) => Hc1c. case Hbb2: (bit_blast_bexp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] l2]. have He2e : QFBV.len_bexp e2 < QFBV.len_exp e by auto_prove_len_lt. move: (IHb _ _ _ _ _ _ _ _ _ _ _ He2e Hbb2) => Hc2c1. rewrite -Hc1c -Hc2c1. case Hfhbt : (find_hbt (QFBV.Bconj e1 e2) c2) => [[csop lop] | ]; case=> _ <- _ _ _; rewrite find_cet_add_cbt; (try rewrite find_cet_add_hbt); done. + rewrite /= Hfcbt. case Hbb1: (bit_blast_bexp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] l1]. have He1e : QFBV.len_bexp e1 < QFBV.len_exp e by auto_prove_len_lt. move: (IHb _ _ _ _ _ _ _ _ _ _ _ He1e Hbb1) => Hc1c. case Hbb2: (bit_blast_bexp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] l2]. have He2e : QFBV.len_bexp e2 < QFBV.len_exp e by auto_prove_len_lt. move: (IHb _ _ _ _ _ _ _ _ _ _ _ He2e Hbb2) => Hc2c1. rewrite -Hc1c -Hc2c1. case Hfhbt : (find_hbt (QFBV.Bdisj e1 e2) c2) => [[csop lop] | ]; case=> _ <- _ _ _; rewrite find_cet_add_cbt; (try rewrite find_cet_add_hbt); done. Qed. (* = bit_blast_exp_ccache_find_cbt and bit_blast_bexp_ccache_find_cbt = *) Lemma bit_blast_exp_ccache_find_cbt : forall e0 e te m c g m' c' g' cs ls, QFBV.len_exp e0 < QFBV.len_bexp e -> bit_blast_exp_ccache te m c g e0 = (m', c', g', cs, ls) -> find_cbt e c' = find_cbt e c with bit_blast_bexp_ccache_find_cbt : forall e0 e te m c g m' c' g' cs l, QFBV.len_bexp e0 < QFBV.len_bexp e -> bit_blast_bexp_ccache te m c g e0 = (m', c', g', cs, l) -> find_cbt e c' = find_cbt e c. Proof. (* bit_blast_exp_ccache_find_cbt *) set IHe := bit_blast_exp_ccache_find_cbt. set IHb := bit_blast_bexp_ccache_find_cbt. move=> e0 e te m c g m' c' g' cs ls. case Hfcet: (find_cet e0 c) => [[cs0 ls0] | ]. - move=> _. rewrite bit_blast_exp_ccache_equation Hfcet /=. case=> _ <- _ _ _. done. - move: Hfcet. case e0 => [v | bs | op e1 | op e1 e2 | b e1 e2] Hfcet Hlen. + rewrite /= Hfcet. case Hfhet : (find_het (QFBV.Evar v) c) => [[csh lsh] | ]. * case=> _ <- _ _ _; apply find_cbt_add_cet. * case Hfind: (SSAVM.find v m) => [rs | ]; last case Hblast : (bit_blast_var te g v) => [[vg vcs] vls]; case=> _ <- _ _ _; rewrite find_cbt_add_cet; by apply find_cbt_add_het. + rewrite /= Hfcet. case Hfhet : (find_het (QFBV.Econst bs) c) => [[csh lsh] | ]; case=> _ <- _ _ _; rewrite find_cbt_add_cet; (try done); by apply find_cbt_add_het. + rewrite /= Hfcet. case Hbb1: (bit_blast_exp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] ls1]. have He1e : QFBV.len_exp e1 < QFBV.len_bexp e by auto_prove_len_lt. move: (IHe _ _ _ _ _ _ _ _ _ _ _ He1e Hbb1) => Hc1c. rewrite -Hc1c. case Hfhet : (find_het (QFBV.Eunop op e1) c1) => [[csop lsop] | ]; last case Hbbop : (bit_blast_eunop op g1 ls1) => [[gop csop] lsop]; case=> _ <- _ _ _; rewrite find_cbt_add_cet; (try done); by apply find_cbt_add_het. + rewrite /= Hfcet. case Hbb1: (bit_blast_exp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] ls1]. have He1e : QFBV.len_exp e1 < QFBV.len_bexp e by auto_prove_len_lt. move: (IHe _ _ _ _ _ _ _ _ _ _ _ He1e Hbb1) => Hc1c. case Hbb2: (bit_blast_exp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] ls2]. have He2e : QFBV.len_exp e2 < QFBV.len_bexp e by auto_prove_len_lt. move: (IHe _ _ _ _ _ _ _ _ _ _ _ He2e Hbb2) => Hc2c1. rewrite -Hc1c -Hc2c1. case Hfhet : (find_het (QFBV.Ebinop op e1 e2) c2) => [[csop lsop] | ]; last case Hbbop : (bit_blast_ebinop op g2 ls1 ls2) => [[gop csop] lsop]; case=> _ <- _ _ _; rewrite find_cbt_add_cet; (try done); by apply find_cbt_add_het. + rewrite /= Hfcet. case Hbbb: (bit_blast_bexp_ccache te m c g b) => [[[[mb cb] gb] csb] lb]. have Hbe : QFBV.len_bexp b < QFBV.len_bexp e by auto_prove_len_lt. move: (IHb _ _ _ _ _ _ _ _ _ _ _ Hbe Hbbb) => Hcbc. case Hbb1: (bit_blast_exp_ccache te mb cb gb e1) => [[[[m1 c1] g1] cs1] ls1]. have He1e : QFBV.len_exp e1 < QFBV.len_bexp e by auto_prove_len_lt. move: (IHe _ _ _ _ _ _ _ _ _ _ _ He1e Hbb1) => Hc1cb. case Hbb2: (bit_blast_exp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] ls2]. have He2e : QFBV.len_exp e2 < QFBV.len_bexp e by auto_prove_len_lt. move: (IHe _ _ _ _ _ _ _ _ _ _ _ He2e Hbb2) => Hc2c1. rewrite -Hcbc -Hc1cb -Hc2c1. case Hfhet : (find_het (QFBV.Eite b e1 e2) c2) => [[csop lsop] | ]; last case Hbbop : (bit_blast_ite g2 lb ls1 ls2) => [[gop csop] lsop]; case=> _ <- _ _ _; rewrite find_cbt_add_cet; (try done); by apply find_cbt_add_het. (* bit_blast_bexp_ccache_find_cbt *) set IHe := bit_blast_exp_ccache_find_cbt. set IHb := bit_blast_bexp_ccache_find_cbt. move=> e0 e te m c g m' c' g' cs l. case Hfcbt: (find_cbt e0 c) => [[cs0 l0] | ]. - move=> _. rewrite bit_blast_bexp_ccache_equation Hfcbt /=. case=> _ <- _ _ _. done. - move: Hfcbt. case e0 => [ | | op e1 e2 | e1 | e1 e2 | e1 e2] Hfcbt Hlen. + rewrite /= Hfcbt. case Hfhet : (find_hbt QFBV.Bfalse c) => [[csh lh] | ]; case=> _ <- _ _ _; rewrite find_cbt_add_cbt_neq; (try auto_prove_neq_by_len); (try rewrite find_cbt_add_hbt); done. + rewrite /= Hfcbt. case Hfhet : (find_hbt QFBV.Btrue c) => [[csh lh] | ]; case=> _ <- _ _ _; rewrite find_cbt_add_cbt_neq; (try auto_prove_neq_by_len); (try rewrite find_cbt_add_hbt); done. + rewrite /= Hfcbt. case Hbb1: (bit_blast_exp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] ls1]. have He1e : QFBV.len_exp e1 < QFBV.len_bexp e by auto_prove_len_lt. move: (IHe _ _ _ _ _ _ _ _ _ _ _ He1e Hbb1) => Hc1c. case Hbb2: (bit_blast_exp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] ls2]. have He2e : QFBV.len_exp e2 < QFBV.len_bexp e by auto_prove_len_lt. move: (IHe _ _ _ _ _ _ _ _ _ _ _ He2e Hbb2) => Hc2c1. rewrite -Hc1c -Hc2c1. case Hfhbt : (find_hbt (QFBV.Bbinop op e1 e2) c2) => [[csop lop] | ]; last case Hbbop : (bit_blast_bbinop op g2 ls1 ls2) => [[gop csop] lsop]; case=> _ <- _ _ _; rewrite find_cbt_add_cbt_neq; (try auto_prove_neq_by_len); (try rewrite find_cbt_add_hbt); done. + rewrite /= Hfcbt. case Hbb1: (bit_blast_bexp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] l1]. have He1e : QFBV.len_bexp e1 < QFBV.len_bexp e by auto_prove_len_lt. move: (IHb _ _ _ _ _ _ _ _ _ _ _ He1e Hbb1) => Hc1c. rewrite -Hc1c. case Hfhbt : (find_hbt (QFBV.Blneg e1) c1) => [[csop lop] | ]; case=> _ <- _ _ _; rewrite find_cbt_add_cbt_neq; (try auto_prove_neq_by_len); (try rewrite find_cbt_add_hbt); done. + rewrite /= Hfcbt. case Hbb1: (bit_blast_bexp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] l1]. have He1e : QFBV.len_bexp e1 < QFBV.len_bexp e by auto_prove_len_lt. move: (IHb _ _ _ _ _ _ _ _ _ _ _ He1e Hbb1) => Hc1c. case Hbb2: (bit_blast_bexp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] l2]. have He2e : QFBV.len_bexp e2 < QFBV.len_bexp e by auto_prove_len_lt. move: (IHb _ _ _ _ _ _ _ _ _ _ _ He2e Hbb2) => Hc2c1. rewrite -Hc1c -Hc2c1. case Hfhbt : (find_hbt (QFBV.Bconj e1 e2) c2) => [[csop lop] | ]; case=> _ <- _ _ _; rewrite find_cbt_add_cbt_neq; (try auto_prove_neq_by_len); (try rewrite find_cet_add_hbt); done. + rewrite /= Hfcbt. case Hbb1: (bit_blast_bexp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] l1]. have He1e : QFBV.len_bexp e1 < QFBV.len_bexp e by auto_prove_len_lt. move: (IHb _ _ _ _ _ _ _ _ _ _ _ He1e Hbb1) => Hc1c. case Hbb2: (bit_blast_bexp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] l2]. have He2e : QFBV.len_bexp e2 < QFBV.len_bexp e by auto_prove_len_lt. move: (IHb _ _ _ _ _ _ _ _ _ _ _ He2e Hbb2) => Hc2c1. rewrite -Hc1c -Hc2c1. case Hfhbt : (find_hbt (QFBV.Bdisj e1 e2) c2) => [[csop lop] | ]; case=> _ <- _ _ _; rewrite find_cbt_add_cbt_neq; (try auto_prove_neq_by_len); (try rewrite find_cbt_add_hbt); done. Qed. (* = bit_blast_exp_ccache_in_cet and bit_blast_bexp_ccache_in_cbt = *) Lemma bit_blast_exp_ccache_in_cet : forall e te m c g m' c' g' cs ls, bit_blast_exp_ccache te m c g e = (m', c', g', cs, ls) -> exists cse, find_cet e c' = Some (cse, ls) with bit_blast_bexp_ccache_in_cbt : forall e te m c g m' c' g' cs l, bit_blast_bexp_ccache te m c g e = (m', c', g', cs, l) -> exists cse, find_cbt e c' = Some (cse, l). Proof. (* exp *) move=> e te m c g m' c' g' cs ls. case Hfcet: (find_cet e c) => [[cse lse] | ]. - rewrite bit_blast_exp_ccache_equation Hfcet /=. case=> _ <- _ _ <-. exists cse; done. - move: Hfcet. case: e. + move=> v Hfcet. rewrite /= Hfcet. case Hfhet : (find_het (QFBV.Evar v) c) => [[cse lse] | ]; last case Hfv : (SSAVM.find v m); last case Hv : (bit_blast_var te g v) => [[gv csv] lsv]; case=> _ <- _ _ <-; [ exists cse | exists [::] | exists csv]; exact: find_cet_add_cet_eq. + move=> bs Hfcet. rewrite /= Hfcet. case Hfhet : (find_het (QFBV.Econst bs) c) => [[cse lse] | ]; case=> _ <- _ _ <-; [ exists cse | exists [::]]; exact: find_cet_add_cet_eq. + move=> op e1 Hfcet. rewrite /= Hfcet. case He1 : (bit_blast_exp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] ls1]. case Hfhet : (find_het (QFBV.Eunop op e1) c1) => [[csop lsop] | ]; last case Hop : (bit_blast_eunop op g1 ls1) => [[gop csop] lsop]; case=> _ <- _ _ <-; exists csop; exact: find_cet_add_cet_eq. + move=> op e1 e2 Hfcet. rewrite /= Hfcet. case He1 : (bit_blast_exp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] ls1]. case He2 : (bit_blast_exp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] ls2]. case Hfhet : (find_het (QFBV.Ebinop op e1 e2) c2) => [[csop lsop] | ]; last case Hop : (bit_blast_ebinop op g2 ls1 ls2) => [[gop csop] lsop]; case=> _ <- _ _ <-; exists csop; exact: find_cet_add_cet_eq. + move=> b e1 e2 Hfcet. rewrite /= Hfcet. case Hb : (bit_blast_bexp_ccache te m c g b) => [[[[mb cb] gb] csb] lb]. case He1 : (bit_blast_exp_ccache te mb cb gb e1) => [[[[m1 c1] g1] cs1] ls1]. case He2 : (bit_blast_exp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] ls2]. case Hfhet : (find_het (QFBV.Eite b e1 e2) c2) => [[csop lsop] | ]; last case Hop : (bit_blast_ite g2 lb ls1 ls2) => [[gop csop] lsop]; case=> _ <- _ _ <-; exists csop; exact: find_cet_add_cet_eq. (* bexp *) move=> e te m c g m' c' g' cs l. case Hfcbt: (find_cbt e c) => [[cse le] | ]. - rewrite bit_blast_bexp_ccache_equation Hfcbt /=. case=> _ <- _ _ <-. exists cse; done. - move: Hfcbt. case: e. + move=> Hfcbt. rewrite /= Hfcbt. case Hfhbt : (find_hbt (QFBV.Bfalse) c) => [[cse le] | ]; case=> _ <- _ _ <-; [ exists cse | exists [::]]; exact: find_cbt_add_cbt_eq. + move=> Hfcbt. rewrite /= Hfcbt. case Hfhbt : (find_hbt (QFBV.Btrue) c) => [[cse le] | ]; case=> _ <- _ _ <-; [ exists cse | exists [::]]; exact: find_cbt_add_cbt_eq. + move=> op e1 e2 Hfcbt. rewrite /= Hfcbt. case He1 : (bit_blast_exp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] ls1]. case He2 : (bit_blast_exp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] ls2]. case Hfhet : (find_hbt (QFBV.Bbinop op e1 e2) c2) => [[csop lop] | ]; last case Hop : (bit_blast_bbinop op g2 ls1 ls2) => [[gop csop] lop]; case=> _ <- _ _ <-; exists csop; exact: find_cbt_add_cbt_eq. + move=> e1 Hfcbt. rewrite /bit_blast_bexp_ccache -/bit_blast_bexp_ccache Hfcbt. case He1 : (bit_blast_bexp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] l1]. case Hfhbt : (find_hbt (QFBV.Blneg e1) c1) => [[csop lop] | ]; last case Hop : (bit_blast_lneg g1 l1) => [[gop csop] lop]; case=> _ <- _ _ <-; exists csop; exact: find_cbt_add_cbt_eq. + move=> e1 e2 Hfcbt. rewrite /bit_blast_bexp_ccache -/bit_blast_bexp_ccache Hfcbt. case He1 : (bit_blast_bexp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] l1]. case He2 : (bit_blast_bexp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] l2]. case Hfhbt : (find_hbt (QFBV.Bconj e1 e2) c2) => [[csop lop] | ]; last case Hop : (bit_blast_conj g2 l1 l2) => [[gop csop] lop]; case=> _ <- _ _ <-; exists csop; exact: find_cbt_add_cbt_eq. + move=> e1 e2 Hfcbt. rewrite /bit_blast_bexp_ccache -/bit_blast_bexp_ccache Hfcbt. case He1 : (bit_blast_bexp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] l1]. case He2 : (bit_blast_bexp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] l2]. case Hfhbt : (find_hbt (QFBV.Bdisj e1 e2) c2) => [[csop lop] | ]; last case Hop : (bit_blast_disj g2 l1 l2) => [[gop csop] lop]; case=> _ <- _ _ <-; exists csop; exact: find_cbt_add_cbt_eq. Qed. (* = bit_blast_exp_ccache_in_het and bit_blast_bexp_ccache_in_hbt = *) Lemma bit_blast_exp_ccache_in_het : forall e te m c g m' c' g' cs ls, bit_blast_exp_ccache te m c g e = (m', c', g', cs, ls) -> CompCache.well_formed c -> exists cse, find_het e c' = Some (cse, ls) with bit_blast_bexp_ccache_in_hbt : forall e te m c g m' c' g' cs l, bit_blast_bexp_ccache te m c g e = (m', c', g', cs, l) -> CompCache.well_formed c -> exists cse, find_hbt e c' = Some (cse, l). Proof. (* exp *) move=> e te m c g m' c' g' cs ls Hbb Hwfc. move: Hbb. case Hfcet: (find_cet e c) => [[cse lse] | ]. - rewrite bit_blast_exp_ccache_equation Hfcet /=. case=> _ <- _ _ <-. exists cse; exact: (well_formed_find_cet Hwfc Hfcet). - move: Hfcet. case: e. + move=> v Hfcet. rewrite /= Hfcet. case Hfhet : (find_het (QFBV.Evar v) c) => [[cse lse] | ]; last case Hfv : (SSAVM.find v m); last case Hv : (bit_blast_var te g v) => [[gv csv] lsv]; case=> _ <- _ _ <-; [ exists cse | exists [::] | exists csv]; rewrite find_het_add_cet; try rewrite find_het_add_het_eq; done. + move=> bs Hfcet. rewrite /= Hfcet. case Hfhet : (find_het (QFBV.Econst bs) c) => [[csop lsop] | ]; case=> _ <- _ _ <-; [ exists csop | exists [::]]; rewrite find_het_add_cet; try rewrite find_het_add_het_eq; done. + move=> op e1 Hfcet. rewrite /= Hfcet. case He1 : (bit_blast_exp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] ls1]. case Hfhet : (find_het (QFBV.Eunop op e1) c1) => [[csop lsop] | ]; last case Hop : (bit_blast_eunop op g1 ls1) => [[gop csop] lsop]; case=> _ <- _ _ <-; exists csop; rewrite find_het_add_cet; try rewrite find_het_add_het_eq; done. + move=> op e1 e2 Hfcet. rewrite /= Hfcet. case He1 : (bit_blast_exp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] ls1]. case He2 : (bit_blast_exp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] ls2]. case Hfhet : (find_het (QFBV.Ebinop op e1 e2) c2) => [[csop lsop] | ]; last case Hop : (bit_blast_ebinop op g2 ls1 ls2) => [[gop csop] lsop]; case=> _ <- _ _ <-; exists csop; rewrite find_het_add_cet; try rewrite find_het_add_het_eq; done. + move=> b e1 e2 Hfcet. rewrite /= Hfcet. case Hb : (bit_blast_bexp_ccache te m c g b) => [[[[mb cb] gb] csb] lb]. case He1 : (bit_blast_exp_ccache te mb cb gb e1) => [[[[m1 c1] g1] cs1] ls1]. case He2 : (bit_blast_exp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] ls2]. case Hfhet : (find_het (QFBV.Eite b e1 e2) c2) => [[csop lsop] | ]; last case Hop : (bit_blast_ite g2 lb ls1 ls2) => [[gop csop] lsop]; case=> _ <- _ _ <-; exists csop; rewrite find_het_add_cet; try rewrite find_het_add_het_eq; done. (* bexp *) move=> e te m c g m' c' g' cs l Hbb Hwfc. move: Hbb. case Hfcbt: (find_cbt e c) => [[cse le] | ]. - rewrite bit_blast_bexp_ccache_equation Hfcbt /=. case=> _ <- _ _ <-. exists cse; exact: (well_formed_find_cbt Hwfc Hfcbt). - move: Hfcbt. case: e. + move=> Hfcbt. rewrite /= Hfcbt. case Hfhbt : (find_hbt (QFBV.Bfalse) c) => [[csop lop] | ]; case=> _ <- _ _ <-; [ exists csop | exists [::]]; rewrite find_hbt_add_cbt; try rewrite find_hbt_add_hbt_eq; done. + move=> Hfcbt. rewrite /= Hfcbt. case Hfhbt : (find_hbt (QFBV.Btrue) c) => [[csop lop] | ]; case=> _ <- _ _ <-; [ exists csop | exists [::]]; rewrite find_hbt_add_cbt; try rewrite find_hbt_add_hbt_eq; done. + move=> op e1 e2 Hfcbt. rewrite /= Hfcbt. case He1 : (bit_blast_exp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] ls1]. case He2 : (bit_blast_exp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] ls2]. case Hfhbt : (find_hbt (QFBV.Bbinop op e1 e2) c2) => [[csop lop] | ]; last case Hop : (bit_blast_bbinop op g2 ls1 ls2) => [[gop csop] lop]; case=> _ <- _ _ <-; exists csop; rewrite find_hbt_add_cbt; try rewrite find_hbt_add_hbt_eq; done. + move=> e1 Hfcbt. rewrite /bit_blast_bexp_ccache -/bit_blast_bexp_ccache Hfcbt. case He1 : (bit_blast_bexp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] l1]. case Hfhbt : (find_hbt (QFBV.Blneg e1) c1) => [[csop lop] | ]; last case Hop : (bit_blast_lneg g1 l1) => [[gop csop] lop]; case=> _ <- _ _ <-; exists csop; rewrite find_hbt_add_cbt; try rewrite find_hbt_add_hbt_eq; done. + move=> e1 e2 Hfcbt. rewrite /bit_blast_bexp_ccache -/bit_blast_bexp_ccache Hfcbt. case He1 : (bit_blast_bexp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] l1]. case He2 : (bit_blast_bexp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] l2]. case Hfhbt : (find_hbt (QFBV.Bconj e1 e2) c2) => [[csop lop] | ]; last case Hop : (bit_blast_conj g2 l1 l2) => [[gop csop] lop]; case=> _ <- _ _ <-; exists csop; rewrite find_hbt_add_cbt; try rewrite find_hbt_add_hbt_eq; done. + move=> e1 e2 Hfcbt. rewrite /bit_blast_bexp_ccache -/bit_blast_bexp_ccache Hfcbt. case He1 : (bit_blast_bexp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] l1]. case He2 : (bit_blast_bexp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] l2]. case Hfhbt : (find_hbt (QFBV.Bdisj e1 e2) c2) => [[csop lop] | ]; last case Hop : (bit_blast_disj g2 l1 l2) => [[gop csop] lop]; case=> _ <- _ _ <-; exists csop; rewrite find_hbt_add_cbt; try rewrite find_hbt_add_hbt_eq; done. Qed.
Formal statement is: lemma limpt_sequential_inj: fixes x :: "'a::metric_space" shows "x islimpt S \<longleftrightarrow> (\<exists>f. (\<forall>n::nat. f n \<in> S - {x}) \<and> inj f \<and> (f \<longlongrightarrow> x) sequentially)" (is "?lhs = ?rhs") Informal statement is: A point $x$ is a limit point of a set $S$ if and only if there exists an injective sequence $(x_n)$ in $S$ that converges to $x$.
library(proto) fifo <- proto(expr = { l <- list() empty <- function(.) length(.$l) == 0 push <- function(., x) { .$l <- c(.$l, list(x)) print(.$l) invisible() } pop <- function(.) { if(.$empty()) stop("can't pop from an empty list") .$l[[1]] <- NULL print(.$l) invisible() } }) #The following code provides output that is the same as the previous example. fifo$empty() fifo$push(3) fifo$push("abc") fifo$push(matrix(1:6, nrow=2)) fifo$empty() fifo$pop() fifo$pop() fifo$pop() fifo$pop()
Formal statement is: lemma interior_surjective_linear_image: fixes f :: "'a::euclidean_space \<Rightarrow> 'a::euclidean_space" assumes "linear f" "surj f" shows "interior(f ` S) = f ` (interior S)" Informal statement is: If $f$ is a linear surjective map, then the interior of the image of a set $S$ is the image of the interior of $S$.
% cmbglobl.m : cmb globals : physical constants that are used through all files % are given a value here % % D Vangheluwe 28 jan 2005, see cmbaccur.m anc cmbacc1.m as the main files global GL_cmb_c GL_cmb_h0 GL_cmb_t0 GL_cmb_T0 GL_cmb_rv GL_cmb_fv GL_cmb_kg1 GL_cmb_ka1 ... GL_cmb_yp GL_cmb_ncr GL_cmb_cr GL_cmb_pcm GL_cmb_dha; % velocity of light in m/s GL_cmb_c = 2.998e8; % the Hubble constant at present in (h Mpc^-1), see my notes p71 GL_cmb_h0 = 1e5/GL_cmb_c; % the present temperature of the CMB in degr Kelvin and in eV GL_cmb_t0 = 2.725; GL_cmb_T0 = GL_cmb_t0/11605; % ratio of radiation density/critical density, see Dodelson (2.87) %fv = 0.405; GL_cmb_rv = (21/8) * (4/11)^(4/3); GL_cmb_fv = GL_cmb_rv/(1 + GL_cmb_rv); GL_cmb_kg1 = 2.47e-5; GL_cmb_ka1 = GL_cmb_kg1/(1 - GL_cmb_fv); %ka1 = 4.15e-5; % the primordial helium mass fraction GL_cmb_yp = 0.24; % critical density in m^-3 GL_cmb_ncr = 11.23; %ncr = 10.8; % Compton cross section in m^2, see Dodelson p 72 GL_cmb_cr = 0.665e-28; % conversion of Parsec to meters GL_cmb_pcm = 3.0856e22; % amplitude of the primordial density perturbation at the horizon, see Dodelson (8.76) GL_cmb_dha = 4.47e-5;
theory T57 imports Main begin lemma "( (\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) & (\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, meet(y, z)) = meet(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(x, join(y, z)) = join(undr(x, y), undr(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(join(x, y), z) = join(over(x, z), over(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(meet(x, y), z) = join(undr(x, z), undr(y, z))) & (\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) & (\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) & (\<forall> x::nat. invo(invo(x)) = x) ) \<longrightarrow> (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(meet(x, y), z) = meet(mult(x, z), mult(y, z))) " nitpick[card nat=10,timeout=86400] oops end
# Integrators A dynamics simulation integrates the differential equations of motion. We have, \begin{align} \frac{dv}{dt} &= a \\ \frac{dx}{dt} &= v \end{align} where $x$ is position, $v$ is velocity and $a$ is acceleration. There is extensive research on integrators and their properties for dynamic systems. Here, we focus on two commond ones: the simple Euler integrator and the slightly more advanced Leapfrog integrator. The integrators are implemented in separate classes and can be extended, e.g. with Runge-Kutta methods. ## Euler The Euler integrator is a simple first-order method. \begin{align} x_{t+1} &= x_t + v_t \Delta t \\ v_{t+1} &= v_t + a_t \Delta t \end{align} ## Leapfrog Reference {cite}`birdsall2004plasma`. The main integrator used here is the Leapfrog integrator. It has only a very small computational overhead compared to the Euler method. \begin{align} x_{t+1} &= x_t + v_t \Delta t + \frac{1}{2} a_t \Delta t^2 \\ v_{t+1} &= v_t + \frac{1}{2}(a_t + a_{t+1}) \Delta t \end{align}
-- | The core type system. module Ethambda.System import Ethambda.Common using ((<.>), (<.)) public export data Tp : Type -> Type where Var : a -> Tp a Fun : Tp a -> Tp a -> Tp a Show a => Show (Tp a) where show t = case t of -- Var a => ?foo Var a => show a Fun a0 b0 => mbrackets a0 <+> "→" <+> show b0 where brackets : String -> String brackets s = "(" <+> s <+> ")" mbrackets : Show a => Tp a -> String mbrackets a = case a of Var _ => neutral Fun _ _ => brackets (show a)
State Before: α : Type u β : Type ?u.54315 w x y z : α inst✝ : BooleanAlgebra α ⊢ xᶜ = y ↔ yᶜ = x State After: no goals Tactic: rw [eq_comm, compl_eq_iff_isCompl, eq_compl_iff_isCompl]
module Test.Bits64 import Data.Prim.Bits64 import Data.SOP import Hedgehog import Test.RingLaws allBits64 : Gen Bits64 allBits64 = bits64 (linear 0 0xffffffffffffffff) gt0 : Gen Bits64 gt0 = bits64 (linear 1 MaxBits64) gt1 : Gen Bits64 gt1 = bits64 (linear 2 MaxBits64) prop_ltMax : Property prop_ltMax = property $ do b8 <- forAll allBits64 (b8 <= MaxBits64) === True prop_ltMin : Property prop_ltMin = property $ do b8 <- forAll allBits64 (b8 >= MinBits64) === True prop_comp : Property prop_comp = property $ do [m,n] <- forAll $ np [allBits64, allBits64] toOrdering (comp m n) === compare m n prop_mod : Property prop_mod = property $ do [n,d] <- forAll $ np [allBits64, gt0] compare (n `mod` d) d === LT prop_div : Property prop_div = property $ do [n,d] <- forAll $ np [gt0, gt1] compare (n `div` d) n === LT prop_divMod : Property prop_divMod = property $ do [n,d] <- forAll $ np [allBits64, gt0] let x = n `div` d r = n `mod` d n === x * d + r export props : Group props = MkGroup "Bits64" $ [ ("prop_ltMax", prop_ltMax) , ("prop_ltMin", prop_ltMin) , ("prop_comp", prop_comp) , ("prop_mod", prop_mod) , ("prop_div", prop_div) , ("prop_divMod", prop_divMod) ] ++ ringProps allBits64
-- @@stderr -- dtrace: failed to compile script test/unittest/types/err.D_DECL_COMBO.badtype4.d: [D_DECL_COMBO] line 21: invalid type combination
module Data.Crypto %default total public class Masher m (b : Nat) where blockLength : Nat
{-# OPTIONS --safe #-} module Cubical.Data.FinSet.Properties where open import Cubical.Foundations.Prelude open import Cubical.Foundations.HLevels open import Cubical.Foundations.Function open import Cubical.Foundations.Structure open import Cubical.Foundations.Isomorphism open import Cubical.Foundations.Univalence open import Cubical.Foundations.Equiv open import Cubical.HITs.PropositionalTruncation open import Cubical.Data.Nat open import Cubical.Data.Unit open import Cubical.Data.Empty renaming (rec to EmptyRec) open import Cubical.Data.Sigma open import Cubical.Data.Fin open import Cubical.Data.SumFin renaming (Fin to SumFin) hiding (discreteFin) open import Cubical.Data.FinSet.Base open import Cubical.Relation.Nullary open import Cubical.Relation.Nullary.DecidableEq open import Cubical.Relation.Nullary.HLevels private variable ℓ ℓ' ℓ'' : Level A : Type ℓ B : Type ℓ' -- infix operator to more conveniently compose equivalences _⋆_ = compEquiv infixr 30 _⋆_ -- useful implications EquivPresIsFinSet : A ≃ B → isFinSet A → isFinSet B EquivPresIsFinSet e = rec isPropIsFinSet (λ (n , p) → ∣ n , compEquiv (invEquiv e) p ∣) isFinSetFin : {n : ℕ} → isFinSet (Fin n) isFinSetFin = ∣ _ , pathToEquiv refl ∣ isFinSetUnit : isFinSet Unit isFinSetUnit = ∣ 1 , Unit≃Fin1 ∣ isFinSet→Discrete : isFinSet A → Discrete A isFinSet→Discrete = rec isPropDiscrete (λ (_ , p) → EquivPresDiscrete (invEquiv p) discreteFin) isContr→isFinSet : isContr A → isFinSet A isContr→isFinSet h = ∣ 1 , isContr→≃Unit* h ⋆ invEquiv (Unit≃Unit* ) ⋆ Unit≃Fin1 ∣ isDecProp→isFinSet : isProp A → Dec A → isFinSet A isDecProp→isFinSet h (yes p) = isContr→isFinSet (inhProp→isContr p h) isDecProp→isFinSet h (no ¬p) = ∣ 0 , uninhabEquiv ¬p ¬Fin0 ∣ {- Alternative definition of finite sets A set is finite if it is merely equivalent to `Fin n` for some `n`. We can translate this to code in two ways: a truncated sigma of a nat and an equivalence, or a sigma of a nat and a truncated equivalence. We prove that both formulations are equivalent. -} isFinSet' : Type ℓ → Type ℓ isFinSet' A = Σ[ n ∈ ℕ ] ∥ A ≃ Fin n ∥ FinSet' : (ℓ : Level) → Type (ℓ-suc ℓ) FinSet' ℓ = TypeWithStr _ isFinSet' isPropIsFinSet' : isProp (isFinSet' A) isPropIsFinSet' {A = A} (n , equivn) (m , equivm) = Σ≡Prop (λ _ → isPropPropTrunc) n≡m where Fin-n≃Fin-m : ∥ Fin n ≃ Fin m ∥ Fin-n≃Fin-m = rec isPropPropTrunc (rec (isPropΠ λ _ → isPropPropTrunc) (λ hm hn → ∣ Fin n ≃⟨ invEquiv hn ⟩ A ≃⟨ hm ⟩ Fin m ■ ∣) equivm ) equivn Fin-n≡Fin-m : ∥ Fin n ≡ Fin m ∥ Fin-n≡Fin-m = rec isPropPropTrunc (∣_∣ ∘ ua) Fin-n≃Fin-m ∥n≡m∥ : ∥ n ≡ m ∥ ∥n≡m∥ = rec isPropPropTrunc (∣_∣ ∘ Fin-inj n m) Fin-n≡Fin-m n≡m : n ≡ m n≡m = rec (isSetℕ n m) (λ p → p) ∥n≡m∥ -- logical equivalence of two definitions isFinSet→isFinSet' : isFinSet A → isFinSet' A isFinSet→isFinSet' ∣ n , equiv ∣ = n , ∣ equiv ∣ isFinSet→isFinSet' (squash p q i) = isPropIsFinSet' (isFinSet→isFinSet' p) (isFinSet→isFinSet' q) i isFinSet'→isFinSet : isFinSet' A → isFinSet A isFinSet'→isFinSet (n , ∣ isFinSet-A ∣) = ∣ n , isFinSet-A ∣ isFinSet'→isFinSet (n , squash p q i) = isPropIsFinSet (isFinSet'→isFinSet (n , p)) (isFinSet'→isFinSet (n , q)) i isFinSet≡isFinSet' : isFinSet A ≡ isFinSet' A isFinSet≡isFinSet' {A = A} = hPropExt isPropIsFinSet isPropIsFinSet' isFinSet→isFinSet' isFinSet'→isFinSet FinSet→FinSet' : FinSet ℓ → FinSet' ℓ FinSet→FinSet' (A , isFinSetA) = A , isFinSet→isFinSet' isFinSetA FinSet'→FinSet : FinSet' ℓ → FinSet ℓ FinSet'→FinSet (A , isFinSet'A) = A , isFinSet'→isFinSet isFinSet'A FinSet≃FinSet' : FinSet ℓ ≃ FinSet' ℓ FinSet≃FinSet' = isoToEquiv (iso FinSet→FinSet' FinSet'→FinSet (λ _ → Σ≡Prop (λ _ → isPropIsFinSet') refl) (λ _ → Σ≡Prop (λ _ → isPropIsFinSet) refl)) FinSet≡FinSet' : FinSet ℓ ≡ FinSet' ℓ FinSet≡FinSet' = ua FinSet≃FinSet' -- cardinality of finite sets card : FinSet ℓ → ℕ card = fst ∘ snd ∘ FinSet→FinSet' -- definitions to reduce problems about FinSet to SumFin ≃Fin : Type ℓ → Type ℓ ≃Fin A = Σ[ n ∈ ℕ ] A ≃ Fin n ≃SumFin : Type ℓ → Type ℓ ≃SumFin A = Σ[ n ∈ ℕ ] A ≃ SumFin n ≃Fin→SumFin : ≃Fin A → ≃SumFin A ≃Fin→SumFin (n , e) = n , compEquiv e (invEquiv (SumFin≃Fin _)) ≃SumFin→Fin : ≃SumFin A → ≃Fin A ≃SumFin→Fin (n , e) = n , compEquiv e (SumFin≃Fin _) transpFamily : {A : Type ℓ}{B : A → Type ℓ'} → ((n , e) : ≃SumFin A) → (x : A) → B x ≃ B (invEq e (e .fst x)) transpFamily {B = B} (n , e) x = pathToEquiv (λ i → B (retEq e x (~ i)))
module Forcing4 where open import Common.Nat renaming (zero to Z; suc to S) open import Lib.Fin open import Common.Equality open import Common.String open import Common.IO open import Common.Unit {- toNat : {n : Nat} → Fin n → Nat toNat (zero _) = 0 toNat (suc _ i) = suc (toNat i) -} Rel : (X : Set) -> Set1 Rel X = X -> X -> Set data _<=_ : Rel Nat where z<=n : ∀ n → Z <= n s<=s : ∀ m n (m<=n : m <= n) → S m <= S n _ℕ<_ : Rel Nat m ℕ< n = S m <= n fromℕ≤ : ∀ {m n} → m ℕ< n → Fin n fromℕ≤ (s<=s .0 n (z<=n .n)) = fz {n} fromℕ≤ (s<=s .(S m) .(S n) (s<=s m n m<=n)) = fs {S n} (fromℕ≤ (s<=s m n m<=n)) fromℕ≤-toℕ : ∀ m (i : Fin m) (i<m : forget i ℕ< m) → fromℕ≤ i<m ≡ i fromℕ≤-toℕ .(S n) (fz {n}) (s<=s .0 .n (z<=n .n)) = refl fromℕ≤-toℕ .(S (S n)) (fs .{S n} y) (s<=s .(S (forget y)) .(S n) (s<=s .(forget y) n m≤n)) = cong (\ n -> fs n) (fromℕ≤-toℕ (S n) y (s<=s (forget y) n m≤n)) [_/2] : Nat -> Nat [ 0 /2] = 0 [ 1 /2] = 0 [ S (S n) /2] = S [ n /2] [1/2]-mono : (m n : Nat) -> m <= n -> [ m /2] <= [ n /2] [1/2]-mono .0 .n (z<=n n) = z<=n [ n /2] [1/2]-mono .1 .(S n) (s<=s .0 .n (z<=n n)) = z<=n [ S n /2] [1/2]-mono .(S (S m)) .(S (S n)) (s<=s .(S m) .(S n) (s<=s m n m<=n)) = s<=s [ m /2] [ n /2] ([1/2]-mono m n m<=n) showEq : {X : Set}{A : X} -> A ≡ A -> String showEq refl = "refl" show<= : {m n : Nat} -> m <= n -> String show<= (z<=n n) = "0 <= " +S+ natToString n show<= (s<=s m n m<=n) = natToString (S m) +S+ " <= " +S+ natToString (S n) data Bot : Set where -- Only to check that it compiles.. foo : (n : Nat) -> S n <= n -> Bot foo .(S n) (s<=s .(S n) n le) = foo n le main : IO Unit main = putStrLn (showEq (fromℕ≤-toℕ 3 (inc (inject 1)) le)) ,, putStrLn (show<= ([1/2]-mono 4 6 le')) where le : 2 <= 3 le = s<=s _ _ (s<=s _ _ (z<=n _)) le' : 4 <= 6 le' = s<=s _ _ (s<=s _ _ (s<=s _ _ (s<=s _ _ (z<=n _))))
section \<open>Lemmas concerning paths to instantiate locale Postdomination\<close> theory ValidPaths imports WellFormed "../StaticInter/Postdomination" begin subsection \<open>Intraprocedural paths from method entry and to method exit\<close> abbreviation path :: "wf_prog \<Rightarrow> node \<Rightarrow> edge list \<Rightarrow> node \<Rightarrow> bool" ("_ \<turnstile> _ -_\<rightarrow>* _") where "wfp \<turnstile> n -as\<rightarrow>* n' \<equiv> CFG.path sourcenode targetnode (valid_edge wfp) n as n'" definition label_incrs :: "edge list \<Rightarrow> nat \<Rightarrow> edge list" ("_ \<oplus>s _" 60) where "as \<oplus>s i \<equiv> map (\<lambda>((p,n),et,(p',n')). ((p,n \<oplus> i),et,(p',n' \<oplus> i))) as" declare One_nat_def [simp del] subsubsection \<open>From \<open>prog\<close> to \<open>prog;;c\<^sub>2\<close>\<close> lemma Proc_CFG_edge_SeqFirst_nodes_Label: "prog \<turnstile> Label l -et\<rightarrow>\<^sub>p Label l' \<Longrightarrow> prog;;c\<^sub>2 \<turnstile> Label l -et\<rightarrow>\<^sub>p Label l'" proof(induct prog "Label l" et "Label l'" rule:Proc_CFG.induct) case (Proc_CFG_SeqSecond c\<^sub>2' n et n' c\<^sub>1) hence "(c\<^sub>1;; c\<^sub>2');; c\<^sub>2 \<turnstile> n \<oplus> #:c\<^sub>1 -et\<rightarrow>\<^sub>p n' \<oplus> #:c\<^sub>1" by(fastforce intro:Proc_CFG_SeqFirst Proc_CFG.Proc_CFG_SeqSecond) with \<open>n \<oplus> #:c\<^sub>1 = Label l\<close> \<open>n' \<oplus> #:c\<^sub>1 = Label l'\<close> show ?case by fastforce next case (Proc_CFG_CondThen c\<^sub>1 n et n' b c\<^sub>2') hence "if (b) c\<^sub>1 else c\<^sub>2';; c\<^sub>2 \<turnstile> n \<oplus> 1 -et\<rightarrow>\<^sub>p n' \<oplus> 1" by(fastforce intro:Proc_CFG_SeqFirst Proc_CFG.Proc_CFG_CondThen) with \<open>n \<oplus> 1 = Label l\<close> \<open>n' \<oplus> 1 = Label l'\<close> show ?case by fastforce next case (Proc_CFG_CondElse c\<^sub>1 n et n' b c\<^sub>2') hence "if (b) c\<^sub>2' else c\<^sub>1 ;; c\<^sub>2 \<turnstile> n \<oplus> #:c\<^sub>2' + 1 -et\<rightarrow>\<^sub>p n' \<oplus> (#:c\<^sub>2' + 1)" by(fastforce intro:Proc_CFG_SeqFirst Proc_CFG.Proc_CFG_CondElse) with \<open>n \<oplus> #:c\<^sub>2' + 1 = Label l\<close> \<open>n' \<oplus> #:c\<^sub>2' + 1 = Label l'\<close> show ?case by fastforce next case (Proc_CFG_WhileBody c' n et n' b) hence "while (b) c';; c\<^sub>2 \<turnstile> n \<oplus> 2 -et\<rightarrow>\<^sub>p n' \<oplus> 2" by(fastforce intro:Proc_CFG_SeqFirst Proc_CFG.Proc_CFG_WhileBody) with \<open>n \<oplus> 2 = Label l\<close> \<open>n' \<oplus> 2 = Label l'\<close> show ?case by fastforce next case (Proc_CFG_WhileBodyExit c' n et b) hence "while (b) c';; c\<^sub>2 \<turnstile> n \<oplus> 2 -et\<rightarrow>\<^sub>p Label 0" by(fastforce intro:Proc_CFG_SeqFirst Proc_CFG.Proc_CFG_WhileBodyExit) with \<open>n \<oplus> 2 = Label l\<close> \<open>0 = l'\<close> show ?case by fastforce qed (auto intro:Proc_CFG.intros) lemma Proc_CFG_edge_SeqFirst_source_Label: assumes "prog \<turnstile> Label l -et\<rightarrow>\<^sub>p n'" obtains nx where "prog;;c\<^sub>2 \<turnstile> Label l -et\<rightarrow>\<^sub>p nx" proof(atomize_elim) from \<open>prog \<turnstile> Label l -et\<rightarrow>\<^sub>p n'\<close> obtain n where "prog \<turnstile> n -et\<rightarrow>\<^sub>p n'" and "Label l = n" by simp thus "\<exists>nx. prog;;c\<^sub>2 \<turnstile> Label l -et\<rightarrow>\<^sub>p nx" proof(induct prog n et n' rule:Proc_CFG.induct) case (Proc_CFG_SeqSecond c\<^sub>2' n et n' c\<^sub>1) show ?case proof(cases "n' = Exit") case True with \<open>c\<^sub>2' \<turnstile> n -et\<rightarrow>\<^sub>p n'\<close> \<open>n \<noteq> Entry\<close> have "c\<^sub>1;; c\<^sub>2' \<turnstile> n \<oplus> #:c\<^sub>1 -et\<rightarrow>\<^sub>p Exit \<oplus> #:c\<^sub>1" by(fastforce intro:Proc_CFG.Proc_CFG_SeqSecond) moreover from \<open>n \<noteq> Entry\<close> have "n \<oplus> #:c\<^sub>1 \<noteq> Entry" by(cases n) auto ultimately have "c\<^sub>1;; c\<^sub>2';; c\<^sub>2 \<turnstile> n \<oplus> #:c\<^sub>1 -et\<rightarrow>\<^sub>p Label (#:c\<^sub>1;; c\<^sub>2')" by(fastforce intro:Proc_CFG_SeqConnect) with \<open>Label l = n \<oplus> #:c\<^sub>1\<close> show ?thesis by fastforce next case False with Proc_CFG_SeqSecond have "(c\<^sub>1;; c\<^sub>2');; c\<^sub>2 \<turnstile> n \<oplus> #:c\<^sub>1 -et\<rightarrow>\<^sub>p n' \<oplus> #:c\<^sub>1" by(fastforce intro:Proc_CFG_SeqFirst Proc_CFG.Proc_CFG_SeqSecond) with \<open>Label l = n \<oplus> #:c\<^sub>1\<close> show ?thesis by fastforce qed next case (Proc_CFG_CondThen c\<^sub>1 n et n' b c\<^sub>2') show ?case proof(cases "n' = Exit") case True with \<open>c\<^sub>1 \<turnstile> n -et\<rightarrow>\<^sub>p n'\<close> \<open>n \<noteq> Entry\<close> have "if (b) c\<^sub>1 else c\<^sub>2' \<turnstile> n \<oplus> 1 -et\<rightarrow>\<^sub>p Exit \<oplus> 1" by(fastforce intro:Proc_CFG.Proc_CFG_CondThen) moreover from \<open>n \<noteq> Entry\<close> have "n \<oplus> 1 \<noteq> Entry" by(cases n) auto ultimately have "if (b) c\<^sub>1 else c\<^sub>2';; c\<^sub>2 \<turnstile> n \<oplus> 1 -et\<rightarrow>\<^sub>p Label (#:if (b) c\<^sub>1 else c\<^sub>2')" by(fastforce intro:Proc_CFG_SeqConnect) with \<open>Label l = n \<oplus> 1\<close> show ?thesis by fastforce next case False hence "n' \<oplus> 1 \<noteq> Exit" by(cases n') auto with Proc_CFG_CondThen have "if (b) c\<^sub>1 else c\<^sub>2';; c\<^sub>2 \<turnstile> Label l -et\<rightarrow>\<^sub>p n' \<oplus> 1" by(fastforce intro:Proc_CFG_SeqFirst Proc_CFG.Proc_CFG_CondThen) with \<open>Label l = n \<oplus> 1\<close> show ?thesis by fastforce qed next case (Proc_CFG_CondElse c\<^sub>1 n et n' b c\<^sub>2') show ?case proof(cases "n' = Exit") case True with \<open>c\<^sub>1 \<turnstile> n -et\<rightarrow>\<^sub>p n'\<close> \<open>n \<noteq> Entry\<close> have "if (b) c\<^sub>2' else c\<^sub>1 \<turnstile> n \<oplus> (#:c\<^sub>2' + 1) -et\<rightarrow>\<^sub>p Exit \<oplus> (#:c\<^sub>2' + 1)" by(fastforce intro:Proc_CFG.Proc_CFG_CondElse) moreover from \<open>n \<noteq> Entry\<close> have "n \<oplus> (#:c\<^sub>2' + 1) \<noteq> Entry" by(cases n) auto ultimately have "if (b) c\<^sub>2' else c\<^sub>1;; c\<^sub>2 \<turnstile> n \<oplus> (#:c\<^sub>2' + 1) -et\<rightarrow>\<^sub>p Label (#:if (b) c\<^sub>2' else c\<^sub>1)" by(fastforce intro:Proc_CFG_SeqConnect) with \<open>Label l = n \<oplus> (#:c\<^sub>2' + 1)\<close> show ?thesis by fastforce next case False hence "n' \<oplus> (#:c\<^sub>2' + 1) \<noteq> Exit" by(cases n') auto with Proc_CFG_CondElse have "if (b) c\<^sub>2' else c\<^sub>1 ;; c\<^sub>2 \<turnstile> Label l -et\<rightarrow>\<^sub>p n' \<oplus> (#:c\<^sub>2' + 1)" by(fastforce intro:Proc_CFG_SeqFirst Proc_CFG.Proc_CFG_CondElse) with \<open>Label l = n \<oplus> (#:c\<^sub>2' + 1)\<close> show ?thesis by fastforce qed qed (auto intro:Proc_CFG.intros) qed lemma Proc_CFG_edge_SeqFirst_target_Label: "\<lbrakk>prog \<turnstile> n -et\<rightarrow>\<^sub>p n'; Label l' = n'\<rbrakk> \<Longrightarrow> prog;;c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p Label l'" proof(induct prog n et n' rule:Proc_CFG.induct) case (Proc_CFG_SeqSecond c\<^sub>2' n et n' c\<^sub>1) from \<open>Label l' = n' \<oplus> #:c\<^sub>1\<close> have "n' \<noteq> Exit" by(cases n') auto with Proc_CFG_SeqSecond show ?case by(fastforce intro:Proc_CFG_SeqFirst intro:Proc_CFG.Proc_CFG_SeqSecond) next case (Proc_CFG_CondThen c\<^sub>1 n et n' b c\<^sub>2') from \<open>Label l' = n' \<oplus> 1\<close> have "n' \<noteq> Exit" by(cases n') auto with Proc_CFG_CondThen show ?case by(fastforce intro:Proc_CFG_SeqFirst Proc_CFG.Proc_CFG_CondThen) qed (auto intro:Proc_CFG.intros) lemma PCFG_edge_SeqFirst_source_Label: assumes "prog,procs \<turnstile> (p,Label l) -et\<rightarrow> (p',n')" obtains nx where "prog;;c\<^sub>2,procs \<turnstile> (p,Label l) -et\<rightarrow> (p',nx)" proof(atomize_elim) from \<open>prog,procs \<turnstile> (p,Label l) -et\<rightarrow> (p',n')\<close> show "\<exists>nx. prog;;c\<^sub>2,procs \<turnstile> (p,Label l) -et\<rightarrow> (p',nx)" proof(induct "(p,Label l)" et "(p',n')" rule:PCFG.induct) case (Main et) from \<open>prog \<turnstile> Label l -IEdge et\<rightarrow>\<^sub>p n'\<close> obtain nx' where "prog;;c\<^sub>2 \<turnstile> Label l -IEdge et\<rightarrow>\<^sub>p nx'" by(auto elim:Proc_CFG_edge_SeqFirst_source_Label) with \<open>Main = p\<close> \<open>Main = p'\<close> show ?case by(fastforce dest:PCFG.Main) next case (Proc ins outs c et ps) from \<open>containsCall procs prog ps p\<close> have "containsCall procs (prog;;c\<^sub>2) ps p" by simp with Proc show ?case by(fastforce dest:PCFG.Proc) next case (MainCall es rets nx ins outs c) from \<open>prog \<turnstile> Label l -CEdge (p', es, rets)\<rightarrow>\<^sub>p nx\<close> obtain lx where [simp]:"nx = Label lx" by(fastforce dest:Proc_CFG_Call_Labels) with \<open>prog \<turnstile> Label l -CEdge (p', es, rets)\<rightarrow>\<^sub>p nx\<close> have "prog;;c\<^sub>2 \<turnstile> Label l -CEdge (p', es, rets)\<rightarrow>\<^sub>p Label lx" by(auto intro:Proc_CFG_edge_SeqFirst_nodes_Label) with MainCall show ?case by(fastforce dest:PCFG.MainCall) next case (ProcCall ins outs c es' rets' l' ins' outs' c' ps) from \<open>containsCall procs prog ps p\<close> have "containsCall procs (prog;;c\<^sub>2) ps p" by simp with ProcCall show ?case by(fastforce intro:PCFG.ProcCall) next case (MainCallReturn px es rets) from \<open>prog \<turnstile> Label l -CEdge (px, es, rets)\<rightarrow>\<^sub>p n'\<close> \<open>Main = p\<close> obtain nx'' where "prog;;c\<^sub>2 \<turnstile> Label l -CEdge (px, es, rets)\<rightarrow>\<^sub>p nx''" by(auto elim:Proc_CFG_edge_SeqFirst_source_Label) with MainCallReturn show ?case by(fastforce dest:PCFG.MainCallReturn) next case (ProcCallReturn ins outs c px' es' rets' ps) from \<open>containsCall procs prog ps p\<close> have "containsCall procs (prog;;c\<^sub>2) ps p" by simp with ProcCallReturn show ?case by(fastforce dest!:PCFG.ProcCallReturn) qed qed lemma PCFG_edge_SeqFirst_target_Label: "prog,procs \<turnstile> (p,n) -et\<rightarrow> (p',Label l') \<Longrightarrow> prog;;c\<^sub>2,procs \<turnstile> (p,n) -et\<rightarrow> (p',Label l')" proof(induct "(p,n)" et "(p',Label l')" rule:PCFG.induct) case Main thus ?case by(fastforce dest:Proc_CFG_edge_SeqFirst_target_Label intro:PCFG.Main) next case (Proc ins outs c et ps) from \<open>containsCall procs prog ps p\<close> have "containsCall procs (prog;;c\<^sub>2) ps p" by simp with Proc show ?case by(fastforce dest:PCFG.Proc) next case MainReturn thus ?case by(fastforce dest:Proc_CFG_edge_SeqFirst_target_Label intro!:PCFG.MainReturn[simplified]) next case (ProcReturn ins outs c lx es' rets' ins' outs' c' ps) from \<open>containsCall procs prog ps p'\<close> have "containsCall procs (prog;;c\<^sub>2) ps p'" by simp with ProcReturn show ?case by(fastforce intro:PCFG.ProcReturn) next case MainCallReturn thus ?case by(fastforce dest:Proc_CFG_edge_SeqFirst_target_Label intro:PCFG.MainCallReturn) next case (ProcCallReturn ins outs c px' es' rets' ps) from \<open>containsCall procs prog ps p\<close> have "containsCall procs (prog;;c\<^sub>2) ps p" by simp with ProcCallReturn show ?case by(fastforce dest!:PCFG.ProcCallReturn) qed lemma path_SeqFirst: assumes "Rep_wf_prog wfp = (prog,procs)" and "Rep_wf_prog wfp' = (prog;;c\<^sub>2,procs)" shows "\<lbrakk>wfp \<turnstile> (p,n) -as\<rightarrow>* (p,Label l); \<forall>a \<in> set as. intra_kind (kind a)\<rbrakk> \<Longrightarrow> wfp' \<turnstile> (p,n) -as\<rightarrow>* (p,Label l)" proof(induct "(p,n)" as "(p,Label l)" arbitrary:n rule:ProcCFG.path.induct) case empty_path from \<open>CFG.valid_node sourcenode targetnode (valid_edge wfp) (p, Label l)\<close> \<open>Rep_wf_prog wfp = (prog, procs)\<close> \<open>Rep_wf_prog wfp' = (prog;; c\<^sub>2, procs)\<close> have "CFG.valid_node sourcenode targetnode (valid_edge wfp') (p, Label l)" apply(auto simp:ProcCFG.valid_node_def valid_edge_def) apply(erule PCFG_edge_SeqFirst_source_Label,fastforce) by(drule PCFG_edge_SeqFirst_target_Label,fastforce) thus ?case by(fastforce intro:ProcCFG.empty_path) next case (Cons_path n'' as a nx) note IH = \<open>\<And>n. \<lbrakk>n'' = (p, n); \<forall>a\<in>set as. intra_kind (kind a)\<rbrakk> \<Longrightarrow> wfp' \<turnstile> (p, n) -as\<rightarrow>* (p, Label l)\<close> note [simp] = \<open>Rep_wf_prog wfp = (prog,procs)\<close> \<open>Rep_wf_prog wfp' = (prog;;c\<^sub>2,procs)\<close> from \<open>Rep_wf_prog wfp = (prog,procs)\<close> have wf:"well_formed procs" by(fastforce intro:wf_wf_prog) from \<open>\<forall>a\<in>set (a # as). intra_kind (kind a)\<close> have "intra_kind (kind a)" and "\<forall>a\<in>set as. intra_kind (kind a)" by simp_all from \<open>valid_edge wfp a\<close> \<open>sourcenode a = (p, nx)\<close> \<open>targetnode a = n''\<close> \<open>intra_kind (kind a)\<close> wf obtain nx' where "n'' = (p,nx')" by(auto elim:PCFG.cases simp:valid_edge_def intra_kind_def) from IH[OF this \<open>\<forall>a\<in>set as. intra_kind (kind a)\<close>] have path:"wfp' \<turnstile> (p, nx') -as\<rightarrow>* (p, Label l)" . have "valid_edge wfp' a" proof(cases nx') case (Label lx) with \<open>valid_edge wfp a\<close> \<open>sourcenode a = (p, nx)\<close> \<open>targetnode a = n''\<close> \<open>n'' = (p,nx')\<close> show ?thesis by(fastforce intro:PCFG_edge_SeqFirst_target_Label simp:intra_kind_def valid_edge_def) next case Entry with \<open>valid_edge wfp a\<close> \<open>targetnode a = n''\<close> \<open>n'' = (p,nx')\<close> \<open>intra_kind (kind a)\<close> have False by(auto elim:PCFG.cases simp:valid_edge_def intra_kind_def) thus ?thesis by simp next case Exit with path \<open>\<forall>a\<in>set as. intra_kind (kind a)\<close> have False by(induct "(p,nx')" as "(p,Label l)" rule:ProcCFG.path.induct) (auto elim!:PCFG.cases simp:valid_edge_def intra_kind_def) thus ?thesis by simp qed with \<open>sourcenode a = (p, nx)\<close> \<open>targetnode a = n''\<close> \<open>n'' = (p,nx')\<close> path show ?case by(fastforce intro:ProcCFG.Cons_path) qed subsubsection \<open>From \<open>prog\<close> to \<open>c\<^sub>1;;prog\<close>\<close> lemma Proc_CFG_edge_SeqSecond_source_not_Entry: "\<lbrakk>prog \<turnstile> n -et\<rightarrow>\<^sub>p n'; n \<noteq> Entry\<rbrakk> \<Longrightarrow> c\<^sub>1;;prog \<turnstile> n \<oplus> #:c\<^sub>1 -et\<rightarrow>\<^sub>p n' \<oplus> #:c\<^sub>1" by(induct rule:Proc_CFG.induct)(fastforce intro:Proc_CFG_SeqSecond Proc_CFG.intros)+ lemma PCFG_Main_edge_SeqSecond_source_not_Entry: "\<lbrakk>prog,procs \<turnstile> (Main,n) -et\<rightarrow> (p',n'); n \<noteq> Entry; intra_kind et; well_formed procs\<rbrakk> \<Longrightarrow> c\<^sub>1;;prog,procs \<turnstile> (Main,n \<oplus> #:c\<^sub>1) -et\<rightarrow> (p',n' \<oplus> #:c\<^sub>1)" proof(induct "(Main,n)" et "(p',n')" rule:PCFG.induct) case Main thus ?case by(fastforce dest:Proc_CFG_edge_SeqSecond_source_not_Entry intro:PCFG.Main) next case (MainCallReturn p es rets) from \<open>prog \<turnstile> n -CEdge (p, es, rets)\<rightarrow>\<^sub>p n'\<close> \<open>n \<noteq> Entry\<close> have "c\<^sub>1;;prog \<turnstile> n \<oplus> #:c\<^sub>1 -CEdge (p, es, rets)\<rightarrow>\<^sub>p n' \<oplus> #:c\<^sub>1" by(rule Proc_CFG_edge_SeqSecond_source_not_Entry) with MainCallReturn show ?case by(fastforce intro:PCFG.MainCallReturn) qed (auto simp:intra_kind_def) lemma valid_node_Main_SeqSecond: assumes "CFG.valid_node sourcenode targetnode (valid_edge wfp) (Main,n)" and "n \<noteq> Entry" and "Rep_wf_prog wfp = (prog,procs)" and "Rep_wf_prog wfp' = (c\<^sub>1;;prog,procs)" shows "CFG.valid_node sourcenode targetnode (valid_edge wfp') (Main, n \<oplus> #:c\<^sub>1)" proof - note [simp] = \<open>Rep_wf_prog wfp = (prog,procs)\<close> \<open>Rep_wf_prog wfp' = (c\<^sub>1;;prog,procs)\<close> from \<open>Rep_wf_prog wfp = (prog,procs)\<close> have wf:"well_formed procs" by(fastforce intro:wf_wf_prog) from \<open>CFG.valid_node sourcenode targetnode (valid_edge wfp) (Main,n)\<close> obtain a where "prog,procs \<turnstile> sourcenode a -kind a\<rightarrow> targetnode a" and "(Main,n) = sourcenode a \<or> (Main,n) = targetnode a" by(fastforce simp:ProcCFG.valid_node_def valid_edge_def) from this \<open>n \<noteq> Entry\<close> wf show ?thesis proof(induct "sourcenode a" "kind a" "targetnode a" rule:PCFG.induct) case (Main nx nx') from \<open>(Main,n) = sourcenode a \<or> (Main,n) = targetnode a\<close> show ?case proof assume "(Main,n) = sourcenode a" with \<open>(Main, nx) = sourcenode a\<close>[THEN sym] have [simp]:"nx = n" by simp from \<open>n \<noteq> Entry\<close> \<open>prog \<turnstile> nx -IEdge (kind a)\<rightarrow>\<^sub>p nx'\<close> have "c\<^sub>1;;prog \<turnstile> n \<oplus> #:c\<^sub>1 -IEdge (kind a)\<rightarrow>\<^sub>p nx' \<oplus> #:c\<^sub>1" by(fastforce intro:Proc_CFG_edge_SeqSecond_source_not_Entry) hence "c\<^sub>1;;prog,procs \<turnstile> (Main,n \<oplus> #:c\<^sub>1) -kind a\<rightarrow> (Main,nx' \<oplus> #:c\<^sub>1)" by(rule PCFG.Main) thus ?thesis by(simp add:ProcCFG.valid_node_def)(fastforce simp:valid_edge_def) next assume "(Main, n) = targetnode a" show ?thesis proof(cases "nx = Entry") case True with \<open>prog \<turnstile> nx -IEdge (kind a)\<rightarrow>\<^sub>p nx'\<close> have "nx' = Exit \<or> nx' = Label 0" by(fastforce dest:Proc_CFG_EntryD) thus ?thesis proof assume "nx' = Exit" with \<open>(Main, n) = targetnode a\<close> \<open>(Main, nx') = targetnode a\<close>[THEN sym] show ?thesis by simp next assume "nx' = Label 0" obtain l etx where "c\<^sub>1 \<turnstile> Label l -IEdge etx\<rightarrow>\<^sub>p Exit" and "l \<le> #:c\<^sub>1" by(erule Proc_CFG_Exit_edge) hence "c\<^sub>1;;prog \<turnstile> Label l -IEdge etx\<rightarrow>\<^sub>p Label #:c\<^sub>1" by(fastforce intro:Proc_CFG_SeqConnect) with \<open>nx' = Label 0\<close> have "c\<^sub>1;;prog,procs \<turnstile> (Main,Label l) -etx\<rightarrow> (Main,nx'\<oplus>#:c\<^sub>1)" by(fastforce intro:PCFG.Main) with \<open>(Main, n) = targetnode a\<close> \<open>(Main, nx') = targetnode a\<close>[THEN sym] show ?thesis by(simp add:ProcCFG.valid_node_def)(fastforce simp:valid_edge_def) qed next case False with \<open>prog \<turnstile> nx -IEdge (kind a)\<rightarrow>\<^sub>p nx'\<close> have "c\<^sub>1;;prog \<turnstile> nx \<oplus> #:c\<^sub>1 -IEdge (kind a)\<rightarrow>\<^sub>p nx' \<oplus> #:c\<^sub>1" by(fastforce intro:Proc_CFG_edge_SeqSecond_source_not_Entry) hence "c\<^sub>1;;prog,procs \<turnstile> (Main,nx \<oplus> #:c\<^sub>1) -kind a\<rightarrow> (Main,nx' \<oplus> #:c\<^sub>1)" by(rule PCFG.Main) with \<open>(Main, n) = targetnode a\<close> \<open>(Main, nx') = targetnode a\<close>[THEN sym] show ?thesis by(simp add:ProcCFG.valid_node_def)(fastforce simp:valid_edge_def) qed qed next case (Proc p ins outs c nx n' ps) from \<open>(p, nx) = sourcenode a\<close>[THEN sym] \<open>(p, n') = targetnode a\<close>[THEN sym] \<open>(Main, n) = sourcenode a \<or> (Main, n) = targetnode a\<close> \<open>(p, ins, outs, c) \<in> set procs\<close> \<open>well_formed procs\<close> have False by fastforce thus ?case by simp next case (MainCall l p es rets n' ins outs c) from \<open>(p, ins, outs, c) \<in> set procs\<close> wf \<open>(p, Entry) = targetnode a\<close>[THEN sym] \<open>(Main, Label l) = sourcenode a\<close>[THEN sym] \<open>(Main, n) = sourcenode a \<or> (Main, n) = targetnode a\<close> have [simp]:"n = Label l" by fastforce from \<open>prog \<turnstile> Label l -CEdge (p, es, rets)\<rightarrow>\<^sub>p n'\<close> have "c\<^sub>1;;prog \<turnstile> Label l \<oplus> #:c\<^sub>1 -CEdge (p, es, rets)\<rightarrow>\<^sub>p n' \<oplus> #:c\<^sub>1" by -(rule Proc_CFG_edge_SeqSecond_source_not_Entry,auto) with \<open>(p, ins, outs, c) \<in> set procs\<close> have "c\<^sub>1;;prog,procs \<turnstile> (Main,Label (l + #:c\<^sub>1)) -(\<lambda>s. True):(Main,n' \<oplus> #:c\<^sub>1)\<hookrightarrow>\<^bsub>p\<^esub>map (\<lambda>e cf. interpret e cf) es\<rightarrow> (p,Entry)" by(fastforce intro:PCFG.MainCall) thus ?case by(simp add:ProcCFG.valid_node_def)(fastforce simp:valid_edge_def) next case (ProcCall p ins outs c l p' es' rets' l' ins' outs' c') from \<open>(p, Label l) = sourcenode a\<close>[THEN sym] \<open>(p', Entry) = targetnode a\<close>[THEN sym] \<open>well_formed procs\<close> \<open>(p, ins, outs, c) \<in> set procs\<close> \<open>(p', ins', outs', c') \<in> set procs\<close> \<open>(Main, n) = sourcenode a \<or> (Main, n) = targetnode a\<close> have False by fastforce thus ?case by simp next case (MainReturn l p es rets l' ins outs c) from \<open>(p, ins, outs, c) \<in> set procs\<close> wf \<open>(p, Exit) = sourcenode a\<close>[THEN sym] \<open>(Main, Label l') = targetnode a\<close>[THEN sym] \<open>(Main, n) = sourcenode a \<or> (Main, n) = targetnode a\<close> have [simp]:"n = Label l'" by fastforce from \<open>prog \<turnstile> Label l -CEdge (p, es, rets)\<rightarrow>\<^sub>p Label l'\<close> have "c\<^sub>1;;prog \<turnstile> Label l \<oplus> #:c\<^sub>1 -CEdge (p, es, rets)\<rightarrow>\<^sub>p Label l' \<oplus> #:c\<^sub>1" by -(rule Proc_CFG_edge_SeqSecond_source_not_Entry,auto) with \<open>(p, ins, outs, c) \<in> set procs\<close> have "c\<^sub>1;;prog,procs \<turnstile> (p,Exit) -(\<lambda>cf. snd cf = (Main,Label l' \<oplus> #:c\<^sub>1))\<hookleftarrow>\<^bsub>p\<^esub> (\<lambda>cf cf'. cf'(rets [:=] map cf outs))\<rightarrow> (Main,Label (l' + #:c\<^sub>1))" by(fastforce intro:PCFG.MainReturn) thus ?case by(simp add:ProcCFG.valid_node_def)(fastforce simp:valid_edge_def) next case (ProcReturn p ins outs c l p' es' rets' l' ins' outs' c' ps) from \<open>(p', Exit) = sourcenode a\<close>[THEN sym] \<open>(p, Label l') = targetnode a\<close>[THEN sym] \<open>well_formed procs\<close> \<open>(p, ins, outs, c) \<in> set procs\<close> \<open>(p', ins', outs', c') \<in> set procs\<close> \<open>(Main, n) = sourcenode a \<or> (Main, n) = targetnode a\<close> have False by fastforce thus ?case by simp next case (MainCallReturn nx p es rets nx') from \<open>(Main,n) = sourcenode a \<or> (Main,n) = targetnode a\<close> show ?case proof assume "(Main,n) = sourcenode a" with \<open>(Main, nx) = sourcenode a\<close>[THEN sym] have [simp]:"nx = n" by simp from \<open>n \<noteq> Entry\<close> \<open>prog \<turnstile> nx -CEdge (p, es, rets)\<rightarrow>\<^sub>p nx'\<close> have "c\<^sub>1;;prog \<turnstile> n \<oplus> #:c\<^sub>1 -CEdge (p, es, rets)\<rightarrow>\<^sub>p nx' \<oplus> #:c\<^sub>1" by(fastforce intro:Proc_CFG_edge_SeqSecond_source_not_Entry) hence "c\<^sub>1;;prog,procs \<turnstile> (Main,n \<oplus> #:c\<^sub>1) -(\<lambda>s. False)\<^sub>\<surd>\<rightarrow> (Main,nx' \<oplus> #:c\<^sub>1)" by -(rule PCFG.MainCallReturn) thus ?thesis by(simp add:ProcCFG.valid_node_def)(fastforce simp:valid_edge_def) next assume "(Main, n) = targetnode a" from \<open>prog \<turnstile> nx -CEdge (p, es, rets)\<rightarrow>\<^sub>p nx'\<close> have "nx \<noteq> Entry" by(fastforce dest:Proc_CFG_Call_Labels) with \<open>prog \<turnstile> nx -CEdge (p, es, rets)\<rightarrow>\<^sub>p nx'\<close> have "c\<^sub>1;;prog \<turnstile> nx \<oplus> #:c\<^sub>1 -CEdge (p, es, rets)\<rightarrow>\<^sub>p nx' \<oplus> #:c\<^sub>1" by(fastforce intro:Proc_CFG_edge_SeqSecond_source_not_Entry) hence "c\<^sub>1;;prog,procs \<turnstile> (Main,nx \<oplus> #:c\<^sub>1) -(\<lambda>s. False)\<^sub>\<surd>\<rightarrow> (Main,nx' \<oplus> #:c\<^sub>1)" by -(rule PCFG.MainCallReturn) with \<open>(Main, n) = targetnode a\<close> \<open>(Main, nx') = targetnode a\<close>[THEN sym] show ?thesis by(simp add:ProcCFG.valid_node_def)(fastforce simp:valid_edge_def) qed next case (ProcCallReturn p ins outs c nx p' es' rets' n' ps) from \<open>(p, nx) = sourcenode a\<close>[THEN sym] \<open>(p, n') = targetnode a\<close>[THEN sym] \<open>(p, ins, outs, c) \<in> set procs\<close> \<open>well_formed procs\<close> \<open>(Main, n) = sourcenode a \<or> (Main, n) = targetnode a\<close> have False by fastforce thus ?case by simp qed qed lemma path_Main_SeqSecond: assumes "Rep_wf_prog wfp = (prog,procs)" and "Rep_wf_prog wfp' = (c\<^sub>1;;prog,procs)" shows "\<lbrakk>wfp \<turnstile> (Main,n) -as\<rightarrow>* (p',n'); \<forall>a \<in> set as. intra_kind (kind a); n \<noteq> Entry\<rbrakk> \<Longrightarrow> wfp' \<turnstile> (Main,n \<oplus> #:c\<^sub>1) -as \<oplus>s #:c\<^sub>1\<rightarrow>* (p',n' \<oplus> #:c\<^sub>1)" proof(induct "(Main,n)" as "(p',n')" arbitrary:n rule:ProcCFG.path.induct) case empty_path from \<open>CFG.valid_node sourcenode targetnode (valid_edge wfp) (Main, n')\<close> \<open>n' \<noteq> Entry\<close> \<open>Rep_wf_prog wfp = (prog,procs)\<close> \<open>Rep_wf_prog wfp' = (c\<^sub>1;;prog,procs)\<close> have "CFG.valid_node sourcenode targetnode (valid_edge wfp') (Main, n' \<oplus> #:c\<^sub>1)" by(fastforce intro:valid_node_Main_SeqSecond) with \<open>Main = p'\<close> show ?case by(fastforce intro:ProcCFG.empty_path simp:label_incrs_def) next case (Cons_path n'' as a n) note IH = \<open>\<And>n. \<lbrakk>n'' = (Main, n); \<forall>a\<in>set as. intra_kind (kind a); n \<noteq> Entry\<rbrakk> \<Longrightarrow> wfp' \<turnstile> (Main, n \<oplus> #:c\<^sub>1) -as \<oplus>s #:c\<^sub>1\<rightarrow>* (p', n' \<oplus> #:c\<^sub>1)\<close> note [simp] = \<open>Rep_wf_prog wfp = (prog,procs)\<close> \<open>Rep_wf_prog wfp' = (c\<^sub>1;;prog,procs)\<close> from \<open>Rep_wf_prog wfp = (prog,procs)\<close> have wf:"well_formed procs" by(fastforce intro:wf_wf_prog) from \<open>\<forall>a\<in>set (a # as). intra_kind (kind a)\<close> have "intra_kind (kind a)" and "\<forall>a\<in>set as. intra_kind (kind a)" by simp_all from \<open>valid_edge wfp a\<close> \<open>sourcenode a = (Main, n)\<close> \<open>targetnode a = n''\<close> \<open>intra_kind (kind a)\<close> wf obtain nx'' where "n'' = (Main,nx'')" and "nx'' \<noteq> Entry" by(auto elim!:PCFG.cases simp:valid_edge_def intra_kind_def) from IH[OF \<open>n'' = (Main,nx'')\<close> \<open>\<forall>a\<in>set as. intra_kind (kind a)\<close> \<open>nx'' \<noteq> Entry\<close>] have path:"wfp' \<turnstile> (Main, nx'' \<oplus> #:c\<^sub>1) -as \<oplus>s #:c\<^sub>1\<rightarrow>* (p', n' \<oplus> #:c\<^sub>1)" . from \<open>valid_edge wfp a\<close> \<open>sourcenode a = (Main, n)\<close> \<open>targetnode a = n''\<close> \<open>n'' = (Main,nx'')\<close> \<open>n \<noteq> Entry\<close> \<open>intra_kind (kind a)\<close> wf have "c\<^sub>1;; prog,procs \<turnstile> (Main, n \<oplus> #:c\<^sub>1) -kind a\<rightarrow> (Main, nx'' \<oplus> #:c\<^sub>1)" by(fastforce intro:PCFG_Main_edge_SeqSecond_source_not_Entry simp:valid_edge_def) with path \<open>sourcenode a = (Main, n)\<close> \<open>targetnode a = n''\<close> \<open>n'' = (Main,nx'')\<close> show ?case apply(cases a) apply(clarsimp simp:label_incrs_def) by(auto intro:ProcCFG.Cons_path simp:valid_edge_def) qed subsubsection \<open>From \<open>prog\<close> to \<open>if (b) prog else c\<^sub>2\<close>\<close> lemma Proc_CFG_edge_CondTrue_source_not_Entry: "\<lbrakk>prog \<turnstile> n -et\<rightarrow>\<^sub>p n'; n \<noteq> Entry\<rbrakk> \<Longrightarrow> if (b) prog else c\<^sub>2 \<turnstile> n \<oplus> 1 -et\<rightarrow>\<^sub>p n' \<oplus> 1" by(induct rule:Proc_CFG.induct)(fastforce intro:Proc_CFG_CondThen Proc_CFG.intros)+ lemma PCFG_Main_edge_CondTrue_source_not_Entry: "\<lbrakk>prog,procs \<turnstile> (Main,n) -et\<rightarrow> (p',n'); n \<noteq> Entry; intra_kind et; well_formed procs\<rbrakk> \<Longrightarrow> if (b) prog else c\<^sub>2,procs \<turnstile> (Main,n \<oplus> 1) -et\<rightarrow> (p',n' \<oplus> 1)" proof(induct "(Main,n)" et "(p',n')" rule:PCFG.induct) case Main thus ?case by(fastforce dest:Proc_CFG_edge_CondTrue_source_not_Entry intro:PCFG.Main) next case (MainCallReturn p es rets) from \<open>prog \<turnstile> n -CEdge (p, es, rets)\<rightarrow>\<^sub>p n'\<close> \<open>n \<noteq> Entry\<close> have "if (b) prog else c\<^sub>2 \<turnstile> n \<oplus> 1 -CEdge (p, es, rets)\<rightarrow>\<^sub>p n' \<oplus> 1" by(rule Proc_CFG_edge_CondTrue_source_not_Entry) with MainCallReturn show ?case by(fastforce intro:PCFG.MainCallReturn) qed (auto simp:intra_kind_def) lemma valid_node_Main_CondTrue: assumes "CFG.valid_node sourcenode targetnode (valid_edge wfp) (Main,n)" and "n \<noteq> Entry" and "Rep_wf_prog wfp = (prog,procs)" and "Rep_wf_prog wfp' = (if (b) prog else c\<^sub>2,procs)" shows "CFG.valid_node sourcenode targetnode (valid_edge wfp') (Main, n \<oplus> 1)" proof - note [simp] = \<open>Rep_wf_prog wfp = (prog,procs)\<close> \<open>Rep_wf_prog wfp' = (if (b) prog else c\<^sub>2,procs)\<close> from \<open>Rep_wf_prog wfp = (prog,procs)\<close> have wf:"well_formed procs" by(fastforce intro:wf_wf_prog) from \<open>CFG.valid_node sourcenode targetnode (valid_edge wfp) (Main,n)\<close> obtain a where "prog,procs \<turnstile> sourcenode a -kind a\<rightarrow> targetnode a" and "(Main,n) = sourcenode a \<or> (Main,n) = targetnode a" by(fastforce simp:ProcCFG.valid_node_def valid_edge_def) from this \<open>n \<noteq> Entry\<close> wf show ?thesis proof(induct "sourcenode a" "kind a" "targetnode a" rule:PCFG.induct) case (Main nx nx') from \<open>(Main,n) = sourcenode a \<or> (Main,n) = targetnode a\<close> show ?case proof assume "(Main,n) = sourcenode a" with \<open>(Main, nx) = sourcenode a\<close>[THEN sym] have [simp]:"nx = n" by simp from \<open>n \<noteq> Entry\<close> \<open>prog \<turnstile> nx -IEdge (kind a)\<rightarrow>\<^sub>p nx'\<close> have "if (b) prog else c\<^sub>2 \<turnstile> n \<oplus> 1 -IEdge (kind a)\<rightarrow>\<^sub>p nx' \<oplus> 1" by(fastforce intro:Proc_CFG_edge_CondTrue_source_not_Entry) hence "if (b) prog else c\<^sub>2,procs \<turnstile> (Main,n \<oplus> 1) -kind a\<rightarrow> (Main,nx' \<oplus> 1)" by(rule PCFG.Main) thus ?thesis by(simp add:ProcCFG.valid_node_def)(fastforce simp:valid_edge_def) next assume "(Main, n) = targetnode a" show ?thesis proof(cases "nx = Entry") case True with \<open>prog \<turnstile> nx -IEdge (kind a)\<rightarrow>\<^sub>p nx'\<close> have "nx' = Exit \<or> nx' = Label 0" by(fastforce dest:Proc_CFG_EntryD) thus ?thesis proof assume "nx' = Exit" with \<open>(Main, n) = targetnode a\<close> \<open>(Main, nx') = targetnode a\<close>[THEN sym] show ?thesis by simp next assume "nx' = Label 0" have "if (b) prog else c\<^sub>2 \<turnstile> Label 0 -IEdge (\<lambda>cf. state_check cf b (Some true))\<^sub>\<surd>\<rightarrow>\<^sub>p Label 1" by(rule Proc_CFG_CondTrue) with \<open>nx' = Label 0\<close> have "if (b) prog else c\<^sub>2,procs \<turnstile> (Main,Label 0) -(\<lambda>cf. state_check cf b (Some true))\<^sub>\<surd>\<rightarrow> (Main,nx' \<oplus> 1)" by(fastforce intro:PCFG.Main) with \<open>(Main, n) = targetnode a\<close> \<open>(Main, nx') = targetnode a\<close>[THEN sym] show ?thesis by(simp add:ProcCFG.valid_node_def)(fastforce simp:valid_edge_def) qed next case False with \<open>prog \<turnstile> nx -IEdge (kind a)\<rightarrow>\<^sub>p nx'\<close> have "if (b) prog else c\<^sub>2 \<turnstile> nx \<oplus> 1 -IEdge (kind a)\<rightarrow>\<^sub>p nx' \<oplus> 1" by(fastforce intro:Proc_CFG_edge_CondTrue_source_not_Entry) hence "if (b) prog else c\<^sub>2,procs \<turnstile> (Main,nx \<oplus> 1) -kind a\<rightarrow> (Main,nx' \<oplus> 1)" by(rule PCFG.Main) with \<open>(Main, n) = targetnode a\<close> \<open>(Main, nx') = targetnode a\<close>[THEN sym] show ?thesis by(simp add:ProcCFG.valid_node_def)(fastforce simp:valid_edge_def) qed qed next case (Proc p ins outs c nx n' ps) from \<open>(p, nx) = sourcenode a\<close>[THEN sym] \<open>(p, n') = targetnode a\<close>[THEN sym] \<open>(p, ins, outs, c) \<in> set procs\<close> \<open>well_formed procs\<close> \<open>(Main, n) = sourcenode a \<or> (Main, n) = targetnode a\<close> have False by fastforce thus ?case by simp next case (MainCall l p es rets n' ins outs c) from \<open>(p, ins, outs, c) \<in> set procs\<close> \<open>(p, Entry) = targetnode a\<close>[THEN sym] \<open>(Main, Label l) = sourcenode a\<close>[THEN sym] wf \<open>(Main, n) = sourcenode a \<or> (Main, n) = targetnode a\<close> have [simp]:"n = Label l" by fastforce from \<open>prog \<turnstile> Label l -CEdge (p, es, rets)\<rightarrow>\<^sub>p n'\<close> have "if (b) prog else c\<^sub>2 \<turnstile> Label l \<oplus> 1 -CEdge (p, es, rets)\<rightarrow>\<^sub>p n' \<oplus> 1" by -(rule Proc_CFG_edge_CondTrue_source_not_Entry,auto) with \<open>(p, ins, outs, c) \<in> set procs\<close> have "if (b) prog else c\<^sub>2,procs \<turnstile> (Main,Label (l + 1)) -(\<lambda>s. True):(Main,n' \<oplus> 1)\<hookrightarrow>\<^bsub>p\<^esub>map (\<lambda>e cf. interpret e cf) es\<rightarrow> (p,Entry)" by(fastforce intro:PCFG.MainCall) thus ?case by(simp add:ProcCFG.valid_node_def)(fastforce simp:valid_edge_def) next case (ProcCall p ins outs c l p' es' rets' l' ins' outs' c' ps) from \<open>(p, Label l) = sourcenode a\<close>[THEN sym] \<open>(p', Entry) = targetnode a\<close>[THEN sym] \<open>well_formed procs\<close> \<open>(p, ins, outs, c) \<in> set procs\<close> \<open>(p', ins', outs', c') \<in> set procs\<close> \<open>(Main, n) = sourcenode a \<or> (Main, n) = targetnode a\<close> have False by fastforce thus ?case by simp next case (MainReturn l p es rets l' ins outs c) from \<open>(p, ins, outs, c) \<in> set procs\<close> \<open>(p, Exit) = sourcenode a\<close>[THEN sym] \<open>(Main, Label l') = targetnode a\<close>[THEN sym] wf \<open>(Main, n) = sourcenode a \<or> (Main, n) = targetnode a\<close> have [simp]:"n = Label l'" by fastforce from \<open>prog \<turnstile> Label l -CEdge (p, es, rets)\<rightarrow>\<^sub>p Label l'\<close> have "if (b) prog else c\<^sub>2 \<turnstile> Label l \<oplus> 1 -CEdge (p, es, rets)\<rightarrow>\<^sub>p Label l' \<oplus> 1" by -(rule Proc_CFG_edge_CondTrue_source_not_Entry,auto) with \<open>(p, ins, outs, c) \<in> set procs\<close> have "if (b) prog else c\<^sub>2,procs \<turnstile> (p,Exit) -(\<lambda>cf. snd cf = (Main,Label l' \<oplus> 1))\<hookleftarrow>\<^bsub>p\<^esub> (\<lambda>cf cf'. cf'(rets [:=] map cf outs))\<rightarrow> (Main,Label (l' + 1))" by(fastforce intro:PCFG.MainReturn) thus ?case by(simp add:ProcCFG.valid_node_def)(fastforce simp:valid_edge_def) next case (ProcReturn p ins outs c l p' es' rets' l' ins' outs' c' ps) from \<open>(p', Exit) = sourcenode a\<close>[THEN sym] \<open>(p, Label l') = targetnode a\<close>[THEN sym] \<open>well_formed procs\<close> \<open>(p, ins, outs, c) \<in> set procs\<close> \<open>(p', ins', outs', c') \<in> set procs\<close> \<open>(Main, n) = sourcenode a \<or> (Main, n) = targetnode a\<close> have False by fastforce thus ?case by simp next case (MainCallReturn nx p es rets nx') from \<open>(Main,n) = sourcenode a \<or> (Main,n) = targetnode a\<close> show ?case proof assume "(Main,n) = sourcenode a" with \<open>(Main, nx) = sourcenode a\<close>[THEN sym] have [simp]:"nx = n" by simp from \<open>n \<noteq> Entry\<close> \<open>prog \<turnstile> nx -CEdge (p, es, rets)\<rightarrow>\<^sub>p nx'\<close> have "if (b) prog else c\<^sub>2 \<turnstile> n \<oplus> 1 -CEdge (p, es, rets)\<rightarrow>\<^sub>p nx' \<oplus> 1" by(fastforce intro:Proc_CFG_edge_CondTrue_source_not_Entry) hence "if (b) prog else c\<^sub>2,procs \<turnstile> (Main,n \<oplus> 1) -(\<lambda>s. False)\<^sub>\<surd>\<rightarrow> (Main,nx' \<oplus> 1)" by -(rule PCFG.MainCallReturn) thus ?thesis by(simp add:ProcCFG.valid_node_def)(fastforce simp:valid_edge_def) next assume "(Main, n) = targetnode a" from \<open>prog \<turnstile> nx -CEdge (p, es, rets)\<rightarrow>\<^sub>p nx'\<close> have "nx \<noteq> Entry" by(fastforce dest:Proc_CFG_Call_Labels) with \<open>prog \<turnstile> nx -CEdge (p, es, rets)\<rightarrow>\<^sub>p nx'\<close> have "if (b) prog else c\<^sub>2 \<turnstile> nx \<oplus> 1 -CEdge (p, es, rets)\<rightarrow>\<^sub>p nx' \<oplus> 1" by(fastforce intro:Proc_CFG_edge_CondTrue_source_not_Entry) hence "if (b) prog else c\<^sub>2,procs \<turnstile> (Main,nx \<oplus> 1) -(\<lambda>s. False)\<^sub>\<surd>\<rightarrow> (Main,nx' \<oplus> 1)" by -(rule PCFG.MainCallReturn) with \<open>(Main, n) = targetnode a\<close> \<open>(Main, nx') = targetnode a\<close>[THEN sym] show ?thesis by(simp add:ProcCFG.valid_node_def)(fastforce simp:valid_edge_def) qed next case (ProcCallReturn p ins outs c nx p' es' rets' n' ps) from \<open>(p, nx) = sourcenode a\<close>[THEN sym] \<open>(p, n') = targetnode a\<close>[THEN sym] \<open>(p, ins, outs, c) \<in> set procs\<close> \<open>well_formed procs\<close> \<open>(Main, n) = sourcenode a \<or> (Main, n) = targetnode a\<close> have False by fastforce thus ?case by simp qed qed lemma path_Main_CondTrue: assumes "Rep_wf_prog wfp = (prog,procs)" and "Rep_wf_prog wfp' = (if (b) prog else c\<^sub>2,procs)" shows "\<lbrakk>wfp \<turnstile> (Main,n) -as\<rightarrow>* (p',n'); \<forall>a \<in> set as. intra_kind (kind a); n \<noteq> Entry\<rbrakk> \<Longrightarrow> wfp' \<turnstile> (Main,n \<oplus> 1) -as \<oplus>s 1\<rightarrow>* (p',n' \<oplus> 1)" proof(induct "(Main,n)" as "(p',n')" arbitrary:n rule:ProcCFG.path.induct) case empty_path from \<open>CFG.valid_node sourcenode targetnode (valid_edge wfp) (Main, n')\<close> \<open>n' \<noteq> Entry\<close> \<open>Rep_wf_prog wfp = (prog,procs)\<close> \<open>Rep_wf_prog wfp' = (if (b) prog else c\<^sub>2,procs)\<close> have "CFG.valid_node sourcenode targetnode (valid_edge wfp') (Main, n' \<oplus> 1)" by(fastforce intro:valid_node_Main_CondTrue) with \<open>Main = p'\<close> show ?case by(fastforce intro:ProcCFG.empty_path simp:label_incrs_def) next case (Cons_path n'' as a n) note IH = \<open>\<And>n. \<lbrakk>n'' = (Main, n); \<forall>a\<in>set as. intra_kind (kind a); n \<noteq> Entry\<rbrakk> \<Longrightarrow> wfp' \<turnstile> (Main, n \<oplus> 1) -as \<oplus>s 1\<rightarrow>* (p', n' \<oplus> 1)\<close> note [simp] = \<open>Rep_wf_prog wfp = (prog,procs)\<close> \<open>Rep_wf_prog wfp' = (if (b) prog else c\<^sub>2,procs)\<close> from \<open>Rep_wf_prog wfp = (prog,procs)\<close> have wf:"well_formed procs" by(fastforce intro:wf_wf_prog) from \<open>\<forall>a\<in>set (a # as). intra_kind (kind a)\<close> have "intra_kind (kind a)" and "\<forall>a\<in>set as. intra_kind (kind a)" by simp_all from \<open>valid_edge wfp a\<close> \<open>sourcenode a = (Main, n)\<close> \<open>targetnode a = n''\<close> \<open>intra_kind (kind a)\<close> wf obtain nx'' where "n'' = (Main,nx'')" and "nx'' \<noteq> Entry" by(auto elim!:PCFG.cases simp:valid_edge_def intra_kind_def) from IH[OF \<open>n'' = (Main,nx'')\<close> \<open>\<forall>a\<in>set as. intra_kind (kind a)\<close> \<open>nx'' \<noteq> Entry\<close>] have path:"wfp' \<turnstile> (Main, nx'' \<oplus> 1) -as \<oplus>s 1\<rightarrow>* (p', n' \<oplus> 1)" . from \<open>valid_edge wfp a\<close> \<open>sourcenode a = (Main, n)\<close> \<open>targetnode a = n''\<close> \<open>n'' = (Main,nx'')\<close> \<open>n \<noteq> Entry\<close> \<open>intra_kind (kind a)\<close> wf have "if (b) prog else c\<^sub>2,procs \<turnstile> (Main, n \<oplus> 1) -kind a\<rightarrow> (Main, nx'' \<oplus> 1)" by(fastforce intro:PCFG_Main_edge_CondTrue_source_not_Entry simp:valid_edge_def) with path \<open>sourcenode a = (Main, n)\<close> \<open>targetnode a = n''\<close> \<open>n'' = (Main,nx'')\<close> show ?case apply(cases a) apply(clarsimp simp:label_incrs_def) by(auto intro:ProcCFG.Cons_path simp:valid_edge_def) qed subsubsection \<open>From \<open>prog\<close> to \<open>if (b) c\<^sub>1 else prog\<close>\<close> lemma Proc_CFG_edge_CondFalse_source_not_Entry: "\<lbrakk>prog \<turnstile> n -et\<rightarrow>\<^sub>p n'; n \<noteq> Entry\<rbrakk> \<Longrightarrow> if (b) c\<^sub>1 else prog \<turnstile> n \<oplus> (#:c\<^sub>1 + 1) -et\<rightarrow>\<^sub>p n' \<oplus> (#:c\<^sub>1 + 1)" by(induct rule:Proc_CFG.induct)(fastforce intro:Proc_CFG_CondElse Proc_CFG.intros)+ lemma PCFG_Main_edge_CondFalse_source_not_Entry: "\<lbrakk>prog,procs \<turnstile> (Main,n) -et\<rightarrow> (p',n'); n \<noteq> Entry; intra_kind et; well_formed procs\<rbrakk> \<Longrightarrow> if (b) c\<^sub>1 else prog,procs \<turnstile> (Main,n \<oplus> (#:c\<^sub>1 + 1)) -et\<rightarrow> (p',n' \<oplus> (#:c\<^sub>1 + 1))" proof(induct "(Main,n)" et "(p',n')" rule:PCFG.induct) case Main thus ?case by(fastforce dest:Proc_CFG_edge_CondFalse_source_not_Entry intro:PCFG.Main) next case (MainCallReturn p es rets) from \<open>prog \<turnstile> n -CEdge (p, es, rets)\<rightarrow>\<^sub>p n'\<close> \<open>n \<noteq> Entry\<close> have "if (b) c\<^sub>1 else prog \<turnstile> n \<oplus> (#:c\<^sub>1 + 1) -CEdge (p, es, rets)\<rightarrow>\<^sub>p n' \<oplus> (#:c\<^sub>1 + 1)" by(rule Proc_CFG_edge_CondFalse_source_not_Entry) with MainCallReturn show ?case by(fastforce intro:PCFG.MainCallReturn) qed (auto simp:intra_kind_def) lemma path_Main_CondFalse: assumes "Rep_wf_prog wfp = (prog,procs)" and "Rep_wf_prog wfp' = (if (b) c\<^sub>1 else prog,procs)" shows "\<lbrakk>wfp \<turnstile> (Main,n) -as\<rightarrow>* (p',n'); \<forall>a \<in> set as. intra_kind (kind a); n \<noteq> Entry\<rbrakk> \<Longrightarrow> wfp' \<turnstile> (Main,n \<oplus> (#:c\<^sub>1 + 1)) -as \<oplus>s (#:c\<^sub>1 + 1)\<rightarrow>* (p',n' \<oplus> (#:c\<^sub>1 + 1))" proof(induct "(Main,n)" as "(p',n')" arbitrary:n rule:ProcCFG.path.induct) case empty_path from \<open>CFG.valid_node sourcenode targetnode (valid_edge wfp) (Main, n')\<close> \<open>n' \<noteq> Entry\<close> \<open>Rep_wf_prog wfp = (prog,procs)\<close> \<open>Rep_wf_prog wfp' = (if (b) c\<^sub>1 else prog,procs)\<close> have "CFG.valid_node sourcenode targetnode (valid_edge wfp') (Main, n' \<oplus> (#:c\<^sub>1 + 1))" by(fastforce intro:valid_node_Main_CondFalse) with \<open>Main = p'\<close> show ?case by(fastforce intro:ProcCFG.empty_path simp:label_incrs_def) next case (Cons_path n'' as a n) note IH = \<open>\<And>n. \<And>n. \<lbrakk>n'' = (Main, n); \<forall>a\<in>set as. intra_kind (kind a); n \<noteq> Entry\<rbrakk> \<Longrightarrow> wfp' \<turnstile> (Main, n \<oplus> (#:c\<^sub>1 + 1)) -as \<oplus>s (#:c\<^sub>1 + 1)\<rightarrow>* (p', n' \<oplus> (#:c\<^sub>1 + 1))\<close> note [simp] = \<open>Rep_wf_prog wfp = (prog,procs)\<close> \<open>Rep_wf_prog wfp' = (if (b) c\<^sub>1 else prog,procs)\<close> from \<open>Rep_wf_prog wfp = (prog,procs)\<close> have wf:"well_formed procs" by(fastforce intro:wf_wf_prog) from \<open>\<forall>a\<in>set (a # as). intra_kind (kind a)\<close> have "intra_kind (kind a)" and "\<forall>a\<in>set as. intra_kind (kind a)" by simp_all from \<open>valid_edge wfp a\<close> \<open>sourcenode a = (Main, n)\<close> \<open>targetnode a = n''\<close> \<open>intra_kind (kind a)\<close> wf obtain nx'' where "n'' = (Main,nx'')" and "nx'' \<noteq> Entry" by(auto elim!:PCFG.cases simp:valid_edge_def intra_kind_def) from IH[OF \<open>n'' = (Main,nx'')\<close> \<open>\<forall>a\<in>set as. intra_kind (kind a)\<close> \<open>nx'' \<noteq> Entry\<close>] have path:"wfp' \<turnstile> (Main, nx'' \<oplus> (#:c\<^sub>1 + 1)) -as \<oplus>s (#:c\<^sub>1 + 1)\<rightarrow>* (p', n' \<oplus> (#:c\<^sub>1 + 1))" . from \<open>valid_edge wfp a\<close> \<open>sourcenode a = (Main, n)\<close> \<open>targetnode a = n''\<close> \<open>n'' = (Main,nx'')\<close> \<open>n \<noteq> Entry\<close> \<open>intra_kind (kind a)\<close> wf have "if (b) c\<^sub>1 else prog,procs \<turnstile> (Main, n \<oplus> (#:c\<^sub>1 + 1)) -kind a\<rightarrow> (Main, nx'' \<oplus> (#:c\<^sub>1 + 1))" by(fastforce intro:PCFG_Main_edge_CondFalse_source_not_Entry simp:valid_edge_def) with path \<open>sourcenode a = (Main, n)\<close> \<open>targetnode a = n''\<close> \<open>n'' = (Main,nx'')\<close> show ?case apply(cases a) apply(clarsimp simp:label_incrs_def) by(auto intro:ProcCFG.Cons_path simp:valid_edge_def) qed subsubsection \<open>From \<open>prog\<close> to \<open>while (b) prog\<close>\<close> lemma Proc_CFG_edge_WhileBody_source_not_Entry: "\<lbrakk>prog \<turnstile> n -et\<rightarrow>\<^sub>p n'; n \<noteq> Entry; n' \<noteq> Exit\<rbrakk> \<Longrightarrow> while (b) prog \<turnstile> n \<oplus> 2 -et\<rightarrow>\<^sub>p n' \<oplus> 2" by(induct rule:Proc_CFG.induct)(fastforce intro:Proc_CFG_WhileBody Proc_CFG.intros)+ lemma PCFG_Main_edge_WhileBody_source_not_Entry: "\<lbrakk>prog,procs \<turnstile> (Main,n) -et\<rightarrow> (p',n'); n \<noteq> Entry; n' \<noteq> Exit; intra_kind et; well_formed procs\<rbrakk> \<Longrightarrow> while (b) prog,procs \<turnstile> (Main,n \<oplus> 2) -et\<rightarrow> (p',n' \<oplus> 2)" proof(induct "(Main,n)" et "(p',n')" rule:PCFG.induct) case Main thus ?case by(fastforce dest:Proc_CFG_edge_WhileBody_source_not_Entry intro:PCFG.Main) next case (MainCallReturn p es rets) from \<open>prog \<turnstile> n -CEdge (p, es, rets)\<rightarrow>\<^sub>p n'\<close> \<open>n \<noteq> Entry\<close> \<open>n' \<noteq> Exit\<close> have "while (b) prog \<turnstile> n \<oplus> 2 -CEdge (p, es, rets)\<rightarrow>\<^sub>p n' \<oplus> 2" by(rule Proc_CFG_edge_WhileBody_source_not_Entry) with MainCallReturn show ?case by(fastforce intro:PCFG.MainCallReturn) qed (auto simp:intra_kind_def) lemma valid_node_Main_WhileBody: assumes "CFG.valid_node sourcenode targetnode (valid_edge wfp) (Main,n)" and "n \<noteq> Entry" and "Rep_wf_prog wfp = (prog,procs)" and "Rep_wf_prog wfp' = (while (b) prog,procs)" shows "CFG.valid_node sourcenode targetnode (valid_edge wfp') (Main, n \<oplus> 2)" proof - note [simp] = \<open>Rep_wf_prog wfp = (prog,procs)\<close> \<open>Rep_wf_prog wfp' = (while (b) prog,procs)\<close> from \<open>Rep_wf_prog wfp = (prog,procs)\<close> have wf:"well_formed procs" by(fastforce intro:wf_wf_prog) from \<open>CFG.valid_node sourcenode targetnode (valid_edge wfp) (Main,n)\<close> obtain a where "prog,procs \<turnstile> sourcenode a -kind a\<rightarrow> targetnode a" and "(Main,n) = sourcenode a \<or> (Main,n) = targetnode a" by(fastforce simp:ProcCFG.valid_node_def valid_edge_def) from this \<open>n \<noteq> Entry\<close> wf show ?thesis proof(induct "sourcenode a" "kind a" "targetnode a" rule:PCFG.induct) case (Main nx nx') from \<open>(Main,n) = sourcenode a \<or> (Main,n) = targetnode a\<close> show ?case proof assume "(Main,n) = sourcenode a" with \<open>(Main, nx) = sourcenode a\<close>[THEN sym] have [simp]:"nx = n" by simp show ?thesis proof(cases "nx' = Exit") case True with \<open>n \<noteq> Entry\<close> \<open>prog \<turnstile> nx -IEdge (kind a)\<rightarrow>\<^sub>p nx'\<close> have "while (b) prog \<turnstile> n \<oplus> 2 -IEdge (kind a)\<rightarrow>\<^sub>p Label 0" by(fastforce intro:Proc_CFG_WhileBodyExit) hence "while (b) prog,procs \<turnstile> (Main,n \<oplus> 2) -kind a\<rightarrow> (Main,Label 0)" by(rule PCFG.Main) thus ?thesis by(simp add:ProcCFG.valid_node_def)(fastforce simp:valid_edge_def) next case False with \<open>n \<noteq> Entry\<close> \<open>prog \<turnstile> nx -IEdge (kind a)\<rightarrow>\<^sub>p nx'\<close> have "while (b) prog \<turnstile> n \<oplus> 2 -IEdge (kind a)\<rightarrow>\<^sub>p nx' \<oplus> 2" by(fastforce intro:Proc_CFG_edge_WhileBody_source_not_Entry) hence "while (b) prog,procs \<turnstile> (Main,n \<oplus> 2) -kind a\<rightarrow> (Main,nx' \<oplus> 2)" by(rule PCFG.Main) thus ?thesis by(simp add:ProcCFG.valid_node_def)(fastforce simp:valid_edge_def) qed next assume "(Main, n) = targetnode a" show ?thesis proof(cases "nx = Entry") case True with \<open>prog \<turnstile> nx -IEdge (kind a)\<rightarrow>\<^sub>p nx'\<close> have "nx' = Exit \<or> nx' = Label 0" by(fastforce dest:Proc_CFG_EntryD) thus ?thesis proof assume "nx' = Exit" with \<open>(Main, n) = targetnode a\<close> \<open>(Main, nx') = targetnode a\<close>[THEN sym] show ?thesis by simp next assume "nx' = Label 0" have "while (b) prog \<turnstile> Label 0 -IEdge (\<lambda>cf. state_check cf b (Some true))\<^sub>\<surd>\<rightarrow>\<^sub>p Label 2" by(rule Proc_CFG_WhileTrue) hence "while (b) prog,procs \<turnstile> (Main,Label 0) -(\<lambda>cf. state_check cf b (Some true))\<^sub>\<surd>\<rightarrow> (Main,Label 2)" by(fastforce intro:PCFG.Main) with \<open>(Main, n) = targetnode a\<close> \<open>(Main, nx') = targetnode a\<close>[THEN sym] \<open>nx' = Label 0\<close> show ?thesis by(simp add:ProcCFG.valid_node_def)(fastforce simp:valid_edge_def) qed next case False show ?thesis proof(cases "nx' = Exit") case True with \<open>(Main, n) = targetnode a\<close> \<open>(Main, nx') = targetnode a\<close>[THEN sym] show ?thesis by simp next case False with \<open>prog \<turnstile> nx -IEdge (kind a)\<rightarrow>\<^sub>p nx'\<close> \<open>nx \<noteq> Entry\<close> have "while (b) prog \<turnstile> nx \<oplus> 2 -IEdge (kind a)\<rightarrow>\<^sub>p nx' \<oplus> 2" by(fastforce intro:Proc_CFG_edge_WhileBody_source_not_Entry) hence "while (b) prog,procs \<turnstile> (Main,nx \<oplus> 2) -kind a\<rightarrow> (Main,nx' \<oplus> 2)" by(rule PCFG.Main) with \<open>(Main, n) = targetnode a\<close> \<open>(Main, nx') = targetnode a\<close>[THEN sym] show ?thesis by(simp add:ProcCFG.valid_node_def)(fastforce simp:valid_edge_def) qed qed qed next case (Proc p ins outs c nx n' ps) from \<open>(p, nx) = sourcenode a\<close>[THEN sym] \<open>(p, n') = targetnode a\<close>[THEN sym] \<open>(Main, n) = sourcenode a \<or> (Main, n) = targetnode a\<close> \<open>(p, ins, outs, c) \<in> set procs\<close> \<open>well_formed procs\<close> have False by fastforce thus ?case by simp next case (MainCall l p es rets n' ins outs c) from \<open>(p, ins, outs, c) \<in> set procs\<close> \<open>(p, Entry) = targetnode a\<close>[THEN sym] \<open>(Main, Label l) = sourcenode a\<close>[THEN sym] wf \<open>(Main, n) = sourcenode a \<or> (Main, n) = targetnode a\<close> have [simp]:"n = Label l" by fastforce from \<open>prog \<turnstile> Label l -CEdge (p, es, rets)\<rightarrow>\<^sub>p n'\<close> have "n' \<noteq> Exit" by(fastforce dest:Proc_CFG_Call_Labels) with \<open>prog \<turnstile> Label l -CEdge (p, es, rets)\<rightarrow>\<^sub>p n'\<close> have "while (b) prog \<turnstile> Label l \<oplus> 2 -CEdge (p, es, rets)\<rightarrow>\<^sub>p n' \<oplus> 2" by -(rule Proc_CFG_edge_WhileBody_source_not_Entry,auto) with \<open>(p, ins, outs, c) \<in> set procs\<close> have "while (b) prog,procs \<turnstile> (Main,Label l \<oplus> 2) -(\<lambda>s. True):(Main,n' \<oplus> 2)\<hookrightarrow>\<^bsub>p\<^esub>map (\<lambda>e cf. interpret e cf) es\<rightarrow> (p,Entry)" by(fastforce intro:PCFG.MainCall) thus ?case by(simp add:ProcCFG.valid_node_def)(fastforce simp:valid_edge_def) next case (ProcCall p ins outs c l p' es' rets' l' ins' outs' c') from \<open>(p, Label l) = sourcenode a\<close>[THEN sym] \<open>(p', Entry) = targetnode a\<close>[THEN sym] \<open>well_formed procs\<close> \<open>(p, ins, outs, c) \<in> set procs\<close> \<open>(p', ins', outs', c') \<in> set procs\<close> \<open>(Main, n) = sourcenode a \<or> (Main, n) = targetnode a\<close> have False by fastforce thus ?case by simp next case (MainReturn l p es rets l' ins outs c) from \<open>(p, ins, outs, c) \<in> set procs\<close> \<open>(p, Exit) = sourcenode a\<close>[THEN sym] \<open>(Main, Label l') = targetnode a\<close>[THEN sym] wf \<open>(Main, n) = sourcenode a \<or> (Main, n) = targetnode a\<close> have [simp]:"n = Label l'" by fastforce from \<open>prog \<turnstile> Label l -CEdge (p, es, rets)\<rightarrow>\<^sub>p Label l'\<close> have "while (b) prog \<turnstile> Label l \<oplus> 2 -CEdge (p, es, rets)\<rightarrow>\<^sub>p Label l' \<oplus> 2" by -(rule Proc_CFG_edge_WhileBody_source_not_Entry,auto) with \<open>(p, ins, outs, c) \<in> set procs\<close> have "while (b) prog,procs \<turnstile> (p,Exit) -(\<lambda>cf. snd cf = (Main,Label l' \<oplus> 2))\<hookleftarrow>\<^bsub>p\<^esub> (\<lambda>cf cf'. cf'(rets [:=] map cf outs))\<rightarrow> (Main,Label l' \<oplus> 2)" by(fastforce intro:PCFG.MainReturn) thus ?case by(simp add:ProcCFG.valid_node_def)(fastforce simp:valid_edge_def) next case (ProcReturn p ins outs c l p' es' rets' l' ins' outs' c' ps) from \<open>(p', Exit) = sourcenode a\<close>[THEN sym] \<open>(p, Label l') = targetnode a\<close>[THEN sym] \<open>well_formed procs\<close> \<open>(p, ins, outs, c) \<in> set procs\<close> \<open>(p', ins', outs', c') \<in> set procs\<close> \<open>(Main, n) = sourcenode a \<or> (Main, n) = targetnode a\<close> have False by fastforce thus ?case by simp next case (MainCallReturn nx p es rets nx') from \<open>(Main,n) = sourcenode a \<or> (Main,n) = targetnode a\<close> show ?case proof assume "(Main,n) = sourcenode a" with \<open>(Main, nx) = sourcenode a\<close>[THEN sym] have [simp]:"nx = n" by simp from \<open>prog \<turnstile> nx -CEdge (p, es, rets)\<rightarrow>\<^sub>p nx'\<close> have "nx' \<noteq> Exit" by(fastforce dest:Proc_CFG_Call_Labels) with \<open>n \<noteq> Entry\<close> \<open>prog \<turnstile> nx -CEdge (p, es, rets)\<rightarrow>\<^sub>p nx'\<close> have "while (b) prog \<turnstile> n \<oplus> 2 -CEdge (p, es, rets)\<rightarrow>\<^sub>p nx' \<oplus> 2" by(fastforce intro:Proc_CFG_edge_WhileBody_source_not_Entry) hence "while (b) prog,procs \<turnstile> (Main,n \<oplus> 2) -(\<lambda>s. False)\<^sub>\<surd>\<rightarrow> (Main,nx' \<oplus> 2)" by -(rule PCFG.MainCallReturn) thus ?thesis by(simp add:ProcCFG.valid_node_def)(fastforce simp:valid_edge_def) next assume "(Main, n) = targetnode a" from \<open>prog \<turnstile> nx -CEdge (p, es, rets)\<rightarrow>\<^sub>p nx'\<close> have "nx \<noteq> Entry" and "nx' \<noteq> Exit" by(auto dest:Proc_CFG_Call_Labels) with \<open>prog \<turnstile> nx -CEdge (p, es, rets)\<rightarrow>\<^sub>p nx'\<close> have "while (b) prog \<turnstile> nx \<oplus> 2 -CEdge (p, es, rets)\<rightarrow>\<^sub>p nx' \<oplus> 2" by(fastforce intro:Proc_CFG_edge_WhileBody_source_not_Entry) hence "while (b) prog,procs \<turnstile> (Main,nx \<oplus> 2) -(\<lambda>s. False)\<^sub>\<surd>\<rightarrow> (Main,nx' \<oplus> 2)" by -(rule PCFG.MainCallReturn) with \<open>(Main, n) = targetnode a\<close> \<open>(Main, nx') = targetnode a\<close>[THEN sym] show ?thesis by(simp add:ProcCFG.valid_node_def)(fastforce simp:valid_edge_def) qed next case (ProcCallReturn p ins outs c nx p' es' rets' n' ps) from \<open>(p, nx) = sourcenode a\<close>[THEN sym] \<open>(p, n') = targetnode a\<close>[THEN sym] \<open>(p, ins, outs, c) \<in> set procs\<close> \<open>well_formed procs\<close> \<open>(Main, n) = sourcenode a \<or> (Main, n) = targetnode a\<close> have False by fastforce thus ?case by simp qed qed lemma path_Main_WhileBody: assumes "Rep_wf_prog wfp = (prog,procs)" and "Rep_wf_prog wfp' = (while (b) prog,procs)" shows "\<lbrakk>wfp \<turnstile> (Main,n) -as\<rightarrow>* (p',n'); \<forall>a \<in> set as. intra_kind (kind a); n \<noteq> Entry; n' \<noteq> Exit\<rbrakk> \<Longrightarrow> wfp' \<turnstile> (Main,n \<oplus> 2) -as \<oplus>s 2\<rightarrow>* (p',n' \<oplus> 2)" proof(induct "(Main,n)" as "(p',n')" arbitrary:n rule:ProcCFG.path.induct) case empty_path from \<open>CFG.valid_node sourcenode targetnode (valid_edge wfp) (Main, n')\<close> \<open>n' \<noteq> Entry\<close> \<open>Rep_wf_prog wfp = (prog,procs)\<close> \<open>Rep_wf_prog wfp' = (while (b) prog,procs)\<close> have "CFG.valid_node sourcenode targetnode (valid_edge wfp') (Main, n' \<oplus> 2)" by(fastforce intro:valid_node_Main_WhileBody) with \<open>Main = p'\<close> show ?case by(fastforce intro:ProcCFG.empty_path simp:label_incrs_def) next case (Cons_path n'' as a n) note IH = \<open>\<And>n. \<lbrakk>n'' = (Main, n); \<forall>a\<in>set as. intra_kind (kind a); n \<noteq> Entry; n' \<noteq> Exit\<rbrakk> \<Longrightarrow> wfp' \<turnstile> (Main, n \<oplus> 2) -as \<oplus>s 2\<rightarrow>* (p', n' \<oplus> 2)\<close> note [simp] = \<open>Rep_wf_prog wfp = (prog,procs)\<close> \<open>Rep_wf_prog wfp' = (while (b) prog,procs)\<close> from \<open>Rep_wf_prog wfp = (prog,procs)\<close> have wf:"well_formed procs" by(fastforce intro:wf_wf_prog) from \<open>\<forall>a\<in>set (a # as). intra_kind (kind a)\<close> have "intra_kind (kind a)" and "\<forall>a\<in>set as. intra_kind (kind a)" by simp_all from \<open>valid_edge wfp a\<close> \<open>sourcenode a = (Main, n)\<close> \<open>targetnode a = n''\<close> \<open>intra_kind (kind a)\<close> wf obtain nx'' where "n'' = (Main,nx'')" and "nx'' \<noteq> Entry" by(auto elim!:PCFG.cases simp:valid_edge_def intra_kind_def) from IH[OF \<open>n'' = (Main,nx'')\<close> \<open>\<forall>a\<in>set as. intra_kind (kind a)\<close> \<open>nx'' \<noteq> Entry\<close> \<open>n' \<noteq> Exit\<close>] have path:"wfp' \<turnstile> (Main, nx'' \<oplus> 2) -as \<oplus>s 2\<rightarrow>* (p', n' \<oplus> 2)" . with \<open>n' \<noteq> Exit\<close> have "nx'' \<noteq> Exit" by(fastforce dest:ProcCFGExit.path_Exit_source) with \<open>valid_edge wfp a\<close> \<open>sourcenode a = (Main, n)\<close> \<open>targetnode a = n''\<close> \<open>n'' = (Main,nx'')\<close> \<open>n \<noteq> Entry\<close> \<open>intra_kind (kind a)\<close> wf have "while (b) prog,procs \<turnstile> (Main, n \<oplus> 2) -kind a\<rightarrow> (Main, nx'' \<oplus> 2)" by(fastforce intro:PCFG_Main_edge_WhileBody_source_not_Entry simp:valid_edge_def) with path \<open>sourcenode a = (Main, n)\<close> \<open>targetnode a = n''\<close> \<open>n'' = (Main,nx'')\<close> show ?case apply(cases a) apply(clarsimp simp:label_incrs_def) by(auto intro:ProcCFG.Cons_path simp:valid_edge_def) qed subsubsection \<open>Existence of intraprodecural paths\<close> lemma Label_Proc_CFG_Entry_Exit_path_Main: assumes "Rep_wf_prog wfp = (prog,procs)" and "l < #:prog" obtains as as' where "wfp \<turnstile> (Main,Label l) -as\<rightarrow>* (Main,Exit)" and "\<forall>a \<in> set as. intra_kind (kind a)" and "wfp \<turnstile> (Main,Entry) -as'\<rightarrow>* (Main,Label l)" and "\<forall>a \<in> set as'. intra_kind (kind a)" proof(atomize_elim) from \<open>Rep_wf_prog wfp = (prog,procs)\<close> have wf:"well_formed procs" by(fastforce intro:wf_wf_prog) from \<open>l < #:prog\<close> \<open>Rep_wf_prog wfp = (prog,procs)\<close> show "\<exists>as as'. wfp \<turnstile> (Main, Label l) -as\<rightarrow>* (Main, Exit) \<and> (\<forall>a\<in>set as. intra_kind (kind a)) \<and> wfp \<turnstile> (Main, Entry) -as'\<rightarrow>* (Main, Label l) \<and> (\<forall>a\<in>set as'. intra_kind (kind a))" proof(induct prog arbitrary:l wfp) case Skip note [simp] = \<open>Rep_wf_prog wfp = (Skip, procs)\<close> from \<open>l < #:Skip\<close> have [simp]:"l = 0" by simp have "wfp \<turnstile> (Main,Entry) -[((Main,Entry),(\<lambda>s. True)\<^sub>\<surd>,(Main,Label 0))]\<rightarrow>* (Main,Label 0)" by(fastforce intro:ProcCFG.path.intros Main Proc_CFG_Entry simp:valid_edge_def ProcCFG.valid_node_def) moreover have "wfp \<turnstile> (Main,Label l) -[((Main,Label l),\<Up>id,(Main,Exit))]\<rightarrow>* (Main,Exit)" by(fastforce intro:ProcCFG.path.intros Main Proc_CFG_Skip simp:valid_edge_def) ultimately show ?case by(fastforce simp:intra_kind_def) next case (LAss V e) note [simp] = \<open>Rep_wf_prog wfp = (V:=e, procs)\<close> from \<open>l < #:V:=e\<close> have "l = 0 \<or> l = 1" by auto thus ?case proof assume [simp]:"l = 0" have "wfp \<turnstile> (Main,Entry) -[((Main,Entry),(\<lambda>s. True)\<^sub>\<surd>,(Main,Label 0))]\<rightarrow>* (Main,Label 0)" by(fastforce intro:ProcCFG.path.intros Main Proc_CFG_Entry simp:valid_edge_def ProcCFG.valid_node_def) moreover have "wfp \<turnstile> (Main,Label 0) -((Main,Label 0),\<Up>(\<lambda>cf. update cf V e),(Main,Label 1))# [((Main,Label 1),\<Up>id,(Main,Exit))]\<rightarrow>* (Main,Exit)" by(fastforce intro:ProcCFG.Cons_path ProcCFG.path.intros Main Proc_CFG_LAss Proc_CFG_LAssSkip simp:valid_edge_def ProcCFG.valid_node_def) ultimately show ?thesis by(fastforce simp:intra_kind_def) next assume [simp]:"l = 1" have "wfp \<turnstile> (Main,Entry) -((Main,Entry),(\<lambda>s. True)\<^sub>\<surd>,(Main,Label 0))# [((Main,Label 0),\<Up>(\<lambda>cf. update cf V e),(Main,Label 1))]\<rightarrow>* (Main,Label 1)" by(fastforce intro:ProcCFG.path.intros Main Proc_CFG_LAss ProcCFG.Cons_path Main Proc_CFG_Entry simp:ProcCFG.valid_node_def valid_edge_def) moreover have "wfp \<turnstile> (Main,Label 1) -[((Main,Label 1),\<Up>id,(Main,Exit))]\<rightarrow>* (Main,Exit)" by(fastforce intro:ProcCFG.path.intros Main Proc_CFG_LAssSkip simp:valid_edge_def ProcCFG.valid_node_def) ultimately show ?thesis by(fastforce simp:intra_kind_def) qed next case (Seq c\<^sub>1 c\<^sub>2) note IH1 = \<open>\<And>l wfp. \<lbrakk>l < #:c\<^sub>1; Rep_wf_prog wfp = (c\<^sub>1, procs)\<rbrakk> \<Longrightarrow> \<exists>as as'. wfp \<turnstile> (Main, Label l) -as\<rightarrow>* (Main, Exit) \<and> (\<forall>a\<in>set as. intra_kind (kind a)) \<and> wfp \<turnstile> (Main, Entry) -as'\<rightarrow>* (Main, Label l) \<and> (\<forall>a\<in>set as'. intra_kind (kind a))\<close> note IH2 = \<open>\<And>l wfp. \<lbrakk>l < #:c\<^sub>2; Rep_wf_prog wfp = (c\<^sub>2, procs)\<rbrakk> \<Longrightarrow> \<exists>as as'. wfp \<turnstile> (Main, Label l) -as\<rightarrow>* (Main, Exit) \<and> (\<forall>a\<in>set as. intra_kind (kind a)) \<and> wfp \<turnstile> (Main, Entry) -as'\<rightarrow>* (Main, Label l) \<and> (\<forall>a\<in>set as'. intra_kind (kind a))\<close> note [simp] = \<open>Rep_wf_prog wfp = (c\<^sub>1;; c\<^sub>2, procs)\<close> show ?case proof(cases "l < #:c\<^sub>1") case True from \<open>Rep_wf_prog wfp = (c\<^sub>1;; c\<^sub>2, procs)\<close> obtain wfp' where [simp]:"Rep_wf_prog wfp' = (c\<^sub>1, procs)" by(erule wfp_Seq1) from IH1[OF True this] obtain as as' where path1:"wfp' \<turnstile> (Main, Label l) -as\<rightarrow>* (Main, Exit)" and intra1:"\<forall>a\<in>set as. intra_kind (kind a)" and path2:"wfp' \<turnstile> (Main, Entry) -as'\<rightarrow>* (Main, Label l)" and intra2:"\<forall>a\<in>set as'. intra_kind (kind a)" by blast from path1 have "as \<noteq> []" by(fastforce elim:ProcCFG.path.cases) then obtain ax asx where [simp]:"as = asx@[ax]" by(cases as rule:rev_cases) fastforce+ with path1 have "wfp' \<turnstile> (Main, Label l) -asx\<rightarrow>* sourcenode ax" and "valid_edge wfp' ax" and "targetnode ax = (Main, Exit)" by(auto elim:ProcCFG.path_split_snoc) from \<open>valid_edge wfp' ax\<close> \<open>targetnode ax = (Main, Exit)\<close> obtain nx where "sourcenode ax = (Main,nx)" by(fastforce elim:PCFG.cases simp:valid_edge_def) with \<open>wfp' \<turnstile> (Main, Label l) -asx\<rightarrow>* sourcenode ax\<close> have "nx \<noteq> Entry" by fastforce moreover from \<open>valid_edge wfp' ax\<close> \<open>sourcenode ax = (Main,nx)\<close> have "nx \<noteq> Exit" by(fastforce intro:ProcCFGExit.Exit_source) ultimately obtain lx where [simp]:"nx = Label lx" by(cases nx) auto with \<open>wfp' \<turnstile> (Main, Label l) -asx\<rightarrow>* sourcenode ax\<close> \<open>sourcenode ax = (Main,nx)\<close> intra1 have path3:"wfp \<turnstile> (Main, Label l) -asx\<rightarrow>* (Main, Label lx)" by -(rule path_SeqFirst,auto) from \<open>valid_edge wfp' ax\<close> \<open>targetnode ax = (Main, Exit)\<close> \<open>sourcenode ax = (Main,nx)\<close> wf obtain etx where "c\<^sub>1 \<turnstile> Label lx -etx\<rightarrow>\<^sub>p Exit" by(fastforce elim!:PCFG.cases simp:valid_edge_def) then obtain et where [simp]:"etx = IEdge et" by(cases etx)(auto dest:Proc_CFG_Call_Labels) with \<open>c\<^sub>1 \<turnstile> Label lx -etx\<rightarrow>\<^sub>p Exit\<close> have "intra_kind et" by(fastforce intro:Proc_CFG_IEdge_intra_kind) from \<open>c\<^sub>1 \<turnstile> Label lx -etx\<rightarrow>\<^sub>p Exit\<close> path3 have path4:"wfp \<turnstile> (Main, Label l) -asx@ [((Main, Label lx),et,(Main,Label 0 \<oplus> #:c\<^sub>1))] \<rightarrow>* (Main,Label 0 \<oplus> #:c\<^sub>1)" by(fastforce intro:ProcCFG.path_Append ProcCFG.path.intros Proc_CFG_SeqConnect Main simp:ProcCFG.valid_node_def valid_edge_def) from \<open>Rep_wf_prog wfp = (c\<^sub>1;; c\<^sub>2, procs)\<close> obtain wfp'' where [simp]:"Rep_wf_prog wfp'' = (c\<^sub>2, procs)" by(erule wfp_Seq2) from IH2[OF _ this,of "0"] obtain asx' where "wfp'' \<turnstile> (Main, Label 0) -asx'\<rightarrow>* (Main, Exit)" and "\<forall>a\<in>set asx'. intra_kind (kind a)" by blast with path4 intra1 \<open>intra_kind et\<close> have "wfp \<turnstile> (Main, Label l) -(asx@[((Main, Label lx),et,(Main,Label 0 \<oplus> #:c\<^sub>1))])@(asx' \<oplus>s #:c\<^sub>1)\<rightarrow>* (Main, Exit \<oplus> #:c\<^sub>1)" by -(erule ProcCFG.path_Append,rule path_Main_SeqSecond,auto) moreover from intra1 \<open>intra_kind et\<close> \<open>\<forall>a\<in>set asx'. intra_kind (kind a)\<close> have "\<forall>a \<in> set ((asx@[((Main, Label lx),et,(Main,Label #:c\<^sub>1))])@(asx' \<oplus>s #:c\<^sub>1)). intra_kind (kind a)" by(auto simp:label_incrs_def) moreover from path2 intra2 have "wfp \<turnstile> (Main, Entry) -as'\<rightarrow>* (Main, Label l)" by -(rule path_SeqFirst,auto) ultimately show ?thesis using \<open>\<forall>a\<in>set as'. intra_kind (kind a)\<close> by fastforce next case False hence "#:c\<^sub>1 \<le> l" by simp then obtain l' where [simp]:"l = l' + #:c\<^sub>1" and "l' = l - #:c\<^sub>1" by simp from \<open>l < #:c\<^sub>1;; c\<^sub>2\<close> have "l' < #:c\<^sub>2" by simp from \<open>Rep_wf_prog wfp = (c\<^sub>1;; c\<^sub>2, procs)\<close> obtain wfp' where [simp]:"Rep_wf_prog wfp' = (c\<^sub>2, procs)" by(erule wfp_Seq2) from IH2[OF \<open>l' < #:c\<^sub>2\<close> this] obtain as as' where path1:"wfp' \<turnstile> (Main, Label l') -as\<rightarrow>* (Main, Exit)" and intra1:"\<forall>a\<in>set as. intra_kind (kind a)" and path2:"wfp' \<turnstile> (Main, Entry) -as'\<rightarrow>* (Main, Label l')" and intra2:"\<forall>a\<in>set as'. intra_kind (kind a)" by blast from path1 intra1 have "wfp \<turnstile> (Main, Label l' \<oplus> #:c\<^sub>1) -as \<oplus>s #:c\<^sub>1\<rightarrow>* (Main, Exit \<oplus> #:c\<^sub>1)" by -(rule path_Main_SeqSecond,auto) moreover from path2 have "as' \<noteq> []" by(fastforce elim:ProcCFG.path.cases) with path2 obtain ax' asx' where [simp]:"as' = ax'#asx'" and "sourcenode ax' = (Main, Entry)" and "valid_edge wfp' ax'" and "wfp' \<turnstile> targetnode ax' -asx'\<rightarrow>* (Main, Label l')" by -(erule ProcCFG.path_split_Cons,fastforce+) from \<open>wfp' \<turnstile> targetnode ax' -asx'\<rightarrow>* (Main, Label l')\<close> have "targetnode ax' \<noteq> (Main,Exit)" by fastforce with \<open>valid_edge wfp' ax'\<close> \<open>sourcenode ax' = (Main, Entry)\<close> wf have "targetnode ax' = (Main,Label 0)" by(fastforce elim:PCFG.cases dest:Proc_CFG_EntryD simp:valid_edge_def) with \<open>wfp' \<turnstile> targetnode ax' -asx'\<rightarrow>* (Main, Label l')\<close> intra2 have path3:"wfp \<turnstile> (Main,Label 0 \<oplus> #:c\<^sub>1) -asx' \<oplus>s #:c\<^sub>1\<rightarrow>* (Main, Label l' \<oplus> #:c\<^sub>1)" by -(rule path_Main_SeqSecond,auto) from \<open>Rep_wf_prog wfp = (c\<^sub>1;; c\<^sub>2, procs)\<close> obtain wfp'' where [simp]:"Rep_wf_prog wfp'' = (c\<^sub>1, procs)" by(erule wfp_Seq1) from IH1[OF _ this,of "0"] obtain xs where "wfp'' \<turnstile> (Main, Label 0) -xs\<rightarrow>* (Main, Exit)" and "\<forall>a\<in>set xs. intra_kind (kind a)" by blast from \<open>wfp'' \<turnstile> (Main, Label 0) -xs\<rightarrow>* (Main, Exit)\<close> have "xs \<noteq> []" by(fastforce elim:ProcCFG.path.cases) then obtain x xs' where [simp]:"xs = xs'@[x]" by(cases xs rule:rev_cases) fastforce+ with \<open>wfp'' \<turnstile> (Main, Label 0) -xs\<rightarrow>* (Main, Exit)\<close> have "wfp'' \<turnstile> (Main, Label 0) -xs'\<rightarrow>* sourcenode x" and "valid_edge wfp'' x" and "targetnode x = (Main, Exit)" by(auto elim:ProcCFG.path_split_snoc) from \<open>valid_edge wfp'' x\<close> \<open>targetnode x = (Main, Exit)\<close> obtain nx where "sourcenode x = (Main,nx)" by(fastforce elim:PCFG.cases simp:valid_edge_def) with \<open>wfp'' \<turnstile> (Main, Label 0) -xs'\<rightarrow>* sourcenode x\<close> have "nx \<noteq> Entry" by fastforce from \<open>valid_edge wfp'' x\<close> \<open>sourcenode x = (Main,nx)\<close> have "nx \<noteq> Exit" by(fastforce intro:ProcCFGExit.Exit_source) with \<open>nx \<noteq> Entry\<close> obtain lx where [simp]:"nx = Label lx" by(cases nx) auto from \<open>wfp'' \<turnstile> (Main, Label 0) -xs'\<rightarrow>* sourcenode x\<close> \<open>sourcenode x = (Main,nx)\<close> \<open>\<forall>a\<in>set xs. intra_kind (kind a)\<close> have "wfp \<turnstile> (Main, Entry) -((Main, Entry),(\<lambda>s. True)\<^sub>\<surd>,(Main, Label 0))#xs'\<rightarrow>* sourcenode x" apply simp apply(rule path_SeqFirst[OF \<open>Rep_wf_prog wfp'' = (c\<^sub>1, procs)\<close>]) apply(auto intro!:ProcCFG.Cons_path) by(auto intro:Main Proc_CFG_Entry simp:valid_edge_def intra_kind_def) with \<open>valid_edge wfp'' x\<close> \<open>targetnode x = (Main, Exit)\<close> path3 \<open>sourcenode x = (Main,nx)\<close> \<open>nx \<noteq> Entry\<close> \<open>sourcenode x = (Main,nx)\<close> wf have "wfp \<turnstile> (Main, Entry) -((((Main, Entry),(\<lambda>s. True)\<^sub>\<surd>,(Main, Label 0))#xs')@ [(sourcenode x,kind x,(Main,Label #:c\<^sub>1))])@(asx' \<oplus>s #:c\<^sub>1)\<rightarrow>* (Main, Label l' \<oplus> #:c\<^sub>1)" by(fastforce intro:ProcCFG.path_Append ProcCFG.path.intros Main Proc_CFG_SeqConnect elim!:PCFG.cases dest:Proc_CFG_Call_Labels simp:ProcCFG.valid_node_def valid_edge_def) ultimately show ?thesis using intra1 intra2 \<open>\<forall>a\<in>set xs. intra_kind (kind a)\<close> by(fastforce simp:label_incrs_def intra_kind_def) qed next case (Cond b c\<^sub>1 c\<^sub>2) note IH1 = \<open>\<And>l wfp. \<lbrakk>l < #:c\<^sub>1; Rep_wf_prog wfp = (c\<^sub>1, procs)\<rbrakk> \<Longrightarrow> \<exists>as as'. wfp \<turnstile> (Main, Label l) -as\<rightarrow>* (Main, Exit) \<and> (\<forall>a\<in>set as. intra_kind (kind a)) \<and> wfp \<turnstile> (Main, Entry) -as'\<rightarrow>* (Main, Label l) \<and> (\<forall>a\<in>set as'. intra_kind (kind a))\<close> note IH2 = \<open>\<And>l wfp. \<lbrakk>l < #:c\<^sub>2; Rep_wf_prog wfp = (c\<^sub>2, procs)\<rbrakk> \<Longrightarrow> \<exists>as as'. wfp \<turnstile> (Main, Label l) -as\<rightarrow>* (Main, Exit) \<and> (\<forall>a\<in>set as. intra_kind (kind a)) \<and> wfp \<turnstile> (Main, Entry) -as'\<rightarrow>* (Main, Label l) \<and> (\<forall>a\<in>set as'. intra_kind (kind a))\<close> note [simp] = \<open>Rep_wf_prog wfp = (if (b) c\<^sub>1 else c\<^sub>2, procs)\<close> show ?case proof(cases "l = 0") case True from \<open>Rep_wf_prog wfp = (if (b) c\<^sub>1 else c\<^sub>2, procs)\<close> obtain wfp' where [simp]:"Rep_wf_prog wfp' = (c\<^sub>1, procs)" by(erule wfp_CondTrue) from IH1[OF _ this,of 0] obtain as where path:"wfp' \<turnstile> (Main, Label 0) -as\<rightarrow>* (Main, Exit)" and intra:"\<forall>a\<in>set as. intra_kind (kind a)" by blast have "if (b) c\<^sub>1 else c\<^sub>2,procs \<turnstile> (Main,Label 0) -(\<lambda>cf. state_check cf b (Some true))\<^sub>\<surd>\<rightarrow> (Main,Label 0 \<oplus> 1)" by(fastforce intro:Main Proc_CFG_CondTrue) with path intra have "wfp \<turnstile> (Main,Label 0) -[((Main,Label 0),(\<lambda>cf. state_check cf b (Some true))\<^sub>\<surd>,(Main,Label 0 \<oplus> 1))]@ (as \<oplus>s 1)\<rightarrow>* (Main,Exit \<oplus> 1)" apply - apply(rule ProcCFG.path_Append) apply(rule ProcCFG.path.intros)+ prefer 5 apply(rule path_Main_CondTrue) apply(auto intro:ProcCFG.path.intros simp:valid_edge_def) by(fastforce simp:ProcCFG.valid_node_def valid_edge_def) moreover have "if (b) c\<^sub>1 else c\<^sub>2,procs \<turnstile> (Main,Entry) -(\<lambda>s. True)\<^sub>\<surd>\<rightarrow> (Main,Label 0)" by(fastforce intro:Main Proc_CFG_Entry) hence "wfp \<turnstile> (Main,Entry) -[((Main,Entry),(\<lambda>s. True)\<^sub>\<surd>,(Main,Label 0))]\<rightarrow>* (Main,Label 0)" by(fastforce intro:ProcCFG.path.intros simp:ProcCFG.valid_node_def valid_edge_def) ultimately show ?thesis using \<open>l = 0\<close> \<open>\<forall>a\<in>set as. intra_kind (kind a)\<close> by(fastforce simp:label_incrs_def intra_kind_def) next case False hence "0 < l" by simp then obtain l' where [simp]:"l = l' + 1" and "l' = l - 1" by simp show ?thesis proof(cases "l' < #:c\<^sub>1") case True from \<open>Rep_wf_prog wfp = (if (b) c\<^sub>1 else c\<^sub>2, procs)\<close> obtain wfp' where [simp]:"Rep_wf_prog wfp' = (c\<^sub>1, procs)" by(erule wfp_CondTrue) from IH1[OF True this] obtain as as' where path1:"wfp' \<turnstile> (Main, Label l') -as\<rightarrow>* (Main, Exit)" and intra1:"\<forall>a\<in>set as. intra_kind (kind a)" and path2:"wfp' \<turnstile> (Main, Entry) -as'\<rightarrow>* (Main, Label l')" and intra2:"\<forall>a\<in>set as'. intra_kind (kind a)" by blast from path1 intra1 have "wfp \<turnstile> (Main, Label l' \<oplus> 1) -as \<oplus>s 1\<rightarrow>* (Main, Exit \<oplus> 1)" by -(rule path_Main_CondTrue,auto) moreover from path2 obtain ax' asx' where [simp]:"as' = ax'#asx'" and "sourcenode ax' = (Main,Entry)" and "valid_edge wfp' ax'" and "wfp' \<turnstile> targetnode ax' -asx'\<rightarrow>* (Main, Label l')" by -(erule ProcCFG.path.cases,fastforce+) with wf have "targetnode ax' = (Main,Label 0)" by(fastforce elim:PCFG.cases dest:Proc_CFG_EntryD Proc_CFG_Call_Labels simp:valid_edge_def) with \<open>wfp' \<turnstile> targetnode ax' -asx'\<rightarrow>* (Main, Label l')\<close> intra2 have "wfp \<turnstile> (Main,Entry) -((Main,Entry),(\<lambda>s. True)\<^sub>\<surd>,(Main,Label 0))# ((Main,Label 0),(\<lambda>cf. state_check cf b (Some true))\<^sub>\<surd>,(Main,Label 0 \<oplus> 1))# (asx' \<oplus>s 1)\<rightarrow>* (Main,Label l' \<oplus> 1)" apply - apply(rule ProcCFG.path.intros)+ apply(rule path_Main_CondTrue) by(auto intro:Main Proc_CFG_Entry Proc_CFG_CondTrue simp:valid_edge_def) ultimately show ?thesis using intra1 intra2 by(fastforce simp:label_incrs_def intra_kind_def) next case False hence "#:c\<^sub>1 \<le> l'" by simp then obtain l'' where [simp]:"l' = l'' + #:c\<^sub>1" and "l'' = l' - #:c\<^sub>1" by simp from \<open>l < #:(if (b) c\<^sub>1 else c\<^sub>2)\<close> have "l'' < #:c\<^sub>2" by simp from \<open>Rep_wf_prog wfp = (if (b) c\<^sub>1 else c\<^sub>2, procs)\<close> obtain wfp'' where [simp]:"Rep_wf_prog wfp'' = (c\<^sub>2, procs)" by(erule wfp_CondFalse) from IH2[OF \<open>l'' < #:c\<^sub>2\<close> this] obtain as as' where path1:"wfp'' \<turnstile> (Main, Label l'') -as\<rightarrow>* (Main, Exit)" and intra1:"\<forall>a\<in>set as. intra_kind (kind a)" and path2:"wfp'' \<turnstile> (Main, Entry) -as'\<rightarrow>* (Main, Label l'')" and intra2:"\<forall>a\<in>set as'. intra_kind (kind a)" by blast from path1 intra1 have "wfp \<turnstile> (Main, Label l'' \<oplus> (#:c\<^sub>1 + 1)) -as \<oplus>s (#:c\<^sub>1 + 1)\<rightarrow>* (Main, Exit \<oplus> (#:c\<^sub>1 + 1))" by -(rule path_Main_CondFalse,auto simp:add.assoc) moreover from path2 obtain ax' asx' where [simp]:"as' = ax'#asx'" and "sourcenode ax' = (Main,Entry)" and "valid_edge wfp'' ax'" and "wfp'' \<turnstile> targetnode ax' -asx'\<rightarrow>* (Main, Label l'')" by -(erule ProcCFG.path.cases,fastforce+) with wf have "targetnode ax' = (Main,Label 0)" by(fastforce elim:PCFG.cases dest:Proc_CFG_EntryD Proc_CFG_Call_Labels simp:valid_edge_def) with \<open>wfp'' \<turnstile> targetnode ax' -asx'\<rightarrow>* (Main, Label l'')\<close> intra2 have "wfp \<turnstile> (Main,Entry) -((Main,Entry),(\<lambda>s. True)\<^sub>\<surd>,(Main,Label 0))# ((Main,Label 0),(\<lambda>cf. state_check cf b (Some false))\<^sub>\<surd>, (Main,Label (#:c\<^sub>1 + 1)))#(asx' \<oplus>s (#:c\<^sub>1 + 1))\<rightarrow>* (Main,Label l'' \<oplus> (#:c\<^sub>1 + 1))" apply - apply(rule ProcCFG.path.intros)+ apply(rule path_Main_CondFalse) by(auto intro:Main Proc_CFG_Entry Proc_CFG_CondFalse simp:valid_edge_def) ultimately show ?thesis using intra1 intra2 by(fastforce simp:label_incrs_def intra_kind_def add.assoc) qed qed next case (While b c') note IH = \<open>\<And>l wfp. \<lbrakk>l < #:c'; Rep_wf_prog wfp = (c', procs)\<rbrakk> \<Longrightarrow> \<exists>as as'. wfp \<turnstile> (Main, Label l) -as\<rightarrow>* (Main, Exit) \<and> (\<forall>a\<in>set as. intra_kind (kind a)) \<and> wfp \<turnstile> (Main, Entry) -as'\<rightarrow>* (Main, Label l) \<and> (\<forall>a\<in>set as'. intra_kind (kind a))\<close> note [simp] = \<open>Rep_wf_prog wfp = (while (b) c', procs)\<close> show ?case proof(cases "l = 0") case True hence "wfp \<turnstile> (Main,Label l) - ((Main,Label 0),(\<lambda>cf. state_check cf b (Some false))\<^sub>\<surd>,(Main,Label 1))# [((Main,Label 1),\<Up>id,(Main,Exit))]\<rightarrow>* (Main,Exit)" by(fastforce intro:ProcCFG.path.intros Main Proc_CFG_WhileFalseSkip Proc_CFG_WhileFalse simp:valid_edge_def) moreover have "while (b) c' \<turnstile> Entry -IEdge (\<lambda>s. True)\<^sub>\<surd>\<rightarrow>\<^sub>p Label 0" by(rule Proc_CFG_Entry) with \<open>l = 0\<close> have "wfp \<turnstile> (Main,Entry) -[((Main,Entry),(\<lambda>s. True)\<^sub>\<surd>,(Main,Label 0))]\<rightarrow>* (Main,Label l)" by(fastforce intro:ProcCFG.path.intros Main simp:ProcCFG.valid_node_def valid_edge_def) ultimately show ?thesis by(fastforce simp:intra_kind_def) next case False hence "1 \<le> l" by simp thus ?thesis proof(cases "l < 2") case True with \<open>1 \<le> l\<close> have [simp]:"l = 1" by simp have "wfp \<turnstile> (Main,Label l) -[((Main,Label 1),\<Up>id,(Main,Exit))]\<rightarrow>* (Main,Exit)" by(fastforce intro:ProcCFG.path.intros Main Proc_CFG_WhileFalseSkip simp:valid_edge_def) moreover have "while (b) c' \<turnstile> Label 0 -IEdge (\<lambda>cf. state_check cf b (Some false))\<^sub>\<surd>\<rightarrow>\<^sub>p Label 1" by(rule Proc_CFG_WhileFalse) hence "wfp \<turnstile> (Main,Entry) -((Main,Entry),(\<lambda>s. True)\<^sub>\<surd>,(Main,Label 0))# [((Main,Label 0),(\<lambda>cf. state_check cf b (Some false))\<^sub>\<surd>,(Main,Label 1))]\<rightarrow>* (Main,Label l)" by(fastforce intro:ProcCFG.path.intros Main Proc_CFG_Entry simp:ProcCFG.valid_node_def valid_edge_def) ultimately show ?thesis by(fastforce simp:intra_kind_def) next case False with \<open>1 \<le> l\<close> have "2 \<le> l" by simp then obtain l' where [simp]:"l = l' + 2" and "l' = l - 2" by(simp del:add_2_eq_Suc') from \<open>l < #:while (b) c'\<close> have "l' < #:c'" by simp from \<open>Rep_wf_prog wfp = (while (b) c', procs)\<close> obtain wfp' where [simp]:"Rep_wf_prog wfp' = (c', procs)" by(erule wfp_WhileBody) from IH[OF \<open>l' < #:c'\<close> this] obtain as as' where path1:"wfp' \<turnstile> (Main, Label l') -as\<rightarrow>* (Main, Exit)" and intra1:"\<forall>a\<in>set as. intra_kind (kind a)" and path2:"wfp' \<turnstile> (Main, Entry) -as'\<rightarrow>* (Main, Label l')" and intra2:"\<forall>a\<in>set as'. intra_kind (kind a)" by blast from path1 have "as \<noteq> []" by(fastforce elim:ProcCFG.path.cases) with path1 obtain ax asx where [simp]:"as = asx@[ax]" and "wfp' \<turnstile> (Main, Label l') -asx\<rightarrow>* sourcenode ax" and "valid_edge wfp' ax" and "targetnode ax = (Main, Exit)" by -(erule ProcCFG.path_split_snoc,fastforce+) with wf obtain lx etx where "sourcenode ax = (Main,Label lx)" and "intra_kind (kind ax)" apply(auto elim!:PCFG.cases dest:Proc_CFG_Call_Labels simp:valid_edge_def) by(case_tac n)(auto dest:Proc_CFG_IEdge_intra_kind) with \<open>wfp' \<turnstile> (Main, Label l') -asx\<rightarrow>* sourcenode ax\<close> intra1 have "wfp \<turnstile> (Main, Label l' \<oplus> 2) -asx \<oplus>s 2\<rightarrow>* (Main,Label lx \<oplus> 2)" by -(rule path_Main_WhileBody,auto) from \<open>valid_edge wfp' ax\<close> \<open>sourcenode ax = (Main,Label lx)\<close> \<open>targetnode ax = (Main, Exit)\<close> \<open>intra_kind (kind ax)\<close> wf have "while (b) c',procs \<turnstile> (Main,Label lx \<oplus> 2) -kind ax\<rightarrow> (Main,Label 0)" by(fastforce intro!:Main Proc_CFG_WhileBodyExit elim!:PCFG.cases dest:Proc_CFG_Call_Labels simp:valid_edge_def) hence "wfp \<turnstile> (Main,Label lx \<oplus> 2) -((Main,Label lx \<oplus> 2),kind ax,(Main,Label 0))# ((Main,Label 0),(\<lambda>cf. state_check cf b (Some false))\<^sub>\<surd>,(Main,Label 1))# [((Main,Label 1),\<Up>id,(Main,Exit))]\<rightarrow>* (Main,Exit)" by(fastforce intro:ProcCFG.path.intros Main Proc_CFG_WhileFalse Proc_CFG_WhileFalseSkip simp:valid_edge_def) with \<open>wfp \<turnstile> (Main, Label l' \<oplus> 2) -asx \<oplus>s 2\<rightarrow>* (Main,Label lx \<oplus> 2)\<close> have "wfp \<turnstile> (Main, Label l) -(asx \<oplus>s 2)@ (((Main,Label lx \<oplus> 2),kind ax,(Main,Label 0))# ((Main,Label 0),(\<lambda>cf. state_check cf b (Some false))\<^sub>\<surd>,(Main,Label 1))# [((Main,Label 1),\<Up>id,(Main,Exit))])\<rightarrow>* (Main,Exit)" by(fastforce intro:ProcCFG.path_Append) moreover from path2 have "as' \<noteq> []" by(fastforce elim:ProcCFG.path.cases) with path2 obtain ax' asx' where [simp]:"as' = ax'#asx'" and "wfp' \<turnstile> targetnode ax' -asx'\<rightarrow>* (Main,Label l')" and "valid_edge wfp' ax'" and "sourcenode ax' = (Main, Entry)" by -(erule ProcCFG.path_split_Cons,fastforce+) with wf have "targetnode ax' = (Main,Label 0)" and "intra_kind (kind ax')" by(fastforce elim!:PCFG.cases dest:Proc_CFG_Call_Labels Proc_CFG_EntryD simp:intra_kind_def valid_edge_def)+ with \<open>wfp' \<turnstile> targetnode ax' -asx'\<rightarrow>* (Main,Label l')\<close> intra2 have "wfp \<turnstile> (Main, Label 0 \<oplus> 2) -asx' \<oplus>s 2\<rightarrow>* (Main,Label l' \<oplus> 2)" by -(rule path_Main_WhileBody,auto simp del:add_2_eq_Suc') hence "wfp \<turnstile> (Main,Entry) -((Main,Entry),(\<lambda>s. True)\<^sub>\<surd>,(Main,Label 0))# ((Main,Label 0),(\<lambda>cf. state_check cf b (Some true))\<^sub>\<surd>,(Main,Label 2))# (asx' \<oplus>s 2)\<rightarrow>* (Main,Label l)" by(fastforce intro:ProcCFG.path.intros Main Proc_CFG_WhileTrue Proc_CFG_Entry simp:valid_edge_def) ultimately show ?thesis using \<open>intra_kind (kind ax)\<close> intra1 intra2 by(fastforce simp:label_incrs_def intra_kind_def) qed qed next case (Call p es rets) note Rep [simp] = \<open>Rep_wf_prog wfp = (Call p es rets, procs)\<close> have cC:"containsCall procs (Call p es rets) [] p" by simp show ?case proof(cases "l = 0") case True have "wfp \<turnstile> (Main,Label 0) -((Main,Label 0),(\<lambda>s. False)\<^sub>\<surd>,(Main,Label 1))# [((Main,Label 1),\<Up>id,(Main,Exit))]\<rightarrow>* (Main,Exit)" by(fastforce intro:ProcCFG.path.intros Main Proc_CFG_CallSkip MainCallReturn Proc_CFG_Call simp:valid_edge_def) moreover have "Call p es rets,procs \<turnstile> (Main,Entry) -(\<lambda>s. True)\<^sub>\<surd>\<rightarrow> (Main,Label 0)" by(fastforce intro:Main Proc_CFG_Entry) hence "wfp \<turnstile> (Main,Entry) -[((Main,Entry),(\<lambda>s. True)\<^sub>\<surd>,(Main,Label 0))]\<rightarrow>* (Main,Label 0)" by(fastforce intro:ProcCFG.path.intros simp:ProcCFG.valid_node_def valid_edge_def) ultimately show ?thesis using \<open>l = 0\<close> by(fastforce simp:intra_kind_def) next case False with \<open>l < #:Call p es rets\<close> have "l = 1" by simp have "wfp \<turnstile> (Main,Label 1) -[((Main,Label 1),\<Up>id,(Main,Exit))]\<rightarrow>* (Main,Exit)" by(fastforce intro:ProcCFG.path.intros Main Proc_CFG_CallSkip simp:valid_edge_def) moreover have "Call p es rets,procs \<turnstile> (Main,Label 0) -(\<lambda>s. False)\<^sub>\<surd>\<rightarrow> (Main,Label 1)" by(fastforce intro:MainCallReturn Proc_CFG_Call) hence "wfp \<turnstile> (Main,Entry) -((Main,Entry),(\<lambda>s. True)\<^sub>\<surd>,(Main,Label 0))# [((Main,Label 0),(\<lambda>s. False)\<^sub>\<surd>,(Main,Label 1))]\<rightarrow>* (Main,Label 1)" by(fastforce intro:ProcCFG.path.intros Main Proc_CFG_Entry simp:ProcCFG.valid_node_def valid_edge_def) ultimately show ?thesis using \<open>l = 1\<close> by(fastforce simp:intra_kind_def) qed qed qed subsection \<open>Lifting from edges in procedure Main to arbitrary procedures\<close> lemma lift_edge_Main_Main: "\<lbrakk>c,procs \<turnstile> (Main, n) -et\<rightarrow> (Main, n'); (p,ins,outs,c) \<in> set procs; containsCall procs prog ps p; well_formed procs\<rbrakk> \<Longrightarrow> prog,procs \<turnstile> (p, n) -et\<rightarrow> (p, n')" proof(induct "(Main,n)" et "(Main,n')" rule:PCFG.induct) case Main thus ?case by(fastforce intro:Proc) next case MainCallReturn thus ?case by(fastforce intro:ProcCallReturn) qed auto lemma lift_edge_Main_Proc: "\<lbrakk>c,procs \<turnstile> (Main, n) -et\<rightarrow> (q, n'); q \<noteq> Main; (p,ins,outs,c) \<in> set procs; containsCall procs prog ps p; well_formed procs\<rbrakk> \<Longrightarrow> \<exists>et'. prog,procs \<turnstile> (p, n) -et'\<rightarrow> (q, n')" proof(induct "(Main,n)" et "(q,n')" rule:PCFG.induct) case (MainCall l esx retsx n'x insx outsx cx) from \<open>c \<turnstile> Label l -CEdge (q, esx, retsx)\<rightarrow>\<^sub>p n'x\<close> obtain l' where [simp]:"n'x = Label l'" by(fastforce dest:Proc_CFG_Call_Labels) with MainCall have "prog,procs \<turnstile> (p, n) -(\<lambda>s. True):(p,n'x)\<hookrightarrow>\<^bsub>q\<^esub>map (\<lambda>e cf. interpret e cf) esx\<rightarrow> (q, n')" by(fastforce intro:ProcCall) thus ?case by fastforce qed auto lemma lift_edge_Proc_Main: "\<lbrakk>c,procs \<turnstile> (q, n) -et\<rightarrow> (Main, n'); q \<noteq> Main; (p,ins,outs,c) \<in> set procs; containsCall procs prog ps p; well_formed procs\<rbrakk> \<Longrightarrow> \<exists>et'. prog,procs \<turnstile> (q, n) -et'\<rightarrow> (p, n')" proof(induct "(q,n)" et "(Main,n')" rule:PCFG.induct) case (MainReturn l esx retsx l' insx outsx cx) note [simp] = \<open>Exit = n\<close>[THEN sym] \<open>Label l' = n'\<close>[THEN sym] from MainReturn have "prog,procs \<turnstile> (q,Exit) -(\<lambda>cf. snd cf = (p,Label l'))\<hookleftarrow>\<^bsub>q\<^esub> (\<lambda>cf cf'. cf'(retsx [:=] map cf outsx))\<rightarrow> (p,Label l')" by(fastforce intro!:ProcReturn) thus ?case by fastforce qed auto fun lift_edge :: "edge \<Rightarrow> pname \<Rightarrow> edge" where "lift_edge a p = ((p,snd(sourcenode a)),kind a,(p,snd(targetnode a)))" fun lift_path :: "edge list \<Rightarrow> pname \<Rightarrow> edge list" where "lift_path as p = map (\<lambda>a. lift_edge a p) as" lemma lift_path_Proc: assumes "Rep_wf_prog wfp' = (c,procs)" and "Rep_wf_prog wfp = (prog,procs)" and "(p,ins,outs,c) \<in> set procs" and "containsCall procs prog ps p" shows "\<lbrakk>wfp' \<turnstile> (Main,n) -as\<rightarrow>* (Main,n'); \<forall>a \<in> set as. intra_kind (kind a)\<rbrakk> \<Longrightarrow> wfp \<turnstile> (p,n) -lift_path as p\<rightarrow>* (p,n')" proof(induct "(Main,n)" as "(Main,n')" arbitrary:n rule:ProcCFG.path.induct) case empty_path from \<open>Rep_wf_prog wfp = (prog,procs)\<close> have wf:"well_formed procs" by(fastforce intro:wf_wf_prog) from \<open>CFG.valid_node sourcenode targetnode (valid_edge wfp') (Main, n')\<close> assms wf have "CFG.valid_node sourcenode targetnode (valid_edge wfp) (p,n')" apply(auto simp:ProcCFG.valid_node_def valid_edge_def) apply(case_tac "ab = Main") apply(fastforce dest:lift_edge_Main_Main) apply(fastforce dest!:lift_edge_Main_Proc) apply(case_tac "a = Main") apply(fastforce dest:lift_edge_Main_Main) by(fastforce dest!:lift_edge_Proc_Main) thus ?case by(fastforce dest:ProcCFG.empty_path) next case (Cons_path m'' as a n) note IH = \<open>\<And>n. \<lbrakk>m'' = (Main, n); \<forall>a\<in>set as. intra_kind (kind a)\<rbrakk> \<Longrightarrow> wfp \<turnstile> (p, n) -lift_path as p\<rightarrow>* (p, n')\<close> from \<open>Rep_wf_prog wfp = (prog,procs)\<close> have wf:"well_formed procs" by(fastforce intro:wf_wf_prog) from \<open>\<forall>a\<in>set (a # as). intra_kind (kind a)\<close> have "intra_kind (kind a)" and "\<forall>a\<in>set as. intra_kind (kind a)" by simp_all from \<open>valid_edge wfp' a\<close> \<open>intra_kind (kind a)\<close> \<open>sourcenode a = (Main, n)\<close> \<open>targetnode a = m''\<close> \<open>Rep_wf_prog wfp' = (c,procs)\<close> obtain n'' where "m'' = (Main, n'')" by(fastforce elim:PCFG.cases simp:valid_edge_def intra_kind_def) with \<open>valid_edge wfp' a\<close> \<open>Rep_wf_prog wfp' = (c,procs)\<close> \<open>sourcenode a = (Main, n)\<close> \<open>targetnode a = m''\<close> \<open>(p,ins,outs,c) \<in> set procs\<close> \<open>containsCall procs prog ps p\<close> \<open>Rep_wf_prog wfp = (prog,procs)\<close> wf have "prog,procs \<turnstile> (p, n) -kind a\<rightarrow> (p, n'')" by(auto intro:lift_edge_Main_Main simp:valid_edge_def) from IH[OF \<open>m'' = (Main, n'')\<close> \<open>\<forall>a\<in>set as. intra_kind (kind a)\<close>] have "wfp \<turnstile> (p, n'') -lift_path as p\<rightarrow>* (p, n')" . with \<open>prog,procs \<turnstile> (p, n) -kind a\<rightarrow> (p, n'')\<close> \<open>Rep_wf_prog wfp = (prog,procs)\<close> \<open>sourcenode a = (Main, n)\<close> \<open>targetnode a = m''\<close> \<open>m'' = (Main, n'')\<close> show ?case by simp (rule ProcCFG.Cons_path,auto simp:valid_edge_def) qed subsection \<open>Existence of paths from Entry and to Exit\<close> lemma Label_Proc_CFG_Entry_Exit_path_Proc: assumes "Rep_wf_prog wfp = (prog,procs)" and "l < #:c" and "(p,ins,outs,c) \<in> set procs" and "containsCall procs prog ps p" obtains as as' where "wfp \<turnstile> (p,Label l) -as\<rightarrow>* (p,Exit)" and "\<forall>a \<in> set as. intra_kind (kind a)" and "wfp \<turnstile> (p,Entry) -as'\<rightarrow>* (p,Label l)" and "\<forall>a \<in> set as'. intra_kind (kind a)" proof(atomize_elim) from \<open>Rep_wf_prog wfp = (prog,procs)\<close> \<open>(p,ins,outs,c) \<in> set procs\<close> \<open>containsCall procs prog ps p\<close> obtain wfp' where "Rep_wf_prog wfp' = (c,procs)" by(erule wfp_Call) from this \<open>l < #:c\<close> obtain as as' where "wfp' \<turnstile> (Main,Label l) -as\<rightarrow>* (Main,Exit)" and "\<forall>a \<in> set as. intra_kind (kind a)" and "wfp' \<turnstile> (Main,Entry) -as'\<rightarrow>* (Main,Label l)" and "\<forall>a \<in> set as'. intra_kind (kind a)" by(erule Label_Proc_CFG_Entry_Exit_path_Main) from \<open>Rep_wf_prog wfp' = (c,procs)\<close> \<open>Rep_wf_prog wfp = (prog,procs)\<close> \<open>(p,ins,outs,c) \<in> set procs\<close> \<open>containsCall procs prog ps p\<close> \<open>wfp' \<turnstile> (Main,Label l) -as\<rightarrow>* (Main,Exit)\<close> \<open>\<forall>a \<in> set as. intra_kind (kind a)\<close> have "wfp \<turnstile> (p,Label l) -lift_path as p\<rightarrow>* (p,Exit)" by(fastforce intro:lift_path_Proc) moreover from \<open>Rep_wf_prog wfp' = (c,procs)\<close> \<open>Rep_wf_prog wfp = (prog,procs)\<close> \<open>(p,ins,outs,c) \<in> set procs\<close> \<open>containsCall procs prog ps p\<close> \<open>wfp' \<turnstile> (Main,Entry) -as'\<rightarrow>* (Main,Label l)\<close> \<open>\<forall>a \<in> set as'. intra_kind (kind a)\<close> have "wfp \<turnstile> (p,Entry) -lift_path as' p\<rightarrow>* (p,Label l)" by(fastforce intro:lift_path_Proc) moreover from \<open>\<forall>a \<in> set as. intra_kind (kind a)\<close> \<open>\<forall>a \<in> set as'. intra_kind (kind a)\<close> have "\<forall>a \<in> set (lift_path as p). intra_kind (kind a)" and "\<forall>a \<in> set (lift_path as' p). intra_kind (kind a)" by auto ultimately show "\<exists>as as'. wfp \<turnstile> (p, Label l) -as\<rightarrow>* (p, Exit) \<and> (\<forall>a\<in>set as. intra_kind (kind a)) \<and> wfp \<turnstile> (p, Entry) -as'\<rightarrow>* (p, Label l) \<and> (\<forall>a\<in>set as'. intra_kind (kind a))" by fastforce qed lemma Entry_to_Entry_and_Exit_to_Exit: assumes "Rep_wf_prog wfp = (prog,procs)" and "containsCall procs prog ps p" and "(p,ins,outs,c) \<in> set procs" obtains as as' where "CFG.valid_path' sourcenode targetnode kind (valid_edge wfp) (get_return_edges wfp) (Main,Entry) as (p,Entry)" and "CFG.valid_path' sourcenode targetnode kind (valid_edge wfp) (get_return_edges wfp) (p,Exit) as' (Main,Exit)" proof(atomize_elim) from \<open>containsCall procs prog ps p\<close> \<open>(p,ins,outs,c) \<in> set procs\<close> show "\<exists>as as'. CFG.valid_path' sourcenode targetnode kind (valid_edge wfp) (get_return_edges wfp) (Main, Entry) as (p, Entry) \<and> CFG.valid_path' sourcenode targetnode kind (valid_edge wfp) (get_return_edges wfp) (p, Exit) as' (Main, Exit)" proof(induct ps arbitrary:p ins outs c rule:rev_induct) case Nil from \<open>containsCall procs prog [] p\<close> obtain lx es rets lx' where "prog \<turnstile> Label lx -CEdge (p,es,rets)\<rightarrow>\<^sub>p Label lx'" by(erule containsCall_empty_Proc_CFG_Call_edge) with \<open>(p, ins, outs, c) \<in> set procs\<close> have "prog,procs \<turnstile> (Main,Label lx) -(\<lambda>s. True):(Main,Label lx')\<hookrightarrow>\<^bsub>p\<^esub> map (\<lambda>e cf. interpret e cf) es\<rightarrow> (p,Entry)" and "prog,procs \<turnstile> (p,Exit) -(\<lambda>cf. snd cf = (Main,Label lx'))\<hookleftarrow>\<^bsub>p\<^esub> (\<lambda>cf cf'. cf'(rets [:=] map cf outs))\<rightarrow> (Main,Label lx')" by -(rule MainCall,assumption+,rule MainReturn) with \<open>Rep_wf_prog wfp = (prog,procs)\<close> have "wfp \<turnstile> (Main,Label lx) -[((Main,Label lx), (\<lambda>s. True):(Main,Label lx')\<hookrightarrow>\<^bsub>p\<^esub>map (\<lambda>e cf. interpret e cf) es,(p,Entry))]\<rightarrow>* (p,Entry)" and "wfp \<turnstile> (p,Exit) -[((p,Exit),(\<lambda>cf. snd cf = (Main,Label lx'))\<hookleftarrow>\<^bsub>p\<^esub> (\<lambda>cf cf'. cf'(rets [:=] map cf outs)),(Main,Label lx'))]\<rightarrow>* (Main,Label lx')" by(fastforce intro:ProcCFG.path.intros simp:ProcCFG.valid_node_def valid_edge_def)+ moreover from \<open>prog \<turnstile> Label lx -CEdge (p,es,rets)\<rightarrow>\<^sub>p Label lx'\<close> have "lx < #:prog" and "lx' < #:prog" by(auto intro:Proc_CFG_sourcelabel_less_num_nodes Proc_CFG_targetlabel_less_num_nodes) from \<open>Rep_wf_prog wfp = (prog,procs)\<close> \<open>lx < #:prog\<close> obtain as where "wfp \<turnstile> (Main,Entry) -as\<rightarrow>* (Main,Label lx)" and "\<forall>a \<in> set as. intra_kind (kind a)" by -(erule Label_Proc_CFG_Entry_Exit_path_Main) moreover from \<open>Rep_wf_prog wfp = (prog,procs)\<close> \<open>lx' < #:prog\<close> obtain as' where "wfp \<turnstile> (Main,Label lx') -as'\<rightarrow>* (Main,Exit)" and "\<forall>a \<in> set as'. intra_kind (kind a)" by -(erule Label_Proc_CFG_Entry_Exit_path_Main) moreover from \<open>\<forall>a \<in> set as. intra_kind (kind a)\<close> have "CFG.valid_path kind (get_return_edges wfp) (as@[((Main,Label lx),(\<lambda>s. True):(Main,Label lx')\<hookrightarrow>\<^bsub>p\<^esub> map (\<lambda>e cf. interpret e cf) es,(p,Entry))])" by(fastforce intro:ProcCFG.same_level_path_valid_path_Append ProcCFG.intras_same_level_path simp:ProcCFG.valid_path_def) moreover from \<open>\<forall>a \<in> set as'. intra_kind (kind a)\<close> have "CFG.valid_path kind (get_return_edges wfp) ([((p,Exit),(\<lambda>cf. snd cf = (Main,Label lx'))\<hookleftarrow>\<^bsub>p\<^esub> (\<lambda>cf cf'. cf'(rets [:=] map cf outs)),(Main,Label lx'))]@as')" by(fastforce intro:ProcCFG.valid_path_same_level_path_Append ProcCFG.intras_same_level_path simp:ProcCFG.valid_path_def) ultimately show ?case by(fastforce intro:ProcCFG.path_Append simp:ProcCFG.vp_def) next case (snoc p' ps') note IH = \<open>\<And>p ins outs c. \<lbrakk>containsCall procs prog ps' p; (p,ins,outs,c) \<in> set procs\<rbrakk> \<Longrightarrow> \<exists>as as'. CFG.valid_path' sourcenode targetnode kind (valid_edge wfp) (get_return_edges wfp) (Main, Entry) as (p, Entry) \<and> CFG.valid_path' sourcenode targetnode kind (valid_edge wfp) (get_return_edges wfp) (p, Exit) as' (Main, Exit)\<close> from \<open>containsCall procs prog (ps' @ [p']) p\<close> obtain ins' outs' c' where "(p',ins',outs',c') \<in> set procs" and "containsCall procs c' [] p" and "containsCall procs prog ps' p'" by(auto elim:containsCallE) from IH[OF \<open>containsCall procs prog ps' p'\<close> \<open>(p',ins',outs',c') \<in> set procs\<close>] obtain as as' where pathE:"CFG.valid_path' sourcenode targetnode kind (valid_edge wfp) (get_return_edges wfp) (Main, Entry) as (p', Entry)" and pathX:"CFG.valid_path' sourcenode targetnode kind (valid_edge wfp) (get_return_edges wfp) (p', Exit) as' (Main, Exit)" by blast from \<open>containsCall procs c' [] p\<close> obtain lx es rets lx' where edge:"c' \<turnstile> Label lx -CEdge (p,es,rets)\<rightarrow>\<^sub>p Label lx'" by(erule containsCall_empty_Proc_CFG_Call_edge) hence "lx < #:c'" and "lx' < #:c'" by(auto intro:Proc_CFG_sourcelabel_less_num_nodes Proc_CFG_targetlabel_less_num_nodes) from \<open>lx < #:c'\<close> \<open>Rep_wf_prog wfp = (prog,procs)\<close> \<open>(p',ins',outs',c') \<in> set procs\<close> \<open>containsCall procs prog ps' p'\<close> obtain asx where "wfp \<turnstile> (p',Entry) -asx\<rightarrow>* (p',Label lx)" and "\<forall>a \<in> set asx. intra_kind (kind a)" by(fastforce elim:Label_Proc_CFG_Entry_Exit_path_Proc) with pathE have pathE2:"CFG.valid_path' sourcenode targetnode kind (valid_edge wfp) (get_return_edges wfp) (Main, Entry) (as@asx) (p', Label lx)" by(fastforce intro:ProcCFG.path_Append ProcCFG.valid_path_same_level_path_Append ProcCFG.intras_same_level_path simp:ProcCFG.vp_def) from \<open>lx' < #:c'\<close> \<open>Rep_wf_prog wfp = (prog,procs)\<close> \<open>(p',ins',outs',c') \<in> set procs\<close> \<open>containsCall procs prog ps' p'\<close> obtain asx' where "wfp \<turnstile> (p',Label lx') -asx'\<rightarrow>* (p',Exit)" and "\<forall>a \<in> set asx'. intra_kind (kind a)" by(fastforce elim:Label_Proc_CFG_Entry_Exit_path_Proc) with pathX have pathX2:"CFG.valid_path' sourcenode targetnode kind (valid_edge wfp) (get_return_edges wfp) (p', Label lx') (asx'@as') (Main, Exit)" by(fastforce intro:ProcCFG.path_Append ProcCFG.same_level_path_valid_path_Append ProcCFG.intras_same_level_path simp:ProcCFG.vp_def) from edge \<open>(p,ins,outs,c) \<in> set procs\<close> \<open>(p',ins',outs',c') \<in> set procs\<close> \<open>containsCall procs prog ps' p'\<close> have "prog,procs \<turnstile> (p',Label lx) -(\<lambda>s. True):(p',Label lx')\<hookrightarrow>\<^bsub>p\<^esub> map (\<lambda>e cf. interpret e cf) es\<rightarrow> (p,Entry)" and "prog,procs \<turnstile> (p,Exit) -(\<lambda>cf. snd cf = (p',Label lx'))\<hookleftarrow>\<^bsub>p\<^esub> (\<lambda>cf cf'. cf'(rets [:=] map cf outs))\<rightarrow> (p',Label lx')" by(fastforce intro:ProcCall ProcReturn)+ with \<open>Rep_wf_prog wfp = (prog,procs)\<close> have path:"wfp \<turnstile> (p',Label lx) -[((p',Label lx),(\<lambda>s. True):(p',Label lx')\<hookrightarrow>\<^bsub>p\<^esub> map (\<lambda>e cf. interpret e cf) es,(p,Entry))]\<rightarrow>* (p,Entry)" and path':"wfp \<turnstile> (p,Exit) -[((p,Exit),(\<lambda>cf. snd cf = (p',Label lx'))\<hookleftarrow>\<^bsub>p\<^esub> (\<lambda>cf cf'. cf'(rets [:=] map cf outs)),(p',Label lx'))]\<rightarrow>* (p',Label lx')" by(fastforce intro:ProcCFG.path.intros simp:ProcCFG.valid_node_def valid_edge_def)+ from path pathE2 have "CFG.valid_path' sourcenode targetnode kind (valid_edge wfp) (get_return_edges wfp) (Main, Entry) ((as@asx)@[((p',Label lx), (\<lambda>s. True):(p',Label lx')\<hookrightarrow>\<^bsub>p\<^esub>map (\<lambda>e cf. interpret e cf) es,(p,Entry))]) (p,Entry)" apply(unfold ProcCFG.vp_def) apply(rule conjI) apply(fastforce intro:ProcCFG.path_Append) by(unfold ProcCFG.valid_path_def,fastforce intro:ProcCFG.vpa_snoc_Call) moreover from path' pathX2 have "CFG.valid_path' sourcenode targetnode kind (valid_edge wfp) (get_return_edges wfp) (p,Exit) ([((p,Exit),(\<lambda>cf. snd cf = (p',Label lx'))\<hookleftarrow>\<^bsub>p\<^esub> (\<lambda>cf cf'. cf'(rets [:=] map cf outs)),(p',Label lx'))]@(asx'@as')) (Main, Exit)" apply(unfold ProcCFG.vp_def) apply(rule conjI) apply(fastforce intro:ProcCFG.path_Append) by(simp add:ProcCFG.valid_path_def ProcCFG.valid_path_def) ultimately show ?case by blast qed qed lemma edge_valid_paths: assumes "prog,procs \<turnstile> sourcenode a -kind a\<rightarrow> targetnode a" and disj:"(p,n) = sourcenode a \<or> (p,n) = targetnode a" and [simp]:"Rep_wf_prog wfp = (prog,procs)" shows "\<exists>as as'. CFG.valid_path' sourcenode targetnode kind (valid_edge wfp) (get_return_edges wfp) (Main,Entry) as (p,n) \<and> CFG.valid_path' sourcenode targetnode kind (valid_edge wfp) (get_return_edges wfp) (p,n) as' (Main,Exit)" proof - from \<open>Rep_wf_prog wfp = (prog,procs)\<close> have wf:"well_formed procs" by(fastforce intro:wf_wf_prog) from \<open>prog,procs \<turnstile> sourcenode a -kind a\<rightarrow> targetnode a\<close> show ?thesis proof(induct "sourcenode a" "kind a" "targetnode a" rule:PCFG.induct) case (Main nx nx') from \<open>(Main, nx) = sourcenode a\<close>[THEN sym] \<open>(Main, nx') = targetnode a\<close>[THEN sym] disj have [simp]:"p = Main" by auto have "prog,procs \<turnstile> (Main, Entry) -(\<lambda>s. False)\<^sub>\<surd>\<rightarrow> (Main, Exit)" by(fastforce intro:PCFG.Main Proc_CFG_Entry_Exit) hence EXpath:"wfp \<turnstile> (Main,Entry) -[((Main,Entry),(\<lambda>s. False)\<^sub>\<surd>,(Main,Exit))]\<rightarrow>* (Main,Exit)" by(fastforce intro:ProcCFG.path.intros simp:valid_edge_def ProcCFG.valid_node_def) show ?case proof(cases n) case (Label l) with \<open>prog \<turnstile> nx -IEdge (kind a)\<rightarrow>\<^sub>p nx'\<close> \<open>(Main, nx) = sourcenode a\<close>[THEN sym] \<open>(Main, nx') = targetnode a\<close>[THEN sym] disj have "l < #:prog" by(auto intro:Proc_CFG_sourcelabel_less_num_nodes Proc_CFG_targetlabel_less_num_nodes) with \<open>Rep_wf_prog wfp = (prog,procs)\<close> obtain as as' where "wfp \<turnstile> (Main,Entry) -as\<rightarrow>* (Main,Label l)" and "\<forall>a \<in> set as. intra_kind (kind a)" and "wfp \<turnstile> (Main,Label l) -as'\<rightarrow>* (Main,Exit)" and "\<forall>a \<in> set as'. intra_kind (kind a)" by -(erule Label_Proc_CFG_Entry_Exit_path_Main)+ with Label show ?thesis apply(rule_tac x="as" in exI) apply(rule_tac x="as'" in exI) apply simp by(fastforce intro:ProcCFG.intra_path_vp simp:ProcCFG.intra_path_def) next case Entry hence "wfp \<turnstile> (Main,Entry) -[]\<rightarrow>* (Main,n)" by(fastforce intro:ProcCFG.empty_path) with EXpath show ?thesis by(fastforce simp:ProcCFG.vp_def ProcCFG.valid_path_def) next case Exit hence "wfp \<turnstile> (Main,n) -[]\<rightarrow>* (Main,Exit)" by(fastforce intro:ProcCFG.empty_path) with Exit EXpath show ?thesis using Exit apply(rule_tac x="[((Main,Entry),(\<lambda>s. False)\<^sub>\<surd>,(Main,Exit))]" in exI) apply simp by(fastforce intro:ProcCFG.intra_path_vp simp:ProcCFG.intra_path_def intra_kind_def) qed next case (Proc px ins outs c nx nx' ps) from \<open>(px, ins, outs, c) \<in> set procs\<close> wf have [simp]:"px \<noteq> Main" by auto from disj \<open>(px, nx) = sourcenode a\<close>[THEN sym] \<open>(px, nx') = targetnode a\<close>[THEN sym] have [simp]:"p = px" by auto from \<open>Rep_wf_prog wfp = (prog,procs)\<close> \<open>containsCall procs prog ps px\<close> \<open>(px, ins, outs, c) \<in> set procs\<close> obtain asx asx' where path:"CFG.valid_path' sourcenode targetnode kind (valid_edge wfp) (get_return_edges wfp) (Main,Entry) asx (px,Entry)" and path':"CFG.valid_path' sourcenode targetnode kind (valid_edge wfp) (get_return_edges wfp) (px,Exit) asx' (Main,Exit)" by -(erule Entry_to_Entry_and_Exit_to_Exit)+ from \<open>containsCall procs prog ps px\<close> \<open>(px, ins, outs, c) \<in> set procs\<close> have "prog,procs \<turnstile> (px, Entry) -(\<lambda>s. False)\<^sub>\<surd>\<rightarrow> (px, Exit)" by(fastforce intro:PCFG.Proc Proc_CFG_Entry_Exit) hence EXpath:"wfp \<turnstile> (px,Entry) -[((px,Entry),(\<lambda>s. False)\<^sub>\<surd>,(px,Exit))]\<rightarrow>* (px,Exit)" by(fastforce intro:ProcCFG.path.intros simp:valid_edge_def ProcCFG.valid_node_def) show ?case proof(cases n) case (Label l) with \<open>c \<turnstile> nx -IEdge (kind a)\<rightarrow>\<^sub>p nx'\<close> disj \<open>(px, nx) = sourcenode a\<close>[THEN sym] \<open>(px, nx') = targetnode a\<close>[THEN sym] have "l < #:c" by(auto intro:Proc_CFG_sourcelabel_less_num_nodes Proc_CFG_targetlabel_less_num_nodes) with \<open>Rep_wf_prog wfp = (prog,procs)\<close> \<open>(px, ins, outs, c) \<in> set procs\<close> \<open>containsCall procs prog ps px\<close> obtain as as' where "wfp \<turnstile> (px,Entry) -as\<rightarrow>* (px,Label l)" and "\<forall>a \<in> set as. intra_kind (kind a)" and "wfp \<turnstile> (px,Label l) -as'\<rightarrow>* (px,Exit)" and "\<forall>a \<in> set as'. intra_kind (kind a)" by -(erule Label_Proc_CFG_Entry_Exit_path_Proc)+ with path path' show ?thesis using Label apply(rule_tac x="asx@as" in exI) apply(rule_tac x="as'@asx'" in exI) by(auto intro:ProcCFG.path_Append ProcCFG.valid_path_same_level_path_Append ProcCFG.same_level_path_valid_path_Append ProcCFG.intras_same_level_path simp:ProcCFG.vp_def) next case Entry from EXpath path' have "CFG.valid_path' sourcenode targetnode kind (valid_edge wfp) (get_return_edges wfp) (px,Entry) ([((px,Entry),(\<lambda>s. False)\<^sub>\<surd>,(px,Exit))]@asx') (Main, Exit)" apply(unfold ProcCFG.vp_def) apply(erule conjE) apply(rule conjI) by(fastforce intro:ProcCFG.path_Append ProcCFG.same_level_path_valid_path_Append ProcCFG.intras_same_level_path simp:intra_kind_def)+ with path Entry show ?thesis by simp blast next case Exit with path EXpath path' show ?thesis apply(rule_tac x="asx@[((px,Entry),(\<lambda>s. False)\<^sub>\<surd>,(px,Exit))]" in exI) apply simp by(fastforce intro:ProcCFG.path_Append ProcCFG.valid_path_same_level_path_Append ProcCFG.intras_same_level_path simp:ProcCFG.vp_def ProcCFG.intra_path_def intra_kind_def) qed next case (MainCall l px es rets nx' ins outs c) from disj show ?case proof assume "(p,n) = sourcenode a" with \<open>(Main, Label l) = sourcenode a\<close>[THEN sym] have [simp]:"n = Label l" "p = Main" by simp_all with \<open>prog \<turnstile> Label l -CEdge (px, es, rets)\<rightarrow>\<^sub>p nx'\<close> have "l < #:prog" by(fastforce intro:Proc_CFG_sourcelabel_less_num_nodes) with \<open>Rep_wf_prog wfp = (prog,procs)\<close> obtain as as' where "wfp \<turnstile> (Main,Entry) -as\<rightarrow>* (Main,Label l)" and "\<forall>a \<in> set as. intra_kind (kind a)" and "wfp \<turnstile> (Main,Label l) -as'\<rightarrow>* (Main,Exit)" and "\<forall>a \<in> set as'. intra_kind (kind a)" by -(erule Label_Proc_CFG_Entry_Exit_path_Main)+ thus ?thesis by(fastforce intro:ProcCFG.intra_path_vp simp:ProcCFG.intra_path_def) next assume "(p,n) = targetnode a" with \<open>(px, Entry) = targetnode a\<close>[THEN sym] have [simp]:"n = Entry" "p = px" by simp_all from \<open>prog \<turnstile> Label l -CEdge (px, es, rets)\<rightarrow>\<^sub>p nx'\<close> have "containsCall procs prog [] px" by(rule Proc_CFG_Call_containsCall) with \<open>Rep_wf_prog wfp = (prog,procs)\<close> \<open>(px, ins, outs, c) \<in> set procs\<close> obtain as' where Xpath:"CFG.valid_path' sourcenode targetnode kind (valid_edge wfp) (get_return_edges wfp) (px,Exit) as' (Main,Exit)" by -(erule Entry_to_Entry_and_Exit_to_Exit) from \<open>containsCall procs prog [] px\<close> \<open>(px, ins, outs, c) \<in> set procs\<close> have "prog,procs \<turnstile> (px, Entry) -(\<lambda>s. False)\<^sub>\<surd>\<rightarrow> (px, Exit)" by(fastforce intro:PCFG.Proc Proc_CFG_Entry_Exit) hence "wfp \<turnstile> (px,Entry) -[((px,Entry),(\<lambda>s. False)\<^sub>\<surd>,(px,Exit))]\<rightarrow>* (px,Exit)" by(fastforce intro:ProcCFG.path.intros simp:valid_edge_def ProcCFG.valid_node_def) with Xpath have "CFG.valid_path' sourcenode targetnode kind (valid_edge wfp) (get_return_edges wfp) (px,Entry) ([((px,Entry),(\<lambda>s. False)\<^sub>\<surd>,(px,Exit))]@as') (Main,Exit)" apply(unfold ProcCFG.vp_def) apply(erule conjE) apply(rule conjI) by(fastforce intro:ProcCFG.path_Append ProcCFG.same_level_path_valid_path_Append ProcCFG.intras_same_level_path simp:intra_kind_def)+ with \<open>containsCall procs prog [] px\<close> \<open>Rep_wf_prog wfp = (prog,procs)\<close> \<open>(px, ins, outs, c) \<in> set procs\<close> show ?thesis by(fastforce elim:Entry_to_Entry_and_Exit_to_Exit) qed next case (ProcCall px ins outs c l p' es' rets' l' ins' outs' c' ps) from disj show ?case proof assume "(p,n) = sourcenode a" with \<open>(px, Label l) = sourcenode a\<close>[THEN sym] have [simp]:"n = Label l" "p = px" by simp_all with \<open>c \<turnstile> Label l -CEdge (p', es', rets')\<rightarrow>\<^sub>p Label l'\<close> have "l < #:c" by(fastforce intro:Proc_CFG_sourcelabel_less_num_nodes) from \<open>Rep_wf_prog wfp = (prog,procs)\<close> \<open>l < #:c\<close> \<open>containsCall procs prog ps px\<close> \<open>(px, ins, outs, c) \<in> set procs\<close> obtain as as' where "wfp \<turnstile> (px,Label l) -as\<rightarrow>* (px,Exit)" and "\<forall>a \<in> set as. intra_kind (kind a)" and "wfp \<turnstile> (px,Entry) -as'\<rightarrow>* (px,Label l)" and "\<forall>a \<in> set as'. intra_kind (kind a)" by -(erule Label_Proc_CFG_Entry_Exit_path_Proc)+ moreover from \<open>Rep_wf_prog wfp = (prog,procs)\<close> \<open>containsCall procs prog ps px\<close> \<open>(px, ins, outs, c) \<in> set procs\<close> obtain asx asx' where" CFG.valid_path' sourcenode targetnode kind (valid_edge wfp) (get_return_edges wfp) (Main,Entry) asx (px,Entry)" and "CFG.valid_path' sourcenode targetnode kind (valid_edge wfp) (get_return_edges wfp) (px,Exit) asx' (Main,Exit)" by -(erule Entry_to_Entry_and_Exit_to_Exit)+ ultimately show ?thesis apply(rule_tac x="asx@as'" in exI) apply(rule_tac x="as@asx'" in exI) by(auto intro:ProcCFG.path_Append ProcCFG.valid_path_same_level_path_Append ProcCFG.same_level_path_valid_path_Append ProcCFG.intras_same_level_path simp:ProcCFG.vp_def) next assume "(p,n) = targetnode a" with \<open>(p', Entry) = targetnode a\<close>[THEN sym] have [simp]:"n = Entry" "p = p'" by simp_all from \<open>c \<turnstile> Label l -CEdge (p', es', rets')\<rightarrow>\<^sub>p Label l'\<close> have "containsCall procs c [] p'" by(rule Proc_CFG_Call_containsCall) with \<open>containsCall procs prog ps px\<close> \<open>(px, ins, outs, c) \<in> set procs\<close> have "containsCall procs prog (ps@[px]) p'" by(rule containsCall_in_proc) with \<open>(p', ins', outs', c') \<in> set procs\<close> have "prog,procs \<turnstile> (p', Entry) -(\<lambda>s. False)\<^sub>\<surd>\<rightarrow> (p', Exit)" by(fastforce intro:PCFG.Proc Proc_CFG_Entry_Exit) hence "wfp \<turnstile> (p',Entry) -[((p',Entry),(\<lambda>s. False)\<^sub>\<surd>,(p',Exit))]\<rightarrow>* (p',Exit)" by(fastforce intro:ProcCFG.path.intros simp:valid_edge_def ProcCFG.valid_node_def) moreover from \<open>Rep_wf_prog wfp = (prog,procs)\<close> \<open>(p', ins', outs', c') \<in> set procs\<close> \<open>containsCall procs prog (ps@[px]) p'\<close> obtain as as' where "CFG.valid_path' sourcenode targetnode kind (valid_edge wfp) (get_return_edges wfp) (Main,Entry) as (p',Entry)" and "CFG.valid_path' sourcenode targetnode kind (valid_edge wfp) (get_return_edges wfp) (p',Exit) as' (Main,Exit)" by -(erule Entry_to_Entry_and_Exit_to_Exit)+ ultimately show ?thesis apply(rule_tac x="as" in exI) apply(rule_tac x="[((p',Entry),(\<lambda>s. False)\<^sub>\<surd>,(p',Exit))]@as'" in exI) apply(unfold ProcCFG.vp_def) by(fastforce intro:ProcCFG.path_Append ProcCFG.same_level_path_valid_path_Append ProcCFG.intras_same_level_path simp:intra_kind_def)+ qed next case (MainReturn l px es rets l' ins outs c) from disj show ?case proof assume "(p,n) = sourcenode a" with \<open>(px, Exit) = sourcenode a\<close>[THEN sym] have [simp]:"n = Exit" "p = px" by simp_all from \<open>prog \<turnstile> Label l -CEdge (px, es, rets)\<rightarrow>\<^sub>p Label l'\<close> have "containsCall procs prog [] px" by(rule Proc_CFG_Call_containsCall) with \<open>(px, ins, outs, c) \<in> set procs\<close> have "prog,procs \<turnstile> (px, Entry) -(\<lambda>s. False)\<^sub>\<surd>\<rightarrow> (px, Exit)" by(fastforce intro:PCFG.Proc Proc_CFG_Entry_Exit) hence "wfp \<turnstile> (px,Entry) -[((px,Entry),(\<lambda>s. False)\<^sub>\<surd>,(px,Exit))]\<rightarrow>* (px,Exit)" by(fastforce intro:ProcCFG.path.intros simp:valid_edge_def ProcCFG.valid_node_def) moreover from \<open>Rep_wf_prog wfp = (prog,procs)\<close> \<open>(px, ins, outs, c) \<in> set procs\<close> \<open>containsCall procs prog [] px\<close> obtain as as' where "CFG.valid_path' sourcenode targetnode kind (valid_edge wfp) (get_return_edges wfp) (Main,Entry) as (px,Entry)" and "CFG.valid_path' sourcenode targetnode kind (valid_edge wfp) (get_return_edges wfp) (px,Exit) as' (Main,Exit)" by -(erule Entry_to_Entry_and_Exit_to_Exit)+ ultimately show ?thesis apply(rule_tac x="as@[((px,Entry),(\<lambda>s. False)\<^sub>\<surd>,(px,Exit))]" in exI) apply(rule_tac x="as'" in exI) apply(unfold ProcCFG.vp_def) by(fastforce intro:ProcCFG.path_Append ProcCFG.valid_path_same_level_path_Append ProcCFG.intras_same_level_path simp:intra_kind_def)+ next assume "(p, n) = targetnode a" with \<open>(Main, Label l') = targetnode a\<close>[THEN sym] have [simp]:"n = Label l'" "p = Main" by simp_all with \<open>prog \<turnstile> Label l -CEdge (px, es, rets)\<rightarrow>\<^sub>p Label l'\<close> have "l' < #:prog" by(fastforce intro:Proc_CFG_targetlabel_less_num_nodes) with \<open>Rep_wf_prog wfp = (prog,procs)\<close> obtain as as' where "wfp \<turnstile> (Main,Entry) -as\<rightarrow>* (Main,Label l')" and "\<forall>a \<in> set as. intra_kind (kind a)" and "wfp \<turnstile> (Main,Label l') -as'\<rightarrow>* (Main,Exit)" and "\<forall>a \<in> set as'. intra_kind (kind a)" by -(erule Label_Proc_CFG_Entry_Exit_path_Main)+ thus ?thesis by(fastforce intro:ProcCFG.intra_path_vp simp:ProcCFG.intra_path_def) qed next case (ProcReturn px ins outs c l p' es' rets' l' ins' outs' c' ps) from disj show ?case proof assume "(p,n) = sourcenode a" with \<open>(p', Exit) = sourcenode a\<close>[THEN sym] have [simp]:"n = Exit" "p = p'" by simp_all from \<open>c \<turnstile> Label l -CEdge (p', es', rets')\<rightarrow>\<^sub>p Label l'\<close> have "containsCall procs c [] p'" by(rule Proc_CFG_Call_containsCall) with \<open>containsCall procs prog ps px\<close> \<open>(px, ins, outs, c) \<in> set procs\<close> have "containsCall procs prog (ps@[px]) p'" by(rule containsCall_in_proc) with \<open>(p', ins', outs', c') \<in> set procs\<close> have "prog,procs \<turnstile> (p', Entry) -(\<lambda>s. False)\<^sub>\<surd>\<rightarrow> (p', Exit)" by(fastforce intro:PCFG.Proc Proc_CFG_Entry_Exit) hence "wfp \<turnstile> (p',Entry) -[((p',Entry),(\<lambda>s. False)\<^sub>\<surd>,(p',Exit))]\<rightarrow>* (p',Exit)" by(fastforce intro:ProcCFG.path.intros simp:valid_edge_def ProcCFG.valid_node_def) moreover from \<open>Rep_wf_prog wfp = (prog,procs)\<close> \<open>(p', ins', outs', c') \<in> set procs\<close> \<open>containsCall procs prog (ps@[px]) p'\<close> obtain as as' where "CFG.valid_path' sourcenode targetnode kind (valid_edge wfp) (get_return_edges wfp) (Main,Entry) as (p',Entry)" and "CFG.valid_path' sourcenode targetnode kind (valid_edge wfp) (get_return_edges wfp) (p',Exit) as' (Main,Exit)" by -(erule Entry_to_Entry_and_Exit_to_Exit)+ ultimately show ?thesis apply(rule_tac x="as@[((p',Entry),(\<lambda>s. False)\<^sub>\<surd>,(p',Exit))]" in exI) apply(rule_tac x="as'" in exI) apply(unfold ProcCFG.vp_def) by(fastforce intro:ProcCFG.path_Append ProcCFG.valid_path_same_level_path_Append ProcCFG.intras_same_level_path simp:intra_kind_def)+ next assume "(p, n) = targetnode a" with \<open>(px, Label l') = targetnode a\<close>[THEN sym] have [simp]:"n = Label l'" "p = px" by simp_all with \<open>c \<turnstile> Label l -CEdge (p', es', rets')\<rightarrow>\<^sub>p Label l'\<close> have "l' < #:c" by(fastforce intro:Proc_CFG_targetlabel_less_num_nodes) from \<open>Rep_wf_prog wfp = (prog,procs)\<close> \<open>l' < #:c\<close> \<open>containsCall procs prog ps px\<close> \<open>(px, ins, outs, c) \<in> set procs\<close> obtain as as' where "wfp \<turnstile> (px,Label l') -as\<rightarrow>* (px,Exit)" and "\<forall>a \<in> set as. intra_kind (kind a)" and "wfp \<turnstile> (px,Entry) -as'\<rightarrow>* (px,Label l')" and "\<forall>a \<in> set as'. intra_kind (kind a)" by -(erule Label_Proc_CFG_Entry_Exit_path_Proc)+ moreover from \<open>Rep_wf_prog wfp = (prog,procs)\<close> \<open>containsCall procs prog ps px\<close> \<open>(px, ins, outs, c) \<in> set procs\<close> obtain asx asx' where" CFG.valid_path' sourcenode targetnode kind (valid_edge wfp) (get_return_edges wfp) (Main,Entry) asx (px,Entry)" and "CFG.valid_path' sourcenode targetnode kind (valid_edge wfp) (get_return_edges wfp) (px,Exit) asx' (Main,Exit)" by -(erule Entry_to_Entry_and_Exit_to_Exit)+ ultimately show ?thesis apply(rule_tac x="asx@as'" in exI) apply(rule_tac x="as@asx'" in exI) by(auto intro:ProcCFG.path_Append ProcCFG.valid_path_same_level_path_Append ProcCFG.same_level_path_valid_path_Append ProcCFG.intras_same_level_path simp:ProcCFG.vp_def) qed next case (MainCallReturn nx px es rets nx') from \<open>prog \<turnstile> nx -CEdge (px, es, rets)\<rightarrow>\<^sub>p nx'\<close> disj \<open>(Main, nx) = sourcenode a\<close>[THEN sym] \<open>(Main, nx') = targetnode a\<close>[THEN sym] obtain l where [simp]:"n = Label l" "p = Main" by(fastforce dest:Proc_CFG_Call_Labels) from \<open>prog \<turnstile> nx -CEdge (px, es, rets)\<rightarrow>\<^sub>p nx'\<close> disj \<open>(Main, nx) = sourcenode a\<close>[THEN sym] \<open>(Main, nx') = targetnode a\<close>[THEN sym] have "l < #:prog" by(auto intro:Proc_CFG_sourcelabel_less_num_nodes Proc_CFG_targetlabel_less_num_nodes) with \<open>Rep_wf_prog wfp = (prog,procs)\<close> obtain as as' where "wfp \<turnstile> (Main,Entry) -as\<rightarrow>* (Main,Label l)" and "\<forall>a \<in> set as. intra_kind (kind a)" and "wfp \<turnstile> (Main,Label l) -as'\<rightarrow>* (Main,Exit)" and "\<forall>a \<in> set as'. intra_kind (kind a)" by -(erule Label_Proc_CFG_Entry_Exit_path_Main)+ thus ?thesis apply(rule_tac x="as" in exI) apply(rule_tac x="as'" in exI) apply simp by(fastforce intro:ProcCFG.intra_path_vp simp:ProcCFG.intra_path_def) next case (ProcCallReturn px ins outs c nx p' es' rets' nx' ps) from \<open>(px, ins, outs, c) \<in> set procs\<close> wf have [simp]:"px \<noteq> Main" by auto from \<open>c \<turnstile> nx -CEdge (p', es', rets')\<rightarrow>\<^sub>p nx'\<close> disj \<open>(px, nx) = sourcenode a\<close>[THEN sym] \<open>(px, nx') = targetnode a\<close>[THEN sym] obtain l where [simp]:"n = Label l" "p = px" by(fastforce dest:Proc_CFG_Call_Labels) from \<open>c \<turnstile> nx -CEdge (p', es', rets')\<rightarrow>\<^sub>p nx'\<close> disj \<open>(px, nx) = sourcenode a\<close>[THEN sym] \<open>(px, nx') = targetnode a\<close>[THEN sym] have "l < #:c" by(auto intro:Proc_CFG_sourcelabel_less_num_nodes Proc_CFG_targetlabel_less_num_nodes) with \<open>Rep_wf_prog wfp = (prog,procs)\<close> \<open>(px, ins, outs, c) \<in> set procs\<close> \<open>containsCall procs prog ps px\<close> obtain as as' where "wfp \<turnstile> (px,Entry) -as\<rightarrow>* (px,Label l)" and "\<forall>a \<in> set as. intra_kind (kind a)" and "wfp \<turnstile> (px,Label l) -as'\<rightarrow>* (px,Exit)" and "\<forall>a \<in> set as'. intra_kind (kind a)" by -(erule Label_Proc_CFG_Entry_Exit_path_Proc)+ moreover from \<open>Rep_wf_prog wfp = (prog,procs)\<close> \<open>containsCall procs prog ps px\<close> \<open>(px, ins, outs, c) \<in> set procs\<close> obtain asx asx' where "CFG.valid_path' sourcenode targetnode kind (valid_edge wfp) (get_return_edges wfp) (Main,Entry) asx (px,Entry)" and "CFG.valid_path' sourcenode targetnode kind (valid_edge wfp) (get_return_edges wfp) (px,Exit) asx' (Main,Exit)" by -(erule Entry_to_Entry_and_Exit_to_Exit)+ ultimately show ?thesis apply(rule_tac x="asx@as" in exI) apply(rule_tac x="as'@asx'" in exI) by(auto intro:ProcCFG.path_Append ProcCFG.valid_path_same_level_path_Append ProcCFG.same_level_path_valid_path_Append ProcCFG.intras_same_level_path simp:ProcCFG.vp_def) qed qed subsection \<open>Instantiating the \<open>Postdomination\<close> locale\<close> interpretation ProcPostdomination: Postdomination sourcenode targetnode kind "valid_edge wfp" "(Main,Entry)" get_proc "get_return_edges wfp" "lift_procs wfp" Main "(Main,Exit)" for wfp proof - from Rep_wf_prog[of wfp] obtain prog procs where [simp]:"Rep_wf_prog wfp = (prog,procs)" by(fastforce simp:wf_prog_def) hence wf:"well_formed procs" by(fastforce intro:wf_wf_prog) show "Postdomination sourcenode targetnode kind (valid_edge wfp) (Main, Entry) get_proc (get_return_edges wfp) (lift_procs wfp) Main (Main, Exit)" proof fix m assume "CFG.valid_node sourcenode targetnode (valid_edge wfp) m" then obtain a where "valid_edge wfp a" and "m = sourcenode a \<or> m = targetnode a" by(fastforce simp:ProcCFG.valid_node_def) obtain p n where [simp]:"m = (p,n)" by(cases m) auto from \<open>valid_edge wfp a\<close> \<open>m = sourcenode a \<or> m = targetnode a\<close> \<open>Rep_wf_prog wfp = (prog,procs)\<close> show "\<exists>as. CFG.valid_path' sourcenode targetnode kind (valid_edge wfp) (get_return_edges wfp) (Main, Entry) as m" by(auto dest!:edge_valid_paths simp:valid_edge_def) next fix m assume "CFG.valid_node sourcenode targetnode (valid_edge wfp) m" then obtain a where "valid_edge wfp a" and "m = sourcenode a \<or> m = targetnode a" by(fastforce simp:ProcCFG.valid_node_def) obtain p n where [simp]:"m = (p,n)" by(cases m) auto from \<open>valid_edge wfp a\<close> \<open>m = sourcenode a \<or> m = targetnode a\<close> \<open>Rep_wf_prog wfp = (prog,procs)\<close> show "\<exists>as. CFG.valid_path' sourcenode targetnode kind (valid_edge wfp) (get_return_edges wfp) m as (Main,Exit)" by(auto dest!:edge_valid_paths simp:valid_edge_def) next fix n n' assume mex1:"CFGExit.method_exit sourcenode kind (valid_edge wfp) (Main,Exit) n" and mex2:"CFGExit.method_exit sourcenode kind (valid_edge wfp) (Main,Exit) n'" and "get_proc n = get_proc n'" from mex1 have "n = (Main,Exit) \<or> (\<exists>a Q p f. n = sourcenode a \<and> valid_edge wfp a \<and> kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f)" by(simp add:ProcCFGExit.method_exit_def) thus "n = n'" proof assume "n = (Main,Exit)" from mex2 have "n' = (Main,Exit) \<or> (\<exists>a Q p f. n' = sourcenode a \<and> valid_edge wfp a \<and> kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f)" by(simp add:ProcCFGExit.method_exit_def) thus ?thesis proof assume "n' = (Main,Exit)" with \<open>n = (Main,Exit)\<close> show ?thesis by simp next assume "\<exists>a Q p f. n' = sourcenode a \<and> valid_edge wfp a \<and> kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f" then obtain a Q p f where "n' = sourcenode a" and "valid_edge wfp a" and "kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f" by blast from \<open>valid_edge wfp a\<close> \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> have "get_proc (sourcenode a) = p" by(rule ProcCFG.get_proc_return) with \<open>get_proc n = get_proc n'\<close> \<open>n = (Main,Exit)\<close> \<open>n' = sourcenode a\<close> have "get_proc (Main,Exit) = p" by simp hence "p = Main" by simp with \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> have "kind a = Q\<hookleftarrow>\<^bsub>Main\<^esub>f" by simp with \<open>valid_edge wfp a\<close> have False by(rule ProcCFG.Main_no_return_source) thus ?thesis by simp qed next assume "\<exists>a Q p f. n = sourcenode a \<and> valid_edge wfp a \<and> kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f" then obtain a Q p f where "n = sourcenode a" and "valid_edge wfp a" and "kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f" by blast from \<open>valid_edge wfp a\<close> \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> have "get_proc (sourcenode a) = p" by(rule ProcCFG.get_proc_return) from mex2 have "n' = (Main,Exit) \<or> (\<exists>a Q p f. n' = sourcenode a \<and> valid_edge wfp a \<and> kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f)" by(simp add:ProcCFGExit.method_exit_def) thus ?thesis proof assume "n' = (Main,Exit)" from \<open>get_proc (sourcenode a) = p\<close> \<open>get_proc n = get_proc n'\<close> \<open>n' = (Main,Exit)\<close> \<open>n = sourcenode a\<close> have "get_proc (Main,Exit) = p" by simp hence "p = Main" by simp with \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> have "kind a = Q\<hookleftarrow>\<^bsub>Main\<^esub>f" by simp with \<open>valid_edge wfp a\<close> have False by(rule ProcCFG.Main_no_return_source) thus ?thesis by simp next assume "\<exists>a Q p f. n' = sourcenode a \<and> valid_edge wfp a \<and> kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f" then obtain a' Q' p' f' where "n' = sourcenode a'" and "valid_edge wfp a'" and "kind a' = Q'\<hookleftarrow>\<^bsub>p'\<^esub>f'" by blast from \<open>valid_edge wfp a'\<close> \<open>kind a' = Q'\<hookleftarrow>\<^bsub>p'\<^esub>f'\<close> have "get_proc (sourcenode a') = p'" by(rule ProcCFG.get_proc_return) with \<open>get_proc n = get_proc n'\<close> \<open>get_proc (sourcenode a) = p\<close> \<open>n = sourcenode a\<close> \<open>n' = sourcenode a'\<close> have "p' = p" by simp from \<open>valid_edge wfp a\<close> \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> have "sourcenode a = (p,Exit)" by(auto elim:PCFG.cases simp:valid_edge_def) from \<open>valid_edge wfp a'\<close> \<open>kind a' = Q'\<hookleftarrow>\<^bsub>p'\<^esub>f'\<close> have "sourcenode a' = (p',Exit)" by(auto elim:PCFG.cases simp:valid_edge_def) with \<open>n = sourcenode a\<close> \<open>n' = sourcenode a'\<close> \<open>p' = p\<close> \<open>sourcenode a = (p,Exit)\<close> show ?thesis by simp qed qed qed qed end
State Before: G : Type ?u.38544 M : Type u_1 N : Type ?u.38550 α : Sort ?u.38553 β : Sort ?u.38556 ι : Sort ?u.38559 inst✝² : CommMonoid M inst✝¹ : CommMonoid N p : Prop inst✝ : Decidable p f : p → M ⊢ (∏ᶠ (i : p), f i) = if h : p then f h else 1 State After: case inl G : Type ?u.38544 M : Type u_1 N : Type ?u.38550 α : Sort ?u.38553 β : Sort ?u.38556 ι : Sort ?u.38559 inst✝² : CommMonoid M inst✝¹ : CommMonoid N p : Prop inst✝ : Decidable p f : p → M h : p ⊢ (∏ᶠ (i : p), f i) = f h case inr G : Type ?u.38544 M : Type u_1 N : Type ?u.38550 α : Sort ?u.38553 β : Sort ?u.38556 ι : Sort ?u.38559 inst✝² : CommMonoid M inst✝¹ : CommMonoid N p : Prop inst✝ : Decidable p f : p → M h : ¬p ⊢ (∏ᶠ (i : p), f i) = 1 Tactic: split_ifs with h State Before: case inl G : Type ?u.38544 M : Type u_1 N : Type ?u.38550 α : Sort ?u.38553 β : Sort ?u.38556 ι : Sort ?u.38559 inst✝² : CommMonoid M inst✝¹ : CommMonoid N p : Prop inst✝ : Decidable p f : p → M h : p ⊢ (∏ᶠ (i : p), f i) = f h State After: case inl G : Type ?u.38544 M : Type u_1 N : Type ?u.38550 α : Sort ?u.38553 β : Sort ?u.38556 ι : Sort ?u.38559 inst✝² : CommMonoid M inst✝¹ : CommMonoid N p : Prop inst✝ : Decidable p f : p → M h : p this : Unique p ⊢ (∏ᶠ (i : p), f i) = f h Tactic: haveI : Unique p := ⟨⟨h⟩, fun _ => rfl⟩ State Before: case inl G : Type ?u.38544 M : Type u_1 N : Type ?u.38550 α : Sort ?u.38553 β : Sort ?u.38556 ι : Sort ?u.38559 inst✝² : CommMonoid M inst✝¹ : CommMonoid N p : Prop inst✝ : Decidable p f : p → M h : p this : Unique p ⊢ (∏ᶠ (i : p), f i) = f h State After: no goals Tactic: exact finprod_unique f State Before: case inr G : Type ?u.38544 M : Type u_1 N : Type ?u.38550 α : Sort ?u.38553 β : Sort ?u.38556 ι : Sort ?u.38559 inst✝² : CommMonoid M inst✝¹ : CommMonoid N p : Prop inst✝ : Decidable p f : p → M h : ¬p ⊢ (∏ᶠ (i : p), f i) = 1 State After: case inr G : Type ?u.38544 M : Type u_1 N : Type ?u.38550 α : Sort ?u.38553 β : Sort ?u.38556 ι : Sort ?u.38559 inst✝² : CommMonoid M inst✝¹ : CommMonoid N p : Prop inst✝ : Decidable p f : p → M h : ¬p this : IsEmpty p ⊢ (∏ᶠ (i : p), f i) = 1 Tactic: haveI : IsEmpty p := ⟨h⟩ State Before: case inr G : Type ?u.38544 M : Type u_1 N : Type ?u.38550 α : Sort ?u.38553 β : Sort ?u.38556 ι : Sort ?u.38559 inst✝² : CommMonoid M inst✝¹ : CommMonoid N p : Prop inst✝ : Decidable p f : p → M h : ¬p this : IsEmpty p ⊢ (∏ᶠ (i : p), f i) = 1 State After: no goals Tactic: exact finprod_of_isEmpty f
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta -/ import category_theory.limits.has_limits import category_theory.discrete_category noncomputable theory universes v u u₂ open category_theory namespace category_theory.limits variables {β : Type v} variables {C : Type u} [category.{v} C] -- We don't need an analogue of `pair` (for binary products), `parallel_pair` (for equalizers), -- or `(co)span`, since we already have `discrete.functor`. /-- A fan over `f : β → C` consists of a collection of maps from an object `P` to every `f b`. -/ abbreviation fan (f : β → C) := cone (discrete.functor f) /-- A cofan over `f : β → C` consists of a collection of maps from every `f b` to an object `P`. -/ abbreviation cofan (f : β → C) := cocone (discrete.functor f) /-- A fan over `f : β → C` consists of a collection of maps from an object `P` to every `f b`. -/ @[simps] def fan.mk {f : β → C} (P : C) (p : Π b, P ⟶ f b) : fan f := { X := P, π := { app := p } } /-- A cofan over `f : β → C` consists of a collection of maps from every `f b` to an object `P`. -/ @[simps] def cofan.mk {f : β → C} (P : C) (p : Π b, f b ⟶ P) : cofan f := { X := P, ι := { app := p } } /-- An abbreviation for `has_limit (discrete.functor f)`. -/ abbreviation has_product (f : β → C) := has_limit (discrete.functor f) /-- An abbreviation for `has_colimit (discrete.functor f)`. -/ abbreviation has_coproduct (f : β → C) := has_colimit (discrete.functor f) section variables (C) /-- An abbreviation for `has_limits_of_shape (discrete f)`. -/ abbreviation has_products_of_shape (β : Type v) := has_limits_of_shape.{v} (discrete β) /-- An abbreviation for `has_colimits_of_shape (discrete f)`. -/ abbreviation has_coproducts_of_shape (β : Type v) := has_colimits_of_shape.{v} (discrete β) end /-- `pi_obj f` computes the product of a family of elements `f`. (It is defined as an abbreviation for `limit (discrete.functor f)`, so for most facts about `pi_obj f`, you will just use general facts about limits.) -/ abbreviation pi_obj (f : β → C) [has_product f] := limit (discrete.functor f) /-- `sigma_obj f` computes the coproduct of a family of elements `f`. (It is defined as an abbreviation for `colimit (discrete.functor f)`, so for most facts about `sigma_obj f`, you will just use general facts about colimits.) -/ abbreviation sigma_obj (f : β → C) [has_coproduct f] := colimit (discrete.functor f) notation `∏ ` f:20 := pi_obj f notation `∐ ` f:20 := sigma_obj f /-- The `b`-th projection from the pi object over `f` has the form `∏ f ⟶ f b`. -/ abbreviation pi.π (f : β → C) [has_product f] (b : β) : ∏ f ⟶ f b := limit.π (discrete.functor f) b /-- The `b`-th inclusion into the sigma object over `f` has the form `f b ⟶ ∐ f`. -/ abbreviation sigma.ι (f : β → C) [has_coproduct f] (b : β) : f b ⟶ ∐ f := colimit.ι (discrete.functor f) b /-- The fan constructed of the projections from the product is limiting. -/ def product_is_product (f : β → C) [has_product f] : is_limit (fan.mk _ (pi.π f)) := is_limit.of_iso_limit (limit.is_limit (discrete.functor f)) (cones.ext (iso.refl _) (by tidy)) /-- The cofan constructed of the inclusions from the coproduct is colimiting. -/ def coproduct_is_coproduct (f : β → C) [has_coproduct f] : is_colimit (cofan.mk _ (sigma.ι f)) := is_colimit.of_iso_colimit (colimit.is_colimit (discrete.functor f)) (cocones.ext (iso.refl _) (by tidy)) /-- A collection of morphisms `P ⟶ f b` induces a morphism `P ⟶ ∏ f`. -/ abbreviation pi.lift {f : β → C} [has_product f] {P : C} (p : Π b, P ⟶ f b) : P ⟶ ∏ f := limit.lift _ (fan.mk P p) /-- A collection of morphisms `f b ⟶ P` induces a morphism `∐ f ⟶ P`. -/ abbreviation sigma.desc {f : β → C} [has_coproduct f] {P : C} (p : Π b, f b ⟶ P) : ∐ f ⟶ P := colimit.desc _ (cofan.mk P p) /-- Construct a morphism between categorical products (indexed by the same type) from a family of morphisms between the factors. -/ abbreviation pi.map {f g : β → C} [has_product f] [has_product g] (p : Π b, f b ⟶ g b) : ∏ f ⟶ ∏ g := lim_map (discrete.nat_trans p) /-- Construct an isomorphism between categorical products (indexed by the same type) from a family of isomorphisms between the factors. -/ abbreviation pi.map_iso {f g : β → C} [has_products_of_shape β C] (p : Π b, f b ≅ g b) : ∏ f ≅ ∏ g := lim.map_iso (discrete.nat_iso p) /-- Construct a morphism between categorical coproducts (indexed by the same type) from a family of morphisms between the factors. -/ abbreviation sigma.map {f g : β → C} [has_coproduct f] [has_coproduct g] (p : Π b, f b ⟶ g b) : ∐ f ⟶ ∐ g := colim_map (discrete.nat_trans p) /-- Construct an isomorphism between categorical coproducts (indexed by the same type) from a family of isomorphisms between the factors. -/ abbreviation sigma.map_iso {f g : β → C} [has_coproducts_of_shape β C] (p : Π b, f b ≅ g b) : ∐ f ≅ ∐ g := colim.map_iso (discrete.nat_iso p) section comparison variables {D : Type u₂} [category.{v} D] (G : C ⥤ D) variables (f : β → C) -- TODO: show this is an iso iff G preserves the product of f. /-- The comparison morphism for the product of `f`. -/ def pi_comparison [has_product f] [has_product (λ b, G.obj (f b))] : G.obj (∏ f) ⟶ ∏ (λ b, G.obj (f b)) := pi.lift (λ b, G.map (pi.π f b)) @[simp, reassoc] lemma pi_comparison_comp_π [has_product f] [has_product (λ b, G.obj (f b))] (b : β) : pi_comparison G f ≫ pi.π _ b = G.map (pi.π f b) := limit.lift_π _ b @[simp, reassoc] lemma map_lift_pi_comparison [has_product f] [has_product (λ b, G.obj (f b))] (P : C) (g : Π j, P ⟶ f j) : G.map (pi.lift g) ≫ pi_comparison G f = pi.lift (λ j, G.map (g j)) := by { ext, simp [← G.map_comp] } -- TODO: show this is an iso iff G preserves the coproduct of f. /-- The comparison morphism for the coproduct of `f`. -/ def sigma_comparison [has_coproduct f] [has_coproduct (λ b, G.obj (f b))] : ∐ (λ b, G.obj (f b)) ⟶ G.obj (∐ f) := sigma.desc (λ b, G.map (sigma.ι f b)) @[simp, reassoc] lemma ι_comp_sigma_comparison [has_coproduct f] [has_coproduct (λ b, G.obj (f b))] (b : β) : sigma.ι _ b ≫ sigma_comparison G f = G.map (sigma.ι f b) := colimit.ι_desc _ b @[simp, reassoc] lemma sigma_comparison_map_desc [has_coproduct f] [has_coproduct (λ b, G.obj (f b))] (P : C) (g : Π j, f j ⟶ P) : sigma_comparison G f ≫ G.map (sigma.desc g) = sigma.desc (λ j, G.map (g j)) := by { ext, simp [← G.map_comp] } end comparison variables (C) /-- An abbreviation for `Π J, has_limits_of_shape (discrete J) C` -/ abbreviation has_products := Π (J : Type v), has_limits_of_shape (discrete J) C /-- An abbreviation for `Π J, has_colimits_of_shape (discrete J) C` -/ abbreviation has_coproducts := Π (J : Type v), has_colimits_of_shape (discrete J) C end category_theory.limits
State Before: k : Type u_1 V : Type u_3 P : Type u_4 inst✝² : Ring k inst✝¹ : AddCommGroup V inst✝ : Module k V S : AffineSpace V P ι : Type u_2 s : Finset ι ι₂ : Type ?u.31556 s₂ : Finset ι₂ w : ι → k p : ι → P h : ∑ i in s, w i = 0 b₁ b₂ : P ⊢ ↑(weightedVSubOfPoint s p b₁) w = ↑(weightedVSubOfPoint s p b₂) w State After: case h k : Type u_1 V : Type u_3 P : Type u_4 inst✝² : Ring k inst✝¹ : AddCommGroup V inst✝ : Module k V S : AffineSpace V P ι : Type u_2 s : Finset ι ι₂ : Type ?u.31556 s₂ : Finset ι₂ w : ι → k p : ι → P h : ∑ i in s, w i = 0 b₁ b₂ : P ⊢ ↑(weightedVSubOfPoint s p b₁) w - ↑(weightedVSubOfPoint s p b₂) w = 0 Tactic: apply eq_of_sub_eq_zero State Before: case h k : Type u_1 V : Type u_3 P : Type u_4 inst✝² : Ring k inst✝¹ : AddCommGroup V inst✝ : Module k V S : AffineSpace V P ι : Type u_2 s : Finset ι ι₂ : Type ?u.31556 s₂ : Finset ι₂ w : ι → k p : ι → P h : ∑ i in s, w i = 0 b₁ b₂ : P ⊢ ↑(weightedVSubOfPoint s p b₁) w - ↑(weightedVSubOfPoint s p b₂) w = 0 State After: case h k : Type u_1 V : Type u_3 P : Type u_4 inst✝² : Ring k inst✝¹ : AddCommGroup V inst✝ : Module k V S : AffineSpace V P ι : Type u_2 s : Finset ι ι₂ : Type ?u.31556 s₂ : Finset ι₂ w : ι → k p : ι → P h : ∑ i in s, w i = 0 b₁ b₂ : P ⊢ ∑ x in s, (w x • (p x -ᵥ b₁) - w x • (p x -ᵥ b₂)) = 0 Tactic: rw [weightedVSubOfPoint_apply, weightedVSubOfPoint_apply, ← sum_sub_distrib] State Before: case h k : Type u_1 V : Type u_3 P : Type u_4 inst✝² : Ring k inst✝¹ : AddCommGroup V inst✝ : Module k V S : AffineSpace V P ι : Type u_2 s : Finset ι ι₂ : Type ?u.31556 s₂ : Finset ι₂ w : ι → k p : ι → P h : ∑ i in s, w i = 0 b₁ b₂ : P ⊢ ∑ x in s, w x • (b₂ -ᵥ b₁) = 0 State After: no goals Tactic: rw [← sum_smul, h, zero_smul]
(* Title: CCL/Type.thy Author: Martin Coen Copyright 1993 University of Cambridge *) section \<open>Types in CCL are defined as sets of terms\<close> theory Type imports Term begin definition Subtype :: "['a set, 'a \<Rightarrow> o] \<Rightarrow> 'a set" where "Subtype(A, P) == {x. x:A \<and> P(x)}" syntax "_Subtype" :: "[idt, 'a set, o] \<Rightarrow> 'a set" ("(1{_: _ ./ _})") translations "{x: A. B}" == "CONST Subtype(A, \<lambda>x. B)" definition Unit :: "i set" where "Unit == {x. x=one}" definition Bool :: "i set" where "Bool == {x. x=true | x=false}" definition Plus :: "[i set, i set] \<Rightarrow> i set" (infixr "+" 55) where "A+B == {x. (EX a:A. x=inl(a)) | (EX b:B. x=inr(b))}" definition Pi :: "[i set, i \<Rightarrow> i set] \<Rightarrow> i set" where "Pi(A,B) == {x. EX b. x=lam x. b(x) \<and> (ALL x:A. b(x):B(x))}" definition Sigma :: "[i set, i \<Rightarrow> i set] \<Rightarrow> i set" where "Sigma(A,B) == {x. EX a:A. EX b:B(a).x=<a,b>}" syntax "_Pi" :: "[idt, i set, i set] \<Rightarrow> i set" ("(3PROD _:_./ _)" [0,0,60] 60) "_Sigma" :: "[idt, i set, i set] \<Rightarrow> i set" ("(3SUM _:_./ _)" [0,0,60] 60) "_arrow" :: "[i set, i set] \<Rightarrow> i set" ("(_ ->/ _)" [54, 53] 53) "_star" :: "[i set, i set] \<Rightarrow> i set" ("(_ */ _)" [56, 55] 55) translations "PROD x:A. B" \<rightharpoonup> "CONST Pi(A, \<lambda>x. B)" "A -> B" \<rightharpoonup> "CONST Pi(A, \<lambda>_. B)" "SUM x:A. B" \<rightharpoonup> "CONST Sigma(A, \<lambda>x. B)" "A * B" \<rightharpoonup> "CONST Sigma(A, \<lambda>_. B)" print_translation \<open> [(\<^const_syntax>\<open>Pi\<close>, fn _ => Syntax_Trans.dependent_tr' (\<^syntax_const>\<open>_Pi\<close>, \<^syntax_const>\<open>_arrow\<close>)), (\<^const_syntax>\<open>Sigma\<close>, fn _ => Syntax_Trans.dependent_tr' (\<^syntax_const>\<open>_Sigma\<close>, \<^syntax_const>\<open>_star\<close>))] \<close> definition Nat :: "i set" where "Nat == lfp(\<lambda>X. Unit + X)" definition List :: "i set \<Rightarrow> i set" where "List(A) == lfp(\<lambda>X. Unit + A*X)" definition Lists :: "i set \<Rightarrow> i set" where "Lists(A) == gfp(\<lambda>X. Unit + A*X)" definition ILists :: "i set \<Rightarrow> i set" where "ILists(A) == gfp(\<lambda>X.{} + A*X)" definition TAll :: "(i set \<Rightarrow> i set) \<Rightarrow> i set" (binder "TALL " 55) where "TALL X. B(X) == Inter({X. EX Y. X=B(Y)})" definition TEx :: "(i set \<Rightarrow> i set) \<Rightarrow> i set" (binder "TEX " 55) where "TEX X. B(X) == Union({X. EX Y. X=B(Y)})" definition Lift :: "i set \<Rightarrow> i set" ("(3[_])") where "[A] == A Un {bot}" definition SPLIT :: "[i, [i, i] \<Rightarrow> i set] \<Rightarrow> i set" where "SPLIT(p,B) == Union({A. EX x y. p=<x,y> \<and> A=B(x,y)})" lemmas simp_type_defs = Subtype_def Unit_def Bool_def Plus_def Sigma_def Pi_def Lift_def TAll_def TEx_def and ind_type_defs = Nat_def List_def and simp_data_defs = one_def inl_def inr_def and ind_data_defs = zero_def succ_def nil_def cons_def lemma subsetXH: "A <= B \<longleftrightarrow> (ALL x. x:A \<longrightarrow> x:B)" by blast subsection \<open>Exhaustion Rules\<close> lemma EmptyXH: "\<And>a. a : {} \<longleftrightarrow> False" and SubtypeXH: "\<And>a A P. a : {x:A. P(x)} \<longleftrightarrow> (a:A \<and> P(a))" and UnitXH: "\<And>a. a : Unit \<longleftrightarrow> a=one" and BoolXH: "\<And>a. a : Bool \<longleftrightarrow> a=true | a=false" and PlusXH: "\<And>a A B. a : A+B \<longleftrightarrow> (EX x:A. a=inl(x)) | (EX x:B. a=inr(x))" and PiXH: "\<And>a A B. a : PROD x:A. B(x) \<longleftrightarrow> (EX b. a=lam x. b(x) \<and> (ALL x:A. b(x):B(x)))" and SgXH: "\<And>a A B. a : SUM x:A. B(x) \<longleftrightarrow> (EX x:A. EX y:B(x).a=<x,y>)" unfolding simp_type_defs by blast+ lemmas XHs = EmptyXH SubtypeXH UnitXH BoolXH PlusXH PiXH SgXH lemma LiftXH: "a : [A] \<longleftrightarrow> (a=bot | a:A)" and TallXH: "a : TALL X. B(X) \<longleftrightarrow> (ALL X. a:B(X))" and TexXH: "a : TEX X. B(X) \<longleftrightarrow> (EX X. a:B(X))" unfolding simp_type_defs by blast+ ML \<open>ML_Thms.bind_thms ("case_rls", XH_to_Es @{thms XHs})\<close> subsection \<open>Canonical Type Rules\<close> lemma oneT: "one : Unit" and trueT: "true : Bool" and falseT: "false : Bool" and lamT: "\<And>b B. (\<And>x. x:A \<Longrightarrow> b(x):B(x)) \<Longrightarrow> lam x. b(x) : Pi(A,B)" and pairT: "\<And>b B. \<lbrakk>a:A; b:B(a)\<rbrakk> \<Longrightarrow> <a,b>:Sigma(A,B)" and inlT: "a:A \<Longrightarrow> inl(a) : A+B" and inrT: "b:B \<Longrightarrow> inr(b) : A+B" by (blast intro: XHs [THEN iffD2])+ lemmas canTs = oneT trueT falseT pairT lamT inlT inrT subsection \<open>Non-Canonical Type Rules\<close> lemma lem: "\<lbrakk>a:B(u); u = v\<rbrakk> \<Longrightarrow> a : B(v)" by blast ML \<open> fun mk_ncanT_tac top_crls crls = SUBPROOF (fn {context = ctxt, prems = major :: prems, ...} => resolve_tac ctxt ([major] RL top_crls) 1 THEN REPEAT_SOME (eresolve_tac ctxt (crls @ @{thms exE bexE conjE disjE})) THEN ALLGOALS (asm_simp_tac ctxt) THEN ALLGOALS (assume_tac ctxt ORELSE' resolve_tac ctxt (prems RL [@{thm lem}]) ORELSE' eresolve_tac ctxt @{thms bspec}) THEN safe_tac (ctxt addSIs prems)) \<close> method_setup ncanT = \<open> Scan.succeed (SIMPLE_METHOD' o mk_ncanT_tac @{thms case_rls} @{thms case_rls}) \<close> lemma ifT: "\<lbrakk>b:Bool; b=true \<Longrightarrow> t:A(true); b=false \<Longrightarrow> u:A(false)\<rbrakk> \<Longrightarrow> if b then t else u : A(b)" by ncanT lemma applyT: "\<lbrakk>f : Pi(A,B); a:A\<rbrakk> \<Longrightarrow> f ` a : B(a)" by ncanT lemma splitT: "\<lbrakk>p:Sigma(A,B); \<And>x y. \<lbrakk>x:A; y:B(x); p=<x,y>\<rbrakk> \<Longrightarrow> c(x,y):C(<x,y>)\<rbrakk> \<Longrightarrow> split(p,c):C(p)" by ncanT lemma whenT: "\<lbrakk>p:A+B; \<And>x. \<lbrakk>x:A; p=inl(x)\<rbrakk> \<Longrightarrow> a(x):C(inl(x)); \<And>y. \<lbrakk>y:B; p=inr(y)\<rbrakk> \<Longrightarrow> b(y):C(inr(y))\<rbrakk> \<Longrightarrow> when(p,a,b) : C(p)" by ncanT lemmas ncanTs = ifT applyT splitT whenT subsection \<open>Subtypes\<close> lemma SubtypeD1: "a : Subtype(A, P) \<Longrightarrow> a : A" and SubtypeD2: "a : Subtype(A, P) \<Longrightarrow> P(a)" by (simp_all add: SubtypeXH) lemma SubtypeI: "\<lbrakk>a:A; P(a)\<rbrakk> \<Longrightarrow> a : {x:A. P(x)}" by (simp add: SubtypeXH) lemma SubtypeE: "\<lbrakk>a : {x:A. P(x)}; \<lbrakk>a:A; P(a)\<rbrakk> \<Longrightarrow> Q\<rbrakk> \<Longrightarrow> Q" by (simp add: SubtypeXH) subsection \<open>Monotonicity\<close> lemma idM: "mono (\<lambda>X. X)" apply (rule monoI) apply assumption done lemma constM: "mono(\<lambda>X. A)" apply (rule monoI) apply (rule subset_refl) done lemma "mono(\<lambda>X. A(X)) \<Longrightarrow> mono(\<lambda>X.[A(X)])" apply (rule subsetI [THEN monoI]) apply (drule LiftXH [THEN iffD1]) apply (erule disjE) apply (erule disjI1 [THEN LiftXH [THEN iffD2]]) apply (rule disjI2 [THEN LiftXH [THEN iffD2]]) apply (drule (1) monoD) apply blast done lemma SgM: "\<lbrakk>mono(\<lambda>X. A(X)); \<And>x X. x:A(X) \<Longrightarrow> mono(\<lambda>X. B(X,x))\<rbrakk> \<Longrightarrow> mono(\<lambda>X. Sigma(A(X),B(X)))" by (blast intro!: subsetI [THEN monoI] canTs elim!: case_rls dest!: monoD [THEN subsetD]) lemma PiM: "(\<And>x. x:A \<Longrightarrow> mono(\<lambda>X. B(X,x))) \<Longrightarrow> mono(\<lambda>X. Pi(A,B(X)))" by (blast intro!: subsetI [THEN monoI] canTs elim!: case_rls dest!: monoD [THEN subsetD]) lemma PlusM: "\<lbrakk>mono(\<lambda>X. A(X)); mono(\<lambda>X. B(X))\<rbrakk> \<Longrightarrow> mono(\<lambda>X. A(X)+B(X))" by (blast intro!: subsetI [THEN monoI] canTs elim!: case_rls dest!: monoD [THEN subsetD]) subsection \<open>Recursive types\<close> subsubsection \<open>Conversion Rules for Fixed Points via monotonicity and Tarski\<close> lemma NatM: "mono(\<lambda>X. Unit+X)" apply (rule PlusM constM idM)+ done lemma def_NatB: "Nat = Unit + Nat" apply (rule def_lfp_Tarski [OF Nat_def]) apply (rule NatM) done lemma ListM: "mono(\<lambda>X.(Unit+Sigma(A,\<lambda>y. X)))" apply (rule PlusM SgM constM idM)+ done lemma def_ListB: "List(A) = Unit + A * List(A)" apply (rule def_lfp_Tarski [OF List_def]) apply (rule ListM) done lemma def_ListsB: "Lists(A) = Unit + A * Lists(A)" apply (rule def_gfp_Tarski [OF Lists_def]) apply (rule ListM) done lemma IListsM: "mono(\<lambda>X.({} + Sigma(A,\<lambda>y. X)))" apply (rule PlusM SgM constM idM)+ done lemma def_IListsB: "ILists(A) = {} + A * ILists(A)" apply (rule def_gfp_Tarski [OF ILists_def]) apply (rule IListsM) done lemmas ind_type_eqs = def_NatB def_ListB def_ListsB def_IListsB subsection \<open>Exhaustion Rules\<close> lemma NatXH: "a : Nat \<longleftrightarrow> (a=zero | (EX x:Nat. a=succ(x)))" and ListXH: "a : List(A) \<longleftrightarrow> (a=[] | (EX x:A. EX xs:List(A).a=x$xs))" and ListsXH: "a : Lists(A) \<longleftrightarrow> (a=[] | (EX x:A. EX xs:Lists(A).a=x$xs))" and IListsXH: "a : ILists(A) \<longleftrightarrow> (EX x:A. EX xs:ILists(A).a=x$xs)" unfolding ind_data_defs by (rule ind_type_eqs [THEN XHlemma1], blast intro!: canTs elim!: case_rls)+ lemmas iXHs = NatXH ListXH ML \<open>ML_Thms.bind_thms ("icase_rls", XH_to_Es @{thms iXHs})\<close> subsection \<open>Type Rules\<close> lemma zeroT: "zero : Nat" and succT: "n:Nat \<Longrightarrow> succ(n) : Nat" and nilT: "[] : List(A)" and consT: "\<lbrakk>h:A; t:List(A)\<rbrakk> \<Longrightarrow> h$t : List(A)" by (blast intro: iXHs [THEN iffD2])+ lemmas icanTs = zeroT succT nilT consT method_setup incanT = \<open> Scan.succeed (SIMPLE_METHOD' o mk_ncanT_tac @{thms icase_rls} @{thms case_rls}) \<close> lemma ncaseT: "\<lbrakk>n:Nat; n=zero \<Longrightarrow> b:C(zero); \<And>x. \<lbrakk>x:Nat; n=succ(x)\<rbrakk> \<Longrightarrow> c(x):C(succ(x))\<rbrakk> \<Longrightarrow> ncase(n,b,c) : C(n)" by incanT lemma lcaseT: "\<lbrakk>l:List(A); l = [] \<Longrightarrow> b:C([]); \<And>h t. \<lbrakk>h:A; t:List(A); l=h$t\<rbrakk> \<Longrightarrow> c(h,t):C(h$t)\<rbrakk> \<Longrightarrow> lcase(l,b,c) : C(l)" by incanT lemmas incanTs = ncaseT lcaseT subsection \<open>Induction Rules\<close> lemmas ind_Ms = NatM ListM lemma Nat_ind: "\<lbrakk>n:Nat; P(zero); \<And>x. \<lbrakk>x:Nat; P(x)\<rbrakk> \<Longrightarrow> P(succ(x))\<rbrakk> \<Longrightarrow> P(n)" apply (unfold ind_data_defs) apply (erule def_induct [OF Nat_def _ NatM]) apply (blast intro: canTs elim!: case_rls) done lemma List_ind: "\<lbrakk>l:List(A); P([]); \<And>x xs. \<lbrakk>x:A; xs:List(A); P(xs)\<rbrakk> \<Longrightarrow> P(x$xs)\<rbrakk> \<Longrightarrow> P(l)" apply (unfold ind_data_defs) apply (erule def_induct [OF List_def _ ListM]) apply (blast intro: canTs elim!: case_rls) done lemmas inds = Nat_ind List_ind subsection \<open>Primitive Recursive Rules\<close> lemma nrecT: "\<lbrakk>n:Nat; b:C(zero); \<And>x g. \<lbrakk>x:Nat; g:C(x)\<rbrakk> \<Longrightarrow> c(x,g):C(succ(x))\<rbrakk> \<Longrightarrow> nrec(n,b,c) : C(n)" by (erule Nat_ind) auto lemma lrecT: "\<lbrakk>l:List(A); b:C([]); \<And>x xs g. \<lbrakk>x:A; xs:List(A); g:C(xs)\<rbrakk> \<Longrightarrow> c(x,xs,g):C(x$xs) \<rbrakk> \<Longrightarrow> lrec(l,b,c) : C(l)" by (erule List_ind) auto lemmas precTs = nrecT lrecT subsection \<open>Theorem proving\<close> lemma SgE2: "\<lbrakk><a,b> : Sigma(A,B); \<lbrakk>a:A; b:B(a)\<rbrakk> \<Longrightarrow> P\<rbrakk> \<Longrightarrow> P" unfolding SgXH by blast (* General theorem proving ignores non-canonical term-formers, *) (* - intro rules are type rules for canonical terms *) (* - elim rules are case rules (no non-canonical terms appear) *) ML \<open>ML_Thms.bind_thms ("XHEs", XH_to_Es @{thms XHs})\<close> lemmas [intro!] = SubtypeI canTs icanTs and [elim!] = SubtypeE XHEs subsection \<open>Infinite Data Types\<close> lemma lfp_subset_gfp: "mono(f) \<Longrightarrow> lfp(f) <= gfp(f)" apply (rule lfp_lowerbound [THEN subset_trans]) apply (erule gfp_lemma3) apply (rule subset_refl) done lemma gfpI: assumes "a:A" and "\<And>x X. \<lbrakk>x:A; ALL y:A. t(y):X\<rbrakk> \<Longrightarrow> t(x) : B(X)" shows "t(a) : gfp(B)" apply (rule coinduct) apply (rule_tac P = "\<lambda>x. EX y:A. x=t (y)" in CollectI) apply (blast intro!: assms)+ done lemma def_gfpI: "\<lbrakk>C == gfp(B); a:A; \<And>x X. \<lbrakk>x:A; ALL y:A. t(y):X\<rbrakk> \<Longrightarrow> t(x) : B(X)\<rbrakk> \<Longrightarrow> t(a) : C" apply unfold apply (erule gfpI) apply blast done (* EG *) lemma "letrec g x be zero$g(x) in g(bot) : Lists(Nat)" apply (rule refl [THEN UnitXH [THEN iffD2], THEN Lists_def [THEN def_gfpI]]) apply (subst letrecB) apply (unfold cons_def) apply blast done subsection \<open>Lemmas and tactics for using the rule \<open>coinduct3\<close> on \<open>[=\<close> and \<open>=\<close>\<close> lemma lfpI: "\<lbrakk>mono(f); a : f(lfp(f))\<rbrakk> \<Longrightarrow> a : lfp(f)" apply (erule lfp_Tarski [THEN ssubst]) apply assumption done lemma ssubst_single: "\<lbrakk>a = a'; a' : A\<rbrakk> \<Longrightarrow> a : A" by simp lemma ssubst_pair: "\<lbrakk>a = a'; b = b'; <a',b'> : A\<rbrakk> \<Longrightarrow> <a,b> : A" by simp ML \<open> val coinduct3_tac = SUBPROOF (fn {context = ctxt, prems = mono :: prems, ...} => fast_tac (ctxt addIs (mono RS @{thm coinduct3_mono_lemma} RS @{thm lfpI}) :: prems) 1); \<close> method_setup coinduct3 = \<open>Scan.succeed (SIMPLE_METHOD' o coinduct3_tac)\<close> lemma ci3_RI: "\<lbrakk>mono(Agen); a : R\<rbrakk> \<Longrightarrow> a : lfp(\<lambda>x. Agen(x) Un R Un A)" by coinduct3 lemma ci3_AgenI: "\<lbrakk>mono(Agen); a : Agen(lfp(\<lambda>x. Agen(x) Un R Un A))\<rbrakk> \<Longrightarrow> a : lfp(\<lambda>x. Agen(x) Un R Un A)" by coinduct3 lemma ci3_AI: "\<lbrakk>mono(Agen); a : A\<rbrakk> \<Longrightarrow> a : lfp(\<lambda>x. Agen(x) Un R Un A)" by coinduct3 ML \<open> fun genIs_tac ctxt genXH gen_mono = resolve_tac ctxt [genXH RS @{thm iffD2}] THEN' simp_tac ctxt THEN' TRY o fast_tac (ctxt addIs [genXH RS @{thm iffD2}, gen_mono RS @{thm coinduct3_mono_lemma} RS @{thm lfpI}]) \<close> method_setup genIs = \<open> Attrib.thm -- Attrib.thm >> (fn (genXH, gen_mono) => fn ctxt => SIMPLE_METHOD' (genIs_tac ctxt genXH gen_mono)) \<close> subsection \<open>POgen\<close> lemma PO_refl: "<a,a> : PO" by (rule po_refl [THEN PO_iff [THEN iffD1]]) lemma POgenIs: "<true,true> : POgen(R)" "<false,false> : POgen(R)" "\<lbrakk><a,a'> : R; <b,b'> : R\<rbrakk> \<Longrightarrow> <<a,b>,<a',b'>> : POgen(R)" "\<And>b b'. (\<And>x. <b(x),b'(x)> : R) \<Longrightarrow> <lam x. b(x),lam x. b'(x)> : POgen(R)" "<one,one> : POgen(R)" "<a,a'> : lfp(\<lambda>x. POgen(x) Un R Un PO) \<Longrightarrow> <inl(a),inl(a')> : POgen(lfp(\<lambda>x. POgen(x) Un R Un PO))" "<b,b'> : lfp(\<lambda>x. POgen(x) Un R Un PO) \<Longrightarrow> <inr(b),inr(b')> : POgen(lfp(\<lambda>x. POgen(x) Un R Un PO))" "<zero,zero> : POgen(lfp(\<lambda>x. POgen(x) Un R Un PO))" "<n,n'> : lfp(\<lambda>x. POgen(x) Un R Un PO) \<Longrightarrow> <succ(n),succ(n')> : POgen(lfp(\<lambda>x. POgen(x) Un R Un PO))" "<[],[]> : POgen(lfp(\<lambda>x. POgen(x) Un R Un PO))" "\<lbrakk><h,h'> : lfp(\<lambda>x. POgen(x) Un R Un PO); <t,t'> : lfp(\<lambda>x. POgen(x) Un R Un PO)\<rbrakk> \<Longrightarrow> <h$t,h'$t'> : POgen(lfp(\<lambda>x. POgen(x) Un R Un PO))" unfolding data_defs by (genIs POgenXH POgen_mono)+ ML \<open> fun POgen_tac ctxt (rla, rlb) i = SELECT_GOAL (safe_tac ctxt) i THEN resolve_tac ctxt [rlb RS (rla RS @{thm ssubst_pair})] i THEN (REPEAT (resolve_tac ctxt (@{thms POgenIs} @ [@{thm PO_refl} RS (@{thm POgen_mono} RS @{thm ci3_AI})] @ (@{thms POgenIs} RL [@{thm POgen_mono} RS @{thm ci3_AgenI}]) @ [@{thm POgen_mono} RS @{thm ci3_RI}]) i)) \<close> subsection \<open>EQgen\<close> lemma EQ_refl: "<a,a> : EQ" by (rule refl [THEN EQ_iff [THEN iffD1]]) lemma EQgenIs: "<true,true> : EQgen(R)" "<false,false> : EQgen(R)" "\<lbrakk><a,a'> : R; <b,b'> : R\<rbrakk> \<Longrightarrow> <<a,b>,<a',b'>> : EQgen(R)" "\<And>b b'. (\<And>x. <b(x),b'(x)> : R) \<Longrightarrow> <lam x. b(x),lam x. b'(x)> : EQgen(R)" "<one,one> : EQgen(R)" "<a,a'> : lfp(\<lambda>x. EQgen(x) Un R Un EQ) \<Longrightarrow> <inl(a),inl(a')> : EQgen(lfp(\<lambda>x. EQgen(x) Un R Un EQ))" "<b,b'> : lfp(\<lambda>x. EQgen(x) Un R Un EQ) \<Longrightarrow> <inr(b),inr(b')> : EQgen(lfp(\<lambda>x. EQgen(x) Un R Un EQ))" "<zero,zero> : EQgen(lfp(\<lambda>x. EQgen(x) Un R Un EQ))" "<n,n'> : lfp(\<lambda>x. EQgen(x) Un R Un EQ) \<Longrightarrow> <succ(n),succ(n')> : EQgen(lfp(\<lambda>x. EQgen(x) Un R Un EQ))" "<[],[]> : EQgen(lfp(\<lambda>x. EQgen(x) Un R Un EQ))" "\<lbrakk><h,h'> : lfp(\<lambda>x. EQgen(x) Un R Un EQ); <t,t'> : lfp(\<lambda>x. EQgen(x) Un R Un EQ)\<rbrakk> \<Longrightarrow> <h$t,h'$t'> : EQgen(lfp(\<lambda>x. EQgen(x) Un R Un EQ))" unfolding data_defs by (genIs EQgenXH EQgen_mono)+ ML \<open> fun EQgen_raw_tac ctxt i = (REPEAT (resolve_tac ctxt (@{thms EQgenIs} @ [@{thm EQ_refl} RS (@{thm EQgen_mono} RS @{thm ci3_AI})] @ (@{thms EQgenIs} RL [@{thm EQgen_mono} RS @{thm ci3_AgenI}]) @ [@{thm EQgen_mono} RS @{thm ci3_RI}]) i)) (* Goals of the form R <= EQgen(R) - rewrite elements <a,b> : EQgen(R) using rews and *) (* then reduce this to a goal <a',b'> : R (hopefully?) *) (* rews are rewrite rules that would cause looping in the simpifier *) fun EQgen_tac ctxt rews i = SELECT_GOAL (TRY (safe_tac ctxt) THEN resolve_tac ctxt ((rews @ [@{thm refl}]) RL ((rews @ [@{thm refl}]) RL [@{thm ssubst_pair}])) i THEN ALLGOALS (simp_tac ctxt) THEN ALLGOALS (EQgen_raw_tac ctxt)) i \<close> method_setup EQgen = \<open> Attrib.thms >> (fn ths => fn ctxt => SIMPLE_METHOD' (EQgen_tac ctxt ths)) \<close> end
Require Import OrderedType. Require Import OrderedTypeEx. Module Type PairOrderedType_Type (O1 O2:OrderedType). Module MO1:=OrderedTypeFacts(O1). Module MO2:=OrderedTypeFacts(O2). Definition t := prod O1.t O2.t. Definition eq x y := O1.eq (fst x) (fst y) /\ O2.eq (snd x) (snd y). Definition lt x y := O1.lt (fst x) (fst y) \/ (O1.eq (fst x) (fst y) /\ O2.lt (snd x) (snd y)). Parameter eq_refl : forall x : t, eq x x. Parameter eq_sym : forall x y : t, eq x y -> eq y x. Parameter eq_trans : forall x y z : t, eq x y -> eq y z -> eq x z. Parameter lt_trans : forall x y z : t, lt x y -> lt y z -> lt x z. Parameter lt_not_eq : forall x y : t, lt x y -> ~ eq x y. Parameter compare : forall x y : t, Compare lt eq x y. Parameter eq_dec : forall x y : t, {eq x y} + {~ eq x y}. End PairOrderedType_Type.
theory T154 imports Main begin lemma "( (\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) & (\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, meet(y, z)) = meet(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(meet(x, y), z) = meet(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(x, join(y, z)) = join(undr(x, y), undr(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(join(x, y), z) = join(over(x, z), over(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(meet(x, y), z) = join(undr(x, z), undr(y, z))) & (\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) & (\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) & (\<forall> x::nat. invo(invo(x)) = x) ) \<longrightarrow> (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(x, meet(y, z)) = join(over(x, y), over(x, z))) " nitpick[card nat=8,timeout=86400] oops end
[STATEMENT] lemma zero_assoc3: "(x \<cdot> y) \<cdot> 0 = x \<cdot> (y \<cdot> 0)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. x \<cdot> y \<cdot> (0::'a) = x \<cdot> (y \<cdot> (0::'a)) [PROOF STEP] by (metis local.cl5 local.s_prod_annil)
State Before: G₀ : Type u_1 inst✝ : GroupWithZero G₀ a✝ : G₀ m✝ n✝ : ℕ a : G₀ m n : ℕ h : n < m ⊢ a ^ (m - n) = a ^ m * (a ^ n)⁻¹ State After: case inl G₀ : Type u_1 inst✝ : GroupWithZero G₀ a : G₀ m✝ n✝ m n : ℕ h : n < m ⊢ 0 ^ (m - n) = 0 ^ m * (0 ^ n)⁻¹ case inr G₀ : Type u_1 inst✝ : GroupWithZero G₀ a✝ : G₀ m✝ n✝ : ℕ a : G₀ m n : ℕ h : n < m ha : a ≠ 0 ⊢ a ^ (m - n) = a ^ m * (a ^ n)⁻¹ Tactic: obtain rfl | ha := eq_or_ne a 0 State Before: case inl G₀ : Type u_1 inst✝ : GroupWithZero G₀ a : G₀ m✝ n✝ m n : ℕ h : n < m ⊢ 0 ^ (m - n) = 0 ^ m * (0 ^ n)⁻¹ State After: no goals Tactic: rw [zero_pow (tsub_pos_of_lt h), zero_pow (n.zero_le.trans_lt h), zero_mul] State Before: case inr G₀ : Type u_1 inst✝ : GroupWithZero G₀ a✝ : G₀ m✝ n✝ : ℕ a : G₀ m n : ℕ h : n < m ha : a ≠ 0 ⊢ a ^ (m - n) = a ^ m * (a ^ n)⁻¹ State After: no goals Tactic: exact pow_sub₀ _ ha h.le
The Chronicle of Ireland records that in 431 AD Bishop Palladius arrived in Ireland on a mission from Pope Celestine I to minister to the Irish " already believing in Christ " . The same chronicle records that Saint Patrick , Ireland 's best known patron saint , arrived the following year . There is continued debate over the missions of Palladius and Patrick but the consensus is that they both took place and that the older druid tradition collapsed in the face of the new religion . Irish Christian scholars excelled in the study of Latin and Greek learning and Christian theology . In the monastic culture that followed the Christianisation of Ireland , Latin and Greek learning was preserved in Ireland during the Early Middle Ages in contrast to elsewhere in Europe , where the Dark Ages followed the decline of the Roman Empire .
(** Fixed precision machine words *) Require Import Coq.Arith.Arith Coq.Arith.Div2 Coq.NArith.NArith Coq.Bool.Bool Coq.omega.Omega. Require Import Bedrock.Nomega. Set Implicit Arguments. (** * Basic definitions and conversion to and from [nat] *) Inductive word : nat -> Set := | WO : word O | WS : bool -> forall n, word n -> word (S n). Fixpoint wordToNat sz (w : word sz) : nat := match w with | WO => O | WS false _ w' => (wordToNat w') * 2 | WS true _ w' => S (wordToNat w' * 2) end. Fixpoint wordToNat' sz (w : word sz) : nat := match w with | WO => O | WS false _ w' => 2 * wordToNat w' | WS true _ w' => S (2 * wordToNat w') end. Theorem wordToNat_wordToNat' : forall sz (w : word sz), wordToNat w = wordToNat' w. Proof. induction w. auto. simpl. rewrite mult_comm. reflexivity. Qed. Fixpoint mod2 (n : nat) : bool := match n with | 0 => false | 1 => true | S (S n') => mod2 n' end. Fixpoint natToWord (sz n : nat) : word sz := match sz with | O => WO | S sz' => WS (mod2 n) (natToWord sz' (div2 n)) end. Fixpoint wordToN sz (w : word sz) : N := match w with | WO => 0 | WS false _ w' => 2 * wordToN w' | WS true _ w' => Nsucc (2 * wordToN w') end%N. Definition Nmod2 (n : N) : bool := match n with | N0 => false | Npos (xO _) => false | _ => true end. Definition wzero sz := natToWord sz 0. Fixpoint wzero' (sz : nat) : word sz := match sz with | O => WO | S sz' => WS false (wzero' sz') end. Fixpoint posToWord (sz : nat) (p : positive) {struct p} : word sz := match sz with | O => WO | S sz' => match p with | xI p' => WS true (posToWord sz' p') | xO p' => WS false (posToWord sz' p') | xH => WS true (wzero' sz') end end. Definition NToWord (sz : nat) (n : N) : word sz := match n with | N0 => wzero' sz | Npos p => posToWord sz p end. Fixpoint Npow2 (n : nat) : N := match n with | O => 1 | S n' => 2 * Npow2 n' end%N. Ltac rethink := match goal with | [ H : ?f ?n = _ |- ?f ?m = _ ] => replace m with n; simpl; auto end. Theorem mod2_S_double : forall n, mod2 (S (2 * n)) = true. induction n; simpl; intuition; rethink. Qed. Theorem mod2_double : forall n, mod2 (2 * n) = false. induction n; simpl; intuition; rewrite <- plus_n_Sm; rethink. Qed. Local Hint Resolve mod2_S_double mod2_double. Theorem div2_double : forall n, div2 (2 * n) = n. induction n; simpl; intuition; rewrite <- plus_n_Sm; f_equal; rethink. Qed. Theorem div2_S_double : forall n, div2 (S (2 * n)) = n. induction n; simpl; intuition; f_equal; rethink. Qed. Hint Rewrite div2_double div2_S_double : div2. Theorem natToWord_wordToNat : forall sz w, natToWord sz (wordToNat w) = w. induction w; rewrite wordToNat_wordToNat'; intuition; f_equal; unfold natToWord, wordToNat'; fold natToWord; fold wordToNat'; destruct b; f_equal; autorewrite with div2; intuition. Qed. Fixpoint pow2 (n : nat) : nat := match n with | O => 1 | S n' => 2 * pow2 n' end. Theorem roundTrip_0 : forall sz, wordToNat (natToWord sz 0) = 0. induction sz; simpl; intuition. Qed. Hint Rewrite roundTrip_0 : wordToNat. Local Hint Extern 1 (@eq nat _ _) => omega. Theorem untimes2 : forall n, n + (n + 0) = 2 * n. auto. Qed. Section strong. Variable P : nat -> Prop. Hypothesis PH : forall n, (forall m, m < n -> P m) -> P n. Lemma strong' : forall n m, m <= n -> P m. induction n; simpl; intuition; apply PH; intuition. elimtype False; omega. Qed. Theorem strong : forall n, P n. intros; eapply strong'; eauto. Qed. End strong. Theorem div2_odd : forall n, mod2 n = true -> n = S (2 * div2 n). induction n using strong; simpl; intuition. destruct n; simpl in *; intuition. discriminate. destruct n; simpl in *; intuition. do 2 f_equal. replace (div2 n + S (div2 n + 0)) with (S (div2 n + (div2 n + 0))); auto. Qed. Theorem div2_even : forall n, mod2 n = false -> n = 2 * div2 n. induction n using strong; simpl; intuition. destruct n; simpl in *; intuition. destruct n; simpl in *; intuition. discriminate. f_equal. replace (div2 n + S (div2 n + 0)) with (S (div2 n + (div2 n + 0))); auto. Qed. Lemma wordToNat_natToWord' : forall sz w, exists k, wordToNat (natToWord sz w) + k * pow2 sz = w. induction sz; simpl; intuition; repeat rewrite untimes2. exists w; intuition. case_eq (mod2 w); intro Hmw. specialize (IHsz (div2 w)); firstorder. rewrite wordToNat_wordToNat' in *. exists x; intuition. rewrite mult_assoc. rewrite (mult_comm x 2). rewrite mult_comm. simpl mult at 1. rewrite (plus_Sn_m (2 * wordToNat' (natToWord sz (div2 w)))). rewrite <- mult_assoc. rewrite <- mult_plus_distr_l. rewrite H; clear H. symmetry; apply div2_odd; auto. specialize (IHsz (div2 w)); firstorder. exists x; intuition. rewrite mult_assoc. rewrite (mult_comm x 2). rewrite <- mult_assoc. rewrite mult_comm. rewrite <- mult_plus_distr_l. rewrite H; clear H. symmetry; apply div2_even; auto. Qed. Theorem wordToNat_natToWord : forall sz w, exists k, wordToNat (natToWord sz w) = w - k * pow2 sz /\ k * pow2 sz <= w. intros; destruct (wordToNat_natToWord' sz w) as [k]; exists k; intuition. Qed. Definition wone sz := natToWord sz 1. Fixpoint wones (sz : nat) : word sz := match sz with | O => WO | S sz' => WS true (wones sz') end. (** Comparisons *) Fixpoint wmsb sz (w : word sz) (a : bool) : bool := match w with | WO => a | WS b _ x => wmsb x b end. Definition whd sz (w : word (S sz)) : bool := match w in word sz' return match sz' with | O => unit | S _ => bool end with | WO => tt | WS b _ _ => b end. Definition wtl sz (w : word (S sz)) : word sz := match w in word sz' return match sz' with | O => unit | S sz'' => word sz'' end with | WO => tt | WS _ _ w' => w' end. Theorem WS_neq : forall b1 b2 sz (w1 w2 : word sz), (b1 <> b2 \/ w1 <> w2) -> WS b1 w1 <> WS b2 w2. intuition. apply (f_equal (@whd _)) in H0; tauto. apply (f_equal (@wtl _)) in H0; tauto. Qed. (** Shattering **) Lemma shatter_word : forall n (a : word n), match n return word n -> Prop with | O => fun a => a = WO | S _ => fun a => a = WS (whd a) (wtl a) end a. destruct a; eauto. Qed. Lemma shatter_word_S : forall n (a : word (S n)), exists b, exists c, a = WS b c. Proof. intros; repeat eexists; apply (shatter_word a). Qed. Lemma shatter_word_0 : forall a : word 0, a = WO. Proof. intros; apply (shatter_word a). Qed. Hint Resolve shatter_word_0. Require Import Coq.Logic.Eqdep_dec. Definition weq : forall sz (x y : word sz), {x = y} + {x <> y}. refine (fix weq sz (x : word sz) : forall y : word sz, {x = y} + {x <> y} := match x in word sz return forall y : word sz, {x = y} + {x <> y} with | WO => fun _ => left _ _ | WS b _ x' => fun y => if bool_dec b (whd y) then if weq _ x' (wtl y) then left _ _ else right _ _ else right _ _ end); clear weq. abstract (symmetry; apply shatter_word_0). abstract (subst; symmetry; apply (shatter_word y)). abstract (rewrite (shatter_word y); simpl; intro; injection H; intros; apply _H0; apply inj_pair2_eq_dec in H0; [ auto | apply eq_nat_dec ]). abstract (rewrite (shatter_word y); simpl; intro; apply _H; injection H; auto). Defined. Fixpoint weqb sz (x : word sz) : word sz -> bool := match x in word sz return word sz -> bool with | WO => fun _ => true | WS b _ x' => fun y => if eqb b (whd y) then if @weqb _ x' (wtl y) then true else false else false end. Theorem weqb_true_iff : forall sz x y, @weqb sz x y = true <-> x = y. Proof. induction x; simpl; intros. { split; auto. } { rewrite (shatter_word y) in *. simpl in *. case_eq (eqb b (whd y)); intros. case_eq (weqb x (wtl y)); intros. split; auto; intros. rewrite eqb_true_iff in H. f_equal; eauto. eapply IHx; eauto. split; intros; try congruence. inversion H1; clear H1; subst. eapply inj_pair2_eq_dec in H4. eapply IHx in H4. congruence. eapply Peano_dec.eq_nat_dec. split; intros; try congruence. inversion H0. apply eqb_false_iff in H. congruence. } Qed. (** * Combining and splitting *) Fixpoint combine (sz1 : nat) (w : word sz1) : forall sz2, word sz2 -> word (sz1 + sz2) := match w in word sz1 return forall sz2, word sz2 -> word (sz1 + sz2) with | WO => fun _ w' => w' | WS b _ w' => fun _ w'' => WS b (combine w' w'') end. Fixpoint split1 (sz1 sz2 : nat) : word (sz1 + sz2) -> word sz1 := match sz1 with | O => fun _ => WO | S sz1' => fun w => WS (whd w) (split1 sz1' sz2 (wtl w)) end. Fixpoint split2 (sz1 sz2 : nat) : word (sz1 + sz2) -> word sz2 := match sz1 with | O => fun w => w | S sz1' => fun w => split2 sz1' sz2 (wtl w) end. Ltac shatterer := simpl; intuition; match goal with | [ w : _ |- _ ] => rewrite (shatter_word w); simpl end; f_equal; auto. Theorem combine_split : forall sz1 sz2 (w : word (sz1 + sz2)), combine (split1 sz1 sz2 w) (split2 sz1 sz2 w) = w. induction sz1; shatterer. Qed. Theorem split1_combine : forall sz1 sz2 (w : word sz1) (z : word sz2), split1 sz1 sz2 (combine w z) = w. induction sz1; shatterer. Qed. Theorem split2_combine : forall sz1 sz2 (w : word sz1) (z : word sz2), split2 sz1 sz2 (combine w z) = z. induction sz1; shatterer. Qed. Require Import Coq.Logic.Eqdep_dec. Theorem combine_assoc : forall n1 (w1 : word n1) n2 n3 (w2 : word n2) (w3 : word n3) Heq, combine (combine w1 w2) w3 = match Heq in _ = N return word N with | refl_equal => combine w1 (combine w2 w3) end. induction w1; simpl; intuition. rewrite (UIP_dec eq_nat_dec Heq (refl_equal _)); reflexivity. rewrite (IHw1 _ _ _ _ (plus_assoc _ _ _)); clear IHw1. repeat match goal with | [ |- context[match ?pf with refl_equal => _ end] ] => generalize pf end. generalize dependent (combine w1 (combine w2 w3)). rewrite plus_assoc; intros. rewrite (UIP_dec eq_nat_dec e (refl_equal _)). rewrite (UIP_dec eq_nat_dec Heq0 (refl_equal _)). reflexivity. Qed. Theorem split2_iter : forall n1 n2 n3 Heq w, split2 n2 n3 (split2 n1 (n2 + n3) w) = split2 (n1 + n2) n3 (match Heq in _ = N return word N with | refl_equal => w end). induction n1; simpl; intuition. rewrite (UIP_dec eq_nat_dec Heq (refl_equal _)); reflexivity. rewrite (IHn1 _ _ (plus_assoc _ _ _)). f_equal. repeat match goal with | [ |- context[match ?pf with refl_equal => _ end] ] => generalize pf end. generalize dependent w. simpl. fold plus. generalize (n1 + (n2 + n3)); clear. intros. generalize Heq e. subst. intros. rewrite (UIP_dec eq_nat_dec e (refl_equal _)). rewrite (UIP_dec eq_nat_dec Heq0 (refl_equal _)). reflexivity. Qed. Theorem combine_end : forall n1 n2 n3 Heq w, combine (split1 n2 n3 (split2 n1 (n2 + n3) w)) (split2 (n1 + n2) n3 (match Heq in _ = N return word N with | refl_equal => w end)) = split2 n1 (n2 + n3) w. induction n1; simpl; intros. rewrite (UIP_dec eq_nat_dec Heq (refl_equal _)). apply combine_split. rewrite (shatter_word w) in *. simpl. eapply trans_eq; [ | apply IHn1 with (Heq := plus_assoc _ _ _) ]; clear IHn1. repeat f_equal. repeat match goal with | [ |- context[match ?pf with refl_equal => _ end] ] => generalize pf end. simpl. generalize dependent w. rewrite plus_assoc. intros. rewrite (UIP_dec eq_nat_dec e (refl_equal _)). rewrite (UIP_dec eq_nat_dec Heq0 (refl_equal _)). reflexivity. Qed. (** * Extension operators *) Definition sext (sz : nat) (w : word sz) (sz' : nat) : word (sz + sz') := if wmsb w false then combine w (wones sz') else combine w (wzero sz'). Definition zext (sz : nat) (w : word sz) (sz' : nat) : word (sz + sz') := combine w (wzero sz'). (** * Arithmetic *) Definition wneg sz (x : word sz) : word sz := NToWord sz (Npow2 sz - wordToN x). Definition wordBin (f : N -> N -> N) sz (x y : word sz) : word sz := NToWord sz (f (wordToN x) (wordToN y)). Definition wplus := wordBin Nplus. Definition wmult := wordBin Nmult. Definition wmult' sz (x y : word sz) : word sz := split2 sz sz (NToWord (sz + sz) (Nmult (wordToN x) (wordToN y))). Definition wminus sz (x y : word sz) : word sz := wplus x (wneg y). Definition wnegN sz (x : word sz) : word sz := natToWord sz (pow2 sz - wordToNat x). Definition wordBinN (f : nat -> nat -> nat) sz (x y : word sz) : word sz := natToWord sz (f (wordToNat x) (wordToNat y)). Definition wplusN := wordBinN plus. Definition wmultN := wordBinN mult. Definition wmultN' sz (x y : word sz) : word sz := split2 sz sz (natToWord (sz + sz) (mult (wordToNat x) (wordToNat y))). Definition wminusN sz (x y : word sz) : word sz := wplusN x (wnegN y). (** * Notations *) Delimit Scope word_scope with word. Bind Scope word_scope with word. Notation "w ~ 1" := (WS true w) (at level 7, left associativity, format "w '~' '1'") : word_scope. Notation "w ~ 0" := (WS false w) (at level 7, left associativity, format "w '~' '0'") : word_scope. Notation "^~" := wneg. Notation "l ^+ r" := (@wplus _ l%word r%word) (at level 50, left associativity). Notation "l ^* r" := (@wmult _ l%word r%word) (at level 40, left associativity). Notation "l ^- r" := (@wminus _ l%word r%word) (at level 50, left associativity). Theorem wordToN_nat : forall sz (w : word sz), wordToN w = N_of_nat (wordToNat w). induction w; intuition. destruct b; unfold wordToN, wordToNat; fold wordToN; fold wordToNat. rewrite N_of_S. rewrite N_of_mult. rewrite <- IHw. rewrite Nmult_comm. reflexivity. rewrite N_of_mult. rewrite <- IHw. rewrite Nmult_comm. reflexivity. Qed. Theorem mod2_S : forall n k, 2 * k = S n -> mod2 n = true. induction n using strong; intros. destruct n; simpl in *. elimtype False; omega. destruct n; simpl in *; auto. destruct k; simpl in *. discriminate. apply H with k; auto. Qed. Theorem wzero'_def : forall sz, wzero' sz = wzero sz. unfold wzero; induction sz; simpl; intuition. congruence. Qed. Theorem posToWord_nat : forall p sz, posToWord sz p = natToWord sz (nat_of_P p). induction p; destruct sz; simpl; intuition; f_equal; try rewrite wzero'_def in *. rewrite ZL6. destruct (ZL4 p) as [? Heq]; rewrite Heq; simpl. replace (x + S x) with (S (2 * x)) by omega. symmetry; apply mod2_S_double. rewrite IHp. rewrite ZL6. destruct (nat_of_P p); simpl; intuition. replace (n + S n) with (S (2 * n)) by omega. rewrite div2_S_double; auto. unfold nat_of_P; simpl. rewrite ZL6. replace (nat_of_P p + nat_of_P p) with (2 * nat_of_P p) by omega. symmetry; apply mod2_double. rewrite IHp. unfold nat_of_P; simpl. rewrite ZL6. replace (nat_of_P p + nat_of_P p) with (2 * nat_of_P p) by omega. rewrite div2_double. auto. auto. Qed. Theorem NToWord_nat : forall sz n, NToWord sz n = natToWord sz (nat_of_N n). destruct n; simpl; intuition; try rewrite wzero'_def in *. auto. apply posToWord_nat. Qed. Theorem wplus_alt : forall sz (x y : word sz), wplus x y = wplusN x y. unfold wplusN, wplus, wordBinN, wordBin; intros. repeat rewrite wordToN_nat; repeat rewrite NToWord_nat. rewrite nat_of_Nplus. repeat rewrite nat_of_N_of_nat. reflexivity. Qed. Theorem wmult_alt : forall sz (x y : word sz), wmult x y = wmultN x y. unfold wmultN, wmult, wordBinN, wordBin; intros. repeat rewrite wordToN_nat; repeat rewrite NToWord_nat. rewrite nat_of_Nmult. repeat rewrite nat_of_N_of_nat. reflexivity. Qed. Theorem Npow2_nat : forall n, nat_of_N (Npow2 n) = pow2 n. induction n; simpl; intuition. rewrite <- IHn; clear IHn. case_eq (Npow2 n); intuition. rewrite untimes2. replace (Npos p~0) with (Ndouble (Npos p)) by reflexivity. apply nat_of_Ndouble. Qed. Theorem wneg_alt : forall sz (x : word sz), wneg x = wnegN x. unfold wnegN, wneg; intros. repeat rewrite wordToN_nat; repeat rewrite NToWord_nat. rewrite nat_of_Nminus. do 2 f_equal. apply Npow2_nat. apply nat_of_N_of_nat. Qed. Theorem wminus_Alt : forall sz (x y : word sz), wminus x y = wminusN x y. intros; unfold wminusN, wminus; rewrite wneg_alt; apply wplus_alt. Qed. Theorem wplus_unit : forall sz (x : word sz), natToWord sz 0 ^+ x = x. intros; rewrite wplus_alt; unfold wplusN, wordBinN; intros. rewrite roundTrip_0; apply natToWord_wordToNat. Qed. Theorem wplus_comm : forall sz (x y : word sz), x ^+ y = y ^+ x. intros; repeat rewrite wplus_alt; unfold wplusN, wordBinN; f_equal; auto. Qed. Theorem drop_mod2 : forall n k, 2 * k <= n -> mod2 (n - 2 * k) = mod2 n. induction n using strong; intros. do 2 (destruct n; simpl in *; repeat rewrite untimes2 in *; intuition). destruct k; simpl in *; intuition. destruct k; simpl; intuition. rewrite <- plus_n_Sm. repeat rewrite untimes2 in *. simpl; auto. apply H; omega. Qed. Theorem div2_minus_2 : forall n k, 2 * k <= n -> div2 (n - 2 * k) = div2 n - k. induction n using strong; intros. do 2 (destruct n; simpl in *; intuition; repeat rewrite untimes2 in *). destruct k; simpl in *; intuition. destruct k; simpl in *; intuition. rewrite <- plus_n_Sm. apply H; omega. Qed. Theorem div2_bound : forall k n, 2 * k <= n -> k <= div2 n. intros; case_eq (mod2 n); intro Heq. rewrite (div2_odd _ Heq) in H. omega. rewrite (div2_even _ Heq) in H. omega. Qed. Theorem drop_sub : forall sz n k, k * pow2 sz <= n -> natToWord sz (n - k * pow2 sz) = natToWord sz n. induction sz; simpl; intuition; repeat rewrite untimes2 in *; f_equal. rewrite mult_assoc. rewrite (mult_comm k). rewrite <- mult_assoc. apply drop_mod2. rewrite mult_assoc. rewrite (mult_comm 2). rewrite <- mult_assoc. auto. rewrite <- (IHsz (div2 n) k). rewrite mult_assoc. rewrite (mult_comm k). rewrite <- mult_assoc. rewrite div2_minus_2. reflexivity. rewrite mult_assoc. rewrite (mult_comm 2). rewrite <- mult_assoc. auto. apply div2_bound. rewrite mult_assoc. rewrite (mult_comm 2). rewrite <- mult_assoc. auto. Qed. Local Hint Extern 1 (_ <= _) => omega. Theorem wplus_assoc : forall sz (x y z : word sz), x ^+ (y ^+ z) = x ^+ y ^+ z. intros; repeat rewrite wplus_alt; unfold wplusN, wordBinN; intros. repeat match goal with | [ |- context[wordToNat (natToWord ?sz ?w)] ] => let Heq := fresh "Heq" in destruct (wordToNat_natToWord sz w) as [? [Heq ?]]; rewrite Heq end. replace (wordToNat x + wordToNat y - x1 * pow2 sz + wordToNat z) with (wordToNat x + wordToNat y + wordToNat z - x1 * pow2 sz) by auto. replace (wordToNat x + (wordToNat y + wordToNat z - x0 * pow2 sz)) with (wordToNat x + wordToNat y + wordToNat z - x0 * pow2 sz) by auto. repeat rewrite drop_sub; auto. Qed. Theorem roundTrip_1 : forall sz, wordToNat (natToWord (S sz) 1) = 1. induction sz; simpl in *; intuition. Qed. Theorem mod2_WS : forall sz (x : word sz) b, mod2 (wordToNat (WS b x)) = b. intros. rewrite wordToNat_wordToNat'. destruct b; simpl. rewrite untimes2. case_eq (2 * wordToNat x); intuition. eapply mod2_S; eauto. rewrite <- (mod2_double (wordToNat x)); f_equal; omega. Qed. Theorem div2_WS : forall sz (x : word sz) b, div2 (wordToNat (WS b x)) = wordToNat x. destruct b; rewrite wordToNat_wordToNat'; unfold wordToNat'; fold wordToNat'. apply div2_S_double. apply div2_double. Qed. Theorem wmult_unit : forall sz (x : word sz), natToWord sz 1 ^* x = x. intros; rewrite wmult_alt; unfold wmultN, wordBinN; intros. destruct sz; simpl. rewrite (shatter_word x); reflexivity. rewrite roundTrip_0; simpl. rewrite plus_0_r. rewrite (shatter_word x). f_equal. apply mod2_WS. rewrite div2_WS. apply natToWord_wordToNat. Qed. Theorem wmult_comm : forall sz (x y : word sz), x ^* y = y ^* x. intros; repeat rewrite wmult_alt; unfold wmultN, wordBinN; auto with arith. Qed. Theorem wmult_assoc : forall sz (x y z : word sz), x ^* (y ^* z) = x ^* y ^* z. intros; repeat rewrite wmult_alt; unfold wmultN, wordBinN; intros. repeat match goal with | [ |- context[wordToNat (natToWord ?sz ?w)] ] => let Heq := fresh "Heq" in destruct (wordToNat_natToWord sz w) as [? [Heq ?]]; rewrite Heq end. rewrite mult_minus_distr_l. rewrite mult_minus_distr_r. rewrite (mult_assoc (wordToNat x) x0). rewrite <- (mult_assoc x1). rewrite (mult_comm (pow2 sz)). rewrite (mult_assoc x1). repeat rewrite drop_sub; auto with arith. rewrite (mult_comm x1). rewrite <- (mult_assoc (wordToNat x)). rewrite (mult_comm (wordToNat y)). rewrite mult_assoc. rewrite (mult_comm (wordToNat x)). repeat rewrite <- mult_assoc. auto with arith. repeat rewrite <- mult_assoc. auto with arith. Qed. Theorem wmult_plus_distr : forall sz (x y z : word sz), (x ^+ y) ^* z = (x ^* z) ^+ (y ^* z). intros; repeat rewrite wmult_alt; repeat rewrite wplus_alt; unfold wmultN, wplusN, wordBinN; intros. repeat match goal with | [ |- context[wordToNat (natToWord ?sz ?w)] ] => let Heq := fresh "Heq" in destruct (wordToNat_natToWord sz w) as [? [Heq ?]]; rewrite Heq end. rewrite mult_minus_distr_r. rewrite <- (mult_assoc x0). rewrite (mult_comm (pow2 sz)). rewrite (mult_assoc x0). replace (wordToNat x * wordToNat z - x1 * pow2 sz + (wordToNat y * wordToNat z - x2 * pow2 sz)) with (wordToNat x * wordToNat z + wordToNat y * wordToNat z - x1 * pow2 sz - x2 * pow2 sz). repeat rewrite drop_sub; auto with arith. rewrite (mult_comm x0). rewrite (mult_comm (wordToNat x + wordToNat y)). rewrite <- (mult_assoc (wordToNat z)). auto with arith. generalize dependent (wordToNat x * wordToNat z). generalize dependent (wordToNat y * wordToNat z). intros. omega. Qed. Theorem wminus_def : forall sz (x y : word sz), x ^- y = x ^+ ^~ y. reflexivity. Qed. Theorem wordToNat_bound : forall sz (w : word sz), wordToNat w < pow2 sz. induction w; simpl; intuition. destruct b; simpl; omega. Qed. Theorem natToWord_pow2 : forall sz, natToWord sz (pow2 sz) = natToWord sz 0. induction sz; simpl; intuition. generalize (div2_double (pow2 sz)); simpl; intro Hr; rewrite Hr; clear Hr. f_equal. generalize (mod2_double (pow2 sz)); auto. auto. Qed. Theorem wminus_inv : forall sz (x : word sz), x ^+ ^~ x = wzero sz. intros; rewrite wneg_alt; rewrite wplus_alt; unfold wnegN, wplusN, wzero, wordBinN; intros. repeat match goal with | [ |- context[wordToNat (natToWord ?sz ?w)] ] => let Heq := fresh "Heq" in destruct (wordToNat_natToWord sz w) as [? [Heq ?]]; rewrite Heq end. replace (wordToNat x + (pow2 sz - wordToNat x - x0 * pow2 sz)) with (pow2 sz - x0 * pow2 sz). rewrite drop_sub; auto with arith. apply natToWord_pow2. generalize (wordToNat_bound x). omega. Qed. Definition wring (sz : nat) : ring_theory (wzero sz) (wone sz) (@wplus sz) (@wmult sz) (@wminus sz) (@wneg sz) (@eq _) := mk_rt _ _ _ _ _ _ _ (@wplus_unit _) (@wplus_comm _) (@wplus_assoc _) (@wmult_unit _) (@wmult_comm _) (@wmult_assoc _) (@wmult_plus_distr _) (@wminus_def _) (@wminus_inv _). Theorem weqb_sound : forall sz (x y : word sz), weqb x y = true -> x = y. Proof. eapply weqb_true_iff. Qed. Implicit Arguments weqb_sound []. Ltac isWcst w := match eval hnf in w with | WO => constr:true | WS ?b ?w' => match eval hnf in b with | true => isWcst w' | false => isWcst w' | _ => constr:false end | _ => constr:false end. Ltac wcst w := let b := isWcst w in match b with | true => w | _ => constr:NotConstant end. (* Here's how you can add a ring for a specific bit-width. There doesn't seem to be a polymorphic method, so this code really does need to be copied. *) (* Definition wring8 := wring 8. Add Ring wring8 : wring8 (decidable (weqb_sound 8), constants [wcst]). *) (** * Bitwise operators *) Fixpoint wnot sz (w : word sz) : word sz := match w with | WO => WO | WS b _ w' => WS (negb b) (wnot w') end. Fixpoint bitwp (f : bool -> bool -> bool) sz (w1 : word sz) : word sz -> word sz := match w1 with | WO => fun _ => WO | WS b _ w1' => fun w2 => WS (f b (whd w2)) (bitwp f w1' (wtl w2)) end. Definition wor := bitwp orb. Definition wand := bitwp andb. Definition wxor := bitwp xorb. Notation "l ^| r" := (@wor _ l%word r%word) (at level 50, left associativity). Notation "l ^& r" := (@wand _ l%word r%word) (at level 40, left associativity). Theorem wor_unit : forall sz (x : word sz), wzero sz ^| x = x. unfold wzero, wor; induction x; simpl; intuition congruence. Qed. Theorem wor_comm : forall sz (x y : word sz), x ^| y = y ^| x. unfold wor; induction x; intro y; rewrite (shatter_word y); simpl; intuition; f_equal; auto with bool. Qed. Theorem wor_assoc : forall sz (x y z : word sz), x ^| (y ^| z) = x ^| y ^| z. unfold wor; induction x; intro y; rewrite (shatter_word y); simpl; intuition; f_equal; auto with bool. Qed. Theorem wand_unit : forall sz (x : word sz), wones sz ^& x = x. unfold wand; induction x; simpl; intuition congruence. Qed. Theorem wand_kill : forall sz (x : word sz), wzero sz ^& x = wzero sz. unfold wzero, wand; induction x; simpl; intuition congruence. Qed. Theorem wand_comm : forall sz (x y : word sz), x ^& y = y ^& x. unfold wand; induction x; intro y; rewrite (shatter_word y); simpl; intuition; f_equal; auto with bool. Qed. Theorem wand_assoc : forall sz (x y z : word sz), x ^& (y ^& z) = x ^& y ^& z. unfold wand; induction x; intro y; rewrite (shatter_word y); simpl; intuition; f_equal; auto with bool. Qed. Theorem wand_or_distr : forall sz (x y z : word sz), (x ^| y) ^& z = (x ^& z) ^| (y ^& z). unfold wand, wor; induction x; intro y; rewrite (shatter_word y); intro z; rewrite (shatter_word z); simpl; intuition; f_equal; auto with bool. destruct (whd y); destruct (whd z); destruct b; reflexivity. Qed. Definition wbring (sz : nat) : semi_ring_theory (wzero sz) (wones sz) (@wor sz) (@wand sz) (@eq _) := mk_srt _ _ _ _ _ (@wor_unit _) (@wor_comm _) (@wor_assoc _) (@wand_unit _) (@wand_kill _) (@wand_comm _) (@wand_assoc _) (@wand_or_distr _). (** * Inequality proofs *) Ltac word_simpl := unfold sext, zext, wzero in *; simpl in *. Ltac word_eq := ring. Ltac word_eq1 := match goal with | _ => ring | [ H : _ = _ |- _ ] => ring [H] end. Theorem word_neq : forall sz (w1 w2 : word sz), w1 ^- w2 <> wzero sz -> w1 <> w2. intros; intro; subst. unfold wminus in H. rewrite wminus_inv in H. tauto. Qed. Ltac word_neq := apply word_neq; let H := fresh "H" in intro H; simpl in H; ring_simplify in H; try discriminate. Ltac word_contra := match goal with | [ H : _ <> _ |- False ] => apply H; ring end. Ltac word_contra1 := match goal with | [ H : _ <> _ |- False ] => apply H; match goal with | _ => ring | [ H' : _ = _ |- _ ] => ring [H'] end end. Open Scope word_scope. (** * Signed Logic **) Fixpoint wordToZ sz (w : word sz) : Z := if wmsb w true then (** Negative **) match wordToN (wneg w) with | N0 => 0%Z | Npos x => Zneg x end else (** Positive **) match wordToN w with | N0 => 0%Z | Npos x => Zpos x end. (** * Comparison Predicates and Deciders **) Definition wlt sz (l r : word sz) : Prop := Nlt (wordToN l) (wordToN r). Definition wslt sz (l r : word sz) : Prop := Zlt (wordToZ l) (wordToZ r). Notation "w1 > w2" := (@wlt _ w2%word w1%word) : word_scope. Notation "w1 >= w2" := (~(@wlt _ w1%word w2%word)) : word_scope. Notation "w1 < w2" := (@wlt _ w1%word w2%word) : word_scope. Notation "w1 <= w2" := (~(@wlt _ w2%word w1%word)) : word_scope. Notation "w1 '>s' w2" := (@wslt _ w2%word w1%word) (at level 70) : word_scope. Notation "w1 '>s=' w2" := (~(@wslt _ w1%word w2%word)) (at level 70) : word_scope. Notation "w1 '<s' w2" := (@wslt _ w1%word w2%word) (at level 70) : word_scope. Notation "w1 '<s=' w2" := (~(@wslt _ w2%word w1%word)) (at level 70) : word_scope. Definition wlt_dec : forall sz (l r : word sz), {l < r} + {l >= r}. refine (fun sz l r => match Ncompare (wordToN l) (wordToN r) as k return Ncompare (wordToN l) (wordToN r) = k -> _ with | Lt => fun pf => left _ _ | _ => fun pf => right _ _ end (refl_equal _)); abstract congruence. Defined. Definition wslt_dec : forall sz (l r : word sz), {l <s r} + {l >s= r}. refine (fun sz l r => match Zcompare (wordToZ l) (wordToZ r) as c return Zcompare (wordToZ l) (wordToZ r) = c -> _ with | Lt => fun pf => left _ _ | _ => fun pf => right _ _ end (refl_equal _)); abstract congruence. Defined. (* Ordering Lemmas **) Lemma lt_le : forall sz (a b : word sz), a < b -> a <= b. Proof. unfold wlt, Nlt. intros. intro. rewrite <- Ncompare_antisym in H0. rewrite H in H0. simpl in *. congruence. Qed. Lemma eq_le : forall sz (a b : word sz), a = b -> a <= b. Proof. intros; subst. unfold wlt, Nlt. rewrite Ncompare_refl. congruence. Qed. Lemma wordToN_inj : forall sz (a b : word sz), wordToN a = wordToN b -> a = b. Proof. induction a; intro b0; rewrite (shatter_word b0); intuition. simpl in H. destruct b; destruct (whd b0); intros. f_equal. eapply IHa. eapply Nsucc_inj in H. destruct (wordToN a); destruct (wordToN (wtl b0)); try congruence. destruct (wordToN (wtl b0)); destruct (wordToN a); inversion H. destruct (wordToN (wtl b0)); destruct (wordToN a); inversion H. f_equal. eapply IHa. destruct (wordToN a); destruct (wordToN (wtl b0)); try congruence. Qed. Lemma unique_inverse : forall sz (a b1 b2 : word sz), a ^+ b1 = wzero _ -> a ^+ b2 = wzero _ -> b1 = b2. Proof. intros. transitivity (b1 ^+ wzero _). rewrite wplus_comm. rewrite wplus_unit. auto. transitivity (b1 ^+ (a ^+ b2)). congruence. rewrite wplus_assoc. rewrite (wplus_comm b1). rewrite H. rewrite wplus_unit. auto. Qed. Lemma sub_0_eq : forall sz (a b : word sz), a ^- b = wzero _ -> a = b. Proof. intros. destruct (weq (wneg b) (wneg a)). transitivity (a ^+ (^~ b ^+ b)). rewrite (wplus_comm (^~ b)). rewrite wminus_inv. rewrite wplus_comm. rewrite wplus_unit. auto. rewrite e. rewrite wplus_assoc. rewrite wminus_inv. rewrite wplus_unit. auto. unfold wminus in H. generalize (unique_inverse a (wneg a) (^~ b)). intros. elimtype False. apply n. symmetry; apply H0. apply wminus_inv. auto. Qed. Lemma le_neq_lt : forall sz (a b : word sz), b <= a -> a <> b -> b < a. Proof. intros; destruct (wlt_dec b a); auto. elimtype False. apply H0. unfold wlt, Nlt in *. eapply wordToN_inj. eapply Ncompare_eq_correct. case_eq ((wordToN a ?= wordToN b)%N); auto; try congruence. intros. rewrite <- Ncompare_antisym in n. rewrite H1 in n. simpl in *. congruence. Qed. Hint Resolve word_neq lt_le eq_le sub_0_eq le_neq_lt : worder. Ltac shatter_word x := match type of x with | word 0 => try rewrite (shatter_word_0 x) in * | word (S ?N) => let x' := fresh in let H := fresh in destruct (@shatter_word_S N x) as [ ? [ x' H ] ]; rewrite H in *; clear H; shatter_word x' end. (** Uniqueness of equality proofs **) Lemma rewrite_weq : forall sz (a b : word sz) (pf : a = b), weq a b = left _ pf. Proof. intros; destruct (weq a b); try solve [ elimtype False; auto ]. f_equal. eapply UIP_dec. eapply weq. Qed. (** * Some more useful derived facts *) Lemma natToWord_plus : forall sz n m, natToWord sz (n + m) = natToWord _ n ^+ natToWord _ m. destruct sz; intuition. rewrite wplus_alt. unfold wplusN, wordBinN. destruct (wordToNat_natToWord (S sz) n); intuition. destruct (wordToNat_natToWord (S sz) m); intuition. rewrite H0; rewrite H2; clear H0 H2. replace (n - x * pow2 (S sz) + (m - x0 * pow2 (S sz))) with (n + m - x * pow2 (S sz) - x0 * pow2 (S sz)) by omega. repeat rewrite drop_sub; auto; omega. Qed. Lemma natToWord_S : forall sz n, natToWord sz (S n) = natToWord _ 1 ^+ natToWord _ n. intros; change (S n) with (1 + n); apply natToWord_plus. Qed. Theorem natToWord_inj : forall sz n m, natToWord sz n = natToWord sz m -> (n < pow2 sz)%nat -> (m < pow2 sz)%nat -> n = m. intros. apply (f_equal (@wordToNat _)) in H. destruct (wordToNat_natToWord sz n). destruct (wordToNat_natToWord sz m). intuition. rewrite H4 in H; rewrite H2 in H; clear H4 H2. assert (x = 0). destruct x; auto. simpl in *. generalize dependent (x * pow2 sz). intros. omega. assert (x0 = 0). destruct x0; auto. simpl in *. generalize dependent (x0 * pow2 sz). intros. omega. subst; simpl in *; omega. Qed. Lemma wordToNat_natToWord_idempotent : forall sz n, (N.of_nat n < Npow2 sz)%N -> wordToNat (natToWord sz n) = n. intros. destruct (wordToNat_natToWord sz n); intuition. destruct x. simpl in *; omega. simpl in *. apply Nlt_out in H. autorewrite with N in *. rewrite Npow2_nat in *. generalize dependent (x * pow2 sz). intros; omega. Qed. Lemma wplus_cancel : forall sz (a b c : word sz), a ^+ c = b ^+ c -> a = b. intros. apply (f_equal (fun x => x ^+ ^~ c)) in H. repeat rewrite <- wplus_assoc in H. rewrite wminus_inv in H. repeat rewrite (wplus_comm _ (wzero sz)) in H. repeat rewrite wplus_unit in H. assumption. Qed.
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import order.omega_complete_partial_order import order.category.Preorder import category_theory.limits.shapes.products import category_theory.limits.shapes.equalizers import category_theory.limits.constructions.limits_of_products_and_equalizers /-! # Category of types with a omega complete partial order In this file, we bundle the class `omega_complete_partial_order` into a concrete category and prove that continuous functions also form a `omega_complete_partial_order`. ## Main definitions * `ωCPO` * an instance of `category` and `concrete_category` -/ open category_theory universes u v /-- The category of types with a omega complete partial order. -/ def ωCPO : Type (u+1) := bundled omega_complete_partial_order namespace ωCPO open omega_complete_partial_order instance : bundled_hom @continuous_hom := { to_fun := @continuous_hom.simps.apply, id := @continuous_hom.id, comp := @continuous_hom.comp, hom_ext := @continuous_hom.coe_inj } attribute [derive [large_category, concrete_category]] ωCPO instance : has_coe_to_sort ωCPO Type* := bundled.has_coe_to_sort /-- Construct a bundled ωCPO from the underlying type and typeclass. -/ def of (α : Type*) [omega_complete_partial_order α] : ωCPO := bundled.of α @[simp] lemma coe_of (α : Type*) [omega_complete_partial_order α] : ↥(of α) = α := rfl instance : inhabited ωCPO := ⟨of punit⟩ instance (α : ωCPO) : omega_complete_partial_order α := α.str section open category_theory.limits namespace has_products /-- The pi-type gives a cone for a product. -/ def product {J : Type v} (f : J → ωCPO.{v}) : fan f := fan.mk (of (Π j, f j)) (λ j, continuous_hom.of_mono (pi.eval_order_hom j) (λ c, rfl)) /-- The pi-type is a limit cone for the product. -/ def is_product (J : Type v) (f : J → ωCPO) : is_limit (product f) := { lift := λ s, ⟨⟨λ t j, s.π.app j t, λ x y h j, (s.π.app j).monotone h⟩, λ x, funext (λ j, (s.π.app j).continuous x)⟩, uniq' := λ s m w, begin ext t j, change m t j = s.π.app j t, rw ← w j, refl, end }. instance (J : Type v) (f : J → ωCPO.{v}) : has_product f := has_limit.mk ⟨_, is_product _ f⟩ end has_products instance omega_complete_partial_order_equalizer {α β : Type*} [omega_complete_partial_order α] [omega_complete_partial_order β] (f g : α →𝒄 β) : omega_complete_partial_order {a : α // f a = g a} := omega_complete_partial_order.subtype _ $ λ c hc, begin rw [f.continuous, g.continuous], congr' 1, ext, apply hc _ ⟨_, rfl⟩, end namespace has_equalizers /-- The equalizer inclusion function as a `continuous_hom`. -/ def equalizer_ι {α β : Type*} [omega_complete_partial_order α] [omega_complete_partial_order β] (f g : α →𝒄 β) : {a : α // f a = g a} →𝒄 α := continuous_hom.of_mono (order_hom.subtype.val _) (λ c, rfl) /-- A construction of the equalizer fork. -/ def equalizer {X Y : ωCPO.{v}} (f g : X ⟶ Y) : fork f g := @fork.of_ι _ _ _ _ _ _ (ωCPO.of {a // f a = g a}) (equalizer_ι f g) (continuous_hom.ext _ _ (λ x, x.2)) /-- The equalizer fork is a limit. -/ def is_equalizer {X Y : ωCPO.{v}} (f g : X ⟶ Y) : is_limit (equalizer f g) := fork.is_limit.mk' _ $ λ s, ⟨{ to_fun := λ x, ⟨s.ι x, by apply continuous_hom.congr_fun s.condition⟩, monotone' := λ x y h, s.ι.monotone h, cont := λ x, subtype.ext (s.ι.continuous x) }, by { ext, refl }, λ m hm, begin ext, apply continuous_hom.congr_fun hm, end⟩ end has_equalizers instance : has_products ωCPO.{v} := λ J, { has_limit := λ F, has_limit_of_iso discrete.nat_iso_functor.symm } instance {X Y : ωCPO.{v}} (f g : X ⟶ Y) : has_limit (parallel_pair f g) := has_limit.mk ⟨_, has_equalizers.is_equalizer f g⟩ instance : has_equalizers ωCPO.{v} := has_equalizers_of_has_limit_parallel_pair _ instance : has_limits ωCPO.{v} := limits_from_equalizers_and_products end end ωCPO
{-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} module ComposableSDR.Types ( compose , addPipe , unPipe , toArray , elemSize , sampleFormat , Demodulator , Pipe(..) , ArrayPipe , AudioFormat(..) , SamplesIQCF32 , SoapyException(..) , Array(..) ) where import Control.Category (Category (..)) import Prelude hiding ((.)) import Data.Complex import Data.Typeable import Foreign.C.Types import Foreign.ForeignPtr (plusForeignPtr, withForeignPtr) import Foreign.Ptr import Control.Exception (Exception) import Control.Monad import qualified Control.Monad.Catch as MC import Control.Monad.State import qualified Control.Monad.Trans.Control as MTC import qualified Sound.File.Sndfile as SF import qualified Streamly.Internal.Data.Fold.Types as FL import Streamly.Internal.Data.Stream.StreamK.Type (IsStream) import qualified Streamly.Internal.Memory.Array.Types as AT (Array (..)) import qualified Streamly.Memory.Array as A import qualified Streamly.Prelude as S data AudioFormat = AU | WAV deriving (Show, Read) data Pipe m a b = forall r. Pipe { _start :: m r , _process :: r -> a -> m b , _done :: r -> m () } newtype Array a = Array { fromArray :: AT.Array a } instance SF.Buffer Array Float where fromForeignPtr fp i n = withForeignPtr fp $ \p -> do let v = AT.Array { AT.aStart = fp `plusForeignPtr` i , AT.aEnd = p `plusPtr` (i + 4 * n) , AT.aBound = p `plusPtr` (i + 4 * n) } return $ toArray v toForeignPtr = return . (\x -> (AT.aStart x, 0, A.length x)) . fromArray type ArrayPipe m a b = Pipe m (A.Array a) (A.Array b) type Demodulator = ArrayPipe IO SamplesIQCF32 Float data SoapyException = SoapyException deriving (Show, Typeable) instance Exception SoapyException type SamplesIQCF32 = Complex CFloat elemSize :: Int elemSize = 8 sampleFormat :: String sampleFormat = "CF32" toArray :: AT.Array a -> Array a toArray = Array compose :: Monad m => Pipe m b c -> Pipe m a b -> Pipe m a c compose (Pipe start1 process1 done1) (Pipe start2 process2 done2) = Pipe start process done where start = (,) <$> start1 <*> start2 done (r1, r2) = done2 r2 >> done1 r1 process (r1, r2) = process2 r2 >=> process1 r1 instance Monad m => Category (Pipe m) where id = Pipe (return ()) (const return) (const $ return ()) (.) = compose instance Monad m => Functor (Pipe m a) where fmap f (Pipe start process done) = Pipe start (\r a -> fmap f (process r a)) done unPipe :: (IsStream t, MonadIO m, MTC.MonadBaseControl IO m, MC.MonadThrow m) => Pipe m a b -> m (t m a -> t m b, m ()) unPipe (Pipe creat process dest) = do r <- creat return (S.mapM (process r), dest r) addPipe :: MonadIO m => Pipe m a b -> FL.Fold m b c -> FL.Fold m a c addPipe (Pipe creat process dest) (FL.Fold step1 start1 done1) = FL.Fold step start done where start = do s <- start1 r <- creat return (s, r, process r) done (s, r, _) = do dest r done1 s step (s, r, f) a = do b <- f a s' <- step1 s b return (s', r, f)
theory T147 imports Main begin lemma "( (\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) & (\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(meet(x, y), z) = meet(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(join(x, y), z) = join(over(x, z), over(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(meet(x, y), z) = join(undr(x, z), undr(y, z))) & (\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) & (\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) & (\<forall> x::nat. invo(invo(x)) = x) ) \<longrightarrow> (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(x, meet(y, z)) = join(over(x, y), over(x, z))) " nitpick[card nat=4,timeout=86400] oops end
lemma metric_LIM_imp_LIM: fixes l :: "'a::metric_space" and m :: "'b::metric_space" assumes f: "f \<midarrow>a\<rightarrow> l" and le: "\<And>x. x \<noteq> a \<Longrightarrow> dist (g x) m \<le> dist (f x) l" shows "g \<midarrow>a\<rightarrow> m"
(* Author: Norbert Schirmer Maintainer: Norbert Schirmer, norbert.schirmer at web de License: LGPL *) (* Title: HoareTotalDef.thy Author: Norbert Schirmer, TU Muenchen Copyright (C) 2004-2008 Norbert Schirmer Some rights reserved, TU Muenchen This library 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 library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) section \<open>Hoare Logic for Total Correctness\<close> theory HoareTotalDef imports HoarePartialDef Termination begin subsection \<open>Validity of Hoare Tuples: \<open>\<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A\<close>\<close> definition validt :: "[('s,'p,'f) body,'f set,'s assn,('s,'p,'f) com,'s assn,'s assn] \<Rightarrow> bool" ("_\<Turnstile>\<^sub>t\<^bsub>'/_\<^esub>/ _ _ _,_" [61,60,1000, 20, 1000,1000] 60) where "\<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A \<equiv> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A \<and> (\<forall>s \<in> Normal ` P. \<Gamma>\<turnstile>c\<down>s)" definition cvalidt:: "[('s,'p,'f) body,('s,'p) quadruple set,'f set, 's assn,('s,'p,'f) com,'s assn,'s assn] \<Rightarrow> bool" ("_,_\<Turnstile>\<^sub>t\<^bsub>'/_\<^esub>/ _ _ _,_" [61,60, 60,1000, 20, 1000,1000] 60) where "\<Gamma>,\<Theta>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A \<equiv> (\<forall>(P,p,Q,A)\<in>\<Theta>. \<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P (Call p) Q,A) \<longrightarrow> \<Gamma> \<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" notation (ASCII) validt ("_|=t'/_/ _ _ _,_" [61,60,1000, 20, 1000,1000] 60) and cvalidt ("_,_|=t'/_ / _ _ _,_" [61,60,60,1000, 20, 1000,1000] 60) subsection \<open>Properties of Validity\<close> lemma validtI: "\<lbrakk>\<And>s t. \<lbrakk>\<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> \<Rightarrow> t;s \<in> P;t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A; \<And>s. s \<in> P \<Longrightarrow> \<Gamma>\<turnstile> c\<down>(Normal s) \<rbrakk> \<Longrightarrow> \<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" by (auto simp add: validt_def valid_def) lemma cvalidtI: "\<lbrakk>\<And>s t. \<lbrakk>\<forall>(P,p,Q,A)\<in>\<Theta>. \<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P (Call p) Q,A;\<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> \<Rightarrow> t;s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A; \<And>s. \<lbrakk>\<forall>(P,p,Q,A)\<in>\<Theta>. \<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P (Call p) Q,A; s\<in>P\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>c\<down>(Normal s)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" by (auto simp add: cvalidt_def validt_def valid_def) lemma cvalidt_postD: "\<lbrakk>\<Gamma>,\<Theta>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A; \<forall>(P,p,Q,A)\<in>\<Theta>. \<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P (Call p) Q,A;\<Gamma>\<turnstile>\<langle>c,Normal s \<rangle> \<Rightarrow> t; s \<in> P;t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A" by (simp add: cvalidt_def validt_def valid_def) lemma cvalidt_termD: "\<lbrakk>\<Gamma>,\<Theta>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A; \<forall>(P,p,Q,A)\<in>\<Theta>. \<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P (Call p) Q,A;s \<in> P\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>c\<down>(Normal s)" by (simp add: cvalidt_def validt_def valid_def) lemma validt_augment_Faults: assumes valid:"\<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" assumes F': "F \<subseteq> F'" shows "\<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F'\<^esub> P c Q,A" using valid F' by (auto intro: valid_augment_Faults simp add: validt_def) subsection \<open>The Hoare Rules: \<open>\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A\<close>\<close> inductive "hoaret"::"[('s,'p,'f) body,('s,'p) quadruple set,'f set, 's assn,('s,'p,'f) com,'s assn,'s assn] => bool" ("(3_,_/\<turnstile>\<^sub>t\<^bsub>'/_\<^esub> (_/ (_)/ _,_))" [61,60,60,1000,20,1000,1000]60) for \<Gamma>::"('s,'p,'f) body" where Skip: "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> Q Skip Q,A" | Basic: "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> {s. f s \<in> Q} (Basic f) Q,A" | Spec: "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> {s. (\<forall>t. (s,t) \<in> r \<longrightarrow> t \<in> Q) \<and> (\<exists>t. (s,t) \<in> r)} (Spec r) Q,A" | Seq: "\<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c\<^sub>1 R,A; \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P Seq c\<^sub>1 c\<^sub>2 Q,A" | Cond: "\<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> (P \<inter> b) c\<^sub>1 Q,A; \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> (P \<inter> - b) c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P (Cond b c\<^sub>1 c\<^sub>2) Q,A" | While: "\<lbrakk>wf r; \<forall>\<sigma>. \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> ({\<sigma>} \<inter> P \<inter> b) c ({t. (t,\<sigma>)\<in>r} \<inter> P),A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P (While b c) (P \<inter> - b),A" | Guard: "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> (g \<inter> P) c Q,A \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> (g \<inter> P) Guard f g c Q,A" | Guarantee: "\<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P (Guard f g c) Q,A" | CallRec: "\<lbrakk>(P,p,Q,A) \<in> Specs; wf r; Specs_wf = (\<lambda>p \<sigma>. (\<lambda>(P,q,Q,A). (P \<inter> {s. ((s,q),(\<sigma>,p)) \<in> r},q,Q,A)) ` Specs); \<forall>(P,p,Q,A)\<in> Specs. p \<in> dom \<Gamma> \<and> (\<forall>\<sigma>. \<Gamma>,\<Theta> \<union> Specs_wf p \<sigma>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> ({\<sigma>} \<inter> P) (the (\<Gamma> p)) Q,A) \<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P (Call p) Q,A" | DynCom: "\<forall>s \<in> P. \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P (c s) Q,A \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P (DynCom c) Q,A" | Throw: "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> A Throw Q,A" | Catch: "\<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A" | Conseq: "\<forall>s \<in> P. \<exists>P' Q' A'. \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P' c Q',A' \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" | Asm: "(P,p,Q,A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P (Call p) Q,A" | ExFalso: "\<lbrakk>\<Gamma>,\<Theta>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" \<comment> \<open>This is a hack rule that enables us to derive completeness for an arbitrary context \<open>\<Theta>\<close>, from completeness for an empty context.\<close> text \<open>Does not work, because of rule ExFalso, the context \<open>\<Theta>\<close> is to blame. A weaker version with empty context can be derived from soundness later on.\<close> lemma hoaret_to_hoarep: assumes hoaret: "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P p Q,A" shows "\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F\<^esub> P p Q,A" using hoaret proof (induct) case Skip thus ?case by (rule hoarep.intros) next case Basic thus ?case by (rule hoarep.intros) next case Seq thus ?case by - (rule hoarep.intros) next case Cond thus ?case by - (rule hoarep.intros) next case (While r \<Theta> F P b c A) hence "\<forall>\<sigma>. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F\<^esub> ({\<sigma>} \<inter> P \<inter> b) c ({t. (t, \<sigma>) \<in> r} \<inter> P),A" by iprover hence "\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F\<^esub> (P \<inter> b) c P,A" by (rule HoarePartialDef.conseq) blast then show "\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F\<^esub> P While b c (P \<inter> - b),A" by (rule hoarep.While) next case Guard thus ?case by - (rule hoarep.intros) (*next case (CallRec A F P Procs Q Z \<Theta> p r) hence hyp: "\<forall>p\<in>Procs. \<forall>\<tau> Z. \<Gamma>,\<Theta> \<union> (\<Union>q\<in>Procs. \<Union>Z. {(P q Z \<inter> {s. ((s, q), \<tau>, p) \<in> r}, Call q, Q q Z,A q Z)})\<turnstile>\<^bsub>/F\<^esub> ({\<tau>} \<inter> P p Z) (the (\<Gamma> p)) (Q p Z),(A p Z)" by blast have "\<forall>p\<in>Procs. \<forall>Z. \<Gamma>,\<Theta> \<union> (\<Union>q\<in>Procs. \<Union>Z. {(P q Z, Call q, Q q Z,A q Z)})\<turnstile>\<^bsub>/F\<^esub> (P p Z) (the (\<Gamma> p)) (Q p Z),(A p Z)" proof (intro ballI allI) fix p Z assume "p \<in> Procs" with hyp have hyp': "\<And> \<tau>. \<Gamma>,\<Theta> \<union> (\<Union>q\<in>Procs. \<Union>Z. {(P q Z \<inter> {s. ((s, q), \<tau>, p) \<in> r}, Call q, Q q Z, A q Z)})\<turnstile>\<^bsub>/F\<^esub> ({\<tau>} \<inter> P p Z) (the (\<Gamma> p)) (Q p Z),(A p Z)" by blast have "\<forall>\<tau>. \<Gamma>,\<Theta> \<union> (\<Union>q\<in>Procs. \<Union>Z. {(P q Z, Call q, Q q Z,A q Z)})\<turnstile>\<^bsub>/F\<^esub> ({\<tau>} \<inter> P p Z) (the (\<Gamma> p)) (Q p Z),(A p Z)" (is "\<forall>\<tau>. \<Gamma>,?\<Theta>'\<turnstile>\<^bsub>/F\<^esub> ({\<tau>} \<inter> P p Z) (the (\<Gamma> p)) (Q p Z),(A p Z)") proof (rule allI, rule WeakenContext [OF hyp'],clarify) fix \<tau> P' c Q' A' assume "(P', c, Q', A') \<in> \<Theta> \<union> (\<Union>q\<in>Procs. \<Union>Z. {(P q Z \<inter> {s. ((s, q), \<tau>, p) \<in> r}, Call q, Q q Z, A q Z)})" (is "(P', c, Q', A') \<in> \<Theta> \<union> ?Spec") then show "\<Gamma>,?\<Theta>'\<turnstile>\<^bsub>/F\<^esub> P' c Q',A'" proof (cases rule: UnE [consumes 1]) assume "(P',c,Q',A') \<in> \<Theta>" then show ?thesis by (blast intro: HoarePartialDef.Asm) next assume "(P',c,Q',A') \<in> ?Spec" then show ?thesis proof (clarify) fix q Z assume q: "q \<in> Procs" show "\<Gamma>,?\<Theta>'\<turnstile>\<^bsub>/F\<^esub> (P q Z \<inter> {s. ((s, q), \<tau>, p) \<in> r}) Call q (Q q Z),(A q Z)" proof - from q have "\<Gamma>,?\<Theta>'\<turnstile>\<^bsub>/F\<^esub> (P q Z) Call q (Q q Z),(A q Z)" by - (rule HoarePartialDef.Asm,blast) thus ?thesis by (rule HoarePartialDef.conseqPre) blast qed qed qed qed then show "\<Gamma>,\<Theta> \<union> (\<Union>q\<in>Procs. \<Union>Z. {(P q Z, Call q, Q q Z,A q Z)}) \<turnstile>\<^bsub>/F\<^esub> (P p Z) (the (\<Gamma> p)) (Q p Z),(A p Z)" by (rule HoarePartialDef.conseq) blast qed thus ?case by - (rule hoarep.CallRec)*) next case DynCom thus ?case by (blast intro: hoarep.DynCom) next case Throw thus ?case by - (rule hoarep.Throw) next case Catch thus ?case by - (rule hoarep.Catch) next case Conseq thus ?case by - (rule hoarep.Conseq,blast) next case Asm thus ?case by (rule HoarePartialDef.Asm) next case (ExFalso \<Theta> F P c Q A) assume "\<Gamma>,\<Theta>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" hence "\<Gamma>,\<Theta>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A" oops lemma hoaret_augment_context: assumes deriv: "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P p Q,A" shows "\<And>\<Theta>'. \<Theta> \<subseteq> \<Theta>' \<Longrightarrow> \<Gamma>,\<Theta>'\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P p Q,A" using deriv proof (induct) case (CallRec P p Q A Specs r Specs_wf \<Theta> F \<Theta>') have aug: "\<Theta> \<subseteq> \<Theta>'" by fact then have h: "\<And>\<tau> p. \<Theta> \<union> Specs_wf p \<tau> \<subseteq> \<Theta>' \<union> Specs_wf p \<tau>" by blast have "\<forall>(P,p,Q,A)\<in>Specs. p \<in> dom \<Gamma> \<and> (\<forall>\<tau>. \<Gamma>,\<Theta> \<union> Specs_wf p \<tau>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> ({\<tau>} \<inter> P) (the (\<Gamma> p)) Q,A \<and> (\<forall>x. \<Theta> \<union> Specs_wf p \<tau> \<subseteq> x \<longrightarrow> \<Gamma>,x\<turnstile>\<^sub>t\<^bsub>/F\<^esub> ({\<tau>} \<inter> P) (the (\<Gamma> p)) Q,A))" by fact hence "\<forall>(P,p,Q,A)\<in>Specs. p \<in> dom \<Gamma> \<and> (\<forall>\<tau>. \<Gamma>,\<Theta>'\<union> Specs_wf p \<tau> \<turnstile>\<^sub>t\<^bsub>/F\<^esub> ({\<tau>} \<inter> P) (the (\<Gamma> p)) Q,A)" apply (clarify) apply (rename_tac P p Q A) apply (drule (1) bspec) apply (clarsimp) apply (erule_tac x=\<tau> in allE) apply clarify apply (erule_tac x="\<Theta>' \<union> Specs_wf p \<tau>" in allE) apply (insert aug) apply auto done with CallRec show ?case by - (rule hoaret.CallRec) next case DynCom thus ?case by (blast intro: hoaret.DynCom) next case (Conseq P \<Theta> F c Q A \<Theta>') from Conseq have "\<forall>s \<in> P. (\<exists>P' Q' A'. (\<Gamma>,\<Theta>' \<turnstile>\<^sub>t\<^bsub>/F\<^esub> P' c Q',A') \<and> s \<in> P'\<and> Q' \<subseteq> Q \<and> A' \<subseteq> A)" by blast with Conseq show ?case by - (rule hoaret.Conseq) next case (ExFalso \<Theta> F P c Q A \<Theta>') have "\<Gamma>,\<Theta>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" "\<not> \<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" "\<Theta> \<subseteq> \<Theta>'" by fact+ then show ?case by (fastforce intro: hoaret.ExFalso simp add: cvalidt_def) qed (blast intro: hoaret.intros)+ subsection \<open>Some Derived Rules\<close> lemma Conseq': "\<forall>s. s \<in> P \<longrightarrow> (\<exists>P' Q' A'. (\<forall> Z. \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> (P' Z) c (Q' Z),(A' Z)) \<and> (\<exists>Z. s \<in> P' Z \<and> (Q' Z \<subseteq> Q) \<and> (A' Z \<subseteq> A))) \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" apply (rule Conseq) apply (rule ballI) apply (erule_tac x=s in allE) apply (clarify) apply (rule_tac x="P' Z" in exI) apply (rule_tac x="Q' Z" in exI) apply (rule_tac x="A' Z" in exI) apply blast done lemma conseq:"\<lbrakk>\<forall>Z. \<Gamma>,\<Theta> \<turnstile>\<^sub>t\<^bsub>/F\<^esub> (P' Z) c (Q' Z),(A' Z); \<forall>s. s \<in> P \<longrightarrow> (\<exists> Z. s\<in>P' Z \<and> (Q' Z \<subseteq> Q)\<and> (A' Z \<subseteq> A))\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" by (rule Conseq) blast theorem conseqPrePost: "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P' c Q',A' \<Longrightarrow> P \<subseteq> P' \<Longrightarrow> Q' \<subseteq> Q \<Longrightarrow> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" by (rule conseq [where ?P'="\<lambda>Z. P'" and ?Q'="\<lambda>Z. Q'"]) auto lemma conseqPre: "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P' c Q,A \<Longrightarrow> P \<subseteq> P' \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" by (rule conseq) auto lemma conseqPost: "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q',A'\<Longrightarrow> Q' \<subseteq> Q \<Longrightarrow> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" by (rule conseq) auto lemma Spec_wf_conv: "(\<lambda>(P, q, Q, A). (P \<inter> {s. ((s, q), \<tau>, p) \<in> r}, q, Q, A)) ` (\<Union>p\<in>Procs. \<Union>Z. {(P p Z, p, Q p Z, A p Z)}) = (\<Union>q\<in>Procs. \<Union>Z. {(P q Z \<inter> {s. ((s, q), \<tau>, p) \<in> r}, q, Q q Z, A q Z)})" by (auto intro!: image_eqI) lemma CallRec': "\<lbrakk>p\<in>Procs; Procs \<subseteq> dom \<Gamma>; wf r; \<forall>p\<in>Procs. \<forall>\<tau> Z. \<Gamma>,\<Theta>\<union>(\<Union>q\<in>Procs. \<Union>Z. {((P q Z) \<inter> {s. ((s,q),(\<tau>,p)) \<in> r},q,Q q Z,(A q Z))}) \<turnstile>\<^sub>t\<^bsub>/F\<^esub> ({\<tau>} \<inter> (P p Z)) (the (\<Gamma> p)) (Q p Z),(A p Z)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> (P p Z) (Call p) (Q p Z),(A p Z)" apply (rule CallRec [where Specs="\<Union>p\<in>Procs. \<Union>Z. {((P p Z),p,Q p Z,A p Z)}" and r=r]) apply blast apply assumption apply (rule refl) apply (clarsimp) apply (rename_tac p') apply (rule conjI) apply blast apply (intro allI) apply (rename_tac Z \<tau>) apply (drule_tac x=p' in bspec, assumption) apply (erule_tac x=\<tau> in allE) apply (erule_tac x=Z in allE) apply (fastforce simp add: Spec_wf_conv) done end
Require Import Basics. Require Import Spaces.Int. Require Import Spaces.Finite. (** * Successor Structures. *) (** A successor structure is just a type with a endofunctor on it, called 'successor'. Typical examples include either the integers or natural numbers with the successor (or predecessor) operation. *) Record SuccStr : Type := { ss_carrier : Type ; ss_succ : ss_carrier -> ss_carrier ; }. Coercion ss_carrier : SuccStr >-> Sortclass. Declare Scope succ_scope. Local Open Scope nat_scope. Local Open Scope succ_scope. Delimit Scope succ_scope with succ. Arguments ss_succ {_} _. Notation "x .+1" := (ss_succ x) : succ_scope. (** Successor structure of naturals *) Definition NatSucc : SuccStr := Build_SuccStr nat Nat.Core.succ. (** Successor structure of integers *) Definition IntSucc : SuccStr := Build_SuccStr Int int_succ. Notation "'+N'" := NatSucc : succ_scope. Notation "'+Z'" := IntSucc : succ_scope. (** Stratified successor structures *) Definition StratifiedType (N : SuccStr) (n : nat) : Type := N * Fin n. Definition stratified_succ (N : SuccStr) (n : nat) (x : StratifiedType N n) : StratifiedType N n. Proof. constructor. + induction n. - induction (snd x). - destruct (dec (snd x = inr tt)). * exact (ss_succ (fst x)). * exact (fst x). + exact (fsucc_mod (snd x)). Defined. Definition Stratified (N : SuccStr) (n : nat) : SuccStr := Build_SuccStr (StratifiedType N n) (stratified_succ N n). (** Addition in successor structures *) Fixpoint ss_add {N : SuccStr} (n : N) (k : nat) : N := match k with | O => n | S k => (ss_add n k).+1 end. Infix "+" := ss_add : succ_scope. Definition ss_add_succ {N : SuccStr} (n : N) (k : nat) : (n + k.+1) = n.+1 + k. Proof. induction k. + reflexivity. + exact (ap ss_succ IHk). Defined. (** Nat and Int segmented by triples *) Notation "'N3'" := (Stratified (+N) 3) : succ_scope. Notation "'Z3'" := (Stratified (+Z) 3) : succ_scope.
-- @@stderr -- dtrace: failed to compile script test/unittest/types/err.D_SYNTAX.badid.d: [D_SYNTAX] line 18: syntax error near "0"
module BoehmBerarducci %default total NatQ : Type NatQ = (A : Type) -> (A -> A) -> A -> A unNatQ : {A : Type} -> (A -> A) -> A -> NatQ -> A unNatQ f a q = q _ f a succQ : NatQ -> NatQ succQ q = \_, f, a => f (q _ f a) zeroQ : NatQ zeroQ = \_, f, a => a fromNatQ : NatQ -> Nat fromNatQ q = unNatQ S Z q toNatQ : Nat -> NatQ toNatQ (S n) = succQ (toNatQ n) toNatQ Z = zeroQ iterated : Nat -> (a -> a) -> a -> a iterated (S n) f a = f (iterated n f a) iterated Z f a = a test_iterated : (n : Nat) -> iterated n S Z = n test_iterated (S n) = rewrite test_iterated n in Refl test_iterated Z = Refl test_fromNatQ : (n : Nat) -> fromNatQ (iterated n succQ zeroQ) = n test_fromNatQ (S n) = rewrite test_fromNatQ n in Refl test_fromNatQ Z = Refl test_toNatQ : (n : Nat) -> toNatQ n = iterated n succQ zeroQ test_toNatQ (S n) = rewrite test_toNatQ n in Refl test_toNatQ Z = Refl ListQ : Type -> Type ListQ A = (B : Type) -> (A -> B -> B) -> B -> B unListQ : {A, B : Type} -> (A -> B -> B) -> B -> ListQ A -> B unListQ f b q = q _ f b consQ : {A : Type} -> A -> ListQ A -> ListQ A consQ a q = \_, f, b => f a (q _ f b) nilQ : {A : Type} -> ListQ A nilQ = \_, f, b => b fromListQ : {A : Type} -> ListQ A -> List A fromListQ q = unListQ (::) [] q toListQ : {A : Type} -> List A -> ListQ A toListQ (a :: aa) = consQ a (toListQ aa) toListQ [] = nilQ