Datasets:
AI4M
/

text
stringlengths
0
3.34M
myTestRule { # Input parameters: # srcFile - iRODS image file that will be converted # srcOptions - Optional srcFile property values # (only image format values are allowed if this parameter is used) # destFile - iRODS image file that will be created to hold converted image # destOptions - Optional destFile properties string giving parameters for conversion # (only file format and compression flags are allowed) # # Uses ImageMagick. # # Set properties for destOptions... in this case, the compression # # Get properties for srcFile - just for perusing msiImageGetProperties(*srcFile, "null", *Prop); writeLine("stdout", "Original file properties:"); msiPrintKeyValPair("stdout", *Prop); # Get image format just for checking msiPropertiesGet(*Prop, "image.Compression", *compVal); writeLine("stdout", ""); writeLine("stdout", "Original compression: *compVal"); # Convert msiImageConvert(*srcFile,"null",*destFile,*destOptions); # Write a message to the server log writeLine("serverLog", "Converting *srcFile to *destFile"); # Write a message to stdout writeLine("stdout", ""); # Write out properties of new image file msiImageGetProperties(*destFile, "null", *Prop); writeLine("stdout", "Converted file properties:"); msiPrintKeyValPair("stdout", *Prop); msiPropertiesGet(*Prop, "image.Compression", *compVal); writeLine("stdout", ""); writeLine("stdout", "Compression of converted file: *compVal"); } INPUT *srcFile="/tempZone/home/rods/image/ncdc.png", *destFile="/tempZone/home/rods/image/ncdc-recomp.png", *destOptions="<image.Compression>lossless</image.Compression>" OUTPUT ruleExecOut
lemmas scaleR_zero_left = real_vector.scale_zero_left
module Main import Effects import Effect.StdIO import IdrisNet.Socket import IdrisNet.UDP.UDPServer udpServerLoop : Nat -> { [UDPSERVER UDPBound, STDIO] ==> [UDPSERVER (), STDIO] } Eff IO () udpServerLoop Z = udpClose udpServerLoop (S k) = do case !(udpReadString 1024) of UDPSuccess (addr, str, _) => do putStr ("Received: " ++ str ++ "from " ++ (show (remote_addr addr)) ++ "\n") UDPSuccess _ <- udpWriteString (IPv4Addr 127 0 0 1) 9001 "pines test" | UDPFailure err => do putStr ("Error!" ++ (show err)) udpFinalise | UDPRecoverableError err => do putStr ("Error!" ++ (show err)) udpClose udpServerLoop k UDPRecoverableError _ => udpServerLoop (S k) UDPFailure err => do putStr ("Error: " ++ (show err) ++ "\n") udpFinalise udpBindAndLoop : Port -> { [UDPSERVER (), STDIO] } Eff IO () udpBindAndLoop p = do case !(udpBind Nothing p) of UDPSuccess _ => udpServerLoop 5 UDPRecoverableError err => putStr ("Error binding: " ++ (show err) ++ "\n") UDPFailure err => putStr ("Error binding: " ++ (show err) ++ "\n") main : IO () main = run (udpBindAndLoop 4099)
(* Copyright 2021 Joshua M. Cohen Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) Require Import Specs. Require Import ReedSolomonList. Require Import Verif_decode. Require Import Verif_encode. Require Import ReedSolomon. (* VST/CompCert require several axioms. Some are related to the real numbers; some are standard (propositional and functional extensionality, law of the excluded middle, and [eq_rect_eq]. We do not add any axioms beyond these. *) (* VST Specs: *) Require Import String. Local Open Scope string_scope. Goal True. idtac "Encoder VST Spec Axioms:". idtac " ". Print Assumptions fec_blk_encode_spec. idtac " ". idtac "Decoder VST Spec Axioms:". idtac " ". Print Assumptions fec_blk_decode_spec. idtac " ". (* VST funspec proofs: *) idtac "Encoder VST Proof Axioms:". idtac " ". Print Assumptions body_fec_blk_encode. idtac " ". idtac "Decoder VST Proof Axioms:". idtac " ". Print Assumptions body_fec_blk_decode. idtac " ". (* Decoder correctness theorem *) idtac "Decoder Correctness Theorem Axioms:". idtac " ". Print Assumptions decoder_list_correct. idtac " ". (* The high-level correctness theorem (using only MathComp and no VST) requires no axioms: *) idtac "High-level correctness theorem axioms:". idtac " ". Print Assumptions decoder_correct. idtac " ". Abort.
Formal statement is: lemma sigma_algebra_imp_Dynkin_system: assumes "sigma_algebra \<Omega> M" shows "Dynkin_system \<Omega> M" Informal statement is: If $\mathcal{M}$ is a $\sigma$-algebra, then it is a Dynkin system.
[STATEMENT] lemma ec_Sup_directed: "(\<And>a. a \<in> A \<Longrightarrow> ec a) \<Longrightarrow> (\<And>a b. a \<in> A \<Longrightarrow> b \<in> A \<Longrightarrow> \<exists>c\<in>A. a \<le> c \<and> b \<le> c) \<Longrightarrow> ec (\<Squnion>A)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>\<And>a. a \<in> A \<Longrightarrow> ec a; \<And>a b. \<lbrakk>a \<in> A; b \<in> A\<rbrakk> \<Longrightarrow> \<exists>c\<in>A. a \<le> c \<and> b \<le> c\<rbrakk> \<Longrightarrow> ec (\<Squnion> A) [PROOF STEP] by (auto simp: ec_def closed_mdpc_SupI sc_SupI_directed)
{-# OPTIONS --cubical --no-import-sorts --allow-unsolved-metas #-} module Number.Instances.QuoInt where open import Cubical.Foundations.Everything hiding (⋆) renaming (_⁻¹ to _⁻¹ᵖ; assoc to ∙-assoc) open import Cubical.Foundations.Logic renaming (inl to inlᵖ; inr to inrᵖ) open import Cubical.Relation.Nullary.Base renaming (¬_ to ¬ᵗ_) open import Cubical.Relation.Binary.Base open import Cubical.Data.Sum.Base renaming (_⊎_ to infixr 4 _⊎_) open import Cubical.Data.Sigma.Base renaming (_×_ to infixr 4 _×_) open import Cubical.Data.Sigma open import Cubical.Data.Bool as Bool using (Bool; not; true; false) open import Cubical.Data.Empty renaming (elim to ⊥-elim; ⊥ to ⊥⊥) -- `⊥` and `elim` open import Cubical.Foundations.Logic renaming (¬_ to ¬ᵖ_; inl to inlᵖ; inr to inrᵖ) open import Function.Base using (it; _∋_; _$_) open import Cubical.Foundations.Isomorphism open import Cubical.HITs.PropositionalTruncation --.Properties open import Utils using (!_; !!_) open import MoreLogic.Reasoning open import MoreLogic.Definitions open import MoreLogic.Properties open import MorePropAlgebra.Definitions hiding (_≤''_) open import MorePropAlgebra.Structures open import MorePropAlgebra.Bundles open import MorePropAlgebra.Consequences open import Number.Structures2 open import Number.Bundles2 open import Cubical.Data.Nat.Literals open import Cubical.Data.Nat using (suc; zero; ℕ; HasFromNat) open import Number.Prelude.Nat using (¬-<ⁿ-zero; +ⁿ-comm; ¬suc<ⁿ0; _+ⁿ_; _·ⁿ_; ·ⁿ-reflects-≡ˡ') open import Number.Instances.QuoIntFromInt public open import Cubical.HITs.Ints.QuoInt as QuoInt using ( ℤ ; HasFromNat ; _+_ ; Int≡ℤ ; signed ; posneg ; ℤ→Int ; sucℤ ; predℤ ; sign ; abs ; pos ; neg ; +-comm ; +-assoc ; sucℤ-+ʳ ; sucℤ-+ˡ ; spos ; sneg ; *-pos-suc ; negate-invol ) renaming ( isSetℤ to is-set ; _*_ to _·_ ; -_ to infixl 6 -_ ; *-comm to ·-comm ) open IsLinearlyOrderedCommRing is-LinearlyOrderedCommRing using ( _-_ ; <-irrefl ; <-trans ; +-<-ext ; +-rinv ; +-identity ; ·-identity ; _≤_ ; ·-preserves-< ; <-tricho ; <-asym ; _#_ ; +-inverse ; ·-assoc ) 0<1 : [ 0 < 1 ] 0<1 = 0 , refl -- TODO: import these properties from somewhere else +-reflects-< : ∀ x y z → [ (x + z < y + z) ⇒ ( x < y ) ] +-preserves-< : ∀ x y z → [ ( x < y ) ⇒ (x + z < y + z) ] +-creates-< : ∀ x y z → [ ( x < y ) ⇔ (x + z < y + z) ] +-preserves-< a b x = snd ( ( a < b ) ⇒ᵖ⟨ transport (λ i → [ sym (fst (+-identity a)) i < sym (fst (+-identity b)) i ]) ⟩ ( a + 0 < b + 0 ) ⇒ᵖ⟨ transport (λ i → [ a + sym (+-rinv x) i < b + sym (+-rinv x) i ]) ⟩ ( a + (x - x) < b + (x - x)) ⇒ᵖ⟨ transport (λ i → [ +-assoc a x (- x) i < +-assoc b x (- x) i ]) ⟩ ((a + x) - x < (b + x) - x ) ⇒ᵖ⟨ +-<-ext (a + x) (- x) (b + x) (- x) ⟩ ((a + x < b + x) ⊔ (- x < - x)) ⇒ᵖ⟨ (λ q → case q as (a + x < b + x) ⊔ (- x < - x) ⇒ a + x < b + x of λ { (inl a+x<b+x) → a+x<b+x -- somehow ⊥-elim needs a hint in the next line ; (inr -x<-x ) → ⊥-elim {A = λ _ → [ a + x < b + x ]} (<-irrefl (- x) -x<-x) }) ⟩ a + x < b + x ◼ᵖ) +-reflects-< x y z = snd ( x + z < y + z ⇒ᵖ⟨ +-preserves-< (x + z) (y + z) (- z) ⟩ (x + z) - z < (y + z) - z ⇒ᵖ⟨ transport (λ i → [ +-assoc x z (- z) (~ i) < +-assoc y z (- z) (~ i) ]) ⟩ x + (z - z) < y + (z - z) ⇒ᵖ⟨ transport (λ i → [ x + +-rinv z i < y + +-rinv z i ]) ⟩ x + 0 < y + 0 ⇒ᵖ⟨ transport (λ i → [ fst (+-identity x) i < fst (+-identity y) i ]) ⟩ x < y ◼ᵖ) +-creates-< x y z .fst = +-preserves-< x y z +-creates-< x y z .snd = +-reflects-< x y z suc-creates-< : ∀ x y → [ (x < y) ⇔ (sucℤ x < sucℤ y) ] suc-creates-< x y .fst p = substₚ (λ p → sucℤ x < p) (∣ +-comm y (pos 1) ∣) $ substₚ (λ p → p < y + pos 1) (∣ +-comm x (pos 1) ∣) (+-preserves-< x y (pos 1) p) suc-creates-< x y .snd p = +-reflects-< x y (pos 1) $ substₚ (λ p → p < y + pos 1) (∣ +-comm (pos 1) x ∣) $ substₚ (λ p → sucℤ x < p) (∣ +-comm (pos 1) y ∣) p ·-creates-< : ∀ a b x → [ 0 < x ] → [ (a < b) ⇔ ((a · x) < (b · x)) ] ·-creates-< a b x p .fst q = ·-preserves-< a b x p q ·-creates-< a b x p .snd q = ·-reflects-< a b x p q ·-creates-<ˡ : ∀ a b x → [ 0 < x ] → [ (a < b) ⇔ ((x · a) < (x · b)) ] ·-creates-<ˡ a b x p .fst q = transport (λ i → [ ·-comm a x i < ·-comm b x i ]) $ ·-preserves-< a b x p q ·-creates-<ˡ a b x p .snd q = ·-reflects-< a b x p (transport (λ i → [ ·-comm x a i < ·-comm x b i ]) q) ·-creates-<-≡ : ∀ a b x → [ 0 < x ] → (a < b) ≡ ((a · x) < (b · x)) ·-creates-<-≡ a b x p = ⇔toPath' (·-creates-< a b x p) ·-creates-<ˡ-≡ : ∀ a b x → [ 0 < x ] → (a < b) ≡ ((x · a) < (x · b)) ·-creates-<ˡ-≡ a b x p = ⇔toPath' (·-creates-<ˡ a b x p) +-creates-≤ : ∀ a b x → [ (a ≤ b) ⇔ ((a + x) ≤ (b + x)) ] +-creates-≤ a b x = {! !} ·-creates-≤ : ∀ a b x → [ 0 ≤ x ] → [ (a ≤ b) ⇔ ((a · x) ≤ (b · x)) ] ·-creates-≤ a b x 0≤x .fst p = {! !} ·-creates-≤ a b x 0≤x .snd p = {! !} ·-creates-≤-≡ : ∀ a b x → [ 0 ≤ x ] → (a ≤ b) ≡ ((a · x) ≤ (b · x)) ·-creates-≤-≡ a b x 0≤x = uncurry ⇔toPath $ ·-creates-≤ a b x 0≤x ≤-dicho : ∀ x y → [ (x ≤ y) ⊔ (y ≤ x) ] ≤-dicho x y with <-tricho x y ... | inl (inl x<y) = inlᵖ $ <-asym x y x<y ... | inl (inr y<x) = inrᵖ $ <-asym y x y<x ... | inr x≡y = inlᵖ $ subst (λ p → [ ¬(p < x) ]) x≡y (<-irrefl x) ℤlattice : Lattice {ℓ-zero} {ℓ-zero} ℤlattice = record { LinearlyOrderedCommRing bundle renaming (≤-Lattice to is-Lattice) } open import MorePropAlgebra.Properties.Lattice ℤlattice open OnSet is-set hiding (+-min-distribʳ; ·-min-distribʳ; +-max-distribʳ; ·-max-distribʳ) ≤-min-+ : ∀ a b c w → [ w ≤ (a + c) ] → [ w ≤ (b + c) ] → [ w ≤ (min a b + c) ] ≤-max-+ : ∀ a b c w → [ (a + c) ≤ w ] → [ (b + c) ≤ w ] → [ (max a b + c) ≤ w ] ≤-min-· : ∀ a b c w → [ w ≤ (a · c) ] → [ w ≤ (b · c) ] → [ w ≤ (min a b · c) ] ≤-max-· : ∀ a b c w → [ (a · c) ≤ w ] → [ (b · c) ≤ w ] → [ (max a b · c) ≤ w ] ≤-min-+ = OnType.≤-dicho⇒+.≤-min-+ _+_ ≤-dicho ≤-max-+ = OnType.≤-dicho⇒+.≤-max-+ _+_ ≤-dicho ≤-min-· = OnType.≤-dicho⇒·.≤-min-· _·_ ≤-dicho ≤-max-· = OnType.≤-dicho⇒·.≤-max-· _·_ ≤-dicho +-min-distribʳ : ∀ x y z → (min x y + z) ≡ min (x + z) (y + z) ·-min-distribʳ : ∀ x y z → [ 0 ≤ z ] → (min x y · z) ≡ min (x · z) (y · z) +-max-distribʳ : ∀ x y z → (max x y + z) ≡ max (x + z) (y + z) ·-max-distribʳ : ∀ x y z → [ 0 ≤ z ] → (max x y · z) ≡ max (x · z) (y · z) +-min-distribˡ : ∀ x y z → (z + min x y) ≡ min (z + x) (z + y) ·-min-distribˡ : ∀ x y z → [ 0 ≤ z ] → (z · min x y) ≡ min (z · x) (z · y) +-max-distribˡ : ∀ x y z → (z + max x y) ≡ max (z + x) (z + y) ·-max-distribˡ : ∀ x y z → [ 0 ≤ z ] → (z · max x y) ≡ max (z · x) (z · y) +-min-distribʳ = OnSet.+-min-distribʳ is-set _+_ +-creates-≤ ≤-min-+ ·-min-distribʳ = OnSet.·-min-distribʳ is-set 0 _·_ ·-creates-≤ ≤-min-· +-max-distribʳ = OnSet.+-max-distribʳ is-set _+_ +-creates-≤ ≤-max-+ ·-max-distribʳ = OnSet.·-max-distribʳ is-set 0 _·_ ·-creates-≤ ≤-max-· +-min-distribˡ x y z = +-comm z (min x y) ∙ +-min-distribʳ x y z ∙ (λ i → min (+-comm x z i) (+-comm y z i)) ·-min-distribˡ x y z p = ·-comm z (min x y) ∙ ·-min-distribʳ x y z p ∙ (λ i → min (·-comm x z i) (·-comm y z i)) +-max-distribˡ x y z = +-comm z (max x y) ∙ +-max-distribʳ x y z ∙ (λ i → max (+-comm x z i) (+-comm y z i)) ·-max-distribˡ x y z p = ·-comm z (max x y) ∙ ·-max-distribʳ x y z p ∙ (λ i → max (·-comm x z i) (·-comm y z i)) pos<pos[suc] : ∀ x → [ pos x < pos (suc x) ] pos<pos[suc] 0 = 0<1 pos<pos[suc] (suc x) = suc-creates-< (pos x) (pos (suc x)) .fst (pos<pos[suc] x) 0<ᶻpos[suc] : ∀ x → [ 0 < pos (suc x) ] 0<ᶻpos[suc] 0 = 0<1 0<ᶻpos[suc] (suc x) = <-trans 0 (pos (suc x)) (pos (suc (suc x))) (0<ᶻpos[suc] x) (suc-creates-< (pos x) (pos (suc x)) .fst (pos<pos[suc] x)) ·-nullifiesˡ : ∀(x : ℤ) → 0 · x ≡ 0 ·-nullifiesˡ (pos zero) = refl ·-nullifiesˡ (neg zero) = refl ·-nullifiesˡ (posneg i) = refl ·-nullifiesˡ (pos (suc n)) = refl ·-nullifiesˡ (neg (suc n)) = sym posneg ·-nullifiesʳ : ∀(x : ℤ) → x · 0 ≡ 0 ·-nullifiesʳ x = ·-comm x 0 ∙ ·-nullifiesˡ x ·-preserves-0< : ∀ a b → [ 0 < a ] → [ 0 < b ] → [ 0 < a · b ] ·-preserves-0< a b p q = subst (λ p → [ p < a · b ]) (·-nullifiesˡ b) (·-preserves-< 0 a b q p) private term : ∀ b x → Type ℓ-zero term b x = [ ((pos 0 < x) ⇒ (pos 0 < b)) ⊓ ((pos 0 < b) ⇒ (pos 0 < x)) ] ·-reflects-<ˡ : (x y z : ℤ) → [ pos 0 < z ] → [ z · x < z · y ] → [ x < y ] ·-reflects-<ˡ x y z p q = ·-reflects-< x y z p (transport (λ i → [ ·-comm z x i < ·-comm z y i ]) q) -flips-<0 : ∀ x → [ (x < 0) ⇔ (0 < (- x)) ] -flips-<0 (signed spos zero) = (λ x → x) , (λ x → x) -flips-<0 (signed sneg zero) = (λ x → x) , (λ x → x) -flips-<0 (ℤ.posneg i) = (λ x → x) , (λ x → x) -flips-<0 (signed spos (suc n)) .fst p = ¬-<ⁿ-zero p -flips-<0 (signed sneg (suc n)) .fst tt = n , +ⁿ-comm n 1 -flips-<0 (signed sneg (suc n)) .snd p = tt -- NOTE: this could be a path, if we make `+-creates-<` into a path -flips-< : ∀ x y → [ x < y ] → [ - y < - x ] -flips-< x y p = ( ( x < y ) ⇒ᵖ⟨ +-creates-< x y (- y) .fst ⟩ ( x - y < y - y) ⇒ᵖ⟨ transport (λ i → [ +-comm x (- y) i < +-rinv y i ]) ⟩ ( (- y) + x < 0 ) ⇒ᵖ⟨ +-creates-< ((- y) + x) 0 (- x) .fst ⟩ (((- y) + x) - x < 0 - x) ⇒ᵖ⟨ transport (λ i → [ +-assoc (- y) x (- x) (~ i) < +-identity (- x) .snd i ]) ⟩ ( (- y) + (x - x) < - x ) ⇒ᵖ⟨ transport (λ i → [ (- y) + +-rinv x i < - x ]) ⟩ ( (- y) + 0 < - x ) ⇒ᵖ⟨ transport (λ i → [ +-identity (- y) .fst i < - x ]) ⟩ ( - y < - x ) ◼ᵖ) .snd p -flips-<-⇔ : ∀ x y → [ (x < y) ⇔ (- y < - x) ] -flips-<-⇔ x y .fst = -flips-< x y -flips-<-⇔ x y .snd p = transport (λ i → [ negate-invol x i < negate-invol y i ]) $ -flips-< (- y) (- x) p -flips-<-≡ : ∀ x y → (x < y) ≡ (- y < - x) -flips-<-≡ x y = ⇔toPath' (-flips-<-⇔ x y) -identity-· : ∀ a → (- 1) · a ≡ - a -identity-· (pos zero) j = posneg (~ i0 ∨ ~ j) -identity-· (neg zero) j = posneg (~ i1 ∨ ~ j) -identity-· (posneg i) j = posneg (~ i ∨ ~ j) -identity-· (pos (suc n)) i = neg (suc (+ⁿ-comm n 0 i)) -identity-· (neg (suc n)) i = pos (suc (+ⁿ-comm n 0 i)) -distˡ : ∀ a b → -(a · b) ≡ (- a) · b -distˡ a b = -(a · b) ≡⟨ sym $ -identity-· (a · b) ⟩ (- 1) · (a · b) ≡⟨ ·-assoc (- 1) a b ⟩ ((- 1) · a) · b ≡⟨ (λ i → -identity-· a i · b) ⟩ (- a) · b ∎ private lem : ∀ z → [ z < 0 ] → [ 0 < - z ] lem z p = subst (λ p → [ p < - z ]) (sym posneg) $ -flips-< z 0 p ·-creates-<-flippedˡ-≡ : (x y z : ℤ) → [ z < 0 ] → (z · x < z · y) ≡ (y < x) ·-creates-<-flippedˡ-≡ x y z p = z · x < z · y ≡⟨ -flips-<-≡ (z · x) (z · y) ⟩ - (z · y) < - (z · x) ≡⟨ (λ i → -distˡ z y i < -distˡ z x i) ⟩ (- z) · y < (- z) · x ≡⟨ sym $ ·-creates-<ˡ-≡ y x (- z) (lem z p) ⟩ y < x ∎ ·-creates-<-flippedʳ-≡ : (x y z : ℤ) → [ z < 0 ] → (x · z < y · z) ≡ (y < x) ·-creates-<-flippedʳ-≡ x y z p = (λ i → ·-comm x z i < ·-comm y z i) ∙ ·-creates-<-flippedˡ-≡ x y z p ·-reflects-<-flippedˡ : (x y z : ℤ) → [ z < 0 ] → [ z · x < z · y ] → [ y < x ] ·-reflects-<-flippedˡ x y z p q = pathTo⇒ (·-creates-<-flippedˡ-≡ x y z p) q -- (z · x < z · y ⇒ᵖ⟨ -flips-< (z · x) (z · y) ⟩ -- - (z · y) < - (z · x) ⇒ᵖ⟨ transport (λ i → [ -distˡ z y i < -distˡ z x i ]) ⟩ -- (- z) · y < (- z) · x ⇒ᵖ⟨ ·-creates-<ˡ y x (- z) (lem z p) .snd ⟩ -- y < x ◼ᵖ) .snd q ·-reflects-<-flippedʳ : (x y z : ℤ) → [ z < 0 ] → [ x · z < y · z ] → [ y < x ] ·-reflects-<-flippedʳ x y z p q = ·-reflects-<-flippedˡ x y z p (transport (λ i → [ ·-comm x z i < ·-comm y z i ]) q) -- ·-preserves-<-flippedˡ : (x y z : ℤ) → [ z < 0 ] → [ x < y ] → [ z · y < z · x ] -- ·-preserves-<-flippedˡ x y z p q = {! !} ·-reflects-0< : ∀ a b → [ 0 < a · b ] → [ ((0 < a) ⇔ (0 < b)) ⊓ ((a < 0) ⇔ (b < 0)) ] ·-reflects-0< a b p .fst .fst q = ·-reflects-<ˡ 0 b a q (transport (λ i → [ ·-nullifiesʳ a (~ i) < a · b ]) p) ·-reflects-0< a b p .fst .snd q = ·-reflects-< 0 a b q (transport (λ i → [ ·-nullifiesˡ b (~ i) < a · b ]) p) ·-reflects-0< a b p .snd .fst q = ·-reflects-<-flippedˡ 0 b a q (transport (λ i → [ ·-nullifiesʳ a (~ i) < a · b ]) p) ·-reflects-0< a b p .snd .snd q = ·-reflects-<-flippedʳ 0 a b q (transport (λ i → [ ·-nullifiesˡ b (~ i) < a · b ]) p) #-dicho : ∀ x → [ x # 0 ] ⊎ (x ≡ 0) #-dicho x = <-tricho x 0 ⊕-identityʳ : ∀ s → (s Bool.⊕ spos) ≡ s ⊕-identityʳ spos = refl ⊕-identityʳ sneg = refl ·-preserves-signˡ : ∀ x y → [ 0 < y ] → sign (x · y) ≡ sign x ·-preserves-signˡ x (signed spos zero) p = ⊥-elim {A = λ _ → sign (x · ℤ.posneg i0) ≡ sign x} (¬-<ⁿ-zero p) ·-preserves-signˡ x (signed sneg zero) p = ⊥-elim {A = λ _ → sign (x · ℤ.posneg i1) ≡ sign x} (¬-<ⁿ-zero p) ·-preserves-signˡ x (ℤ.posneg i) p = ⊥-elim {A = λ _ → sign (x · ℤ.posneg i ) ≡ sign x} (¬-<ⁿ-zero p) ·-preserves-signˡ (signed spos zero) (signed spos (suc n)) p = refl ·-preserves-signˡ (signed sneg zero) (signed spos (suc n)) p = refl ·-preserves-signˡ (ℤ.posneg i) (signed spos (suc n)) p = refl ·-preserves-signˡ (signed s (suc n₁)) (signed spos (suc n)) p = ⊕-identityʳ s #⇒≢ : ∀ x → [ x # 0 ] → ¬ᵗ(0 ≡ x) #⇒≢ x (inl p) q = <-irrefl 0 $ subst (λ p → [ p < pos 0 ]) (sym q) p #⇒≢ x (inr p) q = <-irrefl 0 $ subst (λ p → [ pos 0 < p ]) (sym q) p <-split-pos : ∀ z → [ 0 < z ] → Σ[ n ∈ ℕ ] z ≡ pos (suc n) <-split-pos (pos zero) p = ⊥-elim {A = λ _ → Σ[ n ∈ ℕ ] posneg i0 ≡ pos (suc n)} (<-irrefl 0 p) <-split-pos (neg zero) p = ⊥-elim {A = λ _ → Σ[ n ∈ ℕ ] posneg i1 ≡ pos (suc n)} (<-irrefl 0 p) <-split-pos (posneg i) p = ⊥-elim {A = λ _ → Σ[ n ∈ ℕ ] posneg i ≡ pos (suc n)} (<-irrefl 0 p) <-split-pos (pos (suc n)) p = n , refl <-split-neg : ∀ z → [ z < 0 ] → Σ[ n ∈ ℕ ] z ≡ neg (suc n) <-split-neg (pos zero) p = ⊥-elim {A = λ _ → Σ[ n ∈ ℕ ] posneg i0 ≡ neg (suc n)} (<-irrefl 0 p) <-split-neg (neg zero) p = ⊥-elim {A = λ _ → Σ[ n ∈ ℕ ] posneg i1 ≡ neg (suc n)} (<-irrefl 0 p) <-split-neg (posneg i) p = ⊥-elim {A = λ _ → Σ[ n ∈ ℕ ] posneg i ≡ neg (suc n)} (<-irrefl 0 p) <-split-neg (pos (suc m)) p = ⊥-elim {A = λ _ → Σ[ n ∈ ℕ ] pos (suc m) ≡ neg (suc n)} (¬suc<ⁿ0 m p) <-split-neg (neg (suc m)) p = m , refl #-split-abs : ∀ a → [ a # 0 ] → Σ[ x ∈ _ ] (abs a ≡ suc (abs x)) #-split-abs a (inl a<0) with <-split-neg a a<0; ... | (n , p) = neg n , λ i → abs (p i) #-split-abs a (inr 0<a) with <-split-pos a 0<a; ... | (n , p) = pos n , λ i → abs (p i) -- this is QuoInt.signed-zero signed0≡0 : ∀ s → signed s 0 ≡ 0 signed0≡0 spos = refl signed0≡0 sneg i = posneg (~ i) ·-sucIntʳ⁺ : ∀ m n → m · pos (suc n) ≡ m + m · pos n ·-sucIntʳ⁺ m n = ·-comm m (pos (suc n)) ∙ *-pos-suc n m ∙ (λ i → m + ·-comm (pos n) m i) signed-respects-+ : ∀ s a b → signed s (a +ⁿ b) ≡ signed s a + signed s b signed-respects-+ spos zero b = refl signed-respects-+ sneg zero b = refl signed-respects-+ spos (suc a) b i = sucℤ $ signed-respects-+ spos a b i signed-respects-+ sneg (suc a) b i = predℤ $ signed-respects-+ sneg a b i -- this is QuoInt.signed-inv sign-abs-identity : ∀ a → signed (sign a) (abs a) ≡ a sign-abs-identity (pos zero) j = posneg (i0 ∧ j) sign-abs-identity (neg zero) j = posneg (i1 ∧ j) sign-abs-identity (posneg i) j = posneg (i ∧ j) sign-abs-identity (pos (suc n)) = refl sign-abs-identity (neg (suc n)) = refl signed-reflects-≡₁ : ∀ s₁ s₂ n → signed s₁ (suc n) ≡ signed s₂ (suc n) → s₁ ≡ s₂ signed-reflects-≡₁ s₁ s₂ n p i = sign (p i) signed-reflects-≡₂ : ∀ s₁ s₂ a b → signed s₁ a ≡ signed s₂ b → a ≡ b signed-reflects-≡₂ s₁ s₂ a b p i = abs (p i) -abs : ∀ a → abs (- a) ≡ abs a -abs (signed s n) = refl -abs (posneg i) = refl -reflects-≡ : ∀ a b → - a ≡ - b → a ≡ b -reflects-≡ a b p = sym (negate-invol a) ∙ (λ i → - p i) ∙ negate-invol b abs-preserves-· : ∀ a b → abs (a · b) ≡ abs a ·ⁿ abs b abs-preserves-· a b = refl sign-abs-≡ : ∀ a b → sign a ≡ sign b → abs a ≡ abs b → a ≡ b sign-abs-≡ a b p q = transport (λ i → sign-abs-identity a i ≡ sign-abs-identity b i) λ i → signed (p i) (q i) 0<-sign : ∀ z → [ 0 < z ] → sign z ≡ spos 0<-sign z p i = sign $ <-split-pos z p .snd i <0-sign : ∀ z → [ z < 0 ] → sign z ≡ sneg <0-sign z p i = sign $ <-split-neg z p .snd i sign-pos : ∀ n → sign (pos n) ≡ spos sign-pos zero = refl sign-pos (suc n) = refl -- inj-*sm : l * suc m ≡ n * suc m → l ≡ n -- inj-*sm {zero} {m} {n} p = 0≡n*sm→0≡n p -- inj-*sm {l} {m} {zero} p = sym (0≡n*sm→0≡n (sym p)) -- inj-*sm {suc l} {m} {suc n} p = cong suc (inj-*sm (inj-m+ {m = suc m} p)) private lem1 : ∀ a x → sign a ≡ sign (signed (sign a) (abs a +ⁿ x ·ⁿ abs a)) lem1 (pos zero) x = sym $ sign-pos (x ·ⁿ 0) lem1 (neg zero) x = sym $ sign-pos (x ·ⁿ 0) lem1 (posneg i) x = sym $ sign-pos (x ·ⁿ 0) lem1 (pos (suc n)) x = refl lem1 (neg (suc n)) x = refl ·-reflects-≡ˡ⁺ : ∀ a b x → (pos (suc x)) · a ≡ (pos (suc x)) · b → a ≡ b ·-reflects-≡ˡ⁺ a b x p = sym (sign-abs-identity a) ∙ (λ i → signed (κ i) (γ i)) ∙ sign-abs-identity b where φ : suc x ·ⁿ abs a ≡ suc x ·ⁿ abs b φ = signed-reflects-≡₂ _ _ _ _ p γ : abs a ≡ abs b γ = ·ⁿ-reflects-≡ˡ' {x} {abs a} {abs b} φ κ = transport ( sign (signed (sign a) (suc x ·ⁿ abs a)) ≡ sign (signed (sign b) (suc x ·ⁿ abs b)) ≡⟨ (λ i → lem1 a x (~ i) ≡ lem1 b x (~ i)) ⟩ sign a ≡ sign b ∎) (λ i → sign (p i)) ·-reflects-≡ˡ⁻ : ∀ a b x → (neg (suc x)) · a ≡ (neg (suc x)) · b → a ≡ b ·-reflects-≡ˡ⁻ a b x p = sym (sign-abs-identity a) ∙ γ ∙ sign-abs-identity b where φ : suc x ·ⁿ abs a ≡ suc x ·ⁿ abs b φ = signed-reflects-≡₂ _ _ _ _ p κ : abs a ≡ abs b κ = ·ⁿ-reflects-≡ˡ' {x} {abs a} {abs b} φ γ : signed (sign a) (abs a) ≡ signed (sign b) (abs b) γ with #-dicho a ... | inl a#0 = -reflects-≡ _ _ (λ i → signed (θ i) (κ i)) where abstract c = #-split-abs a a#0 .fst q₁ : abs a ≡ suc (abs c) q₁ = #-split-abs a a#0 .snd q₂ : abs b ≡ suc (abs c) q₂ = sym κ ∙ q₁ θ : not (sign a) ≡ not (sign b) θ = signed-reflects-≡₁ _ _ _ (transport (λ i → signed (not (sign a)) (suc x ·ⁿ q₁ i) ≡ signed (not (sign b)) (suc x ·ⁿ q₂ i)) p) ... | inr a≡0 = cong₂ signed refl (λ i → abs (a≡0 i)) ∙ signed0≡0 (sign a) ∙ sym (signed0≡0 (sign b)) ∙ cong₂ signed refl ((λ i → abs (a≡0 (~ i))) ∙ κ) ·-reflects-≡ˡ : ∀ a b x → [ x # 0 ] → x · a ≡ x · b → a ≡ b ·-reflects-≡ˡ a b x (inl x<0) q = let (y , r) = <-split-neg x x<0 in ·-reflects-≡ˡ⁻ a b y (transport (λ i → r i · a ≡ r i · b) q) ·-reflects-≡ˡ a b x (inr 0<x) q = let (y , r) = <-split-pos x 0<x in ·-reflects-≡ˡ⁺ a b y (transport (λ i → r i · a ≡ r i · b) q) ·-reflects-≡ʳ : ∀ a b x → [ x # 0 ] → a · x ≡ b · x → a ≡ b ·-reflects-≡ʳ a b x p q = ·-reflects-≡ˡ a b x p (·-comm x a ∙ q ∙ ·-comm b x)
! ! Copyright (c) 2015, NVIDIA CORPORATION. All rights reserved. ! ! Licensed under the Apache License, Version 2.0 (the "License"); ! you may not use this file except in compliance with the License. ! You may obtain a copy of the License at ! ! http://www.apache.org/licenses/LICENSE-2.0 ! ! Unless required by applicable law or agreed to in writing, software ! distributed under the License is distributed on an "AS IS" BASIS, ! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ! See the License for the specific language governing permissions and ! limitations under the License. ! ! bind(c) complex function -- -O delete_stores() failure; derived from the ! entry test, ie10.f complex function cp1(i, j) bind(c) cp1 = cmplx(i, j) cp1 = cp1 + (1, 1) end interface complex function cp1(i, j) bind(c) endfunction endinterface integer(4) expect(2) integer(4) res(2) data expect/2,4/ complex z z = cp1(1,3) res(1) = real(z) res(2) = aimag(z) ! print *, z call check(res, expect, 2) end
lemmas linear_linear = linear_conv_bounded_linear[symmetric]
// This file is part of the dune-xt project: // https://zivgitlab.uni-muenster.de/ag-ohlberger/dune-community/dune-xt // Copyright 2009-2021 dune-xt developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2013 - 2017, 2019) // René Fritze (2013 - 2016, 2018 - 2020) // Sven Kaulmann (2013) // Tobias Leibner (2014, 2016, 2019 - 2020) #ifndef DUNE_XT_GRID_OUTPUT_ENTITY_VISUALIZATION_HH #define DUNE_XT_GRID_OUTPUT_ENTITY_VISUALIZATION_HH #include <boost/io/ios_state.hpp> #include <dune/grid/common/mcmgmapper.hh> #include <dune/grid/io/file/vtk/vtkwriter.hh> #include <dune/grid/common/rangegenerators.hh> #include <dune/xt/common/filesystem.hh> #include <dune/xt/common/logging.hh> #include <dune/xt/common/ranges.hh> #include <dune/xt/common/string.hh> #include <dune/xt/common/type_traits.hh> #include <dune/xt/grid/boundaryinfo/types.hh> #include <dune/xt/grid/capabilities.hh> #include <dune/xt/grid/type_traits.hh> #include <utility> namespace Dune::XT::Grid { struct ElementVisualization { // demonstrate attaching data to elements template <class View, class F> static void elementdata(const View& view, const F& f) { // make a mapper for codim 0 entities in the leaf grid using Grid = extract_grid_t<View>; Dune::MultipleCodimMultipleGeomTypeMapper<View> mapper(view, mcmgElementLayout()); std::vector<double> values(mapper.size()); for (auto&& entity : elements(view)) { values[mapper.index(entity)] = f(entity); } Dune::VTKWriter<typename Grid::LeafGridView> vtkwriter(view); vtkwriter.addCellData(values, "data"); const std::string piecefilesFolderName = "piecefiles"; const std::string piecefilesPath = f.dir() + "/" + piecefilesFolderName + "/"; Common::test_create_directory(piecefilesPath); vtkwriter.pwrite(f.filename(), f.dir(), piecefilesFolderName, Dune::VTK::appendedraw); } template <class GridViewType> class FunctorBase { public: using Element = extract_entity_t<GridViewType>; FunctorBase(std::string filename = "Functor", std::string dirname = ".") : filename_(std::move(filename)) , dir_(std::move(dirname)) {} virtual ~FunctorBase() = default; std::string filename() const { return filename_; } std::string dir() const { return dir_; } virtual double operator()(const Element& /*ent*/) const = 0; std::vector<double> values(const GridViewType& view) { std::vector<double> ret(view.size(0)); return ret; } protected: const std::string filename_; const std::string dir_; }; template <class GridViewType> class VolumeFunctor : public FunctorBase<GridViewType> { public: using Element = typename FunctorBase<GridViewType>::Element; VolumeFunctor(const std::string& filename = "VolumeFunctor", const std::string& dirname = ".") : FunctorBase<GridViewType>(filename, dirname) {} double operator()(const Element& ent) const { return ent.geometry().volume(); } }; template <class GridViewType> class ProcessIdFunctor : public FunctorBase<GridViewType> { public: using Element = typename FunctorBase<GridViewType>::Element; ProcessIdFunctor(const std::string& filename = "ProcessIDFunctor", const std::string& dirname = ".") : FunctorBase<GridViewType>(filename, dirname) {} double operator()(const Element& /*ent*/) const { return Dune::MPIHelper::getCollectiveCommunication().rank(); } }; template <class GridViewType, bool enable = has_boundary_id<GridViewType>::value> class BoundaryIDFunctor : public FunctorBase<GridViewType> { const GridViewType& gridview_; public: using Element = typename FunctorBase<GridViewType>::Element; BoundaryIDFunctor(const GridViewType& view, const std::string& filename = "BoundaryIDFunctor", const std::string& dirname = ".") : FunctorBase<GridViewType>(filename, dirname) , gridview_(view) {} double operator()(const Element& entity) const { double ret(0.0); int numberOfBoundarySegments(0); bool isOnBoundary = false; for (auto&& intersection : intersections(gridview_, entity)) { if (!intersection.neighbor() && intersection.boundary()) { isOnBoundary = true; numberOfBoundarySegments += 1; ret += double(intersection.boundaryId()); } } if (isOnBoundary) { ret /= double(numberOfBoundarySegments); } return ret; } }; template <class GridViewType> class BoundaryIDFunctor<GridViewType, false> : public FunctorBase<GridViewType> { const GridViewType& gridview_; public: using Element = typename FunctorBase<GridViewType>::Element; BoundaryIDFunctor(const GridViewType& view, const std::string& filename = "BoundaryIDFunctor", const std::string& dirname = ".") : FunctorBase<GridViewType>(filename, dirname) , gridview_(view) { DXTC_LOG_INFO_0 << "Boundary visualization for unsupported grid requested " << XT::Common::get_typename(gridview_) << std::endl; } double operator()(const Element&) const override { return -1; } }; template <class GridViewType, class BoundaryInfoType> class BoundaryTypeFunctor : public FunctorBase<GridViewType> { const GridViewType& gridview_; const std::string type_; const BoundaryInfoType& boundaryInfo_; public: using Element = typename FunctorBase<GridViewType>::Element; BoundaryTypeFunctor(const GridViewType& view, const BoundaryInfoType& boundaryInfo, std::string type, const std::string& filename = "BoundaryTypeFunctor", const std::string& dirname = ".") : FunctorBase<GridViewType>(filename, dirname) , gridview_(view) , type_(std::move(type)) , boundaryInfo_(boundaryInfo) {} double operator()(const Element& entity) const override { static constexpr DirichletBoundary dirichlet_type{}; static constexpr NeumannBoundary neumann_type{}; for (auto intersectionIt = gridview_.ibegin(entity); intersectionIt != gridview_.iend(entity); ++intersectionIt) { if (type_ == "dirichlet") { return (boundaryInfo_.type(*intersectionIt) == dirichlet_type); } if (type_ == "neumann") { return (boundaryInfo_.type(*intersectionIt) == neumann_type); } DUNE_THROW(Common::Exceptions::internal_error, "Unknown type '" << type_ << "'!"); } return 0; } }; template <class GridViewType> class AreaMarker : public FunctorBase<GridViewType> { public: using Element = typename FunctorBase<GridViewType>::Element; AreaMarker(const std::string& filename = "AreaFunctor", const std::string& dirname = ".") : FunctorBase<GridViewType>(filename, dirname) {} double operator()(const Element& entity) const { using EntityGeometryType = typename Element::Geometry; using DomainType = Dune::FieldVector<typename EntityGeometryType::ctype, EntityGeometryType::coorddimension>; const EntityGeometryType& geometry = entity.geometry(); DomainType baryCenter(0.0); for (auto corner : Common::value_range(geometry.corners())) { baryCenter += geometry.corner(corner); } baryCenter /= geometry.corners(); double ret(0.0); if (!((baryCenter[0] < 0.0) || (baryCenter[0] > 1.0))) { // only in unit square if (!((baryCenter[1] < 0.0) || (baryCenter[1] > 1.0))) { ret = 1.0; } } return ret; } }; template <class GridViewType> class GeometryFunctor : public FunctorBase<GridViewType> { public: using Element = typename FunctorBase<GridViewType>::Element; GeometryFunctor(const std::string& filename = "GeometryFunctor", const std::string& dirname = ".") : FunctorBase<GridViewType>(filename, dirname) {} double operator()(const Element& ent) const { const auto& geo = ent.geometry(); double vol = geo.volume(); if (vol < 0) { boost::io::ios_all_saver guard(DXTC_LOG_ERROR); DXTC_LOG_ERROR << std::setiosflags(std::ios::fixed) << std::setprecision(6) << std::setw(8); // std::cout.showpoint(); for (auto i : Common::value_range(geo.corners())) { DXTC_LOG_ERROR << geo.corner(i) << "\t\t"; } DXTC_LOG_ERROR << std::endl; } return vol; } }; template <class GridViewType> class PartitionTypeFunctor : public FunctorBase<GridViewType> { public: using Element = typename FunctorBase<GridViewType>::Element; PartitionTypeFunctor(const std::string& filename = "PartitionTypeFunctor", const std::string& dirname = ".") : FunctorBase<GridViewType>(filename, dirname) {} double operator()(const Element& ent) const { const int type{static_cast<int>(ent.partitionType())}; DXTC_LOG_ERROR << "TYPE " << type << std::endl; return static_cast<double>(type); } }; template <class GridViewType, bool enable = has_boundary_id<GridViewType>::value> class IndexFunctor : public FunctorBase<GridViewType> { const GridViewType& gridview_; public: using Element = typename FunctorBase<GridViewType>::Element; IndexFunctor(const GridViewType& view, const std::string& filename = "IndexFunctor", const std::string& dirname = ".") : FunctorBase<GridViewType>(filename, dirname) , gridview_(view) {} double operator()(const Element& entity) const override { return gridview_.indexSet().index(entity); } }; //! supply functor template <class Grid> static void all(const Grid& grid, const std::string& outputDir = "visualisation") { // make function objects BoundaryIDFunctor<Grid> boundaryFunctor(grid, "boundaryFunctor", outputDir); AreaMarker<Grid> areaMarker("areaMarker", outputDir); GeometryFunctor<Grid> geometryFunctor("geometryFunctor", outputDir); ProcessIdFunctor<Grid> processIdFunctor("ProcessIdFunctor", outputDir); VolumeFunctor<Grid> volumeFunctor("volumeFunctor", outputDir); PartitionTypeFunctor<Grid> partitionTypeFunctor("partitionTypeFunctor", outputDir); // call the visualization functions const auto view = grid.leafGridView(); elementdata(view, boundaryFunctor); elementdata(view, areaMarker); elementdata(view, geometryFunctor); elementdata(view, processIdFunctor); elementdata(view, volumeFunctor); elementdata(view, partitionTypeFunctor); } }; template <class GridType> void visualize_index_per_level(const GridType& grid_, const std::string& filename) { if (GridType::dimension > 3) DUNE_THROW(NotImplemented, "For grids of dimension > 3!"); for (auto lvl : Common::value_range(grid_.maxLevel() + 1)) { const auto grid_view = grid_.levelGridView(lvl); std::vector<double> entityId(grid_view.indexSet().size(0)); for (auto&& entity : elements(grid_view)) { const auto& index = grid_view.indexSet().index(entity); entityId[index] = double(index); } Dune::VTKWriter<decltype(grid_view)> vtkwriter(grid_view); vtkwriter.addCellData(entityId, "entity_id__level_" + Common::to_string(lvl)); vtkwriter.write(filename + "__level_" + Common::to_string(lvl), VTK::appendedraw); } } // ... visualize_plain(...) } // namespace Dune::XT::Grid #endif // DUNE_XT_GRID_OUTPUT_ENTITY_VISUALIZATION_HH
Formal statement is: lemma LIMSEQ_binaryset: assumes f: "f {} = 0" shows "(\<lambda>n. \<Sum>i<n. f (binaryset A B i)) \<longlonglongrightarrow> f A + f B" Informal statement is: If $f$ is a function that maps the empty set to $0$, then the sum of $f$ over the binary sets of $A$ and $B$ converges to $f(A) + f(B)$.
module Issue2447.Internal-error where import Issue2447.M {-# IMPOSSIBLE #-}
theory Imperative_Loops imports "Refine_Imperative_HOL.Sepref_HOL_Bindings" "Refine_Imperative_HOL.Pf_Mono_Prover" "Refine_Imperative_HOL.Pf_Add" begin section \<open>Imperative Loops\<close> text "An auxiliary while rule provided by Peter Lammich." lemma heap_WHILET_rule: assumes "wf R" "P \<Longrightarrow>\<^sub>A I s" "\<And>s. <I s * true> bi s <\<lambda>r. I s * \<up>(r \<longleftrightarrow> b s)>\<^sub>t" "\<And>s. b s \<Longrightarrow> <I s * true> f s <\<lambda>s'. I s' * \<up>((s', s) \<in> R)>\<^sub>t" "\<And>s. \<not> b s \<Longrightarrow> I s \<Longrightarrow>\<^sub>A Q s" shows "<P * true> heap_WHILET bi f s <Q>\<^sub>t" proof - have "<I s * true> heap_WHILET bi f s <\<lambda>s'. I s' * \<up>(\<not> b s')>\<^sub>t" using assms(1) proof (induction arbitrary:) case (less s) show ?case proof (cases "b s") case True then show ?thesis by (subst heap_WHILET_unfold) (sep_auto heap: assms(3,4) less) next case False then show ?thesis by (subst heap_WHILET_unfold) (sep_auto heap: assms(3)) qed qed then show ?thesis apply (rule cons_rule[rotated 2]) apply (intro ent_star_mono assms(2) ent_refl) apply clarsimp apply (intro ent_star_mono assms(5) ent_refl) . qed lemma heap_WHILET_rule': assumes "wf R" "P \<Longrightarrow>\<^sub>A I s si * F" "\<And>si s. <I s si * F> bi si <\<lambda>r. I s si * F * \<up>(r \<longleftrightarrow> b s)>\<^sub>t" "\<And>si s. b s \<Longrightarrow> <I s si * F> f si <\<lambda>si'. \<exists>\<^sub>As'. I s' si' * F * \<up>((s', s) \<in> R)>\<^sub>t" "\<And>si s. \<not> b s \<Longrightarrow> I s si * F \<Longrightarrow>\<^sub>A Q s si" shows "<P> heap_WHILET bi f si <\<lambda>si. \<exists>\<^sub>As. Q s si>\<^sub>t" proof - have "<I s si * F> heap_WHILET bi f si <\<lambda>si'. \<exists>\<^sub>As'. I s' si' * F * \<up>(\<not> b s')>\<^sub>t" using assms(1) proof (induction arbitrary: si) case (less s) show ?case proof (cases "b s") case True then show ?thesis apply (subst heap_WHILET_unfold) apply (sep_auto heap: assms(3,4) less) done next case False then show ?thesis by (subst heap_WHILET_unfold) (sep_auto heap: assms(3)) qed qed then show ?thesis apply (rule cons_rule[rotated 2]) apply (intro ent_star_mono assms(2) ent_refl) apply clarsimp apply (sep_auto ) apply (erule ent_frame_fwd[OF assms(5)]) apply frame_inference by sep_auto qed (* Added by NM, just a technicality since this rule fits our use case better *) text "I derived my own version, simply because it was a better fit to my use case." corollary heap_WHILET_rule'': assumes "wf R" "P \<Longrightarrow>\<^sub>A I s" "\<And>s. <I s * true> bi s <\<lambda>r. I s * \<up>(r \<longleftrightarrow> b s)>\<^sub>t" "\<And>s. b s \<Longrightarrow> <I s * true> f s <\<lambda>s'. I s' * \<up>((s', s) \<in> R)>\<^sub>t" "\<And>s. \<not> b s \<Longrightarrow> I s \<Longrightarrow>\<^sub>A Q s" shows "<P> heap_WHILET bi f s <Q>\<^sub>t" supply R = heap_WHILET_rule'[of R P "\<lambda>s si. \<up>(s = si) * I s" s _ true bi b f "\<lambda>s si.\<up>(s = si) * Q s * true"] thm R using assms ent_true_drop apply(sep_auto heap: R assms) done (* explicit proof: proof - have "<I s * true> heap_WHILET bi f s <\<lambda>s'. I s' * \<up>(\<not> b s')>\<^sub>t" using assms(1) proof (induction arbitrary:) case (less s) show ?case proof (cases "b s") case True then show ?thesis by (subst heap_WHILET_unfold) (sep_auto heap: assms(3,4) less) next case False then show ?thesis by (subst heap_WHILET_unfold) (sep_auto heap: assms(3)) qed qed then show ?thesis apply (rule cons_rule[rotated 2]) apply (intro ent_true_drop assms(2) ent_refl) apply clarsimp apply(intro ent_star_mono assms(5) ent_refl) . qed *) end
theory Ex1_7 imports Main begin primrec list_union :: "['a list , 'a list] \<Rightarrow> 'a list" where "list_union [] ys = ys"| "list_union (x # xs) ys = (let res = list_union xs ys in if x \<in> set res then res else x # res)" lemma "set (list_union xs ys) = set xs \<union> set ys" proof (induct xs) case Nil then show ?case by simp next case (Cons a xs) assume hyp:"set (list_union xs ys) = set xs \<union> set ys" let ?tmp = "list_union xs ys" have "set (list_union (a # xs) ys) = set (if a \<in> set ?tmp then ?tmp else a # ?tmp )" by simp then show ?case proof (cases "a \<in> set ?tmp") case True assume a:"a \<in> set (list_union xs ys)" then show ?thesis by (auto simp add : hyp) next case False then show ?thesis by (auto simp add : hyp) qed qed lemma [rule_format] : "distinct xs \<longrightarrow> distinct ys \<longrightarrow> (distinct (list_union xs ys))" proof (induct xs) case Nil then show ?case by simp next case (Cons a xs) assume hyp:"distinct xs \<longrightarrow> distinct ys \<longrightarrow> distinct (list_union xs ys)" show ?case proof (cases "a \<in> set (list_union xs ys)") case True assume "a \<in> set (list_union xs ys)" then show ?thesis using hyp by simp next case False assume "a \<notin> set (list_union xs ys)" then show ?thesis using hyp by simp qed qed lemma "((\<forall> x \<in> A . P x) \<and> (\<forall> x \<in> B . P x)) \<longrightarrow> (\<forall> x \<in> A \<union> B . P x)" using [[simp_trace_new mode=full]] proof - { assume a:"(\<forall> x \<in> A . P x) \<and> (\<forall> x \<in> B . P x)" hence b:"\<forall> x \<in> A . P x" by simp from a have c:"\<forall> x \<in> B . P x" by simp with b have "\<forall> x \<in> A \<union> B . P x" by auto } thus ?thesis by (rule impI) qed lemma "\<forall>x \<in> A . Q (f x) \<Longrightarrow> \<forall> y \<in> f ` A . Q y" by blast
[STATEMENT] lemma (in ring) eval_append: assumes "set p \<subseteq> carrier R" "set q \<subseteq> carrier R" and "a \<in> carrier R" shows "eval (p @ q) a = ((eval p a) \<otimes> (a [^] (length q))) \<oplus> (eval q a)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a [PROOF STEP] using assms(2) [PROOF STATE] proof (prove) using this: set q \<subseteq> carrier R goal (1 subgoal): 1. local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a [PROOF STEP] proof (induct "length q" arbitrary: q) [PROOF STATE] proof (state) goal (2 subgoals): 1. \<And>q. \<lbrakk>0 = length q; set q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a 2. \<And>x q. \<lbrakk>\<And>q. \<lbrakk>x = length q; set q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a; Suc x = length q; set q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a [PROOF STEP] case 0 [PROOF STATE] proof (state) this: 0 = length q set q \<subseteq> carrier R goal (2 subgoals): 1. \<And>q. \<lbrakk>0 = length q; set q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a 2. \<And>x q. \<lbrakk>\<And>q. \<lbrakk>x = length q; set q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a; Suc x = length q; set q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a [PROOF STEP] thus ?case [PROOF STATE] proof (prove) using this: 0 = length q set q \<subseteq> carrier R goal (1 subgoal): 1. local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a [PROOF STEP] using eval_in_carrier[OF assms(1,3)] [PROOF STATE] proof (prove) using this: 0 = length q set q \<subseteq> carrier R local.eval p a \<in> carrier R goal (1 subgoal): 1. local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a [PROOF STEP] by auto [PROOF STATE] proof (state) this: local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a goal (1 subgoal): 1. \<And>x q. \<lbrakk>\<And>q. \<lbrakk>x = length q; set q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a; Suc x = length q; set q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>x q. \<lbrakk>\<And>q. \<lbrakk>x = length q; set q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a; Suc x = length q; set q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a [PROOF STEP] case (Suc n) [PROOF STATE] proof (state) this: \<lbrakk>n = length ?q; set ?q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ ?q) a = local.eval p a \<otimes> a [^] length ?q \<oplus> local.eval ?q a Suc n = length q set q \<subseteq> carrier R goal (1 subgoal): 1. \<And>x q. \<lbrakk>\<And>q. \<lbrakk>x = length q; set q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a; Suc x = length q; set q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a [PROOF STEP] then [PROOF STATE] proof (chain) picking this: \<lbrakk>n = length ?q; set ?q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ ?q) a = local.eval p a \<otimes> a [^] length ?q \<oplus> local.eval ?q a Suc n = length q set q \<subseteq> carrier R [PROOF STEP] obtain b q' where q: "q = q' @ [ b ]" [PROOF STATE] proof (prove) using this: \<lbrakk>n = length ?q; set ?q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ ?q) a = local.eval p a \<otimes> a [^] length ?q \<oplus> local.eval ?q a Suc n = length q set q \<subseteq> carrier R goal (1 subgoal): 1. (\<And>q' b. q = q' @ [b] \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by (metis length_Suc_conv list.simps(3) rev_exhaust) [PROOF STATE] proof (state) this: q = q' @ [b] goal (1 subgoal): 1. \<And>x q. \<lbrakk>\<And>q. \<lbrakk>x = length q; set q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a; Suc x = length q; set q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a [PROOF STEP] hence in_carrier: "eval p a \<in> carrier R" "eval q' a \<in> carrier R" "a [^] (length q') \<in> carrier R" "b \<in> carrier R" [PROOF STATE] proof (prove) using this: q = q' @ [b] goal (1 subgoal): 1. (local.eval p a \<in> carrier R &&& local.eval q' a \<in> carrier R) &&& a [^] length q' \<in> carrier R &&& b \<in> carrier R [PROOF STEP] using assms(1,3) Suc(3) eval_in_carrier[OF _ assms(3)] [PROOF STATE] proof (prove) using this: q = q' @ [b] set p \<subseteq> carrier R a \<in> carrier R set q \<subseteq> carrier R set ?p \<subseteq> carrier R \<Longrightarrow> local.eval ?p a \<in> carrier R goal (1 subgoal): 1. (local.eval p a \<in> carrier R &&& local.eval q' a \<in> carrier R) &&& a [^] length q' \<in> carrier R &&& b \<in> carrier R [PROOF STEP] by auto [PROOF STATE] proof (state) this: local.eval p a \<in> carrier R local.eval q' a \<in> carrier R a [^] length q' \<in> carrier R b \<in> carrier R goal (1 subgoal): 1. \<And>x q. \<lbrakk>\<And>q. \<lbrakk>x = length q; set q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a; Suc x = length q; set q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a [PROOF STEP] have "eval (p @ q) a = ((eval (p @ q') a) \<otimes> a) \<oplus> b" [PROOF STATE] proof (prove) goal (1 subgoal): 1. local.eval (p @ q) a = local.eval (p @ q') a \<otimes> a \<oplus> b [PROOF STEP] using eval_append_aux[OF _ _ assms(3), of "p @ q'" b] assms(1) Suc(3) [PROOF STATE] proof (prove) using this: \<lbrakk>set (p @ q') \<subseteq> carrier R; b \<in> carrier R\<rbrakk> \<Longrightarrow> local.eval ((p @ q') @ [b]) a = local.eval (p @ q') a \<otimes> a \<oplus> b set p \<subseteq> carrier R set q \<subseteq> carrier R goal (1 subgoal): 1. local.eval (p @ q) a = local.eval (p @ q') a \<otimes> a \<oplus> b [PROOF STEP] unfolding q [PROOF STATE] proof (prove) using this: \<lbrakk>set (p @ q') \<subseteq> carrier R; b \<in> carrier R\<rbrakk> \<Longrightarrow> local.eval ((p @ q') @ [b]) a = local.eval (p @ q') a \<otimes> a \<oplus> b set p \<subseteq> carrier R set (q' @ [b]) \<subseteq> carrier R goal (1 subgoal): 1. local.eval (p @ q' @ [b]) a = local.eval (p @ q') a \<otimes> a \<oplus> b [PROOF STEP] by auto [PROOF STATE] proof (state) this: local.eval (p @ q) a = local.eval (p @ q') a \<otimes> a \<oplus> b goal (1 subgoal): 1. \<And>x q. \<lbrakk>\<And>q. \<lbrakk>x = length q; set q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a; Suc x = length q; set q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a [PROOF STEP] also [PROOF STATE] proof (state) this: local.eval (p @ q) a = local.eval (p @ q') a \<otimes> a \<oplus> b goal (1 subgoal): 1. \<And>x q. \<lbrakk>\<And>q. \<lbrakk>x = length q; set q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a; Suc x = length q; set q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a [PROOF STEP] have " ... = ((((eval p a) \<otimes> (a [^] (length q'))) \<oplus> (eval q' a)) \<otimes> a) \<oplus> b" [PROOF STATE] proof (prove) goal (1 subgoal): 1. local.eval (p @ q') a \<otimes> a \<oplus> b = (local.eval p a \<otimes> a [^] length q' \<oplus> local.eval q' a) \<otimes> a \<oplus> b [PROOF STEP] using Suc [PROOF STATE] proof (prove) using this: \<lbrakk>n = length ?q; set ?q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ ?q) a = local.eval p a \<otimes> a [^] length ?q \<oplus> local.eval ?q a Suc n = length q set q \<subseteq> carrier R goal (1 subgoal): 1. local.eval (p @ q') a \<otimes> a \<oplus> b = (local.eval p a \<otimes> a [^] length q' \<oplus> local.eval q' a) \<otimes> a \<oplus> b [PROOF STEP] unfolding q [PROOF STATE] proof (prove) using this: \<lbrakk>n = length ?q; set ?q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ ?q) a = local.eval p a \<otimes> a [^] length ?q \<oplus> local.eval ?q a Suc n = length (q' @ [b]) set (q' @ [b]) \<subseteq> carrier R goal (1 subgoal): 1. local.eval (p @ q') a \<otimes> a \<oplus> b = (local.eval p a \<otimes> a [^] length q' \<oplus> local.eval q' a) \<otimes> a \<oplus> b [PROOF STEP] by auto [PROOF STATE] proof (state) this: local.eval (p @ q') a \<otimes> a \<oplus> b = (local.eval p a \<otimes> a [^] length q' \<oplus> local.eval q' a) \<otimes> a \<oplus> b goal (1 subgoal): 1. \<And>x q. \<lbrakk>\<And>q. \<lbrakk>x = length q; set q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a; Suc x = length q; set q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a [PROOF STEP] also [PROOF STATE] proof (state) this: local.eval (p @ q') a \<otimes> a \<oplus> b = (local.eval p a \<otimes> a [^] length q' \<oplus> local.eval q' a) \<otimes> a \<oplus> b goal (1 subgoal): 1. \<And>x q. \<lbrakk>\<And>q. \<lbrakk>x = length q; set q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a; Suc x = length q; set q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a [PROOF STEP] have " ... = (((eval p a) \<otimes> ((a [^] (length q')) \<otimes> a))) \<oplus> (((eval q' a) \<otimes> a) \<oplus> b)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (local.eval p a \<otimes> a [^] length q' \<oplus> local.eval q' a) \<otimes> a \<oplus> b = local.eval p a \<otimes> (a [^] length q' \<otimes> a) \<oplus> (local.eval q' a \<otimes> a \<oplus> b) [PROOF STEP] using assms(3) in_carrier [PROOF STATE] proof (prove) using this: a \<in> carrier R local.eval p a \<in> carrier R local.eval q' a \<in> carrier R a [^] length q' \<in> carrier R b \<in> carrier R goal (1 subgoal): 1. (local.eval p a \<otimes> a [^] length q' \<oplus> local.eval q' a) \<otimes> a \<oplus> b = local.eval p a \<otimes> (a [^] length q' \<otimes> a) \<oplus> (local.eval q' a \<otimes> a \<oplus> b) [PROOF STEP] by algebra [PROOF STATE] proof (state) this: (local.eval p a \<otimes> a [^] length q' \<oplus> local.eval q' a) \<otimes> a \<oplus> b = local.eval p a \<otimes> (a [^] length q' \<otimes> a) \<oplus> (local.eval q' a \<otimes> a \<oplus> b) goal (1 subgoal): 1. \<And>x q. \<lbrakk>\<And>q. \<lbrakk>x = length q; set q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a; Suc x = length q; set q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a [PROOF STEP] also [PROOF STATE] proof (state) this: (local.eval p a \<otimes> a [^] length q' \<oplus> local.eval q' a) \<otimes> a \<oplus> b = local.eval p a \<otimes> (a [^] length q' \<otimes> a) \<oplus> (local.eval q' a \<otimes> a \<oplus> b) goal (1 subgoal): 1. \<And>x q. \<lbrakk>\<And>q. \<lbrakk>x = length q; set q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a; Suc x = length q; set q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a [PROOF STEP] have " ... = (eval p a) \<otimes> (a [^] (length q)) \<oplus> (eval q a)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. local.eval p a \<otimes> (a [^] length q' \<otimes> a) \<oplus> (local.eval q' a \<otimes> a \<oplus> b) = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a [PROOF STEP] using eval_append_aux[OF _ in_carrier(4) assms(3), of q'] Suc(3) [PROOF STATE] proof (prove) using this: set q' \<subseteq> carrier R \<Longrightarrow> local.eval (q' @ [b]) a = local.eval q' a \<otimes> a \<oplus> b set q \<subseteq> carrier R goal (1 subgoal): 1. local.eval p a \<otimes> (a [^] length q' \<otimes> a) \<oplus> (local.eval q' a \<otimes> a \<oplus> b) = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a [PROOF STEP] unfolding q [PROOF STATE] proof (prove) using this: set q' \<subseteq> carrier R \<Longrightarrow> local.eval (q' @ [b]) a = local.eval q' a \<otimes> a \<oplus> b set (q' @ [b]) \<subseteq> carrier R goal (1 subgoal): 1. local.eval p a \<otimes> (a [^] length q' \<otimes> a) \<oplus> (local.eval q' a \<otimes> a \<oplus> b) = local.eval p a \<otimes> a [^] length (q' @ [b]) \<oplus> local.eval (q' @ [b]) a [PROOF STEP] by auto [PROOF STATE] proof (state) this: local.eval p a \<otimes> (a [^] length q' \<otimes> a) \<oplus> (local.eval q' a \<otimes> a \<oplus> b) = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a goal (1 subgoal): 1. \<And>x q. \<lbrakk>\<And>q. \<lbrakk>x = length q; set q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a; Suc x = length q; set q \<subseteq> carrier R\<rbrakk> \<Longrightarrow> local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a [PROOF STEP] finally [PROOF STATE] proof (chain) picking this: local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a [PROOF STEP] show ?case [PROOF STATE] proof (prove) using this: local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a goal (1 subgoal): 1. local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a [PROOF STEP] . [PROOF STATE] proof (state) this: local.eval (p @ q) a = local.eval p a \<otimes> a [^] length q \<oplus> local.eval q a goal: No subgoals! [PROOF STEP] qed
# Indexing at a point @inline function (itp::GriddedInterpolation{T,N})(x::Vararg{Number,N}) where {T,N} @boundscheck (checkbounds(Bool, itp, x...) || Base.throw_boundserror(itp, x)) wis = weightedindexes((value_weights,), itpinfo(itp)..., x) coefficients(itp)[wis...] end @inline function (itp::GriddedInterpolation)(x::Vararg{UnexpandedIndexTypes}) itp(to_indices(itp, x)...) end @inline function gradient(itp::GriddedInterpolation{T,N}, x::Vararg{Number,N}) where {T,N} @boundscheck (checkbounds(Bool, itp, x...) || Base.throw_boundserror(itp, x)) wis = weightedindexes((value_weights, gradient_weights), itpinfo(itp)..., x) SVector(map(inds->coefficients(itp)[inds...], wis)) end itpinfo(itp::GriddedInterpolation) = (tcollect(itpflag, itp), itp.knots) weightedindex_parts(fs::F, itpflag::Gridded, ax, x) where F = weightedindex_parts(fs, degree(itpflag), ax, x) roundbounds(x::Integer, knotvec::AbstractVector) = gridded_roundbounds(x, knotvec) roundbounds(x::Number, knotvec::AbstractVector) = gridded_roundbounds(x, knotvec) function gridded_roundbounds(x, knotvec::AbstractVector) i = find_knot_index(knotvec, x) iclamp = max(i, first(axes1(knotvec))) inext = min(iclamp+1, last(axes1(knotvec))) ifelse(i < iclamp, i+1, ifelse(x - knotvec[iclamp] < knotvec[inext] - x, i, inext)) end floorbounds(x::Integer, knotvec::AbstractVector) = gridded_floorbounds(x, knotvec) floorbounds(x, knotvec::AbstractVector) = gridded_floorbounds(x, knotvec) function gridded_floorbounds(x, knotvec::AbstractVector) i = find_knot_index(knotvec, x) max(i, first(axes1(knotvec))) end @inline find_knot_index(knotv, x) = searchsortedfirst(knotv, x, first(axes1(knotv)), length(knotv), Base.Order.ForwardOrdering()) - 1 function weightedindex_parts(fs::F, deg::Degree, knotvec::AbstractVector, x) where F i = find_knot_index(knotvec, x) ax1 = axes1(knotvec) iclamp = clamp(i, first(ax1), last(ax1)-1) weightedindex(fs, deg, knotvec, x, iclamp) end function weightedindex(fs::F, deg::Constant, knotvec, x, iclamp) where F pos, δx = positions(deg, knotvec, x) (position=pos, coefs=fmap(fs, deg, δx)) end function weightedindex(fs::F, deg::Degree, knotvec, x, iclamp) where F @inbounds l, u = knotvec[iclamp], knotvec[iclamp+1] δx = (x - l)/(u - l) (position=iclamp, coefs=rescale_gridded(fs, fmap(fs, deg, δx), u-l)) end rescale_gridded(fs::F, coefs, Δx) where F = (rescale_gridded(fs[1], coefs[1], Δx), rescale_gridded(Base.tail(fs), Base.tail(coefs), Δx)...) rescale_gridded(::Tuple{}, ::Tuple{}, Δx) = () rescale_gridded(::typeof(value_weights), coefs, Δx) = coefs rescale_gridded(::typeof(gradient_weights), coefs, Δx) = coefs./Δx rescale_gridded(::typeof(hessian_weights), coefs, Δx) = coefs./Δx.^2 @inline function (itp::GriddedInterpolation{T,N})(x::Vararg{Union{Number,AbstractVector},N}) where {T,N} @boundscheck (checkbounds(Bool, itp, x...) || Base.throw_boundserror(itp, x)) itps = tcollect(itpflag, itp) wis = dimension_wis(value_weights, itps, itp.knots, x) coefs = coefficients(itp) ret = [coefs[i...] for i in Iterators.product(wis...)] reshape(ret, shape(wis...)) end function dimension_wis(f::F, itps, knots, xs) where F itpflag, knotvec, x = itps[1], knots[1], xs[1] function makewi(y) pos, coefs = weightedindex_parts((f,), itpflag, knotvec, y) maybe_weightedindex(pos, coefs[1]) end (makewi.(x), dimension_wis(f, Base.tail(itps), Base.tail(knots), Base.tail(xs))...) end function dimension_wis(f::F, itps::Tuple{NoInterp,Vararg{Any}}, knots, xs) where F (Int.(xs[1]), dimension_wis(f, Base.tail(itps), Base.tail(knots), Base.tail(xs))...) end dimension_wis(f, ::Tuple{}, ::Tuple{}, ::Tuple{}) = () function getindex_return_type(::Type{GriddedInterpolation{T,N,TCoefs,IT,K}}, argtypes) where {T,N,TCoefs,IT<:DimSpec{Gridded},K} Tret = TCoefs for a in argtypes Tret = Base.promote_op(*, Tret, a) end Tret end
That I might drink , and leave the world unseen ,
------------------------------------------------------------------------ -- The Agda standard library -- -- Vector equality over propositional equality ------------------------------------------------------------------------ {-# OPTIONS --without-K --safe #-} open import Relation.Binary module Data.Vec.Relation.Binary.Equality.Propositional {a} {A : Set a} where open import Data.Nat.Base using (ℕ; zero; suc; _+_) open import Data.Vec open import Data.Vec.Relation.Binary.Pointwise.Inductive using (Pointwise-≡⇒≡; ≡⇒Pointwise-≡) import Data.Vec.Relation.Binary.Equality.Setoid as SEq open import Relation.Binary.PropositionalEquality ------------------------------------------------------------------------ -- Publically re-export everything from setoid equality open SEq (setoid A) public ------------------------------------------------------------------------ -- ≋ is propositional ≋⇒≡ : ∀ {n} {xs ys : Vec A n} → xs ≋ ys → xs ≡ ys ≋⇒≡ = Pointwise-≡⇒≡ ≡⇒≋ : ∀ {n} {xs ys : Vec A n} → xs ≡ ys → xs ≋ ys ≡⇒≋ = ≡⇒Pointwise-≡ -- See also Data.Vec.Relation.Binary.Equality.Propositional.WithK.≋⇒≅.
/- Copyright (c) 2022 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser ! This file was ported from Lean 3 source module group_theory.group_action.embedding ! leanprover-community/mathlib commit a437a2499163d85d670479f69f625f461cc5fef9 ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathlib.GroupTheory.GroupAction.Group import Mathlib.GroupTheory.GroupAction.Pi /-! # Group actions on embeddings This file provides a `MulAction G (α ↪ β)` instance that agrees with the `MulAction G (α → β)` instances defined by `Pi.mulAction`. Note that unlike the `Pi` instance, this requires `G` to be a group. -/ universe u v w variable {G G' α β : Type _} namespace Function.Embedding @[to_additive] instance smul [Group G] [MulAction G β] : SMul G (α ↪ β) := ⟨fun g f => f.trans (MulAction.toPerm g).toEmbedding⟩ @[to_additive] theorem smul_def [Group G] [MulAction G β] (g : G) (f : α ↪ β) : g • f = f.trans (MulAction.toPerm g).toEmbedding := rfl #align function.embedding.smul_def Function.Embedding.smul_def #align function.embedding.vadd_def Function.Embedding.vadd_def @[to_additive (attr := simp)] theorem smul_apply [Group G] [MulAction G β] (g : G) (f : α ↪ β) (a : α) : (g • f) a = g • f a := rfl #align function.embedding.smul_apply Function.Embedding.smul_apply #align function.embedding.vadd_apply Function.Embedding.vadd_apply @[to_additive] theorem coe_smul [Group G] [MulAction G β] (g : G) (f : α ↪ β) : ⇑(g • f) = g • ⇑f := rfl #align function.embedding.coe_smul Function.Embedding.coe_smul #align function.embedding.coe_vadd Function.Embedding.coe_vadd instance [Group G] [Group G'] [SMul G G'] [MulAction G β] [MulAction G' β] [IsScalarTower G G' β] : IsScalarTower G G' (α ↪ β) := ⟨fun x y z => Function.Embedding.ext fun i => smul_assoc x y (z i)⟩ @[to_additive] instance [Group G] [Group G'] [MulAction G β] [MulAction G' β] [SMulCommClass G G' β] : SMulCommClass G G' (α ↪ β) := ⟨fun x y z => Function.Embedding.ext fun i => smul_comm x y (z i)⟩ instance [Group G] [MulAction G β] [MulAction Gᵐᵒᵖ β] [IsCentralScalar G β] : IsCentralScalar G (α ↪ β) := ⟨fun _ _ => Function.Embedding.ext fun _ => op_smul_eq_smul _ _⟩ @[to_additive] instance [Group G] [MulAction G β] : MulAction G (α ↪ β) := FunLike.coe_injective.mulAction _ coe_smul end Function.Embedding
[STATEMENT] lemma square_part_1 [simp]: "square_part 1 = 1" [PROOF STATE] proof (prove) goal (1 subgoal): 1. square_part (1::'a) = (1::'a) [PROOF STEP] by simp
-- --------------------------------------------------------------------- -- Ejercicio. Demostrar que los primos mayores que 2 son impares. -- ---------------------------------------------------------------------- import data.nat.prime data.nat.parity tactic open set nat example : { n | prime n } ∩ { n | n > 2} ⊆ { n | ¬ even n } := begin intro n, simp, intro nprime, cases prime.eq_two_or_odd nprime with h h, { rw h, intro, linarith }, { rw even_iff, rw h, norm_num }, end -- Prueba -- ====== /- ⊢ {n : ℕ | n.prime} ∩ {n : ℕ | n > 2} ⊆ {n : ℕ | ¬n.even} >> intro n, n : ℕ ⊢ n ∈ {n : ℕ | n.prime} ∩ {n : ℕ | n > 2} → n ∈ {n : ℕ | ¬n.even} >> simp, ⊢ n.prime → 2 < n → ¬n.even >> intro nprime, nprime : n.prime ⊢ 2 < n → ¬n.even >> cases prime.eq_two_or_odd nprime with h h, | h : n = 2 | ⊢ 2 < n → ¬n.even | >> { rw h, | ⊢ 2 < 2 → ¬2.even | >> intro, | a : 2 < 2 | ⊢ ¬2.even | >> linarith }, h : n % 2 = 1 ⊢ 2 < n → ¬n.even >> { rw even_iff, ⊢ 2 < n → ¬n % 2 = 0 >> rw h, ⊢ 2 < n → ¬1 = 0 >> norm_num }, no goals -/ -- Comentario: Se han usado los lemas -- + prime.eq_two_or_odd : p.prime → p = 2 ∨ p % 2 = 1 -- + even_iff : even n ↔ n % 2 = 0 variables (n p : ℕ) -- #check @prime.eq_two_or_odd p -- #check @even_iff n
State Before: α✝ : Type ?u.31102 α : Type u inst✝ : DecidableEq α l : List α l' : List (Multiset α) H : ∀ ⦃x : Multiset α × Multiset α⦄, x ∈ revzip l' → x.fst + x.snd = ↑l ⊢ revzip l' = List.map (fun x => (x, ↑l - x)) l' State After: α✝ : Type ?u.31102 α : Type u inst✝ : DecidableEq α l : List α l' : List (Multiset α) H : ∀ ⦃x : Multiset α × Multiset α⦄, x ∈ revzip l' → x.fst + x.snd = ↑l this : Forall₂ (fun p s => p = (s, ↑l - s)) (revzip l') (List.map Prod.fst (revzip l')) ⊢ revzip l' = List.map (fun x => (x, ↑l - x)) l' Tactic: have : Forall₂ (fun (p : Multiset α × Multiset α) (s : Multiset α) => p = (s, ↑l - s)) (revzip l') ((revzip l').map Prod.fst) := by rw [forall₂_map_right_iff, forall₂_same] rintro ⟨s, t⟩ h dsimp rw [← H h, add_tsub_cancel_left] State Before: α✝ : Type ?u.31102 α : Type u inst✝ : DecidableEq α l : List α l' : List (Multiset α) H : ∀ ⦃x : Multiset α × Multiset α⦄, x ∈ revzip l' → x.fst + x.snd = ↑l this : Forall₂ (fun p s => p = (s, ↑l - s)) (revzip l') (List.map Prod.fst (revzip l')) ⊢ revzip l' = List.map (fun x => (x, ↑l - x)) l' State After: α✝ : Type ?u.31102 α : Type u inst✝ : DecidableEq α l : List α l' : List (Multiset α) H : ∀ ⦃x : Multiset α × Multiset α⦄, x ∈ revzip l' → x.fst + x.snd = ↑l this : Forall₂ (fun p s => p = (s, ↑l - s)) (revzip l') (List.map Prod.fst (revzip l')) ⊢ Forall₂ (fun a c => a = (c, ↑l - c)) (revzip l') l' Tactic: rw [← forall₂_eq_eq_eq, forall₂_map_right_iff] State Before: α✝ : Type ?u.31102 α : Type u inst✝ : DecidableEq α l : List α l' : List (Multiset α) H : ∀ ⦃x : Multiset α × Multiset α⦄, x ∈ revzip l' → x.fst + x.snd = ↑l this : Forall₂ (fun p s => p = (s, ↑l - s)) (revzip l') (List.map Prod.fst (revzip l')) ⊢ Forall₂ (fun a c => a = (c, ↑l - c)) (revzip l') l' State After: no goals Tactic: simpa using this State Before: α✝ : Type ?u.31102 α : Type u inst✝ : DecidableEq α l : List α l' : List (Multiset α) H : ∀ ⦃x : Multiset α × Multiset α⦄, x ∈ revzip l' → x.fst + x.snd = ↑l ⊢ Forall₂ (fun p s => p = (s, ↑l - s)) (revzip l') (List.map Prod.fst (revzip l')) State After: α✝ : Type ?u.31102 α : Type u inst✝ : DecidableEq α l : List α l' : List (Multiset α) H : ∀ ⦃x : Multiset α × Multiset α⦄, x ∈ revzip l' → x.fst + x.snd = ↑l ⊢ ∀ (x : Multiset α × Multiset α), x ∈ revzip l' → x = (x.fst, ↑l - x.fst) Tactic: rw [forall₂_map_right_iff, forall₂_same] State Before: α✝ : Type ?u.31102 α : Type u inst✝ : DecidableEq α l : List α l' : List (Multiset α) H : ∀ ⦃x : Multiset α × Multiset α⦄, x ∈ revzip l' → x.fst + x.snd = ↑l ⊢ ∀ (x : Multiset α × Multiset α), x ∈ revzip l' → x = (x.fst, ↑l - x.fst) State After: case mk α✝ : Type ?u.31102 α : Type u inst✝ : DecidableEq α l : List α l' : List (Multiset α) H : ∀ ⦃x : Multiset α × Multiset α⦄, x ∈ revzip l' → x.fst + x.snd = ↑l s t : Multiset α h : (s, t) ∈ revzip l' ⊢ (s, t) = ((s, t).fst, ↑l - (s, t).fst) Tactic: rintro ⟨s, t⟩ h State Before: case mk α✝ : Type ?u.31102 α : Type u inst✝ : DecidableEq α l : List α l' : List (Multiset α) H : ∀ ⦃x : Multiset α × Multiset α⦄, x ∈ revzip l' → x.fst + x.snd = ↑l s t : Multiset α h : (s, t) ∈ revzip l' ⊢ (s, t) = ((s, t).fst, ↑l - (s, t).fst) State After: case mk α✝ : Type ?u.31102 α : Type u inst✝ : DecidableEq α l : List α l' : List (Multiset α) H : ∀ ⦃x : Multiset α × Multiset α⦄, x ∈ revzip l' → x.fst + x.snd = ↑l s t : Multiset α h : (s, t) ∈ revzip l' ⊢ (s, t) = (s, ↑l - s) Tactic: dsimp State Before: case mk α✝ : Type ?u.31102 α : Type u inst✝ : DecidableEq α l : List α l' : List (Multiset α) H : ∀ ⦃x : Multiset α × Multiset α⦄, x ∈ revzip l' → x.fst + x.snd = ↑l s t : Multiset α h : (s, t) ∈ revzip l' ⊢ (s, t) = (s, ↑l - s) State After: no goals Tactic: rw [← H h, add_tsub_cancel_left]
State Before: a b : Int e : b = ↑(natAbs b) ⊢ a ∣ ↑(natAbs b) ↔ a ∣ b State After: no goals Tactic: rw [← e] State Before: a b : Int e : b = -↑(natAbs b) ⊢ a ∣ ↑(natAbs b) ↔ a ∣ b State After: no goals Tactic: rw [← Int.dvd_neg, ← e]
State Before: α : Type u β : Type v γ : Type w c : Computation (WSeq α) s : WSeq α h : s ∈ c ⊢ flatten c ~ʷ s State After: case h1 α : Type u β : Type v γ : Type w c : Computation (WSeq α) s : WSeq α h : s ∈ c ⊢ flatten (Computation.pure s) ~ʷ s case h2 α : Type u β : Type v γ : Type w c : Computation (WSeq α) s : WSeq α h : s ∈ c ⊢ ∀ (s_1 : Computation (WSeq α)), flatten s_1 ~ʷ s → flatten (Computation.think s_1) ~ʷ s Tactic: apply Computation.memRecOn h State Before: case h1 α : Type u β : Type v γ : Type w c : Computation (WSeq α) s : WSeq α h : s ∈ c ⊢ flatten (Computation.pure s) ~ʷ s State After: no goals Tactic: simp [Equiv.refl] State Before: case h2 α : Type u β : Type v γ : Type w c : Computation (WSeq α) s : WSeq α h : s ∈ c ⊢ ∀ (s_1 : Computation (WSeq α)), flatten s_1 ~ʷ s → flatten (Computation.think s_1) ~ʷ s State After: case h2 α : Type u β : Type v γ : Type w c : Computation (WSeq α) s : WSeq α h : s ∈ c s' : Computation (WSeq α) ⊢ flatten s' ~ʷ s → flatten (Computation.think s') ~ʷ s Tactic: intro s' State Before: case h2 α : Type u β : Type v γ : Type w c : Computation (WSeq α) s : WSeq α h : s ∈ c s' : Computation (WSeq α) ⊢ flatten s' ~ʷ s → flatten (Computation.think s') ~ʷ s State After: case h2.a α : Type u β : Type v γ : Type w c : Computation (WSeq α) s : WSeq α h : s ∈ c s' : Computation (WSeq α) ⊢ flatten (Computation.think s') ~ʷ flatten s' Tactic: apply Equiv.trans State Before: case h2.a α : Type u β : Type v γ : Type w c : Computation (WSeq α) s : WSeq α h : s ∈ c s' : Computation (WSeq α) ⊢ flatten (Computation.think s') ~ʷ flatten s' State After: no goals Tactic: simp [think_equiv]
function model = read_svm_detection_weights( filepath ) load(filepath, 'weights', 'bias'); model = {weights; bias}; end
State Before: α β ι : Type u c : ι → Cardinal ⊢ lift (prod c) = prod fun i => lift (c i) State After: case intro α β ι : Type u c : ι → Type v ⊢ lift (prod fun i => #c i) = prod fun i => lift ((fun i => #c i) i) Tactic: lift c to ι → Type v using fun _ => trivial State Before: case intro α β ι : Type u c : ι → Type v ⊢ lift (prod fun i => #c i) = prod fun i => lift ((fun i => #c i) i) State After: case intro α β ι : Type u c : ι → Type v ⊢ (#ULift ((i : ι) → c i)) = (#(i : ι) → ULift (c i)) Tactic: simp only [← mk_pi, ← mk_uLift] State Before: case intro α β ι : Type u c : ι → Type v ⊢ (#ULift ((i : ι) → c i)) = (#(i : ι) → ULift (c i)) State After: no goals Tactic: exact mk_congr (Equiv.ulift.trans <| Equiv.piCongrRight fun i => Equiv.ulift.symm)
Length : 16 @.@ 45 m ( 53 ft 11 ½ in )
# ニコニコAIスクール 第2回 機械学習入門 基礎演習 ## 今日の目標 * 機械学習の目的及び種類とその評価方法を理解する。 * 第1回に引き続き、numpyで頻出する関数の使い方を実践的に理解する。 * csvファイルを題材として、実データの読み書きができる。 * k-NN法を理解し、それをnumpyを用いて実装できる。 ## 目次 * 総和、平均、最大値、最小値(np.sum, np.mean, np.max, np.min) * L2ノルム (np.linalg.norm) * 数学関数 (np.sin, np.cos, np.tah, np.exp, np.log など) * 乱数生成 (np.random.random, np.random.normal) * ソート関連(np.sort, np.argsort) * ユークリッド距離・コサイン類似度 * ファイル入出力 # はじめに * エラーがでたら落ち着いてエラーを読んでみましょう(エラーを恐れる必要はありません) * エラーを読んでも理解できない場合は,エラー文をそのままググると解決法が見つかることが多いです * 詰まったな,と思ったら気軽に質問して下さい * numpyはドキュメントが充実しています.こんな計算出来ないだろうか,この関数の引数について知りたい,といった場合はドキュメントを見ると解決することが多いです (https://docs.scipy.org/doc/) ## Colaboratoryことはじめ * コードの編集:各セルをクリックして、直接編集 * コードの実行:セル左上の再生ボタンをクリックまたはShift+Enter * 実行停止:セル左上の停止ボタンをクリック * Notebook中のコードを全て実行:"Runtime"->"Run all" * 再起動:"Runtime"->"Restart runtime" * 出力のクリア:"Edit"->"Clear all outputs" 詳しい操作はチュートリアルを参照してください。 ### Jupyter notebookとの比較 |操作|Colaboratory|Jupyter Notebook| |:--|--:|--:| |コードの編集|セルをクリック|セルをクリック| |コードの実行|セル左上の再生ボタン|画面上の再生ボタン| |実行停止|セル左上の停止ボタン|画面上の停止ボタン| |全て実行|"Runtime"->"Run all"|"Cell"->"Run all"| |再起動|"Runtime"->"Restart runtime"|"Kernel"->"Restart"| |クリア|"Edit"->"Clear all outputs"|"Kernel"->"Restart and clear output"| ## この演習をJupyter notebook上で実行したい方へ Pythonは通常インデントの幅を4とすることが多いのですが、Colaboratoryのデフォルトのインデント幅は例外的に2になっています。 そこで、本来デフォルトの4に設定されているJupyter notebook側の設定を変更する必要があります。 もしこの演習をJupyter notebook上で実行したい場合は、次の指示に従ってください: 1. "F12"キーを押して、出てきた画面内の「コンソール (Console)」タブをクリック 2. 次のコードをコンソールに入力、実行: ``` var cell = Jupyter.notebook.get_selected_cell(); var config = cell.config; var patch = { CodeCell:{ cm_config:{indentUnit:2} } } config.update(patch) ``` もし設定を戻したい場合は、同様に次のコードを実行すると戻ります: ``` var cell = Jupyter.notebook.get_selected_cell(); var config = cell.config; var patch = { CodeCell:{ cm_config:{indentUnit: null} // only change here. } } config.update(patch) ``` 参考:http://jupyter-notebook.readthedocs.io/en/stable/frontend_config.html ただし、一部の画像の表示が乱れる場合があります。 # 1. Numpy入門 (2) ```python import numpy as np # numpyを'np'という名前でインポートする ``` ## 配列の総和、平均、最大値、最小値 (np.sum, np.mean, np.max, np.min) * ベクトルの最大値を得る * データの平均を計算する * 行列の各行の最小値を得る などの操作は非常に頻繁に現れます。Numpyでは、配列の形状にかかわらず上記の操作を1行で書くことができます。 ```python # 長さ5のベクトル x = np.array([0.1, 0.2, 0.3, 0.4, 0.5]) x.shape ``` ```python # np.sum: 配列の総和 np.sum(x) ``` ```python # np.mean: 配列の平均 np.mean(x) ``` ```python # np.max: 配列の最大値 np.max(x) ``` ```python # np.min: 配列の最小値 np.min(x) ``` ```python # 同じ操作を多次元配列で行ってみる X = np.random.random((5, 10)) # (5, 10)の乱数行列を生成 (後述) X.shape ``` ```python print(np.sum(X)) print(np.mean(X)) print(np.max(X)) print(np.min(X)) ``` ### axis (軸) の指定 上記の関数は、デフォルトでは配列全体にたいして1つの値しか返しません。 「各行 (0軸目)」「各列 (1軸目)」などの特定の軸上で平均値等を計算したい場合には**axisキーワード**を指定します。 軸のインデックスは0から始まります。 ```python print(np.sum(X, axis=0)) # 各行 (0軸目) の総和を求める (各要素は1行=5つの総和) print(np.sum(X, axis=0).shape) # 結果は1次元配列になる ``` ```python print(np.sum(X, axis=1)) # 各列 (1軸目) の総和を求める (各要素は1列=10個の総和) print(np.sum(X, axis=1).shape) # 結果は1次元配列になる ``` ## 最大/最小値のインデックスを取る (np.argmax, np.argmin) さて、これで配列中の最大/最小値を取ることが出きました。 では、**最大・最小値をとる要素が配列中のどこにあるのか**がほしい場合はどうすればいいでしょう? np.argmaxとnp.argminを使いましょう! ```python # 長さ5のベクトル x = np.array([0.1, 0.2, 0.3, 0.4, 0.5]) x.shape ``` ```python np.argmax(x) # -> 4 (5つ目の要素) ``` ```python np.argmin(x) # -> 0 (1つ目の要素) ``` ## 書いてみよう:配列の操作 1. [1, 2, ..., 10]なるベクトルをnp.arange関数で作成し、その総和と平均を計算せよ。 2. 多値分類問題では、「サンプルiがクラスcに所属する確率」を(N, C)の行列に格納し、各サンプルにおいて最も大きい確率を取るインデックスをとる処理が行われる。 y = XW + bを計算し、np.argmax関数を使って最大値を得るインデックスを計算せよ。 ```python # Q1 # WRITE ME! ``` ```python # Q2 N = 10 D = 2 C = 5 X = np.random.random((N, D)) W = np.random.random((D, C)) b = np.random.random((1, C)) # ブロードキャスティングができるように0次元目に1を詰める # WRITE ME! # まずXW + bを計算 (行列積を使おう) ``` ## データをどう格納するか? (講義資料末尾参照) 実際にnumpyでアルゴリズムを書く時、「データ」はどういう形で入っているのでしょうか? Pythonについては、基本的に **(サンプル数、次元数)** の形で格納することをおすすめします。 どちらでも全く問題なく書けるのですが、 * 「i番目のサンプル」にアクセスするときに data[i] と書ける (逆の場合data[:, i]) * scikit-learnなどの主要ライブラリが上記に従っている * Numpyがデフォルトでrow-major orderを採用している (下記参照) などの理由によりサンプル数を0次元目とするのが一般的です。 ### *行アクセスと列アクセスの速度の違い numpyがどのように配列をメモリ上に配置しているかは、次の簡単な実験からも類推することができます: (参考: http://kaisk.hatenadiary.com/entry/2015/02/19/224531) ```python a = np.random.rand(2000, 2000) %timeit a[0,:].sum() # 行へのアクセスは速い %timeit a[:,0].sum() # 列へのアクセスは遅い ``` ## ノルム (np.linalg.norm) np.linalg.normは、ベクトルを引数としてとった場合、L2ノルム (ざっくり言うとユークリッド距離) \begin{equation} \|x\|_2 = \sqrt{x_1^2 + x_2^2 + \dots + x_n^2} \end{equation} 行列を引数としてとった場合、フロベニウスノルム \begin{equation} \|A\|_F = \sqrt{\sum_{i=1}^m \sum_{j=1}^n \left| a_{ij}^2 \right|} \end{equation} を返します。axisを指定することで、行列から各行または列のL2ノルムを求めるなど、頻繁に使われます。 ```python e = [-4, -3, -2, -1, 0, 1, 2, 3, 4] np.linalg.norm(e) ``` ```python f = [1, 1] np.linalg.norm(f) ``` ```python g = np.array([[1, 2], [3, 4]]) np.linalg.norm(g, axis=1) # axis=1 (各行) に関してL2ノルムを計算 ``` ## 数学関数 (np.sin, np.cos, np.tah, np.exp, np.log など) NumpyにはPythonの標準とは別に専用の数学関数が用意されています。 また、これらの関数は**ベクトルや行列を引数として**、要素ごとに演算を適用できます。 ```python np.sin(np.pi / 2.0) # π/2=90度 ``` ```python np.log([1, np.e, np.e ** 2, np.e ** 3]) # **演算子は累乗 ``` ```python np.log(0) # log0は定義できないのでnumpyではマイナス無限大が返る ``` ## 乱数生成 続いて乱数の作り方を覚えましょう。 乱数は次のような場面で使います: * 学習器のパラメータ (重み行列) をランダムに初期化する * 複数のサンプルをランダムにシャッフルする ### np.random.seed(seed) 乱数の「種」を初期化します。「種」には自由に値を設定できます。 通常乱数は環境によって毎回結果が変わってしまいますが、「種」が一緒であれば異なる環境でも同じ数字を再現できます。 この機能は (この講義のように) 再現性が重要な場合に非常に重要です。 ### np.random.random(size) 0以上1未満の一様分布を生成します (shapeには形状のタプルが入ります)。 ### np.random.random(loc=0.0, scale=1.0, size) 平均がloc、分散がscaleの正規分布 (ガウス分布) N(loc, scale) を生成します。 わからなくなったらドキュメントを参照しましょう: * https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.random.random.html#numpy.random.random * https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.random.normal.html ```python # Ctrl+Enterで同じセルを何回か実行してみよう (種を指定しない) np.random.random() ``` ```python # Ctrl+Enterで同じセルを何回か実行してみよう (種を指定する) np.random.seed(1701) np.random.random() ``` ```python # 複数一気に作る np.random.random(5) ``` ```python # 正規分布 np.random.normal(size=5) # random.randomと微妙に呼び出しが違うので注意 ``` 試しに1000個程度値を生成してプロットしてみると一目瞭然です: ```python import matplotlib.pyplot as plt plt.figure() plt.hist(np.random.random(1000), bins=20) plt.title("Uniform distribution U[0, 1]") plt.show() ``` ```python plt.figure() plt.hist(np.random.normal(0, 1, 1000), bins=20) plt.title("Normal (Gaussian) distribution N(0, 1)") plt.show() ``` ### 配列をシャッフル 配列のシャッフルにはnp.random.shuffleを、配列からランダムに選び出すにはnp.random.choiceを使います。 ```python x = np.arange(10) print(x) np.random.shuffle(x) # ランダムにシャッフル print(x) ``` ```python x = np.arange(12) print(np.random.choice(x, 10)) # ランダムに10個選ぶ (重複を許す) print(np.random.choice(x, 10, replace=False)) # ランダムに10個選ぶ (重複を許さない) ``` ## 書いてみよう:乱数生成 1. -1から1までの一様な乱数を生成せよ 2. 深層学習では、重み行列を入力側の層のユニット数nに対して、 $$ N(0, \frac{1}{\sqrt{n}}) $$ なる正規分布に従う乱数で初期化するテクニックが知られている (Xavierの初期化)。 入力層のユニット数が100、出力層のユニット数が50である重み行列WをXavierの初期化に従って作成せよ。 ### ヒント * 重み行列の形状は(100, 50) * 平方根はnp.sqrt * np.random.normalでscaleを指定するかN(0, 1) * scaleとしてやれば良い (正規分布の性質) ```python # Q1 # WRITE ME! ``` ```python # Q2 # WRITE ME! W = np.zeros((100, 50)) # これを書き換える ``` ```python # プロットしてみよう plt.figure() plt.hist(W.flatten(), bins=20) plt.title("Xavier initialization (red line is 2sigma)") plt.axvline(x=0.2, c='r') plt.axvline(x=-0.2, c='r') plt.show() ``` ### *整数の乱数 np.random.randint(low, high, size) もちろん整数も作れます。 low <= x < highなる整数を作ります。 https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.random.randint.html ```python np.random.randint(10, size=(100,)) # 0から9 ``` ```python np.random.randint(-10, 11, size=(100,)) # -10から10 ``` ## ソート関連(np.sort, np.argsort) k-NNアルゴリズムでは**距離が小さいベクトルをk本取得する**操作を使います。 高速なソートアルゴリズムもnumpyは備えています。 ```python f = np.array([5, 2, 3, 1, 4]) np.sort(f) ``` ```python np.argsort(f) ``` ```python f[np.argsort(f)] # 確かにインデックスが取れている (advanced indexingを使用) ``` 大きい順で欲しい場合には、スライシング [start:end:step]を使いましょう: ```python np.sort(f)[::-1] # 逆順で取るときにはstepを-1にすれば良い ``` ## 書いてみよう:ソート Q: np.sortを使用して,fの最大の数,上から2番目の数,最小の数を出力せよ。 ```python # WRITE ME! ``` ## 2. 機械学習の距離尺度 (ユークリッド距離・マンハッタン距離・コサイン類似度) ### ユークリッド距離 講義で述べたとおり、 今日扱うk-NN法では、ユークリッド距離 (L2ノルム) $$ \|p - q\|_2 = \sqrt{\sum_{i=1}^D (p_i - q_i)^2}$$ を使います。ユークリッド距離はnp.linalg.normを用いて書くことができます。 ```python x = np.array([1, 0]) y = np.array([0, -1]) def euclidian_distance(p, q): return np.linalg.norm(p - q) euclidian_distance(x, y) ``` ### マンハッタン距離 ユークリッド距離に続いてよく使われる距離尺度としては、マンハッタン距離 (L1ノルム) $$ \|p - q\|_1 = \sum_{i=1}^D |p_i - q_i|$$ があります。これも同様に書くことができます。 ```python def manhattan_distance(p, q): return np.linalg.norm(p - q, ord=1) manhattan_distance(x, y) ``` ### コサイン類似度 (コサイン距離) コサイン類似度は、次のように定義される尺度で、-1から1までの値が得られます。 コサイン類似度が1の時2本のベクトルは最も近く、-1の時は最も遠いと判断されます。 コサイン類似度は距離の公理を満たしませんが、自然言語処理などの分野でしばしば使用されます。 $$ cosine(p, q) = \frac{p \cdot q}{\| p \| \cdot \|q \|} $$ ## 書いてみよう:コサイン類似度 Q: 上記のコサイン類似度を実装せよ。 ```python def cosine_similarity(p, q): # WRITE ME! print(cosine_similarity(x, y)) print(cosine_similarity(x, x)) print(cosine_similarity(x, -x)) ``` # 3. ファイルの入出力 本節では、実データに機械学習を適用する際に不可欠な、データの読み書きに焦点をあて、csvファイルの読み書きを題材にその基礎を解説・実践します。 実際には、以下に示すモジュールを用いればサンプルより簡単にデータを読み込み・処理できますが、時間の関係上今回は飛ばします。 * csvモジュール * jsonモジュール * pandas (データ解析支援ライブラリ) とはいえ、pandasは大規模データを取り扱うための各種機能を搭載しているため、データがある程度複雑なら、**pandasを利用したほうが良い**です。 ## osモジュール 通常、処理コードとデータは別々のディレクトリに保存されており、適切なファイルパスを指定し、それを読み込む必要があります。こうした * ディレクトリ間の移動 * ディレクトリの作成 * パスの作成・加工 などを担うのがosモジュールです。今回は、 1. テキストファイルの読み込み 2. CSVファイル (irisデータセット) の読み書き 3. The Allen Mouse Brain Connectivity Atlasの読み込み の3つの題材を通じて、osモジュールの主要関数の使い方を学習します。 ### 今回のディレクトリ構成 ``` +---nico2ai_lecture2_exercise.ipynb (このファイル) +---nico2ai_lecture2_practice.ipynb +---data/ +---sample.txt +---iris.csv +---nature/ +---nature13186-s3.csv +---nature13186-s4-w-ipsi.csv +---nature13186-s5.csv ``` ### 事前準備 (一度のみ実行) ```python !wget https://www.dropbox.com/s/8fqayqdai15en2f/data.zip !unzip -n data.zip ``` ### ファイルの読み込み ファイルの読み込みには、**open関数**を用いまず。第2引数のモードには * "r": 読み込み専用 * "w": 書き込み専用 (ファイルが存在しない場合、新規作成) * "r+": 読み書き療養 * "a": 追記用 (すでに同名のファイルが存在する場合、その末尾から追記) の4種類がありますが、まずは読み込み専用の"r"を使いましょう。 ```python f = open("data/sample.txt", "r") # open関数が成功すると、ファイルオブジェクトが返る for line in f: print(line.strip("\n")) # 余計な改行を除去 # 古い書き方:今は直接for文で行ごとに読み込める #line = f.readline() #while line: # print(line) # line = f.readline() f.close() # 必ずcloseする ``` ### with ~ as文 上記の例では、openしたファイルを必ずcloseしなければならず、後処理を忘れる危険性がありました。 with文を使うと、同じ式をエレガントに書けます。 ```python with open("data/sample.txt", "r") as f: # Closeする必要なし for line in f: print(line.strip("\n")) # 余計な改行を除去 ``` 上記の原文は亀語 (単語の並び順が人間語と逆順) であるため、配列のアクセスを工夫して人間語に戻してあげましょう。 (サンプルの出典: Roald Dahl, "Esio Trot", Viking Press, 1990) その際、次の文字列操作関数を用います: * str.strip(str): 文字列中からstrを取り除く * str.split(delimiter): delimiterで文字列を区切り、区切られた部分文字列のリストを返す * str.join(str_list): splitと逆の操作を行い、strを区切り文字としてstr_listの各要素を連結して返す * str.replace(str1, str2): 文字列中のstr1をstr2に置き換える ```python with open("data/sample.txt", "r") as f: for line in f: line = line.strip("\n") words = line.split(" ") words_reversed = [] for word in words: # 始点・終点を変えずに逆順に進める words_reversed.append(word[::-1]) # 始点・終点を変えずに逆順に進める line_reversed = " ".join(words_reversed) # スペースで連結 line_reversed = line_reversed.replace("OISE ,TORT", "TORT OISE,") # TORT OISEが本来1語であるのを逆にしてしまったので、元に戻す print(line_reversed) ``` 句読点が若干変ですが、これで読めました。大きくなあれ! ## csvの読み込みとパース 続いて、csvファイルの読み込みを行います。csv (comma-separated values)は、その名の示す通り、ファイル内の要素がカンマで区切られています。そのため、カンマ区切りの各要素を読みだしたうえで、そのデータ型に合わせて適切にパース (parse) しなければなりません。 文字列から数値への変換及びその逆は ``` float("3.1") -> 3.1 int("5") -> 5 str(5) -> "5" ``` などで行うことができます。 ### Irisデータセット 今回サンプルcsvとして用いるのは、"Iris"と呼ばれる非常に有名なデータセットです。 * Setosa * Verisicolor * Virginica という3種類の品種のアヤメの * がく片の長さ (1列目) * がく片の幅 (2列目) * 花弁の長さ (3列目) * 花弁の幅 (4列目) がcm単位で格納されています。5列目は品種名(文字列)です。 1列目〜4列目まではすべてfloatに変換できるので、5列目を除いたデータをnumpy配列に変換してみましょう。 ```python with open("data/iris.csv", "r") as f: lines = [] for line in f: strs = line.split(",")[0:4] lines.append([float(x) for x in strs]) # すべての要素をfloatに変換 data = np.array(lines) print(data) ``` ### ファイルの書き込み 続いて、前項でnumpy配列として読み込んだデータを再びリストに戻し、スペース区切りのファイルとして再保存しましょう。 処理の流れは次のようになります: 1. os.makedirsとos.path.existsの組み合わせで出力先のフォルダを作成する 2. open関数で書き込み用にファイルを開く 3. numpy配列をtolist関数でリストに戻す 4. 各行をスペース区切りの文字列として、ファイルに書き込む その際、使用する関数は次のとおりです。これらはPythonのデータ処理で頻出するので覚えておきましょう。 * os.path.join(str1, str2, ...):パスの連結。"/"の有無を吸収してパスを結合してくれるので、文字列を単純に連結するより安全 * os.path.exists(path):そのパスにファイルまたはディレクトリが存在するかを返す * os.makedirs(path):新規ディレクトリを作成する。ただし、すでに作成済みである場合にはエラーを返すので常にその存在性を注意する必要がある * f.write(str):ファイルの末尾の行に文字列を書き込む * tolist():numpy配列を通常のリストに変換する ```python import os outdir_name = "outputs" outpath = os.path.join(outdir_name, "processed.txt") if not os.path.exists(outdir_name): # もしディレクトリが存在しなければ os.makedirs(outdir_name) # outdir_nameと同じ名前のディレクトリを作成する with open(outpath, "w") as f: # 書き込み用 for line_data in data.tolist(): f.write(" ".join([str(x) for x in line_data]) + "\n") # 末尾に改行を加える ``` ### *Colaboratoryからのファイルの取得 colaboratoryからファイルを取得するには、次のコードを使用してください (Jupyter notebookでは動きません) ```python # 使用するにはコメントアウト # from google.colab import files # files.download("outputs/processed.txt") ``` ## 書いてみよう:irisデータの読み書き Q: Irisデータセットの品種名は文字列で格納されているが、これはラベルとしては扱いにくい形をしている。 * Setosa -> 0 * Verisicolor -> 1 * Virginica -> 2 というIDを振り、5列目を品種名ではなく品種IDに書き換えたものをoutputs/iris_with_label.csvとしてカンマ区切りで出力せよ。 ### ヒント: * str.replaceを用いる * 各行の文字列を置換するだけで今回の操作は実現できる (数値に変換する必要はない) ```python # WRITE ME! ``` ### *おまけ 余裕があれば、次の関数を用いて、irisデータの各特徴の平均や分散を求めてみましょう: * np.mean * np.var * np.sum 各関数の解説は、numpyのリファレンスから読めます: https://docs.scipy.org/doc/numpy/reference/ ```python #WRITE ME! ``` ```python ```
function checkFieldNames(structure, field_names) %CHECKFIELDNAMES Checks structure field names for existance. % % DESCRIPTION: % checkFieldNames checks the field names of a MATLAB structure % against a cell array of allowable field names. If a field name is % found within the structure that is not contained within the cell % array, an error is thrown with the field name given in the error % message. The function is useful for checking for spelling errors in % field names for structure inputs. % % USAGE: % checkFieldNames(structure, field_names) % % INPUTS: % structure - MATLAB structure % field_names - cell array of allowable field names % % ABOUT: % author - Bradley Treeby % date - 13th October 2009 % last update - 13th October 2009 % % This function is part of the k-Wave Toolbox (http://www.k-wave.org) % Copyright (C) 2009-2014 Bradley Treeby and Ben Cox % % See also fieldnames % This file is part of k-Wave. k-Wave is free software: you can % redistribute it and/or modify it under the terms of the GNU Lesser % General Public License as published by the Free Software Foundation, % either version 3 of the License, or (at your option) any later version. % % k-Wave is distributed in the hope that it will be useful, but WITHOUT ANY % WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS % FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for % more details. % % You should have received a copy of the GNU Lesser General Public License % along with k-Wave. If not, see <http://www.gnu.org/licenses/>. names = fieldnames(structure); for names_index = 1:length(names) name_found = false; for field_index = 1:length(field_names) if strcmp(names{names_index}, field_names{field_index}) name_found = true; end end if ~name_found error([names{names_index} ' is not a valid field for the structure ' inputname(1)]); end end
(* matrices *) Set Nested Proofs Allowed. Set Implicit Arguments. Require Import Utf8 Arith Bool. Import List List.ListNotations. Require Import Init.Nat. Require Import Misc. Require Import RingLike IterAdd IterMul IterAnd. Require Import MyVector Signature. (* matrices *) Record matrix T := mk_mat { mat_list_list : list (list T) }. Definition mat_nrows {T} (M : matrix T) := length (mat_list_list M). Definition mat_ncols {T} (M : matrix T) := length (hd [] (mat_list_list M)). Definition mat_el {T} {ro : ring_like_op T} (M : matrix T) i j := nth (j - 1) (nth (i - 1) (mat_list_list M) []) 0%L. (* *) Definition mat_eqb {T} (eqb : T → T → bool) (A B : matrix T) := list_eqv (list_eqv eqb) (mat_list_list A) (mat_list_list B). (* correct_matrix: matrix whose list list is made of non empty lists (rows) of same length *) Definition is_correct_matrix {T} (M : matrix T) := ((mat_ncols M ≠? 0) || (mat_nrows M =? 0)) && (⋀ (l ∈ mat_list_list M), (length l =? mat_ncols M)). (* square_matrix: matrix whose list list is mode of non empty lists of same length as the list list *) Definition is_square_matrix {T} (M : matrix T) := ((mat_ncols M ≠? 0) || (mat_nrows M =? 0)) && (⋀ (l ∈ mat_list_list M), (length l =? mat_nrows M)). (* mat_eqb is an equality *) Theorem mat_eqb_eq : ∀ T (eqb : T → T → bool), equality eqb → ∀ (A B : matrix T), mat_eqb eqb A B = true ↔ A = B. Proof. intros * Heqb *. split; intros Hab. { unfold mat_eqb in Hab. apply list_eqb_eq in Hab; [ | now apply -> equality_list_eqv ]. destruct A as (lla). destruct B as (llb). now cbn in Hab; f_equal. } { subst B. apply list_eqb_eq; [ | easy ]. now apply -> equality_list_eqv. } Qed. (* is_correct_matrix (a bool) easier to use with Prop *) Theorem is_scm_mat_iff {T} : ∀ f (M : matrix T), ((mat_ncols M ≠? 0) || (mat_nrows M =? 0)) && (⋀ (l ∈ mat_list_list M), (length l =? f)) = true ↔ (mat_ncols M = 0 → mat_nrows M = 0) ∧ ∀ l, l ∈ mat_list_list M → length l = f. Proof. intros. split; intros Hm. { apply Bool.andb_true_iff in Hm. destruct Hm as (Hrc, Hc). apply Bool.orb_true_iff in Hrc. split. { intros Hcz. destruct Hrc as [Hrc| Hrc]. { apply negb_true_iff in Hrc. now apply Nat.eqb_neq in Hrc. } { now apply Nat.eqb_eq in Hrc. } } intros l Hl. remember (mat_list_list M) as ll eqn:Hll. clear Hll. induction ll as [| la]; [ easy | cbn ]. rewrite and_list_cons in Hc. apply Bool.andb_true_iff in Hc. destruct Hc as (Hla, Hc). apply Nat.eqb_eq in Hla. destruct Hl as [Hl| Hl]; [ now subst l | ]. now apply IHll. } { destruct Hm as (Hrc & Hc). apply Bool.andb_true_iff. split. { apply Bool.orb_true_iff. destruct (Nat.eq_dec (mat_nrows M) 0) as [Hnz| Hnz]. { now right; apply Nat.eqb_eq. } left. apply negb_true_iff. apply Nat.eqb_neq. intros H. now apply Hnz, Hrc. } remember (mat_list_list M) as ll eqn:Hll. clear Hll. induction ll as [| la]; [ easy | ]. rewrite and_list_cons. apply Bool.andb_true_iff. split; [ now apply Nat.eqb_eq, Hc; left | ]. apply IHll. intros l Hl. now apply Hc; right. } Qed. Theorem tail_is_correct_matrix : ∀ {A} (M : matrix A), is_correct_matrix M = true → is_correct_matrix (mk_mat (tl (mat_list_list M))) = true. Proof. intros * Hcm. apply is_scm_mat_iff in Hcm. apply is_scm_mat_iff. destruct Hcm as (Hcr, Hcl). split. { unfold mat_ncols; cbn. intros Hr. apply length_zero_iff_nil in Hr. unfold mat_ncols in Hcr, Hcl. destruct M as (ll); cbn in *. destruct ll as [| la]; [ easy | ]. cbn in Hr |-*. destruct ll as [| la']; [ easy | ]. cbn in Hr; subst la'; exfalso. cbn in Hcr. specialize (Hcl [] (or_intror (or_introl eq_refl))) as H1. cbn in H1; symmetry in H1. now specialize (Hcr H1). } { intros l Hl; cbn in Hl. unfold mat_ncols; cbn. rewrite Hcl. 2: { destruct M as (ll); cbn in Hl |-*. destruct ll as [| la]; [ easy | ]. now right. } symmetry. rewrite Hcl. 2: { destruct M as (ll); cbn in Hl |-*. destruct ll as [| la]; [ easy | ]. destruct ll as [| la']; [ easy | ]. cbn in Hl |-*. now right; left. } easy. } Qed. Theorem matrix_eq : ∀ T (ro : ring_like_op T) MA MB, (∀ i j, 1 ≤ i ≤ mat_nrows MA → 1 ≤ j ≤ mat_ncols MB → mat_el MA i j = mat_el MB i j) → is_correct_matrix MA = true → is_correct_matrix MB = true → mat_nrows MA = mat_nrows MB → mat_ncols MA = mat_ncols MB → MA = MB. Proof. intros * Hij Ha Hb Hrr Hcc. destruct MA as (lla). destruct MB as (llb). f_equal. cbn in *. remember (length lla) as len eqn:Hr; symmetry in Hr. rename Hrr into Hc; symmetry in Hc; move Hc before Hr. revert lla llb Hr Hc Hij Hcc Ha Hb. induction len; intros. { apply length_zero_iff_nil in Hr, Hc; congruence. } destruct lla as [| la]; [ easy | ]. destruct llb as [| lb]; [ easy | ]. cbn in Hr, Hc, Hcc. apply Nat.succ_inj in Hr, Hc. f_equal. { apply nth_ext with (d := 0%L) (d' := 0%L); [ easy | ]. intros i Hi. unfold mat_ncols in Hij. cbn - [ nth ] in Hij. specialize (Hij 1 (i + 1)). rewrite Nat.add_sub, Nat.sub_diag in Hij; cbn in Hij. apply Hij. { split; [ easy | ]. now apply -> Nat.succ_le_mono. } rewrite Nat.add_1_r. split; [ now apply -> Nat.succ_le_mono | ]. now rewrite <- Hcc. } apply IHlen; [ easy | easy | | | | ]; cycle 1. { apply is_scm_mat_iff in Ha. apply is_scm_mat_iff in Hb. destruct Ha as (Ha1, Ha2). destruct Hb as (Hb1, Hb2). unfold mat_ncols; cbn. specialize (Ha2 (hd [] lla)). specialize (Hb2 (hd [] llb)). cbn - [ In ] in Ha2, Hb2. destruct lla as [| la']. { cbn in Hr; subst len. now apply length_zero_iff_nil in Hc; subst llb. } destruct llb as [| lb']. { now cbn in Hc; move Hc at top; subst len. } cbn in Ha2, Hb2 |-*. specialize (Ha2 (or_intror (or_introl eq_refl))). specialize (Hb2 (or_intror (or_introl eq_refl))). congruence. } { now apply tail_is_correct_matrix in Ha. } { now apply tail_is_correct_matrix in Hb. } intros * Hi Hj. unfold mat_ncols in Hij, Hj. cbn - [ nth ] in Hij. cbn in Hj. specialize (Hij (S i) j) as H1. assert (H : 1 ≤ S i ≤ S len). { now split; apply -> Nat.succ_le_mono. } specialize (H1 H); clear H. destruct i; [ easy | ]. rewrite Nat_sub_succ_1 in H1 |-*. rewrite List_nth_succ_cons in H1. apply H1. split; [ easy | ]. apply is_scm_mat_iff in Hb. destruct Hb as (Hb1, Hb2). unfold mat_ncols in Hb2; cbn in Hb2. destruct llb as [| lb']; cbn in Hj; [ flia Hj | ]. specialize (Hb2 lb' (or_intror (or_introl eq_refl))). now rewrite Hb2 in Hj. Qed. Theorem fold_mat_nrows {T} : ∀ (M : matrix T), length (mat_list_list M) = mat_nrows M. Proof. easy. Qed. Theorem fold_mat_ncols {T} : ∀ (M : matrix T), length (hd [] (mat_list_list M)) = mat_ncols M. Proof. easy. Qed. Theorem fold_mat_el {T} {ro : ring_like_op T} : ∀ (M : matrix T) i j, nth j (nth i (mat_list_list M) []) 0%L = mat_el M (S i) (S j). Proof. intros. unfold mat_el. now do 2 rewrite Nat_sub_succ_1. Qed. Theorem eq_mat_nrows_0 {T} : ∀ M : matrix T, mat_nrows M = 0 → mat_list_list M = []. Proof. intros * Hr. unfold mat_nrows in Hr. now apply length_zero_iff_nil in Hr. Qed. Theorem fold_left_mat_fold_left_list_list : ∀ T A (M : matrix T) (l : list A) f, fold_left f l M = mk_mat (fold_left (λ ll k, mat_list_list (f (mk_mat ll) k)) l (mat_list_list M)). Proof. intros. revert M. induction l as [| a]; intros; [ now destruct M | cbn ]. rewrite IHl; cbn. now destruct M. Qed. Record correct_matrix T := mk_cm { cm_mat : matrix T; cm_prop : is_correct_matrix cm_mat = true }. Theorem fold_corr_mat_ncols {T} : ∀ (M : matrix T) d, is_correct_matrix M = true → ∀ i, i < mat_nrows M → length (nth i (mat_list_list M) d) = mat_ncols M. Proof. intros * Hm * Him. apply is_scm_mat_iff in Hm. destruct Hm as (Hcr, Hc). apply Hc. apply nth_In. now rewrite fold_mat_nrows. Qed. Record square_matrix n T := { sm_mat : matrix T; sm_prop : (mat_nrows sm_mat =? n) && is_square_matrix sm_mat = true }. Theorem square_matrix_eq {n T} : ∀ (MA MB : square_matrix n T), sm_mat MA = sm_mat MB → MA = MB. Proof. intros * Hab. destruct MA as (MA, Ha). destruct MB as (MB, Hb). cbn in Hab. destruct Hab. f_equal. apply (Eqdep_dec.UIP_dec Bool.bool_dec). Qed. Theorem squ_mat_ncols {T} : ∀ (M : matrix T), is_square_matrix M = true → mat_ncols M = mat_nrows M. Proof. intros * Hm. apply is_scm_mat_iff in Hm. destruct Hm as (Hcr & Hc). destruct (Nat.eq_dec (mat_nrows M) 0) as [Hnz| Hnz]. { unfold mat_nrows, mat_ncols in Hnz |-*. now apply length_zero_iff_nil in Hnz; rewrite Hnz. } apply Nat.neq_0_lt_0 in Hnz. now apply Hc, List_hd_in. Qed. Theorem squ_mat_is_corr {T} : ∀ (M : matrix T), is_square_matrix M = true → is_correct_matrix M = true. Proof. intros * Hsm. specialize (squ_mat_ncols _ Hsm) as Hc. apply is_scm_mat_iff in Hsm. apply is_scm_mat_iff. split; [ easy | ]. intros l Hl. destruct Hsm as (Hcr & Hc'). now rewrite Hc'. Qed. (* *) Fixpoint concat_list_in_list {T} (ll1 ll2 : list (list T)) := match ll1 with | [] => ll2 | l1 :: ll1' => match ll2 with | [] => ll1 | l2 :: ll2' => app l1 l2 :: concat_list_in_list ll1' ll2' end end. Section a. Context {T : Type}. Context (ro : ring_like_op T). Context {rp : ring_like_prop T}. (* addition *) Definition mat_add (MA MB : matrix T) : matrix T := mk_mat (map2 (map2 rngl_add) (mat_list_list MA) (mat_list_list MB)). (* multiplication *) Definition mat_mul_el MA MB i k := ∑ (j = 1, mat_ncols MA), mat_el MA i j * mat_el MB j k. Definition mat_mul (MA MB : matrix T) : matrix T := mk_mat (map (λ i, map (mat_mul_el MA MB i) (seq 1 (mat_ncols MB))) (seq 1 (mat_nrows MA))). (* opposite *) Definition mat_opp (M : matrix T) : matrix T := mk_mat (map (map rngl_opp) (mat_list_list M)). (* subtraction *) Definition mat_sub (MA MB : matrix T) := mat_add MA (mat_opp MB). (* vector as a matrix nx1 *) Definition mat_of_vert_vect (V : vector T) := mk_mat (map (λ i, [i]) (vect_list V)). (* vector as a matrix 1xn *) Definition mat_of_horiz_vect (V : vector T) := mk_mat [vect_list V]. (* concatenation of a matrix and a column vector *) Definition mat_vect_concat (M : matrix T) V := mk_mat (map2 (λ row e, row ++ [e]) (mat_list_list M) (vect_list V)). (* multiplication of a matrix and a vector *) Definition mat_mul_vect_r (M : matrix T) (V : vector T) := mk_vect (map (λ row, vect_dot_mul (mk_vect row) V) (mat_list_list M)). (* Definition mat_mul_vect_r' (M : matrix T) (V : vector T) := mk_vect match vect_list V with | nil => [] | cons d _ => map (hd d) (mat_list_list (mat_mul M (mat_of_vert_vect V))) end. *) (* multiplication of a vector and a matrix *) (* to be analyzed and completed Definition mat_mul_vect_l (V : vector T) (M : matrix T) := mk_vect (map (λ row, vect_dot_mul (mk_vect row) V) (mat_list_list M)). *) (* multiplication of a matrix by a scalar *) Definition mat_mul_scal_l s (M : matrix T) := mk_mat (map (map (rngl_mul s)) (mat_list_list M)). (* matrix whose k-th column is replaced by a vector *) Definition mat_repl_vect k (M : matrix T) (V : vector T) := mk_mat (map2 (replace_at (k - 1)) (mat_list_list M) (vect_list V)). Theorem mat_el_repl_vect : ∀ (M : matrix T) V i j k, is_correct_matrix M = true → i ≤ vect_size V → 1 ≤ i ≤ mat_nrows M → 1 ≤ j ≤ mat_ncols M → 1 ≤ k ≤ mat_ncols M → mat_el (mat_repl_vect k M V) i j = if Nat.eq_dec j k then vect_el V i else mat_el M i j. Proof. intros * Hm His Hir Hjc Hkc; cbn. rewrite map2_nth with (a := []) (b := 0%L); cycle 1. { rewrite fold_mat_nrows. now apply Nat_1_le_sub_lt. } { rewrite fold_vect_size. now apply Nat_1_le_sub_lt. } unfold replace_at. destruct (Nat.eq_dec j k) as [Hjk| Hjk]. { subst k. rewrite app_nth2. 2: { rewrite firstn_length. rewrite fold_corr_mat_ncols; [ | easy | now apply Nat_1_le_sub_lt ]. unfold ge. rewrite Nat.min_l; [ easy | flia Hjc ]. } rewrite firstn_length. rewrite fold_corr_mat_ncols; [ | easy | now apply Nat_1_le_sub_lt ]. rewrite Nat.min_l; [ | flia Hjc ]. now rewrite Nat.sub_diag. } destruct (lt_dec j k) as [Hljk| Hljk]. { rewrite app_nth1. 2: { rewrite firstn_length. rewrite fold_corr_mat_ncols; [ | easy | now apply Nat_1_le_sub_lt ]. rewrite Nat.min_l; [ | flia Hkc ]. apply Nat_1_le_sub_lt. split; [ easy | flia Hjk Hljk ]. } rewrite List_nth_firstn; [ easy | flia Hjc Hljk ]. } { apply Nat.nlt_ge in Hljk. rewrite app_nth2. 2: { rewrite firstn_length. rewrite fold_corr_mat_ncols; [ | easy | now apply Nat_1_le_sub_lt ]. rewrite Nat.min_l; [ flia Hjc Hljk | flia Hkc ]. } rewrite firstn_length. rewrite fold_corr_mat_ncols; [ | easy | now apply Nat_1_le_sub_lt ]. rewrite Nat.min_l; [ | flia Hkc ]. rewrite Nat_succ_sub_succ_r; [ | flia Hkc Hjk Hljk ]. cbn - [ skipn ]. rewrite List_nth_skipn. rewrite Nat.sub_add; [ easy | flia Hkc Hjk Hljk ]. } Qed. Theorem mat_repl_vect_nrows : ∀ k (M : matrix T) V, vect_size V = mat_nrows M → mat_nrows (mat_repl_vect k M V) = mat_nrows M. Proof. intros * Hv; cbn. rewrite map2_length. rewrite fold_mat_nrows, fold_vect_size, Hv. apply Nat.min_id. Qed. Theorem mat_repl_vect_ncols : ∀ k (M : matrix T) V, 1 ≤ k ≤ mat_ncols M → vect_size V = mat_ncols M → mat_ncols (mat_repl_vect k M V) = mat_ncols M. Proof. intros * Hkc Hv. (* works with nrows=0 *) destruct (Nat.eq_dec (mat_nrows M) 0) as [Hrz| Hrz]. { unfold mat_nrows in Hrz. apply length_zero_iff_nil in Hrz. unfold mat_ncols; cbn. now rewrite Hrz. } apply Nat.neq_0_lt_0 in Hrz. (* works with ncols=0 *) destruct (Nat.eq_dec (mat_ncols M) 0) as [Hcz| Hcz]. { rewrite Hcz in Hv. unfold vect_size in Hv. apply length_zero_iff_nil in Hv. unfold mat_ncols in Hcz. apply length_zero_iff_nil in Hcz. unfold mat_ncols; cbn. rewrite Hv. now rewrite map2_nil_r, Hcz. } apply Nat.neq_0_lt_0 in Hcz. unfold mat_ncols. cbn - [ skipn ]. rewrite List_hd_nth_0. rewrite map2_nth with (a := []) (b := 0%L); cycle 1. { now rewrite fold_mat_nrows. } { now rewrite fold_vect_size, Hv. } unfold replace_at. rewrite app_length. rewrite firstn_length. rewrite <- List_hd_nth_0. rewrite fold_mat_ncols. rewrite List_cons_length. rewrite skipn_length. rewrite fold_mat_ncols. flia Hkc. Qed. Theorem mat_repl_vect_is_square : ∀ k (M : matrix T) V, 1 ≤ k ≤ mat_ncols M → vect_size V = mat_nrows M → is_square_matrix M = true → is_square_matrix (mat_repl_vect k M V) = true. Proof. intros * Hkc Hv Hm. specialize (squ_mat_ncols _ Hm) as Hcn. apply is_scm_mat_iff in Hm. apply is_scm_mat_iff. destruct Hm as (Hcr & Hc). rewrite mat_repl_vect_nrows; [ | congruence ]. split. { destruct (lt_dec k (mat_ncols M)) as [Hkm| Hkm]. { rewrite mat_repl_vect_ncols; [ easy | easy | congruence ]. } apply Nat.nlt_ge in Hkm. rewrite mat_repl_vect_ncols; [ easy | easy | congruence ]. } { intros la Hla. cbn - [ skipn ] in Hla. apply in_map2_iff in Hla. destruct Hla as (i & Hi & lb & a & Hla). rewrite fold_mat_nrows, fold_vect_size, Hv in Hi. rewrite Nat.min_id in Hi. subst la. unfold replace_at. rewrite app_length. rewrite firstn_length. cbn - [ skipn ]. rewrite skipn_length. rewrite fold_corr_mat_ncols; [ | | easy ]. 2: { apply is_scm_mat_iff. split; [ easy | now rewrite Hcn ]. } rewrite Nat.min_l; [ | flia Hkc ]. rewrite Hcn in Hkc |-*. flia Hkc. } Qed. (* null matrix of dimension m × n *) Definition mZ m n : matrix T := mk_mat (repeat (repeat 0%L n) m). (* identity square matrix of dimension n *) Definition δ i j := if i =? j then 1%L else 0%L. Definition mI n : matrix T := mk_mat (map (λ i, map (δ i) (seq 0 n)) (seq 0 n)). Theorem δ_diag : ∀ i, δ i i = 1%L. Proof. intros. unfold δ. now rewrite Nat.eqb_refl. Qed. Theorem δ_ndiag : ∀ i j, i ≠ j → δ i j = 0%L. Proof. intros * Hij. unfold δ. rewrite if_eqb_eq_dec. now destruct (Nat.eq_dec i j). Qed. Theorem mI_any_seq_start : ∀ sta len, mI len = mk_mat (map (λ i, map (δ i) (seq sta len)) (seq sta len)). Proof. intros. unfold mI; f_equal. symmetry. rewrite List_map_seq. apply map_ext_in. intros i Hi. rewrite List_map_seq. apply map_ext_in. intros j Hj. destruct (Nat.eq_dec i j) as [Hij| Hij]. { now subst j; do 2 rewrite δ_diag. } rewrite δ_ndiag; [ | flia Hij ]. now rewrite δ_ndiag. Qed. End a. Section a. Context {T : Type}. Context (ro : ring_like_op T). Context {rp : ring_like_prop T}. Context {Hop : @rngl_has_opp T ro = true}. Declare Scope M_scope. Delimit Scope M_scope with M. Arguments δ {T ro} (i j)%nat. Arguments matrix_eq {T}%type {ro} (MA MB)%M. Arguments mat_add {T ro} MA%M MB%M. Arguments mat_mul {T ro} MA%M MB%M. Arguments mat_mul_el {T}%type {ro} (MA MB)%M (i k)%nat. Arguments mat_mul_scal_l {T ro} s%L M%M. Arguments mat_list_list [T]%type m%M. Arguments mat_nrows {T}%type M%M. Arguments mat_ncols {T}%type M%M. Arguments mat_el {T}%type {ro} M%M (i j)%nat. Arguments mat_opp {T}%type {ro}. Arguments mat_sub {T ro} MA%M MB%M. Arguments mI {T ro} n%nat. Arguments mZ {T ro} (m n)%nat. Arguments minus_one_pow {T ro}. Arguments vect_zero {T ro} n%nat. Arguments is_correct_matrix {T}%type M%M. Arguments is_square_matrix {T}%type M%M. Arguments Build_square_matrix n%nat [T]%type sm_mat%M. Notation "A + B" := (mat_add A B) : M_scope. Notation "A - B" := (mat_sub A B) : M_scope. Notation "A * B" := (mat_mul A B) : M_scope. Notation "μ × A" := (mat_mul_scal_l μ A) (at level 40) : M_scope. Notation "- A" := (mat_opp A) : M_scope. Arguments mat_mul_vect_r {T ro} M%M V%V. Notation "A • V" := (mat_mul_vect_r A V) (at level 40) : M_scope. Notation "A • V" := (mat_mul_vect_r A V) (at level 40) : V_scope. Notation "μ × A" := (mat_mul_scal_l μ A) (at level 40) : M_scope. Theorem fold_mat_sub : ∀ (MA MB : matrix T), (MA + - MB = MA - MB)%M. Proof. easy. Qed. (* commutativity of addition *) Theorem mat_add_comm : ∀ (MA MB : matrix T), (MA + MB = MB + MA)%M. Proof. intros. unfold mat_add; f_equal. remember (mat_list_list MA) as lla eqn:Hlla. remember (mat_list_list MB) as llb eqn:Hllb. clear MA MB Hlla Hllb. revert llb. induction lla as [| la]; intros; [ now destruct llb | cbn ]. destruct llb as [| lb]; [ easy | cbn ]. rewrite IHlla; f_equal. revert lb. induction la as [| a]; intros; [ now destruct lb | cbn ]. destruct lb as [| b]; [ easy | cbn ]. now rewrite rngl_add_comm, IHla. Qed. (* associativity of addition *) Theorem mat_add_add_swap : ∀ (MA MB MC : matrix T), (MA + MB + MC = MA + MC + MB)%M. Proof. intros. unfold mat_add; f_equal; cbn. remember (mat_list_list MA) as lla eqn:Hlla. remember (mat_list_list MB) as llb eqn:Hllb. remember (mat_list_list MC) as llc eqn:Hllc. clear MA MB MC Hlla Hllb Hllc. revert llb llc. induction lla as [| la]; intros; [ easy | cbn ]. destruct llb as [| lb]; [ now destruct llc | cbn ]. destruct llc as [| lc]; [ easy | cbn ]. rewrite IHlla; f_equal. revert lb lc. induction la as [| a]; intros; [ easy | cbn ]. destruct lb as [| b]; [ now destruct lc | cbn ]. destruct lc as [| c]; [ easy | cbn ]. now rewrite rngl_add_add_swap, IHla. Qed. Theorem mat_add_assoc : ∀ (MA MB MC : matrix T), (MA + (MB + MC) = (MA + MB) + MC)%M. Proof. intros. rewrite mat_add_comm. rewrite mat_add_add_swap. f_equal. apply mat_add_comm. Qed. (* addition to zero *) Theorem mat_add_0_l {m n} : ∀ (M : matrix T), is_correct_matrix M = true → m = mat_nrows M → n = mat_ncols M → (mZ m n + M)%M = M. Proof. intros * HM Hr Hc. subst m n. apply is_scm_mat_iff in HM. destruct HM as (_, HM). unfold mZ, "+"%M, mat_nrows, mat_ncols. unfold mat_ncols in HM. destruct M as (ll); cbn in HM |-*; f_equal. remember (length (hd [] ll)) as ncols eqn:H. clear H. revert ncols HM. induction ll as [| la]; intros; [ easy | cbn ]. rewrite IHll. 2: { intros l Hl. now apply HM; right. } f_equal. specialize (HM la (or_introl eq_refl)). clear - rp HM. revert ncols HM. induction la as [| a]; intros; [ now destruct ncols | cbn ]. destruct ncols; [ easy | cbn ]. rewrite rngl_add_0_l; f_equal. apply IHla. cbn in HM. now apply Nat.succ_inj in HM. Qed. Theorem mat_add_0_r {m n} : ∀ (M : matrix T), is_correct_matrix M = true → m = mat_nrows M → n = mat_ncols M → (M + mZ m n)%M = M. Proof. intros * HM Hr Hc. rewrite mat_add_comm. now apply mat_add_0_l. Qed. (* addition left and right with opposite *) Theorem mat_add_opp_l {m n} : ∀ (M : matrix T), is_correct_matrix M = true → m = mat_nrows M → n = mat_ncols M → (- M + M = mZ m n)%M. Proof. intros * HM Hr Hc. subst m n. apply is_scm_mat_iff in HM. destruct HM as (_, HM). unfold "+"%M, mZ, mat_nrows, mat_ncols; cbn; f_equal. unfold mat_ncols in HM. destruct M as (ll); cbn in HM |-*. remember (length (hd [] ll)) as ncols eqn:H; clear H. induction ll as [| la]; [ easy | cbn ]. rewrite IHll. 2: { intros * Hl. now apply HM; right. } f_equal. clear IHll. specialize (HM la (or_introl eq_refl)). revert ncols HM. induction la as [| a]; intros; cbn; [ now rewrite <- HM | ]. rewrite rngl_add_opp_l; [ | easy ]. destruct ncols; [ easy | ]. cbn; f_equal. cbn in HM. apply Nat.succ_inj in HM. now apply IHla. Qed. Theorem mat_add_opp_r : ∀ (M : matrix T), is_correct_matrix M = true → (M - M = mZ (mat_nrows M) (mat_ncols M))%M. Proof. intros * HM. unfold mat_sub. rewrite mat_add_comm. now apply mat_add_opp_l. Qed. Theorem mat_add_sub : ∀ MA MB : matrix T, is_correct_matrix MA = true → is_correct_matrix MB = true → mat_nrows MA = mat_nrows MB → mat_ncols MA = mat_ncols MB → (MA + MB - MB)%M = MA. Proof. intros * Ha Hb Hrab Hcab. unfold mat_sub. rewrite <- mat_add_assoc. rewrite fold_mat_sub. rewrite mat_add_opp_r; [ | easy ]. now rewrite mat_add_0_r. Qed. Theorem mZ_nrows : ∀ m n, mat_nrows (mZ m n) = m. Proof. intros; cbn. apply repeat_length. Qed. Theorem mZ_ncols : ∀ m n, m ≠ 0 → mat_ncols (mZ m n) = n. Proof. intros * Hmz. unfold mZ, mat_ncols; cbn. destruct m; [ easy | cbn ]. apply repeat_length. Qed. Theorem mI_nrows : ∀ n, mat_nrows (mI n) = n. Proof. intros. destruct n; cbn - [ "=?" ]; [ easy | ]. now rewrite List_map_seq_length. Qed. Theorem mI_ncols : ∀ n, mat_ncols (mI n) = n. Proof. intros. destruct n; cbn - [ "=?" ]; [ easy | ]. now rewrite List_map_seq_length. Qed. Theorem mat_el_mI_ndiag : ∀ n i j, 1 ≤ i → 1 ≤ j → i ≠ j → mat_el (mI n) i j = 0%L. Proof. intros * Hi Hj Hij. unfold mat_el, mI; cbn. destruct (Nat.eq_dec n 0) as [Hnz| Hnz]. { subst n; cbn. rewrite Tauto_match_nat_same. now rewrite List_nth_nil. } apply Nat.neq_0_lt_0 in Hnz. destruct (le_dec i n) as [Hin| Hin]. { rewrite List_map_nth' with (a := 0); [ | rewrite seq_length; flia Hi Hin ]. destruct (le_dec j n) as [Hjn| Hjn]. { rewrite List_map_nth' with (a := 0). 2: { rewrite seq_length; flia Hj Hjn. } rewrite seq_nth; [ | flia Hi Hin ]. rewrite seq_nth; [ cbn | flia Hj Hjn ]. unfold δ. rewrite if_eqb_eq_dec. destruct (Nat.eq_dec (i - 1) (j - 1)) as [H| ]; [ | easy ]. flia Hi Hj Hij H. } apply Nat.nle_gt in Hjn. apply nth_overflow. rewrite List_map_seq_length. flia Hjn. } apply Nat.nle_gt in Hin. apply nth_overflow. rewrite nth_overflow; [ cbn; flia | ]. rewrite List_map_seq_length. flia Hin. Qed. Theorem mat_el_mI_diag : ∀ n i, 1 ≤ i ≤ n → mat_el (mI n) i i = 1%L. Proof. intros * Hin. unfold mat_el, mI; cbn. rewrite List_map_nth' with (a := 0). 2: { now rewrite seq_length; apply Nat_1_le_sub_lt. } rewrite List_map_nth' with (a := 0). 2: { now rewrite seq_length; apply Nat_1_le_sub_lt. } rewrite seq_nth; [ | now apply Nat_1_le_sub_lt ]. unfold δ. now rewrite Nat.eqb_refl. Qed. (* *) Theorem mat_mul_nrows : ∀ MA MB, mat_nrows (MA * MB) = mat_nrows MA. Proof. intros; cbn. now rewrite List_map_seq_length. Qed. Theorem mat_mul_ncols : ∀ MA MB, mat_nrows MA ≠ 0 → mat_ncols (MA * MB) = mat_ncols MB. Proof. intros * Hraz; unfold mat_ncols; cbn. rewrite (List_map_hd 0). 2: { rewrite seq_length. now apply Nat.neq_0_lt_0. } now rewrite map_length, seq_length. Qed. Theorem mat_el_mul : ∀ MA MB i j, 1 ≤ i ≤ mat_nrows (MA * MB) → 1 ≤ j ≤ mat_ncols (MA * MB) → mat_el (MA * MB) i j = ∑ (k = 1, mat_ncols MA), mat_el MA i k * mat_el MB k j. Proof. intros * Hir Hjc; cbn. rewrite mat_mul_nrows in Hir. rewrite mat_mul_ncols in Hjc; [ | flia Hir ]. rewrite (List_map_nth' 0). 2: { now rewrite seq_length; apply Nat_1_le_sub_lt. } rewrite (List_map_nth' 0). 2: { now rewrite seq_length; apply Nat_1_le_sub_lt. } rewrite seq_nth; [ | now apply Nat_1_le_sub_lt ]. rewrite seq_nth; [ | now apply Nat_1_le_sub_lt ]. rewrite Nat.add_comm, Nat.sub_add; [ | easy ]. rewrite Nat.add_comm, Nat.sub_add; [ | easy ]. easy. Qed. (* multiplication left and right with identity *) Theorem mat_mul_1_l {n} : ∀ (M : matrix T), is_correct_matrix M = true → n = mat_nrows M → (mI n * M)%M = M. Proof. intros * HM Hn; subst n. specialize (proj2 rngl_has_opp_or_subt_iff) as Hos. specialize (Hos (or_introl Hop)). move Hos before Hop. apply is_scm_mat_iff in HM. destruct HM as (_, HM). unfold "*"%M. rewrite mI_nrows. destruct M as (ll); cbn in HM |-*. f_equal. unfold mat_ncols; cbn. remember (length (hd [] ll)) as ncols eqn:Hc. remember (map _ _) as x. rewrite List_map_nth_seq with (d := []); subst x. rewrite <- seq_shift. rewrite <- seq_shift, map_map. apply map_ext_in. intros i Hi. remember (nth i ll []) as la eqn:Hla. rewrite List_map_nth_seq with (d := 0%L). rewrite (HM la). 2: { rewrite Hla. apply nth_In. now apply in_seq in Hi. } unfold mat_ncols; cbn. rewrite <- Hc. rewrite map_map. apply map_ext_in. intros j Hj. unfold mat_mul_el. rewrite rngl_summation_split3 with (j := S i). 2: { split; [ now apply -> Nat.succ_le_mono | ]. apply in_seq in Hi. rewrite mI_ncols; flia Hi. } rewrite all_0_rngl_summation_0. 2: { intros k Hk. rewrite mat_el_mI_ndiag; [ | flia Hk | flia Hk | flia Hk ]. now apply rngl_mul_0_l. } rewrite rngl_add_0_l. apply in_seq in Hi. rewrite mat_el_mI_diag; [ | flia Hi ]. rewrite rngl_mul_1_l. remember (∑ (k = _, _), _) as x; cbn; subst x. do 2 rewrite Nat.sub_0_r. rewrite <- Hla. rewrite all_0_rngl_summation_0. 2: { intros k Hk. rewrite mat_el_mI_ndiag; [ | flia Hk | flia Hk | flia Hk ]. now apply rngl_mul_0_l. } apply rngl_add_0_r. Qed. Theorem mat_mul_1_r {n} : ∀ (M : matrix T), is_correct_matrix M = true → n = mat_ncols M → (M * mI n)%M = M. Proof. intros * HM H; subst n. specialize (proj2 rngl_has_opp_or_subt_iff) as Hos. specialize (Hos (or_introl Hop)). move Hos before Hop. apply is_scm_mat_iff in HM. destruct HM as (_, HM). unfold "*"%M. rewrite mI_ncols. destruct M as (ll); cbn in HM |-*. f_equal. unfold mat_ncols; cbn. remember (length (hd [] ll)) as ncols eqn:Hc. remember (map _ _) as x. rewrite List_map_nth_seq with (d := []); subst x. rewrite <- seq_shift, <- seq_shift, map_map. apply map_ext_in. intros i Hi. remember (nth i ll []) as la eqn:Hla. rewrite List_map_nth_seq with (d := 0%L). rewrite (HM la). 2: { rewrite Hla. apply nth_In. now apply in_seq in Hi. } unfold mat_ncols; cbn. rewrite <- Hc, map_map. apply map_ext_in. intros j Hj. unfold mat_mul_el. unfold mat_ncols at 1. cbn - [ mat_el ]. destruct ll as [| lb]; [ easy | ]. cbn - [ mat_el ]. rewrite (HM lb (or_introl eq_refl)). (* rather use more modern rngl_summation_split3... *) rewrite rngl_summation_split with (j := S j). 2: { split; [ now apply -> Nat.succ_le_mono | ]. apply -> Nat.succ_le_mono. apply in_seq in Hj. cbn in Hc |-*; rewrite <- Hc. flia Hj. } rewrite rngl_summation_split_last; [ | now apply -> Nat.succ_le_mono ]. rewrite all_0_rngl_summation_0. 2: { intros k Hk. rewrite mat_el_mI_ndiag; [ | flia Hk | flia | flia Hk ]. now apply rngl_mul_0_r. } rewrite rngl_add_0_l. apply in_seq in Hj. rewrite mat_el_mI_diag; [ | flia Hj ]. rewrite rngl_mul_1_r. rewrite all_0_rngl_summation_0. 2: { intros k Hk. rewrite mat_el_mI_ndiag; [ | flia Hk | flia | flia Hk ]. now apply rngl_mul_0_r. } rewrite rngl_add_0_r. subst la; cbn. now destruct i, j. Qed. Theorem mat_vect_mul_1_l : ∀ n (V : vector T), n = vect_size V → (mI n • V)%M = V. Proof. intros * Hn; subst n. specialize (proj2 rngl_has_opp_or_subt_iff) as Hos. specialize (Hos (or_introl Hop)). move Hos before Hop. apply vector_eq. 2: { now cbn; do 2 rewrite map_length; rewrite seq_length. } cbn; do 2 rewrite map_length; rewrite seq_length. intros i Hi. rewrite (List_map_nth' []). 2: { rewrite List_map_seq_length. now apply Nat_1_le_sub_lt. } rewrite (List_map_nth' 0). 2: { rewrite seq_length. now apply Nat_1_le_sub_lt. } rewrite seq_nth; [ cbn | now apply Nat_1_le_sub_lt ]. unfold vect_dot_mul; cbn. destruct V as (l); cbn in Hi |-*. rewrite map2_map_l. destruct i; [ easy | ]. rewrite Nat_sub_succ_1. rewrite (List_seq_cut3 i); [ cbn | now apply in_seq ]. rewrite Nat.sub_0_r. rewrite map2_app_l. rewrite seq_length. erewrite map2_ext_in. 2: { intros j k Hj Hk; apply in_seq in Hj. destruct Hj as (_, Hj); cbn in Hj. rewrite δ_ndiag; [ | flia Hj ]. now rewrite rngl_mul_0_l. } rewrite rngl_summation_list_app. rewrite all_0_rngl_summation_list_0. 2: { intros j Hj. apply in_map2_iff in Hj. destruct Hj as (k & Hki & u & v & Hu). easy. } rewrite rngl_add_0_l. remember (skipn i l) as l' eqn:Hl'. symmetry in Hl'. destruct l' as [| a']. { exfalso. revert l Hi Hl'. induction i; intros; [ now cbn in Hl'; subst l | ]. destruct l as [| a]; [ easy | ]. cbn in Hi, Hl'. apply (IHi l); [ flia Hi | easy ]. } cbn. rewrite δ_diag. rewrite rngl_mul_1_l. erewrite map2_ext_in. 2: { intros j k Hj Hk; apply in_seq in Hj. destruct Hj as (Hj, _). rewrite δ_ndiag; [ | flia Hj ]. now rewrite rngl_mul_0_l. } rewrite rngl_summation_list_cons. rewrite all_0_rngl_summation_list_0. 2: { intros j Hj. apply in_map2_iff in Hj. destruct Hj as (k & Hki & u & v & Hu). easy. } rewrite rngl_add_0_r. revert l Hl' Hi. induction i; intros; [ now cbn in Hl'; subst l | ]. destruct l as [| b]; [ easy | ]. cbn in Hi, Hl' |-*. apply IHi; [ easy | flia Hi ]. Qed. (* associativity of multiplication *) Theorem mat_mul_assoc : ∀ (MA : matrix T) (MB : matrix T) (MC : matrix T), mat_nrows MB ≠ 0 → mat_ncols MB ≠ 0 → mat_ncols MA = mat_nrows MB → (MA * (MB * MC))%M = ((MA * MB) * MC)%M. Proof. intros * Hrbz Hcbz Hcarb. specialize (proj2 rngl_has_opp_or_subt_iff) as Hos. specialize (Hos (or_introl Hop)). move Hos before Hop. unfold "*"%M. f_equal. unfold mat_nrows at 5; cbn. rewrite List_map_seq_length. apply map_ext_in. intros i Hi. unfold mat_ncols at 2; cbn. rewrite (List_map_hd 0). 2: { now rewrite seq_length; apply Nat.neq_0_lt_0. } rewrite List_map_seq_length. apply map_ext_in. intros j Hj. move j before i. unfold mat_mul_el. unfold mat_ncols at 4. cbn. rewrite (List_map_hd 0). 2: { rewrite seq_length; apply Nat.neq_0_lt_0. now intros H; rewrite H in Hi. } rewrite List_map_seq_length. rewrite (rngl_summation_shift 1); [ | flia Hcarb Hrbz ]. rewrite Nat.sub_diag. erewrite rngl_summation_eq_compat. 2: { intros k Hk. rewrite List_map_nth' with (a := 0). 2: { rewrite seq_length. rewrite Hcarb in Hk. flia Hrbz Hk. } rewrite List_map_nth' with (a := 0). 2: { rewrite seq_length. apply in_seq in Hj. apply Nat_1_le_sub_lt. flia Hj. } rewrite (rngl_summation_shift 1); [ | flia Hcbz ]. rewrite Nat.sub_diag. erewrite rngl_summation_eq_compat. 2: { intros m Hm. rewrite seq_nth; [ | rewrite Hcarb in Hk; flia Hrbz Hk ]. rewrite seq_nth. 2: { apply in_seq in Hj. apply Nat_1_le_sub_lt. flia Hj. } easy. } rewrite rngl_mul_summation_distr_l; [ | easy ]. erewrite rngl_summation_eq_compat. 2: { intros m Hm. now rewrite rngl_mul_assoc. } rewrite Nat.add_comm, Nat.add_sub, Nat.add_1_r. apply in_seq in Hj. rewrite (Nat.add_comm 1 (j - 1)), Nat.sub_add; [ | easy ]. easy. } cbn. symmetry. rewrite (rngl_summation_shift 1); [ | flia Hcbz ]. rewrite Nat.sub_diag. erewrite rngl_summation_eq_compat. 2: { intros k Hk. rewrite Nat.add_comm, Nat.add_sub. rewrite List_map_nth' with (a := 0). 2: { rewrite seq_length. apply in_seq in Hi; flia Hi. } rewrite List_map_nth' with (a := 0). 2: { rewrite seq_length. flia Hcbz Hk. } rewrite (rngl_summation_shift 1); [ | flia Hcarb Hrbz ]. rewrite Nat.sub_diag. erewrite rngl_summation_eq_compat. 2: { intros m Hm. rewrite seq_nth; [ | now apply in_seq in Hi; flia Hi ]. rewrite seq_nth; [ | flia Hcbz Hk ]. easy. } rewrite rngl_mul_summation_distr_r; [ | easy ]. apply in_seq in Hi. rewrite Nat.add_comm, Nat.sub_add; [ | easy ]. rewrite Nat.add_1_r. easy. } cbn. symmetry. apply rngl_summation_summation_list_swap. Qed. (* left distributivity of multiplication over addition *) Theorem mat_mul_add_distr_l : ∀ (MA : matrix T) (MB : matrix T) (MC : matrix T), is_correct_matrix MB = true → is_correct_matrix MC = true → mat_nrows MB ≠ 0 → mat_ncols MA = mat_nrows MB → mat_nrows MB = mat_nrows MC → mat_ncols MB = mat_ncols MC → (MA * (MB + MC) = MA * MB + MA * MC)%M. Proof. intros * Hb Hc Hrbz Hcarb Hcrbc Hcbc. unfold "*"%M, "+"%M. f_equal; cbn. rewrite map2_map_l, map2_map_r, map2_diag. apply map_ext_in. intros i Hi. rewrite map2_map_l, map2_map_r, <- Hcbc, map2_diag. unfold mat_ncols at 1; cbn. rewrite List_hd_nth_0. rewrite map2_nth with (a := []) (b := []); cycle 1. { rewrite fold_mat_nrows; flia Hrbz. } { rewrite fold_mat_nrows; flia Hrbz Hcrbc. } rewrite map2_length; cbn. do 2 rewrite <- List_hd_nth_0. do 2 rewrite fold_mat_ncols. rewrite <- Hcbc, Nat.min_id. apply map_ext_in. intros j Hj. unfold mat_mul_el; cbn. rewrite <- rngl_summation_add_distr. apply rngl_summation_eq_compat. intros k Hk. rewrite <- rngl_mul_add_distr_l. f_equal. rewrite map2_nth with (a := []) (b := []); cycle 1. { rewrite fold_mat_nrows. rewrite Hcarb in Hk; flia Hrbz Hk. } { rewrite fold_mat_nrows. rewrite Hcarb, Hcrbc in Hk. flia Hrbz Hcrbc Hk. } rewrite map2_nth with (a := 0%L) (b := 0%L); cycle 1. { apply is_scm_mat_iff in Hb. destruct Hb as (_, Hb). apply in_seq in Hj. rewrite Hb; [ flia Hj | ]. apply nth_In. rewrite fold_mat_nrows. rewrite Hcarb in Hk. flia Hrbz Hk. } { apply in_seq in Hj. rewrite fold_corr_mat_ncols; [ now rewrite <- Hcbc; flia Hj | easy | ]. rewrite <- Hcrbc. rewrite Hcarb in Hk. flia Hrbz Hk. } do 2 rewrite fold_mat_el. apply in_seq in Hj. rewrite <- Nat.sub_succ_l; [ | easy ]. rewrite <- Nat.sub_succ_l; [ | easy ]. now do 2 rewrite Nat_sub_succ_1. Qed. (* right distributivity of multiplication over addition *) Theorem mat_mul_add_distr_r : ∀ (MA : matrix T) (MB : matrix T) (MC : matrix T), is_correct_matrix MA = true → is_correct_matrix MB = true → mat_nrows MA ≠ 0 → mat_nrows MA = mat_nrows MB → mat_ncols MA = mat_ncols MB → ((MA + MB) * MC = MA * MC + MB * MC)%M. Proof. intros * Ha Hb Hraz Hrarb Hcacb. assert (Hcaz : mat_ncols MA ≠ 0). { apply is_scm_mat_iff in Ha. destruct Ha as (Ha, _). intros H; apply Hraz. now apply Ha. } unfold "*"%M, "+"%M. f_equal; cbn. rewrite map2_length. do 2 rewrite fold_mat_nrows. rewrite map2_map_l, map2_map_r, <- Hrarb, map2_diag. rewrite Nat.min_id. apply map_ext_in. intros i Hi. rewrite map2_map_l, map2_map_r, map2_diag. apply map_ext_in. intros j Hj. unfold mat_mul_el; cbn. rewrite <- Hcacb. rewrite <- rngl_summation_add_distr. unfold mat_ncols at 1; cbn. rewrite List_hd_nth_0. rewrite map2_nth with (a := []) (b := []); cycle 1. { rewrite fold_mat_nrows; flia Hraz. } { rewrite fold_mat_nrows, <- Hrarb; flia Hraz. } rewrite map2_length. do 2 rewrite <- List_hd_nth_0. do 2 rewrite fold_mat_ncols. rewrite <- Hcacb, Nat.min_id. apply rngl_summation_eq_compat. intros k Hk. rewrite map2_nth with (a := []) (b := []); cycle 1. { rewrite fold_mat_nrows. apply in_seq in Hi; flia Hi. } { rewrite fold_mat_nrows, <- Hrarb. apply in_seq in Hi; flia Hi. } rewrite map2_nth with (a := 0%L) (b := 0%L); cycle 1. { apply in_seq in Hi. rewrite fold_corr_mat_ncols; [ flia Hcaz Hk | easy | flia Hi ]. } { apply in_seq in Hi. rewrite Hrarb in Hi. rewrite fold_corr_mat_ncols; [ | easy | flia Hi ]. rewrite <- Hcacb; flia Hcaz Hk. } do 2 rewrite fold_mat_el. apply in_seq in Hi. rewrite <- Nat.sub_succ_l; [ | easy ]. rewrite <- Nat.sub_succ_l; [ | easy ]. do 2 rewrite Nat_sub_succ_1. apply rngl_mul_add_distr_r. Qed. (* *) Theorem mat_mul_scal_l_nrows : ∀ M μ, mat_nrows (μ × M) = mat_nrows M. Proof. now intros; cbn; rewrite map_length. Qed. Theorem mat_mul_scal_l_ncols : ∀ M μ, mat_ncols (μ × M) = mat_ncols M. Proof. intros. unfold mat_ncols; cbn. destruct (Nat.eq_dec (mat_nrows M) 0) as [Hrz| Hrz]. { unfold mat_nrows in Hrz. apply length_zero_iff_nil in Hrz. now rewrite Hrz. } apply Nat.neq_0_lt_0 in Hrz. rewrite (List_map_hd []); [ | now rewrite fold_mat_nrows ]. apply map_length. Qed. Theorem is_correct_matrix_mul_scal_l : ∀ M μ, is_correct_matrix M = true → is_correct_matrix (μ × M) = true. Proof. intros * Hm. apply is_scm_mat_iff in Hm. apply is_scm_mat_iff. destruct Hm as (Hcr, Hc). split. { unfold mat_ncols; cbn. rewrite map_length, fold_mat_nrows. intros Hc'. destruct (Nat.eq_dec (mat_nrows M) 0) as [Hrz| Hrz]; [ easy | ]. rewrite (List_map_hd []) in Hc'. 2: { rewrite fold_mat_nrows. now apply Nat.neq_0_lt_0 in Hrz. } rewrite map_length in Hc'. rewrite fold_mat_ncols in Hc'. now apply Hcr. } { intros la Hla. cbn in Hla. apply in_map_iff in Hla. destruct Hla as (lb & Hla & Hlb). subst la. rewrite map_length. rewrite mat_mul_scal_l_ncols. now apply Hc. } Qed. (* left distributivity of multiplication by scalar over addition *) Theorem mat_mul_scal_l_add_distr_r : ∀ a b (M : matrix T), ((a + b)%L × M)%M = (a × M + b × M)%M. Proof. intros. unfold "+"%M, "×"%M. cbn; f_equal. rewrite map2_map_l, map2_map_r. rewrite map2_diag. apply map_ext_in. intros la Hla. rewrite map2_map_l, map2_map_r. rewrite map2_diag. apply map_ext_in. intros c Hc. apply rngl_mul_add_distr_r. Qed. (* associativity of multiplication by scalar *) Theorem mat_mul_scal_l_mul_assoc : ∀ a b (M : matrix T), (a × (b × M))%M = ((a * b)%L × M)%M. Proof. intros. unfold "*"%M, "×"%M. cbn; f_equal. rewrite map_map. apply map_ext_in. intros la Hla. rewrite map_map. apply map_ext_in. intros i Hi. apply rngl_mul_assoc. Qed. Theorem mat_mul_scal_l_mul : ∀ a (MA : matrix T) (MB : matrix T), is_correct_matrix MA = true → (a × MA * MB = a × (MA * MB))%M. Proof. intros * Ha. specialize (proj2 rngl_has_opp_or_subt_iff) as Hos. specialize (Hos (or_introl Hop)). move Hos before Hop. unfold "*"%M, "×"%M. cbn; f_equal. rewrite map_length; cbn. rewrite fold_mat_nrows. rewrite map_map. apply map_ext_in. intros i Hi. destruct (Nat.eq_dec (mat_nrows MA) 0) as [Hraz| Hraz]. { now rewrite Hraz in Hi. } rewrite map_map. apply map_ext_in. intros j Hj. unfold mat_mul_el; cbn. unfold mat_ncols at 1; cbn. rewrite (List_map_hd []). 2: { now rewrite fold_mat_nrows; apply Nat.neq_0_lt_0. } rewrite map_length. rewrite fold_mat_ncols. rewrite rngl_mul_summation_distr_l; [ | easy ]. apply rngl_summation_eq_compat. intros k Hk. rewrite List_map_nth' with (a := []). 2: { rewrite fold_mat_nrows. apply in_seq in Hi; flia Hi. } rewrite List_map_nth' with (a := 0%L). 2: { apply is_scm_mat_iff in Ha. destruct Ha as (Harc, Ha). rewrite Ha. 2: { apply nth_In. rewrite fold_mat_nrows. apply in_seq in Hi; flia Hi. } assert (Hcaz : mat_ncols MA ≠ 0). { intros H; apply Hraz. now apply Harc. } flia Hk Hcaz. } rewrite fold_mat_el. symmetry. apply in_seq in Hi. rewrite <- Nat.sub_succ_l; [ | easy ]. rewrite <- Nat.sub_succ_l; [ | easy ]. do 2 rewrite Nat_sub_succ_1. apply rngl_mul_assoc. Qed. Theorem mat_mul_mul_scal_l : rngl_mul_is_comm = true → ∀ a (MA : matrix T) (MB : matrix T), is_correct_matrix MB = true → mat_ncols MA ≠ 0 → mat_ncols MA = mat_nrows MB → (MA * (a × MB) = a × (MA * MB))%M. Proof. intros Hic * Hb Hcaz Hcarb. specialize (proj2 rngl_has_opp_or_subt_iff) as Hos. specialize (Hos (or_introl Hop)). move Hos before Hop. apply Nat.neq_0_lt_0 in Hcaz. unfold "*"%M, "×"%M; cbn. f_equal. rewrite map_map. apply map_ext_in. intros i Hi. unfold mat_ncols at 1; cbn. rewrite (List_map_hd []); [ | now rewrite fold_mat_nrows, <- Hcarb ]. rewrite map_length. rewrite fold_mat_ncols. rewrite map_map. apply map_ext_in. intros j Hj. unfold mat_mul_el; cbn. rewrite rngl_mul_summation_distr_l; [ | easy ]. apply rngl_summation_eq_compat. intros k Hk. rewrite List_map_nth' with (a := []). 2: { rewrite fold_mat_nrows, <- Hcarb. flia Hcaz Hk. } rewrite List_map_nth' with (a := 0%L). 2: { apply is_scm_mat_iff in Hb. destruct Hb as (Hbzz, Hb). rewrite Hb; [ apply in_seq in Hj; flia Hj | ]. apply nth_In. rewrite fold_mat_nrows, <- Hcarb. flia Hcaz Hk. } rewrite fold_mat_el. rewrite rngl_mul_comm; [ | easy ]. rewrite <- rngl_mul_assoc. f_equal. apply in_seq in Hj. rewrite <- Nat.sub_succ_l; [ | easy ]. rewrite <- Nat.sub_succ_l; [ | easy ]. do 2 rewrite Nat_sub_succ_1. now apply rngl_mul_comm. Qed. Theorem mat_mul_scal_l_add_distr_l : ∀ a (MA MB : matrix T), (a × (MA + MB) = (a × MA + a × MB))%M. Proof. intros. unfold "+"%M, "×"%M; cbn. f_equal. rewrite map2_map_l, map2_map_r, map_map2. apply map2_ext_in. rename a into c. intros la lb Hla Hlb. rewrite map2_map_l, map2_map_r, map_map2. apply map2_ext_in. intros a b Ha Hb. apply rngl_mul_add_distr_l. Qed. (* associativity with multiplication with vector *) Theorem mat_vect_mul_assoc_as_sums : ∀ (A : matrix T) (B : matrix T) (V : vector T) i, 1 ≤ i ≤ mat_nrows A → ∑ (j = 1, mat_ncols A), mat_el A i j * (∑ (k = 1, vect_size V), mat_el B j k * vect_el V k) = ∑ (j = 1, vect_size V), (∑ (k = 1, mat_ncols A), mat_el A i k * mat_el B k j) * vect_el V j. Proof. intros * Hi. specialize (proj2 rngl_has_opp_or_subt_iff) as Hos. specialize (Hos (or_introl Hop)). move Hos before Hop. erewrite rngl_summation_eq_compat. 2: { intros j Hj. now rewrite rngl_mul_summation_distr_l. } symmetry. erewrite rngl_summation_eq_compat. 2: { intros j Hj. now rewrite rngl_mul_summation_distr_r. } symmetry. cbn. unfold iter_seq at 1 2. rewrite rngl_summation_summation_list_swap. rewrite fold_iter_seq. apply rngl_summation_eq_compat. intros j Hj. apply rngl_summation_eq_compat. intros k Hk. apply rngl_mul_assoc. Qed. Theorem mat_vect_mul_assoc : ∀ (A : matrix T) (B : matrix T) (V : vector T), is_correct_matrix A = true → is_correct_matrix B = true → mat_ncols A = mat_nrows B → mat_ncols B = vect_size V → (A • (B • V) = (A * B) • V)%M. Proof. intros * Ha Hb Hcarb Hcbv. specialize (proj2 rngl_has_opp_or_subt_iff) as Hos. specialize (Hos (or_introl Hop)). move Hos before Hop. unfold "•"%M, "*"%M; cbn. f_equal. rewrite map_map. rewrite List_map_map_seq with (d := []). rewrite fold_mat_nrows. symmetry. remember (seq 1 (mat_nrows A)) as x eqn:Hx. rewrite <- seq_shift in Hx; subst x. rewrite map_map. symmetry. apply map_ext_in. intros i Hi. unfold vect_dot_mul; cbn. rewrite map2_map_r. rewrite map2_map2_seq_l with (d := 0%L). rewrite map2_map2_seq_r with (d := []). apply is_scm_mat_iff in Ha. destruct Ha as (Harc, Ha). rewrite Ha. 2: { apply nth_In. rewrite fold_mat_nrows. now apply in_seq in Hi. } rewrite fold_mat_nrows. symmetry. rewrite map2_map2_seq_r with (d := 0%L). rewrite fold_vect_size. symmetry. rewrite <- Hcarb. rewrite map2_diag. rewrite rngl_summation_list_map. rewrite rngl_summation_seq_summation. 2: { intros H; apply Harc in H. now rewrite H in Hi. } cbn. apply is_scm_mat_iff in Hb. destruct Hb as (Hbrc, Hb). erewrite rngl_summation_eq_compat. 2: { intros j Hj. rewrite fold_mat_el. unfold vect_dot_mul; cbn. rewrite map2_map2_seq_l with (d := 0%L). rewrite Hb with (l := nth j (mat_list_list B) []). 2: { apply nth_In. rewrite fold_mat_nrows. rewrite <- Hcarb. destruct Hj as (_, Hj). apply Nat.lt_succ_r in Hj. rewrite <- Nat.sub_succ_l in Hj. 2: { apply Nat.le_succ_l. apply Nat.neq_0_lt_0. intros H. apply Harc in H. now rewrite H in Hi. } now rewrite Nat_sub_succ_1 in Hj. } rewrite map2_map2_seq_r with (d := 0%L). rewrite fold_vect_size. rewrite Hcbv. rewrite map2_diag. rewrite rngl_summation_list_map. rewrite rngl_summation_seq_summation. 2: { intros H; rewrite <- Hcbv in H. apply Hbrc in H. rewrite <- Hcarb in H. apply Harc in H. now rewrite H in Hi. } erewrite rngl_summation_eq_compat. 2: { intros k Hk. now rewrite fold_mat_el. } easy. } cbn. rewrite Hcbv. rewrite map2_map_l. rewrite <- seq_shift. rewrite map2_map_l. rewrite map2_diag. rewrite rngl_summation_list_map. rewrite rngl_summation_seq_summation. 2: { intros H; rewrite <- Hcbv in H. apply Hbrc in H. rewrite <- Hcarb in H. apply Harc in H. now rewrite H in Hi. } apply in_seq in Hi. rewrite rngl_summation_rshift. rewrite <- Nat.sub_succ_l. 2: { destruct (mat_ncols A); [ | flia ]. now rewrite Harc in Hi. } rewrite Nat_sub_succ_1. erewrite rngl_summation_eq_compat. 2: { intros j Hj. rewrite rngl_summation_rshift. rewrite <- Nat.sub_succ_l; [ | easy ]. rewrite Nat_sub_succ_1. rewrite <- Hcbv. rewrite <- Nat.sub_succ_l. 2: { remember (mat_ncols B) as c eqn:Hc; symmetry in Hc. destruct c; [ exfalso | flia ]. rewrite Hbrc in Hcarb; [ | easy ]. rewrite Hcarb in Hj; flia Hj. } rewrite Nat_sub_succ_1. erewrite rngl_summation_eq_compat. 2: { intros k Hk. rewrite <- Nat.sub_succ_l; [ | easy ]. rewrite Nat_sub_succ_1. easy. } easy. } rewrite Hcbv. rewrite mat_vect_mul_assoc_as_sums; [ | flia Hi ]. remember (vect_size V) as s eqn:Hs; symmetry in Hs. destruct s. { rewrite rngl_summation_empty; [ | easy ]. rewrite rngl_summation_only_one; cbn. rewrite Hbrc in Hcarb; [ | easy ]. destruct A as (lla). destruct B as (llb). unfold mat_mul_el; cbn. rewrite Hcarb. rewrite rngl_summation_empty; [ | easy ]. symmetry. now apply rngl_mul_0_l. } rewrite (rngl_summation_shift 1). 2: { split; [ easy | flia ]. } rewrite Nat.sub_diag, Nat.add_0_l, Nat_sub_succ_1. apply rngl_summation_eq_compat. intros j Hj. f_equal. unfold vect_el. now rewrite Nat.add_comm, Nat.add_sub. Qed. Theorem mat_mul_scal_vect_assoc : ∀ a (MA : matrix T) (V : vector T), is_correct_matrix MA = true → mat_ncols MA = vect_size V → (a × (MA • V))%V = ((a × MA) • V)%M. Proof. intros * Ha Hcav. specialize (proj2 rngl_has_opp_or_subt_iff) as Hos. specialize (Hos (or_introl Hop)). move Hos before Hop. unfold "×"%V, "×"%M, "•"%V; cbn. f_equal. do 2 rewrite map_map. rewrite List_map_map_seq with (d := []). rewrite fold_mat_nrows. rewrite List_map_map_seq with (d := []). rewrite fold_mat_nrows. apply map_ext_in. intros i Hi. unfold vect_dot_mul; cbn. rewrite map2_map_l. rewrite rngl_mul_summation_list_distr_l; [ | easy ]. rewrite map2_map2_seq_l with (d := 0%L). apply is_scm_mat_iff in Ha. destruct Ha as (Harc, Ha). rewrite Ha. 2: { apply nth_In. rewrite fold_mat_nrows. now apply in_seq in Hi. } rewrite map2_map2_seq_r with (d := 0%L). rewrite fold_vect_size, Hcav. rewrite map2_diag. rewrite rngl_summation_list_map. rewrite rngl_summation_seq_summation. 2: { rewrite <- Hcav; intros H. apply Harc in H. now rewrite H in Hi. } erewrite rngl_summation_eq_compat; [ | easy ]. rewrite map2_map2_seq_l with (d := 0%L). rewrite Ha. 2: { apply nth_In. rewrite fold_mat_nrows. now apply in_seq in Hi. } rewrite map2_map2_seq_r with (d := 0%L). rewrite fold_vect_size, Hcav. rewrite map2_diag. rewrite rngl_summation_list_map. rewrite rngl_summation_seq_summation. 2: { rewrite <- Hcav; intros H. apply Harc in H. now rewrite H in Hi. } symmetry. erewrite rngl_summation_eq_compat; [ | easy ]. symmetry. apply rngl_summation_eq_compat. intros j Hj. apply rngl_mul_assoc. Qed. Theorem mat_mul_scal_vect_comm : rngl_mul_is_comm = true → ∀ a (MA : matrix T) V, is_correct_matrix MA = true → mat_ncols MA = vect_size V → (a × (MA • V) = MA • (a × V))%V. Proof. intros Hic * Ha Hcav. specialize (proj2 rngl_has_opp_or_subt_iff) as Hos. specialize (Hos (or_introl Hop)). move Hos before Hop. unfold "×"%V, "•"%M; cbn. f_equal. rewrite map_map. do 2 rewrite List_map_map_seq with (d := []). rewrite fold_mat_nrows. apply map_ext_in. intros i Hi. unfold vect_dot_mul; cbn. rewrite rngl_mul_summation_list_distr_l; [ | easy ]. rewrite map2_map_r. rewrite map2_map2_seq_l with (d := 0%L). rewrite map2_map2_seq_r with (d := 0%L). rewrite fold_vect_size. apply is_scm_mat_iff in Ha. destruct Ha as (Harc, Ha). rewrite Ha. 2: { apply nth_In. rewrite fold_mat_nrows. now apply in_seq in Hi. } symmetry. rewrite map2_map2_seq_l with (d := 0%L). rewrite map2_map2_seq_r with (d := 0%L). rewrite fold_vect_size. rewrite Ha. 2: { apply nth_In. rewrite fold_mat_nrows. now apply in_seq in Hi. } rewrite Hcav. do 2 rewrite map2_diag. do 2 rewrite rngl_summation_list_map. assert (Hvz : vect_size V ≠ 0). { intros H; rewrite <- Hcav in H. apply Harc in H. now rewrite H in Hi. } rewrite rngl_summation_seq_summation; [ | easy ]. rewrite rngl_summation_seq_summation; [ | easy ]. apply rngl_summation_eq_compat. intros j Hj. do 2 rewrite rngl_mul_assoc. f_equal. now apply rngl_mul_comm. Qed. (* matrix transpose *) Definition mat_transp (M : matrix T) : matrix T := mk_mat (map (λ j, map (λ i, mat_el M i j) (seq 1 (mat_nrows M))) (seq 1 (mat_ncols M))). Notation "A ⁺" := (mat_transp A) (at level 1, format "A ⁺") : M_scope. Theorem fold_mat_transp : ∀ M, mk_mat (map (λ j, map (λ i, mat_el M i j) (seq 1 (mat_nrows M))) (seq 1 (mat_ncols M))) = mat_transp M. Proof. easy. Qed. Theorem mat_transp_nrows : ∀ M, mat_nrows M⁺ = mat_ncols M. Proof. intros. unfold mat_ncols; cbn. now rewrite map_length, seq_length. Qed. Theorem mat_transp_ncols : ∀ M, mat_ncols M⁺ = if mat_ncols M =? 0 then 0 else mat_nrows M. Proof. intros. rewrite if_eqb_eq_dec. destruct (Nat.eq_dec (mat_ncols M) 0) as [Hcz| Hcz]. { now unfold mat_ncols; cbn; rewrite Hcz. } apply Nat.neq_0_lt_0 in Hcz. unfold mat_ncols; cbn. rewrite (List_map_hd 0); [ | now rewrite seq_length ]. now rewrite List_map_seq_length. Qed. Theorem mat_transp_is_corr : ∀ M, is_correct_matrix M = true → is_correct_matrix M⁺ = true. Proof. intros * Hcm. apply is_scm_mat_iff in Hcm. destruct Hcm as (H1, H2). destruct (Nat.eq_dec (mat_ncols M) 0) as [Hcz| Hcz]. { specialize (H1 Hcz). unfold mat_transp. now rewrite H1, Hcz. } apply is_scm_mat_iff. rewrite mat_transp_ncols. apply Nat.eqb_neq in Hcz; rewrite Hcz. apply Nat.eqb_neq in Hcz. split. { intros Hr. unfold mat_nrows in Hr. unfold mat_ncols in Hcz. apply length_zero_iff_nil in Hr. now rewrite Hr in Hcz. } { intros l Hl. unfold mat_transp in Hl; cbn in Hl. apply in_map_iff in Hl. destruct Hl as (j & Hjl & Hj). now rewrite <- Hjl, List_map_seq_length. } Qed. Theorem mat_mul_is_corr : ∀ A B, is_correct_matrix A = true → is_correct_matrix B = true → mat_nrows B ≠ 0 → is_correct_matrix (A * B) = true. Proof. intros * Ha Hb Hbz. destruct (Nat.eq_dec (mat_nrows A) 0) as [Haz| Haz]. { unfold mat_nrows in Haz. apply length_zero_iff_nil in Haz. now destruct A as (lla); cbn in Haz; subst lla. } apply Nat.neq_0_lt_0 in Haz, Hbz. apply is_scm_mat_iff in Ha. apply is_scm_mat_iff in Hb. apply is_scm_mat_iff. destruct Ha as (Hacr & Hac). destruct Hb as (Hbcr & Hbc). split. { intros Hab. unfold mat_ncols in Hab. cbn in Hab |-*. rewrite List_map_seq_length. rewrite (List_map_hd 0) in Hab; [ | now rewrite seq_length ]. rewrite List_map_seq_length in Hab. now rewrite Hbcr in Hbz. } { intros lab Hlab. unfold mat_ncols; cbn. rewrite (List_map_hd 0); [ | now rewrite seq_length ]. rewrite List_map_seq_length. cbn in Hlab. apply in_map_iff in Hlab. destruct Hlab as (x & Hlab & Hx). now rewrite <- Hlab, List_map_seq_length. } Qed. Theorem mat_transp_el : ∀ M i j, is_correct_matrix M = true → i ≠ 0 → j ≠ 0 → mat_el M⁺ i j = mat_el M j i. Proof. intros * Hcm Hiz Hjz. unfold mat_el; cbn. destruct (le_dec i (mat_ncols M)) as [Hic| Hic]. 2: { apply Nat.nle_gt in Hic. rewrite nth_overflow. 2: { rewrite nth_overflow; [ easy | ]. rewrite List_map_seq_length. flia Hic. } rewrite nth_overflow; [ easy | ]. destruct (le_dec j (mat_nrows M)) as [Hjr| Hjr]. { apply is_scm_mat_iff in Hcm. destruct Hcm as (H1, H2). rewrite H2; [ flia Hic | ]. apply nth_In; rewrite fold_mat_nrows. flia Hjz Hjr. } apply Nat.nle_gt in Hjr. rewrite nth_overflow; [ easy | ]. rewrite fold_mat_nrows. flia Hjz Hjr. } rewrite (List_map_nth' 0); [ | rewrite seq_length; flia Hiz Hic ]. destruct (le_dec j (mat_nrows M)) as [Hjr| Hjr]. { rewrite (List_map_nth' 0); [ | rewrite seq_length; flia Hjz Hjr ]. unfold mat_el. rewrite seq_nth; [ cbn | flia Hiz Hic ]. rewrite seq_nth; [ cbn | flia Hjz Hjr ]. do 2 rewrite Nat.sub_0_r. easy. } apply Nat.nle_gt in Hjr. rewrite nth_overflow; [ | rewrite List_map_seq_length; flia Hjr ]. rewrite nth_overflow; [ easy | ]. destruct i; [ easy | cbn ]. rewrite Nat.sub_0_r. rewrite nth_overflow; [ easy | ]. rewrite fold_mat_nrows; flia Hjz Hjr. Qed. Theorem mat_transp_mul : rngl_mul_is_comm = true → ∀ (MA : matrix T) (MB : matrix T), is_correct_matrix MA = true → is_correct_matrix MB = true → mat_nrows MA ≠ 0 → mat_nrows MB ≠ 0 → mat_ncols MA = mat_nrows MB → ((MA * MB)⁺ = MB⁺ * MA⁺)%M. Proof. intros Hic * Ha Hb Haz Hbz Hcarb. apply matrix_eq; cycle 1. { apply mat_transp_is_corr. now apply mat_mul_is_corr. } { apply mat_mul_is_corr. { now apply mat_transp_is_corr. } { now apply mat_transp_is_corr. } rewrite mat_transp_nrows. intros H. apply is_scm_mat_iff in Ha. destruct Ha as (Hcra, Hcla). now apply Hcra in H. } { cbn. unfold mat_ncols; cbn. do 3 rewrite List_map_seq_length. rewrite (List_map_hd 0); [ | now rewrite seq_length; apply Nat.neq_0_lt_0 ]. now rewrite List_map_seq_length. } { unfold mat_ncols; cbn. do 2 rewrite List_map_seq_length. rewrite (List_map_hd 0). 2: { rewrite seq_length. unfold mat_ncols; cbn. rewrite (List_map_hd 0). 2: { rewrite seq_length. now apply Nat.neq_0_lt_0. } rewrite List_map_seq_length. apply Nat.neq_0_lt_0. intros H. apply is_scm_mat_iff in Hb. now apply Hb in H. } rewrite List_map_seq_length. rewrite (List_map_hd 0). 2: { rewrite seq_length. apply Nat.neq_0_lt_0. intros H. apply is_scm_mat_iff in Hb. now apply Hb in H. } rewrite List_map_seq_length. rewrite mat_transp_ncols. rewrite if_eqb_eq_dec. destruct (Nat.eq_dec _ _) as [Hacz| Hacz]; [ | easy ]. apply is_scm_mat_iff in Ha. now apply Ha. } intros i j Hi Hj. rewrite mat_transp_nrows in Hi. rewrite mat_transp_el; [ | now apply mat_mul_is_corr | flia Hi | flia Hj ]. rewrite mat_mul_ncols in Hi; [ | easy ]. rewrite mat_mul_ncols in Hj; [ | rewrite mat_transp_nrows; flia Hi ]. rewrite mat_transp_ncols in Hj. rewrite if_eqb_eq_dec in Hj. destruct (Nat.eq_dec (mat_ncols MA) 0) as [H1| H1]; [ flia Hj | ]. rewrite mat_el_mul; cycle 1. { now rewrite mat_mul_nrows. } { now rewrite mat_mul_ncols. } rewrite mat_el_mul; cycle 1. { now rewrite mat_mul_nrows, mat_transp_nrows. } { rewrite mat_mul_ncols, mat_transp_ncols. 2: { rewrite mat_transp_nrows; flia Hi. } now apply Nat.eqb_neq in H1; rewrite H1. } rewrite mat_transp_ncols. rewrite if_eqb_eq_dec. destruct (Nat.eq_dec (mat_ncols MB) 0) as [H2| H2]; [ flia Hi H2 | ]. rewrite <- Hcarb; symmetry. erewrite rngl_summation_eq_compat. 2: { intros k Hk. rewrite rngl_mul_comm; [ | easy ]. rewrite mat_transp_el; [ | easy | flia Hk | flia Hj ]. easy. } cbn - [ mat_el ]. apply rngl_summation_eq_compat. intros k Hk. f_equal. unfold mat_transp; cbn. unfold mat_el. rewrite (List_map_nth' 0); [ | rewrite seq_length; flia Hi ]. rewrite (List_map_nth' 0); [ | rewrite seq_length ]. 2: { rewrite <- Hcarb; flia Hk. } rewrite seq_nth; [ | flia Hi ]. rewrite seq_nth; [ | flia Hk Hcarb ]. rewrite Nat.add_comm, Nat.add_sub. rewrite Nat.add_comm, Nat.add_sub. easy. Qed. (* matrix without row i and column j *) Definition subm i j (M : matrix T) := mk_mat (map (butn (j - 1)) (butn (i - 1) (mat_list_list M))). (* combinations of submatrix and other operations *) Theorem mat_nrows_subm : ∀ (M : matrix T) i j, mat_nrows (subm i j M) = mat_nrows M - Nat.b2n (i <=? mat_nrows M). Proof. intros. destruct M as (ll); cbn - [ "<?" ]. rewrite map_length, butn_length. unfold Nat.b2n. rewrite if_ltb_lt_dec, if_leb_le_dec. destruct (lt_dec _ _) as [H1| H1]. { destruct (le_dec _ _) as [H2| H2]; [ easy | flia H1 H2 ]. } destruct (le_dec _ _) as [H2| H2]; [ flia H1 H2 | easy ]. Qed. Theorem mat_ncols_subm : ∀ (M : matrix T) i j, is_correct_matrix M = true → 1 ≤ i ≤ mat_nrows M → 1 ≤ j ≤ mat_ncols M → mat_ncols (subm i j M) = if mat_nrows M =? 1 then 0 else mat_ncols M - 1. Proof. intros * Hcm Hi Hj. destruct M as (ll); cbn in Hi, Hj. unfold mat_ncols in Hj |-*; cbn in Hj |-*. destruct i; [ easy | ]. destruct j; [ easy | ]. destruct Hi as (_, Hi). destruct Hj as (_, Hj). apply -> Nat.le_succ_l in Hi. apply -> Nat.le_succ_l in Hj. do 2 rewrite Nat_sub_succ_1. apply is_scm_mat_iff in Hcm. unfold mat_ncols in Hcm; cbn in Hcm. destruct Hcm as (_, Hcl). destruct ll as [| la]; intros; [ easy | ]. cbn in Hi, Hj |-*. cbn - [ In ] in Hcl. assert (H : ∀ l, l ∈ ll → length l = length la). { intros l Hl. now apply Hcl; right. } move H before Hcl; clear Hcl; rename H into Hcl. apply Nat.le_succ_l in Hi. apply Nat.succ_le_mono in Hi. destruct ll as [| lb]. { now apply Nat.le_0_r in Hi; subst i; cbn. } cbn in Hi |-*. destruct i. { cbn; rewrite butn_length. rewrite Hcl; [ | now left ]. now apply Nat.ltb_lt in Hj; rewrite Hj. } apply Nat.succ_le_mono in Hi. cbn; rewrite butn_length. now apply Nat.ltb_lt in Hj; rewrite Hj. Qed. Theorem is_squ_mat_subm : ∀ (M : matrix T) i j, 1 ≤ i ≤ mat_nrows M → 1 ≤ j ≤ mat_nrows M → is_square_matrix M = true → is_square_matrix (subm i j M) = true. Proof. intros * Hi Hj Hm. apply is_scm_mat_iff. specialize (squ_mat_ncols _ Hm) as Hcm. destruct (Nat.eq_dec (mat_nrows M) 1) as [Hr1| Hr1]. { rewrite Hr1 in Hi, Hj. replace i with 1 by flia Hi. replace j with 1 by flia Hj. cbn. destruct M as (ll); cbn in Hr1 |-*. destruct ll as [| l]; [ easy | ]. now destruct ll. } split. { intros Hcs. rewrite <- Hcm in Hj. rewrite mat_ncols_subm in Hcs; [ | | easy | easy ]. 2: { now apply squ_mat_is_corr. } apply Nat.eqb_neq in Hr1; rewrite Hr1 in Hcs. apply Nat.eqb_neq in Hr1. flia Hj Hcm Hr1 Hcs. } { intros l Hl. apply is_scm_mat_iff in Hm. destruct Hm as (_ & Hc). clear Hcm Hr1. rewrite mat_nrows_subm. generalize Hi; intros (_, H). apply Nat.leb_le in H; rewrite H; clear H; cbn. destruct M as (ll). cbn in Hc, Hi, Hj |-*. cbn - [ butn ] in Hl. rewrite map_butn in Hl. apply in_butn in Hl. apply in_map_iff in Hl. destruct Hl as (l' & Hjl & Hl). rewrite <- Hjl. rewrite butn_length. unfold Nat.b2n. rewrite if_ltb_lt_dec. destruct (lt_dec _ (length l')) as [Hljl| Hljl]. { f_equal. now apply Hc. } apply Nat.nlt_ge in Hljl. rewrite butn_out in Hjl; [ | easy ]. subst l'. rewrite Hc in Hljl; [ | easy ]. flia Hj Hljl. } Qed. Theorem subm_is_corr_mat : ∀ (A : matrix T) i j, mat_ncols A ≠ 1 → is_correct_matrix A = true → 1 ≤ i ≤ mat_nrows A → 1 ≤ j ≤ mat_ncols A → is_correct_matrix (subm i j A) = true. Proof. intros * Hc1 Ha Hi Hj. apply is_scm_mat_iff. split. { rewrite mat_nrows_subm. generalize Hi; intros (_, H). apply Nat.leb_le in H; rewrite H; clear H; cbn. rewrite mat_ncols_subm; [ | easy | easy | easy ]. rewrite if_eqb_eq_dec. destruct (Nat.eq_dec (mat_nrows A) 1) as [Hr1| Hr1]; [ now rewrite Hr1 | ]. intros H. flia Hc1 H Hj. } { intros l Hl. rewrite mat_ncols_subm; [ | easy | easy | easy ]. rewrite if_eqb_eq_dec. destruct (Nat.eq_dec _ _) as [Hr1| Hr1]. { destruct A as (ll). cbn - [ butn ] in *. destruct ll as [| lb]; [ easy | ]. destruct ll; [ | easy ]. cbn in Hi. now replace i with 1 in Hl by flia Hi. } move Hr1 after Hc1. cbn in Hl. apply in_map_iff in Hl. destruct Hl as (la & Hl & Hla). subst l. rewrite butn_length. unfold Nat.b2n. rewrite if_ltb_lt_dec. apply is_scm_mat_iff in Ha. destruct Ha as (_, Hcl). apply in_butn in Hla. specialize (Hcl _ Hla). destruct (lt_dec _ _) as [Hja| Hja]; [ now rewrite Hcl | ]. rewrite Nat.nlt_ge in Hja. rewrite Hcl in Hja. flia Hj Hja. } Qed. Theorem mat_mul_scal_1_l : ∀ (M : matrix T), (1 × M = M)%M. Proof. intros. unfold "×"%M. destruct M as (ll). f_equal; cbn. induction ll as [| la]; [ easy | cbn ]. rewrite IHll; f_equal. induction la as [| a]; [ easy | cbn ]. now rewrite rngl_mul_1_l, IHla. Qed. (* ring of square matrices *) Theorem smat_nrows : ∀ n (M : square_matrix n T), mat_nrows (sm_mat M) = n. Proof. intros. destruct M as (M & Hmp); cbn. apply Bool.andb_true_iff in Hmp. destruct Hmp as (Hr & Hmp). now apply Nat.eqb_eq in Hr. Qed. Theorem smat_ncols : ∀ n (M : square_matrix n T), mat_ncols (sm_mat M) = n. Proof. intros. destruct M as (M, Hmp); cbn. apply Bool.andb_true_iff in Hmp. destruct Hmp as (Hr, Hmp). apply Nat.eqb_eq in Hr. apply is_scm_mat_iff in Hmp. destruct Hmp as (Hrc, Hc). destruct (Nat.eq_dec n 0) as [Hnz| Hnz]. { move Hnz at top; subst n. unfold mat_ncols. unfold mat_nrows in Hr. apply length_zero_iff_nil in Hr. now rewrite Hr. } unfold mat_ncols. rewrite <- Hr. apply Hc. apply List_hd_in. unfold mat_nrows in Hr. rewrite Hr. now apply Nat.neq_0_lt_0. Qed. Theorem mI_is_square_matrix : ∀ n, is_square_matrix (mI n) = true. Proof. intros. apply is_scm_mat_iff. destruct (Nat.eq_dec n 0) as [Hnz| Hnz]; [ now subst n | ]. apply Nat.neq_0_lt_0 in Hnz. split. { unfold mat_ncols. cbn; rewrite map_length, seq_length. rewrite (List_map_hd 0); [ | now rewrite seq_length ]. now rewrite map_length, seq_length. } intros la Hla. cbn in Hla. apply in_map_iff in Hla. destruct Hla as (i & Hin & Hi). subst la; cbn. now do 2 rewrite List_map_seq_length. Qed. Theorem mI_is_correct_matrix : ∀ n, is_correct_matrix (mI n) = true. Proof. intros. apply squ_mat_is_corr, mI_is_square_matrix. Qed. Theorem mZ_is_correct_matrix : ∀ m n, n ≠ 0 → is_correct_matrix (mZ m n) = true. Proof. intros * Hnz. destruct (Nat.eq_dec m 0) as [Hmz| Hmz]; [ now subst m | ]. apply is_scm_mat_iff. split. { intros Hc. now rewrite mZ_ncols in Hc. } intros l Hl. rewrite mZ_ncols; [ | easy ]. cbn in Hl. apply repeat_spec in Hl. subst l. apply repeat_length. Qed. Theorem mat_opp_is_correct : ∀ M, is_correct_matrix M = true → is_correct_matrix (- M) = true. Proof. intros * Hm. apply is_scm_mat_iff in Hm. apply is_scm_mat_iff. destruct Hm as (Hcr, Hc). destruct (Nat.eq_dec (mat_nrows M) 0) as [Hrz| Hrz]. { apply eq_mat_nrows_0 in Hrz. unfold is_correct_matrix. unfold mat_ncols, mat_nrows; cbn. now rewrite Hrz; cbn. } apply Nat.neq_0_lt_0 in Hrz. unfold is_correct_matrix. unfold mat_ncols, mat_nrows; cbn. rewrite (List_map_hd []); [ | easy ]. do 2 rewrite map_length. rewrite fold_mat_nrows, fold_mat_ncols. split; [ easy | ]. intros la Hla. apply in_map_iff in Hla. destruct Hla as (lb & Hla & Hlb); subst la. rewrite map_length. now apply Hc. Qed. Theorem squ_mat_add_is_squ : ∀ (MA MB : matrix T), is_square_matrix MA = true → is_square_matrix MB = true → is_square_matrix (MA + MB) = true. Proof. intros * Ha Hb. apply is_scm_mat_iff; cbn. apply is_scm_mat_iff in Ha. apply is_scm_mat_iff in Hb. destruct Ha as (Hcra & Hca). destruct Hb as (Hcrb & Hcb). split. { intros Hcc. rewrite map2_length. do 2 rewrite fold_mat_nrows. unfold mat_ncols in Hcc; cbn in Hcc. destruct (Nat.eq_dec (mat_nrows MA) 0) as [Hraz| Hraz]. { now rewrite Hraz, Nat.min_0_l. } destruct (Nat.eq_dec (mat_nrows MB) 0) as [Hrbz| Hrbz]. { now rewrite Hrbz, Nat.min_0_r. } apply Nat.neq_0_lt_0 in Hraz, Hrbz. rewrite List_hd_nth_0 in Hcc. rewrite map2_nth with (a := []) (b := []) in Hcc; [ | easy | easy ]. rewrite map2_length in Hcc. do 2 rewrite <- List_hd_nth_0 in Hcc. do 2 rewrite fold_mat_ncols in Hcc. apply Nat.le_0_r, Nat.min_le in Hcc. destruct Hcc as [Hc| Hc]; apply Nat.le_0_r in Hc. { now rewrite Hcra in Hraz. } { now rewrite Hcrb in Hrbz. } } { intros l Hl. apply in_map2_iff in Hl. destruct Hl as (i & Him & a & b & Hl). subst l. do 2 rewrite map2_length. do 2 rewrite fold_mat_nrows in Him |-*. apply Nat.min_glb_lt_iff in Him. rewrite Hca; [ | now apply nth_In; rewrite fold_mat_nrows ]. rewrite Hcb; [ | now apply nth_In; rewrite fold_mat_nrows ]. easy. } Qed. Theorem squ_mat_mul_is_squ : ∀ (MA MB : matrix T), is_square_matrix MA = true → is_square_matrix MB = true → mat_nrows MA = mat_nrows MB → is_square_matrix (MA * MB) = true. Proof. intros * Ha Hb Hrab. apply is_scm_mat_iff; cbn. rewrite List_map_seq_length. rewrite (squ_mat_ncols MB); [ | easy ]. split. { intros Hcc. unfold mat_ncols in Hcc; cbn in Hcc. rewrite squ_mat_ncols in Hcc; [ | easy ]. rewrite <- Hrab in Hcc. apply length_zero_iff_nil in Hcc. destruct (Nat.eq_dec (mat_nrows MA) 0) as [Hrz| Hrz]; [ easy | ]. apply Nat.neq_0_lt_0 in Hrz. rewrite (List_map_hd 0) in Hcc; [ | now rewrite seq_length ]. apply map_eq_nil in Hcc. now apply List_seq_eq_nil in Hcc. } { intros l Hl. apply in_map_iff in Hl. destruct Hl as (i & Hil & Hi). subst l. now rewrite List_map_seq_length. } Qed. Theorem square_matrix_add_is_square : ∀ n (MA MB : square_matrix n T), is_square_matrix (sm_mat MA + sm_mat MB)%M = true. Proof. intros. destruct MA as (MA & Ha). destruct MB as (MB & Hb); cbn. apply Bool.andb_true_iff in Ha, Hb. now apply squ_mat_add_is_squ. Qed. Theorem square_matrix_mul_is_square : ∀ n (MA MB : square_matrix n T), is_square_matrix (sm_mat MA * sm_mat MB) = true. Proof. intros. destruct MA as (MA & Ha). destruct MB as (MB & Hb); cbn. apply Bool.andb_true_iff in Ha, Hb. apply squ_mat_mul_is_squ; [ easy | easy | ]. destruct Ha as (Ha, _). destruct Hb as (Hb, _). apply Nat.eqb_eq in Ha. apply Nat.eqb_eq in Hb. congruence. Qed. Theorem square_matrix_opp_is_square : ∀ n (M : square_matrix n T), is_square_matrix (- sm_mat M)%M = true. Proof. intros. apply is_scm_mat_iff. split. { intros Hco; cbn. rewrite map_length. rewrite fold_mat_nrows. rewrite smat_nrows. destruct (Nat.eq_dec n 0) as [Hnz| Hnz]; [ easy | exfalso ]. apply Nat.neq_0_lt_0 in Hnz. unfold mat_ncols in Hco. cbn in Hco. apply length_zero_iff_nil in Hco. rewrite (List_map_hd []) in Hco. 2: { now rewrite fold_mat_nrows, smat_nrows. } apply map_eq_nil in Hco. apply (f_equal length) in Hco. rewrite fold_mat_ncols in Hco. rewrite smat_ncols in Hco. now rewrite Hco in Hnz. } { intros l Hl. destruct M as (M & Hrc); cbn in Hl |-*. apply Bool.andb_true_iff in Hrc. destruct Hrc as (Hr, Hsm). apply Nat.eqb_eq in Hr. apply is_scm_mat_iff in Hsm. destruct Hsm as (Hrc, Hc). rewrite Hr in Hrc, Hc. rewrite map_length, fold_mat_nrows, Hr. apply in_map_iff in Hl. destruct Hl as (la & Hlm & Hla). subst l. rewrite map_length. now apply Hc. } Qed. Theorem squ_mat_mul_scal_l_is_squ : ∀ (M : matrix T) μ, is_square_matrix M = true → is_square_matrix (μ × M) = true. Proof. intros * Hm. apply is_scm_mat_iff in Hm. apply is_scm_mat_iff. destruct Hm as (Hcr & Hc). cbn; rewrite map_length, fold_mat_nrows. split. { intros H1. destruct (Nat.eq_dec (mat_nrows M) 0) as [Hrz| Hrz]; [ easy | ]. apply Nat.neq_0_lt_0 in Hrz. apply Hcr. unfold mat_ncols in H1 |-*; cbn in H1 |-*. rewrite (List_map_hd []) in H1; [ | easy ]. now rewrite map_length in H1. } intros la Hla. apply in_map_iff in Hla. destruct Hla as (lb & Hla & Hi); subst la. rewrite map_length. now apply Hc. Qed. Theorem square_matrix_is_correct : ∀ n (M : square_matrix n T), is_correct_matrix (sm_mat M) = true. Proof. intros. destruct M as (M, Hm); cbn. apply Bool.andb_true_iff in Hm. destruct Hm as (Hr, Hm). now apply squ_mat_is_corr. Qed. (* Theorem mat_opt_eq_dec : if rngl_has_dec_eq then ∀ MA MB : matrix T, {MA = MB} + {MA ≠ MB} else not_applicable. Proof. remember rngl_has_dec_eq as de eqn:Hde; symmetry in Hde. destruct de; [ | easy ]. intros MA MB. destruct MA as (lla). destruct MB as (llb). specialize (list_eq_dec (list_eq_dec (rngl_eq_dec Hde)) lla llb) as H1. destruct H1 as [H1| H1]; [ now subst lla; left | ]. right. intros H; apply H1; clear H1. now injection H. Qed. Theorem mat_eq_dec : rngl_has_dec_eq = true → ∀ MA MB : matrix T, {MA = MB} + {MA ≠ MB}. Proof. intros * Hde *. specialize mat_opt_eq_dec as H1. rewrite Hde in H1. apply H1. Qed. *) Theorem mat_add_nrows : ∀ MA MB : matrix T, mat_nrows (MA + MB) = min (mat_nrows MA) (mat_nrows MB). Proof. intros. unfold mZ, "+"%M, mat_nrows. destruct MA as (lla). destruct MB as (llb); cbn. apply map2_length. Qed. Theorem mat_add_ncols : ∀ MA MB : matrix T, mat_ncols (MA + MB) = min (mat_ncols MA) (mat_ncols MB). Proof. intros. unfold mZ, "+"%M, mat_ncols. destruct MA as (lla). destruct MB as (llb); cbn. destruct lla as [| la]; [ easy | cbn ]. destruct llb as [| lb]; cbn; [ symmetry; apply Nat.min_r; flia | ]. apply map2_length. Qed. Theorem mat_el_add : ∀ (MA MB : matrix T) i j, is_correct_matrix MA = true → is_correct_matrix MB = true → 1 ≤ i ≤ mat_nrows MA → 1 ≤ i ≤ mat_nrows MB → 1 ≤ j ≤ mat_ncols MA → 1 ≤ j ≤ mat_ncols MB → mat_el (MA + MB) i j = (mat_el MA i j + mat_el MB i j)%L. Proof. intros * Ha Hb Hia Hib Hja Hjb. unfold "+"%M; cbn. rewrite map2_nth with (a := []) (b := []); cycle 1. { rewrite fold_mat_nrows; flia Hia. } { rewrite fold_mat_nrows; flia Hib. } rewrite map2_nth with (a := 0%L) (b := 0%L); cycle 1. { apply is_scm_mat_iff in Ha. destruct Ha as (Hcra & Hca). rewrite Hca; [ flia Hja | ]. apply nth_In. rewrite fold_mat_nrows; flia Hia. } { apply is_scm_mat_iff in Hb. destruct Hb as (Hcrb & Hcb). rewrite Hcb; [ flia Hjb | ]. apply nth_In. rewrite fold_mat_nrows; flia Hib. } easy. Qed. Theorem List_repeat_as_map : ∀ A (a : A) n, repeat a n = map (λ _, a) (seq 0 n). Proof. intros. induction n; [ easy | cbn ]. f_equal. now rewrite <- seq_shift, map_map. Qed. Theorem mat_vect_mul_0_r : ∀ m n (M : matrix T), m = mat_nrows M → n = mat_ncols M → (M • vect_zero n = vect_zero m)%V. Proof. intros * Hr Hc. specialize (proj2 rngl_has_opp_or_subt_iff) as Hos. specialize (Hos (or_introl Hop)). move Hos before Hop. subst m n. unfold "•"%V, vect_zero; cbn; f_equal. unfold vect_dot_mul; cbn. rewrite (List_repeat_as_map _ (mat_nrows _)). destruct M as (lla); cbn. rewrite (List_map_nth_seq lla) with (d := []) at 1. rewrite map_map. apply map_ext_in. intros i Hi. apply all_0_rngl_summation_list_0. intros j Hj. unfold mat_ncols in Hj; cbn in Hj. apply in_map2_iff in Hj. destruct Hj as (k & Hkm & a & b & Hk). subst j. rewrite List_nth_repeat; cbn. rewrite repeat_length in Hkm. apply Nat.min_glb_lt_iff in Hkm. destruct (lt_dec k (length (hd [] lla))) as [H| H]; [ | flia Hkm H ]. now apply rngl_mul_0_r. Qed. Notation "A ⁺" := (mat_transp A) (at level 1, format "A ⁺") : M_scope. Theorem mat_subm_transp : ∀ i j (M : matrix T), is_square_matrix M = true → 1 ≤ i ≤ mat_ncols M → 1 ≤ j ≤ mat_nrows M → ((subm j i M)⁺ = subm i j M⁺)%M. Proof. intros * Hsm Hi Hj. specialize (squ_mat_ncols _ Hsm) as Hcr. destruct (Nat.eq_dec (mat_ncols M) 1) as [Hc1| Hc1]. { rewrite Hc1 in Hi. rewrite <- Hcr, Hc1 in Hj. replace i with 1 by flia Hi. replace j with 1 by flia Hj. clear i j Hi Hj. unfold subm, mat_transp. rewrite Nat.sub_diag. cbn - [ butn ]. f_equal. rewrite map_length. rewrite butn_length. rewrite fold_mat_nrows, <- Hcr, Hc1. cbn - [ butn ]. destruct M as (ll); cbn. destruct ll as [| l]; [ easy | ]. cbn in Hc1. destruct ll as [| l']; [ easy | ]. cbn. destruct l as [| a]; [ easy | ]. destruct l; [ | easy ]. cbn in Hcr; flia Hcr. } assert (Hcm : is_correct_matrix M = true) by now apply squ_mat_is_corr. assert (Hcmt : is_correct_matrix M⁺ = true) by now apply mat_transp_is_corr. assert (Hit : 1 ≤ i ≤ mat_nrows M⁺) by now rewrite mat_transp_nrows. assert (Hjt : 1 ≤ j ≤ mat_ncols M⁺). { rewrite mat_transp_ncols. rewrite if_eqb_eq_dec. destruct (Nat.eq_dec (mat_ncols M) 0) as [H| H]; [ | easy ]. flia H Hi. } apply matrix_eq; cycle 1. { apply mat_transp_is_corr, subm_is_corr_mat; try easy. } { apply subm_is_corr_mat; [ | easy | easy | easy ]. rewrite mat_transp_ncols. rewrite if_eqb_eq_dec. rewrite Hcr in Hc1. now destruct (Nat.eq_dec (mat_ncols M) 0). } { rewrite mat_transp_nrows. rewrite mat_nrows_subm. rewrite mat_ncols_subm; [ | easy | easy | easy ]. generalize Hc1; intros H. rewrite Hcr in H. apply Nat.eqb_neq in H; rewrite H; clear H. rewrite mat_transp_nrows; cbn. generalize Hi; intros (_, H). now apply Nat.leb_le in H; rewrite H. } { rewrite mat_transp_ncols. rewrite mat_ncols_subm; [ | easy | easy | easy ]. generalize Hc1; intros H. rewrite Hcr in H. apply Nat.eqb_neq in H; rewrite H; clear H. rewrite if_eqb_eq_dec. destruct (Nat.eq_dec (mat_ncols M - 1) 0) as [H| H]; [ flia Hi H Hc1 | ]. clear H. rewrite mat_ncols_subm; [ | easy | easy | easy ]. rewrite mat_transp_nrows. generalize Hc1; intros H. apply Nat.eqb_neq in H; rewrite H; clear H. rewrite mat_transp_ncols. rewrite if_eqb_eq_dec. destruct (Nat.eq_dec (mat_ncols M) 0) as [H| H]; [ flia Hi H Hc1 | ]. clear H. rewrite mat_nrows_subm. generalize Hj; intros (_, H). now apply Nat.leb_le in H; rewrite H. } intros u v Hu Hv. rewrite mat_transp_el; [ | now apply subm_is_corr_mat | flia Hu | flia Hv ]. unfold mat_transp; cbn. rewrite (List_map_nth' []). 2: { rewrite butn_length. rewrite fold_mat_nrows. rewrite mat_ncols_subm in Hv; [ | easy | easy | easy ]. rewrite mat_transp_nrows in Hv. rewrite mat_transp_ncols in Hv. enough (H : v < mat_nrows M). { destruct v; [ easy | ]. destruct (mat_nrows M); [ easy | ]. rewrite Nat_sub_succ_1. apply Nat.succ_lt_mono in H. unfold Nat.b2n. rewrite if_ltb_lt_dec. destruct (lt_dec (j - 1) (S n)); flia H. } generalize Hc1; intros H. apply Nat.eqb_neq in H; rewrite H in Hv; clear H. rewrite if_eqb_eq_dec in Hv. destruct (Nat.eq_dec (mat_ncols M) 0) as [H| H]; [ flia Hi H | ]. flia Hv. } rewrite (List_map_nth' []). 2: { rewrite butn_length. rewrite List_map_seq_length. rewrite mat_transp_nrows in Hu. rewrite mat_ncols_subm in Hu; [ | easy | easy | easy ]. enough (H : u < mat_ncols M). { destruct u; [ easy | ]. destruct (mat_ncols M); [ easy | ]. rewrite Nat_sub_succ_1. apply Nat.succ_lt_mono in H. unfold Nat.b2n. rewrite if_ltb_lt_dec. destruct (lt_dec (i - 1) (S n)); flia H. } generalize Hc1; intros H. rewrite Hcr in H. apply Nat.eqb_neq in H; rewrite H in Hu; clear H. flia Hu. } do 4 rewrite nth_butn. rewrite mat_transp_nrows in Hu. rewrite mat_ncols_subm in Hu; [ | easy | easy | easy ]. rewrite mat_ncols_subm in Hv; [ | easy | easy | easy ]. rewrite mat_transp_nrows in Hv. rewrite mat_transp_ncols in Hv. assert (H : (mat_nrows M =? 1) = false) by (apply Nat.eqb_neq; congruence). rewrite H in Hu; clear H. assert (H : (mat_ncols M =? 1) = false) by now apply Nat.eqb_neq. rewrite H in Hv; clear H. assert (H : (mat_ncols M =? 0) = false) by (apply Nat.eqb_neq; flia Hi). rewrite H in Hv; clear H. rewrite (List_map_nth' 0). 2: { rewrite seq_length. unfold Nat.b2n; rewrite if_leb_le_dec. destruct (le_dec (i - 1) (u - 1)); flia Hu. } rewrite (List_map_nth' 0). 2: { rewrite seq_length. unfold Nat.b2n; rewrite if_leb_le_dec. destruct (le_dec (j - 1) (v - 1)); flia Hv. } rewrite seq_nth. 2: { unfold Nat.b2n; rewrite if_leb_le_dec. destruct (le_dec (j - 1) (v - 1)); flia Hv. } rewrite seq_nth. 2: { unfold Nat.b2n; rewrite if_leb_le_dec. destruct (le_dec (i - 1) (u - 1)); flia Hu. } unfold mat_el. rewrite Nat.add_assoc, (Nat.add_comm 1 (u - 1)). rewrite Nat.sub_add; [ | easy ]. rewrite Nat.add_sub_swap; [ | easy ]. f_equal. rewrite Nat.add_assoc, (Nat.add_comm 1 (v - 1)). rewrite Nat.sub_add; [ | easy ]. rewrite Nat.add_sub_swap; [ | easy ]. easy. Qed. Theorem mat_transp_is_square : ∀ M, is_square_matrix M = true → is_square_matrix M⁺ = true. Proof. intros * Hsm. specialize (squ_mat_ncols _ Hsm) as Hc. apply is_scm_mat_iff in Hsm. apply is_scm_mat_iff. destruct Hsm as (Hcr & Hcl). cbn; rewrite List_map_seq_length. split. { intros Hct. destruct (Nat.eq_dec (mat_ncols M) 0) as [Hcz| Hcz]; [ easy | ]. rewrite mat_transp_ncols in Hct. apply Nat.eqb_neq in Hcz; rewrite Hcz in Hct. congruence. } { intros l Hl. apply in_map_iff in Hl. destruct Hl as (i & Hi & Hic). now rewrite <- Hi, map_length, seq_length. } Qed. Theorem mat_transp_involutive : ∀ M, is_correct_matrix M = true → (M⁺⁺)%M = M. Proof. intros * Hcm. destruct (Nat.eq_dec (mat_ncols M) 0) as [Hcz| Hcz]. { destruct M as (ll); cbn. unfold mat_ncols in Hcz; cbn in Hcz. apply length_zero_iff_nil in Hcz. destruct ll as [| l]; [ easy | ]. cbn in Hcz; subst l; cbn. unfold mat_transp, mat_ncols; cbn; f_equal. apply is_scm_mat_iff in Hcm. unfold mat_ncols in Hcm; cbn in Hcm. destruct Hcm as (Hcr, _). now specialize (Hcr eq_refl). } destruct M as (ll); cbn. unfold mat_transp, mat_ncols; cbn; f_equal. rewrite (List_map_nth_seq ll []) at 2. rewrite List_map_seq_length. rewrite (List_map_hd 0). 2: { rewrite seq_length. unfold mat_ncols in Hcz. cbn in Hcz. now apply Nat.neq_0_lt_0. } rewrite List_map_seq_length. rewrite <- seq_shift, map_map. apply map_ext_in. intros i Hi; apply in_seq in Hi. destruct Hi as (_, Hi); cbn in Hi. erewrite map_ext_in. 2: { intros j Hj; apply in_seq in Hj. cbn in Hj. rewrite Nat_sub_succ_1. rewrite (List_map_nth' 0); [ | rewrite seq_length; flia Hj ]. rewrite (List_map_nth' 0); [ | now rewrite List_map_seq_length ]. rewrite seq_shift. rewrite seq_nth; [ | flia Hj ]. rewrite seq_nth; [ | easy ]. now do 2 rewrite Nat.add_comm, Nat.add_sub. } destruct ll as [| l]; [ easy | ]. unfold mat_ncols in Hcz; cbn in Hcz. cbn - [ nth ]. rewrite (List_map_nth_seq (nth i (l :: ll) []) 0%L) at 1. apply is_scm_mat_iff in Hcm. unfold mat_ncols in Hcm; cbn - [ In ] in Hcm. destruct Hcm as (_, Hcl). rewrite <- seq_shift, map_map. erewrite map_ext_in. 2: { now intros; rewrite Nat_sub_succ_1. } symmetry. rewrite Hcl; [ easy | ]. now apply nth_In. Qed. End a. Module matrix_Notations. Declare Scope M_scope. Delimit Scope M_scope with M. Arguments Build_square_matrix n%nat [T]%type sm_mat%M. Arguments is_correct_matrix {T}%type M%M. Arguments is_square_matrix {T}%type M%M. Arguments mat_add_0_l {T}%type {ro rp} {m n}%nat M%M. Arguments mat_add_0_r {T}%type {ro rp} {m n}%nat M%M. Arguments mat_add_add_swap {T}%type {ro rp} (MA MB MC)%M. Arguments mat_add_assoc {T}%type {ro rp} (MA MB MC)%M. Arguments mat_add_comm {T}%type {ro rp} (MA MB)%M. Arguments mat_add_opp_r {T}%type {ro rp} Hop M%M. Arguments mat_add_sub {T}%type {ro rp} Hop (MA MB)%M. Arguments mat_add {T}%type {ro} (MA MB)%M. Arguments mat_el {T}%type {ro} M%M (i j)%nat. Arguments mat_list_list {T}%type m%M. Arguments mat_mul_1_l {T}%type {ro rp} Hop {n}%nat M%M. Arguments mat_mul_1_r {T}%type {ro rp} Hop {n}%nat M%M. Arguments mat_mul_add_distr_l {T}%type {ro rp} (MA MB MC)%M. Arguments mat_mul_assoc {T}%type {ro rp} Hop (MA MB MC)%M. Arguments mat_mul_el {T}%type {ro} (MA MB)%M (i k)%nat. Arguments mat_mul_mul_scal_l {T}%type {ro rp} Hop Hic a%L (MA MB)%M. Arguments mat_mul_scal_1_l {T}%type {ro rp} M%M. Arguments mat_mul_scal_l_add_distr_l {T}%type {ro rp} a%L (MA MB)%M. Arguments mat_mul_scal_l_add_distr_r {T}%type {ro rp} (a b)%L M%M. Arguments mat_mul_scal_l_mul_assoc {T}%type {ro rp} (a b)%L M%M. Arguments mat_mul_scal_l_mul {T}%type {ro rp} Hop a%L (MA MB)%M. Arguments mat_mul_scal_l {T ro} s%L M%M. Arguments mat_mul_scal_vect_assoc {T}%type {ro rp} Hop a%L MA%M V%V. Arguments mat_mul_scal_vect_comm {T}%type {ro rp} Hop Hic a%L MA%M V%V. Arguments mat_mul {T}%type {ro} (MA MB)%M. Arguments mat_mul_vect_r {T ro} M%M V%V. Arguments mat_ncols {T}%type M%M. Arguments mat_nrows {T}%type M%M. Arguments mat_opp {T ro} M%M. Arguments mat_repl_vect_is_square {T}%type {ro} [k]%nat M%M V%V. Arguments mat_repl_vect_ncols {T ro} [k]%nat M%M V%V. Arguments matrix_eq {T ro} (MA MB)%M. Arguments mat_subm_transp {T ro} [i j]%nat. Arguments mat_sub {T ro} MA%M MB%M. Arguments mat_transp_is_square {T ro} M%M. Arguments mat_transp_mul {T ro rp} _ (MA MB)%M. Arguments mat_transp_nrows {T}%type {ro} M%M. Arguments mat_transp {T ro} M%M. Arguments mat_vect_mul_0_r {T}%type {ro rp} Hop [m n]%nat M%M. Arguments mat_vect_mul_1_l {T}%type {ro rp} Hop {n}%nat V%V. Arguments mat_vect_mul_assoc {T}%type {ro rp} Hop (A B)%M V%V. Arguments mI_any_seq_start {T ro} (sta len)%nat. Arguments mI_is_correct_matrix {T}%type {ro} n%nat. Arguments minus_one_pow {T ro}. Arguments mI {T ro} n%nat. Arguments mZ {T ro} (m n)%nat. Arguments squ_mat_ncols {T}%type M%M. Arguments subm {T} i%nat j%nat M%M. Arguments δ {T}%type {ro} (i j)%nat. Notation "A + B" := (mat_add A B) : M_scope. Notation "A - B" := (mat_sub A B) : M_scope. Notation "A * B" := (mat_mul A B) : M_scope. Notation "μ × A" := (mat_mul_scal_l μ A) (at level 40) : M_scope. Notation "- A" := (mat_opp A) : M_scope. Notation "A ⁺" := (mat_transp A) (at level 1, format "A ⁺") : M_scope. Notation "A • V" := (mat_mul_vect_r A V) (at level 40) : M_scope. Notation "A • V" := (mat_mul_vect_r A V) (at level 40) : V_scope. End matrix_Notations.
program test_ode !! Program to test the ode module. !! The [Lorenz chaotic system](https://en.wikipedia.org/wiki/Lorenz_system) is solved: !! \[ !! \frac{dx}{dt}= a\left(y-x\right)\\ !! \frac{dy}{dt}= x\left(b-z\right) - y \\ !! \frac{dz}{dt}= xy - cz !! \] !! The system is integrated for \(t\in[0,10]\) with \(a=\), \(b=\) and \(c=\). !! For initial conditions \(\left(x(0),y(0),z(0)\right) = \left(1,1,1\right)\), the solution is: !! ![Image of the trayectory](../../lorenz.png) use ode implicit none integer, parameter :: N = 1000; real :: Tf, dT real :: t(0:N), y(0:N,3) integer :: i, u Tf = 10 dT = Tf/N do i =0, N t(i) = i*dT end do y = forward_euler(lorenz, t, [ 1.,1.,1.]) open(file='datos.dat',newunit=u) do i = 0, N write(u,*) t(i), y(i,1), y(i,2), y(i,3) end do close(u) contains function lorenz(U,t) result(dU) !! function for defining derivative in the !! [Lorenz system](https://en.wikipedia.org/wiki/Lorenz_system) !! written as: !! \[ !! \frac{d\mathbf{U}}{dt}=\mathbf{F}\left(\mathbf{U},t\right) !! \] !! where: !! \[ !! \mathbf{U}\left(t\right) = !! \begin{pmatrix} !! x\left(t\right)\\ !! y\left(t\right)\\ !! z\left(t\right) !! \end{pmatrix} !! \] !! and !! \[ !! \mathbf{F}\left(\mathbf{U},t\right)= !! \begin{pmatrix} !! a \left( U_2 - U_1 \right) \\ !! U_1 \left( b - U_3 \right) - U_2 \\ !! U_1 U_2 - cU_3 !! \end{pmatrix} !! \] real, intent(in) :: U(:) real, intent(in) :: t real :: dU(size(U)) real, parameter :: a = 10. real, parameter :: b = 28. real, parameter :: c = 8./3. dU(1) = a*(U(2)-U(1)) dU(2) = U(1)*(b-U(3)) - U(2) dU(3) =U(1)*U(2) - c*U(3) end function end program
open import Agda.Builtin.Nat f : Nat → Nat f 0 = zero f 0 = 0 -- All -- But Only f (suc n) = n -- These f 0 = 0 -- Lines -- These Two -- Used to be highlighted -- Should be! g : Nat → Nat g 0 = zero g 0 -- The highlihting should still = 0 -- span multiple lines if the clause does g (suc n) = n g 0 -- Even -- With -- A Lot = 0 -- Of Empty Lines in between
State Before: l m r : List Char f : Char → Bool ⊢ Substring.any { str := { data := l ++ m ++ r }, startPos := { byteIdx := utf8Len l }, stopPos := { byteIdx := utf8Len l + utf8Len m } } f = List.any m f State After: no goals Tactic: simp [-List.append_assoc, Substring.any, anyAux_of_valid]
module Example where data Nat : Set where zero : Nat suc : Nat -> Nat postulate case-Nat : (P : Nat -> Set) -> P zero -> ((n:Nat) -> P (suc n)) -> (n : Nat) -> P n -- test : Nat -> Nat test = case-Nat _ zero (\n -> n) {- data Size : Set where empty : Size nonempty : Size whatever : Size data Nat : Set where zero : Nat suc : Nat -> Nat data List (A:Set) : Set where nil : List A (::) : A -> List A -> List A data Monad (M:Set -> Set) : Set1 where monad : Monad M postulate build : {M:Set -> Set} -> Monad M -> {C:Size -> Set} -> (A:Set) -> (A -> C nonempty) -> ((n:Size) -> List (C n) -> M (List A)) -> List A -> M (C whatever) test : (A:Set) -> Nat test A = build monad A (\x -> x) (\n xs -> xs) nil -}
module problem_tagging_module use amrex_fort_module, only : rt => amrex_real implicit none public contains ! This is a template routine for users to set their own tags based on the state. ! It will be overwritten by having a copy of this file in the user's problem setup. subroutine set_problem_tags(lo, hi, tag, tagl1, tagl2, tagh1, tagh2, & state, state_l1, state_l2, state_h1, state_h2,& set, clear,& dx, problo, time, level) & bind(C, name="set_problem_tags") use meth_params_module, only: NVAR use amrex_fort_module, only : rt => amrex_real implicit none integer, intent(in ) :: lo(2), hi(2) integer, intent(in ) :: state_l1, state_l2, & state_h1, state_h2 integer, intent(in ) :: tagl1, tagl2, tagh1, tagh2 real(rt), intent(in ) :: state(state_l1:state_h1, & state_l2:state_h2, NVAR) integer, intent(inout) :: tag(tagl1:tagh1, tagl2:tagh2) real(rt), intent(in ) :: problo(2), dx(2), time integer, intent(in ) :: level, set, clear end subroutine set_problem_tags end module problem_tagging_module
//================================================================================================== /*! @file @copyright 2016 NumScale SAS Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ //================================================================================================== #ifndef BOOST_SIMD_FUNCTION_IS_NEZ_HPP_INCLUDED #define BOOST_SIMD_FUNCTION_IS_NEZ_HPP_INCLUDED #if defined(DOXYGEN_ONLY) namespace boost { namespace simd { /*! @ingroup group-predicates This function object returns @ref True if x is not equal to @ref Zero else returns @ref False. @par Header <boost/simd/function/is_nez.hpp> @par Note Using `is_nez(x)` is similar to: `x != 0` @par Example: @snippet is_nez.cpp is_nez @par Possible output: @snippet is_nez.txt is_nez **/ as_logical_t<Value> is_nez(Value const& x); } } #endif #include <boost/simd/function/scalar/is_nez.hpp> #include <boost/simd/function/simd/is_nez.hpp> #endif
From Equations Require Import Equations. Require Import Equations.Prop.Subterm. Require Import Psatz. Require Import Coq.Strings.String. Require Import Coq.Lists.List. Require Export SystemFR.TOpenTClose. Require Export SystemFR.OpenTOpen. Require Export SystemFR.StrictPositivity. Require Export SystemFR.NoTypeFVarLemmas. Require Export SystemFR.ReducibilityUnused. Opaque makeFresh. Opaque PeanoNat.Nat.eq_dec. Opaque reducible_values. Opaque strictly_positive. Definition non_empty ρ A := exists v, [ ρ ⊨ v : A ]v. Lemma instantiate_non_empty: forall ρ A, non_empty ρ A -> exists a, [ ρ ⊨ a : A ]v. Proof. unfold non_empty; steps; eauto. Qed. Ltac instantiate_non_empty := match goal with | H: non_empty ?ρ ?A |- _ => poseNew (Mark (ρ,A) "instantiate_non_empty"); pose proof (instantiate_non_empty _ _ H) end. Lemma non_empty_extend: forall ρ A x RC, non_empty ρ A -> reducibility_candidate RC -> valid_interpretation ρ -> ~(x ∈ pfv A type_var) -> non_empty ((x, RC) :: ρ) A. Proof. unfold non_empty; repeat step || exists v || apply reducible_unused2. Qed. Lemma strictly_positive_open_aux: forall n T vars rep k, type_nodes T < n -> is_erased_type T -> is_erased_term rep -> strictly_positive T vars -> strictly_positive (open k T rep) vars. Proof. induction n; destruct T; repeat step || simp_spos || apply no_type_fvar_open || apply IHn ; try lia; try solve [ left; repeat step || apply no_type_fvar_open ]; try solve [ right; eexists; eauto; repeat step || apply no_type_fvar_open ]. right. exists X; repeat step || fv_open || list_utils || rewrite is_erased_term_tfv in * by steps. rewrite <- open_topen; repeat step || apply IHn || autorewrite with bsize in * || apply is_erased_type_topen; eauto with twf wf lia. Qed. Lemma strictly_positive_open: forall T vars rep k, is_erased_type T -> is_erased_term rep -> strictly_positive T vars -> strictly_positive (open k T rep) vars. Proof. eauto using strictly_positive_open_aux. Qed. Lemma push_all_cons: forall X (RC: tree -> Prop) ρ (P: tree -> Prop), (X, fun v => forall a, P a -> RC v) :: push_all P ρ = push_all P ((X, fun a => RC) :: ρ). Proof. steps. Qed. Lemma push_is_candidate: forall (ρ : interpretation) (A a : tree) (RC : tree -> Prop), reducibility_candidate RC -> [ ρ ⊨ a : A ]v -> reducibility_candidate (fun v : tree => [ ρ ⊨ a : A ]v -> RC v). Proof. repeat step || unfold non_empty in * || unfold reducibility_candidate in * || instantiate_any; eauto with fv wf. Qed. Lemma push_all_is_candidate: forall (ρ : interpretation) (A : tree) (RC : tree -> Prop), reducibility_candidate RC -> non_empty ρ A -> reducibility_candidate (fun v : tree => forall a, [ ρ ⊨ a : A ]v -> RC v). Proof. repeat step || unfold non_empty in * || unfold reducibility_candidate in * || instantiate_any; eauto with fv wf. Qed. Ltac find_exists2 := match goal with | H1: [ ?ρ ⊨ ?a : ?T1 ]v, H2: [ ?ρ ⊨ ?v : open 0 ?T2 ?a ]v |- _ => exists a end. Lemma no_type_fvar_strictly_positive: forall T vars, is_erased_type T -> no_type_fvar T vars -> strictly_positive T vars. Proof. induction T; repeat step || simp_spos || destruct_tag || unfold no_type_fvar in * || apply_any || left; try solve [ eapply_any; eauto; repeat step || list_utils ]. Qed. Ltac t_red_is_val := eapply red_is_val; eauto; repeat step || apply valid_interpretation_append || eapply valid_interpretation_one || eauto with b_valid_interp; steps; eauto with apply_any. #[export] Hint Extern 50 => solve [ t_red_is_val ]: b_red_is_val. Lemma strictly_positive_rename_aux: forall n T T' vars vars' rel, type_nodes T < n -> strictly_positive T vars -> equal_with_relation type_var rel T T' -> similar_sets rel vars vars' -> strictly_positive T' vars'. Proof. induction n; try solve [ intros; lia ]; destruct T; inversion 3; repeat match goal with | _ => step || simp_spos || destruct_tag | H1: equal_with_relation _ ?rel ?T ?T', H2: strictly_positive ?T ?vars |- strictly_positive ?T' ?vars' => apply IHn with T vars rel end; eauto using no_type_fvar_rename; try lia. right. exists (makeFresh ((X :: nil) :: pfv Ts' type_var :: nil)); repeat step; try finisher. match goal with | H1: equal_with_relation _ ?rel _ _, H2: strictly_positive ?T (?X :: nil) |- strictly_positive (topen 0 ?T' (fvar ?M type_var)) ?vars' => apply IHn with T (X :: nil) ((X,M) :: rel) end; repeat unfold similar_sets || step || autorewrite with bsize in * || apply equal_with_relation_topen; try lia; try finisher. Qed. Lemma strictly_positive_rename: forall T T' vars vars' rel, strictly_positive T vars -> equal_with_relation type_var rel T T' -> similar_sets rel vars vars' -> strictly_positive T' vars'. Proof. eauto using strictly_positive_rename_aux. Qed. Lemma no_type_fvar_swap: forall T vars i j, no_type_fvar T vars -> no_type_fvar (swap_type_holes T i j) vars. Proof. unfold no_type_fvar; repeat step || rewrite pfv_swap_type_holes in *; eauto. Qed. Lemma strictly_positive_swap_aux: forall n T vars i j, type_nodes T < n -> strictly_positive T vars -> strictly_positive (swap_type_holes T i j) vars. Proof. induction n; destruct T; repeat step || simp_spos || apply_any; try lia; eauto using no_type_fvar_swap. right; exists X; repeat step || rewrite pfv_swap_type_holes in *. rewrite topen_swap2; steps. apply IHn; repeat step || autorewrite with bsize in *; try lia. Qed. Lemma strictly_positive_swap: forall T vars i j, strictly_positive T vars -> strictly_positive (swap_type_holes T i j) vars. Proof. eauto using strictly_positive_swap_aux. Qed. Lemma strictly_positive_topen_aux: forall n T vars k X, type_nodes T < n -> strictly_positive T vars -> ~(X ∈ vars) -> strictly_positive (topen k T (fvar X type_var)) vars. Proof. induction n; destruct T; repeat step || simp_spos || apply IHn; eauto using no_type_fvar_in_topen; try lia. right; exists (makeFresh ((X0 :: nil) :: (X :: nil) :: pfv T3 type_var :: pfv (topen (S k) T3 (fvar X type_var)) type_var :: nil)); steps; try finisher. rewrite open_swap; repeat step. apply IHn; repeat step || autorewrite with bsize in *; try lia; try finisher. rewrite topen_swap; steps. apply strictly_positive_swap. match goal with | H2: strictly_positive (topen 0 ?T (fvar ?X type_var)) (?X :: nil) |- strictly_positive (topen 0 ?T (fvar ?M type_var)) (?M :: nil) => apply strictly_positive_rename with (topen 0 T (fvar X type_var)) (X :: nil) ((X,M) :: idrel (pfv T type_var)) end; unfold similar_sets; repeat step || apply equal_with_relation_topen; try finisher; eauto using equal_with_relation_refl2; eauto using equal_with_idrel. Qed. Lemma support_push_one: forall ρ a, support (push_one a ρ) = support ρ. Proof. unfold push_one; repeat step || rewrite support_map_values. Qed. Lemma support_push_all: forall ρ P, support (push_all P ρ) = support ρ. Proof. unfold push_all; repeat step || rewrite support_map_values. Qed. Lemma strictly_positive_topen: forall T vars k X, strictly_positive T vars -> ~(X ∈ vars) -> strictly_positive (topen k T (fvar X type_var)) vars. Proof. eauto using strictly_positive_topen_aux. Qed. Definition pre_interpretation := list (nat * (tree -> tree -> Prop)). Fixpoint forall_implies (P: tree -> Prop) (pre_ρ: pre_interpretation) (ρ: interpretation) := match pre_ρ, ρ with | nil, nil => True | (X,pre_rc) :: pre_ρ', (Y,rc) :: ρ' => X = Y /\ forall_implies P pre_ρ' ρ' /\ forall (v: tree), (forall a, P a -> pre_rc a v) -> rc v | _, _ => False end. Lemma forall_implies_apply: forall P pre_ρ ρ X pre_rc rc v, forall_implies P pre_ρ ρ -> lookup PeanoNat.Nat.eq_dec pre_ρ X = Some pre_rc -> lookup PeanoNat.Nat.eq_dec ρ X = Some rc -> (forall a, P a -> pre_rc a v) -> rc v. Proof. induction pre_ρ; destruct ρ; repeat step || eapply_any. Qed. Ltac t_forall_implies_apply := match goal with | H1: forall_implies ?P ?pre_ρ ?ρ, H2: lookup _ ?pre_ρ ?X = Some ?prc, H3: lookup _ ?ρ ?X = Some ?rc |- ?rc ?v => apply (forall_implies_apply _ _ _ _ _ _ _ H1 H2 H3) end. Lemma forall_implies_support: forall P pre_ρ ρ, forall_implies P pre_ρ ρ -> support pre_ρ = support ρ. Proof. induction pre_ρ; destruct ρ; repeat step || f_equal. Qed. Ltac t_forall_implies_support := match goal with | H: forall_implies ?P ?pre_ρ ?ρ |- _ => poseNew (Mark (pre_ρ,ρ) "forall_implies_suppoft"); pose proof (forall_implies_support _ _ _ H) end. Lemma forall_implies_equiv: forall P1 P2 pre_ρ ρ, forall_implies P1 pre_ρ ρ -> (forall x, P1 x <-> P2 x) -> forall_implies P2 pre_ρ ρ. Proof. induction pre_ρ; destruct ρ; steps; eauto with eapply_any. Qed. Ltac t_forall_implies_equiv := match goal with | H1: forall_implies ?P1 ?pre_ρ ?ρ |- forall_implies _ ?pre_ρ ?ρ => apply forall_implies_equiv with P1 end. Lemma strictly_positive_append_aux: forall n T vars1 vars2, type_nodes T < n -> strictly_positive T vars1 -> strictly_positive T vars2 -> strictly_positive T (vars1 ++ vars2). Proof. induction n; destruct T; repeat lia || step || destruct_tag || simp_spos || apply_any; eauto using no_type_fvar_append. Qed. Lemma strictly_positive_append: forall T vars1 vars2, strictly_positive T vars1 -> strictly_positive T vars2 -> strictly_positive T (vars1 ++ vars2). Proof. eauto using strictly_positive_append_aux. Qed. Lemma strictly_positive_cons: forall T X vars, strictly_positive T (X :: nil) -> strictly_positive T vars -> strictly_positive T (X :: vars). Proof. intros. change (X :: vars) with ((X :: nil) ++ vars); eauto using strictly_positive_append. Qed. Lemma strictly_positive_topen2: forall T k X vars, ~(X ∈ vars) -> strictly_positive T vars -> strictly_positive (topen k T (fvar X type_var)) (X :: nil) -> strictly_positive (topen k T (fvar X type_var)) (X :: vars). Proof. intros; apply strictly_positive_cons; repeat step || apply strictly_positive_topen. Qed. Lemma strictly_positive_rename_one: forall T X Y vars, strictly_positive (topen 0 T (fvar X type_var)) (X :: vars) -> ~(X ∈ pfv T type_var) -> ~(Y ∈ pfv T type_var) -> strictly_positive (topen 0 T (fvar Y type_var)) (Y :: vars). Proof. intros. apply strictly_positive_rename with (topen 0 T (fvar X type_var)) (X :: vars) ((X,Y) :: idrel (pfv T type_var)); repeat step || apply equal_with_relation_topen || unfold similar_sets || rewrite swap_idrel in * || t_idrel_lookup2; eauto using equal_with_idrel. Qed. Lemma strictly_positive_no_fv: forall T vars, is_erased_type T -> (forall X, X ∈ pfv T type_var -> False) -> strictly_positive T vars. Proof. intros. apply no_type_fvar_strictly_positive; repeat step || unfold no_type_fvar; eauto. Qed.
[STATEMENT] lemma frac_in_Rats_iff [simp]: fixes r::"'a::{floor_ceiling,field_char_0}" shows "frac r \<in> \<rat> \<longleftrightarrow> r \<in> \<rat>" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (frac r \<in> \<rat>) = (r \<in> \<rat>) [PROOF STEP] by (metis Rats_add Rats_diff Rats_of_int diff_add_cancel frac_def)
{-# OPTIONS --without-K --safe #-} module Categories.Category.Construction.Properties.Presheaves where open import Categories.Category.Construction.Properties.Presheaves.Cartesian using (module IsCartesian) public open import Categories.Category.Construction.Properties.Presheaves.CartesianClosed using (module IsCCC) public open import Categories.Category.Construction.Properties.Presheaves.Complete using (Presheaves-Complete; Presheaves-Cocomplete) public
import Graphics.Gloss import Graphics.Gloss.Raster.Field import Graphics.Gloss.Data.ViewPort import Data.Complex import Data.Colour.RGBSpace import Data.Colour.RGBSpace.HSV import qualified Graphics.Gloss.Data.Point.Arithmetic as PA mandelbrot :: Complex Float -> Complex Float -> Int -> (Complex Float, Int) mandelbrot z _ 0 = (z, 0) mandelbrot z c n | magnitude z > 2 = (z, n) | otherwise = mandelbrot (z * z + c) c (n - 1) rgbcolor :: Float -> Float -> Float -> Color rgbcolor r g b = makeColor r g b 1.0 smoothcolor :: Complex Float -> Int -> Int -> Color smoothcolor _ 0 _ = black smoothcolor z n max = (uncurryRGB rgbcolor) $ hsv deg 1 1 where deg = 360 * ((fromIntegral n) - 1.0 + (log (log (magnitude z))) / (log 2)) / (fromIntegral max) colorof :: Int -> Point -> Color colorof max (x,y) = let (z, n) = mandelbrot 0 (x :+ y) max in smoothcolor z n max getpicture :: ViewPort -> Float -> (Picture,Point) -> (Picture,Point) getpicture vp _ pd@(pic,pt) = let npt = invertViewPort vp (1,1) adjpt = (PA.- (1/300 PA.* t)).(300/scl PA.*) adjpic = (translate (-tx) (-ty)).(scale (300 /scl) (300/scl)) t@(tx,ty) = viewPortTranslate vp scl = 300 * (viewPortScale vp) max = (round $ 4 * (log scl)) in case (pt /= npt) of True -> (adjpic $ makePicture 600 600 5 5 ((colorof max).adjpt), npt) False -> pd main :: IO () main = simulate (InWindow "Mandelbrot" (600,600) (20,20)) black 1 (Circle 0, (0,0)) (\(p,_ ) -> p) getpicture
lemma continuous_on_prod_compactE: fixes fx::"'a::topological_space \<times> 'b::topological_space \<Rightarrow> 'c::metric_space" and e::real assumes cont_fx: "continuous_on (U \<times> C) fx" assumes "compact C" assumes [intro]: "x0 \<in> U" notes [continuous_intros] = continuous_on_compose2[OF cont_fx] assumes "e > 0" obtains X0 where "x0 \<in> X0" "open X0" "\<forall>x\<in>X0 \<inter> U. \<forall>t \<in> C. dist (fx (x, t)) (fx (x0, t)) \<le> e"
# Convert the output GeoTIFF to KMZ library(raster) InputFile = "../data/pixel-based/predictions/randomforest-median-threestep-walltowall.tif" OutputFile = "../output/global-lc-fraction-map.kmz" TIFFFile = brick(InputFile) TIFFFile = TIFFFile[[-1]] KML(TIFFFile, OutputFile, maxpixels = ncell(TIFFFile), blur=1, col=gray.colors(101, 0, 1), zlim=c(0, 100), overwrite=TRUE)
\chapter*{General Conclusion} \phantomsection \addcontentsline{toc}{chapter}{\numberline{}General Conclusion} \markboth{General Conclusion}{General Conclusion} \section*{Summary} ***. \section*{Ongoing and future work} By the end of this project, numerous problems still remain open. Several points deserve further investigations: \begin{itemize}[label = \scriptsize$\blacktriangleright$] \item ***. \item ***. \item ***. \item ***. \end{itemize}
module Statistics.Classification.ConfusionMatrix ( module ConfusionMatrix ) where import Statistics.Classification.ConfusionMatrix.Binary as ConfusionMatrix import Statistics.Classification.ConfusionMatrix.Multi as ConfusionMatrix
print("Hello World") #My Contribution
/* * gpcxx/examples/dynamical_system/program_options.hpp * Date: 2016-02-26 * Author: Karsten Ahnert ([email protected]) * Copyright: Karsten Ahnert * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or * copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef GPCXX_EXAMPLES_DYNAMICAL_SYSTEM_PROGRAM_OPTIONS_HPP_INCLUDED #define GPCXX_EXAMPLES_DYNAMICAL_SYSTEM_PROGRAM_OPTIONS_HPP_INCLUDED #include <boost/program_options.hpp> #include <string> #include <utility> namespace dynsys { inline auto get_options( void ) { namespace po = boost::program_options; po::options_description options( "Options" ); options.add_options() ( "normalize" , po::value< bool >() , "normalize the input data" ) ; return options; } inline auto get_positional_options( void ) { namespace po = boost::program_options; po::options_description hidden( "Positional arguments" ); hidden.add_options() ( "evolution" , po::value< std::string >() , "outfile for the evolution" ) ( "result" , po::value< std::string >() , "outfile for the result" ) ( "winner" , po::value< std::string >() , "outfile for the winner" ) ; po::positional_options_description positional_options; positional_options.add( "evolution", 1 ).add( "result", 1 ).add( "winner" , 1 ); return std::make_pair( positional_options , hidden ); } } // namespace dynsys #endif // GPCXX_EXAMPLES_DYNAMICAL_SYSTEM_PROGRAM_OPTIONS_HPP_INCLUDED
=begin # sample-gaussian-elimination01.rb require "algebra" M = MatrixAlgebra(Rational, 5, 4) a = M.matrix{|i, j| i + j} a.display #=> #[0, 1, 2, 3] #[1, 2, 3, 4] #[2, 3, 4, 5] #[3, 4, 5, 6] #[4, 5, 6, 7] a.kernel_basis.each do |v| puts "a * #{v} = #{a * v}" #=> a * [1, -2, 1, 0] = [0, 0, 0, 0, 0] #=> a * [2, -3, 0, 1] = [0, 0, 0, 0, 0] end ((<_|CONTENTS>)) =end
State Before: 𝕜 : Type u_3 E : Type u_1 M : Type u_2 H : Type u_4 E' : Type ?u.225289 M' : Type ?u.225292 H' : Type ?u.225295 inst✝¹⁰ : NontriviallyNormedField 𝕜 inst✝⁹ : NormedAddCommGroup E inst✝⁸ : NormedSpace 𝕜 E inst✝⁷ : TopologicalSpace H inst✝⁶ : TopologicalSpace M f f' : LocalHomeomorph M H I : ModelWithCorners 𝕜 E H inst✝⁵ : NormedAddCommGroup E' inst✝⁴ : NormedSpace 𝕜 E' inst✝³ : TopologicalSpace H' inst✝² : TopologicalSpace M' I' : ModelWithCorners 𝕜 E' H' x : M s t : Set M inst✝¹ : ChartedSpace H M inst✝ : ChartedSpace H' M' ⊢ ↑(LocalEquiv.symm (extChartAt I x)) ⁻¹' (s ∩ t) ∩ range ↑I = ↑(LocalEquiv.symm (extChartAt I x)) ⁻¹' s ∩ range ↑I ∩ ↑(LocalEquiv.symm (extChartAt I x)) ⁻¹' t State After: no goals Tactic: mfld_set_tac
\chapter{{Verb phrases}}\label{sec:6} This is the second linguistic chapter with a focus on the salient markers and characteristics of Ship English. This chapter on \isi{verb} phrases begins with the simplest realization of any \isi{verb} constituent as a single word and continues with the expansion of the \isi{verb phrase} as it incorporates \isi{tense}, modality and aspect. Subsequently, \sectref{sec:6.1}, verbs in Ship English, opens with a discussion of how the variety favors a [\isi{non-specific verb} + \isi{specifying nominal complement}] construction in which the syntactic \isi{verb} serves to introduce a \isi{nominal form} in the \isi{direct object position} which expresses the core event of the sentence.\footnote{Also know as a light verb construction.} This sections then presents data on phrasal verbs and negation markers. The second section, 6.2 on tense, discusses present and past \isi{tense variation} and features a discussion of the potential role of the Northern Subject Rule, \footnote{The Northern Subject Rule, described by \citet{deHaas2008} as a unique variation in verbal endings specific to Northern dialects of British English that involves variation in verbal endings according to type and position of the subject. She explains, “Finite verbs adjacent to a pronominal subject (excepting 2SG thou and 3SG, which always take -s) take a zero ending, whereas finite verbs adjacent to a nominal (Determiner Phrase or DP) subject or not adjacent to any subject take an -s ending” (\citealt{deHaas2008}: 111).} and the manifestation of Narrative Present in performative speech in addition to the presentation of potential linguistic constraints on salient zero-inflection and the use of \isi{infinitive} forms. The third section, 6.3 on the copula and auxiliary “be”, presents data on variation in the \isi{inflectional paradigm} and discusses how the \isi{verb} “be” is used and omitted in various contexts including those with \isi{aspectual} meaning. The last section, 6.4 on auxiliaries, presents data on inflectional variation and uses of auxiliary verbs such as “have” and “do” as they are used in interrogative, indicative, and conditional modalities with details on how they express \isi{aspectual meaning}. \section{{Verbs in Ship English}}\label{sec:6.1} \subsection{{The [non-specific verb + specifying nominal compliment] construction}}\label{sec:6.1.1} As discussed in chapter 5, the data indicate that Ship English favors heavy nominalization. This section shows how verbal constructions promote this perception by relying on [\isi{non-specific verb} + \isi{specifying nominal complement}] constructions, in which verbs retain their \isi{syntactic function}, but nominals carry more semantic load compared with prototypical “heavy” verb constructions. For example, “the first man they gave torment to” [HCA 1/9/16] rather than “the first man they tormented”, and “[they] Spyed a Sayle and gave him chase” [HCA 1/9/13] rather than “they spied a sail and chased him”. Furthermore, this usage is found in sea shanties and so speaks to the frequency and salience of the construction in cultural forms of expression, e.g., “Give ear unto the mariners” (\isi{shanty} in \citealt{Hugill1969}: 6). Other verbs such as “use” and “offer” are used with similar \isi{syntactic function} that favor the description of the event in \isi{nominal form} as the direct objects, e.g., “he used some threatenings” [HCA 1/99/22] rather than “he threatened”, and “any one that offered any hurt or violence to Clarke he would make him suffer” [HCA 1/9/51] rather than “any one that hurt…Clarke”. The use of nominals, most frequently in the position of the \isi{direct object}, to express events means that speakers can rely on semantically less-specific verbs. This consequently means that the original direct object is demoted to another nominal position, for example an indirect object, e.g., “to have satisfaction made him” [HCA 1/99/1], “Would not return him any answer” [HCA 1/52/133], and “to make him dishoner” [HCA 1/9/8]. The \isi{pronoun} “him” in all three examples above might be expressed as the \isi{direct object} of a verbal form which is semantically specific enough to actually denote the central event of the sentence on its own, e.g., “to satisfy him”, “to answer him” and “to dishonor him”. However, “him” is expressed as the syntactic indirect object in all three Ship English examples because the \isi{direct object position} is already occupied by the nominal forms specifying the central event of the sentence, i.e., “satisfaction”, “answer”, and “dishonor”. Similarly, in the example “the \isi{prisoner} was put commander of the small sloop” (meaning that he was given command) [HCA 1/99 New Providence 1722], the use of the semantically \isi{non-specific verb} “put” necessitates that the \isi{direct object position} be occupied by a \isi{nominal form} that specifies the actual central event of the sentence “command” which forces “the small sloop” (what is commanded) into the position of the object of the \isi{preposition} in an \isi{adverbial phrase}. In short, sailors’ preference for the [\isi{non-specific verb} + \isi{specifying nominal complement}] construction means that the sentences they used favor relatively non-specific verbs and make ample use of event nominalizations. The \isi{verb} “make” is the most commonly used \isi{verb} in [\isi{non-specific verb} + \isi{specifying nominal complement}] constructions in the \isi{corpus}. It often denotes that an event comes to pass or is caused to happen, and this event is subsequently expressed in \isi{nominal form} , e.g., “in order to make trade” [HCA 1/99/4], “he made a resistance with a cutlass” [HCA 1/99/9], “make information against them” [HCA 1/99/7], “Freebourne made answer” [HCA 1/9/6], and “Letts goe and make an end of the fellow” [HCA 1/9/51]. Here the events “trade”, “resist”, “inform”, and “answer” are expressed in \isi{nominal form} in the \isi{direct object} positions following the usage patterns discussed in the previous paragraph. Yet the \isi{verb} “make” is worthy of individual discussion as it not only permits a \isi{noun phrase} object, but also a \isi{prepositional phrase} indicating a direction or manner of movement, e.g., “she made away from him” [HCA 1/9/18], “the informant made to her” [HCA 1/52/124], and “this examinant made for Cape Charles” [HCA 1/9/13]. Indeed, this sense of movement may explain the \isi{idiomatic usage} in the \isi{corpus} that associates the \isi{verb} “make” with travel, transit and arrival, e.g., “we made the Island” [1045.f.3/1/16], “he made the best of his way” [HCA 1/98/254], “they made what saile they could after them” [HCA 1/53/12], “he designs to make his escape” [HCA 1/99/51], and “Make all the dispatch you can” [HCA 1/101/553]. These sample clauses with the \isi{verb} “make”, whether they are expressed with nominal or prepositional complements, all illustrate the preference for the [\isi{non-specific verb} + \isi{specifying nominal complement}] construction in Ship English and is a salient feature of the \isi{corpus}. \subsection{{Phrasal verbs}}\label{sec:6.1.2} Phrasal verbs in the \isi{corpus} show a tendency to be expressed as fixed expressions, in which the verb and the particle need to be adjacent. These expressions resist the insertion of an \isi{object noun} phrase or \isi{pronoun} between the main \isi{verb} and the \isi{satellite particle}. The majority of phrasal verbs occur without separation of the verbal particle(s) and \isi{satellite particle}(s), e.g., (with emphasis added) “by \textit{breaking downe} her misson mast" [ADM 106/288/40], “[he] was presently \textit{sent for up} by the said Taylor” [HCA 1/9/39], and “when they \textit{got up} the anchor” [HCA 1/99/6]. A few examples show that it was permissible to insert a direct \isi{object noun} phrase between a \isi{verb} and a \isi{satellite particle}, for example the separation of “fetch out” in the example, “he \textit{fetch’d} the captain’s charts \textit{out}” [HCA 1/99/7]. Indeed, when the \isi{direct object} of a \isi{transitive} \isi{phrasal verb} is a \isi{pronoun}, we would anticipate it to be expressed in a position separating the \isi{verb} and the \isi{satellite particle}, e.g., “they \textit{whipped} him \textit{up} again” [HCA 1/99/7]. Yet phrasal verbs in Ship English appear to resist even this type of separation. Instead, the \isi{direct object} is more commonly expressed after the complete \isi{phrasal verb}, regardless of whether it is a \isi{noun phrase} or a \isi{pronoun}, e.g., (with phrasal verbs italicized and direct objects in bold for emphasis) “\textit{call abroad} \textbf{him}” [E134/34Chas2/Mich36], “\textit{took away} out of his packett \textbf{his} \textbf{Sealed} \textbf{ring}” [HCA 1/9/18], and “they \textit{let go} \textbf{her} \textbf{anchor}” [HCA 1/52/2]. Thus, although phrasal verbs permitted separation of the \isi{verb} and the \isi{satellite particle}, it was common to keep both or all parts of the \isi{phrasal verb} together without separating them with either a nominal or pronominal \isi{direct object}. \subsection{{Negation}}\label{sec:6.1.3} Negation can be marked in a variety of ways in Ship English, the most common of which was the use of the negative particle “not” after a \isi{finite verb}.\footnote{The most common pre-verbal usage of the negating marker “not” occurred in phrases headed with “being”, e.g., “he did not Duty \textit{not being well}” [HCA 1/99/108] and “the \isi{merchant} ship \textit{not being gon} into York river” [CO 5/1411/702].} Modern day speakers of English are accustomed to the particle “not” used with “be” used as an auxiliary verb, and this type of modern-\isi{standard usage} was evident in the \isi{corpus} (all examples emphasized), e.g., “Our Ankor \textit{was not} no sounder” [T/70/1215], “the country and his colonies \textit{was not} under his command” [CO 5/1411/101], and “the Prisoner was not only never on Board” [HCA 1/99/156]. Standard \isi{modern usage} also requires “do-support” in the negation of verbs expressed in the \isi{present tense} \isi{indicative mood}, e.g., “he \textit{does not} / \textit{doesn’t} work”, and this type of \isi{standard usage} was also evident in the \isi{corpus}, e.g., “he \textit{did not hear} it” [HCA 1/99/5], “The English \textit{did not row}” [HCA 1/13/96], “he \textit{did nott thinks} itt convenientt” [ADM 52/2/3], and “Porter complained that they \textit{did not work}” [HCA 1/99/8]. The verb “do” is also used as an auxiliary with indicative verbs despite the fact that the conjugation of the auxiliary, particularly with \isi{third person singular} subjects, does not always align with modern-day \isi{standard usage}, e.g., “Capt Rigby \textit{doe not} nor shall \textit{carry off} this land any Persons” [HCA 1/9/7], “Captain Sharp \textit{don’t forget} to Speak for us” [HCA 1/99/30], “he \textit{don’t know} that the \isi{prisoner} had any money” [HCA 1/99/10], and “[he] \textit{do’s not know} what ship” [HCA 1/99/99].\footnote{The use of “doth” in negation is rare in the \isi{corpus} and mostly seems to derive from the speech acts of judicial representatives in court records and not the sailors themselves, e.g., “he doth not know of any corespond[ance]” [HCA 1/14/140], “Doth not know the ships name” [HCA 1/14/140], and “whose name he doth not remember” [HCA 1/14/203].} However, this type of negation using “do support” and the “not” marker for simple \isi{verb} phrases in the negated \isi{indicative mood} had a low frequency in the \isi{corpus} and may only reflect recent changes in the direction of Early Modern English. Much more salient was the use of the particle “not” immediately after the \isi{verb} and without any auxiliary marker. Examples of this type of negation appear in logbooks, e.g., “wee \textit{weighd nott}” [ADM 52/2/6], and “But [we] \textit{found not} A man in har [i.e., her]” [T/70/1215]; in journals, e.g., “I \textit{hope not} so” [445f.1/26], and “I \textit{got not} in till the next Day” [1045.f.3/1/22]; and in private correspondence, e.g., “they \textit{had not} those termes” [CO 5/1411/39], and “I \textit{doubt not}” [BL/74/816/m/11/36/1]. Yet, it was most common in witness testimony, e.g., “he \textit{intended not} to sell the said rope” [HCA 1/101/224], “She \textit{remembers not}” [HCA 1/9/51], “He \textit{cared not} what the master did” [HCA 1/9/139], “I sent for him aboard but hee \textit{came not}” [HCA 1/9/4], and “he \textit{had not} opportunity of getting away” [HCA 1/99/165]. This type of negation was even more pronounced with the \isi{verb} “know”, which showed up in negated statements repeatedly in the \isi{corpus} in both past and \isi{present tense}, e.g., “he \textit{knew not} the design of the others” [HCA 1/99/5], “he \textit{knew not} when he would return” [HCA 1/14/151], “he \textit{knew not} but that he might prosecute him” [HCA 1/52/46], “He \textit{knowes not} of any Nutmeggs or Cloves” [HCA 1/12/78], “whose names I \textit{know not}” [BL/74/816/m/11/36/3], “I \textit{know not} of any methods” [CO 5/1411/655], and “He \textit{knows not} nor ever heard” [HCA 1/9/51]. However, negation with the “not” marker was versatile and permitted syntactic variation; for instance, it occurs in a position separated from the \isi{verb} by a pronominal \isi{direct object} (emphasized in bold), e.g., “wee \textit{saw}\textbf{ }\textbf{him} \textit{not}” [HCA 1/12/2], “yet [we] \textit{made} \textbf{him} \textit{not} Bear for our company” [T/70/1216/13], “he \textit{has} \textbf{it} \textit{not} for himself” [HCA 1/99/51], and “They \textit{found} \textbf{it} \textit{not} safe to hazard” [ADM 51/4322/4]. Indeed, “not” was the most versatile and the most common \isi{negation marker} in the \isi{corpus}, and based on a sample of 204 items (see \figref{fig:key:6.1}), accounts for more than half of all negated \isi{verb} phrases. In sum, although the salient “not” \isi{negation marker} was used in a manner comparable to modern-day usage of the verb “be” and with “do-support”, it was more frequent in a variant \isi{post-verbal position} without any auxiliary marker. \footnote{Negation using “not” with auxiliaries of conditional modality also feature in the \isi{corpus}, but are discussed in \sectref{sec:6.4.3} Modal Auxiliaries.} \begin{figure} \footnotesize \begin{minipage}[c]{.28\textwidth}% \begin{tabular}{ll} \lsptoprule Marker & No.\\ \midrule Not & 104\\ Never&42\\ No&25\\ Nor& 17\\ Nothing&8\\ Neither&3\\ No one&3\\ Prefix <un> & 2\\ \midrule & 204\\ \lspbottomrule \end{tabular}\end{minipage}% \begin{minipage}[c]{.72\textwidth}% \begin{tikzpicture}\footnotesize % [ % pie chart, % slice type={Not}{lsDarkBlue}, % slice type={Never}{lsMidBlue}, % slice type={No}{lsMidDarkBlue}, % slice type={Nor}{lsLightBlue}, % slice type={Nothing}{lsDarkGreenTwo}, % slice type={Neither}{lsRichGreen}, % slice type={Noone}{lsLightGreen}, % slice type={un}{lsMidGreen}, % scale=4 % ] % \pie[text=pin,radius=2,color={lsMidBlue,lsLightGreen,lsMidGreen,lsLightBlue},/pgf/Minimum Angle=8,]{49/Adjective,32/Noun,18/Adverb,1/Infinitive (1\%)} \pie[text=pin,radius=3,sum=auto,color={lsDarkBlue,lsMidBlue,lsMidDarkBlue,lsLightBlue,lsDarkGreenTwo,lsRichGreen,lsLightGreen,lsMidGreen},pgf/Minimum Angle=8]{104/Not,42/Never,25/No,17/Nor,8/Nothing,3/Neither (3),3/No one (3),2/Prefix \textit{un-} (2)} % 21/Never, % 12/No, % 8/Nor, % 4/Nothing, % 2/Neither, % 1/Noone, % 1/un} % \legend[shift={(1.5cm,17mm)}]{{Not (104)}/Not, % {Never (42)}/Never, % {No (25)}/No, % {Nor (17) }/Nor, % {Nothing (8)}/Nothing, % {Neither (3)}/Neither, % {No one (3)}/Noone, % {Prefix \textit{un-} (2)}/un} \end{tikzpicture}\end{minipage} \caption[Distribution of negation markers used in a sample of 204 verb phrases]{\label{fig:key:6.1} Distribution of negation markers used in a sample of 204 verb phrases\\ \sourcebox{\tiny Sources: 1045.f.3/1, 445f.1, AC WO 16–16/8–16, ADM 51/4322, 3983, 3954, ADM 52/1, 2, BL/74/816/m/11/36, CO 5/1411, DDB6 8/4, HCA 1/9, HCA 1/11,12,13,14, HCA 1/52, HCA 1/98, 99, 101, Palmer (1986]. SP 42/6, T/70/1215.} } % \todo[inline]{fix legend} \end{figure} The second most common \isi{negation marker} in the sample was the word “never” which was used both to mark categorical denial over time (as in standard \isi{modern usage}) and to mark the negation of a simple \isi{verb} form with no \isi{aspectual meaning}. Given that the term “never” derives etymologically from the negative particle “ne” (meaning “no”) and the \isi{adverb} “ever”, the most transparent meaning of the negative marker is one associated with a \isi{durative aspect} and the most logical context is with a situation of zero-possibility with a cumulative quantification over time, i.e., something that has categorically not happened up to and including the present moment. This meaning is evident in the \isi{corpus} (all marked for emphasis), e.g., “he did not hear it Read, nor \textit{never} heard that it was read” [HCA 1/99/5], “he had \textit{never} been arrested of any ill action” [HCA 1/99/8], “was \textit{never} till now taken” [HCA 1/13/95], “was \textit{never} before seen by him” [HCA 1/13/92], and “\textit{Never} had any acquaintance or discourse with nor ever saw the said Prock or Richard [...] before” [HCA 1/52/133]. However, less than a quarter of the “never” negation markers in the sample, only 10 of the 42 items sampled, had the meaning “no(t) ever”, see \figref{fig:key:6.1}. The majority of examples of “never” were used with specific durations of time or to negate indicative \isi{past tense} situations. The marker “never” used to negate specific durations of time and that frequently occurs with adverbs such as “(un)til” or “since” is comparable to negation in \isi{perfect aspect} or with \isi{preterit} verbs in modern standard English. For example, “he \textit{never} was at attacking any Ship, Since he has been among them” [HCA 1/99/80] is comparable to \isi{perfect aspect} negation in modern-day usage, i.e., “he \textit{had not attacked} any ship since he had been among them”. In contrast, “he \textit{never} knew the prisoners till taken in the boat” [HCA 1/99 \isi{Bahama} Islands 1722] is comparable to \isi{preterit} negation in modern-day usage, i.e., “he \textit{didn't know} the prisoners until taken in the boat”. Even more common than this, however, was the use of “never” to negate events with little or no evidence of \isi{durative aspect}, e.g., “[on] July the 16th 1720, [he] owned he helped travessing a Gun but \textit{never} fired” [HCA 1/99/78], “he knew very well he had \textit{never} signed the Articles” [HCA 1/99/62], “he \textit{never} see him Sober Scarce” [HCA 1/99/44], and "Shows [shoes], stocking, which \textit{never} cost about [...] shillings” [SP 42/6]. Some examples of this type of indicative \isi{past tense} negation are only evident in light of the context of the utterance, e.g. the defendant who claims he “did \textit{never} see any letter” [HCA 1/98/255] is clearly referring to a specific letter at a specific time and not “any” letter at any previous time in his life (as would be implied by the use of “never” meaning “not” + “ever”). Similarly, when John Barefoote, Yeoman of the powder room of the \textit{Antelope} during April of 1663, testifies that he “\textit{never} had any discourse with Nathaniel Paintor Armourer in the \textit{Anthelope} nor with any other person in the said shipps Gunroome” [HCA 1/9/63] he is most likely referring to a specific conversation on a specific day (and hence, \isi{preterit} negation) rather than the idea that he “never” spoke with the armorer of the vessel nor any other person in the gunroom — an unlikely claim given that his job was to store and manage the gunpowder. Thus, whether it is evident from the linguistic context of the clause itself or the wider socio-historical context of the \isi{speech act}, the majority of negated statements using “never” appear to denote indicative past negation and not any kind of \isi{durative aspect} that we might associate with a \isi{lexeme} that derives from the negative particle “ne” and the \isi{adverb} “ever”.\footnote{It is worth noting that this past indicative use of the adverb “never” without \isi{durative aspect} is still found (in addition to other variant uses with varying degrees of \isi{aspectual} meaning) in modern-day non-standard English dialects (see \citealt{LucasWillis2012}).} \largerpage The third and fourth most common \isi{negation marker}s in the sample were the words “no” and the conjunction “nor”, which sampled at 12 and 8 percent of the total number of examples, respectively (see \figref{fig:key:6.1}). The negative marker “no” was most typically used in a prenominal position before a direct object or object compliment and took the function of a zero-marking determiner, e.g., “wee having noe boate” [HCA 1/12/2], “we found noe ground with our hand line” [ADM 52/1/7], “he thought himself no robber” [HCA 1/99/23], “Being able to get no imploy” [HCA 1/13/97], and “He knew of no offense that he had done therefore would ask him no pardon” [HCA 1/52/14]. This method of negation functions in accordance with the previously discussed tendency in Ship English to favor nominalization using light verbs, e.g., “Wee tooke no harme” [ADM 51/3983/1], “The Governour was a board of us but made no stay” [ADM 52/1/8], “but knows of no Sharing they made” [HCA 1/99 New Providence 1722], and “no vessell comeing that year could make noe prize” [HCA 1/98/262]. The negative marker “nor”, instead of being used in a pre-nominal position after an inflected \isi{verb}, often preceded a non-\isi{finite verb}, e.g., “he nor seeing them come out nor dealing with the master” [T 70/1/10] and “nor being neither this Deponent” [HCA 1/14/51]. However, the more customary use of “nor” as a negating conjunction frequently occurs in the \isi{corpus} and often functions to conjoin constituents that already have negation. Such \isi{negative concord} was a salient feature of sailors’ speech that manifests itself in popular songs about life at sea, such as the seventeenth-century song “Another of Seafarers” that includes the line “Nor have no room” (cited in \citealt{Palmer1986}: 6). The simplest example of negative concord in the \isi{corpus} is the word “nor” used to conjoin two negated \isi{verb} phrases, e.g., “He knows not \textit{nor} ever heard” [HCA 1/9/51] and “he …did \textit{not} bye them \textit{nor} had \textit{not} any conferences” [HCA 1/101/221]. In addition to concordant markers of negation occurring in the same phrase, strings of negated clauses are also common in the \isi{corpus}, for instance, the witness statement “But knows \textit{not} what it was, for he did \textit{not} hear it Read, \textit{nor never} heard that it was read, \textit{nor} knows \textit{not} how the Vessell was fitted out” [HCA 1/99/5] includes 6 negation markers, “not” (used three times both in a post verbal context and with “do support”), “nor” (twice), and “never” (once). The conjunction “nor” functions to join three negated clauses, firstly, “for he did \textit{not} hear it Read”, secondly, “\textit{never} heard that it was read”, and lastly “\textit{nor} knows \textit{not} how the Vessell was fitted out” and all of these are prefaced by another negated clause “But knows \textit{not} what it was” making a string of four negated clauses. A few times, the negative particle “nor” occurs as part of a correlative conjunction with the word “neither”, e.g., “he \textit{neythor} aske any price of the said Sherman for the said goods \textit{nor} the said Sherman never asked him if he would sell them or not” [HCA 1/101/224]. Yet, even in these few instances, the clauses that are conjoined often include \isi{negative concord} within the conjoined structure, such as in the example, “\textit{nor} the said Sherman \textit{never} asked him if he would sell them or \textit{not}.” This type of \isi{negative concord} may have been a feature of Ship English, but it was not distinctive from other varieties of English. The phenomena of \isi{negative concord} in non-standard varieties of English is widespread around the modern-day Atlantic (\citealt{vanderAuwera2016}), and (\citealt{KortmannLunkenheimer2013}) attest to 80\% \isi{negative concord} among global varieties of English . Thus, \isi{negative concord}, specifically using “no” in a prenominal position and joining negated phrases or clauses with the conjunction “nor”, is a salient feature of Ship English, but this is not surprising given its occurrence in Old English and its persistence throughout history up to the modern day in variant negation systems throughout the Anglophone world. \section{{Tense}}\label{sec:6.2} \subsection{{Present tense variation} }\label{sec:6.2.1} Logbooks, letters and depositions alike show variation in inflection patterns for \isi{present tense} \isi{indicative modality}, specifically an absence of inflection with \isi{singular third person} subjects. The following examples show \isi{uninflected} finite verbs (emphasized by italics) with \isi{singular third person} \isi{noun} phrases (emphasized in bold) “\textbf{moderate} \textbf{weather} \textit{blow} fresh” [ADM 52/2/3], “\textbf{Our} \textbf{boat} \textit{goe} in to Black Slakes” [ADM 52/2/9], “\textbf{all} \textbf{shipping} that \textit{come}” [BL/Egerton 2395/0007], and “\textbf{the} \textbf{boat} \textit{want} for wood” [CO 5/1411/712]. One specific \isi{witness deposition} taken in Grand \isi{Bahama} Island and dated 1722 shows inflection as a superscript particle (see \figref{fig:key:6.2}) suggesting that the original statement may not have included the inflection but it was added at a later stage in the \isi{court clerk}’s revisions. In addition to the examples of verbs used with \isi{singular third person} \isi{noun} phrases, there is also evidence of zero inflection with \isi{singular third person} pronouns, e.g., “\textbf{whoever} \textit{see} one first” [HCA 1/99/143], “He swore that \textbf{he} \textit{know} no negroes” [T 70/1/5], “\textbf{He} \textit{know} of no commission” [HCA 1/9/10], “\textbf{he} \textit{know} not” [HCA 1/101/219], and “\textbf{He} well \textit{know} Joseph Passof” [HCA 1/14/150]. Examples appear to connect the zero inflection with negation and specifically the \isi{verb} “know”, suggesting that this variation may be conditioned by linguistic constraints or favored specific lexemes in idiomatic phrases, however, the potential role of the Northern Subject Rule might also affect the selection of zero inflection with \isi{third person} pronominal subjects (see \citealt{deHaas2008}). \begin{figure} \includegraphics[width=\textwidth]{figures/delgado-img16.png} \caption{\label{fig:key:6.2} Excerpt from a deposition showing superscript inflection with a third person singular noun phrase in present tense indicative modality [HCA 1/99 Bahama {Islands 1722}]} \end{figure} The Northern Subject Rule may also account for examples of atypical inflection with \isi{plural} \isi{third person} subjects and when the \isi{verb} is not adjacent to a subject. In the \isi{corpus}, some \isi{plural} \isi{third person} subjects that are expressed as \isi{noun} phrases (emphasized in bold) take an inflected \isi{verb} (emphasized in italics), e.g., “\textbf{the} \textbf{barracks} \textit{tooks} fire” [SP 42/6], “\textbf{severall} \textbf{papers} which \textit{comes} herewith” [SP 42/6], and “\textbf{which} \textbf{accts} plainly \textit{demonstrates} the tricks” [SP 42/6]. The last two examples show the inflected \isi{verb} in a position that is not immediately adjacent to the \isi{noun phrase} subject, and perhaps this was a conditioning factor in the use of inflection with \isi{third person} subjects. Yet, whether it was due to the Northern Subject Rule, or another conditioning factor, the atypical inflection with \isi{plural} \isi{third person} subjects in Ship English — particularly when the \isi{verb} is not adjacent to a subject — was salient enough to be recorded in \isi{seventeenth century} sea-songs, e.g., “They cried \textbf{Englishmen} \textit{comes}” (from “A joyful new Ballad” cited in \citealt{Palmer1986}: 16), and “\textbf{Brave} \textbf{sailors} that \textit{sails} on the main” (from “Sailors for my Money” cited in \citealt{Palmer1986}: 31). Thus, although the constraints of the variation within inflectional paradigms are not entirely clear, sailors of the period were known to inflect verbs in ways that did not follow conventional contemporary standards. In addition to variation in \isi{present tense} inflection, there is also evidence of \isi{present tense} use in past contexts. Logbook entries clearly marked for past context make use of verbs inflected for the present indicative \isi{tense}, e.g., (with italic emphasis), “Last night the wind \textit{proves} Westerly” [ADM 52/2/9]. Witness depositions feature the use of \isi{present tense} more heavily despite the fact that the statements are marked for past context by the nature of their narrative content and also by the use of other \isi{preterit} verbs (emphasized in bold), e.g., “Then the Captain \textit{goes} upon the Half-Deck again, and \textbf{call’d} to his Man” [445f.1/23], and “the \isi{mariner} \textbf{Lay} and there \textit{talkes} with the men” [HCA 1/101/217]. Indeed, the use of inflected \isi{present tense} in past contexts in alteration with \isi{preterit} forms may be a manifestation of the narrative function of witness statements. Fleischman explains, “the NP [Narrative Present] is a spontaneous use of the PR [\isi{present tense}] that occurs consistently in \textit{alternation} with tenses of the P [past] and is linked to a performative mode of \textit{oral} storytelling” (1990: 258, author’s italics). Witness statements are certainly a modality of oral storytelling and in this context, alternation from past to present forms may have helped sailors bring immediacy — and thereby credibility — to their performances in court. The same use of Narrative Present \isi{tense} features in journal writing, e.g., Angelo and De Carli’s published work, “A Curious and Exact Account of a Voyage to Congo in the Years of 1666 and 1667” that narrates events alternating between \isi{present tense} forms (in italics) and \isi{past tense} forms (in bold): \begin{quotation} In a little time \textit{comes} the Lieutenant, and \textit{says} to one of them, Go down to thy Quarters; his answer \textbf{was}, I \textit{can} Fight no more; The which \textbf{was} what he looked for; for he \textbf{was} our greatest Enemy. Then he \textit{goes} to the captain, and \textit{makes} the worst of it, saying, Yonder the Quakers be altogether, and I \textit{do not know} but they \textit{will} Mutiny, and one \textit{says} he \textit{cannot} Fight; then he \textbf{ask’d} his name and \textbf{came} down. [445f.1/23] \end{quotation} Although the use of the \isi{present tense} is understandable in the representations of direct speech in this excerpt, narrative phrases also use \isi{present tense} to provide immediacy for the reader. So, although we might anticipate that the oral performance of witness testimony be more likely to show evidence of the Narrative Present, examples suggest that sailors also alternated between past and present in logbooks and journals, potentially reflecting their oral and performative culture (discussed in Chapter 4, Section 4.2.6 on shared ideologies and leisure activities). \subsection{{Past tense variation} }\label{sec:6.2.2} Variation in \isi{past tense marking} was one of the most salient features in the \isi{corpus}. There are many examples of regular inflection with weak (i.e., regular) \isi{verb} stems, (emphasized by italics) e.g., “we \textit{stopped} our ship” [ADM 52/2/5], “he \textit{answered} that he does not know” [HCA 1/13/94], and “he came afterwards \& \textit{robbed} her” [HCA 1/99/41]. Even with non-standard orthography, many examples of verbs imply pronunciation of the regular \isi{past tense} suffix <ed>, e.g., “[he] \textit{call’d} to his Man” [445f.1/23], “wee \textit{stopt} the Ebb all the flett \textit{Ankerd}” [ADM 52/2/1], “wee \textit{waid} [weighed] Anker” [ADM 52/2/1], “Both his pistolls \textit{mist} [missed] fire and did not go off” [HCA 1/52/137], and “\textit{kist} [kissed]… \textit{tript} [tripped]” [HCA 1/99/11].\footnote{In addition to these accepted regular forms of \isi{preterit} weak verbs, the use of “-th” inflections were also acceptable in the Early Modern English period, e.g., “who \textit{giveth} him dayly wages” [HCA 1/101/219] and “[he] \textit{saith} hee did” [HCA 1/9/3], although they were not a dominant form in the \isi{corpus}.} However, there were also many examples of weak finite verbs that were not inflected in a regular \isi{preterit} form despite being contextualized in the \isi{past tense} (by virtue of their narrative content and/or the past inflections of adjacent \isi{verb} phrases). Excerpts from depositions illustrate this phenomenon (emphasized by italics), e.g., “he \textit{fetch} some wine and \& beer” [CO 5/1411/47], “He \textit{hoyst} sayle \& went from that place” [HCA 1/52/41], “The Carpenter… came up, and \textit{answer} to the captaine” [HCA 1/52/41], and “[the men] \textit{board} and \textit{board} in which severall men were killed” [HCA 1/53/3]. Note that in the last three examples the unmarked forms are used in collocation with the \isi{preterit} forms of strong verbs, “went”, “came”, and “were”, respectively, which not only mark the past context of the excerpt but also show that unmarked forms were not universal in individual speech acts or for individual speakers. Similarly, excerpts from logbooks also include frequent \isi{uninflected} weak verbs in the \isi{past tense}, e.g., from the logbook of the \textit{Pideaux:} “this morning we \textit{lift} him again” and “he \textit{lift} the vessel” [HCA 1/99/53] and from the logbook of the Albemarle: “at 9 at night wee \textit{anker} in 30 fathom water”, “in the afternoon we \textit{fetch} 3 boat Loads of Ballast”, “at night we weighed \& \textit{fill up} the boy”, and “We \textit{Bury} overboard another Wounded” [ADM 52/2/1,6,8,9]. Although a number of the examples from logbooks follow prepositional phrases marking time, this is not considered to be a linguistic constraint of unmarked \isi{preterit} forms as there are also many examples of weak verbs with regular <ed> suffixes in this context. In short, it appears that Ship English permits \isi{free variation} between regular weak \isi{preterit} forms and unmarked \isi{preterit} forms, and this can occur across a range of registers, modalities, and linguistic contexts. Strong verbs (i.e., irregular verbs) presented the most variation in \isi{past tense marking}. There are many examples of strong \isi{preterit} forms in the \isi{corpus}, e.g., (with italic emphasis) “and [I] \textit{spoke} with him” [CO 5/1411/700], “They \textit{took} and plundered and \textit{took out} some rice \& sugar” [HCA 1/52/75], and “he \textit{saw} the \isi{prisoner} have a Sword” [HCA 1/99/72]. Yet, numerous examples also attest to variant methods of marking the \isi{preterit}. In some excerpts, past participles are used as \isi{preterit} forms of strong verbs, e.g., “he \textit{seen} him cut her cable” [HCA 1/99/73], “he \textit{seen} him go on Board” [HCA 1/99/96], and “[we] \textit{Rid} all night” [ADM 52/2/6].\footnote{According to \citet[95]{Blake2002} the \isi{preterit} and \isi{past tense} forms were encroaching into each other’s syntactic space in the Early Modern English period and so this type of variation may have been common at the time. Furthermore, this usage remains common in some modern non-standard varieties (\citealt{Cheshire1994}: 125).} Other excerpts show alternative irregular \isi{preterit} forms, e.g., “I \textit{writ} from Leverpoole” [445f.1/46], “I am informed of a letter you \textit{writ}” [HCA 1/98/66], and “we \textit{kam} to Anankor" [DDB6 8/4].\footnote{The \isi{preterit} in the example “we kam to Anankor" [DDB6 8/4], is somewhat problematic and depends on the speaker’s realization of the orthographic ‘a’ which appears to be [{ӕ] but could just have likely been realized as the diphthong [{ɪ}] or another allophonic variant acceptable in contemporary usage.} } The most common inflected variant however was a regularized form of a strong \isi{preterit} that was marked with a regular <ed> suffix, e.g., “He should not be \textit{hurted}” [HCA 1/99/9], “[I] \textit{quitted}” [HCA 1/99/12], “he \textit{waked}” [HCA 1/99/4], “she went out and \textit{catched} the Swallow” [HCA 1/99/150], and “[he] \textit{threw’d} the Dept. against the Ladder” [HCA 1/99/152]. The last example is particularly interesting as it marks \isi{tense} twice, once in the form of the anticipated strong \isi{preterit} form “threw” and again with the regular inflection “-ed” common to weak verbs. This example appears to corroborate the double \isi{tense marking} that Bailey and Ross found in logbook entries: “we \textit{bored} the yards” (1688: Sloane 3671) and “we \textit{tookt} in the Virgins Prises” [ADM 51/4298 1692] (cited in \citealt{BaileyRoss1988}: 204). It also potentially corresponds with the type of concordant \isi{past tense marking} in examples using an \isi{auxiliary verb}, e.g., “\textit{Did found} Robert Clarke” [HCA 1/9/51] that marks \isi{past tense} once in the \isi{auxiliary verb} “did” and again in the strong \isi{preterit} “found”. There were no discernable linguistic constraints that governed selection of \isi{past tense} realization, and some documents written in the same hand show \isi{free variation} in similar linguistic contexts, e.g., the journal of \isi{mariner} and \isi{merchant} Bryan Blundell (1687–1754) that includes the phrase “[the wind] \textit{blowed} very hard” and also “the wind \textit{blu} very hard” [DDB6 8/4] showing examples of the regularized \isi{past tense} form and the irregular form by the same author. Just like their weak counterparts, strong verbs also frequently occur without any \isi{past tense marking}, and this was the most common variant realization in the \isi{corpus} for this type of \isi{verb}. Strong verbs in witness testimony narrating past events frequently show zero marking, (emphasized by italics), e.g., “hee well \textit{know}” [HCA 1/52/1], “\textit{strike} him severall bloes about the head” [HCA 1/11/74], “He left one \& \textit{Bring} one to us” [ADM 52/2/9], “he \textit{say} that” [HCA 1/98/24], and “he was a Brisk Fellow [...] and \textit{tell} Roberts” [HCA 1/99/132]. Strong verbs in logbook entries relating to recent events in the \isi{past tense} also show frequent zero marking, e.g., “Longboat in a Violent Gust \textit{break}” [ADM 51/3954], “The wind \textit{blow} fresh” [ADM 51/4322/1], “we \textit{gett} 32 punsh [punch] \& 31 butt ashore” [ADM 52/1/8], “wee \textit{give} Our ship” [ADM 51/3797/1]. Although the frequency of zero-marked \isi{preterit} strong verbs is significant for a range of verbs both in logbooks and witness depositions, there were some trends that suggest a higher usage with specific verbs. The \isi{verb} “see” was sampled with zero \isi{past tense marking} 21 times (significantly more than any other \isi{verb}) throughout the \isi{corpus}, e.g., “I \textit{see} him put it under his left arm” [HCA 1/99/7], “he \textit{See} him go over the Side” [HCA 1/99/147], “he \textit{see} him cruelly beat to make him go” [HCA 1/99/147], “hee \textit{see} George Freebound” [HCA 1/9/3], and “In Hasting Bay wee \textit{see} Severall French Shipps” [ADM 52/3/7]. Four counts of zero marking with negation imply a possible condition, e.g., “he never \textit{see} them any more” [HCA 1/99/110], “never \textit{see} him in Arms” [HCA 1/99/133], “never \textit{see} any Letter” [HCA 1/98/20], and “Gott about the mast but \textit{see} nothing but three small Topsails” [ADM 52/3/7]. However, there is little evidence that this specific \isi{verb} is conditioned by any specific factors that select zero \isi{preterit} marking and the strong \isi{preterit} form is equally represented in the \isi{corpus} (including in phrases with negation) e.g., “had never saw a Prize taken” [HCA 1/99/8], “wee saw him not” [HCA 1/12/2], “At two yesterday [...] \textit{saw} our fleat” [ADM 52/1/1], “he \textit{saw} the \isi{prisoner} have a Sword” [HCA 1/99/72], and “he run away when he saw twas the Kings Ship” [HCA 1/99/96]. Thus, the lexical item itself rather than the linguistic context of its use appears to select a preference for zero marking, although zero marking occurs with a range of verbs and is not restricted to specific lexical items like the \isi{verb} “see”. The \isi{verb} “run” was the second most heavily occurring strong \isi{verb} with an unmarked \isi{preterit} form, sampled 18 times in the \isi{corpus}. Every one of the 18 examples occur in the context of a \isi{phrasal verb} (emphasized in italics) e.g., “he \textit{run up} the shrouds” [HCA 1/99/9], “\textit{Run out} to the buoy” [ADM 52/2/5], “they \textit{run} her \textit{on} ground” [HCA 1/99/10], and “he Saw the Kings Colours he \textit{run down}” [HCA 1/99/78]. As in the last example, many of these unmarked phrasal verbs occur in contexts where other strong \isi{preterit} forms and weak \isi{preterit} forms are explicitly marked for \isi{past tense} (marked in bold), e.g., “when he \textbf{Saw} the Kings Colours he \textit{run down}, \textbf{Confessed} he had been on Board” [HCA 1/99/78], and “we \textbf{shote} his maine yard Down but he \textit{run over} the officer and \textit{run up} Poldard bay [...] where he \textbf{durst} not follow” [ADM 52/1/1]. The \isi{satellite particle} “away” used with the \isi{verb} “run” appears to favor zero \isi{past tense marking} more than any other \isi{satellite particle}. This is evidenced by the fact that “run away” composes more than half of the recorded samples using the \isi{verb} stem “run” (10 of the 18 samples),\footnote{The high frequency of “run away” may, in part, be explained by the nature of witness testimony coupled with the number of court cases related to sailors deserting their vessel.} e.g., “John Hardin who \textit{run} away” [SP 42/6], “one of them who run away with the sloop” [HCA 1/99 \isi{Bahama} Islands 1722], “Kenyou \textit{run away} crying what have you done” [HCA 1/99/7], “he \textit{run away} when he saw twas the Kings Ship” [HCA 1/99/96], and “Some men that \textit{Run away}” [HCA 1/13/100]. Yet “run” (with whatever \isi{satellite particle} it takes) is not the only \isi{verb} stem in a \isi{phrasal verb} that is represented with zero marking in the \isi{corpus}. Various \isi{uninflected} verbs with a range of satellite particles also select zero marking, e.g., “We \textit{goe away} Before” [ADM 52/2/9], “The Cable \textit{give waye}” [ADM 51/3797/1], “His Company aforesaid and \textit{take away} his said Vesell” [HCA 1/52/133], “At two yesterday [...] saw our fleat then we \textit{hall in}” [ADM 52/1/1], “A saile \textit{stand out} of the Ba [bay]” [ADM 52/2/9], “We soon \textit{come up with} her” [ADM 52/2/9], “Watts \textit{take off}” [HCA 1/99/145], and “I \textit{come to} an Anchor” [1045.f.3/1/16]. In short, although “run”, specifically used with the \isi{satellite particle} “away”, was the most salient example of unmarked strong \isi{preterit} forms in the \isi{corpus} when expressed as a \isi{phrasal verb}, evidence indicates that Ship English permits zero marking in any \isi{phrasal verb} composition, although certain lexemes might favor zero marking in \isi{idiomatic usage}. \newpage As discussed in the previous paragraphs, \isi{past tense} variant forms may be conditioned by certain lexemes such as “see” and “run” or they may be conditioned by verbs used in \isi{phrasal verb} constituents, yet overall there is no convincing evidence that linguistic or socio-linguistic factors play a role in past \isi{tense variation}. Instead, variant forms occur in the same linguistic contexts, in the same documents, and in the same handwriting across a range of documents with varying levels of formality and stylistic expectations. For example, one \isi{witness deposition} includes the statement, “They \textbf{took} and \textbf{plundered} and took out some rice \& sugar and some rigging and then \textit{sink} her” [HCA 1/52/75] in which an unmarked \isi{preterit} “sink” occurs in a coordinated clause structure with the standard inflected weak \isi{verb} in \isi{past tense} “plundered” and also the standard form of the strong \isi{verb} \isi{preterit} “took”. Logbooks also show examples of zero marked \isi{preterit} forms in coordinated clauses with standard forms of strong verbs, e.g., “severall of the fleet \textit{break} their Cables \& we \textbf{lost} our Long boat” [ADM 52/2/6], and “every one \textbf{came} and \textit{eat} and \textbf{drank} with him” [HCA 1/99/59]. Other logbooks show the same \isi{verb} occurring in standard and \isi{preterit} forms in a single \isi{speech act}, e.g., the \isi{verb} forms “gett” and “gott” in the excerpt, “We \textit{gett} Anchor aboard [...] we \textit{see} severall ships a stern which \textbf{Came} into our fleet … severall of the fleet \textbf{made} Sayle and \textbf{gott} into [...] harbor” [ADM 52/3/7]. A longer excerpt from a single witness statement taken at the Rhode Island and Providence Plantation on 9 September {1725} shows similar variation among standard and zero-marked forms of strong verbs by one speaker: \begin{quotation} he [the captain] \textbf{told} me he would make me Sign and \textbf{sent} for two candles in a plate and \textbf{made} me eat them. And then \textit{bid} me go to the Devil for he would force no man then I \textit{see} some of them with Sticks in their Hands \& Needles through the end of them I \textbf{asked} Jonathan Barney a \isi{prisoner} on Board what they \textbf{were} for. [HCA 1/99/5] \end{quotation} Such evidence of wide-ranging yet non-universal distribution of variant forms in the \isi{past tense} suggests that \isi{free variation} is a more probable explanation than conditioned variation. \subsection{{Infinitives}}\label{sec:6.2.3} Ship English permits infinitives in non-standard contexts and also permits their omission when \isi{standard usage} anticipates them. Infinitives are permitted after \isi{participle} forms of a \isi{verb}, for instance, present participles (marked in bold) permit subsequent infinitives (in italics), e.g., “\textbf{observing} Shaik Joseph \textit{to hold} a Bag in his hand” [HCA 1/99 Bombay, July 17 1730, 3], and “\textbf{finding} the Pink \textit{to sayle} heavy” [HCA 1/98/28]. Yet infinitives after past participles (marked in bold), are more common, e.g., “they mett with a little Dutch shipp \textbf{designed} \textit{to go} trade with or among the Spaniards” [CO 5/1411/97], “[he was] \textbf{obliged} \textit{to leave} the money he had formerly wrought for (being a carpenter], and was \textbf{gone} \textit{to receive}” [HCA 1/99/8 New Providence 1722], “Barbley, about two dayes after \textbf{caused} the Saw \textit{to be} brought into his yard” [HCA 1/9/57], “[he was] \textbf{promised} \textit{to be} landed in England” [HCA 1/13/97], and “[he] \textbf{assisted} \textit{to rob} her” [HCA 1/99/42].\footnote{This last example “[he] \textbf{assisted} \textit{to rob} her” [HCA 1/99/42] may not be a true \isi{infinitive} but a manifestation of the commonly collocated “assisted to” expression that is seen elsewhere in the \isi{corpus} prior to a \isi{noun phrase}, e.g., “\textbf{assisting} \textbf{to} the Robbing of his Ship” [HCA 1/99/42].} Infinitives are also permitted after auxiliary verbs with conditional modality (marked in bold), e.g., “he begged if possible his Ship Mates \textbf{cou’d} \textit{to hide} him from the Pyrates” [HCA 1/99/21], “a Lock, and Key which the \isi{prisoner} \textbf{wou’d} \textbf{have} \textit{to belong} to him” [HCA 1/99/30], and “our men \textbf{would} \textbf{have} me \textit{to put} them on” [445f.1/45]. Infinitive use after modal auxiliaries also occurs in parallel structures with verbs expressed in their \isi{uninflected} form (marked in bold), e.g., “for I cannot \textbf{doe} what I would \textit{to doe}” [HCA 1/101/423], and “they would \textbf{put} the Goods in the Hould [...] and \textit{to send} her in with twelve men” [HCA 1/9/9], suggesting that the \isi{uninflected} form and the \isi{infinitive} may have been interchangeable. This suggestion is supported by omission of the particle “to” in some contexts, e.g., “bidding him [\textit{to}] hold his tongue” [HCA 1/9/139], “I humbly thank you for any share you are pleased [\textit{to}] take in my favour” [HCA 1/101/382], “you need [\textit{to}] chuse” [CO 5/1411/658], and “the \isi{prisoner} bid the \isi{deponent} [\textit{to}] look for the saw” [HCA 1/99 \isi{Williamsburg}, Aug 14 1729]. Omission of a complete \isi{infinitive} form (both the particle and the \isi{verb}) is permitted when the meaning is evident from context, e.g., “wee met with Shipton again who forced us [\textit{to go}] with him” [HCA 1/99/5], and “believes him [\textit{to be}] one of those who divided his Cloths” [HCA 1/99/140].\footnote{The omission of the \isi{infinitive} “to be” is specifically discussed in a later subsection on usage and omission of “be” in this chapter, see \sectref{sec:6.3.2}.} In sum, and although there were too few examples to make strong claims about the \isi{linguistic conditioning} of variant infinitives, samples suggest that these verbs without \isi{tense} were permitted after \isi{participle} forms and modal auxiliaries but were completely or partially omitted in other contexts; they were also potentially interchangeable with the \isi{uninflected} form of the \isi{verb}. \section{{The copula and auxiliary “be”}}\label{sec:6.3} \subsection{{Inflection}}\label{sec:6.3.1} The \isi{verb} “to be” features most predominantly in \isi{past tense}, and “was” occurs as the most frequent \isi{past tense} inflection with all types of nominal and pronominal subjects in first, second, and \isi{third person}.\footnote{Variation in \isi{past tense} realizations of the \isi{verb} “be” is no surprise given the widespread tendency to level the contrast between “was” and “were” potentially owing to the fact that “be” is seen as “a defective \isi{verb}”, with an \isi{inflectional paradigm} that derives from three distinct and independent verbs in Aryan, Teutonic and Greek (\citealt{oed1989}, Vol 2: 1).} The standard \isi{preterit} form “were” is evident in the \isi{corpus}, but is not common, e.g., “we \textit{were} foresd” [ADM 52/1/7], “they \textit{were} in trenches” [ADM 52/1/7], “the Men out of the \textit{Onflow were} Volunteers” [HCA 1/99/112], and “those who \textit{were} active and were minded to recommend themselves for brave men” [HCA 1/99/94] (all italicized for emphasis). Of these limited examples, the most common occurrence of the inflection “were” occurred in statements marked for subjunctive mood, e.g., “except he \textit{were} dead” [HCA 1/9/51], “If he \textit{were} a Hollander” [HCA 1/9/9], “if all \textit{were} of my mind” [HCA 1/99/36], “asked how he would like it, \textit{were} he a \isi{prisoner}” [HCA 1/99/30], and “ask’d if any vessel were coming from \isi{Barbados}” [HCA 1/99/6]. Far more common than “were” in all indicative contexts was the \isi{preterit} form “was” that appears with first, second, and \isi{third person} subjects (both with \isi{noun} phrases and pronouns), in singular and \isi{plural} contexts (see \tabref{tab:key:6.1}). \begin{table} \caption{\label{tab:key:6.1} Examples of the preterit “was” used for with first, second, and third person nouns and pronouns, both singular and plural} \small \begin{tabularx}{\textwidth}{llQQ} \lsptoprule person & & \textbf{Singular} & \textbf{Plural}\\ \midrule \textbf{1\textsuperscript{st}} & \textbf{Noun phrase} & n/a\textsuperscript{a} & “My Self and the rest of the Company under my command \textit{was} entered and Musterd on board” [ADM 51/4170/2]\\ \tablevspace & \textbf{Pronoun} & “I \textit{was} told, no other Trees fit to build with” [1045.f.3/1/27] & “then he made [out] what we \textit{was}” [ADM 52/1/1]\\ \midrule \textbf{2\textsuperscript{nd}} & \textbf{Noun phrase} & n/a\textsuperscript{a} & “you also John Jessop \textit{was} lately wicked” [HCA 1/99/170]\\ \tablevspace & \textbf{Pronoun} & “it may be you \textit{was} not willing at the first” [CO 5/1411/42] & “\textit{was} you [\biberror{referring} to John Houghling, Corneluis Franc and Francois Delaune] on board the pyrate shipp when she was taken” [CO 5/1411/28] \\ \midrule \textbf{3\textsuperscript{rd}} & \textbf{Noun phrase} & “the \isi{prisoner} \textit{was} belonging to Augustino’s \isi{crew}” [HCA 1/99/7] & “those goods \textit{was} to ship” [HCA 1/98/43] \\ \tablevspace & \textbf{Pronoun} & “after he \textit{was} come on board” [CO 5/1411/99] & “where they \textit{was} carried” [HCA 1/101/220]\\ \lspbottomrule \end{tabularx} \parbox{\textwidth}{\footnotesize \textsuperscript{a}Not applicable as reference to self (first person) or addressee (second person) using a \isi{noun phrase} renders it \isi{third person}. } \end{table} In terms of \isi{linguistic conditioning}, the most salient use of the \isi{preterit} form “was” appeared in \isi{third person} \isi{plural} contexts with a \isi{noun phrase} (emphasized in bold), and most examples of these were to be found in witness depositions, e.g., “\textbf{those} \textbf{men} [...] that \textit{was}n't immediately on board” [ADM 106/300/25], “they met with \textbf{two} \textbf{ships} which \textit{was} pirates” [HCA 1/98/47], “there \textit{was} \textbf{three} at first” [HCA 1/99/8], “about \textbf{tew} \textbf{of} \textbf{them} \textit{was} gone” [HCA 1/99/126], “Four to one \textit{was} \textbf{odds}” [HCA 1/9/155], and “to confes, where \textbf{their} \textbf{moneys} \textit{was}” [HCA 1/9/18]. Although various examples of \isi{third person} \isi{plural} \isi{noun} phrases used with “was” appear, very few trends of usage suggest any type of internal \isi{linguistic conditioning} that selected the \isi{preterit} form “was” over the alternative variant “were”. One potential conditioning factor was the use of a compound \isi{noun phrase} as a subject that is formed with a conjunction (\isi{noun phrase} emphasized in bold), e.g., “\textbf{8} \textbf{sayle} \textbf{of} \textbf{English} \textbf{\&} \textbf{Dutch} \textit{was} drawn out” [ADM 52/2/5], “Where \textbf{his} \textbf{money} \textbf{\&} \textbf{Gold} \textit{was}” [HCA 1/9/18], “\textbf{my} \textbf{Ledger} \textbf{and} \textbf{hauwl} \textit{was} carried a shore” [ADM 51/3954], “\textbf{hee} \textbf{and} \textbf{Captaine} \textbf{Thomas} \textbf{Garnett} \textit{was} taken” [HCA 1/9/67], “\textbf{the} \textbf{country} \textbf{and} \textbf{his} \textbf{colonies} \textit{was} not under his command” [CO 5/1411/101], and “\textbf{Nutmeggs} \textbf{or} \textbf{Cloves} that \textit{was} given away” [HCA 1/12/78]. Yet there is no evidence to suggest that the \isi{plural} or singular nature of either constituent in the conjoined \isi{noun} phrases affects the choice of “be” \isi{preterit} as either “was” or “were” and this may signify that the use of the conjunction itself selected the use of “was” rather than the composition of the conjoined \isi{noun phrase}. Another potential conditioning factor may have been the use of a first person \isi{plural} \isi{pronoun} subject “we” as the subject of the clause in which “was” forms the main \isi{verb} of the predicate, particularly when directly preceding “be”, e.g., “\textbf{wee} \textit{was} forced soe neare the shoare” [HCA 1/12/2], “\textbf{we} \textit{was} forsed to Stand to the Westward” [ADM 52/1/1], “masking what \textbf{we} \textit{was}” [ADM 52/1/1], and “agreeable to you as \textbf{we} \textit{was} then got out” [D/Earle/3/1]. The salience of this usage is also highlighted by its inclusion in published sea-songs of the \isi{seventeenth century}, e.g., “As \textbf{we} \textit{was} sailing on the main [...] we was in danger” (cited in \citealt{Palmer1986}: 51). Yet, despite these two potential conditioning factors for selecting “was” rather than the \isi{preterit} form “were”, the frequency and range of variation in the \isi{corpus} suggests either \isi{free variation} or a general tendency to select “was” in all contexts rather than complementary distribution of the “was” and “were” forms. Present \isi{tense} and infinite forms of the \isi{verb} “be” feature less frequently than \isi{past tense} forms in the \isi{corpus}, but show similar variation. In the \isi{present tense}, examples of usage show a tendency to level the contrast between “is” and “are”, with “is” appearing more frequently with \isi{noun phrase} subjects in the singular and \isi{plural} \isi{third person} forms. Furthermore, this occurred when the “be” was in pre- and post-subject positions and also when it was either adjacent to or separated from the subject, e.g., “here \textit{is} \textbf{2} \textbf{Merchant} \textbf{men}” [ADM 52/1/8], “\textbf{pitch}, which \textit{is} wanting” [5/1411/646], “\textbf{The} \textbf{ships} \textit{is} all gone” [HCA 1/101/553], “Give me an account how \textbf{all} \textbf{things} \textit{is} in the Contrey” [HCA 1/12/86], “\textbf{These} \textit{is} received” [ADM 106/300/12], and “Men which die yearly in those Forts, \textbf{whose} \textbf{Substance,} \textbf{Wages,} \textbf{etc.} \textit{is} left for the Company” [BL/74/816/m/11/36/2]. This finding supports \citegen{BaileyRoss1988} observation that in \isi{seventeenth century} logbooks “\textit{is} is the predominant \isi{plural} in many of the logs, with \textit{are} relatively uncommon” (p.201, authors’ italics). In addition to preference for “is”, Bailey and Ross also recognize the use of the \isi{uninflected} \isi{verb} “be” in finite contexts in the logbooks they analyzed, e.g., “they \textit{bee} well sett people” (1988: Sloane 3833) and “the corkers \textit{be} come to Corke” [ADM 52/78], both cited in Bailey \& Ross (1988: 200). The usage of \isi{uninflected} “be” also seems to characterize representations of sailors’ speech in publications such as sea-songs, e.g., “Victuals and weapons they \textit{be} nothing scant”, “Her flags \textit{be} new trimmed”, and “The dangers great on seas \textit{be} rife” (cited in \citealt{Palmer1986}: 2, 3, \& 6, respectively). Seminal literary works related to sailors also show this type of usage, e.g., “\textit{be} it some Object”, “he \textit{be} much O glad”, and “you teach wild Mans \textit{be} good” in \citegen{Defoe1719} \textit{Robinson Crusoe},\footnote{The last two of these three examples from \textit{Robinson Crusoe} are contextualized in the voice of Man Friday and thus potentially aim to illustrate a Ship \isi{Pidgin} feature rather than a variation inherent to Ship English.} and “Master Billy Bones, if that \textit{be} your name” (part 1, ch 2), “the slight, if there \textit{be} one, was unintentional” (part 2, ch 9) in \citegen{Stevenson1883} \textit{Treasure Island}. However, although usage of \isi{uninflected} “be” was evident in the \isi{corpus}, e.g., “if any such there \textit{be}” [CO 5/1411/649], it was not a regular nor salient feature of present indicative statements as claimed by Baily and Ross’s scholarship and suggested by literature representing sailors’ speech. Instead, the use of \isi{uninflected} “be” seems to be restricted to the context of subjunctive or \isi{imperative modality} that equates with \isi{standard usage}, e.g., “yet one thing I have to advise you of, that you \textit{be} not ensnared” [445f.1/22], and “\textit{be} not afraid” [445f.1/44]. It may be that popular representations of foreign sailors’ speech that potentially suggest a maritime \isi{Pidgin} have influenced the perceived salience of a variant \isi{uninflected} “be” feature that is not significantly represented in the extended \isi{corpus} of this study. \subsection{{Usage and omission} }\label{sec:6.3.2} The \isi{verb} “be” is not frequently used as the principal inflected \isi{verb} in the \isi{corpus} in a way that corresponds to how we use the \isi{verb} in a non-auxiliary manner in standard modern English. Specifically, the use of the \isi{copula} as a type of \isi{linking verb} with a predicate \isi{adjective}, \isi{noun}, or \isi{adverb} does appear in the \isi{corpus}, but this type of usage is not common, e.g., with a predicate \isi{adjective} (in bold), “John Jessop \textit{was} lately \textbf{wicked}” [HCA 1/99/170]; with a \isi{predicate noun} (in bold), “I considered to strike them that was next [to] me, which \textit{was} \textbf{the} \textbf{weakest}” [445f.1/44]; and with a predicate \isi{adverb} (in bold), “and we \textit{was} \textbf{up} \textbf{in} \textbf{the} \textbf{country}” [T/70/1216/10]. The use of the \isi{copula} as part of an existential clause is also evident but is similarly infrequent, e.g., “\textit{There was} five hundred thousand cheeses” [HCA 1/12/84], “\textit{itt is} a very hey [high] Iland” [DDB6 8/4], “\textit{it was} stolen goods” [HCA 1/101/220], and “\textit{there was not} any Ship or vessell taken by him or any of his Company” [HCA 1/14/205]. Existential use of “there” plus the inflected \isi{copula} is not common in the \isi{corpus} given the propensity of sailors to express attendant circumstances with a present \isi{participle phrase} headed with being, e.g. “And account \textit{being} given to me by you captn John Aldred” [CO 5/1411/665] “but could not speak with them \textit{being} night and hazey” [CO 5/1411/699], and “The capt \& Lieut \textit{being standing} together” [HCA 1/9/155]. Even when expletives such as “there” and “it” are explicit, it is permissible to use a predicate headed by the infinite \isi{participle} “being” rather than the \isi{finite copula}, e.g., “weighed [anchor] \textbf{it} \textit{being} little wind” [CO 5/1411/694]. In short, linking and existential contexts in which the \isi{finite copula} might be common in \isi{standard usage} are evident but infrequent in the \isi{corpus} of Ship English under study. In contrast, the finite forms of the \isi{verb} “be” appear frequently in the \isi{corpus} as a requisite of passive structures. Sometimes these structures are made explicit by the use of a \isi{prepositional phrase} of agency (in bold), e.g., “he \textit{was} misused and beat \textbf{by} \textbf{the} \textbf{pyrates}” [HCA 1/99/31], “[they] \textit{was}\textbf{ }fired at \textbf{by} \textbf{a} \textbf{great} \textbf{Spanish} \textbf{shipp}” [HCA 1/9/18], and “the Governers Wife and Daughter of Cuba \textit{were} taken Prisoners \textbf{by} \textbf{a} \textbf{Pyrate}” [HCA 1/99/9]. However, more frequently, the omission of such a prepositional constituent obscures the \isi{logical subject} of the \isi{transitive verb} that has been rendered in passive form, e.g., “we \textit{are} excused” [HCA 1/99/39], “our Spare Anchor \textit{was} gott aboard” [ADM 52/2/3], “he \textit{was} beat” [HCA 1/99/124], “they \textit{were} not permitted to trade” [HCA 1/9/18]. It is worth noting that “be” in passive structures is subject to the same variation and tendency to level the \isi{inflectional paradigm} as with any other finite usage (discussed above), e.g., “[\textbf{we}] \textit{were} forced on a reife of sand and \textbf{[we]} \textit{was} forced to cut away our main mast” [HCA 1/12/2], “\textbf{2} \textbf{ships} that \textit{was} driven from the Virginia Coast” [ADM 52/1/8], and “\textbf{they} \textit{was} carried” [HCA 1/101/220]. In addition to inflectional variation, finite “be” omission in passive structures is also a permissible variant, e.g., “Five pounds [was] payd him in money” [HCA 1/9/64], “today [was] Taken out of the George Hoy Tho Harris” [ADM 52/1/5], “found his chest [was] broke open” [HCA 1/99/7], and “they [were] called to go one Boarde” [HCA 1/99/140]. In short, frequent uses of the “be” in passive structures support the general tendency for \isi{leveling} of the \isi{inflectional paradigm} but also indicate that “be” omission was an acceptable variation. The omission of “be”, regarding which Bailey and Ross find “zero evidence” in their study of \isi{seventeenth century} logbooks (1988: 202), manifests itself in a range of contexts in this extended \isi{corpus} of documents ranging from 1620 to 1750 and composing logbooks, depositions, letters and miscellaneous documents. Interestingly, most of the examples come from logbooks of the late 1600s and early 1700s, e.g., “the wind [is/was] blowing violent \& contrary” [HCA 1/12/2], “the wind [is/was] very little or calme” [ADM 52/2/3], “we thought it [is/was] the same” [HCA 1/99/27], “we [are/were] Riding Single till noon” [ADM 52/2/5], “our Long Boate [is/was] employed to fetch water all night” [ADM 52/1/8], “at day light [there is/was] little wind” [ADM 52/2/3], and “fair pleasant we [are/were] excuse[d]; all Drunk” [HCA 1/99/39]. The abbreviated style permitted in logbook writing may have conditioned “be” omission, particularly in \isi{stative} contexts when used as the main inflected \isi{verb} and even more so when the meaning was self-evident or routinely referenced such as talking about wind conditions. Omission of “be” was also evident in other types of documents, e.g., the letter that opens, “It [is/was] appealing to me, that it is for his majestys official service” [CO 5/1411/666], and the testimony that states, “information wee have from one that [was] razed with him” [ADM 106/288/42]. Omission of “be” in its \isi{infinitive} form (i.e., the \isi{satellite particle} “to” and the base form “be”) occurs in witness depositions, e.g., “believes him [to be] one of those who divided his Cloths” [HCA 1/99/140], “happened [to be] in your way” [HCA 1/99/3/2], and “owns himselfe [to be] and Irishman” [HCA 1/53/3]. And, just like the finite omission in logbooks and letters, this type of \isi{infinitive} omission in courtroom testimony could also have been conditioned by the function of the \isi{verb} in contexts where meaning is self-evident or routinely referenced such as giving character descriptions (\isi{stative} or existential \isi{copula} function) or indicating places (locative function). \subsection{{Aspect using “be” auxiliary}}\label{sec:6.3.3} \largerpage Finite “be” auxiliaries and \isi{present participle} verbs are used to mark \isi{progressive aspect} in the \isi{corpus}, however the structure permits variation that is not typical in \isi{standard usage}. Limited examples show \isi{standard usage} of the finite “be” verb (in italics) with a \isi{present participle} \isi{verb phrase} denoting active process (in bold), e.g., “\textit{Edgar} wch \textit{is} now in \textbf{Paying} \& hope to dispatch to morrow” [ADM 106/288/30], and “his tobacco \textit{was} \textbf{throwing} overboard” [CO 5/1411/58].\footnote{Note that the example “his tobacco \textit{was} \textbf{throwing} overboard” [CO 5/1411/58] is expressed in the passive voice and so a standard version might be rendered “his tobacco \textit{was being thrown} overboard”.} This usage is standard because the finite auxiliary (“is” and “was”, respectively) projects a \isi{present participle} denoting active process (“Paying” and “throwing”) and both events are continuous over a period of time (\citealt{SILInternational2005}). However, comparable to uses of the \isi{progressive aspect} with a \isi{present participle} denoting active process, the \isi{corpus} includes many more examples of this same structure used with participles of verbs that have a \isi{stative} meaning, e.g., “the \isi{prisoner} \textit{was} \textbf{belonging} to Augustino’s \isi{crew}” [HCA 1/99/7], “I do not know nor never heard that the Master or any of the Seamen \textit{were} \textbf{knowing} of it” [HCA 1/9/51], and “it \textit{was} \textbf{being} with some officers upon an island sevrall daies withouth victualls” [CO 5/1411/41].\footnote{The combination of the finite “be” auxiliary with a \isi{present participle} of a \isi{stative} \isi{verb} was (and is) not generally permissible in \isi{standard usage} but was (and still is) acceptable in certain dialects and contexts, (\citealt{Römer2005}: 113–116).} The \isi{stative} meaning of the participles emphasized in bold are more suited to \isi{preterit} \isi{verb} use in standard English, i.e., “the \isi{prisoner} \textit{belonged} to Augustino’s \isi{crew}”, “…the Master or any of the Seamen \textit{knew} it”, and “it \textit{was} with some officers upon an island sevrall daies withouth victualls” [CO 5/1411/41]. Indeed, for this reason many of the \isi{progressive aspect} structures in the \isi{corpus} of Ship English might be more suitably rendered in \isi{preterit} \isi{tense} in \isi{standard usage}. Yet, use of a structure composed of the auxiliary “be” and a \isi{stative} \isi{participle} seems to have been a feature of sailors’ talk, and the fact that it features in popular sea-songs attests to its salience as a marker of their speech, e.g., the line “They \textit{were} the treasure \textbf{possessing}” (cited in \citealt{Palmer1986}: 55). In sum, when sailors used the \isi{progressive aspect} they sometimes rendered it with a \isi{present participle} denoting active process (in accordance with \isi{standard usage}) but more frequently rendered it with The use of present participles as the only constituent of a main \isi{verb} structure implies that “be” may have been omitted when used as an auxiliary in an underlying \isi{aspectual} structure. Interestingly, this type of omission occurs more often with active verbs that would be more suited to the progressive \isi{aspectual} structure, e.g., “they [were] whispering and afterwards [were] agreeing one with another” [HCA 1/99/112], “he [was] with his Cutlass spoiling and hacking everything” [HCA 1/99/126], “they [were] abusing him” [HCA 1/99/103], and “we [were] Riding Single till noon” [ADM 52/2/5]. Without any finite auxiliary, these excerpts are reduced to phrases headed with a \isi{present participle}. Yet, it is possible that these phrases derive from underlying progressive \isi{aspectual} structures with omitted finite auxiliaries, and that would explain how they appear to function as independent clauses of attendant circumstances rather than as modifications of an antecedent \isi{noun phrase}. This interpretation is reinforced by the fact that many examples of these structures appear in coordination with clauses that have indicative non-\isi{aspectual} verbs and therefore potentially show a time sequence juxtaposing the progressive duration of one clause with the single time referent of another. To illustrate, the following excerpt from a \isi{witness deposition}: “they tarrying longer the said Le Fort sailed away” [HCA 1/52/137] can be interpreted as two clauses, the first expressed with \isi{progressive aspect} and the second with a \isi{preterit} \isi{indicative verb} specifically denoting the fact that it occurred later and interrupted the durative event of the first \isi{verb}, i.e., “they [were] tarrying longer [when] the said Le Fort sailed away”. In another example of a letter written by \isi{mariner} John Morris to his wife, the opening excerpt reads, “Ever Loufing wief these lines is to arkquint you that I Lying more like to die than to lief desiring you to remember my kind love to my three Cussons” [HCA 1/52/51]. If we interpret the two present participles “Lying” and “desiring” to derive from underlying progressive \isi{aspectual} structures with omitted finite auxiliaries and the three \isi{verb} constituents to represent three separate clauses, then the excerpt would be interpreted as: “Ever Loufing wief these lines is to arkquint you that I [am] Lying more like to die than to lief [and I am] desiring you to remember my kind love to my three Cussons”. This excerpt then expresses three distinct ideas, firstly, the \isi{matrix clause}, “these lines is[are] to aquaint you”, secondly, the embedded \isi{relative clause}, “that I am lying more likely to die than to live”, and thirdly, the subordinating clause, “[so] I am desiring [I desire] you to remember my kind love”. Moreover, this interpretation matches the proposed sailors’ standard use of the \isi{progressive aspect} in standard distribution with active verbs (“I am lying”) and also demonstrates their tendency to use a marked variation of the same structures with \isi{stative} verbs (“I am desiring”). Such examples support the suggestion that \isi{present participle} phrases may have denoted (or derived from) clauses with progressive aspects in which finite “be” had been omitted but are still manifest in the underlying structure. Variant usage of the verb “be” includes structures that denote completed events and therefore suggest perfect \isi{aspectual meaning}. These structures are sometimes expressed in the finite present or \isi{past tense}, e.g., “wee \textit{are} 6 month and 6 days upon our \isi{voyage}” [DDB6 8/4], “the ship \textit{is} sailed…he \textit{is} run away” [5/1411/646], meaning “we \textbf{have} \textbf{been} 6 month[s] and 6 days upon our \isi{voyage}” and “the ship \textbf{had }\textbf{sailed}…he \textbf{had} \textbf{run} \textbf{away}”, respectively. Other completive events are expressed with the \isi{present participle} of “be”, e.g., “the \isi{merchant} ship not \textit{being} gon into York river” [CO 5/1411/702], and “news \textit{being} come at that time” [HCA 1/99/9], meaning “the \isi{merchant} ship \textbf{had} \textbf{not} \textbf{gone} into York river”, and “news \textbf{had} \textbf{come} at that time” respectively. In all of these examples, the \isi{verb} “be” appears to function the same as the auxiliary “have” does in structures with \isi{perfect aspect} and suggests that this exchange may have been a variant feature of how “be” was used to denote aspect in Ship English. \section{{Auxiliaries}}\label{sec:6.4} \subsection{{The auxiliary “have”}}\label{sec:6.4.1} The \isi{verb} “have” is frequently used to denote \isi{perfect aspect} in the \isi{corpus} of Ship English under study, but just like “be”, it is prone to inflectional variation. The range of historical forms of this \isi{verb} available to Early Modern English speakers owes to various dialectal forms derived “largely to weakness and stresslessness of the word in many uses, both as a principal \isi{verb} and as an auxiliary” (\citealt{oed1989}, Vol 7: 15). However, the four most common to sailors were the two \isi{present tense} forms “has” and “have” and the \isi{past tense} form “had” that are still in use today, in addition to the obsolete form “hath” that was familiar to contemporary speakers. The oldest form “hath” (italicized) was used infrequently with a \isi{third person} subject (emphasized in bold) functioning as an \isi{auxiliary verb} in perfect constructions, e.g., “\textbf{it} \textit{hath} Blowed hard” [ADM 52/2/5], “\textbf{our} \textbf{Longboat} \textit{hath} made 3 Tunnes” [ADM 52/2/5], and “\textbf{The} \textbf{examinant} \textit{hath} not since seen him” [HCA 1/14/140]. The standard form “had” was more commonly used with all subjects, including \isi{third person singular} subjects, e.g., “\textbf{Bragg} \textit{had} broke two of his ribbs” [HCA 1/53/48], and “[\textbf{the} \textbf{quartermaster}] had Iron \& Beads stole away from him” [HCA 1/12/2], and “\textbf{he} \textit{had} got lame” [HCA 1/99/62]. The inflected form “has” was used with \isi{third person singular} and \isi{plural} subjects, e.g., “\textbf{he} \textit{has} at time Spoke to him” [HCA 1/99/142], “\textbf{this} \textbf{month} \textbf{last} \textbf{past} \textit{has} been such turbulent weather: the like has not been all this Winter” [CO 5/1411/654], and “\textbf{Our} \textbf{people} \textit{has} no mind to go to sea” [HCA 1/101/553].\footnote{The \isi{noun} “people” as \isi{plural} referent with a \isi{singular third person} \isi{verb} conjugation “has” reflects the arbitrary designation of \isi{count noun} and potentially reflects similar singular forms in other Romance languages, e.g., “la gente” in Spanish.} The non-standard use of this variant with \isi{third person} \isi{plural} subjects appears to have been a marked feature of sailors’ speech that was represented in the lyrics of sea-songs, e.g., “\textbf{Many} \textit{has} searched” (cited in \citealt{Palmer1986}: 54), and “\textit{Has} not \textbf{men} wished and cried” (cited in \citealt{Palmer1986}: 57).\largerpage The last variation, the \isi{uninflected} form “have”, was used most notably with \isi{third person singular} subjects that require the inflected form “has” in \isi{standard usage}, e.g., “the said \textbf{Frederik} \textbf{Philips} \textit{have} manumitted” [HCA 1/98/72].\footnote{Although the word “have” is here discussed as an \isi{uninflected} form, it is also possible that speakers/writers were using the \isi{third person} \isi{plural form} that takes the same form as the \isi{uninflected} \isi{verb} i.e., “have”. I acknowledge that the variation of this paradigm may therefore be considered as a singular/\isi{plural} \isi{inflectional paradigm} rather than a finite/infinite paradigm. My interpretation of the paradigm as a finite/infinite variation owes to the earlier work of Bailey \& Ross in which they describe \isi{present tense} marking and specifically describe “third singular forms are sometimes unmarked [i.e., \isi{uninflected}]” (1988: 199).} Yet, many examples of the non-\isi{standard usage} of “have” with \isi{third person} subjects derive from perfect-aspect \isi{verb} phrases using the \isi{participle} “been”, (emphasized) e.g., “\textbf{Wm} \textbf{Lilburne} \textit{have been} aiding [...] he have ordered us” [SP 42/6], “\textbf{the} \textbf{wind} \textit{have been} at SW” [ADM 52/2/1], “\textbf{This} \textbf{evidence} that \textit{have been} already produced” [CO 5/1411/33], and “\textbf{John} \textbf{Smith} who is and \textit{have been} as badd” [HCA 1/99 Barbados 1733]. The frequency of \isi{uninflected} “have” with the \isi{past participle} “been” in collocation suggests that this may have conditioned the variation regardless of the singular or \isi{plural} nature of the third-person subject. The perfect structures available to speakers of Ship English correlate with \isi{standard usage} but permit internal variation such as separation of the auxiliary and its associated \isi{verb phrase} and deletion or substitution of the auxiliary constituent. Sailors made use of different types of perfect structures permitted in \isi{standard usage}, for instance: \isi{perfect aspect} with \isi{indicative mood}, e.g., “if they \textit{had known} the sloop had been fitted out” [HCA 1/99 \isi{Bahama} Islands 1722]; \isi{perfect aspect} with conditional modality, e.g., “they \textit{would have kept} me” [445f.1/27]; \isi{perfect aspect} with \isi{progressive aspect}, e.g., “Wm Lilburne \textit{have been aiding”} [SP 42/6]; and \isi{perfect aspect} with negation, e.g., “they \textit{would not have come} on board" [HCA 1/99 \isi{Bahama} Islands 1722]. In perfect structures, Ship English permits the separation of the \isi{auxiliary verb} “have” and its associated \isi{participle} \isi{verb phrase} in contexts such as adverbial placement and negation, e.g., “after he \textit{had} \textbf{unfortunately} \textit{fell} into their hands” [HCA 1/99/38], and “he \textit{had} \textbf{never} \textit{done} it since he had belonged to them” [HCA 1/99/23].\footnote{Note that the separation of \isi{auxiliary verb} and its \isi{participle} \isi{verb phrase} was permitted in a range of Early Modern English dialects and continues to be acceptable in modern varieties including standard American English.} It also permits nominals to separate auxiliary verbs and their associated \isi{participle} \isi{verb} phrases, e.g., “We the mariners belonging to His Majesty’s Ship \textit{James Galley have} \textbf{many} \textbf{of} \textbf{us} \textit{been} desperately sick” (cited in \citealt{Brown2011}: 49). Another variation was the apparent omission of the \isi{auxiliary verb}, e.g., “John Hardin who [had] run away from a ship” [SP 42/6], “I thought you would [have] been as you promised me” [HCA 1/12/85], and “one of the people who [had] stole or run away with the boat" [HCA 1/99 \isi{Bahama} Islands 1722].\footnote{It may be that some examples do not have an underlying \isi{verb phrase} with \isi{perfect aspect} but instead are manifestations of the \isi{preterit} forms of verbs without \isi{past tense} inflection, e.g., the example “John Hardin who run away from a ship” [SP 42/6] might have an underlying perfect structure with a deleted auxiliary, i.e., “John Hardin who \textit{had run} away from a ship” or might be a \isi{preterit} \isi{verb} without inflection, i.e., “John Hardin who \textit{ran} away from a ship”. In many cases, the context permits both alternatives.} Ship English also appears to permit substitution of the \isi{auxiliary verb} phrase in passive structures, e.g., the use of auxiliary “be” in “after he \textit{was come} [had come] on board” [CO 5/1411/99] and “he \textit{was beine} [had been] at Martinco” [HCA 1/13/95];\footnote{See \sectref{sec:6.3.3} for more examples of “be” used as an auxiliary in \isi{verb} phrases with perfect \isi{aspectual meaning}.} So, although \isi{verb} phrases with \isi{perfect aspect} are used in syntactic constructions that are predominantly aligned with \isi{standard usage}, they also permit some internal variation that is not typical. One of the most marked features of variation in perfect \isi{verb} phrases is not the auxiliary itself, but what verbal particle it is permitted to select in a perfect structure. Standard English requires the auxiliary “have” to select a \isi{past participle} in \isi{verb} phrases with \isi{perfect aspect}, and this does sometimes occur in Ship English, e.g., “whether he had not \textit{returned}” [HCA 1/99/52], “We had \textit{been} gone from there aboutt two moones” [T/70/1213], “if they had \textit{known} the sloop” [HCA 1/99 \isi{Bahama} Islands 1722], “would have \textit{had} an anchor let goe” [HCA 1/9/155], and “had \textit{heard} it talked” [HCA 1/99/153]. However, much more common was the selection of a variant verbal form such as an irregular formation or an \isi{uninflected} form (marked for emphasis), e.g., “it hath \textit{Blowed} hard” [ADM 52/2/5], “they had \textit{arrive}” [HCA 1/53/66], “wee have sayled \& \textit{Logg} 116 miles” [HCA 51/3983/1], and “he had been misused and \textit{beat} and threatened to be shot” [HCA 1/99/97]. The last example includes the \isi{uninflected} form “beat” in coordination with the inflected weak verbs “misused” and “threatened” and potentially illustrates the common feature of \isi{preterit} verbal usage in \isi{perfect aspect} constructions. In other words, although the word “beat” may be an \isi{uninflected} form of the strong \isi{verb}, it is also the form of the \isi{preterit}, as in the \isi{standard usage} “he beat the \isi{prisoner}”, and this usage supports evidence that it was the \isi{preterit} forms of the verbs that were used in collocation with the auxiliary “have” in perfect structures and not a distinct \isi{past participle} form. This interpretation is complicated by the fact that the \isi{past participle} forms of weak (i.e., regular) verbs are the same as the \isi{preterit} form, e.g., “I have \textit{answered}” (\isi{perfect aspect}) and “I \textit{answered}’ (\isi{preterit}) in contrast to strong (i.e., irregular) verbs that usually have different \isi{preterit} forms, e.g., “I have written” (\isi{perfect aspect}) and “I wrote” (\isi{preterit}). Thus, the weak verbs appear to have standard \isi{past participle} forms as the \isi{preterit} is inflected with the morpheme “-ed” just as the \isi{past participle} is in \isi{standard usage}. However, the strong verbs appear to show marked variation (see \tabref{tab:key:6.2}), when in fact they may demonstrate the same \isi{inflectional paradigm} as the weak verbs. \begin{table} \caption{\label{tab:key:6.2} Sample of 11 verb phrases marked for perfect aspect that permit the preterit forms of strong verbs after the auxiliary “have”} \small \begin{tabularx}{\textwidth}{Qp{20mm}l} \lsptoprule \textbf{Ship English citation}\newline (with \isi{preterit} form marked for emphasis) & \textbf{Standard past participle} & \textbf{Source document}\\ \midrule wee have \textit{rid} her & ridden & ADM 52/2/1\\ he before had \textit{spoke} through me & spoken & 445f.1/35\\ this day we have \textit{took} out & taken & ADM 52/2/5\\{} [he] had Iron \& Beads \textit{stole} away from him & stolen & HCA 1/12/2\\ had never \textit{saw} a Prize taken & seen & HCA 1/99/8\\ those who had \textit{fell} into their Hands & fallen & HCA 1/99/51\\ Make him Lye in Irons till he had \textit{swore} & sworn & T 70/1/5\\ he had \textit{broke} open his chest & broken & HCA 1/99/7\\ when he had \textit{hid} himself & hidden & HCA 1/99/52\\ I had \textit{forgot} to write you & forgotten & AC WO 16–16/8–16\\ I have \textit{wrote} & written & 445f.1/46\\ \lspbottomrule \end{tabularx}\end{table} One interpretation of this inflectional variation is that Ship English permitted a \isi{preterit} verbal form of any strong or weak \isi{verb} after the auxiliary “have” in a construction marked for \isi{perfect aspect}, although this was not universal nor conditioned by any additional internal linguistic constraints. This interpretation is one that appears to have been favored by Bailey and Ross whose discussion of \isi{preterit} forms of strong verbs recognizes “the use of what are now strong preterits as past participles” (1988: 204). However, the data presented above may also be evidence of a collapsing and simplification of the \isi{preterit} and \isi{past participle} paradigm system rather than \isi{free variation} between \isi{preterit} and \isi{past participle} forms in perfect structures. Further evidence of this potential simplification of \isi{preterit} and \isi{past participle} forms occurs in the variant usage of verbal forms in passive structures with auxiliary “be”, e.g., “his head was \textit{broke}” [HCA 1/52/148], “2 new cables that were \textit{hid}” [HCA 1/99/41], “The Anchor and Cable…is \textit{took} up” [5/1411/645], and “he was \textit{beat} and forced among them” [HCA 1/99/54]. It may be that sailors used a simplified paradigm of verbal forms in which the \isi{preterit} and the \isi{past participle} (in both passive and perfect structures) were the same. This would certainly have made it easier for foreign language speakers to acquire correct Ship English syntax and may have been a salient feature of sailors’ speech in general during the early \isi{colonial period}, as suggested by the repeated use of such structures in seventeenth-century sea-songs, e.g., “Many persons of good account were \textit{took}” (“A Joyful New Ballad”, cited in \citealt{Palmer1986}: 17) and “[they] Were \textit{drove} out” (“Sailors for my Money”, cited in \citealt{Palmer1986}: 44). \subsection{{The auxiliary “do”}}\label{sec:6.4.2} The \isi{verb} “do” is frequently used as an \isi{auxiliary verb} in the \isi{corpus} of Ship English under study, but is not prone to significant inflectional variation. Although there were a range of inflections available in the Early Modern English period for the \isi{verb} “do” (see \citealt{oed1989}, Vol 4: 901), this \isi{corpus} suggests that sailors generally used “did” for the past and “do” for the \isi{present tense}, with a few infrequent cases of “does” occurring in \isi{late seventeenth century} and early \isi{eighteenth century} documents, e.g., “[he] \textit{do’s not know} what ship” [HCA 1/99/99, c. 1694] and “he answered that he \textit{does} not know” [HCA 1/13/94 1731]. The archaic form “doth” was similarly infrequent and more associated with court usage than sailors, for instance, one sailors’ testimony reads “David Czah who there \textsuperscript{did} and still \textsuperscript{doth} owns himselfe an Irishman” [HCA 1/53/3] in which the words “did” and “doth” are inserted superscript, potentially as corrections to the sailors’ spontaneous speech that was transcribed in haste and later revised for accuracy (see also footnote in this chapter for examples of “doth” used by court officials in negated statements). Although sailors did use this archaic inflection of the \isi{verb}, e.g. “\textit{Doth} believe Really they got their money by pyracy” [HCA 1/98/259], “the other seamen \textit{doth} believe that they were Likewise killed” [HCA 1/101/405], and “He \textit{Doth} suppose that these nine men may have some Riches on board” [HCA 1/98/29], the scarcity of examples of this form in the data suggest that the inflection “doth” was not common. Thus, although the \isi{verb} “do” appears often in the \isi{corpus}, it does not demonstrate the same frequency of inflectional variation as other auxiliaries such as “be” or the perfect auxiliary “have”. Verbs phrases using “do” are common in the \isi{corpus} of Ship English, but the \isi{verb} “do”, rather than functioning as a requisite constituent of negatives and questions (as in \isi{standard usage}), composes affirmative statements in the \isi{indicative mood}, which may or may not reflect \isi{standard usage} to mark emphasis. It is possible that statements may have included the grammatically redundant \isi{auxiliary verb} “do” as a marker of emphasis, particularly considering that much of the \isi{corpus} derives from witness depositions that were made in response to direct questions. For instance, the witness that stated, “he \textit{did} attend upon them” [HCA 1/98/267] may have been responding to the direct question “Did he attend upon them?”.\footnote{The majority of witness depositions are written in continuous prose and do not include the interrogative contributions of a second speaker, it is therefore extremely difficult to assess the validity of this suggestion although it is logical given the context of the \isi{court testimony} to assume that witnesses were asked questions.} However, other examples suggest that emphasis was not intended, such as the comments in logbook entries about daily events, e.g., “[we] have taken a strict and carefull survey, and \textit{doe} find that she wants calking inside and outside” [CO 5/1411/662], “The wind from the SSW to the SW \textit{did} blow” [ADM 52/2/3], and “six violent squails of wind and rain all which \textit{did} continue till this day noon” [ADM 52/2/3]. Letters also include this structure in a way that does not suggest \isi{emphatic} usage, e.g., “as many have and daily \textit{doe} find” [BL/Egerton 2395/0007], “the Royal Company \textit{do} expend yearly 20000l. Sterling” [BL/74/816/m/11/36/2], and “I \textit{doe} so consider” [HCA 1/101/527]. In addition to these contexts in which the \isi{verb} “do” serves as a redundant auxiliary marker of emphasis or \isi{indicative mood}, \isi{verb} phrases with auxiliary “do” (or “do support”) function in \isi{standard usage} to create negated \isi{preterit} structures from principle verbs that have no existing auxiliary in the \isi{indicative mood}; they also serve as auxiliary particles that can be moved to mark the interrogative mood. And both standard uses of the auxiliary “do” are evident in the \isi{corpus} (emphasized), e.g., for negation, “Both his pistolls mist [missed] fire and \textit{did} not go off” [HCA 1/52/137] and for interrogative mood, “where \textit{did} they take this shipp” [CO 5/1411/97]. However, most structures containing the \isi{auxiliary verb} “do” do not suggest \isi{emphatic} usage, nor do they mark negatives or questions, instead they are seemingly redundant auxiliaries of the \isi{indicative mood} expressed in the affirmative, e.g., “we \textit{doe} assure you” [ADM 106/288/30], “I \textit{doe} wonder” [HCA 1/98/57], “our ketch \textit{did} touch our stearn and \textit{did} us some damage” [ADM 52/2/3].\footnote{The first two examples: “we \textit{doe} assure you” [ADM 106/288/30], “I \textit{doe} wonder” [HCA 1/98/57] could be interpreted as \isi{emphatic} usage that may have been customary in formal speech. However, the last example “our ketch \textit{did} touch our stearn and \textit{did} us some damage” [ADM 52/2/3] does not appear to be \isi{emphatic} and neither do the excerpts from the sea shanties that follow these three examples.} Furthermore, this type of usage is marked in representations of sailors’ speech in a range of sea shanties and songs, e.g., “now mind what I \textit{do} say” (cited in \citealt{Hugill1969}: 51), “I \textit{did} dwell” (cited in \citealt{Palmer1986}: 4), “Their admiral \textit{did} want to be / Aboard” (cited in \citealt{Palmer1986}: 52), and “What the laws \textit{did} still forbid” (cited in \citealt{Palmer1986}: 75). In short, the scope and frequency of the \isi{auxiliary verb} “do” in depositions, logbooks, and personal statements without explicit \isi{emphatic} meaning suggests that the auxiliary was commonly used as a component of the \isi{indicative mood} regardless of negation, \isi{interrogative modality} or \isi{emphatic} meaning. Indeed, using a default \isi{auxiliary verb} for all \isi{verb} phrases would have arguably made Ship English easier to learn for new recruits for whom English was not native as it meant that if they mastered the \isi{verb} “do” in its \isi{present tense} and \isi{preterit} inflections they could use any other \isi{verb} in its \isi{uninflected} form in any simple indicative, negated, or interrogative structure. However, the use of an affirmative \isi{indicative verb} phrase with the auxiliary “do” often combines at the clause level with a singular principal \isi{verb} in \isi{preterit} form, suggesting that the use of the auxiliary marker was not a default but was used in complementary distribution to create contrast in meaning. To illustrate, the following excerpt includes two clauses, the first is expressed with a \isi{preterit} \isi{verb phrase} (in bold) and the second is expressed with a \isi{verb phrase} containing the auxiliary “do” (italicized): “wee \textbf{came} where wee \textit{did take in} the Soulders [soldiers]” [ADM 51/4322/1]. If the use of the auxiliary “do” were a default in constructions with affirmative \isi{indicative modality} then both \isi{verb} phrases in the sentence would take it, i.e., “wee \textit{did come} where wee \textit{did take in} the Soulders” and if the default were not to use the auxiliary in the \isi{indicative mood}, then neither clause would use it, i.e., “wee \textbf{came} where wee \textbf{took} \textbf{in} the Soulders”. Yet the conscious variation within the utterance appears to mark the clauses differently. It may be that the \isi{preterit} and the \isi{verb phrase} expressed with an auxiliary are marked for sequence or \isi{subordination} in the sense that “wee \textbf{came}” necessarily occurred first and “wee \textit{did take in} the Soulders” occurred after — and because of — the completed first event. Indeed, this type of subordinating or \isi{aspectual} interpretation of the complementary \isi{verb} forms appears to be supported by various examples which express a sequence of events, e.g., “he \textbf{was} Drunk when \textit{he did consent}” [HCA 1/99 \isi{Bahama} Islands 1722] in which the event of being drunk occurs before (and potentially causes) the event of consenting;\footnote{Past perfect constructions typically indicate the sequence of events in \isi{standard usage} by marking the \isi{verb} that occurred first (i.e., “drunk” would be the \isi{verb} marked by past perfect as it occurred first, creating the phrase “He had been drunk when he consented”.) Note that the excerpt “he was Drunk when \textit{he did consent}” marks the second of the two verbs (i.e., “consent”) and thus demonstrates contrast to \isi{standard usage} in sequential marking on the second event rather than the first event.} and “the wind\textbf{ [...] came} from Dover and \textbf{brought} ten tunns of Watter and \textit{did Returne} this day thither againe” [ADM 52/2/2] in which the event of the wind and water coming is completed before they return. The examples given above include \isi{verb} phrases that are written in the same sequence as they occur, but even when these \isi{verb} phrases appear in reverse order, the meaning still favors the \isi{completive aspect} of the \isi{preterit} \isi{verb} before the \isi{verb} with the “do” auxiliary happens, e.g., “And [I] \textit{did heare} that the captain \textbf{took} them” [HCA 1/13/97] in which the taking of prisoners occurs before the witness can hear about it; and “before they \textit{did do} it, he \textbf{had} \textbf{expressed} himself extremely glad” [HCA 1/99/20] in which the \isi{adverb} “before” makes it explicit that the expression of emotion occurs before the unspecified event was performed. It appears that in these contexts, regardless of the order of the clauses, the expression of the \isi{verb phrase} as either a principal \isi{verb} in \isi{preterit} form or a \isi{verb phrase} in \isi{past tense} with “do support” communicates subordinating and \isi{aspectual} information that may reinforce the listener’s interpretation of the sequence and causation of events.\footnote{This complex interpretation of how “do support” functions to mark \isi{aspectual} and/or subordinating meaning in affirmative clauses in the \isi{indicative mood} when used in conjunction with \isi{preterit} forms does not necessarily negate the conclusive statement of the previous paragraph, i.e., that “do support” may have been a universal in all affirmative \isi{verb} phrases to aid the process of acquisition for language learners. Instead, the use of “do” may change with any individual speaker’s fluency with the language; learners might have defaulted to a universal use of “do support” without \isi{aspectual} or subordinating meaning, and native/fluent speakers might have used the available structure to mark subtle distinctions in meaning between \isi{verb} phrases.} \subsection{{Modal auxiliaries}}\label{sec:6.4.3} While most of this chapter’s analysis is based on the indicative or unmarked modality of \isi{verb} phrases in Ship English,\footnote{The subjunctive and imperative moods are addressed briefly in \sectref{sec:6.3.1}.} this section is dedicated to auxiliaries used in the marked interrogative and conditional modalities. The interrogative mood is briefly addressed in \sectref{sec:6.4.2} regarding the auxiliary “do”, given that the standard method of forming interrogative modalities uses “do support”, as illustrated by the prosecutor who asked witness Joseph Wood, “\textit{Did} you heare the Pyrates talk of blowing ther shipp up?” [CO 5/1411/37] (marked for emphasis). However, it is important to recognize there were relatively few examples of sailors using the \isi{interrogative modality} in the documents composing the \isi{corpus}, and this is not surprising given that witness depositions, logbooks, and personal communications are predominantly informative in purpose and therefore disposed to \isi{indicative modality}. Yet, limited examples show that “do support” was used in interrogative contexts such as the tag question in the excerpt, “he took part of the drink \textit{did} he not?” [CO 5/1411/57] and samples of indirect speech in which a question was asked, e.g., “ask him where \textit{did} they take this shipp” [CO 5/1411/97]. Sailors’ use of “do support” in \isi{interrogative modality} is further supported by its occurrence in sea shanties, e.g., “When I passed a whole fortnight atween decks with you, / \textit{Did} I ere give a kiss, lad, to one of your \isi{crew}?” (voice of a female character in a \isi{shanty} attributed to John Gay 1685–1732, and cited in \citealt{Hugill1969}: 17). Thus, although not attested to in many examples, the use of “do support” to form questions was evidently one option available to sailors of the early \isi{colonial period}. Sailors employed a variety of structures to form questions and were not restricted to the use of the auxiliary “do” in \isi{interrogative modality}. One variation that did not require the use of the auxiliary “do” was to move the main \isi{verb} to a fronted position before the subject to create a verb-subject construction. Subject-\isi{verb} inversion is typical of \isi{standard usage} in Early Modern English, yet the distinguishing factor of sailors’ syntax is that the verbs undergoing movement are not auxiliaries but the principal inflected \isi{verb}, e.g., “how \textit{came} you to say you shot the shott that killed the master?” [CO 5/1411/43]. In other words, the interrogative construction “how came you” shows movement of the principal inflected \isi{verb} “to come” before the subject “you” rather than the insertion and movement of an \isi{auxiliary verb} as in the modern standard variation “how \textit{did} you come”. The same structure could potentially occur with any principal \isi{verb}, e.g., “what \textit{lack} you” [445f.1/31]. Yet, this type of construction notably occurs with the \isi{verb} “have”, e.g., “what colours \textit{had} the pyrates” [CO 5/1411/22] and “\textit{had} you any goods on board” [CO 5/1411/37], suggesting that it may have been conditioned by \isi{verb} choice, potentially because the \isi{verb} “have” can function as an auxiliary when used as part of a perfective \isi{verb phrase}, although it is not doing so in these examples.\footnote{The fronted \isi{verb} “have” still occurs in a limited set of phrases such as “Have you no shame/decency/compassion?” which appear to signal a dramatic challenge or critique of a person’s actions.} In these examples, the \isi{verb} “have” is used as a principal \isi{verb} meaning to own or possess and thus should therefore be subject to the same paradigm as the other principal verbs for which the “do” auxiliary is inserted and moved. However, the occurrence of the \isi{verb} “have”, immaterial of its function, appears to favor movement of the principal \isi{verb} rather than the insertion and movement of the auxiliary “do”. This potential \isi{linguistic conditioning} caused by the use of the \isi{verb} “have” is also suggested by how the structure is used in complementary distribution by court officials in Admiralty trails, for instance, the same prosecutor who asks “what number of English prisoners \textit{had} the pyrates shipp” [CO 5/1411/23] and “what office \textit{had} he” [CO 5/1411/29], showing movement of the \isi{verb} “have”, also asks “\textit{Did} you heare him say any thing” [CO 5/1411/29] and “\textit{did} you leap overboard” [CO 5/1411/30] showing insertion and movement of an \isi{auxiliary verb} when the principal \isi{verb} was not “have”. The movement of the \isi{verb} “have” (even when it functions as a principal \isi{verb}) may have been reinforced by systemic \isi{leveling} given that this syntax results in the same construction that is used with “be” in \isi{interrogative modality} (even when used as a principal \isi{verb}), e.g., “\textit{was} you on board the pyrate shipp” [CO 5/1411/28].\footnote{This question does not derive from a \isi{sailor} but a court prosecutor who addresses it multiple times to different witnesses in the trial of John Houghling, Corneluis Franc and Francois Delaune (Virginia, 13–17th May {1700}).} Thus, one hypothesis that might be tested with further research is that when forming questions, sailors defaulted to the movement of verbs before the subject if they were verbs that can function as auxiliaries, i.e., “do”, “have”, or “be”, regardless of whether they were used as auxiliaries or as principal verbs. The standard construction of the conditional mood is common in Ship English but permits verbal omission in ways that are not accepted in \isi{standard usage}. Ship English incorporates \isi{verb} phrases marked for modality in conditional sentences that express an event whose realization is dependent on another factor, just like \isi{standard usage}, e.g., “If he did see any one that offered any hurt or violence to Clarke he would make him suffer” [HCA 1/9/51] and “Terrors of Death (which they said they were sure would be their Position should they refuse)” [HCA 1/99/8]. Most examples of conditional mood occur in the context of a simple modal auxiliary (italicized) and a base \isi{verb} (bold), e.g., “they \textit{would} \textbf{pistoll} him” [HCA 1/101/406], “lest the prisoners \textit{should} \textbf{force} him away” [HCA 1/99 \isi{Williamsburg}, Aug 14 1729], and “he \textit{may} \textbf{be} att Liberty” [HCA 1/14/28]. Although some examples suggest that either the modal auxiliary or the main \isi{verb} could be omitted in contexts where meaning was apparent, e.g., “in case of resistance he [\textit{would}] \textbf{compell} him by force so to doe” [CO 5/1411/663], “he \textbf{had} [\textit{would} \textbf{have}] done it if there had been Powder enough” [HCA 1/99/157], “whether he \textit{would} [\textbf{go}] to sea” [CO 5/1411/639], and “The Governor bidding them [...] they \textit{would} [\textbf{go}] away from thence” [HCA 1/9/18]. Interestingly, various examples of omitted main verbs in conditional structures suggest movement, such as the omission, assumed to be the \isi{verb} “to go” in the previous examples. The following examples are also assumed to omit verbs synonymous with travel that could also be expressed using the \isi{verb} “to go” (emphasized in bold), e.g., “you \textit{must} [\textbf{head/go}] away 50 Leagues \& then you are clear of the sands” [HCA 1/99/22], “Declared that he \textit{would} [\textbf{sail/go}] for the North of Cuba” [HCA 1/9/6], and “most of them \textit{would} [\textbf{disembark/go}] about noon” [ADM 52/1/7]. In sum, most \isi{verb} phrases with conditional modality are constructions comparable to \isi{standard usage} with a single auxiliary and a single main \isi{verb}, yet either constituent could be omitted, particularly if the main \isi{verb} expressed movement or travel in a manner synonymous with the \isi{verb} “to go”. There is little evidence in the \isi{corpus} to indicate that sailors used expanded modal constructions with either perfect or \isi{progressive aspect}. Most conditional structures were simple with one modal auxiliary (italicized) and a base \isi{verb} (in bold), e.g., “we \textit{could} \textbf{doe} little good of it” [ADM 52/1/8] and “he \textit{might} \textbf{prosecute} him” [HCA 1/52/46]. Rare examples of \isi{verb} phrases with more than one verbal component after the modal auxiliary include “two or three Passengers…\textit{might} \textbf{be} \textbf{heard} to justifie his being forced” [HCA 1/99/85], and “the Purser said he \textit{must} \textbf{\textit{needs}} \textbf{goe} a shore himsefle” [ADM 52/1/8]. Yet neither of these examples suggest an expanded \isi{verb phrase}; the first example, “might be heard”, is explained by its passive status and the second, “must needs goe”, is explained by the idiomatic use of the expression “must needs” (surviving today in the form of “needs must”) with the word “needs” appearing to form part of the modal auxiliary stem. None of the documentary evidence in the \isi{corpus} indicates that sailors used expanded modal constructions such as perfect conditionals (“I should have gone”) progressive conditionals (“I should be going”), or perfect-progressive conditionals (“I should have been going”). However, certain examples of conditional verbal phrases indicate an underlying assumption of \isi{aspectual meaning} that would suppose a perfect conditional structure, e.g., “any Irregularities he \textit{might} \textbf{commit}, was the Drink that he was a forced man” [HCA 1/99/40]. This example refers to a completed period when the accused was on board an alleged \isi{pirate} vessel and he wishes to express repentance for any “irregularities” (i.e., crimes) he might have committed in a way that does not incriminate him. However, the perfect conditional “might have committed” is not used, instead the conditional phrase used is “might commit” which suggests that he is talking about potential future events rather than events that are completed. Another example of conditional modality expressed as a simple construction (i.e., auxiliary modal + main \isi{verb}) yet with completed \isi{aspectual meaning} in the context of its utterance, is “Harry Gatsby believes he \textit{might} \textbf{be} \textbf{forced} at first but since had done as others” [HCA 1/99/93]. This example marks \isi{completive aspect} with the adverbs “at first” and “since” but does not express the conditional verbal phrase with \isi{perfect aspect} “might have been forced”, instead the construction “might be forced” suggests that the event is extant as opposed to its assumed completive meaning. Other examples show that sailors attempted to express conditional modality and \isi{completive aspect} in other ways (italicized), e.g., “threatened him in So much that he \textit{had like to have incurid} [would have likely incurred] Some severe punishement about it” [HCA 1/99/93]. The fact that sailors used alternative methods to mark completive conditional modality may suggest that they avoided multiple auxiliaries in \isi{verb} phrases or may suggest more specifically that the perfect auxiliary “have” was not permitted in coordination with conditional auxiliaries. As a result, most \isi{verb} phrases with conditional modality are basic constructions with a single auxiliary and a single main \isi{verb} despite evidence that attests to intended \isi{aspectual meaning}. Negation in conditional modality predominantly aligns with the general trends discussed in \sectref{sec:6.1}, and specifically the section dealing with negation, \sectref{sec:6.1.3}. The most common negative marker was the word “not” inserted after the conditional \isi{auxiliary verb}, e.g., “our Ship but \textit{could not} gett her keel out” [ADM 52/1/8], “the captain \textit{would not} wrong me” [CO 5/1411/638], and “what the event is I \textit{cannot} tell” [ADM 52/1/8]. Other negative markers include negation with “no”, that was typically placed in a \isi{noun phrase} constituent or an \isi{adverbial phrase} (in bold for emphasis) e.g., “I \textit{could} get him \textbf{no} \textbf{way} to adhere to me” [445f.1/36], “we \textit{culd} see her \textbf{no} \textbf{longer}" [DDB6 8/4], “But \textit{could} get \textbf{no} \textbf{more}” [ADM 51/3954], “the Pyrates \textit{would} accept of \textbf{no} \textbf{Foreigners}” [HCA 1/99/20], and “[I] \textit{could} see \textbf{no} \textbf{sign} of the boat" [HCA 1/99 \isi{Bahama} Islands 1722]. Less frequent markers of conditional negation include “never” used pre-verbally, e.g., “he \textbf{never} \textit{wou’d} go even in his Turn” [HCA 1/99/156] and \isi{negative concord} using the conjunction “nor”, e.g., “The Captain said, I \textit{can}\textbf{not} sell the King’s Victuals. I answered, \textbf{Nor} I \textit{can}\textbf{not} do the King’s Work”. [445f.1/29], “he \textit{would} do him \textbf{no} \textbf{hurt} and \textbf{nor} the money in his pocket \textit{should} be touched” [HCA 1/99/8], and “Capt Rigby doe \textbf{not} \textbf{nor} \textit{shall} carry off this land any Persons” [HCA 1/9/7]. Overall, negation in \isi{verb} phrases marked for conditional modality did not always align with \isi{standard usage}, but is comparable to trends identified for \isi{indicative verb} phrases. \section{{Summary}}\label{sec:6.5} Sailors’ preferences for nominalization are evidenced by a tendency to use non-specific verbs which permit the expression of the main event of the sentence in \isi{nominal form} in the \isi{direct object position}. Common constructions using “make” suggest an event (expressed nominally as the \isi{direct object}) that is brought into being or caused to happen, and \isi{idiomatic usage} of the \isi{verb} “make” with travel and transit permits prepositional complements. Phrasal verbs show a tendency to be expressed as fixed expressions in the \isi{corpus} and resist the insertion of an \isi{object noun} phrase or \isi{pronoun} between the main \isi{verb} and the \isi{satellite particle}. Examples of negation in the \isi{corpus} demonstrate significant variation, but the most common negative construction is the use of the negative particle “not” after a \isi{finite verb} regardless of whether it is an auxiliary or base \isi{indicative verb} without any auxiliary support. The second most common \isi{negation marker} in the sample is the word “never” which is sometimes used to mark distinct categorical denial over time (as in standard \isi{modern usage}), but is more commonly contextualized with specific durations of time or to negate indicative \isi{past tense} situations with no \isi{aspectual meaning}. Other common negation markers include the particle “no” after a non-\isi{finite verb} and the conjunction “nor”, both of which often compose or join clauses that already have negation. The resultant \isi{negative concord} is a salient feature of the \isi{corpus}. Inflectional variation in \isi{verb} forms expressed in \isi{indicative modality} — specifically zero inflection with \isi{singular third person} subjects — is potentially conditioned by using certain verbs such as “know”, by negation and \isi{third person} pronominal subjects, and/or by observance of the Northern Subject Rule. The use of \isi{present tense} in past narrative contexts may have reflected sailors’ performance culture, but variation in \isi{past tense marking} appears to be the result of \isi{free variation} given the range of forms occurring in the same linguistic contexts, in the same documents, and in the same handwriting across a range of registers and modalities. Preterit forms of weak verbs could be either inflected according to the regular “-ed” paradigm or left in an \isi{uninflected} form, but \isi{preterit} forms of strong verbs might be expressed as past participles, variant \isi{preterit} forms, twice-marked irregular stems with regular inflection, or \isi{uninflected} verbs. Certain verbs such as “see” and “run” appear to select a preference for zero marking and phrasal verbs with a range of satellite particles appear to permit zero marking in the \isi{preterit} form of the associated \isi{verb}. Variant forms of infinitives occur after present and past participles and after auxiliary verbs with conditional modality but are omitted in contexts of transparent meaning, and there is also some evidence to suggest that the base form of a \isi{verb} and its \isi{infinitive} may have been interchangeable. The scope of variation permitted in form and usage of the \isi{verb} “be” marks it as one of the most divergent features of Ship English. In terms of inflection, “was” occurs as the most frequent \isi{past tense} form of the verb with all nominal and pronominal subjects in first, second, and \isi{third person}, although compound third-person \isi{noun} phrases and \isi{plural} first-person pronouns were the most salient contexts that selected this non-standard \isi{past tense} form. Present \isi{tense} and infinite forms of the \isi{verb} “be” show similar variation, with “is” occurring as the most frequently used present-\isi{tense} form alongside \isi{free variation} with non-finite variants such as the \isi{uninflected} form and the \isi{present participle}. In terms of usage, the \isi{copula} does not commonly occur as the principal \isi{verb} of a clause, but “be” occurs frequently in the \isi{corpus} as a requisite of passive structures. Variation in these passive structures supports the general tendency for \isi{leveling} of the \isi{inflectional paradigm} but also indicates that “be” omission was acceptable, and this type of omission is mirrored in contexts when it is used as an auxiliary in structures marked for \isi{progressive aspect}. In these progressive structures, auxiliary “be” commonly selects a \isi{stative} \isi{present participle} rather than the standard default of an active \isi{present participle}. There is also evidence to suggest that the auxiliary “be” could mark \isi{perfect aspect} in addition to \isi{progressive aspect}. The \isi{auxiliary verb} “have” is prone to inflectional variation such as the non-standard use of “has” with \isi{third person} \isi{plural} subjects, and \isi{uninflected} “have” in conjunction with the \isi{past participle} “been” regardless of the subject, and this may have been an indicator of a collapsed \isi{inflectional paradigm}. Examples of \isi{verb} phrases marked for \isi{perfect aspect} also permit separation of the auxiliary and its associated \isi{verb phrase}, and deletion or substitution of the auxiliary constituent. However, the most salient variation in perfect \isi{verb} phrases is not the auxiliary itself, but the fact that it often selects a \isi{preterit} verbal particle or a form resulting from a leveled paradigm of the \isi{preterit} and \isi{past participle} forms. The auxiliary “do” is not prone to significant inflectional variation but is used in affirmative statements of the \isi{indicative mood} in ways that mirror its insertion in negative and \isi{interrogative modality}. Although this might suggest emphasis, repeated usage in contexts without explicit \isi{emphatic} meaning suggests that sailors commonly used the auxiliary as a component of the \isi{indicative mood}. Although this may attest to systemic \isi{leveling} that aided language learners, evidence also suggests that fluent speakers used the auxiliary “do” in juxtaposition to \isi{preterit} verbs to communicate subordinating and \isi{aspectual} information. In addition to the standard use of “do support” to form questions, Ship English also permits the movement of the main \isi{verb} to a fronted position before the subject to create a verb-subject construction common to \isi{standard usage}. However, the verbs undergoing movement in Ship English are not auxiliaries but the principal inflected \isi{verb}, and this type of construction is specifically notable with principal verbs that can also function as auxiliaries. Most \isi{verb} phrases with conditional modality are constructions with a single auxiliary and a single \isi{verb} form, yet either the auxiliary or the principal \isi{verb} could be omitted, particularly if the principal \isi{verb} expressed movement or travel in a manner synonymous with the \isi{verb} “to go”. There is little evidence in the \isi{corpus} to indicate that sailors used expanded modal constructions with either perfect or \isi{progressive aspect}, and as such, the conditional mood had a limited scope of usage in Ship English. Finally, negation in \isi{verb} phrases marked for conditional modality showed variation that was not common to \isi{standard usage} but is comparable to trends identified for \isi{indicative verb} phrases.
#--------- #Title #--------- #Respiratory control and thermal sensibility in benthic #life stages of porcelain crab (Petrolisthes laevigatus). #----------------------------------------------- #Cleaning working space rm(list=ls()) #Creator: 20160817 FPL #Modifications: 20170408 CG today<-format(Sys.Date(),"%Y%m%d") #-------------------------------------------- #From Linux # get working directory # setwd("~/Insync/Laboratorio.Poblaciones.Marinas/Publicaciones/Plasticidad pela/analisis/datos") #From Windows # setwd("D:/[email protected]/Laboratorio.Poblaciones.Marinas/Publicaciones/Plasticidad pela/analisis/datos") setwd("C:/Users/Invunche/Dropbox/Radboud University/publicaciones/Publicadas/3. Leiva et al Mar Biol 2018/data") getwd() #verifico directorio #----------------------------------------------- #Libraries #----------------------------------------------- library(nlme);library(car);library(multcomp) #----------------------------------------------- #reading my data #------------------------------------------------ pela<-read.csv("data.pela.csv", header=TRUE, sep=",",dec=".", strip.white=TRUE) names(pela) summary(pela) str(pela) #------------------------------------------------ #--------------------------------------------------------------------------- #Units for each explicative variable #--------------------------------------------------------------------------- #dry_weight_g: individual dry weight,expressed in grams #mo2: metabolic rate, expressed as mg O2 por hour per individual #mo2.1: metabolic rate, expressed as mg O2 per hour per gram dry weight #mo2.2: metabolic rate, expressed as mmol O2 per hour per gram dry weight #mo2.3: metabolic rate, expressed as umol O2 per hour per gram dry weight #mo2.4: metabolic rate, expressed as umol O2 por hour per individual #-------------------------------------------------------- #Transformation of variables wrongly assigned to numeric #-------------------------------------------------------- pela$stage=as.factor(pela$stage) pela$oxygen_mg=as.numeric(pela$oxygen_mg) pela$saturation=as.numeric(pela$saturation) pela$mo2=as.numeric(pela$mo2) pela$kpa<-as.numeric(pela$kpa) pela$temperature=as.factor(pela$temperature) ########################################### #EXPORTO MEDIAS PARA METAZOA grouped <- group_by(pela,stage,kpa.mean,temperature) datos.mean<-summarise(grouped, mean=mean(mo2.4), sd=sd(mo2.4)) round_df <- function(datos.mean, digits) { nums <- vapply(datos.mean, is.numeric, FUN.VALUE = logical(1)) datos.mean[,nums] <- round(datos.mean[,nums], digits = digits) (datos.mean) } datos.met<-round_df(datos.mean, digits=6) data.pela.metazoa<-merge(datos.mass,datos.met,by=c("stage","kpa.mean","temperature")) data.pela.metazoa<-rename(data.pela.metazoa,dry_mass_mean=mean.x) data.pela.metazoa<-rename(data.pela.metazoa,dry_mass_sd=sd.x) data.pela.metazoa<-rename(data.pela.metazoa,resp_mean=mean.y) data.pela.metazoa<-rename(data.pela.metazoa,resp_sd=sd.y) #write.csv(data.pela.metazoa,"6090 Supplementary data of respiration.csv",row.names = FALSE) ########################################### #------------------------------------------------------------- #Scaling of Metabolic rates #-------------------------------------------------------- # subset by stage #-------------------------------------------------------- datos<-pela unique(pela$stage) embrio<-subset(datos,datos$stage=="Embryo") adult<-subset(datos,datos$stage=="Adult") juvenil<-subset(datos,datos$stage=="Juvenile") megalopa<-subset(datos,datos$stage=="Megalopae") Embryo01<-c(1:588) Embryo01[which(pela$stage!="Embryo")]<-0 #without embryos Embryo01[which(pela$stage=="Embryo")]<-1 #with embryos pela<-cbind(pela,Embryo01) pela$Embryo01<- as.factor(pela$Embryo01) # sapply(datos,class) #--------------------------------------------------- #Testing different models #--------------------------------------------------- stag1<-lm(log10(mo2.4)~log10(dry_weight_g),data=pela) # summary(stag1) AIC(stag1) anova(stag1) stag2<-lm(log10(mo2.4)~log10(dry_weight_g)*as.numeric(temperature),data=pela) summary(stag2) AIC(stag2) anova(stag2) stag3<-lm(log10(mo2.4)~log10(dry_weight_g)*kpa.mean,data=pela) summary(stag3) AIC(stag3) anova(stag3) stag4<-lm(log10(mo2.4)~log10(dry_weight_g)*kpa.mean+as.numeric(temperature),data=pela) summary(stag4) anova(stag4) AIC(stag4) # Ajusto mejor modelo stag4, ahora considerando huevos como una grupo separado a las otras etapas eggs<-lm(log10(mo2.4)~log10(dry_weight_g)*kpa.mean+as.numeric(temperature)+Embryo01,data=pela) summary(eggs) anova(eggs) AIC(eggs) eggs1<-lm(log10(mo2.4)~log10(dry_weight_g)*as.factor(kpa.mean)+as.numeric(temperature)+Embryo01,data=pela) summary(eggs1) anova(eggs1) AIC(eggs1) AIC(stag4)-AIC(eggs1) # diferencia # coeficientes y anova summary(eggs) Anova(eggs) # exploratory graphics plot(log10(mo2.4)~log10(dry_weight_g), data=pela) # pendiente stag4: todas las etapas como un solo grupo abline(stag4$coefficients[1]+stag4$coefficients[3]*mean(pela$kpa)+stag4$coefficients[4]*mean(as.numeric(pela$temperature)) +stag4$coefficients[5]*mean(pela$kpa)*mean(as.numeric(pela$temperature)),stag4$coefficients[2]) # pendiente eggs: huevos como un grupo diferente de las otras tres etapas abline(eggs$coefficients[1]+eggs$coefficients[3]*mean(pela$kpa)+eggs$coefficients[4]*mean(as.numeric(pela$temperature)) +eggs$coefficients[6]*mean(pela$kpa)*mean(as.numeric(pela$temperature)),eggs$coefficients[2], col="gray") #--------------------------------------------------- #plots + predict setwd("D:/Dropbox/FL+WB/PELA/manuscript") #setwd("~/Insync/Laboratorio.Poblaciones.Marinas/Publicaciones/Plasticidad pela/analisis/Submission") #setwd("D:/[email protected]/Laboratorio.Poblaciones.Marinas/Publicaciones/Plasticidad pela/analisis/datos") {png(filename="1.1. Figure 2.png",width=8,height=4,units="in",res=600) par(mfrow=c(1,2), tcl=-0.3, family="Arial", oma=c(2,2,0,0)) par(mai=c(0.4,0.5,0.2,0.2)) # PLOT 1 plot(log10(mo2.4)~log10(dry_weight_g),cex=0.8,xlim=c(-5,1),ylim=c(-5,1),ylab="", xlab="", yaxs="i",xaxs="i",col="white",las=1,frame.plot=FALSE,data=pela) points(log10(mo2.4)~log10(dry_weight_g), data =subset(pela,!stage=="Embryo"), col="black",cex=0.8) points(log10(mo2.4)~log10(dry_weight_g), data =subset(pela,stage=="Embryo"), col="gray50",cex=0.8) #display embryo data in grey # modelo todas las etapas= 1 solo grupo clip(x1=-4.5,x2=0.9,y1=-4.5,y2=0.9) # limite para abline abline(stag4$coefficients[1]+stag4$coefficients[3]*mean(pela$kpa)+stag4$coefficients[4]*mean(as.numeric(pela$temperature)) +stag4$coefficients[5]*mean(pela$kpa)*mean(as.numeric(pela$temperature)),stag4$coefficients[2], lwd=2,col="gray50") # modelo que considera huevos separado de las otras tres etapas clip(x1=-3.5,x2=0.9,y1=-3,y2=0.95) # clip(x1=-4.5,x2=0.9,y1=-4.5,y2=0.9) # limite para abline abline(eggs$coefficients[1]+eggs$coefficients[3]*mean(pela$kpa.mean)+eggs$coefficients[4]*mean(as.numeric(pela$temperature)) +eggs$coefficients[6]*mean(pela$kpa.mean)*mean(as.numeric(pela$temperature)),eggs$coefficients[2], lwd=2) # axis labels mtext(expression(paste(Log[10]," metabolic rate")),side=2,cex=1, outer = T) mtext(expression(paste(Log[10]," body mass")),side=1, cex=1, outer=T) # labels slope whit egg text(-1.5,-3.6,paste("slope =",round(stag4$coefficients[2],2), "?", round(summary(stag4)$coefficients[2,2],2) ," eggs"),cex = 0.8, col="gray50") #Mass exponent=1.05 + 0.016 # # labels slope whithout eggs text(-1.33,-4,paste("slope =",round(eggs$coefficients[2],2), "?", round(summary(eggs)$coefficients[2,2],2)," no eggs"),cex = 0.8, col="black") #Mass exponent=0.92 text(-4.5,0.8,"A)",font = 2) #--------------------------------------------------------------------------------------------- # PLOT 2 # Ajusto Modelos por cada nivel de kpa y a temperatura constante=12°C #--------------------------------------------------------------------------------------------- #x<-seq(from = min(log10(pela$dry_weight_g)), to = max(log10(pela$dry_weight_g)), length.out = 1000) # Plot 2 plot(log10(mo2.4)~log10(dry_weight_g),cex=0.8,xlim=c(-5,1),ylim=c(-5,1),yaxs="i",xaxs="i",col="white", xlab="", ylab="",las=1, frame.plot=FALSE,data=pela) points(log10(mo2.4)~log10(dry_weight_g), data =subset(pela,!stage=="Embryo"), col="black",cex=0.8) points(log10(mo2.4)~log10(dry_weight_g), data =subset(pela,stage=="Embryo"), col="gray50",cex=0.8) #display embryo data in grey clip(x1=-3.5,x2=0.9,y1=-3,y2=0.95) # limite para abline # kpa= 21 df21<-subset(pela,temperature==12 & kpa==21.21) lmdf21<-lm(log10(mo2.4)~log10(dry_weight_g)+Embryo01,data=df21) abline(lmdf21$coefficients[1]+lmdf21$coefficients[3]*0,lmdf21$coefficients[2]) # if Embryo=0, without eggs summary(lmdf21)$coeff # kpa= 14 df14<-subset(pela,temperature==12 & kpa==14.14) lmdf14<-lm(log10(mo2.4)~log10(dry_weight_g)+Embryo01,data=df14) abline(lmdf14$coefficients[1]+lmdf14$coefficients[3]*0,lmdf14$coefficients[2], lty=5) # # if Embryo=0, without eggs summary(lmdf14)$coeff # kpa= 9 df9<-subset(pela,temperature==12 & kpa==9.43) lmdf9<-lm(log10(mo2.4)~log10(dry_weight_g)+Embryo01,data=df9)# if Embryo=0, without eggs abline(lmdf9$coefficients[1]+lmdf9$coefficients[3]*0,lmdf9$coefficients[2], lty=2) summary(lmdf9)$coeff # kpa= 5 df5<-subset(pela,temperature==12 & kpa==4.71) lmdf5<-lm(log10(mo2.4)~log10(dry_weight_g)+Embryo01,data=df5)#without embryos abline(lmdf5$coefficients[1]+lmdf5$coefficients[3]*0,lmdf5$coefficients[2], lty=4) summary(lmdf5)$coeff # kpa= 2 df2<-subset(pela,temperature==12 & kpa==2.36) lmdf2<-lm(log10(mo2.4)~log10(dry_weight_g)+Embryo01,data=df2)#without embryos abline(lmdf2$coefficients[1]+lmdf2$coefficients[1]*0,lmdf2$coefficients[2], lty=3) summary(lmdf2)$coeff # labels slope models without embryos clip(x1=-5,x2=0.9,y1=-5,y2=0.95) # limite para abline text(-1,-3,paste("slope 21 kPa =",round(lmdf21$coefficients[2],2), "?", round(summary(lmdf21)$coefficients[2,2],2)),cex = 0.8, col="black") lines(x=c(-3.1,-2.7), y=c(-3,-3)) text(-1,-3.25,paste("slope 14 kPa =",round(lmdf14$coefficients[2],2), "?", round(summary(lmdf14)$coefficients[2,2],2)),cex = 0.8, col="black") lines(x=c(-3.1,-2.7), y=c(-3.25,-3.25),lty=5) text(-1,-3.5,paste("slope"," ","9 kPa =",round(lmdf9$coefficients[2],2), "?", round(summary(lmdf9)$coefficients[2,2],2)),cex = 0.8, col="black") lines(x=c(-3.1,-2.7), y=c(-3.5,-3.5),lty=2) text(-1,-3.75,paste("slope"," " ,"5 kPa =",round(lmdf5$coefficients[2],2), "?", round(summary(lmdf5)$coefficients[2,2],2)),cex = 0.8, col="black") lines(x=c(-3.1,-2.7), y=c(-3.75,-3.75),lty=4) text(-1,-4,paste("slope", " ","2 kPa =",round(lmdf2$coefficients[2],2), "?", round(summary(lmdf2)$coefficients[2,2],2)),cex = 0.8, col="black") lines(x=c(-3.1,-2.7), y=c(-4,-4),lty=3) text(-4.5,0.8,"B)",font = 2) } dev.off() #Figure S2 Supplementary information temp6.s<-lm(log10(mo2.4)~log10(dry_weight_g)*kpa+Embryo01,data=subset(pela, temperature==6)) temp12.s<-lm(log10(mo2.4)~log10(dry_weight_g)*kpa+Embryo01,data=subset(pela, temperature==12)) temp18.s<-lm(log10(mo2.4)~log10(dry_weight_g)*kpa+Embryo01,data=subset(pela, temperature==18)) { png(filename="Figure S2.png",width=6,height=6,units="in",res=600) par(mfrow=c(1,1), tcl=-0.3, family="Arial", oma=c(0,0,0,0)) plot(log10(mo2.4)~log10(dry_weight_g),cex=0.8,xlim=c(-5,1),ylim=c(-5,1),ylab="", xlab="", yaxs="i",xaxs="i",col="white",las=1,frame.plot=FALSE,data=pela) points(log10(mo2.4)~log10(dry_weight_g), data=subset(pela, !stage=="Embryo"), col="black",cex=0.8) points(log10(mo2.4)~log10(dry_weight_g), data=subset(pela, stage=="Embryo"), col="gray50",cex=0.8) mtext(expression(paste(Log[10]," metabolic rate")),side=2, line=2, outer=F) mtext(expression(paste(Log[10]," body mass")),side=1, cex=1, outer=F, line=3) # Without eggs at 6?C clip(x1=-3.5,x2=0.9,y1=-4.5,y2=0.9) # limite para abline abline(temp6.s$coefficients[1]+temp6.s$coefficients[3]*mean(pela$kpa)+temp6.s$coefficients[5]*mean(log10(pela$dry_weight_g))*mean(pela$kpa), temp6.s$coefficients[2], lty=1,col="black") text(-1.0,-3.5,paste("slope 6°C =",round(temp6.s$coefficients[2],2), "±", round(summary(temp6.s)$coefficients[2,2],2)),cex = 0.9, col="black") lines(x=c(-2.3,-2.6), y=c(-3.5,-3.5),lty=1, col="black") # Without eggs at 12?C clip(x1=-3.5,x2=0.9,y1=-4.5,y2=0.9) # limite para abline abline(temp12.s$coefficients[1]+temp12.s$coefficients[3]*mean(pela$kpa)+temp12.s$coefficients[5]*mean(log10(pela$dry_weight_g))*mean(pela$kpa), temp12.s$coefficients[2], lty=2,col="black") text(-1.0,-3.75,paste("slope 12°C =",round(temp12.s$coefficients[2],2), "±", round(summary(temp12.s)$coefficients[2,2],2)),cex = 0.9, col="black") lines(x=c(-2.3,-2.6), y=c(-3.75,-3.75),lty=2, col="black") # Without eggs at 18?C clip(x1=-3.5,x2=0.9,y1=-4.5,y2=0.9) # limite para abline abline(temp18.s$coefficients[1]+temp18.s$coefficients[3]*mean(pela$kpa)+temp18.s$coefficients[5]*mean(log10(pela$dry_weight_g))*mean(pela$kpa), temp18.s$coefficients[2], lty=3,col="black") text(-1.0,-4,paste("slope 18°C =",round(temp18.s$coefficients[2],2), "±", round(summary(temp18.s)$coefficients[2,2],2)),cex = 0.9, col="black") lines(x=c(-2.3,-2.6), y=c(-4,-4),lty=3, col="black") } dev.off() # #Figure S2 Supplementary information # # temp6<-lm(log10(mo2.4)~log10(dry_weight_g)*kpa,data=subset(pela, temperature==6)) # temp6.s<-lm(log10(mo2.4)~log10(dry_weight_g)*kpa+Embryo01,data=subset(pela, temperature==6)) # temp12<-lm(log10(mo2.4)~log10(dry_weight_g)*kpa,data=subset(pela, temperature==12)) # temp12.s<-lm(log10(mo2.4)~log10(dry_weight_g)*kpa+Embryo01,data=subset(pela, temperature==12)) # temp18<-lm(log10(mo2.4)~log10(dry_weight_g)*kpa,data=subset(pela, temperature==18)) # temp18.s<-lm(log10(mo2.4)~log10(dry_weight_g)*kpa+Embryo01,data=subset(pela, temperature==18)) # # #png(filename="D:/Dropbox/FL+WB/PELA/manuscript/submission/ 1.1. Figure S2 Scaling of metabolic rate by tempeature.png",width=6,height=6,units="in",res=600) # plot(log10(mo2.4)~log10(dry_weight_g),cex=0.8,xlim=c(-5,1),ylim=c(-5,1),ylab="", xlab="", # yaxs="i",xaxs="i",col="white",las=1,frame.plot=FALSE,data=pela) # points(log10(mo2.4)~log10(dry_weight_g), data=subset(pela, !stage=="Embryo"), col="black",cex=0.8) # points(log10(mo2.4)~log10(dry_weight_g), data=subset(pela, stage=="Embryo"), col="gray50",cex=0.8) # mtext(expression(paste(Log[10]," metabolic rate")),side=2, line=2, outer=F) # mtext(expression(paste(Log[10]," body mass")),side=1, cex=1, outer=F, line=3) # # # Fit for all life stages at 6?C # clip(x1=-4.5,x2=0.9,y1=-4.5,y2=0.9) # limite para abline # abline(temp6$coefficients[1]+temp6$coefficients[3]*mean(pela$kpa)+temp6$coefficients[4]*mean(log10(pela$dry_weight_g))*mean(pela$kpa), # temp6$coefficients[2], lty=1,col="gray50") # # # Fit for all life stages at 12?C # clip(x1=-4.5,x2=0.9,y1=-4.5,y2=0.9) # limite para abline # abline(temp12$coefficients[1]+temp12$coefficients[3]*mean(pela$kpa)+temp12$coefficients[4]*mean(log10(pela$dry_weight_g))*mean(pela$kpa), # temp12$coefficients[2], lty=3,col="gray50") # # # Fit for all life stages at 18?C # clip(x1=-4.5,x2=0.9,y1=-4.5,y2=0.9) # limite para abline # abline(temp18$coefficients[1]+temp18$coefficients[3]*mean(pela$kpa)+temp18$coefficients[4]*mean(log10(pela$dry_weight_g))*mean(pela$kpa), # temp18$coefficients[2], lty=4,col="gray50") # # text(-0.81,-3,paste("slope 6?C =",round(temp6$coefficients[2],2), "?", # round(summary(temp6)$coefficients[2,2],2)), col="gray50") # lines(x=c(-2,-2.3), y=c(-3,-3),lty=1, col="gray50") # text(-0.79,-3.5,paste("slope 12?C =",round(temp12$coefficients[2],2), "?", # round(summary(temp12)$coefficients[2,2],2)), col="gray50") # lines(x=c(-2,-2.3), y=c(-3.5,-3.5),lty=3, col="gray50") # # text(-0.79,-4,paste("slope 18?C =",round(temp18$coefficients[2],2), "?", # round(summary(temp18)$coefficients[2,2],2)), col="gray50") # lines(x=c(-2,-2.3), y=c(-4,-4),lty=4, col="gray50") # # #dev.off() # # # # #---------------------------------------------------------------------------------------- # # Modelo para cada temperatura version 2 # #---------------------------------------------------------------------------------------- # temp6<-lm(log10(mo2.4)~log10(dry_weight_g)*kpa,data=subset(pela, temperature==6)) # temp12<-lm(log10(mo2.4)~log10(dry_weight_g)*kpa,data=subset(pela, temperature==12)) # temp18<-lm(log10(mo2.4)~log10(dry_weight_g)*kpa,data=subset(pela, temperature==18)) # # png(filename="D:/Dropbox/FL+WB/PELA/manuscript/submission/ 1.1. Figure S2b Scaling of metabolic rate by tempeature.png",width=8,height=8,units="in",res=600) # par(mfrow=c(2,2)) # # #6?C # plot(log10(mo2.4)~log10(dry_weight_g),cex=0.8,xlim=c(-5,1),ylim=c(-5,1),ylab="", xlab="", # yaxs="i",xaxs="i",col="white",las=1,frame.plot=FALSE,data=pela) # points(log10(mo2.4)~log10(dry_weight_g), data =subset(pela, temperature==6 & !stage=="Embryo"), col="black",cex=0.8) # points(log10(mo2.4)~log10(dry_weight_g), data =subset(pela, temperature==6 & stage=="Embryo"), col="gray50",cex=0.8) # mtext(expression(paste(Log[10]," metabolic rate")),side=2, line=2, outer=F) # mtext(expression(paste(Log[10]," body mass")),side=1, cex=1, outer=F, line=3) # # All life stages at 6?C # clip(x1=-4.5,x2=0.9,y1=-4.5,y2=0.9) # limite para abline # abline(temp6$coefficients[1]+temp6$coefficients[3]*mean(pela$kpa)+temp6$coefficients[4]*mean(log10(pela$dry_weight_g))*mean(pela$kpa), # temp6$coefficients[2], lty=1,col="gray50") # # Without eggs at 6?C # clip(x1=-3.5,x2=0.9,y1=-4.5,y2=0.9) # limite para abline # abline(temp6.s$coefficients[1]+temp6.s$coefficients[3]*mean(pela$kpa)+temp6.s$coefficients[5]*mean(log10(pela$dry_weight_g))*mean(pela$kpa), # temp6.s$coefficients[2], lty=1,col="black") # # labels at 6?C # text(-1.1,-3.5,paste("slope 6?C eggs =",round(temp6$coefficients[2],2), "?", # round(summary(temp6)$coefficients[2,2],2)),cex = 0.9, col="gray50") # lines(x=c(-3,-3.3), y=c(-3.5,-3.5),lty=1, col="gray50") # text(-1.0,-4.0,paste("slope 6?C no eggs =",round(temp6.s$coefficients[2],2), "?", # round(summary(temp6.s)$coefficients[2,2],2)),cex = 0.9, col="black") # lines(x=c(-3,-3.3), y=c(-4,-4),lty=1, col="black") # # # 12?C # plot(log10(mo2.4)~log10(dry_weight_g),cex=0.8,xlim=c(-5,1),ylim=c(-5,1),ylab="", xlab="", # yaxs="i",xaxs="i",col="white",las=1,frame.plot=FALSE,data=pela) # points(log10(mo2.4)~log10(dry_weight_g), data =subset(pela, temperature==12 & !stage=="Embryo"), col="black",cex=0.8) # points(log10(mo2.4)~log10(dry_weight_g), data =subset(pela, temperature==12 & stage=="Embryo"), col="gray50",cex=0.8) # mtext(expression(paste(Log[10]," metabolic rates")),side=2, line=2, outer=F) # mtext(expression(paste(Log[10]," body mass")),side=1, cex=1, outer=F, line=3) # # # All life stages at 12?C # clip(x1=-4.5,x2=0.9,y1=-4.5,y2=0.9) # limite para abline # abline(temp12$coefficients[1]+temp12$coefficients[3]*mean(pela$kpa)+temp12$coefficients[4]*mean(log10(pela$dry_weight_g))*mean(pela$kpa), # temp12$coefficients[2], lty=1,col="gray50") # # Without eggs at 12?C # clip(x1=-3.5,x2=0.9,y1=-4.5,y2=0.9) # limite para abline # abline(temp12.s$coefficients[1]+temp12.s$coefficients[3]*mean(pela$kpa)+temp12.s$coefficients[5]*mean(log10(pela$dry_weight_g))*mean(pela$kpa), # temp12.s$coefficients[2], lty=1,col="black") # # labels at 12C? # text(-1.1,-3.5,paste("slope 12?C eggs =",round(temp12$coefficients[2],2), "?", # round(summary(temp12)$coefficients[2,2],2)),cex = 0.9, col="gray50") # lines(x=c(-3,-3.3), y=c(-3.5,-3.5),lty=1, col="gray50") # text(-1.0,-4,paste("slope 12?C no eggs =",round(temp12.s$coefficients[2],2), "?", # round(summary(temp12.s)$coefficients[2,2],2)),cex = 0.9, col="black") # lines(x=c(-3,-3.3), y=c(-4,-4),lty=1, col="black") # # # Without eggs at 12?C # plot(log10(mo2.4)~log10(dry_weight_g),cex=0.8,xlim=c(-5,1),ylim=c(-5,1),ylab="", xlab="", # yaxs="i",xaxs="i",col="white",las=1,frame.plot=FALSE,data=pela) # points(log10(mo2.4)~log10(dry_weight_g), data =subset(pela, temperature==18 & !stage=="Embryo"), col="black",cex=0.8) # points(log10(mo2.4)~log10(dry_weight_g), data =subset(pela, temperature==18 & stage=="Embryo"), col="gray50",cex=0.8) # mtext(expression(paste(Log[10]," metabolic rates")),side=2, line=2, outer=F) # mtext(expression(paste(Log[10]," body mass")),side=1, cex=1, outer=F, line=3) # # # # All life stages at 18?C # clip(x1=-4.5,x2=0.9,y1=-4.5,y2=0.9) # limite para abline # abline(temp18$coefficients[1]+temp18$coefficients[3]*mean(pela$kpa)+temp18$coefficients[4]*mean(log10(pela$dry_weight_g))*mean(pela$kpa), # temp18$coefficients[2], lty=1,col="gray50") # # Without eggs at 18?C # clip(x1=-3.5,x2=0.9,y1=-4.5,y2=0.9) # limite para abline # abline(temp18.s$coefficients[1]+temp18.s$coefficients[3]*mean(pela$kpa)+temp18.s$coefficients[5]*mean(log10(pela$dry_weight_g))*mean(pela$kpa), # temp18.s$coefficients[2], lty=1,col="black") # # labels at 18?C # text(-1.1,-3.5,paste("slope 18?C eggs =",round(temp18$coefficients[2],2), "?", # round(summary(temp18)$coefficients[2,2],2)),cex = 0.9, col="gray50") # lines(x=c(-3,-3.3), y=c(-3.5,-3.5),lty=1, col="gray50") # text(-1.0,-4,paste("slope 18?C no eggs =",round(temp18.s$coefficients[2],2), "?", # round(summary(temp18.s)$coefficients[2,2],2)),cex = 0.9, col="black") # lines(x=c(-3,-3.3), y=c(-4,-4),lty=1, col="black") # dev.off() #
If $f$ is a continuous function defined on a compact set $S$, then $f$ is Borel integrable on $S$.
require(rms) set.seed(1) a <- runif(100) b <- factor(sample(c('a','b','c'), 100, TRUE)) b[10] <- NA d <- data.frame(a, b) x <- aregImpute(~ a + b, data=d) x$imputed$b fit.mult.impute(a ~ b, ols, x, data=d)
{-# OPTIONS --without-K --safe #-} module Data.Binary.Tests.Subtraction where open import Data.List as List using (List; _∷_; []) open import Data.Product open import Data.Nat as ℕ using (ℕ; suc; zero) open import Data.Binary.Definitions open import Data.Binary.Operations.Semantics as Pos using (⟦_⇓⟧⁺) open import Relation.Binary.PropositionalEquality open import Data.Maybe as Maybe using (Maybe; just; nothing) ℤ : Set ℤ = Bit × ℕ ⟦_⇓⟧ : 𝔹± → ℤ ⟦ 0< (O , snd) ⇓⟧ = O , ⟦ snd ⇓⟧⁺ ⟦ 0< (I , snd) ⇓⟧ = I , ℕ.pred ⟦ snd ⇓⟧⁺ ⟦ 0ᵇ ⇓⟧ = O , 0 - : ℕ → ℤ - zero = O , zero - (suc snd) = I , snd +⇑ : ℕ → ℤ +⇑ = O ,_ ⟦_⇑⟧ : ℤ → 𝔹± ⟦ O , snd ⇑⟧ = Maybe.map (O ,_) Pos.⟦ snd ⇑⟧ ⟦ I , snd ⇑⟧ = Maybe.map (I ,_) Pos.⟦ suc snd ⇑⟧ -- _≡⌈_⌉≡_ : (𝔹 → 𝔹) → ℕ → (ℕ → ℕ) → Set -- fᵇ ≡⌈ n ⌉≡ fⁿ = let xs = List.upTo n in List.map (λ x → ⟦ fᵇ ⟦ x ⇑⟧ ⇓⟧ ) xs ≡ List.map fⁿ xs prod : ∀ {a b} {A : Set a} {B : Set b} → List A → List B → List (A × B) prod [] ys = [] prod (x ∷ xs) ys = List.foldr (λ y ys → (x , y) ∷ ys) (prod xs ys) ys _≡⌈_⌉₂≡_ : (𝔹± → 𝔹± → 𝔹±) → ℕ → (ℤ → ℤ → ℤ) → Set fᵇ ≡⌈ n ⌉₂≡ fⁿ = List.map (λ { (x , y) → ⟦ fᵇ ⟦ x ⇑⟧ ⟦ y ⇑⟧ ⇓⟧ }) zs ≡ List.map (uncurry fⁿ) zs where xs : List ℕ xs = List.upTo n ys = List.map (I ,_) xs List.++ List.map (O ,_) xs zs = prod ys ys _ℤ-_ : ℕ → ℕ → ℤ x ℤ- y with y ℕ.<ᵇ x (x ℤ- y) | I = O , (x ℕ.∸ suc y) (x ℤ- y) | O = I , (y ℕ.∸ x) _z+_ : ℤ → ℤ → ℤ (O , x) z+ (O , y) = O , (x ℕ.+ y) (O , x) z+ (I , y) = x ℤ- y (I , x) z+ (O , y) = y ℤ- x (I , x) z+ (I , y) = I , (suc x ℕ.+ y) {-# DISPLAY _,_ I xn = - (suc xn) #-} {-# DISPLAY _,_ O xn = +⇑ xn #-} open import Data.Binary.Operations.Subtraction -- _ : ⟦ ⟦ (- 3) ⇑⟧ + ⟦ +⇑ 2 ⇑⟧ ⇓⟧ ≡ (- 1) -- _ = refl -- _ : _+_ ≡⌈ 3 ⌉₂≡ _z+_ -- _ = refl
The polynomial $n$ is equal to the monomial $nx^0$.
[STATEMENT] lemma neumann_3B_b: assumes "u \<succ>[\<R>] v" assumes "\<alpha> \<in> {0<..<1}" shows "u \<succ>[\<R>] mix_pmf \<alpha> u v" [PROOF STATE] proof (prove) goal (1 subgoal): 1. u \<succeq>[\<R>] mix_pmf \<alpha> u v \<and> (mix_pmf \<alpha> u v, u) \<notin> \<R> [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. u \<succeq>[\<R>] mix_pmf \<alpha> u v \<and> (mix_pmf \<alpha> u v, u) \<notin> \<R> [PROOF STEP] have *: "preorder_on \<P> \<R> \<and> rational_preference_axioms \<P> \<R>" [PROOF STATE] proof (prove) goal (1 subgoal): 1. preorder_on local.\<P> \<R> \<and> rational_preference_axioms local.\<P> \<R> [PROOF STEP] by (metis (no_types) preference_def rational_preference_def rpr) [PROOF STATE] proof (state) this: preorder_on local.\<P> \<R> \<and> rational_preference_axioms local.\<P> \<R> goal (1 subgoal): 1. u \<succeq>[\<R>] mix_pmf \<alpha> u v \<and> (mix_pmf \<alpha> u v, u) \<notin> \<R> [PROOF STEP] have "1 - \<alpha> \<in> {0<..1}" [PROOF STATE] proof (prove) goal (1 subgoal): 1. 1 - \<alpha> \<in> {0<..1} [PROOF STEP] using assms(2) [PROOF STATE] proof (prove) using this: \<alpha> \<in> {0<..<1} goal (1 subgoal): 1. 1 - \<alpha> \<in> {0<..1} [PROOF STEP] by auto [PROOF STATE] proof (state) this: 1 - \<alpha> \<in> {0<..1} goal (1 subgoal): 1. u \<succeq>[\<R>] mix_pmf \<alpha> u v \<and> (mix_pmf \<alpha> u v, u) \<notin> \<R> [PROOF STEP] then [PROOF STATE] proof (chain) picking this: 1 - \<alpha> \<in> {0<..1} [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: 1 - \<alpha> \<in> {0<..1} goal (1 subgoal): 1. u \<succeq>[\<R>] mix_pmf \<alpha> u v \<and> (mix_pmf \<alpha> u v, u) \<notin> \<R> [PROOF STEP] using * assms [PROOF STATE] proof (prove) using this: 1 - \<alpha> \<in> {0<..1} preorder_on local.\<P> \<R> \<and> rational_preference_axioms local.\<P> \<R> u \<succeq>[\<R>] v \<and> (v, u) \<notin> \<R> \<alpha> \<in> {0<..<1} goal (1 subgoal): 1. u \<succeq>[\<R>] mix_pmf \<alpha> u v \<and> (mix_pmf \<alpha> u v, u) \<notin> \<R> [PROOF STEP] by (metis atLeastAtMost_iff greaterThanLessThan_iff less_eq_real_def pmf_inverse_switch_eqals x_sg_y_sg_mpmf_right) [PROOF STATE] proof (state) this: u \<succeq>[\<R>] mix_pmf \<alpha> u v \<and> (mix_pmf \<alpha> u v, u) \<notin> \<R> goal: No subgoals! [PROOF STEP] qed
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_const_mksa.h> #include <gsl/gsl_roots.h> #include "ccl.h" // Global variable to hold the neutrino phase-space spline gsl_spline* nu_spline = NULL; // these are NOT adjustable // this phase space integral is only done once and the following is accurate // enough according to tests done by the devs /** * Absolute precision in neutrino root finding */ #define GSL_EPSABS_NU 1E-7 /** * Relative precision in neutrino root finding */ #define GSL_EPSREL_NU 1E-7 /** * Number of iterations for neutrino root finding */ #define GSL_N_ITERATION_NU 1000 /* ------- ROUTINE: nu_integrand ------ INPUTS: x: dimensionless momentum, *r: pointer to a dimensionless mass / temperature TASK: Integrand of phase-space massive neutrino integral */ static double nu_integrand(double x, void *r) { double rat = *((double*)(r)); double x2 = x*x; return sqrt(x2 + rat*rat) / (exp(x)+1.0) * x2; } /* ------- ROUTINE: ccl_calculate_nu_phasespace_spline ------ TASK: Get the spline of the result of the phase-space integral required for massive neutrinos. */ gsl_spline* calculate_nu_phasespace_spline(int *status) { int N = CCL_NU_MNUT_N; double *mnut = NULL; double *y = NULL; gsl_spline* spl = NULL; gsl_integration_cquad_workspace * workspace = NULL; int stat = 0, gslstatus; gsl_function F; mnut = ccl_linear_spacing(log(CCL_NU_MNUT_MIN), log(CCL_NU_MNUT_MAX), N); y = malloc(sizeof(double)*CCL_NU_MNUT_N); if ((y == NULL) || (mnut == NULL)) { // Not setting a status_message here because we can't easily pass a // cosmology to this function - message printed in ccl_error.c. *status = CCL_ERROR_NU_INT; } if (*status == 0) { workspace = gsl_integration_cquad_workspace_alloc(GSL_N_ITERATION_NU); if (workspace == NULL) *status = CCL_ERROR_NU_INT; } if (*status == 0) { F.function = &nu_integrand; for (int i=0; i < CCL_NU_MNUT_N; i++) { double mnut_ = exp(mnut[i]); F.params = &(mnut_); gslstatus = gsl_integration_cquad(&F, 0, 1000.0, GSL_EPSABS_NU, GSL_EPSREL_NU, workspace, &y[i], NULL, NULL); if (gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_neutrinos.c: calculate_nu_phasespace_spline():"); stat |= gslstatus; } } double renorm = 1./y[0]; for (int i=0; i < CCL_NU_MNUT_N; i++) y[i] *= renorm; if (stat) { *status = CCL_ERROR_NU_INT; } } if (*status == 0) { spl = gsl_spline_alloc(gsl_interp_akima, CCL_NU_MNUT_N); if (spl == NULL) *status = CCL_ERROR_NU_INT; } if (*status == 0) { stat |= gsl_spline_init(spl, mnut, y, CCL_NU_MNUT_N); if (stat) { ccl_raise_gsl_warning(gslstatus, "ccl_neutrinos.c: calculate_nu_phasespace_spline():"); *status = CCL_ERROR_NU_INT; } } // Check for errors in creating the spline if (stat || (*status)) { // Not setting a status_message here because we can't easily pass a // cosmology to this function - message printed in ccl_error.c. *status = CCL_ERROR_NU_INT; gsl_spline_free(spl); } gsl_integration_cquad_workspace_free(workspace); free(mnut); free(y); return spl; } /* ------- ROUTINE: ccl_nu_phasespace_intg ------ INPUTS: mnuOT: the dimensionless mass / temperature of a single massive neutrino TASK: Get the value of the phase space integral at mnuOT */ double nu_phasespace_intg(double mnuOT, int* status) { // Check if the global variable for the phasespace spline has been defined yet: if (nu_spline == NULL) nu_spline = calculate_nu_phasespace_spline(status); if (*status) { return NAN; } double integral_value = 0.; // First check the cases where we are in the limits. if (mnuOT < CCL_NU_MNUT_MIN) return 7./8.; else if (mnuOT > CCL_NU_MNUT_MAX) return 0.2776566337 * mnuOT; int gslstatus = gsl_spline_eval_e(nu_spline, log(mnuOT), NULL, &integral_value); if (gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_neutrinos.c: nu_phasespace_intg():"); *status |= gslstatus; } return integral_value * 7./8.; } /* -------- ROUTINE: Omeganuh2 --------- INPUTS: a: scale factor, Nnumass: number of massive neutrino species, mnu: total mass in eV of neutrinos, T_CMB: CMB temperature, status: pointer to status integer. TASK: Compute Omeganu * h^2 as a function of time. !! To all practical purposes, Neff is simply N_nu_mass !! */ double ccl_Omeganuh2 (double a, int N_nu_mass, double* mnu, double T_CMB, int* status) { double Tnu, a4, prefix_massless, mnuone, OmNuh2; double Tnu_eff, mnuOT, intval, prefix_massive; double total_mass; // To check if this is the massless or massive case. // First check if N_nu_mass is 0 if (N_nu_mass == 0) return 0.0; Tnu = T_CMB*pow(4./11.,1./3.); a4 = a*a*a*a; // Check if mnu=0. We assume that in the massless case mnu is a // pointer to a single element and that element is 0. This should in principle never be called. if (mnu[0] < 0.00017) { // Limit taken from Lesgourges et al. 2012 prefix_massless = NU_CONST * Tnu * Tnu * Tnu * Tnu; return N_nu_mass*prefix_massless*7./8./a4; } // And the remaining massive case. // Tnu_eff is used in the massive case because CLASS uses an effective // temperature of nonLCDM components to match to mnu / Omeganu =93.14eV. Tnu_eff = T_ncdm * T_CMB = 0.71611 * T_CMB Tnu_eff = Tnu * ccl_constants.TNCDM / (pow(4./11.,1./3.)); // Define the prefix using the effective temperature (to get mnu / Omega = 93.14 eV) for the massive case: prefix_massive = NU_CONST * Tnu_eff * Tnu_eff * Tnu_eff * Tnu_eff; OmNuh2 = 0.; // Initialize to 0 - we add to this for each massive neutrino species. for(int i=0; i < N_nu_mass; i++) { // Get mass over T (mass (eV) / ((kb eV/s/K) Tnu_eff (K)) // This returns the density normalized so that we get nuh2 at a=0 mnuOT = mnu[i] / (Tnu_eff/a) * (ccl_constants.EV_IN_J / (ccl_constants.KBOLTZ)); // Get the value of the phase-space integral intval = nu_phasespace_intg(mnuOT, status); OmNuh2 = intval*prefix_massive/a4 + OmNuh2; } return OmNuh2; } /* -------- ROUTINE: Omeganuh2_to_Mnu --------- INPUTS: OmNuh2: neutrino mass density today Omeganu * h^2, label: how you want to split up the masses, see ccl_neutrinos.h for options, T_CMB: CMB temperature, status: pointer to status integer. TASK: Given Omeganuh2 today, the method of splitting into masses, and the temperature of the CMB, output a pointer to the array of neutrino masses (may be length 1 if label asks for sum) */ double* ccl_nu_masses(double OmNuh2, ccl_neutrino_mass_splits mass_split, double T_CMB, int* status) { double sumnu; double *mnu = NULL; sumnu = 93.14 * OmNuh2; // Now split the sum up into three masses depending on the label given: if (mass_split == ccl_nu_normal) { mnu = malloc(3*sizeof(double)); if (mnu == NULL) { *status = CCL_ERROR_MEMORY; } if (*status == 0) { // See CCL note for how we get these expressions for the neutrino masses in // normal and inverted hierarchy. mnu[0] = ( 2./3.* sumnu - 1./6. * pow(-6. * ccl_constants.DELTAM12_sq + 12. * ccl_constants.DELTAM13_sq_pos + 4. * sumnu*sumnu, 0.5) - 0.25 * ccl_constants.DELTAM12_sq / (2./3.* sumnu - 1./6. * pow(-6. * ccl_constants.DELTAM12_sq + 12. * ccl_constants.DELTAM13_sq_pos + 4. * sumnu*sumnu, 0.5))); mnu[1] = ( 2./3.* sumnu - 1./6. * pow(-6. * ccl_constants.DELTAM12_sq + 12. * ccl_constants.DELTAM13_sq_pos + 4. * sumnu*sumnu, 0.5) + 0.25 * ccl_constants.DELTAM12_sq / (2./3.* sumnu - 1./6. * pow(-6. * ccl_constants.DELTAM12_sq + 12. * ccl_constants.DELTAM13_sq_pos + 4. * sumnu*sumnu, 0.5))); mnu[2] = ( -1./3. * sumnu + 1./3 * pow(-6. * ccl_constants.DELTAM12_sq + 12. * ccl_constants.DELTAM13_sq_pos + 4. * sumnu*sumnu, 0.5)); if (mnu[0] < 0 || mnu[1] < 0 || mnu[2] < 0) { // The user has provided a sum that is below the physical limit. if (sumnu < 1e-14) { mnu[0] = 0.; mnu[1] = 0.; mnu[2] = 0.; } else { *status = CCL_ERROR_MNU_UNPHYSICAL; ccl_raise_warning( *status, "CCL_ERROR_MNU_UNPHYSICAL: Sum of neutrinos masses for this Omeganu " "value is incompatible with the requested mass hierarchy."); } } } } else if (mass_split == ccl_nu_inverted) { mnu = malloc(3*sizeof(double)); if (mnu == NULL) { *status = CCL_ERROR_MEMORY; } if (*status == 0) { mnu[0] = ( 2./3.* sumnu - 1./6. * pow(-6. * ccl_constants.DELTAM12_sq + 12. * ccl_constants.DELTAM13_sq_neg + 4. * sumnu * sumnu, 0.5) - 0.25 * ccl_constants.DELTAM12_sq / (2./3.* sumnu - 1./6. * pow(-6. * ccl_constants.DELTAM12_sq + 12. * ccl_constants.DELTAM13_sq_neg + 4. * sumnu * sumnu, 0.5))); mnu[1] = ( 2./3.* sumnu - 1./6. * pow(-6. * ccl_constants.DELTAM12_sq + 12. * ccl_constants.DELTAM13_sq_neg + 4. * sumnu*sumnu, 0.5) + 0.25 * ccl_constants.DELTAM12_sq / (2./3.* sumnu - 1./6. * pow(-6. * ccl_constants.DELTAM12_sq + 12. * ccl_constants.DELTAM13_sq_neg + 4. * sumnu*sumnu, 0.5))); mnu[2] = ( -1./3. * sumnu + 1./3 * pow(-6. * ccl_constants.DELTAM12_sq + 12. * ccl_constants.DELTAM13_sq_neg + 4. * sumnu*sumnu, 0.5)); if (mnu[0] < 0 || mnu[1] < 0 || mnu[2] < 0) { // The user has provided a sum that is below the physical limit. if (sumnu < 1e-14) { mnu[0] = 0.; mnu[1] = 0.; mnu[2] = 0.;; } else { *status = CCL_ERROR_MNU_UNPHYSICAL; ccl_raise_warning( *status, "CCL_ERROR_MNU_UNPHYSICAL: Sum of neutrinos masses for this Omeganu " "value is incompatible with the requested mass hierarchy."); } } } } else if (mass_split == ccl_nu_equal) { mnu = malloc(3*sizeof(double)); if (mnu == NULL) { *status = CCL_ERROR_MEMORY; } if (*status == 0) { mnu[0] = sumnu/3.; mnu[1] = sumnu/3.; mnu[2] = sumnu/3.; } } else if (mass_split == ccl_nu_sum) { mnu = malloc(sizeof(double)); if (mnu == NULL) { *status = CCL_ERROR_MEMORY; } if (*status == 0) { mnu[0] = sumnu; } } else { *status = CCL_ERROR_MNU_UNPHYSICAL; ccl_raise_warning( *status, "mass option = %d not yet supported!", mass_split); } return mnu; } #undef GSL_EPSABS_NU #undef GSL_EPSREL_NU #undef GSL_N_ITERATION_NU
# Built-in UnorderedTuples(["iced", "jam", "plain"], 2);
Require Import CSet Util IL EqDec LengthEq Get. Require Import Coq.Classes.RelationClasses MoreList AllInRel ListUpdateAt. Require Import SizeInduction Infra.Lattice OptionR DecSolve. Require Import Annotation AnnotationLattice Subterm. Set Implicit Arguments. Lemma option_eq_option_R X (R:relation X) x y : option_eq R x y <-> option_R R x y. Proof. split; inversion 1; econstructor; eauto. Qed. Inductive anni (A:Type) : Type := | anni0 : anni A | anni1 (a1:A) : anni A | anni2 (a1:A) (a2:A) : anni A | anni2opt (a1:option A) (a2:option A) : anni A. Arguments anni0 [A]. Fixpoint setAnni {A} (a:ann A) (ai:anni A) : ann A := match a, ai with | ann1 a an, anni1 a1 => ann1 a (setTopAnn an a1) | ann2 a an1 an2, anni2 a1 a2 => ann2 a (setTopAnn an1 a1) (setTopAnn an2 a2) | an, _ => an end. Definition mapAnni {A B} (f:A -> B) (ai:anni A) : anni B := match ai with | anni0 => anni0 | anni1 a1 => anni1 (f a1) | anni2 a1 a2 => anni2 (f a1) (f a2) | anni2opt o1 o2 => anni2opt (mapOption f o1) (mapOption f o2) end. Inductive anni_R A B (R : A -> B -> Prop) : anni A -> anni B -> Prop := | anni_R0 : anni_R R anni0 anni0 | anni_R1 a1 a2 : R a1 a2 -> anni_R R (anni1 a1) (anni1 a2) | anni_R2 a1 a1' a2 a2' : R a1 a2 -> R a1' a2' -> anni_R R (anni2 a1 a1') (anni2 a2 a2') | anni_R2o o1 o1' o2 o2' : option_R R o1 o2 -> option_R R o1' o2' -> anni_R R (anni2opt o1 o1') (anni2opt o2 o2'). Instance anni_R_refl {A} {R} `{Reflexive A R} : Reflexive (anni_R R). Proof. hnf; intros; destruct x; eauto using anni_R, option_R. econstructor; reflexivity. Qed. Instance anni_R_sym {A} {R} `{Symmetric A R} : Symmetric (anni_R R). Proof. hnf; intros. inv H0; eauto using anni_R. econstructor; symmetry; eauto. Qed. Instance anni_R_trans A R `{Transitive A R} : Transitive (anni_R R). Proof. hnf; intros ? ? ? B C. inv B; inv C; econstructor; eauto. - etransitivity; eauto. - etransitivity; eauto. Qed. Instance anni_R_equivalence A R `{Equivalence A R} : Equivalence (anni_R R). Proof. econstructor; eauto with typeclass_instances. Qed. Instance anni_R_anti A R Eq `{EqA:Equivalence _ Eq} `{@Antisymmetric A Eq EqA R} : @Antisymmetric _ (anni_R Eq) _ (anni_R R). Proof. intros ? ? B C. inv B; inv C; eauto using anni_R. econstructor; eapply option_R_anti; eauto. Qed. Instance anni_R_dec A B (R:A->B->Prop) `{forall a b, Computable (R a b)} (a:anni A) (b:anni B) : Computable (anni_R R a b). Proof. destruct a,b; try dec_solve. - decide (R a1 a0); dec_solve. - decide (R a1 a0); decide (R a2 a3); dec_solve. - decide (option_R R a1 a0); decide (option_R R a2 a3); dec_solve. Defined. Instance PartialOrder_anni Dom `{PartialOrder Dom} : PartialOrder (anni Dom) := { poLe := anni_R poLe; poLe_dec := @anni_R_dec _ _ poLe poLe_dec; poEq := anni_R poEq; poEq_dec := @anni_R_dec _ _ poEq poEq_dec; }. Proof. - intros. inv H0; eauto 20 using @anni_R, poLe_refl. econstructor; eauto. inv H1; econstructor; eauto. inv H2; econstructor; eauto. Defined. Definition getAnni A (a:A) (an:anni A) := match an with | anni1 a => a | _ => a end. Lemma poLe_getAnni A `{PartialOrder A} (a a':A) an an' : poLe a a' -> poLe an an' -> poLe (getAnni a an) (getAnni a' an'). Proof. intros LE LE'; inv LE'; simpl; eauto. Qed. Lemma poEq_getAnni A `{PartialOrder A} (a a':A) an an' : poEq a a' -> poEq an an' -> poEq (getAnni a an) (getAnni a' an'). Proof. intros LE LE'; inv LE'; simpl; eauto. Qed. Hint Resolve poLe_getAnni poEq_getAnni. Definition getAnniLeft A (a:A) (an:anni A) := match an with | anni2 a _ => a | _ => a end. Lemma poLe_getAnniLeft A `{PartialOrder A} (a a':A) an an' : poLe a a' -> poLe an an' -> poLe (getAnniLeft a an) (getAnniLeft a' an'). Proof. intros LE LE'; inv LE'; simpl; eauto. Qed. Lemma poEq_getAnniLeft A `{PartialOrder A} (a a':A) an an' : poEq a a' -> poEq an an' -> poEq (getAnniLeft a an) (getAnniLeft a' an'). Proof. intros LE LE'; inv LE'; simpl; eauto. Qed. Hint Resolve poLe_getAnniLeft poEq_getAnniLeft. Definition getAnniRight A (a:A) (an:anni A) := match an with | anni2 _ a => a | _ => a end. Lemma poLe_getAnniRight A `{PartialOrder A} (a a':A) an an' : poLe a a' -> poLe an an' -> poLe (getAnniRight a an) (getAnniRight a' an'). Proof. intros LE LE'; inv LE'; simpl; eauto. Qed. Lemma poEq_getAnniRight A `{PartialOrder A} (a a':A) an an' : poEq a a' -> poEq an an' -> poEq (getAnniRight a an) (getAnniRight a' an'). Proof. intros LE LE'; inv LE'; simpl; eauto. Qed. Hint Resolve poLe_getAnniRight poEq_getAnniRight. Lemma ann_bottom s' (Dom:Type) `{LowerBounded Dom} : forall (d : ann Dom), annotation s' d -> setAnn bottom s' ⊑ d. Proof. sind s'; destruct s'; simpl; intros d' Ann; inv Ann; simpl; eauto using bottom_least. - econstructor; eauto using bottom_least with len. + intros; inv_get. eapply IH; eauto. + eapply IH; eauto. Qed. Definition setTopAnnO {A} `{LowerBounded A} a (al:option A) := match al with | None => setTopAnn a bottom | Some al' => setTopAnn a al' end. Lemma setTopAnnO_annotation A `{LowerBounded A} a (al:option A) s : annotation s a -> annotation s (setTopAnnO a al). Proof. intros. unfold setTopAnnO; cases; eauto using setTopAnn_annotation. Qed. Lemma ann_R_setTopAnnO_poLe (A : Type) `{PartialOrder A} `{LowerBounded A} a b (an : ann A) (bn : ann A) : poLe a b -> poLe an bn -> poLe (setTopAnnO an a) (setTopAnnO bn b). Proof. intros. unfold setTopAnnO; repeat cases; eauto. eapply ann_R_setTopAnn; eauto. eapply bottom_least. Qed. Lemma ann_R_setTopAnnO_poEq (A : Type) `{PartialOrder A} `{LowerBounded A} a b (an : ann A) (bn : ann A) : poEq a b -> poEq an bn -> poEq (setTopAnnO an a) (setTopAnnO bn b). Proof. intros. unfold setTopAnnO; repeat cases; eapply ann_R_setTopAnn; eauto. Qed. Hint Resolve ann_R_setTopAnnO_poLe ann_R_setTopAnnO_poEq. (* Lemma poLe_zip_setTopAnnO X `{PartialOrder X} (A A':list (ann X)) (B B':list X) : poLe A A' -> poLe B B' -> poLe ((@setTopAnnO _) ⊜ A B) (@setTopAnnO _ ⊜ A' B'). Proof. intros LE_A LE_B; simpl in *. general induction LE_A; inv LE_B; simpl; eauto using PIR2. - econstructor; eauto. eapply ann_R_setTopAnnO; eauto. eapply IHLE_A; eauto. Qed. Lemma PIR2_poEq_zip_setTopAnnO X `{PartialOrder X} (A A':list (ann X)) (B B':list X) : poEq A A' -> poEq B B' -> poEq ((@setTopAnnO _) ⊜ A B) (@setTopAnnO _ ⊜ A' B'). Proof. intros LE_A LE_B; simpl in *. general induction LE_A; inv LE_B; simpl; eauto using PIR2. - econstructor; eauto. eapply ann_R_setTopAnnO; eauto. eapply IHLE_A; eauto. Qed. Lemma PIR2_setTopAnnO_zip_left X (R:X->X->Prop) `{Reflexive _ R} (A:list (ann X)) B : PIR2 R (Take.take ❬A❭ B) (getAnn ⊝ A) -> PIR2 (ann_R R) (@setTopAnnO _ ⊜ A B) A. Proof. intros P. general induction P; destruct A, B; isabsurd; eauto using PIR2. simpl in *. clear_trivial_eqs. econstructor; eauto. eapply ann_R_setTopAnnO_left; eauto. Qed. *) Lemma PIR2_ojoin_zip A `{JoinSemiLattice A} (a:list A) a' b b' : poLe a a' -> poLe b b' -> poLe (join ⊜ a b) (join ⊜ a' b'). Proof. intros. hnf in H1,H2. general induction H1; inv H2; simpl; eauto using PIR2. econstructor; eauto. rewrite pf, pf0. reflexivity. eapply IHPIR2; eauto. Qed. Lemma poEq_join_zip A `{JoinSemiLattice A} (a:list A) a' b b' : poEq a a' -> poEq b b' -> poEq (join ⊜ a b) (join ⊜ a' b'). Proof. intros. hnf in H1,H2. general induction H1; inv H2; simpl; eauto using PIR2. econstructor; eauto. rewrite pf, pf0. reflexivity. eapply IHPIR2; eauto. Qed. Hint Resolve PIR2_ojoin_zip poEq_join_zip. Lemma update_at_poLe A `{LowerBounded A} B (L:list B) n (a:A) b : poLe a b -> poLe (list_update_at (tab bottom ‖L‖) n a) (list_update_at (tab bottom ‖L‖) n b). Proof. intros. general induction L; simpl; eauto using PIR2. - destruct n; simpl; eauto using @PIR2. Qed. Lemma update_at_poEq A `{LowerBounded A} B (L:list B) n (a:A) b : poEq a b -> poEq (list_update_at (tab bottom ‖L‖) n a) (list_update_at (tab bottom ‖L‖) n b). Proof. intros. general induction L; simpl; eauto using PIR2. - destruct n; simpl; eauto using @PIR2. Qed. Hint Resolve update_at_poLe update_at_poEq. Lemma PIR2_fold_zip_join X `{JoinSemiLattice X} (A A':list (list X)) (B B':list X) : poLe A A' -> poLe B B' -> poLe (fold_left (zip join) A B) (fold_left (zip join) A' B'). Proof. intros. simpl in *. general induction H1; simpl; eauto. Qed. Lemma PIR2_fold_zip_join_poEq X `{JoinSemiLattice X} (A A':list (list X)) (B B':list X) : poEq A A' -> poEq B B' -> poEq (fold_left (zip join) A B) (fold_left (zip join) A' B'). Proof. intros. simpl in *. general induction H1; simpl; eauto. Qed. Hint Resolve PIR2_fold_zip_join PIR2_fold_zip_join_poEq. Lemma tab_false_impb Dom `{PartialOrder Dom} AL AL' : poLe AL AL' -> poLe (tab false ‖AL‖) (tab false ‖AL'‖). Proof. intros. hnf in H0. general induction H0; simpl; unfold impb; eauto. Qed. Lemma update_at_impb Dom `{PartialOrder Dom} AL AL' n : poLe AL AL' -> poLe (list_update_at (tab false ‖AL‖) n true) (list_update_at (tab false ‖AL'‖) n true). Proof. intros A. general induction A; simpl; eauto. - destruct n; simpl; eauto using @PIR2, tab_false_impb. Qed. Ltac refold_PIR2_PO := match goal with | [ H : context [ PIR2 (@poLe ?D _) ] |- _ ] => change (PIR2 (@poLe D _)) with (@poLe (list D) _) in H | [ H : context [ PIR2 (@poEq ?D _) ] |- _ ] => change (PIR2 (@poLe D _)) with (@poLe (list D) _) in H | [ |- context [ PIR2 (@poLe ?D ?PO) ] ] => change (PIR2 (@poLe D PO)) with (@poLe (list D) _) | [ |- context [ PIR2 (@poEq ?D ?PO) ] ] => change (PIR2 (@poEq D PO)) with (@poEq (list D) _) (* | [ H : context [ PIR2 (@poEq _ _) ] |- _ ] => let EQ := fresh "PIR2_EQ" in assert (EQ:forall X (PO : PartialOrder X) x y, PIR2 (@poEq X PO) x y = @poEq (list X) (@PartialOrder_list X PO) x y) by (intros; reflexivity); setoid_rewrite EQ in H*) end. Smpl Add refold_PIR2_PO : inversion_cleanup. Ltac refold_ann_PO := match goal with | [ H : context [ @ann_R ?A ?A (@poLe ?A ?I) ] |- _ ] => change (@ann_R A A (@poLe A I)) with (@poLe (@ann A) _) in H | [ |- context [ ann_R poLe ?x ?y ] ] => change (ann_R poLe x y) with (poLe x y) | [ H : context [ @ann_R ?A ?A (@poEq ?A ?I) ] |- _ ] => change (@ann_R A A (@poEq A I)) with (@poEq (@ann A) _) in H | [ |- context [ ann_R poEq ?x ?y ] ] => change (ann_R poEq x y) with (poEq x y) end. Smpl Add refold_ann_PO : inversion_cleanup. Hint Resolve join_struct join_struct_eq. Lemma PIR2_poLe_join X `{JoinSemiLattice X} (A A' B B':list X) : poLe A A' -> poLe B B' -> poLe (join ⊜ A B) (join ⊜ A' B'). Proof. intros AA BB. general induction AA; simpl; inv BB; eauto. Qed. Hint Resolve PIR2_poLe_join. Lemma PIR2_impb_orb A A' B B' : PIR2 impb A A' -> PIR2 impb B B' -> PIR2 impb (orb ⊜ A B) (orb ⊜ A' B'). Proof. intros. pose proof (@PIR2_poLe_join bool _ _). eapply H1; eauto. Qed. Smpl Add 10 match goal with | [ H : _ < _ |- _ ] => simpl in H | [ H : _ <= _ |- _ ] => simpl in H end : inv_trivial. Smpl Add match goal with | [ H : S _ < 0 |- _ ] => exfalso; inv H | [ H : S _ <= 0 |- _ ] => exfalso; inv H end : inv_trivial. Hint Resolve join_poLe. Lemma join_poLe_left X `{JoinSemiLattice X} x y z : poLe x y -> poLe x (join y z). Proof. intros LE. rewrite LE. eauto. Qed. Lemma join_poLe_right X `{JoinSemiLattice X} x y z : poLe x y -> poLe x (join z y). Proof. intros LE. rewrite LE. rewrite join_commutative. eauto. Qed. Hint Resolve join_poLe_left join_poLe_right | 50. Lemma join_poLe_left_inv X `{JoinSemiLattice X} x y z : poLe (join y z) x -> poLe y x. Proof. intros LE. rewrite <- LE. eauto. Qed. Lemma join_poLe_right_inv X `{JoinSemiLattice X} x y z : poLe (join z y) x -> poLe y x. Proof. intros LE. rewrite <- LE. eauto. Qed. Hint Resolve le_S_n | 100. Lemma PIR2_poLe_join_right X `{JoinSemiLattice X} A A' B : length A <= length B -> poLe A A' -> poLe A (join ⊜ A' B). Proof. intros LEN AA. general induction AA; destruct B; simpl in *; clear_trivial_eqs; eauto. Qed. Lemma PIR2_poLe_join_left X `{JoinSemiLattice X} A A' B : length A <= length B -> poLe A A' -> poLe A (join ⊜ B A'). Proof. intros LEN AA. general induction AA; destruct B; simpl in *; clear_trivial_eqs; eauto. Qed. Hint Resolve PIR2_poLe_join_right PIR2_poLe_join_left | 50. Smpl Add 50 match goal with | [ H : context [ impb ] |- _ ] => change impb with (@poLe bool PartialOrder_bool) in H | [ |- context [ impb ] ] => change impb with (@poLe bool PartialOrder_bool) end : inversion_cleanup. Smpl Add 50 match goal with | [ H : context [ orb ] |- _ ] => change orb with (@join bool _ bool_joinsemilattice) in H | [ |- context [ orb ] ] => change orb with (@join bool _ bool_joinsemilattice) end : inversion_cleanup. Lemma poLe_length X `{PartialOrder X} A B : poLe A B -> ❬A❭ <= ❬B❭. Proof. intros. hnf in H0. erewrite PIR2_length; eauto. Qed. Lemma poLe_length_eq X `{PartialOrder X} A B : poLe A B -> ❬A❭ = ❬B❭. Proof. intros. hnf in H0. erewrite PIR2_length; eauto. Qed. Hint Resolve poLe_length : len. Hint Resolve poLe_length_eq : len. Instance poLe_length_proper X `{PartialOrder X} : Proper (poLe ==> eq) (@length X). Proof. unfold Proper, respectful; intros. eauto with len. Qed. Lemma PIR2_impb_fold (A A':list (list bool * bool)) (B B':list bool) : poLe A A' -> poLe B B' -> (forall n a, get A n a -> length B <= length (fst a)) -> poLe (fold_left (fun a (b:list bool * bool) => if snd b then orb ⊜ a (fst b) else a) A B) (fold_left (fun a (b:list bool * bool) => if snd b then orb ⊜ a (fst b) else a) A' B'). Proof. intros. general induction H; simpl; inv_cleanup; eauto. eapply IHPIR2; eauto using PIR2_impb_orb. - exploit H1; eauto using get. inv pf. repeat cases; eauto. eapply PIR2_poLe_join_right; eauto using get. rewrite <- H3; eauto. - intros. cases; eauto using get. rewrite zip_length3; eauto using get. Qed. Lemma PIR2_zip_join_inv_left X `{JoinSemiLattice X} A B C : poLe (join ⊜ A B) C -> length A = length B -> poLe A C. Proof. intros. length_equify. general induction H1; inv H2; simpl in *; clear_trivial_eqs; eauto using join_poLe_left_inv. Qed. Lemma PIR2_zip_join_inv_right X `{JoinSemiLattice X} A B C : poLe (join ⊜ A B) C -> length A = length B -> poLe B C. Proof. intros. general induction H2; inv H1; clear_trivial_eqs; eauto using join_poLe_right_inv. Qed. Lemma PIR2_poLe_zip_join_left X `{JoinSemiLattice X} A B : length A = length B -> poLe A (join ⊜ A B). Proof. intros. general induction H1; simpl in *; eauto using PIR2; try solve [ congruence ]. Qed. Lemma PIR2_zip_join_commutative X `{JoinSemiLattice X} A B : poLe (join ⊜ B A) (join ⊜ A B). Proof. intros. general induction A; destruct B; simpl in *; eauto. eauto using join_commutative. Qed. Lemma PIR2_poLe_zip_join_right X `{JoinSemiLattice X} A B : length A = length B -> poLe B (join ⊜ A B). Proof. intros. rewrite <- PIR2_zip_join_commutative. (* todo: missing morphism *) eapply PIR2_poLe_zip_join_left; congruence. Qed. Lemma PIR2_fold_zip_join_inv X `{JoinSemiLattice X} A B C : poLe (fold_left (zip join) A B) C -> (forall n a, get A n a -> length a = length B) -> poLe B C. Proof. intros. general induction A; simpl in *; eauto. eapply IHA; eauto using get. rewrite <- H1. eauto. eapply PIR2_fold_zip_join; eauto. eapply PIR2_poLe_zip_join_left. symmetry. eauto using get. Qed. Lemma PIR2_fold_zip_join_right X `{JoinSemiLattice X} (A:list X) B C : (forall n a, get B n a -> length a = length C) -> poLe A C -> poLe A (fold_left (zip join) B C). Proof. general induction B; simpl; eauto. eapply IHB; intros; eauto using get with len. - rewrite zip_length2; eauto using eq_sym, get. - rewrite H2. eapply PIR2_poLe_zip_join_left. symmetry. eauto using get. Qed. Lemma PIR2_fold_zip_join_left X `{JoinSemiLattice X} (A:list X) B C a k : get B k a -> poLe A a -> (forall n a, get B n a -> length a = length C) -> poLe A (fold_left (zip join) B C). Proof. intros. general induction B; simpl in *; eauto. - inv H1. + eapply PIR2_fold_zip_join_right. intros. rewrite zip_length2; eauto using eq_sym, get. rewrite H2. eapply PIR2_poLe_zip_join_right. eauto using eq_sym, get. + eapply IHB; eauto using get. intros. rewrite zip_length2; eauto using eq_sym, get. Qed. Lemma get_union_union_b X `{JoinSemiLattice X} (A:list (list X)) (b:list X) n x : get b n x -> (forall n a, get A n a -> ❬a❭ = ❬b❭) -> exists y, get (fold_left (zip join) A b) n y /\ poLe x y. Proof. intros GETb LEN. general induction A; simpl in *. - eexists x. eauto with cset. - exploit LEN; eauto using get. edestruct (get_length_eq _ GETb (eq_sym H1)) as [y GETa]; eauto. exploit (zip_get join GETb GETa). + exploit IHA; try eapply GET; eauto. rewrite zip_length2; eauto using get with len. edestruct H3; dcr; subst. eexists; split; eauto using join_poLe_left_inv. Qed. Lemma get_fold_zip_join X (f: X-> X-> X) (A:list (list X)) (b:list X) n : (forall n a, get A n a -> ❬a❭ = ❬b❭) -> n < ❬b❭ -> exists y, get (fold_left (zip f) A b) n y. Proof. intros LEN. general induction A; simpl in *. - edestruct get_in_range; eauto. - exploit LEN; eauto using get. eapply IHA; eauto using get with len. Qed. Lemma get_union_union_A X `{JoinSemiLattice X} (A:list (list X)) a b n k x : get A k a -> get a n x -> (forall n a, get A n a -> ❬a❭ = ❬b❭) -> exists y, get (fold_left (zip join) A b) n y /\ poLe x y. Proof. intros GETA GETa LEN. general induction A; simpl in * |- *; isabsurd. inv GETA; eauto. - exploit LEN; eauto using get. edestruct (get_length_eq _ GETa H1) as [y GETb]. exploit (zip_get join GETb GETa). exploit (@get_union_union_b _ _ _ A); eauto. rewrite zip_length2; eauto using get with len. destruct H3; dcr; subst. eexists; split; eauto using join_poLe_right_inv. - exploit IHA; eauto. rewrite zip_length2; eauto using get. symmetry; eauto using get. Qed. Lemma fold_left_zip_orb_inv A b n : get (fold_left (zip orb) A b) n true -> get b n true \/ exists k a, get A k a /\ get a n true. Proof. intros Get. general induction A; simpl in *; eauto. edestruct IHA; dcr; eauto 20 using get. inv_get. destruct x, x0; isabsurd; eauto using get. Qed. Lemma fold_left_mono A A' b b' : poLe A A' -> poLe b b' -> poLe (fold_left (zip orb) A b) (fold_left (zip orb) A' b'). Proof. intros. hnf in H. general induction H; simpl; eauto. Qed. Lemma fold_list_length A B (f:list B -> (list A * bool) -> list B) (a:list (list A * bool)) (b: list B) : (forall n aa, get a n aa -> ❬b❭ <= ❬fst aa❭) -> (forall aa b, ❬b❭ <= ❬fst aa❭ -> ❬f b aa❭ = ❬b❭) -> length (fold_left f a b) = ❬b❭. Proof. intros LEN. general induction a; simpl; eauto. erewrite IHa; eauto 10 using get with len. intros. rewrite H; eauto using get. Qed. Lemma fold_list_length' A B (f:list B -> (list A) -> list B) (a:list (list A)) (b: list B) : (forall n aa, get a n aa -> ❬b❭ <= ❬aa❭) -> (forall aa b, ❬b❭ <= ❬aa❭ -> ❬f b aa❭ = ❬b❭) -> length (fold_left f a b) = ❬b❭. Proof. intros LEN. general induction a; simpl; eauto. erewrite IHa; eauto 10 using get with len. intros. rewrite H; eauto using get. Qed. Lemma ZLIncl_ext sT st F t (ZL:list params) (EQ:st = stmtFun F t) (ST:subTerm st sT) (ZLIncl:list_union (of_list ⊝ ZL) ⊆ occurVars sT) : list_union (of_list ⊝ (fst ⊝ F ++ ZL)) [<=] occurVars sT. Proof. subst. rewrite List.map_app. rewrite list_union_app. eapply union_incl_split; eauto. pose proof (subTerm_occurVars ST). simpl in *. rewrite <- H. eapply incl_union_left. eapply list_union_incl; intros; eauto with cset. inv_get. eapply incl_list_union. eapply map_get_1; eauto. cset_tac. Qed. Lemma ZLIncl_App_Z sT ZL n (Incl:list_union (of_list ⊝ ZL) [<=] occurVars sT) : of_list (nth n ZL (nil : params)) [<=] occurVars sT. Proof. destruct (get_dec ZL n); dcr. - erewrite get_nth; eauto. rewrite <- Incl. eapply incl_list_union; eauto using zip_get. - rewrite not_get_nth_default; eauto. simpl. cset_tac. Qed. Arguments ZLIncl_App_Z {sT} {ZL} n Incl. Lemma agree_on_option_R_fstNoneOrR (X : Type) `{OrderedType X} (Y : Type) (R R':Y -> Y -> Prop) (D:set X) (f g h:X -> option Y) : agree_on (option_R R) D f g -> agree_on (fstNoneOrR R') D g h -> (forall a b c, R a b -> R' b c -> R' a c) -> agree_on (fstNoneOrR R') D f h. Proof. intros AGR1 AGR2 Trans; hnf; intros. exploit AGR1 as EQ1; eauto. exploit AGR2 as EQ2; eauto. inv EQ1; inv EQ2; clear_trivial_eqs; try econstructor; try congruence. assert (x0 = b) by congruence; subst. eauto. Qed.
lemma i_even_power [simp]: "\<i> ^ (n * 2) = (-1) ^ n"
/- 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 ! This file was ported from Lean 3 source module analysis.normed_space.enorm ! leanprover-community/mathlib commit 57ac39bd365c2f80589a700f9fbb664d3a1a30c2 ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathbin.Analysis.NormedSpace.Basic /-! # Extended norm In this file we define a structure `enorm 𝕜 V` representing an extended norm (i.e., a norm that can take the value `∞`) on a vector space `V` over a normed field `𝕜`. We do not use `class` for an `enorm` because the same space can have more than one extended norm. For example, the space of measurable functions `f : α → ℝ` has a family of `L_p` extended norms. We prove some basic inequalities, then define * `emetric_space` structure on `V` corresponding to `e : enorm 𝕜 V`; * the subspace of vectors with finite norm, called `e.finite_subspace`; * a `normed_space` structure on this space. The last definition is an instance because the type involves `e`. ## Implementation notes We do not define extended normed groups. They can be added to the chain once someone will need them. ## Tags normed space, extended norm -/ noncomputable section attribute [local instance] Classical.propDecidable open ENNReal /-- Extended norm on a vector space. As in the case of normed spaces, we require only `‖c • x‖ ≤ ‖c‖ * ‖x‖` in the definition, then prove an equality in `map_smul`. -/ structure Enorm (𝕜 : Type _) (V : Type _) [NormedField 𝕜] [AddCommGroup V] [Module 𝕜 V] where toFun : V → ℝ≥0∞ eq_zero' : ∀ x, to_fun x = 0 → x = 0 map_add_le' : ∀ x y : V, to_fun (x + y) ≤ to_fun x + to_fun y map_smul_le' : ∀ (c : 𝕜) (x : V), to_fun (c • x) ≤ ‖c‖₊ * to_fun x #align enorm Enorm namespace Enorm variable {𝕜 : Type _} {V : Type _} [NormedField 𝕜] [AddCommGroup V] [Module 𝕜 V] (e : Enorm 𝕜 V) instance : CoeFun (Enorm 𝕜 V) fun _ => V → ℝ≥0∞ := ⟨Enorm.toFun⟩ theorem coeFn_injective : Function.Injective (coeFn : Enorm 𝕜 V → V → ℝ≥0∞) := fun e₁ e₂ h => by cases e₁ <;> cases e₂ <;> congr <;> exact h #align enorm.coe_fn_injective Enorm.coeFn_injective @[ext] theorem ext {e₁ e₂ : Enorm 𝕜 V} (h : ∀ x, e₁ x = e₂ x) : e₁ = e₂ := coeFn_injective <| funext h #align enorm.ext Enorm.ext theorem ext_iff {e₁ e₂ : Enorm 𝕜 V} : e₁ = e₂ ↔ ∀ x, e₁ x = e₂ x := ⟨fun h x => h ▸ rfl, ext⟩ #align enorm.ext_iff Enorm.ext_iff @[simp, norm_cast] theorem coe_inj {e₁ e₂ : Enorm 𝕜 V} : (e₁ : V → ℝ≥0∞) = e₂ ↔ e₁ = e₂ := coeFn_injective.eq_iff #align enorm.coe_inj Enorm.coe_inj @[simp] theorem map_smul (c : 𝕜) (x : V) : e (c • x) = ‖c‖₊ * e x := le_antisymm (e.map_smul_le' c x) <| by by_cases hc : c = 0; · simp [hc] calc (‖c‖₊ : ℝ≥0∞) * e x = ‖c‖₊ * e (c⁻¹ • c • x) := by rw [inv_smul_smul₀ hc] _ ≤ ‖c‖₊ * (‖c⁻¹‖₊ * e (c • x)) := _ _ = e (c • x) := _ · exact mul_le_mul_left' (e.map_smul_le' _ _) _ · rw [← mul_assoc, nnnorm_inv, ENNReal.coe_inv, ENNReal.mul_inv_cancel _ ENNReal.coe_ne_top, one_mul] <;> simp [hc] #align enorm.map_smul Enorm.map_smul @[simp] theorem map_zero : e 0 = 0 := by rw [← zero_smul 𝕜 (0 : V), e.map_smul] norm_num #align enorm.map_zero Enorm.map_zero @[simp] theorem eq_zero_iff {x : V} : e x = 0 ↔ x = 0 := ⟨e.eq_zero' x, fun h => h.symm ▸ e.map_zero⟩ #align enorm.eq_zero_iff Enorm.eq_zero_iff @[simp] theorem map_neg (x : V) : e (-x) = e x := calc e (-x) = ‖(-1 : 𝕜)‖₊ * e x := by rw [← map_smul, neg_one_smul] _ = e x := by simp #align enorm.map_neg Enorm.map_neg theorem map_sub_rev (x y : V) : e (x - y) = e (y - x) := by rw [← neg_sub, e.map_neg] #align enorm.map_sub_rev Enorm.map_sub_rev theorem map_add_le (x y : V) : e (x + y) ≤ e x + e y := e.map_add_le' x y #align enorm.map_add_le Enorm.map_add_le theorem map_sub_le (x y : V) : e (x - y) ≤ e x + e y := calc e (x - y) = e (x + -y) := by rw [sub_eq_add_neg] _ ≤ e x + e (-y) := (e.map_add_le x (-y)) _ = e x + e y := by rw [e.map_neg] #align enorm.map_sub_le Enorm.map_sub_le instance : PartialOrder (Enorm 𝕜 V) where le e₁ e₂ := ∀ x, e₁ x ≤ e₂ x le_refl e x := le_rfl le_trans e₁ e₂ e₃ h₁₂ h₂₃ x := le_trans (h₁₂ x) (h₂₃ x) le_antisymm e₁ e₂ h₁₂ h₂₁ := ext fun x => le_antisymm (h₁₂ x) (h₂₁ x) /-- The `enorm` sending each non-zero vector to infinity. -/ noncomputable instance : Top (Enorm 𝕜 V) := ⟨{ toFun := fun x => if x = 0 then 0 else ⊤ eq_zero' := fun x => by split_ifs <;> simp [*] map_add_le' := fun x y => by split_ifs with hxy hx hy hy hx hy hy <;> try simp [*] simpa [hx, hy] using hxy map_smul_le' := fun c x => by split_ifs with hcx hx hx <;> simp only [smul_eq_zero, not_or] at hcx · simp only [MulZeroClass.mul_zero, le_refl] · have : c = 0 := by tauto simp [this] · tauto · simp [hcx.1] }⟩ noncomputable instance : Inhabited (Enorm 𝕜 V) := ⟨⊤⟩ theorem top_map {x : V} (hx : x ≠ 0) : (⊤ : Enorm 𝕜 V) x = ⊤ := if_neg hx #align enorm.top_map Enorm.top_map noncomputable instance : OrderTop (Enorm 𝕜 V) where top := ⊤ le_top e x := if h : x = 0 then by simp [h] else by simp [top_map h] noncomputable instance : SemilatticeSup (Enorm 𝕜 V) := { Enorm.partialOrder with le := (· ≤ ·) lt := (· < ·) sup := fun e₁ e₂ => { toFun := fun x => max (e₁ x) (e₂ x) eq_zero' := fun x h => e₁.eq_zero_iff.1 (ENNReal.max_eq_zero_iff.1 h).1 map_add_le' := fun x y => max_le (le_trans (e₁.map_add_le _ _) <| add_le_add (le_max_left _ _) (le_max_left _ _)) (le_trans (e₂.map_add_le _ _) <| add_le_add (le_max_right _ _) (le_max_right _ _)) map_smul_le' := fun c x => le_of_eq <| by simp only [map_smul, ENNReal.mul_max] } le_sup_left := fun e₁ e₂ x => le_max_left _ _ le_sup_right := fun e₁ e₂ x => le_max_right _ _ sup_le := fun e₁ e₂ e₃ h₁ h₂ x => max_le (h₁ x) (h₂ x) } @[simp, norm_cast] theorem coe_max (e₁ e₂ : Enorm 𝕜 V) : ⇑(e₁ ⊔ e₂) = fun x => max (e₁ x) (e₂ x) := rfl #align enorm.coe_max Enorm.coe_max @[norm_cast] theorem max_map (e₁ e₂ : Enorm 𝕜 V) (x : V) : (e₁ ⊔ e₂) x = max (e₁ x) (e₂ x) := rfl #align enorm.max_map Enorm.max_map /-- Structure of an `emetric_space` defined by an extended norm. -/ @[reducible] def emetricSpace : EMetricSpace V where edist x y := e (x - y) edist_self x := by simp eq_of_edist_eq_zero x y := by simp [sub_eq_zero] edist_comm := e.map_sub_rev edist_triangle x y z := calc e (x - z) = e (x - y + (y - z)) := by rw [sub_add_sub_cancel] _ ≤ e (x - y) + e (y - z) := e.map_add_le (x - y) (y - z) #align enorm.emetric_space Enorm.emetricSpace /-- The subspace of vectors with finite enorm. -/ def finiteSubspace : Subspace 𝕜 V where carrier := { x | e x < ⊤ } zero_mem' := by simp add_mem' x y hx hy := lt_of_le_of_lt (e.map_add_le x y) (ENNReal.add_lt_top.2 ⟨hx, hy⟩) smul_mem' c x (hx : _ < _) := calc e (c • x) = ‖c‖₊ * e x := e.map_smul c x _ < ⊤ := ENNReal.mul_lt_top ENNReal.coe_ne_top hx.Ne #align enorm.finite_subspace Enorm.finiteSubspace /-- Metric space structure on `e.finite_subspace`. We use `emetric_space.to_metric_space` to ensure that this definition agrees with `e.emetric_space`. -/ instance : MetricSpace e.finiteSubspace := by letI := e.emetric_space refine' EMetricSpace.toMetricSpace fun x y => _ change e (x - y) ≠ ⊤ exact ne_top_of_le_ne_top (ENNReal.add_lt_top.2 ⟨x.2, y.2⟩).Ne (e.map_sub_le x y) theorem finite_dist_eq (x y : e.finiteSubspace) : dist x y = (e (x - y)).toReal := rfl #align enorm.finite_dist_eq Enorm.finite_dist_eq theorem finite_edist_eq (x y : e.finiteSubspace) : edist x y = e (x - y) := rfl #align enorm.finite_edist_eq Enorm.finite_edist_eq /-- Normed group instance on `e.finite_subspace`. -/ instance : NormedAddCommGroup e.finiteSubspace := { finiteSubspace.metricSpace e, Submodule.addCommGroup _ with norm := fun x => (e x).toReal dist_eq := fun x y => rfl } theorem finite_norm_eq (x : e.finiteSubspace) : ‖x‖ = (e x).toReal := rfl #align enorm.finite_norm_eq Enorm.finite_norm_eq /-- Normed space instance on `e.finite_subspace`. -/ instance : NormedSpace 𝕜 e.finiteSubspace where norm_smul_le c x := le_of_eq <| by simp [finite_norm_eq, ENNReal.toReal_mul] end Enorm
[STATEMENT] lemma ball_tsp_P3: fixes P1 :: "sterm \<Rightarrow> bool" and P2 :: "sterm \<Rightarrow> fVariable \<Rightarrow> fVariable \<Rightarrow> bool" and P3 :: "sterm \<Rightarrow> bool" and f :: "Label -~> sterm" assumes "\<And>t. \<lbrakk> P1 t; \<forall>s p. s \<notin> L \<and> p \<notin> L \<and> s \<noteq> p \<longrightarrow> P2 t s p \<rbrakk> \<Longrightarrow> P3 t" and "\<forall>l\<in>dom f. P1 (the(f l))" and "\<forall>l\<in>dom f. \<forall>s p. s \<notin> L \<and> p \<notin> L \<and> s \<noteq> p \<longrightarrow> P2 (the(f l)) s p" shows "\<forall>l\<in>dom f. P3 (the(f l))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<forall>l\<in>dom f. P3 (the (f l)) [PROOF STEP] proof (intro strip) [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>l. l \<in> dom f \<Longrightarrow> P3 (the (f l)) [PROOF STEP] fix l [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>l. l \<in> dom f \<Longrightarrow> P3 (the (f l)) [PROOF STEP] assume "l \<in> dom f" [PROOF STATE] proof (state) this: l \<in> dom f goal (1 subgoal): 1. \<And>l. l \<in> dom f \<Longrightarrow> P3 (the (f l)) [PROOF STEP] with assms(2) [PROOF STATE] proof (chain) picking this: \<forall>l\<in>dom f. P1 (the (f l)) l \<in> dom f [PROOF STEP] have "P1 (the(f l))" [PROOF STATE] proof (prove) using this: \<forall>l\<in>dom f. P1 (the (f l)) l \<in> dom f goal (1 subgoal): 1. P1 (the (f l)) [PROOF STEP] by blast [PROOF STATE] proof (state) this: P1 (the (f l)) goal (1 subgoal): 1. \<And>l. l \<in> dom f \<Longrightarrow> P3 (the (f l)) [PROOF STEP] moreover [PROOF STATE] proof (state) this: P1 (the (f l)) goal (1 subgoal): 1. \<And>l. l \<in> dom f \<Longrightarrow> P3 (the (f l)) [PROOF STEP] from assms(3) \<open>l \<in> dom f\<close> [PROOF STATE] proof (chain) picking this: \<forall>l\<in>dom f. \<forall>s p. s \<notin> L \<and> p \<notin> L \<and> s \<noteq> p \<longrightarrow> P2 (the (f l)) s p l \<in> dom f [PROOF STEP] have "\<forall>s p. s \<notin> L \<and> p \<notin> L \<and> s \<noteq> p \<longrightarrow> P2 (the(f l)) s p" [PROOF STATE] proof (prove) using this: \<forall>l\<in>dom f. \<forall>s p. s \<notin> L \<and> p \<notin> L \<and> s \<noteq> p \<longrightarrow> P2 (the (f l)) s p l \<in> dom f goal (1 subgoal): 1. \<forall>s p. s \<notin> L \<and> p \<notin> L \<and> s \<noteq> p \<longrightarrow> P2 (the (f l)) s p [PROOF STEP] by blast [PROOF STATE] proof (state) this: \<forall>s p. s \<notin> L \<and> p \<notin> L \<and> s \<noteq> p \<longrightarrow> P2 (the (f l)) s p goal (1 subgoal): 1. \<And>l. l \<in> dom f \<Longrightarrow> P3 (the (f l)) [PROOF STEP] ultimately [PROOF STATE] proof (chain) picking this: P1 (the (f l)) \<forall>s p. s \<notin> L \<and> p \<notin> L \<and> s \<noteq> p \<longrightarrow> P2 (the (f l)) s p [PROOF STEP] show "P3 (the(f l))" [PROOF STATE] proof (prove) using this: P1 (the (f l)) \<forall>s p. s \<notin> L \<and> p \<notin> L \<and> s \<noteq> p \<longrightarrow> P2 (the (f l)) s p goal (1 subgoal): 1. P3 (the (f l)) [PROOF STEP] using assms(1) [PROOF STATE] proof (prove) using this: P1 (the (f l)) \<forall>s p. s \<notin> L \<and> p \<notin> L \<and> s \<noteq> p \<longrightarrow> P2 (the (f l)) s p \<lbrakk>P1 ?t; \<forall>s p. s \<notin> L \<and> p \<notin> L \<and> s \<noteq> p \<longrightarrow> P2 ?t s p\<rbrakk> \<Longrightarrow> P3 ?t goal (1 subgoal): 1. P3 (the (f l)) [PROOF STEP] by simp [PROOF STATE] proof (state) this: P3 (the (f l)) goal: No subgoals! [PROOF STEP] qed
#!/usr/bin/env stack -- stack --resolver lts-5.15 --install-ghc runghc --package hmatrix --package MonadRandom -- FROM: https://github.com/mstksg/inCode/blob/master/code-samples/dependent-haskell/NetworkUntyped.hs {-# LANGUAGE BangPatterns #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE ScopedTypeVariables #-} import Control.Monad import Control.Monad.Random import Data.List import Data.Maybe import Numeric.LinearAlgebra import System.Environment import Text.Read data Weights = W { wBiases :: !(Vector Double) -- n , wNodes :: !(Matrix Double) -- n x m } -- "m to n" layer data Network = Last !Weights | Link !Weights Network logistic :: Floating a => a -> a logistic x = 1 / (1 + exp (-x)) logistic' :: Floating a => a -> a logistic' x = logix * (1 - logix) where logix = logistic x runLayer :: Weights -> Vector Double -> Vector Double runLayer (W wB wN) v = wB + wN #> v runNet :: Network -> Vector Double -> Vector Double runNet (O w) !v = logistic (runLayer w v) runNet (w :&~ n') !v = let v' = logistic (runLayer w v) in runNet n' v' randomWeights :: MonadRandom m => Int -> Int -> m Weights randomWeights i o = do seed1 :: Int <- getRandom seed2 :: Int <- getRandom let wB = randomVector seed1 Uniform o * 2 - 1 wN = uniformSample seed2 o (replicate i (-1, 1)) return $ W wB wN randomNet :: MonadRandom m => Int -> [Int] -> Int -> m Network randomNet i [] o = O <$> randomWeights i o randomNet i (h:hs) o = (:&~) <$> randomWeights i h <*> randomNet h hs o train :: Double -- ^ learning rate -> Vector Double -- ^ input vector -> Vector Double -- ^ target vector -> Network -- ^ network to train -> Network train rate x0 target = fst . go x0 where go :: Vector Double -- ^ input vector -> Network -- ^ network to train -> (Network, Vector Double) -- handle the output layer go !x (O w@(W wB wN)) = let y = runLayer w x o = logistic y -- the gradient (how much y affects the error) -- (logistic' is the derivative of logistic) dEdy = logistic' y * (o - target) -- new bias weights and node weights wB' = wB - scale rate dEdy wN' = wN - scale rate (dEdy `outer` x) w' = W wB' wN' -- bundle of derivatives for next step dWs = tr wN #> dEdy in (O w', dWs) -- handle the inner layers go !x (w@(W wB wN) :&~ n) = let y = runLayer w x o = logistic y -- get dWs', bundle of derivatives from rest of the net (n', dWs') = go o n -- the gradient (how much y affects the error) dEdy = logistic' y * dWs' -- new bias weights and node weights wB' = wB - scale rate dEdy wN' = wN - scale rate (dEdy `outer` x) w' = W wB' wN' -- bundle of derivatives for next step dWs = tr wN #> dEdy in (w' :&~ n', dWs) netTest :: MonadRandom m => Double -> Int -> m String netTest rate n = do inps <- replicateM n $ do s <- getRandom return $ randomVector s Uniform 2 * 2 - 1 let outs = flip map inps $ \v -> if v `inCircle` (fromRational 0.33, 0.33) || v `inCircle` (fromRational (-0.33), 0.33) then fromRational 1 else fromRational 0 net0 <- randomNet 2 [16,8] 1 let trained = foldl' trainEach net0 (zip inps outs) where trainEach :: Network -> (Vector Double, Vector Double) -> Network trainEach nt (i, o) = train rate i o nt outMat = [ [ render (norm_2 (runNet trained (vector [x / 25 - 1,y / 10 - 1]))) | x <- [0..50] ] | y <- [0..20] ] render r | r <= 0.2 = ' ' | r <= 0.4 = '.' | r <= 0.6 = '-' | r <= 0.8 = '=' | otherwise = '#' return $ unlines outMat where inCircle :: Vector Double -> (Vector Double, Double) -> Bool v `inCircle` (o, r) = norm_2 (v - o) <= r main :: IO () main = do args <- getArgs let n = readMaybe =<< (args !!? 0) rate = readMaybe =<< (args !!? 1) putStrLn "Training network..." putStrLn =<< evalRandIO (netTest (fromMaybe 0.25 rate) (fromMaybe 500000 n ) ) (!!?) :: [a] -> Int -> Maybe a xs !!? i = listToMaybe (drop i xs)
Require Import HoTT.Types.Universe HoTT.Basics.Decidable HoTT.Classes.interfaces.abstract_algebra HoTT.Classes.interfaces.integers HoTT.Classes.interfaces.naturals HoTT.Classes.interfaces.rationals HoTT.Classes.interfaces.orders HoTT.Classes.implementations.natpair_integers HoTT.Classes.theory.rings HoTT.Classes.theory.integers HoTT.Classes.theory.dec_fields HoTT.Classes.orders.dec_fields HoTT.Classes.theory.rationals HoTT.Classes.orders.lattices HoTT.Classes.theory.additional_operations HoTT.Classes.theory.premetric HoTT.Classes.implementations.assume_rationals HoTTClasses.cauchy_completion. Require Export HoTTClasses.cauchy_reals.base HoTTClasses.cauchy_reals.abs HoTTClasses.cauchy_reals.order. Local Set Universe Minimization ToSet. Lemma equiv_0_metric' : forall e u, close e u 0 -> abs u < rat (' e). Proof. intros e u;revert u e;apply (C_ind0 _ (fun u => forall e, _ -> _)). - intros q e E. rewrite (equiv_eta_eta_def _) in E. apply Qclose_alt in E. rewrite negate_0,plus_0_r in E. apply rat_lt_preserving. trivial. - intros x IH e xi. apply rounded in xi. revert xi. apply (Trunc_ind _);intros [d [d' [He xi]]]. rewrite (equiv_lim_eta_def _) in xi. revert xi;apply (Trunc_ind _);intros [n [n' [Hd E1]]]. apply IH in E1. rewrite He,Hd. assert (Hrw : (' (n + n' + d')) = ' n' + ' (n + d')) by ring_tac.ring_with_nat. rewrite Hrw;clear Hrw. apply (Rlt_close_rat_plus _ _ E1). apply (non_expanding abs). rewrite qpos_plus_comm. apply (equiv_lim _). Qed. Definition equiv_0_metric@{} := equiv_0_metric'@{UQ UQ}. Lemma equiv_to_metric@{} : forall e u v, close e u v -> abs (u - v) < rat (' e). Proof. intros e u v xi. rewrite <-Rabs_idempotent. apply equiv_0_metric. rewrite <-(Rabs_of_0' (v - v));[|apply right_inverse]. apply (non_expanding (fun w => abs (w - v))). trivial. Qed. Lemma metric_to_equiv_rat_lim@{} (q : Q) (y : Approximation real) (IHy : forall e e0 : Q+, abs (rat q - y e) < rat (' e0) -> close e0 (rat q) (y e)) (e : Q+) (E1 : abs (rat q - lim y) < rat (' e)) : close e (rat q) (lim y). Proof. generalize (R_archimedean _ _ E1). apply (Trunc_ind _);intros [d [E2 E3]]. apply rat_lt_reflecting in E3. pose proof (snd (flip_pos_minus _ _) E3) as E4. assert (Hd : 0 < d). { revert E2;apply (Trunc_ind _). intros [s [s' [F1 [F2 F3]]]]. apply rat_le_reflecting in F3. apply lt_le_trans with s';trivial. apply le_lt_trans with s;trivial. apply rat_le_reflecting. transitivity (abs (rat q - lim y));trivial. apply Rabs_nonneg. } pose (D := mkQpos d Hd). pose (ED := mkQpos _ E4). assert (Hrw : e = D + (ED / 4 + ED / 4) + (ED / 4 + ED / 4)). { path_via (D + ED). { apply pos_eq;unfold D, ED. abstract ring_tac.ring_with_integers (NatPair.Z nat). } path_via (D + 4 / 4 * ED). { rewrite pos_recip_r,Qpos_mult_1_l;trivial. } apply pos_eq;abstract ring_tac.ring_with_nat. } rewrite Hrw. eapply (equiv_triangle _);[|apply (equiv_lim _)]. apply IHy. apply (Rlt_close_rat_plus _ _ E2). apply (non_expanding (fun u => abs (rat q - u))). apply (equiv_symm _),(equiv_lim _). Qed. Lemma metric_to_equiv_lim_lim@{} (x : Approximation real) (IHx : forall (e : Q+) (v : real) (e0 : Q+), abs (x e - v) < rat (' e0) -> close e0 (x e) v) (y : Approximation real) (IHy : forall e e0 : Q+, abs (lim x - y e) < rat (' e0) -> close e0 (lim x) (y e)) (e : Q+) (E1 : abs (lim x - lim y) < rat (' e)) : close e (lim x) (lim y). Proof. generalize (R_archimedean _ _ E1). apply (Trunc_ind _);intros [d [E2 E3]]. apply rat_lt_reflecting in E3. pose proof (snd (flip_pos_minus _ _) E3) as E4. assert (Hd : 0 < d). { revert E2;apply (Trunc_ind _). intros [s [s' [F1 [F2 F3]]]]. apply rat_le_reflecting in F3. apply lt_le_trans with s';trivial. apply le_lt_trans with s;trivial. apply rat_le_reflecting. transitivity (abs (lim x - lim y));trivial. apply Rabs_nonneg. } pose (D := mkQpos d Hd). pose (ED := mkQpos _ E4). assert (Hrw : e = D + (ED / 4 + ED / 4) + (ED / 4 + ED / 4)). { path_via (D + ED). { apply pos_eq;unfold D, ED. abstract ring_tac.ring_with_integers (NatPair.Z nat). } path_via (D + 4 / 4 * ED). { rewrite pos_recip_r,Qpos_mult_1_l;trivial. } apply pos_eq;abstract ring_tac.ring_with_nat. } rewrite Hrw. eapply (equiv_triangle _);[|apply (equiv_lim _)]. apply IHy. apply (Rlt_close_rat_plus _ _ E2). apply (non_expanding (fun u => abs (lim x - u))). apply (equiv_symm _),(equiv_lim _). Qed. Lemma metric_to_equiv@{} : forall e u v, abs (u - v) < rat (' e) -> close e u v. Proof. intros e u v;revert u v e;apply (C_ind0 _ (fun u => forall v e, _ -> _)); [intros q|intros x IHx]; (apply (C_ind0 _ (fun v => forall e, _ -> _));[intros r|intros y IHy]); intros e E1. - apply equiv_eta_eta. apply Qclose_alt. apply rat_lt_reflecting,E1. - apply metric_to_equiv_rat_lim;auto. - apply (equiv_symm _),metric_to_equiv_rat_lim. + intros n n' E;apply (equiv_symm _),IHx. rewrite Rabs_neg_flip. trivial. + rewrite Rabs_neg_flip. trivial. - apply metric_to_equiv_lim_lim;auto. Qed. Lemma equiv_metric_applied_rw' : forall e u v, close e u v = (abs (u - v) < rat (' e)). Proof. intros. apply TruncType.path_iff_ishprop_uncurried. split. - apply equiv_to_metric. - apply metric_to_equiv. Qed. Definition equiv_metric_applied_rw@{} := equiv_metric_applied_rw'@{Ularge}. Lemma equiv_metric_rw' : close = fun e u v => abs (u - v) < rat (' e). Proof. repeat (apply path_forall;intro). apply equiv_metric_applied_rw. Qed. Definition equiv_metric_rw@{} := equiv_metric_rw'.
import Preloaded Solution theorem task_1 : TASK_1 := one_plus_one_is_three #print axioms task_1 theorem task_2 : TASK_2 := two_plus_two_is_five #print axioms task_2
------------------------------------------------------------------------ -- Isomorphisms and equalities relating an arbitrary "equality with J" -- to path equality, along with a proof of extensionality for the -- "equality with J" ------------------------------------------------------------------------ {-# OPTIONS --erased-cubical --safe #-} import Equality.Path as P module Equality.Path.Isomorphisms {e⁺} (eq : ∀ {a p} → P.Equality-with-paths a p e⁺) where open P.Derived-definitions-and-properties eq open import Prelude import Bijection import Embedding import Equivalence import Equivalence.Contractible-preimages import Equivalence.Half-adjoint import Function-universe import H-level import Surjection import Univalence-axiom private module B = Bijection equality-with-J module CP = Equivalence.Contractible-preimages equality-with-J module HA = Equivalence.Half-adjoint equality-with-J module Eq = Equivalence equality-with-J module F = Function-universe equality-with-J module PB = Bijection P.equality-with-J module PM = Embedding P.equality-with-J module PE = Equivalence P.equality-with-J module PCP = Equivalence.Contractible-preimages P.equality-with-J module PHA = Equivalence.Half-adjoint P.equality-with-J module PF = Function-universe P.equality-with-J module PH = H-level P.equality-with-J module PS = Surjection P.equality-with-J module PU = Univalence-axiom P.equality-with-J open B using (_↔_) open Embedding equality-with-J hiding (id; _∘_) open Eq using (_≃_; Is-equivalence) open F hiding (id; _∘_) open H-level equality-with-J open Surjection equality-with-J using (_↠_) open Univalence-axiom equality-with-J private variable a b c p q ℓ : Level A : Type a B : A → Type b u v x y z : A f g h : (x : A) → B x n : ℕ ------------------------------------------------------------------------ -- Extensionality -- The proof bad-ext is perhaps not less "good" than ext (I don't -- know), it is called this simply because it is not defined using -- good-ext. bad-ext : Extensionality a b apply-ext bad-ext {f = f} {g = g} = (∀ x → f x ≡ g x) ↝⟨ (λ p x → _↔_.to ≡↔≡ (p x)) ⟩ (∀ x → f x P.≡ g x) ↝⟨ P.apply-ext P.ext ⟩ f P.≡ g ↔⟨ inverse ≡↔≡ ⟩□ f ≡ g □ -- Extensionality. ext : Extensionality a b ext = Eq.good-ext bad-ext ⟨ext⟩ : Extensionality′ A B ⟨ext⟩ = apply-ext ext abstract -- The function ⟨ext⟩ is an equivalence. ext-is-equivalence : Is-equivalence {A = ∀ x → f x ≡ g x} ⟨ext⟩ ext-is-equivalence = Eq.good-ext-is-equivalence bad-ext -- Equality rearrangement lemmas for ⟨ext⟩. ext-refl : ⟨ext⟩ (λ x → refl (f x)) ≡ refl f ext-refl = Eq.good-ext-refl bad-ext _ ext-const : (x≡y : x ≡ y) → ⟨ext⟩ (const {B = A} x≡y) ≡ cong const x≡y ext-const = Eq.good-ext-const bad-ext cong-ext : ∀ (f≡g : ∀ x → f x ≡ g x) {x} → cong (_$ x) (⟨ext⟩ f≡g) ≡ f≡g x cong-ext = Eq.cong-good-ext bad-ext ext-cong : {B : Type b} {C : B → Type c} {f : A → (x : B) → C x} {x≡y : x ≡ y} → ⟨ext⟩ (λ z → cong (flip f z) x≡y) ≡ cong f x≡y ext-cong = Eq.good-ext-cong bad-ext subst-ext : ∀ {f g : (x : A) → B x} (P : B x → Type p) {p} (f≡g : ∀ x → f x ≡ g x) → subst (λ f → P (f x)) (⟨ext⟩ f≡g) p ≡ subst P (f≡g x) p subst-ext = Eq.subst-good-ext bad-ext elim-ext : (P : B x → B x → Type p) (p : (y : B x) → P y y) {f g : (x : A) → B x} (f≡g : ∀ x → f x ≡ g x) → elim (λ {f g} _ → P (f x) (g x)) (p ∘ (_$ x)) (⟨ext⟩ f≡g) ≡ elim (λ {x y} _ → P x y) p (f≡g x) elim-ext = Eq.elim-good-ext bad-ext -- I based the statements of the following three lemmas on code in -- the Lean Homotopy Type Theory Library with Jakob von Raumer and -- Floris van Doorn listed as authors. The file was claimed to have -- been ported from the Coq HoTT library. (The third lemma has later -- been generalised.) ext-sym : (f≡g : ∀ x → f x ≡ g x) → ⟨ext⟩ (sym ∘ f≡g) ≡ sym (⟨ext⟩ f≡g) ext-sym = Eq.good-ext-sym bad-ext ext-trans : (f≡g : ∀ x → f x ≡ g x) (g≡h : ∀ x → g x ≡ h x) → ⟨ext⟩ (λ x → trans (f≡g x) (g≡h x)) ≡ trans (⟨ext⟩ f≡g) (⟨ext⟩ g≡h) ext-trans = Eq.good-ext-trans bad-ext cong-post-∘-ext : (f≡g : ∀ x → f x ≡ g x) → cong (h ∘_) (⟨ext⟩ f≡g) ≡ ⟨ext⟩ (cong h ∘ f≡g) cong-post-∘-ext = Eq.cong-post-∘-good-ext bad-ext bad-ext cong-pre-∘-ext : (f≡g : ∀ x → f x ≡ g x) → cong (_∘ h) (⟨ext⟩ f≡g) ≡ ⟨ext⟩ (f≡g ∘ h) cong-pre-∘-ext = Eq.cong-pre-∘-good-ext bad-ext bad-ext cong-∘-ext : {A : Type a} {B : Type b} {C : Type c} {f g : B → C} (f≡g : ∀ x → f x ≡ g x) → cong {B = (A → B) → (A → C)} (λ f → f ∘_) (⟨ext⟩ f≡g) ≡ ⟨ext⟩ λ h → ⟨ext⟩ λ x → f≡g (h x) cong-∘-ext = Eq.cong-∘-good-ext bad-ext bad-ext bad-ext ------------------------------------------------------------------------ -- More isomorphisms and related properties -- Split surjections expressed using equality are equivalent to split -- surjections expressed using paths. ↠≃↠ : {A : Type a} {B : Type b} → (A ↠ B) ≃ (A PS.↠ B) ↠≃↠ = Eq.↔→≃ (λ A↠B → record { logical-equivalence = _↠_.logical-equivalence A↠B ; right-inverse-of = _↔_.to ≡↔≡ ∘ _↠_.right-inverse-of A↠B }) (λ A↠B → record { logical-equivalence = PS._↠_.logical-equivalence A↠B ; right-inverse-of = _↔_.from ≡↔≡ ∘ PS._↠_.right-inverse-of A↠B }) (λ A↠B → cong (λ r → record { logical-equivalence = PS._↠_.logical-equivalence A↠B ; right-inverse-of = r }) $ ⟨ext⟩ λ _ → _↔_.right-inverse-of ≡↔≡ _) (λ A↠B → cong (λ r → record { logical-equivalence = _↠_.logical-equivalence A↠B ; right-inverse-of = r }) $ ⟨ext⟩ λ _ → _↔_.left-inverse-of ≡↔≡ _) private -- Bijections expressed using paths can be converted into bijections -- expressed using equality. ↔→↔ : {A B : Type ℓ} → A PB.↔ B → A ↔ B ↔→↔ A↔B = record { surjection = _≃_.from ↠≃↠ $ PB._↔_.surjection A↔B ; left-inverse-of = _↔_.from ≡↔≡ ∘ PB._↔_.left-inverse-of A↔B } -- Bijections expressed using equality are equivalent to bijections -- expressed using paths. ↔≃↔ : {A : Type a} {B : Type b} → (A ↔ B) ≃ (A PB.↔ B) ↔≃↔ {A = A} {B = B} = A ↔ B ↔⟨ B.↔-as-Σ ⟩ (∃ λ (f : A → B) → ∃ λ (f⁻¹ : B → A) → (∀ x → f (f⁻¹ x) ≡ x) × (∀ x → f⁻¹ (f x) ≡ x)) ↔⟨ (∃-cong λ _ → ∃-cong λ _ → (∀-cong ext λ _ → ≡↔≡) ×-cong (∀-cong ext λ _ → ≡↔≡)) ⟩ (∃ λ (f : A → B) → ∃ λ (f⁻¹ : B → A) → (∀ x → f (f⁻¹ x) P.≡ x) × (∀ x → f⁻¹ (f x) P.≡ x)) ↔⟨ inverse $ ↔→↔ $ PB.↔-as-Σ ⟩□ A PB.↔ B □ -- H-level expressed using equality is isomorphic to H-level expressed -- using paths. H-level↔H-level : ∀ n → H-level n A ↔ PH.H-level n A H-level↔H-level {A = A} zero = H-level 0 A ↔⟨⟩ (∃ λ (x : A) → ∀ y → x ≡ y) ↝⟨ (∃-cong λ _ → ∀-cong ext λ _ → ≡↔≡) ⟩ (∃ λ (x : A) → ∀ y → x P.≡ y) ↔⟨⟩ PH.H-level 0 A □ H-level↔H-level {A = A} (suc n) = H-level (suc n) A ↝⟨ inverse $ ≡↔+ _ ext ⟩ (∀ x y → H-level n (x ≡ y)) ↝⟨ (∀-cong ext λ _ → ∀-cong ext λ _ → H-level-cong ext _ ≡↔≡) ⟩ (∀ x y → H-level n (x P.≡ y)) ↝⟨ (∀-cong ext λ _ → ∀-cong ext λ _ → H-level↔H-level n) ⟩ (∀ x y → PH.H-level n (x P.≡ y)) ↝⟨ ↔→↔ $ PF.≡↔+ _ P.ext ⟩ PH.H-level (suc n) A □ -- CP.Is-equivalence is isomorphic to PCP.Is-equivalence. Is-equivalence-CP↔Is-equivalence-CP : CP.Is-equivalence f ↔ PCP.Is-equivalence f Is-equivalence-CP↔Is-equivalence-CP {f = f} = CP.Is-equivalence f ↔⟨⟩ (∀ y → Contractible (∃ λ x → f x ≡ y)) ↝⟨ (∀-cong ext λ _ → H-level-cong ext _ $ ∃-cong λ _ → ≡↔≡) ⟩ (∀ y → Contractible (∃ λ x → f x P.≡ y)) ↝⟨ (∀-cong ext λ _ → H-level↔H-level _) ⟩ (∀ y → P.Contractible (∃ λ x → f x P.≡ y)) ↔⟨⟩ PCP.Is-equivalence f □ -- Is-equivalence expressed using equality is isomorphic to -- Is-equivalence expressed using paths. Is-equivalence↔Is-equivalence : Is-equivalence f ↔ PE.Is-equivalence f Is-equivalence↔Is-equivalence {f = f} = Is-equivalence f ↝⟨ HA.Is-equivalence↔Is-equivalence-CP ext ⟩ CP.Is-equivalence f ↝⟨ Is-equivalence-CP↔Is-equivalence-CP ⟩ PCP.Is-equivalence f ↝⟨ inverse $ ↔→↔ $ PHA.Is-equivalence↔Is-equivalence-CP P.ext ⟩□ PE.Is-equivalence f □ -- The type of equivalences, expressed using equality, is isomorphic -- to the type of equivalences, expressed using paths. ≃↔≃ : {A : Type a} {B : Type b} → A ≃ B ↔ A PE.≃ B ≃↔≃ {A = A} {B = B} = A ≃ B ↝⟨ Eq.≃-as-Σ ⟩ ∃ Is-equivalence ↝⟨ (∃-cong λ _ → Is-equivalence↔Is-equivalence) ⟩ ∃ PE.Is-equivalence ↝⟨ inverse $ ↔→↔ PE.≃-as-Σ ⟩□ A PE.≃ B □ private -- ≃↔≃ computes in the "right" way. to-≃↔≃ : {A : Type a} {B : Type b} {A≃B : A ≃ B} → PE._≃_.logical-equivalence (_↔_.to ≃↔≃ A≃B) ≡ _≃_.logical-equivalence A≃B to-≃↔≃ = refl _ from-≃↔≃ : {A : Type a} {B : Type b} {A≃B : A PE.≃ B} → _≃_.logical-equivalence (_↔_.from ≃↔≃ A≃B) ≡ PE._≃_.logical-equivalence A≃B from-≃↔≃ = refl _ -- The type of equivalences, expressed using "contractible preimages" -- and equality, is isomorphic to the type of equivalences, expressed -- using contractible preimages and paths. ≃-CP↔≃-CP : {A : Type a} {B : Type b} → A CP.≃ B ↔ A PCP.≃ B ≃-CP↔≃-CP {A = A} {B = B} = ∃ CP.Is-equivalence ↝⟨ (∃-cong λ _ → Is-equivalence-CP↔Is-equivalence-CP) ⟩□ ∃ PCP.Is-equivalence □ -- The cong function for paths can be expressed in terms of the cong -- function for equality. cong≡cong : {A : Type a} {B : Type b} {f : A → B} {x y : A} {x≡y : x P.≡ y} → cong f (_↔_.from ≡↔≡ x≡y) ≡ _↔_.from ≡↔≡ (P.cong f x≡y) cong≡cong {f = f} {x≡y = x≡y} = P.elim (λ x≡y → cong f (_↔_.from ≡↔≡ x≡y) ≡ _↔_.from ≡↔≡ (P.cong f x≡y)) (λ x → cong f (_↔_.from ≡↔≡ P.refl) ≡⟨ cong (cong f) from-≡↔≡-refl ⟩ cong f (refl x) ≡⟨ cong-refl _ ⟩ refl (f x) ≡⟨ sym $ from-≡↔≡-refl ⟩ _↔_.from ≡↔≡ P.refl ≡⟨ cong (_↔_.from ≡↔≡) $ sym $ _↔_.from ≡↔≡ $ P.cong-refl f ⟩∎ _↔_.from ≡↔≡ (P.cong f P.refl) ∎) x≡y -- The sym function for paths can be expressed in terms of the sym -- function for equality. sym≡sym : {x≡y : x P.≡ y} → sym (_↔_.from ≡↔≡ x≡y) ≡ _↔_.from ≡↔≡ (P.sym x≡y) sym≡sym {x≡y = x≡y} = P.elim₁ (λ x≡y → sym (_↔_.from ≡↔≡ x≡y) ≡ _↔_.from ≡↔≡ (P.sym x≡y)) (sym (_↔_.from ≡↔≡ P.refl) ≡⟨ cong sym from-≡↔≡-refl ⟩ sym (refl _) ≡⟨ sym-refl ⟩ refl _ ≡⟨ sym from-≡↔≡-refl ⟩ _↔_.from ≡↔≡ P.refl ≡⟨ cong (_↔_.from ≡↔≡) $ sym $ _↔_.from ≡↔≡ P.sym-refl ⟩∎ _↔_.from ≡↔≡ (P.sym P.refl) ∎) x≡y -- The trans function for paths can be expressed in terms of the trans -- function for equality. trans≡trans : {x≡y : x P.≡ y} {y≡z : y P.≡ z} → trans (_↔_.from ≡↔≡ x≡y) (_↔_.from ≡↔≡ y≡z) ≡ _↔_.from ≡↔≡ (P.trans x≡y y≡z) trans≡trans {x≡y = x≡y} {y≡z = y≡z} = P.elim₁ (λ x≡y → trans (_↔_.from ≡↔≡ x≡y) (_↔_.from ≡↔≡ y≡z) ≡ _↔_.from ≡↔≡ (P.trans x≡y y≡z)) (trans (_↔_.from ≡↔≡ P.refl) (_↔_.from ≡↔≡ y≡z) ≡⟨ cong (flip trans _) from-≡↔≡-refl ⟩ trans (refl _) (_↔_.from ≡↔≡ y≡z) ≡⟨ trans-reflˡ _ ⟩ _↔_.from ≡↔≡ y≡z ≡⟨ cong (_↔_.from ≡↔≡) $ sym $ _↔_.from ≡↔≡ $ P.trans-reflˡ _ ⟩∎ _↔_.from ≡↔≡ (P.trans P.refl y≡z) ∎) x≡y -- The type of embeddings, expressed using equality, is isomorphic to -- the type of embeddings, expressed using paths. Embedding↔Embedding : {A : Type a} {B : Type b} → Embedding A B ↔ PM.Embedding A B Embedding↔Embedding {A = A} {B = B} = Embedding A B ↝⟨ Embedding-as-Σ ⟩ (∃ λ f → ∀ x y → Is-equivalence (cong f)) ↔⟨ (∃-cong λ f → ∀-cong ext λ x → ∀-cong ext λ y → Eq.⇔→≃ (Eq.propositional ext _) (Eq.propositional ext _) (λ is → _≃_.is-equivalence $ Eq.with-other-function ( x P.≡ y ↔⟨ inverse ≡↔≡ ⟩ x ≡ y ↝⟨ Eq.⟨ _ , is ⟩ ⟩ f x ≡ f y ↔⟨ ≡↔≡ ⟩□ f x P.≡ f y □) (P.cong f) (λ eq → _↔_.to ≡↔≡ (cong f (_↔_.from ≡↔≡ eq)) ≡⟨ cong (_↔_.to ≡↔≡) cong≡cong ⟩ _↔_.to ≡↔≡ (_↔_.from ≡↔≡ (P.cong f eq)) ≡⟨ _↔_.right-inverse-of ≡↔≡ _ ⟩∎ P.cong f eq ∎)) (λ is → _≃_.is-equivalence $ Eq.with-other-function ( x ≡ y ↔⟨ ≡↔≡ ⟩ x P.≡ y ↝⟨ Eq.⟨ _ , is ⟩ ⟩ f x P.≡ f y ↔⟨ inverse ≡↔≡ ⟩□ f x ≡ f y □) (cong f) (λ eq → _↔_.from ≡↔≡ (P.cong f (_↔_.to ≡↔≡ eq)) ≡⟨ sym cong≡cong ⟩ cong f (_↔_.from ≡↔≡ (_↔_.to ≡↔≡ eq)) ≡⟨ cong (cong f) $ _↔_.left-inverse-of ≡↔≡ _ ⟩∎ cong f eq ∎))) ⟩ (∃ λ f → ∀ x y → Is-equivalence (P.cong f)) ↝⟨ (∃-cong λ _ → ∀-cong ext λ _ → ∀-cong ext λ _ → Is-equivalence↔Is-equivalence) ⟩ (∃ λ f → ∀ x y → PE.Is-equivalence (P.cong f)) ↝⟨ inverse $ ↔→↔ PM.Embedding-as-Σ ⟩□ PM.Embedding A B □ -- The subst function for paths can be expressed in terms of the subst -- function for equality. subst≡subst : ∀ {P : A → Type p} {x≡y : x P.≡ y} {p} → subst P (_↔_.from ≡↔≡ x≡y) p ≡ P.subst P x≡y p subst≡subst {P = P} {x≡y} = P.elim (λ x≡y → ∀ {p} → subst P (_↔_.from ≡↔≡ x≡y) p ≡ P.subst P x≡y p) (λ x {p} → subst P (_↔_.from ≡↔≡ P.refl) p ≡⟨ cong (λ eq → subst P eq p) from-≡↔≡-refl ⟩ subst P (refl x) p ≡⟨ subst-refl _ _ ⟩ p ≡⟨ sym $ _↔_.from ≡↔≡ $ P.subst-refl P _ ⟩∎ P.subst P P.refl p ∎) x≡y -- A "computation" rule for subst≡subst. subst≡subst-refl : ∀ {P : A → Type p} {p : P x} → subst≡subst {x≡y = P.refl} ≡ trans (cong (λ eq → subst P eq p) from-≡↔≡-refl) (trans (subst-refl _ _) (sym $ _↔_.from ≡↔≡ $ P.subst-refl P _)) subst≡subst-refl {P = P} = cong (λ f → f {p = _}) $ _↔_.from ≡↔≡ $ P.elim-refl (λ x≡y → ∀ {p} → subst P (_↔_.from ≡↔≡ x≡y) p ≡ P.subst P x≡y p) (λ _ → trans (cong (λ eq → subst P eq _) from-≡↔≡-refl) (trans (subst-refl _ _) (sym $ _↔_.from ≡↔≡ $ P.subst-refl P _))) -- Some corollaries. subst≡↔subst≡ : ∀ {eq : x P.≡ y} → subst B (_↔_.from ≡↔≡ eq) u ≡ v ↔ P.subst B eq u P.≡ v subst≡↔subst≡ {B = B} {u = u} {v = v} {eq = eq} = subst B (_↔_.from ≡↔≡ eq) u ≡ v ↝⟨ ≡⇒↝ _ $ cong (_≡ _) subst≡subst ⟩ P.subst B eq u ≡ v ↝⟨ ≡↔≡ ⟩□ P.subst B eq u P.≡ v □ subst≡↔[]≡ : {eq : x P.≡ y} → subst B (_↔_.from ≡↔≡ eq) u ≡ v ↔ P.[ (λ i → B (eq i)) ] u ≡ v subst≡↔[]≡ {B = B} {u = u} {v = v} {eq = eq} = subst B (_↔_.from ≡↔≡ eq) u ≡ v ↝⟨ subst≡↔subst≡ ⟩ P.subst B eq u P.≡ v ↝⟨ ↔→↔ $ PB.inverse $ P.heterogeneous↔homogeneous _ ⟩□ P.[ (λ i → B (eq i)) ] u ≡ v □ -- The dcong function for paths can be expressed using dcong for -- equality (up to pointwise equality). dcong≡dcong : {f : (x : A) → B x} {x≡y : x P.≡ y} → _↔_.to subst≡↔subst≡ (dcong f (_↔_.from ≡↔≡ x≡y)) ≡ P.dcong f x≡y dcong≡dcong {B = B} {f = f} {x≡y} = P.elim (λ x≡y → _↔_.to subst≡↔subst≡ (dcong f (_↔_.from ≡↔≡ x≡y)) ≡ P.dcong f x≡y) (λ x → _↔_.to subst≡↔subst≡ (dcong f (_↔_.from ≡↔≡ P.refl)) ≡⟨⟩ _↔_.to ≡↔≡ (_↔_.to (≡⇒↝ _ $ cong (_≡ _) subst≡subst) $ dcong f (_↔_.from ≡↔≡ P.refl)) ≡⟨ cong (_↔_.to ≡↔≡) $ lemma x ⟩ _↔_.to ≡↔≡ (_↔_.from ≡↔≡ $ P.subst-refl B (f x)) ≡⟨ _↔_.right-inverse-of ≡↔≡ _ ⟩ P.subst-refl B (f x) ≡⟨ sym $ _↔_.from ≡↔≡ $ P.dcong-refl f ⟩∎ P.dcong f P.refl ∎) x≡y where lemma : ∀ _ → _ lemma _ = _↔_.to (≡⇒↝ _ $ cong (_≡ _) subst≡subst) (dcong f (_↔_.from ≡↔≡ P.refl)) ≡⟨ sym $ subst-in-terms-of-≡⇒↝ bijection _ _ _ ⟩ subst (_≡ _) subst≡subst (dcong f (_↔_.from ≡↔≡ P.refl)) ≡⟨ cong (λ p → subst (_≡ _) p $ dcong f _) $ sym $ sym-sym _ ⟩ subst (_≡ _) (sym $ sym subst≡subst) (dcong f (_↔_.from ≡↔≡ P.refl)) ≡⟨ subst-trans _ ⟩ trans (sym (subst≡subst {x≡y = P.refl})) (dcong f (_↔_.from ≡↔≡ P.refl)) ≡⟨ cong (λ p → trans (sym p) (dcong f (_↔_.from ≡↔≡ P.refl))) subst≡subst-refl ⟩ trans (sym $ trans (cong (λ eq → subst B eq _) from-≡↔≡-refl) (trans (subst-refl _ _) (sym $ _↔_.from ≡↔≡ $ P.subst-refl B _))) (dcong f (_↔_.from ≡↔≡ P.refl)) ≡⟨ elim₁ (λ {x} p → trans (sym $ trans (cong (λ eq → subst B eq _) p) (trans (subst-refl _ _) (sym $ _↔_.from ≡↔≡ $ P.subst-refl B _))) (dcong f x) ≡ trans (sym $ trans (cong (λ eq → subst B eq _) (refl _)) (trans (subst-refl _ _) (sym $ _↔_.from ≡↔≡ $ P.subst-refl B _))) (dcong f (refl _))) (refl _) from-≡↔≡-refl ⟩ trans (sym $ trans (cong (λ eq → subst B eq _) (refl _)) (trans (subst-refl _ _) (sym $ _↔_.from ≡↔≡ $ P.subst-refl B _))) (dcong f (refl _)) ≡⟨ cong₂ (λ p → trans $ sym $ trans p $ trans (subst-refl _ _) $ sym $ _↔_.from ≡↔≡ $ P.subst-refl B _) (cong-refl _) (dcong-refl _) ⟩ trans (sym $ trans (refl _) (trans (subst-refl _ _) (sym $ _↔_.from ≡↔≡ $ P.subst-refl B _))) (subst-refl B _) ≡⟨ cong (λ p → trans (sym p) (subst-refl _ _)) $ trans-reflˡ _ ⟩ trans (sym $ trans (subst-refl _ _) (sym $ _↔_.from ≡↔≡ $ P.subst-refl B _)) (subst-refl B _) ≡⟨ cong (λ p → trans p (subst-refl _ _)) $ sym-trans _ _ ⟩ trans (trans (sym $ sym $ _↔_.from ≡↔≡ $ P.subst-refl B _) (sym $ subst-refl _ _)) (subst-refl B _) ≡⟨ trans-[trans-sym]- _ _ ⟩ sym $ sym $ _↔_.from ≡↔≡ $ P.subst-refl B _ ≡⟨ sym-sym _ ⟩∎ _↔_.from ≡↔≡ $ P.subst-refl B _ ∎ -- A lemma relating dcong and hcong (for paths). dcong≡hcong : {x≡y : x P.≡ y} (f : (x : A) → B x) → dcong f (_↔_.from ≡↔≡ x≡y) ≡ _↔_.from subst≡↔[]≡ (P.hcong f x≡y) dcong≡hcong {x≡y = x≡y} f = dcong f (_↔_.from ≡↔≡ x≡y) ≡⟨ sym $ _↔_.from-to (inverse subst≡↔subst≡) dcong≡dcong ⟩ _↔_.from subst≡↔subst≡ (P.dcong f x≡y) ≡⟨ cong (_↔_.from subst≡↔subst≡) $ _↔_.from ≡↔≡ $ P.dcong≡hcong f ⟩ _↔_.from subst≡↔subst≡ (PB._↔_.to (P.heterogeneous↔homogeneous _) (P.hcong f x≡y)) ≡⟨⟩ _↔_.from subst≡↔[]≡ (P.hcong f x≡y) ∎ -- Three corollaries, intended to be used in the implementation of -- eliminators for HITs. For some examples, see Interval and -- Quotient.HIT. subst≡→[]≡ : {eq : x P.≡ y} → subst B (_↔_.from ≡↔≡ eq) u ≡ v → P.[ (λ i → B (eq i)) ] u ≡ v subst≡→[]≡ = _↔_.to subst≡↔[]≡ dcong-subst≡→[]≡ : {eq₁ : x P.≡ y} {eq₂ : subst B (_↔_.from ≡↔≡ eq₁) (f x) ≡ f y} → P.hcong f eq₁ ≡ subst≡→[]≡ eq₂ → dcong f (_↔_.from ≡↔≡ eq₁) ≡ eq₂ dcong-subst≡→[]≡ {B = B} {f = f} {eq₁} {eq₂} hyp = dcong f (_↔_.from ≡↔≡ eq₁) ≡⟨ dcong≡hcong f ⟩ _↔_.from subst≡↔[]≡ (P.hcong f eq₁) ≡⟨ cong (_↔_.from subst≡↔[]≡) hyp ⟩ _↔_.from subst≡↔[]≡ (_↔_.to subst≡↔[]≡ eq₂) ≡⟨ _↔_.left-inverse-of subst≡↔[]≡ _ ⟩∎ eq₂ ∎ cong-≡↔≡ : {eq₁ : x P.≡ y} {eq₂ : f x ≡ f y} → P.cong f eq₁ ≡ _↔_.to ≡↔≡ eq₂ → cong f (_↔_.from ≡↔≡ eq₁) ≡ eq₂ cong-≡↔≡ {f = f} {eq₁ = eq₁} {eq₂} hyp = cong f (_↔_.from ≡↔≡ eq₁) ≡⟨ cong≡cong ⟩ _↔_.from ≡↔≡ $ P.cong f eq₁ ≡⟨ cong (_↔_.from ≡↔≡) hyp ⟩ _↔_.from ≡↔≡ $ _↔_.to ≡↔≡ eq₂ ≡⟨ _↔_.left-inverse-of ≡↔≡ _ ⟩∎ eq₂ ∎ ------------------------------------------------------------------------ -- Univalence -- CP.Univalence′ is pointwise equivalent to PCP.Univalence′. Univalence′-CP≃Univalence′-CP : {A B : Type ℓ} → CP.Univalence′ A B ≃ PCP.Univalence′ A B Univalence′-CP≃Univalence′-CP {A = A} {B = B} = ((A≃B : A CP.≃ B) → ∃ λ (x : ∃ λ A≡B → CP.≡⇒≃ A≡B ≡ A≃B) → ∀ y → x ≡ y) ↔⟨⟩ ((A≃B : ∃ λ (f : A → B) → CP.Is-equivalence f) → ∃ λ (x : ∃ λ A≡B → CP.≡⇒≃ A≡B ≡ A≃B) → ∀ y → x ≡ y) ↝⟨ (Π-cong ext (∃-cong λ _ → Is-equivalence-CP↔Is-equivalence-CP) λ A≃B → Σ-cong (lemma₁ A≃B) λ _ → Π-cong ext (lemma₁ A≃B) λ _ → inverse $ Eq.≃-≡ (lemma₁ A≃B)) ⟩ ((A≃B : ∃ λ (f : A → B) → PCP.Is-equivalence f) → ∃ λ (x : ∃ λ A≡B → PCP.≡⇒≃ A≡B ≡ A≃B) → ∀ y → x ≡ y) ↔⟨⟩ ((A≃B : A PCP.≃ B) → ∃ λ (x : ∃ λ A≡B → PCP.≡⇒≃ A≡B ≡ A≃B) → ∀ y → x ≡ y) ↔⟨ Is-equivalence-CP↔Is-equivalence-CP ⟩□ ((A≃B : A PCP.≃ B) → ∃ λ (x : ∃ λ A≡B → PCP.≡⇒≃ A≡B P.≡ A≃B) → ∀ y → x P.≡ y) □ where lemma₃ : (A≡B : A ≡ B) → _↔_.to ≃-CP↔≃-CP (CP.≡⇒≃ A≡B) ≡ PCP.≡⇒≃ (_↔_.to ≡↔≡ A≡B) lemma₃ = elim¹ (λ A≡B → _↔_.to ≃-CP↔≃-CP (CP.≡⇒≃ A≡B) ≡ PCP.≡⇒≃ (_↔_.to ≡↔≡ A≡B)) (_↔_.to ≃-CP↔≃-CP (CP.≡⇒≃ (refl _)) ≡⟨ cong (_↔_.to ≃-CP↔≃-CP) CP.≡⇒≃-refl ⟩ _↔_.to ≃-CP↔≃-CP CP.id ≡⟨ _↔_.from ≡↔≡ $ P.Σ-≡,≡→≡ P.refl (PCP.propositional P.ext _ _ _) ⟩ PCP.id ≡⟨ sym $ _↔_.from ≡↔≡ PCP.≡⇒≃-refl ⟩ PCP.≡⇒≃ P.refl ≡⟨ sym $ cong PCP.≡⇒≃ to-≡↔≡-refl ⟩∎ PCP.≡⇒≃ (_↔_.to ≡↔≡ (refl _)) ∎) lemma₂ : ∀ _ _ → _ ≃ _ lemma₂ A≡B (f , f-eq) = CP.≡⇒≃ A≡B ≡ (f , f-eq) ↝⟨ inverse $ Eq.≃-≡ (Eq.↔⇒≃ ≃-CP↔≃-CP) ⟩ _↔_.to ≃-CP↔≃-CP (CP.≡⇒≃ A≡B) ≡ (f , _↔_.to Is-equivalence-CP↔Is-equivalence-CP f-eq) ↝⟨ ≡⇒≃ $ cong (_≡ (f , _↔_.to Is-equivalence-CP↔Is-equivalence-CP f-eq)) $ lemma₃ A≡B ⟩□ PCP.≡⇒≃ (_↔_.to ≡↔≡ A≡B) ≡ (f , _↔_.to Is-equivalence-CP↔Is-equivalence-CP f-eq) □ lemma₁ : ∀ A≃B → (∃ λ A≡B → CP.≡⇒≃ A≡B ≡ A≃B) ≃ (∃ λ A≡B → PCP.≡⇒≃ A≡B ≡ ( proj₁ A≃B , _↔_.to Is-equivalence-CP↔Is-equivalence-CP (proj₂ A≃B) )) lemma₁ A≃B = Σ-cong ≡↔≡ λ A≡B → lemma₂ A≡B A≃B -- Univalence′ expressed using equality is equivalent to Univalence′ -- expressed using paths. Univalence′≃Univalence′ : {A B : Type ℓ} → Univalence′ A B ≃ PU.Univalence′ A B Univalence′≃Univalence′ {A = A} {B = B} = Univalence′ A B ↝⟨ Univalence′≃Univalence′-CP ext ⟩ CP.Univalence′ A B ↝⟨ Univalence′-CP≃Univalence′-CP ⟩ PCP.Univalence′ A B ↝⟨ inverse $ _↔_.from ≃↔≃ $ PU.Univalence′≃Univalence′-CP P.ext ⟩□ PU.Univalence′ A B □ -- Univalence expressed using equality is equivalent to univalence -- expressed using paths. Univalence≃Univalence : Univalence ℓ ≃ PU.Univalence ℓ Univalence≃Univalence {ℓ = ℓ} = ({A B : Type ℓ} → Univalence′ A B) ↝⟨ implicit-∀-cong ext $ implicit-∀-cong ext Univalence′≃Univalence′ ⟩□ ({A B : Type ℓ} → PU.Univalence′ A B) □
Definition something (P:Type) (e:P) := e. Inductive myunit : Set := mytt. (* Proof below works when definition is in Type, however builtin types such as unit are in Set. *) Lemma demo_hide_generic : let x := mytt in x = x. Proof. intros. change mytt with (@something _ mytt) in x. subst x. (* Proof works if this line is removed *) reflexivity. Qed.
import data.nat.basic import data.rat.basic import data.real.basic import analysis.special_functions.exp_log import analysis.special_functions.pow set_option eqn_compiler.zeta true #check nat.factors --http://sms.math.nus.edu.sg/Simo/IMO_Problems/97.pdf lemma IMO1997Q5_aux : ∀ (a t : ℕ), a > 1 ∧ t ≥ 1 → ¬ (a ^ (2 * t) = a * t) := sorry #check mul_div_cancel_left lemma IMO1997Q5_aux2 : ∀ (a p q : ℕ), ( q ≠ 0 → nat.coprime p q → (∃ (n : ℕ), (a : ℝ) ^ (p / q : ℝ) = (n : ℝ)) → (∃ (m : ℕ), (a : ℝ) ^ (1 / q : ℝ) = (m : ℝ))) := begin rintros a p q hqneq0 hpq ⟨n, hn⟩, have hqneq0' : (q : ℝ) ≠ 0 := λ h, hqneq0 (nat.cast_eq_zero.1 h), suffices hsuff : ∃ (k : ℕ), a = k ^ q, { cases hsuff with k hk, existsi k, have h0lek : 0 ≤ (k : ℝ) := (nat.cast_le.2 (nat.zero_le k)), rw [hk, nat.cast_pow, ←real.rpow_nat_cast, one_div, ←real.rpow_mul h0lek], rw [mul_comm, inv_mul_cancel hqneq0'], norm_num, }, -- ∃ (k : ℕ), a = k ^ q replace hn := congr_arg (λ x, x ^ (q : ℝ)) hn; dsimp at hn, rw [←real.rpow_mul (nat.cast_le.2 (nat.zero_le a))] at hn, rw [mul_comm, ←mul_div_assoc, mul_div_cancel_left _ hqneq0'] at hn, iterate 2 { rw [real.rpow_nat_cast, ←nat.cast_pow] at hn, }, replace hn := nat.cast_inj.1 hn, have hnfactors := congr_arg nat.factors hn, -- Idea: Use pnat.factors_multiset instead. sorry, end lemma IMO1997Q5 : ∀ (a b : ℕ), a ≥ 1 ∧ b ≥ 1 ∧ a ^ (b ^ 2) = b ^ a → (a = 1 ∧ b = 1) ∨ (a = 27 ∧ b = 3) ∨ (a = 16 ∧ b = 2) := begin rintros a b ⟨ha, hb, h⟩, replace ha := eq_or_lt_of_le ha, replace hb := eq_or_lt_of_le hb, cases ha with h1eqa h1lta; cases hb with h1eqb h1ltb, -- Easy cases if a = 1 or b = 1. { left, exact ⟨h1eqa.symm, h1eqb.symm⟩, }, { left, rw [←h1eqa, one_pow, pow_one] at h, exact ⟨h1eqa.symm, h.symm⟩, }, { left, rw [←h1eqb, one_pow, pow_one, one_pow] at h, exact ⟨h, h1eqb.symm⟩, }, -- Otherwise, a, b > 1. { right, have haneq0 : (a : ℝ) ≠ 0, { intros hc, replace hc := nat.cast_eq_zero.1 hc, rw [hc] at h1lta, cases h1lta, }, have h0lea : 0 < (a : ℝ) := nat.cast_lt.2 (nat.lt_trans nat.zero_lt_one h1lta), have h0leb : 0 < (b : ℝ) := nat.cast_lt.2 (nat.lt_trans nat.zero_lt_one h1ltb), let t := ((b : ℝ) ^ 2) / (a : ℝ), have hb2 : (b : ℝ) ^ 2 = (a : ℝ) * t, { rw [←mul_div_assoc, div_eq_mul_inv, mul_comm _ ((↑a)⁻¹), ←mul_assoc], rw [inv_mul_cancel haneq0, one_mul], }, have hb : (b : ℝ) = (a : ℝ) ^ (t : ℝ), { have hlog := congr_arg real.log (congr_arg coe h), iterate 2 { rw [nat.cast_pow] at hlog, }, rw [←real.rpow_nat_cast a, ←real.rpow_nat_cast b a] at hlog, rw [real.rpow_def_of_pos h0lea, real.rpow_def_of_pos h0leb] at hlog, iterate 2 { rw [real.log_exp] at hlog, }, replace hlog := congr_arg (λ x, x / ↑a) hlog; simp at hlog, rw [mul_comm _ ↑a, mul_div_cancel_left _ haneq0, mul_div_assoc] at hlog, replace hlog := congr_arg real.exp hlog, rw [real.exp_log h0leb, ←real.rpow_def_of_pos h0lea] at hlog, rw ←hlog, }, have hat : (a : ℝ) ^ (2 * t) = (a : ℝ) * t, { rw [mul_comm _ t, real.rpow_mul (le_of_lt h0lea)], rw [←hb, ←hb2, ←real.rpow_nat_cast], norm_num, }, let tpq : ℚ := rat.mk (b ^ 2) a, have ht : (tpq : ℝ) = t, { rw rat.cast_mk, norm_num, }, have hq : 1 < tpq.denom, { have hqle1 := nat.add_one_le_iff.2 tpq.pos, rw zero_add at hqle1, suffices hsuff : tpq.denom ≠ 1, { rw ←not_le, intros hc, apply hsuff, exact (le_antisymm hc hqle1), }, intros hq1, rw [←ht] at hat, rw [←(rat.denom_eq_one_iff tpq).1 hq1] at hat, have hpgt1 : tpq.num.to_nat ≥ 1, { sorry, }, apply (IMO1997Q5_aux a (int.to_nat tpq.num) ⟨h1lta, hpgt1⟩), rw [←(@nat.cast_inj ℝ _ _ _), nat.cast_pow, nat.cast_mul], simp at hat, --rw [←nat.cast_mul] at hat, --rw real.rpow_nat_cast at hat, --have H := int.to_nat_of_nonneg (le_trans (le_of_lt int.zero_lt_one) (ge_iff_le.1 hpgt1)), sorry, }, }, end
! Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. ! See https://llvm.org/LICENSE.txt for license information. ! SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception ! module my_container type container integer i real r contains procedure :: init => init_container procedure :: xi => extract_i procedure :: xr => extract_r !generic :: extract => xi, xr end type container contains subroutine extract_i(this, ii) class(container) :: this integer ii ii = this%i end subroutine subroutine extract_r(this, rr) class(container) :: this real rr rr = this%r end subroutine subroutine init_container(this, ic, ir) class(container) :: this integer :: ic real :: ir this%i = ic this%r = ir end subroutine end module my_container program prg USE CHECK_MOD use my_container type(container) :: t integer ei real er logical rslt(2) logical expect(2) rslt = .false. expect = .true. call t%init(23,4.5) call extract_r(t, er) call t%xr(er) call t%xi(ei) rslt(1) = er .eq. 4.5 rslt(2) = ei .eq. 23 call check(rslt,expect,2) end
Formal statement is: lemma SUP_sigma_sigma: "M \<noteq> {} \<Longrightarrow> (\<And>m. m \<in> M \<Longrightarrow> f m \<subseteq> Pow \<Omega>) \<Longrightarrow> (SUP m\<in>M. sigma \<Omega> (f m)) = sigma \<Omega> (\<Union>m\<in>M. f m)" Informal statement is: If $M$ is a nonempty set and $f$ is a function from $M$ to the power set of $\Omega$, then $\sigma(\bigcup_{m \in M} f(m)) = \sigma(\bigcup_{m \in M} \sigma(\Omega, f(m)))$.
#ifndef __QBLAS_EXTEND__CD #define __QBLAS_EXTEND__CD #ifdef HAVE_CBLAS_H #include <cblas.h> #elif (defined HAVE_MKL_CBLAS_H) #include <mkl_cblas.h> #elif (defined HAVE_GSL_CBLAS_H) #include <gsl_cblas.h> #endif /* some convenience functions for the case where all vectors are continguous in memory */ inline void cblas_daxpy(const int N, const double alpha, const double *X, double *Y) { cblas_daxpy(N,alpha,X,1,Y,1); } inline double cblas_dnrm2(const int N, const double *X) { return cblas_dnrm2(N,X,1); } inline void cblas_dcopy(const int N, const double *X, double *Y ) { cblas_dcopy(N,X,1,Y,1); } inline void cblas_dscal(const int N, const double alpha, double *X) { cblas_dscal(N,alpha,X,1); } inline double cblas_ddot(const int N, const double *X, const double *Y ) { return cblas_ddot(N,X,1,Y,1); } inline double cblas_ddot(const int N, const double *X) { return cblas_ddot(N,X,1,X,1); } inline void cblas_zdotc_sub(const int N, const double *X, const double *Y, double* dot) { return cblas_zdotc_sub(N,X,1,Y,1, dot); } //inline void cblas_cdotc_sub(const int N, const float *X, const float *Y, // float* dot) //{ return cblas_cdotc_sub(N,X,Y,dot); } #endif
# # Shor's 9 qubit code # The well-known Shor's 9 qubit code can correct any single Pauli error, but it can also correct some other # kinds of errors. Its circuit is shown as below # ![shor-9-circuit](assets/shor9circuit.png) # which can be constructed by the following code using Yao shor(E) = chain(9, ## encode circuit cnot(1, 4), cnot(1, 7), put(1=>H), put(4=>H), put(7=>H), cnot(1,2), cnot(1,3), cnot(4,5), cnot(4,6), cnot(7,8), cnot(7,9), E, # the error ## decode circuit cnot(1,2), cnot(1,3), cnot((2, 3), 1), cnot(4,5), cnot(4,6), cnot((5, 6), 4), cnot(7,8), cnot(7,9), cnot((8, 9), 7), put(1=>H), put(4=>H), put(7=>H), cnot(1, 4), cnot(1, 7), cnot((4, 7), 1) ) # Now we can check whether it can correct a given error by doing symbolic computation # on an arbitrary 1-qubit pure quantum state ``α|0⟩ + β|1⟩`` and a specific weight-9 error. @vars α β s = α * ket"0" + β * ket"1" |> addbits!(8) E = kron(1=>X, 2=>Z, 3=>Z, 4=>X, 5=>Z, 6=>Z, 7=>X, 8=>Z, 9=>Z); s |> shor(E) |> partial_tr(2:9) |> expand
Open the Recording dialog to set how the camera should store events (alarms). The recording methods are independent of the selected video codec (JPEG, MxPEG). In order to obtain the highest frame rate and the most efficient storage method, however, you should use the MOBOTIX MxPEG codec. The effectiveness of Limit Frame Rate When Idle setting in the Setup Menu > General Image Settings dialog will be reduced when using high frame rates in continuous recording or pre-alarm images, or when using pre-alarm image intervals that are too short. For the time defined in Recording Time, the camera continues storing the video stream as MxPEG clips (or the Post-Alarm Images in Snap Shot mode). The camera records only when the respective custom signal is true. The camera records only when the master camera's Recording is armed. Note: Actions and Messages are not connected to recording and the camera will execute these functions even if recording has been deactivated. In order to arm the camera in a time-controlled manner, you need to select a Time Table Profile. Arm Recording in this dialog (see above) has to be set to Enable or can be set to work with the camera's signal input (e.g. with a key switch) using the SI Closed (low) or SI Open (high) options. The camera signs the recorded data using the X.509 certificate of the camera's web server. The function will automatically stop the recording of images or video clips if one of the selected events occur once the Time Before Terminate has been used up. Use this option if you would like freeze the stored images or image sequences and to prevent them from being overwritten. Note: The selected event(s) must have been activated in the Event Settings dialog; deactivated events are shown accordingly. If the recording has been terminated, the action symbol TR will be displayed in yellow: TR. Set Retrigger Recording to All in order to combine all events in one event folder with the one event number. Note: Event Recording is only available for Secure cameras. Event recording stores MxPEG Clips (M00001.jpg, M00002.jpg, ...; max. ten seconds recording time each) that can also contain audio data (the Record Audio Data option has been activated). One of the advantages of this recording method is the efficient recording method that results in a high increase in server performance (e.g. up to 100 cameras can record on a single standard PC (P4, 3 GHz)). On the other hand, this method also allows storing lip-synchronous audio (sound) data of the camera. Note: Continuous Recording is only available for Secure cameras. Continuous recording stores MxPEG Clips all the time (M00001.jpg, M00002.jpg, ...) that can also contain audio data (the Record Audio Data option has been activated). The advantage of this recording mode is a continuous recording with reduced frame rate and permanent audio recording where the camera automatically increases the frame rate if it detects an event. Similar to Event Recording, the Recording End (RE) event is triggered once the recording has been finished (including retriggered—i.e. prolonged—recording). The HD (1280x720) and Full HD (1920x1080) resolutions available in the live image and in the image profiles are not available for this mode. Since these resolutions do not have an aspect ratio of 4:3 (letterbox), full image recording would clip parts of the image at the top and the bottom of the image.
-- Patterns are parsed as expressions. That means that expressions can contain -- pattern parts. That's of course not ok. module NotAnExpression where X = x @ y -- as pattern as an expression
[GOAL] X : Type u_1 inst✝ : TopologicalSpace X ⊢ SimplyConnectedSpace X ↔ Nonempty X ∧ ∀ (x y : X), Nonempty (Unique (Path.Homotopic.Quotient x y)) [PROOFSTEP] rw [simply_connected_def, equiv_punit_iff_unique] [GOAL] X : Type u_1 inst✝ : TopologicalSpace X ⊢ (Nonempty (FundamentalGroupoid X) ∧ ∀ (x y : FundamentalGroupoid X), Nonempty (Unique (x ⟶ y))) ↔ Nonempty X ∧ ∀ (x y : X), Nonempty (Unique (Path.Homotopic.Quotient x y)) [PROOFSTEP] rfl [GOAL] X : Type u_1 inst✝¹ : TopologicalSpace X inst✝ : SimplyConnectedSpace X x y : X ⊢ Nonempty (Unique (Path.Homotopic.Quotient x y)) [PROOFSTEP] rw [simply_connected_iff_unique_homotopic] at * [GOAL] X : Type u_1 inst✝¹ : TopologicalSpace X inst✝ : Nonempty X ∧ ∀ (x y : X), Nonempty (Unique (Path.Homotopic.Quotient x y)) x y : X ⊢ Nonempty (Unique (Path.Homotopic.Quotient x y)) [PROOFSTEP] tauto [GOAL] Y : Type u_1 inst✝ : TopologicalSpace Y ⊢ SimplyConnectedSpace Y → PathConnectedSpace Y ∧ ∀ (x y : Y), Subsingleton (Path.Homotopic.Quotient x y) [PROOFSTEP] intro [GOAL] Y : Type u_1 inst✝ : TopologicalSpace Y a✝ : SimplyConnectedSpace Y ⊢ PathConnectedSpace Y ∧ ∀ (x y : Y), Subsingleton (Path.Homotopic.Quotient x y) [PROOFSTEP] constructor [GOAL] case left Y : Type u_1 inst✝ : TopologicalSpace Y a✝ : SimplyConnectedSpace Y ⊢ PathConnectedSpace Y [PROOFSTEP] infer_instance [GOAL] case right Y : Type u_1 inst✝ : TopologicalSpace Y a✝ : SimplyConnectedSpace Y ⊢ ∀ (x y : Y), Subsingleton (Path.Homotopic.Quotient x y) [PROOFSTEP] infer_instance [GOAL] Y : Type u_1 inst✝ : TopologicalSpace Y h : PathConnectedSpace Y ∧ ∀ (x y : Y), Subsingleton (Path.Homotopic.Quotient x y) ⊢ SimplyConnectedSpace Y [PROOFSTEP] cases h [GOAL] case intro Y : Type u_1 inst✝ : TopologicalSpace Y left✝ : PathConnectedSpace Y right✝ : ∀ (x y : Y), Subsingleton (Path.Homotopic.Quotient x y) ⊢ SimplyConnectedSpace Y [PROOFSTEP] rw [simply_connected_iff_unique_homotopic] [GOAL] case intro Y : Type u_1 inst✝ : TopologicalSpace Y left✝ : PathConnectedSpace Y right✝ : ∀ (x y : Y), Subsingleton (Path.Homotopic.Quotient x y) ⊢ Nonempty Y ∧ ∀ (x y : Y), Nonempty (Unique (Path.Homotopic.Quotient x y)) [PROOFSTEP] exact ⟨inferInstance, fun x y => ⟨uniqueOfSubsingleton ⟦PathConnectedSpace.somePath x y⟧⟩⟩ [GOAL] Y : Type u_1 inst✝ : TopologicalSpace Y ⊢ SimplyConnectedSpace Y ↔ PathConnectedSpace Y ∧ ∀ {x y : Y} (p₁ p₂ : Path x y), Path.Homotopic p₁ p₂ [PROOFSTEP] convert simply_connected_iff_paths_homotopic (Y := Y) [GOAL] case h.e'_2.h.e'_2.h.h.a Y : Type u_1 inst✝ : TopologicalSpace Y a✝¹ a✝ : Y ⊢ (∀ (p₁ p₂ : Path a✝¹ a✝), Path.Homotopic p₁ p₂) ↔ Subsingleton (Path.Homotopic.Quotient a✝¹ a✝) [PROOFSTEP] simp [Path.Homotopic.Quotient, Setoid.eq_top_iff] [GOAL] case h.e'_2.h.e'_2.h.h.a Y : Type u_1 inst✝ : TopologicalSpace Y a✝¹ a✝ : Y ⊢ (∀ (p₁ p₂ : Path a✝¹ a✝), Path.Homotopic p₁ p₂) ↔ ∀ (x y : Path a✝¹ a✝), Setoid.Rel (Path.Homotopic.setoid a✝¹ a✝) x y [PROOFSTEP] rfl
function ob = ctranspose(ob) %function ob = ctranspose(ob) % "ctranspose" method for Gtomo2 class ob.is_transpose = ~ob.is_transpose; [ob.index1 ob.index2] = deal(ob.index2, ob.index1); ob.dims = fliplr(ob.dims);
From SMTCoq Require Import SMTCoq. From SMTCoq Require Import PArray Int63. Require Import GCHQ. Import Datatypes. Notation "'X'" := (id true). Notation "'O'" := (id false). Definition sol_pb1 := ( (O :: O :: O :: O :: O :: O :: O :: X :: O :: O :: O :: X :: X :: X :: O :: X :: O :: X :: O :: O :: O :: O :: O :: O :: O :: nil) :: (O :: X :: X :: X :: X :: X :: O :: X :: O :: O :: X :: O :: O :: X :: X :: X :: X :: X :: O :: X :: X :: X :: X :: X :: O :: nil) :: (O :: X :: O :: O :: O :: X :: O :: X :: X :: X :: X :: X :: O :: O :: O :: X :: O :: X :: O :: X :: O :: O :: O :: X :: O :: nil) :: (O :: X :: O :: O :: O :: X :: O :: X :: O :: X :: X :: O :: O :: O :: O :: O :: O :: X :: O :: X :: O :: O :: O :: X :: O :: nil) :: (O :: X :: O :: O :: O :: X :: O :: X :: X :: O :: O :: O :: O :: O :: X :: O :: O :: X :: O :: X :: O :: O :: O :: X :: O :: nil) :: (O :: X :: X :: X :: X :: X :: O :: X :: X :: O :: O :: X :: X :: X :: X :: X :: X :: X :: O :: X :: X :: X :: X :: X :: O :: nil) :: (O :: O :: O :: O :: O :: O :: O :: X :: O :: X :: O :: X :: O :: X :: O :: X :: O :: X :: O :: O :: O :: O :: O :: O :: O :: nil) :: (X :: X :: X :: X :: X :: X :: X :: X :: O :: O :: O :: X :: X :: X :: O :: O :: O :: X :: X :: X :: X :: X :: X :: X :: X :: nil) :: (O :: X :: O :: O :: X :: O :: O :: O :: X :: X :: O :: X :: O :: X :: O :: O :: O :: X :: O :: X :: X :: O :: X :: O :: O :: nil) :: (O :: X :: O :: X :: X :: X :: X :: X :: X :: O :: O :: O :: X :: O :: O :: X :: X :: X :: X :: O :: X :: X :: X :: O :: X :: nil) :: (X :: O :: O :: O :: O :: X :: O :: X :: O :: O :: O :: O :: X :: O :: O :: X :: O :: X :: X :: X :: X :: O :: O :: X :: X :: nil) :: (X :: O :: X :: O :: X :: X :: X :: O :: X :: X :: X :: O :: X :: O :: X :: O :: O :: O :: O :: X :: O :: X :: O :: O :: O :: nil) :: (X :: X :: O :: O :: X :: X :: O :: X :: O :: X :: O :: X :: X :: X :: X :: X :: X :: O :: O :: X :: O :: O :: O :: O :: O :: nil) :: (X :: X :: X :: O :: O :: O :: X :: O :: O :: X :: O :: O :: X :: O :: O :: O :: O :: O :: O :: X :: O :: O :: O :: X :: O :: nil) :: (O :: X :: O :: O :: O :: O :: O :: O :: O :: O :: O :: X :: O :: X :: O :: X :: X :: O :: O :: X :: X :: X :: X :: O :: X :: nil) :: (X :: O :: O :: X :: O :: X :: X :: O :: O :: X :: X :: X :: O :: O :: X :: O :: O :: O :: X :: X :: X :: X :: X :: O :: X :: nil) :: (O :: O :: O :: X :: O :: X :: O :: X :: O :: X :: X :: O :: X :: X :: X :: X :: O :: O :: O :: O :: O :: X :: O :: X :: X :: nil) :: (X :: X :: X :: X :: X :: X :: X :: X :: O :: X :: X :: X :: O :: O :: X :: O :: O :: X :: X :: X :: O :: O :: O :: O :: O :: nil) :: (O :: O :: O :: O :: O :: O :: O :: X :: O :: X :: X :: O :: O :: X :: X :: X :: O :: X :: O :: X :: O :: X :: O :: O :: O :: nil) :: (O :: X :: X :: X :: X :: X :: O :: X :: O :: O :: X :: X :: O :: X :: X :: O :: O :: X :: X :: X :: O :: O :: X :: O :: X :: nil) :: (O :: X :: O :: O :: O :: X :: O :: X :: X :: X :: O :: O :: O :: O :: X :: X :: O :: O :: O :: O :: O :: X :: X :: O :: X :: nil) :: (O :: X :: O :: O :: O :: X :: O :: X :: O :: O :: O :: X :: O :: O :: O :: O :: O :: O :: O :: O :: O :: O :: X :: O :: O :: nil) :: (O :: X :: O :: O :: O :: X :: O :: X :: O :: X :: X :: O :: O :: O :: O :: O :: O :: X :: O :: O :: O :: O :: O :: O :: X :: nil) :: (O :: X :: X :: X :: X :: X :: O :: X :: X :: O :: O :: X :: X :: X :: X :: X :: X :: O :: X :: O :: X :: O :: O :: X :: X :: nil) :: (O :: O :: O :: O :: O :: O :: O :: X :: O :: O :: X :: X :: X :: O :: X :: O :: O :: X :: X :: X :: O :: O :: O :: O :: O :: nil) :: nil ). Lemma verify_sol_pb1 : verify_sol pb1 sol_pb1. Proof. by compute. Qed. Lemma interp_free f u : interp f u = let ff f := finterp u (fun x => f (to_Z x)) in ff (fun x => f (Int63Op.of_Z x)) true false Bool.eqb mk_andb mk_implb mk_orb Datatypes.negb. Proof. simpl. apply interp_ext; intro x. by rewrite Int63Axioms.of_to_Z. Qed. Lemma sol_pb1_ok s : verify_sol pb1 s -> sol_pb1 = s. Proof. intro H. apply (test_eq_correct pb1). - by compute. - by compute. - by compute. - by apply verify_sol_pb1. - by exact H. rewrite interp_free. set (u := fun _ => _). vm_compute in u. set (ff := (fun _ => _)). unfold u. lazy delta[is_true mk_andb mk_orb mk_implb seq.head seq.foldl seq.foldr seq.behead] iota beta. unfold is_true. verit. Qed. (* Definition pb := pb2. Definition es : sol := nil. Definition tr (z : Z) := true. Time Definition tt1 f := Eval vm_compute in finterp (gen_all pb) (fun x => f (to_Z x)). Time Definition tt2 := Eval lazy delta[tt1 mk_andb mk_orb seq.head seq.foldl seq.behead] iota beta in tt1 tr true false Bool.eqb mk_andb mk_implb mk_orb Datatypes.negb. Ltac end_tac v := let w := eval compute in v in idtac w; (timeout 40 ( try ( assert (Datatypes.implb tt2 ((tr w))); [ unfold tt2; verit | idtac]; idtac "ho"; fail 1); idtac "false"; exact false)) || idtac "true"; exact true. Ltac col i j n := let u := constr:(Zeq_bool j n) in let v := eval compute in u in match v with true => exact nil |false => apply cons; [end_tac (i * n + j)%Z| col i (j + 1)%Z n] end. Ltac row i n := let u := constr:(Zeq_bool i n) in let v := eval compute in u in match v with true => exact nil |false => apply cons; [col i 0%Z n| row (i + 1)%Z n] end. Definition s : sol. row 0 (Z.of_nat (p_size pb)). Defined. Lemma verify_sol_s : verify_sol pb s. Proof. by compute. Qed. Lemma interp_free f u : interp f u = let ff f := finterp u (fun x => f (to_Z x)) in ff (fun x => f (Int63Op.of_Z x)) true false Bool.eqb mk_andb mk_implb mk_orb Datatypes.negb. Proof. simpl. apply interp_ext; intro x. by rewrite Int63Axioms.of_to_Z. Qed. Lemma s_ok s1 : verify_sol pb s1 -> s = s1. Proof. intro H. apply (test_eq_correct pb). - by compute. - by compute. - by compute. - by apply verify_sol_s. - by exact H. rewrite interp_free. set (u := fun _ => _). compute in u. set (ff := (fun _ => _)). unfold u. lazy delta[is_true mk_andb mk_orb mk_implb seq.head seq.foldl seq.foldr seq.behead] iota beta. verit. Qed. *)
The purpose of this role is to provide individualized support to enable people to remain independent and continue to live within their own homes. We are looking for caring and compassionate people to become day makers ensuring our service users are happy and comfortable with the service they receive. As a home care assistant, you will spend your time out in the community visiting our service users and ensuring they are well looked after, safe and happy. The type of care and support that we offer varies depending on each service user’s individual needs.
------------------------------------------------------------------------ -- The Agda standard library -- -- An inductive definition for the permutation relation ------------------------------------------------------------------------ {-# OPTIONS --without-K --safe #-} module Data.List.Relation.Binary.Permutation.Propositional {a} {A : Set a} where open import Data.List.Base using (List; []; _∷_) open import Relation.Binary open import Relation.Binary.PropositionalEquality using (_≡_; refl) import Relation.Binary.Reasoning.Setoid as EqReasoning ------------------------------------------------------------------------ -- An inductive definition of permutation -- Note that one would expect that this would be defined in terms of -- `Permutation.Setoid`. This is not currently the case as it involves -- adding in a bunch of trivial `_≡_` proofs to the constructors which -- a) adds noise and b) prevents easy access to the variables `x`, `y`. -- This may be changed in future when a better solution is found. infix 3 _↭_ data _↭_ : Rel (List A) a where refl : ∀ {xs} → xs ↭ xs prep : ∀ {xs ys} x → xs ↭ ys → x ∷ xs ↭ x ∷ ys swap : ∀ {xs ys} x y → xs ↭ ys → x ∷ y ∷ xs ↭ y ∷ x ∷ ys trans : ∀ {xs ys zs} → xs ↭ ys → ys ↭ zs → xs ↭ zs ------------------------------------------------------------------------ -- _↭_ is an equivalence ↭-reflexive : _≡_ ⇒ _↭_ ↭-reflexive refl = refl ↭-refl : Reflexive _↭_ ↭-refl = refl ↭-sym : ∀ {xs ys} → xs ↭ ys → ys ↭ xs ↭-sym refl = refl ↭-sym (prep x xs↭ys) = prep x (↭-sym xs↭ys) ↭-sym (swap x y xs↭ys) = swap y x (↭-sym xs↭ys) ↭-sym (trans xs↭ys ys↭zs) = trans (↭-sym ys↭zs) (↭-sym xs↭ys) -- A smart version of trans that avoids unnecessary `refl`s (see #1113). ↭-trans : Transitive _↭_ ↭-trans refl ρ₂ = ρ₂ ↭-trans ρ₁ refl = ρ₁ ↭-trans ρ₁ ρ₂ = trans ρ₁ ρ₂ ↭-isEquivalence : IsEquivalence _↭_ ↭-isEquivalence = record { refl = refl ; sym = ↭-sym ; trans = ↭-trans } ↭-setoid : Setoid _ _ ↭-setoid = record { isEquivalence = ↭-isEquivalence } ------------------------------------------------------------------------ -- A reasoning API to chain permutation proofs and allow "zooming in" -- to localised reasoning. module PermutationReasoning where private module Base = EqReasoning ↭-setoid open EqReasoning ↭-setoid public hiding (step-≈; step-≈˘) infixr 2 step-↭ step-↭˘ step-swap step-prep step-↭ = Base.step-≈ step-↭˘ = Base.step-≈˘ -- Skip reasoning on the first element step-prep : ∀ x xs {ys zs : List A} → (x ∷ ys) IsRelatedTo zs → xs ↭ ys → (x ∷ xs) IsRelatedTo zs step-prep x xs rel xs↭ys = relTo (trans (prep x xs↭ys) (begin rel)) -- Skip reasoning about the first two elements step-swap : ∀ x y xs {ys zs : List A} → (y ∷ x ∷ ys) IsRelatedTo zs → xs ↭ ys → (x ∷ y ∷ xs) IsRelatedTo zs step-swap x y xs rel xs↭ys = relTo (trans (swap x y xs↭ys) (begin rel)) syntax step-↭ x y↭z x↭y = x ↭⟨ x↭y ⟩ y↭z syntax step-↭˘ x y↭z y↭x = x ↭˘⟨ y↭x ⟩ y↭z syntax step-prep x xs y↭z x↭y = x ∷ xs <⟨ x↭y ⟩ y↭z syntax step-swap x y xs y↭z x↭y = x ∷ y ∷ xs <<⟨ x↭y ⟩ y↭z
import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np from pylab import cm a,b = np.loadtxt('Result_Alg1.csv',unpack=True,delimiter=',',skiprows=1); fig = plt.figure(); plt.ylim(450,490) plt.scatter(a,b,color= "green",marker= ".", s=0.3); plt.xlabel('The key number (10,000 random keys selected in total)') plt.ylabel('The number of ineffective ciphertexts (N)') plt.savefig("Alg1_Simulation_DES.eps"); plt.show() #colors = cm.get_cmap('tab10',2);
# Euler's Formula [back to overview page](index.ipynb) a proof: http://austinrochford.com/posts/2014-02-05-eulers-formula-sympy.html ```python import sympy as sp sp.init_printing() ``` ```python x = sp.symbols('x', real=True) ``` ```python exp1 = sp.exp(sp.I * x) exp1 ``` ```python exp2 = exp1.expand(complex=True) exp2 ``` ```python exp2.rewrite(sp.exp) ``` Euler's identity: ```python sp.exp(sp.I * sp.pi) + 1 ``` <p xmlns:dct="http://purl.org/dc/terms/"> <a rel="license" href="http://creativecommons.org/publicdomain/zero/1.0/"> </a> <br /> To the extent possible under law, <span rel="dct:publisher" resource="[_:publisher]">the person who associated CC0</span> with this work has waived all copyright and related or neighboring rights to this work. </p>
lemma fold_coeffs_monom [simp]: "a \<noteq> 0 \<Longrightarrow> fold_coeffs f (monom a n) = f 0 ^^ n \<circ> f a"
# Copyright (c) 2018-2021, Carnegie Mellon University # See LICENSE for details # ========================================================================== # Sparse # ========================================================================== Class(Sparse, BaseMat, rec( new := meth(self, L) Constraint(IsList(L)); if not ForAll(L, t -> IsList(t) and Length(t)=3 and IsInt(t[1]) and IsInt(t[2])) then Error("<L> must be a list of triples [i, j, a_(i,j)]"); fi; return SPL(WithBases( self, rec( element := L, dimensions := [ Maximum(List(L, t->t[1])), Maximum(List(L, t->t[2])) ] ))); end, #----------------------------------------------------------------------- dims := self >> [ Maximum(List(self.element, t->t[1])), Maximum(List(self.element, t->t[2])) ], #----------------------------------------------------------------------- isPermutation := False, #----------------------------------------------------------------------- isReal := self >> ForAll(self.element, t -> IsRealNumber(t[3])), #----------------------------------------------------------------------- toAMat := self >> AMatMat(List(MatSparseSPL(self), r -> List(r, EvalScalar))), #----------------------------------------------------------------------- transpose := meth(self) # we use CopyFields to copy all fields of self local L, t; L := [ ]; for t in self.element do Add(L, [t[2], t[1], t[3]]); od; return CopyFields(self, rec(element := L, dimensions := Reversed(self.dims()))); end, conjTranspose := meth(self) # we use CopyFields to copy all fields of self local L, t; L := [ ]; for t in self.element do Add(L, [t[2], t[1], Global.Conjugate(t[3])]); od; return CopyFields(self, rec(element := L, dimensions := Reversed(self.dims()))); end, #----------------------------------------------------------------------- arithmeticCost := meth(self, costMul, costAddMul) local cost, row, elms; cost := costMul(0) - costMul(0); # will work even when costMul(0) <> 0 for row in [1..self.dimensions[1]] do elms := Filtered(self.element, e -> e[1]=row); if Length(elms) > 0 then cost := cost + costMul(elms[1][3]) + Sum(elms{[2..Length(elms)]}, e -> costAddMul(e[3])); fi; od; return cost; end ));
------------------------------------------------------------------------ -- The Agda standard library -- -- Lemmas relating algebraic definitions (such as associativity and -- commutativity) that don't the equality relation to be a setoid. ------------------------------------------------------------------------ {-# OPTIONS --without-K --safe #-} module Algebra.Consequences.Base {a} {A : Set a} where open import Algebra.Core open import Algebra.Definitions open import Data.Sum.Base open import Relation.Binary.Core sel⇒idem : ∀ {ℓ} {_•_ : Op₂ A} (_≈_ : Rel A ℓ) → Selective _≈_ _•_ → Idempotent _≈_ _•_ sel⇒idem _ sel x with sel x x ... | inj₁ x•x≈x = x•x≈x ... | inj₂ x•x≈x = x•x≈x
"I am currently a senior mechanical engineering student at Stony Brook University. My key quality as a tutor aside for the passion I have for my subjects is definitely my patience with students. I feel that tutoring is not just instruction, but a means of communication with students. From my years of tutoring I have come to learn that misunderstanding of subject concepts come not from the students own lack of understanding, but rather from lack of proper interpretation of students questions. Ta"
#include "irods/rmdirUtil.h" #include "irods/rmUtil.h" #include "irods/rodsPath.h" #include "irods/rodsErrorTable.h" #include "irods/rodsLog.h" #include "irods/rcGlobalExtern.h" #include "irods/rodsPath.h" #include "irods/rcMisc.h" #include "irods/filesystem.hpp" #include <boost/filesystem.hpp> #include <iostream> int rmdirUtil( rcComm_t *conn, rodsArguments_t *myRodsArgs, int treatAsPathname, int numColls, rodsPath_t collPaths[] ) { if ( numColls <= 0 ) { return USER__NULL_INPUT_ERR; } int status = 0; for ( int i = 0; i < numColls; ++i ) { status = rmdirCollUtil( conn, myRodsArgs, treatAsPathname, collPaths[i] ); } return status; } int rmdirCollUtil(rcComm_t *conn, rodsArguments_t *myRodsArgs, int treatAsPathname, rodsPath_t collPath) { namespace fs = irods::experimental::filesystem; fs::path abs_path = collPath.outPath; // Handle "-p". if (treatAsPathname) { try { const auto options = myRodsArgs->force ? fs::remove_options::no_trash : fs::remove_options::none; // Iterate over the elements in the path. This guarantees that no collections // above the ones provided are touched. for (auto&& _ : fs::path{collPath.inPath}) { const auto status = fs::client::status(*conn, abs_path); if (!fs::client::exists(status)) { std::cerr << "Failed to remove [" << abs_path << "]: Collection does not exist\n"; return 0; } if (!fs::client::is_collection(status)) { std::cerr << "Failed to remove [" << abs_path << "]: Path does not point to a collection\n"; return 0; } if (!fs::client::is_empty(*conn, abs_path)) { std::cerr << "Failed to remove [" << abs_path << "]: Collection is not empty\n"; return 0; } fs::client::remove(*conn, abs_path, options); abs_path = abs_path.parent_path(); static_cast<void>(_); // Unused } } catch (const fs::filesystem_error& e) { std::cerr << "Error: " << e.what() << '\n'; } return 0; } if (!fs::client::is_collection(*conn, abs_path)) { std::cout << "Failed to remove [" << abs_path << "]: Collection does not exist\n"; return 0; } // check to make sure it's not /, /home, or /home/username? // XXXXX if (!fs::client::is_empty(*conn, abs_path)) { std::cout << "Failed to remove [" << abs_path << "]: Collection is not empty\n"; return 0; } collInp_t collInp; dataObjInp_t dataObjInp; initCondForRm( myRodsArgs, &dataObjInp, &collInp ); rstrcpy( collInp.collName, collPath.outPath, MAX_NAME_LEN ); const int status = rcRmColl( conn, &collInp, myRodsArgs->verbose ); if (status < 0) { std::cout << "rmdirColl: rcRmColl failed with error " << status << '\n'; } return status; }
Formal statement is: lemma bounded_linear_componentwise_iff: "(bounded_linear f') \<longleftrightarrow> (\<forall>i\<in>Basis. bounded_linear (\<lambda>x. f' x \<bullet> i))" (is "?lhs = ?rhs") Informal statement is: A linear map $f'$ is bounded if and only if each of its components is bounded.
[STATEMENT] lemma (in is_functor) cf_cf_obj_comma_proj_ArrMap_app[cat_comma_cs_simps]: assumes "ABF = [A, B, [g, h]\<^sub>\<circ>]\<^sub>\<circ>" and "[A, B, [g, h]\<^sub>\<circ>]\<^sub>\<circ> \<in>\<^sub>\<circ> \<FF> \<^sub>C\<^sub>F\<down> b\<lparr>Arr\<rparr>" shows "\<FF> \<^sub>C\<^sub>F\<Sqinter>\<^sub>O b\<lparr>ArrMap\<rparr>\<lparr>ABF\<rparr> = g" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<FF> \<^sub>C\<^sub>F\<Sqinter>\<^sub>O b\<lparr>ArrMap\<rparr>\<lparr>ABF\<rparr> = g [PROOF STEP] by ( rule cf_comma_proj_left_ArrMap_app[ OF assms(1) assms(2)[unfolded cat_cf_obj_comma_def], folded cf_cf_obj_comma_proj_def ] )
lemma (in semiring_of_sets) sets_Collect_finite_All': assumes "\<And>i. i \<in> S \<Longrightarrow> {x\<in>\<Omega>. P i x} \<in> M" "finite S" "S \<noteq> {}" shows "{x\<in>\<Omega>. \<forall>i\<in>S. P i x} \<in> M"
# Built in R features # Example Vector vector <- c(1:20) # Creates sequestes, takes 3 arguments, # 1. Where it starts, 2. Where it ends, 3. the "by=", how it should just foreach step seq(0, 20, by = 10) # gives (0, 10, 20) # Sorts vectors sort(vector, decreasing = TRUE) # vector, decreasing = TRUE/FALSE # Reverse the object rev(vector) # 20 .. 1 # Show the structure of the object str(vector) # int[1:20] 1 .. 20 # Merge lists and vectors together append(vector, 21:25) # is. checks the class is correct. is.vector(vector) # as. convert to this data-type as.list(vector) # Returns random numbers sampe(x = 100, 3) add.random <- function(x) { rand <- sample(1:100, 1) return(x+rand) } # Applies the function to every vector, and returns a list lapply(vector, add.random) # Apples the function to every vector, and returns a vector sapply(vector, add.random) # Anonymous functions sapply(vector, function(num) {num * 2}) # Math functions abs() # Computes the absolute value sum() # returns the sum of values mean() # computes the arithemitc mean round() # Rounds values, more arguments for nearest, digits = 2 text <- "Hi, do you know who you are voting for?" # Regular expressions grepl('voting', text) # Returns logical TRUE/FALSE grep() # Returns index of searched object # Dates Sys.Date() # TODAY # Normal dates in R date <- "1990-01-01" %>% as.Date() # Or formating like this my.date <- as.Date("Nov-03-90", format = "%b-%d-%y") # Most used, includes time as.POSTXCT() # Should be used strptime() # Pipe operator # Works like promises result <- mtcars %>% filter(mpq > 20) %>% sample_n(size = 5) %>% arrange(desc(mpq)) # Data manipulation library(Dplyr) # Manipulation of data fliter(flights, month == 11, day == 3, carrier, 'AA') # Overrules the normal filter slice(flights, 1:10) # Returns the amount of rows in a dataframe arrange(flights, year, month, day, airtime) # Reorders the row after parameters select(flights, carrier) # Takes out parameters with lesser syntax rename(flights, airline_carrier = carrier) # Renames columns, replaces the old distinct(select(flights, carrier)) # Takes all the unique values mutate(flights, new_col = arr_delay-dep_deplay) # Creates a new column and remakes the args transmute() # Same as mutate, but returns the "new row" summarise(flights, avg_air_time = mean(air_time, na.rm = T)) # Works like aggregate sample_n(flights, 10) # Returns random rows (10) sample_frac(flights, 0.1) # Returns a fraction of rows (%) library(tidyr) # Cleaning Data gather(df, Quarter, Revenue, Quarter1:Quarter4) # Collapses multiple columns into fewer spread(stocks, price) # Reverses the gather separate(df, which.to.separate, c('col1','col2')) # separates using values thats non characters etc. unite(df, joined.col, col1, col2) # Reverses the separate # Layers of data visualization with GGPLOT2 library(ggplot2) # Data - library # Aestehtics = aes(x=, y=) # Geometry - geom_point() # Facets - lets us put multiple plots on the same grid # Statistics - facets_grid() gives the extra layers # Coordinates -coord_cartesian(xlim = vector) ggplot(data = mtcars) # Data pl <- ggplot(data = mtcars, aes(x = mpg, y = hp)) # Aestehtics pl <- pl + geom_point() # Geomtry pl <- pl + facet_grid(cyl ~ .) # Separates the plots depending on how many cylinders they have pl2 <- pl + stat_smooth() # Smoothing out the curves pl2 <- coord_cartesian(xlim = c(15:25)) # Theme layer - adding to the theme layer pl2 <- pl2 + theme_bw() # Using ggplot2movies library install.packages('ggplot2movies') library(ggplot2movies) # (movies) # Histogram # Data & Aesthetics movpl <- ggplot(movies, aes(x=rating)) # only need x movpl2 <- movpl + geom_histogram(binwidth = 0.1, aes(fill=..count..)) # Prints a histogram with ratings movpl3 <- xlab('Movie Rating') + ylab('Count') # Labeling the x and y print(movpl3 + ggtitle("Title")) # Scatterplots carpl <- ggplot(mtcars, aes(x=wt, y=mpg)) # DATA / AES carpl <- carpl + geom_point(aes(size=hp)) # Bigger size depending on the hp # Barplots - Categorical data barpl <- ggplot(mpg, aes(x = class)) barplcolor <- barpl + geom_bar()# geom_bar specifies a barplot barplcolor <- barpl+ geom_bar(aes(fill=drv), position = 'dodge') # Splits up positions # Boxplot - Depicting data of numerical data boxpl <- ggplot(mtcars, aes(x = factor(cyl), y = mpg)) boxplot <- boxpl + geom_boxplot() # Two variable plots twovpl <- ggplot(movies, aes(x = year, y = rating) + geom_bin2d()) twovpl <- twovpl + scale_fill_gradient(high = 'red', low = 'blue') # install.package('hexbin') twovpl <- twovpl + geom_hex() / geom_density2d() # Gives a hex pattern # Working with Coordinates and Faceting # Coordinates - Resize the plots # Faceting - Allows us to place more plots at the side of eachother pl <- ggplot(mpg, aes(x = displ, y = hwy)) + geom_point() # xlim / ylim takes vectors as arguments pl + coord_cartesian(xlim = c(1,4), ylim = c(15, 30)) pl + coord_fixed(ratio = 1/3) # Resizes the plot # creates multiple grids with facet_grid() pl + facet_grid(. ~ cyl) # the . is the x axis, the cyl is the y axis # Themes theme_set(theme_minimal()) # Set global theme pl <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() pl + theme_dart() # Install more themes install.package('ggthemes') library(ggthemes) # Plotly - Interactive ggplots 'https://plot.ly/ggplot2' install.packages('plotly') library(ggplot2) library(plotly) gplo <- ggplot(mtcars, aes(mpg,wt)) + geom_point() # pass in plot in ggplotly gplot <- ggplotly(gplo) # Any type of GGPLOT2 visualization 'http://ropensci.github.io/plotly-test-table/tables/0e3d5ca144d27d8416318824c1b6ec1421a51045/index.html'
proposition le_measure: "sets M = sets N \<Longrightarrow> M \<le> N \<longleftrightarrow> (\<forall>A\<in>sets M. emeasure M A \<le> emeasure N A)"
import data.nat.basic data.int.basic data.nat.modeq tactic.norm_num data.nat.prime namespace nat def mod_inv_aux : ℕ → ℕ → ℤ | 0 p := 0 | (succ m) p := have (p%succ m)<succ m:=mod_lt p (succ_pos m), (↑(gcd (succ m) p) - (mod_inv_aux (p%succ m) (succ m)*↑p))/↑(succ m) def mod_inv : ℕ → ℕ → ℕ := λ m p, int.nat_abs (mod_inv_aux m p % (↑(p/gcd m p))) theorem mod_inv_aux_bezout :∀ a b:ℕ,mod_inv_aux a b * ↑a +mod_inv_aux (b%a) a * ↑b = gcd a b:=begin assume m p,rw add_comm,apply gcd.induction m p,assume n,rw mod_zero,simp[mod_inv_aux],cases n with n,simp [mod_inv_aux],simp [mod_inv_aux],rw int.div_self,norm_num, rw [←int.coe_nat_zero,add_comm,int.coe_nat_add_one_out,int.coe_nat_eq_coe_nat_iff],exact dec_trivial,intros m1 p1,cases m1 with m1,intros,exfalso,revert a,exact dec_trivial, have: mod_inv_aux (succ m1) p1 = (↑(gcd (succ m1) p1) - mod_inv_aux (p1 % succ m1) (succ m1) * ↑p1) / ↑(succ m1):=by unfold mod_inv_aux, rw this,assume H H1,rw [eq_comm,←sub_eq_iff_eq_add] at H1,unfold gcd, rw[int.mod_def,mul_sub,←sub_add,eq_comm,←sub_eq_iff_eq_add,mul_comm _ (↑p1 / ↑(succ m1)),←mul_assoc,←sub_mul] at H1,rw ←H1,rw int.mul_div_cancel,rw [sub_mul,sub_eq_iff_eq_add] at H1, rw [sub_mul,H1],norm_num,rw[←int.coe_nat_zero,add_comm,int.coe_nat_add_one_out,int.coe_nat_eq_coe_nat_iff],exact dec_trivial, end theorem mod_inv_gcd :∀ m p:ℕ,p>0→ m * mod_inv m p ≡ gcd m p [MOD p]:=begin unfold mod_inv,assume m p Hp,rw modeq.modeq_iff_dvd, have H2:∀ x y:ℤ, x%y = x - y * (x/y) :=begin assume x y, rw[eq_comm,sub_eq_iff_eq_add,eq_comm],apply int.mod_add_div, end, rw [←mod_inv_aux_bezout,int.coe_nat_mul, ←int.abs_eq_nat_abs,abs_of_nonneg, H2,mul_sub],simp,rw [←add_assoc,←add_assoc,mul_comm (↑m),add_comm (mod_inv_aux m p * ↑m)],simp, have : p ∣ (p/gcd m p) * m:=begin cases exists_eq_mul_right_of_dvd (and.left(gcd_dvd m p)) with c Hc, have : p / gcd m p * m= p /gcd m p *gcd m p * c:=by rw[mul_assoc,←Hc],rw this,rw nat.div_mul_cancel (and.right(gcd_dvd m p)),simp,end, apply dvd_add,simp,rw ←int.coe_nat_dvd at this,rw [←mul_assoc,←int.coe_nat_mul,mul_comm m],apply dvd_mul_of_dvd_left this, apply int.mod_nonneg,cases exists_eq_mul_left_of_dvd (and.right(gcd_dvd m p)) with c Hc,have :p / gcd m p=c*gcd m p/gcd m p:= by rw ←Hc,rw this,rw nat.mul_div_cancel,intro,rw [←int.coe_nat_zero,int.coe_nat_eq_coe_nat_iff] at a,rw a at Hc,simp at Hc,rw Hc at Hp,revert Hp,exact dec_trivial, apply gcd_pos_of_pos_right m Hp, end theorem mod_inv_unique :∀ m n p:ℕ,p>0→ coprime m p→ (m * n ≡ 1 [MOD p] ↔ n ≡ mod_inv m p [MOD p]):=begin assume m n p Hp Hc,apply iff.intro,assume H, have H1:= modeq.modeq_mul (modeq.refl (mod_inv m p)) H, rw [←mul_assoc,mul_comm _ m] at H1,have H2:=modeq.trans (modeq.symm(modeq.modeq_mul (mod_inv_gcd m p Hp) (modeq.refl n))) H1, rw coprime.gcd_eq_one Hc at H2,simp at H2,exact H2,intro, have :=modeq.trans (modeq.modeq_mul (modeq.refl m) a) (mod_inv_gcd m p Hp), rw coprime.gcd_eq_one Hc at this,assumption, end theorem modeq_mul_cancel{ a b c p:ℕ}:p > 0 → coprime a p → (a * b ≡ a * c [MOD p] ↔ b ≡ c [MOD p]):=begin assume H0 Hco,apply iff.intro,assume H, have H1:=modeq.modeq_mul (modeq.refl (mod_inv a p)) H,rw[←mul_assoc,←mul_assoc] at H1, have Hb:=modeq.symm (modeq.modeq_mul (mod_inv_gcd a p H0) (modeq.refl b)), have Hc:=(modeq.modeq_mul (mod_inv_gcd a p H0) (modeq.refl c)),rw [coprime.gcd_eq_one Hco,one_mul,mul_comm a] at *, exact modeq.trans (modeq.trans Hb H1) Hc,exact modeq.modeq_mul (modeq.refl a), end theorem modeq_zero:∀ a b:ℕ, a ≡ b [MOD 0] ↔ a = b:=λ a b, by simp[modeq] open list theorem modeq_prod_list : ∀ (A B : list ℕ) (z:ℕ),(∀y:ℕ,countp (λ x,x ≡ y [MOD z]) A = countp (λ x,x ≡ y [MOD z]) B)→ prod A ≡ prod B [MOD z]:=begin intros A B z H,revert B, induction A with p A1 Hi,intros B H, simp,simp at H,cases B with b B,simp,exfalso, have:= H b,rw list.countp_cons_of_pos at this, have H:list.countp (λ (x : ℕ), x ≡ b [MOD z]) B + 1≥1:=le_add_left _ _,rw ←this at H,revert H,exact dec_trivial, apply modeq.refl,intros B H,have H1:= H p,rw list.countp_cons_of_pos at H1,have H2:0<list.countp (λ (x : ℕ), x ≡ p [MOD z]) A1 + 1:=le_add_left _ _, rw H1 at H2,rw list.countp_pos at H2,cases H2 with q Hq,cases Hq with Hq Hq1, have H2:(∀ (y : ℕ), list.countp (λ (x : ℕ), x ≡ y [MOD z]) A1 = list.countp (λ (x : ℕ), x ≡ y [MOD z]) (list.erase B q)):=begin intro y,have H2:= H y,have H3:=perm_erase Hq,have H4:=perm_countp (λ (x : ℕ), x ≡ y [MOD z]) H3, cases decidable.em (p ≡ y [MOD z]) with A A,rw countp_cons_of_pos at H2,rw[H4,countp_cons_of_pos] at H2,apply add_right_cancel H2,exact modeq.trans Hq1 A,assumption, rw list.countp_cons_of_neg at H2,rwa[H4,countp_cons_of_neg] at H2,intro,have H3:=modeq.symm Hq1,exact A (modeq.trans H3 a),assumption, end,have H3:=Hi(list.erase B q) H2,have H4:=prod_eq_of_perm (perm_erase Hq),rw [H4,prod_cons,prod_cons],exact modeq.modeq_mul (modeq.symm Hq1) H3,apply modeq.refl, end def Lb : ℕ → ℕ → list ℕ | 0 b := list.nil | (succ n) b := (b*succ n):: Lb n b theorem L3 :∀(A B:list ℕ)(p:ℕ),(∀a:ℕ,a∈A→∃(b:ℕ)(H:b∈B),b≡a[MOD p])→(∀b:ℕ,b∈B→∃(a:ℕ)(H:a∈A),a≡b[MOD p])→(∀a₁ a₂:ℕ,a₁∈A→a₂∈list.erase A a₁→¬a₁≡a₂[MOD p])→(∀b₁ b₂:ℕ,b₁∈B→b₂∈list.erase B b₁→¬b₁≡b₂[MOD p])→(∀y:ℕ,countp(λa,a≡y[MOD p])A=countp(λb,b≡y[MOD p])B):=begin assume A B p HA HB HA1 HB1 y, cases decidable.em(∃(b:ℕ)(H:b∈B),b≡y[MOD p]) with Hb Hb, apply exists.elim Hb, assume b1 Hb1, cases Hb1 with Hb1 Hb2, have Ha:= HB b1 Hb1, apply exists.elim Ha, assume a1 H,cases H with Ha1 Ha2, have Hb:= HA a1 Ha1, rw [perm_countp _ (perm_erase Hb1),perm_countp _ (perm_erase Ha1),countp_cons_of_pos,countp_cons_of_pos], cases decidable.em (0<countp (λ (a : ℕ), a ≡ y [MOD p]) (list.erase A a1)) with Ha4 Ha4, exfalso,rw countp_pos at Ha4,cases Ha4 with a₂ Ha₂,cases Ha₂ with ha₂ Ha₂,have:=HA1 a1 a₂ Ha1 ha₂, exact this (modeq.trans (modeq.trans Ha2 Hb2) (modeq.symm Ha₂)), cases decidable.em (0<countp (λ (b : ℕ), b ≡ y [MOD p]) (list.erase B b1)) with Hb4 Hb4, exfalso,rw countp_pos at Hb4,cases Hb4 with b₂ Hb₂,cases Hb₂ with hb₂ Hb₂,have:=HB1 b1 b₂ Hb1 hb₂, exact this (modeq.trans Hb2 (modeq.symm Hb₂)), rw [eq_zero_of_le_zero (le_of_not_gt Ha4),eq_zero_of_le_zero (le_of_not_gt Hb4)],assumption,exact modeq.trans Ha2 Hb2, cases decidable.em(∃(a:ℕ)(H:a∈A),a≡y[MOD p])with H2 H2, cases H2 with a1 HA1,cases HA1 with HA1 HA2,exfalso, cases (HA a1 HA1) with b1 Hb1,cases Hb1 with Hb1 Hb2, exact Hb (exists.intro b1 (exists.intro Hb1 (modeq.trans Hb2 HA2))), rw ←countp_pos at H2 Hb, have H1:= eq_zero_of_le_zero (le_of_not_gt Hb),have H2:=eq_zero_of_le_zero (le_of_not_gt H2), rw[H1, ←H2] end theorem modeq_mod_cancel:∀ a p:nat, a % p ≡ a [MOD p] :=begin assume a p,rw modeq.modeq_iff_dvd,rw [int.coe_nat_mod,int.mod_def],norm_num, end theorem mem_Lb :∀ k p b:ℕ,b>0→(k*b∈Lb (p-1) b↔k>0∧k<p):=begin assume k p b Hb,induction p with p1,simp [Lb],intro,exact dec_trivial, cases p1 with p2, simp[Lb],intro,apply le_of_lt_succ,apply succ_lt_succ,assumption, simp[Lb],apply iff.intro, assume H, cases H,rw[mul_comm,nat.mul_left_inj Hb] at H,rw H,apply and.intro,exact dec_trivial,exact lt_succ_self _, rw succ_sub_one at p_ih, simp [H] at p_ih, exact ⟨p_ih.left,lt_trans p_ih.right (lt_succ_self _)⟩, cases decidable.em (k<succ p2),intro,simp [a,h] at p_ih,simp[p_ih],intro,rw[mul_comm,nat.mul_left_inj Hb],have:=le_of_not_gt h,simp [le_antisymm (le_of_not_gt h) (le_of_succ_le_succ (succ_le_of_lt a.right))], end theorem Lb_dvd:∀ p b a:ℕ,a ∈ Lb (p-1) b→∃ k,k*b=a∧k>0∧k<p:=begin assume p b a,induction p with p1,simp [Lb],simp[Lb],cases p1 with p2,simp[Lb],simp[Lb],assume H,cases H,existsi succ p2,simp[H],rw mul_comm,exact ⟨rfl,dec_trivial,lt_succ_self (succ p2)⟩, rw succ_sub_one at p_ih,cases p_ih H,existsi w,exact ⟨h.left,h.right.left,lt_trans h.right.right (lt_succ_self (succ p2))⟩, end theorem L1Lb : ∀ p c:ℕ,c>0→ prime p → coprime c p→ (∀a:ℕ,a∈(Lb (p-1) 1)→∃(b:ℕ)(H:b∈(Lb (p-1) c)),b≡a[MOD p])∧(∀b:ℕ,b∈(Lb (p-1)c)→∃(a:ℕ)(H:a∈(Lb (p-1) 1)),a≡b[MOD p]):=begin assume p c Hc Hp Hco,have Hp0:=lt_trans (dec_trivial:0<1) (prime.gt_one Hp),apply and.intro,assume a Ha,have Hp0:=lt_trans (dec_trivial:0<1) (prime.gt_one Hp), existsi (a*mod_inv c p)%p*c,rw mem_Lb _ _ _ Hc,simp[mod_lt (a * mod_inv c p) Hp0], have H:=mod_inv_gcd c p Hp0,rw coprime.gcd_eq_one Hco at H, have H1:a * ( c*mod_inv c p ) ≡ a *1 [MOD p]:=modeq.modeq_mul (modeq.refl a) H,rw[mul_comm c,←mul_assoc,mul_one] at H1, have H4:=modeq_mod_cancel (a * mod_inv c p) p, have H2:=modeq.modeq_mul (modeq_mod_cancel (a * mod_inv c p) p) (modeq.refl c), have H3:=modeq.trans H2 H1,simp[H3],cases decidable.em(a * mod_inv c p % p = 0),exfalso,rw [←dvd_iff_mod_eq_zero,prime.dvd_mul Hp] at h,rw[←mul_one a,mem_Lb]at Ha, have:=mod_eq_of_lt Ha.right,rw dvd_iff_mod_eq_zero at h,rw this at h,simp[ne_of_gt Ha.left] at h, rw ←modeq.modeq_zero_iff at h,have :=modeq.symm(modeq.trans (modeq.symm(modeq.modeq_mul (modeq.refl c) h)) H), simp at this,rw modeq.modeq_zero_iff at this,exact prime.not_dvd_one Hp this, exact dec_trivial,cases a * mod_inv c p % p,revert h,simp,exact dec_trivial, assume a Ha,existsi a%p,rw [←mul_one (a%p),mem_Lb _ _ _ (dec_trivial:1>0)],simp,simp[mod_lt a Hp0,modeq_mod_cancel a p], cases decidable.em(a % p = 0),exfalso, rw[←dvd_iff_mod_eq_zero] at h,cases Lb_dvd _ _ _ Ha,rw [←h_1.left,prime.dvd_mul] at h,cases h,have:= mod_eq_of_lt h_1.right.right,rw dvd_iff_mod_eq_zero at h,rw h at this,rw ←this at h_1,exact (dec_trivial:¬0<0) h_1.right.left, have:= coprime.eq_one_of_dvd (coprime.symm Hco) h,rw this at Hp,revert Hp, simp[prime],exact dec_trivial,assumption,cases a%p,exfalso,revert h,exact dec_trivial,exact dec_trivial, end theorem Lb_ne: ∀ (p c k :nat), c>0→(k>0→k<p→count (k*c) (Lb (p-1) c) = 1)∧(k≥p→count (k*c) (Lb (p-1) c) = 0):=begin assume p c k Hc,induction p with p1 Hi,simp [Lb],intro,exact not_lt_zero k,cases p1 with p2,simp[Lb],intro,have:=succ_le_of_lt a,intro,exact not_lt_of_ge this a_1, have Hkp1:k<succ(succ p2) ↔k=succ p2 ∨ k<succ p2:=begin rw ←le_iff_eq_or_lt,rw ←succ_le_succ_iff,apply iff.intro, intro, apply succ_le_of_lt a,intro, apply lt_of_succ_le a, end, rw Hkp1,apply and.intro, assume Hk Hkp,clear Hkp1,cases Hkp,simp at Hi,rw ←Hkp at Hi,have:=Hi.right (le_refl k),simp [Lb],rw [←Hkp,mul_comm,count_cons_self,mul_comm,this], simp at Hi,simp[Lb],rw count_cons_of_ne,exact Hi.left Hk Hkp,rw mul_comm,rw ←mul_lt_mul_left Hc at Hkp,exact ne_of_lt Hkp, assume H,have:= Hi.right (ge_trans H (le_succ _)),simp[Lb],simp at this,rwa count_cons_of_ne, have:=lt_of_lt_of_le (lt_succ_self (succ p2)) H,rw ←mul_lt_mul_left Hc at this,rw mul_comm,apply ne.symm, exact ne_of_lt this, end theorem ladida:∀ c a b p:ℕ,coprime c p →a>0→a<p→b>0→b<p→p>0→(c*a ≡ c*b [MOD p] ↔ a = b):=begin assume c a b p Hco Ha0 Hap Hb0 Hbp Hp0,apply iff.intro, assume Hc,have:=@modeq_mul_cancel c b a p Hp0 Hco,have Hc1:=modeq.symm Hc,rw this at Hc1,clear Hc, simp[modeq] at Hc1,rw [mod_eq_of_lt Hap,mod_eq_of_lt Hbp] at Hc1,rw Hc1,intro,rw a_1, end theorem not_modeq_list:∀ p b:ℕ,coprime b p→p>0→b>0→(∀a₁ a₂:ℕ,a₁∈Lb (p-1) b→a₂∈list.erase (Lb (p-1) b) a₁→¬a₁≡a₂[MOD p]):=begin assume p b Hp Hp0 Hb a₁ a₂ Ha₁ Ha₂,have ha₁:=Lb_dvd _ _ _ Ha₁,have H1:=perm_count (perm_erase Ha₁) a₂,have H2:=iff.elim_right count_pos Ha₂, rw count_cons' at H1,have:=lt_of_lt_of_le H2 (le_add_right _ (ite (a₂ = a₁) 1 0)),rw ←H1 at this,rw count_pos at this, have ha₂:=Lb_dvd _ _ _ this, have :¬a₁=a₂:=begin cases ha₁ with k₁ Hk₁,cases ha₂ with k₂ Hk₂,rw ←Hk₁.left at Ha₁,rw ←Hk₂.left at Ha₂,clear H1, have hk₂:=(Lb_ne p b k₂ Hb).left Hk₂.right.left Hk₂.right.right, rw perm_count (perm_erase Ha₁) at hk₂,rw Hk₁.left at Ha₁ hk₂, rw Hk₂.left at hk₂ Ha₂, assume H,rw [←H,←count_pos] at Ha₂,rw [H,count_cons_self] at hk₂,have :=succ_inj hk₂,rw [H,this] at Ha₂, revert Ha₂,exact dec_trivial, end, cases ha₁ with k₁ Hk₁,cases ha₂ with k₂ Hk₂,rw [←Hk₁.left,←Hk₂.left], rw[mul_comm,mul_comm k₂,ladida b k₁ k₂ p Hp Hk₁.right.left Hk₁.right.right Hk₂.right.left Hk₂.right.right Hp0], rw [←Hk₁.left,←Hk₂.left] at this,intro,rw a at this,revert this,simp, end theorem fact_list :∀ p k:ℕ,p>0→prod (Lb p k)=k^p*fact p:=begin assume p k,induction p with p1,simp [(dec_trivial:¬0>0)],cases p1 with p2,simp[Lb],simp[Lb,fact,pow],simp[Lb,fact,pow] at p_ih,intro, have:=p_ih dec_trivial,rw this,cc, end theorem prime_not_dvd_fact : ∀ p k:ℕ,k<p → prime p→¬p∣fact k:=begin assume p k, induction k with k1,simp [fact,prime],intros,intro,rw a_3 at a_1,revert a_1,exact dec_trivial, assume H H1,simp[fact],assume H3,rw prime.dvd_mul H1 at H3,cases H3, rw [dvd_iff_mod_eq_zero] at H3,rw mod_eq_of_lt H at H3,revert H3,exact dec_trivial, exact k_ih (lt_trans (lt_succ_self _) H) H1 H3, end theorem fermats_little_theorem1 :∀ a p:ℕ,prime p→ coprime a p → a^(p-1) ≡ 1 [MOD p]:=begin assume b p Hp Hpc,have Hp1:(p-1)>0:=nat.sub_pos_of_lt (lt_of_lt_of_le (dec_trivial:1<2) Hp.left), have Hp0:p>0:=by unfold prime at Hp;exact lt_of_lt_of_le (dec_trivial:0<2) Hp.left, rw [←@modeq_mul_cancel (fact(p-1)) (b^(p-1)) 1 p Hp0,mul_comm,mul_comm (fact (p-1)),←fact_list _ _ Hp1],have:∀ p:ℕ, 1=1^p := begin assume p,induction p,simp,rw pow_succ,simp,assumption, end, have H:1 * fact (p - 1) = 1^(p-1) * fact(p-1):=by rw ←this,rw H, clear H this,rw ←fact_list _ _ Hp1, suffices: (∀y:ℕ,countp (λ x,x ≡ y [MOD p]) (Lb (p - 1) b) = countp (λ x,x ≡ y [MOD p]) (Lb (p - 1) 1)), exact modeq_prod_list (Lb (p - 1) b) (Lb (p - 1) 1) p this,revert b, assume c Hpc, suffices :(∀a:ℕ,a∈(Lb (p - 1) c)→∃(b:ℕ)(H:b∈(Lb (p - 1) 1)),b≡a[MOD p])∧(∀b:ℕ,b∈(Lb (p - 1) 1)→∃(a:ℕ)(H:a∈(Lb (p - 1) c)),a≡b[MOD p])∧(∀a₁ a₂:ℕ,a₁∈(Lb (p - 1) c)→a₂∈list.erase (Lb (p - 1) c) a₁→¬a₁≡a₂[MOD p])∧(∀b₁ b₂:ℕ,b₁∈(Lb (p - 1) 1)→b₂∈list.erase (Lb (p - 1) 1) b₁→¬b₁≡b₂[MOD p]), exact L3 (Lb (p - 1) c) (Lb (p - 1) 1) p this.left this.right.left this.right.right.left this.right.right.right, suffices Hc:c>0,rw ←and.assoc, apply and.intro,rw and.comm, exact(L1Lb p c Hc Hp Hpc), apply and.intro,exact not_modeq_list p c Hpc Hp0 Hc, have Hco:coprime 1 p:=begin apply coprime.symm,rw[prime.coprime_iff_not_dvd Hp],exact prime.not_dvd_one Hp, end, exact not_modeq_list p 1 Hco Hp0 (dec_trivial:1>0), cases c,have:=coprime.gcd_eq_one Hpc,exfalso,revert this,simp[gcd],unfold prime at Hp,intro,rw this at Hp,revert Hp,simp [(dec_trivial:¬1≥2)],exact dec_trivial, have Hp3:(p-1)<p:= nat.sub_lt_self (lt_trans (dec_trivial:0<1) (prime.gt_one Hp)) (dec_trivial:1>0), have:=prime_not_dvd_fact p (p-1) Hp3 Hp, rw ←prime.coprime_iff_not_dvd Hp at this, exact coprime.symm this, end theorem fermats_little_theorem : ∀ b p:ℕ,prime p→b^p ≡ b [MOD p]:=begin assume b p,cases decidable.em (p ∣ b) with A A, have H:∀x y z:ℕ, 1≤z→x ∣ y → y^z ≡ 0 [MOD x] :=begin intros x y z H H1, induction z with z1 Hi,exfalso,revert H,exact dec_trivial, cases z1 with z2,simp,rwa nat.modeq.modeq_zero_iff, rw nat.pow_succ,have H2:= Hi dec_trivial,rw nat.modeq.modeq_zero_iff at H2, rw nat.modeq.modeq_zero_iff, exact dvd_mul_of_dvd_left H2 _, end,intro H1,have :1≤ p:=by {unfold nat.prime at H1,exact le_trans (dec_trivial:1≤2) (and.left H1)}, have := H p b p this A,rw ←modeq.modeq_zero_iff at A,have A:= modeq.symm A,exact modeq.trans this A, assume Hp,rw ←prime.coprime_iff_not_dvd Hp at A,have Hp0:p>0:=begin unfold prime at Hp, exact lt_of_lt_of_le (dec_trivial:0<2) (Hp.left) end, suffices :b^(p-1)≡ 1 [MOD p],have h:= modeq.modeq_mul this (modeq.refl b),rwa [one_mul,←pow_succ,←succ_sub,succ_sub_one ]at h, exact le_trans (dec_trivial:1≤2) (prime.ge_two Hp),apply fermats_little_theorem1 b p Hp (coprime.symm A), end end nat
section {* Relational operational semantics *} theory utp_rel_opsem imports "../../Isabelle-UTP-Extended/AlgebraicLaws/Algebraic_Laws" begin text {* This theory uses the laws of relational calculus to create a basic operational semantics. It is based on Chapter 10 of the UTP book~\cite{Hoare&98}. *} fun trel :: "'\<alpha> usubst \<times> '\<alpha> hrel \<Rightarrow> '\<alpha> usubst \<times> '\<alpha> hrel \<Rightarrow> bool" (infix "\<rightarrow>\<^sub>u" 85) where "(\<sigma>, P) \<rightarrow>\<^sub>u (\<rho>, Q) \<longleftrightarrow> (\<langle>\<sigma>\<rangle>\<^sub>a ;; P) \<sqsubseteq> (\<langle>\<rho>\<rangle>\<^sub>a ;; Q)" lemma trans_trel: "\<lbrakk> (\<sigma>, P) \<rightarrow>\<^sub>u (\<rho>, Q); (\<rho>, Q) \<rightarrow>\<^sub>u (\<phi>, R) \<rbrakk> \<Longrightarrow> (\<sigma>, P) \<rightarrow>\<^sub>u (\<phi>, R)" by auto lemma skip_trel: "(\<sigma>, II) \<rightarrow>\<^sub>u (\<sigma>, II)" by simp lemma assigns_trel: "(\<sigma>, \<langle>\<rho>\<rangle>\<^sub>a) \<rightarrow>\<^sub>u (\<rho> \<circ> \<sigma>, II)" by (simp add: assigns_comp) lemma assign_trel: "(\<sigma>, x :== v) \<rightarrow>\<^sub>u (\<sigma>(x \<mapsto>\<^sub>s \<sigma> \<dagger> v), II)" by (simp add: assigns_comp usubst) lemma seq_trel: assumes "(\<sigma>, P) \<rightarrow>\<^sub>u (\<rho>, Q)" shows "(\<sigma>, P ;; R) \<rightarrow>\<^sub>u (\<rho>, Q ;; R)" by (metis (no_types, lifting) assms order_refl seqr_assoc seqr_mono trel.simps) lemma seq_skip_trel: "(\<sigma>, II ;; P) \<rightarrow>\<^sub>u (\<sigma>, P)" by simp lemma nondet_left_trel: "(\<sigma>, P \<sqinter> Q) \<rightarrow>\<^sub>u (\<sigma>, P)" by (metis (no_types, hide_lams) disj_comm disj_upred_def semilattice_sup_class.sup.absorb_iff1 semilattice_sup_class.sup.left_idem seqr_or_distr trel.simps) lemma nondet_right_trel: "(\<sigma>, P \<sqinter> Q) \<rightarrow>\<^sub>u (\<sigma>, Q)" by (simp add: seqr_mono) lemma rcond_true_trel: assumes "\<sigma> \<dagger> b = true" shows "(\<sigma>, P \<triangleleft> b \<triangleright>\<^sub>r Q) \<rightarrow>\<^sub>u (\<sigma>, P)" using assms by (simp add: assigns_r_comp usubst aext_true cond_unit_T) lemma rcond_false_trel: assumes "\<sigma> \<dagger> b = false" shows "(\<sigma>, P \<triangleleft> b \<triangleright>\<^sub>r Q) \<rightarrow>\<^sub>u (\<sigma>, Q)" using assms by (simp add: assigns_r_comp usubst aext_false cond_unit_F) lemma while_true_trel: assumes "\<sigma> \<dagger> b = true" shows "(\<sigma>, while\<^sub>\<bottom> b do P od) \<rightarrow>\<^sub>u (\<sigma>, P ;; while\<^sub>\<bottom> b do P od)" by (metis assms rcond_true_trel while_lfp_rel_unfold) lemma while_false_trel: assumes "\<sigma> \<dagger> b = false" shows "(\<sigma>, while\<^sub>\<bottom> b do P od) \<rightarrow>\<^sub>u (\<sigma>, II)" by (metis assms rcond_false_trel while_lfp_rel_unfold) declare trel.simps [simp del] end
Require Export LClos. Require Import FunInd. Open Scope LClos. (** *** Closure calculus interpreter *) Definition CompBeta s t := match s,t with |CompClos (lam ls) A,CompClos (lam lt) B => Some (CompClos ls (CompClos (lam lt) B::A)) |_,_ => None end. Definition CompAppCount j u v := match u,v with (l,u),(k,v) => (j+(l+k),CompApp u v) end. Fixpoint CompSeval n (u: nat * Comp) : nat * Comp:= match n with S n => match u with | (l,CompApp s t) => match CompBeta s t with | Some u => CompSeval n (S l,u) | None => CompSeval n (CompAppCount l (CompSeval n (0,s)) (CompSeval n (0,t))) end | (l,CompClos (app s t) A) => CompSeval n (l,(CompClos s A) (CompClos t A)) | (l,CompClos (var x) A) => (l,nth x A (CompVar x)) | u => u end | _ => u end. Lemma CompBeta_validComp s t u: validComp s -> validComp t -> CompBeta s t = Some u -> validComp u. Proof with repeat (auto || congruence || subst || simpl in * || intuition). intros vs vt eq. inv vs; inv vt... destruct s0... destruct s,s0... inv eq. repeat constructor... inv H1... Qed. Lemma CompSeval_validComp s k n: validComp s -> validComp (snd (CompSeval n (k,s))). Proof with repeat (apply validCompApp ||apply validCompClos || eauto || congruence || subst || simpl in * || intuition). revert s k. induction n; intros s k vs... inv vs... case_eq (CompBeta s0 t);intros... -apply CompBeta_validComp in H1... -assert (IHn1 := IHn s0 0 H). assert (IHn2 := IHn t 0 H0). unfold snd in *. do 2 destruct ((CompSeval n (_,_)))... -destruct s0... Qed. Hint Resolve CompSeval_validComp. Lemma CompBeta_sound s t u: CompBeta s t = Some u -> s t >[(1)] u. Proof with repeat (auto || congruence || subst || simpl in * || intuition). intros eq. destruct s,t... destruct s... destruct s... destruct s... destruct s0... inv eq. repeat constructor... Qed. Functional Scheme CompSeval_ind := Induction for CompSeval Sort Prop. Lemma CompSeval_sound' n s l : let (k,t) := CompSeval n (l,s) in k >= l /\ s >[(k-l)] t. Proof with (repeat inv_validComp;repeat (constructor || intuition|| subst ; eauto using star || rewrite Nat.sub_diag||cbn in *)). pose (p:= (l,s)). change (let (k, t) := CompSeval n p in k >= fst p /\ (snd p) >[(k-(fst p))] t). generalize p. clear l s p. intros p. functional induction (CompSeval n p); intros;cbn... -apply CompBeta_sound in e2. destruct (CompSeval _ _);split... eapply CPow_trans;try eassumption. omega. -repeat destruct (CompSeval _ _)... eapply CPow_trans... -repeat destruct (CompSeval _ _)... eapply CPow_trans... Qed. Lemma CompSeval_sound (n k:nat) s t : CompSeval n (0,s) = (k,t) -> s >[(k)] t. Proof. specialize (CompSeval_sound' n s 0). destruct _;intros. inv H0. rewrite <- minus_n_O in H. tauto. Qed.
lemmas primes_coprime_int = primes_coprime[where ?'a = nat]
Formal statement is: lemma measure_subadditive_countably: assumes A: "range A \<subseteq> sets M" and fin: "(\<Sum>i. emeasure M (A i)) \<noteq> \<infinity>" shows "measure M (\<Union>i. A i) \<le> (\<Sum>i. measure M (A i))" Informal statement is: If $A_1, A_2, \ldots$ are measurable sets, then the measure of their union is less than or equal to the sum of their measures.
module NeuralNet.Train ( nnBackward, updateNNParams ) where import NeuralNet.Net import NeuralNet.Layer import NeuralNet.Example import NeuralNet.Activation import NeuralNet.Matrix import Numeric.LinearAlgebra nnBackward :: NeuralNet -> [ForwardPropStep] -> ExampleSet -> [(Matrix Double, Matrix Double)] nnBackward nn steps examples | numLayers /= stepsSize - 1 = error ("should be one entry (" ++ show stepsSize ++ ") for each layer (" ++ show numLayers ++ ")") | otherwise = reverse (nnBackwardStep layers orderedSteps dAL) where layers = reverse (nnLayers nn) orderedSteps = reverse steps numLayers = length layers stepsSize = length steps y = exampleSetY examples al = forwardPropA (head orderedSteps) unitRowVector = row (replicate (cols y) 1) dAL1 = y / al dAL2 = (unitRowVector - y) / (unitRowVector - al) dAL = -(dAL1 - dAL2) nnBackwardStep :: [NeuronLayer] -> [ForwardPropStep] -> Matrix Double -> [(Matrix Double, Matrix Double)] nnBackwardStep [] _ _ = [] nnBackwardStep _ [] _ = error "Shouldn't get here" nnBackwardStep _ [_] _ = error "Shouldn't get here" nnBackwardStep (l:ls) (s:ss@(ps:_)) prevDA = (dW, db) : nnBackwardStep ls ss dA where (dA, dW, db) = nnBackwardLayer l prevDA (forwardPropA ps) (forwardPropZ s) nnBackwardLayer :: NeuronLayer -> Matrix Double -> Matrix Double -> Matrix Double -> (Matrix Double, Matrix Double, Matrix Double) nnBackwardLayer l dA prevA z = (dANext, dW, db) where m = fromIntegral (cols prevA) dZ = backward (layerActivation l) dA z dW = scale (1/m) (dZ <> tr prevA) db = scale (1/m) (sumRows dZ) dANext = tr (layerW l) <> dZ updateNNParams :: NeuralNet -> [(Matrix Double, Matrix Double)] -> Double -> NeuralNet updateNNParams nn grads learningRate | length layers /= length grads = error "Must provide one grad per layer" | otherwise = updateNNLayers nn newLayers where layers = nnLayers nn layerSets = zip layers grads newLayers = map (\(l, (dW, dB)) -> updateLayerParamsFromGrads l dW dB learningRate) layerSets updateLayerParamsFromGrads :: NeuronLayer -> Matrix Double -> Matrix Double -> Double -> NeuronLayer updateLayerParamsFromGrads l dW db learningRate = updateLayerParams l newDw newDb where newDw = layerW l - scale learningRate dW newDb = layerB l - scale learningRate db
[STATEMENT] lemma Alt_elim_zeros[simp]: "Alt (elim_zeros r) s ~ elim_zeros (Alt r s)" "Alt r (elim_zeros s) ~ elim_zeros (Alt r s)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Alt (elim_zeros r) s ~ elim_zeros (Alt r s) &&& Alt r (elim_zeros s) ~ elim_zeros (Alt r s) [PROOF STEP] by (smt (verit, ccfv_threshold) ACIDZ.simps elim_zeros.simps(1) elim_zeros_idem)+
[STATEMENT] lemma cart_correct: assumes I[simp, intro!]: "s1.invar s1" "s2.invar s2" shows "s3.\<alpha> (cart s1 s2) = s1.\<alpha> s1 \<times> s2.\<alpha> s2" (is ?T1) "s3.invar (cart s1 s2)" (is ?T2) [PROOF STATE] proof (prove) goal (1 subgoal): 1. s3.\<alpha> (cart s1 s2) = s1.\<alpha> s1 \<times> s2.\<alpha> s2 &&& s3.invar (cart s1 s2) [PROOF STEP] unfolding cart_alt [PROOF STATE] proof (prove) goal (1 subgoal): 1. s3.\<alpha> (inj_image_filter_cartesian_product Some s1 s2) = s1.\<alpha> s1 \<times> s2.\<alpha> s2 &&& s3.invar (inj_image_filter_cartesian_product Some s1 s2) [PROOF STEP] by (auto simp add: inj_image_filter_cartesian_product_correct[OF I, where f=Some])
section \<open>CNOT Circuit\<close> theory CNOT imports Isabelle_Marries_Dirac.Basics Isabelle_Marries_Dirac.Quantum Isabelle_Marries_Dirac.More_Tensor Isabelle_Marries_Dirac.Deutsch begin abbreviation \<psi>\<^sub>0\<^sub>0 :: "complex Matrix.mat" where "\<psi>\<^sub>0\<^sub>0 \<equiv> mat_of_cols_list 4 [[1,0,0,0]]" abbreviation \<psi>\<^sub>1\<^sub>0 :: "complex Matrix.mat" where "\<psi>\<^sub>1\<^sub>0 \<equiv> mat_of_cols_list 4 [[0,0,1,0]]" abbreviation \<psi>\<^sub>1\<^sub>1 :: "complex Matrix.mat" where "\<psi>\<^sub>1\<^sub>1 \<equiv> mat_of_cols_list 4 [[0,0,0,1]]" lemma \<psi>\<^sub>0\<^sub>0_is_zero_zero: shows "\<psi>\<^sub>0\<^sub>0 = |zero\<rangle> \<Otimes> |zero\<rangle>" proof show "dim_row \<psi>\<^sub>0\<^sub>0 = dim_row ( |zero\<rangle> \<Otimes> |zero\<rangle>)" by (simp add: mat_of_cols_list_def) show "dim_col \<psi>\<^sub>0\<^sub>0 = dim_col ( |zero\<rangle> \<Otimes> |zero\<rangle>)" by (simp add: mat_of_cols_list_def) fix i j:: nat assume "i < dim_row ( |zero\<rangle> \<Otimes> |zero\<rangle>)" and "j < dim_col ( |zero\<rangle> \<Otimes> |zero\<rangle>)" then have "i \<in> {0,1,2,3}" and "j = 0" using mat_of_cols_list_def by auto show "\<psi>\<^sub>0\<^sub>0 $$ (i,j) = ( |zero\<rangle> \<Otimes> |zero\<rangle>) $$ (i,j)" using ket_zero_is_state by auto qed lemma \<psi>\<^sub>0\<^sub>0_is_state: shows "state 2 \<psi>\<^sub>0\<^sub>0" proof show "dim_col \<psi>\<^sub>0\<^sub>0 = 1" by (simp add: mat_of_cols_list_def) show "dim_row \<psi>\<^sub>0\<^sub>0 = 2\<^sup>2" by (simp add: mat_of_cols_list_def) have "\<parallel>Matrix.col |zero\<rangle> 0\<parallel> = 1" using ket_zero_is_state state.is_normal by auto thus "\<parallel>Matrix.col \<psi>\<^sub>0\<^sub>0 0\<parallel> = 1" using state.is_normal tensor_state2 \<psi>\<^sub>0\<^sub>0_is_zero_zero ket_zero_is_state by force qed subsection "First Operation" abbreviation X_on_ctrl where "X_on_ctrl \<equiv> (X \<Otimes> Id 1)" lemma X_tensor_id: defines d: "v \<equiv> mat_of_cols_list 4 [[0,0,1,0], [0,0,0,1], [1,0,0,0], [0,1,0,0]]" shows "X_on_ctrl = v" proof show "dim_col X_on_ctrl = dim_col v" by (simp add: d X_def Id_def mat_of_cols_list_def) show "dim_row X_on_ctrl = dim_row v" by (simp add: d X_def Id_def mat_of_cols_list_def) fix i j:: nat assume "i < dim_row v" and "j < dim_col v" then have "i \<in> {0..<4} \<and> j \<in> {0..<4}" by (auto simp add: d mat_of_cols_list_def) thus "X_on_ctrl $$ (i, j) = v $$ (i, j)" by (auto simp add: d Id_def X_def mat_of_cols_list_def) qed lemma X_on_ctrl_is_gate: shows "gate 2 X_on_ctrl" proof show "unitary X_on_ctrl" using X_is_gate id_is_gate gate_def tensor_gate by blast show "square_mat X_on_ctrl" using X_is_gate id_is_gate gate_def tensor_gate by blast show "dim_row X_on_ctrl = 2\<^sup>2" using X_tensor_id by (simp add: mat_of_cols_list_def) qed lemma \<psi>\<^sub>0\<^sub>0_to_\<psi>\<^sub>1\<^sub>0: shows "(X \<Otimes> Id 1) * \<psi>\<^sub>0\<^sub>0 = \<psi>\<^sub>1\<^sub>0" proof fix i j:: nat assume "i < dim_row \<psi>\<^sub>1\<^sub>0" and "j < dim_col \<psi>\<^sub>1\<^sub>0" then have a0:"i \<in> {0,1,2,3} \<and> j = 0" by (auto simp add: mat_of_cols_list_def) then have "i < dim_row (X_on_ctrl) \<and> j < dim_col \<psi>\<^sub>0\<^sub>0" using mat_of_cols_list_def X_tensor_id by auto then have "(X_on_ctrl*\<psi>\<^sub>0\<^sub>0) $$ (i,j) = (\<Sum> k \<in> {0 ..< dim_vec \<psi>\<^sub>0\<^sub>0}. (Matrix.row (X_on_ctrl) i) $ k * (Matrix.col \<psi>\<^sub>0\<^sub>0 j) $ k)" by (auto simp: times_mat_def scalar_prod_def) thus "(X_on_ctrl * \<psi>\<^sub>0\<^sub>0) $$ (i, j) = \<psi>\<^sub>1\<^sub>0 $$ (i, j)" using mat_of_cols_list_def X_tensor_id a0 by (auto simp: diff_divide_distrib) next show "dim_row (X_on_ctrl * \<psi>\<^sub>0\<^sub>0) = dim_row \<psi>\<^sub>1\<^sub>0" using X_tensor_id mat_of_cols_list_def by simp show "dim_col (X_on_ctrl * \<psi>\<^sub>0\<^sub>0) = dim_col \<psi>\<^sub>1\<^sub>0" using X_tensor_id mat_of_cols_list_def by simp qed lemma \<psi>\<^sub>1\<^sub>0_is_state: shows "state 2 \<psi>\<^sub>1\<^sub>0" using X_on_ctrl_is_gate \<psi>\<^sub>0\<^sub>0_is_state \<psi>\<^sub>0\<^sub>0_to_\<psi>\<^sub>1\<^sub>0 by (metis gate_on_state_is_state) subsection "Second Operation" lemma \<psi>\<^sub>1\<^sub>0_to_\<psi>\<^sub>1\<^sub>1: shows "CNOT * \<psi>\<^sub>1\<^sub>0 = \<psi>\<^sub>1\<^sub>1" proof show "dim_row (CNOT * \<psi>\<^sub>1\<^sub>0) = dim_row \<psi>\<^sub>1\<^sub>1" by (simp add: CNOT_def mat_of_cols_list_def) show "dim_col (CNOT * \<psi>\<^sub>1\<^sub>0) = dim_col \<psi>\<^sub>1\<^sub>1" by (simp add: CNOT_def mat_of_cols_list_def) fix i j:: nat assume "i < dim_row \<psi>\<^sub>1\<^sub>1" and "j < dim_col \<psi>\<^sub>1\<^sub>1" then have asm:"i \<in> {0,1,2,3} \<and> j = 0" by (auto simp add: mat_of_cols_list_def) then have "i < dim_row CNOT \<and> j < dim_col \<psi>\<^sub>1\<^sub>0" by (auto simp: mat_of_cols_list_def CNOT_def) then have "(CNOT * \<psi>\<^sub>1\<^sub>0) $$ (i,j) = (\<Sum> k \<in> {0 ..< dim_vec \<psi>\<^sub>1\<^sub>0}. (Matrix.row (CNOT) i) $ k * (Matrix.col \<psi>\<^sub>1\<^sub>0 j) $ k)" by (auto simp: times_mat_def scalar_prod_def) thus "(CNOT * \<psi>\<^sub>1\<^sub>0) $$ (i, j) = \<psi>\<^sub>1\<^sub>1 $$ (i, j)" using mat_of_cols_list_def asm by (auto simp add: CNOT_def) qed lemma \<psi>\<^sub>1\<^sub>1_is_state: shows "state 2 \<psi>\<^sub>1\<^sub>1" using CNOT_is_gate \<psi>\<^sub>1\<^sub>0_is_state \<psi>\<^sub>1\<^sub>0_to_\<psi>\<^sub>1\<^sub>1 by (metis gate_on_state_is_state) subsection "Circuit" definition circ:: "complex Matrix.mat" where "circ \<equiv> CNOT * ((X_on_ctrl) * ( |zero\<rangle> \<Otimes> |zero\<rangle>))" lemma circ_result [simp]: shows "circ = \<psi>\<^sub>1\<^sub>1" using circ_def \<psi>\<^sub>0\<^sub>0_is_zero_zero \<psi>\<^sub>0\<^sub>0_to_\<psi>\<^sub>1\<^sub>0 \<psi>\<^sub>1\<^sub>0_to_\<psi>\<^sub>1\<^sub>1 by simp lemma circ_res_is_state: shows "state 2 circ" using \<psi>\<^sub>1\<^sub>1_is_state by auto end
------------------------------------------------------------------------ -- Formalisation of subtyping for recursive types -- -- Nils Anders Danielsson ------------------------------------------------------------------------ -- This formalisation is explained in "Subtyping, Declaratively—An -- Exercise in Mixed Induction and Coinduction" (coauthored with -- Thorsten Altenkirch). The code is partly based on "Coinductive -- Axiomatization of Recursive Type Equality and Subtyping" by Michael -- Brandt and Fritz Henglein. module RecursiveTypes where -- Recursive types and potentially infinite trees. import RecursiveTypes.Syntax -- Substitutions. import RecursiveTypes.Substitution -- The semantics of recursive types, defined in terms of the trees -- that you get when unfolding them. import RecursiveTypes.Semantics -- The definition of subtyping which, in my eyes, is the most obvious. -- Some people may dislike coinductive definitions, though. import RecursiveTypes.Subtyping.Semantic.Coinductive -- An example. import RecursiveTypes.Subtyping.Example -- Another definition of subtyping, this time in terms of finite -- approximations. According to Brandt and Henglein this definition is -- due to Amadio and Cardelli. import RecursiveTypes.Subtyping.Semantic.Inductive -- The two semantical definitions of subtyping above can easily be -- proved equivalent. import RecursiveTypes.Subtyping.Semantic.Equivalence -- An axiomatisation of subtyping which is inspired by Brandt and -- Henglein's. The main difference is that their axiomatisation is -- inductive, using explicit hypotheses to get a coinductive flavour, -- whereas mine is mixed inductive/coinductive, using no explicit -- hypotheses. The axiomatisation is proved equivalent to the -- coinductive semantic definition of subtyping. The proof is a lot -- simpler than Brandt and Henglein's, but their proof includes a -- decision procedure for subtyping. import RecursiveTypes.Subtyping.Axiomatic.Coinductive -- Brandt and Henglein's axiomatisation, plus some proofs: -- • A proof showing that the axiomatisation is sound with respect to -- the ones above. The soundness proof is different from the one -- given by Brandt and Henglein: it is cyclic (but productive). -- • Proofs of decidability and completeness, based on Brandt and -- Henglein's algorithm. import RecursiveTypes.Subtyping.Axiomatic.Inductive -- Some modules containing supporting code for the proof of -- decidability, including Brandt and Henglein's subterm relation. import RecursiveTypes.Subterm import RecursiveTypes.Subterm.RestrictedHypothesis import RecursiveTypes.Syntax.UnfoldedOrFixpoint -- An incorrect "subtyping" relation which illustrates the fact that -- taking the transitive closure of a coinductively defined relation -- is not in general equivalent to adding an inductive transitivity -- constructor to it. import RecursiveTypes.Subtyping.Axiomatic.Incorrect -- Finally some code which is not directly related to subtyping or -- recursive types: an example which shows that, in a coinductive -- setting, it is not always sound to postulate admissible rules -- (inductively). import AdmissibleButNotPostulable