Datasets:
AI4M
/

text
stringlengths
0
3.34M
(** * Non-unital lB0-systems By Vladimir Voevodsky, started on Jan. 24, 2015 *) Require Import UniMath.Foundations.All. Require Import TypeTheory.Csystems.hSet_ltowers. Require Export TypeTheory.Bsystems.prelB. Require Export TypeTheory.Bsystems.TS_ST. Require Export TypeTheory.Bsystems.STid . Require Export TypeTheory.Bsystems.dlt . (** ** Definitions of the main layers *) (** *** The layer associated with operations T *) Definition T_layer ( BB : lBsystem_carrier ) := ∑ T : T_layer_0 BB, ( T_ax1a_type T ) × ( T_ax1b_type T ). (** Warning: [T_layer_0] refers to a pre-lB-system, [T_layer] refers to a lB0-system. *) Definition T_layer_to_T_layer_0 ( BB : lBsystem_carrier ) : T_layer BB -> T_layer_0 BB := pr1 . Coercion T_layer_to_T_layer_0 : T_layer >-> T_layer_0 . (** *** The layer associated with operations Tt *) Definition Tt_layer { BB : lBsystem_carrier } ( T : T_ops_type BB ) := ∑ Tt : Tt_ops_type BB, Tt_ax1_type T Tt. Definition Tt_layer_to_Tt_ops_type ( BB : lBsystem_carrier ) ( T : T_ops_type BB ) ( Tt : Tt_layer T ) : Tt_ops_type BB := pr1 Tt . Coercion Tt_layer_to_Tt_ops_type : Tt_layer >-> Tt_ops_type . (** *** The structure formed by operations T and Tt *) Definition T_Tt_layer ( BB : lBsystem_carrier ) := ∑ T : T_layer BB, Tt_layer T. Definition T_Tt_layer_to_T_layer { BB : lBsystem_carrier } ( T_Tt : T_Tt_layer BB ) : T_layer BB := pr1 T_Tt . Coercion T_Tt_layer_to_T_layer : T_Tt_layer >-> T_layer . Definition T_Tt_layer_to_Tt_layer { BB : lBsystem_carrier } ( T_Tt : T_Tt_layer BB ) : Tt_layer T_Tt := pr2 T_Tt . Coercion T_Tt_layer_to_Tt_layer : T_Tt_layer >-> Tt_layer . (** *** The layer associated with operations S *) Definition S_layer ( BB : lBsystem_carrier ) := ∑ S : S_layer_0 BB, ( S_ax1a_type S ) × ( S_ax1b_type S ). Definition S_layer_to_S_layer_0 ( BB : lBsystem_carrier ) : S_layer BB -> S_layer_0 BB := pr1 . Coercion S_layer_to_S_layer_0 : S_layer >-> S_layer_0 . (** *** The layer associated with operations St *) Definition St_layer { BB : lBsystem_carrier } ( S : S_ops_type BB ) := ∑ St : St_ops_type BB, St_ax1_type S St. Definition St_layer_to_St_ops_type ( BB : lBsystem_carrier ) ( S : S_ops_type BB ) ( St : St_layer S ) : St_ops_type BB := pr1 St. Coercion St_layer_to_St_ops_type : St_layer >-> St_ops_type . (** *** The structure formed by operations S and St *) Definition S_St_layer ( BB : lBsystem_carrier ) := ∑ S : S_layer BB, St_layer S. Definition S_St_layer_to_S_layer { BB : lBsystem_carrier } ( S_St : S_St_layer BB ) : S_layer BB := pr1 S_St . Coercion S_St_layer_to_S_layer : S_St_layer >-> S_layer . Definition S_St_layer_to_St_layer { BB : lBsystem_carrier } ( S_St : S_St_layer BB ) : St_layer S_St := pr2 S_St . Coercion S_St_layer_to_St_layer : S_St_layer >-> St_layer . (** ** Complete definition of a non-unital lB0-system *) Definition T_ax1_type ( BB : prelBsystem_non_unital ) := ( T_ax1a_type ( @T_op BB ) ) × ( T_ax1b_type ( @T_op BB ) ) . Definition Tt_ax1_type' ( BB : prelBsystem_non_unital ) := Tt_ax1_type ( @T_op BB ) ( @Tt_op BB ) . Definition S_ax1_type ( BB : prelBsystem_non_unital ) := ( S_ax1a_type ( @S_op BB ) ) × ( S_ax1b_type ( @S_op BB ) ) . Definition St_ax1_type' ( BB : prelBsystem_non_unital ) := St_ax1_type ( @S_op BB ) ( @St_op BB ) . Definition lB0system_non_unital := ∑ BB : prelBsystem_non_unital, ( ( T_ax1_type BB ) × ( Tt_ax1_type' BB ) ) × ( ( S_ax1_type BB ) × ( St_ax1_type' BB ) ). (** This definition corresponds to Definition 2.5 in arXiv:1410.5389v1 modulo the details on the treatment of the second cases of 2.5.2 and 2.5.4, discussed elsewhere (see the definition of [T_ax1b_type] and [S_ax1b_type] and the lemmas [ft_T] and [ft_S]). *) Definition lB0system_non_unital_pr1 : lB0system_non_unital -> prelBsystem_non_unital := pr1 . Coercion lB0system_non_unital_pr1 : lB0system_non_unital >-> prelBsystem_non_unital . (** *** Access functions to the axioms *) Definition T_ax1a { BB : lB0system_non_unital } : T_ax1a_type ( @T_op BB ) := pr1 ( pr1 ( pr1 ( pr2 BB ) ) ) . Definition T_ax1b { BB : lB0system_non_unital } : T_ax1b_type ( @T_op BB ) := pr2 ( pr1 ( pr1 ( pr2 BB ) ) ) . Definition Tt_ax1 { BB : lB0system_non_unital } : Tt_ax1_type ( @T_op BB ) ( @Tt_op BB ) := pr2 ( pr1 ( pr2 BB ) ) . Definition Tt_ax0 { BB : lB0system_non_unital } : Tt_ax0_type ( @Tt_op BB ) := Tt_ax1_to_Tt_ax0 ( @T_ax0 BB ) ( @Tt_ax1 BB ) . Definition S_ax1a { BB : lB0system_non_unital } : S_ax1a_type ( @S_op BB ) := pr1 ( pr1 ( pr2 ( pr2 BB ) ) ) . Definition S_ax1b { BB : lB0system_non_unital } : S_ax1b_type ( @S_op BB ) := pr2 ( pr1 ( pr2 ( pr2 BB ) ) ) . Definition St_ax1 { BB : lB0system_non_unital } : St_ax1_type ( @S_op BB ) ( @St_op BB ) := pr2 ( pr2 ( pr2 BB ) ) . Definition St_ax0 { BB : lB0system_non_unital } : St_ax0_type ( @St_op BB ) := St_ax1_to_St_ax0 ( @S_ax0 BB ) ( @St_ax1 BB ) . (** ** Derived operations re-defined in a more streamlined form *) (** *** Derived operations related to operation T *) Definition T_fun { BB : lB0system_non_unital } ( X : BB ) ( gt0 : ll X > 0 ) : ltower_fun ( ltower_over ( ft X ) ) ( ltower_over X ) := T_fun.T_fun ( @T_ax0 BB ) ( @T_ax1a BB ) ( @T_ax1b BB ) gt0 . Definition Tj_fun { BB : lB0system_non_unital } { A X1 : BB } ( isov : isover X1 A ) : ltower_fun ( ltower_over A ) ( ltower_over X1 ) := T_fun.Tj_fun ( @T_ax0 BB ) ( @T_ax1a BB ) ( @T_ax1b BB ) isov . Definition Tj_fun_compt { BB : lB0system_non_unital } { X Y : BB } ( isab : isabove X Y ) : Tj_fun isab = ltower_funcomp ( Tj_fun ( isover_ft' isab ) ) ( T_fun X ( isabove_gt0 isab ) ) := Tj_fun_compt ( @T_ax0 BB ) ( @T_ax1a BB ) ( @T_ax1b BB ) isab . Definition Tj { BB : lB0system_non_unital } { X A Y : BB } ( isov1 : isover X A ) ( isov2 : isover Y A ) : BB := pocto ( Tj_fun isov1 ( obj_over_constr isov2 ) ) . Definition isover_Tj { BB : lB0system_non_unital } { X A Y : BB } ( isov1 : isover X A ) ( isov2 : isover Y A ) : isover ( Tj isov1 isov2 ) X := pr2 ( Tj_fun isov1 ( obj_over_constr isov2 ) ) . Definition Tj_compt { BB : lB0system_non_unital } { X A Y : BB } ( isab : isabove X A ) ( isov2 : isover Y A ) : Tj isab isov2 = T_ext X ( Tj ( isover_ft' isab ) isov2 ) ( isabove_gt0 isab ) ( isover_Tj ( isover_ft' isab ) isov2 ) . Proof. unfold Tj . rewrite Tj_fun_compt . apply idpath . Defined. Definition Tprod_over { BB : lB0system_non_unital } ( X1 : BB ) : ltower_fun BB ( ltower_over X1 ) := T_fun.Tprod_fun ( @T_ax0 BB ) ( @T_ax1a BB ) ( @T_ax1b BB ) X1 . Definition Tprod { BB : lB0system_non_unital } ( X Y : BB ) : BB := pocto ( Tprod_over X Y ) . Definition isover_Tprod { BB : lB0system_non_unital } ( X Y : BB ) : isover ( Tprod X Y ) X := pr2 ( Tprod_over X Y ) . Lemma ll_Tprod { BB : lB0system_non_unital } ( X Y : BB ) : ll ( Tprod X Y ) = ll X + ll Y . Proof. unfold Tprod . rewrite ll_pocto . rewrite natpluscomm . rewrite ( @ll_ltower_fun BB _ ( Tprod_over X ) ) . apply idpath . Defined. Definition Tprod_compt { BB : lB0system_non_unital } ( X Y : BB ) ( gt0 : ll X > 0 ) : Tprod X Y = T_ext X ( Tprod ( ft X ) Y ) gt0 ( isover_Tprod _ _ ) . Proof. set ( int := T_fun.Tprod_compt ( @T_ax0 BB ) ( @T_ax1a BB ) ( @T_ax1b BB ) X Y gt0 ). exact ( maponpaths pocto int ) . Defined. (** *** Derived operations related to operation S *) Lemma ll_S_ext { BB : lB0system_non_unital } ( r : Tilde BB ) ( X : BB ) ( inn : isover X ( dd r ) ) : ll ( S_ext r X inn ) = ll X - 1. Proof. apply S_fun.ll_S_ext . + apply ( @S_ax0 BB ) . + apply ( @S_ax1b BB ) . Defined. Definition S_fun { BB : lB0system_non_unital } ( r : Tilde BB ) : ltower_fun ( ltower_over ( dd r ) ) ( ltower_over ( ft ( dd r ) ) ) := ltower_fun_S ( @S_ax0 BB ) ( @S_ax1a BB ) ( @S_ax1b BB ) r . (* End of the file lB0_non_unital.v *)
(* Copyright (C) 2017 M.A.L. Marques This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. *) (* type: gga_exc *) $define xc_dimensions_2d _2d_b86_beta := 0.002105: _2d_b86_gamma := 0.000119: _2d_b86_f := x -> (1 + _2d_b86_beta*x^2)/(1 + _2d_b86_gamma*x^2): f := (rs, zeta, xt, xs0, xs1) -> gga_exchange(_2d_b86_f, rs, zeta, xs0, xs1):
function [v,x,t,m,ze]=quadpeak(z) %PEAK2DQUAD find quadratically-interpolated peak in a N-D array % % Inputs: Z(m,n,...) is the input array (ignoring trailing singleton dimensions) % Note: a row vector will have 2 dimensions % % Outputs: V is the peak value % X(:,1) is the position of the peak (in fractional subscript values) % T is -1, 0, +1 for maximum, saddle point or minimum % M defines the fitted quadratic: z = [x y ... 1]*M*[x y ... 1]' % ZE the estimated version of Z % Copyright (C) Mike Brookes 2008 % Version: $Id: quadpeak.m 713 2011-10-16 14:45:43Z dmb $ % % VOICEBOX is a MATLAB toolbox for speech processing. % Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % 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 can obtain a copy of the GNU General Public License from % http://www.gnu.org/copyleft/gpl.html or by writing to % Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% persistent wz a % first calculate the fixed matrix, a (can be stored if sz is constant) sz=size(z); % size of input array psz=prod(sz); % number of elements in input array dz=numel(sz); % number of input dimensions mz=find(sz>1); % non-singleton dimension indices nm=numel(mz); % number of non-singleton dimensions vz=sz(mz); % size of squeezed input array dx=max(mz); % number of output dimensions if ~nm % if the input array is a scalar error('Cannot find peak of a scalar'); end nc=(nm+1)*(nm+2)/2; % number of columns in A matrix if min(vz)<3 error('Need at least 3 points in each non-singleton dimension'); end if isempty(wz) || numel(wz)~=numel(vz) || ~all(wz==vz) wz=vz; a=ones(psz,nc); ix=(0:psz-1)'; for i=1:nm jx=floor(ix/sz(mz(i))); a(:,i+nc-nm-1)=1+ix-jx*sz(mz(i)); ix=jx; a(:,(i^2-i+2)/2:i*(i+1)/2)=a(:,nc-nm:i+nc-nm-1).*repmat(a(:,i+nc-nm-1),1,i); end a=(a'*a)\a'; % converts to polynomial coeficients {x^2 xy y^2 x y 1] end % now find the peak c=a*z(:); % polynomial coefficients for this data w=zeros(nm+1,nm+1); i=1:(nm+1)*(nm+2)/2; j=floor((sqrt(8*i-7)-1)/2); w(i+j.*(2*nm+1-j)/2)=c; w=(w+w.')/2; % make it symmetrical mr=w(1:nm,1:nm); we=w(1:nm,nm+1); y=-(mr\we); v=y'*we+w(nm+1,nm+1); % value at peak % insert singleton dimensions into outputs x=zeros(dx,1); x(mz)=y; m=zeros(dx+1,dx+1); mz(nm+1)=dx+1; m(mz,mz)=w; if nargout>2 ev=eig(mr); t=all(ev>0)-all(ev<0); end if nargout>4 ze=zeros(sz); scp=cumprod([1 sz(1:end-1)]); ivec=fix(repmat((0:psz-1)',1,dz)./repmat(scp,psz,1)); xe=[1+ivec-repmat(sz,psz,1).*fix(ivec./repmat(sz,psz,1)) ones(psz,1)]; ze=reshape(sum((xe*m).*xe,2),sz); end if ~nargout && nm<=2 % plot the data desc={'Maximum','Saddle Point','Minimum'}; if nargout<=2 ev=eig(mr); t=all(ev>0)-all(ev<0); end if nm==1 xax=linspace(1,psz,100); plot(xax,c(1)*xax.^2+c(2)*xax+c(3),'-r',1:psz,z(:),'ob',x,v,'^k'); set(gca,'xlim',[0.9 psz+0.1]); ylabel('z'); xlabel(sprintf('x%d',mz(1))); title(sprintf('\\Delta = %s: z(%.2g) = %.2g',desc{t+2},y(1),v)); else ngr=17; xax=repmat(linspace(1,vz(1),ngr)',1,ngr); yax=repmat(linspace(1,vz(2),ngr),ngr,1); zq=(c(1)*xax+c(2)*yax+c(4)).*xax+(c(3)*yax+c(5)).*yax+c(6); hold off mesh(xax,yax,zq,'EdgeColor','r'); hold on plot3(repmat((1:vz(1))',1,vz(2)),repmat(1:vz(2),vz(1),1),reshape(z,vz),'ob',y(1),y(2),v,'^k'); hold off set(gca,'xlim',[0.9 vz(1)+0.1],'ylim',[0.9 vz(2)+0.1]); xlabel(sprintf('x%d',mz(1))); ylabel(sprintf('x%d',mz(2))); zlabel('z'); title(sprintf('\\Delta = %s: z(%.2g,%.2g) = %.2g',desc{t+2},y(1),y(2),v)); end end
{-# OPTIONS --type-in-type #-} module poly0 where open import prelude open import functors open import poly.core public variable A B C X Y : ∫ I A⁺ B⁺ C⁺ X⁺ Y⁺ : Set A⁻ : A⁺ → Set B⁻ : B⁺ → Set C⁻ : C⁺ → Set X⁻ : X⁺ → Set Y⁻ : Y⁺ → Set ∃⊤ ∃⊥ ⊤∫ ∫∫ : Set → ∫ ∃⊤ a = a , λ _ → ⊤ ∃⊥ a = a , λ _ → ⊥ ⊤∫ a = ⊤ , λ _ → a ∫∫ a = a , λ _ → a 𝒴 𝟘 : ∫ 𝒴 = ⊤ , λ _ → ⊤ 𝟘 = ⊥ , λ _ → ⊥ module _ {A@(A⁺ , A⁻) B@(B⁺ , B⁻) : ∫} where infixl 5 _★_ -- infix notatjon for get _★_ : A⁺ → (l : ∫[ A , B ]) → B⁺ σa ★ l = get l σa infixr 4 _#_←_ -- Infix notatjon for set _#_←_ : (a⁺ : A⁺) → (A↝B : ∫[ A , B ]) → B⁻ (a⁺ ★ A↝B) → A⁻ a⁺ a⁺ # l ← b⁻ = π₂ (l a⁺) b⁻ _↕_ : (get : A⁺ → B⁺) → (set : (a⁺ : A⁺) → B⁻ (get a⁺) → A⁻ a⁺) → ∫[ A , B ] g ↕ s = λ a⁺ → (g a⁺) , (s a⁺) module _ {A@(A⁺ , A⁻) C@(C⁺ , C⁻) : ∫} (l : ∫[ A , C ]) where -- vertical and cartesian factorization Factor : Σ[ B ∈ ∫ ] (∫[ A , B ]) × (∫[ B , C ]) Factor = (A⁺ , C⁻ ∘ get l) , id ↕ set l , get l ↕ λ _ → id module lenses (f : A⁺ → B⁺) where constant : ∫[ ∃⊥ A⁺ , ∃⊥ B⁺ ] emitter : ∫[ ∃⊤ A⁺ , ∃⊤ B⁺ ] sensor : ∫[ ⊤∫ B⁺ , ⊤∫ A⁺ ] constant a⁺ = f a⁺ , id emitter a⁺ = f a⁺ , λ _ → tt sensor _ = tt , f open lenses public enclose : ((a⁺ : A⁺) → B⁻ a⁺) → ∫[ (A⁺ , B⁻) , 𝒴 ] enclose f a⁺ = tt , λ _ → f a⁺ auto : ∫[ ∃⊤ A⁺ , 𝒴 ] auto = enclose λ _ → tt {- lift∫ : (f : Set → Set) → ∫ → ∫ lift∫ f (A⁺ , A⁻) = A⁺ , f ∘ A⁻ liftLens : ∀ {A B} (f : Set → Set) → ∫[ A , B ] → ∫[ lift∫ f A , lift∫ f B ] liftLens f l a⁺ with l a⁺ ... | b⁺ , setb = b⁺ , φ setb -} {- module lift_comonad (f : Set → Set) {A : ∫} ⦃ f_monad : Monad f ⦄ where extract : lift∫ f A ↝ A extract a⁺ = a⁺ , η f_monad -- id ↕ λ _ → η duplicate : lift∫ f A ↝ lift∫ f (lift∫ f A) duplicate a⁺ = a⁺ , μ -} module poly-ops where infixl 6 _⊗_ infixl 5 _⊕_ _⊕_ _⊗_ _⊠_ _⊚_ : ∫ → ∫ → ∫ (A⁺ , A⁻) ⊕ (B⁺ , B⁻) = (A⁺ ⊎ B⁺) , (A⁻ ⨄ B⁻) -- coproduct (A⁺ , A⁻) ⊗ (B⁺ , B⁻) = (A⁺ × B⁺) , (A⁻ ⨃ B⁻) -- product (A⁺ , A⁻) ⊠ (B⁺ , B⁻) = (A⁺ × B⁺) , (A⁻ ⨉ B⁻) -- juxtapose (A⁺ , A⁻) ⊚ (B⁺ , B⁻) = (Σ[ a⁺ ∈ A⁺ ](A⁻ a⁺ → B⁺)) -- compose , λ (_ , bs) → ∃ (B⁻ ∘ bs) -- N-ary Σ⊕ : (I → ∫) → ∫ Σ⊕ {I = I} A = Σ I (π₁ ∘ A) , λ (i , a⁺) → π₂ (A i) a⁺ Π⊗ : (I → ∫) → ∫ Π⊗ {I = I} a = ((i : I) → π₁ (a i)) , λ a⁺ → Σ[ i ∈ I ](π₂ (a i) (a⁺ i)) Π⊠ : (I → ∫) → ∫ Π⊠ {I = I} a = ((i : I) → π₁ (a i)) , (λ a⁺ → (i : I) -> π₂ (a i) (a⁺ i)) _ᵒ_ : ∫ → ℕ → ∫ _ ᵒ ℕz = 𝒴 a ᵒ ℕs n = a ⊚ (a ᵒ n) open poly-ops public module lens-ops where _⟦+⟧_ : ∀ {a b x y} → ∫[ a , b ] → ∫[ x , y ] → ∫[ a ⊕ x , b ⊕ y ] -- coproduct _⟦|⟧_ : ∀ {a b x } → ∫[ a , x ] → ∫[ b , x ] → ∫[ a ⊕ b , x ] -- copair _⟦⊗⟧_ : ∀ {a b x y} → ∫[ a , b ] → ∫[ x , y ] → ∫[ a ⊗ x , b ⊗ y ] -- product _⟦×⟧_ : ∀ {x a b } → ∫[ x , a ] → ∫[ x , b ] → ∫[ x , a ⊗ b ] -- pair _⟦⊠⟧_ : ∀ {a b x y} → ∫[ a , b ] → ∫[ x , y ] → ∫[ a ⊠ x , b ⊠ y ] -- juxtaposition _⟦⊚⟧_ : ∀ {a b x y} → ∫[ a , b ] → ∫[ x , y ] → ∫[ a ⊚ x , b ⊚ y ] -- composition (a↝b ⟦+⟧ x↝y) = λ{(Σ₁ a⁺) → let b⁺ , setb = a↝b a⁺ in Σ₁ b⁺ , setb ;(Σ₂ x⁺) → let y⁺ , sety = x↝y x⁺ in Σ₂ y⁺ , sety} (a↝x ⟦|⟧ b↝x) = λ{(Σ₁ a⁺) → a↝x a⁺ ;(Σ₂ b⁺) → b↝x b⁺} (a↝b ⟦⊗⟧ x↝y) (a⁺ , x⁺) with a↝b a⁺ | x↝y x⁺ ... | b⁺ , setb | y⁺ , sety = (b⁺ , y⁺) , λ{(Σ₁ b⁻) → Σ₁ (setb b⁻) ;(Σ₂ y⁻) → Σ₂ (sety y⁻)} _⟦×⟧_ x↝a x↝b x⁺ with x↝a x⁺ | x↝b x⁺ ... | a⁺ , seta | b⁺ , setb = (a⁺ , b⁺) , λ{(Σ₁ a⁻) → seta a⁻ ;(Σ₂ b⁻) → setb b⁻} _⟦⊠⟧_ a↝b x↝y (a⁺ , x⁺) = ((a⁺ ★ a↝b) , (x⁺ ★ x↝y)) , λ (b⁻ , y⁻) → (a⁺ # a↝b ← b⁻) , (x⁺ # x↝y ← y⁻) (a↝b ⟦⊚⟧ x↝y) (a⁺ , a⁻→x⁺) with a↝b a⁺ ... | b⁺ , setb = (b⁺ , get x↝y ∘ a⁻→x⁺ ∘ setb) , λ (b⁻ , y⁻) → let a⁻ = setb b⁻ in a⁻ , (a⁻→x⁺ a⁻ # x↝y ← y⁻) -- N-ary Π⟦⊠⟧ : {as bs : I → ∫} → ((i : I) → (∫[ as i , bs i ])) → ∫[ Π⊠ as , Π⊠ bs ] Π⟦⊠⟧ ls as⁺ = (λ i → as⁺ i ★ ls i) , (λ dbs i → as⁺ i # ls i ← dbs i) _⟦ᵒ⟧_ : ∫[ A , B ] → (n : ℕ) → ∫[ A ᵒ n , B ᵒ n ] _⟦ᵒ⟧_ {a} {b} l = go where go : (n : ℕ) → ∫[ a ᵒ n , b ᵒ n ] go ℕz = 𝒾 {x = 𝒴} go (ℕs n) = l ⟦⊚⟧ (go n) open lens-ops public
# Connecting Qiskit Pulse with Qiskit Dynamics This tutorial shows a simple model of a qubit used to demonstrate how Qiskit Dynamics can simulate the time evolution of a pulse schedule. The qubit is modeled by the drift hamiltonian \begin{align} \hat H_\text{drift} = \frac{\omega}{2} Z \end{align} to which we apply the drive \begin{align} \hat H_\text{drive}(t) = \frac{r\,\Omega(t)}{2} X \end{align} Here, $\Omega(t)$ is the drive signal which we will create using Qiskit pulse. The factor $r$ is the strength with which the drive signal drives the qubit. We begin by creating a pulse schedule with a `sx` gate followed by a phase shift on the drive so that the following pulse creates a `sy` rotation. Therefore, if the qubit begins in the ground state we expect that this second pulse will not have any effect on the qubit. This situation is simulated with the following steps: 1. Create the pulse schedule 2. Convert the pulse schedule to a Signal 3. Create the system model 4. Simulate the pulse schedule using the model ## 1. Create the pulse schedule First, we use the pulse module in Qiskit to create a pulse schedule. ```python import numpy as np import qiskit.pulse as pulse ``` ```python # Strength of the Rabi-rate in GHz. r = 0.1 # Frequency of the qubit transition in GHz. w = 5. # Sample rate of the backend in ns. dt = 0.222 # Define gaussian envelope function to have a pi rotation. amp = 1. area = 1 sig = area*0.399128/r/amp T = 4*sig duration = int(T / dt) beta = 2.0 # The 1.75 factor is used to approximately get a sx gate. # Further "calibration" could be done to refine the pulse amplitude. with pulse.build(name="sx-sy schedule") as xp: pulse.play(pulse.Drag(duration, amp / 1.75, sig / dt, beta), pulse.DriveChannel(0)) pulse.shift_phase(np.pi/2, pulse.DriveChannel(0)) pulse.play(pulse.Drag(duration, amp / 1.75, sig / dt, beta), pulse.DriveChannel(0)) xp.draw() ``` ## 2. Convert the pulse schedule to a Signal To use Qiskit Dynamics we must convert the pulse schedule to instances of `Signal`. This is done using the pulse instruction to signal converter `InstructionToSignals`. This converter needs to know the sample rate of the arbitrary waveform generators creating the signals, i.e. `dt`, as well as the carrier frequency of the signals, i.e. `w`. The plot below shows the envelopes and the signals resulting from this conversion. The dashed line shows the time at which the virtual `Z` gate is applied. ```python from matplotlib import pyplot as plt from qiskit_dynamics.pulse import InstructionToSignals plt.rcParams["font.size"] = 16 ``` ```python converter = InstructionToSignals(dt, carriers=[w]) signals = converter.get_signals(xp) fig, axs = plt.subplots(1, 2, figsize=(14, 4.5)) for ax, title in zip(axs, ["envelope", "signal"]): signals[0].draw(0, 2*T, 2000, title, axis=ax) ax.set_xlabel("Time (ns)") ax.set_ylabel("Amplitude") ax.set_title(title) ax.vlines(T, ax.get_ylim()[0], ax.get_ylim()[1], "k", linestyle="dashed") ``` ## 3. Create the system model We now setup the Hamiltonian with the signals as drives, enter the rotating frame and perform the rotating wave approximation. ```python from qiskit.quantum_info.operators import Operator from qiskit_dynamics import Solver ``` ```python # construct operators X = Operator.from_label('X') Z = Operator.from_label('Z') drift = 2 * np.pi * w * Z/2 operators = [2 * np.pi * r * X/2] # construct the solver hamiltonian_solver = Solver( drift=drift, hamiltonian_operators=operators, hamiltonian_signals=signals, rotating_frame=drift, rwa_cutoff_freq=2*w ) ``` ## 4. Simulate the pulse schedule using the model In the last step we perform the simulation and plot the results. ```python from qiskit.quantum_info.states import Statevector ``` ```python # Start the qubit in its ground state. y0 = Statevector([1., 0.]) %time sol = hamiltonian_solver.solve(t_span=[0., 2*T], y0=y0, atol=1e-10, rtol=1e-10) ``` CPU times: user 24.6 s, sys: 1.82 ms, total: 24.6 s Wall time: 24.6 s ```python def plot_populations(sol): pop0 = [psi.probabilities()[0] for psi in sol.y] pop1 = [psi.probabilities()[1] for psi in sol.y] fig = plt.figure(figsize=(8, 5)) plt.plot(sol.t, pop0, lw=3, label="Population in |0>") plt.plot(sol.t, pop1, lw=3, label="Population in |1>") plt.xlabel("Time (ns)") plt.ylabel("Population") plt.legend(frameon=False) plt.ylim([0, 1.05]) plt.xlim([0, 2*T]) plt.vlines(T, 0, 1.05, "k", linestyle="dashed") ``` The plot below shows the population of the qubit as it evolves during the pulses. The vertical dashed line shows the time of the virtual Z rotation which was induced by the `shift_phase` instruction in the pulse schedule. As expected, the first pulse moves the qubit to an eigenstate of the `Y` operator. Therefore, the second pulse, which drives around the `Y`-axis due to the phase shift, has hardley any influence on the populations of the qubit. ```python plot_populations(sol) ``` ```python ```
There are many signs in this world that call to us on a daily basis; but if you're not looking for them, chances are you're not going to find them. Waking up at the same time every night, even when you've not set any alarms? This is one sign that many people miss. As a human on this Earth, you are inherently powerful with a myriad of different energies, and energy meridians. As these meridians are used in Traditional Chinese Medicine, they are linked to a clock-like system that energizes certain regions of the body, depending on the time of day. If you're having a tough time falling asleep during this time period (which is the most common bedtime for people), it's a sign that you're still carrying the stresses and worries from your day. To combat these effects, practice meditation, promotive mantras, and other relaxation practices. Yoga and stretching also work wonders. Traditional Chinese Medicine posits that this period of time is linked to our gall bladders. If you're waking up during these hours, it can be indicative of emotional disappointment. Focus on unconditional self-love, and remember to forgive yourself for any mistakes you've made. This time period is connected to our liver. If you're waking during these hours, it's a good sign that you are harboring feelings of anger, and have too much yang energy. Poor a tall glass of cold water and reconcile with your anger; figure out what is troubling you, so you may get some rest. Waking during these hours is linked to our lungs, and is a sign of sadness. To return to restful nights, practice deep breathing exercises while you focus your thoughts on expressing faith in whatever your higher power may be. Know that they will help you. Additionally, waking between these hours can be a sign that your higher power is trying to tell you something. When they are sending you messages, it is wise to pay attention; they are trying to bring you into better alignment with your ultimate purpose. During this time, our energy resides mostly in our guts, the large intestines. If you're waking up during these hours, you might having emotional blockages. Once you're awake, stretch out your body or use the bathroom to fall back into a slumber. When we dream, we are highly receptive of any messages being sent to us from our Higher Power. If we look closely enough, we can see that our dreams depict certain details of our journey through life. This spiritual journey is important, and thus, so are the messages being sent to us. Once we realize that we are living this life in order to become the best version of ourselves that we can possibly be, we gain a higher awareness, a deeper form of consciousness, one that allows us to ascend. Consistently waking between 3:00am and 5:00am is a sign that your Higher Power is trying to contact you. Do your best to listen to what it has to say.
#include <LibtorrentWrapper/WrapperInternal.h> #include <QtCore/QFileInfo> #include <QtCore/QSysInfo> #include <QtCore/QUrl> #include <libtorrent/hasher.hpp> #include <libtorrent/storage.hpp> #include <libtorrent/bencode.hpp> #include <libtorrent/alert.hpp> #include <libtorrent/alert_types.hpp> #include <libtorrent/extensions/ut_pex.hpp> #include <libtorrent/extensions/smart_ban.hpp> #include <libtorrent/peer_info.hpp> #include <libtorrent/config.hpp> #include <libtorrent/session.hpp> #include <libtorrent/error_code.hpp> #include <libtorrent/torrent_info.hpp> #include <libtorrent/torrent_handle.hpp> #include <libtorrent/entry.hpp> #include <libtorrent/lazy_entry.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <QtCore/QMutexLocker> #include <QtCore/QVariant> #include <QtCore/QMetaObject> #include <QtCore/QCoreApplication> #include <QtCore/QDir> #include <QtCore/QFileInfo> #include <QtCore/QTime> #include <QtCore/QDebug> #define SIGNAL_CONNECT_CHECK(X) { bool result = X; Q_ASSERT_X(result, __FUNCTION__ , #X); } using namespace libtorrent; namespace P1 { namespace Libtorrent { WrapperInternal::WrapperInternal(QObject *parent) : QObject(parent) , _session(0) , _seedEnabled(false) , _shuttingDown(false) , _initialized(false) , _lastDirectDownloaded(0) , _lastPeerDownloaded(0) , _uploadRateLimit(-1) , _downloadRateLimit(-1) , _connectionsLimit(-1) { this->_fastResumeWaitTimeInSec = 30; this->_fastresumeCounterMax = 40; this->_fastresumeCounter = 0; this->_startupListeningPort = 11888; this->_errorNotificationHandler.wrapperInternal = this; this->_statusNotificationHandler.wrapperInternal = this; this->_trackerNotificationHandler.wrapperInternal = this; this->_storageNotificationHandler.wrapperInternal = this; SIGNAL_CONNECT_CHECK(QObject::connect(&this->_alertTimer, SIGNAL(timeout()), this, SLOT(alertTimerTick()))); SIGNAL_CONNECT_CHECK(QObject::connect(&this->_progressTimer, SIGNAL(timeout()), this, SLOT(progressTimerTick()))); } WrapperInternal::~WrapperInternal() { delete this->_session; } void WrapperInternal::initEngine(libtorrent::session_settings &settings) { QMutexLocker lock(&this->_torrentsMapLock); if (this->_shuttingDown) return; // 1. construct a session // 2. load_state() // 3. add_extension() // 4. start DHT, LSD, UPnP, NAT-PMP etc this->_session = new session(fingerprint("LT", LIBTORRENT_VERSION_MAJOR, LIBTORRENT_VERSION_MINOR, 0, 0) , session::start_default_features | session::add_default_plugins , alert::error_notification + alert::status_notification + alert::tracker_notification + alert::storage_notification ); this->_session->start_lsd(); this->_session->start_upnp(); this->_session->start_natpmp(); this->_session->start_dht(); this->_session->add_dht_router(std::make_pair(std::string("router.bittorrent.com"), 6881)); this->_session->add_dht_router(std::make_pair(std::string("router.utorrent.com"), 6881)); this->_session->add_dht_router(std::make_pair(std::string("router.bitcomet.com"), 6881)); error_code ec; this->_session->listen_on(std::make_pair(this->_startupListeningPort, this->_startupListeningPort), ec); if (ec) { DEBUG_LOG << "can't listen on " << this->_startupListeningPort << " error code " << ec; emit this->listenFailed(this->_startupListeningPort, ec.value()); } this->loadSessionState(); this->setProfile(settings); if (this->_seedEnabled) QTimer::singleShot(300000, this, SLOT(backgroundSeedStart())); this->_alertTimer.start(100); this->_progressTimer.start(1000); this->_initialized = true; } void WrapperInternal::setProfile(libtorrent::session_settings &settings) { if (!this->_session || this->_shuttingDown) return; if (this->_connectionsLimit != -1) settings.connections_limit = this->_connectionsLimit; if (this->_uploadRateLimit != -1) settings.upload_rate_limit = this->_uploadRateLimit; if (this->_downloadRateLimit != -1) settings.download_rate_limit = this->_downloadRateLimit; this->_session->set_settings(settings); } void WrapperInternal::start(const QString& id, TorrentConfig& config) { QMutexLocker lock(&this->_torrentsMapLock); if (!this->_initialized) return; TorrentState *state = this->getStateById(id); if (!state) { this->loadAndStartTorrent(id, config); return; } DEBUG_LOG << "start " << id << " background " << state->backgroundSeeding() << " reload require " << config.isReloadRequired(); if (state->pathToTorrent() != config.pathToTorrentFile()) config.setIsReloadRequired(true); if (config.isReloadRequired()) { this->_session->remove_torrent(state->handle()); this->_idToTorrentState.remove(id); QString infohash = QString::fromStdString(state->handle().info_hash().to_string()); this->_infohashToTorrentState.remove(infohash); delete state; this->loadAndStartTorrent(id, config); } else { state->setBackgroundSeeding(false); torrent_handle handle = state->handle(); // UNDONE: Тут могут остаьтся пробелмы с другими стадиями. if (handle.is_valid()) { if (config.rehashOnly()) { if (handle.status().state == torrent_status::seeding) { emit this->torrentRehashed(id, true); } else if (handle.status().state == torrent_status::downloading) { emit this->torrentRehashed(id, false); } else { handle.resume(); } } else { if (handle.status().state == torrent_status::seeding) emit this->torrentDownloadFinished(id); else handle.resume(); } } } } void WrapperInternal::createFastResume(const QString& id, TorrentConfig& config) { error_code ec; torrent_info torrentInfo(config.pathToTorrentFile().toUtf8().data(), ec); if (ec) { WARNING_LOG << "Can't create torrent info from file" << config.pathToTorrentFile() << "with reasons" << QString::fromLocal8Bit(ec.message().c_str()); return; } libtorrent::entry entry; entry["file-format"] = "libtorrent resume file"; entry["file-version"] = 1; entry["libtorrent-version"] = LIBTORRENT_VERSION; entry["sequential_download"] = 0; entry["save_path"] = config.downloadPath().toUtf8().data(); entry["info-hash"] = torrentInfo.info_hash().to_string(); auto fileSizes = libtorrent::get_filesizes(torrentInfo.files(), config.downloadPath().toStdString()); libtorrent::entry::list_type& fl = entry["file sizes"].list(); for (std::vector<std::pair<libtorrent::size_type, std::time_t> >::iterator i = fileSizes.begin(), end(fileSizes.end()); i != end; ++i) { libtorrent::entry::list_type p; p.push_back(libtorrent::entry(i->first)); p.push_back(libtorrent::entry(i->second)); fl.push_back(libtorrent::entry(p)); } libtorrent::entry::string_type& pieces = entry["pieces"].string(); pieces.resize(torrentInfo.num_pieces()); std::memset(&pieces[0], 1, pieces.size()); this->saveFastResumeEntry(this->getFastResumeFilePath(id), entry); } void WrapperInternal::stop(const QString& id) { QMutexLocker lock(&this->_torrentsMapLock); if (!this->_initialized) return; TorrentState *state = this->getStateById(id); if (!state) return; if (state->handle().is_valid()) { state->setIsStopping(true); state->handle().pause(); } } void WrapperInternal::remove(const QString& id) { QMutexLocker lock(&this->_torrentsMapLock); if (!this->_initialized) return; TorrentState *state = this->getStateById(id); if (!state) return; this->_session->remove_torrent(state->handle()); this->_idToTorrentState.remove(id); QString infohash = QString::fromStdString(state->handle().info_hash().to_string()); this->_infohashToTorrentState.remove(infohash); delete state; } void WrapperInternal::setTorrentConfigDirectoryPath(const QString& path) { this->_torrentConfigDirectoryPath = path; } void WrapperInternal::alertTimerTick() { std::auto_ptr<alert> alertObject = this->_session->pop_alert(); while (alertObject.get()) { if (tracker_error_alert* p = alert_cast<tracker_error_alert>(alertObject.get())) this->_errorNotificationHandler(*p); else if (tracker_warning_alert* p = alert_cast<tracker_warning_alert>(alertObject.get())) this->_errorNotificationHandler(*p); else if (scrape_failed_alert* p = alert_cast<scrape_failed_alert>(alertObject.get())) this->_errorNotificationHandler(*p); else if (torrent_delete_failed_alert* p = alert_cast<torrent_delete_failed_alert>(alertObject.get())) this->_errorNotificationHandler(*p); if (save_resume_data_failed_alert* p = alert_cast<save_resume_data_failed_alert>(alertObject.get())) this->_errorNotificationHandler(*p); else if (url_seed_alert* p = alert_cast<url_seed_alert>(alertObject.get())) this->_errorNotificationHandler(*p); else if (file_error_alert* p = alert_cast<file_error_alert>(alertObject.get())) this->_errorNotificationHandler(*p); else if (metadata_failed_alert* p = alert_cast<metadata_failed_alert>(alertObject.get())) this->_errorNotificationHandler(*p); else if (udp_error_alert* p = alert_cast<udp_error_alert>(alertObject.get())) this->_errorNotificationHandler(*p); else if (listen_failed_alert* p = alert_cast<listen_failed_alert>(alertObject.get())) this->_errorNotificationHandler(*p); else if (portmap_error_alert* p = alert_cast<portmap_error_alert>(alertObject.get())) this->_errorNotificationHandler(*p); else if (fastresume_rejected_alert* p = alert_cast<fastresume_rejected_alert>(alertObject.get())) this->_errorNotificationHandler(*p); else if (torrent_error_alert* p = alert_cast<torrent_error_alert>(alertObject.get())) this->_errorNotificationHandler(*p); else if (state_changed_alert* p = alert_cast<state_changed_alert>(alertObject.get())) this->_statusNotificationHandler(*p); else if (hash_failed_alert* p = alert_cast<hash_failed_alert>(alertObject.get())) this->_statusNotificationHandler(*p); else if (torrent_finished_alert* p = alert_cast<torrent_finished_alert>(alertObject.get())) this->_statusNotificationHandler(*p); else if (torrent_paused_alert* p = alert_cast<torrent_paused_alert>(alertObject.get())) this->_statusNotificationHandler(*p); else if (torrent_resumed_alert* p = alert_cast<torrent_resumed_alert>(alertObject.get())) this->_statusNotificationHandler(*p); else if (torrent_checked_alert* p = alert_cast<torrent_checked_alert>(alertObject.get())) this->_statusNotificationHandler(*p); else if (metadata_received_alert* p = alert_cast<metadata_received_alert>(alertObject.get())) this->_statusNotificationHandler(*p); else if (external_ip_alert* p = alert_cast<external_ip_alert>(alertObject.get())) this->_statusNotificationHandler(*p); else if (listen_succeeded_alert* p = alert_cast<listen_succeeded_alert>(alertObject.get())) this->_statusNotificationHandler(*p); else if (torrent_added_alert* p = alert_cast<torrent_added_alert>(alertObject.get())) this->_statusNotificationHandler(*p); else if (trackerid_alert* p = alert_cast<trackerid_alert>(alertObject.get())) this->_statusNotificationHandler(*p); else if (torrent_removed_alert* p = alert_cast<torrent_removed_alert>(alertObject.get())) this->_statusNotificationHandler(*p); else if (tracker_announce_alert* p = alert_cast<tracker_announce_alert>(alertObject.get())) this->_trackerNotificationHandler(*p); else if (scrape_reply_alert* p = alert_cast<scrape_reply_alert>(alertObject.get())) this->_trackerNotificationHandler(*p); else if (tracker_reply_alert* p = alert_cast<tracker_reply_alert>(alertObject.get())) this->_trackerNotificationHandler(*p); else if (dht_reply_alert* p = alert_cast<dht_reply_alert>(alertObject.get())) this->_trackerNotificationHandler(*p); else if (read_piece_alert* p = alert_cast<read_piece_alert>(alertObject.get())) this->_storageNotificationHandler(*p); else if (file_renamed_alert* p = alert_cast<file_renamed_alert>(alertObject.get())) this->_storageNotificationHandler(*p); else if (file_rename_failed_alert* p = alert_cast<file_rename_failed_alert>(alertObject.get())) this->_storageNotificationHandler(*p); else if (storage_moved_alert* p = alert_cast<storage_moved_alert>(alertObject.get())) this->_storageNotificationHandler(*p); else if (storage_moved_failed_alert* p = alert_cast<storage_moved_failed_alert>(alertObject.get())) this->_storageNotificationHandler(*p); else if (torrent_deleted_alert* p = alert_cast<torrent_deleted_alert>(alertObject.get())) this->_storageNotificationHandler(*p); else if (save_resume_data_alert* p = alert_cast<save_resume_data_alert>(alertObject.get())) this->_storageNotificationHandler(*p); else if (cache_flushed_alert* p = alert_cast<cache_flushed_alert>(alertObject.get())) this->_storageNotificationHandler(*p); else { QString str = QString::fromLocal8Bit(alertObject->message().c_str()); qCritical() << "unhandled_alert category: " << alertObject->category() << typeid(*alertObject).name() << " msg: " << str; } alertObject = this->_session->pop_alert(); } } void WrapperInternal::progressTimerTick() { if (!this->_torrentsMapLock.tryLock()) return; if (!this->_initialized) return; QMap<QString, TorrentState*>::const_iterator it = this->_idToTorrentState.constBegin(); QMap<QString, TorrentState*>::const_iterator end = this->_idToTorrentState.constEnd(); for(; it != end; ++it) { TorrentState *state = it.value(); if (state->backgroundSeeding()) continue; torrent_handle handle = state->handle(); if (!handle.is_valid()) continue; torrent_status status = handle.status(0); if (status.paused) continue; if (status.state == torrent_status::downloading || status.state == torrent_status::checking_files) { this->emitTorrentProgress(state->id(), handle); } if (status.state == torrent_status::downloading) { if (this->_fastresumeCounter > this->_fastresumeCounterMax) { handle.save_resume_data(); this->_fastresumeCounter = 0; } else { this->_fastresumeCounter++; } } } this->_torrentsMapLock.unlock(); } int WrapperInternal::loadFile(std::string const& filename, std::vector<char>& v, error_code& ec, int limit) { ec.clear(); file f; if (!f.open(filename, file::read_only, ec)) return -1; size_type s = f.get_size(ec); if (ec) return -1; if (s > limit) { ec = error_code(errors::metadata_too_large, get_libtorrent_category()); return -2; } v.resize(s); if (s == 0) return 0; file::iovec_t b = {&v[0], s}; size_type read = f.readv(0, &b, 1, ec); if (read != s) return -3; if (ec) return -3; return 0; } void WrapperInternal::loadAndStartTorrent(const QString& id, const TorrentConfig &config, bool backgroudSeeding) { if (config.isSeedEnable()) { ResumeInfo resumeInfo; resumeInfo.setId(id); resumeInfo.setSavePath(config.downloadPath()); resumeInfo.setTorrentPath(config.pathToTorrentFile()); this->_resumeInfo[id] = resumeInfo; } if (backgroudSeeding) DEBUG_LOG << "background " << id; error_code ec; torrent_info *torrentInfo = new torrent_info(config.pathToTorrentFile().toUtf8().data(), ec); if (ec) { QString str = QString::fromLocal8Bit(ec.message().c_str()); WARNING_LOG << "Can't create torrent info from file" << config.pathToTorrentFile() << "with reasons" << str; emit this->startTorrentFailed(id, ec.value()); return; } add_torrent_params p; p.flags = add_torrent_params::flag_override_resume_data; p.ti = torrentInfo; // Должен быть определен дефайн UNICODE // http://article.gmane.org/gmane.network.bit-torrent.libtorrent/1482/match=save+path QByteArray downloadPathArray = config.downloadPath().toUtf8(); p.save_path = downloadPathArray.data(); p.storage_mode = libtorrent::storage_mode_sparse; QString resumeFilePath = this->getFastResumeFilePath(id); std::vector<char> buf; if (!config.isForceRehash()) { if (this->loadFile(resumeFilePath.toUtf8().data(), buf, ec) == 0) p.resume_data = buf; else DEBUG_LOG << "can't load fast resume for" << id << "error" << ec.value(); } else { DEBUG_LOG << "force rehash for" << id; } torrent_handle h = this->_session->add_torrent(p, ec); if (ec) { QString str = QString::fromLocal8Bit(ec.message().c_str()); CRITICAL_LOG << "start error" << str << "in" << id; emit this->startTorrentFailed(id, ec.value()); return; } this->updateTrackerCredentials(h); TorrentState *state = new TorrentState(); state->setId(id); state->setHandle(h); state->setBackgroundSeeding(backgroudSeeding); state->setRehashOnly(config.rehashOnly()); state->setIsSeedEnable(config.isSeedEnable()); state->setPathToTorrent(config.pathToTorrentFile()); this->_idToTorrentState[id] = state; QString infohash = QString::fromStdString(torrentInfo->info_hash().to_string()); this->_infohashToTorrentState[infohash] = state; } P1::Libtorrent::EventArgs::ProgressEventArgs::TorrentStatus WrapperInternal::convertStatus(torrent_status::state_t status) { switch(status) { case torrent_status::queued_for_checking: return P1::Libtorrent::EventArgs::ProgressEventArgs::QueuedForChecking; case torrent_status::checking_files: return P1::Libtorrent::EventArgs::ProgressEventArgs::CheckingFiles; case torrent_status::downloading_metadata: return P1::Libtorrent::EventArgs::ProgressEventArgs::DownloadingMetadata; case torrent_status::downloading: return P1::Libtorrent::EventArgs::ProgressEventArgs::Downloading; case torrent_status::finished: return P1::Libtorrent::EventArgs::ProgressEventArgs::Finished; case torrent_status::seeding: return P1::Libtorrent::EventArgs::ProgressEventArgs::Seeding; case torrent_status::allocating: return P1::Libtorrent::EventArgs::ProgressEventArgs::Allocating; case torrent_status::checking_resume_data: return P1::Libtorrent::EventArgs::ProgressEventArgs::CheckingResumeData; } return P1::Libtorrent::EventArgs::ProgressEventArgs::Finished; } void WrapperInternal::saveFastResume(const torrent_handle &handle, boost::shared_ptr<entry> resumeData) { QMutexLocker lock(&this->_torrentsMapLock); if (!this->_initialized) return; this->saveFastResumeWithoutLock(handle, resumeData); } void WrapperInternal::saveFastResumeWithoutLock(const torrent_handle &handle, boost::shared_ptr<entry> resumeData) { TorrentState *state = this->getStateByTorrentHandle(handle); if (!state) return; QString resumeFilePath = this->getFastResumeFilePath(state->id()); this->saveFastResumeEntry(resumeFilePath, *resumeData); } QString WrapperInternal::getFastResumeFilePath(const QString& id) { return QString("%1/%2.resume").arg(this->_torrentConfigDirectoryPath, id); } void WrapperInternal::shutdown() { QMutexLocker lock(&this->_torrentsMapLock); this->_shuttingDown = true; if (!this->_initialized) return; this->_initialized = false; this->_alertTimer.stop(); this->_progressTimer.stop(); this->_session->pause(); this->_session->stop_lsd(); this->_session->stop_upnp(); this->_session->stop_natpmp(); int numResumeData = 0; QMap<QString, TorrentState*>::const_iterator it = this->_idToTorrentState.constBegin(); QMap<QString, TorrentState*>::const_iterator end = this->_idToTorrentState.constEnd(); for(; it != end; ++it) { torrent_handle h = it.value()->handle(); if (!h.is_valid()) continue; if (h.status().paused) continue; if (!h.status().has_metadata) continue; h.save_resume_data(); ++numResumeData; } while (numResumeData > 0) { alert const* a = this->_session->wait_for_alert(seconds(this->_fastResumeWaitTimeInSec)); if (a == 0) { WARNING_LOG << "failed to wait for all fast resume saved"; break; } std::auto_ptr<alert> holder = this->_session->pop_alert(); const save_resume_data_failed_alert *failAlert = alert_cast<save_resume_data_failed_alert>(a); if (failAlert) { WARNING_LOG << "failed to save fast resume" << QString::fromStdString(failAlert->message()); --numResumeData; continue; } save_resume_data_alert const* rd = alert_cast<save_resume_data_alert>(a); if (!rd) continue; --numResumeData; if (!rd->resume_data) continue; this->saveFastResumeWithoutLock(rd->handle, rd->resume_data); } this->saveSessionState(); this->_session->stop_dht(); delete this->_session; this->_session = 0; this->cleanIdToTorrentStateMap(); } void WrapperInternal::createDirectoryIfNotExists(const QString& resumeFilePath) { QDir dir = QFileInfo(resumeFilePath).absoluteDir(); if (!dir.exists()) dir.mkpath(dir.absolutePath()); } void WrapperInternal::torrentPausedAlert(const torrent_handle &handle) { QMutexLocker lock(&this->_torrentsMapLock); if (!this->_initialized) return; TorrentState *state = getStateByTorrentHandle(handle); DEBUG_LOG << "torrentPausedAlert" << (state ? state->id() : "") << (state ? state->backgroundSeeding() : ""); if (!state || state->backgroundSeeding() || !handle.is_valid() || !state->isSeedEnable()) return; handle.save_resume_data(); if (state->isStopping()) { state->setIsStopping(false); this->emitTorrentProgress(state->id(), handle); emit this->torrentPaused(state->id()); } } void WrapperInternal::calcDirectSpeed(P1::Libtorrent::EventArgs::ProgressEventArgs& args, const libtorrent::torrent_handle &handle) { std::vector<libtorrent::peer_info> peerInfo; handle.get_peer_info(peerInfo); int peerInfoSize = peerInfo.size(); int directDownloadSpeed = 0; int peerDownloadSpeed = 0; qint64 directDownloaded = 0; qint64 peerDownloaded = 0; for (std::vector<libtorrent::peer_info>::iterator i = peerInfo.begin(); i != peerInfo.end(); ++i) { if ((*i).connection_type == libtorrent::peer_info::web_seed) { directDownloadSpeed += (*i).down_speed; directDownloaded += (*i).total_download; } if ((*i).connection_type != libtorrent::peer_info::web_seed) { peerDownloadSpeed += (*i).down_speed; peerDownloaded += (*i).total_download; } } if (peerInfoSize > 0) { this->_lastDirectDownloaded = directDownloaded; this->_lastPeerDownloaded = peerDownloaded; } args.setDirectPayloadDownloadRate(directDownloadSpeed); args.setDirectTotalDownload(directDownloaded); args.setPeerPayloadDownloadRate(peerDownloadSpeed); args.setPeerTotalDownload(peerDownloaded); } void WrapperInternal::emitTorrentProgress(const QString& id, const torrent_handle &handle) { torrent_status status = handle.status(0); this->emitTorrentProgress(id, handle, status, status.state); } void WrapperInternal::emitTorrentProgress( const QString& id, const torrent_handle& handle, torrent_status &status, torrent_status::state_t torrentState) { P1::Libtorrent::EventArgs::ProgressEventArgs args; args.setId(id); args.setProgress(status.progress); args.setStatus(this->convertStatus(torrentState)); args.setTotalWanted(status.total_wanted); args.setTotalWantedDone(status.total_wanted_done); args.setDownloadRate(status.download_rate); args.setUploadRate(status.upload_rate); // down\up payload rate args.setPayloadDownloadRate(status.download_payload_rate); args.setPayloadUploadRate(status.upload_payload_rate); this->calcDirectSpeed(args, handle); // down\up payload total args.setPayloadTotalDownload(this->_lastDirectDownloaded + this->_lastPeerDownloaded); args.setTotalPayloadUpload(status.total_payload_upload); // в случае паузы вычислить скачанное по пирам невозможно, поэтому показываем последние значения if (status.paused) { args.setDirectPayloadDownloadRate(0); args.setPeerPayloadDownloadRate(0); args.setDirectTotalDownload(this->_lastDirectDownloaded); args.setPeerTotalDownload(this->_lastPeerDownloaded); args.setPayloadUploadRate(0); } emit this->progressChanged(args); } void WrapperInternal::trackerErrorAlert(const torrent_handle &handle, int failCountInARow, int httpStatusCode) { QMutexLocker lock(&this->_torrentsMapLock); if (!this->_initialized) return; TorrentState *state = this->getStateByTorrentHandle(handle); if (state && !state->backgroundSeeding()) emit this->trackerFailed(state->id(), failCountInARow, httpStatusCode); } void WrapperInternal::fileErrorAlert(const torrent_handle &handle, const QString& filePath, int errorCode) { QMutexLocker lock(&this->_torrentsMapLock); if (!this->_initialized) return; TorrentState *state = this->getStateByTorrentHandle(handle); if (state && !state->backgroundSeeding()) emit this->fileError(state->id(), filePath, errorCode); } void WrapperInternal::listenFailAlert(int port, int errorCode) { emit this->listenFailed(port, errorCode); } void WrapperInternal::torrentStatusChangedAlert(const torrent_handle &handle, torrent_status::state_t oldState , torrent_status::state_t newState) { QMutexLocker lock(&this->_torrentsMapLock); if (!this->_initialized) return; TorrentState *state = this->getStateByTorrentHandle(handle); if (!state || !handle.is_valid()) return; DEBUG_LOG << "torrentStatusChangedAlert " << state->id() << " old " << oldState << " new " << newState << " background " << state->backgroundSeeding(); if (state->backgroundSeeding()) { if (newState == torrent_status::downloading) { torrent_status status = handle.status(0); if (!status.is_finished) state->handle().pause(); } return; } if (state->rehashOnly()) { if (newState == torrent_status::downloading) { torrent_status status = handle.status(0); if (!status.is_finished) { state->handle().pause(); emit this->torrentRehashed(state->id(), false); } return; } else if (newState == torrent_status::seeding) { emit this->torrentRehashed(state->id(), true); return; } } if (!state->isSeedEnable() && newState == torrent_status::seeding) state->handle().pause(); emit this->torrentStatusChanged(state->id(), this->convertStatus(oldState), this->convertStatus(newState)); torrent_status status = handle.status(0); this->emitTorrentProgress(state->id(), handle, status, oldState); } void WrapperInternal::torrentFinishedAlert(const torrent_handle &handle) { if (!handle.is_valid()) return; handle.save_resume_data(); QMutexLocker lock(&this->_torrentsMapLock); if (!this->_initialized) return; TorrentState *state = this->getStateByTorrentHandle(handle); if (!state) return; DEBUG_LOG << "torrentFinishedAlert " << state->id() << " background " << state->backgroundSeeding(); // Торрент скачан и готов к фоновому сидированию if (state->isSeedEnable()) { this->_resumeInfo[state->id()].setFinished(true); this->saveSessionState(); } if (!this->_seedEnabled) handle.pause(); if (state->backgroundSeeding()) return; emit this->torrentDownloadFinished(state->id()); this->emitTorrentProgress(state->id(), handle); torrent_status status = handle.status(0); this->emitTorrentProgress(state->id(), handle, status, torrent_status::downloading); } void WrapperInternal::torrentResumedAlert(const torrent_handle &handle) { QMutexLocker lock(&this->_torrentsMapLock); if (!this->_initialized) return; TorrentState *state = this->getStateByTorrentHandle(handle); if (state && !state->backgroundSeeding()) emit this->torrentResumed(state->id()); } TorrentState* WrapperInternal::getStateByTorrentHandle(const torrent_handle &handle) { if (!handle.is_valid()) return 0; QString infoHash = QString::fromStdString(handle.info_hash().to_string()); if (!this->_infohashToTorrentState.contains(infoHash)) return 0; return this->_infohashToTorrentState[infoHash]; } void WrapperInternal::changeListeningPort(unsigned short port) { error_code ec; this->_session->listen_on(std::make_pair(port, port), ec); if (ec) { CRITICAL_LOG << "can't start listen code: " << ec << "for port" << port; emit this->listenFailed(port, ec.value()); return; } int newport = this->_session->listen_port(); DEBUG_LOG << "start listen on " << newport; emit this->listeningPortChanged(newport); } void WrapperInternal::saveSessionState() { entry sessionState; this->_session->save_state(sessionState, libtorrent::session::save_settings | libtorrent::session::save_dht_settings | libtorrent::session::save_dht_state | libtorrent::session::save_feeds); entry::dictionary_type& resume = sessionState["GGSResumeInfo"].dict(); Q_FOREACH(ResumeInfo resumeInfo, this->_resumeInfo) { if (!resumeInfo.finished()) continue; std::string id(resumeInfo.id().toUtf8()); std::string torrentPath(resumeInfo.torrentPath().toUtf8()); std::string savePath(resumeInfo.savePath().toUtf8()); entry::dictionary_type& resumeService = resume[id].dict(); resumeService["torrentPath"].string() = torrentPath; resumeService["savePath"].string() = savePath; } QString resumeFilePath = this->getSessionStatePath(); this->createDirectoryIfNotExists(resumeFilePath); const wchar_t *resumePath = reinterpret_cast<const wchar_t*>(resumeFilePath.utf16()); try { boost::filesystem::ofstream out(resumePath, std::ios_base::binary); out.unsetf(std::ios_base::skipws); bencode(std::ostream_iterator<char>(out), sessionState); out.close(); } catch(boost::filesystem::filesystem_error& err) { DEBUG_LOG << err.what(); } catch(std::exception& stdExc) { DEBUG_LOG << stdExc.what(); } } void WrapperInternal::loadSessionState() { std::vector<char> in; error_code ec; QString sessionStatePath = this->getSessionStatePath(); QFileInfo fileInfo(sessionStatePath); if (!fileInfo.exists()) { DEBUG_LOG << "session state file" << sessionStatePath << "not exists"; return; } if (this->loadFile(sessionStatePath.toUtf8().data(), in, ec) != 0) { CRITICAL_LOG << "Can't load session state from" << sessionStatePath <<"with error code:" << ec; return; } if (in.size() == 0) return; lazy_entry e; if (lazy_bdecode(&in[0], &in[0] + in.size(), e, ec) != 0) return; this->_session->load_state(e); lazy_entry *resumeInfo = e.dict_find("GGSResumeInfo"); if (!resumeInfo) return; int size = resumeInfo->dict_size(); for (int i = 0; i < size; ++i) { std::pair<std::string, lazy_entry const*> p = resumeInfo->dict_at(i); QString id = QString::fromUtf8(p.first.c_str()); QString torrentPath = QString::fromUtf8(p.second->dict_find_string_value("torrentPath").c_str()); QString savePath = QString::fromUtf8(p.second->dict_find_string_value("savePath").c_str()); ResumeInfo info; info.setId(id); info.setFinished(true); info.setTorrentPath(torrentPath); info.setSavePath(savePath); this->_resumeInfo[id] = info; } } unsigned short WrapperInternal::listeningPort() const { if (!this->_session || this->_shuttingDown) return 0; return this->_session->listen_port(); } void WrapperInternal::setUploadRateLimit(int bytesPerSecond) { if (!this->_session || this->_shuttingDown) return; this->_uploadRateLimit = bytesPerSecond; libtorrent::session_settings settings = this->_session->settings(); settings.upload_rate_limit = bytesPerSecond; this->_session->set_settings(settings); } void WrapperInternal::setDownloadRateLimit(int bytesPerSecond) { if (!this->_session || this->_shuttingDown) return; this->_downloadRateLimit = bytesPerSecond; libtorrent::session_settings settings= this->_session->settings(); settings.download_rate_limit = bytesPerSecond; this->_session->set_settings(settings); } int WrapperInternal::uploadRateLimit() const { if (!this->_session || this->_shuttingDown) return 0; return this->_session->settings().upload_rate_limit; } int WrapperInternal::downloadRateLimit() const { if (!this->_session || this->_shuttingDown) return 0; return this->_session->settings().download_rate_limit; } TorrentState* WrapperInternal::getStateById(const QString& id) { if (!this->_idToTorrentState.contains(id)) return 0; return this->_idToTorrentState[id]; } QString WrapperInternal::getSessionStatePath() { return QString("%1/.session_state").arg(this->_torrentConfigDirectoryPath); } void WrapperInternal::torrentUrlSeedAlert(const torrent_handle &handle, const std::string& url ) { DEBUG_LOG << "url seed banned" << QString::fromStdString(url); if (handle.is_valid()) handle.add_url_seed(url); } void WrapperInternal::cleanIdToTorrentStateMap() { QMap<QString, TorrentState*>::const_iterator it = this->_idToTorrentState.constBegin(); QMap<QString, TorrentState*>::const_iterator end = this->_idToTorrentState.constEnd(); for(; it != end; ++it) delete it.value(); } void WrapperInternal::torrentErrorAlert(const libtorrent::torrent_handle &handle) { if (!handle.is_valid()) return; QMutexLocker lock(&this->_torrentsMapLock); if (!this->_initialized) return; TorrentState *state = this->getStateByTorrentHandle(handle); if (state && !state->backgroundSeeding()) emit this->torrentError(state->id()); } int WrapperInternal::maxConnection() { if (!this->_session || this->_shuttingDown) return 0; return this->_session->settings().connections_limit; } void WrapperInternal::setMaxConnection(int maxConnection) { if (!this->_session || this->_shuttingDown) return; this->_connectionsLimit = maxConnection; libtorrent::session_settings settings = this->_session->settings(); settings.connections_limit = maxConnection; this->_session->set_settings(settings); } void WrapperInternal::pauseSession() { if (!this->_session) return; this->_session->pause(); } void WrapperInternal::resumeSession() { if (!this->_session) return; this->_session->resume(); } void WrapperInternal::backgroundSeedStart() { QMutexLocker lock(&this->_torrentsMapLock); if (!this->_initialized) return; Q_FOREACH(ResumeInfo info, this->_resumeInfo) { if (!info.finished()) continue; if (this->_idToTorrentState.contains(info.id())) continue; TorrentConfig config; config.setDownloadPath(info.savePath()); config.setIsForceRehash(false); config.setIsReloadRequired(false); config.setPathToTorrentFile(info.torrentPath()); this->loadAndStartTorrent(info.id(), config, true); } } bool WrapperInternal::seedEnabled() const { return this->_seedEnabled; } void WrapperInternal::setSeedEnabled(bool value) { this->_seedEnabled = value; } bool WrapperInternal::getInfoHash(const QString& path, QString& result) { std::vector<char> in; error_code ec; QFileInfo fileInfo(path); if (!fileInfo.exists()) return false; if (this->loadFile(path.toUtf8().data(), in, ec) != 0) return false; if (in.size() == 0) return false; lazy_entry e; if (lazy_bdecode(&in[0], &in[0] + in.size(), e, ec) != 0) return false; lazy_entry const* info = e.dict_find_dict("info"); libtorrent::hasher h; std::pair<char const*, int> section = info->data_section(); h.update(section.first, section.second); sha1_hash infoHash = h.final(); std::string str = to_hex(infoHash.to_string()); result = QString::fromStdString(str); return true; } bool WrapperInternal::getFileList(const QString& path, QList<QString> &result) { error_code ec; torrent_info *torrentInfo = new torrent_info(path.toUtf8().data(), ec); if (ec) { QString str = QString::fromLocal8Bit(ec.message().c_str()); WARNING_LOG << "Can't create torrent info from file" << path << "with reasons" << str; return false; } QString torrentName = QString::fromStdString(torrentInfo->name()); int count = torrentInfo->num_files(); for (int i = 0; i < count; ++i) { std::string name = torrentInfo->file_at(i).path; QString fileName = QString::fromUtf8(name.c_str(), name.size()); fileName = fileName.right(fileName.length() - torrentName.length() - 1); result.append(fileName); } return true; } void WrapperInternal::saveFastResumeEntry(const QString &resumeFilePath, const libtorrent::entry &resumeData) { this->createDirectoryIfNotExists(resumeFilePath); try { const wchar_t *resumePath = reinterpret_cast<const wchar_t*>(resumeFilePath.utf16()); boost::filesystem::ofstream out(resumePath, std::ios_base::binary); out.unsetf(std::ios_base::skipws); bencode(std::ostream_iterator<char>(out), resumeData); out.close(); } catch (boost::filesystem::filesystem_error& err) { DEBUG_LOG << err.what(); } catch (std::exception& stdExc) { DEBUG_LOG << stdExc.what(); } } void WrapperInternal::setCredentials(const QString &userId, const QString &hash) { if (this->_credentialUserId == userId && this->_credentialHash == hash) return; this->_credentialUserId = userId; this->_credentialHash = hash; this->updateCredentials(); } void WrapperInternal::resetCredentials() { if (this->_credentialUserId.isEmpty() && this->_credentialHash.isEmpty()) return; this->_credentialUserId.clear(); this->_credentialHash.clear(); this->updateCredentials(); } void WrapperInternal::updateCredentials() { for (libtorrent::torrent_handle &torrent : this->_session->get_torrents()) { this->updateTrackerCredentials(torrent); } } void WrapperInternal::updateTrackerCredentials(libtorrent::torrent_handle& handle) { auto announceEntries = handle.trackers(); bool hasUdpTrackers = false; bool hasEmptyCreds = this->_credentialUserId.isEmpty() || this->_credentialHash.isEmpty(); QString query = hasEmptyCreds ? QString() : QString("userId=%1&hash=%2").arg(this->_credentialUserId).arg(this->_credentialHash); for (libtorrent::announce_entry &entry : announceEntries) { QUrl announceUrl(QString::fromStdString(entry.url)); if (announceUrl.scheme() != "udp") continue; if (hasEmptyCreds && !announceUrl.hasQuery()) continue; hasUdpTrackers = true; announceUrl.setQuery(query); announceUrl.setPath("/"); entry.url = announceUrl.toString().toStdString(); } if (hasUdpTrackers) handle.replace_trackers(announceEntries); } void WrapperInternal::setListeningPort(unsigned short port) { this->_startupListeningPort = port; } } }
"""Plot pointings to test pointing generation.""" import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np from frbpoppy import Survey N_POINTS = 1000 def plot_coordinates(ra, dec): """Plot coordinate in 3D plot.""" dec = np.deg2rad(dec) ra = np.deg2rad(ra) x = np.cos(ra) * np.cos(dec) y = np.sin(ra) * np.cos(dec) z = np.sin(dec) fig = plt.figure() ax = fig.add_subplot(111, projection=Axes3D.name) p = ax.scatter(x, y, z, c=np.arange(0, x.size)) plt.colorbar(p) ax.axes.set_xlim3d(left=-1, right=1) ax.axes.set_ylim3d(bottom=-1, top=1) ax.axes.set_zlim3d(bottom=-1, top=1) plt.show() if __name__ == '__main__': transit = Survey('chime-frb') transit.set_pointings(mount_type='transit', n_pointings=N_POINTS) transit.gen_pointings() plot_coordinates(*transit.pointings) tracking = Survey('perfect-small') tracking.set_pointings(mount_type='tracking', n_pointings=N_POINTS) tracking.gen_pointings() plot_coordinates(*tracking.pointings)
{-# OPTIONS --without-K --safe #-} module Categories.Morphism.Cartesian where open import Level open import Categories.Category open import Categories.Functor private variable o ℓ e : Level C D : Category o ℓ e record Cartesian (F : Functor C D) {X Y} (f : C [ X , Y ]) : Set (levelOfTerm F) where private module C = Category C module D = Category D open Functor F open D field universal : ∀ {A} {u : F₀ A ⇒ F₀ X} (h : C [ A , Y ]) → F₁ f ∘ u ≈ F₁ h → C [ A , X ] commute : ∀ {A} {u : F₀ A ⇒ F₀ X} {h : C [ A , Y ]} (eq : F₁ f ∘ u ≈ F₁ h) → C [ C [ f ∘ universal h eq ] ≈ h ] compat : ∀ {A} {u : F₀ A ⇒ F₀ X} {h : C [ A , Y ]} (eq : F₁ f ∘ u ≈ F₁ h) → F₁ (universal h eq) ≈ u
(* Title: HOL/Analysis/Path_Connected.thy Authors: LC Paulson and Robert Himmelmann (TU Muenchen), based on material from HOL Light *) section \<open>Path-Connectedness\<close> theory Path_Connected imports Starlike T1_Spaces begin subsection \<open>Paths and Arcs\<close> definition\<^marker>\<open>tag important\<close> path :: "(real \<Rightarrow> 'a::topological_space) \<Rightarrow> bool" where "path g \<equiv> continuous_on {0..1} g" definition\<^marker>\<open>tag important\<close> pathstart :: "(real \<Rightarrow> 'a::topological_space) \<Rightarrow> 'a" where "pathstart g \<equiv> g 0" definition\<^marker>\<open>tag important\<close> pathfinish :: "(real \<Rightarrow> 'a::topological_space) \<Rightarrow> 'a" where "pathfinish g \<equiv> g 1" definition\<^marker>\<open>tag important\<close> path_image :: "(real \<Rightarrow> 'a::topological_space) \<Rightarrow> 'a set" where "path_image g \<equiv> g ` {0 .. 1}" definition\<^marker>\<open>tag important\<close> reversepath :: "(real \<Rightarrow> 'a::topological_space) \<Rightarrow> real \<Rightarrow> 'a" where "reversepath g \<equiv> (\<lambda>x. g(1 - x))" definition\<^marker>\<open>tag important\<close> joinpaths :: "(real \<Rightarrow> 'a::topological_space) \<Rightarrow> (real \<Rightarrow> 'a) \<Rightarrow> real \<Rightarrow> 'a" (infixr "+++" 75) where "g1 +++ g2 \<equiv> (\<lambda>x. if x \<le> 1/2 then g1 (2 * x) else g2 (2 * x - 1))" definition\<^marker>\<open>tag important\<close> loop_free :: "(real \<Rightarrow> 'a::topological_space) \<Rightarrow> bool" where "loop_free g \<equiv> \<forall>x\<in>{0..1}. \<forall>y\<in>{0..1}. g x = g y \<longrightarrow> x = y \<or> x = 0 \<and> y = 1 \<or> x = 1 \<and> y = 0" definition\<^marker>\<open>tag important\<close> simple_path :: "(real \<Rightarrow> 'a::topological_space) \<Rightarrow> bool" where "simple_path g \<equiv> path g \<and> loop_free g" definition\<^marker>\<open>tag important\<close> arc :: "(real \<Rightarrow> 'a :: topological_space) \<Rightarrow> bool" where "arc g \<equiv> path g \<and> inj_on g {0..1}" subsection\<^marker>\<open>tag unimportant\<close>\<open>Invariance theorems\<close> lemma path_eq: "path p \<Longrightarrow> (\<And>t. t \<in> {0..1} \<Longrightarrow> p t = q t) \<Longrightarrow> path q" using continuous_on_eq path_def by blast lemma path_continuous_image: "path g \<Longrightarrow> continuous_on (path_image g) f \<Longrightarrow> path(f \<circ> g)" unfolding path_def path_image_def using continuous_on_compose by blast lemma continuous_on_translation_eq: fixes g :: "'a :: real_normed_vector \<Rightarrow> 'b :: real_normed_vector" shows "continuous_on A ((+) a \<circ> g) = continuous_on A g" proof - have g: "g = (\<lambda>x. -a + x) \<circ> ((\<lambda>x. a + x) \<circ> g)" by (rule ext) simp show ?thesis by (metis (no_types, opaque_lifting) g continuous_on_compose homeomorphism_def homeomorphism_translation) qed lemma path_translation_eq: fixes g :: "real \<Rightarrow> 'a :: real_normed_vector" shows "path((\<lambda>x. a + x) \<circ> g) = path g" using continuous_on_translation_eq path_def by blast lemma path_linear_image_eq: fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space" assumes "linear f" "inj f" shows "path(f \<circ> g) = path g" proof - from linear_injective_left_inverse [OF assms] obtain h where h: "linear h" "h \<circ> f = id" by blast with assms show ?thesis by (metis comp_assoc id_comp linear_continuous_on linear_linear path_continuous_image) qed lemma pathstart_translation: "pathstart((\<lambda>x. a + x) \<circ> g) = a + pathstart g" by (simp add: pathstart_def) lemma pathstart_linear_image_eq: "linear f \<Longrightarrow> pathstart(f \<circ> g) = f(pathstart g)" by (simp add: pathstart_def) lemma pathfinish_translation: "pathfinish((\<lambda>x. a + x) \<circ> g) = a + pathfinish g" by (simp add: pathfinish_def) lemma pathfinish_linear_image: "linear f \<Longrightarrow> pathfinish(f \<circ> g) = f(pathfinish g)" by (simp add: pathfinish_def) lemma path_image_translation: "path_image((\<lambda>x. a + x) \<circ> g) = (\<lambda>x. a + x) ` (path_image g)" by (simp add: image_comp path_image_def) lemma path_image_linear_image: "linear f \<Longrightarrow> path_image(f \<circ> g) = f ` (path_image g)" by (simp add: image_comp path_image_def) lemma reversepath_translation: "reversepath((\<lambda>x. a + x) \<circ> g) = (\<lambda>x. a + x) \<circ> reversepath g" by (rule ext) (simp add: reversepath_def) lemma reversepath_linear_image: "linear f \<Longrightarrow> reversepath(f \<circ> g) = f \<circ> reversepath g" by (rule ext) (simp add: reversepath_def) lemma joinpaths_translation: "((\<lambda>x. a + x) \<circ> g1) +++ ((\<lambda>x. a + x) \<circ> g2) = (\<lambda>x. a + x) \<circ> (g1 +++ g2)" by (rule ext) (simp add: joinpaths_def) lemma joinpaths_linear_image: "linear f \<Longrightarrow> (f \<circ> g1) +++ (f \<circ> g2) = f \<circ> (g1 +++ g2)" by (rule ext) (simp add: joinpaths_def) lemma loop_free_translation_eq: fixes g :: "real \<Rightarrow> 'a::euclidean_space" shows "loop_free((\<lambda>x. a + x) \<circ> g) = loop_free g" by (simp add: loop_free_def) lemma simple_path_translation_eq: fixes g :: "real \<Rightarrow> 'a::euclidean_space" shows "simple_path((\<lambda>x. a + x) \<circ> g) = simple_path g" by (simp add: simple_path_def loop_free_translation_eq path_translation_eq) lemma loop_free_linear_image_eq: fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space" assumes "linear f" "inj f" shows "loop_free(f \<circ> g) = loop_free g" using assms inj_on_eq_iff [of f] by (auto simp: loop_free_def) lemma simple_path_linear_image_eq: fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space" assumes "linear f" "inj f" shows "simple_path(f \<circ> g) = simple_path g" using assms by (simp add: loop_free_linear_image_eq path_linear_image_eq simple_path_def) lemma arc_translation_eq: fixes g :: "real \<Rightarrow> 'a::euclidean_space" shows "arc((\<lambda>x. a + x) \<circ> g) \<longleftrightarrow> arc g" by (auto simp: arc_def inj_on_def path_translation_eq) lemma arc_linear_image_eq: fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space" assumes "linear f" "inj f" shows "arc(f \<circ> g) = arc g" using assms inj_on_eq_iff [of f] by (auto simp: arc_def inj_on_def path_linear_image_eq) subsection\<^marker>\<open>tag unimportant\<close>\<open>Basic lemmas about paths\<close> lemma path_of_real: "path complex_of_real" unfolding path_def by (intro continuous_intros) lemma path_const: "path (\<lambda>t. a)" for a::"'a::real_normed_vector" unfolding path_def by (intro continuous_intros) lemma path_minus: "path g \<Longrightarrow> path (\<lambda>t. - g t)" for g::"real\<Rightarrow>'a::real_normed_vector" unfolding path_def by (intro continuous_intros) lemma path_add: "\<lbrakk>path f; path g\<rbrakk> \<Longrightarrow> path (\<lambda>t. f t + g t)" for f::"real\<Rightarrow>'a::real_normed_vector" unfolding path_def by (intro continuous_intros) lemma path_diff: "\<lbrakk>path f; path g\<rbrakk> \<Longrightarrow> path (\<lambda>t. f t - g t)" for f::"real\<Rightarrow>'a::real_normed_vector" unfolding path_def by (intro continuous_intros) lemma path_mult: "\<lbrakk>path f; path g\<rbrakk> \<Longrightarrow> path (\<lambda>t. f t * g t)" for f::"real\<Rightarrow>'a::real_normed_field" unfolding path_def by (intro continuous_intros) lemma pathin_iff_path_real [simp]: "pathin euclideanreal g \<longleftrightarrow> path g" by (simp add: pathin_def path_def) lemma continuous_on_path: "path f \<Longrightarrow> t \<subseteq> {0..1} \<Longrightarrow> continuous_on t f" using continuous_on_subset path_def by blast lemma inj_on_imp_loop_free: "inj_on g {0..1} \<Longrightarrow> loop_free g" by (simp add: inj_onD loop_free_def) lemma arc_imp_simple_path: "arc g \<Longrightarrow> simple_path g" by (simp add: arc_def inj_on_imp_loop_free simple_path_def) lemma arc_imp_path: "arc g \<Longrightarrow> path g" using arc_def by blast lemma arc_imp_inj_on: "arc g \<Longrightarrow> inj_on g {0..1}" by (auto simp: arc_def) lemma simple_path_imp_path: "simple_path g \<Longrightarrow> path g" using simple_path_def by blast lemma loop_free_cases: "loop_free g \<Longrightarrow> inj_on g {0..1} \<or> pathfinish g = pathstart g" by (force simp: inj_on_def loop_free_def pathfinish_def pathstart_def) lemma simple_path_cases: "simple_path g \<Longrightarrow> arc g \<or> pathfinish g = pathstart g" using arc_def loop_free_cases simple_path_def by blast lemma simple_path_imp_arc: "simple_path g \<Longrightarrow> pathfinish g \<noteq> pathstart g \<Longrightarrow> arc g" using simple_path_cases by auto lemma arc_distinct_ends: "arc g \<Longrightarrow> pathfinish g \<noteq> pathstart g" unfolding arc_def inj_on_def pathfinish_def pathstart_def by fastforce lemma arc_simple_path: "arc g \<longleftrightarrow> simple_path g \<and> pathfinish g \<noteq> pathstart g" using arc_distinct_ends arc_imp_simple_path simple_path_cases by blast lemma simple_path_eq_arc: "pathfinish g \<noteq> pathstart g \<Longrightarrow> (simple_path g = arc g)" by (simp add: arc_simple_path) lemma path_image_const [simp]: "path_image (\<lambda>t. a) = {a}" by (force simp: path_image_def) lemma path_image_nonempty [simp]: "path_image g \<noteq> {}" unfolding path_image_def image_is_empty box_eq_empty by auto lemma pathstart_in_path_image[intro]: "pathstart g \<in> path_image g" unfolding pathstart_def path_image_def by auto lemma pathfinish_in_path_image[intro]: "pathfinish g \<in> path_image g" unfolding pathfinish_def path_image_def by auto lemma connected_path_image[intro]: "path g \<Longrightarrow> connected (path_image g)" unfolding path_def path_image_def using connected_continuous_image connected_Icc by blast lemma compact_path_image[intro]: "path g \<Longrightarrow> compact (path_image g)" unfolding path_def path_image_def using compact_continuous_image connected_Icc by blast lemma reversepath_reversepath[simp]: "reversepath (reversepath g) = g" unfolding reversepath_def by auto lemma pathstart_reversepath[simp]: "pathstart (reversepath g) = pathfinish g" unfolding pathstart_def reversepath_def pathfinish_def by auto lemma pathfinish_reversepath[simp]: "pathfinish (reversepath g) = pathstart g" unfolding pathstart_def reversepath_def pathfinish_def by auto lemma reversepath_o: "reversepath g = g \<circ> (-)1" by (auto simp: reversepath_def) lemma pathstart_join[simp]: "pathstart (g1 +++ g2) = pathstart g1" unfolding pathstart_def joinpaths_def pathfinish_def by auto lemma pathfinish_join[simp]: "pathfinish (g1 +++ g2) = pathfinish g2" unfolding pathstart_def joinpaths_def pathfinish_def by auto lemma path_image_reversepath[simp]: "path_image (reversepath g) = path_image g" proof - have *: "\<And>g. path_image (reversepath g) \<subseteq> path_image g" unfolding path_image_def subset_eq reversepath_def Ball_def image_iff by force show ?thesis using *[of g] *[of "reversepath g"] unfolding reversepath_reversepath by auto qed lemma path_reversepath [simp]: "path (reversepath g) \<longleftrightarrow> path g" proof - have *: "\<And>g. path g \<Longrightarrow> path (reversepath g)" by (metis cancel_comm_monoid_add_class.diff_cancel continuous_on_compose continuous_on_op_minus diff_zero image_diff_atLeastAtMost path_def reversepath_o) then show ?thesis by force qed lemma arc_reversepath: assumes "arc g" shows "arc(reversepath g)" proof - have injg: "inj_on g {0..1}" using assms by (simp add: arc_def) have **: "\<And>x y::real. 1-x = 1-y \<Longrightarrow> x = y" by simp show ?thesis using assms by (clarsimp simp: arc_def intro!: inj_onI) (simp add: inj_onD reversepath_def **) qed lemma loop_free_reversepath: assumes "loop_free g" shows "loop_free(reversepath g)" using assms by (simp add: reversepath_def loop_free_def Ball_def) (smt (verit)) lemma simple_path_reversepath: "simple_path g \<Longrightarrow> simple_path (reversepath g)" by (simp add: loop_free_reversepath simple_path_def) lemmas reversepath_simps = path_reversepath path_image_reversepath pathstart_reversepath pathfinish_reversepath lemma path_join[simp]: assumes "pathfinish g1 = pathstart g2" shows "path (g1 +++ g2) \<longleftrightarrow> path g1 \<and> path g2" unfolding path_def pathfinish_def pathstart_def proof safe assume cont: "continuous_on {0..1} (g1 +++ g2)" have g1: "continuous_on {0..1} g1 \<longleftrightarrow> continuous_on {0..1} ((g1 +++ g2) \<circ> (\<lambda>x. x / 2))" by (intro continuous_on_cong refl) (auto simp: joinpaths_def) have g2: "continuous_on {0..1} g2 \<longleftrightarrow> continuous_on {0..1} ((g1 +++ g2) \<circ> (\<lambda>x. x / 2 + 1/2))" using assms by (intro continuous_on_cong refl) (auto simp: joinpaths_def pathfinish_def pathstart_def) show "continuous_on {0..1} g1" and "continuous_on {0..1} g2" unfolding g1 g2 by (auto intro!: continuous_intros continuous_on_subset[OF cont] simp del: o_apply) next assume g1g2: "continuous_on {0..1} g1" "continuous_on {0..1} g2" have 01: "{0 .. 1} = {0..1/2} \<union> {1/2 .. 1::real}" by auto { fix x :: real assume "0 \<le> x" and "x \<le> 1" then have "x \<in> (\<lambda>x. x * 2) ` {0..1 / 2}" by (intro image_eqI[where x="x/2"]) auto } note 1 = this { fix x :: real assume "0 \<le> x" and "x \<le> 1" then have "x \<in> (\<lambda>x. x * 2 - 1) ` {1 / 2..1}" by (intro image_eqI[where x="x/2 + 1/2"]) auto } note 2 = this show "continuous_on {0..1} (g1 +++ g2)" using assms unfolding joinpaths_def 01 apply (intro continuous_on_cases closed_atLeastAtMost g1g2[THEN continuous_on_compose2] continuous_intros) apply (auto simp: field_simps pathfinish_def pathstart_def intro!: 1 2) done qed subsection\<^marker>\<open>tag unimportant\<close> \<open>Path Images\<close> lemma bounded_path_image: "path g \<Longrightarrow> bounded(path_image g)" by (simp add: compact_imp_bounded compact_path_image) lemma closed_path_image: fixes g :: "real \<Rightarrow> 'a::t2_space" shows "path g \<Longrightarrow> closed(path_image g)" by (metis compact_path_image compact_imp_closed) lemma connected_simple_path_image: "simple_path g \<Longrightarrow> connected(path_image g)" by (metis connected_path_image simple_path_imp_path) lemma compact_simple_path_image: "simple_path g \<Longrightarrow> compact(path_image g)" by (metis compact_path_image simple_path_imp_path) lemma bounded_simple_path_image: "simple_path g \<Longrightarrow> bounded(path_image g)" by (metis bounded_path_image simple_path_imp_path) lemma closed_simple_path_image: fixes g :: "real \<Rightarrow> 'a::t2_space" shows "simple_path g \<Longrightarrow> closed(path_image g)" by (metis closed_path_image simple_path_imp_path) lemma connected_arc_image: "arc g \<Longrightarrow> connected(path_image g)" by (metis connected_path_image arc_imp_path) lemma compact_arc_image: "arc g \<Longrightarrow> compact(path_image g)" by (metis compact_path_image arc_imp_path) lemma bounded_arc_image: "arc g \<Longrightarrow> bounded(path_image g)" by (metis bounded_path_image arc_imp_path) lemma closed_arc_image: fixes g :: "real \<Rightarrow> 'a::t2_space" shows "arc g \<Longrightarrow> closed(path_image g)" by (metis closed_path_image arc_imp_path) lemma path_image_join_subset: "path_image (g1 +++ g2) \<subseteq> path_image g1 \<union> path_image g2" unfolding path_image_def joinpaths_def by auto lemma subset_path_image_join: assumes "path_image g1 \<subseteq> s" and "path_image g2 \<subseteq> s" shows "path_image (g1 +++ g2) \<subseteq> s" using path_image_join_subset[of g1 g2] and assms by auto lemma path_image_join: assumes "pathfinish g1 = pathstart g2" shows "path_image(g1 +++ g2) = path_image g1 \<union> path_image g2" proof - have "path_image g1 \<subseteq> path_image (g1 +++ g2)" proof (clarsimp simp: path_image_def joinpaths_def) fix u::real assume "0 \<le> u" "u \<le> 1" then show "g1 u \<in> (\<lambda>x. g1 (2 * x)) ` ({0..1} \<inter> {x. x * 2 \<le> 1})" by (rule_tac x="u/2" in image_eqI) auto qed moreover have \<section>: "g2 u \<in> (\<lambda>x. g2 (2 * x - 1)) ` ({0..1} \<inter> {x. \<not> x * 2 \<le> 1})" if "0 < u" "u \<le> 1" for u using that assms by (rule_tac x="(u+1)/2" in image_eqI) (auto simp: field_simps pathfinish_def pathstart_def) have "g2 0 \<in> (\<lambda>x. g1 (2 * x)) ` ({0..1} \<inter> {x. x * 2 \<le> 1})" using assms by (rule_tac x="1/2" in image_eqI) (auto simp: pathfinish_def pathstart_def) then have "path_image g2 \<subseteq> path_image (g1 +++ g2)" by (auto simp: path_image_def joinpaths_def intro!: \<section>) ultimately show ?thesis using path_image_join_subset by blast qed lemma not_in_path_image_join: assumes "x \<notin> path_image g1" and "x \<notin> path_image g2" shows "x \<notin> path_image (g1 +++ g2)" using assms and path_image_join_subset[of g1 g2] by auto lemma pathstart_compose: "pathstart(f \<circ> p) = f(pathstart p)" by (simp add: pathstart_def) lemma pathfinish_compose: "pathfinish(f \<circ> p) = f(pathfinish p)" by (simp add: pathfinish_def) lemma path_image_compose: "path_image (f \<circ> p) = f ` (path_image p)" by (simp add: image_comp path_image_def) lemma path_compose_join: "f \<circ> (p +++ q) = (f \<circ> p) +++ (f \<circ> q)" by (rule ext) (simp add: joinpaths_def) lemma path_compose_reversepath: "f \<circ> reversepath p = reversepath(f \<circ> p)" by (rule ext) (simp add: reversepath_def) lemma joinpaths_eq: "(\<And>t. t \<in> {0..1} \<Longrightarrow> p t = p' t) \<Longrightarrow> (\<And>t. t \<in> {0..1} \<Longrightarrow> q t = q' t) \<Longrightarrow> t \<in> {0..1} \<Longrightarrow> (p +++ q) t = (p' +++ q') t" by (auto simp: joinpaths_def) lemma loop_free_inj_on: "loop_free g \<Longrightarrow> inj_on g {0<..<1}" by (force simp: inj_on_def loop_free_def) lemma simple_path_inj_on: "simple_path g \<Longrightarrow> inj_on g {0<..<1}" using loop_free_inj_on simple_path_def by auto subsection\<^marker>\<open>tag unimportant\<close>\<open>Simple paths with the endpoints removed\<close> lemma simple_path_endless: assumes "simple_path c" shows "path_image c - {pathstart c,pathfinish c} = c ` {0<..<1}" (is "?lhs = ?rhs") proof show "?lhs \<subseteq> ?rhs" using less_eq_real_def by (auto simp: path_image_def pathstart_def pathfinish_def) show "?rhs \<subseteq> ?lhs" using assms apply (simp add: image_subset_iff path_image_def pathstart_def pathfinish_def simple_path_def loop_free_def Ball_def) by (smt (verit)) qed lemma connected_simple_path_endless: assumes "simple_path c" shows "connected(path_image c - {pathstart c,pathfinish c})" proof - have "continuous_on {0<..<1} c" using assms by (simp add: simple_path_def continuous_on_path path_def subset_iff) then have "connected (c ` {0<..<1})" using connected_Ioo connected_continuous_image by blast then show ?thesis using assms by (simp add: simple_path_endless) qed lemma nonempty_simple_path_endless: "simple_path c \<Longrightarrow> path_image c - {pathstart c,pathfinish c} \<noteq> {}" by (simp add: simple_path_endless) subsection\<^marker>\<open>tag unimportant\<close>\<open>The operations on paths\<close> lemma path_image_subset_reversepath: "path_image(reversepath g) \<le> path_image g" by simp lemma path_imp_reversepath: "path g \<Longrightarrow> path(reversepath g)" by simp lemma half_bounded_equal: "1 \<le> x * 2 \<Longrightarrow> x * 2 \<le> 1 \<longleftrightarrow> x = (1/2::real)" by simp lemma continuous_on_joinpaths: assumes "continuous_on {0..1} g1" "continuous_on {0..1} g2" "pathfinish g1 = pathstart g2" shows "continuous_on {0..1} (g1 +++ g2)" using assms path_def path_join by blast lemma path_join_imp: "\<lbrakk>path g1; path g2; pathfinish g1 = pathstart g2\<rbrakk> \<Longrightarrow> path(g1 +++ g2)" by simp lemma arc_join: assumes "arc g1" "arc g2" "pathfinish g1 = pathstart g2" "path_image g1 \<inter> path_image g2 \<subseteq> {pathstart g2}" shows "arc(g1 +++ g2)" proof - have injg1: "inj_on g1 {0..1}" using assms by (simp add: arc_def) have injg2: "inj_on g2 {0..1}" using assms by (simp add: arc_def) have g11: "g1 1 = g2 0" and sb: "g1 ` {0..1} \<inter> g2 ` {0..1} \<subseteq> {g2 0}" using assms by (simp_all add: arc_def pathfinish_def pathstart_def path_image_def) { fix x and y::real assume xy: "g2 (2 * x - 1) = g1 (2 * y)" "x \<le> 1" "0 \<le> y" " y * 2 \<le> 1" "\<not> x * 2 \<le> 1" then have "g1 (2 * y) = g2 0" using sb by force then have False using xy inj_onD injg2 by fastforce } note * = this have "inj_on (g1 +++ g2) {0..1}" using inj_onD [OF injg1] inj_onD [OF injg2] * by (simp add: inj_on_def joinpaths_def Ball_def) (smt (verit)) then show ?thesis using arc_def assms path_join_imp by blast qed lemma simple_path_join_loop: assumes "arc g1" "arc g2" "pathfinish g1 = pathstart g2" "pathfinish g2 = pathstart g1" "path_image g1 \<inter> path_image g2 \<subseteq> {pathstart g1, pathstart g2}" shows "simple_path(g1 +++ g2)" proof - have injg1: "inj_on g1 {0..1}" and injg2: "inj_on g2 {0..1}" using assms by (auto simp add: arc_def) have g12: "g1 1 = g2 0" and g21: "g2 1 = g1 0" and sb: "g1 ` {0..1} \<inter> g2 ` {0..1} \<subseteq> {g1 0, g2 0}" using assms by (simp_all add: arc_def pathfinish_def pathstart_def path_image_def) { fix x and y::real assume g2_eq: "g2 (2 * x - 1) = g1 (2 * y)" and xyI: "x \<noteq> 1 \<or> y \<noteq> 0" and xy: "x \<le> 1" "0 \<le> y" " y * 2 \<le> 1" "\<not> x * 2 \<le> 1" then consider "g1 (2 * y) = g1 0" | "g1 (2 * y) = g2 0" using sb by force then have False proof cases case 1 then have "y = 0" using xy g2_eq by (auto dest!: inj_onD [OF injg1]) then show ?thesis using xy g2_eq xyI by (auto dest: inj_onD [OF injg2] simp flip: g21) next case 2 then have "2*x = 1" using g2_eq g12 inj_onD [OF injg2] atLeastAtMost_iff xy(1) xy(4) by fastforce with xy show False by auto qed } note * = this have "loop_free(g1 +++ g2)" using inj_onD [OF injg1] inj_onD [OF injg2] * by (simp add: loop_free_def joinpaths_def Ball_def) (smt (verit)) then show ?thesis by (simp add: arc_imp_path assms simple_path_def) qed lemma reversepath_joinpaths: "pathfinish g1 = pathstart g2 \<Longrightarrow> reversepath(g1 +++ g2) = reversepath g2 +++ reversepath g1" unfolding reversepath_def pathfinish_def pathstart_def joinpaths_def by (rule ext) (auto simp: mult.commute) subsection\<^marker>\<open>tag unimportant\<close>\<open>Some reversed and "if and only if" versions of joining theorems\<close> lemma path_join_path_ends: fixes g1 :: "real \<Rightarrow> 'a::metric_space" assumes "path(g1 +++ g2)" "path g2" shows "pathfinish g1 = pathstart g2" proof (rule ccontr) define e where "e = dist (g1 1) (g2 0)" assume Neg: "pathfinish g1 \<noteq> pathstart g2" then have "0 < dist (pathfinish g1) (pathstart g2)" by auto then have "e > 0" by (metis e_def pathfinish_def pathstart_def) then have "\<forall>e>0. \<exists>d>0. \<forall>x'\<in>{0..1}. dist x' 0 < d \<longrightarrow> dist (g2 x') (g2 0) < e" using \<open>path g2\<close> atLeastAtMost_iff zero_le_one unfolding path_def continuous_on_iff by blast then obtain d1 where "d1 > 0" and d1: "\<And>x'. \<lbrakk>x'\<in>{0..1}; norm x' < d1\<rbrakk> \<Longrightarrow> dist (g2 x') (g2 0) < e/2" by (metis \<open>0 < e\<close> half_gt_zero_iff norm_conv_dist) obtain d2 where "d2 > 0" and d2: "\<And>x'. \<lbrakk>x'\<in>{0..1}; dist x' (1/2) < d2\<rbrakk> \<Longrightarrow> dist ((g1 +++ g2) x') (g1 1) < e/2" using assms(1) \<open>e > 0\<close> unfolding path_def continuous_on_iff apply (drule_tac x="1/2" in bspec, simp) apply (drule_tac x="e/2" in spec, force simp: joinpaths_def) done have int01_1: "min (1/2) (min d1 d2) / 2 \<in> {0..1}" using \<open>d1 > 0\<close> \<open>d2 > 0\<close> by (simp add: min_def) have dist1: "norm (min (1 / 2) (min d1 d2) / 2) < d1" using \<open>d1 > 0\<close> \<open>d2 > 0\<close> by (simp add: min_def dist_norm) have int01_2: "1/2 + min (1/2) (min d1 d2) / 4 \<in> {0..1}" using \<open>d1 > 0\<close> \<open>d2 > 0\<close> by (simp add: min_def) have dist2: "dist (1 / 2 + min (1 / 2) (min d1 d2) / 4) (1 / 2) < d2" using \<open>d1 > 0\<close> \<open>d2 > 0\<close> by (simp add: min_def dist_norm) have [simp]: "\<not> min (1 / 2) (min d1 d2) \<le> 0" using \<open>d1 > 0\<close> \<open>d2 > 0\<close> by (simp add: min_def) have "dist (g2 (min (1 / 2) (min d1 d2) / 2)) (g1 1) < e/2" "dist (g2 (min (1 / 2) (min d1 d2) / 2)) (g2 0) < e/2" using d1 [OF int01_1 dist1] d2 [OF int01_2 dist2] by (simp_all add: joinpaths_def) then have "dist (g1 1) (g2 0) < e/2 + e/2" using dist_triangle_half_r e_def by blast then show False by (simp add: e_def [symmetric]) qed lemma path_join_eq [simp]: fixes g1 :: "real \<Rightarrow> 'a::metric_space" assumes "path g1" "path g2" shows "path(g1 +++ g2) \<longleftrightarrow> pathfinish g1 = pathstart g2" using assms by (metis path_join_path_ends path_join_imp) lemma simple_path_joinE: assumes "simple_path(g1 +++ g2)" and "pathfinish g1 = pathstart g2" obtains "arc g1" "arc g2" "path_image g1 \<inter> path_image g2 \<subseteq> {pathstart g1, pathstart g2}" proof - have *: "\<And>x y. \<lbrakk>0 \<le> x; x \<le> 1; 0 \<le> y; y \<le> 1; (g1 +++ g2) x = (g1 +++ g2) y\<rbrakk> \<Longrightarrow> x = y \<or> x = 0 \<and> y = 1 \<or> x = 1 \<and> y = 0" using assms by (simp add: simple_path_def loop_free_def) have "path g1" using assms path_join simple_path_imp_path by blast moreover have "inj_on g1 {0..1}" proof (clarsimp simp: inj_on_def) fix x y assume "g1 x = g1 y" "0 \<le> x" "x \<le> 1" "0 \<le> y" "y \<le> 1" then show "x = y" using * [of "x/2" "y/2"] by (simp add: joinpaths_def split_ifs) qed ultimately have "arc g1" using assms by (simp add: arc_def) have [simp]: "g2 0 = g1 1" using assms by (metis pathfinish_def pathstart_def) have "path g2" using assms path_join simple_path_imp_path by blast moreover have "inj_on g2 {0..1}" proof (clarsimp simp: inj_on_def) fix x y assume "g2 x = g2 y" "0 \<le> x" "x \<le> 1" "0 \<le> y" "y \<le> 1" then show "x = y" using * [of "(x+1) / 2" "(y+1) / 2"] by (force simp: joinpaths_def split_ifs field_split_simps) qed ultimately have "arc g2" using assms by (simp add: arc_def) have "g2 y = g1 0 \<or> g2 y = g1 1" if "g1 x = g2 y" "0 \<le> x" "x \<le> 1" "0 \<le> y" "y \<le> 1" for x y using * [of "x / 2" "(y + 1) / 2"] that by (auto simp: joinpaths_def split_ifs field_split_simps) then have "path_image g1 \<inter> path_image g2 \<subseteq> {pathstart g1, pathstart g2}" by (fastforce simp: pathstart_def pathfinish_def path_image_def) with \<open>arc g1\<close> \<open>arc g2\<close> show ?thesis using that by blast qed lemma simple_path_join_loop_eq: assumes "pathfinish g2 = pathstart g1" "pathfinish g1 = pathstart g2" shows "simple_path(g1 +++ g2) \<longleftrightarrow> arc g1 \<and> arc g2 \<and> path_image g1 \<inter> path_image g2 \<subseteq> {pathstart g1, pathstart g2}" by (metis assms simple_path_joinE simple_path_join_loop) lemma arc_join_eq: assumes "pathfinish g1 = pathstart g2" shows "arc(g1 +++ g2) \<longleftrightarrow> arc g1 \<and> arc g2 \<and> path_image g1 \<inter> path_image g2 \<subseteq> {pathstart g2}" (is "?lhs = ?rhs") proof assume ?lhs then show ?rhs using reversepath_simps assms by (smt (verit, ccfv_threshold) Int_commute arc_distinct_ends arc_imp_simple_path arc_reversepath in_mono insertE pathfinish_join reversepath_joinpaths simple_path_joinE subsetI) next assume ?rhs then show ?lhs using assms by (fastforce simp: pathfinish_def pathstart_def intro!: arc_join) qed lemma arc_join_eq_alt: "pathfinish g1 = pathstart g2 \<Longrightarrow> (arc(g1 +++ g2) \<longleftrightarrow> arc g1 \<and> arc g2 \<and> path_image g1 \<inter> path_image g2 = {pathstart g2})" using pathfinish_in_path_image by (fastforce simp: arc_join_eq) subsection\<^marker>\<open>tag unimportant\<close>\<open>The joining of paths is associative\<close> lemma path_assoc: "\<lbrakk>pathfinish p = pathstart q; pathfinish q = pathstart r\<rbrakk> \<Longrightarrow> path(p +++ (q +++ r)) \<longleftrightarrow> path((p +++ q) +++ r)" by simp lemma simple_path_assoc: assumes "pathfinish p = pathstart q" "pathfinish q = pathstart r" shows "simple_path (p +++ (q +++ r)) \<longleftrightarrow> simple_path ((p +++ q) +++ r)" proof (cases "pathstart p = pathfinish r") case True show ?thesis proof assume "simple_path (p +++ q +++ r)" with assms True show "simple_path ((p +++ q) +++ r)" by (fastforce simp add: simple_path_join_loop_eq arc_join_eq path_image_join dest: arc_distinct_ends [of r]) next assume 0: "simple_path ((p +++ q) +++ r)" with assms True have q: "pathfinish r \<notin> path_image q" using arc_distinct_ends by (fastforce simp add: simple_path_join_loop_eq arc_join_eq path_image_join) have "pathstart r \<notin> path_image p" using assms by (metis 0 IntI arc_distinct_ends arc_join_eq_alt empty_iff insert_iff pathfinish_in_path_image pathfinish_join simple_path_joinE) with assms 0 q True show "simple_path (p +++ q +++ r)" by (auto simp: simple_path_join_loop_eq arc_join_eq path_image_join dest!: subsetD [OF _ IntI]) qed next case False { fix x :: 'a assume a: "path_image p \<inter> path_image q \<subseteq> {pathstart q}" "(path_image p \<union> path_image q) \<inter> path_image r \<subseteq> {pathstart r}" "x \<in> path_image p" "x \<in> path_image r" have "pathstart r \<in> path_image q" by (metis assms(2) pathfinish_in_path_image) with a have "x = pathstart q" by blast } with False assms show ?thesis by (auto simp: simple_path_eq_arc simple_path_join_loop_eq arc_join_eq path_image_join) qed lemma arc_assoc: "\<lbrakk>pathfinish p = pathstart q; pathfinish q = pathstart r\<rbrakk> \<Longrightarrow> arc(p +++ (q +++ r)) \<longleftrightarrow> arc((p +++ q) +++ r)" by (simp add: arc_simple_path simple_path_assoc) subsubsection\<^marker>\<open>tag unimportant\<close>\<open>Symmetry and loops\<close> lemma path_sym: "\<lbrakk>pathfinish p = pathstart q; pathfinish q = pathstart p\<rbrakk> \<Longrightarrow> path(p +++ q) \<longleftrightarrow> path(q +++ p)" by auto lemma simple_path_sym: "\<lbrakk>pathfinish p = pathstart q; pathfinish q = pathstart p\<rbrakk> \<Longrightarrow> simple_path(p +++ q) \<longleftrightarrow> simple_path(q +++ p)" by (metis (full_types) inf_commute insert_commute simple_path_joinE simple_path_join_loop) lemma path_image_sym: "\<lbrakk>pathfinish p = pathstart q; pathfinish q = pathstart p\<rbrakk> \<Longrightarrow> path_image(p +++ q) = path_image(q +++ p)" by (simp add: path_image_join sup_commute) subsection\<open>Subpath\<close> definition\<^marker>\<open>tag important\<close> subpath :: "real \<Rightarrow> real \<Rightarrow> (real \<Rightarrow> 'a) \<Rightarrow> real \<Rightarrow> 'a::real_normed_vector" where "subpath a b g \<equiv> \<lambda>x. g((b - a) * x + a)" lemma path_image_subpath_gen: fixes g :: "_ \<Rightarrow> 'a::real_normed_vector" shows "path_image(subpath u v g) = g ` (closed_segment u v)" by (auto simp add: closed_segment_real_eq path_image_def subpath_def) lemma path_image_subpath: fixes g :: "real \<Rightarrow> 'a::real_normed_vector" shows "path_image(subpath u v g) = (if u \<le> v then g ` {u..v} else g ` {v..u})" by (simp add: path_image_subpath_gen closed_segment_eq_real_ivl) lemma path_image_subpath_commute: fixes g :: "real \<Rightarrow> 'a::real_normed_vector" shows "path_image(subpath u v g) = path_image(subpath v u g)" by (simp add: path_image_subpath_gen closed_segment_eq_real_ivl) lemma path_subpath [simp]: fixes g :: "real \<Rightarrow> 'a::real_normed_vector" assumes "path g" "u \<in> {0..1}" "v \<in> {0..1}" shows "path(subpath u v g)" proof - have "continuous_on {u..v} g" "continuous_on {v..u} g" using assms continuous_on_path by fastforce+ then have "continuous_on {0..1} (g \<circ> (\<lambda>x. ((v-u) * x+ u)))" by (intro continuous_intros; simp add: image_affinity_atLeastAtMost [where c=u]) then show ?thesis by (simp add: path_def subpath_def) qed lemma pathstart_subpath [simp]: "pathstart(subpath u v g) = g(u)" by (simp add: pathstart_def subpath_def) lemma pathfinish_subpath [simp]: "pathfinish(subpath u v g) = g(v)" by (simp add: pathfinish_def subpath_def) lemma subpath_trivial [simp]: "subpath 0 1 g = g" by (simp add: subpath_def) lemma subpath_reversepath: "subpath 1 0 g = reversepath g" by (simp add: reversepath_def subpath_def) lemma reversepath_subpath: "reversepath(subpath u v g) = subpath v u g" by (simp add: reversepath_def subpath_def algebra_simps) lemma subpath_translation: "subpath u v ((\<lambda>x. a + x) \<circ> g) = (\<lambda>x. a + x) \<circ> subpath u v g" by (rule ext) (simp add: subpath_def) lemma subpath_image: "subpath u v (f \<circ> g) = f \<circ> subpath u v g" by (rule ext) (simp add: subpath_def) lemma affine_ineq: fixes x :: "'a::linordered_idom" assumes "x \<le> 1" "v \<le> u" shows "v + x * u \<le> u + x * v" proof - have "(1-x)*(u-v) \<ge> 0" using assms by auto then show ?thesis by (simp add: algebra_simps) qed lemma sum_le_prod1: fixes a::real shows "\<lbrakk>a \<le> 1; b \<le> 1\<rbrakk> \<Longrightarrow> a + b \<le> 1 + a * b" by (metis add.commute affine_ineq mult.right_neutral) lemma simple_path_subpath_eq: "simple_path(subpath u v g) \<longleftrightarrow> path(subpath u v g) \<and> u\<noteq>v \<and> (\<forall>x y. x \<in> closed_segment u v \<and> y \<in> closed_segment u v \<and> g x = g y \<longrightarrow> x = y \<or> x = u \<and> y = v \<or> x = v \<and> y = u)" (is "?lhs = ?rhs") proof assume ?lhs then have p: "path (\<lambda>x. g ((v - u) * x + u))" and sim: "(\<And>x y. \<lbrakk>x\<in>{0..1}; y\<in>{0..1}; g ((v - u) * x + u) = g ((v - u) * y + u)\<rbrakk> \<Longrightarrow> x = y \<or> x = 0 \<and> y = 1 \<or> x = 1 \<and> y = 0)" by (auto simp: simple_path_def loop_free_def subpath_def) { fix x y assume "x \<in> closed_segment u v" "y \<in> closed_segment u v" "g x = g y" then have "x = y \<or> x = u \<and> y = v \<or> x = v \<and> y = u" using sim [of "(x-u)/(v-u)" "(y-u)/(v-u)"] p by (auto split: if_split_asm simp add: closed_segment_real_eq image_affinity_atLeastAtMost) (simp_all add: field_split_simps) } moreover have "path(subpath u v g) \<and> u\<noteq>v" using sim [of "1/3" "2/3"] p by (auto simp: subpath_def) ultimately show ?rhs by metis next assume ?rhs then have d1: "\<And>x y. \<lbrakk>g x = g y; u \<le> x; x \<le> v; u \<le> y; y \<le> v\<rbrakk> \<Longrightarrow> x = y \<or> x = u \<and> y = v \<or> x = v \<and> y = u" and d2: "\<And>x y. \<lbrakk>g x = g y; v \<le> x; x \<le> u; v \<le> y; y \<le> u\<rbrakk> \<Longrightarrow> x = y \<or> x = u \<and> y = v \<or> x = v \<and> y = u" and ne: "u < v \<or> v < u" and psp: "path (subpath u v g)" by (auto simp: closed_segment_real_eq image_affinity_atLeastAtMost) have [simp]: "\<And>x. u + x * v = v + x * u \<longleftrightarrow> u=v \<or> x=1" by algebra show ?lhs using psp ne unfolding simple_path_def loop_free_def subpath_def by (fastforce simp add: algebra_simps affine_ineq mult_left_mono crossproduct_eq dest: d1 d2) qed lemma arc_subpath_eq: "arc(subpath u v g) \<longleftrightarrow> path(subpath u v g) \<and> u\<noteq>v \<and> inj_on g (closed_segment u v)" by (smt (verit, best) arc_simple_path closed_segment_commute ends_in_segment(2) inj_on_def pathfinish_subpath pathstart_subpath simple_path_subpath_eq) lemma simple_path_subpath: assumes "simple_path g" "u \<in> {0..1}" "v \<in> {0..1}" "u \<noteq> v" shows "simple_path(subpath u v g)" using assms apply (simp add: simple_path_subpath_eq simple_path_imp_path) apply (simp add: simple_path_def loop_free_def closed_segment_real_eq image_affinity_atLeastAtMost, fastforce) done lemma arc_simple_path_subpath: "\<lbrakk>simple_path g; u \<in> {0..1}; v \<in> {0..1}; g u \<noteq> g v\<rbrakk> \<Longrightarrow> arc(subpath u v g)" by (force intro: simple_path_subpath simple_path_imp_arc) lemma arc_subpath_arc: "\<lbrakk>arc g; u \<in> {0..1}; v \<in> {0..1}; u \<noteq> v\<rbrakk> \<Longrightarrow> arc(subpath u v g)" by (meson arc_def arc_imp_simple_path arc_simple_path_subpath inj_onD) lemma arc_simple_path_subpath_interior: "\<lbrakk>simple_path g; u \<in> {0..1}; v \<in> {0..1}; u \<noteq> v; \<bar>u-v\<bar> < 1\<rbrakk> \<Longrightarrow> arc(subpath u v g)" by (force simp: simple_path_def loop_free_def intro: arc_simple_path_subpath) lemma path_image_subpath_subset: "\<lbrakk>u \<in> {0..1}; v \<in> {0..1}\<rbrakk> \<Longrightarrow> path_image(subpath u v g) \<subseteq> path_image g" by (metis atLeastAtMost_iff atLeastatMost_subset_iff path_image_def path_image_subpath subset_image_iff) lemma join_subpaths_middle: "subpath (0) ((1 / 2)) p +++ subpath ((1 / 2)) 1 p = p" by (rule ext) (simp add: joinpaths_def subpath_def field_split_simps) subsection\<^marker>\<open>tag unimportant\<close>\<open>There is a subpath to the frontier\<close> lemma subpath_to_frontier_explicit: fixes S :: "'a::metric_space set" assumes g: "path g" and "pathfinish g \<notin> S" obtains u where "0 \<le> u" "u \<le> 1" "\<And>x. 0 \<le> x \<and> x < u \<Longrightarrow> g x \<in> interior S" "(g u \<notin> interior S)" "(u = 0 \<or> g u \<in> closure S)" proof - have gcon: "continuous_on {0..1} g" using g by (simp add: path_def) moreover have "bounded ({u. g u \<in> closure (- S)} \<inter> {0..1})" using compact_eq_bounded_closed by fastforce ultimately have com: "compact ({0..1} \<inter> {u. g u \<in> closure (- S)})" using closed_vimage_Int by (metis (full_types) Int_commute closed_atLeastAtMost closed_closure compact_eq_bounded_closed vimage_def) have "1 \<in> {u. g u \<in> closure (- S)}" using assms by (simp add: pathfinish_def closure_def) then have dis: "{0..1} \<inter> {u. g u \<in> closure (- S)} \<noteq> {}" using atLeastAtMost_iff zero_le_one by blast then obtain u where "0 \<le> u" "u \<le> 1" and gu: "g u \<in> closure (- S)" and umin: "\<And>t. \<lbrakk>0 \<le> t; t \<le> 1; g t \<in> closure (- S)\<rbrakk> \<Longrightarrow> u \<le> t" using compact_attains_inf [OF com dis] by fastforce then have umin': "\<And>t. \<lbrakk>0 \<le> t; t \<le> 1; t < u\<rbrakk> \<Longrightarrow> g t \<in> S" using closure_def by fastforce have \<section>: "g u \<in> closure S" if "u \<noteq> 0" proof - have "u > 0" using that \<open>0 \<le> u\<close> by auto { fix e::real assume "e > 0" obtain d where "d>0" and d: "\<And>x'. \<lbrakk>x' \<in> {0..1}; dist x' u \<le> d\<rbrakk> \<Longrightarrow> dist (g x') (g u) < e" using continuous_onE [OF gcon _ \<open>e > 0\<close>] \<open>0 \<le> _\<close> \<open>_ \<le> 1\<close> atLeastAtMost_iff by auto have *: "dist (max 0 (u - d / 2)) u \<le> d" using \<open>0 \<le> u\<close> \<open>u \<le> 1\<close> \<open>d > 0\<close> by (simp add: dist_real_def) have "\<exists>y\<in>S. dist y (g u) < e" using \<open>0 < u\<close> \<open>u \<le> 1\<close> \<open>d > 0\<close> by (force intro: d [OF _ *] umin') } then show ?thesis by (simp add: frontier_def closure_approachable) qed show ?thesis proof show "\<And>x. 0 \<le> x \<and> x < u \<Longrightarrow> g x \<in> interior S" using \<open>u \<le> 1\<close> interior_closure umin by fastforce show "g u \<notin> interior S" by (simp add: gu interior_closure) qed (use \<open>0 \<le> u\<close> \<open>u \<le> 1\<close> \<section> in auto) qed lemma subpath_to_frontier_strong: assumes g: "path g" and "pathfinish g \<notin> S" obtains u where "0 \<le> u" "u \<le> 1" "g u \<notin> interior S" "u = 0 \<or> (\<forall>x. 0 \<le> x \<and> x < 1 \<longrightarrow> subpath 0 u g x \<in> interior S) \<and> g u \<in> closure S" proof - obtain u where "0 \<le> u" "u \<le> 1" and gxin: "\<And>x. 0 \<le> x \<and> x < u \<Longrightarrow> g x \<in> interior S" and gunot: "(g u \<notin> interior S)" and u0: "(u = 0 \<or> g u \<in> closure S)" using subpath_to_frontier_explicit [OF assms] by blast show ?thesis proof show "g u \<notin> interior S" using gunot by blast qed (use \<open>0 \<le> u\<close> \<open>u \<le> 1\<close> u0 in \<open>(force simp: subpath_def gxin)+\<close>) qed lemma subpath_to_frontier: assumes g: "path g" and g0: "pathstart g \<in> closure S" and g1: "pathfinish g \<notin> S" obtains u where "0 \<le> u" "u \<le> 1" "g u \<in> frontier S" "path_image(subpath 0 u g) - {g u} \<subseteq> interior S" proof - obtain u where "0 \<le> u" "u \<le> 1" and notin: "g u \<notin> interior S" and disj: "u = 0 \<or> (\<forall>x. 0 \<le> x \<and> x < 1 \<longrightarrow> subpath 0 u g x \<in> interior S) \<and> g u \<in> closure S" (is "_ \<or> ?P") using subpath_to_frontier_strong [OF g g1] by blast show ?thesis proof show "g u \<in> frontier S" by (metis DiffI disj frontier_def g0 notin pathstart_def) show "path_image (subpath 0 u g) - {g u} \<subseteq> interior S" using disj proof assume "u = 0" then show ?thesis by (simp add: path_image_subpath) next assume P: ?P show ?thesis proof (clarsimp simp add: path_image_subpath_gen) fix y assume y: "y \<in> closed_segment 0 u" "g y \<notin> interior S" with \<open>0 \<le> u\<close> have "0 \<le> y" "y \<le> u" by (auto simp: closed_segment_eq_real_ivl split: if_split_asm) then have "y=u \<or> subpath 0 u g (y/u) \<in> interior S" using P less_eq_real_def by force then show "g y = g u" using y by (auto simp: subpath_def split: if_split_asm) qed qed qed (use \<open>0 \<le> u\<close> \<open>u \<le> 1\<close> in auto) qed lemma exists_path_subpath_to_frontier: fixes S :: "'a::real_normed_vector set" assumes "path g" "pathstart g \<in> closure S" "pathfinish g \<notin> S" obtains h where "path h" "pathstart h = pathstart g" "path_image h \<subseteq> path_image g" "path_image h - {pathfinish h} \<subseteq> interior S" "pathfinish h \<in> frontier S" proof - obtain u where u: "0 \<le> u" "u \<le> 1" "g u \<in> frontier S" "(path_image(subpath 0 u g) - {g u}) \<subseteq> interior S" using subpath_to_frontier [OF assms] by blast show ?thesis proof show "path_image (subpath 0 u g) \<subseteq> path_image g" by (simp add: path_image_subpath_subset u) show "pathstart (subpath 0 u g) = pathstart g" by (metis pathstart_def pathstart_subpath) qed (use assms u in \<open>auto simp: path_image_subpath\<close>) qed lemma exists_path_subpath_to_frontier_closed: fixes S :: "'a::real_normed_vector set" assumes S: "closed S" and g: "path g" and g0: "pathstart g \<in> S" and g1: "pathfinish g \<notin> S" obtains h where "path h" "pathstart h = pathstart g" "path_image h \<subseteq> path_image g \<inter> S" "pathfinish h \<in> frontier S" by (smt (verit, del_insts) Diff_iff Int_iff S closure_closed exists_path_subpath_to_frontier frontier_def g g0 g1 interior_subset singletonD subset_eq) subsection \<open>Shift Path to Start at Some Given Point\<close> definition\<^marker>\<open>tag important\<close> shiftpath :: "real \<Rightarrow> (real \<Rightarrow> 'a::topological_space) \<Rightarrow> real \<Rightarrow> 'a" where "shiftpath a f = (\<lambda>x. if (a + x) \<le> 1 then f (a + x) else f (a + x - 1))" lemma shiftpath_alt_def: "shiftpath a f = (\<lambda>x. if x \<le> 1-a then f (a + x) else f (a + x - 1))" by (auto simp: shiftpath_def) lemma pathstart_shiftpath: "a \<le> 1 \<Longrightarrow> pathstart (shiftpath a g) = g a" unfolding pathstart_def shiftpath_def by auto lemma pathfinish_shiftpath: assumes "0 \<le> a" and "pathfinish g = pathstart g" shows "pathfinish (shiftpath a g) = g a" using assms unfolding pathstart_def pathfinish_def shiftpath_def by auto lemma endpoints_shiftpath: assumes "pathfinish g = pathstart g" and "a \<in> {0 .. 1}" shows "pathfinish (shiftpath a g) = g a" and "pathstart (shiftpath a g) = g a" using assms by (auto intro!: pathfinish_shiftpath pathstart_shiftpath) lemma closed_shiftpath: assumes "pathfinish g = pathstart g" and "a \<in> {0..1}" shows "pathfinish (shiftpath a g) = pathstart (shiftpath a g)" using endpoints_shiftpath[OF assms] by auto lemma path_shiftpath: assumes "path g" and "pathfinish g = pathstart g" and "a \<in> {0..1}" shows "path (shiftpath a g)" proof - have *: "{0 .. 1} = {0 .. 1-a} \<union> {1-a .. 1}" using assms(3) by auto have **: "\<And>x. x + a = 1 \<Longrightarrow> g (x + a - 1) = g (x + a)" by (smt (verit, best) assms(2) pathfinish_def pathstart_def) show ?thesis unfolding path_def shiftpath_def * proof (rule continuous_on_closed_Un) have contg: "continuous_on {0..1} g" using \<open>path g\<close> path_def by blast show "continuous_on {0..1-a} (\<lambda>x. if a + x \<le> 1 then g (a + x) else g (a + x - 1))" proof (rule continuous_on_eq) show "continuous_on {0..1-a} (g \<circ> (+) a)" by (intro continuous_intros continuous_on_subset [OF contg]) (use \<open>a \<in> {0..1}\<close> in auto) qed auto show "continuous_on {1-a..1} (\<lambda>x. if a + x \<le> 1 then g (a + x) else g (a + x - 1))" proof (rule continuous_on_eq) show "continuous_on {1-a..1} (g \<circ> (+) (a - 1))" by (intro continuous_intros continuous_on_subset [OF contg]) (use \<open>a \<in> {0..1}\<close> in auto) qed (auto simp: "**" add.commute add_diff_eq) qed auto qed lemma shiftpath_shiftpath: assumes "pathfinish g = pathstart g" and "a \<in> {0..1}" and "x \<in> {0..1}" shows "shiftpath (1 - a) (shiftpath a g) x = g x" using assms unfolding pathfinish_def pathstart_def shiftpath_def by auto lemma path_image_shiftpath: assumes a: "a \<in> {0..1}" and "pathfinish g = pathstart g" shows "path_image (shiftpath a g) = path_image g" proof - { fix x assume g: "g 1 = g 0" "x \<in> {0..1::real}" and gne: "\<And>y. y\<in>{0..1} \<inter> {x. \<not> a + x \<le> 1} \<Longrightarrow> g x \<noteq> g (a + y - 1)" then have "\<exists>y\<in>{0..1} \<inter> {x. a + x \<le> 1}. g x = g (a + y)" proof (cases "a \<le> x") case False then show ?thesis apply (rule_tac x="1 + x - a" in bexI) using g gne[of "1 + x - a"] a by (force simp: field_simps)+ next case True then show ?thesis using g a by (rule_tac x="x - a" in bexI) (auto simp: field_simps) qed } then show ?thesis using assms unfolding shiftpath_def path_image_def pathfinish_def pathstart_def by (auto simp: image_iff) qed lemma loop_free_shiftpath: assumes "loop_free g" "pathfinish g = pathstart g" and a: "0 \<le> a" "a \<le> 1" shows "loop_free (shiftpath a g)" unfolding loop_free_def proof (intro conjI impI ballI) show "x = y \<or> x = 0 \<and> y = 1 \<or> x = 1 \<and> y = 0" if "x \<in> {0..1}" "y \<in> {0..1}" "shiftpath a g x = shiftpath a g y" for x y using that a assms unfolding shiftpath_def loop_free_def by (smt (verit, ccfv_threshold) atLeastAtMost_iff) qed lemma simple_path_shiftpath: assumes "simple_path g" "pathfinish g = pathstart g" and a: "0 \<le> a" "a \<le> 1" shows "simple_path (shiftpath a g)" using assms loop_free_shiftpath path_shiftpath simple_path_def by fastforce subsection \<open>Straight-Line Paths\<close> definition\<^marker>\<open>tag important\<close> linepath :: "'a::real_normed_vector \<Rightarrow> 'a \<Rightarrow> real \<Rightarrow> 'a" where "linepath a b = (\<lambda>x. (1 - x) *\<^sub>R a + x *\<^sub>R b)" lemma pathstart_linepath[simp]: "pathstart (linepath a b) = a" unfolding pathstart_def linepath_def by auto lemma pathfinish_linepath[simp]: "pathfinish (linepath a b) = b" unfolding pathfinish_def linepath_def by auto lemma linepath_inner: "linepath a b x \<bullet> v = linepath (a \<bullet> v) (b \<bullet> v) x" by (simp add: linepath_def algebra_simps) lemma Re_linepath': "Re (linepath a b x) = linepath (Re a) (Re b) x" by (simp add: linepath_def) lemma Im_linepath': "Im (linepath a b x) = linepath (Im a) (Im b) x" by (simp add: linepath_def) lemma linepath_0': "linepath a b 0 = a" by (simp add: linepath_def) lemma linepath_1': "linepath a b 1 = b" by (simp add: linepath_def) lemma continuous_linepath_at[intro]: "continuous (at x) (linepath a b)" unfolding linepath_def by (intro continuous_intros) lemma continuous_on_linepath [intro,continuous_intros]: "continuous_on s (linepath a b)" using continuous_linepath_at by (auto intro!: continuous_at_imp_continuous_on) lemma path_linepath[iff]: "path (linepath a b)" unfolding path_def by (rule continuous_on_linepath) lemma path_image_linepath[simp]: "path_image (linepath a b) = closed_segment a b" unfolding path_image_def segment linepath_def by auto lemma reversepath_linepath[simp]: "reversepath (linepath a b) = linepath b a" unfolding reversepath_def linepath_def by auto lemma linepath_0 [simp]: "linepath 0 b x = x *\<^sub>R b" by (simp add: linepath_def) lemma linepath_cnj: "cnj (linepath a b x) = linepath (cnj a) (cnj b) x" by (simp add: linepath_def) lemma arc_linepath: assumes "a \<noteq> b" shows [simp]: "arc (linepath a b)" proof - { fix x y :: "real" assume "x *\<^sub>R b + y *\<^sub>R a = x *\<^sub>R a + y *\<^sub>R b" then have "(x - y) *\<^sub>R a = (x - y) *\<^sub>R b" by (simp add: algebra_simps) with assms have "x = y" by simp } then show ?thesis unfolding arc_def inj_on_def by (fastforce simp: algebra_simps linepath_def) qed lemma simple_path_linepath[intro]: "a \<noteq> b \<Longrightarrow> simple_path (linepath a b)" by (simp add: arc_imp_simple_path) lemma linepath_trivial [simp]: "linepath a a x = a" by (simp add: linepath_def real_vector.scale_left_diff_distrib) lemma linepath_refl: "linepath a a = (\<lambda>x. a)" by auto lemma subpath_refl: "subpath a a g = linepath (g a) (g a)" by (simp add: subpath_def linepath_def algebra_simps) lemma linepath_of_real: "(linepath (of_real a) (of_real b) x) = of_real ((1 - x)*a + x*b)" by (simp add: scaleR_conv_of_real linepath_def) lemma of_real_linepath: "of_real (linepath a b x) = linepath (of_real a) (of_real b) x" by (metis linepath_of_real mult.right_neutral of_real_def real_scaleR_def) lemma inj_on_linepath: assumes "a \<noteq> b" shows "inj_on (linepath a b) {0..1}" using arc_imp_inj_on arc_linepath assms by blast lemma linepath_le_1: fixes a::"'a::linordered_idom" shows "\<lbrakk>a \<le> 1; b \<le> 1; 0 \<le> u; u \<le> 1\<rbrakk> \<Longrightarrow> (1 - u) * a + u * b \<le> 1" using mult_left_le [of a "1-u"] mult_left_le [of b u] by auto lemma linepath_in_path: shows "x \<in> {0..1} \<Longrightarrow> linepath a b x \<in> closed_segment a b" by (auto simp: segment linepath_def) lemma linepath_image_01: "linepath a b ` {0..1} = closed_segment a b" by (auto simp: segment linepath_def) lemma linepath_in_convex_hull: fixes x::real assumes "a \<in> convex hull S" and "b \<in> convex hull S" and "0\<le>x" "x\<le>1" shows "linepath a b x \<in> convex hull S" by (meson assms atLeastAtMost_iff convex_contains_segment convex_convex_hull linepath_in_path subset_eq) lemma Re_linepath: "Re(linepath (of_real a) (of_real b) x) = (1 - x)*a + x*b" by (simp add: linepath_def) lemma Im_linepath: "Im(linepath (of_real a) (of_real b) x) = 0" by (simp add: linepath_def) lemma bounded_linear_linepath: assumes "bounded_linear f" shows "f (linepath a b x) = linepath (f a) (f b) x" proof - interpret f: bounded_linear f by fact show ?thesis by (simp add: linepath_def f.add f.scale) qed lemma bounded_linear_linepath': assumes "bounded_linear f" shows "f \<circ> linepath a b = linepath (f a) (f b)" using bounded_linear_linepath[OF assms] by (simp add: fun_eq_iff) lemma linepath_cnj': "cnj \<circ> linepath a b = linepath (cnj a) (cnj b)" by (simp add: linepath_def fun_eq_iff) lemma differentiable_linepath [intro]: "linepath a b differentiable at x within A" by (auto simp: linepath_def) lemma has_vector_derivative_linepath_within: "(linepath a b has_vector_derivative (b - a)) (at x within S)" by (force intro: derivative_eq_intros simp add: linepath_def has_vector_derivative_def algebra_simps) subsection\<^marker>\<open>tag unimportant\<close>\<open>Segments via convex hulls\<close> lemma segments_subset_convex_hull: "closed_segment a b \<subseteq> (convex hull {a,b,c})" "closed_segment a c \<subseteq> (convex hull {a,b,c})" "closed_segment b c \<subseteq> (convex hull {a,b,c})" "closed_segment b a \<subseteq> (convex hull {a,b,c})" "closed_segment c a \<subseteq> (convex hull {a,b,c})" "closed_segment c b \<subseteq> (convex hull {a,b,c})" by (auto simp: segment_convex_hull linepath_of_real elim!: rev_subsetD [OF _ hull_mono]) lemma midpoints_in_convex_hull: assumes "x \<in> convex hull s" "y \<in> convex hull s" shows "midpoint x y \<in> convex hull s" using assms closed_segment_subset_convex_hull csegment_midpoint_subset by blast lemma not_in_interior_convex_hull_3: fixes a :: "complex" shows "a \<notin> interior(convex hull {a,b,c})" "b \<notin> interior(convex hull {a,b,c})" "c \<notin> interior(convex hull {a,b,c})" by (auto simp: card_insert_le_m1 not_in_interior_convex_hull) lemma midpoint_in_closed_segment [simp]: "midpoint a b \<in> closed_segment a b" using midpoints_in_convex_hull segment_convex_hull by blast lemma midpoint_in_open_segment [simp]: "midpoint a b \<in> open_segment a b \<longleftrightarrow> a \<noteq> b" by (simp add: open_segment_def) lemma continuous_IVT_local_extremum: fixes f :: "'a::euclidean_space \<Rightarrow> real" assumes contf: "continuous_on (closed_segment a b) f" and ab: "a \<noteq> b" "f a = f b" obtains z where "z \<in> open_segment a b" "(\<forall>w \<in> closed_segment a b. (f w) \<le> (f z)) \<or> (\<forall>w \<in> closed_segment a b. (f z) \<le> (f w))" proof - obtain c where "c \<in> closed_segment a b" and c: "\<And>y. y \<in> closed_segment a b \<Longrightarrow> f y \<le> f c" using continuous_attains_sup [of "closed_segment a b" f] contf by auto moreover obtain d where "d \<in> closed_segment a b" and d: "\<And>y. y \<in> closed_segment a b \<Longrightarrow> f d \<le> f y" using continuous_attains_inf [of "closed_segment a b" f] contf by auto ultimately show ?thesis by (smt (verit) UnE ab closed_segment_eq_open empty_iff insert_iff midpoint_in_open_segment that) qed text\<open>An injective map into R is also an open map w.r.T. the universe, and conversely. \<close> proposition injective_eq_1d_open_map_UNIV: fixes f :: "real \<Rightarrow> real" assumes contf: "continuous_on S f" and S: "is_interval S" shows "inj_on f S \<longleftrightarrow> (\<forall>T. open T \<and> T \<subseteq> S \<longrightarrow> open(f ` T))" (is "?lhs = ?rhs") proof safe fix T assume injf: ?lhs and "open T" and "T \<subseteq> S" have "\<exists>U. open U \<and> f x \<in> U \<and> U \<subseteq> f ` T" if "x \<in> T" for x proof - obtain \<delta> where "\<delta> > 0" and \<delta>: "cball x \<delta> \<subseteq> T" using \<open>open T\<close> \<open>x \<in> T\<close> open_contains_cball_eq by blast show ?thesis proof (intro exI conjI) have "closed_segment (x-\<delta>) (x+\<delta>) = {x-\<delta>..x+\<delta>}" using \<open>0 < \<delta>\<close> by (auto simp: closed_segment_eq_real_ivl) also have "\<dots> \<subseteq> S" using \<delta> \<open>T \<subseteq> S\<close> by (auto simp: dist_norm subset_eq) finally have "f ` (open_segment (x-\<delta>) (x+\<delta>)) = open_segment (f (x-\<delta>)) (f (x+\<delta>))" using continuous_injective_image_open_segment_1 by (metis continuous_on_subset [OF contf] inj_on_subset [OF injf]) then show "open (f ` {x-\<delta><..<x+\<delta>})" using \<open>0 < \<delta>\<close> by (simp add: open_segment_eq_real_ivl) show "f x \<in> f ` {x - \<delta><..<x + \<delta>}" by (auto simp: \<open>\<delta> > 0\<close>) show "f ` {x - \<delta><..<x + \<delta>} \<subseteq> f ` T" using \<delta> by (auto simp: dist_norm subset_iff) qed qed with open_subopen show "open (f ` T)" by blast next assume R: ?rhs have False if xy: "x \<in> S" "y \<in> S" and "f x = f y" "x \<noteq> y" for x y proof - have "open (f ` open_segment x y)" using R by (metis S convex_contains_open_segment is_interval_convex open_greaterThanLessThan open_segment_eq_real_ivl xy) moreover have "continuous_on (closed_segment x y) f" by (meson S closed_segment_subset contf continuous_on_subset is_interval_convex that) then obtain \<xi> where "\<xi> \<in> open_segment x y" and \<xi>: "(\<forall>w \<in> closed_segment x y. (f w) \<le> (f \<xi>)) \<or> (\<forall>w \<in> closed_segment x y. (f \<xi>) \<le> (f w))" using continuous_IVT_local_extremum [of x y f] \<open>f x = f y\<close> \<open>x \<noteq> y\<close> by blast ultimately obtain e where "e>0" and e: "\<And>u. dist u (f \<xi>) < e \<Longrightarrow> u \<in> f ` open_segment x y" using open_dist by (metis image_eqI) have fin: "f \<xi> + (e/2) \<in> f ` open_segment x y" "f \<xi> - (e/2) \<in> f ` open_segment x y" using e [of "f \<xi> + (e/2)"] e [of "f \<xi> - (e/2)"] \<open>e > 0\<close> by (auto simp: dist_norm) show ?thesis using \<xi> \<open>0 < e\<close> fin open_closed_segment by fastforce qed then show ?lhs by (force simp: inj_on_def) qed subsection\<^marker>\<open>tag unimportant\<close> \<open>Bounding a point away from a path\<close> lemma not_on_path_ball: fixes g :: "real \<Rightarrow> 'a::heine_borel" assumes "path g" and z: "z \<notin> path_image g" shows "\<exists>e > 0. ball z e \<inter> path_image g = {}" proof - have "closed (path_image g)" by (simp add: \<open>path g\<close> closed_path_image) then obtain a where "a \<in> path_image g" "\<forall>y \<in> path_image g. dist z a \<le> dist z y" by (auto intro: distance_attains_inf[OF _ path_image_nonempty, of g z]) then show ?thesis by (rule_tac x="dist z a" in exI) (use dist_commute z in auto) qed lemma not_on_path_cball: fixes g :: "real \<Rightarrow> 'a::heine_borel" assumes "path g" and "z \<notin> path_image g" shows "\<exists>e>0. cball z e \<inter> (path_image g) = {}" by (smt (verit, ccfv_threshold) open_ball assms centre_in_ball inf.orderE inf_assoc inf_bot_right not_on_path_ball open_contains_cball_eq) subsection \<open>Path component\<close> text \<open>Original formalization by Tom Hales\<close> definition\<^marker>\<open>tag important\<close> "path_component S x y \<equiv> (\<exists>g. path g \<and> path_image g \<subseteq> S \<and> pathstart g = x \<and> pathfinish g = y)" abbreviation\<^marker>\<open>tag important\<close> "path_component_set S x \<equiv> Collect (path_component S x)" lemmas path_defs = path_def pathstart_def pathfinish_def path_image_def path_component_def lemma path_component_mem: assumes "path_component S x y" shows "x \<in> S" and "y \<in> S" using assms unfolding path_defs by auto lemma path_component_refl: assumes "x \<in> S" shows "path_component S x x" using assms unfolding path_defs by (metis (full_types) assms continuous_on_const image_subset_iff path_image_def) lemma path_component_refl_eq: "path_component S x x \<longleftrightarrow> x \<in> S" by (auto intro!: path_component_mem path_component_refl) lemma path_component_sym: "path_component S x y \<Longrightarrow> path_component S y x" unfolding path_component_def by (metis (no_types) path_image_reversepath path_reversepath pathfinish_reversepath pathstart_reversepath) lemma path_component_trans: assumes "path_component S x y" and "path_component S y z" shows "path_component S x z" using assms unfolding path_component_def by (metis path_join pathfinish_join pathstart_join subset_path_image_join) lemma path_component_of_subset: "S \<subseteq> T \<Longrightarrow> path_component S x y \<Longrightarrow> path_component T x y" unfolding path_component_def by auto lemma path_component_linepath: fixes S :: "'a::real_normed_vector set" shows "closed_segment a b \<subseteq> S \<Longrightarrow> path_component S a b" unfolding path_component_def by fastforce subsubsection\<^marker>\<open>tag unimportant\<close> \<open>Path components as sets\<close> lemma path_component_set: "path_component_set S x = {y. (\<exists>g. path g \<and> path_image g \<subseteq> S \<and> pathstart g = x \<and> pathfinish g = y)}" by (auto simp: path_component_def) lemma path_component_subset: "path_component_set S x \<subseteq> S" by (auto simp: path_component_mem(2)) lemma path_component_eq_empty: "path_component_set S x = {} \<longleftrightarrow> x \<notin> S" using path_component_mem path_component_refl_eq by fastforce lemma path_component_mono: "S \<subseteq> T \<Longrightarrow> (path_component_set S x) \<subseteq> (path_component_set T x)" by (simp add: Collect_mono path_component_of_subset) lemma path_component_eq: "y \<in> path_component_set S x \<Longrightarrow> path_component_set S y = path_component_set S x" by (metis (no_types, lifting) Collect_cong mem_Collect_eq path_component_sym path_component_trans) subsection \<open>Path connectedness of a space\<close> definition\<^marker>\<open>tag important\<close> "path_connected S \<longleftrightarrow> (\<forall>x\<in>S. \<forall>y\<in>S. \<exists>g. path g \<and> path_image g \<subseteq> S \<and> pathstart g = x \<and> pathfinish g = y)" lemma path_connectedin_iff_path_connected_real [simp]: "path_connectedin euclideanreal S \<longleftrightarrow> path_connected S" by (simp add: path_connectedin path_connected_def path_defs) lemma path_connected_component: "path_connected S \<longleftrightarrow> (\<forall>x\<in>S. \<forall>y\<in>S. path_component S x y)" unfolding path_connected_def path_component_def by auto lemma path_connected_component_set: "path_connected S \<longleftrightarrow> (\<forall>x\<in>S. path_component_set S x = S)" unfolding path_connected_component path_component_subset using path_component_mem by blast lemma path_component_maximal: "\<lbrakk>x \<in> T; path_connected T; T \<subseteq> S\<rbrakk> \<Longrightarrow> T \<subseteq> (path_component_set S x)" by (metis path_component_mono path_connected_component_set) lemma convex_imp_path_connected: fixes S :: "'a::real_normed_vector set" assumes "convex S" shows "path_connected S" unfolding path_connected_def using assms convex_contains_segment by fastforce lemma path_connected_UNIV [iff]: "path_connected (UNIV :: 'a::real_normed_vector set)" by (simp add: convex_imp_path_connected) lemma path_component_UNIV: "path_component_set UNIV x = (UNIV :: 'a::real_normed_vector set)" using path_connected_component_set by auto lemma path_connected_imp_connected: assumes "path_connected S" shows "connected S" proof (rule connectedI) fix e1 e2 assume as: "open e1" "open e2" "S \<subseteq> e1 \<union> e2" "e1 \<inter> e2 \<inter> S = {}" "e1 \<inter> S \<noteq> {}" "e2 \<inter> S \<noteq> {}" then obtain x1 x2 where obt:"x1 \<in> e1 \<inter> S" "x2 \<in> e2 \<inter> S" by auto then obtain g where g: "path g" "path_image g \<subseteq> S" and pg: "pathstart g = x1" "pathfinish g = x2" using assms[unfolded path_connected_def,rule_format,of x1 x2] by auto have *: "connected {0..1::real}" by (auto intro!: convex_connected) have "{0..1} \<subseteq> {x \<in> {0..1}. g x \<in> e1} \<union> {x \<in> {0..1}. g x \<in> e2}" using as(3) g(2)[unfolded path_defs] by blast moreover have "{x \<in> {0..1}. g x \<in> e1} \<inter> {x \<in> {0..1}. g x \<in> e2} = {}" using as(4) g(2)[unfolded path_defs] unfolding subset_eq by auto moreover have "{x \<in> {0..1}. g x \<in> e1} \<noteq> {} \<and> {x \<in> {0..1}. g x \<in> e2} \<noteq> {}" by (smt (verit, ccfv_threshold) IntE atLeastAtMost_iff empty_iff pg mem_Collect_eq obt pathfinish_def pathstart_def) ultimately show False using *[unfolded connected_local not_ex, rule_format, of "{0..1} \<inter> g -` e1" "{0..1} \<inter> g -` e2"] using continuous_openin_preimage_gen[OF g(1)[unfolded path_def] as(1)] using continuous_openin_preimage_gen[OF g(1)[unfolded path_def] as(2)] by auto qed lemma open_path_component: fixes S :: "'a::real_normed_vector set" assumes "open S" shows "open (path_component_set S x)" unfolding open_contains_ball by (metis assms centre_in_ball convex_ball convex_imp_path_connected equals0D openE path_component_eq path_component_eq_empty path_component_maximal) lemma open_non_path_component: fixes S :: "'a::real_normed_vector set" assumes "open S" shows "open (S - path_component_set S x)" unfolding open_contains_ball proof fix y assume y: "y \<in> S - path_component_set S x" then obtain e where e: "e > 0" "ball y e \<subseteq> S" using assms openE by auto show "\<exists>e>0. ball y e \<subseteq> S - path_component_set S x" proof (intro exI conjI subsetI DiffI notI) show "\<And>x. x \<in> ball y e \<Longrightarrow> x \<in> S" using e by blast show False if "z \<in> ball y e" "z \<in> path_component_set S x" for z by (metis (no_types, lifting) Diff_iff centre_in_ball convex_ball convex_imp_path_connected path_component_eq path_component_maximal subsetD that y e) qed (use e in auto) qed lemma connected_open_path_connected: fixes S :: "'a::real_normed_vector set" assumes "open S" and "connected S" shows "path_connected S" unfolding path_connected_component_set proof (rule, rule, rule path_component_subset, rule) fix x y assume "x \<in> S" and "y \<in> S" show "y \<in> path_component_set S x" proof (rule ccontr) assume "\<not> ?thesis" moreover have "path_component_set S x \<inter> S \<noteq> {}" using \<open>x \<in> S\<close> path_component_eq_empty path_component_subset[of S x] by auto ultimately show False using \<open>y \<in> S\<close> open_non_path_component[OF \<open>open S\<close>] open_path_component[OF \<open>open S\<close>] using \<open>connected S\<close>[unfolded connected_def not_ex, rule_format, of "path_component_set S x" "S - path_component_set S x"] by auto qed qed lemma path_connected_continuous_image: assumes contf: "continuous_on S f" and "path_connected S" shows "path_connected (f ` S)" unfolding path_connected_def proof clarsimp fix x y assume x: "x \<in> S" and y: "y \<in> S" with \<open>path_connected S\<close> show "\<exists>g. path g \<and> path_image g \<subseteq> f ` S \<and> pathstart g = f x \<and> pathfinish g = f y" unfolding path_defs path_connected_def using continuous_on_subset[OF contf] by (smt (verit, ccfv_threshold) continuous_on_compose2 image_eqI image_subset_iff) qed lemma path_connected_translationI: fixes a :: "'a :: topological_group_add" assumes "path_connected S" shows "path_connected ((\<lambda>x. a + x) ` S)" by (intro path_connected_continuous_image assms continuous_intros) lemma path_connected_translation: fixes a :: "'a :: topological_group_add" shows "path_connected ((\<lambda>x. a + x) ` S) = path_connected S" proof - have "\<forall>x y. (+) (x::'a) ` (+) (0 - x) ` y = y" by (simp add: image_image) then show ?thesis by (metis (no_types) path_connected_translationI) qed lemma path_connected_segment [simp]: fixes a :: "'a::real_normed_vector" shows "path_connected (closed_segment a b)" by (simp add: convex_imp_path_connected) lemma path_connected_open_segment [simp]: fixes a :: "'a::real_normed_vector" shows "path_connected (open_segment a b)" by (simp add: convex_imp_path_connected) lemma homeomorphic_path_connectedness: "S homeomorphic T \<Longrightarrow> path_connected S \<longleftrightarrow> path_connected T" unfolding homeomorphic_def homeomorphism_def by (metis path_connected_continuous_image) lemma path_connected_empty [simp]: "path_connected {}" unfolding path_connected_def by auto lemma path_connected_singleton [simp]: "path_connected {a}" unfolding path_connected_def pathstart_def pathfinish_def path_image_def using path_def by fastforce lemma path_connected_Un: assumes "path_connected S" and "path_connected T" and "S \<inter> T \<noteq> {}" shows "path_connected (S \<union> T)" unfolding path_connected_component proof (intro ballI) fix x y assume x: "x \<in> S \<union> T" and y: "y \<in> S \<union> T" from assms obtain z where z: "z \<in> S" "z \<in> T" by auto with x y show "path_component (S \<union> T) x y" by (smt (verit) assms(1,2) in_mono mem_Collect_eq path_component_eq path_component_maximal sup.bounded_iff sup.cobounded2 sup_ge1) qed lemma path_connected_UNION: assumes "\<And>i. i \<in> A \<Longrightarrow> path_connected (S i)" and "\<And>i. i \<in> A \<Longrightarrow> z \<in> S i" shows "path_connected (\<Union>i\<in>A. S i)" unfolding path_connected_component proof clarify fix x i y j assume *: "i \<in> A" "x \<in> S i" "j \<in> A" "y \<in> S j" then have "path_component (S i) x z" and "path_component (S j) z y" using assms by (simp_all add: path_connected_component) then have "path_component (\<Union>i\<in>A. S i) x z" and "path_component (\<Union>i\<in>A. S i) z y" using *(1,3) by (meson SUP_upper path_component_of_subset)+ then show "path_component (\<Union>i\<in>A. S i) x y" by (rule path_component_trans) qed lemma path_component_path_image_pathstart: assumes p: "path p" and x: "x \<in> path_image p" shows "path_component (path_image p) (pathstart p) x" proof - obtain y where x: "x = p y" and y: "0 \<le> y" "y \<le> 1" using x by (auto simp: path_image_def) show ?thesis unfolding path_component_def proof (intro exI conjI) have "continuous_on ((*) y ` {0..1}) p" by (simp add: continuous_on_path image_mult_atLeastAtMost_if p y) then have "continuous_on {0..1} (p \<circ> ((*) y))" using continuous_on_compose continuous_on_mult_const by blast then show "path (\<lambda>u. p (y * u))" by (simp add: path_def) show "path_image (\<lambda>u. p (y * u)) \<subseteq> path_image p" using y mult_le_one by (fastforce simp: path_image_def image_iff) qed (auto simp: pathstart_def pathfinish_def x) qed lemma path_connected_path_image: "path p \<Longrightarrow> path_connected(path_image p)" unfolding path_connected_component by (meson path_component_path_image_pathstart path_component_sym path_component_trans) lemma path_connected_path_component [simp]: "path_connected (path_component_set S x)" proof (clarsimp simp: path_connected_def) fix y z assume pa: "path_component S x y" "path_component S x z" then have pae: "path_component_set S x = path_component_set S y" using path_component_eq by auto obtain g where g: "path g \<and> path_image g \<subseteq> S \<and> pathstart g = y \<and> pathfinish g = z" using pa path_component_sym path_component_trans path_component_def by metis then have "path_image g \<subseteq> path_component_set S x" using pae path_component_maximal path_connected_path_image by blast then show "\<exists>g. path g \<and> path_image g \<subseteq> path_component_set S x \<and> pathstart g = y \<and> pathfinish g = z" using g by blast qed lemma path_component: "path_component S x y \<longleftrightarrow> (\<exists>t. path_connected t \<and> t \<subseteq> S \<and> x \<in> t \<and> y \<in> t)" (is "?lhs = ?rhs") proof assume ?lhs then show ?rhs by (metis path_component_def path_connected_path_image pathfinish_in_path_image pathstart_in_path_image) next assume ?rhs then show ?lhs by (meson path_component_of_subset path_connected_component) qed lemma path_component_path_component [simp]: "path_component_set (path_component_set S x) x = path_component_set S x" proof (cases "x \<in> S") case True show ?thesis by (metis True mem_Collect_eq path_component_refl path_connected_component_set path_connected_path_component) next case False then show ?thesis by (metis False empty_iff path_component_eq_empty) qed lemma path_component_subset_connected_component: "(path_component_set S x) \<subseteq> (connected_component_set S x)" proof (cases "x \<in> S") case True show ?thesis by (simp add: True connected_component_maximal path_component_refl path_component_subset path_connected_imp_connected) next case False then show ?thesis using path_component_eq_empty by auto qed subsection\<^marker>\<open>tag unimportant\<close>\<open>Lemmas about path-connectedness\<close> lemma path_connected_linear_image: fixes f :: "'a::real_normed_vector \<Rightarrow> 'b::real_normed_vector" assumes "path_connected S" "bounded_linear f" shows "path_connected(f ` S)" by (auto simp: linear_continuous_on assms path_connected_continuous_image) lemma is_interval_path_connected: "is_interval S \<Longrightarrow> path_connected S" by (simp add: convex_imp_path_connected is_interval_convex) lemma path_connected_Ioi[simp]: "path_connected {a<..}" for a :: real by (simp add: convex_imp_path_connected) lemma path_connected_Ici[simp]: "path_connected {a..}" for a :: real by (simp add: convex_imp_path_connected) lemma path_connected_Iio[simp]: "path_connected {..<a}" for a :: real by (simp add: convex_imp_path_connected) lemma path_connected_Iic[simp]: "path_connected {..a}" for a :: real by (simp add: convex_imp_path_connected) lemma path_connected_Ioo[simp]: "path_connected {a<..<b}" for a b :: real by (simp add: convex_imp_path_connected) lemma path_connected_Ioc[simp]: "path_connected {a<..b}" for a b :: real by (simp add: convex_imp_path_connected) lemma path_connected_Ico[simp]: "path_connected {a..<b}" for a b :: real by (simp add: convex_imp_path_connected) lemma path_connectedin_path_image: assumes "pathin X g" shows "path_connectedin X (g ` ({0..1}))" unfolding pathin_def proof (rule path_connectedin_continuous_map_image) show "continuous_map (subtopology euclideanreal {0..1}) X g" using assms pathin_def by blast qed (auto simp: is_interval_1 is_interval_path_connected) lemma path_connected_space_subconnected: "path_connected_space X \<longleftrightarrow> (\<forall>x \<in> topspace X. \<forall>y \<in> topspace X. \<exists>S. path_connectedin X S \<and> x \<in> S \<and> y \<in> S)" by (metis path_connectedin path_connectedin_topspace path_connected_space_def) lemma connectedin_path_image: "pathin X g \<Longrightarrow> connectedin X (g ` ({0..1}))" by (simp add: path_connectedin_imp_connectedin path_connectedin_path_image) lemma compactin_path_image: "pathin X g \<Longrightarrow> compactin X (g ` ({0..1}))" unfolding pathin_def by (rule image_compactin [of "top_of_set {0..1}"]) auto lemma linear_homeomorphism_image: fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space" assumes "linear f" "inj f" obtains g where "homeomorphism (f ` S) S g f" proof - obtain g where "linear g" "g \<circ> f = id" using assms linear_injective_left_inverse by blast then have "homeomorphism (f ` S) S g f" using assms unfolding homeomorphism_def by (auto simp: eq_id_iff [symmetric] image_comp linear_conv_bounded_linear linear_continuous_on) then show thesis .. qed lemma linear_homeomorphic_image: fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space" assumes "linear f" "inj f" shows "S homeomorphic f ` S" by (meson homeomorphic_def homeomorphic_sym linear_homeomorphism_image [OF assms]) lemma path_connected_Times: assumes "path_connected s" "path_connected t" shows "path_connected (s \<times> t)" proof (simp add: path_connected_def Sigma_def, clarify) fix x1 y1 x2 y2 assume "x1 \<in> s" "y1 \<in> t" "x2 \<in> s" "y2 \<in> t" obtain g where "path g" and g: "path_image g \<subseteq> s" and gs: "pathstart g = x1" and gf: "pathfinish g = x2" using \<open>x1 \<in> s\<close> \<open>x2 \<in> s\<close> assms by (force simp: path_connected_def) obtain h where "path h" and h: "path_image h \<subseteq> t" and hs: "pathstart h = y1" and hf: "pathfinish h = y2" using \<open>y1 \<in> t\<close> \<open>y2 \<in> t\<close> assms by (force simp: path_connected_def) have "path (\<lambda>z. (x1, h z))" using \<open>path h\<close> unfolding path_def by (intro continuous_intros continuous_on_compose2 [where g = "Pair _"]; force) moreover have "path (\<lambda>z. (g z, y2))" using \<open>path g\<close> unfolding path_def by (intro continuous_intros continuous_on_compose2 [where g = "Pair _"]; force) ultimately have 1: "path ((\<lambda>z. (x1, h z)) +++ (\<lambda>z. (g z, y2)))" by (metis hf gs path_join_imp pathstart_def pathfinish_def) have "path_image ((\<lambda>z. (x1, h z)) +++ (\<lambda>z. (g z, y2))) \<subseteq> path_image (\<lambda>z. (x1, h z)) \<union> path_image (\<lambda>z. (g z, y2))" by (rule Path_Connected.path_image_join_subset) also have "\<dots> \<subseteq> (\<Union>x\<in>s. \<Union>x1\<in>t. {(x, x1)})" using g h \<open>x1 \<in> s\<close> \<open>y2 \<in> t\<close> by (force simp: path_image_def) finally have 2: "path_image ((\<lambda>z. (x1, h z)) +++ (\<lambda>z. (g z, y2))) \<subseteq> (\<Union>x\<in>s. \<Union>x1\<in>t. {(x, x1)})" . show "\<exists>g. path g \<and> path_image g \<subseteq> (\<Union>x\<in>s. \<Union>x1\<in>t. {(x, x1)}) \<and> pathstart g = (x1, y1) \<and> pathfinish g = (x2, y2)" using 1 2 gf hs by (metis (no_types, lifting) pathfinish_def pathfinish_join pathstart_def pathstart_join) qed lemma is_interval_path_connected_1: fixes s :: "real set" shows "is_interval s \<longleftrightarrow> path_connected s" using is_interval_connected_1 is_interval_path_connected path_connected_imp_connected by blast subsection\<^marker>\<open>tag unimportant\<close>\<open>Path components\<close> lemma Union_path_component [simp]: "Union {path_component_set S x |x. x \<in> S} = S" using path_component_subset path_component_refl by blast lemma path_component_disjoint: "disjnt (path_component_set S a) (path_component_set S b) \<longleftrightarrow> (a \<notin> path_component_set S b)" unfolding disjnt_iff using path_component_sym path_component_trans by blast lemma path_component_eq_eq: "path_component S x = path_component S y \<longleftrightarrow> (x \<notin> S) \<and> (y \<notin> S) \<or> x \<in> S \<and> y \<in> S \<and> path_component S x y" (is "?lhs = ?rhs") proof assume ?lhs then show ?rhs by (metis (no_types) path_component_mem(1) path_component_refl) next assume ?rhs then show ?lhs proof assume "x \<notin> S \<and> y \<notin> S" then show ?lhs by (metis Collect_empty_eq_bot path_component_eq_empty) next assume S: "x \<in> S \<and> y \<in> S \<and> path_component S x y" show ?lhs by (rule ext) (metis S path_component_trans path_component_sym) qed qed lemma path_component_unique: assumes "x \<in> c" "c \<subseteq> S" "path_connected c" "\<And>c'. \<lbrakk>x \<in> c'; c' \<subseteq> S; path_connected c'\<rbrakk> \<Longrightarrow> c' \<subseteq> c" shows "path_component_set S x = c" (is "?lhs = ?rhs") proof show "?lhs \<subseteq> ?rhs" using assms by (metis mem_Collect_eq path_component_refl path_component_subset path_connected_path_component subsetD) qed (simp add: assms path_component_maximal) lemma path_component_intermediate_subset: "path_component_set u a \<subseteq> t \<and> t \<subseteq> u \<Longrightarrow> path_component_set t a = path_component_set u a" by (metis (no_types) path_component_mono path_component_path_component subset_antisym) lemma complement_path_component_Union: fixes x :: "'a :: topological_space" shows "S - path_component_set S x = \<Union>({path_component_set S y| y. y \<in> S} - {path_component_set S x})" proof - have *: "(\<And>x. x \<in> S - {a} \<Longrightarrow> disjnt a x) \<Longrightarrow> \<Union>S - a = \<Union>(S - {a})" for a::"'a set" and S by (auto simp: disjnt_def) have "\<And>y. y \<in> {path_component_set S x |x. x \<in> S} - {path_component_set S x} \<Longrightarrow> disjnt (path_component_set S x) y" using path_component_disjoint path_component_eq by fastforce then have "\<Union>{path_component_set S x |x. x \<in> S} - path_component_set S x = \<Union>({path_component_set S y |y. y \<in> S} - {path_component_set S x})" by (meson *) then show ?thesis by simp qed subsection\<open>Path components\<close> definition path_component_of where "path_component_of X x y \<equiv> \<exists>g. pathin X g \<and> g 0 = x \<and> g 1 = y" abbreviation path_component_of_set where "path_component_of_set X x \<equiv> Collect (path_component_of X x)" definition path_components_of :: "'a topology \<Rightarrow> 'a set set" where "path_components_of X \<equiv> path_component_of_set X ` topspace X" lemma pathin_canon_iff: "pathin (top_of_set T) g \<longleftrightarrow> path g \<and> g ` {0..1} \<subseteq> T" by (simp add: path_def pathin_def) lemma path_component_of_canon_iff [simp]: "path_component_of (top_of_set T) a b \<longleftrightarrow> path_component T a b" by (simp add: path_component_of_def pathin_canon_iff path_defs) lemma path_component_in_topspace: "path_component_of X x y \<Longrightarrow> x \<in> topspace X \<and> y \<in> topspace X" by (auto simp: path_component_of_def pathin_def continuous_map_def) lemma path_component_of_refl: "path_component_of X x x \<longleftrightarrow> x \<in> topspace X" by (metis path_component_in_topspace path_component_of_def pathin_const) lemma path_component_of_sym: assumes "path_component_of X x y" shows "path_component_of X y x" using assms apply (clarsimp simp: path_component_of_def pathin_def) apply (rule_tac x="g \<circ> (\<lambda>t. 1 - t)" in exI) apply (auto intro!: continuous_map_compose simp: continuous_map_in_subtopology continuous_on_op_minus) done lemma path_component_of_sym_iff: "path_component_of X x y \<longleftrightarrow> path_component_of X y x" by (metis path_component_of_sym) lemma continuous_map_cases_le: assumes contp: "continuous_map X euclideanreal p" and contq: "continuous_map X euclideanreal q" and contf: "continuous_map (subtopology X {x. x \<in> topspace X \<and> p x \<le> q x}) Y f" and contg: "continuous_map (subtopology X {x. x \<in> topspace X \<and> q x \<le> p x}) Y g" and fg: "\<And>x. \<lbrakk>x \<in> topspace X; p x = q x\<rbrakk> \<Longrightarrow> f x = g x" shows "continuous_map X Y (\<lambda>x. if p x \<le> q x then f x else g x)" proof - have "continuous_map X Y (\<lambda>x. if q x - p x \<in> {0..} then f x else g x)" proof (rule continuous_map_cases_function) show "continuous_map X euclideanreal (\<lambda>x. q x - p x)" by (intro contp contq continuous_intros) show "continuous_map (subtopology X {x \<in> topspace X. q x - p x \<in> euclideanreal closure_of {0..}}) Y f" by (simp add: contf) show "continuous_map (subtopology X {x \<in> topspace X. q x - p x \<in> euclideanreal closure_of (topspace euclideanreal - {0..})}) Y g" by (simp add: contg flip: Compl_eq_Diff_UNIV) qed (auto simp: fg) then show ?thesis by simp qed lemma continuous_map_cases_lt: assumes contp: "continuous_map X euclideanreal p" and contq: "continuous_map X euclideanreal q" and contf: "continuous_map (subtopology X {x. x \<in> topspace X \<and> p x \<le> q x}) Y f" and contg: "continuous_map (subtopology X {x. x \<in> topspace X \<and> q x \<le> p x}) Y g" and fg: "\<And>x. \<lbrakk>x \<in> topspace X; p x = q x\<rbrakk> \<Longrightarrow> f x = g x" shows "continuous_map X Y (\<lambda>x. if p x < q x then f x else g x)" proof - have "continuous_map X Y (\<lambda>x. if q x - p x \<in> {0<..} then f x else g x)" proof (rule continuous_map_cases_function) show "continuous_map X euclideanreal (\<lambda>x. q x - p x)" by (intro contp contq continuous_intros) show "continuous_map (subtopology X {x \<in> topspace X. q x - p x \<in> euclideanreal closure_of {0<..}}) Y f" by (simp add: contf) show "continuous_map (subtopology X {x \<in> topspace X. q x - p x \<in> euclideanreal closure_of (topspace euclideanreal - {0<..})}) Y g" by (simp add: contg flip: Compl_eq_Diff_UNIV) qed (auto simp: fg) then show ?thesis by simp qed lemma path_component_of_trans: assumes "path_component_of X x y" and "path_component_of X y z" shows "path_component_of X x z" unfolding path_component_of_def pathin_def proof - let ?T01 = "top_of_set {0..1::real}" obtain g1 g2 where g1: "continuous_map ?T01 X g1" "x = g1 0" "y = g1 1" and g2: "continuous_map ?T01 X g2" "g2 0 = g1 1" "z = g2 1" using assms unfolding path_component_of_def pathin_def by blast let ?g = "\<lambda>x. if x \<le> 1/2 then (g1 \<circ> (\<lambda>t. 2 * t)) x else (g2 \<circ> (\<lambda>t. 2 * t -1)) x" show "\<exists>g. continuous_map ?T01 X g \<and> g 0 = x \<and> g 1 = z" proof (intro exI conjI) show "continuous_map (subtopology euclideanreal {0..1}) X ?g" proof (intro continuous_map_cases_le continuous_map_compose, force, force) show "continuous_map (subtopology ?T01 {x \<in> topspace ?T01. x \<le> 1/2}) ?T01 ((*) 2)" by (auto simp: continuous_map_in_subtopology continuous_map_from_subtopology) have "continuous_map (subtopology (top_of_set {0..1}) {x. 0 \<le> x \<and> x \<le> 1 \<and> 1 \<le> x * 2}) euclideanreal (\<lambda>t. 2 * t - 1)" by (intro continuous_intros) (force intro: continuous_map_from_subtopology) then show "continuous_map (subtopology ?T01 {x \<in> topspace ?T01. 1/2 \<le> x}) ?T01 (\<lambda>t. 2 * t - 1)" by (force simp: continuous_map_in_subtopology) show "(g1 \<circ> (*) 2) x = (g2 \<circ> (\<lambda>t. 2 * t - 1)) x" if "x \<in> topspace ?T01" "x = 1/2" for x using that by (simp add: g2(2) mult.commute continuous_map_from_subtopology) qed (auto simp: g1 g2) qed (auto simp: g1 g2) qed lemma path_component_of_mono: "\<lbrakk>path_component_of (subtopology X S) x y; S \<subseteq> T\<rbrakk> \<Longrightarrow> path_component_of (subtopology X T) x y" unfolding path_component_of_def by (metis subsetD pathin_subtopology) lemma path_component_of: "path_component_of X x y \<longleftrightarrow> (\<exists>T. path_connectedin X T \<and> x \<in> T \<and> y \<in> T)" (is "?lhs = ?rhs") proof assume ?lhs then show ?rhs by (metis atLeastAtMost_iff image_eqI order_refl path_component_of_def path_connectedin_path_image zero_le_one) next assume ?rhs then show ?lhs by (metis path_component_of_def path_connectedin) qed lemma path_component_of_set: "path_component_of X x y \<longleftrightarrow> (\<exists>g. pathin X g \<and> g 0 = x \<and> g 1 = y)" by (auto simp: path_component_of_def) lemma path_component_of_subset_topspace: "Collect(path_component_of X x) \<subseteq> topspace X" using path_component_in_topspace by fastforce lemma path_component_of_eq_empty: "Collect(path_component_of X x) = {} \<longleftrightarrow> (x \<notin> topspace X)" using path_component_in_topspace path_component_of_refl by fastforce lemma path_connected_space_iff_path_component: "path_connected_space X \<longleftrightarrow> (\<forall>x \<in> topspace X. \<forall>y \<in> topspace X. path_component_of X x y)" by (simp add: path_component_of path_connected_space_subconnected) lemma path_connected_space_imp_path_component_of: "\<lbrakk>path_connected_space X; a \<in> topspace X; b \<in> topspace X\<rbrakk> \<Longrightarrow> path_component_of X a b" by (simp add: path_connected_space_iff_path_component) lemma path_connected_space_path_component_set: "path_connected_space X \<longleftrightarrow> (\<forall>x \<in> topspace X. Collect(path_component_of X x) = topspace X)" using path_component_of_subset_topspace path_connected_space_iff_path_component by fastforce lemma path_component_of_maximal: "\<lbrakk>path_connectedin X s; x \<in> s\<rbrakk> \<Longrightarrow> s \<subseteq> Collect(path_component_of X x)" using path_component_of by fastforce lemma path_component_of_equiv: "path_component_of X x y \<longleftrightarrow> x \<in> topspace X \<and> y \<in> topspace X \<and> path_component_of X x = path_component_of X y" (is "?lhs = ?rhs") proof assume ?lhs then show ?rhs apply (simp add: fun_eq_iff path_component_in_topspace) apply (meson path_component_of_sym path_component_of_trans) done qed (simp add: path_component_of_refl) lemma path_component_of_disjoint: "disjnt (Collect (path_component_of X x)) (Collect (path_component_of X y)) \<longleftrightarrow> ~(path_component_of X x y)" by (force simp: disjnt_def path_component_of_eq_empty path_component_of_equiv) lemma path_component_of_eq: "path_component_of X x = path_component_of X y \<longleftrightarrow> (x \<notin> topspace X) \<and> (y \<notin> topspace X) \<or> x \<in> topspace X \<and> y \<in> topspace X \<and> path_component_of X x y" by (metis Collect_empty_eq_bot path_component_of_eq_empty path_component_of_equiv) lemma path_component_of_aux: "path_component_of X x y \<Longrightarrow> path_component_of (subtopology X (Collect (path_component_of X x))) x y" by (meson path_component_of path_component_of_maximal path_connectedin_subtopology) lemma path_connectedin_path_component_of: "path_connectedin X (Collect (path_component_of X x))" proof - have "topspace (subtopology X (path_component_of_set X x)) = path_component_of_set X x" by (meson path_component_of_subset_topspace topspace_subtopology_subset) then have "path_connected_space (subtopology X (path_component_of_set X x))" by (metis (full_types) path_component_of_aux mem_Collect_eq path_component_of_equiv path_connected_space_iff_path_component) then show ?thesis by (simp add: path_component_of_subset_topspace path_connectedin_def) qed lemma path_connectedin_euclidean [simp]: "path_connectedin euclidean S \<longleftrightarrow> path_connected S" by (auto simp: path_connectedin_def path_connected_space_iff_path_component path_connected_component) lemma path_connected_space_euclidean_subtopology [simp]: "path_connected_space(subtopology euclidean S) \<longleftrightarrow> path_connected S" using path_connectedin_topspace by force lemma Union_path_components_of: "\<Union>(path_components_of X) = topspace X" by (auto simp: path_components_of_def path_component_of_equiv) lemma path_components_of_maximal: "\<lbrakk>C \<in> path_components_of X; path_connectedin X S; ~disjnt C S\<rbrakk> \<Longrightarrow> S \<subseteq> C" by (smt (verit, ccfv_SIG) disjnt_iff imageE mem_Collect_eq path_component_of_equiv path_component_of_maximal path_components_of_def) lemma pairwise_disjoint_path_components_of: "pairwise disjnt (path_components_of X)" by (auto simp: path_components_of_def pairwise_def path_component_of_disjoint path_component_of_equiv) lemma complement_path_components_of_Union: "C \<in> path_components_of X \<Longrightarrow> topspace X - C = \<Union>(path_components_of X - {C})" by (metis Union_path_components_of bot.extremum ccpo_Sup_singleton diff_Union_pairwise_disjoint insert_subsetI pairwise_disjoint_path_components_of) lemma nonempty_path_components_of: assumes "C \<in> path_components_of X" shows "C \<noteq> {}" by (metis assms imageE path_component_of_eq_empty path_components_of_def) lemma path_components_of_subset: "C \<in> path_components_of X \<Longrightarrow> C \<subseteq> topspace X" by (auto simp: path_components_of_def path_component_of_equiv) lemma path_connectedin_path_components_of: "C \<in> path_components_of X \<Longrightarrow> path_connectedin X C" by (auto simp: path_components_of_def path_connectedin_path_component_of) lemma path_component_in_path_components_of: "Collect (path_component_of X a) \<in> path_components_of X \<longleftrightarrow> a \<in> topspace X" by (metis imageI nonempty_path_components_of path_component_of_eq_empty path_components_of_def) lemma path_connectedin_Union: assumes \<A>: "\<And>S. S \<in> \<A> \<Longrightarrow> path_connectedin X S" "\<Inter>\<A> \<noteq> {}" shows "path_connectedin X (\<Union>\<A>)" proof - obtain a where "\<And>S. S \<in> \<A> \<Longrightarrow> a \<in> S" using assms by blast then have "\<And>x. x \<in> topspace (subtopology X (\<Union>\<A>)) \<Longrightarrow> path_component_of (subtopology X (\<Union>\<A>)) a x" by simp (meson Union_upper \<A> path_component_of path_connectedin_subtopology) then show ?thesis using \<A> unfolding path_connectedin_def by (metis Sup_le_iff path_component_of_equiv path_connected_space_iff_path_component) qed lemma path_connectedin_Un: "\<lbrakk>path_connectedin X S; path_connectedin X T; S \<inter> T \<noteq> {}\<rbrakk> \<Longrightarrow> path_connectedin X (S \<union> T)" by (blast intro: path_connectedin_Union [of "{S,T}", simplified]) lemma path_connected_space_iff_components_eq: "path_connected_space X \<longleftrightarrow> (\<forall>C \<in> path_components_of X. \<forall>C' \<in> path_components_of X. C = C')" unfolding path_components_of_def proof (intro iffI ballI) assume "\<forall>C \<in> path_component_of_set X ` topspace X. \<forall>C' \<in> path_component_of_set X ` topspace X. C = C'" then show "path_connected_space X" using path_component_of_refl path_connected_space_iff_path_component by fastforce qed (auto simp: path_connected_space_path_component_set) lemma path_components_of_eq_empty: "path_components_of X = {} \<longleftrightarrow> topspace X = {}" using Union_path_components_of nonempty_path_components_of by fastforce lemma path_components_of_empty_space: "topspace X = {} \<Longrightarrow> path_components_of X = {}" by (simp add: path_components_of_eq_empty) lemma path_components_of_subset_singleton: "path_components_of X \<subseteq> {S} \<longleftrightarrow> path_connected_space X \<and> (topspace X = {} \<or> topspace X = S)" proof (cases "topspace X = {}") case True then show ?thesis by (auto simp: path_components_of_empty_space path_connected_space_topspace_empty) next case False have "(path_components_of X = {S}) \<longleftrightarrow> (path_connected_space X \<and> topspace X = S)" by (metis False Set.set_insert ex_in_conv insert_iff path_component_in_path_components_of path_connected_space_iff_components_eq path_connected_space_path_component_set) with False show ?thesis by (simp add: path_components_of_eq_empty subset_singleton_iff) qed lemma path_connected_space_iff_components_subset_singleton: "path_connected_space X \<longleftrightarrow> (\<exists>a. path_components_of X \<subseteq> {a})" by (simp add: path_components_of_subset_singleton) lemma path_components_of_eq_singleton: "path_components_of X = {S} \<longleftrightarrow> path_connected_space X \<and> topspace X \<noteq> {} \<and> S = topspace X" by (metis cSup_singleton insert_not_empty path_components_of_subset_singleton subset_singleton_iff) lemma path_components_of_path_connected_space: "path_connected_space X \<Longrightarrow> path_components_of X = (if topspace X = {} then {} else {topspace X})" by (simp add: path_components_of_eq_empty path_components_of_eq_singleton) lemma path_component_subset_connected_component_of: "path_component_of_set X x \<subseteq> connected_component_of_set X x" proof (cases "x \<in> topspace X") case True then show ?thesis by (simp add: connected_component_of_maximal path_component_of_refl path_connectedin_imp_connectedin path_connectedin_path_component_of) next case False then show ?thesis using path_component_of_eq_empty by fastforce qed lemma exists_path_component_of_superset: assumes S: "path_connectedin X S" and ne: "topspace X \<noteq> {}" obtains C where "C \<in> path_components_of X" "S \<subseteq> C" by (metis S ne ex_in_conv path_component_in_path_components_of path_component_of_maximal path_component_of_subset_topspace subset_eq that) lemma path_component_of_eq_overlap: "path_component_of X x = path_component_of X y \<longleftrightarrow> (x \<notin> topspace X) \<and> (y \<notin> topspace X) \<or> Collect (path_component_of X x) \<inter> Collect (path_component_of X y) \<noteq> {}" by (metis disjnt_def empty_iff inf_bot_right mem_Collect_eq path_component_of_disjoint path_component_of_eq path_component_of_eq_empty) lemma path_component_of_nonoverlap: "Collect (path_component_of X x) \<inter> Collect (path_component_of X y) = {} \<longleftrightarrow> (x \<notin> topspace X) \<or> (y \<notin> topspace X) \<or> path_component_of X x \<noteq> path_component_of X y" by (metis inf.idem path_component_of_eq_empty path_component_of_eq_overlap) lemma path_component_of_overlap: "Collect (path_component_of X x) \<inter> Collect (path_component_of X y) \<noteq> {} \<longleftrightarrow> x \<in> topspace X \<and> y \<in> topspace X \<and> path_component_of X x = path_component_of X y" by (meson path_component_of_nonoverlap) lemma path_components_of_disjoint: "\<lbrakk>C \<in> path_components_of X; C' \<in> path_components_of X\<rbrakk> \<Longrightarrow> disjnt C C' \<longleftrightarrow> C \<noteq> C'" by (auto simp: path_components_of_def path_component_of_disjoint path_component_of_equiv) lemma path_components_of_overlap: "\<lbrakk>C \<in> path_components_of X; C' \<in> path_components_of X\<rbrakk> \<Longrightarrow> C \<inter> C' \<noteq> {} \<longleftrightarrow> C = C'" by (auto simp: path_components_of_def path_component_of_equiv) lemma path_component_of_unique: "\<lbrakk>x \<in> C; path_connectedin X C; \<And>C'. \<lbrakk>x \<in> C'; path_connectedin X C'\<rbrakk> \<Longrightarrow> C' \<subseteq> C\<rbrakk> \<Longrightarrow> Collect (path_component_of X x) = C" by (meson subsetD eq_iff path_component_of_maximal path_connectedin_path_component_of) lemma path_component_of_discrete_topology [simp]: "Collect (path_component_of (discrete_topology U) x) = (if x \<in> U then {x} else {})" proof - have "\<And>C'. \<lbrakk>x \<in> C'; path_connectedin (discrete_topology U) C'\<rbrakk> \<Longrightarrow> C' \<subseteq> {x}" by (metis path_connectedin_discrete_topology subsetD singletonD) then have "x \<in> U \<Longrightarrow> Collect (path_component_of (discrete_topology U) x) = {x}" by (simp add: path_component_of_unique) then show ?thesis using path_component_in_topspace by fastforce qed lemma path_component_of_discrete_topology_iff [simp]: "path_component_of (discrete_topology U) x y \<longleftrightarrow> x \<in> U \<and> y=x" by (metis empty_iff insertI1 mem_Collect_eq path_component_of_discrete_topology singletonD) lemma path_components_of_discrete_topology [simp]: "path_components_of (discrete_topology U) = (\<lambda>x. {x}) ` U" by (auto simp: path_components_of_def image_def fun_eq_iff) lemma homeomorphic_map_path_component_of: assumes f: "homeomorphic_map X Y f" and x: "x \<in> topspace X" shows "Collect (path_component_of Y (f x)) = f ` Collect(path_component_of X x)" proof - obtain g where g: "homeomorphic_maps X Y f g" using f homeomorphic_map_maps by blast show ?thesis proof have "Collect (path_component_of Y (f x)) \<subseteq> topspace Y" by (simp add: path_component_of_subset_topspace) moreover have "g ` Collect(path_component_of Y (f x)) \<subseteq> Collect (path_component_of X (g (f x)))" using f g x unfolding homeomorphic_maps_def by (metis image_Collect_subsetI image_eqI mem_Collect_eq path_component_of_equiv path_component_of_maximal path_connectedin_continuous_map_image path_connectedin_path_component_of) ultimately show "Collect (path_component_of Y (f x)) \<subseteq> f ` Collect (path_component_of X x)" using g x unfolding homeomorphic_maps_def continuous_map_def image_iff subset_iff by metis show "f ` Collect (path_component_of X x) \<subseteq> Collect (path_component_of Y (f x))" proof (rule path_component_of_maximal) show "path_connectedin Y (f ` Collect (path_component_of X x))" by (meson f homeomorphic_map_path_connectedness_eq path_connectedin_path_component_of) qed (simp add: path_component_of_refl x) qed qed lemma homeomorphic_map_path_components_of: assumes "homeomorphic_map X Y f" shows "path_components_of Y = (image f) ` (path_components_of X)" unfolding path_components_of_def homeomorphic_imp_surjective_map [OF assms, symmetric] using assms homeomorphic_map_path_component_of by fastforce subsection \<open>Sphere is path-connected\<close> lemma path_connected_punctured_universe: assumes "2 \<le> DIM('a::euclidean_space)" shows "path_connected (- {a::'a})" proof - let ?A = "{x::'a. \<exists>i\<in>Basis. x \<bullet> i < a \<bullet> i}" let ?B = "{x::'a. \<exists>i\<in>Basis. a \<bullet> i < x \<bullet> i}" have A: "path_connected ?A" unfolding Collect_bex_eq proof (rule path_connected_UNION) fix i :: 'a assume "i \<in> Basis" then show "(\<Sum>i\<in>Basis. (a \<bullet> i - 1)*\<^sub>R i) \<in> {x::'a. x \<bullet> i < a \<bullet> i}" by simp show "path_connected {x. x \<bullet> i < a \<bullet> i}" using convex_imp_path_connected [OF convex_halfspace_lt, of i "a \<bullet> i"] by (simp add: inner_commute) qed have B: "path_connected ?B" unfolding Collect_bex_eq proof (rule path_connected_UNION) fix i :: 'a assume "i \<in> Basis" then show "(\<Sum>i\<in>Basis. (a \<bullet> i + 1) *\<^sub>R i) \<in> {x::'a. a \<bullet> i < x \<bullet> i}" by simp show "path_connected {x. a \<bullet> i < x \<bullet> i}" using convex_imp_path_connected [OF convex_halfspace_gt, of "a \<bullet> i" i] by (simp add: inner_commute) qed obtain S :: "'a set" where "S \<subseteq> Basis" and "card S = Suc (Suc 0)" using obtain_subset_with_card_n[OF assms] by (force simp add: eval_nat_numeral) then obtain b0 b1 :: 'a where "b0 \<in> Basis" and "b1 \<in> Basis" and "b0 \<noteq> b1" unfolding card_Suc_eq by auto then have "a + b0 - b1 \<in> ?A \<inter> ?B" by (auto simp: inner_simps inner_Basis) then have "?A \<inter> ?B \<noteq> {}" by fast with A B have "path_connected (?A \<union> ?B)" by (rule path_connected_Un) also have "?A \<union> ?B = {x. \<exists>i\<in>Basis. x \<bullet> i \<noteq> a \<bullet> i}" unfolding neq_iff bex_disj_distrib Collect_disj_eq .. also have "\<dots> = {x. x \<noteq> a}" unfolding euclidean_eq_iff [where 'a='a] by (simp add: Bex_def) also have "\<dots> = - {a}" by auto finally show ?thesis . qed corollary connected_punctured_universe: "2 \<le> DIM('N::euclidean_space) \<Longrightarrow> connected(- {a::'N})" by (simp add: path_connected_punctured_universe path_connected_imp_connected) proposition path_connected_sphere: fixes a :: "'a :: euclidean_space" assumes "2 \<le> DIM('a)" shows "path_connected(sphere a r)" proof (cases r "0::real" rule: linorder_cases) case less then show ?thesis by simp next case equal then show ?thesis by simp next case greater then have eq: "(sphere (0::'a) r) = (\<lambda>x. (r / norm x) *\<^sub>R x) ` (- {0::'a})" by (force simp: image_iff split: if_split_asm) have "continuous_on (- {0::'a}) (\<lambda>x. (r / norm x) *\<^sub>R x)" by (intro continuous_intros) auto then have "path_connected ((\<lambda>x. (r / norm x) *\<^sub>R x) ` (- {0::'a}))" by (intro path_connected_continuous_image path_connected_punctured_universe assms) with eq have "path_connected (sphere (0::'a) r)" by auto then have "path_connected((+) a ` (sphere (0::'a) r))" by (simp add: path_connected_translation) then show ?thesis by (metis add.right_neutral sphere_translation) qed lemma connected_sphere: fixes a :: "'a :: euclidean_space" assumes "2 \<le> DIM('a)" shows "connected(sphere a r)" using path_connected_sphere [OF assms] by (simp add: path_connected_imp_connected) corollary path_connected_complement_bounded_convex: fixes S :: "'a :: euclidean_space set" assumes "bounded S" "convex S" and 2: "2 \<le> DIM('a)" shows "path_connected (- S)" proof (cases "S = {}") case True then show ?thesis using convex_imp_path_connected by auto next case False then obtain a where "a \<in> S" by auto have \<section> [rule_format]: "\<forall>y\<in>S. \<forall>u. 0 \<le> u \<and> u \<le> 1 \<longrightarrow> (1 - u) *\<^sub>R a + u *\<^sub>R y \<in> S" using \<open>convex S\<close> \<open>a \<in> S\<close> by (simp add: convex_alt) { fix x y assume "x \<notin> S" "y \<notin> S" then have "x \<noteq> a" "y \<noteq> a" using \<open>a \<in> S\<close> by auto then have bxy: "bounded(insert x (insert y S))" by (simp add: \<open>bounded S\<close>) then obtain B::real where B: "0 < B" and Bx: "norm (a - x) < B" and By: "norm (a - y) < B" and "S \<subseteq> ball a B" using bounded_subset_ballD [OF bxy, of a] by (auto simp: dist_norm) define C where "C = B / norm(x - a)" let ?Cxa = "a + C *\<^sub>R (x - a)" { fix u assume u: "(1 - u) *\<^sub>R x + u *\<^sub>R ?Cxa \<in> S" and "0 \<le> u" "u \<le> 1" have CC: "1 \<le> 1 + (C - 1) * u" using \<open>x \<noteq> a\<close> \<open>0 \<le> u\<close> Bx by (auto simp add: C_def norm_minus_commute) have *: "\<And>v. (1 - u) *\<^sub>R x + u *\<^sub>R (a + v *\<^sub>R (x - a)) = a + (1 + (v - 1) * u) *\<^sub>R (x - a)" by (simp add: algebra_simps) have "a + ((1 / (1 + C * u - u)) *\<^sub>R x + ((u / (1 + C * u - u)) *\<^sub>R a + (C * u / (1 + C * u - u)) *\<^sub>R x)) = (1 + (u / (1 + C * u - u))) *\<^sub>R a + ((1 / (1 + C * u - u)) + (C * u / (1 + C * u - u))) *\<^sub>R x" by (simp add: algebra_simps) also have "\<dots> = (1 + (u / (1 + C * u - u))) *\<^sub>R a + (1 + (u / (1 + C * u - u))) *\<^sub>R x" using CC by (simp add: field_simps) also have "\<dots> = x + (1 + (u / (1 + C * u - u))) *\<^sub>R a + (u / (1 + C * u - u)) *\<^sub>R x" by (simp add: algebra_simps) also have "\<dots> = x + ((1 / (1 + C * u - u)) *\<^sub>R a + ((u / (1 + C * u - u)) *\<^sub>R x + (C * u / (1 + C * u - u)) *\<^sub>R a))" using CC by (simp add: field_simps) (simp add: add_divide_distrib scaleR_add_left) finally have xeq: "(1 - 1 / (1 + (C - 1) * u)) *\<^sub>R a + (1 / (1 + (C - 1) * u)) *\<^sub>R (a + (1 + (C - 1) * u) *\<^sub>R (x - a)) = x" by (simp add: algebra_simps) have False using \<section> [of "a + (1 + (C - 1) * u) *\<^sub>R (x - a)" "1 / (1 + (C - 1) * u)"] using u \<open>x \<noteq> a\<close> \<open>x \<notin> S\<close> \<open>0 \<le> u\<close> CC by (auto simp: xeq *) } then have pcx: "path_component (- S) x ?Cxa" by (force simp: closed_segment_def intro!: path_component_linepath) define D where "D = B / norm(y - a)" \<comment> \<open>massive duplication with the proof above\<close> let ?Dya = "a + D *\<^sub>R (y - a)" { fix u assume u: "(1 - u) *\<^sub>R y + u *\<^sub>R ?Dya \<in> S" and "0 \<le> u" "u \<le> 1" have DD: "1 \<le> 1 + (D - 1) * u" using \<open>y \<noteq> a\<close> \<open>0 \<le> u\<close> By by (auto simp add: D_def norm_minus_commute) have *: "\<And>v. (1 - u) *\<^sub>R y + u *\<^sub>R (a + v *\<^sub>R (y - a)) = a + (1 + (v - 1) * u) *\<^sub>R (y - a)" by (simp add: algebra_simps) have "a + ((1 / (1 + D * u - u)) *\<^sub>R y + ((u / (1 + D * u - u)) *\<^sub>R a + (D * u / (1 + D * u - u)) *\<^sub>R y)) = (1 + (u / (1 + D * u - u))) *\<^sub>R a + ((1 / (1 + D * u - u)) + (D * u / (1 + D * u - u))) *\<^sub>R y" by (simp add: algebra_simps) also have "\<dots> = (1 + (u / (1 + D * u - u))) *\<^sub>R a + (1 + (u / (1 + D * u - u))) *\<^sub>R y" using DD by (simp add: field_simps) also have "\<dots> = y + (1 + (u / (1 + D * u - u))) *\<^sub>R a + (u / (1 + D * u - u)) *\<^sub>R y" by (simp add: algebra_simps) also have "\<dots> = y + ((1 / (1 + D * u - u)) *\<^sub>R a + ((u / (1 + D * u - u)) *\<^sub>R y + (D * u / (1 + D * u - u)) *\<^sub>R a))" using DD by (simp add: field_simps) (simp add: add_divide_distrib scaleR_add_left) finally have xeq: "(1 - 1 / (1 + (D - 1) * u)) *\<^sub>R a + (1 / (1 + (D - 1) * u)) *\<^sub>R (a + (1 + (D - 1) * u) *\<^sub>R (y - a)) = y" by (simp add: algebra_simps) have False using \<section> [of "a + (1 + (D - 1) * u) *\<^sub>R (y - a)" "1 / (1 + (D - 1) * u)"] using u \<open>y \<noteq> a\<close> \<open>y \<notin> S\<close> \<open>0 \<le> u\<close> DD by (auto simp: xeq *) } then have pdy: "path_component (- S) y ?Dya" by (force simp: closed_segment_def intro!: path_component_linepath) have pyx: "path_component (- S) ?Dya ?Cxa" proof (rule path_component_of_subset) show "sphere a B \<subseteq> - S" using \<open>S \<subseteq> ball a B\<close> by (force simp: ball_def dist_norm norm_minus_commute) have aB: "?Dya \<in> sphere a B" "?Cxa \<in> sphere a B" using \<open>x \<noteq> a\<close> using \<open>y \<noteq> a\<close> B by (auto simp: dist_norm C_def D_def) then show "path_component (sphere a B) ?Dya ?Cxa" using path_connected_sphere [OF 2] path_connected_component by blast qed have "path_component (- S) x y" by (metis path_component_trans path_component_sym pcx pdy pyx) } then show ?thesis by (auto simp: path_connected_component) qed lemma connected_complement_bounded_convex: fixes S :: "'a :: euclidean_space set" assumes "bounded S" "convex S" "2 \<le> DIM('a)" shows "connected (- S)" using path_connected_complement_bounded_convex [OF assms] path_connected_imp_connected by blast lemma connected_diff_ball: fixes S :: "'a :: euclidean_space set" assumes "connected S" "cball a r \<subseteq> S" "2 \<le> DIM('a)" shows "connected (S - ball a r)" proof (rule connected_diff_open_from_closed [OF ball_subset_cball]) show "connected (cball a r - ball a r)" using assms connected_sphere by (auto simp: cball_diff_eq_sphere) qed (auto simp: assms dist_norm) proposition connected_open_delete: assumes "open S" "connected S" and 2: "2 \<le> DIM('N::euclidean_space)" shows "connected(S - {a::'N})" proof (cases "a \<in> S") case True with \<open>open S\<close> obtain \<epsilon> where "\<epsilon> > 0" and \<epsilon>: "cball a \<epsilon> \<subseteq> S" using open_contains_cball_eq by blast define b where "b \<equiv> a + \<epsilon> *\<^sub>R (SOME i. i \<in> Basis)" have "dist a b = \<epsilon>" by (simp add: b_def dist_norm SOME_Basis \<open>0 < \<epsilon>\<close> less_imp_le) with \<epsilon> have "b \<in> \<Inter>{S - ball a r |r. 0 < r \<and> r < \<epsilon>}" by auto then have nonemp: "(\<Inter>{S - ball a r |r. 0 < r \<and> r < \<epsilon>}) = {} \<Longrightarrow> False" by auto have con: "\<And>r. r < \<epsilon> \<Longrightarrow> connected (S - ball a r)" using \<epsilon> by (force intro: connected_diff_ball [OF \<open>connected S\<close> _ 2]) have "x \<in> \<Union>{S - ball a r |r. 0 < r \<and> r < \<epsilon>}" if "x \<in> S - {a}" for x using that \<open>0 < \<epsilon>\<close> by (intro UnionI [of "S - ball a (min \<epsilon> (dist a x) / 2)"]) auto then have "S - {a} = \<Union>{S - ball a r | r. 0 < r \<and> r < \<epsilon>}" by auto then show ?thesis by (auto intro: connected_Union con dest!: nonemp) next case False then show ?thesis by (simp add: \<open>connected S\<close>) qed corollary path_connected_open_delete: assumes "open S" "connected S" and 2: "2 \<le> DIM('N::euclidean_space)" shows "path_connected(S - {a::'N})" by (simp add: assms connected_open_delete connected_open_path_connected open_delete) corollary path_connected_punctured_ball: "2 \<le> DIM('N::euclidean_space) \<Longrightarrow> path_connected(ball a r - {a::'N})" by (simp add: path_connected_open_delete) corollary connected_punctured_ball: "2 \<le> DIM('N::euclidean_space) \<Longrightarrow> connected(ball a r - {a::'N})" by (simp add: connected_open_delete) corollary connected_open_delete_finite: fixes S T::"'a::euclidean_space set" assumes S: "open S" "connected S" and 2: "2 \<le> DIM('a)" and "finite T" shows "connected(S - T)" using \<open>finite T\<close> S proof (induct T) case empty show ?case using \<open>connected S\<close> by simp next case (insert x T) then have "connected (S-T)" by auto moreover have "open (S - T)" using finite_imp_closed[OF \<open>finite T\<close>] \<open>open S\<close> by auto ultimately have "connected (S - T - {x})" using connected_open_delete[OF _ _ 2] by auto thus ?case by (metis Diff_insert) qed lemma sphere_1D_doubleton_zero: assumes 1: "DIM('a) = 1" and "r > 0" obtains x y::"'a::euclidean_space" where "sphere 0 r = {x,y} \<and> dist x y = 2*r" proof - obtain b::'a where b: "Basis = {b}" using 1 card_1_singletonE by blast show ?thesis proof (intro that conjI) have "x = norm x *\<^sub>R b \<or> x = - norm x *\<^sub>R b" if "r = norm x" for x proof - have xb: "(x \<bullet> b) *\<^sub>R b = x" using euclidean_representation [of x, unfolded b] by force then have "norm ((x \<bullet> b) *\<^sub>R b) = norm x" by simp with b have "\<bar>x \<bullet> b\<bar> = norm x" using norm_Basis by (simp add: b) with xb show ?thesis by (metis (mono_tags, opaque_lifting) abs_eq_iff abs_norm_cancel) qed with \<open>r > 0\<close> b show "sphere 0 r = {r *\<^sub>R b, - r *\<^sub>R b}" by (force simp: sphere_def dist_norm) have "dist (r *\<^sub>R b) (- r *\<^sub>R b) = norm (r *\<^sub>R b + r *\<^sub>R b)" by (simp add: dist_norm) also have "\<dots> = norm ((2*r) *\<^sub>R b)" by (metis mult_2 scaleR_add_left) also have "\<dots> = 2*r" using \<open>r > 0\<close> b norm_Basis by fastforce finally show "dist (r *\<^sub>R b) (- r *\<^sub>R b) = 2*r" . qed qed lemma sphere_1D_doubleton: fixes a :: "'a :: euclidean_space" assumes "DIM('a) = 1" and "r > 0" obtains x y where "sphere a r = {x,y} \<and> dist x y = 2*r" using sphere_1D_doubleton_zero [OF assms] dist_add_cancel image_empty image_insert by (metis (no_types, opaque_lifting) add.right_neutral sphere_translation) lemma psubset_sphere_Compl_connected: fixes S :: "'a::euclidean_space set" assumes S: "S \<subset> sphere a r" and "0 < r" and 2: "2 \<le> DIM('a)" shows "connected(- S)" proof - have "S \<subseteq> sphere a r" using S by blast obtain b where "dist a b = r" and "b \<notin> S" using S mem_sphere by blast have CS: "- S = {x. dist a x \<le> r \<and> (x \<notin> S)} \<union> {x. r \<le> dist a x \<and> (x \<notin> S)}" by auto have "{x. dist a x \<le> r \<and> x \<notin> S} \<inter> {x. r \<le> dist a x \<and> x \<notin> S} \<noteq> {}" using \<open>b \<notin> S\<close> \<open>dist a b = r\<close> by blast moreover have "connected {x. dist a x \<le> r \<and> x \<notin> S}" using assms by (force intro: connected_intermediate_closure [of "ball a r"]) moreover have "connected {x. r \<le> dist a x \<and> x \<notin> S}" proof (rule connected_intermediate_closure [of "- cball a r"]) show "{x. r \<le> dist a x \<and> x \<notin> S} \<subseteq> closure (- cball a r)" using interior_closure by (force intro: connected_complement_bounded_convex) qed (use assms connected_complement_bounded_convex in auto) ultimately show ?thesis by (simp add: CS connected_Un) qed subsection\<open>Every annulus is a connected set\<close> lemma path_connected_2DIM_I: fixes a :: "'N::euclidean_space" assumes 2: "2 \<le> DIM('N)" and pc: "path_connected {r. 0 \<le> r \<and> P r}" shows "path_connected {x. P(norm(x - a))}" proof - have "{x. P(norm(x - a))} = (+) a ` {x. P(norm x)}" by force moreover have "path_connected {x::'N. P(norm x)}" proof - let ?D = "{x. 0 \<le> x \<and> P x} \<times> sphere (0::'N) 1" have "x \<in> (\<lambda>z. fst z *\<^sub>R snd z) ` ?D" if "P (norm x)" for x::'N proof (cases "x=0") case True with that show ?thesis apply (simp add: image_iff) by (metis (no_types) mem_sphere_0 order_refl vector_choose_size zero_le_one) next case False with that show ?thesis by (rule_tac x="(norm x, x /\<^sub>R norm x)" in image_eqI) auto qed then have *: "{x::'N. P(norm x)} = (\<lambda>z. fst z *\<^sub>R snd z) ` ?D" by auto have "continuous_on ?D (\<lambda>z:: real\<times>'N. fst z *\<^sub>R snd z)" by (intro continuous_intros) moreover have "path_connected ?D" by (metis path_connected_Times [OF pc] path_connected_sphere 2) ultimately show ?thesis by (simp add: "*" path_connected_continuous_image) qed ultimately show ?thesis using path_connected_translation by metis qed proposition path_connected_annulus: fixes a :: "'N::euclidean_space" assumes "2 \<le> DIM('N)" shows "path_connected {x. r1 < norm(x - a) \<and> norm(x - a) < r2}" "path_connected {x. r1 < norm(x - a) \<and> norm(x - a) \<le> r2}" "path_connected {x. r1 \<le> norm(x - a) \<and> norm(x - a) < r2}" "path_connected {x. r1 \<le> norm(x - a) \<and> norm(x - a) \<le> r2}" by (auto simp: is_interval_def intro!: is_interval_convex convex_imp_path_connected path_connected_2DIM_I [OF assms]) proposition connected_annulus: fixes a :: "'N::euclidean_space" assumes "2 \<le> DIM('N::euclidean_space)" shows "connected {x. r1 < norm(x - a) \<and> norm(x - a) < r2}" "connected {x. r1 < norm(x - a) \<and> norm(x - a) \<le> r2}" "connected {x. r1 \<le> norm(x - a) \<and> norm(x - a) < r2}" "connected {x. r1 \<le> norm(x - a) \<and> norm(x - a) \<le> r2}" by (auto simp: path_connected_annulus [OF assms] path_connected_imp_connected) subsection\<^marker>\<open>tag unimportant\<close>\<open>Relations between components and path components\<close> lemma open_connected_component: fixes S :: "'a::real_normed_vector set" assumes "open S" shows "open (connected_component_set S x)" proof (clarsimp simp: open_contains_ball) fix y assume xy: "connected_component S x y" then obtain e where "e>0" "ball y e \<subseteq> S" using assms connected_component_in openE by blast then show "\<exists>e>0. ball y e \<subseteq> connected_component_set S x" by (metis xy centre_in_ball connected_ball connected_component_eq_eq connected_component_in connected_component_maximal) qed corollary open_components: fixes S :: "'a::real_normed_vector set" shows "\<lbrakk>open u; S \<in> components u\<rbrakk> \<Longrightarrow> open S" by (simp add: components_iff) (metis open_connected_component) lemma in_closure_connected_component: fixes S :: "'a::real_normed_vector set" assumes x: "x \<in> S" and S: "open S" shows "x \<in> closure (connected_component_set S y) \<longleftrightarrow> x \<in> connected_component_set S y" proof - have "x islimpt connected_component_set S y \<Longrightarrow> connected_component S y x" by (metis (no_types, lifting) S connected_component_eq connected_component_refl islimptE mem_Collect_eq open_connected_component x) then show ?thesis by (auto simp: closure_def) qed lemma connected_disjoint_Union_open_pick: assumes "pairwise disjnt B" "\<And>S. S \<in> A \<Longrightarrow> connected S \<and> S \<noteq> {}" "\<And>S. S \<in> B \<Longrightarrow> open S" "\<Union>A \<subseteq> \<Union>B" "S \<in> A" obtains T where "T \<in> B" "S \<subseteq> T" "S \<inter> \<Union>(B - {T}) = {}" proof - have "S \<subseteq> \<Union>B" "connected S" "S \<noteq> {}" using assms \<open>S \<in> A\<close> by blast+ then obtain T where "T \<in> B" "S \<inter> T \<noteq> {}" by (metis Sup_inf_eq_bot_iff inf.absorb_iff2 inf_commute) have 1: "open T" by (simp add: \<open>T \<in> B\<close> assms) have 2: "open (\<Union>(B-{T}))" using assms by blast have 3: "S \<subseteq> T \<union> \<Union>(B - {T})" using \<open>S \<subseteq> \<Union>B\<close> by blast have "T \<inter> \<Union>(B - {T}) = {}" using \<open>T \<in> B\<close> \<open>pairwise disjnt B\<close> by (auto simp: pairwise_def disjnt_def) then have 4: "T \<inter> \<Union>(B - {T}) \<inter> S = {}" by auto from connectedD [OF \<open>connected S\<close> 1 2 4 3] have "S \<inter> \<Union>(B-{T}) = {}" by (auto simp: Int_commute \<open>S \<inter> T \<noteq> {}\<close>) with \<open>T \<in> B\<close> 3 that show ?thesis by (metis IntI UnE empty_iff subsetD subsetI) qed lemma connected_disjoint_Union_open_subset: assumes A: "pairwise disjnt A" and B: "pairwise disjnt B" and SA: "\<And>S. S \<in> A \<Longrightarrow> open S \<and> connected S \<and> S \<noteq> {}" and SB: "\<And>S. S \<in> B \<Longrightarrow> open S \<and> connected S \<and> S \<noteq> {}" and eq [simp]: "\<Union>A = \<Union>B" shows "A \<subseteq> B" proof fix S assume "S \<in> A" obtain T where "T \<in> B" "S \<subseteq> T" "S \<inter> \<Union>(B - {T}) = {}" using SA SB \<open>S \<in> A\<close> connected_disjoint_Union_open_pick [OF B, of A] eq order_refl by blast moreover obtain S' where "S' \<in> A" "T \<subseteq> S'" "T \<inter> \<Union>(A - {S'}) = {}" using SA SB \<open>T \<in> B\<close> connected_disjoint_Union_open_pick [OF A, of B] eq order_refl by blast ultimately have "S' = S" by (metis A Int_subset_iff SA \<open>S \<in> A\<close> disjnt_def inf.orderE pairwise_def) with \<open>T \<subseteq> S'\<close> have "T \<subseteq> S" by simp with \<open>S \<subseteq> T\<close> have "S = T" by blast with \<open>T \<in> B\<close> show "S \<in> B" by simp qed lemma connected_disjoint_Union_open_unique: assumes A: "pairwise disjnt A" and B: "pairwise disjnt B" and SA: "\<And>S. S \<in> A \<Longrightarrow> open S \<and> connected S \<and> S \<noteq> {}" and SB: "\<And>S. S \<in> B \<Longrightarrow> open S \<and> connected S \<and> S \<noteq> {}" and eq [simp]: "\<Union>A = \<Union>B" shows "A = B" by (metis subset_antisym connected_disjoint_Union_open_subset assms) proposition components_open_unique: fixes S :: "'a::real_normed_vector set" assumes "pairwise disjnt A" "\<Union>A = S" "\<And>X. X \<in> A \<Longrightarrow> open X \<and> connected X \<and> X \<noteq> {}" shows "components S = A" proof - have "open S" using assms by blast show ?thesis proof (rule connected_disjoint_Union_open_unique) show "disjoint (components S)" by (simp add: components_eq disjnt_def pairwise_def) qed (use \<open>open S\<close> in \<open>simp_all add: assms open_components in_components_connected in_components_nonempty\<close>) qed subsection\<^marker>\<open>tag unimportant\<close>\<open>Existence of unbounded components\<close> lemma cobounded_unbounded_component: fixes S :: "'a :: euclidean_space set" assumes "bounded (-S)" shows "\<exists>x. x \<in> S \<and> \<not> bounded (connected_component_set S x)" proof - obtain i::'a where i: "i \<in> Basis" using nonempty_Basis by blast obtain B where B: "B>0" "-S \<subseteq> ball 0 B" using bounded_subset_ballD [OF assms, of 0] by auto then have *: "\<And>x. B \<le> norm x \<Longrightarrow> x \<in> S" by (force simp: ball_def dist_norm) have unbounded_inner: "\<not> bounded {x. inner i x \<ge> B}" proof (clarsimp simp: bounded_def dist_norm) fix e x show "\<exists>y. B \<le> i \<bullet> y \<and> \<not> norm (x - y) \<le> e" using i by (rule_tac x="x + (max B e + 1 + \<bar>i \<bullet> x\<bar>) *\<^sub>R i" in exI) (auto simp: inner_right_distrib) qed have \<section>: "\<And>x. B \<le> i \<bullet> x \<Longrightarrow> x \<in> S" using * Basis_le_norm [OF i] by (metis abs_ge_self inner_commute order_trans) have "{x. B \<le> i \<bullet> x} \<subseteq> connected_component_set S (B *\<^sub>R i)" by (intro connected_component_maximal) (auto simp: i intro: convex_connected convex_halfspace_ge [of B] \<section>) then have "\<not> bounded (connected_component_set S (B *\<^sub>R i))" using bounded_subset unbounded_inner by blast moreover have "B *\<^sub>R i \<in> S" by (rule *) (simp add: norm_Basis [OF i]) ultimately show ?thesis by blast qed lemma cobounded_unique_unbounded_component: fixes S :: "'a :: euclidean_space set" assumes bs: "bounded (-S)" and "2 \<le> DIM('a)" and bo: "\<not> bounded(connected_component_set S x)" "\<not> bounded(connected_component_set S y)" shows "connected_component_set S x = connected_component_set S y" proof - obtain i::'a where i: "i \<in> Basis" using nonempty_Basis by blast obtain B where B: "B>0" "-S \<subseteq> ball 0 B" using bounded_subset_ballD [OF bs, of 0] by auto then have *: "\<And>x. B \<le> norm x \<Longrightarrow> x \<in> S" by (force simp: ball_def dist_norm) obtain x' where x': "connected_component S x x'" "norm x' > B" using B(1) bo(1) bounded_pos by force obtain y' where y': "connected_component S y y'" "norm y' > B" using B(1) bo(2) bounded_pos by force have x'y': "connected_component S x' y'" unfolding connected_component_def proof (intro exI conjI) show "connected (- ball 0 B :: 'a set)" using assms by (auto intro: connected_complement_bounded_convex) qed (use x' y' dist_norm * in auto) show ?thesis using x' y' x'y' by (metis connected_component_eq mem_Collect_eq) qed lemma cobounded_unbounded_components: fixes S :: "'a :: euclidean_space set" shows "bounded (-S) \<Longrightarrow> \<exists>c. c \<in> components S \<and> \<not>bounded c" by (metis cobounded_unbounded_component components_def imageI) lemma cobounded_unique_unbounded_components: fixes S :: "'a :: euclidean_space set" shows "\<lbrakk>bounded (- S); c \<in> components S; \<not> bounded c; c' \<in> components S; \<not> bounded c'; 2 \<le> DIM('a)\<rbrakk> \<Longrightarrow> c' = c" unfolding components_iff by (metis cobounded_unique_unbounded_component) lemma cobounded_has_bounded_component: fixes S :: "'a :: euclidean_space set" assumes "bounded (- S)" "\<not> connected S" "2 \<le> DIM('a)" obtains C where "C \<in> components S" "bounded C" by (meson cobounded_unique_unbounded_components connected_eq_connected_components_eq assms) subsection\<open>The \<open>inside\<close> and \<open>outside\<close> of a Set\<close> text\<^marker>\<open>tag important\<close>\<open>The inside comprises the points in a bounded connected component of the set's complement. The outside comprises the points in unbounded connected component of the complement.\<close> definition\<^marker>\<open>tag important\<close> inside where "inside S \<equiv> {x. (x \<notin> S) \<and> bounded(connected_component_set ( - S) x)}" definition\<^marker>\<open>tag important\<close> outside where "outside S \<equiv> -S \<inter> {x. \<not> bounded(connected_component_set (- S) x)}" lemma outside: "outside S = {x. \<not> bounded(connected_component_set (- S) x)}" by (auto simp: outside_def) (metis Compl_iff bounded_empty connected_component_eq_empty) lemma inside_no_overlap [simp]: "inside S \<inter> S = {}" by (auto simp: inside_def) lemma outside_no_overlap [simp]: "outside S \<inter> S = {}" by (auto simp: outside_def) lemma inside_Int_outside [simp]: "inside S \<inter> outside S = {}" by (auto simp: inside_def outside_def) lemma inside_Un_outside [simp]: "inside S \<union> outside S = (- S)" by (auto simp: inside_def outside_def) lemma inside_eq_outside: "inside S = outside S \<longleftrightarrow> S = UNIV" by (auto simp: inside_def outside_def) lemma inside_outside: "inside S = (- (S \<union> outside S))" by (force simp: inside_def outside) lemma outside_inside: "outside S = (- (S \<union> inside S))" by (auto simp: inside_outside) (metis IntI equals0D outside_no_overlap) lemma union_with_inside: "S \<union> inside S = - outside S" by (auto simp: inside_outside) (simp add: outside_inside) lemma union_with_outside: "S \<union> outside S = - inside S" by (simp add: inside_outside) lemma outside_mono: "S \<subseteq> T \<Longrightarrow> outside T \<subseteq> outside S" by (auto simp: outside bounded_subset connected_component_mono) lemma inside_mono: "S \<subseteq> T \<Longrightarrow> inside S - T \<subseteq> inside T" by (auto simp: inside_def bounded_subset connected_component_mono) lemma segment_bound_lemma: fixes u::real assumes "x \<ge> B" "y \<ge> B" "0 \<le> u" "u \<le> 1" shows "(1 - u) * x + u * y \<ge> B" by (smt (verit) assms convex_bound_le ge_iff_diff_ge_0 minus_add_distrib mult_minus_right neg_le_iff_le) lemma cobounded_outside: fixes S :: "'a :: real_normed_vector set" assumes "bounded S" shows "bounded (- outside S)" proof - obtain B where B: "B>0" "S \<subseteq> ball 0 B" using bounded_subset_ballD [OF assms, of 0] by auto { fix x::'a and C::real assume Bno: "B \<le> norm x" and C: "0 < C" have "\<exists>y. connected_component (- S) x y \<and> norm y > C" proof (cases "x = 0") case True with B Bno show ?thesis by force next case False have "closed_segment x (((B + C) / norm x) *\<^sub>R x) \<subseteq> - ball 0 B" proof fix w assume "w \<in> closed_segment x (((B + C) / norm x) *\<^sub>R x)" then obtain u where w: "w = (1 - u + u * (B + C) / norm x) *\<^sub>R x" "0 \<le> u" "u \<le> 1" by (auto simp add: closed_segment_def real_vector_class.scaleR_add_left [symmetric]) with False B C have "B \<le> (1 - u) * norm x + u * (B + C)" using segment_bound_lemma [of B "norm x" "B + C" u] Bno by simp with False B C show "w \<in> - ball 0 B" using distrib_right [of _ _ "norm x"] by (simp add: ball_def w not_less) qed also have "... \<subseteq> -S" by (simp add: B) finally have "\<exists>T. connected T \<and> T \<subseteq> - S \<and> x \<in> T \<and> ((B + C) / norm x) *\<^sub>R x \<in> T" by (rule_tac x="closed_segment x (((B+C)/norm x) *\<^sub>R x)" in exI) simp with False B show ?thesis by (rule_tac x="((B+C)/norm x) *\<^sub>R x" in exI) (simp add: connected_component_def) qed } then show ?thesis apply (simp add: outside_def assms) apply (rule bounded_subset [OF bounded_ball [of 0 B]]) apply (force simp: dist_norm not_less bounded_pos) done qed lemma unbounded_outside: fixes S :: "'a::{real_normed_vector, perfect_space} set" shows "bounded S \<Longrightarrow> \<not> bounded(outside S)" using cobounded_imp_unbounded cobounded_outside by blast lemma bounded_inside: fixes S :: "'a::{real_normed_vector, perfect_space} set" shows "bounded S \<Longrightarrow> bounded(inside S)" by (simp add: bounded_Int cobounded_outside inside_outside) lemma connected_outside: fixes S :: "'a::euclidean_space set" assumes "bounded S" "2 \<le> DIM('a)" shows "connected(outside S)" apply (clarsimp simp add: connected_iff_connected_component outside) apply (rule_tac S="connected_component_set (- S) x" in connected_component_of_subset) apply (metis (no_types) assms cobounded_unbounded_component cobounded_unique_unbounded_component connected_component_eq_eq connected_component_idemp double_complement mem_Collect_eq) by (simp add: Collect_mono connected_component_eq) lemma outside_connected_component_lt: "outside S = {x. \<forall>B. \<exists>y. B < norm(y) \<and> connected_component (- S) x y}" proof - have "\<And>x B. x \<in> outside S \<Longrightarrow> \<exists>y. B < norm y \<and> connected_component (- S) x y" by (metis boundedI linorder_not_less mem_Collect_eq outside) moreover have "\<And>x. \<forall>B. \<exists>y. B < norm y \<and> connected_component (- S) x y \<Longrightarrow> x \<in> outside S" by (metis bounded_pos linorder_not_less mem_Collect_eq outside) ultimately show ?thesis by auto qed lemma outside_connected_component_le: "outside S = {x. \<forall>B. \<exists>y. B \<le> norm(y) \<and> connected_component (- S) x y}" apply (simp add: outside_connected_component_lt Set.set_eq_iff) by (meson gt_ex leD le_less_linear less_imp_le order.trans) lemma not_outside_connected_component_lt: fixes S :: "'a::euclidean_space set" assumes S: "bounded S" and "2 \<le> DIM('a)" shows "- (outside S) = {x. \<forall>B. \<exists>y. B < norm(y) \<and> \<not> connected_component (- S) x y}" proof - obtain B::real where B: "0 < B" and Bno: "\<And>x. x \<in> S \<Longrightarrow> norm x \<le> B" using S [simplified bounded_pos] by auto have cyz: "connected_component (- S) y z" if yz: "B < norm z" "B < norm y" for y::'a and z::'a proof - have "connected_component (- cball 0 B) y z" using assms yz by (force simp: dist_norm intro: connected_componentI [OF _ subset_refl] connected_complement_bounded_convex) then show ?thesis by (metis connected_component_of_subset Bno Compl_anti_mono mem_cball_0 subset_iff) qed show ?thesis apply (auto simp: outside bounded_pos) apply (metis Compl_iff bounded_iff cobounded_imp_unbounded mem_Collect_eq not_le) by (metis B connected_component_trans cyz not_le) qed lemma not_outside_connected_component_le: fixes S :: "'a::euclidean_space set" assumes S: "bounded S" "2 \<le> DIM('a)" shows "- (outside S) = {x. \<forall>B. \<exists>y. B \<le> norm(y) \<and> \<not> connected_component (- S) x y}" apply (auto intro: less_imp_le simp: not_outside_connected_component_lt [OF assms]) by (meson gt_ex less_le_trans) lemma inside_connected_component_lt: fixes S :: "'a::euclidean_space set" assumes S: "bounded S" "2 \<le> DIM('a)" shows "inside S = {x. (x \<notin> S) \<and> (\<forall>B. \<exists>y. B < norm(y) \<and> \<not> connected_component (- S) x y)}" by (auto simp: inside_outside not_outside_connected_component_lt [OF assms]) lemma inside_connected_component_le: fixes S :: "'a::euclidean_space set" assumes S: "bounded S" "2 \<le> DIM('a)" shows "inside S = {x. (x \<notin> S) \<and> (\<forall>B. \<exists>y. B \<le> norm(y) \<and> \<not> connected_component (- S) x y)}" by (auto simp: inside_outside not_outside_connected_component_le [OF assms]) lemma inside_subset: assumes "connected U" and "\<not> bounded U" and "T \<union> U = - S" shows "inside S \<subseteq> T" using bounded_subset [of "connected_component_set (- S) _" U] assms by (metis (no_types, lifting) ComplI Un_iff connected_component_maximal inside_def mem_Collect_eq subsetI) lemma frontier_not_empty: fixes S :: "'a :: real_normed_vector set" shows "\<lbrakk>S \<noteq> {}; S \<noteq> UNIV\<rbrakk> \<Longrightarrow> frontier S \<noteq> {}" using connected_Int_frontier [of UNIV S] by auto lemma frontier_eq_empty: fixes S :: "'a :: real_normed_vector set" shows "frontier S = {} \<longleftrightarrow> S = {} \<or> S = UNIV" using frontier_UNIV frontier_empty frontier_not_empty by blast lemma frontier_of_connected_component_subset: fixes S :: "'a::real_normed_vector set" shows "frontier(connected_component_set S x) \<subseteq> frontier S" proof - { fix y assume y1: "y \<in> closure (connected_component_set S x)" and y2: "y \<notin> interior (connected_component_set S x)" have "y \<in> closure S" using y1 closure_mono connected_component_subset by blast moreover have "z \<in> interior (connected_component_set S x)" if "0 < e" "ball y e \<subseteq> interior S" "dist y z < e" for e z proof - have "ball y e \<subseteq> connected_component_set S y" using connected_component_maximal that interior_subset by (metis centre_in_ball connected_ball subset_trans) then show ?thesis using y1 apply (simp add: closure_approachable open_contains_ball_eq [OF open_interior]) by (metis connected_component_eq dist_commute mem_Collect_eq mem_ball mem_interior subsetD \<open>0 < e\<close> y2) qed then have "y \<notin> interior S" using y2 by (force simp: open_contains_ball_eq [OF open_interior]) ultimately have "y \<in> frontier S" by (auto simp: frontier_def) } then show ?thesis by (auto simp: frontier_def) qed lemma frontier_Union_subset_closure: fixes F :: "'a::real_normed_vector set set" shows "frontier(\<Union>F) \<subseteq> closure(\<Union>t \<in> F. frontier t)" proof - have "\<exists>y\<in>F. \<exists>y\<in>frontier y. dist y x < e" if "T \<in> F" "y \<in> T" "dist y x < e" "x \<notin> interior (\<Union>F)" "0 < e" for x y e T proof (cases "x \<in> T") case True with that show ?thesis by (metis Diff_iff Sup_upper closure_subset contra_subsetD dist_self frontier_def interior_mono) next case False have \<section>: "closed_segment x y \<inter> T \<noteq> {}" "closed_segment x y - T \<noteq> {}" using \<open>y \<in> T\<close> False by blast+ obtain c where "c \<in> closed_segment x y" "c \<in> frontier T" using False connected_Int_frontier [OF connected_segment \<section>] by auto with that show ?thesis by (smt (verit) dist_norm segment_bound1) qed then show ?thesis by (fastforce simp add: frontier_def closure_approachable) qed lemma frontier_Union_subset: fixes F :: "'a::real_normed_vector set set" shows "finite F \<Longrightarrow> frontier(\<Union>F) \<subseteq> (\<Union>t \<in> F. frontier t)" by (metis closed_UN closure_closed frontier_Union_subset_closure frontier_closed) lemma frontier_of_components_subset: fixes S :: "'a::real_normed_vector set" shows "C \<in> components S \<Longrightarrow> frontier C \<subseteq> frontier S" by (metis Path_Connected.frontier_of_connected_component_subset components_iff) lemma frontier_of_components_closed_complement: fixes S :: "'a::real_normed_vector set" shows "\<lbrakk>closed S; C \<in> components (- S)\<rbrakk> \<Longrightarrow> frontier C \<subseteq> S" using frontier_complement frontier_of_components_subset frontier_subset_eq by blast lemma frontier_minimal_separating_closed: fixes S :: "'a::real_normed_vector set" assumes "closed S" and nconn: "\<not> connected(- S)" and C: "C \<in> components (- S)" and conn: "\<And>T. \<lbrakk>closed T; T \<subset> S\<rbrakk> \<Longrightarrow> connected(- T)" shows "frontier C = S" proof (rule ccontr) assume "frontier C \<noteq> S" then have "frontier C \<subset> S" using frontier_of_components_closed_complement [OF \<open>closed S\<close> C] by blast then have "connected(- (frontier C))" by (simp add: conn) have "\<not> connected(- (frontier C))" unfolding connected_def not_not proof (intro exI conjI) show "open C" using C \<open>closed S\<close> open_components by blast show "open (- closure C)" by blast show "C \<inter> - closure C \<inter> - frontier C = {}" using closure_subset by blast show "C \<inter> - frontier C \<noteq> {}" using C \<open>open C\<close> components_eq frontier_disjoint_eq by fastforce show "- frontier C \<subseteq> C \<union> - closure C" by (simp add: \<open>open C\<close> closed_Compl frontier_closures) then show "- closure C \<inter> - frontier C \<noteq> {}" by (metis C Compl_Diff_eq Un_Int_eq(4) Un_commute \<open>frontier C \<subset> S\<close> \<open>open C\<close> compl_le_compl_iff frontier_def in_components_subset interior_eq leD sup_bot.right_neutral) qed then show False using \<open>connected (- frontier C)\<close> by blast qed lemma connected_component_UNIV [simp]: fixes x :: "'a::real_normed_vector" shows "connected_component_set UNIV x = UNIV" using connected_iff_eq_connected_component_set [of "UNIV::'a set"] connected_UNIV by auto lemma connected_component_eq_UNIV: fixes x :: "'a::real_normed_vector" shows "connected_component_set s x = UNIV \<longleftrightarrow> s = UNIV" using connected_component_in connected_component_UNIV by blast lemma components_UNIV [simp]: "components UNIV = {UNIV :: 'a::real_normed_vector set}" by (auto simp: components_eq_sing_iff) lemma interior_inside_frontier: fixes S :: "'a::real_normed_vector set" assumes "bounded S" shows "interior S \<subseteq> inside (frontier S)" proof - { fix x y assume x: "x \<in> interior S" and y: "y \<notin> S" and cc: "connected_component (- frontier S) x y" have "connected_component_set (- frontier S) x \<inter> frontier S \<noteq> {}" proof (rule connected_Int_frontier; simp add: set_eq_iff) show "\<exists>u. connected_component (- frontier S) x u \<and> u \<in> S" by (meson cc connected_component_in connected_component_refl_eq interior_subset subsetD x) show "\<exists>u. connected_component (- frontier S) x u \<and> u \<notin> S" using y cc by blast qed then have "bounded (connected_component_set (- frontier S) x)" using connected_component_in by auto } then show ?thesis using bounded_subset [OF assms] by (metis (no_types, lifting) Diff_iff frontier_def inside_def mem_Collect_eq subsetI) qed lemma inside_empty [simp]: "inside {} = ({} :: 'a :: {real_normed_vector, perfect_space} set)" by (simp add: inside_def) lemma outside_empty [simp]: "outside {} = (UNIV :: 'a :: {real_normed_vector, perfect_space} set)" using inside_empty inside_Un_outside by blast lemma inside_same_component: "\<lbrakk>connected_component (- S) x y; x \<in> inside S\<rbrakk> \<Longrightarrow> y \<in> inside S" using connected_component_eq connected_component_in by (fastforce simp add: inside_def) lemma outside_same_component: "\<lbrakk>connected_component (- S) x y; x \<in> outside S\<rbrakk> \<Longrightarrow> y \<in> outside S" using connected_component_eq connected_component_in by (fastforce simp add: outside_def) lemma convex_in_outside: fixes S :: "'a :: {real_normed_vector, perfect_space} set" assumes S: "convex S" and z: "z \<notin> S" shows "z \<in> outside S" proof (cases "S={}") case True then show ?thesis by simp next case False then obtain a where "a \<in> S" by blast with z have zna: "z \<noteq> a" by auto { assume "bounded (connected_component_set (- S) z)" with bounded_pos_less obtain B where "B>0" and B: "\<And>x. connected_component (- S) z x \<Longrightarrow> norm x < B" by (metis mem_Collect_eq) define C where "C = (B + 1 + norm z) / norm (z-a)" have "C > 0" using \<open>0 < B\<close> zna by (simp add: C_def field_split_simps add_strict_increasing) have "\<bar>norm (z + C *\<^sub>R (z-a)) - norm (C *\<^sub>R (z-a))\<bar> \<le> norm z" by (metis add_diff_cancel norm_triangle_ineq3) moreover have "norm (C *\<^sub>R (z-a)) > norm z + B" using zna \<open>B>0\<close> by (simp add: C_def le_max_iff_disj) ultimately have C: "norm (z + C *\<^sub>R (z-a)) > B" by linarith { fix u::real assume u: "0\<le>u" "u\<le>1" and ins: "(1 - u) *\<^sub>R z + u *\<^sub>R (z + C *\<^sub>R (z - a)) \<in> S" then have Cpos: "1 + u * C > 0" by (meson \<open>0 < C\<close> add_pos_nonneg less_eq_real_def zero_le_mult_iff zero_less_one) then have *: "(1 / (1 + u * C)) *\<^sub>R z + (u * C / (1 + u * C)) *\<^sub>R z = z" by (simp add: scaleR_add_left [symmetric] field_split_simps) then have False using convexD_alt [OF S \<open>a \<in> S\<close> ins, of "1/(u*C + 1)"] \<open>C>0\<close> \<open>z \<notin> S\<close> Cpos u by (simp add: * field_split_simps) } note contra = this have "connected_component (- S) z (z + C *\<^sub>R (z-a))" proof (rule connected_componentI [OF connected_segment]) show "closed_segment z (z + C *\<^sub>R (z - a)) \<subseteq> - S" using contra by (force simp add: closed_segment_def) qed auto then have False using zna B [of "z + C *\<^sub>R (z-a)"] C by (auto simp: field_split_simps max_mult_distrib_right) } then show ?thesis by (auto simp: outside_def z) qed lemma outside_convex: fixes S :: "'a :: {real_normed_vector, perfect_space} set" assumes "convex S" shows "outside S = - S" by (metis ComplD assms convex_in_outside equalityI inside_Un_outside subsetI sup.cobounded2) lemma outside_singleton [simp]: fixes x :: "'a :: {real_normed_vector, perfect_space}" shows "outside {x} = -{x}" by (auto simp: outside_convex) lemma inside_convex: fixes S :: "'a :: {real_normed_vector, perfect_space} set" shows "convex S \<Longrightarrow> inside S = {}" by (simp add: inside_outside outside_convex) lemma inside_singleton [simp]: fixes x :: "'a :: {real_normed_vector, perfect_space}" shows "inside {x} = {}" by (auto simp: inside_convex) lemma outside_subset_convex: fixes S :: "'a :: {real_normed_vector, perfect_space} set" shows "\<lbrakk>convex T; S \<subseteq> T\<rbrakk> \<Longrightarrow> - T \<subseteq> outside S" using outside_convex outside_mono by blast lemma outside_Un_outside_Un: fixes S :: "'a::real_normed_vector set" assumes "S \<inter> outside(T \<union> U) = {}" shows "outside(T \<union> U) \<subseteq> outside(T \<union> S)" proof fix x assume x: "x \<in> outside (T \<union> U)" have "Y \<subseteq> - S" if "connected Y" "Y \<subseteq> - T" "Y \<subseteq> - U" "x \<in> Y" "u \<in> Y" for u Y proof - have "Y \<subseteq> connected_component_set (- (T \<union> U)) x" by (simp add: connected_component_maximal that) also have "\<dots> \<subseteq> outside(T \<union> U)" by (metis (mono_tags, lifting) Collect_mono mem_Collect_eq outside outside_same_component x) finally have "Y \<subseteq> outside(T \<union> U)" . with assms show ?thesis by auto qed with x show "x \<in> outside (T \<union> S)" by (simp add: outside_connected_component_lt connected_component_def) meson qed lemma outside_frontier_misses_closure: fixes S :: "'a::real_normed_vector set" assumes "bounded S" shows "outside(frontier S) \<subseteq> - closure S" using assms frontier_def interior_inside_frontier outside_inside by fastforce lemma outside_frontier_eq_complement_closure: fixes S :: "'a :: {real_normed_vector, perfect_space} set" assumes "bounded S" "convex S" shows "outside(frontier S) = - closure S" by (metis Diff_subset assms convex_closure frontier_def outside_frontier_misses_closure outside_subset_convex subset_antisym) lemma inside_frontier_eq_interior: fixes S :: "'a :: {real_normed_vector, perfect_space} set" shows "\<lbrakk>bounded S; convex S\<rbrakk> \<Longrightarrow> inside(frontier S) = interior S" apply (simp add: inside_outside outside_frontier_eq_complement_closure) using closure_subset interior_subset apply (auto simp: frontier_def) done lemma open_inside: fixes S :: "'a::real_normed_vector set" assumes "closed S" shows "open (inside S)" proof - { fix x assume x: "x \<in> inside S" have "open (connected_component_set (- S) x)" using assms open_connected_component by blast then obtain e where e: "e>0" and e: "\<And>y. dist y x < e \<longrightarrow> connected_component (- S) x y" using dist_not_less_zero apply (simp add: open_dist) by (metis (no_types, lifting) Compl_iff connected_component_refl_eq inside_def mem_Collect_eq x) then have "\<exists>e>0. ball x e \<subseteq> inside S" by (metis e dist_commute inside_same_component mem_ball subsetI x) } then show ?thesis by (simp add: open_contains_ball) qed lemma open_outside: fixes S :: "'a::real_normed_vector set" assumes "closed S" shows "open (outside S)" proof - { fix x assume x: "x \<in> outside S" have "open (connected_component_set (- S) x)" using assms open_connected_component by blast then obtain e where e: "e>0" and e: "\<And>y. dist y x < e \<longrightarrow> connected_component (- S) x y" using dist_not_less_zero x by (auto simp add: open_dist outside_def intro: connected_component_refl) then have "\<exists>e>0. ball x e \<subseteq> outside S" by (metis e dist_commute outside_same_component mem_ball subsetI x) } then show ?thesis by (simp add: open_contains_ball) qed lemma closure_inside_subset: fixes S :: "'a::real_normed_vector set" assumes "closed S" shows "closure(inside S) \<subseteq> S \<union> inside S" by (metis assms closure_minimal open_closed open_outside sup.cobounded2 union_with_inside) lemma frontier_inside_subset: fixes S :: "'a::real_normed_vector set" assumes "closed S" shows "frontier(inside S) \<subseteq> S" using assms closure_inside_subset frontier_closures frontier_disjoint_eq open_inside by fastforce lemma closure_outside_subset: fixes S :: "'a::real_normed_vector set" assumes "closed S" shows "closure(outside S) \<subseteq> S \<union> outside S" by (metis assms closed_open closure_minimal inside_outside open_inside sup_ge2) lemma closed_path_image_Un_inside: fixes g :: "real \<Rightarrow> 'a :: real_normed_vector" assumes "path g" shows "closed (path_image g \<union> inside (path_image g))" by (simp add: assms closed_Compl closed_path_image open_outside union_with_inside) lemma frontier_outside_subset: fixes S :: "'a::real_normed_vector set" assumes "closed S" shows "frontier(outside S) \<subseteq> S" unfolding frontier_def by (metis Diff_subset_conv assms closure_outside_subset interior_eq open_outside sup_aci(1)) lemma inside_complement_unbounded_connected_empty: "\<lbrakk>connected (- S); \<not> bounded (- S)\<rbrakk> \<Longrightarrow> inside S = {}" using inside_subset by blast lemma inside_bounded_complement_connected_empty: fixes S :: "'a::{real_normed_vector, perfect_space} set" shows "\<lbrakk>connected (- S); bounded S\<rbrakk> \<Longrightarrow> inside S = {}" by (metis inside_complement_unbounded_connected_empty cobounded_imp_unbounded) lemma inside_inside: assumes "S \<subseteq> inside T" shows "inside S - T \<subseteq> inside T" unfolding inside_def proof clarify fix x assume x: "x \<notin> T" "x \<notin> S" and bo: "bounded (connected_component_set (- S) x)" show "bounded (connected_component_set (- T) x)" proof (cases "S \<inter> connected_component_set (- T) x = {}") case True then show ?thesis by (metis bounded_subset [OF bo] compl_le_compl_iff connected_component_idemp connected_component_mono disjoint_eq_subset_Compl double_compl) next case False then obtain y where y: "y \<in> S" "y \<in> connected_component_set (- T) x" by (meson disjoint_iff) then have "bounded (connected_component_set (- T) y)" using assms [unfolded inside_def] by blast with y show ?thesis by (metis connected_component_eq) qed qed lemma inside_inside_subset: "inside(inside S) \<subseteq> S" using inside_inside union_with_outside by fastforce lemma inside_outside_intersect_connected: "\<lbrakk>connected T; inside S \<inter> T \<noteq> {}; outside S \<inter> T \<noteq> {}\<rbrakk> \<Longrightarrow> S \<inter> T \<noteq> {}" apply (simp add: inside_def outside_def ex_in_conv [symmetric] disjoint_eq_subset_Compl, clarify) by (metis (no_types, opaque_lifting) Compl_anti_mono connected_component_eq connected_component_maximal contra_subsetD double_compl) lemma outside_bounded_nonempty: fixes S :: "'a :: {real_normed_vector, perfect_space} set" assumes "bounded S" shows "outside S \<noteq> {}" using assms unbounded_outside by force lemma outside_compact_in_open: fixes S :: "'a :: {real_normed_vector,perfect_space} set" assumes S: "compact S" and T: "open T" and "S \<subseteq> T" "T \<noteq> {}" shows "outside S \<inter> T \<noteq> {}" proof - have "outside S \<noteq> {}" by (simp add: compact_imp_bounded outside_bounded_nonempty S) with assms obtain a b where a: "a \<in> outside S" and b: "b \<in> T" by auto show ?thesis proof (cases "a \<in> T") case True with a show ?thesis by blast next case False have front: "frontier T \<subseteq> - S" using \<open>S \<subseteq> T\<close> frontier_disjoint_eq T by auto { fix \<gamma> assume "path \<gamma>" and pimg_sbs: "path_image \<gamma> - {pathfinish \<gamma>} \<subseteq> interior (- T)" and pf: "pathfinish \<gamma> \<in> frontier T" and ps: "pathstart \<gamma> = a" define c where "c = pathfinish \<gamma>" have "c \<in> -S" unfolding c_def using front pf by blast moreover have "open (-S)" using S compact_imp_closed by blast ultimately obtain \<epsilon>::real where "\<epsilon> > 0" and \<epsilon>: "cball c \<epsilon> \<subseteq> -S" using open_contains_cball[of "-S"] S by blast then obtain d where "d \<in> T" and d: "dist d c < \<epsilon>" using closure_approachable [of c T] pf unfolding c_def by (metis Diff_iff frontier_def) then have "d \<in> -S" using \<epsilon> using dist_commute by (metis contra_subsetD mem_cball not_le not_less_iff_gr_or_eq) have pimg_sbs_cos: "path_image \<gamma> \<subseteq> -S" using \<open>c \<in> - S\<close> \<open>S \<subseteq> T\<close> c_def interior_subset pimg_sbs by fastforce have "closed_segment c d \<le> cball c \<epsilon>" by (metis \<open>0 < \<epsilon>\<close> centre_in_cball closed_segment_subset convex_cball d dist_commute less_eq_real_def mem_cball) with \<epsilon> have "closed_segment c d \<subseteq> -S" by blast moreover have con_gcd: "connected (path_image \<gamma> \<union> closed_segment c d)" by (rule connected_Un) (auto simp: c_def \<open>path \<gamma>\<close> connected_path_image) ultimately have "connected_component (- S) a d" unfolding connected_component_def using pimg_sbs_cos ps by blast then have "outside S \<inter> T \<noteq> {}" using outside_same_component [OF _ a] by (metis IntI \<open>d \<in> T\<close> empty_iff) } note * = this have pal: "pathstart (linepath a b) \<in> closure (- T)" by (auto simp: False closure_def) show ?thesis by (rule exists_path_subpath_to_frontier [OF path_linepath pal _ *]) (auto simp: b) qed qed lemma inside_inside_compact_connected: fixes S :: "'a :: euclidean_space set" assumes S: "closed S" and T: "compact T" and "connected T" "S \<subseteq> inside T" shows "inside S \<subseteq> inside T" proof (cases "inside T = {}") case True with assms show ?thesis by auto next case False consider "DIM('a) = 1" | "DIM('a) \<ge> 2" using antisym not_less_eq_eq by fastforce then show ?thesis proof cases case 1 then show ?thesis using connected_convex_1_gen assms False inside_convex by blast next case 2 have "bounded S" using assms by (meson bounded_inside bounded_subset compact_imp_bounded) then have coms: "compact S" by (simp add: S compact_eq_bounded_closed) then have bst: "bounded (S \<union> T)" by (simp add: compact_imp_bounded T) then obtain r where "0 < r" and r: "S \<union> T \<subseteq> ball 0 r" using bounded_subset_ballD by blast have outst: "outside S \<inter> outside T \<noteq> {}" by (metis bounded_Un bounded_subset bst cobounded_outside disjoint_eq_subset_Compl unbounded_outside) have "S \<inter> T = {}" using assms by (metis disjoint_iff_not_equal inside_no_overlap subsetCE) moreover have "outside S \<inter> inside T \<noteq> {}" by (meson False assms(4) compact_eq_bounded_closed coms open_inside outside_compact_in_open T) ultimately have "inside S \<inter> T = {}" using inside_outside_intersect_connected [OF \<open>connected T\<close>, of S] by (metis "2" compact_eq_bounded_closed coms connected_outside inf.commute inside_outside_intersect_connected outst) then show ?thesis using inside_inside [OF \<open>S \<subseteq> inside T\<close>] by blast qed qed lemma connected_with_inside: fixes S :: "'a :: real_normed_vector set" assumes S: "closed S" and cons: "connected S" shows "connected(S \<union> inside S)" proof (cases "S \<union> inside S = UNIV") case True with assms show ?thesis by auto next case False then obtain b where b: "b \<notin> S" "b \<notin> inside S" by blast have *: "\<exists>y T. y \<in> S \<and> connected T \<and> a \<in> T \<and> y \<in> T \<and> T \<subseteq> (S \<union> inside S)" if "a \<in> S \<union> inside S" for a using that proof assume "a \<in> S" then show ?thesis using cons by blast next assume a: "a \<in> inside S" then have ain: "a \<in> closure (inside S)" by (simp add: closure_def) obtain h where h: "path h" "pathstart h = a" "path_image h - {pathfinish h} \<subseteq> interior (inside S)" "pathfinish h \<in> frontier (inside S)" using ain b by (metis exists_path_subpath_to_frontier path_linepath pathfinish_linepath pathstart_linepath) moreover have h1S: "pathfinish h \<in> S" using S h frontier_inside_subset by blast moreover have "path_image h \<subseteq> S \<union> inside S" using IntD1 S h1S h interior_eq open_inside by fastforce ultimately show ?thesis by blast qed show ?thesis apply (simp add: connected_iff_connected_component) apply (clarsimp simp add: connected_component_def dest!: *) subgoal for x y u u' T t' by (rule_tac x = "S \<union> T \<union> t'" in exI) (auto intro!: connected_Un cons) done qed text\<open>The proof is virtually the same as that above.\<close> lemma connected_with_outside: fixes S :: "'a :: real_normed_vector set" assumes S: "closed S" and cons: "connected S" shows "connected(S \<union> outside S)" proof (cases "S \<union> outside S = UNIV") case True with assms show ?thesis by auto next case False then obtain b where b: "b \<notin> S" "b \<notin> outside S" by blast have *: "\<exists>y T. y \<in> S \<and> connected T \<and> a \<in> T \<and> y \<in> T \<and> T \<subseteq> (S \<union> outside S)" if "a \<in> (S \<union> outside S)" for a using that proof assume "a \<in> S" then show ?thesis by (rule_tac x=a in exI, rule_tac x="{a}" in exI, simp) next assume a: "a \<in> outside S" then have ain: "a \<in> closure (outside S)" by (simp add: closure_def) obtain h where h: "path h" "pathstart h = a" "path_image h - {pathfinish h} \<subseteq> interior (outside S)" "pathfinish h \<in> frontier (outside S)" using ain b by (metis exists_path_subpath_to_frontier path_linepath pathfinish_linepath pathstart_linepath) moreover have h1S: "pathfinish h \<in> S" using S frontier_outside_subset h(4) by blast moreover have "path_image h \<subseteq> S \<union> outside S" using IntD1 S h1S h interior_eq open_outside by fastforce ultimately show ?thesis by blast qed show ?thesis apply (simp add: connected_iff_connected_component) apply (clarsimp simp add: connected_component_def dest!: *) subgoal for x y u u' T t' by (rule_tac x="(S \<union> T \<union> t')" in exI) (auto intro!: connected_Un cons) done qed lemma inside_inside_eq_empty [simp]: fixes S :: "'a :: {real_normed_vector, perfect_space} set" assumes S: "closed S" and cons: "connected S" shows "inside (inside S) = {}" proof - have "connected (- inside S)" by (metis S connected_with_outside cons union_with_outside) then show ?thesis by (metis bounded_Un inside_complement_unbounded_connected_empty unbounded_outside union_with_outside) qed lemma inside_in_components: "inside S \<in> components (- S) \<longleftrightarrow> connected(inside S) \<and> inside S \<noteq> {}" (is "?lhs = ?rhs") proof assume R: ?rhs then have "\<And>x. \<lbrakk>x \<in> S; x \<in> inside S\<rbrakk> \<Longrightarrow> \<not> connected (inside S)" by (simp add: inside_outside) with R show ?lhs unfolding in_components_maximal by (auto intro: inside_same_component connected_componentI) qed (simp add: in_components_maximal) text\<open>The proof is like that above.\<close> lemma outside_in_components: "outside S \<in> components (- S) \<longleftrightarrow> connected(outside S) \<and> outside S \<noteq> {}" (is "?lhs = ?rhs") proof assume R: ?rhs then have "\<And>x. \<lbrakk>x \<in> S; x \<in> outside S\<rbrakk> \<Longrightarrow> \<not> connected (outside S)" by (meson disjoint_iff outside_no_overlap) with R show ?lhs unfolding in_components_maximal by (auto intro: outside_same_component connected_componentI) qed (simp add: in_components_maximal) lemma bounded_unique_outside: fixes S :: "'a :: euclidean_space set" assumes "bounded S" "DIM('a) \<ge> 2" shows "(c \<in> components (- S) \<and> \<not> bounded c) \<longleftrightarrow> c = outside S" using assms by (metis cobounded_unique_unbounded_components connected_outside double_compl outside_bounded_nonempty outside_in_components unbounded_outside) subsection\<open>Condition for an open map's image to contain a ball\<close> proposition ball_subset_open_map_image: fixes f :: "'a::heine_borel \<Rightarrow> 'b :: {real_normed_vector,heine_borel}" assumes contf: "continuous_on (closure S) f" and oint: "open (f ` interior S)" and le_no: "\<And>z. z \<in> frontier S \<Longrightarrow> r \<le> norm(f z - f a)" and "bounded S" "a \<in> S" "0 < r" shows "ball (f a) r \<subseteq> f ` S" proof (cases "f ` S = UNIV") case True then show ?thesis by simp next case False then have "closed (frontier (f ` S))" "frontier (f ` S) \<noteq> {}" using \<open>a \<in> S\<close> by (auto simp: frontier_eq_empty) then obtain w where w: "w \<in> frontier (f ` S)" and dw_le: "\<And>y. y \<in> frontier (f ` S) \<Longrightarrow> norm (f a - w) \<le> norm (f a - y)" by (auto simp add: dist_norm intro: distance_attains_inf [of "frontier(f ` S)" "f a"]) then obtain \<xi> where \<xi>: "\<And>n. \<xi> n \<in> f ` S" and tendsw: "\<xi> \<longlonglongrightarrow> w" by (metis Diff_iff frontier_def closure_sequential) then have "\<And>n. \<exists>x \<in> S. \<xi> n = f x" by force then obtain z where zs: "\<And>n. z n \<in> S" and fz: "\<And>n. \<xi> n = f (z n)" by metis then obtain y K where y: "y \<in> closure S" and "strict_mono (K :: nat \<Rightarrow> nat)" and Klim: "(z \<circ> K) \<longlonglongrightarrow> y" using \<open>bounded S\<close> unfolding compact_closure [symmetric] compact_def by (meson closure_subset subset_iff) then have ftendsw: "((\<lambda>n. f (z n)) \<circ> K) \<longlonglongrightarrow> w" by (metis LIMSEQ_subseq_LIMSEQ fun.map_cong0 fz tendsw) have zKs: "\<And>n. (z \<circ> K) n \<in> S" by (simp add: zs) have fz: "f \<circ> z = \<xi>" "(\<lambda>n. f (z n)) = \<xi>" using fz by auto then have "(\<xi> \<circ> K) \<longlonglongrightarrow> f y" by (metis (no_types) Klim zKs y contf comp_assoc continuous_on_closure_sequentially) with fz have wy: "w = f y" using fz LIMSEQ_unique ftendsw by auto have "r \<le> norm (f y - f a)" proof (rule le_no) show "y \<in> frontier S" using w wy oint by (force simp: imageI image_mono interiorI interior_subset frontier_def y) qed then have "\<And>y. \<lbrakk>norm (f a - y) < r; y \<in> frontier (f ` S)\<rbrakk> \<Longrightarrow> False" by (metis dw_le norm_minus_commute not_less order_trans wy) then have "ball (f a) r \<inter> frontier (f ` S) = {}" by (metis disjoint_iff_not_equal dist_norm mem_ball) moreover have "ball (f a) r \<inter> f ` S \<noteq> {}" using \<open>a \<in> S\<close> \<open>0 < r\<close> centre_in_ball by blast ultimately show ?thesis by (meson connected_Int_frontier connected_ball diff_shunt_var) qed subsubsection\<open>Special characterizations of classes of functions into and out of R.\<close> lemma Hausdorff_space_euclidean [simp]: "Hausdorff_space (euclidean :: 'a::metric_space topology)" proof - have "\<exists>U V. open U \<and> open V \<and> x \<in> U \<and> y \<in> V \<and> disjnt U V" if "x \<noteq> y" for x y :: 'a proof (intro exI conjI) let ?r = "dist x y / 2" have [simp]: "?r > 0" by (simp add: that) show "open (ball x ?r)" "open (ball y ?r)" "x \<in> (ball x ?r)" "y \<in> (ball y ?r)" by (auto simp add: that) show "disjnt (ball x ?r) (ball y ?r)" unfolding disjnt_def by (simp add: disjoint_ballI) qed then show ?thesis by (simp add: Hausdorff_space_def) qed proposition embedding_map_into_euclideanreal: assumes "path_connected_space X" shows "embedding_map X euclideanreal f \<longleftrightarrow> continuous_map X euclideanreal f \<and> inj_on f (topspace X)" proof safe show "continuous_map X euclideanreal f" if "embedding_map X euclideanreal f" using continuous_map_in_subtopology homeomorphic_imp_continuous_map that unfolding embedding_map_def by blast show "inj_on f (topspace X)" if "embedding_map X euclideanreal f" using that homeomorphic_imp_injective_map unfolding embedding_map_def by blast show "embedding_map X euclideanreal f" if cont: "continuous_map X euclideanreal f" and inj: "inj_on f (topspace X)" proof - obtain g where gf: "\<And>x. x \<in> topspace X \<Longrightarrow> g (f x) = x" using inv_into_f_f [OF inj] by auto show ?thesis unfolding embedding_map_def homeomorphic_map_maps homeomorphic_maps_def proof (intro exI conjI) show "continuous_map X (top_of_set (f ` topspace X)) f" by (simp add: cont continuous_map_in_subtopology) let ?S = "f ` topspace X" have eq: "{x \<in> ?S. g x \<in> U} = f ` U" if "openin X U" for U using openin_subset [OF that] by (auto simp: gf) have 1: "g ` ?S \<subseteq> topspace X" using eq by blast have "openin (top_of_set ?S) {x \<in> ?S. g x \<in> T}" if "openin X T" for T proof - have "T \<subseteq> topspace X" by (simp add: openin_subset that) have RR: "\<forall>x \<in> ?S \<inter> g -` T. \<exists>d>0. \<forall>x' \<in> ?S \<inter> ball x d. g x' \<in> T" proof (clarsimp simp add: gf) have pcS: "path_connectedin euclidean ?S" using assms cont path_connectedin_continuous_map_image path_connectedin_topspace by blast show "\<exists>d>0. \<forall>x'\<in>f ` topspace X \<inter> ball (f x) d. g x' \<in> T" if "x \<in> T" for x proof - have x: "x \<in> topspace X" using \<open>T \<subseteq> topspace X\<close> \<open>x \<in> T\<close> by blast obtain u v d where "0 < d" "u \<in> topspace X" "v \<in> topspace X" and sub_fuv: "?S \<inter> {f x - d .. f x + d} \<subseteq> {f u..f v}" proof (cases "\<exists>u \<in> topspace X. f u < f x") case True then obtain u where u: "u \<in> topspace X" "f u < f x" .. show ?thesis proof (cases "\<exists>v \<in> topspace X. f x < f v") case True then obtain v where v: "v \<in> topspace X" "f x < f v" .. show ?thesis proof let ?d = "min (f x - f u) (f v - f x)" show "0 < ?d" by (simp add: \<open>f u < f x\<close> \<open>f x < f v\<close>) show "f ` topspace X \<inter> {f x - ?d..f x + ?d} \<subseteq> {f u..f v}" by fastforce qed (auto simp: u v) next case False show ?thesis proof let ?d = "f x - f u" show "0 < ?d" by (simp add: u) show "f ` topspace X \<inter> {f x - ?d..f x + ?d} \<subseteq> {f u..f x}" using x u False by auto qed (auto simp: x u) qed next case False note no_u = False show ?thesis proof (cases "\<exists>v \<in> topspace X. f x < f v") case True then obtain v where v: "v \<in> topspace X" "f x < f v" .. show ?thesis proof let ?d = "f v - f x" show "0 < ?d" by (simp add: v) show "f ` topspace X \<inter> {f x - ?d..f x + ?d} \<subseteq> {f x..f v}" using False by auto qed (auto simp: x v) next case False show ?thesis proof show "f ` topspace X \<inter> {f x - 1..f x + 1} \<subseteq> {f x..f x}" using False no_u by fastforce qed (auto simp: x) qed qed then obtain h where "pathin X h" "h 0 = u" "h 1 = v" using assms unfolding path_connected_space_def by blast obtain C where "compactin X C" "connectedin X C" "u \<in> C" "v \<in> C" proof show "compactin X (h ` {0..1})" using that by (simp add: \<open>pathin X h\<close> compactin_path_image) show "connectedin X (h ` {0..1})" using \<open>pathin X h\<close> connectedin_path_image by blast qed (use \<open>h 0 = u\<close> \<open>h 1 = v\<close> in auto) have "continuous_map (subtopology euclideanreal (?S \<inter> {f x - d .. f x + d})) (subtopology X C) g" proof (rule continuous_inverse_map) show "compact_space (subtopology X C)" using \<open>compactin X C\<close> compactin_subspace by blast show "continuous_map (subtopology X C) euclideanreal f" by (simp add: cont continuous_map_from_subtopology) have "{f u .. f v} \<subseteq> f ` topspace (subtopology X C)" proof (rule connected_contains_Icc) show "connected (f ` topspace (subtopology X C))" using connectedin_continuous_map_image [OF cont] by (simp add: \<open>compactin X C\<close> \<open>connectedin X C\<close> compactin_subset_topspace inf_absorb2) show "f u \<in> f ` topspace (subtopology X C)" by (simp add: \<open>u \<in> C\<close> \<open>u \<in> topspace X\<close>) show "f v \<in> f ` topspace (subtopology X C)" by (simp add: \<open>v \<in> C\<close> \<open>v \<in> topspace X\<close>) qed then show "f ` topspace X \<inter> {f x - d..f x + d} \<subseteq> f ` topspace (subtopology X C)" using sub_fuv by blast qed (auto simp: gf) then have contg: "continuous_map (subtopology euclideanreal (?S \<inter> {f x - d .. f x + d})) X g" using continuous_map_in_subtopology by blast have "\<exists>e>0. \<forall>x \<in> ?S \<inter> {f x - d .. f x + d} \<inter> ball (f x) e. g x \<in> T" using openin_continuous_map_preimage [OF contg \<open>openin X T\<close>] x \<open>x \<in> T\<close> \<open>0 < d\<close> unfolding openin_euclidean_subtopology_iff by (force simp: gf dist_commute) then obtain e where "e > 0 \<and> (\<forall>x\<in>f ` topspace X \<inter> {f x - d..f x + d} \<inter> ball (f x) e. g x \<in> T)" by metis with \<open>0 < d\<close> have "min d e > 0" "\<forall>u. u \<in> topspace X \<longrightarrow> \<bar>f x - f u\<bar> < min d e \<longrightarrow> u \<in> T" using dist_real_def gf by force+ then show ?thesis by (metis (full_types) Int_iff dist_real_def image_iff mem_ball gf) qed qed then obtain d where d: "\<And>r. r \<in> ?S \<inter> g -` T \<Longrightarrow> d r > 0 \<and> (\<forall>x \<in> ?S \<inter> ball r (d r). g x \<in> T)" by metis show ?thesis unfolding openin_subtopology proof (intro exI conjI) show "{x \<in> ?S. g x \<in> T} = (\<Union>r \<in> ?S \<inter> g -` T. ball r (d r)) \<inter> f ` topspace X" using d by (auto simp: gf) qed auto qed then show "continuous_map (top_of_set ?S) X g" by (simp add: continuous_map_def gf) qed (auto simp: gf) qed qed subsubsection \<open>An injective function into R is a homeomorphism and so an open map.\<close> lemma injective_into_1d_eq_homeomorphism: fixes f :: "'a::topological_space \<Rightarrow> real" assumes f: "continuous_on S f" and S: "path_connected S" shows "inj_on f S \<longleftrightarrow> (\<exists>g. homeomorphism S (f ` S) f g)" proof show "\<exists>g. homeomorphism S (f ` S) f g" if "inj_on f S" proof - have "embedding_map (top_of_set S) euclideanreal f" using that embedding_map_into_euclideanreal [of "top_of_set S" f] assms by auto then show ?thesis by (simp add: embedding_map_def) (metis all_closedin_homeomorphic_image f homeomorphism_injective_closed_map that) qed qed (metis homeomorphism_def inj_onI) lemma injective_into_1d_imp_open_map: fixes f :: "'a::topological_space \<Rightarrow> real" assumes "continuous_on S f" "path_connected S" "inj_on f S" "openin (subtopology euclidean S) T" shows "openin (subtopology euclidean (f ` S)) (f ` T)" using assms homeomorphism_imp_open_map injective_into_1d_eq_homeomorphism by blast lemma homeomorphism_into_1d: fixes f :: "'a::topological_space \<Rightarrow> real" assumes "path_connected S" "continuous_on S f" "f ` S = T" "inj_on f S" shows "\<exists>g. homeomorphism S T f g" using assms injective_into_1d_eq_homeomorphism by blast subsection\<^marker>\<open>tag unimportant\<close> \<open>Rectangular paths\<close> definition\<^marker>\<open>tag unimportant\<close> rectpath where "rectpath a1 a3 = (let a2 = Complex (Re a3) (Im a1); a4 = Complex (Re a1) (Im a3) in linepath a1 a2 +++ linepath a2 a3 +++ linepath a3 a4 +++ linepath a4 a1)" lemma path_rectpath [simp, intro]: "path (rectpath a b)" by (simp add: Let_def rectpath_def) lemma pathstart_rectpath [simp]: "pathstart (rectpath a1 a3) = a1" by (simp add: rectpath_def Let_def) lemma pathfinish_rectpath [simp]: "pathfinish (rectpath a1 a3) = a1" by (simp add: rectpath_def Let_def) lemma simple_path_rectpath [simp, intro]: assumes "Re a1 \<noteq> Re a3" "Im a1 \<noteq> Im a3" shows "simple_path (rectpath a1 a3)" unfolding rectpath_def Let_def using assms by (intro simple_path_join_loop arc_join arc_linepath) (auto simp: complex_eq_iff path_image_join closed_segment_same_Re closed_segment_same_Im) lemma path_image_rectpath: assumes "Re a1 \<le> Re a3" "Im a1 \<le> Im a3" shows "path_image (rectpath a1 a3) = {z. Re z \<in> {Re a1, Re a3} \<and> Im z \<in> {Im a1..Im a3}} \<union> {z. Im z \<in> {Im a1, Im a3} \<and> Re z \<in> {Re a1..Re a3}}" (is "?lhs = ?rhs") proof - define a2 a4 where "a2 = Complex (Re a3) (Im a1)" and "a4 = Complex (Re a1) (Im a3)" have "?lhs = closed_segment a1 a2 \<union> closed_segment a2 a3 \<union> closed_segment a4 a3 \<union> closed_segment a1 a4" by (simp_all add: rectpath_def Let_def path_image_join closed_segment_commute a2_def a4_def Un_assoc) also have "\<dots> = ?rhs" using assms by (auto simp: rectpath_def Let_def path_image_join a2_def a4_def closed_segment_same_Re closed_segment_same_Im closed_segment_eq_real_ivl) finally show ?thesis . qed lemma path_image_rectpath_subset_cbox: assumes "Re a \<le> Re b" "Im a \<le> Im b" shows "path_image (rectpath a b) \<subseteq> cbox a b" using assms by (auto simp: path_image_rectpath in_cbox_complex_iff) lemma path_image_rectpath_inter_box: assumes "Re a \<le> Re b" "Im a \<le> Im b" shows "path_image (rectpath a b) \<inter> box a b = {}" using assms by (auto simp: path_image_rectpath in_box_complex_iff) lemma path_image_rectpath_cbox_minus_box: assumes "Re a \<le> Re b" "Im a \<le> Im b" shows "path_image (rectpath a b) = cbox a b - box a b" using assms by (auto simp: path_image_rectpath in_cbox_complex_iff in_box_complex_iff) end
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.limits.shapes.pullbacks import Mathlib.category_theory.limits.shapes.equalizers import Mathlib.category_theory.limits.preserves.basic import Mathlib.category_theory.is_connected import Mathlib.PostPort universes v₁ u_1 u₂ v₂ namespace Mathlib /-! # Connected limits A connected limit is a limit whose shape is a connected category. We give examples of connected categories, and prove that the functor given by `(X × -)` preserves any connected limit. That is, any limit of shape `J` where `J` is a connected category is preserved by the functor `(X × -)`. -/ namespace category_theory protected instance wide_pullback_shape_connected (J : Type v₁) : is_connected (limits.wide_pullback_shape J) := is_connected.of_induct fun (p : set (limits.wide_pullback_shape J)) (hp : none ∈ p) (t : ∀ {j₁ j₂ : limits.wide_pullback_shape J}, (j₁ ⟶ j₂) → (j₁ ∈ p ↔ j₂ ∈ p)) (j : limits.wide_pullback_shape J) => option.cases_on j hp fun (j : J) => eq.mpr (id (Eq._oldrec (Eq.refl (some j ∈ p)) (propext (t (limits.wide_pullback_shape.hom.term j))))) hp protected instance wide_pushout_shape_connected (J : Type v₁) : is_connected (limits.wide_pushout_shape J) := is_connected.of_induct fun (p : set (limits.wide_pushout_shape J)) (hp : none ∈ p) (t : ∀ {j₁ j₂ : limits.wide_pushout_shape J}, (j₁ ⟶ j₂) → (j₁ ∈ p ↔ j₂ ∈ p)) (j : limits.wide_pushout_shape J) => option.cases_on j hp fun (j : J) => eq.mpr (id (Eq._oldrec (Eq.refl (some j ∈ p)) (Eq.symm (propext (t (limits.wide_pushout_shape.hom.init j)))))) hp protected instance parallel_pair_inhabited : Inhabited limits.walking_parallel_pair := { default := limits.walking_parallel_pair.one } protected instance parallel_pair_connected : is_connected limits.walking_parallel_pair := is_connected.of_induct fun (p : set limits.walking_parallel_pair) (ᾰ : limits.walking_parallel_pair.one ∈ p) (t : ∀ {j₁ j₂ : limits.walking_parallel_pair}, (j₁ ⟶ j₂) → (j₁ ∈ p ↔ j₂ ∈ p)) (j : limits.walking_parallel_pair) => limits.walking_parallel_pair.cases_on j (eq.mpr (id (Eq._oldrec (Eq.refl (limits.walking_parallel_pair.zero ∈ p)) (propext (t limits.walking_parallel_pair_hom.left)))) ᾰ) ᾰ namespace prod_preserves_connected_limits /-- (Impl). The obvious natural transformation from (X × K -) to K. -/ def γ₂ {C : Type u₂} [category C] [limits.has_binary_products C] {J : Type v₂} [small_category J] {K : J ⥤ C} (X : C) : K ⋙ functor.obj limits.prod.functor X ⟶ K := nat_trans.mk fun (Y : J) => limits.prod.snd /-- (Impl). The obvious natural transformation from (X × K -) to X -/ @[simp] theorem γ₁_app {C : Type u₂} [category C] [limits.has_binary_products C] {J : Type v₂} [small_category J] {K : J ⥤ C} (X : C) (Y : J) : nat_trans.app (γ₁ X) Y = limits.prod.fst := Eq.refl (nat_trans.app (γ₁ X) Y) /-- (Impl). Given a cone for (X × K -), produce a cone for K using the natural transformation `γ₂` -/ @[simp] theorem forget_cone_π {C : Type u₂} [category C] [limits.has_binary_products C] {J : Type v₂} [small_category J] {X : C} {K : J ⥤ C} (s : limits.cone (K ⋙ functor.obj limits.prod.functor X)) : limits.cone.π (forget_cone s) = limits.cone.π s ≫ γ₂ X := Eq.refl (limits.cone.π (forget_cone s)) end prod_preserves_connected_limits /-- The functor `(X × -)` preserves any connected limit. Note that this functor does not preserve the two most obvious disconnected limits - that is, `(X × -)` does not preserve products or terminal object, eg `(X ⨯ A) ⨯ (X ⨯ B)` is not isomorphic to `X ⨯ (A ⨯ B)` and `X ⨯ 1` is not isomorphic to `1`. -/ def prod_preserves_connected_limits {C : Type u₂} [category C] [limits.has_binary_products C] {J : Type v₂} [small_category J] [is_connected J] (X : C) : limits.preserves_limits_of_shape J (functor.obj limits.prod.functor X) := limits.preserves_limits_of_shape.mk fun (K : J ⥤ C) => limits.preserves_limit.mk fun (c : limits.cone K) (l : limits.is_limit c) => limits.is_limit.mk fun (s : limits.cone (K ⋙ functor.obj limits.prod.functor X)) => limits.prod.lift (nat_trans.app (limits.cone.π s) (classical.arbitrary J) ≫ limits.prod.fst) (limits.is_limit.lift l sorry)
#pragma once #include "PreConfig.h" #ifdef CRU_PLATFORM_WINDOWS #ifdef CRU_BASE_EXPORT_API #define CRU_BASE_API __declspec(dllexport) #else #define CRU_BASE_API __declspec(dllimport) #endif #else #define CRU_BASE_API #endif #include <gsl/gsl> #define CRU_UNUSED(entity) static_cast<void>(entity); #define CRU__CONCAT(a, b) a##b #define CRU_MAKE_UNICODE_LITERAL(str) CRU__CONCAT(u, #str) #define CRU_DEFAULT_COPY(classname) \ classname(const classname&) = default; \ classname& operator=(const classname&) = default; #define CRU_DEFAULT_MOVE(classname) \ classname(classname&&) = default; \ classname& operator=(classname&&) = default; #define CRU_DELETE_COPY(classname) \ classname(const classname&) = delete; \ classname& operator=(const classname&) = delete; #define CRU_DELETE_MOVE(classname) \ classname(classname&&) = delete; \ classname& operator=(classname&&) = delete; #define CRU_DEFAULT_DESTRUCTOR(classname) ~classname() = default; #define CRU_DEFAULT_CONSTRUCTOR_DESTRUCTOR(classname) \ classname() = default; \ ~classname() = default; #define CRU_DEFINE_COMPARE_OPERATORS(classname) \ inline bool operator==(const classname& left, const classname& right) { \ return left.Compare(right) == 0; \ } \ \ inline bool operator!=(const classname& left, const classname& right) { \ return left.Compare(right) != 0; \ } \ \ inline bool operator<(const classname& left, const classname& right) { \ return left.Compare(right) < 0; \ } \ \ inline bool operator<=(const classname& left, const classname& right) { \ return left.Compare(right) <= 0; \ } \ \ inline bool operator>(const classname& left, const classname& right) { \ return left.Compare(right) > 0; \ } \ \ inline bool operator>=(const classname& left, const classname& right) { \ return left.Compare(right) >= 0; \ } namespace cru { class CRU_BASE_API Object { public: Object() = default; CRU_DEFAULT_COPY(Object) CRU_DEFAULT_MOVE(Object) virtual ~Object() = default; }; struct CRU_BASE_API Interface { Interface() = default; CRU_DELETE_COPY(Interface) CRU_DELETE_MOVE(Interface) virtual ~Interface() = default; }; [[noreturn]] void CRU_BASE_API UnreachableCode(); using Index = gsl::index; // https://www.boost.org/doc/libs/1_54_0/doc/html/hash/reference.html#boost.hash_combine template <class T> inline void hash_combine(std::size_t& s, const T& v) { std::hash<T> h; s ^= h(v) + 0x9e3779b9 + (s << 6) + (s >> 2); } #define CRU_DEFINE_CLASS_LOG_TAG(tag) \ private: \ constexpr static const char16_t* kLogTag = tag; } // namespace cru
/- Copyright (c) 2021 Bhavik Mehta, Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Alena Gusakov, Yaël Dillies -/ import algebra.big_operators.basic import data.nat.interval import order.antichain /-! # `r`-sets and slice > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the `r`-th slice of a set family and provides a way to say that a set family is made of `r`-sets. An `r`-set is a finset of cardinality `r` (aka of *size* `r`). The `r`-th slice of a set family is the set family made of its `r`-sets. ## Main declarations * `set.sized`: `A.sized r` means that `A` only contains `r`-sets. * `finset.slice`: `A.slice r` is the set of `r`-sets in `A`. ## Notation `A # r` is notation for `A.slice r` in locale `finset_family`. -/ open finset nat open_locale big_operators variables {α : Type*} {ι : Sort*} {κ : ι → Sort*} namespace set variables {A B : set (finset α)} {r : ℕ} /-! ### Families of `r`-sets -/ /-- `sized r A` means that every finset in `A` has size `r`. -/ def sized (r : ℕ) (A : set (finset α)) : Prop := ∀ ⦃x⦄, x ∈ A → card x = r lemma sized.mono (h : A ⊆ B) (hB : B.sized r) : A.sized r := λ x hx, hB $ h hx lemma sized_union : (A ∪ B).sized r ↔ A.sized r ∧ B.sized r := ⟨λ hA, ⟨hA.mono $ subset_union_left _ _, hA.mono $ subset_union_right _ _⟩, λ hA x hx, hx.elim (λ h, hA.1 h) $ λ h, hA.2 h⟩ alias sized_union ↔ _ sized.union --TODO: A `forall_Union` lemma would be handy here. @[simp] lemma sized_Union {f : ι → set (finset α)} : (⋃ i, f i).sized r ↔ ∀ i, (f i).sized r := by { simp_rw [set.sized, set.mem_Union, forall_exists_index], exact forall_swap } @[simp] lemma sized_Union₂ {f : Π i, κ i → set (finset α)} : (⋃ i j, f i j).sized r ↔ ∀ i j, (f i j).sized r := by simp_rw sized_Union protected lemma sized.is_antichain (hA : A.sized r) : is_antichain (⊆) A := λ s hs t ht h hst, h $ finset.eq_of_subset_of_card_le hst ((hA ht).trans (hA hs).symm).le protected lemma sized.subsingleton (hA : A.sized 0) : A.subsingleton := subsingleton_of_forall_eq ∅ $ λ s hs, card_eq_zero.1 $ hA hs lemma sized.subsingleton' [fintype α] (hA : A.sized (fintype.card α)) : A.subsingleton := subsingleton_of_forall_eq finset.univ $ λ s hs, s.card_eq_iff_eq_univ.1 $ hA hs lemma sized.empty_mem_iff (hA : A.sized r) : ∅ ∈ A ↔ A = {∅} := hA.is_antichain.bot_mem_iff lemma sized.univ_mem_iff [fintype α] (hA : A.sized r) : finset.univ ∈ A ↔ A = {finset.univ} := hA.is_antichain.top_mem_iff lemma sized_powerset_len (s : finset α) (r : ℕ) : (powerset_len r s : set (finset α)).sized r := λ t ht, (mem_powerset_len.1 ht).2 end set namespace finset section sized variables [fintype α] {𝒜 : finset (finset α)} {s : finset α} {r : ℕ} lemma subset_powerset_len_univ_iff : 𝒜 ⊆ powerset_len r univ ↔ (𝒜 : set (finset α)).sized r := forall_congr $ λ A, by rw [mem_powerset_len_univ_iff, mem_coe] alias subset_powerset_len_univ_iff ↔ _ _root_.set.sized.subset_powerset_len_univ lemma _root_.set.sized.card_le (h𝒜 : (𝒜 : set (finset α)).sized r) : card 𝒜 ≤ (fintype.card α).choose r := begin rw [fintype.card, ←card_powerset_len], exact card_le_of_subset h𝒜.subset_powerset_len_univ, end end sized /-! ### Slices -/ section slice variables {𝒜 : finset (finset α)} {A A₁ A₂ : finset α} {r r₁ r₂ : ℕ} /-- The `r`-th slice of a set family is the subset of its elements which have cardinality `r`. -/ def slice (𝒜 : finset (finset α)) (r : ℕ) : finset (finset α) := 𝒜.filter (λ i, i.card = r) localized "infix (name := finset.slice) ` # `:90 := finset.slice" in finset_family /-- `A` is in the `r`-th slice of `𝒜` iff it's in `𝒜` and has cardinality `r`. -/ lemma mem_slice : A ∈ 𝒜 # r ↔ A ∈ 𝒜 ∧ A.card = r := mem_filter /-- The `r`-th slice of `𝒜` is a subset of `𝒜`. -/ lemma slice_subset : 𝒜 # r ⊆ 𝒜 := filter_subset _ _ /-- Everything in the `r`-th slice of `𝒜` has size `r`. -/ lemma sized_slice : (𝒜 # r : set (finset α)).sized r := λ _, and.right ∘ mem_slice.mp lemma eq_of_mem_slice (h₁ : A ∈ 𝒜 # r₁) (h₂ : A ∈ 𝒜 # r₂) : r₁ = r₂ := (sized_slice h₁).symm.trans $ sized_slice h₂ /-- Elements in distinct slices must be distinct. -/ lemma ne_of_mem_slice (h₁ : A₁ ∈ 𝒜 # r₁) (h₂ : A₂ ∈ 𝒜 # r₂) : r₁ ≠ r₂ → A₁ ≠ A₂ := mt $ λ h, (sized_slice h₁).symm.trans ((congr_arg card h).trans (sized_slice h₂)) lemma pairwise_disjoint_slice : (set.univ : set ℕ).pairwise_disjoint (slice 𝒜) := λ m _ n _ hmn, disjoint_filter.2 $ λ s hs hm hn, hmn $ hm.symm.trans hn variables [fintype α] (𝒜) @[simp] lemma bUnion_slice [decidable_eq α] : (Iic $ fintype.card α).bUnion 𝒜.slice = 𝒜 := subset.antisymm (bUnion_subset.2 $ λ r _, slice_subset) $ λ s hs, mem_bUnion.2 ⟨s.card, mem_Iic.2 $ s.card_le_univ, mem_slice.2 $ ⟨hs, rfl⟩⟩ @[simp] lemma sum_card_slice : ∑ r in Iic (fintype.card α), (𝒜 # r).card = 𝒜.card := begin letI := classical.dec_eq α, rw [←card_bUnion, bUnion_slice], exact finset.pairwise_disjoint_slice.subset (set.subset_univ _), end end slice end finset
/- Copyright (c) 2022 Yaël Dillies, Sara Rousta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies ! This file was ported from Lean 3 source module order.upper_lower.hom ! leanprover-community/mathlib commit b6da1a0b3e7cd83b1f744c49ce48ef8c6307d2f6 ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathbin.Order.UpperLower.Basic import Mathbin.Order.Hom.CompleteLattice /-! # `upper_set.Ici` etc as `sup`/`Sup`/`inf`/`Inf`-homomorphisms > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define `upper_set.Ici_sup_hom` etc. These functions are `upper_set.Ici` and `lower_set.Iic` bundled as `sup_hom`s, `inf_hom`s, `Sup_hom`s, or `Inf_hom`s. -/ variable {α : Type _} open OrderDual namespace UpperSet section SemilatticeSup variable [SemilatticeSup α] /- warning: upper_set.Ici_sup_hom -> UpperSet.iciSupHom is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : SemilatticeSup.{u1} α], SupHom.{u1, u1} α (UpperSet.{u1} α (Preorder.toLE.{u1} α (PartialOrder.toPreorder.{u1} α (SemilatticeSup.toPartialOrder.{u1} α _inst_1)))) (SemilatticeSup.toHasSup.{u1} α _inst_1) (UpperSet.hasSup.{u1} α (Preorder.toLE.{u1} α (PartialOrder.toPreorder.{u1} α (SemilatticeSup.toPartialOrder.{u1} α _inst_1)))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : SemilatticeSup.{u1} α], SupHom.{u1, u1} α (UpperSet.{u1} α (Preorder.toLE.{u1} α (PartialOrder.toPreorder.{u1} α (SemilatticeSup.toPartialOrder.{u1} α _inst_1)))) (SemilatticeSup.toSup.{u1} α _inst_1) (UpperSet.instSupUpperSet.{u1} α (Preorder.toLE.{u1} α (PartialOrder.toPreorder.{u1} α (SemilatticeSup.toPartialOrder.{u1} α _inst_1)))) Case conversion may be inaccurate. Consider using '#align upper_set.Ici_sup_hom UpperSet.iciSupHomₓ'. -/ /-- `upper_set.Ici` as a `sup_hom`. -/ def iciSupHom : SupHom α (UpperSet α) := ⟨Ici, Ici_sup⟩ #align upper_set.Ici_sup_hom UpperSet.iciSupHom #print UpperSet.coe_iciSupHom /- @[simp] theorem coe_iciSupHom : (iciSupHom : α → UpperSet α) = Ici := rfl #align upper_set.coe_Ici_sup_hom UpperSet.coe_iciSupHom -/ #print UpperSet.iciSupHom_apply /- @[simp] theorem iciSupHom_apply (a : α) : iciSupHom a = Ici a := rfl #align upper_set.Ici_sup_hom_apply UpperSet.iciSupHom_apply -/ end SemilatticeSup variable [CompleteLattice α] /-- `upper_set.Ici` as a `Sup_hom`. -/ def iciSupₛHom : SupₛHom α (UpperSet α) := ⟨Ici, fun s => (Ici_supₛ s).trans supₛ_image.symm⟩ #align upper_set.Ici_Sup_hom UpperSet.iciSupₛHomₓ @[simp] theorem coe_iciSupₛHom : (iciSupₛHom : α → UpperSet α) = Ici := rfl #align upper_set.coe_Ici_Sup_hom UpperSet.coe_iciSupₛHomₓ @[simp] theorem iciSupₛHom_apply (a : α) : iciSupₛHom a = Ici a := rfl #align upper_set.Ici_Sup_hom_apply UpperSet.iciSupₛHom_applyₓ end UpperSet namespace LowerSet section SemilatticeInf variable [SemilatticeInf α] /- warning: lower_set.Iic_inf_hom -> LowerSet.iicInfHom is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : SemilatticeInf.{u1} α], InfHom.{u1, u1} α (LowerSet.{u1} α (Preorder.toLE.{u1} α (PartialOrder.toPreorder.{u1} α (SemilatticeInf.toPartialOrder.{u1} α _inst_1)))) (SemilatticeInf.toHasInf.{u1} α _inst_1) (LowerSet.hasInf.{u1} α (Preorder.toLE.{u1} α (PartialOrder.toPreorder.{u1} α (SemilatticeInf.toPartialOrder.{u1} α _inst_1)))) but is expected to have type forall {α : Type.{u1}} [_inst_1 : SemilatticeInf.{u1} α], InfHom.{u1, u1} α (LowerSet.{u1} α (Preorder.toLE.{u1} α (PartialOrder.toPreorder.{u1} α (SemilatticeInf.toPartialOrder.{u1} α _inst_1)))) (SemilatticeInf.toInf.{u1} α _inst_1) (LowerSet.instInfLowerSet.{u1} α (Preorder.toLE.{u1} α (PartialOrder.toPreorder.{u1} α (SemilatticeInf.toPartialOrder.{u1} α _inst_1)))) Case conversion may be inaccurate. Consider using '#align lower_set.Iic_inf_hom LowerSet.iicInfHomₓ'. -/ /-- `lower_set.Iic` as an `inf_hom`. -/ def iicInfHom : InfHom α (LowerSet α) := ⟨Iic, Iic_inf⟩ #align lower_set.Iic_inf_hom LowerSet.iicInfHom #print LowerSet.coe_iicInfHom /- @[simp] theorem coe_iicInfHom : (iicInfHom : α → LowerSet α) = Iic := rfl #align lower_set.coe_Iic_inf_hom LowerSet.coe_iicInfHom -/ #print LowerSet.iicInfHom_apply /- @[simp] theorem iicInfHom_apply (a : α) : iicInfHom a = Iic a := rfl #align lower_set.Iic_inf_hom_apply LowerSet.iicInfHom_apply -/ end SemilatticeInf variable [CompleteLattice α] /-- `lower_set.Iic` as an `Inf_hom`. -/ def iicInfₛHom : InfₛHom α (LowerSet α) := ⟨Iic, fun s => (Iic_infₛ s).trans infₛ_image.symm⟩ #align lower_set.Iic_Inf_hom LowerSet.iicInfₛHomₓ @[simp] theorem coe_iicInfₛHom : (iicInfₛHom : α → LowerSet α) = Iic := rfl #align lower_set.coe_Iic_Inf_hom LowerSet.coe_iicInfₛHomₓ @[simp] theorem iicInfₛHom_apply (a : α) : iicInfₛHom a = Iic a := rfl #align lower_set.Iic_Inf_hom_apply LowerSet.iicInfₛHom_applyₓ end LowerSet
import os import numpy as np import matplotlib.pyplot as plt from osgeo import gdal as gd # get list of all subdirectories in a directory def get_subdirs(dir): "Get a list of immediate subdirectories" return next(os.walk(dir))[1] # get list of immediate files in a directory def get_subfiles(dir): "Get a list of immediate subfiles" return next(os.walk(dir))[2] # Function to stretch the 16bit image to 8bit. Play with the percent inputs. def stretch_8bit(bands, lower_percent=0.5, higher_percent=99.5): out = np.zeros_like(bands) for i in range(3): a = 0 b = 255 c = np.percentile(bands[:, :, i], lower_percent) d = np.percentile(bands[:, :, i], higher_percent) t = a + (bands[:, :, i] - c) * (b - a) / (d - c) t[t < a] = a t[t > b] = b out[:, :, i] = t return out.astype(np.uint8) # Save stretched 8bit array to png def saveTopng(tifffolder, pngfolder, tifffilename, dpi=400): ds = gd.Open(tifffolder + '/' + tifffilename) r = ds.GetRasterBand(1).ReadAsArray() g = ds.GetRasterBand(2).ReadAsArray() b = ds.GetRasterBand(3).ReadAsArray() img = np.zeros((r.shape[0],r.shape[1],3)) img[:, :, 0] = r img[:, :, 1] = g img[:, :, 2] = b pngfile = pngfolder + '/' + tifffilename.split('.')[0] + '.png' plt.imsave(pngfile, stretch_8bit(img), dpi=dpi) # convert images from tiff to png format def convert_all_to_png(tifffolder, pngfolder): dpi=800 # Get all geotiff files alltiffs = get_subfiles(tifffolder) for tifffilename in alltiffs: saveTopng(tifffolder, pngfolder, tifffilename, dpi=dpi)
Kevin Froese, on deck at left, of Mennonite Disaster Service, speaks during the Aug. 23 dedication of the first of 11 houses to be completed by ecumenical volunteers after last year’s Carlton Complex Fire in Washington. The house was framed by the Amish from Montana, the MDS and United Methodists finished the interior. From left, Linda Robinson, Clint Baker and Nancy Baker are among the volunteers providing meals and shelter to residents finding refuge from wildfires at Pateros Community United Methodist Church in Washington. Last summer, a wildfire scorched the back of Pateros Community United Methodist Church in Washington State and burned down its parsonage. This August, as fires once again devastate the drought-plagued western U.S., the church in Pateros is open 24 hours a day to those in need of shelter, food and a place to escape the smoke. Volunteers from throughout the denomination’s Pacific Northwest Conference, which encompasses Washington and 10 counties in the northern panhandle of Idaho, have been assisting “from Day 1,” said Jim Truitt, who has served as the conference’s United Methodist Volunteers in Mission disaster response coordinator for the past nine years. The United Methodist Committee on Relief recently distributed wildfire-related emergency grants to both the Pacific Northwest and California-Nevada conferences. Sparked by lightning without rain and aided by high winds and tinder-dry brush and trees, single fires in Chelan, Douglas and Okanogan counties have merged into “complex” infernos. Even before that point, the Washington wildfires claimed the lives of three firefighters with the U.S. Forest Service and injured four others when shifting flames overtook a fire crew Aug. 19 after their vehicle had crashed. One of them, Andrew Zajac, 26, was the son of the Rev. Mary Zajac, senior pastor at Baker Memorial United Methodist Church in St. Charles, Illinois, and her husband, Jim Zajac. The family, including his wife, Jennifer, released a video statement about him. Richard “Rick” Wheeler, 31, was a member of First United Methodist Church in Wenatchee, Washington, where the pastor, the Rev. Joanne Coleman Campbell, comforted his wife, Celeste, after she received news of his death. Tom Zbyszewski, 20, the third firefighter who died, had just finished his sophomore year at Whitman College in Walla Walla and was spending his second summer with the U.S. Forest Service, where his parents also have worked. A memorial service for all three firefighters is planned at 1p.m. Sunday, Aug. 30, in Wenatchee. Residents evacuating from those fires to the north and the Chelan Complex fire to the south have fled to Pateros and Brewster, where the Red Cross has opened a shelter. Most of the people currently seeking shelter at the church are from the north and came with animals that aren’t allowed at the Red Cross shelter. As of mid-day on Aug. 25, three families were in residence, but the numbers fluctuate. “In 20 minutes, I could have 50 people at the door,” Lane said. Truitt dispatched six clergy and lay persons to Pateros last week to offer support and “simply provide a presence” until the fire chaplains could arrive. He delivered some needed supplies — underwear, toothpaste and gas cards — to the church shelter over the weekend. Part of the anxiety, Truitt said, is that it often takes a long time to learn what has been lost or saved. “The fires are so severe and the smoke is so thick the assessors simply can’t tell them the status of their homes,” he explained. Just a year ago, the Carlton Complex fire was the largest wildfire in state history and volunteers continue to work on long-term recovery plans. On Aug. 23, the first two of 11 houses to be rebuilt this year were dedicated even as smoke filled the air, said Truitt, who participated in the ceremony. “The Amish poured the foundation and framed the house and the Mennonites finished the inside with some help from the Methodists,” he wrote on the conference’s UMVIM Facebook page. The Rev. Stanley Norman —who serves as co-chair for disaster response with the Rev. Gerri Harvill — believes the Pacific Northwest Conference is better prepared because of last year’s experience. Money from the conference’s disaster response account was used to help fund disaster case management, with Cathy Earl of UMCOR providing training to 27 individuals last October, several of whom were hired by the long-term recovery group. “That was really an important step and we’ll probably be calling on those same case managers,” Norman said. More than 50 percent of state residents affected by wildfires are unable to secure fire insurance and receive no federal or state funds, Norman noted, so they depend on nonprofit and faith groups for assistance.
#py from parse import parse #py import model #py plugin = parse(pycpp.params['xml_file']) #include "stubs.h" #include <cstdlib> #include <iostream> #include <boost/lexical_cast.hpp> #include <boost/format.hpp> #define CATCH_AND_RETHROW(prefix) \ catch(std::exception &ex) \ { \ std::string msg = prefix; \ msg += ex.what(); \ throw exception(msg); \ } \ catch(std::string& s) \ { \ std::string msg = prefix; \ msg += s; \ throw exception(msg); \ } \ catch(int& n) \ { \ std::stringstream msg; \ msg << prefix; \ msg << "error #" << n; \ throw exception(msg.str()); \ } bool isDebugStubsEnabled() { static int enabled = -1; if(enabled == 0) return false; if(enabled == 1) return true; char *val = std::getenv("DEBUG_STUBS"); if(!val) enabled = 0; else enabled = boost::lexical_cast<int>(val) != 0 ? 1 : 0; return enabled; } simInt simRegisterScriptCallbackFunctionE(const simChar *funcNameAtPluginName, const simChar *callTips, simVoid (*callBack)(struct SScriptCallBack *cb)) { simInt ret = simRegisterScriptCallbackFunction(funcNameAtPluginName, callTips, callBack); if(ret == 0) { std::cout << "Plugin '`plugin.name`': warning: replaced function '" << funcNameAtPluginName << "'" << std::endl; } if(ret == -1) throw exception("simRegisterScriptCallbackFunction: error"); return ret; } simInt simRegisterScriptVariableE(const simChar *varName, const simChar *varValue, simInt stackID) { simInt ret = simRegisterScriptVariable(varName, varValue, stackID); if(ret == 0) { std::cout << "Plugin '`plugin.name`': warning: replaced variable '" << varName << "'" << std::endl; } if(ret == -1) throw exception("simRegisterScriptVariable: error"); return ret; } simVoid simCallScriptFunctionExE(simInt scriptHandleOrType,const simChar* functionNameAtScriptName,simInt stackId) { if(simCallScriptFunctionEx(scriptHandleOrType, functionNameAtScriptName, stackId) == -1) throw exception("simCallScriptFunctionEx: error"); } simInt simCreateStackE() { #ifdef DEBUG if(isDebugStubsEnabled()) { std::cout << "DEBUG_STUBS: simCreateStack()" << std::endl; } #endif // DEBUG simInt ret = simCreateStack(); if(ret == -1) throw exception("simCreateStack: error"); return ret; } simVoid simReleaseStackE(simInt stackHandle) { #ifdef DEBUG if(isDebugStubsEnabled()) { std::cout << "DEBUG_STUBS: simReleaseStack(stack)" << std::endl; } #endif // DEBUG if(simReleaseStack(stackHandle) != 1) throw exception("simReleaseStack: error"); } simInt simCopyStackE(simInt stackHandle) { #ifdef DEBUG if(isDebugStubsEnabled()) { std::cout << "DEBUG_STUBS: simCopyStack(stack)" << std::endl; } #endif // DEBUG simInt ret = simCopyStack(stackHandle); if(ret == -1) throw exception("simCopyStack: error"); return ret; } simVoid simPushNullOntoStackE(simInt stackHandle) { #ifdef DEBUG if(isDebugStubsEnabled()) { std::cout << "DEBUG_STUBS: simPushNullOntoStack(stack)" << std::endl; } #endif // DEBUG if(simPushNullOntoStack(stackHandle) == -1) throw exception("simPushNullOntoStack: error"); } simVoid simPushBoolOntoStackE(simInt stackHandle, simBool value) { #ifdef DEBUG if(isDebugStubsEnabled()) { std::cout << "DEBUG_STUBS: simPushBoolOntoStack(stack, " << value << ")" << std::endl; } #endif // DEBUG if(simPushBoolOntoStack(stackHandle, value) == -1) throw exception("simPushBoolOntoStack: error"); } simVoid simPushInt32OntoStackE(simInt stackHandle, simInt value) { #ifdef DEBUG if(isDebugStubsEnabled()) { std::cout << "DEBUG_STUBS: simPushInt32OntoStack(stack, " << value << ")" << std::endl; } #endif // DEBUG if(simPushInt32OntoStack(stackHandle, value) == -1) throw exception("simPushInt32OntoStack: error"); } simVoid simPushFloatOntoStackE(simInt stackHandle, simFloat value) { #ifdef DEBUG if(isDebugStubsEnabled()) { std::cout << "DEBUG_STUBS: simPushFloatOntoStack(stack, " << value << ")" << std::endl; } #endif // DEBUG if(simPushFloatOntoStack(stackHandle, value) == -1) throw exception("simPushFloatOntoStack: error"); } simVoid simPushDoubleOntoStackE(simInt stackHandle, simDouble value) { #ifdef DEBUG if(isDebugStubsEnabled()) { std::cout << "DEBUG_STUBS: simPushDoubleOntoStack(stack, " << value << ")" << std::endl; } #endif // DEBUG if(simPushDoubleOntoStack(stackHandle, value) == -1) throw exception("simPushDoubleOntoStack: error"); } simVoid simPushStringOntoStackE(simInt stackHandle, const simChar *value, simInt stringSize) { #ifdef DEBUG if(isDebugStubsEnabled()) { std::cout << "DEBUG_STUBS: simPushStringOntoStack(stack, \"" << value << "\" [" << stringSize << "])" << std::endl; } #endif // DEBUG if(simPushStringOntoStack(stackHandle, value, stringSize) == -1) throw exception("simPushStringOntoStack: error"); } simVoid simPushUInt8TableOntoStackE(simInt stackHandle, const simUChar *values, simInt valueCnt) { #ifdef DEBUG if(isDebugStubsEnabled()) { std::cout << "DEBUG_STUBS: simPushUInt8TableOntoStack(stack, <" << valueCnt << " values>)" << std::endl; } #endif // DEBUG if(simPushUInt8TableOntoStack(stackHandle, values, valueCnt) == -1) throw exception("simPushUInt8TableOntoStack: error"); } simVoid simPushInt32TableOntoStackE(simInt stackHandle, const simInt *values, simInt valueCnt) { #ifdef DEBUG if(isDebugStubsEnabled()) { std::cout << "DEBUG_STUBS: simPushInt32TableOntoStack(stack, <" << valueCnt << " values>)" << std::endl; } #endif // DEBUG if(simPushInt32TableOntoStack(stackHandle, values, valueCnt) == -1) throw exception("simPushInt32TableOntoStack: error"); } simVoid simPushFloatTableOntoStackE(simInt stackHandle, const simFloat *values, simInt valueCnt) { #ifdef DEBUG if(isDebugStubsEnabled()) { std::cout << "DEBUG_STUBS: simPushFloatTableOntoStack(stack, <" << valueCnt << " values>)" << std::endl; } #endif // DEBUG if(simPushFloatTableOntoStack(stackHandle, values, valueCnt) == -1) throw exception("simPushFloatTableOntoStack: error"); } simVoid simPushDoubleTableOntoStackE(simInt stackHandle, const simDouble *values, simInt valueCnt) { #ifdef DEBUG if(isDebugStubsEnabled()) { std::cout << "DEBUG_STUBS: simPushDoubleTableOntoStack(stack, <" << valueCnt << " values>)" << std::endl; } #endif // DEBUG if(simPushDoubleTableOntoStack(stackHandle, values, valueCnt) == -1) throw exception("simPushDoubleTableOntoStack: error"); } simVoid simPushTableOntoStackE(simInt stackHandle) { #ifdef DEBUG if(isDebugStubsEnabled()) { std::cout << "DEBUG_STUBS: simPushTableOntoStack(stack)" << std::endl; } #endif // DEBUG if(simPushTableOntoStack(stackHandle) == -1) throw exception("simPushTableOntoStack: error"); } simVoid simInsertDataIntoStackTableE(simInt stackHandle) { #ifdef DEBUG if(isDebugStubsEnabled()) { std::cout << "DEBUG_STUBS: simInsertDataIntoStackTable(stack)" << std::endl; } #endif // DEBUG if(simInsertDataIntoStackTable(stackHandle) == -1) throw exception("simInsertDataIntoStackTable: error"); } simInt simGetStackSizeE(simInt stackHandle) { simInt ret = simGetStackSize(stackHandle); #ifdef DEBUG if(isDebugStubsEnabled()) { std::cout << "DEBUG_STUBS: simGetStackSize(stack) -> " << ret << std::endl; } #endif // DEBUG if(ret == -1) throw exception("simGetStackSize: error"); return ret; } simInt simPopStackItemE(simInt stackHandle, simInt count) { simInt ret = simPopStackItem(stackHandle, count); #ifdef DEBUG if(isDebugStubsEnabled()) { std::cout << "DEBUG_STUBS: simPopStackItem(stack, " << count << ") -> " << ret << std::endl; } #endif // DEBUG if(ret == -1) throw exception("simPopStackItem: error"); return ret; } simVoid simMoveStackItemToTopE(simInt stackHandle, simInt cIndex) { #ifdef DEBUG if(isDebugStubsEnabled()) { std::cout << "DEBUG_STUBS: simMoveStackItemToTop(stack, " << cIndex << ")" << std::endl; } #endif // DEBUG if(simMoveStackItemToTop(stackHandle, cIndex) == -1) throw exception("simMoveStackItemToTop: error"); } simInt simIsStackValueNullE(simInt stackHandle) { simInt ret = simIsStackValueNull(stackHandle); if(ret == -1) throw exception("simIsStackValueNull: error"); return ret; } simInt simGetStackBoolValueE(simInt stackHandle, simBool *boolValue) { simInt ret = simGetStackBoolValue(stackHandle, boolValue); if(ret == -1) throw exception("simGetStackBoolValue: error"); return ret; } simInt simGetStackInt32ValueE(simInt stackHandle, simInt *numberValue) { simInt ret = simGetStackInt32Value(stackHandle, numberValue); if(ret == -1) throw exception("simGetStackInt32Value: error"); return ret; } simInt simGetStackFloatValueE(simInt stackHandle, simFloat *numberValue) { simInt ret = simGetStackFloatValue(stackHandle, numberValue); if(ret == -1) throw exception("simGetStackFloatValue: error"); return ret; } simInt simGetStackDoubleValueE(simInt stackHandle, simDouble *numberValue) { simInt ret = simGetStackDoubleValue(stackHandle, numberValue); if(ret == -1) throw exception("simGetStackDoubleValue: error"); return ret; } simChar* simGetStackStringValueE(simInt stackHandle, simInt *stringSize) { simChar *ret = simGetStackStringValue(stackHandle, stringSize); // if stringSize is NULL, we cannot distinguish error (-1) from type error (0) if(ret == NULL && stringSize && *stringSize == -1) throw exception("simGetStackStringValue: error"); return ret; } simInt simGetStackTableInfoE(simInt stackHandle, simInt infoType) { simInt ret = simGetStackTableInfo(stackHandle, infoType); #ifdef DEBUG if(isDebugStubsEnabled()) { std::cout << "DEBUG_STUBS: simGetStackTableInfo(stack, " << infoType << ") -> " << ret << std::endl; } #endif // DEBUG if(ret == -1) throw exception("simGetStackTableInfo: error"); return ret; } simInt simGetStackUInt8TableE(simInt stackHandle, simUChar *array, simInt count) { simInt ret = simGetStackUInt8Table(stackHandle, array, count); if(ret == -1) throw exception("simGetStackUInt8Table: error"); return ret; } simInt simGetStackInt32TableE(simInt stackHandle, simInt *array, simInt count) { simInt ret = simGetStackInt32Table(stackHandle, array, count); if(ret == -1) throw exception("simGetStackInt32Table: error"); return ret; } simInt simGetStackFloatTableE(simInt stackHandle, simFloat *array, simInt count) { simInt ret = simGetStackFloatTable(stackHandle, array, count); if(ret == -1) throw exception("simGetStackFloatTable: error"); return ret; } simInt simGetStackDoubleTableE(simInt stackHandle, simDouble *array, simInt count) { simInt ret = simGetStackDoubleTable(stackHandle, array, count); if(ret == -1) throw exception("simGetStackDoubleTable: error"); return ret; } simVoid simUnfoldStackTableE(simInt stackHandle) { #ifdef DEBUG if(isDebugStubsEnabled()) { std::cout << "DEBUG_STUBS: simUnfoldStackTable(stack)" << std::endl; } #endif // DEBUG if(simUnfoldStackTable(stackHandle) == -1) throw exception("simUnfoldStackTable: error"); } simInt simGetInt32ParameterE(simInt parameter) { simInt ret; if(simGetInt32Parameter(parameter, &ret) == -1) throw exception("simGetInt32Parameter: error"); return ret; } simChar* simCreateBufferE(simInt size) { simChar *ret = simCreateBuffer(size); if(ret == NULL) throw exception("simCreateBuffer: error"); return ret; } simVoid simReleaseBufferE(simChar *buffer) { if(simReleaseBuffer(buffer) == -1) throw exception("simReleaseBuffer: error"); } void read__bool(int stack, bool *value) { simBool v; if(simGetStackBoolValueE(stack, &v) == 1) { *value = v; simPopStackItemE(stack, 1); } else { throw exception("expected bool"); } } void read__int(int stack, int *value) { int v; if(simGetStackInt32ValueE(stack, &v) == 1) { *value = v; simPopStackItemE(stack, 1); } else { throw exception("expected int"); } } void read__float(int stack, float *value) { simFloat v; if(simGetStackFloatValueE(stack, &v) == 1) { *value = v; simPopStackItemE(stack, 1); } else { throw exception("expected float"); } } void read__double(int stack, double *value) { simDouble v; if(simGetStackDoubleValueE(stack, &v) == 1) { *value = v; simPopStackItemE(stack, 1); } else { throw exception("expected double"); } } void read__std__string(int stack, std::string *value) { simChar *str; simInt strSize; if((str = simGetStackStringValueE(stack, &strSize)) != NULL && strSize >= 0) { *value = std::string(str, strSize); simPopStackItemE(stack, 1); simReleaseBufferE(str); } else { throw exception("expected string"); } } #py for struct in plugin.structs: void read__`struct.name`(int stack, `struct.name` *value) { #ifdef DEBUG if(isDebugStubsEnabled()) { std::cout << "DEBUG_STUBS: reading struct \"`struct.name`\"..." << std::endl; } #endif // DEBUG try { simInt info = simGetStackTableInfoE(stack, 0); if(info == sim_stack_table_empty) return; if(info != sim_stack_table_map) { #ifdef DEBUG if(isDebugStubsEnabled()) simDebugStack(stack, -1); #endif // DEBUG throw exception("expected a table"); } int oldsz = simGetStackSizeE(stack); simUnfoldStackTableE(stack); int numItems = (simGetStackSizeE(stack) - oldsz + 1) / 2; char *str; int strSz; while(numItems >= 1) { simMoveStackItemToTopE(stack, oldsz - 1); // move key to top if((str = simGetStackStringValueE(stack, &strSz)) != NULL && strSz >= 0) { simPopStackItemE(stack, 1); simMoveStackItemToTopE(stack, oldsz - 1); // move value to top if(0) {} #py for field in struct.fields: else if(strcmp(str, "`field.name`") == 0) { #ifdef DEBUG if(isDebugStubsEnabled()) std::cout << "DEBUG_STUBS: reading field \"`field.name`\"..." << std::endl; #endif // DEBUG try { #py if isinstance(field, model.ParamTable): // read field '`field.name`' of type array of `field.ctype()` simMoveStackItemToTopE(stack, 0); int i = simGetStackTableInfoE(stack, 0); if(i < 0) { #ifdef DEBUG if(isDebugStubsEnabled()) simDebugStack(stack, -1); #endif // DEBUG throw exception((boost::format("expected array (simGetStackTableInfo(stack, 0) returned %d)") % i).str()); } int oldsz = simGetStackSizeE(stack); simUnfoldStackTableE(stack); int sz = (simGetStackSizeE(stack) - oldsz + 1) / 2; for(int i = 0; i < sz; i++) { simMoveStackItemToTopE(stack, oldsz - 1); int j; read__int(stack, &j); simMoveStackItemToTop(stack, oldsz - 1); `field.ctype_normalized()` v; read__`field.ctype_normalized()`(stack, &v); value->`field.name`.push_back(v); } #py if field.minsize > 0 and field.minsize == field.maxsize: if(value->`field.name`.size() != `field.minsize`) throw exception("must have exactly `field.minsize` elements"); #py else: #py if field.minsize > 0: if(value->`field.name`.size() < `field.minsize`) throw exception("must have at least `field.minsize` elements"); #py endif #py if field.maxsize is not None: if(value->`field.name`.size() > `field.maxsize`) throw exception("must have at most `field.maxsize` elements"); #py endif #py endif #py else: // read field '`field.name`' of type `field.ctype()` read__`field.ctype_normalized()`(stack, &(value->`field.name`)); #py endif } CATCH_AND_RETHROW("field '`field.name`': ") } #py endfor else { std::string msg = "unexpected key: "; msg += str; throw exception(msg); } } numItems = (simGetStackSizeE(stack) - oldsz + 1) / 2; } } CATCH_AND_RETHROW("read__`struct.name`: ") } #py endfor void write__bool(bool value, int stack) { simBool v = value; simPushBoolOntoStackE(stack, v); } void write__int(int value, int stack) { simInt v = value; simPushInt32OntoStackE(stack, v); } void write__float(float value, int stack) { simFloat v = value; simPushFloatOntoStackE(stack, v); } void write__double(double value, int stack) { simDouble v = value; simPushDoubleOntoStackE(stack, v); } void write__std__string(std::string value, int stack) { const simChar *v = value.c_str(); simPushStringOntoStackE(stack, v, value.length()); } #py for struct in plugin.structs: void write__`struct.name`(`struct.name` *value, int stack) { #ifdef DEBUG if(isDebugStubsEnabled()) { std::cout << "DEBUG_STUBS: writing struct \"`struct.name`\"..." << std::endl; } #endif // DEBUG try { simPushTableOntoStackE(stack); #py for field in struct.fields: try { #ifdef DEBUG if(isDebugStubsEnabled()) std::cout << "DEBUG_STUBS: writing field \"`field.name`\"..." << std::endl; #endif // DEBUG simPushStringOntoStackE(stack, "`field.name`", 0); #py if isinstance(field, model.ParamTable): // write field '`field.name`' of type array of `field.ctype()` simPushTableOntoStackE(stack); for(int i = 0; i < value->`field.name`.size(); i++) { write__int(i + 1, stack); write__`field.ctype_normalized()`(`field.argmod()`(value->`field.name`[i]), stack); simInsertDataIntoStackTableE(stack); } #py else: // write field '`field.name`' of type `field.ctype()` write__`field.ctype_normalized()`(`field.argmod()`(value->`field.name`), stack); #py endif simInsertDataIntoStackTableE(stack); } CATCH_AND_RETHROW("field '`field.name`': ") #py endfor } CATCH_AND_RETHROW("write__`struct.name`: ") } #py endfor #py for struct in plugin.structs: `struct.name`::`struct.name`() { #py for field in struct.fields: #py if field.default: `field.name` = `field.cdefault()`; #py endif #py endfor } #py endfor bool registerScriptStuff() { try { { simInt vrepVer = 0, vrepRev = 0, vrepMinVer = 30400, vrepMinRev = 9; simGetIntegerParameter(sim_intparam_program_version, &vrepVer); simGetIntegerParameter(sim_intparam_program_revision, &vrepRev); if(vrepVer < vrepMinVer || (vrepVer == vrepMinVer && vrepRev < vrepMinRev)) { std::stringstream ss; ss << "this plugin requires at least V-REP " << (vrepMinVer / 10000) << "." << (vrepMinVer / 100 % 100) << "." << (vrepMinVer % 100) << " rev" << vrepMinRev; throw exception(ss.str()); } } try { #py if plugin.short_name: simRegisterScriptVariableE("sim`plugin.short_name`", "{}", 0); simRegisterScriptVariableE("sim`plugin.short_name`", "require('simExt`plugin.name`')", 0); #py endif #py if plugin.short_name: // register new-style short-version varables #py for enum in plugin.enums: simRegisterScriptVariableE("sim`plugin.short_name`.`enum.name`", "{}", 0); #py for item in enum.items: simRegisterScriptVariableE("sim`plugin.short_name`.`enum.name`.`item`", (boost::lexical_cast<std::string>(sim_`plugin.short_name.lower()`_`enum.item_prefix``item`)).c_str(), 0); #py endfor #py endfor // register new-style short-version commands #py for cmd in plugin.commands: simRegisterScriptCallbackFunctionE("sim`plugin.short_name`.`cmd.name`@`plugin.name`", "`cmd.help_out_args_text`sim`plugin.short_name`.`cmd.name`(`cmd.help_in_args_text`)`cmd.documentation`", `cmd.name`_callback); #py endfor #py endif #py if plugin.short_name: // commands simExt<PLUGIN_NAME>_<COMMAND_NAME> (deprecated) #py for cmd in plugin.commands: simRegisterScriptCallbackFunctionE("`plugin.command_prefix``cmd.name`@`plugin.name`", "`cmd.help_text`\n\n(DEPRECATED, please use sim`plugin.short_name`.`cmd.name`)", `cmd.name`_callback); #py endfor // register variables (deprecated) #py for enum in plugin.enums: #py for item in enum.items: simRegisterScriptVariableE("sim_`plugin.name.lower()`_`enum.item_prefix``item`", (boost::lexical_cast<std::string>(sim_`plugin.name.lower()`_`enum.item_prefix``item`)).c_str(), -1); #py endfor #py endfor #py else: // commands simExt<PLUGIN_NAME>_<COMMAND_NAME> #py for cmd in plugin.commands: simRegisterScriptCallbackFunctionE("`plugin.command_prefix``cmd.name`@`plugin.name`", "`cmd.help_text``cmd.documentation`", `cmd.name`_callback); #py endfor // register variables #py for enum in plugin.enums: #py for item in enum.items: simRegisterScriptVariableE("sim_`plugin.name.lower()`_`enum.item_prefix``item`", (boost::lexical_cast<std::string>(sim_`plugin.name.lower()`_`enum.item_prefix``item`)).c_str(), 0); #py endfor #py endfor #py endif #include "lua_calltips.cpp" } CATCH_AND_RETHROW("Initialization failed (registerScriptStuff): ") } catch(exception& ex) { std::cout << ex.what() << std::endl; return false; } return true; } #py for enum in plugin.enums: const char* `enum.name.lower()`_string(`enum.name` x) { switch(x) { #py for item in enum.items: case sim_`plugin.name.lower()`_`enum.item_prefix``item`: return "sim_`plugin.name.lower()`_`enum.item_prefix``item`"; #py endfor default: return "???"; } } #py endfor #py for cmd in plugin.commands: `cmd.name`_in::`cmd.name`_in() { #py for p in cmd.params: #py if p.cdefault() is not None: `p.name` = `p.cdefault()`; #py endif #py endfor } `cmd.name`_out::`cmd.name`_out() { #py for p in cmd.returns: #py if p.cdefault() is not None: `p.name` = `p.cdefault()`; #py endif #py endfor } void `cmd.name`(SScriptCallBack *p, `cmd.name`_in *in_args, `cmd.name`_out *out_args) { `cmd.name`(p, "`plugin.command_prefix``cmd.name`", in_args, out_args); } #py if len(cmd.returns) == 1: `cmd.returns[0].ctype()` `cmd.name`(`cmd.c_arg_list(pre_args=['SScriptCallBack *p'])`) { `cmd.name`_in in_args; #py for p in cmd.params: in_args.`p.name` = `p.name`; #py endfor `cmd.name`_out out_args; `cmd.name`(p, &in_args, &out_args); return out_args.`cmd.returns[0].name`; } #py endif #py if len(cmd.returns) == 0: void `cmd.name`(`cmd.c_arg_list(pre_args=['SScriptCallBack *p'])`) { `cmd.name`_in in_args; #py for p in cmd.params: in_args.`p.name` = `p.name`; #py endfor `cmd.name`_out out_args; `cmd.name`(p, &in_args, &out_args); } #py endif void `cmd.name`(`cmd.c_arg_list(pre_args=['SScriptCallBack *p', '%s_out *out_args' % cmd.name])`) { `cmd.name`_in in_args; #py for p in cmd.params: in_args.`p.name` = `p.name`; #py endfor `cmd.name`(p, &in_args, out_args); } void `cmd.name`_callback(SScriptCallBack *p) { #ifdef DEBUG if(isDebugStubsEnabled()) { std::cout << "DEBUG_STUBS: script callback for \"`cmd.name`\"..." << std::endl; std::cout << "DEBUG_STUBS: reading input arguments..." << std::endl; simDebugStack(p->stackID, -1); } #endif // DEBUG const char *cmd = "`plugin.command_prefix``cmd.name`"; `cmd.name`_in in_args; `cmd.name`_out out_args; try { // check argument count int numArgs = simGetStackSizeE(p->stackID); if(numArgs < `cmd.params_min`) throw exception("not enough arguments"); if(numArgs > `cmd.params_max`) throw exception("too many arguments"); // read input arguments from stack #py for i, p in enumerate(cmd.params): if(numArgs >= `i+1`) { #ifdef DEBUG if(isDebugStubsEnabled()) std::cout << "DEBUG_STUBS: reading input argument `i+1` (`p.name`)..." << std::endl; #endif // DEBUG try { #py if isinstance(p, model.ParamTable): #py if p.itype in ('float', 'double', 'int'): // read input argument `i+1` (`p.name`) of type array of `p.ctype()` using fast function simMoveStackItemToTopE(p->stackID, 0); int sz = simGetStackTableInfoE(p->stackID, 0); if(sz < 0) { #ifdef DEBUG if(isDebugStubsEnabled()) simDebugStack(p->stackID, -1); #endif // DEBUG throw exception((boost::format("expected array (simGetStackTableInfo(stack, 0) returned %d)") % sz).str()); } if(simGetStackTableInfoE(p->stackID, 2) != 1) { throw exception("fast_write_type reader exception #1 (simGetStackTableInfo(stack, 2) returned error)"); } in_args.`p.name`.resize(sz); #py if p.itype == 'float': simGetStackFloatTableE(p->stackID, &(in_args.`p.name`[0]), sz); #py elif p.itype == 'double': simGetStackDoubleTableE(p->stackID, &(in_args.`p.name`[0]), sz); #py elif p.itype == 'int': simGetStackInt32TableE(p->stackID, &(in_args.`p.name`[0]), sz); #py endif simPopStackItemE(p->stackID, 1); #py else: // read input argument `i+1` (`p.name`) of type array of `p.ctype()` simMoveStackItemToTopE(p->stackID, 0); int i = simGetStackTableInfoE(p->stackID, 0); if(i < 0) { #ifdef DEBUG if(isDebugStubsEnabled()) simDebugStack(p->stackID, -1); #endif // DEBUG throw exception((boost::format("expected array (simGetStackTableInfo(stack, 0) returned %d)") % i).str()); } int oldsz = simGetStackSizeE(p->stackID); simUnfoldStackTableE(p->stackID); int sz = (simGetStackSizeE(p->stackID) - oldsz + 1) / 2; for(int i = 0; i < sz; i++) { simMoveStackItemToTopE(p->stackID, oldsz - 1); int j; read__int(p->stackID, &j); simMoveStackItemToTop(p->stackID, oldsz - 1); `p.item_dummy().ctype()` v; read__`p.ctype_normalized()`(p->stackID, &v); in_args.`p.name`.push_back(v); } #py endif #py if p.minsize > 0 and p.minsize == p.maxsize: if(in_args.`p.name`.size() != `p.minsize`) throw exception("must have exactly `p.minsize` elements"); #py else: #py if p.minsize > 0: if(in_args.`p.name`.size() < `p.minsize`) throw exception("must have at least `p.minsize` elements"); #py endif #py if p.maxsize is not None: if(in_args.`p.name`.size() > `p.maxsize`) throw exception("must have at most `p.maxsize` elements"); #py endif #py endif #py else: // read input argument `i+1` (`p.name`) of type `p.ctype()` simMoveStackItemToTopE(p->stackID, 0); read__`p.ctype_normalized()`(p->stackID, &(in_args.`p.name`)); #py endif } CATCH_AND_RETHROW("read in arg `i+1` (`p.name`): ") } #py endfor #ifdef DEBUG if(isDebugStubsEnabled()) simDebugStack(p->stackID, -1); #endif // DEBUG #py if cmd.clear_stack_after_reading_input: // clear stack simPopStackItemE(p->stackID, 0); #py endif `cmd.name`(p, cmd, &in_args, &out_args); } catch(std::exception& e) { #ifdef DEBUG std::cerr << cmd << ": " << e.what() << std::endl; #endif simSetLastError(cmd, e.what()); } catch(std::string& s) { #ifdef DEBUG std::cerr << cmd << ": " << s << std::endl; #endif simSetLastError(cmd, s.c_str()); } catch(int& n) { std::stringstream ss; ss << "error #" << n; #ifdef DEBUG std::cerr << cmd << ": " << ss.str() << std::endl; #endif simSetLastError(cmd, ss.str().c_str()); } try { #ifdef DEBUG if(isDebugStubsEnabled()) { std::cout << "DEBUG_STUBS: writing output arguments..." << std::endl; simDebugStack(p->stackID, -1); } #endif // DEBUG #py if cmd.clear_stack_before_writing_output: // clear stack simPopStackItemE(p->stackID, 0); #py endif // write output arguments to stack #py for i, p in enumerate(cmd.returns): try { #ifdef DEBUG if(isDebugStubsEnabled()) std::cout << "DEBUG_STUBS: writing output argument `i+1` (`p.name`)..." << std::endl; #endif // DEBUG #py if isinstance(p, model.ParamTable): // write output argument `i+1` (`p.name`) of type array of `p.ctype()` simPushTableOntoStackE(p->stackID); for(int i = 0; i < out_args.`p.name`.size(); i++) { write__int(i + 1, p->stackID); write__`p.ctype_normalized()`(`p.argmod()`(out_args.`p.name`[i]), p->stackID); simInsertDataIntoStackTableE(p->stackID); } #py else: // write output argument `i+1` (`p.name`) of type `p.ctype()` write__`p.ctype_normalized()`(`p.argmod()`(out_args.`p.name`), p->stackID); #py endif } CATCH_AND_RETHROW("write out arg `i+1` (`p.name`): ") #py endfor #ifdef DEBUG if(isDebugStubsEnabled()) simDebugStack(p->stackID, -1); #endif // DEBUG } catch(std::exception& e) { #ifdef DEBUG std::cerr << cmd << ": " << e.what() << std::endl; #endif simSetLastError(cmd, e.what()); // clear stack simPopStackItem(p->stackID, 0); // don't throw } catch(std::string& s) { #ifdef DEBUG std::cerr << cmd << ": " << s << std::endl; #endif simSetLastError(cmd, s.c_str()); // clear stack simPopStackItem(p->stackID, 0); // don't throw } catch(int& n) { std::stringstream ss; ss << "error #" << n; #ifdef DEBUG std::cerr << cmd << ": " << ss.str() << std::endl; #endif simSetLastError(cmd, ss.str().c_str()); // clear stack simPopStackItem(p->stackID, 0); // don't throw } } #py endfor #py for fn in plugin.script_functions: `fn.name`_in::`fn.name`_in() { #py for p in fn.params: #py if p.default is not None: `p.name` = `p.cdefault()`; #py endif #py endfor } `fn.name`_out::`fn.name`_out() { #py for p in fn.returns: #py if p.default is not None: `p.name` = `p.cdefault()`; #py endif #py endfor } bool `fn.name`(simInt scriptId, const char *func, `fn.name`_in *in_args, `fn.name`_out *out_args) { #ifdef DEBUG if(isDebugStubsEnabled()) { std::cout << "DEBUG_STUBS: script callback function for \"`fn.name`\"..." << std::endl; std::cout << "DEBUG_STUBS: writing input arguments..." << std::endl; } #endif // DEBUG int stackID = -1; try { stackID = simCreateStackE(); // write input arguments to stack #py for i, p in enumerate(fn.params): try { #py if isinstance(p, model.ParamTable): // write input argument `i+1` (`p.name`) of type array of `p.ctype()` simPushTableOntoStackE(stackID); for(int i = 0; i < in_args->`p.name`.size(); i++) { write__int(i + 1, stackID); write__`p.ctype_normalized()`(`p.argmod()`(in_args->`p.name`[i]), stackID); simInsertDataIntoStackTableE(stackID); } #py else: // write input argument `i+1` (`p.name`) of type `p.ctype()` write__`p.ctype_normalized()`(`p.argmod()`(in_args->`p.name`), stackID); #py endif } CATCH_AND_RETHROW("writing input argument `i+1` (`p.name`): ") #py endfor #ifdef DEBUG if(isDebugStubsEnabled()) simDebugStack(stackID, -1); #endif // DEBUG simCallScriptFunctionExE(scriptId, func, stackID); // read output arguments from stack #ifdef DEBUG if(isDebugStubsEnabled()) std::cout << "DEBUG_STUBS: reading output arguments..." << std::endl; #endif // DEBUG #py for i, p in enumerate(fn.returns): try { #py if isinstance(p, model.ParamTable): // read output argument `i+1` (`p.name`) of type array of `p.ctype()` simMoveStackItemToTopE(stackID, 0); int i = simGetStackTableInfoE(stackID, 0); if(i < 0) { #ifdef DEBUG if(isDebugStubsEnabled()) simDebugStack(stackID, -1); #endif // DEBUG throw exception((boost::format("expected array (simGetStackTableInfo(stack, 0) returned %d)") % i).str()); } int oldsz = simGetStackSizeE(stackID); simUnfoldStackTableE(stackID); int sz = (simGetStackSizeE(stackID) - oldsz + 1) / 2; for(int i = 0; i < sz; i++) { simMoveStackItemToTopE(stackID, oldsz - 1); int j; read__int(stackID, &j); simMoveStackItemToTop(stackID, oldsz - 1); `p.ctype_normalized()` v; read__`p.ctype_normalized()`(stackID, &v); out_args->`p.name`.push_back(v); } #py if p.minsize > 0 and p.minsize == p.maxsize: if(out_args->`p.name`.size() != `p.minsize`) throw exception("must have exactly `p.minsize` elements"); #py else: #py if p.minsize > 0: if(out_args->`p.name`.size() < `p.minsize`) throw exception("must have at least `p.minsize` elements"); #py endif #py if p.maxsize is not None: if(out_args->`p.name`.size() > `p.maxsize`) throw exception("must have at most `p.maxsize` elements"); #py endif #py endif #py else: // read output argument `i+1` (`p.name`) of type `p.ctype()` read__`p.ctype_normalized()`(stackID, &(out_args->`p.name`)); #py endif } CATCH_AND_RETHROW("read out arg `i+1` (`p.name`): ") #py endfor #ifdef DEBUG if(isDebugStubsEnabled()) simDebugStack(stackID, -1); #endif // DEBUG simReleaseStackE(stackID); stackID = -1; } catch(std::exception& ex) { if(stackID != -1) simReleaseStack(stackID); // don't throw simSetLastError(func, ex.what()); return false; } catch(std::string& s) { if(stackID != -1) simReleaseStack(stackID); // don't throw simSetLastError(func, s.c_str()); return false; } catch(int& n) { if(stackID != -1) simReleaseStack(stackID); // don't throw std::stringstream ss; ss << "error #" << n; simSetLastError(func, ss.str().c_str()); return false; } return true; } #py endfor
(* !!! WARNING: AUTO GENERATED. DO NOT MODIFY !!! *) Require Import Metalib.Metatheory. (** syntax *) Definition i := nat. Inductive co : Set := (*r coercion *) | co_id : co (*r id *) | co_trans (c1:co) (c2:co) | co_top : co (*r top *) | co_arr (c1:co) (c2:co) (*r arr *) | co_pair (c1:co) (c2:co) (*r pair *) | co_proj1 : co (*r proj1 *) | co_proj2 : co (*r proj2 *) | co_distArr : co | co_distRcd (l:i) | co_rcd (l:i) (c:co) | co_topArr : co | co_topRcd (l:i). Inductive styp : Set := (*r source types *) | styp_top : styp (*r top *) | styp_nat : styp (*r nat *) | styp_and (A:styp) (B:styp) (*r intersection *) | styp_arrow (A:styp) (B:styp) (*r function *) | styp_rcd (l:i) (A:styp) (*r record *). Inductive exp : Set := (*r target expressions *) | trm_var_b (_:nat) (*r variables *) | trm_var_f (x:var) (*r variables *) | trm_unit : exp (*r unit *) | trm_lit (i5:i) (*r lit *) | trm_abs (e:exp) (*r abstractions *) | trm_app (e1:exp) (e2:exp) (*r applications *) | trm_pair (e1:exp) (e2:exp) (*r pair *) | trm_rcd (l:i) (e:exp) (*r record *) | trm_proj (e:exp) (l:i) (*r projection *) | trm_capp (c:co) (e:exp) (*r coApp *). Inductive sexp : Set := (*r source expressions *) | e_var_b (_:nat) (*r variable *) | e_var_f (x:var) (*r variable *) | e_top : sexp (*r top *) | e_lit (i5:i) (*r lit *) | e_abs (ee:sexp) (*r abstraction *) | e_app (ee1:sexp) (ee2:sexp) (*r applications *) | e_merge (ee1:sexp) (ee2:sexp) (*r merge *) | e_anno (ee:sexp) (A:styp) (*r annotations *) | e_rcd (l:i) (ee:sexp) (*r record *) | e_proj (ee:sexp) (l:i) (*r projection *). Inductive st : Set := | st_ty (A:styp) | st_la (l:i). Inductive typ : Set := (*r target types *) | a_nat : typ (*r nat *) | a_unit : typ (*r unit *) | a_arrow (T1:typ) (T2:typ) (*r function types *) | a_prod (T1:typ) (T2:typ) (*r product *) | a_rcd (l:i) (T:typ) (*r record *). Inductive cc : Set := (*r target context *) | cc_Empty : cc | cc_Lam (x:var) (cc5:cc) | cc_AppL (cc5:cc) (e:exp) | cc_AppR (e:exp) (cc5:cc) | cc_PairL (cc5:cc) (e:exp) | cc_PairR (e:exp) (cc5:cc) | cc_Co (c:co) (cc5:cc) | cc_Rcd (l:i) (cc5:cc) | cc_Proj (cc5:cc) (l:i). Definition sctx : Set := list ( atom * styp ). Inductive dirflag : Set := (*r checking direction *) | Inf : dirflag | Chk : dirflag. Inductive C : Set := (*r program context *) | C_Empty : C | C_Lam (x:var) (C5:C) | C_AppL (C5:C) (ee:sexp) | C_AppRd (ee:sexp) (C5:C) | C_MergeL (C5:C) (ee:sexp) | C_MergeR (ee:sexp) (C5:C) | C_Anno (C5:C) (A:styp) | C_Rcd (l:i) (C5:C) | C_Proj (C5:C) (l:i). Definition ls : Set := list st. Definition ctx : Set := list ( atom * typ ). (* EXPERIMENTAL *) (** auxiliary functions on the new list types *) (** library functions *) (** subrules *) (** arities *) (** opening up abstractions *) Fixpoint open_exp_wrt_exp_rec (k:nat) (e_5:exp) (e__6:exp) {struct e__6}: exp := match e__6 with | (trm_var_b nat) => match lt_eq_lt_dec nat k with | inleft (left _) => trm_var_b nat | inleft (right _) => e_5 | inright _ => trm_var_b (nat - 1) end | (trm_var_f x) => trm_var_f x | trm_unit => trm_unit | (trm_lit i5) => trm_lit i5 | (trm_abs e) => trm_abs (open_exp_wrt_exp_rec (S k) e_5 e) | (trm_app e1 e2) => trm_app (open_exp_wrt_exp_rec k e_5 e1) (open_exp_wrt_exp_rec k e_5 e2) | (trm_pair e1 e2) => trm_pair (open_exp_wrt_exp_rec k e_5 e1) (open_exp_wrt_exp_rec k e_5 e2) | (trm_rcd l e) => trm_rcd l (open_exp_wrt_exp_rec k e_5 e) | (trm_proj e l) => trm_proj (open_exp_wrt_exp_rec k e_5 e) l | (trm_capp c e) => trm_capp c (open_exp_wrt_exp_rec k e_5 e) end. Fixpoint open_sexp_wrt_sexp_rec (k:nat) (ee_5:sexp) (ee__6:sexp) {struct ee__6}: sexp := match ee__6 with | (e_var_b nat) => match lt_eq_lt_dec nat k with | inleft (left _) => e_var_b nat | inleft (right _) => ee_5 | inright _ => e_var_b (nat - 1) end | (e_var_f x) => e_var_f x | e_top => e_top | (e_lit i5) => e_lit i5 | (e_abs ee) => e_abs (open_sexp_wrt_sexp_rec (S k) ee_5 ee) | (e_app ee1 ee2) => e_app (open_sexp_wrt_sexp_rec k ee_5 ee1) (open_sexp_wrt_sexp_rec k ee_5 ee2) | (e_merge ee1 ee2) => e_merge (open_sexp_wrt_sexp_rec k ee_5 ee1) (open_sexp_wrt_sexp_rec k ee_5 ee2) | (e_anno ee A) => e_anno (open_sexp_wrt_sexp_rec k ee_5 ee) A | (e_rcd l ee) => e_rcd l (open_sexp_wrt_sexp_rec k ee_5 ee) | (e_proj ee l) => e_proj (open_sexp_wrt_sexp_rec k ee_5 ee) l end. Fixpoint open_cc_wrt_exp_rec (k:nat) (e5:exp) (cc_6:cc) {struct cc_6}: cc := match cc_6 with | cc_Empty => cc_Empty | (cc_Lam x cc5) => cc_Lam x (open_cc_wrt_exp_rec k e5 cc5) | (cc_AppL cc5 e) => cc_AppL (open_cc_wrt_exp_rec k e5 cc5) (open_exp_wrt_exp_rec k e5 e) | (cc_AppR e cc5) => cc_AppR (open_exp_wrt_exp_rec k e5 e) (open_cc_wrt_exp_rec k e5 cc5) | (cc_PairL cc5 e) => cc_PairL (open_cc_wrt_exp_rec k e5 cc5) (open_exp_wrt_exp_rec k e5 e) | (cc_PairR e cc5) => cc_PairR (open_exp_wrt_exp_rec k e5 e) (open_cc_wrt_exp_rec k e5 cc5) | (cc_Co c cc5) => cc_Co c (open_cc_wrt_exp_rec k e5 cc5) | (cc_Rcd l cc5) => cc_Rcd l (open_cc_wrt_exp_rec k e5 cc5) | (cc_Proj cc5 l) => cc_Proj (open_cc_wrt_exp_rec k e5 cc5) l end. Fixpoint open_C_wrt_sexp_rec (k:nat) (ee5:sexp) (C_6:C) {struct C_6}: C := match C_6 with | C_Empty => C_Empty | (C_Lam x C5) => C_Lam x (open_C_wrt_sexp_rec k ee5 C5) | (C_AppL C5 ee) => C_AppL (open_C_wrt_sexp_rec k ee5 C5) (open_sexp_wrt_sexp_rec k ee5 ee) | (C_AppRd ee C5) => C_AppRd (open_sexp_wrt_sexp_rec k ee5 ee) (open_C_wrt_sexp_rec k ee5 C5) | (C_MergeL C5 ee) => C_MergeL (open_C_wrt_sexp_rec k ee5 C5) (open_sexp_wrt_sexp_rec k ee5 ee) | (C_MergeR ee C5) => C_MergeR (open_sexp_wrt_sexp_rec k ee5 ee) (open_C_wrt_sexp_rec k ee5 C5) | (C_Anno C5 A) => C_Anno (open_C_wrt_sexp_rec k ee5 C5) A | (C_Rcd l C5) => C_Rcd l (open_C_wrt_sexp_rec k ee5 C5) | (C_Proj C5 l) => C_Proj (open_C_wrt_sexp_rec k ee5 C5) l end. Definition open_cc_wrt_exp e5 cc_6 := open_cc_wrt_exp_rec 0 cc_6 e5. Definition open_exp_wrt_exp e_5 e__6 := open_exp_wrt_exp_rec 0 e__6 e_5. Definition open_C_wrt_sexp ee5 C_6 := open_C_wrt_sexp_rec 0 C_6 ee5. Definition open_sexp_wrt_sexp ee_5 ee__6 := open_sexp_wrt_sexp_rec 0 ee__6 ee_5. (** terms are locally-closed pre-terms *) (** definitions *) (* defns LC_exp *) Inductive lc_exp : exp -> Prop := (* defn lc_exp *) | lc_trm_var_f : forall (x:var), (lc_exp (trm_var_f x)) | lc_trm_unit : (lc_exp trm_unit) | lc_trm_lit : forall (i5:i), (lc_exp (trm_lit i5)) | lc_trm_abs : forall (e:exp), ( forall x , lc_exp ( open_exp_wrt_exp e (trm_var_f x) ) ) -> (lc_exp (trm_abs e)) | lc_trm_app : forall (e1 e2:exp), (lc_exp e1) -> (lc_exp e2) -> (lc_exp (trm_app e1 e2)) | lc_trm_pair : forall (e1 e2:exp), (lc_exp e1) -> (lc_exp e2) -> (lc_exp (trm_pair e1 e2)) | lc_trm_rcd : forall (l:i) (e:exp), (lc_exp e) -> (lc_exp (trm_rcd l e)) | lc_trm_proj : forall (e:exp) (l:i), (lc_exp e) -> (lc_exp (trm_proj e l)) | lc_trm_capp : forall (c:co) (e:exp), (lc_exp e) -> (lc_exp (trm_capp c e)). (* defns LC_sexp *) Inductive lc_sexp : sexp -> Prop := (* defn lc_sexp *) | lc_e_var_f : forall (x:var), (lc_sexp (e_var_f x)) | lc_e_top : (lc_sexp e_top) | lc_e_lit : forall (i5:i), (lc_sexp (e_lit i5)) | lc_e_abs : forall (ee:sexp), ( forall x , lc_sexp ( open_sexp_wrt_sexp ee (e_var_f x) ) ) -> (lc_sexp (e_abs ee)) | lc_e_app : forall (ee1 ee2:sexp), (lc_sexp ee1) -> (lc_sexp ee2) -> (lc_sexp (e_app ee1 ee2)) | lc_e_merge : forall (ee1 ee2:sexp), (lc_sexp ee1) -> (lc_sexp ee2) -> (lc_sexp (e_merge ee1 ee2)) | lc_e_anno : forall (ee:sexp) (A:styp), (lc_sexp ee) -> (lc_sexp (e_anno ee A)) | lc_e_rcd : forall (l:i) (ee:sexp), (lc_sexp ee) -> (lc_sexp (e_rcd l ee)) | lc_e_proj : forall (ee:sexp) (l:i), (lc_sexp ee) -> (lc_sexp (e_proj ee l)). (* defns LC_cc *) Inductive lc_cc : cc -> Prop := (* defn lc_cc *) | lc_cc_Empty : (lc_cc cc_Empty) | lc_cc_Lam : forall (x:var) (cc5:cc), (lc_cc cc5) -> (lc_cc (cc_Lam x cc5)) | lc_cc_AppL : forall (cc5:cc) (e:exp), (lc_cc cc5) -> (lc_exp e) -> (lc_cc (cc_AppL cc5 e)) | lc_cc_AppR : forall (e:exp) (cc5:cc), (lc_exp e) -> (lc_cc cc5) -> (lc_cc (cc_AppR e cc5)) | lc_cc_PairL : forall (cc5:cc) (e:exp), (lc_cc cc5) -> (lc_exp e) -> (lc_cc (cc_PairL cc5 e)) | lc_cc_PairR : forall (e:exp) (cc5:cc), (lc_exp e) -> (lc_cc cc5) -> (lc_cc (cc_PairR e cc5)) | lc_cc_Co : forall (c:co) (cc5:cc), (lc_cc cc5) -> (lc_cc (cc_Co c cc5)) | lc_cc_Rcd : forall (l:i) (cc5:cc), (lc_cc cc5) -> (lc_cc (cc_Rcd l cc5)) | lc_cc_Proj : forall (cc5:cc) (l:i), (lc_cc cc5) -> (lc_cc (cc_Proj cc5 l)). (* defns LC_C *) Inductive lc_C : C -> Prop := (* defn lc_C *) | lc_C_Empty : (lc_C C_Empty) | lc_C_Lam : forall (x:var) (C5:C), (lc_C C5) -> (lc_C (C_Lam x C5)) | lc_C_AppL : forall (C5:C) (ee:sexp), (lc_C C5) -> (lc_sexp ee) -> (lc_C (C_AppL C5 ee)) | lc_C_AppRd : forall (ee:sexp) (C5:C), (lc_sexp ee) -> (lc_C C5) -> (lc_C (C_AppRd ee C5)) | lc_C_MergeL : forall (C5:C) (ee:sexp), (lc_C C5) -> (lc_sexp ee) -> (lc_C (C_MergeL C5 ee)) | lc_C_MergeR : forall (ee:sexp) (C5:C), (lc_sexp ee) -> (lc_C C5) -> (lc_C (C_MergeR ee C5)) | lc_C_Anno : forall (C5:C) (A:styp), (lc_C C5) -> (lc_C (C_Anno C5 A)) | lc_C_Rcd : forall (l:i) (C5:C), (lc_C C5) -> (lc_C (C_Rcd l C5)) | lc_C_Proj : forall (C5:C) (l:i), (lc_C C5) -> (lc_C (C_Proj C5 l)). (** free variables *) Fixpoint fv_exp (e_5:exp) : vars := match e_5 with | (trm_var_b nat) => {} | (trm_var_f x) => {{x}} | trm_unit => {} | (trm_lit i5) => {} | (trm_abs e) => (fv_exp e) | (trm_app e1 e2) => (fv_exp e1) \u (fv_exp e2) | (trm_pair e1 e2) => (fv_exp e1) \u (fv_exp e2) | (trm_rcd l e) => (fv_exp e) | (trm_proj e l) => (fv_exp e) | (trm_capp c e) => (fv_exp e) end. Fixpoint fv_cc (cc_6:cc) : vars := match cc_6 with | cc_Empty => {} | (cc_Lam x cc5) => (fv_cc cc5) | (cc_AppL cc5 e) => (fv_cc cc5) \u (fv_exp e) | (cc_AppR e cc5) => (fv_exp e) \u (fv_cc cc5) | (cc_PairL cc5 e) => (fv_cc cc5) \u (fv_exp e) | (cc_PairR e cc5) => (fv_exp e) \u (fv_cc cc5) | (cc_Co c cc5) => (fv_cc cc5) | (cc_Rcd l cc5) => (fv_cc cc5) | (cc_Proj cc5 l) => (fv_cc cc5) end. (** substitutions *) Fixpoint subst_exp (e_5:exp) (x5:var) (e__6:exp) {struct e__6} : exp := match e__6 with | (trm_var_b nat) => trm_var_b nat | (trm_var_f x) => (if eq_var x x5 then e_5 else (trm_var_f x)) | trm_unit => trm_unit | (trm_lit i5) => trm_lit i5 | (trm_abs e) => trm_abs (subst_exp e_5 x5 e) | (trm_app e1 e2) => trm_app (subst_exp e_5 x5 e1) (subst_exp e_5 x5 e2) | (trm_pair e1 e2) => trm_pair (subst_exp e_5 x5 e1) (subst_exp e_5 x5 e2) | (trm_rcd l e) => trm_rcd l (subst_exp e_5 x5 e) | (trm_proj e l) => trm_proj (subst_exp e_5 x5 e) l | (trm_capp c e) => trm_capp c (subst_exp e_5 x5 e) end. Fixpoint subst_cc (e5:exp) (x5:var) (cc_6:cc) {struct cc_6} : cc := match cc_6 with | cc_Empty => cc_Empty | (cc_Lam x cc5) => cc_Lam x (subst_cc e5 x5 cc5) | (cc_AppL cc5 e) => cc_AppL (subst_cc e5 x5 cc5) (subst_exp e5 x5 e) | (cc_AppR e cc5) => cc_AppR (subst_exp e5 x5 e) (subst_cc e5 x5 cc5) | (cc_PairL cc5 e) => cc_PairL (subst_cc e5 x5 cc5) (subst_exp e5 x5 e) | (cc_PairR e cc5) => cc_PairR (subst_exp e5 x5 e) (subst_cc e5 x5 cc5) | (cc_Co c cc5) => cc_Co c (subst_cc e5 x5 cc5) | (cc_Rcd l cc5) => cc_Rcd l (subst_cc e5 x5 cc5) | (cc_Proj cc5 l) => cc_Proj (subst_cc e5 x5 cc5) l end. Fixpoint calAnd (fs : ls) : co := match fs with | nil => co_id | cons l fs' => match l with | st_ty _ => (co_trans (co_arr co_id (calAnd fs')) co_distArr) | st_la l => (co_trans (co_rcd l (calAnd fs')) (co_distRcd l)) end end. Fixpoint calTop (fs : ls) : co := match fs with | nil => co_top | cons l fs' => match l with | st_ty _ => (co_trans (co_arr co_id (calTop fs')) (co_trans (co_arr co_top co_top) (co_trans co_topArr co_top))) | st_la l => (co_trans (co_rcd l (calTop fs')) (co_topRcd l)) end end. Fixpoint ptyp2styp (A : styp) : typ := match A with | styp_nat => a_nat | styp_arrow A1 A2 => a_arrow (ptyp2styp A1) (ptyp2styp A2) | styp_and A1 A2 => a_prod (ptyp2styp A1) (ptyp2styp A2) | styp_top => a_unit | styp_rcd l A => a_rcd l (ptyp2styp A) end. (** definitions *) (* defns JSubtyping *) Inductive sub : styp -> styp -> co -> Prop := (* defn sub *) | S_refl : forall (A:styp), sub A A co_id | S_trans : forall (A1 A3:styp) (c1 c2:co) (A2:styp), sub A2 A3 c1 -> sub A1 A2 c2 -> sub A1 A3 (co_trans c1 c2) | S_top : forall (A:styp), sub A styp_top co_top | S_topArr : sub styp_top (styp_arrow styp_top styp_top) co_topArr | S_topRcd : forall (l:i), sub styp_top (styp_rcd l styp_top) (co_topRcd l) | S_arr : forall (A1 A2 B1 B2:styp) (c1 c2:co), sub B1 A1 c1 -> sub A2 B2 c2 -> sub (styp_arrow A1 A2) (styp_arrow B1 B2) (co_arr c1 c2) | S_and : forall (A1 A2 A3:styp) (c1 c2:co), sub A1 A2 c1 -> sub A1 A3 c2 -> sub A1 (styp_and A2 A3) (co_pair c1 c2) | S_andl : forall (A1 A2:styp), sub (styp_and A1 A2) A1 co_proj1 | S_andr : forall (A1 A2:styp), sub (styp_and A1 A2) A2 co_proj2 | S_distArr : forall (A1 A2 A3:styp), sub (styp_and (styp_arrow A1 A2) (styp_arrow A1 A3) ) (styp_arrow A1 (styp_and A2 A3)) co_distArr | S_rcd : forall (l:i) (A B:styp) (c:co), sub A B c -> sub (styp_rcd l A) (styp_rcd l B) (co_rcd l c) | S_distRcd : forall (l:i) (A B:styp), sub (styp_and (styp_rcd l A) (styp_rcd l B)) (styp_rcd l (styp_and A B)) (co_distRcd l). (* defns JASubtype *) Inductive ASub : ls -> styp -> styp -> co -> Prop := (* defn ASub *) | A_nat : ASub nil styp_nat styp_nat co_id | A_rcdNat : forall (l:i) (fs:ls) (A:styp) (c:co), ASub fs A styp_nat c -> ASub (cons (st_la l ) fs ) (styp_rcd l A) styp_nat (co_rcd l c) | A_rcd : forall (fs:ls) (A:styp) (l:i) (B:styp) (c:co), ASub ( fs ++ (cons (st_la l ) nil)) A B c -> ASub fs A (styp_rcd l B) c | A_top : forall (fs:ls) (A:styp), ASub fs A styp_top (co_trans (calTop fs ) co_top) | A_and : forall (fs:ls) (A B1 B2:styp) (c1 c2:co), ASub fs A B1 c1 -> ASub fs A B2 c2 -> ASub fs A (styp_and B1 B2) (co_trans (calAnd fs ) (co_pair c1 c2)) | A_arr : forall (fs:ls) (A B1 B2:styp) (c:co), ASub ( fs ++ (cons (st_ty B1 ) nil)) A B2 c -> ASub fs A (styp_arrow B1 B2) c | A_andN1 : forall (fs:ls) (A1 A2:styp) (c:co), ASub fs A1 styp_nat c -> ASub fs (styp_and A1 A2) styp_nat (co_trans c co_proj1) | A_andN2 : forall (fs:ls) (A1 A2:styp) (c:co), ASub fs A2 styp_nat c -> ASub fs (styp_and A1 A2) styp_nat (co_trans c co_proj2) | A_arrNat : forall (A:styp) (fs:ls) (A1 A2:styp) (c1 c2:co), ASub nil A A1 c1 -> ASub fs A2 styp_nat c2 -> ASub (cons (st_ty A ) fs ) (styp_arrow A1 A2) styp_nat (co_arr c1 c2). (* defns Disjoint *) Inductive disjoint : styp -> styp -> Prop := (* defn disjoint *) | D_topL : forall (A:styp), disjoint styp_top A | D_topR : forall (A:styp), disjoint A styp_top | D_arr : forall (A1 A2 B1 B2:styp), disjoint A2 B2 -> disjoint (styp_arrow A1 A2) (styp_arrow B1 B2) | D_andL : forall (A1 A2 B:styp), disjoint A1 B -> disjoint A2 B -> disjoint (styp_and A1 A2) B | D_andR : forall (A B1 B2:styp), disjoint A B1 -> disjoint A B2 -> disjoint A (styp_and B1 B2) | D_rcdEq : forall (l:i) (A B:styp), disjoint A B -> disjoint (styp_rcd l A) (styp_rcd l B) | D_rcdNeq : forall (l1:i) (A:styp) (l2:i) (B:styp), l1 <> l2 -> disjoint (styp_rcd l1 A) (styp_rcd l2 B) | D_axNatArr : forall (A1 A2:styp), disjoint styp_nat (styp_arrow A1 A2) | D_axArrNat : forall (A1 A2:styp), disjoint (styp_arrow A1 A2) styp_nat | D_axNatRcd : forall (l:i) (A:styp), disjoint styp_nat (styp_rcd l A) | D_axRcdNat : forall (l:i) (A:styp), disjoint (styp_rcd l A) styp_nat | D_axArrRcd : forall (A1 A2:styp) (l:i) (A:styp), disjoint (styp_arrow A1 A2) (styp_rcd l A) | D_axRcdArr : forall (l:i) (A A1 A2:styp), disjoint (styp_rcd l A) (styp_arrow A1 A2). (* defns JSTyping *) Inductive has_type : sctx -> sexp -> dirflag -> styp -> exp -> Prop := (* defn has_type *) | T_top : forall (GG:sctx), uniq GG -> has_type GG e_top Inf styp_top trm_unit | T_lit : forall (GG:sctx) (i5:i), uniq GG -> has_type GG (e_lit i5) Inf styp_nat (trm_lit i5) | T_var : forall (GG:sctx) (x:var) (A:styp), uniq GG -> binds x A GG -> has_type GG (e_var_f x) Inf A (trm_var_f x) | T_app : forall (GG:sctx) (ee1 ee2:sexp) (A2:styp) (e1 e2:exp) (A1:styp), has_type GG ee1 Inf (styp_arrow A1 A2) e1 -> has_type GG ee2 Chk A1 e2 -> has_type GG (e_app ee1 ee2) Inf A2 (trm_app e1 e2) | T_merge : forall (GG:sctx) (ee1 ee2:sexp) (A1 A2:styp) (e1 e2:exp), has_type GG ee1 Inf A1 e1 -> has_type GG ee2 Inf A2 e2 -> disjoint A1 A2 -> has_type GG (e_merge ee1 ee2) Inf (styp_and A1 A2) (trm_pair e1 e2) | T_rcd : forall (GG:sctx) (l:i) (ee:sexp) (A:styp) (e:exp), has_type GG ee Inf A e -> has_type GG (e_rcd l ee) Inf (styp_rcd l A) (trm_rcd l e) | T_proj : forall (GG:sctx) (ee:sexp) (l:i) (A:styp) (e:exp), has_type GG ee Inf (styp_rcd l A) e -> has_type GG (e_proj ee l) Inf A (trm_proj e l) | T_anno : forall (GG:sctx) (ee:sexp) (A:styp) (e:exp), has_type GG ee Chk A e -> has_type GG (e_anno ee A) Inf A e | T_abs : forall (L:vars) (GG:sctx) (ee:sexp) (A B:styp) (e:exp), ( forall x , x \notin L -> has_type (( x ~ A )++ GG ) ( open_sexp_wrt_sexp ee (e_var_f x) ) Chk B ( open_exp_wrt_exp e (trm_var_f x) ) ) -> has_type GG (e_abs ee) Chk (styp_arrow A B) (trm_abs e) | T_sub : forall (GG:sctx) (ee:sexp) (A:styp) (c:co) (e:exp) (B:styp), has_type GG ee Inf B e -> sub B A c -> has_type GG ee Chk A (trm_capp c e). (* defns JCTyping *) Inductive CTyp : C -> sctx -> dirflag -> styp -> sctx -> dirflag -> styp -> cc -> Prop := (* defn CTyp *) | CTyp_empty1 : forall (GG:sctx) (A:styp), CTyp C_Empty GG Inf A GG Inf A cc_Empty | CTyp_empty2 : forall (GG:sctx) (A:styp), CTyp C_Empty GG Chk A GG Chk A cc_Empty | CTyp_appL1 : forall (C5:C) (ee2:sexp) (GG:sctx) (A:styp) (GG':sctx) (A2:styp) (cc5:cc) (e:exp) (A1:styp), CTyp C5 GG Inf A GG' Inf (styp_arrow A1 A2) cc5 -> has_type GG' ee2 Chk A1 e -> CTyp (C_AppL C5 ee2) GG Inf A GG' Inf A2 (cc_AppL cc5 e) | CTyp_appL2 : forall (C5:C) (ee2:sexp) (GG:sctx) (A:styp) (GG':sctx) (A2:styp) (cc5:cc) (e:exp) (A1:styp), CTyp C5 GG Chk A GG' Inf (styp_arrow A1 A2) cc5 -> has_type GG' ee2 Chk A1 e -> CTyp (C_AppL C5 ee2) GG Chk A GG' Inf A2 (cc_AppL cc5 e) | CTyp_appR1 : forall (ee1:sexp) (C5:C) (GG:sctx) (A:styp) (GG':sctx) (A2:styp) (e:exp) (cc5:cc) (A1:styp), has_type GG' ee1 Inf (styp_arrow A1 A2) e -> CTyp C5 GG Inf A GG' Chk A1 cc5 -> CTyp (C_AppRd ee1 C5) GG Inf A GG' Inf A2 (cc_AppR e cc5) | CTyp_appR2 : forall (ee1:sexp) (C5:C) (GG:sctx) (A:styp) (GG':sctx) (A2:styp) (e:exp) (cc5:cc) (A1:styp), has_type GG' ee1 Inf (styp_arrow A1 A2) e -> CTyp C5 GG Chk A GG' Chk A1 cc5 -> CTyp (C_AppRd ee1 C5) GG Chk A GG' Inf A2 (cc_AppR e cc5) | CTyp_mergeL1 : forall (C5:C) (ee2:sexp) (GG:sctx) (A:styp) (GG':sctx) (A1 A2:styp) (cc5:cc) (e:exp), CTyp C5 GG Inf A GG' Inf A1 cc5 -> has_type GG' ee2 Inf A2 e -> disjoint A1 A2 -> CTyp (C_MergeL C5 ee2) GG Inf A GG' Inf (styp_and A1 A2) (cc_PairL cc5 e) | CTyp_mergeL2 : forall (C5:C) (ee2:sexp) (GG:sctx) (A:styp) (GG':sctx) (A1 A2:styp) (cc5:cc) (e:exp), CTyp C5 GG Chk A GG' Inf A1 cc5 -> has_type GG' ee2 Inf A2 e -> disjoint A1 A2 -> CTyp (C_MergeL C5 ee2) GG Chk A GG' Inf (styp_and A1 A2) (cc_PairL cc5 e) | CTyp_mergeR1 : forall (ee1:sexp) (C5:C) (GG:sctx) (A:styp) (GG':sctx) (A1 A2:styp) (e:exp) (cc5:cc), has_type GG' ee1 Inf A1 e -> CTyp C5 GG Inf A GG' Inf A2 cc5 -> disjoint A1 A2 -> CTyp (C_MergeR ee1 C5) GG Inf A GG' Inf (styp_and A1 A2) (cc_PairR e cc5) | CTyp_mergeR2 : forall (ee1:sexp) (C5:C) (GG:sctx) (A:styp) (GG':sctx) (A1 A2:styp) (e:exp) (cc5:cc), has_type GG' ee1 Inf A1 e -> CTyp C5 GG Chk A GG' Inf A2 cc5 -> disjoint A1 A2 -> CTyp (C_MergeR ee1 C5) GG Chk A GG' Inf (styp_and A1 A2) (cc_PairR e cc5) | CTyp_rcd1 : forall (l:i) (C5:C) (GG:sctx) (A:styp) (GG':sctx) (B:styp) (cc5:cc), CTyp C5 GG Inf A GG' Inf B cc5 -> CTyp (C_Rcd l C5) GG Inf A GG' Inf (styp_rcd l B) (cc_Rcd l cc5) | CTyp_rcd2 : forall (l:i) (C5:C) (GG:sctx) (A:styp) (GG':sctx) (B:styp) (cc5:cc), CTyp C5 GG Chk A GG' Inf B cc5 -> CTyp (C_Rcd l C5) GG Chk A GG' Inf (styp_rcd l B) (cc_Rcd l cc5) | CTyp_proj1 : forall (C5:C) (l:i) (GG:sctx) (A:styp) (GG':sctx) (B:styp) (cc5:cc), CTyp C5 GG Inf A GG' Inf (styp_rcd l B) cc5 -> CTyp (C_Proj C5 l) GG Inf A GG' Inf B (cc_Proj cc5 l) | CTyp_proj2 : forall (C5:C) (l:i) (GG:sctx) (A:styp) (GG':sctx) (B:styp) (cc5:cc), CTyp C5 GG Chk A GG' Inf (styp_rcd l B) cc5 -> CTyp (C_Proj C5 l) GG Chk A GG' Inf B (cc_Proj cc5 l) | CTyp_anno1 : forall (C5:C) (A:styp) (GG:sctx) (B:styp) (GG':sctx) (cc5:cc), CTyp C5 GG Inf B GG' Chk A cc5 -> CTyp (C_Anno C5 A) GG Inf B GG' Inf A cc5 | CTyp_anno2 : forall (C5:C) (A:styp) (GG:sctx) (B:styp) (GG':sctx) (cc5:cc), CTyp C5 GG Chk B GG' Chk A cc5 -> CTyp (C_Anno C5 A) GG Chk B GG' Inf A cc5 | CTyp_abs1 : forall (x:var) (C5:C) (GG:sctx) (A:styp) (GG':sctx) (A1 A2:styp) (cc5:cc), CTyp C5 GG Inf A (( x ~ A1 )++ GG' ) Chk A2 cc5 -> ~ AtomSetImpl.In x (dom GG' ) -> CTyp (C_Lam x C5) GG Inf A GG' Chk (styp_arrow A1 A2) (cc_Lam x cc5) | CTyp_abs2 : forall (x:var) (C5:C) (GG:sctx) (A:styp) (GG':sctx) (A1 A2:styp) (cc5:cc), CTyp C5 GG Chk A (( x ~ A1 )++ GG' ) Chk A2 cc5 -> ~ AtomSetImpl.In x (dom GG' ) -> CTyp (C_Lam x C5) GG Chk A GG' Chk (styp_arrow A1 A2) (cc_Lam x cc5). (* defns JCoTyping *) Inductive cotyp : co -> typ -> typ -> Prop := (* defn cotyp *) | cotyp_refl : forall (T:typ), cotyp co_id T T | cotyp_trans : forall (c1 c2:co) (T1 T3 T2:typ), cotyp c1 T2 T3 -> cotyp c2 T1 T2 -> cotyp (co_trans c1 c2) T1 T3 | cotyp_top : forall (T:typ), cotyp co_top T a_unit | cotyp_topArr : cotyp co_topArr a_unit (a_arrow a_unit a_unit) | cotyp_arr : forall (c1 c2:co) (T1 T2 T1' T2':typ), cotyp c1 T1' T1 -> cotyp c2 T2 T2' -> cotyp (co_arr c1 c2) (a_arrow T1 T2) (a_arrow T1' T2') | cotyp_pair : forall (c1 c2:co) (T1 T2 T3:typ), cotyp c1 T1 T2 -> cotyp c2 T1 T3 -> cotyp (co_pair c1 c2) T1 (a_prod T2 T3) | cotyp_distArr : forall (T1 T2 T3:typ), cotyp co_distArr (a_prod (a_arrow T1 T2) (a_arrow T1 T3) ) (a_arrow T1 (a_prod T2 T3)) | cotyp_projl : forall (T1 T2:typ), cotyp co_proj1 (a_prod T1 T2) T1 | cotyp_projr : forall (T1 T2:typ), cotyp co_proj2 (a_prod T1 T2) T2 | cotyp_rcd : forall (l:i) (c:co) (T1 T2:typ), cotyp c T1 T2 -> cotyp (co_rcd l c) (a_rcd l T1) (a_rcd l T2) | cotyp_topRcd : forall (l:i), cotyp (co_topRcd l) a_unit (a_rcd l a_unit) | cotyp_distRcd : forall (l:i) (T1 T2:typ), cotyp (co_distRcd l) (a_prod (a_rcd l T1) (a_rcd l T2)) (a_rcd l (a_prod T1 T2)). (* defns JTyping *) Inductive typing : ctx -> exp -> typ -> Prop := (* defn typing *) | typ_unit : forall (G:ctx), uniq G -> typing G trm_unit a_unit | typ_lit : forall (G:ctx) (i5:i), uniq G -> typing G (trm_lit i5) a_nat | typ_var : forall (G:ctx) (x:var) (T:typ), uniq G -> binds x T G -> typing G (trm_var_f x) T | typ_abs : forall (L:vars) (G:ctx) (e:exp) (T1 T2:typ), ( forall x , x \notin L -> typing (( x ~ T1 )++ G ) ( open_exp_wrt_exp e (trm_var_f x) ) T2 ) -> typing G (trm_abs e) (a_arrow T1 T2) | typ_app : forall (G:ctx) (e1 e2:exp) (T2 T1:typ), typing G e1 (a_arrow T1 T2) -> typing G e2 T1 -> typing G (trm_app e1 e2) T2 | typ_pair : forall (G:ctx) (e1 e2:exp) (T1 T2:typ), typing G e1 T1 -> typing G e2 T2 -> typing G (trm_pair e1 e2) (a_prod T1 T2) | typ_capp : forall (G:ctx) (c:co) (e:exp) (T' T:typ), typing G e T -> cotyp c T T' -> typing G (trm_capp c e) T' | typ_rcd : forall (G:ctx) (l:i) (e:exp) (T:typ), typing G e T -> typing G (trm_rcd l e) (a_rcd l T) | typ_proj : forall (G:ctx) (e:exp) (l:i) (T:typ), typing G e (a_rcd l T) -> typing G (trm_proj e l) T. (* defns JValue *) Inductive value : exp -> Prop := (* defn value *) | value_unit : value trm_unit | value_lit : forall (i5:i), value (trm_lit i5) | value_abs : forall (e:exp), lc_exp (trm_abs e) -> value (trm_abs e) | value_pair : forall (v1 v2:exp), value v1 -> value v2 -> value (trm_pair v1 v2) | value_rcd : forall (l:i) (v:exp), value v -> value (trm_rcd l v) | value_cabs : forall (c1 c2:co) (v:exp), value v -> value (trm_capp ( (co_arr c1 c2) ) v) | value_cpair : forall (v:exp), value v -> value (trm_capp co_distArr v) | value_topArr : forall (v:exp), value v -> value (trm_capp co_topArr v). (* defns JEval *) Inductive step : exp -> exp -> Prop := (* defn step *) | step_id : forall (v:exp), value v -> step (trm_capp co_id v) v | step_trans : forall (c1 c2:co) (v:exp), value v -> step (trm_capp ( (co_trans c1 c2) ) v) (trm_capp c1 ( (trm_capp c2 v) ) ) | step_top : forall (v:exp), value v -> step (trm_capp co_top v) trm_unit | step_topArr : step (trm_app ( (trm_capp co_topArr trm_unit) ) trm_unit) trm_unit | step_arr : forall (c1 c2:co) (v1 v2:exp), value v1 -> value v2 -> step (trm_app ( (trm_capp ( (co_arr c1 c2) ) v1) ) v2) (trm_capp c2 ( (trm_app v1 ( (trm_capp c1 v2) ) ) ) ) | step_pair : forall (c1 c2:co) (v:exp), value v -> step (trm_capp (co_pair c1 c2) v) (trm_pair (trm_capp c1 v) (trm_capp c2 v)) | step_distArr : forall (v1 v2 v3:exp), value v1 -> value v2 -> value v3 -> step (trm_app ( (trm_capp co_distArr (trm_pair v1 v2)) ) v3) (trm_pair (trm_app v1 v3) (trm_app v2 v3)) | step_projl : forall (v1 v2:exp), value v1 -> value v2 -> step (trm_capp co_proj1 (trm_pair v1 v2)) v1 | step_projr : forall (v1 v2:exp), value v1 -> value v2 -> step (trm_capp co_proj2 (trm_pair v1 v2)) v2 | step_crcd : forall (l:i) (c:co) (v:exp), value v -> step (trm_capp (co_rcd l c) (trm_rcd l v)) (trm_rcd l (trm_capp c v)) | step_topRcd : forall (l:i), step (trm_capp (co_topRcd l) trm_unit) (trm_rcd l trm_unit) | step_distRcd : forall (l:i) (v1 v2:exp), value v1 -> value v2 -> step (trm_capp (co_distRcd l) (trm_pair (trm_rcd l v1) (trm_rcd l v2))) (trm_rcd l (trm_pair v1 v2)) | step_projRcd : forall (l:i) (v:exp), value v -> step (trm_proj (trm_rcd l v) l) v | step_beta : forall (e v:exp), lc_exp (trm_abs e) -> value v -> step (trm_app ( (trm_abs e) ) v) (open_exp_wrt_exp e v ) | step_app1 : forall (e1 e2 e1':exp), lc_exp e2 -> step e1 e1' -> step (trm_app e1 e2) (trm_app e1' e2) | step_app2 : forall (v1 e2 e2':exp), value v1 -> step e2 e2' -> step (trm_app v1 e2) (trm_app v1 e2') | step_pair1 : forall (e1 e2 e1':exp), lc_exp e2 -> step e1 e1' -> step (trm_pair e1 e2) (trm_pair e1' e2) | step_pair2 : forall (v1 e2 e2':exp), value v1 -> step e2 e2' -> step (trm_pair v1 e2) (trm_pair v1 e2') | step_capp : forall (c:co) (e e':exp), step e e' -> step (trm_capp c e) (trm_capp c e') | step_rcd1 : forall (l:i) (e e':exp), step e e' -> step (trm_rcd l e) (trm_rcd l e') | step_rcd2 : forall (e:exp) (l:i) (e':exp), step e e' -> step (trm_proj e l) (trm_proj e' l). (** infrastructure *) Hint Constructors sub ASub disjoint has_type CTyp cotyp typing value step lc_exp lc_sexp lc_cc lc_C.
```javascript %%javascript MathJax.Hub.Config({TeX: { equationNumbers: { autoNumber: "AMS" } }}); ``` <IPython.core.display.Javascript object> # BMFLC - band-limited multiple-FLC The band-limited multiple-FLC (BMFLC) \cite{BMFLC1,BMFLC2} is based on the concepts of the WFLC algorithm. The WFLC algorithm adapts to a single frequency present in the tremor signal, but for tremor signals modulated by two or more frequencies close in the spectral domain, the performance of the WFLC will degrade. In such cases, the frequency adaption process of the WFLC will never stabilize, and accurate estimation will never be attained. To overcome this weakness, the BMFLC can track multiple frequency components in the incoming signal. Instead of having one variable frequency $w_{0_k}$ that adapts to the fundamental frequency of the tremor like with the WFLC, the BMFLC predefines a band of frequencies $[\omega_1-\omega_n]$, and then divide the frequency band into $n$ finite divisions, with distance $\Delta w$ between them, as shown in the second figure. In the first figure we can see that $n$-FLCs are combined to form the BMFLC, this algorithm is now capable of estimating a signal with multiple dominant frequencies. In this [paper](https://onlinelibrary.wiley.com/doi/abs/10.1002/rcs.340), to compare the efficiency of the WFLC and BMFLC, they used a modulating sinusoidal signal with two frequencies \eqref{eq:BMFLC_testsignal}, simulating a tremor signal. When the two frequencies in the signal where equal, the WFLC slightly outperformed the BMFLC, but when the frequency gap increase, the WFLC fails to adapt to the modulated signal. The BMFLC is not affected by the frequency gap. When setting the value of $\Delta w$ to 0.1-0.5, estimation accuracy of 96-98\% was obtained with the BMFLC. \begin{equation} y_k=\sum_{r=1}^{n}a_{rk}\sin(\omega_r k )+b_{rk}\cos(\omega_rk) \end{equation} \begin{align} \textbf{x}_k&= \begin{bmatrix} [\sin(\omega_1k)&\sin(\omega_2k)&\cdots&\sin(\omega_nk)]^T \\ [\cos(\omega_1k)&\cos(\omega_2k)&\cdots&\cos(\omega_nk)]^T \end{bmatrix}\\ \textbf{w}_k&=\begin{bmatrix} [a_{1k}&a_{2k}&\cdots & a_{nk}]^T\\ [b_{1k}&b_{2k}&\cdots & b_{nk}]^T \end{bmatrix} \\ y_k&=\textbf{w}_k^T\textbf{x}_k\\ \varepsilon_k&=s_k-y_k\\ \textbf{w}_{k+1}&=\textbf{w}_k+2\mu\textbf{x}_k\epsilon_k \end{align} \begin{equation}\label{eq:BMFLC_testsignal} s_k=3.5\sin(2\pi f_1 t) + 2.5\cos(2\pi f_2 t) \end{equation}
module Data.Buffer import System.Directory import System.File import System.FFI import Data.List %default total -- Reading and writing binary buffers. Note that this primitives are unsafe, -- in that they don't check that buffer locations are within bounds. -- We really need a safe wrapper! -- They are used in the Idris compiler itself for reading/writing checked -- files. -- This is known to the compiler, so maybe ought to be moved to Builtin export data Buffer : Type where [external] bufferClass : String bufferClass = "io/github/mmhelloworld/idrisjvm/runtime/IdrisBuffer" stringsClass : String stringsClass = "io/github/mmhelloworld/idrisjvm/runtime/Strings" %foreign "scheme:blodwen-buffer-size" "RefC:getBufferSize" "node:lambda:b => BigInt(b.length)" jvm bufferClass "size" prim__bufferSize : Buffer -> Int export %inline rawSize : HasIO io => Buffer -> io Int rawSize buf = pure (prim__bufferSize buf) %foreign "scheme:blodwen-new-buffer" "RefC:newBuffer" "node:lambda:s=>Buffer.alloc(Number(s))" jvm bufferClass "create" prim__newBuffer : Int -> PrimIO Buffer export newBuffer : HasIO io => Int -> io (Maybe Buffer) newBuffer size = if size >= 0 then do buf <- primIO (prim__newBuffer size) pure $ Just buf else pure Nothing -- if prim__nullAnyPtr buf /= 0 -- then pure Nothing -- else pure $ Just $ MkBuffer buf size 0 %foreign "scheme:blodwen-buffer-setbyte" "RefC:setBufferByte" "node:lambda:(buf,offset,value)=>buf.writeUInt8(Number(value), Number(offset))" jvm bufferClass "setByte" prim__setByte : Buffer -> Int -> Int -> PrimIO () %foreign "scheme:blodwen-buffer-setbyte" "RefC:setBufferByte" "node:lambda:(buf,offset,value)=>buf.writeUInt8(Number(value), Number(offset))" jvm bufferClass "setByte" prim__setBits8 : Buffer -> Int -> Bits8 -> PrimIO () -- Assumes val is in the range 0-255 export %inline setByte : HasIO io => Buffer -> (loc : Int) -> (val : Int) -> io () setByte buf loc val = primIO (prim__setByte buf loc val) export %inline setBits8 : HasIO io => Buffer -> (loc : Int) -> (val : Bits8) -> io () setBits8 buf loc val = primIO (prim__setBits8 buf loc val) %foreign "scheme:blodwen-buffer-getbyte" "RefC:getBufferByte" "node:lambda:(buf,offset)=>BigInt(buf.readUInt8(Number(offset)))" jvm bufferClass "getByte" prim__getByte : Buffer -> Int -> PrimIO Int %foreign "scheme:blodwen-buffer-getbyte" "RefC:getBufferByte" "node:lambda:(buf,offset)=>BigInt(buf.readUInt8(Number(offset)))" jvm bufferClass "getByte" prim__getBits8 : Buffer -> Int -> PrimIO Bits8 export %inline getByte : HasIO io => Buffer -> (loc : Int) -> io Int getByte buf loc = primIO (prim__getByte buf loc) export %inline getBits8 : HasIO io => Buffer -> (loc : Int) -> io Bits8 getBits8 buf loc = primIO (prim__getBits8 buf loc) %foreign "scheme:blodwen-buffer-setbits16" "node:lambda:(buf,offset,value)=>buf.writeUInt16LE(Number(value), Number(offset))" jvm bufferClass "setShort" prim__setBits16 : Buffer -> Int -> Bits16 -> PrimIO () export %inline setBits16 : HasIO io => Buffer -> (loc : Int) -> (val : Bits16) -> io () setBits16 buf loc val = primIO (prim__setBits16 buf loc val) %foreign "scheme:blodwen-buffer-getbits16" "node:lambda:(buf,offset)=>BigInt(buf.readUInt16LE(Number(offset)))" jvm bufferClass "getShort" prim__getBits16 : Buffer -> Int -> PrimIO Bits16 export %inline getBits16 : HasIO io => Buffer -> (loc : Int) -> io Bits16 getBits16 buf loc = primIO (prim__getBits16 buf loc) %foreign "scheme:blodwen-buffer-setbits32" "node:lambda:(buf,offset,value)=>buf.writeUInt32LE(Number(value), Number(offset))" jvm bufferClass "setInt" prim__setBits32 : Buffer -> Int -> Bits32 -> PrimIO () export %inline setBits32 : HasIO io => Buffer -> (loc : Int) -> (val : Bits32) -> io () setBits32 buf loc val = primIO (prim__setBits32 buf loc val) %foreign "scheme:blodwen-buffer-getbits32" "node:lambda:(buf,offset)=>BigInt(buf.readUInt32LE(Number(offset)))" jvm bufferClass "getInt" prim__getBits32 : Buffer -> Int -> PrimIO Bits32 export %inline getBits32 : HasIO io => Buffer -> (loc : Int) -> io Bits32 getBits32 buf loc = primIO (prim__getBits32 buf loc) %foreign "scheme:blodwen-buffer-setbits64" jvm bufferClass "setLong" prim__setBits64 : Buffer -> Int -> Bits64 -> PrimIO () export %inline setBits64 : HasIO io => Buffer -> (loc : Int) -> (val : Bits64) -> io () setBits64 buf loc val = primIO (prim__setBits64 buf loc val) %foreign "scheme:blodwen-buffer-getbits64" jvm bufferClass "getLong" prim__getBits64 : Buffer -> Int -> PrimIO Bits64 export %inline getBits64 : HasIO io => Buffer -> (loc : Int) -> io Bits64 getBits64 buf loc = primIO (prim__getBits64 buf loc) %foreign "scheme:blodwen-buffer-setint32" "node:lambda:(buf,offset,value)=>buf.writeInt32LE(Number(value), Number(offset))" jvm bufferClass "setInt" prim__setInt32 : Buffer -> Int -> Int -> PrimIO () export %inline setInt32 : HasIO io => Buffer -> (loc : Int) -> (val : Int) -> io () setInt32 buf loc val = primIO (prim__setInt32 buf loc val) %foreign "scheme:blodwen-buffer-getint32" "node:lambda:(buf,offset)=>BigInt(buf.readInt32LE(Number(offset)))" jvm bufferClass "getInt" prim__getInt32 : Buffer -> Int -> PrimIO Int export %inline getInt32 : HasIO io => Buffer -> (loc : Int) -> io Int getInt32 buf loc = primIO (prim__getInt32 buf loc) %foreign "scheme:blodwen-buffer-setint" "RefC:setBufferInt" "node:lambda:(buf,offset,value)=>buf.writeInt64(Number(value), Number(offset))" jvm bufferClass "setInt" prim__setInt : Buffer -> Int -> Int -> PrimIO () export %inline setInt : HasIO io => Buffer -> (loc : Int) -> (val : Int) -> io () setInt buf loc val = primIO (prim__setInt buf loc val) %foreign "scheme:blodwen-buffer-getint" "RefC:getBufferInt" "node:lambda:(buf,offset)=>BigInt(buf.readInt64(Number(offset)))" jvm bufferClass "getInt" prim__getInt : Buffer -> Int -> PrimIO Int export %inline getInt : HasIO io => Buffer -> (loc : Int) -> io Int getInt buf loc = primIO (prim__getInt buf loc) %foreign "scheme:blodwen-buffer-setdouble" "RefC:setBufferDouble" "node:lambda:(buf,offset,value)=>buf.writeDoubleLE(value, Number(offset))" jvm bufferClass "setDouble" prim__setDouble : Buffer -> Int -> Double -> PrimIO () export %inline setDouble : HasIO io => Buffer -> (loc : Int) -> (val : Double) -> io () setDouble buf loc val = primIO (prim__setDouble buf loc val) %foreign "scheme:blodwen-buffer-getdouble" "RefC:getBufferDouble" "node:lambda:(buf,offset)=>buf.readDoubleLE(Number(offset))" jvm bufferClass "getDouble" prim__getDouble : Buffer -> Int -> PrimIO Double export %inline getDouble : HasIO io => Buffer -> (loc : Int) -> io Double getDouble buf loc = primIO (prim__getDouble buf loc) -- Get the length of a string in bytes, rather than characters export %foreign "C:strlen,libc 6" jvm stringsClass "bytesLengthUtf8" stringByteLength : String -> Int %foreign "scheme:blodwen-buffer-setstring" "RefC:setBufferString" "node:lambda:(buf,offset,value)=>buf.write(value, Number(offset),buf.length - Number(offset), 'utf-8')" jvm bufferClass "setString" prim__setString : Buffer -> Int -> String -> PrimIO () export %inline setString : HasIO io => Buffer -> (loc : Int) -> (val : String) -> io () setString buf loc val = primIO (prim__setString buf loc val) %foreign "scheme:blodwen-buffer-getstring" "RefC:getBufferString" "node:lambda:(buf,offset,len)=>buf.slice(Number(offset), Number(offset+len)).toString('utf-8')" jvm bufferClass "getString" prim__getString : Buffer -> Int -> Int -> PrimIO String export %inline getString : HasIO io => Buffer -> (loc : Int) -> (len : Int) -> io String getString buf loc len = primIO (prim__getString buf loc len) export covering bufferData : HasIO io => Buffer -> io (List Int) bufferData buf = do len <- rawSize buf unpackTo [] len where covering unpackTo : List Int -> Int -> io (List Int) unpackTo acc 0 = pure acc unpackTo acc loc = do val <- getByte buf (loc - 1) unpackTo (val :: acc) (loc - 1) %foreign "scheme:blodwen-buffer-copydata" "RefC:copyBuffer" "node:lambda:(b1,o1,length,b2,o2)=>b1.copy(b2,Number(o2), Number(o1), Number(o1+length))" jvm bufferClass "copy" prim__copyData : Buffer -> Int -> Int -> Buffer -> Int -> PrimIO () export copyData : HasIO io => (src : Buffer) -> (start, len : Int) -> (dest : Buffer) -> (loc : Int) -> io () copyData src start len dest loc = primIO (prim__copyData src start len dest loc) %foreign "C:idris2_readBufferData, libidris2_support, idris_file.h" "RefC:readBufferData" "node:lambda:(f,b,l,m) => BigInt(require('fs').readSync(f.fd,b,Number(l), Number(m)))" "jvm:readFromFile(java/nio/channels/ReadableByteChannel io/github/mmhelloworld/idrisjvm/runtime/IdrisBuffer int int int),io/github/mmhelloworld/idrisjvm/runtime/IdrisBuffer" prim__readBufferData : FilePtr -> Buffer -> Int -> Int -> PrimIO Int %foreign "C:idris2_writeBufferData, libidris2_support, idris_file.h" "RefC:writeBufferData" "node:lambda:(f,b,l,m) => BigInt(require('fs').writeSync(f.fd,b,Number(l), Number(m)))" "jvm:writeToFile(java/nio/channels/WritableByteChannel io/github/mmhelloworld/idrisjvm/runtime/IdrisBuffer int int int),io/github/mmhelloworld/idrisjvm/runtime/IdrisBuffer" prim__writeBufferData : FilePtr -> Buffer -> Int -> Int -> PrimIO Int export readBufferData : HasIO io => File -> Buffer -> (loc : Int) -> -- position in buffer to start adding (maxbytes : Int) -> -- maximums size to read, which must not -- exceed buffer length io (Either FileError ()) readBufferData (FHandle h) buf loc max = do read <- primIO (prim__readBufferData h buf loc max) if read >= 0 then pure (Right ()) else pure (Left FileReadError) export writeBufferData : HasIO io => File -> Buffer -> (loc : Int) -> -- position in buffer to write from (maxbytes : Int) -> -- maximums size to write, which must not -- exceed buffer length io (Either FileError ()) writeBufferData (FHandle h) buf loc max = do written <- primIO (prim__writeBufferData h buf loc max) if written >= 0 then pure (Right ()) else pure (Left FileWriteError) export writeBufferToFile : HasIO io => String -> Buffer -> Int -> io (Either FileError ()) writeBufferToFile fn buf max = do Right f <- openFile fn WriteTruncate | Left err => pure (Left err) Right ok <- writeBufferData f buf 0 max | Left err => pure (Left err) closeFile f pure (Right ok) export createBufferFromFile : HasIO io => String -> io (Either FileError Buffer) createBufferFromFile fn = do Right f <- openFile fn Read | Left err => pure (Left err) Right size <- fileSize f | Left err => pure (Left err) Just buf <- newBuffer size | Nothing => pure (Left FileReadError) Right ok <- readBufferData f buf 0 size | Left err => pure (Left err) closeFile f pure (Right buf) export resizeBuffer : HasIO io => Buffer -> Int -> io (Maybe Buffer) resizeBuffer old newsize = do Just buf <- newBuffer newsize | Nothing => pure Nothing -- If the new buffer is smaller than the old one, just copy what -- fits oldsize <- rawSize old let len = if newsize < oldsize then newsize else oldsize copyData old 0 len buf 0 pure (Just buf) ||| Create a buffer containing the concatenated content from a ||| list of buffers. export concatBuffers : HasIO io => List Buffer -> io (Maybe Buffer) concatBuffers xs = do let sizes = map prim__bufferSize xs let (totalSize, revCumulative) = foldl scanSize (0,[]) sizes let cumulative = reverse revCumulative Just buf <- newBuffer totalSize | Nothing => pure Nothing traverse_ (\(b, size, watermark) => copyData b 0 size buf watermark) (zip3 xs sizes cumulative) pure (Just buf) where scanSize : (Int, List Int) -> Int -> (Int, List Int) scanSize (s, cs) x = (s+x, s::cs) ||| Split a buffer into two at a position. export splitBuffer : HasIO io => Buffer -> Int -> io (Maybe (Buffer, Buffer)) splitBuffer buf pos = do size <- rawSize buf if pos > 0 && pos < size then do Just first <- newBuffer pos | Nothing => pure Nothing Just second <- newBuffer (size - pos) | Nothing => pure Nothing copyData buf 0 pos first 0 copyData buf pos (size-pos) second 0 pure $ Just (first, second) else pure Nothing
lemma contour_integral_reversepath: assumes "valid_path g" shows "contour_integral (reversepath g) f = - (contour_integral g f)"
{-# OPTIONS --cubical --no-import-sorts --no-exact-split --safe #-} module Cubical.Experiments.NatMinusTwo.Base where open import Cubical.Core.Primitives open import Cubical.Data.Nat open import Cubical.Data.Empty record ℕ₋₂ : Type₀ where constructor -2+_ field n : ℕ pattern neg2 = -2+ zero pattern neg1 = -2+ (suc zero) pattern ℕ→ℕ₋₂ n = -2+ (suc (suc n)) pattern -1+_ n = -2+ (suc n) 2+_ : ℕ₋₂ → ℕ 2+ (-2+ n) = n pred₋₂ : ℕ₋₂ → ℕ₋₂ pred₋₂ neg2 = neg2 pred₋₂ neg1 = neg2 pred₋₂ (ℕ→ℕ₋₂ zero) = neg1 pred₋₂ (ℕ→ℕ₋₂ (suc n)) = (ℕ→ℕ₋₂ n) suc₋₂ : ℕ₋₂ → ℕ₋₂ suc₋₂ (-2+ n) = -2+ (suc n) -- Natural number and negative integer literals for ℕ₋₂ open import Cubical.Data.Nat.Literals public instance fromNatℕ₋₂ : HasFromNat ℕ₋₂ fromNatℕ₋₂ = record { Constraint = λ _ → Unit ; fromNat = ℕ→ℕ₋₂ } instance fromNegℕ₋₂ : HasFromNeg ℕ₋₂ fromNegℕ₋₂ = record { Constraint = λ { (suc (suc (suc _))) → ⊥ ; _ → Unit } ; fromNeg = λ { zero → 0 ; (suc zero) → neg1 ; (suc (suc zero)) → neg2 } }
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.finset.prod import data.sym.sym2 /-! # Symmetric powers of a finset This file defines the symmetric powers of a finset as `finset (sym α n)` and `finset (sym2 α)`. ## Main declarations * `finset.sym`: The symmetric power of a finset. `s.sym n` is all the multisets of cardinality `n` whose elements are in `s`. * `finset.sym2`: The symmetric square of a finset. `s.sym2` is all the pairs whose elements are in `s`. ## TODO `finset.sym` forms a Galois connection between `finset α` and `finset (sym α n)`. Similar for `finset.sym2`. -/ namespace finset variables {α : Type*} [decidable_eq α] {s t : finset α} {a b : α} lemma is_diag_mk_of_mem_diag {a : α × α} (h : a ∈ s.diag) : sym2.is_diag ⟦a⟧ := (sym2.is_diag_iff_proj_eq _).2 ((mem_diag _ _).1 h).2 lemma not_is_diag_mk_of_mem_off_diag {a : α × α} (h : a ∈ s.off_diag) : ¬ sym2.is_diag ⟦a⟧ := by { rw sym2.is_diag_iff_proj_eq, exact ((mem_off_diag _ _).1 h).2.2 } section sym2 variables {m : sym2 α} /-- Lifts a finset to `sym2 α`. `s.sym2` is the finset of all pairs with elements in `s`. -/ protected def sym2 (s : finset α) : finset (sym2 α) := (s.product s).image quotient.mk @[simp] lemma mem_sym2_iff : m ∈ s.sym2 ↔ ∀ a ∈ m, a ∈ s := begin refine mem_image.trans ⟨_, λ h, ⟨m.out, mem_product.2 ⟨h _ m.out_fst_mem, h _ m.out_snd_mem⟩, m.out_eq⟩⟩, rintro ⟨⟨a, b⟩, h, rfl⟩, rw sym2.ball, rwa mem_product at h, end lemma mk_mem_sym2_iff : ⟦(a, b)⟧ ∈ s.sym2 ↔ a ∈ s ∧ b ∈ s := by rw [mem_sym2_iff, sym2.ball] @[simp] lemma sym2_empty : (∅ : finset α).sym2 = ∅ := rfl @[simp] lemma sym2_eq_empty : s.sym2 = ∅ ↔ s = ∅ := by rw [finset.sym2, image_eq_empty, product_eq_empty, or_self] @[simp] lemma sym2_nonempty : s.sym2.nonempty ↔ s.nonempty := by rw [finset.sym2, nonempty.image_iff, nonempty_product, and_self] alias sym2_nonempty ↔ _ nonempty.sym2 attribute [protected] nonempty.sym2 @[simp] lemma sym2_univ [fintype α] : (univ : finset α).sym2 = univ := rfl @[simp] lemma sym2_singleton (a : α) : ({a} : finset α).sym2 = {sym2.diag a} := by rw [finset.sym2, singleton_product_singleton, image_singleton, sym2.diag] @[simp] lemma diag_mem_sym2_iff : sym2.diag a ∈ s.sym2 ↔ a ∈ s := mk_mem_sym2_iff.trans $ and_self _ @[simp] lemma sym2_mono (h : s ⊆ t) : s.sym2 ⊆ t.sym2 := λ m he, mem_sym2_iff.2 $ λ a ha, h $ mem_sym2_iff.1 he _ ha lemma image_diag_union_image_off_diag : s.diag.image quotient.mk ∪ s.off_diag.image quotient.mk = s.sym2 := by { rw [←image_union, diag_union_off_diag], refl } end sym2 section sym variables {n : ℕ} {m : sym α n} /-- Lifts a finset to `sym α n`. `s.sym n` is the finset of all unordered tuples of cardinality `n` with elements in `s`. -/ protected def sym (s : finset α) : Π n, finset (sym α n) | 0 := {∅} | (n + 1) := s.sup $ λ a, (sym n).image $ _root_.sym.cons a @[simp] lemma sym_zero : s.sym 0 = {∅} := rfl @[simp] lemma sym_succ : s.sym (n + 1) = s.sup (λ a, (s.sym n).image $ sym.cons a) := rfl @[simp] lemma mem_sym_iff : m ∈ s.sym n ↔ ∀ a ∈ m, a ∈ s := begin induction n with n ih, { refine mem_singleton.trans ⟨_, λ _, sym.eq_nil_of_card_zero _⟩, rintro rfl, exact λ a ha, ha.elim }, refine mem_sup.trans ⟨_, λ h, _⟩, { rintro ⟨a, ha, he⟩ b hb, rw mem_image at he, obtain ⟨m, he, rfl⟩ := he, rw sym.mem_cons at hb, obtain rfl | hb := hb, { exact ha }, { exact ih.1 he _ hb } }, { obtain ⟨a, m, rfl⟩ := m.exists_eq_cons_of_succ, exact ⟨a, h _ $ sym.mem_cons_self _ _, mem_image_of_mem _ $ ih.2 $ λ b hb, h _ $ sym.mem_cons_of_mem hb⟩ } end @[simp] lemma sym_empty (n : ℕ) : (∅ : finset α).sym (n + 1) = ∅ := rfl lemma repeat_mem_sym (ha : a ∈ s) (n : ℕ) : sym.repeat a n ∈ s.sym n := mem_sym_iff.2 $ λ b hb, by rwa (sym.mem_repeat.1 hb).2 protected lemma nonempty.sym (h : s.nonempty) (n : ℕ) : (s.sym n).nonempty := let ⟨a, ha⟩ := h in ⟨_, repeat_mem_sym ha n⟩ @[simp] lemma sym_singleton (a : α) (n : ℕ) : ({a} : finset α).sym n = {sym.repeat a n} := eq_singleton_iff_nonempty_unique_mem.2 ⟨(singleton_nonempty _).sym n, λ s hs, sym.eq_repeat_iff.2 $ λ b hb, eq_of_mem_singleton $ mem_sym_iff.1 hs _ hb⟩ lemma eq_empty_of_sym_eq_empty (h : s.sym n = ∅) : s = ∅ := begin rw ←not_nonempty_iff_eq_empty at ⊢ h, exact λ hs, h (hs.sym _), end @[simp] lemma sym_eq_empty : s.sym n = ∅ ↔ n ≠ 0 ∧ s = ∅ := begin cases n, { exact iff_of_false (singleton_ne_empty _) (λ h, (h.1 rfl).elim) }, { refine ⟨λ h, ⟨n.succ_ne_zero, eq_empty_of_sym_eq_empty h⟩, _⟩, rintro ⟨_, rfl⟩, exact sym_empty _ } end @[simp] lemma sym_nonempty : (s.sym n).nonempty ↔ n = 0 ∨ s.nonempty := by simp_rw [nonempty_iff_ne_empty, ne.def, sym_eq_empty, not_and_distrib, not_ne_iff] alias sym2_nonempty ↔ _ nonempty.sym2 attribute [protected] nonempty.sym2 @[simp] lemma sym_univ [fintype α] (n : ℕ) : (univ : finset α).sym n = univ := eq_univ_iff_forall.2 $ λ s, mem_sym_iff.2 $ λ a _, mem_univ _ @[simp] lemma sym_mono (h : s ⊆ t) (n : ℕ): s.sym n ⊆ t.sym n := λ m hm, mem_sym_iff.2 $ λ a ha, h $ mem_sym_iff.1 hm _ ha @[simp] lemma sym_inter (s t : finset α) (n : ℕ) : (s ∩ t).sym n = s.sym n ∩ t.sym n := by { ext m, simp only [mem_inter, mem_sym_iff, imp_and_distrib, forall_and_distrib] } @[simp] lemma sym_union (s t : finset α) (n : ℕ) : s.sym n ∪ t.sym n ⊆ (s ∪ t).sym n := union_subset (sym_mono (subset_union_left s t) n) (sym_mono (subset_union_right s t) n) end sym end finset
--/** -- * <copyright> -- * -- * Copyright (c) 2010, 2009 IBM Corporation and others. -- * All rights reserved. This program and the accompanying materials -- * are made available under the terms of the Eclipse Public License v2.0 -- * which accompanies this distribution, and is available at -- * http://www.eclipse.org/legal/epl-v20.html -- * -- * Contributors: -- * See (or edit) Notice Declaration below -- * -- * </copyright> -- */ -- -- The Essential OCL KeyWord Lexer -- %options slr %options fp=EssentialOCLKWLexer,prefix=Char_ %options noserialize %options package=org.eclipse.ocl.xtext.essentialocl.parser %options template=../lpg/KeywordTemplateF.gi %options export_terminals=("EssentialOCLParsersym.java", "TK_") %options include_directory="../lpg" %Import KWLexerMapF.gi %End %Define -- -- Definition of macros used in the template -- $action_class /.$file_prefix./ $eof_char /.Char_EOF./ $copyright_contributions /.*./ %End %Notice /./** * Essential OCL Keyword Lexer * <copyright> * * Copyright (c) 2010, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v2.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v20.html * * Contributors: * IBM - Initial API and implementation * E.D.Willink - Lexer and Parser refactoring to support extensibility and flexible error handling * E.D.Willink - Bug 285633, 292112 * Adolfo Sanchez-Barbudo Herrera (Open Canarias) - LPG v 2.0.17 adoption (242153) * Adolfo Sanchez-Barbudo Herrera (Open Canarias) - Introducing new LPG templates (299396) $copyright_contributions * </copyright> * * */ ./ %End %Globals /../ %End %Export self if then else endif and or xor not implies let in true false null invalid -- -- the remainder of the LPG keywords are defined as such for the -- purpose of constructing the CST grammar. They are not OCL -- reserved words -- Set Bag Sequence Collection OrderedSet String Integer UnlimitedNatural Real Boolean Tuple OclAny OclVoid OclInvalid %End %Start KeyWord %End %Rules -- The Goal for the parser is a single Keyword KeyWord ::= s e l f /.$BeginAction $setResult($_self); $EndAction ./ | i f /.$BeginAction $setResult($_if); $EndAction ./ | t h e n /.$BeginAction $setResult($_then); $EndAction ./ | e l s e /.$BeginAction $setResult($_else); $EndAction ./ | e n d i f /.$BeginAction $setResult($_endif); $EndAction ./ | a n d /.$BeginAction $setResult($_and); $EndAction ./ | o r /.$BeginAction $setResult($_or); $EndAction ./ | x o r /.$BeginAction $setResult($_xor); $EndAction ./ | n o t /.$BeginAction $setResult($_not); $EndAction ./ | i m p l i e s /.$BeginAction $setResult($_implies); $EndAction ./ | l e t /.$BeginAction $setResult($_let); $EndAction ./ | i n /.$BeginAction $setResult($_in); $EndAction ./ | t r u e /.$BeginAction $setResult($_true); $EndAction ./ | f a l s e /.$BeginAction $setResult($_false); $EndAction ./ | S e t /.$BeginAction $setResult($_Set); $EndAction ./ | B a g /.$BeginAction $setResult($_Bag); $EndAction ./ | S e q u e n c e /.$BeginAction $setResult($_Sequence); $EndAction ./ | C o l l e c t i o n /.$BeginAction $setResult($_Collection); $EndAction ./ | O r d e r e d S e t /.$BeginAction $setResult($_OrderedSet); $EndAction ./ | S t r i n g /.$BeginAction $setResult($_String); $EndAction ./ | I n t e g e r /.$BeginAction $setResult($_Integer); $EndAction ./ | U n l i m i t e d N a t u r a l /.$BeginAction $setResult($_UnlimitedNatural); $EndAction ./ | R e a l /.$BeginAction $setResult($_Real); $EndAction ./ | B o o l e a n /.$BeginAction $setResult($_Boolean); $EndAction ./ | T u p l e /.$BeginAction $setResult($_Tuple); $EndAction ./ | O c l A n y /.$BeginAction $setResult($_OclAny); $EndAction ./ | O c l V o i d /.$BeginAction $setResult($_OclVoid); $EndAction ./ | O c l I n v a l i d /.$BeginAction $setResult($_OclInvalid); $EndAction ./ | n u l l /.$BeginAction $setResult($_null); $EndAction ./ | i n v a l i d /.$BeginAction $setResult($_invalid); $EndAction ./ %End
theory Instance_Graph imports Main Multiplicity_Pair Type_Graph Extended_Graph_Theory begin section "Node set definitions" datatype ('nt, 'lt) NodeDef = typed "'lt LabDef" "'nt" | bool bool | int int | real real | string string | invalid fun nodeType :: "('nt, 'lt) NodeDef \<Rightarrow> ('lt) LabDef" where "nodeType (typed t n) = t" | "nodeType (bool v) = LabDef.bool" | "nodeType (int v) = LabDef.int" | "nodeType (real v) = LabDef.real" | "nodeType (string v) = LabDef.string" | "nodeType invalid = undefined" fun nodeId :: "('nt, 'lt) NodeDef \<Rightarrow> 'nt" where "nodeId (typed t n) = n" | "nodeId _ = undefined" subsection "Typed nodes" inductive_set Node\<^sub>t :: "('nt, 'lt) NodeDef set" where rule_typed_nodes: "\<And>t n. t \<in> Lab\<^sub>t \<Longrightarrow> typed t n \<in> Node\<^sub>t" lemma typed_nodes_member[simp]: "x \<in> Node\<^sub>t \<Longrightarrow> \<exists>y z. x = typed y z" using Node\<^sub>t.cases by blast lemma typed_nodes_contains_no_bool[simp]: "bool x \<notin> Node\<^sub>t" using typed_nodes_member by blast lemma typed_nodes_contains_no_int[simp]: "int x \<notin> Node\<^sub>t" using typed_nodes_member by blast lemma typed_nodes_contains_no_real[simp]: "real x \<notin> Node\<^sub>t" using typed_nodes_member by blast lemma typed_nodes_contains_no_string[simp]: "string x \<notin> Node\<^sub>t" using typed_nodes_member by blast lemma typed_nodes_node_type: "x \<in> Node\<^sub>t \<Longrightarrow> nodeType x \<in> Lab\<^sub>t" using Node\<^sub>t.cases nodeType.simps(1) by metis lemma typed_nodes_not_invalid[simp]: "invalid \<notin> Node\<^sub>t" using typed_nodes_member by blast subsection "Set of value nodes" subsubsection "Boolean nodes" definition BooleanNode\<^sub>v :: "('nt, 'lt) NodeDef set" where "BooleanNode\<^sub>v \<equiv> {bool True, bool False}" fun boolValue :: "('nt, 'lt) NodeDef \<Rightarrow> bool" where "boolValue (bool v) = v" | "boolValue _ = undefined" lemma boolean_nodes_member[simp]: "x \<in> BooleanNode\<^sub>v \<Longrightarrow> x = bool True \<or> x = bool False" by (simp add: BooleanNode\<^sub>v_def) lemma boolean_nodes_contains_no_typed_node[simp]: "typed x y \<notin> BooleanNode\<^sub>v" using boolean_nodes_member by blast lemma boolean_nodes_contains_no_int[simp]: "int x \<notin> BooleanNode\<^sub>v" using boolean_nodes_member by blast lemma boolean_nodes_contains_no_real[simp]: "real x \<notin> BooleanNode\<^sub>v" using boolean_nodes_member by blast lemma boolean_nodes_contains_no_string[simp]: "string x \<notin> BooleanNode\<^sub>v" using boolean_nodes_member by blast lemma boolean_nodes_typed_nodes_intersect[simp]: "BooleanNode\<^sub>v \<inter> Node\<^sub>t = {}" using typed_nodes_member by fastforce lemma boolean_nodes_node_type[simp]: "x \<in> BooleanNode\<^sub>v \<Longrightarrow> nodeType x = LabDef.bool" using boolean_nodes_member nodeType.simps(2) by blast lemma boolean_nodes_not_invalid[simp]: "invalid \<notin> BooleanNode\<^sub>v" using boolean_nodes_member by blast lemma boolean_nodes_value[simp]: "x \<in> BooleanNode\<^sub>v \<Longrightarrow> x = bool y \<Longrightarrow> boolValue x = y" by simp subsubsection "Integer nodes" inductive_set IntegerNode\<^sub>v :: "('nt, 'lt) NodeDef set" where rule_integer_nodes: "\<And>i. int i \<in> IntegerNode\<^sub>v" fun intValue :: "('nt, 'lt) NodeDef \<Rightarrow> int" where "intValue (int v) = v" | "intValue _ = undefined" lemma integer_nodes_member[simp]: "x \<in> IntegerNode\<^sub>v \<Longrightarrow> \<exists>y. x = int y" using IntegerNode\<^sub>v.cases by blast lemma integer_nodes_contains_no_typed_node[simp]: "typed x y \<notin> IntegerNode\<^sub>v" using integer_nodes_member by blast lemma integer_nodes_contains_no_bool[simp]: "bool x \<notin> IntegerNode\<^sub>v" using integer_nodes_member by blast lemma integer_nodes_contains_no_real[simp]: "real x \<notin> IntegerNode\<^sub>v" using integer_nodes_member by blast lemma integer_nodes_contains_no_string[simp]: "string x \<notin> IntegerNode\<^sub>v" using integer_nodes_member by blast lemma integer_nodes_typed_nodes_intersect[simp]: "IntegerNode\<^sub>v \<inter> Node\<^sub>t = {}" using typed_nodes_member by fastforce lemma integer_nodes_boolean_nodes_intersect[simp]: "IntegerNode\<^sub>v \<inter> BooleanNode\<^sub>v = {}" using boolean_nodes_member by fastforce lemma integer_nodes_node_type[simp]: "x \<in> IntegerNode\<^sub>v \<Longrightarrow> nodeType x = LabDef.int" using integer_nodes_member nodeType.simps(3) by blast lemma integer_nodes_not_invalid[simp]: "invalid \<notin> IntegerNode\<^sub>v" using integer_nodes_member by blast lemma integer_nodes_value[simp]: "x \<in> IntegerNode\<^sub>v \<Longrightarrow> x = int y \<Longrightarrow> intValue x = y" by simp subsubsection "Real nodes" inductive_set RealNode\<^sub>v :: "('nt, 'lt) NodeDef set" where rule_real_nodes: "\<And>r. real r \<in> RealNode\<^sub>v" fun realValue :: "('nt, 'lt) NodeDef \<Rightarrow> real" where "realValue (real v) = v" | "realValue _ = undefined" lemma real_nodes_member[simp]: "x \<in> RealNode\<^sub>v \<Longrightarrow> \<exists>y. x = real y" using RealNode\<^sub>v.cases by blast lemma real_nodes_contains_no_typed_node[simp]: "typed x y \<notin> RealNode\<^sub>v" using real_nodes_member by blast lemma real_nodes_contains_no_bool[simp]: "bool x \<notin> RealNode\<^sub>v" using real_nodes_member by blast lemma real_nodes_contains_no_int[simp]: "int x \<notin> RealNode\<^sub>v" using real_nodes_member by blast lemma real_nodes_contains_no_string[simp]: "string x \<notin> RealNode\<^sub>v" using real_nodes_member by blast lemma real_nodes_typed_nodes_intersect[simp]: "RealNode\<^sub>v \<inter> Node\<^sub>t = {}" using typed_nodes_member by fastforce lemma real_nodes_boolean_nodes_intersect[simp]: "RealNode\<^sub>v \<inter> BooleanNode\<^sub>v = {}" using boolean_nodes_member by fastforce lemma real_nodes_integer_nodes_intersect[simp]: "RealNode\<^sub>v \<inter> IntegerNode\<^sub>v = {}" using integer_nodes_member by fastforce lemma real_nodes_node_type[simp]: "x \<in> RealNode\<^sub>v \<Longrightarrow> nodeType x = LabDef.real" using real_nodes_member nodeType.simps(4) by blast lemma real_nodes_not_invalid[simp]: "invalid \<notin> RealNode\<^sub>v" using real_nodes_member by blast lemma real_nodes_value[simp]: "x \<in> RealNode\<^sub>v \<Longrightarrow> x = real y \<Longrightarrow> realValue x = y" by simp subsubsection "String nodes" inductive_set StringNode\<^sub>v :: "('nt, 'lt) NodeDef set" where rule_string_nodes: "\<And>s. string s \<in> StringNode\<^sub>v" fun stringValue :: "('nt, 'lt) NodeDef \<Rightarrow> string" where "stringValue (string v) = v" | "stringValue _ = undefined" lemma string_nodes_member[simp]: "x \<in> StringNode\<^sub>v \<Longrightarrow> \<exists>y. x = string y" using StringNode\<^sub>v.cases by blast lemma string_nodes_contains_no_typed_node[simp]: "typed x y \<notin> StringNode\<^sub>v" using string_nodes_member by blast lemma string_nodes_contains_no_bool[simp]: "bool x \<notin> StringNode\<^sub>v" using string_nodes_member by blast lemma string_nodes_contains_no_int[simp]: "int x \<notin> StringNode\<^sub>v" using string_nodes_member by blast lemma string_nodes_contains_no_real[simp]: "real x \<notin> StringNode\<^sub>v" using string_nodes_member by blast lemma string_nodes_typed_nodes_intersect[simp]: "StringNode\<^sub>v \<inter> Node\<^sub>t = {}" using typed_nodes_member by fastforce lemma string_nodes_boolean_nodes_intersect[simp]: "StringNode\<^sub>v \<inter> BooleanNode\<^sub>v = {}" using boolean_nodes_member by fastforce lemma string_nodes_integer_nodes_intersect[simp]: "StringNode\<^sub>v \<inter> IntegerNode\<^sub>v = {}" using integer_nodes_member by fastforce lemma string_nodes_real_nodes_intersect[simp]: "StringNode\<^sub>v \<inter> RealNode\<^sub>v = {}" using real_nodes_member by fastforce lemma string_nodes_node_type[simp]: "x \<in> StringNode\<^sub>v \<Longrightarrow> nodeType x = LabDef.string" using string_nodes_member nodeType.simps(5) by blast lemma string_nodes_not_invalid[simp]: "invalid \<notin> StringNode\<^sub>v" using string_nodes_member by blast lemma string_nodes_value[simp]: "x \<in> StringNode\<^sub>v \<Longrightarrow> x = string y \<Longrightarrow> stringValue x = y" by simp subsubsection "Value nodes" definition Node\<^sub>v :: "('nt, 'lt) NodeDef set" where "Node\<^sub>v \<equiv> BooleanNode\<^sub>v \<union> IntegerNode\<^sub>v \<union> RealNode\<^sub>v \<union> StringNode\<^sub>v" lemma value_nodes_member[simp]: "x \<in> Node\<^sub>v \<Longrightarrow> x = bool True \<or> x = bool False \<or> (\<exists>y. x = int y) \<or> (\<exists>y. x = real y) \<or> (\<exists>y. x = string y)" unfolding Node\<^sub>v_def using boolean_nodes_member integer_nodes_member real_nodes_member string_nodes_member by blast lemma value_nodes_contains_no_typed_node[simp]: "typed x y \<notin> Node\<^sub>v" using value_nodes_member by blast lemma value_nodes_typed_nodes_intersect[simp]: "Node\<^sub>v \<inter> Node\<^sub>t = {}" using typed_nodes_member by fastforce lemma value_nodes_boolean_nodes_intersect[simp]: "Node\<^sub>v \<inter> BooleanNode\<^sub>v = BooleanNode\<^sub>v" using Node\<^sub>v_def by fastforce lemma value_nodes_integer_nodes_intersect[simp]: "Node\<^sub>v \<inter> IntegerNode\<^sub>v = IntegerNode\<^sub>v" using Node\<^sub>v_def by fastforce lemma value_nodes_real_nodes_intersect[simp]: "Node\<^sub>v \<inter> RealNode\<^sub>v = RealNode\<^sub>v" using Node\<^sub>v_def by fastforce lemma value_nodes_string_nodes_intersect[simp]: "Node\<^sub>v \<inter> StringNode\<^sub>v = StringNode\<^sub>v" using Node\<^sub>v_def by fastforce lemma value_nodes_contain_boolean_nodes[simp]: "BooleanNode\<^sub>v \<subseteq> Node\<^sub>v" using value_nodes_boolean_nodes_intersect by fastforce lemma value_nodes_contain_integer_nodes[simp]: "IntegerNode\<^sub>v \<subseteq> Node\<^sub>v" using value_nodes_integer_nodes_intersect by fastforce lemma value_nodes_contain_real_nodes[simp]: "RealNode\<^sub>v \<subseteq> Node\<^sub>v" using value_nodes_real_nodes_intersect by fastforce lemma value_nodes_contain_string_nodes[simp]: "StringNode\<^sub>v \<subseteq> Node\<^sub>v" using value_nodes_string_nodes_intersect by fastforce lemma value_nodes_node_type: "x \<in> Node\<^sub>v \<Longrightarrow> nodeType x \<in> Lab\<^sub>p" using Lab\<^sub>p_def value_nodes_member by fastforce lemma value_nodes_not_invalid[simp]: "invalid \<notin> Node\<^sub>v" using value_nodes_member by blast subsection "Nodes" definition Node :: "('nt, 'lt) NodeDef set" where "Node \<equiv> Node\<^sub>t \<union> Node\<^sub>v" lemma nodes_typed_nodes_intersect[simp]: "Node \<inter> Node\<^sub>t = Node\<^sub>t" using Node_def by fastforce lemma nodes_value_nodes_intersect[simp]: "Node \<inter> Node\<^sub>v = Node\<^sub>v" using Node_def by fastforce lemma nodes_boolean_nodes_intersect[simp]: "Node \<inter> BooleanNode\<^sub>v = BooleanNode\<^sub>v" using nodes_value_nodes_intersect value_nodes_boolean_nodes_intersect by blast lemma nodes_integer_nodes_intersect[simp]: "Node \<inter> IntegerNode\<^sub>v = IntegerNode\<^sub>v" using nodes_value_nodes_intersect value_nodes_integer_nodes_intersect by blast lemma nodes_real_nodes_intersect[simp]: "Node \<inter> RealNode\<^sub>v = RealNode\<^sub>v" using nodes_value_nodes_intersect value_nodes_real_nodes_intersect by blast lemma nodes_string_nodes_intersect[simp]: "Node \<inter> StringNode\<^sub>v = StringNode\<^sub>v" using nodes_value_nodes_intersect value_nodes_string_nodes_intersect by blast lemma nodes_contain_typed_nodes[simp]: "Node\<^sub>t \<subseteq> Node" using nodes_typed_nodes_intersect by fastforce lemma nodes_contain_value_nodes[simp]: "Node\<^sub>v \<subseteq> Node" using nodes_value_nodes_intersect by fastforce lemma nodes_contain_boolean_nodes[simp]: "BooleanNode\<^sub>v \<subseteq> Node" using nodes_boolean_nodes_intersect by fastforce lemma nodes_contain_integer_nodes[simp]: "IntegerNode\<^sub>v \<subseteq> Node" using nodes_integer_nodes_intersect by fastforce lemma nodes_contain_real_nodes[simp]: "RealNode\<^sub>v \<subseteq> Node" using nodes_real_nodes_intersect by fastforce lemma nodes_contain_string_nodes[simp]: "StringNode\<^sub>v \<subseteq> Node" using nodes_string_nodes_intersect by fastforce lemma nodes_node_type: "x \<in> Node \<Longrightarrow> nodeType x \<in> Lab\<^sub>t \<union> Lab\<^sub>p" using Node_def typed_nodes_node_type value_nodes_node_type by auto lemma nodes_not_invalid[simp]: "invalid \<notin> Node" unfolding Node_def by simp section "Instance graph tuple definition" record ('nt, 'lt, 'id) instance_graph = TG :: "('lt) type_graph" Id :: "'id set" N :: "('nt, 'lt) NodeDef set" E :: "(('nt, 'lt) NodeDef \<times> ('lt LabDef \<times> 'lt LabDef \<times> 'lt LabDef) \<times> ('nt, 'lt) NodeDef) set" ident :: "'id \<Rightarrow> ('nt, 'lt) NodeDef" section "Types" definition type\<^sub>n :: "('nt, 'lt) NodeDef \<Rightarrow> 'lt LabDef" where "type\<^sub>n \<equiv> nodeType" declare type\<^sub>n_def[simp add] definition type\<^sub>e :: "('nt, 'lt) NodeDef \<times> ('lt LabDef \<times> 'lt LabDef \<times> 'lt LabDef) \<times> ('nt, 'lt) NodeDef \<Rightarrow> 'lt LabDef \<times> 'lt LabDef \<times> 'lt LabDef" where "type\<^sub>e e \<equiv> fst (snd e)" declare type\<^sub>e_def[simp add] section "Graph theory projection" definition instance_graph_proj :: "('nt, 'lt, 'id) instance_graph \<Rightarrow> (('nt, 'lt) NodeDef, ('nt, 'lt) NodeDef \<times> ('lt LabDef \<times> 'lt LabDef \<times> 'lt LabDef) \<times> ('nt, 'lt) NodeDef) pre_digraph" where "instance_graph_proj IG = \<lparr> verts = N IG, arcs = E IG, tail = tgt, head = src \<rparr>" declare [[coercion instance_graph_proj]] definition instance_graph_containment_proj :: "('nt, 'lt, 'id) instance_graph \<Rightarrow> (('nt, 'lt) NodeDef, ('nt, 'lt) NodeDef \<times> ('lt LabDef \<times> 'lt LabDef \<times> 'lt LabDef) \<times> ('nt, 'lt) NodeDef) pre_digraph" where "instance_graph_containment_proj IG = \<lparr> verts = N IG, arcs = { e \<in> E IG. type\<^sub>e e \<in> contains (TG IG) }, tail = tgt, head = src \<rparr>" section "Instance graph validity" locale instance_graph = fixes IG :: "('nt, 'lt, 'id) instance_graph" assumes structure_nodes_wellformed[simp]: "\<And>n. n \<in> N IG \<Longrightarrow> n \<in> Node" assumes structure_edges_wellformed: "\<And>s l t. (s, l, t) \<in> E IG \<Longrightarrow> s \<in> N IG \<and> l \<in> ET (TG IG) \<and> t \<in> N IG" assumes structure_ident_wellformed: "\<And>i. i \<in> Id IG \<Longrightarrow> ident IG i \<in> N IG \<and> type\<^sub>n (ident IG i) \<in> Lab\<^sub>t" assumes structure_ident_domain[simp]: "\<And>i. i \<notin> Id IG \<Longrightarrow> ident IG i = undefined" assumes validity_type_graph[simp]: "type_graph (TG IG)" assumes validity_node_typed[simp]: "\<And>n. n \<in> N IG \<Longrightarrow> type\<^sub>n n \<in> NT (TG IG)" assumes validity_edge_src_typed[simp]: "\<And>e. e \<in> E IG \<Longrightarrow> (type\<^sub>n (src e), src (type\<^sub>e e)) \<in> inh (TG IG)" assumes validity_edge_tgt_typed[simp]: "\<And>e. e \<in> E IG \<Longrightarrow> (type\<^sub>n (tgt e), tgt (type\<^sub>e e)) \<in> inh (TG IG)" assumes validity_abs_no_instances[simp]: "\<And>n. n \<in> N IG \<Longrightarrow> type\<^sub>n n \<notin> abs (TG IG)" assumes validity_outgoing_mult[simp]: "\<And>et n. et \<in> ET (TG IG) \<Longrightarrow> n \<in> N IG \<Longrightarrow> (type\<^sub>n n, src et) \<in> inh (TG IG) \<Longrightarrow> card { e. e \<in> E IG \<and> src e = n \<and> type\<^sub>e e = et} in m_out (mult (TG IG) et)" assumes validity_ingoing_mult[simp]: "\<And>et n. et \<in> ET (TG IG) \<Longrightarrow> n \<in> N IG \<Longrightarrow> (type\<^sub>n n, tgt et) \<in> inh (TG IG) \<Longrightarrow> card { e. e \<in> E IG \<and> tgt e = n \<and> type\<^sub>e e = et} in m_in (mult (TG IG) et)" assumes validity_contained_node[simp]: "\<And>n. n \<in> N IG \<Longrightarrow> card { e. e \<in> E IG \<and> tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG) } \<le> 1" assumes validity_containment[simp]: "\<And>p. \<not>pre_digraph.cycle (instance_graph_containment_proj IG) p" context instance_graph begin lemma structure_edges_wellformed_src_node[simp]: "\<And>s. (s, l, t) \<in> E IG \<Longrightarrow> s \<in> N IG" by (simp add: structure_edges_wellformed) lemma structure_edges_wellformed_edge_type[simp]: "\<And>l. (s, l, t) \<in> E IG \<Longrightarrow> l \<in> ET (TG IG)" by (simp add: structure_edges_wellformed) lemma structure_edges_wellformed_tgt_node[simp]: "\<And>t. (s, l, t) \<in> E IG \<Longrightarrow> t \<in> N IG" by (simp add: structure_edges_wellformed) lemma structure_edges_wellformed_alt: "\<And>e. e \<in> E IG \<Longrightarrow> src e \<in> N IG \<and> type\<^sub>e e \<in> ET (TG IG) \<and> tgt e \<in> N IG" by auto lemma structure_edges_wellformed_src_node_alt[simp]: "\<And>e. e \<in> E IG \<Longrightarrow> src e \<in> N IG" by auto lemma structure_edges_wellformed_edge_type_alt[simp]: "\<And>e. e \<in> E IG \<Longrightarrow> type\<^sub>e e \<in> ET (TG IG)" by auto lemma structure_edges_wellformed_tgt_node_alt[simp]: "\<And>e. e \<in> E IG \<Longrightarrow> tgt e \<in> N IG" by auto lemma structure_ident_wellformed_node[simp]: "\<And>i. i \<in> Id IG \<Longrightarrow> ident IG i \<in> N IG" using structure_ident_wellformed by blast lemma structure_ident_wellformed_node_type[simp]: "\<And>i. i \<in> Id IG \<Longrightarrow> type\<^sub>n (ident IG i) \<in> Lab\<^sub>t" using structure_ident_wellformed by blast lemma validity_edge_src_typed_alt[simp]: "\<And>s l t. (s, l, t) \<in> E IG \<Longrightarrow> (type\<^sub>n s, src l) \<in> inh (TG IG)" proof- fix s l t assume "(s, l, t) \<in> E IG" then have "(type\<^sub>n (src (s, l, t)), src (type\<^sub>e (s, l, t))) \<in> inh (TG IG)" by (fact validity_edge_src_typed) then show "(type\<^sub>n s, src l) \<in> inh (TG IG)" by simp qed lemma validity_edge_tgt_typed_alt[simp]: "\<And>s l t. (s, l, t) \<in> E IG \<Longrightarrow> (type\<^sub>n t, tgt l) \<in> inh (TG IG)" proof- fix s l t assume "(s, l, t) \<in> E IG" then have "(type\<^sub>n (tgt (s, l, t)), tgt (type\<^sub>e (s, l, t))) \<in> inh (TG IG)" by (fact validity_edge_tgt_typed) then show "(type\<^sub>n t, tgt l) \<in> inh (TG IG)" by simp qed lemma validity_contained_node_alt[simp]: "\<And>n. n \<in> N IG \<Longrightarrow> card { (s, l, t). (s, l, t) \<in> E IG \<and> t = n \<and> l \<in> contains (TG IG) } \<le> 1" proof- fix n assume n_in_nodes: "n \<in> N IG" have "{ e. e \<in> E IG \<and> tgt e = n \<and> type\<^sub>e e \<in> contains (TG IG) } = { (s, l, t). (s, l, t) \<in> E IG \<and> tgt (s, l, t) = n \<and> type\<^sub>e (s, l, t) \<in> contains (TG IG) }" by blast then have "card { (s, l, t). (s, l, t) \<in> E IG \<and> tgt (s, l, t) = n \<and> type\<^sub>e (s, l, t) \<in> contains (TG IG) } \<le> 1" using n_in_nodes validity_contained_node by fastforce then show "card { (s, l, t). (s, l, t) \<in> E IG \<and> t = n \<and> l \<in> contains (TG IG) } \<le> 1" by simp qed end section "Graph theory compatibility" sublocale instance_graph \<subseteq> pre_digraph "instance_graph_proj IG" rewrites "verts IG = N IG" and "arcs IG = E IG" and "tail IG = tgt" and "head IG = src" by unfold_locales (simp_all add: instance_graph_proj_def) sublocale instance_graph \<subseteq> wf_digraph IG proof have verts_are_nodes: "verts (instance_graph_proj IG) = N IG" by (simp add: instance_graph_proj_def) have head_is_src: "head (instance_graph_proj IG) = src" by (simp add: instance_graph_proj_def) have tail_is_tgt: "tail (instance_graph_proj IG) = tgt" by (simp add: instance_graph_proj_def) fix e assume "e \<in> arcs (instance_graph_proj IG)" then have e_in_edges: "e \<in> E IG" by (simp add: instance_graph_proj_def) show "tail (instance_graph_proj IG) e \<in> verts (instance_graph_proj IG)" using e_in_edges verts_are_nodes tail_is_tgt structure_edges_wellformed_tgt_node_alt by auto show "head (instance_graph_proj IG) e \<in> verts (instance_graph_proj IG)" using e_in_edges verts_are_nodes head_is_src structure_edges_wellformed_src_node_alt by auto qed lemma validity_containment_alt: assumes structure_edges_wellformed: "\<And>e. e \<in> E IG \<Longrightarrow> type\<^sub>e e \<in> contains (TG IG) \<Longrightarrow> src e \<in> N IG \<and> tgt e \<in> N IG" assumes validity_containment: "\<And>p. \<not>pre_digraph.cycle (instance_graph_containment_proj IG) p" shows "irrefl ((edge_to_tuple ` { e \<in> E IG. type\<^sub>e e \<in> contains (TG IG) })\<^sup>+)" proof- have "irrefl ((pre_digraph.arc_to_tuple (instance_graph_containment_proj IG) ` arcs (instance_graph_containment_proj IG))\<^sup>+)" proof (intro wf_digraph.acyclic_impl_irrefl_trancl) show "wf_digraph (instance_graph_containment_proj IG)" proof (intro wf_digraph.intro) fix e assume "e \<in> arcs (instance_graph_containment_proj IG)" then have "e \<in> { e \<in> E IG. type\<^sub>e e \<in> contains (TG IG) }" unfolding instance_graph_containment_proj_def by simp then show "tail (instance_graph_containment_proj IG) e \<in> verts (instance_graph_containment_proj IG)" unfolding instance_graph_containment_proj_def using structure_edges_wellformed by simp next fix e assume "e \<in> arcs (instance_graph_containment_proj IG)" then have "e \<in> { e \<in> E IG. type\<^sub>e e \<in> contains (TG IG) }" unfolding instance_graph_containment_proj_def by simp then show "head (instance_graph_containment_proj IG) e \<in> verts (instance_graph_containment_proj IG)" unfolding instance_graph_containment_proj_def using structure_edges_wellformed by simp qed next show "\<And>p. \<not>pre_digraph.cycle (instance_graph_containment_proj IG) p" by (fact validity_containment) qed then show "irrefl ((edge_to_tuple ` { e \<in> E IG. type\<^sub>e e \<in> contains (TG IG) })\<^sup>+)" unfolding pre_digraph.arc_to_tuple_def edge_to_tuple_def instance_graph_containment_proj_def by simp qed lemma (in instance_graph) validity_containment_alt': shows "irrefl ((edge_to_tuple ` { e \<in> E IG. type\<^sub>e e \<in> contains (TG IG) })\<^sup>+)" proof (intro validity_containment_alt) show "\<And>e. e \<in> E IG \<Longrightarrow> type\<^sub>e e \<in> contains (TG IG) \<Longrightarrow> src e \<in> N IG \<and> tgt e \<in> N IG" by fastforce next show "\<And>p. \<not>pre_digraph.cycle (instance_graph_containment_proj IG) p" by simp qed lemma validity_containmentI[intro]: assumes structure_edges_wellformed: "\<And>e. e \<in> E IG \<Longrightarrow> type\<^sub>e e \<in> contains (TG IG) \<Longrightarrow> src e \<in> N IG \<and> tgt e \<in> N IG" assumes irrefl_contains_edges: "irrefl ((edge_to_tuple ` { e \<in> E IG. type\<^sub>e e \<in> contains (TG IG) })\<^sup>+)" shows "\<not>pre_digraph.cycle (instance_graph_containment_proj IG) p" proof (intro wf_digraph.irrefl_trancl_impl_acyclic) show "wf_digraph (instance_graph_containment_proj IG)" proof (intro wf_digraph.intro) fix e assume "e \<in> arcs (instance_graph_containment_proj IG)" then have "e \<in> { e \<in> E IG. type\<^sub>e e \<in> contains (TG IG) }" unfolding instance_graph_containment_proj_def by simp then show "tail (instance_graph_containment_proj IG) e \<in> verts (instance_graph_containment_proj IG)" unfolding instance_graph_containment_proj_def using structure_edges_wellformed by simp next fix e assume "e \<in> arcs (instance_graph_containment_proj IG)" then have "e \<in> { e \<in> E IG. type\<^sub>e e \<in> contains (TG IG) }" unfolding instance_graph_containment_proj_def by simp then show "head (instance_graph_containment_proj IG) e \<in> verts (instance_graph_containment_proj IG)" unfolding instance_graph_containment_proj_def using structure_edges_wellformed by simp qed next have "pre_digraph.arc_to_tuple (instance_graph_containment_proj IG) ` arcs (instance_graph_containment_proj IG) = edge_to_tuple ` { e \<in> E IG. type\<^sub>e e \<in> contains (TG IG) }" proof show "pre_digraph.arc_to_tuple (instance_graph_containment_proj IG) ` arcs (instance_graph_containment_proj IG) \<subseteq> edge_to_tuple ` {e \<in> E IG. type\<^sub>e e \<in> contains (TG IG)}" proof fix x assume "x \<in> pre_digraph.arc_to_tuple (instance_graph_containment_proj IG) ` arcs (instance_graph_containment_proj IG)" then show "x \<in> edge_to_tuple ` {e \<in> E IG. type\<^sub>e e \<in> contains (TG IG)}" proof fix xa assume x_is_xa: "x = pre_digraph.arc_to_tuple (instance_graph_containment_proj IG) xa" assume "xa \<in> arcs (instance_graph_containment_proj IG)" then have "pre_digraph.arc_to_tuple (instance_graph_containment_proj IG) xa \<in> edge_to_tuple ` {e \<in> E IG. type\<^sub>e e \<in> contains (TG IG)}" unfolding instance_graph_containment_proj_def pre_digraph.arc_to_tuple_def by simp then show "x \<in> edge_to_tuple ` {e \<in> E IG. type\<^sub>e e \<in> contains (TG IG)}" by (simp add: x_is_xa) qed qed next show "edge_to_tuple ` {e \<in> E IG. type\<^sub>e e \<in> contains (TG IG)} \<subseteq> pre_digraph.arc_to_tuple (instance_graph_containment_proj IG) ` arcs (instance_graph_containment_proj IG)" proof fix x assume "x \<in> edge_to_tuple ` {e \<in> E IG. type\<^sub>e e \<in> contains (TG IG)}" then show "x \<in> pre_digraph.arc_to_tuple (instance_graph_containment_proj IG) ` arcs (instance_graph_containment_proj IG)" unfolding instance_graph_containment_proj_def pre_digraph.arc_to_tuple_def edge_to_tuple_def by simp qed qed then show "irrefl ((pre_digraph.arc_to_tuple (instance_graph_containment_proj IG) ` arcs (instance_graph_containment_proj IG))\<^sup>+)" using irrefl_contains_edges by simp qed section "Validity of trivial instance graphs" definition ig_empty :: "('nt, 'lt, 'id) instance_graph" where [simp]: "ig_empty = \<lparr> TG = tg_empty, Id = {}, N = {}, E = {}, ident = (\<lambda>x. undefined) \<rparr>" lemma ig_empty_correct[simp]: "instance_graph ig_empty" proof (intro instance_graph.intro) show "type_graph (TG ig_empty)" unfolding ig_empty_def using tg_empty_correct by simp next fix p :: "(('nt, 'lt) NodeDef \<times> ('lt LabDef \<times> 'lt LabDef \<times> 'lt LabDef) \<times> ('nt, 'lt) NodeDef) awalk" show "\<not>pre_digraph.cycle (instance_graph_containment_proj ig_empty) p" unfolding instance_graph_containment_proj_def pre_digraph.cycle_def pre_digraph.awalk_def by simp qed (simp_all) lemma ig_empty_any_type_graph_correct[simp]: assumes instance_graph_type_graph: "type_graph (TG IG)" assumes instance_graph_id: "Id IG = {}" assumes instance_graph_nodes: "N IG = {}" assumes instance_graph_edges: "E IG = {}" assumes instance_graph_ident: "ident IG = (\<lambda>x. undefined)" shows "instance_graph IG" proof (intro instance_graph.intro) fix p show "\<not>pre_digraph.cycle (instance_graph_containment_proj IG) p" unfolding instance_graph_containment_proj_def pre_digraph.cycle_def pre_digraph.awalk_def by (simp add: instance_graph_nodes) qed (simp_all add: assms) end
function texture_id!(fg::FrameGraph, arg::Texture, pass)::UInt32 # let's create the resource eagerly for now img = image(fg, arg.name) (; frame, resource_graph) = fg if !isnothing(arg.sampling) # combined image sampler sampling = arg.sampling sampler = Vk.Sampler(device(fg), sampling) # preserve sampler register(frame, gensym(:sampler), sampler; persistent = false) combined_image_sampler_state = frame.gd.resources.gset.state[Vk.DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER] push!(combined_image_sampler_state, Vk.DescriptorImageInfo(sampler, View(img), image_layout(resource_graph, fg.resources[arg.name], pass))) length(combined_image_sampler_state) - 1 else # sampled image sampler = empty_handle(Vk.Sampler) sampled_image_state = frame.gd.resources.gset.state[Vk.DESCRIPTOR_TYPE_SAMPLED_IMAGE] push!(sampled_image_state, Vk.DescriptorImageInfo(sampler, View(img), image_layout(resource_graph, fg.resources[arg.name], pass))) length(sampled_image_state) - 1 end end function sampler_id!(fg::FrameGraph, arg::Sampling) (; frame) = fg view = empty_handle(Vk.ImageView) sampler = Vk.Sampler(device(fg), sampling) # preserve sampler register(frame, gensym(:sampler), sampler; persistent = false) sampler_state = frame.gd.resources.gset.state[Vk.DESCRIPTOR_TYPE_SAMPLER] push!(sampler_state, Vk.DescriptorImageInfo(sampler, view, Vk.IMAGE_LAYOUT_UNDEFINED)) length(sampler_state) - 1 end #= """ Encode a lifetime context that allows the deletion of staged resources once expired. """ abstract type LifeTimeContext end """ Period of time that extends for a whole frame. Work between frames is assumed to be independent. """ struct FrameContext <: LifeTimeContext end struct PersistentContext <: LifeTimeContext end struct Resources descriptors::ResourceDescriptors "Number of frames during which resources were not used." unused::Dictionary{Int,Vector{Int}} "Persistent resources, never to be garbage-collected." persistent::Vector{Int} end """ Transition from one frame to another. """ function transition(resources::Resources) for resource in resources end struct Frame fg::FrameGraph data::GlobalData resources::Resources fences::Vector{Vk.Fence} end =#
(* * Copyright 2014, General Dynamics C4 Systems * * SPDX-License-Identifier: GPL-2.0-only *) (* Proofs about untyped invocations. *) theory Untyped_R imports Detype_R Invocations_R InterruptAcc_R begin context begin interpretation Arch . (*FIXME: arch_split*) primrec untypinv_relation :: "Invocations_A.untyped_invocation \<Rightarrow> Invocations_H.untyped_invocation \<Rightarrow> bool" where "untypinv_relation (Invocations_A.Retype c reset ob n ao n2 cl d) x = (\<exists>ao'. x = (Invocations_H.Retype (cte_map c) reset ob n ao' n2 (map cte_map cl) d) \<and> ao = APIType_map2 (Inr ao'))" primrec valid_untyped_inv_wcap' :: "Invocations_H.untyped_invocation \<Rightarrow> capability option \<Rightarrow> kernel_state \<Rightarrow> bool" where "valid_untyped_inv_wcap' (Invocations_H.Retype slot reset ptr_base ptr ty us slots d) = (\<lambda>co s. \<exists>sz idx. (cte_wp_at' (\<lambda>cte. cteCap cte = UntypedCap d ptr_base sz idx \<and> (co = None \<or> co = Some (cteCap cte))) slot s \<and> range_cover ptr sz (APIType_capBits ty us) (length slots) \<and> ((\<not> reset \<and> idx \<le> unat (ptr - ptr_base)) \<or> (reset \<and> ptr = ptr_base)) \<and> (ptr && ~~ mask sz) = ptr_base) \<and> (reset \<longrightarrow> descendants_of' slot (ctes_of s) = {}) \<and> distinct (slot # slots) \<and> (ty = APIObjectType ArchTypes_H.CapTableObject \<longrightarrow> us > 0) \<and> (ty = APIObjectType ArchTypes_H.Untyped \<longrightarrow> minUntypedSizeBits \<le> us \<and> us \<le> maxUntypedSizeBits) \<and> (\<forall>slot \<in> set slots. cte_wp_at' (\<lambda>c. cteCap c = NullCap) slot s) \<and> (\<forall>slot \<in> set slots. ex_cte_cap_to' slot s) \<and> sch_act_simple s \<and> 0 < length slots \<and> (d \<longrightarrow> ty = APIObjectType ArchTypes_H.Untyped \<or> isFrameType ty) \<and> APIType_capBits ty us \<le> maxUntypedSizeBits)" abbreviation "valid_untyped_inv' ui \<equiv> valid_untyped_inv_wcap' ui None" lemma valid_untyped_inv_wcap': "valid_untyped_inv' ui = (\<lambda>s. \<exists>sz idx. valid_untyped_inv_wcap' ui (Some (case ui of Invocations_H.Retype slot reset ptr_base ptr ty us slots d \<Rightarrow> UntypedCap d (ptr && ~~ mask sz) sz idx)) s)" by (cases ui, auto simp: fun_eq_iff cte_wp_at_ctes_of) lemma whenE_rangeCheck_eq: "(rangeCheck (x :: 'a :: {linorder, integral}) y z) = (whenE (x < fromIntegral y \<or> fromIntegral z < x) (throwError (RangeError (fromIntegral y) (fromIntegral z))))" by (simp add: rangeCheck_def unlessE_whenE linorder_not_le[symmetric]) lemma APIType_map2_CapTable[simp]: "(APIType_map2 ty = Structures_A.CapTableObject) = (ty = Inr (APIObjectType ArchTypes_H.CapTableObject))" by (simp add: APIType_map2_def split: sum.split X64_H.object_type.split apiobject_type.split kernel_object.split arch_kernel_object.splits) lemma alignUp_H[simp]: "Untyped_H.alignUp = More_Word_Operations.alignUp" apply (rule ext)+ apply (clarsimp simp:Untyped_H.alignUp_def More_Word_Operations.alignUp_def mask_def) done (* MOVE *) lemma corres_check_no_children: "corres (\<lambda>x y. x = y) (cte_at slot) (pspace_aligned' and pspace_distinct' and valid_mdb' and cte_wp_at' (\<lambda>_. True) (cte_map slot)) (const_on_failure x (doE z \<leftarrow> ensure_no_children slot; returnOk y odE)) (constOnFailure x (doE z \<leftarrow> ensureNoChildren (cte_map slot); returnOk y odE))" apply (clarsimp simp:const_on_failure_def constOnFailure_def) apply (rule corres_guard_imp) apply (rule corres_split_catch[where E = dc and E'=dc]) apply (rule corres_guard_imp[OF corres_splitEE]) apply (rule ensureNoChildren_corres) apply simp apply (rule corres_returnOkTT) apply simp apply wp+ apply simp+ apply (clarsimp simp:dc_def,wp)+ apply simp apply simp done lemma mapM_x_stateAssert: "mapM_x (\<lambda>x. stateAssert (f x) (ss x)) xs = stateAssert (\<lambda>s. \<forall>x \<in> set xs. f x s) []" apply (induct xs) apply (simp add: mapM_x_Nil) apply (simp add: mapM_x_Cons) apply (simp add: fun_eq_iff stateAssert_def bind_assoc exec_get assert_def) done lemma mapM_locate_eq: "isCNodeCap cap \<Longrightarrow> mapM (\<lambda>x. locateSlotCap cap x) xs = (do stateAssert (\<lambda>s. case gsCNodes s (capUntypedPtr cap) of None \<Rightarrow> xs = [] | Some n \<Rightarrow> \<forall>x \<in> set xs. n = capCNodeBits cap \<and> x < 2 ^ n) []; return (map (\<lambda>x. (capCNodePtr cap) + 2 ^ cte_level_bits * x) xs) od)" apply (clarsimp simp: isCap_simps) apply (simp add: locateSlot_conv objBits_simps cte_level_bits_def liftM_def[symmetric] mapM_liftM_const isCap_simps) apply (simp add: liftM_def mapM_discarded mapM_x_stateAssert) apply (intro bind_cong refl arg_cong2[where f=stateAssert] ext) apply (simp add: isCap_simps split: option.split) done lemmas is_frame_type_defs = is_frame_type_def isFrameType_def arch_is_frame_type_def lemma is_frame_type_isFrameType_eq[simp]: "(is_frame_type (APIType_map2 (Inr (toEnum (unat arg0))))) = (Types_H.isFrameType (toEnum (unat arg0)))" by (simp add: APIType_map2_def is_frame_type_defs split: apiobject_type.splits object_type.splits)+ (* FIXME: remove *) lemmas APIType_capBits = objSize_eq_capBits (* FIXME: move *) lemma corres_whenE_throw_merge: "corres r P P' f (doE _ \<leftarrow> whenE (A \<or> B) (throwError e); h odE) \<Longrightarrow> corres r P P' f (doE _ \<leftarrow> whenE A (throwError e); _ \<leftarrow> whenE B (throwError e); h odE)" by (auto simp: whenE_def split: if_splits) lemma decodeUntypedInvocation_corres: assumes cap_rel: "list_all2 cap_relation cs cs'" shows "corres (ser \<oplus> untypinv_relation) (invs and cte_wp_at ((=) (cap.UntypedCap d w n idx)) slot and (\<lambda>s. \<forall>x \<in> set cs. s \<turnstile> x)) (invs' and (\<lambda>s. \<forall>x \<in> set cs'. s \<turnstile>' x)) (decode_untyped_invocation label args slot (cap.UntypedCap d w n idx) cs) (decodeUntypedInvocation label args (cte_map slot) (capability.UntypedCap d w n idx) cs')" proof (cases "6 \<le> length args \<and> cs \<noteq> [] \<and> gen_invocation_type label = UntypedRetype") case False show ?thesis using False cap_rel apply (clarsimp simp: decode_untyped_invocation_def decodeUntypedInvocation_def whenE_whenE_body unlessE_whenE split del: if_split cong: list.case_cong) apply (auto split: list.split) done next case True have val_le_length_Cons: (* clagged from Tcb_R *) "\<And>n xs. n \<noteq> 0 \<Longrightarrow> (n \<le> length xs) = (\<exists>y ys. xs = y # ys \<and> (n - 1) \<le> length ys)" apply (case_tac xs, simp_all) apply (case_tac n, simp_all) done obtain arg0 arg1 arg2 arg3 arg4 arg5 argsmore cap cap' csmore csmore' where args: "args = arg0 # arg1 # arg2 # arg3 # arg4 # arg5 # argsmore" and cs: "cs = cap # csmore" and cs': "cs' = cap' # csmore'" and crel: "cap_relation cap cap'" using True cap_rel by (clarsimp simp: neq_Nil_conv list_all2_Cons1 val_le_length_Cons) have il: "gen_invocation_type label = UntypedRetype" using True by simp have word_unat_power2: "\<And>bits. \<lbrakk> bits < 64 \<or> bits < word_bits \<rbrakk> \<Longrightarrow> unat (2 ^ bits :: machine_word) = 2 ^ bits" by (simp add: word_bits_def) have P: "\<And>P. corres (ser \<oplus> dc) \<top> \<top> (whenE P (throwError ExceptionTypes_A.syscall_error.TruncatedMessage)) (whenE P (throwError Fault_H.syscall_error.TruncatedMessage))" by (simp add: whenE_def returnOk_def) have Q: "\<And>v. corres (ser \<oplus> (\<lambda>a b. APIType_map2 (Inr (toEnum (unat v))) = a)) \<top> \<top> (data_to_obj_type v) (whenE (fromEnum (maxBound :: X64_H.object_type) < unat v) (throwError (Fault_H.syscall_error.InvalidArgument 0)))" apply (simp only: data_to_obj_type_def returnOk_bindE fun_app_def) apply (simp add: maxBound_def enum_apiobject_type fromEnum_def whenE_def) apply (simp add: returnOk_def APIType_map2_def toEnum_def enum_apiobject_type enum_object_type) apply (intro conjI impI) apply (subgoal_tac "unat v - 5 > 6") apply (simp add: arch_data_to_obj_type_def) apply simp apply (subgoal_tac "\<exists>n. unat v = n + 5") apply (clarsimp simp: arch_data_to_obj_type_def returnOk_def) apply (rule_tac x="unat v - 5" in exI) apply arith done have S: "\<And>x (y :: ('g :: len) word) (z :: 'g word) bits. \<lbrakk> bits < len_of TYPE('g); x < 2 ^ bits \<rbrakk> \<Longrightarrow> toEnum x = (of_nat x :: 'g word)" apply (rule toEnum_of_nat) apply (erule order_less_trans) apply simp done obtain xs where xs: "xs = [unat arg4..<unat arg4 + unat arg5]" by simp have YUCK: "\<And>ref bits. \<lbrakk> is_aligned ref bits; Suc (unat arg4 + unat arg5 - Suc 0) \<le> 2 ^ bits; bits < 64; 1 \<le> arg4 + arg5; arg4 \<le> arg4 + arg5 \<rbrakk> \<Longrightarrow> (map (\<lambda>x. ref + 2 ^ cte_level_bits * x) [arg4 .e. arg4 + arg5 - 1]) = map cte_map (map (Pair ref) (map (nat_to_cref bits) xs))" apply (subgoal_tac "Suc (unat (arg4 + arg5 - 1)) = unat arg4 + unat arg5") apply (simp add: upto_enum_def xs del: upt.simps) apply (clarsimp simp: cte_map_def) apply (subst of_bl_nat_to_cref) apply simp apply (simp add: word_bits_def) apply (subst S) apply simp apply simp apply (simp add: cte_level_bits_def) apply unat_arith done have another: "\<And>bits a. \<lbrakk> (a::machine_word) \<le> 2 ^ bits; bits < word_bits\<rbrakk> \<Longrightarrow> 2 ^ bits - a = of_nat (2 ^ bits - unat a)" apply (subst of_nat_diff) apply (subst (asm) word_le_nat_alt) apply (simp add: word_unat_power2) apply simp done have ty_size: "\<And>x y. (obj_bits_api (APIType_map2 (Inr x)) y) = (Types_H.getObjectSize x y)" apply (clarsimp simp:obj_bits_api_def APIType_map2_def getObjectSize_def simp del: APIType_capBits) apply (case_tac x) apply (simp_all add:arch_kobj_size_def default_arch_object_def pageBits_def pdBits_def ptBits_def) apply (rename_tac apiobject_type) apply (case_tac apiobject_type) apply (simp_all add:apiGetObjectSize_def tcbBlockSizeBits_def epSizeBits_def ntfnSizeBits_def slot_bits_def cteSizeBits_def bit_simps) done obtain if_res where if_res_def: "\<And>reset. if_res reset = (if reset then 0 else idx)" by auto have if_res_2n: "\<And>d res. (\<exists>s. s \<turnstile> cap.UntypedCap d w n idx) \<Longrightarrow> if_res res \<le> 2 ^ n" by (simp add: if_res_def valid_cap_def) note word_unat_power [symmetric, simp del] show ?thesis apply (rule corres_name_pre) apply clarsimp apply (subgoal_tac "cte_wp_at' (\<lambda>cte. cteCap cte = (capability.UntypedCap d w n idx)) (cte_map slot) s'") prefer 2 apply (drule state_relation_pspace_relation) apply (case_tac slot) apply simp apply (drule(1) pspace_relation_cte_wp_at) apply fastforce+ apply (clarsimp simp:cte_wp_at_caps_of_state) apply (frule caps_of_state_valid_cap[unfolded valid_cap_def]) apply fastforce apply (clarsimp simp:cap_aligned_def) (* ugh yuck. who likes a word proof? furthermore, some more restriction of the returnOk_bindE stuff needs to be done in order to give you a single target to do the word proof against or else it needs repeating. ugh. maybe could seperate out the equality Isar-style? *) apply (simp add: decodeUntypedInvocation_def decode_untyped_invocation_def args cs cs' xs[symmetric] il whenE_rangeCheck_eq cap_case_CNodeCap unlessE_whenE case_bool_If lookupTargetSlot_def untypedBits_defs untyped_min_bits_def untyped_max_bits_def del: upt.simps split del: if_split cong: if_cong list.case_cong) apply (rule corres_guard_imp) apply (rule corres_splitEE[OF Q]) apply (rule corres_whenE_throw_merge) apply (rule whenE_throwError_corres) apply (simp add: word_bits_def word_size) apply (clarsimp simp: word_size word_bits_def fromIntegral_def ty_size toInteger_nat fromInteger_nat wordBits_def) apply (simp add: not_le) apply (rule whenE_throwError_corres, simp) apply (clarsimp simp: fromAPIType_def X64_H.fromAPIType_def) apply (rule whenE_throwError_corres, simp) apply (clarsimp simp: fromAPIType_def X64_H.fromAPIType_def) apply (rule_tac r' = "\<lambda>cap cap'. cap_relation cap cap'" in corres_splitEE[OF corres_if]) apply simp apply (rule corres_returnOkTT) apply (rule crel) apply simp apply (rule corres_splitEE[OF lookupSlotForCNodeOp_corres]) apply (rule crel) apply simp apply simp apply (rule getSlotCap_corres,simp) apply wp+ apply (rule_tac corres_split_norE) apply (rule corres_if) apply simp apply (rule corres_returnOkTT, simp) apply (rule corres_trivial) apply (clarsimp simp: fromAPIType_def lookup_failure_map_def) apply (rule_tac F="is_cnode_cap rva \<and> cap_aligned rva" in corres_gen_asm) apply (subgoal_tac "is_aligned (obj_ref_of rva) (bits_of rva) \<and> bits_of rva < 64") prefer 2 apply (clarsimp simp: is_cap_simps bits_of_def cap_aligned_def word_bits_def is_aligned_weaken) apply (rule whenE_throwError_corres) apply (clarsimp simp:Kernel_Config.retypeFanOutLimit_def is_cap_simps bits_of_def)+ apply (simp add: unat_arith_simps(2) unat_2p_sub_1 word_bits_def) apply (rule whenE_throwError_corres) apply (clarsimp simp:Kernel_Config.retypeFanOutLimit_def is_cap_simps bits_of_def)+ apply (simp add: unat_eq_0 word_less_nat_alt) apply (rule whenE_throwError_corres) apply (clarsimp simp:Kernel_Config.retypeFanOutLimit_def is_cap_simps bits_of_def)+ apply (clarsimp simp:toInteger_word unat_arith_simps(2) cap_aligned_def) apply (subst unat_sub) apply (simp add: linorder_not_less word_le_nat_alt) apply (fold neq0_conv) apply (simp add: unat_eq_0 cap_aligned_def) apply (clarsimp simp:fromAPIType_def) apply (clarsimp simp:liftE_bindE mapM_locate_eq) apply (subgoal_tac "unat (arg4 + arg5) = unat arg4 + unat arg5") prefer 2 apply (clarsimp simp:not_less) apply (subst unat_word_ariths(1)) apply (rule mod_less) apply (unfold word_bits_len_of)[1] apply (subgoal_tac "2 ^ bits_of rva < (2 :: nat) ^ word_bits") apply arith apply (rule power_strict_increasing, simp add: word_bits_conv) apply simp apply (rule_tac P'="valid_cap rva" in corres_stateAssert_implied) apply (frule_tac bits2 = "bits_of rva" in YUCK) apply (simp) apply (simp add: word_bits_conv) apply (simp add: word_le_nat_alt) apply (simp add: word_le_nat_alt) apply (simp add:liftE_bindE[symmetric] free_index_of_def) apply (rule corres_split_norE) apply (clarsimp simp:is_cap_simps simp del:ser_def) apply (simp add: mapME_x_map_simp del: ser_def) apply (rule_tac P = "valid_cap (cap.CNodeCap r bits g) and invs" in corres_guard_imp [where P' = invs']) apply (rule mapME_x_corres_inv [OF _ _ _ refl]) apply (simp del: ser_def) apply (rule ensureEmptySlot_corres) apply (clarsimp simp: is_cap_simps) apply (simp, wp) apply (simp, wp) apply clarsimp apply (clarsimp simp add: xs is_cap_simps bits_of_def valid_cap_def) apply (erule cap_table_at_cte_at) apply (simp add: nat_to_cref_def word_bits_conv) apply simp apply (subst liftE_bindE)+ apply (rule corres_split_eqr[OF corres_check_no_children]) apply (simp only: free_index_of_def cap.simps if_res_def[symmetric]) apply (rule_tac F="if_res reset \<le> 2 ^ n" in corres_gen_asm) apply (rule whenE_throwError_corres) apply (clarsimp simp:shiftL_nat word_less_nat_alt shiftr_div_2n' split del: if_split)+ apply (simp add: word_of_nat_le another) apply (drule_tac x = "if_res reset" in unat_of_nat64[OF le_less_trans]) apply (simp add:ty_size shiftR_nat)+ apply (simp add:unat_of_nat64 le_less_trans[OF div_le_dividend] le_less_trans[OF diff_le_self]) apply (rule whenE_throwError_corres) apply (clarsimp) apply (clarsimp simp: fromAPIType_def) apply (rule corres_returnOkTT) apply (clarsimp simp:ty_size getFreeRef_def get_free_ref_def is_cap_simps) apply simp apply (strengthen if_res_2n, wp) apply simp apply wp apply (wp mapME_x_inv_wp validE_R_validE[OF valid_validE_R[OF ensure_empty_inv]] validE_R_validE[OF valid_validE_R[OF ensureEmpty_inv]])+ apply (clarsimp simp: is_cap_simps valid_cap_simps cap_table_at_gsCNodes bits_of_def linorder_not_less) apply (erule order_le_less_trans) apply (rule word_leq_le_minus_one) apply (simp add: word_le_nat_alt) apply (simp add: unat_arith_simps) apply wp+ apply clarsimp apply (rule hoare_strengthen_post [where Q = "\<lambda>r. invs and valid_cap r and cte_at slot"]) apply wp+ apply (clarsimp simp: is_cap_simps bits_of_def cap_aligned_def valid_cap_def word_bits_def) apply (frule caps_of_state_valid_cap, clarsimp+) apply (strengthen refl exI[mk_strg I E] exI[where x=d])+ apply simp apply wp+ apply (rule hoare_strengthen_post [where Q = "\<lambda>r. invs' and cte_at' (cte_map slot)"]) apply wp+ apply (clarsimp simp:invs_pspace_aligned' invs_pspace_distinct') apply (wp whenE_throwError_wp | wp (once) hoare_drop_imps)+ apply (clarsimp simp: invs_valid_objs' invs_pspace_aligned' invs_pspace_distinct' cte_wp_at_caps_of_state cte_wp_at_ctes_of ) apply (clarsimp simp: invs_valid_objs invs_psp_aligned) apply (frule caps_of_state_valid_cap, clarsimp+) apply (strengthen refl[where t=True] refl exI[mk_strg I E] exI[where x=d])+ apply (clarsimp simp: is_cap_simps valid_cap_def bits_of_def cap_aligned_def cte_level_bits_def word_bits_conv) apply (clarsimp simp: invs_valid_objs' invs_pspace_aligned' invs_pspace_distinct' cte_wp_at_caps_of_state cte_wp_at_ctes_of ) done qed lemma decodeUntyped_inv[wp]: "\<lbrace>P\<rbrace> decodeUntypedInvocation label args slot (UntypedCap d w n idx) cs \<lbrace>\<lambda>rv. P\<rbrace>" apply (simp add: decodeUntypedInvocation_def whenE_def split_def unlessE_def Let_def split del: if_split cong: if_cong list.case_cong) apply (rule hoare_pre) apply (wp mapME_x_inv_wp hoare_drop_imps constOnFailure_wp mapM_wp' | wpcw | simp add: lookupTargetSlot_def locateSlot_conv)+ done declare inj_Pair[simp] declare upt_Suc[simp del] lemma descendants_of_cte_at': "\<lbrakk>p \<in> descendants_of' x (ctes_of s); valid_mdb' s\<rbrakk> \<Longrightarrow> cte_wp_at' (\<lambda>_. True) p s" by (clarsimp simp:descendants_of'_def cte_wp_at_ctes_of dest!:subtree_target_Some) lemma ctes_of_ko: "valid_cap' cap s \<Longrightarrow> isUntypedCap cap \<or> (\<forall>ptr\<in>capRange cap. \<exists>optr ko. ksPSpace s optr = Some ko \<and> ptr \<in> obj_range' optr ko)" apply (case_tac cap) \<comment> \<open>TCB case\<close> apply (simp_all add: isCap_simps capRange_def) apply (clarsimp simp: valid_cap'_def obj_at'_def) apply (intro exI conjI, assumption) apply (clarsimp simp: projectKO_eq objBits_def obj_range'_def dest!: projectKO_opt_tcbD simp: objBitsKO_def) \<comment> \<open>NTFN case\<close> apply (clarsimp simp: valid_cap'_def obj_at'_def) apply (intro exI conjI, assumption) apply (clarsimp simp: projectKO_eq objBits_def obj_range'_def projectKO_ntfn objBitsKO_def) \<comment> \<open>EP case\<close> apply (clarsimp simp: valid_cap'_def obj_at'_def) apply (intro exI conjI, assumption) apply (clarsimp simp: projectKO_eq objBits_def obj_range'_def projectKO_ep objBitsKO_def) \<comment> \<open>Zombie case\<close> apply (rename_tac word zombie_type nat) apply (case_tac zombie_type) apply (clarsimp simp: valid_cap'_def obj_at'_def) apply (intro exI conjI, assumption) apply (clarsimp simp: projectKO_eq objBits_simps' obj_range'_def dest!: projectKO_opt_tcbD) apply (clarsimp simp: valid_cap'_def obj_at'_def capAligned_def objBits_simps' projectKOs) apply (frule_tac ptr=ptr and sz=cte_level_bits in nasty_range [where 'a=machine_word_len, folded word_bits_def]) apply (simp add: cte_level_bits_def)+ apply clarsimp apply (drule_tac x=idx in spec) apply (clarsimp simp: less_mask_eq) apply (fastforce simp: obj_range'_def projectKOs objBits_simps' field_simps)[1] \<comment> \<open>Arch cases\<close> apply (rename_tac arch_capability) apply (case_tac arch_capability) \<comment> \<open>ASID case\<close> apply (clarsimp simp: valid_cap'_def typ_at'_def ko_wp_at'_def) apply (intro exI conjI, assumption) apply (clarsimp simp: obj_range'_def archObjSize_def objBitsKO_def) apply (case_tac ko, simp+)[1] apply (rename_tac arch_kernel_object) apply (case_tac arch_kernel_object; simp add: archObjSize_def asid_low_bits_def pageBits_def bit_simps) apply simp \<comment> \<open>IOPort case\<close> apply clarsimp \<comment> \<open>IOPortControl case\<close> apply clarsimp \<comment> \<open>Page case\<close> apply (rename_tac word vmrights vmpage_size option) apply (clarsimp simp: valid_cap'_def typ_at'_def ko_wp_at'_def capAligned_def) apply (frule_tac ptr = ptr and sz = "pageBits" in nasty_range [where 'a=machine_word_len, folded word_bits_def]) apply assumption apply (simp add: pbfs_atleast_pageBits)+ apply (clarsimp,drule_tac x = idx in spec,clarsimp) apply (intro exI conjI,assumption) apply (clarsimp simp: obj_range'_def) apply (case_tac ko, simp_all split: if_splits, (simp add: objBitsKO_def archObjSize_def field_simps shiftl_t2n)+)[1] \<comment> \<open>PT case\<close> apply (rename_tac word option) apply (clarsimp simp: valid_cap'_def obj_at'_def pageBits_def bit_simps page_table_at'_def typ_at'_def ko_wp_at'_def ptBits_def) apply (frule_tac ptr=ptr and sz=3 in nasty_range[where 'a=machine_word_len and bz="ptBits", folded word_bits_def, simplified ptBits_def pageBits_def word_bits_def bit_simps, simplified]) apply simp apply simp apply clarsimp apply (drule_tac x=idx in spec) apply clarsimp apply (intro exI conjI,assumption) apply (clarsimp simp: obj_range'_def) apply (case_tac ko; simp) apply (rename_tac arch_kernel_object) apply (case_tac arch_kernel_object; simp) apply (simp add: objBitsKO_def archObjSize_def field_simps shiftl_t2n) \<comment> \<open>PD case\<close> apply (clarsimp simp: valid_cap'_def obj_at'_def pageBits_def pdBits_def bit_simps page_directory_at'_def typ_at'_def ko_wp_at'_def) apply (frule_tac ptr=ptr and sz=3 in nasty_range[where 'a=machine_word_len and bz="pdBits", folded word_bits_def, simplified pdBits_def pageBits_def word_bits_def bit_simps, simplified]) apply simp apply simp apply clarsimp apply (drule_tac x="idx" in spec) apply clarsimp apply (intro exI conjI, assumption) apply (clarsimp simp: obj_range'_def objBitsKO_def field_simps) apply (case_tac ko; simp) apply (rename_tac arch_kernel_object) apply (case_tac arch_kernel_object; simp) apply (simp add: field_simps archObjSize_def shiftl_t2n) \<comment> \<open>PDPT case\<close> apply (clarsimp simp: valid_cap'_def obj_at'_def pageBits_def pdptBits_def bit_simps pd_pointer_table_at'_def typ_at'_def ko_wp_at'_def) apply (frule_tac ptr=ptr and sz=3 in nasty_range[where 'a=machine_word_len and bz="pdptBits", folded word_bits_def, simplified pdptBits_def pageBits_def word_bits_def bit_simps, simplified]) apply simp apply simp apply clarsimp apply (drule_tac x="idx" in spec) apply clarsimp apply (intro exI conjI, assumption) apply (clarsimp simp: obj_range'_def objBitsKO_def field_simps) apply (case_tac ko; simp) apply (rename_tac arch_kernel_object) apply (case_tac arch_kernel_object; simp) apply (simp add: field_simps archObjSize_def shiftl_t2n) \<comment> \<open>PML4 case\<close> apply (clarsimp simp: valid_cap'_def obj_at'_def pageBits_def pml4Bits_def bit_simps page_map_l4_at'_def typ_at'_def ko_wp_at'_def) apply (frule_tac ptr=ptr and sz=3 in nasty_range[where 'a=machine_word_len and bz="pml4Bits", folded word_bits_def, simplified pml4Bits_def pageBits_def word_bits_def bit_simps, simplified]) apply simp apply simp apply clarsimp apply (drule_tac x="idx" in spec) apply clarsimp apply (intro exI conjI, assumption) apply (clarsimp simp: obj_range'_def objBitsKO_def field_simps) apply (case_tac ko; simp) apply (rename_tac arch_kernel_object) apply (case_tac arch_kernel_object; simp) apply (simp add: field_simps archObjSize_def shiftl_t2n) \<comment> \<open>CNode case\<close> apply (clarsimp simp: valid_cap'_def obj_at'_def capAligned_def objBits_simps projectKOs) apply (frule_tac ptr=ptr and sz=cte_level_bits in nasty_range [where 'a=machine_word_len, folded word_bits_def]) apply (simp add: cte_level_bits_def objBits_defs)+ apply clarsimp apply (drule_tac x=idx in spec) apply (clarsimp simp: less_mask_eq) apply (fastforce simp: obj_range'_def projectKOs objBits_simps' field_simps)[1] done lemma untypedCap_descendants_range': "\<lbrakk>valid_pspace' s; (ctes_of s) p = Some cte; isUntypedCap (cteCap cte);valid_mdb' s; q \<in> descendants_of' p (ctes_of s)\<rbrakk> \<Longrightarrow> cte_wp_at' (\<lambda>c. (capRange (cteCap c) \<inter> usableUntypedRange (cteCap cte) = {})) q s" apply (clarsimp simp: valid_pspace'_def) apply (frule(1) descendants_of_cte_at') apply (clarsimp simp:cte_wp_at_ctes_of) apply (clarsimp simp:valid_mdb'_def) apply (frule valid_mdb_no_loops) apply (case_tac "isUntypedCap (cteCap ctea)") apply (case_tac ctea) apply (rename_tac cap node) apply (case_tac cte) apply (rename_tac cap' node') apply clarsimp apply (frule(1) valid_capAligned[OF ctes_of_valid_cap']) apply (frule_tac c = cap in valid_capAligned[OF ctes_of_valid_cap']) apply (simp add:untypedCapRange)+ apply (frule_tac c = cap' in aligned_untypedRange_non_empty) apply simp apply (frule_tac c = cap in aligned_untypedRange_non_empty) apply simp apply (clarsimp simp:valid_mdb'_def valid_mdb_ctes_def) apply (drule untyped_incD') apply simp+ apply clarify apply (erule subset_splitE) apply simp apply (thin_tac "P \<longrightarrow> Q" for P Q)+ apply (elim conjE) apply (simp add:descendants_of'_def) apply (drule(1) subtree_trans) apply (simp add:no_loops_no_subtree) apply simp apply (clarsimp simp:descendants_of'_def | erule disjE)+ apply (drule(1) subtree_trans) apply (simp add:no_loops_no_subtree)+ apply (thin_tac "P \<longrightarrow> Q" for P Q)+ apply (erule(1) disjoint_subset2[OF usableRange_subseteq]) apply (simp add:Int_ac) apply (case_tac ctea) apply (rename_tac cap node) apply (case_tac cte) apply clarsimp apply (drule(1) ctes_of_valid_cap')+ apply (frule_tac cap = cap in ctes_of_ko) apply (elim disjE) apply clarsimp+ apply (thin_tac "s \<turnstile>' cap") apply (clarsimp simp: valid_cap'_def isCap_simps valid_untyped'_def simp del: usableUntypedRange.simps untypedRange.simps) apply (thin_tac "\<forall>x y z. P x y z" for P) apply (rule ccontr) apply (clarsimp dest!: int_not_emptyD simp del: usableUntypedRange.simps untypedRange.simps) apply (drule(1) bspec) apply (clarsimp simp: ko_wp_at'_def simp del: usableUntypedRange.simps untypedRange.simps) apply (drule_tac x = optr in spec) apply (clarsimp simp: ko_wp_at'_def simp del: usableUntypedRange.simps untypedRange.simps) apply (frule(1) pspace_alignedD') apply (frule(1) pspace_distinctD') apply (erule(1) impE) apply (clarsimp simp del: usableUntypedRange.simps untypedRange.simps) apply blast done lemma cte_wp_at_caps_descendants_range_inI': "\<lbrakk>invs' s; cte_wp_at' (\<lambda>c. (cteCap c) = capability.UntypedCap d (ptr && ~~ mask sz) sz idx) cref s; idx \<le> unat (ptr && mask sz); sz < word_bits\<rbrakk> \<Longrightarrow> descendants_range_in' {ptr .. (ptr && ~~ mask sz) + 2 ^ sz - 1} cref (ctes_of s)" apply (frule invs_mdb') apply (frule(1) le_mask_le_2p) apply (clarsimp simp: descendants_range_in'_def cte_wp_at_ctes_of) apply (drule untypedCap_descendants_range'[rotated]) apply (simp add: isCap_simps)+ apply (simp add: invs_valid_pspace') apply (clarsimp simp: cte_wp_at_ctes_of) apply (erule disjoint_subset2[rotated]) apply clarsimp apply (rule le_plus'[OF word_and_le2]) apply simp apply (erule word_of_nat_le) done lemma checkFreeIndex_wp: "\<lbrace>\<lambda>s. if descendants_of' slot (ctes_of s) = {} then Q y s else Q x s\<rbrace> constOnFailure x (doE z \<leftarrow> ensureNoChildren slot; returnOk y odE) \<lbrace>Q\<rbrace>" apply (clarsimp simp:constOnFailure_def const_def) apply (wp ensureNoChildren_wp) apply simp done declare upt_Suc[simp] lemma ensureNoChildren_sp: "\<lbrace>P\<rbrace> ensureNoChildren sl \<lbrace>\<lambda>rv s. P s \<and> descendants_of' sl (ctes_of s) = {}\<rbrace>,-" by (wp ensureNoChildren_wp, simp) declare isPML4Cap'_PML4 [simp] lemma dui_sp_helper': "\<lbrace>P\<rbrace> if Q then returnOk root_cap else doE slot \<leftarrow> lookupTargetSlot root_cap cref dpth; liftE (getSlotCap slot) odE \<lbrace>\<lambda>rv s. (rv = root_cap \<or> (\<exists>slot. cte_wp_at' ((=) rv o cteCap) slot s)) \<and> P s\<rbrace>, -" apply (cases Q, simp_all add: lookupTargetSlot_def) apply (wp, simp) apply (simp add: getSlotCap_def split_def) apply wp apply (rule hoare_strengthen_post [OF getCTE_sp[where P=P]]) apply (clarsimp simp: cte_wp_at_ctes_of) apply (elim allE, drule(1) mp) apply simp apply wpsimp apply simp done lemma map_ensure_empty': "\<lbrace>\<lambda>s. (\<forall>slot \<in> set slots. cte_wp_at' (\<lambda>cte. cteCap cte = NullCap) slot s) \<longrightarrow> P s\<rbrace> mapME_x ensureEmptySlot slots \<lbrace>\<lambda>rv s. P s \<rbrace>,-" apply (induct slots arbitrary: P) apply (simp add: mapME_x_def sequenceE_x_def) apply wp apply (simp add: mapME_x_def sequenceE_x_def) apply (rule_tac Q="\<lambda>rv s. (\<forall>slot\<in>set slots. cte_wp_at' (\<lambda>cte. cteCap cte = capability.NullCap) slot s) \<longrightarrow> P s" in validE_R_sp) apply (simp add: ensureEmptySlot_def unlessE_def) apply (wp getCTE_wp') apply (clarsimp elim!: cte_wp_at_weakenE') apply (erule meta_allE) apply (erule hoare_post_imp_R) apply clarsimp done lemma irq_nodes_global: "irq_node' s + (ucast (irq :: 8 word)) * 32 \<in> global_refs' s" by (simp add: global_refs'_def mult.commute mult.left_commute) lemma valid_global_refsD2': "\<lbrakk>ctes_of s p = Some cte; valid_global_refs' s\<rbrakk> \<Longrightarrow> global_refs' s \<inter> capRange (cteCap cte) = {}" by (blast dest: valid_global_refsD') lemma cte_cap_in_untyped_range: "\<lbrakk> ptr \<le> x; x \<le> ptr + 2 ^ bits - 1; cte_wp_at' (\<lambda>cte. cteCap cte = UntypedCap d ptr bits idx) cref s; descendants_of' cref (ctes_of s) = {}; invs' s; ex_cte_cap_to' x s; valid_global_refs' s \<rbrakk> \<Longrightarrow> False" apply (clarsimp simp: ex_cte_cap_to'_def cte_wp_at_ctes_of) apply (case_tac ctea, simp) apply (rename_tac cap node) apply (frule ctes_of_valid_cap', clarsimp) apply (case_tac "\<exists>irq. cap = IRQHandlerCap irq") apply (drule (1) equals0D[where a=x, OF valid_global_refsD2'[where p=cref]]) apply (clarsimp simp: irq_nodes_global) apply (frule_tac p=crefa and p'=cref in caps_containedD', assumption) apply (clarsimp dest!: isCapDs) apply (rule_tac x=x in notemptyI) apply (simp add: subsetD [OF cte_refs_capRange]) apply (clarsimp simp: invs'_def valid_state'_def valid_pspace'_def valid_mdb'_def valid_mdb_ctes_def) apply (frule_tac p=cref and p'=crefa in untyped_mdbD', assumption) apply (simp_all add: isUntypedCap_def) apply (frule valid_capAligned) apply (frule capAligned_capUntypedPtr) apply (case_tac cap; simp) apply blast apply (case_tac cap; simp) apply (clarsimp simp: invs'_def valid_state'_def valid_pspace'_def valid_mdb'_def valid_mdb_ctes_def) done lemma cap_case_CNodeCap_True_throw: "(case cap of CNodeCap a b c d \<Rightarrow> returnOk () | _ \<Rightarrow> throw $ e) = (whenE (\<not>isCNodeCap cap) (throwError e))" by (simp split: capability.split bool.split add: whenE_def isCNodeCap_def) lemma empty_descendants_range_in': "\<lbrakk>descendants_of' slot m = {}\<rbrakk> \<Longrightarrow> descendants_range_in' S slot m " by (clarsimp simp:descendants_range_in'_def) lemma liftE_validE_R: "\<lbrace>P\<rbrace> f \<lbrace>Q\<rbrace> \<Longrightarrow> \<lbrace>P\<rbrace> liftE f \<lbrace>Q\<rbrace>,-" by wpsimp lemma decodeUntyped_wf[wp]: "\<lbrace>invs' and cte_wp_at' (\<lambda>cte. cteCap cte = UntypedCap d w sz idx) slot and sch_act_simple and (\<lambda>s. \<forall>x \<in> set cs. s \<turnstile>' x) and (\<lambda>s. \<forall>x \<in> set cs. \<forall>r \<in> cte_refs' x (irq_node' s). ex_cte_cap_to' r s)\<rbrace> decodeUntypedInvocation label args slot (UntypedCap d w sz idx) cs \<lbrace>valid_untyped_inv'\<rbrace>,-" unfolding decodeUntypedInvocation_def apply (simp add: unlessE_def[symmetric] unlessE_whenE rangeCheck_def whenE_def[symmetric] returnOk_liftE[symmetric] Let_def cap_case_CNodeCap_True_throw split del: if_split cong: if_cong list.case_cong) apply (rule list_case_throw_validE_R) apply (clarsimp split del: if_split split: list.splits) apply (intro conjI impI allI) apply (wp+)[6] apply (clarsimp split del: if_split) apply (rename_tac ty us nodeIndexW nodeDepthW nodeOffset nodeWindow rootCap cs' xs') apply (rule validE_R_sp[OF map_ensure_empty'] validE_R_sp[OF whenE_throwError_sp] validE_R_sp[OF dui_sp_helper'])+ apply (case_tac "\<not> isCNodeCap nodeCap") apply (simp add: validE_R_def) apply (simp add: mapM_locate_eq bind_liftE_distrib bindE_assoc returnOk_liftE[symmetric]) apply (rule validE_R_sp, rule liftE_validE_R, rule stateAssert_sp) apply (rule hoare_pre, wp whenE_throwError_wp checkFreeIndex_wp map_ensure_empty') apply (clarsimp simp:cte_wp_at_ctes_of not_less shiftL_nat) apply (case_tac cte) apply clarsimp apply (frule(1) valid_capAligned[OF ctes_of_valid_cap'[OF _ invs_valid_objs']]) apply (clarsimp simp:capAligned_def) apply (subgoal_tac "idx \<le> 2^ sz") prefer 2 apply (frule(1) ctes_of_valid_cap'[OF _ invs_valid_objs']) apply (clarsimp simp:valid_cap'_def valid_untyped_def) apply (subgoal_tac "(2 ^ sz - idx) < 2^ word_bits") prefer 2 apply (rule le_less_trans[where y = "2^sz"]) apply simp+ apply (subgoal_tac "of_nat (2 ^ sz - idx) = (2::machine_word)^sz - of_nat idx") prefer 2 apply (simp add:word_of_nat_minus) apply (subgoal_tac "valid_cap' nodeCap s") prefer 2 apply (erule disjE) apply (fastforce dest: cte_wp_at_valid_objs_valid_cap') apply clarsimp apply (case_tac cte) apply clarsimp apply (drule(1) ctes_of_valid_cap'[OF _ invs_valid_objs'])+ apply simp apply (clarsimp simp: toEnum_of_nat [OF less_Suc_unat_less_bound]) apply (subgoal_tac "args ! 4 \<le> 2 ^ capCNodeBits nodeCap") prefer 2 apply (clarsimp simp: isCap_simps) apply (subst (asm) le_m1_iff_lt[THEN iffD1]) apply (clarsimp simp:valid_cap'_def isCap_simps p2_gt_0 capAligned_def word_bits_def) apply (rule less_imp_le) apply simp apply (subgoal_tac "distinct (map (\<lambda>y. capCNodePtr nodeCap + y * 2^cte_level_bits) [args ! 4 .e. args ! 4 + args ! 5 - 1])") prefer 2 apply (simp add: distinct_map upto_enum_def del: upt_Suc) apply (rule comp_inj_on) apply (rule inj_onI) apply (clarsimp dest!: less_Suc_unat_less_bound) apply (erule word_unat.Abs_eqD) apply (simp add: unats_def) apply (simp add: unats_def) apply (rule inj_onI) apply (clarsimp simp: toEnum_of_nat[OF less_Suc_unat_less_bound] ucast_id isCap_simps) apply (erule(2) inj_bits, simp add: cte_level_bits_def word_bits_def) apply (subst Suc_unat_diff_1) apply (rule word_le_plus_either,simp) apply (subst olen_add_eqv) apply (subst add.commute) apply (erule(1) plus_minus_no_overflow_ab) apply (drule(1) le_plus) apply (rule unat_le_helper) apply (erule order_trans) apply (subst unat_power_lower64[symmetric], simp add: word_bits_def cte_level_bits_def) apply (simp add: word_less_nat_alt[symmetric]) apply (rule two_power_increasing) apply (clarsimp dest!: valid_capAligned simp: capAligned_def objBits_def objBitsKO_def) apply (simp_all add: word_bits_def cte_level_bits_def objBits_defs)[2] apply (clarsimp simp: X64_H.fromAPIType_def) apply (subgoal_tac "Suc (unat (args ! 4 + args ! 5 - 1)) = unat (args ! 4) + unat (args ! 5)") prefer 2 apply simp apply (subst Suc_unat_diff_1) apply (rule word_le_plus_either,simp) apply (subst olen_add_eqv) apply (subst add.commute) apply (erule(1) plus_minus_no_overflow_ab) apply (rule unat_plus_simple[THEN iffD1]) apply (subst olen_add_eqv) apply (subst add.commute) apply (erule(1) plus_minus_no_overflow_ab) apply clarsimp apply (subgoal_tac "(\<forall>x. (args ! 4) \<le> x \<and> x \<le> (args ! 4) + (args ! 5) - 1 \<longrightarrow> ex_cte_cap_wp_to' (\<lambda>_. True) (capCNodePtr nodeCap + x * 2^cteSizeBits) s)") prefer 2 apply clarsimp apply (erule disjE) apply (erule bspec) apply (clarsimp simp:isCap_simps image_def) apply (rule_tac x = x in bexI,simp) apply simp apply (erule order_trans) apply (frule(1) le_plus) apply (rule word_l_diffs,simp+) apply (rule word_le_plus_either,simp) apply (subst olen_add_eqv) apply (subst add.commute) apply (erule(1) plus_minus_no_overflow_ab) apply (clarsimp simp:ex_cte_cap_wp_to'_def) apply (rule_tac x = nodeSlot in exI) apply (case_tac cte) apply (clarsimp simp: cte_wp_at_ctes_of isCap_simps image_def) apply (rule_tac x = x in bexI,simp) apply simp apply (erule order_trans) apply (frule(1) le_plus) apply (rule word_l_diffs,simp+) apply (rule word_le_plus_either,simp) apply (subst olen_add_eqv) apply (subst add.commute) apply (erule(1) plus_minus_no_overflow_ab) apply (simp add: fromIntegral_def toInteger_nat fromInteger_nat) apply (rule conjI) apply (simp add: objBits_defs cte_level_bits_def) apply (clarsimp simp:of_nat_shiftR word_le_nat_alt) apply (frule_tac n = "unat (args ! 5)" and bits = "(APIType_capBits (toEnum (unat (args ! 0))) (unat (args ! 1)))" in range_cover_stuff[where rv = 0,rotated -1]) apply (simp add:unat_1_0) apply simp apply (simp add:word_sub_le_iff word_of_nat_le) apply simp+ apply (clarsimp simp:getFreeRef_def) apply (frule alignUp_idem[OF is_aligned_weaken,where a = w]) apply (erule range_cover.sz) apply (simp add:range_cover_def) apply (simp add:empty_descendants_range_in' untypedBits_defs) apply (clarsimp simp: image_def isCap_simps nullPointer_def word_size field_simps) apply (intro conjI) apply (clarsimp simp: image_def isCap_simps nullPointer_def word_size field_simps) apply (drule_tac x=x in spec)+ apply simp apply (clarsimp simp: APIType_capBits_def) apply clarsimp apply (clarsimp simp: image_def getFreeRef_def cte_level_bits_def objBits_simps' field_simps) apply (clarsimp simp: of_nat_shiftR word_le_nat_alt) apply (frule_tac n = "unat (args ! 5)" and bits = "(APIType_capBits (toEnum (unat (args ! 0))) (unat (args ! 1)))" in range_cover_stuff[where w=w and sz=sz and rv = idx,rotated -1]; simp?) apply (intro conjI; clarsimp simp add: image_def word_size) apply (clarsimp simp: image_def isCap_simps nullPointer_def word_size field_simps) apply (drule_tac x=x in spec)+ apply simp apply (clarsimp simp: APIType_capBits_def) done lemma corres_list_all2_mapM_': assumes w: "suffix xs oxs" "suffix ys oys" assumes y: "\<And>x xs y ys. \<lbrakk> F x y; suffix (x # xs) oxs; suffix (y # ys) oys \<rbrakk> \<Longrightarrow> corres dc (P (x # xs)) (P' (y # ys)) (f x) (g y)" assumes z: "\<And>x y xs. \<lbrakk> F x y; suffix (x # xs) oxs \<rbrakk> \<Longrightarrow> \<lbrace>P (x # xs)\<rbrace> f x \<lbrace>\<lambda>rv. P xs\<rbrace>" "\<And>x y ys. \<lbrakk> F x y; suffix (y # ys) oys \<rbrakk> \<Longrightarrow> \<lbrace>P' (y # ys)\<rbrace> g y \<lbrace>\<lambda>rv. P' ys\<rbrace>" assumes x: "list_all2 F xs ys" shows "corres dc (P xs) (P' ys) (mapM_x f xs) (mapM_x g ys)" apply (insert x w) apply (induct xs arbitrary: ys) apply (simp add: mapM_x_def sequence_x_def) apply (case_tac ys) apply simp apply (clarsimp simp add: mapM_x_def sequence_x_def) apply (rule corres_guard_imp) apply (rule corres_split[OF y]) apply assumption apply assumption apply assumption apply (clarsimp dest!: suffix_ConsD) apply (erule meta_allE, (drule(1) meta_mp)+) apply assumption apply (erule(1) z)+ apply simp+ done lemmas suffix_refl = suffix_order.refl lemmas corres_list_all2_mapM_ = corres_list_all2_mapM_' [OF suffix_refl suffix_refl] declare modify_map_id[simp] lemma valid_mdbD3': "\<lbrakk> ctes_of s p = Some cte; valid_mdb' s \<rbrakk> \<Longrightarrow> p \<noteq> 0" by (clarsimp simp add: valid_mdb'_def valid_mdb_ctes_def no_0_def) lemma capRange_sameRegionAs: "\<lbrakk> sameRegionAs x y; s \<turnstile>' y; capClass x = PhysicalClass \<or> capClass y = PhysicalClass \<rbrakk> \<Longrightarrow> capRange x \<inter> capRange y \<noteq> {}" apply (erule sameRegionAsE) apply (subgoal_tac "capClass x = capClass y \<and> capRange x = capRange y") apply simp apply (drule valid_capAligned) apply (drule(1) capAligned_capUntypedPtr) apply clarsimp apply (rule conjI) apply (rule master_eqI, rule capClass_Master, simp) apply (rule master_eqI, rule capRange_Master, simp) apply blast apply blast apply (clarsimp simp: isCap_simps)+ done end locale mdb_insert_again = mdb_ptr_parent?: mdb_ptr m _ _ parent parent_cap parent_node + mdb_ptr_site?: mdb_ptr m _ _ site site_cap site_node for m parent parent_cap parent_node site site_cap site_node + fixes c' assumes site_cap: "site_cap = NullCap" assumes site_prev: "mdbPrev site_node = 0" assumes site_next: "mdbNext site_node = 0" assumes is_untyped: "isUntypedCap parent_cap" assumes same_region: "sameRegionAs parent_cap c'" assumes range: "descendants_range' c' parent m" assumes phys: "capClass c' = PhysicalClass" fixes s assumes valid_capI': "m p = Some (CTE cap node) \<Longrightarrow> s \<turnstile>' cap" assumes ut_rev: "ut_revocable' m" fixes n defines "n \<equiv> (modify_map (\<lambda>x. if x = site then Some (CTE c' (MDB (mdbNext parent_node) parent True True)) else m x) parent (cteMDBNode_update (mdbNext_update (\<lambda>x. site))))" assumes neq: "parent \<noteq> site" context mdb_insert_again begin interpretation Arch . (*FIXME: arch_split*) lemmas parent = mdb_ptr_parent.m_p lemmas site = mdb_ptr_site.m_p lemma next_wont_bite: "\<lbrakk> mdbNext parent_node \<noteq> 0; m (mdbNext parent_node) = Some cte \<rbrakk> \<Longrightarrow> \<not> sameRegionAs c' (cteCap cte)" using range ut_rev apply (cases cte) apply clarsimp apply (cases "m \<turnstile> parent \<rightarrow> mdbNext parent_node") apply (drule (2) descendants_rangeD') apply (drule capRange_sameRegionAs) apply (erule valid_capI') apply (simp add: phys) apply blast apply (erule notE, rule direct_parent) apply (clarsimp simp: mdb_next_unfold parent) apply assumption apply (simp add: parentOf_def parent) apply (insert is_untyped same_region) apply (clarsimp simp: isMDBParentOf_CTE) apply (rule conjI) apply (erule (1) sameRegionAs_trans) apply (simp add: ut_revocable'_def) apply (insert parent) apply simp apply (clarsimp simp: isCap_simps) done lemma no_0_helper: "no_0 m \<Longrightarrow> no_0 n" by (simp add: n_def, simp add: no_0_def) lemma no_0_n [intro!]: "no_0 n" by (auto intro: no_0_helper) lemmas n_0_simps [iff] = no_0_simps [OF no_0_n] lemmas neqs [simp] = neq neq [symmetric] definition "new_site \<equiv> CTE c' (MDB (mdbNext parent_node) parent True True)" definition "new_parent \<equiv> CTE parent_cap (mdbNext_update (\<lambda>a. site) parent_node)" lemma n: "n = m (site \<mapsto> new_site, parent \<mapsto> new_parent)" using parent site by (simp add: n_def modify_map_apply new_site_def new_parent_def fun_upd_def[symmetric]) lemma site_no_parent [iff]: "m \<turnstile> site \<rightarrow> x = False" using site site_next by (auto dest: subtree_next_0) lemma site_no_child [iff]: "m \<turnstile> x \<rightarrow> site = False" using site site_prev by (auto dest: subtree_prev_0) lemma parent_next: "m \<turnstile> parent \<leadsto> mdbNext parent_node" by (simp add: parent mdb_next_unfold) lemma parent_next_rtrancl_conv [simp]: "m \<turnstile> mdbNext parent_node \<leadsto>\<^sup>* site = m \<turnstile> parent \<leadsto>\<^sup>+ site" apply (rule iffI) apply (insert parent_next) apply (fastforce dest: rtranclD) apply (drule tranclD) apply (clarsimp simp: mdb_next_unfold) done lemma site_no_next [iff]: "m \<turnstile> x \<leadsto> site = False" using site site_prev dlist apply clarsimp apply (simp add: mdb_next_unfold) apply (elim exE conjE) apply (case_tac z) apply simp apply (rule dlistEn [where p=x], assumption) apply clarsimp apply clarsimp done lemma site_no_next_trans [iff]: "m \<turnstile> x \<leadsto>\<^sup>+ site = False" by (clarsimp dest!: tranclD2) lemma site_no_prev [iff]: "m \<turnstile> site \<leadsto> p = (p = 0)" using site site_next by (simp add: mdb_next_unfold) lemma site_no_prev_trancl [iff]: "m \<turnstile> site \<leadsto>\<^sup>+ p = (p = 0)" apply (rule iffI) apply (drule tranclD) apply clarsimp apply simp apply (insert chain site) apply (simp add: mdb_chain_0_def) apply auto done lemma chain_n: "mdb_chain_0 n" proof - from chain have "m \<turnstile> mdbNext parent_node \<leadsto>\<^sup>* 0" using dlist parent apply (cases "mdbNext parent_node = 0") apply simp apply (erule dlistEn, simp) apply (auto simp: mdb_chain_0_def) done moreover have "\<not>m \<turnstile> mdbNext parent_node \<leadsto>\<^sup>* parent" using parent_next apply clarsimp apply (drule (1) rtrancl_into_trancl2) apply simp done moreover have "\<not> m \<turnstile> 0 \<leadsto>\<^sup>* site" using no_0 site by (auto elim!: next_rtrancl_tranclE dest!: no_0_lhs_trancl) moreover have "\<not> m \<turnstile> 0 \<leadsto>\<^sup>* parent" using no_0 parent by (auto elim!: next_rtrancl_tranclE dest!: no_0_lhs_trancl) moreover note chain ultimately show "mdb_chain_0 n" using no_0 parent site apply (simp add: n new_parent_def new_site_def) apply (auto intro!: mdb_chain_0_update no_0_update simp: next_update_lhs_rtrancl) done qed lemma no_loops_n: "no_loops n" using chain_n no_0_n by (rule mdb_chain_0_no_loops) lemma n_direct_eq: "n \<turnstile> p \<leadsto> p' = (if p = parent then p' = site else if p = site then m \<turnstile> parent \<leadsto> p' else m \<turnstile> p \<leadsto> p')" using parent site site_prev by (auto simp: mdb_next_update n new_parent_def new_site_def parent_next mdb_next_unfold) lemma next_not_parent: "\<lbrakk> mdbNext parent_node \<noteq> 0; m (mdbNext parent_node) = Some cte \<rbrakk> \<Longrightarrow> \<not> isMDBParentOf new_site cte" apply (drule(1) next_wont_bite) apply (cases cte) apply (simp add: isMDBParentOf_def new_site_def) done (* The newly inserted cap should never have children. *) lemma site_no_parent_n: "n \<turnstile> site \<rightarrow> p = False" using parent valid_badges apply clarsimp apply (erule subtree.induct) prefer 2 apply simp apply (clarsimp simp: parentOf_def mdb_next_unfold new_site_def n) apply (cases "mdbNext parent_node = site") apply (subgoal_tac "m \<turnstile> parent \<leadsto> site") apply simp apply (subst mdb_next_unfold) apply (simp add: parent) apply clarsimp apply (erule notE[rotated], erule(1) next_not_parent[unfolded new_site_def]) done end locale mdb_insert_again_child = mdb_insert_again + assumes child: "isMDBParentOf (CTE parent_cap parent_node) (CTE c' (MDB (mdbNext parent_node) parent True True))" context mdb_insert_again_child begin lemma new_child [simp]: "isMDBParentOf new_parent new_site" by (simp add: new_parent_def new_site_def) (rule child) lemma n_site_child: "n \<turnstile> parent \<rightarrow> site" apply (rule subtree.direct_parent) apply (simp add: n_direct_eq) apply simp apply (clarsimp simp: parentOf_def parent site n) done lemma parent_m_n: assumes "m \<turnstile> p \<rightarrow> p'" shows "if p' = parent then n \<turnstile> p \<rightarrow> site \<and> n \<turnstile> p \<rightarrow> p' else n \<turnstile> p \<rightarrow> p'" using assms proof induct case (direct_parent c) thus ?case apply (cases "p = parent") apply simp apply (rule conjI, clarsimp) apply clarsimp apply (rule subtree.trans_parent [where c'=site]) apply (rule n_site_child) apply (simp add: n_direct_eq) apply simp apply (clarsimp simp: parentOf_def n) apply (clarsimp simp: new_parent_def parent) apply simp apply (subgoal_tac "n \<turnstile> p \<rightarrow> c") prefer 2 apply (rule subtree.direct_parent) apply (clarsimp simp add: n_direct_eq) apply simp apply (clarsimp simp: parentOf_def n) apply (fastforce simp: new_parent_def parent) apply clarsimp apply (erule subtree_trans) apply (rule n_site_child) done next case (trans_parent c d) thus ?case apply - apply (cases "c = site", simp) apply (cases "d = site", simp) apply (cases "c = parent") apply clarsimp apply (erule subtree.trans_parent [where c'=site]) apply (clarsimp simp add: n_direct_eq) apply simp apply (clarsimp simp: parentOf_def n) apply (rule conjI, clarsimp) apply (clarsimp simp: new_parent_def parent) apply clarsimp apply (subgoal_tac "n \<turnstile> p \<rightarrow> d") apply clarsimp apply (erule subtree_trans, rule n_site_child) apply (erule subtree.trans_parent) apply (simp add: n_direct_eq) apply simp apply (clarsimp simp: parentOf_def n) apply (fastforce simp: parent new_parent_def) done qed lemma n_to_site [simp]: "n \<turnstile> p \<leadsto> site = (p = parent)" by (simp add: n_direct_eq) lemma parent_n_m: assumes "n \<turnstile> p \<rightarrow> p'" shows "if p' = site then p \<noteq> parent \<longrightarrow> m \<turnstile> p \<rightarrow> parent else m \<turnstile> p \<rightarrow> p'" proof - from assms have [simp]: "p \<noteq> site" by (clarsimp simp: site_no_parent_n) from assms show ?thesis proof induct case (direct_parent c) thus ?case apply simp apply (rule conjI) apply clarsimp apply clarsimp apply (rule subtree.direct_parent) apply (simp add: n_direct_eq split: if_split_asm) apply simp apply (clarsimp simp: parentOf_def n parent new_parent_def split: if_split_asm) done next case (trans_parent c d) thus ?case apply clarsimp apply (rule conjI, clarsimp) apply (clarsimp split: if_split_asm) apply (simp add: n_direct_eq) apply (cases "p=parent") apply simp apply (rule subtree.direct_parent, assumption, assumption) apply (clarsimp simp: parentOf_def n parent new_parent_def split: if_split_asm) apply clarsimp apply (erule subtree.trans_parent, assumption, assumption) apply (clarsimp simp: parentOf_def n parent new_parent_def split: if_split_asm) apply (erule subtree.trans_parent) apply (simp add: n_direct_eq split: if_split_asm) apply assumption apply (clarsimp simp: parentOf_def n parent new_parent_def split: if_split_asm) done qed qed lemma descendants: "descendants_of' p n = (if parent \<in> descendants_of' p m \<or> p = parent then descendants_of' p m \<union> {site} else descendants_of' p m)" apply (rule set_eqI) apply (simp add: descendants_of'_def) apply (fastforce dest!: parent_n_m dest: parent_m_n simp: n_site_child split: if_split_asm) done end lemma blarg_descendants_of': "descendants_of' x (modify_map m p (if P then id else cteMDBNode_update (mdbPrev_update f))) = descendants_of' x m" by (simp add: descendants_of'_def) lemma bluhr_descendants_of': "mdb_insert_again_child (ctes_of s') parent parent_cap pmdb site site_cap site_node cap s \<Longrightarrow> descendants_of' x (modify_map (modify_map (\<lambda>c. if c = site then Some (CTE cap (MDB (mdbNext pmdb) parent True True)) else ctes_of s' c) (mdbNext pmdb) (if mdbNext pmdb = 0 then id else cteMDBNode_update (mdbPrev_update (\<lambda>x. site)))) parent (cteMDBNode_update (mdbNext_update (\<lambda>x. site)))) = (if parent \<in> descendants_of' x (ctes_of s') \<or> x = parent then descendants_of' x (ctes_of s') \<union> {site} else descendants_of' x (ctes_of s'))" apply (subst modify_map_com) apply (case_tac x, rename_tac node, case_tac node, clarsimp) apply (subst blarg_descendants_of') apply (erule mdb_insert_again_child.descendants) done lemma mdb_relation_simp: "\<lbrakk> (s, s') \<in> state_relation; cte_at p s \<rbrakk> \<Longrightarrow> descendants_of' (cte_map p) (ctes_of s') = cte_map ` descendants_of p (cdt s)" by (cases p, clarsimp simp: state_relation_def cdt_relation_def) lemma in_getCTE2: "((cte, s') \<in> fst (getCTE p s)) = (s' = s \<and> cte_wp_at' ((=) cte) p s)" apply (safe dest!: in_getCTE) apply (clarsimp simp: cte_wp_at'_def getCTE_def) done declare wrap_ext_op_det_ext_ext_def[simp] lemma do_ext_op_update_cdt_list_symb_exec_l': "corres_underlying {(s::det_state, s'). f (kheap s) (ekheap s) s'} nf nf' dc P P' (create_cap_ext p z a) (return x)" apply (simp add: corres_underlying_def create_cap_ext_def update_cdt_list_def set_cdt_list_def bind_def put_def get_def gets_def return_def) done crunches updateMDB, updateNewFreeIndex for it'[wp]: "\<lambda>s. P (ksIdleThread s)" and ups'[wp]: "\<lambda>s. P (gsUserPages s)" and cns'[wp]: "\<lambda>s. P (gsCNodes s)" and ksDomainTime[wp]: "\<lambda>s. P (ksDomainTime s)" and ksDomScheduleIdx[wp]: "\<lambda>s. P (ksDomScheduleIdx s)" and ksWorkUnitsCompleted[wp]: "\<lambda>s. P (ksWorkUnitsCompleted s)" and ksMachineState[wp]: "\<lambda>s. P (ksMachineState s)" and ksArchState[wp]: "\<lambda>s. P (ksArchState s)" crunches insertNewCap for ksInterrupt[wp]: "\<lambda>s. P (ksInterruptState s)" and norq[wp]: "\<lambda>s. P (ksReadyQueues s)" and ksIdleThread[wp]: "\<lambda>s. P (ksIdleThread s)" and ksDomSchedule[wp]: "\<lambda>s. P (ksDomSchedule s)" and ksCurDomain[wp]: "\<lambda>s. P (ksCurDomain s)" and ksCurThread[wp]: "\<lambda>s. P (ksCurThread s)" (wp: crunch_wps) crunch nosch[wp]: insertNewCaps "\<lambda>s. P (ksSchedulerAction s)" (simp: crunch_simps zipWithM_x_mapM wp: crunch_wps) crunch exst[wp]: set_cdt "\<lambda>s. P (exst s)" (*FIXME: Move to StateRelation*) lemma state_relation_schact[elim!]: "(s,s') \<in> state_relation \<Longrightarrow> sched_act_relation (scheduler_action s) (ksSchedulerAction s')" apply (simp add: state_relation_def) done lemma state_relation_queues[elim!]: "(s,s') \<in> state_relation \<Longrightarrow> ready_queues_relation (ready_queues s) (ksReadyQueues s')" apply (simp add: state_relation_def) done lemma set_original_symb_exec_l: "corres_underlying {(s, s'). f (kheap s) (exst s) s'} nf nf' dc P P' (set_original p b) (return x)" by (simp add: corres_underlying_def return_def set_original_def in_monad Bex_def) lemma set_cdt_symb_exec_l: "corres_underlying {(s, s'). f (kheap s) (exst s) s'} nf nf' dc P P' (set_cdt g) (return x)" by (simp add: corres_underlying_def return_def set_cdt_def in_monad Bex_def) crunches create_cap_ext for domain_index[wp]: "\<lambda>s. P (domain_index s)" and domain_list[wp]: "\<lambda>s. P (domain_list s)" and domain_time[wp]: "\<lambda>s. P (domain_time s)" and work_units_completed[wp]: "\<lambda>s. P (work_units_completed s)" (ignore_del: create_cap_ext) context begin interpretation Arch . (*FIXME: arch_split*) lemma updateNewFreeIndex_noop_psp_corres: "corres_underlying {(s, s'). pspace_relations (ekheap s) (kheap s) (ksPSpace s')} False True dc \<top> (cte_at' slot) (return ()) (updateNewFreeIndex slot)" apply (simp add: updateNewFreeIndex_def) apply (rule corres_guard_imp) apply (rule corres_bind_return2) apply (rule corres_symb_exec_r_conj[where P'="cte_at' slot"]) apply (rule corres_trivial, simp) apply (wp getCTE_wp' | wpc | simp add: updateTrackedFreeIndex_def getSlotCap_def)+ done lemma insertNewCap_corres: notes if_cong[cong del] if_weak_cong[cong] shows "\<lbrakk> cref' = cte_map (fst tup) \<and> cap_relation (default_cap tp (snd tup) sz d) cap \<rbrakk> \<Longrightarrow> corres dc (cte_wp_at ((=) cap.NullCap) (fst tup) and pspace_aligned and pspace_distinct and valid_objs and valid_mdb and valid_list and cte_wp_at ((\<noteq>) cap.NullCap) p) (cte_wp_at' (\<lambda>c. cteCap c = NullCap) cref' and cte_wp_at' (\<lambda>cte. isUntypedCap (cteCap cte) \<and> sameRegionAs (cteCap cte) cap) (cte_map p) and valid_mdb' and pspace_aligned' and pspace_distinct' and valid_objs' and (\<lambda>s. descendants_range' cap (cte_map p) (ctes_of s))) (create_cap tp sz p d tup) (insertNewCap (cte_map p) cref' cap)" apply (cases tup, clarsimp simp add: create_cap_def insertNewCap_def liftM_def) apply (rule corres_symb_exec_r [OF _ getCTE_sp])+ prefer 3 apply (rule no_fail_pre, wp) apply (clarsimp elim!: cte_wp_at_weakenE') prefer 4 apply (rule no_fail_pre, wp) apply (clarsimp elim!: cte_wp_at_weakenE') apply (rule corres_assert_assume) prefer 2 apply (case_tac oldCTE) apply (clarsimp simp: cte_wp_at_ctes_of valid_mdb'_def valid_mdb_ctes_def valid_nullcaps_def) apply (erule allE)+ apply (erule (1) impE) apply (simp add: initMDBNode_def) apply clarsimp apply (rule_tac F="capClass cap = PhysicalClass" in corres_req) apply (clarsimp simp: cte_wp_at_ctes_of isCap_simps) apply (drule sameRegionAs_classes, simp) apply (rule corres_caps_decomposition) prefer 3 apply wp+ apply (rule hoare_post_imp, simp) apply (wp | assumption)+ defer apply ((wp | simp)+)[1] apply (simp add: create_cap_ext_def set_cdt_list_def update_cdt_list_def bind_assoc) apply ((wp | simp)+)[1] apply (wp updateMDB_ctes_of_cases | simp add: o_def split del: if_split)+ apply (clarsimp simp: cdt_relation_def cte_wp_at_ctes_of split del: if_split cong: if_cong simp del: id_apply) apply (subst if_not_P, erule(1) valid_mdbD3') apply (case_tac x, case_tac oldCTE) apply (subst bluhr_descendants_of') apply (rule mdb_insert_again_child.intro) apply (rule mdb_insert_again.intro) apply (rule mdb_ptr.intro) apply (simp add: valid_mdb'_def vmdb_def) apply (rule mdb_ptr_axioms.intro) apply simp apply (rule mdb_ptr.intro) apply (simp add: valid_mdb'_def vmdb_def) apply (rule mdb_ptr_axioms.intro) apply fastforce apply (rule mdb_insert_again_axioms.intro) apply (clarsimp simp: nullPointer_def)+ apply (erule (1) ctes_of_valid_cap') apply (simp add: valid_mdb'_def valid_mdb_ctes_def) apply clarsimp apply (rule mdb_insert_again_child_axioms.intro) apply (clarsimp simp: isMDBParentOf_def) apply (clarsimp simp: isCap_simps) apply (clarsimp simp: valid_mdb'_def valid_mdb_ctes_def ut_revocable'_def) apply (fold fun_upd_def) apply (subst descendants_of_insert_child') apply (erule(1) mdb_Null_descendants) apply (clarsimp simp: cte_wp_at_def) apply (erule(1) mdb_Null_None) apply (subgoal_tac "cte_at (aa, bb) s") prefer 2 apply (drule not_sym, clarsimp simp: cte_wp_at_caps_of_state split: if_split_asm) apply (subst descendants_of_eq' [OF _ cte_wp_at_cte_at], assumption+) apply (clarsimp simp: state_relation_def) apply assumption+ apply (subst cte_map_eq_subst [OF _ cte_wp_at_cte_at], assumption+) apply (simp add: mdb_relation_simp) defer apply (clarsimp split del: if_split)+ apply (clarsimp simp add: revokable_relation_def cte_wp_at_ctes_of split del: if_split) apply simp apply (rule conjI) apply clarsimp apply (elim modify_map_casesE) apply ((clarsimp split: if_split_asm cong: conj_cong simp: cte_map_eq_subst cte_wp_at_cte_at revokable_relation_simp)+)[4] apply clarsimp apply (subgoal_tac "null_filter (caps_of_state s) (aa, bb) \<noteq> None") prefer 2 apply (clarsimp simp: null_filter_def cte_wp_at_caps_of_state split: if_split_asm) apply (subgoal_tac "cte_at (aa,bb) s") prefer 2 apply clarsimp apply (drule null_filter_caps_of_stateD) apply (erule cte_wp_cte_at) apply (elim modify_map_casesE) apply (clarsimp split: if_split_asm cong: conj_cong simp: cte_map_eq_subst cte_wp_at_cte_at revokable_relation_simp)+ apply (clarsimp simp: state_relation_def ghost_relation_of_heap)+ apply wp+ apply (rule corres_guard_imp) apply (rule corres_underlying_symb_exec_l [OF gets_symb_exec_l]) apply (rule corres_underlying_symb_exec_l [OF gets_symb_exec_l]) apply (rule corres_underlying_symb_exec_l [OF set_cdt_symb_exec_l]) apply (rule corres_underlying_symb_exec_l [OF do_ext_op_update_cdt_list_symb_exec_l']) apply (rule corres_underlying_symb_exec_l [OF set_original_symb_exec_l]) apply (rule corres_cong[OF refl refl _ refl refl, THEN iffD1]) apply (rule bind_return[THEN fun_cong]) apply (rule corres_split) apply (rule setCTE_corres; simp) apply (subst bind_return[symmetric], rule corres_split) apply (simp add: dc_def[symmetric]) apply (rule updateMDB_symb_exec_r) apply (simp add: dc_def[symmetric]) apply (rule corres_split_noop_rhs[OF updateMDB_symb_exec_r]) apply (rule updateNewFreeIndex_noop_psp_corres) apply (wp getCTE_wp set_cdt_valid_objs set_cdt_cte_at hoare_weak_lift_imp | simp add: o_def)+ apply (clarsimp simp: cte_wp_at_cte_at) apply (clarsimp simp: cte_wp_at_ctes_of no_0_def valid_mdb'_def valid_mdb_ctes_def) apply (rule conjI, clarsimp) apply clarsimp apply (erule (2) valid_dlistEn) apply simp apply(simp only: cdt_list_relation_def valid_mdb_def2) apply(subgoal_tac "finite_depth (cdt s)") prefer 2 apply(simp add: finite_depth valid_mdb_def2[symmetric]) apply(intro impI allI) apply(subgoal_tac "mdb_insert_abs (cdt s) p (a, b)") prefer 2 apply(clarsimp simp: cte_wp_at_caps_of_state) apply(rule mdb_insert_abs.intro) apply(clarsimp) apply(erule (1) mdb_cte_at_Null_None) apply (erule (1) mdb_cte_at_Null_descendants) apply(subgoal_tac "no_0 (ctes_of s')") prefer 2 apply(simp add: valid_mdb_ctes_def valid_mdb'_def) apply simp apply (elim conjE) apply (case_tac "cdt s (a,b)") prefer 2 apply (simp add: mdb_insert_abs_def) apply simp apply(case_tac x) apply(simp add: cte_wp_at_ctes_of) apply(simp add: mdb_insert_abs.next_slot split del: if_split) apply(case_tac "c=p") apply(simp) apply(clarsimp simp: modify_map_def) apply(case_tac z) apply(fastforce split: if_split_asm) apply(case_tac "c = (a, b)") apply(simp) apply(case_tac "next_slot p (cdt_list s) (cdt s)") apply(simp) apply(simp) apply(clarsimp simp: modify_map_def const_def) apply(clarsimp split: if_split_asm) apply(drule_tac p="cte_map p" in valid_mdbD1') apply(simp) apply(simp add: valid_mdb'_def valid_mdb_ctes_def) apply(clarsimp simp: nullPointer_def no_0_def) apply(clarsimp simp: state_relation_def) apply(clarsimp simp: cte_wp_at_caps_of_state) apply(drule_tac slot=p in pspace_relation_ctes_ofI) apply(simp add: cte_wp_at_caps_of_state) apply(simp) apply(simp) apply(simp) apply(clarsimp simp: state_relation_def cdt_list_relation_def) apply(erule_tac x="fst p" in allE, erule_tac x="snd p" in allE) apply(fastforce) apply(simp) apply(case_tac "next_slot c (cdt_list s) (cdt s)") apply(simp) apply(simp) apply(subgoal_tac "cte_at c s") prefer 2 apply(rule cte_at_next_slot) apply(simp_all add: valid_mdb_def2)[4] apply(clarsimp simp: modify_map_def const_def) apply(simp split: if_split_asm) apply(simp add: valid_mdb'_def) apply(drule_tac ptr="cte_map p" in no_self_loop_next) apply(simp) apply(simp) apply(drule_tac p="(aa, bb)" in cte_map_inj) apply(simp_all add: cte_wp_at_caps_of_state)[5] apply(clarsimp) apply(simp) apply(clarsimp) apply(drule cte_map_inj_eq; simp add: cte_wp_at_caps_of_state) apply(clarsimp) apply(case_tac z) apply(clarsimp simp: state_relation_def cdt_list_relation_def) apply(erule_tac x=aa in allE, erule_tac x=bb in allE) apply(fastforce) apply(clarsimp) apply(drule cte_map_inj_eq) apply(simp_all add: cte_wp_at_caps_of_state)[6] apply(clarsimp simp: state_relation_def cdt_list_relation_def) apply(erule_tac x=aa in allE, erule_tac x=bb in allE, fastforce) done lemma setCTE_cteCaps_of[wp]: "\<lbrace>\<lambda>s. P ((cteCaps_of s)(p \<mapsto> cteCap cte))\<rbrace> setCTE p cte \<lbrace>\<lambda>rv s. P (cteCaps_of s)\<rbrace>" apply (simp add: cteCaps_of_def) apply wp apply (clarsimp elim!: rsubst[where P=P] intro!: ext) done lemma insertNewCap_wps[wp]: "\<lbrace>pspace_aligned'\<rbrace> insertNewCap parent slot cap \<lbrace>\<lambda>rv. pspace_aligned'\<rbrace>" "\<lbrace>pspace_canonical'\<rbrace> insertNewCap parent slot cap \<lbrace>\<lambda>rv. pspace_canonical'\<rbrace>" "\<lbrace>pspace_in_kernel_mappings'\<rbrace> insertNewCap parent slot cap \<lbrace>\<lambda>rv. pspace_in_kernel_mappings'\<rbrace>" "\<lbrace>pspace_distinct'\<rbrace> insertNewCap parent slot cap \<lbrace>\<lambda>rv. pspace_distinct'\<rbrace>" "\<lbrace>\<lambda>s. P ((cteCaps_of s)(slot \<mapsto> cap))\<rbrace> insertNewCap parent slot cap \<lbrace>\<lambda>rv s. P (cteCaps_of s)\<rbrace>" apply (simp_all add: insertNewCap_def) apply (wp hoare_drop_imps | simp add: o_def)+ apply (clarsimp elim!: rsubst[where P=P] intro!: ext) done definition apitype_of :: "cap \<Rightarrow> apiobject_type option" where "apitype_of c \<equiv> case c of Structures_A.UntypedCap d p b idx \<Rightarrow> Some ArchTypes_H.Untyped | Structures_A.EndpointCap r badge rights \<Rightarrow> Some EndpointObject | Structures_A.NotificationCap r badge rights \<Rightarrow> Some NotificationObject | Structures_A.CNodeCap r bits guard \<Rightarrow> Some ArchTypes_H.CapTableObject | Structures_A.ThreadCap r \<Rightarrow> Some TCBObject | _ \<Rightarrow> None" lemma cte_wp_at_cteCaps_of: "cte_wp_at' (\<lambda>cte. P (cteCap cte)) p s = (\<exists>cap. cteCaps_of s p = Some cap \<and> P cap)" apply (subst tree_cte_cteCap_eq[unfolded o_def]) apply (clarsimp split: option.splits) done lemma caps_contained_modify_mdb_helper[simp]: "(\<exists>n. modify_map m p (cteMDBNode_update f) x = Some (CTE c n)) = (\<exists>n. m x = Some (CTE c n))" apply (cases "m p", simp_all add: modify_map_def) apply (case_tac a, simp_all) done lemma sameRegionAs_capRange_subset: "\<lbrakk> sameRegionAs c c'; capClass c = PhysicalClass \<rbrakk> \<Longrightarrow> capRange c' \<subseteq> capRange c" apply (erule sameRegionAsE) apply (rule equalityD1) apply (rule master_eqI, rule capRange_Master) apply simp apply assumption+ apply (clarsimp simp: isCap_simps)+ done definition is_end_chunk :: "cte_heap \<Rightarrow> capability \<Rightarrow> machine_word \<Rightarrow> bool" where "is_end_chunk ctes cap p \<equiv> \<exists>p'. ctes \<turnstile> p \<leadsto> p' \<and> (\<exists>cte. ctes p = Some cte \<and> sameRegionAs cap (cteCap cte)) \<and> (\<forall>cte'. ctes p' = Some cte' \<longrightarrow> \<not> sameRegionAs cap (cteCap cte'))" definition mdb_chunked2 :: "cte_heap \<Rightarrow> bool" where "mdb_chunked2 ctes \<equiv> (\<forall>x p p' cte. ctes x = Some cte \<and> is_end_chunk ctes (cteCap cte) p \<and> is_end_chunk ctes (cteCap cte) p' \<longrightarrow> p = p') \<and> (\<forall>p p' cte cte'. ctes p = Some cte \<and> ctes p' = Some cte' \<and> ctes \<turnstile> p \<leadsto> p' \<and> sameRegionAs (cteCap cte') (cteCap cte) \<longrightarrow> sameRegionAs (cteCap cte) (cteCap cte'))" lemma mdb_chunked2_revD: "\<lbrakk> ctes p = Some cte; ctes p' = Some cte'; ctes \<turnstile> p \<leadsto> p'; mdb_chunked2 ctes; sameRegionAs (cteCap cte') (cteCap cte) \<rbrakk> \<Longrightarrow> sameRegionAs (cteCap cte) (cteCap cte')" by (fastforce simp add: mdb_chunked2_def) lemma valid_dlist_step_back: "\<lbrakk> ctes \<turnstile> p \<leadsto> p''; ctes \<turnstile> p' \<leadsto> p''; valid_dlist ctes; p'' \<noteq> 0 \<rbrakk> \<Longrightarrow> p = p'" apply (simp add: mdb_next_unfold valid_dlist_def) apply (frule_tac x=p in spec) apply (drule_tac x=p' in spec) apply (clarsimp simp: Let_def) done lemma chunk_sameRegionAs_step1: "\<lbrakk> ctes \<turnstile> p' \<leadsto>\<^sup>* p''; ctes p'' = Some cte; is_chunk ctes (cteCap cte) p p''; mdb_chunked2 ctes; valid_dlist ctes \<rbrakk> \<Longrightarrow> \<forall>cte'. ctes p' = Some cte' \<longrightarrow> ctes \<turnstile> p \<leadsto>\<^sup>+ p' \<longrightarrow> sameRegionAs (cteCap cte') (cteCap cte)" apply (erule converse_rtrancl_induct) apply (clarsimp simp: is_chunk_def) apply (drule_tac x=p'' in spec, clarsimp) apply (clarsimp simp: is_chunk_def) apply (frule_tac x=y in spec) apply (drule_tac x=z in spec) apply ((drule mp, erule(1) transitive_closure_trans) | clarsimp)+ apply (rule sameRegionAs_trans[rotated], assumption) apply (drule(3) mdb_chunked2_revD) apply simp apply (erule(1) sameRegionAs_trans) apply simp done end locale mdb_insert_again_all = mdb_insert_again_child + assumes valid_c': "s \<turnstile>' c'" fixes n' defines "n' \<equiv> modify_map n (mdbNext parent_node) (cteMDBNode_update (mdbPrev_update (\<lambda>a. site)))" begin interpretation Arch . (*FIXME: arch_split*) lemma no_0_n' [simp]: "no_0 n'" using no_0_n by (simp add: n'_def) lemma dom_n' [simp]: "dom n' = dom n" apply (simp add: n'_def) apply (simp add: modify_map_if dom_def) apply (rule set_eqI) apply simp apply (rule iffI) apply auto[1] apply clarsimp apply (case_tac y) apply (case_tac "mdbNext parent_node = x") apply auto done lemma mdb_chain_0_n' [simp]: "mdb_chain_0 n'" using chain_n apply (simp add: mdb_chain_0_def) apply (simp add: n'_def trancl_prev_update) done lemma parency_n': "n' \<turnstile> p \<rightarrow> p' = (if m \<turnstile> p \<rightarrow> parent \<or> p = parent then m \<turnstile> p \<rightarrow> p' \<or> p' = site else m \<turnstile> p \<rightarrow> p')" using descendants [of p] unfolding descendants_of'_def by (auto simp add: set_eq_iff n'_def) lemma n'_direct_eq: "n' \<turnstile> p \<leadsto> p' = (if p = parent then p' = site else if p = site then m \<turnstile> parent \<leadsto> p' else m \<turnstile> p \<leadsto> p')" by (simp add: n'_def n_direct_eq) lemma n'_tranclD: "n' \<turnstile> p \<leadsto>\<^sup>+ p' \<Longrightarrow> (if p = site then m \<turnstile> parent \<leadsto>\<^sup>+ p' else if m \<turnstile> p \<leadsto>\<^sup>+ parent \<or> p = parent then m \<turnstile> p \<leadsto>\<^sup>+ p' \<or> p' = site else m \<turnstile> p \<leadsto>\<^sup>+ p')" apply (erule trancl_induct) apply (fastforce simp: n'_direct_eq split: if_split_asm) apply (fastforce simp: n'_direct_eq split: if_split_asm elim: trancl_trans) done lemma site_in_dom: "site \<in> dom n" by (simp add: n) lemma m_tranclD: assumes m: "m \<turnstile> p \<leadsto>\<^sup>+ p'" shows "p' \<noteq> site \<and> n' \<turnstile> p \<leadsto>\<^sup>+ p'" proof - from m have "p = site \<longrightarrow> p' = 0" by clarsimp with mdb_chain_0_n' m show ?thesis apply - apply (erule trancl_induct) apply (rule context_conjI) apply clarsimp apply (cases "p = site") apply (simp add: mdb_chain_0_def site_in_dom) apply (cases "p = parent") apply simp apply (rule trancl_trans) apply (rule r_into_trancl) apply (simp add: n'_direct_eq) apply (rule r_into_trancl) apply (simp add: n'_direct_eq) apply (rule r_into_trancl) apply (simp add: n'_direct_eq) apply (rule context_conjI) apply clarsimp apply clarsimp apply (erule trancl_trans) apply (case_tac "y = parent") apply simp apply (rule trancl_trans) apply (rule r_into_trancl) apply (simp add: n'_direct_eq) apply (rule r_into_trancl) apply (simp add: n'_direct_eq) apply (rule r_into_trancl) apply (simp add: n'_direct_eq) done qed lemma n'_trancl_eq: "n' \<turnstile> p \<leadsto>\<^sup>+ p' = (if p = site then m \<turnstile> parent \<leadsto>\<^sup>+ p' else if m \<turnstile> p \<leadsto>\<^sup>+ parent \<or> p = parent then m \<turnstile> p \<leadsto>\<^sup>+ p' \<or> p' = site else m \<turnstile> p \<leadsto>\<^sup>+ p')" apply simp apply (intro conjI impI iffI) apply (drule n'_tranclD) apply simp apply simp apply (drule n'_tranclD) apply simp apply (erule disjE) apply (drule m_tranclD)+ apply simp apply (drule m_tranclD) apply simp apply (erule trancl_trans) apply (rule r_into_trancl) apply (simp add: n'_direct_eq) apply (drule n'_tranclD, simp) apply (erule disjE) apply (drule m_tranclD) apply simp apply simp apply (rule r_into_trancl) apply (simp add: n'_direct_eq) apply (drule n'_tranclD, simp) apply simp apply (cases "p' = site", simp) apply (drule m_tranclD) apply clarsimp apply (drule tranclD) apply (clarsimp simp: n'_direct_eq) apply (simp add: rtrancl_eq_or_trancl) apply (drule n'_tranclD, simp) apply clarsimp apply (drule m_tranclD, simp) done lemma n'_rtrancl_eq: "n' \<turnstile> p \<leadsto>\<^sup>* p' = (if p = site then p' \<noteq> site \<and> m \<turnstile> parent \<leadsto>\<^sup>+ p' \<or> p' = site else if m \<turnstile> p \<leadsto>\<^sup>* parent then m \<turnstile> p \<leadsto>\<^sup>* p' \<or> p' = site else m \<turnstile> p \<leadsto>\<^sup>* p')" by (auto simp: rtrancl_eq_or_trancl n'_trancl_eq) lemma mdbNext_parent_site [simp]: "mdbNext parent_node \<noteq> site" proof assume "mdbNext parent_node = site" hence "m \<turnstile> parent \<leadsto> site" using parent by (unfold mdb_next_unfold) simp thus False by simp qed lemma mdbPrev_parent_site [simp]: "site \<noteq> mdbPrev parent_node" proof assume "site = mdbPrev parent_node" with parent site have "m \<turnstile> site \<leadsto> parent" apply (unfold mdb_next_unfold) apply simp apply (erule dlistEp) apply clarsimp apply clarsimp done with p_0 show False by simp qed lemma parent_prev: "(m \<turnstile> parent \<leftarrow> p) = (p = mdbNext parent_node \<and> p \<noteq> 0)" apply (rule iffI) apply (frule dlist_prevD, rule parent) apply (simp add: mdb_next_unfold parent) apply (clarsimp simp: mdb_prev_def) apply clarsimp apply (rule dlist_nextD0) apply (rule parent_next) apply assumption done lemma parent_next_prev: "(m \<turnstile> p \<leftarrow> mdbNext parent_node) = (p = parent \<and> mdbNext parent_node \<noteq> 0)" using parent apply - apply (rule iffI) apply (clarsimp simp add: mdb_prev_def) apply (rule conjI) apply (erule dlistEn) apply clarsimp apply simp apply clarsimp apply clarsimp apply (rule dlist_nextD0) apply (rule parent_next) apply assumption done lemma n'_prev_eq: notes if_cong[cong del] if_weak_cong[cong] shows "n' \<turnstile> p \<leftarrow> p' = (if p' = site then p = parent else if p = site then m \<turnstile> parent \<leftarrow> p' else if p = parent then p' = site else m \<turnstile> p \<leftarrow> p')" using parent site site_prev apply (simp add: n'_def n mdb_prev_def new_parent_def new_site_def split del: if_split) apply (clarsimp simp add: modify_map_if cong: if_cong split del: if_split) apply (cases "p' = site", simp) apply (simp cong: if_cong split del: if_split) apply (cases "p' = parent") apply clarsimp apply (rule conjI, clarsimp simp: mdb_prev_def) apply (clarsimp simp: mdb_prev_def) apply (simp cong: if_cong split del: if_split) apply (cases "p = site") apply (simp add: parent_prev) apply (cases "mdbNext parent_node = p'") apply simp apply (rule iffI) prefer 2 apply clarsimp apply (erule dlistEn) apply simp apply clarsimp apply (case_tac cte') apply clarsimp apply clarsimp apply clarsimp apply (insert site_next)[1] apply (rule valid_dlistEp [OF dlist, where p=p'], assumption) apply clarsimp apply clarsimp apply (simp cong: if_cong split del: if_split) apply (cases "p = parent") apply clarsimp apply (insert site_next) apply (cases "mdbNext parent_node = p'", clarsimp) apply clarsimp apply (rule valid_dlistEp [OF dlist, where p=p'], assumption) apply clarsimp apply clarsimp apply simp apply (cases "mdbNext parent_node = p'") prefer 2 apply (clarsimp simp: mdb_prev_def) apply (rule iffI, clarsimp) apply clarsimp apply (case_tac z) apply simp apply (rule iffI) apply (clarsimp simp: mdb_prev_def) apply (drule sym [where t=p']) apply (simp add: parent_next_prev) done lemma dlist_n' [simp]: notes if_cong[cong del] if_weak_cong[cong] shows "valid_dlist n'" using no_0_n' by (clarsimp simp: valid_dlist_def2 n'_direct_eq n'_prev_eq Invariants_H.valid_dlist_prevD [OF dlist]) lemma n'_cap: "n' p = Some (CTE c node) \<Longrightarrow> if p = site then c = c' \<and> m p = Some (CTE NullCap site_node) else \<exists>node'. m p = Some (CTE c node')" by (auto simp: n'_def n modify_map_if new_parent_def parent new_site_def site site_cap split: if_split_asm) lemma m_cap: "m p = Some (CTE c node) \<Longrightarrow> if p = site then \<exists>node'. n' site = Some (CTE c' node') else \<exists>node'. n' p = Some (CTE c node')" by (clarsimp simp: n n'_def new_parent_def new_site_def parent) lemma n'_badged: "n' p = Some (CTE c node) \<Longrightarrow> if p = site then c = c' \<and> mdbFirstBadged node else \<exists>node'. m p = Some (CTE c node') \<and> mdbFirstBadged node = mdbFirstBadged node'" by (auto simp: n'_def n modify_map_if new_parent_def parent new_site_def site site_cap split: if_split_asm) lemma no_next_region: "\<lbrakk> m \<turnstile> parent \<leadsto> p'; m p' = Some (CTE cap' node) \<rbrakk> \<Longrightarrow> \<not>sameRegionAs c' cap'" apply (clarsimp simp: mdb_next_unfold parent) apply (frule next_wont_bite [rotated], clarsimp) apply simp done lemma valid_badges_n' [simp]: "valid_badges n'" using valid_badges apply (clarsimp simp: valid_badges_def) apply (simp add: n'_direct_eq) apply (drule n'_badged)+ apply (clarsimp split: if_split_asm) apply (drule (1) no_next_region) apply simp apply (erule_tac x=p in allE) apply (erule_tac x=p' in allE) apply simp done lemma c'_not_Null: "c' \<noteq> NullCap" using same_region by clarsimp lemma valid_nullcaps_n' [simp]: "valid_nullcaps n'" using nullcaps is_untyped c'_not_Null apply (clarsimp simp: valid_nullcaps_def n'_def n modify_map_if new_site_def new_parent_def isCap_simps) apply (erule allE)+ apply (erule (1) impE) apply (simp add: nullMDBNode_def) apply (insert parent) apply (rule dlistEn, rule parent) apply clarsimp apply (clarsimp simp: nullPointer_def) done lemma phys': "capClass parent_cap = PhysicalClass" using sameRegionAs_classes [OF same_region] phys by simp lemma capRange_c': "capRange c' \<subseteq> capRange parent_cap" apply (rule sameRegionAs_capRange_subset) apply (rule same_region) apply (rule phys') done lemma untypedRange_c': assumes ut: "isUntypedCap c'" shows "untypedRange c' \<subseteq> untypedRange parent_cap" using ut is_untyped capRange_c' by (auto simp: isCap_simps) lemma sameRegion_parentI: "sameRegionAs c' cap \<Longrightarrow> sameRegionAs parent_cap cap" using same_region apply - apply (erule (1) sameRegionAs_trans) done lemma no_loops_n': "no_loops n'" using mdb_chain_0_n' no_0_n' by (rule mdb_chain_0_no_loops) lemmas no_loops_simps' [simp]= no_loops_trancl_simp [OF no_loops_n'] no_loops_direct_simp [OF no_loops_n'] lemma rangeD: "\<lbrakk> m \<turnstile> parent \<rightarrow> p; m p = Some (CTE cap node) \<rbrakk> \<Longrightarrow> capRange cap \<inter> capRange c' = {}" using range by (rule descendants_rangeD') lemma capAligned_c': "capAligned c'" using valid_c' by (rule valid_capAligned) lemma capRange_ut: "capRange c' \<subseteq> untypedRange parent_cap" using capRange_c' is_untyped by (clarsimp simp: isCap_simps del: subsetI) lemma untyped_mdb_n' [simp]: "untyped_mdb' n'" using untyped_mdb capRange_ut untyped_inc apply (clarsimp simp: untyped_mdb'_def descendants_of'_def) apply (drule n'_cap)+ apply (simp add: parency_n') apply (simp split: if_split_asm) apply clarsimp apply (erule_tac x=parent in allE) apply (simp add: parent is_untyped) apply (erule_tac x=p' in allE) apply simp apply (frule untypedCapRange) apply (drule untypedRange_c') apply (erule impE, blast) apply (drule (1) rangeD) apply simp apply clarsimp apply (thin_tac "All P" for P) apply (simp add: untyped_inc'_def) apply (erule_tac x=parent in allE) apply (erule_tac x=p in allE) apply (simp add: parent is_untyped) apply (clarsimp simp: descendants_of'_def) apply (case_tac "untypedRange parent_cap = untypedRange c") apply simp apply (elim disjE conjE) apply (drule (1) rangeD) apply (drule untypedCapRange) apply simp apply blast apply simp apply (erule disjE) apply clarsimp apply (erule disjE) apply (simp add: psubsetI) apply (elim conjE) apply (drule (1) rangeD) apply (drule untypedCapRange) apply simp apply blast apply blast apply clarsimp done lemma site': "n' site = Some new_site" by (simp add: n n'_def modify_map_if new_site_def) lemma loopE: "m \<turnstile> x \<leadsto>\<^sup>+ x \<Longrightarrow> P" by simp lemma m_loop_trancl_rtrancl: "m \<turnstile> y \<leadsto>\<^sup>* x \<Longrightarrow> \<not> m \<turnstile> x \<leadsto>\<^sup>+ y" apply clarsimp apply (drule(1) transitive_closure_trans) apply (erule loopE) done lemma m_rtrancl_to_site: "m \<turnstile> p \<leadsto>\<^sup>* site = (p = site)" apply (rule iffI) apply (erule rtranclE) apply assumption apply simp apply simp done lemma descendants_of'_D: "p' \<in> descendants_of' p ctes \<Longrightarrow> ctes \<turnstile> p \<rightarrow> p' " by (clarsimp simp:descendants_of'_def) lemma untyped_inc_mdbD: "\<lbrakk> sameRegionAs cap cap'; isUntypedCap cap; ctes p = Some (CTE cap node); ctes p' = Some (CTE cap' node'); untyped_inc' ctes; untyped_mdb' ctes; no_loops ctes \<rbrakk> \<Longrightarrow> ctes \<turnstile> p \<rightarrow> p' \<or> p = p' \<or> (isUntypedCap cap' \<and> untypedRange cap \<subseteq> untypedRange cap' \<and> sameRegionAs cap' cap \<and> ctes \<turnstile> p' \<rightarrow> p)" apply (subgoal_tac "untypedRange cap \<subseteq> untypedRange cap' \<longrightarrow> sameRegionAs cap' cap") apply (cases "isUntypedCap cap'") apply (drule(4) untyped_incD'[where p=p and p'=p']) apply (erule sameRegionAsE, simp_all add: untypedCapRange)[1] apply (cases "untypedRange cap = untypedRange cap'") apply simp apply (elim disjE conjE) apply (simp only: simp_thms descendants_of'_D)+ apply (elim disjE conjE) apply (simp add: subset_iff_psubset_eq) apply (elim disjE) apply (simp add:descendants_of'_D)+ apply (clarsimp simp:descendants_of'_def) apply ((clarsimp simp: isCap_simps)+)[2] apply clarsimp apply (erule sameRegionAsE) apply simp apply (drule(1) untyped_mdbD',simp) apply (simp add:untypedCapRange) apply blast apply simp apply assumption apply (simp add:descendants_of'_def) apply (clarsimp simp:isCap_simps) apply ((clarsimp simp add:isCap_simps)+)[2] apply (clarsimp simp add: sameRegionAs_def3 del: disjCI) apply (rule disjI1) apply (erule disjE) apply (intro conjI) apply blast apply (simp add:untypedCapRange) apply (erule subset_trans[OF _ untypedRange_in_capRange]) apply clarsimp apply (rule untypedRange_not_emptyD) apply (simp add:untypedCapRange) apply blast apply (clarsimp simp:isCap_simps) done lemma parent_chunk: "is_chunk n' parent_cap parent site" by (clarsimp simp: is_chunk_def n'_trancl_eq n'_rtrancl_eq site' new_site_def same_region m_loop_trancl_rtrancl m_rtrancl_to_site) lemma mdb_chunked_n' [simp]: notes if_cong[cong del] if_weak_cong[cong] shows "mdb_chunked n'" using chunked untyped_mdb untyped_inc apply (clarsimp simp: mdb_chunked_def) apply (drule n'_cap)+ apply (simp add: n'_trancl_eq split del: if_split) apply (simp split: if_split_asm) apply clarsimp apply (frule sameRegion_parentI) apply (frule(1) untyped_inc_mdbD [OF _ is_untyped _ _ untyped_inc untyped_mdb no_loops, OF _ parent]) apply (elim disjE) apply (frule sameRegionAs_capRange_Int) apply (simp add: phys) apply (rule valid_capAligned [OF valid_c']) apply (rule valid_capAligned) apply (erule valid_capI') apply (erule notE, erule(1) descendants_rangeD' [OF range, rotated]) apply (clarsimp simp: parent parent_chunk) apply clarsimp apply (frule subtree_mdb_next) apply (simp add: m_loop_trancl_rtrancl [OF trancl_into_rtrancl, where x=parent]) apply (case_tac "p' = parent") apply (clarsimp simp: parent) apply (drule_tac x=p' in spec) apply (drule_tac x=parent in spec) apply (frule sameRegionAs_trans [OF _ same_region]) apply (clarsimp simp: parent is_chunk_def n'_trancl_eq n'_rtrancl_eq m_rtrancl_to_site site' new_site_def) apply (drule_tac x=p'' in spec) apply clarsimp apply (drule_tac p=p'' in m_cap, clarsimp) apply clarsimp apply (erule_tac x=p in allE) apply (erule_tac x=parent in allE) apply (insert parent is_untyped)[1] apply simp apply (case_tac "p = parent") apply (simp add: parent) apply (clarsimp simp add: is_chunk_def) apply (simp add: rtrancl_eq_or_trancl) apply (erule disjE) apply (clarsimp simp: site' new_site_def) apply clarsimp apply (drule tranclD) apply (clarsimp simp: n'_direct_eq) apply (drule (1) transitive_closure_trans) apply simp apply simp apply (case_tac "isUntypedCap cap") prefer 2 apply (simp add: untyped_mdb'_def) apply (erule_tac x=parent in allE) apply simp apply (erule_tac x=p in allE) apply (simp add: descendants_of'_def) apply (drule mp[where P="S \<inter> T \<noteq> {}" for S T]) apply (frule sameRegionAs_capRange_Int, simp add: phys) apply (rule valid_capAligned, erule valid_capI') apply (rule valid_capAligned, rule valid_c') apply (insert capRange_ut)[1] apply blast apply (drule (1) rangeD) apply (drule capRange_sameRegionAs, rule valid_c') apply (simp add: phys) apply simp apply (case_tac "untypedRange parent_cap \<subseteq> untypedRange cap") apply (erule impE) apply (clarsimp simp only: isCap_simps untypedRange.simps) apply (subst (asm) range_subset_eq) apply (drule valid_capI')+ apply (drule valid_capAligned)+ apply (clarsimp simp: capAligned_def) apply (erule is_aligned_no_overflow) apply (simp(no_asm) add: sameRegionAs_def3 isCap_simps) apply (drule valid_capI')+ apply (drule valid_capAligned)+ apply (clarsimp simp: capAligned_def is_aligned_no_overflow) apply clarsimp apply (erule disjE) apply simp apply (rule conjI) prefer 2 apply clarsimp apply (drule (1) trancl_trans, erule loopE) apply (thin_tac "P \<longrightarrow> Q" for P Q) apply (clarsimp simp: is_chunk_def) apply (simp add: n'_trancl_eq n'_rtrancl_eq split: if_split_asm) apply (simp add: site' new_site_def) apply (erule_tac x=p'' in allE) apply clarsimp apply (drule_tac p=p'' in m_cap) apply clarsimp apply (simp add: rtrancl_eq_or_trancl) apply simp apply (rule conjI) apply clarsimp apply (drule (1) trancl_trans, erule loopE) apply clarsimp apply (clarsimp simp: is_chunk_def) apply (simp add: n'_trancl_eq n'_rtrancl_eq split: if_split_asm) apply (drule (1) transitive_closure_trans, erule loopE) apply (subgoal_tac "m \<turnstile> p \<rightarrow> parent") apply (drule subtree_mdb_next) apply (drule (1) trancl_trans, erule loopE) apply (thin_tac "All P" for P) apply (drule_tac p=parent and p'=p in untyped_incD'[rotated], assumption+) apply simp apply (subgoal_tac "\<not> m \<turnstile> parent \<rightarrow> p") prefer 2 apply clarsimp apply (drule (1) rangeD) apply (drule capRange_sameRegionAs, rule valid_c') apply (simp add: phys) apply simp apply (clarsimp simp: descendants_of'_def subset_iff_psubset_eq) apply (erule disjE,simp,simp) apply (drule_tac p=parent and p'=p in untyped_incD'[rotated], assumption+) apply (simp add:subset_iff_psubset_eq descendants_of'_def) apply (elim disjE conjE| simp )+ apply (drule(1) rangeD) apply (drule capRange_sameRegionAs[OF _ valid_c']) apply (simp add:phys)+ apply (insert capRange_c' is_untyped)[1] apply (simp add: untypedCapRange [symmetric]) apply (drule(1) disjoint_subset) apply (drule capRange_sameRegionAs[OF _ valid_c']) apply (simp add:phys) apply (simp add:Int_ac) apply clarsimp apply (erule_tac x=p in allE) apply (erule_tac x=p' in allE) apply clarsimp apply (erule disjE) apply simp apply (thin_tac "P \<longrightarrow> Q" for P Q) apply (subgoal_tac "is_chunk n' cap p p'") prefer 2 apply (clarsimp simp: is_chunk_def) apply (simp add: n'_trancl_eq n'_rtrancl_eq split: if_split_asm) apply (erule disjE) apply (erule_tac x=parent in allE) apply clarsimp apply (erule impE, fastforce) apply (clarsimp simp: parent) apply (simp add: site' new_site_def) apply (erule sameRegionAs_trans, rule same_region) apply (clarsimp simp add: parent) apply (simp add: site' new_site_def) apply (rule same_region) apply (erule_tac x=p'' in allE) apply clarsimp apply (drule_tac p=p'' in m_cap) apply clarsimp apply (erule_tac x=p'' in allE) apply clarsimp apply (drule_tac p=p'' in m_cap) apply clarsimp apply (erule_tac x=p'' in allE) apply clarsimp apply (drule_tac p=p'' in m_cap) apply clarsimp apply (erule_tac x=p'' in allE) apply clarsimp apply (drule_tac p=p'' in m_cap) apply clarsimp apply simp apply (rule conjI) apply clarsimp apply (rule conjI) apply clarsimp apply (drule (1) trancl_trans, erule loopE) apply (rule conjI, clarsimp) apply (drule (1) trancl_trans, erule loopE) apply clarsimp apply (drule (1) trancl_trans, erule loopE) apply (rule conjI) apply clarsimp apply (drule (1) trancl_trans, erule loopE) apply clarsimp apply (rule conjI) apply clarsimp apply (drule (1) trancl_trans, erule loopE) apply (rule conjI, clarsimp) apply clarsimp apply (drule (1) trancl_trans, erule loopE) apply simp apply (thin_tac "P \<longrightarrow> Q" for P Q) apply (subgoal_tac "is_chunk n' cap' p' p") prefer 2 apply (clarsimp simp: is_chunk_def) apply (simp add: n'_trancl_eq n'_rtrancl_eq split: if_split_asm) apply (erule disjE) apply (erule_tac x=parent in allE) apply clarsimp apply (erule impE, fastforce) apply (clarsimp simp: parent) apply (simp add: site' new_site_def) apply (erule sameRegionAs_trans, rule same_region) apply (clarsimp simp add: parent) apply (simp add: site' new_site_def) apply (rule same_region) apply (erule_tac x=p'' in allE) apply clarsimp apply (drule_tac p=p'' in m_cap) apply clarsimp apply (erule_tac x=p'' in allE) apply clarsimp apply (drule_tac p=p'' in m_cap) apply clarsimp apply (erule_tac x=p'' in allE) apply clarsimp apply (drule_tac p=p'' in m_cap) apply clarsimp apply (erule_tac x=p'' in allE) apply clarsimp apply (drule_tac p=p'' in m_cap) apply clarsimp apply simp apply (rule conjI) apply clarsimp apply (rule conjI) apply clarsimp apply (drule (1) trancl_trans, erule loopE) apply (rule conjI, clarsimp) apply (drule (1) trancl_trans, erule loopE) apply clarsimp apply (drule (1) trancl_trans, erule loopE) apply (rule conjI) apply clarsimp apply (drule (1) trancl_trans, erule loopE) apply clarsimp apply (rule conjI) apply clarsimp apply (drule (1) trancl_trans, erule loopE) apply (rule conjI, clarsimp) apply clarsimp apply (drule (1) trancl_trans, erule loopE) done lemma caps_contained_n' [simp]: "caps_contained' n'" using caps_contained untyped_mdb untyped_inc apply (clarsimp simp: caps_contained'_def) apply (drule n'_cap)+ apply (clarsimp split: if_split_asm) apply (drule capRange_untyped) apply simp apply (frule capRange_untyped) apply (frule untypedRange_c') apply (erule_tac x=parent in allE) apply (erule_tac x=p' in allE) apply (simp add: parent) apply (erule impE, blast) apply (simp add: untyped_mdb'_def) apply (erule_tac x=parent in allE) apply (erule_tac x=p' in allE) apply (simp add: parent is_untyped descendants_of'_def) apply (erule impE) apply (thin_tac "m site = t" for t) apply (drule valid_capI') apply (frule valid_capAligned) apply blast apply (drule (1) rangeD) apply (frule capRange_untyped) apply (drule untypedCapRange) apply simp apply (thin_tac "All P" for P) apply (insert capRange_c')[1] apply (simp add: untypedCapRange is_untyped) apply (subgoal_tac "untypedRange parent_cap \<inter> untypedRange c \<noteq> {}") prefer 2 apply blast apply (frule untyped_incD'[OF _ capRange_untyped _ is_untyped]) apply (case_tac c) apply simp_all apply (simp add:isCap_simps) apply (rule parent) apply clarsimp apply (case_tac "untypedRange c = untypedRange parent_cap") apply blast apply simp apply (elim disjE) apply (drule_tac A = "untypedRange c" in psubsetI) apply simp+ apply (thin_tac "P\<longrightarrow>Q" for P Q) apply (elim conjE) apply (simp add:descendants_of'_def) apply (drule(1) rangeD) apply (frule capRange_untyped) apply (simp add:untypedCapRange Int_ac) apply blast apply (simp add:descendants_of'_def) apply blast apply blast done lemma untyped_inc_n' [simp]: "untypedRange c' \<inter> usableUntypedRange parent_cap = {} \<Longrightarrow> untyped_inc' n'" using untyped_inc apply (clarsimp simp: untyped_inc'_def) apply (drule n'_cap)+ apply (clarsimp simp: descendants_of'_def parency_n' split: if_split_asm) apply (frule untypedRange_c') apply (insert parent is_untyped)[1] apply (erule_tac x=parent in allE) apply (erule_tac x=p' in allE) apply clarsimp apply (case_tac "untypedRange parent_cap = untypedRange c'a") apply simp apply (intro conjI) apply (intro impI) apply (elim disjE conjE) apply (drule(1) subtree_trans,simp) apply (simp add:subset_not_psubset) apply simp apply (clarsimp simp:subset_not_psubset) apply (drule valid_capI')+ apply (drule(2) disjoint_subset[OF usableRange_subseteq[OF valid_capAligned],rotated -1]) apply simp apply (clarsimp) apply (rule int_not_empty_subsetD) apply (drule(1) rangeD) apply (simp add:untypedCapRange Int_ac) apply (erule aligned_untypedRange_non_empty[OF valid_capAligned[OF valid_c']]) apply (erule(1) aligned_untypedRange_non_empty[OF valid_capAligned[OF valid_capI']]) apply simp apply (erule subset_splitE) apply (simp|elim conjE)+ apply (thin_tac "P \<longrightarrow> Q" for P Q)+ apply blast apply (simp|elim conjE)+ apply (thin_tac "P \<longrightarrow> Q" for P Q)+ apply (intro conjI,intro impI,drule(1) subtree_trans,simp) apply clarsimp apply (intro impI) apply (drule(1) rangeD) apply (simp add:untypedCapRange Int_ac) apply (rule int_not_empty_subsetD) apply (simp add:Int_ac) apply (erule aligned_untypedRange_non_empty[OF valid_capAligned[OF valid_c']]) apply (erule(1) aligned_untypedRange_non_empty[OF valid_capAligned[OF valid_capI']]) apply simp apply (thin_tac "P \<longrightarrow> Q" for P Q)+ apply (drule(1) disjoint_subset[rotated]) apply simp apply (drule_tac B = "untypedRange c'a" in int_not_empty_subsetD) apply (erule aligned_untypedRange_non_empty[OF capAligned_c']) apply (erule(1) aligned_untypedRange_non_empty[OF valid_capAligned[OF valid_capI']]) apply simp apply (frule untypedRange_c') apply (insert parent is_untyped)[1] apply (erule_tac x=p in allE) apply (erule_tac x=parent in allE) apply clarsimp apply (case_tac "untypedRange parent_cap = untypedRange c") apply simp apply (intro conjI) apply (intro impI) apply (elim disjE conjE) apply (clarsimp simp:subset_not_psubset )+ apply (drule(1) subtree_trans,simp) apply simp apply (clarsimp simp:subset_not_psubset) apply (drule disjoint_subset[OF usableRange_subseteq[OF valid_capAligned[OF valid_capI']],rotated]) apply simp apply assumption apply simp apply clarsimp apply (rule int_not_empty_subsetD) apply (drule(1) rangeD) apply (simp add:untypedCapRange Int_ac) apply (erule(1) aligned_untypedRange_non_empty[OF valid_capAligned[OF valid_capI']]) apply (erule aligned_untypedRange_non_empty[OF capAligned_c']) apply simp apply (erule subset_splitE) apply (simp|elim conjE)+ apply (thin_tac "P \<longrightarrow> Q" for P Q)+ apply (intro conjI,intro impI,drule(1) subtree_trans,simp) apply clarsimp apply (intro impI) apply (drule(1) rangeD) apply (simp add:untypedCapRange Int_ac) apply (rule int_not_empty_subsetD) apply (simp add:Int_ac) apply (erule(1) aligned_untypedRange_non_empty[OF valid_capAligned[OF valid_capI']]) apply (erule aligned_untypedRange_non_empty[OF valid_capAligned[OF valid_c']]) apply simp apply (thin_tac "P\<longrightarrow>Q" for P Q)+ apply blast apply (thin_tac "P\<longrightarrow>Q" for P Q)+ apply simp apply (drule(1) disjoint_subset2[rotated]) apply simp apply (drule_tac B = "untypedRange c'" in int_not_empty_subsetD) apply (erule(1) aligned_untypedRange_non_empty[OF valid_capAligned[OF valid_capI']]) apply (erule aligned_untypedRange_non_empty[OF capAligned_c']) apply simp apply (erule_tac x=p in allE) apply (erule_tac x=p' in allE) apply simp apply blast done lemma ut_rev_n' [simp]: "ut_revocable' n'" using ut_rev apply (clarsimp simp: ut_revocable'_def n'_def n_def) apply (clarsimp simp: modify_map_if split: if_split_asm) done lemma class_links_m: "class_links m" using valid by (simp add: valid_mdb_ctes_def) lemma parent_phys: "capClass parent_cap = PhysicalClass" using is_untyped by (clarsimp simp: isCap_simps) lemma class_links [simp]: "class_links n'" using class_links_m apply (clarsimp simp add: class_links_def) apply (simp add: n'_direct_eq split: if_split_asm) apply (case_tac cte, clarsimp dest!: n'_cap simp: site' parent new_site_def phys parent_phys) apply (drule_tac x=parent in spec) apply (drule_tac x=p' in spec) apply (case_tac cte') apply (clarsimp simp: site' new_site_def parent parent_phys phys dest!: n'_cap split: if_split_asm) apply (case_tac cte, case_tac cte') apply (clarsimp dest!: n'_cap split: if_split_asm) apply fastforce done lemma irq_control_n' [simp]: "irq_control n'" using irq_control phys apply (clarsimp simp: irq_control_def) apply (clarsimp simp: n'_def n_def) apply (clarsimp simp: modify_map_if split: if_split_asm) done lemma ioport_control_n' [simp]: "ioport_control n'" using ioport_control phys apply (clarsimp simp: ioport_control_def) apply (clarsimp simp: n'_def n_def) apply (clarsimp simp: modify_map_if split: if_split_asm) done lemma dist_z_m: "distinct_zombies m" using valid by auto lemma dist_z [simp]: "distinct_zombies n'" using dist_z_m apply (simp add: n'_def distinct_zombies_nonCTE_modify_map) apply (simp add: n_def distinct_zombies_nonCTE_modify_map fun_upd_def[symmetric]) apply (erule distinct_zombies_seperateE, simp) apply (case_tac cte, clarsimp) apply (rename_tac cap node) apply (subgoal_tac "capRange cap \<inter> capRange c' \<noteq> {}") apply (frule untyped_mdbD' [OF _ _ _ _ _ untyped_mdb, OF parent]) apply (simp add: is_untyped) apply (clarsimp simp add: untypedCapRange[OF is_untyped, symmetric]) apply (drule disjoint_subset2 [OF capRange_c']) apply simp apply simp apply (simp add: descendants_of'_def) apply (drule(1) rangeD) apply simp apply (drule capAligned_capUntypedPtr [OF capAligned_c']) apply (frule valid_capAligned [OF valid_capI']) apply (drule(1) capAligned_capUntypedPtr) apply auto done lemma reply_masters_rvk_fb_m: "reply_masters_rvk_fb m" using valid by auto lemma reply_masters_rvk_fb_n[simp]: "reply_masters_rvk_fb n'" using reply_masters_rvk_fb_m apply (simp add: reply_masters_rvk_fb_def n'_def ball_ran_modify_map_eq n_def fun_upd_def[symmetric]) apply (rule ball_ran_fun_updI, assumption) apply clarsimp done lemma valid_n': "untypedRange c' \<inter> usableUntypedRange parent_cap = {} \<Longrightarrow> valid_mdb_ctes n'" by auto end lemma caps_overlap_reserved'_D: "\<lbrakk>caps_overlap_reserved' S s; ctes_of s p = Some cte;isUntypedCap (cteCap cte)\<rbrakk> \<Longrightarrow> usableUntypedRange (cteCap cte) \<inter> S = {}" apply (simp add:caps_overlap_reserved'_def) apply (erule ballE) apply (erule(2) impE) apply fastforce done context begin interpretation Arch . (*FIXME: arch_split*) lemma insertNewCap_valid_mdb: "\<lbrace>valid_mdb' and valid_objs' and K (slot \<noteq> p) and caps_overlap_reserved' (untypedRange cap) and cte_wp_at' (\<lambda>cte. isUntypedCap (cteCap cte) \<and> sameRegionAs (cteCap cte) cap) p and K (\<not>isZombie cap) and valid_cap' cap and (\<lambda>s. descendants_range' cap p (ctes_of s))\<rbrace> insertNewCap p slot cap \<lbrace>\<lambda>rv. valid_mdb'\<rbrace>" apply (clarsimp simp: insertNewCap_def valid_mdb'_def) apply (wp getCTE_ctes_of | simp add: o_def)+ apply (clarsimp simp: cte_wp_at_ctes_of) apply (rule conjI) apply (clarsimp simp: no_0_def valid_mdb_ctes_def) apply (case_tac cte) apply (rename_tac p_cap p_node) apply (clarsimp cong: if_cong) apply (case_tac ya) apply (rename_tac node) apply (clarsimp simp: nullPointer_def) apply (rule mdb_insert_again_all.valid_n') apply unfold_locales[1] apply (assumption|rule refl)+ apply (frule sameRegionAs_classes, clarsimp simp: isCap_simps) apply (erule (1) ctes_of_valid_cap') apply (simp add: valid_mdb_ctes_def) apply simp apply (clarsimp simp: isMDBParentOf_CTE) apply (clarsimp simp: isCap_simps valid_mdb_ctes_def ut_revocable'_def) apply assumption apply (drule(1) caps_overlap_reserved'_D) apply simp apply (simp add:Int_ac) done (* FIXME: move *) lemma no_default_zombie: "cap_relation (default_cap tp p sz d) cap \<Longrightarrow> \<not>isZombie cap" by (cases tp, auto simp: isCap_simps) lemmas updateNewFreeIndex_typ_ats[wp] = typ_at_lifts[OF updateNewFreeIndex_typ_at'] lemma updateNewFreeIndex_valid_objs[wp]: "\<lbrace>valid_objs'\<rbrace> updateNewFreeIndex slot \<lbrace>\<lambda>_. valid_objs'\<rbrace>" apply (simp add: updateNewFreeIndex_def getSlotCap_def) apply (wp getCTE_wp' | wpc | simp add: updateTrackedFreeIndex_def)+ done lemma insertNewCap_valid_objs [wp]: "\<lbrace> valid_objs' and valid_cap' cap and pspace_aligned' and pspace_distinct'\<rbrace> insertNewCap parent slot cap \<lbrace>\<lambda>_. valid_objs'\<rbrace>" apply (simp add: insertNewCap_def) apply (wp setCTE_valid_objs getCTE_wp') apply clarsimp done lemma insertNewCap_valid_cap [wp]: "\<lbrace> valid_cap' c \<rbrace> insertNewCap parent slot cap \<lbrace>\<lambda>_. valid_cap' c\<rbrace>" apply (simp add: insertNewCap_def) apply (wp getCTE_wp') apply clarsimp done lemmas descendants_of'_mdbPrev = descendants_of_prev_update lemma insertNewCap_ranges: "\<lbrace>\<lambda>s. descendants_range' c p (ctes_of s) \<and> descendants_range' cap p (ctes_of s) \<and> capRange c \<inter> capRange cap = {} \<and> cte_wp_at' (\<lambda>cte. isUntypedCap (cteCap cte) \<and> sameRegionAs (cteCap cte) cap) p s \<and> valid_mdb' s \<and> valid_objs' s\<rbrace> insertNewCap p slot cap \<lbrace>\<lambda>_ s. descendants_range' c p (ctes_of s)\<rbrace>" apply (simp add: insertNewCap_def) apply (wp getCTE_wp') apply (clarsimp simp: cte_wp_at_ctes_of) apply (rule conjI) apply (clarsimp simp: valid_mdb'_def valid_mdb_ctes_def no_0_def) apply (case_tac ctea) apply (case_tac cteb) apply (clarsimp simp: nullPointer_def cong: if_cong) apply (simp (no_asm) add: descendants_range'_def descendants_of'_mdbPrev) apply (subst mdb_insert_again_child.descendants) apply unfold_locales[1] apply (simp add: valid_mdb'_def) apply (assumption|rule refl)+ apply (frule sameRegionAs_classes, clarsimp simp: isCap_simps) apply (erule (1) ctes_of_valid_cap') apply (simp add: valid_mdb'_def valid_mdb_ctes_def) apply clarsimp apply (clarsimp simp: isMDBParentOf_def) apply (clarsimp simp: isCap_simps valid_mdb'_def valid_mdb_ctes_def ut_revocable'_def) apply clarsimp apply (rule context_conjI, blast) apply (clarsimp simp: descendants_range'_def) done lemma insertNewCap_overlap_reserved'[wp]: "\<lbrace>\<lambda>s. caps_overlap_reserved' (capRange c) s\<and> capRange c \<inter> capRange cap = {} \<and> capAligned cap \<and> cte_wp_at' (\<lambda>cte. isUntypedCap (cteCap cte) \<and> sameRegionAs (cteCap cte) cap) p s \<and> valid_mdb' s \<and> valid_objs' s\<rbrace> insertNewCap p slot cap \<lbrace>\<lambda>_ s. caps_overlap_reserved' (capRange c) s\<rbrace>" apply (simp add: insertNewCap_def caps_overlap_reserved'_def) apply (wp getCTE_wp') apply (clarsimp simp: cte_wp_at_ctes_of) apply (rule conjI) apply (clarsimp simp: valid_mdb'_def valid_mdb_ctes_def no_0_def) apply (case_tac ctea) apply (case_tac cteb) apply (clarsimp simp: nullPointer_def ball_ran_modify_map_eq caps_overlap_reserved'_def[symmetric]) apply (clarsimp simp: ran_def split: if_splits) apply (case_tac "slot = a") apply clarsimp apply (rule disjoint_subset) apply (erule(1) usableRange_subseteq) apply (simp add:untypedCapRange Int_ac)+ apply (subst Int_commute) apply (erule(2) caps_overlap_reserved'_D) done crunch ksArch[wp]: insertNewCap "\<lambda>s. P (ksArchState s)" (wp: crunch_wps) lemma inv_untyped_corres_helper1: "list_all2 cap_relation (map (\<lambda>ref. default_cap tp ref sz d) orefs) cps \<Longrightarrow> corres dc (\<lambda>s. pspace_aligned s \<and> pspace_distinct s \<and> valid_objs s \<and> valid_mdb s \<and> valid_list s \<and> cte_wp_at is_untyped_cap p s \<and> (\<forall>tup \<in> set (zip crefs orefs). cte_wp_at (\<lambda>c. cap_range (default_cap tp (snd tup) sz d) \<subseteq> untyped_range c) p s) \<and> (\<forall>tup \<in> set (zip crefs orefs). descendants_range (default_cap tp (snd tup) sz d) p s) \<and> (\<forall>tup \<in> set (zip crefs orefs). caps_overlap_reserved (untyped_range (default_cap tp (snd tup) sz d)) s) \<and> (\<forall>tup \<in> set (zip crefs orefs). real_cte_at (fst tup) s) \<and> (\<forall>tup \<in> set (zip crefs orefs). cte_wp_at ((=) cap.NullCap) (fst tup) s) \<and> distinct (p # (map fst (zip crefs orefs))) \<and> distinct_sets (map (\<lambda>tup. cap_range (default_cap tp (snd tup) sz d)) (zip crefs orefs)) \<and> (\<forall>tup \<in> set (zip crefs orefs). valid_cap (default_cap tp (snd tup) sz d) s)) (\<lambda>s. (\<forall>tup \<in> set (zip (map cte_map crefs) cps). valid_cap' (snd tup) s) \<and> (\<forall>tup \<in> set (zip (map cte_map crefs) cps). cte_wp_at' (\<lambda>c. cteCap c = NullCap) (fst tup) s) \<and> cte_wp_at' (\<lambda>cte. isUntypedCap (cteCap cte) \<and> (\<forall>tup \<in> set (zip (map cte_map crefs) cps). sameRegionAs (cteCap cte) (snd tup))) (cte_map p) s \<and> distinct ((cte_map p) # (map fst (zip (map cte_map crefs) cps))) \<and> valid_mdb' s \<and> valid_objs' s \<and> pspace_aligned' s \<and> pspace_distinct' s \<and> (\<forall>tup \<in> set (zip (map cte_map crefs) cps). descendants_range' (snd tup) (cte_map p) (ctes_of s)) \<and> (\<forall>tup \<in> set (zip (map cte_map crefs) cps). caps_overlap_reserved' (capRange (snd tup)) s) \<and> distinct_sets (map capRange (map snd (zip (map cte_map crefs) cps)))) (sequence_x (map (create_cap tp sz p d) (zip crefs orefs))) (zipWithM_x (insertNewCap (cte_map p)) ((map cte_map crefs)) cps)" apply (simp add: zipWithM_x_def zipWith_def split_def) apply (fold mapM_x_def) apply (rule corres_list_all2_mapM_) apply (rule corres_guard_imp) apply (erule insertNewCap_corres) apply (clarsimp simp: cte_wp_at_def is_cap_simps) apply (clarsimp simp: fun_upd_def cte_wp_at_ctes_of) apply clarsimp apply (rule hoare_pre, wp hoare_vcg_const_Ball_lift) apply clarsimp apply (rule conjI) apply (clarsimp simp: cte_wp_at_caps_of_state cap_range_def[where c="default_cap a b c d" for a b c d]) apply (drule(2) caps_overlap_reservedD[rotated]) apply (simp add:Int_ac) apply (rule conjI) apply (clarsimp simp: valid_cap_def) apply (rule conjI) apply (clarsimp simp: cte_wp_at_caps_of_state) apply (rule conjI) apply (clarsimp simp:Int_ac) apply (erule disjoint_subset2[rotated]) apply fastforce apply clarsimp apply (rule conjI) apply clarsimp apply (rule conjI) subgoal by fastforce apply (clarsimp simp: cte_wp_at_caps_of_state is_cap_simps valid_cap_def) apply (fastforce simp: image_def) apply (rule hoare_pre) apply (wp hoare_vcg_const_Ball_lift insertNewCap_valid_mdb hoare_vcg_all_lift insertNewCap_ranges | subst cte_wp_at_cteCaps_of)+ apply (subst(asm) cte_wp_at_cteCaps_of)+ apply (clarsimp simp only:) apply simp apply (rule conjI) apply clarsimp apply (thin_tac "cte_map p \<notin> S" for S) apply (erule notE, erule rev_image_eqI) apply simp apply (rule conjI,clarsimp+) apply (rule conjI,erule caps_overlap_reserved'_subseteq) apply (rule untypedRange_in_capRange) apply (rule conjI,erule no_default_zombie) apply (rule conjI, clarsimp simp:Int_ac) apply fastforce apply (clarsimp simp:Int_ac valid_capAligned ) apply fastforce apply (rule list_all2_zip_split) apply (simp add: list_all2_map2 list_all2_refl) apply (simp add: list_all2_map1) done lemma createNewCaps_valid_pspace_extras: "\<lbrace>(\<lambda>s. n \<noteq> 0 \<and> ptr \<noteq> 0 \<and> range_cover ptr sz (APIType_capBits ty us) n \<and> sz \<le> maxUntypedSizeBits \<and> canonical_address (ptr && ~~ mask sz) \<and> ptr && ~~ mask sz \<in> kernel_mappings \<and> pspace_no_overlap' ptr sz s \<and> valid_pspace' s \<and> caps_no_overlap'' ptr sz s \<and> caps_overlap_reserved' {ptr .. ptr + of_nat n * 2 ^ APIType_capBits ty us - 1} s \<and> ksCurDomain s \<le> maxDomain )\<rbrace> createNewCaps ty ptr n us d \<lbrace>\<lambda>rv. pspace_aligned'\<rbrace>" "\<lbrace>(\<lambda>s. n \<noteq> 0 \<and> ptr \<noteq> 0 \<and> range_cover ptr sz (APIType_capBits ty us) n \<and> sz \<le> maxUntypedSizeBits \<and> canonical_address (ptr && ~~ mask sz) \<and> ptr && ~~ mask sz \<in> kernel_mappings \<and> pspace_no_overlap' ptr sz s \<and> valid_pspace' s \<and> caps_no_overlap'' ptr sz s \<and> caps_overlap_reserved' {ptr .. ptr + of_nat n * 2 ^ APIType_capBits ty us - 1} s \<and> ksCurDomain s \<le> maxDomain )\<rbrace> createNewCaps ty ptr n us d \<lbrace>\<lambda>rv. pspace_canonical'\<rbrace>" "\<lbrace>(\<lambda>s. n \<noteq> 0 \<and> ptr \<noteq> 0 \<and> range_cover ptr sz (APIType_capBits ty us) n \<and> sz \<le> maxUntypedSizeBits \<and> canonical_address (ptr && ~~ mask sz) \<and> ptr && ~~ mask sz \<in> kernel_mappings \<and> pspace_no_overlap' ptr sz s \<and> valid_pspace' s \<and> caps_no_overlap'' ptr sz s \<and> caps_overlap_reserved' {ptr .. ptr + of_nat n * 2 ^ APIType_capBits ty us - 1} s \<and> ksCurDomain s \<le> maxDomain )\<rbrace> createNewCaps ty ptr n us d \<lbrace>\<lambda>rv. pspace_distinct'\<rbrace>" "\<lbrace>(\<lambda>s. n \<noteq> 0 \<and> ptr \<noteq> 0 \<and> range_cover ptr sz (APIType_capBits ty us) n \<and> sz \<le> maxUntypedSizeBits \<and> canonical_address (ptr && ~~ mask sz) \<and> ptr && ~~ mask sz \<in> kernel_mappings \<and> pspace_no_overlap' ptr sz s \<and> valid_pspace' s \<and> caps_no_overlap'' ptr sz s \<and> caps_overlap_reserved' {ptr .. ptr + of_nat n * 2 ^ APIType_capBits ty us - 1} s \<and> ksCurDomain s \<le> maxDomain )\<rbrace> createNewCaps ty ptr n us d \<lbrace>\<lambda>rv. valid_mdb'\<rbrace>" "\<lbrace>(\<lambda>s. n \<noteq> 0 \<and> ptr \<noteq> 0 \<and> range_cover ptr sz (APIType_capBits ty us) n \<and> sz \<le> maxUntypedSizeBits \<and> canonical_address (ptr && ~~ mask sz) \<and> ptr && ~~ mask sz \<in> kernel_mappings \<and> pspace_no_overlap' ptr sz s \<and> valid_pspace' s \<and> caps_no_overlap'' ptr sz s \<and> caps_overlap_reserved' {ptr .. ptr + of_nat n * 2 ^ APIType_capBits ty us - 1} s \<and> ksCurDomain s \<le> maxDomain )\<rbrace> createNewCaps ty ptr n us d \<lbrace>\<lambda>rv. valid_objs'\<rbrace>" apply (rule hoare_grab_asm)+ apply (rule hoare_pre,rule hoare_strengthen_post[OF createNewCaps_valid_pspace]) apply (simp add:valid_pspace'_def)+ apply (rule hoare_grab_asm)+ apply (rule hoare_pre,rule hoare_strengthen_post[OF createNewCaps_valid_pspace]) apply (simp add:valid_pspace'_def)+ apply (rule hoare_grab_asm)+ apply (rule hoare_pre,rule hoare_strengthen_post[OF createNewCaps_valid_pspace]) apply (simp add:valid_pspace'_def)+ apply (rule hoare_grab_asm)+ apply (rule hoare_pre,rule hoare_strengthen_post[OF createNewCaps_valid_pspace]) apply (simp add:valid_pspace'_def)+ apply (rule hoare_grab_asm)+ apply (rule hoare_pre,rule hoare_strengthen_post[OF createNewCaps_valid_pspace]) apply (simp add:valid_pspace'_def)+ done declare map_fst_zip_prefix[simp] declare map_snd_zip_prefix[simp] declare word_unat_power [symmetric, simp del] lemma createNewCaps_range_helper: "\<lbrace>\<lambda>s. range_cover ptr sz (APIType_capBits tp us) n \<and> 0 < n\<rbrace> createNewCaps tp ptr n us d \<lbrace>\<lambda>rv s. \<exists>capfn. rv = map capfn (map (\<lambda>p. ptr_add ptr (p * 2 ^ (APIType_capBits tp us))) [0 ..< n]) \<and> (\<forall>p. capClass (capfn p) = PhysicalClass \<and> capUntypedPtr (capfn p) = p \<and> capBits (capfn p) = (APIType_capBits tp us))\<rbrace>" apply (simp add: createNewCaps_def toAPIType_def Arch_createNewCaps_def split del: if_split cong: option.case_cong) apply (rule hoare_grab_asm)+ apply (frule range_cover.range_cover_n_less) apply (frule range_cover.unat_of_nat_n) apply (cases tp, simp_all split del: if_split) apply (rename_tac apiobject_type) apply (case_tac apiobject_type, simp_all split del: if_split) apply (rule hoare_pre, wp) apply (frule range_cover_not_zero[rotated -1],simp) apply (clarsimp simp: APIType_capBits_def objBits_simps archObjSize_def ptr_add_def o_def) apply (subst upto_enum_red') apply unat_arith apply (clarsimp simp: o_def fromIntegral_def toInteger_nat fromInteger_nat) apply fastforce apply (rule hoare_pre,wp createObjects_ret2) apply (clarsimp simp: APIType_capBits_def word_bits_def bit_simps objBits_simps archObjSize_def ptr_add_def o_def) apply (fastforce simp: objBitsKO_def objBits_def) apply (rule hoare_pre,wp createObjects_ret2) apply (clarsimp simp: APIType_capBits_def word_bits_def objBits_simps archObjSize_def ptr_add_def o_def) apply (fastforce simp: objBitsKO_def objBits_def) apply (rule hoare_pre,wp createObjects_ret2) apply (clarsimp simp: APIType_capBits_def word_bits_def objBits_simps archObjSize_def ptr_add_def o_def) apply (fastforce simp: objBitsKO_def objBits_def) apply (rule hoare_pre,wp createObjects_ret2) apply (clarsimp simp: APIType_capBits_def word_bits_def objBits_simps archObjSize_def ptr_add_def o_def) apply (fastforce simp: objBitsKO_def objBits_def) apply (wp createObjects_ret2 | clarsimp simp: APIType_capBits_def objBits_if_dev archObjSize_def word_bits_def bit_simps split del: if_split | simp add: objBits_simps | (rule exI, (fastforce simp: bit_simps)))+ done lemma createNewCaps_range_helper2: "\<lbrace>\<lambda>s. range_cover ptr sz (APIType_capBits tp us) n \<and> 0 < n\<rbrace> createNewCaps tp ptr n us d \<lbrace>\<lambda>rv s. \<forall>cp \<in> set rv. capRange cp \<noteq> {} \<and> capRange cp \<subseteq> {ptr .. (ptr && ~~ mask sz) + 2 ^ sz - 1}\<rbrace>" apply (rule hoare_assume_pre) apply (rule hoare_strengthen_post) apply (rule createNewCaps_range_helper) apply (clarsimp simp: capRange_def ptr_add_def word_unat_power[symmetric] simp del: atLeastatMost_subset_iff dest!: less_two_pow_divD) apply (rule conjI) apply (rule is_aligned_no_overflow) apply (rule is_aligned_add_multI [OF _ _ refl]) apply (fastforce simp:range_cover_def) apply simp apply (rule range_subsetI) apply (rule machine_word_plus_mono_right_split[OF range_cover.range_cover_compare]) apply (assumption)+ apply (simp add:range_cover_def word_bits_def) apply (frule range_cover_cell_subset) apply (erule of_nat_mono_maybe[rotated]) apply (drule (1) range_cover.range_cover_n_less ) apply (clarsimp) apply (erule impE) apply (simp add:range_cover_def) apply (rule is_aligned_no_overflow) apply (rule is_aligned_add_multI[OF _ le_refl refl]) apply (fastforce simp:range_cover_def) apply simp done lemma createNewCaps_children: "\<lbrace>\<lambda>s. cap = UntypedCap d (ptr && ~~ mask sz) sz idx \<and> range_cover ptr sz (APIType_capBits tp us) n \<and> 0 < n\<rbrace> createNewCaps tp ptr n us d \<lbrace>\<lambda>rv s. \<forall>y \<in> set rv. (sameRegionAs cap y)\<rbrace>" apply (rule hoare_assume_pre) apply (rule hoare_chain [OF createNewCaps_range_helper2]) apply fastforce apply clarsimp apply (drule(1) bspec) apply (clarsimp simp: sameRegionAs_def3 isCap_simps) apply (drule(1) subsetD) apply clarsimp apply (erule order_trans[rotated]) apply (rule word_and_le2) done fun isDeviceCap :: "capability \<Rightarrow> bool" where "isDeviceCap (UntypedCap d _ _ _) = d" | "isDeviceCap (ArchObjectCap (PageCap _ _ _ _ d _)) = d" | "isDeviceCap _ = False" lemmas makeObjectKO_simp = makeObjectKO_def[split_simps X64_H.object_type.split Structures_H.kernel_object.split ArchTypes_H.apiobject_type.split sum.split arch_kernel_object.split] lemma createNewCaps_descendants_range': "\<lbrace>\<lambda>s. descendants_range' p q (ctes_of s) \<and> range_cover ptr sz (APIType_capBits ty us) n \<and> n \<noteq> 0 \<and> pspace_aligned' s \<and> pspace_distinct' s \<and> pspace_no_overlap' ptr sz s\<rbrace> createNewCaps ty ptr n us d \<lbrace> \<lambda>rv s. descendants_range' p q (ctes_of s)\<rbrace>" apply (clarsimp simp:descendants_range'_def2 descendants_range_in'_def2) apply (wp createNewCaps_null_filter') apply fastforce done lemma caps_overlap_reserved'_def2: "caps_overlap_reserved' S = (\<lambda>s. (\<forall>cte \<in> ran (null_filter' (ctes_of s)). isUntypedCap (cteCap cte) \<longrightarrow> usableUntypedRange (cteCap cte) \<inter> S = {}))" apply (rule ext) apply (clarsimp simp:caps_overlap_reserved'_def) apply (intro iffI ballI impI) apply (elim ballE impE) apply simp apply simp apply (simp add:ran_def null_filter'_def split:if_split_asm option.splits) apply (elim ballE impE) apply simp apply simp apply (clarsimp simp: ran_def null_filter'_def is_cap_simps simp del: split_paired_All split_paired_Ex split: if_splits) apply (drule_tac x = a in spec) apply simp done lemma createNewCaps_caps_overlap_reserved': "\<lbrace>\<lambda>s. caps_overlap_reserved' S s \<and> pspace_aligned' s \<and> pspace_distinct' s \<and> pspace_no_overlap' ptr sz s \<and> 0 < n \<and> range_cover ptr sz (APIType_capBits ty us) n\<rbrace> createNewCaps ty ptr n us d \<lbrace>\<lambda>rv s. caps_overlap_reserved' S s\<rbrace>" apply (clarsimp simp: caps_overlap_reserved'_def2) apply (wp createNewCaps_null_filter') apply fastforce done lemma createNewCaps_caps_overlap_reserved_ret': "\<lbrace>\<lambda>s. caps_overlap_reserved' {ptr..ptr + of_nat n * 2 ^ APIType_capBits ty us - 1} s \<and> pspace_aligned' s \<and> pspace_distinct' s \<and> pspace_no_overlap' ptr sz s \<and> 0 < n \<and> range_cover ptr sz (APIType_capBits ty us) n\<rbrace> createNewCaps ty ptr n us d \<lbrace>\<lambda>rv s. \<forall>y\<in>set rv. caps_overlap_reserved' (capRange y) s\<rbrace>" apply (rule hoare_name_pre_state) apply (clarsimp simp:valid_def) apply (frule use_valid[OF _ createNewCaps_range_helper]) apply fastforce apply clarsimp apply (erule use_valid[OF _ createNewCaps_caps_overlap_reserved']) apply (intro conjI,simp_all) apply (erule caps_overlap_reserved'_subseteq) apply (drule(1) range_cover_subset) apply simp apply (clarsimp simp: ptr_add_def capRange_def simp del: atLeastAtMost_iff atLeastatMost_subset_iff atLeastLessThan_iff Int_atLeastAtMost atLeastatMost_empty_iff) done lemma createNewCaps_descendants_range_ret': "\<lbrace>\<lambda>s. (range_cover ptr sz (APIType_capBits ty us) n \<and> 0 < n) \<and> pspace_aligned' s \<and> pspace_distinct' s \<and> pspace_no_overlap' ptr sz s \<and> descendants_range_in' {ptr..ptr + of_nat n * 2^(APIType_capBits ty us) - 1} cref (ctes_of s)\<rbrace> createNewCaps ty ptr n us d \<lbrace> \<lambda>rv s. \<forall>y\<in>set rv. descendants_range' y cref (ctes_of s)\<rbrace>" apply (rule hoare_name_pre_state) apply (clarsimp simp: valid_def) apply (frule use_valid[OF _ createNewCaps_range_helper]) apply simp apply (erule use_valid[OF _ createNewCaps_descendants_range']) apply (intro conjI,simp_all) apply (clarsimp simp:descendants_range'_def descendants_range_in'_def) apply (drule(1) bspec)+ apply (clarsimp simp:cte_wp_at_ctes_of) apply (erule disjoint_subset2[rotated]) apply (drule(1) range_cover_subset) apply simp apply (simp add:capRange_def ptr_add_def) done lemma createNewCaps_parent_helper: "\<lbrace>\<lambda>s. cte_wp_at' (\<lambda>cte. cteCap cte = UntypedCap d (ptr && ~~ mask sz) sz idx) p s \<and> pspace_aligned' s \<and> pspace_distinct' s \<and> pspace_no_overlap' ptr sz s \<and> (ty = APIObjectType ArchTypes_H.CapTableObject \<longrightarrow> 0 < us) \<and> range_cover ptr sz (APIType_capBits ty us) n \<and> 0 < n \<rbrace> createNewCaps ty ptr n us d \<lbrace>\<lambda>rv. cte_wp_at' (\<lambda>cte. isUntypedCap (cteCap cte) \<and> (\<forall>tup\<in>set (zip (xs rv) rv). sameRegionAs (cteCap cte) (snd tup))) p\<rbrace>" apply (rule hoare_post_imp [where Q="\<lambda>rv s. \<exists>cte. cte_wp_at' ((=) cte) p s \<and> isUntypedCap (cteCap cte) \<and> (\<forall>tup\<in>set (zip (xs rv) rv). sameRegionAs (cteCap cte) (snd tup))"]) apply (clarsimp elim!: cte_wp_at_weakenE') apply (rule hoare_pre) apply (wp hoare_vcg_ex_lift createNewCaps_cte_wp_at' set_tuple_pick createNewCaps_children) apply (auto simp:cte_wp_at'_def isCap_simps) done lemma createNewCaps_valid_cap': "\<lbrace>\<lambda>s. pspace_no_overlap' ptr sz s \<and> valid_pspace' s \<and> n \<noteq> 0 \<and> range_cover ptr sz (APIType_capBits ty us) n \<and> (ty = APIObjectType ArchTypes_H.CapTableObject \<longrightarrow> 0 < us) \<and> (ty = APIObjectType apiobject_type.Untyped \<longrightarrow> minUntypedSizeBits \<le> us \<and> us \<le> maxUntypedSizeBits) \<and> ptr \<noteq> 0 \<and> sz \<le> maxUntypedSizeBits \<and> canonical_address (ptr && ~~ mask sz) \<and> ptr && ~~ mask sz \<in> kernel_mappings \<rbrace> createNewCaps ty ptr n us d \<lbrace>\<lambda>r s. \<forall>cap\<in>set r. s \<turnstile>' cap\<rbrace>" apply (rule hoare_assume_pre) apply clarsimp apply (erule createNewCaps_valid_cap) apply simp+ done lemma dmo_ctes_of[wp]: "\<lbrace>\<lambda>s. P (ctes_of s)\<rbrace> doMachineOp mop \<lbrace>\<lambda>rv s. P (ctes_of s)\<rbrace>" by (simp add: doMachineOp_def split_def | wp select_wp)+ lemma createNewCaps_ranges: "\<lbrace>\<lambda>s. range_cover ptr sz (APIType_capBits ty us) n \<and> 0<n \<rbrace> createNewCaps ty ptr n us d \<lbrace>\<lambda>rv s. distinct_sets (map capRange rv)\<rbrace>" apply (rule hoare_assume_pre) apply (rule hoare_chain) apply (rule createNewCaps_range_helper) apply fastforce apply (clarsimp simp: distinct_sets_prop distinct_prop_map) apply (rule distinct_prop_distinct) apply simp apply (clarsimp simp: capRange_def simp del: Int_atLeastAtMost dest!: less_two_pow_divD) apply (rule aligned_neq_into_no_overlap[simplified field_simps]) apply (rule notI) apply (erule(3) ptr_add_distinct_helper) apply (simp add:range_cover_def word_bits_def) apply (erule range_cover.range_cover_n_le(1)[where 'a=machine_word_len]) apply (clarsimp simp: ptr_add_def word_unat_power[symmetric]) apply (rule is_aligned_add_multI[OF _ le_refl refl]) apply (simp add:range_cover_def)+ apply (clarsimp simp: ptr_add_def word_unat_power[symmetric]) apply (rule is_aligned_add_multI[OF _ le_refl refl]) apply (simp add:range_cover_def)+ done lemma createNewCaps_ranges': "\<lbrace>\<lambda>s. range_cover ptr sz (APIType_capBits ty us) n \<and> 0 < n\<rbrace> createNewCaps ty ptr n us d \<lbrace>\<lambda>rv s. distinct_sets (map capRange (map snd (zip xs rv)))\<rbrace>" apply (rule hoare_strengthen_post) apply (rule createNewCaps_ranges) apply (simp add: distinct_sets_prop del: map_map) apply (erule distinct_prop_prefixE) apply (rule Sublist.map_mono_prefix) apply (rule map_snd_zip_prefix [unfolded less_eq_list_def]) done declare split_paired_Ex[simp del] lemmas corres_split_retype_createNewCaps = corres_split[OF corres_retype_region_createNewCaps, simplified bind_assoc, simplified ] declare split_paired_Ex[simp add] lemma retype_region_caps_overlap_reserved: "\<lbrace>valid_pspace and valid_mdb and pspace_no_overlap_range_cover ptr sz and caps_no_overlap ptr sz and caps_overlap_reserved {ptr..ptr + of_nat n * 2^obj_bits_api (APIType_map2 (Inr ao')) us - 1} and (\<lambda>s. \<exists>slot. cte_wp_at (\<lambda>c. up_aligned_area ptr sz \<subseteq> cap_range c \<and> cap_is_device c = dev) slot s) and K (APIType_map2 (Inr ao') = Structures_A.apiobject_type.CapTableObject \<longrightarrow> 0 < us) and K (range_cover ptr sz (obj_bits_api (APIType_map2 (Inr ao')) us) n) and K (S \<subseteq> {ptr..ptr + of_nat n * 2 ^ obj_bits_api (APIType_map2 (Inr ao')) us - 1})\<rbrace> retype_region ptr n us (APIType_map2 (Inr ao')) dev \<lbrace>\<lambda>rv s. caps_overlap_reserved S s\<rbrace>" apply (rule hoare_gen_asm)+ apply (simp (no_asm) add:caps_overlap_reserved_def2) apply (rule hoare_pre) apply (wp retype_region_caps_of) apply simp+ apply (simp add:caps_overlap_reserved_def2) apply (intro conjI,simp+) apply clarsimp apply (drule bspec) apply simp+ apply (erule(1) disjoint_subset2) done lemma retype_region_caps_overlap_reserved_ret: "\<lbrace>valid_pspace and valid_mdb and caps_no_overlap ptr sz and pspace_no_overlap_range_cover ptr sz and caps_overlap_reserved {ptr..ptr + of_nat n * 2^obj_bits_api (APIType_map2 (Inr ao')) us - 1} and (\<lambda>s. \<exists>slot. cte_wp_at (\<lambda>c. up_aligned_area ptr sz \<subseteq> cap_range c \<and> cap_is_device c = dev) slot s) and K (APIType_map2 (Inr ao') = Structures_A.apiobject_type.CapTableObject \<longrightarrow> 0 < us) and K (range_cover ptr sz (obj_bits_api (APIType_map2 (Inr ao')) us) n)\<rbrace> retype_region ptr n us (APIType_map2 (Inr ao')) dev \<lbrace>\<lambda>rv s. \<forall>y\<in>set rv. caps_overlap_reserved (untyped_range (default_cap (APIType_map2 (Inr ao')) y us d)) s\<rbrace>" apply (rule hoare_name_pre_state) apply (clarsimp simp:valid_def) apply (frule retype_region_ret[unfolded valid_def,simplified,THEN spec,THEN bspec]) apply clarsimp apply (erule use_valid[OF _ retype_region_caps_overlap_reserved]) apply clarsimp apply (intro conjI,simp_all) apply fastforce apply (case_tac ao') apply (simp_all add:APIType_map2_def) apply (rename_tac apiobject_type) apply (case_tac apiobject_type) apply (simp_all add:obj_bits_api_def ptr_add_def) apply (drule(1) range_cover_subset) apply (clarsimp)+ done lemma updateFreeIndex_pspace_no_overlap': "\<lbrace>\<lambda>s. pspace_no_overlap' ptr sz s \<and> valid_pspace' s \<and> cte_wp_at' (isUntypedCap o cteCap) src s\<rbrace> updateFreeIndex src index \<lbrace>\<lambda>r s. pspace_no_overlap' ptr sz s\<rbrace>" apply (simp add: updateFreeIndex_def getSlotCap_def updateTrackedFreeIndex_def) apply (rule hoare_pre) apply (wp getCTE_wp' | wp (once) pspace_no_overlap'_lift | simp)+ apply (clarsimp simp:valid_pspace'_def pspace_no_overlap'_def) done lemma updateFreeIndex_updateCap_caps_overlap_reserved: "\<lbrace>\<lambda>s. valid_mdb' s \<and> valid_objs' s \<and> S \<subseteq> untypedRange cap \<and> usableUntypedRange (capFreeIndex_update (\<lambda>_. index) cap) \<inter> S = {} \<and> isUntypedCap cap \<and> descendants_range_in' S src (ctes_of s) \<and> cte_wp_at' (\<lambda>c. cteCap c = cap) src s\<rbrace> updateCap src (capFreeIndex_update (\<lambda>_. index) cap) \<lbrace>\<lambda>r s. caps_overlap_reserved' S s\<rbrace>" apply (clarsimp simp:caps_overlap_reserved'_def) apply (wp updateCap_ctes_of_wp) apply (clarsimp simp:modify_map_def cte_wp_at_ctes_of) apply (erule ranE) apply (clarsimp split:if_split_asm simp:valid_mdb'_def valid_mdb_ctes_def) apply (case_tac cte) apply (case_tac ctea) apply simp apply (drule untyped_incD') apply (simp+)[4] apply clarify apply (erule subset_splitE) apply (simp del:usable_untyped_range.simps) apply (thin_tac "P \<longrightarrow> Q" for P Q)+ apply (elim conjE) apply blast apply (simp) apply (thin_tac "P\<longrightarrow>Q" for P Q)+ apply (elim conjE) apply (drule(2) descendants_range_inD') apply simp apply (rule disjoint_subset[OF usableRange_subseteq]) apply (rule valid_capAligned) apply (erule(1) ctes_of_valid_cap') apply (simp add:untypedCapRange)+ apply (elim disjE) apply clarsimp apply (drule(2) descendants_range_inD') apply simp apply (rule disjoint_subset[OF usableRange_subseteq]) apply (rule valid_capAligned) apply (erule(1) ctes_of_valid_cap') apply (simp add:untypedCapRange)+ apply (thin_tac "P\<longrightarrow>Q" for P Q)+ apply (rule disjoint_subset[OF usableRange_subseteq]) apply (rule valid_capAligned) apply (erule(1) ctes_of_valid_cap') apply simp+ apply blast done lemma updateFreeIndex_caps_overlap_reserved: "\<lbrace>\<lambda>s. valid_pspace' s \<and> descendants_range_in' S src (ctes_of s) \<and> cte_wp_at' ((\<lambda>cap. S \<subseteq> untypedRange cap \<and> usableUntypedRange (capFreeIndex_update (\<lambda>_. index) cap) \<inter> S = {} \<and> isUntypedCap cap) o cteCap) src s\<rbrace> updateFreeIndex src index \<lbrace>\<lambda>r s. caps_overlap_reserved' S s\<rbrace>" apply (simp add: updateFreeIndex_def updateTrackedFreeIndex_def getSlotCap_def) apply (wp updateFreeIndex_updateCap_caps_overlap_reserved getCTE_wp') apply (clarsimp simp: cte_wp_at_ctes_of valid_pspace'_def) apply (clarsimp simp: valid_mdb'_def split: option.split) done lemma updateFreeIndex_updateCap_caps_no_overlap'': "\<lbrace>\<lambda>s. isUntypedCap cap \<and> caps_no_overlap'' ptr sz s \<and> cte_wp_at' (\<lambda>c. cteCap c = cap) src s\<rbrace> updateCap src (capFreeIndex_update (\<lambda>_. index) cap) \<lbrace>\<lambda>r s. caps_no_overlap'' ptr sz s\<rbrace>" apply (clarsimp simp:caps_no_overlap''_def) apply (wp updateCap_ctes_of_wp) apply (clarsimp simp: modify_map_def ran_def cte_wp_at_ctes_of simp del: atLeastAtMost_iff atLeastatMost_subset_iff atLeastLessThan_iff Int_atLeastAtMost atLeastatMost_empty_iff split_paired_Ex) apply (case_tac "a = src") apply (clarsimp simp del: atLeastAtMost_iff atLeastatMost_subset_iff atLeastLessThan_iff Int_atLeastAtMost atLeastatMost_empty_iff split_paired_Ex) apply (erule subsetD[rotated]) apply (elim allE impE) apply fastforce apply (clarsimp simp:isCap_simps) apply (erule subset_trans) apply (clarsimp simp:isCap_simps) apply (clarsimp simp del: atLeastAtMost_iff atLeastatMost_subset_iff atLeastLessThan_iff Int_atLeastAtMost atLeastatMost_empty_iff split_paired_Ex) apply (erule subsetD[rotated]) apply (elim allE impE) prefer 2 apply assumption apply fastforce+ done lemma updateFreeIndex_caps_no_overlap'': "\<lbrace>\<lambda>s. caps_no_overlap'' ptr sz s \<and> cte_wp_at' (isUntypedCap o cteCap) src s\<rbrace> updateFreeIndex src index \<lbrace>\<lambda>r s. caps_no_overlap'' ptr sz s\<rbrace>" apply (simp add: updateFreeIndex_def updateTrackedFreeIndex_def getSlotCap_def) apply (wp updateFreeIndex_updateCap_caps_no_overlap'' getCTE_wp') apply (clarsimp simp: cte_wp_at_ctes_of) apply (clarsimp simp: caps_no_overlap''_def split: option.split) done lemma updateFreeIndex_descendants_of': "\<lbrace>\<lambda>s. cte_wp_at' (\<lambda>c. \<exists>idx'. cteCap c = capFreeIndex_update (K idx') cap) ptr s \<and> isUntypedCap cap \<and> P ((swp descendants_of') (null_filter' (ctes_of s)))\<rbrace> updateCap ptr (capFreeIndex_update (\<lambda>_. index) cap) \<lbrace>\<lambda>r s. P ((swp descendants_of') (null_filter' (ctes_of s)))\<rbrace>" apply (wp updateCap_ctes_of_wp) apply clarsimp apply (erule subst[rotated,where P = P]) apply (rule ext) apply (clarsimp simp:null_filter_descendants_of'[OF null_filter_simp']) apply (rule mdb_inv_preserve.descendants_of) apply (clarsimp simp:cte_wp_at_ctes_of) apply (frule_tac m="ctes_of s" and index=index in mdb_inv_preserve_updateCap) apply (clarsimp simp: isCap_simps) apply (clarsimp simp: isCap_simps) done lemma updateFreeIndex_updateCap_descendants_range_in': "\<lbrace>\<lambda>s. cte_wp_at' (\<lambda>c. cteCap c = cap) slot s \<and> isUntypedCap cap \<and> descendants_range_in' S slot (ctes_of s)\<rbrace> updateCap slot (capFreeIndex_update (\<lambda>_. index) cap) \<lbrace>\<lambda>r s. descendants_range_in' S slot (ctes_of s)\<rbrace>" apply (rule hoare_pre) apply (wp descendants_range_in_lift' [where Q'="\<lambda>s. cte_wp_at' (\<lambda>c. cteCap c = cap) slot s \<and> isUntypedCap cap" and Q = "\<lambda>s. cte_wp_at' (\<lambda>c. cteCap c = cap) slot s \<and> isUntypedCap cap "] ) apply (wp updateFreeIndex_descendants_of') apply (clarsimp simp: cte_wp_at_ctes_of swp_def isCap_simps) apply (simp add:updateCap_def) apply (wp setCTE_weak_cte_wp_at getCTE_wp) apply (fastforce simp:cte_wp_at_ctes_of isCap_simps) apply (clarsimp) done lemma updateFreeIndex_descendants_range_in': "\<lbrace>\<lambda>s. cte_wp_at' (isUntypedCap o cteCap) slot s \<and> descendants_range_in' S slot (ctes_of s)\<rbrace> updateFreeIndex slot index \<lbrace>\<lambda>r s. descendants_range_in' S slot (ctes_of s)\<rbrace>" apply (simp add: updateFreeIndex_def updateTrackedFreeIndex_def getSlotCap_def) apply (wp updateFreeIndex_updateCap_descendants_range_in' getCTE_wp') apply (clarsimp simp: cte_wp_at_ctes_of) done lemma caps_no_overlap''_def2: "caps_no_overlap'' ptr sz = (\<lambda>s. \<forall>cte\<in>ran (null_filter' (ctes_of s)). untypedRange (cteCap cte) \<inter> {ptr..(ptr && ~~ mask sz) + 2 ^ sz - 1} \<noteq> {} \<longrightarrow> {ptr..(ptr && ~~ mask sz) + 2 ^ sz - 1} \<subseteq> untypedRange (cteCap cte))" apply (intro ext iffI) apply (clarsimp simp:caps_no_overlap''_def null_filter'_def ran_def) apply (drule_tac x = cte in spec) apply fastforce apply (clarsimp simp:caps_no_overlap''_def null_filter'_def) apply (case_tac "cte = CTE capability.NullCap nullMDBNode") apply clarsimp apply (drule_tac x = cte in bspec) apply (clarsimp simp:ran_def) apply (rule_tac x= a in exI) apply clarsimp apply clarsimp apply (erule subsetD) apply simp done lemma deleteObjects_caps_no_overlap'': "\<lbrace>\<lambda>s. invs' s \<and> ct_active' s \<and> sch_act_simple s \<and> cte_wp_at' (\<lambda>c. cteCap c = capability.UntypedCap d ptr sz idx) slot s \<and> caps_no_overlap'' ptr sz s \<and> descendants_range' (capability.UntypedCap d ptr sz idx) slot (ctes_of s)\<rbrace> deleteObjects ptr sz \<lbrace>\<lambda>rv s. caps_no_overlap'' ptr sz s\<rbrace>" apply (rule hoare_name_pre_state) apply (clarsimp split:if_splits) apply (clarsimp simp:caps_no_overlap''_def2 deleteObjects_def2 capAligned_def valid_cap'_def dest!:ctes_of_valid_cap') apply (wp deleteObjects_null_filter[where idx = idx and p = slot]) apply (clarsimp simp:cte_wp_at_ctes_of invs_def) apply (case_tac cte) apply clarsimp apply (frule ctes_of_valid_cap') apply (simp add:invs_valid_objs') apply (simp add:valid_cap'_def capAligned_def) done lemma descendants_range_in_subseteq': "\<lbrakk>descendants_range_in' A p ms ;B\<subseteq> A\<rbrakk> \<Longrightarrow> descendants_range_in' B p ms" by (auto simp:descendants_range_in'_def cte_wp_at_ctes_of dest!:bspec) lemma updateFreeIndex_mdb_simple': "\<lbrace>\<lambda>s. descendants_of' src (ctes_of s) = {} \<and> pspace_no_overlap' (capPtr cap) (capBlockSize cap) s \<and> valid_pspace' s \<and> cte_wp_at' (\<lambda>c. \<exists>idx'. cteCap c = capFreeIndex_update (\<lambda>_. idx') cap) src s \<and> isUntypedCap cap\<rbrace> updateCap src (capFreeIndex_update (\<lambda>_. idx) cap) \<lbrace>\<lambda>rv. valid_mdb'\<rbrace>" apply (clarsimp simp:valid_mdb'_def updateCap_def valid_pspace'_def) apply (wp getCTE_wp) apply (clarsimp simp:cte_wp_at_ctes_of isCap_simps simp del:fun_upd_apply) apply (frule mdb_inv_preserve_updateCap[where index=idx and m="ctes_of s" and slot=src for s]) apply (simp add: isCap_simps) apply (simp add: modify_map_def) apply (clarsimp simp add: mdb_inv_preserve.preserve_stuff mdb_inv_preserve.by_products valid_mdb_ctes_def) proof - fix s cte ptr sz idx' d assume descendants: "descendants_of' src (ctes_of s) = {}" and cte_wp_at' :"ctes_of s src = Some cte" "cteCap cte = capability.UntypedCap d ptr sz idx'" and unt_inc' :"untyped_inc' (ctes_of s)" and valid_objs' :"valid_objs' s" and invp: "mdb_inv_preserve (ctes_of s) (ctes_of s(src \<mapsto> cteCap_update (\<lambda>_. capability.UntypedCap d ptr sz idx) cte))" (is "mdb_inv_preserve (ctes_of s) ?ctes") show "untyped_inc' ?ctes" using cte_wp_at' apply (clarsimp simp:untyped_inc'_def mdb_inv_preserve.descendants_of[OF invp, symmetric] descendants split del: if_split) apply (case_tac "ctes_of s p") apply (simp split: if_split_asm) apply (case_tac "ctes_of s p'") apply (simp split: if_split_asm) apply (case_tac "the (ctes_of s p)", case_tac "the (ctes_of s p')") apply clarsimp apply (cut_tac p=p and p'=p' in untyped_incD'[OF _ _ _ _ unt_inc']) apply assumption apply (clarsimp simp: isCap_simps split: if_split_asm) apply assumption apply (clarsimp simp: isCap_simps split: if_split_asm) apply (clarsimp simp: descendants split: if_split_asm) done qed lemma pspace_no_overlap_valid_untyped': "\<lbrakk> pspace_no_overlap' ptr bits s; is_aligned ptr bits; bits < word_bits; pspace_aligned' s \<rbrakk> \<Longrightarrow> valid_untyped' d ptr bits idx s" apply (clarsimp simp: valid_untyped'_def ko_wp_at'_def split del: if_split) apply (frule(1) pspace_no_overlapD') apply (simp add: obj_range'_def[symmetric] Int_commute) apply (erule disjE) apply (drule base_member_set[simplified field_simps]) apply (simp add: word_bits_def) apply blast apply (simp split: if_split_asm) apply (erule notE, erule disjoint_subset2[rotated]) apply (clarsimp simp: is_aligned_no_wrap'[OF _ word_of_nat_less]) done lemma updateFreeIndex_valid_pspace_no_overlap': "\<lbrace>\<lambda>s. valid_pspace' s \<and> (\<exists>ptr sz. pspace_no_overlap' ptr sz s \<and> idx \<le> 2 ^ sz \<and> cte_wp_at' ((\<lambda>c. isUntypedCap c \<and> capPtr c = ptr \<and> capBlockSize c = sz) o cteCap) src s) \<and> is_aligned (of_nat idx :: machine_word) minUntypedSizeBits \<and> descendants_of' src (ctes_of s) = {}\<rbrace> updateFreeIndex src idx \<lbrace>\<lambda>r s. valid_pspace' s\<rbrace>" apply (clarsimp simp:valid_pspace'_def updateFreeIndex_def updateTrackedFreeIndex_def) apply (rule hoare_pre) apply (rule hoare_vcg_conj_lift) apply (clarsimp simp:updateCap_def getSlotCap_def) apply (wp getCTE_wp | simp)+ apply (wp updateFreeIndex_mdb_simple' getCTE_wp' | simp add: getSlotCap_def)+ apply (clarsimp simp:cte_wp_at_ctes_of valid_pspace'_def) apply (case_tac cte,simp add:isCap_simps) apply (frule(1) ctes_of_valid_cap') apply (clarsimp simp: valid_cap_simps' capAligned_def pspace_no_overlap_valid_untyped') done crunch vms'[wp]: updateFreeIndex "valid_machine_state'" (* FIXME: move *) lemma setCTE_tcbDomain_inv[wp]: "\<lbrace>obj_at' (\<lambda>tcb. P (tcbState tcb)) t\<rbrace> setCTE ptr v \<lbrace>\<lambda>_. obj_at' (\<lambda>tcb. P (tcbState tcb)) t\<rbrace>" apply (simp add: setCTE_def) apply (rule setObject_cte_obj_at_tcb', simp_all) done (* FIXME: move *) crunch tcbState_inv[wp]: cteInsert "obj_at' (\<lambda>tcb. P (tcbState tcb)) t" (wp: crunch_simps hoare_drop_imps) lemma updateFreeIndex_clear_invs': "\<lbrace>\<lambda>s. invs' s \<and> (\<exists>ptr sz. pspace_no_overlap' ptr sz s \<and> idx \<le> 2 ^ sz \<and> cte_wp_at' ((\<lambda>c. isUntypedCap c \<and> capPtr c = ptr \<and> capBlockSize c = sz) o cteCap) src s) \<and> is_aligned (of_nat idx :: machine_word) minUntypedSizeBits \<and> descendants_of' src (ctes_of s) = {}\<rbrace> updateFreeIndex src idx \<lbrace>\<lambda>r s. invs' s\<rbrace>" apply (clarsimp simp:invs'_def valid_state'_def) apply (wp updateFreeIndex_valid_pspace_no_overlap') apply (simp add: updateFreeIndex_def updateTrackedFreeIndex_def) apply (wp updateFreeIndex_valid_pspace_no_overlap' sch_act_wf_lift valid_queues_lift updateCap_iflive' tcb_in_cur_domain'_lift | simp add: pred_tcb_at'_def)+ apply (rule hoare_vcg_conj_lift) apply (simp add: ifunsafe'_def3 cteInsert_def setUntypedCapAsFull_def split del: if_split) apply wp+ apply (rule hoare_vcg_conj_lift) apply (simp add:updateCap_def) apply wp+ apply (wp valid_irq_node_lift) apply (rule hoare_vcg_conj_lift) apply (simp add:updateCap_def) apply (wp setCTE_irq_handlers' getCTE_wp) apply (simp add:updateCap_def) apply (wp irqs_masked_lift valid_queues_lift' cur_tcb_lift ct_idle_or_in_cur_domain'_lift hoare_vcg_disj_lift untyped_ranges_zero_lift getCTE_wp setCTE_ioports' | wp (once) hoare_use_eq[where f="gsUntypedZeroRanges"] | simp add: getSlotCap_def | simp add: cte_wp_at_ctes_of)+ apply (clarsimp simp: cte_wp_at_ctes_of fun_upd_def[symmetric]) apply (clarsimp simp: isCap_simps) apply (frule(1) valid_global_refsD_with_objSize) apply clarsimp apply (intro conjI allI impI) apply (clarsimp simp: modify_map_def cteCaps_of_def ifunsafe'_def3 split:if_splits) apply (drule_tac x=src in spec) apply (clarsimp simp:isCap_simps) apply (rule_tac x = cref' in exI) apply clarsimp apply (drule_tac x = cref in spec) apply clarsimp apply (rule_tac x = cref' in exI) apply clarsimp apply (clarsimp simp: valid_pspace'_def) apply (erule untyped_ranges_zero_fun_upd, simp_all) apply (clarsimp simp: untypedZeroRange_def cteCaps_of_def isCap_simps) done lemma cte_wp_at_pspace_no_overlapI': "\<lbrakk>invs' s; cte_wp_at' (\<lambda>c. cteCap c = capability.UntypedCap d (ptr && ~~ mask sz) sz idx) cref s; idx \<le> unat (ptr && mask sz); sz < word_bits\<rbrakk> \<Longrightarrow> pspace_no_overlap' ptr sz s" apply (clarsimp simp:cte_wp_at_ctes_of) apply (case_tac cte,clarsimp) apply (frule ctes_of_valid_cap') apply (simp add:invs_valid_objs') apply (clarsimp simp:valid_cap'_def invs'_def valid_state'_def valid_pspace'_def valid_untyped'_def simp del:usableUntypedRange.simps) apply (unfold pspace_no_overlap'_def) apply (intro allI impI) apply (unfold ko_wp_at'_def) apply (clarsimp simp del: atLeastAtMost_iff atLeastatMost_subset_iff atLeastLessThan_iff Int_atLeastAtMost atLeastatMost_empty_iff usableUntypedRange.simps) apply (drule spec)+ apply (frule(1) pspace_distinctD') apply (frule(1) pspace_alignedD') apply (erule(1) impE)+ apply (clarsimp simp: obj_range'_def simp del: atLeastAtMost_iff atLeastatMost_subset_iff atLeastLessThan_iff Int_atLeastAtMost atLeastatMost_empty_iff usableUntypedRange.simps) apply (erule disjoint_subset2[rotated]) apply (frule(1) le_mask_le_2p) apply (clarsimp simp:p_assoc_help) apply (rule le_plus'[OF word_and_le2]) apply simp apply (erule word_of_nat_le) done lemma descendants_range_caps_no_overlapI': "\<lbrakk>invs' s; cte_wp_at' (\<lambda>c. cteCap c = capability.UntypedCap d (ptr && ~~ mask sz) sz idx) cref s; descendants_range_in' {ptr .. (ptr && ~~ mask sz) +2^sz - 1} cref (ctes_of s)\<rbrakk> \<Longrightarrow> caps_no_overlap'' ptr sz s" apply (frule invs_mdb') apply (clarsimp simp:valid_mdb'_def valid_mdb_ctes_def cte_wp_at_ctes_of simp del:usableUntypedRange.simps untypedRange.simps) apply (unfold caps_no_overlap''_def) apply (intro ballI impI) apply (erule ranE) apply (subgoal_tac "isUntypedCap (cteCap ctea)") prefer 2 apply (rule untypedRange_not_emptyD) apply blast apply (case_tac ctea,case_tac cte) apply simp apply (drule untyped_incD') apply ((simp add:isCap_simps del:usableUntypedRange.simps untypedRange.simps)+)[4] apply (elim conjE subset_splitE) apply (erule subset_trans[OF _ psubset_imp_subset,rotated]) apply (clarsimp simp:word_and_le2) apply simp apply (elim conjE) apply (thin_tac "P\<longrightarrow>Q" for P Q)+ apply (drule(2) descendants_range_inD') apply (simp add:untypedCapRange)+ apply (erule subset_trans[OF _ equalityD1,rotated]) apply (clarsimp simp:word_and_le2) apply (thin_tac "P\<longrightarrow>Q" for P Q)+ apply (drule disjoint_subset[rotated, where A' = "{ptr..(ptr && ~~ mask sz) + 2 ^ sz - 1}"]) apply (clarsimp simp:word_and_le2 Int_ac)+ done lemma cte_wp_at_caps_no_overlapI': "\<lbrakk>invs' s; cte_wp_at' (\<lambda>c. (cteCap c) = capability.UntypedCap d (ptr && ~~ mask sz) sz idx) cref s; idx \<le> unat (ptr && mask sz); sz < word_bits\<rbrakk> \<Longrightarrow> caps_no_overlap'' ptr sz s" apply (frule invs_mdb') apply (frule(1) le_mask_le_2p) apply (clarsimp simp:valid_mdb'_def valid_mdb_ctes_def cte_wp_at_ctes_of) apply (case_tac cte) apply simp apply (frule(1) ctes_of_valid_cap'[OF _ invs_valid_objs']) apply (unfold caps_no_overlap''_def) apply (intro ballI impI) apply (erule ranE) apply (subgoal_tac "isUntypedCap (cteCap ctea)") prefer 2 apply (rule untypedRange_not_emptyD) apply blast apply (case_tac ctea) apply simp apply (drule untyped_incD') apply (simp add:isCap_simps)+ apply (elim conjE) apply (erule subset_splitE) apply (erule subset_trans[OF _ psubset_imp_subset,rotated]) apply (clarsimp simp: word_and_le2) apply simp apply (thin_tac "P\<longrightarrow>Q" for P Q)+ apply (elim conjE) apply (drule disjoint_subset2[rotated, where B' = "{ptr..(ptr && ~~ mask sz) + 2 ^ sz - 1}"]) apply clarsimp apply (rule le_plus'[OF word_and_le2]) apply simp apply (erule word_of_nat_le) apply simp apply simp apply (erule subset_trans[OF _ equalityD1,rotated]) apply (clarsimp simp:word_and_le2) apply (thin_tac "P\<longrightarrow>Q" for P Q)+ apply (drule disjoint_subset[rotated, where A' = "{ptr..(ptr && ~~ mask sz) + 2 ^ sz - 1}"]) apply (clarsimp simp:word_and_le2 Int_ac)+ done lemma descendants_range_ex_cte': "\<lbrakk>descendants_range_in' S p (ctes_of s');ex_cte_cap_wp_to' P q s'; S \<subseteq> capRange (cteCap cte); invs' s';ctes_of s' p = Some cte;isUntypedCap (cteCap cte)\<rbrakk> \<Longrightarrow> q \<notin> S" apply (frule invs_valid_objs') apply (frule invs_mdb') apply (clarsimp simp:invs'_def valid_state'_def) apply (clarsimp simp: ex_cte_cap_to'_def cte_wp_at_ctes_of) apply (frule_tac cte = "cte" in valid_global_refsD') apply simp apply (case_tac "\<exists>irq. cteCap ctea = IRQHandlerCap irq") apply clarsimp apply (erule(1) in_empty_interE[OF _ _ subsetD,rotated -1]) apply (clarsimp simp:global_refs'_def) apply (erule_tac A = "range P" for P in subsetD) apply (simp add:range_eqI field_simps) apply (case_tac ctea) apply clarsimp apply (case_tac ctea) apply (drule_tac cte = "cte" and cte' = ctea in untyped_mdbD') apply assumption apply (clarsimp simp:isCap_simps) apply (drule_tac B = "untypedRange (cteCap cte)" in subsetD[rotated]) apply (clarsimp simp:untypedCapRange) apply clarsimp apply (drule_tac x = " (irq_node' s')" in cte_refs_capRange[rotated]) apply (erule(1) ctes_of_valid_cap') apply blast apply (clarsimp simp:isCap_simps) apply (simp add:valid_mdb'_def valid_mdb_ctes_def) apply (drule(2) descendants_range_inD') apply clarsimp apply (drule_tac x = " (irq_node' s')" in cte_refs_capRange[rotated]) apply (erule(1) ctes_of_valid_cap') apply blast done lemma updateCap_isUntypedCap_corres: "\<lbrakk>is_untyped_cap cap; isUntypedCap cap'; cap_relation cap cap'\<rbrakk> \<Longrightarrow> corres dc (cte_wp_at (\<lambda>c. is_untyped_cap c \<and> obj_ref_of c = obj_ref_of cap \<and> cap_bits c = cap_bits cap \<and> cap_is_device c = cap_is_device cap) src and valid_objs and pspace_aligned and pspace_distinct) (cte_at' (cte_map src) and pspace_distinct' and pspace_aligned') (set_cap cap src) (updateCap (cte_map src) cap')" apply (rule corres_name_pre) apply (simp add: updateCap_def) apply (frule state_relation_pspace_relation) apply (clarsimp simp: cte_wp_at_ctes_of) apply (frule pspace_relation_cte_wp_atI) apply (fastforce simp: cte_wp_at_ctes_of) apply simp apply clarify apply (frule cte_map_inj_eq) apply (fastforce simp: cte_wp_at_ctes_of cte_wp_at_caps_of_state)+ apply (clarsimp simp: is_cap_simps isCap_simps) apply (rule corres_guard_imp) apply (rule corres_symb_exec_r) apply (rule_tac F = "cteCap_update (\<lambda>_. capability.UntypedCap dev r bits f) ctea = cteCap_update (\<lambda>cap. capFreeIndex_update (\<lambda>_. f) (cteCap cte)) cte" in corres_gen_asm2) apply (rule_tac F = " (cap.UntypedCap dev r bits f) = free_index_update (\<lambda>_. f) c" in corres_gen_asm) apply simp apply (rule setCTE_UntypedCap_corres) apply ((clarsimp simp: cte_wp_at_caps_of_state cte_wp_at_ctes_of)+)[3] apply (subst identity_eq) apply (wp getCTE_sp getCTE_get no_fail_getCTE)+ apply (clarsimp simp: cte_wp_at_ctes_of cte_wp_at_caps_of_state)+ done end lemma updateFreeIndex_corres: "\<lbrakk>is_untyped_cap cap; free_index_of cap = idx \<rbrakk> \<Longrightarrow> corres dc (cte_wp_at (\<lambda>c. is_untyped_cap c \<and> obj_ref_of c = obj_ref_of cap \<and> cap_bits c = cap_bits cap \<and> cap_is_device c = cap_is_device cap) src and valid_objs and pspace_aligned and pspace_distinct) (cte_at' (cte_map src) and pspace_distinct' and pspace_aligned') (set_cap cap src) (updateFreeIndex (cte_map src) idx)" apply (rule corres_name_pre) apply (simp add: updateFreeIndex_def updateTrackedFreeIndex_def) apply (rule corres_guard_imp) apply (rule corres_symb_exec_r_conj[where P'="cte_at' (cte_map src)"])+ apply (rule_tac F="isUntypedCap capa \<and> cap_relation cap (capFreeIndex_update (\<lambda>_. idx) capa)" in corres_gen_asm2) apply (rule updateCap_isUntypedCap_corres, simp+) apply (clarsimp simp: isCap_simps) apply simp apply (wp getSlotCap_wp)+ apply (clarsimp simp: state_relation_def cte_wp_at_ctes_of) apply (rule no_fail_pre, wp no_fail_getSlotCap) apply (clarsimp simp: cte_wp_at_ctes_of) apply (wp getSlotCap_wp)+ apply (clarsimp simp: state_relation_def cte_wp_at_ctes_of) apply (rule no_fail_pre, wp no_fail_getSlotCap) apply simp apply clarsimp apply (clarsimp simp: cte_wp_at_ctes_of cte_wp_at_caps_of_state) apply (frule state_relation_pspace_relation) apply (frule(1) pspace_relation_ctes_ofI[OF _ caps_of_state_cteD], simp+) apply (clarsimp simp: isCap_simps is_cap_simps cte_wp_at_caps_of_state free_index_of_def) done locale invokeUntyped_proofs = fixes s cref reset ptr_base ptr tp us slots sz idx dev assumes vui: "valid_untyped_inv_wcap' (Invocations_H.Retype cref reset ptr_base ptr tp us slots dev) (Some (UntypedCap dev (ptr && ~~ mask sz) sz idx)) s" and misc: "ct_active' s" "invs' s" begin lemma cte_wp_at': "cte_wp_at' (\<lambda>cte. cteCap cte = capability.UntypedCap dev (ptr && ~~ mask sz) sz idx) cref s" and cover: "range_cover ptr sz (APIType_capBits tp us) (length (slots::machine_word list))" and misc2: "distinct slots" "slots \<noteq> []" "\<forall>slot\<in>set slots. cte_wp_at' (\<lambda>c. cteCap c = capability.NullCap) slot s" "\<forall>x\<in>set slots. ex_cte_cap_wp_to' (\<lambda>_. True) x s" using vui by (auto simp: cte_wp_at_ctes_of) interpretation Arch . (*FIXME: arch_split*) lemma idx_cases: "((\<not> reset \<and> idx \<le> unat (ptr - (ptr && ~~ mask sz))) \<or> reset \<and> ptr = ptr && ~~ mask sz)" using vui by (clarsimp simp: cte_wp_at_ctes_of) lemma desc_range: "reset \<longrightarrow> descendants_range_in' {ptr..ptr + 2 ^ sz - 1} (cref) (ctes_of s)" using vui by (clarsimp simp: empty_descendants_range_in') abbreviation(input) "retype_range == {ptr..ptr + of_nat (length slots) * 2 ^ APIType_capBits tp us - 1}" abbreviation(input) "usable_range == {ptr..(ptr && ~~ mask sz) + 2 ^ sz - 1}" lemma not_0_ptr[simp]: "ptr\<noteq> 0" using misc cte_wp_at' apply (clarsimp simp: cte_wp_at_ctes_of) apply (case_tac cte) apply clarsimp apply (drule(1) ctes_of_valid_cap'[OF _ invs_valid_objs']) apply (simp add: valid_cap'_def) done lemma subset_stuff[simp]: "retype_range \<subseteq> usable_range" apply (rule range_cover_subset'[OF cover]) apply (simp add:misc2) done lemma descendants_range[simp]: "descendants_range_in' usable_range cref (ctes_of s)" "descendants_range_in' retype_range cref (ctes_of s)" proof - have "descendants_range_in' usable_range cref (ctes_of s)" using misc idx_cases cte_wp_at' cover apply - apply (erule disjE) apply (erule cte_wp_at_caps_descendants_range_inI' [OF _ _ _ range_cover.sz(1)[where 'a=machine_word_len, folded word_bits_def]]) apply simp+ using desc_range apply simp done thus "descendants_range_in' usable_range cref (ctes_of s)" by simp thus "descendants_range_in' retype_range cref (ctes_of s)" by (rule descendants_range_in_subseteq'[OF _ subset_stuff]) qed lemma vc'[simp] : "s \<turnstile>' capability.UntypedCap dev (ptr && ~~ mask sz) sz idx" using misc cte_wp_at' apply (clarsimp simp: cte_wp_at_ctes_of) apply (case_tac cte) apply clarsimp apply (erule ctes_of_valid_cap') apply (simp add: invs_valid_objs') done lemma ptr_cn[simp]: "canonical_address (ptr && ~~ mask sz)" using vc' unfolding valid_cap'_def by clarsimp lemma ptr_km[simp]: "ptr && ~~ mask sz \<in> kernel_mappings" using vc' unfolding valid_cap'_def by clarsimp lemma sz_limit[simp]: "sz \<le> maxUntypedSizeBits" using vc' unfolding valid_cap'_def by clarsimp lemma ps_no_overlap'[simp]: "\<not> reset \<Longrightarrow> pspace_no_overlap' ptr sz s" using misc cte_wp_at' cover idx_cases apply clarsimp apply (erule cte_wp_at_pspace_no_overlapI' [OF _ _ _ range_cover.sz(1)[where 'a=machine_word_len, folded word_bits_def]]) apply (simp add: cte_wp_at_ctes_of) apply simp+ done lemma caps_no_overlap'[simp]: "caps_no_overlap'' ptr sz s" using cte_wp_at' misc cover desc_range idx_cases apply - apply (erule disjE) apply (erule cte_wp_at_caps_no_overlapI' [OF _ _ _ range_cover.sz(1)[where 'a=machine_word_len, folded word_bits_def]]) apply simp+ apply (erule descendants_range_caps_no_overlapI') apply simp+ done lemma idx_compare'[simp]:"unat ((ptr && mask sz) + (of_nat (length slots)<< (APIType_capBits tp us))) \<le> 2 ^ sz" apply (rule le_trans[OF unat_plus_gt]) apply (simp add: range_cover.unat_of_nat_n_shift[OF cover] range_cover_unat) apply (insert range_cover.range_cover_compare_bound[OF cover]) apply simp done lemma ex_cte_no_overlap': "\<And>P p. ex_cte_cap_wp_to' P p s \<Longrightarrow> p \<notin> usable_range" using cte_wp_at' misc apply (clarsimp simp: cte_wp_at_ctes_of) apply (drule_tac cte = cte in descendants_range_ex_cte'[OF descendants_range(1)]) apply (clarsimp simp: word_and_le2 isCap_simps)+ done lemma cref_inv: "cref \<notin> usable_range" apply (insert misc cte_wp_at') apply (drule if_unsafe_then_capD') apply (simp add: invs'_def valid_state'_def) apply simp apply (erule ex_cte_no_overlap') done lemma slots_invD: "\<And>x. x \<in> set slots \<Longrightarrow> x \<noteq> cref \<and> x \<notin> usable_range \<and> ex_cte_cap_wp_to' (\<lambda>_. True) x s" using misc cte_wp_at' vui apply - apply clarsimp apply (drule(1) bspec)+ apply (drule ex_cte_no_overlap') apply simp apply (clarsimp simp: cte_wp_at_ctes_of) done lemma usableRange_disjoint: "usableUntypedRange (capability.UntypedCap d (ptr && ~~ mask sz) sz (unat ((ptr && mask sz) + of_nat (length slots) * 2 ^ APIType_capBits tp us))) \<inter> {ptr..ptr + of_nat (length slots) * 2 ^ APIType_capBits tp us - 1} = {}" proof - have idx_compare''[simp]: "unat ((ptr && mask sz) + (of_nat (length slots) * (2::machine_word) ^ APIType_capBits tp us)) < 2 ^ sz \<Longrightarrow> ptr + of_nat (length slots) * 2 ^ APIType_capBits tp us - 1 < ptr + of_nat (length slots) * 2 ^ APIType_capBits tp us" apply (rule word_leq_le_minus_one,simp) apply (rule neq_0_no_wrap) apply (rule machine_word_plus_mono_right_split) apply (simp add: shiftl_t2n range_cover_unat[OF cover] field_simps) apply (simp add: range_cover.sz(1) [where 'a=machine_word_len, folded word_bits_def, OF cover])+ done show ?thesis apply (clarsimp simp: mask_out_sub_mask) apply (drule idx_compare'') apply simp done qed lemma szw: "sz < word_bits" using cte_wp_at_valid_objs_valid_cap'[OF cte_wp_at'] misc by (clarsimp simp: valid_cap_simps' capAligned_def invs_valid_objs') lemma idx_le_new_offs: "\<not> reset \<longrightarrow> idx \<le> unat ((ptr && mask sz) + (of_nat (length slots) * 2 ^ (APIType_capBits tp us)))" using misc idx_cases range_cover.range_cover_base_le[OF cover] apply (clarsimp simp only: simp_thms) apply (erule order_trans) apply (simp add: word_le_nat_alt[symmetric] shiftl_t2n mult.commute) done end lemma valid_sched_etcbs[elim!]: "valid_sched_2 queues ekh sa cdom kh ct it \<Longrightarrow> valid_etcbs_2 ekh kh" by (simp add: valid_sched_def) crunch ksIdleThread[wp]: deleteObjects "\<lambda>s. P (ksIdleThread s)" (simp: crunch_simps wp: hoare_drop_imps unless_wp ignore: freeMemory) crunch ksCurDomain[wp]: deleteObjects "\<lambda>s. P (ksCurDomain s)" (simp: crunch_simps wp: hoare_drop_imps unless_wp ignore: freeMemory) crunch irq_node[wp]: deleteObjects "\<lambda>s. P (irq_node' s)" (simp: crunch_simps wp: hoare_drop_imps unless_wp ignore: freeMemory) lemma deleteObjects_ksCurThread[wp]: "\<lbrace>\<lambda>s. P (ksCurThread s)\<rbrace> deleteObjects ptr sz \<lbrace>\<lambda>_ s. P (ksCurThread s)\<rbrace>" apply (simp add: deleteObjects_def3) apply (wp | simp add: doMachineOp_def split_def)+ done lemma deleteObjects_ct_active': "\<lbrace>invs' and sch_act_simple and ct_active' and cte_wp_at' (\<lambda>c. cteCap c = UntypedCap d ptr sz idx) cref and (\<lambda>s. descendants_range' (UntypedCap d ptr sz idx) cref (ctes_of s)) and K (sz < word_bits \<and> is_aligned ptr sz)\<rbrace> deleteObjects ptr sz \<lbrace>\<lambda>_. ct_active'\<rbrace>" apply (simp add: ct_in_state'_def) apply (rule hoare_pre) apply wps apply (wp deleteObjects_st_tcb_at') apply (auto simp: ct_in_state'_def elim: pred_tcb'_weakenE) done defs cNodeOverlap_def: "cNodeOverlap \<equiv> \<lambda>cns inRange. \<exists>p n. cns p = Some n \<and> (\<not> is_aligned p (cte_level_bits + n) \<or> cte_level_bits + n \<ge> word_bits \<or> ({p .. p + 2 ^ (cte_level_bits + n) - 1} \<inter> {p. inRange p} \<noteq> {}))" lemma cNodeNoOverlap: notes Int_atLeastAtMost[simp del] shows "corres dc (\<lambda>s. \<exists>cref. cte_wp_at (\<lambda>cap. is_untyped_cap cap \<and> Collect R \<subseteq> usable_untyped_range cap) cref s \<and> valid_objs s \<and> pspace_aligned s) \<top> (return x) (stateAssert (\<lambda>s. \<not> cNodeOverlap (gsCNodes s) R) [])" apply (simp add: stateAssert_def assert_def) apply (rule corres_symb_exec_r[OF _ get_sp]) apply (rule corres_req[rotated], subst if_P, assumption) apply simp apply (clarsimp simp: cNodeOverlap_def cte_wp_at_caps_of_state) apply (frule(1) caps_of_state_valid_cap) apply (frule usable_range_subseteq[rotated], simp add: valid_cap_def) apply (clarsimp simp: valid_cap_def valid_untyped_def cap_table_at_gsCNodes_eq obj_at_def is_cap_table is_cap_simps) apply (frule(1) pspace_alignedD) apply simp apply (elim allE, drule(1) mp, simp add: obj_range_def valid_obj_def cap_aligned_def) apply (erule is_aligned_get_word_bits[where 'a=machine_word_len, folded word_bits_def]) apply (clarsimp simp: is_aligned_no_overflow simp del: ) apply blast apply (simp add: is_aligned_no_overflow power_overflow word_bits_def Int_atLeastAtMost) apply wp+ done lemma reset_ineq_eq_idx_0: "idx \<le> 2 ^ sz \<Longrightarrow> b \<le> sz \<Longrightarrow> (ptr :: obj_ref) \<noteq> 0 \<Longrightarrow> is_aligned ptr sz \<Longrightarrow> sz < word_bits \<Longrightarrow> (ptr + of_nat idx - 1 < ptr) = (idx = 0)" apply (cases "idx = 0") apply (simp add: gt0_iff_gem1[symmetric] word_neq_0_conv) apply simp apply (subgoal_tac "ptr \<le> ptr + of_nat idx - 1", simp_all)[1] apply (subst field_simps[symmetric], erule is_aligned_no_wrap') apply (subst word_less_nat_alt) apply simp apply (subst unat_of_nat_minus_1) apply (erule order_le_less_trans, rule power_strict_increasing) apply (simp add: word_bits_def) apply simp apply (rule notI, simp) apply (erule order_less_le_trans[rotated]) apply simp done lemma reset_addrs_same: "idx \<le> 2 ^ sz \<Longrightarrow> resetChunkBits \<le> sz \<Longrightarrow> ptr \<noteq> 0 \<Longrightarrow> is_aligned ptr sz \<Longrightarrow> sz < word_bits \<Longrightarrow> [ptr , ptr + 2 ^ resetChunkBits .e. getFreeRef ptr idx - 1] = (map (\<lambda>i. getFreeRef ptr (i * 2 ^ resetChunkBits)) ([i\<leftarrow>[0..<2 ^ (sz - resetChunkBits)]. i * 2 ^ resetChunkBits < idx]))" apply (simp add: upto_enum_step_def getFreeRef_def reset_ineq_eq_idx_0) apply (clarsimp simp: upto_enum_word o_def unat_div simp del: upt.simps) apply (subst unat_of_nat_minus_1) apply (rule_tac y="2 ^ sz" in order_le_less_trans, simp) apply (rule power_strict_increasing, simp_all add: word_bits_def)[1] apply simp apply (rule_tac f="map f" for f in arg_cong) apply (rule filter_upt_eq[symmetric]) apply clarsimp apply (erule order_le_less_trans[rotated]) apply simp apply (rule notI) apply (drule order_less_le_trans[where x="a * b" for a b], rule_tac m="2 ^ resetChunkBits" and n=idx in alignUp_ge_nat) apply simp+ apply (simp add: field_simps) apply (simp only: mult_Suc_right[symmetric]) apply (subst(asm) div_add_self1[where 'a=nat, simplified, symmetric]) apply simp apply (simp only: field_simps) apply simp apply clarsimp apply (rule order_le_less_trans, rule div_mult_le, simp) apply (simp add: Suc_le_eq td_gal_lt[symmetric] power_add[symmetric]) done lemmas descendants_of_null_filter' = null_filter_descendants_of'[OF null_filter_simp'] lemmas deleteObjects_descendants = deleteObjects_null_filter[where P="\<lambda>c. Q (descendants_of' p c)" for p Q, simplified descendants_of_null_filter'] lemma updateFreeIndex_descendants_of2: " \<lbrace>\<lambda>s. cte_wp_at' (isUntypedCap o cteCap) ptr s \<and> P (\<lambda>y. descendants_of' y (ctes_of s))\<rbrace> updateFreeIndex ptr index \<lbrace>\<lambda>r s. P (\<lambda>y. descendants_of' y (ctes_of s))\<rbrace>" apply (simp add: updateFreeIndex_def updateTrackedFreeIndex_def getSlotCap_def) apply (wp updateFreeIndex_descendants_of'[simplified swp_def descendants_of_null_filter'] getCTE_wp') apply (clarsimp simp: cte_wp_at_ctes_of isCap_simps) done crunch typ_at'[wp]: updateFreeIndex "\<lambda>s. P (typ_at' T p s)" lemma updateFreeIndex_cte_wp_at: "\<lbrace>\<lambda>s. cte_wp_at' (\<lambda>c. P (cteCap_update (if p = slot then capFreeIndex_update (\<lambda>_. idx) else id) c)) p s\<rbrace> updateFreeIndex slot idx \<lbrace>\<lambda>rv. cte_wp_at' P p\<rbrace>" apply (simp add: updateFreeIndex_def updateTrackedFreeIndex_def getSlotCap_def split del: if_split) apply (rule hoare_pre, wp updateCap_cte_wp_at' getCTE_wp') apply (clarsimp simp: cte_wp_at_ctes_of) apply (case_tac "the (ctes_of s p)") apply (auto split: if_split_asm) done lemma ex_tupI: "P (fst x) (snd x) \<Longrightarrow> \<exists>a b. P a b" by blast context begin interpretation Arch . (*FIXME: arch_split*) (* mostly stuff about PPtr/fromPPtr, which seems pretty soft *) lemma resetUntypedCap_corres: "untypinv_relation ui ui' \<Longrightarrow> corres (dc \<oplus> dc) (invs and valid_untyped_inv_wcap ui (Some (cap.UntypedCap dev ptr sz idx)) and ct_active and einvs and (\<lambda>_. \<exists>ptr_base ptr' ty us slots dev'. ui = Invocations_A.Retype slot True ptr_base ptr' ty us slots dev)) (invs' and valid_untyped_inv_wcap' ui' (Some (UntypedCap dev ptr sz idx)) and ct_active') (reset_untyped_cap slot) (resetUntypedCap (cte_map slot))" apply (rule corres_gen_asm, clarsimp) apply (simp add: reset_untyped_cap_def resetUntypedCap_def liftE_bindE) apply (rule corres_guard_imp) apply (rule corres_split[OF getSlotCap_corres]) apply simp apply (rule_tac F="cap = cap.UntypedCap dev ptr sz idx \<and> (\<exists>s. s \<turnstile> cap)" in corres_gen_asm) apply (clarsimp simp: bits_of_def free_index_of_def unlessE_def split del: if_split) apply (rule corres_if[OF refl]) apply (rule corres_returnOk[where P=\<top> and P'=\<top>], simp) apply (simp add: liftE_bindE bits_of_def split del: if_split) apply (rule corres_split[OF deleteObjects_corres]) apply (clarsimp simp add: valid_cap_def cap_aligned_def) apply (clarsimp simp add: valid_cap_def untyped_min_bits_def) apply (rule corres_if) apply simp apply (simp add: bits_of_def shiftL_nat) apply (rule corres_split_nor) apply (simp add: unless_def) apply (rule corres_when, simp) apply (rule corres_machine_op) apply (rule corres_Id, simp, simp, wp) apply (rule updateFreeIndex_corres, simp) apply (simp add: free_index_of_def) apply (wp | simp only: unless_def)+ apply (rule_tac F="sz < word_bits \<and> idx \<le> 2 ^ sz \<and> ptr \<noteq> 0 \<and> is_aligned ptr sz \<and> resetChunkBits \<le> sz" in corres_gen_asm) apply (simp add: bits_of_def free_index_of_def mapME_x_map_simp liftE_bindE reset_addrs_same[where ptr=ptr and idx=idx and sz=sz] o_def rev_map del: capFreeIndex_update.simps) apply (rule_tac P="\<lambda>x. valid_objs and pspace_aligned and pspace_distinct and pspace_no_overlap {ptr .. ptr + 2 ^ sz - 1} and cte_wp_at (\<lambda>a. is_untyped_cap a \<and> obj_ref_of a = ptr \<and> cap_bits a = sz \<and> cap_is_device a = dev) slot" and P'="\<lambda>_. valid_pspace' and (\<lambda>s. descendants_of' (cte_map slot) (ctes_of s) = {}) and pspace_no_overlap' ptr sz and cte_wp_at' (\<lambda>cte. \<exists>idx. cteCap cte = UntypedCap dev ptr sz idx) (cte_map slot)" in mapME_x_corres_same_xs) apply (rule corres_guard_imp) apply (rule corres_split_nor) apply (rule corres_machine_op) apply (rule corres_Id) apply (simp add: shiftL_nat getFreeRef_def shiftl_t2n mult.commute) apply simp apply wp apply (rule corres_split_nor[OF updateFreeIndex_corres]) apply simp apply (simp add: getFreeRef_def getFreeIndex_def free_index_of_def) apply clarify apply (subst unat_mult_simple) apply (subst unat_of_nat_eq) apply (rule order_less_trans[rotated], rule_tac n=sz in power_strict_increasing; simp add: word_bits_def) apply (erule order_less_le_trans; simp) apply (subst unat_p2) apply (simp add: Kernel_Config.resetChunkBits_def) apply (rule order_less_trans[rotated], rule_tac n=sz in power_strict_increasing; simp add: word_bits_def) apply (subst unat_of_nat_eq) apply (rule order_less_trans[rotated], rule_tac n=sz in power_strict_increasing; simp add: word_bits_def) apply (erule order_less_le_trans; simp) apply simp apply (rule preemptionPoint_corres) apply wp+ apply (clarsimp simp: cte_wp_at_caps_of_state) apply (clarsimp simp: getFreeRef_def valid_pspace'_def cte_wp_at_ctes_of valid_cap_def cap_aligned_def) apply (erule aligned_add_aligned) apply (rule is_aligned_weaken) apply (rule is_aligned_mult_triv2) apply (simp add: Kernel_Config.resetChunkBits_def) apply (simp add: untyped_min_bits_def) apply (rule hoare_pre) apply simp apply (strengthen imp_consequent) apply (wp preemption_point_inv set_cap_cte_wp_at update_untyped_cap_valid_objs set_cap_no_overlap | simp)+ apply (clarsimp simp: exI cte_wp_at_caps_of_state) apply (drule caps_of_state_valid_cap, simp+) apply (clarsimp simp: is_cap_simps valid_cap_simps cap_aligned_def valid_untyped_pspace_no_overlap) apply (rule hoare_pre) apply (simp del: capFreeIndex_update.simps) apply (strengthen imp_consequent) apply (wp updateFreeIndex_valid_pspace_no_overlap' updateFreeIndex_descendants_of2 doMachineOp_psp_no_overlap updateFreeIndex_cte_wp_at pspace_no_overlap'_lift preemptionPoint_inv hoare_vcg_ex_lift | simp)+ apply (clarsimp simp add: cte_wp_at_ctes_of exI isCap_simps valid_pspace'_def) apply (clarsimp simp: getFreeIndex_def getFreeRef_def) apply (subst is_aligned_weaken[OF is_aligned_mult_triv2]) apply (simp add: Kernel_Config.resetChunkBits_def minUntypedSizeBits_def) apply (subst unat_mult_simple) apply (subst unat_of_nat_eq) apply (rule order_less_trans[rotated], rule_tac n=sz in power_strict_increasing; simp add: word_bits_def) apply (erule order_less_le_trans; simp) apply (subst unat_p2) apply (simp add: Kernel_Config.resetChunkBits_def) apply (rule order_less_trans[rotated], rule_tac n=sz in power_strict_increasing; simp add: word_bits_def) apply (subst unat_of_nat_eq) apply (rule order_less_trans[rotated], rule_tac n=sz in power_strict_increasing; simp add: word_bits_def) apply (erule order_less_le_trans; simp) apply simp apply simp apply (simp add: if_apply_def2) apply (strengthen invs_valid_objs invs_psp_aligned invs_distinct) apply (wp hoare_vcg_const_imp_lift) apply (simp add: if_apply_def2) apply (strengthen invs_pspace_aligned' invs_pspace_distinct' invs_valid_pspace') apply (wp hoare_vcg_const_imp_lift deleteObjects_cte_wp_at'[where p="cte_map slot"] deleteObjects_invs'[where p="cte_map slot"] deleteObjects_descendants[where p="cte_map slot"] | simp)+ apply (wp get_cap_wp getCTE_wp' | simp add: getSlotCap_def)+ apply (clarsimp simp: cte_wp_at_caps_of_state descendants_range_def2) apply (cases slot) apply (strengthen empty_descendants_range_in ex_tupI[where x=slot])+ apply (frule(1) caps_of_state_valid) apply (clarsimp simp: valid_cap_simps cap_aligned_def) apply (frule(1) caps_of_state_valid) apply (frule if_unsafe_then_capD[OF caps_of_state_cteD], clarsimp+) apply (drule(1) ex_cte_cap_protects[OF _ caps_of_state_cteD empty_descendants_range_in _ order_refl], clarsimp+) apply (intro conjI impI; auto)[1] apply (clarsimp simp: cte_wp_at_ctes_of descendants_range'_def2 empty_descendants_range_in') apply (frule cte_wp_at_valid_objs_valid_cap'[OF ctes_of_cte_wpD], clarsimp+) apply (clarsimp simp: valid_cap_simps' capAligned_def is_aligned_weaken untypedBits_defs) apply (frule if_unsafe_then_capD'[OF ctes_of_cte_wpD], clarsimp+) apply (frule(1) descendants_range_ex_cte'[OF empty_descendants_range_in' _ order_refl], (simp add: isCap_simps)+) apply (intro conjI impI; clarsimp) done end lemma deleteObjects_ex_cte_cap_wp_to': "\<lbrace>invs' and ex_cte_cap_wp_to' P slot and (\<lambda>s. descendants_of' p (ctes_of s) = {}) and cte_wp_at' (\<lambda>cte. \<exists>idx d. cteCap cte = UntypedCap d ptr sz idx) p\<rbrace> deleteObjects ptr sz \<lbrace>\<lambda>rv. ex_cte_cap_wp_to' P slot\<rbrace>" apply (rule hoare_name_pre_state) apply (clarsimp simp: cte_wp_at_ctes_of) apply (rule hoare_pre) apply (simp add: ex_cte_cap_wp_to'_def) apply wps apply (wp hoare_vcg_ex_lift) apply (rule_tac idx=idx in deleteObjects_cte_wp_at') apply (clarsimp simp: cte_wp_at_ctes_of) apply (frule ctes_of_valid[OF ctes_of_cte_wpD], clarsimp+) apply (clarsimp simp: ex_cte_cap_wp_to'_def cte_wp_at_ctes_of) apply (rule_tac x=cref in exI, simp) apply (frule_tac p=cref in if_unsafe_then_capD'[OF ctes_of_cte_wpD], clarsimp+) apply (frule descendants_range_ex_cte'[rotated, OF _ order_refl, where p=p], (simp add: isCap_simps empty_descendants_range_in')+) apply auto done lemma updateCap_cte_cap_wp_to': "\<lbrace>\<lambda>s. cte_wp_at' (\<lambda>cte. p' \<in> cte_refs' (cteCap cte) (irq_node' s) \<and> P (cteCap cte) \<longrightarrow> p' \<in> cte_refs' cap (irq_node' s) \<and> P cap) p s \<and> ex_cte_cap_wp_to' P p' s\<rbrace> updateCap p cap \<lbrace>\<lambda>rv. ex_cte_cap_wp_to' P p'\<rbrace>" apply (simp add: ex_cte_cap_wp_to'_def cte_wp_at_ctes_of updateCap_def) apply (rule hoare_pre, (wp getCTE_wp | wps)+) apply (clarsimp simp: cte_wp_at_ctes_of) apply (rule_tac x=cref in exI) apply auto done crunch ct_in_state'[wp]: doMachineOp "ct_in_state' P" (simp: crunch_simps ct_in_state'_def) crunch st_tcb_at'[wp]: doMachineOp "st_tcb_at' P p" (simp: crunch_simps ct_in_state'_def) lemma ex_cte_cap_wp_to_irq_state_independent_H[simp]: "irq_state_independent_H (ex_cte_cap_wp_to' P slot)" by (simp add: ex_cte_cap_wp_to'_def) context begin interpretation Arch . (*FIXME: arch_split*) lemma updateFreeIndex_ctes_of: "\<lbrace>\<lambda>s. P (modify_map (ctes_of s) ptr (cteCap_update (capFreeIndex_update (\<lambda>_. idx))))\<rbrace> updateFreeIndex ptr idx \<lbrace>\<lambda>r s. P (ctes_of s)\<rbrace>" apply (simp add: updateFreeIndex_def updateTrackedFreeIndex_def getSlotCap_def) apply (wp updateCap_ctes_of_wp getCTE_wp' | simp)+ apply (clarsimp simp: cte_wp_at_ctes_of) apply (erule rsubst[where P=P]) apply (case_tac cte) apply (clarsimp simp: modify_map_def fun_eq_iff) done lemma updateFreeIndex_cte_cap_wp_to'[wp]: "\<lbrace>\<lambda>s. cte_wp_at' (isUntypedCap o cteCap) p s \<and> ex_cte_cap_wp_to' P p' s\<rbrace> updateFreeIndex p idx \<lbrace>\<lambda>rv. ex_cte_cap_wp_to' P p'\<rbrace>" apply (simp add: updateFreeIndex_def updateTrackedFreeIndex_def getSlotCap_def) apply (wp updateCap_cte_cap_wp_to' getCTE_wp') apply (clarsimp simp: cte_wp_at_ctes_of) apply (clarsimp simp: isCap_simps ex_cte_cap_wp_to'_def split: option.split) done lemma setCTE_ct_in_state: "\<lbrace>ct_in_state' P\<rbrace> setCTE p cte \<lbrace>\<lambda>rv. ct_in_state' P\<rbrace>" apply (rule hoare_name_pre_state) apply (rule hoare_pre, wp ct_in_state'_decomp setCTE_pred_tcb_at') apply (auto simp: ct_in_state'_def) done crunch ct_in_state[wp]: updateFreeIndex "ct_in_state' P" crunch nosch[wp]: updateFreeIndex "\<lambda>s. P (ksSchedulerAction s)" lemma resetUntypedCap_invs_etc: "\<lbrace>invs' and valid_untyped_inv_wcap' ui (Some (UntypedCap dev ptr sz idx)) and ct_active' and K (\<exists>ptr_base ptr' ty us slots. ui = Retype slot True ptr_base ptr' ty us slots dev)\<rbrace> resetUntypedCap slot \<lbrace>\<lambda>_. invs' and valid_untyped_inv_wcap' ui (Some (UntypedCap dev ptr sz 0)) and ct_active' and pspace_no_overlap' ptr sz\<rbrace>, \<lbrace>\<lambda>_. invs'\<rbrace>" (is "\<lbrace>invs' and valid_untyped_inv_wcap' ?ui (Some ?cap) and ct_active' and ?asm\<rbrace> ?f \<lbrace>\<lambda>_. invs' and ?vu2 and ct_active' and ?psp\<rbrace>, \<lbrace>\<lambda>_. invs'\<rbrace>") apply (simp add: resetUntypedCap_def getSlotCap_def liftE_bind_return_bindE_returnOk bindE_assoc) apply (rule hoare_vcg_seqE[rotated]) apply simp apply (rule getCTE_sp) apply (rule hoare_name_pre_stateE) apply (clarsimp split del: if_split) apply (subgoal_tac "capAligned ?cap") prefer 2 apply (frule cte_wp_at_valid_objs_valid_cap', clarsimp+) apply (clarsimp simp: cte_wp_at_ctes_of capAligned_def valid_cap_simps') apply (cases "idx = 0") apply (clarsimp simp: cte_wp_at_ctes_of unlessE_def split del: if_split) apply wp apply (clarsimp simp: valid_cap_simps' capAligned_def) apply (rule cte_wp_at_pspace_no_overlapI'[where cref=slot], (simp_all add: cte_wp_at_ctes_of)+)[1] apply (clarsimp simp: unlessE_def cte_wp_at_ctes_of split del: if_split) apply (rule_tac B="\<lambda>_. invs' and valid_untyped_inv_wcap' ?ui (Some ?cap) and ct_active' and ?psp" in hoare_vcg_seqE[rotated]) apply clarsimp apply (rule hoare_pre) apply (simp add: sch_act_simple_def) apply (wps ) apply (wp deleteObject_no_overlap[where idx=idx] deleteObjects_invs'[where idx=idx and p=slot] hoare_vcg_ex_lift hoare_vcg_const_Ball_lift deleteObjects_cte_wp_at'[where idx=idx] deleteObjects_descendants[where p=slot] deleteObjects_nosch deleteObjects_ct_active'[where idx=idx and cref=slot] deleteObjects_ex_cte_cap_wp_to'[where p=slot]) apply (clarsimp simp: cte_wp_at_ctes_of descendants_range'_def2 empty_descendants_range_in' capAligned_def sch_act_simple_def) apply (strengthen refl) apply (frule ctes_of_valid[OF ctes_of_cte_wpD], clarsimp+) apply (frule if_unsafe_then_capD'[OF ctes_of_cte_wpD], clarsimp+) apply (erule rev_mp[where P="Ball S f" for S f] rev_mp[where P="ex_cte_cap_wp_to' P p s" for P p s])+ apply (strengthen descendants_range_ex_cte'[rotated, OF _ order_refl, mk_strg D _ E]) apply (clarsimp simp: isCap_simps empty_descendants_range_in') apply auto[1] apply (cases "dev \<or> sz < resetChunkBits") apply (simp add: pred_conj_def unless_def) apply (rule hoare_pre) apply (strengthen exI[where x=sz]) apply (wp updateFreeIndex_clear_invs' hoare_vcg_ex_lift hoare_vcg_const_Ball_lift updateFreeIndex_descendants_of2 sch_act_simple_lift pspace_no_overlap'_lift doMachineOp_psp_no_overlap updateFreeIndex_ctes_of updateFreeIndex_cte_wp_at | simp | wps | wp (once) ex_cte_cap_to'_pres)+ apply (clarsimp simp: cte_wp_at_ctes_of isCap_simps modify_map_def) apply auto[1] apply simp apply (rule hoare_pre, rule hoare_post_impErr, rule_tac P="\<lambda>i. invs' and ?psp and ct_active' and valid_untyped_inv_wcap' ?ui (Some (UntypedCap dev ptr sz (if i = 0 then idx else (length [ptr , ptr + 2 ^ resetChunkBits .e. getFreeRef ptr idx - 1] - i) * 2 ^ resetChunkBits)))" and E="\<lambda>_. invs'" in mapME_x_validE_nth) apply (rule hoare_pre) apply simp apply (wp preemptionPoint_invs updateFreeIndex_clear_invs' hoare_vcg_ex_lift updateFreeIndex_descendants_of2 updateFreeIndex_ctes_of updateFreeIndex_cte_wp_at doMachineOp_psp_no_overlap hoare_vcg_ex_lift hoare_vcg_const_Ball_lift pspace_no_overlap'_lift[OF preemptionPoint_inv] pspace_no_overlap'_lift updateFreeIndex_ct_in_state[unfolded ct_in_state'_def] | strengthen invs_pspace_aligned' invs_pspace_distinct' | simp add: ct_in_state'_def sch_act_simple_def | rule hoare_vcg_conj_lift_R | wp (once) preemptionPoint_inv | wps | wp (once) ex_cte_cap_to'_pres)+ apply (clarsimp simp: cte_wp_at_ctes_of isCap_simps conj_comms) apply (subgoal_tac "getFreeIndex ptr (rev [ptr , ptr + 2 ^ resetChunkBits .e. getFreeRef ptr idx - 1] ! i) = (length [ptr , ptr + 2 ^ resetChunkBits .e. getFreeRef ptr idx - 1] - Suc i) * 2 ^ resetChunkBits") apply clarsimp apply (frule ctes_of_valid[OF ctes_of_cte_wpD], clarsimp+) apply (subgoal_tac "resetChunkBits < word_bits \<and> sz < word_bits") apply (strengthen is_aligned_weaken[OF is_aligned_mult_triv2]) apply (subst nat_less_power_trans2[THEN order_less_imp_le]) apply (clarsimp simp add: upto_enum_step_def getFreeRef_def) apply (rule less_imp_diff_less) apply (simp add: unat_div td_gal_lt[symmetric] power_add[symmetric]) apply (cases "idx = 0") apply (simp add: gt0_iff_gem1[symmetric, folded word_neq_0_conv]) apply (simp add: valid_cap_simps') apply (subst unat_minus_one) apply (clarsimp simp: valid_cap_simps') apply (drule of_nat64_0) apply (erule order_le_less_trans, simp) apply simp apply (clarsimp simp: unat_of_nat valid_cap_simps') apply (erule order_less_le_trans[rotated], simp) apply simp apply (auto simp: Kernel_Config.resetChunkBits_def minUntypedSizeBits_def)[1] apply (simp add: valid_cap_simps' Kernel_Config.resetChunkBits_def capAligned_def) apply (simp add: nth_rev) apply (simp add: upto_enum_step_def upto_enum_word getFreeIndex_def getFreeRef_def del: upt.simps) apply (intro conjI impI, simp_all)[1] apply (subgoal_tac "resetChunkBits < word_bits") apply (rule word_unat.Abs_eqD[OF _ word_unat.Rep]) apply (simp add: word_of_nat_plus Abs_fnat_hom_mult[symmetric]) apply (simp only: unats_def word_bits_def[symmetric]) apply (clarsimp simp: unat_div nat_mult_power_less_eq) apply (rule less_imp_diff_less) apply (simp add: td_gal_lt[symmetric] power_add[symmetric]) apply (simp only: unat_lt2p word_bits_def) apply (simp add: Kernel_Config.resetChunkBits_def word_bits_def) apply (clarsimp simp: cte_wp_at_ctes_of getFreeRef_def upto_enum_step_def upto_enum_word) apply (frule cte_wp_at_valid_objs_valid_cap'[OF ctes_of_cte_wpD], clarsimp+) apply (clarsimp simp: valid_cap_simps' capAligned_def) apply (simp add: reset_ineq_eq_idx_0) apply simp apply clarsimp done end lemma whenE_reset_resetUntypedCap_invs_etc: "\<lbrace>invs' and valid_untyped_inv_wcap' ui (Some (UntypedCap dev ptr sz idx)) and ct_active' and K (\<exists>ptr_base ty us slots. ui = Retype slot reset ptr_base ptr' ty us slots dev)\<rbrace> whenE reset (resetUntypedCap slot) \<lbrace>\<lambda>_. invs' and valid_untyped_inv_wcap' ui (Some (UntypedCap dev ptr sz (if reset then 0 else idx))) and ct_active' and pspace_no_overlap' (if reset then ptr else ptr') sz\<rbrace>, \<lbrace>\<lambda>_. invs'\<rbrace>" apply (rule hoare_pre) apply (wp whenE_wp resetUntypedCap_invs_etc[where idx=idx, simplified pred_conj_def conj_assoc] | simp)+ apply (clarsimp simp: cte_wp_at_ctes_of) apply (frule cte_wp_at_valid_objs_valid_cap'[OF ctes_of_cte_wpD], clarsimp+) apply (clarsimp simp: valid_cap_simps' capAligned_def) apply (drule_tac cref=slot in cte_wp_at_pspace_no_overlapI', simp add: cte_wp_at_ctes_of, simp+) done crunch ksCurDomain[wp]: updateFreeIndex "\<lambda>s. P (ksCurDomain s)" lemma (in range_cover) funky_aligned: "is_aligned ((ptr && foo) + v * 2 ^ sbit) sbit" apply (rule aligned_add_aligned) apply (rule is_aligned_andI1) apply (rule aligned) apply (rule is_aligned_mult_triv2) apply simp done context begin interpretation Arch . (*FIXME: arch_split*) lemma inv_untyped_corres': "\<lbrakk> untypinv_relation ui ui' \<rbrakk> \<Longrightarrow> corres (dc \<oplus> (=)) (einvs and valid_untyped_inv ui and ct_active) (invs' and valid_untyped_inv' ui' and ct_active') (invoke_untyped ui) (invokeUntyped ui')" apply (cases ui) apply (rule corres_name_pre) apply (clarsimp simp only: valid_untyped_inv_wcap valid_untyped_inv_wcap' Invocations_A.untyped_invocation.simps Invocations_H.untyped_invocation.simps untypinv_relation.simps) apply (rename_tac cref oref reset ptr ptr' dc us slots dev s s' ao' sz sz' idx idx') proof - fix cref reset ptr ptr_base us slots dev ao' sz sz' idx idx' s s' let ?ui = "Invocations_A.Retype cref reset ptr_base ptr (APIType_map2 (Inr ao')) us slots dev" let ?ui' = "Invocations_H.untyped_invocation.Retype (cte_map cref) reset ptr_base ptr ao' us (map cte_map slots) dev" assume invs: "invs (s :: det_state)" "ct_active s" "valid_list s" "valid_sched s" and invs': "invs' s'" "ct_active' s'" and sr: "(s, s') \<in> state_relation" and vui: "valid_untyped_inv_wcap ?ui (Some (cap.UntypedCap dev (ptr && ~~ mask sz) sz idx)) s" (is "valid_untyped_inv_wcap _ (Some ?cap) s") and vui': "valid_untyped_inv_wcap' ?ui' (Some (UntypedCap dev (ptr && ~~ mask sz') sz' idx')) s'" assume ui: "ui = ?ui" and ui': "ui' = ?ui'" have cte_at: "cte_wp_at ((=) ?cap) cref s" (is "?cte_cond s") using vui by (simp add:cte_wp_at_caps_of_state) have ptr_sz_simp[simp]: "ptr_base = ptr && ~~ mask sz \<and> sz' = sz \<and> idx' = idx \<and> 2 \<le> sz" using cte_at vui vui' sr invs apply (clarsimp simp: cte_wp_at_ctes_of) apply (drule pspace_relation_cte_wp_atI'[OF state_relation_pspace_relation]) apply (simp add:cte_wp_at_ctes_of) apply (simp add:invs_valid_objs) apply (clarsimp simp:is_cap_simps isCap_simps) apply (frule cte_map_inj_eq) apply ((erule cte_wp_at_weakenE | simp | clarsimp simp: cte_wp_at_caps_of_state)+)[5] apply (clarsimp simp:cte_wp_at_caps_of_state cte_wp_at_ctes_of) apply (drule caps_of_state_valid_cap,fastforce) apply (clarsimp simp:valid_cap_def untyped_min_bits_def) done have obj_bits_low_bound[simp]: "minUntypedSizeBits \<le> obj_bits_api (APIType_map2 (Inr ao')) us" using vui apply clarsimp apply (cases ao') apply (simp_all add: obj_bits_api_def slot_bits_def arch_kobj_size_def default_arch_object_def APIType_map2_def bit_simps untyped_min_bits_def minUntypedSizeBits_def split: apiobject_type.splits) done have cover: "range_cover ptr sz (obj_bits_api (APIType_map2 (Inr ao')) us) (length slots)" and vslot: "slots\<noteq> []" using vui by (auto simp: cte_wp_at_caps_of_state) have misc'[simp]: "distinct (map cte_map slots)" using vui' by (auto simp: cte_wp_at_ctes_of) have intvl_eq[simp]: "ptr && ~~ mask sz = ptr \<Longrightarrow> {ptr + of_nat k |k. k < 2 ^ sz} = {ptr..ptr + 2 ^ sz - 1}" using cover apply (subgoal_tac "is_aligned (ptr &&~~ mask sz) sz") apply (rule intvl_range_conv) apply (simp) apply (drule range_cover.sz) apply simp apply (rule is_aligned_neg_mask,simp) done have delete_objects_rewrite: "ptr && ~~ mask sz = ptr \<Longrightarrow> delete_objects ptr sz = do y \<leftarrow> modify (clear_um {ptr + of_nat k |k. k < 2 ^ sz}); modify (detype {ptr && ~~ mask sz..ptr + 2 ^ sz - 1}) od" using cover apply (clarsimp simp:delete_objects_def freeMemory_def word_size_def) apply (subgoal_tac "is_aligned (ptr &&~~ mask sz) sz") apply (subst mapM_storeWord_clear_um[simplified word_size_def word_size_bits_def]; clarsimp simp: range_cover_def word_bits_def) apply (drule_tac z=sz in order_trans[OF obj_bits_low_bound]; simp add: minUntypedSizeBits_def) apply (rule is_aligned_neg_mask) apply simp done have of_nat_length: "(of_nat (length slots)::machine_word) - (1::machine_word) < (of_nat (length slots)::machine_word)" using vslot using range_cover.range_cover_le_n_less(1)[OF cover,where p = "length slots"] apply - apply (case_tac slots) apply clarsimp+ apply (subst add.commute) apply (subst word_le_make_less[symmetric]) apply (rule less_imp_neq) apply (simp add:word_bits_def minus_one_norm) apply (rule word_of_nat_less) apply auto done have not_0_ptr[simp]: "ptr\<noteq> 0" using cte_at invs apply (clarsimp simp:cte_wp_at_caps_of_state) apply (drule(1) caps_of_state_valid)+ apply (simp add:valid_cap_def) done have size_eq[simp]: "APIType_capBits ao' us = obj_bits_api (APIType_map2 (Inr ao')) us" apply (case_tac ao') apply (rename_tac apiobject_type) apply (case_tac apiobject_type) apply (clarsimp simp: APIType_capBits_def objBits_simps' arch_kobj_size_def default_arch_object_def obj_bits_api_def APIType_map2_def slot_bits_def pageBitsForSize_def bit_simps)+ done have non_reset_idx_le[simp]: "\<not> reset \<Longrightarrow> idx < 2^sz" using vui apply (clarsimp simp: cte_wp_at_caps_of_state ) apply (erule le_less_trans) apply (rule unat_less_helper) apply simp apply (rule and_mask_less') using cover apply (clarsimp simp:range_cover_def) done note blah[simp del] = untyped_range.simps usable_untyped_range.simps atLeastAtMost_iff atLeastatMost_subset_iff atLeastLessThan_iff Int_atLeastAtMost atLeastatMost_empty_iff split_paired_Ex usableUntypedRange.simps have vc'[simp] : "s' \<turnstile>' capability.UntypedCap dev (ptr && ~~ mask sz) sz idx" using vui' invs' apply (clarsimp simp:cte_wp_at_ctes_of) apply (case_tac cte) apply clarsimp apply (erule ctes_of_valid_cap') apply (simp add:invs_valid_objs') done have nidx[simp]: "ptr + (of_nat (length slots) * 2^obj_bits_api (APIType_map2 (Inr ao')) us) - (ptr && ~~ mask sz) = (ptr && mask sz) + (of_nat (length slots) * 2^obj_bits_api (APIType_map2 (Inr ao')) us)" apply (subst word_plus_and_or_coroll2[symmetric,where w = "mask sz" and t = ptr]) apply simp done have idx_compare'[simp]:"unat ((ptr && mask sz) + (of_nat (length slots)<< obj_bits_api (APIType_map2 (Inr ao')) us)) \<le> 2 ^ sz" apply (rule le_trans[OF unat_plus_gt]) apply (simp add:range_cover.unat_of_nat_n_shift[OF cover] range_cover_unat) apply (insert range_cover.range_cover_compare_bound[OF cover]) apply simp done have idx_compare''[simp]: "unat ((ptr && mask sz) + (of_nat (length slots) * (2::machine_word) ^ obj_bits_api (APIType_map2 (Inr ao')) us)) < 2 ^ sz \<Longrightarrow> ptr + of_nat (length slots) * 2 ^ obj_bits_api (APIType_map2 (Inr ao')) us - 1 < ptr + of_nat (length slots) * 2 ^ obj_bits_api (APIType_map2 (Inr ao')) us" apply (rule word_leq_le_minus_one,simp) apply (rule neq_0_no_wrap) apply (rule machine_word_plus_mono_right_split) apply (simp add:shiftl_t2n range_cover_unat[OF cover] field_simps) apply (simp add:range_cover.sz[where 'a=machine_word_len, folded word_bits_def, OF cover])+ done note neg_mask_add_mask = word_plus_and_or_coroll2[symmetric,where w = "mask sz" and t = ptr,symmetric] have idx_compare'''[simp]: "\<lbrakk>unat (of_nat (length slots) * (2::machine_word) ^ obj_bits_api (APIType_map2 (Inr ao')) us) < 2 ^ sz; ptr && ~~ mask sz = ptr\<rbrakk> \<Longrightarrow> ptr + of_nat (length slots) * 2 ^ obj_bits_api (APIType_map2 (Inr ao')) us - 1 < ptr + of_nat (length slots) * 2 ^ obj_bits_api (APIType_map2 (Inr ao')) us " apply (rule word_leq_le_minus_one,simp) apply (simp add:is_aligned_neg_mask_eq'[symmetric]) apply (rule neq_0_no_wrap) apply (rule machine_word_plus_mono_right_split[where sz = sz]) apply (simp add:is_aligned_mask)+ apply (simp add:range_cover.sz[where 'a=machine_word_len, folded word_bits_def, OF cover])+ done have maxDomain:"ksCurDomain s' \<le> maxDomain" using invs' by (simp add:invs'_def valid_state'_def) have sz_mask_less: "unat (ptr && mask sz) < 2 ^ sz" using range_cover.sz[OF cover] by (simp add: unat_less_helper and_mask_less_size word_size) have overlap_ranges1: "{x. ptr \<le> x \<and> x \<le> ptr + 2 ^ obj_bits_api (APIType_map2 (Inr ao')) us * of_nat (length slots) - 1} \<subseteq> {ptr .. (ptr && ~~ mask sz) + 2 ^ sz - 1}" apply (rule order_trans[rotated]) apply (rule range_cover_subset'[OF cover], simp add: vslot) apply (clarsimp simp: atLeastAtMost_iff field_simps) done have overlap_ranges2: "idx \<le> unat (ptr && mask sz) \<Longrightarrow> {x. ptr \<le> x \<and> x \<le> ptr + 2 ^ obj_bits_api (APIType_map2 (Inr ao')) us * of_nat (length slots) - 1} \<subseteq> {(ptr && ~~ mask sz) + of_nat idx..(ptr && ~~ mask sz) + 2 ^ sz - 1}" apply (rule order_trans[OF overlap_ranges1]) apply (clarsimp simp add: atLeastatMost_subset_iff) apply (rule order_trans, rule word_plus_mono_right) apply (erule word_of_nat_le) apply (simp add: add.commute word_plus_and_or_coroll2 word_and_le2) apply (simp add: add.commute word_plus_and_or_coroll2) done have overlap_ranges: "{x. ptr \<le> x \<and> x \<le> ptr + 2 ^ obj_bits_api (APIType_map2 (Inr ao')) us * of_nat (length slots) - 1} \<subseteq> usable_untyped_range (cap.UntypedCap dev (ptr && ~~ mask sz) sz (if reset then 0 else idx))" apply (cases reset, simp_all add: usable_untyped_range.simps) apply (rule order_trans, rule overlap_ranges1) apply (simp add: blah word_and_le2) apply (rule overlap_ranges2) apply (cut_tac vui) apply (clarsimp simp: cte_wp_at_caps_of_state) done have ptr_cn[simp]: "canonical_address (ptr && ~~ mask sz)" using vc' unfolding valid_cap'_def by clarsimp have ptr_km[simp]: "ptr && ~~ mask sz \<in> kernel_mappings" using vc' unfolding valid_cap'_def by clarsimp have sz_limit[simp]: "sz \<le> maxUntypedSizeBits" using vc' unfolding valid_cap'_def by clarsimp note set_cap_free_index_invs_spec = set_free_index_invs[where cap = "cap.UntypedCap dev (ptr && ~~ mask sz) sz (if reset then 0 else idx)" ,unfolded free_index_update_def free_index_of_def,simplified] note msimp[simp add] = neg_mask_add_mask note if_split[split del] show " corres (dc \<oplus> (=)) ((=) s) ((=) s') (invoke_untyped ?ui) (invokeUntyped ?ui')" apply (clarsimp simp:invokeUntyped_def invoke_untyped_def getSlotCap_def bind_assoc) apply (insert cover) apply (rule corres_guard_imp) apply (rule corres_split_norE) apply (rule corres_whenE, simp) apply (rule resetUntypedCap_corres[where ui=ui and ui'=ui']) apply (simp add: ui ui') apply simp apply simp apply (rule corres_symb_exec_l_Ex) apply (rule_tac F = "cap = cap.UntypedCap dev (ptr && ~~ mask sz) sz (if reset then 0 else idx)" in corres_gen_asm) apply (rule corres_add_noop_lhs) apply (rule corres_split_nor[OF cNodeNoOverlap _ return_wp stateAssert_wp]) apply (rule corres_split[OF updateFreeIndex_corres]) apply (simp add:isCap_simps)+ apply (clarsimp simp:getFreeIndex_def bits_of_def shiftL_nat shiftl_t2n free_index_of_def) apply (insert range_cover.range_cover_n_less[OF cover] vslot) apply (rule createNewObjects_corres_helper) apply simp+ apply (simp add: insertNewCaps_def) apply (rule corres_split_retype_createNewCaps[where sz = sz,OF corres_rel_imp]) apply (rule inv_untyped_corres_helper1) apply simp apply simp apply ((wp retype_region_invs_extras[where sz = sz] retype_region_plain_invs [where sz = sz] retype_region_descendants_range_ret[where sz = sz] retype_region_caps_overlap_reserved_ret[where sz = sz] retype_region_cte_at_other[where sz = sz] retype_region_distinct_sets[where sz = sz] retype_region_ranges[where p=cref and sz = sz] retype_ret_valid_caps [where sz = sz] retype_region_arch_objs [where sza = "\<lambda>_. sz"] hoare_vcg_const_Ball_lift set_tuple_pick distinct_tuple_helper retype_region_obj_at_other3[where sz = sz] | assumption)+)[1] apply (wp set_tuple_pick createNewCaps_cte_wp_at'[where sz= sz] hoare_vcg_ex_lift distinct_tuple_helper createNewCaps_parent_helper [where p="cte_map cref" and sz = sz] createNewCaps_valid_pspace_extras [where ptr=ptr and sz = sz] createNewCaps_ranges'[where sz = sz] hoare_vcg_const_Ball_lift createNewCaps_valid_cap'[where sz = sz] createNewCaps_descendants_range_ret'[where sz = sz] createNewCaps_caps_overlap_reserved_ret'[where sz = sz]) apply clarsimp apply (erule cte_wp_at_weakenE') apply (case_tac c, simp) apply hypsubst apply (case_tac c,clarsimp simp:isCap_simps) apply (clarsimp simp: getFreeIndex_def is_cap_simps bits_of_def shiftL_nat) apply (clarsimp simp:conj_comms) apply (strengthen invs_mdb invs_valid_objs invs_valid_pspace invs_arch_state invs_psp_aligned caps_region_kernel_window_imp[where p=cref] invs_cap_refs_in_kernel_window)+ apply (clarsimp simp:conj_comms bits_of_def) apply (wp set_cap_free_index_invs_spec set_cap_caps_no_overlap set_cap_no_overlap) apply (rule hoare_vcg_conj_lift) apply (rule hoare_strengthen_post[OF set_cap_sets]) apply (clarsimp simp:cte_wp_at_caps_of_state) apply (wp set_cap_no_overlap hoare_vcg_ball_lift set_cap_free_index_invs_spec set_cap_descendants_range_in set_untyped_cap_caps_overlap_reserved[where idx="if reset then 0 else idx"] set_cap_cte_wp_at | strengthen exI[where x=cref])+ apply (clarsimp simp:conj_comms ball_conj_distrib simp del:capFreeIndex_update.simps) apply (strengthen invs_pspace_aligned' invs_pspace_distinct' invs_valid_pspace' invs_arch_state' imp_consequent[where Q = "(\<exists>x. x \<in> cte_map ` set slots)"] | clarsimp simp: conj_comms simp del: capFreeIndex_update.simps)+ apply ((wp updateFreeIndex_forward_invs' updateFreeIndex_caps_overlap_reserved updateFreeIndex_caps_no_overlap'' updateFreeIndex_pspace_no_overlap' hoare_vcg_const_Ball_lift updateFreeIndex_cte_wp_at updateFreeIndex_descendants_range_in')+)[1] apply clarsimp apply (clarsimp simp:conj_comms) apply (strengthen invs_mdb invs_valid_objs invs_valid_pspace invs_arch_state invs_psp_aligned invs_distinct) apply (clarsimp simp:conj_comms ball_conj_distrib ex_in_conv) apply ((rule validE_R_validE)?, rule_tac Q'="\<lambda>_ s. valid_etcbs s \<and> valid_list s \<and> invs s \<and> ct_active s \<and> valid_untyped_inv_wcap ui (Some (cap.UntypedCap dev (ptr && ~~ mask sz) sz (if reset then 0 else idx))) s \<and> (reset \<longrightarrow> pspace_no_overlap {ptr && ~~ mask sz..(ptr && ~~ mask sz) + 2 ^ sz - 1} s) " in hoare_post_imp_R) apply (simp add: whenE_def split del: if_split, wp) apply (rule validE_validE_R, rule hoare_post_impErr, rule reset_untyped_cap_invs_etc, auto)[1] apply wp apply (clarsimp simp: ui cte_wp_at_caps_of_state bits_of_def untyped_range.simps) apply (frule(1) valid_global_refsD2[OF _ invs_valid_global_refs]) apply (cut_tac cref="cref" and reset=reset in invoke_untyped_proofs.intro, simp_all add: cte_wp_at_caps_of_state)[1] apply (rule conjI, (assumption | rule refl))+ apply (simp split: if_split) apply (simp add: invoke_untyped_proofs.simps) apply (strengthen if_split[where P="\<lambda>v. v \<le> unat x" for x, THEN iffD2] exI[where x=cref]) apply (simp add: arg_cong[OF mask_out_sub_mask, where f="\<lambda>y. x - y" for x] field_simps invoke_untyped_proofs.idx_le_new_offs if_split[where P="\<lambda>v. v \<le> unat x" for x]) apply (frule range_cover.sz(1), fold word_bits_def) apply (frule cte_wp_at_pspace_no_overlapI, simp add: cte_wp_at_caps_of_state, simp split: if_split, simp add: invoke_untyped_proofs.szw) apply (simp add: field_simps conj_comms ex_in_conv cte_wp_at_caps_of_state in_get_cap_cte_wp_at atLeastatMost_subset_iff[where b=x and d=x for x] word_and_le2) apply (intro conjI impI) (* offs *) apply (drule(1) invoke_untyped_proofs.idx_le_new_offs) apply simp (* usable untyped range *) apply (simp add: shiftL_nat shiftl_t2n overlap_ranges) apply (rule order_trans, erule invoke_untyped_proofs.subset_stuff) apply (simp add: blah word_and_le2) apply (drule invoke_untyped_proofs.usable_range_disjoint) apply (clarsimp simp: field_simps mask_out_sub_mask shiftl_t2n) apply ((rule validE_validE_R)?, rule hoare_post_impErr, rule whenE_reset_resetUntypedCap_invs_etc[where ptr="ptr && ~~ mask sz" and ptr'=ptr and sz=sz and idx=idx and ui=ui' and dev=dev]) prefer 2 apply simp apply clarsimp apply (simp only: ui') apply (frule(2) invokeUntyped_proofs.intro) apply (clarsimp simp: cte_wp_at_ctes_of invokeUntyped_proofs.caps_no_overlap' invokeUntyped_proofs.ps_no_overlap' invokeUntyped_proofs.descendants_range if_split[where P="\<lambda>v. v \<le> getFreeIndex x y" for x y] empty_descendants_range_in' invs_pspace_aligned' invs_pspace_distinct' invs_ksCurDomain_maxDomain' cong: if_cong) apply (strengthen refl) apply (frule invokeUntyped_proofs.idx_le_new_offs) apply (frule invokeUntyped_proofs.szw) apply (frule invokeUntyped_proofs.descendants_range(2), simp) apply (clarsimp simp: getFreeIndex_def conj_comms shiftL_nat is_aligned_weaken[OF range_cover.funky_aligned] invs_valid_pspace' isCap_simps arg_cong[OF mask_out_sub_mask, where f="\<lambda>y. x - y" for x] field_simps) apply (intro conjI) (* pspace_no_overlap' *) apply (cases reset, simp_all)[1] apply (rule order_trans[rotated], erule invokeUntyped_proofs.idx_compare') apply (simp add: shiftl_t2n mult.commute) apply (drule invokeUntyped_proofs.subset_stuff, simp, erule order_trans, simp add: blah word_and_le2) apply (auto split: if_split)[1] apply (drule invokeUntyped_proofs.usableRange_disjoint, simp) apply (clarsimp simp only: pred_conj_def invs ui) apply (strengthen vui) apply (cut_tac vui invs invs') apply (clarsimp simp: cte_wp_at_caps_of_state valid_sched_etcbs) apply (cut_tac vui' invs') apply (clarsimp simp: ui cte_wp_at_ctes_of if_apply_def2 ui') done qed lemmas inv_untyped_corres = inv_untyped_corres' crunch pred_tcb_at'[wp]: insertNewCap "pred_tcb_at' proj P t" (wp: crunch_wps) crunch pred_tcb_at'[wp]: doMachineOp "pred_tcb_at' proj P t" (wp: crunch_wps) crunch irq_node[wp]: set_thread_state "\<lambda>s. P (interrupt_irq_node s)" crunch ctes_of [wp]: setQueue "\<lambda>s. P (ctes_of s)" crunch cte_wp_at [wp]: setQueue "cte_wp_at' P p" (simp: cte_wp_at_ctes_of) lemma sts_valid_untyped_inv': "\<lbrace>valid_untyped_inv' ui\<rbrace> setThreadState st t \<lbrace>\<lambda>rv. valid_untyped_inv' ui\<rbrace>" apply (cases ui, simp add: ex_cte_cap_to'_def) apply (rule hoare_pre) apply (rule hoare_use_eq_irq_node' [OF setThreadState_ksInterruptState]) apply (wp hoare_vcg_const_Ball_lift hoare_vcg_ex_lift | simp)+ done crunch nosch[wp]: invokeUntyped "\<lambda>s. P (ksSchedulerAction s)" (simp: crunch_simps zipWithM_x_mapM wp: crunch_wps unless_wp mapME_x_inv_wp preemptionPoint_inv) crunch no_0_obj'[wp]: insertNewCap no_0_obj' (wp: crunch_wps) lemma insertNewCap_valid_pspace': "\<lbrace>\<lambda>s. valid_pspace' s \<and> s \<turnstile>' cap \<and> slot \<noteq> parent \<and> caps_overlap_reserved' (untypedRange cap) s \<and> cte_wp_at' (\<lambda>cte. isUntypedCap (cteCap cte) \<and> sameRegionAs (cteCap cte) cap) parent s \<and> \<not> isZombie cap \<and> descendants_range' cap parent (ctes_of s)\<rbrace> insertNewCap parent slot cap \<lbrace>\<lambda>rv. valid_pspace'\<rbrace>" apply (simp add: valid_pspace'_def) apply (wp insertNewCap_valid_mdb) apply simp_all done crunch tcb'[wp]: insertNewCap "tcb_at' t" (wp: crunch_wps) crunch inQ[wp]: insertNewCap "obj_at' (inQ d p) t" (wp: crunch_wps) crunch norqL1[wp]: insertNewCap "\<lambda>s. P (ksReadyQueuesL1Bitmap s)" (wp: crunch_wps) crunch norqL2[wp]: insertNewCap "\<lambda>s. P (ksReadyQueuesL2Bitmap s)" (wp: crunch_wps) crunch ct[wp]: insertNewCap "\<lambda>s. P (ksCurThread s)" (wp: crunch_wps) crunch state_refs_of'[wp]: insertNewCap "\<lambda>s. P (state_refs_of' s)" (wp: crunch_wps) crunch cteCaps[wp]: updateNewFreeIndex "\<lambda>s. P (cteCaps_of s)" crunch if_unsafe_then_cap'[wp]: updateNewFreeIndex "if_unsafe_then_cap'" lemma insertNewCap_ifunsafe'[wp]: "\<lbrace>if_unsafe_then_cap' and ex_cte_cap_to' slot\<rbrace> insertNewCap parent slot cap \<lbrace>\<lambda>rv s. if_unsafe_then_cap' s\<rbrace>" apply (simp add: insertNewCap_def) apply (rule hoare_pre) apply (wp getCTE_wp' | clarsimp simp: ifunsafe'_def3)+ apply (clarsimp simp: ex_cte_cap_to'_def cte_wp_at_ctes_of cteCaps_of_def) apply (drule_tac x=cref in spec) apply (rule conjI) apply clarsimp apply (rule_tac x=crefa in exI, fastforce) apply clarsimp apply (rule_tac x=cref' in exI, fastforce) done crunch if_live_then_nonz_cap'[wp]: updateNewFreeIndex "if_live_then_nonz_cap'" lemma insertNewCap_iflive'[wp]: "\<lbrace>if_live_then_nonz_cap'\<rbrace> insertNewCap parent slot cap \<lbrace>\<lambda>rv. if_live_then_nonz_cap'\<rbrace>" apply (simp add: insertNewCap_def) apply (wp setCTE_iflive' getCTE_wp') apply (clarsimp elim!: cte_wp_at_weakenE') done lemma insertNewCap_cte_wp_at'': "\<lbrace>cte_wp_at' (\<lambda>cte. P (cteCap cte)) p and K (\<not> P NullCap)\<rbrace> insertNewCap parent slot cap \<lbrace>\<lambda>rv s. cte_wp_at' (P \<circ> cteCap) p s\<rbrace>" apply (simp add: insertNewCap_def tree_cte_cteCap_eq) apply (wp getCTE_wp') apply (clarsimp simp: cte_wp_at_ctes_of cteCaps_of_def) done lemmas insertNewCap_cte_wp_at' = insertNewCap_cte_wp_at''[unfolded o_def] lemma insertNewCap_cap_to'[wp]: "\<lbrace>ex_cte_cap_to' p\<rbrace> insertNewCap parent slot cap \<lbrace>\<lambda>rv. ex_cte_cap_to' p\<rbrace>" apply (simp add: ex_cte_cap_to'_def) apply (rule hoare_pre) apply (rule hoare_use_eq_irq_node'[OF insertNewCap_ksInterrupt]) apply (wp hoare_vcg_ex_lift insertNewCap_cte_wp_at') apply clarsimp done lemma insertNewCap_nullcap: "\<lbrace>P and cte_wp_at' (\<lambda>cte. cteCap cte = NullCap) slot\<rbrace> insertNewCap parent slot cap \<lbrace>Q\<rbrace> \<Longrightarrow> \<lbrace>P\<rbrace> insertNewCap parent slot cap \<lbrace>Q\<rbrace>" apply (clarsimp simp: valid_def) apply (subgoal_tac "cte_wp_at' (\<lambda>cte. cteCap cte = NullCap) slot s") apply fastforce apply (clarsimp simp: insertNewCap_def in_monad cte_wp_at_ctes_of liftM_def dest!: use_valid [OF _ getCTE_sp[where P="(=) s" for s], OF _ refl]) done crunch idle'[wp]: insertNewCap "valid_idle'" (wp: getCTE_wp') crunch global_refs': insertNewCap "\<lambda>s. P (global_refs' s)" (wp: crunch_wps simp: crunch_simps) crunch gsMaxObjectSize[wp]: insertNewCap "\<lambda>s. P (gsMaxObjectSize s)" (wp: crunch_wps simp: crunch_simps) lemma insertNewCap_valid_global_refs': "\<lbrace>valid_global_refs' and cte_wp_at' (\<lambda>cte. capRange cap \<subseteq> capRange (cteCap cte) \<and> capBits cap \<le> capBits (cteCap cte)) parent\<rbrace> insertNewCap parent slot cap \<lbrace>\<lambda>rv. valid_global_refs'\<rbrace>" apply (simp add: valid_global_refs'_def valid_refs'_cteCaps valid_cap_sizes_cteCaps) apply (rule hoare_pre) apply (rule hoare_use_eq [where f=global_refs', OF insertNewCap_global_refs']) apply (rule hoare_use_eq [where f=gsMaxObjectSize]) apply wp+ apply (clarsimp simp: cte_wp_at_ctes_of cteCaps_of_def ball_ran_eq) apply (frule power_increasing[where a=2], simp) apply (blast intro: order_trans) done lemma insertNewCap_valid_irq_handlers: "\<lbrace>valid_irq_handlers' and (\<lambda>s. \<forall>irq. cap = IRQHandlerCap irq \<longrightarrow> irq_issued' irq s)\<rbrace> insertNewCap parent slot cap \<lbrace>\<lambda>rv. valid_irq_handlers'\<rbrace>" apply (simp add: insertNewCap_def valid_irq_handlers'_def irq_issued'_def) apply (wp | wp (once) hoare_use_eq[where f=ksInterruptState, OF updateNewFreeIndex_ksInterrupt])+ apply (simp add: cteCaps_of_def) apply (wp | wp (once) hoare_use_eq[where f=ksInterruptState, OF setCTE_ksInterruptState] getCTE_wp)+ apply (clarsimp simp: cteCaps_of_def cte_wp_at_ctes_of ran_def) apply auto done crunch ioports[wp]: updateNewFreeIndex "valid_ioports'" lemma insertNewCap_ioports': "\<lbrace>valid_ioports' and safe_ioport_insert' cap NullCap\<rbrace> insertNewCap parent slot cap \<lbrace>\<lambda>rv. valid_ioports'\<rbrace>" apply (simp add: insertNewCap_def) apply (wpsimp wp: setCTE_ioports' getCTE_wp) by (clarsimp simp: cte_wp_at_ctes_of) crunch irq_states' [wp]: insertNewCap valid_irq_states' (wp: getCTE_wp') crunch vq'[wp]: insertNewCap valid_queues' (wp: crunch_wps) crunch irqs_masked' [wp]: insertNewCap irqs_masked' (wp: crunch_wps rule: irqs_masked_lift) crunch valid_machine_state'[wp]: insertNewCap valid_machine_state' (wp: crunch_wps) crunch pspace_domain_valid[wp]: insertNewCap pspace_domain_valid (wp: crunch_wps) crunch ct_not_inQ[wp]: insertNewCap "ct_not_inQ" (wp: crunch_wps) crunch tcbState_inv[wp]: insertNewCap "obj_at' (\<lambda>tcb. P (tcbState tcb)) t" (wp: crunch_simps hoare_drop_imps) crunch tcbDomain_inv[wp]: insertNewCap "obj_at' (\<lambda>tcb. P (tcbDomain tcb)) t" (wp: crunch_simps hoare_drop_imps) crunch tcbPriority_inv[wp]: insertNewCap "obj_at' (\<lambda>tcb. P (tcbPriority tcb)) t" (wp: crunch_simps hoare_drop_imps) lemma insertNewCap_ct_idle_or_in_cur_domain'[wp]: "\<lbrace>ct_idle_or_in_cur_domain' and ct_active'\<rbrace> insertNewCap parent slot cap \<lbrace>\<lambda>_. ct_idle_or_in_cur_domain'\<rbrace>" apply (wp ct_idle_or_in_cur_domain'_lift_futz[where Q=\<top>]) apply (rule_tac Q="\<lambda>_. obj_at' (\<lambda>tcb. tcbState tcb \<noteq> Structures_H.thread_state.Inactive) t and obj_at' (\<lambda>tcb. d = tcbDomain tcb) t" in hoare_strengthen_post) apply (wp | clarsimp elim: obj_at'_weakenE)+ apply (auto simp: obj_at'_def) done crunch ksDomScheduleIdx[wp]: insertNewCap "\<lambda>s. P (ksDomScheduleIdx s)" (wp: crunch_simps hoare_drop_imps) lemma capRange_subset_capBits: "capAligned cap \<Longrightarrow> capAligned cap' \<Longrightarrow> capRange cap \<subseteq> capRange cap' \<Longrightarrow> capRange cap \<noteq> {} \<Longrightarrow> capBits cap \<le> capBits cap'" supply is_aligned_neg_mask_eq[simp del] is_aligned_neg_mask_weaken[simp del] apply (simp add: capRange_def capAligned_def is_aligned_no_overflow split: if_split_asm del: atLeastatMost_subset_iff) apply (frule_tac c="capUntypedPtr cap" in subsetD) apply (simp only: mask_in_range[symmetric]) apply (simp add: is_aligned_neg_mask_eq) apply (drule_tac c="(capUntypedPtr cap && ~~ mask (capBits cap)) || (~~ capUntypedPtr cap' && mask (capBits cap))" in subsetD) apply (simp_all only: mask_in_range[symmetric]) apply (simp add: word_ao_dist is_aligned_neg_mask_eq) apply (simp add: word_ao_dist) apply (cases "capBits cap = 0") apply simp apply (drule_tac f="\<lambda>x. x !! (capBits cap - 1)" and x="a || b" for a b in arg_cong) apply (simp add: word_ops_nth_size word_bits_def word_size) apply auto done lemma insertNewCap_urz[wp]: "\<lbrace>untyped_ranges_zero' and valid_objs' and valid_mdb'\<rbrace> insertNewCap parent slot cap \<lbrace>\<lambda>rv. untyped_ranges_zero'\<rbrace>" apply (simp add: insertNewCap_def updateNewFreeIndex_def) apply (wp getCTE_cteCap_wp | simp add: updateTrackedFreeIndex_def getSlotCap_def case_eq_if_isUntypedCap split: option.split split del: if_split | wps | wp (once) getCTE_wp')+ apply (clarsimp simp: cte_wp_at_ctes_of fun_upd_def[symmetric]) apply (strengthen untyped_ranges_zero_fun_upd[mk_strg I E]) apply (intro conjI impI; clarsimp simp: isCap_simps) apply (auto simp add: cteCaps_of_def untypedZeroRange_def isCap_simps) done lemma safe_ioport_insert'_capRange: "capRange cap \<noteq> {} \<Longrightarrow> safe_ioport_insert' cap cap' s" apply (clarsimp simp: safe_ioport_insert'_def) apply (case_tac cap; clarsimp) by (rename_tac ac, case_tac ac; clarsimp simp: capRange_def) lemma insertNewCap_invs': "\<lbrace>invs' and ct_active' and valid_cap' cap and cte_wp_at' (\<lambda>cte. isUntypedCap (cteCap cte) \<and> sameRegionAs (cteCap cte) cap) parent and K (\<not> isZombie cap) and (\<lambda>s. descendants_range' cap parent (ctes_of s)) and caps_overlap_reserved' (untypedRange cap) and ex_cte_cap_to' slot and (\<lambda>s. ksIdleThread s \<notin> capRange cap) and (\<lambda>s. \<forall>irq. cap = IRQHandlerCap irq \<longrightarrow> irq_issued' irq s)\<rbrace> insertNewCap parent slot cap \<lbrace>\<lambda>rv. invs'\<rbrace>" apply (rule insertNewCap_nullcap) apply (simp add: invs'_def valid_state'_def) apply (rule hoare_pre) apply (wp insertNewCap_valid_pspace' sch_act_wf_lift valid_queues_lift cur_tcb_lift tcb_in_cur_domain'_lift insertNewCap_valid_global_refs' valid_arch_state_lift' insertNewCap_ioports' valid_irq_node_lift insertNewCap_valid_irq_handlers) apply (clarsimp simp: cte_wp_at_ctes_of) apply (frule ctes_of_valid[rotated, where p=parent, OF valid_pspace_valid_objs']) apply (fastforce simp: cte_wp_at_ctes_of) apply (auto simp: isCap_simps sameRegionAs_def3 intro!: capRange_subset_capBits safe_ioport_insert'_capRange elim: valid_capAligned) done lemma insertNewCap_irq_issued'[wp]: "\<lbrace>\<lambda>s. P (irq_issued' irq s)\<rbrace> insertNewCap parent slot cap \<lbrace>\<lambda>rv s. P (irq_issued' irq s)\<rbrace>" by (simp add: irq_issued'_def, wp) lemma insertNewCap_ct_in_state'[wp]: "\<lbrace>ct_in_state' p\<rbrace>insertNewCap parent slot cap \<lbrace>\<lambda>rv. ct_in_state' p\<rbrace>" unfolding ct_in_state'_def apply (rule hoare_pre) apply wps apply wp apply simp done lemma zipWithM_x_insertNewCap_invs'': "\<lbrace>\<lambda>s. invs' s \<and> ct_active' s \<and> (\<forall>tup \<in> set ls. s \<turnstile>' snd tup) \<and> cte_wp_at' (\<lambda>cte. isUntypedCap (cteCap cte) \<and> (\<forall>tup \<in> set ls. sameRegionAs (cteCap cte) (snd tup))) parent s \<and> (\<forall>tup \<in> set ls. \<not> isZombie (snd tup)) \<and> (\<forall>tup \<in> set ls. ex_cte_cap_to' (fst tup) s) \<and> (\<forall>tup \<in> set ls. descendants_range' (snd tup) parent (ctes_of s)) \<and> (\<forall>tup \<in> set ls. ksIdleThread s \<notin> capRange (snd tup)) \<and> (\<forall>tup \<in> set ls. caps_overlap_reserved' (capRange (snd tup)) s) \<and> distinct_sets (map capRange (map snd ls)) \<and> (\<forall>irq. IRQHandlerCap irq \<in> set (map snd ls) \<longrightarrow> irq_issued' irq s) \<and> distinct (map fst ls)\<rbrace> mapM (\<lambda>(x, y). insertNewCap parent x y) ls \<lbrace>\<lambda>rv. invs'\<rbrace>" apply (induct ls) apply (simp add: mapM_def sequence_def) apply (wp, simp) apply (simp add: mapM_Cons) including no_pre apply wp apply (thin_tac "valid P f Q" for P f Q) apply clarsimp apply (rule hoare_pre) apply (wp insertNewCap_invs' hoare_vcg_const_Ball_lift insertNewCap_cte_wp_at' insertNewCap_ranges hoare_vcg_all_lift insertNewCap_pred_tcb_at')+ apply (clarsimp simp: cte_wp_at_ctes_of invs_mdb' invs_valid_objs' dest!:valid_capAligned) apply (drule caps_overlap_reserved'_subseteq[OF _ untypedRange_in_capRange]) apply (auto simp:comp_def) done lemma createNewCaps_not_isZombie[wp]: "\<lbrace>\<top>\<rbrace> createNewCaps ty ptr bits sz d \<lbrace>\<lambda>rv s. (\<forall>cap \<in> set rv. \<not> isZombie cap)\<rbrace>" apply (simp add: createNewCaps_def toAPIType_def X64_H.toAPIType_def createNewCaps_def split del: if_split cong: option.case_cong if_cong apiobject_type.case_cong X64_H.object_type.case_cong) apply (rule hoare_pre) apply (wp undefined_valid | wpc | simp add: isCap_simps)+ apply auto? done lemma createNewCaps_cap_to': "\<lbrace>\<lambda>s. ex_cte_cap_to' p s \<and> 0 < n \<and> range_cover ptr sz (APIType_capBits ty us) n \<and> pspace_aligned' s \<and> pspace_distinct' s \<and> pspace_no_overlap' ptr sz s\<rbrace> createNewCaps ty ptr n us d \<lbrace>\<lambda>rv. ex_cte_cap_to' p\<rbrace>" apply (simp add: ex_cte_cap_to'_def) apply (wp hoare_vcg_ex_lift hoare_use_eq_irq_node' [OF createNewCaps_ksInterrupt createNewCaps_cte_wp_at']) apply fastforce done crunch it[wp]: copyGlobalMappings "\<lambda>s. P (ksIdleThread s)" (wp: mapM_x_wp' ignore: clearMemory) lemma createNewCaps_idlethread[wp]: "\<lbrace>\<lambda>s. P (ksIdleThread s)\<rbrace> createNewCaps tp ptr sz us d \<lbrace>\<lambda>rv s. P (ksIdleThread s)\<rbrace>" apply (simp add: createNewCaps_def toAPIType_def split: X64_H.object_type.split apiobject_type.split) apply safe apply (wp mapM_x_wp' | simp)+ done lemma createNewCaps_idlethread_ranges[wp]: "\<lbrace>\<lambda>s. 0 < n \<and> range_cover ptr sz (APIType_capBits tp us) n \<and> ksIdleThread s \<notin> {ptr .. (ptr && ~~ mask sz) + 2 ^ sz - 1}\<rbrace> createNewCaps tp ptr n us d \<lbrace>\<lambda>rv s. \<forall>cap\<in>set rv. ksIdleThread s \<notin> capRange cap\<rbrace>" apply (rule hoare_as_subst [OF createNewCaps_idlethread]) apply (rule hoare_assume_pre) apply (rule hoare_chain, rule createNewCaps_range_helper2) apply fastforce apply blast done lemma createNewCaps_IRQHandler[wp]: "\<lbrace>\<top>\<rbrace> createNewCaps tp ptr sz us d \<lbrace>\<lambda>rv s. IRQHandlerCap irq \<in> set rv \<longrightarrow> P rv s\<rbrace>" apply (simp add: createNewCaps_def split del: if_split) apply (rule hoare_pre) apply (wp | wpc | simp add: image_def | rule hoare_pre_cont)+ done crunch ksIdleThread[wp]: updateCap "\<lambda>s. P (ksIdleThread s)" lemma createNewCaps_ct_active': "\<lbrace>ct_active' and pspace_aligned' and pspace_distinct' and pspace_no_overlap' ptr sz and K (range_cover ptr sz (APIType_capBits ty us) n \<and> 0 < n)\<rbrace> createNewCaps ty ptr n us d \<lbrace>\<lambda>_. ct_active'\<rbrace>" apply (simp add: ct_in_state'_def) apply (rule hoare_pre) apply wps apply (wp createNewCaps_pred_tcb_at'[where sz=sz]) apply simp done crunch gsMaxObjectSize[wp]: deleteObjects "\<lambda>s. P (gsMaxObjectSize s)" (simp: unless_def wp: crunch_wps) crunch gsMaxObjectSize[wp]: updateFreeIndex "\<lambda>s. P (gsMaxObjectSize s)" crunch ksIdleThread[wp]: updateFreeIndex "\<lambda>s. P (ksIdleThread s)" lemma invokeUntyped_invs'': assumes insertNew_Q[wp]: "\<And>p cref cap. \<lbrace>Q\<rbrace> insertNewCap p cref cap \<lbrace>\<lambda>_. Q\<rbrace>" assumes createNew_Q: "\<And>tp ptr n us sz dev. \<lbrace>\<lambda>s. Q s \<and> range_cover ptr sz (APIType_capBits tp us) n \<and> (tp = APIObjectType ArchTypes_H.apiobject_type.CapTableObject \<longrightarrow> 0 < us) \<and> 0 < n \<and> valid_pspace' s \<and> pspace_no_overlap' ptr sz s\<rbrace> createNewCaps tp ptr n us dev \<lbrace>\<lambda>_. Q\<rbrace>" assumes set_free_Q[wp]: "\<And>slot idx. \<lbrace>invs' and Q\<rbrace> updateFreeIndex slot idx \<lbrace>\<lambda>_.Q\<rbrace>" assumes reset_Q: "\<lbrace>Q'\<rbrace> resetUntypedCap (case ui of Invocations_H.Retype src_slot _ _ _ _ _ _ _ \<Rightarrow> src_slot) \<lbrace>\<lambda>_. Q\<rbrace>" shows "\<lbrace>invs' and valid_untyped_inv' ui and (\<lambda>s. (case ui of Invocations_H.Retype _ reset _ _ _ _ _ _ \<Rightarrow> reset) \<longrightarrow> Q' s) and Q and ct_active'\<rbrace> invokeUntyped ui \<lbrace>\<lambda>rv. invs' and Q\<rbrace>" apply (rule hoare_name_pre_state) apply (clarsimp simp only: pred_conj_def valid_untyped_inv_wcap') proof - fix s sz idx assume vui1: "valid_untyped_inv_wcap' ui (Some (case ui of Invocations_H.untyped_invocation.Retype slot reset ptr_base ptr ty us slots d \<Rightarrow> capability.UntypedCap d (ptr && ~~ mask sz) sz idx)) s" assume misc: "invs' s" "Q s" "ct_active' s" "(case ui of Invocations_H.untyped_invocation.Retype x reset _ _ _ _ _ _ \<Rightarrow> reset) \<longrightarrow> Q' s" obtain cref reset ptr tp us slots dev where pf: "invokeUntyped_proofs s cref reset (ptr && ~~ mask sz) ptr tp us slots sz idx dev" and ui: "ui = Invocations_H.Retype cref reset (ptr && ~~ mask sz) ptr tp us slots dev" using vui1 misc apply (cases ui, simp only: Invocations_H.untyped_invocation.simps) apply (frule(2) invokeUntyped_proofs.intro) apply clarsimp apply (unfold cte_wp_at_ctes_of) apply (drule meta_mp; clarsimp) done note vui = vui1[simplified ui Invocations_H.untyped_invocation.simps] have cover: "range_cover ptr sz (APIType_capBits tp us) (length slots)" and slots: "cref \<notin> set slots" "distinct slots" "slots \<noteq> []" and tps: "tp = APIObjectType ArchTypes_H.apiobject_type.CapTableObject \<longrightarrow> 0 < us" "tp = APIObjectType ArchTypes_H.apiobject_type.Untyped \<longrightarrow> minUntypedSizeBits \<le> us \<and> us \<le> maxUntypedSizeBits" using vui by (clarsimp simp: ui cte_wp_at_ctes_of)+ note not_0_ptr[simp] = invokeUntyped_proofs.not_0_ptr [OF pf] note subset_stuff[simp] = invokeUntyped_proofs.subset_stuff[OF pf] have non_detype_idx_le[simp]: "~ reset \<Longrightarrow> idx < 2^sz" using vui ui apply (clarsimp simp: cte_wp_at_ctes_of) apply (erule le_less_trans) apply (rule unat_less_helper) apply simp apply (rule le_less_trans) apply (rule word_and_le1) apply (simp add:mask_def) apply (rule word_leq_le_minus_one) apply simp apply (clarsimp simp:range_cover_def) done note blah[simp del] = untyped_range.simps usable_untyped_range.simps atLeastAtMost_iff atLeastatMost_subset_iff atLeastLessThan_iff Int_atLeastAtMost atLeastatMost_empty_iff split_paired_Ex usableUntypedRange.simps note descendants_range[simp] = invokeUntyped_proofs.descendants_range[OF pf] note vc'[simp] = invokeUntyped_proofs.vc'[OF pf] note ps_no_overlap'[simp] = invokeUntyped_proofs.ps_no_overlap'[OF pf] note caps_no_overlap'[simp] = invokeUntyped_proofs.caps_no_overlap'[OF pf] note ex_cte_no_overlap' = invokeUntyped_proofs.ex_cte_no_overlap'[OF pf] note cref_inv = invokeUntyped_proofs.cref_inv[OF pf] note slots_invD = invokeUntyped_proofs.slots_invD[OF pf] note nidx[simp] = add_minus_neg_mask[where ptr = ptr] note idx_compare' = invokeUntyped_proofs.idx_compare'[OF pf] note ptr_cn[simp] = invokeUntyped_proofs.ptr_cn[OF pf] note ptr_km[simp] = invokeUntyped_proofs.ptr_km[OF pf] note sz_limit[simp] = invokeUntyped_proofs.sz_limit[OF pf] have valid_global_refs': "valid_global_refs' s" using misc by auto have mapM_insertNewCap_Q: "\<And>caps. \<lbrace>Q\<rbrace> mapM (\<lambda>(x, y). insertNewCap cref x y) (zip slots caps) \<lbrace>\<lambda>rv. Q\<rbrace>" by (wp mapM_wp' | clarsimp)+ note reset_Q' = reset_Q[simplified ui, simplified] note neg_mask_add_mask = word_plus_and_or_coroll2 [symmetric,where w = "mask sz" and t = ptr,symmetric] note msimp[simp add] = misc neg_mask_add_mask show "\<lbrace>(=) s\<rbrace> invokeUntyped ui \<lbrace>\<lambda>rv s. invs' s \<and> Q s\<rbrace>" including no_pre apply (clarsimp simp:invokeUntyped_def getSlotCap_def ui) apply (rule validE_valid) apply (rule hoare_pre) apply (rule_tac B="\<lambda>_ s. invs' s \<and> Q s \<and> ct_active' s \<and> valid_untyped_inv_wcap' ui (Some (UntypedCap dev (ptr && ~~ mask sz) sz (if reset then 0 else idx))) s \<and> (reset \<longrightarrow> pspace_no_overlap' (ptr && ~~ mask sz) sz s) " in hoare_vcg_seqE[rotated]) apply (simp only: whenE_def) apply wp apply (rule hoare_post_impErr, rule combine_validE, rule resetUntypedCap_invs_etc, rule valid_validE, rule reset_Q') apply (clarsimp simp only: if_True) apply auto[1] apply simp apply wp[1] prefer 2 apply (cut_tac vui1 misc) apply (clarsimp simp: ui cte_wp_at_ctes_of simp del: misc) apply auto[1] apply (rule hoare_pre) apply (wp createNewObjects_wp_helper[where sz = sz]) apply (simp add: slots)+ apply (rule cover) apply (simp add: slots)+ apply (clarsimp simp:insertNewCaps_def) apply (wp zipWithM_x_insertNewCap_invs'' set_tuple_pick distinct_tuple_helper hoare_vcg_const_Ball_lift createNewCaps_invs'[where sz = sz] createNewCaps_valid_cap[where sz = sz,OF cover] createNewCaps_parent_helper[where sz = sz] createNewCaps_cap_to'[where sz = sz] createNewCaps_descendants_range_ret'[where sz = sz] createNewCaps_caps_overlap_reserved_ret'[where sz = sz] createNewCaps_ranges[where sz = sz] createNewCaps_ranges'[where sz = sz] createNewCaps_IRQHandler createNewCaps_ct_active'[where sz=sz] mapM_insertNewCap_Q | simp add: zipWithM_x_mapM slots tps)+ apply (wp hoare_vcg_all_lift) apply (wp hoare_strengthen_post[OF createNewCaps_IRQHandler]) apply (intro impI) apply (erule impE) apply (erule(1) snd_set_zip_in_set) apply (simp add: conj_comms, wp createNew_Q[where sz=sz]) apply (wp hoare_strengthen_post[OF createNewCaps_range_helper[where sz = sz]]) apply (clarsimp simp: slots) apply (clarsimp simp:conj_comms ball_conj_distrib pred_conj_def simp del:capFreeIndex_update.simps) apply (strengthen invs_pspace_aligned' invs_pspace_distinct' invs_valid_pspace' invs_arch_state' imp_consequent[where Q = "(\<exists>x. x \<in> set slots)"] | clarsimp simp: conj_comms simp del: capFreeIndex_update.simps)+ apply (wp updateFreeIndex_forward_invs' updateFreeIndex_caps_overlap_reserved updateFreeIndex_caps_no_overlap'' updateFreeIndex_pspace_no_overlap' hoare_vcg_const_Ball_lift updateFreeIndex_cte_wp_at updateCap_cte_cap_wp_to') apply (wp updateFreeIndex_caps_overlap_reserved updateFreeIndex_descendants_range_in' getCTE_wp | simp)+ apply (clarsimp simp only: ui) apply (frule(2) invokeUntyped_proofs.intro) apply (frule invokeUntyped_proofs.idx_le_new_offs) apply (frule invokeUntyped_proofs.szw) apply (frule invokeUntyped_proofs.descendants_range(2), simp) apply (frule invokeUntyped_proofs.idx_compare') apply (clarsimp simp: cte_wp_at_ctes_of isCap_simps getFreeIndex_def shiftL_nat shiftl_t2n mult.commute if_split[where P="\<lambda>x. x \<le> unat v" for v] invs_valid_pspace' invs_ksCurDomain_maxDomain' invokeUntyped_proofs.caps_no_overlap' invokeUntyped_proofs.usableRange_disjoint split del: if_split) apply (strengthen refl) apply simp apply (intro conjI; assumption?) apply (erule is_aligned_weaken[OF range_cover.funky_aligned]) apply (simp add: APIType_capBits_def objBits_simps' bit_simps untypedBits_defs split: object_type.split apiobject_type.split)[1] apply (cases reset) apply (clarsimp simp: bit_simps) apply (clarsimp simp: invokeUntyped_proofs.ps_no_overlap') apply (drule invs_valid_global') apply (clarsimp simp: valid_global_refs'_def cte_at_valid_cap_sizes_0) apply auto[1] apply (frule valid_global_refsD', clarsimp) apply (clarsimp simp: Int_commute) apply (erule disjoint_subset2[rotated]) apply (simp add: blah word_and_le2) apply (rule order_trans, erule invokeUntyped_proofs.subset_stuff) apply (simp add: blah word_and_le2) apply (frule valid_global_refsD2', clarsimp) apply (clarsimp simp: global_refs'_def) apply (erule notE, erule subsetD[rotated], simp add: blah word_and_le2) done qed lemma invokeUntyped_invs'[wp]: "\<lbrace>invs' and valid_untyped_inv' ui and ct_active'\<rbrace> invokeUntyped ui \<lbrace>\<lambda>rv. invs'\<rbrace>" apply (wp invokeUntyped_invs''[where Q=\<top>, simplified hoare_post_taut, simplified]) apply auto done crunch pred_tcb_at'[wp]: updateFreeIndex "pred_tcb_at' pr P p" lemma resetUntypedCap_st_tcb_at': "\<lbrace>invs' and st_tcb_at' (P and ((\<noteq>) Inactive) and ((\<noteq>) IdleThreadState)) t and cte_wp_at' (\<lambda>cp. isUntypedCap (cteCap cp)) slot and ct_active' and sch_act_simple and (\<lambda>s. descendants_of' slot (ctes_of s) = {})\<rbrace> resetUntypedCap slot \<lbrace>\<lambda>_. st_tcb_at' P t\<rbrace>" apply (rule hoare_name_pre_state) apply (clarsimp simp: cte_wp_at_ctes_of isCap_simps) apply (simp add: resetUntypedCap_def) apply (rule hoare_pre) apply (wp mapME_x_inv_wp preemptionPoint_inv deleteObjects_st_tcb_at'[where p=slot] getSlotCap_wp | simp add: unless_def | wp (once) hoare_drop_imps)+ apply (clarsimp simp: cte_wp_at_ctes_of) apply (strengthen refl) apply (rule exI, strengthen refl) apply (frule cte_wp_at_valid_objs_valid_cap'[OF ctes_of_cte_wpD], clarsimp+) apply (clarsimp simp: valid_cap_simps' capAligned_def empty_descendants_range_in' descendants_range'_def2 elim!: pred_tcb'_weakenE) done lemma inv_untyp_st_tcb_at'[wp]: "\<lbrace>invs' and st_tcb_at' (P and ((\<noteq>) Inactive) and ((\<noteq>) IdleThreadState)) tptr and valid_untyped_inv' ui and ct_active'\<rbrace> invokeUntyped ui \<lbrace>\<lambda>rv. st_tcb_at' P tptr\<rbrace>" apply (rule hoare_pre) apply (rule hoare_strengthen_post) apply (rule invokeUntyped_invs''[where Q="st_tcb_at' P tptr"]; wp createNewCaps_pred_tcb_at') apply (auto simp: valid_pspace'_def)[1] apply (wp resetUntypedCap_st_tcb_at' | simp)+ apply (cases ui, clarsimp simp: cte_wp_at_ctes_of isCap_simps) apply (clarsimp elim!: pred_tcb'_weakenE) done lemma inv_untyp_tcb'[wp]: "\<lbrace>invs' and st_tcb_at' active' tptr and valid_untyped_inv' ui and ct_active'\<rbrace> invokeUntyped ui \<lbrace>\<lambda>rv. tcb_at' tptr\<rbrace>" apply (rule hoare_chain [OF inv_untyp_st_tcb_at'[where tptr=tptr and P="\<top>"]]) apply (clarsimp elim!: pred_tcb'_weakenE) apply fastforce apply (clarsimp simp: pred_tcb_at'_def) done crunch ksInterruptState_eq[wp]: invokeUntyped "\<lambda>s. P (ksInterruptState s)" (wp: crunch_wps mapME_x_inv_wp preemptionPoint_inv simp: crunch_simps unless_def) crunches deleteObjects, updateFreeIndex for valid_irq_states'[wp]: "valid_irq_states'" (wp: doMachineOp_irq_states' crunch_wps simp: freeMemory_def no_irq_storeWord unless_def) lemma resetUntypedCap_IRQInactive: "\<lbrace>valid_irq_states'\<rbrace> resetUntypedCap slot \<lbrace>\<lambda>_ _. True\<rbrace>, \<lbrace>\<lambda>rv s. intStateIRQTable (ksInterruptState s) rv \<noteq> irqstate.IRQInactive\<rbrace>" (is "\<lbrace>?P\<rbrace> resetUntypedCap slot \<lbrace>?Q\<rbrace>,\<lbrace>?E\<rbrace>") apply (simp add: resetUntypedCap_def) apply (rule hoare_pre) apply (wp mapME_x_inv_wp[where P=valid_irq_states' and E="?E", THEN hoare_post_impErr] doMachineOp_irq_states' preemptionPoint_inv hoare_drop_imps | simp add: no_irq_clearMemory if_apply_def2)+ done lemma inv_untyped_IRQInactive: "\<lbrace>valid_irq_states'\<rbrace> invokeUntyped ui -, \<lbrace>\<lambda>rv s. intStateIRQTable (ksInterruptState s) rv \<noteq> irqstate.IRQInactive\<rbrace>" apply (simp add: invokeUntyped_def) apply (wpsimp wp: resetUntypedCap_IRQInactive) done end end
/- Copyright (c) 2021 David Wärn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Wärn -/ import order.well_founded import data.nat.basic import combinatorics.quiver.subquiver import combinatorics.quiver.path /-! # Arborescences A quiver `V` is an arborescence (or directed rooted tree) when we have a root vertex `root : V` such that for every `b : V` there is a unique path from `root` to `b`. ## Main definitions - `quiver.arborescence V`: a typeclass asserting that `V` is an arborescence - `arborescence_mk`: a convenient way of proving that a quiver is an arborescence - `rooted_connected r`: a typeclass asserting that there is at least one path from `r` to `b` for every `b`. - `geodesic_subtree r`: given `[rooted_conntected r]`, this is a subquiver of `V` which contains just enough edges to include a shortest path from `r` to `b` for every `b`. - `geodesic_arborescence : arborescence (geodesic_subtree r)`: an instance saying that the geodesic subtree is an arborescence. This proves the directed analogue of 'every connected graph has a spanning tree'. This proof avoids the use of Zorn's lemma. -/ open opposite universes v u namespace quiver /-- A quiver is an arborescence when there is a unique path from the default vertex to every other vertex. -/ class arborescence (V : Type u) [quiver.{v} V] : Type (max u v) := (root : V) (unique_path : Π (b : V), unique (path root b)) /-- The root of an arborescence. -/ def root (V : Type u) [quiver V] [arborescence V] : V := arborescence.root instance {V : Type u} [quiver V] [arborescence V] (b : V) : unique (path (root V) b) := arborescence.unique_path b /-- To show that `[quiver V]` is an arborescence with root `r : V`, it suffices to - provide a height function `V → ℕ` such that every arrow goes from a lower vertex to a higher vertex, - show that every vertex has at most one arrow to it, and - show that every vertex other than `r` has an arrow to it. -/ noncomputable def arborescence_mk {V : Type u} [quiver V] (r : V) (height : V → ℕ) (height_lt : ∀ ⦃a b⦄, (a ⟶ b) → height a < height b) (unique_arrow : ∀ ⦃a b c : V⦄ (e : a ⟶ c) (f : b ⟶ c), a = b ∧ e == f) (root_or_arrow : ∀ b, b = r ∨ ∃ a, nonempty (a ⟶ b)) : arborescence V := { root := r, unique_path := λ b, ⟨classical.inhabited_of_nonempty begin rcases (show ∃ n, height b < n, from ⟨_, lt_add_one _⟩) with ⟨n, hn⟩, induction n with n ih generalizing b, { exact false.elim (nat.not_lt_zero _ hn) }, rcases root_or_arrow b with ⟨⟨⟩⟩ | ⟨a, ⟨e⟩⟩, { exact ⟨path.nil⟩ }, { rcases ih a (lt_of_lt_of_le (height_lt e) (nat.lt_succ_iff.mp hn)) with ⟨p⟩, exact ⟨p.cons e⟩ } end, begin have height_le : ∀ {a b}, path a b → height a ≤ height b, { intros a b p, induction p with b c p e ih, refl, exact le_of_lt (lt_of_le_of_lt ih (height_lt e)) }, suffices : ∀ p q : path r b, p = q, { intro p, apply this }, intros p q, induction p with a c p e ih; cases q with b _ q f, { refl }, { exact false.elim (lt_irrefl _ (lt_of_le_of_lt (height_le q) (height_lt f))) }, { exact false.elim (lt_irrefl _ (lt_of_le_of_lt (height_le p) (height_lt e))) }, { rcases unique_arrow e f with ⟨⟨⟩, ⟨⟩⟩, rw ih }, end ⟩ } /-- `rooted_connected r` means that there is a path from `r` to any other vertex. -/ class rooted_connected {V : Type u} [quiver V] (r : V) : Prop := (nonempty_path : ∀ b : V, nonempty (path r b)) attribute [instance] rooted_connected.nonempty_path section geodesic_subtree variables {V : Type u} [quiver.{v+1} V] (r : V) [rooted_connected r] /-- A path from `r` of minimal length. -/ noncomputable def shortest_path (b : V) : path r b := well_founded.min (measure_wf path.length) set.univ set.univ_nonempty /-- The length of a path is at least the length of the shortest path -/ lemma shortest_path_spec {a : V} (p : path r a) : (shortest_path r a).length ≤ p.length := not_lt.mp (well_founded.not_lt_min (measure_wf _) set.univ _ trivial) /-- A subquiver which by construction is an arborescence. -/ def geodesic_subtree : wide_subquiver V := λ a b, { e | ∃ p : path r a, shortest_path r b = p.cons e } noncomputable instance geodesic_arborescence : arborescence (geodesic_subtree r) := arborescence_mk r (λ a, (shortest_path r a).length) (by { rintros a b ⟨e, p, h⟩, rw [h, path.length_cons, nat.lt_succ_iff], apply shortest_path_spec }) (by { rintros a b c ⟨e, p, h⟩ ⟨f, q, j⟩, cases h.symm.trans j, split; refl }) begin intro b, rcases hp : shortest_path r b with (_ | ⟨a, _, p, e⟩), { exact or.inl rfl }, { exact or.inr ⟨a, ⟨⟨e, p, hp⟩⟩⟩ } end end geodesic_subtree end quiver
-- -------------------------------------------------------------- [ Parser.idr ] -- Module : UML.Deployment.Parser -- Description : Parser for textual UML deployment diagrams. -- Copyright : (c) Jan de Muijnck-Hughes -- License : see LICENSE -- --------------------------------------------------------------------- [ EOH ] module UML.Deployment.Parser import Lightyear import Lightyear.Strings import UML.Types import UML.Deployment.Model import UML.Utils.Parsing %access private -- -------------------------------------------------------------------- [ Misc ] ||| Parse a key-value pair. ||| ||| Key value pairs are of the form: `<key> : "<value>"`. ||| kvpair : Parser Attribute kvpair = do key <- ident <* space colon value <- literallyBetween '\"' pure (key, value) <?> "KV Pair" ||| Parse pair of braces containing many comma separated KV pairs. kvBody : Parser Attributes kvBody = braces $ (commaSep1 (kvpair <* space) <* space) <?> "KV Body" ||| Parse several properties. properties : Parser Attributes properties = do token "properties" ps <- kvBody pure ps <?> "Properties" -- --------------------------------------------------------------- [ Relations ] ||| Parse a relation defined between two entities. relation : Parser $ DeploymentModel RELA relation = do xID <- ident <* space token "commsWith" yID <- ident <* space token "via" proto <- ident <* space pure $ Relation xID yID proto <?> "Relation" -- ----------------------------------------------------------- [ Specification ] spec : Parser $ DeploymentModel SPEC spec = do token "spec" id <- ident <* space as <- opt kvBody pure $ Spec id $ fromMaybe Nil as -- ---------------------------------------------------------------- [ Artifact ] artifactTy : Parser ArtifactTy artifactTy = do token "doc" pure Document <|> do token "src" pure Source <|> do token "lib" pure Library <|> do token "exe" pure Executable <|> do token "script" pure Script <?> "Artifact Type" artifact : Parser $ DeploymentModel ARTIFACT artifact = do token "artifact" ty <- artifactTy id <- ident <* space s <- opt artBody pure $ Artifact ty id s <?> "Artifact" where artBody : Parser (DeploymentModel SPEC) artBody = do token "with" <* space s <- spec pure s -- ----------------------------------------------------------------- [ Exe Env ] envTy : Parser EnvTy envTy = do token "os" pure OS <|> do token "engine" pure Engine <|> do token "container" pure Container <|> do token "appserver" pure AppServer <|> do token "app" pure App <?> "ExeEnv Type" exenv : Parser $ DeploymentModel ENV exenv = do token "env" ty <- envTy <* space id <- ident <* space (as, ps) <- braces (exenvBody <* space) pure $ Env ty id as ps <?> "Execution Environment" where exenvBody : Parser (List $ DeploymentModel ARTIFACT, Maybe Attributes) exenvBody = do as <- some (artifact <* space) ps <- opt properties <* space pure (as, ps) -- ----------------------------------------------------------------- [ Devices ] devTy : Parser DeviceTy devTy = do token "embedded" pure Embedded <|> do token "mobile" pure Mobile <|> do token "workstation" pure Workstation <|> do token "server" pure Server <?> "Device Type" device : Parser $ DeploymentModel DEVICE device = do token "device" ty <- opt devTy id <- ident <* space (es, ps) <- braces $ deviceBody pure $ Device (fromMaybe GenericDev ty) id es ps <?> "Device" where deviceBody : Parser (List $ DeploymentModel ENV, Maybe Attributes) deviceBody = do es <- some (exenv <* space) ps <- opt properties <* space pure (es, ps) public deploymentModel : Parser UML deploymentModel = do ds <- some (device <* space) rs <- some (relation <* space) pure $ Deployment $ MkDeployment ds rs <?> "Deployment Model" -- --------------------------------------------------------------------- [ EOF ]
SUBROUTINE WASP4 C C CHANGE RECORD C ** SUBROUTINE WASPOUT WRITES OUTPUT FILES PROVIDING ADVECTIVE AND C ** DIFFUSIVE TRANSPORT FIELDS FOR THE WASP4 WATER QUALITY MODEL C USE GLOBAL INTEGER,SAVE,ALLOCATABLE,DIMENSION(:)::LDTMP INTEGER,SAVE,ALLOCATABLE,DIMENSION(:)::LUTMP REAL,SAVE,ALLOCATABLE,DIMENSION(:)::QTMP IF(.NOT.ALLOCATED(LDTMP))THEN ALLOCATE(LDTMP(KCM*LCM)) ALLOCATE(LUTMP(KCM*LCM)) ALLOCATE(QTMP(KCM*LCM)) LDTMP=0 LUTMP=0 QTMP=0.0 ENDIF C C ** WARNING!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! C ** THE VALUE OF X IN THE F10.X FORMATS MAY NEED TO BE CHANGED C ** FROM PROBLEM TO PROBLEM. A PRELIMINARY RUN USING E10.3 C ** CAN BE USED TO SPEED THE ADJUSTMENT C ** READ CONTROL DATA FOR WRITING TO WASP COMPATIABLE FILES C SVPT=1. IF(NTSMMT.LT.NTSPTC)SVPT=0. IF(JSWASP.EQ.1)THEN OPEN(1,FILE='EFDC.WSP',STATUS='UNKNOWN') READ(1,1) READ(1,1) READ(1,*) IVOPT,IBEDV,SCALV,CONVV,VMULT,VEXP,DMULT,DEXP READ(1,1) READ(1,1) READ(1,*) NRFLD,SCALR,CONVR READ(1,1) READ(1,1) READ(1,*) IQOPT,NFIELD,SCALQ,CONVQ READ(1,1) READ(1,1) READ(1,*) DEPSED CLOSE(1) ENDIF 1 FORMAT (80X) C C ** WRITE HORIZONTAL POSITION AND LAYER FILE WASPP.OUT C ** WRITE INITIAL VOLUME FILE WASPC.OUT C ** FILE WASPC.OUT IS CONSISTENT WITH DATA GROUP C SPECIFICATIONS C ** ON PAGE 172 OF THE WASP4 MANUAL PB88-185095, JAN 1988 C ** FILE WASPP.OUT DEFINES THE LAYER (1 IS SURFACE WATER LAYER, WITH C ** LAYER NUMBERING INCREASING WITH DEPTH IN WATER COLUMN) AND C ** HORIZONTAL POSITIONS IN LON,LAT OR UTME, UTMN OF THE WATER C ** QUALITY (LONG TERM TRANSPORT) CELLS OR SEGEMENTS C IF(JSWASP.EQ.1)THEN OPEN(90,FILE='WASPP.OUT',STATUS='UNKNOWN') OPEN(93,FILE='WASPC.OUT',STATUS='UNKNOWN') CLOSE(90,STATUS='DELETE') CLOSE(93,STATUS='DELETE') OPEN(90,FILE='WASPP.OUT',STATUS='UNKNOWN') OPEN(93,FILE='WASPC.OUT',STATUS='UNKNOWN') C C IVOPT=2 C IBEDV=0 C WRITE(93,1031)IVOPT,IBEDV C C SCALV=1. C CONVV=1. C WRITE(93,1032)SCALV,CONVV C C VMULT=0. C VEXP=0. C DMULT=0. C DEXP=0. C LCLTM2=LCLT-2 LWASP=0 IF(KC.GT.1)THEN LTYPE=1 KWASP=1 DO LT=2,LALT LWASP=LWASP+1 LBELOW=LWASP+LCLTM2 I=ILLT(LT) J=JLLT(LT) L=LIJ(I,J) VOLUME=DXYP(L)*HLPF(L)*DZC(KC) WRITE(90,1001)LWASP,KWASP,I,J,DLON(L),DLAT(L) WRITE(93,1033)LWASP,LBELOW,LTYPE,VOLUME,VMULT,VEXP, & DMULT,DEXP ENDDO LTYPE=2 DO K=KS,2,-1 KWASP=KC-K+1 DO LT=2,LALT LWASP=LWASP+1 LBELOW=LWASP+LCLTM2 I=ILLT(LT) J=JLLT(LT) L=LIJ(I,J) VOLUME=DXYP(L)*HLPF(L)*DZC(K) WRITE(90,1001)LWASP,KWASP,I,J,DLON(L),DLAT(L) WRITE(93,1033)LWASP,LBELOW,LTYPE,VOLUME,VMULT,VEXP, & DMULT,DEXP ENDDO ENDDO ENDIF LTYPE=2 IF(KC.EQ.1) LTYPE=1 KWASP=KC DO LT=2,LALT LWASP=LWASP+1 C C LBELOW=0 C LBELOW=LWASP+LCLTM2 I=ILLT(LT) J=JLLT(LT) L=LIJ(I,J) VOLUME=DXYP(L)*HLPF(L)*DZC(1) WRITE(90,1001)LWASP,KWASP,I,J,DLON(L),DLAT(L) WRITE(93,1033)LWASP,LBELOW,LTYPE,VOLUME,VMULT,VEXP, & DMULT,DEXP ENDDO LTYPE=3 KWASP=KC+1 DO LT=2,LALT LWASP=LWASP+1 LBELOW=0 I=ILLT(LT) J=JLLT(LT) L=LIJ(I,J) VOLUME=DXYP(L)*DEPSED WRITE(90,1001)LWASP,KWASP,I,J,DLON(L),DLAT(L) WRITE(93,1033)LWASP,LBELOW,LTYPE,VOLUME,VMULT,VEXP, & DMULT,DEXP ENDDO CLOSE(90) CLOSE(93) ENDIF 1001 FORMAT(4I5,2F10.4) 1031 FORMAT(2I5) 1032 FORMAT(2F10.4) 1033 FORMAT(3I10,5E10.3) C C ** WRITE DIFFUSIVE AND DISPERSIVE TRANSPORT FILE WASPB.OUT C ** FILE WASPB.OUT IS CONSISTENT WITH DATA GROUP B SPECIFICATIONS C ** ON PAGE 170 OF THE WASP4 MANUAL PB88-185095, JAN 1988 C IF(JSWASP.EQ.1)THEN OPEN(91,FILE='WASPB.OUT',STATUS='UNKNOWN') CLOSE(91,STATUS='DELETE') OPEN(91,FILE='WASPB.OUT',STATUS='UNKNOWN') C C NRFLD=1 C WRITE(91,1011)NRFLD NTEX=NTS/NTSMMT C C SCALR=1. C CONVR=1. C WRITE(91,1012)NTEX,SCALR,CONVR CLOSE(91) ENDIF OPEN(91,FILE='WASPB.OUT',POSITION='APPEND',STATUS='UNKNOWN') LCLTM2=LCLT-2 NORSH=0 NORSV=0 DO LT=2,LALT I=ILLT(LT) J=JLLT(LT) L=LIJ(I,J) NORSH=NORSH+INT(SUB(L))+INT(SVB(L)) NORSV=NORSV+INT(SPB(L)) ENDDO NORS=KC*NORSH+KS*NORSV WRITE(91,1013)NORS UNITY=1. DO K=KC,1,-1 KMUL=KC-K DO LT=2,LALT I=ILLT(LT) J=JLLT(LT) L=LIJ(I,J) IF(SUB(L).EQ.1.)THEN LWASP=LT-1+KMUL*LCLTM2 LWASPW=LWASP-1 LW=LWEST(L) ADDLW=DYU(L)*AHULPF(L,K)*DZC(K)*0.5*(HLPF(L) & +HLPF(LW))*DXIU(L) WRITE(91,1014)ADDLW,UNITY,LWASPW,LWASP ENDIF ENDDO ENDDO UNITY=1. DO K=KC,1,-1 KMUL=KC-K DO LT=2,LALT I=ILLT(LT) J=JLLT(LT) L=LIJ(I,J) IF(SVB(L).EQ.1.)THEN LWASP=LT-1+KMUL*LCLTM2 LSLT=LSCLT(LT) LWASPS=LSLT-1+KMUL*LCLTM2 LS=LSC(L) ADDLS=DXV(L)*AHVLPF(L,K)*DZC(K)*0.5*(HLPF(L) & +HLPF(LS))*DYIV(L) WRITE(91,1014)ADDLS,UNITY,LWASPS,LWASP ENDIF ENDDO ENDDO IF(KC.GT.1)THEN UNITY=1. DO K=KS,1,-1 KMUL1=KS-K KMUL2=KMUL1+1 DO LT=2,LALT I=ILLT(LT) J=JLLT(LT) L=LIJ(I,J) IF(SPB(L).EQ.1.)THEN LWASP=LT-1+KMUL1*LCLTM2 LBELOW=LT-1+KMUL2*LCLTM2 ADDL=DXYP(L)*ABLPF(L,K)*DZIG(K) WRITE(91,1014)ADDL,UNITY,LWASP,LBELOW ENDIF ENDDO ENDDO ENDIF NBRK=6 WRITE(91,1015)NBRK IF(ISDYNSTP.EQ.0)THEN TSTOP=DT*FLOAT(N)+TCON*TBEGIN TSTART=TSTOP-DT*FLOAT(NTSMMT) ELSE TSTOP=TENDRNSEC TSTART=TSTOP-DT*FLOAT(NTSMMT) ENDIF TSTOP=TSTOP/86400. TSTART=TSTART/86400. TSMALL=1.E-5 D1=0. T1=0.-2*TSMALL D2=0. T2=TSTART-TSMALL D3=1. T3=TSTART+TSMALL D4=1. T4=TSTOP-TSMALL D5=0. T5=TSTOP+TSMALL D6=0. T6=2*TSMALL+(DT*FLOAT(NTS)+TBEGIN*TCON)/86400. WRITE(91,1016)D1,T1,D2,T2,D3,T3,D4,T4 WRITE(91,1016)D5,T5,D6,T6 CLOSE(91) 1011 FORMAT(I5) 1012 FORMAT(I5,2F10.4) 1013 FORMAT(I5) 1014 FORMAT(2E10.3,2I5) 1015 FORMAT(I5) 1016 FORMAT(4(2F10.5)) 1017 FORMAT(16I5) C C ** WRITE ADVECTIVE TRANSPORT FILE WASPD.OUT C ** FILE WASPD.OUT IS CONSISTENT WITH DATA GROUP D.1 SPECIFICATIONS C ** ON PAGE 174 OF THE WASP4 MANUAL PB88-185095, JAN 1988 C IF(JSWASP.EQ.1)THEN OPEN(92,FILE='WASPD.OUT',STATUS='UNKNOWN') CLOSE(92,STATUS='DELETE') OPEN(92,FILE='WASPD.OUT',STATUS='UNKNOWN') C C IQOPT=1 C NFIELD=1 C WRITE(92,1021)IQOPT,NFIELD NINQ=NTS/NTSMMT C C SCALQ=1 C CONVQ=1 C WRITE(92,1022)NINQ,SCALQ,CONVQ CLOSE(92) ENDIF OPEN(92,FILE='WASPD.OUT',POSITION='APPEND',STATUS='UNKNOWN') LCLTM2=LCLT-2 NOQSH=0 NOQSV=0 DO LT=2,LALT I=ILLT(LT) J=JLLT(LT) L=LIJ(I,J) NOQSH=NOQSH+INT(SUB(L))+INT(SVB(L)) NOQSV=NOQSV+INT(SWB(L)) ENDDO NOQS=KC*NOQSH+KS*NOQSV WRITE(92,1023)NOQS LL=0 DO K=KC,1,-1 KMUL=KC-K DO LT=2,LALT I=ILLT(LT) J=JLLT(LT) L=LIJ(I,J) IF(SUB(L).EQ.1.)THEN LL=LL+1 LDTMP(LL)=LT-1+KMUL*LCLTM2 LUTMP(LL)=LDTMP(LL)-1 QTMP(LL)=DYU(L)*(UHLPF(L,K)+SVPT*UVPT(L,K))*DZC(K) ENDIF ENDDO ENDDO DO L=1,LL,4 WRITE(92,1024)QTMP(L), LUTMP(L), LDTMP(L), & QTMP(LEAST(L)),LUTMP(LEAST(L)),LDTMP(LEAST(L)), & QTMP(L+2),LUTMP(L+2),LDTMP(L+2), & QTMP(L+3),LUTMP(L+3),LDTMP(L+3) ENDDO LL=0 DO K=KC,1,-1 KMUL=KC-K DO LT=2,LALT I=ILLT(LT) J=JLLT(LT) L=LIJ(I,J) IF(SVB(L).EQ.1.)THEN LL=LL+1 LSLT=LSCLT(LT) LDTMP(LL)=LT-1+KMUL*LCLTM2 LUTMP(LL)=LSLT-1+KMUL*LCLTM2 QTMP(LL)=DXV(L)*(VHLPF(L,K)+SVPT*VVPT(L,K))*DZC(K) ENDIF ENDDO ENDDO DO L=1,LL,4 WRITE(92,1024)QTMP(L), LUTMP(L), LDTMP(L), & QTMP(LEAST(L)),LUTMP(LEAST(L)),LDTMP(LEAST(L)), & QTMP(L+2),LUTMP(L+2),LDTMP(L+2), & QTMP(L+3),LUTMP(L+3),LDTMP(L+3) ENDDO IF(KC.GT.1)THEN LL=0 DO K=KS,1,-1 KMUL1=KS-K KMUL2=KMUL1+1 DO LT=2,LALT I=ILLT(LT) J=JLLT(LT) L=LIJ(I,J) IF(SWB(L).EQ.1.)THEN LL=LL+1 LUTMP(LL)=LT-1+KMUL1*LCLTM2 LDTMP(LL)=LT-1+KMUL2*LCLTM2 QTMP(LL)=-DXYP(L)*(WLPF(L,K)+SVPT*WVPT(L,K)) ENDIF ENDDO ENDDO ENDIF IF(KC.GT.1)THEN DO L=1,LL,4 WRITE(92,1024) QTMP(L), LUTMP(L), LDTMP(L), & QTMP(LEAST(L)),LUTMP(LEAST(L)),LDTMP(LEAST(L)), & QTMP(L+2),LUTMP(L+2),LDTMP(L+2), & QTMP(L+3),LUTMP(L+3),LDTMP(L+3) ENDDO ENDIF NBRKQ=6 WRITE(92,1025)NBRKQ WRITE(92,1026)D1,T1,D2,T2,D3,T3,D4,T4 WRITE(92,1026)D5,T5,D6,T6 CLOSE(92) 1021 FORMAT(2I5) 1022 FORMAT(I5,2F10.4) 1023 FORMAT(I5) 1024 FORMAT(4(E10.3,2I5)) 1025 FORMAT(I5) 1026 FORMAT(4(2F10.5)) C C ** WRITE TO DYNHYD.HYD EMULATION FILES WASPDH.OUT AND WASPDHU.OUT C IF(JSWASP.EQ.1)THEN OPEN(90,FILE='WASPDHD.OUT',STATUS='UNKNOWN') OPEN(94,FILE='WASPDH.OUT',STATUS='UNKNOWN') OPEN(95,FILE='WASPDHU.OUT',STATUS='UNKNOWN', & FORM='UNFORMATTED') CLOSE(90,STATUS='DELETE') CLOSE(94,STATUS='DELETE') CLOSE(95,STATUS='DELETE') OPEN(90,FILE='WASPDHD.OUT',STATUS='UNKNOWN') OPEN(94,FILE='WASPDH.OUT',STATUS='UNKNOWN') OPEN(95,FILE='WASPDHU.OUT',STATUS='UNKNOWN', & FORM='UNFORMATTED') KCLC=KC*LCLT LCLTM2=LCLT-2 DO KL=1,KCLC NCHNC(KL)=0 ENDDO DO M=1,10 DO KL=1,KCLC LCHNC(KL,M)=0 ENDDO ENDDO NJUN=KC*(LCLT-2) NCHNH=0 NCHNV=0 DO LT=2,LALT I=ILLT(LT) J=JLLT(LT) L=LIJ(I,J) NCHNH=NCHNH+INT(SUB(L))+INT(SVB(L)) NCHNV=NCHNV+INT(SWB(L)) ENDDO NCHN=KC*NCHNH+KS*NCHNV ISTMP=0 NODYN=NFLTMT TZERO=TBEGIN*TCON/86400. WRITE(90,901)NJUN,NCHN WRITE(94,941)NJUN,NCHN,DT,ISTMP,NTS,ISTMP,NODYN,TZERO WRITE(95)NJUN,NCHN,DT,ISTMP,NTS,ISTMP,NODYN,TZERO C C ** CHANNEL DATA C RMNDUM=0. LCHN=0 DO K=KC,1,-1 KMUL=KC-K DO LT=2,LALT I=ILLT(LT) J=JLLT(LT) L=LIJ(I,J) IF(SUB(L).EQ.1.)THEN LDTM=LT-1+KMUL*LCLTM2 LUTM=LDTM-1 RLENTH=DXU(L) WIDTH=DYU(L) LCHN=LCHN+1 NCHNC(LDTM)=NCHNC(LDTM)+1 NCHNC(LUTM)=NCHNC(LUTM)+1 LCHNC(LDTM,NCHNC(LDTM))=LCHN LCHNC(LUTM,NCHNC(LUTM))=LCHN WRITE(90,902)LCHN,RLENTH,WIDTH,RMNDUM,LUTM,LDTM WRITE(94,942)RLENTH,WIDTH,RMNDUM,LUTM,LDTM WRITE(95)RLENTH,WIDTH,RMNDUM,LUTM,LDTM ENDIF ENDDO ENDDO DO K=KC,1,-1 KMUL=KC-K DO LT=2,LALT I=ILLT(LT) J=JLLT(LT) L=LIJ(I,J) IF(SVB(L).EQ.1.)THEN LSLT=LSCLT(LT) LDTM=LT-1+KMUL*LCLTM2 LUTM=LSLT-1+KMUL*LCLTM2 RLENTH=DYV(L) WIDTH=DXV(L) LCHN=LCHN+1 NCHNC(LDTM)=NCHNC(LDTM)+1 NCHNC(LUTM)=NCHNC(LUTM)+1 LCHNC(LDTM,NCHNC(LDTM))=LCHN LCHNC(LUTM,NCHNC(LUTM))=LCHN WRITE(90,902)LCHN,RLENTH,WIDTH,RMNDUM,LUTM,LDTM WRITE(94,942)RLENTH,WIDTH,RMNDUM,LUTM,LDTM WRITE(95)RLENTH,WIDTH,RMNDUM,LUTM,LDTM ENDIF ENDDO ENDDO IF(KC.GT.1)THEN DO K=KS,1,-1 KMUL1=KS-K KMUL2=KMUL1+1 DO LT=2,LALT I=ILLT(LT) J=JLLT(LT) L=LIJ(I,J) IF(SWB(L).EQ.1.)THEN LUTM=LT-1+KMUL1*LCLTM2 LDTM=LT-1+KMUL2*LCLTM2 RLENTH=HLPF(L)*DZG(K) WIDTH=SQRT(DXYP(L)) LCHN=LCHN+1 NCHNC(LDTM)=NCHNC(LDTM)+1 NCHNC(LUTM)=NCHNC(LUTM)+1 LCHNC(LDTM,NCHNC(LDTM))=LCHN LCHNC(LUTM,NCHNC(LUTM))=LCHN WRITE(90,902)LCHN,RLENTH,WIDTH,RMNDUM,LUTM,LDTM WRITE(94,942)RLENTH,WIDTH,RMNDUM,LUTM,LDTM WRITE(95)RLENTH,WIDTH,RMNDUM,LUTM,LDTM ENDIF ENDDO ENDDO ENDIF C C ** JUNCTION DATA C DO K=KC,1,-1 KMUL=KC-K DO LT=2,LALT I=ILLT(LT) J=JLLT(LT) L=LIJ(I,J) LCELL=LT-1+KMUL*LCLTM2 WRITE(90,904)LCELL,DXYP(L),(LCHNC(LCELL,M),M=1,10) WRITE(94,944)DXYP(L),(LCHNC(LCELL,M),M=1,10) WRITE(95)DXYP(L),(LCHNC(LCELL,M),M=1,10) ENDDO ENDDO CLOSE(90) CLOSE(94) CLOSE(95) ENDIF C C ** WRITE TIME STEP, VOLUME AND FLOW DATA C OPEN(94,FILE='WASPDH.OUT',POSITION='APPEND',STATUS='UNKNOWN') OPEN(95,FILE='WASPDHU.OUT',POSITION='APPEND',STATUS='UNKNOWN', & FORM='UNFORMATTED') LCLTM2=LCLT-2 IZERO=0 RZERO=0 NSTEP=N-NTSMMT WRITE(94,945)NSTEP DO K=KC,1,-1 DO LT=2,LALT I=ILLT(LT) J=JLLT(LT) L=LIJ(I,J) LN=LNC(L) VOLUM=DXYP(L)*HLPF(L)*DZC(K) QIN=QSUMELPF(L)*DZC(K) FLOWXI=DYU(L)*(UHLPF(L,K)+SVPT*UVPT(L,K))*DZC(K) FLOWYI=DXV(L)*(VHLPF(L,K)+SVPT*VVPT(L,K))*DZC(K) FLOWZI=DXYP(L)*(WLPF(L,K-1)+SVPT*WVPT(L,K-1)) FLOWXO=DYU(LEAST(L))*(UHLPF(LEAST(L),K)+SVPT*UVPT(LEAST(L),K))*DZC(K) FLOWYO=DXV(LN)*(VHLPF(LN,K)+SVPT*VVPT(LN,K))*DZC(K) FLOWZO=DXYP(L)*(WLPF(L,K)+SVPT*WVPT(L,K)) QQSUM=QIN+FLOWXI+FLOWYI+FLOWZI-FLOWXO-FLOWYO-FLOWZO DEPTH=HLPF(L)*DZC(K) VELX=0.5*(UHLPF(L,K)+SVPT*UVPT(L,K) & +UHLPF(LEAST(L),K)+SVPT*UVPT(LEAST(L),K))/HLPF(L) VELY=0.5*(VHLPF(L,K)+SVPT*VVPT(L,K) & +VHLPF(LN,K)+SVPT*VVPT(LN,K))/HLPF(L) VELZ=0.5*(WLPF(L,K-1)+SVPT*WVPT(L,K-1) & +WLPF(L,K)+SVPT*WVPT(L,K)) VELMAG=SQRT(VELX*VELX+VELY*VELY+VELZ*VELZ) WRITE(94,946)VOLUM,QIN,QSUM,DEPTH,VELMAG WRITE(95)VOLUM,QIN,QQSUM,DEPTH,VELMAG ENDDO ENDDO DO K=KC,1,-1 DO LT=2,LALT I=ILLT(LT) J=JLLT(LT) L=LIJ(I,J) IF(SUB(L).EQ.1.)THEN FLOWX=DYU(L)*(UHLPF(L,K)+SVPT*UVPT(L,K))*DZC(K) WRITE(94,946)FLOWX WRITE(95)FLOWX ENDIF ENDDO ENDDO DO K=KC,1,-1 DO LT=2,LALT I=ILLT(LT) J=JLLT(LT) L=LIJ(I,J) IF(SVB(L).EQ.1.)THEN FLOWY=DXV(L)*(VHLPF(L,K)+SVPT*VVPT(L,K))*DZC(K) WRITE(94,946)FLOWY WRITE(95)FLOWY ENDIF ENDDO ENDDO IF(KC.GT.1)THEN DO K=KS,1,-1 DO LT=2,LALT I=ILLT(LT) J=JLLT(LT) L=LIJ(I,J) IF(SWB(L).EQ.1.)THEN FLOWZ=-DXYP(L)*(WLPF(L,K)+SVPT*WVPT(L,K)) WRITE(94,946)FLOWZ WRITE(95)FLOWZ ENDIF ENDDO ENDDO ENDIF CLOSE(94) CLOSE(95) 901 FORMAT(2I5,E12.4,4I5,E12.4) 902 FORMAT(I5,2X,3E12.4,2I5) 903 FORMAT(3E12.4,2I5) 904 FORMAT(I5,2X,E12.4,10I5) 905 FORMAT(I5) 906 FORMAT(5E12.4) 941 FORMAT(2I5,E12.4,4I5,E12.4) 942 FORMAT(3E12.4,2I5) 943 FORMAT(3E12.4,2I5) 944 FORMAT(E12.4,10I5) 945 FORMAT(I5) 946 FORMAT(5E12.4) JSWASP=0 RETURN END
/- Copyright (c) 2015 Joseph Hua. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Hua -/ import data.W.basic /-! # Examples of W-types > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We take the view of W types as inductive types. Given `α : Type` and `β : α → Type`, the W type determined by this data, `W_type β`, is the inductively with constructors from `α` and arities of each constructor `a : α` given by `β a`. This file contains `nat` and `list` as examples of W types. ## Main results * `W_type.equiv_nat`: the construction of the naturals as a W-type is equivalent to `nat` * `W_type.equiv_list`: the construction of lists on a type `γ` as a W-type is equivalent to `list γ` -/ universes u v namespace W_type section nat /-- The constructors for the naturals -/ inductive nat_α : Type | zero : nat_α | succ : nat_α instance : inhabited nat_α := ⟨ nat_α.zero ⟩ /-- The arity of the constructors for the naturals, `zero` takes no arguments, `succ` takes one -/ def nat_β : nat_α → Type | nat_α.zero := empty | nat_α.succ := unit instance : inhabited (nat_β nat_α.succ) := ⟨ () ⟩ /-- The isomorphism from the naturals to its corresponding `W_type` -/ @[simp] def of_nat : ℕ → W_type nat_β | nat.zero := ⟨ nat_α.zero , empty.elim ⟩ | (nat.succ n) := ⟨ nat_α.succ , λ _ , of_nat n ⟩ /-- The isomorphism from the `W_type` of the naturals to the naturals -/ @[simp] def to_nat : W_type nat_β → ℕ | (W_type.mk nat_α.zero f) := 0 | (W_type.mk nat_α.succ f) := (to_nat (f ())).succ lemma left_inv_nat : function.left_inverse of_nat to_nat | (W_type.mk nat_α.zero f) := by { simp, tidy } | (W_type.mk nat_α.succ f) := by { simp, tidy } lemma right_inv_nat : function.right_inverse of_nat to_nat | nat.zero := rfl | (nat.succ n) := by rw [of_nat, to_nat, right_inv_nat n] /-- The naturals are equivalent to their associated `W_type` -/ def equiv_nat : W_type nat_β ≃ ℕ := { to_fun := to_nat, inv_fun := of_nat, left_inv := left_inv_nat, right_inv := right_inv_nat } open sum punit /-- `W_type.nat_α` is equivalent to `punit ⊕ punit`. This is useful when considering the associated polynomial endofunctor. -/ @[simps] def nat_α_equiv_punit_sum_punit : nat_α ≃ punit.{u + 1} ⊕ punit := { to_fun := λ c, match c with | nat_α.zero := inl star | nat_α.succ := inr star end, inv_fun := λ b, match b with | inl x := nat_α.zero | inr x := nat_α.succ end, left_inv := λ c, match c with | nat_α.zero := rfl | nat_α.succ := rfl end, right_inv := λ b, match b with | inl star := rfl | inr star := rfl end } end nat section list variable (γ : Type u) /-- The constructors for lists. There is "one constructor `cons x` for each `x : γ`", since we view `list γ` as ``` | nil : list γ | cons x₀ : list γ → list γ | cons x₁ : list γ → list γ | ⋮ γ many times ``` -/ inductive list_α : Type u | nil : list_α | cons : γ → list_α instance : inhabited (list_α γ) := ⟨ list_α.nil ⟩ /-- The arities of each constructor for lists, `nil` takes no arguments, `cons hd` takes one -/ def list_β : list_α γ → Type u | list_α.nil := pempty | (list_α.cons hd) := punit instance (hd : γ) : inhabited (list_β γ (list_α.cons hd)) := ⟨ punit.star ⟩ /-- The isomorphism from lists to the `W_type` construction of lists -/ @[simp] def of_list : list γ → W_type (list_β γ) | list.nil := ⟨ list_α.nil, pempty.elim ⟩ | (list.cons hd tl) := ⟨ list_α.cons hd, λ _ , of_list tl ⟩ /-- The isomorphism from the `W_type` construction of lists to lists -/ @[simp] def to_list : W_type (list_β γ) → list γ | (W_type.mk list_α.nil f) := [] | (W_type.mk (list_α.cons hd) f) := hd :: to_list (f punit.star) lemma left_inv_list : function.left_inverse (of_list γ) (to_list _) | (W_type.mk list_α.nil f) := by { simp, tidy } | (W_type.mk (list_α.cons x) f) := by { simp, tidy } lemma right_inv_list : function.right_inverse (of_list γ) (to_list _) | list.nil := rfl | (list.cons hd tl) := by simp [right_inv_list tl] /-- Lists are equivalent to their associated `W_type` -/ def equiv_list : W_type (list_β γ) ≃ list γ := { to_fun := to_list _, inv_fun := of_list _, left_inv := left_inv_list _, right_inv := right_inv_list _ } /-- `W_type.list_α` is equivalent to `γ` with an extra point. This is useful when considering the associated polynomial endofunctor -/ def list_α_equiv_punit_sum : list_α γ ≃ punit.{v + 1} ⊕ γ := { to_fun := λ c, match c with | list_α.nil := sum.inl punit.star | list_α.cons x := sum.inr x end, inv_fun := sum.elim (λ _, list_α.nil) (λ x, list_α.cons x), left_inv := λ c, match c with | list_α.nil := rfl | list_α.cons x := rfl end, right_inv := λ x, match x with | sum.inl punit.star := rfl | sum.inr x := rfl end, } end list end W_type
SUBROUTINE PDGGQRF( N, M, P, A, IA, JA, DESCA, TAUA, B, IB, JB, $ DESCB, TAUB, WORK, LWORK, INFO ) * * -- ScaLAPACK routine (version 1.7) -- * University of Tennessee, Knoxville, Oak Ridge National Laboratory, * and University of California, Berkeley. * May 1, 1997 * * .. Scalar Arguments .. INTEGER IA, IB, INFO, JA, JB, LWORK, M, N, P * .. * .. Array Arguments .. INTEGER DESCA( * ), DESCB( * ) DOUBLE PRECISION A( * ), B( * ), TAUA( * ), TAUB( * ), WORK( * ) * .. * * Purpose * ======= * * PDGGQRF computes a generalized QR factorization of * an N-by-M matrix sub( A ) = A(IA:IA+N-1,JA:JA+M-1) and * an N-by-P matrix sub( B ) = B(IB:IB+N-1,JB:JB+P-1): * * sub( A ) = Q*R, sub( B ) = Q*T*Z, * * where Q is an N-by-N orthogonal matrix, Z is a P-by-P orthogonal * matrix, and R and T assume one of the forms: * * if N >= M, R = ( R11 ) M , or if N < M, R = ( R11 R12 ) N, * ( 0 ) N-M N M-N * M * * where R11 is upper triangular, and * * if N <= P, T = ( 0 T12 ) N, or if N > P, T = ( T11 ) N-P, * P-N N ( T21 ) P * P * * where T12 or T21 is upper triangular. * * In particular, if sub( B ) is square and nonsingular, the GQR * factorization of sub( A ) and sub( B ) implicitly gives the QR * factorization of inv( sub( B ) )* sub( A ): * * inv( sub( B ) )*sub( A )= Z'*(inv(T)*R) * * where inv( sub( B ) ) denotes the inverse of the matrix sub( B ), * and Z' denotes the transpose of matrix Z. * * Notes * ===== * * Each global data object is described by an associated description * vector. This vector stores the information required to establish * the mapping between an object element and its corresponding process * and memory location. * * Let A be a generic term for any 2D block cyclicly distributed array. * Such a global array has an associated description vector DESCA. * In the following comments, the character _ should be read as * "of the global array". * * NOTATION STORED IN EXPLANATION * --------------- -------------- -------------------------------------- * DTYPE_A(global) DESCA( DTYPE_ )The descriptor type. In this case, * DTYPE_A = 1. * CTXT_A (global) DESCA( CTXT_ ) The BLACS context handle, indicating * the BLACS process grid A is distribu- * ted over. The context itself is glo- * bal, but the handle (the integer * value) may vary. * M_A (global) DESCA( M_ ) The number of rows in the global * array A. * N_A (global) DESCA( N_ ) The number of columns in the global * array A. * MB_A (global) DESCA( MB_ ) The blocking factor used to distribute * the rows of the array. * NB_A (global) DESCA( NB_ ) The blocking factor used to distribute * the columns of the array. * RSRC_A (global) DESCA( RSRC_ ) The process row over which the first * row of the array A is distributed. * CSRC_A (global) DESCA( CSRC_ ) The process column over which the * first column of the array A is * distributed. * LLD_A (local) DESCA( LLD_ ) The leading dimension of the local * array. LLD_A >= MAX(1,LOCr(M_A)). * * Let K be the number of rows or columns of a distributed matrix, * and assume that its process grid has dimension p x q. * LOCr( K ) denotes the number of elements of K that a process * would receive if K were distributed over the p processes of its * process column. * Similarly, LOCc( K ) denotes the number of elements of K that a * process would receive if K were distributed over the q processes of * its process row. * The values of LOCr() and LOCc() may be determined via a call to the * ScaLAPACK tool function, NUMROC: * LOCr( M ) = NUMROC( M, MB_A, MYROW, RSRC_A, NPROW ), * LOCc( N ) = NUMROC( N, NB_A, MYCOL, CSRC_A, NPCOL ). * An upper bound for these quantities may be computed by: * LOCr( M ) <= ceil( ceil(M/MB_A)/NPROW )*MB_A * LOCc( N ) <= ceil( ceil(N/NB_A)/NPCOL )*NB_A * * Arguments * ========= * * N (global input) INTEGER * The number of rows to be operated on i.e the number of rows * of the distributed submatrices sub( A ) and sub( B ). N >= 0. * * M (global input) INTEGER * The number of columns to be operated on i.e the number of * columns of the distributed submatrix sub( A ). M >= 0. * * P (global input) INTEGER * The number of columns to be operated on i.e the number of * columns of the distributed submatrix sub( B ). P >= 0. * * A (local input/local output) DOUBLE PRECISION pointer into the * local memory to an array of dimension (LLD_A, LOCc(JA+M-1)). * On entry, the local pieces of the N-by-M distributed matrix * sub( A ) which is to be factored. On exit, the elements on * and above the diagonal of sub( A ) contain the min(N,M) by M * upper trapezoidal matrix R (R is upper triangular if N >= M); * the elements below the diagonal, with the array TAUA, * represent the orthogonal matrix Q as a product of min(N,M) * elementary reflectors (see Further Details). * * IA (global input) INTEGER * The row index in the global array A indicating the first * row of sub( A ). * * JA (global input) INTEGER * The column index in the global array A indicating the * first column of sub( A ). * * DESCA (global and local input) INTEGER array of dimension DLEN_. * The array descriptor for the distributed matrix A. * * TAUA (local output) DOUBLE PRECISION array, dimension * LOCc(JA+MIN(N,M)-1). This array contains the scalar factors * TAUA of the elementary reflectors which represent the * orthogonal matrix Q. TAUA is tied to the distributed matrix * A. (see Further Details). * * B (local input/local output) DOUBLE PRECISION pointer into the * local memory to an array of dimension (LLD_B, LOCc(JB+P-1)). * On entry, the local pieces of the N-by-P distributed matrix * sub( B ) which is to be factored. On exit, if N <= P, the * upper triangle of B(IB:IB+N-1,JB+P-N:JB+P-1) contains the * N by N upper triangular matrix T; if N > P, the elements on * and above the (N-P)-th subdiagonal contain the N by P upper * trapezoidal matrix T; the remaining elements, with the array * TAUB, represent the orthogonal matrix Z as a product of * elementary reflectors (see Further Details). * * IB (global input) INTEGER * The row index in the global array B indicating the first * row of sub( B ). * * JB (global input) INTEGER * The column index in the global array B indicating the * first column of sub( B ). * * DESCB (global and local input) INTEGER array of dimension DLEN_. * The array descriptor for the distributed matrix B. * * TAUB (local output) DOUBLE PRECISION array, dimension LOCr(IB+N-1) * This array contains the scalar factors of the elementary * reflectors which represent the orthogonal unitary matrix Z. * TAUB is tied to the distributed matrix B (see Further * Details). * * WORK (local workspace/local output) DOUBLE PRECISION array, * dimension (LWORK) * On exit, WORK(1) returns the minimal and optimal LWORK. * * LWORK (local or global input) INTEGER * The dimension of the array WORK. * LWORK is local input and must be at least * LWORK >= MAX( NB_A * ( NpA0 + MqA0 + NB_A ), * MAX( (NB_A*(NB_A-1))/2, (PqB0 + NpB0)*NB_A ) + * NB_A * NB_A, * MB_B * ( NpB0 + PqB0 + MB_B ) ), where * * IROFFA = MOD( IA-1, MB_A ), ICOFFA = MOD( JA-1, NB_A ), * IAROW = INDXG2P( IA, MB_A, MYROW, RSRC_A, NPROW ), * IACOL = INDXG2P( JA, NB_A, MYCOL, CSRC_A, NPCOL ), * NpA0 = NUMROC( N+IROFFA, MB_A, MYROW, IAROW, NPROW ), * MqA0 = NUMROC( M+ICOFFA, NB_A, MYCOL, IACOL, NPCOL ), * * IROFFB = MOD( IB-1, MB_B ), ICOFFB = MOD( JB-1, NB_B ), * IBROW = INDXG2P( IB, MB_B, MYROW, RSRC_B, NPROW ), * IBCOL = INDXG2P( JB, NB_B, MYCOL, CSRC_B, NPCOL ), * NpB0 = NUMROC( N+IROFFB, MB_B, MYROW, IBROW, NPROW ), * PqB0 = NUMROC( P+ICOFFB, NB_B, MYCOL, IBCOL, NPCOL ), * * and NUMROC, INDXG2P are ScaLAPACK tool functions; * MYROW, MYCOL, NPROW and NPCOL can be determined by calling * the subroutine BLACS_GRIDINFO. * * If LWORK = -1, then LWORK is global input and a workspace * query is assumed; the routine only calculates the minimum * and optimal size for all work arrays. Each of these * values is returned in the first entry of the corresponding * work array, and no error message is issued by PXERBLA. * * INFO (global output) INTEGER * = 0: successful exit * < 0: If the i-th argument is an array and the j-entry had * an illegal value, then INFO = -(i*100+j), if the i-th * argument is a scalar and had an illegal value, then * INFO = -i. * * Further Details * =============== * * The matrix Q is represented as a product of elementary reflectors * * Q = H(ja) H(ja+1) . . . H(ja+k-1), where k = min(n,m). * * Each H(i) has the form * * H(i) = I - taua * v * v' * * where taua is a real scalar, and v is a real vector with * v(1:i-1) = 0 and v(i) = 1; v(i+1:n) is stored on exit in * A(ia+i:ia+n-1,ja+i-1), and taua in TAUA(ja+i-1). * To form Q explicitly, use ScaLAPACK subroutine PDORGQR. * To use Q to update another matrix, use ScaLAPACK subroutine PDORMQR. * * The matrix Z is represented as a product of elementary reflectors * * Z = H(ib) H(ib+1) . . . H(ib+k-1), where k = min(n,p). * * Each H(i) has the form * * H(i) = I - taub * v * v' * * where taub is a real scalar, and v is a real vector with * v(p-k+i+1:p) = 0 and v(p-k+i) = 1; v(1:p-k+i-1) is stored on exit in * B(ib+n-k+i-1,jb:jb+p-k+i-2), and taub in TAUB(ib+n-k+i-1). * To form Z explicitly, use ScaLAPACK subroutine PDORGRQ. * To use Z to update another matrix, use ScaLAPACK subroutine PDORMRQ. * * Alignment requirements * ====================== * * The distributed submatrices sub( A ) and sub( B ) must verify some * alignment properties, namely the following expression should be true: * * ( MB_A.EQ.MB_B .AND. IROFFA.EQ.IROFFB .AND. IAROW.EQ.IBROW ) * * ===================================================================== * * .. Parameters .. INTEGER BLOCK_CYCLIC_2D, CSRC_, CTXT_, DLEN_, DTYPE_, $ LLD_, MB_, M_, NB_, N_, RSRC_ PARAMETER ( BLOCK_CYCLIC_2D = 1, DLEN_ = 9, DTYPE_ = 1, $ CTXT_ = 2, M_ = 3, N_ = 4, MB_ = 5, NB_ = 6, $ RSRC_ = 7, CSRC_ = 8, LLD_ = 9 ) * .. * .. Local Scalars .. LOGICAL LQUERY INTEGER IACOL, IAROW, IBCOL, IBROW, ICOFFA, ICOFFB, $ ICTXT, IROFFA, IROFFB, LWMIN, MQA0, MYCOL, $ MYROW, NPA0, NPB0, NPCOL, NPROW, PQB0 * .. * .. External Subroutines .. EXTERNAL BLACS_GRIDINFO, CHK1MAT, PCHK2MAT, PDGEQRF, $ PDGERQF, PDORMQR, PXERBLA * .. * .. Local Arrays .. INTEGER IDUM1( 1 ), IDUM2( 1 ) * .. * .. External Functions .. INTEGER INDXG2P, NUMROC EXTERNAL INDXG2P, NUMROC * .. * .. Intrinsic Functions .. INTRINSIC DBLE, INT, MAX, MIN, MOD * .. * .. Executable Statements .. * * Get grid parameters * ICTXT = DESCA( CTXT_ ) CALL BLACS_GRIDINFO( ICTXT, NPROW, NPCOL, MYROW, MYCOL ) * * Test the input parameters * INFO = 0 IF( NPROW.EQ.-1 ) THEN INFO = -707 ELSE CALL CHK1MAT( N, 1, M, 2, IA, JA, DESCA, 7, INFO ) CALL CHK1MAT( N, 1, P, 3, IB, JB, DESCB, 12, INFO ) IF( INFO.EQ.0 ) THEN IROFFA = MOD( IA-1, DESCA( MB_ ) ) ICOFFA = MOD( JA-1, DESCA( NB_ ) ) IROFFB = MOD( IB-1, DESCB( MB_ ) ) ICOFFB = MOD( JB-1, DESCB( NB_ ) ) IAROW = INDXG2P( IA, DESCA( MB_ ), MYROW, DESCA( RSRC_ ), $ NPROW ) IACOL = INDXG2P( JA, DESCA( NB_ ), MYCOL, DESCA( CSRC_ ), $ NPCOL ) IBROW = INDXG2P( IB, DESCB( MB_ ), MYROW, DESCB( RSRC_ ), $ NPROW ) IBCOL = INDXG2P( JB, DESCB( NB_ ), MYCOL, DESCB( CSRC_ ), $ NPCOL ) NPA0 = NUMROC( N+IROFFA, DESCA( MB_ ), MYROW, IAROW, NPROW ) MQA0 = NUMROC( M+ICOFFA, DESCA( NB_ ), MYCOL, IACOL, NPCOL ) NPB0 = NUMROC( N+IROFFB, DESCB( MB_ ), MYROW, IBROW, NPROW ) PQB0 = NUMROC( P+ICOFFB, DESCB( NB_ ), MYCOL, IBCOL, NPCOL ) LWMIN = MAX( DESCA( NB_ ) * ( NPA0 + MQA0 + DESCA( NB_ ) ), $ MAX( MAX( ( DESCA( NB_ )*( DESCA( NB_ ) - 1 ) ) / 2, $ ( PQB0 + NPB0 ) * DESCA( NB_ ) ) + $ DESCA( NB_ ) * DESCA( NB_ ), $ DESCB( MB_ ) * ( NPB0 + PQB0 + DESCB( MB_ ) ) ) ) * WORK( 1 ) = DBLE( LWMIN ) LQUERY = ( LWORK.EQ.-1 ) IF( IAROW.NE.IBROW .OR. IROFFA.NE.IROFFB ) THEN INFO = -10 ELSE IF( DESCA( MB_ ).NE.DESCB( MB_ ) ) THEN INFO = -1203 ELSE IF( ICTXT.NE.DESCB( CTXT_ ) ) THEN INFO = -1207 ELSE IF( LWORK.LT.LWMIN .AND. .NOT.LQUERY ) THEN INFO = -15 END IF END IF IF( LQUERY ) THEN IDUM1( 1 ) = -1 ELSE IDUM1( 1 ) = 1 END IF IDUM2( 1 ) = 15 CALL PCHK2MAT( N, 1, M, 2, IA, JA, DESCA, 7, N, 1, P, 3, IB, $ JB, DESCB, 12, 1, IDUM1, IDUM2, INFO ) END IF * IF( INFO.NE.0 ) THEN CALL PXERBLA( ICTXT, 'PDGGQRF', -INFO ) RETURN ELSE IF( LQUERY ) THEN RETURN END IF * * QR factorization of N-by-M matrix sub( A ): sub( A ) = Q*R * CALL PDGEQRF( N, M, A, IA, JA, DESCA, TAUA, WORK, LWORK, INFO ) LWMIN = INT( WORK( 1 ) ) * * Update sub( B ) := Q'*sub( B ). * CALL PDORMQR( 'Left', 'Transpose', N, P, MIN( N, M ), A, IA, JA, $ DESCA, TAUA, B, IB, JB, DESCB, WORK, LWORK, INFO ) LWMIN = MIN( LWMIN, INT( WORK( 1 ) ) ) * * RQ factorization of N-by-P matrix sub( B ): sub( B ) = T*Z. * CALL PDGERQF( N, P, B, IB, JB, DESCB, TAUB, WORK, LWORK, INFO ) WORK( 1 ) = DBLE( MAX( LWMIN, INT( WORK( 1 ) ) ) ) * RETURN * * End of PDGGQRF * END
[STATEMENT] lemma has_prod_unique: fixes f :: "nat \<Rightarrow> 'a :: {semidom,t2_space}" shows "f has_prod s \<Longrightarrow> s = prodinf f" [PROOF STATE] proof (prove) goal (1 subgoal): 1. f has_prod s \<Longrightarrow> s = prodinf f [PROOF STEP] by (simp add: has_prod_unique2 prodinf_def the_equality)
[STATEMENT] lemma Ri_subset_\<Gamma>: "Ri N \<subseteq> \<Gamma>" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Ri N \<subseteq> \<Gamma> [PROOF STEP] unfolding Ri_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. {\<gamma> \<in> \<Gamma>. redundant_infer N \<gamma>} \<subseteq> \<Gamma> [PROOF STEP] by blast
From Hammer Require Import Hammer. Require Import Rbase. Require Import Rfunctions. Require Import SeqSeries. Require Import Rtrigo1. Require Import Ranalysis. Local Open Scope R_scope. Definition Newton_integrable (f:R -> R) (a b:R) : Type := { g:R -> R | antiderivative f g a b \/ antiderivative f g b a }. Definition NewtonInt (f:R -> R) (a b:R) (pr:Newton_integrable f a b) : R := let (g,_) := pr in g b - g a. Lemma FTCN_step1 : forall (f:Differential) (a b:R), Newton_integrable (fun x:R => derive_pt f x (cond_diff f x)) a b. Proof. hammer_hook "NewtonInt" "NewtonInt.FTCN_step1". intros f a b; unfold Newton_integrable; exists (d1 f); unfold antiderivative; intros; case (Rle_dec a b); intro; [ left; split; [ intros; exists (cond_diff f x); reflexivity | assumption ] | right; split; [ intros; exists (cond_diff f x); reflexivity | auto with real ] ]. Defined. Lemma FTC_Newton : forall (f:Differential) (a b:R), NewtonInt (fun x:R => derive_pt f x (cond_diff f x)) a b (FTCN_step1 f a b) = f b - f a. Proof. hammer_hook "NewtonInt" "NewtonInt.FTC_Newton". intros; unfold NewtonInt; reflexivity. Qed. Lemma NewtonInt_P1 : forall (f:R -> R) (a:R), Newton_integrable f a a. Proof. hammer_hook "NewtonInt" "NewtonInt.NewtonInt_P1". intros f a; unfold Newton_integrable; exists (fct_cte (f a) * id)%F; left; unfold antiderivative; split. intros; assert (H1 : derivable_pt (fct_cte (f a) * id) x). apply derivable_pt_mult. apply derivable_pt_const. apply derivable_pt_id. exists H1; assert (H2 : x = a). elim H; intros; apply Rle_antisym; assumption. symmetry ; apply derive_pt_eq_0; replace (f x) with (0 * id x + fct_cte (f a) x * 1); [ apply (derivable_pt_lim_mult (fct_cte (f a)) id x); [ apply derivable_pt_lim_const | apply derivable_pt_lim_id ] | unfold id, fct_cte; rewrite H2; ring ]. right; reflexivity. Qed. Lemma NewtonInt_P2 : forall (f:R -> R) (a:R), NewtonInt f a a (NewtonInt_P1 f a) = 0. Proof. hammer_hook "NewtonInt" "NewtonInt.NewtonInt_P2". intros; unfold NewtonInt; simpl; unfold mult_fct, fct_cte, id. destruct NewtonInt_P1 as [g _]. now apply Rminus_diag_eq. Qed. Lemma NewtonInt_P3 : forall (f:R -> R) (a b:R) (X:Newton_integrable f a b), Newton_integrable f b a. Proof. hammer_hook "NewtonInt" "NewtonInt.NewtonInt_P3". unfold Newton_integrable; intros; elim X; intros g H; exists g; tauto. Defined. Lemma NewtonInt_P4 : forall (f:R -> R) (a b:R) (pr:Newton_integrable f a b), NewtonInt f a b pr = - NewtonInt f b a (NewtonInt_P3 f a b pr). Proof. hammer_hook "NewtonInt" "NewtonInt.NewtonInt_P4". intros f a b (x,H). unfold NewtonInt, NewtonInt_P3; simpl; ring. Qed. Lemma NewtonInt_P5 : forall (f g:R -> R) (l a b:R), Newton_integrable f a b -> Newton_integrable g a b -> Newton_integrable (fun x:R => l * f x + g x) a b. Proof. hammer_hook "NewtonInt" "NewtonInt.NewtonInt_P5". unfold Newton_integrable; intros f g l a b X X0; elim X; intros x p; elim X0; intros x0 p0; exists (fun y:R => l * x y + x0 y). elim p; intro. elim p0; intro. left; unfold antiderivative; unfold antiderivative in H, H0; elim H; clear H; intros; elim H0; clear H0; intros H0 _. split. intros; elim (H _ H2); elim (H0 _ H2); intros. assert (H5 : derivable_pt (fun y:R => l * x y + x0 y) x1). reg. exists H5; symmetry ; reg; rewrite <- H3; rewrite <- H4; reflexivity. assumption. unfold antiderivative in H, H0; elim H; elim H0; intros; elim H4; intro. elim (Rlt_irrefl _ (Rlt_le_trans _ _ _ H5 H2)). left; rewrite <- H5; unfold antiderivative; split. intros; elim H6; intros; assert (H9 : x1 = a). apply Rle_antisym; assumption. assert (H10 : a <= x1 <= b). split; right; [ symmetry ; assumption | rewrite <- H5; assumption ]. assert (H11 : b <= x1 <= a). split; right; [ rewrite <- H5; symmetry ; assumption | assumption ]. assert (H12 : derivable_pt x x1). unfold derivable_pt; exists (f x1); elim (H3 _ H10); intros; eapply derive_pt_eq_1; symmetry ; apply H12. assert (H13 : derivable_pt x0 x1). unfold derivable_pt; exists (g x1); elim (H1 _ H11); intros; eapply derive_pt_eq_1; symmetry ; apply H13. assert (H14 : derivable_pt (fun y:R => l * x y + x0 y) x1). reg. exists H14; symmetry ; reg. assert (H15 : derive_pt x0 x1 H13 = g x1). elim (H1 _ H11); intros; rewrite H15; apply pr_nu. assert (H16 : derive_pt x x1 H12 = f x1). elim (H3 _ H10); intros; rewrite H16; apply pr_nu. rewrite H15; rewrite H16; ring. right; reflexivity. elim p0; intro. unfold antiderivative in H, H0; elim H; elim H0; intros; elim H4; intro. elim (Rlt_irrefl _ (Rlt_le_trans _ _ _ H5 H2)). left; rewrite H5; unfold antiderivative; split. intros; elim H6; intros; assert (H9 : x1 = a). apply Rle_antisym; assumption. assert (H10 : a <= x1 <= b). split; right; [ symmetry ; assumption | rewrite H5; assumption ]. assert (H11 : b <= x1 <= a). split; right; [ rewrite H5; symmetry ; assumption | assumption ]. assert (H12 : derivable_pt x x1). unfold derivable_pt; exists (f x1); elim (H3 _ H11); intros; eapply derive_pt_eq_1; symmetry ; apply H12. assert (H13 : derivable_pt x0 x1). unfold derivable_pt; exists (g x1); elim (H1 _ H10); intros; eapply derive_pt_eq_1; symmetry ; apply H13. assert (H14 : derivable_pt (fun y:R => l * x y + x0 y) x1). reg. exists H14; symmetry ; reg. assert (H15 : derive_pt x0 x1 H13 = g x1). elim (H1 _ H10); intros; rewrite H15; apply pr_nu. assert (H16 : derive_pt x x1 H12 = f x1). elim (H3 _ H11); intros; rewrite H16; apply pr_nu. rewrite H15; rewrite H16; ring. right; reflexivity. right; unfold antiderivative; unfold antiderivative in H, H0; elim H; clear H; intros; elim H0; clear H0; intros H0 _; split. intros; elim (H _ H2); elim (H0 _ H2); intros. assert (H5 : derivable_pt (fun y:R => l * x y + x0 y) x1). reg. exists H5; symmetry ; reg; rewrite <- H3; rewrite <- H4; reflexivity. assumption. Defined. Lemma antiderivative_P1 : forall (f g F G:R -> R) (l a b:R), antiderivative f F a b -> antiderivative g G a b -> antiderivative (fun x:R => l * f x + g x) (fun x:R => l * F x + G x) a b. Proof. hammer_hook "NewtonInt" "NewtonInt.antiderivative_P1". unfold antiderivative; intros; elim H; elim H0; clear H H0; intros; split. intros; elim (H _ H3); elim (H1 _ H3); intros. assert (H6 : derivable_pt (fun x:R => l * F x + G x) x). reg. exists H6; symmetry ; reg; rewrite <- H4; rewrite <- H5; ring. assumption. Qed. Lemma NewtonInt_P6 : forall (f g:R -> R) (l a b:R) (pr1:Newton_integrable f a b) (pr2:Newton_integrable g a b), NewtonInt (fun x:R => l * f x + g x) a b (NewtonInt_P5 f g l a b pr1 pr2) = l * NewtonInt f a b pr1 + NewtonInt g a b pr2. Proof. hammer_hook "NewtonInt" "NewtonInt.NewtonInt_P6". intros f g l a b pr1 pr2; unfold NewtonInt; destruct (NewtonInt_P5 f g l a b pr1 pr2) as (x,o); destruct pr1 as (x0,o0); destruct pr2 as (x1,o1); destruct (total_order_T a b) as [[Hlt|Heq]|Hgt]. elim o; intro. elim o0; intro. elim o1; intro. assert (H2 := antiderivative_P1 f g x0 x1 l a b H0 H1); assert (H3 := antiderivative_Ucte _ _ _ _ _ H H2); elim H3; intros; assert (H5 : a <= a <= b). split; [ right; reflexivity | left; assumption ]. assert (H6 : a <= b <= b). split; [ left; assumption | right; reflexivity ]. assert (H7 := H4 _ H5); assert (H8 := H4 _ H6); rewrite H7; rewrite H8; ring. unfold antiderivative in H1; elim H1; intros; elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H3 Hlt)). unfold antiderivative in H0; elim H0; intros; elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H2 Hlt)). unfold antiderivative in H; elim H; intros; elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H1 Hlt)). rewrite Heq; ring. elim o; intro. unfold antiderivative in H; elim H; intros; elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H1 Hgt)). elim o0; intro. unfold antiderivative in H0; elim H0; intros; elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H2 Hgt)). elim o1; intro. unfold antiderivative in H1; elim H1; intros; elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H3 Hgt)). assert (H2 := antiderivative_P1 f g x0 x1 l b a H0 H1); assert (H3 := antiderivative_Ucte _ _ _ _ _ H H2); elim H3; intros; assert (H5 : b <= a <= a). split; [ left; assumption | right; reflexivity ]. assert (H6 : b <= b <= a). split; [ right; reflexivity | left; assumption ]. assert (H7 := H4 _ H5); assert (H8 := H4 _ H6); rewrite H7; rewrite H8; ring. Qed. Lemma antiderivative_P2 : forall (f F0 F1:R -> R) (a b c:R), antiderivative f F0 a b -> antiderivative f F1 b c -> antiderivative f (fun x:R => match Rle_dec x b with | left _ => F0 x | right _ => F1 x + (F0 b - F1 b) end) a c. Proof. hammer_hook "NewtonInt" "NewtonInt.antiderivative_P2". intros; destruct H as (H,H1), H0 as (H0,H2); split. 2: apply Rle_trans with b; assumption. intros x (H3,H4); destruct (total_order_T x b) as [[Hlt|Heq]|Hgt]. assert (H5 : a <= x <= b). split; [ assumption | left; assumption ]. destruct (H _ H5) as (x0,H6). assert (H7 : derivable_pt_lim (fun x:R => match Rle_dec x b with | left _ => F0 x | right _ => F1 x + (F0 b - F1 b) end) x (f x)). unfold derivable_pt_lim. intros eps H9. assert (H7 : derive_pt F0 x x0 = f x) by (symmetry; assumption). destruct (derive_pt_eq_1 F0 x (f x) x0 H7 _ H9) as (x1,H10); set (D := Rmin x1 (b - x)). assert (H11 : 0 < D). unfold D, Rmin; case (Rle_dec x1 (b - x)); intro. apply (cond_pos x1). apply Rlt_Rminus; assumption. exists (mkposreal _ H11); intros h H12 H13. case (Rle_dec x b) as [|[]]. case (Rle_dec (x + h) b) as [|[]]. apply H10. assumption. apply Rlt_le_trans with D; [ assumption | unfold D; apply Rmin_l ]. left; apply Rlt_le_trans with (x + D). apply Rplus_lt_compat_l; apply Rle_lt_trans with (Rabs h). apply RRle_abs. apply H13. apply Rplus_le_reg_l with (- x); rewrite <- Rplus_assoc; rewrite Rplus_opp_l; rewrite Rplus_0_l; rewrite Rplus_comm; unfold D; apply Rmin_r. left; assumption. assert (H8 : derivable_pt (fun x:R => match Rle_dec x b with | left _ => F0 x | right _ => F1 x + (F0 b - F1 b) end) x). unfold derivable_pt; exists (f x); apply H7. exists H8; symmetry ; apply derive_pt_eq_0; apply H7. assert (H5 : a <= x <= b). split; [ assumption | right; assumption ]. assert (H6 : b <= x <= c). split; [ right; symmetry ; assumption | assumption ]. elim (H _ H5); elim (H0 _ H6); intros; assert (H9 : derive_pt F0 x x1 = f x). symmetry ; assumption. assert (H10 : derive_pt F1 x x0 = f x). symmetry ; assumption. assert (H11 := derive_pt_eq_1 F0 x (f x) x1 H9); assert (H12 := derive_pt_eq_1 F1 x (f x) x0 H10); assert (H13 : derivable_pt_lim (fun x:R => match Rle_dec x b with | left _ => F0 x | right _ => F1 x + (F0 b - F1 b) end) x (f x)). unfold derivable_pt_lim; unfold derivable_pt_lim in H11, H12; intros; elim (H11 _ H13); elim (H12 _ H13); intros; set (D := Rmin x2 x3); assert (H16 : 0 < D). unfold D; unfold Rmin; case (Rle_dec x2 x3); intro. apply (cond_pos x2). apply (cond_pos x3). exists (mkposreal _ H16); intros; case (Rle_dec x b) as [|[]]. case (Rle_dec (x + h) b); intro. apply H15. assumption. apply Rlt_le_trans with D; [ assumption | unfold D; apply Rmin_r ]. replace (F1 (x + h) + (F0 b - F1 b) - F0 x) with (F1 (x + h) - F1 x). apply H14. assumption. apply Rlt_le_trans with D; [ assumption | unfold D; apply Rmin_l ]. rewrite Heq; ring. right; assumption. assert (H14 : derivable_pt (fun x:R => match Rle_dec x b with | left _ => F0 x | right _ => F1 x + (F0 b - F1 b) end) x). unfold derivable_pt; exists (f x); apply H13. exists H14; symmetry ; apply derive_pt_eq_0; apply H13. assert (H5 : b <= x <= c). split; [ left; assumption | assumption ]. assert (H6 := H0 _ H5); elim H6; clear H6; intros; assert (H7 : derivable_pt_lim (fun x:R => match Rle_dec x b with | left _ => F0 x | right _ => F1 x + (F0 b - F1 b) end) x (f x)). unfold derivable_pt_lim; assert (H7 : derive_pt F1 x x0 = f x). symmetry ; assumption. assert (H8 := derive_pt_eq_1 F1 x (f x) x0 H7); unfold derivable_pt_lim in H8; intros; elim (H8 _ H9); intros; set (D := Rmin x1 (x - b)); assert (H11 : 0 < D). unfold D; unfold Rmin; case (Rle_dec x1 (x - b)); intro. apply (cond_pos x1). apply Rlt_Rminus; assumption. exists (mkposreal _ H11); intros; destruct (Rle_dec x b) as [Hle|Hnle]. elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ Hle Hgt)). destruct (Rle_dec (x + h) b) as [Hle'|Hnle']. cut (b < x + h). intro; elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ Hle' H14)). apply Rplus_lt_reg_l with (- h - b); replace (- h - b + b) with (- h); [ idtac | ring ]; replace (- h - b + (x + h)) with (x - b); [ idtac | ring ]; apply Rle_lt_trans with (Rabs h). rewrite <- Rabs_Ropp; apply RRle_abs. apply Rlt_le_trans with D. apply H13. unfold D; apply Rmin_r. replace (F1 (x + h) + (F0 b - F1 b) - (F1 x + (F0 b - F1 b))) with (F1 (x + h) - F1 x); [ idtac | ring ]; apply H10. assumption. apply Rlt_le_trans with D. assumption. unfold D; apply Rmin_l. assert (H8 : derivable_pt (fun x:R => match Rle_dec x b with | left _ => F0 x | right _ => F1 x + (F0 b - F1 b) end) x). unfold derivable_pt; exists (f x); apply H7. exists H8; symmetry ; apply derive_pt_eq_0; apply H7. Qed. Lemma antiderivative_P3 : forall (f F0 F1:R -> R) (a b c:R), antiderivative f F0 a b -> antiderivative f F1 c b -> antiderivative f F1 c a \/ antiderivative f F0 a c. Proof. hammer_hook "NewtonInt" "NewtonInt.antiderivative_P3". intros; unfold antiderivative in H, H0; elim H; clear H; elim H0; clear H0; intros; destruct (total_order_T a c) as [[Hle|Heq]|Hgt]. right; unfold antiderivative; split. intros; apply H1; elim H3; intros; split; [ assumption | apply Rle_trans with c; assumption ]. left; assumption. right; unfold antiderivative; split. intros; apply H1; elim H3; intros; split; [ assumption | apply Rle_trans with c; assumption ]. right; assumption. left; unfold antiderivative; split. intros; apply H; elim H3; intros; split; [ assumption | apply Rle_trans with a; assumption ]. left; assumption. Qed. Lemma antiderivative_P4 : forall (f F0 F1:R -> R) (a b c:R), antiderivative f F0 a b -> antiderivative f F1 a c -> antiderivative f F1 b c \/ antiderivative f F0 c b. Proof. hammer_hook "NewtonInt" "NewtonInt.antiderivative_P4". intros; unfold antiderivative in H, H0; elim H; clear H; elim H0; clear H0; intros; destruct (total_order_T c b) as [[Hlt|Heq]|Hgt]. right; unfold antiderivative; split. intros; apply H1; elim H3; intros; split; [ apply Rle_trans with c; assumption | assumption ]. left; assumption. right; unfold antiderivative; split. intros; apply H1; elim H3; intros; split; [ apply Rle_trans with c; assumption | assumption ]. right; assumption. left; unfold antiderivative; split. intros; apply H; elim H3; intros; split; [ apply Rle_trans with b; assumption | assumption ]. left; assumption. Qed. Lemma NewtonInt_P7 : forall (f:R -> R) (a b c:R), a < b -> b < c -> Newton_integrable f a b -> Newton_integrable f b c -> Newton_integrable f a c. Proof. hammer_hook "NewtonInt" "NewtonInt.NewtonInt_P7". unfold Newton_integrable; intros f a b c Hab Hbc X X0; elim X; clear X; intros F0 H0; elim X0; clear X0; intros F1 H1; set (g := fun x:R => match Rle_dec x b with | left _ => F0 x | right _ => F1 x + (F0 b - F1 b) end); exists g; left; unfold g; apply antiderivative_P2. elim H0; intro. assumption. unfold antiderivative in H; elim H; clear H; intros; elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H2 Hab)). elim H1; intro. assumption. unfold antiderivative in H; elim H; clear H; intros; elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H2 Hbc)). Qed. Lemma NewtonInt_P8 : forall (f:R -> R) (a b c:R), Newton_integrable f a b -> Newton_integrable f b c -> Newton_integrable f a c. Proof. hammer_hook "NewtonInt" "NewtonInt.NewtonInt_P8". intros. elim X; intros F0 H0. elim X0; intros F1 H1. destruct (total_order_T a b) as [[Hlt|Heq]|Hgt]. destruct (total_order_T b c) as [[Hlt'|Heq']|Hgt']. unfold Newton_integrable; exists (fun x:R => match Rle_dec x b with | left _ => F0 x | right _ => F1 x + (F0 b - F1 b) end). elim H0; intro. elim H1; intro. left; apply antiderivative_P2; assumption. unfold antiderivative in H2; elim H2; clear H2; intros _ H2. elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H2 Hlt')). unfold antiderivative in H; elim H; clear H; intros _ H. elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H Hlt)). rewrite Heq' in X; apply X. destruct (total_order_T a c) as [[Hlt''|Heq'']|Hgt'']. unfold Newton_integrable; exists F0. left. elim H1; intro. unfold antiderivative in H; elim H; clear H; intros _ H. elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H Hgt')). elim H0; intro. assert (H3 := antiderivative_P3 f F0 F1 a b c H2 H). elim H3; intro. unfold antiderivative in H4; elim H4; clear H4; intros _ H4. elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H4 Hlt'')). assumption. unfold antiderivative in H2; elim H2; clear H2; intros _ H2. elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H2 Hlt)). rewrite Heq''; apply NewtonInt_P1. unfold Newton_integrable; exists F1. right. elim H1; intro. unfold antiderivative in H; elim H; clear H; intros _ H. elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H Hgt')). elim H0; intro. assert (H3 := antiderivative_P3 f F0 F1 a b c H2 H). elim H3; intro. assumption. unfold antiderivative in H4; elim H4; clear H4; intros _ H4. elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H4 Hgt'')). unfold antiderivative in H2; elim H2; clear H2; intros _ H2. elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H2 Hlt)). rewrite Heq; apply X0. destruct (total_order_T b c) as [[Hlt'|Heq']|Hgt']. destruct (total_order_T a c) as [[Hlt''|Heq'']|Hgt'']. unfold Newton_integrable; exists F1. left. elim H1; intro. elim H0; intro. unfold antiderivative in H2; elim H2; clear H2; intros _ H2. elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H2 Hgt)). assert (H3 := antiderivative_P4 f F0 F1 b a c H2 H). elim H3; intro. assumption. unfold antiderivative in H4; elim H4; clear H4; intros _ H4. elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H4 Hlt'')). unfold antiderivative in H; elim H; clear H; intros _ H. elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H Hlt')). rewrite Heq''; apply NewtonInt_P1. unfold Newton_integrable; exists F0. right. elim H0; intro. unfold antiderivative in H; elim H; clear H; intros _ H. elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H Hgt)). elim H1; intro. assert (H3 := antiderivative_P4 f F0 F1 b a c H H2). elim H3; intro. unfold antiderivative in H4; elim H4; clear H4; intros _ H4. elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H4 Hgt'')). assumption. unfold antiderivative in H2; elim H2; clear H2; intros _ H2. elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H2 Hlt')). rewrite Heq' in X; apply X. assert (X1 := NewtonInt_P3 f a b X). assert (X2 := NewtonInt_P3 f b c X0). apply NewtonInt_P3. apply NewtonInt_P7 with b; assumption. Qed. Lemma NewtonInt_P9 : forall (f:R -> R) (a b c:R) (pr1:Newton_integrable f a b) (pr2:Newton_integrable f b c), NewtonInt f a c (NewtonInt_P8 f a b c pr1 pr2) = NewtonInt f a b pr1 + NewtonInt f b c pr2. Proof. hammer_hook "NewtonInt" "NewtonInt.NewtonInt_P9". intros; unfold NewtonInt. case (NewtonInt_P8 f a b c pr1 pr2) as (x,Hor). case pr1 as (x0,Hor0). case pr2 as (x1,Hor1). destruct (total_order_T a b) as [[Hlt|Heq]|Hgt]. destruct (total_order_T b c) as [[Hlt'|Heq']|Hgt']. case Hor0; intro. case Hor1; intro. case Hor; intro. assert (H2 := antiderivative_P2 f x0 x1 a b c H H0). assert (H3 := antiderivative_Ucte f x (fun x:R => match Rle_dec x b with | left _ => x0 x | right _ => x1 x + (x0 b - x1 b) end) a c H1 H2). elim H3; intros. assert (H5 : a <= a <= c). split; [ right; reflexivity | left; apply Rlt_trans with b; assumption ]. assert (H6 : a <= c <= c). split; [ left; apply Rlt_trans with b; assumption | right; reflexivity ]. rewrite (H4 _ H5); rewrite (H4 _ H6). destruct (Rle_dec a b) as [Hlea|Hnlea]. destruct (Rle_dec c b) as [Hlec|Hnlec]. elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ Hlec Hlt')). ring. elim Hnlea; left; assumption. unfold antiderivative in H1; elim H1; clear H1; intros _ H1. elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H1 (Rlt_trans _ _ _ Hlt Hlt'))). unfold antiderivative in H0; elim H0; clear H0; intros _ H0. elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H0 Hlt')). unfold antiderivative in H; elim H; clear H; intros _ H. elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H Hlt)). rewrite <- Heq'. unfold Rminus; rewrite Rplus_opp_r; rewrite Rplus_0_r. rewrite <- Heq' in Hor. elim Hor0; intro. elim Hor; intro. assert (H1 := antiderivative_Ucte f x x0 a b H0 H). elim H1; intros. rewrite (H2 b). rewrite (H2 a). ring. split; [ right; reflexivity | left; assumption ]. split; [ left; assumption | right; reflexivity ]. unfold antiderivative in H0; elim H0; clear H0; intros _ H0. elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H0 Hlt)). unfold antiderivative in H; elim H; clear H; intros _ H. elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H Hlt)). elim Hor1; intro. unfold antiderivative in H; elim H; clear H; intros _ H. elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H Hgt')). elim Hor0; intro. elim Hor; intro. assert (H2 := antiderivative_P2 f x x1 a c b H1 H). assert (H3 := antiderivative_Ucte _ _ _ a b H0 H2). elim H3; intros. rewrite (H4 a). rewrite (H4 b). destruct (Rle_dec b c) as [Hle|Hnle]. elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ Hle Hgt')). destruct (Rle_dec a c) as [Hle'|Hnle']. ring. elim Hnle'; unfold antiderivative in H1; elim H1; intros; assumption. split; [ left; assumption | right; reflexivity ]. split; [ right; reflexivity | left; assumption ]. assert (H2 := antiderivative_P2 _ _ _ _ _ _ H1 H0). assert (H3 := antiderivative_Ucte _ _ _ c b H H2). elim H3; intros. rewrite (H4 c). rewrite (H4 b). destruct (Rle_dec b a) as [Hle|Hnle]. elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ Hle Hlt)). destruct (Rle_dec c a) as [Hle'|[]]. ring. unfold antiderivative in H1; elim H1; intros; assumption. split; [ left; assumption | right; reflexivity ]. split; [ right; reflexivity | left; assumption ]. unfold antiderivative in H0; elim H0; clear H0; intros _ H0. elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H0 Hlt)). rewrite Heq in Hor |- *. elim Hor; intro. elim Hor1; intro. assert (H1 := antiderivative_Ucte _ _ _ b c H H0). elim H1; intros. assert (H3 : b <= c). unfold antiderivative in H; elim H; intros; assumption. rewrite (H2 b). rewrite (H2 c). ring. split; [ assumption | right; reflexivity ]. split; [ right; reflexivity | assumption ]. assert (H1 : b = c). unfold antiderivative in H, H0; elim H; elim H0; intros; apply Rle_antisym; assumption. rewrite H1; ring. elim Hor1; intro. assert (H1 : b = c). unfold antiderivative in H, H0; elim H; elim H0; intros; apply Rle_antisym; assumption. rewrite H1; ring. assert (H1 := antiderivative_Ucte _ _ _ c b H H0). elim H1; intros. assert (H3 : c <= b). unfold antiderivative in H; elim H; intros; assumption. rewrite (H2 c). rewrite (H2 b). ring. split; [ assumption | right; reflexivity ]. split; [ right; reflexivity | assumption ]. destruct (total_order_T b c) as [[Hlt'|Heq']|Hgt']. elim Hor0; intro. unfold antiderivative in H; elim H; clear H; intros _ H. elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H Hgt)). elim Hor1; intro. elim Hor; intro. assert (H2 := antiderivative_P2 _ _ _ _ _ _ H H1). assert (H3 := antiderivative_Ucte _ _ _ b c H0 H2). elim H3; intros. rewrite (H4 b). rewrite (H4 c). case (Rle_dec b a) as [|[]]. case (Rle_dec c a) as [|]. assert (H5 : a = c). unfold antiderivative in H1; elim H1; intros; apply Rle_antisym; assumption. rewrite H5; ring. ring. left; assumption. split; [ left; assumption | right; reflexivity ]. split; [ right; reflexivity | left; assumption ]. assert (H2 := antiderivative_P2 _ _ _ _ _ _ H0 H1). assert (H3 := antiderivative_Ucte _ _ _ b a H H2). elim H3; intros. rewrite (H4 a). rewrite (H4 b). case (Rle_dec b c) as [|[]]. case (Rle_dec a c) as [|]. assert (H5 : a = c). unfold antiderivative in H1; elim H1; intros; apply Rle_antisym; assumption. rewrite H5; ring. ring. left; assumption. split; [ right; reflexivity | left; assumption ]. split; [ left; assumption | right; reflexivity ]. unfold antiderivative in H0; elim H0; clear H0; intros _ H0. elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H0 Hlt')). rewrite <- Heq'. unfold Rminus; rewrite Rplus_opp_r; rewrite Rplus_0_r. rewrite <- Heq' in Hor. elim Hor0; intro. unfold antiderivative in H; elim H; clear H; intros _ H. elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H Hgt)). elim Hor; intro. unfold antiderivative in H0; elim H0; clear H0; intros _ H0. elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H0 Hgt)). assert (H1 := antiderivative_Ucte f x x0 b a H0 H). elim H1; intros. rewrite (H2 b). rewrite (H2 a). ring. split; [ left; assumption | right; reflexivity ]. split; [ right; reflexivity | left; assumption ]. elim Hor0; intro. unfold antiderivative in H; elim H; clear H; intros _ H. elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H Hgt)). elim Hor1; intro. unfold antiderivative in H0; elim H0; clear H0; intros _ H0. elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H0 Hgt')). elim Hor; intro. unfold antiderivative in H1; elim H1; clear H1; intros _ H1. elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H1 (Rlt_trans _ _ _ Hgt' Hgt))). assert (H2 := antiderivative_P2 _ _ _ _ _ _ H0 H). assert (H3 := antiderivative_Ucte _ _ _ c a H1 H2). elim H3; intros. assert (H5 : c <= a). unfold antiderivative in H1; elim H1; intros; assumption. rewrite (H4 c). rewrite (H4 a). destruct (Rle_dec a b) as [Hle|Hnle]. elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ Hle Hgt)). destruct (Rle_dec c b) as [|[]]. ring. left; assumption. split; [ assumption | right; reflexivity ]. split; [ right; reflexivity | assumption ]. Qed.
# -*- coding: utf-8 -*- from allpy import eq2p import numpy as np import matplotlib.pyplot as plt # define functions def v(si, sj): return 9 / 10 + np.exp(-30 * (si + sj)) / (np.exp(-40) + np.exp(-30 * (si + sj))) def c1(si): return si ** 2 def c2(si): return si # use the package eq = eq2p(v=(v, v), c=(c1, c2), b=1) # get objects to plot S = eq["s"] Sbar = eq["sbar"] G1, G2 = eq["cdf"] # plot CDFs plt.plot(S, G1) plt.plot(S, G2) plt.legend(["$G_1$", "$G_2$"]) plt.xlabel("Score") plt.ylim(0, 1) plt.xlim(0, Sbar) plt.show()
\subsection{Type I and type II errors}
[STATEMENT] lemma n_omega_mult: "n(x\<^sup>\<omega> * y) = n(x\<^sup>\<omega>)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. n (x\<^sup>\<omega> * y) = n (x\<^sup>\<omega>) [PROOF STEP] by (simp add: n_isotone n_mult_left_upper_bound omega_sub_vector order.eq_iff)
%% template.tex %% from %% bare_conf.tex %% V1.4b %% 2015/08/26 %% by Michael Shell %% See: %% http://www.michaelshell.org/ %% for current contact information. %% %% This is a skeleton file demonstrating the use of IEEEtran.cls %% (requires IEEEtran.cls version 1.8b or later) with an IEEE %% conference paper. %% %% Support sites: %% http://www.michaelshell.org/tex/ieeetran/ %% http://www.ctan.org/pkg/ieeetran %% and %% http://www.ieee.org/ %%************************************************************************* %% Legal Notice: %% This code is offered as-is without any warranty either expressed or %% implied; without even the implied warranty of MERCHANTABILITY or %% FITNESS FOR A PARTICULAR PURPOSE! %% User assumes all risk. %% In no event shall the IEEE or any contributor to this code be liable for %% any damages or losses, including, but not limited to, incidental, %% consequential, or any other damages, resulting from the use or misuse %% of any information contained here. %% %% All comments are the opinions of their respective authors and are not %% necessarily endorsed by the IEEE. %% %% This work is distributed under the LaTeX Project Public License (LPPL) %% ( http://www.latex-project.org/ ) version 1.3, and may be freely used, %% distributed and modified. A copy of the LPPL, version 1.3, is included %% in the base LaTeX documentation of all distributions of LaTeX released %% 2003/12/01 or later. %% Retain all contribution notices and credits. %% ** Modified files should be clearly indicated as such, including ** %% ** renaming them and changing author support contact information. ** %%************************************************************************* % *** Authors should verify (and, if needed, correct) their LaTeX system *** % *** with the testflow diagnostic prior to trusting their LaTeX platform *** % *** with production work. The IEEE's font choices and paper sizes can *** % *** trigger bugs that do not appear when using other class files. *** *** % The testflow support page is at: % http://www.michaelshell.org/tex/testflow/ \documentclass[conference,final,]{IEEEtran} % Some Computer Society conferences also require the compsoc mode option, % but others use the standard conference format. % % If IEEEtran.cls has not been installed into the LaTeX system files, % manually specify the path to it like: % \documentclass[conference]{../sty/IEEEtran} % Some very useful LaTeX packages include: % (uncomment the ones you want to load) % *** MISC UTILITY PACKAGES *** % %\usepackage{ifpdf} % Heiko Oberdiek's ifpdf.sty is very useful if you need conditional % compilation based on whether the output is pdf or dvi. % usage: % \ifpdf % % pdf code % \else % % dvi code % \fi % The latest version of ifpdf.sty can be obtained from: % http://www.ctan.org/pkg/ifpdf % Also, note that IEEEtran.cls V1.7 and later provides a builtin % \ifCLASSINFOpdf conditional that works the same way. % When switching from latex to pdflatex and vice-versa, the compiler may % have to be run twice to clear warning/error messages. % *** CITATION PACKAGES *** % %\usepackage{cite} % cite.sty was written by Donald Arseneau % V1.6 and later of IEEEtran pre-defines the format of the cite.sty package % \cite{} output to follow that of the IEEE. Loading the cite package will % result in citation numbers being automatically sorted and properly % "compressed/ranged". e.g., [1], [9], [2], [7], [5], [6] without using % cite.sty will become [1], [2], [5]--[7], [9] using cite.sty. cite.sty's % \cite will automatically add leading space, if needed. Use cite.sty's % noadjust option (cite.sty V3.8 and later) if you want to turn this off % such as if a citation ever needs to be enclosed in parenthesis. % cite.sty is already installed on most LaTeX systems. Be sure and use % version 5.0 (2009-03-20) and later if using hyperref.sty. % The latest version can be obtained at: % http://www.ctan.org/pkg/cite % The documentation is contained in the cite.sty file itself. % *** GRAPHICS RELATED PACKAGES *** % \ifCLASSINFOpdf % \usepackage[pdftex]{graphicx} % declare the path(s) where your graphic files are % \graphicspath{{../pdf/}{../jpeg/}} % and their extensions so you won't have to specify these with % every instance of \includegraphics % \DeclareGraphicsExtensions{.pdf,.jpeg,.png} \else % or other class option (dvipsone, dvipdf, if not using dvips). graphicx % will default to the driver specified in the system graphics.cfg if no % driver is specified. % \usepackage[dvips]{graphicx} % declare the path(s) where your graphic files are % \graphicspath{{../eps/}} % and their extensions so you won't have to specify these with % every instance of \includegraphics % \DeclareGraphicsExtensions{.eps} \fi % graphicx was written by David Carlisle and Sebastian Rahtz. It is % required if you want graphics, photos, etc. graphicx.sty is already % installed on most LaTeX systems. The latest version and documentation % can be obtained at: % http://www.ctan.org/pkg/graphicx % Another good source of documentation is "Using Imported Graphics in % LaTeX2e" by Keith Reckdahl which can be found at: % http://www.ctan.org/pkg/epslatex % % latex, and pdflatex in dvi mode, support graphics in encapsulated % postscript (.eps) format. pdflatex in pdf mode supports graphics % in .pdf, .jpeg, .png and .mps (metapost) formats. Users should ensure % that all non-photo figures use a vector format (.eps, .pdf, .mps) and % not a bitmapped formats (.jpeg, .png). The IEEE frowns on bitmapped formats % which can result in "jaggedy"/blurry rendering of lines and letters as % well as large increases in file sizes. % % You can find documentation about the pdfTeX application at: % http://www.tug.org/applications/pdftex % *** MATH PACKAGES *** % %\usepackage{amsmath} % A popular package from the American Mathematical Society that provides % many useful and powerful commands for dealing with mathematics. % % Note that the amsmath package sets \interdisplaylinepenalty to 10000 % thus preventing page breaks from occurring within multiline equations. Use: %\interdisplaylinepenalty=2500 % after loading amsmath to restore such page breaks as IEEEtran.cls normally % does. amsmath.sty is already installed on most LaTeX systems. The latest % version and documentation can be obtained at: % http://www.ctan.org/pkg/amsmath % *** SPECIALIZED LIST PACKAGES *** % %\usepackage{algorithmic} % algorithmic.sty was written by Peter Williams and Rogerio Brito. % This package provides an algorithmic environment fo describing algorithms. % You can use the algorithmic environment in-text or within a figure % environment to provide for a floating algorithm. Do NOT use the algorithm % floating environment provided by algorithm.sty (by the same authors) or % algorithm2e.sty (by Christophe Fiorio) as the IEEE does not use dedicated % algorithm float types and packages that provide these will not provide % correct IEEE style captions. The latest version and documentation of % algorithmic.sty can be obtained at: % http://www.ctan.org/pkg/algorithms % Also of interest may be the (relatively newer and more customizable) % algorithmicx.sty package by Szasz Janos: % http://www.ctan.org/pkg/algorithmicx % *** ALIGNMENT PACKAGES *** % %\usepackage{array} % Frank Mittelbach's and David Carlisle's array.sty patches and improves % the standard LaTeX2e array and tabular environments to provide better % appearance and additional user controls. As the default LaTeX2e table % generation code is lacking to the point of almost being broken with % respect to the quality of the end results, all users are strongly % advised to use an enhanced (at the very least that provided by array.sty) % set of table tools. array.sty is already installed on most systems. The % latest version and documentation can be obtained at: % http://www.ctan.org/pkg/array % IEEEtran contains the IEEEeqnarray family of commands that can be used to % generate multiline equations as well as matrices, tables, etc., of high % quality. % *** SUBFIGURE PACKAGES *** %\ifCLASSOPTIONcompsoc % \usepackage[caption=false,font=normalsize,labelfont=sf,textfont=sf]{subfig} %\else % \usepackage[caption=false,font=footnotesize]{subfig} %\fi % subfig.sty, written by Steven Douglas Cochran, is the modern replacement % for subfigure.sty, the latter of which is no longer maintained and is % incompatible with some LaTeX packages including fixltx2e. However, % subfig.sty requires and automatically loads Axel Sommerfeldt's caption.sty % which will override IEEEtran.cls' handling of captions and this will result % in non-IEEE style figure/table captions. To prevent this problem, be sure % and invoke subfig.sty's "caption=false" package option (available since % subfig.sty version 1.3, 2005/06/28) as this is will preserve IEEEtran.cls % handling of captions. % Note that the Computer Society format requires a larger sans serif font % than the serif footnote size font used in traditional IEEE formatting % and thus the need to invoke different subfig.sty package options depending % on whether compsoc mode has been enabled. % % The latest version and documentation of subfig.sty can be obtained at: % http://www.ctan.org/pkg/subfig % *** FLOAT PACKAGES *** % %\usepackage{fixltx2e} % fixltx2e, the successor to the earlier fix2col.sty, was written by % Frank Mittelbach and David Carlisle. This package corrects a few problems % in the LaTeX2e kernel, the most notable of which is that in current % LaTeX2e releases, the ordering of single and double column floats is not % guaranteed to be preserved. Thus, an unpatched LaTeX2e can allow a % single column figure to be placed prior to an earlier double column % figure. % Be aware that LaTeX2e kernels dated 2015 and later have fixltx2e.sty's % corrections already built into the system in which case a warning will % be issued if an attempt is made to load fixltx2e.sty as it is no longer % needed. % The latest version and documentation can be found at: % http://www.ctan.org/pkg/fixltx2e %\usepackage{stfloats} % stfloats.sty was written by Sigitas Tolusis. This package gives LaTeX2e % the ability to do double column floats at the bottom of the page as well % as the top. (e.g., "\begin{figure*}[!b]" is not normally possible in % LaTeX2e). It also provides a command: %\fnbelowfloat % to enable the placement of footnotes below bottom floats (the standard % LaTeX2e kernel puts them above bottom floats). This is an invasive package % which rewrites many portions of the LaTeX2e float routines. It may not work % with other packages that modify the LaTeX2e float routines. The latest % version and documentation can be obtained at: % http://www.ctan.org/pkg/stfloats % Do not use the stfloats baselinefloat ability as the IEEE does not allow % \baselineskip to stretch. Authors submitting work to the IEEE should note % that the IEEE rarely uses double column equations and that authors should try % to avoid such use. Do not be tempted to use the cuted.sty or midfloat.sty % packages (also by Sigitas Tolusis) as the IEEE does not format its papers in % such ways. % Do not attempt to use stfloats with fixltx2e as they are incompatible. % Instead, use Morten Hogholm'a dblfloatfix which combines the features % of both fixltx2e and stfloats: % % \usepackage{dblfloatfix} % The latest version can be found at: % http://www.ctan.org/pkg/dblfloatfix % *** PDF, URL AND HYPERLINK PACKAGES *** % %\usepackage{url} % url.sty was written by Donald Arseneau. It provides better support for % handling and breaking URLs. url.sty is already installed on most LaTeX % systems. The latest version and documentation can be obtained at: % http://www.ctan.org/pkg/url % Basically, \url{my_url_here}. % *** Do not adjust lengths that control margins, column widths, etc. *** % *** Do not use packages that alter fonts (such as pslatex). *** % There should be no need to do such things with IEEEtran.cls V1.6 and later. % (Unless specifically asked to do so by the journal or conference you plan % to submit to, of course. ) %% BEGIN MY ADDITIONS %% \usepackage{longtable,booktabs} \usepackage{graphicx} % We will generate all images so they have a width \maxwidth. This means % that they will get their normal width if they fit onto the page, but % are scaled down if they would overflow the margins. \makeatletter \def\maxwidth{\ifdim\Gin@nat@width>\linewidth\linewidth \else\Gin@nat@width\fi} \makeatother \let\Oldincludegraphics\includegraphics \renewcommand{\includegraphics}[1]{\Oldincludegraphics[width=\maxwidth]{#1}} \usepackage[unicode=true]{hyperref} \hypersetup{ pdftitle={Assessing the Global COVID19 Impact on Air Transport with Open Data}, pdfborder={0 0 0}, breaklinks=true} \urlstyle{same} % don't use monospace font for urls % Pandoc toggle for numbering sections (defaults to be off) \setcounter{secnumdepth}{5} % Pandoc syntax highlighting \usepackage{color} \usepackage{fancyvrb} \newcommand{\VerbBar}{|} \newcommand{\VERB}{\Verb[commandchars=\\\{\}]} \DefineVerbatimEnvironment{Highlighting}{Verbatim}{commandchars=\\\{\}} % Add ',fontsize=\small' for more characters per line \usepackage{framed} \definecolor{shadecolor}{RGB}{248,248,248} \newenvironment{Shaded}{\begin{snugshade}}{\end{snugshade}} \newcommand{\AlertTok}[1]{\textcolor[rgb]{0.94,0.16,0.16}{#1}} \newcommand{\AnnotationTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}} \newcommand{\AttributeTok}[1]{\textcolor[rgb]{0.77,0.63,0.00}{#1}} \newcommand{\BaseNTok}[1]{\textcolor[rgb]{0.00,0.00,0.81}{#1}} \newcommand{\BuiltInTok}[1]{#1} \newcommand{\CharTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}} \newcommand{\CommentTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textit{#1}}} \newcommand{\CommentVarTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}} \newcommand{\ConstantTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}} \newcommand{\ControlFlowTok}[1]{\textcolor[rgb]{0.13,0.29,0.53}{\textbf{#1}}} \newcommand{\DataTypeTok}[1]{\textcolor[rgb]{0.13,0.29,0.53}{#1}} \newcommand{\DecValTok}[1]{\textcolor[rgb]{0.00,0.00,0.81}{#1}} \newcommand{\DocumentationTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}} \newcommand{\ErrorTok}[1]{\textcolor[rgb]{0.64,0.00,0.00}{\textbf{#1}}} \newcommand{\ExtensionTok}[1]{#1} \newcommand{\FloatTok}[1]{\textcolor[rgb]{0.00,0.00,0.81}{#1}} \newcommand{\FunctionTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}} \newcommand{\ImportTok}[1]{#1} \newcommand{\InformationTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}} \newcommand{\KeywordTok}[1]{\textcolor[rgb]{0.13,0.29,0.53}{\textbf{#1}}} \newcommand{\NormalTok}[1]{#1} \newcommand{\OperatorTok}[1]{\textcolor[rgb]{0.81,0.36,0.00}{\textbf{#1}}} \newcommand{\OtherTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{#1}} \newcommand{\PreprocessorTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textit{#1}}} \newcommand{\RegionMarkerTok}[1]{#1} \newcommand{\SpecialCharTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}} \newcommand{\SpecialStringTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}} \newcommand{\StringTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}} \newcommand{\VariableTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}} \newcommand{\VerbatimStringTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}} \newcommand{\WarningTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}} % Pandoc citation processing \newlength{\csllabelwidth} \setlength{\csllabelwidth}{3em} \newlength{\cslhangindent} \setlength{\cslhangindent}{1.5em} % for Pandoc 2.8 to 2.10.1 \newenvironment{cslreferences}% {}% {\par} % For Pandoc 2.11+ \newenvironment{CSLReferences}[3] % #1 hanging-ident, #2 entry spacing {% don't indent paragraphs \setlength{\parindent}{0pt} % turn on hanging indent if param 1 is 1 \ifodd #1 \everypar{\setlength{\hangindent}{\cslhangindent}}\ignorespaces\fi % set entry spacing \ifnum #2 > 0 \setlength{\parskip}{#2\baselineskip} \fi }% {} \usepackage{calc} % for calculating minipage widths \newcommand{\CSLBlock}[1]{#1\hfill\break} \newcommand{\CSLLeftMargin}[1]{\parbox[t]{\csllabelwidth}{#1}} \newcommand{\CSLRightInline}[1]{\parbox[t]{\linewidth - \csllabelwidth}{#1}} \newcommand{\CSLIndent}[1]{\hspace{\cslhangindent}#1} % Pandoc header \providecommand{\tightlist}{% \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}} %% END MY ADDITIONS %% \hyphenation{op-tical net-works semi-conduc-tor} \begin{document} % % paper title % Titles are generally capitalized except for words such as a, an, and, as, % at, but, by, for, in, nor, of, on, or, the, to and up, which are usually % not capitalized unless they are the first or last word of the title. % Linebreaks \\ can be used within to get better formatting as desired. % Do not put math or special symbols in the title. \title{Assessing the Global COVID19 Impact on Air Transport with Open Data} % author names and affiliations % use a multiple column layout for up to three different % affiliations \author{ %% ---- classic IEEETrans wide authors' list ---------------- % -- end affiliation.wide %% ---------------------------------------------------------- %% ---- classic IEEETrans one column per institution -------- %% -- beg if/affiliation.institution-columnar \IEEEauthorblockN{ %% -- beg for/affiliation.institution.author Rainer Koelle %% -- end for/affiliation.institution.author } \IEEEauthorblockA{Performance Review Unit\\ EUROCONTROL\\ Brussels (Belgium) %% -- beg for/affiliation.institution.author \\[email protected] %% -- end for/affiliation.institution.author } \and \IEEEauthorblockN{ %% -- beg for/affiliation.institution.author Fabio Lourenco Carneiro Barbosa %% -- end for/affiliation.institution.author } \IEEEauthorblockA{Subdepartment of Operations\\ DECEA\\ Rio de Janeiro (Brazil) %% -- beg for/affiliation.institution.author \\[email protected] %% -- end for/affiliation.institution.author } %% -- end for/affiliation.institution %% -- end if/affiliation.institution-columnar %% ---------------------------------------------------------- %% ---- one column per author, classic/default IEEETrans ---- %% -- end if/affiliation.institution-columnar %% ---------------------------------------------------------- } % conference papers do not typically use \thanks and this command % is locked out in conference mode. If really needed, such as for % the acknowledgment of grants, issue a \IEEEoverridecommandlockouts % after \documentclass % for over three affiliations, or if they all won't fit within the width % of the page, use this alternative format: % %\author{\IEEEauthorblockN{Michael Shell\IEEEauthorrefmark{1}, %Homer Simpson\IEEEauthorrefmark{2}, %James Kirk\IEEEauthorrefmark{3}, %Montgomery Scott\IEEEauthorrefmark{3} and %Eldon Tyrell\IEEEauthorrefmark{4}} %\IEEEauthorblockA{\IEEEauthorrefmark{1}School of Electrical and Computer Engineering\\ %Georgia Institute of Technology, %Atlanta, Georgia 30332--0250\\ Email: see http://www.michaelshell.org/contact.html} %\IEEEauthorblockA{\IEEEauthorrefmark{2}Twentieth Century Fox, Springfield, USA\\ %Email: [email protected]} %\IEEEauthorblockA{\IEEEauthorrefmark{3}Starfleet Academy, San Francisco, California 96678-2391\\ %Telephone: (800) 555--1212, Fax: (888) 555--1212} %\IEEEauthorblockA{\IEEEauthorrefmark{4}Tyrell Inc., 123 Replicant Street, Los Angeles, California 90210--4321}} % use for special paper notices %\IEEEspecialpapernotice{(Invited Paper)} % make the title area \maketitle % As a general rule, do not put math, special symbols or citations % in the abstract \begin{abstract} This paper approaches the impact of the pandemic as a massive service disruption of the pre-pandemic global connectivity and regional air transport networks. In particular, the project aims to provide data analytical evidence for policy success and transformation of the air transportation system. As an aspirational goal, the industry aims to recover in a ``greener'' manner. The project builds on openly available data sets. The paper will be produced in a reproducible manner making the data, code, and its processing available to interested reseachers and practitioners. The open assessment will provide policy makers with a tool to assess the reaction to local or regional measures. \end{abstract} % keywords % use for special paper notices % make the title area \maketitle % no keywords % For peer review papers, you can put extra information on the cover % page as needed: % \ifCLASSOPTIONpeerreview % \begin{center} \bfseries EDICS Category: 3-BBND \end{center} % \fi % % For peerreview papers, this IEEEtran command inserts a page break and % creates the second title. It will be ignored for other modes. \IEEEpeerreviewmaketitle \begin{Shaded} \begin{Highlighting}[] \DocumentationTok{\#\# set bookdown specs/defaults for high quality output} \CommentTok{\#{-}{-}{-}{-}{-}{-}{-}{-}{-}{-} check for the settings} \DocumentationTok{\#\# theme default for ggplot} \FunctionTok{theme\_set}\NormalTok{(} \FunctionTok{theme\_minimal}\NormalTok{()} \NormalTok{ )} \DocumentationTok{\#\#\#Preparatory codes} \CommentTok{\#If someone needs filters below, here we can control any selective sample} \CommentTok{\#Filtering Brazilian and European data to reduce the sample (and csv) size} \CommentTok{\#Currently, those filters are not in use in the code, they are here just in case.} \NormalTok{bra\_10\_apts }\OtherTok{\textless{}{-}} \FunctionTok{c}\NormalTok{(}\StringTok{"SBBR"}\NormalTok{, }\StringTok{"SBGR"}\NormalTok{, }\StringTok{"SBSP"}\NormalTok{, }\StringTok{"SBKP"}\NormalTok{, }\StringTok{"SBRJ"}\NormalTok{, }\StringTok{"SBGL"}\NormalTok{, }\StringTok{"SBCF"}\NormalTok{, }\StringTok{"SBSV"}\NormalTok{, }\StringTok{"SBPA"}\NormalTok{, }\StringTok{"SBCT"}\NormalTok{)} \NormalTok{eur\_apts }\OtherTok{\textless{}{-}} \FunctionTok{c}\NormalTok{(}\StringTok{"EHAM"}\NormalTok{,}\StringTok{"LFPG"}\NormalTok{,}\StringTok{"EGLL"}\NormalTok{,}\StringTok{"EDDF"}\NormalTok{,}\StringTok{"EDDM"}\NormalTok{,}\StringTok{"LEMD"}\NormalTok{,}\StringTok{"LIRF"}\NormalTok{,}\StringTok{"LEBL"}\NormalTok{,}\StringTok{"EGKK"}\NormalTok{,}\StringTok{"LSZH"}\NormalTok{)} \NormalTok{study\_airports }\OtherTok{\textless{}{-}} \FunctionTok{c}\NormalTok{(bra\_10\_apts, eur\_apts)} \DocumentationTok{\#\#\#Preparing airport file} \CommentTok{\#NOTE: the airports.csv file below is the downloaded file from www.ourairports.org.} \NormalTok{airports }\OtherTok{\textless{}{-}} \FunctionTok{read\_csv}\NormalTok{(}\StringTok{"data{-}raw/airports.csv"}\NormalTok{) }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{mutate}\NormalTok{(}\AttributeTok{continent =} \FunctionTok{case\_when}\NormalTok{(}\FunctionTok{is.na}\NormalTok{(continent) }\SpecialCharTok{\textasciitilde{}} \StringTok{"NA"}\NormalTok{, }\ConstantTok{TRUE} \SpecialCharTok{\textasciitilde{}}\NormalTok{ continent))} \CommentTok{\#There are missing airports and too much variables} \NormalTok{apt\_countries }\OtherTok{\textless{}{-}}\NormalTok{ airports }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{transmute}\NormalTok{(}\AttributeTok{ICAO =}\NormalTok{ ident, }\AttributeTok{CTRY =}\NormalTok{ iso\_country) }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{add\_row}\NormalTok{(}\AttributeTok{ICAO =} \FunctionTok{c}\NormalTok{(}\StringTok{"SPJC"}\NormalTok{, }\StringTok{"YBMC"}\NormalTok{, }\StringTok{"LSZM"}\NormalTok{, }\StringTok{"YSCH"}\NormalTok{, }\StringTok{"EPLB"}\NormalTok{, }\StringTok{"K3M3"}\NormalTok{, }\StringTok{"VV01"}\NormalTok{, }\StringTok{"SC28"}\NormalTok{, }\StringTok{"CWF2"}\NormalTok{, }\StringTok{"EHDB"}\NormalTok{, }\StringTok{"74XA"}\NormalTok{, }\StringTok{"HE13"}\NormalTok{), }\AttributeTok{CTRY =} \FunctionTok{c}\NormalTok{(}\StringTok{"PE"}\NormalTok{, }\StringTok{"AU"}\NormalTok{, }\StringTok{"FR"}\NormalTok{, }\StringTok{"AU"}\NormalTok{, }\StringTok{"PL"}\NormalTok{, }\StringTok{"US"}\NormalTok{, }\StringTok{"VN"}\NormalTok{, }\StringTok{"US"}\NormalTok{, }\StringTok{"CA"}\NormalTok{, }\StringTok{"NL"}\NormalTok{, }\StringTok{"US"}\NormalTok{, }\StringTok{"EG"}\NormalTok{))} \CommentTok{\#If you need to write} \CommentTok{\#write\_csv(apt\_countries, "./data/apt\_countries.csv")} \CommentTok{\#apt\_countries is ready.} \CommentTok{\# Associate the regions} \NormalTok{a }\OtherTok{\textless{}{-}}\NormalTok{ airports }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{filter}\NormalTok{(continent }\SpecialCharTok{==} \StringTok{"EU"}\NormalTok{) }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{select}\NormalTok{(iso\_country) }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{unique}\NormalTok{()} \NormalTok{eur\_countries }\OtherTok{\textless{}{-}}\NormalTok{ a}\SpecialCharTok{$}\NormalTok{iso\_country} \CommentTok{\#eur\_countries is ready.} \end{Highlighting} \end{Shaded} \begin{Shaded} \begin{Highlighting}[] \CommentTok{\#CURRENT COMMENTS AND TO{-}DO\textquotesingle{}S} \CommentTok{\# I HAVE DOWNLOADED 3 FILES FOR NOW (APR/19, APR/2020, APR/2021), JUST TO START "TIDYING" AND EXPLORING.} \CommentTok{\#IT\textquotesingle{}S IN THE DATA{-}RAW FOLDER (NOT SHARED WITH GITHUB), AS ALWAYS.} \end{Highlighting} \end{Shaded} \hypertarget{introduction}{% \section{Introduction}\label{introduction}} This paper is heavily informed by the work of (Strohmeier et al. 2021). For many years, many concerns of the global air traffic management community has been directed to the evident problem of imbalances between capacity and demand. The pressing, increasing demand for air transport registered in the last decade not only has already produced challenging delay management practices, but also fostered projections of even worse scenarios. EUROCONTROL (\_\_\_\_), for example, argued that delays in Europe could reach up to 20 minutes per flight in 2040, in stark contrast to the 12 minutes per flight, as registered in 2016. In the above scenario, many disturbances on the air navigation system could represent a real threat to multiple stakeholders. Events such as extreme bad weather, unexpected interruptions of air navigation services, changes in regulatory framework and others: all of those inputs could promote even more delay and its propagation effects. That is why the concept of resilience in ATM system became similarly relevant in the agenda during the same period. Arguably, a resilient ATM system could mitigate the negative effects of excessive demands on insufficient capacity and their respective constraints and bottlenecks. However, the recent COVID-19 crisis posed a completely different, unexpected, and inverted challenge. Demand for air transport dropped as low as 90\% of the previous ``normal'' in many places. Where the lack of capacity was previously the issue, now the lack of demand threatened the ATM system stability. In the financial perspective, airlines and airports had to deal with an unprecedented decrease in incomes. As a result, air navigation providers collected less fees for their services, due to significantly fewer flights. In the operational perspective, pilots and air traffic controllers practiced less. The problems and obstacles developed into many other dimensions. Hence, the current scenario is a proper moment to further investigate the concept of resilience. \begin{Shaded} \begin{Highlighting}[] \CommentTok{\# Problem Statement } \CommentTok{\# The problem is that, currently, the concept} \CommentTok{\# of resilience is mostly directed to recovery} \CommentTok{\# against delay propagation after negative } \CommentTok{\# disturbances. However, the current scenario} \CommentTok{\# poses an inverted challenge, of very low } \CommentTok{\# delays due to low demand against surplus } \CommentTok{\# capacity. Therefore, there is room for } \CommentTok{\# enlarging the comprehension of the concept} \CommentTok{\# of resilience in ATM systems. } \CommentTok{\# \# Purpose Statement} \CommentTok{\# } \CommentTok{\# ???The purpose of this research is to } \CommentTok{\# investigate additional dimensions in which } \CommentTok{\# resilience could be measured, in addition} \CommentTok{\# to the current framework of delay analysis.} \CommentTok{\# } \CommentTok{\# Research Question} \CommentTok{\# } \CommentTok{\# ???How can we enlarge the concept of } \CommentTok{\# resilience, so that it is applicable to} \CommentTok{\# scenarios of low traffic? } \CommentTok{\#} \CommentTok{\# ???Research Question: } \CommentTok{\# ???RQ1.What was the impact of the pandemic on ATM resilience?} \CommentTok{\# ??? RQ1.1 How resilience can be modeled in a low{-}demand scenario?} \CommentTok{\# ??? RQ1.2 How resilient were different ATM systems worldwide?} \end{Highlighting} \end{Shaded} This paper approaches the impact of the pandemic as a massive service disruption of the pre-pandemic global connectivity and regional air transport networks. In particular, the project aims to provide data analytical evidence for policy success and transformation of the air transportation system. As an aspirational goal, the industry aims to recover in a ``greener'' manner. To date, no assessment of this transformational aspects has been conducted. \begin{itemize} \tightlist \item data-analytical approach - using open data / freely available (tbd: validated against organisational data) \item ???RQ1.1 = through a qualitative analysis of previous proposed models \item ???RQ1.2 = through a quantitative analysis of open data \end{itemize} The contribution of this paper are \begin{itemize} \item conceptualisation of the COVID-19 impact on air transportation as a resilience problem; \item assessing the impact on the basis of open data \item identification of patterns and/or measures to describe and quantify/evaluate the level of recovery (or disruption) \end{itemize} \hypertarget{background}{% \section{Background}\label{background}} \hypertarget{covid-19-air-transportation}{% \subsection{COVID-19 \& Air Transportation}\label{covid-19-air-transportation}} \hypertarget{resilience}{% \subsection{Resilience}\label{resilience}} EUROCONTROL (2009): first definition of resilience in ATM context -- ``Resilience is the intrinsic ability of a system to adjust its functioning prior to, during, or following changes and disturbances, so that it can sustain required operations under both expected and unexpected conditions.'' Gluchshenko (2012): Definitions for Resilience, robustness, disturbance, stress, and perturbation Proposition for a framework of different levels of stress/perturbations Proposition of metrics for resilience (both quantitative and qualitative) Gluchshenko (2013): repeats the previous ideas and adds a performance-based approach as well as an algorithm to investigate resilience Project Resilience 2050 (Jun/2012 + 43 months) -- includes the previous definitions and other technical tasks. However, it evolves the way to measure resilience. Now, not only the time of deviation and time of recovery is considered. The project measures it as the relative difference of rate of delays correlation, or R = (ax1 -- dx1)/dx1 -- it has no unit, it's the difference between two pearson correlations. Koelle (2015): proposes to address resilience as a situation management and state-oriented problem. Through two case studies, argued that ``there is a lack of fit of the current operational ANS performance indicators to address impact of disruptions as they are primarily based on actual timestamps or transition times.'' \hypertarget{if-we-need-to-fill-space-crowd-sourced-data-collection}{% \subsection{\textless if we need to fill space\textgreater{} Crowd-Sourced Data Collection}\label{if-we-need-to-fill-space-crowd-sourced-data-collection}} \hypertarget{methodmaterials}{% \section{Method/Materials}\label{methodmaterials}} A mixed-method approach, based on: \begin{enumerate} \def\labelenumi{\alph{enumi})} \tightlist \item to answer RQ1.1, a qualitative analysis of previous models to develop acute low-demand as a disturbance \item to answer RQ1.2, a quantitative analysis of open data, to observe (or not) different levels/stages of stress/recovery, which could indicate different ``more'' or ``less'' resilience to the disturbances \end{enumerate} \hypertarget{open-source-data}{% \subsection{Open-source Data}\label{open-source-data}} This study builds on publicly available data. Opensky Network collects crowdsourced air traffic data from more than 2500 feeders (sensor stations). To support the process of illustrating and studying the impact of the COVID pandemic on air traffic demand, a flight-by-flight dataset is provided on a monthly basis (Olive, Strohmeier, and Lübbe 2021). The data spans the period since 1. January 2019. Fig. \ref{fig:osndaily} shows the number of daily flights tracked by Opensky Network globally. \begin{Shaded} \begin{Highlighting}[] \NormalTok{daily\_tfc }\OtherTok{\textless{}{-}} \FunctionTok{read\_csv}\NormalTok{(}\StringTok{"./data/daily\_osn.csv"}\NormalTok{)} \NormalTok{daily\_tfc }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{ggplot}\NormalTok{(}\AttributeTok{mapping =} \FunctionTok{aes}\NormalTok{(}\AttributeTok{x =}\NormalTok{ DATE, }\AttributeTok{y =}\NormalTok{ FLTS)) }\SpecialCharTok{+} \FunctionTok{geom\_line}\NormalTok{() }\SpecialCharTok{+} \FunctionTok{labs}\NormalTok{(}\AttributeTok{x =} \ConstantTok{NULL}\NormalTok{, }\AttributeTok{y =} \StringTok{"flights"}\NormalTok{)} \end{Highlighting} \end{Shaded} \begin{figure} \centering \includegraphics{paper_files/figure-latex/osndaily-1.pdf} \caption{\label{fig:osndaily}Daily flights tracked by Opensky Network} \end{figure} \hypertarget{resultsdiscussion}{% \section{Results/Discussion}\label{resultsdiscussion}} 1.1 \begin{enumerate} \def\labelenumi{\alph{enumi})} \tightlist \item Resilience can be measured as a function of time - the smaller the relationship between time of stress and the time of recovery, more resilient a system is. \end{enumerate} 1.2 how to use open data to ``see'' resilience? 1.2.1 Gather and prepare data \begin{Shaded} \begin{Highlighting}[] \CommentTok{\#Reading raw data} \FunctionTok{source}\NormalTok{(}\StringTok{"./R/list\_apt\_files.R"}\NormalTok{)} \CommentTok{\#Here I will assign only one month {-} "202105". If you want to include a full year, just assign year to "2021" or "2020". It works.} \NormalTok{year }\OtherTok{\textless{}{-}} \StringTok{"2021"} \NormalTok{file\_names }\OtherTok{\textless{}{-}} \FunctionTok{list\_apt\_files}\NormalTok{(}\AttributeTok{.year =}\NormalTok{ year)} \NormalTok{open\_sky }\OtherTok{\textless{}{-}} \FunctionTok{map\_dfr}\NormalTok{(file\_names, read\_csv)} \end{Highlighting} \end{Shaded} \begin{verbatim} ## ## -- Column specification -------------------------------------------------------- ## cols( ## callsign = col_character(), ## number = col_character(), ## icao24 = col_character(), ## registration = col_character(), ## typecode = col_character(), ## origin = col_character(), ## destination = col_character(), ## firstseen = col_datetime(format = ""), ## lastseen = col_datetime(format = ""), ## day = col_datetime(format = ""), ## latitude_1 = col_double(), ## longitude_1 = col_double(), ## altitude_1 = col_double(), ## latitude_2 = col_double(), ## longitude_2 = col_double(), ## altitude_2 = col_double() ## ) ## ## ## -- Column specification -------------------------------------------------------- ## cols( ## callsign = col_character(), ## number = col_character(), ## icao24 = col_character(), ## registration = col_character(), ## typecode = col_character(), ## origin = col_character(), ## destination = col_character(), ## firstseen = col_datetime(format = ""), ## lastseen = col_datetime(format = ""), ## day = col_datetime(format = ""), ## latitude_1 = col_double(), ## longitude_1 = col_double(), ## altitude_1 = col_double(), ## latitude_2 = col_double(), ## longitude_2 = col_double(), ## altitude_2 = col_double() ## ) ## ## ## -- Column specification -------------------------------------------------------- ## cols( ## callsign = col_character(), ## number = col_character(), ## icao24 = col_character(), ## registration = col_character(), ## typecode = col_character(), ## origin = col_character(), ## destination = col_character(), ## firstseen = col_datetime(format = ""), ## lastseen = col_datetime(format = ""), ## day = col_datetime(format = ""), ## latitude_1 = col_double(), ## longitude_1 = col_double(), ## altitude_1 = col_double(), ## latitude_2 = col_double(), ## longitude_2 = col_double(), ## altitude_2 = col_double() ## ) ## ## ## -- Column specification -------------------------------------------------------- ## cols( ## callsign = col_character(), ## number = col_character(), ## icao24 = col_character(), ## registration = col_character(), ## typecode = col_character(), ## origin = col_character(), ## destination = col_character(), ## firstseen = col_datetime(format = ""), ## lastseen = col_datetime(format = ""), ## day = col_datetime(format = ""), ## latitude_1 = col_double(), ## longitude_1 = col_double(), ## altitude_1 = col_double(), ## latitude_2 = col_double(), ## longitude_2 = col_double(), ## altitude_2 = col_double() ## ) ## ## ## -- Column specification -------------------------------------------------------- ## cols( ## callsign = col_character(), ## number = col_character(), ## icao24 = col_character(), ## registration = col_character(), ## typecode = col_character(), ## origin = col_character(), ## destination = col_character(), ## firstseen = col_datetime(format = ""), ## lastseen = col_datetime(format = ""), ## day = col_datetime(format = ""), ## latitude_1 = col_double(), ## longitude_1 = col_double(), ## altitude_1 = col_double(), ## latitude_2 = col_double(), ## longitude_2 = col_double(), ## altitude_2 = col_double() ## ) \end{verbatim} \begin{Shaded} \begin{Highlighting}[] \CommentTok{\#Selecting relevant variables} \NormalTok{fb }\OtherTok{\textless{}{-}}\NormalTok{ open\_sky }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{transmute}\NormalTok{(}\AttributeTok{ADEP =}\NormalTok{ origin, }\AttributeTok{ADES =}\NormalTok{ destination, }\AttributeTok{TYPE =} \FunctionTok{as.factor}\NormalTok{(typecode), }\AttributeTok{DATE =} \FunctionTok{date}\NormalTok{(day), }\AttributeTok{CALL =}\NormalTok{ callsign} \CommentTok{\#, ACFT\_ID = aircraft\_uid} \NormalTok{ )} \CommentTok{\#Easily "dropping NA\textquotesingle{}s\# {-} this can be further sofisticated} \NormalTok{fb1 }\OtherTok{\textless{}{-}}\NormalTok{ fb }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{drop\_na}\NormalTok{()} \NormalTok{fb1} \end{Highlighting} \end{Shaded} \begin{verbatim} ## # A tibble: 3,338,649 x 5 ## ADEP ADES TYPE DATE CALL ## <chr> <chr> <fct> <date> <chr> ## 1 KJFK LSGG B788 2021-01-01 ETH726 ## 2 KMIA KMIA B763 2021-01-01 LCO1108 ## 3 VHHH 71KY G650 2021-01-01 ABW9515 ## 4 OMDM YSSY A343 2021-01-01 ASY052 ## 5 KLAX EDDF B77L 2021-01-01 CSN461 ## 6 EBLG EBLG B744 2021-01-01 ATG6652 ## 7 KORD EHAM B77L 2021-01-01 CSN5203 ## 8 FAOR OMDB B738 2021-01-01 KQA304 ## 9 YSSY OMDB B77W 2021-01-01 UAE415 ## 10 YSSY WSSS A332 2021-01-01 ALK302 ## # ... with 3,338,639 more rows \end{verbatim} \begin{Shaded} \begin{Highlighting}[] \CommentTok{\#Joining to ADEP} \NormalTok{fb2 }\OtherTok{\textless{}{-}} \FunctionTok{left\_join}\NormalTok{(fb1, apt\_countries, }\AttributeTok{by =} \FunctionTok{c}\NormalTok{(}\StringTok{"ADEP"} \OtherTok{=} \StringTok{"ICAO"}\NormalTok{)) }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{mutate}\NormalTok{(}\AttributeTok{ADEP\_CTRY =}\NormalTok{ CTRY, }\AttributeTok{.keep =} \StringTok{"unused"}\NormalTok{, }\AttributeTok{.after =}\NormalTok{ ADEP)} \CommentTok{\#Joining to ADES} \NormalTok{fb3 }\OtherTok{\textless{}{-}} \FunctionTok{left\_join}\NormalTok{(fb2, apt\_countries, }\AttributeTok{by =} \FunctionTok{c}\NormalTok{(}\StringTok{"ADES"} \OtherTok{=} \StringTok{"ICAO"}\NormalTok{)) }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{mutate}\NormalTok{(}\AttributeTok{ADES\_CTRY =}\NormalTok{ CTRY, }\AttributeTok{.keep =} \StringTok{"unused"}\NormalTok{, }\AttributeTok{.after =}\NormalTok{ ADES)} \CommentTok{\#Check NA\textquotesingle{}s} \FunctionTok{colSums}\NormalTok{(}\FunctionTok{is.na}\NormalTok{(fb3))} \end{Highlighting} \end{Shaded} \begin{verbatim} ## ADEP ADEP_CTRY ADES ADES_CTRY TYPE DATE CALL ## 0 1271 0 1446 0 0 0 \end{verbatim} \begin{Shaded} \begin{Highlighting}[] \CommentTok{\# Very few NA\textquotesingle{}s {-} it\textquotesingle{}s safe to drop and factor now} \NormalTok{fb4 }\OtherTok{\textless{}{-}}\NormalTok{ fb3 }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{drop\_na}\NormalTok{() }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{mutate}\NormalTok{(}\AttributeTok{ADEP\_CTRY =} \FunctionTok{as.factor}\NormalTok{(ADEP\_CTRY), }\AttributeTok{ADES\_CTRY =} \FunctionTok{as.factor}\NormalTok{(ADES\_CTRY))} \CommentTok{\#NOTE: Here we can adjust the European countries that comprises EU region by editing the "eur\_countries" vector:} \CommentTok{\# Currently in european countries: "GB" "AD" "ES" "AL" "XK" "AT" "BA" "BE" "BG" "IS" "BY" "UA" "CH" "CZ" "SK" "DE" "RU" "DK" "HR" "EE" "FI" "GG" "JE" "IM" "NL" "IE" "FO" "LU" "NO" "PL" "PT" "SE" "LV" "LT" "FR" "GR" "HU" "IT" "LI" "SI" "MT" "MC" "RO" "TR" "MD" "MK" "GI" "RS" "ME" "SM" "GE" "VA"} \NormalTok{base\_dataset }\OtherTok{\textless{}{-}}\NormalTok{ fb4 }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{mutate}\NormalTok{(}\AttributeTok{ADEP\_REG =} \FunctionTok{as.factor}\NormalTok{(}\FunctionTok{case\_when}\NormalTok{(ADEP\_CTRY }\SpecialCharTok{==} \StringTok{"US"} \SpecialCharTok{\textasciitilde{}} \StringTok{"US"}\NormalTok{,} \NormalTok{ ADEP\_CTRY }\SpecialCharTok{==} \StringTok{"BR"} \SpecialCharTok{\textasciitilde{}} \StringTok{"BR"}\NormalTok{,} \NormalTok{ ADEP\_CTRY }\SpecialCharTok{\%in\%}\NormalTok{ eur\_countries }\SpecialCharTok{\textasciitilde{}} \StringTok{"EU"}\NormalTok{,} \ConstantTok{TRUE} \SpecialCharTok{\textasciitilde{}} \StringTok{"Other"}\NormalTok{)), }\AttributeTok{.after =}\NormalTok{ ADEP\_CTRY) }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{mutate}\NormalTok{(}\AttributeTok{ADES\_REG =} \FunctionTok{as.factor}\NormalTok{(}\FunctionTok{case\_when}\NormalTok{(ADES\_CTRY }\SpecialCharTok{==} \StringTok{"US"} \SpecialCharTok{\textasciitilde{}} \StringTok{"US"}\NormalTok{,} \NormalTok{ ADES\_CTRY }\SpecialCharTok{==} \StringTok{"BR"} \SpecialCharTok{\textasciitilde{}} \StringTok{"BR"}\NormalTok{,} \NormalTok{ ADES\_CTRY }\SpecialCharTok{\%in\%}\NormalTok{ eur\_countries }\SpecialCharTok{\textasciitilde{}} \StringTok{"EU"}\NormalTok{,} \ConstantTok{TRUE} \SpecialCharTok{\textasciitilde{}} \StringTok{"Other"}\NormalTok{)), }\AttributeTok{.after =}\NormalTok{ ADES\_CTRY)} \FunctionTok{colSums}\NormalTok{(}\FunctionTok{is.na}\NormalTok{(base\_dataset))} \end{Highlighting} \end{Shaded} \begin{verbatim} ## ADEP ADEP_CTRY ADEP_REG ADES ADES_CTRY ADES_REG TYPE DATE ## 0 0 0 0 0 0 0 0 ## CALL ## 0 \end{verbatim} \begin{Shaded} \begin{Highlighting}[] \CommentTok{\# No NA\textquotesingle{}s {-} yaaayy!!} \FunctionTok{glimpse}\NormalTok{(base\_dataset)} \end{Highlighting} \end{Shaded} \begin{verbatim} ## Rows: 3,336,679 ## Columns: 9 ## $ ADEP <chr> "KJFK", "KMIA", "VHHH", "OMDM", "KLAX", "EBLG", "KORD", "FAO~ ## $ ADEP_CTRY <fct> US, US, HK, AE, US, BE, US, ZA, AU, AU, TW, NL, TW, US, QA, ~ ## $ ADEP_REG <fct> US, US, Other, Other, US, EU, US, Other, Other, Other, Other~ ## $ ADES <chr> "LSGG", "KMIA", "71KY", "YSSY", "EDDF", "EBLG", "EHAM", "OMD~ ## $ ADES_CTRY <fct> CH, US, US, AU, DE, BE, NL, AE, AE, SG, US, PE, CA, AU, QA, ~ ## $ ADES_REG <fct> EU, US, US, Other, EU, EU, EU, Other, Other, Other, US, Othe~ ## $ TYPE <fct> B788, B763, G650, A343, B77L, B744, B77L, B738, B77W, A332, ~ ## $ DATE <date> 2021-01-01, 2021-01-01, 2021-01-01, 2021-01-01, 2021-01-01,~ ## $ CALL <chr> "ETH726", "LCO1108", "ABW9515", "ASY052", "CSN461", "ATG6652~ \end{verbatim} \begin{Shaded} \begin{Highlighting}[] \FunctionTok{summary}\NormalTok{(base\_dataset)} \end{Highlighting} \end{Shaded} \begin{verbatim} ## ADEP ADEP_CTRY ADEP_REG ADES ## Length:3336679 US :2225791 BR : 35791 Length:3336679 ## Class :character AU : 127008 EU : 596507 Class :character ## Mode :character DE : 109611 Other: 478590 Mode :character ## GB : 84635 US :2225791 ## FR : 64874 ## CA : 45627 ## (Other): 679133 ## ADES_CTRY ADES_REG TYPE DATE ## US :2223845 BR : 35937 B738 : 356779 Min. :2021-01-01 ## AU : 127206 EU : 597541 A320 : 234165 1st Qu.:2021-02-14 ## DE : 109350 Other: 479356 B737 : 205056 Median :2021-03-26 ## GB : 84605 US :2223845 A321 : 135527 Mean :2021-03-22 ## FR : 65219 A319 : 118359 3rd Qu.:2021-04-29 ## CA : 45727 E75L : 112965 Max. :2021-05-30 ## (Other): 680727 (Other):2173828 ## CALL ## Length:3336679 ## Class :character ## Mode :character ## ## ## ## \end{verbatim} \begin{Shaded} \begin{Highlighting}[] \CommentTok{\#quick peek} \NormalTok{base\_dataset} \end{Highlighting} \end{Shaded} \begin{verbatim} ## # A tibble: 3,336,679 x 9 ## ADEP ADEP_CTRY ADEP_REG ADES ADES_CTRY ADES_REG TYPE DATE CALL ## <chr> <fct> <fct> <chr> <fct> <fct> <fct> <date> <chr> ## 1 KJFK US US LSGG CH EU B788 2021-01-01 ETH726 ## 2 KMIA US US KMIA US US B763 2021-01-01 LCO1108 ## 3 VHHH HK Other 71KY US US G650 2021-01-01 ABW9515 ## 4 OMDM AE Other YSSY AU Other A343 2021-01-01 ASY052 ## 5 KLAX US US EDDF DE EU B77L 2021-01-01 CSN461 ## 6 EBLG BE EU EBLG BE EU B744 2021-01-01 ATG6652 ## 7 KORD US US EHAM NL EU B77L 2021-01-01 CSN5203 ## 8 FAOR ZA Other OMDB AE Other B738 2021-01-01 KQA304 ## 9 YSSY AU Other OMDB AE Other B77W 2021-01-01 UAE415 ## 10 YSSY AU Other WSSS SG Other A332 2021-01-01 ALK302 ## # ... with 3,336,669 more rows \end{verbatim} \begin{Shaded} \begin{Highlighting}[] \CommentTok{\#} \CommentTok{\#} \CommentTok{\#} \CommentTok{\#NOW IT\textquotesingle{}S TIME TO LOOP TO OTHER MONTHS AND BIND THEM ALL!} \CommentTok{\#} \CommentTok{\#} \CommentTok{\#} \end{Highlighting} \end{Shaded} \begin{Shaded} \begin{Highlighting}[] \CommentTok{\#quick first look} \NormalTok{temp1 }\OtherTok{\textless{}{-}}\NormalTok{ base\_dataset }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{group\_by}\NormalTok{(DATE, ADEP\_REG, ADES\_REG) }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{summarize}\NormalTok{(}\AttributeTok{FLIGHTS =} \FunctionTok{n}\NormalTok{(), }\AttributeTok{.groups =} \StringTok{"drop"}\NormalTok{) }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{filter}\NormalTok{(ADEP\_REG }\SpecialCharTok{\%in\%} \FunctionTok{c}\NormalTok{(}\StringTok{"BR"}\NormalTok{, }\StringTok{"EU"}\NormalTok{), ADES\_REG }\SpecialCharTok{\%in\%} \FunctionTok{c}\NormalTok{(}\StringTok{"BR"}\NormalTok{, }\StringTok{"EU"}\NormalTok{)) }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{mutate}\NormalTok{(}\AttributeTok{ROUTE =} \FunctionTok{paste}\NormalTok{(ADEP\_REG, ADES\_REG, }\AttributeTok{sep =} \StringTok{"{-}"}\NormalTok{), }\AttributeTok{.keep =} \StringTok{"unused"}\NormalTok{, }\AttributeTok{.before =} \StringTok{"FLIGHTS"}\NormalTok{) }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{pivot\_wider}\NormalTok{(}\AttributeTok{names\_from =}\NormalTok{ ROUTE, }\AttributeTok{values\_from =}\NormalTok{ FLIGHTS) } \NormalTok{temp1} \end{Highlighting} \end{Shaded} \begin{verbatim} ## # A tibble: 149 x 5 ## DATE `BR-BR` `BR-EU` `EU-BR` `EU-EU` ## <date> <int> <int> <int> <int> ## 1 2021-01-01 189 8 7 1792 ## 2 2021-01-02 265 7 10 3088 ## 3 2021-01-03 264 12 6 3721 ## 4 2021-01-04 273 6 11 3446 ## 5 2021-01-05 320 5 11 3068 ## 6 2021-01-06 262 10 7 2930 ## 7 2021-01-07 288 8 11 3088 ## 8 2021-01-08 266 3 1 3343 ## 9 2021-01-09 253 7 11 2695 ## 10 2021-01-10 233 7 7 3371 ## # ... with 139 more rows \end{verbatim} \begin{Shaded} \begin{Highlighting}[] \CommentTok{\#First stab at different levels of traffic} \NormalTok{n }\OtherTok{\textless{}{-}} \FloatTok{0.5} \NormalTok{temp1 }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{ggplot}\NormalTok{(}\FunctionTok{aes}\NormalTok{(}\AttributeTok{x =}\NormalTok{ DATE)) }\SpecialCharTok{+} \FunctionTok{geom\_point}\NormalTok{(}\FunctionTok{aes}\NormalTok{(}\AttributeTok{y =} \StringTok{\textasciigrave{}}\AttributeTok{EU{-}EU}\StringTok{\textasciigrave{}}\NormalTok{, }\AttributeTok{color =} \StringTok{\textasciigrave{}}\AttributeTok{EU{-}EU}\StringTok{\textasciigrave{}} \SpecialCharTok{\textgreater{}} \FunctionTok{quantile}\NormalTok{(}\StringTok{\textasciigrave{}}\AttributeTok{EU{-}EU}\StringTok{\textasciigrave{}}\NormalTok{[}\FunctionTok{month}\NormalTok{(DATE) }\SpecialCharTok{\%in\%} \DecValTok{1}\SpecialCharTok{:}\DecValTok{2}\NormalTok{], }\AttributeTok{probs =}\NormalTok{ n)), }\AttributeTok{shape =} \DecValTok{4}\NormalTok{) }\SpecialCharTok{+} \FunctionTok{geom\_point}\NormalTok{(}\FunctionTok{aes}\NormalTok{(}\AttributeTok{y =} \StringTok{\textasciigrave{}}\AttributeTok{BR{-}BR}\StringTok{\textasciigrave{}}\NormalTok{, }\AttributeTok{color =} \StringTok{\textasciigrave{}}\AttributeTok{BR{-}BR}\StringTok{\textasciigrave{}} \SpecialCharTok{\textgreater{}} \FunctionTok{quantile}\NormalTok{(}\StringTok{\textasciigrave{}}\AttributeTok{BR{-}BR}\StringTok{\textasciigrave{}}\NormalTok{[}\FunctionTok{month}\NormalTok{(DATE) }\SpecialCharTok{\%in\%} \DecValTok{1}\SpecialCharTok{:}\DecValTok{2}\NormalTok{], }\AttributeTok{probs =}\NormalTok{ n)), }\AttributeTok{shape =} \DecValTok{1}\NormalTok{) }\SpecialCharTok{+} \FunctionTok{labs}\NormalTok{(}\AttributeTok{y =} \StringTok{"Flights"}\NormalTok{) }\SpecialCharTok{+} \FunctionTok{theme}\NormalTok{(}\AttributeTok{legend.position =} \StringTok{"bottom"}\NormalTok{)} \end{Highlighting} \end{Shaded} \includegraphics{paper_files/figure-latex/unnamed-chunk-6-1.pdf} \begin{Shaded} \begin{Highlighting}[] \CommentTok{\#Normalized by the median of the last 3 months of the dataset} \NormalTok{temp2 }\OtherTok{\textless{}{-}}\NormalTok{ temp1 }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{pivot\_longer}\NormalTok{(}\AttributeTok{cols =} \DecValTok{2}\SpecialCharTok{:}\DecValTok{5}\NormalTok{, }\AttributeTok{names\_to =} \StringTok{"ROUTE"}\NormalTok{, }\AttributeTok{values\_to =} \StringTok{"FLIGHTS"}\NormalTok{) }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{group\_by}\NormalTok{(ROUTE) }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{mutate}\NormalTok{(}\AttributeTok{MOVING\_MEDIAN =} \FunctionTok{quantile}\NormalTok{(FLIGHTS[}\FunctionTok{month}\NormalTok{(DATE) }\SpecialCharTok{\%in\%} \FunctionTok{month}\NormalTok{(}\FunctionTok{last}\NormalTok{(DATE))}\SpecialCharTok{{-}}\DecValTok{2}\SpecialCharTok{:}\FunctionTok{month}\NormalTok{(}\FunctionTok{last}\NormalTok{(DATE))], }\AttributeTok{probs =} \FloatTok{0.5}\NormalTok{), }\AttributeTok{NORM\_FLTS =}\NormalTok{ FLIGHTS}\SpecialCharTok{/}\NormalTok{MOVING\_MEDIAN)} \end{Highlighting} \end{Shaded} \begin{verbatim} ## Warning in month(DATE) %in% month(last(DATE)) - 2:month(last(DATE)): Länge des längeren Objektes ## ist kein Vielfaches der Länge des kürzeren Objektes ## Warning in month(DATE) %in% month(last(DATE)) - 2:month(last(DATE)): Länge des längeren Objektes ## ist kein Vielfaches der Länge des kürzeren Objektes ## Warning in month(DATE) %in% month(last(DATE)) - 2:month(last(DATE)): Länge des längeren Objektes ## ist kein Vielfaches der Länge des kürzeren Objektes ## Warning in month(DATE) %in% month(last(DATE)) - 2:month(last(DATE)): Länge des längeren Objektes ## ist kein Vielfaches der Länge des kürzeren Objektes \end{verbatim} \begin{Shaded} \begin{Highlighting}[] \NormalTok{temp2} \end{Highlighting} \end{Shaded} \begin{verbatim} ## # A tibble: 596 x 5 ## # Groups: ROUTE [4] ## DATE ROUTE FLIGHTS MOVING_MEDIAN NORM_FLTS ## <date> <chr> <int> <dbl> <dbl> ## 1 2021-01-01 BR-BR 189 214. 0.881 ## 2 2021-01-01 BR-EU 8 7 1.14 ## 3 2021-01-01 EU-BR 7 9 0.778 ## 4 2021-01-01 EU-EU 1792 3397 0.528 ## 5 2021-01-02 BR-BR 265 214. 1.24 ## 6 2021-01-02 BR-EU 7 7 1 ## 7 2021-01-02 EU-BR 10 9 1.11 ## 8 2021-01-02 EU-EU 3088 3397 0.909 ## 9 2021-01-03 BR-BR 264 214. 1.23 ## 10 2021-01-03 BR-EU 12 7 1.71 ## # ... with 586 more rows \end{verbatim} \begin{Shaded} \begin{Highlighting}[] \NormalTok{temp2 }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{ggplot}\NormalTok{(}\FunctionTok{aes}\NormalTok{(}\AttributeTok{x =}\NormalTok{ DATE)) }\SpecialCharTok{+} \FunctionTok{geom\_line}\NormalTok{(}\FunctionTok{aes}\NormalTok{(}\AttributeTok{y =}\NormalTok{ NORM\_FLTS, }\AttributeTok{color =}\NormalTok{ ROUTE)) }\SpecialCharTok{+} \FunctionTok{theme\_minimal}\NormalTok{()} \end{Highlighting} \end{Shaded} \includegraphics{paper_files/figure-latex/unnamed-chunk-6-2.pdf} 1.2.2 \hypertarget{conclusion}{% \section{Conclusion}\label{conclusion}} \hypertarget{acknowledgment}{% \section*{Acknowledgment}\label{acknowledgment}} \addcontentsline{toc}{section}{Acknowledgment} \hypertarget{references}{% \section*{References}\label{references}} \addcontentsline{toc}{section}{References} \hypertarget{refs}{} \begin{CSLReferences}{1}{0} \leavevmode\hypertarget{ref-xavier_olive_2021_4893103}{}% Olive, Xavier, Martin Strohmeier, and Jannis Lübbe. 2021. {``{Crowdsourced air traffic data from The OpenSky Network 2020}.''} Zenodo. \url{https://doi.org/10.5281/zenodo.4893103}. \leavevmode\hypertarget{ref-strohmeier_crowdsourced_2021}{}% Strohmeier, Martin, Xavier Olive, Jannis Lübbe, Matthias Schäfer, and Vincent Lenders. 2021. {``Crowdsourced Air Traffic Data from {OpenSky Network} 2019-2020.''} \emph{Earth Systems Science Data} 13: 357--66. \url{https://doi.org/10.5194/essd-13-357-2021}. \end{CSLReferences} \end{document}
{-# OPTIONS --without-K --safe #-} {- Properties regarding Morphisms of a category: - Regular Monomorphism - Regular Epimorphism https://ncatlab.org/nlab/show/regular+epimorphism These are defined here rather than in Morphism, as this might cause import cycles (and make the dependency graph very odd). -} open import Categories.Category.Core module Categories.Morphism.Regular {o ℓ e} (𝒞 : Category o ℓ e) where open import Level open import Categories.Morphism 𝒞 open import Categories.Diagram.Equalizer 𝒞 open import Categories.Diagram.Coequalizer 𝒞 open Category 𝒞 private variable A B : Obj f : A ⇒ B record RegularMono (f : A ⇒ B) : Set (o ⊔ ℓ ⊔ e) where field { C } : Obj g : B ⇒ C h : B ⇒ C equalizer : IsEqualizer f h g record RegularEpi (f : A ⇒ B) : Set (o ⊔ ℓ ⊔ e) where field { C } : Obj h : C ⇒ A g : C ⇒ A coequalizer : IsCoequalizer h g f RegularMono⇒Mono : RegularMono f → Mono f RegularMono⇒Mono regular = IsEqualizer⇒Mono equalizer where open RegularMono regular RegularEpi⇒Epi : RegularEpi f → Epi f RegularEpi⇒Epi regular = IsCoequalizer⇒Epi coequalizer where open RegularEpi regular
Sengoku Basara 3 could very much be summed up as a really diversified Dynasty Warriors clone. It’s not much of an insult or a too far from being considered a compliment, either. Nevertheless, for gamers who enjoy thousand-army battlefield games then Sengoku Basara will definitely appeal to you. We have a series of new video trailers available for viewing here at Blend Games and that means that it’s time for another gameplay media blowout, courtesy of GameTrailers. The videos showcase different characters and spotlight their moves, special abilities as well as a few boss encounters. For this game to be on the Wii it actually looks pretty good, and any gamer knows that it’s a testament to the developer’s capabilities to even have a game that runs on both the Wii and the PS3 and not have the Wii version dumb-downed to a little retarded quarter experience of the original (i.e., Ghostbusters). You can check out the new videos below or visit the Official Capcom Website for more info.
[STATEMENT] lemma "((x::real) \<le> y) = (x < y \<or> x = y)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (x \<le> y) = (x < y \<or> x = y) [PROOF STEP] by arith
function xpad = zpad0(x, nxp, nyp, nzp) %function xpad = zpad0(x, nxp, nyp, nzp) % zero pad an input signal x symmetrically around "0" (image center) % by A. Yendiki if nargin < 1, ir_usage, end if nargin == 1 && streq(x, 'test'), zpad0_test, return, end if nargin == 2 xpad = ir_pad_into_center(x, nxp); elseif nargin == 3 xpad = ir_pad_into_center(x, [nxp nyp]); elseif nargin == 4 xpad = ir_pad_into_center(x, [nxp nyp nzp]); else error 'Too many arguments' end function zpad0_test zpad0([1 2 1], 7) zpad0([1 2 1], 7, 3)
from .order import Order import numpy as np STANDARD_FEES = { 'FUT': 3.00, 'SEC': 0.01, } class OMS(): """ The Order Management System (OMS) is meant to the point of contact between a user defined strategy and the portfolio. A strategy places orders, and whether or not that order gets filled puts the assets into the portfolio. ... Paramaters ---------- adv_participation : float, optional (default : .10) percentage of average daily volume for the asset traded adv_period : float, optional (default : 21) days for which to calculate average daily volume adv_oi : float, optional (default : 0.05) percentage of open interested to trade with fee structure : dict, optional fee structure for asset types to calculate trading comissions and fees Attributes ---------- portfolio : tradester.portfolios.Portfolio the connected portfolio object manager : tradester.factories.ClockManager the connected central clock order_num : int the current order number (for tracking in the logs) order_book : dict a one sided order book (i.e. each contract can only have one entry) order_log : list a log of all orders and order actions during the runtime Methods ------- _connect(manager : tradester.factories.ClockManager, portfolio : tradester.portfolios.Portfolio) used in the engine to connect the oms to the central ClockManager and Portfolio _remove_from_ob(identifier : string) removes the identifier order from the order_book, appends the order info to the order_log _fill_order(order : tradester.oms.Order, fill_price : float, filled_units : int, fees : float) fills the order, places the trade into the portfolio place_order(side : int, asset : tradester.finance.Asset, units : int, time_in_force : int, optional, order_type : string, bands : dict, fok : bool, optional) places the order onto the order_book with the desired paramaters: side = 1 is buy, side = -1 is sell - possible order_types: MARKET -> fills at close OPEN -> fills at open LIMIT -> fills at limit price, limit prices defined in bands kwarg (ex: bands = {'LIMIT': 100}), order remains open till filled or updated RANGE -> fills at avg of high and low price RANGE_BOUND_C -> fills at the average of the low and close for a buy or high and close for a sell RANGE_BOUND_O -> fills at the average of the low and open for a buy or high and open for a sell INVERSE_BOUND_C -> fills at the average of the low and close for a sell or high and close for a buy INVERSE_BOUND_O -> fills at the average of the low and open for a sell or high and open for a buy BEST_FILL -> fills at the low for a buy and high for a sell WORST_FILL -> fills at the low for a sell and high for a buy TRIANGULAR_C -> fills at the average of high, low, and close TRIANGULAR_O -> fills at the average of high, low, and open BAR_AVG -> fills at the average of open, high, low, and close max_shares(asset : tradester.finance.Asset) returns the maximum tradeable shares based on adv_participation and adv_oi if applicable process() processes all orders on the order_book to check for fills """ def __init__(self, adv_participation = .10, adv_period = 21, adv_oi = .05, fee_structure = None): self.adv_participation = adv_participation self.adv_period = adv_period self.adv_oi = adv_oi self.fee_structure = STANDARD_FEES if fee_structure is None else fee_structure self.portfolio = None self.manager = None self._order_num = 1 self.order_book = {} self.order_log = [] @property def order_num(self): return self._order_num def _connect(self, manager, portfolio): self.manager = manager self.portfolio = portfolio def _remove_from_ob(self, identifier): if identifier in self.order_book.keys(): info = self.order_book[identifier].info del self.order_book[identifier] self.order_log.append(info) def _log_order(self, order): self.order_log.append(order.info) def _fill_order(self, order, fill_price, filled_units, fees): order.fill(self.manager.now, fill_price, filled_units) info = order.info asset = order.asset multiplier = asset.price_stream.multiplier self._remove_from_ob(info['identifier']) side = info['side'] cost_basis = side * fill_price * filled_units * multiplier + fees fok = info['fok'] if side == 1: self.portfolio.buy( asset, filled_units, cost_basis ) elif side == -1: self.portfolio.sell( asset, filled_units, cost_basis ) if not fok: if filled_units < info['units']: self.place_order( side, asset, info['units'] - filled_units, time_in_force = info['time_in_force'], order_type = info['order_type'], bands = info['bands'] ) def place_order(self, side, asset, units, time_in_force = None, order_type = 'MARKET', bands = {}, fok = False, peg_to_open = False, temp = False): id_type = asset.id_type identifier = asset.identifier if identifier in list(self.order_book.keys()): self.order_book[identifier].update(self.manager.now) self._remove_from_ob(identifier) self._order_num += 1 if temp: return Order( self.order_num, order_type, asset, side, units, self.manager.now, asset.price_stream.close.v, bands = bands, fok = fok, peg_to_open = peg_to_open, ) else: self.order_book[identifier] = Order( self.order_num, order_type, asset, side, units, self.manager.now, asset.price_stream.close.v, bands = bands, fok = fok, peg_to_open = peg_to_open, ) def max_shares(self, asset): adv = int(asset.price_stream.volume.ts[-self.adv_period:].mean() * self.adv_participation) if asset.id_type == 'FUT': oi = int(asset.price_stream.open_interest.v * self.adv_oi) adv = max(oi, adv) return adv def _process_single_order(self, identifier, order): order.bump() info = order.info asset = order.asset if not asset.tradeable: order.cancel(self.manager.now) self._remove_from_ob(identifier) return side = info['side'] bands = info['bands'] order_type = info['order_type'] units = info['units'] id_type = info['id_type'] fee = self.fee_structure[id_type] open = asset.price_stream.open.v high = asset.price_stream.high.v low = asset.price_stream.low.v close = asset.price_stream.close.v market_value = asset.price_stream.market_value multiplier = asset.price_stream.multiplier max_shares = self.max_shares(asset) filled_units = min(units, max(max_shares, 2)) order_fill = False if order_type == 'MARKET': order_fill = True fill_price = close elif order_type == 'OPEN': order_fill = True fill_price = open elif order_type == 'LIMIT': limit = bands['LIMIT'] if side == 1: if low <= limit: order_fill = True fill_price = limit elif close <= limit: order_fill = True fill_price = limit elif side == -1: if high >= limit: order_fill = True fill_price = limit elif close >= limit: order_fill = True fill_price == limit elif order_type == 'LOF': limit = bands['LIMIT'] if side == 1: if low <= limit: order_fill = True fill_price = limit elif close <= limit: order_fill = True fill_price = limit else: order_fill = True fill_price = close elif side == -1: if high >= limit: order_fill = True fill_price = limit elif close >= limit: order_fill = True fill_price = limit else: order_fill = True fill_price = close elif order_type == 'RANGE': order_fill = True fill_price = (high + low) / 2 elif order_type == 'RANGE_BOUND_C': order_fill = True if side == 1: fill_price = (low + close) / 2 elif side == -1: fill_price = (high + close) / 2 elif order_type == 'INVERSE_BOUND_C': order_fill = True if side == 1: fill_price = (high + close) / 2 elif side == -1: fill_price = (low + close) / 2 elif order_type == 'RANGE_BOUND_O': order_fill = True if side == 1: fill_price = (low + open) / 2 elif side == -1: fill_price = (high + open) / 2 elif order_type == 'INVERSE_BOUND_O': order_fill = True if side == 1: fill_price = (high + open) / 2 elif side == -1: fill_price = (low + open) / 2 elif order_type == 'BEST_FILL': order_fill = True if side == 1: fill_price = low elif side == -1: fill_price = high elif order_type == 'WORST_FILL': order_fill = True if side == 1: fill_price = high elif side == -1: fill_price = low elif order_type == 'TRIANGULAR_C': order_fill = True fill_price = (high + low + close) / 3 elif order_type == 'TRIANGULAR_O': order_fill = True fill_price = (high + low + open) / 3 elif order_type == 'BAR_AVG': order_fill = True fill_price = (high + low + open + close) / 4 elif order_type == 'TWAP': order_fill = True if close > open: ol = (open + low) / 2 hl = (high + low) / 2 hc = (high + close) / 2 fill_price = (ol + hl + hc) / 3 else: oh = (open + high) / 2 hl = (high + low) / 2 lc = (low + close) / 2 fill_price = (oh+hl+lc)/3 if order_fill: self._fill_order(order, fill_price, filled_units, fee * filled_units) if not order_fill and not order.canceled: if not info['time_in_force'] is None and info['time_in_force'] >= info['days_on']: order.cancel() self._remove_from_ob(identifier) def _process_complex_order(self, identifier, order): order.bump() info = order.info asset = order.asset if not asset.tradeable: order.cancel(self.manager.now) self._remove_from_ob(identifier) return side = info['side'] bands = info['bands'] order_type = info['order_type'] units = info['units'] id_type = info['id_type'] fee = self.fee_structure[id_type] open = asset.price_stream.open.v high = asset.price_stream.high.v low = asset.price_stream.low.v close = asset.price_stream.close.v market_value = asset.price_stream.market_value multiplier = asset.price_stream.multiplier max_shares = self.max_shares(asset) filled_units = min(units, max(max_shares, 2)) order_fill = False order.working() self._remove_from_ob(identifier) bid = bands['BID'] ask = bands['ASK'] if order.peg_to_open: bid = open - bid ask = open + ask bid_order = self.place_order(1, asset, units, temp = True) ask_order = self.place_order(-1, asset, units, order_type = 'MM', temp = True) if isinstance(bid, str) and isinstance(ask, str): if bid == 'BEST': self._fill_order(bid_order, low, filled_units, fee * filled_units) if ask == 'BEST': self._fill_order(ask_order, high, filled_units, fee * filled_units) if bid == 'OPEN': self._fill_order(bid_order, open, filled_units, fee * filled_units) if bid == 'CLOSE': self._fill_order(bid_order, close, filled_units, fee * filled_units) if ask == 'OPEN': self._fill_order(ask_order, open, filled_units, fee * filled_units) if ask == 'CLOSE': self._fill_order(ask_order, close, filled_units, fee * filled_units) self._log_order(bid_order) self._log_order(ask_order) else: take_trade = False if low <= bid or high >= ask: take_trade = True if take_trade: if low < bid: self._fill_order(bid_order, bid, filled_units, fee * filled_units) else: self._fill_order(bid_order, close, filled_units, fee * filled_units) if high > ask: self._fill_order(ask_order, ask, filled_units, fee * filled_units) else: self._fill_order(ask_order, close, filled_units, fee * filled_units) self._log_order(bid_order) self._log_order(ask_order) def process(self): for identifier, order in list(self.order_book.items()): if order.side != 0: self._process_single_order(identifier, order) else: self._process_complex_order(identifier, order)
import tactic.norm_num import data.fintype /- M1F May exam 2018, question 3. Solutions by Abhimanyu Pallavi Sudhir, part (d) generalised to all types of size 2 by KMB -/ universe u local attribute [instance, priority 0] classical.prop_decidable --QUESTION 3 variable {S : Type u} -- Q3(a)(i) -- answer variable (binary_relation : S → S → Prop) local infix ` ~ `:1000 := binary_relation -- Q3(a)(ii) def reflexivity := ∀ x, x ~ x def symmetry := ∀ (x y), x ~ y → y ~ x def transitivity := ∀ (x y z), x ~ y → y ~ z → x ~ z -- answer def is_equivalence := reflexivity binary_relation ∧ symmetry binary_relation ∧ transitivity binary_relation -- Q3(a)(iii) variable {binary_relation} -- answer def cl (h : is_equivalence binary_relation) (a : S) : set S := { x | x ~ a } -- Q3(b) theorem classes_injective2 (h : is_equivalence binary_relation) (a b : S) : (cl h a = cl h b) ∨ (cl h a ∩ cl h b) = ∅ := -- answer begin /-duplicate h so we can continue using it as a parameter to cl, then unpack hDupe-/ have hDupe : is_equivalence binary_relation := h, cases hDupe with hR hST, cases hST with hS hT, rw reflexivity at hR, rw symmetry at hS, rw transitivity at hT, /-if one of them is true (if they exclude) we don't need to bother-/ cases classical.em (cl h a ∩ cl h b = ∅) with excl intsct, --case excl right, exact excl, --case intsct left, /-prove that if something isn't empty it must have stuff in it-/ rw set.eq_empty_iff_forall_not_mem at intsct, rw not_forall_not at intsct, /-clean stuff up-/ cases intsct with x intsctX, cases intsctX with intsctXa intsctXb, rw cl at intsctXa, rw cl at intsctXb, change binary_relation x a at intsctXa, change binary_relation x b at intsctXb, rename intsctXa Hrxa, rename intsctXb Hrxb, rw cl, rw cl, /-now do the actual math-/ have Hrax : binary_relation a x, apply hS x a, exact Hrxa, have Hrab : binary_relation a b, apply hT a x b, exact Hrax, exact Hrxb, have Hrba : binary_relation b a, apply hS a b, exact Hrab, /-definition of set equivalence-/ apply set.eq_of_subset_of_subset, --split 1 /-clean things up again-/ intro y, intro Hrya, change binary_relation y a at Hrya, change binary_relation y b, /-do math again-/ apply hT y a b, exact Hrya, exact Hrab, --split 2 /-clean things up again-/ intro y, intro Hryb, change binary_relation y b at Hryb, change binary_relation y a, /-do math again-/ have Hrby : binary_relation b y, apply hS y b, exact Hryb, apply hT y b a, exact Hryb, exact Hrba, end -- Q3(c) inductive double_cosets : ℤ → ℤ → Prop | cond1 : ∀ x, double_cosets x (x + 3) | cond2 : ∀ x, double_cosets x (x - 5) | condT : ∀ x y z, double_cosets x y → double_cosets y z → double_cosets x z -- transitivity local infix ` ⋆ `:1001 := double_cosets theorem double_cosets_reflexive : reflexivity double_cosets := ---answer begin rw reflexivity, intro x, /-get some trivial things out of the way-/ have H0 : x - 5 - 5 - 5 + 3 + 3 + 3 + 3 + 3 = x, norm_num, /-start moving-/ have Hx5x : x ⋆ (x - 5), exact double_cosets.cond2 x, have H5x10x : (x - 5) ⋆ (x - 5 - 5), exact double_cosets.cond2 (x - 5), have H10x15x : (x - 5 - 5) ⋆ (x - 5 - 5 - 5), exact double_cosets.cond2 (x - 5 - 5), /-transitivity is hopper fare-/ have Hx10x : x ⋆ (x - 5 - 5), apply double_cosets.condT x (x - 5) (x - 5 - 5), exact Hx5x, exact H5x10x, have Hx15x : x ⋆ (x - 5 - 5 - 5), apply double_cosets.condT x (x - 5 - 5) (x - 5 - 5 - 5), exact Hx10x, exact H10x15x, /-now come back-/ have H15x12x : (x - 5 - 5 - 5) ⋆ (x - 5 - 5 - 5 + 3), exact double_cosets.cond1 (x - 5 - 5 - 5), have H12x9x : (x - 5 - 5 - 5 + 3) ⋆ (x - 5 - 5 - 5 + 3 + 3), exact double_cosets.cond1 (x - 5 - 5 - 5 + 3), have H9x6x : (x - 5 - 5 - 5 + 3 + 3) ⋆ (x - 5 - 5 - 5 + 3 + 3 + 3), exact double_cosets.cond1 (x - 5 - 5 - 5 + 3 + 3), have H6x3x : (x - 5 - 5 - 5 + 3 + 3 + 3) ⋆ (x - 5 - 5 - 5 + 3 + 3 + 3 + 3), exact double_cosets.cond1 (x - 5 - 5 - 5 + 3 + 3 + 3), have H3xx : (x - 5 - 5 - 5 + 3 + 3 + 3 + 3) ⋆ (x - 5 - 5 - 5 + 3 + 3 + 3 + 3 + 3), exact double_cosets.cond1 (x - 5 - 5 - 5 + 3 + 3 + 3 + 3), /-are we still within 1 hour?-/ have H15x9x : (x - 5 - 5 - 5) ⋆ (x - 5 - 5 - 5 + 3 + 3), apply double_cosets.condT (x - 5 - 5 - 5) (x - 5 - 5 - 5 + 3) (x - 5 - 5 - 5 + 3 + 3), exact H15x12x, exact H12x9x, have H15x6x : (x - 5 - 5 - 5) ⋆ (x - 5 - 5 - 5 + 3 + 3 + 3), apply double_cosets.condT (x - 5 - 5 - 5) (x - 5 - 5 - 5 + 3 + 3) (x - 5 - 5 - 5 + 3 + 3 + 3), exact H15x9x, exact H9x6x, have H15x3x : (x - 5 - 5 - 5) ⋆ (x - 5 - 5 - 5 + 3 + 3 + 3 + 3), apply double_cosets.condT (x - 5 - 5 - 5) (x - 5 - 5 - 5 + 3 + 3 + 3) (x - 5 - 5 - 5 + 3 + 3 + 3 + 3), exact H15x6x, exact H6x3x, have H15xx : (x - 5 - 5 - 5) ⋆ (x - 5 - 5 - 5 + 3 + 3 + 3 + 3 + 3), apply double_cosets.condT (x - 5 - 5 - 5) (x - 5 - 5 - 5 + 3 + 3 + 3 + 3) (x - 5 - 5 - 5 + 3 + 3 + 3 + 3 + 3), exact H15x3x, exact H3xx, have Hxx : x ⋆ (x - 5 - 5 - 5 + 3 + 3 + 3 + 3 + 3), apply double_cosets.condT x (x - 5 - 5 - 5) (x - 5 - 5 - 5 + 3 + 3 + 3 + 3 + 3), exact Hx15x, exact H15xx, /-show that we're back-/ rw H0 at Hxx, exact Hxx, end -- Q3(d) preparation -- first prove the result for `bool`, a concrete set with two elements theorem trans_of_refl_aux (r : bool → bool → Prop) (hr : reflexivity r) : transitivity r := begin rw transitivity, intros x y z, have Hxyyzzx : x = y ∨ y = z ∨ z = x, cases x; cases y; cases z; simp, rcases Hxyyzzx with rfl | rfl | rfl, { intros h hxz, exact hxz}, { intros hxy h, exact hxy}, { intros h1 h2, exact hr z} end -- now deduce it for an arbitrary set with two elements variable [fintype S] -- Q3(d) theorem trans_of_refl (h : fintype.card S = 2) (r : S → S → Prop) (hr : reflexivity r) : transitivity r := begin have Heq : S ≃ bool, { have h1 := trunc.out (fintype.equiv_fin S), rw h at h1, have h2 := trunc.out (fintype.equiv_fin bool), rw fintype.card_bool at h2, exact h1.trans h2.symm, }, -- transport needs to done manually, counterintuitive to mathematicians let rb : bool → bool → Prop := λ b1 b2, r (Heq.symm b1) (Heq.symm b2), have Hr : r = λ x y, rb (Heq x) (Heq y), { ext x y, congr'; simp }, have hrb : reflexivity rb, { intro s, exact hr (Heq.symm s) }, have htb : transitivity rb := trans_of_refl_aux rb hrb, intros x y z hxy hyz, rw Hr, apply htb (Heq x) (Heq y) (Heq z), convert hxy, rw Hr, convert hyz, rw Hr, end
SUBROUTINE CROSS(Z,L,N) COMPLEX Z(1),TEMP,B1 C OBTAIN TWO FFT'S OF REAL-VALUED TIME HISTORIES SIMULTANEDUSLY NN=N CALL FOUR(Z,NN,-1) NH=N/2 NH1=NH+1 B1=AIMAG(Z(1)) Z(1)=REAL(Z(1)) DO 112 I=2,NH TEMP=0.5*(Z(I)+CONJG(Z(N+2-I))) Z(N+2-I)=(0.,-0.5)*(Z(I)-CONJG(Z(N+2-I))) 112 Z(I)=TEMP C COMPUTE THE RAW CROSS SPECTRUM,S FN=FLOAT(N*L) Z(1)=CONJG(Z(1))*B1/FN DO 113 I=2,NH 113 Z(I)=CONJG(Z(I))*Z(N+2-I)/FN Z(NH1)=AIMAG(Z(NH1))*REAL(Z(NH1))/FN DO 114 I=2,NH 114 Z(N+2-I)=CONJG(Z(I)) C COMPUTE THE INVERS FFT OF S TO OBTAIN THE CROSS CORRELATION CALL FOUR(Z,NN,1) A=REAL(Z(1)) WRITE(6,5) A 5 FORMAT(42H1CROSSCOVARIANCE FUNCTION AT THE ORIGIN = ,1PE10.3) WRITE(6,6) 6 FORMAT(1H ,50X,29H CROSSCORRELATION COEFFICIENT) WRITE(6,7) SIG 7 FORMAT(1X,1PE10.3) SIG=1. Z(1)=Z(1)/SIG DO 115 I=2,L Z(N+2-I)=Z(N+2-I)*FLOAT(L)/(SIG*FLOAT(L+1-I)) 115 Z(I)=Z(I)*FLOAT(L)/(SIG*FLOAT(L+1-I)) RETURN END
(* Title: HOL/Auth/n_flash_nodata_cub_lemma_on_inv__4.thy Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences *) header{*The n_flash_nodata_cub Protocol Case Study*} theory n_flash_nodata_cub_lemma_on_inv__4 imports n_flash_nodata_cub_base begin section{*All lemmas on causal relation between inv__4 and some rule r*} lemma n_PI_Remote_GetVsinv__4: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_PI_Remote_Get src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_PI_Remote_Get src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_PI_Remote_GetXVsinv__4: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_PI_Remote_GetX src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_PI_Remote_GetX src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_NakVsinv__4: assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Nak dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Nak dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(dst=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_Nak__part__0Vsinv__4: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_Nak__part__1Vsinv__4: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_Nak__part__2Vsinv__4: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_Get__part__0Vsinv__4: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_Get__part__1Vsinv__4: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_Put_HeadVsinv__4: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_PutVsinv__4: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_Put_DirtyVsinv__4: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_Get_NakVsinv__4: assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_Get_PutVsinv__4: assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_Nak__part__0Vsinv__4: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_Nak__part__1Vsinv__4: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_Nak__part__2Vsinv__4: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_GetX__part__0Vsinv__4: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_GetX__part__1Vsinv__4: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_1Vsinv__4: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_2Vsinv__4: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_3Vsinv__4: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_4Vsinv__4: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_5Vsinv__4: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_6Vsinv__4: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_7__part__0Vsinv__4: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_7__part__1Vsinv__4: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__0Vsinv__4: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__1Vsinv__4: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_8_HomeVsinv__4: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_8_Home_NODE_GetVsinv__4: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_8Vsinv__4: assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_8_NODE_GetVsinv__4: assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_9__part__0Vsinv__4: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeProc'') ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_9__part__1Vsinv__4: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeProc'') ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_10_HomeVsinv__4: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeShrSet'')) (Const true)))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_10Vsinv__4: assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeProc'') ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_11Vsinv__4: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_GetX_NakVsinv__4: assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_GetX_PutXVsinv__4: assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') dst) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeProc'') ''CacheState'')) (Const CACHE_E))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_PutVsinv__4: assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Put dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Put dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(dst=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_PutXVsinv__4: assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_PutX dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_PutX dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(dst=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_PI_Local_Get_PutVsinv__4: assumes a1: "(r=n_PI_Local_Get_Put )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "((formEval (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeProc'') ''InvMarked'')) (Const true)) s))\<or>((formEval (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeProc'') ''InvMarked'')) (Const true))) s))" by auto moreover { assume c1: "((formEval (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeProc'') ''InvMarked'')) (Const true)) s))" have "?P1 s" proof(cut_tac a1 a2 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume c1: "((formEval (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeProc'') ''InvMarked'')) (Const true))) s))" have "?P1 s" proof(cut_tac a1 a2 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_PI_Local_GetX_PutX_HeadVld__part__0Vsinv__4: assumes a1: "(r=n_PI_Local_GetX_PutX_HeadVld__part__0 N )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "?P3 s" apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_PI_Local_GetX_PutX_HeadVld__part__1Vsinv__4: assumes a1: "(r=n_PI_Local_GetX_PutX_HeadVld__part__1 N )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "?P3 s" apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_PI_Local_GetX_PutX__part__0Vsinv__4: assumes a1: "(r=n_PI_Local_GetX_PutX__part__0 )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "?P3 s" apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_PI_Local_GetX_PutX__part__1Vsinv__4: assumes a1: "(r=n_PI_Local_GetX_PutX__part__1 )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "?P3 s" apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_PI_Local_PutXVsinv__4: assumes a1: "(r=n_PI_Local_PutX )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "((formEval (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Pending'')) (Const true)) s))\<or>((formEval (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Pending'')) (Const true))) s))" by auto moreover { assume c1: "((formEval (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Pending'')) (Const true)) s))" have "?P1 s" proof(cut_tac a1 a2 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume c1: "((formEval (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Pending'')) (Const true))) s))" have "?P1 s" proof(cut_tac a1 a2 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_PI_Local_ReplaceVsinv__4: assumes a1: "(r=n_PI_Local_Replace )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Local_PutVsinv__4: assumes a1: "(r=n_NI_Local_Put )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "((formEval (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeProc'') ''InvMarked'')) (Const true)) s))\<or>((formEval (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeProc'') ''InvMarked'')) (Const true))) s))" by auto moreover { assume c1: "((formEval (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeProc'') ''InvMarked'')) (Const true)) s))" have "?P1 s" proof(cut_tac a1 a2 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume c1: "((formEval (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeProc'') ''InvMarked'')) (Const true))) s))" have "?P1 s" proof(cut_tac a1 a2 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_PutXAcksDoneVsinv__4: assumes a1: "(r=n_NI_Local_PutXAcksDone )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__4 p__Inv4" apply fastforce done have "?P3 s" apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeUniMsg'') ''Cmd'')) (Const UNI_PutX))))" in exI, auto) done then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Remote_GetX_PutX_HomeVsinv__4: assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_PutX_Home dst" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_WbVsinv__4: assumes a1: "r=n_NI_Wb " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvAck_3Vsinv__4: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_3 N src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvAck_1Vsinv__4: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_1 N src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_GetX_GetX__part__1Vsinv__4: assumes a1: "r=n_PI_Local_GetX_GetX__part__1 " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_GetX_GetX__part__0Vsinv__4: assumes a1: "r=n_PI_Local_GetX_GetX__part__0 " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Remote_ReplaceVsinv__4: assumes a1: "\<exists> src. src\<le>N\<and>r=n_PI_Remote_Replace src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvAck_existsVsinv__4: assumes a1: "\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_InvAck_exists src pp" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Remote_PutXVsinv__4: assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_PI_Remote_PutX dst" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Remote_Get_Put_HomeVsinv__4: assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Put_Home dst" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvVsinv__4: assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Inv dst" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_ShWbVsinv__4: assumes a1: "r=n_NI_ShWb N " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_ReplaceVsinv__4: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Replace src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Remote_GetX_Nak_HomeVsinv__4: assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_Nak_Home dst" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Remote_Get_Nak_HomeVsinv__4: assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Nak_Home dst" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvAck_exists_HomeVsinv__4: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_exists_Home src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Replace_HomeVsinv__4: assumes a1: "r=n_NI_Replace_Home " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Nak_ClearVsinv__4: assumes a1: "r=n_NI_Nak_Clear " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_Get_GetVsinv__4: assumes a1: "r=n_PI_Local_Get_Get " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Nak_HomeVsinv__4: assumes a1: "r=n_NI_Nak_Home " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvAck_2Vsinv__4: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_2 N src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_FAckVsinv__4: assumes a1: "r=n_NI_FAck " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__4 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done end
Formal statement is: lemma open_contains_cball_eq: "open S \<Longrightarrow> (\<forall>x. x \<in> S \<longleftrightarrow> (\<exists>e>0. cball x e \<subseteq> S))" Informal statement is: A set is open if and only if for every point in the set, there exists a ball around that point that is contained in the set.
lemma convex_hull_scaling: "convex hull ((\<lambda>x. c *\<^sub>R x) ` S) = (\<lambda>x. c *\<^sub>R x) ` (convex hull S)"
Recording sessions of the basic instrumental tracks for Wrapped in Red took place in Kurstin 's Echo Studio in Los Angeles while orchestral sessions were recorded at EastWest Studios in Hollywood and featured vocals recorded in The Barn studio in Nashville . In recording tracks for the album , Clarkson and Kurstin wanted to showcase as many different styles as they could by experimenting in various sounds and styles to create fresh , contemporary sound to classic @-@ sounding music . He recalled , " It was a lot of fun for us because we got to go back to our roots . When Kelly started singing , it was clear she had the chops and had been trained to do anything . " Further adding , " We really experimented . It was so much fun and liberating . And it pays off . " Kurstin , who studied with jazz musician Jaki Byard at The New School for Jazz and Contemporary Music , recruited various jazz and soul musicians such as James Gadson , Kevin Dukes , Roy McCurdy , and Bill Withers to perform on the record to resonate a Memphis soul sound . He also collaborated with Joseph Trapanese to arrange and conduct a chamber orchestra .
[GOAL] I : Type u_1 A : Type u_2 X : I → Type u_3 inst✝¹ : (i : I) → TopologicalSpace (X i) inst✝ : TopologicalSpace A f g : (i : I) → C(A, X i) S : Set A homotopies : (i : I) → HomotopyRel (f i) (g i) S src✝ : Homotopy (ContinuousMap.pi fun i => f i) (ContinuousMap.pi fun i => g i) := Homotopy.pi fun i => (homotopies i).toHomotopy ⊢ ∀ (t : ↑unitInterval) (x : A), x ∈ S → ↑(mk fun x => ContinuousMap.toFun { toContinuousMap := src✝.toContinuousMap, map_zero_left := (_ : ∀ (x : A), ContinuousMap.toFun src✝.toContinuousMap (0, x) = ↑(ContinuousMap.pi fun i => f i) x), map_one_left := (_ : ∀ (x : A), ContinuousMap.toFun src✝.toContinuousMap (1, x) = ↑(ContinuousMap.pi fun i => g i) x) }.toContinuousMap (t, x)) x = ↑(ContinuousMap.pi f) x ∧ ↑(mk fun x => ContinuousMap.toFun { toContinuousMap := src✝.toContinuousMap, map_zero_left := (_ : ∀ (x : A), ContinuousMap.toFun src✝.toContinuousMap (0, x) = ↑(ContinuousMap.pi fun i => f i) x), map_one_left := (_ : ∀ (x : A), ContinuousMap.toFun src✝.toContinuousMap (1, x) = ↑(ContinuousMap.pi fun i => g i) x) }.toContinuousMap (t, x)) x = ↑(ContinuousMap.pi g) x [PROOFSTEP] intro t x hx [GOAL] I : Type u_1 A : Type u_2 X : I → Type u_3 inst✝¹ : (i : I) → TopologicalSpace (X i) inst✝ : TopologicalSpace A f g : (i : I) → C(A, X i) S : Set A homotopies : (i : I) → HomotopyRel (f i) (g i) S src✝ : Homotopy (ContinuousMap.pi fun i => f i) (ContinuousMap.pi fun i => g i) := Homotopy.pi fun i => (homotopies i).toHomotopy t : ↑unitInterval x : A hx : x ∈ S ⊢ ↑(mk fun x => ContinuousMap.toFun { toContinuousMap := src✝.toContinuousMap, map_zero_left := (_ : ∀ (x : A), ContinuousMap.toFun src✝.toContinuousMap (0, x) = ↑(ContinuousMap.pi fun i => f i) x), map_one_left := (_ : ∀ (x : A), ContinuousMap.toFun src✝.toContinuousMap (1, x) = ↑(ContinuousMap.pi fun i => g i) x) }.toContinuousMap (t, x)) x = ↑(ContinuousMap.pi f) x ∧ ↑(mk fun x => ContinuousMap.toFun { toContinuousMap := src✝.toContinuousMap, map_zero_left := (_ : ∀ (x : A), ContinuousMap.toFun src✝.toContinuousMap (0, x) = ↑(ContinuousMap.pi fun i => f i) x), map_one_left := (_ : ∀ (x : A), ContinuousMap.toFun src✝.toContinuousMap (1, x) = ↑(ContinuousMap.pi fun i => g i) x) }.toContinuousMap (t, x)) x = ↑(ContinuousMap.pi g) x [PROOFSTEP] dsimp only [coe_mk, pi_eval, toFun_eq_coe, HomotopyWith.coe_toContinuousMap] [GOAL] I : Type u_1 A : Type u_2 X : I → Type u_3 inst✝¹ : (i : I) → TopologicalSpace (X i) inst✝ : TopologicalSpace A f g : (i : I) → C(A, X i) S : Set A homotopies : (i : I) → HomotopyRel (f i) (g i) S src✝ : Homotopy (ContinuousMap.pi fun i => f i) (ContinuousMap.pi fun i => g i) := Homotopy.pi fun i => (homotopies i).toHomotopy t : ↑unitInterval x : A hx : x ∈ S ⊢ (↑(Homotopy.pi fun i => (homotopies i).toHomotopy).toContinuousMap (t, x) = fun i => ↑(f i) x) ∧ ↑(Homotopy.pi fun i => (homotopies i).toHomotopy).toContinuousMap (t, x) = fun i => ↑(g i) x [PROOFSTEP] simp only [Function.funext_iff, ← forall_and] [GOAL] I : Type u_1 A : Type u_2 X : I → Type u_3 inst✝¹ : (i : I) → TopologicalSpace (X i) inst✝ : TopologicalSpace A f g : (i : I) → C(A, X i) S : Set A homotopies : (i : I) → HomotopyRel (f i) (g i) S src✝ : Homotopy (ContinuousMap.pi fun i => f i) (ContinuousMap.pi fun i => g i) := Homotopy.pi fun i => (homotopies i).toHomotopy t : ↑unitInterval x : A hx : x ∈ S ⊢ ∀ (x_1 : I), ↑(Homotopy.pi fun i => (homotopies i).toHomotopy).toContinuousMap (t, x) x_1 = ↑(f x_1) x ∧ ↑(Homotopy.pi fun i => (homotopies i).toHomotopy).toContinuousMap (t, x) x_1 = ↑(g x_1) x [PROOFSTEP] intro i [GOAL] I : Type u_1 A : Type u_2 X : I → Type u_3 inst✝¹ : (i : I) → TopologicalSpace (X i) inst✝ : TopologicalSpace A f g : (i : I) → C(A, X i) S : Set A homotopies : (i : I) → HomotopyRel (f i) (g i) S src✝ : Homotopy (ContinuousMap.pi fun i => f i) (ContinuousMap.pi fun i => g i) := Homotopy.pi fun i => (homotopies i).toHomotopy t : ↑unitInterval x : A hx : x ∈ S i : I ⊢ ↑(Homotopy.pi fun i => (homotopies i).toHomotopy).toContinuousMap (t, x) i = ↑(f i) x ∧ ↑(Homotopy.pi fun i => (homotopies i).toHomotopy).toContinuousMap (t, x) i = ↑(g i) x [PROOFSTEP] exact (homotopies i).prop' t x hx [GOAL] α : Type u_1 β : Type u_2 inst✝² : TopologicalSpace α inst✝¹ : TopologicalSpace β A : Type u_3 inst✝ : TopologicalSpace A f₀ f₁ : C(A, α) g₀ g₁ : C(A, β) S : Set A F : Homotopy f₀ f₁ G : Homotopy g₀ g₁ x : A ⊢ ContinuousMap.toFun (ContinuousMap.mk fun t => (↑F t, ↑G t)) (0, x) = ↑(ContinuousMap.prodMk f₀ g₀) x [PROOFSTEP] simp only [prod_eval, Homotopy.apply_zero] [GOAL] α : Type u_1 β : Type u_2 inst✝² : TopologicalSpace α inst✝¹ : TopologicalSpace β A : Type u_3 inst✝ : TopologicalSpace A f₀ f₁ : C(A, α) g₀ g₁ : C(A, β) S : Set A F : Homotopy f₀ f₁ G : Homotopy g₀ g₁ x : A ⊢ ContinuousMap.toFun (ContinuousMap.mk fun t => (↑F t, ↑G t)) (1, x) = ↑(ContinuousMap.prodMk f₁ g₁) x [PROOFSTEP] simp only [prod_eval, Homotopy.apply_one] [GOAL] α : Type u_1 β : Type u_2 inst✝² : TopologicalSpace α inst✝¹ : TopologicalSpace β A : Type u_3 inst✝ : TopologicalSpace A f₀ f₁ : C(A, α) g₀ g₁ : C(A, β) S : Set A F : HomotopyRel f₀ f₁ S G : HomotopyRel g₀ g₁ S src✝ : Homotopy (prodMk f₀ g₀) (prodMk f₁ g₁) := Homotopy.prod F.toHomotopy G.toHomotopy ⊢ ∀ (t : ↑unitInterval) (x : A), x ∈ S → ↑(mk fun x => ContinuousMap.toFun { toContinuousMap := src✝.toContinuousMap, map_zero_left := (_ : ∀ (x : A), ContinuousMap.toFun src✝.toContinuousMap (0, x) = ↑(prodMk f₀ g₀) x), map_one_left := (_ : ∀ (x : A), ContinuousMap.toFun src✝.toContinuousMap (1, x) = ↑(prodMk f₁ g₁) x) }.toContinuousMap (t, x)) x = ↑(prodMk f₀ g₀) x ∧ ↑(mk fun x => ContinuousMap.toFun { toContinuousMap := src✝.toContinuousMap, map_zero_left := (_ : ∀ (x : A), ContinuousMap.toFun src✝.toContinuousMap (0, x) = ↑(prodMk f₀ g₀) x), map_one_left := (_ : ∀ (x : A), ContinuousMap.toFun src✝.toContinuousMap (1, x) = ↑(prodMk f₁ g₁) x) }.toContinuousMap (t, x)) x = ↑(prodMk f₁ g₁) x [PROOFSTEP] intro t x hx [GOAL] α : Type u_1 β : Type u_2 inst✝² : TopologicalSpace α inst✝¹ : TopologicalSpace β A : Type u_3 inst✝ : TopologicalSpace A f₀ f₁ : C(A, α) g₀ g₁ : C(A, β) S : Set A F : HomotopyRel f₀ f₁ S G : HomotopyRel g₀ g₁ S src✝ : Homotopy (prodMk f₀ g₀) (prodMk f₁ g₁) := Homotopy.prod F.toHomotopy G.toHomotopy t : ↑unitInterval x : A hx : x ∈ S ⊢ ↑(mk fun x => ContinuousMap.toFun { toContinuousMap := src✝.toContinuousMap, map_zero_left := (_ : ∀ (x : A), ContinuousMap.toFun src✝.toContinuousMap (0, x) = ↑(prodMk f₀ g₀) x), map_one_left := (_ : ∀ (x : A), ContinuousMap.toFun src✝.toContinuousMap (1, x) = ↑(prodMk f₁ g₁) x) }.toContinuousMap (t, x)) x = ↑(prodMk f₀ g₀) x ∧ ↑(mk fun x => ContinuousMap.toFun { toContinuousMap := src✝.toContinuousMap, map_zero_left := (_ : ∀ (x : A), ContinuousMap.toFun src✝.toContinuousMap (0, x) = ↑(prodMk f₀ g₀) x), map_one_left := (_ : ∀ (x : A), ContinuousMap.toFun src✝.toContinuousMap (1, x) = ↑(prodMk f₁ g₁) x) }.toContinuousMap (t, x)) x = ↑(prodMk f₁ g₁) x [PROOFSTEP] have hF := F.prop' t x hx [GOAL] α : Type u_1 β : Type u_2 inst✝² : TopologicalSpace α inst✝¹ : TopologicalSpace β A : Type u_3 inst✝ : TopologicalSpace A f₀ f₁ : C(A, α) g₀ g₁ : C(A, β) S : Set A F : HomotopyRel f₀ f₁ S G : HomotopyRel g₀ g₁ S src✝ : Homotopy (prodMk f₀ g₀) (prodMk f₁ g₁) := Homotopy.prod F.toHomotopy G.toHomotopy t : ↑unitInterval x : A hx : x ∈ S hF : ↑(mk fun x => ContinuousMap.toFun F.toContinuousMap (t, x)) x = ↑f₀ x ∧ ↑(mk fun x => ContinuousMap.toFun F.toContinuousMap (t, x)) x = ↑f₁ x ⊢ ↑(mk fun x => ContinuousMap.toFun { toContinuousMap := src✝.toContinuousMap, map_zero_left := (_ : ∀ (x : A), ContinuousMap.toFun src✝.toContinuousMap (0, x) = ↑(prodMk f₀ g₀) x), map_one_left := (_ : ∀ (x : A), ContinuousMap.toFun src✝.toContinuousMap (1, x) = ↑(prodMk f₁ g₁) x) }.toContinuousMap (t, x)) x = ↑(prodMk f₀ g₀) x ∧ ↑(mk fun x => ContinuousMap.toFun { toContinuousMap := src✝.toContinuousMap, map_zero_left := (_ : ∀ (x : A), ContinuousMap.toFun src✝.toContinuousMap (0, x) = ↑(prodMk f₀ g₀) x), map_one_left := (_ : ∀ (x : A), ContinuousMap.toFun src✝.toContinuousMap (1, x) = ↑(prodMk f₁ g₁) x) }.toContinuousMap (t, x)) x = ↑(prodMk f₁ g₁) x [PROOFSTEP] have hG := G.prop' t x hx [GOAL] α : Type u_1 β : Type u_2 inst✝² : TopologicalSpace α inst✝¹ : TopologicalSpace β A : Type u_3 inst✝ : TopologicalSpace A f₀ f₁ : C(A, α) g₀ g₁ : C(A, β) S : Set A F : HomotopyRel f₀ f₁ S G : HomotopyRel g₀ g₁ S src✝ : Homotopy (prodMk f₀ g₀) (prodMk f₁ g₁) := Homotopy.prod F.toHomotopy G.toHomotopy t : ↑unitInterval x : A hx : x ∈ S hF : ↑(mk fun x => ContinuousMap.toFun F.toContinuousMap (t, x)) x = ↑f₀ x ∧ ↑(mk fun x => ContinuousMap.toFun F.toContinuousMap (t, x)) x = ↑f₁ x hG : ↑(mk fun x => ContinuousMap.toFun G.toContinuousMap (t, x)) x = ↑g₀ x ∧ ↑(mk fun x => ContinuousMap.toFun G.toContinuousMap (t, x)) x = ↑g₁ x ⊢ ↑(mk fun x => ContinuousMap.toFun { toContinuousMap := src✝.toContinuousMap, map_zero_left := (_ : ∀ (x : A), ContinuousMap.toFun src✝.toContinuousMap (0, x) = ↑(prodMk f₀ g₀) x), map_one_left := (_ : ∀ (x : A), ContinuousMap.toFun src✝.toContinuousMap (1, x) = ↑(prodMk f₁ g₁) x) }.toContinuousMap (t, x)) x = ↑(prodMk f₀ g₀) x ∧ ↑(mk fun x => ContinuousMap.toFun { toContinuousMap := src✝.toContinuousMap, map_zero_left := (_ : ∀ (x : A), ContinuousMap.toFun src✝.toContinuousMap (0, x) = ↑(prodMk f₀ g₀) x), map_one_left := (_ : ∀ (x : A), ContinuousMap.toFun src✝.toContinuousMap (1, x) = ↑(prodMk f₁ g₁) x) }.toContinuousMap (t, x)) x = ↑(prodMk f₁ g₁) x [PROOFSTEP] simp only [coe_mk, prod_eval, Prod.mk.inj_iff, Homotopy.prod] at hF hG ⊢ [GOAL] α : Type u_1 β : Type u_2 inst✝² : TopologicalSpace α inst✝¹ : TopologicalSpace β A : Type u_3 inst✝ : TopologicalSpace A f₀ f₁ : C(A, α) g₀ g₁ : C(A, β) S : Set A F : HomotopyRel f₀ f₁ S G : HomotopyRel g₀ g₁ S src✝ : Homotopy (prodMk f₀ g₀) (prodMk f₁ g₁) := Homotopy.prod F.toHomotopy G.toHomotopy t : ↑unitInterval x : A hx : x ∈ S hF : ContinuousMap.toFun F.toContinuousMap (t, x) = ↑f₀ x ∧ ContinuousMap.toFun F.toContinuousMap (t, x) = ↑f₁ x hG : ContinuousMap.toFun G.toContinuousMap (t, x) = ↑g₀ x ∧ ContinuousMap.toFun G.toContinuousMap (t, x) = ↑g₁ x ⊢ (↑F.toHomotopy (t, x) = ↑f₀ x ∧ ↑G.toHomotopy (t, x) = ↑g₀ x) ∧ ↑F.toHomotopy (t, x) = ↑f₁ x ∧ ↑G.toHomotopy (t, x) = ↑g₁ x [PROOFSTEP] exact ⟨⟨hF.1, hG.1⟩, ⟨hF.2, hG.2⟩⟩ [GOAL] ι : Type u_1 X : ι → Type u_2 inst✝ : (i : ι) → TopologicalSpace (X i) as bs cs : (i : ι) → X i γ : (i : ι) → Path (as i) (bs i) ⊢ (pi fun i => Quotient.mk (Homotopic.setoid (as i) (bs i)) (γ i)) = Quotient.mk (Homotopic.setoid (fun i => as i) fun i => bs i) (Path.pi γ) [PROOFSTEP] unfold pi [GOAL] ι : Type u_1 X : ι → Type u_2 inst✝ : (i : ι) → TopologicalSpace (X i) as bs cs : (i : ι) → X i γ : (i : ι) → Path (as i) (bs i) ⊢ Quotient.map Path.pi (_ : ∀ (x y : (i : ι) → Path (as i) (bs i)), x ≈ y → Nonempty (Homotopy (Path.pi x) (Path.pi y))) (Quotient.choice fun i => Quotient.mk (Homotopic.setoid (as i) (bs i)) (γ i)) = Quotient.mk (Homotopic.setoid (fun i => as i) fun i => bs i) (Path.pi γ) [PROOFSTEP] simp [GOAL] ι : Type u_1 X : ι → Type u_2 inst✝ : (i : ι) → TopologicalSpace (X i) as bs cs : (i : ι) → X i γ₀ : (i : ι) → Homotopic.Quotient (as i) (bs i) γ₁ : (i : ι) → Homotopic.Quotient (bs i) (cs i) ⊢ pi γ₀ ⬝ pi γ₁ = pi fun i => γ₀ i ⬝ γ₁ i [PROOFSTEP] apply Quotient.induction_on_pi (p := _) γ₁ [GOAL] ι : Type u_1 X : ι → Type u_2 inst✝ : (i : ι) → TopologicalSpace (X i) as bs cs : (i : ι) → X i γ₀ : (i : ι) → Homotopic.Quotient (as i) (bs i) γ₁ : (i : ι) → Homotopic.Quotient (bs i) (cs i) ⊢ ∀ (a : (i : ι) → Path (bs i) (cs i)), (pi γ₀ ⬝ pi fun i => Quotient.mk (Homotopic.setoid (bs i) (cs i)) (a i)) = pi fun i => γ₀ i ⬝ (fun i => Quotient.mk (Homotopic.setoid (bs i) (cs i)) (a i)) i [PROOFSTEP] intro a [GOAL] ι : Type u_1 X : ι → Type u_2 inst✝ : (i : ι) → TopologicalSpace (X i) as bs cs : (i : ι) → X i γ₀ : (i : ι) → Homotopic.Quotient (as i) (bs i) γ₁ : (i : ι) → Homotopic.Quotient (bs i) (cs i) a : (i : ι) → Path (bs i) (cs i) ⊢ (pi γ₀ ⬝ pi fun i => Quotient.mk (Homotopic.setoid (bs i) (cs i)) (a i)) = pi fun i => γ₀ i ⬝ (fun i => Quotient.mk (Homotopic.setoid (bs i) (cs i)) (a i)) i [PROOFSTEP] apply Quotient.induction_on_pi (p := _) γ₀ [GOAL] ι : Type u_1 X : ι → Type u_2 inst✝ : (i : ι) → TopologicalSpace (X i) as bs cs : (i : ι) → X i γ₀ : (i : ι) → Homotopic.Quotient (as i) (bs i) γ₁ : (i : ι) → Homotopic.Quotient (bs i) (cs i) a : (i : ι) → Path (bs i) (cs i) ⊢ ∀ (a_1 : (i : ι) → Path (as i) (bs i)), ((pi fun i => Quotient.mk (Homotopic.setoid (as i) (bs i)) (a_1 i)) ⬝ pi fun i => Quotient.mk (Homotopic.setoid (bs i) (cs i)) (a i)) = pi fun i => (fun i => Quotient.mk (Homotopic.setoid (as i) (bs i)) (a_1 i)) i ⬝ (fun i => Quotient.mk (Homotopic.setoid (bs i) (cs i)) (a i)) i [PROOFSTEP] intros [GOAL] ι : Type u_1 X : ι → Type u_2 inst✝ : (i : ι) → TopologicalSpace (X i) as bs cs : (i : ι) → X i γ₀ : (i : ι) → Homotopic.Quotient (as i) (bs i) γ₁ : (i : ι) → Homotopic.Quotient (bs i) (cs i) a : (i : ι) → Path (bs i) (cs i) a✝ : (i : ι) → Path (as i) (bs i) ⊢ ((pi fun i => Quotient.mk (Homotopic.setoid (as i) (bs i)) (a✝ i)) ⬝ pi fun i => Quotient.mk (Homotopic.setoid (bs i) (cs i)) (a i)) = pi fun i => (fun i => Quotient.mk (Homotopic.setoid (as i) (bs i)) (a✝ i)) i ⬝ (fun i => Quotient.mk (Homotopic.setoid (bs i) (cs i)) (a i)) i [PROOFSTEP] simp only [pi_lift] [GOAL] ι : Type u_1 X : ι → Type u_2 inst✝ : (i : ι) → TopologicalSpace (X i) as bs cs : (i : ι) → X i γ₀ : (i : ι) → Homotopic.Quotient (as i) (bs i) γ₁ : (i : ι) → Homotopic.Quotient (bs i) (cs i) a : (i : ι) → Path (bs i) (cs i) a✝ : (i : ι) → Path (as i) (bs i) ⊢ Quotient.mk (Homotopic.setoid (fun i => as i) fun i => bs i) (Path.pi fun i => a✝ i) ⬝ Quotient.mk (Homotopic.setoid (fun i => bs i) fun i => cs i) (Path.pi fun i => a i) = pi fun i => Quotient.mk (Homotopic.setoid (as i) (bs i)) (a✝ i) ⬝ Quotient.mk (Homotopic.setoid (bs i) (cs i)) (a i) [PROOFSTEP] rw [← Path.Homotopic.comp_lift, Path.trans_pi_eq_pi_trans, ← pi_lift] [GOAL] ι : Type u_1 X : ι → Type u_2 inst✝ : (i : ι) → TopologicalSpace (X i) as bs cs : (i : ι) → X i γ₀ : (i : ι) → Homotopic.Quotient (as i) (bs i) γ₁ : (i : ι) → Homotopic.Quotient (bs i) (cs i) a : (i : ι) → Path (bs i) (cs i) a✝ : (i : ι) → Path (as i) (bs i) ⊢ (pi fun i => Quotient.mk (Homotopic.setoid (as i) (cs i)) (Path.trans (a✝ i) (a i))) = pi fun i => Quotient.mk (Homotopic.setoid (as i) (bs i)) (a✝ i) ⬝ Quotient.mk (Homotopic.setoid (bs i) (cs i)) (a i) [PROOFSTEP] rfl [GOAL] ι : Type u_1 X : ι → Type u_2 inst✝ : (i : ι) → TopologicalSpace (X i) as bs cs : (i : ι) → X i i : ι paths : (i : ι) → Homotopic.Quotient (as i) (bs i) ⊢ proj i (pi paths) = paths i [PROOFSTEP] apply Quotient.induction_on_pi (p := _) paths [GOAL] ι : Type u_1 X : ι → Type u_2 inst✝ : (i : ι) → TopologicalSpace (X i) as bs cs : (i : ι) → X i i : ι paths : (i : ι) → Homotopic.Quotient (as i) (bs i) ⊢ ∀ (a : (i : ι) → Path (as i) (bs i)), proj i (pi fun i => Quotient.mk (Homotopic.setoid (as i) (bs i)) (a i)) = (fun i => Quotient.mk (Homotopic.setoid (as i) (bs i)) (a i)) i [PROOFSTEP] intro [GOAL] ι : Type u_1 X : ι → Type u_2 inst✝ : (i : ι) → TopologicalSpace (X i) as bs cs : (i : ι) → X i i : ι paths : (i : ι) → Homotopic.Quotient (as i) (bs i) a✝ : (i : ι) → Path (as i) (bs i) ⊢ proj i (pi fun i => Quotient.mk (Homotopic.setoid (as i) (bs i)) (a✝ i)) = (fun i => Quotient.mk (Homotopic.setoid (as i) (bs i)) (a✝ i)) i [PROOFSTEP] unfold proj [GOAL] ι : Type u_1 X : ι → Type u_2 inst✝ : (i : ι) → TopologicalSpace (X i) as bs cs : (i : ι) → X i i : ι paths : (i : ι) → Homotopic.Quotient (as i) (bs i) a✝ : (i : ι) → Path (as i) (bs i) ⊢ Quotient.mapFn (pi fun i => Quotient.mk (Homotopic.setoid (as i) (bs i)) (a✝ i)) (ContinuousMap.mk fun p => p i) = (fun i => Quotient.mk (Homotopic.setoid (as i) (bs i)) (a✝ i)) i [PROOFSTEP] rw [pi_lift, ← Path.Homotopic.map_lift] [GOAL] ι : Type u_1 X : ι → Type u_2 inst✝ : (i : ι) → TopologicalSpace (X i) as bs cs : (i : ι) → X i i : ι paths : (i : ι) → Homotopic.Quotient (as i) (bs i) a✝ : (i : ι) → Path (as i) (bs i) ⊢ Quotient.mk (Homotopic.setoid (↑(ContinuousMap.mk fun p => p i) fun i => as i) (↑(ContinuousMap.mk fun p => p i) fun i => bs i)) (Path.map (Path.pi fun i => a✝ i) (_ : Continuous ↑(ContinuousMap.mk fun p => p i))) = (fun i => Quotient.mk (Homotopic.setoid (as i) (bs i)) (a✝ i)) i [PROOFSTEP] congr [GOAL] ι : Type u_1 X : ι → Type u_2 inst✝ : (i : ι) → TopologicalSpace (X i) as bs cs : (i : ι) → X i p : Homotopic.Quotient as bs ⊢ (pi fun i => proj i p) = p [PROOFSTEP] apply Quotient.inductionOn (motive := _) p [GOAL] ι : Type u_1 X : ι → Type u_2 inst✝ : (i : ι) → TopologicalSpace (X i) as bs cs : (i : ι) → X i p : Homotopic.Quotient as bs ⊢ ∀ (a : Path as bs), (pi fun i => proj i (Quotient.mk (Homotopic.setoid as bs) a)) = Quotient.mk (Homotopic.setoid as bs) a [PROOFSTEP] intro [GOAL] ι : Type u_1 X : ι → Type u_2 inst✝ : (i : ι) → TopologicalSpace (X i) as bs cs : (i : ι) → X i p : Homotopic.Quotient as bs a✝ : Path as bs ⊢ (pi fun i => proj i (Quotient.mk (Homotopic.setoid as bs) a✝)) = Quotient.mk (Homotopic.setoid as bs) a✝ [PROOFSTEP] unfold proj [GOAL] ι : Type u_1 X : ι → Type u_2 inst✝ : (i : ι) → TopologicalSpace (X i) as bs cs : (i : ι) → X i p : Homotopic.Quotient as bs a✝ : Path as bs ⊢ (pi fun i => Quotient.mapFn (Quotient.mk (Homotopic.setoid as bs) a✝) (ContinuousMap.mk fun p => p i)) = Quotient.mk (Homotopic.setoid as bs) a✝ [PROOFSTEP] simp_rw [← Path.Homotopic.map_lift] [GOAL] ι : Type u_1 X : ι → Type u_2 inst✝ : (i : ι) → TopologicalSpace (X i) as bs cs : (i : ι) → X i p : Homotopic.Quotient as bs a✝ : Path as bs ⊢ (pi fun i => Quotient.mk (Homotopic.setoid (↑(ContinuousMap.mk fun p => p i) as) (↑(ContinuousMap.mk fun p => p i) bs)) (Path.map a✝ (_ : Continuous ↑(ContinuousMap.mk fun p => p i)))) = Quotient.mk (Homotopic.setoid as bs) a✝ [PROOFSTEP] erw [pi_lift] [GOAL] ι : Type u_1 X : ι → Type u_2 inst✝ : (i : ι) → TopologicalSpace (X i) as bs cs : (i : ι) → X i p : Homotopic.Quotient as bs a✝ : Path as bs ⊢ Quotient.mk (Homotopic.setoid (fun i => as i) fun i => bs i) (Path.pi fun i => Path.map a✝ (_ : Continuous ↑(ContinuousMap.mk fun p => p i))) = Quotient.mk (Homotopic.setoid as bs) a✝ [PROOFSTEP] congr [GOAL] α : Type u_1 β : Type u_2 inst✝¹ : TopologicalSpace α inst✝ : TopologicalSpace β a₁ a₂ a₃ : α b₁ b₂ b₃ : β p₁ p₁' : Path a₁ a₂ p₂ p₂' : Path b₁ b₂ q₁ : Homotopic.Quotient a₁ a₂ q₂ : Homotopic.Quotient b₁ b₂ r₁ : Homotopic.Quotient a₂ a₃ r₂ : Homotopic.Quotient b₂ b₃ ⊢ prod q₁ q₂ ⬝ prod r₁ r₂ = prod (q₁ ⬝ r₁) (q₂ ⬝ r₂) [PROOFSTEP] apply Quotient.inductionOn₂ (motive := _) q₁ q₂ [GOAL] α : Type u_1 β : Type u_2 inst✝¹ : TopologicalSpace α inst✝ : TopologicalSpace β a₁ a₂ a₃ : α b₁ b₂ b₃ : β p₁ p₁' : Path a₁ a₂ p₂ p₂' : Path b₁ b₂ q₁ : Homotopic.Quotient a₁ a₂ q₂ : Homotopic.Quotient b₁ b₂ r₁ : Homotopic.Quotient a₂ a₃ r₂ : Homotopic.Quotient b₂ b₃ ⊢ ∀ (a : Path a₁ a₂) (b : Path b₁ b₂), prod (Quotient.mk (Homotopic.setoid a₁ a₂) a) (Quotient.mk (Homotopic.setoid b₁ b₂) b) ⬝ prod r₁ r₂ = prod (Quotient.mk (Homotopic.setoid a₁ a₂) a ⬝ r₁) (Quotient.mk (Homotopic.setoid b₁ b₂) b ⬝ r₂) [PROOFSTEP] intro a b [GOAL] α : Type u_1 β : Type u_2 inst✝¹ : TopologicalSpace α inst✝ : TopologicalSpace β a₁ a₂ a₃ : α b₁ b₂ b₃ : β p₁ p₁' : Path a₁ a₂ p₂ p₂' : Path b₁ b₂ q₁ : Homotopic.Quotient a₁ a₂ q₂ : Homotopic.Quotient b₁ b₂ r₁ : Homotopic.Quotient a₂ a₃ r₂ : Homotopic.Quotient b₂ b₃ a : Path a₁ a₂ b : Path b₁ b₂ ⊢ prod (Quotient.mk (Homotopic.setoid a₁ a₂) a) (Quotient.mk (Homotopic.setoid b₁ b₂) b) ⬝ prod r₁ r₂ = prod (Quotient.mk (Homotopic.setoid a₁ a₂) a ⬝ r₁) (Quotient.mk (Homotopic.setoid b₁ b₂) b ⬝ r₂) [PROOFSTEP] apply Quotient.inductionOn₂ (motive := _) r₁ r₂ [GOAL] α : Type u_1 β : Type u_2 inst✝¹ : TopologicalSpace α inst✝ : TopologicalSpace β a₁ a₂ a₃ : α b₁ b₂ b₃ : β p₁ p₁' : Path a₁ a₂ p₂ p₂' : Path b₁ b₂ q₁ : Homotopic.Quotient a₁ a₂ q₂ : Homotopic.Quotient b₁ b₂ r₁ : Homotopic.Quotient a₂ a₃ r₂ : Homotopic.Quotient b₂ b₃ a : Path a₁ a₂ b : Path b₁ b₂ ⊢ ∀ (a_1 : Path a₂ a₃) (b_1 : Path b₂ b₃), prod (Quotient.mk (Homotopic.setoid a₁ a₂) a) (Quotient.mk (Homotopic.setoid b₁ b₂) b) ⬝ prod (Quotient.mk (Homotopic.setoid a₂ a₃) a_1) (Quotient.mk (Homotopic.setoid b₂ b₃) b_1) = prod (Quotient.mk (Homotopic.setoid a₁ a₂) a ⬝ Quotient.mk (Homotopic.setoid a₂ a₃) a_1) (Quotient.mk (Homotopic.setoid b₁ b₂) b ⬝ Quotient.mk (Homotopic.setoid b₂ b₃) b_1) [PROOFSTEP] intros [GOAL] α : Type u_1 β : Type u_2 inst✝¹ : TopologicalSpace α inst✝ : TopologicalSpace β a₁ a₂ a₃ : α b₁ b₂ b₃ : β p₁ p₁' : Path a₁ a₂ p₂ p₂' : Path b₁ b₂ q₁ : Homotopic.Quotient a₁ a₂ q₂ : Homotopic.Quotient b₁ b₂ r₁ : Homotopic.Quotient a₂ a₃ r₂ : Homotopic.Quotient b₂ b₃ a : Path a₁ a₂ b : Path b₁ b₂ a✝ : Path a₂ a₃ b✝ : Path b₂ b₃ ⊢ prod (Quotient.mk (Homotopic.setoid a₁ a₂) a) (Quotient.mk (Homotopic.setoid b₁ b₂) b) ⬝ prod (Quotient.mk (Homotopic.setoid a₂ a₃) a✝) (Quotient.mk (Homotopic.setoid b₂ b₃) b✝) = prod (Quotient.mk (Homotopic.setoid a₁ a₂) a ⬝ Quotient.mk (Homotopic.setoid a₂ a₃) a✝) (Quotient.mk (Homotopic.setoid b₁ b₂) b ⬝ Quotient.mk (Homotopic.setoid b₂ b₃) b✝) [PROOFSTEP] simp only [prod_lift, ← Path.Homotopic.comp_lift, Path.trans_prod_eq_prod_trans] [GOAL] α : Type u_1 β : Type u_2 inst✝¹ : TopologicalSpace α inst✝ : TopologicalSpace β a₁ a₂ a₃ : α b₁ b₂ b₃ : β p₁ p₁' : Path a₁ a₂ p₂ p₂' : Path b₁ b₂ q₁ : Homotopic.Quotient a₁ a₂ q₂ : Homotopic.Quotient b₁ b₂ r₁ : Homotopic.Quotient a₂ a₃ r₂ : Homotopic.Quotient b₂ b₃ c₁ c₂ : α × β ⊢ projLeft (prod q₁ q₂) = q₁ [PROOFSTEP] apply Quotient.inductionOn₂ (motive := _) q₁ q₂ [GOAL] α : Type u_1 β : Type u_2 inst✝¹ : TopologicalSpace α inst✝ : TopologicalSpace β a₁ a₂ a₃ : α b₁ b₂ b₃ : β p₁ p₁' : Path a₁ a₂ p₂ p₂' : Path b₁ b₂ q₁ : Homotopic.Quotient a₁ a₂ q₂ : Homotopic.Quotient b₁ b₂ r₁ : Homotopic.Quotient a₂ a₃ r₂ : Homotopic.Quotient b₂ b₃ c₁ c₂ : α × β ⊢ ∀ (a : Path a₁ a₂) (b : Path b₁ b₂), projLeft (prod (Quotient.mk (Homotopic.setoid a₁ a₂) a) (Quotient.mk (Homotopic.setoid b₁ b₂) b)) = Quotient.mk (Homotopic.setoid a₁ a₂) a [PROOFSTEP] intro p₁ p₂ [GOAL] α : Type u_1 β : Type u_2 inst✝¹ : TopologicalSpace α inst✝ : TopologicalSpace β a₁ a₂ a₃ : α b₁ b₂ b₃ : β p₁✝ p₁' : Path a₁ a₂ p₂✝ p₂' : Path b₁ b₂ q₁ : Homotopic.Quotient a₁ a₂ q₂ : Homotopic.Quotient b₁ b₂ r₁ : Homotopic.Quotient a₂ a₃ r₂ : Homotopic.Quotient b₂ b₃ c₁ c₂ : α × β p₁ : Path a₁ a₂ p₂ : Path b₁ b₂ ⊢ projLeft (prod (Quotient.mk (Homotopic.setoid a₁ a₂) p₁) (Quotient.mk (Homotopic.setoid b₁ b₂) p₂)) = Quotient.mk (Homotopic.setoid a₁ a₂) p₁ [PROOFSTEP] unfold projLeft [GOAL] α : Type u_1 β : Type u_2 inst✝¹ : TopologicalSpace α inst✝ : TopologicalSpace β a₁ a₂ a₃ : α b₁ b₂ b₃ : β p₁✝ p₁' : Path a₁ a₂ p₂✝ p₂' : Path b₁ b₂ q₁ : Homotopic.Quotient a₁ a₂ q₂ : Homotopic.Quotient b₁ b₂ r₁ : Homotopic.Quotient a₂ a₃ r₂ : Homotopic.Quotient b₂ b₃ c₁ c₂ : α × β p₁ : Path a₁ a₂ p₂ : Path b₁ b₂ ⊢ Quotient.mapFn (prod (Quotient.mk (Homotopic.setoid a₁ a₂) p₁) (Quotient.mk (Homotopic.setoid b₁ b₂) p₂)) (ContinuousMap.mk Prod.fst) = Quotient.mk (Homotopic.setoid a₁ a₂) p₁ [PROOFSTEP] rw [prod_lift, ← Path.Homotopic.map_lift] [GOAL] α : Type u_1 β : Type u_2 inst✝¹ : TopologicalSpace α inst✝ : TopologicalSpace β a₁ a₂ a₃ : α b₁ b₂ b₃ : β p₁✝ p₁' : Path a₁ a₂ p₂✝ p₂' : Path b₁ b₂ q₁ : Homotopic.Quotient a₁ a₂ q₂ : Homotopic.Quotient b₁ b₂ r₁ : Homotopic.Quotient a₂ a₃ r₂ : Homotopic.Quotient b₂ b₃ c₁ c₂ : α × β p₁ : Path a₁ a₂ p₂ : Path b₁ b₂ ⊢ Quotient.mk (Homotopic.setoid (↑(ContinuousMap.mk Prod.fst) (a₁, b₁)) (↑(ContinuousMap.mk Prod.fst) (a₂, b₂))) (Path.map (Path.prod p₁ p₂) (_ : Continuous ↑(ContinuousMap.mk Prod.fst))) = Quotient.mk (Homotopic.setoid a₁ a₂) p₁ [PROOFSTEP] congr [GOAL] α : Type u_1 β : Type u_2 inst✝¹ : TopologicalSpace α inst✝ : TopologicalSpace β a₁ a₂ a₃ : α b₁ b₂ b₃ : β p₁ p₁' : Path a₁ a₂ p₂ p₂' : Path b₁ b₂ q₁ : Homotopic.Quotient a₁ a₂ q₂ : Homotopic.Quotient b₁ b₂ r₁ : Homotopic.Quotient a₂ a₃ r₂ : Homotopic.Quotient b₂ b₃ c₁ c₂ : α × β ⊢ projRight (prod q₁ q₂) = q₂ [PROOFSTEP] apply Quotient.inductionOn₂ (motive := _) q₁ q₂ [GOAL] α : Type u_1 β : Type u_2 inst✝¹ : TopologicalSpace α inst✝ : TopologicalSpace β a₁ a₂ a₃ : α b₁ b₂ b₃ : β p₁ p₁' : Path a₁ a₂ p₂ p₂' : Path b₁ b₂ q₁ : Homotopic.Quotient a₁ a₂ q₂ : Homotopic.Quotient b₁ b₂ r₁ : Homotopic.Quotient a₂ a₃ r₂ : Homotopic.Quotient b₂ b₃ c₁ c₂ : α × β ⊢ ∀ (a : Path a₁ a₂) (b : Path b₁ b₂), projRight (prod (Quotient.mk (Homotopic.setoid a₁ a₂) a) (Quotient.mk (Homotopic.setoid b₁ b₂) b)) = Quotient.mk (Homotopic.setoid b₁ b₂) b [PROOFSTEP] intro p₁ p₂ [GOAL] α : Type u_1 β : Type u_2 inst✝¹ : TopologicalSpace α inst✝ : TopologicalSpace β a₁ a₂ a₃ : α b₁ b₂ b₃ : β p₁✝ p₁' : Path a₁ a₂ p₂✝ p₂' : Path b₁ b₂ q₁ : Homotopic.Quotient a₁ a₂ q₂ : Homotopic.Quotient b₁ b₂ r₁ : Homotopic.Quotient a₂ a₃ r₂ : Homotopic.Quotient b₂ b₃ c₁ c₂ : α × β p₁ : Path a₁ a₂ p₂ : Path b₁ b₂ ⊢ projRight (prod (Quotient.mk (Homotopic.setoid a₁ a₂) p₁) (Quotient.mk (Homotopic.setoid b₁ b₂) p₂)) = Quotient.mk (Homotopic.setoid b₁ b₂) p₂ [PROOFSTEP] unfold projRight [GOAL] α : Type u_1 β : Type u_2 inst✝¹ : TopologicalSpace α inst✝ : TopologicalSpace β a₁ a₂ a₃ : α b₁ b₂ b₃ : β p₁✝ p₁' : Path a₁ a₂ p₂✝ p₂' : Path b₁ b₂ q₁ : Homotopic.Quotient a₁ a₂ q₂ : Homotopic.Quotient b₁ b₂ r₁ : Homotopic.Quotient a₂ a₃ r₂ : Homotopic.Quotient b₂ b₃ c₁ c₂ : α × β p₁ : Path a₁ a₂ p₂ : Path b₁ b₂ ⊢ Quotient.mapFn (prod (Quotient.mk (Homotopic.setoid a₁ a₂) p₁) (Quotient.mk (Homotopic.setoid b₁ b₂) p₂)) (ContinuousMap.mk Prod.snd) = Quotient.mk (Homotopic.setoid b₁ b₂) p₂ [PROOFSTEP] rw [prod_lift, ← Path.Homotopic.map_lift] [GOAL] α : Type u_1 β : Type u_2 inst✝¹ : TopologicalSpace α inst✝ : TopologicalSpace β a₁ a₂ a₃ : α b₁ b₂ b₃ : β p₁✝ p₁' : Path a₁ a₂ p₂✝ p₂' : Path b₁ b₂ q₁ : Homotopic.Quotient a₁ a₂ q₂ : Homotopic.Quotient b₁ b₂ r₁ : Homotopic.Quotient a₂ a₃ r₂ : Homotopic.Quotient b₂ b₃ c₁ c₂ : α × β p₁ : Path a₁ a₂ p₂ : Path b₁ b₂ ⊢ Quotient.mk (Homotopic.setoid (↑(ContinuousMap.mk Prod.snd) (a₁, b₁)) (↑(ContinuousMap.mk Prod.snd) (a₂, b₂))) (Path.map (Path.prod p₁ p₂) (_ : Continuous ↑(ContinuousMap.mk Prod.snd))) = Quotient.mk (Homotopic.setoid b₁ b₂) p₂ [PROOFSTEP] congr [GOAL] α : Type u_1 β : Type u_2 inst✝¹ : TopologicalSpace α inst✝ : TopologicalSpace β a₁ a₂ a₃ : α b₁ b₂ b₃ : β p₁ p₁' : Path a₁ a₂ p₂ p₂' : Path b₁ b₂ q₁ : Homotopic.Quotient a₁ a₂ q₂ : Homotopic.Quotient b₁ b₂ r₁ : Homotopic.Quotient a₂ a₃ r₂ : Homotopic.Quotient b₂ b₃ c₁ c₂ : α × β p : Homotopic.Quotient (a₁, b₁) (a₂, b₂) ⊢ prod (projLeft p) (projRight p) = p [PROOFSTEP] apply Quotient.inductionOn (motive := _) p [GOAL] α : Type u_1 β : Type u_2 inst✝¹ : TopologicalSpace α inst✝ : TopologicalSpace β a₁ a₂ a₃ : α b₁ b₂ b₃ : β p₁ p₁' : Path a₁ a₂ p₂ p₂' : Path b₁ b₂ q₁ : Homotopic.Quotient a₁ a₂ q₂ : Homotopic.Quotient b₁ b₂ r₁ : Homotopic.Quotient a₂ a₃ r₂ : Homotopic.Quotient b₂ b₃ c₁ c₂ : α × β p : Homotopic.Quotient (a₁, b₁) (a₂, b₂) ⊢ ∀ (a : Path (a₁, b₁) (a₂, b₂)), prod (projLeft (Quotient.mk (Homotopic.setoid (a₁, b₁) (a₂, b₂)) a)) (projRight (Quotient.mk (Homotopic.setoid (a₁, b₁) (a₂, b₂)) a)) = Quotient.mk (Homotopic.setoid (a₁, b₁) (a₂, b₂)) a [PROOFSTEP] intro p' [GOAL] α : Type u_1 β : Type u_2 inst✝¹ : TopologicalSpace α inst✝ : TopologicalSpace β a₁ a₂ a₃ : α b₁ b₂ b₃ : β p₁ p₁' : Path a₁ a₂ p₂ p₂' : Path b₁ b₂ q₁ : Homotopic.Quotient a₁ a₂ q₂ : Homotopic.Quotient b₁ b₂ r₁ : Homotopic.Quotient a₂ a₃ r₂ : Homotopic.Quotient b₂ b₃ c₁ c₂ : α × β p : Homotopic.Quotient (a₁, b₁) (a₂, b₂) p' : Path (a₁, b₁) (a₂, b₂) ⊢ prod (projLeft (Quotient.mk (Homotopic.setoid (a₁, b₁) (a₂, b₂)) p')) (projRight (Quotient.mk (Homotopic.setoid (a₁, b₁) (a₂, b₂)) p')) = Quotient.mk (Homotopic.setoid (a₁, b₁) (a₂, b₂)) p' [PROOFSTEP] unfold projLeft [GOAL] α : Type u_1 β : Type u_2 inst✝¹ : TopologicalSpace α inst✝ : TopologicalSpace β a₁ a₂ a₃ : α b₁ b₂ b₃ : β p₁ p₁' : Path a₁ a₂ p₂ p₂' : Path b₁ b₂ q₁ : Homotopic.Quotient a₁ a₂ q₂ : Homotopic.Quotient b₁ b₂ r₁ : Homotopic.Quotient a₂ a₃ r₂ : Homotopic.Quotient b₂ b₃ c₁ c₂ : α × β p : Homotopic.Quotient (a₁, b₁) (a₂, b₂) p' : Path (a₁, b₁) (a₂, b₂) ⊢ prod (Quotient.mapFn (Quotient.mk (Homotopic.setoid (a₁, b₁) (a₂, b₂)) p') (ContinuousMap.mk Prod.fst)) (projRight (Quotient.mk (Homotopic.setoid (a₁, b₁) (a₂, b₂)) p')) = Quotient.mk (Homotopic.setoid (a₁, b₁) (a₂, b₂)) p' [PROOFSTEP] unfold projRight [GOAL] α : Type u_1 β : Type u_2 inst✝¹ : TopologicalSpace α inst✝ : TopologicalSpace β a₁ a₂ a₃ : α b₁ b₂ b₃ : β p₁ p₁' : Path a₁ a₂ p₂ p₂' : Path b₁ b₂ q₁ : Homotopic.Quotient a₁ a₂ q₂ : Homotopic.Quotient b₁ b₂ r₁ : Homotopic.Quotient a₂ a₃ r₂ : Homotopic.Quotient b₂ b₃ c₁ c₂ : α × β p : Homotopic.Quotient (a₁, b₁) (a₂, b₂) p' : Path (a₁, b₁) (a₂, b₂) ⊢ prod (Quotient.mapFn (Quotient.mk (Homotopic.setoid (a₁, b₁) (a₂, b₂)) p') (ContinuousMap.mk Prod.fst)) (Quotient.mapFn (Quotient.mk (Homotopic.setoid (a₁, b₁) (a₂, b₂)) p') (ContinuousMap.mk Prod.snd)) = Quotient.mk (Homotopic.setoid (a₁, b₁) (a₂, b₂)) p' [PROOFSTEP] simp only [← Path.Homotopic.map_lift, prod_lift] [GOAL] α : Type u_1 β : Type u_2 inst✝¹ : TopologicalSpace α inst✝ : TopologicalSpace β a₁ a₂ a₃ : α b₁ b₂ b₃ : β p₁ p₁' : Path a₁ a₂ p₂ p₂' : Path b₁ b₂ q₁ : Homotopic.Quotient a₁ a₂ q₂ : Homotopic.Quotient b₁ b₂ r₁ : Homotopic.Quotient a₂ a₃ r₂ : Homotopic.Quotient b₂ b₃ c₁ c₂ : α × β p : Homotopic.Quotient (a₁, b₁) (a₂, b₂) p' : Path (a₁, b₁) (a₂, b₂) ⊢ prod (Quotient.mk (Homotopic.setoid (↑(ContinuousMap.mk Prod.fst) (a₁, b₁)) (↑(ContinuousMap.mk Prod.fst) (a₂, b₂))) (Path.map p' (_ : Continuous ↑(ContinuousMap.mk Prod.fst)))) (Quotient.mk (Homotopic.setoid (↑(ContinuousMap.mk Prod.snd) (a₁, b₁)) (↑(ContinuousMap.mk Prod.snd) (a₂, b₂))) (Path.map p' (_ : Continuous ↑(ContinuousMap.mk Prod.snd)))) = Quotient.mk (Homotopic.setoid (a₁, b₁) (a₂, b₂)) p' [PROOFSTEP] congr
The components of a topological space are pairwise disjoint.
# title : GBM vs Light GBM in R # author : Heo Sung Wook # depends : h2o library(h2o) # before using h2o, 'h2o.init()' must be needed. h2o.init() h2o.removeAll() # read data set churn <- read.csv("../data/churn.csv") # for using h2o, data must be "h2o data frame" churn_hex <- as.h2o(churn) # split data, train:valid:test = 6:2:2 splits <- h2o.splitFrame(churn_hex, c(0.6,0.2), seed=1234) # assign train, valid, test each train <- h2o.assign(splits[[1]], "train.hex") valid <- h2o.assign(splits[[2]], "valid.hex") test <- h2o.assign(splits[[3]], "test.hex") # 20's column is target('Churn.') colnames(churn) # parameter = default start.time <- Sys.time() ml_GBM <- h2o.gbm(training_frame = train, validation_frame = valid, x=1:19, y=20, seed = 1234) Sys.time() - start.time # check time # check model performance by using test data set # AUC = 0.9118117 # LogLoss = 0.1953534 h2o.performance(ml_GBM, newdata = test) # In h2o, there is no specific module for LightGBM yet. # Instead, using "tree_method='hist'" and "grow_policy='lossguide'" in h2o.xgboost() offer "LightGBM algorithm" to us # you can find detail information in h2o website => http://docs.h2o.ai/h2o/latest-stable/h2o-docs/data-science/xgboost.html # parameter = default start.time <- Sys.time() ml_LGB <- h2o.xgboost( training_frame = train, validation_frame = valid, x=1:19, y=20, tree_method="hist", grow_policy="lossguide", seed = 1234) Sys.time() - start.time # check time # check model performance by using test data set # AUC = 0.9234419 # LogLoss = 0.1694313 h2o.performance(ml_LGB, newdata = test)
If $f$ is a continuous function from a topological space to a normed vector space, and $f(a) \neq 0$, then the sign function of $f$ is continuous at $a$.
C ********************************************************* C * * C * TEST NUMBER: 04.02.05.01/01 * C * TEST TITLE : Simple setting and inquiring * C * * C * PHIGS Validation Tests, produced by NIST * C * * C ********************************************************* COMMON /GLOBNU/ CTLHND, ERRSIG, ERRFIL, IERRCT, UNERR, 1 TESTCT, IFLERR, PASSSW, ERRSW, MAXLIN, 2 CONID, MEMUN, WKID, WTYPE, GLBLUN, INDLUN, 3 DUMINT, DUMRL INTEGER CTLHND, ERRSIG, ERRFIL, IERRCT, UNERR, 1 TESTCT, IFLERR, PASSSW, ERRSW, MAXLIN, 2 CONID, MEMUN, WKID, WTYPE, GLBLUN, INDLUN, 3 DUMINT(20), ERRIND REAL DUMRL(20) COMMON /GLOBCH/ PIDENT, GLBERR, TSTMSG, FUNCID, 1 DUMCH CHARACTER PIDENT*40, GLBERR*60, TSTMSG*900, FUNCID*80, 1 DUMCH(20)*20 INTEGER INLEN, RELEN, STLEN PARAMETER (INLEN=50, RELEN=50, STLEN=50) C PHIGS parameter types INTEGER ELTYPE, INTLEN, INTG, RLLEN, RL, STRLEN, STR, STRID INTEGER INTAR (INLEN), STRARL (STLEN) REAL RLAR (RELEN), RPTVAR (9) CHARACTER STRAR (STLEN), MSG*200 INTEGER I, ISTYLE, EFLAG REAL RINCR, RATR1,RATR2 C interior style INTEGER PHOLLO, PSOLID, PPATTR, PHATCH, PISEMP PARAMETER (PHOLLO=0, PSOLID=1, PPATTR=2, PHATCH=3, PISEMP=4) C edge flag indicator INTEGER POFF, PON PARAMETER (POFF=0, PON=1) CALL INITGL ('04.02.05.01/01') C open PHIGS CALL XPOPPH (ERRFIL, MEMUN) C structure identifier = 1 STRID = 1 C open structure CALL POPST (STRID) C *** *** *** *** *** Interior style *** *** *** *** *** C set value for attribute CALL PSIS (PPATTR) CALL SETMSG ('1 5', '<Inquire current element type ' // 1 'and size> should return interior style ' // 2 'as the type of the created element and ' // 3 'the appropriate element size.') CALL PQCETS (ERRIND, ELTYPE, INTLEN, RLLEN, STRLEN) C checking correct element type C 43 is the PHIGS enumeration type for peis CALL IFPF (ERRIND .EQ. 0 .AND. 1 ELTYPE .EQ. 43 .AND. 2 INTLEN .EQ. 1 .AND. 3 RLLEN .EQ. 0 .AND. 4 STRLEN .EQ. 0) CALL SETMSG ('2 5 6', '<Inquire current element content> ' // 1 'should return the standard representation for ' // 2 'all valid interior style values.') DO 100 ISTYLE = PHOLLO, PISEMP CALL PSIS (ISTYLE) CALL PQCECO (INLEN, RELEN, STLEN, ERRIND, INTG, INTAR, 1 RL, RLAR, STR, STRARL, STRAR) IF (ERRIND .EQ. 0 .AND. 1 INTAR(1) .EQ. ISTYLE .AND. 2 INTG .EQ. 1 .AND. 3 RL .EQ. 0 .AND. 4 STR .EQ. 0) THEN C OK so far ELSE CALL FAIL WRITE (MSG, '(A,I2,A)') 'Failure for interior style = ', 1 ISTYLE, '.' CALL INMSG (MSG) GOTO 110 ENDIF 100 CONTINUE CALL PASS 110 CONTINUE C *** *** *** *** *** Interior style index *** *** *** *** *** C set value for attribute CALL PSISI (5) CALL SETMSG ('1 18', '<Inquire current element type ' // 1 'and size> should return interior style ' // 2 'index as the type of the created element ' // 3 'and the appropriate element size.') CALL PQCETS (ERRIND, ELTYPE, INTLEN, RLLEN, STRLEN) C checking correct element type C 44 is the PHIGS enumeration type for peisi CALL IFPF (ERRIND .EQ. 0 .AND. 1 ELTYPE .EQ. 44 .AND. 2 INTLEN .EQ. 1 .AND. 3 RLLEN .EQ. 0 .AND. 4 STRLEN .EQ. 0) CALL SETMSG ('2 18', '<Inquire current element content> ' // 1 'should return the standard representation for ' // 2 'the interior style index value.') CALL PQCECO (INLEN, RELEN, STLEN, ERRIND, INTG, INTAR, 1 RL, RLAR, STR, STRARL, STRAR) C checking correct output parameters for data record type peisi CALL IFPF (ERRIND .EQ. 0 .AND. 1 INTAR(1) .EQ. 5 .AND. 2 INTG .EQ. 1 .AND. 3 RL .EQ. 0 .AND. 4 STR .EQ. 0) C *** *** *** *** *** Interior colour index *** *** *** *** *** C set value for attribute CALL PSICI (2) CALL SETMSG ('1 26', '<Inquire current element type ' // 1 'and size> should return interior ' // 2 'colour index as the type of the ' // 3 'created element and the appropriate ' // 4 'element size.') CALL PQCETS (ERRIND, ELTYPE, INTLEN, RLLEN, STRLEN) C checking correct element type C 45 is the PHIGS enumeration type for peici CALL IFPF (ERRIND .EQ. 0 .AND. 1 ELTYPE .EQ. 45 .AND. 2 INTLEN .EQ. 1 .AND. 3 RLLEN .EQ. 0 .AND. 4 STRLEN .EQ. 0) CALL SETMSG ('2 26', '<Inquire current element content> ' // 1 'should return the standard representation for ' // 2 'the interior colour index value.') CALL PQCECO (INLEN, RELEN, STLEN, ERRIND, INTG, INTAR, 1 RL, RLAR, STR, STRARL, STRAR) C checking correct output parameters for data record type peici CALL IFPF (ERRIND .EQ. 0 .AND. 1 INTAR(1) .EQ. 2 .AND. 2 INTG .EQ. 1 .AND. 3 RL .EQ. 0 .AND. 4 STR .EQ. 0) C *** *** *** *** *** Pattern size *** *** *** *** *** C set value for attribute RATR1 = 4.1 RATR2 = 5.1 CALL PSPA (RATR1, RATR2) CALL SETMSG ('1 61', '<Inquire current element type ' // 1 'and size> should return pattern size ' // 2 'as the type of the created element and ' // 3 'the appropriate element size.') CALL PQCETS (ERRIND, ELTYPE, INTLEN, RLLEN, STRLEN) C checking correct element type C 50 is the PHIGS enumeration type for pepa CALL IFPF (ERRIND .EQ. 0 .AND. 1 ELTYPE .EQ. 50 .AND. 2 INTLEN .EQ. 0 .AND. 3 RLLEN .EQ. 2 .AND. 4 STRLEN .EQ. 0) CALL SETMSG ('2 61', '<Inquire current element content> ' // 1 'should return the standard representation for ' // 2 'the pattern size value.') CALL PQCECO (INLEN, RELEN, STLEN, ERRIND, INTG, INTAR, 1 RL, RLAR, STR, STRARL, STRAR) C checking correct output parameters for data record type peii CALL IFPF (ERRIND .EQ. 0 .AND. 1 RLAR(1) .EQ. RATR1 .AND. 1 RLAR(2) .EQ. RATR2 .AND. 2 INTG .EQ. 0 .AND. 3 RL .EQ. 2 .AND. 4 STR .EQ. 0) C *** *** *** Pattern reference point and vectors *** *** *** C set value for attribute RINCR = 0.5 DO 200 I = 1,9 RPTVAR(I) = RINCR RINCR = RINCR + 0.2 200 CONTINUE CALL PSPRPV (RPTVAR(1), RPTVAR(2), RPTVAR(3), 1 RPTVAR(4), RPTVAR(6), RPTVAR(8) ) CALL SETMSG ('1 66', '<Inquire current element type ' // 1 'and size> should return pattern reference ' // 2 'point and vectors as the type of the ' // 3 'created element and the appropriate ' // 4 'element size.') CALL PQCETS (ERRIND, ELTYPE, INTLEN, RLLEN, STRLEN) C checking correct element type C 51 is the PHIGS enumeration type for peprpv CALL IFPF (ERRIND .EQ. 0 .AND. 1 ELTYPE .EQ. 51 .AND. 2 INTLEN .EQ. 0 .AND. 3 RLLEN .EQ. 9 .AND. 4 STRLEN .EQ. 0) CALL SETMSG ('2 66', '<Inquire current element content> ' // 1 'should return the standard representation for ' // 2 'the pattern reference point and vectors values.') CALL PQCECO (INLEN, RELEN, STLEN, ERRIND, INTG, INTAR, 1 RL, RLAR, STR, STRARL, STRAR) C checking correct output parameters for data record type peprpv CALL IFPF (ERRIND .EQ. 0 .AND. C reference point: 1 RLAR(1) .EQ. RPTVAR(1) .AND. 2 RLAR(2) .EQ. RPTVAR(2) .AND. 3 RLAR(3) .EQ. RPTVAR(3) .AND. C vector 1: 1 RLAR(4) .EQ. RPTVAR(4) .AND. 2 RLAR(5) .EQ. RPTVAR(6) .AND. 3 RLAR(6) .EQ. RPTVAR(8) .AND. C vector 2: 1 RLAR(7) .EQ. RPTVAR(5) .AND. 2 RLAR(8) .EQ. RPTVAR(7) .AND. 3 RLAR(9) .EQ. RPTVAR(9) .AND. C array sizes: 1 INTG .EQ. 0 .AND. 2 RL .EQ. 9 .AND. 3 STR .EQ. 0) C *** *** *** *** Pattern reference point *** *** *** *** 300 CONTINUE C set value for attribute RATR1 = 0.35 RATR2 = 0.21 CALL PSPARF (RATR1, RATR2) CALL SETMSG ('1 67', '<Inquire current element type ' // 1 'and size> should return pattern reference ' // 2 'point as the type of the created element ' // 3 'and the appropriate element size.') CALL PQCETS (ERRIND, ELTYPE, INTLEN, RLLEN, STRLEN) C checking correct element type C 52 is the PHIGS enumeration type for peparf CALL IFPF (ERRIND .EQ. 0 .AND. 1 ELTYPE .EQ. 52 .AND. 2 INTLEN .EQ. 0 .AND. 3 RLLEN .EQ. 2 .AND. 4 STRLEN .EQ. 0) CALL SETMSG ('2 67', '<Inquire current element content> ' // 1 'should return the standard representation for ' // 2 'the pattern reference point values.') CALL PQCECO (INLEN, RELEN, STLEN, ERRIND, INTG, INTAR, 1 RL, RLAR, STR, STRARL, STRAR) C checking correct output parameters for data record type peprpv CALL IFPF (ERRIND .EQ. 0 .AND. 1 RLAR(1) .EQ. RATR1 .AND. 2 RLAR(2) .EQ. RATR2 .AND. 3 INTG .EQ. 0 .AND. 4 RL .EQ. 2 .AND. 5 STR .EQ. 0) C *** *** *** *** *** Edge flag *** *** *** *** *** C set value for attribute CALL PSEDFG (PON) CALL SETMSG ('1 32', '<Inquire current element type ' // 1 'and size> should return edge flag as ' // 2 'the type of the created element and ' // 3 'the appropriate element size.') CALL PQCETS (ERRIND, ELTYPE, INTLEN, RLLEN, STRLEN) C checking correct element type C 46 is the PHIGS enumeration type for peedfg CALL IFPF (ERRIND .EQ. 0 .AND. 1 ELTYPE .EQ. 46 .AND. 2 INTLEN .EQ. 1 .AND. 3 RLLEN .EQ. 0 .AND. 4 STRLEN .EQ. 0) CALL SETMSG ('2 32 33', '<Inquire current element content> ' // 1 'should return the standard representation for ' // 2 'all valid edge flag values.') DO 1100 EFLAG = POFF, PON CALL PSEDFG (EFLAG) CALL PQCECO (INLEN, RELEN, STLEN, ERRIND, INTG, INTAR, 1 RL, RLAR, STR, STRARL, STRAR) IF (ERRIND .EQ. 0 .AND. 1 INTAR(1) .EQ. EFLAG .AND. 2 INTG .EQ. 1 .AND. 3 RL .EQ. 0 .AND. 4 STR .EQ. 0) THEN C OK so far ELSE CALL FAIL WRITE (MSG, '(A,I2,A)') 'Failure for edge flag = ', 1 EFLAG, '.' CALL INMSG (MSG) GOTO 1110 ENDIF 1100 CONTINUE CALL PASS 1110 CONTINUE C *** *** *** *** *** Edgetype *** *** *** *** *** C set value for attribute CALL PSEDT (6) CALL SETMSG ('1 40', '<Inquire current element type ' // 1 'and size> should return edgetype ' // 2 'as the type of the created element and ' // 3 'the appropriate element size.') CALL PQCETS (ERRIND, ELTYPE, INTLEN, RLLEN, STRLEN) C checking correct element type C 47 is the PHIGS enumeration type for peedt CALL IFPF (ERRIND .EQ. 0 .AND. 1 ELTYPE .EQ. 47 .AND. 2 INTLEN .EQ. 1 .AND. 3 RLLEN .EQ. 0 .AND. 4 STRLEN .EQ. 0) CALL SETMSG ('2 40', '<Inquire current element content> ' // 1 'should return the standard representation for ' // 2 'the edgetype value.') CALL PQCECO (INLEN, RELEN, STLEN, ERRIND, INTG, INTAR, 1 RL, RLAR, STR, STRARL, STRAR) C checking correct output parameters for data record type peedt CALL IFPF (ERRIND .EQ. 0 .AND. 1 INTAR(1) .EQ. 6 .AND. 2 INTG .EQ. 1 .AND. 3 RL .EQ. 0 .AND. 4 STR .EQ. 0) C *** *** *** *** Edgewidth scale factor *** *** *** *** C set value for attribute RATR1 = 0.33 CALL PSEWSC (RATR1) CALL SETMSG ('1 49', '<Inquire current element type ' // 1 'and size> should return edgewidth ' // 2 'scale factor as the type of the ' // 3 'created element and the appropriate ' // 4 'element size.') CALL PQCETS (ERRIND, ELTYPE, INTLEN, RLLEN, STRLEN) C checking correct element type C 48 is the PHIGS enumeration type for peewsc CALL IFPF (ERRIND .EQ. 0 .AND. 1 ELTYPE .EQ. 48 .AND. 2 INTLEN .EQ. 0 .AND. 3 RLLEN .EQ. 1 .AND. 4 STRLEN .EQ. 0) CALL SETMSG ('2 49', '<Inquire current element content> ' // 1 'should return the standard representation for ' // 2 'the edgewidth scale factor value.') CALL PQCECO (INLEN, RELEN, STLEN, ERRIND, INTG, INTAR, 1 RL, RLAR, STR, STRARL, STRAR) C checking correct output parameters for data record type peewsc CALL IFPF (ERRIND .EQ. 0 .AND. 1 RLAR(1) .EQ. RATR1 .AND. 2 INTG .EQ. 0 .AND. 3 RL .EQ. 1 .AND. 4 STR .EQ. 0) C *** *** *** *** *** Edge colour index *** *** *** *** *** C set value for attribute CALL PSEDCI (3) CALL SETMSG ('1 55', '<Inquire current element type ' // 1 'and size> should return edge colour index ' // 2 'as the type of the created element ' // 3 'and the appropriate element size.') CALL PQCETS (ERRIND, ELTYPE, INTLEN, RLLEN, STRLEN) C checking correct element type C 49 is the PHIGS enumeration type for peedci CALL IFPF (ERRIND .EQ. 0 .AND. 1 ELTYPE .EQ. 49 .AND. 2 INTLEN .EQ. 1 .AND. 3 RLLEN .EQ. 0 .AND. 4 STRLEN .EQ. 0) CALL SETMSG ('2 55', '<Inquire current element content> ' // 1 'should return the standard representation for ' // 2 'the edge colour index value.') CALL PQCECO (INLEN, RELEN, STLEN, ERRIND, INTG, INTAR, 1 RL, RLAR, STR, STRARL, STRAR) C checking correct output parameters for data record type pepmi CALL IFPF (ERRIND .EQ. 0 .AND. 1 INTAR(1) .EQ. 3 .AND. 2 INTG .EQ. 1 .AND. 3 RL .EQ. 0 .AND. 4 STR .EQ. 0) CALL ENDIT END
Formal statement is: lemma filterlim_divide_at_infinity: fixes f g :: "'a \<Rightarrow> 'a :: real_normed_field" assumes "filterlim f (nhds c) F" "filterlim g (at 0) F" "c \<noteq> 0" shows "filterlim (\<lambda>x. f x / g x) at_infinity F" Informal statement is: If $f$ and $g$ are functions such that $f$ approaches $c$ and $g$ approaches $0$, then $f/g$ approaches $\infty$.
#redirect Bob Black
module TooManyFields where postulate X : Set record D : Set where field x : X d : X -> D d x = record {x = x; y = x}
#Introduction Linear algebra is a field of mathematics that is widely used in various disciplines. Linear algebra plays an important role in data science and machine learning. A solid understanding of linear algebra concepts can enhance the understanding of many data science and machine learning algorithms. This chapter introduces basic concepts for data science and includes vector spaces, orthogonality, eigenvalues, matrix decomposition and further expanded to include linear regression and principal component analysis where linear algebra plays a central role for solving data science problems. More advanced concepts and applications of linear algebra can be found in many references $[1, 2, 3, 4]$. #Elements of Linear Algebra ##Linear Spaces ###Linear Combinations ```python import numpy as np v = np.array([[3.3],[11]]) w = np.array([[-2],[-40]]) a = 1.5 b = 4.9 u = a*v + b*w u ``` array([[ -4.85], [-179.5 ]]) ```python import numpy as np x = np.array([[4, 8, 1], [2, 11, 0], [1, 7.4, 0.2]]) y = ([3.65, 1.55, 3.42]) result = np.linalg.solve(x, y) result ``` array([-2.19148936, 0.5393617 , 8.10106383]) ###Linear Independence and Dimension ```python import sympy import numpy as np matrix = np.array([[2,1,7],[2,9,11]]) _, inds = sympy.Matrix(matrix).T.rref() print(inds) ``` (0, 1) This means vetor 0 and vector 1 are linearly independent. ```python matrix = np.array([[0,1,0,0],[0,0,1,0],[0,1,1,0],[1,0,0,1]]) _, inds = sympy.Matrix(matrix).T.rref() print(inds) ``` (0, 1, 3) This means vetor 0, vector 1, and vector 3 are lineatly independent while vector 2 is linearly dependent. ##Orthogonality Inner product ```python a = np.array([1.6,2.5,3.9]) b = np.array([4,1,11]) np.inner(a, b) ``` 51.8 Norm ```python from numpy import linalg as LA c = np.array([[ 1.3, -7.2, 12.1], [-1, 0, 4]]) LA.norm(c) ``` 14.728883189162714 Orthogonality ```python v1 = np.array([1,-2, 4]) v2 = np.array([2, 5, 2]) dot_product = np.dot(v1,v2) if dot_product == 0: print('v1 and v2 are orthorgonal') else: print('v1 and v2 are not orthorgonal') ``` v1 and v2 are orthorgonal ```python n1 = LA.norm(v1) n2 = LA.norm(v2) if n1 == 1 and n2 == 1: print('v1 and v2 are orthornormal') else: print('v1 and v2 are not orthornormal') ``` v1 and v2 are not orthornormal ##Gram-Schmidt Process ```python import numpy as np def gs(X): Q, R = np.linalg.qr(X) return Q ``` ```python X = np.array([[3,-1,0],[1.8,11.3,-7.5], [4,13/4,-7/3]]) gs(X) ``` array([[-0.56453245, 0.40891852, -0.71699983], [-0.33871947, -0.90691722, -0.25053997], [-0.75270993, 0.10142386, 0.65049286]]) ##Eigenvalues and Eigenvectors ```python import numpy as np from numpy.linalg import eig a = np.array([[2.1, -5/2, 11.4], [1, 3, 5], [2.4, 3.5, 7.4]]) u,v=eig(a) print('E-value:', u) print('E-vector', v) ``` E-value: [12.05944603 -1.69840975 2.13896373] E-vector [[-0.63272391 -0.94998594 0.88313257] [-0.42654701 -0.10917553 -0.45885676] [-0.64631115 0.29258746 -0.09760805]] #Linear Regression ##QR Decomposition ```python import numpy as np from numpy.linalg import qr m = np.array([[1/2, -2.8, 5/3], [2.5, 3, 9], [8.3, 4, -5.2]]) q, r = qr(m) print('Q:', q) print('R:', r) n = np.dot(q, r) print('QR:', n) ``` Q: [[-0.0575855 0.87080492 -0.4882445 ] [-0.28792749 -0.48276155 -0.82706653] [-0.95591928 0.09295198 0.27852874]] R: [[-8.6827415 -4.5262202 2.28345698] [ 0. -3.51473053 -3.3768627 ] [ 0. 0. -9.70568907]] QR: [[ 0.5 -2.8 1.66666667] [ 2.5 3. 9. ] [ 8.3 4. -5.2 ]] ##Least-squares Problems Use direct inverse method ```python import numpy as np from scipy import optimize import matplotlib.pyplot as plt plt.style.use('seaborn-poster') x = np.linspace(0, 10, 500) y = 1/2 + x * np.random.random(len(x)) A = np.vstack([x, np.ones(len(x))]).T y = y[:, np.newaxis] lst_sqr = np.dot((np.dot(np.linalg.inv(np.dot(A.T,A)),A.T)),y) print(lst_sqr) ``` [[0.5248105 ] [0.48146998]] Use the pseudoinverse ```python pinv = np.linalg.pinv(A) lst_sqr = pinv.dot(y) print(lst_sqr) ``` [[0.5248105 ] [0.48146998]] Use numpy.linalg.lstsq ```python lst_sqr = np.linalg.lstsq(A, y, rcond=None)[0] print(lst_sqr) ``` [[0.5248105 ] [0.48146998]] Use optimize.curve_fit from scipy ```python x = np.linspace(0, 10, 500) y = 1/2 + x * np.random.random(len(x)) def func(x, a, b): y = a*x + b return y lst_sqr = optimize.curve_fit(func, xdata = x, ydata = y)[0] print(lst_sqr) ``` [0.55132487 0.30482114] ## Linear Regression ```python import numpy as np from sklearn.linear_model import LinearRegression x = np.array([5.3, 15.2, 25.8, 35.4, 45.5, 54.9]).reshape((-1, 1)) y = np.array([4.7, 20.4, 31/2, 33.2, 22, 38.6]) model = LinearRegression().fit(x, y) r_sq = model.score(x, y) print('coefficient of determination:', r_sq) ``` coefficient of determination: 0.7007120636613271 ```python print('intercept:', model.intercept_) ``` intercept: 5.763991287587402 ```python print('slope:', model.coef_) ``` slope: [0.54813867] ```python y_pred = model.predict(x) print('predicted response:', y_pred, sep='\n') ``` predicted response: [ 8.66912625 14.09569911 19.90596904 25.1681003 30.70430089 35.85680441] #Principal Component Analysis ##Singular Value Decomposition ```python from numpy import array from scipy.linalg import svd A = array([[3, -2, 5], [1, 0, -3], [4, 6, -1]]) print('Matrix A:') print(A) U, sigma, VT = svd(A) print('The m × m orthogonal matrix:') print(U) print('The m × n diagonal matrix:') print(sigma) print('The n × n orthogonal matrix:') print(VT) ``` Matrix A: [[ 3 -2 5] [ 1 0 -3] [ 4 6 -1]] The m × m orthogonal matrix: [[-0.38248394 0.86430926 0.32661221] [ 0.23115377 -0.25273925 0.93951626] [ 0.89458033 0.43484753 -0.10311964]] The m × n diagonal matrix: [7.54629306 6.24447219 2.24945061] The n × n orthogonal matrix: [[ 0.35275906 0.81264401 -0.46386502] [ 0.6533104 0.14099937 0.74384454] [ 0.66988548 -0.56544574 -0.48116998]] ##Principal Component Analysis Covariance Matrix ```python A = array([[3, -2, 5], [1, 0, -3], [4, 6, -1]]) covMatrix = np.cov(A,bias=True) print('Covariance matrix of A:') print(covMatrix) ``` Covariance matrix of A: [[ 8.66666667 -2.66666667 -7.66666667] [-2.66666667 2.88888889 4.33333333] [-7.66666667 4.33333333 8.66666667]] Principal Component Analysis ```python import numpy as np from numpy.linalg import eig X = np.random.randint(10,50,100).reshape(20,5) X_meaned = X - np.mean(X , axis = 0) covMatrix = np.cov(X_meaned, rowvar = False) val,vec = eig(covMatrix) s_index = np.argsort(val)[::-1] s_val = val[s_index] s_vec = vec[:,s_index] n_components = 8 vec_sub = s_vec[:,0:n_components] #Transform the data X_reduced = np.dot(vec_sub.transpose(), X_meaned.transpose()).transpose() X_reduced ``` array([[-14.2097599 , 11.1638481 , 0.28399481, 6.72774374, -6.5223102 ], [ 25.06735619, 0.65710691, 6.85236627, -0.17476694, -6.8806175 ], [-21.61411193, -13.0377964 , -12.16006542, 5.05948329, 5.30216639], [-27.78196313, -9.86254508, -6.96332075, 2.28424895, -1.19146972], [ -0.22967199, 24.5661952 , 2.66240043, 2.63708048, 5.03380919], [ 11.15926987, 17.71804406, 2.51916061, 5.85025062, -5.6923201 ], [ 11.5482325 , -9.11311102, 9.98129819, -10.96725047, 11.84124727], [ 5.57296606, -7.13463359, -25.32274739, 2.06609699, -0.24750938], [-17.22161772, -11.97678995, 13.20560437, -14.20500239, -11.55139844], [-13.62600723, 17.70093422, 8.90913338, 2.01548555, 3.03422397], [-26.51289728, -8.97206962, 4.14445894, 7.02884273, -2.02967354], [ -4.03180426, 25.35080447, -18.62772438, -7.32506778, 0.4062433 ], [ 14.2056229 , -6.05889182, 11.24736988, -5.4258927 , -6.71408721], [ 20.30238914, -14.09296297, -7.57112907, 6.59989966, -5.98775578], [-11.4490343 , -18.98788569, 10.6311743 , 1.03120515, 6.07676389], [ 11.12612414, 3.55634731, 19.45836326, 11.10664498, -1.5839167 ], [ 27.74171335, -14.62724333, -18.83519665, 1.72806277, 0.85015228], [ -3.39768961, 8.03689297, -7.86477459, -2.56432008, 2.22848377], [ 0.40503237, 6.32555287, -4.50101459, -16.90395115, 0.59424993], [ 12.94585082, -1.21179662, 11.95064838, 3.43120659, 13.03371858]]) Total Variance ```python B = covMatrix total_var_matr = B.trace() print('Total variance of A:') print(total_var_matr) ``` Total variance of A: 716.65
{-# OPTIONS --cubical --no-import-sorts --safe #-} module Cubical.Categories.Functor.Base where open import Cubical.Foundations.Prelude open import Cubical.Data.Sigma open import Cubical.Categories.Category private variable ℓC ℓC' ℓD ℓD' : Level record Functor (C : Precategory ℓC ℓC') (D : Precategory ℓD ℓD') : Type (ℓ-max (ℓ-max ℓC ℓC') (ℓ-max ℓD ℓD')) where no-eta-equality open Precategory field F-ob : C .ob → D .ob F-hom : {x y : C .ob} → C [ x , y ] → D [(F-ob x) , (F-ob y)] F-id : {x : C .ob} → F-hom (C .id x) ≡ D .id (F-ob x) F-seq : {x y z : C .ob} (f : C [ x , y ]) (g : C [ y , z ]) → F-hom (f ⋆⟨ C ⟩ g) ≡ (F-hom f) ⋆⟨ D ⟩ (F-hom g) isFull = (x y : _) (F[f] : D [(F-ob x) , (F-ob y)]) → ∃ (C [ x , y ]) (λ f → F-hom f ≡ F[f]) isFaithful = (x y : _) (f g : C [ x , y ]) → F-hom f ≡ F-hom g → f ≡ g isEssentiallySurj = ∀ (d : D .ob) → Σ[ c ∈ C .ob ] CatIso {C = D} (F-ob c) d private variable ℓ ℓ' : Level C D E : Precategory ℓ ℓ' open Precategory open Functor -- Helpful notation -- action on objects infix 30 _⟅_⟆ _⟅_⟆ : (F : Functor C D) → C .ob → D .ob _⟅_⟆ = F-ob -- action on morphisms infix 30 _⟪_⟫ -- same infix level as on objects since these will never be used in the same context _⟪_⟫ : (F : Functor C D) → ∀ {x y} → C [ x , y ] → D [(F ⟅ x ⟆) , (F ⟅ y ⟆)] _⟪_⟫ = F-hom -- Functor constructions 𝟙⟨_⟩ : ∀ (C : Precategory ℓ ℓ') → Functor C C 𝟙⟨ C ⟩ .F-ob x = x 𝟙⟨ C ⟩ .F-hom f = f 𝟙⟨ C ⟩ .F-id = refl 𝟙⟨ C ⟩ .F-seq _ _ = refl -- functor composition funcComp : ∀ (G : Functor D E) (F : Functor C D) → Functor C E (funcComp G F) .F-ob c = G ⟅ F ⟅ c ⟆ ⟆ (funcComp G F) .F-hom f = G ⟪ F ⟪ f ⟫ ⟫ (funcComp {D = D} {E = E} {C = C} G F) .F-id {c} = (G ⟪ F ⟪ C .id c ⟫ ⟫) ≡⟨ cong (G ⟪_⟫) (F .F-id) ⟩ G .F-id -- (G ⟪ D .id (F ⟅ c ⟆) ⟫) -- deleted this cause the extra refl composition was annoying -- ≡⟨ G .F-id ⟩ -- E .id (G ⟅ F ⟅ c ⟆ ⟆) -- ∎ (funcComp {D = D} {E = E} {C = C} G F) .F-seq {x} {y} {z} f g = (G ⟪ F ⟪ f ⋆⟨ C ⟩ g ⟫ ⟫) ≡⟨ cong (G ⟪_⟫) (F .F-seq _ _) ⟩ G .F-seq _ _ -- (G ⟪ (F ⟪ f ⟫) ⋆⟨ D ⟩ (F ⟪ g ⟫) ⟫) -- deleted for same reason as above -- ≡⟨ G .F-seq _ _ ⟩ -- (G ⟪ F ⟪ f ⟫ ⟫) ⋆⟨ E ⟩ (G ⟪ F ⟪ g ⟫ ⟫) -- ∎ infixr 30 funcComp syntax funcComp G F = G ∘F F _^opF : Functor C D → Functor (C ^op) (D ^op) (F ^opF) .F-ob = F .F-ob (F ^opF) .F-hom = F .F-hom (F ^opF) .F-id = F .F-id (F ^opF) .F-seq f g = F .F-seq g f
#ifndef SIMPLEBOT_DRIVER_HPP #define SIMPLEBOT_DRIVER_HPP #include <JetsonGPIO.h> #include <string> #include <cmath> #include <boost/asio.hpp> #include "nlohmann/json.hpp" #include <ros/ros.h> typedef struct { int pinPWM; int pinDirA; int pinDirB; } pinInfo; typedef struct{ int left; int right; } encoderData; class simplebotDriver { public: simplebotDriver(pinInfo left,pinInfo right, std::string serialPort,int baudRate); ~simplebotDriver(); void outputToMotor(int outputDutyLeft,int outputDutyRight); encoderData readEncoderFromMotor();//todo リクエスト送ったらエンコーダ更新実装(マイコン側要変更) private: std::shared_ptr<GPIO::PWM> rightPWM_; std::shared_ptr<GPIO::PWM> leftPWM_; boost::asio::serial_port *serial_; pinInfo rightPin_; pinInfo leftPin_; std::string serialPort_; int baudRate_; void outputToMotorDir_(int Duty,pinInfo pin); }; #endif //SIMPLEBOT_DRIVER_HPP
State Before: α : Type u_1 β : Type u_2 l : AssocList α β ⊢ isEmpty l = List.isEmpty (toList l) State After: no goals Tactic: cases l <;> simp [*, isEmpty, List.isEmpty]
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef INCLUDED_DATAFLAVORMAPPING_HXX_ #define INCLUDED_DATAFLAVORMAPPING_HXX_ #include <com/sun/star/datatransfer/DataFlavor.hpp> #include <com/sun/star/datatransfer/XMimeContentTypeFactory.hpp> #include <com/sun/star/datatransfer/XTransferable.hpp> #include <com/sun/star/lang/XMultiComponentFactory.hpp> #include <premac.h> #import <Cocoa/Cocoa.h> #include <postmac.h> #include <hash_map> #include <memory> #include <boost/shared_ptr.hpp> /* An interface to get the clipboard data in either system or OOo format. */ class DataProvider { public: virtual ~DataProvider() {}; /* Get the clipboard data in the system format. The caller has to retain/release the returned CFDataRef on demand. */ virtual NSData* getSystemData() = 0; /* Get the clipboard data in OOo format. */ virtual com::sun::star::uno::Any getOOoData() = 0; }; typedef std::auto_ptr<DataProvider> DataProviderPtr_t; //################################ class DataFlavorMapper { public: /* Initialialize a DataFavorMapper instance. Throws a RuntimeException in case the XMimeContentTypeFactory service cannot be created. */ DataFlavorMapper(); ~DataFlavorMapper(); /* Map a system data flavor to an OpenOffice data flavor. Return an empty string if there is not suiteable mapping from a system data flavor to a OpenOffice data flavor. */ com::sun::star::datatransfer::DataFlavor systemToOpenOfficeFlavor( const NSString* systemDataFlavor) const; /* Map an OpenOffice data flavor to a system data flavor. If there is no suiteable mapping available NULL will be returned. */ const NSString* openOfficeToSystemFlavor(const com::sun::star::datatransfer::DataFlavor& oooDataFlavor, bool& rbInternal) const; /* Select the best available image data type If there is no suiteable mapping available NULL will be returned. */ NSString* openOfficeImageToSystemFlavor(NSPasteboard* pPasteboard) const; /* Get a data provider which is able to provide the data 'rTransferable' offers in a format that can be put on to the system clipboard. */ DataProviderPtr_t getDataProvider( const NSString* systemFlavor, const com::sun::star::uno::Reference< com::sun::star::datatransfer::XTransferable > rTransferable) const; /* Get a data provider which is able to provide 'systemData' in the OOo expected format. */ DataProviderPtr_t getDataProvider( const NSString* systemFlavor, NSArray* systemData) const; /* Get a data provider which is able to provide 'systemData' in the OOo expected format. */ DataProviderPtr_t getDataProvider( const NSString* systemFlavor, NSData* systemData) const; /* Translate a sequence of DataFlavors into a NSArray of system types. Only those DataFlavors for which a suitable mapping to a system type exist will be contained in the returned types array. */ NSArray* flavorSequenceToTypesArray(const com::sun::star::uno::Sequence<com::sun::star::datatransfer::DataFlavor>& flavors) const; /* Translate a NSArray of system types into a sequence of DataFlavors. Only those types for which a suitable mapping to a DataFlavor exist will be contained in the new DataFlavor Sequence. */ com::sun::star::uno::Sequence<com::sun::star::datatransfer::DataFlavor> typesArrayToFlavorSequence(NSArray* types) const; /* Returns an NSArray containing all pasteboard types supported by OOo */ NSArray* getAllSupportedPboardTypes() const; private: /* Determines if the provided Mime content type is valid. */ bool isValidMimeContentType(const rtl::OUString& contentType) const; private: ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XMimeContentTypeFactory> mrXMimeCntFactory; typedef std::hash_map< rtl::OUString, NSString*, rtl::OUStringHash > OfficeOnlyTypes; mutable OfficeOnlyTypes maOfficeOnlyTypes; }; typedef boost::shared_ptr<DataFlavorMapper> DataFlavorMapperPtr_t; #endif
function [MSLPoints,coeffData]=ellips2MSLHelmert(points,useNGAApprox,modelType,coeffData) %%ELLIPS2MSLHELMERT Given points in WGS-84 ellipsoidal coordinates, % convert the ellipsoidal height components of the % points into heights above mean-sea level (MSL) % using Helmert's projection method with the EGM2008 % gravitational (and terrain correction) models. This % differs from the more precise but seldom-used % Pizzetti's projection method in that the curvature of % the plumb line is completely ignored. % %INPUTS: points One or more points given in WGS-84 geodetic latitude and % longitude, in radians, and height, in meters for which the % corresponding MSL heights are desired. To convert N points, % points is a 3XN matrix with each column having the format % [latitude;longitude; height]. % useNGAApprox If one wishes the intermediate tide-free geoid computation % to match the results of the National Geospatial % Intelligence Agency's code to three digits after the % decimal point, then this should be true. Setting this to % false might produce results that are marginally more % accurate. The default is false if this parameter is % omitted. % modelType An optional parameter specifying coefficient model to % load if coeffData is not provided. Possible values are % 0 (The default if omitted) Load the EGM2008 model. % 1 Load the EGM96 model. % coeffData A set of pre-loaded coefficients that can speed up the % computation by eliminating the need to compute them on the % fly. coeffData is as defined for the coeffData return value % of getEGMGeoidHeight. % %OUTPUTS: MSLPoints A 3XN array of the converted points, where each vector % contains [latitude;longitude;MSLHeight]; The latitude % and longitude are unchanged from the input data, but % the heights have been converted from WGS-84 ellipsoidal % heights to MSL heights. % coeffData The coeffData coefficients that can be passed to % another call of ellips2MSLHelmert or MSL2EllipseHelmert % to make it faster. % %Note that this function will be very slow if one hasn't called %CompileCLibraries to compile the spherical harmonic synthesis functions. % %As described in Chapter 5.5 of [1], the MSL height using Helmert's %projection is just the ellipsoidal height minus the geoid height. This %function calls getEGMGeoidHeight to get the geoidal height and %subtracts it off. % %Helmert's projection calculated the height using a line from the point to %the reference ellipsoid, subtracting off the distance from the point to %the geoid along the line. Pizzetti's projection follows the curved plumb %line down to the geoid. Thus, the latitude and longitude of the projected %point on the geoid are not the same as that of the point being projected. %The MSL height obtained is also slightly different. However, the %difference is small and Pizzetti's projection is difficult to use, so %Helmert's projection is almost always used. % %The inverse of this function is MSL2EllipseHelmert. % %REFERENCES: %[1] B. Hofmann-Wellenhof and H. Moritz, Physical Geodesy, 2nd ed. % SpringerWienNewYork, 2006. % %January 2014 David F. Crouse, Naval Research Laboratory, Washington D.C. %(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release. if(nargin<2||isempty(useNGAApprox)) useNGAApprox=false; end if(nargin<3||isempty(modelType)) modelType=0; end if(nargin>3) [geoidHeight,coeffData]=getEGMGeoidHeight(points(1:2,:),1,useNGAApprox,modelType,coeffData); else [geoidHeight,coeffData]=getEGMGeoidHeight(points(1:2,:),1,useNGAApprox,modelType); end MSLHeight=points(3,:)-geoidHeight'; numPoints=size(points,2); MSLPoints=zeros(3,numPoints); MSLPoints(1:2,:)=points(1:2,:); MSLPoints(3,:)=MSLHeight; end %LICENSE: % %The source code is in the public domain and not licensed or under %copyright. The information and software may be used freely by the public. %As required by 17 U.S.C. 403, third parties producing copyrighted works %consisting predominantly of the material produced by U.S. government %agencies must provide notice with such work(s) identifying the U.S. %Government material incorporated and stating that such material is not %subject to copyright protection. % %Derived works shall not identify themselves in a manner that implies an %endorsement by or an affiliation with the Naval Research Laboratory. % %RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE %SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL %RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS %OF RECIPIENT IN THE USE OF THE SOFTWARE.
import itertools import scipy.cluster.hierarchy as cluster import matplotlib.pyplot as plt import os.path import rsabias.core.features as features import rsabias.core.dataset as dataset class TableException(Exception): pass def show_dendrogram(linkage, labels, threshold): d = cluster.dendrogram(linkage, labels=labels, above_threshold_color='gray', orientation='left', color_threshold=threshold) # TODO color labels: # http://www.nxn.se/valent/extract-cluster-elements-by-color-in-python plt.axvline(x=threshold) # TODO collapse source versions deep under threshold class Table: def __init__(self, top_transformation): self.trans = top_transformation def import_json(self): pass def export_json(self): pass @staticmethod def group(metas, dists, trans, norm=1, out_path=None, threshold_hint=None): """ Add treshold as a parameter. If defined, save fig (matplotlib). If not defined, set default treshold. Then, we have to show the dendrogram plot. We have to capture the clickevent to set alternative treshold. We're doing this as long as we're not satisfied with the treshold. When the plot is closed, save the current treshold. """ names = set(d.name for d in dists) classes = set(type(d) for d in dists) if len(names) != 1 or len(classes) != 1: raise TableException('Cannot group different distributions') name = names.pop() if name != trans.name(): raise TableException('Transformations not matching "{}" and "{}"' .format(name, trans.name())) cls = classes.pop() if cls == features.MultiFeatureDistribution: sub_dists = zip(*[d.counts for d in dists]) sub_trans = trans.trans sub_groups = [Table.group(metas, sd, st, norm=norm, out_path=out_path) for sd, st in zip(sub_dists, sub_trans)] return ['*'.join([str(t) for t in sg]) for sg in zip(*sub_groups)] else: combinations = list(itertools.combinations(range(len(dists)), 2)) distances = [dists[a].distance(dists[b], norm) for (a, b) in combinations] linkage = cluster.linkage(distances) threshold = 0.1 # TODO dynamic threshold if out_path: figure = plt.figure(figsize=(10, 20)) labels = ['{} ({})'.format(' '.join(m.source()), m.files[0].records) for m in metas] tp = ThresholdPicker(figure, linkage, labels) show_dendrogram(linkage, labels, threshold) plt.title(name) #plt.tight_layout() tp.connect() plt.show() tp.disconnect() plt.close(figure) threshold = tp.threshold # plt.show() destroys the picture, draw again for saving figure = plt.figure(figsize=(10, 20)) show_dendrogram(linkage, labels, threshold) plt.title(name) #plt.tight_layout() # TODO too long file_path = os.path.join(out_path, 'dendogram_{}_{}.pdf'.format(name, norm)) # file_path = os.path.join(out_path, 'dendogram_{}_{}.pdf'.format('private', norm)) plt.savefig(file_path, dpi=3000) plt.close(figure) groups = cluster.fcluster(linkage, threshold, criterion='distance') return list(groups) @staticmethod def marginalize_partial(metas, dists, trans, subspaces, output_path): """ Compute marginal distributions for specific subspaces """ marginal_trans = [] for dimensions in subspaces: marginal_trans.append(trans.subspace(dimensions)) independent = features.Append(marginal_trans) for d, meta in zip(dists, metas): marginal_dists = [] for dimensions in subspaces: marginal_dists.append(d.subspace(dimensions)) m = features.MultiFeatureDistribution(independent, marginal_dists) w = dataset.Writer(output_path, meta, skip_writing=True) w.save_distributions(m) w.close() # TODO output independent transformation print(independent.name()) @staticmethod def marginalize(metas, dists, trans, output_path): independent = features.Append(trans.trans) for d, meta in zip(dists, metas): if isinstance(d, features.MultiDimDistribution): m = features.MultiFeatureDistribution(independent, d.marginal) w = dataset.Writer(output_path, meta, skip_writing=True) w.save_distributions(m) w.close() class ThresholdPicker: def __init__(self, figure, linkage, labels): self.figure = figure self.linkage = linkage self.cid_press = None self.cid_release = None self.labels = labels self.threshold = None def connect(self): self.cid_press = self.figure.canvas.mpl_connect( 'button_press_event', self.on_press) self.cid_release = self.figure.canvas.mpl_connect( 'button_release_event', self.on_release) def on_press(self, event): # TODO do all in on_release, skip if mouse dragged threshold = event.xdata if threshold is None or threshold < 0: return self.threshold = threshold plt.cla() show_dendrogram(self.linkage, self.labels, threshold) def on_release(self, event): self.figure.canvas.draw() def disconnect(self): self.figure.canvas.mpl_disconnect(self.cid_press) self.figure.canvas.mpl_disconnect(self.cid_release)
subroutine hruallo !! ~ ~ ~ PURPOSE ~ ~ ~ !! This subroutine calculates the number of management operation types, etc. !! used in the simulation. These values are used to allocate array sizes for !! processes occurring in the HRU. !! ~ ~ ~ OUTGOING VARIABLES ~ ~ ~ !! name |units |definition !! ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ !! mapp |none |max number of applications !! mcr |none |max number of crops grown per year !! mcut |none |max number of cuttings per year !! mgr |none |max number of grazings per year !! mlyr |none |max number of soil layers !! mnr |none |max number of years of rotation !! pstflg(:) |none |flag for types of pesticide used in watershed !! |array location is pesticide ID number !! |0: pesticide not used !! |1: pesticide used !! ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ !! ~ ~ ~ LOCAL VARIABLES ~ ~ ~ !! name |units |definition !! ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ !! ap_af |none |number of autofertilizer operations in mgt file !! ap_ai |none |number of autoirrigation operations in mgt file !! ap_cc |none |number of continuous cuuting operations in mgt !! ap_cf |none |number of continuous fertilization operations in mgt !! ap_ci |none |number of continuous irrigation operations in mgt !! ap_f |none |number of fertilizer operations in mgt file !! ap_i |none |number of irrigation operations in mgt file !! ap_p |none |number of pesticide operations in mgt file !! ap_r |none |number of release/impound operations in mgt file !! ap_s |none |number of sweep operations in mgt file !! ap_t |none |number of tillage operations in mgt file !! chmfile |NA |HRU soil chemical data file name (.chm) !! cut |none |number of harvest only operations in mgt file !! depth(:) |mm |depth to bottom of soil layer !! eof |none |end of file flag (=-1 if eof, else =0) !! grz |none |number of grazing operations in mgt file !! hkll |none |number of harvest/kill operations in mgt file !! hru |none |number of HRUs in subbasin !! hrufile |NA |name of HRU general data file name (.hru) !! ii |none |counter !! j |none |counter !! k |none |counter !! kll |none |number of kill operations in mgt file !! lyrtot |none |total number of layers in profile !! mgt_op |none |manangement operation code !! mgt1i |none |sixth parameter in mgt file operation line !! mgtfile |NA |HRU management data file name (.mgt) !! plt |none |number of plant operations in mgt file !! pstnum |none |pesticide ID number from database file !! rot |none |number of years in rotation used in HRU !! solfile |NA |HRU soil data file name (.sol) !! titldum |NA |input lines in .sub that are not processed !! ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ !! ~ ~ ~ SUBROUTINES/FUNCTIONS CALLED ~ ~ ~ !! Intrinsic: Max !! SWAT: caps !! ~ ~ ~ ~ ~ ~ END SPECIFICATIONS ~ ~ ~ ~ ~ ~ use parm character (len=13) :: hrufile, mgtfile, solfile, chmfile character (len=80) :: titldum integer :: eof, j, k, lyrtot, rot, plt, ap_f, ap_p, ap_t, ap_i integer :: grz, cut, mgt1i, pstnum, ii, ap_r, ap_s, kll, hkll integer :: ap_ai, ap_af, mgt_op, ap_cf, ap_cc, ap_ci, jj integer :: iopera_sub real :: depth(25) do j= mhru1, mhru mgtfile = "" solfile = "" chmfile = "" read (25,5300,iostat=eof)hrufile, mgtfile, solfile, chmfile, ilnds if (eof < 0) return if (ilnds > 0) then ils_nofig = 1 end if call caps(mgtfile) call caps(solfile) call caps(chmfile) open (9,file=solfile,recl=350) !! calculate # of soil layers in profile depth = 0. lyrtot = 0 read (9,6000) titldum read (9,6000) titldum read (9,6000) titldum read (9,6000) titldum read (9,6000) titldum read (9,6000) titldum read (9,6000) titldum read (9,6100) (depth(k), k = 1, 25) do k = 1, 25 if (depth(k) <= 0.001) lyrtot = k - 1 if (depth(k) <= 0.001) exit end do mlyr = Max(mlyr,lyrtot) close (9) open (10,file=mgtfile) !! calculate max number of operations per hru iopera_sub = 1 mcri = 0 do kk = 1, 30 read (10,6000) titldum end do do kk = 1, 1000 read (10,6300,iostat=eof) mgt_op, mgt1i if (eof < 0) exit if (mgt_op == 1) then mcri = mcri + 1 end if if (mgt_op == 4 .and. mgt1i > 0) pstflg(mgt1i) = 1 iopera_sub = iopera_sub + 1 end do iopera = Max(iopera,iopera_sub) mcr = Max(mcr,mcri) close (10) !! nubz test open (11,file=chmfile) eof = 0 do do k = 1, 11 read (11,6000,iostat=eof) titldum if (eof < 0) exit end do if (eof < 0) exit do pstnum = 0 read (11,*,iostat=eof) pstnum if (eof < 0) exit if (pstnum > 0) pstflg(pstnum) = 1 end do if (eof < 0) exit end do close (11) end do ! hru loop return 5000 format (6a) 5001 format (a1,9x,5i6) 5002 format(a) 5100 format (20a4) 5200 format (10i4) 5300 format (4a13,52x,i6) 6000 format (a80) 6100 format (27x,25f12.2) 6200 format (1x,i3) 6300 format (16x,i2,1x,i4) end
# This file is a part of Julia. License is MIT: https://julialang.org/license using Test using SuiteSparse if Base.USE_GPL_LIBS include("umfpack.jl") include("cholmod.jl") include("spqr.jl") end
### Introducing Pandas String Operations # Before, covered NP / PD generalized arithmetic operations. A refresher: import numpy as np x = np.array([2, 3, 5, 7, 11, 13]) x * 2 # Vectorization of operations simplifies the syntax (not concerned with LENs) # NP lacks this for arrays of strings though, forced to construct loop: data = ['peter', 'Paul', 'MARY', 'gUIDO'] [s.capitalize() for s in data] # As such, it fails for any arrs with NAs data = ['peter', 'Paul', None, 'MARY', 'gUIDO'] [s.capitalize() for s in data] # Pandas has vectorized string operations though import pandas as pd names = pd.Series(data) names names.str.capitalize() # tab-complete str<> to list ALL vectorized str methods ############################## ### Tables of Pandas String Methods # setup new data Series: monte = pd.Series(['Graham Chapman', 'John Cleese', 'Terry Gilliam', 'Eric Idle', 'Terry Jones', 'Michael Palin']) ## List of PD Methods similar to Python string methods: # many Pandas vectorized string methods are mirrored by overall # Python str methods # len() lower() # ljust() upper() # rjust() find() # center() rfind() # etc... see ch for full list. most are self-explanatory # str.lower() returns series of strings: monte.str.lower() # str.len() returns length of string in Int: monte.str.len() # str.startswith() returns Bool monte.str.startswith('T') # str.split() returns list for each element monte.str.split() ## Methods using regular expressions # these methods accept regular expressions, and mirror API conventions # of Python's built-in "re" module # Method Description # ------------------------- match() # call re.match() on each element. return Bool extract() # call re.match() on each element. return match strs findall() # call re.findall() on each el. replace() # replace occurrences of pattern with other str contains() # call re.search() on each el. return bool count() # count occurrences of pattern split() # equiv. to str.split(), but with regexs rsplit() # equiv. to str.rsplit, but with regexs # ------------------------- # as always, regexs are quite powerful when dealing with strings: # get first name from each element: monte.str.extract('([A-Za-z]+)', expand=False) monte.str.findall(r'^[^AEIOU].*[^aeiou]$') ## Miscellaneous methods: # the following are other convenient operations for strings: get() # Index each element slice() # Slice each element slice_replace() # replace slice in each element with passed value join() # Join strings in element of series with passed seperator cat() # String concatenation repeat() # repeat values normalize() # Return Unicode form of string pad() # Add whitespace to left|right|both sides of string wrap() # Split long strings into lines under a passed width get_dummies() # extract dummy variables as a dataframe ## Vectorized item access and slicing get() slice() # both are enablers for vectorized element access from each array # example: str.slice(0, 3) df.str.slice(0, 3) # these 2 statements are equivalent, df.stf[0:3] # 2nd being the Python standard indexing syntax # get and slice allow access to elements of arrs returned by split() # e.g. Pull last name:: monte.str.split().str.get(-1) ## Indicator Variables # get_dummies() is useful when data has a column containing coded indicator # Example dataset: contains following encoding: # A = "born in America" # B = "born in the United Kingdom" # C = "likes cheese" # D = "likes spam" full_monte = pd.DataFrame({'name': monte, 'info': ['B|C|D', 'B|D', 'A|C', 'B|D', 'B|C', 'B|C|D']}) full_monte full_monte['info'].str.get_dummies('|') ############################## ### Example: Recipe Database # Data GET (gunzip cmdlet - Linux only. Win - use 7zip | ubuntuvm) # !curl -O http://openrecipes.s3.amazonaws.com/recipeitems-latest.json.gz # NOTE: per Issue 218 on the projects github page https://github.com/fictivekin/openrecipes/issues/218 # the daily json exports are failing and will not be reinstated # must use link for the last known working export: # https://s3.amazonaws.com/openrecipes/20170107-061401-recipeitems.json.gz # !gunzip recipeitems-latest.json.gz # NOTE: ipython doesn't have gunzip module, so had to go boot up the old # ubuntuvm machine for curl to work. # Attempt to read in values: try: recipes = pd.read_json('data/20170107-061401-recipeitems.json') except ValueError as e: print("ValueError:", e) # exception thrown mentions 'trailing data' - due to using file in which # each line is itself valid json, but the file itself is not. Verify true: with open('data/20170107-061401-recipeitems.json') as f: line = f.readline() pd.read_json(line).shape # read the entire file into a Python array with open('data/20170107-061401-recipeitems.json', 'r') as f: # extract each line data = (line.strip() for line in f) # reformat each line into element of a list data_json = "[{0}]".format(','.join(data)) # still fails, 'charmap' can't decode byte ___ in position ___, # character maps to <undefined> # read the result as a JSON recipes = pd.read_json(data_json) recipes.shape
header {* \isaheader{List Based Sets} *} theory Impl_List_Set imports "../../Iterator/Iterator" "../Intf/Intf_Set" begin (* TODO: Move *) lemma list_all2_refl_conv: "list_all2 P xs xs \<longleftrightarrow> (\<forall>x\<in>set xs. P x x)" by (induct xs) auto primrec glist_member :: "('a\<Rightarrow>'a\<Rightarrow>bool) \<Rightarrow> 'a \<Rightarrow> 'a list \<Rightarrow> bool" where "glist_member eq x [] \<longleftrightarrow> False" | "glist_member eq x (y#ys) \<longleftrightarrow> eq x y \<or> glist_member eq x ys" lemma param_glist_member[param]: "(glist_member,glist_member)\<in>(Ra\<rightarrow>Ra\<rightarrow>Id) \<rightarrow> Ra \<rightarrow> \<langle>Ra\<rangle>list_rel \<rightarrow> Id" unfolding glist_member_def by (parametricity) lemma list_member_alt: "List.member = (\<lambda>l x. glist_member op = x l)" proof (intro ext) fix x l show "List.member l x = glist_member op = x l" by (induct l) (auto simp: List.member_rec) qed thm List.insert_def definition "glist_insert eq x xs = (if glist_member eq x xs then xs else x#xs)" lemma param_glist_insert[param]: "(glist_insert, glist_insert) \<in> (R\<rightarrow>R\<rightarrow>Id) \<rightarrow> R \<rightarrow> \<langle>R\<rangle>list_rel \<rightarrow> \<langle>R\<rangle>list_rel" unfolding glist_insert_def[abs_def] by (parametricity) primrec rev_append where "rev_append [] ac = ac" | "rev_append (x#xs) ac = rev_append xs (x#ac)" lemma rev_append_eq: "rev_append l ac = rev l @ ac" by (induct l arbitrary: ac) auto (* primrec glist_delete_aux1 :: "('a\<Rightarrow>'a\<Rightarrow>bool) \<Rightarrow> 'a \<Rightarrow> 'a list \<Rightarrow> 'a list" where "glist_delete_aux1 eq x [] = []" | "glist_delete_aux1 eq x (y#ys) = ( if eq x y then ys else y#glist_delete_aux1 eq x ys)" primrec glist_delete_aux2 :: "('a\<Rightarrow>'a\<Rightarrow>_) \<Rightarrow> _" where "glist_delete_aux2 eq ac x [] = ac" | "glist_delete_aux2 eq ac x (y#ys) = (if eq x y then rev_append ys ac else glist_delete_aux2 eq (y#ac) x ys )" lemma glist_delete_aux2_eq1: "glist_delete_aux2 eq ac x l = rev (glist_delete_aux1 eq x l) @ ac" by (induct l arbitrary: ac) (auto simp: rev_append_eq) definition "glist_delete eq x l = glist_delete_aux2 eq [] x l" *) primrec glist_delete_aux :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> _" where "glist_delete_aux eq x [] as = as" | "glist_delete_aux eq x (y#ys) as = ( if eq x y then rev_append as ys else glist_delete_aux eq x ys (y#as) )" definition glist_delete where "glist_delete eq x l \<equiv> glist_delete_aux eq x l []" lemma param_glist_delete[param]: "(glist_delete, glist_delete) \<in> (R\<rightarrow>R\<rightarrow>Id) \<rightarrow> R \<rightarrow> \<langle>R\<rangle>list_rel \<rightarrow> \<langle>R\<rangle>list_rel" unfolding glist_delete_def[abs_def] glist_delete_aux_def rev_append_def by (parametricity) definition list_set_rel_internal_def: "list_set_rel R \<equiv> \<langle>R\<rangle>list_rel O br set distinct" lemma list_rel_Range: "\<forall>x'\<in>set l'. x' \<in> Range R \<Longrightarrow> l' \<in> Range (\<langle>R\<rangle>list_rel)" proof (induction l') case Nil thus ?case by force next case (Cons x' xs') then obtain xs where "(xs,xs') \<in> \<langle>R\<rangle> list_rel" by force moreover from Cons.prems obtain x where "(x,x') \<in> R" by force ultimately have "(x#xs, x'#xs') \<in> \<langle>R\<rangle> list_rel" by simp thus ?case .. qed lemma list_set_rel_def: "\<langle>R\<rangle>list_set_rel = \<langle>R\<rangle>list_rel O br set distinct" unfolding list_set_rel_internal_def[abs_def] by (simp add: relAPP_def) text {* All finite sets can be represented *} lemma list_set_rel_range: "Range (\<langle>R\<rangle>list_set_rel) = { S. finite S \<and> S\<subseteq>Range R }" (is "?A = ?B") proof (intro equalityI subsetI) fix s' assume "s' \<in> ?A" then obtain l l' where A: "(l,l') \<in> \<langle>R\<rangle>list_rel" and B: "s' = set l'" and C: "distinct l'" unfolding list_set_rel_def br_def by blast moreover have "set l' \<subseteq> Range R" by (induction rule: list_rel_induct[OF A], auto) ultimately show "s' \<in> ?B" by simp next fix s' assume A: "s' \<in> ?B" then obtain l' where B: "set l' = s'" and C: "distinct l'" using finite_distinct_list by blast hence "(l',s') \<in> br set distinct" by (simp add: br_def) moreover from A and B have "\<forall>x\<in>set l'. x \<in> Range R" by blast from list_rel_Range[OF this] obtain l where "(l,l') \<in> \<langle>R\<rangle>list_rel" by blast ultimately show "s' \<in> ?A" unfolding list_set_rel_def by fast qed lemmas [autoref_rel_intf] = REL_INTFI[of list_set_rel i_set] lemma list_set_rel_finite[autoref_ga_rules]: "finite_set_rel (\<langle>R\<rangle>list_set_rel)" unfolding finite_set_rel_def list_set_rel_def by (auto simp: br_def) lemma list_set_rel_sv[relator_props]: "single_valued R \<Longrightarrow> single_valued (\<langle>R\<rangle>list_set_rel)" unfolding list_set_rel_def by tagged_solver (* TODO: Move to Misc *) lemma Id_comp_Id: "Id O Id = Id" by simp lemma glist_member_id_impl: "(glist_member op =, op \<in>) \<in> Id \<rightarrow> br set distinct \<rightarrow> Id" proof (intro fun_relI) case (goal1 x x' l s') thus ?case by (induct l arbitrary: s') (auto simp: br_def) qed lemma glist_insert_id_impl: "(glist_insert op =, Set.insert) \<in> Id \<rightarrow> br set distinct \<rightarrow> br set distinct" proof - have IC: "\<And>x s. insert x s = (if x\<in>s then s else insert x s)" by auto show ?thesis apply (intro fun_relI) apply (subst IC) unfolding glist_insert_def apply (parametricity add: glist_member_id_impl) apply (auto simp: br_def) done qed lemma glist_delete_id_impl: "(glist_delete op =, \<lambda>x s. s-{x}) \<in> Id\<rightarrow>br set distinct \<rightarrow> br set distinct" proof (intro fun_relI) fix x x':: 'a and s and s' :: "'a set" assume XREL: "(x, x') \<in> Id" and SREL: "(s, s') \<in> br set distinct" from XREL have [simp]: "x'=x" by simp { fix a and a' :: "'a set" assume "(a,a')\<in>br set distinct" and "s' \<inter> a' = {}" hence "(glist_delete_aux op = x s a, s'-{x'} \<union> a')\<in>br set distinct" using SREL proof (induction s arbitrary: a s' a') case Nil thus ?case by (simp add: br_def) next case (Cons y s) show ?case proof (cases "x=y") case True with Cons show ?thesis by (auto simp add: br_def rev_append_eq) next case False have "glist_delete_aux op = x (y # s) a = glist_delete_aux op = x s (y#a)" by (simp add: False) also have "(\<dots>,set s - {x'} \<union> insert y a')\<in>br set distinct" apply (rule Cons.IH[of "y#a" "insert y a'" "set s"]) using Cons.prems by (auto simp: br_def) also have "set s - {x'} \<union> insert y a' = (s' - {x'}) \<union> a'" proof - from Cons.prems have [simp]: "s' = insert y (set s)" by (auto simp: br_def) show ?thesis using False by auto qed finally show ?thesis . qed qed } from this[of "[]" "{}"] show "(glist_delete op = x s, s' - {x'}) \<in> br set distinct" unfolding glist_delete_def by (simp add: br_def) qed lemma list_set_autoref_empty[autoref_rules]: "([],{})\<in>\<langle>R\<rangle>list_set_rel" by (auto simp: list_set_rel_def br_def) lemma list_set_autoref_member[autoref_rules]: assumes "GEN_OP eq op= (R\<rightarrow>R\<rightarrow>Id)" shows "(glist_member eq,op \<in>) \<in> R \<rightarrow> \<langle>R\<rangle>list_set_rel \<rightarrow> Id" using assms apply (intro fun_relI) unfolding list_set_rel_def apply (erule relcompE) apply (simp del: pair_in_Id_conv) apply (subst Id_comp_Id[symmetric]) apply (rule relcompI[rotated]) apply (rule glist_member_id_impl[param_fo]) apply (rule IdI) apply assumption apply parametricity done lemma list_set_autoref_insert[autoref_rules]: assumes "GEN_OP eq op= (R\<rightarrow>R\<rightarrow>Id)" shows "(glist_insert eq,Set.insert) \<in> R \<rightarrow> \<langle>R\<rangle>list_set_rel \<rightarrow> \<langle>R\<rangle>list_set_rel" using assms apply (intro fun_relI) unfolding list_set_rel_def apply (erule relcompE) apply (simp del: pair_in_Id_conv) apply (rule relcompI[rotated]) apply (rule glist_insert_id_impl[param_fo]) apply (rule IdI) apply assumption apply parametricity done lemma list_set_autoref_delete[autoref_rules]: assumes "GEN_OP eq op= (R\<rightarrow>R\<rightarrow>Id)" shows "(glist_delete eq,op_set_delete) \<in> R \<rightarrow> \<langle>R\<rangle>list_set_rel \<rightarrow> \<langle>R\<rangle>list_set_rel" using assms apply (intro fun_relI) unfolding list_set_rel_def apply (erule relcompE) apply (simp del: pair_in_Id_conv) apply (rule relcompI[rotated]) apply (rule glist_delete_id_impl[param_fo]) apply (rule IdI) apply assumption apply parametricity done lemma list_set_autoref_to_list[autoref_ga_rules]: shows "is_set_to_sorted_list (\<lambda>_ _. True) R list_set_rel id" unfolding is_set_to_list_def is_set_to_sorted_list_def it_to_sorted_list_def list_set_rel_def br_def by auto lemma list_set_it_simp[refine_transfer_post_simp]: "foldli (id l) = foldli l" by simp lemma glist_insert_dj_id_impl: "\<lbrakk> x\<notin>s; (l,s)\<in>br set distinct \<rbrakk> \<Longrightarrow> (x#l,insert x s)\<in>br set distinct" by (auto simp: br_def) context begin interpretation autoref_syn . lemma list_set_autoref_insert_dj[autoref_rules]: assumes "PRIO_TAG_OPTIMIZATION" assumes "SIDE_PRECOND_OPT (x'\<notin>s')" assumes "(x,x')\<in>R" assumes "(s,s')\<in>\<langle>R\<rangle>list_set_rel" shows "(x#s, (OP Set.insert ::: R \<rightarrow> \<langle>R\<rangle>list_set_rel \<rightarrow> \<langle>R\<rangle>list_set_rel) $ x' $ s') \<in> \<langle>R\<rangle>list_set_rel" using assms unfolding autoref_tag_defs unfolding list_set_rel_def apply - apply (erule relcompE) apply (simp del: pair_in_Id_conv) apply (rule relcompI[rotated]) apply (rule glist_insert_dj_id_impl) apply assumption apply assumption apply parametricity done end subsection {* More Operations *} lemma list_set_autoref_isEmpty[autoref_rules]: "(is_Nil,op_set_isEmpty) \<in> \<langle>R\<rangle>list_set_rel \<rightarrow> bool_rel" by (auto simp: list_set_rel_def br_def split: list.split_asm) lemma list_set_autoref_filter[autoref_rules]: "(filter,op_set_filter) \<in> (R \<rightarrow> bool_rel) \<rightarrow> \<langle>R\<rangle>list_set_rel \<rightarrow> \<langle>R\<rangle>list_set_rel" proof - have "(filter, op_set_filter) \<in> (Id \<rightarrow> bool_rel) \<rightarrow> \<langle>Id\<rangle>list_set_rel \<rightarrow> \<langle>Id\<rangle>list_set_rel" by (auto simp: list_set_rel_def br_def) note this[param_fo] moreover have "(filter,filter)\<in>(R \<rightarrow> bool_rel) \<rightarrow> \<langle>R\<rangle>list_rel \<rightarrow> \<langle>R\<rangle>list_rel" unfolding List.filter_def by parametricity note this[param_fo] ultimately show ?thesis unfolding list_set_rel_def apply (intro fun_relI) apply (erule relcompE, simp) apply (rule relcompI) apply (rprems, assumption+) apply (rprems, simp+) done qed context begin interpretation autoref_syn . lemma list_set_autoref_inj_image[autoref_rules]: assumes "PRIO_TAG_OPTIMIZATION" assumes INJ: "SIDE_PRECOND_OPT (inj_on f s)" assumes [param]: "(fi,f)\<in>Ra\<rightarrow>Rb" assumes LP: "(l,s)\<in>\<langle>Ra\<rangle>list_set_rel" shows "(map fi l, (OP op ` ::: (Ra\<rightarrow>Rb) \<rightarrow> \<langle>Ra\<rangle>list_set_rel \<rightarrow> \<langle>Rb\<rangle>list_set_rel)$f$s) \<in> \<langle>Rb\<rangle>list_set_rel" proof - from LP obtain l' where [param]: "(l,l')\<in>\<langle>Ra\<rangle>list_rel" and L'S: "(l',s)\<in>br set distinct" unfolding list_set_rel_def by auto have "(map fi l, map f l')\<in>\<langle>Rb\<rangle>list_rel" by parametricity also from INJ L'S have "(map f l',f`s)\<in>br set distinct" apply (induction l' arbitrary: s) apply (auto simp: br_def dest: injD) done finally (relcompI) show ?thesis unfolding autoref_tag_defs list_set_rel_def . qed end lemma list_set_cart_autoref[autoref_rules]: fixes Rx :: "('xi \<times> 'x) set" fixes Ry :: "('yi \<times> 'y) set" shows "(\<lambda>xl yl. [ (x,y). x\<leftarrow>xl, y\<leftarrow>yl], op_set_cart) \<in> \<langle>Rx\<rangle>list_set_rel \<rightarrow> \<langle>Ry\<rangle>list_set_rel \<rightarrow> \<langle>Rx \<times>\<^sub>r Ry\<rangle>list_set_rel" proof (intro fun_relI) fix xl xs yl ys assume "(xl, xs) \<in> \<langle>Rx\<rangle>list_set_rel" "(yl, ys) \<in> \<langle>Ry\<rangle>list_set_rel" then obtain xl' :: "'x list" and yl' :: "'y list" where [param]: "(xl,xl')\<in>\<langle>Rx\<rangle>list_rel" "(yl,yl')\<in>\<langle>Ry\<rangle>list_rel" and XLS: "(xl',xs)\<in>br set distinct" and YLS: "(yl',ys)\<in>br set distinct" unfolding list_set_rel_def by auto have "([ (x,y). x\<leftarrow>xl, y\<leftarrow>yl ], [ (x,y). x\<leftarrow>xl', y\<leftarrow>yl' ]) \<in> \<langle>Rx \<times>\<^sub>r Ry\<rangle>list_rel" by parametricity also have "([ (x,y). x\<leftarrow>xl', y\<leftarrow>yl' ], xs \<times> ys) \<in> br set distinct" using XLS YLS apply (auto simp: br_def) apply hypsubst_thin apply (induction xl') apply simp apply (induction yl') apply simp apply auto [] apply (metis (lifting) concat_map_maps distinct.simps(2) distinct_singleton maps_simps(2)) done finally (relcompI) show "([ (x,y). x\<leftarrow>xl, y\<leftarrow>yl ], op_set_cart xs ys) \<in> \<langle>Rx \<times>\<^sub>r Ry\<rangle>list_set_rel" unfolding list_set_rel_def by simp qed subsection {* Optimizations *} lemma glist_delete_hd: "eq x y \<Longrightarrow> glist_delete eq x (y#s) = s" by (simp add: glist_delete_def) text {* Hack to ensure specific ordering. Note that ordering has no meaning abstractly *} definition [simp]: "LIST_SET_REV_TAG \<equiv> \<lambda>x. x" lemma LIST_SET_REV_TAG_autoref[autoref_rules]: "(rev,LIST_SET_REV_TAG) \<in> \<langle>R\<rangle>list_set_rel \<rightarrow> \<langle>R\<rangle>list_set_rel" unfolding list_set_rel_def apply (intro fun_relI) apply (elim relcompE) apply (clarsimp simp: br_def) apply (rule relcompI) apply (rule param_rev[param_fo], assumption) apply auto done end
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.wf import Mathlib.Lean3Lib.init.data.nat.basic namespace Mathlib namespace nat protected def div (x : ℕ) : ℕ → ℕ := well_founded.fix lt_wf div.F protected instance has_div : Div ℕ := { div := nat.div } theorem div_def_aux (x : ℕ) (y : ℕ) : x / y = dite (0 < y ∧ y ≤ x) (fun (h : 0 < y ∧ y ≤ x) => (x - y) / y + 1) fun (h : ¬(0 < y ∧ y ≤ x)) => 0 := congr_fun (well_founded.fix_eq lt_wf div.F x) y protected def mod (x : ℕ) : ℕ → ℕ := well_founded.fix lt_wf mod.F protected instance has_mod : Mod ℕ := { mod := nat.mod } theorem mod_def_aux (x : ℕ) (y : ℕ) : x % y = dite (0 < y ∧ y ≤ x) (fun (h : 0 < y ∧ y ≤ x) => (x - y) % y) fun (h : ¬(0 < y ∧ y ≤ x)) => x := congr_fun (well_founded.fix_eq lt_wf mod.F x) y end Mathlib
[STATEMENT] lemma pos_pp_np_help: "\<And>x. 0\<le>f x \<Longrightarrow> pp f x = f x \<and> np f x = 0" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>x. (0::'b) \<le> f x \<Longrightarrow> pp f x = f x \<and> np f x = (0::'b) [PROOF STEP] by (simp add: positive_part_def negative_part_def)
\subsection{Introduction}% ===> this file was generated automatically by noweave --- better not edit it The {\Tt{}subnetize\nwendquote} file includes Lua code related to turning an ordinary function into a subnet. Internally, the code segment \begin{verbatim} subnet foo(A, material, l) -- stuff -- end \end{verbatim} is equivalent to \begin{verbatim} function foo(args) local A = args[1] or args.A or (args.material and args.material.A) local material = args[2] or args.material or (args.material and args.material.material) local l = args[3] or args.l or (args.material and args.material.l) end foo = subnetize(foo) \end{verbatim} Thus, almost all the work of making a subnet be a subnet goes into the {\Tt{}subnetize\nwendquote} function. This module defines the standard version of {\Tt{}subnetize\nwendquote}, which maintains a heirarchical namespace for nodes declared in subnets and maintains the stack of nested local coordinate systems defined in the {\Tt{}xformstack\nwendquote} module. \subsection{Implementation} \nwfilename{subnetize.nw}\nwbegincode{1}\sublabel{NW43EEfw-4X7xiH-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW43EEfw-4X7xiH-1}}}\moddef{subnetize.lua~{\nwtagstyle{}\subpageref{NW43EEfw-4X7xiH-1}}}\endmoddef\nwstartdeflinemarkup\nwenddeflinemarkup use("xformstack.lua") \LA{}initialize data structures~{\nwtagstyle{}\subpageref{NW43EEfw-1XHLTx-1}}\RA{} \LA{}functions~{\nwtagstyle{}\subpageref{NW43EEfw-nRuDO-1}}\RA{} \nwnotused{subnetize.lua}\nwendcode{}\nwbegindocs{2}\nwdocspar The {\Tt{}namestack\nwendquote} is a stack of prefixes for names declared in the current scope. For the global scope, the stack entry is an empty string (when you say ``foo'', you mean ``foo''). Inside of a subnet instance ``bar,'' though, when you make a node named ``foo'' you actually get ``bar.foo.'' Therefore, the prefix ``bar.'' is stored on the stack while processing the subnet instance. The {\Tt{}localnames\nwendquote} is a table of names for local nodes (nodes in the current scope). \nwenddocs{}\nwbegincode{3}\sublabel{NW43EEfw-1XHLTx-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW43EEfw-1XHLTx-1}}}\moddef{initialize data structures~{\nwtagstyle{}\subpageref{NW43EEfw-1XHLTx-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW43EEfw-4X7xiH-1}}\nwenddeflinemarkup -- Stack of node name prefixes _namestack = \{""; n = 1, nanon = 0\}; -- Table of node names in the current scope _localnames = \{\}; \nwused{\\{NW43EEfw-4X7xiH-1}}\nwendcode{}\nwbegindocs{4}\nwdocspar The {\Tt{}subnetize\nwendquote} function transforms a function that creates a substructure into a function that creates a substructure in a nested coordinate frame. \nwenddocs{}\nwbegincode{5}\sublabel{NW43EEfw-nRuDO-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW43EEfw-nRuDO-1}}}\moddef{functions~{\nwtagstyle{}\subpageref{NW43EEfw-nRuDO-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW43EEfw-4X7xiH-1}}\nwprevnextdefs{\relax}{NW43EEfw-nRuDO-2}\nwenddeflinemarkup function subnetize(f) return function(p) \LA{}add name of current subnet instance to stack~{\nwtagstyle{}\subpageref{NW43EEfw-16KUvp-1}}\RA{} local old_localnames = _localnames _localnames = \{\}; \LA{}form $T$ from \code{}ox\edoc{}, \code{}oy\edoc{}, and \code{}oz\edoc{}~{\nwtagstyle{}\subpageref{NW43EEfw-4dR2dX-1}}\RA{} xform_push(T) %f(p) xform_pop() _localnames = old_localnames _namestack.n = _namestack.n - 1 end end \nwalsodefined{\\{NW43EEfw-nRuDO-2}}\nwused{\\{NW43EEfw-4X7xiH-1}}\nwendcode{}\nwbegindocs{6}\nwdocspar When we add a new subnet instance, we store its extended name on the stack. If it has no name, it is assigned a name beginning with the tag ``anon.'' \nwenddocs{}\nwbegincode{7}\sublabel{NW43EEfw-16KUvp-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW43EEfw-16KUvp-1}}}\moddef{add name of current subnet instance to stack~{\nwtagstyle{}\subpageref{NW43EEfw-16KUvp-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW43EEfw-nRuDO-1}}\nwenddeflinemarkup local name = p.name if not name then name = "anon" .. _namestack.nanon _namestack.nanon = _namestack.nanon + 1 end _namestack[_namestack.n + 1] = _namestack[_namestack.n] .. name .. "." _namestack.n = _namestack.n + 1 if p.name then p.name = _namestack[_namestack.n-1] .. name end \nwused{\\{NW43EEfw-nRuDO-1}}\nwendcode{}\nwbegindocs{8}\nwdocspar When setting up coordinate transformations, we rotate about the $y$ axis, then $z$, then $x$. I am unsure why that convention was chosen, but it is the same convention used in SUGAR 2.0. \nwenddocs{}\nwbegincode{9}\sublabel{NW43EEfw-4dR2dX-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW43EEfw-4dR2dX-1}}}\moddef{form $T$ from \code{}ox\edoc{}, \code{}oy\edoc{}, and \code{}oz\edoc{}~{\nwtagstyle{}\subpageref{NW43EEfw-4dR2dX-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW43EEfw-nRuDO-1}}\nwenddeflinemarkup local T = xform_identity() if p.oy then T = xform_compose(T, xform_oy(p.oy)) p.oy = nil end if p.oz then T = xform_compose(T, xform_oz(p.oz)) p.oz = nil end if p.ox then T = xform_compose(T, xform_ox(p.ox)) p.ox = nil end \nwused{\\{NW43EEfw-nRuDO-1}}\nwendcode{}\nwbegindocs{10}\nwdocspar \nwenddocs{}\nwbegincode{11}\sublabel{NW43EEfw-nRuDO-2}\nwmargintag{{\nwtagstyle{}\subpageref{NW43EEfw-nRuDO-2}}}\moddef{functions~{\nwtagstyle{}\subpageref{NW43EEfw-nRuDO-1}}}\plusendmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW43EEfw-4X7xiH-1}}\nwprevnextdefs{NW43EEfw-nRuDO-1}{\relax}\nwenddeflinemarkup -- Create a new node. If something with the same name -- already exists in the current scope, use that. -- function node(args) if type(args) == "string" then args = \{name = args\} end local name = args.name if not name then name = "anon" .. _namestack.nanon _namestack.nanon = _namestack.nanon + 1 end if not _localnames[name] then args.name = _namestack[_namestack.n] .. name _localnames[name] = %node(args) end return _localnames[name] end \nwused{\\{NW43EEfw-4X7xiH-1}}\nwendcode{} \nwixlogsorted{c}{{add name of current subnet instance to stack}{NW43EEfw-16KUvp-1}{\nwixu{NW43EEfw-nRuDO-1}\nwixd{NW43EEfw-16KUvp-1}}}% \nwixlogsorted{c}{{form $T$ from \code{}ox\edoc{}, \code{}oy\edoc{}, and \code{}oz\edoc{}}{NW43EEfw-4dR2dX-1}{\nwixu{NW43EEfw-nRuDO-1}\nwixd{NW43EEfw-4dR2dX-1}}}% \nwixlogsorted{c}{{functions}{NW43EEfw-nRuDO-1}{\nwixu{NW43EEfw-4X7xiH-1}\nwixd{NW43EEfw-nRuDO-1}\nwixd{NW43EEfw-nRuDO-2}}}% \nwixlogsorted{c}{{initialize data structures}{NW43EEfw-1XHLTx-1}{\nwixu{NW43EEfw-4X7xiH-1}\nwixd{NW43EEfw-1XHLTx-1}}}% \nwixlogsorted{c}{{subnetize.lua}{NW43EEfw-4X7xiH-1}{\nwixd{NW43EEfw-4X7xiH-1}}}% \nwbegindocs{12}\nwdocspar \nwenddocs{}
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov, Johannes Hölzl -/ import order.conditionally_complete_lattice.basic import order.rel_iso.basic /-! # Order continuity > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We say that a function is *left order continuous* if it sends all least upper bounds to least upper bounds. The order dual notion is called *right order continuity*. For monotone functions `ℝ → ℝ` these notions correspond to the usual left and right continuity. We prove some basic lemmas (`map_sup`, `map_Sup` etc) and prove that an `rel_iso` is both left and right order continuous. -/ universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} open function order_dual set /-! ### Definitions -/ /-- A function `f` between preorders is left order continuous if it preserves all suprema. We define it using `is_lub` instead of `Sup` so that the proof works both for complete lattices and conditionally complete lattices. -/ def left_ord_continuous [preorder α] [preorder β] (f : α → β) := ∀ ⦃s : set α⦄ ⦃x⦄, is_lub s x → is_lub (f '' s) (f x) /-- A function `f` between preorders is right order continuous if it preserves all infima. We define it using `is_glb` instead of `Inf` so that the proof works both for complete lattices and conditionally complete lattices. -/ def right_ord_continuous [preorder α] [preorder β] (f : α → β) := ∀ ⦃s : set α⦄ ⦃x⦄, is_glb s x → is_glb (f '' s) (f x) namespace left_ord_continuous section preorder variables (α) [preorder α] [preorder β] [preorder γ] {g : β → γ} {f : α → β} protected lemma id : left_ord_continuous (id : α → α) := λ s x h, by simpa only [image_id] using h variable {α} protected lemma order_dual : left_ord_continuous f → right_ord_continuous (to_dual ∘ f ∘ of_dual) := id lemma map_is_greatest (hf : left_ord_continuous f) {s : set α} {x : α} (h : is_greatest s x): is_greatest (f '' s) (f x) := ⟨mem_image_of_mem f h.1, (hf h.is_lub).1⟩ lemma comp (hg : left_ord_continuous g) (hf : left_ord_continuous f) : left_ord_continuous (g ∘ f) := λ s x h, by simpa only [image_image] using hg (hf h) protected lemma iterate {f : α → α} (hf : left_ord_continuous f) (n : ℕ) : left_ord_continuous (f^[n]) := nat.rec_on n (left_ord_continuous.id α) $ λ n ihn, ihn.comp hf end preorder section semilattice_sup variables [semilattice_sup α] [semilattice_sup β] {f : α → β} lemma map_sup (hf : left_ord_continuous f) (x y : α) : f (x ⊔ y) = f x ⊔ f y := (hf is_lub_pair).unique $ by simp only [image_pair, is_lub_pair] lemma le_iff (hf : left_ord_continuous f) (h : injective f) {x y} : f x ≤ f y ↔ x ≤ y := by simp only [← sup_eq_right, ← hf.map_sup, h.eq_iff] lemma lt_iff (hf : left_ord_continuous f) (h : injective f) {x y} : f x < f y ↔ x < y := by simp only [lt_iff_le_not_le, hf.le_iff h] variable (f) /-- Convert an injective left order continuous function to an order embedding. -/ def to_order_embedding (hf : left_ord_continuous f) (h : injective f) : α ↪o β := ⟨⟨f, h⟩, λ x y, hf.le_iff h⟩ variable {f} @[simp] lemma coe_to_order_embedding (hf : left_ord_continuous f) (h : injective f) : ⇑(hf.to_order_embedding f h) = f := rfl end semilattice_sup section complete_lattice variables [complete_lattice α] [complete_lattice β] {f : α → β} lemma map_Sup' (hf : left_ord_continuous f) (s : set α) : f (Sup s) = Sup (f '' s) := (hf $ is_lub_Sup s).Sup_eq.symm lemma map_Sup (hf : left_ord_continuous f) (s : set α) : f (Sup s) = ⨆ x ∈ s, f x := by rw [hf.map_Sup', Sup_image] lemma map_supr (hf : left_ord_continuous f) (g : ι → α) : f (⨆ i, g i) = ⨆ i, f (g i) := by simp only [supr, hf.map_Sup', ← range_comp] end complete_lattice section conditionally_complete_lattice variables [conditionally_complete_lattice α] [conditionally_complete_lattice β] [nonempty ι] {f : α → β} lemma map_cSup (hf : left_ord_continuous f) {s : set α} (sne : s.nonempty) (sbdd : bdd_above s) : f (Sup s) = Sup (f '' s) := ((hf $ is_lub_cSup sne sbdd).cSup_eq $ sne.image f).symm lemma map_csupr (hf : left_ord_continuous f) {g : ι → α} (hg : bdd_above (range g)) : f (⨆ i, g i) = ⨆ i, f (g i) := by simp only [supr, hf.map_cSup (range_nonempty _) hg, ← range_comp] end conditionally_complete_lattice end left_ord_continuous namespace right_ord_continuous section preorder variables (α) [preorder α] [preorder β] [preorder γ] {g : β → γ} {f : α → β} protected lemma id : right_ord_continuous (id : α → α) := λ s x h, by simpa only [image_id] using h variable {α} protected lemma order_dual : right_ord_continuous f → left_ord_continuous (to_dual ∘ f ∘ of_dual) := id lemma map_is_least (hf : right_ord_continuous f) {s : set α} {x : α} (h : is_least s x): is_least (f '' s) (f x) := hf.order_dual.map_is_greatest h lemma mono (hf : right_ord_continuous f) : monotone f := hf.order_dual.mono.dual lemma comp (hg : right_ord_continuous g) (hf : right_ord_continuous f) : right_ord_continuous (g ∘ f) := hg.order_dual.comp hf.order_dual protected lemma iterate {f : α → α} (hf : right_ord_continuous f) (n : ℕ) : right_ord_continuous (f^[n]) := hf.order_dual.iterate n end preorder section semilattice_inf variables [semilattice_inf α] [semilattice_inf β] {f : α → β} lemma map_inf (hf : right_ord_continuous f) (x y : α) : f (x ⊓ y) = f x ⊓ f y := hf.order_dual.map_sup x y lemma le_iff (hf : right_ord_continuous f) (h : injective f) {x y} : f x ≤ f y ↔ x ≤ y := hf.order_dual.le_iff h lemma lt_iff (hf : right_ord_continuous f) (h : injective f) {x y} : f x < f y ↔ x < y := hf.order_dual.lt_iff h variable (f) /-- Convert an injective left order continuous function to a `order_embedding`. -/ def to_order_embedding (hf : right_ord_continuous f) (h : injective f) : α ↪o β := ⟨⟨f, h⟩, λ x y, hf.le_iff h⟩ variable {f} @[simp] lemma coe_to_order_embedding (hf : right_ord_continuous f) (h : injective f) : ⇑(hf.to_order_embedding f h) = f := rfl end semilattice_inf section complete_lattice variables [complete_lattice α] [complete_lattice β] {f : α → β} lemma map_Inf' (hf : right_ord_continuous f) (s : set α) : f (Inf s) = Inf (f '' s) := hf.order_dual.map_Sup' s lemma map_Inf (hf : right_ord_continuous f) (s : set α) : f (Inf s) = ⨅ x ∈ s, f x := hf.order_dual.map_Sup s lemma map_infi (hf : right_ord_continuous f) (g : ι → α) : f (⨅ i, g i) = ⨅ i, f (g i) := hf.order_dual.map_supr g end complete_lattice section conditionally_complete_lattice variables [conditionally_complete_lattice α] [conditionally_complete_lattice β] [nonempty ι] {f : α → β} lemma map_cInf (hf : right_ord_continuous f) {s : set α} (sne : s.nonempty) (sbdd : bdd_below s) : f (Inf s) = Inf (f '' s) := hf.order_dual.map_cSup sne sbdd lemma map_cinfi (hf : right_ord_continuous f) {g : ι → α} (hg : bdd_below (range g)) : f (⨅ i, g i) = ⨅ i, f (g i) := hf.order_dual.map_csupr hg end conditionally_complete_lattice end right_ord_continuous namespace order_iso section preorder variables [preorder α] [preorder β] (e : α ≃o β) {s : set α} {x : α} protected lemma left_ord_continuous : left_ord_continuous e := λ s x hx, ⟨monotone.mem_upper_bounds_image (λ x y, e.map_rel_iff.2) hx.1, λ y hy, e.rel_symm_apply.1 $ (is_lub_le_iff hx).2 $ λ x' hx', e.rel_symm_apply.2 $ hy $ mem_image_of_mem _ hx'⟩ protected lemma right_ord_continuous : right_ord_continuous e := order_iso.left_ord_continuous e.dual end preorder end order_iso
[STATEMENT] lemma left_option_is_option[simp, intro]: "zin x (left_options g) \<Longrightarrow> zin x (options g)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. zin x (left_options g) \<Longrightarrow> zin x (options g) [PROOF STEP] by (simp add: options_def zunion)
State Before: α : Type u_1 β : Type ?u.734418 γ : Type ?u.734421 δ : Type ?u.734424 m : MeasurableSpace α μ ν : Measure α inst✝² : MeasurableSpace δ inst✝¹ : NormedAddCommGroup β inst✝ : NormedAddCommGroup γ f : α → ℝ hfi : HasFiniteIntegral f ⊢ IsFiniteMeasure (Measure.withDensity μ fun x => ENNReal.ofReal (f x)) State After: α : Type u_1 β : Type ?u.734418 γ : Type ?u.734421 δ : Type ?u.734424 m : MeasurableSpace α μ ν : Measure α inst✝² : MeasurableSpace δ inst✝¹ : NormedAddCommGroup β inst✝ : NormedAddCommGroup γ f : α → ℝ hfi : HasFiniteIntegral f x : α ⊢ ENNReal.ofReal (f x) ≤ ↑‖f x‖₊ Tactic: refine' isFiniteMeasure_withDensity ((lintegral_mono fun x => _).trans_lt hfi).ne State Before: α : Type u_1 β : Type ?u.734418 γ : Type ?u.734421 δ : Type ?u.734424 m : MeasurableSpace α μ ν : Measure α inst✝² : MeasurableSpace δ inst✝¹ : NormedAddCommGroup β inst✝ : NormedAddCommGroup γ f : α → ℝ hfi : HasFiniteIntegral f x : α ⊢ ENNReal.ofReal (f x) ≤ ↑‖f x‖₊ State After: no goals Tactic: exact Real.ofReal_le_ennnorm (f x)
Set Warnings "-notation-overridden". Require Import Category.Lib. Require Export Category.Theory.Functor. Require Export Category.Theory.Unique. Generalizable All Variables. Set Primitive Projections. Set Universe Polymorphism. Unset Transparent Obligations. Section UniversalArrow. Context `{C : Category}. Context `{D : Category}. Require Import Category.Structure.Initial. Require Import Category.Construction.Comma. Require Import Category.Functor.Diagonal. (* A universal arrow is an initial object in the comma category (=(c) ↓ F). *) Class UniversalArrow (c : C) (F : D ⟶ C) := { arrow_initial : @Initial (=(c) ↓ F); arrow_obj := snd (`1 (@initial_obj _ arrow_initial)); arrow : c ~> F arrow_obj := `2 (@initial_obj _ arrow_initial) }. Notation "c ⟿ F" := (UniversalArrow c F) (at level 20) : category_theory_scope. (* The following UMP follows directly from the nature of initial objects in a comma category. *) Corollary ump_universal_arrows `(c ⟿ F) `(h : c ~> F d) : ∃! g : arrow_obj ~> d, h ≈ fmap[F] g ∘ arrow. Proof. unfold arrow_obj, arrow; simpl. destruct (@zero _ arrow_initial ((tt, d); h)), x. simpl in *. rewrite id_right in e. exists h1. assumption. intros. rewrite <- id_right in e. rewrite <- id_right in X. exact (snd (@zero_unique _ arrow_initial ((tt, d); h) ((tt, h1); e) ((tt, v); X))). Qed. End UniversalArrow.
\section{Learning MPIs}\label{sec:learning-mpis} Some of the major challenges in high-quality novel view synthesis include synthesizing pixels occluded in one or more of the provided views, disentangling and localizing ambiguous pixels at/near the boundaries of foreground and background objects, localizing pixels at transparent, translucent, reflective, or texture-less surfaces, etc. Moreover, whereas interpolating novel views at desired viewpoints lying within the convex hull of given viewpoints is easier to achieve than extrapolating significantly beyond the baselines (distances between camera centers) of input views, these challenges can emerge in either case. So far, it has been found that learning view synthesis is the way to go for tackling them all in one shot. Before the Machine Learning (ML) boom in Computer Vision (CV) circles in 2012, convolutional filters had to be handcrafted and dexterously layered one atop the other before input views could be subjected to them and various types of features could be extracted in the process of rendering novel views. All the aforementioned view synthesis challenges had to be manually targeted by way of devising various combinations of these filters. This meant a high proportion of artifacts induced in novel views could be left unresolved. Since the time that the efficacy of CNNs in CV was proven by Krizhevsky, Sutskever, and Hinton~\cite{krizhevsky_imagenet_2012} in 2012, to the delight of the CV community, the need to handcraft filters was obviated by ML models that learned to design all required convolutional filters on their own in their various hidden layers. These self-taught filters are defined by the weights and biases in each hidden layer neuron. The weights and biases constantly improve during training and the convolutional filters defined by them are specific to the datasets they are trained on, with some degree of generalizability to other datasets. If trained well under effective hyperparamter tuning, learned filters can evolve to surpass manual filters in addressing occlusion, transparency, reflection, and other image synthesis challenges. View synthesis can lend itself to being a semi-well-posed to well-posed learning problem where two or more images of a scene can be shot and an ML model can be exposed to one of more of these images while being expected to predict one or more of the remaining views that have been withheld from it. The quantitative difference between the corresponding predicted and withheld (as ground truth) views will then be the loss that the ML training seeks to minimize. Since end-to-end view synthesis without an intermediate representation is still largely unrealized, the popular way to synthesize novel views is to learn an intermediate representation of the scene common to the input views and use this intermediate representation to render novel views. The MPI intermediate representation has proven to be one the most effective representations for this purpose with implications as significant as real-time high-quality spatially-consistent view synthesis. \subsection{Seminal Work}\label{subsec:seminal-work} The roots of the MPI representation may be traced back to seminal papers such as 1996's Collins~\cite{collins_space-sweep_1996}, 1998's Shade et al.~\cite{shade_layered_1998}, and 1999's Szeliski and Golland~\cite{szeliski_stereo_1999}. Collins perfected the concept of Plane Sweep Volumes (PSVs), Shade et al. introduced layered depth images, and Szeliski and Golland introduced the actual MPI representation itself. These groundbreaking techniques have also been compared in Scharstein and Szeliski~\cite{scharstein_taxonomy_2002}. \begin{figure}[!h] \includegraphics[width=1\columnwidth]{figures/plane-sweep-volume.png} \caption{Plane Sweep Volume Representation~\cite{svetlana_2019}} \label{fig:plane-sweep-volume} \end{figure} Collins~\cite{collins_space-sweep_1996} applied the PSV representation to the problem of reconstructing the 3D scene from multiple views while simultaneously performing feature matching across all views sharing common features. Feature matching is the process of matching corresponding ``features of interest" characterized by their repeatability across multiple views of the same world scene. Examples include keypoints, corners, edges, objects, etc. Matched views can be rectified and used for triangulating depth, etc., as mentioned in section~\ref{sec:motivation}. In the author's implementation, instead of going for a resource-intensive 3D representation that would require splitting the entire 3D scene space into voxels and reprojecting\footnote{projecting to a target plane by unapplying and applying the homographies needed to project to the source and target planes, respectively, while accounting for surface normals, plane offsets, camera rotations and translations, etc., as described in subsection~\ref{subsec:base-papers}} all feature points from all views in such manner that the reprojected light rays passed through this uniformly partitioned space, he sampled the 3D scene space at various 2D planes along the depth ($z$) axis, as if capturing just one 2D plane sweeping though it at various instants in time. He partitioned the sweeping plane into cells and allowed each reprojected light ray to vote for a group of cells that fell within a certain radius of the point of intersection of the light ray with the plane. This accounts for the fact that rays from corresponding feature points across all views may not converge most of the time due to reprojection errors. He then chose the $z$-coordinate of the sampled plane containing the cell with the maximum votes for a feature point to be the $z$-coordinate of the feature point in the world scene. The $x$ and $y$ world coordinates would be defined by this winning cell. The victor cell would also determine the 2D feature point correspondences simultaneously just by virtue of the converging rays being retraced to their respective originating views. PSVs, in their various reimplemented forms, have become almost synonymous of layered volumetric representations these days (Figure~\ref{fig:plane-sweep-volume}). Shade et al.'s~\cite{shade_layered_1998} Layered Depth Image (LDI) scene representation is similar to MPI scene representation in that both MPI and LDI consist of a series of fronto-parallel planes facing a chosen reference viewpoint and placed at varying depths from it. These planes contain the RGB information of the original pixels of the scene's image(s), segregated according to depth. MPI differs from LDI (and PSV) in that it has alpha masking effects at each layer, as it is generated with alpha transparency maps for each layer. Also, MPIs have fixed depths for each layer as opposed to the variable layer depths of LDIs (and PSVs). But in both cases, by virtue of layering, users are able to experience a simulation of what happens when they move their heads while looking at a scene in the world --- they are able to look around foreground objects that occlude background ones. Szeliski and Golland~\cite{szeliski_stereo_1999} first introduced the MPI representation for purposes of stereo matching with simultaneous RGBA estimation at each matched pixel. Stereo matching, otherwise called disparity mapping, uses feature matching techniques such as SIFT\footnote{Scale-Invariant Feature Transform~\cite{lowe_distinctive_2004}} in pixel-and-sub-pixel-wise disparity estimation for 3D scene reconstruction from rectified stereo images. The authors' framework was the first to extract high-accuracy depth, color, and transparency maps for several images at a time, operating even at sub-pixel levels. They were able to enforce sub-pixel accuracy and perform effective matte separation of foreground and background elements despite the usual 3D vision challenges such as occlusions, etc., because they came as close to modern ML reimplementations as possible. They implemented various loss functions such as a pixel-wise weighted photometric $L_1$ norm between the input and reprojected images, a per-pixel smoothness constraint on the RGBA values allowed in the reprojected images, etc. They then performed an iterative refinement of the estimated RGBA values with the help of a gradient\footnote{vector of partial derivatives of the function(s) to be optimized} descent algorithm designed to optimize a combination of all these losses, but sans the explosive power of neural networks. \subsection{Influential Work}\label{subsec:influential-work} DeepStereo~\cite{deep_stereo_2016} was the first to apply CNNs in an end-to-end manner to novel view synthesis from diverse collections of indoor and outdoor imagery in the wild, given the availability of camera parameters\footnote{camera intrinscics such as focal length and principal point and camera extrinsics/pose such as position and orientation} for each input image. Their paper describes why it would be unwise to expect a typical present-day CNN to synthesize any ground-truth target image without being provided with the pose of the view as well --- the network would needlessly be learning epipolar geometry itself! Epipolar geometry --- the geometry of binocular and multi-view stereo vision --- gives us the epipolar constraint $x'^T F x = 0$ between all corresponding points $x$ and $x'$ on a stereo pair. Here, $F$ is called the fundamental matrix and is derived from the intrinsic and extrinsic parameters of the stereo cameras involved. To circumvent such an indeterminable and expensive pixel-to-pixel training scenario, the authors had PSVs (Figure~\ref{fig:plane-sweep-volume}) come to the rescue. They supplied all input views required to synthesize a target view as separate PSVs to their network. Each input plane sweep would contain all pixels of the respective input view reprojected onto a chosen number of planes at chosen depths in the usual ``stack of acetates" manner, with the planes all having their viewpoints match with the target view's. The plane that each RGB pixel gets reprojected onto will also determine the availability of the pixel (as alpha values ranging from 0 to 1) to the surrounding voxels of the PSV. The plane sweep of each input view has the pose information of the view implicitly encoded in it just by virtue of its construction. Moreover, the plane sweeps of all input views of the same scene trivially enforce the epipolar constraint as all matching pixels across these originating input views may be located in the same depth-wise column of each plane sweep. Each of these depth-wise columns may then be computed upon by the network independently of other columns, in producing the corresponding synthesized target pixel. The network learns to predict the best weight and color for each reprojected pixel on all input planes, so it may perform a weighted summation of these estimated pixel colors and obtain a final predicted target pixel color. Such averaging has a smoothing effect over the color values of the synthesized target image. The error signal that is iteratively minimized by the training is given by the pixel-wise $L_1$ (absolute difference) loss between the actual target color $C_{i,j}^t$ and the synthesized target color $C_{i,j}^s$ at each pixel $(i,j)$: \[\mathcal{L} = \sum_{i,j} |C_{i,j}^t - C_{i,j}^s|\] Kalantari et al.'s~\cite{kalantari_2016} model learns to interpolate novel views in the 8x8 central view grid of a Lytro camera containing a microlens array. It was the state-of-the-art learning-based view synthesis model prior to Zhou et al.'s~\cite{zhou2018stereo} \textit{stereo magnification} MPI model. It is composed of disparity and color predictor components in the form of simple 4-layered sequential CNNs. The training signal it optimizes is given by the $L_2$ (squared difference) pixel reconstruction loss between each pair of original and interpolated target views. Both DeepStereo and Kalantari et al. are unable to train on training images in their entirety. Instead, they extract patches of training images for their models to train on. This is because, unlike how Zhou et al.'s model is designed to predict a global scene representation once for a pair of views belonging to the same scene and render many novel views with it at near-real-time speeds, the former models are designed to predict each novel view in an end-to-end fashion independently of other novel views and so have to rerun their prediction pipelines every time, making novel view synthesis prohibitively slow for high-resolution and real-time applications. Moreover, when rendering nearby views, the former methods produce much more artifact-ridden, spatially-incoherent views compared to the views inferred by Zhou et al. What Zhou et al. has going for it in these scenarios is an implicit smoothness prior imposed by the common scene representation over the color and depth values being inferred for each synthesized nearby view. What also comes close to the MPI representation is the layered representation of Penner and Zhang~\cite{penner_soft_2017}. But then again, in all these prior methods, a unique scene representation is predicted in the reference coordinate frame of each target view to be rerendered, negatively impacting view synthesis efficiency. Other innovative MPI-related papers released subsequently to Zhou et al. and leading up to Tucker and Snavely's~\cite{single_view_mpi} \textit{single-view} MPIs are 2019's Srinivasan et al.~\cite{srinivasan_pushing_2019}, Mildenhall et al.~\cite{mildenhall_local_2019}, and DeepView~\cite{flynn_deepview_2019}. Srinivasan et al. improved the quality and increased the disparity and baseline ranges of predicted MPIs and rendered views, by bringing in a 3D CNN architecture, training on random-resolution views, and introducing an optical flow constraint over the appearance of occluded content in rendered views. Mildenhall et al.'s model converts an grid of irregularly sampled views into MPIs, i.e., mini-light-field representations, and blends such nearby local light fields to render novel views. They were able to establish a minimum density of sampled views required for robust rendering, which turned out to be 4000$\times$ less than the Nyquist frequency required to prevent aliasing. DeepView~\cite{flynn_deepview_2019} replaced the update step\footnote{involving step size and other parameters such as priors/biases} of the network's gradient descent algorithm with a CNN that learns the various gradient descent parameters instead. As a consequence, the network takes much larger strides along the direction of optimization and converges much sooner and with more accuracy than a network using standard gradient descent. However, these methods do not tackle the monocular-image approach for generating MPIs. \subsection{Base Papers}\label{subsec:base-papers} Zhou et al.~\cite{zhou2018stereo} was the first to implement view extrapolation to significantly larger baselines (up to 8$\times$ input baselines) than prior work --- a process they call stereo magnification. They use stereo pairs to learn an MPI (Figure~\ref{fig:mpi-layered-representation}) prediction network in the following manner: \begin{figure}[!h] \includegraphics[width=1\columnwidth]{figures/inferred-mpi.png} \caption{Inferred MPI~\cite{zhou2018stereo}} \label{fig:inferred-mpi} \end{figure} \begin{itemize} \item The camera parameters $c_1 = (p_1,\ k_1)$ and $c_2 = (p_2,\ k_2)$ of the stereo pair, $(I_1,\ I_2)$, are also needed for the prediction process, along with the target image $I_t$ and its parameters $c_t$. Here, $p$'s and $k$'s refer to the camera extrinsics and intrinsics of the respective images. \item The viewpoint of one image of the stereo pair, $I_1$, is used as the reference viewpoint for the MPI to be predicted at. Hence, $p_1$ would be the identity pose $[I|\boldsymbol{\mathit{0}}]$. \item The goal is to learn a network that generates an MPI representation (Figure~\ref{fig:inferred-mpi}) with inputs $(I_1,\ I_2,\ c_1,\ c_2)$ such that when the MPI is rendered at viewpoint $c_t$, it would produce the target image $I_t$. \item As demonstrated by DeepStereo~\cite{deep_stereo_2016}, an effective way to encode pose information for training is via a PSV (Figure~\ref{fig:plane-sweep-volume}). Hence, the input to their customized encoder-decoder type network includes a PSV version of $I_2$ $(\hat{I_2})$ with the planes all reprojected into the output MPI's viewpoint, $c_1$, and with the entire plane sweep concatenated internally and with an unaltered $I_1$ along the three color channels. The depth planes of $\hat{I_2}$ are also chosen to coincide with the ones of the output MPI. \item The 3D structure of the scene depicted by $I_1$ and $I_2$ is automatically learnt by the network by merely being able to compare $I_1$ with each of the reprojected images of $I_2$ in the input stack $(\hat{I_2^1},\ \hat{I_2^2},\ \ldots,\ \hat{I_2^D},\ I_1)$, where $D$ is the total number of MPI depth planes. The depth at each pixel of any known or novel view of the scene must be the depth of the plane where $I_1$ and $\hat{I_2}$ concur. \item In order to reduce resource consumption due to network over-parameterization, the network's initial outputs do not consist of separate RGBA maps for each MPI layer but rather just a ``background" image intended to capture pixels occluded in $I_1$ and a set of color blending weight maps and alpha maps for each MPI layer. \item The actual RGB values in each layer, $C_i$, are then easily computed by taking the per-pixel weighted average of $I_1$ and the predicted background image $\hat{I_b}$: \[C_i = w_i \odot I_1 + (1 - w_i) \odot \hat{I_b}\] Here, $\odot$ is the Hadamard product and $w_i$ refers to the RGB blending weights from the initial network output, specific to MPI layer $i$. \item $\hat{I_b}$ need not itself be a natural image as the network can selectively and softly blend each $\hat{I_b}$ pixel with $I_1$, based on respective layer $\alpha$'s and $w$'s. Intuitively, $I_1$'s contribution would be more in foreground layers than in the background ones; and conversely for $\hat{I_b}$. \end{itemize} The rest of the training pipeline consists of the rendering of the MPI at the target viewpoint, $c_t$, and the gradient descent algorithm involving a VGG perceptual (similar to LPIPS~\cite{zhang_unreasonable_2018}) loss function between the rendered view and ground-truth target view. The perceptual loss is proven to be more robust than unmodified pixel reconstruction losses such as $L_1$ and $L_2$ norms. Adam gradient descent algorithm is used (similarly to Tucker and Snavely~\cite{single_view_mpi}) to optimize this loss. Adam~\cite{kingma_adam_2017} is better than regular stochastic gradient descent but is still not superior to DeepView's~\cite{flynn_deepview_2019} implementation of learned gradient descent. Rendering an MPI first involves warping each RGBA MPI layer onto the target camera's image plane using the standard inverse homography or reprojection operation~\cite{hartley_multiple_2004}, as illustrated in figure~\ref{fig:standard-inverse-homography}. But, anticipating usual reprojection mismatches, they resample each pixel to be warped by bilinear interpolation with respective four-grid neighbors. These rerendered MPI layers are then alpha-composited in back-to-front order to get the final predicted target view. All elements of the rendering process are differentiable. \begin{figure}[!h] \includegraphics[width=0.75\columnwidth]{figures/standard-inverse-homography.png} \caption{Standard Inverse Homography or Reprojection~\cite{brann_forelesninger_2016}} \label{fig:standard-inverse-homography} {\small Here, the 3D point $\boldsymbol{X}$ on the MPI plane in the world is the \textit{homogeneous} version (determined up to scale) of its projection $\boldsymbol{x}$ on the reference camera's image plane in camera coordinates, i.e., with the camera's image plane centered at the camera center, $c_{ref}$. More precisely, $\boldsymbol{X} = [X,Y,d_m]^T \sim \tilde{\boldsymbol{x}} = [X/d_m,Y/d_m,1]$. This is because all MPI world planes are fronto-parallel to the reference camera and their equations can be given by $\boldsymbol{n_m \cdot \tilde{x}} + a = 0$, where $\boldsymbol{n_m} = [0,0,1]$ is the plane normal and $a = -d_m$ is the plane offset from $c_{ref}$. The projection $\boldsymbol{u}$ on the reference camera's image plane in regular image coordinates is attained by applying reference camera intrinsics $\boldsymbol{K_{ref}}$ to $\boldsymbol{x}$. Since the MPI is not necessarily fronto-parallel to the target camera $c_k$, $\tilde{\boldsymbol{x'}}$ need not be $[X/d_m,Y/d_m,1]$ even though $\boldsymbol{X} \sim \tilde{\boldsymbol{x'}}$ as well. $\boldsymbol{u'}$ and $\boldsymbol{K_k}$ similarly belong to the target camera, as does target camera pose (relative to reference camera) $[R_k|\boldsymbol{t_k}]$. The world plane \textit{induces} the homography $H = \boldsymbol{K_k} (R_k - \boldsymbol{t_k} \boldsymbol{n_m}^T / a) \boldsymbol{K_{ref}}^{-1}$ between the image planes of $c_{ref}$ and $c_k$, so we can go from $\boldsymbol{u}$ to $\boldsymbol{u'}$. To go from $\boldsymbol{u'}$ back to $\boldsymbol{u}$, we'd use $H^{-1}$~\cite{zikuicai_derivation_2019}.} \end{figure} Zhou et al.'s methods are ingenious in a number of ways. They trained their model to predict novel views at varying distances from input views so as not to overfit to predicting only up to a limited number of baselines. They used assorted but apt convolutional layers such as dilated convolutions to bring back larger scene contexts at lower computational costs and fractionally-strided convolutions~\cite{prove_introduction_2018} with skip connections~\cite{adaloglou_intuitive_2020} from preceding layers to capture even the finer texture details. The use of VGG perceptual loss allowed them to retain these intricate micro textures together with macro object geometries in synthesized views. Also commendable is their meticulous RealEstate10K dataset creation process which was continued by Tucker and Snavely~\cite{single_view_mpi} in bringing the dataset to it's current state~\cite{zhou2018stereo}. Knowing that state-of-the-art Structure from Motion (SfM) and bundle adjustment\footnote{initial scene reconstruction, camera calibration (including field of view estimation), and pose estimation for a candidate pair of scene views, followed by simultaneous iterative refinement of the 3D scene structure and all estimated camera parameters, using each additional view of the scene, as well, for feature matching} algorithms such as COLMAP~\cite{schoenberger2016sfm,schoenberger2016mvs} are not yet fully optimized for camera tracking in videos, they first subject candidate real estate YouTube videos to Simultaneous Localization And Mapping (SLAM) techniques such as ORB-SLAM2~\cite{mur-artal_orb-slam_2015} to obtain initial camera parameter estimates for all consecutive frames tracked. Consecutive, here, implies that each tracked frame's viewpoint is no farther than a certain percentage of the average of its two neighboring viewpoints. This process naturally breaks a video apart into clips with smoother camera motion. They then process all video clips obtained this way with COLMAP to get a sparse 3D point cloud reconstruction of the scene in each clip and a refined set of camera parameter estimates for all frames. As a final step, they \textit{scale-normalize} each subsequence and its reconstructed camera parameters and 3D points in one shot by scaling the point cloud up or down so the nearest set of points is at a fixed distance from the cameras. Points clouds are discarded by Zhou et al. after scale-normalizing the dataset whereas they are used by Tucker and Snavely~\cite{single_view_mpi} to ``scale-normalize", effectively, their entire single-view training process itself, for they don't have the luxury of inferring parameter and scene scale from more than one view at a time like how Zhou et al. does. SfM involves the estimation of the (generally sparse) 3D structure of a static scene from the multiple (usually unstructured) views of a (often uncalibrated) camera moving around the scene, accompanied by the simultaneous estimation of respective camera parameters. It is essentially a more generic version of Multi-View Stereo (MVS), which itself is an extension of stereo matching and requires known camera parameters to reconstruct (mostly) dense 3D points clouds. COLMAP is capable of both SfM and MVS. Both SfM and MVS can utilize bundle adjustment similarly to SLAM from the Robotics community. SLAM doesn't stop at bundle adjustment but rather proceeds to map out the entire terrain encountered by a robot by making connections between camera trajectories, viewed scenes, etc.~\cite{noauthor_what_nodate}. Zhou et al. made some major observations in their various ablation studies. They found that their model trained better on their preferred MPI prediction format consisting of a predicted background image that is blended with the reference image (taken as foreground) using a set of predicted color blending weights, to form each layer of the MPI. This format beat other, more-expressive formats such as ones with an additional predicted foreground or with fully predicted MPI layers. They speculate that the network's somewhat diminished performance with the latter formats could be because of network over-parameterization, more utilization of synthesized layers rather than the original reference image, and perhaps even because of lesser camera movement between the synthesized layers for the network to efficiently learn depth complexity out of. Moreover, they were able to verify that the greater the number of MPI planes used, the higher would be the model's training performance and the quality of synthesized views. Their model presents considerable scope for improvement when it comes to accurately localizing and fixing the depths of multiple overlapping fine textures, avoiding ``stacks of cards" edges in synthesized views when the disparity between the neighboring layers of an MPI exceeds one pixel, etc. Tucker and Snavely~\cite{single_view_mpi} was the first to implement learning-based single-view view synthesis on videos in the wild. It is fascinating to see how they were able to achieve efficient single-view view synthesis --- an objective coveted by Vision and Graphics communities. Moreover, there are numerous other perks to their model. It produces byproduct disparity maps that can be used in imposing a smoothness prior over synthesized viefws, in computing a global scale factor, etc. It learns to inpaint occluded content behind foreground objects without requiring ground truth 3D or depth, mainly due to their utilization of \textit{scale-invariant} view synthesis for supervision. As mentioned previously in this subsection, although Tucker and Snavely extended RealEstate10K dataset by adopting the same methods as Zhou et al.~\cite{zhou2018stereo}, yet they had to incorporate scale-normalization/scale-invariance into their training in order to circumvent the global scale factor ambiguity that arises when attempting to infer scene geometry from monocular views. They accomplish this in the following manner (Figure~\ref{fig:tucker-snavely-pipeline}): \begin{figure}[!h] \includegraphics[width=1\columnwidth]{figures/tucker-snavely-pipeline.png} \caption{Tucker and Snavely's Single-View View Synthesis Pipeline~\cite{single_view_mpi}} \label{fig:tucker-snavely-pipeline} \end{figure} \begin{itemize} \item The sparse point cloud of the scene depicted by each group of sequential video frames, the lists of all 3D points \textit{visible} from each frame, the camera parameters of each frame, and the video frames themselves are needed for training. All these input components result from the ORB-SLAM2, COLMAP, and scale-normalization procedures of Zhou et al. \item Pairs of source and target frames $(I_s,\ I_t)$ and respective camera parameters $(c_s,\ c_t)$ are randomly picked for training, along with the respective visible point sets of source frames. The sets of visible points are converted from world coordinates to camera coordinates to get a final point set $P_s = \{(x,\ y,\ d),\ \ldots\}$ for each source frame, where the $z$-coordinate of each world point becomes the depth $d$ of the world point from the source camera, and the mapped 2D points are denoted by the positions $(x,\ y)$ within the source image. \item Similarly to Zhou et al., Tucker and Snavely's chosen reference camera for the MPI planes (Figure~\ref{fig:mpi-layered-representation}) is $c_s$, and their preferred MPI prediction format consists of a predicted background image $\hat{I_b}$, a set of layer-wise predicted alphas, and a set of layer-wise color blending weights that (unlike Zhou et al.) are calculated from the alphas and not predicted by the network. Tucker and Snavely derives color blending weights $w_i$ for each MPI layer $i$ as $w_i = \underbrace{\prod_{j>i} (1 - \alpha_j)}$, and final color values $C_i$ for each layer as $C_i = w_i I_s + (1 - w_i) \hat{I_b}$. \item Similarly to Zhou et al., when rendering an MPI, Tucker and Snavely's warping function $\mathcal{W}$ uses bilinear sampling and standard inverse homography (Figure~\ref{fig:standard-inverse-homography}) to warp each layer from source viewpoint $c_s$ to target viewpoint $c_t$: $C_i' = \mathcal{W}_{c_s, c_t}(\sigma d_i, C_i)$; $\alpha_i' = \mathcal{W}_{c_s, c_t}(\sigma d_i, \alpha_i)$. The only difference is that Tucker and Snavely's $\mathcal{W}$ scales the depths by a factor $\sigma$, which they compute separately for each training instance. \item To get the final rerendered target $\hat{I_t}$, the warped layers $(C_i', \alpha_i')$ are alpha-composited as usual: \begin{equation}\label{eq:rerendered-target} \hat{I_t} = \sum_{i=1}^D \left(C_i' \alpha_i'\ \underbrace{\prod_{j=i+1}^D (1 - \alpha_j')}\right) \end{equation} Furthermore, the disparity map $\hat{D_s}$ of the source image can also be similarly synthesized from the MPI using the inverse depths $d^{-1}$ of visible points $P_s$: \begin{equation}\label{eq:disparity-map} \hat{D_s} = \sum_{i=1}^D \left(d_i^{-1} \alpha_i\ \underbrace{\prod_{j=i+1}^D (1 - \alpha_j)}\right) \end{equation} \item DeepView~\cite{flynn_deepview_2019} describes the under-braced terms in all previously mentioned formulae to be the \textit{net transmittance} at respective depth planes $i$. They reason that the terms represent the fraction of the color/disparity that persists in layer $i$ after getting attenuated through all prior layers. \item Learning the 3D scene structure from a single view is trickier than from multiple views, for only the relative pose between multiple views can implicitly resolve global scale ambiguity. But Tucker and Snavely's method is able to accept source and target inputs of unknown scale and still make rerendered images match ground-truth because they solve for the unknown scale factor as part of their MPI generation. They observe that RealEstate10K-dataset-derived inputs $c_s$, $c_t$, and $P_s$ are consistent in scale for each training instance. They, therefore, compute $\sigma$ to be the scale factor that minimizes the log-squared error between the predicted disparity map $\hat{D_s}$, bilinearly sampled at each position $(x,y)$, and the point set $P_s$: \[\sigma = exp \left[\frac{1}{|P_s|} \sum_{(x,y,d) \in P_s} (ln \hat{D_s}(x,y) - ln(d^{-1}))\right]\] After $\sigma$ is applied in warping with $\mathcal{W}$ as shown before, the rendered image no longer varies with the scale of the input viewpoints and point set, and can be used in the various loss functions. \item Their weighted aggregate loss function is given by \begin{equation}\label{eq:aggregate-loss} \mathcal{L} = \lambda_p \mathcal{L}^{pixel} + \lambda_s \mathcal{L}^{smooth} + \lambda_d \mathcal{L}^{depth} \end{equation} Here, $\mathcal{L}^{pixel}$ is just the regular $L_1$ photometric distance between synthesize and ground-truth target views: \[\mathcal{L}^{pixel} = \sum_{channels} \frac{1}{N} \sum_{(x,y)} |\hat{I_t} - I_t|\] $\mathcal{L}^{smooth}$ is the \textit{edge-aware smoothness loss} that prevents the gradients of the synthesized disparity map $\hat{D_s}$ from crossing a certain threshold ($g_{min}$, usually 0.05) whenever there is no edge detected in the source image, like so: \[\mathcal{L}^{smooth} = \frac{1}{N} \sum_{(x,y)} \left(max\left(G(\hat{D_s}) - g_{min},\ 0\right) \odot (1 - E_s)\right)\] where $\odot$ is the Hadamard product, $G$ represents the $L_1$ norm of the gradient of an image summed over all three color channels, like so: \[G(I) = \sum_{channels} ||\nabla I||_1\] where Sobel filters are used to compute the gradient, and $E_s$ represents a custom edge detector for the source image, which signals the presence of an edge whenever the gradient of the source image is at least a fraction ($e_{min}$, usually 0.1) of its own maximum value over the entire image, like so: \[E_s = min \left(\frac{G(I_s)}{e_{min} \times max_{(x,y)} G(I_s)},\ 1\right)\] and $\mathcal{L}^{depth}$ is a sparse depth loss given by the $L_2$ difference between the logs of the disparities derived using the predicted alphas (i.e., the synthesized disparity map) on the on hand and the input point set $P_s$ and the other, like so \[\mathcal{L}^{depth} = \frac{1}{|P_s|} \sum_{(x,y,d) \in P_s} \left(ln\frac{\hat{D_s}(x,y)}{\sigma} - ln(d^{-1})\right)^2\] where the computed scale factor $\sigma$ that minimizes $\mathcal{L}^{depth}$ is itself included. \end{itemize} The network used is architecturally similar to DispNet~\cite{mayer_large_2016}. In our work, in the process of recreating Tucker and Snavely's model and retraining it on video-chat-relevant scenes, we have reimplemented their weighted aggregate loss function, among other model features. We retained their chosen loss function weights of $\lambda_p = 1$ and $\lambda_s = 0.5$, except for picking $\lambda_d$ to be 1 whereas their chosen $\lambda_d$ value was 0.1. We also retained their choice of optimizer --- Adam --- but used a different learning rate 0.00001. Even though there is still a lot of scope for improvement in performance with regard to model-induced artifacts reducing the quality of synthesized views, Tucker and Snavely's authors share how the various aspects of the model contribute to it beating the state-of-the-art. They show that the scale-invariant nature of the model's supervision by view synthesis (i.e., usage of ground-truth target views) plays a major role in its success, followed by the edge-aware smoothness prior, and the chosen MPI format involving a predicted background. Another triumph of their model is that even though it does not use depth supervision at all, it is comparable to state-of-the-art depth prediction methods that use explicit depth supervision. Their project presents exciting future opportunities such as turning the model into a Generative Adversarial Network (GAN)~\cite{goodfellow_generative_2014} to possibly produce more extensive and realistic inpainting, and so on.
<a href="https://colab.research.google.com/github/NeuromatchAcademy/course-content/blob/master/tutorials/W2D3_BiologicalNeuronModels/W2D3_Tutorial1.ipynb" target="_parent"></a> # Tutorial 1: The Leaky Integrate-and-Fire (LIF) Neuron Model **Week 2, Day 3: Biological Neuron Models** **By Neuromatch Academy** __Content creators:__ Qinglong Gu, Songtin Li, John Murray, Richard Naud, Arvind Kumar __Content reviewers:__ Maryam Vaziri-Pashkam, Ella Batty, Lorenzo Fontolan, Richard Gao, Matthew Krause, Spiros Chavlis, Michael Waskom, Ethan Cheng **Our 2021 Sponsors, including Presenting Sponsor Facebook Reality Labs** <p align='center'></p> --- # Tutorial Objectives *Estimated timing of tutorial: 1 hour, 10 min* This is Tutorial 1 of a series on implementing realistic neuron models. In this tutorial, we will build up a leaky integrate-and-fire (LIF) neuron model and study its dynamics in response to various types of inputs. In particular, we are going to write a few lines of code to: - simulate the LIF neuron model - drive the LIF neuron with external inputs, such as direct currents, Gaussian white noise, and Poisson spike trains, etc. - study how different inputs affect the LIF neuron's output (firing rate and spike time irregularity) Here, we will especially emphasize identifying conditions (input statistics) under which a neuron can spike at low firing rates and in an irregular manner. The reason for focusing on this is that in most cases, neocortical neurons spike in an irregular manner. ```python # @title Tutorial slides # @markdown These are the slides for the videos in all tutorials today from IPython.display import IFrame IFrame(src=f"https://mfr.ca-1.osf.io/render?url=https://osf.io/8djsm/?direct%26mode=render%26action=download%26mode=render", width=854, height=480) ``` --- # Setup ```python # Imports import numpy as np import matplotlib.pyplot as plt ``` ```python # @title Figure Settings import ipywidgets as widgets # interactive display %config InlineBackend.figure_format = 'retina' # use NMA plot style plt.style.use("https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/nma.mplstyle") my_layout = widgets.Layout() ``` ```python # @title Plotting Functions def plot_volt_trace(pars, v, sp): """ Plot trajetory of membrane potential for a single neuron Expects: pars : parameter dictionary v : volt trajetory sp : spike train Returns: figure of the membrane potential trajetory for a single neuron """ V_th = pars['V_th'] dt, range_t = pars['dt'], pars['range_t'] if sp.size: sp_num = (sp / dt).astype(int) - 1 v[sp_num] += 20 # draw nicer spikes plt.plot(pars['range_t'], v, 'b') plt.axhline(V_th, 0, 1, color='k', ls='--') plt.xlabel('Time (ms)') plt.ylabel('V (mV)') plt.legend(['Membrane\npotential', r'Threshold V$_{\mathrm{th}}$'], loc=[1.05, 0.75]) plt.ylim([-80, -40]) def plot_GWN(pars, I_GWN): """ Args: pars : parameter dictionary I_GWN : Gaussian white noise input Returns: figure of the gaussian white noise input """ plt.figure(figsize=(12, 4)) plt.subplot(121) plt.plot(pars['range_t'][::3], I_GWN[::3], 'b') plt.xlabel('Time (ms)') plt.ylabel(r'$I_{GWN}$ (pA)') plt.subplot(122) plot_volt_trace(pars, v, sp) plt.tight_layout() def my_hists(isi1, isi2, cv1, cv2, sigma1, sigma2): """ Args: isi1 : vector with inter-spike intervals isi2 : vector with inter-spike intervals cv1 : coefficient of variation for isi1 cv2 : coefficient of variation for isi2 Returns: figure with two histograms, isi1, isi2 """ plt.figure(figsize=(11, 4)) my_bins = np.linspace(10, 30, 20) plt.subplot(121) plt.hist(isi1, bins=my_bins, color='b', alpha=0.5) plt.xlabel('ISI (ms)') plt.ylabel('count') plt.title(r'$\sigma_{GWN}=$%.1f, CV$_{\mathrm{isi}}$=%.3f' % (sigma1, cv1)) plt.subplot(122) plt.hist(isi2, bins=my_bins, color='b', alpha=0.5) plt.xlabel('ISI (ms)') plt.ylabel('count') plt.title(r'$\sigma_{GWN}=$%.1f, CV$_{\mathrm{isi}}$=%.3f' % (sigma2, cv2)) plt.tight_layout() plt.show() ``` --- # Section 1: The Leaky Integrate-and-Fire (LIF) model ```python # @title Video 1: Reduced Neuron Models from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = 'https://player.bilibili.com/player.html?bvid={0}&page={1}'.format(id, page) super(BiliVideo, self).__init__(src, width, height, **kwargs) video = BiliVideo(id="av456396195", width=854, height=480, fs=1) print('Video available at https://www.bilibili.com/video/{0}'.format(video.id)) display(video) out1 = widgets.Output() with out1: from IPython.display import YouTubeVideo video = YouTubeVideo(id="rSExvwCVRYg", width=854, height=480, fs=1, rel=0) print('Video available at https://youtube.com/watch?v=' + video.id) display(video) out = widgets.Tab([out1, out2]) out.set_title(0, 'Youtube') out.set_title(1, 'Bilibili') display(out) ``` Tab(children=(Output(), Output()), _titles={'0': 'Youtube', '1': 'Bilibili'}) This video introduces the reduction of a biological neuron to a simple leaky-integrate-fire (LIF) neuron model. <details> <summary> <font color='blue'>Click here for text recap of video </font></summary> Now, it's your turn to implement one of the simplest mathematical model of a neuron: the leaky integrate-and-fire (LIF) model. The basic idea of LIF neuron was proposed in 1907 by Louis Édouard Lapicque, long before we understood the electrophysiology of a neuron (see a translation of [Lapicque's paper](https://pubmed.ncbi.nlm.nih.gov/17968583/) ). More details of the model can be found in the book [**Theoretical neuroscience**](http://www.gatsby.ucl.ac.uk/~dayan/book/) by Peter Dayan and Laurence F. Abbott. The subthreshold membrane potential dynamics of a LIF neuron is described by \begin{eqnarray} C_m\frac{dV}{dt} = -g_L(V-E_L) + I,\quad (1) \end{eqnarray} where $C_m$ is the membrane capacitance, $V$ is the membrane potential, $g_L$ is the leak conductance ($g_L = 1/R$, the inverse of the leak resistance $R$ mentioned in previous tutorials), $E_L$ is the resting potential, and $I$ is the external input current. Dividing both sides of the above equation by $g_L$ gives \begin{align} \tau_m\frac{dV}{dt} = -(V-E_L) + \frac{I}{g_L}\,,\quad (2) \end{align} where the $\tau_m$ is membrane time constant and is defined as $\tau_m=C_m/g_L$. Note that dividing capacitance by conductance gives units of time! Below, we will use Eqn.(2) to simulate LIF neuron dynamics. If $I$ is sufficiently strong such that $V$ reaches a certain threshold value $V_{\rm th}$, $V$ is reset to a reset potential $V_{\rm reset}< V_{\rm th}$, and voltage is clamped to $V_{\rm reset}$ for $\tau_{\rm ref}$ ms, mimicking the refractoriness of the neuron during an action potential: \begin{eqnarray} \mathrm{if}\quad V(t_{\text{sp}})\geq V_{\rm th}&:& V(t)=V_{\rm reset} \text{ for } t\in(t_{\text{sp}}, t_{\text{sp}} + \tau_{\text{ref}}] \end{eqnarray} where $t_{\rm sp}$ is the spike time when $V(t)$ just exceeded $V_{\rm th}$. (__Note__: in the lecture slides, $\theta$ corresponds to the threshold voltage $V_{th}$, and $\Delta$ corresponds to the refractory time $\tau_{\rm ref}$.) </details> Note that you have seen the LIF model before if you looked at the pre-reqs Python or Calculus days! The LIF model captures the facts that a neuron: - performs spatial and temporal integration of synaptic inputs - generates a spike when the voltage reaches a certain threshold - goes refractory during the action potential - has a leaky membrane The LIF model assumes that the spatial and temporal integration of inputs is linear. Also, membrane potential dynamics close to the spike threshold are much slower in LIF neurons than in real neurons. ## Coding Exercise 1: Python code to simulate the LIF neuron We now write Python code to calculate our equation for the LIF neuron and simulate the LIF neuron dynamics. We will use the Euler method, which you saw in the linear systems case yesterday to numerically integrate this equation: \begin{align*} \tau_m\frac{dV}{dt} = -(V-E_L) + \frac{I}{g_L}\, \end{align*} where $V$ is the membrane potential, $g_L$ is the leak conductance, $E_L$ is the resting potential, $I$ is the external input current, and $\tau_m$ is membrane time constant. The cell below initializes a dictionary that stores parameters of the LIF neuron model and the simulation scheme. You can use `pars=default_pars(T=simulation_time, dt=time_step)` to get the parameters. Note that, `simulation_time` and `time_step` have the unit `ms`. In addition, you can add the value to a new parameter by `pars['New_param'] = value`. ```python # @markdown Execute this code to initialize the default parameters def default_pars(**kwargs): pars = {} # typical neuron parameters# pars['V_th'] = -55. # spike threshold [mV] pars['V_reset'] = -75. # reset potential [mV] pars['tau_m'] = 10. # membrane time constant [ms] pars['g_L'] = 10. # leak conductance [nS] pars['V_init'] = -75. # initial potential [mV] pars['E_L'] = -75. # leak reversal potential [mV] pars['tref'] = 2. # refractory time (ms) # simulation parameters # pars['T'] = 400. # Total duration of simulation [ms] pars['dt'] = .1 # Simulation time step [ms] # external parameters if any # for k in kwargs: pars[k] = kwargs[k] pars['range_t'] = np.arange(0, pars['T'], pars['dt']) # Vector of discretized time points [ms] return pars pars = default_pars() print(pars) ``` {'V_th': -55.0, 'V_reset': -75.0, 'tau_m': 10.0, 'g_L': 10.0, 'V_init': -75.0, 'E_L': -75.0, 'tref': 2.0, 'T': 400.0, 'dt': 0.1, 'range_t': array([0.000e+00, 1.000e-01, 2.000e-01, ..., 3.997e+02, 3.998e+02, 3.999e+02])} Complete the function below to simulate the LIF neuron when receiving external current inputs. You can use `v, sp = run_LIF(pars, Iinj)` to get the membrane potential (`v`) and spike train (`sp`) given the dictionary `pars` and input current `Iinj`. ```python def run_LIF(pars, Iinj, stop=False): """ Simulate the LIF dynamics with external input current Args: pars : parameter dictionary Iinj : input current [pA]. The injected current here can be a value or an array stop : boolean. If True, use a current pulse Returns: rec_v : membrane potential rec_sp : spike times """ # Set parameters V_th, V_reset = pars['V_th'], pars['V_reset'] tau_m, g_L = pars['tau_m'], pars['g_L'] V_init, E_L = pars['V_init'], pars['E_L'] dt, range_t = pars['dt'], pars['range_t'] Lt = range_t.size tref = pars['tref'] # Initialize voltage v = np.zeros(Lt) v[0] = V_init # Set current time course Iinj = Iinj * np.ones(Lt) # If current pulse, set beginning and end to 0 if stop: Iinj[:int(len(Iinj) / 2) - 1000] = 0 Iinj[int(len(Iinj) / 2) + 1000:] = 0 # Loop over time rec_spikes = [] # record spike times tr = 0. # the count for refractory duration for it in range(Lt - 1): if tr > 0: # check if in refractory period v[it] = V_reset # set voltage to reset tr = tr - 1 # reduce running counter of refractory period elif v[it] >= V_th: # if voltage over threshold rec_spikes.append(it) # record spike event v[it] = V_reset # reset voltage tr = tref / dt # set refractory time ######################################################################## ## TODO for students: compute the membrane potential v, spike train sp # # Fill out function and remove #raise NotImplementedError('Student Exercise: calculate the dv/dt and the update step!') ######################################################################## # Calculate the increment of the membrane potential dv = (1 / tau_m ) * ( -1 * ( v[it] - E_L ) + Iinj[it] / g_L ) * dt # Update the membrane potential v[it + 1] = v[it] + dv # Get spike times in ms rec_spikes = np.array(rec_spikes) * dt return v, rec_spikes # Get parameters pars = default_pars(T=500) # Simulate LIF model v, sp = run_LIF(pars, Iinj=100, stop=True) # Visualize plot_volt_trace(pars, v, sp) ``` ```python # to_remove solution def run_LIF(pars, Iinj, stop=False): """ Simulate the LIF dynamics with external input current Args: pars : parameter dictionary Iinj : input current [pA]. The injected current here can be a value or an array stop : boolean. If True, use a current pulse Returns: rec_v : membrane potential rec_sp : spike times """ # Set parameters V_th, V_reset = pars['V_th'], pars['V_reset'] tau_m, g_L = pars['tau_m'], pars['g_L'] V_init, E_L = pars['V_init'], pars['E_L'] dt, range_t = pars['dt'], pars['range_t'] Lt = range_t.size tref = pars['tref'] # Initialize voltage v = np.zeros(Lt) v[0] = V_init # Set current time course Iinj = Iinj * np.ones(Lt) # If current pulse, set beginning and end to 0 if stop: Iinj[:int(len(Iinj) / 2) - 1000] = 0 Iinj[int(len(Iinj) / 2) + 1000:] = 0 # Loop over time rec_spikes = [] # record spike times tr = 0. # the count for refractory duration for it in range(Lt - 1): if tr > 0: # check if in refractory period v[it] = V_reset # set voltage to reset tr = tr - 1 # reduce running counter of refractory period elif v[it] >= V_th: # if voltage over threshold rec_spikes.append(it) # record spike event v[it] = V_reset # reset voltage tr = tref / dt # set refractory time # Calculate the increment of the membrane potential dv = (-(v[it] - E_L) + Iinj[it] / g_L) * (dt / tau_m) # Update the membrane potential v[it + 1] = v[it] + dv # Get spike times in ms rec_spikes = np.array(rec_spikes) * dt return v, rec_spikes # Get parameters pars = default_pars(T=500) # Simulate LIF model v, sp = run_LIF(pars, Iinj=100, stop=True) # Visualize with plt.xkcd(): plot_volt_trace(pars, v, sp) ``` --- # Section 2: Response of an LIF model to different types of input currents *Estimated timing to here from start of tutorial: 20 min* In the following section, we will learn how to inject direct current and white noise to study the response of an LIF neuron. ```python # @title Video 2: Response of the LIF neuron to different inputs from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = 'https://player.bilibili.com/player.html?bvid={0}&page={1}'.format(id, page) super(BiliVideo, self).__init__(src, width, height, **kwargs) video = BiliVideo(id="av541417171", width=854, height=480, fs=1) print('Video available at https://www.bilibili.com/video/{0}'.format(video.id)) display(video) out1 = widgets.Output() with out1: from IPython.display import YouTubeVideo video = YouTubeVideo(id="preNGdab7Kk", width=854, height=480, fs=1, rel=0) print('Video available at https://youtube.com/watch?v=' + video.id) display(video) out = widgets.Tab([out1, out2]) out.set_title(0, 'Youtube') out.set_title(1, 'Bilibili') display(out) ``` Tab(children=(Output(), Output()), _titles={'0': 'Youtube', '1': 'Bilibili'}) ## Section 2.1: Direct current (DC) *Estimated timing to here from start of tutorial: 30 min* ### Interactive Demo 2.1: Parameter exploration of DC input amplitude Here's an interactive demo that shows how the LIF neuron behavior changes for DC input (constant current) with different amplitudes. We plot the membrane potential of an LIF neuron. You may notice that the neuron generates a spike. But this is just a cosmetic spike only for illustration purposes. In an LIF neuron, we only need to keep track of times when the neuron hit the threshold so the postsynaptic neurons can be informed of the spike. How much DC is needed to reach the threshold (rheobase current)? How does the membrane time constant affect the frequency of the neuron? ```python # @title # @markdown Make sure you execute this cell to enable the widget! my_layout.width = '450px' @widgets.interact( I_dc=widgets.FloatSlider(50., min=0., max=300., step=10., layout=my_layout), tau_m=widgets.FloatSlider(10., min=2., max=20., step=2., layout=my_layout) ) def diff_DC(I_dc=200., tau_m=10.): pars = default_pars(T=100.) pars['tau_m'] = tau_m v, sp = run_LIF(pars, Iinj=I_dc) plot_volt_trace(pars, v, sp) plt.show() ``` interactive(children=(FloatSlider(value=50.0, description='I_dc', layout=Layout(width='450px'), max=300.0, ste… ```python # to_remove explanation """ 1. As we increase the current, we observe that at 210 pA we cross the threshold. 2. As we increase the membrane time constant (slower membrane), the firing rate is decreased because the membrane needs more time to reach the threshold after the reset. """; ``` ## Section 2.2: Gaussian white noise (GWN) current *Estimated timing to here from start of tutorial: 38 min* Given the noisy nature of neuronal activity _in vivo_, neurons usually receive complex, time-varying inputs. To mimic this, we will now investigate the neuronal response when the LIF neuron receives Gaussian white noise $\xi(t)$ with mean 0 ($\mu = 0$) and some standard deviation $\sigma$. Note that the GWN has zero mean, that is, it describes only the fluctuations of the input received by a neuron. We can thus modify our definition of GWN to have a nonzero mean value $\mu$ that equals the DC input, since this is the average input into the cell. The cell below defines the modified gaussian white noise currents with nonzero mean $\mu$. ### Interactive Demo 2.2: LIF neuron Explorer for noisy input The mean of the Gaussian white noise (GWN) is the amplitude of DC. Indeed, when $\sigma = 0$, GWN is just a DC. So the question arises how does $\sigma$ of the GWN affect the spiking behavior of the neuron. For instance we may want to know 1. how does the minimum input (i.e. $\mu$) needed to make a neuron spike change with increase in $\sigma$ 2. how does the spike regularity change with increase in $\sigma$ To get an intuition about these questions you can use the following interactive demo that shows how the LIF neuron behavior changes for noisy input with different amplitudes (the mean $\mu$) and fluctuation sizes ($\sigma$). We use a helper function to generate this noisy input current: `my_GWN(pars, mu, sig, myseed=False)`. Note that fixing the value of the random seed (e.g., `myseed=2020`) will allow you to obtain the same result every time you run this. We then use our `run_LIF` function to simulate the LIF model. ```python # @markdown Execute to enable helper function `my_GWN` def my_GWN(pars, mu, sig, myseed=False): """ Function that generates Gaussian white noise input Args: pars : parameter dictionary mu : noise baseline (mean) sig : noise amplitute (standard deviation) myseed : random seed. int or boolean the same seed will give the same random number sequence Returns: I : Gaussian white noise input """ # Retrieve simulation parameters dt, range_t = pars['dt'], pars['range_t'] Lt = range_t.size # Set random seed if myseed: np.random.seed(seed=myseed) else: np.random.seed() # Generate GWN # we divide here by 1000 to convert units to sec. I_gwn = mu + sig * np.random.randn(Lt) / np.sqrt(dt / 1000.) return I_gwn help(my_GWN) ``` Help on function my_GWN in module __main__: my_GWN(pars, mu, sig, myseed=False) Function that generates Gaussian white noise input Args: pars : parameter dictionary mu : noise baseline (mean) sig : noise amplitute (standard deviation) myseed : random seed. int or boolean the same seed will give the same random number sequence Returns: I : Gaussian white noise input ```python # @title # @markdown Make sure you execute this cell to enable the widget! my_layout.width = '450px' @widgets.interact( mu_gwn=widgets.FloatSlider(200., min=100., max=300., step=5., layout=my_layout), sig_gwn=widgets.FloatSlider(2.5, min=0., max=5., step=.5, layout=my_layout) ) def diff_GWN_to_LIF(mu_gwn, sig_gwn): pars = default_pars(T=100.) I_GWN = my_GWN(pars, mu=mu_gwn, sig=sig_gwn) v, sp = run_LIF(pars, Iinj=I_GWN) plt.figure(figsize=(12, 4)) plt.subplot(121) plt.plot(pars['range_t'][::3], I_GWN[::3], 'b') plt.xlabel('Time (ms)') plt.ylabel(r'$I_{GWN}$ (pA)') plt.subplot(122) plot_volt_trace(pars, v, sp) plt.tight_layout() plt.show() ``` interactive(children=(FloatSlider(value=200.0, description='mu_gwn', layout=Layout(width='450px'), max=300.0, … ```python # to_remove explanation """ 1) If we have bigger current fluctuations (increased sigma), the minimum input needed to make a neuron spike is smaller as the fluctuations can help push the voltage above threshold. 2) The standard deviation (or size of current fluctuations) dictates the level of irregularity of the spikes; the higher the sigma the more irregular the observed spikes. """; ``` ### Think! 2.2: Analyzing GWN Effects on Spiking - As we increase the input average ($\mu$) or the input fluctuation ($\sigma$), the spike count changes. How much can we increase the spike count, and what might be the relationship between GWN mean/std or DC value and spike count? - We have seen above that when we inject DC, the neuron spikes in a regular manner (clock like), and this regularity is reduced when GWN is injected. The question is, how irregular can we make the neurons spiking by changing the parameters of the GWN? We will see the answers to these questions in the next section but discuss first! --- # Section 3: Firing rate and spike time irregularity *Estimated timing to here from start of tutorial: 48 min* When we plot the output firing rate as a function of GWN mean or DC value, it is called the input-output transfer function of the neuron (so simply F-I curve). Spike regularity can be quantified as the **coefficient of variation (CV) of the inter-spike-interval (ISI)**: \begin{align} \text{CV}_{\text{ISI}} = \frac{std(\text{ISI})}{mean(\text{ISI})} \end{align} A Poisson train is an example of high irregularity, in which $\textbf{CV}_{\textbf{ISI}} \textbf{= 1}$. And for a clocklike (regular) process we have $\textbf{CV}_{\textbf{ISI}} \textbf{= 0}$ because of **std(ISI)=0**. ## Interactive Demo 3A: F-I Explorer for different `sig_gwn` How does the F-I curve of the LIF neuron change as we increase the $\sigma$ of the GWN? We can already expect that the F-I curve will be stochastic and the results will vary from one trial to another. But will there be any other change compared to the F-I curved measured using DC? Here's an interactive demo that shows how the F-I curve of a LIF neuron changes for different levels of fluctuation $\sigma$. ```python # @title # @markdown Make sure you execute this cell to enable the widget! my_layout.width = '450px' @widgets.interact( sig_gwn=widgets.FloatSlider(3.0, min=0., max=6., step=0.5, layout=my_layout) ) def diff_std_affect_fI(sig_gwn): pars = default_pars(T=1000.) I_mean = np.arange(100., 400., 10.) spk_count = np.zeros(len(I_mean)) spk_count_dc = np.zeros(len(I_mean)) for idx in range(len(I_mean)): I_GWN = my_GWN(pars, mu=I_mean[idx], sig=sig_gwn, myseed=2020) v, rec_spikes = run_LIF(pars, Iinj=I_GWN) v_dc, rec_sp_dc = run_LIF(pars, Iinj=I_mean[idx]) spk_count[idx] = len(rec_spikes) spk_count_dc[idx] = len(rec_sp_dc) # Plot the F-I curve i.e. Output firing rate as a function of input mean. plt.figure() plt.plot(I_mean, spk_count, 'k', label=r'$\sigma_{\mathrm{GWN}}=%.2f$' % sig_gwn) plt.plot(I_mean, spk_count_dc, 'k--', alpha=0.5, lw=4, dashes=(2, 2), label='DC input') plt.ylabel('Spike count') plt.xlabel('Average injected current (pA)') plt.legend(loc='best') plt.show() ``` interactive(children=(FloatSlider(value=3.0, description='sig_gwn', layout=Layout(width='450px'), max=6.0, ste… ```python # to_remove explanation """ If we use a DC input, the F-I curve is deterministic, and we can found its shape by solving the membrane equation of the neuron. If we have GWN, as we increase the sigma, the F-I curve has a more linear shape, and the neuron reaches its threshold using less average injected current. """ ``` ## Coding Exercise 3: Compute $CV_{ISI}$ values As shown above, the F-I curve becomes smoother while increasing the amplitude of the fluctuation ($\sigma$). In addition, the fluctuation can also change the irregularity of the spikes. Let's investigate the effect of $\mu=250$ with $\sigma=0.5$ vs $\sigma=3$. Fill in the code below to compute ISI, then plot the histogram of the ISI and compute the $CV_{ISI}$. Note that, you can use `np.diff` to calculate ISI. ```python def isi_cv_LIF(spike_times): """ Calculates the inter-spike intervals (isi) and the coefficient of variation (cv) for a given spike_train Args: spike_times : (n, ) vector with the spike times (ndarray) Returns: isi : (n-1,) vector with the inter-spike intervals (ms) cv : coefficient of variation of isi (float) """ ######################################################################## ## TODO for students: compute the membrane potential v, spike train sp # # Fill out function and remove #raise NotImplementedError('Student Exercise: calculate the isi and the cv!') ######################################################################## if len(spike_times) >= 2: # Compute isi isi = np.diff(spike_times) # Compute cv cv = np.std(isi) / np.mean(isi) else: isi = np.nan cv = np.nan return isi, cv # Set parameters pars = default_pars(T=1000.) mu_gwn = 250 sig_gwn1 = 0.5 sig_gwn2 = 3.0 # Run LIF model for sigma = 0.5 I_GWN1 = my_GWN(pars, mu=mu_gwn, sig=sig_gwn1, myseed=2020) _, sp1 = run_LIF(pars, Iinj=I_GWN1) # Run LIF model for sigma = 3 I_GWN2 = my_GWN(pars, mu=mu_gwn, sig=sig_gwn2, myseed=2020) _, sp2 = run_LIF(pars, Iinj=I_GWN2) # Compute ISIs/CV isi1, cv1 = isi_cv_LIF(sp1) isi2, cv2 = isi_cv_LIF(sp2) # Visualize my_hists(isi1, isi2, cv1, cv2, sig_gwn1, sig_gwn2) ``` ```python # to_remove solution def isi_cv_LIF(spike_times): """ Calculates the inter-spike intervals (isi) and the coefficient of variation (cv) for a given spike_train Args: spike_times : (n, ) vector with the spike times (ndarray) Returns: isi : (n-1,) vector with the inter-spike intervals (ms) cv : coefficient of variation of isi (float) """ if len(spike_times) >= 2: # Compute isi isi = np.diff(spike_times) # Compute cv cv = isi.std()/isi.mean() else: isi = np.nan cv = np.nan return isi, cv # Set parameters pars = default_pars(T=1000.) mu_gwn = 250 sig_gwn1 = 0.5 sig_gwn2 = 3.0 # Run LIF model for sigma = 0.5 I_GWN1 = my_GWN(pars, mu=mu_gwn, sig=sig_gwn1, myseed=2020) _, sp1 = run_LIF(pars, Iinj=I_GWN1) # Run LIF model for sigma = 3 I_GWN2 = my_GWN(pars, mu=mu_gwn, sig=sig_gwn2, myseed=2020) _, sp2 = run_LIF(pars, Iinj=I_GWN2) # Compute ISIs/CV isi1, cv1 = isi_cv_LIF(sp1) isi2, cv2 = isi_cv_LIF(sp2) # Visualize with plt.xkcd(): my_hists(isi1, isi2, cv1, cv2, sig_gwn1, sig_gwn2) ``` ## Interactive Demo 3B: Spike irregularity explorer for different `sig_gwn` In the above illustration, we see that the CV of inter-spike-interval (ISI) distribution depends on $\sigma$ of GWN. What about the mean of GWN, should that also affect the CV$_{\rm ISI}$? If yes, how? Does the efficacy of $\sigma$ in increasing the CV$_{\rm ISI}$ depend on $\mu$? In the following interactive demo, you will examine how different levels of fluctuation $\sigma$ affect the CVs for different average injected currents ($\mu$). 1. Does the standard deviation of the injected current affect the F-I curve in any qualitative manner? 2. Why does increasing the mean of GWN reduce the $CV_{ISI}$? 3. If you plot spike count (or rate) vs. $CV_{ISI}$, should there be a relationship between the two? Try out yourself. ```python #@title #@markdown Make sure you execute this cell to enable the widget! my_layout.width = '450px' @widgets.interact( sig_gwn=widgets.FloatSlider(0.0, min=0., max=10., step=0.5, layout=my_layout) ) def diff_std_affect_fI(sig_gwn): pars = default_pars(T=1000.) I_mean = np.arange(100., 400., 20) spk_count = np.zeros(len(I_mean)) cv_isi = np.empty(len(I_mean)) for idx in range(len(I_mean)): I_GWN = my_GWN(pars, mu=I_mean[idx], sig=sig_gwn) v, rec_spikes = run_LIF(pars, Iinj=I_GWN) spk_count[idx] = len(rec_spikes) if len(rec_spikes) > 3: isi = np.diff(rec_spikes) cv_isi[idx] = np.std(isi) / np.mean(isi) # Plot the F-I curve i.e. Output firing rate as a function of input mean. plt.figure() plt.plot(I_mean[spk_count > 5], cv_isi[spk_count > 5], 'bo', alpha=0.5) plt.xlabel('Average injected current (pA)') plt.ylabel(r'Spike irregularity ($\mathrm{CV}_\mathrm{ISI}$)') plt.ylim(-0.1, 1.5) plt.grid(True) plt.show() ``` interactive(children=(FloatSlider(value=0.0, description='sig_gwn', layout=Layout(width='450px'), max=10.0, st… ```python # to_remove explanation """ 1. Yes, it does. With DC input the F-I curve has a strong non-linearity but when a neuron is driven with GWN, as we increase the $\sigma$ the non-linearity is smoothened out. Essentially, in this case noise is acting to suppress the non-linearities and render a neuron as a linear system. 2. (here is a short answer) When we increase the mean of the GWN, at some point effective input mean is above the spike threshold and then the neuron operates in the so called mean-driven regime -- as the input is so high all the neuron is does is charge up to the spike threshold and reset. This essentially gives almost regular spiking. 3. In an LIF, high firing rates are achieved for high GWN mean. Higher the mean, higher the firing rate and lower the CV_ISI. So you will expect that as firing rate increases, spike irregularity decreases. This is because of the spike threshold. For a Poisson process there is no relationship between spike rate and spike irregularity. """; ``` --- # Summary *Estimated timing of tutorial: 1 hour, 10 min* Congratulations! You've just built a leaky integrate-and-fire (LIF) neuron model from scratch, and studied its dynamics in response to various types of inputs, having: - simulated the LIF neuron model - driven the LIF neuron with external inputs, such as direct current and Gaussian white noise - studied how different inputs affect the LIF neuron's output (firing rate and spike time irregularity), with a special focus on low rate and irregular firing regime to mimc real cortical neurons. The next tutorial will look at how spiking statistics may be influenced by a neuron's input statistics. If you have extra time, look at the bonus sections below to explore a different type of noise input and learn about extensions to integrate-and-fire models. --- # Bonus --- ## Bonus Section 1: Orenstein-Uhlenbeck Process When a neuron receives spiking input, the synaptic current is Shot Noise -- which is a kind of colored noise and the spectrum of the noise determined by the synaptic kernel time constant. That is, a neuron is driven by **colored noise** and not GWN. We can model colored noise using the Ohrenstein-Uhlenbeck process - filtered white noise. We next study if the input current is temporally correlated and is modeled as an Ornstein-Uhlenbeck process $\eta(t)$, i.e., low-pass filtered GWN with a time constant $\tau_{\eta}$: $$\tau_\eta \frac{d}{dt}\eta(t) = \mu-\eta(t) + \sigma_\eta\sqrt{2\tau_\eta}\xi(t).$$ **Hint:** An OU process as defined above has $$E[\eta(t)]=\mu$$ and autocovariance $$[\eta(t)\eta(t+\tau)]=\sigma_\eta^2e^{-|t-\tau|/\tau_\eta},$$ which can be used to check your code. ```python # @markdown Execute this cell to get helper function `my_OU` def my_OU(pars, mu, sig, myseed=False): """ Function that produces Ornstein-Uhlenbeck input Args: pars : parameter dictionary sig : noise amplitute myseed : random seed. int or boolean Returns: I_ou : Ornstein-Uhlenbeck input current """ # Retrieve simulation parameters dt, range_t = pars['dt'], pars['range_t'] Lt = range_t.size tau_ou = pars['tau_ou'] # [ms] # set random seed if myseed: np.random.seed(seed=myseed) else: np.random.seed() # Initialize noise = np.random.randn(Lt) I_ou = np.zeros(Lt) I_ou[0] = noise[0] * sig # generate OU for it in range(Lt-1): I_ou[it+1] = I_ou[it] + (dt / tau_ou) * (mu - I_ou[it]) + np.sqrt(2 * dt / tau_ou) * sig * noise[it + 1] return I_ou help(my_OU) ``` ### Bonus Interactive Demo 1: LIF Explorer with OU input In the following, we will check how a neuron responds to a noisy current that follows the statistics of an OU process. - How does the OU type input change neuron responsiveness? - What do you think will happen to the spike pattern and rate if you increased or decreased the time constant of the OU process? ```python # @title # @markdown Remember to enable the widget by running the cell! my_layout.width = '450px' @widgets.interact( tau_ou=widgets.FloatSlider(10.0, min=5., max=20., step=2.5, layout=my_layout), sig_ou=widgets.FloatSlider(10.0, min=5., max=40., step=2.5, layout=my_layout), mu_ou=widgets.FloatSlider(190.0, min=180., max=220., step=2.5, layout=my_layout) ) def LIF_with_OU(tau_ou=10., sig_ou=40., mu_ou=200.): pars = default_pars(T=1000.) pars['tau_ou'] = tau_ou # [ms] I_ou = my_OU(pars, mu_ou, sig_ou) v, sp = run_LIF(pars, Iinj=I_ou) plt.figure(figsize=(12, 4)) plt.subplot(121) plt.plot(pars['range_t'], I_ou, 'b', lw=1.0) plt.xlabel('Time (ms)') plt.ylabel(r'$I_{\mathrm{OU}}$ (pA)') plt.subplot(122) plot_volt_trace(pars, v, sp) plt.tight_layout() plt.show() ``` ```python # to_remove explanation """ In a limiting case, when the time constant of the OU process is very long and the input current is almost flat, we expect the firing rate to decrease and neuron will spike more regularly. So as the OU process time constant increases, we expect firing rate and CV_ISI to decrease, if all other parameters are kept constant. We can also relate the OU process time constant to the membrane time constant as the neuron membrane does the same operation. This way we can link to the very first interactive demo. """; ``` --- ## Bonus Section 2: Generalized Integrate-and-Fire models LIF model is not the only abstraction of real neurons. If you want to learn about more realistic types of neuronal models, watch the Bonus Video! ```python # @title Video 3 (Bonus): Extensions to Integrate-and-Fire models from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = 'https://player.bilibili.com/player.html?bvid={0}&page={1}'.format(id, page) super(BiliVideo, self).__init__(src, width, height, **kwargs) video = BiliVideo(id="", width=854, height=480, fs=1) print('Video available at https://www.bilibili.com/video/{0}'.format(video.id)) display(video) out1 = widgets.Output() with out1: from IPython.display import YouTubeVideo video = YouTubeVideo(id="G0b6wLhuQxE", width=854, height=480, fs=1, rel=0) print('Video available at https://youtube.com/watch?v=' + video.id) display(video) out = widgets.Tab([out1, out2]) out.set_title(0, 'Youtube') out.set_title(1, 'Bilibili') display(out) ```
Formal statement is: lemma triangle_points_closer: fixes a::complex shows "\<lbrakk>x \<in> convex hull {a,b,c}; y \<in> convex hull {a,b,c}\<rbrakk> \<Longrightarrow> norm(x - y) \<le> norm(a - b) \<or> norm(x - y) \<le> norm(b - c) \<or> norm(x - y) \<le> norm(c - a)" Informal statement is: If $x$ and $y$ are points in the convex hull of $a$, $b$, and $c$, then the distance between $x$ and $y$ is less than or equal to the distance between any two of $a$, $b$, and $c$.
(** printing |-# %\vdash_{\#}% #&vdash;<sub>&#35;</sub># *) (** printing |-## %\vdash_{\#\#}% #&vdash;<sub>&#35&#35</sub># *) (** printing |-##v %\vdash_{\#\#v}% #&vdash;<sub>&#35&#35v</sub># *) (** printing |-! %\vdash_!% #&vdash;<sub>!</sub># *) (** remove printing ~ *) Set Implicit Arguments. Require Import ConstrLangAlt ConstrInterp ConstrEntailment Definitions Subenvironments RecordAndInertTypes. (** * Typing Rules *) Reserved Notation "e '⊢c' t ':' T" (at level 39, t at level 59). Reserved Notation "e '/-c' d : D" (at level 39, d at level 59). Reserved Notation "e '/-c' ds :: D" (at level 39, ds at level 59). Reserved Notation "e '⊢c' T '<:' U" (at level 39, T at level 59). (** ** Term typing [G ⊢c t: T] *) Inductive cty_trm : (constr * ctx) -> trm -> typ -> Prop := (** [G(x) = T] #<br># [――――――――] #<br># [C, G ⊢c x: T] *) | cty_var : forall C G x T, binds x T G -> (C, G) ⊢c trm_var (avar_f x) : T (** [C, (G, x: T) ⊢c t^x: U^x] #<br># [x fresh] #<br># [――――――――――――――――――――――] #<br># [C, G ⊢c lambda(T)t: forall(T)U] *) | cty_all_intro : forall L C G T t U, (forall x, x \notin L -> (C, G & x ~ T) ⊢c open_trm x t : open_typ x U) -> (C, G) ⊢c trm_val (val_lambda T t) : typ_all T U (** [C, G ⊢c x: forall(S)T] #<br># [C, G ⊢c z: S] #<br># [――――――――――――] #<br># [C, G ⊢c x z: T^z] *) | cty_all_elim : forall C G x z S T, (C, G) ⊢c trm_var (avar_f x) : typ_all S T -> (C, G) ⊢c trm_var (avar_f z) : S -> (C, G) ⊢c trm_app (avar_f x) (avar_f z) : open_typ z T (** [C, (G, x: T^x) ⊢ ds^x :: T^x] #<br># [x fresh] #<br># [―――――――――――――――――――――――] #<br># [C, G ⊢ nu(T)ds :: mu(T)] *) | cty_new_intro : forall L C G T ds, (forall x, x \notin L -> (C, G & (x ~ open_typ x T)) /-c open_defs x ds :: open_typ x T) -> (C, G) ⊢c trm_val (val_new T ds) : typ_bnd T (** [C, G ⊢c x: {a: T}] #<br># [―――――――――――――] #<br># [C, G ⊢c x.a: T] *) | cty_new_elim : forall C G x a T, (C, G) ⊢c trm_var (avar_f x) : typ_rcd (dec_trm a T) -> (C, G) ⊢c trm_sel (avar_f x) a : T (** [C, G ⊢c t: T] #<br># [C, G, x: T ⊢c u^x: U] #<br># [x fresh] #<br># [―――――――――――――――――] #<br># [C, G ⊢c let t in u: U] *) | cty_let : forall L C G t u T U, (C, G) ⊢c t : T -> (forall x, x \notin L -> (C, G & x ~ T) ⊢c open_trm x u : U) -> (C, G) ⊢c trm_let t u : U (** [C, G ⊢c x: T^x] #<br># [――――――――――――] #<br># [C, G ⊢c x: mu(T)] *) | cty_rec_intro : forall C G x T, (C, G) ⊢c trm_var (avar_f x) : open_typ x T -> (C, G) ⊢c trm_var (avar_f x) : typ_bnd T (** [C, G ⊢c x: mu(T)] #<br># [――――――――――――] #<br># [C, G ⊢c x: T^x] *) | cty_rec_elim : forall C G x T, (C, G) ⊢c trm_var (avar_f x) : typ_bnd T -> (C, G) ⊢c trm_var (avar_f x) : open_typ x T (** [C, G ⊢c x: T] #<br># [C, G ⊢c x: U] #<br># [――――――――――――] #<br># [C, G ⊢c x: T /\ U] *) | cty_and_intro : forall C G x T U, (C, G) ⊢c trm_var (avar_f x) : T -> (C, G) ⊢c trm_var (avar_f x) : U -> (C, G) ⊢c trm_var (avar_f x) : typ_and T U (** [C, G ⊢c t: T] #<br># [C ⊩ S <: T] #<br># [――――――――――] #<br># [C, G ⊢c t: U] *) | cty_sub : forall C G t T U, (C, G) ⊢c t : T -> (C, G) ⊢c T <: U -> (C, G) ⊢c t : U where "e '⊢c' t ':' T" := (cty_trm e t T) (** ** Single-definition typing [G ⊢ d: D] *) with cty_def : (constr * ctx) -> def -> dec -> Prop := (** [C, G ⊢c {A = T}: {A: T..T}] *) | cty_def_typ : forall C G A T, (C, G) /-c def_typ A T : dec_typ A T T (** [C, G ⊢c t: T] #<br># [―――――――――――――――――――] #<br># [C, G ⊢c {a = t}: {a: T}] *) | cty_def_trm : forall C G a t T, (C, G) ⊢c t : T -> (C, G) /-c def_trm a t : dec_trm a T where "e '/-c' d ':' D" := (cty_def e d D) (** ** Multiple-definition typing [G ⊢ ds :: T] *) with cty_defs : (constr * ctx) -> defs -> typ -> Prop := (** [C, G ⊢c d: D] #<br># [―――――――――――――――――――――] #<br># [C, G ⊢c d ++ defs_nil : D] *) | cty_defs_one : forall C G d D, (C, G) /-c d : D -> (C, G) /-c defs_cons defs_nil d :: typ_rcd D (** [C, G ⊢c ds :: T] #<br># [C, G ⊢c d: D] #<br># [d \notin ds] #<br># [―――――――――――――――――――] #<br># [C, G ⊢c ds ++ d : T /\ D] *) | cty_defs_cons : forall C G ds d T D, (C, G) /-c ds :: T -> (C, G) /-c d : D -> defs_hasnt ds (label_of_def d) -> (C, G) /-c defs_cons ds d :: typ_and T (typ_rcd D) where "e '/-c' ds '::' T" := (cty_defs e ds T) with csubtyp : (constr * ctx) -> typ -> typ -> Prop := (** [C, G ⊢c x: S] #<br># [C ⋏ x: S, G ⊢c T <: U] #<br># [――――――――――] #<br># [C, G ⊢c T <: U] *) | csubtyp_intro : forall C G x S S' T U, S ⩭ S' -> binds x S' G -> (C ⋏ ctrm_cvar (cvar_x (avar_f x)) ⦂ S, G) ⊢c T <: U -> (C, G) ⊢c T <: U (** [C ⊩ T <: U] #<br># [――――――――――] #<br># [C, G ⊢c T <: U] *) | csubtyp_inst : forall C G S S' T T', S ⩭ S' -> T ⩭ T' -> C ⊩ S <⦂ T -> (C, G) ⊢c S' <: T' where "e '⊢c' T '<:' U" := (csubtyp e T U). Hint Constructors cty_trm cty_def cty_defs csubtyp. Scheme cts_ty_trm_mut := Induction for cty_trm Sort Prop with cts_subtyp := Induction for csubtyp Sort Prop. Combined Scheme cts_mutind from cts_ty_trm_mut, cts_subtyp. Scheme crules_trm_mut := Induction for cty_trm Sort Prop with crules_def_mut := Induction for cty_def Sort Prop with crules_defs_mut := Induction for cty_defs Sort Prop with crules_subtyp := Induction for csubtyp Sort Prop. Combined Scheme crules_mutind from crules_trm_mut, crules_def_mut, crules_defs_mut, crules_subtyp. (** ** Well-typed programs *) Definition compatible_constr C G t T := exists tm vm, (tm, vm, G) ⊧ C /\ (C, G) ⊢c t: T. (* (** ⊤, (x: {A: {X: ⊥..T1}..{X: ⊥..T2}}, y: T1) ⊢c y: T2 *) *) (* Lemma typing_example1 : forall G x y A X T1 T2, *) (* binds x *) (* (typ_rcd *) (* (dec_typ A *) (* (typ_rcd (dec_typ X typ_bot T1)) *) (* (typ_rcd (dec_typ X typ_bot T2)))) *) (* G -> *) (* binds y T1 G -> *) (* ⊤, G ⊢c trm_var (avar_f y) : T2. *) (* Proof. *) (* introv Hx Hy. *) (* eapply ty_constr_intro with (t := trm_var (avar_f x)). *) (* - constructor*. *) (* - apply ty_sub with (T := T1). *) (* -- constructor*. *) (* -- eapply ent_trans. *) (* + apply ent_and_right. *) (* + eapply ent_trans. apply ent_exists_v_intro'. *) (* eapply ent_trans. apply ent_cong_exists_v. *) (* 2: { *) (* eapply ent_trans. *) (* eapply ent_bound_sub. *) (* eapply ent_trans. apply ent_and_right. *) (* eapply ent_trans. eapply ent_inv_subtyp_typ. *) (* apply ent_and_right. *) (* } *) (* simpl_open_constr. introv Heqc Heqd. subst C' D'. *) (* eapply ent_and_intro. apply ent_refl. *) (* Qed. *) (** [G ⊢ ds :: U] #<br># [U] is a record type with labels [ls] #<br># [ds] are definitions with label [ls'] #<br># [l \notin ls'] #<br># [―――――――――――――――――――――――――――――――――――] #<br># [l \notin ls] *) Lemma constr_hasnt_notin : forall C G ds ls l U, (C, G) /-c ds :: U -> record_typ U ls -> defs_hasnt ds l -> l \notin ls. Proof. Ltac inversion_def_typ := match goal with | [ H: _ /-c _ : _ |- _ ] => inversions H end. introv Hds Hrec Hhasnt. inversions Hhasnt. gen ds. induction Hrec; intros; inversions Hds. - inversion_def_typ; simpl in *; case_if; apply* notin_singleton. - apply notin_union; split; simpl in *. + apply* IHHrec. case_if*. + inversion_def_typ; case_if; apply* notin_singleton. Qed. (** The type of definitions is a record type. *) Lemma cty_defs_record_type : forall C G ds T, (C, G) /-c ds :: T -> record_type T. Proof. intros. induction H; destruct D; repeat match goal with | [ H: record_type _ |- _ ] => destruct H | [ Hd: _ /-c _ : dec_typ _ _ _ |- _ ] => inversions Hd | [ Hd: _ /-c _ : dec_trm _ _ |- _ ] => inversions Hd end; match goal with | [ ls: fset label, t: trm_label |- _ ] => exists (ls \u \{ label_trm t }) | [ ls: fset label, t: typ_label |- _ ] => exists (ls \u \{ label_typ t }) | [ t: trm_label |- _ ] => exists \{ label_trm t } | [ t: typ_label |- _ ] => exists \{ label_typ t } end; constructor*; try constructor; apply (constr_hasnt_notin H); eauto. Qed.
If $f$ is a function that converges to $l$ and $l$ is not an integer, then for all sufficiently large $x$, the ceiling of $f(x)$ is equal to the ceiling of $l$.
import tactic import graph_theory.minor graph_theory.product analysis.complex.basic namespace simple_graph def Z : simple_graph ℤ := { adj := λ x y, |x-y| = 1, symm := λ x y h, by { rw ←h, convert abs_neg _, ring }, loopless := λ x, by simp only [sub_self, abs_zero, zero_ne_one, not_false_iff] } variables {V V' : Type*} {G : simple_graph V} {G' : simple_graph V'} def plane : simple_graph (ℤ × ℤ) := Z □ Z namespace plane variables {x x' y y' z z' : ℤ} open walk def flip : plane →g plane := { to_fun := prod.swap, map_rel' := by { rintros ⟨x,y⟩ ⟨x',y'⟩ h, cases h, { right, exact and.symm h }, { left, exact and.symm h } } } lemma horiz_path_aux : ∀ (n : ℕ), reachable plane (x,y) (x+n,y) | 0 := by simp | (n+1) := by { refine reachable.trans (horiz_path_aux n) (reachable.step (or.inr _)), simp [Z] } lemma horiz_path : reachable plane (x,y) (x',y) := begin by_cases (x'-x>=0), { obtain ⟨n,hn⟩ := int.eq_coe_of_zero_le h, convert horiz_path_aux n, linarith }, { replace h : x-x' ≥ 0, by linarith, obtain ⟨n,hn⟩ := int.eq_coe_of_zero_le h, symmetry, convert (@horiz_path_aux x' y n), linarith } end lemma vert_path : reachable plane (x,y) (x,y') := by { obtain ⟨p⟩ := horiz_path, use p.map flip } lemma connected_plane : connected plane := ⟨λ ⟨x,y⟩ ⟨x',y'⟩, reachable.trans horiz_path vert_path, ⟨(0,0)⟩⟩ end plane def K5 := complete_graph (finset.range 5) def K33 := complete_bipartite_graph (finset.range 3) (finset.range 3) -- theorem kuratowski [fintype V] : G ≼ plane ↔ K5 ⋠ G ∧ K33 ⋠ G end simple_graph
-- @@stderr -- dtrace: failed to open wassup: No such file or directory
```python import numpy as np import matplotlib.pyplot as plt import scipy from sklearn.model_selection import ParameterGrid from sklearn.manifold import Isomap import time from tqdm import tqdm import librosa from librosa import cqt from librosa.core import amplitude_to_db from librosa.display import specshow import os import glob ``` ```python hop_size= 512 q= 24 ``` ```python import h5py with h5py.File("NTVow.h5", "r") as f: features_dict = {key:f[key][()] for key in f.keys()} ``` ```python len(list(features_dict.keys())) ``` 3190 ```python grid = { 'Q': [24], 'k': [3], 'comp': ['log'], 'instr': ['all'], 'dyn': ['all'] } settings = list(ParameterGrid(grid)) for setting in settings: if setting["instr"] == 'all': setting['instr'] = '' if setting['dyn'] == 'all': setting['dyn'] = '' ``` ```python batch_str = [] CQT_OCTAVES = 7 features_keys = list(features_dict.keys()) for setting in settings: q = setting['Q'] # Batch process and store in a folder batch_str = [setting['instr'], setting['dyn']] batch_features = [] for feature_key in features_keys: # Get features that match setting if all(x in feature_key for x in batch_str): batch_features.append(features_dict[feature_key]) batch_features = np.stack(batch_features, axis=1) # Isomap parameters hop_size = 512 compression = 'log' features = amplitude_to_db(batch_features) n_neighbors = setting['k'] n_dimensions = 3 n_octaves = 3 # Prune feature matrix bin_low = np.where((np.std(features, axis=1) / np.std(features)) > 0.1)[0][0] + q bin_high = bin_low + n_octaves*q X = features[bin_low:bin_high, :] # Z-score Standardization- improves contrast in correlation matrix mus = np.mean(X, axis=1) sigmas = np.std(X, axis=1) X_std = (X - mus[:, np.newaxis]) / (1e-6 + sigmas[:, np.newaxis]) # 1e-6 to avoid runtime division by zero # Pearson correlation matrix rho_std = np.dot(X_std, X_std.T) / X_std.shape[1] # Isomap embedding isomap = Isomap(n_components= n_dimensions, n_neighbors= n_neighbors) coords = isomap.fit_transform(rho_std) # Get note value freqs= librosa.cqt_frequencies(q*CQT_OCTAVES, fmin=librosa.note_to_hz('C1'), bins_per_octave=q) #librosa CQT default fmin is C1 chroma_list= librosa.core.hz_to_note(freqs[bin_low:bin_high]) notes = [] reps = q//12 for chroma in chroma_list: for i in range(reps): notes.append(chroma) ``` ```python curr_fig= plt.figure(figsize=(5.5, 2.75)) ax= curr_fig.add_subplot(121) ax.axis('off') import colorcet as cc subsampled_color_ids = np.floor(np.linspace(0, 256, q, endpoint=False)).astype('int') color_list= [cc.cyclic_mygbm_30_95_c78[i] for i in subsampled_color_ids] # Plot embedding with color for i in range(coords.shape[0]): plt.scatter(coords[i, 0], coords[i, 1], color= color_list[i%q], s=30.0) plt.plot(coords[:, 0], coords[:, 1], color='black', linewidth=0.2) # Plot Pearson correlation matrix rho_frequencies = freqs[bin_low:bin_high] freq_ticklabels = ['A2', 'A3', 'A4'] freq_ticks = librosa.core.note_to_hz(freq_ticklabels) tick_bins = [] tick_labels= [] for i,freq_tick in enumerate(freq_ticks): tick_bin = np.argmin(np.abs(rho_frequencies-freq_tick)) tick_bins.append(tick_bin) tick_labels.append(freq_ticklabels[i]) plt.figure(figsize=(2.5,2.5)) plt.imshow(np.abs(rho_std), cmap='magma_r') plt.xticks(tick_bins) plt.gca().set_xticklabels(freq_ticklabels) # plt.xlabel('Log-frequency (octaves)') plt.yticks(tick_bins) plt.gca().set_yticklabels(freq_ticklabels) # plt.ylabel('Log-frequency (octaves)') plt.gca().invert_yaxis() plt.clim(0, 1) ``` ```python import circle_fit import importlib importlib.reload(circle_fit) from circle_fit import circle_fit A = np.transpose(coords[:,:-1]) x, r, circle_residual = circle_fit(A, verbose=True) ``` ```python import matplotlib matplotlib.rc('font', family='serif') fig, axes = plt.subplots() plt.scatter(A[0,:],A[1,:]) plt.plot(x[0],x[1],'rx') circle = plt.Circle(x, radius=r, fill=False, linestyle='-.') axes.set_aspect(1) axes.add_artist(circle) # axes.set_ylim([-5,6]) # axes.set_xlim([-2,8]) plt.title('Circle fit: TinySOL all instr', pad=10.0) plt.show() print(np.sqrt(circle_residual)/72) ``` ```python def d_squared(a, b): # Takes two n-D tuples and returns euclidean distance between them # Cast to array for computation # Cast first to tuple in case a or b are Sympy Point objects p_a = np.array(tuple(a), dtype='float') p_b = np.array(tuple(b), dtype='float') return np.sum(np.square(p_a - p_b)) ``` ```python import sympy from sympy.geometry import Circle, Point, Line center = Point(x, evaluate=False) c = Circle(center, r, evaluate=False) l = Line(Point(coords[0,:-1]), center, evaluate=False) points = [tuple(p) for p in l.points] xy_prime = [] # TODO: Optimize to a more pythonic manner for x,y in coords[:,:2]: intersections = c.intersection(Line(Point(x,y), center, evaluate=False)) if d_squared((x,y),intersections[0]) < d_squared((x,y), intersections[1]): xy_prime.append([float(p) for p in intersections[0]]) else: xy_prime.append([float(p) for p in intersections[1]]) ``` ```python fig, axes = plt.subplots() plt.scatter(np.array(xy_prime)[:,0],np.array(xy_prime)[:,1], s=10, label='projected points') plt.scatter(A[0,:],A[1,:], s=0.5, label='isomap embedding points (2D)') plt.plot(center[0],center[1],'rx') circle = plt.Circle([float(p) for p in center], radius=r, fill=False, linestyle='--', label='estimated circle fit') axes.set_aspect(1) axes.add_artist(circle) plt.title('Projected points on circle', pad=10.0) plt.legend(bbox_to_anchor=(1,1)) plt.show() ``` ```python z = np.arange(len(coords[:,2])) z_fit = scipy.stats.linregress(z, coords[:,2]) print(z_fit.stderr) ``` 0.015001619033788483 ```python plt.figure() plt.title('Line fit: TinySOL all instr') plt.scatter(np.arange(len(coords[:,2])), coords[:,2]) plt.plot(z_fit.intercept + z_fit.slope*z, 'b') ``` ```python # New line coordinates z_prime = [i * z_fit.slope + z_fit.intercept for i,_ in enumerate(coords[:,2])] ``` ```python coords_prime = np.append(np.array(xy_prime), np.expand_dims(np.array(z_prime), axis=1), axis=1) coords_length = coords_prime.shape[0] ``` ```python # Projected helix self-distance matrix D_proj = np.zeros((coords_length, coords_length)) for i in range(coords_length): for j in range(i,coords_length): D_proj[i][j] = d_squared(coords_prime[i,:], coords_prime[j,:]) # Isomap embedding self-distance matrix D_isomap = np.zeros((coords_length, coords_length)) # Projected points same no. as isomap for i in range(coords_length): for j in range(i, coords_length): D_isomap[i][j] = d_squared(coords[i,:], coords[j,:]) # Geodesic self-distance matrix D_geodesic = isomap.dist_matrix_ # Convert to upper triangular sparse matrix for i in range(coords_length): for j in range(i): D_geodesic[i,j] = 0 ``` ```python ## Centering matrix def centered(A, Q=24, J=3): # Returns centered distance matrix ''' Inputs ----- A - squared distance matrix Q - quality factor, 24 by default J - number of octaves, 3 by default Returns ----- tau - MDS style diagonalized matrix of A ''' coords_length = A.shape[0] H = np.zeros((coords_length, coords_length)) const = 1/(Q*J) for i in range(coords_length): for j in range(coords_length): if j==i: H[i,j] = 1 - const else: H[i,j] = -const return -0.5 * np.matmul(np.matmul(H, A), H) ``` ```python def frobenius_distance(A, B): # Given two nxn matrices, return their 'Frobenius distance' return np.sqrt(np.sum(np.square(A - B))) ``` ```python loss_isomap = frobenius_distance(centered(D_geodesic), centered(D_isomap))/coords_length loss_total = frobenius_distance(centered(D_geodesic), centered(D_proj))/coords_length loss_proj = frobenius_distance(centered(D_isomap), centered(D_proj))/coords_length print(f"Isomap loss= {loss_isomap}") print(f"Projection loss= {loss_proj}") print(f"Total loss= {loss_total}") ``` Isomap loss= 16.262512975570516 Projection loss= 8.432097710558947 Total loss= 15.011785144620099 ```python (loss_total) - (loss_isomap + loss_proj) < 0 ``` True
#include <bacs/problem/error.hpp> #include <bacs/problem/statement.hpp> #include <boost/filesystem/path.hpp> #include <string> namespace bacs::problem::statement_versions { struct copy_error : virtual error {}; struct invalid_source_name_error : virtual copy_error { using source_name = boost::error_info<struct tag_source_name, boost::filesystem::path>; }; class copy : public statement::version { public: copy(const boost::filesystem::path &location, const boost::property_tree::ptree &config); void make_package(const boost::filesystem::path &destination, const bunsan::pm::entry &package, const bunsan::pm::entry &resources_package, const Revision &revision) const override; private: const boost::filesystem::path m_source; }; } // namespace bacs::problem::statement_versions
lemma Fract_conv_to_fract: "Fract a b = to_fract a / to_fract b"
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.natural_isomorphism import Mathlib.category_theory.eq_to_hom import Mathlib.data.sigma.basic import Mathlib.category_theory.pi.basic import Mathlib.PostPort universes w₁ v₁ u₁ l u₂ v₂ w₂ w₃ namespace Mathlib /-! # Disjoint union of categories We define the category structure on a sigma-type (disjoint union) of categories. -/ namespace category_theory namespace sigma /-- The type of morphisms of a disjoint union of categories: for `X : C i` and `Y : C j`, a morphism `(i, X) ⟶ (j, Y)` if `i = j` is just a morphism `X ⟶ Y`, and if `i ≠ j` there are no such morphisms. -/ inductive sigma_hom {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] : (sigma fun (i : I) => C i) → (sigma fun (i : I) => C i) → Type (max w₁ v₁ u₁) where | mk : {i : I} → {X Y : C i} → (X ⟶ Y) → sigma_hom (sigma.mk i X) (sigma.mk i Y) namespace sigma_hom /-- The identity morphism on an object. -/ def id {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] (X : sigma fun (i : I) => C i) : sigma_hom X X := sorry protected instance inhabited {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] (X : sigma fun (i : I) => C i) : Inhabited (sigma_hom X X) := { default := id X } /-- Composition of sigma homomorphisms. -/ def comp {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] {X : sigma fun (i : I) => C i} {Y : sigma fun (i : I) => C i} {Z : sigma fun (i : I) => C i} : sigma_hom X Y → sigma_hom Y Z → sigma_hom X Z := sorry protected instance sigma.category_theory.category_struct {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] : category_struct (sigma fun (i : I) => C i) := category_struct.mk id fun (X Y Z : sigma fun (i : I) => C i) (f : X ⟶ Y) (g : Y ⟶ Z) => comp f g @[simp] theorem comp_def {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] (i : I) (X : C i) (Y : C i) (Z : C i) (f : X ⟶ Y) (g : Y ⟶ Z) : comp (mk f) (mk g) = mk (f ≫ g) := rfl theorem assoc {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] (X : sigma fun (i : I) => C i) (Y : sigma fun (i : I) => C i) (Z : sigma fun (i : I) => C i) (W : sigma fun (i : I) => C i) (f : X ⟶ Y) (g : Y ⟶ Z) (h : Z ⟶ W) : (f ≫ g) ≫ h = f ≫ g ≫ h := sorry theorem id_comp {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] (X : sigma fun (i : I) => C i) (Y : sigma fun (i : I) => C i) (f : X ⟶ Y) : 𝟙 ≫ f = f := sorry theorem comp_id {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] (X : sigma fun (i : I) => C i) (Y : sigma fun (i : I) => C i) (f : X ⟶ Y) : f ≫ 𝟙 = f := sorry end sigma_hom protected instance sigma {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] : category (sigma fun (i : I) => C i) := category.mk /-- The inclusion functor into the disjoint union of categories. -/ @[simp] theorem incl_map {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] (i : I) (X : C i) (Y : C i) : ∀ (ᾰ : X ⟶ Y), functor.map (incl i) ᾰ = sigma_hom.mk ᾰ := fun (ᾰ : X ⟶ Y) => Eq.refl (functor.map (incl i) ᾰ) @[simp] theorem incl_obj {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] {i : I} (X : C i) : functor.obj (incl i) X = sigma.mk i X := rfl protected instance incl.category_theory.full {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] (i : I) : full (incl i) := full.mk fun (X Y : C i) (_x : functor.obj (incl i) X ⟶ functor.obj (incl i) Y) => sorry protected instance incl.category_theory.faithful {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] (i : I) : faithful (incl i) := faithful.mk /-- To build a natural transformation over the sigma category, it suffices to specify it restricted to each subcategory. -/ def nat_trans {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] {D : Type u₂} [category D] {F : (sigma fun (i : I) => C i) ⥤ D} {G : (sigma fun (i : I) => C i) ⥤ D} (h : (i : I) → incl i ⋙ F ⟶ incl i ⋙ G) : F ⟶ G := nat_trans.mk fun (_x : sigma fun (i : I) => C i) => sorry @[simp] theorem nat_trans_app {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] {D : Type u₂} [category D] {F : (sigma fun (i : I) => C i) ⥤ D} {G : (sigma fun (i : I) => C i) ⥤ D} (h : (i : I) → incl i ⋙ F ⟶ incl i ⋙ G) (i : I) (X : C i) : nat_trans.app (nat_trans h) (sigma.mk i X) = nat_trans.app (h i) X := rfl /-- (Implementation). An auxiliary definition to build the functor `desc`. -/ def desc_map {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] {D : Type u₂} [category D] (F : (i : I) → C i ⥤ D) (X : sigma fun (i : I) => C i) (Y : sigma fun (i : I) => C i) : (X ⟶ Y) → (functor.obj (F (sigma.fst X)) (sigma.snd X) ⟶ functor.obj (F (sigma.fst Y)) (sigma.snd Y)) := sorry /-- Given a collection of functors `F i : C i ⥤ D`, we can produce a functor `(Σ i, C i) ⥤ D`. The produced functor `desc F` satisfies: `incl i ⋙ desc F ≅ F i`, i.e. restricted to just the subcategory `C i`, `desc F` agrees with `F i`, and it is unique (up to natural isomorphism) with this property. This witnesses that the sigma-type is the coproduct in Cat. -/ @[simp] theorem desc_obj {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] {D : Type u₂} [category D] (F : (i : I) → C i ⥤ D) (X : sigma fun (i : I) => C i) : functor.obj (desc F) X = functor.obj (F (sigma.fst X)) (sigma.snd X) := Eq.refl (functor.obj (desc F) X) @[simp] theorem desc_map_mk {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] {D : Type u₂} [category D] (F : (i : I) → C i ⥤ D) {i : I} (X : C i) (Y : C i) (f : X ⟶ Y) : functor.map (desc F) (sigma_hom.mk f) = functor.map (F i) f := rfl /-- This shows that when `desc F` is restricted to just the subcategory `C i`, `desc F` agrees with `F i`. -/ -- We hand-generate the simp lemmas about this since they come out cleaner. def incl_desc {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] {D : Type u₂} [category D] (F : (i : I) → C i ⥤ D) (i : I) : incl i ⋙ desc F ≅ F i := nat_iso.of_components (fun (X : C i) => iso.refl (functor.obj (incl i ⋙ desc F) X)) sorry @[simp] theorem incl_desc_hom_app {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] {D : Type u₂} [category D] (F : (i : I) → C i ⥤ D) (i : I) (X : C i) : nat_trans.app (iso.hom (incl_desc F i)) X = 𝟙 := rfl @[simp] theorem incl_desc_inv_app {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] {D : Type u₂} [category D] (F : (i : I) → C i ⥤ D) (i : I) (X : C i) : nat_trans.app (iso.inv (incl_desc F i)) X = 𝟙 := rfl /-- If `q` when restricted to each subcategory `C i` agrees with `F i`, then `q` is isomorphic to `desc F`. -/ def desc_uniq {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] {D : Type u₂} [category D] (F : (i : I) → C i ⥤ D) (q : (sigma fun (i : I) => C i) ⥤ D) (h : (i : I) → incl i ⋙ q ≅ F i) : q ≅ desc F := nat_iso.of_components (fun (_x : sigma fun (i : I) => C i) => sorry) sorry @[simp] theorem desc_uniq_hom_app {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] {D : Type u₂} [category D] (F : (i : I) → C i ⥤ D) (q : (sigma fun (i : I) => C i) ⥤ D) (h : (i : I) → incl i ⋙ q ≅ F i) (i : I) (X : C i) : nat_trans.app (iso.hom (desc_uniq F q h)) (sigma.mk i X) = nat_trans.app (iso.hom (h i)) X := rfl @[simp] theorem desc_uniq_inv_app {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] {D : Type u₂} [category D] (F : (i : I) → C i ⥤ D) (q : (sigma fun (i : I) => C i) ⥤ D) (h : (i : I) → incl i ⋙ q ≅ F i) (i : I) (X : C i) : nat_trans.app (iso.inv (desc_uniq F q h)) (sigma.mk i X) = nat_trans.app (iso.inv (h i)) X := rfl /-- If `q₁` and `q₂` when restricted to each subcategory `C i` agree, then `q₁` and `q₂` are isomorphic. -/ @[simp] theorem nat_iso_inv {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] {D : Type u₂} [category D] {q₁ : (sigma fun (i : I) => C i) ⥤ D} {q₂ : (sigma fun (i : I) => C i) ⥤ D} (h : (i : I) → incl i ⋙ q₁ ≅ incl i ⋙ q₂) : iso.inv (nat_iso h) = nat_trans fun (i : I) => iso.inv (h i) := Eq.refl (iso.inv (nat_iso h)) /-- A function `J → I` induces a functor `Σ j, C (g j) ⥤ Σ i, C i`. -/ def map {I : Type w₁} (C : I → Type u₁) [(i : I) → category (C i)] {J : Type w₂} (g : J → I) : (sigma fun (j : J) => C (g j)) ⥤ sigma fun (i : I) => C i := desc fun (j : J) => incl (g j) @[simp] theorem map_obj {I : Type w₁} (C : I → Type u₁) [(i : I) → category (C i)] {J : Type w₂} (g : J → I) (j : J) (X : C (g j)) : functor.obj (map C g) (sigma.mk j X) = sigma.mk (g j) X := rfl @[simp] theorem map_map {I : Type w₁} (C : I → Type u₁) [(i : I) → category (C i)] {J : Type w₂} (g : J → I) {j : J} {X : C (g j)} {Y : C (g j)} (f : X ⟶ Y) : functor.map (map C g) (sigma_hom.mk f) = sigma_hom.mk f := rfl /-- The functor `sigma.map C g` restricted to the subcategory `C j` acts as the inclusion of `g j`. -/ @[simp] theorem incl_comp_map_hom_app {I : Type w₁} (C : I → Type u₁) [(i : I) → category (C i)] {J : Type w₂} (g : J → I) (j : J) (X : C (g j)) : nat_trans.app (iso.hom (incl_comp_map C g j)) X = 𝟙 := Eq.refl 𝟙 /-- The functor `sigma.map` applied to the identity function is just the identity functor. -/ @[simp] theorem map_id_hom_app (I : Type w₁) (C : I → Type u₁) [(i : I) → category (C i)] (_x : sigma fun (i : I) => (fun (i : I) => (fun (i : I) => C (id i)) i) i) : nat_trans.app (iso.hom (map_id I C)) _x = nat_trans._match_1 (fun (i : I) => iso.hom (nat_iso.of_components (fun (X : C i) => iso.refl (sigma.mk i X)) (map_id._proof_1 I C i))) _x := sorry /-- The functor `sigma.map` applied to a composition is a composition of functors. -/ @[simp] theorem map_comp_hom_app {I : Type w₁} (C : I → Type u₁) [(i : I) → category (C i)] {J : Type w₂} {K : Type w₃} (f : K → J) (g : J → I) (X : sigma fun (i : K) => (fun (j : K) => function.comp C g (f j)) i) : nat_trans.app (iso.hom (map_comp C f g)) X = iso.hom (desc_uniq._match_1 (fun (j : K) => incl (g (f j))) (map (C ∘ g) f ⋙ map C g) (fun (k : K) => iso_whisker_right (incl_comp_map (C ∘ g) f k) (map C g) ≪≫ incl_comp_map C g (f k)) X) := sorry namespace functor /-- Assemble an `I`-indexed family of functors into a functor between the sigma types. -/ def sigma {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] {D : I → Type u₁} [(i : I) → category (D i)] (F : (i : I) → C i ⥤ D i) : (sigma fun (i : I) => C i) ⥤ sigma fun (i : I) => D i := desc fun (i : I) => F i ⋙ incl i end functor namespace nat_trans /-- Assemble an `I`-indexed family of natural transformations into a single natural transformation. -/ def sigma {I : Type w₁} {C : I → Type u₁} [(i : I) → category (C i)] {D : I → Type u₁} [(i : I) → category (D i)] {F : (i : I) → C i ⥤ D i} {G : (i : I) → C i ⥤ D i} (α : (i : I) → F i ⟶ G i) : functor.sigma F ⟶ functor.sigma G := nat_trans.mk fun (f : sigma fun (i : I) => C i) => sigma_hom.mk (nat_trans.app (α (sigma.fst f)) (sigma.snd f))
#name: RCaretNBApply #meta.mlname: RCaretNB #meta.mlrole: apply #description: Custom R Apply func for Naive Bayes using Caret #language: r #input: blob model #input: dataframe df #input: string namesKeys #input: string namesValues #output: dataframe data_out renv::init() install.packages("naivebayes") library(naivebayes) #>>> If original(namesKeys) and new(namesValues) passed, map original names to new namesKeys = strsplit(namesKeys, ',')[[1]] namesValues = strsplit(namesValues, ',')[[1]] if (length(namesKeys) > 0) { featuresNames = names(df) for (n in 0:length(namesKeys)) names(df)[featuresNames == namesValues[n]] = namesKeys[n] } #>>> Retrieve saved/trained model trained_model = readRDS(model) #>>> Predict using trained model predY = predict(trained_model, df) data_out = data.frame(predY)
[STATEMENT] lemma emeasure_positive: "positive (sets M) (emeasure M)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. positive (sets M) (emeasure M) [PROOF STEP] by (cases M) (auto simp: sets_def emeasure_def Abs_measure_inverse measure_space_def)
lemma open_dist: "open S \<longleftrightarrow> (\<forall>x\<in>S. \<exists>e>0. \<forall>y. dist y x < e \<longrightarrow> y \<in> S)"
(* *********************************************************************) (* *) (* The Compcert verified compiler *) (* *) (* Xavier Leroy, INRIA Paris-Rocquencourt *) (* *) (* Copyright Institut National de Recherche en Informatique et en *) (* Automatique. All rights reserved. This file is distributed *) (* 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 file is also distributed *) (* under the terms of the INRIA Non-Commercial License Agreement. *) (* *) (* *********************************************************************) (** Multi-way branches (``switch'' statements) and their compilation to comparison trees. *) Require Import EqNat. Require Import Coqlib. Require Import Maps. Require Import Integers. Module IntIndexed <: INDEXED_TYPE. Definition t := int. Definition index (n: int) : positive := match Int.unsigned n with | Z0 => xH | Zpos p => xO p | Zneg p => xI p (**r never happens *) end. Lemma index_inj: forall n m, index n = index m -> n = m. Proof. unfold index; intros. rewrite <- (Int.repr_unsigned n). rewrite <- (Int.repr_unsigned m). f_equal. destruct (Int.unsigned n); destruct (Int.unsigned m); congruence. Qed. Definition eq := Int.eq_dec. End IntIndexed. Module IntMap := IMap(IntIndexed). (** A multi-way branch is composed of a list of (key, action) pairs, plus a default action. *) Definition table : Type := list (int * nat). Fixpoint switch_target (n: int) (dfl: nat) (cases: table) {struct cases} : nat := match cases with | nil => dfl | (key, action) :: rem => if Int.eq n key then action else switch_target n dfl rem end. (** Multi-way branches are translated to comparison trees. Each node of the tree performs either - an equality against one of the keys; - or a "less than" test against one of the keys; - or a computed branch (jump table) against a range of key values. *) Inductive comptree : Type := | CTaction: nat -> comptree | CTifeq: int -> nat -> comptree -> comptree | CTiflt: int -> comptree -> comptree -> comptree | CTjumptable: int -> int -> list nat -> comptree -> comptree. Fixpoint comptree_match (n: int) (t: comptree) {struct t}: option nat := match t with | CTaction act => Some act | CTifeq key act t' => if Int.eq n key then Some act else comptree_match n t' | CTiflt key t1 t2 => if Int.ltu n key then comptree_match n t1 else comptree_match n t2 | CTjumptable ofs sz tbl t' => if Int.ltu (Int.sub n ofs) sz then list_nth_z tbl (Int.unsigned (Int.sub n ofs)) else comptree_match n t' end. (** The translation from a table to a comparison tree is performed by untrusted Caml code (function [compile_switch] in file [RTLgenaux.ml]). In Coq, we validate a posteriori the result of this function. In other terms, we now develop and prove correct Coq functions that take a table and a comparison tree, and check that their semantics are equivalent. *) Fixpoint split_lt (pivot: int) (cases: table) {struct cases} : table * table := match cases with | nil => (nil, nil) | (key, act) :: rem => let (l, r) := split_lt pivot rem in if Int.ltu key pivot then ((key, act) :: l, r) else (l, (key, act) :: r) end. Fixpoint split_eq (pivot: int) (cases: table) {struct cases} : option nat * table := match cases with | nil => (None, nil) | (key, act) :: rem => let (same, others) := split_eq pivot rem in if Int.eq key pivot then (Some act, others) else (same, (key, act) :: others) end. Fixpoint split_between (dfl: nat) (ofs sz: int) (cases: table) {struct cases} : IntMap.t nat * table := match cases with | nil => (IntMap.init dfl, nil) | (key, act) :: rem => let (inside, outside) := split_between dfl ofs sz rem in if Int.ltu (Int.sub key ofs) sz then (IntMap.set key act inside, outside) else (inside, (key, act) :: outside) end. Definition refine_low_bound (v lo: Z) := if zeq v lo then lo + 1 else lo. Definition refine_high_bound (v hi: Z) := if zeq v hi then hi - 1 else hi. Fixpoint validate_jumptable (cases: IntMap.t nat) (tbl: list nat) (n: int) {struct tbl} : bool := match tbl with | nil => true | act :: rem => beq_nat act (IntMap.get n cases) && validate_jumptable cases rem (Int.add n Int.one) end. Fixpoint validate (default: nat) (cases: table) (t: comptree) (lo hi: Z) {struct t} : bool := match t with | CTaction act => match cases with | nil => beq_nat act default | (key1, act1) :: _ => zeq (Int.unsigned key1) lo && zeq lo hi && beq_nat act act1 end | CTifeq pivot act t' => match split_eq pivot cases with | (None, _) => false | (Some act', others) => beq_nat act act' && validate default others t' (refine_low_bound (Int.unsigned pivot) lo) (refine_high_bound (Int.unsigned pivot) hi) end | CTiflt pivot t1 t2 => match split_lt pivot cases with | (lcases, rcases) => validate default lcases t1 lo (Int.unsigned pivot - 1) && validate default rcases t2 (Int.unsigned pivot) hi end | CTjumptable ofs sz tbl t' => let tbl_len := list_length_z tbl in match split_between default ofs sz cases with | (inside, outside) => zle (Int.unsigned sz) tbl_len && zle tbl_len Int.max_signed && validate_jumptable inside tbl ofs && validate default outside t' lo hi end end. Definition validate_switch (default: nat) (cases: table) (t: comptree) := validate default cases t 0 Int.max_unsigned. (** Correctness proof for validation. *) Lemma split_eq_prop: forall v default n cases optact cases', split_eq n cases = (optact, cases') -> switch_target v default cases = (if Int.eq v n then match optact with Some act => act | None => default end else switch_target v default cases'). Proof. induction cases; simpl; intros until cases'. intros. inversion H; subst. simpl. destruct (Int.eq v n); auto. destruct a as [key act]. case_eq (split_eq n cases). intros same other SEQ. rewrite (IHcases _ _ SEQ). predSpec Int.eq Int.eq_spec key n; intro EQ; inversion EQ; simpl. subst n. destruct (Int.eq v key). auto. auto. predSpec Int.eq Int.eq_spec v key. subst v. predSpec Int.eq Int.eq_spec key n. congruence. auto. auto. Qed. Lemma split_lt_prop: forall v default n cases lcases rcases, split_lt n cases = (lcases, rcases) -> switch_target v default cases = (if Int.ltu v n then switch_target v default lcases else switch_target v default rcases). Proof. induction cases; intros until rcases; simpl. intro. inversion H; subst. simpl. destruct (Int.ltu v n); auto. destruct a as [key act]. case_eq (split_lt n cases). intros lc rc SEQ. rewrite (IHcases _ _ SEQ). case_eq (Int.ltu key n); intros; inv H0; simpl. predSpec Int.eq Int.eq_spec v key. subst v. rewrite H. auto. auto. predSpec Int.eq Int.eq_spec v key. subst v. rewrite H. auto. auto. Qed. Lemma split_between_prop: forall v default ofs sz cases inside outside, split_between default ofs sz cases = (inside, outside) -> switch_target v default cases = (if Int.ltu (Int.sub v ofs) sz then IntMap.get v inside else switch_target v default outside). Proof. induction cases; intros until outside; simpl; intros SEQ. - inv SEQ. destruct (Int.ltu (Int.sub v ofs) sz); auto. rewrite IntMap.gi. auto. - destruct a as [key act]. destruct (split_between default ofs sz cases) as [ins outs]. erewrite IHcases; eauto. destruct (Int.ltu (Int.sub key ofs) sz) eqn:LT; inv SEQ. + predSpec Int.eq Int.eq_spec v key. subst v. rewrite LT. rewrite IntMap.gss. auto. destruct (Int.ltu (Int.sub v ofs) sz). rewrite IntMap.gso; auto. auto. + simpl. destruct (Int.ltu (Int.sub v ofs) sz) eqn:LT'. rewrite Int.eq_false. auto. congruence. auto. Qed. Lemma validate_jumptable_correct_rec: forall cases tbl base v, validate_jumptable cases tbl base = true -> 0 <= Int.unsigned v < list_length_z tbl -> list_nth_z tbl (Int.unsigned v) = Some(IntMap.get (Int.add base v) cases). Proof. induction tbl; intros until v; simpl. unfold list_length_z; simpl. intros. omegaContradiction. rewrite list_length_z_cons. intros. destruct (andb_prop _ _ H). clear H. generalize (beq_nat_eq _ _ (sym_equal H1)). clear H1. intro. subst a. destruct (zeq (Int.unsigned v) 0). unfold Int.add. rewrite e. rewrite Zplus_0_r. rewrite Int.repr_unsigned. auto. assert (Int.unsigned (Int.sub v Int.one) = Int.unsigned v - 1). unfold Int.sub. change (Int.unsigned Int.one) with 1. apply Int.unsigned_repr. split. omega. generalize (Int.unsigned_range_2 v). omega. replace (Int.add base v) with (Int.add (Int.add base Int.one) (Int.sub v Int.one)). rewrite <- IHtbl. rewrite H. auto. auto. rewrite H. omega. rewrite Int.sub_add_opp. rewrite Int.add_permut. rewrite Int.add_assoc. replace (Int.add Int.one (Int.neg Int.one)) with Int.zero. rewrite Int.add_zero. apply Int.add_commut. rewrite Int.add_neg_zero; auto. Qed. Lemma validate_jumptable_correct: forall cases tbl ofs v sz, validate_jumptable cases tbl ofs = true -> Int.ltu (Int.sub v ofs) sz = true -> Int.unsigned sz <= list_length_z tbl -> list_nth_z tbl (Int.unsigned (Int.sub v ofs)) = Some(IntMap.get v cases). Proof. intros. exploit Int.ltu_inv; eauto. intros. rewrite (validate_jumptable_correct_rec cases tbl ofs). rewrite Int.sub_add_opp. rewrite Int.add_permut. rewrite <- Int.sub_add_opp. rewrite Int.sub_idem. rewrite Int.add_zero. auto. auto. omega. Qed. Lemma validate_correct_rec: forall default v t cases lo hi, validate default cases t lo hi = true -> lo <= Int.unsigned v <= hi -> comptree_match v t = Some (switch_target v default cases). Proof. Opaque Int.sub. induction t; simpl; intros until hi. (* base case *) destruct cases as [ | [key1 act1] cases1]; intros. replace n with default. reflexivity. symmetry. apply beq_nat_eq. auto. destruct (andb_prop _ _ H). destruct (andb_prop _ _ H1). clear H H1. assert (Int.unsigned key1 = lo). eapply proj_sumbool_true; eauto. assert (lo = hi). eapply proj_sumbool_true; eauto. assert (Int.unsigned v = Int.unsigned key1). omega. replace n with act1. simpl. unfold Int.eq. rewrite H5. rewrite zeq_true. auto. symmetry. apply beq_nat_eq. auto. (* eq node *) case_eq (split_eq i cases). intros optact cases' EQ. destruct optact as [ act | ]. 2: congruence. intros. destruct (andb_prop _ _ H). clear H. rewrite (split_eq_prop v default _ _ _ _ EQ). predSpec Int.eq Int.eq_spec v i. f_equal. apply beq_nat_eq; auto. eapply IHt. eauto. assert (Int.unsigned v <> Int.unsigned i). rewrite <- (Int.repr_unsigned v) in H. rewrite <- (Int.repr_unsigned i) in H. congruence. split. unfold refine_low_bound. destruct (zeq (Int.unsigned i) lo); omega. unfold refine_high_bound. destruct (zeq (Int.unsigned i) hi); omega. (* lt node *) case_eq (split_lt i cases). intros lcases rcases EQ V RANGE. destruct (andb_prop _ _ V). clear V. rewrite (split_lt_prop v default _ _ _ _ EQ). unfold Int.ltu. destruct (zlt (Int.unsigned v) (Int.unsigned i)). eapply IHt1. eauto. omega. eapply IHt2. eauto. omega. (* jumptable node *) case_eq (split_between default i i0 cases). intros ins outs EQ V RANGE. destruct (andb_prop _ _ V). clear V. destruct (andb_prop _ _ H). clear H. destruct (andb_prop _ _ H1). clear H1. rewrite (split_between_prop v _ _ _ _ _ _ EQ). case_eq (Int.ltu (Int.sub v i) i0); intros. eapply validate_jumptable_correct; eauto. eapply proj_sumbool_true; eauto. eapply IHt; eauto. Qed. Definition table_tree_agree (default: nat) (cases: table) (t: comptree) : Prop := forall v, comptree_match v t = Some(switch_target v default cases). Theorem validate_switch_correct: forall default t cases, validate_switch default cases t = true -> table_tree_agree default cases t. Proof. unfold validate_switch, table_tree_agree; intros. eapply validate_correct_rec; eauto. apply Int.unsigned_range_2. Qed.
[GOAL] F : Type u_1 inst✝² : Field F inst✝¹ : Finite F inst✝ : Algebra (ZMod (ringChar F)) F a : F ha : a ≠ 0 ⊢ ∃ b, ↑(Algebra.trace (ZMod (ringChar F)) F) (a * b) ≠ 0 [PROOFSTEP] haveI : Fact (ringChar F).Prime := ⟨CharP.char_is_prime F _⟩ [GOAL] F : Type u_1 inst✝² : Field F inst✝¹ : Finite F inst✝ : Algebra (ZMod (ringChar F)) F a : F ha : a ≠ 0 this : Fact (Nat.Prime (ringChar F)) ⊢ ∃ b, ↑(Algebra.trace (ZMod (ringChar F)) F) (a * b) ≠ 0 [PROOFSTEP] have htr := traceForm_nondegenerate (ZMod (ringChar F)) F a [GOAL] F : Type u_1 inst✝² : Field F inst✝¹ : Finite F inst✝ : Algebra (ZMod (ringChar F)) F a : F ha : a ≠ 0 this : Fact (Nat.Prime (ringChar F)) htr : (∀ (n : F), BilinForm.bilin (Algebra.traceForm (ZMod (ringChar F)) F) a n = 0) → a = 0 ⊢ ∃ b, ↑(Algebra.trace (ZMod (ringChar F)) F) (a * b) ≠ 0 [PROOFSTEP] simp_rw [Algebra.traceForm_apply] at htr [GOAL] F : Type u_1 inst✝² : Field F inst✝¹ : Finite F inst✝ : Algebra (ZMod (ringChar F)) F a : F ha : a ≠ 0 this : Fact (Nat.Prime (ringChar F)) htr : (∀ (n : F), ↑(Algebra.trace (ZMod (ringChar F)) F) (a * n) = 0) → a = 0 ⊢ ∃ b, ↑(Algebra.trace (ZMod (ringChar F)) F) (a * b) ≠ 0 [PROOFSTEP] by_contra' hf [GOAL] F : Type u_1 inst✝² : Field F inst✝¹ : Finite F inst✝ : Algebra (ZMod (ringChar F)) F a : F ha : a ≠ 0 this : Fact (Nat.Prime (ringChar F)) htr : (∀ (n : F), ↑(Algebra.trace (ZMod (ringChar F)) F) (a * n) = 0) → a = 0 hf : ∀ (b : F), ↑(Algebra.trace (ZMod (ringChar F)) F) (a * b) = 0 ⊢ False [PROOFSTEP] exact ha (htr hf)
-- @@stderr -- dtrace: failed to compile script test/unittest/funcs/substr/err.D_PROTO_ARG.substr_non_scalar_arg2.d: [D_PROTO_ARG] line 16: substr( ) argument #2 is incompatible with prototype: prototype: int argument: string
(* Title: HOL/Quickcheck_Examples/Quickcheck_Narrowing_Examples.thy Author: Lukas Bulwahn Copyright 2011 TU Muenchen *) section \<open>Examples for narrowing-based testing\<close> theory Quickcheck_Narrowing_Examples imports Main begin declare [[quickcheck_timeout = 3600]] subsection \<open>Minimalistic examples\<close> lemma "x = y" quickcheck[tester = narrowing, finite_types = false, default_type = int, expect = counterexample] oops lemma "x = y" quickcheck[tester = narrowing, finite_types = false, default_type = nat, expect = counterexample] oops subsection \<open>Simple examples with existentials\<close> lemma "\<exists> y :: nat. \<forall> x. x = y" quickcheck[tester = narrowing, finite_types = false, expect = counterexample] oops (* lemma "\<exists> y :: int. \<forall> x. x = y" quickcheck[tester = narrowing, size = 2] oops *) lemma "x > 1 --> (\<exists>y :: nat. x < y & y <= 1)" quickcheck[tester = narrowing, finite_types = false, expect = counterexample] oops lemma "x > 2 \<longrightarrow> (\<exists>y :: nat. x < y \<and> y \<le> 2)" quickcheck[tester = narrowing, finite_types = false, size = 10] oops lemma "\<forall>x. \<exists>y :: nat. x > 3 \<longrightarrow> (y < x \<and> y > 3)" quickcheck[tester = narrowing, finite_types = false, size = 7] oops text \<open>A false conjecture derived from an partial copy-n-paste of @{thm not_distinct_decomp}\<close> lemma "\<not> distinct ws \<Longrightarrow> \<exists>xs ys zs y. ws = xs @ [y] @ ys @ [y]" quickcheck[tester = narrowing, finite_types = false, default_type = nat, expect = counterexample] oops text \<open>A false conjecture derived from theorems @{thm split_list_first} and @{thm split_list_last}\<close> lemma "x \<in> set xs \<Longrightarrow> \<exists>ys zs. xs = ys @ x # zs \<and> x \<notin> set zs \<and> x \<notin> set ys" quickcheck[tester = narrowing, finite_types = false, default_type = nat, expect = counterexample] oops text \<open>A false conjecture derived from @{thm map_eq_Cons_conv} with a typo\<close> lemma "(map f xs = y # ys) = (\<exists>z zs. xs = z' # zs & f z = y \<and> map f zs = ys)" quickcheck[tester = narrowing, finite_types = false, default_type = nat, expect = counterexample] oops lemma "a # xs = ys @ [a] \<Longrightarrow> \<exists>zs. xs = zs @ [a] \<and> ys = a#zs" quickcheck[narrowing, expect = counterexample] quickcheck[exhaustive, random, expect = no_counterexample] oops subsection \<open>Simple list examples\<close> lemma "rev xs = xs" quickcheck[tester = narrowing, finite_types = false, default_type = nat, expect = counterexample] oops lemma "rev xs = xs" quickcheck[tester = narrowing, finite_types = false, default_type = int, expect = counterexample] oops lemma "rev xs = xs" quickcheck[tester = narrowing, finite_types = true, expect = counterexample] oops subsection \<open>Simple examples with functions\<close> lemma "map f xs = map g xs" quickcheck[tester = narrowing, finite_types = false, expect = counterexample] oops lemma "map f xs = map f ys ==> xs = ys" quickcheck[tester = narrowing, finite_types = false, expect = counterexample] oops lemma "list_all2 P (rev xs) (rev ys) = list_all2 P xs (rev ys)" quickcheck[tester = narrowing, finite_types = false, expect = counterexample] oops lemma "map f xs = F f xs" quickcheck[tester = narrowing, finite_types = false, expect = counterexample] oops lemma "map f xs = F f xs" quickcheck[tester = narrowing, finite_types = false, expect = counterexample] oops (* requires some work...*) (* lemma "R O S = S O R" quickcheck[tester = narrowing, size = 2] oops *) subsection \<open>Simple examples with inductive predicates\<close> inductive even where "even 0" | "even n ==> even (Suc (Suc n))" code_pred even . lemma "even (n - 2) ==> even n" quickcheck[narrowing, expect = counterexample] oops subsection \<open>AVL Trees\<close> datatype 'a tree = ET | MKT 'a "'a tree" "'a tree" nat primrec set_of :: "'a tree \<Rightarrow> 'a set" where "set_of ET = {}" | "set_of (MKT n l r h) = insert n (set_of l \<union> set_of r)" primrec height :: "'a tree \<Rightarrow> nat" where "height ET = 0" | "height (MKT x l r h) = max (height l) (height r) + 1" primrec avl :: "'a tree \<Rightarrow> bool" where "avl ET = True" | "avl (MKT x l r h) = ((height l = height r \<or> height l = 1+height r \<or> height r = 1+height l) \<and> h = max (height l) (height r) + 1 \<and> avl l \<and> avl r)" primrec is_ord :: "('a::order) tree \<Rightarrow> bool" where "is_ord ET = True" | "is_ord (MKT n l r h) = ((\<forall>n' \<in> set_of l. n' < n) \<and> (\<forall>n' \<in> set_of r. n < n') \<and> is_ord l \<and> is_ord r)" primrec is_in :: "('a::order) \<Rightarrow> 'a tree \<Rightarrow> bool" where "is_in k ET = False" | "is_in k (MKT n l r h) = (if k = n then True else if k < n then (is_in k l) else (is_in k r))" primrec ht :: "'a tree \<Rightarrow> nat" where "ht ET = 0" | "ht (MKT x l r h) = h" definition mkt :: "'a \<Rightarrow> 'a tree \<Rightarrow> 'a tree \<Rightarrow> 'a tree" where "mkt x l r = MKT x l r (max (ht l) (ht r) + 1)" (* replaced MKT lrn lrl lrr by MKT lrr lrl *) fun l_bal where "l_bal(n, MKT ln ll lr h, r) = (if ht ll < ht lr then case lr of ET \<Rightarrow> ET \<comment> \<open>impossible\<close> | MKT lrn lrr lrl lrh \<Rightarrow> mkt lrn (mkt ln ll lrl) (mkt n lrr r) else mkt ln ll (mkt n lr r))" fun r_bal where "r_bal(n, l, MKT rn rl rr h) = (if ht rl > ht rr then case rl of ET \<Rightarrow> ET \<comment> \<open>impossible\<close> | MKT rln rll rlr h \<Rightarrow> mkt rln (mkt n l rll) (mkt rn rlr rr) else mkt rn (mkt n l rl) rr)" primrec insrt :: "'a::order \<Rightarrow> 'a tree \<Rightarrow> 'a tree" where "insrt x ET = MKT x ET ET 1" | "insrt x (MKT n l r h) = (if x=n then MKT n l r h else if x<n then let l' = insrt x l; hl' = ht l'; hr = ht r in if hl' = 2+hr then l_bal(n,l',r) else MKT n l' r (1 + max hl' hr) else let r' = insrt x r; hl = ht l; hr' = ht r' in if hr' = 2+hl then r_bal(n,l,r') else MKT n l r' (1 + max hl hr'))" subsubsection \<open>Necessary setup for code generation\<close> primrec set_of' where "set_of' ET = []" | "set_of' (MKT n l r h) = n # (set_of' l @ set_of' r)" lemma set_of': "set (set_of' t) = set_of t" by (induct t) auto lemma is_ord_mkt: "is_ord (MKT n l r h) = ((\<forall>n' \<in> set (set_of' l). n' < n) \<and> (\<forall>n' \<in> set (set_of' r). n < n') \<and> is_ord l \<and> is_ord r)" by (simp add: set_of') declare is_ord.simps(1)[code] is_ord_mkt[code] subsubsection \<open>Invalid Lemma due to typo in \<^const>\<open>l_bal\<close>\<close> lemma is_ord_l_bal: "\<lbrakk> is_ord(MKT (x :: nat) l r h); height l = height r + 2 \<rbrakk> \<Longrightarrow> is_ord(l_bal(x,l,r))" quickcheck[tester = narrowing, finite_types = false, default_type = nat, size = 6, expect = counterexample] oops subsection \<open>Examples with hd and last\<close> lemma "hd (xs @ ys) = hd ys" quickcheck[narrowing, expect = counterexample] oops lemma "last(xs @ ys) = last xs" quickcheck[narrowing, expect = counterexample] oops subsection \<open>Examples with underspecified/partial functions\<close> lemma "xs = [] ==> hd xs \<noteq> x" quickcheck[narrowing, expect = no_counterexample] oops lemma "xs = [] ==> hd xs = x" quickcheck[narrowing, expect = no_counterexample] oops lemma "xs = [] ==> hd xs = x ==> x = y" quickcheck[narrowing, expect = no_counterexample] oops lemma "hd (xs @ ys) = (if xs = [] then hd ys else hd xs)" quickcheck[narrowing, expect = no_counterexample] oops lemma "hd (map f xs) = f (hd xs)" quickcheck[narrowing, expect = no_counterexample] oops end
function imgExt = getImgExt(seqFolder) % return image extension including the dot % e.g. '.jpg' imgExt = '.jpg';
SUBROUTINE GR_WGB2 ( lun, nlun, title, num, gdattm, level, + ivcord, parm, idis, icat, iidn, ipdn, + ivco, igdn, iret ) C************************************************************************ C* GR_WGB2 * C* * C* This subroutine writes GRIB2 and GEMPAK grid identifier information * C* to the specified logical unit using a standard format. TITLE is * C* set to indicate that the title line: * C* * C*MESG# GDT# DIS# CAT# ID # PDT# VCD# GEMPAK_TIME LEVEL1 LEVEL2 VCRD PARM* C* * C* is to be written first. The first three parameters written are * C* grid identifiers (grid number, discipline number, category number, * C* product identification template number, and vertical coord. number. * C* * C* GR_WGB2 ( LUN, NLUN, TITLE, NUM, GDATTM, LEVEL, IVCORD, PARM, * C* IDIS, ICAT, IIDN, IPDN, IVCO, IGDN, IRET ) * C* * C* Input parameters: * C* LUN (NLUN) INTEGER Logical unit for write * C* NLUN INTEGER Number of units for write * C* TITLE LOGICAL Flag to write title * C* NUM INTEGER GRIB message number * C* GDATTM (2) CHAR*20 GEMPAK time * C* LEVEL (2) INTEGER Vertical levels * C* IVCORD INTEGER Vertical coordinate * C* PARM CHAR*12 Parameter name * C* IDIS INTEGER GRIB2 discipline number * C* ICAT INTEGER GRIB2 category number * C* IIDN INTEGER GRIB2 id number * C* IPDN INTEGER GRIB2 product definition number * C* IVCO INTEGER GRIB2 vertical coord. number * C* IGDN INTEGER GRIB2 grid definition template #* C* * C* Output parameters: * C* IRET INTEGER Return code * C* 0 = normal return * C** * C* Log: * C* m.gamazaychikov/SAIC 5/03 * C* T. Piper/SAIC 05/03 Fixed title format statement and made * C* integer variables actually integers! * C************************************************************************ CHARACTER*(*) gdattm (*), parm INTEGER level (*), lun (*) LOGICAL title C* CHARACTER vcord*4, dt*16, pm*12, lev*6 C----------------------------------------------------------------------- iret = 0 C C* Translate vertical coordinate. C CALL LV_CCRD ( ivcord, vcord, ier ) C C* Move character strings into variables with correct length. C dt = gdattm (1) pm = parm C C* Make level 2 into a string. Write nothing if level2 = -1. C IF ( level (2) .eq. -1 ) THEN lev = ' ' ELSE CALL ST_INCH ( level (2), lev, ier ) END IF C C* Do prints for all unit numbers. C DO ii = 1, nlun C C* Write title if requested. C IF ( title ) THEN WRITE ( lun(ii), 1000 ) 1000 FORMAT( /1X, 'MESG# GDT# DIS# CAT# ID# PDT# VCD#', + 4X, 'GEMPAK_TIME', 4X, 'LEVL1 LEVL2 VCRD PARM') END IF C C* Write the grid identifier. C WRITE ( lun(ii), 2000 ) num, igdn, idis, icat, iidn, ipdn, + ivco, dt, level(1), lev, vcord, pm 2000 FORMAT ( I5, 2X, 6(I3,2X), 1X, A, I6, 1X, A,1X, A, 1X, A ) C* END DO C* RETURN END
State Before: α : Type u_1 β : Type ?u.981881 γ : Type ?u.981884 δ : Type ?u.981887 m : MeasurableSpace α μ ν : Measure α f g : α → ℝ≥0∞ hf : AEMeasurable f ⊢ ((∫⁻ (x : α), g x ∂μ) - ∫⁻ (x : α), f x ∂μ) ≤ ∫⁻ (x : α), g x - f x ∂μ State After: α : Type u_1 β : Type ?u.981881 γ : Type ?u.981884 δ : Type ?u.981887 m : MeasurableSpace α μ ν : Measure α f g : α → ℝ≥0∞ hf : AEMeasurable f ⊢ (∫⁻ (x : α), g x ∂μ) ≤ (∫⁻ (x : α), g x - f x ∂μ) + ∫⁻ (x : α), f x ∂μ Tactic: rw [tsub_le_iff_right] State Before: α : Type u_1 β : Type ?u.981881 γ : Type ?u.981884 δ : Type ?u.981887 m : MeasurableSpace α μ ν : Measure α f g : α → ℝ≥0∞ hf : AEMeasurable f ⊢ (∫⁻ (x : α), g x ∂μ) ≤ (∫⁻ (x : α), g x - f x ∂μ) + ∫⁻ (x : α), f x ∂μ State After: case pos α : Type u_1 β : Type ?u.981881 γ : Type ?u.981884 δ : Type ?u.981887 m : MeasurableSpace α μ ν : Measure α f g : α → ℝ≥0∞ hf : AEMeasurable f hfi : (∫⁻ (x : α), f x ∂μ) = ⊤ ⊢ (∫⁻ (x : α), g x ∂μ) ≤ (∫⁻ (x : α), g x - f x ∂μ) + ∫⁻ (x : α), f x ∂μ case neg α : Type u_1 β : Type ?u.981881 γ : Type ?u.981884 δ : Type ?u.981887 m : MeasurableSpace α μ ν : Measure α f g : α → ℝ≥0∞ hf : AEMeasurable f hfi : ¬(∫⁻ (x : α), f x ∂μ) = ⊤ ⊢ (∫⁻ (x : α), g x ∂μ) ≤ (∫⁻ (x : α), g x - f x ∂μ) + ∫⁻ (x : α), f x ∂μ Tactic: by_cases hfi : (∫⁻ x, f x ∂μ) = ∞ State Before: case pos α : Type u_1 β : Type ?u.981881 γ : Type ?u.981884 δ : Type ?u.981887 m : MeasurableSpace α μ ν : Measure α f g : α → ℝ≥0∞ hf : AEMeasurable f hfi : (∫⁻ (x : α), f x ∂μ) = ⊤ ⊢ (∫⁻ (x : α), g x ∂μ) ≤ (∫⁻ (x : α), g x - f x ∂μ) + ∫⁻ (x : α), f x ∂μ State After: case pos α : Type u_1 β : Type ?u.981881 γ : Type ?u.981884 δ : Type ?u.981887 m : MeasurableSpace α μ ν : Measure α f g : α → ℝ≥0∞ hf : AEMeasurable f hfi : (∫⁻ (x : α), f x ∂μ) = ⊤ ⊢ (∫⁻ (x : α), g x ∂μ) ≤ ⊤ Tactic: rw [hfi, add_top] State Before: case pos α : Type u_1 β : Type ?u.981881 γ : Type ?u.981884 δ : Type ?u.981887 m : MeasurableSpace α μ ν : Measure α f g : α → ℝ≥0∞ hf : AEMeasurable f hfi : (∫⁻ (x : α), f x ∂μ) = ⊤ ⊢ (∫⁻ (x : α), g x ∂μ) ≤ ⊤ State After: no goals Tactic: exact le_top State Before: case neg α : Type u_1 β : Type ?u.981881 γ : Type ?u.981884 δ : Type ?u.981887 m : MeasurableSpace α μ ν : Measure α f g : α → ℝ≥0∞ hf : AEMeasurable f hfi : ¬(∫⁻ (x : α), f x ∂μ) = ⊤ ⊢ (∫⁻ (x : α), g x ∂μ) ≤ (∫⁻ (x : α), g x - f x ∂μ) + ∫⁻ (x : α), f x ∂μ State After: case neg α : Type u_1 β : Type ?u.981881 γ : Type ?u.981884 δ : Type ?u.981887 m : MeasurableSpace α μ ν : Measure α f g : α → ℝ≥0∞ hf : AEMeasurable f hfi : ¬(∫⁻ (x : α), f x ∂μ) = ⊤ ⊢ (∫⁻ (x : α), g x ∂μ) ≤ ∫⁻ (a : α), g a - f a + f a ∂μ Tactic: rw [← lintegral_add_right' _ hf] State Before: case neg α : Type u_1 β : Type ?u.981881 γ : Type ?u.981884 δ : Type ?u.981887 m : MeasurableSpace α μ ν : Measure α f g : α → ℝ≥0∞ hf : AEMeasurable f hfi : ¬(∫⁻ (x : α), f x ∂μ) = ⊤ ⊢ (∫⁻ (x : α), g x ∂μ) ≤ ∫⁻ (a : α), g a - f a + f a ∂μ State After: no goals Tactic: exact lintegral_mono fun x => le_tsub_add
function args_lesson(s) @add_arg_table s begin "--model-type", "-m" help = "model to be used - one of 'unetlike', 'multiscale3', 'fcrna'" arg_type = String default = "multiscale3" "--patch-mode", "-n" help = "number of patches used for training" default = nothing "--patch-size", "-s" help = "size of the patches used for training" arg_type = Int default = -1 "--batch-size", "-b" help = "number of patches per mini-batch during training" arg_type = Int default = -1 "--batch-normalization", "-B" help = "whether to activate batch normalization (0 or 1)" arg_type = Int default = -1 "--directory", "-d" help = "Overwrite image/label folder suggested by the lesson file" arg_type = String default = "" "--optimizer", "-o" help = "Overwrite optimizer suggested by the lesson file" arg_type = String default = "" "--epochs", "-e" help = "number of training epochs" arg_type = Int default = -1 "--learning-rate", "-l" help = "initial learning rate for the chosen optimizer [-o]" arg_type = Float64 default = -1. "--proximity-kernel-size", "-k" help = "size of the peaks in the proximity map" arg_type = Int default = -1 "--proximity-kernel-height", "-K" help = "height of the peaks in the proximity map" arg_type = Float64 default = -1. "--imageop", "-I" help = "image operation to be performed on the patches" arg_type = String default = "" "--no-gpu" help = "prevent usage of gpu acceleration even if gpu support is detected" action = :store_true "lesson" help = "DCellC lesson (.dcct) file used for training" required = true arg_type = String "modelfile" help = "DCellC model (.dccm) file that the trained model is saved to" required = true arg_type = String end end function cmd_lesson(args) lesson = lessonload(args["lesson"]) if args["directory"] != "" lesson.folder = args["directory"] end if args["optimizer"] != "" lesson.optimizer = args["optimizer"] end if args["epochs"] != -1 lesson.epochs = args["epochs"] end if args["learning-rate"] > 0 lesson.lr = args["learning-rate"] end if args["patch-mode"] != nothing lesson.patchmode = parse(Int, args["patch-mode"]) end if args["patch-size"] != -1 lesson.patchsize = args["patch-size"] end if args["batch-size"] != -1 lesson.batchsize = args["batch-mode"] end if args["batch-normalization"] != -1 lesson.batchnorm = Bool(args["batch-normalization"]) end if args["proximity-kernel-size"] != -1 lesson.kernelsize = args["proximity-kernel-size"] end if args["proximity-kernel-height"] > 0 lesson.kernelheight = args["proximity-kernel-height"] end if args["imageop"] != "" lesson.imageop = eval(parse(args["imageop"])) end if args["no-gpu"] || gpu() < 0 println("# CPU mode") at = Array{Float32} else println("# GPU mode") at = KnetArray{Float32} end train(lesson, modelpath = args["modelfile"], record = false) end
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2014 Catley Lakeman Ltd. The moral rights of the author, David Rees, have been asserted. This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <[email protected]>. The license is also available online at <http://quantlib.org/license.shtml>. 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 license for more details. */ #ifndef quantlib_test_autocall_hpp #define quantlib_test_autocall_hpp #include <boost/test/unit_test.hpp> #include <ql/quantlib.hpp> #include <ql/experimental/exoticoptions/autocall.hpp> using namespace QuantLib; class AutocallTest { public: // Tests for autocall set up to replicate a fixed bond static void testBondBeforeIssueBeforeStrike(); static void testBondBeforeIssueAfterStrike(); static void testBondOnCouponDate(); static void testBondOffCouponDate(); static void testBondAtMaturity(); static void testBondAfterMaturity(); // Test for normal autocall static void testBeforeIssueBeforeStrike(); static void testBeforeIssueAfterStrike(); static void testOnCouponDate(); static void testOffCouponDate(); static void testAtMaturity(); static void testAfterMaturity(); static void testExample(); static void testVsZeroStrikeCall(); static void testVsCallOption(); static void testVsDigitalOption(); static void testVsCallSpread(); static void testVsBarrierOption(); static void testVsEverest(); static boost::unit_test_framework::test_suite* suite(); private: // Enum used for setting the difference evaluation date tests enum EvaluationDateType { BeforeIssueBeforeStrike, BeforeIssueAfterStrike, OnCouponDate, OffCouponDate, AtMaturity, AfterMaturity }; // Test a autocall set up as a fixed bond static void testBondStyle( const std::string& method, const EvaluationDateType& evaluationDateType, const Real& tolerance ); // Test a normal autocall static void testNormal( const std::string& method, const EvaluationDateType& evaluationDateType, const Real& expectedResult, const Real& tolerance ); // Create an autocall with same cashflows as fixed bond static void createBondStyleAutocall( const Date& issueDate, const Size& numUnderlyings, const bool strikeLevelsSet, boost::shared_ptr<Autocall>& bondStyleAutocall, boost::shared_ptr<FixedRateBond>& bond ); // Create a normal autocall static void createNormalAutocall( const Date& issueDate, const Size& numUnderlyings, const bool strikeLevelsSet, boost::shared_ptr<Autocall>& autocall ); // Create market data as of valuation date static void createMarketData( const Date& valuationDate, const Size& numUnderlyings, Handle<YieldTermStructure>& riskFreeRate, boost::shared_ptr<StochasticProcessArray>& process_array ); // Create some more realistic market data as of valuation date static void createMarketDataRealistic( const Size& numUnderlyings, Handle<YieldTermStructure>& riskFreeRate, boost::shared_ptr<StochasticProcessArray>& process_array ); }; #endif
Require Import Bool Arith Coq.Arith.Div2 List. Require Import BellantoniCook.Lib. Notation bs := (list bool). Definition unary (v : bs) := forallb id v. (** * Boolean interpretation of bitstrings *) Definition bs2bool (v:bs) : bool := hd false v. Definition bool2bs (b:bool) : bs := if b then true::nil else nil. Lemma bs_nat2bool_true : forall v, bs2bool v = true -> length v <> 0. Proof. intro v; case v; simpl; auto; intros; discriminate. Qed. Lemma bs_nat2bool_true_conv : forall v, unary v = true -> length v <> 0 -> bs2bool v = true. Proof. intro v; case v; simpl; intros. elim H0; trivial. rewrite andb_true_iff in H. decompose [and] H; destruct b; trivial. Qed. Lemma bs_nat2bool_false v : unary v = true -> bs2bool v = false -> length v = 0. Proof. destruct v; simpl; trivial; intros. rewrite andb_true_iff in H. decompose [and] H; destruct b; discriminate. Qed. Lemma bs_nat2bool_false_conv v : length v = 0 -> bs2bool v = false. Proof. destruct v; simpl; trivial; intros. discriminate. Qed. (** * Binary interpretation of bitstrings *) Fixpoint bs2nat (v:bs) : nat := match v with | nil => 0 | false :: v' => 2 * bs2nat v' | true :: v' => S (2 * bs2nat v') end. Fixpoint succ_bs (v : bs) : bs := match v with | nil => [true] | false :: v' => true :: v' | true :: v' => false :: succ_bs v' end. Lemma succ_bs_correct v : bs2nat (succ_bs v) = bs2nat v + 1. Proof. induction v; simpl; trivial; case a; simpl; ring [IHv]. Qed. Fixpoint nat2bs (n:nat) : bs := match n with | 0 => nil | S n' => succ_bs (nat2bs n') end. Lemma bs2nat_nil : bs2nat nil = 0. Proof. trivial. Qed. Lemma bs2nat_false v : bs2nat (false :: v) = 2 * bs2nat v. Proof. trivial. Qed. Lemma bs2nat_true v : bs2nat (true :: v) = 1 + 2 * bs2nat v. Proof. trivial. Qed. Lemma bs2nat_tl : forall v, bs2nat (tl v) = div2 (bs2nat v). Proof. destruct v; simpl; [ trivial | ]. replace (bs2nat v + (bs2nat v + 0)) with (2 * bs2nat v) by omega. case b;[ rewrite div2_double_plus_one | rewrite div2_double]; trivial. Qed. Lemma bs2nat_nat2bs : forall n, bs2nat (nat2bs n) = n. Proof. induction n as [ | n' IHn]; simpl; auto. rewrite succ_bs_correct; ring [IHn]. Qed.