Datasets:
AI4M
/

text
stringlengths
0
3.34M
#if !defined(STRIPWS_H_INCLUDED) #define STRIPWS_H_INCLUDED #include "FileEnumerator.h" #include "Utils.h" #include <filesystem> #include <gsl/gsl> #include <iosfwd> #include <string> class StripWS { public: static int usage(::std::ostream& strm, const ::std::string& progName, const char* pMsg); StripWS(::gsl::span<const char*const> args); int run() const; StripWS(const StripWS&) = delete; StripWS& operator=(const StripWS&) = delete; StripWS(StripWS&&) = delete; StripWS& operator=(StripWS&&) = delete; PRIVATE_EXCEPT_IN_TEST: using Path = ::std::filesystem::path; void queryFile(const Path& p) const; void translateFile(const Path& p) const; /// \brief Scans the input file, counts the occurrences of white space at /// the end of a line, and optionally strips them into the provided stream. /// /// If pOut is null, then the method simply counts the occurrences of white /// space at the end of a line. /// /// If pOut is not null, then the method additionally translates the file /// into *pOut. static void scanFile(::std::istream& in, /* out */ size_t& numLinesAffected, /* out */ size_t& numSpacesStripped, /* out */ size_t& numTabsStripped, ::std::ostream* pOut = nullptr); static void updateCounts(::std::string const& wsRun, /* in-out */ size_t& numLinesAffected, /* in-out */ size_t& numSpacesStripped, /* in-out */ size_t& numTabsStripped); static void replaceOriginalFileWithTemp(const Path& originalPath, const Path& tempPath); bool m_isInQueryMode; FileEnumerator m_fileEnumerator; }; #endif // STRIPWS_H_INCLUDED
Instruments
# ========================================================================================================================= # Theoretical error bounds for Carleman linearization # # References: # # - [1] Forets, Marcelo, and Amaury Pouly. "Explicit error bounds for carleman linearization." # arXiv preprint arXiv:1711.02552 (2017). # # - [2] Liu, J. P., Kolden, H. Ø., Krovi, H. K., Loureiro, N. F., Trivisa, K., & Childs,7 # A. M. (2021). "Efficient quantum algorithm for dissipative nonlinear differential equations." # Proceedings of the National Academy of Sciences, 118(35). arXiv preprint arXiv:2011.03185. # # ========================================================================================================================= # --- Error bounds using a priori estimate from [1] --- # See Theorem 4.2 in [1]. This is a bound based on an a priori estimate # of the norm of the exact solution x(t). # These bounds use the supremum norm (p = Inf). function error_bound_apriori(α, F₁, F₂; N) nF₂ = opnorm(F₂, Inf) μF₁ = logarithmic_norm(F₁, Inf) β = α * nF₂ / μF₁ ε = t -> α * β^N * (exp(μF₁ * t) - 1)^N return ε end # See Theorem 4.2 in [1] function convergence_radius_apriori(α, F₁, F₂; N) nF₂ = opnorm(F₂, Inf) μF₁ = logarithmic_norm(F₁, Inf) if μF₁ < 0 return Inf end β = α * F₂ / μF₁ T = (1/μF₁) * log(1 + 1/β) return T end # --- Error bounds using power series method from [1] --- # See Theorem 4.3 in [1], which uses the power series method. function error_bound_pseries(x₀, F₁, F₂; N) nx₀ = norm(x₀, Inf) nF₁ = opnorm(F₁, Inf) nF₂ = opnorm(F₂, Inf) β₀ = nx₀ * nF₂ / nF₁ ε = t -> nx₀ * exp(nF₁ * t) / (1 - β₀ * (exp(nF₁ * t) - 1)) * (β₀ * (exp(nF₁ * t) - 1))^N return ε end # See Theorem 4.3 in [1]. function convergence_radius_pseries(x₀, F₁, F₂; N) nx₀ = norm(x₀, Inf) nF₁ = opnorm(F₁, Inf) nF₂ = opnorm(F₂, Inf) β₀ = nx₀ * nF₂ / nF₁ T = (1/nF₁) * log(1 + 1/β₀) return T end # --- Error bounds using spectral abscissa from [2] --- # See Definition (2.2) in [2]. These bounds use the spectral norm (p = 2) function _error_bound_specabs_R(x₀, F₁, F₂; check=true) nx₀ = norm(x₀, 2) nF₂ = opnorm(F₂, 2) # compute eigenvalues and sort them by increasing real part λ = eigvals(F₁, sortby=real) λ₁ = last(λ) Re_λ₁ = real(λ₁) if check @assert Re_λ₁ <= 0 "expected Re(λ₁) ≤ 0, got $Re_λ₁" end R = nx₀ * nF₂ / abs(Re_λ₁) return (R, Re_λ₁) end # See Lemma 2 in [2] function error_bound_specabs(x₀, F₁, F₂; N, check=true) (R, Re_λ₁) = _error_bound_specabs_R(x₀, F₁, F₂; check=check) if check @assert R < 1 "expected R < 1, got R = $R; try scaling the ODE" end nx₀ = norm(x₀, 2) if iszero(Re_λ₁) nF₂ = opnorm(F₂, 2) ε = t -> nx₀ * (nx₀ * nF₂ * t)^N else ε = t -> nx₀ * R^N * (1 - exp(Re_λ₁ * t))^N end return ε end # See Lemma 2 in [2] function convergence_radius_specabs(x₀, F₁, F₂; check=true) (R, Re_λ₁) = _error_bound_specabs_R(x₀, F₁, F₂; check=check) if Re_λ₁ < 0 T = Inf elseif iszero(Re_λ₁) nx₀ = norm(x₀, 2) nF₂ = opnorm(F₂, 2) β = nx₀ * nF₂ T = 1/β else throw(ArgumentError("expected spectral abscissa to be negative or zero, got $Re_λ₁")) end return T end
State Before: C : Type u₁ D : Type u₂ inst✝³ : Category C inst✝² : Category D F : C ⥤ D X Y : C f : X ⟶ Y inst✝¹ : PreservesLimit (cospan f f) F inst✝ : Mono f ⊢ Mono (F.map f) State After: C : Type u₁ D : Type u₂ inst✝³ : Category C inst✝² : Category D F : C ⥤ D X Y : C f : X ⟶ Y inst✝¹ : PreservesLimit (cospan f f) F inst✝ : Mono f this : let_fun this := (_ : F.map (𝟙 X) ≫ F.map f = F.map (𝟙 X) ≫ F.map f); IsLimit (PullbackCone.mk (F.map (𝟙 X)) (F.map (𝟙 X)) this) ⊢ Mono (F.map f) Tactic: have := isLimitPullbackConeMapOfIsLimit F _ (PullbackCone.isLimitMkIdId f) State Before: C : Type u₁ D : Type u₂ inst✝³ : Category C inst✝² : Category D F : C ⥤ D X Y : C f : X ⟶ Y inst✝¹ : PreservesLimit (cospan f f) F inst✝ : Mono f this : let_fun this := (_ : F.map (𝟙 X) ≫ F.map f = F.map (𝟙 X) ≫ F.map f); IsLimit (PullbackCone.mk (F.map (𝟙 X)) (F.map (𝟙 X)) this) ⊢ Mono (F.map f) State After: C : Type u₁ D : Type u₂ inst✝³ : Category C inst✝² : Category D F : C ⥤ D X Y : C f : X ⟶ Y inst✝¹ : PreservesLimit (cospan f f) F inst✝ : Mono f this : IsLimit (PullbackCone.mk (𝟙 (F.obj X)) (𝟙 (F.obj X)) (_ : 𝟙 (F.obj X) ≫ F.map f = 𝟙 (F.obj X) ≫ F.map f)) ⊢ Mono (F.map f) Tactic: simp_rw [F.map_id] at this State Before: C : Type u₁ D : Type u₂ inst✝³ : Category C inst✝² : Category D F : C ⥤ D X Y : C f : X ⟶ Y inst✝¹ : PreservesLimit (cospan f f) F inst✝ : Mono f this : IsLimit (PullbackCone.mk (𝟙 (F.obj X)) (𝟙 (F.obj X)) (_ : 𝟙 (F.obj X) ≫ F.map f = 𝟙 (F.obj X) ≫ F.map f)) ⊢ Mono (F.map f) State After: no goals Tactic: apply PullbackCone.mono_of_isLimitMkIdId _ this
lemma coeffs_pderiv_code [code abstract]: "coeffs (pderiv p) = pderiv_coeffs (coeffs p)"
During the off @-@ season the Blue Jackets parted ways with defensemen Jan Hejda , Anton Stralman , Sami <unk> and Mike Commodore . Hejda , who played four of his first five NHL seasons with the Blue Jackets , was offered a contract by Columbus , but felt that the organization undervalued him and left via free agency . Columbus had offered him a three @-@ year , $ 7 @.@ 5 million contract . He instead signed a four @-@ year , $ 13 million deal with the Colorado Avalanche . Stralman and <unk> were not given qualifying offers which made them unrestricted free agents , and both signed with other teams . Commodore had originally signed a big contract with the Blue Jackets in 2008 , but fell out of favor . He was waived , sent to the minors and eventually had his contract bought out . In order to replace the departed players , Columbus not only acquired James Wisniewski , but also signed ten @-@ year NHL veteran Radek <unk> . <unk> played only seven games with the Blue Jackets before suffering a concussion and missing the remainder of the season . Brett <unk> was brought in to replace him .
function com = pop_expevents(EEG, filename, unit) % pop_expevents() - export events to CSV file % % Usage: % >> pop_expevents(EEG); % >> pop_expevents(EEG, filename); % >> pop_expevents(EEG, filename, unit); % % Inputs: % EEG - EEGLAB dataset % filename - text file name % unit - display latency and duration in 'samples' (default) or 'seconds' % % Outputs: % com - Command to execute this function from the command line % % Examples: % Export all events and show a dialog window: % >> pop_expevents(EEG); % % Export all events to a file, latency and duration in samples: % >> pop_expevents(EEG, filename); % % Export all events to a file, latency and duration in seconds: % >> pop_expevents(EEG, filename, 'seconds'); % Copyright by Clemens Brunner <[email protected]> % Revision: 0.10 % Date: 09/16/2011 % Revision history: % 0.10: Initial version % This program is free software; you can redistribute it and/or modify it under % the terms of the GNU General Public License as published by the Free Software % Foundation; either version 2 of the License, or (at your option) any later % version. % % This program is distributed in the hope that it will be useful, but WITHOUT % ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS % FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. % % You should have received a copy of the GNU General Public License along with % this program; if not, write to the Free Software Foundation, Inc., 59 Temple % Place - Suite 330, Boston, MA 02111-1307, USA. com = ''; if nargin < 1 help pop_expevents; return end if nargin < 2 [filename, filepath] = uiputfile('*.csv', 'File name -- pop_expevents()'); drawnow; if filename == 0 return; end filename = [filepath filename]; end; if nargin < 3 unit = 'samples'; end if ~(strcmp(unit, 'samples') || strcmp(unit, 'seconds')) error('Unit must be either ''samples'' or ''seconds''.'); end eeg_eventtable(EEG, 'dispTable', false, 'exportFile', filename, 'unit', unit); com = sprintf('pop_expevents(%s, ''%s'', ''%s'');', inputname(1), filename, unit);
The brand is sold in 275 stores worldwide and is worn by celebrities including Teri Hatcher , Nicole Kidman , Kelly Ripa , Paris Hilton , and Stefani herself . L.A.M.B sales have expanded from $ 40 million in 2005 to a predicted $ 90 million in 2007 . According to a Nordstrom spokesperson , the debut of L.A.M.B. ' s watch line , which sold out in two days , was the store 's most successful watch launch ever . The brand 's designs have appeared in W , Marie Claire , Elle , Lucky and InStyle .
library(gganimate) library(gapminder) library(gifski) ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, colour = country)) + geom_point(alpha = 0.7, show.legend = FALSE) + scale_colour_manual(values = country_colors) + scale_size(range = c(2, 12)) + scale_x_log10() + facet_wrap(~continent) + # What follows is specific for the gganimate package labs(title = 'Year: {frame_time}', x = 'GDP per capita', y = 'life expectancy') + transition_time(year) + ease_aes('linear') anim_save("GDP.gif", animation = last_animation(), path = "C:/Users/Stefan/OneDrive - MUNI/Github/R-for-students-of-literature")
! ! CalculiX - A 3-dimensional finite element program ! Copyright (C) 1998-2021 Guido Dhondt ! ! This program is free software; you can redistribute it and/or ! modify it under the terms of the GNU General Public License as ! published by the Free Software Foundation(version 2); ! ! ! This program is distributed in the hope that it will be useful, ! but WITHOUT ANY WARRANTY; without even the implied warranty of ! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ! GNU General Public License for more details. ! ! You should have received a copy of the GNU General Public License ! along with this program; if not, write to the Free Software ! Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ! subroutine constraints(inpc,textpart,istat,n, & iline,ipol,inl,ipoinp,inp,ipoinpc,nobject,objectset, & ier,nmethod) ! ! reading the input deck: *CONSTRAINT ! implicit none ! logical copy ! character*1 inpc(*) character*132 textpart(16) character*81 objectset(5,*),drname ! integer istat,n,key,i,iline,ipol,inl,ipoinp(2,*), & inp(3,*),ipoinpc(0:*),nobject,ier,nmethod,iobject, & j,icopy ! real*8 relval,absval ! ! constraints can only be defined within feasible direction steps. ! We ensure that's the case below ! if(nmethod.ne.16) then write(*,*) '*ERROR reading *CONSTRAINT' write(*,*) ' *CONSTRAINT can only be specified' write(*,*) ' within a *FEASIBILE DIRECTION step.' call inputerror(inpc,ipoinpc,iline,"*CONSTRAINT%",ier) return endif ! ! one can define multiple constraints under a single *CONSTRAINT flag which ! means that we need to loop over all of them. ! We do not know how many there are so we run until the line does not ! contain a key or we reached the end of the file. ! do ! ! reading the design response which should be used for this constraint ! we first get a new line and then check if the given name is not longer ! than 80 chars and the design response exists ! call getnewline(inpc,textpart,istat,n,key,iline,ipol,inl, & ipoinp,inp,ipoinpc) ! drname=textpart(1)(1:80) if((istat.lt.0).or.(key.eq.1)) then return else if(textpart(1)(81:81).ne.' ') then write(*,*) '*ERROR reading *CONSTRAINT' write(*,*) ' name of design response must not ' write(*,*) ' be longer than 80 chars.' call inputerror(inpc,ipoinpc,iline,"*CONSTRAINT%",ier) return endif endif ! ! check if design response exists and store the id in iobject; ! if the design response is already used for ! either a (geometric) constraint or an objective ! create a new entry in the objectset with the same name. ! iobject=0 copy=.false. icopy=0 ! do i=1,nobject if(objectset(5,i)(1:80).eq.drname) then if(objectset(5,i)(81:81).ne.' ') then icopy=i copy=.true. else iobject=i exit endif endif enddo ! ! no empty entry with the same name has been found ! -> create a new entry and increment nobject ! if(copy) then nobject=nobject+1 iobject=nobject do j=1,5 objectset(j,iobject)(1:81)=objectset(j,icopy)(1:81) enddo endif ! ! if iobject=0, there is no entry with the same name ! if(iobject.eq.0) then write(*,*) '*ERROR reading *CONSTRAINT' write(*,*) ' name of given design' write(*,*) ' response does not exist:', drname call inputerror(inpc,ipoinpc,iline,"*CONSTRAINT%",ier) return endif ! ! mark this entry as a constraint ! objectset(5,iobject)(81:81)='C' ! ! check the constraint mode (LE, GE) ! throw an error if either its not given or not recognised. ! if(n.ge.2) then if(textpart(2)(1:2).eq.'LE') then objectset(1,iobject)(19:20)='LE' elseif (textpart(2)(1:2).eq.'GE') then objectset(1,iobject)(19:20)='GE' else write(*,*) '*ERROR reading *CONSTRAINT' write(*,*) ' mode of constraint must be' write(*,*) ' either LE or GE' call inputerror(inpc,ipoinpc,iline,"*CONSTRAINT%",ier) return endif else write(*,*) '*ERROR reading *CONSTRAINT' write(*,*) ' mode of constraint must be' write(*,*) ' either LE or GE' call inputerror(inpc,ipoinpc,iline,"*CONSTRAINT%",ier) return endif ! ! some constraints accept relative or absolute constraint values. ! we parse those below ! if((objectset(1,iobject)(1:8).eq.'ALL-DISP').or. & (objectset(1,iobject)(1:6).eq.'X-DISP').or. & (objectset(1,iobject)(1:6).eq.'Y-DISP').or. & (objectset(1,iobject)(1:6).eq.'Z-DISP').or. & (objectset(1,iobject)(1:4).eq.'MASS').or. & (objectset(1,iobject)(1:11).eq.'MODALSTRESS').or. & (objectset(1,iobject)(1:12).eq.'STRAINENERGY').or. & (objectset(1,iobject)(1:6).eq.'STRESS')) then ! ! absolute constraint value ! if(n.ge.3) then read(textpart(3)(1:20),'(f20.0)',iostat=istat) relval if(istat.gt.0) then call inputerror(inpc,ipoinpc,iline,"*CONSTRAINT%",ier) return endif if(istat.le.0) then objectset(1,iobject)(41:60)=textpart(3)(1:20) endif endif ! ! relative constraint value ! if(n.ge.4) then read(textpart(4)(1:20),'(f20.0)',iostat=istat) absval if(istat.gt.0) then call inputerror(inpc,ipoinpc,iline,"*CONSTRAINT%",ier) return endif objectset(1,iobject)(61:80)=textpart(4)(1:20) endif endif enddo ! return end
import Lean import Lean.Parser.Syntax open Lean Elab Command Term /- ## `Syntax`: Solutions -/ /- ### 1. -/ namespace a scoped notation:71 lhs:50 " 💀 " rhs:72 => lhs - rhs end a namespace b set_option quotPrecheck false scoped infixl:71 " 💀 " => fun lhs rhs => lhs - rhs end b namespace c scoped syntax:71 term:50 " 💀 " term:72 : term scoped macro_rules | `($l:term 💀 $r:term) => `($l - $r) end c open a #eval 5 * 8 💀 4 -- 20 #eval 8 💀 6 💀 1 -- 1 /- ### 2. -/ syntax "good morning" : term syntax "hello" : command syntax "yellow" : tactic -- Note: the following are highlighted in red, however that's just because we haven't implemented the semantics ("elaboration function") yet - the syntax parsing stage works. #eval good morning -- works -- good morning -- error: `expected command` hello -- works -- #eval hello -- error: `expected term` example : 2 + 2 = 4 := by yellow -- works -- yellow -- error: `expected command` -- #eval yellow -- error: `unknown identifier 'yellow'` /- ### 3. -/ syntax (name := colors) (("blue"+) <|> ("red"+)) num : command @[command_elab colors] def elabColors : CommandElab := fun stx => Lean.logInfo "success!" blue blue 443 red red red 4 /- ### 4. -/ syntax (name := help) "#better_help" "option" (ident)? : command @[command_elab help] def elabHelp : CommandElab := fun stx => Lean.logInfo "success!" #better_help option #better_help option pp.r #better_help option some.other.name /- ### 5. -/ -- Note: std4 has to be in dependencies of your project for this to work. syntax (name := bigsumin) "∑ " Std.ExtendedBinder.extBinder "in " term "," term : term @[term_elab bigsumin] def elabSum : TermElab := fun stx tp => return mkNatLit 666 #eval ∑ x in { 1, 2, 3 }, x^2 def hi := (∑ x in { "apple", "banana", "cherry" }, x.length) + 1 #eval hi
module Bifunctor ||| Bifunctors ||| @p The action of the Bifunctor on pairs of objects public export interface Bifunctor (p : Type -> Type -> Type) where ||| The action of the Bifunctor on pairs of morphisms ||| ||| ````idris example ||| bimap (\x => x + 1) reverse (1, "hello") == (2, "olleh") ||| ```` ||| bimap : (a -> b) -> (c -> d) -> p a c -> p b d bimap f g = first f . second g ||| The action of the Bifunctor on morphisms pertaining to the first object ||| ||| ````idris example ||| first (\x => x + 1) (1, "hello") == (2, "hello") ||| ```` ||| first : (a -> b) -> p a c -> p b c first = flip bimap id ||| The action of the Bifunctor on morphisms pertaining to the second object ||| ||| ````idris example ||| second reverse (1, "hello") == (1, "olleh") ||| ```` ||| second : (a -> b) -> p c a -> p c b second = bimap id implementation Bifunctor Either where bimap f _ (Left a) = Left $ f a bimap _ g (Right b) = Right $ g b public export implementation Bifunctor Pair where bimap f g (a, b) = (f a, g b)
(** ---- _This file is part of_ ---- *** A Formal Definition of JML in Coq #<br/># and its Application to Runtime Assertion Checking Ph.D. Thesis by Hermann Lehner ---- Online available at #<a href="http://jmlcoq.info/">jmlcoq.info</a># Authors: - Hermann Lehner - David Pichardie (Bicolano) - Andreas Kaegi (Syntax Rewritings, Implementation of ADTs) Copyright 2011 Hermann Lehner Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ---- *) From Coq Require Import List Arith. (** Useful functions on lists, not part of the Coq standard library. Most functions are taken from the Haskell standard libary module Data.List. *) Section ListFunctions. Variable A : Type. Variable B : Type. Variable P : A -> Prop. Variable P_dec : forall a, {P a}+{~ P a}. (** Make a singleton list from the given element a. *) Definition singleton (a:A) : list A := a :: nil. (** Drop all prefix elements of l that satisfy p. *) Fixpoint dropWhile (p:A->bool) (l:list A) {struct l} : list A := match l with | nil => nil | (x::xs) => if p x then dropWhile p xs else xs end. (** Concatenate all given lists into a flat list. *) Definition concat : list (list A) -> list A := flat_map (fun x:list A => x). (** Maximum element of the given list of natural numbers. *) Fixpoint maximum (e:nat) (l:list nat) {struct l} : nat := match l with | nil => e | (x::xs) => max x (maximum e xs) end. (** Like fold_left but take e for the empty list. e is not used for a non-empty list. *) Definition fold_left1 (op:A->A->A) (l:list A) (e:A) : A := match l with | nil => e | x::xs => fold_left op xs x end. (** Like fold_right but take e for the empty list. e is not used for a non-empty list. *) Fixpoint fold_right1 (op:A->A->A) (l:list A) (e:A) : A := match l with | nil => e | x::nil => x | x::xs => op x (fold_right1 op xs e) end. Program Fixpoint Find (l : list A) {struct l} : { a : A | In a l & P a }+{ AllS (fun a' => ~ P a') l } := match l with | nil => inright _ | a0 :: l' => match P_dec a0 with | left Hdec => inleft (exist2 _ _ a0 _ _) | right Hdec => match Find l' with | inleft (exist2 _ _ a1 _ _) => inleft (exist2 _ _ a1 _ _) | inright Hdec => inright _ end end end. End ListFunctions. Arguments singleton [A]. Arguments dropWhile [A]. Arguments concat [A]. Arguments fold_left1 [A]. Arguments fold_right1 [A]. Inductive Expr : Set := | Lit : nat -> Expr | Add : Expr -> Expr -> Expr. (* Eval compute in fold_right1 Add (Lit 1 :: Lit 2 :: Lit 3 :: nil) (Lit 10). *) Section Proofs. Variable A : Type. (** For every element y in the result list (concat l), there exists a list x in l that contains y. *) Lemma in_concat : forall (l:list (list A)) (y:A), In y (concat l) <-> exists x, In x l /\ In y x. Proof. apply (in_flat_map (fun x:list A => x)). Qed. (** e is the maximum of the empty list. *) Lemma maximum_e_nil : forall (e:nat) (l:list nat), l=nil -> maximum e l=e. Proof. intros e l H. rewrite H. simpl. reflexivity. Qed. (** maximum is composable using max and cons. *) Lemma maximum_e_cons : forall (e:nat) (x:nat) (l:list nat), maximum e (x::l) = max x (maximum e l). Proof. intros e x l. simpl. reflexivity. Qed. (** fold_left1 op nil e = e *) Lemma fold_left1_e_nil : forall (op:A->A->A) (e:A) (l:list A), l=nil -> fold_left1 op l e = e. Proof. intros op e l H. rewrite H. simpl. reflexivity. Qed. (** fold_left1 op (x::l) e = fold_left1 op l x, e vanishes for a non-empty list. *) Lemma fold_left1_fold_left : forall (op:A->A->A) (e:A) (x:A) (l:list A), fold_left1 op (x::l) e = fold_left op l x. Proof. intros op e x l. simpl. reflexivity. Qed. (** The element found by find satisfies predicate p. *) Lemma find_def : forall (p:A->bool) (l:list A) (x:A), find p l = Some x -> p x = true. Proof. intros p l x H. induction l. (* BC *) discriminate H. (* IH *) simpl in H. assert (p a = true \/ p a = false). case (p a); auto. elim H0; intro Hpa; rewrite Hpa in H. congruence. auto. Qed. End Proofs.
Add LoadPath "D:\sfsol". Require Export Imp. Definition aequiv (a1 a2 : aexp) : Prop := forall (st:state), aeval st a1 = aeval st a2. Definition bequiv (b1 b2 : bexp) : Prop := forall (st:state), beval st b1 = beval st b2. Definition cequiv (c1 c2 : com) : Prop := forall (st st' : state), (c1 / st || st') <-> (c2 / st || st'). (* {a}{b}{c,h}{d}{e}{f,i}{g} *) Theorem aequiv_example: aequiv (AMinus (AId X) (AId X)) (ANum 0). Proof. unfold aequiv. intros. unfold aeval. induction (st X); simpl; try reflexivity; try assumption. Qed. Theorem bequiv_example: bequiv (BEq (AMinus (AId X) (AId X)) (ANum 0)) BTrue. Proof. unfold bequiv. intros. unfold beval. rewrite -> aequiv_example. simpl. auto. Qed. Theorem skip_left: forall c, cequiv (SKIP;; c) c. Proof. (* WORKED IN CLASS *) intros c st st'. split; intros H. Case "->". inversion H. subst. inversion H2. subst. assumption. Case "<-". apply E_Seq with st. apply E_Skip. assumption. Qed. Theorem skip_right: forall c, cequiv (c;; SKIP) c. Proof. intros c st st'. split; intros. inversion H. inversion H5. rewrite H8 in H2. auto. apply E_Seq with st'. auto. apply E_Skip. Qed. Theorem IFB_true_simple: forall c1 c2, cequiv (IFB BTrue THEN c1 ELSE c2 FI) c1. Proof. intros c1 c2 st st'. split; intros H. inversion H; try inversion H5; try auto. apply E_IfTrue; auto. Qed. Theorem IFB_true: forall b c1 c2, bequiv b BTrue -> cequiv (IFB b THEN c1 ELSE c2 FI) c1. Proof. intros b c1 c2 Hb. split; intros H. Case "->". inversion H; subst. SCase "b evaluates to true". assumption. SCase "b evaluates to false (contradiction)". rewrite Hb in H5. inversion H5. Case "<-". apply E_IfTrue; try assumption. rewrite Hb. reflexivity. Qed. Theorem IFB_false: forall b c1 c2, bequiv b BFalse -> cequiv (IFB b THEN c1 ELSE c2 FI) c2. Proof. intros b c1 c2 Hb. split; intros H. inversion H; subst. rewrite Hb in H5. inversion H5. auto. apply E_IfFalse; try rewrite Hb; auto. Qed. Theorem swap_if_branches: forall b e1 e2, cequiv (IFB b THEN e1 ELSE e2 FI) (IFB BNot b THEN e2 ELSE e1 FI). Proof. intros b e1 e2; split; intros H; inversion H; subst. apply E_IfFalse; simpl; try rewrite H5; try auto. apply E_IfTrue; simpl; try rewrite H5; try auto. apply E_IfFalse; inversion H5; destruct (beval st b); inversion H1; auto. apply E_IfTrue; inversion H5; destruct (beval st b); inversion H1; auto. Qed. Theorem WHILE_false : forall b c, bequiv b BFalse -> cequiv (WHILE b DO c END) SKIP. Proof. intros b c Hb st st'. split; intros H. inversion H; subst; try apply E_Skip; rewrite Hb in H2; inversion H2. inversion H; apply E_WhileEnd; rewrite Hb; auto. Qed. Lemma WHILE_true_nonterm : forall b c st st', bequiv b BTrue -> ~( (WHILE b DO c END) / st || st' ). Proof. (* WORKED IN CLASS *) intros b c st st' Hb. intros H. remember (WHILE b DO c END) as cw eqn:Heqcw. ceval_cases (induction H) Case; (* Most rules don't apply, and we can rule them out by inversion *) inversion Heqcw; subst; clear Heqcw. (* The two interesting cases are the ones for WHILE loops: *) Case "E_WhileEnd". (* contradictory -- b is always true! *) unfold bequiv in Hb. (* rewrite is able to instantiate the quantifier in st *) rewrite Hb in H. inversion H. Case "E_WhileLoop". (* immediate from the IH *) apply IHceval2. reflexivity. Qed. Theorem WHILE_true: forall b c, bequiv b BTrue -> cequiv (WHILE b DO c END) (WHILE BTrue DO SKIP END). Proof. intros b c Hb st st'. split; intros. assert (~(WHILE b DO c END) / st || st'). apply WHILE_true_nonterm. auto. apply H0 in H. inversion H. assert (~(WHILE BTrue DO SKIP END) / st || st'). apply loop_stop. auto. apply H0 in H. inversion H. Qed. Theorem loop_unrolling: forall b c, cequiv (WHILE b DO c END) (IFB b THEN (c;; WHILE b DO c END) ELSE SKIP FI). Proof. intros b c st st'. split; intros H. inversion H; subst. apply E_IfFalse; auto; try apply E_Skip. apply E_IfTrue; auto; try apply E_Seq with st'0; auto. inversion H; subst; inversion H6; subst. apply E_WhileLoop with st'0; auto. apply E_WhileEnd. auto. Qed. Theorem seq_assoc : forall c1 c2 c3, cequiv ((c1;;c2);;c3) (c1;;(c2;;c3)). Proof. intros c1 c2 c3 st st'; split; intros H. inversion H; subst; inversion H2; subst. apply E_Seq with st'1; auto. apply E_Seq with st'0; auto. inversion H; subst; inversion H5; subst. apply E_Seq with st'1; auto. apply E_Seq with st'0; auto. Qed. Axiom functional_extensionality : forall {X Y: Type} {f g : X -> Y}, (forall (x: X), f x = g x) -> f = g. Theorem identity_assignment : forall (X:id), cequiv (X ::= AId X) SKIP. Proof. intros. split; intro H. Case "->". inversion H; subst. simpl. replace (update st X (st X)) with st. constructor. apply functional_extensionality. intro. rewrite update_same; reflexivity. Case "<-". inversion H; subst. assert (st' = (update st' X (st' X))). apply functional_extensionality. intro. rewrite update_same; reflexivity. rewrite H0 at 2. constructor. reflexivity. Qed. Theorem assign_aequiv : forall X e, aequiv (AId X) e -> cequiv SKIP (X ::= e). Proof. intros X e He st st'; split; intros H. inversion H. replace ((X ::= e) / st' || st') with ((X ::= e) / st' || update st' X (aeval st' e)). constructor; auto. replace (update st' X (aeval st' e)) with st'. auto. apply functional_extensionality. intro. rewrite update_same; auto; apply He. inversion H; subst. replace (update st X (aeval st e)) with st. constructor. apply functional_extensionality. intro. rewrite update_same; auto. apply He. Qed. Lemma refl_aequiv : forall (a : aexp), aequiv a a. Proof. intros a st. auto. Qed. Lemma sym_aequiv : forall (a1 a2 : aexp), aequiv a1 a2 -> aequiv a2 a1. Proof. intros a1 a2 H st. symmetry. apply H. Qed. Lemma trans_aequiv : forall (a1 a2 a3 : aexp), aequiv a1 a2 -> aequiv a2 a3 -> aequiv a1 a3. Proof. intros a1 a2 a3 H1 H2 st. rewrite H1. auto. Qed. Lemma refl_bequiv : forall (b : bexp), bequiv b b. Proof. intros b st. auto. Qed. Lemma sym_bequiv : forall (b1 b2 : bexp), bequiv b1 b2 -> bequiv b2 b1. Proof. intros b1 b2 H st. auto. Qed. Lemma trans_bequiv : forall (b1 b2 b3 : bexp), bequiv b1 b2 -> bequiv b2 b3 -> bequiv b1 b3. Proof. intros b1 b2 b3 H1 H2 st. rewrite H1. auto. Qed. Lemma refl_cequiv : forall (c : com), cequiv c c. Proof. intros c st; split; intros H; auto. Qed. Lemma sym_cequiv : forall (c1 c2 : com), cequiv c1 c2 -> cequiv c2 c1. Proof. intros c1 c2 H st; split; apply H. Qed. Lemma iff_trans : forall (P1 P2 P3 : Prop), (P1 <-> P2) -> (P2 <-> P3) -> (P1 <-> P3). Proof. intros P1 P2 P3 H1 H2; split. rewrite H1. apply H2. rewrite <- H2. apply H1. Qed. Lemma trans_cequiv : forall (c1 c2 c3 : com), cequiv c1 c2 -> cequiv c2 c3 -> cequiv c1 c3. Proof. intros c1 c2 c3 H1 H2 st; split; intros H. apply H2. apply H1. apply H. apply H1. apply H2. apply H. Qed. Theorem CAss_congruence : forall i a1 a1', aequiv a1 a1' -> cequiv (CAss i a1) (CAss i a1'). Proof. intros; split; intro; inversion H0; subst; apply E_Ass; rewrite H; auto. Qed. Theorem CWhile_congruence : forall b1 b1' c1 c1', bequiv b1 b1' -> cequiv c1 c1' -> cequiv (WHILE b1 DO c1 END) (WHILE b1' DO c1' END). Proof. (* WORKED IN CLASS *) unfold bequiv,cequiv. intros b1 b1' c1 c1' Hb1e Hc1e st st'. split; intros Hce. Case "->". remember (WHILE b1 DO c1 END) as cwhile eqn:Heqcwhile. induction Hce; inversion Heqcwhile; subst. SCase "E_WhileEnd". apply E_WhileEnd. rewrite <- Hb1e. apply H. SCase "E_WhileLoop". apply E_WhileLoop with (st' := st'). SSCase "show loop runs". rewrite <- Hb1e. apply H. SSCase "body execution". apply (Hc1e st st'). apply Hce1. SSCase "subsequent loop execution". apply IHHce2. reflexivity. Case "<-". remember (WHILE b1' DO c1' END) as c'while eqn:Heqc'while. induction Hce; inversion Heqc'while; subst. SCase "E_WhileEnd". apply E_WhileEnd. rewrite -> Hb1e. apply H. SCase "E_WhileLoop". apply E_WhileLoop with (st' := st'). SSCase "show loop runs". rewrite -> Hb1e. apply H. SSCase "body execution". apply (Hc1e st st'). apply Hce1. SSCase "subsequent loop execution". apply IHHce2. reflexivity. Qed. Theorem CSeq_congruence : forall c1 c1' c2 c2', cequiv c1 c1' -> cequiv c2 c2' -> cequiv (c1;;c2) (c1';;c2'). Proof. intros c1 c1' c2 c2' H1 H2 st st'; split; intros H; inversion H; subst; apply E_Seq with st'0; try apply H1; try apply H2; auto. Qed. Theorem CIf_congruence : forall b b' c1 c1' c2 c2', bequiv b b' -> cequiv c1 c1' -> cequiv c2 c2' -> cequiv (IFB b THEN c1 ELSE c2 FI) (IFB b' THEN c1' ELSE c2' FI). Proof. intros; split; intros Htmp; inversion Htmp; subst. rewrite H in H7; apply E_IfTrue; auto; apply H0; auto. rewrite H in H7; apply E_IfFalse; auto; apply H1; auto. rewrite <- H in H7; apply E_IfTrue; auto; apply H0; auto. rewrite <- H in H7; apply E_IfFalse; auto; apply H1; auto. Qed. Example congruence_example: cequiv (* Program 1: *) (X ::= ANum 0;; IFB (BEq (AId X) (ANum 0)) THEN Y ::= ANum 0 ELSE Y ::= ANum 42 FI) (* Program 2: *) (X ::= ANum 0;; IFB (BEq (AId X) (ANum 0)) THEN Y ::= AMinus (AId X) (AId X) (* <--- changed here *) ELSE Y ::= ANum 42 FI). Proof. apply CSeq_congruence. apply refl_cequiv. apply CIf_congruence. apply refl_bequiv. apply CAss_congruence. unfold aequiv. simpl. symmetry. apply minus_diag. apply refl_cequiv. Qed. Definition atrans_sound (atrans : aexp -> aexp) : Prop := forall (a : aexp), aequiv a (atrans a). Definition btrans_sound (btrans : bexp -> bexp) : Prop := forall (b : bexp), bequiv b (btrans b). Definition ctrans_sound (ctrans : com -> com) : Prop := forall (c : com), cequiv c (ctrans c). Fixpoint fold_constants_aexp (a : aexp) : aexp := match a with | ANum n => ANum n | AId i => AId i | APlus a1 a2 => match (fold_constants_aexp a1, fold_constants_aexp a2) with | (ANum n1, ANum n2) => ANum (n1 + n2) | (a1', a2') => APlus a1' a2' end | AMinus a1 a2 => match (fold_constants_aexp a1, fold_constants_aexp a2) with | (ANum n1, ANum n2) => ANum (n1 - n2) | (a1', a2') => AMinus a1' a2' end | AMult a1 a2 => match (fold_constants_aexp a1, fold_constants_aexp a2) with | (ANum n1, ANum n2) => ANum (n1 * n2) | (a1', a2') => AMult a1' a2' end end. Example fold_aexp_ex1 : fold_constants_aexp (AMult (APlus (ANum 1) (ANum 2)) (AId X)) = AMult (ANum 3) (AId X). Proof. reflexivity. Qed. Example fold_aexp_ex2 : fold_constants_aexp (AMinus (AId X) (APlus (AMult (ANum 0) (ANum 6)) (AId Y))) = AMinus (AId X) (APlus (ANum 0) (AId Y)). Proof. reflexivity. Qed. Fixpoint fold_constants_bexp (b : bexp) : bexp := match b with | BTrue => BTrue | BFalse => BFalse | BEq a1 a2 => match (fold_constants_aexp a1, fold_constants_aexp a2) with | (ANum n1, ANum n2) => if beq_nat n1 n2 then BTrue else BFalse | (a1', a2') => BEq a1' a2' end | BLe a1 a2 => match (fold_constants_aexp a1, fold_constants_aexp a2) with | (ANum n1, ANum n2) => if ble_nat n1 n2 then BTrue else BFalse | (a1', a2') => BLe a1' a2' end | BNot b1 => match (fold_constants_bexp b1) with | BTrue => BFalse | BFalse => BTrue | b1' => BNot b1' end | BAnd b1 b2 => match (fold_constants_bexp b1, fold_constants_bexp b2) with | (BTrue, BTrue) => BTrue | (BTrue, BFalse) => BFalse | (BFalse, BTrue) => BFalse | (BFalse, BFalse) => BFalse | (b1', b2') => BAnd b1' b2' end end. Example fold_bexp_ex1 : fold_constants_bexp (BAnd BTrue (BNot (BAnd BFalse BTrue))) = BTrue. Proof. reflexivity. Qed. Example fold_bexp_ex2 : fold_constants_bexp (BAnd (BEq (AId X) (AId Y)) (BEq (ANum 0) (AMinus (ANum 2) (APlus (ANum 1) (ANum 1))))) = BAnd (BEq (AId X) (AId Y)) BTrue. Proof. reflexivity. Qed. Fixpoint fold_constants_com (c : com) : com := match c with | SKIP => SKIP | i ::= a => CAss i (fold_constants_aexp a) | c1 ;; c2 => (fold_constants_com c1) ;; (fold_constants_com c2) | IFB b THEN c1 ELSE c2 FI => match fold_constants_bexp b with | BTrue => fold_constants_com c1 | BFalse => fold_constants_com c2 | b' => IFB b' THEN fold_constants_com c1 ELSE fold_constants_com c2 FI end | WHILE b DO c END => match fold_constants_bexp b with | BTrue => WHILE BTrue DO SKIP END | BFalse => SKIP | b' => WHILE b' DO (fold_constants_com c) END end end. Example fold_com_ex1 : fold_constants_com (* Original program: *) (X ::= APlus (ANum 4) (ANum 5);; Y ::= AMinus (AId X) (ANum 3);; IFB BEq (AMinus (AId X) (AId Y)) (APlus (ANum 2) (ANum 4)) THEN SKIP ELSE Y ::= ANum 0 FI;; IFB BLe (ANum 0) (AMinus (ANum 4) (APlus (ANum 2) (ANum 1))) THEN Y ::= ANum 0 ELSE SKIP FI;; WHILE BEq (AId Y) (ANum 0) DO X ::= APlus (AId X) (ANum 1) END) = (* After constant folding: *) (X ::= ANum 9;; Y ::= AMinus (AId X) (ANum 3);; IFB BEq (AMinus (AId X) (AId Y)) (ANum 6) THEN SKIP ELSE (Y ::= ANum 0) FI;; Y ::= ANum 0;; WHILE BEq (AId Y) (ANum 0) DO X ::= APlus (AId X) (ANum 1) END). Proof. reflexivity. Qed. Theorem fold_constants_aexp_sound : atrans_sound fold_constants_aexp. Proof. intros a st. induction a; try auto; simpl; remember (fold_constants_aexp a1) as af1; destruct af1; remember (fold_constants_aexp a2) as af2; destruct af2; rewrite IHa1; rewrite IHa2; auto. Qed. Theorem fold_constants_bexp_sound: btrans_sound fold_constants_bexp. Proof. unfold btrans_sound. intros b. unfold bequiv. intros st. bexp_cases (induction b) Case; (* BTrue and BFalse are immediate *) try reflexivity. Case "BEq". (* Doing induction when there are a lot of constructors makes specifying variable names a chore, but Coq doesn't always choose nice variable names. We can rename entries in the context with the rename tactic: rename a into a1 will change a to a1 in the current goal and context. *) rename a into a1. rename a0 into a2. simpl. remember (fold_constants_aexp a1) as a1' eqn:Heqa1'. remember (fold_constants_aexp a2) as a2' eqn:Heqa2'. replace (aeval st a1) with (aeval st a1') by (subst a1'; rewrite <- fold_constants_aexp_sound; reflexivity). replace (aeval st a2) with (aeval st a2') by (subst a2'; rewrite <- fold_constants_aexp_sound; reflexivity). destruct a1'; destruct a2'; try reflexivity. (* The only interesting case is when both a1 and a2 become constants after folding *) simpl. destruct (beq_nat n n0); reflexivity. Case "BLe". simpl. rewrite -> fold_constants_aexp_sound. replace (aeval st a0) with (aeval st (fold_constants_aexp a0)). remember (fold_constants_aexp a) as af; remember (fold_constants_aexp a0) as af0; destruct af; simpl; try auto. destruct af0; simpl; try auto. destruct (ble_nat n n0); auto. rewrite <- fold_constants_aexp_sound. auto. Case "BNot". simpl. remember (fold_constants_bexp b) as b' eqn:Heqb'. rewrite IHb. destruct b'; reflexivity. Case "BAnd". simpl. remember (fold_constants_bexp b1) as b1' eqn:Heqb1'. remember (fold_constants_bexp b2) as b2' eqn:Heqb2'. rewrite IHb1. rewrite IHb2. destruct b1'; destruct b2'; reflexivity. Qed. Theorem fold_constants_com_sound : ctrans_sound fold_constants_com. Proof. unfold ctrans_sound. intros c. com_cases (induction c) Case; simpl. Case "SKIP". apply refl_cequiv. Case "::=". apply CAss_congruence. apply fold_constants_aexp_sound. Case ";;". apply CSeq_congruence; assumption. Case "IFB". assert (bequiv b (fold_constants_bexp b)). SCase "Pf of assertion". apply fold_constants_bexp_sound. destruct (fold_constants_bexp b) eqn:Heqb; (* If the optimization doesn't eliminate the if, then the result is easy to prove from the IH and fold_constants_bexp_sound *) try (apply CIf_congruence; assumption). SCase "b always true". apply trans_cequiv with c1; try assumption. apply IFB_true; assumption. SCase "b always false". apply trans_cequiv with c2; try assumption. apply IFB_false; assumption. Case "WHILE". assert (bequiv b (fold_constants_bexp b)). apply fold_constants_bexp_sound. destruct (fold_constants_bexp b) eqn:Heqb. apply WHILE_true; auto. apply WHILE_false; auto. try apply CWhile_congruence; auto. try apply CWhile_congruence; auto. try apply CWhile_congruence; auto. try apply CWhile_congruence; auto. Qed. Fixpoint optimize_0plus_aexp (e:aexp) : aexp := match e with | ANum n => ANum n | AId i => AId i | APlus (ANum 0) e2 => optimize_0plus_aexp e2 | APlus e1 e2 => APlus (optimize_0plus_aexp e1) (optimize_0plus_aexp e2) | AMinus e1 e2 => AMinus (optimize_0plus_aexp e1) (optimize_0plus_aexp e2) | AMult e1 e2 => AMult (optimize_0plus_aexp e1) (optimize_0plus_aexp e2) end. Fixpoint optimize_0plus_bexp (b : bexp) : bexp := match b with | BTrue => BTrue | BFalse => BFalse | BEq a1 a2 => BEq (optimize_0plus_aexp a1) (optimize_0plus_aexp a2) | BLe a1 a2 => BLe (optimize_0plus_aexp a1) (optimize_0plus_aexp a2) | BNot b1 => BNot (optimize_0plus_bexp b1) | BAnd b1 b2 => BAnd (optimize_0plus_bexp b1) (optimize_0plus_bexp b2) end. Fixpoint optimize_0plus_com (c : com) : com := match c with | SKIP => SKIP | i ::= a => CAss i (optimize_0plus_aexp a) | c1 ;; c2 => (optimize_0plus_com c1) ;; (optimize_0plus_com c2) | IFB b THEN c1 ELSE c2 FI => IFB (optimize_0plus_bexp b) THEN optimize_0plus_com c1 ELSE optimize_0plus_com c2 FI | WHILE b DO c END => WHILE (optimize_0plus_bexp b) DO (optimize_0plus_com c) END end. Theorem optimize_0plus_aexp_sound : atrans_sound optimize_0plus_aexp. Proof. intros a st. induction a; simpl; try auto. destruct a1 eqn:Heqa1; try simpl; auto. destruct n; simpl; auto. Qed. Theorem optimize_0plus_bexp_sound: btrans_sound optimize_0plus_bexp. Proof. intros b st. induction b; try auto; simpl; try rewrite <- optimize_0plus_aexp_sound; try rewrite <- optimize_0plus_aexp_sound; auto. rewrite IHb; auto. rewrite IHb1; rewrite IHb2; auto. Qed. Theorem optimize_0plus_com_sound : ctrans_sound optimize_0plus_com. Proof. unfold ctrans_sound. intros c. induction c; simpl. split; auto. apply CAss_congruence. apply optimize_0plus_aexp_sound. apply CSeq_congruence; auto. apply CIf_congruence; auto; try apply optimize_0plus_bexp_sound. apply CWhile_congruence; auto; try apply optimize_0plus_bexp_sound. Qed. Definition optimizer_0plus_const_com (c : com) : com := optimize_0plus_com (fold_constants_com c). Example optexam1 : optimizer_0plus_const_com (* Original program: *) (X ::= APlus (ANum 4) (ANum 5);; X ::= APlus (ANum 0) (AId X);; Y ::= AMinus (AId X) (ANum 3);; IFB BEq (AMinus (AId X) (AId Y)) (APlus (ANum 2) (ANum 4)) THEN SKIP ELSE Y ::= ANum 0 FI;; IFB BLe (ANum 0) (AMinus (ANum 4) (APlus (ANum 2) (ANum 1))) THEN Y ::= ANum 0 ELSE SKIP FI;; WHILE BEq (AId Y) (ANum 0) DO X ::= APlus (AId X) (ANum 1) END) = (* After constant folding: *) (X ::= ANum 9;; X ::= AId X;; Y ::= AMinus (AId X) (ANum 3);; IFB BEq (AMinus (AId X) (AId Y)) (ANum 6) THEN SKIP ELSE (Y ::= ANum 0) FI;; Y ::= ANum 0;; WHILE BEq (AId Y) (ANum 0) DO X ::= APlus (AId X) (ANum 1) END). Proof. reflexivity. Qed. Theorem optimizer_0plus_const_com_sound : ctrans_sound optimizer_0plus_const_com. Proof. unfold ctrans_sound. intro. unfold optimizer_0plus_const_com. split. intro. apply fold_constants_com_sound in H. apply optimize_0plus_com_sound in H. auto. intros. apply fold_constants_com_sound. apply optimize_0plus_com_sound. auto. Qed. Fixpoint subst_aexp (i : id) (u : aexp) (a : aexp) : aexp := match a with | ANum n => ANum n | AId i' => if eq_id_dec i i' then u else AId i' | APlus a1 a2 => APlus (subst_aexp i u a1) (subst_aexp i u a2) | AMinus a1 a2 => AMinus (subst_aexp i u a1) (subst_aexp i u a2) | AMult a1 a2 => AMult (subst_aexp i u a1) (subst_aexp i u a2) end. Example subst_aexp_ex : subst_aexp X (APlus (ANum 42) (ANum 53)) (APlus (AId Y) (AId X)) = (APlus (AId Y) (APlus (ANum 42) (ANum 53))). Proof. reflexivity. Qed. Definition subst_equiv_property := forall i1 i2 a1 a2, cequiv (i1 ::= a1;; i2 ::= a2) (i1 ::= a1;; i2 ::= subst_aexp i1 a1 a2). Theorem subst_inequiv : ~ subst_equiv_property. Proof. unfold subst_equiv_property. intros Contra. (* Here is the counterexample: assuming that subst_equiv_property holds allows us to prove that these two programs are equivalent... *) remember (X ::= APlus (AId X) (ANum 1);; Y ::= AId X) as c1. remember (X ::= APlus (AId X) (ANum 1);; Y ::= APlus (AId X) (ANum 1)) as c2. assert (cequiv c1 c2) by (subst; apply Contra). (* ... allows us to show that the command c2 can terminate in two different final states: st1 = {X |-> 1, Y |-> 1} st2 = {X |-> 1, Y |-> 2}. *) remember (update (update empty_state X 1) Y 1) as st1. remember (update (update empty_state X 1) Y 2) as st2. assert (H1: c1 / empty_state || st1); assert (H2: c2 / empty_state || st2); try (subst; apply E_Seq with (st' := (update empty_state X 1)); apply E_Ass; reflexivity). apply H in H1. (* Finally, we use the fact that evaluation is deterministic to obtain a contradiction. *) assert (Hcontra: st1 = st2) by (apply (ceval_deterministic c2 empty_state); assumption). assert (Hcontra': st1 Y = st2 Y) by (rewrite Hcontra; reflexivity). subst. inversion Hcontra'. Qed. Inductive var_not_used_in_aexp (X:id) : aexp -> Prop := | VNUNum: forall n, var_not_used_in_aexp X (ANum n) | VNUId: forall Y, X <> Y -> var_not_used_in_aexp X (AId Y) | VNUPlus: forall a1 a2, var_not_used_in_aexp X a1 -> var_not_used_in_aexp X a2 -> var_not_used_in_aexp X (APlus a1 a2) | VNUMinus: forall a1 a2, var_not_used_in_aexp X a1 -> var_not_used_in_aexp X a2 -> var_not_used_in_aexp X (AMinus a1 a2) | VNUMult: forall a1 a2, var_not_used_in_aexp X a1 -> var_not_used_in_aexp X a2 -> var_not_used_in_aexp X (AMult a1 a2). Lemma aeval_weakening : forall i st a ni, var_not_used_in_aexp i a -> aeval (update st i ni) a = aeval st a. Proof. intros. induction a; inversion H; simpl; try auto; try rewrite IHa1; try rewrite IHa2; auto. apply neq_id. auto. Qed. Definition subst_equiv_property' := forall i1 i2 a1 a2, var_not_used_in_aexp i1 a1 -> cequiv (i1 ::= a1;; i2 ::= a2) (i1 ::= a1;; i2 ::= subst_aexp i1 a1 a2). Theorem subst_equiv : subst_equiv_property'. Proof. intros i1 i2 a1 a2 H. split; intro; inversion H0; subst. apply E_Seq with st'0; auto. clear H0. generalize dependent st'. induction a2. intros. simpl. auto. intros; inversion H6; subst; simpl; try apply E_Ass; auto; simpl; try rewrite IHa2_1. destruct (eq_id_dec i1 i) eqn:eqid; auto. inversion H3; subst. simpl. rewrite aeval_weakening; auto. unfold update. rewrite eq_id. auto. intros. inversion H6; subst. assert((i2 ::= subst_aexp i1 a1 a2_1) / st'0 || update st'0 i2 (aeval st'0 a2_1)). apply IHa2_1. constructor. auto. assert((i2 ::= subst_aexp i1 a1 a2_2) / st'0 || update st'0 i2 (aeval st'0 a2_2)). apply IHa2_2. constructor. auto. simpl. apply E_Ass. simpl. assert(aeval st'0 (subst_aexp i1 a1 a2_1) = aeval st'0 a2_1). inversion H0. rewrite H7. assert (update st'0 i2 n i2 = update st'0 i2 (aeval st'0 a2_1) i2). rewrite H8; auto. rewrite update_eq in H9. rewrite update_eq in H9. auto. assert(aeval st'0 (subst_aexp i1 a1 a2_2) = aeval st'0 a2_2). inversion H1. rewrite H8. assert (update st'0 i2 n i2 = update st'0 i2 (aeval st'0 a2_2) i2). rewrite H9; auto. rewrite update_eq in H10. rewrite update_eq in H10. auto. rewrite H2. rewrite H4. auto. intros. assert((i2 ::= subst_aexp i1 a1 a2_1) / st'0 || update st'0 i2 (aeval st'0 a2_1)). apply IHa2_1. constructor. auto. assert((i2 ::= subst_aexp i1 a1 a2_2) / st'0 || update st'0 i2 (aeval st'0 a2_2)). apply IHa2_2. constructor. auto. inversion H6; subst. simpl. apply E_Ass. simpl. assert(aeval st'0 (subst_aexp i1 a1 a2_1) = aeval st'0 a2_1). inversion H0. rewrite H7. assert (update st'0 i2 n i2 = update st'0 i2 (aeval st'0 a2_1) i2). rewrite H8; auto. rewrite update_eq in H9. rewrite update_eq in H9. auto. assert(aeval st'0 (subst_aexp i1 a1 a2_2) = aeval st'0 a2_2). inversion H1. rewrite H8. assert (update st'0 i2 n i2 = update st'0 i2 (aeval st'0 a2_2) i2). rewrite H9; auto. rewrite update_eq in H10. rewrite update_eq in H10. auto. rewrite H2. rewrite H4. auto. intros. assert((i2 ::= subst_aexp i1 a1 a2_1) / st'0 || update st'0 i2 (aeval st'0 a2_1)). apply IHa2_1. constructor. auto. assert((i2 ::= subst_aexp i1 a1 a2_2) / st'0 || update st'0 i2 (aeval st'0 a2_2)). apply IHa2_2. constructor. auto. inversion H6; subst. simpl. apply E_Ass. simpl. assert(aeval st'0 (subst_aexp i1 a1 a2_1) = aeval st'0 a2_1). inversion H0. rewrite H7. assert (update st'0 i2 n i2 = update st'0 i2 (aeval st'0 a2_1) i2). rewrite H8; auto. rewrite update_eq in H9. rewrite update_eq in H9. auto. assert(aeval st'0 (subst_aexp i1 a1 a2_2) = aeval st'0 a2_2). inversion H1. rewrite H8. assert (update st'0 i2 n i2 = update st'0 i2 (aeval st'0 a2_2) i2). rewrite H9; auto. rewrite update_eq in H10. rewrite update_eq in H10. auto. rewrite H2. rewrite H4. auto. intros. apply E_Seq with st'0. auto. generalize dependent st'. induction a2; intros; inversion H6; subst; auto. destruct (eq_id_dec i1 i). apply E_Ass. rewrite <- e. inversion H3; subst. assert(aeval (update st i (aeval st a1)) a1 = aeval st a1). rewrite aeval_weakening; auto. rewrite H1. simpl. apply update_eq. apply E_Ass. auto. assert((i2 ::= a2_1) / st'0 || update st'0 i2 (aeval st'0 (subst_aexp i1 a1 a2_1))). apply IHa2_1. apply E_Seq with st'0. auto. apply E_Ass. auto. apply E_Ass. auto. assert((i2 ::= a2_2) / st'0 || update st'0 i2 (aeval st'0 (subst_aexp i1 a1 a2_2))). apply IHa2_2. apply E_Seq with st'0. auto. apply E_Ass. auto. apply E_Ass. auto. inversion H1; subst. inversion H2; subst. apply E_Ass. simpl. assert(aeval st'0 a2_1 = aeval st'0 (subst_aexp i1 a1 a2_1)). symmetry. rewrite <- update_eq with (X:=i2) (st:=st'0). symmetry. rewrite <- update_eq with (X:=i2) (st:=st'0). rewrite H9. auto. assert(aeval st'0 a2_2 = aeval st'0 (subst_aexp i1 a1 a2_2)). symmetry. rewrite <- update_eq with (X:=i2) (st:=st'0). symmetry. rewrite <- update_eq with (X:=i2) (st:=st'0). rewrite H10. auto. rewrite <- H4. rewrite <- H5. auto. assert((i2 ::= a2_1) / st'0 || update st'0 i2 (aeval st'0 (subst_aexp i1 a1 a2_1))). apply IHa2_1. apply E_Seq with st'0. auto. apply E_Ass. auto. apply E_Ass. auto. assert((i2 ::= a2_2) / st'0 || update st'0 i2 (aeval st'0 (subst_aexp i1 a1 a2_2))). apply IHa2_2. apply E_Seq with st'0. auto. apply E_Ass. auto. apply E_Ass. auto. inversion H1; subst. inversion H2; subst. apply E_Ass. simpl. assert(aeval st'0 a2_1 = aeval st'0 (subst_aexp i1 a1 a2_1)). symmetry. rewrite <- update_eq with (X:=i2) (st:=st'0). symmetry. rewrite <- update_eq with (X:=i2) (st:=st'0). rewrite H9. auto. assert(aeval st'0 a2_2 = aeval st'0 (subst_aexp i1 a1 a2_2)). symmetry. rewrite <- update_eq with (X:=i2) (st:=st'0). symmetry. rewrite <- update_eq with (X:=i2) (st:=st'0). rewrite H10. auto. rewrite <- H4. rewrite <- H5. auto. assert((i2 ::= a2_1) / st'0 || update st'0 i2 (aeval st'0 (subst_aexp i1 a1 a2_1))). apply IHa2_1. apply E_Seq with st'0. auto. apply E_Ass. auto. apply E_Ass. auto. assert((i2 ::= a2_2) / st'0 || update st'0 i2 (aeval st'0 (subst_aexp i1 a1 a2_2))). apply IHa2_2. apply E_Seq with st'0. auto. apply E_Ass. auto. apply E_Ass. auto. inversion H1; subst. inversion H2; subst. apply E_Ass. simpl. assert(aeval st'0 a2_1 = aeval st'0 (subst_aexp i1 a1 a2_1)). symmetry. rewrite <- update_eq with (X:=i2) (st:=st'0). symmetry. rewrite <- update_eq with (X:=i2) (st:=st'0). rewrite H9. auto. assert(aeval st'0 a2_2 = aeval st'0 (subst_aexp i1 a1 a2_2)). symmetry. rewrite <- update_eq with (X:=i2) (st:=st'0). symmetry. rewrite <- update_eq with (X:=i2) (st:=st'0). rewrite H10. auto. rewrite <- H4. rewrite <- H5. auto. Qed. Theorem inequiv_exercise: ~ cequiv (WHILE BTrue DO SKIP END) SKIP. Proof. intros contra. unfold cequiv in contra. assert(forall st: state, SKIP / st || st). intros. apply E_Skip. assert(forall st: state, (WHILE BTrue DO SKIP END) / st || st). intros; apply contra; apply H. assert(forall st: state, ~((WHILE BTrue DO SKIP END) / st || st)). intros. apply loop_never_stops. assert((WHILE BTrue DO SKIP END) / empty_state || empty_state -> False). apply H1. apply H2. apply H0. Qed. Module Himp. Inductive com : Type := | CSkip : com | CAss : id -> aexp -> com | CSeq : com -> com -> com | CIf : bexp -> com -> com -> com | CWhile : bexp -> com -> com | CHavoc : id -> com. Tactic Notation "com_cases" tactic(first) ident(c) := first; [ Case_aux c "SKIP" | Case_aux c "::=" | Case_aux c ";;" | Case_aux c "IFB" | Case_aux c "WHILE" | Case_aux c "HAVOC" ]. Notation "'SKIP'" := CSkip. Notation "X '::=' a" := (CAss X a) (at level 60). Notation "c1 ;; c2" := (CSeq c1 c2) (at level 80, right associativity). Notation "'WHILE' b 'DO' c 'END'" := (CWhile b c) (at level 80, right associativity). Notation "'IFB' e1 'THEN' e2 'ELSE' e3 'FI'" := (CIf e1 e2 e3) (at level 80, right associativity). Notation "'HAVOC' l" := (CHavoc l) (at level 60). Reserved Notation "c1 '/' st '||' st'" (at level 40, st at level 39). Inductive ceval : com -> state -> state -> Prop := | E_Skip : forall st : state, SKIP / st || st | E_Ass : forall (st : state) (a1 : aexp) (n : nat) (X : id), aeval st a1 = n -> (X ::= a1) / st || update st X n | E_Seq : forall (c1 c2 : com) (st st' st'' : state), c1 / st || st' -> c2 / st' || st'' -> (c1 ;; c2) / st || st'' | E_IfTrue : forall (st st' : state) (b1 : bexp) (c1 c2 : com), beval st b1 = true -> c1 / st || st' -> (IFB b1 THEN c1 ELSE c2 FI) / st || st' | E_IfFalse : forall (st st' : state) (b1 : bexp) (c1 c2 : com), beval st b1 = false -> c2 / st || st' -> (IFB b1 THEN c1 ELSE c2 FI) / st || st' | E_WhileEnd : forall (b1 : bexp) (st : state) (c1 : com), beval st b1 = false -> (WHILE b1 DO c1 END) / st || st | E_WhileLoop : forall (st st' st'' : state) (b1 : bexp) (c1 : com), beval st b1 = true -> c1 / st || st' -> (WHILE b1 DO c1 END) / st' || st'' -> (WHILE b1 DO c1 END) / st || st'' | E_Havoc : forall (st : state) (n : nat) (X : id), (HAVOC X) / st || update st X n where "c1 '/' st '||' st'" := (ceval c1 st st'). Tactic Notation "ceval_cases" tactic(first) ident(c) := first; [ Case_aux c "E_Skip" | Case_aux c "E_Ass" | Case_aux c "E_Seq" | Case_aux c "E_IfTrue" | Case_aux c "E_IfFalse" | Case_aux c "E_WhileEnd" | Case_aux c "E_WhileLoop" | Case_aux c "E_Havoc" ]. Example havoc_example1 : (HAVOC X) / empty_state || update empty_state X 0. Proof. apply E_Havoc. Qed. Example havoc_example2 : (SKIP;; HAVOC Z) / empty_state || update empty_state Z 42. Proof. apply E_Seq with empty_state. apply E_Skip. apply E_Havoc. Qed. Definition cequiv (c1 c2 : com) : Prop := forall st st' : state, c1 / st || st' <-> c2 / st || st'. Definition pXY := HAVOC X;; HAVOC Y. Definition pYX := HAVOC Y;; HAVOC X. Theorem update_swap: forall st X Y n n0, X<>Y->update (update st X n) Y n0 = update (update st Y n0) X n. Proof. intros. apply functional_extensionality. intros. simpl. unfold update. destruct (eq_id_dec Y x); try auto. destruct (eq_id_dec X x); try auto; try subst. unfold not in H. assert (x=x). auto. apply H in H0. inversion H0. Qed. Theorem pXY_cequiv_pYX : cequiv pXY pYX \/ ~cequiv pXY pYX. Proof. apply or_introl. intros st st'; split; intros H; inversion H; subst; inversion H2; subst; inversion H5; subst; destruct (eq_id_dec X Y) eqn:eqid; inversion eqid; rewrite update_swap; auto. apply E_Seq with (update st Y n0); apply E_Havoc. apply E_Seq with (update st X n0); apply E_Havoc. Qed. Definition ptwice := HAVOC X;; HAVOC Y. Definition pcopy := HAVOC X;; Y ::= AId X. Theorem ptwice_cequiv_pcopy : cequiv ptwice pcopy \/ ~cequiv ptwice pcopy. Proof. apply or_intror. unfold not. intro. unfold cequiv in H. assert(ptwice / empty_state || update (update empty_state X 0) Y (S 0) <-> pcopy / empty_state || update (update empty_state X 0) Y (S 0)). apply H. clear H. destruct (eq_id_dec X Y) eqn:eqid. inversion eqid. inversion H0 as [H1 H2]. clear H0. assert(pcopy / empty_state || update (update empty_state X 0) Y 1). apply H1. apply E_Seq with (update empty_state X 0); apply E_Havoc. clear H1. clear H2. assert((HAVOC X) / empty_state || update empty_state X 0). apply E_Havoc. inversion H; subst. inversion H3; subst. inversion H6; subst. simpl in H7. destruct n0. assert(update (update empty_state X 0) Y (update empty_state X 0 X) Y = update (update empty_state X 0) Y 1 Y). rewrite H7. auto. rewrite update_eq in H1. rewrite update_eq in H1. rewrite update_eq in H1. inversion H1. assert(update (update empty_state X (S n0)) Y (update empty_state X (S n0) X) X = update (update empty_state X 0) Y 1 X). rewrite H7. auto. rewrite update_neq in H1; auto. rewrite update_eq in H1. rewrite update_neq in H1; auto. rewrite update_eq in H1. inversion H1. Qed. Definition p1 : com := WHILE (BNot (BEq (AId X) (ANum 0))) DO HAVOC Y;; X ::= APlus (AId X) (ANum 1) END. Definition p2 : com := WHILE (BNot (BEq (AId X) (ANum 0))) DO SKIP END. Theorem p1_p2_equiv : cequiv p1 p2. Proof. intros st st'; split; intros; unfold p2. unfold p1 in H. destruct (eq_id_dec X Y) eqn:eq; inversion eq; subst. inversion H; subst. apply E_WhileEnd. auto. remember (WHILE BNot (BEq (AId X) (ANum 0)) DO HAVOC Y;; X ::= APlus (AId X) (ANum 1) END) as loopdef eqn:loop. assert (False). clear H3 H6 st'0. induction H; try inversion loop; subst. rewrite H in H2. inversion H2. apply IHceval2; try auto. clear loop IHceval1 IHceval2. inversion H0; subst. inversion H5; subst. inversion H8; subst. simpl. rewrite update_eq. rewrite update_neq; auto. simpl in H2. destruct (st X). inversion H2. simpl. auto. inversion H0. unfold p1; unfold p2 in H. remember (st X) as stx. destruct stx. inversion H; subst. apply E_WhileEnd. auto. simpl in H2. rewrite <- Heqstx in H2. simpl in H2. inversion H2. assert(False). remember (WHILE BNot (BEq (AId X) (ANum 0)) DO SKIP END) as loopdef eqn:loop. induction H; subst; try inversion loop. rewrite H1 in H. simpl in H. rewrite <- Heqstx in H. simpl in H. inversion H. apply IHceval2; try auto. rewrite H4 in H0. inversion H0. subst. auto. inversion H0. Qed. Definition p3 : com := Z ::= ANum 1;; WHILE (BNot (BEq (AId X) (ANum 0))) DO HAVOC X;; HAVOC Z END. Definition p4 : com := X ::= (ANum 0);; Z ::= (ANum 1). Theorem p3_p4_inequiv : ~ cequiv p3 p4. Proof. intro. unfold cequiv in H. assert(p3/update empty_state X 1||update (update (update (update empty_state X 1) Z 1) X 0) Z 0 <-> p4/update empty_state X 1||update (update (update (update empty_state X 1) Z 1) X 0) Z 0). apply H. inversion H0 as [H1 H2]. clear H H0 H2. assert(p3 / update empty_state X 1 || update (update (update (update empty_state X 1) Z 1) X 0) Z 0). apply E_Seq with (update (update empty_state X 1) Z 1). apply E_Ass. auto. apply E_WhileLoop with (update (update (update (update empty_state X 1) Z 1) X 0) Z 0). simpl. auto. apply E_Seq with (update (update (update empty_state X 1) Z 1) X 0); apply E_Havoc. apply E_WhileEnd. simpl. auto. apply H1 in H. inversion H; subst. inversion H3; subst; simpl in H3. simpl in H6. inversion H6; subst; simpl in H7. assert (update (update (update empty_state X 1) X 0) Z 1 Z= update (update (update (update empty_state X 1) Z 1) X 0) Z 0 Z). rewrite H7. auto. rewrite update_eq in H0. rewrite update_eq in H0. inversion H0. Qed. Definition p5 : com := WHILE (BNot (BEq (AId X) (ANum 1))) DO HAVOC X END. Definition p6 : com := X ::= ANum 1. Theorem p5_p6_equiv : cequiv p5 p6. Proof. intros st st'. unfold p5. unfold p6. split. intros. remember (WHILE BNot (BEq (AId X) (ANum 1)) DO HAVOC X END) as loopdef eqn:loop. induction H; inversion loop; subst. inversion H. unfold negb in H1. destruct (beq_nat (st X) 1) eqn:stx. assert(st = update st X 1). apply functional_extensionality. intros. replace 1 with (st X). symmetry. apply update_same. auto. destruct (st X). inversion stx. destruct n. auto. inversion stx. assert((X ::= ANum 1) / st || update st X 1 -> (X ::= ANum 1) / st || st). rewrite <- H0. auto. apply H2. apply E_Ass. auto. inversion H1. assert((X ::= ANum 1) / st' || st''). apply IHceval2. auto. clear IHceval1 IHceval2. inversion H0; subst. inversion H2; subst. simpl. assert(update (update st X n) X 1 = update st X 1). apply functional_extensionality. intros. destruct (eq_id_dec X x) eqn:eqid; subst. apply update_eq. rewrite update_neq; auto. rewrite update_neq; auto. rewrite update_neq; auto. rewrite H3. apply E_Ass. auto. intro. inversion H; subst. simpl in H. remember (st X) as stx. destruct stx. apply E_WhileLoop with (update st X 1). simpl. rewrite <- Heqstx. auto. apply E_Havoc. apply E_WhileEnd. simpl. auto. destruct stx. simpl. replace (update st X 1) with st. apply E_WhileEnd. simpl. rewrite <- Heqstx. auto. apply functional_extensionality. intros. destruct (eq_id_dec X x) eqn:eqid; subst. rewrite update_eq. auto. rewrite update_neq; auto. apply E_WhileLoop with (update st X 1). simpl; rewrite <- Heqstx; auto. apply E_Havoc. apply E_WhileEnd. simpl. auto. Qed. End Himp. Definition stequiv (st1 st2 : state) : Prop := forall (X:id), st1 X = st2 X. Notation "st1 '~' st2" := (stequiv st1 st2) (at level 30). Lemma stequiv_refl : forall (st : state), st ~ st. Proof. intros. intro X. auto. Qed. Lemma stequiv_sym : forall (st1 st2 : state), st1 ~ st2 -> st2 ~ st1. Proof. intros. intro X. symmetry. apply H. Qed. Lemma stequiv_trans : forall (st1 st2 st3 : state), st1 ~ st2 -> st2 ~ st3 -> st1 ~ st3. Proof. intros. intro X. rewrite H. apply H0. Qed. Lemma stequiv_update : forall (st1 st2 : state), st1 ~ st2 -> forall (X:id) (n:nat), update st1 X n ~ update st2 X n. Proof. intros. intros x. destruct (eq_id_dec X x) eqn:eq. subst. rewrite update_eq. rewrite update_eq. auto. rewrite update_neq; auto. rewrite update_neq; auto. Qed. Lemma stequiv_aeval : forall (st1 st2 : state), st1 ~ st2 -> forall (a:aexp), aeval st1 a = aeval st2 a. Proof. intros. induction a; simpl; auto. Qed. Lemma stequiv_beval : forall (st1 st2 : state), st1 ~ st2 -> forall (b:bexp), beval st1 b = beval st2 b. Proof. intros. induction b; simpl; auto; try rewrite stequiv_aeval with (st2:=st2); auto; try rewrite stequiv_aeval with (st1:=st1) (st2:=st2); auto. rewrite IHb; auto. rewrite IHb1. rewrite IHb2. auto. Qed. Lemma stequiv_ceval: forall (st1 st2 : state), st1 ~ st2 -> forall (c: com) (st1': state), (c / st1 || st1') -> exists st2' : state, ((c / st2 || st2') /\ st1' ~ st2'). Proof. intros st1 st2 STEQV c st1' CEV1. generalize dependent st2. induction CEV1; intros st2 STEQV. Case "SKIP". exists st2. split. constructor. assumption. Case ":=". exists (update st2 x n). split. constructor. rewrite <- H. symmetry. apply stequiv_aeval. assumption. apply stequiv_update. assumption. Case ";". destruct (IHCEV1_1 st2 STEQV) as [st2' [P1 EQV1]]. destruct (IHCEV1_2 st2' EQV1) as [st2'' [P2 EQV2]]. exists st2''. split. apply E_Seq with st2'; assumption. assumption. Case "IfTrue". destruct (IHCEV1 st2 STEQV) as [st2' [P EQV]]. exists st2'. split. apply E_IfTrue. rewrite <- H. symmetry. apply stequiv_beval. assumption. assumption. assumption. Case "IfFalse". destruct (IHCEV1 st2 STEQV) as [st2' [P EQV]]. exists st2'. split. apply E_IfFalse. rewrite <- H. symmetry. apply stequiv_beval. assumption. assumption. assumption. Case "WhileEnd". exists st2. split. apply E_WhileEnd. rewrite <- H. symmetry. apply stequiv_beval. assumption. assumption. Case "WhileLoop". destruct (IHCEV1_1 st2 STEQV) as [st2' [P1 EQV1]]. destruct (IHCEV1_2 st2' EQV1) as [st2'' [P2 EQV2]]. exists st2''. split. apply E_WhileLoop with st2'. rewrite <- H. symmetry. apply stequiv_beval. assumption. assumption. assumption. assumption. Qed. Reserved Notation "c1 '/' st '||'' st'" (at level 40, st at level 39). Inductive ceval' : com -> state -> state -> Prop := | E_equiv : forall c st st' st'', c / st || st' -> st' ~ st'' -> c / st ||' st'' where "c1 '/' st '||'' st'" := (ceval' c1 st st'). Definition cequiv' (c1 c2 : com) : Prop := forall (st st' : state), (c1 / st ||' st') <-> (c2 / st ||' st'). Lemma cequiv__cequiv' : forall (c1 c2: com), cequiv c1 c2 -> cequiv' c1 c2. Proof. unfold cequiv, cequiv'; split; intros. inversion H0 ; subst. apply E_equiv with st'0. apply (H st st'0); assumption. assumption. inversion H0 ; subst. apply E_equiv with st'0. apply (H st st'0). assumption. assumption. Qed. Example identity_assignment' : cequiv' SKIP (X ::= AId X). Proof. unfold cequiv'. intros. split; intros. Case "->". inversion H; subst; clear H. inversion H0; subst. apply E_equiv with (update st'0 X (st'0 X)). constructor. reflexivity. apply stequiv_trans with st'0. unfold stequiv. intros. apply update_same. reflexivity. assumption. Case "<-". inversion H; subst; clear H. apply E_equiv with st'0; auto. generalize H0. apply identity_assignment. Qed. Theorem for_while_skip_equiv : forall b c2 c3 st st', ((FOR(FSKIP,b,c2) DO c3 END) /f st || st') <-> ((WHILEF b DO c3 F; c2 END) /f st || st'). Proof. split; intros. remember (FOR (FSKIP, b, c2)DO c3 END) as floop. induction H; try inversion Heqfloop; subst. inversion H; subst. apply F_WhileEnd; auto. inversion H; subst. apply F_WhileLoop with st''; auto. remember (WHILEF b DO c3 F; c2 END) as loopdef eqn:loop. induction H; try inversion loop; subst. apply F_ForEnd; try constructor; auto. apply F_ForLoop with st st'; try apply F_Skip; subst; auto. Qed. Theorem for_while_equiv : forall b c1 c2 c3 st st', ((FOR(c1,b,c2) DO c3 END) /f st || st') <-> ((c1 F; WHILEF b DO c3 F; c2 END) /f st || st'). Proof. split. generalize dependent st'. remember (FOR (c1, b, c2)DO c3 END) as floop. intros. induction H; try inversion Heqfloop. apply F_Seq with st'; subst; auto. apply F_WhileEnd; auto. apply F_Seq with st'; subst; auto. apply F_WhileLoop with st''; auto. apply for_while_skip_equiv. auto. intros. inversion H; subst. remember (WHILEF b DO c3 F; c2 END) as floopdef eqn:loop. induction H5; try inversion loop; subst. apply F_ForEnd; auto. apply F_ForLoop with st0 st'; try auto. apply for_while_skip_equiv. auto. Qed. Theorem swap_noninterfering_assignments: forall l1 l2 a1 a2, l1 <> l2 -> var_not_used_in_aexp l1 a2 -> var_not_used_in_aexp l2 a1 -> cequiv (l1 ::= a1;; l2 ::= a2) (l2 ::= a2;; l1 ::= a1). Proof. intros. assert(Hevaleq : forall st, update (update st l1 (aeval st a1)) l2 (aeval (update st l1 (aeval st a1)) a2) = update (update st l2 (aeval st a2)) l1 (aeval (update st l2 (aeval st a2)) a1)). intros. apply functional_extensionality. intro. destruct (eq_id_dec l1 x) eqn:id1. rewrite update_neq; subst; auto. rewrite update_eq. rewrite update_eq. rewrite aeval_weakening; auto. destruct (eq_id_dec l2 x) eqn:id2; subst. rewrite update_eq. rewrite aeval_weakening; auto. rewrite update_neq; auto. rewrite update_eq. auto. repeat rewrite update_neq; auto. split; intro; inversion H2; subst; inversion H5; subst; inversion H8; subst. rewrite Hevaleq. apply E_Seq with (update st l2 (aeval st a2)); apply E_Ass; auto. rewrite <- Hevaleq. apply E_Seq with (update st l1 (aeval st a1)); apply E_Ass; auto. Qed.
lemma dist_le_zero_iff [simp]: "dist x y \<le> 0 \<longleftrightarrow> x = y"
Formal statement is: lemma convex_differences: assumes "convex S" "convex T" shows "convex (\<Union>x\<in> S. \<Union>y \<in> T. {x - y})" Informal statement is: If $S$ and $T$ are convex sets, then the set of differences $S - T = \{x - y \mid x \in S, y \in T\}$ is convex.
import tactic import group_theory.subgroup.basic namespace my_kernel_norm_sub variables {G H : Type} [group G] [group H] lemma map_mul_2 {x y : G}{φ : G →* H} : φ(x * y * x⁻¹) = φ(x) * φ(y) * φ(x)⁻¹ := begin -- rewrite twice to get an obvious identiy rw map_mul, rw map_mul, end lemma x_in_kernel_is_identity {k : G}{φ : G →* H}(hk : k ∈ φ.ker) : φ(k) = 1 := begin exact hk, end lemma conjugating_k_in_kernel_by_x_is_identity {k : G}{φ : G →* H}(hk : k ∈ φ.ker){x : G} : φ(x * k * x⁻¹) = 1 := begin -- rewrite our hypothesis to expand to multiplication by function rw map_mul_2, -- kernel element goes to the identity rw x_in_kernel_is_identity hk, -- Remove the multiplication by 1 rw mul_one, -- bring back the multiplication by maps to multiplication within a map rw ← map_mul, -- cancel x * x⁻¹ rw mul_right_inv, -- identity maps to identity rw map_one, end variable {φ : G →* H} lemma conjugating_kernel_by_x_is_in_kernel {k : G}(hk : k ∈ φ.ker){x : G} : x * k * x⁻¹ ∈ φ.ker := begin apply conjugating_k_in_kernel_by_x_is_identity, exact hk, end theorem kernel_is_normal_subgroup_of_domain {φ : G →* H} : subgroup.normal (φ.ker) := begin -- Change the goal to be the hypothesis of what a normal group is apply subgroup.normal.mk, apply conjugating_kernel_by_x_is_in_kernel, end theorem preimage_of_normal_subgroup_is_normal {φ : G →* H} {I : subgroup H}(hn : subgroup.normal(I)) : subgroup.normal (I.comap φ) := begin -- Change the goal to be the hypothesis of what a normal group is apply subgroup.normal.mk, -- y an element of G intro y, -- hypothesis that y is in the preimage of φ intro hyInPreim, -- x any element of G intro x, --Simplifies the goal from x * y * x⁻¹ ∈ subgroup.comap φ I -- to φ(x) * φ(y) * φ(x)⁻¹ ∈ I, simp, -- Apply the conjecture that the image I is a normal subgroup apply hn.conj_mem, -- φ(y) is in the image, thus proving the claim exact hyInPreim, end end my_kernel_norm_sub
[GOAL] J K : Type v inst✝⁴ : SmallCategory J inst✝³ : SmallCategory K C : Type u inst✝² : Category.{v, u} C F : J × K ⥤ C inst✝¹ : HasLimitsOfShape J C inst✝ : HasColimitsOfShape K C j : J ⊢ ∀ ⦃X Y : K⦄ (f : X ⟶ Y), (curry.obj (Prod.swap K J ⋙ F) ⋙ lim).map f ≫ (fun k => limit.π ((curry.obj (Prod.swap K J ⋙ F)).obj k) j ≫ colimit.ι ((curry.obj F).obj j) k) Y = (fun k => limit.π ((curry.obj (Prod.swap K J ⋙ F)).obj k) j ≫ colimit.ι ((curry.obj F).obj j) k) X ≫ ((Functor.const K).obj (colimit.cocone ((curry.obj F).obj j)).1).map f [PROOFSTEP] intro k k' f [GOAL] J K : Type v inst✝⁴ : SmallCategory J inst✝³ : SmallCategory K C : Type u inst✝² : Category.{v, u} C F : J × K ⥤ C inst✝¹ : HasLimitsOfShape J C inst✝ : HasColimitsOfShape K C j : J k k' : K f : k ⟶ k' ⊢ (curry.obj (Prod.swap K J ⋙ F) ⋙ lim).map f ≫ (fun k => limit.π ((curry.obj (Prod.swap K J ⋙ F)).obj k) j ≫ colimit.ι ((curry.obj F).obj j) k) k' = (fun k => limit.π ((curry.obj (Prod.swap K J ⋙ F)).obj k) j ≫ colimit.ι ((curry.obj F).obj j) k) k ≫ ((Functor.const K).obj (colimit.cocone ((curry.obj F).obj j)).1).map f [PROOFSTEP] simp only [Functor.comp_obj, lim_obj, colimit.cocone_x, Functor.const_obj_obj, Functor.comp_map, lim_map, curry_obj_obj_obj, Prod.swap_obj, limMap_π_assoc, curry_obj_map_app, Prod.swap_map, Functor.const_obj_map, Category.comp_id] [GOAL] J K : Type v inst✝⁴ : SmallCategory J inst✝³ : SmallCategory K C : Type u inst✝² : Category.{v, u} C F : J × K ⥤ C inst✝¹ : HasLimitsOfShape J C inst✝ : HasColimitsOfShape K C j : J k k' : K f : k ⟶ k' ⊢ limit.π ((curry.obj (Prod.swap K J ⋙ F)).obj k) j ≫ F.map (𝟙 j, f) ≫ colimit.ι ((curry.obj F).obj j) k' = limit.π ((curry.obj (Prod.swap K J ⋙ F)).obj k) j ≫ colimit.ι ((curry.obj F).obj j) k [PROOFSTEP] rw [map_id_left_eq_curry_map, colimit.w] [GOAL] J K : Type v inst✝⁴ : SmallCategory J inst✝³ : SmallCategory K C : Type u inst✝² : Category.{v, u} C F : J × K ⥤ C inst✝¹ : HasLimitsOfShape J C inst✝ : HasColimitsOfShape K C ⊢ ∀ ⦃X Y : J⦄ (f : X ⟶ Y), ((Functor.const J).obj (colimit.cocone (curry.obj (Prod.swap K J ⋙ F) ⋙ lim)).1).map f ≫ (fun j => colimit.desc (curry.obj (Prod.swap K J ⋙ F) ⋙ lim) { pt := (colimit.cocone ((curry.obj F).obj j)).1, ι := NatTrans.mk fun k => limit.π ((curry.obj (Prod.swap K J ⋙ F)).obj k) j ≫ colimit.ι ((curry.obj F).obj j) k }) Y = (fun j => colimit.desc (curry.obj (Prod.swap K J ⋙ F) ⋙ lim) { pt := (colimit.cocone ((curry.obj F).obj j)).1, ι := NatTrans.mk fun k => limit.π ((curry.obj (Prod.swap K J ⋙ F)).obj k) j ≫ colimit.ι ((curry.obj F).obj j) k }) X ≫ (curry.obj F ⋙ colim).map f [PROOFSTEP] intro j j' f [GOAL] J K : Type v inst✝⁴ : SmallCategory J inst✝³ : SmallCategory K C : Type u inst✝² : Category.{v, u} C F : J × K ⥤ C inst✝¹ : HasLimitsOfShape J C inst✝ : HasColimitsOfShape K C j j' : J f : j ⟶ j' ⊢ ((Functor.const J).obj (colimit.cocone (curry.obj (Prod.swap K J ⋙ F) ⋙ lim)).1).map f ≫ (fun j => colimit.desc (curry.obj (Prod.swap K J ⋙ F) ⋙ lim) { pt := (colimit.cocone ((curry.obj F).obj j)).1, ι := NatTrans.mk fun k => limit.π ((curry.obj (Prod.swap K J ⋙ F)).obj k) j ≫ colimit.ι ((curry.obj F).obj j) k }) j' = (fun j => colimit.desc (curry.obj (Prod.swap K J ⋙ F) ⋙ lim) { pt := (colimit.cocone ((curry.obj F).obj j)).1, ι := NatTrans.mk fun k => limit.π ((curry.obj (Prod.swap K J ⋙ F)).obj k) j ≫ colimit.ι ((curry.obj F).obj j) k }) j ≫ (curry.obj F ⋙ colim).map f [PROOFSTEP] dsimp [GOAL] J K : Type v inst✝⁴ : SmallCategory J inst✝³ : SmallCategory K C : Type u inst✝² : Category.{v, u} C F : J × K ⥤ C inst✝¹ : HasLimitsOfShape J C inst✝ : HasColimitsOfShape K C j j' : J f : j ⟶ j' ⊢ 𝟙 (colimit (curry.obj (Prod.swap K J ⋙ F) ⋙ lim)) ≫ colimit.desc (curry.obj (Prod.swap K J ⋙ F) ⋙ lim) { pt := colimit ((curry.obj F).obj j'), ι := NatTrans.mk fun k => limit.π ((curry.obj (Prod.swap K J ⋙ F)).obj k) j' ≫ colimit.ι ((curry.obj F).obj j') k } = colimit.desc (curry.obj (Prod.swap K J ⋙ F) ⋙ lim) { pt := colimit ((curry.obj F).obj j), ι := NatTrans.mk fun k => limit.π ((curry.obj (Prod.swap K J ⋙ F)).obj k) j ≫ colimit.ι ((curry.obj F).obj j) k } ≫ colimMap ((curry.obj F).map f) [PROOFSTEP] ext k [GOAL] case w J K : Type v inst✝⁴ : SmallCategory J inst✝³ : SmallCategory K C : Type u inst✝² : Category.{v, u} C F : J × K ⥤ C inst✝¹ : HasLimitsOfShape J C inst✝ : HasColimitsOfShape K C j j' : J f : j ⟶ j' k : K ⊢ colimit.ι (curry.obj (Prod.swap K J ⋙ F) ⋙ lim) k ≫ 𝟙 (colimit (curry.obj (Prod.swap K J ⋙ F) ⋙ lim)) ≫ colimit.desc (curry.obj (Prod.swap K J ⋙ F) ⋙ lim) { pt := colimit ((curry.obj F).obj j'), ι := NatTrans.mk fun k => limit.π ((curry.obj (Prod.swap K J ⋙ F)).obj k) j' ≫ colimit.ι ((curry.obj F).obj j') k } = colimit.ι (curry.obj (Prod.swap K J ⋙ F) ⋙ lim) k ≫ colimit.desc (curry.obj (Prod.swap K J ⋙ F) ⋙ lim) { pt := colimit ((curry.obj F).obj j), ι := NatTrans.mk fun k => limit.π ((curry.obj (Prod.swap K J ⋙ F)).obj k) j ≫ colimit.ι ((curry.obj F).obj j) k } ≫ colimMap ((curry.obj F).map f) [PROOFSTEP] simp only [Functor.comp_obj, lim_obj, Category.id_comp, colimit.ι_desc, colimit.ι_desc_assoc, Category.assoc, ι_colimMap, curry_obj_obj_obj, curry_obj_map_app] [GOAL] case w J K : Type v inst✝⁴ : SmallCategory J inst✝³ : SmallCategory K C : Type u inst✝² : Category.{v, u} C F : J × K ⥤ C inst✝¹ : HasLimitsOfShape J C inst✝ : HasColimitsOfShape K C j j' : J f : j ⟶ j' k : K ⊢ limit.π ((curry.obj (Prod.swap K J ⋙ F)).obj k) j' ≫ colimit.ι ((curry.obj F).obj j') k = limit.π ((curry.obj (Prod.swap K J ⋙ F)).obj k) j ≫ F.map (f, 𝟙 k) ≫ colimit.ι ((curry.obj F).obj j') k [PROOFSTEP] rw [map_id_right_eq_curry_swap_map, limit.w_assoc] [GOAL] J K : Type v inst✝⁴ : SmallCategory J inst✝³ : SmallCategory K C : Type u inst✝² : Category.{v, u} C F : J × K ⥤ C inst✝¹ : HasLimitsOfShape J C inst✝ : HasColimitsOfShape K C j : J k : K ⊢ colimit.ι (curry.obj (Prod.swap K J ⋙ F) ⋙ lim) k ≫ colimitLimitToLimitColimit F ≫ limit.π (curry.obj F ⋙ colim) j = limit.π ((curry.obj (Prod.swap K J ⋙ F)).obj k) j ≫ colimit.ι ((curry.obj F).obj j) k [PROOFSTEP] dsimp [colimitLimitToLimitColimit] [GOAL] J K : Type v inst✝⁴ : SmallCategory J inst✝³ : SmallCategory K C : Type u inst✝² : Category.{v, u} C F : J × K ⥤ C inst✝¹ : HasLimitsOfShape J C inst✝ : HasColimitsOfShape K C j : J k : K ⊢ colimit.ι (curry.obj (Prod.swap K J ⋙ F) ⋙ lim) k ≫ limit.lift (curry.obj F ⋙ colim) { pt := colimit (curry.obj (Prod.swap K J ⋙ F) ⋙ lim), π := NatTrans.mk fun j => colimit.desc (curry.obj (Prod.swap K J ⋙ F) ⋙ lim) { pt := colimit ((curry.obj F).obj j), ι := NatTrans.mk fun k => limit.π ((curry.obj (Prod.swap K J ⋙ F)).obj k) j ≫ colimit.ι ((curry.obj F).obj j) k } } ≫ limit.π (curry.obj F ⋙ colim) j = limit.π ((curry.obj (Prod.swap K J ⋙ F)).obj k) j ≫ colimit.ι ((curry.obj F).obj j) k [PROOFSTEP] simp [GOAL] J K : Type v inst✝⁴ : SmallCategory J inst✝³ : SmallCategory K C : Type u inst✝² : Category.{v, u} C F✝ : J × K ⥤ C inst✝¹ : HasLimitsOfShape J C inst✝ : HasColimitsOfShape K C F : J × K ⥤ Type v j : J k : K f : (curry.obj (Prod.swap K J ⋙ F) ⋙ lim).obj k ⊢ limit.π (curry.obj F ⋙ colim) j (colimitLimitToLimitColimit F (colimit.ι (curry.obj (Prod.swap K J ⋙ F) ⋙ lim) k f)) = colimit.ι ((curry.obj F).obj j) k (limit.π ((curry.obj (Prod.swap K J ⋙ F)).obj k) j f) [PROOFSTEP] dsimp [colimitLimitToLimitColimit] [GOAL] J K : Type v inst✝⁴ : SmallCategory J inst✝³ : SmallCategory K C : Type u inst✝² : Category.{v, u} C F✝ : J × K ⥤ C inst✝¹ : HasLimitsOfShape J C inst✝ : HasColimitsOfShape K C F : J × K ⥤ Type v j : J k : K f : (curry.obj (Prod.swap K J ⋙ F) ⋙ lim).obj k ⊢ limit.π (curry.obj F ⋙ colim) j (limit.lift (curry.obj F ⋙ colim) { pt := colimit (curry.obj (Prod.swap K J ⋙ F) ⋙ lim), π := NatTrans.mk fun j => colimit.desc (curry.obj (Prod.swap K J ⋙ F) ⋙ lim) { pt := colimit ((curry.obj F).obj j), ι := NatTrans.mk fun k => limit.π ((curry.obj (Prod.swap K J ⋙ F)).obj k) j ≫ colimit.ι ((curry.obj F).obj j) k } } (colimit.ι (curry.obj (Prod.swap K J ⋙ F) ⋙ lim) k f)) = colimit.ι ((curry.obj F).obj j) k (limit.π ((curry.obj (Prod.swap K J ⋙ F)).obj k) j f) [PROOFSTEP] simp [GOAL] J K : Type v inst✝⁵ : SmallCategory J inst✝⁴ : SmallCategory K C : Type u inst✝³ : Category.{v, u} C F : J × K ⥤ C inst✝² : HasLimitsOfShape J C inst✝¹ : HasColimitsOfShape K C G : J ⥤ K ⥤ C inst✝ : HasLimit G j : J ⊢ (colim.map (limitIsoSwapCompLim G).hom ≫ colimitLimitToLimitColimit (uncurry.obj G) ≫ lim.map (whiskerRight (currying.unitIso.app G).inv colim)) ≫ NatTrans.app (limit.cone (G ⋙ colim)).π j = NatTrans.app (colim.mapCone (limit.cone G)).π j [PROOFSTEP] dsimp [GOAL] J K : Type v inst✝⁵ : SmallCategory J inst✝⁴ : SmallCategory K C : Type u inst✝³ : Category.{v, u} C F : J × K ⥤ C inst✝² : HasLimitsOfShape J C inst✝¹ : HasColimitsOfShape K C G : J ⥤ K ⥤ C inst✝ : HasLimit G j : J ⊢ (colimMap (limitIsoSwapCompLim G).hom ≫ colimitLimitToLimitColimit (uncurry.obj G) ≫ limMap (whiskerRight (NatTrans.app currying.unitIso.inv G) colim)) ≫ limit.π (G ⋙ colim) j = colimMap (limit.π G j) [PROOFSTEP] ext1 k [GOAL] case w J K : Type v inst✝⁵ : SmallCategory J inst✝⁴ : SmallCategory K C : Type u inst✝³ : Category.{v, u} C F : J × K ⥤ C inst✝² : HasLimitsOfShape J C inst✝¹ : HasColimitsOfShape K C G : J ⥤ K ⥤ C inst✝ : HasLimit G j : J k : K ⊢ colimit.ι (limit G) k ≫ (colimMap (limitIsoSwapCompLim G).hom ≫ colimitLimitToLimitColimit (uncurry.obj G) ≫ limMap (whiskerRight (NatTrans.app currying.unitIso.inv G) colim)) ≫ limit.π (G ⋙ colim) j = colimit.ι (limit G) k ≫ colimMap (limit.π G j) [PROOFSTEP] simp only [Category.assoc, limMap_π, Functor.comp_obj, colim_obj, whiskerRight_app, colim_map, ι_colimMap_assoc, lim_obj, limitIsoSwapCompLim_hom_app, ι_colimitLimitToLimitColimit_π_assoc, curry_obj_obj_obj, Prod.swap_obj, uncurry_obj_obj, ι_colimMap, currying_unitIso_inv_app_app_app, Category.id_comp, limMap_π_assoc, Functor.flip_obj_obj, flipIsoCurrySwapUncurry_hom_app_app] [GOAL] case w J K : Type v inst✝⁵ : SmallCategory J inst✝⁴ : SmallCategory K C : Type u inst✝³ : Category.{v, u} C F : J × K ⥤ C inst✝² : HasLimitsOfShape J C inst✝¹ : HasColimitsOfShape K C G : J ⥤ K ⥤ C inst✝ : HasLimit G j : J k : K ⊢ (limitObjIsoLimitCompEvaluation G k).hom ≫ limit.π ((Functor.flip G).obj k) j ≫ colimit.ι (G.obj j) k = NatTrans.app (limit.π G j) k ≫ colimit.ι (G.obj j) k [PROOFSTEP] erw [limitObjIsoLimitCompEvaluation_hom_π_assoc]
\documentclass[../main.tex]{subfiles} \begin{document} A \textit{heuristic} search is a method that: \begin{enumerate} \item sacrifices completeness to increase efficiency; that it might not always find the best solution, but can be guaranteed to find a good solution in a reasonable time. \item it is useful in solving tough problems which could not be solved any other way or solutions that take an infinite time or very long time to compute. \item Classical example of heuristic search methods is the travelling salesman problem. \end{enumerate} \section{Hill Climbing} \section{Simulated Annealing} \section{Best-first Search} \section{The $A^{*}$ Algorithm} \section{Graceful dacay of admissibility} \section{Summary and comparison with Complete Search} We will address how to write search algorithms. In particular we will examine: \begin{enumerate} \item the data structure to keep unexplored nodes. We use a queue (often called a list in many AI books) called OPEN. \item expansion of a node (or generation of its successors). All the successors of a node can be generated at once (method most commonly used) or they could be generated one at a time either in a systematic way or in a random way. The number of successors is called the branching factor. \item strategies for selecting which node to expand next. Different algorithms result from different choices (e.g. depth-first when successor nodes are added at the beginning of the queue, breadth-first when successor nodes are added at the end of the queue, etc), test for goal. We will assume the existence of a predicate that applied to a state will return true or false. \item bookkeeping (keeping track of visited nodes, keeping track of path to goal, etc). Keeping track of visited nodes is usually done by keeping them in a queue (or, better a hash-table) called CLOSED. This prevents getting trapped into loops or repeating work but results in a large space complexity. This is (most often) necessary when optimal solutions are sought, but can be (mostly) avoided in other cases. \item Keeping track of the path followed is not always necessary (when the problem is to find a goal state and knowing how to get there is not important). \end{enumerate} properties of search algorithms and the solutions they find: \begin{enumerate} \item Termination: the computation is guaranteed to terminate, no matter how large the search space is. \item Completeness: an algorithm is complete if it terminates with a solution when one exists. \item Admissibility: an algorithm is admissible if it is guaranteed to return an optimal solution whenever a solution exists. \item Space complexity and Time complexity: how the size of the memory and the time needed to run the algorithm grows depending on branching factor, depth of solution, number of nodes, etc. \end{enumerate} Let's briefly examine the properties of some commonly used uninformed search algorithms. Depth-First Search Termination: guaranteed for a finite space if repeated nodes are checked. Guaranteed when a depth bound is used. Not guaranteed otherwise. Completeness: not guaranteed in general. Guaranteed if the search space is finite (exhaustive search) and repeated nodes are checked. Admissibility: not guaranteed. Breadth-First Search Termination: guaranteed for finite space. Guaranteed when a solution exists. Completeness: guaranteed. Admissibility: the algorithm will always find the shortest path (it might not be the optimal path, if arcs have different costs). Depth-First Search Iterative-Deepening Termination: guaranteed for finite space. Guaranteed when a solution exists. Completeness: guaranteed. Admissibility: the algorithm will always find the shortest path (it might not be the optimal path, if arcs have different costs). classes of search algorithms. We can classify search algorithms along multiple dimensions. Here are some of the most common: uninformed (depth-first, breadth-first, uniform cost, depth-limited, iterative deepening) versus informed (greedy, A*, IDA*, SMA*) local (greedy, hill-climbing) versus global (uniform cost, A*, etc) systematic (depth-first, A*, etc) versus stochastic (simulated annealing, genetic algorithms) \end{document}
import M4R.Set.Finite.Finset namespace M4R variable (f : α → β → α) (hrcomm : ∀ (a : α) (b₁ b₂ : β), f (f a b₂) b₁ = f (f a b₁) b₂) variable (op : α → α → α) (hcomm : ∀ a₁ a₂, op a₁ a₂ = op a₂ a₁) (hassoc : ∀ a₁ a₂ a₃, op (op a₁ a₂) a₃ = op a₁ (op a₂ a₃)) local infix:55 " ⋆ " => op theorem hrcomm_of_comm_assoc {op : α → α → α} (hcomm : ∀ a₁ a₂, op a₁ a₂ = op a₂ a₁) (hassoc : ∀ a₁ a₂ a₃, op (op a₁ a₂) a₃ = op a₁ (op a₂ a₃)) : ∀ (a b c : α), op (op a c) b = op (op a b) c := fun a b c => by rw [hassoc, hcomm c, ←hassoc] namespace UnorderedList def fold (init : α) (s : UnorderedList β) : α := Quot.liftOn s (List.foldl f init) fun _ _ p => by induction p generalizing init with | nil => rfl | cons x _ h => exact h (f init x) | swap x y _ => simp only [List.foldl]; rw [hrcomm init x y] | trans _ _ h₁₂ h₂₃ => exact Eq.trans (h₁₂ init) (h₂₃ init) namespace fold @[simp] theorem empty (init : α) : fold f hrcomm init 0 = init := rfl @[simp] theorem singleton (init : α) (b : β) : fold f hrcomm init (UnorderedList.singleton b) = f init b := rfl @[simp] theorem double (init : α) (b c : β) : fold f hrcomm init [b, c] = f (f init b) c := rfl theorem append (init : α) (s t : UnorderedList β) : fold f hrcomm init (s + t) = fold f hrcomm (fold f hrcomm init s) t := @Quotient.inductionOn₂ (List β) (List β) (Perm.PermSetoid β) (Perm.PermSetoid β) (fun (a b : UnorderedList β) => fold f hrcomm init (a + b) = fold f hrcomm (fold f hrcomm init a) b) s t (fun a b => List.foldl_append f _ a b) theorem cons (init : α) (x : β) (s : UnorderedList β) : fold f hrcomm init (s.cons x) = fold f hrcomm (f init x) s := @Quotient.inductionOn (List β) (Perm.PermSetoid β) (fun (ms : UnorderedList β) => fold f hrcomm init (ms.cons x) = fold f hrcomm (f init x) ms) s (fun l => rfl) theorem cons' (init : α) (x : β) (s : UnorderedList β) : fold f hrcomm init (s.cons x) = f (fold f hrcomm init s) x := by rw [cons, ←singleton f hrcomm _ x, ←singleton f hrcomm _ x, ←append, ←append, append.comm] theorem fold_add (a₁ a₂ : α) (s₁ s₂ : UnorderedList α) : (s₁ + s₂).fold op (hrcomm_of_comm_assoc hcomm hassoc) (op a₁ a₂) = (s₁.fold op (hrcomm_of_comm_assoc hcomm hassoc) a₁) ⋆ (s₂.fold op (hrcomm_of_comm_assoc hcomm hassoc) a₂) := @Quotient.inductionOn (List α) (Perm.PermSetoid α) (fun (l : UnorderedList α) => (s₁ + l).fold op (hrcomm_of_comm_assoc hcomm hassoc) (a₁ ⋆ a₂) = (s₁.fold op (hrcomm_of_comm_assoc hcomm hassoc) a₁) ⋆ (l.fold op (hrcomm_of_comm_assoc hcomm hassoc) a₂)) s₂ (fun l => by induction l with | nil => simp; rw [←cons, cons'] | cons x l ih => simp at ih ⊢; rw [append.cons_over_right, cons', ih, cons', hassoc]) end fold def map_fold (op : α → α → α) (hcomm : ∀ a₁ a₂, op a₁ a₂ = op a₂ a₁) (hassoc : ∀ a₁ a₂ a₃, op (op a₁ a₂) a₃ = op a₁ (op a₂ a₃)) (init : α) (f : β → α) (s : UnorderedList β) : α := (s.map f).fold op (hrcomm_of_comm_assoc hcomm hassoc) init namespace map_fold @[simp] theorem empty (init : α) (f : β → α) : map_fold op hcomm hassoc init f 0 = init := rfl theorem congr_map (init : α) {s : UnorderedList β} {f g : β → α} (H : ∀ x ∈ s, f x = g x) : s.map_fold op hcomm hassoc init f = s.map_fold op hcomm hassoc init g := by simp only [map_fold] rw [map.congr rfl H] theorem cons (init : α) (f : β → α) (s : UnorderedList β) (b : β): (s.cons b).map_fold op hcomm hassoc init f = (s.map_fold op hcomm hassoc init f) ⋆ (f b) := by simp [map_fold, fold.cons'] theorem distrib (init : α) (f g : β → α) (s : UnorderedList β) : init ⋆ s.map_fold op hcomm hassoc init (fun b => f b ⋆ g b) = (s.map_fold op hcomm hassoc init f) ⋆ (s.map_fold op hcomm hassoc init g) := @Quotient.inductionOn (List β) (Perm.PermSetoid β) (fun (l : UnorderedList β) => init ⋆ l.map_fold op hcomm hassoc init (fun b => f b ⋆ g b) = (l.map_fold op hcomm hassoc init f) ⋆ (l.map_fold op hcomm hassoc init g)) s (fun l => by induction l with | nil => simp | cons x l ih => simp [cons]; simp only [list_coe_eq] at ih (conv => rhs; rw [hassoc, ←hassoc (f x), hcomm (f x), hassoc _ (f x), ←hassoc]) rw [←ih, hassoc]) theorem append (init : α) (f : β → α) (s t : UnorderedList β) : (s + t).map_fold op hcomm hassoc init f = t.map_fold op hcomm hassoc (s.map_fold op hcomm hassoc init f) f := by have := fold.append op (hrcomm_of_comm_assoc hcomm hassoc) init (s.map f) (t.map f) rw [←map.add] at this; exact this end map_fold end UnorderedList namespace Finset def fold (init : α) (s : Finset β) : α := UnorderedList.fold f hrcomm init s.elems namespace fold @[simp] theorem empty (init : α) : fold f hrcomm init ∅ = init := rfl @[simp] theorem singleton (init : α) (b : β) : (Finset.singleton b).fold f hrcomm init = f init b := rfl @[simp] theorem fold_insert (init : α) {a : β} {s : Finset β} (h : a ∉ s) : (insert a s).fold f hrcomm init = f (s.fold f hrcomm init) a := by simp only [fold]; rw [insert_val, UnorderedList.ndinsert_of_not_mem h, UnorderedList.fold.cons'] end fold def map_fold (op : α → α → α) (hcomm : ∀ a₁ a₂, op a₁ a₂ = op a₂ a₁) (hassoc : ∀ a₁ a₂ a₃, op (op a₁ a₂) a₃ = op a₁ (op a₂ a₃)) (init : α) (f : β → α) (s : Finset β) : α := UnorderedList.map_fold op hcomm hassoc init f s.elems namespace map_fold @[simp] theorem empty (init : α) (f : β → α) : map_fold op hcomm hassoc init f ∅ = init := rfl theorem congr_map (init : α) {s : Finset β} {f g : β → α} (h : ∀ x ∈ s, f x = g x) : s.map_fold op hcomm hassoc init f = s.map_fold op hcomm hassoc init g := UnorderedList.map_fold.congr_map op hcomm hassoc init h theorem union_inter (f : β → α) {s₁ s₂ : Finset β} {a₁ a₂ : α} : (s₁ ∪ s₂).map_fold op hcomm hassoc a₁ f ⋆ (s₁ ∩ s₂).map_fold op hcomm hassoc a₂ f = s₁.map_fold op hcomm hassoc a₂ f ⋆ s₂.map_fold op hcomm hassoc a₁ f := by simp only [map_fold, UnorderedList.map_fold] rw [←UnorderedList.fold.fold_add op hcomm hassoc, ←UnorderedList.map.add, Finset.union_val, Finset.inter_val, UnorderedList.union_add_inter, UnorderedList.map.add, hcomm, UnorderedList.fold.fold_add op hcomm hassoc] @[simp] theorem fold_insert (init : α) (f : β → α) {a : β} {s : Finset β} (h : a ∉ s) : (insert a s).map_fold op hcomm hassoc init f = f a ⋆ s.map_fold op hcomm hassoc init f := by simp only [map_fold, UnorderedList.map_fold] rw [insert_val, UnorderedList.ndinsert_of_not_mem h, UnorderedList.map.cons, UnorderedList.fold.cons', hcomm] end map_fold end Finset end M4R
function mono_total_next_grlex_test ( ) %*****************************************************************************80 % %% MONO_TOTAL_NEXT_GRLEX_TEST tests MONO_TOTAL_NEXT_GRLEX. % % Licensing: % % This code is distributed under the GNU LGPL license. % % Modified: % % 18 November 2013 % % Author: % % John Burkardt % fprintf ( 1, '\n' ); fprintf ( 1, 'MONO_TOTAL_NEXT_GRLEX_TEST\n' ); fprintf ( 1, ' MONO_TOTAL_NEXT_GRLEX can list the monomials\n' ); fprintf ( 1, ' in M variables, of total degree N,\n' ); fprintf ( 1, ' one at a time, in graded lexicographic order.\n' ); fprintf ( 1, '\n' ); fprintf ( 1, ' We start the process with (0,0,...,0,N).\n' ); fprintf ( 1, ' The process ends with (N,0,...,0,0)\n' ); n = 3; m = 3; fprintf ( 1, '\n' ); fprintf ( 1, ' Let M = %d\n', m ); fprintf ( 1, ' N = %d\n', n ); fprintf ( 1, '\n' ); x = [ 0, 0, n ]; i = 1; while ( 1 ) fprintf ( 1, ' %2d:', i ); for j = 1 : m fprintf ( 1, ' %1d', x(j) ); end fprintf ( 1, '\n' ); if ( x(1) == n ) break end x = mono_total_next_grlex ( m, n, x ); i = i + 1; end return end
section \<open>Attractor Strategies\<close> theory AttractorStrategy imports Main Attractor UniformStrategy begin text \<open>This section proves that every attractor set has an attractor strategy.\<close> context ParityGame begin lemma strategy_attracts_extends_VVp: assumes \<sigma>: "strategy p \<sigma>" "strategy_attracts p \<sigma> S W" and v0: "v0 \<in> VV p" "v0 \<in> directly_attracted p S" "v0 \<notin> S" shows "\<exists>\<sigma>. strategy p \<sigma> \<and> strategy_attracts_via p \<sigma> v0 (insert v0 S) W" proof- from v0(1,2) obtain w where "v0\<rightarrow>w" "w \<in> S" using directly_attracted_def by blast from \<open>w \<in> S\<close> \<sigma>(2) have "strategy_attracts_via p \<sigma> w S W" unfolding strategy_attracts_def by blast let ?\<sigma> = "\<sigma>(v0 := w)" \<comment> \<open>Extend @{term \<sigma>} to the new node.\<close> have "strategy p ?\<sigma>" using \<sigma>(1) \<open>v0\<rightarrow>w\<close> valid_strategy_updates by blast moreover have "strategy_attracts_via p ?\<sigma> v0 (insert v0 S) W" proof fix P assume "vmc_path G P v0 p ?\<sigma>" then interpret vmc_path G P v0 p ?\<sigma> . have "\<not>deadend v0" using \<open>v0\<rightarrow>w\<close> by blast then interpret vmc_path_no_deadend G P v0 p ?\<sigma> by unfold_locales define P'' where [simp]: "P'' = ltl P" have "lhd P'' = w" using v0(1) v0_conforms w0_def by auto hence "vmc_path G P'' w p ?\<sigma>" using vmc_path_ltl by (simp add: w0_def) have *: "v0 \<notin> S - W" using \<open>v0 \<notin> S\<close> by blast have "override_on (\<sigma>(v0 := w)) \<sigma> (S - W) = ?\<sigma>" by (rule ext) (metis * fun_upd_def override_on_def) hence "strategy_attracts p ?\<sigma> S W" using strategy_attracts_irrelevant_override[OF \<sigma>(2,1) \<open>strategy p ?\<sigma>\<close>] by simp hence "strategy_attracts_via p ?\<sigma> w S W" unfolding strategy_attracts_def using \<open>w \<in> S\<close> by blast hence "visits_via P'' S W" unfolding strategy_attracts_via_def using \<open>vmc_path G P'' w p ?\<sigma>\<close> by blast thus "visits_via P (insert v0 S) W" using visits_via_LCons[of "ltl P" S W v0] P_LCons by simp qed ultimately show ?thesis by blast qed lemma strategy_attracts_extends_VVpstar: assumes \<sigma>: "strategy_attracts p \<sigma> S W" and v0: "v0 \<notin> VV p" "v0 \<in> directly_attracted p S" shows "strategy_attracts_via p \<sigma> v0 (insert v0 S) W" proof fix P assume "vmc_path G P v0 p \<sigma>" then interpret vmc_path G P v0 p \<sigma> . have "\<not>deadend v0" using v0(2) directly_attracted_contains_no_deadends by blast then interpret vmc_path_no_deadend G P v0 p \<sigma> by unfold_locales have "visits_via (ltl P) S W" using vmc_path.strategy_attractsE[OF vmc_path_ltl \<sigma>] v0 directly_attracted_def by simp thus "visits_via P (insert v0 S) W" using visits_via_LCons[of "ltl P" S W v0] P_LCons by simp qed lemma attractor_has_strategy_single: assumes "W \<subseteq> V" and v0_def: "v0 \<in> attractor p W" (is "_ \<in> ?A") shows "\<exists>\<sigma>. strategy p \<sigma> \<and> strategy_attracts_via p \<sigma> v0 ?A W" using assms proof (induct arbitrary: v0 rule: attractor_set_induction) case (step S) have "v0 \<in> W \<Longrightarrow> \<exists>\<sigma>. strategy p \<sigma> \<and> strategy_attracts_via p \<sigma> v0 {} W" using strategy_attracts_via_trivial valid_arbitrary_strategy by blast moreover { assume *: "v0 \<in> directly_attracted p S" "v0 \<notin> S" from assms(1) step.hyps(1) step.hyps(2) have "\<exists>\<sigma>. strategy p \<sigma> \<and> strategy_attracts p \<sigma> S W" using merge_attractor_strategies by auto with * have "\<exists>\<sigma>. strategy p \<sigma> \<and> strategy_attracts_via p \<sigma> v0 (insert v0 S) W" using strategy_attracts_extends_VVp strategy_attracts_extends_VVpstar by blast } ultimately show ?case using step.prems step.hyps(2) attractor_strategy_on_extends[of p _ v0 "insert v0 S" W "W \<union> S \<union> directly_attracted p S"] attractor_strategy_on_extends[of p _ v0 "S" W "W \<union> S \<union> directly_attracted p S"] attractor_strategy_on_extends[of p _ v0 "{}" W "W \<union> S \<union> directly_attracted p S"] by blast next case (union M) hence "\<exists>S. S \<in> M \<and> v0 \<in> S" by blast thus ?case by (meson Union_upper attractor_strategy_on_extends union.hyps) qed subsection \<open>Existence\<close> text \<open>Prove that every attractor set has an attractor strategy.\<close> theorem attractor_has_strategy: assumes "W \<subseteq> V" shows "\<exists>\<sigma>. strategy p \<sigma> \<and> strategy_attracts p \<sigma> (attractor p W) W" proof- let ?A = "attractor p W" have "?A \<subseteq> V" by (simp add: \<open>W \<subseteq> V\<close> attractor_in_V) moreover have "\<And>v. v \<in> ?A \<Longrightarrow> \<exists>\<sigma>. strategy p \<sigma> \<and> strategy_attracts_via p \<sigma> v ?A W" using \<open>W \<subseteq> V\<close> attractor_has_strategy_single by blast ultimately show ?thesis using merge_attractor_strategies \<open>W \<subseteq> V\<close> by blast qed end \<comment> \<open>context ParityGame\<close> end
The episode was viewed by an estimated and received a 1 @.@ 8 / 5 percent share among adults between the ages of 18 and 49 , ranking third in its first half @-@ hour timeslot and fourth in its second , marking a slight increase in the ratings from the previous episode . " Livin ' the Dream " received mostly positive reviews from television critics . Critical praise mainly went towards the dynamic between Jim , Pam and Dwight , particularly for the former two 's reconciliation and the latter 's promotion . Andy 's subplot , meanwhile , received more mixed reviews .
lemma measurable_Min_nat[measurable (raw)]: fixes P :: "nat \<Rightarrow> 'a \<Rightarrow> bool" assumes [measurable]: "\<And>i. Measurable.pred M (P i)" shows "(\<lambda>x. Min {i. P i x}) \<in> measurable M (count_space UNIV)"
// (C) Copyright 2008 CodeRage, LLC (turkanis at coderage dot com) // (C) Copyright 2003-2007 Jonathan Turkanis // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.) // See http://www.boost.org/libs/iostreams for documentation. #ifndef BOOST_IOSTREAMS_DETAIL_BROKEN_OVERLOAD_RESOLUTION_HPP_INCLUDED #define BOOST_IOSTREAMS_DETAIL_BROKEN_OVERLOAD_RESOLUTION_HPP_INCLUDED #include <boost/config.hpp> // BOOST_STATIC_CONSANT. #include <boost/mpl/bool.hpp> #include <boost/type_traits/is_same.hpp> namespace boost { namespace iostreams { namespace detail { template<typename Device, typename U> struct forward_impl { BOOST_STATIC_CONSTANT(bool, value = ( !is_same< U, Device >::value && !is_same< U, reference_wrapper<Device> >::value )); }; template<typename Device, typename U> struct forward : mpl::bool_<forward_impl<Device, U>::value> { }; } } } // End namespaces detail, iostreams, boost. #endif // #ifndef BOOST_IOSTREAMS_DETAIL_BROKEN_OVERLOAD_RESOLUTION_HPP_INCLUDED
lemma continuous_on_swap[continuous_intros]: "continuous_on A prod.swap"
% \documentclass[11pt, a4paper, leqno]{article} \usepackage{a4wide} \usepackage[T1]{fontenc} \usepackage[utf8]{inputenc} \usepackage{float, afterpage, rotating, graphicx} \usepackage{epstopdf} \usepackage{longtable, booktabs, tabularx} \usepackage{fancyvrb, moreverb, relsize} \usepackage{eurosym, calc, chngcntr} \usepackage{amsmath, amssymb, amsfonts, amsthm, bm} \usepackage{caption} \usepackage{mdwlist} \usepackage{xfrac} \usepackage{setspace} \usepackage{xcolor} % \usepackage{pdf14} % Enable for Manuscriptcentral -- can't handle pdf 1.5 % \usepackage{endfloat} % Enable to move tables / figures to the end. Useful for some submissions. \usepackage[ natbib=true, bibencoding=inputenc, bibstyle=authoryear-ibid, citestyle=authoryear-comp, maxcitenames=3, maxbibnames=10, useprefix=false, sortcites=true, backend=biber ]{biblatex} \AtBeginDocument{\toggletrue{blx@useprefix}} \AtBeginBibliography{\togglefalse{blx@useprefix}} \setlength{\bibitemsep}{1.5ex} % \addbibresource{refs.bib} \usepackage[unicode=true]{hyperref} \hypersetup{ colorlinks=true, linkcolor=black, anchorcolor=black, citecolor=black, filecolor=black, menucolor=black, runcolor=black, urlcolor=black } \widowpenalty=10000 \clubpenalty=10000 \setlength{\parskip}{1ex} \setlength{\parindent}{0ex} \setstretch{1.5} \begin{document} \title{Cryptocurrency Market Prediction \thanks{Tobias Raabe: University of Bonn, Address. \href{mailto:[email protected]} {\nolinkurl{x [at] y [dot] z}}, tel.~+00000.} % subtitle: % \\[1ex] % \large Subtitle here } \author{Tobias Raabe % \\[1ex] % Additional authors here } \date{ {\bf Preliminary -- please do not quote} \\[1ex] \today } \maketitle \begin{abstract} Some citation. \end{abstract} \clearpage \section{Results} % (fold) \label{sec:results} Here are the results of three different moving averages crossover strategies: \begin{figure}[!ht] \centering \includegraphics[width=\textwidth]{../../out/figures/ma_signal_regime_BTC_POT_10_25.png} \label{fig:figure1} \end{figure} \begin{figure}[!ht] \centering \includegraphics[width=\textwidth]{../../out/figures/ma_price_BTC_POT_10_25.png} \label{fig:figure2} \end{figure} \begin{figure}[!ht] \centering \includegraphics[width=\textwidth]{../../out/figures/ma_signal_regime_BTC_POT_20_50.png} \label{fig:figure3} \end{figure} \begin{figure}[!ht] \centering \includegraphics[width=\textwidth]{../../out/figures/ma_price_BTC_POT_20_50.png} \label{fig:figure4} \end{figure} \begin{figure}[!ht] \centering \includegraphics[width=\textwidth]{../../out/figures/ma_signal_regime_BTC_POT_50_100.png} \label{fig:figure5} \end{figure} \begin{figure}[!ht] \centering \includegraphics[width=\textwidth]{../../out/figures/ma_price_BTC_POT_50_100.png} \label{fig:figure6} \end{figure} \setstretch{1} % \printbibliography \setstretch{1.5} %\appendix %\counterwithin{table}{section} %\counterwithin{figure}{section} \end{document}
function result = substr(s, i, j) %SUBSTR Extracts a substring using s(i:j) when last > 0, or else s(i:end+j). if j > 0 result = s(i:j); else result = s(i:end+j); end end
import os #import pgmagick as pg from collections import namedtuple from math import sqrt import numpy as np import Tkinter as tk from PIL import Image, ImageTk import json import random import struct import csv from colormath.color_objects import LabColor,sRGBColor from colormath.color_conversions import convert_color from colormath.color_diff_matrix import delta_e_cie2000 from sklearn.cluster import KMeans, DBSCAN, MeanShift,estimate_bandwidth from sklearn.utils import shuffle from time import time from skimage import io from collections import Counter import scipy.misc def scilearn_cluster(filename,k,son_object,index): image_to_analyze = io.imread(filename) image_to_analyze = image_to_analyze[son_object['bboxes'][index]['x_left']:son_object['bboxes'][index]['x_right'],son_object['bboxes'][index]['y_left']:son_object['bboxes'][index]['y_right']] #china = load_sample_image('china.jpg') image_to_analyze = np.array(image_to_analyze, dtype=np.float64) / 255 w, h, d = original_shape = tuple(image_to_analyze.shape) assert d == 3 image_array = np.reshape(image_to_analyze, (w * h, d)) print("Fitting model on a small sub-sample of the data") t0 = time() image_array_sample = shuffle(image_array, random_state=0)[:1000] kmeans = KMeans(n_clusters=k, random_state=0).fit(image_array_sample) print("done in %0.3fs." % (time() - t0)) # Get labels for all points print("Predicting color indices on the full image (k-means)") t0 = time() labels = kmeans.predict(image_array) print("done in %0.3fs." % (time() - t0)) counter = Counter(labels) colors_array =[] colors_result=[] for label in counter.keys(): colors_array.append((label,counter[label])) sorted_colors_array = sorted(colors_array, key=lambda color_count: color_count[1]) for i in xrange(0,10): colors_result.append(255*kmeans.cluster_centers_[sorted_colors_array.pop()[0]]) return colors_result #return clusters def dbscan_cluster(filename,son_object,index): #image_to_analyze = io.imread(filename) _image = Image.open(filename) bbox_array=[] bbox_array.append(son_object['bboxes'][index]['x_left']) bbox_array.append(son_object['bboxes'][index]['y_left']) bbox_array.append(son_object['bboxes'][index]['x_right']) bbox_array.append(son_object['bboxes'][index]['y_right']) _image=_image.crop(bbox_array) #im = Image.open(filename) #image_to_analyze = image_to_analyze[son_object['bboxes'][index]['x_left']:son_object['bboxes'][index]['x_right'],son_object['bboxes'][index]['y_left']:son_object['bboxes'][index]['y_right']] image_to_analyze=np.array(_image.getdata(), np.uint8).reshape(_image.size[1], _image.size[0], 3) # print np.array(im.getdata(), # np.uint8).reshape(im.size[1], im.size[0], 3) w_orig, h_orig = _image.size square_width=128 if w_orig<square_width and h_orig<square_width: square_width=64 x_init = w_orig/3-square_width/2 y_init = h_orig/3-square_width/2 bbox_array=[] bbox_array.append(x_init) bbox_array.append(y_init) bbox_array.append(x_init+square_width) bbox_array.append(y_init+square_width) _image=_image.crop(bbox_array) image_to_analyze=np.array(_image.getdata(), np.uint8).reshape(_image.size[1], _image.size[0], 3) # image_to_analyze = image_to_analyze[x_init:x_init+square_width,y_init:y_init+square_width] #china = load_sample_image('china.jpg') image_to_analyze = np.array(image_to_analyze, dtype=np.float64) / 255 w, h, d = original_shape = tuple(image_to_analyze.shape) assert d == 3 image_array = np.reshape(image_to_analyze, (w * h, d)) t0 = time() image_array_sample = shuffle(image_array, random_state=0)[:1000] bandwidth = estimate_bandwidth(image_array, quantile=0.2, n_samples=500) ms = MeanShift(bandwidth=bandwidth, bin_seeding=True) ms.fit(image_array) labels = ms.labels_ cluster_centers = ms.cluster_centers_ labels_unique = np.unique(labels) labels_counters = Counter(labels) n_clusters_ = len(labels_unique) return 255*cluster_centers # dbscan = DBSCAN(eps=0.5,min_samples=50).fit(image_array) # print("done in %0.3fs." % (time() - t0)) # core_samples_mask = np.zeros_like(dbscan.labels_, dtype=bool) # core_samples_mask[dbscan.core_sample_indices_] = True # labels = dbscan.labels_ # n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0) # print('Estimated number of clusters: %d' % n_clusters_) # # dbscan.fit_predict(image_array) # n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0) # print('Estimated number of clusters: %d' % n_clusters_) # # Number of clusters in labels, ignoring noise if present. # n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0) # print('Estimated number of clusters: %d' % n_clusters_) colors =["blue","black","gray","white","brown","red","green","multicolor","beige","purple","silver","orange","pink","yellow","gold","khaki","animal","floral","transparent","teal"] def contains_in_colors(array,colorname): result=False for row in array: if row['colorname']==colorname: result=True return result def remove_background(filename,indices_array,json_object): """ Remove the background of the image in 'filename' """ filename = filename index=1 # for idx,row in enumerate(indices_array): # colors = colorz(filename,3,indices_array[index]['indx'],json_object) # rgb_color_vector = [struct.unpack('BBB',colors[0][1:].decode('hex'))[0],struct.unpack('BBB',colors[0][1:].decode('hex'))[1],struct.unpack('BBB',colors[0][1:].decode('hex'))[2]] # print get_color_name(rgb_color_vector),colors[0] # for idx,row in enumerate(indices_array): # rgb_colors=scilearn_cluster(filename,64,j,indices_array[idx]['indx']) # rgb_color_vector = [rgb_colors[0][0],rgb_colors[0][1],rgb_colors[0][2]] recognized_colors=[] for index in xrange(0,len(indices_array)): colors=[] rgb_color_vector=[] rgb_colors=dbscan_cluster(filename,json_object,indices_array[index]['indx']) for color_item in rgb_colors: rgb_color_vector.append([color_item[0],color_item[1],color_item[2]]) for i in xrange(0,len(rgb_colors)): temp = (rgb_colors[i][0],rgb_colors[i][1],rgb_colors[i][2]) colors.append('#'+struct.pack('BBB',*temp).encode('hex')) k=0 rec_color=get_color_name(rgb_color_vector[0])[0] while contains_in_colors(recognized_colors,rec_color)==True and k<len(rgb_color_vector): k=k+1 rec_color = get_color_name(rgb_color_vector[k])[0] color = {'colorname':rec_color,'color_hex':colors[0],'classname':indices_array[index]['classname']} recognized_colors.append(color) # use a Tkinter label as a panel/frame with a background image # note that Tkinter only reads gif and ppm images # use the Python Image Library (PIL) for other image formats # free from [url]http://www.pythonware.com/products/pil/index.htm[/url] # give Tkinter a namespace to avoid conflicts with PIL # (they both have a class named Image) return recognized_colors root = tk.Tk() root.title('background image') # pick an image file you have .bmp .jpg .gif. .png # load the file and covert it to a Tkinter image object imageFile = filename img_uncropped=Image.open(imageFile) bbox_array=[] bbox_array.append(json_object['bboxes'][indices_array[index]['indx']]['x_left']) bbox_array.append(json_object['bboxes'][indices_array[index]['indx']]['y_left']) bbox_array.append(json_object['bboxes'][indices_array[index]['indx']]['x_right']) bbox_array.append(json_object['bboxes'][indices_array[index]['indx']]['y_right']) imageToRender=img_uncropped.crop(bbox_array) render = imageToRender.resize((800,600)) image1 = ImageTk.PhotoImage(render) # get the image size w = 800#image1.width() h = 600#image1.height() # position coordinates of root 'upper left corner' x = 0 y = 0 # make the root window the size of the image root.geometry("%dx%d+%d+%d" % (w, h, x, y)) # root has no image argument, so use a label as a panel panel1 = tk.Label(root, image=image1) panel1.pack(side='top', fill='both', expand='yes') button1 = tk.Button(panel1, text='button2', background=colors[0]) button1.pack(side='bottom') label1 = tk.Label(panel1,text=colors[2]) label1.pack(side='bottom') button2 = tk.Button(panel1, text='button2', background=colors[1]) button2.pack(side='bottom') label2 = tk.Label(panel1,text=colors[1]) label2.pack(side='bottom') button3 = tk.Button(panel1, text='button2', background=colors[2]) button3.pack(side='bottom') label3 = tk.Label(panel1,text=colors[0]) label3.pack(side='bottom') # save the panel's image from 'garbage collection' panel1.image = image1 # start the event loop root.mainloop() def get_color_name(rgb_vector): ##Find color - https://making.lyst.com/2014/02/22/color-detection/ # load list of 1000 random colors from the XKCD color chart # with open('colors.csv', 'rb') as csvfile: # reader = csv.reader(csvfile) # rgb_matrix = np.array([map(float, row[0:3]) for row in reader],dtype=float) # with open('colors.csv', 'rb') as csvfile: # reader = csv.reader(csvfile) # color_labels= np.array([row[3:] for row in reader]) # # the reference color # lab_matrix=np.array([convert_color(sRGBColor(row[0],row[1],row[2],is_upscaled=True),LabColor) for row in rgb_matrix]) # print lab_matrix # with open('lab_colors.csv', 'wb') as csvfile: # writer = csv.writer(csvfile, delimiter=',', # quotechar='|', quoting=csv.QUOTE_MINIMAL) # for idx,row in enumerate(lab_matrix): # writer.writerow([row.lab_l,row.lab_a,row.lab_b,color_labels[idx][0]]) with open(os.path.join(os.path.dirname(os.path.realpath(__file__)),'lab_colors.csv'), 'rb') as csvfile: reader = csv.reader(csvfile) lab_matrix = np.array([map(float, row[0:3]) for row in reader],dtype=float) color_index=0 lab_color=convert_color(sRGBColor(rgb_vector[0],rgb_vector[1],rgb_vector[2],is_upscaled=True),LabColor) # writer.writerow([row.lab_l,row.lab_a,row.lab_b,color_labels[idx][0]]) with open(os.path.join(os.path.dirname(os.path.realpath(__file__)),'lab_colors.csv'), 'rb') as csvfile: reader = csv.reader(csvfile) color_labels= np.array([row[3:] for row in reader]) _color=[] _color.append(lab_color.lab_l) _color.append(lab_color.lab_a) _color.append(lab_color.lab_b) nearest_color= lab_matrix[np.argmin(delta_e_cie2000(_color,lab_matrix))] color_idx = 0 for idx,item in enumerate(lab_matrix): if item[0] == nearest_color[0] and item[1] == nearest_color[1] and item[2] == nearest_color[2] : color_idx=idx # Find the color difference #print '%s OR %s is closest to %s %s' % (rgb_vector,_color, nearest_color,color_labels[color_idx]) return color_labels[color_idx] def detect_colors(jsonfile): path_in_json=jsonfile['file'] useful_indices=[] for idx,classname in enumerate(jsonfile['classes']): if classname != "__background__": useful_indices_item={'indx':idx,'classname':classname} useful_indices.append(useful_indices_item) #image_dir_path="/home/bitummon/Projects/datasets/fashion/fashion2017_800/images" #image_filepath= os.path.join(image_dir_path, path_in_json.rsplit('/').pop()) image_filepath=path_in_json return remove_background(image_filepath,useful_indices,jsonfile) if __name__ == "__main__": path_to_jsonfile="/home/bitummon/tests/colors/00041.json" f=file(path_to_jsonfile,'r') j=json.load(f) f.close() detect_colors(j)
I have been using opinio for elections for five years and have always run against the criticism that the system administrator can potentially access intermediate results and thus in theory misuse these to influence the remainder of the voting. Would it be possible to provide a function to prevent access to reporting (including report plugins) or survey locks (e.g. to temporarily change the end date to get round this!) for all users including admin from the time of activating it until the survey end date? In addition to this, ideally even the root user of the system shouldn't be able to get at the data via direct calls in the mysql backend. Not sure how to solve that one without a major opinio rewrite to encrypt/decrypt the response data tables. Any ideas anyone? should be possible with a plugin, but it would take some time to develop.
! -*- mode: F90; mode: font-lock -*- ! ------------------------------------------------------------------------------ ! $Id$ ! ------------------------------------------------------------------------------ ! Module functions ! ------------------------------------------------------------------------------ ! Code area 9: general ! ------------------------------------------------------------------------------ !!****h* Conquest/functions * !! NAME !! functions !! PURPOSE !! Collects mathematical and other useful functions in one module !! AUTHOR !! D.R.Bowler !! CREATION DATE !! 2016/02/09 !! MODIFICATION HISTORY !! 2019/11/12 08:13 dave !! Adding sort routines !! SOURCE !! module functions implicit none !!*** contains ! ----------------------------------------------------------- ! Function erfc ! ----------------------------------------------------------- !!****f* DiagModle/erfc * !! !! NAME !! erfc !! USAGE !! erfc(x) !! PURPOSE !! Calculated the complementary error function to rounding-error !! based on erfc() in ewald_module !! accuracy !! INPUTS !! real(double) :: x, argument of complementary error function !! AUTHOR !! Iain Chapman/Lianeng Tong !! CREATION DATE !! 2001 sometime/2010/07/26 !! MODIFICATION HISTORY !! 2016/02/09 08:14 dave !! Moved to functions module from DiagModule !! SOURCE !! real(double) function erfc_cq(x) use datatypes use numbers, only: RD_ERR, one, zero, half, two use GenComms, only: cq_abort implicit none real(double), parameter :: erfc_delta = 1.0e-12_double, & erfc_gln = 0.5723649429247447e0_double, & erfc_fpmax = 1.e30_double integer, parameter:: erfc_iterations = 10000 real(double), intent(in) :: x ! local variables real(double) :: y, y2 real(double) :: ap, sum, del real(double) :: an, b, c, d integer :: i if(x < zero) then y = -x else y = x end if ! This expects y^2 y2 = y*y if(y<RD_ERR) then erfc_cq = one return end if if (y2 < 2.25_double) then ap = half sum = two del = sum do i = 1, erfc_iterations ap = ap + 1.0_double del = del * y2 / ap sum = sum + del if (abs(del) < abs(sum) * erfc_delta) exit end do erfc_cq = one - sum * exp(-y2 + half * log(y2) - erfc_gln) else b = y2 + half c = erfc_fpmax d = one / b sum = d do i = 1, erfc_iterations an = - i * (i - half) b = b + two d = an * d + b c = b + an / c d = one / d del = d * c sum = sum * del if (abs(del - one) < erfc_delta) exit end do erfc_cq = sum * exp(-y2 + half * log(y2) - erfc_gln) end if if (x < zero) erfc_cq = two - erfc_cq return end function erfc_cq !!*** !!****f* functions/j0 * !! !! NAME !! j0 !! USAGE !! !! PURPOSE !! Calculates 0th-order Bessel function !! INPUTS !! x !! OUTPUTS !! !! USES !! !! AUTHOR !! N. Watanabe (Mizuho) with TM, DRB !! CREATION DATE !! 2014 !! MODIFICATION HISTORY !! 2015/11/09 17:28 dave !! - Moved into pseudo_tm_module !! 2016/02/09 08:23 dave !! Moved into functions module !! SOURCE !! function j0( x ) use datatypes use numbers, only: very_small, one_sixth, one implicit none real(double) :: x real(double) :: j0 if( x<very_small ) then j0 = one - one_sixth*x*x else j0 = sin(x)/x endif end function j0 !!*** !!****f* functions/j1 * !! !! NAME !! j1 !! USAGE !! !! PURPOSE !! 1st order bessel function with provision for very small numbers !! INPUTS !! !! !! USES !! !! AUTHOR !! NW (Mizuho) with TM and DRB !! CREATION DATE !! Mid 2014 !! MODIFICATION HISTORY !! 2016/02/09 08:24 dave !! Moved to functions module !! SOURCE !! function j1x( x ) use datatypes use numbers implicit none real(double) :: x real(double) :: j1x if( x<very_small ) then j1x = one_third - one/30.0_double*x*x else j1x = (sin(x)-x*cos(x))/(x*x*x) endif end function j1x !!*** !!****f* functions/heapsort_integer_index * !! !! NAME !! heapsort_integer_index !! USAGE !! !! PURPOSE !! Heap sort for an integer array returning sorted index (not in-place) !! Note that this may appear subtly different to standard implementations !! Arrays starting at 1 have different parent/child formulae to arrays !! starting at 0. Contains the sift_down routine. !! INPUTS !! !! !! USES !! !! AUTHOR !! David Bowler !! CREATION DATE !! 2019/11/12 !! MODIFICATION HISTORY !! SOURCE !! subroutine heapsort_integer_index(n_arr,array,arr_index,reverse) ! Passed variables integer :: n_arr integer, OPTIONAL :: reverse integer, dimension(n_arr) :: array integer, dimension(n_arr) :: arr_index, tmp_index ! Local variables integer :: i, temp ! Set up index do i=1,n_arr arr_index(i) = i end do if(n_arr==1) return ! Create heap do i = n_arr/2, 1, -1 call sift_down_integer_index(i, n_arr) end do ! Sort array do i=n_arr, 2, -1 temp = arr_index(1) arr_index(1) = arr_index(i) arr_index(i) = temp call sift_down_integer_index(1, i-1) end do if(present(reverse)) then if(reverse==1) then do i=1,n_arr tmp_index(n_arr-i+1) = arr_index(i) end do arr_index = tmp_index end if end if return contains ! Note that we inherit access to array and arr_index while this is contained ! in the original routine subroutine sift_down_integer_index(start,end) ! Passed variables integer :: start, end ! Local variables integer :: child, root, temp root = start ! Left child is i*2 child = root*2 do while(child<=end) ! Right child is i*2 + 1 if(child+1<=end) then if(array(arr_index(child))<array(arr_index(child+1))) child = child+1 end if if(array(arr_index(root))<array(arr_index(child))) then temp = arr_index(child) arr_index(child) = arr_index(root) arr_index(root) = temp root = child child = root*2 else return end if end do return end subroutine sift_down_integer_index end subroutine heapsort_integer_index !!****f* functions/heapsort_real_index * !! !! NAME !! heapsort_real_index !! USAGE !! !! PURPOSE !! Heap sort for an integer array returning sorted index (not in-place) !! Note that this may appear subtly different to standard implementations !! Arrays starting at 1 have different parent/child formulae to arrays !! starting at 0. Contains the sift_down routine. !! !! Contains optional flag to signal descending rather than ascending order !! INPUTS !! !! !! USES !! !! AUTHOR !! David Bowler !! CREATION DATE !! 2019/11/12 !! MODIFICATION HISTORY !! 2020/01/24 08:05 dave !! Corrected type of temp to integer !! SOURCE !! subroutine heapsort_real_index(n_arr,array,arr_index,reverse) use datatypes implicit none ! Passed variables integer :: n_arr integer, OPTIONAL :: reverse real(double), dimension(n_arr) :: array integer, dimension(n_arr) :: arr_index, tmp_index ! Local variables integer :: i, temp ! Set up index do i=1,n_arr arr_index(i) = i end do if(n_arr==1) return ! Create heap do i = n_arr/2, 1, -1 call sift_down_real_index(i, n_arr) end do ! Sort array do i=n_arr, 2, -1 temp = arr_index(1) arr_index(1) = arr_index(i) arr_index(i) = temp call sift_down_real_index(1, i-1) end do ! Reverse order (descending) if required if(present(reverse)) then if(reverse==1) then do i=1,n_arr tmp_index(n_arr-i+1) = arr_index(i) end do arr_index = tmp_index end if end if return contains ! Note that we inherit access to array and arr_index while this is contained ! in the original routine subroutine sift_down_real_index(start,end) use datatypes implicit none ! Passed variables integer :: start, end ! Local variables integer :: child, root, temp root = start ! Left child is i*2 child = root*2 do while(child<=end) ! Right child is i*2 + 1 if(child+1<=end) then if(array(arr_index(child))<array(arr_index(child+1))) child = child+1 end if if(array(arr_index(root))<array(arr_index(child))) then temp = arr_index(child) arr_index(child) = arr_index(root) arr_index(root) = temp root = child child = root*2 else return end if end do return end subroutine sift_down_real_index end subroutine heapsort_real_index end module functions
module Lexer import Lightyear import Lightyear.Char import Lightyear.Strings public export data Lexeme = INT Integer | TINT | TBOOL | TRUE | FALSE | FUN | IS | IF | THEN | ELSE | LET | SEMICOLON2 | EQUAL | LESS | TARROW | COLON | LPAREN | RPAREN | PLUS | MINUS | TIMES | VAR String -- XXX: deriving Eq? export implementation Eq Lexeme where (INT i1) == (INT i2) = i1 == i2 TINT == TINT = True TBOOL == TBOOL = True TRUE == TRUE = True FALSE == FALSE = True FUN == FUN = True IS == IS = True IF == IF = True THEN == THEN = True ELSE == ELSE = True LET == LET = True SEMICOLON2 == SEMICOLON2 = True EQUAL == EQUAL = True LESS == LESS = True TARROW == TARROW = True COLON == COLON = True LPAREN == LPAREN = True RPAREN == RPAREN = True PLUS == PLUS = True MINUS == MINUS = True TIMES == TIMES = True (VAR nm1) == (VAR nm2) = nm1 == nm2 _ == _ = False -- XXX: deriving Show? export implementation Show Lexeme where show _ = "<lexeme>" getInteger : List (Fin 10) -> Integer getInteger = foldl (\a => \b => 10 * a + cast b) 0 int : Parser Lexeme int = do digits <- some digit pure $ INT (getInteger digits) kw : String -> Lexeme kw "int" = TINT kw "bool" = TBOOL kw "true" = TRUE kw "false" = FALSE kw "fun" = FUN kw "is" = IS kw "if" = IF kw "then" = THEN kw "else" = ELSE kw "let" = LET kw nm = VAR nm varKw : Parser Lexeme varKw = do nm <- some letter pure $ kw (pack nm) tok : Parser Lexeme tok = int <|> varKw <|> (string ";;" *> pure SEMICOLON2) <|> (string "=" *> pure EQUAL) <|> (string "<" *> pure LESS) <|> (string "->" *> pure TARROW) <|> (string ":" *> pure COLON) <|> (string "(" *> pure LPAREN) <|> (string ")" *> pure RPAREN) <|> (string "+" *> pure PLUS) <|> (string "-" *> pure MINUS) <|> (string "×" *> pure TIMES) <|> (string "*" *> pure TIMES) export lexer : Parser (List Lexeme) lexer = spaces *> (many (tok <* spaces))
"""Top level codes for saving and running simulation models.""" import lmfit import numpy as np import os import pandas as pd import matplotlib.pyplot as plt import constants as cn import gene_network as gn import modeling_game as mg import model_fitting as mf import gene_analyzer as ga import util SIM_TIME = 1200 NUM_POINTS = 120 # Files MODEL_PATH = os.path.join(cn.TELLURIUM_DIR, "full_model.txt") PARAM_PATH = os.path.join(cn.TELLURIUM_DIR, "parameters.csv") def evaluate(desc_stgs, **kwargs): """ Analyzes the quality of a gene description (configuration). :param list-str desc_stgs: list of descriptor strings :param dict kwargs: keyword arguments passed to GeneAnalyzer.do :return GeneAnalyzer: """ analyzer = ga.GeneAnalyzer() for desc_stg in desc_stgs: analyzer.do(desc_stg, **kwargs) title = "%s: Rsq = %1.2f" % (desc_stg, analyzer.rsq) plt.figure() analyzer.plot(title=title) return analyzer def saveAnalysisResults(analyzers, parameters_path=PARAM_PATH, model_path=MODEL_PATH): """ Saves the parameters and model from the accumulated files. :param list-GeneAnalyzer analyzers: :param str parameters_path: Write parameters :param str model_path: Write model """ # Accumulate descriptors and parameters desc_stgs = [] dfs_params = [] for analyzer in analyzers: dfs_params.append(analyzer.makeParameterDF()) desc_stgs.append(str(analyzer.descriptor)) # Write the parameters df_param = pd.concat(dfs_params) df_param = df_param.set_index(cn.NAME) try: df_param = df_param.drop(["Vm1"]) except KeyError: pass df_param = df_param.reset_index() df_param = df_param.drop_duplicates() df_param.to_csv(parameters_path) # Save the parameters required param_dict = {cn.NAME: [], cn.VALUE: []} for parameters in analyzers: dfs_params.append(analyzer.makeParameterDF()) # Write the simulation file network = gn.GeneNetwork() network.update(desc_stgs) # Add the new parameters parameters = mg.makeParameters(df_param[cn.NAME], values=df_param[cn.VALUE]) [network.addInitialization(a.parameters) for a in analyzers] network.generate() with open(model_path, "w") as fd: fd.write(network.model) return df_param, network.model def runModel(model_path=MODEL_PATH, parameters_path=PARAM_PATH, mrna_path=cn.MRNA_PATH): """ Evaluates a previously saved simulation model_path. :param str model_path: path to the Tellurium simulation :param str parameters_path: path to the parameter file """ # Initializations model = getModel(model_path=model_path) df_params = pd.read_csv(parameters_path) parameters = mg.makeParameters(df_params[cn.NAME], df_params[cn.VALUE]) # Run simulation df_mrna = pd.read_csv(mrna_path) df_mrna = df_mrna.set_index(cn.TIME) df_mrna = df_mrna.drop(df_mrna.index[-1]) fitted_parameters = mf.fit(df_mrna, model=model, parameters=parameters, sim_time=SIM_TIME, num_points=NUM_POINTS) # Simulate with fitted parameters and plot mg.plotSimulation(df_mrna, model, parameters=fitted_parameters, is_plot_observations=True, is_plot_model=True, is_plot_residuals=True, title=None) def getModel(model_path=MODEL_PATH): """ :return str: model in the model file """ # Initializations with open(MODEL_PATH, "r") as fd: model = fd.readlines() return "".join(model)
function Y = vl_nndwt2( X, dzdy, varargin ) % dwt multi_channel % only support haart and db2 for 1-level transformation opts.padding = 0 ; opts.wavename = 'haart'; opts = vl_argparse(opts, varargin, 'nonrecursive') ; padding = opts.padding; if nargin <= 1 || isempty(dzdy) sz = size(X); X = X/2; if size(X, 3) == 1 sz(3) = 1; end if size(X, 4) == 1 sz(4) = 1; end im_c1 = X(1:2:end, 1:2:end, :, :); im_c2 = X(1:2:end, 2:2:end, :, :); im_c3 = X(2:2:end, 1:2:end, :, :); im_c4 = X(2:2:end, 2:2:end, :, :); Y = zeros([sz(1)/2 sz(2)/2 sz(3)*4 sz(4)], 'like', X); Y(:,:,1:sz(3),:) = im_c1 + im_c2 + im_c3 + im_c4; Y(:,:,sz(3)+1:sz(3)*2,:) = -im_c1 - im_c2 + im_c3 + im_c4; Y(:,:,sz(3)*2+1:sz(3)*3,:) = -im_c1 + im_c2 - im_c3 + im_c4; Y(:,:,sz(3)*3+1:end,:) = im_c1 - im_c2 - im_c3 + im_c4; else sz = size(dzdy); if size(X, 4) == 1 sz(4) = 1; end dzdy = dzdy/2; Y = zeros([sz(1)*2 sz(2)*2 sz(3)/4 sz(4)],'like',dzdy); Y(1:2:end, 1:2:end, : , :) = dzdy(:,:,1:sz(3)/4,:) - dzdy(:,:,sz(3)/4+1:sz(3)/2,:) - ... dzdy(:,:,sz(3)/2+1:3*sz(3)/4,:) + dzdy(:,:,sz(3)/4*3+1:end,:); Y(1:2:end, 2:2:end, : , :) = dzdy(:,:,1:sz(3)/4,:) - dzdy(:,:,sz(3)/4+1:sz(3)/2,:) + ... dzdy(:,:,sz(3)/2+1:3*sz(3)/4,:) - dzdy(:,:,sz(3)/4*3+1:end,:); Y(2:2:end, 1:2:end, : , :) = dzdy(:,:,1:sz(3)/4,:) + dzdy(:,:,sz(3)/4+1:sz(3)/2,:) - ... dzdy(:,:,sz(3)/2+1:3*sz(3)/4,:) - dzdy(:,:,sz(3)/4*3+1:end,:); Y(2:2:end, 2:2:end, : , :) = dzdy(:,:,1:sz(3)/4,:) + dzdy(:,:,sz(3)/4+1:sz(3)/2,:) + ... dzdy(:,:,sz(3)/2+1:3*sz(3)/4,:) + dzdy(:,:,sz(3)/4*3+1:end,:); end
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Scott Morrison ! This file was ported from Lean 3 source module tactic.simp_result ! leanprover-community/mathlib commit 3c11bd771ef17197a9e9fcd4a3fabfa2804d950c ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathbin.Tactic.Core /-! # simp_result `dsimp_result` and `simp_result` are a pair of tactics for applying `dsimp` or `simp` to the result produced by other tactics. As examples, tactics which use `revert` and `intro` may insert additional `id` terms in the result they produce. If there is some reason these are undesirable (e.g. the result term needs to be human-readable, or satisfying syntactic rather than just definitional properties), wrapping those tactics in `dsimp_result` can remove the `id` terms "after the fact". Similarly, tactics using `subst` and `rw` will nearly always introduce `eq.rec` terms, but sometimes these will be easy to remove, for example by simplifying using `eq_rec_constant`. This is a non-definitional simplification lemma, and so wrapping these tactics in `simp_result` will result in a definitionally different result. There are several examples in the associated test file, demonstrating these interactions with `revert` and `subst`. These tactics should be used with some caution. You should consider whether there is any real need for the simplification of the result, and whether there is a more direct way of producing the result you wanted, before relying on these tactics. Both are implemented in terms of a generic `intercept_result` tactic, which allows you to run an arbitrary tactic and modify the returned results. -/ namespace Tactic /-- `intercept_result m t` attempts to run a tactic `t`, intercepts any results `t` assigns to the goals, and runs `m : expr → tactic expr` on each of the expressions before assigning the returned values to the original goals. Because `intercept_result` uses `unsafe.type_context.assign` rather than `unify`, if the tactic `m` does something unreasonable you may produce terms that don't typecheck, possibly with mysterious error messages. Be careful! -/ unsafe def intercept_result {α} (m : expr → tactic expr) (t : tactic α) : tactic α := do let gs ←-- Replace the goals with copies. get_goals let gs' ← gs.mapM fun g => infer_type g >>= mk_meta_var set_goals gs' let a ←-- Run the tactic on the copied goals. t (-- Run `m` on the produced terms, gs gs').mapM fun ⟨g, g'⟩ => do let g' ← instantiate_mvars g' let g'' ← with_local_goals' gs <| m g' -- and assign to the original goals. -- (We have to use `assign` here, as `unify` and `exact` are apparently -- unreliable about which way they do the assignment!) unsafe.type_context.run <| unsafe.type_context.assign g g'' pure a #align tactic.intercept_result tactic.intercept_result /-- `dsimp_result t` attempts to run a tactic `t`, intercepts any results it assigns to the goals, and runs `dsimp` on those results before assigning the simplified values to the original goals. -/ unsafe def dsimp_result {α} (t : tactic α) (cfg : DsimpConfig := { failIfUnchanged := false }) (no_defaults := false) (attr_names : List Name := []) (hs : List simp_arg_type := []) : tactic α := intercept_result (fun g => g.dsimp cfg no_defaults attr_names hs) t #align tactic.dsimp_result tactic.dsimp_result /-- `simp_result t` attempts to run a tactic `t`, intercepts any results `t` assigns to the goals, and runs `simp` on those results before assigning the simplified values to the original goals. -/ unsafe def simp_result {α} (t : tactic α) (cfg : SimpConfig := { failIfUnchanged := false }) (discharger : tactic Unit := failed) (no_defaults := false) (attr_names : List Name := []) (hs : List simp_arg_type := []) : tactic α := intercept_result (fun g => Prod.fst <$> g.simp cfg discharger no_defaults attr_names hs) t #align tactic.simp_result tactic.simp_result namespace Interactive /- ./././Mathport/Syntax/Translate/Tactic/Mathlib/Core.lean:38:34: unsupported: setup_tactic_parser -/ /-- `dsimp_result { tac }` attempts to run a tactic block `tac`, intercepts any results the tactic block would have assigned to the goals, and runs `dsimp` on those results before assigning the simplified values to the original goals. You can use the usual interactive syntax for `dsimp`, e.g. `dsimp_result only [a, b, c] with attr { tac }`. -/ unsafe def dsimp_result (no_defaults : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (t : itactic) : itactic := tactic.dsimp_result t { failIfUnchanged := false } no_defaults attr_names hs #align tactic.interactive.dsimp_result tactic.interactive.dsimp_result /-- `simp_result { tac }` attempts to run a tactic block `tac`, intercepts any results the tactic block would have assigned to the goals, and runs `simp` on those results before assigning the simplified values to the original goals. You can use the usual interactive syntax for `simp`, e.g. `simp_result only [a, b, c] with attr { tac }`. -/ unsafe def simp_result (no_defaults : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (t : itactic) : itactic := tactic.simp_result t { failIfUnchanged := false } failed no_defaults attr_names hs #align tactic.interactive.simp_result tactic.interactive.simp_result /-- `simp_result { tac }` attempts to run a tactic block `tac`, intercepts any results the tactic block would have assigned to the goals, and runs `simp` on those results before assigning the simplified values to the original goals. You can use the usual interactive syntax for `simp`, e.g. `simp_result only [a, b, c] with attr { tac }`. `dsimp_result { tac }` works similarly, internally using `dsimp` (and so only simplifiying along definitional lemmas). -/ add_tactic_doc { Name := "simp_result" category := DocCategory.tactic declNames := [`` simp_result, `` dsimp_result] tags := ["simplification"] } end Interactive end Tactic
lemma lhopital_complex_simple: assumes "(f has_field_derivative f') (at z)" assumes "(g has_field_derivative g') (at z)" assumes "f z = 0" "g z = 0" "g' \<noteq> 0" "f' / g' = c" shows "((\<lambda>w. f w / g w) \<longlongrightarrow> c) (at z)"
function [out] = recharge_7(p1,fin) %recharge_7 % Copyright (C) 2019, 2021 Wouter J.M. Knoben, Luca Trotter % This file is part of the Modular Assessment of Rainfall-Runoff Models % Toolbox (MARRMoT). % MARRMoT is a free software (GNU GPL v3) and distributed WITHOUT ANY % WARRANTY. See <https://www.gnu.org/licenses/> for details. % Flux function % ------------------ % Description: Constant recharge limited by incoming flux % Constraints: - % @(Inputs): p1 - maximum recharge rate [mm/d] % fin - incoming flux [mm/d] out = min(p1,fin); end
The coefficient of $x^n$ in the polynomial $[a, 1]^n$ is $1$.
C C $Id: ERRORF.f,v 1.1 2001-10-09 00:18:35 haley Exp $ C C**************************************************************** C * C Copyright (C) 1994 * C University Corporation for Atmospheric Research * C All Rights Reserved * C * C**************************************************************** C C File: ERROR.f C C Author: Jeff W. Boote C National Center for Atmospheric Research C PO 3000, Boulder, Colorado C C Date: Fri Apr 15 16:52:28 MDT 1994 C C Description: C C**************************************************************** C C Private functions used by Error C C**************************************************************** C C find out if iunit is connected - return 0 if not 1 if is C subroutine nhlpfinqunit(iunit,iconn,ierr) integer iunit,iconn logical opn inquire(iunit,OPENED=opn,IOSTAT=ierr) if(ierr .EQ. 0) then if (opn .EQV. .TRUE.) then iconn = 1 else iconn = 0 endif endif return end C C open the given file with the given unit number C subroutine nhlpfopnunit(iunit,fname,fname_len,ierr) integer iunit,fname_len,ierr character*(*) fname open(iunit,FILE=fname(:fname_len),IOSTAT=ierr,STATUS='UNKNOWN') return end C C close the given unit number C subroutine nhlpfclsunit(iunit,ierr) integer iunit,ierr close(iunit,IOSTAT=ierr) return end C C print a message to the unit number C subroutine nhlpfprnmes(iunit,ermess,ierlen) external i1mach integer iunit,ierlen,ierr character*(*) ermess write(iunit,*,IOSTAT=ierr) ermess(:ierlen) if(ierr .NE. 0) then write(i1mach(4),*,IOSTAT=ierr) % 'Unable to print Error Messages???' endif return end C C**************************************************************** C C Public Functions C C**************************************************************** C subroutine nhlfperror(slevel,ienum,estring) character*(*) slevel,estring integer ienum call nhlpfperror(slevel,len(slevel),ienum,estring,len(estring)) return end C C C subroutine nhlferrgetid(id_ret) integer id_ret call nhlpferrgetid(id_ret) return end C C C subroutine nhlferrnummsgs(nummsg) integer nummsg call nhlpferrnummsgs(nummsg) return end C C C subroutine nhlferrgetmsg(imsg,ilevel,emess,enum,smess,line,file, % ierr) integer imsg,ilevel,enum,line,ierr character*(*) emess,smess,file call nhlpferrgetmsg(imsg,ilevel,emess,len(emess),enum,smess, % len(smess),line,file,len(file),ierr) return end C C C subroutine nhlferrclearmsgs(ierr) call nhlpferrclearmsgs(ierr) return end C C C subroutine nhlferrsprintmsg(smess,imsg) character*(*) smess integer imsg call nhlpferrsprintmsg(smess,len(smess),imsg) return end C C C subroutine nhlferrfprintmsg(iunit,imsg) integer iunit,imsg character*10240 smsg call nhlferrsprintmsg(smsg,imsg) call nhlpfprnmes(iunit,smsg,len(smsg)) return end
% The contact lib by Mathworks, may change to another lib written by % Professor Hartmut Geyer addpath(genpath(fullfile(pwd,'contat_lib'))); %parameters for ground plane geometry and contract ground.stiff = 5e4; ground.damp = 1000; ground.height = 0.4; %robot body size body.x_length = 0.6; body.y_length = 0.3; body.z_length = 0.15; body.shoulder_size = 0.07; body.upper_length = 0.16; body.lower_length = 0.25; body.foot_radius = 0.035; body.shoulder_distance = 0.2; body.max_stretch = body.upper_length + body.lower_length; body.knee_damping = 0.1; % parameters for leg control ctrl.pos_kp = 30; ctrl.pos_ki = 0; ctrl.pos_kd = 0; ctrl.vel_kp = 4.4; ctrl.vel_ki = 0; ctrl.vel_kd = 0.0; % parameters for high level plan planner.touch_down_height = body.foot_radius; % from foot center to ground planner.stand_s = 0; planner.stand_u = 30*pi/180; planner.stand_k = -60*pi/180; stance_pos = forward_kinematics(planner.stand_s, planner.stand_u, planner.stand_k, body); planner.stand_height = stance_pos(3); planner.flight_height = 1.1*planner.stand_height;% when leg is flying in the air % gait control parameters planner.time_circle = 3; planner.swing_ang = 12/180*pi; planner.init_shake_ang = 3/180*pi; %some gait control goals planner.tgt_body_ang = 0; planner.tgt_body_vx = 0.3; % tested 0.15-0.45 planner.Ts = 0.1; % for x_direction leg place planner.Kv = 0.3; % for x_dreiction leg place planner.y_Ts = 0.21; % for y_direction leg place planner.y_Kv = -0.34; % for y_direction leg place % state transition thredsholds planner.state0_vel_thres = 0.05; % the sample time of the ctrl block is set to be 0.0025 (400Hz); planner.state0_trans_thres = 300; %(0.75 seconds) planner.state0_swing_ang = 10*pi/180; planner.state0_swing_T = 1200; planner.state12_trans_speed = 0.2; planner.leg_swing_time = 70; %(use 0.25s to generate a motion) %robot weight body_weight = 600*body.x_length*body.y_length*body.z_length; leg_density = 660; should_weight = leg_density*0.07^3; upperleg_weight = leg_density*0.04*0.04*body.upper_length; lowerleg_weight = leg_density*0.04*0.04*body.lower_length; foot_weight = 1000*4/3*pi*body.foot_radius^3; total_weight = body_weight + 4*(should_weight+upperleg_weight+lowerleg_weight+foot_weight); body_inertia = diag([0.151875;0.516375;0.6075]);
# <center> ЛАБОРАТОРНАЯ РАБОТА 3 </center> # <center> РЕШЕНИЕ СИСТЕМ ЛИНЕЙНЫХ АЛГЕБРАИЧЕСКИХ УРАВНЕНИЙ ПРЯМЫМИ МЕТОДАМИ. ТЕОРИЯ ВОЗМУЩЕНИЙ </center> Теоретический материал к данной теме содержится в [1, глава 5]. ```python from sympy.solvers import solve from sympy import exp, sin, cos, sqrt, log, ln, pi from sympy import Rational as syR from sympy import Symbol, diff from scipy.misc import derivative import numpy as np import matplotlib.pyplot as plt %matplotlib inline ``` ## Задание 1 Дана система уравнений $Ax=b$ порядка n. Исследовать зависимость погрешности решения x от погрешностей правой части системы b. ## Порядок решения задачи: 1. Задать матрицу системы A и вектор правой части b. Составить программу, реализующую метод Гаусса (схема частичного выбора) для произвольной системы $Ax=b$. Используя составленную программу, найти решение заданной системы $Ax=b$. 2. С помощью встроенной функции вычислить число обусловленности матрицы A. 3. Принимая решение x, полученное в п. 1, за точное, вычислить вектор $d=(d_1,...,d_n)^T$, $$d_i=\frac{||x-x^i||_{\infty}}{||x||_{\infty}},\quad i=1, ..., n,$$ относительных погрешностей решений $x^i$ систем $Ax^i=b^i$ , где компоненты векторов $b^i$ вычисляются по формулам: \begin{equation*} b^{i}_{k}= \begin{cases} b_k+\Delta ,&\text{k=i}\\ b_k ,&\text{$k\neq i$} \end{cases} ;k=1,...,n \end{equation*} ( $\Delta$ - произвольная величина погрешности). 4. На основе вычисленного вектора d построить гистограмму. По гистограмме определить компоненту $b_m$ вектора b, которая оказывает наибольшее влияние на погрешность решения. 5. Оценить теоретически погрешность решения $x^m$ по формуле:$$\delta(x^m)<= cond(A)*\delta(b^m)$$ Сравнить значение $\delta(x^m)$ со значением практической погрешности $d_m$. Объяснить полученные результаты. Компоненты вектора b задаются формулой $b_i=N$ , $\forall i=1...n$, коэффициенты $c=c_{ij}=0.1* N *i*j$ ,$\forall i,j=1,...,n$ Ваши компоненты вектора и матрицы: $c(i,j) = {Task1[TASK_VARIANT][f_latex]}$ $a(i,j) = {Task1[TASK_VARIANT][f_latex]}$ $N={[Task1[TASK_VARIANT][N]};$ ```python epsilon1 = 10**(-5) # Компоненты c1 = {Task1[TASK_VARIANT][f_latex]} a1 = {Task1[TASK_VARIANT][f_latex]} N1 = {Task1[TASK_VARIANT][N]} ``` Решите систему с помощью встроенной функции np.linalg.solve ```python ``` Напишите функцию meth_Gauss, которая реализует метод Гаусса ```python def meth_Gauss(matrix, string_b): return return np.array([b[i]/A[i, i] for i in range(n)]) ``` Определите обусловленность матрицы с помощью встроенной функции np.linalg.cond ```python ##Ответ-число обсуловленности ``` Реализуйте функцию для вычисления вектора d ```python ##решение ``` Постройте гистограмму, используя пакет matplotlib. Укажите компоненту вектора b, которая больше всего влияет на погрешность решения ```python ##график ``` Оцените погреность решения по формуле: $$\delta(x^m)<= cond(A)*\delta(b^m)$$ ```python ##массив тру ```
(* ##################################################### ### PLEASE DO NOT DISTRIBUTE SOLUTIONS PUBLICLY ### ##################################################### *) Require Import Coq.Strings.Ascii. Require Import Coq.Lists.List. From Turing Require Import Lang. From Turing Require Import Util. Import LangNotations. Import ListNotations. Import Lang.Examples. Open Scope lang_scope. Open Scope char_scope. (* ---------------------------------------------------------------------------*) (** Show that any word that is in L4 is either empty or starts with "a". *) Theorem ex1: forall w, L4 w -> w = [] \/ exists w', w = "a" :: w'. Proof. simpl. intros N. intros O. induction O. unfold In, App in H. induction x. destruct H. destruct H. destruct H. destruct H0. inversion H0. inversion H1. - simpl. left. rewrite -> H. rewrite <- H3. rewrite <- H4. reflexivity. - simpl. right. destruct H. destruct H. destruct H. destruct H0. inversion H0. inversion H1. exists (w2 ++ w0 ++ w4). rewrite -> H. rewrite -> H5. rewrite -> H4. rewrite -> H10. simpl. reflexivity. Qed. (** Show that the following word is accepted by the given language. *) Theorem ex2: In ["a"; "b"; "b"; "a"] ("a" >> "b" * >> "a"). Proof. simpl. unfold In, Star, App. exists ["a" ; "b" ; "b"], ["a"]. split. - simpl. reflexivity. - simpl. split. + simpl. exists ["a"], ["b" ; "b"]. simpl. split. * simpl. reflexivity. * simpl. split. -- simpl. reflexivity. -- simpl. exists 2. apply pow_cons with (w1 := ["b"]) (w2 := ["b"]). ++ simpl. apply pow_cons with (w1 := ["b"]) (w2 := []). ** simpl. apply pow_nil. ** simpl. reflexivity. ** simpl. reflexivity. ++ simpl. reflexivity. ++ simpl. reflexivity. + simpl. reflexivity. Qed. (** Show that the following word is rejected by the given language. *) Theorem ex3: ~ In ["b"; "b"] ("a" >> "b" * >> "a"). Proof. simpl. unfold not, In, Star, App. intros N. destruct N. destruct H. destruct H. destruct H0. destruct H0. destruct H0. destruct H0. destruct H2. destruct H3. unfold Char in H2, H1. subst. inversion H. Qed. (** Show that the following language is empty. *) Theorem ex4: "0" * >> {} == {}. Proof. simpl. apply app_r_void_rw. Qed. (** Rearrange the following terms. Hint use the distribution and absorption laws. *) Theorem ex5: ("0" U Nil) >> ( "1" * ) == ( "0" >> "1" * ) U ( "1" * ). Proof. simpl. unfold Equiv. intros N. split. - simpl. intros O. rewrite <- app_union_distr_l in O. rewrite app_l_nil_rw in O. apply O. - simpl. intros O. rewrite <- app_union_distr_l. rewrite app_l_nil_rw. apply O. Qed. (** Show that the following langue only accepts two words. *) Theorem ex6: ("0" >> "1" U "1" >> "0") == fun w => (w = ["0"; "1"] \/ w = ["1"; "0"]). Proof. simpl. unfold Equiv. split. - simpl. unfold App, In, Union. intros N. destruct N. destruct H. destruct H. destruct H. destruct H0. unfold Char in H0. unfold Char in H1. + simpl. left. rewrite -> H. rewrite -> H0. rewrite -> H1. simpl. reflexivity. + simpl. destruct H. destruct H. destruct H. destruct H0. unfold Char in H0. unfold Char in H1. right. rewrite -> H. rewrite -> H0. rewrite -> H1. simpl. reflexivity. - simpl. unfold App, In, Union. intros N. destruct N. + left. exists ["0"]. exists ["1"]. split. ** simpl. rewrite -> H. reflexivity. ** simpl. unfold Char. split. --- simpl. reflexivity. --- simpl. reflexivity. + simpl. right. exists ["1"]. exists ["0"]. split. ** simpl. rewrite H. reflexivity. ** simpl. unfold Char. split. --- simpl. reflexivity. --- simpl. reflexivity. Qed. Theorem ex7: "b" >> ("a" U "b" U Nil) * >> Nil == "b" >> ("b" U "a") *. Proof. simpl. split. - simpl. intros N. rewrite app_r_nil_rw in N. (*opens last part*) rewrite union_sym_rw in N. (*symmetric prop*) rewrite star_union_nil_rw in N. rewrite union_sym_rw. apply N. - simpl. intros N. rewrite app_r_nil_rw. rewrite union_sym_rw. rewrite star_union_nil_rw. rewrite union_sym_rw in N. apply N. Qed. Theorem ex8: (("b" >> ("a" U {}) ) U (Nil >> {} >> "c")* ) * == ("b" >> "a") *. Proof. simpl. split. - simpl. intros N. rewrite union_r_void_rw in N. (*open 2nd part*) rewrite app_r_void_rw in N. (*open Nil part*) rewrite app_l_void_rw in N. (*open last part*) rewrite star_void_rw in N. (*open last part*) rewrite union_sym_rw in N. (*symmetric prop*) rewrite star_union_nil_rw in N. apply N. - simpl. intros N. rewrite union_r_void_rw. rewrite app_r_void_rw. rewrite app_l_void_rw. rewrite star_void_rw. rewrite union_sym_rw. rewrite star_union_nil_rw. apply N. Qed.
function do_all(filename, dir; Ny=32, Nz=32, yLength=2, zLength=2, ν=1e-2, timestepper = :RungeKutta3, advection = WENO5(), z_position=0.6, width=0.3, amplitude=-1e-1, Δt=0.002, stop_time=40.0, iteration_interval=1000, schedule_interval=0.5, output_fields = :all) grid = make_grid(Ny, Nz, yLength, zLength) v_bc, w_bc = no_slip_bc(grid) model = make_model(grid, ν) set_buoyancy!(model, z_position=z_position, width=width, amplitude=amplitude) sim = make_simulation(model, dir, filename, Δt=Δt, stop_time=stop_time, iteration_interval=iteration_interval, schedule_interval=schedule_interval, output_fields=output_fields) run!(sim) return nothing end
module Command import Collie import Collie.Options.Domain import Data.List1 import Data.Version orError : (err : String) -> Maybe a -> Either String a orError err = maybe (Left err) Right public export version : Arguments version = MkArguments True (Some Version) (orError "Expected a semantic version argument." . parseVersion) public export idv : Command "idv" idv = MkCommand { description = """ An Idris 2 version manager. Facilitates simultaneous installation of multiple \ Idris 2 versions. """ , subcommands = [ "--help" ::= basic "Print this help text." none , "list" ::= basic "List all installed and available Idris 2 versions." none , "install" ::= installCommand , "uninstall" ::= uninstallCommand , "select" ::= selectCommand ] , modifiers = [] , arguments = none } where installCommand : Command "install" installCommand = MkCommand { name = "install" , description = "<version> Install the given Idris 2 version and optionally also install the Idris 2 API." , subcommands = [] , modifiers = [ "--api" ::= (flag $ """ Install the Idris 2 API package after installing Idris 2. If the specified version of Idris 2 is already installed, \ the API package will be added under the specified installation. """) , "--lsp" ::= (flag $ """ Install the Idris 2 LSP after installing Idris 2. If the specified version of Idris 2 is already installed, \ the LSP server will be added under the specified installation. """) ] , arguments = version } uninstallCommand : Command "uninstall" uninstallCommand = MkCommand { name = "uninstall" , description = "<version> Uninstall the given Idris 2 version." , subcommands = [] , modifiers = [] , arguments = version } selectCommand : Command "select" selectCommand = MkCommand { name = "select" , description = "<version> Select the given (already installed) version of Idris 2." , subcommands = [ "system" ::= basic "Select the system install of Idris 2 (generally ~/.idris2/bin/idris2)." none ] , modifiers = [] , arguments = version } public export (.handleWith) : {nm : String} -> (cmd : Command nm) -> (cmd ~~> IO a) -> IO a cmd .handleWith h = do Right args <- cmd.parseArgs | Left err => do putStrLn err putStrLn "" putStrLn (cmd .usage) putStrLn "" exitFailure let Pure args = finalising args | Fail err => do putStrLn (show err) exitFailure handle args h
module Toolkit.Data.Vect.Extra import public Decidable.Equality import Data.Vect %default total namespace Equality public export vecEq : Eq type => Vect n type -> Vect m type -> Bool vecEq [] [] = True vecEq [] (x :: xs) = False vecEq (x :: xs) [] = False vecEq (x :: xs) (y :: ys) = x == y && vecEq xs ys namespace Decidable namespace SameLength public export decEq : DecEq type => (n = m) -> (xs : Vect n type) -> (ys : Vect m type) -> Dec (xs = ys) decEq Refl xs ys with (decEq xs ys) decEq Refl ys ys | (Yes Refl) = Yes Refl decEq Refl xs ys | (No contra) = No contra namespace DiffLength public export vectorsDiffLength : DecEq type => (contra : (n = m) -> Void) -> {xs : Vect n type} -> {ys : Vect m type} -> (xs = ys) -> Void vectorsDiffLength contra Refl = contra Refl public export decEq : DecEq type => {n,m : Nat} -> (xs : Vect n type) -> (ys : Vect m type) -> Dec (xs = ys) decEq xs ys {n} {m} with (decEq n m) decEq xs ys {n = m} {m = m} | (Yes Refl) = decEq Refl xs ys decEq xs ys {n = n} {m = m} | (No contra) = No (vectorsDiffLength contra) namespace Shape public export data Shape : (xs : Vect n a) -> (ys : Vect m a) -> Type where Empty : Shape Nil Nil LH : Shape (x::xs) Nil RH : Shape Nil (y::ys) Both : Shape (x::xs) (y::ys) export shape : (xs : Vect n a) -> (ys : Vect m a) -> Shape xs ys shape [] [] = Empty shape [] (y :: ys) = RH shape (x :: xs) [] = LH shape (x :: xs) (y :: ys) = Both namespace ReplaceAt public export data ReplaceAt : (idx : Fin n) -> (xs : Vect n a) -> (this,that : a) -> (ys : Vect n a) -> Type where H : ReplaceAt FZ (x::xs) x y (y::xs) T : ReplaceAt idx xs x y ys -> ReplaceAt (FS idx) (x'::xs) x y (x'::ys) notSame : (x = this -> Void) -> DPair (Vect (S len) a) (ReplaceAt FZ (x :: xs) this that) -> Void notSame _ (MkDPair _ (T y)) impossible notLater : (DPair (Vect len a) (ReplaceAt x xs this that) -> Void) -> DPair (Vect (S len) a) (ReplaceAt (FS x) (y :: xs) this that) -> Void notLater f (MkDPair (y :: ys) (T z)) = f (MkDPair ys z) export replaceAt : DecEq a => (idx : Fin n) -> (xs : Vect n a) -> (this, that : a) -> Dec (DPair (Vect n a) (ReplaceAt idx xs this that)) replaceAt FZ (x :: xs) this that with (decEq x this) replaceAt FZ (x :: xs) x that | (Yes Refl) = Yes (MkDPair (that :: xs) H) replaceAt FZ (x :: xs) this that | (No contra) = No (notSame contra) replaceAt (FS x) (y :: xs) this that with (replaceAt x xs this that) replaceAt (FS x) (y :: xs) this that | (Yes (MkDPair fst snd)) = Yes (MkDPair (y :: fst) (T snd)) replaceAt (FS x) (y :: xs) this that | (No contra) = No (notLater contra) namespace Quantifier namespace AtIndex public export data AtIndex : (type : Type) -> (p : (a : type) -> Type) -> (idx : Fin n) -> (xs : Vect n type) -> Type where Here : (prf : p x) -> AtIndex type p FZ (x::xs) There : (later : AtIndex type p next xs) -> AtIndex type p (FS next) (not_x :: xs) export Uninhabited (AtIndex type p idx Nil) where uninhabited (Here prf) impossible uninhabited (There later) impossible notLater : (AtIndex type p y xs -> Void) -> AtIndex type p (FS y) (x :: xs) -> Void notLater f (There later) = f later notHere : (p x -> Void) -> AtIndex type p FZ (x :: xs) -> Void notHere f (Here prf) = f prf export atIndex : {type : Type} -> {p : type -> Type} -> (dec : (this : type) -> Dec (p this)) -> (idx : Fin n) -> (xs : Vect n type) -> Dec (AtIndex type p idx xs) atIndex dec idx [] = No absurd atIndex dec FZ (x :: xs) with (dec x) atIndex dec FZ (x :: xs) | (Yes prf) = Yes (Here prf) atIndex dec FZ (x :: xs) | (No contra) = No (notHere contra) atIndex dec (FS y) (x :: xs) with (atIndex dec y xs) atIndex dec (FS y) (x :: xs) | (Yes prf) = Yes (There prf) atIndex dec (FS y) (x :: xs) | (No contra) = No (notLater contra) namespace Diff public export data AtIndexI : (type : Type) -> (p : (a : type) -> Type) -> (m,n : Nat) -> (idx : Fin m) -> (xs : Vect n type) -> Type where At : AtIndex type p idx xs -> AtIndexI type p n n idx xs Uninhabited (AtIndexI type p m Z idx Nil) where uninhabited (At (Here prf)) impossible uninhabited (At (There later)) impossible notAtIndex : (AtIndex type p idx xs -> Void) -> AtIndexI type p m m idx xs -> Void notAtIndex f (At x) = f x indexDiffers : (m = n -> Void) -> AtIndexI type p m n idx xs -> Void indexDiffers f (At x) = f Refl export atIndexI : {type : Type} -> {p : type -> Type} -> {m,n : Nat} -> (dec : (this : type) -> Dec (p this)) -> (idx : Fin m) -> (xs : Vect n type) -> Dec (AtIndexI type p m n idx xs) atIndexI {m} {n} dec idx xs with (decEq m n) atIndexI {m = m} {n = m} dec idx xs | (Yes Refl) with (atIndex dec idx xs) atIndexI {m = m} {n = m} dec idx xs | (Yes Refl) | (Yes prf) = Yes (At prf) atIndexI {m = m} {n = m} dec idx xs | (Yes Refl) | (No contra) = No (notAtIndex contra) atIndexI {m = m} {n = n} dec idx xs | (No contra) = No (indexDiffers contra) -- [ EOF ]
### ### Copyright (C) 2017 Rafael Laboissière ### ### This program is free software: you can redistribute it and/or modify it ### under the terms of the GNU General Public License as published by the ### Free Software Foundation, either version 3 of the License, or (at your ### option) any later version. ### ### This program is distributed in the hope that it will be useful, but ### WITHOUT ANY WARRANTY; without even the implied warranty of ### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ### General Public License for more details. ### ### You should have received a copy of the GNU General Public License along ### with this program. If not, see <http://www.gnu.org/licenses/>. ### * Boxplot the results ### ** All conditions, collapsed objects ### *** Threshold pdf (file = "obj-stab-threshold-all.pdf") par (mar = c (11, 4, 1, 1)) boxplot (threshold ~ chair * stimulus * background, data = obj.stab.psycho, las = 2, ylab = "threshold (degree)") dev.off () ### *** Slope pdf (file = "obj-stab-slope-all.pdf") par (mar = c (11, 4, 1, 1)) ### **** Inclination at threshold is 25*a boxplot (abs (25 * slope) ~ chair * stimulus * background, log = "y", data = obj.stab.psycho, las = 2, ylab = "slope (%/degree)") dev.off () ### ** Object condition df <- droplevels (subset (obj.stab.psycho, stimulus == "object")) ### *** Threshold pdf (file = "obj-stab-threshold-object.pdf") par (mar = c (11, 4, 1, 1)) boxplot (threshold ~ object * chair * background, data = df, las = 2, ylab = "threshold (degree)") dev.off () ### *** Slope pdf (file = "obj-stab-slope-object.pdf") par (mar = c (11, 4, 1, 1)) ### **** Inclination at threshold is 25*a boxplot (abs (25 * slope) ~ object * chair * background, log = "y", data = df, las = 2, ylab = "slope (%/degree)") dev.off ()
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import order.filter.lift import topology.subset_properties /-! # Uniform spaces Uniform spaces are a generalization of metric spaces and topological groups. Many concepts directly generalize to uniform spaces, e.g. * uniform continuity (in this file) * completeness (in `cauchy.lean`) * extension of uniform continuous functions to complete spaces (in `uniform_embedding.lean`) * totally bounded sets (in `cauchy.lean`) * totally bounded complete sets are compact (in `cauchy.lean`) A uniform structure on a type `X` is a filter `𝓤 X` on `X × X` satisfying some conditions which makes it reasonable to say that `∀ᶠ (p : X × X) in 𝓤 X, ...` means "for all p.1 and p.2 in X close enough, ...". Elements of this filter are called entourages of `X`. The two main examples are: * If `X` is a metric space, `V ∈ 𝓤 X ↔ ∃ ε > 0, { p | dist p.1 p.2 < ε } ⊆ V` * If `G` is an additive topological group, `V ∈ 𝓤 G ↔ ∃ U ∈ 𝓝 (0 : G), {p | p.2 - p.1 ∈ U} ⊆ V` Those examples are generalizations in two different directions of the elementary example where `X = ℝ` and `V ∈ 𝓤 ℝ ↔ ∃ ε > 0, { p | |p.2 - p.1| < ε } ⊆ V` which features both the topological group structure on `ℝ` and its metric space structure. Each uniform structure on `X` induces a topology on `X` characterized by > `nhds_eq_comap_uniformity : ∀ {x : X}, 𝓝 x = comap (prod.mk x) (𝓤 X)` where `prod.mk x : X → X × X := (λ y, (x, y))` is the partial evaluation of the product constructor. The dictionary with metric spaces includes: * an upper bound for `dist x y` translates into `(x, y) ∈ V` for some `V ∈ 𝓤 X` * a ball `ball x r` roughly corresponds to `uniform_space.ball x V := {y | (x, y) ∈ V}` for some `V ∈ 𝓤 X`, but the later is more general (it includes in particular both open and closed balls for suitable `V`). In particular we have: `is_open_iff_ball_subset {s : set X} : is_open s ↔ ∀ x ∈ s, ∃ V ∈ 𝓤 X, ball x V ⊆ s` The triangle inequality is abstracted to a statement involving the composition of relations in `X`. First note that the triangle inequality in a metric space is equivalent to `∀ (x y z : X) (r r' : ℝ), dist x y ≤ r → dist y z ≤ r' → dist x z ≤ r + r'`. Then, for any `V` and `W` with type `set (X × X)`, the composition `V ○ W : set (X × X)` is defined as `{ p : X × X | ∃ z, (p.1, z) ∈ V ∧ (z, p.2) ∈ W }`. In the metric space case, if `V = { p | dist p.1 p.2 ≤ r }` and `W = { p | dist p.1 p.2 ≤ r' }` then the triangle inequality, as reformulated above, says `V ○ W` is contained in `{p | dist p.1 p.2 ≤ r + r'}` which is the entourage associated to the radius `r + r'`. In general we have `mem_ball_comp (h : y ∈ ball x V) (h' : z ∈ ball y W) : z ∈ ball x (V ○ W)`. Note that this discussion does not depend on any axiom imposed on the uniformity filter, it is simply captured by the definition of composition. The uniform space axioms ask the filter `𝓤 X` to satisfy the following: * every `V ∈ 𝓤 X` contains the diagonal `id_rel = { p | p.1 = p.2 }`. This abstracts the fact that `dist x x ≤ r` for every non-negative radius `r` in the metric space case and also that `x - x` belongs to every neighborhood of zero in the topological group case. * `V ∈ 𝓤 X → prod.swap '' V ∈ 𝓤 X`. This is tightly related the fact that `dist x y = dist y x` in a metric space, and to continuity of negation in the topological group case. * `∀ V ∈ 𝓤 X, ∃ W ∈ 𝓤 X, W ○ W ⊆ V`. In the metric space case, it corresponds to cutting the radius of a ball in half and applying the triangle inequality. In the topological group case, it comes from continuity of addition at `(0, 0)`. These three axioms are stated more abstractly in the definition below, in terms of operations on filters, without directly manipulating entourages. ## Main definitions * `uniform_space X` is a uniform space structure on a type `X` * `uniform_continuous f` is a predicate saying a function `f : α → β` between uniform spaces is uniformly continuous : `∀ r ∈ 𝓤 β, ∀ᶠ (x : α × α) in 𝓤 α, (f x.1, f x.2) ∈ r` In this file we also define a complete lattice structure on the type `uniform_space X` of uniform structures on `X`, as well as the pullback (`uniform_space.comap`) of uniform structures coming from the pullback of filters. Like distance functions, uniform structures cannot be pushed forward in general. ## Notations Localized in `uniformity`, we have the notation `𝓤 X` for the uniformity on a uniform space `X`, and `○` for composition of relations, seen as terms with type `set (X × X)`. ## Implementation notes There is already a theory of relations in `data/rel.lean` where the main definition is `def rel (α β : Type*) := α → β → Prop`. The relations used in the current file involve only one type, but this is not the reason why we don't reuse `data/rel.lean`. We use `set (α × α)` instead of `rel α α` because we really need sets to use the filter library, and elements of filters on `α × α` have type `set (α × α)`. The structure `uniform_space X` bundles a uniform structure on `X`, a topology on `X` and an assumption saying those are compatible. This may not seem mathematically reasonable at first, but is in fact an instance of the forgetful inheritance pattern. See Note [forgetful inheritance] below. ## References The formalization uses the books: * [N. Bourbaki, *General Topology*][bourbaki1966] * [I. M. James, *Topologies and Uniformities*][james1999] But it makes a more systematic use of the filter library. -/ open set filter classical open_locale classical topological_space filter set_option eqn_compiler.zeta true universes u /-! ### Relations, seen as `set (α × α)` -/ variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*} /-- The identity relation, or the graph of the identity function -/ def id_rel {α : Type*} := {p : α × α | p.1 = p.2} @[simp] theorem mem_id_rel {a b : α} : (a, b) ∈ @id_rel α ↔ a = b := iff.rfl @[simp] theorem id_rel_subset {s : set (α × α)} : id_rel ⊆ s ↔ ∀ a, (a, a) ∈ s := by simp [subset_def]; exact forall_congr (λ a, by simp) /-- The composition of relations -/ def comp_rel {α : Type u} (r₁ r₂ : set (α×α)) := {p : α × α | ∃z:α, (p.1, z) ∈ r₁ ∧ (z, p.2) ∈ r₂} localized "infix ` ○ `:55 := comp_rel" in uniformity @[simp] theorem mem_comp_rel {r₁ r₂ : set (α×α)} {x y : α} : (x, y) ∈ r₁ ○ r₂ ↔ ∃ z, (x, z) ∈ r₁ ∧ (z, y) ∈ r₂ := iff.rfl @[simp] theorem swap_id_rel : prod.swap '' id_rel = @id_rel α := set.ext $ assume ⟨a, b⟩, by simp [image_swap_eq_preimage_swap]; exact eq_comm theorem monotone_comp_rel [preorder β] {f g : β → set (α×α)} (hf : monotone f) (hg : monotone g) : monotone (λx, (f x) ○ (g x)) := assume a b h p ⟨z, h₁, h₂⟩, ⟨z, hf h h₁, hg h h₂⟩ @[mono] lemma comp_rel_mono {f g h k: set (α×α)} (h₁ : f ⊆ h) (h₂ : g ⊆ k) : f ○ g ⊆ h ○ k := λ ⟨x, y⟩ ⟨z, h, h'⟩, ⟨z, h₁ h, h₂ h'⟩ lemma prod_mk_mem_comp_rel {a b c : α} {s t : set (α×α)} (h₁ : (a, c) ∈ s) (h₂ : (c, b) ∈ t) : (a, b) ∈ s ○ t := ⟨c, h₁, h₂⟩ @[simp] lemma id_comp_rel {r : set (α×α)} : id_rel ○ r = r := set.ext $ assume ⟨a, b⟩, by simp lemma comp_rel_assoc {r s t : set (α×α)} : (r ○ s) ○ t = r ○ (s ○ t) := by ext p; cases p; simp only [mem_comp_rel]; tauto lemma subset_comp_self {α : Type*} {s : set (α × α)} (h : id_rel ⊆ s) : s ⊆ s ○ s := λ ⟨x, y⟩ xy_in, ⟨x, h (by rw mem_id_rel), xy_in⟩ /-- The relation is invariant under swapping factors. -/ def symmetric_rel (V : set (α × α)) : Prop := prod.swap ⁻¹' V = V /-- The maximal symmetric relation contained in a given relation. -/ def symmetrize_rel (V : set (α × α)) : set (α × α) := V ∩ prod.swap ⁻¹' V lemma symmetric_symmetrize_rel (V : set (α × α)) : symmetric_rel (symmetrize_rel V) := by simp [symmetric_rel, symmetrize_rel, preimage_inter, inter_comm, ← preimage_comp] lemma symmetrize_rel_subset_self (V : set (α × α)) : symmetrize_rel V ⊆ V := sep_subset _ _ @[mono] lemma symmetrize_mono {V W: set (α × α)} (h : V ⊆ W) : symmetrize_rel V ⊆ symmetrize_rel W := inter_subset_inter h $ preimage_mono h lemma symmetric_rel_inter {U V : set (α × α)} (hU : symmetric_rel U) (hV : symmetric_rel V) : symmetric_rel (U ∩ V) := begin unfold symmetric_rel at *, rw [preimage_inter, hU, hV], end /-- This core description of a uniform space is outside of the type class hierarchy. It is useful for constructions of uniform spaces, when the topology is derived from the uniform space. -/ structure uniform_space.core (α : Type u) := (uniformity : filter (α × α)) (refl : 𝓟 id_rel ≤ uniformity) (symm : tendsto prod.swap uniformity uniformity) (comp : uniformity.lift' (λs, s ○ s) ≤ uniformity) /-- An alternative constructor for `uniform_space.core`. This version unfolds various `filter`-related definitions. -/ def uniform_space.core.mk' {α : Type u} (U : filter (α × α)) (refl : ∀ (r ∈ U) x, (x, x) ∈ r) (symm : ∀ r ∈ U, prod.swap ⁻¹' r ∈ U) (comp : ∀ r ∈ U, ∃ t ∈ U, t ○ t ⊆ r) : uniform_space.core α := ⟨U, λ r ru, id_rel_subset.2 (refl _ ru), symm, begin intros r ru, rw [mem_lift'_sets], exact comp _ ru, apply monotone_comp_rel; exact monotone_id, end⟩ /-- A uniform space generates a topological space -/ def uniform_space.core.to_topological_space {α : Type u} (u : uniform_space.core α) : topological_space α := { is_open := λs, ∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ u.uniformity, is_open_univ := by simp; intro; exact univ_mem, is_open_inter := assume s t hs ht x ⟨xs, xt⟩, by filter_upwards [hs x xs, ht x xt]; simp {contextual := tt}, is_open_sUnion := assume s hs x ⟨t, ts, xt⟩, by filter_upwards [hs t ts x xt] assume p ph h, ⟨t, ts, ph h⟩ } lemma uniform_space.core_eq : ∀{u₁ u₂ : uniform_space.core α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | ⟨u₁, _, _, _⟩ ⟨u₂, _, _, _⟩ h := by { congr, exact h } -- the topological structure is embedded in the uniform structure -- to avoid instance diamond issues. See Note [forgetful inheritance]. /-- A uniform space is a generalization of the "uniform" topological aspects of a metric space. It consists of a filter on `α × α` called the "uniformity", which satisfies properties analogous to the reflexivity, symmetry, and triangle properties of a metric. A metric space has a natural uniformity, and a uniform space has a natural topology. A topological group also has a natural uniformity, even when it is not metrizable. -/ class uniform_space (α : Type u) extends topological_space α, uniform_space.core α := (is_open_uniformity : ∀s, is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ uniformity)) /-- Alternative constructor for `uniform_space α` when a topology is already given. -/ @[pattern] def uniform_space.mk' {α} (t : topological_space α) (c : uniform_space.core α) (is_open_uniformity : ∀s:set α, t.is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ c.uniformity)) : uniform_space α := ⟨c, is_open_uniformity⟩ /-- Construct a `uniform_space` from a `uniform_space.core`. -/ def uniform_space.of_core {α : Type u} (u : uniform_space.core α) : uniform_space α := { to_core := u, to_topological_space := u.to_topological_space, is_open_uniformity := assume a, iff.rfl } /-- Construct a `uniform_space` from a `u : uniform_space.core` and a `topological_space` structure that is equal to `u.to_topological_space`. -/ def uniform_space.of_core_eq {α : Type u} (u : uniform_space.core α) (t : topological_space α) (h : t = u.to_topological_space) : uniform_space α := { to_core := u, to_topological_space := t, is_open_uniformity := assume a, h.symm ▸ iff.rfl } lemma uniform_space.to_core_to_topological_space (u : uniform_space α) : u.to_core.to_topological_space = u.to_topological_space := topological_space_eq $ funext $ assume s, by rw [uniform_space.core.to_topological_space, uniform_space.is_open_uniformity] @[ext] lemma uniform_space_eq : ∀{u₁ u₂ : uniform_space α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | (uniform_space.mk' t₁ u₁ o₁) (uniform_space.mk' t₂ u₂ o₂) h := have u₁ = u₂, from uniform_space.core_eq h, have t₁ = t₂, from topological_space_eq $ funext $ assume s, by rw [o₁, o₂]; simp [this], by simp [*] lemma uniform_space.of_core_eq_to_core (u : uniform_space α) (t : topological_space α) (h : t = u.to_core.to_topological_space) : uniform_space.of_core_eq u.to_core t h = u := uniform_space_eq rfl /-- Replace topology in a `uniform_space` instance with a propositionally (but possibly not definitionally) equal one. -/ def uniform_space.replace_topology {α : Type*} [i : topological_space α] (u : uniform_space α) (h : i = u.to_topological_space) : uniform_space α := uniform_space.of_core_eq u.to_core i $ h.trans u.to_core_to_topological_space.symm lemma uniform_space.replace_topology_eq {α : Type*} [i : topological_space α] (u : uniform_space α) (h : i = u.to_topological_space) : u.replace_topology h = u := u.of_core_eq_to_core _ _ section uniform_space variables [uniform_space α] /-- The uniformity is a filter on α × α (inferred from an ambient uniform space structure on α). -/ def uniformity (α : Type u) [uniform_space α] : filter (α × α) := (@uniform_space.to_core α _).uniformity localized "notation `𝓤` := uniformity" in uniformity lemma is_open_uniformity {s : set α} : is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ 𝓤 α) := uniform_space.is_open_uniformity s lemma refl_le_uniformity : 𝓟 id_rel ≤ 𝓤 α := (@uniform_space.to_core α _).refl lemma refl_mem_uniformity {x : α} {s : set (α × α)} (h : s ∈ 𝓤 α) : (x, x) ∈ s := refl_le_uniformity h rfl lemma mem_uniformity_of_eq {x y : α} {s : set (α × α)} (h : s ∈ 𝓤 α) (hx : x = y) : (x, y) ∈ s := hx ▸ refl_mem_uniformity h lemma symm_le_uniformity : map (@prod.swap α α) (𝓤 _) ≤ (𝓤 _) := (@uniform_space.to_core α _).symm lemma comp_le_uniformity : (𝓤 α).lift' (λs:set (α×α), s ○ s) ≤ 𝓤 α := (@uniform_space.to_core α _).comp lemma tendsto_swap_uniformity : tendsto (@prod.swap α α) (𝓤 α) (𝓤 α) := symm_le_uniformity lemma comp_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, t ○ t ⊆ s := have s ∈ (𝓤 α).lift' (λt:set (α×α), t ○ t), from comp_le_uniformity hs, (mem_lift'_sets $ monotone_comp_rel monotone_id monotone_id).mp this /-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is transitive. -/ lemma filter.tendsto.uniformity_trans {l : filter β} {f₁ f₂ f₃ : β → α} (h₁₂ : tendsto (λ x, (f₁ x, f₂ x)) l (𝓤 α)) (h₂₃ : tendsto (λ x, (f₂ x, f₃ x)) l (𝓤 α)) : tendsto (λ x, (f₁ x, f₃ x)) l (𝓤 α) := begin refine le_trans (le_lift' $ λ s hs, mem_map.2 _) comp_le_uniformity, filter_upwards [h₁₂ hs, h₂₃ hs], exact λ x hx₁₂ hx₂₃, ⟨_, hx₁₂, hx₂₃⟩ end /-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is symmetric -/ lemma filter.tendsto.uniformity_symm {l : filter β} {f : β → α × α} (h : tendsto f l (𝓤 α)) : tendsto (λ x, ((f x).2, (f x).1)) l (𝓤 α) := tendsto_swap_uniformity.comp h /-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is reflexive. -/ lemma tendsto_diag_uniformity (f : β → α) (l : filter β) : tendsto (λ x, (f x, f x)) l (𝓤 α) := assume s hs, mem_map.2 $ univ_mem' $ λ x, refl_mem_uniformity hs lemma tendsto_const_uniformity {a : α} {f : filter β} : tendsto (λ _, (a, a)) f (𝓤 α) := tendsto_diag_uniformity (λ _, a) f lemma symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, (∀a b, (a, b) ∈ t → (b, a) ∈ t) ∧ t ⊆ s := have preimage prod.swap s ∈ 𝓤 α, from symm_le_uniformity hs, ⟨s ∩ preimage prod.swap s, inter_mem hs this, λ a b ⟨h₁, h₂⟩, ⟨h₂, h₁⟩, inter_subset_left _ _⟩ lemma comp_symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, (∀{a b}, (a, b) ∈ t → (b, a) ∈ t) ∧ t ○ t ⊆ s := let ⟨t, ht₁, ht₂⟩ := comp_mem_uniformity_sets hs in let ⟨t', ht', ht'₁, ht'₂⟩ := symm_of_uniformity ht₁ in ⟨t', ht', ht'₁, subset.trans (monotone_comp_rel monotone_id monotone_id ht'₂) ht₂⟩ lemma uniformity_le_symm : 𝓤 α ≤ (@prod.swap α α) <$> 𝓤 α := by rw [map_swap_eq_comap_swap]; from map_le_iff_le_comap.1 tendsto_swap_uniformity lemma uniformity_eq_symm : 𝓤 α = (@prod.swap α α) <$> 𝓤 α := le_antisymm uniformity_le_symm symm_le_uniformity lemma symmetrize_mem_uniformity {V : set (α × α)} (h : V ∈ 𝓤 α) : symmetrize_rel V ∈ 𝓤 α := begin apply (𝓤 α).inter_sets h, rw [← image_swap_eq_preimage_swap, uniformity_eq_symm], exact image_mem_map h, end theorem uniformity_lift_le_swap {g : set (α×α) → filter β} {f : filter β} (hg : monotone g) (h : (𝓤 α).lift (λs, g (preimage prod.swap s)) ≤ f) : (𝓤 α).lift g ≤ f := calc (𝓤 α).lift g ≤ (filter.map (@prod.swap α α) $ 𝓤 α).lift g : lift_mono uniformity_le_symm (le_refl _) ... ≤ _ : by rw [map_lift_eq2 hg, image_swap_eq_preimage_swap]; exact h lemma uniformity_lift_le_comp {f : set (α×α) → filter β} (h : monotone f) : (𝓤 α).lift (λs, f (s ○ s)) ≤ (𝓤 α).lift f := calc (𝓤 α).lift (λs, f (s ○ s)) = ((𝓤 α).lift' (λs:set (α×α), s ○ s)).lift f : begin rw [lift_lift'_assoc], exact monotone_comp_rel monotone_id monotone_id, exact h end ... ≤ (𝓤 α).lift f : lift_mono comp_le_uniformity (le_refl _) lemma comp_le_uniformity3 : (𝓤 α).lift' (λs:set (α×α), s ○ (s ○ s)) ≤ (𝓤 α) := calc (𝓤 α).lift' (λd, d ○ (d ○ d)) = (𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), s ○ (t ○ t))) : begin rw [lift_lift'_same_eq_lift'], exact (assume x, monotone_comp_rel monotone_const $ monotone_comp_rel monotone_id monotone_id), exact (assume x, monotone_comp_rel monotone_id monotone_const), end ... ≤ (𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), s ○ t)) : lift_mono' $ assume s hs, @uniformity_lift_le_comp α _ _ (𝓟 ∘ (○) s) $ monotone_principal.comp (monotone_comp_rel monotone_const monotone_id) ... = (𝓤 α).lift' (λs:set(α×α), s ○ s) : lift_lift'_same_eq_lift' (assume s, monotone_comp_rel monotone_const monotone_id) (assume s, monotone_comp_rel monotone_id monotone_const) ... ≤ (𝓤 α) : comp_le_uniformity /-- See also `comp_open_symm_mem_uniformity_sets`. -/ lemma comp_symm_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, symmetric_rel t ∧ t ○ t ⊆ s := begin obtain ⟨w, w_in, w_sub⟩ : ∃ w ∈ 𝓤 α, w ○ w ⊆ s := comp_mem_uniformity_sets hs, use [symmetrize_rel w, symmetrize_mem_uniformity w_in, symmetric_symmetrize_rel w], have : symmetrize_rel w ⊆ w := symmetrize_rel_subset_self w, calc symmetrize_rel w ○ symmetrize_rel w ⊆ w ○ w : by mono ... ⊆ s : w_sub, end lemma subset_comp_self_of_mem_uniformity {s : set (α × α)} (h : s ∈ 𝓤 α) : s ⊆ s ○ s := subset_comp_self (refl_le_uniformity h) lemma comp_comp_symm_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, symmetric_rel t ∧ t ○ t ○ t ⊆ s := begin rcases comp_symm_mem_uniformity_sets hs with ⟨w, w_in, w_symm, w_sub⟩, rcases comp_symm_mem_uniformity_sets w_in with ⟨t, t_in, t_symm, t_sub⟩, use [t, t_in, t_symm], have : t ⊆ t ○ t := subset_comp_self_of_mem_uniformity t_in, calc t ○ t ○ t ⊆ w ○ t : by mono ... ⊆ w ○ (t ○ t) : by mono ... ⊆ w ○ w : by mono ... ⊆ s : w_sub, end /-! ### Balls in uniform spaces -/ /-- The ball around `(x : β)` with respect to `(V : set (β × β))`. Intended to be used for `V ∈ 𝓤 β`, but this is not needed for the definition. Recovers the notions of metric space ball when `V = {p | dist p.1 p.2 < r }`. -/ def uniform_space.ball (x : β) (V : set (β × β)) : set β := (prod.mk x) ⁻¹' V open uniform_space (ball) lemma uniform_space.mem_ball_self (x : α) {V : set (α × α)} (hV : V ∈ 𝓤 α) : x ∈ ball x V := refl_mem_uniformity hV /-- The triangle inequality for `uniform_space.ball` -/ lemma mem_ball_comp {V W : set (β × β)} {x y z} (h : y ∈ ball x V) (h' : z ∈ ball y W) : z ∈ ball x (V ○ W) := prod_mk_mem_comp_rel h h' lemma ball_subset_of_comp_subset {V W : set (β × β)} {x y} (h : x ∈ ball y W) (h' : W ○ W ⊆ V) : ball x W ⊆ ball y V := λ z z_in, h' (mem_ball_comp h z_in) lemma ball_mono {V W : set (β × β)} (h : V ⊆ W) (x : β) : ball x V ⊆ ball x W := by tauto lemma ball_inter_left (x : β) (V W : set (β × β)) : ball x (V ∩ W) ⊆ ball x V := ball_mono (inter_subset_left V W) x lemma ball_inter_right (x : β) (V W : set (β × β)) : ball x (V ∩ W) ⊆ ball x W := ball_mono (inter_subset_right V W) x lemma mem_ball_symmetry {V : set (β × β)} (hV : symmetric_rel V) {x y} : x ∈ ball y V ↔ y ∈ ball x V := show (x, y) ∈ prod.swap ⁻¹' V ↔ (x, y) ∈ V, by { unfold symmetric_rel at hV, rw hV } lemma ball_eq_of_symmetry {V : set (β × β)} (hV : symmetric_rel V) {x} : ball x V = {y | (y, x) ∈ V} := by { ext y, rw mem_ball_symmetry hV, exact iff.rfl } lemma mem_comp_of_mem_ball {V W : set (β × β)} {x y z : β} (hV : symmetric_rel V) (hx : x ∈ ball z V) (hy : y ∈ ball z W) : (x, y) ∈ V ○ W := begin rw mem_ball_symmetry hV at hx, exact ⟨z, hx, hy⟩ end lemma uniform_space.is_open_ball (x : α) {V : set (α × α)} (hV : is_open V) : is_open (ball x V) := hV.preimage $ continuous_const.prod_mk continuous_id lemma mem_comp_comp {V W M : set (β × β)} (hW' : symmetric_rel W) {p : β × β} : p ∈ V ○ M ○ W ↔ ((ball p.1 V).prod (ball p.2 W) ∩ M).nonempty := begin cases p with x y, split, { rintros ⟨z, ⟨w, hpw, hwz⟩, hzy⟩, exact ⟨(w, z), ⟨hpw, by rwa mem_ball_symmetry hW'⟩, hwz⟩, }, { rintro ⟨⟨w, z⟩, ⟨w_in, z_in⟩, hwz⟩, rwa mem_ball_symmetry hW' at z_in, use [z, w] ; tauto }, end /-! ### Neighborhoods in uniform spaces -/ lemma mem_nhds_uniformity_iff_right {x : α} {s : set α} : s ∈ 𝓝 x ↔ {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α := ⟨ begin simp only [mem_nhds_iff, is_open_uniformity, and_imp, exists_imp_distrib], exact assume t ts ht xt, by filter_upwards [ht x xt] assume ⟨x', y⟩ h eq, ts $ h eq end, assume hs, mem_nhds_iff.mpr ⟨{x | {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α}, assume x' hx', refl_mem_uniformity hx' rfl, is_open_uniformity.mpr $ assume x' hx', let ⟨t, ht, tr⟩ := comp_mem_uniformity_sets hx' in by filter_upwards [ht] assume ⟨a, b⟩ hp' (hax' : a = x'), by filter_upwards [ht] assume ⟨a, b'⟩ hp'' (hab : a = b), have hp : (x', b) ∈ t, from hax' ▸ hp', have (b, b') ∈ t, from hab ▸ hp'', have (x', b') ∈ t ○ t, from ⟨b, hp, this⟩, show b' ∈ s, from tr this rfl, hs⟩⟩ lemma mem_nhds_uniformity_iff_left {x : α} {s : set α} : s ∈ 𝓝 x ↔ {p : α × α | p.2 = x → p.1 ∈ s} ∈ 𝓤 α := by { rw [uniformity_eq_symm, mem_nhds_uniformity_iff_right], refl } lemma nhds_eq_comap_uniformity_aux {α : Type u} {x : α} {s : set α} {F : filter (α × α)} : {p : α × α | p.fst = x → p.snd ∈ s} ∈ F ↔ s ∈ comap (prod.mk x) F := by rw mem_comap ; from iff.intro (assume hs, ⟨_, hs, assume x hx, hx rfl⟩) (assume ⟨t, h, ht⟩, F.sets_of_superset h $ assume ⟨p₁, p₂⟩ hp (h : p₁ = x), ht $ by simp [h.symm, hp]) lemma nhds_eq_comap_uniformity {x : α} : 𝓝 x = (𝓤 α).comap (prod.mk x) := by { ext s, rw [mem_nhds_uniformity_iff_right], exact nhds_eq_comap_uniformity_aux } /-- See also `is_open_iff_open_ball_subset`. -/ lemma is_open_iff_ball_subset {s : set α} : is_open s ↔ ∀ x ∈ s, ∃ V ∈ 𝓤 α, ball x V ⊆ s := begin simp_rw [is_open_iff_mem_nhds, nhds_eq_comap_uniformity], exact iff.rfl, end lemma nhds_basis_uniformity' {p : ι → Prop} {s : ι → set (α × α)} (h : (𝓤 α).has_basis p s) {x : α} : (𝓝 x).has_basis p (λ i, ball x (s i)) := by { rw [nhds_eq_comap_uniformity], exact h.comap (prod.mk x) } lemma nhds_basis_uniformity {p : ι → Prop} {s : ι → set (α × α)} (h : (𝓤 α).has_basis p s) {x : α} : (𝓝 x).has_basis p (λ i, {y | (y, x) ∈ s i}) := begin replace h := h.comap prod.swap, rw [← map_swap_eq_comap_swap, ← uniformity_eq_symm] at h, exact nhds_basis_uniformity' h end lemma uniform_space.mem_nhds_iff {x : α} {s : set α} : s ∈ 𝓝 x ↔ ∃ V ∈ 𝓤 α, ball x V ⊆ s := begin rw [nhds_eq_comap_uniformity, mem_comap], exact iff.rfl, end lemma uniform_space.ball_mem_nhds (x : α) ⦃V : set (α × α)⦄ (V_in : V ∈ 𝓤 α) : ball x V ∈ 𝓝 x := begin rw uniform_space.mem_nhds_iff, exact ⟨V, V_in, subset.refl _⟩ end lemma uniform_space.mem_nhds_iff_symm {x : α} {s : set α} : s ∈ 𝓝 x ↔ ∃ V ∈ 𝓤 α, symmetric_rel V ∧ ball x V ⊆ s := begin rw uniform_space.mem_nhds_iff, split, { rintros ⟨V, V_in, V_sub⟩, use [symmetrize_rel V, symmetrize_mem_uniformity V_in, symmetric_symmetrize_rel V], exact subset.trans (ball_mono (symmetrize_rel_subset_self V) x) V_sub }, { rintros ⟨V, V_in, V_symm, V_sub⟩, exact ⟨V, V_in, V_sub⟩ } end lemma uniform_space.has_basis_nhds (x : α) : has_basis (𝓝 x) (λ s : set (α × α), s ∈ 𝓤 α ∧ symmetric_rel s) (λ s, ball x s) := ⟨λ t, by simp [uniform_space.mem_nhds_iff_symm, and_assoc]⟩ open uniform_space lemma uniform_space.mem_closure_iff_symm_ball {s : set α} {x} : x ∈ closure s ↔ ∀ {V}, V ∈ 𝓤 α → symmetric_rel V → (s ∩ ball x V).nonempty := by simp [mem_closure_iff_nhds_basis (has_basis_nhds x), set.nonempty] lemma uniform_space.mem_closure_iff_ball {s : set α} {x} : x ∈ closure s ↔ ∀ {V}, V ∈ 𝓤 α → (ball x V ∩ s).nonempty := by simp [mem_closure_iff_nhds_basis' (nhds_basis_uniformity' (𝓤 α).basis_sets)] lemma uniform_space.has_basis_nhds_prod (x y : α) : has_basis (𝓝 (x, y)) (λ s, s ∈ 𝓤 α ∧ symmetric_rel s) $ λ s, (ball x s).prod (ball y s) := begin rw nhds_prod_eq, apply (has_basis_nhds x).prod' (has_basis_nhds y), rintro U V ⟨U_in, U_symm⟩ ⟨V_in, V_symm⟩, exact ⟨U ∩ V, ⟨(𝓤 α).inter_sets U_in V_in, symmetric_rel_inter U_symm V_symm⟩, ball_inter_left x U V, ball_inter_right y U V⟩, end lemma nhds_eq_uniformity {x : α} : 𝓝 x = (𝓤 α).lift' (ball x) := (nhds_basis_uniformity' (𝓤 α).basis_sets).eq_binfi lemma mem_nhds_left (x : α) {s : set (α×α)} (h : s ∈ 𝓤 α) : {y : α | (x, y) ∈ s} ∈ 𝓝 x := ball_mem_nhds x h lemma mem_nhds_right (y : α) {s : set (α×α)} (h : s ∈ 𝓤 α) : {x : α | (x, y) ∈ s} ∈ 𝓝 y := mem_nhds_left _ (symm_le_uniformity h) lemma tendsto_right_nhds_uniformity {a : α} : tendsto (λa', (a', a)) (𝓝 a) (𝓤 α) := assume s, mem_nhds_right a lemma tendsto_left_nhds_uniformity {a : α} : tendsto (λa', (a, a')) (𝓝 a) (𝓤 α) := assume s, mem_nhds_left a lemma lift_nhds_left {x : α} {g : set α → filter β} (hg : monotone g) : (𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) := eq.trans begin rw [nhds_eq_uniformity], exact (filter.lift_assoc $ monotone_principal.comp $ monotone_preimage.comp monotone_preimage ) end (congr_arg _ $ funext $ assume s, filter.lift_principal hg) lemma lift_nhds_right {x : α} {g : set α → filter β} (hg : monotone g) : (𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (y, x) ∈ s}) := calc (𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : lift_nhds_left hg ... = ((@prod.swap α α) <$> (𝓤 α)).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : by rw [←uniformity_eq_symm] ... = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ image prod.swap s}) : map_lift_eq2 $ hg.comp monotone_preimage ... = _ : by simp [image_swap_eq_preimage_swap] lemma nhds_nhds_eq_uniformity_uniformity_prod {a b : α} : 𝓝 a ×ᶠ 𝓝 b = (𝓤 α).lift (λs:set (α×α), (𝓤 α).lift' (λt:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ t})) := begin rw [prod_def], show (𝓝 a).lift (λs:set α, (𝓝 b).lift (λt:set α, 𝓟 (set.prod s t))) = _, rw [lift_nhds_right], apply congr_arg, funext s, rw [lift_nhds_left], refl, exact monotone_principal.comp (monotone_prod monotone_const monotone_id), exact (monotone_lift' monotone_const $ monotone_lam $ assume x, monotone_prod monotone_id monotone_const) end lemma nhds_eq_uniformity_prod {a b : α} : 𝓝 (a, b) = (𝓤 α).lift' (λs:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ s}) := begin rw [nhds_prod_eq, nhds_nhds_eq_uniformity_uniformity_prod, lift_lift'_same_eq_lift'], { intro s, exact monotone_prod monotone_const monotone_preimage }, { intro t, exact monotone_prod monotone_preimage monotone_const } end lemma nhdset_of_mem_uniformity {d : set (α×α)} (s : set (α×α)) (hd : d ∈ 𝓤 α) : ∃(t : set (α×α)), is_open t ∧ s ⊆ t ∧ t ⊆ {p | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} := let cl_d := {p:α×α | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} in have ∀p ∈ s, ∃t ⊆ cl_d, is_open t ∧ p ∈ t, from assume ⟨x, y⟩ hp, _root_.mem_nhds_iff.mp $ show cl_d ∈ 𝓝 (x, y), begin rw [nhds_eq_uniformity_prod, mem_lift'_sets], exact ⟨d, hd, assume ⟨a, b⟩ ⟨ha, hb⟩, ⟨x, y, ha, hp, hb⟩⟩, exact monotone_prod monotone_preimage monotone_preimage end, have ∃t:(Π(p:α×α) (h:p ∈ s), set (α×α)), ∀p, ∀h:p ∈ s, t p h ⊆ cl_d ∧ is_open (t p h) ∧ p ∈ t p h, by simp [classical.skolem] at this; simp; assumption, match this with | ⟨t, ht⟩ := ⟨(⋃ p:α×α, ⋃ h : p ∈ s, t p h : set (α×α)), is_open_Union $ assume (p:α×α), is_open_Union $ assume hp, (ht p hp).right.left, assume ⟨a, b⟩ hp, begin simp; exact ⟨a, b, hp, (ht (a,b) hp).right.right⟩ end, Union_subset $ assume p, Union_subset $ assume hp, (ht p hp).left⟩ end /-- Entourages are neighborhoods of the diagonal. -/ lemma nhds_le_uniformity (x : α) : 𝓝 (x, x) ≤ 𝓤 α := begin intros V V_in, rcases comp_symm_mem_uniformity_sets V_in with ⟨w, w_in, w_symm, w_sub⟩, have : (ball x w).prod (ball x w) ∈ 𝓝 (x, x), { rw nhds_prod_eq, exact prod_mem_prod (ball_mem_nhds x w_in) (ball_mem_nhds x w_in) }, apply mem_of_superset this, rintros ⟨u, v⟩ ⟨u_in, v_in⟩, exact w_sub (mem_comp_of_mem_ball w_symm u_in v_in) end /-- Entourages are neighborhoods of the diagonal. -/ lemma supr_nhds_le_uniformity : (⨆ x : α, 𝓝 (x, x)) ≤ 𝓤 α := supr_le nhds_le_uniformity /-! ### Closure and interior in uniform spaces -/ lemma closure_eq_uniformity (s : set $ α × α) : closure s = ⋂ V ∈ {V | V ∈ 𝓤 α ∧ symmetric_rel V}, V ○ s ○ V := begin ext ⟨x, y⟩, simp_rw [mem_closure_iff_nhds_basis (uniform_space.has_basis_nhds_prod x y), mem_Inter, mem_set_of_eq], apply forall_congr, intro V, apply forall_congr, rintros ⟨V_in, V_symm⟩, simp_rw [mem_comp_comp V_symm, inter_comm, exists_prop], exact iff.rfl, end lemma uniformity_has_basis_closed : has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α ∧ is_closed V) id := begin refine filter.has_basis_self.2 (λ t h, _), rcases comp_comp_symm_mem_uniformity_sets h with ⟨w, w_in, w_symm, r⟩, refine ⟨closure w, mem_of_superset w_in subset_closure, is_closed_closure, _⟩, refine subset.trans _ r, rw closure_eq_uniformity, apply Inter_subset_of_subset, apply Inter_subset, exact ⟨w_in, w_symm⟩ end /-- Closed entourages form a basis of the uniformity filter. -/ lemma uniformity_has_basis_closure : has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α) closure := ⟨begin intro t, rw uniformity_has_basis_closed.mem_iff, split, { rintros ⟨r, ⟨r_in, r_closed⟩, r_sub⟩, use [r, r_in], convert r_sub, rw r_closed.closure_eq, refl }, { rintros ⟨r, r_in, r_sub⟩, exact ⟨closure r, ⟨mem_of_superset r_in subset_closure, is_closed_closure⟩, r_sub⟩ } end⟩ lemma closure_eq_inter_uniformity {t : set (α×α)} : closure t = (⋂ d ∈ 𝓤 α, d ○ (t ○ d)) := set.ext $ assume ⟨a, b⟩, calc (a, b) ∈ closure t ↔ (𝓝 (a, b) ⊓ 𝓟 t ≠ ⊥) : mem_closure_iff_nhds_ne_bot ... ↔ (((@prod.swap α α) <$> 𝓤 α).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ 𝓟 t ≠ ⊥) : by rw [←uniformity_eq_symm, nhds_eq_uniformity_prod] ... ↔ ((map (@prod.swap α α) (𝓤 α)).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ 𝓟 t ≠ ⊥) : by refl ... ↔ ((𝓤 α).lift' (λ (s : set (α × α)), set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s}) ⊓ 𝓟 t ≠ ⊥) : begin rw [map_lift'_eq2], simp [image_swap_eq_preimage_swap, function.comp], exact monotone_prod monotone_preimage monotone_preimage end ... ↔ (∀s ∈ 𝓤 α, (set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s} ∩ t).nonempty) : begin rw [lift'_inf_principal_eq, ← ne_bot_iff, lift'_ne_bot_iff], exact monotone_inter (monotone_prod monotone_preimage monotone_preimage) monotone_const end ... ↔ (∀ s ∈ 𝓤 α, (a, b) ∈ s ○ (t ○ s)) : forall_congr $ assume s, forall_congr $ assume hs, ⟨assume ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩, ⟨x, hx, y, hxyt, hy⟩, assume ⟨x, hx, y, hxyt, hy⟩, ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩⟩ ... ↔ _ : by simp lemma uniformity_eq_uniformity_closure : 𝓤 α = (𝓤 α).lift' closure := le_antisymm (le_infi $ assume s, le_infi $ assume hs, by simp; filter_upwards [hs] subset_closure) (calc (𝓤 α).lift' closure ≤ (𝓤 α).lift' (λd, d ○ (d ○ d)) : lift'_mono' (by intros s hs; rw [closure_eq_inter_uniformity]; exact bInter_subset_of_mem hs) ... ≤ (𝓤 α) : comp_le_uniformity3) lemma uniformity_eq_uniformity_interior : 𝓤 α = (𝓤 α).lift' interior := le_antisymm (le_infi $ assume d, le_infi $ assume hd, let ⟨s, hs, hs_comp⟩ := (mem_lift'_sets $ monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in let ⟨t, ht, hst, ht_comp⟩ := nhdset_of_mem_uniformity s hs in have s ⊆ interior d, from calc s ⊆ t : hst ... ⊆ interior d : (subset_interior_iff_subset_of_open ht).mpr $ λ x (hx : x ∈ t), let ⟨x, y, h₁, h₂, h₃⟩ := ht_comp hx in hs_comp ⟨x, h₁, y, h₂, h₃⟩, have interior d ∈ 𝓤 α, by filter_upwards [hs] this, by simp [this]) (assume s hs, ((𝓤 α).lift' interior).sets_of_superset (mem_lift' hs) interior_subset) lemma interior_mem_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : interior s ∈ 𝓤 α := by rw [uniformity_eq_uniformity_interior]; exact mem_lift' hs lemma mem_uniformity_is_closed {s : set (α×α)} (h : s ∈ 𝓤 α) : ∃t ∈ 𝓤 α, is_closed t ∧ t ⊆ s := let ⟨t, ⟨ht_mem, htc⟩, hts⟩ := uniformity_has_basis_closed.mem_iff.1 h in ⟨t, ht_mem, htc, hts⟩ lemma is_open_iff_open_ball_subset {s : set α} : is_open s ↔ ∀ x ∈ s, ∃ V ∈ 𝓤 α, is_open V ∧ ball x V ⊆ s := begin rw is_open_iff_ball_subset, split; intros h x hx, { obtain ⟨V, hV, hV'⟩ := h x hx, exact ⟨interior V, interior_mem_uniformity hV, is_open_interior, (ball_mono interior_subset x).trans hV'⟩, }, { obtain ⟨V, hV, -, hV'⟩ := h x hx, exact ⟨V, hV, hV'⟩, }, end /-- The uniform neighborhoods of all points of a dense set cover the whole space. -/ lemma dense.bUnion_uniformity_ball {s : set α} {U : set (α × α)} (hs : dense s) (hU : U ∈ 𝓤 α) : (⋃ x ∈ s, ball x U) = univ := begin refine bUnion_eq_univ_iff.2 (λ y, _), rcases hs.inter_nhds_nonempty (mem_nhds_right y hU) with ⟨x, hxs, hxy : (x, y) ∈ U⟩, exact ⟨x, hxs, hxy⟩ end /-! ### Uniformity bases -/ /-- Open elements of `𝓤 α` form a basis of `𝓤 α`. -/ lemma uniformity_has_basis_open : has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α ∧ is_open V) id := has_basis_self.2 $ λ s hs, ⟨interior s, interior_mem_uniformity hs, is_open_interior, interior_subset⟩ lemma filter.has_basis.mem_uniformity_iff {p : β → Prop} {s : β → set (α×α)} (h : (𝓤 α).has_basis p s) {t : set (α × α)} : t ∈ 𝓤 α ↔ ∃ i (hi : p i), ∀ a b, (a, b) ∈ s i → (a, b) ∈ t := h.mem_iff.trans $ by simp only [prod.forall, subset_def] /-- Symmetric entourages form a basis of `𝓤 α` -/ lemma uniform_space.has_basis_symmetric : (𝓤 α).has_basis (λ s : set (α × α), s ∈ 𝓤 α ∧ symmetric_rel s) id := has_basis_self.2 $ λ t t_in, ⟨symmetrize_rel t, symmetrize_mem_uniformity t_in, symmetric_symmetrize_rel t, symmetrize_rel_subset_self t⟩ /-- Open elements `s : set (α × α)` of `𝓤 α` such that `(x, y) ∈ s ↔ (y, x) ∈ s` form a basis of `𝓤 α`. -/ lemma uniformity_has_basis_open_symmetric : has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α ∧ is_open V ∧ symmetric_rel V) id := begin simp only [← and_assoc], refine uniformity_has_basis_open.restrict (λ s hs, ⟨symmetrize_rel s, _⟩), exact ⟨⟨symmetrize_mem_uniformity hs.1, is_open.inter hs.2 (hs.2.preimage continuous_swap)⟩, symmetric_symmetrize_rel s, symmetrize_rel_subset_self s⟩ end lemma comp_open_symm_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, is_open t ∧ symmetric_rel t ∧ t ○ t ⊆ s := begin obtain ⟨t, ht₁, ht₂⟩ := comp_mem_uniformity_sets hs, obtain ⟨u, ⟨hu₁, hu₂, hu₃⟩, hu₄ : u ⊆ t⟩ := uniformity_has_basis_open_symmetric.mem_iff.mp ht₁, exact ⟨u, hu₁, hu₂, hu₃, (comp_rel_mono hu₄ hu₄).trans ht₂⟩, end section variable (α) lemma uniform_space.has_seq_basis [is_countably_generated $ 𝓤 α] : ∃ V : ℕ → set (α × α), has_antitone_basis (𝓤 α) V ∧ ∀ n, symmetric_rel (V n) := let ⟨U, hsym, hbasis⟩ := uniform_space.has_basis_symmetric.exists_antitone_subbasis in ⟨U, hbasis, λ n, (hsym n).2⟩ end lemma filter.has_basis.bInter_bUnion_ball {p : ι → Prop} {U : ι → set (α × α)} (h : has_basis (𝓤 α) p U) (s : set α) : (⋂ i (hi : p i), ⋃ x ∈ s, ball x (U i)) = closure s := begin ext x, simp [mem_closure_iff_nhds_basis (nhds_basis_uniformity h), ball] end /-! ### Uniform continuity -/ /-- A function `f : α → β` is *uniformly continuous* if `(f x, f y)` tends to the diagonal as `(x, y)` tends to the diagonal. In other words, if `x` is sufficiently close to `y`, then `f x` is close to `f y` no matter where `x` and `y` are located in `α`. -/ def uniform_continuous [uniform_space β] (f : α → β) := tendsto (λx:α×α, (f x.1, f x.2)) (𝓤 α) (𝓤 β) /-- A function `f : α → β` is *uniformly continuous* on `s : set α` if `(f x, f y)` tends to the diagonal as `(x, y)` tends to the diagonal while remaining in `s.prod s`. In other words, if `x` is sufficiently close to `y`, then `f x` is close to `f y` no matter where `x` and `y` are located in `s`.-/ def uniform_continuous_on [uniform_space β] (f : α → β) (s : set α) : Prop := tendsto (λ x : α × α, (f x.1, f x.2)) (𝓤 α ⊓ principal (s.prod s)) (𝓤 β) theorem uniform_continuous_def [uniform_space β] {f : α → β} : uniform_continuous f ↔ ∀ r ∈ 𝓤 β, { x : α × α | (f x.1, f x.2) ∈ r} ∈ 𝓤 α := iff.rfl theorem uniform_continuous_iff_eventually [uniform_space β] {f : α → β} : uniform_continuous f ↔ ∀ r ∈ 𝓤 β, ∀ᶠ (x : α × α) in 𝓤 α, (f x.1, f x.2) ∈ r := iff.rfl theorem uniform_continuous_on_univ [uniform_space β] {f : α → β} : uniform_continuous_on f univ ↔ uniform_continuous f := by rw [uniform_continuous_on, uniform_continuous, univ_prod_univ, principal_univ, inf_top_eq] lemma uniform_continuous_of_const [uniform_space β] {c : α → β} (h : ∀a b, c a = c b) : uniform_continuous c := have (λ (x : α × α), (c (x.fst), c (x.snd))) ⁻¹' id_rel = univ, from eq_univ_iff_forall.2 $ assume ⟨a, b⟩, h a b, le_trans (map_le_iff_le_comap.2 $ by simp [comap_principal, this, univ_mem]) refl_le_uniformity lemma uniform_continuous_id : uniform_continuous (@id α) := by simp [uniform_continuous]; exact tendsto_id lemma uniform_continuous_const [uniform_space β] {b : β} : uniform_continuous (λa:α, b) := uniform_continuous_of_const $ λ _ _, rfl lemma uniform_continuous.comp [uniform_space β] [uniform_space γ] {g : β → γ} {f : α → β} (hg : uniform_continuous g) (hf : uniform_continuous f) : uniform_continuous (g ∘ f) := hg.comp hf lemma filter.has_basis.uniform_continuous_iff [uniform_space β] {p : γ → Prop} {s : γ → set (α×α)} (ha : (𝓤 α).has_basis p s) {q : δ → Prop} {t : δ → set (β×β)} (hb : (𝓤 β).has_basis q t) {f : α → β} : uniform_continuous f ↔ ∀ i (hi : q i), ∃ j (hj : p j), ∀ x y, (x, y) ∈ s j → (f x, f y) ∈ t i := (ha.tendsto_iff hb).trans $ by simp only [prod.forall] lemma filter.has_basis.uniform_continuous_on_iff [uniform_space β] {p : γ → Prop} {s : γ → set (α×α)} (ha : (𝓤 α).has_basis p s) {q : δ → Prop} {t : δ → set (β×β)} (hb : (𝓤 β).has_basis q t) {f : α → β} {S : set α} : uniform_continuous_on f S ↔ ∀ i (hi : q i), ∃ j (hj : p j), ∀ x y ∈ S, (x, y) ∈ s j → (f x, f y) ∈ t i := ((ha.inf_principal (S.prod S)).tendsto_iff hb).trans $ by finish [prod.forall] end uniform_space open_locale uniformity section constructions instance : partial_order (uniform_space α) := { le := λt s, t.uniformity ≤ s.uniformity, le_antisymm := assume t s h₁ h₂, uniform_space_eq $ le_antisymm h₁ h₂, le_refl := assume t, le_refl _, le_trans := assume a b c h₁ h₂, le_trans h₁ h₂ } instance : has_Inf (uniform_space α) := ⟨assume s, uniform_space.of_core { uniformity := (⨅u∈s, @uniformity α u), refl := le_infi $ assume u, le_infi $ assume hu, u.refl, symm := le_infi $ assume u, le_infi $ assume hu, le_trans (map_mono $ infi_le_of_le _ $ infi_le _ hu) u.symm, comp := le_infi $ assume u, le_infi $ assume hu, le_trans (lift'_mono (infi_le_of_le _ $ infi_le _ hu) $ le_refl _) u.comp }⟩ private lemma Inf_le {tt : set (uniform_space α)} {t : uniform_space α} (h : t ∈ tt) : Inf tt ≤ t := show (⨅u∈tt, @uniformity α u) ≤ t.uniformity, from infi_le_of_le t $ infi_le _ h private lemma le_Inf {tt : set (uniform_space α)} {t : uniform_space α} (h : ∀t'∈tt, t ≤ t') : t ≤ Inf tt := show t.uniformity ≤ (⨅u∈tt, @uniformity α u), from le_infi $ assume t', le_infi $ assume ht', h t' ht' instance : has_top (uniform_space α) := ⟨uniform_space.of_core { uniformity := ⊤, refl := le_top, symm := le_top, comp := le_top }⟩ instance : has_bot (uniform_space α) := ⟨{ to_topological_space := ⊥, uniformity := 𝓟 id_rel, refl := le_refl _, symm := by simp [tendsto]; apply subset.refl, comp := begin rw [lift'_principal], {simp}, exact monotone_comp_rel monotone_id monotone_id end, is_open_uniformity := assume s, by simp [is_open_fold, subset_def, id_rel] {contextual := tt } } ⟩ instance : complete_lattice (uniform_space α) := { sup := λa b, Inf {x | a ≤ x ∧ b ≤ x}, le_sup_left := λ a b, le_Inf (λ _ ⟨h, _⟩, h), le_sup_right := λ a b, le_Inf (λ _ ⟨_, h⟩, h), sup_le := λ a b c h₁ h₂, Inf_le ⟨h₁, h₂⟩, inf := λ a b, Inf {a, b}, le_inf := λ a b c h₁ h₂, le_Inf (λ u h, by { cases h, exact h.symm ▸ h₁, exact (mem_singleton_iff.1 h).symm ▸ h₂ }), inf_le_left := λ a b, Inf_le (by simp), inf_le_right := λ a b, Inf_le (by simp), top := ⊤, le_top := λ a, show a.uniformity ≤ ⊤, from le_top, bot := ⊥, bot_le := λ u, u.refl, Sup := λ tt, Inf {t | ∀ t' ∈ tt, t' ≤ t}, le_Sup := λ s u h, le_Inf (λ u' h', h' u h), Sup_le := λ s u h, Inf_le h, Inf := Inf, le_Inf := λ s a hs, le_Inf hs, Inf_le := λ s a ha, Inf_le ha, ..uniform_space.partial_order } lemma infi_uniformity {ι : Sort*} {u : ι → uniform_space α} : (infi u).uniformity = (⨅i, (u i).uniformity) := show (⨅a (h : ∃i:ι, u i = a), a.uniformity) = _, from le_antisymm (le_infi $ assume i, infi_le_of_le (u i) $ infi_le _ ⟨i, rfl⟩) (le_infi $ assume a, le_infi $ assume ⟨i, (ha : u i = a)⟩, ha ▸ infi_le _ _) lemma inf_uniformity {u v : uniform_space α} : (u ⊓ v).uniformity = u.uniformity ⊓ v.uniformity := have (u ⊓ v) = (⨅i (h : i = u ∨ i = v), i), by simp [infi_or, infi_inf_eq], calc (u ⊓ v).uniformity = ((⨅i (h : i = u ∨ i = v), i) : uniform_space α).uniformity : by rw [this] ... = _ : by simp [infi_uniformity, infi_or, infi_inf_eq] instance inhabited_uniform_space : inhabited (uniform_space α) := ⟨⊥⟩ instance inhabited_uniform_space_core : inhabited (uniform_space.core α) := ⟨@uniform_space.to_core _ (default _)⟩ /-- Given `f : α → β` and a uniformity `u` on `β`, the inverse image of `u` under `f` is the inverse image in the filter sense of the induced function `α × α → β × β`. -/ def uniform_space.comap (f : α → β) (u : uniform_space β) : uniform_space α := { uniformity := u.uniformity.comap (λp:α×α, (f p.1, f p.2)), to_topological_space := u.to_topological_space.induced f, refl := le_trans (by simp; exact assume ⟨a, b⟩ (h : a = b), h ▸ rfl) (comap_mono u.refl), symm := by simp [tendsto_comap_iff, prod.swap, (∘)]; exact tendsto_swap_uniformity.comp tendsto_comap, comp := le_trans begin rw [comap_lift'_eq, comap_lift'_eq2], exact (lift'_mono' $ assume s hs ⟨a₁, a₂⟩ ⟨x, h₁, h₂⟩, ⟨f x, h₁, h₂⟩), repeat { exact monotone_comp_rel monotone_id monotone_id } end (comap_mono u.comp), is_open_uniformity := λ s, begin change (@is_open α (u.to_topological_space.induced f) s ↔ _), simp [is_open_iff_nhds, nhds_induced, mem_nhds_uniformity_iff_right, filter.comap, and_comm], refine ball_congr (λ x hx, ⟨_, _⟩), { rintro ⟨t, hts, ht⟩, refine ⟨_, ht, _⟩, rintro ⟨x₁, x₂⟩ h rfl, exact hts (h rfl) }, { rintro ⟨t, ht, hts⟩, exact ⟨{y | (f x, y) ∈ t}, λ y hy, @hts (x, y) hy rfl, mem_nhds_uniformity_iff_right.1 $ mem_nhds_left _ ht⟩ } end } lemma uniformity_comap [uniform_space α] [uniform_space β] {f : α → β} (h : ‹uniform_space α› = uniform_space.comap f ‹uniform_space β›) : 𝓤 α = comap (prod.map f f) (𝓤 β) := by { rw h, refl } lemma uniform_space_comap_id {α : Type*} : uniform_space.comap (id : α → α) = id := by ext u ; dsimp [uniform_space.comap] ; rw [prod.id_prod, filter.comap_id] lemma uniform_space.comap_comap {α β γ} [uγ : uniform_space γ] {f : α → β} {g : β → γ} : uniform_space.comap (g ∘ f) uγ = uniform_space.comap f (uniform_space.comap g uγ) := by ext ; dsimp [uniform_space.comap] ; rw filter.comap_comap lemma uniform_continuous_iff {α β} [uα : uniform_space α] [uβ : uniform_space β] {f : α → β} : uniform_continuous f ↔ uα ≤ uβ.comap f := filter.map_le_iff_le_comap lemma uniform_continuous_comap {f : α → β} [u : uniform_space β] : @uniform_continuous α β (uniform_space.comap f u) u f := tendsto_comap theorem to_topological_space_comap {f : α → β} {u : uniform_space β} : @uniform_space.to_topological_space _ (uniform_space.comap f u) = topological_space.induced f (@uniform_space.to_topological_space β u) := rfl lemma uniform_continuous_comap' {f : γ → β} {g : α → γ} [v : uniform_space β] [u : uniform_space α] (h : uniform_continuous (f ∘ g)) : @uniform_continuous α γ u (uniform_space.comap f v) g := tendsto_comap_iff.2 h lemma to_nhds_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) (a : α) : @nhds _ (@uniform_space.to_topological_space _ u₁) a ≤ @nhds _ (@uniform_space.to_topological_space _ u₂) a := by rw [@nhds_eq_uniformity α u₁ a, @nhds_eq_uniformity α u₂ a]; exact (lift'_mono h le_rfl) lemma to_topological_space_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) : @uniform_space.to_topological_space _ u₁ ≤ @uniform_space.to_topological_space _ u₂ := le_of_nhds_le_nhds $ to_nhds_mono h lemma uniform_continuous.continuous [uniform_space α] [uniform_space β] {f : α → β} (hf : uniform_continuous f) : continuous f := continuous_iff_le_induced.mpr $ to_topological_space_mono $ uniform_continuous_iff.1 hf lemma to_topological_space_bot : @uniform_space.to_topological_space α ⊥ = ⊥ := rfl lemma to_topological_space_top : @uniform_space.to_topological_space α ⊤ = ⊤ := top_unique $ assume s hs, s.eq_empty_or_nonempty.elim (assume : s = ∅, this.symm ▸ @is_open_empty _ ⊤) (assume ⟨x, hx⟩, have s = univ, from top_unique $ assume y hy, hs x hx (x, y) rfl, this.symm ▸ @is_open_univ _ ⊤) lemma to_topological_space_infi {ι : Sort*} {u : ι → uniform_space α} : (infi u).to_topological_space = ⨅i, (u i).to_topological_space := begin casesI is_empty_or_nonempty ι, { rw [infi_of_empty, infi_of_empty, to_topological_space_top] }, { refine (eq_of_nhds_eq_nhds $ assume a, _), rw [nhds_infi, nhds_eq_uniformity], change (infi u).uniformity.lift' (preimage $ prod.mk a) = _, rw [infi_uniformity, lift'_infi], { simp only [nhds_eq_uniformity], refl }, { exact assume a b, rfl } }, end lemma to_topological_space_Inf {s : set (uniform_space α)} : (Inf s).to_topological_space = (⨅i∈s, @uniform_space.to_topological_space α i) := begin rw [Inf_eq_infi], simp only [← to_topological_space_infi], end lemma to_topological_space_inf {u v : uniform_space α} : (u ⊓ v).to_topological_space = u.to_topological_space ⊓ v.to_topological_space := by rw [to_topological_space_Inf, infi_pair] instance : uniform_space empty := ⊥ instance : uniform_space punit := ⊥ instance : uniform_space bool := ⊥ instance : uniform_space ℕ := ⊥ instance : uniform_space ℤ := ⊥ instance {p : α → Prop} [t : uniform_space α] : uniform_space (subtype p) := uniform_space.comap subtype.val t lemma uniformity_subtype {p : α → Prop} [t : uniform_space α] : 𝓤 (subtype p) = comap (λq:subtype p × subtype p, (q.1.1, q.2.1)) (𝓤 α) := rfl lemma uniform_continuous_subtype_val {p : α → Prop} [uniform_space α] : uniform_continuous (subtype.val : {a : α // p a} → α) := uniform_continuous_comap lemma uniform_continuous_subtype_mk {p : α → Prop} [uniform_space α] [uniform_space β] {f : β → α} (hf : uniform_continuous f) (h : ∀x, p (f x)) : uniform_continuous (λx, ⟨f x, h x⟩ : β → subtype p) := uniform_continuous_comap' hf lemma uniform_continuous_on_iff_restrict [uniform_space α] [uniform_space β] {f : α → β} {s : set α} : uniform_continuous_on f s ↔ uniform_continuous (s.restrict f) := begin unfold uniform_continuous_on set.restrict uniform_continuous tendsto, rw [show (λ x : s × s, (f x.1, f x.2)) = prod.map f f ∘ coe, by ext x; cases x; refl, uniformity_comap rfl, show prod.map subtype.val subtype.val = (coe : s × s → α × α), by ext x; cases x; refl], conv in (map _ (comap _ _)) { rw ← filter.map_map }, rw subtype_coe_map_comap_prod, refl, end lemma tendsto_of_uniform_continuous_subtype [uniform_space α] [uniform_space β] {f : α → β} {s : set α} {a : α} (hf : uniform_continuous (λx:s, f x.val)) (ha : s ∈ 𝓝 a) : tendsto f (𝓝 a) (𝓝 (f a)) := by rw [(@map_nhds_subtype_coe_eq α _ s a (mem_of_mem_nhds ha) ha).symm]; exact tendsto_map' (continuous_iff_continuous_at.mp hf.continuous _) lemma uniform_continuous_on.continuous_on [uniform_space α] [uniform_space β] {f : α → β} {s : set α} (h : uniform_continuous_on f s) : continuous_on f s := begin rw uniform_continuous_on_iff_restrict at h, rw continuous_on_iff_continuous_restrict, exact h.continuous end section prod /- a similar product space is possible on the function space (uniformity of pointwise convergence), but we want to have the uniformity of uniform convergence on function spaces -/ instance [u₁ : uniform_space α] [u₂ : uniform_space β] : uniform_space (α × β) := uniform_space.of_core_eq (u₁.comap prod.fst ⊓ u₂.comap prod.snd).to_core prod.topological_space (calc prod.topological_space = (u₁.comap prod.fst ⊓ u₂.comap prod.snd).to_topological_space : by rw [to_topological_space_inf, to_topological_space_comap, to_topological_space_comap]; refl ... = _ : by rw [uniform_space.to_core_to_topological_space]) theorem uniformity_prod [uniform_space α] [uniform_space β] : 𝓤 (α × β) = (𝓤 α).comap (λp:(α × β) × α × β, (p.1.1, p.2.1)) ⊓ (𝓤 β).comap (λp:(α × β) × α × β, (p.1.2, p.2.2)) := inf_uniformity lemma uniformity_prod_eq_prod [uniform_space α] [uniform_space β] : 𝓤 (α×β) = map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) (𝓤 α ×ᶠ 𝓤 β) := have map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) = comap (λp:(α×β)×(α×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))), from funext $ assume f, map_eq_comap_of_inverse (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl) (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl), by rw [this, uniformity_prod, filter.prod, comap_inf, comap_comap, comap_comap] lemma mem_map_iff_exists_image' {α : Type*} {β : Type*} {f : filter α} {m : α → β} {t : set β} : t ∈ (map m f).sets ↔ (∃s∈f, m '' s ⊆ t) := mem_map_iff_exists_image lemma mem_uniformity_of_uniform_continuous_invariant [uniform_space α] {s:set (α×α)} {f : α → α → α} (hf : uniform_continuous (λp:α×α, f p.1 p.2)) (hs : s ∈ 𝓤 α) : ∃u∈𝓤 α, ∀a b c, (a, b) ∈ u → (f a c, f b c) ∈ s := begin rw [uniform_continuous, uniformity_prod_eq_prod, tendsto_map'_iff, (∘)] at hf, rcases mem_map_iff_exists_image'.1 (hf hs) with ⟨t, ht, hts⟩, clear hf, rcases mem_prod_iff.1 ht with ⟨u, hu, v, hv, huvt⟩, clear ht, refine ⟨u, hu, assume a b c hab, hts $ (mem_image _ _ _).2 ⟨⟨⟨a, b⟩, ⟨c, c⟩⟩, huvt ⟨_, _⟩, _⟩⟩, exact hab, exact refl_mem_uniformity hv, refl end lemma mem_uniform_prod [t₁ : uniform_space α] [t₂ : uniform_space β] {a : set (α × α)} {b : set (β × β)} (ha : a ∈ 𝓤 α) (hb : b ∈ 𝓤 β) : {p:(α×β)×(α×β) | (p.1.1, p.2.1) ∈ a ∧ (p.1.2, p.2.2) ∈ b } ∈ (@uniformity (α × β) _) := by rw [uniformity_prod]; exact inter_mem_inf (preimage_mem_comap ha) (preimage_mem_comap hb) lemma tendsto_prod_uniformity_fst [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.1, p.2.1)) (𝓤 (α × β)) (𝓤 α) := le_trans (map_mono (@inf_le_left (uniform_space (α×β)) _ _ _)) map_comap_le lemma tendsto_prod_uniformity_snd [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.2, p.2.2)) (𝓤 (α × β)) (𝓤 β) := le_trans (map_mono (@inf_le_right (uniform_space (α×β)) _ _ _)) map_comap_le lemma uniform_continuous_fst [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.1) := tendsto_prod_uniformity_fst lemma uniform_continuous_snd [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.2) := tendsto_prod_uniformity_snd variables [uniform_space α] [uniform_space β] [uniform_space γ] lemma uniform_continuous.prod_mk {f₁ : α → β} {f₂ : α → γ} (h₁ : uniform_continuous f₁) (h₂ : uniform_continuous f₂) : uniform_continuous (λa, (f₁ a, f₂ a)) := by rw [uniform_continuous, uniformity_prod]; exact tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩ lemma uniform_continuous.prod_mk_left {f : α × β → γ} (h : uniform_continuous f) (b) : uniform_continuous (λ a, f (a,b)) := h.comp (uniform_continuous_id.prod_mk uniform_continuous_const) lemma uniform_continuous.prod_mk_right {f : α × β → γ} (h : uniform_continuous f) (a) : uniform_continuous (λ b, f (a,b)) := h.comp (uniform_continuous_const.prod_mk uniform_continuous_id) lemma uniform_continuous.prod_map [uniform_space δ] {f : α → γ} {g : β → δ} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (prod.map f g) := (hf.comp uniform_continuous_fst).prod_mk (hg.comp uniform_continuous_snd) lemma to_topological_space_prod {α} {β} [u : uniform_space α] [v : uniform_space β] : @uniform_space.to_topological_space (α × β) prod.uniform_space = @prod.topological_space α β u.to_topological_space v.to_topological_space := rfl end prod section open uniform_space function variables {δ' : Type*} [uniform_space α] [uniform_space β] [uniform_space γ] [uniform_space δ] [uniform_space δ'] local notation f `∘₂` g := function.bicompr f g /-- Uniform continuity for functions of two variables. -/ def uniform_continuous₂ (f : α → β → γ) := uniform_continuous (uncurry f) lemma uniform_continuous₂_def (f : α → β → γ) : uniform_continuous₂ f ↔ uniform_continuous (uncurry f) := iff.rfl lemma uniform_continuous₂.uniform_continuous {f : α → β → γ} (h : uniform_continuous₂ f) : uniform_continuous (uncurry f) := h lemma uniform_continuous₂_curry (f : α × β → γ) : uniform_continuous₂ (function.curry f) ↔ uniform_continuous f := by rw [uniform_continuous₂, uncurry_curry] lemma uniform_continuous₂.comp {f : α → β → γ} {g : γ → δ} (hg : uniform_continuous g) (hf : uniform_continuous₂ f) : uniform_continuous₂ (g ∘₂ f) := hg.comp hf lemma uniform_continuous₂.bicompl {f : α → β → γ} {ga : δ → α} {gb : δ' → β} (hf : uniform_continuous₂ f) (hga : uniform_continuous ga) (hgb : uniform_continuous gb) : uniform_continuous₂ (bicompl f ga gb) := hf.uniform_continuous.comp (hga.prod_map hgb) end lemma to_topological_space_subtype [u : uniform_space α] {p : α → Prop} : @uniform_space.to_topological_space (subtype p) subtype.uniform_space = @subtype.topological_space α p u.to_topological_space := rfl section sum variables [uniform_space α] [uniform_space β] open sum /-- Uniformity on a disjoint union. Entourages of the diagonal in the union are obtained by taking independently an entourage of the diagonal in the first part, and an entourage of the diagonal in the second part. -/ def uniform_space.core.sum : uniform_space.core (α ⊕ β) := uniform_space.core.mk' (map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔ map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β)) (λ r ⟨H₁, H₂⟩ x, by cases x; [apply refl_mem_uniformity H₁, apply refl_mem_uniformity H₂]) (λ r ⟨H₁, H₂⟩, ⟨symm_le_uniformity H₁, symm_le_uniformity H₂⟩) (λ r ⟨Hrα, Hrβ⟩, begin rcases comp_mem_uniformity_sets Hrα with ⟨tα, htα, Htα⟩, rcases comp_mem_uniformity_sets Hrβ with ⟨tβ, htβ, Htβ⟩, refine ⟨_, ⟨mem_map_iff_exists_image.2 ⟨tα, htα, subset_union_left _ _⟩, mem_map_iff_exists_image.2 ⟨tβ, htβ, subset_union_right _ _⟩⟩, _⟩, rintros ⟨_, _⟩ ⟨z, ⟨⟨a, b⟩, hab, ⟨⟩⟩ | ⟨⟨a, b⟩, hab, ⟨⟩⟩, ⟨⟨_, c⟩, hbc, ⟨⟩⟩ | ⟨⟨_, c⟩, hbc, ⟨⟩⟩⟩, { have A : (a, c) ∈ tα ○ tα := ⟨b, hab, hbc⟩, exact Htα A }, { have A : (a, c) ∈ tβ ○ tβ := ⟨b, hab, hbc⟩, exact Htβ A } end) /-- The union of an entourage of the diagonal in each set of a disjoint union is again an entourage of the diagonal. -/ lemma union_mem_uniformity_sum {a : set (α × α)} (ha : a ∈ 𝓤 α) {b : set (β × β)} (hb : b ∈ 𝓤 β) : ((λ p : (α × α), (inl p.1, inl p.2)) '' a ∪ (λ p : (β × β), (inr p.1, inr p.2)) '' b) ∈ (@uniform_space.core.sum α β _ _).uniformity := ⟨mem_map_iff_exists_image.2 ⟨_, ha, subset_union_left _ _⟩, mem_map_iff_exists_image.2 ⟨_, hb, subset_union_right _ _⟩⟩ /- To prove that the topology defined by the uniform structure on the disjoint union coincides with the disjoint union topology, we need two lemmas saying that open sets can be characterized by the uniform structure -/ lemma uniformity_sum_of_open_aux {s : set (α ⊕ β)} (hs : is_open s) {x : α ⊕ β} (xs : x ∈ s) : { p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈ (@uniform_space.core.sum α β _ _).uniformity := begin cases x, { refine mem_of_superset (union_mem_uniformity_sum (mem_nhds_uniformity_iff_right.1 (is_open.mem_nhds hs.1 xs)) univ_mem) (union_subset _ _); rintro _ ⟨⟨_, b⟩, h, ⟨⟩⟩ ⟨⟩, exact h rfl }, { refine mem_of_superset (union_mem_uniformity_sum univ_mem (mem_nhds_uniformity_iff_right.1 (is_open.mem_nhds hs.2 xs))) (union_subset _ _); rintro _ ⟨⟨a, _⟩, h, ⟨⟩⟩ ⟨⟩, exact h rfl }, end lemma open_of_uniformity_sum_aux {s : set (α ⊕ β)} (hs : ∀x ∈ s, { p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈ (@uniform_space.core.sum α β _ _).uniformity) : is_open s := begin split, { refine (@is_open_iff_mem_nhds α _ _).2 (λ a ha, mem_nhds_uniformity_iff_right.2 _), rcases mem_map_iff_exists_image.1 (hs _ ha).1 with ⟨t, ht, st⟩, refine mem_of_superset ht _, rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl }, { refine (@is_open_iff_mem_nhds β _ _).2 (λ b hb, mem_nhds_uniformity_iff_right.2 _), rcases mem_map_iff_exists_image.1 (hs _ hb).2 with ⟨t, ht, st⟩, refine mem_of_superset ht _, rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl } end /- We can now define the uniform structure on the disjoint union -/ instance sum.uniform_space : uniform_space (α ⊕ β) := { to_core := uniform_space.core.sum, is_open_uniformity := λ s, ⟨uniformity_sum_of_open_aux, open_of_uniformity_sum_aux⟩ } lemma sum.uniformity : 𝓤 (α ⊕ β) = map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔ map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β) := rfl end sum end constructions -- For a version of the Lebesgue number lemma assuming only a sequentially compact space, -- see topology/sequences.lean /-- Let `c : ι → set α` be an open cover of a compact set `s`. Then there exists an entourage `n` such that for each `x ∈ s` its `n`-neighborhood is contained in some `c i`. -/ lemma lebesgue_number_lemma {α : Type u} [uniform_space α] {s : set α} {ι} {c : ι → set α} (hs : is_compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ i, {y | (x, y) ∈ n} ⊆ c i := begin let u := λ n, {x | ∃ i (m ∈ 𝓤 α), {y | (x, y) ∈ m ○ n} ⊆ c i}, have hu₁ : ∀ n ∈ 𝓤 α, is_open (u n), { refine λ n hn, is_open_uniformity.2 _, rintro x ⟨i, m, hm, h⟩, rcases comp_mem_uniformity_sets hm with ⟨m', hm', mm'⟩, apply (𝓤 α).sets_of_superset hm', rintros ⟨x, y⟩ hp rfl, refine ⟨i, m', hm', λ z hz, h (monotone_comp_rel monotone_id monotone_const mm' _)⟩, dsimp at hz ⊢, rw comp_rel_assoc, exact ⟨y, hp, hz⟩ }, have hu₂ : s ⊆ ⋃ n ∈ 𝓤 α, u n, { intros x hx, rcases mem_Union.1 (hc₂ hx) with ⟨i, h⟩, rcases comp_mem_uniformity_sets (is_open_uniformity.1 (hc₁ i) x h) with ⟨m', hm', mm'⟩, exact mem_bUnion hm' ⟨i, _, hm', λ y hy, mm' hy rfl⟩ }, rcases hs.elim_finite_subcover_image hu₁ hu₂ with ⟨b, bu, b_fin, b_cover⟩, refine ⟨_, (bInter_mem b_fin).2 bu, λ x hx, _⟩, rcases mem_bUnion_iff.1 (b_cover hx) with ⟨n, bn, i, m, hm, h⟩, refine ⟨i, λ y hy, h _⟩, exact prod_mk_mem_comp_rel (refl_mem_uniformity hm) (bInter_subset_of_mem bn hy) end /-- Let `c : set (set α)` be an open cover of a compact set `s`. Then there exists an entourage `n` such that for each `x ∈ s` its `n`-neighborhood is contained in some `t ∈ c`. -/ lemma lebesgue_number_lemma_sUnion {α : Type u} [uniform_space α] {s : set α} {c : set (set α)} (hs : is_compact s) (hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ t ∈ c, ∀ y, (x, y) ∈ n → y ∈ t := by rw sUnion_eq_Union at hc₂; simpa using lebesgue_number_lemma hs (by simpa) hc₂ /-- A useful consequence of the Lebesgue number lemma: given any compact set `K` contained in an open set `U`, we can find an (open) entourage `V` such that the ball of size `V` about any point of `K` is contained in `U`. -/ lemma lebesgue_number_of_compact_open [uniform_space α] {K U : set α} (hK : is_compact K) (hU : is_open U) (hKU : K ⊆ U) : ∃ V ∈ 𝓤 α, is_open V ∧ ∀ x ∈ K, uniform_space.ball x V ⊆ U := begin let W : K → set (α × α) := λ k, classical.some $ is_open_iff_open_ball_subset.mp hU k.1 $ hKU k.2, have hW : ∀ k, W k ∈ 𝓤 α ∧ is_open (W k) ∧ uniform_space.ball k.1 (W k) ⊆ U, { intros k, obtain ⟨h₁, h₂, h₃⟩ := classical.some_spec (is_open_iff_open_ball_subset.mp hU k.1 (hKU k.2)), exact ⟨h₁, h₂, h₃⟩, }, let c : K → set α := λ k, uniform_space.ball k.1 (W k), have hc₁ : ∀ k, is_open (c k), { exact λ k, uniform_space.is_open_ball k.1 (hW k).2.1, }, have hc₂ : K ⊆ ⋃ i, c i, { intros k hk, simp only [mem_Union, set_coe.exists], exact ⟨k, hk, uniform_space.mem_ball_self k (hW ⟨k, hk⟩).1⟩, }, have hc₃ : ∀ k, c k ⊆ U, { exact λ k, (hW k).2.2, }, obtain ⟨V, hV, hV'⟩ := lebesgue_number_lemma hK hc₁ hc₂, refine ⟨interior V, interior_mem_uniformity hV, is_open_interior, _⟩, intros k hk, obtain ⟨k', hk'⟩ := hV' k hk, exact ((ball_mono interior_subset k).trans hk').trans (hc₃ k'), end /-! ### Expressing continuity properties in uniform spaces We reformulate the various continuity properties of functions taking values in a uniform space in terms of the uniformity in the target. Since the same lemmas (essentially with the same names) also exist for metric spaces and emetric spaces (reformulating things in terms of the distance or the edistance in the target), we put them in a namespace `uniform` here. In the metric and emetric space setting, there are also similar lemmas where one assumes that both the source and the target are metric spaces, reformulating things in terms of the distance on both sides. These lemmas are generally written without primes, and the versions where only the target is a metric space is primed. We follow the same convention here, thus giving lemmas with primes. -/ namespace uniform variables [uniform_space α] theorem tendsto_nhds_right {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ tendsto (λ x, (a, u x)) f (𝓤 α) := ⟨λ H, tendsto_left_nhds_uniformity.comp H, λ H s hs, by simpa [mem_of_mem_nhds hs] using H (mem_nhds_uniformity_iff_right.1 hs)⟩ theorem tendsto_nhds_left {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ tendsto (λ x, (u x, a)) f (𝓤 α) := ⟨λ H, tendsto_right_nhds_uniformity.comp H, λ H s hs, by simpa [mem_of_mem_nhds hs] using H (mem_nhds_uniformity_iff_left.1 hs)⟩ theorem continuous_at_iff'_right [topological_space β] {f : β → α} {b : β} : continuous_at f b ↔ tendsto (λ x, (f b, f x)) (𝓝 b) (𝓤 α) := by rw [continuous_at, tendsto_nhds_right] theorem continuous_at_iff'_left [topological_space β] {f : β → α} {b : β} : continuous_at f b ↔ tendsto (λ x, (f x, f b)) (𝓝 b) (𝓤 α) := by rw [continuous_at, tendsto_nhds_left] theorem continuous_at_iff_prod [topological_space β] {f : β → α} {b : β} : continuous_at f b ↔ tendsto (λ x : β × β, (f x.1, f x.2)) (𝓝 (b, b)) (𝓤 α) := ⟨λ H, le_trans (H.prod_map' H) (nhds_le_uniformity _), λ H, continuous_at_iff'_left.2 $ H.comp $ tendsto_id.prod_mk_nhds tendsto_const_nhds⟩ theorem continuous_within_at_iff'_right [topological_space β] {f : β → α} {b : β} {s : set β} : continuous_within_at f s b ↔ tendsto (λ x, (f b, f x)) (𝓝[s] b) (𝓤 α) := by rw [continuous_within_at, tendsto_nhds_right] theorem continuous_within_at_iff'_left [topological_space β] {f : β → α} {b : β} {s : set β} : continuous_within_at f s b ↔ tendsto (λ x, (f x, f b)) (𝓝[s] b) (𝓤 α) := by rw [continuous_within_at, tendsto_nhds_left] theorem continuous_on_iff'_right [topological_space β] {f : β → α} {s : set β} : continuous_on f s ↔ ∀ b ∈ s, tendsto (λ x, (f b, f x)) (𝓝[s] b) (𝓤 α) := by simp [continuous_on, continuous_within_at_iff'_right] theorem continuous_on_iff'_left [topological_space β] {f : β → α} {s : set β} : continuous_on f s ↔ ∀ b ∈ s, tendsto (λ x, (f x, f b)) (𝓝[s] b) (𝓤 α) := by simp [continuous_on, continuous_within_at_iff'_left] theorem continuous_iff'_right [topological_space β] {f : β → α} : continuous f ↔ ∀ b, tendsto (λ x, (f b, f x)) (𝓝 b) (𝓤 α) := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_right theorem continuous_iff'_left [topological_space β] {f : β → α} : continuous f ↔ ∀ b, tendsto (λ x, (f x, f b)) (𝓝 b) (𝓤 α) := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_left end uniform lemma filter.tendsto.congr_uniformity {α β} [uniform_space β] {f g : α → β} {l : filter α} {b : β} (hf : tendsto f l (𝓝 b)) (hg : tendsto (λ x, (f x, g x)) l (𝓤 β)) : tendsto g l (𝓝 b) := uniform.tendsto_nhds_right.2 $ (uniform.tendsto_nhds_right.1 hf).uniformity_trans hg lemma uniform.tendsto_congr {α β} [uniform_space β] {f g : α → β} {l : filter α} {b : β} (hfg : tendsto (λ x, (f x, g x)) l (𝓤 β)) : tendsto f l (𝓝 b) ↔ tendsto g l (𝓝 b) := ⟨λ h, h.congr_uniformity hfg, λ h, h.congr_uniformity hfg.uniformity_symm⟩
------------------------------------------------------------------------ -- A variant of Coherently that is defined without the use of -- coinduction ------------------------------------------------------------------------ {-# OPTIONS --cubical #-} import Equality.Path as P module Lens.Non-dependent.Higher.Coherently.Not-coinductive {e⁺} (eq : ∀ {a p} → P.Equality-with-paths a p e⁺) where open P.Derived-definitions-and-properties eq open import Prelude open import Container.Indexed equality-with-J open import Container.Indexed.M.Function equality-with-J open import H-level.Truncation.Propositional.One-step eq using (∥_∥¹) private variable a b p : Level -- A container that is used to define Coherently. Coherently-container : {B : Type b} (P : {A : Type a} → (A → B) → Type p) (step : {A : Type a} (f : A → B) → P f → ∥ A ∥¹ → B) → Container (∃ λ (A : Type a) → A → B) p lzero Coherently-container P step = λ where .Shape (_ , f) → P f .Position _ → ⊤ .index {o = A , f} {s = p} _ → ∥ A ∥¹ , step f p -- A variant of Coherently, defined using an indexed container. Coherently : {A : Type a} {B : Type b} (P : {A : Type a} → (A → B) → Type p) (step : {A : Type a} (f : A → B) → P f → ∥ A ∥¹ → B) → (f : A → B) → Type (lsuc a ⊔ b ⊔ p) Coherently P step f = M (Coherently-container P step) (_ , f)
[STATEMENT] lemma two_step_step: "step = two_step" "phase = two_phase" [PROOF STATE] proof (prove) goal (1 subgoal): 1. step = two_step &&& phase = two_phase [PROOF STEP] by(auto simp add: step_def two_step_def phase_def two_phase_def)
Every week, we’re busy telling the stories behind our platform, our technology and our place in the gaming and technology industries. For those of you who catch up with ROBLOX over the weekend, the Weekly ROBLOX Roundup collects the best stuff to hit our various avenues of publication in the last week. This time: the launch of the ROBLOX International Film Festival, the fantastic winners of our dynamic lighting video contest, the new in-game sales feature, ROBLOX’s booth at Maker Faire Bay Area 2013, crazyman32’s advice on getting your ambitious ROBLOX project off the ground, the first issue of Feedback Loop, Avert the Odds II, and other bits and pieces. Enjoy. A few weeks ago, we announced the ROBLOX International Film Festival and, on Friday, we opened the doors to your submissions. We’re looking for films in five categories and you have until June 2nd at 11:59 p.m. PT to submit your entry. For complete details and a Film Fest FAQ, read our Friday blog announcement. A word of advice: use the time you have available to produce the best film you can. Test it out on friends and see what they think. After all, it’s a prized BLOXY Award and live screening at BLOXcon on the line! With dynamic lighting available on GameTest1 during the second half of April, we decided to launch a contest and see how you early-adopters could leverage the feature. You did not disappoint. We received somewhere in the neighborhood of 200 submissions and the quality of entries was so high that we awarded the primary prize, the Master of Light and Darkness top hat, to not just five, but 10 entrants. You can see all of their wonderful dynamic lighting videos in the blog post announcing the winners. They’re also featured on the ROBLOX YouTube channel. In 2012, we gave ROBLOX builders the ability to sell Game Passes and gear in association with games and places. Last week, we made it even easier to profit off these features by giving builders an API to sell Game Passes and gear in-game. There are many possibilities in implementing in-game sales, and we’re excited to see how you leverage the feature in your place. If you think you’ve done something particularly exciting or effective, let us know by sending a message to @ROBLOX on Twitter or leaving a comment. For an introduction to the feature and integrating it in your place, see our blog article from Thursday. In what we hope is the first of many builder-authored ROBLOX blog posts, veteran crazyman32 discusses the steps to getting a new game-development project off the ground (see what I did there?) in the context of his upcoming release, Perilous Skies: New Horizons. From building a foundation to sprinkling in the polish and details, his advice will steer you in the right direction as you think about creating your own ambitious project. Like last year, ROBLOX will be at Maker Faire Bay Area 2013. Unlike last year, we’re going to have a large space with a lot of fun stuff to do. Among the fun stuff: collaborative building, a dynamic lighting showcase (using your contest entries) and workshop, play testing new content, and hanging out with ROBLOX admins (most of whom will be at the ROBLOX booth at some point over the weekend. The event takes place on May 18th and 19th in San Mateo, CA. Learn more by reading our full update from Tuesday! We rebooted the long-running but well liked “Responding to User Feedback” series with the catchier and snapper “Feedback Loop” last week. Going forward, we’ll continue to collect questions and ideas from the ROBLOX community using social media and have members of the ROBLOX development team respond with answers and thoughts on where, if anywhere, your thoughts fit into our development pipeline. In this first issue of Feedback Loop, John Shedletsky discusses custom particle-effect creation, improved humanoid manipulation, smart/auto-complete script editing, credits for builder-created catalog assets, individual gear statistics and leaderboards, and more! There's nothing like a cloud of negative hit points floating above the enemy head. Avert the Odds II is a well built first-person shooter by Venvious that constantly delivers fast-paced, competitive multiplayer action. What’s really cool is between rounds, players have the opportunity to vote for the next game mode and the player-created map on which the round will take place. Bot Battle is my personal favorite mode; it lets all players band together to fend off waves of increasingly difficult AI opponents. With the ability to level up and put points into your characters skills and customize a weapon loadout, Avert the Odds II has all the bells and whistles you’ve come to expect from modern-day shooters. Plus, it feels responsive and polished. Great work! I’m not exactly sure what an “artifcial gravity spacecraft” is, but it looks cool. We’ve finally finished announcing Fan Art Contest winners on the ROBLOX Facebook page. Would you like to see or submit more ROBLOX fan art? Let us know and we’ll consider re-opening the contest! Now that it’s in the books, here’s a gallery of all the winning art. Great work, everyone!
From discprob.basic Require Import base sval order monad bigop_ext nify. From mathcomp Require Import ssrfun ssreflect eqtype ssrbool seq fintype choice. From discprob.prob Require Import prob countable finite stochastic_order rearrange. Require Import Reals Psatz. From discprob.idxval Require Import ival ival_dist. Record ival_couplingP {A1 A2} (Is1: ival A1) (Is2: ival A2) (P: A1 → A2 → Prop) : Type := mkICoupling { ic_witness :> ival {xy: A1 * A2 | P (fst xy) (snd xy)}; ic_proj1: eq_ival Is1 (x ← ic_witness; mret (fst (sval x))); ic_proj2: eq_ival Is2 (x ← ic_witness; mret (snd (sval x))); }. Record idist_couplingP {A1 A2} (Is1: ivdist A1) (Is2: ivdist A2) (P: A1 → A2 → Prop) : Type := mkIdCoupling { idc_witness :> ivdist {xy: A1 * A2 | P (fst xy) (snd xy)}; idc_proj1: eq_ivd Is1 (x ← idc_witness; mret (fst (sval x))); idc_proj2: eq_ivd Is2 (x ← idc_witness; mret (snd (sval x))); }. From mathcomp Require Import bigop. Lemma ic_coupling_to_id {A1 A2} (I1: ivdist A1) (I2: ivdist A2) P: ival_couplingP I1 I2 P → idist_couplingP I1 I2 P. Proof. intros [Ic Hproj1 Hproj2]. assert (Hsum1: is_series (countable_sum (ival.val Ic)) 1%R). { replace 1%R with R1 by auto. eapply (eq_ival_series _ _) in Hproj1; last eapply val_sum1. unshelve (eapply (countable_series_rearrange_covering_match _ _); last eassumption). { intros ic. rewrite //=. exists (existT (sval ic) tt). { abstract (rewrite Rmult_1_r => //=; destruct ic => //=). } } - apply val_nonneg. - apply val_nonneg. - intros (n1&?) (n2&?) Heq. apply sval_inj_pred => //=. inversion Heq. auto. - intros ((n1&[])&Hpf) => //=. unshelve (eexists). { exists n1. rewrite //= Rmult_1_r // in Hpf. } apply sval_inj_pred => //=. - intros (n1&Hpf) => //=. nra. } exists {| ivd_ival := Ic; val_sum1 := Hsum1 |}; auto. Qed. Local Open Scope R_scope. Record ival_coupling_nondepP {A1 A2} (Is1: ival A1) (Is2: ival A2) (P: A1 → A2 → Prop) : Type := mkNonDepICoupling { ic_nondep_witness :> ival (A1 * A2); ic_nondep_support : ∀ xy, (∃ i, ind ic_nondep_witness i = xy ∧ val ic_nondep_witness i > 0) → P (fst xy) (snd xy); ic_nondep_proj1: eq_ival Is1 (x ← ic_nondep_witness; mret (fst x)); ic_nondep_proj2: eq_ival Is2 (x ← ic_nondep_witness; mret (snd x)); }. Lemma ival_coupling_nondep_suffice {A1 A2} Is1 Is2 (P: A1 → A2 → Prop): ival_coupling_nondepP Is1 Is2 P → ival_couplingP Is1 Is2 P. Proof. intros [Ic Isupp Hp1 Hp2]. exists (ival_equip Ic _ Isupp). - setoid_rewrite Hp1. setoid_rewrite (ival_bind_P Ic). eapply ival_bind_congr; first reflexivity. intros (a1&a2) => //=; reflexivity. - setoid_rewrite Hp2. setoid_rewrite (ival_bind_P Ic). eapply ival_bind_congr; first reflexivity. intros (a1&a2) => //=; reflexivity. Qed. Lemma ival_coupling_refl {A} (I: ival A) : ival_couplingP I I (λ x y, x = y). Proof. unshelve (eexists). { refine (x ← I; mret (exist _ (x, x) _)). done. } - setoid_rewrite ival_bind_mret_mret. setoid_rewrite ival_right_id. reflexivity. - setoid_rewrite ival_bind_mret_mret. setoid_rewrite ival_right_id. reflexivity. Qed. Lemma ival_coupling_sym {A1 A2} (Is1: ival A1) (Is2: ival A2) P (Ic: ival_couplingP Is1 Is2 P): ival_couplingP Is2 Is1 (λ x y, P y x). Proof. destruct Ic as [Ic Hp1 Hp2]. unshelve (eexists). { refine (mbind _ Ic). intros ((x&y)&HP). refine (mret (exist _ (y, x) _)); auto. } * setoid_rewrite Hp2. setoid_rewrite ival_assoc. apply ival_bind_congr; first by reflexivity. intros ((x&y)&Hpf). setoid_rewrite ival_left_id => //=. reflexivity. * setoid_rewrite Hp1. setoid_rewrite ival_assoc; apply ival_bind_congr; first by reflexivity. intros ((x&y)&Hpf). setoid_rewrite ival_left_id => //=. reflexivity. Qed. Lemma ival_coupling_eq {A} (Is1 Is2: ival A) (Ic: ival_couplingP Is1 Is2 (λ x y, x = y)): eq_ival Is1 Is2. Proof. destruct Ic as [Ic Hp1 Hp2]. setoid_rewrite Hp1. setoid_rewrite Hp2. apply ival_bind_congr; first by reflexivity. intros ((x&y)&Heq) => //=. rewrite //= in Heq; subst; reflexivity. Qed. Lemma ival_coupling_bind {A1 A2 B1 B2} (f1: A1 → ival B1) (f2: A2 → ival B2) Is1 Is2 P Q (Ic: ival_couplingP Is1 Is2 P): (∀ x y, P x y → ival_couplingP (f1 x) (f2 y) Q) → ival_couplingP (mbind f1 Is1) (mbind f2 Is2) Q. Proof. intros Hfc. destruct Ic as [Ic Hp1 Hp2]. unshelve (eexists). { refine (xy ← Ic; _). destruct xy as ((x&y)&HP). exact (Hfc _ _ HP). } - setoid_rewrite Hp1; setoid_rewrite ival_assoc; apply ival_bind_congr; first by reflexivity. intros ((x&y)&HP). setoid_rewrite ival_left_id => //=. destruct (Hfc x y); auto. - setoid_rewrite Hp2; setoid_rewrite ival_assoc; apply ival_bind_congr; first by reflexivity. intros ((x&y)&HP). setoid_rewrite ival_left_id => //=. destruct (Hfc x y); auto. Qed. Lemma ival_coupling_mret {A1 A2} x y (P: A1 → A2 → Prop): P x y → ival_couplingP (mret x) (mret y) P. Proof. intros HP. exists (mret (exist _ (x, y) HP)); setoid_rewrite ival_left_id => //=; reflexivity. Qed. Lemma ival_coupling_conseq {A1 A2} (P1 P2: A1 → A2 → Prop) (I1: ival A1) (I2: ival A2): (∀ x y, P1 x y → P2 x y) → ival_couplingP I1 I2 P1 → ival_couplingP I1 I2 P2. Proof. intros HP [Ic Hp1 Hp2]. unshelve (eexists). { refine (x ← Ic; mret _). destruct x as (x&P). exists x. auto. } - setoid_rewrite Hp1. setoid_rewrite ival_assoc. eapply ival_bind_congr; first reflexivity; intros (?&?). setoid_rewrite ival_left_id; reflexivity. - setoid_rewrite Hp2. setoid_rewrite ival_assoc. eapply ival_bind_congr; first reflexivity; intros (?&?). setoid_rewrite ival_left_id; reflexivity. Qed. Lemma ival_coupling_plus' {A1 A2} p (P : A1 → A2 → Prop) (I1 I1': ival A1) (I2 I2': ival A2) : ival_couplingP I1 I2 P → ival_couplingP I1' I2' P → ival_couplingP (iplus (iscale p I1) (iscale (1 - p) I1')) (iplus (iscale p I2) (iscale (1 - p) I2')) P. Proof. intros [Ic Hp1 Hp2] [Ic' Hp1' Hp2']. exists (ival.iplus (ival.iscale p Ic) (ival.iscale (1 - p) Ic')). - setoid_rewrite ival.ival_plus_bind. setoid_rewrite ival.ival_scale_bind. setoid_rewrite Hp1. setoid_rewrite Hp1'. reflexivity. - setoid_rewrite ival.ival_plus_bind. setoid_rewrite ival.ival_scale_bind. setoid_rewrite Hp2. setoid_rewrite Hp2'. reflexivity. Qed. Lemma ival_coupling_plus {A1 A2} p Hpf Hpf' (P : A1 → A2 → Prop) (I1 I1': ivdist A1) (I2 I2': ivdist A2) : ival_couplingP I1 I2 P → ival_couplingP I1' I2' P → ival_couplingP (ivdplus p Hpf I1 I1') (ivdplus p Hpf' I2 I2') P. Proof. rewrite //=. apply ival_coupling_plus'. Qed. Lemma ival_coupling_idxOf {A1 A2} I1 I2 (P: A1 → A2 → Prop): ival_couplingP I1 I2 P → { Q : {Q: idx I1 → idx I2 → Prop | (∀ i1 i1' i2, Q i1 i2 → Q i1' i2 → i1 = i1')} & ival_couplingP (idxOf I1) (idxOf I2) (λ i1 i2, P (ind I1 i1) (ind I2 i2) ∧ val I1 i1 > 0 ∧ val I2 i2 > 0 ∧ (sval Q) i1 i2 )}. Proof. intros [Ic Hp1 Hp2]. symmetry in Hp1. symmetry in Hp2. apply ClassicalEpsilon.constructive_indefinite_description in Hp1. destruct Hp1 as (h1&Hp1). apply ClassicalEpsilon.constructive_indefinite_description in Hp1. destruct Hp1 as (h1'&Hp1). apply ClassicalEpsilon.constructive_indefinite_description in Hp2. destruct Hp2 as (h2&Hp2). apply ClassicalEpsilon.constructive_indefinite_description in Hp2. destruct Hp2 as (h2'&Hp2). assert (Hgt_coerce: ∀ xy : support (val Ic), Rgt_dec (val Ic (projT1 (@existT _ (λ _, unit) (sval xy) tt)) * 1) 0). { abstract (intros (?&?); rewrite Rmult_1_r => //=; destruct Rgt_dec; auto). } unshelve (eexists). exists (λ i1 i2, ∃ ic1 ic2, sval (h1 ic1) = i1 ∧ sval (h2 ic2) = i2 ∧ sval ic1 = sval ic2). { abstract (intros i1 i1' i2 (ic1&ic2&Heq1&Heq2&Hcoh) (ic1'&ic2'&Heq1'&Heq2'&Hcoh'); assert (ic2' = ic2); first ( abstract (destruct Hp2 as (Hbij2&?); rewrite -(Hbij2 ic2'); rewrite -(Hbij2 ic2); f_equal; apply sval_inj_pred; congruence)); abstract (subst; do 2 f_equal; apply sval_inj_pred; auto; congruence)). } unshelve (eexists). - refine (xy ← supp_idxOf Ic; mret _). unshelve (refine (exist _ ((sval (h1 _)), sval (h2 _)) _)). * exact (exist _ (existT (sval xy) tt) (Hgt_coerce xy)). * exact (exist _ (existT (sval xy) tt) (Hgt_coerce xy)). * abstract( split; [ by (abstract (rewrite //=; destruct Hp1 as (?&?&->&?) => //=; destruct Hp2 as (?&?&->&?) => //=; destruct (ind Ic (sval xy)) => //=)) |]; split; [ by (abstract (rewrite //=; try destruct (h1 _); try destruct (h2 _); rewrite //=; destruct Rgt_dec => //=)) |]; split; [ by (abstract (rewrite //=; try destruct (h1 _); try destruct (h2 _); rewrite //=; destruct Rgt_dec => //=)) |]; abstract ( rewrite //=; exists ((exist _ (existT (sval xy) tt) (Hgt_coerce xy))); exists ((exist _ (existT (sval xy) tt) (Hgt_coerce xy))); done) ). - setoid_rewrite ival_bind_mret_mret. symmetry. unshelve (eexists). { simpl. intros ((ic&?)&Hgt). simpl in h1. rewrite Rmult_1_r in Hgt. destruct ic as (ic&Hgtc). apply h1. exists (existT ic tt). simpl in *. rewrite Rmult_1_r. done. } unshelve (eexists). { simpl. intros ix. destruct (h1' ix) as ((i1&?)&Hgt). simpl in Hgt. unshelve (eexists). { unshelve (refine (existT _ tt)). exists i1. rewrite Rmult_1_r in Hgt. done. } rewrite //=. } rewrite //=. repeat split. * intros (((a&Hgt)&[])&?). destruct Hp1 as (Hinv1&Hinv1'&?). rewrite //=. destruct (Rmult_1_r _). rewrite /eq_rect_r //=. rewrite Hinv1 => //=. apply sval_inj_pred => //=. f_equal. apply sval_inj_pred => //=. * rewrite //= => a. destruct Hp1 as (Hinv1&Hinv1'&?). specialize (Hinv1' a). destruct (h1' a) as ((?&[])&?). rewrite //=. rewrite -Hinv1'. destruct (Rmult_1_r (val Ic x)) => //=. * rewrite //=. intros (((a&Hgt)&[])&?). destruct Hp1 as (Hinv1&Hinv1'&?). rewrite //=. destruct (Rmult_1_r _). rewrite /eq_rect_r //=. f_equal. f_equal. apply sval_inj_pred => //=. * rewrite //=. intros (((a&Hgt)&[])&?). destruct Hp1 as (Hinv1&Hinv1'&?&Hval). rewrite //=. destruct (Rmult_1_r _). rewrite /eq_rect_r //=. rewrite Hval //= !Rmult_1_r //. - setoid_rewrite ival_bind_mret_mret. symmetry. unshelve (eexists). { simpl. intros ((ic&?)&Hgt). simpl in h1. rewrite Rmult_1_r in Hgt. destruct ic as (ic&Hgtc). apply h2. exists (existT ic tt). simpl in *. rewrite Rmult_1_r. done. } unshelve (eexists). { simpl. intros ix. destruct (h2' ix) as ((i1&?)&Hgt). simpl in Hgt. unshelve (eexists). { unshelve (refine (existT _ tt)). exists i1. rewrite Rmult_1_r in Hgt. done. } rewrite //=. } rewrite //=. repeat split. * rewrite //=. intros (((a&Hgt)&[])&?). destruct Hp2 as (Hinv1&Hinv1'&?). rewrite //=. destruct (Rmult_1_r _). rewrite /eq_rect_r //=. rewrite Hinv1 => //=. apply sval_inj_pred => //=. f_equal. apply sval_inj_pred => //=. * rewrite //= => a. destruct Hp2 as (Hinv1&Hinv1'&?). specialize (Hinv1' a). destruct (h2' a) as ((?&[])&?). rewrite //=. rewrite -Hinv1'. destruct (Rmult_1_r (val Ic x)) => //=. * rewrite //=. intros (((a&Hgt)&[])&?). destruct Hp1 as (Hinv1&Hinv1'&?). rewrite //=. destruct (Rmult_1_r _). rewrite /eq_rect_r //=. f_equal. f_equal. apply sval_inj_pred => //=. * rewrite //=. intros (((a&Hgt)&[])&?). destruct Hp2 as (Hinv1&Hinv1'&?&Hval). rewrite //=. destruct (Rmult_1_r _). rewrite /eq_rect_r //=. rewrite Hval //= !Rmult_1_r //. Qed. Lemma ival_coupling_equip {X} I1 (P: X → Prop) Hpf: ival_couplingP I1 (ival_equip I1 P Hpf) (λ x y, x = (sval y)). Proof. unshelve eexists. refine ((x ← ival_equip I1 P Hpf; mret (exist _ (sval x, x) _))); auto. - setoid_rewrite ival_bind_mret_mret. rewrite /sval. etransitivity; first (symmetry; apply ival_right_id). apply ival_bind_P. - setoid_rewrite ival_bind_mret_mret. rewrite /sval. etransitivity; first (symmetry; apply ival_right_id). eapply ival_bind_congr; first reflexivity. intros (?&?) => //=. reflexivity. Qed. Lemma ival_idist_wit_sum1 {X Y} (I1 : ivdist X) (I2: ivdist Y) (P: X → Y → Prop) Hwit: eq_ival I1 (Hwit ≫= (λ x : {xy : X * Y | P xy.1 xy.2}, mret (sval x).1)) → is_series (countable_sum (val Hwit)) 1. Proof. intros Hproj1. eapply eq_ival_series in Hproj1; last apply (val_sum1). rewrite //= in Hproj1. setoid_rewrite Rmult_1_r in Hproj1. unshelve (eapply countable_series_rearrange_covering_match; last eapply Hproj1). { intros x. exists (existT (proj1_sig x) tt). exact (proj2_sig x). } { intros x; apply val_nonneg. } { intros x; apply val_nonneg. } { rewrite //=. intros (?&?) (?&?). inversion 1; subst. apply sval_inj_pi => //=. } { intros ((n&[])&Hpf). exists (exist _ n Hpf). apply sval_inj_pi => //=. } { intros (n&Hpf) => //=. } Qed. Lemma ival_idist_couplingP {X Y} (I1 : ivdist X) (I2: ivdist Y) (P: X → Y → Prop): ival_couplingP I1 I2 P → idist_couplingP I1 I2 P. Proof. intros [Hwit Hproj1 Hproj2]. unshelve (econstructor). { exists Hwit. eapply ival_idist_wit_sum1; eauto. } - rewrite /eq_ivd //=. - rewrite /eq_ivd //=. Qed. Lemma ival_coupling_support {X Y} I1 I2 (P: X → Y → Prop) (Ic: ival_couplingP I1 I2 P) : ival_couplingP I1 I2 (λ x y, ∃ Hpf: P x y, In_isupport x I1 ∧ In_isupport y I2 ∧ In_isupport (exist _ (x, y) Hpf) Ic). Proof. destruct Ic as [Ic Hp1 Hp2]. cut (ival_couplingP I1 I2 (λ x y, ∃ (Hpf: P x y), In_isupport (exist _ (x, y) Hpf) Ic)). { intros. eapply ival_coupling_conseq; last eauto. intros x y (Hpf&Hin). destruct Hin as (ic&Hind&Hval). exists Hpf. repeat split; auto. - rewrite //=. symmetry in Hp1. destruct Hp1 as (h1&?&?&?&Hind1&Hval1). unshelve (eexists). { refine (sval (h1 _ )). exists (existT ic tt). rewrite //= Rmult_1_r. destruct Rgt_dec => //=. } split; rewrite //=. * rewrite Hind1 //= Hind //=. * rewrite Hval1 //= Rmult_1_r //. - rewrite //=. symmetry in Hp2. destruct Hp2 as (h1&?&?&?&Hind1&Hval1). unshelve eexists. { refine (sval (h1 _)). exists (existT ic tt). rewrite //= Rmult_1_r. destruct Rgt_dec => //=. } split; rewrite //=. * rewrite Hind1 //= Hind //=. * rewrite Hval1 //= Rmult_1_r //. - rewrite //=. exists ic; split => //=. } unshelve (eexists). refine (z ← ival_equip Ic (λ xy, In_isupport xy Ic) _; mret _). { destruct z as ((xy&HP)&Hin). exists xy. abstract (exists HP; destruct xy; eauto). } { auto. } - setoid_rewrite Hp1. setoid_rewrite ival_bind_mret_mret. eapply ival_coupling_eq. eapply ival_coupling_bind; first eapply ival_coupling_equip. intros (xy&HP) ((xy'&HP')&Hin). rewrite //=. inversion 1; subst; auto. apply ival_coupling_refl. - setoid_rewrite Hp2. setoid_rewrite ival_bind_mret_mret. eapply ival_coupling_eq. eapply ival_coupling_bind; first eapply ival_coupling_equip. intros (xy&HP) ((xy'&HP')&Hin). rewrite //=. inversion 1; subst; auto. apply ival_coupling_refl. Qed. Lemma ival_coupling_support_wit {X Y} (I1: ivdist X) (I2: ivdist Y) (P: X → Y → Prop) (Ic: ival_couplingP I1 I2 P): { xy : X * Y | ∃ Hpf : P (fst xy) (snd xy), In_isupport (fst xy) I1 ∧ In_isupport (snd xy) I2 ∧ In_isupport (exist _ xy Hpf) Ic}. Proof. specialize (ival_coupling_support I1 I2 P Ic) => Ic'. specialize (ival_idist_couplingP I1 I2 _ Ic') => Ic''. destruct Ic'' as [Ic'' ? ?]. destruct (ivd_support_idx Ic'') as (i&?). destruct (ind Ic'' i) as ((x&y)&?); eauto. Qed. Lemma ival_coupling_proper {X Y} I1 I1' I2 I2' (P: X → Y → Prop) : eq_ival I1 I1' → eq_ival I2 I2' → ival_couplingP I1 I2 P → ival_couplingP I1' I2' P. Proof. intros Heq1 Heq2 [Ic Hp1 Hp2]. exists Ic; etransitivity; eauto; by symmetry. Qed.
-- BearSSL's "adding holes" algorithm for XOR multiplication -- Based on BearSSL ghash_ctmul64.c module Crypto.Hash.GHash import Utils.Bytes import Data.Bits import Data.List import Data.Vect import Data.DPair import Data.Fin import Data.Fin.Extra import Data.Nat import Data.Nat.Order.Properties import Utils.Misc import Crypto.Hash HValues : Type HValues = (Bits64, Bits64, Bits64, Bits64, Bits64, Bits64) -- Carryless multiplication with "holes" bmul : Bits64 -> Bits64 -> Bits64 bmul x y = let x0 = x .&. 0x1111111111111111 x1 = x .&. 0x2222222222222222 x2 = x .&. 0x4444444444444444 x3 = x .&. 0x8888888888888888 y0 = y .&. 0x1111111111111111 y1 = y .&. 0x2222222222222222 y2 = y .&. 0x4444444444444444 y3 = y .&. 0x8888888888888888 z0 = (x0 * y0) `xor` (x1 * y3) `xor` (x2 * y2) `xor` (x3 * y1) z1 = (x0 * y1) `xor` (x1 * y0) `xor` (x2 * y3) `xor` (x3 * y2) z2 = (x0 * y2) `xor` (x1 * y1) `xor` (x2 * y0) `xor` (x3 * y3) z3 = (x0 * y3) `xor` (x1 * y2) `xor` (x2 * y1) `xor` (x3 * y0) in (z0 .&. 0x1111111111111111) .|. (z1 .&. 0x2222222222222222) .|. (z2 .&. 0x4444444444444444) .|. (z3 .&. 0x8888888888888888) rms : Bits64 -> Index {a=Bits64} -> Bits64 -> Bits64 rms m s x = (shiftL (x .&. m) s) .|. ((shiftR x s) .&. m) rev64 : Bits64 -> Bits64 rev64 x = let x' = (rms 0x0000FFFF0000FFFF 16) $ (rms 0x00FF00FF00FF00FF 8 ) $ (rms 0x0F0F0F0F0F0F0F0F 4 ) $ (rms 0x3333333333333333 2 ) $ (rms 0x5555555555555555 1 ) x in (shiftL x' 32) .|. (shiftR x' 32) gmult_core : Bits64 -> Bits64 -> HValues -> (Bits64, Bits64) gmult_core y1 y0 (h0, h0r, h1, h1r, h2, h2r) = let y1r = rev64 y1 y0r = rev64 y0 y2 = xor y0 y1 y2r = xor y0r y1r -- Karatsuba decomposition -- Here we decompose the 128 bit multiplication into -- 3 64-bits multiplication -- The h-suffixed variables are just multiplication for -- reversed bits, which is necessary because we want the -- high bits z0 = bmul y0 h0 z1 = bmul y1 h1 z2 = bmul y2 h2 z0h = bmul y0r h0r z1h = bmul y1r h1r z2h = bmul y2r h2r z2 = xor (xor z0 z1) z2 z2h = xor (xor z0h z1h) z2h z0h = shiftR (rev64 z0h) 1 z1h = shiftR (rev64 z1h) 1 z2h = shiftR (rev64 z2h) 1 -- Since the operation is done in big-endian, but GHASH spec -- needs small endian, we flip the bits v0 = z0 v1 = xor z0h z2 v2 = xor z1 z2h v3 = z1h v3 = (shiftL v3 1) .|. (shiftR v2 63) v2 = (shiftL v2 1) .|. (shiftR v1 63) v1 = (shiftL v1 1) .|. (shiftR v0 63) v0 = (shiftL v0 1) -- Modular reduction to GF[128] v2 = v2 `xor` v0 `xor` (shiftR v0 1) `xor` (shiftR v0 2) `xor` (shiftR v0 7) v1 = v1 `xor` (shiftL v0 63) `xor` (shiftL v0 62) `xor` (shiftL v0 57) v3 = v3 `xor` v1 `xor` (shiftR v1 1) `xor` (shiftR v1 2) `xor` (shiftR v1 7) v2 = v2 `xor` (shiftL v1 63) `xor` (shiftL v1 62) `xor` (shiftL v1 57) in (v3, v2) gcm_mult : HValues -> Vect 16 Bits8 -> Vect 16 Bits8 gcm_mult h y = let y1 = from_be $ take 8 y y0 = from_be $ drop 8 y (y1', y0') = gmult_core y1 y0 h in to_be {n=8} y1' ++ to_be y0' mk_h_values : Vect 16 Bits8 -> HValues mk_h_values h = let h1 = from_be $ take 8 h h0 = from_be $ drop 8 h h0r = rev64 h0 h1r = rev64 h1 h2 = xor h0 h1 h2r = xor h0r h1r in (h0, h0r, h1, h1r, h2, h2r) export data GHash : Type where MkGHash : List Bits8 -> HValues -> Vect 16 Bits8 -> GHash hash_until_done : GHash -> GHash hash_until_done ghash@(MkGHash buffer hval state) = case splitAtExact 16 buffer of Just (a, b) => hash_until_done $ MkGHash b hval (gcm_mult hval (zipWith xor a state)) Nothing => ghash export Digest GHash where digest_nbyte = 16 update message (MkGHash buffer hval state) = hash_until_done (MkGHash (buffer <+> message) hval state) finalize (MkGHash buffer hval state) = let (MkGHash _ _ state) = hash_until_done (MkGHash (pad_zero 16 buffer) hval state) in state export MAC (Vect 16 Bits8) GHash where initialize_mac key = MkGHash [] (mk_h_values key) (replicate _ 0)
The set $X$ is in the $\sigma$-algebra generated by the image of $f$.
Require Import Lang.Syntax Lang.Bindings FinFun. Set Implicit Arguments. Implicit Types EV HV V L : Set. Section section_L_bind_inj. Local Fact disjoint_same_inv A (x : A) : disjoint \{x} \{x} → False. Proof. unfold disjoint ; rewrite inter_same ; intro H. erewrite <- in_empty. rewrite <- H. rewrite in_singleton ; reflexivity. Qed. Lemma L_bind_lid_inj L L' (f : L → lid L') (Inj : Injective f) (i1 i2 : lid L) (Q1 : ∀ α, disjoint (Xs_lid (f α)) (Xs_lid i1)) (Q2 : ∀ α, disjoint (Xs_lid (f α)) (Xs_lid i2)) (H : L_bind_lid f i1 = L_bind_lid f i2) : i1 = i2. Proof. destruct i1 as [ α1 | X1 ], i2 as [ α2 | X2 ] ; simpl in *. + specialize (Inj α1 α2 H) ; congruence. + exfalso. specialize (Q2 α1) ; rewrite H in Q2 ; simpl in Q2. apply disjoint_same_inv in Q2 ; auto. + exfalso. specialize (Q1 α2) ; rewrite <- H in Q1 ; simpl in Q1. apply disjoint_same_inv in Q1 ; auto. + crush. Qed. Lemma L_bind_lbl_inj HV L L' (f : L → lid L') (Inj : Injective f) (l1 l2 : lbl HV L) (Q1 : ∀ α, disjoint (Xs_lid (f α)) (Xs_lbl l1)) (Q2 : ∀ α, disjoint (Xs_lid (f α)) (Xs_lbl l2)) (H : L_bind_lbl f l1 = L_bind_lbl f l2) : l1 = l2. Proof. destruct l1, l2 ; simpl in * ; try inversion H ; clear H ; repeat match goal with | [ H : L_bind_lid ?f _ = L_bind_lid ?f _ |- _ ] => apply L_bind_lid_inj in H ; subst ; clear H end ; crush. Qed. Lemma L_bind_ef_inj EV HV L L' (f : L → lid L') (Inj : Injective f) (ε1 ε2 : ef EV HV L) (Q1 : ∀ α, disjoint (Xs_lid (f α)) (Xs_ef ε1)) (Q2 : ∀ α, disjoint (Xs_lid (f α)) (Xs_ef ε2)) (H : L_bind_ef f ε1 = L_bind_ef f ε2) : ε1 = ε2. Proof. destruct ε1, ε2 ; simpl in * ; try inversion H ; clear H ; repeat match goal with | [ H : L_bind_lbl ?f _ = L_bind_lbl ?f _ |- _ ] => apply L_bind_lbl_inj in H ; subst ; clear H end ; crush. Qed. End section_L_bind_inj. Lemma lbl_EV_bind_hd EV EV' HV V L (f : EV → eff EV' HV L) (h : hd EV HV V L) : lbl_hd (EV_bind_hd f h) = lbl_hd h. Proof. induction h ; crush. Qed. Lemma lbl_L_bind_hd EV HV V L L' (f : L → lid L') (h : hd EV HV V L) : lbl_hd (L_bind_hd f h) = L_bind_lbl f (lbl_hd h). Proof. induction h ; crush. Qed. Lemma lbl_V_bind_hd EV HV V V' L (f : V → val EV HV V' L) (h : hd EV HV V L) : lbl_hd (V_bind_hd f h) = lbl_hd h. Proof. induction h ; crush. Qed. Lemma lbl_HV_bind_hd EV EV' HV HV' V V' L (f : HV → hd EV HV' V L) (g : HV → hd EV' HV' V' L) (Q : ∀ p, lbl_hd (f p) = lbl_hd (g p)) (h : hd EV' HV V' L) : lbl_hd (HV_bind_hd g h) = HV_bind_lbl f (lbl_hd h). Proof. induction h ; crush. Qed. Lemma EV_bind_XEnv_empty EV EV' HV (f : EV → eff EV' HV ∅) : EV_bind_XEnv f empty = empty. Proof. apply map_empty. Qed. Lemma EV_bind_XEnv_single EV EV' HV (f : EV → eff EV' HV ∅) X (T : ty EV HV ∅) (𝓔 : eff EV HV ∅) : EV_bind_XEnv f (X ~ (T, 𝓔)) = X ~ (EV_bind_ty f T, EV_bind_eff f 𝓔). Proof. apply map_single. Qed. Lemma EV_bind_XEnv_concat EV EV' HV (f : EV → eff EV' HV ∅) (Ξ Ξ' : XEnv EV HV) : EV_bind_XEnv f (Ξ & Ξ') = (EV_bind_XEnv f Ξ) & (EV_bind_XEnv f Ξ'). Proof. apply map_concat. Qed. Lemma EV_bind_XEnv_dom EV EV' HV (f : EV → eff EV' HV ∅) (Ξ : XEnv EV HV) : dom (EV_bind_XEnv f Ξ) = dom Ξ. Proof. induction Ξ as [ | ? ? [? ?] IHΞ ] using env_ind. + rewrite EV_bind_XEnv_empty. repeat rewrite dom_empty. reflexivity. + rewrite EV_bind_XEnv_concat, EV_bind_XEnv_single. repeat rewrite dom_concat, dom_single. rewrite IHΞ. reflexivity. Qed. Lemma HV_bind_XEnv_empty EV HV HV' V (f : HV → hd EV HV' V ∅) : HV_bind_XEnv f (empty : XEnv EV HV) = empty. Proof. apply map_empty. Qed. Lemma HV_bind_XEnv_single EV HV HV' V (f : HV → hd EV HV' V ∅) X (T : ty EV HV ∅) (𝓔 : eff EV HV ∅) : HV_bind_XEnv f (X ~ (T, 𝓔)) = X ~ (HV_bind_ty f T, HV_bind_eff f 𝓔). Proof. apply map_single. Qed. Lemma HV_bind_XEnv_concat EV HV HV' V (f : HV → hd EV HV' V ∅) (Ξ Ξ' : XEnv EV HV) : HV_bind_XEnv f (Ξ & Ξ') = (HV_bind_XEnv f Ξ) & (HV_bind_XEnv f Ξ'). Proof. apply map_concat. Qed. Lemma HV_bind_XEnv_dom EV HV HV' V (f : HV → hd EV HV' V ∅) (Ξ : XEnv EV HV) : dom (HV_bind_XEnv f Ξ) = dom Ξ. Proof. induction Ξ as [ | ? ? [? ?] IHΞ ] using env_ind. + rewrite HV_bind_XEnv_empty. repeat rewrite dom_empty. reflexivity. + rewrite HV_bind_XEnv_concat, HV_bind_XEnv_single. repeat rewrite dom_concat, dom_single. rewrite IHΞ. reflexivity. Qed. Section section_binds_EV_bind. Context (EV EV' HV : Set). Context (f : EV → eff EV' HV ∅). Context (X : var). Lemma binds_EV_bind T 𝓔 (Ξ : XEnv EV HV) : binds X (T, 𝓔) Ξ → binds X (EV_bind_ty f T, EV_bind_eff f 𝓔) (EV_bind_XEnv f Ξ). Proof. intro Hbinds. induction Ξ as [ | Ξ' X' [ T' 𝓔' ] IHΞ' ] using env_ind. + apply binds_empty_inv in Hbinds ; crush. + apply binds_concat_inv in Hbinds. rewrite EV_bind_XEnv_concat, EV_bind_XEnv_single. destruct Hbinds as [ Hbinds | Hbinds ]. - apply binds_single_inv in Hbinds ; crush. - destruct Hbinds as [ FrX Hbinds ] ; auto. Qed. Lemma binds_EV_bind_inv (T' : ty EV' HV ∅) (𝓔' : eff EV' HV ∅) (Ξ : XEnv EV HV) : binds X (T', 𝓔') (EV_bind_XEnv f Ξ) → ∃ T 𝓔, T' = EV_bind_ty f T ∧ 𝓔' = EV_bind_eff f 𝓔 ∧ binds X (T, 𝓔) Ξ. Proof. intro Hbinds'. induction Ξ as [ | Ξ Y [ T 𝓔 ] IHΞ ] using env_ind. + rewrite EV_bind_XEnv_empty in Hbinds'. apply binds_empty_inv in Hbinds' ; crush. + rewrite EV_bind_XEnv_concat, EV_bind_XEnv_single in Hbinds'. apply binds_concat_inv in Hbinds'. destruct Hbinds' as [ Hbinds' | Hbinds' ]. - apply binds_single_inv in Hbinds'. destruct Hbinds' as [ [] Heq ]. inversion Heq ; subst. eauto. - destruct Hbinds' as [ FrX Hbinds' ]. specialize (IHΞ Hbinds'). destruct IHΞ as [T'' [𝓔'' [? [? ?]]]]. repeat eexists ; eauto. Qed. End section_binds_EV_bind. Section section_binds_HV_bind. Context (EV HV HV' V : Set). Context (f : HV → hd EV HV' V ∅). Context (X : var). Lemma binds_HV_bind T 𝓔 (Ξ : XEnv EV HV) : binds X (T, 𝓔) Ξ → binds X (HV_bind_ty f T, HV_bind_eff f 𝓔) (HV_bind_XEnv f Ξ). Proof. intro Hbinds. induction Ξ as [ | Ξ' X' [ T' 𝓔' ] IHΞ' ] using env_ind. + apply binds_empty_inv in Hbinds ; crush. + apply binds_concat_inv in Hbinds. rewrite HV_bind_XEnv_concat, HV_bind_XEnv_single. destruct Hbinds as [ Hbinds | Hbinds ]. - apply binds_single_inv in Hbinds ; crush. - destruct Hbinds as [ FrX Hbinds ] ; auto. Qed. Lemma binds_HV_bind_inv (T' : ty EV HV' ∅) (𝓔' : eff EV HV' ∅) (Ξ : XEnv EV HV) : binds X (T', 𝓔') (HV_bind_XEnv f Ξ) → ∃ T 𝓔, T' = HV_bind_ty f T ∧ 𝓔' = HV_bind_eff f 𝓔 ∧ binds X (T, 𝓔) Ξ. Proof. intro Hbinds'. induction Ξ as [ | Ξ Y [ T 𝓔 ] IHΞ ] using env_ind. + rewrite HV_bind_XEnv_empty in Hbinds'. apply binds_empty_inv in Hbinds' ; crush. + rewrite HV_bind_XEnv_concat, HV_bind_XEnv_single in Hbinds'. apply binds_concat_inv in Hbinds'. destruct Hbinds' as [ Hbinds' | Hbinds' ]. - apply binds_single_inv in Hbinds'. destruct Hbinds' as [ [] Heq ]. inversion Heq ; subst. eauto. - destruct Hbinds' as [ FrX Hbinds' ]. specialize (IHΞ Hbinds'). destruct IHΞ as [T'' [𝓔'' [? [? ?]]]]. repeat eexists ; eauto. Qed. End section_binds_HV_bind.
lemma GPicard4: assumes "0 < k" and holf: "f holomorphic_on (ball 0 k - {0})" and AE: "\<And>e. \<lbrakk>0 < e; e < k\<rbrakk> \<Longrightarrow> \<exists>d. 0 < d \<and> d < e \<and> (\<forall>z \<in> sphere 0 d. norm(f z) \<le> B)" obtains \<epsilon> where "0 < \<epsilon>" "\<epsilon> < k" "\<And>z. z \<in> ball 0 \<epsilon> - {0} \<Longrightarrow> norm(f z) \<le> B"
Are you planning to visit Easter Island,(ipc) from Detroit (DTW)? Are you looking for a website on the web where you can find the cheap flights? If yes, there is no need to get worried. Flightsbird can help you in finding the information on the various airlines out there on the web and We provide you direct flights to Easter Island,(ipc). It is really important to choose the right airline in order to have convenient airlines. It is better to find out more about the offers, which comprises the reliability of their booking service. If feasible, you should try to make a note of the safety of your selected airline. So, if you are prepared to make out the most standard booking services on the web for flights from Detroit (DTW) to Easter Island,(ipc), and we are here to provide the right help. No matter, it’s for a responsibility for the sake of your reason; sometimes you require getting away. Possibly, you require flights from Detroit to Easter Island,(ipc) to attend your cousin’s wedding, to ground a business thought to your boss, or possibly just to take care of yourself to a mini holiday. Despite the reasons at the packing your bags and needing to discover the cheapest flights from Detroit (DTW) to Easter Island,(ipc), the friendly services are available for you. The website presents you with some of the best deals on airfare so end that Google flights search. The expert wishes you to spend less on your journey from Detroit (DTW) to Easter Island,(ipc), so you can spend more during your depart. One will discover it easy to land airline tickets with itineraries identical to your travel plan. What’s more, the team offers you with all the information you need to confidently to make reservations on your business, family, or personal trip. Where to purchase Cheap Flights from Detroit (DTW) to Easter Island,(ipc)? The finest approach to discover a great deal on airfare is to hunt multiple sites. One way flights or even Round trip flights, it is better to search here, we hunt for multiple sites and fare sources all at once so you don't have to - which is why the expert website is the best place to discover cheap tickets. Airlines can regulate costs for tickets from Detroit to Easter Island,(ipc) depend on the day and time that you choose to book your flight. The team of expert collects information from different airlines and has found that Tuesdays, Wednesdays, and Saturdays are often the finest days to book flights.
# saturated addition for positive numbers function addsaturated(a::T,b::T) where {T} r = a+b r<a || r<b ? typemax(T) : r # check for overflow end addsaturated(a::T,b::T) where {T<:AbstractFloat} = a+b # Inf+a = Inf, so no overflow check is needed # Finds the shortest paths between all pairs of nodes in an directed graph, specified by a matrix of pairwise distances. # If there are no edges between two nodes, the distance should be typemax(T) (which is Inf for Float64). function floydwarshall!(D::AbstractMatrix{T}) where {T<:Real} @assert ndims(D)==2 @assert size(D,1)==size(D,2) @assert all(D.>=0) N = size(D,1) for k=1:N for j=1:N for i=1:N #D[j,i] = min(D[j,i], D[j,k]+D[k,i]) D[j,i] = min(D[j,i], addsaturated(D[j,k],D[k,i])) end end end # This is not needed since we assume the matrix has only positive entries # for i=1:N # @assert D[i,i]>=0 "The graph has negative cycles." # end D end floydwarshall(D::AbstractMatrix{T}) where {T<:Real} = floydwarshall!(copy(D))
```python import numpy as np import scipy as sp import sklearn as sk import matplotlib as mpl mpl.use('Agg') import matplotlib.pylab as plt from mpl_toolkits.mplot3d import Axes3D %matplotlib inline ``` /home/kang/anaconda3/lib/python3.6/site-packages/matplotlib/font_manager.py:279: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment. 'Matplotlib is building the font cache using fc-list. ' ```python def f(x) : return x**3 - 3*x**2 + x ``` ```python import numpy as np x = np.linspace(-1, 3, 9) ``` array([-1. , -0.5, 0. , 0.5, 1. , 1.5, 2. , 2.5, 3. ]) ```python y = f(x) ``` ```python plt.plot(x, y, 'ro') plt.xlim(-2, 4) plt.xticks(np.arange(-1, 4)) plt.yticks(np.arange(-5, 4)) plt.show() ``` ```python x = np.linspace(-1, 3, 400, 'ro-') y = f(x) plt.plot(x, y) plt.xlim(-2, 4) plt.xticks(np.arange(-1, 4)) plt.yticks(np.arange(-5, 4)) plt.show() ``` ```python def get_slope(x, dx) : function = x**3 - 3*x**2 + x new_function = (x + dx)**3 - 3*(x + dx)**2 + (x +dx) slope = (new_function - function)/ dx return slope ``` ```python get_slope(2, 0.000000000005) ``` 1.000000082740371 ```python get_slope(1.5, 0.000000000005) ``` -1.2501111257279263 ```python get_slope(-0.5, 0.00000000000005) ``` 4.75175454539567 ```python get_slope(2.5, 0.0000000000005) ``` 4.75175454539567 ```python np.e ``` 2.718281828459045 ```python def f(x, y) : return 2* x**2 + 6 * x * y + 7 * y ** 2 - 26 * x - 54 * y + 107 ``` ```python xx = np.linspace(-5, 5, 100) yy = np.linspace(-4, 4, 100) X , Y = np.meshgrid(xx, yy) Z = f(X, Y) ``` ```python from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() fig.gca(projection='3d').plot_surface(X, Y, Z) plt.xlabel('x') plt.ylabel('y') plt.title("Surface Plot") plt.show() ``` ```python CS = plt.contour(X, Y, Z, levels = np.arange(0, 300, 20)) plt.clabel(CS, fmt = "%d") plt.title("Contour Plot") plt.show() ``` $\frac{\partial f}{\partial x} = 2\,\sqrt{a}\,x$ ```python import sympy sympy.init_printing(use_latex = 'mathjax') ``` ```python x = sympy.symbols('x') x ``` $$x$$ ```python type(x) ``` sympy.core.symbol.Symbol ```python f = x * sympy.exp(x) f ``` $$x e^{x}$$ ```python sympy.diff(f) ``` $$x e^{x} + e^{x}$$ ```python sympy.simplify(sympy.diff(f)) ``` $$\left(x + 1\right) e^{x}$$ ```python x, y = sympy.symbols('x y') f = x ** 2 + x * y + y ** 2 f ``` $$x^{2} + x y + y^{2}$$ ```python sympy.diff(f, x) ``` $$2 x + y$$ ```python sympy.diff(f, y) ``` $$x + 2 y$$ ```python x, mu , sigma = sympy.symbols('x mu sigma') f = sympy.exp((x - mu) ** 2 / sigma ** 2) f ``` $$e^{\frac{1}{\sigma^{2}} \left(- \mu + x\right)^{2}}$$ ```python sympy.diff(f, x) ``` $$\frac{1}{\sigma^{2}} \left(- 2 \mu + 2 x\right) e^{\frac{1}{\sigma^{2}} \left(- \mu + x\right)^{2}}$$ ```python sympy.simplify(sympy.diff(f, x)) ``` $$\frac{2}{\sigma^{2}} \left(- \mu + x\right) e^{\frac{1}{\sigma^{2}} \left(\mu - x\right)^{2}}$$ ```python !pip install tangent ``` Collecting tangent Downloading tangent-0.1.9.tar.gz (80kB)  88% |████████████████████████████▎ | 71kB 677kB/s eta 0:00:01 100% |████████████████████████████████| 81kB 628kB/s [?25hCollecting astor>=0.6 (from tangent) Downloading astor-0.6.2-py2.py3-none-any.whl Collecting autograd>=1.2 (from tangent) Downloading autograd-1.2.tar.gz Collecting enum34 (from tangent) Downloading enum34-1.1.6-py3-none-any.whl Collecting future (from tangent) Downloading future-0.16.0.tar.gz (824kB)  100% |████████████████████████████████| 829kB 577kB/s ta 0:00:01 57% |██████████████████▎ | 471kB 1.7MB/s eta 0:00:01 [?25hCollecting gast (from tangent) Downloading gast-0.2.0.tar.gz Requirement already satisfied: nose in /home/kang/anaconda3/lib/python3.6/site-packages (from tangent) Requirement already satisfied: numpy in /home/kang/anaconda3/lib/python3.6/site-packages (from tangent) Requirement already satisfied: six in /home/kang/anaconda3/lib/python3.6/site-packages (from tangent) Collecting tf-nightly>=1.5.0.dev20171026 (from tangent) Downloading tf_nightly-1.6.0.dev20180126-cp36-cp36m-manylinux1_x86_64.whl (44.6MB)  100% |████████████████████████████████| 44.6MB 14kB/s eta 0:00:017 10% |███▍ | 4.8MB 3.5MB/s eta 0:00:12 11% |███▌ | 4.9MB 9.1MB/s eta 0:00:05 15% |████▉ | 6.8MB 2.6MB/s eta 0:00:15 29% |█████████▎ | 13.0MB 3.0MB/s eta 0:00:11 43% |██████████████ | 19.4MB 3.4MB/s eta 0:00:08 57% |██████████████████▌ | 25.7MB 3.5MB/s eta 0:00:06 63% |████████████████████▍ | 28.3MB 2.5MB/s eta 0:00:07 80% |█████████████████████████▉ | 36.0MB 2.8MB/s eta 0:00:04 99% |███████████████████████████████▊| 44.2MB 466kB/s eta 0:00:01 [?25hCollecting protobuf>=3.4.0 (from tf-nightly>=1.5.0.dev20171026->tangent) Downloading protobuf-3.5.1-cp36-cp36m-manylinux1_x86_64.whl (6.4MB)  100% |████████████████████████████████| 6.4MB 100kB/s ta 0:00:011 44% |██████████████▎ | 2.9MB 219kB/s eta 0:00:17 [?25hRequirement already satisfied: wheel>=0.26 in /home/kang/anaconda3/lib/python3.6/site-packages (from tf-nightly>=1.5.0.dev20171026->tangent) Collecting absl-py>=0.1.6 (from tf-nightly>=1.5.0.dev20171026->tangent) Downloading absl-py-0.1.9.tar.gz (79kB)  100% |████████████████████████████████| 81kB 2.2MB/s ta 0:00:01 [?25hCollecting tb-nightly<1.6.0a0,>=1.5.0a0 (from tf-nightly>=1.5.0.dev20171026->tangent) Downloading tb_nightly-1.5.0a20180126-py3-none-any.whl (3.0MB)  100% |████████████████████████████████| 3.0MB 211kB/s ta 0:00:011 [?25hCollecting termcolor>=1.1.0 (from tf-nightly>=1.5.0.dev20171026->tangent) Downloading termcolor-1.1.0.tar.gz Requirement already satisfied: setuptools in /home/kang/anaconda3/lib/python3.6/site-packages (from protobuf>=3.4.0->tf-nightly>=1.5.0.dev20171026->tangent) Collecting bleach==1.5.0 (from tb-nightly<1.6.0a0,>=1.5.0a0->tf-nightly>=1.5.0.dev20171026->tangent) Downloading bleach-1.5.0-py2.py3-none-any.whl Collecting html5lib==0.9999999 (from tb-nightly<1.6.0a0,>=1.5.0a0->tf-nightly>=1.5.0.dev20171026->tangent) Downloading html5lib-0.9999999.tar.gz (889kB)  100% |████████████████████████████████| 890kB 585kB/s ta 0:00:01 [?25hCollecting markdown>=2.6.8 (from tb-nightly<1.6.0a0,>=1.5.0a0->tf-nightly>=1.5.0.dev20171026->tangent) Downloading Markdown-2.6.11-py2.py3-none-any.whl (78kB)  100% |████████████████████████████████| 81kB 2.5MB/s ta 0:00:01 [?25hRequirement already satisfied: werkzeug>=0.11.10 in /home/kang/anaconda3/lib/python3.6/site-packages (from tb-nightly<1.6.0a0,>=1.5.0a0->tf-nightly>=1.5.0.dev20171026->tangent) Building wheels for collected packages: tangent, autograd, future, gast, absl-py, termcolor, html5lib Running setup.py bdist_wheel for tangent ... [?25ldone [?25h Stored in directory: /home/kang/.cache/pip/wheels/f0/ae/c2/5b094a427f1a1b31c32b94df26678b3efcfe7fedddd2ab4181 Running setup.py bdist_wheel for autograd ... [?25ldone [?25h Stored in directory: /home/kang/.cache/pip/wheels/ea/d4/2d/e7d74fb5d727853026c54f23fa96f0b8defefc7d57dcaca0aa Running setup.py bdist_wheel for future ... [?25ldone [?25h Stored in directory: /home/kang/.cache/pip/wheels/c2/50/7c/0d83b4baac4f63ff7a765bd16390d2ab43c93587fac9d6017a Running setup.py bdist_wheel for gast ... [?25ldone [?25h Stored in directory: /home/kang/.cache/pip/wheels/8e/fa/d6/77dd17d18ea23fd7b860e02623d27c1be451521af40dd4a13e Running setup.py bdist_wheel for absl-py ... [?25ldone [?25h Stored in directory: /home/kang/.cache/pip/wheels/04/f5/7c/5d4eab10ddf87dec875016e74ba289d87270a90fb2662a76fc Running setup.py bdist_wheel for termcolor ... [?25ldone [?25h Stored in directory: /home/kang/.cache/pip/wheels/de/f7/bf/1bcac7bf30549e6a4957382e2ecab04c88e513117207067b03 Running setup.py bdist_wheel for html5lib ... [?25ldone [?25h Stored in directory: /home/kang/.cache/pip/wheels/6f/85/6c/56b8e1292c6214c4eb73b9dda50f53e8e977bf65989373c962 Successfully built tangent autograd future gast absl-py termcolor html5lib Installing collected packages: astor, future, autograd, enum34, gast, protobuf, absl-py, html5lib, bleach, markdown, tb-nightly, termcolor, tf-nightly, tangent Found existing installation: html5lib 0.999999999 Uninstalling html5lib-0.999999999: Successfully uninstalled html5lib-0.999999999 Found existing installation: bleach 2.0.0 Uninstalling bleach-2.0.0: Successfully uninstalled bleach-2.0.0 Successfully installed absl-py-0.1.9 astor-0.6.2 autograd-1.2 bleach-1.5.0 enum34-1.1.6 future-0.16.0 gast-0.2.0 html5lib-0.9999999 markdown-2.6.11 protobuf-3.5.1 tangent-0.1.9 tb-nightly-1.5.0a20180126 termcolor-1.1.0 tf-nightly-1.6.0.dev20180126 ```python import tangent def f(x) : return x ** 3 - 3 * x ** 2 + x import numpy as np x = np.linspace(-1, 3, 10) f(x) fprime0 = tangent.grad(f) fprime0(1) fprime = np.vectorize(fprime0) fprime(x) ``` $$ \int 3x^2 dx $$ $$ \int (3x^2 - 6x + 1)dx $$ $$ \int \left( 2 + 6x + 4\exp(x) + \dfrac{5}{x} \right) dx $$ $$ \int \frac{2x}{x^2 - 1} dx $$ $$\int \left( 1 + xy \right) dx = x + \frac{1}{2}x^2 y + C(y)$$ $$\int \$$ ```python import numpy as np import scipy as sp import sklearn as sk import matplotlib as mpl mpl.use('Agg') import matplotlib.pylab as plt from mpl_toolkits.mplot3d import Axes3D %matplotlib inline ``` /home/kang/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:6: UserWarning: This call to matplotlib.use() has no effect because the backend has already been chosen; matplotlib.use() must be called *before* pylab, matplotlib.pyplot, or matplotlib.backends is imported for the first time. The backend was *originally* set to 'module://ipykernel.pylab.backend_inline' by the following code: File "/home/kang/anaconda3/lib/python3.6/runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "/home/kang/anaconda3/lib/python3.6/runpy.py", line 85, in _run_code exec(code, run_globals) File "/home/kang/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py", line 16, in <module> app.launch_new_instance() File "/home/kang/anaconda3/lib/python3.6/site-packages/traitlets/config/application.py", line 658, in launch_instance app.start() File "/home/kang/anaconda3/lib/python3.6/site-packages/ipykernel/kernelapp.py", line 477, in start ioloop.IOLoop.instance().start() File "/home/kang/anaconda3/lib/python3.6/site-packages/zmq/eventloop/ioloop.py", line 177, in start super(ZMQIOLoop, self).start() File "/home/kang/anaconda3/lib/python3.6/site-packages/tornado/ioloop.py", line 888, in start handler_func(fd_obj, events) File "/home/kang/anaconda3/lib/python3.6/site-packages/tornado/stack_context.py", line 277, in null_wrapper return fn(*args, **kwargs) File "/home/kang/anaconda3/lib/python3.6/site-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events self._handle_recv() File "/home/kang/anaconda3/lib/python3.6/site-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv self._run_callback(callback, msg) File "/home/kang/anaconda3/lib/python3.6/site-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback callback(*args, **kwargs) File "/home/kang/anaconda3/lib/python3.6/site-packages/tornado/stack_context.py", line 277, in null_wrapper return fn(*args, **kwargs) File "/home/kang/anaconda3/lib/python3.6/site-packages/ipykernel/kernelbase.py", line 283, in dispatcher return self.dispatch_shell(stream, msg) File "/home/kang/anaconda3/lib/python3.6/site-packages/ipykernel/kernelbase.py", line 235, in dispatch_shell handler(stream, idents, msg) File "/home/kang/anaconda3/lib/python3.6/site-packages/ipykernel/kernelbase.py", line 399, in execute_request user_expressions, allow_stdin) File "/home/kang/anaconda3/lib/python3.6/site-packages/ipykernel/ipkernel.py", line 196, in do_execute res = shell.run_cell(code, store_history=store_history, silent=silent) File "/home/kang/anaconda3/lib/python3.6/site-packages/ipykernel/zmqshell.py", line 533, in run_cell return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs) File "/home/kang/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2698, in run_cell interactivity=interactivity, compiler=compiler, result=result) File "/home/kang/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2808, in run_ast_nodes if self.run_code(code, result): File "/home/kang/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2862, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-75-5fa60e113fc7>", line 10, in <module> get_ipython().magic('matplotlib inline') File "/home/kang/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2146, in magic return self.run_line_magic(magic_name, magic_arg_s) File "/home/kang/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2067, in run_line_magic result = fn(*args,**kwargs) File "<decorator-gen-107>", line 2, in matplotlib File "/home/kang/anaconda3/lib/python3.6/site-packages/IPython/core/magic.py", line 187, in <lambda> call = lambda f, *a, **k: f(*a, **k) File "/home/kang/anaconda3/lib/python3.6/site-packages/IPython/core/magics/pylab.py", line 99, in matplotlib gui, backend = self.shell.enable_matplotlib(args.gui) File "/home/kang/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2930, in enable_matplotlib pt.activate_matplotlib(backend) File "/home/kang/anaconda3/lib/python3.6/site-packages/IPython/core/pylabtools.py", line 307, in activate_matplotlib matplotlib.pyplot.switch_backend(backend) File "/home/kang/anaconda3/lib/python3.6/site-packages/matplotlib/pyplot.py", line 229, in switch_backend matplotlib.use(newbackend, warn=False, force=True) File "/home/kang/anaconda3/lib/python3.6/site-packages/matplotlib/__init__.py", line 1305, in use reload(sys.modules['matplotlib.backends']) File "/home/kang/anaconda3/lib/python3.6/importlib/__init__.py", line 166, in reload _bootstrap._exec(spec, module) File "/home/kang/anaconda3/lib/python3.6/site-packages/matplotlib/backends/__init__.py", line 14, in <module> line for line in traceback.format_stack() ```python import sympy sympy.init_printing(use_latex = 'mathjax') def f(x) : return 3 * x**2 - 6 * x + 1 def f2(x) : return 2 + 6 * x + 4 * sympy.exp(x) + (5/x) ``` ```python sp.integrate.quad(f, 0, 1) ``` $$\left ( -1.0, \quad 1.3085085171449517e-14\right )$$ ```python sp.integrate.quad(f2, 1, 10) ``` $$\left ( 88421.50297737827, \quad 1.5276890734473408e-06\right )$$ ```python def f3(x, y) : return 1 + x* y ``` ```python sp.integrate.quad(f3, -1, 1) ``` ```python import sympy x, y = sympy.symbols('x y') f = 1 + x * y f ``` $$x y + 1$$ ```python #부정 적분 F = sympy.integrate(f, x) F ``` $$\frac{x^{2} y}{2} + x$$ ```python F2 = sympy.integrate(F, y) F2 ``` $$\frac{x^{2} y^{2}}{4} + x y$$ ```python #성환님 답 x, y = sympy.symbols('x y') f = 1+x*y F = sympy.integrate(f, x) F1 = sympy.integrate(F, y) (F1.subs(x, 1) - F1.subs(x, -1)).evalf() ``` $$2.0 y$$ ```python ```
section \<open>Operational Semantics\<close> text \<open>This theory defines the operational semantics of the concurrent revisions model. It also introduces a relaxed formulation of the operational semantics, and proves the main result required for establishing their equivalence.\<close> theory OperationalSemantics imports Substitution begin context substitution begin subsection Definition inductive revision_step :: "'r \<Rightarrow> ('r,'l,'v) global_state \<Rightarrow> ('r,'l,'v) global_state \<Rightarrow> bool" where app: "s r = Some (\<sigma>, \<tau>, \<E>[Apply (VE (Lambda x e)) (VE v)]) \<Longrightarrow> revision_step r s (s(r \<mapsto> (\<sigma>, \<tau>, \<E>[subst (VE v) x e])))" | ifTrue: "s r = Some (\<sigma>, \<tau>, \<E>[Ite (VE (CV T)) e1 e2]) \<Longrightarrow> revision_step r s (s(r \<mapsto> (\<sigma>, \<tau>, \<E>[e1])))" | ifFalse: "s r = Some (\<sigma>, \<tau>, \<E>[Ite (VE (CV F)) e1 e2]) \<Longrightarrow> revision_step r s (s(r \<mapsto> (\<sigma>, \<tau>, \<E>[e2])))" (* store operations *) | new: "s r = Some (\<sigma>, \<tau>, \<E>[Ref (VE v)]) \<Longrightarrow> l \<notin> LID\<^sub>G s \<Longrightarrow> revision_step r s (s(r \<mapsto> (\<sigma>, \<tau>(l \<mapsto> v), \<E>[VE (Loc l)])))" | get: "s r = Some (\<sigma>, \<tau>, \<E>[Read (VE (Loc l))]) \<Longrightarrow> l \<in> dom (\<sigma>;;\<tau>) \<Longrightarrow> revision_step r s (s(r \<mapsto> (\<sigma>, \<tau>, \<E>[VE (the ((\<sigma>;;\<tau>) l))])))" | set: "s r = Some (\<sigma>, \<tau>, \<E>[Assign (VE (Loc l)) (VE v)]) \<Longrightarrow> l \<in> dom (\<sigma>;;\<tau>) \<Longrightarrow> revision_step r s (s(r \<mapsto> (\<sigma>, \<tau>(l \<mapsto> v), \<E>[VE (CV Unit)])))" (* synchronization operations *) | fork: "s r = Some (\<sigma>, \<tau>, \<E>[Rfork e]) \<Longrightarrow> r' \<notin> RID\<^sub>G s \<Longrightarrow> revision_step r s (s(r \<mapsto> (\<sigma>, \<tau>, \<E>[VE (Rid r')]), r' \<mapsto> (\<sigma>;;\<tau>, \<epsilon>, e)))" | join: "s r = Some (\<sigma>, \<tau>, \<E>[Rjoin (VE (Rid r'))]) \<Longrightarrow> s r' = Some (\<sigma>', \<tau>', VE v) \<Longrightarrow> revision_step r s (s(r := Some (\<sigma>, (\<tau>;;\<tau>'), \<E>[VE (CV Unit)]), r' := None))" | join\<^sub>\<epsilon>: "s r = Some (\<sigma>, \<tau>, \<E>[Rjoin (VE (Rid r'))]) \<Longrightarrow> s r' = None \<Longrightarrow> revision_step r s \<epsilon>" inductive_cases revision_stepE [elim, consumes 1, case_names app ifTrue ifFalse new get set fork join join\<^sub>\<epsilon>]: "revision_step r s s'" subsection \<open>Introduction lemmas for identifiers\<close> lemma only_new_introduces_lids [intro, dest]: assumes step: "revision_step r s s'" and not_new: "\<And>\<sigma> \<tau> \<E> v. s r \<noteq> Some (\<sigma>,\<tau>,\<E>[Ref (VE v)])" shows "LID\<^sub>G s' \<subseteq> LID\<^sub>G s" proof (use step in \<open>cases rule: revision_stepE\<close>) case fork thus ?thesis by (auto simp add: fun_upd_twist ID_distr_global_conditional) next case (join _ _ _ r' _ _ _) hence "r \<noteq> r'" by auto thus ?thesis using join by (auto simp add: fun_upd_twist dest!: in_combination_in_component) qed (auto simp add: not_new fun_upd_twist ID_distr_global_conditional dest: LID\<^sub>SI(2)) lemma only_fork_introduces_rids [intro, dest]: assumes step: "revision_step r s s'" and not_fork: "\<And>\<sigma> \<tau> \<E> e. s r \<noteq> Some (\<sigma>,\<tau>,\<E>[Rfork e])" shows "RID\<^sub>G s' \<subseteq> RID\<^sub>G s" proof (use step in \<open>cases rule: revision_stepE\<close>) next case get then show ?thesis by (auto simp add: ID_distr_global_conditional) next case fork then show ?thesis by (simp add: not_fork) next case (join _ _ _r' _ _ _) hence "r \<noteq> r'" by auto then show ?thesis using join by (auto simp add: fun_upd_twist dest!: in_combination_in_component) qed (auto simp add: ID_distr_global_conditional) lemma only_fork_introduces_rids' [dest]: assumes step: "revision_step r s s'" and not_fork: "\<And>\<sigma> \<tau> \<E> e. s r \<noteq> Some (\<sigma>,\<tau>,\<E>[Rfork e])" shows "r' \<notin> RID\<^sub>G s \<Longrightarrow> r' \<notin> RID\<^sub>G s'" using assms by blast lemma only_new_introduces_lids' [dest]: assumes step: "revision_step r s s'" and not_new: "\<And>\<sigma> \<tau> \<E> v. s r \<noteq> Some (\<sigma>,\<tau>,\<E>[Ref (VE v)])" shows "l \<notin> LID\<^sub>G s \<Longrightarrow> l \<notin> LID\<^sub>G s'" using assms by blast subsection \<open>Domain subsumption\<close> subsubsection Definitions definition domains_subsume :: "('r,'l,'v) local_state \<Rightarrow> bool" ("\<S>") where "\<S> ls = (LID\<^sub>L ls \<subseteq> doms ls)" definition domains_subsume_globally :: "('r,'l,'v) global_state \<Rightarrow> bool" ("\<S>\<^sub>G") where "\<S>\<^sub>G s = (\<forall>r ls. s r = Some ls \<longrightarrow> \<S> ls)" lemma domains_subsume_globallyI [intro]: "(\<And>r \<sigma> \<tau> e. s r = Some (\<sigma>,\<tau>,e) \<Longrightarrow> \<S> (\<sigma>,\<tau>,e)) \<Longrightarrow> domains_subsume_globally s" using domains_subsume_globally_def by auto definition subsumes_accessible :: "'r \<Rightarrow> 'r \<Rightarrow> ('r,'l,'v) global_state \<Rightarrow> bool" ("\<A>") where "\<A> r\<^sub>1 r\<^sub>2 s = (r\<^sub>2 \<in> RID\<^sub>L (the (s r\<^sub>1)) \<longrightarrow> (LID\<^sub>S ((the (s r\<^sub>2))\<^sub>\<sigma>) \<subseteq> doms (the (s r\<^sub>1))))" lemma subsumes_accessibleI [intro]: "(r\<^sub>2 \<in> RID\<^sub>L (the (s r\<^sub>1)) \<Longrightarrow> LID\<^sub>S ((the (s r\<^sub>2))\<^sub>\<sigma>) \<subseteq> doms (the (s r\<^sub>1))) \<Longrightarrow> \<A> r\<^sub>1 r\<^sub>2 s" using subsumes_accessible_def by auto definition subsumes_accessible_globally :: "('r,'l,'v) global_state \<Rightarrow> bool" ("\<A>\<^sub>G") where "\<A>\<^sub>G s = (\<forall>r\<^sub>1 r\<^sub>2. r\<^sub>1 \<in> dom s \<longrightarrow> r\<^sub>2 \<in> dom s \<longrightarrow> \<A> r\<^sub>1 r\<^sub>2 s)" lemma subsumes_accessible_globallyI [intro]: "(\<And>r\<^sub>1 \<sigma>\<^sub>1 \<tau>\<^sub>1 e\<^sub>1 r\<^sub>2 \<sigma>\<^sub>2 \<tau>\<^sub>2 e\<^sub>2. s r\<^sub>1 = Some (\<sigma>\<^sub>1,\<tau>\<^sub>1,e\<^sub>1) \<Longrightarrow> s r\<^sub>2 = Some (\<sigma>\<^sub>2,\<tau>\<^sub>2,e\<^sub>2) \<Longrightarrow> \<A> r\<^sub>1 r\<^sub>2 s) \<Longrightarrow> \<A>\<^sub>G s" using subsumes_accessible_globally_def by auto subsubsection \<open>The theorem\<close> lemma \<S>\<^sub>G_imp_\<A>_refl: assumes \<S>\<^sub>G_s: "\<S>\<^sub>G s" and r_in_dom: "r \<in> dom s" shows "\<A> r r s" using assms by (auto simp add: domains_subsume_def domains_subsume_globally_def subsumes_accessibleI) lemma step_preserves_\<S>\<^sub>G_and_\<A>\<^sub>G: assumes step: "revision_step r s s'" and \<S>\<^sub>G_s: "\<S>\<^sub>G s" and \<A>\<^sub>G_s: "\<A>\<^sub>G s" shows "\<S>\<^sub>G s'" "\<A>\<^sub>G s'" proof - show "\<S>\<^sub>G s'" proof (rule domains_subsume_globallyI) fix r' \<sigma> \<tau> e assume s'_r: "s' r' = Some (\<sigma>,\<tau>,e)" show "\<S> (\<sigma>,\<tau>,e)" proof (cases "s' r' = s r'") case True then show ?thesis using \<S>\<^sub>G_s domains_subsume_globally_def s'_r by auto next case r'_was_updated: False show ?thesis proof (use step in \<open>cases rule: revision_stepE\<close>) case (app \<sigma>' \<tau>' \<E>' _ e' v') have "r = r'" by (metis fun_upd_apply app(1) r'_was_updated) have "LID\<^sub>L (the (s' r)) \<subseteq> LID\<^sub>S \<sigma>' \<union> LID\<^sub>S \<tau>' \<union> LID\<^sub>C \<E>' \<union> LID\<^sub>E e' \<union> LID\<^sub>V v'" using app(1) by auto also have "... = LID\<^sub>L (the (s r))" using app(2) by auto also have "... \<subseteq> doms (the (s r))" by (metis \<S>\<^sub>G_s domains_subsume_def domains_subsume_globally_def local.app(2) option.sel) also have "... = doms (the (s' r))" using app by simp finally have "\<S> (the (s' r))" by (simp add: domains_subsume_def) thus ?thesis by (simp add: \<open>r = r'\<close> s'_r) next case ifTrue have "r = r'" by (metis fun_upd_apply ifTrue(1) r'_was_updated) have "LID\<^sub>L (the (s' r)) \<subseteq> LID\<^sub>L (the (s r))" using ifTrue by auto also have "... \<subseteq> doms (the (s r))" by (metis \<S>\<^sub>G_s domains_subsume_def domains_subsume_globally_def ifTrue(2) option.sel) also have "... = doms (the (s' r))" by (simp add: ifTrue) finally have "\<S> (the (s' r))" by (simp add: domains_subsume_def) thus ?thesis by (simp add: \<open>r = r'\<close> s'_r) next case ifFalse have "r = r'" by (metis fun_upd_apply ifFalse(1) r'_was_updated) have "LID\<^sub>L (the (s' r)) \<subseteq> LID\<^sub>L (the (s r))" using ifFalse by auto also have "... \<subseteq> doms (the (s r))" by (metis \<S>\<^sub>G_s domains_subsume_def domains_subsume_globally_def ifFalse(2) option.sel) also have "... = doms (the (s' r))" by (simp add: ifFalse) finally have "\<S> (the (s' r))" by (simp add: domains_subsume_def) thus ?thesis by (simp add: \<open>r = r'\<close> s'_r) next case (new \<sigma>' \<tau>' \<E>' v' l') have "r = r'" by (metis fun_upd_apply new(1) r'_was_updated) have "LID\<^sub>L (the (s' r)) = insert l' (LID\<^sub>S \<sigma>' \<union> LID\<^sub>S \<tau>' \<union> LID\<^sub>V v' \<union> LID\<^sub>C \<E>')" proof - have "l' \<notin> LID\<^sub>S \<tau>'" using new(2-3) by auto thus ?thesis using new(1) by auto qed also have "... = insert l' (LID\<^sub>L (the (s r)))" using new by auto also have "... \<subseteq> insert l' (doms (the (s r)))" by (metis \<S>\<^sub>G_s domains_subsume_def domains_subsume_globally_def insert_mono new(2) option.sel) also have "... = doms (the (s' r))" using new by auto finally have "\<S> (the (s' r))" by (simp add: domains_subsume_def) thus ?thesis by (simp add: \<open>r = r'\<close> s'_r) next case get have "r = r'" by (metis fun_upd_apply get(1) r'_was_updated) have "LID\<^sub>L (the (s' r)) = LID\<^sub>L (the (s r))" using get by auto also have "... \<subseteq> doms (the (s r))" by (metis \<S>\<^sub>G_s domains_subsume_def domains_subsume_globally_def get(2) option.sel) also have "... = doms (the (s' r))" by (simp add: get(1-2)) finally have "\<S> (the (s' r))" by (simp add: domains_subsume_def) thus ?thesis by (simp add: \<open>r = r'\<close> s'_r) next case set have "r = r'" by (metis fun_upd_apply set(1) r'_was_updated) have "LID\<^sub>L (the (s' r)) \<subseteq> LID\<^sub>L (the (s r))" using set(1-2) by auto also have "... \<subseteq> doms (the (s r))" by (metis \<S>\<^sub>G_s domains_subsume_def domains_subsume_globally_def set(2) option.sel) also have "... \<subseteq> doms (the (s' r))" using set(1-2) by auto finally have "\<S> (the (s' r))" by (simp add: domains_subsume_def) thus ?thesis by (simp add: \<open>r = r'\<close> s'_r) next case (fork \<sigma>' \<tau>' _ _ r'') have "r = r' \<or> r'' = r'" using fork r'_was_updated by auto then show ?thesis proof (rule disjE) assume "r = r'" have "LID\<^sub>L (the (s' r)) \<subseteq> LID\<^sub>L (the (s r))" using fork(1-2) by auto also have "... \<subseteq> doms (the (s r))" by (metis \<S>\<^sub>G_s domains_subsume_def domains_subsume_globally_def fork(2) option.sel) also have "... = doms (the (s' r))" using fork by auto finally have "\<S> (the (s' r))" by (simp add: domains_subsume_def) thus ?thesis by (simp add: \<open>r = r'\<close> s'_r) next assume "r'' = r'" have "LID\<^sub>L (the (s' r'')) \<subseteq> LID\<^sub>L (the (s r))" using fork(1-2) by auto also have "... \<subseteq> doms (the (s r))" by (metis \<S>\<^sub>G_s domains_subsume_def domains_subsume_globally_def fork(2) option.sel) also have "... = dom \<sigma>' \<union> dom \<tau>'" using fork by simp also have "... = dom (\<sigma>';;\<tau>')" by (simp add: dom_combination_dom_union) also have "... = doms (the (s' r''))" using fork by simp finally have "\<S> (the (s' r''))" by (simp add: domains_subsume_def) thus ?thesis by (simp add: \<open>r'' = r'\<close> s'_r) qed next case (join \<sigma>' \<tau>' _ r'' \<sigma>'' \<tau>'' _) have "r' = r" by (metis fun_upd_def join(1) option.simps(3) r'_was_updated s'_r) have "LID\<^sub>L (the (s' r)) \<subseteq> LID\<^sub>L (the (s r)) \<union> LID\<^sub>S \<tau>''" using join by auto also have "... \<subseteq> doms (the (s r)) \<union> LID\<^sub>S \<tau>''" by (metis Un_mono \<S>\<^sub>G_s domains_subsume_def domains_subsume_globally_def join(2) option.sel subset_refl) also have "... \<subseteq> doms (the (s r)) \<union> LID\<^sub>L (the (s r''))" using join(3) by auto also have "... \<subseteq> doms (the (s r)) \<union> doms (the (s r''))" by (metis (no_types, lifting) Un_absorb \<S>\<^sub>G_s domains_subsume_def domains_subsume_globally_def join(3) option.sel sup.orderI sup_mono) also have "... = dom \<sigma>' \<union> dom \<tau>' \<union> dom \<sigma>'' \<union> dom \<tau>''" using join by auto also have "... \<subseteq> dom \<sigma>' \<union> dom \<tau>' \<union> LID\<^sub>S \<sigma>'' \<union> dom \<tau>''" by auto also have "... \<subseteq> dom \<sigma>' \<union> dom \<tau>' \<union> dom \<sigma>' \<union> dom \<tau>' \<union> dom \<tau>''" proof - have r_r'': "\<A> r r'' s" using \<A>\<^sub>G_s join(2-3) subsumes_accessible_globally_def by auto have r_accesses_r'': "r'' \<in> RID\<^sub>L (the (s r))" using join by auto have "LID\<^sub>S \<sigma>'' \<subseteq> dom \<sigma>' \<union> dom \<tau>'" using join subsumes_accessible_def r_r'' r_accesses_r'' by auto thus ?thesis by auto qed also have "... = dom \<sigma>' \<union> dom \<tau>' \<union> dom \<tau>''" by auto also have "... = dom \<sigma>' \<union> dom (\<tau>';;\<tau>'')" by (auto simp add: dom_combination_dom_union) also have "... = doms (the (s' r))" using join by auto finally have "\<S> (the (s' r))" by (simp add: domains_subsume_def) thus ?thesis using \<open>r' = r\<close> s'_r by auto next case join\<^sub>\<epsilon> then show ?thesis using s'_r by blast qed qed qed show "\<A>\<^sub>G s'" proof (rule subsumes_accessible_globallyI) fix r\<^sub>1 \<sigma>\<^sub>1 \<tau>\<^sub>1 e\<^sub>1 r\<^sub>2 \<sigma>\<^sub>2 \<tau>\<^sub>2 e\<^sub>2 assume s'_r\<^sub>1: "s' r\<^sub>1 = Some (\<sigma>\<^sub>1, \<tau>\<^sub>1, e\<^sub>1)" and s'_r\<^sub>2: "s' r\<^sub>2 = Some (\<sigma>\<^sub>2, \<tau>\<^sub>2, e\<^sub>2)" show "\<A> r\<^sub>1 r\<^sub>2 s'" proof (cases "r\<^sub>1 = r\<^sub>2") case True then show ?thesis using \<S>\<^sub>G_imp_\<A>_refl \<open>\<S>\<^sub>G s'\<close> s'_r\<^sub>1 by blast next case r\<^sub>1_neq_r\<^sub>2: False have r\<^sub>1_nor_r\<^sub>2_updated_implies_thesis: "s' r\<^sub>1 = s r\<^sub>1 \<Longrightarrow> s' r\<^sub>2 = s r\<^sub>2 \<Longrightarrow> ?thesis" proof - assume r\<^sub>1_unchanged: "s' r\<^sub>1 = s r\<^sub>1" and r\<^sub>2_unchanged: "s' r\<^sub>2 = s r\<^sub>2" have "\<A> r\<^sub>1 r\<^sub>2 s" by (metis \<A>\<^sub>G_s domIff option.discI r\<^sub>1_unchanged r\<^sub>2_unchanged s'_r\<^sub>1 s'_r\<^sub>2 subsumes_accessible_globally_def) show ?thesis using \<open>\<A> r\<^sub>1 r\<^sub>2 s\<close> r\<^sub>1_unchanged r\<^sub>2_unchanged subsumes_accessible_def by auto qed have r\<^sub>1_or_r\<^sub>2_updated_implies_thesis: "s' r\<^sub>1 \<noteq> s r\<^sub>1 \<or> s' r\<^sub>2 \<noteq> s r\<^sub>2 \<Longrightarrow> ?thesis" proof - assume r\<^sub>1_or_r\<^sub>2_updated: "s' r\<^sub>1 \<noteq> s r\<^sub>1 \<or> s' r\<^sub>2 \<noteq> s r\<^sub>2" show ?thesis proof (use step in \<open>cases rule: revision_stepE\<close>) case app have "r\<^sub>1 = r \<or> r\<^sub>2 = r" by (metis fun_upd_other app(1) r\<^sub>1_or_r\<^sub>2_updated) then show ?thesis proof (rule disjE) assume r\<^sub>1_eq_r: "r\<^sub>1 = r" show "\<A> r\<^sub>1 r\<^sub>2 s'" proof (rule subsumes_accessibleI) assume r\<^sub>2_in_s'_r\<^sub>1: "r\<^sub>2 \<in> RID\<^sub>L (the (s' r\<^sub>1))" have "LID\<^sub>S ((the (s' r\<^sub>2))\<^sub>\<sigma>) \<subseteq> LID\<^sub>S ((the (s r\<^sub>2))\<^sub>\<sigma>)" using app by auto also have "... \<subseteq> doms (the (s r\<^sub>1))" proof - have r\<^sub>2_in_s_r\<^sub>1: "r\<^sub>2 \<in> RID\<^sub>L (the (s r\<^sub>1))" using app r\<^sub>2_in_s'_r\<^sub>1 r\<^sub>1_eq_r by auto have "\<A> r\<^sub>1 r\<^sub>2 s" by (metis \<A>\<^sub>G_s domI fun_upd_other app r\<^sub>1_eq_r s'_r\<^sub>2 subsumes_accessible_globally_def) show ?thesis using \<open>\<A> r\<^sub>1 r\<^sub>2 s\<close> r\<^sub>2_in_s_r\<^sub>1 subsumes_accessible_def by blast qed also have "... \<subseteq> doms (the (s' r\<^sub>1))" using app by auto finally show "LID\<^sub>S (the (s' r\<^sub>2)\<^sub>\<sigma>) \<subseteq> doms (the (s' r\<^sub>1))" by simp qed next assume r\<^sub>2_eq_r: "r\<^sub>2 = r" show "\<A> r\<^sub>1 r\<^sub>2 s'" proof (rule subsumes_accessibleI) assume r\<^sub>2_in_s'_r\<^sub>1: "r\<^sub>2 \<in> RID\<^sub>L (the (s' r\<^sub>1))" have "LID\<^sub>S (the (s' r\<^sub>2)\<^sub>\<sigma>) = LID\<^sub>S (the (s r\<^sub>2)\<^sub>\<sigma>)" using app by auto also have "... \<subseteq> doms (the (s r\<^sub>1))" proof - have r\<^sub>2_in_s_r\<^sub>1: "r\<^sub>2 \<in> RID\<^sub>L (the (s r\<^sub>1))" using app(1) r\<^sub>1_neq_r\<^sub>2 r\<^sub>2_eq_r r\<^sub>2_in_s'_r\<^sub>1 by auto have "\<A> r\<^sub>1 r\<^sub>2 s" by (metis (no_types, lifting) \<A>\<^sub>G_s domIff fun_upd_other app option.discI r\<^sub>2_eq_r s'_r\<^sub>1 subsumes_accessible_globally_def) show ?thesis using \<open>\<A> r\<^sub>1 r\<^sub>2 s\<close> r\<^sub>2_in_s_r\<^sub>1 subsumes_accessible_def by blast qed also have "... \<subseteq> doms (the (s' r\<^sub>1))" by (simp add: app) finally show "LID\<^sub>S (the (s' r\<^sub>2)\<^sub>\<sigma>) \<subseteq> doms (the (s' r\<^sub>1))" by simp qed qed next case ifTrue have "r\<^sub>1 = r \<or> r\<^sub>2 = r" by (metis fun_upd_other ifTrue(1) r\<^sub>1_or_r\<^sub>2_updated) then show ?thesis proof (rule disjE) assume r\<^sub>1_eq_r: "r\<^sub>1 = r" show "\<A> r\<^sub>1 r\<^sub>2 s'" proof (rule subsumes_accessibleI) assume r\<^sub>2_in_s'_r\<^sub>1: "r\<^sub>2 \<in> RID\<^sub>L (the (s' r\<^sub>1))" have "LID\<^sub>S ((the (s' r\<^sub>2))\<^sub>\<sigma>) \<subseteq> LID\<^sub>S ((the (s r\<^sub>2))\<^sub>\<sigma>)" using ifTrue by auto also have "... \<subseteq> doms (the (s r\<^sub>1))" proof - have r\<^sub>2_in_s_r\<^sub>1: "r\<^sub>2 \<in> RID\<^sub>L (the (s r\<^sub>1))" using ifTrue r\<^sub>2_in_s'_r\<^sub>1 r\<^sub>1_eq_r by auto have "\<A> r\<^sub>1 r\<^sub>2 s" by (metis \<A>\<^sub>G_s domI fun_upd_other ifTrue r\<^sub>1_eq_r s'_r\<^sub>2 subsumes_accessible_globally_def) show ?thesis using \<open>\<A> r\<^sub>1 r\<^sub>2 s\<close> r\<^sub>2_in_s_r\<^sub>1 subsumes_accessible_def by blast qed also have "... \<subseteq> doms (the (s' r\<^sub>1))" using ifTrue by auto finally show "LID\<^sub>S (the (s' r\<^sub>2)\<^sub>\<sigma>) \<subseteq> doms (the (s' r\<^sub>1))" by simp qed next assume r\<^sub>2_eq_r: "r\<^sub>2 = r" show "\<A> r\<^sub>1 r\<^sub>2 s'" proof (rule subsumes_accessibleI) assume r\<^sub>2_in_s'_r\<^sub>1: "r\<^sub>2 \<in> RID\<^sub>L (the (s' r\<^sub>1))" have "LID\<^sub>S (the (s' r\<^sub>2)\<^sub>\<sigma>) = LID\<^sub>S (the (s r\<^sub>2)\<^sub>\<sigma>)" using ifTrue by auto also have "... \<subseteq> doms (the (s r\<^sub>1))" proof - have r\<^sub>2_in_s_r\<^sub>1: "r\<^sub>2 \<in> RID\<^sub>L (the (s r\<^sub>1))" using ifTrue(1) r\<^sub>1_neq_r\<^sub>2 r\<^sub>2_eq_r r\<^sub>2_in_s'_r\<^sub>1 by auto have "\<A> r\<^sub>1 r\<^sub>2 s" by (metis (no_types, lifting) \<A>\<^sub>G_s domIff fun_upd_other ifTrue option.discI r\<^sub>2_eq_r s'_r\<^sub>1 subsumes_accessible_globally_def) show ?thesis using \<open>\<A> r\<^sub>1 r\<^sub>2 s\<close> r\<^sub>2_in_s_r\<^sub>1 subsumes_accessible_def by blast qed also have "... \<subseteq> doms (the (s' r\<^sub>1))" by (simp add: ifTrue) finally show "LID\<^sub>S (the (s' r\<^sub>2)\<^sub>\<sigma>) \<subseteq> doms (the (s' r\<^sub>1))" by simp qed qed next case ifFalse have "r\<^sub>1 = r \<or> r\<^sub>2 = r" by (metis fun_upd_other ifFalse(1) r\<^sub>1_or_r\<^sub>2_updated) then show ?thesis proof (rule disjE) assume r\<^sub>1_eq_r: "r\<^sub>1 = r" show "\<A> r\<^sub>1 r\<^sub>2 s'" proof (rule subsumes_accessibleI) assume r\<^sub>2_in_s'_r\<^sub>1: "r\<^sub>2 \<in> RID\<^sub>L (the (s' r\<^sub>1))" have "LID\<^sub>S ((the (s' r\<^sub>2))\<^sub>\<sigma>) \<subseteq> LID\<^sub>S ((the (s r\<^sub>2))\<^sub>\<sigma>)" using ifFalse by auto also have "... \<subseteq> doms (the (s r\<^sub>1))" proof - have r\<^sub>2_in_s_r\<^sub>1: "r\<^sub>2 \<in> RID\<^sub>L (the (s r\<^sub>1))" using ifFalse r\<^sub>2_in_s'_r\<^sub>1 r\<^sub>1_eq_r by auto have "\<A> r\<^sub>1 r\<^sub>2 s" by (metis \<A>\<^sub>G_s domI fun_upd_other ifFalse r\<^sub>1_eq_r s'_r\<^sub>2 subsumes_accessible_globally_def) show ?thesis using \<open>\<A> r\<^sub>1 r\<^sub>2 s\<close> r\<^sub>2_in_s_r\<^sub>1 subsumes_accessible_def by blast qed also have "... \<subseteq> doms (the (s' r\<^sub>1))" using ifFalse by auto finally show "LID\<^sub>S (the (s' r\<^sub>2)\<^sub>\<sigma>) \<subseteq> doms (the (s' r\<^sub>1))" by simp qed next assume r\<^sub>2_eq_r: "r\<^sub>2 = r" show "\<A> r\<^sub>1 r\<^sub>2 s'" proof (rule subsumes_accessibleI) assume r\<^sub>2_in_s'_r\<^sub>1: "r\<^sub>2 \<in> RID\<^sub>L (the (s' r\<^sub>1))" have "LID\<^sub>S (the (s' r\<^sub>2)\<^sub>\<sigma>) = LID\<^sub>S (the (s r\<^sub>2)\<^sub>\<sigma>)" using ifFalse by auto also have "... \<subseteq> doms (the (s r\<^sub>1))" proof - have r\<^sub>2_in_s_r\<^sub>1: "r\<^sub>2 \<in> RID\<^sub>L (the (s r\<^sub>1))" using ifFalse(1) r\<^sub>1_neq_r\<^sub>2 r\<^sub>2_eq_r r\<^sub>2_in_s'_r\<^sub>1 by auto have "\<A> r\<^sub>1 r\<^sub>2 s" by (metis (no_types, lifting) \<A>\<^sub>G_s domIff fun_upd_other ifFalse option.discI r\<^sub>2_eq_r s'_r\<^sub>1 subsumes_accessible_globally_def) show ?thesis using \<open>\<A> r\<^sub>1 r\<^sub>2 s\<close> r\<^sub>2_in_s_r\<^sub>1 subsumes_accessible_def by blast qed also have "... \<subseteq> doms (the (s' r\<^sub>1))" by (simp add: ifFalse) finally show "LID\<^sub>S (the (s' r\<^sub>2)\<^sub>\<sigma>) \<subseteq> doms (the (s' r\<^sub>1))" by simp qed qed next case new have "r\<^sub>1 = r \<or> r\<^sub>2 = r" by (metis fun_upd_other new(1) r\<^sub>1_or_r\<^sub>2_updated) then show ?thesis proof (rule disjE) assume r\<^sub>1_eq_r: "r\<^sub>1 = r" show "\<A> r\<^sub>1 r\<^sub>2 s'" proof (rule subsumes_accessibleI) assume r\<^sub>2_in_s'_r\<^sub>1: "r\<^sub>2 \<in> RID\<^sub>L (the (s' r\<^sub>1))" have "LID\<^sub>S ((the (s' r\<^sub>2))\<^sub>\<sigma>) \<subseteq> LID\<^sub>S ((the (s r\<^sub>2))\<^sub>\<sigma>)" using new by auto also have "... \<subseteq> doms (the (s r\<^sub>1))" proof - have r\<^sub>2_in_s_r\<^sub>1: "r\<^sub>2 \<in> RID\<^sub>L (the (s r\<^sub>1))" using new r\<^sub>2_in_s'_r\<^sub>1 r\<^sub>1_eq_r by auto have "\<A> r\<^sub>1 r\<^sub>2 s" by (metis \<A>\<^sub>G_s domI fun_upd_other new(1-2) r\<^sub>1_eq_r s'_r\<^sub>2 subsumes_accessible_globally_def) show ?thesis using \<open>\<A> r\<^sub>1 r\<^sub>2 s\<close> r\<^sub>2_in_s_r\<^sub>1 subsumes_accessible_def by blast qed also have "... \<subseteq> doms (the (s' r\<^sub>1))" using new by auto finally show "LID\<^sub>S (the (s' r\<^sub>2)\<^sub>\<sigma>) \<subseteq> doms (the (s' r\<^sub>1))" by simp qed next assume r\<^sub>2_eq_r: "r\<^sub>2 = r" show "\<A> r\<^sub>1 r\<^sub>2 s'" proof (rule subsumes_accessibleI) assume r\<^sub>2_in_s'_r\<^sub>1: "r\<^sub>2 \<in> RID\<^sub>L (the (s' r\<^sub>1))" have "LID\<^sub>S (the (s' r\<^sub>2)\<^sub>\<sigma>) = LID\<^sub>S (the (s r\<^sub>2)\<^sub>\<sigma>)" using new by auto also have "... \<subseteq> doms (the (s r\<^sub>1))" proof - have r\<^sub>2_in_s_r\<^sub>1: "r\<^sub>2 \<in> RID\<^sub>L (the (s r\<^sub>1))" using new(1) r\<^sub>1_neq_r\<^sub>2 r\<^sub>2_eq_r r\<^sub>2_in_s'_r\<^sub>1 by auto have "\<A> r\<^sub>1 r\<^sub>2 s" by (metis (no_types, lifting) \<A>\<^sub>G_s domIff fun_upd_other new(1-2) option.discI r\<^sub>2_eq_r s'_r\<^sub>1 subsumes_accessible_globally_def) show ?thesis using \<open>\<A> r\<^sub>1 r\<^sub>2 s\<close> r\<^sub>2_in_s_r\<^sub>1 subsumes_accessible_def by blast qed also have "... \<subseteq> doms (the (s' r\<^sub>1))" by (auto simp add: new) finally show "LID\<^sub>S (the (s' r\<^sub>2)\<^sub>\<sigma>) \<subseteq> doms (the (s' r\<^sub>1))" by simp qed qed next case get have "r\<^sub>1 = r \<or> r\<^sub>2 = r" by (metis fun_upd_other get(1) r\<^sub>1_or_r\<^sub>2_updated) then show ?thesis proof (rule disjE) assume r\<^sub>1_eq_r: "r\<^sub>1 = r" show "\<A> r\<^sub>1 r\<^sub>2 s'" proof (rule subsumes_accessibleI) assume r\<^sub>2_in_s'_r\<^sub>1: "r\<^sub>2 \<in> RID\<^sub>L (the (s' r\<^sub>1))" have "LID\<^sub>S ((the (s' r\<^sub>2))\<^sub>\<sigma>) \<subseteq> LID\<^sub>S ((the (s r\<^sub>2))\<^sub>\<sigma>)" using get by auto also have "... \<subseteq> doms (the (s r\<^sub>1))" proof - have r\<^sub>2_in_s_r\<^sub>1: "r\<^sub>2 \<in> RID\<^sub>L (the (s r\<^sub>1))" using get r\<^sub>2_in_s'_r\<^sub>1 r\<^sub>1_eq_r apply auto by (meson RID\<^sub>SI) (* by (auto 1 3) *) have "\<A> r\<^sub>1 r\<^sub>2 s" by (metis \<A>\<^sub>G_s domI fun_upd_other get(1-2) r\<^sub>1_eq_r s'_r\<^sub>2 subsumes_accessible_globally_def) show ?thesis using \<open>\<A> r\<^sub>1 r\<^sub>2 s\<close> r\<^sub>2_in_s_r\<^sub>1 subsumes_accessible_def by blast qed also have "... \<subseteq> doms (the (s' r\<^sub>1))" using get by auto finally show "LID\<^sub>S (the (s' r\<^sub>2)\<^sub>\<sigma>) \<subseteq> doms (the (s' r\<^sub>1))" by simp qed next assume r\<^sub>2_eq_r: "r\<^sub>2 = r" show "\<A> r\<^sub>1 r\<^sub>2 s'" proof (rule subsumes_accessibleI) assume r\<^sub>2_in_s'_r\<^sub>1: "r\<^sub>2 \<in> RID\<^sub>L (the (s' r\<^sub>1))" have "LID\<^sub>S (the (s' r\<^sub>2)\<^sub>\<sigma>) = LID\<^sub>S (the (s r\<^sub>2)\<^sub>\<sigma>)" using get by auto also have "... \<subseteq> doms (the (s r\<^sub>1))" proof - have r\<^sub>2_in_s_r\<^sub>1: "r\<^sub>2 \<in> RID\<^sub>L (the (s r\<^sub>1))" using get(1) r\<^sub>1_neq_r\<^sub>2 r\<^sub>2_eq_r r\<^sub>2_in_s'_r\<^sub>1 by auto have "\<A> r\<^sub>1 r\<^sub>2 s" by (metis (no_types, lifting) \<A>\<^sub>G_s domIff fun_upd_other get(1-2) option.discI r\<^sub>2_eq_r s'_r\<^sub>1 subsumes_accessible_globally_def) show ?thesis using \<open>\<A> r\<^sub>1 r\<^sub>2 s\<close> r\<^sub>2_in_s_r\<^sub>1 subsumes_accessible_def by blast qed also have "... \<subseteq> doms (the (s' r\<^sub>1))" by (simp add: get) finally show "LID\<^sub>S (the (s' r\<^sub>2)\<^sub>\<sigma>) \<subseteq> doms (the (s' r\<^sub>1))" by simp qed qed next case set have "r\<^sub>1 = r \<or> r\<^sub>2 = r" by (metis fun_upd_other set(1) r\<^sub>1_or_r\<^sub>2_updated) then show ?thesis proof (rule disjE) assume r\<^sub>1_eq_r: "r\<^sub>1 = r" show "\<A> r\<^sub>1 r\<^sub>2 s'" proof (rule subsumes_accessibleI) assume r\<^sub>2_in_s'_r\<^sub>1: "r\<^sub>2 \<in> RID\<^sub>L (the (s' r\<^sub>1))" have "LID\<^sub>S ((the (s' r\<^sub>2))\<^sub>\<sigma>) \<subseteq> LID\<^sub>S ((the (s r\<^sub>2))\<^sub>\<sigma>)" using set by auto also have "... \<subseteq> doms (the (s r\<^sub>1))" proof - have r\<^sub>2_in_s_r\<^sub>1: "r\<^sub>2 \<in> RID\<^sub>L (the (s r\<^sub>1))" using set r\<^sub>2_in_s'_r\<^sub>1 r\<^sub>1_eq_r by auto have "\<A> r\<^sub>1 r\<^sub>2 s" by (metis \<A>\<^sub>G_s domI fun_upd_other set(1-2) r\<^sub>1_eq_r s'_r\<^sub>2 subsumes_accessible_globally_def) show ?thesis using \<open>\<A> r\<^sub>1 r\<^sub>2 s\<close> r\<^sub>2_in_s_r\<^sub>1 subsumes_accessible_def by blast qed also have "... \<subseteq> doms (the (s' r\<^sub>1))" using set by auto finally show "LID\<^sub>S (the (s' r\<^sub>2)\<^sub>\<sigma>) \<subseteq> doms (the (s' r\<^sub>1))" by simp qed next assume r\<^sub>2_eq_r: "r\<^sub>2 = r" show "\<A> r\<^sub>1 r\<^sub>2 s'" proof (rule subsumes_accessibleI) assume r\<^sub>2_in_s'_r\<^sub>1: "r\<^sub>2 \<in> RID\<^sub>L (the (s' r\<^sub>1))" have "LID\<^sub>S (the (s' r\<^sub>2)\<^sub>\<sigma>) = LID\<^sub>S (the (s r\<^sub>2)\<^sub>\<sigma>)" using set by auto also have "... \<subseteq> doms (the (s r\<^sub>1))" proof - have r\<^sub>2_in_s_r\<^sub>1: "r\<^sub>2 \<in> RID\<^sub>L (the (s r\<^sub>1))" using set(1) r\<^sub>1_neq_r\<^sub>2 r\<^sub>2_eq_r r\<^sub>2_in_s'_r\<^sub>1 by auto have "\<A> r\<^sub>1 r\<^sub>2 s" by (metis (no_types, lifting) \<A>\<^sub>G_s domIff fun_upd_other set(1-2) option.discI r\<^sub>2_eq_r s'_r\<^sub>1 subsumes_accessible_globally_def) show ?thesis using \<open>\<A> r\<^sub>1 r\<^sub>2 s\<close> r\<^sub>2_in_s_r\<^sub>1 subsumes_accessible_def by blast qed also have "... \<subseteq> doms (the (s' r\<^sub>1))" by (auto simp add: set) finally show "LID\<^sub>S (the (s' r\<^sub>2)\<^sub>\<sigma>) \<subseteq> doms (the (s' r\<^sub>1))" by simp qed qed next case (fork \<sigma> \<tau> \<E> e r') have s'_r: "s' r = Some (\<sigma>, \<tau>, \<E> [VE (Rid r')])" using fork by auto have s'_r': "s' r' = Some (\<sigma>;;\<tau>, \<epsilon>, e)" by (simp add: local.fork(1)) have case1: "r\<^sub>1 = r \<Longrightarrow> r\<^sub>2 \<noteq> r \<Longrightarrow> r\<^sub>2 \<noteq> r' \<Longrightarrow> ?thesis" proof (rule subsumes_accessibleI) assume "r\<^sub>1 = r" "r\<^sub>2 \<noteq> r" "r\<^sub>2 \<noteq> r'" assume r\<^sub>2_in_s'_r\<^sub>1: "r\<^sub>2 \<in> RID\<^sub>L (the (s' r\<^sub>1))" have "LID\<^sub>S ((the (s' r\<^sub>2))\<^sub>\<sigma>) \<subseteq> LID\<^sub>S ((the (s r\<^sub>2))\<^sub>\<sigma>)" using fork(1-2) by (simp add: \<open>r\<^sub>2 \<noteq> r'\<close>) also have "... \<subseteq> doms (the (s r\<^sub>1))" proof - have r\<^sub>2_in_s_r\<^sub>1: "r\<^sub>2 \<in> RID\<^sub>L (the (s r\<^sub>1))" using fork \<open>r\<^sub>1 = r\<close> \<open>r\<^sub>2 \<noteq> r'\<close> r\<^sub>2_in_s'_r\<^sub>1 s'_r by auto have "\<A> r\<^sub>1 r\<^sub>2 s" by (metis (no_types, lifting) \<A>\<^sub>G_s \<open>r\<^sub>1 = r\<close> \<open>r\<^sub>2 \<noteq> r'\<close> domIff fun_upd_other fork(1-2) option.discI s'_r\<^sub>2 subsumes_accessible_globally_def) show ?thesis using \<open>\<A> r\<^sub>1 r\<^sub>2 s\<close> r\<^sub>2_in_s_r\<^sub>1 subsumes_accessible_def by blast qed also have "... \<subseteq> doms (the (s' r\<^sub>1))" by (simp add: \<open>r\<^sub>1 = r\<close> fork(2) s'_r) finally show "LID\<^sub>S (the (s' r\<^sub>2)\<^sub>\<sigma>) \<subseteq> doms (the (s' r\<^sub>1))" by simp qed have case2: "r\<^sub>1 \<noteq> r \<Longrightarrow> r\<^sub>1 \<noteq> r' \<Longrightarrow> r\<^sub>2 = r \<Longrightarrow> ?thesis" proof (rule subsumes_accessibleI) assume "r\<^sub>1 \<noteq> r" "r\<^sub>1 \<noteq> r'" "r\<^sub>2 = r" assume r\<^sub>2_in_s'_r\<^sub>1: "r\<^sub>2 \<in> RID\<^sub>L (the (s' r\<^sub>1))" have "LID\<^sub>S ((the (s' r\<^sub>2))\<^sub>\<sigma>) \<subseteq> LID\<^sub>S ((the (s r\<^sub>2))\<^sub>\<sigma>)" using \<open>r\<^sub>1 \<noteq> r'\<close> \<open>r\<^sub>1 \<noteq> r\<close> fork r\<^sub>2_in_s'_r\<^sub>1 s'_r\<^sub>1 by auto also have "... \<subseteq> doms (the (s r\<^sub>1))" proof - have r\<^sub>2_in_s_r\<^sub>1: "r\<^sub>2 \<in> RID\<^sub>L (the (s r\<^sub>1))" using \<open>r\<^sub>1 \<noteq> r'\<close> \<open>r\<^sub>1 \<noteq> r\<close> fork(1) r\<^sub>2_in_s'_r\<^sub>1 by auto have "\<A> r\<^sub>1 r\<^sub>2 s" by (metis (no_types, lifting) \<A>\<^sub>G_s \<open>r\<^sub>1 \<noteq> r'\<close> \<open>r\<^sub>2 = r\<close> domIff fun_upd_other fork(1-2) option.discI s'_r\<^sub>1 subsumes_accessible_globally_def) show ?thesis using \<open>\<A> r\<^sub>1 r\<^sub>2 s\<close> r\<^sub>2_in_s_r\<^sub>1 subsumes_accessible_def by auto qed also have "... \<subseteq> doms (the (s' r\<^sub>1))" by (simp add: \<open>r\<^sub>1 \<noteq> r'\<close> \<open>r\<^sub>1 \<noteq> r\<close> fork(1)) finally show "LID\<^sub>S (the (s' r\<^sub>2)\<^sub>\<sigma>) \<subseteq> doms (the (s' r\<^sub>1))" by simp qed have case3: "r\<^sub>1 = r' \<Longrightarrow> r\<^sub>2 \<noteq> r \<Longrightarrow> r\<^sub>2 \<noteq> r' \<Longrightarrow> ?thesis" proof (rule subsumes_accessibleI) fix l assume "r\<^sub>1 = r'" "r\<^sub>2 \<noteq> r" "r\<^sub>2 \<noteq> r'" assume "r\<^sub>2 \<in> RID\<^sub>L (the (s' r\<^sub>1))" hence "r\<^sub>2 \<in> RID\<^sub>L (the (s r))" using RID\<^sub>LI(3) \<open>r\<^sub>1 = r'\<close> fork(2) s'_r' by auto have "s r\<^sub>2 = s' r\<^sub>2" by (simp add: \<open>r\<^sub>2 \<noteq> r'\<close> \<open>r\<^sub>2 \<noteq> r\<close> fork(1)) hence "\<A> r r\<^sub>2 s" using \<A>\<^sub>G_s fork(2) s'_r\<^sub>2 subsumes_accessible_globally_def by auto hence "LID\<^sub>S (the (s' r\<^sub>2)\<^sub>\<sigma>) \<subseteq> doms (the (s r))" by (simp add: \<open>r\<^sub>2 \<in> RID\<^sub>L (the (s r))\<close> \<open>s r\<^sub>2 = s' r\<^sub>2\<close> subsumes_accessible_def) also have "... = dom \<sigma> \<union> dom \<tau>" by (simp add: fork(2)) also have "... = dom (\<sigma>;;\<tau>)" by (simp add: dom_combination_dom_union) also have "... = doms (the (s' r'))" by (simp add: s'_r') finally show "LID\<^sub>S (the (s' r\<^sub>2)\<^sub>\<sigma>) \<subseteq> doms (the (s' r\<^sub>1))" using \<open>r\<^sub>1 = r'\<close> by blast qed have case4: "r\<^sub>1 \<noteq> r \<Longrightarrow> r\<^sub>1 \<noteq> r' \<Longrightarrow> r\<^sub>2 = r' \<Longrightarrow> ?thesis" proof - assume "r\<^sub>1 \<noteq> r" "r\<^sub>1 \<noteq> r'" "r\<^sub>2 = r'" have "r\<^sub>2 \<notin> RID\<^sub>L (the (s r\<^sub>1))" using \<open>r\<^sub>1 \<noteq> r'\<close> \<open>r\<^sub>1 \<noteq> r\<close> \<open>r\<^sub>2 = r'\<close> fork(1,3) s'_r\<^sub>1 by auto hence "r\<^sub>2 \<notin> RID\<^sub>L (the (s' r\<^sub>1))" by (simp add: \<open>r\<^sub>1 \<noteq> r'\<close> \<open>r\<^sub>1 \<noteq> r\<close> fork(1)) thus ?thesis by blast qed have case5: "r\<^sub>1 = r \<Longrightarrow> r\<^sub>2 = r' \<Longrightarrow> ?thesis" proof (rule subsumes_accessibleI) assume "r\<^sub>1 = r" "r\<^sub>2 = r'" have "LID\<^sub>S ((the (s' r\<^sub>2))\<^sub>\<sigma>) = LID\<^sub>S (\<sigma>;;\<tau>)" by (simp add: \<open>r\<^sub>2 = r'\<close> s'_r') also have "... \<subseteq> LID\<^sub>S \<sigma> \<union> LID\<^sub>S \<tau>" by auto also have "... \<subseteq> LID\<^sub>L (the (s' r\<^sub>1))" by (simp add: \<open>r\<^sub>1 = r\<close> s'_r) also have "... \<subseteq> doms (the (s' r\<^sub>1))" by (metis \<open>\<S>\<^sub>G s'\<close> \<open>r\<^sub>1 = r\<close> domains_subsume_def domains_subsume_globally_def option.sel s'_r) finally show "LID\<^sub>S (the (s' r\<^sub>2)\<^sub>\<sigma>) \<subseteq> doms (the (s' r\<^sub>1))" by simp qed have case6: "r\<^sub>1 = r' \<Longrightarrow> r\<^sub>2 = r \<Longrightarrow> ?thesis" proof (rule subsumes_accessibleI) assume "r\<^sub>1 = r'" "r\<^sub>2 = r" "r\<^sub>2 \<in> RID\<^sub>L (the (s' r\<^sub>1))" have "LID\<^sub>S (the (s' r\<^sub>2)\<^sub>\<sigma>) \<subseteq> LID\<^sub>L (the (s' r\<^sub>2))" by (simp add: s'_r\<^sub>2 subsetI) also have "... \<subseteq> doms (the (s' r\<^sub>2))" using \<open>\<S>\<^sub>G s'\<close> domains_subsume_def domains_subsume_globally_def s'_r\<^sub>2 by auto also have "... = dom \<sigma> \<union> dom \<tau>" by (simp add: \<open>r\<^sub>2 = r\<close> s'_r) also have "... = dom (\<sigma>;;\<tau>)" by (simp add: dom_combination_dom_union) finally show " LID\<^sub>S (the (s' r\<^sub>2)\<^sub>\<sigma>) \<subseteq> doms (the (s' r\<^sub>1))" using \<open>r\<^sub>1 = r'\<close> s'_r' by auto qed show ?thesis using case1 case2 case3 case4 case5 case6 fork(1) r\<^sub>1_neq_r\<^sub>2 r\<^sub>1_nor_r\<^sub>2_updated_implies_thesis by fastforce next case (join \<sigma> \<tau> \<E> r' \<sigma>' \<tau>' v) have "r\<^sub>1 = r \<or> r\<^sub>2 = r" by (metis fun_upd_def join(1) option.simps(3) r\<^sub>1_or_r\<^sub>2_updated s'_r\<^sub>1 s'_r\<^sub>2) then show ?thesis proof (rule disjE) assume "r\<^sub>1 = r" show "\<A> r\<^sub>1 r\<^sub>2 s'" proof (rule subsumes_accessibleI) assume r\<^sub>2_in_s'_r\<^sub>1: "r\<^sub>2 \<in> RID\<^sub>L (the (s' r\<^sub>1))" show "LID\<^sub>S (the (s' r\<^sub>2)\<^sub>\<sigma>) \<subseteq> doms (the (s' r\<^sub>1))" proof (cases "r\<^sub>2 \<in> RID\<^sub>S \<tau>'") case r\<^sub>2_in_\<tau>': True have "LID\<^sub>S (the (s' r\<^sub>2)\<^sub>\<sigma>) = LID\<^sub>S (the (s r\<^sub>2)\<^sub>\<sigma>)" by (metis \<open>r\<^sub>1 = r\<close> fun_upd_def join(1) option.distinct(1) r\<^sub>1_neq_r\<^sub>2 s'_r\<^sub>2) also have "... \<subseteq> doms (the (s r'))" proof - have r\<^sub>2_in_s_r': "r\<^sub>2 \<in> RID\<^sub>L (the (s r'))" by (simp add: join(3) r\<^sub>2_in_\<tau>') have "\<A> r' r\<^sub>2 s" by (metis \<A>\<^sub>G_s \<open>r\<^sub>1 = r\<close> domI fun_upd_def join(1) join(3) r\<^sub>1_neq_r\<^sub>2 s'_r\<^sub>2 subsumes_accessible_globally_def) show ?thesis using \<open>\<A> r' r\<^sub>2 s\<close> r\<^sub>2_in_s_r' subsumes_accessible_def by blast qed also have "... = dom \<sigma>' \<union> dom \<tau>'" by (simp add: join(3)) also have "... \<subseteq> LID\<^sub>S \<sigma>' \<union> dom \<tau>'" by auto also have "... \<subseteq> dom \<sigma> \<union> dom \<tau> \<union> dom \<tau>'" proof - have "r' \<in> RID\<^sub>L (the (s r))" by (simp add: join(2)) have "\<A> r r' s" using \<A>\<^sub>G_s join(2-3) subsumes_accessible_globally_def by auto show ?thesis using \<open>\<A> r r' s\<close> join(2-3) subsumes_accessible_def by auto qed also have "... = dom \<sigma> \<union> dom (\<tau>;;\<tau>')" by (auto simp add: dom_combination_dom_union) also have "... = doms (the (s' r\<^sub>1))" using join by (auto simp add: \<open>r\<^sub>1 = r\<close>) finally show ?thesis by simp next case r\<^sub>2_nin_\<tau>': False have "LID\<^sub>S (the (s' r\<^sub>2)\<^sub>\<sigma>) = LID\<^sub>S (the (s r\<^sub>2)\<^sub>\<sigma>)" by (metis \<open>r\<^sub>1 = r\<close> fun_upd_def join(1) option.distinct(1) r\<^sub>1_neq_r\<^sub>2 s'_r\<^sub>2) also have "... \<subseteq> doms (the (s r\<^sub>1))" proof - have r\<^sub>2_in_s_r\<^sub>1: "r\<^sub>2 \<in> RID\<^sub>L (the (s r))" proof - have "RID\<^sub>L (the (s' r\<^sub>1)) = RID\<^sub>S \<sigma> \<union> RID\<^sub>S (\<tau>;;\<tau>') \<union> RID\<^sub>C \<E>" by (metis (no_types, lifting) ID_distr_completion(1) ID_distr_local(2) \<open>r\<^sub>1 = r\<close> expr.simps(153) fun_upd_apply local.join(1) option.discI option.sel s'_r\<^sub>1 sup_bot.right_neutral val.simps(66)) hence "r\<^sub>2 \<in> RID\<^sub>S \<sigma> \<union> RID\<^sub>S \<tau> \<union> RID\<^sub>C \<E>" using r\<^sub>2_in_s'_r\<^sub>1 r\<^sub>2_nin_\<tau>' by auto thus ?thesis by (simp add: join(2)) qed have "\<A> r\<^sub>1 r\<^sub>2 s" by (metis (no_types, lifting) \<A>\<^sub>G_s \<open>r\<^sub>1 = r\<close> join(1-2) domIff fun_upd_def option.discI s'_r\<^sub>2 subsumes_accessible_globally_def) show ?thesis using \<open>\<A> r\<^sub>1 r\<^sub>2 s\<close> r\<^sub>2_in_s_r\<^sub>1 subsumes_accessible_def \<open>r\<^sub>1 = r\<close> by blast qed also have "... = dom \<sigma> \<union> dom \<tau>" by (simp add: \<open>r\<^sub>1 = r\<close> join(2)) also have "... \<subseteq> dom \<sigma> \<union> dom (\<tau>;;\<tau>')" by (auto simp add: dom_combination_dom_union) also have "... = doms (the (s' r\<^sub>1))" using join \<open>r\<^sub>1 = r\<close> by auto finally show ?thesis by simp qed qed next assume "r\<^sub>2 = r" show "\<A> r\<^sub>1 r\<^sub>2 s'" proof (rule subsumes_accessibleI) assume r\<^sub>2_in_s'_r\<^sub>1: "r\<^sub>2 \<in> RID\<^sub>L (the (s' r\<^sub>1))" have "LID\<^sub>S (the (s' r\<^sub>2)\<^sub>\<sigma>) = LID\<^sub>S (the (s r\<^sub>2)\<^sub>\<sigma>)" by (metis (no_types, lifting) LID_snapshot.simps fun_upd_apply join(1-2) option.discI option.sel s'_r\<^sub>2) also have "... \<subseteq> doms (the (s r\<^sub>1))" proof - have r\<^sub>2_in_s_r\<^sub>1: "r\<^sub>2 \<in> RID\<^sub>L (the (s r\<^sub>1))" by (metis \<open>r\<^sub>2 = r\<close> fun_upd_apply local.join(1) option.discI r\<^sub>1_neq_r\<^sub>2 r\<^sub>2_in_s'_r\<^sub>1 s'_r\<^sub>1) have "\<A> r\<^sub>1 r\<^sub>2 s" by (metis (no_types, lifting) \<A>\<^sub>G_s \<open>r\<^sub>2 = r\<close> domIff fun_upd_apply join(1-2) option.discI s'_r\<^sub>1 subsumes_accessible_globally_def) show ?thesis using \<open>\<A> r\<^sub>1 r\<^sub>2 s\<close> r\<^sub>2_in_s_r\<^sub>1 subsumes_accessible_def by blast qed also have "... \<subseteq> doms (the (s' r\<^sub>1))" by (metis \<open>r\<^sub>2 = r\<close> eq_refl fun_upd_def local.join(1) option.distinct(1) r\<^sub>1_neq_r\<^sub>2 s'_r\<^sub>1) finally show "LID\<^sub>S (the (s' r\<^sub>2)\<^sub>\<sigma>) \<subseteq> doms (the (s' r\<^sub>1))" by simp qed qed next case join\<^sub>\<epsilon> thus ?thesis using s'_r\<^sub>1 by blast qed qed show "\<A> r\<^sub>1 r\<^sub>2 s'" using r\<^sub>1_nor_r\<^sub>2_updated_implies_thesis r\<^sub>1_or_r\<^sub>2_updated_implies_thesis by blast qed qed qed subsection \<open>Relaxed definition of the operational semantics\<close> inductive revision_step_relaxed :: "'r \<Rightarrow> ('r,'l,'v) global_state \<Rightarrow> ('r,'l,'v) global_state \<Rightarrow> bool" where app: "s r = Some (\<sigma>, \<tau>, \<E>[Apply (VE (Lambda x e)) (VE v)]) \<Longrightarrow> revision_step_relaxed r s (s(r \<mapsto> (\<sigma>, \<tau>, \<E>[subst (VE v) x e])))" | ifTrue: "s r = Some (\<sigma>, \<tau>, \<E>[Ite (VE (CV T)) e1 e2]) \<Longrightarrow> revision_step_relaxed r s (s(r \<mapsto> (\<sigma>, \<tau>, \<E>[e1])))" | ifFalse: "s r = Some (\<sigma>, \<tau>, \<E>[Ite (VE (CV F)) e1 e2]) \<Longrightarrow> revision_step_relaxed r s (s(r \<mapsto> (\<sigma>, \<tau>, \<E>[e2])))" (* store operations *) | new: "s r = Some (\<sigma>, \<tau>, \<E>[Ref (VE v)]) \<Longrightarrow> l \<notin> \<Union> { doms ls | ls. ls \<in> ran s } \<Longrightarrow> revision_step_relaxed r s (s(r \<mapsto> (\<sigma>, \<tau>(l \<mapsto> v), \<E>[VE (Loc l)])))" | get: "s r = Some (\<sigma>, \<tau>, \<E>[Read (VE (Loc l))]) \<Longrightarrow> revision_step_relaxed r s (s(r \<mapsto> (\<sigma>, \<tau>, \<E>[VE (the ((\<sigma>;;\<tau>) l))])))" | set: "s r = Some (\<sigma>, \<tau>, \<E>[Assign (VE (Loc l)) (VE v)]) \<Longrightarrow> revision_step_relaxed r s (s(r \<mapsto> (\<sigma>, \<tau>(l \<mapsto> v), \<E>[VE (CV Unit)])))" (* synchronization operations *) | fork: "s r = Some (\<sigma>, \<tau>, \<E>[Rfork e]) \<Longrightarrow> r' \<notin> RID\<^sub>G s \<Longrightarrow> revision_step_relaxed r s (s(r \<mapsto> (\<sigma>, \<tau>, \<E>[VE (Rid r')]), r' \<mapsto> (\<sigma>;;\<tau>, \<epsilon>, e)))" | join: "s r = Some (\<sigma>, \<tau>, \<E>[Rjoin (VE (Rid r'))]) \<Longrightarrow> s r' = Some (\<sigma>', \<tau>', VE v) \<Longrightarrow> revision_step_relaxed r s (s(r := Some (\<sigma>, (\<tau>;;\<tau>'), \<E>[VE (CV Unit)]), r' := None))" | join\<^sub>\<epsilon>: "s r = Some (\<sigma>, \<tau>, \<E>[Rjoin (VE (Rid r'))]) \<Longrightarrow> s r' = None \<Longrightarrow> revision_step_relaxed r s \<epsilon>" inductive_cases revision_step_relaxedE [elim, consumes 1, case_names app ifTrue ifFalse new get set fork join join\<^sub>\<epsilon>]: "revision_step_relaxed r s s'" end (* substitution locale *) end (* theory *)
\documentclass[aspectratio=169]{beamer} \usefonttheme[onlymath]{serif} \usepackage[utf8]{inputenc} \usepackage{graphicx} % Allows including images \usepackage{booktabs} % Allows the use of \toprule, \midrule and \bottomrule in tables \usepackage{subfigure} \usepackage{subfiles} \usepackage{url} \usepackage{amssymb} \usepackage{amsmath} \usepackage{xcolor,colortbl} \usepackage[backend=bibtex,sorting=none]{biblatex} \usepackage[AutoFakeBold, AutoFakeSlant]{xeCJK} \renewcommand{\figurename}{图} \addbibresource{reference.bib} %BibTeX数据文件及位置 \definecolor{NJUPurple}{rgb}{0.41568, 0, 0.37255} \colorlet{LightNJUPurple}{white!60!NJUPurple} \colorlet{SuperLightNJUPurple}{white!90!NJUPurple} \addbibresource{reference.bib} %BibTeX数据文件及位置 \definecolor{NJUPurple}{rgb}{0.41568, 0, 0.37255} % UBC Blue (primary) \usecolortheme[named=NJUPurple]{structure} %Information to be included in the title page: \title{Beamer 模板} \author{\href{mailto:}{SEer}} \institute{Software Institute, Nanjing University} \date{\today} %Logo in every slide \logo{% \makebox[0.98\paperwidth]{ \href{https://www.nju.edu.cn}{\includegraphics[height=0.75cm,keepaspectratio]{logos/nju_logo.jpg}} \hfill% \href{https://software.nju.edu.cn}{\includegraphics[height=0.75cm,keepaspectratio]{logos/SE_logo.png}}% } } \setbeamertemplate{blocks}[rounded][shadow=true] \setbeamercolor{block title}{fg=white,bg=NJUPurple!50} \setbeamercolor{block body}{fg=black,bg=white} \setbeamerfont{title}{shape=\bfseries,size=\Large} \setbeamerfont{author}{shape=\bfseries} \makeatletter \setbeamertemplate{title page}{% \vbox{} \vfill \vskip2cm%<- added \begingroup \centering \begin{beamercolorbox}[sep=8pt,center]{title} \usebeamerfont{title}\inserttitle\par% \ifx\insertsubtitle\@empty% \else% \vskip0.25em% {\usebeamerfont{subtitle}\usebeamercolor[fg]{subtitle}\insertsubtitle\par}% \fi% \end{beamercolorbox}% \vskip1em\par \vfill%<- added \begin{beamercolorbox}[sep=8pt,center]{author} \usebeamerfont{author}\insertauthor \end{beamercolorbox} \vskip-0.2cm%<- changed \begin{beamercolorbox}[sep=8pt,center]{institute} \usebeamerfont{institute}\insertinstitute \end{beamercolorbox} \vfill%<- added \begin{beamercolorbox}[sep=8pt,center]{date} \usebeamerfont{date}\insertdate \end{beamercolorbox}% \vskip0.5cm%<- changed \endgroup % \vfill%<- removed } \makeatother %Contents before every section's starting slide % https://tex.stackexchange.com/questions/193975/highlight-only-current-subsection-hide-subsections-of-other-sections \AtBeginSection[] { \begin{frame} \frametitle{目录} \tableofcontents[ currentsection, currentsubsection, subsectionstyle=show/show/hide, sectionstyle=show/shaded ] \end{frame} } \AtBeginSubsection[] { \begin{frame} \frametitle{目录} \tableofcontents[ currentsection, currentsubsection, sectionstyle=show/shaded, subsectionstyle=show/shaded/hide, ] \end{frame} } % shape, colour of item, nested item bullets in itemize only \setbeamertemplate{itemize item}[circle] \setbeamercolor{itemize item}{fg=NJUPurple} \setbeamertemplate{itemize subitem}[circle] \setbeamercolor{itemize subitem}{fg=LightNJUPurple} \setbeamertemplate{itemize subsubitem}[circle] \setbeamercolor{itemize subsubitem}{fg=SuperLightNJUPurple} % font size of nested and nested-within-nested bulltes in both itemize and enumerate % options are \tiny, \small, \scriptsize, \normalsize, \footnotesize, \large, \Large, \LARGE, \huge and \Huge \setbeamerfont{itemize/enumerate subbody}{size=\scriptsize} \setbeamerfont{itemize/enumerate subsubbody}{size=\scriptsize} %%setting up some useful slide creation commands %split slide \newenvironment{splitframe}[5] %[1] ==> 1 parameter passed through {} %[2] ==> 2 parameters passed through {}{} %[4] ==> 4 parameters passed through {}{}{}{} { \begin{frame}{#3} \begin{columns} \column{#1\linewidth} \centering #4 \column{#2\linewidth} \centering #5 \end{columns} \centering \vspace{\baselineskip} % adds one line space } %Inside the first pair of braces (ABOVE) is set what your new environment will do before the text within, then inside the second pair of braces (BELOW) declare what your new environment will do after the text. Note second pair can be empty braces too. { \end{frame} } \begin{document} \frame{\titlepage} % no hyperlinks in logos except for titlepage \logo{% \makebox[0.98\paperwidth]{ \includegraphics[height=0.75cm,keepaspectratio]{logos/nju_logo.jpg} \hfill% \includegraphics[height=0.75cm,keepaspectratio]{logos/SE_logo.png}% } } \begin{frame} \frametitle{目录} \tableofcontents[hidesubsections] \end{frame} \section{引言} \begin{frame} \frametitle{测试} 深度学习~\cite{lecun2015deep} ... \end{frame} \section{结论} \begin{frame} \frametitle{Test} Deep Learning~\cite{lecun2015deep} ... \end{frame} \begin{frame} \frametitle{参考文献} \printbibliography \end{frame} \end{document} \end{document}
[STATEMENT] lemma propos_subset: "propos \<phi> \<subseteq> nested_propos \<phi>" [PROOF STATE] proof (prove) goal (1 subgoal): 1. propos \<phi> \<subseteq> nested_propos \<phi> [PROOF STEP] by (induction \<phi>) auto
[STATEMENT] lemma map_of_prod_2[simp]: "i < n \<Longrightarrow> p \<noteq> q \<Longrightarrow> (m ++ map_of (map (\<lambda>i. ((p, i), g i)) [0..<n])) (q, i) = m (q, i)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>i < n; p \<noteq> q\<rbrakk> \<Longrightarrow> (m ++ map_of (map (\<lambda>i. ((p, i), g i)) [0..<n])) (q, i) = m (q, i) [PROOF STEP] apply (rule map_add_dom_app_simps) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>i < n; p \<noteq> q\<rbrakk> \<Longrightarrow> (q, i) \<notin> dom (map_of (map (\<lambda>i. ((p, i), g i)) [0..<n])) [PROOF STEP] apply (subst dom_map_of_conv_image_fst) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>i < n; p \<noteq> q\<rbrakk> \<Longrightarrow> (q, i) \<notin> fst ` set (map (\<lambda>i. ((p, i), g i)) [0..<n]) [PROOF STEP] apply clarsimp [PROOF STATE] proof (prove) goal: No subgoals! [PROOF STEP] done
State Before: p : ℕ hp : Prime p ⊢ ↑Λ p = Real.log ↑p State After: no goals Tactic: rw [vonMangoldt_apply, Prime.minFac_eq hp, if_pos hp.prime.isPrimePow]
#include "io_fixture.hpp" #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_CASE(empty, io_fixture) { { output(); } { input(); } }
../model/channel_aug.v ../model/channel.v
[GOAL] R : Type u_1 S : Type u_2 inst✝¹ : Ring R inst✝ : LinearOrderedCommRing S abv : AbsoluteValue ℤ S x : ℤˣ ⊢ ↑abv ↑x = 1 [PROOFSTEP] rcases Int.units_eq_one_or x with (rfl | rfl) [GOAL] case inl R : Type u_1 S : Type u_2 inst✝¹ : Ring R inst✝ : LinearOrderedCommRing S abv : AbsoluteValue ℤ S ⊢ ↑abv ↑1 = 1 [PROOFSTEP] simp [GOAL] case inr R : Type u_1 S : Type u_2 inst✝¹ : Ring R inst✝ : LinearOrderedCommRing S abv : AbsoluteValue ℤ S ⊢ ↑abv ↑(-1) = 1 [PROOFSTEP] simp [GOAL] R : Type u_1 S : Type u_2 inst✝² : Ring R inst✝¹ : LinearOrderedCommRing S inst✝ : Nontrivial R abv : AbsoluteValue R S x : ℤˣ ⊢ ↑abv ↑↑x = 1 [PROOFSTEP] rcases Int.units_eq_one_or x with (rfl | rfl) [GOAL] case inl R : Type u_1 S : Type u_2 inst✝² : Ring R inst✝¹ : LinearOrderedCommRing S inst✝ : Nontrivial R abv : AbsoluteValue R S ⊢ ↑abv ↑↑1 = 1 [PROOFSTEP] simp [GOAL] case inr R : Type u_1 S : Type u_2 inst✝² : Ring R inst✝¹ : LinearOrderedCommRing S inst✝ : Nontrivial R abv : AbsoluteValue R S ⊢ ↑abv ↑↑(-1) = 1 [PROOFSTEP] simp [GOAL] R : Type u_1 S : Type u_2 inst✝¹ : Ring R inst✝ : LinearOrderedCommRing S abv : AbsoluteValue R S x : ℤˣ y : R ⊢ ↑abv (x • y) = ↑abv y [PROOFSTEP] rcases Int.units_eq_one_or x with (rfl | rfl) [GOAL] case inl R : Type u_1 S : Type u_2 inst✝¹ : Ring R inst✝ : LinearOrderedCommRing S abv : AbsoluteValue R S y : R ⊢ ↑abv (1 • y) = ↑abv y [PROOFSTEP] simp [GOAL] case inr R : Type u_1 S : Type u_2 inst✝¹ : Ring R inst✝ : LinearOrderedCommRing S abv : AbsoluteValue R S y : R ⊢ ↑abv (-1 • y) = ↑abv y [PROOFSTEP] simp
{-# OPTIONS --without-K #-} module Homotopy where open import GroupoidStructure open import PathOperations open import Types infix 1 _∼_ _∼_ : ∀ {a b} {A : Set a} {B : Set b} (f g : A → B) → Set _ f ∼ g = ∀ x → f x ≡ g x naturality : ∀ {a b} {A : Set a} {B : Set b} {x y : A} (f g : A → B) (H : f ∼ g) (p : x ≡ y) → H x · ap g p ≡ ap f p · H y naturality f g H = J (λ x y p → H x · ap g p ≡ ap f p · H y) (λ _ → p·id _) _ _
(************************************************************************) (* *) (* Micromega: A reflexive tactic using the Positivstellensatz *) (* *) (* Frédéric Besson (Irisa/Inria) 2006-2008 *) (* *) (************************************************************************) Require Import Psatz. Require Import QArith. Lemma plus_minus : forall x y, 0 == x + y -> 0 == x -y -> 0 == x /\ 0 == y. Proof. intros. psatzl Q. Qed. (* Other (simple) examples *) Open Scope Q_scope. Lemma binomial : forall x y:Q, ((x+y)^2 == x^2 + (2 # 1) *x*y + y^2). Proof. intros. psatzl Q. Qed. Lemma hol_light19 : forall m n, (2 # 1) * m + n == (n + m) + m. Proof. intros ; psatzl Q. Qed. Open Scope Z_scope. Open Scope Q_scope. Lemma vcgen_25 : forall (n : Q) (m : Q) (jt : Q) (j : Q) (it : Q) (i : Q) (H0 : 1 * it + (-2 # 1) * i + (-1 # 1) == 0) (H : 1 * jt + (-2 # 1) * j + (-1 # 1) == 0) (H1 : 1 * n + (-10 # 1) = 0) (H2 : 0 <= (-4028 # 1) * i + (6222 # 1) * j + (705 # 1) * m + (-16674 # 1)) (H3 : 0 <= (-418 # 1) * i + (651 # 1) * j + (94 # 1) * m + (-1866 # 1)) (H4 : 0 <= (-209 # 1) * i + (302 # 1) * j + (47 # 1) * m + (-839 # 1)) (H5 : 0 <= (-1 # 1) * i + 1 * j + (-1 # 1)) (H6 : 0 <= (-1 # 1) * j + 1 * m + (0 # 1)) (H7 : 0 <= (1 # 1) * j + (5 # 1) * m + (-27 # 1)) (H8 : 0 <= (2 # 1) * j + (-1 # 1) * m + (2 # 1)) (H9 : 0 <= (7 # 1) * j + (10 # 1) * m + (-74 # 1)) (H10 : 0 <= (18 # 1) * j + (-139 # 1) * m + (1188 # 1)) (H11 : 0 <= 1 * i + (0 # 1)) (H13 : 0 <= (121 # 1) * i + (810 # 1) * j + (-7465 # 1) * m + (64350 # 1)), (( 1# 1) == (-2 # 1) * i + it). Proof. intros. psatzl Q. Qed. Goal forall x, -x^2 >= 0 -> x - 1 >= 0 -> False. Proof. intros. psatz Q 2. Qed. Lemma motzkin' : forall x y, (x^2+y^2+1)*(x^2*y^4 + x^4*y^2 + 1 - (3 # 1) *x^2*y^2) >= 0. Proof. intros ; psatz Q. Qed.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Precompute all w_{ij} % Xp is the likelihood of the optimal assignments given % the current output set %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [W, Xp] = getW(B, S, param) P = zeros(size(B,2)); for i = 1:size(B,2) P(i,:) = getIOUFloat(B',B(:,i)'); end P = bsxfun(@times, P, S(:)); P = [P param.lambda*ones(size(B,2),1)]; P = bsxfun(@times, P, 1./sum(P,2)); W = log(P); Xp = W(:,end); W = W(:,1:end-1);
Require Export P03. (** **** Exercise: 2 stars (hoare_asgn_example4) *) (** Translate this "decorated program" into a formal proof: {{ True }} ->> {{ 1 = 1 }} X ::= 1;; {{ X = 1 }} ->> {{ X = 1 /\ 2 = 2 }} Y ::= 2 {{ X = 1 /\ Y = 2 }} *) Example hoare_asgn_example4 : {{fun st => True}} (X ::= (ANum 1);; Y ::= (ANum 2)) {{fun st => st X = 1 /\ st Y = 2}}. Proof. apply hoare_seq with (Q:= (fun st => st X = 1)); unfold hoare_triple; intros. inversion H; subst. simpl. split. rewrite<-H0. reflexivity. reflexivity. unfold hoare_triple; intros. inversion H; subst. reflexivity. Qed.
theory IMP imports Main "~~/src/HOL/IMP/BExp" begin datatype com = SKIP | Assign vname aexp ("_ ::= _" [1000, 62] 62) | Seq com com ("_;;/ _" [60, 61] 60) | If bexp com com ("(IF _/ THEN _/ ELSE _)" [0, 0, 63] 63) | While bexp com ("(WHILE _/ DO _)" [0, 64] 64) | Repeat com bexp ("(REPEAT _/ UNTIL _)" [0, 64] 64) | Or com com ("(_/ OR _)" [61,62] 61) value "SKIP OR WHILE b DO c ;; c2" subsection "Big-Step Semantics of Commands" text {* The big-step semantics is a straight-forward inductive definition with concrete syntax. Note that the first parameter is a tuple, so the syntax becomes @{text "(c,s) \<Rightarrow> s'"}. *} text_raw{*\snip{BigStepdef}{0}{1}{% *} inductive big_step :: "com \<times> state \<Rightarrow> state \<Rightarrow> bool" (infix "\<Rightarrow>" 55) where Skip: "(SKIP,s) \<Rightarrow> s" | Assign: "(x ::= a,s) \<Rightarrow> s(x := aval a s)" | Seq: "\<lbrakk> (c\<^sub>1,s\<^sub>1) \<Rightarrow> s\<^sub>2; (c\<^sub>2,s\<^sub>2) \<Rightarrow> s\<^sub>3 \<rbrakk> \<Longrightarrow> (c\<^sub>1;;c\<^sub>2, s\<^sub>1) \<Rightarrow> s\<^sub>3" | IfTrue: "\<lbrakk> bval b s; (c\<^sub>1,s) \<Rightarrow> t \<rbrakk> \<Longrightarrow> (IF b THEN c\<^sub>1 ELSE c\<^sub>2, s) \<Rightarrow> t" | IfFalse: "\<lbrakk> \<not>bval b s; (c\<^sub>2,s) \<Rightarrow> t \<rbrakk> \<Longrightarrow> (IF b THEN c\<^sub>1 ELSE c\<^sub>2, s) \<Rightarrow> t" | WhileFalse: "\<not>bval b s \<Longrightarrow> (WHILE b DO c,s) \<Rightarrow> s" | WhileTrue: "\<lbrakk> bval b s\<^sub>1; (c,s\<^sub>1) \<Rightarrow> s\<^sub>2; (WHILE b DO c, s\<^sub>2) \<Rightarrow> s\<^sub>3 \<rbrakk> \<Longrightarrow> (WHILE b DO c, s\<^sub>1) \<Rightarrow> s\<^sub>3" | RepeatTrue: "\<lbrakk> bval b s\<rbrakk> \<Longrightarrow> (REPEAT c UNTIL b, s) \<Rightarrow> s" | RepeatFalse: "\<lbrakk> \<not>bval b s; (c, s) \<Rightarrow> s'; (REPEAT c UNTIL b, s') \<Rightarrow> t\<rbrakk> \<Longrightarrow> (REPEAT c UNTIL b, s) \<Rightarrow> t" | OrL: "(a,s) \<Rightarrow> t \<Longrightarrow> (a OR b, s) \<Rightarrow> t" | OrR: "(b,s) \<Rightarrow> t \<Longrightarrow> (a OR b, s) \<Rightarrow> t" text_raw{*}%endsnip*} text{* We want to execute the big-step rules: *} code_pred big_step . text{* For inductive definitions we need command \texttt{values} instead of \texttt{value}. *} values "{t. (SKIP, \<lambda>_. 0) \<Rightarrow> t}" text{* We need to translate the result state into a list to display it. *} values "{map t [''x''] |t. (SKIP, <''x'' := 42>) \<Rightarrow> t}" values "{map t [''x''] |t. (''x'' ::= N 2, <''x'' := 42>) \<Rightarrow> t}" values "{map t [''x'',''y''] |t. (WHILE Less (V ''x'') (V ''y'') DO (''x'' ::= Plus (V ''x'') (N 5)), <''x'' := 0, ''y'' := 13>) \<Rightarrow> t}" values "{map t [''x'',''y''] |t. (REPEAT ''x'' ::= Plus (V ''x'') (N 5) UNTIL Not (Less (V ''x'') (V ''y'')), <''x'' := 0, ''y'' := 13>) \<Rightarrow> t}" values "{map t [''x''] |t. (''x'' ::= N 2 OR ''x'' ::= N 3, <''x'' := 42>) \<Rightarrow> t}" text{* Proof automation: *} text {* The introduction rules are good for automatically construction small program executions. The recursive cases may require backtracking, so we declare the set as unsafe intro rules. *} declare big_step.intros [intro] thm big_step.intros text{* The standard induction rule @{thm [display] big_step.induct [no_vars]} *} thm big_step.induct text{* This induction schema is almost perfect for our purposes, but our trick for reusing the tuple syntax means that the induction schema has two parameters instead of the @{text c}, @{text s}, and @{text s'} that we are likely to encounter. Splitting the tuple parameter fixes this: *} lemmas big_step_induct = big_step.induct[split_format(complete)] thm big_step_induct text {* @{thm [display] big_step_induct [no_vars]} *} subsection "Rule inversion" text{* What can we deduce from @{prop "(SKIP,s) \<Rightarrow> t"} ? That @{prop "s = t"}. This is how we can automatically prove it: *} inductive_cases SkipE[elim!]: "(SKIP,s) \<Rightarrow> t" thm SkipE text{* This is an \emph{elimination rule}. The [elim] attribute tells auto, blast and friends (but not simp!) to use it automatically; [elim!] means that it is applied eagerly. Similarly for the other commands: *} inductive_cases AssignE[elim!]: "(x ::= a,s) \<Rightarrow> t" thm AssignE inductive_cases SeqE[elim!]: "(c1;;c2,s1) \<Rightarrow> s3" thm SeqE inductive_cases IfE[elim!]: "(IF b THEN c1 ELSE c2,s) \<Rightarrow> t" thm IfE inductive_cases WhileE[elim]: "(WHILE b DO c,s) \<Rightarrow> t" thm WhileE inductive_cases RepeatE[elim]: "(REPEAT c UNTIL b, s) \<Rightarrow> t" thm RepeatE inductive_cases OrE[elim]: "(a OR b, s) \<Rightarrow> t" thm OrE text{* Only [elim]: [elim!] would not terminate. *} text{* An automatic example: *} lemma "(IF b THEN SKIP ELSE SKIP, s) \<Rightarrow> t \<Longrightarrow> t = s" by blast text{* Rule inversion by hand via the ``cases'' method: *} lemma assumes "(IF b THEN SKIP ELSE SKIP, s) \<Rightarrow> t" shows "t = s" proof- from assms show ?thesis proof cases --"inverting assms" case IfTrue thm IfTrue thus ?thesis by blast next case IfFalse thus ?thesis by blast qed qed (* Using rule inversion to prove simplification rules: *) lemma assign_simp: "(x ::= a,s) \<Rightarrow> s' \<longleftrightarrow> (s' = s(x := aval a s))" by auto text {* An example combining rule inversion and derivations *} lemma Seq_assoc: "(c1;; c2;; c3, s) \<Rightarrow> s' \<longleftrightarrow> (c1;; (c2;; c3), s) \<Rightarrow> s'" proof assume "(c1;; c2;; c3, s) \<Rightarrow> s'" then obtain s1 s2 where c1: "(c1, s) \<Rightarrow> s1" and c2: "(c2, s1) \<Rightarrow> s2" and c3: "(c3, s2) \<Rightarrow> s'" by auto from c2 c3 have "(c2;; c3, s1) \<Rightarrow> s'" by (rule Seq) with c1 show "(c1;; (c2;; c3), s) \<Rightarrow> s'" by (rule Seq) next -- "The other direction is analogous" assume "(c1;; (c2;; c3), s) \<Rightarrow> s'" thus "(c1;; c2;; c3, s) \<Rightarrow> s'" by auto qed subsection "Command Equivalence" text {* We call two statements @{text c} and @{text c'} equivalent wrt.\ the big-step semantics when \emph{@{text c} started in @{text s} terminates in @{text s'} iff @{text c'} started in the same @{text s} also terminates in the same @{text s'}}. Formally: *} text_raw{*\snip{BigStepEquiv}{0}{1}{% *} abbreviation equiv_c :: "com \<Rightarrow> com \<Rightarrow> bool" (infix "\<sim>" 50) where "c \<sim> c' \<equiv> (\<forall>s t. (c,s) \<Rightarrow> t = (c',s) \<Rightarrow> t)" text_raw{*}%endsnip*} text {* Warning: @{text"\<sim>"} is the symbol written \verb!\ < s i m >! (without spaces). As an example, we show that loop unfolding is an equivalence transformation on programs: *} lemma unfold_while: "(WHILE b DO c) \<sim> (IF b THEN c;; WHILE b DO c ELSE SKIP)" (is "?w \<sim> ?iw") proof (intro allI, rule) fix s t assume "(?w, s) \<Rightarrow> t" then show "(?iw, s) \<Rightarrow> t" proof cases case WhileFalse then show ?thesis by blast next case (WhileTrue s\<^sub>2) then show ?thesis by blast qed next fix s t assume iw: "(?iw, s) \<Rightarrow> t" then show "(?w,s) \<Rightarrow> t" proof(cases "bval b s") case True then have "(c;; WHILE b DO c, s) \<Rightarrow> t" using iw by auto then obtain s' where "(c,s) \<Rightarrow> s'" and "(?w, s') \<Rightarrow> t" by blast then show "(?w, s) \<Rightarrow> t" using True by auto next case False then have "s=t" using iw by auto moreover have "(?w,s) \<Rightarrow> s" using False by auto ultimately show ?thesis by simp qed qed lemma Or_commute: "a OR b \<sim> b OR a" by blast text {* Luckily, such lengthy proofs are seldom necessary. Isabelle can prove many such facts automatically. *} lemma while_unfold: "(WHILE b DO c) \<sim> (IF b THEN c;; WHILE b DO c ELSE SKIP)" by blast lemma repeat_unfild: "(REPEAT c UNTIL b) \<sim> (IF b THEN SKIP ELSE c ;; (REPEAT c UNTIL b))" by blast lemma triv_if: "(IF b THEN c ELSE c) \<sim> c" by blast lemma commute_if: "(IF b1 THEN (IF b2 THEN c11 ELSE c12) ELSE c2) \<sim> (IF b2 THEN (IF b1 THEN c11 ELSE c2) ELSE (IF b1 THEN c12 ELSE c2))" by blast lemma sim_while_cong_aux: "(WHILE b DO c,s) \<Rightarrow> t \<Longrightarrow> c \<sim> c' \<Longrightarrow> (WHILE b DO c',s) \<Rightarrow> t" proof - assume wc:"(WHILE b DO c,s) \<Rightarrow> t" and "c \<sim> c'" then show "(WHILE b DO c',s) \<Rightarrow> t" (is "?w1 \<Rightarrow> t") proof (induction "WHILE b DO c" s t arbitrary: b c rule: big_step_induct) case (WhileFalse b s c) assume "\<not> bval b s" then show "(WHILE b DO c', s) \<Rightarrow> s" by (rule big_step.WhileFalse) next case (WhileTrue b s\<^sub>1 c s\<^sub>2 s\<^sub>3) then have "(c', s\<^sub>1) \<Rightarrow> s\<^sub>2" using `c \<sim> c'` by auto then show "(WHILE b DO c', s\<^sub>1) \<Rightarrow> s\<^sub>3" using WhileTrue by auto qed qed lemma sim_while_cong: "c \<sim> c' \<Longrightarrow> WHILE b DO c \<sim> WHILE b DO c'" by (metis sim_while_cong_aux) text {* Command equivalence is an equivalence relation, i.e.\ it is reflexive, symmetric, and transitive. Because we used an abbreviation above, Isabelle derives this automatically. *} lemma sim_refl: "c \<sim> c" by simp lemma sim_sym: "(c \<sim> c') = (c' \<sim> c)" by auto lemma sim_trans: "c \<sim> c' \<Longrightarrow> c' \<sim> c'' \<Longrightarrow> c \<sim> c''" by auto subsection "Execution is deterministic when no OR" abbreviation "deterministic c \<equiv> \<forall> s t u. (c,s) \<Rightarrow> t \<and> (c,s) \<Rightarrow> u \<longrightarrow> t = u" fun noOr::"com \<Rightarrow> bool" where "noOr (_ OR _) = False" | "noOr (_ ::= _) = True" | "noOr (a ;; b) = (noOr a \<and> noOr b)" | "noOr (IF _ THEN a ELSE b) = (noOr a \<and> noOr b)" | "noOr (WHILE _ DO c) = noOr c"| "noOr (REPEAT c UNTIL _) = noOr c" | "noOr SKIP = True" text {* This proof is automatic. *} (*lemma while_det: assumes "deterministic c" shows" deterministic (WHILE b DO c)" apply(induction "WHILE b DO c" rule: big_step_induct) *) theorem big_step_determ: "noOr c \<Longrightarrow> deterministic c" proof(induction c rule: noOr.induct, auto) fix a s s1 s2 assume "deterministic a" "(a,s) \<Rightarrow> s1" "(a,s) \<Rightarrow> s2" then have "s1 = s2" by auto fix b t u assume "deterministic b" "(b, s1) \<Rightarrow> t" "(b, s2) \<Rightarrow> u" then show "t = u" using `s1 = s2` by auto next fix c s t u b assume "deterministic c" "(WHILE b DO c, s) \<Rightarrow> t" "(WHILE b DO c, s) \<Rightarrow> u" show "(WHILE b DO c, s) \<Rightarrow> t \<Longrightarrow> (WHILE b DO c, s) \<Rightarrow> u \<Longrightarrow> t = u" apply(induction "WHILE b DO c" s t rule: big_step_induct by(induction c s t arbitrary: u rule: big_step_induct, blast+) text {* This is the proof as you might present it in a lecture. The remaining cases are simple enough to be proved automatically: *} text_raw{*\snip{BigStepDetLong}{0}{2}{% *} theorem "(c,s) \<Rightarrow> t \<Longrightarrow> (c,s) \<Rightarrow> t' \<Longrightarrow> t' = t" proof (induction arbitrary: t' rule: big_step.induct) -- "the only interesting case, @{text WhileTrue}:" fix b c s s\<^sub>1 t t' -- "The assumptions of the rule:" assume "bval b s" and "(c,s) \<Rightarrow> s\<^sub>1" and "(WHILE b DO c,s\<^sub>1) \<Rightarrow> t" -- {* Ind.Hyp; note the @{text"\<And>"} because of arbitrary: *} assume IHc: "\<And>t'. (c,s) \<Rightarrow> t' \<Longrightarrow> t' = s\<^sub>1" assume IHw: "\<And>t'. (WHILE b DO c,s\<^sub>1) \<Rightarrow> t' \<Longrightarrow> t' = t" -- "Premise of implication:" assume "(WHILE b DO c,s) \<Rightarrow> t'" with `bval b s` obtain s\<^sub>1' where c: "(c,s) \<Rightarrow> s\<^sub>1'" and w: "(WHILE b DO c,s\<^sub>1') \<Rightarrow> t'" by auto from c IHc have "s\<^sub>1' = s\<^sub>1" by blast with w IHw show "t' = t" by blast qed blast+ -- "prove the rest automatically" text_raw{*}%endsnip*} fun assigned :: "com \<Rightarrow> vname set" where "assigned (v ::= _) = {v}" | "assigned SKIP = {}" | "assigned (a;;b) = assigned a \<union> assigned b" | "assigned (IF b THEN c1 ELSE c2) = assigned c1 \<union> assigned c2" | "assigned (WHILE b DO c) = assigned c" | "assigned (REPEAT c UNTIL b) = assigned c" lemma "\<lbrakk>(c, s) \<Rightarrow> t ; x \<notin> assigned c\<rbrakk> \<Longrightarrow> s x = t x" by(induction c s t rule: big_step_induct, auto) inductive astep :: "aexp \<times> state \<Rightarrow> aexp \<Rightarrow> bool" (infix "\<leadsto>" 50) where "(V x, s) \<leadsto> N (s x)" | "(Plus (N a) (N b), _) \<leadsto> N (a + b)" | "(a, s) \<leadsto> a1 \<Longrightarrow> (Plus a b,s) \<leadsto> Plus a1 b" | "(b, s) \<leadsto> b1 \<Longrightarrow> (Plus (N a) b, s) \<leadsto> Plus (N a) b1" lemmas astep_induct = astep.induct[split_format(complete)] lemma "(a, s) \<leadsto> a' \<Longrightarrow> aval a s = aval a' s" by(induction a s a' rule: astep_induct, auto) fun doWhile :: "bexp \<Rightarrow> com \<Rightarrow> com" where "doWhile b c = c ;; WHILE b DO c" fun dewhile :: "com \<Rightarrow> com" where "dewhile SKIP = SKIP" | "dewhile (a::=b) = (a::=b)"| "dewhile (a;;b) = (dewhile a) ;; (dewhile b)"| "dewhile (IF b THEN c ELSE d) = (IF b THEN dewhile c ELSE dewhile d)"| "dewhile (WHILE b DO c) = IF b THEN doWhile b c ELSE SKIP" | "dewhile (REPEAT c UNTIL b) = IF b THEN SKIP ELSE doWhile (Not b) c" lemma Repeat_suger: "(REPEAT c UNTIL b) \<sim> (WHILE (Not b) DO c)" proof (intro allI, rule) fix s t assume "(REPEAT c UNTIL b, s) \<Rightarrow> t " then show " (WHILE bexp.Not b DO c, s) \<Rightarrow> t" proof(induction "REPEAT c UNTIL b" s t rule: big_step_induct) fix s assume "bval b s" then have "bval (Not b) s = False" by auto then show "(WHILE bexp.Not b DO c, s) \<Rightarrow> s" by auto next fix s s' t assume "\<not> bval b s" then have 1: "bval (Not b) s" by auto assume " (c, s) \<Rightarrow> s'" and "(WHILE bexp.Not b DO c, s') \<Rightarrow> t" then show "(WHILE bexp.Not b DO c, s) \<Rightarrow> t" using 1 by auto qed next fix s t show "(WHILE bexp.Not b DO c, s) \<Rightarrow> t \<Longrightarrow> (REPEAT c UNTIL b, s) \<Rightarrow> t" by(induction "WHILE bexp.Not b DO c" s t rule: big_step_induct, auto) qed lemma "dewhile c \<sim> c" apply(induction c rule: dewhile.induct) by(auto simp add: Repeat_suger while_unfold) end
module New.FunctionLemmas where open import New.Changes module BinaryValid {A : Set} {{CA : ChAlg A}} {B : Set} {{CB : ChAlg B}} {C : Set} {{CC : ChAlg C}} (f : A → B → C) (df : A → Ch A → B → Ch B → Ch C) where binary-valid-preserve-hp = ∀ a da (ada : valid a da) b db (bdb : valid b db) → valid (f a b) (df a da b db) binary-valid-eq-hp = ∀ a da (ada : valid a da) b db (bdb : valid b db) → (f ⊕ df) (a ⊕ da) (b ⊕ db) ≡ f a b ⊕ df a da b db binary-valid : binary-valid-preserve-hp → binary-valid-eq-hp → valid f df binary-valid ext-valid proof a da ada = (λ b db bdb → ext-valid a da ada b db bdb , lem2 b db bdb) , ext lem1 where lem1 : ∀ b → f (a ⊕ da) b ⊕ df (a ⊕ da) (nil (a ⊕ da)) b (nil b) ≡ f a b ⊕ df a da b (nil b) lem1 b rewrite sym (update-nil b) | proof a da ada b (nil b) (nil-valid b) | update-nil b = refl lem2 : ∀ b (db : Ch B) (bdb : valid b db) → f a (b ⊕ db) ⊕ df a da (b ⊕ db) (nil (b ⊕ db)) ≡ f a b ⊕ df a da b db lem2 b db bdb rewrite sym (proof a da ada (b ⊕ db) (nil (b ⊕ db)) (nil-valid (b ⊕ db))) | update-nil (b ⊕ db) = proof a da ada b db bdb module TernaryValid {A : Set} {{CA : ChAlg A}} {B : Set} {{CB : ChAlg B}} {C : Set} {{CC : ChAlg C}} {D : Set} {{CD : ChAlg D}} (f : A → B → C → D) (df : A → Ch A → B → Ch B → C → Ch C → Ch D) where ternary-valid-preserve-hp = ∀ a da (ada : valid a da) b db (bdb : valid b db) c dc (cdc : valid c dc) → valid (f a b c) (df a da b db c dc) -- These are explicit definitions only to speed up typechecking. CA→B→C→D : ChAlg (A → B → C → D) CA→B→C→D = funCA f⊕df = (_⊕_ {{CA→B→C→D}} f df) -- Already this definition takes a while to typecheck. ternary-valid-eq-hp = ∀ a (da : Ch A {{CA}}) (ada : valid {{CA}} a da) b (db : Ch B {{CB}}) (bdb : valid {{CB}} b db) c (dc : Ch C {{CC}}) (cdc : valid {{CC}} c dc) → f⊕df (a ⊕ da) (b ⊕ db) (c ⊕ dc) ≡ f a b c ⊕ df a da b db c dc ternary-valid : ternary-valid-preserve-hp → ternary-valid-eq-hp → valid f df ternary-valid ext-valid proof a da ada = binary-valid (λ b db bdb c dc cdc → ext-valid a da ada b db bdb c dc cdc) lem2 , ext (λ b → ext (lem1 b)) where open BinaryValid (f a) (df a da) lem1 : ∀ b c → f⊕df (a ⊕ da) b c ≡ (f a ⊕ df a da) b c lem1 b c rewrite sym (update-nil b) | sym (update-nil c) | proof a da ada b (nil b) (nil-valid b) c (nil c) (nil-valid c) | update-nil b | update-nil c = refl -- rewrite -- sym -- (proof -- (a ⊕ da) (nil (a ⊕ da)) (nil-valid (a ⊕ da)) -- b (nil b) (nil-valid b) -- c (nil c) (nil-valid c)) -- | update-nil (a ⊕ da) -- | update-nil b -- | update-nil c = {! !} lem2 : ∀ b db (bdb : valid b db) c dc (cdc : valid c dc) → (f a ⊕ df a da) (b ⊕ db) (c ⊕ dc) ≡ f a b c ⊕ df a da b db c dc lem2 b db bdb c dc cdc rewrite sym (proof a da ada (b ⊕ db) (nil (b ⊕ db)) (nil-valid (b ⊕ db)) (c ⊕ dc) (nil (c ⊕ dc)) (nil-valid (c ⊕ dc)) ) | update-nil (b ⊕ db) | update-nil (c ⊕ dc) = proof a da ada b db bdb c dc cdc
------------------------------------------------------------------------ -- The Agda standard library -- -- Streams ------------------------------------------------------------------------ module Data.Stream where open import Coinduction open import Data.Colist using (Colist; []; _∷_) open import Data.Vec using (Vec; []; _∷_) open import Data.Nat using (ℕ; zero; suc) open import Relation.Binary open import Relation.Binary.PropositionalEquality as P using (_≡_) ------------------------------------------------------------------------ -- The type infixr 5 _∷_ data Stream (A : Set) : Set where _∷_ : (x : A) (xs : ∞ (Stream A)) → Stream A {-# IMPORT Data.FFI #-} {-# COMPILED_DATA Stream Data.FFI.AgdaStream Data.FFI.Cons #-} ------------------------------------------------------------------------ -- Some operations head : ∀ {A} → Stream A → A head (x ∷ xs) = x tail : ∀ {A} → Stream A → Stream A tail (x ∷ xs) = ♭ xs map : ∀ {A B} → (A → B) → Stream A → Stream B map f (x ∷ xs) = f x ∷ ♯ map f (♭ xs) zipWith : ∀ {A B C} → (A → B → C) → Stream A → Stream B → Stream C zipWith _∙_ (x ∷ xs) (y ∷ ys) = (x ∙ y) ∷ ♯ zipWith _∙_ (♭ xs) (♭ ys) take : ∀ {A} n → Stream A → Vec A n take zero xs = [] take (suc n) (x ∷ xs) = x ∷ take n (♭ xs) drop : ∀ {A} → ℕ → Stream A → Stream A drop zero xs = xs drop (suc n) (x ∷ xs) = drop n (♭ xs) repeat : ∀ {A} → A → Stream A repeat x = x ∷ ♯ repeat x iterate : ∀ {A} → (A → A) → A → Stream A iterate f x = x ∷ ♯ iterate f (f x) -- Interleaves the two streams. infixr 5 _⋎_ _⋎_ : ∀ {A} → Stream A → Stream A → Stream A (x ∷ xs) ⋎ ys = x ∷ ♯ (ys ⋎ ♭ xs) mutual -- Takes every other element from the stream, starting with the -- first one. evens : ∀ {A} → Stream A → Stream A evens (x ∷ xs) = x ∷ ♯ odds (♭ xs) -- Takes every other element from the stream, starting with the -- second one. odds : ∀ {A} → Stream A → Stream A odds (x ∷ xs) = evens (♭ xs) toColist : ∀ {A} → Stream A → Colist A toColist (x ∷ xs) = x ∷ ♯ toColist (♭ xs) lookup : ∀ {A} → ℕ → Stream A → A lookup zero (x ∷ xs) = x lookup (suc n) (x ∷ xs) = lookup n (♭ xs) infixr 5 _++_ _++_ : ∀ {A} → Colist A → Stream A → Stream A [] ++ ys = ys (x ∷ xs) ++ ys = x ∷ ♯ (♭ xs ++ ys) ------------------------------------------------------------------------ -- Equality and other relations -- xs ≈ ys means that xs and ys are equal. infix 4 _≈_ data _≈_ {A} : Stream A → Stream A → Set where _∷_ : ∀ {x y xs ys} (x≡ : x ≡ y) (xs≈ : ∞ (♭ xs ≈ ♭ ys)) → x ∷ xs ≈ y ∷ ys -- x ∈ xs means that x is a member of xs. infix 4 _∈_ data _∈_ {A} : A → Stream A → Set where here : ∀ {x xs} → x ∈ x ∷ xs there : ∀ {x y xs} (x∈xs : x ∈ ♭ xs) → x ∈ y ∷ xs -- xs ⊑ ys means that xs is a prefix of ys. infix 4 _⊑_ data _⊑_ {A} : Colist A → Stream A → Set where [] : ∀ {ys} → [] ⊑ ys _∷_ : ∀ x {xs ys} (p : ∞ (♭ xs ⊑ ♭ ys)) → x ∷ xs ⊑ x ∷ ys ------------------------------------------------------------------------ -- Some proofs setoid : Set → Setoid _ _ setoid A = record { Carrier = Stream A ; _≈_ = _≈_ {A} ; isEquivalence = record { refl = refl ; sym = sym ; trans = trans } } where refl : Reflexive _≈_ refl {_ ∷ _} = P.refl ∷ ♯ refl sym : Symmetric _≈_ sym (x≡ ∷ xs≈) = P.sym x≡ ∷ ♯ sym (♭ xs≈) trans : Transitive _≈_ trans (x≡ ∷ xs≈) (y≡ ∷ ys≈) = P.trans x≡ y≡ ∷ ♯ trans (♭ xs≈) (♭ ys≈) head-cong : ∀ {A} {xs ys : Stream A} → xs ≈ ys → head xs ≡ head ys head-cong (x≡ ∷ _) = x≡ tail-cong : ∀ {A} {xs ys : Stream A} → xs ≈ ys → tail xs ≈ tail ys tail-cong (_ ∷ xs≈) = ♭ xs≈ map-cong : ∀ {A B} (f : A → B) {xs ys} → xs ≈ ys → map f xs ≈ map f ys map-cong f (x≡ ∷ xs≈) = P.cong f x≡ ∷ ♯ map-cong f (♭ xs≈) zipWith-cong : ∀ {A B C} (_∙_ : A → B → C) {xs xs′ ys ys′} → xs ≈ xs′ → ys ≈ ys′ → zipWith _∙_ xs ys ≈ zipWith _∙_ xs′ ys′ zipWith-cong _∙_ (x≡ ∷ xs≈) (y≡ ∷ ys≈) = P.cong₂ _∙_ x≡ y≡ ∷ ♯ zipWith-cong _∙_ (♭ xs≈) (♭ ys≈) infixr 5 _⋎-cong_ _⋎-cong_ : ∀ {A} {xs xs′ ys ys′ : Stream A} → xs ≈ xs′ → ys ≈ ys′ → xs ⋎ ys ≈ xs′ ⋎ ys′ (x ∷ xs≈) ⋎-cong ys≈ = x ∷ ♯ (ys≈ ⋎-cong ♭ xs≈)
module Main mutual evenT : Nat -> IO Bool evenT Z = pure True evenT (S k) = oddT k oddT : Nat -> IO Bool oddT Z = pure False oddT (S k) = evenT k main : IO () main = evenT 99999 >>= printLn
Kate Greenaway was a childhood favorite and an influence on her art . Barker 's child subjects wear nostalgic clothing as Greenaway 's children do , though Barker 's children are less melancholy and less flat in appearance , due perhaps to advances in printing technology . Barker studied flowers with an analytical eye and was friend to children 's illustrator , Margaret Tarrant . Along with Greenaway , illustrator Alice B. Woodward also influenced Barker 's work .
lemma complex_i_not_one [simp]: "\<i> \<noteq> 1"
lemma fixes c :: "'a::euclidean_space \<Rightarrow> real" and t assumes c: "\<And>j. j \<in> Basis \<Longrightarrow> c j \<noteq> 0" defines "T == (\<lambda>x. t + (\<Sum>j\<in>Basis. (c j * (x \<bullet> j)) *\<^sub>R j))" shows lebesgue_affine_euclidean: "lebesgue = density (distr lebesgue lebesgue T) (\<lambda>_. (\<Prod>j\<in>Basis. \<bar>c j\<bar>))" (is "_ = ?D") and lebesgue_affine_measurable: "T \<in> lebesgue \<rightarrow>\<^sub>M lebesgue"
State Before: ι : Type u_1 ι' : Type ?u.8988 α : ι → Type u_2 β : ι → Type ?u.8998 s s₁ s₂ : Set ι t t₁ t₂ : (i : ι) → Set (α i) u : Set ((i : ι) × α i) x : (i : ι) × α i i j : ι a : α i ⊢ Set.Sigma s₁ t₁ ∩ Set.Sigma s₂ t₂ = Set.Sigma (s₁ ∩ s₂) fun i => t₁ i ∩ t₂ i State After: case h.mk ι : Type u_1 ι' : Type ?u.8988 α : ι → Type u_2 β : ι → Type ?u.8998 s s₁ s₂ : Set ι t t₁ t₂ : (i : ι) → Set (α i) u : Set ((i : ι) × α i) x✝ : (i : ι) × α i i j : ι a : α i x : ι y : α x ⊢ { fst := x, snd := y } ∈ Set.Sigma s₁ t₁ ∩ Set.Sigma s₂ t₂ ↔ { fst := x, snd := y } ∈ Set.Sigma (s₁ ∩ s₂) fun i => t₁ i ∩ t₂ i Tactic: ext ⟨x, y⟩ State Before: case h.mk ι : Type u_1 ι' : Type ?u.8988 α : ι → Type u_2 β : ι → Type ?u.8998 s s₁ s₂ : Set ι t t₁ t₂ : (i : ι) → Set (α i) u : Set ((i : ι) × α i) x✝ : (i : ι) × α i i j : ι a : α i x : ι y : α x ⊢ { fst := x, snd := y } ∈ Set.Sigma s₁ t₁ ∩ Set.Sigma s₂ t₂ ↔ { fst := x, snd := y } ∈ Set.Sigma (s₁ ∩ s₂) fun i => t₁ i ∩ t₂ i State After: no goals Tactic: simp [and_assoc, and_left_comm]
theory Hybrid_Logic imports "HOL-Library.Countable" begin section \<open>Syntax\<close> datatype ('a, 'b) fm = Pro 'a | Nom 'b | Neg \<open>('a, 'b) fm\<close> (\<open>\<^bold>\<not> _\<close> [40] 40) | Dis \<open>('a, 'b) fm\<close> \<open>('a, 'b) fm\<close> (infixr \<open>\<^bold>\<or>\<close> 30) | Dia \<open>('a, 'b) fm\<close> (\<open>\<^bold>\<diamond> _\<close> 10) | Sat 'b \<open>('a, 'b) fm\<close> (\<open>\<^bold>@ _ _\<close> 10) text \<open>We can give other connectives as abbreviations.\<close> abbreviation Top (\<open>\<^bold>\<top>\<close>) where \<open>\<^bold>\<top> \<equiv> (undefined \<^bold>\<or> \<^bold>\<not> undefined)\<close> abbreviation Con (infixr \<open>\<^bold>\<and>\<close> 35) where \<open>p \<^bold>\<and> q \<equiv> \<^bold>\<not> (\<^bold>\<not> p \<^bold>\<or> \<^bold>\<not> q)\<close> abbreviation Imp (infixr \<open>\<^bold>\<longrightarrow>\<close> 25) where \<open>p \<^bold>\<longrightarrow> q \<equiv> \<^bold>\<not> (p \<^bold>\<and> \<^bold>\<not> q)\<close> abbreviation Box (\<open>\<^bold>\<box> _\<close> 10) where \<open>\<^bold>\<box> p \<equiv> \<^bold>\<not> (\<^bold>\<diamond> \<^bold>\<not> p)\<close> primrec nominals :: \<open>('a, 'b) fm \<Rightarrow> 'b set\<close> where \<open>nominals (Pro x) = {}\<close> | \<open>nominals (Nom i) = {i}\<close> | \<open>nominals (\<^bold>\<not> p) = nominals p\<close> | \<open>nominals (p \<^bold>\<or> q) = nominals p \<union> nominals q\<close> | \<open>nominals (\<^bold>\<diamond> p) = nominals p\<close> | \<open>nominals (\<^bold>@ i p) = {i} \<union> nominals p\<close> primrec sub :: \<open>('b \<Rightarrow> 'c) \<Rightarrow> ('a, 'b) fm \<Rightarrow> ('a, 'c) fm\<close> where \<open>sub _ (Pro x) = Pro x\<close> | \<open>sub f (Nom i) = Nom (f i)\<close> | \<open>sub f (\<^bold>\<not> p) = (\<^bold>\<not> sub f p)\<close> | \<open>sub f (p \<^bold>\<or> q) = (sub f p \<^bold>\<or> sub f q)\<close> | \<open>sub f (\<^bold>\<diamond> p) = (\<^bold>\<diamond> sub f p)\<close> | \<open>sub f (\<^bold>@ i p) = (\<^bold>@ (f i) (sub f p))\<close> lemma sub_nominals: \<open>nominals (sub f p) = f ` nominals p\<close> by (induct p) auto lemma sub_id: \<open>sub id p = p\<close> by (induct p) simp_all lemma sub_upd_fresh: \<open>i \<notin> nominals p \<Longrightarrow> sub (f(i := j)) p = sub f p\<close> by (induct p) auto section \<open>Semantics\<close> text \<open> Type variable \<open>'w\<close> stands for the set of worlds and \<open>'a\<close> for the set of propositional symbols. The accessibility relation is given by \<open>R\<close> and the valuation by \<open>V\<close>. The mapping from nominals to worlds is an extra argument \<open>g\<close> to the semantics.\<close> datatype ('w, 'a) model = Model (R: \<open>'w \<Rightarrow> 'w set\<close>) (V: \<open>'w \<Rightarrow> 'a \<Rightarrow> bool\<close>) primrec semantics :: \<open>('w, 'a) model \<Rightarrow> ('b \<Rightarrow> 'w) \<Rightarrow> 'w \<Rightarrow> ('a, 'b) fm \<Rightarrow> bool\<close> (\<open>_, _, _ \<Turnstile> _\<close> [50, 50, 50] 50) where \<open>(M, _, w \<Turnstile> Pro x) = V M w x\<close> | \<open>(_, g, w \<Turnstile> Nom i) = (w = g i)\<close> | \<open>(M, g, w \<Turnstile> \<^bold>\<not> p) = (\<not> M, g, w \<Turnstile> p)\<close> | \<open>(M, g, w \<Turnstile> (p \<^bold>\<or> q)) = ((M, g, w \<Turnstile> p) \<or> (M, g, w \<Turnstile> q))\<close> | \<open>(M, g, w \<Turnstile> \<^bold>\<diamond> p) = (\<exists>v \<in> R M w. M, g, v \<Turnstile> p)\<close> | \<open>(M, g, _ \<Turnstile> \<^bold>@ i p) = (M, g, g i \<Turnstile> p)\<close> lemma \<open>M, g, w \<Turnstile> \<^bold>\<top>\<close> by simp lemma semantics_fresh: \<open>i \<notin> nominals p \<Longrightarrow> (M, g, w \<Turnstile> p) = (M, g(i := v), w \<Turnstile> p)\<close> by (induct p arbitrary: w) auto subsection \<open>Examples\<close> abbreviation is_named :: \<open>('w, 'b) model \<Rightarrow> bool\<close> where \<open>is_named M \<equiv> \<forall>w. \<exists>a. V M a = w\<close> abbreviation reflexive :: \<open>('w, 'b) model \<Rightarrow> bool\<close> where \<open>reflexive M \<equiv> \<forall>w. w \<in> R M w\<close> abbreviation irreflexive :: \<open>('w, 'b) model \<Rightarrow> bool\<close> where \<open>irreflexive M \<equiv> \<forall>w. w \<notin> R M w\<close> abbreviation symmetric :: \<open>('w, 'b) model \<Rightarrow> bool\<close> where \<open>symmetric M \<equiv> \<forall>v w. w \<in> R M v \<longleftrightarrow> v \<in> R M w\<close> abbreviation asymmetric :: \<open>('w, 'b) model \<Rightarrow> bool\<close> where \<open>asymmetric M \<equiv> \<forall>v w. \<not> (w \<in> R M v \<and> v \<in> R M w)\<close> abbreviation transitive :: \<open>('w, 'b) model \<Rightarrow> bool\<close> where \<open>transitive M \<equiv> \<forall>v w x. w \<in> R M v \<and> x \<in> R M w \<longrightarrow> x \<in> R M v\<close> abbreviation universal :: \<open>('w, 'b) model \<Rightarrow> bool\<close> where \<open>universal M \<equiv> \<forall>v w. v \<in> R M w\<close> lemma \<open>irreflexive M \<Longrightarrow> M, g, w \<Turnstile> \<^bold>@ i \<^bold>\<not> (\<^bold>\<diamond> Nom i)\<close> proof - assume \<open>irreflexive M\<close> then have \<open>g i \<notin> R M (g i)\<close> by simp then have \<open>\<not> M, g, g i \<Turnstile> \<^bold>\<diamond> Nom i\<close> by simp then have \<open>M, g, g i \<Turnstile> \<^bold>\<not> (\<^bold>\<diamond> Nom i)\<close> by simp then show \<open>M, g, w \<Turnstile> \<^bold>@ i \<^bold>\<not> (\<^bold>\<diamond> Nom i)\<close> by simp qed text \<open>We can automatically show some characterizations of frames by pure axioms.\<close> lemma \<open>irreflexive M = (\<forall>g w. M, g, w \<Turnstile> \<^bold>@ i \<^bold>\<not> (\<^bold>\<diamond> Nom i))\<close> by auto lemma \<open>asymmetric M = (\<forall>g w. M, g, w \<Turnstile> \<^bold>@ i (\<^bold>\<box> \<^bold>\<not> (\<^bold>\<diamond> Nom i)))\<close> by auto lemma \<open>universal M = (\<forall>g w. M, g, w \<Turnstile> \<^bold>\<diamond> Nom i)\<close> by auto section \<open>Tableau\<close> text \<open> A block is defined as a list of formulas paired with an opening nominal. The opening nominal is not necessarily in the list. A branch is a list of blocks. \<close> type_synonym ('a, 'b) block = \<open>('a, 'b) fm list \<times> 'b\<close> type_synonym ('a, 'b) branch = \<open>('a, 'b) block list\<close> abbreviation member_list :: \<open>'a \<Rightarrow> 'a list \<Rightarrow> bool\<close> (\<open>_ \<in>. _\<close> [51, 51] 50) where \<open>x \<in>. xs \<equiv> x \<in> set xs\<close> text \<open>The predicate \<open>on\<close> presents the opening nominal as appearing on the block.\<close> primrec on :: \<open>('a, 'b) fm \<Rightarrow> ('a, 'b) block \<Rightarrow> bool\<close> (\<open>_ on _\<close> [51, 51] 50) where \<open>p on (ps, i) = (p \<in>. ps \<or> p = Nom i)\<close> syntax "_Ballon" :: \<open>pttrn \<Rightarrow> 'a set \<Rightarrow> bool \<Rightarrow> bool\<close> (\<open>(3\<forall>(_/on_)./ _)\<close> [0, 0, 10] 10) "_Bexon" :: \<open>pttrn \<Rightarrow> 'a set \<Rightarrow> bool \<Rightarrow> bool\<close> (\<open>(3\<exists>(_/on_)./ _)\<close> [0, 0, 10] 10) translations "\<forall>p on A. P" \<rightharpoonup> "\<forall>p. p on A \<longrightarrow> P" "\<exists>p on A. P" \<rightharpoonup> "\<exists>p. p on A \<and> P" abbreviation list_nominals :: \<open>('a, 'b) fm list \<Rightarrow> 'b set\<close> where \<open>list_nominals ps \<equiv> (\<Union>p \<in> set ps. nominals p)\<close> primrec block_nominals :: \<open>('a, 'b) block \<Rightarrow> 'b set\<close> where \<open>block_nominals (ps, i) = {i} \<union> list_nominals ps\<close> definition branch_nominals :: \<open>('a, 'b) branch \<Rightarrow> 'b set\<close> where \<open>branch_nominals branch \<equiv> (\<Union>block \<in> set branch. block_nominals block)\<close> abbreviation at_in_branch :: \<open>('a, 'b) fm \<Rightarrow> 'b \<Rightarrow> ('a, 'b) branch \<Rightarrow> bool\<close> where \<open>at_in_branch p a branch \<equiv> \<exists>ps. (ps, a) \<in>. branch \<and> p on (ps, a)\<close> notation at_in_branch (\<open>_ at _ in _\<close> [51, 51, 51] 50) definition new :: \<open>('a, 'b) fm \<Rightarrow> 'b \<Rightarrow> ('a, 'b) branch \<Rightarrow> bool\<close> where \<open>new p a branch \<equiv> \<not> p at a in branch\<close> definition witnessed :: \<open>('a, 'b) fm \<Rightarrow> 'b \<Rightarrow> ('a, 'b) branch \<Rightarrow> bool\<close> where \<open>witnessed p a branch \<equiv> \<exists>i. (\<^bold>@ i p) at a in branch \<and> (\<^bold>\<diamond> Nom i) at a in branch\<close> text \<open> A branch has a closing tableau iff it is contained in the following inductively defined set. In that case I call the branch closeable. The first argument on the left of the turnstile, \<open>A\<close>, is a fixed set of nominals restricting Nom. This set rules out the copying of nominals and accessibility formulas introduced by DiaP. The second argument is "potential", used to restrict the GoTo rule. \<close> inductive STA :: \<open>'b set \<Rightarrow> nat \<Rightarrow> ('a, 'b) branch \<Rightarrow> bool\<close> (\<open>_, _ \<turnstile> _\<close> [50, 50, 50] 50) for A :: \<open>'b set\<close> where Close: \<open>p at i in branch \<Longrightarrow> (\<^bold>\<not> p) at i in branch \<Longrightarrow> A, n \<turnstile> branch\<close> | Neg: \<open>(\<^bold>\<not> \<^bold>\<not> p) at a in (ps, a) # branch \<Longrightarrow> new p a ((ps, a) # branch) \<Longrightarrow> A, Suc n \<turnstile> (p # ps, a) # branch \<Longrightarrow> A, n \<turnstile> (ps, a) # branch\<close> | DisP: \<open>(p \<^bold>\<or> q) at a in (ps, a) # branch \<Longrightarrow> new p a ((ps, a) # branch) \<Longrightarrow> new q a ((ps, a) # branch) \<Longrightarrow> A, Suc n \<turnstile> (p # ps, a) # branch \<Longrightarrow> A, Suc n \<turnstile> (q # ps, a) # branch \<Longrightarrow> A, n \<turnstile> (ps, a) # branch\<close> | DisN: \<open>(\<^bold>\<not> (p \<^bold>\<or> q)) at a in (ps, a) # branch \<Longrightarrow> new (\<^bold>\<not> p) a ((ps, a) # branch) \<or> new (\<^bold>\<not> q) a ((ps, a) # branch) \<Longrightarrow> A, Suc n \<turnstile> ((\<^bold>\<not> q) # (\<^bold>\<not> p) # ps, a) # branch \<Longrightarrow> A, n \<turnstile> (ps, a) # branch\<close> | DiaP: \<open>(\<^bold>\<diamond> p) at a in (ps, a) # branch \<Longrightarrow> i \<notin> A \<union> branch_nominals ((ps, a) # branch) \<Longrightarrow> \<nexists>a. p = Nom a \<Longrightarrow> \<not> witnessed p a ((ps, a) # branch) \<Longrightarrow> A, Suc n \<turnstile> ((\<^bold>@ i p) # (\<^bold>\<diamond> Nom i) # ps, a) # branch \<Longrightarrow> A, n \<turnstile> (ps, a) # branch\<close> | DiaN: \<open>(\<^bold>\<not> (\<^bold>\<diamond> p)) at a in (ps, a) # branch \<Longrightarrow> (\<^bold>\<diamond> Nom i) at a in (ps, a) # branch \<Longrightarrow> new (\<^bold>\<not> (\<^bold>@ i p)) a ((ps, a) # branch) \<Longrightarrow> A, Suc n \<turnstile> ((\<^bold>\<not> (\<^bold>@ i p)) # ps, a) # branch \<Longrightarrow> A, n \<turnstile> (ps, a) # branch\<close> | SatP: \<open>(\<^bold>@ a p) at b in (ps, a) # branch \<Longrightarrow> new p a ((ps, a) # branch) \<Longrightarrow> A, Suc n \<turnstile> (p # ps, a) # branch \<Longrightarrow> A, n \<turnstile> (ps, a) # branch\<close> | SatN: \<open>(\<^bold>\<not> (\<^bold>@ a p)) at b in (ps, a) # branch \<Longrightarrow> new (\<^bold>\<not> p) a ((ps, a) # branch) \<Longrightarrow> A, Suc n \<turnstile> ((\<^bold>\<not> p) # ps, a) # branch \<Longrightarrow> A, n \<turnstile> (ps, a) # branch\<close> | GoTo: \<open>i \<in> branch_nominals branch \<Longrightarrow> A, n \<turnstile> ([], i) # branch \<Longrightarrow> A, Suc n \<turnstile> branch\<close> | Nom: \<open>p at b in (ps, a) # branch \<Longrightarrow> Nom a at b in (ps, a) # branch \<Longrightarrow> \<forall>i. p = Nom i \<or> p = (\<^bold>\<diamond> Nom i) \<longrightarrow> i \<in> A \<Longrightarrow> new p a ((ps, a) # branch) \<Longrightarrow> A, Suc n \<turnstile> (p # ps, a) # branch \<Longrightarrow> A, n \<turnstile> (ps, a) # branch\<close> abbreviation STA_ex_potential :: \<open>'b set \<Rightarrow> ('a, 'b) branch \<Rightarrow> bool\<close> (\<open>_ \<turnstile> _\<close> [50, 50] 50) where \<open>A \<turnstile> branch \<equiv> \<exists>n. A, n \<turnstile> branch\<close> lemma STA_Suc: \<open>A, n \<turnstile> branch \<Longrightarrow> A, Suc n \<turnstile> branch\<close> by (induct n branch rule: STA.induct) (simp_all add: STA.intros) text \<open>A verified derivation in the calculus.\<close> lemma fixes i defines \<open>p \<equiv> \<^bold>\<not> (\<^bold>@ i (Nom i))\<close> shows \<open>A, Suc n \<turnstile> [([p], a)]\<close> proof - have \<open>i \<in> branch_nominals [([p], a)]\<close> unfolding p_def branch_nominals_def by simp then have ?thesis if \<open>A, n \<turnstile> [([], i), ([p], a)]\<close> using that GoTo by fast moreover have \<open>new (\<^bold>\<not> Nom i) i [([], i), ([p], a)]\<close> unfolding p_def new_def by auto moreover have \<open>(\<^bold>\<not> (\<^bold>@ i (Nom i))) at a in [([], i), ([p], a)]\<close> unfolding p_def by fastforce ultimately have ?thesis if \<open>A, Suc n \<turnstile> [([\<^bold>\<not> Nom i], i), ([p], a)]\<close> using that SatN by fast then show ?thesis by (meson Close list.set_intros(1) on.simps) qed section \<open>Soundness\<close> text \<open> An \<open>i\<close>-block is satisfied by a model \<open>M\<close> and assignment \<open>g\<close> if all formulas on the block are true under \<open>M\<close> at the world \<open>g i\<close> A branch is satisfied by a model and assignment if all blocks on it are. \<close> primrec block_sat :: \<open>('w, 'a) model \<Rightarrow> ('b \<Rightarrow> 'w) \<Rightarrow> ('a, 'b) block \<Rightarrow> bool\<close> (\<open>_, _ \<Turnstile>\<^sub>B _\<close> [50, 50] 50) where \<open>(M, g \<Turnstile>\<^sub>B (ps, i)) = (\<forall>p on (ps, i). M, g, g i \<Turnstile> p)\<close> abbreviation branch_sat :: \<open>('w, 'a) model \<Rightarrow> ('b \<Rightarrow> 'w) \<Rightarrow> ('a, 'b) branch \<Rightarrow> bool\<close> (\<open>_, _ \<Turnstile>\<^sub>\<Theta> _\<close> [50, 50] 50) where \<open>M, g \<Turnstile>\<^sub>\<Theta> branch \<equiv> \<forall>(ps, i) \<in> set branch. M, g \<Turnstile>\<^sub>B (ps, i)\<close> lemma block_nominals: \<open>p on block \<Longrightarrow> i \<in> nominals p \<Longrightarrow> i \<in> block_nominals block\<close> by (induct block) auto lemma block_sat_fresh: assumes \<open>M, g \<Turnstile>\<^sub>B block\<close> \<open>i \<notin> block_nominals block\<close> shows \<open>M, g(i := v) \<Turnstile>\<^sub>B block\<close> using assms proof (induct block) case (Pair ps a) then have \<open>\<forall>p on (ps, a). i \<notin> nominals p\<close> using block_nominals by fast moreover have \<open>i \<noteq> a\<close> using calculation by simp ultimately have \<open>\<forall>p on (ps, a). M, g(i := v), (g(i := v)) a \<Turnstile> p\<close> using Pair semantics_fresh by fastforce then show ?case by (meson block_sat.simps) qed lemma branch_sat_fresh: assumes \<open>M, g \<Turnstile>\<^sub>\<Theta> branch\<close> \<open>i \<notin> branch_nominals branch\<close> shows \<open>M, g(i := v) \<Turnstile>\<^sub>\<Theta> branch\<close> using assms using block_sat_fresh unfolding branch_nominals_def by fast text \<open>If a branch has a derivation then it cannot be satisfied.\<close> lemma soundness': \<open>A, n \<turnstile> branch \<Longrightarrow> M, g \<Turnstile>\<^sub>\<Theta> branch \<Longrightarrow> False\<close> proof (induct n branch arbitrary: g rule: STA.induct) case (Close p i branch) then have \<open>M, g, g i \<Turnstile> p\<close> \<open>M, g, g i \<Turnstile> \<^bold>\<not> p\<close> by fastforce+ then show ?case by simp next case (Neg p a ps branch) have \<open>M, g, g a \<Turnstile> p\<close> using Neg(1, 5) by fastforce then have \<open>M, g \<Turnstile>\<^sub>\<Theta> (p # ps, a) # branch\<close> using Neg(5) by simp then show ?case using Neg(4) by blast next case (DisP p q a ps branch) consider \<open>M, g, g a \<Turnstile> p\<close> | \<open>M, g, g a \<Turnstile> q\<close> using DisP(1, 8) by fastforce then consider \<open>M, g \<Turnstile>\<^sub>\<Theta> (p # ps, a) # branch\<close> | \<open>M, g \<Turnstile>\<^sub>\<Theta> (q # ps, a) # branch\<close> using DisP(8) by auto then show ?case using DisP(5, 7) by metis next case (DisN p q a ps branch) have \<open>M, g, g a \<Turnstile> \<^bold>\<not> p\<close> \<open>M, g, g a \<Turnstile> \<^bold>\<not> q\<close> using DisN(1, 5) by fastforce+ then have \<open>M, g \<Turnstile>\<^sub>\<Theta> ((\<^bold>\<not> q) # (\<^bold>\<not> p) # ps, a) # branch\<close> using DisN(5) by simp then show ?case using DisN(4) by blast next case (DiaP p a ps branch i) then have *: \<open>M, g \<Turnstile>\<^sub>B (ps, a)\<close> by simp have \<open>i \<notin> nominals p\<close> using DiaP(1-2) unfolding branch_nominals_def by fastforce have \<open>M, g, g a \<Turnstile> \<^bold>\<diamond> p\<close> using DiaP(1, 7) by fastforce then obtain v where \<open>v \<in> R M (g a)\<close> \<open>M, g, v \<Turnstile> p\<close> by auto then have \<open>M, g(i := v), v \<Turnstile> p\<close> using \<open>i \<notin> nominals p\<close> semantics_fresh by metis then have \<open>M, g(i := v), g a \<Turnstile> \<^bold>@ i p\<close> by simp moreover have \<open>M, g(i := v), g a \<Turnstile> \<^bold>\<diamond> Nom i\<close> using \<open>v \<in> R M (g a)\<close> by simp moreover have \<open>M, g(i := v) \<Turnstile>\<^sub>\<Theta> (ps, a) # branch\<close> using DiaP(2, 7) branch_sat_fresh by fast moreover have \<open>i \<notin> block_nominals (ps, a)\<close> using DiaP(2) unfolding branch_nominals_def by simp then have \<open>\<forall>p on (ps, a). M, g(i := v), g a \<Turnstile> p\<close> using * semantics_fresh by fastforce ultimately have \<open>M, g(i := v) \<Turnstile>\<^sub>\<Theta> ((\<^bold>@ i p) # (\<^bold>\<diamond> Nom i) # ps, a) # branch\<close> by auto then show ?case using DiaP by blast next case (DiaN p a ps branch i) have \<open>M, g, g a \<Turnstile> \<^bold>\<not> (\<^bold>\<diamond> p)\<close> \<open>M, g, g a \<Turnstile> \<^bold>\<diamond> Nom i\<close> using DiaN(1-2, 6) by fastforce+ then have \<open>M, g, g a \<Turnstile> \<^bold>\<not> (\<^bold>@ i p)\<close> by simp then have \<open>M, g \<Turnstile>\<^sub>\<Theta> ((\<^bold>\<not> (\<^bold>@ i p)) # ps, a) # branch\<close> using DiaN(6) by simp then show ?thesis using DiaN(5) by blast next case (SatP a p b ps branch) have \<open>M, g, g a \<Turnstile> p\<close> using SatP(1, 5) by fastforce then have \<open>M, g \<Turnstile>\<^sub>\<Theta> (p # ps, a) # branch\<close> using SatP(5) by simp then show ?case using SatP(4) by blast next case (SatN a p b ps branch) have \<open>M, g, g a \<Turnstile> \<^bold>\<not> p\<close> using SatN(1, 5) by fastforce then have \<open>M, g \<Turnstile>\<^sub>\<Theta> ((\<^bold>\<not> p) # ps, a) # branch\<close> using SatN(5) by simp then show ?case using SatN(4) by blast next case (GoTo i branch) then show ?case by auto next case (Nom p b ps a branch) have \<open>M, g, g b \<Turnstile> p\<close> \<open>M, g, g b \<Turnstile> Nom a\<close> using Nom(1-2, 7) by fastforce+ moreover have \<open>M, g \<Turnstile>\<^sub>B (ps, a)\<close> using Nom(7) by simp ultimately have \<open>M, g \<Turnstile>\<^sub>B (p # ps, a)\<close> by simp then have \<open>M, g \<Turnstile>\<^sub>\<Theta> (p # ps, a) # branch\<close> using Nom(7) by simp then show ?case using Nom(6) by blast qed lemma block_sat: \<open>\<forall>p on block. M, g, w \<Turnstile> p \<Longrightarrow> M, g \<Turnstile>\<^sub>B block\<close> by (induct block) auto lemma branch_sat: assumes \<open>\<forall>(ps, i) \<in> set branch. \<forall>p on (ps, i). M, g, w \<Turnstile> p\<close> shows \<open>M, g \<Turnstile>\<^sub>\<Theta> branch\<close> using assms block_sat by fast corollary \<open>\<not> A, n \<turnstile> []\<close> using soundness by fastforce theorem soundness_fresh: assumes \<open>A, n \<turnstile> [([\<^bold>\<not> p], i)]\<close> \<open>i \<notin> nominals p\<close> shows \<open>M, g, w \<Turnstile> p\<close> proof - from assms(1) have \<open>M, g, g i \<Turnstile> p\<close> for g using soundness by fastforce then have \<open>M, g(i := w), (g(i := w)) i \<Turnstile> p\<close> by blast then have \<open>M, g(i := w), w \<Turnstile> p\<close> by simp then have \<open>M, g(i := g i), w \<Turnstile> p\<close> using assms(2) semantics_fresh by metis then show ?thesis by simp qed section \<open>No Detours\<close> text \<open> We only need to spend initial potential when we apply GoTo twice in a row. Otherwise another rule will have been applied in-between that justifies the GoTo. Therefore, by filtering out detours we can close any closeable branch starting from a single unit of potential. \<close> primrec nonempty :: \<open>('a, 'b) block \<Rightarrow> bool\<close> where \<open>nonempty (ps, i) = (ps \<noteq> [])\<close> lemma nonempty_Suc: assumes \<open>A, n \<turnstile> (ps, a) # filter nonempty left @ right\<close> \<open>q at a in (ps, a) # filter nonempty left @ right\<close> \<open>q \<noteq> Nom a\<close> shows \<open>A, Suc n \<turnstile> filter nonempty ((ps, a) # left) @ right\<close> proof (cases ps) case Nil then have \<open>a \<in> branch_nominals (filter nonempty left @ right)\<close> unfolding branch_nominals_def using assms(2-3) by fastforce then show ?thesis using assms(1) Nil GoTo by auto next case Cons then show ?thesis using assms(1) STA_Suc by auto qed lemma STA_nonempty: \<open>A, n \<turnstile> left @ right \<Longrightarrow> A, Suc m \<turnstile> filter nonempty left @ right\<close> proof (induct n \<open>left @ right\<close> arbitrary: left right rule: STA.induct) case (Close p i n) have \<open>(\<^bold>\<not> p) at i in filter nonempty left @ right\<close> using Close(2) by fastforce moreover from this have \<open>p at i in filter nonempty left @ right\<close> using Close(1) by fastforce ultimately show ?case using STA.Close by fast next case (Neg p a ps branch n) then show ?case proof (cases left) case Nil then have \<open>A, Suc m \<turnstile> (p # ps, a) # branch\<close> using Neg(4) by fastforce then have \<open>A, m \<turnstile> (ps, a) # branch\<close> using Neg(1-2) STA.Neg by fast then show ?thesis using Nil Neg(5) STA_Suc by auto next case (Cons _ left') then have \<open>A, Suc m \<turnstile> (p # ps, a) # filter nonempty left' @ right\<close> using Neg(4)[where left=\<open>_ # left'\<close>] Neg(5) by fastforce moreover have *: \<open>(\<^bold>\<not> \<^bold>\<not> p) at a in (ps, a) # filter nonempty left' @ right\<close> using Cons Neg(1, 5) by fastforce moreover have \<open>new p a ((ps, a) # filter nonempty left' @ right)\<close> using Cons Neg(2, 5) unfolding new_def by auto ultimately have \<open>A, m \<turnstile> (ps, a) # filter nonempty left' @ right\<close> using STA.Neg by fast then have \<open>A, Suc m \<turnstile> filter nonempty ((ps, a) # left') @ right\<close> using * nonempty_Suc by fast then show ?thesis using Cons Neg(5) by auto qed next case (DisP p q a ps branch n) then show ?case proof (cases left) case Nil then have \<open>A, Suc m \<turnstile> (p # ps, a) # branch\<close> \<open>A, Suc m \<turnstile> (q # ps, a) # branch\<close> using DisP(5, 7) by fastforce+ then have \<open>A, m \<turnstile> (ps, a) # branch\<close> using DisP(1-3) STA.DisP by fast then show ?thesis using Nil DisP(8) STA_Suc by auto next case (Cons _ left') then have \<open>A, Suc m \<turnstile> (p # ps, a) # filter nonempty left' @ right\<close> \<open>A, Suc m \<turnstile> (q # ps, a) # filter nonempty left' @ right\<close> using DisP(5, 7)[where left=\<open>_ # left'\<close>] DisP(8) by fastforce+ moreover have *: \<open>(p \<^bold>\<or> q) at a in (ps, a) # filter nonempty left' @ right\<close> using Cons DisP(1, 8) by fastforce moreover have \<open>new p a ((ps, a) # filter nonempty left' @ right)\<close> \<open>new q a ((ps, a) # filter nonempty left' @ right)\<close> using Cons DisP(2-3, 8) unfolding new_def by auto ultimately have \<open>A, m \<turnstile> (ps, a) # filter nonempty left' @ right\<close> using STA.DisP by fast then have \<open>A, Suc m \<turnstile> filter nonempty ((ps, a) # left') @ right\<close> using * nonempty_Suc by fast then show ?thesis using Cons DisP(8) by auto qed next case (DisN p q a ps branch n) then show ?case proof (cases left) case Nil then have \<open>A, Suc m \<turnstile> ((\<^bold>\<not> q) # (\<^bold>\<not> p) # ps, a) # branch\<close> using DisN(4) by fastforce then have \<open>A, m \<turnstile> (ps, a) # branch\<close> using DisN(1-2) STA.DisN by fast then show ?thesis using Nil DisN(5) STA_Suc by auto next case (Cons _ left') then have \<open>A, Suc m \<turnstile> ((\<^bold>\<not> q) # (\<^bold>\<not> p) # ps, a) # filter nonempty left' @ right\<close> using DisN(4)[where left=\<open>_ # left'\<close>] DisN(5) by fastforce moreover have *: \<open>(\<^bold>\<not> (p \<^bold>\<or> q)) at a in (ps, a) # filter nonempty left' @ right\<close> using Cons DisN(1, 5) by fastforce moreover consider \<open>new (\<^bold>\<not> p) a ((ps, a) # filter nonempty left' @ right)\<close> | \<open>new (\<^bold>\<not> q) a ((ps, a) # filter nonempty left' @ right)\<close> using Cons DisN(2, 5) unfolding new_def by auto ultimately have \<open>A, m \<turnstile> (ps, a) # filter nonempty left' @ right\<close> using STA.DisN by metis then have \<open>A, Suc m \<turnstile> filter nonempty ((ps, a) # left') @ right\<close> using * nonempty_Suc by fast then show ?thesis using Cons DisN(5) by auto qed next case (DiaP p a ps branch i n) then show ?case proof (cases left) case Nil then have \<open>A, Suc m \<turnstile> ((\<^bold>@ i p) # (\<^bold>\<diamond> Nom i) # ps, a) # branch\<close> using DiaP(6) by fastforce then have \<open>A, m \<turnstile> (ps, a) # branch\<close> using DiaP(1-4) STA.DiaP by fast then show ?thesis using Nil DiaP(7) STA_Suc by auto next case (Cons _ left') then have \<open>A, Suc m \<turnstile> ((\<^bold>@ i p) # (\<^bold>\<diamond> Nom i) # ps, a) # filter nonempty left' @ right\<close> using DiaP(6)[where left=\<open>_ # left'\<close>] DiaP(7) by fastforce moreover have *: \<open>(\<^bold>\<diamond> p) at a in (ps, a) # filter nonempty left' @ right\<close> using Cons DiaP(1, 7) by fastforce moreover have \<open>i \<notin> A \<union> branch_nominals ((ps, a) # filter nonempty left' @ right)\<close> using Cons DiaP(2, 7) unfolding branch_nominals_def by auto moreover have \<open>\<not> witnessed p a ((ps, a) # filter nonempty left' @ right)\<close> using Cons DiaP(4, 7) unfolding witnessed_def by auto ultimately have \<open>A, m \<turnstile> (ps, a) # filter nonempty left' @ right\<close> using DiaP(3) STA.DiaP by fast then have \<open>A, Suc m \<turnstile> filter nonempty ((ps, a) # left') @ right\<close> using * nonempty_Suc by fast then show ?thesis using Cons DiaP(7) by auto qed next case (DiaN p a ps branch i n) then show ?case proof (cases left) case Nil then have \<open>A, Suc m \<turnstile> ((\<^bold>\<not> (\<^bold>@ i p)) # ps, a) # branch\<close> using DiaN(5) by fastforce then have \<open>A, m \<turnstile> (ps, a) # branch\<close> using DiaN(1-3) STA.DiaN by fast then show ?thesis using Nil DiaN(6) STA_Suc by auto next case (Cons _ left') then have \<open>A, Suc m \<turnstile> ((\<^bold>\<not> (\<^bold>@ i p)) # ps, a) # filter nonempty left' @ right\<close> using DiaN(5)[where left=\<open>_ # left'\<close>] DiaN(6) by fastforce moreover have *: \<open>(\<^bold>\<not> (\<^bold>\<diamond> p)) at a in (ps, a) # filter nonempty left' @ right\<close> using Cons DiaN(1, 6) by fastforce moreover have *: \<open>(\<^bold>\<diamond> Nom i) at a in (ps, a) # filter nonempty left' @ right\<close> using Cons DiaN(2, 6) by fastforce moreover have \<open>new (\<^bold>\<not> (\<^bold>@ i p)) a ((ps, a) # filter nonempty left' @ right)\<close> using Cons DiaN(3, 6) unfolding new_def by auto ultimately have \<open>A, m \<turnstile> (ps, a) # filter nonempty left' @ right\<close> using STA.DiaN by fast then have \<open>A, Suc m \<turnstile> filter nonempty ((ps, a) # left') @ right\<close> using * nonempty_Suc by fast then show ?thesis using Cons DiaN(6) by auto qed next case (SatP a p b ps branch n) then show ?case proof (cases left) case Nil then have \<open>A, Suc m \<turnstile> (p # ps, a) # branch\<close> using SatP(4) by fastforce then have \<open>A, m \<turnstile> (ps, a) # branch\<close> using SatP(1-2) STA.SatP by fast then show ?thesis using Nil SatP(5) STA_Suc by auto next case (Cons _ left') then have \<open>A, Suc m \<turnstile> (p # ps, a) # filter nonempty left' @ right\<close> using SatP(4)[where left=\<open>_ # left'\<close>] SatP(5) by fastforce moreover have \<open>(\<^bold>@ a p) at b in (ps, a) # filter nonempty left' @ right\<close> using Cons SatP(1, 5) by fastforce moreover have \<open>new p a ((ps, a) # filter nonempty left' @ right)\<close> using Cons SatP(2, 5) unfolding new_def by auto ultimately have *: \<open>A, m \<turnstile> (ps, a) # filter nonempty left' @ right\<close> using STA.SatP by fast then have \<open>A, Suc m \<turnstile> filter nonempty ((ps, a) # left') @ right\<close> proof (cases ps) case Nil then have \<open>a \<in> branch_nominals (filter nonempty left' @ right)\<close> unfolding branch_nominals_def using SatP(1, 5) Cons by fastforce then show ?thesis using * Nil GoTo by fastforce next case Cons then show ?thesis using * STA_Suc by auto qed then show ?thesis using Cons SatP(5) by auto qed next case (SatN a p b ps branch n) then show ?case proof (cases left) case Nil then have \<open>A, Suc m \<turnstile> ((\<^bold>\<not> p) # ps, a) # branch\<close> using SatN(4) by fastforce then have \<open>A, m \<turnstile> (ps, a) # branch\<close> using SatN(1-2) STA.SatN by fast then show ?thesis using Nil SatN(5) STA_Suc by auto next case (Cons _ left') then have \<open>A, Suc m \<turnstile> ((\<^bold>\<not> p) # ps, a) # filter nonempty left' @ right\<close> using SatN(4)[where left=\<open>_ # left'\<close>] SatN(5) by fastforce moreover have \<open>(\<^bold>\<not> (\<^bold>@ a p)) at b in (ps, a) # filter nonempty left' @ right\<close> using Cons SatN(1, 5) by fastforce moreover have \<open>new (\<^bold>\<not> p) a ((ps, a) # filter nonempty left' @ right)\<close> using Cons SatN(2, 5) unfolding new_def by auto ultimately have *: \<open>A, m \<turnstile> (ps, a) # filter nonempty left' @ right\<close> using STA.SatN by fast then have \<open>A, Suc m \<turnstile> filter nonempty ((ps, a) # left') @ right\<close> proof (cases ps) case Nil then have \<open>a \<in> branch_nominals (filter nonempty left' @ right)\<close> unfolding branch_nominals_def using SatN(1, 5) Cons by fastforce then show ?thesis using * Nil GoTo by fastforce next case Cons then show ?thesis using * STA_Suc by auto qed then show ?thesis using Cons SatN(5) by auto qed next case (GoTo i n) show ?case using GoTo(3)[where left=\<open>([], i) # left\<close>] by simp next case (Nom p b ps a branch n) then show ?case proof (cases left) case Nil then have \<open>A, Suc m \<turnstile> (p # ps, a) # branch\<close> using Nom(6) by fastforce then have \<open>A, m \<turnstile> (ps, a) # branch\<close> using Nom(1-4) STA.Nom by metis then show ?thesis using Nil Nom(7) STA_Suc by auto next case (Cons _ left') then have \<open>A, Suc m \<turnstile> (p # ps, a) # filter nonempty left' @ right\<close> using Nom(6)[where left=\<open>_ # left'\<close>] Nom(7) by fastforce moreover have \<open>p at b in (ps, a) # filter nonempty left' @ right\<close> and a: \<open>Nom a at b in (ps, a) # filter nonempty left' @ right\<close> using Cons Nom(1-2, 7) by simp_all (metis empty_iff empty_set)+ moreover have \<open>new p a ((ps, a) # filter nonempty left' @ right)\<close> using Cons Nom(4, 7) unfolding new_def by auto ultimately have *: \<open>A, m \<turnstile> (ps, a) # filter nonempty left' @ right\<close> using Nom(3) STA.Nom by metis then have \<open>A, Suc m \<turnstile> filter nonempty ((ps, a) # left') @ right\<close> proof (cases ps) case Nil moreover have \<open>a \<noteq> b\<close> using Nom(1, 4) unfolding new_def by blast ultimately have \<open>a \<in> branch_nominals (filter nonempty left' @ right)\<close> using a unfolding branch_nominals_def by fastforce then show ?thesis using * Nil GoTo by auto next case Cons then show ?thesis using * STA_Suc by auto qed then show ?thesis using Cons Nom(7) by auto qed qed theorem STA_potential: \<open>A, n \<turnstile> branch \<Longrightarrow> A, Suc m \<turnstile> branch\<close> using STA_nonempty[where left=\<open>[]\<close>] by auto corollary STA_one: \<open>A, n \<turnstile> branch \<Longrightarrow> A, 1 \<turnstile> branch\<close> using STA_potential by auto subsection \<open>Free GoTo\<close> text \<open>The above result allows us to prove a version of GoTo that works "for free."\<close> lemma GoTo': assumes \<open>A, Suc n \<turnstile> ([], i) # branch\<close> \<open>i \<in> branch_nominals branch\<close> shows \<open>A, Suc n \<turnstile> branch\<close> using assms GoTo STA_potential by fast section \<open>Indexed Mapping\<close> text \<open>This section contains some machinery for showing admissible rules.\<close> subsection \<open>Indexing\<close> text \<open> We use pairs of natural numbers to index into the branch. The first component specifies the block and the second specifies the formula on that block. We index from the back to ensure that indices are stable under the addition of new formulas and blocks. \<close> primrec rev_nth :: \<open>'a list \<Rightarrow> nat \<Rightarrow> 'a option\<close> (infixl \<open>!.\<close> 100) where \<open>[] !. v = None\<close> | \<open>(x # xs) !. v = (if length xs = v then Some x else xs !. v)\<close> lemma rev_nth_last: \<open>xs !. 0 = Some x \<Longrightarrow> last xs = x\<close> by (induct xs) auto lemma rev_nth_zero: \<open>(xs @ [x]) !. 0 = Some x\<close> by (induct xs) auto lemma rev_nth_snoc: \<open>(xs @ [x]) !. Suc v = Some y \<Longrightarrow> xs !. v = Some y\<close> by (induct xs) auto lemma rev_nth_bounded: \<open>v < length xs \<Longrightarrow> \<exists>x. xs !. v = Some x\<close> by (induct xs) simp_all lemma rev_nth_Cons: \<open>xs !. v = Some y \<Longrightarrow> (x # xs) !. v = Some y\<close> proof (induct xs arbitrary: v rule: rev_induct) case (snoc a xs) then show ?case proof (induct v) case (Suc v) then have \<open>xs !. v = Some y\<close> using rev_nth_snoc by fast then have \<open>(x # xs) !. v = Some y\<close> using Suc(2) by blast then show ?case using Suc(3) by auto qed simp qed simp lemma rev_nth_append: \<open>xs !. v = Some y \<Longrightarrow> (ys @ xs) !. v = Some y\<close> using rev_nth_Cons[where xs=\<open>_ @ xs\<close>] by (induct ys) simp_all lemma rev_nth_mem: \<open>block \<in>. branch \<longleftrightarrow> (\<exists>v. branch !. v = Some block)\<close> proof assume \<open>block \<in>. branch\<close> then show \<open>\<exists>v. branch !. v = Some block\<close> proof (induct branch) case (Cons block' branch) then show ?case proof (cases \<open>block = block'\<close>) case False then have \<open>\<exists>v. branch !. v = Some block\<close> using Cons by simp then show ?thesis using rev_nth_Cons by fast qed auto qed simp next assume \<open>\<exists>v. branch !. v = Some block\<close> then show \<open>block \<in>. branch\<close> proof (induct branch) case (Cons block' branch) then show ?case by simp (metis option.sel) qed simp qed lemma rev_nth_Some: \<open>xs !. v = Some y \<Longrightarrow> v < length xs\<close> proof (induct xs arbitrary: v rule: rev_induct) case (snoc x xs) then show ?case by (induct v) (simp_all, metis rev_nth_snoc) qed simp lemma index_Cons: assumes \<open>((ps, a) # branch) !. v = Some (qs, b)\<close> \<open>qs !. v' = Some q\<close> shows \<open>\<exists>qs'. ((p # ps, a) # branch) !. v = Some (qs', b) \<and> qs' !. v' = Some q\<close> proof - have \<open>((p # ps, a) # branch) !. v = Some (qs, b) \<or> ((p # ps, a) # branch) !. v = Some (p # qs, b)\<close> using assms(1) by auto moreover have \<open>qs !. v' = Some q\<close> \<open>(p # qs) !. v' = Some q\<close> using assms(2) rev_nth_Cons by fast+ ultimately show ?thesis by fastforce qed subsection \<open>Mapping\<close> primrec mapi :: \<open>(nat \<Rightarrow> 'a \<Rightarrow> 'b) \<Rightarrow> 'a list \<Rightarrow> 'b list\<close> where \<open>mapi f [] = []\<close> | \<open>mapi f (x # xs) = f (length xs) x # mapi f xs\<close> primrec mapi_block :: \<open>(nat \<Rightarrow> ('a, 'b) fm \<Rightarrow> ('a, 'b) fm) \<Rightarrow> (('a, 'b) block \<Rightarrow> ('a, 'b) block)\<close> where \<open>mapi_block f (ps, i) = (mapi f ps, i)\<close> definition mapi_branch :: \<open>(nat \<Rightarrow> nat \<Rightarrow> ('a, 'b) fm \<Rightarrow> ('a, 'b) fm) \<Rightarrow> (('a, 'b) branch \<Rightarrow> ('a, 'b) branch)\<close> where \<open>mapi_branch f branch \<equiv> mapi (\<lambda>v. mapi_block (f v)) branch\<close> abbreviation mapper :: \<open>(('a, 'b) fm \<Rightarrow> ('a, 'b) fm) \<Rightarrow> (nat \<times> nat) set \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> ('a, 'b) fm \<Rightarrow> ('a, 'b) fm\<close> where \<open>mapper f xs v v' p \<equiv> (if (v, v') \<in> xs then f p else p)\<close> lemma mapi_block_add_oob: assumes \<open>length ps \<le> v'\<close> shows \<open>mapi_block (mapper f ({(v, v')} \<union> xs) v) (ps, i) = mapi_block (mapper f xs v) (ps, i)\<close> using assms by (induct ps) simp_all lemma mapi_branch_add_oob: assumes \<open>length branch \<le> v\<close> shows \<open>mapi_branch (mapper f ({(v, v')} \<union> xs)) branch = mapi_branch (mapper f xs) branch\<close> unfolding mapi_branch_def using assms by (induct branch) simp_all lemma mapi_branch_head_add_oob: \<open>mapi_branch (mapper f ({(length branch, length ps)} \<union> xs)) ((ps, a) # branch) = mapi_branch (mapper f xs) ((ps, a) # branch)\<close> using mapi_branch_add_oob[where branch=branch] unfolding mapi_branch_def using mapi_block_add_oob[where ps=ps] by simp lemma mapi_branch_mem: assumes \<open>(ps, i) \<in>. branch\<close> shows \<open>\<exists>v. (mapi (f v) ps, i) \<in>. mapi_branch f branch\<close> unfolding mapi_branch_def using assms by (induct branch) auto lemma rev_nth_mapi_block: assumes \<open>ps !. v' = Some p\<close> shows \<open>f v' p on (mapi f ps, a)\<close> using assms by (induct ps) (simp_all, metis option.sel) lemma mapi_append: \<open>mapi f (xs @ ys) = mapi (\<lambda>v. f (v + length ys)) xs @ mapi f ys\<close> by (induct xs) simp_all lemma mapi_block_id: \<open>mapi_block (mapper f {} v) (ps, i) = (ps, i)\<close> by (induct ps) auto lemma mapi_branch_id: \<open>mapi_branch (mapper f {}) branch = branch\<close> unfolding mapi_branch_def using mapi_block_id by (induct branch) auto lemma length_mapi: \<open>length (mapi f xs) = length xs\<close> by (induct xs) auto lemma mapi_rev_nth: assumes \<open>xs !. v = Some x\<close> shows \<open>mapi f xs !. v = Some (f v x)\<close> using assms proof (induct xs arbitrary: v) case (Cons y xs) have *: \<open>mapi f (y # xs) = f (length xs) y # mapi f xs\<close> by simp show ?case proof (cases \<open>v = length xs\<close>) case True then have \<open>mapi f (y # xs) !. v = Some (f (length xs) y)\<close> using length_mapi * by (metis rev_nth.simps(2)) then show ?thesis using Cons.prems True by auto next case False then show ?thesis using * Cons length_mapi by (metis rev_nth.simps(2)) qed qed simp section \<open>Duplicate Formulas\<close> subsection \<open>Removable indices\<close> abbreviation \<open>proj \<equiv> Equiv_Relations.proj\<close> definition all_is :: \<open>('a, 'b) fm \<Rightarrow> ('a, 'b) fm list \<Rightarrow> nat set \<Rightarrow> bool\<close> where \<open>all_is p ps xs \<equiv> \<forall>v \<in> xs. ps !. v = Some p\<close> definition is_at :: \<open>('a, 'b) fm \<Rightarrow> 'b \<Rightarrow> ('a, 'b) branch \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> bool\<close> where \<open>is_at p i branch v v' \<equiv> \<exists>ps. branch !. v = Some (ps, i) \<and> ps !. v' = Some p\<close> text \<open>This definition is slightly complicated by the inability to index the opening nominal.\<close> definition is_elsewhere :: \<open>('a, 'b) fm \<Rightarrow> 'b \<Rightarrow> ('a, 'b) branch \<Rightarrow> (nat \<times> nat) set \<Rightarrow> bool\<close> where \<open>is_elsewhere p i branch xs \<equiv> \<exists>w w' ps. (w, w') \<notin> xs \<and> branch !. w = Some (ps, i) \<and> (p = Nom i \<or> ps !. w' = Some p)\<close> definition Dup :: \<open>('a, 'b) fm \<Rightarrow> 'b \<Rightarrow> ('a, 'b) branch \<Rightarrow> (nat \<times> nat) set \<Rightarrow> bool\<close> where \<open>Dup p i branch xs \<equiv> \<forall>(v, v') \<in> xs. is_at p i branch v v' \<and> is_elsewhere p i branch xs\<close> lemma Dup_all_is: assumes \<open>Dup p i branch xs\<close> \<open>branch !. v = Some (ps, a)\<close> shows \<open>all_is p ps (proj xs v)\<close> using assms unfolding Dup_def is_at_def all_is_def proj_def by auto lemma Dup_branch: \<open>Dup p i branch xs \<Longrightarrow> Dup p i (extra @ branch) xs\<close> unfolding Dup_def is_at_def is_elsewhere_def using rev_nth_append by fast lemma Dup_block: assumes \<open>Dup p i ((ps, a) # branch) xs\<close> shows \<open>Dup p i ((ps' @ ps, a) # branch) xs\<close> unfolding Dup_def proof safe fix v v' assume \<open>(v, v') \<in> xs\<close> then show \<open>is_at p i ((ps' @ ps, a) # branch) v v'\<close> using assms rev_nth_append unfolding Dup_def is_at_def by fastforce next fix v v' assume \<open>(v, v') \<in> xs\<close> then obtain w w' qs where \<open>(w, w') \<notin> xs\<close> \<open>((ps, a) # branch) !. w = Some (qs, i)\<close> \<open>p = Nom i \<or> qs !. w' = Some p\<close> using assms unfolding Dup_def is_elsewhere_def by blast then have \<open>\<exists>qs. ((ps' @ ps, a) # branch) !. w = Some (qs, i) \<and> (p = Nom i \<or> qs !. w' = Some p)\<close> using rev_nth_append by fastforce then show \<open>is_elsewhere p i ((ps' @ ps, a) # branch) xs\<close> unfolding is_elsewhere_def using \<open>(w, w') \<notin> xs\<close> by blast qed definition only_touches :: \<open>'b \<Rightarrow> ('a, 'b) branch \<Rightarrow> (nat \<times> nat) set \<Rightarrow> bool\<close> where \<open>only_touches i branch xs \<equiv> \<forall>(v, v') \<in> xs. \<forall>ps a. branch !. v = Some (ps, a) \<longrightarrow> i = a\<close> lemma Dup_touches: \<open>Dup p i branch xs \<Longrightarrow> only_touches i branch xs\<close> unfolding Dup_def is_at_def only_touches_def by auto lemma only_touches_opening: assumes \<open>only_touches i branch xs\<close> \<open>(v, v') \<in> xs\<close> \<open>branch !. v = Some (ps, a)\<close> shows \<open>i = a\<close> using assms unfolding only_touches_def is_at_def by auto lemma Dup_head: \<open>Dup p i ((ps, a) # branch) xs \<Longrightarrow> Dup p i ((q # ps, a) # branch) xs\<close> using Dup_block[where ps'=\<open>[_]\<close>] by simp lemma Dup_head_oob': assumes \<open>Dup p i ((ps, a) # branch) xs\<close> shows \<open>(length branch, k + length ps) \<notin> xs\<close> using assms rev_nth_Some unfolding Dup_def is_at_def by fastforce lemma Dup_head_oob: assumes \<open>Dup p i ((ps, a) # branch) xs\<close> shows \<open>(length branch, length ps) \<notin> xs\<close> using assms Dup_head_oob'[where k=0] by fastforce subsection \<open>Omitting formulas\<close> primrec omit :: \<open>nat set \<Rightarrow> ('a, 'b) fm list \<Rightarrow> ('a, 'b) fm list\<close> where \<open>omit xs [] = []\<close> | \<open>omit xs (p # ps) = (if length ps \<in> xs then omit xs ps else p # omit xs ps)\<close> primrec omit_block :: \<open>nat set \<Rightarrow> ('a, 'b) block \<Rightarrow> ('a, 'b) block\<close> where \<open>omit_block xs (ps, a) = (omit xs ps, a)\<close> definition omit_branch :: \<open>(nat \<times> nat) set \<Rightarrow> ('a, 'b) branch \<Rightarrow> ('a, 'b) branch\<close> where \<open>omit_branch xs branch \<equiv> mapi (\<lambda>v. omit_block (proj xs v)) branch\<close> lemma omit_mem: \<open>ps !. v = Some p \<Longrightarrow> v \<notin> xs \<Longrightarrow> p \<in>. omit xs ps\<close> proof (induct ps) case (Cons q ps) then show ?case by (cases \<open>v = length ps\<close>) simp_all qed simp lemma omit_id: \<open>omit {} ps = ps\<close> by (induct ps) auto lemma omit_block_id: \<open>omit_block {} block = block\<close> using omit_id by (cases block) simp lemma omit_branch_id: \<open>omit_branch {} branch = branch\<close> unfolding omit_branch_def proj_def using omit_block_id by (induct branch) fastforce+ lemma omit_branch_mem_diff_opening: assumes \<open>only_touches i branch xs\<close> \<open>(ps, a) \<in>. branch\<close> \<open>i \<noteq> a\<close> shows \<open>(ps, a) \<in>. omit_branch xs branch\<close> proof - obtain v where v: \<open>branch !. v = Some (ps, a)\<close> using assms(2) rev_nth_mem by fast then have \<open>omit_branch xs branch !. v = Some (omit (proj xs v) ps, a)\<close> unfolding omit_branch_def by (simp add: mapi_rev_nth) then have *: \<open>(omit (proj xs v) ps, a) \<in>. omit_branch xs branch\<close> using rev_nth_mem by fast moreover have \<open>proj xs v = {}\<close> unfolding proj_def using assms(1, 3) v only_touches_opening by fast then have \<open>omit (proj xs v) ps = ps\<close> using omit_id by auto ultimately show ?thesis by simp qed lemma Dup_omit_branch_mem_same_opening: assumes \<open>Dup p i branch xs\<close> \<open>p at i in branch\<close> shows \<open>p at i in omit_branch xs branch\<close> proof - obtain ps where ps: \<open>(ps, i) \<in>. branch\<close> \<open>p on (ps, i)\<close> using assms(2) by blast then obtain v where v: \<open>branch !. v = Some (ps, i)\<close> using rev_nth_mem by fast then have \<open>omit_branch xs branch !. v = Some (omit (proj xs v) ps, i)\<close> unfolding omit_branch_def by (simp add: mapi_rev_nth) then have *: \<open>(omit (proj xs v) ps, i) \<in>. omit_branch xs branch\<close> using rev_nth_mem by fast consider v' where \<open>ps !. v' = Some p\<close> \<open>(v, v') \<in> xs\<close> | v' where \<open>ps !. v' = Some p\<close> \<open>(v, v') \<notin> xs\<close> | \<open>p = Nom i\<close> using ps v rev_nth_mem by fastforce then show ?thesis proof cases case (1 v') then obtain qs w w' where qs: \<open>(w, w') \<notin> xs\<close> \<open>branch !. w = Some (qs, i)\<close> \<open>p = Nom i \<or> qs !. w' = Some p\<close> using assms(1) unfolding Dup_def is_elsewhere_def by blast then have \<open>omit_branch xs branch !. w = Some (omit (proj xs w) qs, i)\<close> unfolding omit_branch_def by (simp add: mapi_rev_nth) then have \<open>(omit (proj xs w) qs, i) \<in>. omit_branch xs branch\<close> using rev_nth_mem by fast moreover have \<open>p on (omit (proj xs w) qs, i)\<close> unfolding proj_def using qs(1, 3) omit_mem by fastforce ultimately show ?thesis by blast next case (2 v') then show ?thesis using * omit_mem unfolding proj_def by (metis Image_singleton_iff on.simps) next case 3 then show ?thesis using * by auto qed qed lemma omit_all_is: assumes \<open>all_is p ps xs\<close> \<open>q \<in>. ps\<close> \<open>q \<notin> set (omit xs ps)\<close> shows \<open>q = p\<close> using assms omit_del unfolding all_is_def by fastforce definition all_is_branch :: \<open>('a, 'b) fm \<Rightarrow> 'b \<Rightarrow> ('a, 'b) branch \<Rightarrow> (nat \<times> nat) set \<Rightarrow> bool\<close> where \<open>all_is_branch p i branch xs \<equiv> \<forall>(v, v') \<in> xs. v < length branch \<longrightarrow> is_at p i branch v v'\<close> lemma all_is_branch: \<open>all_is_branch p i branch xs \<Longrightarrow> branch !. v = Some (ps, a) \<Longrightarrow> all_is p ps (proj xs v)\<close> unfolding all_is_branch_def is_at_def all_is_def proj_def using rev_nth_Some by fastforce lemma Dup_all_is_branch: \<open>Dup p i branch xs \<Longrightarrow> all_is_branch p i branch xs\<close> unfolding all_is_branch_def Dup_def by fast lemma omit_branch_mem_diff_formula: assumes \<open>all_is_branch p i branch xs\<close> \<open>q at i in branch\<close> \<open>p \<noteq> q\<close> shows \<open>q at i in omit_branch xs branch\<close> proof - obtain ps where ps: \<open>(ps, i) \<in>. branch\<close> \<open>q on (ps, i)\<close> using assms(2) by blast then obtain v where v: \<open>branch !. v = Some (ps, i)\<close> using rev_nth_mem by fast then have \<open>omit_branch xs branch !. v = Some (omit (proj xs v) ps, i)\<close> unfolding omit_branch_def by (simp add: mapi_rev_nth) then have *: \<open>(omit (proj xs v) ps, i) \<in>. omit_branch xs branch\<close> using rev_nth_mem by fast moreover have \<open>all_is p ps (proj xs v)\<close> using assms(1) v all_is_branch by fast then have \<open>q on (omit (proj xs v) ps, i)\<close> using ps assms(3) omit_all_is by auto ultimately show ?thesis by blast qed lemma Dup_omit_branch_mem: assumes \<open>Dup p i branch xs\<close> \<open>q at a in branch\<close> shows \<open>q at a in omit_branch xs branch\<close> using assms omit_branch_mem_diff_opening Dup_touches Dup_omit_branch_mem_same_opening omit_branch_mem_diff_formula Dup_all_is_branch by fast lemma omit_set: \<open>set (omit xs ps) \<subseteq> set ps\<close> by (induct ps) auto lemma on_omit: \<open>p on (omit xs ps, i) \<Longrightarrow> p on (ps, i)\<close> using omit_set by auto lemma all_is_set: assumes \<open>all_is p ps xs\<close> shows \<open>{p} \<union> set (omit xs ps) = {p} \<union> set ps\<close> using assms omit_all_is omit_set unfolding all_is_def by fast lemma all_is_list_nominals: assumes \<open>all_is p ps xs\<close> shows \<open>nominals p \<union> list_nominals (omit xs ps) = nominals p \<union> list_nominals ps\<close> using assms all_is_set by fastforce lemma all_is_block_nominals: assumes \<open>all_is p ps xs\<close> shows \<open>nominals p \<union> block_nominals (omit xs ps, i) = nominals p \<union> block_nominals (ps, i)\<close> using assms by (simp add: all_is_list_nominals) lemma all_is_branch_nominals': assumes \<open>all_is_branch p i branch xs\<close> shows \<open>nominals p \<union> branch_nominals (omit_branch xs branch) = nominals p \<union> branch_nominals branch\<close> proof - have \<open>\<forall>(v, v') \<in> xs. v < length branch \<longrightarrow> is_at p i branch v v'\<close> using assms unfolding all_is_branch_def is_at_def by auto then show ?thesis proof (induct branch) case Nil then show ?case unfolding omit_branch_def by simp next case (Cons block branch) then show ?case proof (cases block) case (Pair ps a) have \<open>\<forall>(v, v') \<in> xs. v < length branch \<longrightarrow> is_at p i branch v v'\<close> using Cons(2) rev_nth_Cons unfolding is_at_def by auto then have \<open>nominals p \<union> branch_nominals (omit_branch xs branch) = nominals p \<union> branch_nominals branch\<close> using Cons(1) by blast then have \<open>nominals p \<union> branch_nominals (omit_branch xs ((ps, a) # branch)) = nominals p \<union> block_nominals (omit (proj xs (length branch)) ps, a) \<union> branch_nominals branch\<close> unfolding branch_nominals_def omit_branch_def by auto moreover have \<open>all_is p ps (proj xs (length branch))\<close> using Cons(2) Pair unfolding proj_def all_is_def is_at_def by auto then have \<open>nominals p \<union> block_nominals (omit (proj xs (length branch)) ps, a) = nominals p \<union> block_nominals (ps, a)\<close> using all_is_block_nominals by fast then have \<open>nominals p \<union> block_nominals (omit_block (proj xs (length branch)) (ps, a)) = nominals p \<union> block_nominals (ps, a)\<close> by simp ultimately have \<open>nominals p \<union> branch_nominals (omit_branch xs ((ps, a) # branch)) = nominals p \<union> block_nominals (ps, a) \<union> branch_nominals branch\<close> by auto then show ?thesis unfolding branch_nominals_def using Pair by auto qed qed qed lemma Dup_branch_nominals: assumes \<open>Dup p i branch xs\<close> shows \<open>branch_nominals (omit_branch xs branch) = branch_nominals branch\<close> proof (cases \<open>xs = {}\<close>) case True then show ?thesis using omit_branch_id by metis next case False with assms obtain ps w w' where \<open>(w, w') \<notin> xs\<close> \<open>branch !. w = Some (ps, i)\<close> \<open>p = Nom i \<or> ps !. w' = Some p\<close> unfolding Dup_def is_elsewhere_def by fast then have *: \<open>(ps, i) \<in>. branch\<close> \<open>p on (ps, i)\<close> using rev_nth_mem rev_nth_on by fast+ then have \<open>nominals p \<subseteq> branch_nominals branch\<close> unfolding branch_nominals_def using block_nominals by fast moreover obtain ps' where \<open>(ps', i) \<in>. omit_branch xs branch\<close> \<open>p on (ps', i)\<close> using assms * Dup_omit_branch_mem by fast then have \<open>nominals p \<subseteq> branch_nominals (omit_branch xs branch)\<close> unfolding branch_nominals_def using block_nominals by fast moreover have \<open>nominals p \<union> branch_nominals (omit_branch xs branch) = nominals p \<union> branch_nominals branch\<close> using assms all_is_branch_nominals' Dup_all_is_branch by fast ultimately show ?thesis by blast qed lemma omit_branch_mem_dual: assumes \<open>p at i in omit_branch xs branch\<close> shows \<open>p at i in branch\<close> proof - obtain ps where ps: \<open>(ps, i) \<in>. omit_branch xs branch\<close> \<open>p on (ps, i)\<close> using assms(1) by blast then obtain v where v: \<open>omit_branch xs branch !. v = Some (ps, i)\<close> using rev_nth_mem unfolding omit_branch_def by fast then have \<open>v < length (omit_branch xs branch)\<close> using rev_nth_Some by fast then have \<open>v < length branch\<close> unfolding omit_branch_def using length_mapi by metis then obtain ps' i' where ps': \<open>branch !. v = Some (ps', i')\<close> using rev_nth_bounded by (metis surj_pair) then have \<open>omit_branch xs branch !. v = Some (omit (proj xs v) ps', i')\<close> unfolding omit_branch_def by (simp add: mapi_rev_nth) then have \<open>ps = omit (proj xs v) ps'\<close> \<open>i = i'\<close> using v by simp_all then have \<open>p on (ps', i)\<close> using ps omit_set by auto moreover have \<open>(ps', i) \<in>. branch\<close> using ps' \<open>i = i'\<close> rev_nth_mem by fast ultimately show ?thesis using \<open>ps = omit (proj xs v) ps'\<close> by blast qed lemma witnessed_omit_branch: assumes \<open>witnessed p a (omit_branch xs branch)\<close> shows \<open>witnessed p a branch\<close> proof - obtain ps qs i where ps: \<open>(ps, a) \<in>. omit_branch xs branch\<close> \<open>(\<^bold>@ i p) on (ps, a)\<close> and qs: \<open>(qs, a) \<in>. omit_branch xs branch\<close> \<open>(\<^bold>\<diamond> Nom i) on (qs, a)\<close> using assms unfolding witnessed_def by blast from ps obtain ps' where \<open>(ps', a) \<in>. branch\<close> \<open>(\<^bold>@ i p) on (ps', a)\<close> using omit_branch_mem_dual by fast moreover from qs obtain qs' where \<open>(qs', a) \<in>. branch\<close> \<open>(\<^bold>\<diamond> Nom i) on (qs', a)\<close> using omit_branch_mem_dual by fast ultimately show ?thesis unfolding witnessed_def by blast qed lemma new_omit_branch: assumes \<open>new p a branch\<close> shows \<open>new p a (omit_branch xs branch)\<close> using assms omit_branch_mem_dual unfolding new_def by fast lemma omit_oob: assumes \<open>length ps \<le> v\<close> shows \<open>omit ({v} \<union> xs) ps = omit xs ps\<close> using assms by (induct ps) simp_all lemma omit_branch_oob: assumes \<open>length branch \<le> v\<close> shows \<open>omit_branch ({(v, v')} \<union> xs) branch = omit_branch xs branch\<close> using assms proof (induct branch) case Nil then show ?case unfolding omit_branch_def by simp next case (Cons block branch) let ?xs = \<open>({(v, v')} \<union> xs)\<close> show ?case proof (cases block) case (Pair ps a) then have \<open>omit_branch ?xs ((ps, a) # branch) = (omit (proj ?xs (length branch)) ps, a) # omit_branch xs branch\<close> using Cons unfolding omit_branch_def by simp moreover have \<open>proj ?xs (length branch) = proj xs (length branch)\<close> using Cons(2) unfolding proj_def by auto ultimately show ?thesis unfolding omit_branch_def by simp qed qed subsection \<open>Induction\<close> lemma STA_Dup: assumes \<open>A, n \<turnstile> branch\<close> \<open>Dup q i branch xs\<close> shows \<open>A, n \<turnstile> omit_branch xs branch\<close> using assms proof (induct n branch) case (Close p i' branch n) have \<open>p at i' in omit_branch xs branch\<close> using Close(1, 3) Dup_omit_branch_mem by fast moreover have \<open>(\<^bold>\<not> p) at i' in omit_branch xs branch\<close> using Close(2, 3) Dup_omit_branch_mem by fast ultimately show ?case using STA.Close by fast next case (Neg p a ps branch n) have \<open>A, Suc n \<turnstile> omit_branch xs ((p # ps, a) # branch)\<close> using Neg(4-) Dup_head by fast moreover have \<open>(length branch, length ps) \<notin> xs\<close> using Neg(5) Dup_head_oob by fast ultimately have \<open>A, Suc n \<turnstile> (p # omit (proj xs (length branch)) ps, a) # omit_branch xs branch\<close> unfolding omit_branch_def proj_def by simp moreover have \<open>(\<^bold>\<not> \<^bold>\<not> p) at a in omit_branch xs ((ps, a) # branch)\<close> using Neg(1, 5) Dup_omit_branch_mem by fast moreover have \<open>new p a (omit_branch xs ((ps, a) # branch))\<close> using Neg(2) new_omit_branch by fast ultimately show ?case by (simp add: omit_branch_def STA.Neg) next case (DisP p q a ps branch n) have \<open>A, Suc n \<turnstile> omit_branch xs ((p # ps, a) # branch)\<close> \<open>A, Suc n \<turnstile> omit_branch xs ((q # ps, a) # branch)\<close> using DisP(4-) Dup_head by fast+ moreover have \<open>(length branch, length ps) \<notin> xs\<close> using DisP(8) Dup_head_oob by fast ultimately have \<open>A, Suc n \<turnstile> (p # omit (proj xs (length branch)) ps, a) # omit_branch xs branch\<close> \<open>A, Suc n \<turnstile> (q # omit (proj xs (length branch)) ps, a) # omit_branch xs branch\<close> unfolding omit_branch_def proj_def by simp_all moreover have \<open>(p \<^bold>\<or> q) at a in omit_branch xs ((ps, a) # branch)\<close> using DisP(1, 8) Dup_omit_branch_mem by fast moreover have \<open>new p a (omit_branch xs ((ps, a) # branch))\<close> using DisP(2) new_omit_branch by fast moreover have \<open>new q a (omit_branch xs ((ps, a) # branch))\<close> using DisP(3) new_omit_branch by fast ultimately show ?case by (simp add: omit_branch_def STA.DisP) next case (DisN p q a ps branch n) have \<open>A, Suc n \<turnstile> omit_branch xs (((\<^bold>\<not> q) # (\<^bold>\<not> p) # ps, a) # branch)\<close> using DisN(4-) Dup_block[where ps'=\<open>[_, _]\<close>] by fastforce moreover have \<open>(length branch, length ps) \<notin> xs\<close> using DisN(5) Dup_head_oob by fast moreover have \<open>(length branch, 1 + length ps) \<notin> xs\<close> using DisN(5) Dup_head_oob' by fast ultimately have \<open>A, Suc n \<turnstile> ((\<^bold>\<not> q) # (\<^bold>\<not> p) # omit (proj xs (length branch)) ps, a) # omit_branch xs branch\<close> unfolding omit_branch_def proj_def by simp moreover have \<open>(\<^bold>\<not> (p \<^bold>\<or> q)) at a in omit_branch xs ((ps, a) # branch)\<close> using DisN(1, 5) Dup_omit_branch_mem by fast moreover have \<open>new (\<^bold>\<not> p) a (omit_branch xs ((ps, a) # branch)) \<or> new (\<^bold>\<not> q) a (omit_branch xs ((ps, a) # branch))\<close> using DisN(2) new_omit_branch by fast ultimately show ?case by (simp add: omit_branch_def STA.DisN) next case (DiaP p a ps branch i n) have \<open>A, Suc n \<turnstile> omit_branch xs (((\<^bold>@ i p) # (\<^bold>\<diamond> Nom i) # ps, a) # branch)\<close> using DiaP(4-) Dup_block[where ps'=\<open>[_, _]\<close>] by fastforce moreover have \<open>(length branch, length ps) \<notin> xs\<close> using DiaP(7) Dup_head_oob by fast moreover have \<open>(length branch, 1+ length ps) \<notin> xs\<close> using DiaP(7) Dup_head_oob' by fast ultimately have \<open>A, Suc n \<turnstile> ((\<^bold>@ i p) # (\<^bold>\<diamond> Nom i) # omit (proj xs (length branch)) ps, a) # omit_branch xs branch\<close> unfolding omit_branch_def proj_def by simp moreover have \<open>(\<^bold>\<diamond> p) at a in omit_branch xs ((ps, a) # branch)\<close> using DiaP(1, 7) Dup_omit_branch_mem by fast moreover have \<open>i \<notin> A \<union> branch_nominals (omit_branch xs ((ps, a) # branch))\<close> using DiaP(2, 7) Dup_branch_nominals by fast moreover have \<open>\<not> witnessed p a (omit_branch xs ((ps, a) # branch))\<close> using DiaP(4) witnessed_omit_branch by fast ultimately show ?case using DiaP(3) by (simp add: omit_branch_def STA.DiaP) next case (DiaN p a ps branch i n) have \<open>A, Suc n \<turnstile> omit_branch xs (((\<^bold>\<not> (\<^bold>@ i p)) # ps, a) # branch)\<close> using DiaN(4-) Dup_head by fast moreover have \<open>(length branch, length ps) \<notin> xs\<close> using DiaN(6) Dup_head_oob by fast ultimately have \<open>A, Suc n \<turnstile> ((\<^bold>\<not> (\<^bold>@ i p)) # omit (proj xs (length branch)) ps, a) # omit_branch xs branch\<close> unfolding omit_branch_def proj_def by simp moreover have \<open>(\<^bold>\<not> (\<^bold>\<diamond> p)) at a in omit_branch xs ((ps, a) # branch)\<close> using DiaN(1, 6) Dup_omit_branch_mem by fast moreover have \<open>(\<^bold>\<diamond> Nom i) at a in omit_branch xs ((ps, a) # branch)\<close> using DiaN(2, 6) Dup_omit_branch_mem by fast moreover have \<open>new (\<^bold>\<not> (\<^bold>@ i p)) a (omit_branch xs ((ps, a) # branch))\<close> using DiaN(3) new_omit_branch by fast ultimately show ?case by (simp add: omit_branch_def STA.DiaN) next case (SatP a p b ps branch n) have \<open>A, Suc n \<turnstile> omit_branch xs ((p # ps, a) # branch)\<close> using SatP(4-) Dup_head by fast moreover have \<open>(length branch, length ps) \<notin> xs\<close> using SatP(5) Dup_head_oob by fast ultimately have \<open>A, Suc n \<turnstile> (p # omit (proj xs (length branch)) ps, a) # omit_branch xs branch\<close> unfolding omit_branch_def proj_def by simp moreover have \<open>(\<^bold>@ a p) at b in omit_branch xs ((ps, a) # branch)\<close> using SatP(1, 5) Dup_omit_branch_mem by fast moreover have \<open>new p a (omit_branch xs ((ps, a) # branch))\<close> using SatP(2) new_omit_branch by fast ultimately show ?case by (simp add: omit_branch_def STA.SatP) next case (SatN a p b ps branch n) have \<open>A, Suc n \<turnstile> omit_branch xs (((\<^bold>\<not> p) # ps, a) # branch)\<close> using SatN(4-) Dup_head by fast moreover have \<open>(length branch, length ps) \<notin> xs\<close> using SatN(5) Dup_head_oob by fast ultimately have \<open>A, Suc n \<turnstile> ((\<^bold>\<not> p) # omit (proj xs (length branch)) ps, a) # omit_branch xs branch\<close> unfolding omit_branch_def proj_def by simp moreover have \<open>(\<^bold>\<not> (\<^bold>@ a p)) at b in omit_branch xs ((ps, a) # branch)\<close> using SatN(1, 5) Dup_omit_branch_mem by fast moreover have \<open>new (\<^bold>\<not> p) a (omit_branch xs ((ps, a) # branch))\<close> using SatN(2) new_omit_branch by fast ultimately show ?case by (simp add: omit_branch_def STA.SatN) next case (GoTo i branch n) then have \<open>A, n \<turnstile> omit_branch xs (([], i) # branch)\<close> using Dup_branch[where extra=\<open>[([], i)]\<close>] by fastforce then have \<open>A, n \<turnstile> ([], i) # omit_branch xs branch\<close> unfolding omit_branch_def by simp moreover have \<open>i \<in> branch_nominals (omit_branch xs branch)\<close> using GoTo(1, 4) Dup_branch_nominals by fast ultimately show ?case unfolding omit_branch_def by (simp add: STA.GoTo) next case (Nom p b ps a branch n) have \<open>A, Suc n \<turnstile> omit_branch xs ((p # ps, a) # branch)\<close> using Nom(4-) Dup_head by fast moreover have \<open>(length branch, length ps) \<notin> xs\<close> using Nom(7) Dup_head_oob by fast ultimately have \<open>A, Suc n \<turnstile> (p # omit (proj xs (length branch)) ps, a) # omit_branch xs branch\<close> unfolding omit_branch_def proj_def by simp moreover have \<open>p at b in omit_branch xs ((ps, a) # branch)\<close> using Nom(1, 7) Dup_omit_branch_mem by fast moreover have \<open>Nom a at b in omit_branch xs ((ps, a) # branch)\<close> using Nom(2, 7) Dup_omit_branch_mem by fast moreover have \<open>new p a (omit_branch xs ((ps, a) # branch))\<close> using Nom(4) new_omit_branch by fast ultimately show ?case using Nom(3) by (simp add: omit_branch_def STA.Nom) qed theorem Dup: assumes \<open>A, n \<turnstile> (p # ps, a) # branch\<close> \<open>\<not> new p a ((ps, a) # branch)\<close> shows \<open>A, n \<turnstile> (ps, a) # branch\<close> proof - obtain qs where qs: \<open>(qs, a) \<in>. (ps, a) # branch\<close> \<open>p on (qs, a)\<close> using assms(2) unfolding new_def by blast let ?xs = \<open>{(length branch, length ps)}\<close> have *: \<open>is_at p a ((p # ps, a) # branch) (length branch) (length ps)\<close> unfolding is_at_def by simp have \<open>Dup p a ((p # ps, a) # branch) ?xs\<close> proof (cases \<open>p = Nom a\<close>) case True moreover have \<open>((p # ps, a) # branch) !. length branch = Some (p # ps, a)\<close> by simp moreover have \<open>p on (p # ps, a)\<close> by simp ultimately have \<open>is_elsewhere p a ((p # ps, a) # branch) ?xs\<close> unfolding is_elsewhere_def using assms(2) rev_nth_Some by (metis (mono_tags, lifting) Pair_inject less_le singletonD) then show ?thesis unfolding Dup_def using * by blast next case false: False then show ?thesis proof (cases \<open>ps = qs\<close>) case True then obtain w' where w': \<open>qs !. w' = Some p\<close> using qs(2) false rev_nth_mem by fastforce then have \<open>(p # ps) !. w' = Some p\<close> using True rev_nth_Cons by fast moreover have \<open>((p # ps, a) # branch) !. length branch = Some (p # ps, a)\<close> by simp moreover have \<open>(length branch, w') \<notin> ?xs\<close> using True w' rev_nth_Some by fast ultimately have \<open>is_elsewhere p a ((p # ps, a) # branch) ?xs\<close> unfolding is_elsewhere_def by fast then show ?thesis unfolding Dup_def using * by fast next case False then obtain w where w: \<open>branch !. w = Some (qs, a)\<close> using qs(1) rev_nth_mem by fastforce moreover obtain w' where w': \<open>qs !. w' = Some p\<close> using qs(2) false rev_nth_mem by fastforce moreover have \<open>(w, w') \<notin> ?xs\<close> using rev_nth_Some w by fast ultimately have \<open>is_elsewhere p a ((p # ps, a) # branch) ?xs\<close> unfolding is_elsewhere_def using rev_nth_Cons by fast then show ?thesis unfolding Dup_def using * by fast qed qed then have \<open>A, n \<turnstile> omit_branch ?xs ((p # ps, a) # branch)\<close> using assms(1) STA_Dup by fast then have \<open>A, n \<turnstile> (omit (proj ?xs (length branch)) ps, a) # omit_branch ?xs branch\<close> unfolding omit_branch_def proj_def by simp moreover have \<open>omit_branch ?xs branch = omit_branch {} branch\<close> using omit_branch_oob by auto then have \<open>omit_branch ?xs branch = branch\<close> using omit_branch_id by simp moreover have \<open>proj ?xs (length branch) = {length ps}\<close> unfolding proj_def by blast then have \<open>omit (proj ?xs (length branch)) ps = omit {} ps\<close> using omit_oob by auto then have \<open>omit (proj ?xs (length branch)) ps = ps\<close> using omit_id by simp ultimately show ?thesis by simp qed subsection \<open>Unrestricted rules\<close> lemma STA_add: \<open>A, n \<turnstile> branch \<Longrightarrow> A, m + n \<turnstile> branch\<close> using STA_Suc by (induct m) auto lemma STA_le: \<open>A, n \<turnstile> branch \<Longrightarrow> n \<le> m \<Longrightarrow> A, m \<turnstile> branch\<close> using STA_add by (metis le_add_diff_inverse2) lemma Neg': assumes \<open>(\<^bold>\<not> \<^bold>\<not> p) at a in (ps, a) # branch\<close> \<open>A, n \<turnstile> (p # ps, a) # branch\<close> shows \<open>A, n \<turnstile> (ps, a) # branch\<close> using assms Neg Dup STA_Suc by metis lemma DisP': assumes \<open>(p \<^bold>\<or> q) at a in (ps, a) # branch\<close> \<open>A, n \<turnstile> (p # ps, a) # branch\<close> \<open>A, n \<turnstile> (q # ps, a) # branch\<close> shows \<open>A, n \<turnstile> (ps, a) # branch\<close> proof (cases \<open>new p a ((ps, a) # branch) \<and> new q a ((ps, a) # branch)\<close>) case True moreover have \<open>A, Suc n \<turnstile> (p # ps, a) # branch\<close> \<open>A, Suc n \<turnstile> (q # ps, a) # branch\<close> using assms(2-3) STA_Suc by fast+ ultimately show ?thesis using assms(1) DisP by fast next case False then show ?thesis using assms Dup by fast qed lemma DisN': assumes \<open>(\<^bold>\<not> (p \<^bold>\<or> q)) at a in (ps, a) # branch\<close> \<open>A, n \<turnstile> ((\<^bold>\<not> q) # (\<^bold>\<not> p) # ps, a) # branch\<close> shows \<open>A, n \<turnstile> (ps, a) # branch\<close> proof (cases \<open>new (\<^bold>\<not> q) a ((ps, a) # branch) \<or> new (\<^bold>\<not> p) a ((ps, a) # branch)\<close>) case True then show ?thesis using assms DisN STA_Suc by fast next case False then show ?thesis using assms Dup by (metis (no_types, lifting) list.set_intros(1-2) new_def on.simps set_ConsD) qed lemma DiaP': assumes \<open>(\<^bold>\<diamond> p) at a in (ps, a) # branch\<close> \<open>i \<notin> A \<union> branch_nominals ((ps, a) # branch)\<close> \<open>\<nexists>a. p = Nom a\<close> \<open>\<not> witnessed p a ((ps, a) # branch)\<close> \<open>A, n \<turnstile> ((\<^bold>@ i p) # (\<^bold>\<diamond> Nom i) # ps, a) # branch\<close> shows \<open>A, n \<turnstile> (ps, a) # branch\<close> using assms DiaP STA_Suc by fast lemma DiaN': assumes \<open>(\<^bold>\<not> (\<^bold>\<diamond> p)) at a in (ps, a) # branch\<close> \<open>(\<^bold>\<diamond> Nom i) at a in (ps, a) # branch\<close> \<open>A, n \<turnstile> ((\<^bold>\<not> (\<^bold>@ i p)) # ps, a) # branch\<close> shows \<open>A, n \<turnstile> (ps, a) # branch\<close> using assms DiaN Dup STA_Suc by fast lemma SatP': assumes \<open>(\<^bold>@ a p) at b in (ps, a) # branch\<close> \<open>A, n \<turnstile> (p # ps, a) # branch\<close> shows \<open>A, n \<turnstile> (ps, a) # branch\<close> using assms SatP Dup STA_Suc by fast lemma SatN': assumes \<open>(\<^bold>\<not> (\<^bold>@ a p)) at b in (ps, a) # branch\<close> \<open>A, n \<turnstile> ((\<^bold>\<not> p) # ps, a) # branch\<close> shows \<open>A, n \<turnstile> (ps, a) # branch\<close> using assms SatN Dup STA_Suc by fast lemma Nom': assumes \<open>p at b in (ps, a) # branch\<close> \<open>Nom a at b in (ps, a) # branch\<close> \<open>\<forall>i. p = Nom i \<or> p = (\<^bold>\<diamond> Nom i) \<longrightarrow> i \<in> A\<close> \<open>A, n \<turnstile> (p # ps, a) # branch\<close> shows \<open>A, n \<turnstile> (ps, a) # branch\<close> proof (cases \<open>new p a ((ps, a) # branch)\<close>) case True moreover have \<open>A, Suc n \<turnstile> (p # ps, a) # branch\<close> using assms(4) STA_Suc by blast ultimately show ?thesis using assms(1-3) Nom by metis next case False then show ?thesis using assms Dup by fast qed section \<open>Substitution\<close> lemma finite_nominals: \<open>finite (nominals p)\<close> by (induct p) simp_all lemma finite_block_nominals: \<open>finite (block_nominals block)\<close> using finite_nominals by (induct block) auto lemma finite_branch_nominals: \<open>finite (branch_nominals branch)\<close> unfolding branch_nominals_def by (induct branch) (auto simp: finite_block_nominals) abbreviation sub_list :: \<open>('b \<Rightarrow> 'c) \<Rightarrow> ('a, 'b) fm list \<Rightarrow> ('a, 'c) fm list\<close> where \<open>sub_list f ps \<equiv> map (sub f) ps\<close> primrec sub_block :: \<open>('b \<Rightarrow> 'c) \<Rightarrow> ('a, 'b) block \<Rightarrow> ('a, 'c) block\<close> where \<open>sub_block f (ps, i) = (sub_list f ps, f i)\<close> definition sub_branch :: \<open>('b \<Rightarrow> 'c) \<Rightarrow> ('a, 'b) branch \<Rightarrow> ('a, 'c) branch\<close> where \<open>sub_branch f blocks \<equiv> map (sub_block f) blocks\<close> lemma sub_block_mem: \<open>p on block \<Longrightarrow> sub f p on sub_block f block\<close> by (induct block) auto lemma sub_branch_mem: assumes \<open>(ps, i) \<in>. branch\<close> shows \<open>(sub_list f ps, f i) \<in>. sub_branch f branch\<close> unfolding sub_branch_def using assms image_iff by fastforce lemma sub_block_nominals: \<open>block_nominals (sub_block f block) = f ` block_nominals block\<close> by (induct block) (auto simp: sub_nominals) lemma sub_branch_nominals: \<open>branch_nominals (sub_branch f branch) = f ` branch_nominals branch\<close> unfolding branch_nominals_def sub_branch_def by (induct branch) (auto simp: sub_block_nominals) lemma sub_list_id: \<open>sub_list id ps = ps\<close> using sub_id by (induct ps) auto lemma sub_block_id: \<open>sub_block id block = block\<close> using sub_list_id by (induct block) auto lemma sub_branch_id: \<open>sub_branch id branch = branch\<close> unfolding sub_branch_def using sub_block_id by (induct branch) auto lemma sub_block_upd_fresh: assumes \<open>i \<notin> block_nominals block\<close> shows \<open>sub_block (f(i := j)) block = sub_block f block\<close> using assms by (induct block) (auto simp add: sub_upd_fresh) lemma sub_branch_upd_fresh: assumes \<open>i \<notin> branch_nominals branch\<close> shows \<open>sub_branch (f(i := j)) branch = sub_branch f branch\<close> using assms unfolding branch_nominals_def sub_branch_def by (induct branch) (auto simp: sub_block_upd_fresh) lemma sub_comp: \<open>sub f (sub g p) = sub (f o g) p\<close> by (induct p) simp_all lemma sub_list_comp: \<open>sub_list f (sub_list g ps) = sub_list (f o g) ps\<close> using sub_comp by (induct ps) auto lemma sub_block_comp: \<open>sub_block f (sub_block g block) = sub_block (f o g) block\<close> using sub_list_comp by (induct block) simp_all lemma sub_branch_comp: \<open>sub_branch f (sub_branch g branch) = sub_branch (f o g) branch\<close> unfolding sub_branch_def using sub_block_comp by (induct branch) fastforce+ lemma swap_id: \<open>(id(i := j, j := i)) o (id(i := j, j := i)) = id\<close> by auto lemma at_in_sub_branch: assumes \<open>p at i in (ps, a) # branch\<close> shows \<open>sub f p at f i in (sub_list f ps, f a) # sub_branch f branch\<close> using assms sub_branch_mem by fastforce lemma sub_still_allowed: assumes \<open>\<forall>i. p = Nom i \<or> p = (\<^bold>\<diamond> Nom i) \<longrightarrow> i \<in> A\<close> shows \<open>sub f p = Nom i \<or> sub f p = (\<^bold>\<diamond> Nom i) \<longrightarrow> i \<in> f ` A\<close> proof safe assume \<open>sub f p = Nom i\<close> then obtain i' where i': \<open>p = Nom i'\<close> \<open>f i' = i\<close> by (cases p) simp_all then have \<open>i' \<in> A\<close> using assms by fast then show \<open>i \<in> f ` A\<close> using i' by fast next assume \<open>sub f p = (\<^bold>\<diamond> Nom i)\<close> then obtain i' where i': \<open>p = (\<^bold>\<diamond> Nom i')\<close> \<open>f i' = i\<close> proof (induct p) case (Dia q) then show ?case by (cases q) simp_all qed simp_all then have \<open>i' \<in> A\<close> using assms by fast then show \<open>i \<in> f ` A\<close> using i' by fast qed text \<open> If a branch has a closing tableau then so does any branch obtained by renaming nominals as long as the substitution leaves some nominals free. This is always the case for substitutions that do not change the type of nominals. Since some formulas on the renamed branch may no longer be new, they do not contribute any potential and so we existentially quantify over the potential needed to close the new branch. We assume that the set of allowed nominals \<open>A\<close> is finite such that we can obtain a free nominal. \<close> lemma STA_sub': fixes f :: \<open>'b \<Rightarrow> 'c\<close> assumes \<open>\<And>(f :: 'b \<Rightarrow> 'c) i A. finite A \<Longrightarrow> i \<notin> A \<Longrightarrow> \<exists>j. j \<notin> f ` A\<close> \<open>finite A\<close> \<open>A, n \<turnstile> branch\<close> shows \<open>f ` A \<turnstile> sub_branch f branch\<close> using assms(3-) proof (induct n branch arbitrary: f rule: STA.induct) case (Close p i branch n) have \<open>sub f p at f i in sub_branch f branch\<close> using Close(1) sub_branch_mem by fastforce moreover have \<open>(\<^bold>\<not> sub f p) at f i in sub_branch f branch\<close> using Close(2) sub_branch_mem by force ultimately show ?case using STA.Close by fast next case (Neg p a ps branch n f) then have \<open>f ` A \<turnstile> (sub f p # sub_list f ps, f a) # sub_branch f branch\<close> unfolding sub_branch_def by simp moreover have \<open>(\<^bold>\<not> \<^bold>\<not> sub f p) at f a in (sub_list f ps, f a) # sub_branch f branch\<close> using Neg(1) at_in_sub_branch by (metis (no_types, opaque_lifting) sub.simps(3)) ultimately have \<open>f ` A \<turnstile> (sub_list f ps, f a) # sub_branch f branch\<close> using Neg' by fast then show ?case unfolding sub_branch_def by simp next case (DisP p q a ps branch n) then have \<open>f ` A \<turnstile> (sub f p # sub_list f ps, f a) # sub_branch f branch\<close> \<open>f ` A \<turnstile> (sub f q # sub_list f ps, f a) # sub_branch f branch\<close> unfolding sub_branch_def by simp_all moreover have \<open>(sub f p \<^bold>\<or> sub f q) at f a in (sub_list f ps, f a) # sub_branch f branch\<close> using DisP(1) at_in_sub_branch by (metis (no_types, opaque_lifting) sub.simps(4)) ultimately have \<open>f ` A \<turnstile> (sub_list f ps, f a) # sub_branch f branch\<close> using DisP'' by fast then show ?case unfolding sub_branch_def by simp next case (DisN p q a ps branch n) then have \<open>f ` A \<turnstile> ((\<^bold>\<not> sub f q) # (\<^bold>\<not> sub f p) # sub_list f ps, f a) # sub_branch f branch\<close> unfolding sub_branch_def by simp moreover have \<open>(\<^bold>\<not> (sub f p \<^bold>\<or> sub f q)) at f a in (sub_list f ps, f a) # sub_branch f branch\<close> using DisN(1) at_in_sub_branch by (metis (no_types, opaque_lifting) sub.simps(3-4)) ultimately have \<open>f ` A \<turnstile> (sub_list f ps, f a) # sub_branch f branch\<close> using DisN' by fast then show ?case unfolding sub_branch_def by simp next case (DiaP p a ps branch i n) have \<open>i \<notin> A\<close> using DiaP(2) by simp show ?case proof (cases \<open>witnessed (sub f p) (f a) (sub_branch f ((ps, a) # branch))\<close>) case True then obtain i' where rs: \<open>(\<^bold>@ i' (sub f p)) at f a in (sub_list f ps, f a) # sub_branch f branch\<close> and ts: \<open>(\<^bold>\<diamond> Nom i') at f a in (sub_list f ps, f a) # sub_branch f branch\<close> unfolding sub_branch_def witnessed_def by auto from rs have rs': \<open>(\<^bold>@ i' (sub f p)) at f a in ((\<^bold>\<diamond> Nom i') # sub_list f ps, f a) # sub_branch f branch\<close> by fastforce let ?f = \<open>f(i := i')\<close> let ?branch = \<open>sub_branch ?f branch\<close> have \<open>sub_branch ?f ((ps, a) # branch) = sub_branch f ((ps, a) # branch)\<close> using DiaP(2) sub_branch_upd_fresh by fast then have **: \<open>sub_list ?f ps = sub_list f ps\<close> \<open>?f a = f a\<close> \<open>?branch = sub_branch f branch\<close> unfolding sub_branch_def by simp_all have p: \<open>sub ?f p = sub f p\<close> using DiaP(1-2) sub_upd_fresh unfolding branch_nominals_def by fastforce have \<open>?f ` A \<turnstile> sub_branch ?f (((\<^bold>@ i p) # (\<^bold>\<diamond> Nom i) # ps, a) # branch)\<close> using DiaP(6) by blast then have \<open>?f ` A \<turnstile> ((\<^bold>@ (?f i) (sub ?f p)) # (\<^bold>\<diamond> Nom (?f i)) # sub_list ?f ps, ?f a) # ?branch\<close> unfolding sub_branch_def by fastforce then have \<open>?f ` A \<turnstile> ((\<^bold>@ i' (sub f p)) # (\<^bold>\<diamond> Nom i') # sub_list f ps, f a) # sub_branch f branch\<close> using p ** by simp then have \<open>?f ` A \<turnstile> ((\<^bold>\<diamond> Nom i') # sub_list f ps, f a) # sub_branch f branch\<close> using rs' by (meson Dup new_def) then have \<open>?f ` A \<turnstile> (sub_list f ps, f a) # sub_branch f branch\<close> using ts by (meson Dup new_def) moreover have \<open>?f ` A = f ` A\<close> using \<open>i \<notin> A\<close> by auto ultimately show ?thesis unfolding sub_branch_def by auto next case False have \<open>finite (branch_nominals ((ps, a) # branch))\<close> by (simp add: finite_branch_nominals) then have \<open>finite (A \<union> branch_nominals ((ps, a) # branch))\<close> using \<open>finite A\<close> by simp then obtain j where *: \<open>j \<notin> f ` (A \<union> branch_nominals ((ps, a) # branch))\<close> using DiaP(2) assms by metis then have \<open>j \<notin> f ` A\<close> by blast let ?f = \<open>f(i := j)\<close> let ?branch = \<open>sub_branch ?f branch\<close> have **: \<open>sub_branch ?f ((ps, a) # branch) = sub_branch f ((ps, a) # branch)\<close> using DiaP(2) sub_branch_upd_fresh by fast then have ***: \<open>sub_list ?f ps = sub_list f ps\<close> \<open>?f a = f a\<close> \<open>?branch = sub_branch f branch\<close> unfolding sub_branch_def by simp_all moreover have p: \<open>sub ?f p = sub f p\<close> using DiaP(1-2) sub_upd_fresh unfolding branch_nominals_def by fastforce ultimately have \<open>\<not> witnessed (sub ?f p) (?f a) (sub_branch ?f ((ps, a) # branch))\<close> using False ** by simp then have w: \<open>\<not> witnessed (sub ?f p) (?f a) ((sub_list ?f ps, ?f a) # ?branch)\<close> unfolding sub_branch_def by simp have f: \<open>?f ` A = f ` A\<close> using \<open>i \<notin> A\<close> by auto have \<open>?f ` A \<turnstile> sub_branch ?f (((\<^bold>@ i p) # (\<^bold>\<diamond> Nom i) # ps, a) # branch)\<close> using DiaP(6) by blast then have \<open>f ` A \<turnstile> ((\<^bold>@ (?f i) (sub ?f p)) # (\<^bold>\<diamond> Nom (?f i)) # sub_list ?f ps, ?f a) # ?branch\<close> unfolding sub_branch_def using f by simp moreover have \<open>sub ?f (\<^bold>\<diamond> p) at ?f a in (sub_list ?f ps, ?f a) # sub_branch ?f branch\<close> using DiaP(1) at_in_sub_branch by fast then have \<open>(\<^bold>\<diamond> sub ?f p) at ?f a in (sub_list ?f ps, ?f a) # sub_branch ?f branch\<close> by simp moreover have \<open>\<nexists>a. sub ?f p = Nom a\<close> using DiaP(3) by (cases p) simp_all moreover have \<open>j \<notin> f ` (branch_nominals ((ps, a) # branch))\<close> using * by blast then have \<open>?f i \<notin> branch_nominals ((sub_list ?f ps, ?f a) # ?branch)\<close> using ** sub_branch_nominals unfolding sub_branch_def by (metis fun_upd_same list.simps(9) sub_block.simps) ultimately have \<open>f ` A \<turnstile> (sub_list ?f ps, ?f a) # ?branch\<close> using w DiaP' \<open>j \<notin> f ` A\<close> by (metis Un_iff fun_upd_same) then show ?thesis using *** unfolding sub_branch_def by simp qed next case (DiaN p a ps branch i n) then have \<open>f ` A \<turnstile> ((\<^bold>\<not> (\<^bold>@ (f i) (sub f p))) # sub_list f ps, f a) # sub_branch f branch\<close> unfolding sub_branch_def by simp moreover have \<open>(\<^bold>\<not> (\<^bold>\<diamond> sub f p)) at f a in (sub_list f ps, f a) # sub_branch f branch\<close> using DiaN(1) at_in_sub_branch by (metis (no_types, opaque_lifting) sub.simps(3, 5)) moreover have \<open>(\<^bold>\<diamond> Nom (f i)) at f a in (sub_list f ps, f a) # sub_branch f branch\<close> using DiaN(2) at_in_sub_branch by (metis (no_types, opaque_lifting) sub.simps(2, 5)) ultimately have \<open>f ` A \<turnstile> (sub_list f ps, f a) # sub_branch f branch\<close> using DiaN' by fast then show ?case unfolding sub_branch_def by simp next case (SatP a p b ps branch n) then have \<open>f ` A \<turnstile> (sub f p # sub_list f ps, f a) # sub_branch f branch\<close> unfolding sub_branch_def by simp moreover have \<open>(\<^bold>@ (f a) (sub f p)) at f b in (sub_list f ps, f a) # sub_branch f branch\<close> using SatP(1) at_in_sub_branch by (metis (no_types, opaque_lifting) sub.simps(6)) ultimately have \<open>f ` A \<turnstile> (sub_list f ps, f a) # sub_branch f branch\<close> using SatP' by fast then show ?case unfolding sub_branch_def by simp next case (SatN a p b ps branch n) then have \<open>f ` A \<turnstile> ((\<^bold>\<not> sub f p) # sub_list f ps, f a) # sub_branch f branch\<close> unfolding sub_branch_def by simp moreover have \<open>(\<^bold>\<not> (\<^bold>@ (f a) (sub f p))) at f b in (sub_list f ps, f a) # sub_branch f branch\<close> using SatN(1) at_in_sub_branch by (metis (no_types, opaque_lifting) sub.simps(3, 6)) ultimately have \<open>f ` A \<turnstile> (sub_list f ps, f a) # sub_branch f branch\<close> using SatN' by fast then show ?case unfolding sub_branch_def by simp next case (GoTo i branch n) then have \<open>f ` A \<turnstile> ([], f i) # sub_branch f branch\<close> unfolding sub_branch_def by simp moreover have \<open>f i \<in> branch_nominals (sub_branch f branch)\<close> using GoTo(1) sub_branch_nominals by fast ultimately show ?case using STA.GoTo by fast next case (Nom p b ps a branch n) then have \<open>f ` A \<turnstile> sub_branch f ((p # ps, a) # branch)\<close> by blast then have \<open>f ` A \<turnstile> (sub f p # sub_list f ps, f a) # sub_branch f branch\<close> unfolding sub_branch_def by simp moreover have \<open>sub f p at f b in (sub_list f ps, f a) # sub_branch f branch\<close> using Nom(1) at_in_sub_branch by fast moreover have \<open>Nom (f a) at f b in (sub_list f ps, f a) # sub_branch f branch\<close> using Nom(2) at_in_sub_branch by (metis (no_types, opaque_lifting) sub.simps(2)) moreover have \<open>\<forall>i. sub f p = Nom i \<or> sub f p = (\<^bold>\<diamond> Nom i) \<longrightarrow> i \<in> f ` A\<close> using Nom(3) sub_still_allowed by metis ultimately have \<open>f ` A \<turnstile> (sub_list f ps, f a) # sub_branch f branch\<close> using Nom' by metis then show ?case unfolding sub_branch_def by simp qed lemma ex_fresh_gt: fixes f :: \<open>'b \<Rightarrow> 'c\<close> assumes \<open>\<exists>g :: 'c \<Rightarrow> 'b. surj g\<close> \<open>finite A\<close> \<open>i \<notin> A\<close> shows \<open>\<exists>j. j \<notin> f ` A\<close> proof (rule ccontr) assume \<open>\<nexists>j. j \<notin> f ` A\<close> moreover obtain g :: \<open>'c \<Rightarrow> 'b\<close> where \<open>surj g\<close> using assms(1) by blast ultimately show False using assms(2-3) by (metis UNIV_I UNIV_eq_I card_image_le card_seteq finite_imageI image_comp subsetI) qed corollary STA_sub_gt: fixes f :: \<open>'b \<Rightarrow> 'c\<close> assumes \<open>\<exists>g :: 'c \<Rightarrow> 'b. surj g\<close> \<open>A \<turnstile> branch\<close> \<open>finite A\<close> \<open>\<forall>i \<in> branch_nominals branch. f i \<in> f ` A \<longrightarrow> i \<in> A\<close> shows \<open>f ` A \<turnstile> sub_branch f branch\<close> using assms ex_fresh_gt STA_sub' by metis corollary STA_sub_inf: fixes f :: \<open>'b \<Rightarrow> 'c\<close> assumes \<open>infinite (UNIV :: 'c set)\<close> \<open>A \<turnstile> branch\<close> \<open>finite A\<close> \<open>\<forall>i \<in> branch_nominals branch. f i \<in> f ` A \<longrightarrow> i \<in> A\<close> shows \<open>f ` A \<turnstile> sub_branch f branch\<close> proof - have \<open>finite A \<Longrightarrow> \<exists>j. j \<notin> f ` A\<close> for A and f :: \<open>'b \<Rightarrow> 'c\<close> using assms(1) ex_new_if_finite by blast then show ?thesis using assms(2-) STA_sub' by metis qed corollary STA_sub: fixes f :: \<open>'b \<Rightarrow> 'b\<close> assumes \<open>A \<turnstile> branch\<close> \<open>finite A\<close> shows \<open>f ` A \<turnstile> sub_branch f branch\<close> proof - have \<open>finite A \<Longrightarrow> i \<notin> A \<Longrightarrow> \<exists>j. j \<notin> f ` A\<close> for i A and f :: \<open>'b \<Rightarrow> 'b\<close> by (metis card_image_le card_seteq finite_imageI subsetI) then show ?thesis using assms STA_sub' by metis qed subsection \<open>Unrestricted \<open>(\<^bold>\<diamond>)\<close> rule\<close> lemma DiaP'': assumes \<open>(\<^bold>\<diamond> p) at a in (ps, a) # branch\<close> \<open>i \<notin> A \<union> branch_nominals ((ps, a) # branch)\<close> \<open>\<nexists>a. p = Nom a\<close> \<open>finite A\<close> \<open>A \<turnstile> ((\<^bold>@ i p) # (\<^bold>\<diamond> Nom i) # ps, a) # branch\<close> shows \<open>A \<turnstile> (ps, a) # branch\<close> proof (cases \<open>witnessed p a ((ps, a) # branch)\<close>) case True then obtain i' where rs: \<open>(\<^bold>@ i' p) at a in (ps, a) # branch\<close> and ts: \<open>(\<^bold>\<diamond> Nom i') at a in (ps, a) # branch\<close> unfolding witnessed_def by blast then have rs': \<open>(\<^bold>@ i' p) at a in ((\<^bold>\<diamond> Nom i') # ps, a) # branch\<close> by fastforce let ?f = \<open>id(i := i')\<close> have \<open>?f ` A \<turnstile> sub_branch ?f (((\<^bold>@ i p) # (\<^bold>\<diamond> Nom i) # ps, a) # branch)\<close> using assms(4-5) STA_sub by blast then have \<open>?f ` A \<turnstile> ((\<^bold>@ i' (sub ?f p)) # (\<^bold>\<diamond> Nom i') # sub_list ?f ps, ?f a) # sub_branch ?f branch\<close> unfolding sub_branch_def by simp moreover have \<open>i \<notin> nominals p\<close> \<open>i \<notin> list_nominals ps\<close> \<open>i \<noteq> a\<close> \<open>i \<notin> branch_nominals branch\<close> using assms(1-3) unfolding branch_nominals_def by fastforce+ then have \<open>sub ?f p = p\<close> by (simp add: sub_id sub_upd_fresh) moreover have \<open>sub_list ?f ps = ps\<close> using \<open>i \<notin> list_nominals ps\<close> by (simp add: map_idI sub_id sub_upd_fresh) moreover have \<open>?f a = a\<close> using \<open>i \<noteq> a\<close> by simp moreover have \<open>sub_branch ?f branch = branch\<close> using \<open>i \<notin> branch_nominals branch\<close> by (simp add: sub_branch_id sub_branch_upd_fresh) ultimately have \<open>?f ` A \<turnstile> ((\<^bold>@ i' p) # (\<^bold>\<diamond> Nom i') # ps, a) # branch\<close> by simp then have \<open>?f ` A \<turnstile> ((\<^bold>\<diamond> Nom i') # ps, a) # branch\<close> using rs' by (meson Dup new_def) then have \<open>?f ` A \<turnstile> (ps, a) # branch\<close> using ts by (meson Dup new_def) moreover have \<open>?f ` A = A\<close> using assms(2) by auto ultimately show ?thesis by simp next case False then show ?thesis using assms DiaP' STA_Suc by fast qed section \<open>Structural Properties\<close> lemma block_nominals_branch: assumes \<open>block \<in>. branch\<close> shows \<open>block_nominals block \<subseteq> branch_nominals branch\<close> unfolding branch_nominals_def using assms by blast lemma sub_block_fresh: assumes \<open>i \<notin> branch_nominals branch\<close> \<open>block \<in>. branch\<close> shows \<open>sub_block (f(i := j)) block = sub_block f block\<close> using assms block_nominals_branch sub_block_upd_fresh by fast lemma list_down_induct [consumes 1, case_names Start Cons]: assumes \<open>\<forall>y \<in> set ys. Q y\<close> \<open>P (ys @ xs)\<close> \<open>\<And>y xs. Q y \<Longrightarrow> P (y # xs) \<Longrightarrow> P xs\<close> shows \<open>P xs\<close> using assms by (induct ys) auto text \<open> If the last block on a branch has opening nominal \<open>a\<close> and the last formulas on that block occur on another block alongside nominal \<open>a\<close>, then we can drop those formulas. \<close> lemma STA_drop_prefix: assumes \<open>set ps \<subseteq> set qs\<close> \<open>(qs, a) \<in>. branch\<close> \<open>A, n \<turnstile> (ps @ ps', a) # branch\<close> shows \<open>A, n \<turnstile> (ps', a) # branch\<close> proof - have \<open>\<forall>p \<in> set ps. p on (qs, a)\<close> using assms(1) by auto then show ?thesis proof (induct ps' rule: list_down_induct) case Start then show ?case using assms(3) . next case (Cons p ps) then show ?case using assms(2) by (meson Dup new_def list.set_intros(2)) qed qed text \<open>We can drop a block if it is subsumed by another block.\<close> lemma STA_drop_block: assumes \<open>set ps \<subseteq> set ps'\<close> \<open>(ps', a) \<in>. branch\<close> \<open>A, n \<turnstile> (ps, a) # branch\<close> shows \<open>A, Suc n \<turnstile> branch\<close> using assms proof (induct branch) case Nil then show ?case by simp next case (Cons block branch) then show ?case proof (cases block) case (Pair qs b) then have \<open>A, n \<turnstile> ([], a) # (qs, b) # branch\<close> using Cons(2-4) STA_drop_prefix[where branch=\<open>(qs, b) # branch\<close>] by simp moreover have \<open>a \<in> branch_nominals ((qs, b) # branch)\<close> unfolding branch_nominals_def using Cons(3) Pair by fastforce ultimately have \<open>A, Suc n \<turnstile> (qs, b) # branch\<close> by (simp add: GoTo) then show ?thesis using Pair Dup by fast qed qed lemma STA_drop_block': assumes \<open>A, n \<turnstile> (ps, a) # branch\<close> \<open>(ps, a) \<in>. branch\<close> shows \<open>A, Suc n \<turnstile> branch\<close> using assms STA_drop_block by fastforce lemma sub_branch_image: \<open>set (sub_branch f branch) = sub_block f ` set branch\<close> unfolding sub_branch_def by simp lemma sub_block_repl: assumes \<open>j \<notin> block_nominals block\<close> shows \<open>i \<notin> block_nominals (sub_block (id(i := j, j := i)) block)\<close> using assms by (simp add: image_iff sub_block_nominals) lemma sub_branch_repl: assumes \<open>j \<notin> branch_nominals branch\<close> shows \<open>i \<notin> branch_nominals (sub_branch (id(i := j, j := i)) branch)\<close> using assms by (simp add: image_iff sub_branch_nominals) text \<open>If a finite set of blocks has a closing tableau then so does any finite superset.\<close> lemma STA_struct: fixes branch :: \<open>('a, 'b) branch\<close> assumes inf: \<open>infinite (UNIV :: 'b set)\<close> and fin: \<open>finite A\<close> and \<open>A, n \<turnstile> branch\<close> \<open>set branch \<subseteq> set branch'\<close> shows \<open>A \<turnstile> branch'\<close> using assms(3-) proof (induct n branch arbitrary: branch' rule: STA.induct) case (Close p i branch n) then show ?case using STA.Close by fast next case (Neg p a ps branch n) have \<open>A \<turnstile> (p # ps, a) # branch'\<close> using Neg(4-) by (simp add: subset_code(1)) moreover have \<open>(\<^bold>\<not> \<^bold>\<not> p) at a in (ps, a) # branch'\<close> using Neg(1, 5) by auto ultimately have \<open>A \<turnstile> (ps, a) # branch'\<close> using Neg' by fast moreover have \<open>(ps, a) \<in>. branch'\<close> using Neg(5) by simp ultimately show ?case using STA_drop_block' by fast next case (DisP p q a ps branch n) have \<open>A \<turnstile> (p # ps, a) # branch'\<close> \<open>A \<turnstile> (q # ps, a) # branch'\<close> using DisP(5, 7-) by (simp_all add: subset_code(1)) moreover have \<open>(p \<^bold>\<or> q) at a in (ps, a) # branch'\<close> using DisP(1, 8) by auto ultimately have \<open>A \<turnstile> (ps, a) # branch'\<close> using DisP'' by fast moreover have \<open>(ps, a) \<in>. branch'\<close> using DisP(8) by simp ultimately show ?case using STA_drop_block' by fast next case (DisN p q a ps branch n) have \<open>A \<turnstile> ((\<^bold>\<not> q) # (\<^bold>\<not> p) # ps, a)# branch'\<close> using DisN(4-) by (simp add: subset_code(1)) moreover have \<open>(\<^bold>\<not> (p \<^bold>\<or> q)) at a in (ps, a) # branch'\<close> using DisN(1, 5) by auto ultimately have \<open>A \<turnstile> (ps, a) # branch'\<close> using DisN' by fast moreover have \<open>(ps, a) \<in>. branch'\<close> using DisN(5) by simp ultimately show ?case using STA_drop_block' by fast next case (DiaP p a ps branch i n) have \<open>finite (A \<union> branch_nominals branch')\<close> using fin by (simp add: finite_branch_nominals) then obtain j where j: \<open>j \<notin> A \<union> branch_nominals branch'\<close> using assms ex_new_if_finite by blast then have j': \<open>j \<notin> branch_nominals ((ps, a) # branch)\<close> using DiaP(7) unfolding branch_nominals_def by blast let ?f = \<open>id(i := j, j := i)\<close> let ?branch' = \<open>sub_branch ?f branch'\<close> have branch': \<open>sub_branch ?f ?branch' = branch'\<close> using sub_branch_comp sub_branch_id swap_id by metis have \<open>i \<notin> branch_nominals ((ps, a) # branch)\<close> using DiaP(2) by blast then have branch: \<open>sub_branch ?f ((ps, a) # branch) = (ps, a) # branch\<close> using DiaP(2) j' sub_branch_id sub_branch_upd_fresh by metis moreover have \<open>set (sub_branch ?f ((ps, a) # branch)) \<subseteq> set ?branch'\<close> using DiaP(7) sub_branch_image by blast ultimately have *: \<open>set ((ps, a) # branch) \<subseteq> set ?branch'\<close> unfolding sub_branch_def by auto have \<open>i \<notin> block_nominals (ps, a)\<close> using DiaP unfolding branch_nominals_def by simp moreover have \<open>i \<notin> branch_nominals ?branch'\<close> using j sub_branch_repl by fast ultimately have i: \<open>i \<notin> branch_nominals ((ps, a) # ?branch')\<close> unfolding branch_nominals_def by simp have \<open>?f ` A = A\<close> using DiaP(2) j by auto have \<open>A \<turnstile> ((\<^bold>@ i p) # (\<^bold>\<diamond> Nom i) # ps, a) # ?branch'\<close> using DiaP(6) * by (metis (no_types, lifting) subset_code(1) insert_mono list.set(2) set_subset_Cons) moreover have \<open>(\<^bold>\<diamond> p) at a in (ps, a) # ?branch'\<close> using DiaP(1, 7) * by (meson set_subset_Cons subset_code(1)) ultimately have \<open>A \<turnstile> (ps, a) # ?branch'\<close> using inf DiaP(2-3) fin i DiaP'' by (metis Un_iff) then have \<open>?f ` A \<turnstile> sub_branch ?f ((ps, a) # ?branch')\<close> using STA_sub fin by blast then have \<open>A \<turnstile> (ps, a) # branch'\<close> using \<open>?f ` A = A\<close> branch' branch unfolding sub_branch_def by simp moreover have \<open>(ps, a) \<in>. branch'\<close> using \<open>set ((ps, a) # branch) \<subseteq> set branch'\<close> by simp ultimately show ?case using STA_drop_block' by fast next case (DiaN p a ps branch i n) have \<open>A \<turnstile> ((\<^bold>\<not> (\<^bold>@ i p)) # ps, a) # branch'\<close> using DiaN(5-) by (simp add: subset_code(1)) moreover have \<open>(\<^bold>\<not> (\<^bold>\<diamond> p)) at a in (ps, a) # branch'\<close> \<open>(\<^bold>\<diamond> Nom i) at a in (ps, a) # branch'\<close> using DiaN(1-2, 6) by auto ultimately have \<open>A \<turnstile> (ps, a) # branch'\<close> using DiaN' by fast moreover have \<open>(ps, a) \<in>. branch'\<close> using DiaN(6) by simp ultimately show ?case using STA_drop_block' by fast next case (SatP a p b ps branch n) have \<open>A \<turnstile> (p # ps, a) # branch'\<close> using SatP(4-) by (simp add: subset_code(1)) moreover have \<open>(\<^bold>@ a p) at b in (ps, a) # branch'\<close> using SatP(1, 5) by auto ultimately have \<open>A \<turnstile> (ps, a) # branch'\<close> using SatP' by fast moreover have \<open>(ps, a) \<in>. branch'\<close> using SatP(5) by simp ultimately show ?case using STA_drop_block' by fast next case (SatN a p b ps branch n) have \<open>A \<turnstile> ((\<^bold>\<not> p) # ps, a) # branch'\<close> using SatN(4-) by (simp add: subset_code(1)) moreover have \<open>(\<^bold>\<not> (\<^bold>@ a p)) at b in (ps, a) # branch'\<close> using SatN(1, 5) by auto ultimately have \<open>A \<turnstile> (ps, a) # branch'\<close> using SatN' by fast moreover have \<open>(ps, a) \<in>. branch'\<close> using SatN(5) by simp ultimately show ?case using STA_drop_block' by fast next case (GoTo i branch n) then have \<open>A \<turnstile> ([], i) # branch'\<close> by (simp add: subset_code(1)) moreover have \<open>i \<in> branch_nominals branch'\<close> using GoTo(1, 4) unfolding branch_nominals_def by auto ultimately show ?case using GoTo(2) STA.GoTo by fast next case (Nom p b ps a branch n) have \<open>A \<turnstile> (p # ps, a) # branch'\<close> using Nom(6-) by (simp add: subset_code(1)) moreover have \<open>p at b in (ps, a) # branch'\<close> using Nom(1, 7) by auto moreover have \<open>Nom a at b in (ps, a) # branch'\<close> using Nom(2, 7) by auto ultimately have \<open>A \<turnstile> (ps, a) # branch'\<close> using Nom(3) Nom' by metis moreover have \<open>(ps, a) \<in>. branch'\<close> using Nom(7) by simp ultimately show ?case using STA_drop_block' by fast qed text \<open> If a branch has a closing tableau then we can replace the formulas of the last block on that branch with any finite superset and still obtain a closing tableau. \<close> lemma STA_struct_block: fixes branch :: \<open>('a, 'b) branch\<close> assumes inf: \<open>infinite (UNIV :: 'b set)\<close> and fin: \<open>finite A\<close> and \<open>A, n \<turnstile> (ps, a) # branch\<close> \<open>set ps \<subseteq> set ps'\<close> shows \<open>A \<turnstile> (ps', a) # branch\<close> using assms(3-) proof (induct n \<open>(ps, a) # branch\<close> arbitrary: ps ps' rule: STA.induct) case (Close p i n ts ts') then have \<open>p at i in (ts', a) # branch\<close> \<open>(\<^bold>\<not> p) at i in (ts', a) # branch\<close> by auto then show ?case using STA.Close by fast next case (Neg p ps n) then have \<open>(\<^bold>\<not> \<^bold>\<not> p) at a in (ps', a) # branch\<close> by auto moreover have \<open>A \<turnstile> (p # ps', a) # branch\<close> using Neg(4-) by (simp add: subset_code(1)) ultimately show ?case using Neg' by fast next case (DisP p q ps n) then have \<open>(p \<^bold>\<or> q) at a in (ps', a) # branch\<close> by auto moreover have \<open>A \<turnstile> (p # ps', a) # branch\<close> \<open>A \<turnstile> (q # ps', a) # branch\<close> using DisP(5, 7-) by (simp_all add: subset_code(1)) ultimately show ?case using DisP'' by fast next case (DisN p q ps n) then have \<open>(\<^bold>\<not> (p \<^bold>\<or> q)) at a in (ps', a) # branch\<close> by auto moreover have \<open>A \<turnstile> ((\<^bold>\<not> q) # (\<^bold>\<not> p) # ps', a) # branch\<close> using DisN(4-) by (simp add: subset_code(1)) ultimately show ?case using DisN' by fast next case (DiaP p ps i n) have \<open>finite (A \<union> branch_nominals ((ps', a) # branch))\<close> using fin finite_branch_nominals by blast then obtain j where j: \<open>j \<notin> A \<union> branch_nominals ((ps', a) # branch)\<close> using assms ex_new_if_finite by blast then have j': \<open>j \<notin> block_nominals (ps, a)\<close> using DiaP.prems unfolding branch_nominals_def by auto let ?f = \<open>id(i := j, j := i)\<close> let ?ps' = \<open>sub_list ?f ps'\<close> have ps': \<open>sub_list ?f ?ps' = ps'\<close> using sub_list_comp sub_list_id swap_id by metis have \<open>i \<notin> block_nominals (ps, a)\<close> using DiaP(1-2) unfolding branch_nominals_def by simp then have ps: \<open>sub_block ?f (ps, a) = (ps, a)\<close> using j' sub_block_id sub_block_upd_fresh by metis moreover have \<open>set (sub_list ?f ps) \<subseteq> set (sub_list ?f ps')\<close> using \<open>set ps \<subseteq> set ps'\<close> by auto ultimately have *: \<open>set ps \<subseteq> set ?ps'\<close> by simp have \<open>i \<notin> branch_nominals branch\<close> using DiaP unfolding branch_nominals_def by simp moreover have \<open>j \<notin> branch_nominals branch\<close> using j unfolding branch_nominals_def by simp ultimately have branch: \<open>sub_branch ?f branch = branch\<close> using sub_branch_id sub_branch_upd_fresh by metis have \<open>i \<noteq> a\<close> \<open>j \<noteq> a\<close> using DiaP j unfolding branch_nominals_def by simp_all then have \<open>?f a = a\<close> by simp moreover have \<open>j \<notin> block_nominals (ps', a)\<close> using j unfolding branch_nominals_def by simp ultimately have \<open>i \<notin> block_nominals (?ps', a)\<close> using sub_block_repl[where block=\<open>(ps', a)\<close> and i=i and j=j] by simp have \<open>?f ` A = A\<close> using DiaP(2) j by auto have \<open>(\<^bold>\<diamond> p) at a in (?ps', a) # branch\<close> using DiaP(1) * by fastforce moreover have \<open>A \<turnstile> ((\<^bold>@ i p) # (\<^bold>\<diamond> Nom i) # ?ps', a) # branch\<close> using * DiaP(6) fin by (simp add: subset_code(1)) moreover have \<open>i \<notin> A \<union> branch_nominals ((?ps', a) # branch)\<close> using DiaP(2) \<open>i \<notin> block_nominals (?ps', a)\<close> unfolding branch_nominals_def by simp ultimately have \<open>A \<turnstile> (?ps', a) # branch\<close> using DiaP(3) fin DiaP'' by metis then have \<open>?f ` A \<turnstile> sub_branch ?f ((?ps', a) # branch)\<close> using STA_sub fin by blast then have \<open>A \<turnstile> (sub_list ?f ?ps', ?f a) # sub_branch ?f branch\<close> unfolding sub_branch_def using \<open>?f ` A = A\<close> by simp then show ?case using \<open>?f a = a\<close> ps' branch by simp next case (DiaN p ps i n) then have \<open>(\<^bold>\<not> (\<^bold>\<diamond> p)) at a in (ps', a) # branch\<close> \<open>(\<^bold>\<diamond> Nom i) at a in (ps', a) # branch\<close> by auto moreover have \<open>A \<turnstile> ((\<^bold>\<not> (\<^bold>@ i p)) # ps', a) # branch\<close> using DiaN(5-) by (simp add: subset_code(1)) ultimately show ?case using DiaN' by fast next case (SatP p b ps n) then have \<open>(\<^bold>@ a p) at b in (ps', a) # branch\<close> by auto moreover have \<open>A \<turnstile> (p # ps', a) # branch\<close> using SatP(4-) by (simp add: subset_code(1)) ultimately show ?case using SatP' by fast next case (SatN p b ps n) then have \<open>(\<^bold>\<not> (\<^bold>@ a p)) at b in (ps', a) # branch\<close> by auto moreover have \<open>A \<turnstile> ((\<^bold>\<not> p) # ps', a) # branch\<close> using SatN(4-) by (simp add: subset_code(1)) ultimately show ?case using SatN' by fast next case (GoTo i n ps) then have \<open>A, Suc n \<turnstile> (ps, a) # branch\<close> using STA.GoTo by fast then obtain m where \<open>A, m \<turnstile> (ps, a) # (ps', a) # branch\<close> using inf fin STA_struct[where branch'=\<open>(ps, a) # _ # _\<close>] by fastforce then have \<open>A, Suc m \<turnstile> (ps', a) # branch\<close> using GoTo(4) by (simp add: STA_drop_block[where a=a]) then show ?case by blast next case (Nom p b ps n) have \<open>p at b in (ps', a) # branch\<close> using Nom(1, 7) by auto moreover have \<open>Nom a at b in (ps', a) # branch\<close> using Nom(2, 7) by auto moreover have \<open>A \<turnstile> (p # ps', a) # branch\<close> using Nom(6-) by (simp add: subset_code(1)) ultimately show ?case using Nom(3) Nom' by metis qed section \<open>Bridge\<close> text \<open> We define a \<open>descendants k i branch\<close> relation on sets of indices. The sets are built on the index of a \<open>\<^bold>\<diamond> Nom k\<close> on an \<open>i\<close>-block in \<open>branch\<close> and can be extended by indices of formula occurrences that can be thought of as descending from that \<open>\<^bold>\<diamond> Nom k\<close> by application of either the \<open>(\<^bold>\<not> \<^bold>\<diamond>)\<close> or \<open>Nom\<close> rule. We show that if we have nominals \<open>j\<close> and \<open>k\<close> on the same block in a closeable branch, then the branch obtained by the following transformation is also closeable: For every index \<open>v\<close>, if the formula at \<open>v\<close> is \<open>\<^bold>\<diamond> Nom k\<close>, replace it by \<open>\<^bold>\<diamond> Nom j\<close> and if it is \<open>\<^bold>\<not> (\<^bold>@ k p)\<close> replace it by \<open>\<^bold>\<not> (\<^bold>@ j p)\<close>. There are no other cases. From this transformation we can show admissibility of the Bridge rule under the assumption that \<open>j\<close> is an allowed nominal. \<close> subsection \<open>Replacing\<close> abbreviation bridge' :: \<open>'b \<Rightarrow> 'b \<Rightarrow> ('a, 'b) fm \<Rightarrow> ('a, 'b) fm\<close> where \<open>bridge' k j p \<equiv> case p of (\<^bold>\<diamond> Nom k') \<Rightarrow> (if k = k' then (\<^bold>\<diamond> Nom j) else (\<^bold>\<diamond> Nom k')) | (\<^bold>\<not> (\<^bold>@ k' q)) \<Rightarrow> (if k = k' then (\<^bold>\<not> (\<^bold>@ j q)) else (\<^bold>\<not> (\<^bold>@ k' q))) | p \<Rightarrow> p\<close> abbreviation bridge :: \<open>'b \<Rightarrow> 'b \<Rightarrow> (nat \<times> nat) set \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> ('a, 'b) fm \<Rightarrow> ('a, 'b) fm\<close> where \<open>bridge k j \<equiv> mapper (bridge' k j)\<close> lemma bridge_on_Nom: \<open>Nom i on (ps, a) \<Longrightarrow> Nom i on (mapi (bridge k j xs v) ps, a)\<close> by (induct ps) auto lemma bridge'_nominals: \<open>nominals (bridge' k j p) \<union> {k, j} = nominals p \<union> {k, j}\<close> proof (induct p) case (Neg p) then show ?case by (cases p) auto next case (Dia p) then show ?case by (cases p) auto qed auto lemma bridge_nominals: \<open>nominals (bridge k j xs v v' p) \<union> {k, j} = nominals p \<union> {k, j}\<close> proof (cases \<open>(v, v') \<in> xs\<close>) case True then have \<open>nominals (bridge k j xs v v' p) = nominals (bridge' k j p)\<close> by simp then show ?thesis using bridge'_nominals by metis qed simp lemma bridge_block_nominals: \<open>block_nominals (mapi_block (bridge k j xs v) (ps, a)) \<union> {k, j} = block_nominals (ps, a) \<union> {k, j}\<close> proof (induct ps) case Nil then show ?case by simp next case (Cons p ps) have \<open>?case \<longleftrightarrow> (nominals (bridge k j xs v (length ps) p)) \<union> (block_nominals (mapi_block (bridge k j xs v) (ps, a)) \<union> {k, j}) = (nominals p) \<union> (block_nominals (ps, a) \<union> {k, j})\<close> by simp also have \<open>\<dots> \<longleftrightarrow> (nominals (bridge k j xs v (length ps) p) \<union> {k, j}) \<union> (block_nominals (mapi_block (bridge k j xs v) (ps, a)) \<union> {k, j}) = (nominals p \<union> {k, j}) \<union> (block_nominals (ps, a) \<union> {k, j})\<close> by blast moreover have \<open>nominals (bridge k j xs v (length ps) p) \<union> {k, j} = nominals p \<union> {k, j}\<close> using bridge_nominals by metis moreover note Cons ultimately show ?case by argo qed lemma bridge_branch_nominals: \<open>branch_nominals (mapi_branch (bridge k j xs) branch) \<union> {k, j} = branch_nominals branch \<union> {k, j}\<close> proof (induct branch) case Nil then show ?case unfolding branch_nominals_def mapi_branch_def by simp next case (Cons block branch) have \<open>?case \<longleftrightarrow> (block_nominals (mapi_block (bridge k j xs (length branch)) block)) \<union> (branch_nominals (mapi_branch (bridge k j xs) branch) \<union> {k, j}) = (block_nominals block) \<union> (branch_nominals branch \<union> {k, j})\<close> unfolding branch_nominals_def mapi_branch_def by simp also have \<open>\<dots> \<longleftrightarrow> (block_nominals (mapi_block (bridge k j xs (length branch)) block) \<union> {k, j}) \<union> (branch_nominals (mapi_branch (bridge k j xs) branch) \<union> {k, j}) = (block_nominals block \<union> {k, j}) \<union> (branch_nominals branch \<union> {k, j})\<close> by blast moreover have \<open>block_nominals (mapi_block (bridge k j xs (length branch)) block) \<union> {k, j} = block_nominals block \<union> {k, j}\<close> using bridge_block_nominals[where ps=\<open>fst block\<close> and a=\<open>snd block\<close>] by simp ultimately show ?case using Cons by argo qed lemma at_in_mapi_branch: assumes \<open>p at a in branch\<close> \<open>p \<noteq> Nom a\<close> shows \<open>\<exists>v v'. f v v' p at a in mapi_branch f branch\<close> using assms by (meson mapi_branch_mem rev_nth_mapi_block rev_nth_on) lemma nom_at_in_bridge: fixes k j xs defines \<open>f \<equiv> bridge k j xs\<close> assumes \<open>Nom i at a in branch\<close> shows \<open>Nom i at a in mapi_branch f branch\<close> proof - obtain qs where qs: \<open>(qs, a) \<in>. branch\<close> \<open>Nom i on (qs, a)\<close> using assms(2) by blast then obtain l where \<open>(mapi (f l) qs, a) \<in>. mapi_branch f branch\<close> using mapi_branch_mem by fast moreover have \<open>Nom i on (mapi (f l) qs, a)\<close> unfolding f_def using qs(2) by (induct qs) auto ultimately show ?thesis by blast qed lemma nominals_mapi_branch_bridge: assumes \<open>Nom k at j in branch\<close> shows \<open>branch_nominals (mapi_branch (bridge k j xs) branch) = branch_nominals branch\<close> proof - let ?f = \<open>bridge k j xs\<close> have \<open>Nom k at j in mapi_branch ?f branch\<close> using assms nom_at_in_bridge by fast then have \<open>j \<in> branch_nominals (mapi_branch ?f branch)\<close> \<open>k \<in> branch_nominals (mapi_branch ?f branch)\<close> unfolding branch_nominals_def by fastforce+ moreover have \<open>j \<in> branch_nominals branch\<close> \<open>k \<in> branch_nominals branch\<close> using assms unfolding branch_nominals_def by fastforce+ moreover have \<open>branch_nominals (mapi_branch ?f branch) \<union> {k, j} = branch_nominals branch \<union> {k, j}\<close> using bridge_branch_nominals by metis ultimately show ?thesis by blast qed lemma bridge_proper_dia: assumes \<open>\<nexists>a. p = Nom a\<close> shows \<open>bridge k j xs v v' (\<^bold>\<diamond> p) = (\<^bold>\<diamond> p)\<close> using assms by (induct p) simp_all lemma bridge_compl_cases: fixes k j xs v v' w w' p defines \<open>q \<equiv> bridge k j xs v v' p\<close> and \<open>q' \<equiv> bridge k j xs w w' (\<^bold>\<not> p)\<close> shows \<open>(q = (\<^bold>\<diamond> Nom j) \<and> q' = (\<^bold>\<not> (\<^bold>\<diamond> Nom k))) \<or> (\<exists>r. q = (\<^bold>\<not> (\<^bold>@ j r)) \<and> q' = (\<^bold>\<not> \<^bold>\<not> (\<^bold>@ k r))) \<or> (\<exists>r. q = (\<^bold>@ k r) \<and> q' = (\<^bold>\<not> (\<^bold>@ j r))) \<or> (q = p \<and> q' = (\<^bold>\<not> p))\<close> proof (cases p) case (Neg p) then show ?thesis by (cases p) (simp_all add: q_def q'_def) next case (Dia p) then show ?thesis by (cases p) (simp_all add: q_def q'_def) qed (simp_all add: q_def q'_def) subsection \<open>Descendants\<close> inductive descendants :: \<open>'b \<Rightarrow> 'b \<Rightarrow> ('a, 'b) branch \<Rightarrow> (nat \<times> nat) set \<Rightarrow> bool\<close> where Initial: \<open>branch !. v = Some (qs, i) \<Longrightarrow> qs !. v' = Some (\<^bold>\<diamond> Nom k) \<Longrightarrow> descendants k i branch {(v, v')}\<close> | Derived: \<open>branch !. v = Some (qs, a) \<Longrightarrow> qs !. v' = Some (\<^bold>\<not> (\<^bold>@ k p)) \<Longrightarrow> descendants k i branch xs \<Longrightarrow> (w, w') \<in> xs \<Longrightarrow> branch !. w = Some (rs, a) \<Longrightarrow> rs !. w' = Some (\<^bold>\<diamond> Nom k) \<Longrightarrow> descendants k i branch ({(v, v')} \<union> xs)\<close> | Copied: \<open>branch !. v = Some (qs, a) \<Longrightarrow> qs !. v' = Some p \<Longrightarrow> descendants k i branch xs \<Longrightarrow> (w, w') \<in> xs \<Longrightarrow> branch !. w = Some (rs, b) \<Longrightarrow> rs !. w' = Some p \<Longrightarrow> Nom a at b in branch \<Longrightarrow> descendants k i branch ({(v, v')} \<union> xs)\<close> lemma descendants_initial: assumes \<open>descendants k i branch xs\<close> shows \<open>\<exists>(v, v') \<in> xs. \<exists>ps. branch !. v = Some (ps, i) \<and> ps !. v' = Some (\<^bold>\<diamond> Nom k)\<close> using assms by (induct k i branch xs rule: descendants.induct) simp_all lemma descendants_bounds_fst: assumes \<open>descendants k i branch xs\<close> \<open>(v, v') \<in> xs\<close> shows \<open>v < length branch\<close> using assms rev_nth_Some by (induct k i branch xs rule: descendants.induct) fast+ lemma descendants_bounds_snd: assumes \<open>descendants k i branch xs\<close> \<open>(v, v') \<in> xs\<close> \<open>branch !. v = Some (ps, a)\<close> shows \<open>v' < length ps\<close> using assms by (induct k i branch xs rule: descendants.induct) (auto simp: rev_nth_Some) lemma descendants_branch: \<open>descendants k i branch xs \<Longrightarrow> descendants k i (extra @ branch) xs\<close> proof (induct k i branch xs rule: descendants.induct) case (Initial branch v qs i v' k) then show ?case using rev_nth_append descendants.Initial by fast next case (Derived branch v qs a v' k p i xs w w' rs) then have \<open>(extra @ branch) !. v = Some (qs, a)\<close> \<open>(extra @ branch) !. w = Some (rs, a)\<close> using rev_nth_append by fast+ then show ?case using Derived(2, 4-5, 7) descendants.Derived by fast next case (Copied branch v qs a v' p k i xs w w' rs b) then have \<open>(extra @ branch) !. v = Some (qs, a)\<close> \<open>(extra @ branch) !. w = Some (rs, b)\<close> using rev_nth_append by fast+ moreover have \<open>Nom a at b in (extra @ branch)\<close> using Copied(8) by auto ultimately show ?case using Copied(2-4, 5-7) descendants.Copied by fast qed lemma descendants_block: assumes \<open>descendants k i ((ps, a) # branch) xs\<close> shows \<open>descendants k i ((ps' @ ps, a) # branch) xs\<close> using assms proof (induct k i \<open>(ps, a) # branch\<close> xs arbitrary: ps a branch rule: descendants.induct) case (Initial v qs i v' k) have \<open>((ps' @ ps, a) # branch) !. v = Some (qs, i) \<or> ((ps' @ ps, a) # branch) !. v = Some (ps' @ qs, i)\<close> using Initial(1) by auto moreover have \<open>qs !. v' = Some (\<^bold>\<diamond> Nom k)\<close> \<open>(ps' @ qs) !. v' = Some (\<^bold>\<diamond> Nom k)\<close> using Initial(2) rev_nth_append by simp_all ultimately show ?case using descendants.Initial by fast next case (Derived v qs a' v' k p i xs w w' rs) have \<open>((ps' @ ps, a) # branch) !. v = Some (qs, a') \<or> ((ps' @ ps, a) # branch) !. v = Some (ps' @ qs, a')\<close> using Derived(1) by auto moreover have \<open>qs !. v' = Some (\<^bold>\<not> (\<^bold>@ k p))\<close> \<open>(ps' @ qs) !. v' = Some (\<^bold>\<not> (\<^bold>@ k p))\<close> using Derived(2) rev_nth_append by simp_all moreover have \<open>((ps' @ ps, a) # branch) !. w = Some (rs, a') \<or> ((ps' @ ps, a) # branch) !. w = Some (ps' @ rs, a')\<close> using \<open>((ps, a) # branch) !. w = Some (rs, a')\<close> by auto moreover have \<open>rs !. w' = Some (\<^bold>\<diamond> Nom k)\<close> \<open>(ps' @ rs) !. w' = Some (\<^bold>\<diamond> Nom k)\<close> using Derived(7) rev_nth_append by simp_all ultimately show ?case using Derived(4-5) descendants.Derived by fast next case (Copied v qs a' v' p k i xs w w' rs b) have \<open>((ps' @ ps, a) # branch) !. v = Some (qs, a') \<or> ((ps' @ ps, a) # branch) !. v = Some (ps' @ qs, a')\<close> using Copied(1) by auto moreover have \<open>qs !. v' = Some p\<close> \<open>(ps' @ qs) !. v' = Some p\<close> using Copied(2) rev_nth_append by simp_all moreover have \<open>((ps' @ ps, a) # branch) !. w = Some (rs, b) \<or> ((ps' @ ps, a) # branch) !. w = Some (ps' @ rs, b)\<close> using Copied(6) by auto moreover have \<open>rs !. w' = Some p\<close> \<open>(ps' @ rs) !. w' = Some p\<close> using Copied(7) rev_nth_append by simp_all moreover have \<open>((ps' @ ps, a) # branch) !. w = Some (rs, b) \<or> ((ps' @ ps, a) # branch) !. w = Some (ps' @ rs, b)\<close> using Copied(6) by auto moreover have \<open>rs !. w' = Some p\<close> \<open>(ps' @ rs) !. w' = Some p\<close> using Copied(7) rev_nth_append by simp_all moreover have \<open>Nom a' at b in (ps' @ ps, a) # branch\<close> using Copied(8) by fastforce ultimately show ?case using Copied(4-5) descendants.Copied[where branch=\<open>(ps' @ ps, a) # branch\<close>] by blast qed lemma descendants_no_head: assumes \<open>descendants k i ((ps, a) # branch) xs\<close> shows \<open>descendants k i ((p # ps, a) # branch) xs\<close> using assms descendants_block[where ps'=\<open>[_]\<close>] by simp lemma descendants_types: assumes \<open>descendants k i branch xs\<close> \<open>(v, v') \<in> xs\<close> \<open>branch !. v = Some (ps, a)\<close> \<open>ps !. v' = Some p\<close> shows \<open>p = (\<^bold>\<diamond> Nom k) \<or> (\<exists>q. p = (\<^bold>\<not> (\<^bold>@ k q)))\<close> using assms by (induct k i branch xs arbitrary: v v' ps a) fastforce+ lemma descendants_oob_head': assumes \<open>descendants k i ((ps, a) # branch) xs\<close> shows \<open>(length branch, m + length ps) \<notin> xs\<close> using assms descendants_bounds_snd by fastforce lemma descendants_oob_head: assumes \<open>descendants k i ((ps, a) # branch) xs\<close> shows \<open>(length branch, length ps) \<notin> xs\<close> using assms descendants_oob_head'[where m=0] by fastforce subsection \<open>Induction\<close> text \<open> We induct over an arbitrary set of indices. That way, we can determine in each case whether the extension gets replaced or not by manipulating the set before applying the induction hypothesis. \<close> lemma STA_bridge': fixes a :: 'b assumes inf: \<open>infinite (UNIV :: 'b set)\<close> and fin: \<open>finite A\<close> and \<open>j \<in> A\<close> \<open>A, n \<turnstile> (ps, a) # branch\<close> \<open>descendants k i ((ps, a) # branch) xs\<close> \<open>Nom k at j in branch\<close> shows \<open>A \<turnstile> mapi_branch (bridge k j xs) ((ps, a) # branch)\<close> using assms(4-) proof (induct n \<open>(ps, a) # branch\<close> arbitrary: ps a branch xs rule: STA.induct) case (Close p i' n) let ?f = \<open>bridge k j xs\<close> let ?branch = \<open>mapi_branch ?f ((ps, a) # branch)\<close> obtain qs where qs: \<open>(qs, i') \<in>. (ps, a) # branch\<close> \<open>p on (qs, i')\<close> using Close(1) by blast obtain rs where rs: \<open>(rs, i') \<in>. (ps, a) # branch\<close> \<open>(\<^bold>\<not> p) on (rs, i')\<close> using Close(2) by blast obtain v where v: \<open>(mapi (?f v) qs, i') \<in>. ?branch\<close> using qs mapi_branch_mem by fast obtain w where w: \<open>(mapi (?f w) rs, i') \<in>. ?branch\<close> using rs mapi_branch_mem by fast have k: \<open>Nom k at j in ?branch\<close> using Close(4) nom_at_in_bridge unfolding mapi_branch_def by fastforce show ?case proof (cases \<open>\<exists>a. p = Nom a\<close>) case True then have \<open>p on (mapi (?f v) qs, i')\<close> using qs bridge_on_Nom by fast moreover have \<open>(\<^bold>\<not> p) on (mapi (?f w) rs, i')\<close> using rs(2) True by (induct rs) auto ultimately show ?thesis using v w STA.Close by fast next case False then obtain v' where \<open>qs !. v' = Some p\<close> using qs rev_nth_on by fast then have qs': \<open>(?f v v' p) on (mapi (?f v) qs, i')\<close> using rev_nth_mapi_block by fast then obtain w' where \<open>rs !. w' = Some (\<^bold>\<not> p)\<close> using rs rev_nth_on by fast then have rs': \<open>(?f w w' (\<^bold>\<not> p)) on (mapi (?f w) rs, i')\<close> using rev_nth_mapi_block by fast obtain q q' where q: \<open>?f v v' p = q\<close> and q': \<open>?f w w' (\<^bold>\<not> p) = q'\<close> by simp_all then consider (dia) \<open>q = (\<^bold>\<diamond> Nom j)\<close> \<open>q' = (\<^bold>\<not> (\<^bold>\<diamond> Nom k))\<close> | (satn)\<open>\<exists>r. q = (\<^bold>\<not> (\<^bold>@ j r)) \<and> q' = (\<^bold>\<not> \<^bold>\<not> (\<^bold>@ k r))\<close> | (sat) \<open>\<exists>r. q = (\<^bold>@ k r) \<and> q' = (\<^bold>\<not> (\<^bold>@ j r))\<close> | (old) \<open>q = p\<close> \<open>q' = (\<^bold>\<not> p)\<close> using bridge_compl_cases by fast then show ?thesis proof cases case dia then have *: \<open>(\<^bold>\<diamond> Nom j) on (mapi (?f v) qs, i')\<close> \<open>(\<^bold>\<not> (\<^bold>\<diamond> Nom k)) on (mapi (?f w) rs, i')\<close> using q qs' q' rs' by simp_all have \<open>i' \<in> branch_nominals ?branch\<close> unfolding branch_nominals_def using v by fastforce then have ?thesis if \<open>A \<turnstile> ([], i') # ?branch\<close> using that GoTo by fast moreover have \<open>(mapi (?f v) qs, i') \<in>. ([], i') # ?branch\<close> using v by simp moreover have \<open>(mapi (?f w) rs, i') \<in>. ([], i') # ?branch\<close> using w by simp ultimately have ?thesis if \<open>A \<turnstile> ([\<^bold>\<not> (\<^bold>@ j (Nom k))], i') # ?branch\<close> using that * by (meson DiaN') moreover have \<open>j \<in> branch_nominals (([\<^bold>\<not> (\<^bold>@ j (Nom k))], i') # ?branch)\<close> unfolding branch_nominals_def by simp ultimately have ?thesis if \<open>A \<turnstile> ([], j) # ([\<^bold>\<not> (\<^bold>@ j (Nom k))], i') # ?branch\<close> using that GoTo by fast moreover have \<open>(\<^bold>\<not> (\<^bold>@ j (Nom k))) at i' in ([], j) # ([\<^bold>\<not> (\<^bold>@ j (Nom k))], i') # ?branch\<close> by fastforce ultimately have ?thesis if \<open>A \<turnstile> ([\<^bold>\<not> Nom k], j) # ([\<^bold>\<not> (\<^bold>@ j (Nom k))], i') # ?branch\<close> using that SatN' by fast moreover have \<open>Nom k at j in ([\<^bold>\<not> Nom k], j) # ([\<^bold>\<not> (\<^bold>@ j (Nom k))], i') # ?branch\<close> using k by fastforce moreover have \<open>(\<^bold>\<not> Nom k) at j in ([\<^bold>\<not> Nom k], j) # ([\<^bold>\<not> (\<^bold>@ j (Nom k))], i') # ?branch\<close> by fastforce ultimately show ?thesis using STA.Close by fast next case satn then obtain r where *: \<open>(\<^bold>\<not> (\<^bold>@ j r)) on (mapi (?f v) qs, i')\<close> \<open>(\<^bold>\<not> \<^bold>\<not> (\<^bold>@ k r)) on (mapi (?f w) rs, i')\<close> using q qs' q' rs' by auto have \<open>i' \<in> branch_nominals ?branch\<close> unfolding branch_nominals_def using v by fastforce then have ?thesis if \<open>A \<turnstile> ([], i') # ?branch\<close> using that GoTo by fast moreover have \<open>(mapi (?f w) rs, i') \<in>. ([], i') # ?branch\<close> using w by simp ultimately have ?thesis if \<open>A \<turnstile> ([\<^bold>@ k r], i') # ?branch\<close> using that *(2) by (meson Neg') moreover have \<open>j \<in> branch_nominals (([\<^bold>@ k r], i') # ?branch)\<close> unfolding branch_nominals_def using k by fastforce ultimately have ?thesis if \<open>A \<turnstile> ([], j) # ([\<^bold>@ k r], i') # ?branch\<close> using that GoTo by fast moreover have \<open>(\<^bold>\<not> (\<^bold>@ j r)) at i' in ([], j) # ([\<^bold>@ k r], i') # ?branch\<close> using *(1) v by auto ultimately have ?thesis if \<open>A \<turnstile> ([\<^bold>\<not> r], j) # ([\<^bold>@ k r], i') # ?branch\<close> using that SatN' by fast moreover have \<open>k \<in> branch_nominals (([\<^bold>\<not> r], j) # ([\<^bold>@ k r], i') # ?branch)\<close> unfolding branch_nominals_def using k by fastforce ultimately have ?thesis if \<open>A \<turnstile> ([], k) # ([\<^bold>\<not> r], j) # ([\<^bold>@ k r], i') # ?branch\<close> using that GoTo by fast moreover have \<open>(\<^bold>@ k r) at i' in ([], k) # ([\<^bold>\<not> r], j) # ([\<^bold>@ k r], i') # ?branch\<close> by fastforce ultimately have ?thesis if \<open>A \<turnstile> ([r], k) # ([\<^bold>\<not> r], j) # ([\<^bold>@ k r], i') # ?branch\<close> using that SatP' by fast moreover have \<open>Nom k at j in ([r], k) # ([\<^bold>\<not> r], j) # ([\<^bold>@ k r], i') # ?branch\<close> \<open>(\<^bold>\<not> r) at j in ([r], k) # ([\<^bold>\<not> r], j) # ([\<^bold>@ k r], i') # ?branch\<close> using k by fastforce+ ultimately have ?thesis if \<open>A \<turnstile> ([\<^bold>\<not> r, r], k) # ([\<^bold>\<not> r], j) # ([\<^bold>@ k r], i') # ?branch\<close> using that by (meson Nom' fm.distinct(21) fm.simps(18)) moreover have \<open>r at k in ([\<^bold>\<not> r, r], k) # ([\<^bold>\<not> r], j) # ([\<^bold>@ k r], i') # ?branch\<close> \<open>(\<^bold>\<not> r) at k in ([\<^bold>\<not> r, r], k) # ([\<^bold>\<not> r], j) # ([\<^bold>@ k r], i') # ?branch\<close> by fastforce+ ultimately show ?thesis using STA.Close by fast next case sat then obtain r where *: \<open>(\<^bold>@ k r) on (mapi (?f v) qs, i')\<close> \<open>(\<^bold>\<not> (\<^bold>@ j r)) on (mapi (?f w) rs, i')\<close> using q qs' q' rs' by auto have \<open>j \<in> branch_nominals ?branch\<close> unfolding branch_nominals_def using k by fastforce then have ?thesis if \<open>A \<turnstile> ([], j) # ?branch\<close> using that GoTo by fast moreover have \<open>(\<^bold>\<not> (\<^bold>@ j r)) at i' in ([], j) # ?branch\<close> using *(2) w by auto ultimately have ?thesis if \<open>A \<turnstile> ([\<^bold>\<not> r], j) # ?branch\<close> using that by (meson SatN') moreover have \<open>k \<in> branch_nominals (([\<^bold>\<not> r], j) # ?branch)\<close> unfolding branch_nominals_def using k by fastforce ultimately have ?thesis if \<open>A \<turnstile> ([], k) # ([\<^bold>\<not> r], j) # ?branch\<close> using that GoTo by fast moreover have \<open>(\<^bold>@ k r) at i' in ([], k) # ([\<^bold>\<not> r], j) # ?branch\<close> using *(1) v by auto ultimately have ?thesis if \<open>A \<turnstile> ([r], k) # ([\<^bold>\<not> r], j) # ?branch\<close> using that SatP' by fast moreover have \<open>Nom k at j in ([r], k) # ([\<^bold>\<not> r], j) # ?branch\<close> \<open>(\<^bold>\<not> r) at j in ([r], k) # ([\<^bold>\<not> r], j) # ?branch\<close> using k by fastforce+ ultimately have ?thesis if \<open>A \<turnstile> ([\<^bold>\<not> r, r], k) # ([\<^bold>\<not> r], j) # ?branch\<close> using that by (meson Nom' fm.distinct(21) fm.simps(18)) moreover have \<open>r at k in ([\<^bold>\<not> r, r], k) # ([\<^bold>\<not> r], j) # ?branch\<close> \<open>(\<^bold>\<not> r) at k in ([\<^bold>\<not> r, r], k) # ([\<^bold>\<not> r], j) # ?branch\<close> by fastforce+ ultimately show ?thesis using STA.Close by fast next case old then have \<open>p on (mapi (?f v) qs, i')\<close> \<open>(\<^bold>\<not> p) on (mapi (?f w) rs, i')\<close> using q qs' q' rs' by simp_all then show ?thesis using v w STA.Close[where p=p and i=i'] by fast qed qed next case (Neg p a ps branch n) let ?f = \<open>bridge k j xs\<close> have p: \<open>?f l l' (\<^bold>\<not> \<^bold>\<not> p) = (\<^bold>\<not> \<^bold>\<not> p)\<close> for l l' by simp have \<open>descendants k i ((p # ps, a) # branch) xs\<close> using Neg(5) descendants_no_head by fast then have \<open>A \<turnstile> mapi_branch ?f ((p # ps, a) # branch)\<close> using Neg(4-) by blast moreover have \<open>(length branch, length ps) \<notin> xs\<close> using Neg(5) descendants_oob_head by fast ultimately have \<open>A \<turnstile> (p # mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> unfolding mapi_branch_def by simp moreover have \<open>\<exists>l l'. ?f l l' (\<^bold>\<not> \<^bold>\<not> p) at a in mapi_branch ?f ((ps, a) # branch)\<close> using Neg(1) at_in_mapi_branch by fast then have \<open>(\<^bold>\<not> \<^bold>\<not> p) at a in (mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> unfolding mapi_branch_def using p by simp ultimately have \<open>A \<turnstile> (mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> using Neg' by fast then show ?case unfolding mapi_branch_def by auto next case (DisP p q a ps branch n) let ?f = \<open>bridge k j xs\<close> have p: \<open>?f l l' (p \<^bold>\<or> q) = (p \<^bold>\<or> q)\<close> for l l' by simp have \<open>descendants k i ((p # ps, a) # branch) xs\<close> \<open>descendants k i ((q # ps, a) # branch) xs\<close> using DisP(8) descendants_no_head by fast+ then have \<open>A \<turnstile> mapi_branch ?f ((p # ps, a) # branch)\<close> \<open>A \<turnstile> mapi_branch ?f ((q # ps, a) # branch)\<close> using DisP(5-) by blast+ moreover have \<open>(length branch, length ps) \<notin> xs\<close> using DisP(8) descendants_oob_head by fast ultimately have \<open>A \<turnstile> (p # mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> \<open>A \<turnstile> (q # mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> unfolding mapi_branch_def by simp_all moreover have \<open>\<exists>l l'. ?f l l' (p \<^bold>\<or> q) at a in mapi_branch ?f ((ps, a) # branch)\<close> using DisP(1) at_in_mapi_branch by fast then have \<open>(p \<^bold>\<or> q) at a in (mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> unfolding mapi_branch_def using p by simp ultimately have \<open>A \<turnstile> (mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> using DisP'' by fast then show ?case unfolding mapi_branch_def by auto next case (DisN p q a ps branch n) let ?f = \<open>bridge k j xs\<close> have p: \<open>?f l l' (\<^bold>\<not> (p \<^bold>\<or> q)) = (\<^bold>\<not> (p \<^bold>\<or> q))\<close> for l l' by simp have \<open>descendants k i (((\<^bold>\<not> p) # ps, a) # branch) xs\<close> using DisN(5) descendants_no_head by fast then have \<open>descendants k i (((\<^bold>\<not> q) # (\<^bold>\<not> p) # ps, a) # branch) xs\<close> using descendants_no_head by fast then have \<open>A \<turnstile> mapi_branch ?f (((\<^bold>\<not> q) # (\<^bold>\<not> p) # ps, a) # branch)\<close> using DisN(4-) by blast moreover have \<open>(length branch, length ps) \<notin> xs\<close> using DisN(5) descendants_oob_head by fast moreover have \<open>(length branch, 1 + length ps) \<notin> xs\<close> using DisN(5) descendants_oob_head' by fast ultimately have \<open>A \<turnstile> ((\<^bold>\<not> q) # (\<^bold>\<not> p) # mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> unfolding mapi_branch_def by simp moreover have \<open>\<exists>l l'. ?f l l' (\<^bold>\<not> (p \<^bold>\<or> q)) at a in mapi_branch ?f ((ps, a) # branch)\<close> using DisN(1) at_in_mapi_branch by fast then have \<open>(\<^bold>\<not> (p \<^bold>\<or> q)) at a in (mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> unfolding mapi_branch_def using p by simp ultimately have \<open>A \<turnstile> (mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> using DisN' by fast then show ?case unfolding mapi_branch_def by auto next case (DiaP p a ps branch i' n) let ?f = \<open>bridge k j xs\<close> have p: \<open>?f l l' (\<^bold>\<diamond> p) = (\<^bold>\<diamond> p)\<close> for l l' using DiaP(3) bridge_proper_dia by fast have \<open>branch_nominals (mapi_branch ?f ((ps, a) # branch)) = branch_nominals ((ps, a) # branch)\<close> using DiaP(8-) nominals_mapi_branch_bridge[where j=j and k=k and branch=\<open>(ps, a) # branch\<close>] by auto then have i': \<open>i' \<notin> A \<union> branch_nominals ((mapi (?f (length branch)) ps, a) # mapi_branch ?f branch)\<close> unfolding mapi_branch_def using DiaP(2) by simp have 1: \<open>?f (length branch) (1 + length ps) (\<^bold>@ i' p) = (\<^bold>@ i' p)\<close> by simp have \<open>i' \<noteq> k\<close> using DiaP(2, 8) unfolding branch_nominals_def by fastforce then have 2: \<open>?f (length branch) (length ps) (\<^bold>\<diamond> Nom i') = (\<^bold>\<diamond> Nom i')\<close> by simp have \<open>i' \<noteq> j\<close> using DiaP(2, 8) unfolding branch_nominals_def by fastforce moreover have \<open>descendants k i (((\<^bold>@ i' p) # (\<^bold>\<diamond> Nom i') # ps, a) # branch) xs\<close> using DiaP(7) descendants_block[where ps'=\<open>[_, _]\<close>] by fastforce ultimately have \<open>A \<turnstile> mapi_branch ?f (((\<^bold>@ i' p) # (\<^bold>\<diamond> Nom i') # ps, a) # branch)\<close> using DiaP(4-) by blast then have \<open>A \<turnstile> ((\<^bold>@ i' p) # (\<^bold>\<diamond> Nom i') # mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> unfolding mapi_branch_def using 1 by (simp add: 2) moreover have \<open>\<exists>l l'. ?f l l' (\<^bold>\<diamond> p) at a in mapi_branch ?f ((ps, a) # branch)\<close> using DiaP(1) at_in_mapi_branch by fast then have \<open>(\<^bold>\<diamond> p) at a in (mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> unfolding mapi_branch_def using p by simp ultimately have \<open>A \<turnstile> (mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> using i' DiaP(3) fin DiaP'' by fast then show ?case unfolding mapi_branch_def by simp next case (DiaN p a ps branch i' n) have p: \<open>bridge k j xs l l' (\<^bold>\<not> (\<^bold>\<diamond> p)) = (\<^bold>\<not> (\<^bold>\<diamond> p))\<close> for xs l l' by simp obtain rs where rs: \<open>(rs, a) \<in>. (ps, a) # branch\<close> \<open>(\<^bold>\<diamond> Nom i') on (rs, a)\<close> using DiaN(2) by fast obtain v where v: \<open>((ps, a) # branch) !. v = Some (rs, a)\<close> using rs(1) rev_nth_mem by fast obtain v' where v': \<open>rs !. v' = Some (\<^bold>\<diamond> Nom i')\<close> using rs(2) rev_nth_on by fast show ?case proof (cases \<open>(v, v') \<in> xs\<close>) case True then have \<open>i' = k\<close> using DiaN(6) v v' descendants_types by fast let ?xs = \<open>{(length branch, length ps)} \<union> xs\<close> let ?f = \<open>bridge k j ?xs\<close> let ?branch = \<open>((\<^bold>\<not> (\<^bold>@ i' p)) # ps, a) # branch\<close> obtain rs' where \<open>(((\<^bold>\<not> (\<^bold>@ k p)) # ps, a) # branch) !. v = Some (rs', a)\<close> \<open>rs' !. v' = Some (\<^bold>\<diamond> Nom i')\<close> using v v' index_Cons by fast moreover have \<open>descendants k i (((\<^bold>\<not> (\<^bold>@ k p)) # ps, a) # branch) xs\<close> using DiaN(6) descendants_block[where ps'=\<open>[_]\<close>] by fastforce moreover have \<open>?branch !. length branch = Some ((\<^bold>\<not> (\<^bold>@ k p)) # ps, a)\<close> using \<open>i' = k\<close> by simp moreover have \<open>((\<^bold>\<not> (\<^bold>@ k p)) # ps) !. length ps = Some (\<^bold>\<not> (\<^bold>@ k p))\<close> by simp ultimately have \<open>descendants k i (((\<^bold>\<not> (\<^bold>@ k p)) # ps, a) # branch) ?xs\<close> using True \<open>i' = k\<close> Derived[where branch=\<open>_ # branch\<close>] by simp then have \<open>A \<turnstile> mapi_branch ?f (((\<^bold>\<not> (\<^bold>@ k p)) # ps, a) # branch)\<close> using \<open>i' = k\<close> DiaN(5-) by blast then have \<open>A \<turnstile> ((\<^bold>\<not> (\<^bold>@ j p)) # mapi (?f (length branch)) ps, a) # mapi_branch (bridge k j ?xs) branch\<close> unfolding mapi_branch_def using \<open>i' = k\<close> by simp moreover have \<open>\<exists>l l'. ?f l l' (\<^bold>\<not> (\<^bold>\<diamond> p)) at a in mapi_branch ?f ((ps, a) # branch)\<close> using DiaN(1) at_in_mapi_branch by fast then have \<open>(\<^bold>\<not> (\<^bold>\<diamond> p)) at a in (mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> unfolding mapi_branch_def using p[where xs=\<open>?xs\<close>] by simp moreover have \<open>(mapi (?f v) rs, a) \<in>. mapi_branch ?f ((ps, a) # branch)\<close> using v rev_nth_mapi_branch by fast then have \<open>(mapi (?f v) rs, a) \<in> set ((mapi (?f (length branch)) ps, a) # mapi_branch ?f branch)\<close> unfolding mapi_branch_def by simp moreover have \<open>?f v v' (\<^bold>\<diamond> Nom i') on (mapi (?f v) rs, a)\<close> using v' rev_nth_mapi_block by fast then have \<open>(\<^bold>\<diamond> Nom j) on (mapi (?f v) rs, a)\<close> using True \<open>i' = k\<close> by simp ultimately have \<open>A \<turnstile> (mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> by (meson DiaN') then have \<open>A \<turnstile> (mapi (bridge k j xs (length branch)) ps, a) # mapi_branch (bridge k j xs) branch\<close> using mapi_branch_head_add_oob[where branch=branch and ps=ps] unfolding mapi_branch_def by simp then show ?thesis unfolding mapi_branch_def by simp next case False let ?f = \<open>bridge k j xs\<close> have \<open>descendants k i (((\<^bold>\<not> (\<^bold>@ i' p)) # ps, a) # branch) xs\<close> using DiaN(6) descendants_no_head by fast then have \<open>A \<turnstile> mapi_branch ?f (((\<^bold>\<not> (\<^bold>@ i' p)) # ps, a) # branch)\<close> using DiaN(5-) by blast moreover have \<open>(length branch, length ps) \<notin> xs\<close> using DiaN(6) descendants_oob_head by fast ultimately have \<open>A \<turnstile> ((\<^bold>\<not> (\<^bold>@ i' p)) # mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> unfolding mapi_branch_def by simp moreover have \<open>\<exists>l l'. ?f l l' (\<^bold>\<not> (\<^bold>\<diamond> p)) at a in mapi_branch ?f ((ps, a) # branch)\<close> using DiaN(1) at_in_mapi_branch by fast then have \<open>(\<^bold>\<not> (\<^bold>\<diamond> p)) at a in (mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> unfolding mapi_branch_def using p[where xs=\<open>xs\<close>] by simp moreover have \<open>(mapi (?f v) rs, a) \<in>. mapi_branch ?f ((ps, a) # branch)\<close> using v rev_nth_mapi_branch by fast then have \<open>(mapi (?f v) rs, a) \<in> set ((mapi (?f (length branch)) ps, a) # mapi_branch ?f branch)\<close> unfolding mapi_branch_def by simp moreover have \<open>?f v v' (\<^bold>\<diamond> Nom i') on (mapi (?f v) rs, a)\<close> using v' rev_nth_mapi_block by fast then have \<open>(\<^bold>\<diamond> Nom i') on (mapi (?f v) rs, a)\<close> using False by simp ultimately have \<open>A \<turnstile> (mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> by (meson DiaN') then show ?thesis unfolding mapi_branch_def by simp qed next case (SatP a p b ps branch n) let ?f = \<open>bridge k j xs\<close> have p: \<open>?f l l' (\<^bold>@ a p) = (\<^bold>@ a p)\<close> for l l' by simp have \<open>descendants k i ((p # ps, a) # branch) xs\<close> using SatP(5) descendants_no_head by fast then have \<open>A \<turnstile> mapi_branch ?f ((p # ps, a) # branch)\<close> using SatP(4-) by blast moreover have \<open>(length branch, length ps) \<notin> xs\<close> using SatP(5) descendants_oob_head by fast ultimately have \<open>A \<turnstile> (p # mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> unfolding mapi_branch_def by simp moreover have \<open>\<exists>l l'. ?f l l' (\<^bold>@ a p) at b in mapi_branch ?f ((ps, a) # branch)\<close> using SatP(1) at_in_mapi_branch by fast then have \<open>(\<^bold>@ a p) at b in (mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> unfolding mapi_branch_def using p by simp ultimately have \<open>A \<turnstile> (mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> using SatP' by fast then show ?case unfolding mapi_branch_def by simp next case (SatN a p b ps branch n) obtain qs where qs: \<open>(qs, b) \<in>. (ps, a) # branch\<close> \<open>(\<^bold>\<not> (\<^bold>@ a p)) on (qs, b)\<close> using SatN(1) by fast obtain v where v: \<open>((ps, a) # branch) !. v = Some (qs, b)\<close> using qs(1) rev_nth_mem by fast obtain v' where v': \<open>qs !. v' = Some (\<^bold>\<not> (\<^bold>@ a p))\<close> using qs(2) rev_nth_on by fast show ?case proof (cases \<open>(v, v') \<in> xs\<close>) case True then have \<open>a = k\<close> using SatN(5) v v' descendants_types by fast let ?f = \<open>bridge k j xs\<close> let ?branch = \<open>((\<^bold>\<not> p) # ps, a) # branch\<close> have p: \<open>?f v v' (\<^bold>\<not> (\<^bold>@ k p)) = (\<^bold>\<not> (\<^bold>@ j p))\<close> using True by simp obtain rs' where \<open>?branch !. v = Some (rs', b)\<close> \<open>rs' !. v' = Some (\<^bold>\<not> (\<^bold>@ k p))\<close> using v v' \<open>a = k\<close> index_Cons by fast have \<open>descendants k i ?branch xs\<close> using SatN(5) descendants_no_head by fast then have \<open>A \<turnstile> mapi_branch ?f ?branch\<close> using \<open>a = k\<close> SatN(4-) by blast moreover have \<open>(length branch, length ps) \<notin> xs\<close> using SatN(5) descendants_oob_head by fast ultimately have \<open>A \<turnstile> ((\<^bold>\<not> p) # mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> unfolding mapi_branch_def using \<open>a = k\<close> by simp moreover have \<open>set (((\<^bold>\<not> p) # mapi (?f (length branch)) ps, a) # mapi_branch ?f branch) \<subseteq> set (((\<^bold>\<not> p) # mapi (?f (length branch)) ps, a) # ([\<^bold>\<not> p], j) # mapi_branch ?f branch)\<close> by auto ultimately have *: \<open>A \<turnstile> ((\<^bold>\<not> p) # mapi (?f (length branch)) ps, a) # ([\<^bold>\<not> p], j) # mapi_branch ?f branch\<close> using inf fin STA_struct by fastforce have k: \<open>Nom k at j in mapi_branch ?f ((ps, a) # branch)\<close> using SatN(6) nom_at_in_bridge unfolding mapi_branch_def by fastforce have \<open>(mapi (?f v) qs, b) \<in>. mapi_branch ?f ((ps, a) # branch)\<close> using v rev_nth_mapi_branch by fast moreover have \<open>?f v v' (\<^bold>\<not> (\<^bold>@ k p)) on (mapi (?f v) qs, b)\<close> using v' \<open>a = k\<close> rev_nth_mapi_block by fast then have \<open>(\<^bold>\<not> (\<^bold>@ j p)) on (mapi (?f v) qs, b)\<close> using p by simp ultimately have satn: \<open>(\<^bold>\<not> (\<^bold>@ j p)) at b in mapi_branch ?f ((ps, a) # branch)\<close> by blast have \<open>j \<in> branch_nominals (mapi_branch ?f ((ps, a) # branch))\<close> unfolding branch_nominals_def using k by fastforce then have ?thesis if \<open>A \<turnstile> ([], j) # mapi_branch ?f ((ps, a) # branch)\<close> using that GoTo by fast moreover have \<open>(\<^bold>\<not> (\<^bold>@ j p)) at b in ([], j) # mapi_branch ?f ((ps, a) # branch)\<close> using satn by auto ultimately have ?thesis if \<open>A \<turnstile> ([\<^bold>\<not> p], j) # mapi_branch ?f ((ps, a) # branch)\<close> using that SatN' by fast then have ?thesis if \<open>A \<turnstile> ([\<^bold>\<not> p], j) # mapi_branch ?f ((ps, a) # branch)\<close> using that SatN' by fast then have ?thesis if \<open>A \<turnstile> ([\<^bold>\<not> p], j) # (mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> using that unfolding mapi_branch_def by simp moreover have \<open>set ((mapi (?f (length branch)) ps, a) # ([\<^bold>\<not> p], j) # mapi_branch ?f branch) \<subseteq> set (([\<^bold>\<not> p], j) # (mapi (?f (length branch)) ps, a) # mapi_branch ?f branch)\<close> by auto ultimately have ?thesis if \<open>A \<turnstile> (mapi (?f (length branch)) ps, a) # ([\<^bold>\<not> p], j) # mapi_branch ?f branch\<close> using that inf fin STA_struct by blast moreover have \<open>Nom k at j in (mapi (?f (length branch)) ps, a) # ([\<^bold>\<not> p], j) # mapi_branch ?f branch\<close> using k unfolding mapi_branch_def by auto moreover have \<open>(\<^bold>\<not> p) at j in (mapi (?f (length branch)) ps, a) # ([\<^bold>\<not> p], j) # mapi_branch ?f branch\<close> by fastforce ultimately have ?thesis if \<open>A \<turnstile> ((\<^bold>\<not> p) # mapi (?f (length branch)) ps, a) # ([\<^bold>\<not> p], j) # mapi_branch ?f branch\<close> using that \<open>a = k\<close> by (meson Nom' fm.distinct(21) fm.simps(18)) then show ?thesis using * by blast next case False let ?f = \<open>bridge k j xs\<close> have \<open>descendants k i (((\<^bold>\<not> p) # ps, a) # branch) xs\<close> using SatN(5) descendants_no_head by fast then have \<open>A \<turnstile> mapi_branch (bridge k j xs) (((\<^bold>\<not> p) # ps, a) # branch)\<close> using SatN(4-) by blast moreover have \<open>(length branch, length ps) \<notin> xs\<close> using SatN(5) descendants_oob_head by fast ultimately have \<open>A \<turnstile> ((\<^bold>\<not> p) # mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> unfolding mapi_branch_def by simp moreover have \<open>(mapi (?f v) qs, b) \<in>. mapi_branch ?f ((ps, a) # branch)\<close> using v rev_nth_mapi_branch by fast then have \<open>(mapi (?f v) qs, b) \<in> set ((mapi (?f (length branch)) ps, a) # mapi_branch ?f branch)\<close> unfolding mapi_branch_def by simp moreover have \<open>?f v v' (\<^bold>\<not> (\<^bold>@ a p)) on (mapi (?f v) qs, b)\<close> using v' rev_nth_mapi_block by fast then have \<open>(\<^bold>\<not> (\<^bold>@ a p)) on (mapi (?f v) qs, b)\<close> using False by simp ultimately have \<open>A \<turnstile> (mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> by (meson SatN') then show ?thesis unfolding mapi_branch_def by simp qed next case (GoTo i' n ps a branch) let ?f = \<open>bridge k j xs\<close> have \<open>descendants k i (([], i') # (ps, a) # branch) xs\<close> using GoTo(4) descendants_branch[where extra=\<open>[_]\<close>] by simp then have \<open>A \<turnstile> mapi_branch ?f (([], i') # (ps, a) # branch)\<close> using GoTo(3, 5-) by auto then have \<open>A \<turnstile> ([], i') # mapi_branch ?f ((ps, a) # branch)\<close> unfolding mapi_branch_def by simp moreover have \<open>branch_nominals (mapi_branch ?f ((ps, a) # branch)) = branch_nominals ((ps, a) # branch)\<close> using GoTo(5-) nominals_mapi_branch_bridge[where j=j and k=k and branch=\<open>(ps, a) # branch\<close>] by auto then have \<open>i' \<in> branch_nominals (mapi_branch (bridge k j xs) ((ps, a) # branch))\<close> using GoTo(1) by blast ultimately show ?case using STA.GoTo by fast next case (Nom p b ps a branch n) show ?case proof (cases \<open>\<exists>j. p = Nom j\<close>) case True let ?f = \<open>bridge k j xs\<close> have \<open>descendants k i ((p # ps, a) # branch) xs\<close> using Nom(7) descendants_block[where ps'=\<open>[p]\<close>] by simp then have \<open>A \<turnstile> mapi_branch ?f ((p # ps, a) # branch)\<close> using Nom(6-) by blast moreover have \<open>?f (length branch) (length ps) p = p\<close> using True by auto ultimately have \<open>A \<turnstile> (p # mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> unfolding mapi_branch_def by simp moreover have \<open>p at b in mapi_branch ?f ((ps, a) # branch)\<close> using Nom(1) True nom_at_in_bridge by fast then have \<open>p at b in (mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> unfolding mapi_branch_def by simp moreover have \<open>Nom a at b in mapi_branch ?f ((ps, a) # branch)\<close> using Nom(2) True nom_at_in_bridge by fast then have \<open>Nom a at b in (mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> unfolding mapi_branch_def by simp ultimately have \<open>A \<turnstile> (mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> by (meson Nom' Nom.hyps(3)) then show ?thesis unfolding mapi_branch_def by simp next case False obtain qs where qs: \<open>(qs, b) \<in>. (ps, a) # branch\<close> \<open>p on (qs, b)\<close> using Nom(1) by blast obtain v where v: \<open>((ps, a) # branch) !. v = Some (qs, b)\<close> using qs(1) rev_nth_mem by fast obtain v' where v': \<open>qs !. v' = Some p\<close> using qs(2) False rev_nth_on by fast show ?thesis proof (cases \<open>(v, v') \<in> xs\<close>) case True let ?xs = \<open>{(length branch, length ps)} \<union> xs\<close> let ?f = \<open>bridge k j ?xs\<close> let ?p = \<open>bridge' k j p\<close> have p: \<open>?f v v' p = ?p\<close> using True by simp consider (dia) \<open>p = (\<^bold>\<diamond> Nom k)\<close> | (satn) q where \<open>p = (\<^bold>\<not> (\<^bold>@ k q))\<close> | (old) \<open>?p = p\<close> by (meson Nom.prems(1) True descendants_types v v') then have A: \<open>\<forall>i. ?p = Nom i \<or> ?p = (\<^bold>\<diamond> Nom i) \<longrightarrow> i \<in> A\<close> using Nom(3) \<open>j \<in> A\<close> by cases simp_all obtain qs' where \<open>((p # ps, a) # branch) !. v = Some (qs', b)\<close> \<open>qs' !. v' = Some p\<close> using v v' index_Cons by fast moreover have \<open>Nom a at b in (p # ps, a) # branch\<close> using Nom(2) by fastforce moreover have \<open>descendants k i ((p # ps, a) # branch) xs\<close> using Nom(7) descendants_block[where ps'=\<open>[p]\<close>] by simp moreover have \<open>((p # ps, a) # branch) !. length branch = Some (p # ps, a)\<close> \<open>(p # ps) !. length ps = Some p\<close> by simp_all ultimately have \<open>descendants k i ((p # ps, a) # branch) ?xs\<close> using True Copied by fast then have \<open>A \<turnstile> mapi_branch ?f ((p # ps, a) # branch)\<close> using Nom(6-) by blast then have \<open>A \<turnstile> (?p # mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> unfolding mapi_branch_def by simp moreover have \<open>(mapi (?f v) qs, b) \<in>. mapi_branch ?f ((ps, a) # branch)\<close> using v rev_nth_mapi_branch by fast then have \<open>(mapi (?f v) qs, b) \<in>. (mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> unfolding mapi_branch_def by simp moreover have \<open>?f v v' p on (mapi (?f v) qs, b)\<close> using v v' rev_nth_mapi_block by fast then have \<open>?p on (mapi (?f v) qs, b)\<close> using p by simp moreover have \<open>Nom a at b in mapi_branch ?f ((ps, a) # branch)\<close> using Nom(2) nom_at_in_bridge by fast then have \<open>Nom a at b in (mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> unfolding mapi_branch_def by simp ultimately have \<open>A \<turnstile> (mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> using A by (meson Nom' Nom(3)) then have \<open>A \<turnstile> (mapi (bridge k j xs (length branch)) ps, a) # mapi_branch (bridge k j xs) branch\<close> using mapi_branch_head_add_oob[where branch=branch and ps=ps] unfolding mapi_branch_def by simp then show ?thesis unfolding mapi_branch_def by simp next case False let ?f = \<open>bridge k j xs\<close> have \<open>descendants k i ((p # ps, a) # branch) xs\<close> using Nom(7) descendants_no_head by fast then have \<open>A \<turnstile> mapi_branch ?f ((p # ps, a) # branch)\<close> using Nom(6-) by blast moreover have \<open>(length branch, length ps) \<notin> xs\<close> using Nom(7) descendants_oob_head by fast ultimately have \<open>A \<turnstile> (p # mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> unfolding mapi_branch_def by simp moreover have \<open>(mapi (?f v) qs, b) \<in>. mapi_branch ?f ((ps, a) # branch)\<close> using v rev_nth_mapi_branch by fast then have \<open>(mapi (?f v) qs, b) \<in>. (mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> unfolding mapi_branch_def by simp moreover have \<open>?f v v' p on (mapi (?f v) qs, b)\<close> using v v' rev_nth_mapi_block by fast then have \<open>p on (mapi (?f v) qs, b)\<close> using False by simp moreover have \<open>Nom a at b in mapi_branch ?f ((ps, a) # branch)\<close> using Nom(2) nom_at_in_bridge by fast then have \<open>Nom a at b in (mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> unfolding mapi_branch_def by simp ultimately have \<open>A \<turnstile> (mapi (?f (length branch)) ps, a) # mapi_branch ?f branch\<close> by (meson Nom' Nom(3)) then show ?thesis unfolding mapi_branch_def by simp qed qed qed lemma STA_bridge: fixes i :: 'b assumes inf: \<open>infinite (UNIV :: 'b set)\<close> and \<open>A \<turnstile> branch\<close> \<open>descendants k i branch xs\<close> \<open>Nom k at j in branch\<close> \<open>finite A\<close> \<open>j \<in> A\<close> shows \<open>A \<turnstile> mapi_branch (bridge k j xs) branch\<close> proof - have \<open>A \<turnstile> ([], j) # branch\<close> using assms(2, 5-6) inf STA_struct[where branch'=\<open>([], j) # branch\<close>] by auto moreover have \<open>descendants k i (([], j) # branch) xs\<close> using assms(3) descendants_branch[where extra=\<open>[_]\<close>] by fastforce ultimately have \<open>A \<turnstile> mapi_branch (bridge k j xs) (([], j) # branch)\<close> using STA_bridge' inf assms(3-) by fast then have *: \<open>A \<turnstile> ([], j) # mapi_branch (bridge k j xs) branch\<close> unfolding mapi_branch_def by simp have \<open>branch_nominals (mapi_branch (bridge k j xs) branch) = branch_nominals branch\<close> using nominals_mapi_branch_bridge assms(4-) by fast moreover have \<open>j \<in> branch_nominals branch\<close> using assms(4) unfolding branch_nominals_def by fastforce ultimately have \<open>j \<in> branch_nominals (mapi_branch (bridge k j xs) branch)\<close> by simp then show ?thesis using * GoTo by fast qed subsection \<open>Derivation\<close> theorem Bridge: fixes i :: 'b assumes inf: \<open>infinite (UNIV :: 'b set)\<close> and fin: \<open>finite A\<close> and \<open>j \<in> A\<close> \<open>Nom k at j in (ps, i) # branch\<close> \<open>(\<^bold>\<diamond> Nom j) at i in (ps, i) # branch\<close> \<open>A \<turnstile> ((\<^bold>\<diamond> Nom k) # ps, i) # branch\<close> shows \<open>A \<turnstile> (ps, i) # branch\<close> proof - let ?xs = \<open>{(length branch, length ps)}\<close> have \<open>descendants k i (((\<^bold>\<diamond> Nom k) # ps, i) # branch) ?xs\<close> using Initial by force moreover have \<open>Nom k at j in ((\<^bold>\<diamond> Nom k) # ps, i) # branch\<close> using assms(4) by fastforce ultimately have \<open>A \<turnstile> mapi_branch (bridge k j ?xs) (((\<^bold>\<diamond> Nom k) # ps, i) # branch)\<close> using STA_bridge inf fin assms(3, 6) by fast then have \<open>A \<turnstile> ((\<^bold>\<diamond> Nom j) # mapi (bridge k j ?xs (length branch)) ps, i) # mapi_branch (bridge k j ?xs) branch\<close> unfolding mapi_branch_def by simp moreover have \<open>mapi_branch (bridge k j {(length branch, length ps)}) branch = mapi_branch (bridge k j {}) branch\<close> using mapi_branch_add_oob[where xs=\<open>{}\<close>] by fastforce moreover have \<open>mapi (bridge k j ?xs (length branch)) ps = mapi (bridge k j {} (length branch)) ps\<close> using mapi_block_add_oob[where xs=\<open>{}\<close> and ps=ps] by simp ultimately have \<open>A \<turnstile> ((\<^bold>\<diamond> Nom j) # ps, i) # branch\<close> using mapi_block_id[where ps=ps] mapi_branch_id[where branch=branch] by simp then show ?thesis using Dup assms(5) by (metis new_def) qed section \<open>Completeness\<close> subsection \<open>Hintikka\<close> abbreviation at_in_set :: \<open>('a, 'b) fm \<Rightarrow> 'b \<Rightarrow> ('a, 'b) block set \<Rightarrow> bool\<close> where \<open>at_in_set p a S \<equiv> \<exists>ps. (ps, a) \<in> S \<and> p on (ps, a)\<close> notation at_in_set (\<open>_ at _ in'' _\<close> [51, 51, 51] 50) text \<open> A set of blocks is Hintikka if it satisfies the following requirements. Intuitively, if it corresponds to an exhausted open branch with respect to the fixed set of allowed nominals \<open>A\<close>. For example, we only require symmetry, "if \<open>j\<close> occurs at \<open>i\<close> then \<open>i\<close> occurs at \<open>j\<close>" if \<open>i \<in> A\<close>. \<close> locale Hintikka = fixes A :: \<open>'b set\<close> and H :: \<open>('a, 'b) block set\<close> assumes ProP: \<open>Nom j at i in' H \<Longrightarrow> Pro x at j in' H \<Longrightarrow> \<not> (\<^bold>\<not> Pro x) at i in' H\<close> and NomP: \<open>Nom a at i in' H \<Longrightarrow> \<not> (\<^bold>\<not> Nom a) at i in' H\<close> and NegN: \<open>(\<^bold>\<not> \<^bold>\<not> p) at i in' H \<Longrightarrow> p at i in' H\<close> and DisP: \<open>(p \<^bold>\<or> q) at i in' H \<Longrightarrow> p at i in' H \<or> q at i in' H\<close> and DisN: \<open>(\<^bold>\<not> (p \<^bold>\<or> q)) at i in' H \<Longrightarrow> (\<^bold>\<not> p) at i in' H \<and> (\<^bold>\<not> q) at i in' H\<close> and DiaP: \<open>\<nexists>a. p = Nom a \<Longrightarrow> (\<^bold>\<diamond> p) at i in' H \<Longrightarrow> \<exists>j. (\<^bold>\<diamond> Nom j) at i in' H \<and> (\<^bold>@ j p) at i in' H\<close> and DiaN: \<open>(\<^bold>\<not> (\<^bold>\<diamond> p)) at i in' H \<Longrightarrow> (\<^bold>\<diamond> Nom j) at i in' H \<Longrightarrow> (\<^bold>\<not> (\<^bold>@ j p)) at i in' H\<close> and SatP: \<open>(\<^bold>@ i p) at a in' H \<Longrightarrow> p at i in' H\<close> and SatN: \<open>(\<^bold>\<not> (\<^bold>@ i p)) at a in' H \<Longrightarrow> (\<^bold>\<not> p) at i in' H\<close> and GoTo: \<open>i \<in> nominals p \<Longrightarrow> \<exists>a. p at a in' H \<Longrightarrow> \<exists>ps. (ps, i) \<in> H\<close> and Nom: \<open>\<forall>a. p = Nom a \<or> p = (\<^bold>\<diamond> Nom a) \<longrightarrow> a \<in> A \<Longrightarrow> p at i in' H \<Longrightarrow> Nom j at i in' H \<Longrightarrow> p at j in' H\<close> text \<open> Two nominals \<open>i\<close> and \<open>j\<close> are equivalent in respect to a Hintikka set \<open>H\<close> if \<open>H\<close> contains an \<open>i\<close>-block with \<open>j\<close> on it. This is an equivalence relation on the names in \<open>H\<close> intersected with the allowed nominals \<open>A\<close>. \<close> definition hequiv :: \<open>('a, 'b) block set \<Rightarrow> 'b \<Rightarrow> 'b \<Rightarrow> bool\<close> where \<open>hequiv H i j \<equiv> Nom j at i in' H\<close> abbreviation hequiv_rel :: \<open>'b set \<Rightarrow> ('a, 'b) block set \<Rightarrow> ('b \<times> 'b) set\<close> where \<open>hequiv_rel A H \<equiv> {(i, j) |i j. hequiv H i j \<and> i \<in> A \<and> j \<in> A}\<close> definition names :: \<open>('a, 'b) block set \<Rightarrow> 'b set\<close> where \<open>names H \<equiv> {i |ps i. (ps, i) \<in> H}\<close> lemma hequiv_refl: \<open>i \<in> names H \<Longrightarrow> hequiv H i i\<close> unfolding hequiv_def names_def by simp lemma hequiv_refl': \<open>(ps, i) \<in> H \<Longrightarrow> hequiv H i i\<close> using hequiv_refl unfolding names_def by fastforce lemma hequiv_sym': assumes \<open>Hintikka A H\<close> \<open>i \<in> A\<close> \<open>hequiv H i j\<close> shows \<open>hequiv H j i\<close> proof - have \<open>i \<in> A \<longrightarrow> Nom i at i in' H \<longrightarrow> Nom j at i in' H \<longrightarrow> Nom i at j in' H\<close> for i j using assms(1) Hintikka.Nom by fast then show ?thesis using assms(2-) unfolding hequiv_def by auto qed lemma hequiv_sym: \<open>Hintikka A H \<Longrightarrow> i \<in> A \<Longrightarrow> j \<in> A \<Longrightarrow> hequiv H i j \<longleftrightarrow> hequiv H j i\<close> by (meson hequiv_sym') lemma hequiv_trans: assumes \<open>Hintikka A H\<close> \<open>i \<in> A\<close> \<open>k \<in> A\<close> \<open>hequiv H i j\<close> \<open>hequiv H j k\<close> shows \<open>hequiv H i k\<close> proof - have \<open>hequiv H j i\<close> by (meson assms(1-2, 4) hequiv_sym') moreover have \<open>k \<in> A \<longrightarrow> Nom k at j in' H \<longrightarrow> Nom i at j in' H \<longrightarrow> Nom k at i in' H\<close> for i k j using assms(1) Hintikka.Nom by fast ultimately show ?thesis using assms(3-) unfolding hequiv_def by blast qed lemma hequiv_names: \<open>hequiv H i j \<Longrightarrow> i \<in> names H\<close> unfolding hequiv_def names_def by blast lemma hequiv_names_rel: assumes \<open>Hintikka A H\<close> shows \<open>hequiv_rel A H \<subseteq> names H \<times> names H\<close> using assms hequiv_names hequiv_sym by fast lemma hequiv_refl_rel: assumes \<open>Hintikka A H\<close> shows \<open>refl_on (names H \<inter> A) (hequiv_rel A H)\<close> unfolding refl_on_def using assms hequiv_refl hequiv_names_rel by fast lemma hequiv_sym_rel: \<open>Hintikka A H \<Longrightarrow> sym (hequiv_rel A H)\<close> unfolding sym_def using hequiv_sym by fast lemma hequiv_trans_rel: \<open>Hintikka B A \<Longrightarrow> trans (hequiv_rel B A)\<close> unfolding trans_def using hequiv_trans by fast lemma hequiv_rel: \<open>Hintikka A H \<Longrightarrow> equiv (names H \<inter> A) (hequiv_rel A H)\<close> using hequiv_refl_rel hequiv_sym_rel hequiv_trans_rel by (rule equivI) lemma nominal_in_names: assumes \<open>Hintikka A H\<close> \<open>\<exists>block \<in> H. i \<in> block_nominals block\<close> shows \<open>i \<in> names H\<close> using assms Hintikka.GoTo unfolding names_def by fastforce subsubsection \<open>Named model\<close> text \<open> Given a Hintikka set \<open>H\<close>, a formula \<open>p\<close> on a block in \<open>H\<close> and a set of allowed nominals \<open>A\<close> which contains all "root-like" nominals in \<open>p\<close> we construct a model that satisfies \<open>p\<close>. The worlds of our model are sets of equivalent nominals and nominals are assigned to the equivalence class of an equivalent allowed nominal. This definition resembles the "ur-father" notion. From a world \<open>is\<close>, we can reach a world \<open>js\<close> iff there is an \<open>i \<in> is\<close> and a \<open>j \<in> js\<close> s.t. there is an \<open>i\<close>-block in \<open>H\<close> with \<open>\<^bold>\<diamond> Nom j\<close> on it. A propositional symbol \<open>p\<close> is true in a world \<open>is\<close> if there exists an \<open>i \<in> is\<close> s.t. \<open>p\<close> occurs on an \<open>i\<close>-block in \<open>H\<close>. \<close> definition assign :: \<open>'b set \<Rightarrow> ('a, 'b) block set \<Rightarrow> 'b \<Rightarrow> 'b set\<close> where \<open>assign A H i \<equiv> if \<exists>a. a \<in> A \<and> Nom a at i in' H then proj (hequiv_rel A H) (SOME a. a \<in> A \<and> Nom a at i in' H) else {i}\<close> definition reach :: \<open>'b set \<Rightarrow> ('a, 'b) block set \<Rightarrow> 'b set \<Rightarrow> 'b set set\<close> where \<open>reach A H is \<equiv> {assign A H j |i j. i \<in> is \<and> (\<^bold>\<diamond> Nom j) at i in' H}\<close> definition val :: \<open>('a, 'b) block set \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> bool\<close> where \<open>val H is x \<equiv> \<exists>i \<in> is. Pro x at i in' H\<close> lemma ex_assignment: assumes \<open>Hintikka A H\<close> shows \<open>assign A H i \<noteq> {}\<close> proof (cases \<open>\<exists>b. b \<in> A \<and> Nom b at i in' H\<close>) case True let ?b = \<open>SOME b. b \<in> A \<and> Nom b at i in' H\<close> have *: \<open>?b \<in> A \<and> Nom ?b at i in' H\<close> using someI_ex True . moreover from this have \<open>hequiv H ?b ?b\<close> using assms block_nominals nominal_in_names hequiv_refl by (metis (no_types, lifting) nominals.simps(2) singletonI) ultimately show ?thesis unfolding assign_def proj_def by auto next case False then show ?thesis unfolding assign_def by auto qed lemma ur_closure: assumes \<open>Hintikka A H\<close> \<open>p at i in' H\<close> \<open>\<forall>a. p = Nom a \<or> p = (\<^bold>\<diamond> Nom a) \<longrightarrow> a \<in> A\<close> shows \<open>\<forall>a \<in> assign A H i. p at a in' H\<close> proof (cases \<open>\<exists>b. b \<in> A \<and> Nom b at i in' H\<close>) case True let ?b = \<open>SOME b. b \<in> A \<and> Nom b at i in' H\<close> have *: \<open>?b \<in> A \<and> Nom ?b at i in' H\<close> using someI_ex True . then have \<open>p at ?b in' H\<close> using assms by (meson Hintikka.Nom) then have \<open>p at a in' H\<close> if \<open>hequiv H ?b a\<close> for a using that assms(1, 3) unfolding hequiv_def by (meson Hintikka.Nom) moreover have \<open>assign A H i = proj (hequiv_rel A H) ?b\<close> unfolding assign_def using True by simp ultimately show ?thesis unfolding proj_def by blast next case False then show ?thesis unfolding assign_def using assms by auto qed lemma ur_closure': assumes \<open>Hintikka A H\<close> \<open>p at i in' H\<close> \<open>\<forall>a. p = Nom a \<or> p = (\<^bold>\<diamond> Nom a) \<longrightarrow> a \<in> A\<close> shows \<open>\<exists>a \<in> assign A H i. p at a in' H\<close> proof - obtain a where \<open>a \<in> assign A H i\<close> using assms(1) ex_assignment by fast then show ?thesis using assms ur_closure[where i=i] by blast qed lemma mem_hequiv_rel: \<open>a \<in> proj (hequiv_rel A H) b \<Longrightarrow> a \<in> A\<close> unfolding proj_def by blast lemma hequiv_proj: assumes \<open>Hintikka A H\<close> \<open>Nom a at i in' H\<close> \<open>a \<in> A\<close> \<open>Nom b at i in' H\<close> \<open>b \<in> A\<close> shows \<open>proj (hequiv_rel A H) a = proj (hequiv_rel A H) b\<close> proof - have \<open>equiv (names H \<inter> A) (hequiv_rel A H)\<close> using assms(1) hequiv_rel by fast moreover have \<open>{a, b} \<subseteq> names H \<inter> A\<close> using assms(1-5) nominal_in_names by fastforce moreover have \<open>Nom b at a in' H\<close> using assms(1-2, 4-5) Hintikka.Nom by fast then have \<open>hequiv H a b\<close> unfolding hequiv_def by simp ultimately show ?thesis by (simp add: proj_iff) qed lemma hequiv_proj_opening: assumes \<open>Hintikka A H\<close> \<open>Nom a at i in' H\<close> \<open>a \<in> A\<close> \<open>i \<in> A\<close> shows \<open>proj (hequiv_rel A H) a = proj (hequiv_rel A H) i\<close> using hequiv_proj assms by fastforce lemma assign_proj_refl: assumes \<open>Hintikka A H\<close> \<open>Nom i at i in' H\<close> \<open>i \<in> A\<close> shows \<open>assign A H i = proj (hequiv_rel A H) i\<close> proof - let ?a = \<open>SOME a. a \<in> A \<and> Nom a at i in' H\<close> have \<open>\<exists>a. a \<in> A \<and> Nom a at i in' H\<close> using assms(2-3) by fast with someI_ex have *: \<open>?a \<in> A \<and> Nom ?a at i in' H\<close> . then have \<open>assign A H i = proj (hequiv_rel A H) ?a\<close> unfolding assign_def by auto then show ?thesis unfolding assign_def using hequiv_proj * assms by fast qed lemma assign_named: assumes \<open>Hintikka A H\<close> \<open>i \<in> proj (hequiv_rel A H) a\<close> shows \<open>i \<in> names H\<close> using assms unfolding proj_def by simp (meson hequiv_names hequiv_sym') lemma assign_unique: assumes \<open>Hintikka A H\<close> \<open>a \<in> assign A H i\<close> shows \<open>assign A H a = assign A H i\<close> proof (cases \<open>\<exists>b. b \<in> A \<and> Nom b at i in' H\<close>) case True let ?b = \<open>SOME b. b \<in> A \<and> Nom b at i in' H\<close> have *: \<open>?b \<in> A \<and> Nom ?b at i in' H\<close> using someI_ex True . have **: \<open>assign A H i = proj (hequiv_rel A H) ?b\<close> unfolding assign_def using True by simp moreover from this have \<open>Nom a at a in' H\<close> using assms assign_named unfolding names_def by fastforce ultimately have \<open>assign A H a = proj (hequiv_rel A H) a\<close> using assms assign_proj_refl mem_hequiv_rel by fast with ** show ?thesis unfolding proj_def using assms by simp (meson hequiv_sym' hequiv_trans) next case False then have \<open>assign A H i = {i}\<close> unfolding assign_def by auto then have \<open>a = i\<close> using assms(2) by simp then show ?thesis by simp qed lemma assign_val: assumes \<open>Hintikka A H\<close> \<open>Pro x at a in' H\<close> \<open>(\<^bold>\<not> Pro x) at i in' H\<close> \<open>a \<in> assign A H i\<close> \<open>i \<in> names H\<close> shows False using assms Hintikka.ProP ur_closure by fastforce lemma Hintikka_model: assumes \<open>Hintikka A H\<close> shows \<open>p at i in' H \<Longrightarrow> nominals p \<subseteq> A \<Longrightarrow> Model (reach A H) (val H), assign A H, assign A H i \<Turnstile> p\<close> \<open>(\<^bold>\<not> p) at i in' H \<Longrightarrow> nominals p \<subseteq> A \<Longrightarrow> \<not> Model (reach A H) (val H), assign A H, assign A H i \<Turnstile> p\<close> proof (induct p arbitrary: i) fix i case (Pro x) assume \<open>Pro x at i in' H\<close> then show \<open>Model (reach A H) (val H), assign A H, assign A H i \<Turnstile> Pro x\<close> using assms(1) ur_closure' unfolding val_def by fastforce next fix i case (Pro x) assume \<open>(\<^bold>\<not> Pro x) at i in' H\<close> then have \<open>\<nexists>a. a \<in> assign A H i \<and> Pro x at a in' H\<close> using assms(1) assign_val unfolding names_def by fast then have \<open>\<not> val H (assign A H i) x\<close> unfolding proj_def val_def hequiv_def by simp then show \<open>\<not> Model (reach A H) (val H), assign A H, assign A H i \<Turnstile> Pro x\<close> by simp next fix i case (Nom a) assume *: \<open>Nom a at i in' H\<close> \<open>nominals (Nom a) \<subseteq> A\<close> let ?b = \<open>SOME b. b \<in> A \<and> Nom b at i in' H\<close> let ?c = \<open>SOME b. b \<in> A \<and> Nom b at a in' H\<close> have \<open>a \<in> A\<close> using *(2) by simp then have \<open>\<exists>b. b \<in> A \<and> Nom b at i in' H\<close> using * by fast with someI_ex have b: \<open>?b \<in> A \<and> Nom ?b at i in' H\<close> . then have \<open>assign A H i = proj (hequiv_rel A H) ?b\<close> unfolding assign_def by auto also have \<open>proj (hequiv_rel A H) ?b = proj (hequiv_rel A H) a\<close> using hequiv_proj assms(1) b * \<open>a \<in> A\<close> by fast also have \<open>Nom a at a in' H\<close> using * \<open>a \<in> A\<close> assms(1) Hintikka.Nom by fast then have \<open>\<exists>c. c \<in> A \<and> Nom c at a in' H\<close> using \<open>a \<in> A\<close> by blast with someI_ex have c: \<open>?c \<in> A \<and> Nom ?c at a in' H\<close> . then have \<open>assign A H a = proj (hequiv_rel A H) ?c\<close> unfolding assign_def by auto then have \<open>proj (hequiv_rel A H) a = assign A H a\<close> using hequiv_proj_opening assms(1) \<open>a \<in> A\<close> c by fast finally have \<open>assign A H i = assign A H a\<close> . then show \<open>Model (reach A H) (val H), assign A H, assign A H i \<Turnstile> Nom a\<close> by simp next fix i case (Nom a) assume *: \<open>(\<^bold>\<not> Nom a) at i in' H\<close> \<open>nominals (Nom a) \<subseteq> A\<close> then have \<open>a \<in> A\<close> by simp have \<open>hequiv H a a\<close> using hequiv_refl * nominal_in_names assms(1) by fastforce obtain j where j: \<open>j \<in> assign A H i\<close> \<open>(\<^bold>\<not> Nom a) at j in' H\<close> using ur_closure' assms(1) * by fastforce then have \<open>\<not> Nom a at j in' H\<close> using assms(1) Hintikka.NomP by fast moreover have \<open>\<forall>b \<in> assign A H a. Nom a at b in' H\<close> using assms \<open>a \<in> A\<close> \<open>hequiv H a a\<close> ur_closure unfolding hequiv_def by fast ultimately have \<open>assign A H a \<noteq> assign A H i\<close> using j by blast then show \<open>\<not> Model (reach A H) (val H), assign A H, assign A H i \<Turnstile> Nom a\<close> by simp next fix i case (Neg p) moreover assume \<open>(\<^bold>\<not> p) at i in' H\<close> \<open>nominals (\<^bold>\<not> p) \<subseteq> A\<close> ultimately show \<open>Model (reach A H) (val H), assign A H, assign A H i \<Turnstile> \<^bold>\<not> p\<close> by simp next fix i case (Neg p) moreover assume *: \<open>(\<^bold>\<not> \<^bold>\<not> p) at i in' H\<close> then have \<open>p at i in' H\<close> using assms(1) Hintikka.NegN by fast moreover assume \<open>nominals (\<^bold>\<not> p) \<subseteq> A\<close> moreover from this * have \<open>\<forall>a. p = (\<^bold>\<diamond> Nom a) \<longrightarrow> a \<in> A\<close> by auto ultimately show \<open>\<not> Model (reach A H) (val H), assign A H, assign A H i \<Turnstile> \<^bold>\<not> p\<close> using assms(1) by auto next fix i case (Dis p q) moreover assume *: \<open>(p \<^bold>\<or> q) at i in' H\<close> then have \<open>p at i in' H \<or> q at i in' H\<close> using assms(1) Hintikka.DisP by fast moreover assume \<open>nominals (p \<^bold>\<or> q) \<subseteq> A\<close> moreover from this * have \<open>\<forall>a. p = (\<^bold>\<diamond> Nom a) \<longrightarrow> a \<in> A\<close> \<open>\<forall>a. q = (\<^bold>\<diamond> Nom a) \<longrightarrow> a \<in> A\<close> by auto ultimately show \<open>Model (reach A H) (val H), assign A H, assign A H i \<Turnstile> (p \<^bold>\<or> q)\<close> by simp metis next fix i case (Dis p q) moreover assume *: \<open>(\<^bold>\<not> (p \<^bold>\<or> q)) at i in' H\<close> then have \<open>(\<^bold>\<not> p) at i in' H\<close> \<open>(\<^bold>\<not> q) at i in' H\<close> using assms(1) Hintikka.DisN by fast+ moreover assume \<open>nominals (p \<^bold>\<or> q) \<subseteq> A\<close> moreover from this * have \<open>\<forall>a. p = (\<^bold>\<diamond> Nom a) \<longrightarrow> a \<in> A\<close> \<open>\<forall>a. q = (\<^bold>\<diamond> Nom a) \<longrightarrow> a \<in> A\<close> by auto ultimately show \<open>\<not> Model (reach A H) (val H), assign A H, assign A H i \<Turnstile> (p \<^bold>\<or> q)\<close> by auto next fix i case (Dia p) assume *: \<open>(\<^bold>\<diamond> p) at i in' H\<close> \<open>nominals (\<^bold>\<diamond> p) \<subseteq> A\<close> with * have p: \<open>\<forall>a. p = (\<^bold>\<diamond> Nom a) \<longrightarrow> a \<in> A\<close> by auto show \<open>Model (reach A H) (val H), assign A H, assign A H i \<Turnstile> \<^bold>\<diamond> p\<close> proof (cases \<open>\<exists>j. p = Nom j\<close>) case True then obtain j where j: \<open>p = Nom j\<close> \<open>j \<in> A\<close> using *(2) by auto then obtain a where a: \<open>a \<in> assign A H i\<close> \<open>(\<^bold>\<diamond> Nom j) at a in' H\<close> using ur_closure' assms(1) \<open>(\<^bold>\<diamond> p) at i in' H\<close> by fast from j have \<open>(\<^bold>\<diamond> Nom j) at i in' H\<close> using *(1) by simp then have \<open>(\<^bold>\<diamond> Nom j) at a in' H\<close> using ur_closure assms(1) a(2) by fast then have \<open>assign A H j \<in> reach A H (assign A H i)\<close> unfolding reach_def using a(1) by fast then show ?thesis using j(1) by simp next case False then obtain a where a: \<open>a \<in> assign A H i\<close> \<open>(\<^bold>\<diamond> p) at a in' H\<close> using ur_closure' assms(1) \<open>(\<^bold>\<diamond> p) at i in' H\<close> by fast then have \<open>\<exists>j. (\<^bold>\<diamond> Nom j) at a in' H \<and> (\<^bold>@ j p) at a in' H\<close> using False assms \<open>(\<^bold>\<diamond> p) at i in' H\<close> by (meson Hintikka.DiaP) then obtain j where j: \<open>(\<^bold>\<diamond> Nom j) at a in' H\<close> \<open>(\<^bold>@ j p) at a in' H\<close> by blast from j(2) have \<open>p at j in' H\<close> using assms(1) Hintikka.SatP by fast then have \<open>Model (reach A H) (val H), assign A H, assign A H j \<Turnstile> p\<close> using Dia p *(2) by simp moreover have \<open>assign A H j \<in> reach A H (assign A H i)\<close> unfolding reach_def using a(1) j(1) by blast ultimately show ?thesis by auto qed next fix i case (Dia p) assume *: \<open>(\<^bold>\<not> (\<^bold>\<diamond> p)) at i in' H\<close> \<open>nominals (\<^bold>\<diamond> p) \<subseteq> A\<close> then obtain a where a: \<open>a \<in> assign A H i\<close> \<open>(\<^bold>\<not> (\<^bold>\<diamond> p)) at a in' H\<close> using ur_closure' assms(1) by fast { fix j b assume \<open>(\<^bold>\<diamond> Nom j) at b in' H\<close> \<open>b \<in> assign A H a\<close> moreover have \<open>(\<^bold>\<not> (\<^bold>\<diamond> p)) at b in' H\<close> using a(2) assms(1) calculation(2) ur_closure by fast ultimately have \<open>(\<^bold>\<not> (\<^bold>@ j p)) at b in' H\<close> using assms(1) Hintikka.DiaN by fast then have \<open>(\<^bold>\<not> p) at j in' H\<close> using assms(1) Hintikka.SatN by fast then have \<open>\<not> Model (reach A H) (val H), assign A H, assign A H j \<Turnstile> p\<close> using Dia *(2) by simp } then have \<open>\<not> Model (reach A H) (val H), assign A H, assign A H a \<Turnstile> \<^bold>\<diamond> p\<close> unfolding reach_def by auto moreover have \<open>assign A H a = assign A H i\<close> using assms(1) a assign_unique by fast ultimately show \<open>\<not> Model (reach A H) (val H), assign A H, assign A H i \<Turnstile> \<^bold>\<diamond> p\<close> by simp next fix i case (Sat j p) assume \<open>(\<^bold>@ j p) at i in' H\<close> \<open>nominals (\<^bold>@ j p) \<subseteq> A\<close> moreover from this have \<open>\<forall>a. p = (\<^bold>\<diamond> Nom a) \<longrightarrow> a \<in> A\<close> by auto moreover have \<open>p at j in' H\<close> if \<open>\<exists>a. (\<^bold>@ j p) at a in' H\<close> using that assms(1) Hintikka.SatP by fast ultimately show \<open>Model (reach A H) (val H), assign A H, assign A H i \<Turnstile> \<^bold>@ j p\<close> using Sat by auto next fix i case (Sat j p) assume \<open>(\<^bold>\<not> (\<^bold>@ j p)) at i in' H\<close> \<open>nominals (\<^bold>@ j p) \<subseteq> A\<close> moreover from this have \<open>\<forall>a. p = (\<^bold>\<diamond> Nom a) \<longrightarrow> a \<in> A\<close> by auto moreover have \<open>(\<^bold>\<not> p) at j in' H\<close> if \<open>\<exists>a. (\<^bold>\<not> (\<^bold>@ j p)) at a in' H\<close> using that assms(1) Hintikka.SatN by fast ultimately show \<open>\<not> Model (reach A H) (val H), assign A H, assign A H i \<Turnstile> \<^bold>@ j p\<close> using Sat by fastforce qed subsection \<open>Lindenbaum-Henkin\<close> text \<open> A set of blocks is consistent if no finite subset can be derived. Given a consistent set of blocks we are going to extend it to be saturated and maximally consistent and show that is then Hintikka. All definitions are with respect to the set of allowed nominals. \<close> definition consistent :: \<open>'b set \<Rightarrow> ('a, 'b) block set \<Rightarrow> bool\<close> where \<open>consistent A S \<equiv> \<nexists>S'. set S' \<subseteq> S \<and> A \<turnstile> S'\<close> instance fm :: (countable, countable) countable by countable_datatype definition proper_dia :: \<open>('a, 'b) fm \<Rightarrow> ('a, 'b) fm option\<close> where \<open>proper_dia p \<equiv> case p of (\<^bold>\<diamond> p) \<Rightarrow> (if \<nexists>a. p = Nom a then Some p else None) | _ \<Rightarrow> None\<close> lemma proper_dia: \<open>proper_dia p = Some q \<Longrightarrow> p = (\<^bold>\<diamond> q) \<and> (\<nexists>a. q = Nom a)\<close> unfolding proper_dia_def by (cases p) (simp_all, metis option.discI option.inject) text \<open>The following function witnesses each \<open>\<^bold>\<diamond> p\<close> in a fresh world.\<close> primrec witness_list :: \<open>('a, 'b) fm list \<Rightarrow> 'b set \<Rightarrow> ('a, 'b) fm list\<close> where \<open>witness_list [] _ = []\<close> | \<open>witness_list (p # ps) used = (case proper_dia p of None \<Rightarrow> witness_list ps used | Some q \<Rightarrow> let i = SOME i. i \<notin> used in (\<^bold>@ i q) # (\<^bold>\<diamond> Nom i) # witness_list ps ({i} \<union> used))\<close> primrec witness :: \<open>('a, 'b) block \<Rightarrow> 'b set \<Rightarrow> ('a, 'b) block\<close> where \<open>witness (ps, a) used = (witness_list ps used, a)\<close> lemma witness_list: \<open>proper_dia p = Some q \<Longrightarrow> witness_list (p # ps) used = (let i = SOME i. i \<notin> used in (\<^bold>@ i q) # (\<^bold>\<diamond> Nom i) # witness_list ps ({i} \<union> used))\<close> by simp primrec extend :: \<open>'b set \<Rightarrow> ('a, 'b) block set \<Rightarrow> (nat \<Rightarrow> ('a, 'b) block) \<Rightarrow> nat \<Rightarrow> ('a, 'b) block set\<close> where \<open>extend A S f 0 = S\<close> | \<open>extend A S f (Suc n) = (if \<not> consistent A ({f n} \<union> extend A S f n) then extend A S f n else let used = A \<union> (\<Union>block \<in> {f n} \<union> extend A S f n. block_nominals block) in {f n, witness (f n) used} \<union> extend A S f n)\<close> definition Extend :: \<open>'b set \<Rightarrow> ('a, 'b) block set \<Rightarrow> (nat \<Rightarrow> ('a, 'b) block) \<Rightarrow> ('a, 'b) block set\<close> where \<open>Extend A S f \<equiv> (\<Union>n. extend A S f n)\<close> lemma extend_chain: \<open>extend A S f n \<subseteq> extend A S f (Suc n)\<close> by auto lemma extend_mem: \<open>S \<subseteq> extend A S f n\<close> by (induct n) auto lemma Extend_mem: \<open>S \<subseteq> Extend A S f\<close> unfolding Extend_def using extend_mem by fast subsubsection \<open>Consistency\<close> lemma split_list: \<open>set A \<subseteq> {x} \<union> X \<Longrightarrow> x \<in>. A \<Longrightarrow> \<exists>B. set (x # B) = set A \<and> x \<notin> set B\<close> by simp (metis Diff_insert_absorb mk_disjoint_insert set_removeAll) lemma consistent_drop_single: fixes a :: 'b assumes inf: \<open>infinite (UNIV :: 'b set)\<close> and fin: \<open>finite A\<close> and cons: \<open>consistent A ({(p # ps, a)} \<union> S)\<close> shows \<open>consistent A ({(ps, a)} \<union> S)\<close> unfolding consistent_def proof assume \<open>\<exists>S'. set S' \<subseteq> {(ps, a)} \<union> S \<and> A \<turnstile> S'\<close> then obtain S' n where \<open>set S' \<subseteq> {(ps, a)} \<union> S\<close> \<open>(ps, a) \<in>. S'\<close> \<open>A, n \<turnstile> S'\<close> using assms unfolding consistent_def by blast then obtain S'' where \<open>set ((ps, a) # S'') = set S'\<close> \<open>(ps, a) \<notin> set S''\<close> using split_list by metis then have \<open>A \<turnstile> (ps, a) # S''\<close> using inf fin STA_struct \<open>A, n \<turnstile> S'\<close> by blast then have \<open>A \<turnstile> (p # ps, a) # S''\<close> using inf fin STA_struct_block[where ps'=\<open>p # ps\<close>] by fastforce moreover have \<open>set ((p # ps, a) # S'') \<subseteq> {(p # ps, a)} \<union> S\<close> using \<open>(ps, a) \<notin> set S''\<close> \<open>set ((ps, a) # S'') = set S'\<close> \<open>set S' \<subseteq> {(ps, a)} \<union> S\<close> by auto ultimately show False using cons unfolding consistent_def by blast qed lemma consistent_drop_block: \<open>consistent A ({block} \<union> S) \<Longrightarrow> consistent A S\<close> unfolding consistent_def by blast lemma inconsistent_weaken: \<open>\<not> consistent A S \<Longrightarrow> S \<subseteq> S' \<Longrightarrow> \<not> consistent A S'\<close> unfolding consistent_def by blast lemma finite_nominals_set: \<open>finite S \<Longrightarrow> finite (\<Union>block \<in> S. block_nominals block)\<close> by (induct S rule: finite_induct) (simp_all add: finite_block_nominals) lemma witness_list_used: fixes i :: 'b assumes inf: \<open>infinite (UNIV :: 'b set)\<close> and \<open>finite used\<close> \<open>i \<notin> list_nominals ps\<close> shows \<open>i \<notin> list_nominals (witness_list ps ({i} \<union> used))\<close> using assms(2-) proof (induct ps arbitrary: used) case (Cons p ps) then show ?case proof (cases \<open>proper_dia p\<close>) case (Some q) let ?j = \<open>SOME j. j \<notin> {i} \<union> used\<close> have \<open>finite ({i} \<union> used)\<close> using \<open>finite used\<close> by simp then have \<open>\<exists>j. j \<notin> {i} \<union> used\<close> using inf ex_new_if_finite by metis then have j: \<open>?j \<notin> {i} \<union> used\<close> using someI_ex by metis have \<open>witness_list (p # ps) ({i} \<union> used) = (\<^bold>@ ?j q) # (\<^bold>\<diamond> Nom ?j) # witness_list ps ({?j} \<union> ({i} \<union> used))\<close> using Some witness_list by metis then have *: \<open>list_nominals (witness_list (p # ps) ({i} \<union> used)) = {?j} \<union> nominals q \<union> list_nominals (witness_list ps ({?j} \<union> ({i} \<union> used)))\<close> by simp have \<open>finite ({?j} \<union> used)\<close> using \<open>finite used\<close> by simp moreover have \<open>i \<notin> list_nominals ps\<close> using \<open>i \<notin> list_nominals (p # ps)\<close> by simp ultimately have \<open>i \<notin> list_nominals (witness_list ps ({i} \<union> ({?j} \<union> used)))\<close> using Cons by metis moreover have \<open>{i} \<union> ({?j} \<union> used) = {?j} \<union> ({i} \<union> used)\<close> by blast moreover have \<open>i \<noteq> ?j\<close> using j by auto ultimately have \<open>i \<in> list_nominals (witness_list (p # ps) ({i} \<union> used)) \<longleftrightarrow> i \<in> nominals q\<close> using * by simp moreover have \<open>i \<notin> nominals q\<close> using Cons(3) Some proper_dia by fastforce ultimately show ?thesis by blast qed simp qed simp lemma consistent_witness_list: fixes a :: 'b assumes inf: \<open>infinite (UNIV :: 'b set)\<close> and \<open>consistent A S\<close> \<open>(ps, a) \<in> S\<close> \<open>finite used\<close> \<open>A \<union> \<Union> (block_nominals ` S) \<subseteq> used\<close> shows \<open>consistent A ({(witness_list ps used, a)} \<union> S)\<close> using assms(2-) proof (induct ps arbitrary: used S) case Nil then have \<open>{(witness_list [] used, a)} \<union> S = S\<close> by auto moreover have \<open>finite {}\<close> \<open>{} \<inter> used = {}\<close> by simp_all ultimately show ?case using \<open>consistent A S\<close> by simp next case (Cons p ps) have fin: \<open>finite A\<close> using assms(4-5) finite_subset by fast have \<open>{(p # ps, a)} \<union> S = S\<close> using \<open>(p # ps, a) \<in> S\<close> by blast then have \<open>consistent A ({(p # ps, a)} \<union> S)\<close> using \<open>consistent A S\<close> by simp then have \<open>consistent A ({(ps, a)} \<union> S)\<close> using inf fin consistent_drop_single by fast moreover have \<open>(ps, a) \<in> {(ps, a)} \<union> S\<close> by simp moreover have \<open>A \<union> \<Union> (block_nominals ` ({(ps, a)} \<union> S)) \<subseteq> extra \<union> used\<close> for extra using \<open>(p # ps, a) \<in> S\<close> \<open>A \<union> \<Union> (block_nominals ` S) \<subseteq> used\<close> by fastforce moreover have \<open>finite (extra \<union> used)\<close> if \<open>finite extra\<close> for extra using that \<open>finite used\<close> by blast ultimately have cons: \<open>consistent A ({(witness_list ps (extra \<union> used), a)} \<union> ({(ps, a)} \<union> S))\<close> if \<open>finite extra\<close> for extra using that Cons by metis show ?case proof (cases \<open>proper_dia p\<close>) case None then have \<open>witness_list (p # ps) used = witness_list ps used\<close> by auto moreover have \<open>consistent A ({(witness_list ps used, a)} \<union> ({(ps, a)} \<union> S))\<close> using cons[where extra=\<open>{}\<close>] by simp then have \<open>consistent A ({(witness_list ps used, a)} \<union> S)\<close> using consistent_drop_block[where block=\<open>(ps, a)\<close>] by auto ultimately show ?thesis by simp next case (Some q) let ?i = \<open>SOME i. i \<notin> used\<close> have \<open>\<exists>i. i \<notin> used\<close> using ex_new_if_finite inf \<open>finite used\<close> . with someI_ex have \<open>?i \<notin> used\<close> . then have i: \<open>?i \<notin> \<Union> (block_nominals ` S)\<close> using Cons by auto then have \<open>?i \<notin> block_nominals (p # ps, a)\<close> using Cons by blast let ?tail = \<open>witness_list ps ({?i} \<union> used)\<close> have \<open>consistent A ({(?tail, a)} \<union> ({(ps, a)} \<union> S))\<close> using cons[where extra=\<open>{?i}\<close>] by blast then have *: \<open>consistent A ({(?tail, a)} \<union> S)\<close> using consistent_drop_block[where block=\<open>(ps, a)\<close>] by simp have \<open>witness_list (p # ps) used = (\<^bold>@ ?i q) # (\<^bold>\<diamond> Nom ?i) # ?tail\<close> using Some witness_list by metis moreover have \<open>consistent A ({((\<^bold>@ ?i q) # (\<^bold>\<diamond> Nom ?i) # ?tail, a)} \<union> S)\<close> unfolding consistent_def proof assume \<open>\<exists>S'. set S' \<subseteq> {((\<^bold>@ ?i q) # (\<^bold>\<diamond> Nom ?i) # ?tail, a)} \<union> S \<and> A \<turnstile> S'\<close> then obtain S' n where \<open>A, n \<turnstile> S'\<close> and S': \<open>set S' \<subseteq> {((\<^bold>@ ?i q) # (\<^bold>\<diamond> Nom ?i) # ?tail, a)} \<union> S\<close> \<open>((\<^bold>@ ?i q) # (\<^bold>\<diamond> Nom ?i) # ?tail, a) \<in>. S'\<close> using * unfolding consistent_def by blast then obtain S'' where S'': \<open>set (((\<^bold>@ ?i q) # (\<^bold>\<diamond> Nom ?i) # ?tail, a) # S'') = set S'\<close> \<open>((\<^bold>@ ?i q) # (\<^bold>\<diamond> Nom ?i) # ?tail, a) \<notin> set S''\<close> using split_list[where x=\<open>((\<^bold>@ ?i q) # (\<^bold>\<diamond> Nom ?i) # ?tail, a)\<close>] by blast then have \<open>A \<turnstile> ((\<^bold>@ ?i q) # (\<^bold>\<diamond> Nom ?i) # ?tail, a) # S''\<close> using inf \<open>finite A\<close> STA_struct \<open>A, n \<turnstile> S'\<close> by blast moreover have \<open>set (((\<^bold>@ ?i q) # (\<^bold>\<diamond> Nom ?i) # ?tail, a) # S'') \<subseteq> set (((\<^bold>@ ?i q) # (\<^bold>\<diamond> Nom ?i) # ?tail, a) # (p # ps, a) # S'')\<close> by auto ultimately have **: \<open>A \<turnstile> ((\<^bold>@ ?i q) # (\<^bold>\<diamond> Nom ?i) # ?tail, a) # (p # ps, a) # S''\<close> using inf \<open>finite A\<close> STA_struct by blast have \<open>?i \<notin> block_nominals (?tail, a)\<close> using inf \<open>finite used\<close> \<open>?i \<notin> block_nominals (p # ps, a)\<close> witness_used by fastforce moreover have \<open>?i \<notin> branch_nominals S''\<close> unfolding branch_nominals_def using i S' S'' by auto ultimately have \<open>?i \<notin> branch_nominals ((?tail, a) # (p # ps, a) # S'')\<close> using \<open>?i \<notin> block_nominals (p # ps, a)\<close> unfolding branch_nominals_def by simp then have \<open>?i \<notin> A \<union> branch_nominals ((?tail, a) # (p # ps, a) # S'')\<close> using \<open>?i \<notin> used\<close> Cons.prems(4) by blast moreover have \<open>\<nexists>a. q = Nom a\<close> using Some proper_dia by blast moreover have \<open>(p # ps, a) \<in>. (?tail, a) # (p # ps, a) # S''\<close> by simp moreover have \<open>p = (\<^bold>\<diamond> q)\<close> using Some proper_dia by blast then have \<open>(\<^bold>\<diamond> q) on (p # ps, a)\<close> by simp ultimately have \<open>A \<turnstile> (?tail, a) # (p # ps, a) # S''\<close> using ** \<open>finite A\<close> DiaP'' by fast moreover have \<open>set ((p # ps, a) # S'') \<subseteq> S\<close> using Cons(3) S' S'' by auto ultimately show False using * unfolding consistent_def by (simp add: subset_Un_eq) qed ultimately show ?thesis by simp qed qed lemma consistent_witness: fixes block :: \<open>('a, 'b) block\<close> assumes \<open>infinite (UNIV :: 'b set)\<close> \<open>consistent A S\<close> \<open>finite (\<Union> (block_nominals ` S))\<close> \<open>block \<in> S\<close> \<open>finite A\<close> shows \<open>consistent A ({witness block (A \<union> \<Union> (block_nominals ` S))} \<union> S)\<close> using assms consistent_witness_list by (cases block) fastforce lemma consistent_extend: fixes S :: \<open>('a, 'b) block set\<close> assumes inf: \<open>infinite (UNIV :: 'b set)\<close> and fin: \<open>finite A\<close> and \<open>consistent A (extend A S f n)\<close> \<open>finite (\<Union> (block_nominals ` extend A S f n))\<close> shows \<open>consistent A (extend A S f (Suc n))\<close> proof (cases \<open>consistent A ({f n} \<union> extend A S f n)\<close>) case True let ?used = \<open>A \<union> (\<Union>block \<in> {f n} \<union> extend A S f n. block_nominals block)\<close> have *: \<open>extend A S f (n + 1) = {f n, witness (f n) ?used} \<union> extend A S f n\<close> using True by simp have \<open>consistent A ({f n} \<union> extend A S f n)\<close> using True by simp moreover have \<open>finite ((\<Union> (block_nominals ` ({f n} \<union> extend A S f n))))\<close> using \<open>finite (\<Union> (block_nominals ` extend A S f n))\<close> finite_nominals_set by force moreover have \<open>f n \<in> {f n} \<union> extend A S f n\<close> by simp ultimately have \<open>consistent A ({witness (f n) ?used} \<union> ({f n} \<union> extend A S f n))\<close> using inf fin consistent_witness by blast then show ?thesis using * by simp next case False then show ?thesis using assms(3) by simp qed lemma finite_nominals_extend: assumes \<open>finite (\<Union> (block_nominals ` S))\<close> shows \<open>finite (\<Union> (block_nominals ` extend A S f n))\<close> using assms by (induct n) (auto simp add: finite_block_nominals) lemma consistent_extend': fixes S :: \<open>('a, 'b) block set\<close> assumes \<open>infinite (UNIV :: 'b set)\<close> \<open>finite A\<close> \<open>consistent A S\<close> \<open>finite (\<Union> (block_nominals ` S))\<close> shows \<open>consistent A (extend A S f n)\<close> using assms proof (induct n) case (Suc n) then show ?case by (metis consistent_extend finite_nominals_extend) qed simp lemma UN_finite_bound: assumes \<open>finite A\<close> \<open>A \<subseteq> (\<Union>n. f n)\<close> shows \<open>\<exists>m :: nat. A \<subseteq> (\<Union>n \<le> m. f n)\<close> using assms proof (induct A rule: finite_induct) case (insert x A) then obtain m where \<open>A \<subseteq> (\<Union>n \<le> m. f n)\<close> by fast then have \<open>A \<subseteq> (\<Union>n \<le> (m + k). f n)\<close> for k by fastforce moreover obtain m' where \<open>x \<in> f m'\<close> using insert(4) by blast ultimately have \<open>{x} \<union> A \<subseteq> (\<Union>n \<le> m + m'. f n)\<close> by auto then show ?case by blast qed simp lemma extend_bound: \<open>(\<Union>n \<le> m. extend A S f n) = extend A S f m\<close> proof (induct m) case (Suc m) have \<open>\<Union> (extend A S f ` {..Suc m}) = \<Union> (extend A S f ` {..m}) \<union> extend A S f (Suc m)\<close> using atMost_Suc by auto also have \<open>\<dots> = extend A S f m \<union> extend A S f (Suc m)\<close> using Suc by blast also have \<open>\<dots> = extend A S f (Suc m)\<close> using extend_chain by blast finally show ?case by simp qed simp lemma consistent_Extend: fixes S :: \<open>('a, 'b) block set\<close> assumes inf: \<open>infinite (UNIV :: 'b set)\<close> and \<open>finite A\<close> \<open>consistent A S\<close> \<open>finite (\<Union> (block_nominals ` S))\<close> shows \<open>consistent A (Extend A S f)\<close> unfolding Extend_def proof (rule ccontr) assume \<open>\<not> consistent A (\<Union> (range (extend A S f)))\<close> then obtain S' n where *: \<open>A, n \<turnstile> S'\<close> \<open>set S' \<subseteq> (\<Union>n. extend A S f n)\<close> unfolding consistent_def by blast moreover have \<open>finite (set S')\<close> by simp ultimately obtain m where \<open>set S' \<subseteq> (\<Union>n \<le> m. extend A S f n)\<close> using UN_finite_bound by metis then have \<open>set S' \<subseteq> extend A S f m\<close> using extend_bound by blast moreover have \<open>consistent A (extend A S f m)\<close> using assms consistent_extend' by blast ultimately show False unfolding consistent_def using * by blast qed subsubsection \<open>Maximality\<close> text \<open>A set of blocks is maximally consistent if any proper extension makes it inconsistent.\<close> definition maximal :: \<open>'b set \<Rightarrow> ('a, 'b) block set \<Rightarrow> bool\<close> where \<open>maximal A S \<equiv> consistent A S \<and> (\<forall>block. block \<notin> S \<longrightarrow> \<not> consistent A ({block} \<union> S))\<close> lemma extend_not_mem: \<open>f n \<notin> extend A S f (Suc n) \<Longrightarrow> \<not> consistent A ({f n} \<union> extend A S f n)\<close> by (metis Un_insert_left extend.simps(2) insertI1) lemma maximal_Extend: fixes S :: \<open>('a, 'b) block set\<close> assumes inf: \<open>infinite (UNIV :: 'b set)\<close> and \<open>finite A\<close> \<open>consistent A S\<close> \<open>finite (\<Union> (block_nominals ` S))\<close> \<open>surj f\<close> shows \<open>maximal A (Extend A S f)\<close> proof (rule ccontr) assume \<open>\<not> maximal A (Extend A S f)\<close> then obtain block where \<open>block \<notin> Extend A S f\<close> \<open>consistent A ({block} \<union> Extend A S f)\<close> unfolding maximal_def using assms consistent_Extend by metis obtain n where n: \<open>f n = block\<close> using \<open>surj f\<close> unfolding surj_def by metis then have \<open>block \<notin> extend A S f (Suc n)\<close> using \<open>block \<notin> Extend A S f\<close> extend_chain unfolding Extend_def by blast then have \<open>\<not> consistent A ({block} \<union> extend A S f n)\<close> using n extend_not_mem by blast moreover have \<open>block \<notin> extend A S f n\<close> using \<open>block \<notin> extend A S f (Suc n)\<close> extend_chain by blast then have \<open>{block} \<union> extend A S f n \<subseteq> {block} \<union> Extend A S f\<close> unfolding Extend_def by blast ultimately have \<open>\<not> consistent A ({block} \<union> Extend A S f)\<close> using inconsistent_weaken by blast then show False using \<open>consistent A ({block} \<union> Extend A S f)\<close> by simp qed subsubsection \<open>Saturation\<close> text \<open>A set of blocks is saturated if every \<open>\<^bold>\<diamond> p\<close> is witnessed.\<close> definition saturated :: \<open>('a, 'b) block set \<Rightarrow> bool\<close> where \<open>saturated S \<equiv> \<forall>p i. (\<^bold>\<diamond> p) at i in' S \<longrightarrow> (\<nexists>a. p = Nom a) \<longrightarrow> (\<exists>j. (\<^bold>@ j p) at i in' S \<and> (\<^bold>\<diamond> Nom j) at i in' S)\<close> lemma witness_list_append: \<open>\<exists>extra. witness_list (ps @ qs) used = witness_list ps used @ witness_list qs (extra \<union> used)\<close> proof (induct ps arbitrary: used) case Nil then show ?case by (metis Un_absorb append_self_conv2 witness_list.simps(1)) next case (Cons p ps) show ?case proof (cases \<open>\<exists>q. proper_dia p = Some q\<close>) case True let ?i = \<open>SOME i. i \<notin> used\<close> from True obtain q where q: \<open>proper_dia p = Some q\<close> by blast moreover have \<open>(p # ps) @ qs = p # (ps @ qs)\<close> by simp ultimately have \<open>witness_list ((p # ps) @ qs) used = (\<^bold>@ ?i q) # (\<^bold>\<diamond> Nom ?i) # witness_list (ps @ qs) ({?i} \<union> used)\<close> using witness_list by metis then have \<open>\<exists>extra. witness_list ((p # ps) @ qs) used = (\<^bold>@ ?i q) # (\<^bold>\<diamond> Nom ?i) # witness_list ps ({?i} \<union> used) @ witness_list qs (extra \<union> ({?i} \<union> used))\<close> using Cons by metis moreover have \<open>(\<^bold>@ ?i q) # (\<^bold>\<diamond> Nom ?i) # witness_list ps ({?i} \<union> used) = witness_list (p # ps) used\<close> using q witness_list by metis ultimately have \<open>\<exists>extra. witness_list ((p # ps) @ qs) used = witness_list (p # ps) used @ witness_list qs (extra \<union> ({?i} \<union> used))\<close> by (metis append_Cons) then have \<open>\<exists>extra. witness_list ((p # ps) @ qs) used = witness_list (p # ps) used @ witness_list qs (({?i} \<union> extra) \<union> used)\<close> by simp then show ?thesis by blast qed (simp add: Cons) qed lemma ex_witness_list: assumes \<open>p \<in>. ps\<close> \<open>proper_dia p = Some q\<close> shows \<open>\<exists>i. {\<^bold>@ i q, \<^bold>\<diamond> Nom i} \<subseteq> set (witness_list ps used)\<close> using \<open>p \<in>. ps\<close> proof (induct ps arbitrary: used) case (Cons a ps) then show ?case proof (induct \<open>a = p\<close>) case True then have \<open>\<exists>i. witness_list (a # ps) used = (\<^bold>@ i q) # (\<^bold>\<diamond> Nom i) # witness_list ps ({i} \<union> used)\<close> using \<open>proper_dia p = Some q\<close> witness_list by metis then show ?case by auto next case False then have \<open>\<exists>i. {\<^bold>@ i q, \<^bold>\<diamond> Nom i} \<subseteq> set (witness_list ps (extra \<union> used))\<close> for extra by simp moreover have \<open>\<exists>extra. witness_list (a # ps) used = witness_list [a] used @ witness_list ps (extra \<union> used)\<close> using witness_list_append[where ps=\<open>[_]\<close>] by simp ultimately show ?case by fastforce qed qed simp lemma saturated_Extend: fixes S :: \<open>('a, 'b) block set\<close> assumes inf: \<open>infinite (UNIV :: 'b set)\<close> and fin: \<open>finite A\<close> and \<open>consistent A S\<close> \<open>finite (\<Union> (block_nominals ` S))\<close> \<open>surj f\<close> shows \<open>saturated (Extend A S f)\<close> unfolding saturated_def proof safe fix ps i p assume \<open>(ps, i) \<in> Extend A S f\<close> \<open>(\<^bold>\<diamond> p) on (ps, i)\<close> \<open>\<nexists>a. p = Nom a\<close> obtain n where n: \<open>f n = (ps, i)\<close> using \<open>surj f\<close> unfolding surj_def by metis let ?used = \<open>A \<union> (\<Union>block \<in> {f n} \<union> extend A S f n. block_nominals block)\<close> have \<open>extend A S f n \<subseteq> Extend A S f\<close> unfolding Extend_def by auto moreover have \<open>consistent A (Extend A S f)\<close> using assms consistent_Extend by blast ultimately have \<open>consistent A ({(ps, i)} \<union> extend A S f n)\<close> using \<open>(ps, i) \<in> Extend A S f\<close> inconsistent_weaken by blast then have \<open>extend A S f (Suc n) = {f n, witness (f n) ?used} \<union> extend A S f n\<close> using n \<open>(\<^bold>\<diamond> p) on (ps, i)\<close> by auto then have \<open>witness (f n) ?used \<in> Extend A S f\<close> unfolding Extend_def by blast then have *: \<open>(witness_list ps ?used, i) \<in> Extend A S f\<close> using n by simp have \<open>(\<^bold>\<diamond> p) \<in>. ps\<close> using \<open>(\<^bold>\<diamond> p) on (ps, i)\<close> by simp moreover have \<open>proper_dia (\<^bold>\<diamond> p) = Some p\<close> unfolding proper_dia_def using \<open>\<nexists>a. p = Nom a\<close> by simp ultimately have \<open>\<exists>j. (\<^bold>@ j p) on (witness_list ps ?used, i) \<and> (\<^bold>\<diamond> Nom j) on (witness_list ps ?used, i)\<close> using ex_witness_list by fastforce then show \<open>\<exists>j. (\<exists>qs. (qs, i) \<in> Extend A S f \<and> (\<^bold>@ j p) on (qs, i)) \<and> (\<exists>rs. (rs, i) \<in> Extend A S f \<and> (\<^bold>\<diamond> Nom j) on (rs, i))\<close> using * by blast qed subsection \<open>Smullyan-Fitting\<close> lemma Hintikka_Extend: fixes S :: \<open>('a, 'b) block set\<close> assumes inf: \<open>infinite (UNIV :: 'b set)\<close> and fin: \<open>finite A\<close> and \<open>maximal A S\<close> \<open>consistent A S\<close> \<open>saturated S\<close> shows \<open>Hintikka A S\<close> unfolding Hintikka_def proof safe fix x i j ps qs rs assume ps: \<open>(ps, i) \<in> S\<close> \<open>Nom j on (ps, i)\<close> and qs: \<open>(qs, j) \<in> S\<close> \<open>Pro x on (qs, j)\<close> and rs: \<open>(rs, i) \<in> S\<close> \<open>(\<^bold>\<not> Pro x) on (rs, i)\<close> then have \<open>\<not> A, n \<turnstile> [(qs, j), (ps, i), (rs, i)]\<close> for n using \<open>consistent A S\<close> unfolding consistent_def by simp moreover have \<open>A, n \<turnstile> [((\<^bold>\<not> Pro x) # qs, j), (ps, i), (rs, i)]\<close> for n using qs(2) Close by (metis (no_types, lifting) list.set_intros(1) on.simps set_subset_Cons subsetD) then have \<open>A, n \<turnstile> [(qs, j), (ps, i), (rs, i)]\<close> for n using ps(2) rs(2) by (meson Nom' fm.distinct(21) fm.simps(18) list.set_intros(1) set_subset_Cons subsetD) ultimately show False by blast next fix a i ps qs assume ps: \<open>(ps, i) \<in> S\<close> \<open>Nom a on (ps, i)\<close> and qs: \<open>(qs, i) \<in> S\<close> \<open>(\<^bold>\<not> Nom a) on (qs, i)\<close> then have \<open>\<not> A , n \<turnstile> [(ps, i), (qs, i)]\<close> for n using \<open>consistent A S\<close> unfolding consistent_def by simp moreover have \<open>A, n \<turnstile> [(ps, i), (qs, i)]\<close> for n using ps(2) qs(2) by (meson Close list.set_intros(1) set_subset_Cons subset_code(1)) ultimately show False by blast next fix p i ps assume ps: \<open>(ps, i) \<in> S\<close> \<open>(\<^bold>\<not> \<^bold>\<not> p) on (ps, i)\<close> show \<open>p at i in' S\<close> proof (rule ccontr) assume \<open>\<not> p at i in' S\<close> then obtain S' n where \<open>A, n \<turnstile> S'\<close> and S': \<open>set S' \<subseteq> {(p # ps, i)} \<union> S\<close> and \<open>(p # ps, i) \<in>. S'\<close> using \<open>maximal A S\<close> unfolding maximal_def consistent_def by (metis insert_is_Un list.set_intros(1) on.simps subset_insert) then obtain S'' where S'': \<open>set ((p # ps, i) # S'') = set S'\<close> \<open>(p # ps, i) \<notin> set S''\<close> using split_list[where x=\<open>(p # ps, i)\<close>] by blast then have \<open>A \<turnstile> (p # ps, i) # S''\<close> using inf fin STA_struct \<open>A, n \<turnstile> S'\<close> by blast then have \<open>A \<turnstile> (ps, i) # S''\<close> using ps by (meson Neg' list.set_intros(1)) moreover have \<open>set ((ps, i) # S'') \<subseteq> S\<close> using S' S'' ps by auto ultimately show False using \<open>consistent A S\<close> unfolding consistent_def by blast qed next fix p q i ps assume ps: \<open>(ps, i) \<in> S\<close> \<open>(p \<^bold>\<or> q) on (ps, i)\<close> and *: \<open>\<not> q at i in' S\<close> show \<open>p at i in' S\<close> proof (rule ccontr) assume \<open>\<not> p at i in' S\<close> then obtain Sp' np where \<open>A, np \<turnstile> Sp'\<close> and Sp': \<open>set Sp' \<subseteq> {(p # ps, i)} \<union> S\<close> and \<open>(p # ps, i) \<in>. Sp'\<close> using \<open>maximal A S\<close> unfolding maximal_def consistent_def by (metis insert_is_Un list.set_intros(1) on.simps subset_insert) then obtain Sp'' where Sp'': \<open>set ((p # ps, i) # Sp'') = set Sp'\<close> \<open>(p # ps, i) \<notin> set Sp''\<close> using split_list[where x=\<open>(p # ps, i)\<close>] by blast then have \<open>A \<turnstile> (p # ps, i) # Sp''\<close> using \<open>A, np \<turnstile> Sp'\<close> inf fin STA_struct by blast obtain Sq' nq where \<open>A, nq \<turnstile> Sq'\<close> and Sq': \<open>set Sq' \<subseteq> {(q # ps, i)} \<union> S\<close> and \<open>(q # ps, i) \<in>. Sq'\<close> using * \<open>maximal A S\<close> unfolding maximal_def consistent_def by (metis insert_is_Un list.set_intros(1) on.simps subset_insert) then obtain Sq'' where Sq'': \<open>set ((q # ps, i) # Sq'') = set Sq'\<close> \<open>(q # ps, i) \<notin> set Sq''\<close> using split_list[where x=\<open>(q # ps, i)\<close>] by blast then have \<open>A \<turnstile> (q # ps, i) # Sq''\<close> using \<open>A, nq \<turnstile> Sq'\<close> inf fin STA_struct by blast obtain S'' where S'': \<open>set S'' = set Sp'' \<union> set Sq''\<close> by (meson set_union) then have \<open>set ((p # ps, i) # Sp'') \<subseteq> set ((p # ps, i) # S'')\<close> \<open>set ((q # ps, i) # Sq'') \<subseteq> set ((q # ps, i) # S'')\<close> by auto then have \<open>A \<turnstile> (p # ps, i) # S''\<close> \<open>A \<turnstile> (q # ps, i) # S''\<close> using \<open>A \<turnstile> (p # ps, i) # Sp''\<close> \<open>A \<turnstile> (q # ps, i) # Sq''\<close> inf fin STA_struct by blast+ then have \<open>A \<turnstile> (ps, i) # S''\<close> using ps by (meson DisP'' list.set_intros(1)) moreover have \<open>set ((ps, i) # S'') \<subseteq> S\<close> using ps Sp' Sp'' Sq' Sq'' S'' by auto ultimately show False using \<open>consistent A S\<close> unfolding consistent_def by blast qed next fix p q i ps assume ps: \<open>(ps, i) \<in> S\<close> \<open>(\<^bold>\<not> (p \<^bold>\<or> q)) on (ps, i)\<close> show \<open>(\<^bold>\<not> p) at i in' S\<close> proof (rule ccontr) assume \<open>\<not> (\<^bold>\<not> p) at i in' S\<close> then obtain S' where \<open>A \<turnstile> S'\<close> and S': \<open>set S' \<subseteq> {((\<^bold>\<not> q) # (\<^bold>\<not> p) # ps, i)} \<union> S\<close> and \<open>((\<^bold>\<not> q) # (\<^bold>\<not> p) # ps, i) \<in>. S'\<close> using \<open>maximal A S\<close> unfolding maximal_def consistent_def by (metis (mono_tags, lifting) insert_is_Un insert_subset list.simps(15) on.simps set_subset_Cons subset_insert) then obtain S'' where S'': \<open>set (((\<^bold>\<not> q) # (\<^bold>\<not> p) # ps, i) # S'') = set S'\<close> \<open>((\<^bold>\<not> q) # (\<^bold>\<not> p) # ps, i) \<notin> set S''\<close> using split_list[where x=\<open>((\<^bold>\<not> q) # (\<^bold>\<not> p) # ps, i)\<close>] by blast then have \<open>A \<turnstile> ((\<^bold>\<not> q) # (\<^bold>\<not> p) # ps, i) # S''\<close> using inf fin STA_struct \<open>A \<turnstile> S'\<close> by blast then have \<open>A \<turnstile> (ps, i) # S''\<close> using ps by (meson DisN' list.set_intros(1)) moreover have \<open>set ((ps, i) # S'') \<subseteq> S\<close> using S' S'' ps by auto ultimately show False using \<open>consistent A S\<close> unfolding consistent_def by blast qed next fix p q i ps assume ps: \<open>(ps, i) \<in> S\<close> \<open>(\<^bold>\<not> (p \<^bold>\<or> q)) on (ps, i)\<close> show \<open>(\<^bold>\<not> q) at i in' S\<close> proof (rule ccontr) assume \<open>\<not> (\<^bold>\<not> q) at i in' S\<close> then obtain S' where \<open>A \<turnstile> S'\<close> and S': \<open>set S' \<subseteq> {((\<^bold>\<not> q) # (\<^bold>\<not> p) # ps, i)} \<union> S\<close> and \<open>((\<^bold>\<not> q) # (\<^bold>\<not> p) # ps, i) \<in>. S'\<close> using \<open>maximal A S\<close> unfolding maximal_def consistent_def by (metis (mono_tags, lifting) insert_is_Un insert_subset list.simps(15) on.simps set_subset_Cons subset_insert) then obtain S'' where S'': \<open>set (((\<^bold>\<not> q) # (\<^bold>\<not> p) # ps, i) # S'') = set S'\<close> \<open>((\<^bold>\<not> q) # (\<^bold>\<not> p) # ps, i) \<notin> set S''\<close> using split_list[where x=\<open>((\<^bold>\<not> q) # (\<^bold>\<not> p) # ps, i)\<close>] by blast then have \<open>A \<turnstile> ((\<^bold>\<not> q) # (\<^bold>\<not> p) # ps, i) # S''\<close> using inf fin STA_struct \<open>A \<turnstile> S'\<close> by blast then have \<open>A \<turnstile> (ps, i) # S''\<close> using ps by (meson DisN' list.set_intros(1)) moreover have \<open>set ((ps, i) # S'') \<subseteq> S\<close> using S' S'' ps by auto ultimately show False using \<open>consistent A S\<close> unfolding consistent_def by blast qed next fix p i ps assume \<open>\<nexists>a. p = Nom a\<close> \<open>(ps, i) \<in> S\<close> \<open>(\<^bold>\<diamond> p) on (ps, i)\<close> then show \<open>\<exists>j. (\<^bold>\<diamond> Nom j) at i in' S \<and> (\<^bold>@ j p) at i in' S\<close> using \<open>saturated S\<close> unfolding saturated_def by blast next fix p i j ps qs assume ps: \<open>(ps, i) \<in> S\<close> \<open>(\<^bold>\<not> (\<^bold>\<diamond> p)) on (ps, i)\<close> and qs: \<open>(qs, i) \<in> S\<close> \<open>(\<^bold>\<diamond> Nom j) on (qs, i)\<close> show \<open>(\<^bold>\<not> (\<^bold>@ j p)) at i in' S\<close> proof (rule ccontr) assume \<open>\<not> (\<^bold>\<not> (\<^bold>@ j p)) at i in' S\<close> then obtain S' n where \<open>A, n \<turnstile> S'\<close> and S': \<open>set S' \<subseteq> {([\<^bold>\<not> (\<^bold>@ j p)], i)} \<union> S\<close> and \<open>([\<^bold>\<not> (\<^bold>@ j p)], i) \<in>. S'\<close> using \<open>maximal A S\<close> unfolding maximal_def consistent_def by (metis insert_is_Un list.set_intros(1) on.simps subset_insert) then obtain S'' where S'': \<open>set (([\<^bold>\<not> (\<^bold>@ j p)], i) # S'') = set S'\<close> \<open>([\<^bold>\<not> (\<^bold>@ j p)], i) \<notin> set S''\<close> using split_list[where x=\<open>([\<^bold>\<not> (\<^bold>@ j p)], i)\<close>] by blast then have \<open>A \<turnstile> ([\<^bold>\<not> (\<^bold>@ j p)], i) # S''\<close> using inf fin STA_struct \<open>A, n \<turnstile> S'\<close> by blast then have \<open>A \<turnstile> ([\<^bold>\<not> (\<^bold>@ j p)], i) # (ps, i) # (qs, i) # S''\<close> using inf fin STA_struct[where branch'=\<open>([_], _) # (ps, i) # (qs, i) # S''\<close>] \<open>A, n \<turnstile> S'\<close> by fastforce then have \<open>A \<turnstile> ([], i) # (ps, i) # (qs, i) # S''\<close> using ps(2) qs(2) by (meson DiaN' list.set_intros(1) set_subset_Cons subset_iff) moreover have \<open>i \<in> branch_nominals ((ps, i) # (qs, i) # S'')\<close> unfolding branch_nominals_def by simp ultimately have \<open>A \<turnstile> (ps, i) # (qs, i) # S''\<close> using GoTo by fast moreover have \<open>set ((ps, i) # (qs, i) # S'') \<subseteq> S\<close> using S' S'' ps qs by auto ultimately show False using \<open>consistent A S\<close> unfolding consistent_def by blast qed next fix p i ps a assume ps: \<open>(ps, a) \<in> S\<close> \<open>(\<^bold>@ i p) on (ps, a)\<close> show \<open>p at i in' S\<close> proof (rule ccontr) assume \<open>\<not> p at i in' S\<close> then obtain S' n where \<open>A, n \<turnstile> S'\<close> and S': \<open>set S' \<subseteq> {([p], i)} \<union> S\<close> and \<open>([p], i) \<in>. S'\<close> using \<open>maximal A S\<close> unfolding maximal_def consistent_def by (metis insert_is_Un list.set_intros(1) on.simps subset_insert) then obtain S'' where S'': \<open>set (([p], i) # S'') = set S'\<close> \<open>([p], i) \<notin> set S''\<close> using split_list[where x=\<open>([p], i)\<close>] by blast then have \<open>A \<turnstile> ([p], i) # S''\<close> using inf fin STA_struct \<open>A, n \<turnstile> S'\<close> by blast moreover have \<open>set (([p], i) # S'') \<subseteq> set (([p], i) # (ps, a) # S'')\<close> by auto ultimately have \<open>A \<turnstile> ([p], i) # (ps, a) # S''\<close> using inf fin STA_struct \<open>A, n \<turnstile> S'\<close> by blast then have \<open>A \<turnstile> ([], i) # (ps, a) # S''\<close> using ps by (metis SatP' insert_iff list.simps(15)) moreover have \<open>i \<in> branch_nominals ((ps, a) # S'')\<close> using ps unfolding branch_nominals_def by fastforce ultimately have \<open>A \<turnstile> (ps, a) # S''\<close> using GoTo by fast moreover have \<open>set ((ps, a) # S'') \<subseteq> S\<close> using S' S'' ps by auto ultimately show False using \<open>consistent A S\<close> unfolding consistent_def by blast qed next fix p i ps a assume ps: \<open>(ps, a) \<in> S\<close> \<open>(\<^bold>\<not> (\<^bold>@ i p)) on (ps, a)\<close> show \<open>(\<^bold>\<not> p) at i in' S\<close> proof (rule ccontr) assume \<open>\<not> (\<^bold>\<not> p) at i in' S\<close> then obtain S' n where \<open>A, n \<turnstile> S'\<close> and S': \<open>set S' \<subseteq> {([\<^bold>\<not> p], i)} \<union> S\<close> and \<open>([\<^bold>\<not> p], i) \<in>. S'\<close> using \<open>maximal A S\<close> unfolding maximal_def consistent_def by (metis insert_is_Un list.set_intros(1) on.simps subset_insert) then obtain S'' where S'': \<open>set (([\<^bold>\<not> p], i) # S'') = set S'\<close> \<open>([\<^bold>\<not> p], i) \<notin> set S''\<close> using split_list[where x=\<open>([\<^bold>\<not> p], i)\<close>] by blast then have \<open>A \<turnstile> ([\<^bold>\<not> p], i) # S''\<close> using inf fin STA_struct \<open>A, n \<turnstile> S'\<close> by blast then have \<open>A \<turnstile> ([\<^bold>\<not> p], i) # (ps, a) # S''\<close> using inf fin STA_struct[where branch'=\<open>([\<^bold>\<not> p], i) # _ # S''\<close>] \<open>A, n \<turnstile> S'\<close> by fastforce then have \<open>A \<turnstile> ([], i) # (ps, a) # S''\<close> using ps by (metis SatN' insert_iff list.simps(15)) moreover have \<open>i \<in> branch_nominals ((ps, a) # S'')\<close> using ps unfolding branch_nominals_def by fastforce ultimately have \<open>A \<turnstile> (ps, a) # S''\<close> using GoTo by fast moreover have \<open>set ((ps, a) # S'') \<subseteq> S\<close> using S' S'' ps by auto ultimately show False using \<open>consistent A S\<close> unfolding consistent_def by blast qed next fix p i ps a assume i: \<open>i \<in> nominals p\<close> and ps: \<open>(ps, a) \<in> S\<close> \<open>p on (ps, a)\<close> show \<open>\<exists>qs. (qs, i) \<in> S\<close> proof (rule ccontr) assume \<open>\<nexists>qs. (qs, i) \<in> S\<close> then obtain S' n where \<open>A, n \<turnstile> S'\<close> and S': \<open>set S' \<subseteq> {([], i)} \<union> S\<close> and \<open>([], i) \<in>. S'\<close> using \<open>maximal A S\<close> unfolding maximal_def consistent_def by (metis insert_is_Un subset_insert) then obtain S'' where S'': \<open>set (([], i) # S'') = set S'\<close> \<open>([], i) \<notin> set S''\<close> using split_list[where x=\<open>([], i)\<close>] by blast then have \<open>A \<turnstile> ([], i) # (ps, a) # S''\<close> using inf fin STA_struct[where branch'=\<open>([], i) # (ps, a) # S''\<close>] \<open>A, n \<turnstile> S'\<close> by fastforce moreover have \<open>i \<in> branch_nominals ((ps, a) # S'')\<close> using i ps unfolding branch_nominals_def by auto ultimately have \<open>A \<turnstile> (ps, a) # S''\<close> using GoTo by fast moreover have \<open>set ((ps, a) # S'') \<subseteq> S\<close> using S' S'' ps by auto ultimately show False using \<open>consistent A S\<close> unfolding consistent_def by blast qed next fix p i j ps qs assume p: \<open>\<forall>a. p = Nom a \<or> p = (\<^bold>\<diamond> Nom a) \<longrightarrow> a \<in> A\<close> and ps: \<open>(ps, i) \<in> S\<close> \<open>p on (ps, i)\<close> and qs: \<open>(qs, i) \<in> S\<close> \<open>Nom j on (qs, i)\<close> show \<open>p at j in' S\<close> proof (rule ccontr) assume \<open>\<nexists>rs. (rs, j) \<in> S \<and> p on (rs, j)\<close> then obtain S' n where \<open>A, n \<turnstile> S'\<close> and S': \<open>set S' \<subseteq> {([p], j)} \<union> S\<close> and \<open>([p], j) \<in>. S'\<close> using \<open>maximal A S\<close> unfolding maximal_def consistent_def by (metis insert_is_Un list.set_intros(1) on.simps subset_insert) then obtain S'' where S'': \<open>set (([p], j) # S'') = set S'\<close> \<open>([p], j) \<notin> set S''\<close> using split_list[where x=\<open>([p], j)\<close>] by blast then have \<open>A \<turnstile> ([p], j) # S''\<close> using inf fin STA_struct \<open>A, n \<turnstile> S'\<close> by blast then have \<open>A \<turnstile> ([p], j) # (ps, i) # (qs, i) # S''\<close> using inf fin STA_struct[where branch'=\<open>([_], _) # (ps, i) # (qs, i) # S''\<close>] \<open>A, n \<turnstile> S'\<close> by fastforce then have \<open>A \<turnstile> ([], j) # (ps, i) # (qs, i) # S''\<close> using ps(2) qs(2) p by (meson Nom' in_mono list.set_intros(1) set_subset_Cons) moreover have \<open>j \<in> branch_nominals ((ps, i) # (qs, i) # S'')\<close> using qs(2) unfolding branch_nominals_def by fastforce ultimately have \<open>A \<turnstile> (ps, i) # (qs, i) # S''\<close> using GoTo by fast moreover have \<open>set ((ps, i) # (qs, i) # S'') \<subseteq> S\<close> using S' S'' ps qs by auto ultimately show False using \<open>consistent A S\<close> unfolding consistent_def by blast qed qed subsection \<open>Result\<close> theorem completeness: fixes p :: \<open>('a :: countable, 'b :: countable) fm\<close> assumes inf: \<open>infinite (UNIV :: 'b set)\<close> and valid: \<open>\<forall>(M :: ('b set, 'a) model) g w. M, g, w \<Turnstile> p\<close> shows \<open>nominals p, 1 \<turnstile> [([\<^bold>\<not> p], i)]\<close> proof - let ?A = \<open>nominals p\<close> have \<open>?A \<turnstile> [([\<^bold>\<not> p], i)]\<close> proof (rule ccontr) assume \<open>\<not> ?A \<turnstile> [([\<^bold>\<not> p], i)]\<close> moreover have \<open>finite ?A\<close> using finite_nominals by blast ultimately have *: \<open>consistent ?A {([\<^bold>\<not> p], i)}\<close> unfolding consistent_def using STA_struct inf by (metis empty_set list.simps(15)) let ?S = \<open>Extend ?A {([\<^bold>\<not> p], i)} from_nat\<close> have \<open>finite {([\<^bold>\<not> p], i)}\<close> by simp then have fin: \<open>finite (\<Union> (block_nominals ` {([\<^bold>\<not> p], i)}))\<close> using finite_nominals_set by blast have \<open>consistent ?A ?S\<close> using consistent_Extend inf * fin \<open>finite ?A\<close> by blast moreover have \<open>maximal ?A ?S\<close> using maximal_Extend inf * fin by fastforce moreover have \<open>saturated ?S\<close> using saturated_Extend inf * fin by fastforce ultimately have \<open>Hintikka ?A ?S\<close> using Hintikka_Extend inf \<open>finite ?A\<close> by blast moreover have \<open>([\<^bold>\<not> p], i) \<in> ?S\<close> using Extend_mem by blast moreover have \<open>(\<^bold>\<not> p) on ([\<^bold>\<not> p], i)\<close> by simp ultimately have \<open>\<not> Model (reach ?A ?S) (val ?S), assign ?A ?S, assign ?A ?S i \<Turnstile> p\<close> using Hintikka_model(2) by fast then show False using valid by blast qed then show ?thesis using STA_one by fast qed text \<open> We arbitrarily fix nominal and propositional symbols to be natural numbers (any countably infinite type suffices) and define validity as truth in all models with sets of natural numbers as worlds. We show below that this implies validity for any type of worlds. \<close> abbreviation \<open>valid p \<equiv> \<forall>(M :: (nat set, nat) model) (g :: nat \<Rightarrow> _) w. M, g, w \<Turnstile> p\<close> text \<open> A formula is valid iff its negation has a closing tableau from a fresh world. We can assume a single unit of potential and take the allowed nominals to be the root nominals. \<close> theorem main: assumes \<open>i \<notin> nominals p\<close> shows \<open>valid p \<longleftrightarrow> nominals p, 1 \<turnstile> [([\<^bold>\<not> p], i)]\<close> proof assume \<open>valid p\<close> then show \<open>nominals p, 1 \<turnstile> [([\<^bold>\<not> p], i)]\<close> using completeness by blast next assume \<open>nominals p, 1 \<turnstile> [([\<^bold>\<not> p], i)]\<close> then show \<open>valid p\<close> using assms soundness_fresh by fast qed text \<open>The restricted validity implies validity in general.\<close> theorem valid_semantics: \<open>valid p \<longrightarrow> M, g, w \<Turnstile> p\<close> proof assume \<open>valid p\<close> then have \<open>i \<notin> nominals p \<Longrightarrow> nominals p \<turnstile> [([\<^bold>\<not> p], i)]\<close> for i using main by blast moreover have \<open>\<exists>i. i \<notin> nominals p\<close> by (simp add: finite_nominals ex_new_if_finite) ultimately show \<open>M, g, w \<Turnstile> p\<close> using soundness_fresh by fast qed end
------------------------------------------------------------------------ -- The one-sided Step function, used to define similarity and the -- two-sided Step function ------------------------------------------------------------------------ {-# OPTIONS --sized-types #-} open import Prelude open import Labelled-transition-system module Similarity.Step {ℓ} (lts : LTS ℓ) (open LTS lts) (_[_]↝_ : Proc → Label → Proc → Type ℓ) where open import Equality.Propositional open import Logical-equivalence using (_⇔_) open import Bijection equality-with-J as Bijection using (_↔_) import Equivalence equality-with-J as Eq open import Function-universe equality-with-J as F hiding (id; _∘_) open import H-level equality-with-J open import H-level.Closure equality-with-J open import Indexed-container hiding (⟨_⟩) open import Relation private module Temporarily-private where -- If _[_]↝_ is instantiated with _[_]⟶_, then this is basically the -- function s from Section 6.3.4.2 in Pous and Sangiorgi's -- "Enhancements of the bisimulation proof method", except that -- clause (3) is omitted. -- -- Similarly, if _[_]↝_ is instantiated with _[_]⇒̂_, then this is -- basically the function w from Section 6.5.2.4, except that -- "P R Q" is omitted. record Step {r} (R : Rel₂ r Proc) (pq : Proc × Proc) : Type (ℓ ⊔ r) where constructor ⟨_⟩ private p = proj₁ pq q = proj₂ pq field challenge : ∀ {p′ μ} → p [ μ ]⟶ p′ → ∃ λ q′ → q [ μ ]↝ q′ × R (p′ , q′) open Temporarily-private using (Step) -- Used to aid unification. Note that this type is parametrised (see -- the module telescope above). The inclusion of a value of this type -- in the definition of StepC below makes it easier for Agda to infer -- the LTS parameter from the types ν StepC i (p , q) and -- ν′ StepC i (p , q). record Magic : Type where -- The Magic type is isomorphic to the unit type. Magic↔⊤ : Magic ↔ ⊤ Magic↔⊤ = record { surjection = record { right-inverse-of = λ _ → refl } ; left-inverse-of = λ _ → refl } -- The Step function, expressed as an indexed container. StepC : Container (Proc × Proc) (Proc × Proc) StepC = (λ { (p , q) → Magic -- Included in order to aid type inference. × (∀ {p′ μ} → p [ μ ]⟶ p′ → ∃ λ q′ → q [ μ ]↝ q′) }) ◁ (λ { {o = p , q} (_ , lr) (p′ , q′) → ∃ λ μ → ∃ λ (p⟶p′ : p [ μ ]⟶ p′) → proj₁ (lr p⟶p′) ≡ q′ }) -- The definition of Step in terms of a container is pointwise -- logically equivalent to the direct definition, and in the presence -- of extensionality it is pointwise isomorphic to the direct -- definition. Step↔StepC : ∀ {k r} {R : Rel₂ r Proc} {pq} → Extensionality? k ℓ (ℓ ⊔ r) → Step R pq ↝[ k ] ⟦ StepC ⟧ R pq Step↔StepC {r = r} {R} {pq} = generalise-ext? Step⇔StepC (λ ext → (λ (_ , f) → Σ-≡,≡→≡ refl $ implicit-extensionality ext λ _ → apply-ext (lower-extensionality lzero ℓ ext) $ to₂∘from f) , (λ _ → refl)) where to₁ : Step R pq → Container.Shape StepC pq to₁ Temporarily-private.⟨ lr ⟩ = _ , (λ p⟶p′ → Σ-map id proj₁ (lr p⟶p′)) to₂ : (s : Step R pq) → Container.Position StepC (to₁ s) ⊆ R to₂ Temporarily-private.⟨ lr ⟩ (_ , p⟶p′ , refl) = proj₂ (proj₂ (lr p⟶p′)) from : ⟦ StepC ⟧ R pq → Step R pq from ((_ , lr) , f) = Temporarily-private.⟨ (λ p⟶p′ → let q′ , q⟶q′ = lr p⟶p′ in q′ , q⟶q′ , f (_ , p⟶p′ , refl)) ⟩ Step⇔StepC : Step R pq ⇔ ⟦ StepC ⟧ R pq Step⇔StepC = record { to = λ s → to₁ s , to₂ s ; from = from } to₂∘from : ∀ {p′q′} {s : Container.Shape StepC pq} (f : Container.Position StepC s ⊆ R) → (pos : Container.Position StepC s p′q′) → proj₂ (_⇔_.to Step⇔StepC (_⇔_.from Step⇔StepC (s , f))) pos ≡ f pos to₂∘from f (_ , _ , refl) = refl module StepC {r} {R : Rel₂ r Proc} {p q} where -- A "constructor". ⟨_⟩ : (∀ {p′ μ} → p [ μ ]⟶ p′ → ∃ λ q′ → q [ μ ]↝ q′ × R (p′ , q′)) → ⟦ StepC ⟧ R (p , q) ⟨ lr ⟩ = _⇔_.to (Step↔StepC _) Temporarily-private.⟨ lr ⟩ -- A "projection". challenge : ⟦ StepC ⟧ R (p , q) → ∀ {p′ μ} → p [ μ ]⟶ p′ → ∃ λ q′ → q [ μ ]↝ q′ × R (p′ , q′) challenge = Step.challenge ∘ _⇔_.from (Step↔StepC _) open Temporarily-private public -- An unfolding lemma for ⟦ StepC ⟧₂. ⟦StepC⟧₂↔ : ∀ {x} {X : Rel₂ x Proc} → Extensionality ℓ ℓ → (R : ∀ {o} → Rel₂ ℓ (X o)) → ∀ {p q} (p∼q₁ p∼q₂ : ⟦ StepC ⟧ X (p , q)) → ⟦ StepC ⟧₂ R (p∼q₁ , p∼q₂) ↔ (∀ {p′ μ} (p⟶p′ : p [ μ ]⟶ p′) → let q′₁ , q⟶q′₁ , p′≤q′₁ = StepC.challenge p∼q₁ p⟶p′ q′₂ , q⟶q′₂ , p′≤q′₂ = StepC.challenge p∼q₂ p⟶p′ in ∃ λ (q′₁≡q′₂ : q′₁ ≡ q′₂) → subst (q [ μ ]↝_) q′₁≡q′₂ q⟶q′₁ ≡ q⟶q′₂ × R (subst (X ∘ (p′ ,_)) q′₁≡q′₂ p′≤q′₁ , p′≤q′₂)) ⟦StepC⟧₂↔ {X = X} ext R {p} {q} (s₁@(_ , ch₁) , f₁) (s₂@(_ , ch₂) , f₂) = (∃ λ (eq : s₁ ≡ s₂) → ∀ {o} (p : Container.Position StepC s₁ o) → R (f₁ p , f₂ (subst (λ s → Container.Position StepC s o) eq p))) ↝⟨ inverse $ Σ-cong ≡×≡↔≡ (λ _ → F.id) ⟩ (∃ λ (eq : proj₁ s₁ ≡ proj₁ s₂ × (λ {_ _} → ch₁) ≡ ch₂) → ∀ {o} (p : Container.Position StepC s₁ o) → R (f₁ p , f₂ (subst (λ s → Container.Position StepC s o) (cong₂ _,_ (proj₁ eq) (proj₂ eq)) p))) ↝⟨ inverse Σ-assoc ⟩ (∃ λ (eq₁ : proj₁ s₁ ≡ proj₁ s₂) → ∃ λ (eq₂ : (λ {_ _} → ch₁) ≡ ch₂) → ∀ {o} (p : Container.Position StepC s₁ o) → R (f₁ p , f₂ (subst (λ s → Container.Position StepC s o) (cong₂ _,_ eq₁ eq₂) p))) ↝⟨ drop-⊤-left-Σ $ _⇔_.to contractible⇔↔⊤ $ +⇒≡ $ mono₁ 0 (_⇔_.from contractible⇔↔⊤ Magic↔⊤) ⟩ (∃ λ (eq : (λ {_ _} → ch₁) ≡ ch₂) → ∀ {o} (p : Container.Position StepC s₁ o) → R (f₁ p , f₂ (subst (λ s → Container.Position StepC s o) (cong₂ _,_ refl eq) p))) ↝⟨ (∃-cong λ eq → implicit-∀-cong ext $ ∀-cong ext λ _ → ≡⇒↝ _ $ cong (λ (eq : s₁ ≡ s₂) → R (f₁ _ , f₂ (subst (λ s → Container.Position StepC s _) eq _))) $ trans-reflˡ (cong (_ ,_) eq)) ⟩ (∃ λ (eq : (λ {_ _} → ch₁) ≡ ch₂) → ∀ {o} (p : Container.Position StepC s₁ o) → R (f₁ p , f₂ (subst (λ (s : _ × _) → Container.Position StepC s o) (cong (_ ,_) eq) p))) ↝⟨ (∃-cong λ eq → implicit-∀-cong ext λ {o} → ∀-cong ext λ p → ≡⇒↝ _ $ cong (λ p → R {o = o} (f₁ _ , f₂ p)) $ sym $ subst-∘ (λ (s : Container.Shape StepC _) → Container.Position StepC s o) _ eq) ⟩ (∃ λ (eq : (λ {_ _} → ch₁) ≡ ch₂) → ∀ {o} (p : Container.Position StepC s₁ o) → R (f₁ p , f₂ (subst (λ (ch : ∀ {_ _} → _) → Container.Position StepC (_ , ch) o) eq p))) ↔⟨⟩ (∃ λ (eq : _≡_ {A = ∀ {p′ μ} → _} ch₁ ch₂) → ∀ {p′q′} → (pos : ∃ λ μ → ∃ λ (p⟶p′ : p [ μ ]⟶ proj₁ p′q′) → proj₁ (ch₁ p⟶p′) ≡ proj₂ p′q′) → R (f₁ pos , f₂ (subst (λ ch → ∃ λ μ → ∃ λ (p⟶p′ : p [ μ ]⟶ proj₁ p′q′) → proj₁ (ch p⟶p′) ≡ proj₂ p′q′) eq pos))) ↝⟨ (∃-cong λ _ → Bijection.implicit-Π↔Π) ⟩ (∃ λ (eq : _≡_ {A = ∀ {p′ μ} → _} ch₁ ch₂) → ∀ p′q′ → (pos : ∃ λ μ → ∃ λ (p⟶p′ : p [ μ ]⟶ proj₁ p′q′) → proj₁ (ch₁ p⟶p′) ≡ proj₂ p′q′) → R (f₁ pos , f₂ (subst (λ ch → ∃ λ μ → ∃ λ (p⟶p′ : p [ μ ]⟶ proj₁ p′q′) → proj₁ (ch p⟶p′) ≡ proj₂ p′q′) eq pos))) ↝⟨ (∃-cong λ _ → currying) ⟩ (∃ λ (eq : _≡_ {A = ∀ {p′ μ} → _} ch₁ ch₂) → ∀ p′ q′ → (pos : ∃ λ μ → ∃ λ (p⟶p′ : p [ μ ]⟶ p′) → proj₁ (ch₁ p⟶p′) ≡ q′) → R (f₁ pos , f₂ (subst (λ ch → ∃ λ μ → ∃ λ (p⟶p′ : p [ μ ]⟶ p′) → proj₁ (ch p⟶p′) ≡ q′) eq pos))) ↝⟨ (∃-cong λ _ → ∀-cong ext λ _ → ∀-cong ext λ _ → currying) ⟩ (∃ λ (eq : _≡_ {A = ∀ {p′ μ} → _} ch₁ ch₂) → ∀ p′ q′ μ → (pos : ∃ λ (p⟶p′ : p [ μ ]⟶ p′) → proj₁ (ch₁ p⟶p′) ≡ q′) → R (f₁ (μ , pos) , f₂ (subst (λ ch → ∃ λ μ → ∃ λ (p⟶p′ : p [ μ ]⟶ p′) → proj₁ (ch p⟶p′) ≡ q′) eq (μ , pos)))) ↝⟨ (∃-cong λ _ → ∀-cong ext λ _ → ∀-cong ext λ _ → ∀-cong ext λ _ → currying) ⟩ (∃ λ (eq : _≡_ {A = ∀ {p′ μ} → _} ch₁ ch₂) → ∀ p′ q′ μ (p⟶p′ : p [ μ ]⟶ p′) (≡q′ : proj₁ (ch₁ p⟶p′) ≡ q′) → R (f₁ (μ , p⟶p′ , ≡q′) , f₂ (subst (λ ch → ∃ λ μ → ∃ λ (p⟶p′ : p [ μ ]⟶ p′) → proj₁ (ch p⟶p′) ≡ q′) eq (μ , p⟶p′ , ≡q′)))) ↝⟨ (∃-cong λ _ → ∀-cong ext λ _ → Π-comm) ⟩ (∃ λ (eq : _≡_ {A = ∀ {p′ μ} → _} ch₁ ch₂) → ∀ p′ μ q′ (p⟶p′ : p [ μ ]⟶ p′) (≡q′ : proj₁ (ch₁ p⟶p′) ≡ q′) → R (f₁ (μ , p⟶p′ , ≡q′) , f₂ (subst (λ ch → ∃ λ μ → ∃ λ (p⟶p′ : p [ μ ]⟶ p′) → proj₁ (ch p⟶p′) ≡ q′) eq (μ , p⟶p′ , ≡q′)))) ↝⟨ (∃-cong λ _ → ∀-cong ext λ _ → ∀-cong ext λ _ → Π-comm) ⟩ (∃ λ (eq : _≡_ {A = ∀ {p′ μ} → _} ch₁ ch₂) → ∀ p′ μ (p⟶p′ : p [ μ ]⟶ p′) q′ (≡q′ : proj₁ (ch₁ p⟶p′) ≡ q′) → R (f₁ (μ , p⟶p′ , ≡q′) , f₂ (subst (λ ch → ∃ λ μ → ∃ λ (p⟶p′ : p [ μ ]⟶ p′) → proj₁ (ch p⟶p′) ≡ q′) eq (μ , p⟶p′ , ≡q′)))) ↝⟨ (∃-cong λ _ → ∀-cong ext λ _ → ∀-cong ext λ _ → ∀-cong ext λ _ → inverse $ ∀-intro _ ext) ⟩ (∃ λ (eq : _≡_ {A = ∀ {p′ μ} → _} ch₁ ch₂) → ∀ p′ μ (p⟶p′ : p [ μ ]⟶ p′) → R (f₁ (μ , p⟶p′ , refl) , f₂ (subst (λ ch → ∃ λ μ → ∃ λ (p⟶p′′ : p [ μ ]⟶ p′) → proj₁ (ch p⟶p′′) ≡ proj₁ (ch₁ p⟶p′)) eq (μ , p⟶p′ , refl)))) ↝⟨ (∃-cong λ eq → ∀-cong ext λ _ → ∀-cong ext λ _ → ∀-cong ext λ _ → ≡⇒↝ _ $ cong (R ∘ (f₁ _ ,_) ∘ f₂) $ lemma₁ eq) ⟩ (∃ λ (eq : _≡_ {A = ∀ {p′ μ} → _} ch₁ ch₂) → ∀ p′ μ (p⟶p′ : p [ μ ]⟶ p′) → R (f₁ (μ , p⟶p′ , refl) , f₂ (μ , p⟶p′ , sym (cong (λ ch → proj₁ (ch p⟶p′)) eq)))) ↝⟨ (∃-cong λ eq → ∀-cong ext λ _ → inverse Bijection.implicit-Π↔Π) ⟩ (∃ λ (eq : _≡_ {A = ∀ {p′ μ} → _} ch₁ ch₂) → ∀ p′ {μ} (p⟶p′ : p [ μ ]⟶ p′) → R (f₁ (μ , p⟶p′ , refl) , f₂ (μ , p⟶p′ , sym (cong (λ ch → proj₁ (ch p⟶p′)) eq)))) ↝⟨ (∃-cong λ eq → inverse Bijection.implicit-Π↔Π) ⟩ (∃ λ (eq : _≡_ {A = ∀ {p′ μ} → _} ch₁ ch₂) → ∀ {p′ μ} (p⟶p′ : p [ μ ]⟶ p′) → R (f₁ (μ , p⟶p′ , refl) , f₂ (μ , p⟶p′ , sym (cong (λ ch → proj₁ (ch p⟶p′)) eq)))) ↝⟨ (Σ-cong (inverse $ implicit-extensionality-isomorphism {k = bijection} ext) λ eq → implicit-∀-cong ext $ implicit-∀-cong ext $ ∀-cong ext λ p⟶p′ → ≡⇒↝ _ $ sym $ cong (λ eq → R (f₁ _ , f₂ (_ , p⟶p′ , sym (cong (λ ch → proj₁ (ch p⟶p′)) eq)))) $ _↔_.right-inverse-of (implicit-extensionality-isomorphism ext) eq) ⟩ (∃ λ (eq : ∀ p′ → (λ {μ} → ch₁ {p′ = p′} {μ = μ}) ≡ ch₂) → let eq′ = _↔_.to (implicit-extensionality-isomorphism ext) eq in ∀ {p′ μ} (p⟶p′ : p [ μ ]⟶ p′) → R (f₁ (μ , p⟶p′ , refl) , f₂ (μ , p⟶p′ , sym (cong (λ ch → proj₁ (ch p⟶p′)) eq′)))) ↝⟨ (∃-cong λ eq → implicit-∀-cong ext $ implicit-∀-cong ext $ ∀-cong ext λ p⟶p′ → ≡⇒↝ _ $ cong (λ eq → R (f₁ _ , f₂ (_ , p⟶p′ , sym eq))) $ lemma₂ eq) ⟩ (∃ λ (eq : ∀ p′ → (λ {μ} → ch₁ {p′ = p′} {μ = μ}) ≡ ch₂) → ∀ {p′ μ} (p⟶p′ : p [ μ ]⟶ p′) → R (f₁ (μ , p⟶p′ , refl) , f₂ (μ , p⟶p′ , sym (cong (λ ch → proj₁ (ch p′ p⟶p′)) (apply-ext (Eq.good-ext ext) eq))))) ↝⟨ (Σ-cong (inverse $ ∀-cong ext λ _ → implicit-extensionality-isomorphism {k = bijection} ext) λ eq → implicit-∀-cong ext $ implicit-∀-cong ext $ ∀-cong ext λ p⟶p′ → ≡⇒↝ _ $ sym $ cong (λ eq → R (f₁ _ , f₂ (_ , p⟶p′ , sym (cong (λ ch → proj₁ (ch _ p⟶p′)) (apply-ext (Eq.good-ext ext) eq))))) $ apply-ext ext $ _↔_.right-inverse-of (implicit-extensionality-isomorphism ext) ∘ eq) ⟩ (∃ λ (eq : ∀ p′ μ → ch₁ {p′ = p′} {μ = μ} ≡ ch₂) → let eq′ = implicit-extensionality (Eq.good-ext ext) ∘ eq in ∀ {p′ μ} (p⟶p′ : p [ μ ]⟶ p′) → R (f₁ (μ , p⟶p′ , refl) , f₂ (μ , p⟶p′ , sym (cong (λ ch → proj₁ (ch p′ p⟶p′)) (apply-ext (Eq.good-ext ext) eq′))))) ↝⟨ (∃-cong λ _ → implicit-∀-cong ext $ implicit-∀-cong ext $ ∀-cong ext λ _ → ≡⇒↝ _ $ cong (λ eq → R (f₁ _ , f₂ (_ , _ , sym eq))) $ lemma₃ _) ⟩ (∃ λ (eq : ∀ p′ μ → ch₁ {p′ = p′} {μ = μ} ≡ ch₂) → ∀ {p′ μ} (p⟶p′ : p [ μ ]⟶ p′) → R (f₁ (μ , p⟶p′ , refl) , f₂ (μ , p⟶p′ , sym (cong (λ ch → proj₁ (ch p⟶p′)) (eq p′ μ))))) ↝⟨ Σ-cong (inverse Bijection.implicit-Π↔Π) (λ _ → F.id) ⟩ (∃ λ (eq : ∀ {p′} μ → ch₁ {p′ = p′} {μ = μ} ≡ ch₂) → ∀ {p′ μ} (p⟶p′ : p [ μ ]⟶ p′) → R (f₁ (μ , p⟶p′ , refl) , f₂ (μ , p⟶p′ , sym (cong (λ ch → proj₁ (ch p⟶p′)) (eq μ))))) ↝⟨ Σ-cong (implicit-∀-cong ext $ inverse Bijection.implicit-Π↔Π) (λ _ → F.id) ⟩ (∃ λ (eq : ∀ {p′ μ} → ch₁ {p′ = p′} {μ = μ} ≡ ch₂) → ∀ {p′ μ} (p⟶p′ : p [ μ ]⟶ p′) → R (f₁ (μ , p⟶p′ , refl) , f₂ (μ , p⟶p′ , sym (cong (λ ch → proj₁ (ch p⟶p′)) eq)))) ↝⟨ (∃-cong λ eq → implicit-∀-cong ext $ implicit-∀-cong ext $ ∀-cong ext λ p⟶p′ → ≡⇒↝ _ $ cong (λ eq → R (f₁ _ , f₂ (_ , _ , sym eq))) $ sym $ cong-∘ proj₁ (_$ p⟶p′) (eq {μ = _})) ⟩ (∃ λ (eq : ∀ {p′ μ} → ch₁ {p′ = p′} {μ = μ} ≡ ch₂) → ∀ {p′ μ} (p⟶p′ : p [ μ ]⟶ p′) → R (f₁ (μ , p⟶p′ , refl) , f₂ (μ , p⟶p′ , sym (cong proj₁ $ cong (_$ p⟶p′) eq)))) ↝⟨ Σ-cong (implicit-∀-cong ext $ implicit-∀-cong ext $ inverse $ Eq.extensionality-isomorphism ext) (λ _ → F.id) ⟩ (∃ λ (eq : ∀ {p′ μ} (p⟶p′ : p [ μ ]⟶ p′) → ch₁ p⟶p′ ≡ ch₂ p⟶p′) → ∀ {p′ μ} (p⟶p′ : p [ μ ]⟶ p′) → R (f₁ (μ , p⟶p′ , refl) , f₂ (μ , p⟶p′ , sym (cong proj₁ (eq p⟶p′))))) ↝⟨ inverse implicit-ΠΣ-comm ⟩ (∀ {p′} → ∃ λ (eq : ∀ {μ} (p⟶p′ : p [ μ ]⟶ p′) → ch₁ p⟶p′ ≡ ch₂ p⟶p′) → ∀ {μ} (p⟶p′ : p [ μ ]⟶ p′) → R (f₁ (μ , p⟶p′ , refl) , f₂ (μ , p⟶p′ , sym (cong proj₁ (eq p⟶p′))))) ↝⟨ implicit-∀-cong ext $ inverse implicit-ΠΣ-comm ⟩ (∀ {p′ μ} → ∃ λ (eq : (p⟶p′ : p [ μ ]⟶ p′) → ch₁ p⟶p′ ≡ ch₂ p⟶p′) → ∀ p⟶p′ → R (f₁ (μ , p⟶p′ , refl) , f₂ (μ , p⟶p′ , sym (cong proj₁ (eq p⟶p′))))) ↝⟨ implicit-∀-cong ext $ implicit-∀-cong ext $ inverse ΠΣ-comm ⟩ (∀ {p′ μ} (p⟶p′ : p [ μ ]⟶ p′) → ∃ λ (eq : ch₁ p⟶p′ ≡ ch₂ p⟶p′) → R (f₁ (μ , p⟶p′ , refl) , f₂ (μ , p⟶p′ , sym (cong proj₁ eq)))) ↝⟨ (inverse $ implicit-∀-cong ext $ implicit-∀-cong ext $ ∀-cong ext λ _ → Σ-cong Bijection.Σ-≡,≡↔≡ λ _ → F.id) ⟩ (∀ {p′ μ} (p⟶p′ : p [ μ ]⟶ p′) → let q′₁ , q⟶q′₁ = ch₁ p⟶p′ q′₂ , q⟶q′₂ = ch₂ p⟶p′ in ∃ λ (eq : ∃ λ (q′₁≡q′₂ : q′₁ ≡ q′₂) → subst (q [ μ ]↝_) q′₁≡q′₂ q⟶q′₁ ≡ q⟶q′₂) → R (f₁ (μ , p⟶p′ , refl) , f₂ (μ , p⟶p′ , sym (cong proj₁ (uncurry Σ-≡,≡→≡ eq))))) ↝⟨ (implicit-∀-cong ext $ implicit-∀-cong ext $ ∀-cong ext λ _ → ∃-cong λ eq → ≡⇒↝ _ $ cong (λ eq → R (f₁ _ , f₂ (_ , _ , sym eq))) $ proj₁-Σ-≡,≡→≡ (proj₁ eq) (proj₂ eq)) ⟩ (∀ {p′ μ} (p⟶p′ : p [ μ ]⟶ p′) → let q′₁ , q⟶q′₁ = ch₁ p⟶p′ q′₂ , q⟶q′₂ = ch₂ p⟶p′ in ∃ λ (eq : ∃ λ (q′₁≡q′₂ : q′₁ ≡ q′₂) → subst (q [ μ ]↝_) q′₁≡q′₂ q⟶q′₁ ≡ q⟶q′₂) → R (f₁ (μ , p⟶p′ , refl) , f₂ (μ , p⟶p′ , sym (proj₁ eq)))) ↝⟨ (implicit-∀-cong ext $ implicit-∀-cong ext $ ∀-cong ext λ _ → inverse Σ-assoc) ⟩ (∀ {p′ μ} (p⟶p′ : p [ μ ]⟶ p′) → let q′₁ , q⟶q′₁ = ch₁ p⟶p′ q′₂ , q⟶q′₂ = ch₂ p⟶p′ in ∃ λ (q′₁≡q′₂ : q′₁ ≡ q′₂) → subst (q [ μ ]↝_) q′₁≡q′₂ q⟶q′₁ ≡ q⟶q′₂ × R (f₁ (μ , p⟶p′ , refl) , f₂ (μ , p⟶p′ , sym q′₁≡q′₂))) ↝⟨ (implicit-∀-cong ext $ implicit-∀-cong ext $ ∀-cong ext λ p⟶p′ → ∃-cong λ q′₁≡q′₂ → ∃-cong λ _ → ≡⇒↝ _ $ lemma₄ q′₁≡q′₂) ⟩ (∀ {p′ μ} (p⟶p′ : p [ μ ]⟶ p′) → let q′₁ , q⟶q′₁ = ch₁ p⟶p′ q′₂ , q⟶q′₂ = ch₂ p⟶p′ in ∃ λ (q′₁≡q′₂ : q′₁ ≡ q′₂) → subst (q [ μ ]↝_) q′₁≡q′₂ q⟶q′₁ ≡ q⟶q′₂ × R (subst (X ∘ (p′ ,_)) q′₁≡q′₂ (f₁ (_ , p⟶p′ , refl)) , f₂ (_ , p⟶p′ , refl))) ↔⟨⟩ (∀ {p′ μ} (p⟶p′ : p [ μ ]⟶ p′) → let q′₁ , q⟶q′₁ , p′≤q′₁ = StepC.challenge (s₁ , f₁) p⟶p′ q′₂ , q⟶q′₂ , p′≤q′₂ = StepC.challenge (s₂ , f₂) p⟶p′ in ∃ λ (q′₁≡q′₂ : q′₁ ≡ q′₂) → subst (q [ μ ]↝_) q′₁≡q′₂ q⟶q′₁ ≡ q⟶q′₂ × R (subst (X ∘ (p′ ,_)) q′₁≡q′₂ p′≤q′₁ , p′≤q′₂)) □ where lemma₁ : ∀ {p q} {f g : ∀ {p′ μ} → p [ μ ]⟶ p′ → ∃ (q [ μ ]↝_)} (eq : (λ {p′ μ} → f {p′ = p′} {μ = μ}) ≡ g) {p′ μ} {p⟶p′ : p [ μ ]⟶ p′} → _ lemma₁ {p} {q} {f} {g} eq {p′} {μ} {p⟶p′} = subst (λ ch → ∃ λ μ → ∃ λ (p⟶p′′ : p [ μ ]⟶ p′) → proj₁ (ch p⟶p′′) ≡ proj₁ (f p⟶p′)) eq (μ , p⟶p′ , refl) ≡⟨ push-subst-pair′ {y≡z = eq} _ _ _ ⟩ ( μ , subst₂ (λ { (ch , μ) → ∃ λ (p⟶p′′ : p [ μ ]⟶ p′) → proj₁ (ch p⟶p′′) ≡ proj₁ (f p⟶p′) }) eq (subst-const eq) (p⟶p′ , refl) ) ≡⟨ cong (μ ,_) $ cong (λ eq → subst (λ { (ch , μ) → ∃ λ (p⟶p′′ : p [ μ ]⟶ p′) → proj₁ (ch p⟶p′′) ≡ proj₁ (f p⟶p′) }) eq (p⟶p′ , refl)) $ Σ-≡,≡→≡-subst-const eq refl ⟩ ( μ , subst (λ { (ch , μ) → ∃ λ (p⟶p′′ : p [ μ ]⟶ p′) → proj₁ (ch p⟶p′′) ≡ proj₁ (f p⟶p′) }) (cong₂ _,_ eq refl) (p⟶p′ , refl) ) ≡⟨⟩ ( μ , subst (λ { (ch , μ) → ∃ λ (p⟶p′′ : p [ μ ]⟶ p′) → proj₁ (ch p⟶p′′) ≡ proj₁ (f p⟶p′) }) (cong (_, _) eq) (p⟶p′ , refl) ) ≡⟨ cong (μ ,_) $ sym $ subst-∘ _ _ eq ⟩ ( μ , subst (λ ch → ∃ λ (p⟶p′′ : p [ μ ]⟶ p′) → proj₁ (ch p⟶p′′) ≡ proj₁ (f p⟶p′)) eq (p⟶p′ , refl) ) ≡⟨ cong (μ ,_) $ push-subst-pair′ {y≡z = eq} _ _ _ ⟩ ( μ , p⟶p′ , subst₂ (λ { (ch , p⟶p′′) → proj₁ (ch p⟶p′′) ≡ proj₁ (f p⟶p′) }) eq (subst-const eq) refl ) ≡⟨ cong (λ eq → (_ , p⟶p′ , subst (λ { (ch , p⟶p′′) → proj₁ (ch p⟶p′′) ≡ proj₁ (f p⟶p′) }) eq refl)) $ Σ-≡,≡→≡-subst-const eq refl ⟩ ( μ , p⟶p′ , subst (λ { (ch , p⟶p′′) → proj₁ (ch p⟶p′′) ≡ proj₁ (f p⟶p′) }) (cong (_, _) eq) refl ) ≡⟨ cong (λ eq → (_ , p⟶p′ , eq)) $ sym $ subst-∘ _ _ eq ⟩ ( μ , p⟶p′ , subst (λ ch → proj₁ (ch p⟶p′) ≡ proj₁ (f p⟶p′)) eq refl ) ≡⟨ cong (λ eq → (_ , p⟶p′ , eq)) $ subst-∘ _ _ eq ⟩ ( μ , p⟶p′ , subst (_≡ proj₁ (f p⟶p′)) (cong (λ ch → proj₁ (ch p⟶p′)) eq) refl ) ≡⟨ cong (λ eq → (_ , p⟶p′ , subst (_≡ _) eq refl)) $ sym $ sym-sym (cong (λ ch → proj₁ (ch p⟶p′)) eq) ⟩ ( μ , p⟶p′ , subst (_≡ proj₁ (f p⟶p′)) (sym $ sym $ cong (λ ch → proj₁ (ch p⟶p′)) eq) refl ) ≡⟨ cong (λ eq → (_ , p⟶p′ , eq)) $ subst-trans (sym $ cong (λ ch → proj₁ (ch p⟶p′)) eq) ⟩∎ ( μ , p⟶p′ , sym (cong (λ ch → proj₁ (ch p⟶p′)) eq) ) ∎ lemma₂ : ∀ {p q} {f g : ∀ {p′ μ} → p [ μ ]⟶ p′ → ∃ (q [ μ ]↝_)} (eq : ∀ p′ → (λ {μ} → f {p′ = p′} {μ = μ}) ≡ g) {p′ μ} {p⟶p′ : p [ μ ]⟶ p′} → _ lemma₂ {p} {q} {f} {g} eq {p′} {μ} {p⟶p′} = cong (λ ch → proj₁ (ch p⟶p′)) (_↔_.to (implicit-extensionality-isomorphism ext) eq) ≡⟨⟩ cong (λ ch → proj₁ (ch p⟶p′)) (implicit-extensionality (Eq.good-ext ext) eq) ≡⟨ cong-∘ _ _ (apply-ext (Eq.good-ext ext) eq) ⟩∎ cong (λ ch → proj₁ (ch p′ p⟶p′)) (apply-ext (Eq.good-ext ext) eq) ∎ lemma₃ : ∀ {p q} {f g : ∀ {p′ μ} → p [ μ ]⟶ p′ → ∃ (q [ μ ]↝_)} (eq : ∀ p′ μ → f {p′ = p′} {μ = μ} ≡ g) {p′ μ p⟶p′} → _ lemma₃ {p} {q} {f} {g} eq {p′} {μ} {p⟶p′} = cong (λ (ch : ∀ _ {μ} → _) → proj₁ (ch p′ {μ = μ} p⟶p′)) (apply-ext (Eq.good-ext ext) (implicit-extensionality (Eq.good-ext ext) ∘ eq)) ≡⟨⟩ cong (λ ch → proj₁ (ch p′ p⟶p′)) (apply-ext (Eq.good-ext ext) (cong (λ f {x} → f x) ∘ (apply-ext (Eq.good-ext ext) ∘ eq))) ≡⟨ cong (cong (λ ch → proj₁ (ch p′ p⟶p′))) $ sym $ Eq.cong-post-∘-good-ext {h = λ f {x} → f x} ext ext (apply-ext (Eq.good-ext ext) ∘ eq) ⟩ cong (λ ch → proj₁ (ch p′ p⟶p′)) (cong (λ f x {y} → f x y) (apply-ext (Eq.good-ext ext) (apply-ext (Eq.good-ext ext) ∘ eq))) ≡⟨ cong-∘ _ _ (apply-ext (Eq.good-ext ext) (apply-ext (Eq.good-ext ext) ∘ eq)) ⟩ cong (λ ch → proj₁ (ch p′ μ p⟶p′)) (apply-ext (Eq.good-ext ext) (apply-ext (Eq.good-ext ext) ∘ eq)) ≡⟨ sym $ cong-∘ _ _ (apply-ext (Eq.good-ext ext) (apply-ext (Eq.good-ext ext) ∘ eq)) ⟩ cong (λ ch → proj₁ (ch μ p⟶p′)) (cong (_$ p′) (apply-ext (Eq.good-ext ext) (apply-ext (Eq.good-ext ext) ∘ eq))) ≡⟨ cong (cong (λ ch → proj₁ (ch μ p⟶p′))) $ Eq.cong-good-ext ext _ ⟩ cong (λ ch → proj₁ (ch μ p⟶p′)) (apply-ext (Eq.good-ext ext) (eq p′)) ≡⟨ sym $ cong-∘ _ _ (apply-ext (Eq.good-ext ext) (eq p′)) ⟩ cong (λ ch → proj₁ (ch p⟶p′)) (cong (_$ μ) (apply-ext (Eq.good-ext ext) (eq p′))) ≡⟨ cong (cong (λ ch → proj₁ (ch p⟶p′))) $ Eq.cong-good-ext ext _ ⟩∎ cong (λ ch → proj₁ (ch p⟶p′)) (eq p′ μ) ∎ lemma₄ : ∀ {p′ μ} {p⟶p′ : p [ μ ]⟶ p′} (q′₁≡q′₂ : proj₁ (ch₁ p⟶p′) ≡ proj₁ (ch₂ p⟶p′)) → R (f₁ (μ , p⟶p′ , refl) , f₂ (μ , p⟶p′ , sym q′₁≡q′₂)) ≡ R (subst (X ∘ (p′ ,_)) q′₁≡q′₂ (f₁ (_ , p⟶p′ , refl)) , f₂ (_ , p⟶p′ , refl)) lemma₄ {p′} {μ} {p⟶p′} q′₁≡q′₂ = R (f₁ (μ , p⟶p′ , refl) , f₂ (μ , p⟶p′ , sym q′₁≡q′₂)) ≡⟨ cong (R ∘ (f₁ _ ,_)) $ lemma′ q′₁≡q′₂ ⟩ R (f₁ (μ , p⟶p′ , refl) , subst (X ∘ (p′ ,_)) (sym q′₁≡q′₂) (f₂ (_ , p⟶p′ , refl))) ≡⟨ lemma″ q′₁≡q′₂ ⟩∎ R (subst (X ∘ (p′ ,_)) q′₁≡q′₂ (f₁ (_ , p⟶p′ , refl)) , f₂ (_ , p⟶p′ , refl)) ∎ where lemma′ : ∀ {q′₁} (q′₁≡q′₂ : q′₁ ≡ proj₁ (ch₂ p⟶p′)) → f₂ (μ , p⟶p′ , sym q′₁≡q′₂) ≡ subst (X ∘ (p′ ,_)) (sym q′₁≡q′₂) (f₂ (_ , p⟶p′ , refl)) lemma′ refl = refl lemma″ : ∀ {q′₂ x} (q′₁≡q′₂ : proj₁ (ch₁ p⟶p′) ≡ q′₂) → R (f₁ (μ , p⟶p′ , refl) , subst (X ∘ (p′ ,_)) (sym q′₁≡q′₂) x) ≡ R (subst (X ∘ (p′ ,_)) q′₁≡q′₂ (f₁ (_ , p⟶p′ , refl)) , x) lemma″ refl = refl
[STATEMENT] lemma last_H: assumes "enabled Start \<omega>" "hit_C \<omega>" shows "before_C {last_H \<omega>} \<omega>" "last_H \<omega> \<in> H" [PROOF STATE] proof (prove) goal (1 subgoal): 1. before_C {last_H \<omega>} \<omega> &&& last_H \<omega> \<in> H [PROOF STEP] by (metis before_C_single hit_C_imp_before_C last_H_eq Int_iff assms)+
------------------------------------------------------------------------------ -- Totality properties for Tree using induction instance ------------------------------------------------------------------------------ {-# OPTIONS --exact-split #-} {-# OPTIONS --no-sized-types #-} {-# OPTIONS --no-universe-polymorphism #-} {-# OPTIONS --without-K #-} module FOT.FOTC.Program.Mirror.Tree.Induction.Instances.TotalityATP where open import FOTC.Base open import FOTC.Base.List open import FOTC.Data.List open import FOTC.Program.Mirror.Forest.TotalityATP open import FOTC.Program.Mirror.Mirror open import FOTC.Program.Mirror.Type ------------------------------------------------------------------------------ mirror-Tree-ind-instance : (∀ d {ts} → Forest ts → Forest (map mirror ts) → Tree (mirror · node d ts)) → Forest (map mirror []) → (∀ {t ts} → Tree t → Tree (mirror · t) → Forest ts → Forest (map mirror ts) → Forest (map mirror (t ∷ ts))) → ∀ {t} → Tree t → Tree (mirror · t) mirror-Tree-ind-instance = Tree-mutual-ind postulate mirror-Tree : ∀ {t} → Tree t → Tree (mirror · t) {-# ATP prove mirror-Tree mirror-Tree-ind-instance reverse-Forest #-}
[GOAL] X : Type ?u.7 inst✝² : TopologicalSpace X s : Set X inst✝¹ : T0Space ↑s inst✝ : SecondCountableTopology ↑s ⊢ HasCountableSeparatingOn X IsOpen s [PROOFSTEP] suffices HasCountableSeparatingOn s IsOpen univ from .of_subtype fun _ ↦ isOpen_induced_iff.1 [GOAL] X : Type ?u.7 inst✝² : TopologicalSpace X s : Set X inst✝¹ : T0Space ↑s inst✝ : SecondCountableTopology ↑s ⊢ HasCountableSeparatingOn (↑s) IsOpen univ [PROOFSTEP] refine ⟨⟨countableBasis s, countable_countableBasis _, fun _ ↦ isOpen_of_mem_countableBasis, fun x _ y _ h ↦ ?_⟩⟩ [GOAL] X : Type ?u.7 inst✝² : TopologicalSpace X s : Set X inst✝¹ : T0Space ↑s inst✝ : SecondCountableTopology ↑s x : ↑s x✝¹ : x ∈ univ y : ↑s x✝ : y ∈ univ h : ∀ (s_1 : Set ↑s), s_1 ∈ countableBasis ↑s → (x ∈ s_1 ↔ y ∈ s_1) ⊢ x = y [PROOFSTEP] exact ((isBasis_countableBasis _).inseparable_iff.2 h).eq
#include <boost/asio/windows/stream_handle.hpp>
------------------------------------------------------------------------ -- The Agda standard library -- -- Properties satisfied by join semilattices ------------------------------------------------------------------------ {-# OPTIONS --without-K --safe #-} open import Relation.Binary.Lattice module Relation.Binary.Properties.JoinSemilattice {c ℓ₁ ℓ₂} (J : JoinSemilattice c ℓ₁ ℓ₂) where open JoinSemilattice J import Algebra as Alg import Algebra.Structures as Alg import Algebra.FunctionProperties as P; open P _≈_ open import Data.Product open import Function using (_∘_; flip) open import Relation.Binary open import Relation.Binary.Properties.Poset poset import Relation.Binary.Reasoning.PartialOrder as PoR -- The join operation is monotonic. ∨-monotonic : _∨_ Preserves₂ _≤_ ⟶ _≤_ ⟶ _≤_ ∨-monotonic {x} {y} {u} {v} x≤y u≤v = let _ , _ , least = supremum x u y≤y∨v , v≤y∨v , _ = supremum y v in least (y ∨ v) (trans x≤y y≤y∨v) (trans u≤v v≤y∨v) ∨-cong : _∨_ Preserves₂ _≈_ ⟶ _≈_ ⟶ _≈_ ∨-cong x≈y u≈v = antisym (∨-monotonic (reflexive x≈y) (reflexive u≈v)) (∨-monotonic (reflexive (Eq.sym x≈y)) (reflexive (Eq.sym u≈v))) -- The join operation is commutative, associative and idempotent. ∨-comm : Commutative _∨_ ∨-comm x y = let x≤x∨y , y≤x∨y , least = supremum x y y≤y∨x , x≤y∨x , least′ = supremum y x in antisym (least (y ∨ x) x≤y∨x y≤y∨x) (least′ (x ∨ y) y≤x∨y x≤x∨y) ∨-assoc : Associative _∨_ ∨-assoc x y z = let x∨y≤[x∨y]∨z , z≤[x∨y]∨z , least = supremum (x ∨ y) z x≤x∨[y∨z] , y∨z≤x∨[y∨z] , least′ = supremum x (y ∨ z) y≤y∨z , z≤y∨z , _ = supremum y z x≤x∨y , y≤x∨y , _ = supremum x y in antisym (least (x ∨ (y ∨ z)) (∨-monotonic refl y≤y∨z) (trans z≤y∨z y∨z≤x∨[y∨z])) (least′ ((x ∨ y) ∨ z) (trans x≤x∨y x∨y≤[x∨y]∨z) (∨-monotonic y≤x∨y refl)) ∨-idempotent : Idempotent _∨_ ∨-idempotent x = let x≤x∨x , _ , least = supremum x x in antisym (least x refl refl) x≤x∨x x≤y⇒x∨y≈y : ∀ {x y} → x ≤ y → x ∨ y ≈ y x≤y⇒x∨y≈y {x} {y} x≤y = antisym (begin x ∨ y ≤⟨ ∨-monotonic x≤y refl ⟩ y ∨ y ≈⟨ ∨-idempotent _ ⟩ y ∎) (y≤x∨y _ _) where open PoR poset -- Every order-theoretic semilattice can be turned into an algebraic one. isAlgSemilattice : Alg.IsSemilattice _≈_ _∨_ isAlgSemilattice = record { isBand = record { isSemigroup = record { isMagma = record { isEquivalence = isEquivalence ; ∙-cong = ∨-cong } ; assoc = ∨-assoc } ; idem = ∨-idempotent } ; comm = ∨-comm } algSemilattice : Alg.Semilattice c ℓ₁ algSemilattice = record { isSemilattice = isAlgSemilattice } -- The dual construction is a meet semilattice. dualIsMeetSemilattice : IsMeetSemilattice _≈_ (flip _≤_) _∨_ dualIsMeetSemilattice = record { isPartialOrder = invIsPartialOrder ; infimum = supremum } dualMeetSemilattice : MeetSemilattice c ℓ₁ ℓ₂ dualMeetSemilattice = record { _∧_ = _∨_ ; isMeetSemilattice = dualIsMeetSemilattice }
State Before: α : Type u_1 M : Type u_2 inst✝ : CommMonoid M f : α → M s : Finset (Option α) ⊢ ∏ x in ↑eraseNone s, f x = ∏ x in s, Option.elim' 1 f x State After: no goals Tactic: classical calc (∏ x in eraseNone s, f x) = ∏ x in (eraseNone s).map Embedding.some, Option.elim' 1 f x := (prod_map (eraseNone s) Embedding.some <| Option.elim' 1 f).symm _ = ∏ x in s.erase none, Option.elim' 1 f x := by rw [map_some_eraseNone] _ = ∏ x in s, Option.elim' 1 f x := prod_erase _ rfl State Before: α : Type u_1 M : Type u_2 inst✝ : CommMonoid M f : α → M s : Finset (Option α) ⊢ ∏ x in ↑eraseNone s, f x = ∏ x in s, Option.elim' 1 f x State After: no goals Tactic: calc (∏ x in eraseNone s, f x) = ∏ x in (eraseNone s).map Embedding.some, Option.elim' 1 f x := (prod_map (eraseNone s) Embedding.some <| Option.elim' 1 f).symm _ = ∏ x in s.erase none, Option.elim' 1 f x := by rw [map_some_eraseNone] _ = ∏ x in s, Option.elim' 1 f x := prod_erase _ rfl State Before: α : Type u_1 M : Type u_2 inst✝ : CommMonoid M f : α → M s : Finset (Option α) ⊢ ∏ x in map Embedding.some (↑eraseNone s), Option.elim' 1 f x = ∏ x in erase s none, Option.elim' 1 f x State After: no goals Tactic: rw [map_some_eraseNone]
lemma in_closed_iff_infdist_zero: assumes "closed A" "A \<noteq> {}" shows "x \<in> A \<longleftrightarrow> infdist x A = 0"
(* * Copyright 2014, NICTA * * This software may be distributed and modified according to the terms of * the GNU General Public License version 2. Note that NO WARRANTY is provided. * See "LICENSE_GPLv2.txt" for details. * * @TAG(NICTA_GPL) *) chapter {* RPC Receive *} (*<*) theory RPCTo imports "../../tools/c-parser/CTranslation" "../../tools/autocorres/AutoCorres" begin (* THIS THEORY IS GENERATED. DO NOT EDIT. *) (* ucast is type-polymorphic, but often appears in a visually indistinguishable form in proofs. * These abbreviations help you identify which type signature you're looking at. These * abbreviations need to exist outside the locale in order to be used in output. *) abbreviation "ucast_32_to_32 \<equiv> ucast :: word32 \<Rightarrow> word32" abbreviation "ucast_s32_to_32 \<equiv> ucast :: sword32 \<Rightarrow> word32" abbreviation "ucast_32_to_s32 \<equiv> ucast :: word32 \<Rightarrow> sword32" abbreviation "ucast_s32_to_s32 \<equiv> ucast :: sword32 \<Rightarrow> sword32" (* As above for scast. *) abbreviation "scast_32_to_32 \<equiv> scast :: word32 \<Rightarrow> word32" abbreviation "scast_s32_to_32 \<equiv> scast :: sword32 \<Rightarrow> word32" abbreviation "scast_32_to_s32 \<equiv> scast :: word32 \<Rightarrow> sword32" abbreviation "scast_s32_to_s32 \<equiv> scast :: sword32 \<Rightarrow> sword32" declare [[allow_underscore_idents=true]] install_C_file "RPCTo.c" (* Use non-determinism instead of the standard option monad type stregthening and do not heap * abstract seL4_SetMR. *) autocorres [ts_rules = nondet, no_heap_abs = seL4_SetMR] "RPCTo.c" context RPCTo begin (* Repeated constants from C. *) abbreviation "seL4_MsgMaxLength \<equiv> 120" definition seL4_SetMR_lifted' :: "int \<Rightarrow> word32 \<Rightarrow> lifted_globals \<Rightarrow> (unit \<times> lifted_globals) set \<times> bool" where "seL4_SetMR_lifted' i val \<equiv> do ret' \<leftarrow> seL4_GetIPCBuffer'; guard (\<lambda>s. i < seL4_MsgMaxLength); guard (\<lambda>s. 0 \<le> i); modify (\<lambda>s. s \<lparr>heap_seL4_IPCBuffer__C := (heap_seL4_IPCBuffer__C s)(ret' := msg_C_update ( \<lambda>a. Arrays.update a (nat i) val) (heap_seL4_IPCBuffer__C s ret') ) \<rparr>) od" end locale RPCTo_glue = RPCTo + assumes seL4_SetMR_axiom: "exec_concrete lift_global_heap (seL4_SetMR' i val) = seL4_SetMR_lifted' i val" assumes RPCTo_echo_int_wp: "\<lbrace>\<lambda>s0'. \<forall>r1'. P2' r1' s0'\<rbrace> RPCTo_echo_int' i3' \<lbrace>P2'\<rbrace>!" assumes RPCTo_echo_parameter_wp: "\<lbrace>\<lambda>s4'. \<forall>r5'. P6' r5' s4'\<rbrace> RPCTo_echo_parameter' pin7' pout8' \<lbrace>P6'\<rbrace>!" assumes RPCTo_echo_char_wp: "\<lbrace>\<lambda>s9'. \<forall>r10'. P11' r10' s9'\<rbrace> RPCTo_echo_char' i12' \<lbrace>P11'\<rbrace>!" assumes RPCTo_increment_char_wp: "\<lbrace>\<lambda>s13'. \<forall>r14'. P15' r14' s13'\<rbrace> RPCTo_increment_char' x16' \<lbrace>P15'\<rbrace>!" assumes RPCTo_increment_parameter_wp: "\<lbrace>\<lambda>s17'. \<forall>r18'. P19' r18' s17'\<rbrace> RPCTo_increment_parameter' x20' \<lbrace>P19'\<rbrace>!" assumes RPCTo_increment_64_wp: "\<lbrace>\<lambda>s21'. \<forall>r22'. P23' r22' s21'\<rbrace> RPCTo_increment_64' x24' \<lbrace>P23'\<rbrace>!" assumes swi_safe_to_ignore[simplified, simp]: "asm_semantics_ok_to_ignore TYPE(nat) true (''swi '' @ x)" begin definition globals_frame_intact :: "lifted_globals \<Rightarrow> bool" where "globals_frame_intact s \<equiv> is_valid_seL4_IPCBuffer__C'ptr s (Ptr (scast seL4_GlobalsFrame))" definition ipc_buffer_valid :: "lifted_globals \<Rightarrow> bool" where "ipc_buffer_valid s \<equiv> is_valid_seL4_IPCBuffer__C s (heap_seL4_IPCBuffer__C'ptr s (Ptr (scast seL4_GlobalsFrame)))" lemma abort_wp[wp]: "\<lbrace>\<lambda>_. False\<rbrace> abort' \<lbrace>P\<rbrace>!" by (rule validNF_false_pre) definition setMR :: "lifted_globals \<Rightarrow> nat \<Rightarrow> word32 \<Rightarrow> lifted_globals" where "setMR s i v \<equiv> s\<lparr>heap_seL4_IPCBuffer__C := (heap_seL4_IPCBuffer__C s) (heap_seL4_IPCBuffer__C'ptr s (Ptr (scast seL4_GlobalsFrame)) := msg_C_update (\<lambda>a. Arrays.update a i v) (heap_seL4_IPCBuffer__C s (heap_seL4_IPCBuffer__C'ptr s (Ptr (scast seL4_GlobalsFrame)))))\<rparr>" definition setMRs :: "lifted_globals \<Rightarrow> word32 \<Rightarrow> word32 \<Rightarrow> word32 \<Rightarrow> word32 \<Rightarrow> lifted_globals" where "setMRs s mr0 mr1 mr2 mr3 \<equiv> setMR (setMR (setMR (setMR s 0 mr0) 1 mr1) 2 mr2) 3 mr3" lemma seL4_GetIPCBuffer_wp': "\<forall>s'. \<lbrace>\<lambda>s. globals_frame_intact s \<and> s = s'\<rbrace> seL4_GetIPCBuffer' \<lbrace>\<lambda>r s. r = heap_seL4_IPCBuffer__C'ptr s (Ptr (scast seL4_GlobalsFrame)) \<and> s = s'\<rbrace>!" apply (rule allI) apply (simp add:seL4_GetIPCBuffer'_def) apply wp apply (clarsimp simp:globals_frame_intact_def) done lemmas seL4_GetIPCBuffer_wp[wp_unsafe] = seL4_GetIPCBuffer_wp'[THEN validNF_make_schematic_post, simplified] lemma seL4_SetMR_wp[wp_unsafe]: notes seL4_SetMR_axiom[simp] shows "\<lbrace>\<lambda>s. globals_frame_intact s \<and> ipc_buffer_valid s \<and> i \<ge> 0 \<and> i < seL4_MsgMaxLength \<and> (\<forall>x. P x (setMR s (nat i) v))\<rbrace> exec_concrete lift_global_heap (seL4_SetMR' i v) \<lbrace>P\<rbrace>!" apply (simp add:seL4_SetMR_lifted'_def) apply (wp seL4_GetIPCBuffer_wp) apply (simp add:setMR_def globals_frame_intact_def ipc_buffer_valid_def) done lemma seL4_GetMR_wp[wp_unsafe]: "\<lbrace>\<lambda>s. \<forall>x. i \<ge> 0 \<and> i < seL4_MsgMaxLength \<and> globals_frame_intact s \<and> ipc_buffer_valid s \<and> P x s\<rbrace> seL4_GetMR' i \<lbrace>P\<rbrace>!" apply (simp add:seL4_GetMR'_def) apply (wp seL4_GetIPCBuffer_wp) apply (simp add:globals_frame_intact_def ipc_buffer_valid_def) done lemma seL4_Wait_wp[wp_unsafe]: "\<lbrace>\<lambda>s. globals_frame_intact s \<and> ipc_buffer_valid s \<and> (\<forall>x v0 v1 v2 v3. P x (setMRs s v0 v1 v2 v3))\<rbrace> seL4_Wait' cap NULL \<lbrace>P\<rbrace>!" apply (simp add:seL4_Wait'_def) apply (wp seL4_SetMR_wp) apply (simp add:globals_frame_intact_def ipc_buffer_valid_def setMRs_def setMR_def) done lemma seL4_ReplyWait_wp[wp_unsafe]: "\<lbrace>\<lambda>s. globals_frame_intact s \<and> ipc_buffer_valid s \<and> (\<forall>x v0 v1 v2 v3. P x (setMRs s v0 v1 v2 v3))\<rbrace> seL4_ReplyWait' cap info NULL \<lbrace>P\<rbrace>!" apply (simp add:seL4_ReplyWait'_def seL4_GetMR'_def) apply (wp seL4_SetMR_wp seL4_GetIPCBuffer_wp) apply (simp add:globals_frame_intact_def ipc_buffer_valid_def setMRs_def setMR_def) done definition thread_count :: word32 where "thread_count \<equiv> 2" (* Various definitions used in assumptions on the TLS region. *) definition tls_ptr :: "lifted_globals \<Rightarrow> camkes_tls_t_C ptr" where "tls_ptr s \<equiv> Ptr (ptr_val (heap_seL4_IPCBuffer__C'ptr s (Ptr (scast_s32_to_32 seL4_GlobalsFrame))) && 0xFFFFF000)" definition tls :: "lifted_globals \<Rightarrow> camkes_tls_t_C" where "tls s \<equiv> heap_camkes_tls_t_C s (tls_ptr s)" definition tls_valid :: "lifted_globals \<Rightarrow> bool" where "tls_valid s \<equiv> is_valid_camkes_tls_t_C s (tls_ptr s)" lemma camkes_get_tls_wp': "\<forall>s'. \<lbrace>\<lambda>s. tls_valid s \<and> globals_frame_intact s \<and> s = s'\<rbrace> camkes_get_tls' \<lbrace>\<lambda>r s. s = s' \<and> r = tls_ptr s\<rbrace>!" apply (rule allI) apply (simp add:camkes_get_tls'_def seL4_GetIPCBuffer'_def tls_valid_def) apply wp apply (clarsimp simp:globals_frame_intact_def tls_ptr_def) done lemmas camkes_get_tls'_wp[wp] = camkes_get_tls_wp'[THEN validNF_make_schematic_post, simplified] (*>*) text {* The generated definitions and lemmas in this chapter have been formed from the same procedure specification provided in the previous chapter. Again, to give some context to the proofs below, the generated receiving code for the \code{echo\_int} method is given here. \clisting{to-echo-int.c} The glue code receiving an RPC invocation from another component unmarshals arguments and then invokes the user's interface implementation. To show the safety of this glue code we assume that the user's implementation being invoked does not modify the state of the system. For example, for the \code{echo\_int} method, we assume the following property. @{term "\<lbrace>\<lambda>s. \<forall>r. P r s\<rbrace> RPCTo_echo_int' i \<lbrace>P\<rbrace>!"} The unbound variables in the above statement, @{term P} and @{term i}, unify with any suitably typed expression to allow use of the assumption in all contexts. This property states that the user's implementation, \code{RPCTo\_echo\_int}, only manipulates local variables and does not write to any global memory. The property we ultimately need from the user's implementation is weaker than this; that the function does not invalidate the TLS memory. In future the assumption above will be reduced to this, but for now we assume this stronger property. *} text {* For each thread-local variable, a function to retrieve a pointer to the relevant memory for the current thread is emitted. For each of these we generate a proof that it does not modify the state. This is uninteresting, in and of itself, but useful for reasoning about glue code that calls these. *} text {* \newpage *} lemma get_echo_int_i_nf: "\<forall>s25'. \<lbrace>\<lambda>s26'. globals_frame_intact s26' \<and> ipc_buffer_valid s26' \<and> tls_valid s26' \<and> thread_index_C (tls s26') \<in> {1..thread_count} \<and> is_valid_w32 s26' (Ptr (symbol_table ''echo_int_i_1'')) \<and> is_valid_w32 s26' (Ptr (symbol_table ''echo_int_i_2'')) \<and> s26' = s25'\<rbrace> get_echo_int_i' \<lbrace>\<lambda>r27' s26'. r27' \<in> {Ptr (symbol_table ''echo_int_i_1''), Ptr (symbol_table ''echo_int_i_2'')} \<and> s26' = s25'\<rbrace>!" apply (rule allI) apply (simp add:get_echo_int_i'_def) apply (wp seL4_GetIPCBuffer_wp) apply (clarsimp simp:thread_count_def tls_valid_def tls_def) apply unat_arith done (*<*) lemmas get_echo_int_i_wp[wp_unsafe] = get_echo_int_i_nf[THEN validNF_make_schematic_post, simplified] definition update_global_w32 :: "char list \<Rightarrow> word32 \<Rightarrow> lifted_globals \<Rightarrow> lifted_globals" where "update_global_w32 symbol v s \<equiv> heap_w32_update (\<lambda>c. c(Ptr (symbol_table symbol) := (ucast v))) s" lemma get_echo_parameter_pin_nf: "\<forall>s28'. \<lbrace>\<lambda>s29'. globals_frame_intact s29' \<and> ipc_buffer_valid s29' \<and> tls_valid s29' \<and> thread_index_C (tls s29') \<in> {1..thread_count} \<and> is_valid_w32 s29' (Ptr (symbol_table ''echo_parameter_pin_1'')) \<and> is_valid_w32 s29' (Ptr (symbol_table ''echo_parameter_pin_2'')) \<and> s29' = s28'\<rbrace> get_echo_parameter_pin' \<lbrace>\<lambda>r30' s29'. r30' \<in> {Ptr (symbol_table ''echo_parameter_pin_1''), Ptr (symbol_table ''echo_parameter_pin_2'')} \<and> s29' = s28'\<rbrace>!" apply (rule allI) apply (simp add:get_echo_parameter_pin'_def) apply (wp seL4_GetIPCBuffer_wp) apply (clarsimp simp:thread_count_def tls_valid_def tls_def) apply unat_arith done lemmas get_echo_parameter_pin_wp[wp_unsafe] = get_echo_parameter_pin_nf[THEN validNF_make_schematic_post, simplified] lemma get_echo_parameter_pout_nf: "\<forall>s31'. \<lbrace>\<lambda>s32'. globals_frame_intact s32' \<and> ipc_buffer_valid s32' \<and> tls_valid s32' \<and> thread_index_C (tls s32') \<in> {1..thread_count} \<and> is_valid_w32 s32' (Ptr (symbol_table ''echo_parameter_pout_1'')) \<and> is_valid_w32 s32' (Ptr (symbol_table ''echo_parameter_pout_2'')) \<and> s32' = s31'\<rbrace> get_echo_parameter_pout' \<lbrace>\<lambda>r33' s32'. r33' \<in> {Ptr (symbol_table ''echo_parameter_pout_1''), Ptr (symbol_table ''echo_parameter_pout_2'') } \<and> s32' = s31'\<rbrace>!" apply (rule allI) apply (simp add:get_echo_parameter_pout'_def) apply (wp seL4_GetIPCBuffer_wp) apply (clarsimp simp:thread_count_def tls_valid_def tls_def) apply unat_arith done lemmas get_echo_parameter_pout_wp[wp_unsafe] = get_echo_parameter_pout_nf[THEN validNF_make_schematic_post, simplified] lemma get_echo_char_i_nf: "\<forall>s34'. \<lbrace>\<lambda>s35'. globals_frame_intact s35' \<and> ipc_buffer_valid s35' \<and> tls_valid s35' \<and> thread_index_C (tls s35') \<in> {1..thread_count} \<and> is_valid_w8 s35' (Ptr (symbol_table ''echo_char_i_1'')) \<and> is_valid_w8 s35' (Ptr (symbol_table ''echo_char_i_2'')) \<and> s35' = s34'\<rbrace> get_echo_char_i' \<lbrace>\<lambda>r36' s35'. r36' \<in> {Ptr (symbol_table ''echo_char_i_1''), Ptr (symbol_table ''echo_char_i_2'')} \<and> s35' = s34'\<rbrace>!" apply (rule allI) apply (simp add:get_echo_char_i'_def) apply (wp seL4_GetIPCBuffer_wp) apply (clarsimp simp:thread_count_def tls_valid_def tls_def) apply unat_arith done lemmas get_echo_char_i_wp[wp_unsafe] = get_echo_char_i_nf[THEN validNF_make_schematic_post, simplified] definition update_global_w8 :: "char list \<Rightarrow> word32 \<Rightarrow> lifted_globals \<Rightarrow> lifted_globals" where "update_global_w8 symbol v s \<equiv> heap_w8_update (\<lambda>c. c(Ptr (symbol_table symbol) := (ucast v))) s" lemma get_increment_char_x_nf: "\<forall>s37'. \<lbrace>\<lambda>s38'. globals_frame_intact s38' \<and> ipc_buffer_valid s38' \<and> tls_valid s38' \<and> thread_index_C (tls s38') \<in> {1..thread_count} \<and> is_valid_w8 s38' (Ptr (symbol_table ''increment_char_x_1'')) \<and> is_valid_w8 s38' (Ptr (symbol_table ''increment_char_x_2'')) \<and> s38' = s37'\<rbrace> get_increment_char_x' \<lbrace>\<lambda>r39' s38'. r39' \<in> {Ptr (symbol_table ''increment_char_x_1''), Ptr (symbol_table ''increment_char_x_2'')} \<and> s38' = s37'\<rbrace>!" apply (rule allI) apply (simp add:get_increment_char_x'_def) apply (wp seL4_GetIPCBuffer_wp) apply (clarsimp simp:thread_count_def tls_valid_def tls_def) apply unat_arith done lemmas get_increment_char_x_wp[wp_unsafe] = get_increment_char_x_nf[THEN validNF_make_schematic_post, simplified] lemma get_increment_parameter_x_nf: "\<forall>s40'. \<lbrace>\<lambda>s41'. globals_frame_intact s41' \<and> ipc_buffer_valid s41' \<and> tls_valid s41' \<and> thread_index_C (tls s41') \<in> {1..thread_count} \<and> is_valid_w32 s41' (Ptr (symbol_table ''increment_parameter_x_1'')) \<and> is_valid_w32 s41' (Ptr (symbol_table ''increment_parameter_x_2'')) \<and> s41' = s40'\<rbrace> get_increment_parameter_x' \<lbrace>\<lambda>r42' s41'. r42' \<in> {Ptr (symbol_table ''increment_parameter_x_1''), Ptr (symbol_table ''increment_parameter_x_2'')} \<and> s41' = s40'\<rbrace>!" apply (rule allI) apply (simp add:get_increment_parameter_x'_def) apply (wp seL4_GetIPCBuffer_wp) apply (clarsimp simp:thread_count_def tls_valid_def tls_def) apply unat_arith done lemmas get_increment_parameter_x_wp[wp_unsafe] = get_increment_parameter_x_nf[THEN validNF_make_schematic_post, simplified] lemma get_increment_64_x_nf: "\<forall>s43'. \<lbrace>\<lambda>s44'. globals_frame_intact s44' \<and> ipc_buffer_valid s44' \<and> tls_valid s44' \<and> thread_index_C (tls s44') \<in> {1..thread_count} \<and> is_valid_w64 s44' (Ptr (symbol_table ''increment_64_x_1'')) \<and> is_valid_w64 s44' (Ptr (symbol_table ''increment_64_x_2'')) \<and> s44' = s43'\<rbrace> get_increment_64_x' \<lbrace>\<lambda>r45' s44'. r45' \<in> {Ptr (symbol_table ''increment_64_x_1''), Ptr (symbol_table ''increment_64_x_2'')} \<and> s44' = s43'\<rbrace>!" apply (rule allI) apply (simp add:get_increment_64_x'_def) apply (wp seL4_GetIPCBuffer_wp) apply (clarsimp simp:thread_count_def tls_valid_def tls_def) apply unat_arith done lemmas get_increment_64_x_wp[wp_unsafe] = get_increment_64_x_nf[THEN validNF_make_schematic_post, simplified] definition update_global_w64 :: "char list \<Rightarrow> word32 \<Rightarrow> lifted_globals \<Rightarrow> lifted_globals" where "update_global_w64 symbol v s \<equiv> heap_w64_update (\<lambda>c. c(Ptr (symbol_table symbol) := (ucast v))) s" definition update_global_w64_high :: "char list \<Rightarrow> word32 \<Rightarrow> lifted_globals \<Rightarrow> lifted_globals" where "update_global_w64_high symbol high s \<equiv> heap_w64_update (\<lambda>c. c(Ptr (symbol_table symbol) := (heap_w64 s (Ptr (symbol_table symbol))) || (ucast high << 32))) s" (*>*) text {* For each method in the procedure we generate a function for specifically handling receiving of a call to that method. A top-level dispatch function is generated that selects the appropriate handler to invoke after receiving an RPC invocation. The handler function for the first method is the code given at the start of this chapter. We generate proofs that the handler functions do not fail, as given below. *} lemma echo_int_internal_wp[wp_unsafe]: notes seL4_GetMR_wp[wp] seL4_SetMR_wp[wp] shows "\<lbrace>\<lambda>s46'. globals_frame_intact s46' \<and> ipc_buffer_valid s46' \<and> tls_valid s46' \<and> thread_index_C (tls s46') \<in> {1..thread_count} \<and> is_valid_w32 s46' (Ptr (symbol_table ''echo_int_i_1'')) \<and> is_valid_w32 s46' (Ptr (symbol_table ''echo_int_i_2'')) \<and> (\<forall>x r47' i_in_value . \<forall> i_symbol \<in> {''echo_int_i_1'', ''echo_int_i_2''}. P48' x (setMR (update_global_w32 i_symbol i_in_value s46') 0 r47') )\<rbrace> echo_int_internal' \<lbrace>P48'\<rbrace>!" apply (simp add:echo_int_internal'_def) apply wp apply (wp RPCTo_echo_int_wp)+ apply (wp get_echo_int_i_wp)+ apply (clarsimp simp:globals_frame_intact_def ipc_buffer_valid_def tls_valid_def tls_def tls_ptr_def thread_count_def setMR_def ucast_id update_global_w32_def) apply force? done lemma echo_parameter_internal_wp[wp_unsafe]: notes seL4_GetMR_wp[wp] seL4_SetMR_wp[wp] shows "\<lbrace>\<lambda>s49'. globals_frame_intact s49' \<and> ipc_buffer_valid s49' \<and> tls_valid s49' \<and> thread_index_C (tls s49') \<in> {1..thread_count} \<and> is_valid_w32 s49' (Ptr (symbol_table ''echo_parameter_pin_1'')) \<and> is_valid_w32 s49' (Ptr (symbol_table ''echo_parameter_pin_2'')) \<and> is_valid_w32 s49' (Ptr (symbol_table ''echo_parameter_pout_1'')) \<and> is_valid_w32 s49' (Ptr (symbol_table ''echo_parameter_pout_2'')) \<and> (\<forall>x r50' pin_in_value pout_out_value . \<forall> pin_symbol \<in> {''echo_parameter_pin_1'', ''echo_parameter_pin_2''}. \<forall> pout_symbol \<in> {''echo_parameter_pout_1'', ''echo_parameter_pout_2''}. P51' x (setMR (setMR (update_global_w32 pin_symbol pin_in_value s49') 0 r50') 1 pout_out_value))\<rbrace> echo_parameter_internal' \<lbrace>P51'\<rbrace>!" apply (simp add:echo_parameter_internal'_def) apply wp apply (wp RPCTo_echo_parameter_wp)+ apply (wp get_echo_parameter_pout_wp) apply (wp get_echo_parameter_pin_wp)+ apply (clarsimp simp:globals_frame_intact_def ipc_buffer_valid_def tls_valid_def tls_def tls_ptr_def thread_count_def setMR_def ucast_id update_global_w32_def) apply force? done lemma echo_char_internal_wp[wp_unsafe]: notes seL4_GetMR_wp[wp] seL4_SetMR_wp[wp] shows "\<lbrace>\<lambda>s52'. globals_frame_intact s52' \<and> ipc_buffer_valid s52' \<and> tls_valid s52' \<and> thread_index_C (tls s52') \<in> {1..thread_count} \<and> is_valid_w8 s52' (Ptr (symbol_table ''echo_char_i_1'')) \<and> is_valid_w8 s52' (Ptr (symbol_table ''echo_char_i_2'')) \<and> (\<forall>x r53' i_in_value . \<forall> i_symbol \<in> {''echo_char_i_1'', ''echo_char_i_2''}. P54' x (setMR (update_global_w8 i_symbol i_in_value s52') 0 r53') )\<rbrace> echo_char_internal' \<lbrace>P54'\<rbrace>!" apply (simp add:echo_char_internal'_def) apply wp apply (wp RPCTo_echo_char_wp)+ apply (wp get_echo_char_i_wp)+ apply (clarsimp simp:globals_frame_intact_def ipc_buffer_valid_def tls_valid_def tls_def tls_ptr_def thread_count_def setMR_def ucast_id update_global_w8_def) apply force? done lemma increment_char_internal_wp[wp_unsafe]: notes seL4_GetMR_wp[wp] seL4_SetMR_wp[wp] shows "\<lbrace>\<lambda>s55'. globals_frame_intact s55' \<and> ipc_buffer_valid s55' \<and> tls_valid s55' \<and> thread_index_C (tls s55') \<in> {1..thread_count} \<and> is_valid_w8 s55' (Ptr (symbol_table ''increment_char_x_1'')) \<and> is_valid_w8 s55' (Ptr (symbol_table ''increment_char_x_2'')) \<and> (\<forall>x x_in_value x_out_value . \<forall> x_symbol \<in> {''increment_char_x_1'', ''increment_char_x_2''}. P57' x (setMR (update_global_w8 x_symbol x_in_value s55') 0 x_out_value) )\<rbrace> increment_char_internal' \<lbrace>P57'\<rbrace>!" apply (simp add:increment_char_internal'_def) apply wp apply (wp RPCTo_increment_char_wp)+ apply (wp get_increment_char_x_wp)+ apply (clarsimp simp:globals_frame_intact_def ipc_buffer_valid_def tls_valid_def tls_def tls_ptr_def thread_count_def setMR_def ucast_id update_global_w8_def) apply force? done lemma increment_parameter_internal_wp[wp_unsafe]: notes seL4_GetMR_wp[wp] seL4_SetMR_wp[wp] shows "\<lbrace>\<lambda>s58'. globals_frame_intact s58' \<and> ipc_buffer_valid s58' \<and> tls_valid s58' \<and> thread_index_C (tls s58') \<in> {1..thread_count} \<and> is_valid_w32 s58' (Ptr (symbol_table ''increment_parameter_x_1'')) \<and> is_valid_w32 s58' (Ptr (symbol_table ''increment_parameter_x_2'')) \<and> (\<forall>x x_in_value x_out_value . \<forall> x_symbol \<in> {''increment_parameter_x_1'', ''increment_parameter_x_2''}. P60' x (setMR (update_global_w32 x_symbol x_in_value s58') 0 x_out_value) )\<rbrace> increment_parameter_internal' \<lbrace>P60'\<rbrace>!" apply (simp add:increment_parameter_internal'_def) apply wp apply (wp RPCTo_increment_parameter_wp)+ apply (wp get_increment_parameter_x_wp)+ apply (clarsimp simp:globals_frame_intact_def ipc_buffer_valid_def tls_valid_def tls_def tls_ptr_def thread_count_def setMR_def ucast_id update_global_w32_def) apply force? done lemma increment_64_internal_wp[wp_unsafe]: notes seL4_GetMR_wp[wp] seL4_SetMR_wp[wp] shows "\<lbrace>\<lambda>s61'. globals_frame_intact s61' \<and> ipc_buffer_valid s61' \<and> tls_valid s61' \<and> thread_index_C (tls s61') \<in> {1..thread_count} \<and> is_valid_w64 s61' (Ptr (symbol_table ''increment_64_x_1'')) \<and> is_valid_w64 s61' (Ptr (symbol_table ''increment_64_x_2'')) \<and> (\<forall>x x_in_value x_in_value_high x_out_value x_out_value_high . \<forall> x_symbol \<in> {''increment_64_x_1'', ''increment_64_x_2''}. P63' x (setMR (setMR (update_global_w64_high x_symbol x_in_value_high (update_global_w64 x_symbol x_in_value s61') ) 0 x_out_value) 1 x_out_value_high))\<rbrace> increment_64_internal' \<lbrace>P63'\<rbrace>!" apply (simp add:increment_64_internal'_def) apply wp apply (wp RPCTo_increment_64_wp)+ apply (wp get_increment_64_x_wp)+ apply (clarsimp simp:globals_frame_intact_def ipc_buffer_valid_def tls_valid_def tls_def tls_ptr_def thread_count_def setMR_def ucast_id update_global_w64_def update_global_w64_high_def) apply force? done text {* \newpage With proofs that the handler functions do not fail, the proof of the same for the top-level dispatch function can be generated by composing these. Note that we accumulate the pre- and post-conditions from the leaf functions. *} lemma RPCTo_run_internal_wp[wp_unsafe]: notes seL4_SetMR_axiom[simp] seL4_SetMR_wp[wp] seL4_GetMR_wp[wp] shows "\<lbrace>\<lambda>s64'. globals_frame_intact s64' \<and> tls_valid s64' \<and> thread_index_C (tls s64') \<in> {1..thread_count} \<and> is_valid_w32 s64' (Ptr (symbol_table ''echo_int_i_1'')) \<and> is_valid_w32 s64' (Ptr (symbol_table ''echo_int_i_2'')) \<and> is_valid_w32 s64' (Ptr (symbol_table ''echo_parameter_pin_1'')) \<and> is_valid_w32 s64' (Ptr (symbol_table ''echo_parameter_pin_2'')) \<and> is_valid_w32 s64' (Ptr (symbol_table ''echo_parameter_pout_1'')) \<and> is_valid_w32 s64' (Ptr (symbol_table ''echo_parameter_pout_2'')) \<and> is_valid_w8 s64' (Ptr (symbol_table ''echo_char_i_1'')) \<and> is_valid_w8 s64' (Ptr (symbol_table ''echo_char_i_2'')) \<and> is_valid_w8 s64' (Ptr (symbol_table ''increment_char_x_1'')) \<and> is_valid_w8 s64' (Ptr (symbol_table ''increment_char_x_2'')) \<and> is_valid_w32 s64' (Ptr (symbol_table ''increment_parameter_x_1'')) \<and> is_valid_w32 s64' (Ptr (symbol_table ''increment_parameter_x_2'')) \<and> is_valid_w64 s64' (Ptr (symbol_table ''increment_64_x_1'')) \<and> is_valid_w64 s64' (Ptr (symbol_table ''increment_64_x_2'')) \<and> ipc_buffer_valid s64'\<rbrace> RPCTo__run_internal' first65' info66' \<lbrace>\<lambda>_ s64'. globals_frame_intact s64' \<and> tls_valid s64' \<and> thread_index_C (tls s64') \<in> {1..thread_count} \<and> is_valid_w32 s64' (Ptr (symbol_table ''echo_int_i_1'')) \<and> is_valid_w32 s64' (Ptr (symbol_table ''echo_int_i_2'')) \<and> is_valid_w32 s64' (Ptr (symbol_table ''echo_parameter_pin_1'')) \<and> is_valid_w32 s64' (Ptr (symbol_table ''echo_parameter_pin_2'')) \<and> is_valid_w32 s64' (Ptr (symbol_table ''echo_parameter_pout_1'')) \<and> is_valid_w32 s64' (Ptr (symbol_table ''echo_parameter_pout_2'')) \<and> is_valid_w8 s64' (Ptr (symbol_table ''echo_char_i_1'')) \<and> is_valid_w8 s64' (Ptr (symbol_table ''echo_char_i_2'')) \<and> is_valid_w8 s64' (Ptr (symbol_table ''increment_char_x_1'')) \<and> is_valid_w8 s64' (Ptr (symbol_table ''increment_char_x_2'')) \<and> is_valid_w32 s64' (Ptr (symbol_table ''increment_parameter_x_1'')) \<and> is_valid_w32 s64' (Ptr (symbol_table ''increment_parameter_x_2'')) \<and> is_valid_w64 s64' (Ptr (symbol_table ''increment_64_x_1'')) \<and> is_valid_w64 s64' (Ptr (symbol_table ''increment_64_x_2'')) \<and> ipc_buffer_valid s64'\<rbrace>!" apply (simp add:RPCTo__run_internal'_def) apply wp apply (wp seL4_ReplyWait_wp) apply (simp add:seL4_MessageInfo_new'_def) apply wp apply (wp echo_int_internal_wp) apply (wp seL4_ReplyWait_wp) apply (simp add:seL4_MessageInfo_new'_def) apply wp apply (wp echo_parameter_internal_wp) apply (wp seL4_ReplyWait_wp) apply (simp add:seL4_MessageInfo_new'_def) apply wp apply (wp echo_char_internal_wp) apply (wp seL4_ReplyWait_wp) apply (simp add:seL4_MessageInfo_new'_def) apply wp apply (wp increment_char_internal_wp) apply (wp seL4_ReplyWait_wp) apply (simp add:seL4_MessageInfo_new'_def) apply wp apply (wp increment_parameter_internal_wp) apply (wp seL4_ReplyWait_wp) apply (simp add:seL4_MessageInfo_new'_def) apply wp apply (wp increment_64_internal_wp) apply (wp seL4_Wait_wp)+ apply (clarsimp simp:globals_frame_intact_def ipc_buffer_valid_def tls_valid_def tls_def tls_ptr_def ucast_id seL4_GetIPCBuffer'_def thread_count_def setMR_def setMRs_def update_global_w32_def update_global_w8_def update_global_w64_def update_global_w64_high_def) done (*<*) end end (*>*)
lemma convex_explicit: fixes S :: "'a::real_vector set" shows "convex S \<longleftrightarrow> (\<forall>t u. finite t \<and> t \<subseteq> S \<and> (\<forall>x\<in>t. 0 \<le> u x) \<and> sum u t = 1 \<longrightarrow> sum (\<lambda>x. u x *\<^sub>R x) t \<in> S)"
from __future__ import print_function import os import argparse import torch from util.data_util import PartNormalDataset from model.DGCNN_PAConv_vote import PAConv import numpy as np from torch.utils.data import DataLoader from util.util import to_categorical, compute_overall_iou, load_cfg_from_cfg_file, merge_cfg_from_list, IOStream from tqdm import tqdm from collections import defaultdict from torch.autograd import Variable import torch.nn.functional as F classes_str =['aero','bag','cap','car','chair','ear','guitar','knife','lamp','lapt','moto','mug','Pistol','rock','stake','table'] class PointcloudScale(object): def __init__(self, scale_low=2. / 3., scale_high=3. / 2.): self.scale_low = scale_low self.scale_high = scale_high def __call__(self, pc): bsize = pc.size()[0] for i in range(bsize): xyz = np.random.uniform(low=self.scale_low, high=self.scale_high, size=[3]) pc[i, :, 0:3] = torch.mul(pc[i, :, 0:3], torch.from_numpy(xyz).float().cuda()) return pc def get_parser(): parser = argparse.ArgumentParser(description='3D Shape Part Segmentation') parser.add_argument('--config', type=str, default='dgcnn_paconv_test.yaml', help='config file') parser.add_argument('opts', help='see config/dgcnn_paconv_test.yaml for all options', default=None, nargs=argparse.REMAINDER) args = parser.parse_args() assert args.config is not None cfg = load_cfg_from_cfg_file(args.config) if args.opts is not None: cfg = merge_cfg_from_list(cfg, args.opts) cfg['manual_seed'] = cfg.get('manual_seed', 0) cfg['workers'] = cfg.get('workers', 6) return cfg def _init_(): if not os.path.exists('checkpoints'): os.makedirs('checkpoints') if not os.path.exists('checkpoints/' + args.exp_name): os.makedirs('checkpoints/' + args.exp_name) # backup the running files: os.system('cp eval_voting.py checkpoints' + '/' + args.exp_name + '/' + 'eval_voting.py.backup') def test(args, io): # Try to load models num_part = 50 device = torch.device("cuda" if args.cuda else "cpu") model = PAConv(args, num_part).to(device) io.cprint(str(model)) from collections import OrderedDict state_dict = torch.load("checkpoints/%s/best_insiou_model.pth" % args.exp_name, map_location=torch.device('cpu'))['model'] new_state_dict = OrderedDict() for layer in state_dict: new_state_dict[layer.replace('module.', '')] = state_dict[layer] model.load_state_dict(new_state_dict) # Dataloader test_data = PartNormalDataset(npoints=2048, split='test', normalize=False) print("The number of test data is:%d", len(test_data)) test_loader = DataLoader(test_data, batch_size=args.test_batch_size, shuffle=False, num_workers=args.workers, drop_last=False) NUM_PEPEAT = 100 NUM_VOTE = 10 global_Class_mIoU, global_Inst_mIoU = 0, 0 global_total_per_cat_iou = np.zeros((16)).astype(np.float32) num_part = 50 num_classes = 16 pointscale = PointcloudScale(scale_low=0.87, scale_high=1.15) model.eval() for i in range(NUM_PEPEAT): metrics = defaultdict(lambda: list()) shape_ious = [] total_per_cat_iou = np.zeros((16)).astype(np.float32) total_per_cat_seen = np.zeros((16)).astype(np.int32) for batch_id, (points, label, target, norm_plt) in tqdm(enumerate(test_loader), total=len(test_loader), smoothing=0.9): batch_size, num_point, _ = points.size() points, label, target, norm_plt = Variable(points.float()), Variable(label.long()), Variable( target.long()), Variable(norm_plt.float()) # points = points.transpose(2, 1) norm_plt = norm_plt.transpose(2, 1) points, label, target, norm_plt = points.cuda(non_blocking=True), label.squeeze().cuda( non_blocking=True), target.cuda(non_blocking=True), norm_plt.cuda(non_blocking=True) seg_pred = 0 new_points = Variable(torch.zeros(points.size()[0], points.size()[1], points.size()[2]).cuda(), volatile=True) for v in range(NUM_VOTE): if v > 0: new_points.data = pointscale(points.data) with torch.no_grad(): seg_pred += F.softmax( model(points.contiguous().transpose(2, 1), new_points.contiguous().transpose(2, 1), norm_plt, to_categorical(label, num_classes)), dim=2) # xyz,x: only scale feature input seg_pred /= NUM_VOTE # instance iou without considering the class average at each batch_size: batch_shapeious = compute_overall_iou(seg_pred, target, num_part) # [b] shape_ious += batch_shapeious # iou +=, equals to .append # per category iou at each batch_size: for shape_idx in range(seg_pred.size(0)): # sample_idx cur_gt_label = label[shape_idx] # label[sample_idx] total_per_cat_iou[cur_gt_label] += batch_shapeious[shape_idx] total_per_cat_seen[cur_gt_label] += 1 # accuracy: seg_pred = seg_pred.contiguous().view(-1, num_part) target = target.view(-1, 1)[:, 0] pred_choice = seg_pred.data.max(1)[1] correct = pred_choice.eq(target.data).cpu().sum() metrics['accuracy'].append(correct.item() / (batch_size * num_point)) metrics['shape_avg_iou'] = np.mean(shape_ious) for cat_idx in range(16): if total_per_cat_seen[cat_idx] > 0: total_per_cat_iou[cat_idx] = total_per_cat_iou[cat_idx] / total_per_cat_seen[cat_idx] print('\n------ Repeat %3d ------' % (i + 1)) # First we need to calculate the iou of each class and the avg class iou: class_iou = 0 for cat_idx in range(16): class_iou += total_per_cat_iou[cat_idx] io.cprint(classes_str[cat_idx] + ' iou: ' + str(total_per_cat_iou[cat_idx])) # print the iou of each class avg_class_iou = class_iou / 16 outstr = 'Test :: test class mIOU: %f, test instance mIOU: %f' % (avg_class_iou, metrics['shape_avg_iou']) io.cprint(outstr) if avg_class_iou > global_Class_mIoU: global_Class_mIoU = avg_class_iou global_total_per_cat_iou = total_per_cat_iou if metrics['shape_avg_iou'] > global_Inst_mIoU: global_Inst_mIoU = metrics['shape_avg_iou'] # final avg print: final_out_str = 'Best voting result :: test class mIOU: %f, test instance mIOU: %f' % (global_Class_mIoU, global_Inst_mIoU) io.cprint(final_out_str) # final per cat print: for cat_idx in range(16): io.cprint(classes_str[cat_idx] + ' iou: ' + str(global_total_per_cat_iou[cat_idx])) # print iou of each class if __name__ == "__main__": args = get_parser() _init_() io = IOStream('checkpoints/' + args.exp_name + '/%s_voting.log' % (args.exp_name)) io.cprint(str(args)) args.cuda = not args.no_cuda and torch.cuda.is_available() torch.manual_seed(args.manual_seed) if args.cuda: io.cprint( 'Using GPU : ' + str(torch.cuda.current_device()) + ' from ' + str(torch.cuda.device_count()) + ' devices') torch.cuda.manual_seed(args.manual_seed) else: io.cprint('Using CPU') test(args, io)
#ifndef __ESTIMATE_INC_ #define __ESTIMATE__INC_ #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> double getLogLikelyhood(gsl_matrix *cinverse, double det_cmatrix, gsl_matrix *xmodel, gsl_vector *trainingvector, gsl_vector *thetas, gsl_matrix *h_matrix, int nmodel_points, int nthetas, int nparams, int nregression_fns, void (*makeHVector)(gsl_vector *, gsl_vector*, int)); #endif
{-# LANGUAGE CPP, OverloadedStrings, TypeOperators #-} module Main where import Control.Exception import qualified Data.Array.Accelerate as A import qualified Data.Array.Accelerate.Interpreter as ALI import Data.Array.Accelerate.Math.Hilbert import Data.Array.Accelerate.Math.Qtfd import Data.Array.Accelerate.Math.WindowFunc import Data.Attoparsec.Text import ParseArgs import ParseFile import System.Directory #ifdef ACCELERATE_LLVM_NATIVE_BACKEND import qualified Data.Array.Accelerate.LLVM.Native as ALN #endif #ifdef ACCELERATE_LLVM_PTX_BACKEND import qualified Data.Array.Accelerate.LLVM.PTX as ALP #endif import Data.Array.Accelerate.Array.Sugar as S import qualified Data.ByteString.Builder as BB import Data.Complex import qualified Data.Double.Conversion.Convertable as DC import Data.List import Data.Monoid import qualified Data.Text as T import qualified Data.Text.IO as TI import qualified Data.Vector as V import GHC.Float import Math.Gamma import System.IO main :: IO () main = do args <- opts makeQTFDAll args -- | Transform data to text(using Float conversion. It is much faster) and write it to file. writeData :: Handle -- ^ output file -> [Float] -- ^ Data to write -> Int -- ^ number of element -> Int -- ^ elements per row -> IO () writeData _ [] _ _ = return () writeData file (x:xs) w n = do TI.hPutStr file $ DC.toPrecision 5 x <> " " if (n `mod` w) == 0 then do TI.hPutStr file "\n" writeData file xs w (n + 1) else writeData file xs w (n + 1) makeString :: Handle -> [Float] -- ^ Data to write -> Int -- ^ number of element -> Int -- ^ elements per row -> BB.Builder -> IO () makeString _ [] _ _ _ = return () makeString file (x:xs) w n acc = if (n `mod` w) == 0 then BB.hPutBuilder file (acc <> DC.toPrecision 5 x <> " " <> "\n") >> makeString file xs w (n+1) "" else makeString file xs w (n+1) (acc <> DC.toPrecision 5 x <> " ") -- | make Pseudo Wigner-Ville transform to all files in a directory. makeQTFDAll :: Opts -> IO () makeQTFDAll opts = do let path = getPath opts nosAVGflag = subAVGflag opts files <- listDirectory path setCurrentDirectory path let fFiles = filter (isSuffixOf ".txt") files sAVGflag = A.constant $ not nosAVGflag case opts of (OptsPWV _ dev wlen wfun _) -> do if (even wlen) then error "Window length maust be odd !" else do let window = makeWindow wfun (A.unit $ A.constant wlen) :: A.Acc (A.Array A.DIM1 Float) mapM_ (makePWV dev window sAVGflag) fFiles (OptsWV path dev nosAVGflag) -> mapM_ (makeWV dev sAVGflag) fFiles (OptsCW path dev sigma uWindow uWindowFunc nWindow nWindowFunc normalise nosAVGflag) -> do if (even uWindow || even nWindow) then error "Window length maust be odd !" else let uWindowArray = makeWindow uWindowFunc (A.unit $ A.constant uWindow) :: A.Acc (A.Array A.DIM1 Float) nWindowArray = makeWindow nWindowFunc (A.unit $ A.constant nWindow) :: A.Acc (A.Array A.DIM1 Float) bothRectangular = uWindowFunc == Rect && nWindowFunc == Rect in mapM_ (makeCW dev sAVGflag sigma uWindowArray nWindowArray normalise bothRectangular) fFiles (OptsBJ path dev alpha uWindow uWindowFunc nWindow nWindowFunc nosAVGflag) -> do if (even uWindow || even nWindow) then error "Window length maust be odd !" else let uWindowArray = makeWindow uWindowFunc (A.unit $ A.constant uWindow) :: A.Acc (A.Array A.DIM1 Float) nWindowArray = makeWindow nWindowFunc (A.unit $ A.constant nWindow) :: A.Acc (A.Array A.DIM1 Float) bothRectangular = uWindowFunc == Rect && nWindowFunc == Rect in mapM_ (makeBJ dev sAVGflag alpha uWindowArray nWindowArray bothRectangular) fFiles (OptsEMBD path dev alpha beta uWindow uWindowFunc nWindow nWindowFunc normalise nosAVGflag) -> do if (even uWindow || even nWindow) then error "Window length maust be odd !" else let gammas = makeGammaArray beta uWindow uWindowArray = makeWindow uWindowFunc (A.unit $ A.constant uWindow) :: A.Acc (A.Array A.DIM1 Float) nWindowArray = makeWindow nWindowFunc (A.unit $ A.constant nWindow) :: A.Acc (A.Array A.DIM1 Float) bothRectangular = uWindowFunc == Rect && nWindowFunc == Rect in mapM_ (makeEMBD dev sAVGflag alpha gammas uWindowArray nWindowArray bothRectangular normalise) fFiles return () makeCW :: CalcDev -- ^ Calculation device - CPU or GPU -> A.Exp Bool -- ^ Apply subtraction of the mean value from all elements in a column. -> Float -- ^ sigma -> A.Acc (A.Array A.DIM1 Float) -- ^ Smoothing window in frequensy-domain. Length must be odd. -> A.Acc (A.Array A.DIM1 Float) -- ^ Smoothing window in time-domain. Length must be odd. -> Bool -- ^ if the core array should be normalised -> Bool -- ^ if Both windows are rectangular -> FilePath -- ^ Name of file with data. -> IO () makeCW dev sAVGflag sigma uWindowArray nWindowArray normalise bothRect file = do putStrLn $ "processing " ++ file ++ "..." text <- TI.readFile file let parseRes = parseOnly parseFile text case parseRes of (Left errStr) -> error $ errStr (Right dataF) -> mapM_ (startCW dev file sAVGflag sigma uWindowArray nWindowArray normalise bothRect) dataF makeBJ :: CalcDev -- ^ Calculation device - CPU or GPU -> A.Exp Bool -- ^ Apply subtraction of the mean value from all elements in a column. -> Float -- ^ sigma -> A.Acc (A.Array A.DIM1 Float) -- ^ Smoothing window in frequensy-domain. Length must be odd. -> A.Acc (A.Array A.DIM1 Float) -- ^ Smoothing window in time-domain. Length must be odd. -> Bool -- ^ if Both windows are rectangular -> FilePath -- ^ Name of file with data. -> IO () makeBJ dev sAVGflag alpha uWindowArray nWindowArray bothRect file = do putStrLn $ "processing " ++ file ++ "..." text <- TI.readFile file let parseRes = parseOnly parseFile text case parseRes of (Left errStr) -> error $ errStr (Right dataF) -> mapM_ (startBJ dev file sAVGflag alpha uWindowArray nWindowArray bothRect) dataF -- | Make Pseudo Wigner-Ville transform to all columns in the given file makePWV :: CalcDev -- ^ Calculation device - CPU or GPU -> A.Acc (A.Array A.DIM1 Float) -- ^ Smoothing window in time-domain. Length must be odd. -> A.Exp Bool -- ^ Apply subtraction of the mean value from all elements in a column. -> FilePath -- ^ Name of file with data. -> IO () makePWV dev window sAVGflag file = do putStrLn $ "processing " ++ file ++ "..." text <- TI.readFile file let parseRes = parseOnly parseFile text case parseRes of (Left errStr) -> error $ errStr (Right dataF) -> mapM_ (startPWV dev window file sAVGflag) dataF --makeEMBD dev alpha gammas uWindowArray nWindowArray bothRectangular normalise makeEMBD :: CalcDev -- ^ Calculation device - CPU or GPU -> A.Exp Bool -- ^ Apply subtraction of the mean value from all elements in a column. -> Float -- ^ alpha -> [Float] -- ^ gammas -> A.Acc (A.Array A.DIM1 Float) -- ^ Smoothing window in frequensy-domain. Length must be odd. -> A.Acc (A.Array A.DIM1 Float) -- ^ Smoothing window in time-domain. Length must be odd. -> Bool -- ^ if the core array should be normalised -> Bool -- ^ if Both windows are rectangular -> FilePath -- ^ Name of file with data. -> IO () makeEMBD dev sAVGflag alpha gammas uWindowArray nWindowArray normalise bothRect file = do putStrLn $ "processing " ++ file ++ "..." text <- TI.readFile file let parseRes = parseOnly parseFile text case parseRes of (Left errStr) -> error $ errStr (Right dataF) -> mapM_ (startEMBD dev file sAVGflag alpha gammas uWindowArray nWindowArray normalise bothRect) dataF -- | Make Pseudo Wigner-Ville transform to the given column. -- At first it makes subtraction of average value (if supAVGflag) and applies hilbert transform to make analytic signal. After that it applies Pseudo-Wigner transftorm -- and save data to file with startPWV :: CalcDev -- ^ Calculation device - CPU or GPU -> A.Acc (A.Array A.DIM1 Float) -- ^ Smoothing window in time-domain. Length must be odd. -> FilePath -- ^ Name of file with data. -> A.Exp Bool -- ^ Apply subtraction of the mean value from all elements in a column. -> (T.Text,[Float]) -- ^ Name of column and parsed data from column -> IO () startPWV dev window oldName sAVGflag (column_name,dataF) = do let newFName = oldName ++ "-" ++ T.unpack column_name ++ ".txt" putStr $ " Creating file " ++ newFName ++ " ..." let leng = length dataF pData = A.fromList (A.Z A.:. leng) dataF appPWV = (pWignerVille window) . hilbert . supAVG sAVGflag processed = case dev of #ifdef ACCELERATE_LLVM_NATIVE_BACKEND CPU -> ALN.run1 appPWV pData #endif #ifdef ACCELERATE_LLVM_PTX_BACKEND GPU -> ALP.run1 appPWV pData #endif CPU -> ALI.run1 appPWV pData GPU -> error "Compiled without GPU support" pList = S.toList $! processed file <- openFile newFName WriteMode onException (writeData file pList leng 1) (removeFile newFName) hClose file putStrLn "Done !" -- | Make Wigner-Ville transform to all columns in the given file makeWV :: CalcDev -- ^ Calculation device - CPU or GPU -> A.Exp Bool -- ^ Apply subtraction of the mean value from all elements in a column. -> FilePath -- ^ Name of file with data. -> IO () makeWV dev sAVGflag file = do putStrLn $ "processing " ++ file ++ "..." text <- TI.readFile file let parseRes = parseOnly parseFile text case parseRes of (Left errStr) -> error $ errStr (Right dataF) -> mapM_ (startWV dev file sAVGflag) dataF -- | Make Wigner-Ville transform to the given column. -- At first it makes subtraction of average value (if supAVGflag) and applies hilbert transform to make analytic signal. After that it applies Pseudo-Wigner transftorm -- and save data to file with startWV :: CalcDev -- ^ Calculation device - CPU or GPU -> FilePath -- ^ Name of file with data. -> A.Exp Bool -- ^ Apply subtraction of the mean value from all elements in a column. -> (T.Text,[Float]) -- ^ Name of column and parsed data from column -> IO () startWV dev oldName sAVGflag (column_name,dataF) = do let newFName = oldName ++ "-" ++ T.unpack column_name ++ ".txt" putStr $ " Creating file " ++ newFName ++ " ..." let leng = length dataF pData = A.fromList (A.Z A.:. leng) dataF appWV = wignerVilleNew . hilbert . supAVG sAVGflag appWVGPU = wignerVille . hilbert . supAVG sAVGflag processed = case dev of #ifdef ACCELERATE_LLVM_NATIVE_BACKEND CPU -> ALN.run1 appWV pData #endif #ifdef ACCELERATE_LLVM_PTX_BACKEND GPU -> ALP.run1 appWV pData #endif CPU -> ALI.run1 appWV pData GPU -> error "Compiled without GPU support" pList = S.toList $ processed file <- openFile newFName WriteMode hSetBinaryMode file True >> hSetBuffering file LineBuffering -- let resultBsBuilder = makeString pList leng 1 "" onException (makeString file pList leng 1 "") (removeFile newFName) >> hFlush file hClose file putStrLn "Done !" startCW :: CalcDev -- ^ Calculation device - CPU or GPU -> FilePath -- ^ Name of file with data. -> A.Exp Bool -- ^ Apply subtraction of the mean value from all elements in a column. -> Float -- ^ Sigma -> A.Acc (A.Array A.DIM1 Float) -- ^ Smoothing window in frequensy-domain. Length must be odd. -> A.Acc (A.Array A.DIM1 Float) -- ^ Smoothing window in time-domain. Length must be odd. -> Bool -- ^ if the core array should be normalised -> Bool -- ^ if Both windows are rectangular -> (T.Text,[Float]) -- ^ Name of column and parsed data from column -> IO () startCW dev oldName sAVGflag sigma uWindowArray nWindowArray normalise bothRect (column_name,dataF) = do let newFName = oldName ++ "-" ++ T.unpack column_name ++ ".txt" putStr $ " Creating file " ++ newFName ++ " ..." let leng = length dataF uWindow = A.length uWindowArray nWindow = A.length nWindowArray mWindowArrays = if bothRect then Nothing else Just (uWindowArray,nWindowArray) pData = A.fromList (A.Z A.:. leng) dataF appCW = (choiWilliams (A.constant sigma) mWindowArrays uWindow nWindow normalise) . hilbert . supAVG sAVGflag processed = case dev of #ifdef ACCELERATE_LLVM_NATIVE_BACKEND CPU -> ALN.run1 appCW pData #endif #ifdef ACCELERATE_LLVM_PTX_BACKEND GPU -> ALP.run1 appCW pData #endif CPU -> ALI.run1 appCW pData GPU -> error "Compiled without GPU support" pList = S.toList $ processed file <- openFile newFName WriteMode onException (writeData file pList leng 1) (removeFile newFName) hClose file putStrLn "Done !" startBJ :: CalcDev -- ^ Calculation device - CPU or GPU -> FilePath -- ^ Name of file with data. -> A.Exp Bool -- ^ Apply subtraction of the mean value from all elements in a column. -> Float -- ^ Sigma -> A.Acc (A.Array A.DIM1 Float) -- ^ Smoothing window in frequensy-domain. Length must be odd. -> A.Acc (A.Array A.DIM1 Float) -- ^ Smoothing window in time-domain. Length must be odd. -> Bool -- ^ if Both windows are rectangular -> (T.Text,[Float]) -- ^ Name of column and parsed data from column -> IO () startBJ dev oldName sAVGflag alpha uWindowArray nWindowArray bothRect (column_name,dataF) = do let newFName = oldName ++ "-" ++ T.unpack column_name ++ ".txt" putStr $ " Creating file " ++ newFName ++ " ..." let leng = length dataF uWindow = A.length uWindowArray nWindow = A.length nWindowArray mWindowArrays = if bothRect then Nothing else Just (uWindowArray,nWindowArray) pData = A.fromList (A.Z A.:. leng) dataF appCW = (bornJordan (A.constant alpha) mWindowArrays uWindow nWindow) . hilbert . supAVG sAVGflag processed = case dev of #ifdef ACCELERATE_LLVM_NATIVE_BACKEND CPU -> ALN.run1 appCW pData #endif #ifdef ACCELERATE_LLVM_PTX_BACKEND GPU -> ALP.run1 appCW pData #endif CPU -> ALI.run1 appCW pData GPU -> error "Compiled without GPU support" pList = S.toList $ processed file <- openFile newFName WriteMode onException (writeData file pList leng 1) (removeFile newFName) hClose file putStrLn "Done !" startEMBD :: CalcDev -- ^ Calculation device - CPU or GPU -> FilePath -- ^ Name of file with data. -> A.Exp Bool -- ^ Apply subtraction of the mean value from all elements in a column. -> Float -- ^ Alpha -> [Float] -- ^ Gammas -> A.Acc (A.Array A.DIM1 Float) -- ^ Smoothing window in frequensy-domain. Length must be odd. -> A.Acc (A.Array A.DIM1 Float) -- ^ Smoothing window in time-domain. Length must be odd. -> Bool -- ^ if the core array should be normalised -> Bool -- ^ if Both windows are rectangular -> (T.Text,[Float]) -- ^ Name of column and parsed data from column -> IO () startEMBD dev oldName sAVGflag alpha gammas uWindowArray nWindowArray normalise bothRect (column_name,dataF) = do let newFName = oldName ++ "-" ++ T.unpack column_name ++ ".txt" putStr $ " Creating file " ++ newFName ++ " ..." let leng = length dataF uWindow = A.length uWindowArray nWindow = A.length nWindowArray gammasArr = A.use $ A.fromList (A.Z A.:. (length gammas)) gammas mWindowArrays = if bothRect then Nothing else Just (uWindowArray,nWindowArray) pData = A.fromList (A.Z A.:. leng) dataF appEMBD = (eModifiedB (A.constant alpha) gammasArr mWindowArrays uWindow nWindow normalise) . hilbert . supAVG sAVGflag processed = case dev of #ifdef ACCELERATE_LLVM_NATIVE_BACKEND CPU -> ALN.run1 appEMBD pData #endif #ifdef ACCELERATE_LLVM_PTX_BACKEND GPU -> ALP.run1 appEMBD pData #endif CPU -> ALI.run1 appEMBD pData GPU -> error "Compiled without GPU support" pList = S.toList $ processed file <- openFile newFName WriteMode onException (writeData file pList leng 1) (removeFile newFName) hClose file putStrLn "Done !" -- | Subtraction of average value from all elements of column supAVG :: A.Exp Bool -> A.Acc (Array DIM1 Float) -> A.Acc (Array DIM1 Float) supAVG flag arr = A.acond flag (A.map (\x -> x - avg) arr) arr where leng = A.length arr avg = (A.the $ A.sum arr)/(A.fromIntegral leng) makeGammaArray :: Float -> Int -> [Float] makeGammaArray beta wLength = let dwLength = fromIntegral wLength :: Float v = [(-0.5), ((-0.5) + 1.0/dwLength)..0.5] s = map (\x -> beta :+ pi*x) v f = map (\x -> abs $ ((magnitude $ gamma x) ^ 2)/((gamma beta) ^ 2)) s n = floor $ (fromIntegral $ length f)/2.0 frst = Data.List.take (n-1) f secnd = Data.List.drop n f in secnd ++ frst
#pragma once #include <Windows.h> #include <cstdio> #include <cstdlib> #include <cstring> #include <cstddef> #include <cassert> #include <cstdarg> #include <climits> #include <cinttypes> #include <cmath> #include <ctime> #include <algorithm> #include <any> #include <array> #include <chrono> #include <complex> #include <deque> #include <exception> #include <filesystem> #include <functional> #include <iomanip> #include <iostream> #include <iterator> #include <list> #include <locale> #include <memory> #include <mutex> #include <new> #include <numeric> #include <optional> #include <random> #include <ratio> #include <sstream> #include <stack> #include <string> #include <string_view> #include <system_error> #include <thread> #include <tuple> #include <type_traits> #include <typeinfo> #include <unordered_set> #include <utility> #include <valarray> #include <vector> #include <gsl/gsl>
<p style="font-size:32px;text-align:center"> <b>Social network Graph Link Prediction - Facebook Challenge</b> </p> ### Problem statement: Given a directed social graph, have to predict missing links to recommend users (Link Prediction in graph) ### Data Overview Taken data from facebook's recruting challenge on kaggle https://www.kaggle.com/c/FacebookRecruiting data contains two columns source and destination eac edge in graph - Data columns (total 2 columns): - source_node int64 - destination_node int64 ### Mapping the problem into supervised learning problem: - Generated training samples of good and bad links from given directed graph and for each link got some features like no of followers, is he followed back, page rank, katz score, adar index, some svd fetures of adj matrix, some weight features etc. and trained ml model based on these features to predict link. - Some reference papers and videos : - https://www.cs.cornell.edu/home/kleinber/link-pred.pdf - https://www3.nd.edu/~dial/publications/lichtenwalter2010new.pdf - https://kaggle2.blob.core.windows.net/forum-message-attachments/2594/supervised_link_prediction.pdf - https://www.youtube.com/watch?v=2M77Hgy17cg ### Business objectives and constraints: - No low-latency requirement. - Probability of prediction is useful to recommend highest probability links ### Performance metric for supervised learning: - Both precision and recall is important so F1 score is good choice - Confusion matrix ```python #Importing Libraries # please do go through this python notebook: import warnings warnings.filterwarnings("ignore") import csv import pandas as pd#pandas to create small dataframes import datetime #Convert to unix time import time #Convert to unix time # if numpy is not installed already : pip3 install numpy import numpy as np#Do aritmetic operations on arrays # matplotlib: used to plot graphs import matplotlib import matplotlib.pylab as plt import seaborn as sns#Plots from matplotlib import rcParams#Size of plots from sklearn.cluster import MiniBatchKMeans, KMeans#Clustering from sklearn.model_selection import train_test_split import math import pickle import os # to install xgboost: pip3 install xgboost import xgboost as xgb import warnings import networkx as nx import pdb import pickle from pandas import HDFStore,DataFrame from pandas import read_hdf from scipy.sparse.linalg import svds, eigs from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import f1_score import tables from tqdm import tqdm from sklearn.model_selection import RandomizedSearchCV from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import f1_score, auc, roc_auc_score, roc_curve from xgboost import XGBClassifier pd.set_option('max_colwidth', 800) ``` ```python #reading graph if not os.path.isfile('data/after_eda/train_woheader.csv'): traincsv = pd.read_csv('data/train.csv') print(traincsv[traincsv.isna().any(1)]) print(traincsv.info()) print("Number of diplicate entries: ",sum(traincsv.duplicated())) traincsv.to_csv('data/after_eda/train_woheader.csv',header=False,index=False) print("saved the graph into file") g=nx.read_edgelist('data/after_eda/train_woheader.csv',delimiter=',',create_using=nx.DiGraph(),nodetype=int) print(nx.info(g)) ``` Name: Type: DiGraph Number of nodes: 1862220 Number of edges: 9437519 Average in degree: 5.0679 Average out degree: 5.0679 > Displaying a sub graph ```python if not os.path.isfile('train_woheader_sample.csv'): pd.read_csv('data/train.csv', nrows=50).to_csv('train_woheader_sample.csv',header=False,index=False) subgraph=nx.read_edgelist('train_woheader_sample.csv',delimiter=',',create_using=nx.DiGraph(),nodetype=int) # https://stackoverflow.com/questions/9402255/drawing-a-huge-graph-with-networkx-and-matplotlib pos=nx.spring_layout(subgraph) nx.draw(subgraph,pos,node_color='#A0CBE2',edge_color='#00bb5e',width=1,edge_cmap=plt.cm.Blues,with_labels=True) plt.savefig("graph_sample.pdf") print(nx.info(subgraph)) ``` # 1. Exploratory Data Analysis ```python # No of Unique persons print("The number of unique persons",len(g.nodes())) ``` The number of unique persons 1862220 ## 1.1 No of followers for each person ```python indegree_dist = list(dict(g.in_degree()).values()) indegree_dist.sort() plt.figure(figsize=(10,6)) plt.plot(indegree_dist) plt.xlabel('Index No') plt.ylabel('No Of Followers') plt.show() ``` ```python indegree_dist = list(dict(g.in_degree()).values()) indegree_dist.sort() plt.figure(figsize=(10,6)) plt.plot(indegree_dist[0:1500000]) plt.xlabel('Index No') plt.ylabel('No Of Followers') plt.show() ``` ```python plt.boxplot(indegree_dist) plt.ylabel('No Of Followers') plt.show() ``` ```python ### 90-100 percentile for i in range(0,11): print(90+i,'percentile value is',np.percentile(indegree_dist,90+i)) ``` 90 percentile value is 12.0 91 percentile value is 13.0 92 percentile value is 14.0 93 percentile value is 15.0 94 percentile value is 17.0 95 percentile value is 19.0 96 percentile value is 21.0 97 percentile value is 24.0 98 percentile value is 29.0 99 percentile value is 40.0 100 percentile value is 552.0 99% of data having followers of 40 only. ```python ### 99-100 percentile for i in range(10,110,10): print(99+(i/100),'percentile value is',np.percentile(indegree_dist,99+(i/100))) ``` 99.1 percentile value is 42.0 99.2 percentile value is 44.0 99.3 percentile value is 47.0 99.4 percentile value is 50.0 99.5 percentile value is 55.0 99.6 percentile value is 61.0 99.7 percentile value is 70.0 99.8 percentile value is 84.0 99.9 percentile value is 112.0 100.0 percentile value is 552.0 ```python %matplotlib inline sns.set_style('ticks') fig, ax = plt.subplots() fig.set_size_inches(11.7, 8.27) sns.distplot(indegree_dist, color='#16A085') plt.xlabel('PDF of Indegree') sns.despine() #plt.show() ``` ## 1.2 No of people each person is following ```python outdegree_dist = list(dict(g.out_degree()).values()) outdegree_dist.sort() plt.figure(figsize=(10,6)) plt.plot(outdegree_dist) plt.xlabel('Index No') plt.ylabel('No Of people each person is following') plt.show() ``` ```python indegree_dist = list(dict(g.in_degree()).values()) indegree_dist.sort() plt.figure(figsize=(10,6)) plt.plot(outdegree_dist[0:1500000]) plt.xlabel('Index No') plt.ylabel('No Of people each person is following') plt.show() ``` ```python plt.boxplot(indegree_dist) plt.ylabel('No Of people each person is following') plt.show() ``` ```python ### 90-100 percentile for i in range(0,11): print(90+i,'percentile value is',np.percentile(outdegree_dist,90+i)) ``` 90 percentile value is 12.0 91 percentile value is 13.0 92 percentile value is 14.0 93 percentile value is 15.0 94 percentile value is 17.0 95 percentile value is 19.0 96 percentile value is 21.0 97 percentile value is 24.0 98 percentile value is 29.0 99 percentile value is 40.0 100 percentile value is 1566.0 ```python ### 99-100 percentile for i in range(10,110,10): print(99+(i/100),'percentile value is',np.percentile(outdegree_dist,99+(i/100))) ``` 99.1 percentile value is 42.0 99.2 percentile value is 45.0 99.3 percentile value is 48.0 99.4 percentile value is 52.0 99.5 percentile value is 56.0 99.6 percentile value is 63.0 99.7 percentile value is 73.0 99.8 percentile value is 90.0 99.9 percentile value is 123.0 100.0 percentile value is 1566.0 ```python sns.set_style('ticks') fig, ax = plt.subplots() fig.set_size_inches(11.7, 8.27) sns.distplot(outdegree_dist, color='#16A085') plt.xlabel('PDF of Outdegree') sns.despine() ``` ```python print('No of persons those are not following anyone are' ,sum(np.array(outdegree_dist)==0),'and % is', sum(np.array(outdegree_dist)==0)*100/len(outdegree_dist) ) ``` No of persons those are not following anyone are 274512 and % is 14.741115442858524 ```python print('No of persons having zero followers are' ,sum(np.array(indegree_dist)==0),'and % is', sum(np.array(indegree_dist)==0)*100/len(indegree_dist) ) ``` No of persons having zero followers are 188043 and % is 10.097786512871734 ```python count=0 for i in g.nodes(): if len(list(g.predecessors(i)))==0 : if len(list(g.successors(i)))==0: count+=1 print('No of persons those are not not following anyone and also not having any followers are',count) ``` No of persons those are not not following anyone and also not having any followers are 0 ## 1.3 both followers + following ```python from collections import Counter dict_in = dict(g.in_degree()) dict_out = dict(g.out_degree()) d = Counter(dict_in) + Counter(dict_out) in_out_degree = np.array(list(d.values())) ``` ```python in_out_degree_sort = sorted(in_out_degree) plt.figure(figsize=(10,6)) plt.plot(in_out_degree_sort) plt.xlabel('Index No') plt.ylabel('No Of people each person is following + followers') plt.show() ``` ```python in_out_degree_sort = sorted(in_out_degree) plt.figure(figsize=(10,6)) plt.plot(in_out_degree_sort[0:1500000]) plt.xlabel('Index No') plt.ylabel('No Of people each person is following + followers') plt.show() ``` ```python ### 90-100 percentile for i in range(0,11): print(90+i,'percentile value is',np.percentile(in_out_degree_sort,90+i)) ``` 90 percentile value is 24.0 91 percentile value is 26.0 92 percentile value is 28.0 93 percentile value is 31.0 94 percentile value is 33.0 95 percentile value is 37.0 96 percentile value is 41.0 97 percentile value is 48.0 98 percentile value is 58.0 99 percentile value is 79.0 100 percentile value is 1579.0 ```python ### 99-100 percentile for i in range(10,110,10): print(99+(i/100),'percentile value is',np.percentile(in_out_degree_sort,99+(i/100))) ``` 99.1 percentile value is 83.0 99.2 percentile value is 87.0 99.3 percentile value is 93.0 99.4 percentile value is 99.0 99.5 percentile value is 108.0 99.6 percentile value is 120.0 99.7 percentile value is 138.0 99.8 percentile value is 168.0 99.9 percentile value is 221.0 100.0 percentile value is 1579.0 ```python print('Min of no of followers + following is',in_out_degree.min()) print(np.sum(in_out_degree==in_out_degree.min()),' persons having minimum no of followers + following') ``` Min of no of followers + following is 1 334291 persons having minimum no of followers + following ```python print('Max of no of followers + following is',in_out_degree.max()) print(np.sum(in_out_degree==in_out_degree.max()),' persons having maximum no of followers + following') ``` Max of no of followers + following is 1579 1 persons having maximum no of followers + following ```python print('No of persons having followers + following less than 10 are',np.sum(in_out_degree<10)) ``` No of persons having followers + following less than 10 are 1320326 ```python print('No of weakly connected components',len(list(nx.weakly_connected_components(g)))) count=0 for i in list(nx.weakly_connected_components(g)): if len(i)==2: count+=1 print('weakly connected components wit 2 nodes',count) ``` No of weakly connected components 45558 weakly connected components wit 2 nodes 32195 # 2. Posing a problem as classification problem ## 2.1 Generating some edges which are not present in graph for supervised learning Generated Bad links from graph which are not in graph and whose shortest path is greater than 2. ```python %%time ###generating bad edges from given graph import random if not os.path.isfile('data/after_eda/missing_edges_final.p'): #getting all set of edges r = csv.reader(open('data/after_eda/train_woheader.csv','r')) edges = dict() for edge in r: edges[(edge[0], edge[1])] = 1 missing_edges = set([]) while (len(missing_edges)<9437519): a=random.randint(1, 1862220) b=random.randint(1, 1862220) tmp = edges.get((a,b),-1) if tmp == -1 and a!=b: try: if nx.shortest_path_length(g,source=a,target=b) > 2: missing_edges.add((a,b)) else: continue except: missing_edges.add((a,b)) else: continue pickle.dump(missing_edges,open('data/after_eda/missing_edges_final.p','wb')) else: missing_edges = pickle.load(open('data/after_eda/missing_edges_final.p','rb')) ``` CPU times: user 1.96 s, sys: 1.4 s, total: 3.36 s Wall time: 3.83 s ```python len(missing_edges) ``` 9437519 ## 2.2 Training and Test data split: Removed edges from Graph and used as test data and after removing used that graph for creating features for Train and test data ```python if (not os.path.isfile('data/after_eda/train_pos_after_eda.csv')) and (not os.path.isfile('data/after_eda/test_pos_after_eda.csv')): #reading total data df df_pos = pd.read_csv('data/train.csv') df_neg = pd.DataFrame(list(missing_edges), columns=['source_node', 'destination_node']) print("Number of nodes in the graph with edges", df_pos.shape[0]) print("Number of nodes in the graph without edges", df_neg.shape[0]) #Trian test split #Spiltted data into 80-20 #positive links and negative links seperatly because we need positive training data only for creating graph #and for feature generation X_train_pos, X_test_pos, y_train_pos, y_test_pos = train_test_split(df_pos,np.ones(len(df_pos)),test_size=0.2, random_state=9) X_train_neg, X_test_neg, y_train_neg, y_test_neg = train_test_split(df_neg,np.zeros(len(df_neg)),test_size=0.2, random_state=9) print('='*60) print("Number of nodes in the train data graph with edges", X_train_pos.shape[0],"=",y_train_pos.shape[0]) print("Number of nodes in the train data graph without edges", X_train_neg.shape[0],"=", y_train_neg.shape[0]) print('='*60) print("Number of nodes in the test data graph with edges", X_test_pos.shape[0],"=",y_test_pos.shape[0]) print("Number of nodes in the test data graph without edges", X_test_neg.shape[0],"=",y_test_neg.shape[0]) #removing header and saving X_train_pos.to_csv('data/after_eda/train_pos_after_eda.csv',header=False, index=False) X_test_pos.to_csv('data/after_eda/test_pos_after_eda.csv',header=False, index=False) X_train_neg.to_csv('data/after_eda/train_neg_after_eda.csv',header=False, index=False) X_test_neg.to_csv('data/after_eda/test_neg_after_eda.csv',header=False, index=False) else: #Graph from Traing data only del missing_edges ``` ```python if (os.path.isfile('data/after_eda/train_pos_after_eda.csv')) and (os.path.isfile('data/after_eda/test_pos_after_eda.csv')): train_graph=nx.read_edgelist('data/after_eda/train_pos_after_eda.csv',delimiter=',',create_using=nx.DiGraph(),nodetype=int) test_graph=nx.read_edgelist('data/after_eda/test_pos_after_eda.csv',delimiter=',',create_using=nx.DiGraph(),nodetype=int) print(nx.info(train_graph)) print(nx.info(test_graph)) # finding the unique nodes in the both train and test graphs train_nodes_pos = set(train_graph.nodes()) test_nodes_pos = set(test_graph.nodes()) trY_teY = len(train_nodes_pos.intersection(test_nodes_pos)) trY_teN = len(train_nodes_pos - test_nodes_pos) teY_trN = len(test_nodes_pos - train_nodes_pos) print('no of people common in train and test -- ',trY_teY) print('no of people present in train but not present in test -- ',trY_teN) print('no of people present in test but not present in train -- ',teY_trN) print(' % of people not there in Train but exist in Test in total Test data are {} %'.format(teY_trN/len(test_nodes_pos)*100)) ``` Name: Type: DiGraph Number of nodes: 1780722 Number of edges: 7550015 Average in degree: 4.2399 Average out degree: 4.2399 Name: Type: DiGraph Number of nodes: 1144623 Number of edges: 1887504 Average in degree: 1.6490 Average out degree: 1.6490 no of people common in train and test -- 1063125 no of people present in train but not present in test -- 717597 no of people present in test but not present in train -- 81498 % of people not there in Train but exist in Test in total Test data are 7.1200735962845405 % > we have a cold start problem here ```python #final train and test data sets if (not os.path.isfile('data/after_eda/train_after_eda.csv')) and \ (not os.path.isfile('data/after_eda/test_after_eda.csv')) and \ (not os.path.isfile('data/train_y.csv')) and \ (not os.path.isfile('data/test_y.csv')) and \ (os.path.isfile('data/after_eda/train_pos_after_eda.csv')) and \ (os.path.isfile('data/after_eda/test_pos_after_eda.csv')) and \ (os.path.isfile('data/after_eda/train_neg_after_eda.csv')) and \ (os.path.isfile('data/after_eda/test_neg_after_eda.csv')): X_train_pos = pd.read_csv('data/after_eda/train_pos_after_eda.csv', names=['source_node', 'destination_node']) X_test_pos = pd.read_csv('data/after_eda/test_pos_after_eda.csv', names=['source_node', 'destination_node']) X_train_neg = pd.read_csv('data/after_eda/train_neg_after_eda.csv', names=['source_node', 'destination_node']) X_test_neg = pd.read_csv('data/after_eda/test_neg_after_eda.csv', names=['source_node', 'destination_node']) print('='*60) print("Number of nodes in the train data graph with edges", X_train_pos.shape[0]) print("Number of nodes in the train data graph without edges", X_train_neg.shape[0]) print('='*60) print("Number of nodes in the test data graph with edges", X_test_pos.shape[0]) print("Number of nodes in the test data graph without edges", X_test_neg.shape[0]) X_train = X_train_pos.append(X_train_neg,ignore_index=True) y_train = np.concatenate((y_train_pos,y_train_neg)) X_test = X_test_pos.append(X_test_neg,ignore_index=True) y_test = np.concatenate((y_test_pos,y_test_neg)) X_train.to_csv('data/after_eda/train_after_eda.csv',header=False,index=False) X_test.to_csv('data/after_eda/test_after_eda.csv',header=False,index=False) pd.DataFrame(y_train.astype(int)).to_csv('data/train_y.csv',header=False,index=False) pd.DataFrame(y_test.astype(int)).to_csv('data/test_y.csv',header=False,index=False) ``` ```python print("Data points in train data",X_train.shape) print("Data points in test data",X_test.shape) print("Shape of traget variable in train",y_train.shape) print("Shape of traget variable in test", y_test.shape) ``` # 1. Reading Data ```python if os.path.isfile('data/after_eda/train_pos_after_eda.csv'): train_graph=nx.read_edgelist('data/after_eda/train_pos_after_eda.csv',delimiter=',',create_using=nx.DiGraph(),nodetype=int) print(nx.info(train_graph)) else: print("please run the FB_EDA.ipynb or download the files from drive") ``` Name: Type: DiGraph Number of nodes: 1780722 Number of edges: 7550015 Average in degree: 4.2399 Average out degree: 4.2399 # 2. Similarity measures ## 2.1 Jaccard Distance: http://www.statisticshowto.com/jaccard-index/ \begin{equation} j = \frac{|X\cap Y|}{|X \cup Y|} \end{equation} ```python #for followees def jaccard_for_followees(a,b): try: if len(set(train_graph.successors(a))) == 0 | len(set(train_graph.successors(b))) == 0: return 0 sim = (len(set(train_graph.successors(a)).intersection(set(train_graph.successors(b)))))/\ (len(set(train_graph.successors(a)).union(set(train_graph.successors(b))))) except: return 0 return sim ``` ```python #one test case print(jaccard_for_followees(273084,1505602)) ``` 0.0 ```python #node 1635354 not in graph print(jaccard_for_followees(273084,1505602)) ``` 0.0 ```python #for followers def jaccard_for_followers(a,b): try: if len(set(train_graph.predecessors(a))) == 0 | len(set(g.predecessors(b))) == 0: return 0 sim = (len(set(train_graph.predecessors(a)).intersection(set(train_graph.predecessors(b)))))/\ (len(set(train_graph.predecessors(a)).union(set(train_graph.predecessors(b))))) return sim except: return 0 ``` ```python print(jaccard_for_followers(273084,470294)) ``` 0 ```python #node 1635354 not in graph print(jaccard_for_followees(669354,1635354)) ``` 0 ## 2.2 Cosine distance \begin{equation} CosineDistance = \frac{|X\cap Y|}{|X|\cdot|Y|} \end{equation} ```python #for followees def cosine_for_followees(a,b): try: if len(set(train_graph.successors(a))) == 0 | len(set(train_graph.successors(b))) == 0: return 0 sim = (len(set(train_graph.successors(a)).intersection(set(train_graph.successors(b)))))/\ (math.sqrt(len(set(train_graph.successors(a)))*len((set(train_graph.successors(b)))))) return sim except: return 0 ``` ```python print(cosine_for_followees(273084,1505602)) ``` 0.0 ```python print(cosine_for_followees(273084,1635354)) ``` 0 ```python def cosine_for_followers(a,b): try: if len(set(train_graph.predecessors(a))) == 0 | len(set(train_graph.predecessors(b))) == 0: return 0 sim = (len(set(train_graph.predecessors(a)).intersection(set(train_graph.predecessors(b)))))/\ (math.sqrt(len(set(train_graph.predecessors(a))))*(len(set(train_graph.predecessors(b))))) return sim except: return 0 ``` ```python print(cosine_for_followers(2,470294)) ``` 0.02886751345948129 ```python print(cosine_for_followers(669354,1635354)) ``` 0 ## 2.3 Preferential Attachment One well-known concept in social networks is that users with many friends tend to create more connections in the future. This is due to the fact that in some social networks, like in finance, the rich get richer. We estimate how ”rich” our two vertices are by calculating the multiplication between the number of friends (|N(x)|) or followers each vertex has. It may be noted that the similarity index does not require any node neighbor information; therefore, this similarity index has the lowest computational complexity. \begin{equation} Preferential Attachment = {|N(X)| \cdot |N(Y)|} \end{equation} For two nodes a,b, the preferential attachment= number of followers(a)* number of followers(b). ```python def preferentialAttachment(a,b): try: if len(set(train_graph.predecessors(a))) == 0 | len(set(train_graph.predecessors(b))) == 0: return 0 sim = (len(set(train_graph.successors(a)))*len((set(train_graph.successors(b))))) return sim except: return 0 ``` ```python print(preferentialAttachment(273084,1505602)) ``` 120 ```python print(preferentialAttachment(273084,1635354)) ``` 0 ## 3. Ranking Measures https://networkx.github.io/documentation/networkx-1.10/reference/generated/networkx.algorithms.link_analysis.pagerank_alg.pagerank.html PageRank computes a ranking of the nodes in the graph G based on the structure of the incoming links. Mathematical PageRanks for a simple network, expressed as percentages. (Google uses a logarithmic scale.) Page C has a higher PageRank than Page E, even though there are fewer links to C; the one link to C comes from an important page and hence is of high value. If web surfers who start on a random page have an 85% likelihood of choosing a random link from the page they are currently visiting, and a 15% likelihood of jumping to a page chosen at random from the entire web, they will reach Page E 8.1% of the time. <b>(The 15% likelihood of jumping to an arbitrary page corresponds to a damping factor of 85%.) Without damping, all web surfers would eventually end up on Pages A, B, or C, and all other pages would have PageRank zero. In the presence of damping, Page A effectively links to all pages in the web, even though it has no outgoing links of its own.</b> ## 3.1 Page Ranking https://en.wikipedia.org/wiki/PageRank ```python if not os.path.isfile('data/fea_sample/page_rank.p'): pr = nx.pagerank(train_graph, alpha=0.85) pickle.dump(pr,open('data/fea_sample/page_rank.p','wb')) else: pr = pickle.load(open('data/fea_sample/page_rank.p','rb')) ``` ```python print('min',pr[min(pr, key=pr.get)]) print('max',pr[max(pr, key=pr.get)]) print('mean',float(sum(pr.values())) / len(pr)) ``` min 1.6556497245737814e-07 max 2.7098251341935817e-05 mean 5.615699699365892e-07 ```python #for imputing to nodes which are not there in Train data mean_pr = float(sum(pr.values())) / len(pr) print(mean_pr) ``` 5.615699699365892e-07 # 4. Other Graph Features ## 4.1 Shortest path: Getting Shortest path between twoo nodes, if nodes have direct path i.e directly connected then we are removing that edge and calculating path. ```python #if has direct edge then deleting that edge and calculating shortest path def compute_shortest_path_length(a,b): p=-1 try: if train_graph.has_edge(a,b): train_graph.remove_edge(a,b) p= nx.shortest_path_length(train_graph,source=a,target=b) train_graph.add_edge(a,b) else: p= nx.shortest_path_length(train_graph,source=a,target=b) return p except: return -1 ``` ```python #testing compute_shortest_path_length(77697, 826021) ``` 10 ```python #testing compute_shortest_path_length(669354,1635354) ``` -1 ## 4.2 Checking for same community ```python #getting weekly connected edges from graph wcc=list(nx.weakly_connected_components(train_graph)) def belongs_to_same_wcc(a,b): index = [] if train_graph.has_edge(b,a): return 1 if train_graph.has_edge(a,b): for i in wcc: if a in i: index= i break if (b in index): train_graph.remove_edge(a,b) if compute_shortest_path_length(a,b)==-1: train_graph.add_edge(a,b) return 0 else: train_graph.add_edge(a,b) return 1 else: return 0 else: for i in wcc: if a in i: index= i break if(b in index): return 1 else: return 0 ``` ```python belongs_to_same_wcc(861, 1659750) ``` 0 ```python belongs_to_same_wcc(669354,1635354) ``` 0 ## 4.3 Adamic/Adar Index: Adamic/Adar measures is defined as inverted sum of degrees of common neighbours for given two vertices. $$A(x,y)=\sum_{u \in N(x) \cap N(y)}\frac{1}{log(|N(u)|)}$$ ```python #adar index def calc_adar_in(a,b): sum=0 try: n=list(set(train_graph.successors(a)).intersection(set(train_graph.successors(b)))) if len(n)!=0: for i in n: sum=sum+(1/np.log10(len(list(train_graph.predecessors(i))))) return sum else: return 0 except: return 0 ``` ```python calc_adar_in(1,189226) ``` 0 ```python calc_adar_in(669354,1635354) ``` 0 ## 4.4 Is persion was following back: ```python def follows_back(a,b): if train_graph.has_edge(b,a): return 1 else: return 0 ``` ```python follows_back(1,189226) ``` 1 ```python follows_back(669354,1635354) ``` 0 ## 4.5 Katz Centrality: https://en.wikipedia.org/wiki/Katz_centrality https://www.geeksforgeeks.org/katz-centrality-centrality-measure/ Katz centrality computes the centrality for a node based on the centrality of its neighbors. It is a generalization of the eigenvector centrality. The Katz centrality for node `i` is $$x_i = \alpha \sum_{j} A_{ij} x_j + \beta,$$ where `A` is the adjacency matrix of the graph G with eigenvalues $$\lambda$$. The parameter $$\beta$$ controls the initial centrality and $$\alpha < \frac{1}{\lambda_{max}}.$$ ```python if not os.path.isfile('data/fea_sample/katz.p'): katz = nx.katz.katz_centrality(train_graph,alpha=0.005,beta=1) pickle.dump(katz,open('data/fea_sample/katz.p','wb')) else: katz = pickle.load(open('data/fea_sample/katz.p','rb')) ``` ```python print('min',katz[min(katz, key=katz.get)]) print('max',katz[max(katz, key=katz.get)]) print('mean',float(sum(katz.values())) / len(katz)) ``` min 0.0007313532484062579 max 0.003394554981697573 mean 0.0007483800935501884 ```python mean_katz = float(sum(katz.values())) / len(katz) print(mean_katz) ``` 0.0007483800935501884 ## 4.6 Hits Score The HITS algorithm computes two numbers for a node. Authorities estimates the node value based on the incoming links. Hubs estimates the node value based on outgoing links. https://en.wikipedia.org/wiki/HITS_algorithm ```python if not os.path.isfile('data/fea_sample/hits.p'): hits = nx.hits(train_graph, max_iter=100, tol=1e-08, nstart=None, normalized=True) pickle.dump(hits,open('data/fea_sample/hits.p','wb')) else: hits = pickle.load(open('data/fea_sample/hits.p','rb')) ``` ```python print('min',hits[0][min(hits[0], key=hits[0].get)]) print('max',hits[0][max(hits[0], key=hits[0].get)]) print('mean',float(sum(hits[0].values())) / len(hits[0])) ``` min 0.0 max 0.004868653378766884 mean 5.615699699337049e-07 # 5. Featurization ## 5. 1 Reading a sample of Data from both train and test ```python import random if os.path.isfile('data/after_eda/train_after_eda.csv'): filename = "data/after_eda/train_after_eda.csv" # you uncomment this line, if you dont know the lentgh of the file name # here we have hardcoded the number of lines as 15100030 # n_train = sum(1 for line in open(filename)) #number of records in file (excludes header) n_train = 15100028 s = 100000 #desired sample size skip_train = sorted(random.sample(range(1,n_train+1),n_train-s)) #https://stackoverflow.com/a/22259008/4084039 ``` ```python if os.path.isfile('data/after_eda/train_after_eda.csv'): filename = "data/after_eda/test_after_eda.csv" # you uncomment this line, if you dont know the lentgh of the file name # here we have hardcoded the number of lines as 3775008 # n_test = sum(1 for line in open(filename)) #number of records in file (excludes header) n_test = 3775006 s = 50000 #desired sample size skip_test = sorted(random.sample(range(1,n_test+1),n_test-s)) #https://stackoverflow.com/a/22259008/4084039 ``` ```python print("Number of rows in the train data file:", n_train) print("Number of rows we are going to elimiate in train data are",len(skip_train)) print("Number of rows in the test data file:", n_test) print("Number of rows we are going to elimiate in test data are",len(skip_test)) ``` Number of rows in the train data file: 15100028 Number of rows we are going to elimiate in train data are 15000028 Number of rows in the test data file: 3775006 Number of rows we are going to elimiate in test data are 3725006 ```python df_final_train = pd.read_csv('data/after_eda/train_after_eda.csv', skiprows=skip_train, names=['source_node', 'destination_node']) df_final_train['indicator_link'] = pd.read_csv('data/train_y.csv', skiprows=skip_train, names=['indicator_link']) print("Our train matrix size ",df_final_train.shape) df_final_train.head(2) ``` Our train matrix size (100002, 3) <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>source_node</th> <th>destination_node</th> <th>indicator_link</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>273084</td> <td>1505602</td> <td>1</td> </tr> <tr> <th>1</th> <td>1757093</td> <td>912379</td> <td>1</td> </tr> </tbody> </table> </div> ```python df_final_test = pd.read_csv('data/after_eda/test_after_eda.csv', skiprows=skip_test, names=['source_node', 'destination_node']) df_final_test['indicator_link'] = pd.read_csv('data/test_y.csv', skiprows=skip_test, names=['indicator_link']) print("Our test matrix size ",df_final_test.shape) df_final_test.head(2) ``` Our test matrix size (50002, 3) <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>source_node</th> <th>destination_node</th> <th>indicator_link</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>848424</td> <td>784690</td> <td>1</td> </tr> <tr> <th>1</th> <td>1227220</td> <td>827479</td> <td>1</td> </tr> </tbody> </table> </div> ## 5.2 Adding a set of features __we will create these each of these features for both train and test data points__ <ol> <li>jaccard_followers</li> <li>jaccard_followees</li> <li>cosine_followers</li> <li>cosine_followees</li> <li>preferentialAttachment</li> <li>num_followers_s</li> <li>num_followees_s</li> <li>num_followers_d</li> <li>num_followees_d</li> <li>inter_followers</li> <li>inter_followees</li> </ol> ```python if not os.path.isfile('data/fea_sample/storage_sample_stage1.h5'): #mapping jaccrd followers to train and test data df_final_train['jaccard_followers'] = df_final_train.apply(lambda row: jaccard_for_followers(row['source_node'],row['destination_node']),axis=1) df_final_test['jaccard_followers'] = df_final_test.apply(lambda row: jaccard_for_followers(row['source_node'],row['destination_node']),axis=1) #mapping jaccrd followees to train and test data df_final_train['jaccard_followees'] = df_final_train.apply(lambda row: jaccard_for_followees(row['source_node'],row['destination_node']),axis=1) df_final_test['jaccard_followees'] = df_final_test.apply(lambda row: jaccard_for_followees(row['source_node'],row['destination_node']),axis=1) #mapping cosine followers to train and test data df_final_train['cosine_followers'] = df_final_train.apply(lambda row: cosine_for_followers(row['source_node'],row['destination_node']),axis=1) df_final_test['cosine_followers'] = df_final_test.apply(lambda row: cosine_for_followers(row['source_node'],row['destination_node']),axis=1) #mapping cosine followees to train and test data df_final_train['cosine_followees'] = df_final_train.apply(lambda row: cosine_for_followees(row['source_node'],row['destination_node']),axis=1) df_final_test['cosine_followees'] = df_final_test.apply(lambda row: cosine_for_followees(row['source_node'],row['destination_node']),axis=1) #mapping preferential Attachment to train and test data df_final_train['pref_attachment'] = df_final_train.apply(lambda row: preferentialAttachment(row['source_node'],row['destination_node']),axis=1) df_final_test['pref_attachment'] = df_final_test.apply(lambda row: preferentialAttachment(row['source_node'],row['destination_node']),axis=1) ``` ```python def compute_features_stage1(df_final): #calculating no of followers followees for source and destination #calculating intersection of followers and followees for source and destination num_followers_s=[] num_followees_s=[] num_followers_d=[] num_followees_d=[] inter_followers=[] inter_followees=[] for i,row in df_final.iterrows(): try: s1=set(train_graph.predecessors(row['source_node'])) s2=set(train_graph.successors(row['source_node'])) except: s1 = set() s2 = set() try: d1=set(train_graph.predecessors(row['destination_node'])) d2=set(train_graph.successors(row['destination_node'])) except: d1 = set() d2 = set() num_followers_s.append(len(s1)) num_followees_s.append(len(s2)) num_followers_d.append(len(d1)) num_followees_d.append(len(d2)) inter_followers.append(len(s1.intersection(d1))) inter_followees.append(len(s2.intersection(d2))) return num_followers_s, num_followers_d, num_followees_s, num_followees_d, inter_followers, inter_followees ``` ```python if not os.path.isfile('data/fea_sample/storage_sample_stage1.h5'): df_final_train['num_followers_s'], df_final_train['num_followers_d'], \ df_final_train['num_followees_s'], df_final_train['num_followees_d'], \ df_final_train['inter_followers'], df_final_train['inter_followees']= compute_features_stage1(df_final_train) df_final_test['num_followers_s'], df_final_test['num_followers_d'], \ df_final_test['num_followees_s'], df_final_test['num_followees_d'], \ df_final_test['inter_followers'], df_final_test['inter_followees']= compute_features_stage1(df_final_test) hdf = HDFStore('data/fea_sample/storage_sample_stage1.h5') hdf.put('train_df',df_final_train, format='table', data_columns=True) hdf.put('test_df',df_final_test, format='table', data_columns=True) hdf.close() else: df_final_train = read_hdf('data/fea_sample/storage_sample_stage1.h5', 'train_df',mode='r') df_final_test = read_hdf('data/fea_sample/storage_sample_stage1.h5', 'test_df',mode='r') ``` ## 5.3 Adding new set of features __we will create these each of these features for both train and test data points__ <ol> <li>adar index</li> <li>is following back</li> <li>belongs to same weakly connect components</li> <li>shortest path between source and destination</li> </ol> ```python if not os.path.isfile('data/fea_sample/storage_sample_stage2.h5'): #mapping adar index on train df_final_train['adar_index'] = df_final_train.apply(lambda row: calc_adar_in(row['source_node'],row['destination_node']),axis=1) #mapping adar index on test df_final_test['adar_index'] = df_final_test.apply(lambda row: calc_adar_in(row['source_node'],row['destination_node']),axis=1) #-------------------------------------------------------------------------------------------------------- #mapping followback or not on train df_final_train['follows_back'] = df_final_train.apply(lambda row: follows_back(row['source_node'],row['destination_node']),axis=1) #mapping followback or not on test df_final_test['follows_back'] = df_final_test.apply(lambda row: follows_back(row['source_node'],row['destination_node']),axis=1) #-------------------------------------------------------------------------------------------------------- #mapping same component of wcc or not on train df_final_train['same_comp'] = df_final_train.apply(lambda row: belongs_to_same_wcc(row['source_node'],row['destination_node']),axis=1) ##mapping same component of wcc or not on train df_final_test['same_comp'] = df_final_test.apply(lambda row: belongs_to_same_wcc(row['source_node'],row['destination_node']),axis=1) #-------------------------------------------------------------------------------------------------------- #mapping shortest path on train df_final_train['shortest_path'] = df_final_train.apply(lambda row: compute_shortest_path_length(row['source_node'],row['destination_node']),axis=1) #mapping shortest path on test df_final_test['shortest_path'] = df_final_test.apply(lambda row: compute_shortest_path_length(row['source_node'],row['destination_node']),axis=1) hdf = HDFStore('data/fea_sample/storage_sample_stage2.h5') hdf.put('train_df',df_final_train, format='table', data_columns=True) hdf.put('test_df',df_final_test, format='table', data_columns=True) hdf.close() else: df_final_train = read_hdf('data/fea_sample/storage_sample_stage2.h5', 'train_df',mode='r') df_final_test = read_hdf('data/fea_sample/storage_sample_stage2.h5', 'test_df',mode='r') ``` ## 5.4 Adding new set of features __we will create these each of these features for both train and test data points__ <ol> <li>Weight Features <ul> <li>weight of incoming edges</li> <li>weight of outgoing edges</li> <li>weight of incoming edges + weight of outgoing edges</li> <li>weight of incoming edges * weight of outgoing edges</li> <li>2*weight of incoming edges + weight of outgoing edges</li> <li>weight of incoming edges + 2*weight of outgoing edges</li> </ul> </li> <li>Page Ranking of source</li> <li>Page Ranking of dest</li> <li>katz of source</li> <li>katz of dest</li> <li>hubs of source</li> <li>hubs of dest</li> <li>authorities_s of source</li> <li>authorities_s of dest</li> </ol> #### Weight Features In order to determine the similarity of nodes, an edge weight value was calculated between nodes. Edge weight decreases as the neighbor count goes up. Intuitively, consider one million people following a celebrity on a social network then chances are most of them never met each other or the celebrity. On the other hand, if a user has 30 contacts in his/her social network, the chances are higher that many of them know each other. `credit` - Graph-based Features for Supervised Link Prediction William Cukierski, Benjamin Hamner, Bo Yang \begin{equation} W = \frac{1}{\sqrt{1+|X|}} \end{equation} it is directed graph so calculated Weighted in and Weighted out differently ```python #weight for source and destination of each link Weight_in = {} Weight_out = {} for i in tqdm(train_graph.nodes()): s1=set(train_graph.predecessors(i)) w_in = 1.0/(np.sqrt(1+len(s1))) Weight_in[i]=w_in s2=set(train_graph.successors(i)) w_out = 1.0/(np.sqrt(1+len(s2))) Weight_out[i]=w_out #for imputing with mean mean_weight_in = np.mean(list(Weight_in.values())) mean_weight_out = np.mean(list(Weight_out.values())) ``` 100%|██████████| 1780722/1780722 [00:16<00:00, 105780.58it/s] ```python if not os.path.isfile('data/fea_sample/storage_sample_stage3.h5'): #mapping to pandas train df_final_train['weight_in'] = df_final_train.destination_node.apply(lambda x: Weight_in.get(x,mean_weight_in)) df_final_train['weight_out'] = df_final_train.source_node.apply(lambda x: Weight_out.get(x,mean_weight_out)) #mapping to pandas test df_final_test['weight_in'] = df_final_test.destination_node.apply(lambda x: Weight_in.get(x,mean_weight_in)) df_final_test['weight_out'] = df_final_test.source_node.apply(lambda x: Weight_out.get(x,mean_weight_out)) #some features engineerings on the in and out weights df_final_train['weight_f1'] = df_final_train.weight_in + df_final_train.weight_out df_final_train['weight_f2'] = df_final_train.weight_in * df_final_train.weight_out df_final_train['weight_f3'] = (2*df_final_train.weight_in + 1*df_final_train.weight_out) df_final_train['weight_f4'] = (1*df_final_train.weight_in + 2*df_final_train.weight_out) #some features engineerings on the in and out weights df_final_test['weight_f1'] = df_final_test.weight_in + df_final_test.weight_out df_final_test['weight_f2'] = df_final_test.weight_in * df_final_test.weight_out df_final_test['weight_f3'] = (2*df_final_test.weight_in + 1*df_final_test.weight_out) df_final_test['weight_f4'] = (1*df_final_test.weight_in + 2*df_final_test.weight_out) ``` ```python if not os.path.isfile('data/fea_sample/storage_sample_stage3.h5'): #page rank for source and destination in Train and Test #if anything not there in train graph then adding mean page rank df_final_train['page_rank_s'] = df_final_train.source_node.apply(lambda x:pr.get(x,mean_pr)) df_final_train['page_rank_d'] = df_final_train.destination_node.apply(lambda x:pr.get(x,mean_pr)) df_final_test['page_rank_s'] = df_final_test.source_node.apply(lambda x:pr.get(x,mean_pr)) df_final_test['page_rank_d'] = df_final_test.destination_node.apply(lambda x:pr.get(x,mean_pr)) #================================================================================ #Katz centrality score for source and destination in Train and test #if anything not there in train graph then adding mean katz score df_final_train['katz_s'] = df_final_train.source_node.apply(lambda x: katz.get(x,mean_katz)) df_final_train['katz_d'] = df_final_train.destination_node.apply(lambda x: katz.get(x,mean_katz)) df_final_test['katz_s'] = df_final_test.source_node.apply(lambda x: katz.get(x,mean_katz)) df_final_test['katz_d'] = df_final_test.destination_node.apply(lambda x: katz.get(x,mean_katz)) #================================================================================ #Hits algorithm score for source and destination in Train and test #if anything not there in train graph then adding 0 df_final_train['hubs_s'] = df_final_train.source_node.apply(lambda x: hits[0].get(x,0)) df_final_train['hubs_d'] = df_final_train.destination_node.apply(lambda x: hits[0].get(x,0)) df_final_test['hubs_s'] = df_final_test.source_node.apply(lambda x: hits[0].get(x,0)) df_final_test['hubs_d'] = df_final_test.destination_node.apply(lambda x: hits[0].get(x,0)) #================================================================================ #Hits algorithm score for source and destination in Train and Test #if anything not there in train graph then adding 0 df_final_train['authorities_s'] = df_final_train.source_node.apply(lambda x: hits[1].get(x,0)) df_final_train['authorities_d'] = df_final_train.destination_node.apply(lambda x: hits[1].get(x,0)) df_final_test['authorities_s'] = df_final_test.source_node.apply(lambda x: hits[1].get(x,0)) df_final_test['authorities_d'] = df_final_test.destination_node.apply(lambda x: hits[1].get(x,0)) #================================================================================ hdf = HDFStore('data/fea_sample/storage_sample_stage3.h5') hdf.put('train_df',df_final_train, format='table', data_columns=True) hdf.put('test_df',df_final_test, format='table', data_columns=True) hdf.close() else: df_final_train = read_hdf('data/fea_sample/storage_sample_stage3.h5', 'train_df',mode='r') df_final_test = read_hdf('data/fea_sample/storage_sample_stage3.h5', 'test_df',mode='r') ``` ## 5.5 Adding new set of features __we will create these each of these features for both train and test data points__ <ol> <li>SVD features for both source and destination</li> </ol> ```python def svd(x, S): try: z = sadj_dict[x] return S[z] except: return [0,0,0,0,0,0] ``` ```python #for svd features to get feature vector creating a dict node val and inedx in svd vector sadj_col = sorted(train_graph.nodes()) sadj_dict = { val:idx for idx,val in enumerate(sadj_col)} ``` ```python Adj = nx.adjacency_matrix(train_graph,nodelist=sorted(train_graph.nodes())).asfptype() ``` ```python U, s, V = svds(Adj, k = 6) print('Adjacency matrix Shape',Adj.shape) print('U Shape',U.shape) print('V Shape',V.shape) print('s Shape',s.shape) ``` Adjacency matrix Shape (1780722, 1780722) U Shape (1780722, 6) V Shape (6, 1780722) s Shape (6,) ```python if not os.path.isfile('data/fea_sample/storage_sample_stage4.h5'): #=================================================================================================== df_final_train[['svd_u_s_1', 'svd_u_s_2','svd_u_s_3', 'svd_u_s_4', 'svd_u_s_5', 'svd_u_s_6']] = \ df_final_train.source_node.apply(lambda x: svd(x, U)).apply(pd.Series) df_final_train[['svd_u_d_1', 'svd_u_d_2', 'svd_u_d_3', 'svd_u_d_4', 'svd_u_d_5','svd_u_d_6']] = \ df_final_train.destination_node.apply(lambda x: svd(x, U)).apply(pd.Series) #=================================================================================================== df_final_train[['svd_v_s_1','svd_v_s_2', 'svd_v_s_3', 'svd_v_s_4', 'svd_v_s_5', 'svd_v_s_6',]] = \ df_final_train.source_node.apply(lambda x: svd(x, V.T)).apply(pd.Series) df_final_train[['svd_v_d_1', 'svd_v_d_2', 'svd_v_d_3', 'svd_v_d_4', 'svd_v_d_5','svd_v_d_6']] = \ df_final_train.destination_node.apply(lambda x: svd(x, V.T)).apply(pd.Series) #=================================================================================================== df_final_test[['svd_u_s_1', 'svd_u_s_2','svd_u_s_3', 'svd_u_s_4', 'svd_u_s_5', 'svd_u_s_6']] = \ df_final_test.source_node.apply(lambda x: svd(x, U)).apply(pd.Series) df_final_test[['svd_u_d_1', 'svd_u_d_2', 'svd_u_d_3', 'svd_u_d_4', 'svd_u_d_5','svd_u_d_6']] = \ df_final_test.destination_node.apply(lambda x: svd(x, U)).apply(pd.Series) #=================================================================================================== df_final_test[['svd_v_s_1','svd_v_s_2', 'svd_v_s_3', 'svd_v_s_4', 'svd_v_s_5', 'svd_v_s_6',]] = \ df_final_test.source_node.apply(lambda x: svd(x, V.T)).apply(pd.Series) df_final_test[['svd_v_d_1', 'svd_v_d_2', 'svd_v_d_3', 'svd_v_d_4', 'svd_v_d_5','svd_v_d_6']] = \ df_final_test.destination_node.apply(lambda x: svd(x, V.T)).apply(pd.Series) #=================================================================================================== ###### SVD dot is the product between source node svd and destination node svd #Train Dataset s1,s2,s3,s4,s5,s6=df_final_train['svd_u_s_1'],df_final_train['svd_u_s_2'],df_final_train['svd_u_s_3'],df_final_train['svd_u_s_4'],df_final_train['svd_u_s_5'],df_final_train['svd_u_s_6'] s7,s8,s9,s10,s11,s12=df_final_train['svd_v_s_1'],df_final_train['svd_v_s_2'],df_final_train['svd_v_s_3'],df_final_train['svd_v_s_4'],df_final_train['svd_v_s_5'],df_final_train['svd_v_s_6'] d1,d2,d3,d4,d5,d6=df_final_train['svd_u_d_1'],df_final_train['svd_u_d_2'],df_final_train['svd_u_d_3'],df_final_train['svd_u_d_4'],df_final_train['svd_u_d_5'],df_final_train['svd_u_d_6'] d7,d8,d9,d10,d11,d12=df_final_train['svd_v_d_1'],df_final_train['svd_v_d_2'],df_final_train['svd_v_d_3'],df_final_train['svd_v_d_4'],df_final_train['svd_v_d_5'],df_final_train['svd_v_d_6'] svd_dot=[] for i in range(len(np.array(s1))): a=[] b=[] a.append(np.array(s1[i])) a.append(np.array(s2[i])) a.append(np.array(s3[i])) a.append(np.array(s4[i])) a.append(np.array(s5[i])) a.append(np.array(s6[i])) a.append(np.array(s7[i])) a.append(np.array(s8[i])) a.append(np.array(s9[i])) a.append(np.array(s10[i])) a.append(np.array(s11[i])) a.append(np.array(s12[i])) b.append(np.array(d1[i])) b.append(np.array(d2[i])) b.append(np.array(d3[i])) b.append(np.array(d4[i])) b.append(np.array(d5[i])) b.append(np.array(d6[i])) b.append(np.array(d7[i])) b.append(np.array(d8[i])) b.append(np.array(d9[i])) b.append(np.array(d10[i])) b.append(np.array(d11[i])) b.append(np.array(d12[i])) svd_dot.append(np.dot(a,b)) df_final_train['svd_dot']=svd_dot # Test dataset s1,s2,s3,s4,s5,s6=df_final_test['svd_u_s_1'],df_final_test['svd_u_s_2'],df_final_test['svd_u_s_3'],df_final_test['svd_u_s_4'],df_final_test['svd_u_s_5'],df_final_test['svd_u_s_6'] s7,s8,s9,s10,s11,s12=df_final_test['svd_v_s_1'],df_final_test['svd_v_s_2'],df_final_test['svd_v_s_3'],df_final_test['svd_v_s_4'],df_final_test['svd_v_s_5'],df_final_test['svd_v_s_6'] d1,d2,d3,d4,d5,d6=df_final_test['svd_u_d_1'],df_final_test['svd_u_d_2'],df_final_test['svd_u_d_3'],df_final_test['svd_u_d_4'],df_final_test['svd_u_d_5'],df_final_test['svd_u_d_6'] d7,d8,d9,d10,d11,d12=df_final_test['svd_v_d_1'],df_final_test['svd_v_d_2'],df_final_test['svd_v_d_3'],df_final_test['svd_v_d_4'],df_final_test['svd_v_d_5'],df_final_test['svd_v_d_6'] svd_dot=[] for i in range(len(np.array(s1))): a=[] b=[] a.append(np.array(s1[i])) a.append(np.array(s2[i])) a.append(np.array(s3[i])) a.append(np.array(s4[i])) a.append(np.array(s5[i])) a.append(np.array(s6[i])) a.append(np.array(s7[i])) a.append(np.array(s8[i])) a.append(np.array(s9[i])) a.append(np.array(s10[i])) a.append(np.array(s11[i])) a.append(np.array(s12[i])) b.append(np.array(d1[i])) b.append(np.array(d2[i])) b.append(np.array(d3[i])) b.append(np.array(d4[i])) b.append(np.array(d5[i])) b.append(np.array(d6[i])) b.append(np.array(d7[i])) b.append(np.array(d8[i])) b.append(np.array(d9[i])) b.append(np.array(d10[i])) b.append(np.array(d11[i])) b.append(np.array(d12[i])) svd_dot.append(np.dot(a,b)) df_final_test['svd_dot']=svd_dot hdf = HDFStore('data/fea_sample/storage_sample_stage4.h5') hdf.put('train_df',df_final_train, format='table', data_columns=True) hdf.put('test_df',df_final_test, format='table', data_columns=True) hdf.close() ``` ```python df_final_train.head(2) ``` <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>source_node</th> <th>destination_node</th> <th>indicator_link</th> <th>jaccard_followers</th> <th>jaccard_followees</th> <th>cosine_followers</th> <th>cosine_followees</th> <th>pref_attachment</th> <th>num_followers_s</th> <th>num_followers_d</th> <th>...</th> <th>svd_v_s_4</th> <th>svd_v_s_5</th> <th>svd_v_s_6</th> <th>svd_v_d_1</th> <th>svd_v_d_2</th> <th>svd_v_d_3</th> <th>svd_v_d_4</th> <th>svd_v_d_5</th> <th>svd_v_d_6</th> <th>svd_dot</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>273084</td> <td>1505602</td> <td>1</td> <td>0</td> <td>0.0</td> <td>0.000000</td> <td>0.0</td> <td>120</td> <td>11</td> <td>6</td> <td>...</td> <td>1.545073e-13</td> <td>8.108305e-13</td> <td>1.719696e-14</td> <td>-1.355366e-12</td> <td>4.675307e-13</td> <td>1.128584e-06</td> <td>6.616668e-14</td> <td>9.770961e-13</td> <td>4.159941e-14</td> <td>1.338824e-11</td> </tr> <tr> <th>1</th> <td>1757093</td> <td>912379</td> <td>1</td> <td>0</td> <td>0.0</td> <td>0.064818</td> <td>0.0</td> <td>0</td> <td>50</td> <td>72</td> <td>...</td> <td>3.150010e-10</td> <td>6.229440e-10</td> <td>2.030771e-07</td> <td>-1.583718e-12</td> <td>3.249045e-11</td> <td>2.106838e-11</td> <td>3.494949e-10</td> <td>1.282765e-09</td> <td>2.249379e-07</td> <td>4.568064e-14</td> </tr> </tbody> </table> <p>2 rows × 57 columns</p> </div> ```python df_final_test.head(2) ``` <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>source_node</th> <th>destination_node</th> <th>indicator_link</th> <th>jaccard_followers</th> <th>jaccard_followees</th> <th>cosine_followers</th> <th>cosine_followees</th> <th>pref_attachment</th> <th>num_followers_s</th> <th>num_followers_d</th> <th>...</th> <th>svd_v_s_4</th> <th>svd_v_s_5</th> <th>svd_v_s_6</th> <th>svd_v_d_1</th> <th>svd_v_d_2</th> <th>svd_v_d_3</th> <th>svd_v_d_4</th> <th>svd_v_d_5</th> <th>svd_v_d_6</th> <th>svd_dot</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>848424</td> <td>784690</td> <td>1</td> <td>0</td> <td>0.0</td> <td>0.029161</td> <td>0.0</td> <td>54</td> <td>6</td> <td>14</td> <td>...</td> <td>2.701518e-12</td> <td>4.341597e-13</td> <td>5.535511e-14</td> <td>-9.994077e-10</td> <td>5.791913e-10</td> <td>3.512350e-07</td> <td>2.486438e-09</td> <td>2.771146e-09</td> <td>1.727698e-12</td> <td>2.083208e-17</td> </tr> <tr> <th>1</th> <td>1227220</td> <td>827479</td> <td>1</td> <td>0</td> <td>0.0</td> <td>0.000000</td> <td>0.0</td> <td>0</td> <td>5</td> <td>19</td> <td>...</td> <td>7.422933e-12</td> <td>7.576012e-11</td> <td>2.851301e-12</td> <td>-3.030847e-11</td> <td>9.932370e-12</td> <td>8.334294e-06</td> <td>3.858445e-12</td> <td>1.669853e-11</td> <td>6.468241e-13</td> <td>3.522524e-10</td> </tr> </tbody> </table> <p>2 rows × 57 columns</p> </div> <h2> Modelling </h2> ```python from sklearn.metrics import confusion_matrix def plot_confusion_matrix(test_y, predict_y): C = confusion_matrix(test_y, predict_y) A =(((C.T)/(C.sum(axis=1))).T) B =(C/C.sum(axis=0)) plt.figure(figsize=(20,4)) labels = [0,1] # representing A in heatmap format cmap=sns.light_palette("blue") plt.subplot(1, 3, 1) sns.heatmap(C, annot=True, cmap=cmap, fmt=".3f", xticklabels=labels, yticklabels=labels) plt.xlabel('Predicted Class') plt.ylabel('Original Class') plt.title("Confusion matrix") plt.subplot(1, 3, 2) sns.heatmap(B, annot=True, cmap=cmap, fmt=".3f", xticklabels=labels, yticklabels=labels) plt.xlabel('Predicted Class') plt.ylabel('Original Class') plt.title("Precision matrix") plt.subplot(1, 3, 3) # representing B in heatmap format sns.heatmap(A, annot=True, cmap=cmap, fmt=".3f", xticklabels=labels, yticklabels=labels) plt.xlabel('Predicted Class') plt.ylabel('Original Class') plt.title("Recall matrix") plt.show() ``` ```python global_result = pd.DataFrame(columns=['Model', 'Hyperparameters', 'Train-F1-Score', 'Test-F1-Score', 'Train-AUC', 'Test-AUC']) ``` ```python #reading from pandas import read_hdf df_final_train = read_hdf('data/fea_sample/storage_sample_stage4.h5', 'train_df',mode='r') df_final_test = read_hdf('data/fea_sample/storage_sample_stage4.h5', 'test_df',mode='r') ``` ```python df_final_train.columns ``` Index(['source_node', 'destination_node', 'indicator_link', 'jaccard_followers', 'jaccard_followees', 'cosine_followers', 'cosine_followees', 'pref_attachment', 'num_followers_s', 'num_followers_d', 'num_followees_s', 'num_followees_d', 'inter_followers', 'inter_followees', 'adar_index', 'follows_back', 'same_comp', 'shortest_path', 'weight_in', 'weight_out', 'weight_f1', 'weight_f2', 'weight_f3', 'weight_f4', 'page_rank_s', 'page_rank_d', 'katz_s', 'katz_d', 'hubs_s', 'hubs_d', 'authorities_s', 'authorities_d', 'svd_u_s_1', 'svd_u_s_2', 'svd_u_s_3', 'svd_u_s_4', 'svd_u_s_5', 'svd_u_s_6', 'svd_u_d_1', 'svd_u_d_2', 'svd_u_d_3', 'svd_u_d_4', 'svd_u_d_5', 'svd_u_d_6', 'svd_v_s_1', 'svd_v_s_2', 'svd_v_s_3', 'svd_v_s_4', 'svd_v_s_5', 'svd_v_s_6', 'svd_v_d_1', 'svd_v_d_2', 'svd_v_d_3', 'svd_v_d_4', 'svd_v_d_5', 'svd_v_d_6', 'svd_dot'], dtype='object') ```python y_train = df_final_train.indicator_link y_test = df_final_test.indicator_link ``` ```python df_final_train.drop(['source_node', 'destination_node','indicator_link'],axis=1,inplace=True) df_final_test.drop(['source_node', 'destination_node','indicator_link'],axis=1,inplace=True) ``` ```python print("The shape of Train data :",df_final_train.shape) print("The shape of Train data :",df_final_test.shape) ``` The shape of Train data : (100002, 54) The shape of Train data : (50002, 54) <h2> RandomForest Classifier with Default Parameters </h2> ```python clf = RandomForestClassifier(n_jobs=-1, random_state=42) clf.fit(df_final_train, y_train) y_pred_train = clf.predict(df_final_train) y_pred_test = clf.predict(df_final_test) y_pred_train_proba = clf.predict_proba(df_final_train)[:,1] y_pred_test_proba = clf.predict_proba(df_final_test)[:,1] f1_score_val_train = f1_score(y_train, y_pred_train) roc_auc_val_train = roc_auc_score(y_train, y_pred_train) f1_score_val_test = f1_score(y_test, y_pred_test) roc_auc_val_test = roc_auc_score(y_test, y_pred_test) global_result = global_result.append({'Model': "RandomForest", 'Hyperparameters': "Default Parameters", 'Train-F1-Score': '{0:.4}'.format(f1_score_val_train), 'Test-F1-Score': '{0:.4}'.format(f1_score_val_test), 'Train-AUC': '{0:.4}'.format(roc_auc_val_train), 'Test-AUC': '{0:.4}'.format(roc_auc_val_test) }, ignore_index=True) print("TRAIN Scores","*"*20) print("\tF1-Score: ", f1_score_val_train) print("\tROC-AUC : ", roc_auc_val_train) print("TEST Scores","*"*20) print("\tF1-Score: ", f1_score_val_test) print("\tROC-AUC : ", roc_auc_val_test) print("==================================== ROC CURVE ====================================================") # calculate roc curve fpr_train, tpr_train, thresholds = roc_curve(y_train, y_pred_train_proba) plt.plot([0, 1], [0, 1], linestyle='--') plt.plot(fpr_train, tpr_train, marker='.', label='TRAIN-AUC') fpr_test, tpr_test, thresholds = roc_curve(y_test, y_pred_test_proba) plt.plot(fpr_test, tpr_test, marker='.', label='TEST-AUC') # show the plot plt.legend() plt.show() print("====================================TRAIN CONFUSION MATRIX=========================================") plot_confusion_matrix(y_train, y_pred_train) print("====================================TEST CONFUSION MATRIX==========================================") plot_confusion_matrix(y_test, y_pred_test) ``` <h2> RandomForest Classifier with RandomSearchCV </h2> ```python parameters = { 'n_estimators': [10, 50, 100, 125, 150, 200, 300, 500], 'min_samples_leaf': [1, 2, 3, 5, 7, 9], 'min_samples_split': [2, 5, 6, 7, 8, 9] } clf = RandomForestClassifier(n_jobs=-1, random_state=42, oob_score=True) r_clf = RandomizedSearchCV(clf, param_distributions=parameters, scoring='f1', cv=5, random_state=42, n_jobs=-1, return_train_score=True) r_clf.fit(df_final_train, y_train) y_pred_train = r_clf.predict(df_final_train) y_pred_test = r_clf.predict(df_final_test) y_pred_train_proba = r_clf.predict_proba(df_final_train)[:,1] y_pred_test_proba = r_clf.predict_proba(df_final_test)[:,1] f1_score_val_train = f1_score(y_train, y_pred_train) roc_auc_val_train = roc_auc_score(y_train, y_pred_train) f1_score_val_test = f1_score(y_test, y_pred_test) roc_auc_val_test = roc_auc_score(y_test, y_pred_test) global_result = global_result.append({'Model': "RandomForest", 'Hyperparameters': r_clf.best_params_, 'Train-F1-Score': '{0:.4}'.format(f1_score_val_train), 'Test-F1-Score': '{0:.4}'.format(f1_score_val_test), 'Train-AUC': '{0:.4}'.format(roc_auc_val_train), 'Test-AUC': '{0:.4}'.format(roc_auc_val_test) }, ignore_index=True) print("*"*100) print("Best Parameters: ", r_clf.best_params_) print("*"*100) print("TRAIN Scores","*"*20) print("\tF1-Score: ", f1_score_val_train) print("\tROC-AUC : ", roc_auc_val_train) print("TEST Scores","*"*20) print("\tF1-Score: ", f1_score_val_test) print("\tROC-AUC : ", roc_auc_val_test) print("==================================== ROC CURVE ====================================================") # calculate roc curve fpr_train, tpr_train, thresholds = roc_curve(y_train, y_pred_train_proba) plt.plot([0, 1], [0, 1], linestyle='--') plt.plot(fpr_train, tpr_train, marker='.', label='TRAIN-AUC') fpr_test, tpr_test, thresholds = roc_curve(y_test, y_pred_test_proba) plt.plot(fpr_test, tpr_test, marker='.', label='TEST-AUC') # show the plot plt.legend() plt.show() print("====================================TRAIN CONFUSION MATRIX=========================================") plot_confusion_matrix(y_train, y_pred_train) print("====================================TEST CONFUSION MATRIX==========================================") plot_confusion_matrix(y_test, y_pred_test) ``` <h2> XGBoost Classifier with Default parameters </h2> ```python clf = XGBClassifier(n_jobs=-1, random_state=42) clf.fit(df_final_train, y_train) y_pred_train = clf.predict(df_final_train) y_pred_test = clf.predict(df_final_test) y_pred_train_proba = clf.predict_proba(df_final_train)[:,1] y_pred_test_proba = clf.predict_proba(df_final_test)[:,1] f1_score_val_train = f1_score(y_train, y_pred_train) roc_auc_val_train = roc_auc_score(y_train, y_pred_train) f1_score_val_test = f1_score(y_test, y_pred_test) roc_auc_val_test = roc_auc_score(y_test, y_pred_test) global_result = global_result.append({'Model': "XGBoost", 'Hyperparameters': "Default Parameters", 'Train-F1-Score': '{0:.4}'.format(f1_score_val_train), 'Test-F1-Score': '{0:.4}'.format(f1_score_val_test), 'Train-AUC': '{0:.4}'.format(roc_auc_val_train), 'Test-AUC': '{0:.4}'.format(roc_auc_val_test) }, ignore_index=True) print("TRAIN Scores","*"*20) print("\tF1-Score: ", f1_score_val_train) print("\tROC-AUC : ", roc_auc_val_train) print("TEST Scores","*"*20) print("\tF1-Score: ", f1_score_val_test) print("\tROC-AUC : ", roc_auc_val_test) print("==================================== ROC CURVE ====================================================") # calculate roc curve fpr_train, tpr_train, thresholds = roc_curve(y_train, y_pred_train_proba) plt.plot([0, 1], [0, 1], linestyle='--') plt.plot(fpr_train, tpr_train, marker='.', label='TRAIN-AUC') fpr_test, tpr_test, thresholds = roc_curve(y_test, y_pred_test_proba) plt.plot(fpr_test, tpr_test, marker='.', label='TEST-AUC') # show the plot plt.legend() plt.show() print("====================================TRAIN CONFUSION MATRIX=========================================") plot_confusion_matrix(y_train, y_pred_train) print("====================================TEST CONFUSION MATRIX==========================================") plot_confusion_matrix(y_test, y_pred_test) ``` <h2> XGBoost Classifier with RandomSearchCV </h2> ```python parameters = { 'n_estimators': [10, 50, 100, 125, 150, 175, 300], 'learning_rate': [0.1, 0.001, 0.5, 1, 0.005], 'max_depth': [2, 3, 4, 5, 7, 9], 'gamma': [0, 0.01, 0.005, 0.5, 0.001], 'min_child_weight':range(1,6,2) } clf = XGBClassifier(n_jobs=-1, random_state=42, oob_score=True) r_clf = RandomizedSearchCV(clf, param_distributions=parameters, scoring='f1', cv=5, random_state=42, n_jobs=-1, return_train_score=True) r_clf.fit(df_final_train, y_train) y_pred_train = r_clf.predict(df_final_train) y_pred_test = r_clf.predict(df_final_test) y_pred_train_proba = r_clf.predict_proba(df_final_train)[:,1] y_pred_test_proba = r_clf.predict_proba(df_final_test)[:,1] f1_score_val_train = f1_score(y_train, y_pred_train) roc_auc_val_train = roc_auc_score(y_train, y_pred_train) f1_score_val_test = f1_score(y_test, y_pred_test) roc_auc_val_test = roc_auc_score(y_test, y_pred_test) global_result = global_result.append({'Model': "XGBoost", 'Hyperparameters': r_clf.best_params_, 'Train-F1-Score': '{0:.4}'.format(f1_score_val_train), 'Test-F1-Score': '{0:.4}'.format(f1_score_val_test), 'Train-AUC': '{0:.4}'.format(roc_auc_val_train), 'Test-AUC': '{0:.4}'.format(roc_auc_val_test) }, ignore_index=True) print("*"*100) print("Best Parameters: ", r_clf.best_params_) print("*"*100) print("TRAIN Scores","*"*20) print("\tF1-Score: ", f1_score_val_train) print("\tROC-AUC : ", roc_auc_val_train) print("TEST Scores","*"*20) print("\tF1-Score: ", f1_score_val_test) print("\tROC-AUC : ", roc_auc_val_test) print("==================================== ROC CURVE ====================================================") # calculate roc curve fpr_train, tpr_train, thresholds = roc_curve(y_train, y_pred_train_proba) plt.plot([0, 1], [0, 1], linestyle='--') plt.plot(fpr_train, tpr_train, marker='.', label='TRAIN-AUC') fpr_test, tpr_test, thresholds = roc_curve(y_test, y_pred_test_proba) plt.plot(fpr_test, tpr_test, marker='.', label='TEST-AUC') # show the plot plt.legend() plt.show() print("====================================TRAIN CONFUSION MATRIX=========================================") plot_confusion_matrix(y_train, y_pred_train) print("====================================TEST CONFUSION MATRIX==========================================") plot_confusion_matrix(y_test, y_pred_test) ``` <h2> Conclusion </h2> ```python global_result ``` <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>Model</th> <th>Hyperparameters</th> <th>Train-F1-Score</th> <th>Test-F1-Score</th> <th>Train-AUC</th> <th>Test-AUC</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>RandomForest</td> <td>Default Parameters</td> <td>0.9963</td> <td>0.8881</td> <td>0.9963</td> <td>0.8973</td> </tr> <tr> <th>1</th> <td>RandomForest</td> <td>{'n_estimators': 200, 'min_samples_split': 9, 'min_samples_leaf': 1}</td> <td>0.9877</td> <td>0.9277</td> <td>0.9878</td> <td>0.9315</td> </tr> <tr> <th>2</th> <td>XGBoost</td> <td>Default Parameters</td> <td>0.9747</td> <td>0.9196</td> <td>0.9749</td> <td>0.9247</td> </tr> <tr> <th>3</th> <td>XGBoost</td> <td>{'n_estimators': 300, 'learning_rate': 0.5, 'min_child_weight': 1, 'gamma': 0.5, 'max_depth': 3}</td> <td>0.9967</td> <td>0.869</td> <td>0.9967</td> <td>0.8827</td> </tr> </tbody> </table> </div> <h2> Summary </h2> Given a directed social graph, we had to predict missing links to recommend users. The Dataset contains 2 columns - Source Node and Destination Node. The graph based dataset was converted to supervised classification learning problem. I generated training samples of good and bad links from given directed graph and for each link got some features like no of followers, has he followed back, page rank, katz score, adar index, some svd fetures of adj matrix, some weight features, preferential attachment, svd dot etc. and trained ml model based on these features to predict link. I deployed two Models - **RandomForest and XGBoost with hyperparameter tuning using RandomizedSearchCV**. Each model's performance was assessed using __F1-score and AUC score__. <h5>XGBoost with extreme hypertuning was overfitting to a little extent but RandomForest with hyperparameter tuning was performing the best with test f1 score of 0.92 and auc score of 0.93.</h5>
# Use baremodule to shave off a few KB from the serialized `.ji` file baremodule squashfs_tools_jll using Base using Base: UUID import JLLWrappers JLLWrappers.@generate_main_file_header("squashfs_tools") JLLWrappers.@generate_main_file("squashfs_tools", UUID("eed32e3e-a7c5-5bf9-9121-5cf3ab653887")) end # module squashfs_tools_jll
```python %matplotlib inline ``` Hooks for autograd saved tensors ======================= PyTorch typically computes gradients using backpropagation. However, certain operations require intermediary results to be saved in order to perform backpropagation. This tutorial walks through how these tensors are saved/retrieved and how you can define hooks to control the packing/unpacking process. This tutorial assumes you are familiar with how backpropagation works in theory. If not, read this first: https://colab.research.google.com/drive/1aWNdmYt7RcHMbUk-Xz2Cv5-cGFSWPXe0#scrollTo=AHcEJ6nXUb7W Saved tensors ------------- Training a model usually consumes more memory than running it for inference. Broadly speaking, one can say that it is because “PyTorch needs to save the computation graph, which is needed to call ``backward``”, hence the additional memory usage. One goal of this tutorial is to finetune this understanding. In fact, the graph in itself sometimes does not consume much more memory as it never copies any tensors. However, the graph can keep *references* to tensors that would otherwise have gone out of scope: those are referred to as **saved tensors**. Why does training a model (typically) requires more memory than evaluating it? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We start with a simple example: :math: `y = a \mapsto \cdot b` , for which we know the gradients of $y$ with respect to $a$ and $b$: \begin{align}\frac{\partial y}{\partial a} = b\end{align} \begin{align}\frac{\partial y}{\partial b} = a\end{align} ```python import torch a = torch.randn(5, requires_grad=True) b = torch.ones(5, requires_grad=True) y = a * b ``` Using a torchviz, we can visualize the computation graph .. figure:: https://user-images.githubusercontent.com/8019486/130124513-72e016a3-c36f-42b9-88e2-53baf3e016c5.png :width: 300 :align: center In this example, PyTorch saves intermediary values $a$ and $b$ in order to compute the gradient during the backward. .. figure:: https://user-images.githubusercontent.com/8019486/130124538-3da50977-6f0b-46d0-8909-5456ade9b598.png :width: 300 :align: center Those intermediary values (in orange above) can be accessed (for debugging purposes) by looking for attributes of the ``grad_fn`` of ``y`` which start with the prefix ``_saved``: ```python print(y.grad_fn._saved_self) print(y.grad_fn._saved_other) ``` As the computation graph grows in depth, it will store more *saved tensors*. Meanwhile, those tensors would have gone out of scope if not for the graph. ```python def f(x): return x * x x = torch.randn(5, requires_grad=True) y = f(f(f(x))) ``` .. figure:: https://user-images.githubusercontent.com/8019486/130124570-f1074098-1bb3-459e-bf5a-03bf6f65b403.png :width: 500 :align: center In the example above, executing without grad would only have kept ``x`` and ``y`` in the scope, But the graph additionnally stores ``f(x)`` and ``f(f(x)``. Hence, running a forward pass during training will be more costly in memory usage than during evaluation (more precisely, when autograd is not required). The concept of packing / unpacking ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Going back to the first example: ``y.grad_fn._saved_self`` and ``y.grad_fn._saved_other`` point to the original tensor object, respectively ``a`` and ``b``. ```python a = torch.randn(5, requires_grad=True) b = torch.ones(5, requires_grad=True) y = a * b print(y.grad_fn._saved_self is a) # True print(y.grad_fn._saved_other is b) # True ``` However, that may not always be the case. ```python a = torch.randn(5, requires_grad=True) y = torch.exp(a) print(y.grad_fn._saved_result.equal(y)) # True print(y.grad_fn._saved_result is y) # False ``` Under the hood, PyTorch has **packed** and **unpacked** the tensor ``y`` to prevent reference cycles. As a rule of thumb, you should *not* rely on the fact that accessing the tensor saved for backward will yield the same tensor object as the original tensor. They will however share the same *storage*. Saved tensors hooks ------------------- PyTorch provides an API to control how saved tensors should be packed / unpacked. ```python def pack_hook(x): print("Packing", x) return x def unpack_hook(x): print("Unpacking", x) return x a = torch.ones(5, requires_grad=True) b = torch.ones(5, requires_grad=True) * 2 with torch.autograd.graph.saved_tensors_hooks(pack_hook, unpack_hook): y = a * b y.sum().backward() ``` The ``pack_hook`` function will be called everytime an operation saves a tensor for backward. The output of ``pack_hook`` is then stored in the computation graph instead of the original tensor. The ``unpack_hook`` uses that return value to compute a new tensor, which is the one actually used during the backward pass. In general, you want ``unpack_hook(pack_hook(t))`` to be equal to ``t``. ```python x = torch.randn(5, requires_grad=True) with torch.autograd.graph.saved_tensors_hooks(lambda x: x * 4, lambda x: x / 4): y = torch.pow(x, 2) y.sum().backward() assert(x.grad.equal(2 * x)) ``` One thing to note is that the output of ``pack_hook`` can be *any Python object*, as long as ``unpack_hook`` can derive a tensor with the correct value from it. Some unconventional examples ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ First, some silly examples to illustrate what is possible but you probably don’t ever want to do it. **Returning and int** ```python # Returning the index of a Python list # Relatively harmless but with debatable usefulness storage = [] def pack(x): storage.append(x) return len(storage) - 1 def unpack(x): return storage[x] x = torch.randn(5, requires_grad=True) with torch.autograd.graph.saved_tensors_hooks(pack, unpack): y = x * x y.sum().backward() assert(x.grad.equal(2 * x)) ``` **Returning a tuple** ```python # Returning some tensor and a function how to unpack it # Quite unlikely to be useful in its current form def pack(x): delta = torch.randn(*x.size()) return x - delta, lambda x: x + delta def unpack(packed): x, f = packed return f(x) x = torch.randn(5, requires_grad=True) with torch.autograd.graph.saved_tensors_hooks(pack, unpack): y = x * x y.sum().backward() assert(torch.allclose(x.grad, 2 * x)) ``` **Returning a str** ```python # Returning the __repr__ of the tensor # Probably never do this x = torch.randn(5, requires_grad=True) with torch.autograd.graph.saved_tensors_hooks(lambda x: repr(x), lambda x: eval("torch." + x)): y = x * x y.sum().backward() assert(torch.all(x.grad - 2 * x <= 1e-4)) ``` Although those examples will not be useful in practice, they illustrate that the output of ``pack_hook`` can really be any Python object as long as it contains enough information to retrieve the content of the original tensor. In the next sections, we focus on more useful applications. Saving tensors to CPU ~~~~~~~~~~~~~~~~~~~~~ Very often, the tensors involved in the computation graph live on GPU. Keeping a reference to those tensors in the graph is what causes most models to run out of GPU memory during training while they would have done fine during evaluation. Hooks provide a very simple way to implement that. ```python def pack_hook(x): return (x.device, x.cpu()) def unpack_hook(packed): device, tensor = packed return tensor.to(device) x = torch.randn(5, requires_grad=True) with torch.autograd.graph.saved_tensors_hooks(pack, unpack): y = x * x y.sum().backward() torch.allclose(x.grad, (2 * x)) ``` In fact, PyTorch provides an API to conveniently use those hooks (as well as the ability to use pinned memory). ```python import torch.nn as nn class Model(nn.Module): def __init__(self): super().__init__() self.w = nn.Parameter(torch.randn(5)) def forward(self, x): with torch.autograd.graph.save_on_cpu(pin_memory=True): # some computation return self.w * x x = torch.randn(5) model = Model() loss = model(x).sum() loss.backward() ``` In practice, on a A100 GPU, for a resnet-152 with batch size 256, this corresponds to a GPU memory usage reduction from 48GB to 5GB, at the cost of a 6x slowdown. Of course, you can modulate the tradeoff by only saving to CPU certain parts of the network. For instance, you could define a special ``nn.Module`` that wraps any module and saves its tensors to CPU. ```python class SaveToCpu(nn.Module): def __init__(self, module): super().__init__() self.module = module def forward(self, *args, **kwargs): with torch.autograd.graph.save_on_cpu(pin_memory=True): return self.module(*args, **kwargs) model = nn.Sequential( nn.Linear(10, 100), SaveToCpu(nn.Linear(100, 100)), nn.Linear(100, 10), ) x = torch.randn(10) loss = model(x).sum() loss.backward() ``` Saving tensors to disk ~~~~~~~~~~~~~~~~~~~~~~ Similarly, you may want to save those tensors to disk. Again, this is achievable with those hooks. A naive version would look like this. ```python # Naive version - HINT: Don't do this import uuid tmp_dir = "temp" def pack_hook(tensor): name = os.path.join(tmp_dir, str(uuid.uuid4())) torch.save(tensor, name) return name def unpack_hook(name): return torch.load(name) ``` The reason the above code is bad is that we are leaking files on the disk and they are never cleared. Fixing this is not as trivial as it seems. ```python # Incorrect version - HINT: Don't do this import uuid import os import tempfile tmp_dir_obj = tempfile.TemporaryDirectory() tmp_dir = tmp_dir_obj.name def pack_hook(tensor): name = os.path.join(tmp_dir, str(uuid.uuid4())) torch.save(tensor, name) return name def unpack_hook(name): tensor = torch.load(name) os.remove(name) return tensor ``` The reason the above code doesn’t work is that ``unpack_hook`` can be called multiple times. If we delete the file during unpacking the first time, it will not be available when the saved tensor is accessed a second time, which will raise an error. ```python x = torch.ones(5, requires_grad=True) with torch.autograd.graph.saved_tensors_hooks(pack_hook, unpack_hook): y = x.pow(2) print(y.grad_fn._saved_self) try: print(y.grad_fn._saved_self) print("Double access succeeded!") except: print("Double access failed!") ``` To fix this, we can write a version of those hooks that takes advantage of the fact that PyTorch automatically releases (deletes) the saved data when it is no longer needed. ```python class SelfDeletingTempFile(): def __init__(self): self.name = os.path.join(tmp_dir, str(uuid.uuid4())) def __del__(self): os.remove(self.name) def pack_hook(tensor): temp_file = SelfDeletingTempFile() torch.save(tensor, temp_file.name) return temp_file def unpack_hook(temp_file): return torch.load(temp_file.name) ``` When we call ``backward``, the output of ``pack_hook`` will be deleted, which causes the file to be removed, so we’re no longer leaking the files. This can then be used in your model, in the following way: ```python # Only save on disk tensors that have size >= 1000 SAVE_ON_DISK_THRESHOLD = 1000 def pack_hook(x): if x.numel() < SAVE_ON_DISK_THRESHOLD: return x temp_file = SelfDeletingTempFile() torch.save(tensor, temp_file.name) return temp_file def unpack_hook(tensor_or_sctf): if isinstance(tensor_or_sctf, torch.Tensor): return tensor_or_sctf return torch.load(tensor_or_sctf.name) class SaveToDisk(nn.Module): def __init__(self, module): super().__init__() self.module = module def forward(self, *args, **kwargs): with torch.autograd.graph.saved_tensors_hooks(pack_hook, unpack_hook): return self.module(*args, **kwargs) net = nn.DataParallel(SaveToDisk(Model())) ``` In this last example, we also demonstrate how to filter which tensors should be saved (here, those whose number of elements is greater than 1000) and how to combine this feature with ``nn.DataParallel``. If you’ve made it this far, congratulations! You now know how to use saved tensor hooks and how they can be useful in a few scenarios to tradeoff memory for compute.
You can become a dire animal. Prerequisites: Cha 13, Animal Shape, base attack bonus +4, any skinwalker heritage other than bloodmarked. Benefit: When you use your Animal Shape ability, you can instead take the form of an dire animal. Your dire animal form is Large, and grants you a +4 size bonus to your Strength, a -2 penalty to your Dexterity, and a +4 natural armor bonus; the damage die for your natural attack(s) also uses the amount typical for a Large creature. You also gain all special qualities listed in the statblock for a druid’s animal companion appropriate to your animal shape. Special: Bloodmarked instead select the Dire Bat Shape feat. Wayfinder #13. © 2015, Paizo Fans United. Authors: Charlie Bell, Dylan Brooks, Jake Burnett, Jeremy Clements, Ryan Crossman, Kalyna Conrad, Sarah Counts, Matt Duval, Jeff Evans, Christoph Gimmler, Wojciech Gruchala, Garrett Guillotte, Bran Hagger, Andrew Hoskins, Kiel Howell, Jason Keeley, Joseph Kellogg, Joe Kondrak, Cole Kronewitter, Thomas LeBlanc, Jeff Lee, Christopher Lockwood, Nate Love, Ron Lundeen, Ben Martin, Matthew Medeiros, Alex J. Moore, Matt Morris, Mark Nordheim, Nicholas S. Orvis, Michael Riter, Matt Roth, Laura Sheppard, Joe Smith, Neil Spicer, Stephen Stack, Jessie Staffler, Jacob Trier, Ian Turner, Andrew Umphrey, Christopher Wasko, Nick Wasko, and Scott Young.
function [C,t,err] = cubic_vertex_removal(C1,C2,varargin) % CUBIC_VERTEX_REMOVAL Given a G¹ continuous sequence of cubic Bézier curves, % optimize the positions of a new single curve to minimize its integrated % squared distance to those curves. This requires both estimating the % parameterization mapping between the inputs and output (non-linear problem) % and then computing the optimal positions as a linear least squares problem. % % C = cubic_vertex_removal(C1,C2) % [C,t,err] = cubic_vertex_removal(C1,C2,'ParameterName',ParameterValue,…) % % Inputs: % C1 4 by dim list of first curves control point positions % C2 4 by dim list of second curves control point positions, it's assumed % that C1(4,:) == C2(1,:) and C1(4,:) - C1(3,:) = s * (C2(2,:) - C2(1,:)) % for some s>= 0. % Optional: % 'Method' followed by one of the following: % {'perfect'} use root finding. This is fastest when you only care about % finding a perfect fit. It may lead to a very poor approximate when % a perfect fit is not possible. A perfect fit is when % `[C1,C2] = cubic_split(C,t)`. If this is the case, then the % returned `err` for this method should be very close to zero. (Note % that "perfect fit" → err=0 but err=0 does not necessarily imply % "perfect fit". % 'iterative' use iterative method. This is slower but more accurate % when a perfect fit is not possible. % 'MaxIter' followed by maximum number of iterations for iterative % method {100} % 't0' followed by initial guess of t for iterative method {relative % approximate arc lengths} % 'AlreadyGenerated' followed by whether the automatically generated helper % functions cubic_vertex_removal_polyfun and cubic_vertex_removal_g % have already been generated. On some machines checking `exist()` can % be really slow. So, you could call % `cubic_vertex_removal(…,'AlreadyGenerated',false)` onces to % generate the files and the call % `cubic_vertex_removal(…,'AlreadyGenerated',true) for subsequent % calls {false}. % Outputs: % C 4 by dim list of output coordinates. By default: % C(1,:) = C1(1,:), % C(4,:) = C2(4,:), (C₀ continuity) % and % C(2,:) - C(1,:) = s1*(C1(2,:) - C1(1,:)) with s1>=0 % C(4,:) - C(3,:) = s2*(C2(4,:) - C2(3,:)) with s2>=0 (G₁ continutity) % t scalar value between [0,1] defining the piecewise-linear % parameterization mapping between the inputs and output. C1 is mapped to % [0,t] and C2 is mapped to [t1,1]. % err Integrated squared distance between the output and input curves (see % cubic_cubic_integrated_distance). % % Example: % C = [0 0;1 1;2 -1;3 0]; % tgt = 0.1; % [C1,C2] = cubic_split(C,tgt); % [C,t,err] = cubic_vertex_removal(C1,C2,'Method','perfect'); % clf; % hold on; % plot_cubic(C1,[],[],'Color',orange); % plot_cubic(C2,[],[],'Color',orange); % plot_cubic(C,[],[],'Color',blue); % hold off; % axis equal; % set(gca,'YDir','reverse') % title(sprintf('err: %g',err),'FontSize',30); % method = 'perfect'; max_iter = 100; t0 = []; promise_already_built = false; E_tol = 1e-15; grad_tol = 1e-8; % Map of parameter names to variable names params_to_variables = containers.Map( ... {'Method','MaxIter','t0','AlreadyGenerated','Tol','GradientTol',}, ... {'method','max_iter','t0','promise_already_built','E_tol','grad_tol'}); v = 1; while v <= numel(varargin) param_name = varargin{v}; if isKey(params_to_variables,param_name) assert(v+1<=numel(varargin)); v = v+1; % Trick: use feval on anonymous function to use assignin to this workspace feval(@()assignin('caller',params_to_variables(param_name),varargin{v})); else error('Unsupported parameter: %s',varargin{v}); end v=v+1; end if strcmp(method,'cubic-polish') [C,t,err] = cubic_vertex_removal(C1,C2,varargin{:},'Method','cubic'); % Slip in 'MaxIter',1 before user parameters so it gets over-written if % provided. [C,t,err] = cubic_vertex_removal(C1,C2,'MaxIter',1,varargin{:},'t0',t,'Method','iterative'); return; end switch method case {'perfect','cubic'} % _If_ t is perfect, then C is a simple function of t. C_from_t = @(C1,C2,t) ... [C1(1,:); ... (1./t)*(C1(2,:)-C1(1,:)) + C1(1,:); ... (1./(1-t))*(C2(end-1,:)-C2(end,:)) + C2(end,:); ... C2(end,:)]; switch method case 'perfect' % Build a root finder for the 1D problem if ~promise_already_built && ~exist('cubic_vertex_removal_polyfun','file'); warning('assuming L2 not l2 error'); dim = 1; % Matlab is (sometimes?) confused that this is a static workspace and % refuses to let syms create variables. %syms('iC1',[4 dim],'real'); %syms('iC2',[4 dim],'real'); %% complains if I mark st as 'real' %syms('st',[1 1]); iC1 = [ sym('iC11','real') sym('iC12','real') sym('iC13','real') sym('iC14','real')]; iC2 = [ sym('iC21','real') sym('iC22','real') sym('iC23','real') sym('iC24','real')]; st = sym('st'); sC = C_from_t(iC1,iC2,st); [oC1,oC2] = cubic_split(sC,st); % L2 style. sg = sum( [oC1-iC1;oC2-iC2].^2, 'all'); sres = solve(diff(sg,st) == 0,st); %sdgdt = simplify(diff(sg,st)); %vroots = @(C1,C2) double(vpasolve(subs(subs(sdgdt,iC1,C1),iC2,C2)==0,st,[0 1])); sres_children = children(sres(1)); % Should cache these two: %polyfun = matlabFunction(flip(coeffs(sres_children(1),sres_children(2))),'Vars',{iC1,iC2}); % Matlab2023a seems to use slightly different cell arrays for sres_children. polyfun = matlabFunction( ... flip(coeffs(sres_children{1},sres_children{2})), ... 'Vars',{iC1,iC2}, ... 'File','cubic_vertex_removal_polyfun'); g = matlabFunction(sg,'Vars',{iC1,iC2,st},'File','cubic_vertex_removal_g'); else polyfun = @cubic_vertex_removal_polyfun; g = @cubic_vertex_removal_g; end keepreal = @(C) C(imag(C)==0 & real(C)>=0 & real(C)<=1); % Using numerical roots is faster than vroots nroots = @(K1,K2) keepreal(roots(polyfun(K1,K2))); keepmin = @(ts,Es) ts(find(Es==min(Es),1)); % We'll determine t based on the 1D g function. But we'll compute the % returned energy below using the full dim-D problem. keepmin = @(K1,K2,ts) keepmin(ts,arrayfun(@(t) g(K1,K2,t),ts)); find_t = @(K1,K2) keepmin(K1,K2,nroots(K1,K2)); % Decide which coordinate to use (pick a non-degenerate one). % Based on max-extent. [~,i] = max(max([C1(1,:);C2(end,:)])-min([C1(1,:);C2(end,:)])); t = find_t(C1(:,i),C2(:,i)); assert(~isempty(t)); case 'cubic' D1 = -6.*C1(1,:) + 18.*C1(2,:) - 18.*C1(3,:) + 6.*C1(4,:); D2 = -6.*C2(1,:) + 18.*C2(2,:) - 18.*C2(3,:) + 6.*C2(4,:); D2_sqr_len = sum(D2.*D2,2); D1_sqr_len = sum(D1.*D1,2); D2_D1 = sum(D2.*D1,2); r = D2_D1/D1_sqr_len; t = (1 + (r.^(1/3))).^-1; end C = C_from_t(C1,C2,t); case 'iterative' % use arc-length to guess t₁ if isempty(t0) tol = 1e-5; ts = matrixnormalize(cumsum([0;spline_arc_lengths([C1;C2],[1 2 3 4;5 6 7 8],tol)])); t0 = ts(2); end t1 = t0; % Build null space matrices. so that C(:) = S*V + B(:) satisfies C₀ and G₁ % constraints for any V B = [C1(1,:);C1(1,:);C2(4,:);C2(4,:)]; B1 = [0 0;(C1(2,:) - C1(1,:));0 0;0 0]; B2 = [0 0;0 0;(C2(3,:) - C2(4,:));0 0]; S = [B1(:) B2(:)]; f = @(t1) objective_t1(C1,C2,t1,B,S); [E,C] = f(t1); for iter = 1:max_iter %dfdt1 = (f(t1+1e-5)-f(t1-1e-5))/(2*1e-5); % Complex step is bit faster and more accurate/stable. For 1D input, I % believe this should be as good as autodiff and probably as good as we % can get without a lot of hand derivativation/compiling code. dfdt1 = imag(f(complex(t1,1e-100)))/1e-100; if norm(dfdt1,inf) < grad_tol break; end dt1 = 0.5*sign(-dfdt1); [alpha,t1] = backtracking_line_search(f,t1,dfdt1,dt1,0.3,0.5); if alpha == 0 %warning('line search failed'); break; end [E,C] = f(t1); if E < E_tol break; end end t = t1; otherwise error(['unknown method :' method]); end if nargout>2 % L2 not l2 [E1] = cubic_cubic_integrated_distance( ... 0,t, ... 1/t,0, ... C1, ... 1,0, ... C); [E2] = cubic_cubic_integrated_distance( ... t,1, ... 1/(1-t),-t/(1-t), ... C2, ... 1,0, ... C); err = E1+E2; end % Helper functions for iterative method function [E,C] = objective_t1(C1,C2,t1,B,S) if isfloat(t1) && (t1>1 || t1<0) E = inf; return; end C = nan(4,2); [~,H,F,c] = objective(C1,C2,C,t1); % Enforce constraints via subspace % C = [ % C1(1,:) % C1(1,:) + v1 * (C1(2,:) - C1(1,:)) % C2(4,:) + v2 * (C2(3,:) - C2(4,:)) % C2(4,:) % ]; HH = repdiag(H,2); V = ((S.'*HH*S)\(-S.'*F(:)-S.'*HH*B(:))); V = max(V,0); C = reshape( B(:) + S*V , size(C)); [E] = objective(C1,C2,C,t1); end function [E,H,F,c] = objective(C1,C2,C,t1) if isfloat(t1) && (t1>1 || t1<0) E = inf; return; end % WARNING w1 = 1; w2 = 1; %w1 = t1; %w2 = 1-t1; if nargout == 4 % Given t1 update C [H1,F1,c1,E1] = cubic_cubic_integrated_distance( ... 0,t1, ... 1/t1,0, ... C1, ... 1,0, ... C); [H2,F2,c2,E2] = cubic_cubic_integrated_distance( ... t1,1, ... 1/(1-t1),-t1/(1-t1), ... C2, ... 1,0, ... C); % Equal weighting ("L2") H = w1*H1 + w2*H2; F = w1*F1 + w2*F2; c = w1*c1 + w2*c2; else % Given t1 update C [E1] = cubic_cubic_integrated_distance( ... 0,t1, ... 1/t1,0, ... C1, ... 1,0, ... C); [E2] = cubic_cubic_integrated_distance( ... t1,1, ... 1/(1-t1),-t1/(1-t1), ... C2, ... 1,0, ... C); end E = w1*E1 + w2*E2; end end
[STATEMENT] lemma pw_abs_nofail[refine_pw_simps]: "nofail (\<Up>R M) \<longleftrightarrow> (nofail M \<and> (\<forall>x. inres M x \<longrightarrow> x\<in>Domain R))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. nofail (\<Up> R M) = (nofail M \<and> (\<forall>x. inres M x \<longrightarrow> x \<in> Domain R)) [PROOF STEP] apply (cases M) [PROOF STATE] proof (prove) goal (2 subgoals): 1. M = FAIL \<Longrightarrow> nofail (\<Up> R M) = (nofail M \<and> (\<forall>x. inres M x \<longrightarrow> x \<in> Domain R)) 2. \<And>X. M = RES X \<Longrightarrow> nofail (\<Up> R M) = (nofail M \<and> (\<forall>x. inres M x \<longrightarrow> x \<in> Domain R)) [PROOF STEP] apply simp [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>X. M = RES X \<Longrightarrow> nofail (\<Up> R M) = (nofail M \<and> (\<forall>x. inres M x \<longrightarrow> x \<in> Domain R)) [PROOF STEP] apply (auto simp: abs_fun_simps abs_fun_def) [PROOF STATE] proof (prove) goal: No subgoals! [PROOF STEP] done
[STATEMENT] lemma inters_fin_fund: "finite{(t, u). s setinterleaves ((t, u), A)}" [PROOF STATE] proof (prove) goal (1 subgoal): 1. finite {(t, u). s setinterleaves ((t, u), A)} [PROOF STEP] proof (induction "length s" arbitrary:s rule:nat_less_induct) [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>s. \<forall>m<length s. \<forall>x. m = length x \<longrightarrow> finite {(t, u). x setinterleaves ((t, u), A)} \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A)} [PROOF STEP] case 1 [PROOF STATE] proof (state) this: \<forall>m<length s. \<forall>x. m = length x \<longrightarrow> finite {(t, u). x setinterleaves ((t, u), A)} goal (1 subgoal): 1. \<And>s. \<forall>m<length s. \<forall>x. m = length x \<longrightarrow> finite {(t, u). x setinterleaves ((t, u), A)} \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A)} [PROOF STEP] have A:"{(t, u). s setinterleaves((t, u), A)} \<subseteq> {([],[])} \<union> {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists> a list. t = a#list \<and> a \<notin> A) \<and> u = []} \<union> {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists> a list. u = a#list \<and> a \<notin> A) \<and> t = []} \<union> {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists> a list aa lista. u = a#list \<and> t = aa#lista)}" (is "?A \<subseteq> {([],[])} \<union> ?B \<union> ?C \<union> ?D") [PROOF STATE] proof (prove) goal (1 subgoal): 1. {(t, u). s setinterleaves ((t, u), A)} \<subseteq> {([], [])} \<union> {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. t = a # list \<and> a \<notin> A) \<and> u = []} \<union> {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. u = a # list \<and> a \<notin> A) \<and> t = []} \<union> {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} [PROOF STEP] apply (rule subsetI, safe) [PROOF STATE] proof (prove) goal (8 subgoals): 1. \<And>a b. \<lbrakk>(a, b) \<notin> {}; s setinterleaves ((a, b), A); a \<noteq> []; \<nexists>aa list aaa lista. b = aa # list \<and> a = aaa # lista; \<nexists>a list. b = a # list \<and> a \<notin> A\<rbrakk> \<Longrightarrow> \<exists>aa list. a = aa # list \<and> aa \<notin> A 2. \<And>a b. \<lbrakk>(a, b) \<notin> {}; s setinterleaves ((a, b), A); a \<noteq> []; \<nexists>aa list aaa lista. b = aa # list \<and> a = aaa # lista; \<nexists>a list. b = a # list \<and> a \<notin> A\<rbrakk> \<Longrightarrow> b = [] 3. \<And>a b. \<lbrakk>(a, b) \<notin> {}; s setinterleaves ((a, b), A); a \<noteq> []; \<nexists>aa list aaa lista. b = aa # list \<and> a = aaa # lista; a \<noteq> []\<rbrakk> \<Longrightarrow> \<exists>aa list. a = aa # list \<and> aa \<notin> A 4. \<And>a b. \<lbrakk>(a, b) \<notin> {}; s setinterleaves ((a, b), A); a \<noteq> []; \<nexists>aa list aaa lista. b = aa # list \<and> a = aaa # lista; a \<noteq> []\<rbrakk> \<Longrightarrow> b = [] 5. \<And>a b. \<lbrakk>(a, b) \<notin> {}; s setinterleaves ((a, b), A); b \<noteq> []; \<nexists>aa list aaa lista. b = aa # list \<and> a = aaa # lista; \<nexists>a list. b = a # list \<and> a \<notin> A\<rbrakk> \<Longrightarrow> \<exists>aa list. a = aa # list \<and> aa \<notin> A 6. \<And>a b. \<lbrakk>(a, b) \<notin> {}; s setinterleaves ((a, b), A); b \<noteq> []; \<nexists>aa list aaa lista. b = aa # list \<and> a = aaa # lista; \<nexists>a list. b = a # list \<and> a \<notin> A\<rbrakk> \<Longrightarrow> b = [] 7. \<And>a b. \<lbrakk>(a, b) \<notin> {}; s setinterleaves ((a, b), A); b \<noteq> []; \<nexists>aa list aaa lista. b = aa # list \<and> a = aaa # lista; a \<noteq> []\<rbrakk> \<Longrightarrow> \<exists>aa list. a = aa # list \<and> aa \<notin> A 8. \<And>a b. \<lbrakk>(a, b) \<notin> {}; s setinterleaves ((a, b), A); b \<noteq> []; \<nexists>aa list aaa lista. b = aa # list \<and> a = aaa # lista; a \<noteq> []\<rbrakk> \<Longrightarrow> b = [] [PROOF STEP] apply(simp_all add: neq_Nil_conv) [PROOF STATE] proof (prove) goal (6 subgoals): 1. \<And>a b. \<lbrakk>s setinterleaves ((a, b), A); \<exists>y ys. a = y # ys; \<forall>a list. b \<noteq> a # list\<rbrakk> \<Longrightarrow> \<exists>aa. (\<exists>list. a = aa # list) \<and> aa \<notin> A 2. \<And>a b. \<lbrakk>s setinterleaves ((a, b), A); \<exists>y ys. a = y # ys; \<forall>a list. b \<noteq> a # list\<rbrakk> \<Longrightarrow> b = [] 3. \<And>a b. \<lbrakk>s setinterleaves ((a, b), A); (\<forall>a list. b \<noteq> a # list) \<or> (\<forall>aa lista. a \<noteq> aa # lista); \<exists>y ys. a = y # ys\<rbrakk> \<Longrightarrow> \<exists>aa. (\<exists>list. a = aa # list) \<and> aa \<notin> A 4. \<And>a b. \<lbrakk>s setinterleaves ((a, b), A); (\<forall>a list. b \<noteq> a # list) \<or> (\<forall>aa lista. a \<noteq> aa # lista); \<exists>y ys. a = y # ys\<rbrakk> \<Longrightarrow> b = [] 5. \<And>a b. \<lbrakk>s setinterleaves ((a, b), A); \<exists>y ys. b = y # ys; \<forall>aa lista. a \<noteq> aa # lista; \<forall>a. (\<forall>list. b \<noteq> a # list) \<or> a \<in> A\<rbrakk> \<Longrightarrow> False 6. \<And>a b. \<lbrakk>s setinterleaves ((a, b), A); \<exists>y ys. b = y # ys; \<forall>aa lista. a \<noteq> aa # lista; \<forall>a. (\<forall>list. b \<noteq> a # list) \<or> a \<in> A\<rbrakk> \<Longrightarrow> b = [] [PROOF STEP] apply (metis Sync.si_empty2 Sync.sym empty_iff list.exhaust_sel) [PROOF STATE] proof (prove) goal (5 subgoals): 1. \<And>a b. \<lbrakk>s setinterleaves ((a, b), A); \<exists>y ys. a = y # ys; \<forall>a list. b \<noteq> a # list\<rbrakk> \<Longrightarrow> b = [] 2. \<And>a b. \<lbrakk>s setinterleaves ((a, b), A); (\<forall>a list. b \<noteq> a # list) \<or> (\<forall>aa lista. a \<noteq> aa # lista); \<exists>y ys. a = y # ys\<rbrakk> \<Longrightarrow> \<exists>aa. (\<exists>list. a = aa # list) \<and> aa \<notin> A 3. \<And>a b. \<lbrakk>s setinterleaves ((a, b), A); (\<forall>a list. b \<noteq> a # list) \<or> (\<forall>aa lista. a \<noteq> aa # lista); \<exists>y ys. a = y # ys\<rbrakk> \<Longrightarrow> b = [] 4. \<And>a b. \<lbrakk>s setinterleaves ((a, b), A); \<exists>y ys. b = y # ys; \<forall>aa lista. a \<noteq> aa # lista; \<forall>a. (\<forall>list. b \<noteq> a # list) \<or> a \<in> A\<rbrakk> \<Longrightarrow> False 5. \<And>a b. \<lbrakk>s setinterleaves ((a, b), A); \<exists>y ys. b = y # ys; \<forall>aa lista. a \<noteq> aa # lista; \<forall>a. (\<forall>list. b \<noteq> a # list) \<or> a \<in> A\<rbrakk> \<Longrightarrow> b = [] [PROOF STEP] using list.exhaust_sel [PROOF STATE] proof (prove) using this: \<lbrakk>?list = [] \<Longrightarrow> ?P; ?list = hd ?list # tl ?list \<Longrightarrow> ?P\<rbrakk> \<Longrightarrow> ?P goal (5 subgoals): 1. \<And>a b. \<lbrakk>s setinterleaves ((a, b), A); \<exists>y ys. a = y # ys; \<forall>a list. b \<noteq> a # list\<rbrakk> \<Longrightarrow> b = [] 2. \<And>a b. \<lbrakk>s setinterleaves ((a, b), A); (\<forall>a list. b \<noteq> a # list) \<or> (\<forall>aa lista. a \<noteq> aa # lista); \<exists>y ys. a = y # ys\<rbrakk> \<Longrightarrow> \<exists>aa. (\<exists>list. a = aa # list) \<and> aa \<notin> A 3. \<And>a b. \<lbrakk>s setinterleaves ((a, b), A); (\<forall>a list. b \<noteq> a # list) \<or> (\<forall>aa lista. a \<noteq> aa # lista); \<exists>y ys. a = y # ys\<rbrakk> \<Longrightarrow> b = [] 4. \<And>a b. \<lbrakk>s setinterleaves ((a, b), A); \<exists>y ys. b = y # ys; \<forall>aa lista. a \<noteq> aa # lista; \<forall>a. (\<forall>list. b \<noteq> a # list) \<or> a \<in> A\<rbrakk> \<Longrightarrow> False 5. \<And>a b. \<lbrakk>s setinterleaves ((a, b), A); \<exists>y ys. b = y # ys; \<forall>aa lista. a \<noteq> aa # lista; \<forall>a. (\<forall>list. b \<noteq> a # list) \<or> a \<in> A\<rbrakk> \<Longrightarrow> b = [] [PROOF STEP] apply blast [PROOF STATE] proof (prove) goal (4 subgoals): 1. \<And>a b. \<lbrakk>s setinterleaves ((a, b), A); (\<forall>a list. b \<noteq> a # list) \<or> (\<forall>aa lista. a \<noteq> aa # lista); \<exists>y ys. a = y # ys\<rbrakk> \<Longrightarrow> \<exists>aa. (\<exists>list. a = aa # list) \<and> aa \<notin> A 2. \<And>a b. \<lbrakk>s setinterleaves ((a, b), A); (\<forall>a list. b \<noteq> a # list) \<or> (\<forall>aa lista. a \<noteq> aa # lista); \<exists>y ys. a = y # ys\<rbrakk> \<Longrightarrow> b = [] 3. \<And>a b. \<lbrakk>s setinterleaves ((a, b), A); \<exists>y ys. b = y # ys; \<forall>aa lista. a \<noteq> aa # lista; \<forall>a. (\<forall>list. b \<noteq> a # list) \<or> a \<in> A\<rbrakk> \<Longrightarrow> False 4. \<And>a b. \<lbrakk>s setinterleaves ((a, b), A); \<exists>y ys. b = y # ys; \<forall>aa lista. a \<noteq> aa # lista; \<forall>a. (\<forall>list. b \<noteq> a # list) \<or> a \<in> A\<rbrakk> \<Longrightarrow> b = [] [PROOF STEP] apply (metis Sync.sym emptyLeftNonSync list.exhaust_sel list.set_intros(1)) [PROOF STATE] proof (prove) goal (3 subgoals): 1. \<And>a b. \<lbrakk>s setinterleaves ((a, b), A); (\<forall>a list. b \<noteq> a # list) \<or> (\<forall>aa lista. a \<noteq> aa # lista); \<exists>y ys. a = y # ys\<rbrakk> \<Longrightarrow> b = [] 2. \<And>a b. \<lbrakk>s setinterleaves ((a, b), A); \<exists>y ys. b = y # ys; \<forall>aa lista. a \<noteq> aa # lista; \<forall>a. (\<forall>list. b \<noteq> a # list) \<or> a \<in> A\<rbrakk> \<Longrightarrow> False 3. \<And>a b. \<lbrakk>s setinterleaves ((a, b), A); \<exists>y ys. b = y # ys; \<forall>aa lista. a \<noteq> aa # lista; \<forall>a. (\<forall>list. b \<noteq> a # list) \<or> a \<in> A\<rbrakk> \<Longrightarrow> b = [] [PROOF STEP] using list.exhaust_sel [PROOF STATE] proof (prove) using this: \<lbrakk>?list = [] \<Longrightarrow> ?P; ?list = hd ?list # tl ?list \<Longrightarrow> ?P\<rbrakk> \<Longrightarrow> ?P goal (3 subgoals): 1. \<And>a b. \<lbrakk>s setinterleaves ((a, b), A); (\<forall>a list. b \<noteq> a # list) \<or> (\<forall>aa lista. a \<noteq> aa # lista); \<exists>y ys. a = y # ys\<rbrakk> \<Longrightarrow> b = [] 2. \<And>a b. \<lbrakk>s setinterleaves ((a, b), A); \<exists>y ys. b = y # ys; \<forall>aa lista. a \<noteq> aa # lista; \<forall>a. (\<forall>list. b \<noteq> a # list) \<or> a \<in> A\<rbrakk> \<Longrightarrow> False 3. \<And>a b. \<lbrakk>s setinterleaves ((a, b), A); \<exists>y ys. b = y # ys; \<forall>aa lista. a \<noteq> aa # lista; \<forall>a. (\<forall>list. b \<noteq> a # list) \<or> a \<in> A\<rbrakk> \<Longrightarrow> b = [] [PROOF STEP] apply blast [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<And>a b. \<lbrakk>s setinterleaves ((a, b), A); \<exists>y ys. b = y # ys; \<forall>aa lista. a \<noteq> aa # lista; \<forall>a. (\<forall>list. b \<noteq> a # list) \<or> a \<in> A\<rbrakk> \<Longrightarrow> False 2. \<And>a b. \<lbrakk>s setinterleaves ((a, b), A); \<exists>y ys. b = y # ys; \<forall>aa lista. a \<noteq> aa # lista; \<forall>a. (\<forall>list. b \<noteq> a # list) \<or> a \<in> A\<rbrakk> \<Longrightarrow> b = [] [PROOF STEP] apply (metis emptyLeftNonSync list.exhaust_sel list.set_intros(1)) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>a b. \<lbrakk>s setinterleaves ((a, b), A); \<exists>y ys. b = y # ys; \<forall>aa lista. a \<noteq> aa # lista; \<forall>a. (\<forall>list. b \<noteq> a # list) \<or> a \<in> A\<rbrakk> \<Longrightarrow> b = [] [PROOF STEP] by (metis Sync.si_empty2 Sync.sym empty_iff list.exhaust_sel) [PROOF STATE] proof (state) this: {(t, u). s setinterleaves ((t, u), A)} \<subseteq> {([], [])} \<union> {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. t = a # list \<and> a \<notin> A) \<and> u = []} \<union> {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. u = a # list \<and> a \<notin> A) \<and> t = []} \<union> {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} goal (1 subgoal): 1. \<And>s. \<forall>m<length s. \<forall>x. m = length x \<longrightarrow> finite {(t, u). x setinterleaves ((t, u), A)} \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A)} [PROOF STEP] have a1:"?B \<subseteq> { ((hd s#list), [])| list. (tl s) setinterleaves ((list, []), A) \<and> (hd s) \<notin> A}" (is "?B \<subseteq> ?B1") [PROOF STATE] proof (prove) goal (1 subgoal): 1. {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. t = a # list \<and> a \<notin> A) \<and> u = []} \<subseteq> {(hd s # list, []) |list. tl s setinterleaves ((list, []), A) \<and> hd s \<notin> A} [PROOF STEP] by auto [PROOF STATE] proof (state) this: {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. t = a # list \<and> a \<notin> A) \<and> u = []} \<subseteq> {(hd s # list, []) |list. tl s setinterleaves ((list, []), A) \<and> hd s \<notin> A} goal (1 subgoal): 1. \<And>s. \<forall>m<length s. \<forall>x. m = length x \<longrightarrow> finite {(t, u). x setinterleaves ((t, u), A)} \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A)} [PROOF STEP] define f where a2:"f = (\<lambda>a (t, (u::'a event list)). ((a::'a event)#t, ([]::'a event list)))" [PROOF STATE] proof (state) this: f = (\<lambda>a (t, u). (a # t, [])) goal (1 subgoal): 1. \<And>s. \<forall>m<length s. \<forall>x. m = length x \<longrightarrow> finite {(t, u). x setinterleaves ((t, u), A)} \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A)} [PROOF STEP] have a3:"?B1 \<subseteq> {(hd s # list, []) |list. tl s setinterleaves ((list, []), A)} " (is "?B1 \<subseteq> ?B2") [PROOF STATE] proof (prove) goal (1 subgoal): 1. {(hd s # list, []) |list. tl s setinterleaves ((list, []), A) \<and> hd s \<notin> A} \<subseteq> {(hd s # list, []) |list. tl s setinterleaves ((list, []), A)} [PROOF STEP] by blast [PROOF STATE] proof (state) this: {(hd s # list, []) |list. tl s setinterleaves ((list, []), A) \<and> hd s \<notin> A} \<subseteq> {(hd s # list, []) |list. tl s setinterleaves ((list, []), A)} goal (1 subgoal): 1. \<And>s. \<forall>m<length s. \<forall>x. m = length x \<longrightarrow> finite {(t, u). x setinterleaves ((t, u), A)} \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A)} [PROOF STEP] from a1 a3 [PROOF STATE] proof (chain) picking this: {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. t = a # list \<and> a \<notin> A) \<and> u = []} \<subseteq> {(hd s # list, []) |list. tl s setinterleaves ((list, []), A) \<and> hd s \<notin> A} {(hd s # list, []) |list. tl s setinterleaves ((list, []), A) \<and> hd s \<notin> A} \<subseteq> {(hd s # list, []) |list. tl s setinterleaves ((list, []), A)} [PROOF STEP] have a13:"?B \<subseteq> ?B2" [PROOF STATE] proof (prove) using this: {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. t = a # list \<and> a \<notin> A) \<and> u = []} \<subseteq> {(hd s # list, []) |list. tl s setinterleaves ((list, []), A) \<and> hd s \<notin> A} {(hd s # list, []) |list. tl s setinterleaves ((list, []), A) \<and> hd s \<notin> A} \<subseteq> {(hd s # list, []) |list. tl s setinterleaves ((list, []), A)} goal (1 subgoal): 1. {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. t = a # list \<and> a \<notin> A) \<and> u = []} \<subseteq> {(hd s # list, []) |list. tl s setinterleaves ((list, []), A)} [PROOF STEP] by simp [PROOF STATE] proof (state) this: {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. t = a # list \<and> a \<notin> A) \<and> u = []} \<subseteq> {(hd s # list, []) |list. tl s setinterleaves ((list, []), A)} goal (1 subgoal): 1. \<And>s. \<forall>m<length s. \<forall>x. m = length x \<longrightarrow> finite {(t, u). x setinterleaves ((t, u), A)} \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A)} [PROOF STEP] have AA: "finite ?B" [PROOF STATE] proof (prove) goal (1 subgoal): 1. finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. t = a # list \<and> a \<notin> A) \<and> u = []} [PROOF STEP] proof (cases s) [PROOF STATE] proof (state) goal (2 subgoals): 1. s = [] \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. t = a # list \<and> a \<notin> A) \<and> u = []} 2. \<And>a list. s = a # list \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. t = a # list \<and> a \<notin> A) \<and> u = []} [PROOF STEP] case Nil [PROOF STATE] proof (state) this: s = [] goal (2 subgoals): 1. s = [] \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. t = a # list \<and> a \<notin> A) \<and> u = []} 2. \<And>a list. s = a # list \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. t = a # list \<and> a \<notin> A) \<and> u = []} [PROOF STEP] then [PROOF STATE] proof (chain) picking this: s = [] [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: s = [] goal (1 subgoal): 1. finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. t = a # list \<and> a \<notin> A) \<and> u = []} [PROOF STEP] using not_finite_existsD [PROOF STATE] proof (prove) using this: s = [] infinite {a. ?P a} \<Longrightarrow> \<exists>a. ?P a goal (1 subgoal): 1. finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. t = a # list \<and> a \<notin> A) \<and> u = []} [PROOF STEP] by fastforce [PROOF STATE] proof (state) this: finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. t = a # list \<and> a \<notin> A) \<and> u = []} goal (1 subgoal): 1. \<And>a list. s = a # list \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. t = a # list \<and> a \<notin> A) \<and> u = []} [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>a list. s = a # list \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. t = a # list \<and> a \<notin> A) \<and> u = []} [PROOF STEP] case (Cons a list) [PROOF STATE] proof (state) this: s = a # list goal (1 subgoal): 1. \<And>a list. s = a # list \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. t = a # list \<and> a \<notin> A) \<and> u = []} [PROOF STEP] hence aa:"finite{(t,u).(tl s) setinterleaves((t, u), A)}" [PROOF STATE] proof (prove) using this: s = a # list goal (1 subgoal): 1. finite {(t, u). tl s setinterleaves ((t, u), A)} [PROOF STEP] using 1[THEN spec, of "length (tl s)"] [PROOF STATE] proof (prove) using this: s = a # list length (tl s) < length s \<longrightarrow> (\<forall>x. length (tl s) = length x \<longrightarrow> finite {(t, u). x setinterleaves ((t, u), A)}) goal (1 subgoal): 1. finite {(t, u). tl s setinterleaves ((t, u), A)} [PROOF STEP] by (simp) [PROOF STATE] proof (state) this: finite {(t, u). tl s setinterleaves ((t, u), A)} goal (1 subgoal): 1. \<And>a list. s = a # list \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. t = a # list \<and> a \<notin> A) \<and> u = []} [PROOF STEP] have "{(hd s#list, [])|list. tl s setinterleaves((list,[]),A)}\<subseteq>(\<lambda>(t, u).f(hd s)(t, u)) `{(t, u). tl s setinterleaves ((t, u), A)}" [PROOF STATE] proof (prove) goal (1 subgoal): 1. {(hd s # list, []) |list. tl s setinterleaves ((list, []), A)} \<subseteq> (\<lambda>(t, u). f (hd s) (t, u)) ` {(t, u). tl s setinterleaves ((t, u), A)} [PROOF STEP] using a2 [PROOF STATE] proof (prove) using this: f = (\<lambda>a (t, u). (a # t, [])) goal (1 subgoal): 1. {(hd s # list, []) |list. tl s setinterleaves ((list, []), A)} \<subseteq> (\<lambda>(t, u). f (hd s) (t, u)) ` {(t, u). tl s setinterleaves ((t, u), A)} [PROOF STEP] by auto [PROOF STATE] proof (state) this: {(hd s # list, []) |list. tl s setinterleaves ((list, []), A)} \<subseteq> (\<lambda>(t, u). f (hd s) (t, u)) ` {(t, u). tl s setinterleaves ((t, u), A)} goal (1 subgoal): 1. \<And>a list. s = a # list \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. t = a # list \<and> a \<notin> A) \<and> u = []} [PROOF STEP] hence "finite ?B2" [PROOF STATE] proof (prove) using this: {(hd s # list, []) |list. tl s setinterleaves ((list, []), A)} \<subseteq> (\<lambda>(t, u). f (hd s) (t, u)) ` {(t, u). tl s setinterleaves ((t, u), A)} goal (1 subgoal): 1. finite {(hd s # list, []) |list. tl s setinterleaves ((list, []), A)} [PROOF STEP] using finite_imageI [of "{(t, u). (tl s) setinterleaves ((t, u), A)}" "\<lambda>(t, u). f (hd s) (t, u)", OF aa] [PROOF STATE] proof (prove) using this: {(hd s # list, []) |list. tl s setinterleaves ((list, []), A)} \<subseteq> (\<lambda>(t, u). f (hd s) (t, u)) ` {(t, u). tl s setinterleaves ((t, u), A)} finite ((\<lambda>(t, u). f (hd s) (t, u)) ` {(t, u). tl s setinterleaves ((t, u), A)}) goal (1 subgoal): 1. finite {(hd s # list, []) |list. tl s setinterleaves ((list, []), A)} [PROOF STEP] using rev_finite_subset [PROOF STATE] proof (prove) using this: {(hd s # list, []) |list. tl s setinterleaves ((list, []), A)} \<subseteq> (\<lambda>(t, u). f (hd s) (t, u)) ` {(t, u). tl s setinterleaves ((t, u), A)} finite ((\<lambda>(t, u). f (hd s) (t, u)) ` {(t, u). tl s setinterleaves ((t, u), A)}) \<lbrakk>finite ?B; ?A \<subseteq> ?B\<rbrakk> \<Longrightarrow> finite ?A goal (1 subgoal): 1. finite {(hd s # list, []) |list. tl s setinterleaves ((list, []), A)} [PROOF STEP] by auto [PROOF STATE] proof (state) this: finite {(hd s # list, []) |list. tl s setinterleaves ((list, []), A)} goal (1 subgoal): 1. \<And>a list. s = a # list \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. t = a # list \<and> a \<notin> A) \<and> u = []} [PROOF STEP] then [PROOF STATE] proof (chain) picking this: finite {(hd s # list, []) |list. tl s setinterleaves ((list, []), A)} [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: finite {(hd s # list, []) |list. tl s setinterleaves ((list, []), A)} goal (1 subgoal): 1. finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. t = a # list \<and> a \<notin> A) \<and> u = []} [PROOF STEP] using a13 [PROOF STATE] proof (prove) using this: finite {(hd s # list, []) |list. tl s setinterleaves ((list, []), A)} {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. t = a # list \<and> a \<notin> A) \<and> u = []} \<subseteq> {(hd s # list, []) |list. tl s setinterleaves ((list, []), A)} goal (1 subgoal): 1. finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. t = a # list \<and> a \<notin> A) \<and> u = []} [PROOF STEP] by (meson rev_finite_subset) [PROOF STATE] proof (state) this: finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. t = a # list \<and> a \<notin> A) \<and> u = []} goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. t = a # list \<and> a \<notin> A) \<and> u = []} goal (1 subgoal): 1. \<And>s. \<forall>m<length s. \<forall>x. m = length x \<longrightarrow> finite {(t, u). x setinterleaves ((t, u), A)} \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A)} [PROOF STEP] have a1:"?C \<subseteq> { ([],(hd s#list))| list. (tl s) setinterleaves (([],list), A) \<and> (hd s) \<notin> A}" (is "?C \<subseteq> ?C1") [PROOF STATE] proof (prove) goal (1 subgoal): 1. {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. u = a # list \<and> a \<notin> A) \<and> t = []} \<subseteq> {([], hd s # list) |list. tl s setinterleaves (([], list), A) \<and> hd s \<notin> A} [PROOF STEP] by auto [PROOF STATE] proof (state) this: {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. u = a # list \<and> a \<notin> A) \<and> t = []} \<subseteq> {([], hd s # list) |list. tl s setinterleaves (([], list), A) \<and> hd s \<notin> A} goal (1 subgoal): 1. \<And>s. \<forall>m<length s. \<forall>x. m = length x \<longrightarrow> finite {(t, u). x setinterleaves ((t, u), A)} \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A)} [PROOF STEP] define f where a2:"f = (\<lambda>a ((t::'a event list), u). (([]::'a event list), (a::'a event)#u))" [PROOF STATE] proof (state) this: f = (\<lambda>a (t, u). ([], a # u)) goal (1 subgoal): 1. \<And>s. \<forall>m<length s. \<forall>x. m = length x \<longrightarrow> finite {(t, u). x setinterleaves ((t, u), A)} \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A)} [PROOF STEP] have a3:"?C1 \<subseteq> {([],hd s # list) |list. tl s setinterleaves (([],list), A)} " (is "?C1 \<subseteq> ?C2") [PROOF STATE] proof (prove) goal (1 subgoal): 1. {([], hd s # list) |list. tl s setinterleaves (([], list), A) \<and> hd s \<notin> A} \<subseteq> {([], hd s # list) |list. tl s setinterleaves (([], list), A)} [PROOF STEP] by blast [PROOF STATE] proof (state) this: {([], hd s # list) |list. tl s setinterleaves (([], list), A) \<and> hd s \<notin> A} \<subseteq> {([], hd s # list) |list. tl s setinterleaves (([], list), A)} goal (1 subgoal): 1. \<And>s. \<forall>m<length s. \<forall>x. m = length x \<longrightarrow> finite {(t, u). x setinterleaves ((t, u), A)} \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A)} [PROOF STEP] from a1 a3 [PROOF STATE] proof (chain) picking this: {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. u = a # list \<and> a \<notin> A) \<and> t = []} \<subseteq> {([], hd s # list) |list. tl s setinterleaves (([], list), A) \<and> hd s \<notin> A} {([], hd s # list) |list. tl s setinterleaves (([], list), A) \<and> hd s \<notin> A} \<subseteq> {([], hd s # list) |list. tl s setinterleaves (([], list), A)} [PROOF STEP] have a13:"?C \<subseteq> ?C2" [PROOF STATE] proof (prove) using this: {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. u = a # list \<and> a \<notin> A) \<and> t = []} \<subseteq> {([], hd s # list) |list. tl s setinterleaves (([], list), A) \<and> hd s \<notin> A} {([], hd s # list) |list. tl s setinterleaves (([], list), A) \<and> hd s \<notin> A} \<subseteq> {([], hd s # list) |list. tl s setinterleaves (([], list), A)} goal (1 subgoal): 1. {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. u = a # list \<and> a \<notin> A) \<and> t = []} \<subseteq> {([], hd s # list) |list. tl s setinterleaves (([], list), A)} [PROOF STEP] by simp [PROOF STATE] proof (state) this: {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. u = a # list \<and> a \<notin> A) \<and> t = []} \<subseteq> {([], hd s # list) |list. tl s setinterleaves (([], list), A)} goal (1 subgoal): 1. \<And>s. \<forall>m<length s. \<forall>x. m = length x \<longrightarrow> finite {(t, u). x setinterleaves ((t, u), A)} \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A)} [PROOF STEP] have AAA:"finite ?C" [PROOF STATE] proof (prove) goal (1 subgoal): 1. finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. u = a # list \<and> a \<notin> A) \<and> t = []} [PROOF STEP] proof (cases s) [PROOF STATE] proof (state) goal (2 subgoals): 1. s = [] \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. u = a # list \<and> a \<notin> A) \<and> t = []} 2. \<And>a list. s = a # list \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. u = a # list \<and> a \<notin> A) \<and> t = []} [PROOF STEP] case Nil [PROOF STATE] proof (state) this: s = [] goal (2 subgoals): 1. s = [] \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. u = a # list \<and> a \<notin> A) \<and> t = []} 2. \<And>a list. s = a # list \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. u = a # list \<and> a \<notin> A) \<and> t = []} [PROOF STEP] then [PROOF STATE] proof (chain) picking this: s = [] [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: s = [] goal (1 subgoal): 1. finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. u = a # list \<and> a \<notin> A) \<and> t = []} [PROOF STEP] using not_finite_existsD [PROOF STATE] proof (prove) using this: s = [] infinite {a. ?P a} \<Longrightarrow> \<exists>a. ?P a goal (1 subgoal): 1. finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. u = a # list \<and> a \<notin> A) \<and> t = []} [PROOF STEP] by fastforce [PROOF STATE] proof (state) this: finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. u = a # list \<and> a \<notin> A) \<and> t = []} goal (1 subgoal): 1. \<And>a list. s = a # list \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. u = a # list \<and> a \<notin> A) \<and> t = []} [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>a list. s = a # list \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. u = a # list \<and> a \<notin> A) \<and> t = []} [PROOF STEP] case (Cons a list) [PROOF STATE] proof (state) this: s = a # list goal (1 subgoal): 1. \<And>a list. s = a # list \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. u = a # list \<and> a \<notin> A) \<and> t = []} [PROOF STEP] hence aa:"finite {(t,u).(tl s)setinterleaves((t, u), A)}" [PROOF STATE] proof (prove) using this: s = a # list goal (1 subgoal): 1. finite {(t, u). tl s setinterleaves ((t, u), A)} [PROOF STEP] using 1[THEN spec, of "length (tl s)"] [PROOF STATE] proof (prove) using this: s = a # list length (tl s) < length s \<longrightarrow> (\<forall>x. length (tl s) = length x \<longrightarrow> finite {(t, u). x setinterleaves ((t, u), A)}) goal (1 subgoal): 1. finite {(t, u). tl s setinterleaves ((t, u), A)} [PROOF STEP] by (simp) [PROOF STATE] proof (state) this: finite {(t, u). tl s setinterleaves ((t, u), A)} goal (1 subgoal): 1. \<And>a list. s = a # list \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. u = a # list \<and> a \<notin> A) \<and> t = []} [PROOF STEP] have "{([], hd s # list) |list. tl s setinterleaves (([], list), A)} \<subseteq> (\<lambda>(t, u). f (hd s) (t, u)) ` {(t, u). tl s setinterleaves ((t, u), A)}" [PROOF STATE] proof (prove) goal (1 subgoal): 1. {([], hd s # list) |list. tl s setinterleaves (([], list), A)} \<subseteq> (\<lambda>(t, u). f (hd s) (t, u)) ` {(t, u). tl s setinterleaves ((t, u), A)} [PROOF STEP] using a2 [PROOF STATE] proof (prove) using this: f = (\<lambda>a (t, u). ([], a # u)) goal (1 subgoal): 1. {([], hd s # list) |list. tl s setinterleaves (([], list), A)} \<subseteq> (\<lambda>(t, u). f (hd s) (t, u)) ` {(t, u). tl s setinterleaves ((t, u), A)} [PROOF STEP] by auto [PROOF STATE] proof (state) this: {([], hd s # list) |list. tl s setinterleaves (([], list), A)} \<subseteq> (\<lambda>(t, u). f (hd s) (t, u)) ` {(t, u). tl s setinterleaves ((t, u), A)} goal (1 subgoal): 1. \<And>a list. s = a # list \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. u = a # list \<and> a \<notin> A) \<and> t = []} [PROOF STEP] hence "finite ?C2" [PROOF STATE] proof (prove) using this: {([], hd s # list) |list. tl s setinterleaves (([], list), A)} \<subseteq> (\<lambda>(t, u). f (hd s) (t, u)) ` {(t, u). tl s setinterleaves ((t, u), A)} goal (1 subgoal): 1. finite {([], hd s # list) |list. tl s setinterleaves (([], list), A)} [PROOF STEP] using finite_imageI [of "{(t, u). (tl s) setinterleaves ((t, u), A)}" "\<lambda>(t, u). f (hd s) (t, u)", OF aa] [PROOF STATE] proof (prove) using this: {([], hd s # list) |list. tl s setinterleaves (([], list), A)} \<subseteq> (\<lambda>(t, u). f (hd s) (t, u)) ` {(t, u). tl s setinterleaves ((t, u), A)} finite ((\<lambda>(t, u). f (hd s) (t, u)) ` {(t, u). tl s setinterleaves ((t, u), A)}) goal (1 subgoal): 1. finite {([], hd s # list) |list. tl s setinterleaves (([], list), A)} [PROOF STEP] using rev_finite_subset [PROOF STATE] proof (prove) using this: {([], hd s # list) |list. tl s setinterleaves (([], list), A)} \<subseteq> (\<lambda>(t, u). f (hd s) (t, u)) ` {(t, u). tl s setinterleaves ((t, u), A)} finite ((\<lambda>(t, u). f (hd s) (t, u)) ` {(t, u). tl s setinterleaves ((t, u), A)}) \<lbrakk>finite ?B; ?A \<subseteq> ?B\<rbrakk> \<Longrightarrow> finite ?A goal (1 subgoal): 1. finite {([], hd s # list) |list. tl s setinterleaves (([], list), A)} [PROOF STEP] by auto [PROOF STATE] proof (state) this: finite {([], hd s # list) |list. tl s setinterleaves (([], list), A)} goal (1 subgoal): 1. \<And>a list. s = a # list \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. u = a # list \<and> a \<notin> A) \<and> t = []} [PROOF STEP] then [PROOF STATE] proof (chain) picking this: finite {([], hd s # list) |list. tl s setinterleaves (([], list), A)} [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: finite {([], hd s # list) |list. tl s setinterleaves (([], list), A)} goal (1 subgoal): 1. finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. u = a # list \<and> a \<notin> A) \<and> t = []} [PROOF STEP] using a13 [PROOF STATE] proof (prove) using this: finite {([], hd s # list) |list. tl s setinterleaves (([], list), A)} {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. u = a # list \<and> a \<notin> A) \<and> t = []} \<subseteq> {([], hd s # list) |list. tl s setinterleaves (([], list), A)} goal (1 subgoal): 1. finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. u = a # list \<and> a \<notin> A) \<and> t = []} [PROOF STEP] by (meson rev_finite_subset) [PROOF STATE] proof (state) this: finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. u = a # list \<and> a \<notin> A) \<and> t = []} goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. u = a # list \<and> a \<notin> A) \<and> t = []} goal (1 subgoal): 1. \<And>s. \<forall>m<length s. \<forall>x. m = length x \<longrightarrow> finite {(t, u). x setinterleaves ((t, u), A)} \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A)} [PROOF STEP] have dd0:"?D \<subseteq> {(a#l, aa#la)|a aa l la. s setinterleaves ((a#l, aa#la), A)}" (is "?D \<subseteq> ?D1") [PROOF STATE] proof (prove) goal (1 subgoal): 1. {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} \<subseteq> {(a # l, aa # la) |a aa l la. s setinterleaves ((a # l, aa # la), A)} [PROOF STEP] apply (rule subsetI, auto, simp split:if_splits) [PROOF STATE] proof (prove) goal (4 subgoals): 1. \<And>aa aaa list lista. \<lbrakk>aa \<in> A; aaa = aa; \<exists>u. s = aa # u \<and> u setinterleaves ((lista, list), A)\<rbrakk> \<Longrightarrow> \<exists>a aaa l la. (a = aaa \<longrightarrow> (aaa \<notin> A \<longrightarrow> aa = aaa \<and> lista = l \<and> aa = aaa \<and> list = la \<and> ((\<exists>u. s = aaa # u \<and> u setinterleaves ((l, aaa # la), A)) \<or> (\<exists>u. s = aaa # u \<and> u setinterleaves ((aaa # l, la), A)))) \<and> (aaa \<in> A \<longrightarrow> aa = aaa \<and> lista = l \<and> aa = aaa \<and> list = la \<and> (\<exists>u. s = aaa # u \<and> u setinterleaves ((l, la), A)))) \<and> (a \<noteq> aaa \<longrightarrow> (aaa \<notin> A \<longrightarrow> (a \<in> A \<longrightarrow> aa = a \<and> lista = l \<and> aa = aaa \<and> list = la \<and> (\<exists>u. s = aaa # u \<and> u setinterleaves ((a # l, la), A))) \<and> (a \<notin> A \<longrightarrow> aa = a \<and> lista = l \<and> aa = aaa \<and> list = la \<and> ((\<exists>u. s = a # u \<and> u setinterleaves ((l, aaa # la), A)) \<or> (\<exists>u. s = aaa # u \<and> u setinterleaves ((a # l, la), A))))) \<and> (aaa \<in> A \<longrightarrow> a \<notin> A \<and> (a \<notin> A \<longrightarrow> aa = a \<and> lista = l \<and> aa = aaa \<and> list = la \<and> (\<exists>u. s = a # u \<and> u setinterleaves ((l, aaa # la), A))))) 2. \<And>aa aaa list lista. \<lbrakk>aaa \<in> A; aa \<notin> A; \<exists>u. s = aa # u \<and> u setinterleaves ((aaa # lista, list), A)\<rbrakk> \<Longrightarrow> \<exists>a aab l la. (a = aab \<longrightarrow> (aab \<notin> A \<longrightarrow> aaa = aab \<and> lista = l \<and> aa = aab \<and> list = la \<and> ((\<exists>u. s = aab # u \<and> u setinterleaves ((l, aab # la), A)) \<or> (\<exists>u. s = aab # u \<and> u setinterleaves ((aab # l, la), A)))) \<and> (aab \<in> A \<longrightarrow> aaa = aab \<and> lista = l \<and> aa = aab \<and> list = la \<and> (\<exists>u. s = aab # u \<and> u setinterleaves ((l, la), A)))) \<and> (a \<noteq> aab \<longrightarrow> (aab \<notin> A \<longrightarrow> (a \<in> A \<longrightarrow> aaa = a \<and> lista = l \<and> aa = aab \<and> list = la \<and> (\<exists>u. s = aab # u \<and> u setinterleaves ((a # l, la), A))) \<and> (a \<notin> A \<longrightarrow> aaa = a \<and> lista = l \<and> aa = aab \<and> list = la \<and> ((\<exists>u. s = a # u \<and> u setinterleaves ((l, aab # la), A)) \<or> (\<exists>u. s = aab # u \<and> u setinterleaves ((a # l, la), A))))) \<and> (aab \<in> A \<longrightarrow> a \<notin> A \<and> (a \<notin> A \<longrightarrow> aaa = a \<and> lista = l \<and> aa = aab \<and> list = la \<and> (\<exists>u. s = a # u \<and> u setinterleaves ((l, aab # la), A))))) 3. \<And>aa aaa list lista. \<lbrakk>aaa \<notin> A; aa \<notin> A; (\<exists>u. s = aaa # u \<and> u setinterleaves ((lista, aa # list), A)) \<or> (\<exists>u. s = aa # u \<and> u setinterleaves ((aaa # lista, list), A))\<rbrakk> \<Longrightarrow> \<exists>a aab l la. (a = aab \<longrightarrow> (aab \<notin> A \<longrightarrow> aaa = aab \<and> lista = l \<and> aa = aab \<and> list = la \<and> ((\<exists>u. s = aab # u \<and> u setinterleaves ((l, aab # la), A)) \<or> (\<exists>u. s = aab # u \<and> u setinterleaves ((aab # l, la), A)))) \<and> (aab \<in> A \<longrightarrow> aaa = aab \<and> lista = l \<and> aa = aab \<and> list = la \<and> (\<exists>u. s = aab # u \<and> u setinterleaves ((l, la), A)))) \<and> (a \<noteq> aab \<longrightarrow> (aab \<notin> A \<longrightarrow> (a \<in> A \<longrightarrow> aaa = a \<and> lista = l \<and> aa = aab \<and> list = la \<and> (\<exists>u. s = aab # u \<and> u setinterleaves ((a # l, la), A))) \<and> (a \<notin> A \<longrightarrow> aaa = a \<and> lista = l \<and> aa = aab \<and> list = la \<and> ((\<exists>u. s = a # u \<and> u setinterleaves ((l, aab # la), A)) \<or> (\<exists>u. s = aab # u \<and> u setinterleaves ((a # l, la), A))))) \<and> (aab \<in> A \<longrightarrow> a \<notin> A \<and> (a \<notin> A \<longrightarrow> aaa = a \<and> lista = l \<and> aa = aab \<and> list = la \<and> (\<exists>u. s = a # u \<and> u setinterleaves ((l, aab # la), A))))) 4. \<And>aa aaa list lista. \<lbrakk>aaa \<notin> A; aa \<in> A; \<exists>u. s = aaa # u \<and> u setinterleaves ((lista, aa # list), A)\<rbrakk> \<Longrightarrow> \<exists>a aab l la. (a = aab \<longrightarrow> (aab \<notin> A \<longrightarrow> aaa = aab \<and> lista = l \<and> aa = aab \<and> list = la \<and> ((\<exists>u. s = aab # u \<and> u setinterleaves ((l, aab # la), A)) \<or> (\<exists>u. s = aab # u \<and> u setinterleaves ((aab # l, la), A)))) \<and> (aab \<in> A \<longrightarrow> aaa = aab \<and> lista = l \<and> aa = aab \<and> list = la \<and> (\<exists>u. s = aab # u \<and> u setinterleaves ((l, la), A)))) \<and> (a \<noteq> aab \<longrightarrow> (aab \<notin> A \<longrightarrow> (a \<in> A \<longrightarrow> aaa = a \<and> lista = l \<and> aa = aab \<and> list = la \<and> (\<exists>u. s = aab # u \<and> u setinterleaves ((a # l, la), A))) \<and> (a \<notin> A \<longrightarrow> aaa = a \<and> lista = l \<and> aa = aab \<and> list = la \<and> ((\<exists>u. s = a # u \<and> u setinterleaves ((l, aab # la), A)) \<or> (\<exists>u. s = aab # u \<and> u setinterleaves ((a # l, la), A))))) \<and> (aab \<in> A \<longrightarrow> a \<notin> A \<and> (a \<notin> A \<longrightarrow> aaa = a \<and> lista = l \<and> aa = aab \<and> list = la \<and> (\<exists>u. s = a # u \<and> u setinterleaves ((l, aab # la), A))))) [PROOF STEP] by (blast, blast, metis, blast) [PROOF STATE] proof (state) this: {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} \<subseteq> {(a # l, aa # la) |a aa l la. s setinterleaves ((a # l, aa # la), A)} goal (1 subgoal): 1. \<And>s. \<forall>m<length s. \<forall>x. m = length x \<longrightarrow> finite {(t, u). x setinterleaves ((t, u), A)} \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A)} [PROOF STEP] have AAAA:"finite ?D" [PROOF STATE] proof (prove) goal (1 subgoal): 1. finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} [PROOF STEP] proof (cases s) [PROOF STATE] proof (state) goal (2 subgoals): 1. s = [] \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} 2. \<And>a list. s = a # list \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} [PROOF STEP] case Nil [PROOF STATE] proof (state) this: s = [] goal (2 subgoals): 1. s = [] \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} 2. \<And>a list. s = a # list \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} [PROOF STEP] hence "?D \<subseteq> {([],[])}" [PROOF STATE] proof (prove) using this: s = [] goal (1 subgoal): 1. {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} \<subseteq> {([], [])} [PROOF STEP] using empty_setinterleaving [PROOF STATE] proof (prove) using this: s = [] [] setinterleaves ((?t, ?u), ?A) \<Longrightarrow> ?t = [] goal (1 subgoal): 1. {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} \<subseteq> {([], [])} [PROOF STEP] by auto [PROOF STATE] proof (state) this: {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} \<subseteq> {([], [])} goal (2 subgoals): 1. s = [] \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} 2. \<And>a list. s = a # list \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} [PROOF STEP] then [PROOF STATE] proof (chain) picking this: {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} \<subseteq> {([], [])} [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} \<subseteq> {([], [])} goal (1 subgoal): 1. finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} [PROOF STEP] using infinite_super [PROOF STATE] proof (prove) using this: {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} \<subseteq> {([], [])} \<lbrakk>?S \<subseteq> ?T; infinite ?S\<rbrakk> \<Longrightarrow> infinite ?T goal (1 subgoal): 1. finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} [PROOF STEP] by auto [PROOF STATE] proof (state) this: finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} goal (1 subgoal): 1. \<And>a list. s = a # list \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>a list. s = a # list \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} [PROOF STEP] case (Cons a list) [PROOF STATE] proof (state) this: s = a # list goal (1 subgoal): 1. \<And>a list. s = a # list \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} [PROOF STEP] hence dd1:"?D1 \<subseteq> {(a#l, u)| l u. list setinterleaves ((l, u), A)} \<union> {(t, a#la)| t la. list setinterleaves ((t, la), A)} \<union> {(a#l, a#la)|l la. list setinterleaves ((l, la), A)}"(is "?D1 \<subseteq> ?D2 \<union> ?D3 \<union> ?D4") [PROOF STATE] proof (prove) using this: s = a # list goal (1 subgoal): 1. {(a # l, aa # la) |a aa l la. s setinterleaves ((a # l, aa # la), A)} \<subseteq> {(a # l, u) |l u. list setinterleaves ((l, u), A)} \<union> {(t, a # la) |t la. list setinterleaves ((t, la), A)} \<union> {(a # l, a # la) |l la. list setinterleaves ((l, la), A)} [PROOF STEP] by (rule_tac subsetI, auto split:if_splits) [PROOF STATE] proof (state) this: {(a # l, aa # la) |a aa l la. s setinterleaves ((a # l, aa # la), A)} \<subseteq> {(a # l, u) |l u. list setinterleaves ((l, u), A)} \<union> {(t, a # la) |t la. list setinterleaves ((t, la), A)} \<union> {(a # l, a # la) |l la. list setinterleaves ((l, la), A)} goal (1 subgoal): 1. \<And>a list. s = a # list \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} [PROOF STEP] with Cons [PROOF STATE] proof (chain) picking this: s = a # list {(a # l, aa # la) |a aa l la. s setinterleaves ((a # l, aa # la), A)} \<subseteq> {(a # l, u) |l u. list setinterleaves ((l, u), A)} \<union> {(t, a # la) |t la. list setinterleaves ((t, la), A)} \<union> {(a # l, a # la) |l la. list setinterleaves ((l, la), A)} [PROOF STEP] have aa:"finite {(t,u). list setinterleaves ((t, u), A)}" [PROOF STATE] proof (prove) using this: s = a # list {(a # l, aa # la) |a aa l la. s setinterleaves ((a # l, aa # la), A)} \<subseteq> {(a # l, u) |l u. list setinterleaves ((l, u), A)} \<union> {(t, a # la) |t la. list setinterleaves ((t, la), A)} \<union> {(a # l, a # la) |l la. list setinterleaves ((l, la), A)} goal (1 subgoal): 1. finite {(t, u). list setinterleaves ((t, u), A)} [PROOF STEP] using 1[THEN spec, of "length list"] [PROOF STATE] proof (prove) using this: s = a # list {(a # l, aa # la) |a aa l la. s setinterleaves ((a # l, aa # la), A)} \<subseteq> {(a # l, u) |l u. list setinterleaves ((l, u), A)} \<union> {(t, a # la) |t la. list setinterleaves ((t, la), A)} \<union> {(a # l, a # la) |l la. list setinterleaves ((l, la), A)} length list < length s \<longrightarrow> (\<forall>x. length list = length x \<longrightarrow> finite {(t, u). x setinterleaves ((t, u), A)}) goal (1 subgoal): 1. finite {(t, u). list setinterleaves ((t, u), A)} [PROOF STEP] by (simp) [PROOF STATE] proof (state) this: finite {(t, u). list setinterleaves ((t, u), A)} goal (1 subgoal): 1. \<And>a list. s = a # list \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} [PROOF STEP] define f where a2:"f = (\<lambda> (t, (u::'a event list)). ((a::'a event)# t, u))" [PROOF STATE] proof (state) this: f = (\<lambda>(t, u). (a # t, u)) goal (1 subgoal): 1. \<And>a list. s = a # list \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} [PROOF STEP] with Cons [PROOF STATE] proof (chain) picking this: s = a # list f = (\<lambda>(t, u). (a # t, u)) [PROOF STEP] have "?D2 \<subseteq> (f ` {(t, u). list setinterleaves ((t, u), A)})" [PROOF STATE] proof (prove) using this: s = a # list f = (\<lambda>(t, u). (a # t, u)) goal (1 subgoal): 1. {(a # l, u) |l u. list setinterleaves ((l, u), A)} \<subseteq> f ` {(t, u). list setinterleaves ((t, u), A)} [PROOF STEP] using a2 [PROOF STATE] proof (prove) using this: s = a # list f = (\<lambda>(t, u). (a # t, u)) f = (\<lambda>(t, u). (a # t, u)) goal (1 subgoal): 1. {(a # l, u) |l u. list setinterleaves ((l, u), A)} \<subseteq> f ` {(t, u). list setinterleaves ((t, u), A)} [PROOF STEP] by auto [PROOF STATE] proof (state) this: {(a # l, u) |l u. list setinterleaves ((l, u), A)} \<subseteq> f ` {(t, u). list setinterleaves ((t, u), A)} goal (1 subgoal): 1. \<And>a list. s = a # list \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} [PROOF STEP] hence dd2:"finite ?D2" [PROOF STATE] proof (prove) using this: {(a # l, u) |l u. list setinterleaves ((l, u), A)} \<subseteq> f ` {(t, u). list setinterleaves ((t, u), A)} goal (1 subgoal): 1. finite {(a # l, u) |l u. list setinterleaves ((l, u), A)} [PROOF STEP] using finite_imageI [of "{(t, u). list setinterleaves ((t, u), A)}" f, OF aa] [PROOF STATE] proof (prove) using this: {(a # l, u) |l u. list setinterleaves ((l, u), A)} \<subseteq> f ` {(t, u). list setinterleaves ((t, u), A)} finite (f ` {(t, u). list setinterleaves ((t, u), A)}) goal (1 subgoal): 1. finite {(a # l, u) |l u. list setinterleaves ((l, u), A)} [PROOF STEP] by (meson rev_finite_subset) [PROOF STATE] proof (state) this: finite {(a # l, u) |l u. list setinterleaves ((l, u), A)} goal (1 subgoal): 1. \<And>a list. s = a # list \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} [PROOF STEP] define f where a2:"f = (\<lambda> ((t::'a event list),u). (t,(a::'a event)#u))" [PROOF STATE] proof (state) this: f = (\<lambda>(t, u). (t, a # u)) goal (1 subgoal): 1. \<And>a list. s = a # list \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} [PROOF STEP] with Cons [PROOF STATE] proof (chain) picking this: s = a # list f = (\<lambda>(t, u). (t, a # u)) [PROOF STEP] have "?D3 \<subseteq> (f ` {(t, u). list setinterleaves ((t, u), A)})" [PROOF STATE] proof (prove) using this: s = a # list f = (\<lambda>(t, u). (t, a # u)) goal (1 subgoal): 1. {(t, a # la) |t la. list setinterleaves ((t, la), A)} \<subseteq> f ` {(t, u). list setinterleaves ((t, u), A)} [PROOF STEP] using a2 [PROOF STATE] proof (prove) using this: s = a # list f = (\<lambda>(t, u). (t, a # u)) f = (\<lambda>(t, u). (t, a # u)) goal (1 subgoal): 1. {(t, a # la) |t la. list setinterleaves ((t, la), A)} \<subseteq> f ` {(t, u). list setinterleaves ((t, u), A)} [PROOF STEP] by auto [PROOF STATE] proof (state) this: {(t, a # la) |t la. list setinterleaves ((t, la), A)} \<subseteq> f ` {(t, u). list setinterleaves ((t, u), A)} goal (1 subgoal): 1. \<And>a list. s = a # list \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} [PROOF STEP] hence dd3:"finite ?D3" [PROOF STATE] proof (prove) using this: {(t, a # la) |t la. list setinterleaves ((t, la), A)} \<subseteq> f ` {(t, u). list setinterleaves ((t, u), A)} goal (1 subgoal): 1. finite {(t, a # la) |t la. list setinterleaves ((t, la), A)} [PROOF STEP] using finite_imageI [of "{(t, u). list setinterleaves ((t, u), A)}" f, OF aa] [PROOF STATE] proof (prove) using this: {(t, a # la) |t la. list setinterleaves ((t, la), A)} \<subseteq> f ` {(t, u). list setinterleaves ((t, u), A)} finite (f ` {(t, u). list setinterleaves ((t, u), A)}) goal (1 subgoal): 1. finite {(t, a # la) |t la. list setinterleaves ((t, la), A)} [PROOF STEP] by (meson rev_finite_subset) [PROOF STATE] proof (state) this: finite {(t, a # la) |t la. list setinterleaves ((t, la), A)} goal (1 subgoal): 1. \<And>a list. s = a # list \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} [PROOF STEP] define f where a2:"f = (\<lambda> (t,u). ((a::'a event)#t,(a::'a event)#u))" [PROOF STATE] proof (state) this: f = (\<lambda>(t, u). (a # t, a # u)) goal (1 subgoal): 1. \<And>a list. s = a # list \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} [PROOF STEP] with Cons [PROOF STATE] proof (chain) picking this: s = a # list f = (\<lambda>(t, u). (a # t, a # u)) [PROOF STEP] have "?D4 \<subseteq> (f ` {(t, u). list setinterleaves ((t, u), A)})" [PROOF STATE] proof (prove) using this: s = a # list f = (\<lambda>(t, u). (a # t, a # u)) goal (1 subgoal): 1. {(a # l, a # la) |l la. list setinterleaves ((l, la), A)} \<subseteq> f ` {(t, u). list setinterleaves ((t, u), A)} [PROOF STEP] using a2 [PROOF STATE] proof (prove) using this: s = a # list f = (\<lambda>(t, u). (a # t, a # u)) f = (\<lambda>(t, u). (a # t, a # u)) goal (1 subgoal): 1. {(a # l, a # la) |l la. list setinterleaves ((l, la), A)} \<subseteq> f ` {(t, u). list setinterleaves ((t, u), A)} [PROOF STEP] by auto [PROOF STATE] proof (state) this: {(a # l, a # la) |l la. list setinterleaves ((l, la), A)} \<subseteq> f ` {(t, u). list setinterleaves ((t, u), A)} goal (1 subgoal): 1. \<And>a list. s = a # list \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} [PROOF STEP] hence dd4:"finite ?D4" [PROOF STATE] proof (prove) using this: {(a # l, a # la) |l la. list setinterleaves ((l, la), A)} \<subseteq> f ` {(t, u). list setinterleaves ((t, u), A)} goal (1 subgoal): 1. finite {(a # l, a # la) |l la. list setinterleaves ((l, la), A)} [PROOF STEP] using finite_imageI [of "{(t, u). list setinterleaves ((t, u), A)}" f, OF aa] [PROOF STATE] proof (prove) using this: {(a # l, a # la) |l la. list setinterleaves ((l, la), A)} \<subseteq> f ` {(t, u). list setinterleaves ((t, u), A)} finite (f ` {(t, u). list setinterleaves ((t, u), A)}) goal (1 subgoal): 1. finite {(a # l, a # la) |l la. list setinterleaves ((l, la), A)} [PROOF STEP] by (meson rev_finite_subset) [PROOF STATE] proof (state) this: finite {(a # l, a # la) |l la. list setinterleaves ((l, la), A)} goal (1 subgoal): 1. \<And>a list. s = a # list \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} [PROOF STEP] with dd0 dd1 dd2 dd3 dd4 [PROOF STATE] proof (chain) picking this: {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} \<subseteq> {(a # l, aa # la) |a aa l la. s setinterleaves ((a # l, aa # la), A)} {(a # l, aa # la) |a aa l la. s setinterleaves ((a # l, aa # la), A)} \<subseteq> {(a # l, u) |l u. list setinterleaves ((l, u), A)} \<union> {(t, a # la) |t la. list setinterleaves ((t, la), A)} \<union> {(a # l, a # la) |l la. list setinterleaves ((l, la), A)} finite {(a # l, u) |l u. list setinterleaves ((l, u), A)} finite {(t, a # la) |t la. list setinterleaves ((t, la), A)} finite {(a # l, a # la) |l la. list setinterleaves ((l, la), A)} finite {(a # l, a # la) |l la. list setinterleaves ((l, la), A)} [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} \<subseteq> {(a # l, aa # la) |a aa l la. s setinterleaves ((a # l, aa # la), A)} {(a # l, aa # la) |a aa l la. s setinterleaves ((a # l, aa # la), A)} \<subseteq> {(a # l, u) |l u. list setinterleaves ((l, u), A)} \<union> {(t, a # la) |t la. list setinterleaves ((t, la), A)} \<union> {(a # l, a # la) |l la. list setinterleaves ((l, la), A)} finite {(a # l, u) |l u. list setinterleaves ((l, u), A)} finite {(t, a # la) |t la. list setinterleaves ((t, la), A)} finite {(a # l, a # la) |l la. list setinterleaves ((l, la), A)} finite {(a # l, a # la) |l la. list setinterleaves ((l, la), A)} goal (1 subgoal): 1. finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} [PROOF STEP] by (simp add: finite_subset) [PROOF STATE] proof (state) this: finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} goal (1 subgoal): 1. \<And>s. \<forall>m<length s. \<forall>x. m = length x \<longrightarrow> finite {(t, u). x setinterleaves ((t, u), A)} \<Longrightarrow> finite {(t, u). s setinterleaves ((t, u), A)} [PROOF STEP] from A AA AAA AAAA [PROOF STATE] proof (chain) picking this: {(t, u). s setinterleaves ((t, u), A)} \<subseteq> {([], [])} \<union> {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. t = a # list \<and> a \<notin> A) \<and> u = []} \<union> {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. u = a # list \<and> a \<notin> A) \<and> t = []} \<union> {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. t = a # list \<and> a \<notin> A) \<and> u = []} finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. u = a # list \<and> a \<notin> A) \<and> t = []} finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} [PROOF STEP] show ?case [PROOF STATE] proof (prove) using this: {(t, u). s setinterleaves ((t, u), A)} \<subseteq> {([], [])} \<union> {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. t = a # list \<and> a \<notin> A) \<and> u = []} \<union> {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. u = a # list \<and> a \<notin> A) \<and> t = []} \<union> {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. t = a # list \<and> a \<notin> A) \<and> u = []} finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list. u = a # list \<and> a \<notin> A) \<and> t = []} finite {(t, u). s setinterleaves ((t, u), A) \<and> (\<exists>a list aa lista. u = a # list \<and> t = aa # lista)} goal (1 subgoal): 1. finite {(t, u). s setinterleaves ((t, u), A)} [PROOF STEP] by (simp add: finite_subset) [PROOF STATE] proof (state) this: finite {(t, u). s setinterleaves ((t, u), A)} goal: No subgoals! [PROOF STEP] qed