text
stringlengths 0
3.34M
|
---|
(* Title: HOL/Auth/Guard/List_Msg.thy
Author: Frederic Blanqui, University of Cambridge Computer Laboratory
Copyright 2001 University of Cambridge
*)
section\<open>Lists of Messages and Lists of Agents\<close>
theory List_Msg imports Extensions begin
subsection\<open>Implementation of Lists by Messages\<close>
subsubsection\<open>nil is represented by any message which is not a pair\<close>
abbreviation (input)
cons :: "msg => msg => msg" where
"cons x l == \<lbrace>x,l\<rbrace>"
subsubsection\<open>induction principle\<close>
lemma lmsg_induct: "[| !!x. not_MPair x ==> P x; !!x l. P l ==> P (cons x l) |]
==> P l"
by (induct l) auto
subsubsection\<open>head\<close>
primrec head :: "msg => msg" where
"head (cons x l) = x"
subsubsection\<open>tail\<close>
primrec tail :: "msg => msg" where
"tail (cons x l) = l"
subsubsection\<open>length\<close>
fun len :: "msg => nat" where
"len (cons x l) = Suc (len l)" |
"len other = 0"
lemma len_not_empty: "n < len l \<Longrightarrow> \<exists>x l'. l = cons x l'"
by (cases l) auto
subsubsection\<open>membership\<close>
fun isin :: "msg * msg => bool" where
"isin (x, cons y l) = (x=y | isin (x,l))" |
"isin (x, other) = False"
subsubsection\<open>delete an element\<close>
fun del :: "msg * msg => msg" where
"del (x, cons y l) = (if x=y then l else cons y (del (x,l)))" |
"del (x, other) = other"
lemma notin_del [simp]: "~ isin (x,l) ==> del (x,l) = l"
by (induct l) auto
lemma isin_del [rule_format]: "isin (y, del (x,l)) --> isin (y,l)"
by (induct l) auto
subsubsection\<open>concatenation\<close>
fun app :: "msg * msg => msg" where
"app (cons x l, l') = cons x (app (l,l'))" |
"app (other, l') = l'"
lemma isin_app [iff]: "isin (x, app(l,l')) = (isin (x,l) | isin (x,l'))"
by (induct l) auto
subsubsection\<open>replacement\<close>
fun repl :: "msg * nat * msg => msg" where
"repl (cons x l, Suc i, x') = cons x (repl (l,i,x'))" |
"repl (cons x l, 0, x') = cons x' l" |
"repl (other, i, M') = other"
subsubsection\<open>ith element\<close>
fun ith :: "msg * nat => msg" where
"ith (cons x l, Suc i) = ith (l,i)" |
"ith (cons x l, 0) = x" |
"ith (other, i) = other"
lemma ith_head: "0 < len l ==> ith (l,0) = head l"
by (cases l) auto
subsubsection\<open>insertion\<close>
fun ins :: "msg * nat * msg => msg" where
"ins (cons x l, Suc i, y) = cons x (ins (l,i,y))" |
"ins (l, 0, y) = cons y l"
lemma ins_head [simp]: "ins (l,0,y) = cons y l"
by (cases l) auto
subsubsection\<open>truncation\<close>
fun trunc :: "msg * nat => msg" where
"trunc (l,0) = l" |
"trunc (cons x l, Suc i) = trunc (l,i)"
lemma trunc_zero [simp]: "trunc (l,0) = l"
by (cases l) auto
subsection\<open>Agent Lists\<close>
subsubsection\<open>set of well-formed agent-list messages\<close>
abbreviation
nil :: msg where
"nil == Number 0"
inductive_set agl :: "msg set"
where
Nil[intro]: "nil \<in> agl"
| Cons[intro]: "[| A \<in> agent; I \<in> agl |] ==> cons (Agent A) I \<in> agl"
subsubsection\<open>basic facts about agent lists\<close>
lemma del_in_agl [intro]: "I \<in> agl \<Longrightarrow> del (a,I) \<in> agl"
by (erule agl.induct, auto)
lemma app_in_agl [intro]: "[| I \<in> agl; J \<in> agl |] ==> app (I,J) \<in> agl"
by (erule agl.induct, auto)
lemma no_Key_in_agl: "I \<in> agl \<Longrightarrow> Key K \<notin> parts {I}"
by (erule agl.induct, auto)
lemma no_Nonce_in_agl: "I \<in> agl \<Longrightarrow> Nonce n \<notin> parts {I}"
by (erule agl.induct, auto)
lemma no_Key_in_appdel: "[| I \<in> agl; J \<in> agl |] ==>
Key K \<notin> parts {app (J, del (Agent B, I))}"
by (rule no_Key_in_agl, auto)
lemma no_Nonce_in_appdel: "[| I \<in> agl; J \<in> agl |] ==>
Nonce n \<notin> parts {app (J, del (Agent B, I))}"
by (rule no_Nonce_in_agl, auto)
lemma no_Crypt_in_agl: "I \<in> agl \<Longrightarrow> Crypt K X \<notin> parts {I}"
by (erule agl.induct, auto)
lemma no_Crypt_in_appdel: "[| I \<in> agl; J \<in> agl |] ==>
Crypt K X \<notin> parts {app (J, del (Agent B,I))}"
by (rule no_Crypt_in_agl, auto)
end
|
-- --------------------------------------------------------------- [ Types.idr ]
-- Module : Text.Kindle.Clippings.Types
--
-- License : This code is distributed under the MIT license. See the
-- file LICENSE in the root directory for its full text.
-- --------------------------------------------------------------------- [ EOH ]
module Text.Kindle.Clippings.Types
import Data.Vect
import public Data.Date
%access public export
%default total
-- ---------------------------------------------------------------- [ Document ]
||| A title is a string.
Title : Type
Title = String
||| An author is a string.
Author : Type
Author = String
||| A document consists of a title and and maybe an author.
record Document where
||| Make a document.
constructor Doc
||| The title of the document.
title : Title
||| The possible missing author of the document.
author : Maybe Author
implementation Show Document where
show (Doc title Nothing) = title
show (Doc title (Just author)) = title ++ " (" ++ author ++ ")"
implementation Eq Document where
(Doc titleA authorA) == (Doc titleB authorB) =
titleA == titleB &&
authorA == authorB
-- ---------------------------------------------------------------- [ Interval ]
||| An interval is either a single integer or a range of integers.
data Interval : Type where
||| A single place, i.e. `Page' or `Location'.
Singleton : Integer -> Interval
||| A range.
||| @ from The start of the range.
||| @ to The end of the range.
Proper : (from, to : Integer) -> Interval
||| A page is an interval.
Page : Type
Page = Interval
||| A location is an interval.
Location : Type
Location = Interval
implementation Show Interval where
show (Singleton x) = show x
show (Proper from to) = show from ++ "-" ++ show to
-- ---------------------------------------------------------------- [ Position ]
||| A position consists of a page, location or both.
data Position : Type where
||| A page with no location.
||| @ page A page.
PP : (page : Page) -> Position
||| A location with no page.
||| @ loc A location.
Loc : (loc : Location) -> Position
||| A page and location
||| @ page A page.
||| @ loc A location.
PPLoc : (page : Page) -> (loc : Location) -> Position
||| Given a page, location or both, return a position. If both inputs are
||| `Nothing`, return `Nothing`.
||| @ page Maybe a page.
||| @ loc Maybe a location.
mkPosition : (page : Maybe Page) -> (loc : Maybe Location) -> Maybe Position
mkPosition Nothing Nothing = Nothing
mkPosition Nothing (Just loc) = Just $ Loc loc
mkPosition (Just page) Nothing = Just $ PP page
mkPosition (Just page) (Just loc) = Just $ PPLoc page loc
implementation Show Position where
show (PP page) = "page " ++ show page
show (Loc loc) = "Location " ++ show loc
show (PPLoc page loc) = unwords [ show page, "|", show loc ]
-- ----------------------------------------------------------------- [ Content ]
||| Content is either a bookmark, some highlight text, or a note.
data Content : Type where
||| A bookmark.
Bookmark : Content
||| Some highlighted text.
||| @ selection The highlight text.
Highlight : (selection : String) -> Content
||| A note.
||| @ body The body of a note.
Note : (body : String) -> Content
||| If a given string can be parsed as a `Content` data constructor, return just
||| a function that takes a string and returns the appropriate `Content`. If the
||| string can't be parsed, return `Nothing`. N.B. The resulting `Bookmark`
||| function ignores it's input. This makes it easier to use when parsing
||| clippings.
||| @ type A string representing a `Content` data constructor.
mkContent : (type : String) -> Maybe (String -> Content)
mkContent "Bookmark" = Just (const Bookmark)
mkContent "Highlight" = Just Highlight
mkContent "Note" = Just Note
mkContent _ = Nothing
contentType : Content -> String
contentType Bookmark = "Bookmark"
contentType (Highlight _) = "Highlight"
contentType (Note _) = "Note"
implementation Show Content where
show Bookmark = "Bookmark"
show (Highlight selection) = selection
show (Note body) = body
-- ---------------------------------------------------------------- [ Clipping ]
||| A Kindle clipping consists of a document, position, date and content.
record Clipping where
||| Make a clipping.
constructor Clip
||| A document.
document : Document
||| A position.
position : Position
||| A date.
date : Date
||| Some content.
content : Content
implementation Show Clipping where
show (Clip document position date content) =
unlines [ show document
, unwords [ "Your", contentType content, "on", show position
, "| Added on", show date ]
, ""
, show content
, "==========" ]
-- --------------------------------------------------------------------- [ EOF ]
|
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝¹ : Semiring R
p q r : R[X]
inst✝ : DecidableEq R
⊢ Decidable (Monic p)
[PROOFSTEP]
unfold Monic
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝¹ : Semiring R
p q r : R[X]
inst✝ : DecidableEq R
⊢ Decidable (leadingCoeff p = 1)
[PROOFSTEP]
infer_instance
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝¹ : Semiring R
p q r : R[X]
inst✝ : Subsingleton R
⊢ degree p = ⊥
[PROOFSTEP]
rw [Subsingleton.elim p 0, degree_zero]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝¹ : Semiring R
p q r : R[X]
inst✝ : Subsingleton R
⊢ natDegree p = 0
[PROOFSTEP]
rw [Subsingleton.elim p 0, natDegree_zero]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q r : R[X]
hp : p ≠ 0
⊢ degree p = ↑(natDegree p)
[PROOFSTEP]
let ⟨n, hn⟩ := not_forall.1 (mt Option.eq_none_iff_forall_not_mem.2 (mt degree_eq_bot.1 hp))
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q r : R[X]
hp : p ≠ 0
n : ℕ
hn : ¬¬n ∈ degree p
⊢ degree p = ↑(natDegree p)
[PROOFSTEP]
have hn : degree p = some n := Classical.not_not.1 hn
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q r : R[X]
hp : p ≠ 0
n : ℕ
hn✝ : ¬¬n ∈ degree p
hn : degree p = Option.some n
⊢ degree p = ↑(natDegree p)
[PROOFSTEP]
rw [natDegree, hn]
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q r : R[X]
hp : p ≠ 0
n : ℕ
hn✝ : ¬¬n ∈ degree p
hn : degree p = Option.some n
⊢ Option.some n = ↑(WithBot.unbot' 0 (Option.some n))
[PROOFSTEP]
rfl
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q r p : R[X]
n : ℕ
hp : p ≠ 0
⊢ degree p = ↑n ↔ natDegree p = n
[PROOFSTEP]
rw [degree_eq_natDegree hp]
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q r p : R[X]
n : ℕ
hp : p ≠ 0
⊢ ↑(natDegree p) = ↑n ↔ natDegree p = n
[PROOFSTEP]
exact WithBot.coe_eq_coe
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q r p : R[X]
n : ℕ
hn : 0 < n
⊢ degree p = ↑n ↔ natDegree p = n
[PROOFSTEP]
constructor
[GOAL]
case mp
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q r p : R[X]
n : ℕ
hn : 0 < n
⊢ degree p = ↑n → natDegree p = n
[PROOFSTEP]
intro H
[GOAL]
case mp
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q r p : R[X]
n : ℕ
hn : 0 < n
H : degree p = ↑n
⊢ natDegree p = n
[PROOFSTEP]
rwa [← degree_eq_iff_natDegree_eq]
[GOAL]
case mp
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q r p : R[X]
n : ℕ
hn : 0 < n
H : degree p = ↑n
⊢ p ≠ 0
[PROOFSTEP]
rintro rfl
[GOAL]
case mp
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q r : R[X]
n : ℕ
hn : 0 < n
H : degree 0 = ↑n
⊢ False
[PROOFSTEP]
rw [degree_zero] at H
[GOAL]
case mp
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q r : R[X]
n : ℕ
hn : 0 < n
H : ⊥ = ↑n
⊢ False
[PROOFSTEP]
exact Option.noConfusion H
[GOAL]
case mpr
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q r p : R[X]
n : ℕ
hn : 0 < n
⊢ natDegree p = n → degree p = ↑n
[PROOFSTEP]
intro H
[GOAL]
case mpr
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q r p : R[X]
n : ℕ
hn : 0 < n
H : natDegree p = n
⊢ degree p = ↑n
[PROOFSTEP]
rwa [degree_eq_iff_natDegree_eq]
[GOAL]
case mpr
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q r p : R[X]
n : ℕ
hn : 0 < n
H : natDegree p = n
⊢ p ≠ 0
[PROOFSTEP]
rintro rfl
[GOAL]
case mpr
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q r : R[X]
n : ℕ
hn : 0 < n
H : natDegree 0 = n
⊢ False
[PROOFSTEP]
rw [natDegree_zero] at H
[GOAL]
case mpr
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q r : R[X]
n : ℕ
hn : 0 < n
H : 0 = n
⊢ False
[PROOFSTEP]
rw [H] at hn
[GOAL]
case mpr
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q r : R[X]
n : ℕ
hn : n < n
H : 0 = n
⊢ False
[PROOFSTEP]
exact lt_irrefl _ hn
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q r p : R[X]
n : ℕ
h : degree p = ↑n
⊢ natDegree p = n
[PROOFSTEP]
rw [natDegree, h, Nat.cast_withBot, WithBot.unbot'_coe]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝¹ : Semiring R
p q✝ r : R[X]
inst✝ : Semiring S
q : S[X]
h : degree p = degree q
⊢ natDegree p = natDegree q
[PROOFSTEP]
unfold natDegree
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝¹ : Semiring R
p q✝ r : R[X]
inst✝ : Semiring S
q : S[X]
h : degree p = degree q
⊢ WithBot.unbot' 0 (degree p) = WithBot.unbot' 0 (degree q)
[PROOFSTEP]
rw [h]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q r : R[X]
h : coeff p n ≠ 0
⊢ n ≤ natDegree p
[PROOFSTEP]
rw [← Nat.cast_le (α := WithBot ℕ), ← degree_eq_natDegree]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q r : R[X]
h : coeff p n ≠ 0
⊢ ↑n ≤ degree p
R : Type u S : Type v a b c d : R n m : ℕ inst✝ : Semiring R p q r : R[X] h : coeff p n ≠ 0 ⊢ p ≠ 0
[PROOFSTEP]
exact le_degree_of_ne_zero h
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q r : R[X]
h : coeff p n ≠ 0
⊢ p ≠ 0
[PROOFSTEP]
rintro rfl
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
q r : R[X]
h : coeff 0 n ≠ 0
⊢ False
[PROOFSTEP]
exact h rfl
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q r : R[X]
h : coeff q (natDegree p) ≠ 0
⊢ degree p ≤ degree q
[PROOFSTEP]
by_cases hp : p = 0
[GOAL]
case pos
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q r : R[X]
h : coeff q (natDegree p) ≠ 0
hp : p = 0
⊢ degree p ≤ degree q
[PROOFSTEP]
rw [hp]
[GOAL]
case pos
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q r : R[X]
h : coeff q (natDegree p) ≠ 0
hp : p = 0
⊢ degree 0 ≤ degree q
[PROOFSTEP]
exact bot_le
[GOAL]
case neg
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q r : R[X]
h : coeff q (natDegree p) ≠ 0
hp : ¬p = 0
⊢ degree p ≤ degree q
[PROOFSTEP]
rw [degree_eq_natDegree hp]
[GOAL]
case neg
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q r : R[X]
h : coeff q (natDegree p) ≠ 0
hp : ¬p = 0
⊢ ↑(natDegree p) ≤ degree q
[PROOFSTEP]
exact le_degree_of_ne_zero h
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ r p q : R[X]
hp : p ≠ 0
hpq : degree p < degree q
⊢ natDegree p < natDegree q
[PROOFSTEP]
by_cases hq : q = 0
[GOAL]
case pos
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ r p q : R[X]
hp : p ≠ 0
hpq : degree p < degree q
hq : q = 0
⊢ natDegree p < natDegree q
[PROOFSTEP]
exact (not_lt_bot <| hq ▸ hpq).elim
[GOAL]
case neg
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ r p q : R[X]
hp : p ≠ 0
hpq : degree p < degree q
hq : ¬q = 0
⊢ natDegree p < natDegree q
[PROOFSTEP]
rwa [degree_eq_natDegree hp, degree_eq_natDegree hq, Nat.cast_lt] at hpq
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q r : R[X]
ha : a ≠ 0
⊢ degree (↑C a) = 0
[PROOFSTEP]
rw [degree, ← monomial_zero_left, support_monomial 0 ha, max_eq_sup_coe, sup_singleton, WithBot.coe_zero]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q r : R[X]
⊢ degree (↑C a) ≤ 0
[PROOFSTEP]
by_cases h : a = 0
[GOAL]
case pos
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q r : R[X]
h : a = 0
⊢ degree (↑C a) ≤ 0
[PROOFSTEP]
rw [h, C_0]
[GOAL]
case pos
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q r : R[X]
h : a = 0
⊢ degree 0 ≤ 0
[PROOFSTEP]
exact bot_le
[GOAL]
case neg
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q r : R[X]
h : ¬a = 0
⊢ degree (↑C a) ≤ 0
[PROOFSTEP]
rw [degree_C h]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q r : R[X]
⊢ degree 1 ≤ 0
[PROOFSTEP]
rw [← C_1]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q r : R[X]
⊢ degree (↑C 1) ≤ 0
[PROOFSTEP]
exact degree_C_le
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n m : ℕ
inst✝ : Semiring R
p q r : R[X]
a : R
⊢ natDegree (↑C a) = 0
[PROOFSTEP]
by_cases ha : a = 0
[GOAL]
case pos
R : Type u
S : Type v
a✝ b c d : R
n m : ℕ
inst✝ : Semiring R
p q r : R[X]
a : R
ha : a = 0
⊢ natDegree (↑C a) = 0
[PROOFSTEP]
have : C a = 0 := by rw [ha, C_0]
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n m : ℕ
inst✝ : Semiring R
p q r : R[X]
a : R
ha : a = 0
⊢ ↑C a = 0
[PROOFSTEP]
rw [ha, C_0]
[GOAL]
case pos
R : Type u
S : Type v
a✝ b c d : R
n m : ℕ
inst✝ : Semiring R
p q r : R[X]
a : R
ha : a = 0
this : ↑C a = 0
⊢ natDegree (↑C a) = 0
[PROOFSTEP]
rw [natDegree, degree_eq_bot.2 this]
[GOAL]
case pos
R : Type u
S : Type v
a✝ b c d : R
n m : ℕ
inst✝ : Semiring R
p q r : R[X]
a : R
ha : a = 0
this : ↑C a = 0
⊢ WithBot.unbot' 0 ⊥ = 0
[PROOFSTEP]
rfl
[GOAL]
case neg
R : Type u
S : Type v
a✝ b c d : R
n m : ℕ
inst✝ : Semiring R
p q r : R[X]
a : R
ha : ¬a = 0
⊢ natDegree (↑C a) = 0
[PROOFSTEP]
rw [natDegree, degree_C ha]
[GOAL]
case neg
R : Type u
S : Type v
a✝ b c d : R
n m : ℕ
inst✝ : Semiring R
p q r : R[X]
a : R
ha : ¬a = 0
⊢ WithBot.unbot' 0 0 = 0
[PROOFSTEP]
rfl
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q r : R[X]
n : ℕ
⊢ natDegree ↑n = 0
[PROOFSTEP]
simp only [← C_eq_nat_cast, natDegree_C]
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q r : R[X]
n : ℕ
⊢ natDegree ↑n ≤ Zero.zero
[PROOFSTEP]
simp
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q r : R[X]
n : ℕ
ha : a ≠ 0
⊢ degree (↑(monomial n) a) = ↑n
[PROOFSTEP]
rw [degree, support_monomial n ha]
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q r : R[X]
n : ℕ
ha : a ≠ 0
⊢ Finset.max {n} = ↑n
[PROOFSTEP]
rfl
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q r : R[X]
n : ℕ
ha : a ≠ 0
⊢ degree (↑C a * X ^ n) = ↑n
[PROOFSTEP]
rw [C_mul_X_pow_eq_monomial, degree_monomial n ha]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q r : R[X]
ha : a ≠ 0
⊢ degree (↑C a * X) = 1
[PROOFSTEP]
simpa only [pow_one] using degree_C_mul_X_pow 1 ha
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q r : R[X]
n : ℕ
a : R
h : a = 0
⊢ degree (↑(monomial n) a) ≤ ↑n
[PROOFSTEP]
rw [h, (monomial n).map_zero]
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q r : R[X]
n : ℕ
a : R
h : a = 0
⊢ degree 0 ≤ ↑n
[PROOFSTEP]
exact bot_le
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q r : R[X]
n : ℕ
a : R
⊢ degree (↑C a * X ^ n) ≤ ↑n
[PROOFSTEP]
rw [C_mul_X_pow_eq_monomial]
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q r : R[X]
n : ℕ
a : R
⊢ degree (↑(monomial n) a) ≤ ↑n
[PROOFSTEP]
apply degree_monomial_le
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n m : ℕ
inst✝ : Semiring R
p q r : R[X]
a : R
⊢ degree (↑C a * X) ≤ 1
[PROOFSTEP]
simpa only [pow_one] using degree_C_mul_X_pow_le 1 a
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n m : ℕ
inst✝ : Semiring R
p q r : R[X]
a : R
ha : a ≠ 0
⊢ natDegree (↑C a * X) = 1
[PROOFSTEP]
simpa only [pow_one] using natDegree_C_mul_X_pow 1 a ha
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝¹ : Semiring R
p q r✝ : R[X]
inst✝ : DecidableEq R
i : ℕ
r : R
⊢ natDegree (↑(monomial i) r) = if r = 0 then 0 else i
[PROOFSTEP]
split_ifs with hr
[GOAL]
case pos
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝¹ : Semiring R
p q r✝ : R[X]
inst✝ : DecidableEq R
i : ℕ
r : R
hr : r = 0
⊢ natDegree (↑(monomial i) r) = 0
[PROOFSTEP]
simp [hr]
[GOAL]
case neg
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝¹ : Semiring R
p q r✝ : R[X]
inst✝ : DecidableEq R
i : ℕ
r : R
hr : ¬r = 0
⊢ natDegree (↑(monomial i) r) = i
[PROOFSTEP]
rw [← C_mul_X_pow_eq_monomial, natDegree_C_mul_X_pow i r hr]
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n m✝ : ℕ
inst✝ : Semiring R
p q r : R[X]
a : R
m : ℕ
⊢ natDegree (↑(monomial m) a) ≤ m
[PROOFSTEP]
rw [Polynomial.natDegree_monomial]
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n m✝ : ℕ
inst✝ : Semiring R
p q r : R[X]
a : R
m : ℕ
⊢ (if a = 0 then 0 else m) ≤ m
[PROOFSTEP]
split_ifs
[GOAL]
case pos
R : Type u
S : Type v
a✝ b c d : R
n m✝ : ℕ
inst✝ : Semiring R
p q r : R[X]
a : R
m : ℕ
h✝ : a = 0
⊢ 0 ≤ m
case neg R : Type u S : Type v a✝ b c d : R n m✝ : ℕ inst✝ : Semiring R p q r : R[X] a : R m : ℕ h✝ : ¬a = 0 ⊢ m ≤ m
[PROOFSTEP]
exacts [Nat.zero_le _, rfl.le]
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q r p : R[X]
n : ℕ
h : natDegree p < n
⊢ coeff p n = 0
[PROOFSTEP]
apply coeff_eq_zero_of_degree_lt
[GOAL]
case h
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q r p : R[X]
n : ℕ
h : natDegree p < n
⊢ degree p < ↑n
[PROOFSTEP]
by_cases hp : p = 0
[GOAL]
case pos
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q r p : R[X]
n : ℕ
h : natDegree p < n
hp : p = 0
⊢ degree p < ↑n
[PROOFSTEP]
subst hp
[GOAL]
case pos
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q r : R[X]
n : ℕ
h : natDegree 0 < n
⊢ degree 0 < ↑n
[PROOFSTEP]
exact WithBot.bot_lt_coe n
[GOAL]
case neg
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q r p : R[X]
n : ℕ
h : natDegree p < n
hp : ¬p = 0
⊢ degree p < ↑n
[PROOFSTEP]
rwa [degree_eq_natDegree hp, Nat.cast_lt]
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q✝ r p q : R[X]
n : ℕ
hp : natDegree p ≤ n
hq : natDegree q ≤ n
⊢ p = q ↔ ∀ (i : ℕ), i ≤ n → coeff p i = coeff q i
[PROOFSTEP]
refine' Iff.trans Polynomial.ext_iff _
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q✝ r p q : R[X]
n : ℕ
hp : natDegree p ≤ n
hq : natDegree q ≤ n
⊢ (∀ (n : ℕ), coeff p n = coeff q n) ↔ ∀ (i : ℕ), i ≤ n → coeff p i = coeff q i
[PROOFSTEP]
refine' forall_congr' fun i => ⟨fun h _ => h, fun h => _⟩
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q✝ r p q : R[X]
n : ℕ
hp : natDegree p ≤ n
hq : natDegree q ≤ n
i : ℕ
h : i ≤ n → coeff p i = coeff q i
⊢ coeff p i = coeff q i
[PROOFSTEP]
refine' (le_or_lt i n).elim h fun k => _
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q✝ r p q : R[X]
n : ℕ
hp : natDegree p ≤ n
hq : natDegree q ≤ n
i : ℕ
h : i ≤ n → coeff p i = coeff q i
k : n < i
⊢ coeff p i = coeff q i
[PROOFSTEP]
exact (coeff_eq_zero_of_natDegree_lt (hp.trans_lt k)).trans (coeff_eq_zero_of_natDegree_lt (hq.trans_lt k)).symm
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q r p : R[X]
n : ℕ
I : Decidable (n < 1 + natDegree p)
⊢ (if n < 1 + natDegree p then coeff p n else 0) = coeff p n
[PROOFSTEP]
split_ifs with h
[GOAL]
case pos
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q r p : R[X]
n : ℕ
I : Decidable (n < 1 + natDegree p)
h : n < 1 + natDegree p
⊢ coeff p n = coeff p n
[PROOFSTEP]
rfl
[GOAL]
case neg
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q r p : R[X]
n : ℕ
I : Decidable (n < 1 + natDegree p)
h : ¬n < 1 + natDegree p
⊢ 0 = coeff p n
[PROOFSTEP]
exact (coeff_eq_zero_of_natDegree_lt (not_le.1 fun w => h (Nat.lt_one_add_iff.2 w))).symm
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q r p : R[X]
⊢ ∑ i in support p, ↑(monomial i) (coeff p i) = ∑ i in support p, ↑C (coeff p i) * X ^ i
[PROOFSTEP]
simp only [C_mul_X_pow_eq_monomial]
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝¹ : Semiring R
p✝ q r : R[X]
inst✝ : AddCommMonoid S
p : R[X]
f : ℕ → R → S
h : ∀ (n : ℕ), f n 0 = 0
n : ℕ
w : natDegree p < n
⊢ sum p f = ∑ a in range n, f a (coeff p a)
[PROOFSTEP]
rcases p with ⟨⟩
[GOAL]
case ofFinsupp
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝¹ : Semiring R
p q r : R[X]
inst✝ : AddCommMonoid S
f : ℕ → R → S
h : ∀ (n : ℕ), f n 0 = 0
n : ℕ
toFinsupp✝ : AddMonoidAlgebra R ℕ
w : natDegree { toFinsupp := toFinsupp✝ } < n
⊢ sum { toFinsupp := toFinsupp✝ } f = ∑ a in range n, f a (coeff { toFinsupp := toFinsupp✝ } a)
[PROOFSTEP]
have := supp_subset_range w
[GOAL]
case ofFinsupp
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝¹ : Semiring R
p q r : R[X]
inst✝ : AddCommMonoid S
f : ℕ → R → S
h : ∀ (n : ℕ), f n 0 = 0
n : ℕ
toFinsupp✝ : AddMonoidAlgebra R ℕ
w : natDegree { toFinsupp := toFinsupp✝ } < n
this : support { toFinsupp := toFinsupp✝ } ⊆ range n
⊢ sum { toFinsupp := toFinsupp✝ } f = ∑ a in range n, f a (coeff { toFinsupp := toFinsupp✝ } a)
[PROOFSTEP]
simp only [Polynomial.sum, support, coeff, natDegree, degree] at this ⊢
[GOAL]
case ofFinsupp
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝¹ : Semiring R
p q r : R[X]
inst✝ : AddCommMonoid S
f : ℕ → R → S
h : ∀ (n : ℕ), f n 0 = 0
n : ℕ
toFinsupp✝ : AddMonoidAlgebra R ℕ
w : natDegree { toFinsupp := toFinsupp✝ } < n
this : toFinsupp✝.support ⊆ range n
⊢ ∑ x in toFinsupp✝.support, f x (↑toFinsupp✝ x) = ∑ x in range n, f x (↑toFinsupp✝ x)
[PROOFSTEP]
exact Finsupp.sum_of_support_subset _ this _ fun n _hn => h n
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝¹ : Semiring R
p✝ q r : R[X]
inst✝ : AddCommMonoid S
f : ℕ → R → S
hf : ∀ (i : ℕ), f i 0 = 0
n : ℕ
p : R[X]
hn : degree p < ↑n
⊢ ∑ i : Fin n, f (↑i) (coeff p ↑i) = sum p f
[PROOFSTEP]
by_cases hp : p = 0
[GOAL]
case pos
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝¹ : Semiring R
p✝ q r : R[X]
inst✝ : AddCommMonoid S
f : ℕ → R → S
hf : ∀ (i : ℕ), f i 0 = 0
n : ℕ
p : R[X]
hn : degree p < ↑n
hp : p = 0
⊢ ∑ i : Fin n, f (↑i) (coeff p ↑i) = sum p f
[PROOFSTEP]
rw [hp, sum_zero_index, Finset.sum_eq_zero]
[GOAL]
case pos
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝¹ : Semiring R
p✝ q r : R[X]
inst✝ : AddCommMonoid S
f : ℕ → R → S
hf : ∀ (i : ℕ), f i 0 = 0
n : ℕ
p : R[X]
hn : degree p < ↑n
hp : p = 0
⊢ ∀ (x : Fin n), x ∈ univ → f (↑x) (coeff 0 ↑x) = 0
[PROOFSTEP]
intro i _
[GOAL]
case pos
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝¹ : Semiring R
p✝ q r : R[X]
inst✝ : AddCommMonoid S
f : ℕ → R → S
hf : ∀ (i : ℕ), f i 0 = 0
n : ℕ
p : R[X]
hn : degree p < ↑n
hp : p = 0
i : Fin n
a✝ : i ∈ univ
⊢ f (↑i) (coeff 0 ↑i) = 0
[PROOFSTEP]
exact hf i
[GOAL]
case neg
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝¹ : Semiring R
p✝ q r : R[X]
inst✝ : AddCommMonoid S
f : ℕ → R → S
hf : ∀ (i : ℕ), f i 0 = 0
n : ℕ
p : R[X]
hn : degree p < ↑n
hp : ¬p = 0
⊢ ∑ i : Fin n, f (↑i) (coeff p ↑i) = sum p f
[PROOFSTEP]
rw [sum_over_range' _ hf n ((natDegree_lt_iff_degree_lt hp).mpr hn), Fin.sum_univ_eq_sum_range fun i => f i (p.coeff i)]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q r p : R[X]
⊢ ∑ i in range (natDegree p + 1), ↑(monomial i) (coeff p i) = ∑ i in range (natDegree p + 1), ↑C (coeff p i) * X ^ i
[PROOFSTEP]
simp only [C_mul_X_pow_eq_monomial]
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q r : R[X]
h : degree p ≤ 1
n : ℕ
⊢ coeff p Nat.zero = coeff (↑C (coeff p 1) * X + ↑C (coeff p 0)) Nat.zero
[PROOFSTEP]
simp
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝¹ m : ℕ
inst✝ : Semiring R
p q r : R[X]
h : degree p ≤ 1
n✝ n : ℕ
⊢ coeff p (Nat.succ Nat.zero) = coeff (↑C (coeff p 1) * X + ↑C (coeff p 0)) (Nat.succ Nat.zero)
[PROOFSTEP]
simp [coeff_C]
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝¹ m✝ : ℕ
inst✝ : Semiring R
p q r : R[X]
h : degree p ≤ 1
n✝ n m : ℕ
⊢ coeff p (Nat.succ (Nat.succ m)) = coeff (↑C (coeff p 1) * X + ↑C (coeff p 0)) (Nat.succ (Nat.succ m))
[PROOFSTEP]
have : degree p < m.succ.succ := lt_of_le_of_lt h (Iff.mpr WithBot.coe_lt_coe <| Nat.succ_lt_succ <| Nat.zero_lt_succ m)
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝¹ m✝ : ℕ
inst✝ : Semiring R
p q r : R[X]
h : degree p ≤ 1
n✝ n m : ℕ
this : degree p < ↑(Nat.succ (Nat.succ m))
⊢ coeff p (Nat.succ (Nat.succ m)) = coeff (↑C (coeff p 1) * X + ↑C (coeff p 0)) (Nat.succ (Nat.succ m))
[PROOFSTEP]
simp [coeff_eq_zero_of_degree_lt this, coeff_C, Nat.succ_ne_zero, coeff_X, Nat.succ_inj', @eq_comm ℕ 0]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q r : R[X]
h : degree p = 1
⊢ ↑C (coeff p 1) * X + ↑C (coeff p 0) = ↑C (leadingCoeff p) * X + ↑C (coeff p 0)
[PROOFSTEP]
simp only [leadingCoeff, natDegree_eq_of_degree_eq_some h]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q r : R[X]
h : degree p = 1
⊢ ↑C (coeff p 1) * X + ↑C (coeff p 0) = ↑C (coeff p One.one) * X + ↑C (coeff p 0)
[PROOFSTEP]
rfl
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q r : R[X]
hm : Monic p
hnd : natDegree p = 1
⊢ p = X + ↑C (coeff p 0)
[PROOFSTEP]
rw [← one_mul X, ← C_1, ← hm.coeff_natDegree, hnd, ← eq_X_add_C_of_natDegree_le_one hnd.le]
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q r : R[X]
n : ℕ
⊢ degree (X ^ n) ≤ ↑n
[PROOFSTEP]
simpa only [C_1, one_mul] using degree_C_mul_X_pow_le n (1 : R)
[GOAL]
R : Type u
S : Type v
a b c✝ d : R
n✝ m : ℕ
inst✝ : Semiring R
p q r : R[X]
c : R
n : ℕ
⊢ card (support (↑C c * X ^ n)) ≤ 1
[PROOFSTEP]
rw [← card_singleton n]
[GOAL]
R : Type u
S : Type v
a b c✝ d : R
n✝ m : ℕ
inst✝ : Semiring R
p q r : R[X]
c : R
n : ℕ
⊢ card (support (↑C c * X ^ n)) ≤ card {n}
[PROOFSTEP]
apply card_le_of_subset (support_C_mul_X_pow' n c)
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q r p : R[X]
⊢ card (support p) ≤ natDegree p + 1
[PROOFSTEP]
rw [← Finset.card_range (p.natDegree + 1)]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q r p : R[X]
⊢ card (support p) ≤ card (range (natDegree p + 1))
[PROOFSTEP]
exact Finset.card_le_of_subset supp_subset_range_natDegree_succ
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q r : R[X]
⊢ Finset.Nonempty (support p) ↔ p ≠ 0
[PROOFSTEP]
rw [Ne.def, nonempty_iff_ne_empty, Ne.def, ← support_eq_empty]
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n m : ℕ
inst✝ : Ring R
p : R[X]
r : R
a : ℕ
⊢ coeff (p * (X - ↑C r)) (a + 1) = coeff p a - coeff p (a + 1) * r
[PROOFSTEP]
simp [mul_sub]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Ring R
p : R[X]
⊢ degree (-p) = degree p
[PROOFSTEP]
unfold degree
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Ring R
p : R[X]
⊢ Finset.max (support (-p)) = Finset.max (support p)
[PROOFSTEP]
rw [support_neg]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Ring R
p : R[X]
⊢ natDegree (-p) = natDegree p
[PROOFSTEP]
simp [natDegree]
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Ring R
n : ℤ
⊢ natDegree ↑n = 0
[PROOFSTEP]
rw [← C_eq_int_cast, natDegree_C]
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Ring R
n : ℤ
⊢ natDegree ↑n ≤ Zero.zero
[PROOFSTEP]
simp
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Ring R
p : R[X]
⊢ leadingCoeff (-p) = -leadingCoeff p
[PROOFSTEP]
rw [leadingCoeff, leadingCoeff, natDegree_neg, coeff_neg]
[GOAL]
R : Type u
S : Type v
a b c✝ d : R
n m : ℕ
inst✝ : Semiring R
c : R
⊢ nextCoeff (↑C c) = 0
[PROOFSTEP]
rw [nextCoeff]
[GOAL]
R : Type u
S : Type v
a b c✝ d : R
n m : ℕ
inst✝ : Semiring R
c : R
⊢ (if natDegree (↑C c) = 0 then 0 else coeff (↑C c) (natDegree (↑C c) - 1)) = 0
[PROOFSTEP]
simp
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p : R[X]
hp : 0 < natDegree p
⊢ nextCoeff p = coeff p (natDegree p - 1)
[PROOFSTEP]
rw [nextCoeff, if_neg]
[GOAL]
case hnc
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p : R[X]
hp : 0 < natDegree p
⊢ ¬natDegree p = 0
[PROOFSTEP]
contrapose! hp
[GOAL]
case hnc
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p : R[X]
hp : natDegree p = 0
⊢ natDegree p ≤ 0
[PROOFSTEP]
simpa
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
hpq : degree p ≤ degree q
hp : p ≠ 0
⊢ degree p ≠ ⊥
[PROOFSTEP]
rwa [Ne.def, Polynomial.degree_eq_bot]
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
n : ℕ
h : n < natDegree p
H : p = 0
⊢ False
[PROOFSTEP]
simp [H, Nat.not_lt_zero] at h
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : natDegree p < natDegree q
⊢ degree p < degree q
[PROOFSTEP]
by_cases hp : p = 0
[GOAL]
case pos
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : natDegree p < natDegree q
hp : p = 0
⊢ degree p < degree q
[PROOFSTEP]
simp [hp]
[GOAL]
case pos
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : natDegree p < natDegree q
hp : p = 0
⊢ ⊥ < degree q
[PROOFSTEP]
rw [bot_lt_iff_ne_bot]
[GOAL]
case pos
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : natDegree p < natDegree q
hp : p = 0
⊢ degree q ≠ ⊥
[PROOFSTEP]
intro hq
[GOAL]
case pos
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : natDegree p < natDegree q
hp : p = 0
hq : degree q = ⊥
⊢ False
[PROOFSTEP]
simp [hp, degree_eq_bot.mp hq, lt_irrefl] at h
[GOAL]
case neg
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : natDegree p < natDegree q
hp : ¬p = 0
⊢ degree p < degree q
[PROOFSTEP]
rwa [degree_eq_natDegree hp, degree_eq_natDegree <| ne_zero_of_natDegree_gt h, Nat.cast_lt]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
hp : p ≠ 0
h : degree p < degree q
⊢ natDegree p < natDegree q
[PROOFSTEP]
have hq : q ≠ 0 := ne_zero_of_degree_gt h
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
hp : p ≠ 0
h : degree p < degree q
hq : q ≠ 0
⊢ natDegree p < natDegree q
[PROOFSTEP]
rwa [degree_eq_natDegree hp, degree_eq_natDegree hq, Nat.cast_lt] at h
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : degree p ≤ 0
⊢ p = ↑C (coeff p 0)
[PROOFSTEP]
ext (_ | n)
[GOAL]
case a.zero
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : degree p ≤ 0
⊢ coeff p Nat.zero = coeff (↑C (coeff p 0)) Nat.zero
[PROOFSTEP]
simp
[GOAL]
case a.succ
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : degree p ≤ 0
n : ℕ
⊢ coeff p (Nat.succ n) = coeff (↑C (coeff p 0)) (Nat.succ n)
[PROOFSTEP]
rw [coeff_C, if_neg (Nat.succ_ne_zero _), coeff_eq_zero_of_degree_lt]
[GOAL]
case a.succ
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : degree p ≤ 0
n : ℕ
⊢ degree p < ↑(Nat.succ n)
[PROOFSTEP]
exact h.trans_lt (WithBot.some_lt_some.2 n.succ_pos)
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
⊢ degree (p + q) ≤ max (degree p) (degree q)
[PROOFSTEP]
simpa only [degree, ← support_toFinsupp, toFinsupp_add] using AddMonoidAlgebra.sup_support_add_le _ _ _
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
⊢ natDegree (p + q) ≤ max (natDegree p) (natDegree q)
[PROOFSTEP]
cases' le_max_iff.1 (degree_add_le p q) with h h
[GOAL]
case inl
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
h : degree (p + q) ≤ degree p
⊢ natDegree (p + q) ≤ max (natDegree p) (natDegree q)
[PROOFSTEP]
simp [natDegree_le_natDegree h]
[GOAL]
case inr
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
h : degree (p + q) ≤ degree q
⊢ natDegree (p + q) ≤ max (natDegree p) (natDegree q)
[PROOFSTEP]
simp [natDegree_le_natDegree h]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
⊢ leadingCoeff p ≠ 0 ↔ p ≠ 0
[PROOFSTEP]
rw [Ne.def, leadingCoeff_eq_zero]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
⊢ leadingCoeff p = 0 ↔ degree p = ⊥
[PROOFSTEP]
rw [leadingCoeff_eq_zero, degree_eq_bot]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
H : p ≠ 0
⊢ natDegree p ∈ support p
[PROOFSTEP]
rw [mem_support_iff]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
H : p ≠ 0
⊢ coeff p (natDegree p) ≠ 0
[PROOFSTEP]
exact (not_congr leadingCoeff_eq_zero).mpr H
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : degree q < degree p
⊢ coeff (p + q) (natDegree p) ≠ 0
[PROOFSTEP]
rw [coeff_add, coeff_natDegree_eq_zero_of_degree_lt h, add_zero]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : degree q < degree p
⊢ coeff p (natDegree p) ≠ 0
[PROOFSTEP]
exact mt leadingCoeff_eq_zero.1 (ne_zero_of_degree_gt h)
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : degree p < degree q
⊢ degree (p + q) = degree q
[PROOFSTEP]
rw [add_comm, degree_add_eq_left_of_degree_lt h]
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
a : R
⊢ natDegree (p + ↑C a) = natDegree p
[PROOFSTEP]
rcases eq_or_ne p 0 with rfl | hp
[GOAL]
case inl
R : Type u
S : Type v
a✝ b c d : R
n m : ℕ
inst✝ : Semiring R
q : R[X]
ι : Type u_1
a : R
⊢ natDegree (0 + ↑C a) = natDegree 0
[PROOFSTEP]
simp
[GOAL]
case inr
R : Type u
S : Type v
a✝ b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
a : R
hp : p ≠ 0
⊢ natDegree (p + ↑C a) = natDegree p
[PROOFSTEP]
by_cases hpd : p.degree ≤ 0
[GOAL]
case pos
R : Type u
S : Type v
a✝ b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
a : R
hp : p ≠ 0
hpd : degree p ≤ 0
⊢ natDegree (p + ↑C a) = natDegree p
[PROOFSTEP]
rw [eq_C_of_degree_le_zero hpd, ← C_add, natDegree_C, natDegree_C]
[GOAL]
case neg
R : Type u
S : Type v
a✝ b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
a : R
hp : p ≠ 0
hpd : ¬degree p ≤ 0
⊢ natDegree (p + ↑C a) = natDegree p
[PROOFSTEP]
rw [not_le, degree_eq_natDegree hp, Nat.cast_pos, ← natDegree_C a] at hpd
[GOAL]
case neg
R : Type u
S : Type v
a✝ b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
a : R
hp : p ≠ 0
hpd : natDegree (↑C a) < natDegree p
⊢ natDegree (p + ↑C a) = natDegree p
[PROOFSTEP]
exact natDegree_add_eq_left_of_natDegree_lt hpd
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
a : R
⊢ natDegree (↑C a + p) = natDegree p
[PROOFSTEP]
simp [add_comm _ p]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : leadingCoeff p + leadingCoeff q ≠ 0
hlt : degree p < degree q
⊢ max (degree p) (degree q) ≤ degree (p + q)
[PROOFSTEP]
rw [degree_add_eq_right_of_degree_lt hlt, max_eq_right_of_lt hlt]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : leadingCoeff p + leadingCoeff q ≠ 0
HEq : degree p = degree q
hlt : max (degree p) (degree q) > degree (p + q)
⊢ leadingCoeff p + leadingCoeff q = 0
[PROOFSTEP]
rw [HEq, max_self] at hlt
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : leadingCoeff p + leadingCoeff q ≠ 0
HEq : degree p = degree q
hlt : degree q > degree (p + q)
⊢ leadingCoeff p + leadingCoeff q = 0
[PROOFSTEP]
rw [leadingCoeff, leadingCoeff, natDegree_eq_of_degree_eq HEq, ← coeff_add]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : leadingCoeff p + leadingCoeff q ≠ 0
HEq : degree p = degree q
hlt : degree q > degree (p + q)
⊢ coeff (p + q) (natDegree q) = 0
[PROOFSTEP]
exact coeff_natDegree_eq_zero_of_degree_lt hlt
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : leadingCoeff p + leadingCoeff q ≠ 0
hlt : degree q < degree p
⊢ max (degree p) (degree q) ≤ degree (p + q)
[PROOFSTEP]
rw [degree_add_eq_left_of_degree_lt hlt, max_eq_left_of_lt hlt]
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
p : R[X]
n : ℕ
⊢ degree (erase n p) ≤ degree p
[PROOFSTEP]
rcases p with ⟨p⟩
[GOAL]
case ofFinsupp
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
n : ℕ
p : AddMonoidAlgebra R ℕ
⊢ degree (erase n { toFinsupp := p }) ≤ degree { toFinsupp := p }
[PROOFSTEP]
simp only [erase_def, degree, coeff, support]
-- Porting note: simpler convert-free proof to be explicit about definition unfolding
[GOAL]
case ofFinsupp
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
n : ℕ
p : AddMonoidAlgebra R ℕ
⊢ Finset.max (Finsupp.erase n p).support ≤ Finset.max p.support
[PROOFSTEP]
apply sup_mono
[GOAL]
case ofFinsupp.h
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
n : ℕ
p : AddMonoidAlgebra R ℕ
⊢ (Finsupp.erase n p).support ⊆ p.support
[PROOFSTEP]
rw [Finsupp.support_erase]
[GOAL]
case ofFinsupp.h
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
n : ℕ
p : AddMonoidAlgebra R ℕ
⊢ Finset.erase p.support n ⊆ p.support
[PROOFSTEP]
apply Finset.erase_subset
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
hp : p ≠ 0
⊢ degree (erase (natDegree p) p) < degree p
[PROOFSTEP]
apply lt_of_le_of_ne (degree_erase_le _ _)
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
hp : p ≠ 0
⊢ degree (erase (natDegree p) p) ≠ degree p
[PROOFSTEP]
rw [degree_eq_natDegree hp, degree, support_erase]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
hp : p ≠ 0
⊢ Finset.max (Finset.erase (support p) (natDegree p)) ≠ ↑(natDegree p)
[PROOFSTEP]
exact fun h => not_mem_erase _ _ (mem_of_max h)
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
p : R[X]
n : ℕ
a : R
⊢ degree (update p n a) ≤ max (degree p) ↑n
[PROOFSTEP]
rw [degree, support_update]
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
p : R[X]
n : ℕ
a : R
⊢ Finset.max (if a = 0 then Finset.erase (support p) n else insert n (support p)) ≤ max (degree p) ↑n
[PROOFSTEP]
split_ifs
[GOAL]
case pos
R : Type u
S : Type v
a✝ b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
p : R[X]
n : ℕ
a : R
h✝ : a = 0
⊢ Finset.max (Finset.erase (support p) n) ≤ max (degree p) ↑n
[PROOFSTEP]
exact (Finset.max_mono (erase_subset _ _)).trans (le_max_left _ _)
[GOAL]
case neg
R : Type u
S : Type v
a✝ b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
p : R[X]
n : ℕ
a : R
h✝ : ¬a = 0
⊢ Finset.max (insert n (support p)) ≤ max (degree p) ↑n
[PROOFSTEP]
rw [max_insert, max_comm]
[GOAL]
case neg
R : Type u
S : Type v
a✝ b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
p : R[X]
n : ℕ
a : R
h✝ : ¬a = 0
⊢ max (Finset.max (support p)) ↑n ≤ max (degree p) ↑n
[PROOFSTEP]
exact le_rfl
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
s : Finset ι
f : ι → R[X]
⊢ degree (∑ i in ∅, f i) ≤ sup ∅ fun b => degree (f b)
[PROOFSTEP]
simp only [sum_empty, sup_empty, degree_zero, le_refl]
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
s✝ : Finset ι
f : ι → R[X]
a : ι
s : Finset ι
has : ¬a ∈ s
ih : degree (∑ i in s, f i) ≤ sup s fun b => degree (f b)
⊢ degree (∑ i in insert a s, f i) ≤ max (degree (f a)) (degree (∑ i in s, f i))
[PROOFSTEP]
rw [sum_insert has]
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
s✝ : Finset ι
f : ι → R[X]
a : ι
s : Finset ι
has : ¬a ∈ s
ih : degree (∑ i in s, f i) ≤ sup s fun b => degree (f b)
⊢ degree (f a + ∑ x in s, f x) ≤ max (degree (f a)) (degree (∑ i in s, f i))
[PROOFSTEP]
exact degree_add_le _ _
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
s✝ : Finset ι
f : ι → R[X]
a : ι
s : Finset ι
has : ¬a ∈ s
ih : degree (∑ i in s, f i) ≤ sup s fun b => degree (f b)
⊢ max (degree (f a)) (degree (∑ i in s, f i)) ≤ sup (insert a s) fun b => degree (f b)
[PROOFSTEP]
rw [sup_insert, sup_eq_max]
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
s✝ : Finset ι
f : ι → R[X]
a : ι
s : Finset ι
has : ¬a ∈ s
ih : degree (∑ i in s, f i) ≤ sup s fun b => degree (f b)
⊢ max (degree (f a)) (degree (∑ i in s, f i)) ≤ max (degree (f a)) (sup s fun b => degree (f b))
[PROOFSTEP]
exact max_le_max le_rfl ih
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
⊢ degree (p * q) ≤ degree p + degree q
[PROOFSTEP]
simpa only [degree, ← support_toFinsupp, toFinsupp_mul] using
AddMonoidAlgebra.sup_support_mul_le (WithBot.coe_add _ _).le _ _
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
p : R[X]
⊢ degree (p ^ 0) ≤ 0 • degree p
[PROOFSTEP]
rw [pow_zero, zero_nsmul]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
p : R[X]
⊢ degree 1 ≤ 0
[PROOFSTEP]
exact degree_one_le
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
p : R[X]
n : ℕ
⊢ degree (p ^ (n + 1)) ≤ degree p + degree (p ^ n)
[PROOFSTEP]
rw [pow_succ]
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
p : R[X]
n : ℕ
⊢ degree (p * p ^ n) ≤ degree p + degree (p ^ n)
[PROOFSTEP]
exact degree_mul_le _ _
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
p : R[X]
n : ℕ
⊢ degree p + degree (p ^ n) ≤ (n + 1) • degree p
[PROOFSTEP]
rw [succ_nsmul]
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
p : R[X]
n : ℕ
⊢ degree p + degree (p ^ n) ≤ degree p + n • degree p
[PROOFSTEP]
exact add_le_add le_rfl (degree_pow_le _ _)
[GOAL]
R : Type u
S : Type v
a✝ b✝ c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
a : WithBot ℕ
b : ℕ
hp : degree p ≤ a
⊢ degree (p ^ b) ≤ ↑b * a
[PROOFSTEP]
induction b with
| zero => simp [degree_one_le]
| succ n hn =>
rw [Nat.cast_succ, add_mul, one_mul, pow_succ']
exact degree_mul_le_of_le hn hp
[GOAL]
R : Type u
S : Type v
a✝ b✝ c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
a : WithBot ℕ
b : ℕ
hp : degree p ≤ a
⊢ degree (p ^ b) ≤ ↑b * a
[PROOFSTEP]
induction b with
| zero => simp [degree_one_le]
| succ n hn =>
rw [Nat.cast_succ, add_mul, one_mul, pow_succ']
exact degree_mul_le_of_le hn hp
[GOAL]
case zero
R : Type u
S : Type v
a✝ b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
a : WithBot ℕ
hp : degree p ≤ a
⊢ degree (p ^ Nat.zero) ≤ ↑Nat.zero * a
[PROOFSTEP]
| zero => simp [degree_one_le]
[GOAL]
case zero
R : Type u
S : Type v
a✝ b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
a : WithBot ℕ
hp : degree p ≤ a
⊢ degree (p ^ Nat.zero) ≤ ↑Nat.zero * a
[PROOFSTEP]
simp [degree_one_le]
[GOAL]
case succ
R : Type u
S : Type v
a✝ b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
a : WithBot ℕ
hp : degree p ≤ a
n : ℕ
hn : degree (p ^ n) ≤ ↑n * a
⊢ degree (p ^ Nat.succ n) ≤ ↑(Nat.succ n) * a
[PROOFSTEP]
| succ n hn =>
rw [Nat.cast_succ, add_mul, one_mul, pow_succ']
exact degree_mul_le_of_le hn hp
[GOAL]
case succ
R : Type u
S : Type v
a✝ b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
a : WithBot ℕ
hp : degree p ≤ a
n : ℕ
hn : degree (p ^ n) ≤ ↑n * a
⊢ degree (p ^ Nat.succ n) ≤ ↑(Nat.succ n) * a
[PROOFSTEP]
rw [Nat.cast_succ, add_mul, one_mul, pow_succ']
[GOAL]
case succ
R : Type u
S : Type v
a✝ b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
a : WithBot ℕ
hp : degree p ≤ a
n : ℕ
hn : degree (p ^ n) ≤ ↑n * a
⊢ degree (p ^ n * p) ≤ ↑n * a + a
[PROOFSTEP]
exact degree_mul_le_of_le hn hp
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
a : R
n : ℕ
⊢ leadingCoeff (↑(monomial n) a) = a
[PROOFSTEP]
by_cases ha : a = 0
[GOAL]
case pos
R : Type u
S : Type v
a✝ b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
a : R
n : ℕ
ha : a = 0
⊢ leadingCoeff (↑(monomial n) a) = a
[PROOFSTEP]
simp only [ha, (monomial n).map_zero, leadingCoeff_zero]
[GOAL]
case neg
R : Type u
S : Type v
a✝ b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
a : R
n : ℕ
ha : ¬a = 0
⊢ leadingCoeff (↑(monomial n) a) = a
[PROOFSTEP]
rw [leadingCoeff, natDegree_monomial, if_neg ha, coeff_monomial]
[GOAL]
case neg
R : Type u
S : Type v
a✝ b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
a : R
n : ℕ
ha : ¬a = 0
⊢ (if n = n then a else 0) = a
[PROOFSTEP]
simp
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
a : R
n : ℕ
⊢ leadingCoeff (↑C a * X ^ n) = a
[PROOFSTEP]
rw [C_mul_X_pow_eq_monomial, leadingCoeff_monomial]
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
a : R
⊢ leadingCoeff (↑C a * X) = a
[PROOFSTEP]
simpa only [pow_one] using leadingCoeff_C_mul_X_pow a 1
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
n : ℕ
⊢ leadingCoeff (X ^ n) = 1
[PROOFSTEP]
simpa only [C_1, one_mul] using leadingCoeff_C_mul_X_pow (1 : R) n
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
⊢ leadingCoeff X = 1
[PROOFSTEP]
simpa only [pow_one] using @leadingCoeff_X_pow R _ 1
[GOAL]
R✝ : Type u
S : Type v
a b c d : R✝
n m : ℕ
inst✝² : Semiring R✝
p✝ q : R✝[X]
ι : Type u_1
R : Type u_2
inst✝¹ : Semiring R
inst✝ : Nontrivial R
p : R[X]
hp : Monic p
⊢ p ≠ 0
[PROOFSTEP]
rintro rfl
[GOAL]
R✝ : Type u
S : Type v
a b c d : R✝
n m : ℕ
inst✝² : Semiring R✝
p q : R✝[X]
ι : Type u_1
R : Type u_2
inst✝¹ : Semiring R
inst✝ : Nontrivial R
hp : Monic 0
⊢ False
[PROOFSTEP]
simp [Monic] at hp
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
h : 0 ≠ 1
p : R[X]
hp : Monic p
⊢ p ≠ 0
[PROOFSTEP]
nontriviality R
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝¹ : Semiring R
p✝ q : R[X]
ι : Type u_1
h : 0 ≠ 1
p : R[X]
hp : Monic p
inst✝ : Nontrivial R
⊢ p ≠ 0
[PROOFSTEP]
exact hp.ne_zero
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
n : ℕ
pn : natDegree p ≤ n
p1 : coeff p n = 1
⊢ Monic p
[PROOFSTEP]
unfold Monic
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
n : ℕ
pn : natDegree p ≤ n
p1 : coeff p n = 1
⊢ leadingCoeff p = 1
[PROOFSTEP]
nontriviality
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
n : ℕ
pn : natDegree p ≤ n
p1 : coeff p n = 1
✝ : Nontrivial R
⊢ leadingCoeff p = 1
[PROOFSTEP]
refine' (congr_arg _ <| natDegree_eq_of_le_of_coeff_ne_zero pn _).trans p1
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
n : ℕ
pn : natDegree p ≤ n
p1 : coeff p n = 1
✝ : Nontrivial R
⊢ coeff p n ≠ 0
[PROOFSTEP]
exact ne_of_eq_of_ne p1 one_ne_zero
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : degree p < degree q
⊢ leadingCoeff (p + q) = leadingCoeff q
[PROOFSTEP]
have : coeff p (natDegree q) = 0 := coeff_natDegree_eq_zero_of_degree_lt h
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : degree p < degree q
this : coeff p (natDegree q) = 0
⊢ leadingCoeff (p + q) = leadingCoeff q
[PROOFSTEP]
simp only [leadingCoeff, natDegree_eq_of_degree_eq (degree_add_eq_right_of_degree_lt h), this, coeff_add, zero_add]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : degree q < degree p
⊢ leadingCoeff (p + q) = leadingCoeff p
[PROOFSTEP]
rw [add_comm]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : degree q < degree p
⊢ leadingCoeff (q + p) = leadingCoeff p
[PROOFSTEP]
exact leadingCoeff_add_of_degree_lt h
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : degree p = degree q
hlc : leadingCoeff p + leadingCoeff q ≠ 0
⊢ leadingCoeff (p + q) = leadingCoeff p + leadingCoeff q
[PROOFSTEP]
have : natDegree (p + q) = natDegree p := by
apply natDegree_eq_of_degree_eq
rw [degree_add_eq_of_leadingCoeff_add_ne_zero hlc, h, max_self]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : degree p = degree q
hlc : leadingCoeff p + leadingCoeff q ≠ 0
⊢ natDegree (p + q) = natDegree p
[PROOFSTEP]
apply natDegree_eq_of_degree_eq
[GOAL]
case h
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : degree p = degree q
hlc : leadingCoeff p + leadingCoeff q ≠ 0
⊢ degree (p + q) = degree p
[PROOFSTEP]
rw [degree_add_eq_of_leadingCoeff_add_ne_zero hlc, h, max_self]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : degree p = degree q
hlc : leadingCoeff p + leadingCoeff q ≠ 0
this : natDegree (p + q) = natDegree p
⊢ leadingCoeff (p + q) = leadingCoeff p + leadingCoeff q
[PROOFSTEP]
simp only [leadingCoeff, this, natDegree_eq_of_degree_eq h, coeff_add]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
⊢ ∑ x in Nat.antidiagonal (natDegree p + natDegree q), coeff p x.fst * coeff q x.snd =
coeff p (natDegree p) * coeff q (natDegree q)
[PROOFSTEP]
refine' Finset.sum_eq_single (natDegree p, natDegree q) _ _
[GOAL]
case refine'_1
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
⊢ ∀ (b : ℕ × ℕ),
b ∈ Nat.antidiagonal (natDegree p + natDegree q) →
b ≠ (natDegree p, natDegree q) → coeff p b.fst * coeff q b.snd = 0
[PROOFSTEP]
rintro ⟨i, j⟩ h₁ h₂
[GOAL]
case refine'_1.mk
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
i j : ℕ
h₁ : (i, j) ∈ Nat.antidiagonal (natDegree p + natDegree q)
h₂ : (i, j) ≠ (natDegree p, natDegree q)
⊢ coeff p (i, j).fst * coeff q (i, j).snd = 0
[PROOFSTEP]
rw [Nat.mem_antidiagonal] at h₁
[GOAL]
case refine'_1.mk
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
i j : ℕ
h₁ : (i, j).fst + (i, j).snd = natDegree p + natDegree q
h₂ : (i, j) ≠ (natDegree p, natDegree q)
⊢ coeff p (i, j).fst * coeff q (i, j).snd = 0
[PROOFSTEP]
by_cases H : natDegree p < i
[GOAL]
case pos
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
i j : ℕ
h₁ : (i, j).fst + (i, j).snd = natDegree p + natDegree q
h₂ : (i, j) ≠ (natDegree p, natDegree q)
H : natDegree p < i
⊢ coeff p (i, j).fst * coeff q (i, j).snd = 0
[PROOFSTEP]
rw [coeff_eq_zero_of_degree_lt (lt_of_le_of_lt degree_le_natDegree (WithBot.coe_lt_coe.2 H)), zero_mul]
[GOAL]
case neg
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
i j : ℕ
h₁ : (i, j).fst + (i, j).snd = natDegree p + natDegree q
h₂ : (i, j) ≠ (natDegree p, natDegree q)
H : ¬natDegree p < i
⊢ coeff p (i, j).fst * coeff q (i, j).snd = 0
[PROOFSTEP]
rw [not_lt_iff_eq_or_lt] at H
[GOAL]
case neg
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
i j : ℕ
h₁ : (i, j).fst + (i, j).snd = natDegree p + natDegree q
h₂ : (i, j) ≠ (natDegree p, natDegree q)
H : natDegree p = i ∨ i < natDegree p
⊢ coeff p (i, j).fst * coeff q (i, j).snd = 0
[PROOFSTEP]
cases' H with H H
[GOAL]
case neg.inl
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
i j : ℕ
h₁ : (i, j).fst + (i, j).snd = natDegree p + natDegree q
h₂ : (i, j) ≠ (natDegree p, natDegree q)
H : natDegree p = i
⊢ coeff p (i, j).fst * coeff q (i, j).snd = 0
[PROOFSTEP]
subst H
[GOAL]
case neg.inl
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
j : ℕ
h₁ : (natDegree p, j).fst + (natDegree p, j).snd = natDegree p + natDegree q
h₂ : (natDegree p, j) ≠ (natDegree p, natDegree q)
⊢ coeff p (natDegree p, j).fst * coeff q (natDegree p, j).snd = 0
[PROOFSTEP]
rw [add_left_cancel_iff] at h₁
[GOAL]
case neg.inl
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
j : ℕ
h₁ : (natDegree p, j).snd = natDegree q
h₂ : (natDegree p, j) ≠ (natDegree p, natDegree q)
⊢ coeff p (natDegree p, j).fst * coeff q (natDegree p, j).snd = 0
[PROOFSTEP]
dsimp at h₁
[GOAL]
case neg.inl
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
j : ℕ
h₁ : j = natDegree q
h₂ : (natDegree p, j) ≠ (natDegree p, natDegree q)
⊢ coeff p (natDegree p, j).fst * coeff q (natDegree p, j).snd = 0
[PROOFSTEP]
subst h₁
[GOAL]
case neg.inl
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
h₂ : (natDegree p, natDegree q) ≠ (natDegree p, natDegree q)
⊢ coeff p (natDegree p, natDegree q).fst * coeff q (natDegree p, natDegree q).snd = 0
[PROOFSTEP]
exact (h₂ rfl).elim
[GOAL]
case neg.inr
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
i j : ℕ
h₁ : (i, j).fst + (i, j).snd = natDegree p + natDegree q
h₂ : (i, j) ≠ (natDegree p, natDegree q)
H : i < natDegree p
⊢ coeff p (i, j).fst * coeff q (i, j).snd = 0
[PROOFSTEP]
suffices natDegree q < j by
rw [coeff_eq_zero_of_degree_lt (lt_of_le_of_lt degree_le_natDegree (WithBot.coe_lt_coe.2 this)), mul_zero]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
i j : ℕ
h₁ : (i, j).fst + (i, j).snd = natDegree p + natDegree q
h₂ : (i, j) ≠ (natDegree p, natDegree q)
H : i < natDegree p
this : natDegree q < j
⊢ coeff p (i, j).fst * coeff q (i, j).snd = 0
[PROOFSTEP]
rw [coeff_eq_zero_of_degree_lt (lt_of_le_of_lt degree_le_natDegree (WithBot.coe_lt_coe.2 this)), mul_zero]
[GOAL]
case neg.inr
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
i j : ℕ
h₁ : (i, j).fst + (i, j).snd = natDegree p + natDegree q
h₂ : (i, j) ≠ (natDegree p, natDegree q)
H : i < natDegree p
⊢ natDegree q < j
[PROOFSTEP]
by_contra' H'
[GOAL]
case neg.inr
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
i j : ℕ
h₁ : (i, j).fst + (i, j).snd = natDegree p + natDegree q
h₂ : (i, j) ≠ (natDegree p, natDegree q)
H : i < natDegree p
H' : j ≤ natDegree q
⊢ False
[PROOFSTEP]
exact ne_of_lt (Nat.lt_of_lt_of_le (Nat.add_lt_add_right H j) (Nat.add_le_add_left H' _)) h₁
[GOAL]
case refine'_2
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
⊢ ¬(natDegree p, natDegree q) ∈ Nat.antidiagonal (natDegree p + natDegree q) →
coeff p (natDegree p, natDegree q).fst * coeff q (natDegree p, natDegree q).snd = 0
[PROOFSTEP]
intro H
[GOAL]
case refine'_2
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
H : ¬(natDegree p, natDegree q) ∈ Nat.antidiagonal (natDegree p + natDegree q)
⊢ coeff p (natDegree p, natDegree q).fst * coeff q (natDegree p, natDegree q).snd = 0
[PROOFSTEP]
exfalso
[GOAL]
case refine'_2.h
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
H : ¬(natDegree p, natDegree q) ∈ Nat.antidiagonal (natDegree p + natDegree q)
⊢ False
[PROOFSTEP]
apply H
[GOAL]
case refine'_2.h
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
H : ¬(natDegree p, natDegree q) ∈ Nat.antidiagonal (natDegree p + natDegree q)
⊢ (natDegree p, natDegree q) ∈ Nat.antidiagonal (natDegree p + natDegree q)
[PROOFSTEP]
rw [Nat.mem_antidiagonal]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : leadingCoeff p * leadingCoeff q ≠ 0
⊢ p ≠ 0
[PROOFSTEP]
refine' mt _ h
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : leadingCoeff p * leadingCoeff q ≠ 0
⊢ p = 0 → leadingCoeff p * leadingCoeff q = 0
[PROOFSTEP]
exact fun hp => by rw [hp, leadingCoeff_zero, zero_mul]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : leadingCoeff p * leadingCoeff q ≠ 0
hp : p = 0
⊢ leadingCoeff p * leadingCoeff q = 0
[PROOFSTEP]
rw [hp, leadingCoeff_zero, zero_mul]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : leadingCoeff p * leadingCoeff q ≠ 0
hp : p ≠ 0
⊢ q ≠ 0
[PROOFSTEP]
refine' mt _ h
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : leadingCoeff p * leadingCoeff q ≠ 0
hp : p ≠ 0
⊢ q = 0 → leadingCoeff p * leadingCoeff q = 0
[PROOFSTEP]
exact fun hq => by rw [hq, leadingCoeff_zero, mul_zero]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : leadingCoeff p * leadingCoeff q ≠ 0
hp : p ≠ 0
hq : q = 0
⊢ leadingCoeff p * leadingCoeff q = 0
[PROOFSTEP]
rw [hq, leadingCoeff_zero, mul_zero]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : leadingCoeff p * leadingCoeff q ≠ 0
hp : p ≠ 0
hq : q ≠ 0
⊢ degree p + degree q ≤ degree (p * q)
[PROOFSTEP]
rw [degree_eq_natDegree hp, degree_eq_natDegree hq]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : leadingCoeff p * leadingCoeff q ≠ 0
hp : p ≠ 0
hq : q ≠ 0
⊢ ↑(natDegree p) + ↑(natDegree q) ≤ degree (p * q)
[PROOFSTEP]
refine le_degree_of_ne_zero (n := natDegree p + natDegree q) ?_
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : leadingCoeff p * leadingCoeff q ≠ 0
hp : p ≠ 0
hq : q ≠ 0
⊢ coeff (p * q) (natDegree p + natDegree q) ≠ 0
[PROOFSTEP]
rwa [coeff_mul_degree_add_degree]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
hq : Monic q
hp : p = 0
⊢ degree (p * q) = degree p + degree q
[PROOFSTEP]
simp [hp]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
hq : Monic q
hp : ¬p = 0
⊢ Polynomial.leadingCoeff p * Polynomial.leadingCoeff q ≠ 0
[PROOFSTEP]
rwa [hq.leadingCoeff, mul_one, Ne.def, leadingCoeff_eq_zero]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : leadingCoeff p * leadingCoeff q ≠ 0
h₁ : leadingCoeff p = 0
⊢ leadingCoeff p * leadingCoeff q = 0
[PROOFSTEP]
rw [h₁, zero_mul]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : leadingCoeff p * leadingCoeff q ≠ 0
hp : p ≠ 0
h₁ : leadingCoeff q = 0
⊢ leadingCoeff p * leadingCoeff q = 0
[PROOFSTEP]
rw [h₁, mul_zero]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : leadingCoeff p * leadingCoeff q ≠ 0
hp : p ≠ 0
hq : q ≠ 0
⊢ degree (p * q) = ↑(natDegree p + natDegree q)
[PROOFSTEP]
rw [degree_mul' h, Nat.cast_add, degree_eq_natDegree hp, degree_eq_natDegree hq]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : leadingCoeff p * leadingCoeff q ≠ 0
⊢ leadingCoeff (p * q) = leadingCoeff p * leadingCoeff q
[PROOFSTEP]
unfold leadingCoeff
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : leadingCoeff p * leadingCoeff q ≠ 0
⊢ coeff (p * q) (natDegree (p * q)) = coeff p (natDegree p) * coeff q (natDegree q)
[PROOFSTEP]
rw [natDegree_mul' h, coeff_mul_degree_add_degree]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : leadingCoeff p * leadingCoeff q ≠ 0
⊢ leadingCoeff p * leadingCoeff q = coeff p (natDegree p) * coeff q (natDegree q)
[PROOFSTEP]
rfl
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : card (support p) ≤ 1
⊢ ↑(monomial (natDegree p)) (leadingCoeff p) = p
[PROOFSTEP]
rcases card_support_le_one_iff_monomial.1 h with ⟨n, a, rfl⟩
[GOAL]
case intro.intro
R : Type u
S : Type v
a✝ b c d : R
n✝ m : ℕ
inst✝ : Semiring R
q : R[X]
ι : Type u_1
n : ℕ
a : R
h : card (support (↑(monomial n) a)) ≤ 1
⊢ ↑(monomial (natDegree (↑(monomial n) a))) (leadingCoeff (↑(monomial n) a)) = ↑(monomial n) a
[PROOFSTEP]
by_cases ha : a = 0
[GOAL]
case pos
R : Type u
S : Type v
a✝ b c d : R
n✝ m : ℕ
inst✝ : Semiring R
q : R[X]
ι : Type u_1
n : ℕ
a : R
h : card (support (↑(monomial n) a)) ≤ 1
ha : a = 0
⊢ ↑(monomial (natDegree (↑(monomial n) a))) (leadingCoeff (↑(monomial n) a)) = ↑(monomial n) a
[PROOFSTEP]
simp [ha]
[GOAL]
case neg
R : Type u
S : Type v
a✝ b c d : R
n✝ m : ℕ
inst✝ : Semiring R
q : R[X]
ι : Type u_1
n : ℕ
a : R
h : card (support (↑(monomial n) a)) ≤ 1
ha : ¬a = 0
⊢ ↑(monomial (natDegree (↑(monomial n) a))) (leadingCoeff (↑(monomial n) a)) = ↑(monomial n) a
[PROOFSTEP]
simp [ha]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : card (support p) ≤ 1
⊢ ↑C (leadingCoeff p) * X ^ natDegree p = p
[PROOFSTEP]
rw [C_mul_X_pow_eq_monomial, monomial_natDegree_leadingCoeff_eq_self h]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
⊢ leadingCoeff p ^ Nat.zero ≠ 0 → leadingCoeff (p ^ Nat.zero) = leadingCoeff p ^ Nat.zero
[PROOFSTEP]
simp
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
n : ℕ
ih : leadingCoeff p ^ n ≠ 0 → leadingCoeff (p ^ n) = leadingCoeff p ^ n
h : leadingCoeff p ^ Nat.succ n ≠ 0
⊢ leadingCoeff (p ^ Nat.succ n) = leadingCoeff p ^ Nat.succ n
[PROOFSTEP]
have h₁ : leadingCoeff p ^ n ≠ 0 := fun h₁ => h <| by rw [pow_succ, h₁, mul_zero]
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
n : ℕ
ih : leadingCoeff p ^ n ≠ 0 → leadingCoeff (p ^ n) = leadingCoeff p ^ n
h : leadingCoeff p ^ Nat.succ n ≠ 0
h₁ : leadingCoeff p ^ n = 0
⊢ leadingCoeff p ^ Nat.succ n = 0
[PROOFSTEP]
rw [pow_succ, h₁, mul_zero]
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
n : ℕ
ih : leadingCoeff p ^ n ≠ 0 → leadingCoeff (p ^ n) = leadingCoeff p ^ n
h : leadingCoeff p ^ Nat.succ n ≠ 0
h₁ : leadingCoeff p ^ n ≠ 0
⊢ leadingCoeff (p ^ Nat.succ n) = leadingCoeff p ^ Nat.succ n
[PROOFSTEP]
have h₂ : leadingCoeff p * leadingCoeff (p ^ n) ≠ 0 := by rwa [pow_succ, ← ih h₁] at h
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
n : ℕ
ih : leadingCoeff p ^ n ≠ 0 → leadingCoeff (p ^ n) = leadingCoeff p ^ n
h : leadingCoeff p ^ Nat.succ n ≠ 0
h₁ : leadingCoeff p ^ n ≠ 0
⊢ leadingCoeff p * leadingCoeff (p ^ n) ≠ 0
[PROOFSTEP]
rwa [pow_succ, ← ih h₁] at h
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
n : ℕ
ih : leadingCoeff p ^ n ≠ 0 → leadingCoeff (p ^ n) = leadingCoeff p ^ n
h : leadingCoeff p ^ Nat.succ n ≠ 0
h₁ : leadingCoeff p ^ n ≠ 0
h₂ : leadingCoeff p * leadingCoeff (p ^ n) ≠ 0
⊢ leadingCoeff (p ^ Nat.succ n) = leadingCoeff p ^ Nat.succ n
[PROOFSTEP]
rw [pow_succ, pow_succ, leadingCoeff_mul' h₂, ih h₁]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : leadingCoeff p ^ 0 ≠ 0
⊢ degree (p ^ 0) = 0 • degree p
[PROOFSTEP]
rw [pow_zero, ← C_1] at *
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : 1 ≠ 0
⊢ degree (↑C 1) = 0 • degree p
[PROOFSTEP]
rw [degree_C h, zero_nsmul]
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
n : ℕ
h : leadingCoeff p ^ (n + 1) ≠ 0
⊢ degree (p ^ (n + 1)) = (n + 1) • degree p
[PROOFSTEP]
have h₁ : leadingCoeff p ^ n ≠ 0 := fun h₁ => h <| by rw [pow_succ, h₁, mul_zero]
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
n : ℕ
h : leadingCoeff p ^ (n + 1) ≠ 0
h₁ : leadingCoeff p ^ n = 0
⊢ leadingCoeff p ^ (n + 1) = 0
[PROOFSTEP]
rw [pow_succ, h₁, mul_zero]
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
n : ℕ
h : leadingCoeff p ^ (n + 1) ≠ 0
h₁ : leadingCoeff p ^ n ≠ 0
⊢ degree (p ^ (n + 1)) = (n + 1) • degree p
[PROOFSTEP]
have h₂ : leadingCoeff p * leadingCoeff (p ^ n) ≠ 0 := by rwa [pow_succ, ← leadingCoeff_pow' h₁] at h
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
n : ℕ
h : leadingCoeff p ^ (n + 1) ≠ 0
h₁ : leadingCoeff p ^ n ≠ 0
⊢ leadingCoeff p * leadingCoeff (p ^ n) ≠ 0
[PROOFSTEP]
rwa [pow_succ, ← leadingCoeff_pow' h₁] at h
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
n : ℕ
h : leadingCoeff p ^ (n + 1) ≠ 0
h₁ : leadingCoeff p ^ n ≠ 0
h₂ : leadingCoeff p * leadingCoeff (p ^ n) ≠ 0
⊢ degree (p ^ (n + 1)) = (n + 1) • degree p
[PROOFSTEP]
rw [pow_succ, degree_mul' h₂, succ_nsmul, degree_pow' h₁]
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
n : ℕ
h : leadingCoeff p ^ n ≠ 0
hp0 : p = 0
hn0 : n = 0
⊢ natDegree (p ^ n) = n * natDegree p
[PROOFSTEP]
simp [*]
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
n : ℕ
h : leadingCoeff p ^ n ≠ 0
hp0 : p = 0
hn0 : ¬n = 0
⊢ natDegree (p ^ n) = n * natDegree p
[PROOFSTEP]
rw [hp0, zero_pow (Nat.pos_of_ne_zero hn0)]
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
n : ℕ
h : leadingCoeff p ^ n ≠ 0
hp0 : p = 0
hn0 : ¬n = 0
⊢ natDegree 0 = n * natDegree 0
[PROOFSTEP]
simp
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
n : ℕ
h : leadingCoeff p ^ n ≠ 0
hp0 : ¬p = 0
hpn0 : p ^ n = 0
⊢ False
[PROOFSTEP]
have h1 := h
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
n : ℕ
h : leadingCoeff p ^ n ≠ 0
hp0 : ¬p = 0
hpn0 : p ^ n = 0
h1 : leadingCoeff p ^ n ≠ 0
⊢ False
[PROOFSTEP]
rw [← leadingCoeff_pow' h1, hpn0, leadingCoeff_zero] at h
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
n : ℕ
h : 0 ≠ 0
hp0 : ¬p = 0
hpn0 : p ^ n = 0
h1 : leadingCoeff p ^ n ≠ 0
⊢ False
[PROOFSTEP]
exact h rfl
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
n : ℕ
h : leadingCoeff p ^ n ≠ 0
hp0 : ¬p = 0
hpn : p ^ n ≠ 0
⊢ ↑(natDegree (p ^ n)) = ↑(n * natDegree p)
[PROOFSTEP]
rw [← degree_eq_natDegree hpn, degree_pow' h, degree_eq_natDegree hp0]
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
n : ℕ
h : leadingCoeff p ^ n ≠ 0
hp0 : ¬p = 0
hpn : p ^ n ≠ 0
⊢ n • ↑(natDegree p) = ↑(n * natDegree p)
[PROOFSTEP]
simp
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
hp : Monic p
⊢ leadingCoeff (p * q) = leadingCoeff q
[PROOFSTEP]
rcases eq_or_ne q 0 with (rfl | H)
[GOAL]
case inl
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
p : R[X]
hp : Monic p
⊢ leadingCoeff (p * 0) = leadingCoeff 0
[PROOFSTEP]
simp
[GOAL]
case inr
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
hp : Monic p
H : q ≠ 0
⊢ leadingCoeff (p * q) = leadingCoeff q
[PROOFSTEP]
rw [leadingCoeff_mul', hp.leadingCoeff, one_mul]
[GOAL]
case inr
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
hp : Monic p
H : q ≠ 0
⊢ leadingCoeff p * leadingCoeff q ≠ 0
[PROOFSTEP]
rwa [hp.leadingCoeff, one_mul, Ne.def, leadingCoeff_eq_zero]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
hq : Monic q
H : leadingCoeff p = 0
⊢ leadingCoeff (p * q) = leadingCoeff p
[PROOFSTEP]
rw [H, leadingCoeff_eq_zero.1 H, zero_mul, leadingCoeff_zero]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
hq : Monic q
H : leadingCoeff p ≠ 0
⊢ leadingCoeff (p * q) = leadingCoeff p
[PROOFSTEP]
rw [leadingCoeff_mul', hq.leadingCoeff, mul_one]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
hq : Monic q
H : leadingCoeff p ≠ 0
⊢ leadingCoeff p * leadingCoeff q ≠ 0
[PROOFSTEP]
rwa [hq.leadingCoeff, mul_one]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
⊢ natDegree (p * q) ≤ natDegree p + natDegree q
[PROOFSTEP]
apply natDegree_le_of_degree_le
[GOAL]
case a
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
⊢ degree (p * q) ≤ ↑(natDegree p + natDegree q)
[PROOFSTEP]
apply le_trans (degree_mul_le p q)
[GOAL]
case a
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
⊢ degree p + degree q ≤ ↑(natDegree p + natDegree q)
[PROOFSTEP]
rw [Nat.cast_add]
[GOAL]
case a
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
⊢ degree p + degree q ≤ ↑(natDegree p) + ↑(natDegree q)
[PROOFSTEP]
apply add_le_add
[GOAL]
case a.h₁
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
⊢ degree p ≤ ↑(natDegree p)
[PROOFSTEP]
apply degree_le_natDegree
[GOAL]
case a.h₂
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q✝ : R[X]
ι : Type u_1
p q : R[X]
⊢ degree q ≤ ↑(natDegree q)
[PROOFSTEP]
apply degree_le_natDegree
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
p : R[X]
n : ℕ
⊢ natDegree (p ^ n) ≤ n * natDegree p
[PROOFSTEP]
induction' n with i hi
[GOAL]
case zero
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
p : R[X]
⊢ natDegree (p ^ Nat.zero) ≤ Nat.zero * natDegree p
[PROOFSTEP]
simp
[GOAL]
case succ
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
p : R[X]
i : ℕ
hi : natDegree (p ^ i) ≤ i * natDegree p
⊢ natDegree (p ^ Nat.succ i) ≤ Nat.succ i * natDegree p
[PROOFSTEP]
rw [pow_succ, Nat.succ_mul, add_comm]
[GOAL]
case succ
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
p : R[X]
i : ℕ
hi : natDegree (p ^ i) ≤ i * natDegree p
⊢ natDegree (p * p ^ i) ≤ natDegree p + i * natDegree p
[PROOFSTEP]
apply le_trans natDegree_mul_le
[GOAL]
case succ
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
p : R[X]
i : ℕ
hi : natDegree (p ^ i) ≤ i * natDegree p
⊢ natDegree p + natDegree (p ^ i) ≤ natDegree p + i * natDegree p
[PROOFSTEP]
exact add_le_add_left hi _
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
p : R[X]
n : ℕ
⊢ coeff (p ^ n) (n * natDegree p) = leadingCoeff p ^ n
[PROOFSTEP]
induction' n with i hi
[GOAL]
case zero
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
p : R[X]
⊢ coeff (p ^ Nat.zero) (Nat.zero * natDegree p) = leadingCoeff p ^ Nat.zero
[PROOFSTEP]
simp
[GOAL]
case succ
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
p : R[X]
i : ℕ
hi : coeff (p ^ i) (i * natDegree p) = leadingCoeff p ^ i
⊢ coeff (p ^ Nat.succ i) (Nat.succ i * natDegree p) = leadingCoeff p ^ Nat.succ i
[PROOFSTEP]
rw [pow_succ', pow_succ', Nat.succ_mul]
[GOAL]
case succ
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
p : R[X]
i : ℕ
hi : coeff (p ^ i) (i * natDegree p) = leadingCoeff p ^ i
⊢ coeff (p ^ i * p) (i * natDegree p + natDegree p) = leadingCoeff p ^ i * leadingCoeff p
[PROOFSTEP]
by_cases hp1 : p.leadingCoeff ^ i = 0
[GOAL]
case pos
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
p : R[X]
i : ℕ
hi : coeff (p ^ i) (i * natDegree p) = leadingCoeff p ^ i
hp1 : leadingCoeff p ^ i = 0
⊢ coeff (p ^ i * p) (i * natDegree p + natDegree p) = leadingCoeff p ^ i * leadingCoeff p
[PROOFSTEP]
rw [hp1, zero_mul]
[GOAL]
case pos
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
p : R[X]
i : ℕ
hi : coeff (p ^ i) (i * natDegree p) = leadingCoeff p ^ i
hp1 : leadingCoeff p ^ i = 0
⊢ coeff (p ^ i * p) (i * natDegree p + natDegree p) = 0
[PROOFSTEP]
by_cases hp2 : p ^ i = 0
[GOAL]
case pos
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
p : R[X]
i : ℕ
hi : coeff (p ^ i) (i * natDegree p) = leadingCoeff p ^ i
hp1 : leadingCoeff p ^ i = 0
hp2 : p ^ i = 0
⊢ coeff (p ^ i * p) (i * natDegree p + natDegree p) = 0
[PROOFSTEP]
rw [hp2, zero_mul, coeff_zero]
[GOAL]
case neg
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
p : R[X]
i : ℕ
hi : coeff (p ^ i) (i * natDegree p) = leadingCoeff p ^ i
hp1 : leadingCoeff p ^ i = 0
hp2 : ¬p ^ i = 0
⊢ coeff (p ^ i * p) (i * natDegree p + natDegree p) = 0
[PROOFSTEP]
apply coeff_eq_zero_of_natDegree_lt
[GOAL]
case neg.h
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
p : R[X]
i : ℕ
hi : coeff (p ^ i) (i * natDegree p) = leadingCoeff p ^ i
hp1 : leadingCoeff p ^ i = 0
hp2 : ¬p ^ i = 0
⊢ natDegree (p ^ i * p) < i * natDegree p + natDegree p
[PROOFSTEP]
have h1 : (p ^ i).natDegree < i * p.natDegree :=
by
refine lt_of_le_of_ne natDegree_pow_le fun h => hp2 ?_
rw [← h, hp1] at hi
exact leadingCoeff_eq_zero.mp hi
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
p : R[X]
i : ℕ
hi : coeff (p ^ i) (i * natDegree p) = leadingCoeff p ^ i
hp1 : leadingCoeff p ^ i = 0
hp2 : ¬p ^ i = 0
⊢ natDegree (p ^ i) < i * natDegree p
[PROOFSTEP]
refine lt_of_le_of_ne natDegree_pow_le fun h => hp2 ?_
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
p : R[X]
i : ℕ
hi : coeff (p ^ i) (i * natDegree p) = leadingCoeff p ^ i
hp1 : leadingCoeff p ^ i = 0
hp2 : ¬p ^ i = 0
h : natDegree (p ^ i) = i * natDegree p
⊢ p ^ i = 0
[PROOFSTEP]
rw [← h, hp1] at hi
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
p : R[X]
i : ℕ
hi : coeff (p ^ i) (natDegree (p ^ i)) = 0
hp1 : leadingCoeff p ^ i = 0
hp2 : ¬p ^ i = 0
h : natDegree (p ^ i) = i * natDegree p
⊢ p ^ i = 0
[PROOFSTEP]
exact leadingCoeff_eq_zero.mp hi
[GOAL]
case neg.h
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
p : R[X]
i : ℕ
hi : coeff (p ^ i) (i * natDegree p) = leadingCoeff p ^ i
hp1 : leadingCoeff p ^ i = 0
hp2 : ¬p ^ i = 0
h1 : natDegree (p ^ i) < i * natDegree p
⊢ natDegree (p ^ i * p) < i * natDegree p + natDegree p
[PROOFSTEP]
calc
(p ^ i * p).natDegree ≤ (p ^ i).natDegree + p.natDegree := natDegree_mul_le
_ < i * p.natDegree + p.natDegree := add_lt_add_right h1 _
[GOAL]
case neg
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
p : R[X]
i : ℕ
hi : coeff (p ^ i) (i * natDegree p) = leadingCoeff p ^ i
hp1 : ¬leadingCoeff p ^ i = 0
⊢ coeff (p ^ i * p) (i * natDegree p + natDegree p) = leadingCoeff p ^ i * leadingCoeff p
[PROOFSTEP]
rw [← natDegree_pow' hp1, ← leadingCoeff_pow' hp1]
[GOAL]
case neg
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
p : R[X]
i : ℕ
hi : coeff (p ^ i) (i * natDegree p) = leadingCoeff p ^ i
hp1 : ¬leadingCoeff p ^ i = 0
⊢ coeff (p ^ i * p) (natDegree (p ^ i) + natDegree p) = leadingCoeff (p ^ i) * leadingCoeff p
[PROOFSTEP]
exact coeff_mul_degree_add_degree _ _
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
f : R[X]
df dg : ℕ
g : R[X]
hdf : natDegree f ≤ df
hdg : natDegree g ≤ dg
⊢ coeff (f * g) (df + dg) = coeff f df * coeff g dg
[PROOFSTEP]
rw [coeff_mul, Finset.sum_eq_single_of_mem (df, dg)]
[GOAL]
case h
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
f : R[X]
df dg : ℕ
g : R[X]
hdf : natDegree f ≤ df
hdg : natDegree g ≤ dg
⊢ (df, dg) ∈ Nat.antidiagonal (df + dg)
[PROOFSTEP]
rw [Finset.Nat.mem_antidiagonal]
[GOAL]
case h₀
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
f : R[X]
df dg : ℕ
g : R[X]
hdf : natDegree f ≤ df
hdg : natDegree g ≤ dg
⊢ ∀ (b : ℕ × ℕ), b ∈ Nat.antidiagonal (df + dg) → b ≠ (df, dg) → coeff f b.fst * coeff g b.snd = 0
[PROOFSTEP]
rintro ⟨df', dg'⟩ hmem hne
[GOAL]
case h₀.mk
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
f : R[X]
df dg : ℕ
g : R[X]
hdf : natDegree f ≤ df
hdg : natDegree g ≤ dg
df' dg' : ℕ
hmem : (df', dg') ∈ Nat.antidiagonal (df + dg)
hne : (df', dg') ≠ (df, dg)
⊢ coeff f (df', dg').fst * coeff g (df', dg').snd = 0
[PROOFSTEP]
obtain h | hdf' := lt_or_le df df'
[GOAL]
case h₀.mk.inl
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
f : R[X]
df dg : ℕ
g : R[X]
hdf : natDegree f ≤ df
hdg : natDegree g ≤ dg
df' dg' : ℕ
hmem : (df', dg') ∈ Nat.antidiagonal (df + dg)
hne : (df', dg') ≠ (df, dg)
h : df < df'
⊢ coeff f (df', dg').fst * coeff g (df', dg').snd = 0
[PROOFSTEP]
rw [coeff_eq_zero_of_natDegree_lt (hdf.trans_lt h), zero_mul]
[GOAL]
case h₀.mk.inr
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
f : R[X]
df dg : ℕ
g : R[X]
hdf : natDegree f ≤ df
hdg : natDegree g ≤ dg
df' dg' : ℕ
hmem : (df', dg') ∈ Nat.antidiagonal (df + dg)
hne : (df', dg') ≠ (df, dg)
hdf' : df' ≤ df
⊢ coeff f (df', dg').fst * coeff g (df', dg').snd = 0
[PROOFSTEP]
obtain h | hdg' := lt_or_le dg dg'
[GOAL]
case h₀.mk.inr.inl
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
f : R[X]
df dg : ℕ
g : R[X]
hdf : natDegree f ≤ df
hdg : natDegree g ≤ dg
df' dg' : ℕ
hmem : (df', dg') ∈ Nat.antidiagonal (df + dg)
hne : (df', dg') ≠ (df, dg)
hdf' : df' ≤ df
h : dg < dg'
⊢ coeff f (df', dg').fst * coeff g (df', dg').snd = 0
[PROOFSTEP]
rw [coeff_eq_zero_of_natDegree_lt (hdg.trans_lt h), mul_zero]
[GOAL]
case h₀.mk.inr.inr
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
f : R[X]
df dg : ℕ
g : R[X]
hdf : natDegree f ≤ df
hdg : natDegree g ≤ dg
df' dg' : ℕ
hmem : (df', dg') ∈ Nat.antidiagonal (df + dg)
hne : (df', dg') ≠ (df, dg)
hdf' : df' ≤ df
hdg' : dg' ≤ dg
⊢ coeff f (df', dg').fst * coeff g (df', dg').snd = 0
[PROOFSTEP]
obtain ⟨rfl, rfl⟩ := eq_and_eq_of_le_of_le_of_add_le hdf' hdg' (Finset.Nat.mem_antidiagonal.1 hmem).ge
[GOAL]
case h₀.mk.inr.inr.intro
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
f : R[X]
df dg : ℕ
g : R[X]
hdf : natDegree f ≤ df
hdg : natDegree g ≤ dg
hdf' : df ≤ df
hdg' : dg ≤ dg
hmem : (df, dg) ∈ Nat.antidiagonal (df + dg)
hne : (df, dg) ≠ (df, dg)
⊢ coeff f (df, dg).fst * coeff g (df, dg).snd = 0
[PROOFSTEP]
exact (hne rfl).elim
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
⊢ 0 ≤ degree p ↔ p ≠ 0
[PROOFSTEP]
rw [← not_lt, Nat.WithBot.lt_zero_iff, degree_eq_bot]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
⊢ natDegree p = 0 ↔ degree p ≤ 0
[PROOFSTEP]
rw [← nonpos_iff_eq_zero, natDegree_le_iff_degree_le, Nat.cast_zero]
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
f : R[X]
n : WithBot ℕ
⊢ degree f ≤ n ↔ ∀ (m : ℕ), n < ↑m → coeff f m = 0
[PROOFSTEP]
simp only [degree, Finset.max, Finset.sup_le_iff, mem_support_iff, Ne.def, ← not_le, not_imp_comm, Nat.cast_withBot]
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
f : R[X]
n : ℕ
⊢ degree f < ↑n ↔ ∀ (m : ℕ), n ≤ m → coeff f m = 0
[PROOFSTEP]
simp only [degree, Finset.sup_lt_iff (WithBot.bot_lt_coe n), mem_support_iff, WithBot.coe_lt_coe, ← @not_le ℕ,
max_eq_sup_coe, Nat.cast_withBot, Ne.def, not_imp_not]
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n m : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
a : R
p : R[X]
⊢ degree (a • p) ≤ degree p
[PROOFSTEP]
refine (degree_le_iff_coeff_zero _ _).2 fun m hm => ?_
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n m✝ : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
a : R
p : R[X]
m : ℕ
hm : degree p < ↑m
⊢ coeff (a • p) m = 0
[PROOFSTEP]
rw [degree_lt_iff_coeff_zero] at hm
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n m✝ : ℕ
inst✝ : Semiring R
p✝ q : R[X]
ι : Type u_1
a : R
p : R[X]
m : ℕ
hm : ∀ (m_1 : ℕ), m ≤ m_1 → coeff p m_1 = 0
⊢ coeff (a • p) m = 0
[PROOFSTEP]
simp [hm m le_rfl]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
hp : p ≠ 0
⊢ degree p < degree (p * X)
[PROOFSTEP]
haveI := Nontrivial.of_polynomial_ne hp
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
hp : p ≠ 0
this : Nontrivial R
⊢ degree p < degree (p * X)
[PROOFSTEP]
have : leadingCoeff p * leadingCoeff X ≠ 0 := by simpa
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
hp : p ≠ 0
this : Nontrivial R
⊢ leadingCoeff p * leadingCoeff X ≠ 0
[PROOFSTEP]
simpa
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
hp : p ≠ 0
this✝ : Nontrivial R
this : leadingCoeff p * leadingCoeff X ≠ 0
⊢ degree p < degree (p * X)
[PROOFSTEP]
erw [degree_mul' this, degree_eq_natDegree hp, degree_X, ← WithBot.coe_one, ← WithBot.coe_add, WithBot.coe_lt_coe]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
hp : p ≠ 0
this✝ : Nontrivial R
this : leadingCoeff p * leadingCoeff X ≠ 0
⊢ ↑(natDegree p) < ↑(natDegree p) + 1
[PROOFSTEP]
exact Nat.lt_succ_self _
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
h : p = ↑C (coeff p 0)
⊢ natDegree p = 0
[PROOFSTEP]
rw [h, natDegree_C]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
hdeg : ↑n ≤ degree p
⊢ ↑n ≤ ↑(natDegree p)
[PROOFSTEP]
rwa [degree_eq_natDegree <| ne_zero_of_coe_le_degree hdeg] at hdeg
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
ha : a ≠ 0
⊢ degree (↑C b) < degree (↑C a * X)
[PROOFSTEP]
simpa only [degree_C_mul_X ha] using degree_C_lt
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
ha : a ≠ 0
⊢ degree (↑C a * X + ↑C b) = 1
[PROOFSTEP]
rw [degree_add_eq_left_of_degree_lt <| degree_C_lt_degree_C_mul_X ha, degree_C_mul_X ha]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
ha : a ≠ 0
⊢ natDegree (↑C a * X + ↑C b) = 1
[PROOFSTEP]
rw [natDegree_add_C, natDegree_C_mul_X a ha]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
ha : a ≠ 0
⊢ leadingCoeff (↑C a * X + ↑C b) = a
[PROOFSTEP]
rw [add_comm, leadingCoeff_add_of_degree_lt (degree_C_lt_degree_C_mul_X ha), leadingCoeff_C_mul_X]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
⊢ degree (↑C a * X ^ 2 + ↑C b * X + ↑C c) ≤ 2
[PROOFSTEP]
simpa only [add_assoc] using
degree_add_le_of_degree_le (degree_C_mul_X_pow_le 2 a)
(le_trans degree_linear_le <| WithBot.coe_le_coe.mpr one_le_two)
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
ha : a ≠ 0
⊢ degree (↑C b * X + ↑C c) < degree (↑C a * X ^ 2)
[PROOFSTEP]
simpa only [degree_C_mul_X_pow 2 ha] using degree_linear_lt
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
ha : a ≠ 0
⊢ degree (↑C a * X ^ 2 + ↑C b * X + ↑C c) = 2
[PROOFSTEP]
rw [add_assoc, degree_add_eq_left_of_degree_lt <| degree_linear_lt_degree_C_mul_X_sq ha, degree_C_mul_X_pow 2 ha]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
ha : a ≠ 0
⊢ ↑2 = 2
[PROOFSTEP]
rfl
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
ha : a ≠ 0
⊢ leadingCoeff (↑C a * X ^ 2 + ↑C b * X + ↑C c) = a
[PROOFSTEP]
rw [add_assoc, add_comm, leadingCoeff_add_of_degree_lt <| degree_linear_lt_degree_C_mul_X_sq ha,
leadingCoeff_C_mul_X_pow]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
⊢ degree (↑C a * X ^ 3 + ↑C b * X ^ 2 + ↑C c * X + ↑C d) ≤ 3
[PROOFSTEP]
simpa only [add_assoc] using
degree_add_le_of_degree_le (degree_C_mul_X_pow_le 3 a)
(le_trans degree_quadratic_le <| WithBot.coe_le_coe.mpr <| Nat.le_succ 2)
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
ha : a ≠ 0
⊢ degree (↑C b * X ^ 2 + ↑C c * X + ↑C d) < degree (↑C a * X ^ 3)
[PROOFSTEP]
simpa only [degree_C_mul_X_pow 3 ha] using degree_quadratic_lt
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
ha : a ≠ 0
⊢ degree (↑C a * X ^ 3 + ↑C b * X ^ 2 + ↑C c * X + ↑C d) = 3
[PROOFSTEP]
rw [add_assoc, add_assoc, ← add_assoc (C b * X ^ 2),
degree_add_eq_left_of_degree_lt <| degree_quadratic_lt_degree_C_mul_X_cb ha, degree_C_mul_X_pow 3 ha]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
ha : a ≠ 0
⊢ ↑3 = 3
[PROOFSTEP]
rfl
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type u_1
ha : a ≠ 0
⊢ leadingCoeff (↑C a * X ^ 3 + ↑C b * X ^ 2 + ↑C c * X + ↑C d) = a
[PROOFSTEP]
rw [add_assoc, add_assoc, ← add_assoc (C b * X ^ 2), add_comm,
leadingCoeff_add_of_degree_lt <| degree_quadratic_lt_degree_C_mul_X_cb ha, leadingCoeff_C_mul_X_pow]
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝¹ : Semiring R
inst✝ : Nontrivial R
p q : R[X]
n : ℕ
⊢ degree (X ^ n) = ↑n
[PROOFSTEP]
rw [X_pow_eq_monomial, degree_monomial _ (one_ne_zero' R)]
[GOAL]
R✝ : Type u
S : Type v
a b c d : R✝
n✝ m : ℕ
inst✝² : Semiring R✝
inst✝¹ : Nontrivial R✝
p q : R✝[X]
R : Type u_1
inst✝ : Semiring R
n : ℕ
⊢ natDegree (X ^ n) ≤ n
[PROOFSTEP]
nontriviality R
[GOAL]
R✝ : Type u
S : Type v
a b c d : R✝
n✝ m : ℕ
inst✝² : Semiring R✝
inst✝¹ : Nontrivial R✝
p q : R✝[X]
R : Type u_1
inst✝ : Semiring R
n : ℕ
✝ : Nontrivial R
⊢ natDegree (X ^ n) ≤ n
[PROOFSTEP]
rw [Polynomial.natDegree_X_pow]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝¹ : Semiring R
inst✝ : Nontrivial R
p q : R[X]
x✝ : IsUnit X
g : R[X]
_hfg : ↑(monomial 1) 1 * g = 1
hgf : g * ↑(monomial 1) 1 = 1
⊢ 0 = 1
[PROOFSTEP]
rw [← coeff_one_zero, ← hgf]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝¹ : Semiring R
inst✝ : Nontrivial R
p q : R[X]
x✝ : IsUnit X
g : R[X]
_hfg : ↑(monomial 1) 1 * g = 1
hgf : g * ↑(monomial 1) 1 = 1
⊢ 0 = coeff (g * ↑(monomial 1) 1) 0
[PROOFSTEP]
simp
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝¹ : Semiring R
inst✝ : Nontrivial R
p q : R[X]
⊢ degree (p * X) = degree p + 1
[PROOFSTEP]
simp [monic_X.degree_mul]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝¹ : Semiring R
inst✝ : Nontrivial R
p q : R[X]
⊢ degree (p * X ^ n) = degree p + ↑n
[PROOFSTEP]
simp [(monic_X_pow n).degree_mul]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Ring R
p✝ q✝ p q : R[X]
⊢ degree (p - q) ≤ max (degree p) (degree q)
[PROOFSTEP]
simpa only [degree_neg q] using degree_add_le p (-q)
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Ring R
p q : R[X]
h : degree q < degree p
⊢ leadingCoeff (p - q) = leadingCoeff p
[PROOFSTEP]
rw [← q.degree_neg] at h
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Ring R
p q : R[X]
h : degree (-q) < degree p
⊢ leadingCoeff (p - q) = leadingCoeff p
[PROOFSTEP]
rw [sub_eq_add_neg, leadingCoeff_add_of_degree_lt' h]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Ring R
p q : R[X]
h : degree p < degree q
⊢ leadingCoeff (p - q) = -leadingCoeff q
[PROOFSTEP]
rw [← q.degree_neg] at h
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Ring R
p q : R[X]
h : degree p < degree (-q)
⊢ leadingCoeff (p - q) = -leadingCoeff q
[PROOFSTEP]
rw [sub_eq_add_neg, leadingCoeff_add_of_degree_lt h, leadingCoeff_neg]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Ring R
p q : R[X]
h : degree p = degree q
hlc : leadingCoeff p ≠ leadingCoeff q
⊢ leadingCoeff (p - q) = leadingCoeff p - leadingCoeff q
[PROOFSTEP]
replace h : degree p = degree (-q) := by rwa [q.degree_neg]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Ring R
p q : R[X]
h : degree p = degree q
hlc : leadingCoeff p ≠ leadingCoeff q
⊢ degree p = degree (-q)
[PROOFSTEP]
rwa [q.degree_neg]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Ring R
p q : R[X]
hlc : leadingCoeff p ≠ leadingCoeff q
h : degree p = degree (-q)
⊢ leadingCoeff (p - q) = leadingCoeff p - leadingCoeff q
[PROOFSTEP]
replace hlc : leadingCoeff p + leadingCoeff (-q) ≠ 0 := by
rwa [← sub_ne_zero, sub_eq_add_neg, ← q.leadingCoeff_neg] at hlc
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Ring R
p q : R[X]
hlc : leadingCoeff p ≠ leadingCoeff q
h : degree p = degree (-q)
⊢ leadingCoeff p + leadingCoeff (-q) ≠ 0
[PROOFSTEP]
rwa [← sub_ne_zero, sub_eq_add_neg, ← q.leadingCoeff_neg] at hlc
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Ring R
p q : R[X]
h : degree p = degree (-q)
hlc : leadingCoeff p + leadingCoeff (-q) ≠ 0
⊢ leadingCoeff (p - q) = leadingCoeff p - leadingCoeff q
[PROOFSTEP]
rw [sub_eq_add_neg, leadingCoeff_add_of_degree_eq h hlc, leadingCoeff_neg, sub_eq_add_neg]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Ring R
p✝ q✝ p q : R[X]
⊢ natDegree (p - q) ≤ max (natDegree p) (natDegree q)
[PROOFSTEP]
simpa only [← natDegree_neg q] using natDegree_add_le p (-q)
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Ring R
p q : R[X]
hd : degree p = degree q
hp0 : p ≠ 0
hlc : leadingCoeff p = leadingCoeff q
hp : ↑(monomial (natDegree p)) (leadingCoeff p) + erase (natDegree p) p = p
hq : ↑(monomial (natDegree q)) (leadingCoeff q) + erase (natDegree q) q = q
⊢ natDegree p = natDegree q
[PROOFSTEP]
unfold natDegree
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Ring R
p q : R[X]
hd : degree p = degree q
hp0 : p ≠ 0
hlc : leadingCoeff p = leadingCoeff q
hp : ↑(monomial (natDegree p)) (leadingCoeff p) + erase (natDegree p) p = p
hq : ↑(monomial (natDegree q)) (leadingCoeff q) + erase (natDegree q) q = q
⊢ WithBot.unbot' 0 (degree p) = WithBot.unbot' 0 (degree q)
[PROOFSTEP]
rw [hd]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Ring R
p q : R[X]
hd : degree p = degree q
hp0 : p ≠ 0
hlc : leadingCoeff p = leadingCoeff q
hp : ↑(monomial (natDegree p)) (leadingCoeff p) + erase (natDegree p) p = p
hq : ↑(monomial (natDegree q)) (leadingCoeff q) + erase (natDegree q) q = q
hd' : natDegree p = natDegree q
hq0 : q ≠ 0
⊢ degree (p - q) = degree (erase (natDegree q) p + -erase (natDegree q) q)
[PROOFSTEP]
conv =>
lhs
rw [← hp, ← hq, hlc, hd', add_sub_add_left_eq_sub, sub_eq_add_neg]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Ring R
p q : R[X]
hd : degree p = degree q
hp0 : p ≠ 0
hlc : leadingCoeff p = leadingCoeff q
hp : ↑(monomial (natDegree p)) (leadingCoeff p) + erase (natDegree p) p = p
hq : ↑(monomial (natDegree q)) (leadingCoeff q) + erase (natDegree q) q = q
hd' : natDegree p = natDegree q
hq0 : q ≠ 0
| degree (p - q) = degree (erase (natDegree q) p + -erase (natDegree q) q)
[PROOFSTEP]
lhs
rw [← hp, ← hq, hlc, hd', add_sub_add_left_eq_sub, sub_eq_add_neg]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Ring R
p q : R[X]
hd : degree p = degree q
hp0 : p ≠ 0
hlc : leadingCoeff p = leadingCoeff q
hp : ↑(monomial (natDegree p)) (leadingCoeff p) + erase (natDegree p) p = p
hq : ↑(monomial (natDegree q)) (leadingCoeff q) + erase (natDegree q) q = q
hd' : natDegree p = natDegree q
hq0 : q ≠ 0
| degree (p - q) = degree (erase (natDegree q) p + -erase (natDegree q) q)
[PROOFSTEP]
lhs
rw [← hp, ← hq, hlc, hd', add_sub_add_left_eq_sub, sub_eq_add_neg]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Ring R
p q : R[X]
hd : degree p = degree q
hp0 : p ≠ 0
hlc : leadingCoeff p = leadingCoeff q
hp : ↑(monomial (natDegree p)) (leadingCoeff p) + erase (natDegree p) p = p
hq : ↑(monomial (natDegree q)) (leadingCoeff q) + erase (natDegree q) q = q
hd' : natDegree p = natDegree q
hq0 : q ≠ 0
| degree (p - q) = degree (erase (natDegree q) p + -erase (natDegree q) q)
[PROOFSTEP]
lhs
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Ring R
p q : R[X]
hd : degree p = degree q
hp0 : p ≠ 0
hlc : leadingCoeff p = leadingCoeff q
hp : ↑(monomial (natDegree p)) (leadingCoeff p) + erase (natDegree p) p = p
hq : ↑(monomial (natDegree q)) (leadingCoeff q) + erase (natDegree q) q = q
hd' : natDegree p = natDegree q
hq0 : q ≠ 0
| degree (p - q)
[PROOFSTEP]
rw [← hp, ← hq, hlc, hd', add_sub_add_left_eq_sub, sub_eq_add_neg]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Ring R
p q : R[X]
h : degree q < degree p
⊢ degree (p - q) = degree p
[PROOFSTEP]
rw [← degree_neg q] at h
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Ring R
p q : R[X]
h : degree (-q) < degree p
⊢ degree (p - q) = degree p
[PROOFSTEP]
rw [sub_eq_add_neg, degree_add_eq_left_of_degree_lt h]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Ring R
p q : R[X]
h : degree p < degree q
⊢ degree (p - q) = degree q
[PROOFSTEP]
rw [← degree_neg q] at h
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Ring R
p q : R[X]
h : degree p < degree (-q)
⊢ degree (p - q) = degree q
[PROOFSTEP]
rw [sub_eq_add_neg, degree_add_eq_right_of_degree_lt h, degree_neg]
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n m : ℕ
inst✝¹ : Nontrivial R
inst✝ : Semiring R
a : R
⊢ degree (X + ↑C a) = 1
[PROOFSTEP]
have : degree (C a) < degree (X : R[X]) :=
calc
degree (C a) ≤ 0 := degree_C_le
_ < 1 := (WithBot.some_lt_some.mpr zero_lt_one)
_ = degree X := degree_X.symm
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n m : ℕ
inst✝¹ : Nontrivial R
inst✝ : Semiring R
a : R
this : degree (↑C a) < degree X
⊢ degree (X + ↑C a) = 1
[PROOFSTEP]
rw [degree_add_eq_left_of_degree_lt this, degree_X]
[GOAL]
R : Type u
S : Type v
a b c✝ d : R
n m : ℕ
inst✝² : Nontrivial R
inst✝¹ : Semiring R
inst✝ : Semiring S
c : S
⊢ nextCoeff (X + ↑C c) = c
[PROOFSTEP]
nontriviality S
[GOAL]
R : Type u
S : Type v
a b c✝ d : R
n m : ℕ
inst✝² : Nontrivial R
inst✝¹ : Semiring R
inst✝ : Semiring S
c : S
✝ : Nontrivial S
⊢ nextCoeff (X + ↑C c) = c
[PROOFSTEP]
simp [nextCoeff_of_pos_natDegree]
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n✝ m : ℕ
inst✝¹ : Nontrivial R
inst✝ : Semiring R
n : ℕ
hn : 0 < n
a : R
⊢ degree (X ^ n + ↑C a) = ↑n
[PROOFSTEP]
have : degree (C a) < degree ((X : R[X]) ^ n) := degree_C_le.trans_lt <| by rwa [degree_X_pow, Nat.cast_pos]
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n✝ m : ℕ
inst✝¹ : Nontrivial R
inst✝ : Semiring R
n : ℕ
hn : 0 < n
a : R
⊢ 0 < degree (X ^ n)
[PROOFSTEP]
rwa [degree_X_pow, Nat.cast_pos]
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n✝ m : ℕ
inst✝¹ : Nontrivial R
inst✝ : Semiring R
n : ℕ
hn : 0 < n
a : R
this : degree (↑C a) < degree (X ^ n)
⊢ degree (X ^ n + ↑C a) = ↑n
[PROOFSTEP]
rw [degree_add_eq_left_of_degree_lt this, degree_X_pow]
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n✝ m : ℕ
inst✝¹ : Nontrivial R
inst✝ : Semiring R
n : ℕ
hn : 0 < n
a : R
⊢ degree (X ^ n + ↑C a) ≠ ⊥
[PROOFSTEP]
rw [degree_X_pow_add_C hn a]
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n✝ m : ℕ
inst✝¹ : Nontrivial R
inst✝ : Semiring R
n : ℕ
hn : 0 < n
a : R
⊢ ↑n ≠ ⊥
[PROOFSTEP]
exact WithBot.coe_ne_bot
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝¹ : Nontrivial R
inst✝ : Semiring R
n : ℕ
r : R
⊢ natDegree (X ^ n + ↑C r) = n
[PROOFSTEP]
by_cases hn : n = 0
[GOAL]
case pos
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝¹ : Nontrivial R
inst✝ : Semiring R
n : ℕ
r : R
hn : n = 0
⊢ natDegree (X ^ n + ↑C r) = n
[PROOFSTEP]
rw [hn, pow_zero, ← C_1, ← RingHom.map_add, natDegree_C]
[GOAL]
case neg
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝¹ : Nontrivial R
inst✝ : Semiring R
n : ℕ
r : R
hn : ¬n = 0
⊢ natDegree (X ^ n + ↑C r) = n
[PROOFSTEP]
exact natDegree_eq_of_degree_eq_some (degree_X_pow_add_C (pos_iff_ne_zero.mpr hn) r)
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n✝ m : ℕ
inst✝¹ : Nontrivial R
inst✝ : Semiring R
n : ℕ
hn : 0 < n
a : R
h : X ^ n + ↑C a = 1
⊢ n = 0
[PROOFSTEP]
simpa only [natDegree_X_pow_add_C, natDegree_one] using congr_arg natDegree h
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
n : ℕ
hn : 0 < n
r : R
⊢ leadingCoeff (X ^ n + ↑C r) = 1
[PROOFSTEP]
nontriviality R
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Semiring R
n : ℕ
hn : 0 < n
r : R
✝ : Nontrivial R
⊢ leadingCoeff (X ^ n + ↑C r) = 1
[PROOFSTEP]
rw [leadingCoeff, natDegree_X_pow_add_C, coeff_add, coeff_X_pow_self, coeff_C, if_neg (pos_iff_ne_zero.mp hn), add_zero]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝¹ : Semiring R
inst✝ : Semiring S
r : S
⊢ leadingCoeff (X + ↑C r) = 1
[PROOFSTEP]
rw [← pow_one (X : S[X]), leadingCoeff_X_pow_add_C zero_lt_one]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
r : R
i : ℕ
⊢ leadingCoeff ((X + ↑C r) ^ i) = 1
[PROOFSTEP]
nontriviality
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
r : R
i : ℕ
✝ : Nontrivial R
⊢ leadingCoeff ((X + ↑C r) ^ i) = 1
[PROOFSTEP]
rw [leadingCoeff_pow']
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
r : R
i : ℕ
✝ : Nontrivial R
⊢ leadingCoeff (X + ↑C r) ^ i = 1
[PROOFSTEP]
simp
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
r : R
i : ℕ
✝ : Nontrivial R
⊢ leadingCoeff (X + ↑C r) ^ i ≠ 0
[PROOFSTEP]
simp
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝ : Ring R
n : ℕ
hn : 0 < n
r : R
⊢ leadingCoeff (X ^ n - ↑C r) = 1
[PROOFSTEP]
rw [sub_eq_add_neg, ← map_neg C r, leadingCoeff_X_pow_add_C hn]
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n m : ℕ
inst✝¹ : Ring R
inst✝ : Nontrivial R
a : R
⊢ degree (X - ↑C a) = 1
[PROOFSTEP]
rw [sub_eq_add_neg, ← map_neg C a, degree_X_add_C]
[GOAL]
R : Type u
S : Type v
a b c✝ d : R
n m : ℕ
inst✝² : Ring R
inst✝¹ : Nontrivial R
inst✝ : Ring S
c : S
⊢ nextCoeff (X - ↑C c) = -c
[PROOFSTEP]
rw [sub_eq_add_neg, ← map_neg C c, nextCoeff_X_add_C]
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n✝ m : ℕ
inst✝¹ : Ring R
inst✝ : Nontrivial R
n : ℕ
hn : 0 < n
a : R
⊢ degree (X ^ n - ↑C a) = ↑n
[PROOFSTEP]
rw [sub_eq_add_neg, ← map_neg C a, degree_X_pow_add_C hn]
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n✝ m : ℕ
inst✝¹ : Ring R
inst✝ : Nontrivial R
n : ℕ
hn : 0 < n
a : R
⊢ X ^ n - ↑C a ≠ 0
[PROOFSTEP]
rw [sub_eq_add_neg, ← map_neg C a]
[GOAL]
R : Type u
S : Type v
a✝ b c d : R
n✝ m : ℕ
inst✝¹ : Ring R
inst✝ : Nontrivial R
n : ℕ
hn : 0 < n
a : R
⊢ X ^ n + ↑C (-a) ≠ 0
[PROOFSTEP]
exact X_pow_add_C_ne_zero hn _
[GOAL]
R : Type u
S : Type v
a b c d : R
n✝ m : ℕ
inst✝¹ : Ring R
inst✝ : Nontrivial R
n : ℕ
r : R
⊢ natDegree (X ^ n - ↑C r) = n
[PROOFSTEP]
rw [sub_eq_add_neg, ← map_neg C r, natDegree_X_pow_add_C]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝² : Ring R
inst✝¹ : Nontrivial R
inst✝ : Ring S
r : S
⊢ leadingCoeff (X - ↑C r) = 1
[PROOFSTEP]
rw [sub_eq_add_neg, ← map_neg C r, leadingCoeff_X_add_C]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝¹ : Semiring R
inst✝ : NoZeroDivisors R
p q : R[X]
hp0 : p = 0
⊢ degree (p * q) = degree p + degree q
[PROOFSTEP]
simp only [hp0, degree_zero, zero_mul, WithBot.bot_add]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝¹ : Semiring R
inst✝ : NoZeroDivisors R
p q : R[X]
hp0 : ¬p = 0
hq0 : q = 0
⊢ degree (p * q) = degree p + degree q
[PROOFSTEP]
simp only [hq0, degree_zero, mul_zero, WithBot.add_bot]
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝¹ : Semiring R
inst✝ : NoZeroDivisors R
p✝ q✝ p q : R[X]
⊢ leadingCoeff (p * q) = leadingCoeff p * leadingCoeff q
[PROOFSTEP]
by_cases hp : p = 0
[GOAL]
case pos
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝¹ : Semiring R
inst✝ : NoZeroDivisors R
p✝ q✝ p q : R[X]
hp : p = 0
⊢ leadingCoeff (p * q) = leadingCoeff p * leadingCoeff q
[PROOFSTEP]
simp only [hp, zero_mul, leadingCoeff_zero]
[GOAL]
case neg
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝¹ : Semiring R
inst✝ : NoZeroDivisors R
p✝ q✝ p q : R[X]
hp : ¬p = 0
⊢ leadingCoeff (p * q) = leadingCoeff p * leadingCoeff q
[PROOFSTEP]
by_cases hq : q = 0
[GOAL]
case pos
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝¹ : Semiring R
inst✝ : NoZeroDivisors R
p✝ q✝ p q : R[X]
hp : ¬p = 0
hq : q = 0
⊢ leadingCoeff (p * q) = leadingCoeff p * leadingCoeff q
[PROOFSTEP]
simp only [hq, mul_zero, leadingCoeff_zero]
[GOAL]
case neg
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝¹ : Semiring R
inst✝ : NoZeroDivisors R
p✝ q✝ p q : R[X]
hp : ¬p = 0
hq : ¬q = 0
⊢ leadingCoeff (p * q) = leadingCoeff p * leadingCoeff q
[PROOFSTEP]
rw [leadingCoeff_mul']
[GOAL]
case neg
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝¹ : Semiring R
inst✝ : NoZeroDivisors R
p✝ q✝ p q : R[X]
hp : ¬p = 0
hq : ¬q = 0
⊢ leadingCoeff p * leadingCoeff q ≠ 0
[PROOFSTEP]
exact mul_ne_zero (mt leadingCoeff_eq_zero.1 hp) (mt leadingCoeff_eq_zero.1 hq)
[GOAL]
R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝¹ : Semiring R
inst✝ : NoZeroDivisors R
p q : R[X]
⊢ leadingCoeff 1 = 1
[PROOFSTEP]
simp
|
subroutine get_radar_deriv(nx,ny,nz,dx,r_miss, ! I
1 radar_ref_3d,clouds_3d,cld_hts, ! I
1 temp_3d,heights_3d,pres_3d, ! I
1 ibase_array,itop_array,thresh_cvr, ! I
1 vv_to_height_ratio_Cu, ! I
1 cldpcp_type_3d, ! I
1 w_3d,istatus) ! I/O
! Adan Teng
! this rutine calculate the cloud bogus omega in radar echo area
! First does the convective and stratiform region seperate
! In convective region using the parabolic profile as in vv.f
! but using the maximum terminal velocity deduce from reflectivity
! to be the maximum value in parabolic profile
! In stratiform region parabolic profile assigns above(behind)
! the melting level with maximum(minimum) value dependent
! on grid space and cloud depth
Implicit none
integer nx,ny,nz,istatus !input
integer cldpcp_type_3d(nx,ny,nz) !input
integer ibase_array(nx,ny) !input
integer itop_array(nx,ny) !input
real dx,r_miss !input
real radar_ref_3d(nx,ny,nz) !input (dbZ)
real clouds_3d(nx,ny,nz) !input
real cld_hts(nx,ny,nz) !input
real temp_3d(nx,ny,nz) !input
real heights_3d(nx,ny,nz) !input
real pres_3d(nx,ny,nz) !input
real thresh_cvr !input
real w_3d(nx,ny,nz) !input and output
real vv_to_height_ratio_Cu
! temprary variables
integer i,j,k
integer nxx,nyy,ier
integer str_con_index(nx,ny)
integer i_strcon
integer index_random(nx,ny)
real radar_2d_max(nx,ny) ! dbZ (while in this routine)
logical l_cloud
logical l_use_random ! utilize random indices
real temp_1d(nz)
real heights_1d(nz)
real pressure_mb(nz)
real pressure_pa(nz)
integer iarg
integer cloud_type_1d(nz)
real radar_ref_max ! dbZ
real w_1d(nz)
real w_to_omega,om_orig
integer strcon
integer rand_index
integer dbz(nx,ny)
real dx1
integer nstep
l_use_random = .false.
i_strcon = 2 ! 0 - automatic index, 2 - convective
istatus = 1
if (dx .lt. 1500.) then
dx1 = dx
nxx = nx
nyy = ny
else
nstep = int((dx+500.)/1000.)
dx1 = dx /nstep
nxx = (nx-1)*nstep+1
nyy = (ny-1)*nstep+1
endif
write(6,*)' calling get_con_str, nxx/nyy = ',nxx,nyy
! Determine convective and stratiform regions
call get_con_str(nx,ny,nz,nxx,nyy,radar_ref_3d, ! I
1 pres_3d,temp_3d, ! I
1 str_con_index, ! O
1 radar_2d_max,r_miss,ier,index_random, ! O
1 dx1) ! O
if( ier .eq. 0) then
write(*,*)'Cannot separate convection and stratiform region'
istatus = 0
return
endif
do i = 1, nx
do j = 1, ny
l_cloud = .false.
if( ibase_array(i,j) .lt. itop_array(i,j)) then
l_cloud = .true.
endif
do k = 1, nz ! Initialize
temp_1d(k) = temp_3d(i,j,k)-273.15
heights_1d(k) = heights_3d(i,j,k)
pressure_mb(k) = pres_3d(i,j,k) / 100.
pressure_pa(k) = pres_3d(i,j,k)
iarg = cldpcp_type_3d(i,j,k)
cloud_type_1d(k) = iarg - iarg/16*16
w_1d(k) = r_miss
enddo
radar_ref_max = radar_2d_max(i,j)
if(i_strcon .eq. 0)then
strcon = str_con_index(i,j)
else
strcon = i_strcon
endif
if(l_use_random)then
rand_index = index_random(i,j)
else
rand_index = 2
endif
if ( l_cloud ) then
if ( strcon .ne. 0 ) then
if(radar_ref_max .ne. r_miss)then
call radar_bogus_w
1 (dx, cloud_type_1d, heights_1d, temp_1d,
1 radar_ref_max, strcon, nz, w_1d,
1 vv_to_height_ratio_Cu, ! I
1 rand_index)
endif
do k = 1, nz
if( w_1d(k) .ne. r_miss ) then
! om_orig = w_3d(i,j,k)
w_3d(i,j,k) = w_to_omega(w_1d(k), pressure_pa(k))
! if(w_3d(i,j,k) .ne. om_orig .or.
! 1 radar_ref_max .ne. r_miss )then
! write(6,*)' orig/om/w/ref='
! 1 ,om_orig,w_3d(i,j,k),w_1d(k),radar_ref_max
! 1 ,i,j,k
! endif
endif
enddo
endif ! strcon
endif ! l_cloud
enddo !j
enddo !i
return
end
subroutine radar_bogus_w
1 (dx, cloud_type, heights, temp,
1 radar_ref_max, strcon, nz, w,
1 vv_to_height_ratio_Cu, ! I
1 rand_index)
Implicit none
integer nz, cloud_type(nz), strcon
integer rand_index
real heights(nz), temp(nz), w(nz)
real dx, radar_ref_max
real vv_to_height_ratio
real vv_to_height_ratio_Cu
! data vv_to_height_ratio /0.5/
real ratio, vv, parabolic_vv_profile
real parabolic_vv_profile1
integer k, k1, kbase, ktop, kmiddle
real zbase, ztop
real ratio_radar
real depth, vvmax
logical l_always_use_cloud,l_always_use_radar
! Cloud Type /' ','St','Sc','Cu','Ns','Ac','As','Cs','Ci','Cc','Cb'/
! Integer Value 0 1 2 3 4 5 6 7 8 9 10
l_always_use_radar = .true. ! original was .false.
l_always_use_cloud = .true. ! original was .false.
! Put in the vv's for cumuliform clouds with radar reflectivity as determined
! by cloud type at the base
vv_to_height_ratio = vv_to_height_ratio_Cu
ratio = vv_to_height_ratio / dx
if(.not. l_always_use_cloud)then
Do k = 1, nz
If (cloud_type(k) .eq. 3 .OR. cloud_type(k) .eq. 10) then
kbase = k
Go to 10
End if
End do
else
Do k = 1, nz
If (cloud_type(k) .ne. 0) then
kbase = k
Go to 10
End if
End do
endif
Go to 100
10 Do k = kbase, nz
c If (cloud_type(k) .eq. 3 .OR. cloud_type(k) .eq. 10) then
! change to the cloudtop by Adan
If (cloud_type(k) .ne. 0) then
ktop = k
Else
Go to 20
End if
End do
20 k1 = k ! save our place in the column
zbase = heights(kbase)
ztop = heights(ktop)
! Add for recomputing ratio by using terminal velocity dervied by radar
! reflectivity (Jen-Hsin Teng, Adan)
if ( strcon .eq. 2 ) then ! convective
if (rand_index .eq. 2) then ! higher index 2/3 probability
ratio_radar=0.
depth = ztop - zbase
if (depth.ne.0) then
if(radar_ref_max .gt. 0.) then
! vvmax=4.32*radar_ref_max**0.0714286
vvmax=radar_ref_max * 0.1
write(6,*)' radar_ref_max/vvmax = ',radar_ref_max,vvmax
ratio_radar=vvmax / depth / 1.1
if(ratio_radar .gt. ratio .or. l_always_use_radar)then
ratio = ratio_radar
endif
endif
else
write(6,*) 'depth =',depth, 'No changes to ratio'
endif
else ! for rand_index = 1 (1/3 probability)
ratio_radar=0.
depth = ztop - zbase
if (depth.ne.0) then
if(radar_ref_max .gt. 0. ) then
! vvmax=4.32*radar_ref_max**0.0714286
ratio_radar=vvmax / depth / 1.1
! if(ratio_radar .gt. ratio) ratio = ratio_radar
endif
else
write(6,*) 'depth =',depth, 'No changes to ratio'
endif
endif ! rand_index
Do k = 1, ktop
vv = Parabolic_vv_profile (zbase, ztop, ratio, heights(k))
If (vv .gt. 0.) then
w(k) = vv
End if
End do
elseif (strcon .eq. 1) then ! stratiform
if (temp(kbase) .le. 0. .or.
1 temp(ktop) .gt. 0.) then ! doesn't straddle freezing level
! Are warm layers fully below this level
! treated the same as cold layers fully
! above?
if (rand_index .eq. 2) then ! higher index 2/3 probability
ratio_radar=0.
depth = ztop - zbase
if (depth.ne.0) then
vvmax = 1.
ratio_radar=vvmax / depth / 1.1
if(ratio_radar .lt. ratio) ratio = ratio_radar
else
write(6,*) 'depth =',depth, 'No changes to ratio'
endif
else ! for rand_index = 1 (1/3 probability)
ratio = ratio * 0.001
ratio_radar=0.
depth = ztop - zbase
if (depth.ne.0) then
vvmax = 0.001
ratio_radar=vvmax / depth / 1.1
if(ratio_radar .lt. ratio) ratio = ratio_radar
else
write(6,*) 'depth =',depth, 'No changes to ratio'
endif
endif ! rand_index
Do k = 1, ktop
vv = Parabolic_vv_profile (zbase, ztop, ratio, heights(k))
If (vv .gt. 0.) then
w(k) = vv
End if
End do
else ! straddles freezing level
do k = kbase, ktop
if (temp(k) .le. 0.) then
kmiddle = k
go to 30
endif
enddo
30 continue
ztop = heights(kmiddle)
if( rand_index .eq. 2) then ! 2/3 probability
ratio_radar=0.
depth = ztop - zbase
if (depth.ne.0) then
vvmax = 1.
ratio_radar=vvmax / depth /1.1
if(ratio_radar .lt. ratio) ratio = ratio_radar
else
write(6,*) 'depth =',depth, 'No changes to ratio'
endif
else ! for rand_index = 1 (1/3 probabilty)
ratio = ratio * 0.001
ratio_radar=0.
depth = ztop - zbase
if (depth.ne.0) then
vvmax = 0.001
ratio_radar=vvmax / depth /1.1
if(ratio_radar .lt. ratio) ratio = ratio_radar
else
write(6,*) 'depth =',depth, 'No changes to ratio'
endif
endif ! rand_index
do k = 1, kmiddle
vv = Parabolic_vv_profile (zbase, ztop, ratio, heights(k))
if ( vv .gt. 0.) then
w(k) = -1. * vv
endif
enddo
zbase = ztop
ztop = heights(ktop)
if (rand_index .eq. 2) then ! 2/3 probability
ratio_radar=0.
depth = ztop - zbase
if (depth.ne.0) then
vvmax = 1.
ratio_radar=vvmax / depth
if(ratio_radar .lt. ratio) ratio = ratio_radar
else
write(6,*) 'depth =',depth, 'No changes to ratio'
endif
else ! for rand_index = 1 (1/3 probability)
ratio = ratio * 0.001
ratio_radar=0.
depth = ztop - zbase
if (depth.ne.0) then
vvmax = 0.001
ratio_radar=vvmax / depth
if(ratio_radar .lt. ratio) ratio = ratio_radar
else
write(6,*) 'depth =',depth, 'No changes to ratio'
endif
endif ! rand_index
! Above the freezing layer while within the echo apply a parabolic
! profile that extends only inside this layer
do k = kmiddle, ktop
vv = Parabolic_vv_profile1 (zbase, ztop, ratio, heights(k))
if ( vv .gt. 0.) then
w(k) = vv
endif
enddo
endif ! temp of layer doesn't straddle freezing level?
endif ! strcon
100 continue
return
end
subroutine get_con_str(nx,ny,nz,nxx,nyy,radar_ref_3d,pres_3d,
1 temp_3d,str_con_index,radar_2d_max,r_miss,ier,
1 index_random,dx1)
!
! Description : Interpolate radar reflectivity to 1 km
! resolution, then call dfconstr to define
! convective and stratiform region
! Also calculate the maximum reflectivity in
! vertical column
! Arguments :
! I/O/W name, type, description
! I nx integer x-dimension
! I ny integer y-dimension
! I nz integer z-dimension
! I nxx integer x-dimension for 1 km resolution
! I nyy integer y-dimension for 1 km resolution
! I radar_ref_3d real array 3d reflectivity data (dbZ)
! O str_con_index int array 2d conevction or stratiform index
! =0, missing data area
! =1, stratiform region
! =2, convective region
! I pres_3d real array 3d pressure data (pa)
! I temp_3d real array 3d temperature data (K)
! O radar_2d_max real array 2d reflectivity maximum data
! I r_miss real missing data
! O ier int =0, failure
! =1, success
! O index_random int array 2d random number index
! =0 missing data area
! =1 random number less than
! devide_random
! =2 random number greater than
! devide_random
! I dx1 real grid size of small resolution
!
implicit none
integer nx, ny, nz, nxx, nyy
real radar_ref_3d(nx,ny,nz)
real pres_3d(nx,ny,nz)
real temp_3d(nx,ny,nz)
integer str_con_index(nx,ny)
integer index_random(nx,ny)
real radar_2d_max(nx,ny)
real r_miss
real devide_random
real dx1
integer ier
integer i,j,k,ii,jj
real ref_2d(nxx,nyy)
integer icon(nxx,nyy)
integer istep,jstep
integer ref_max
integer i1, i2, j1, j2
integer idx, jdy
real a1, a2
integer ierdf
integer iconmax, icon0, icon1, icon2, icont
!
! Initialize the data
!
ier = 1
ierdf = 1
devide_random = 0.33
do i = 1, nx
do j = 1, ny
radar_2d_max(i,j) = r_miss
str_con_index(i,j) = 0
index_random(i,j) = 0
enddo
enddo
!
! calculate the maximum reflectivity in vertical column
!
do i = 1, nx
do j = 1, ny
ref_max = -10.
do k = 1, nz
if( radar_ref_3d(i,j,k) .ne. r_miss .and.
1 radar_ref_3d(i,j,k) .gt. ref_max ) then
ref_max = radar_ref_3d(i,j,k)
endif
enddo
if(ref_max .lt. -5.) then
radar_2d_max(i,j) = r_miss
else
radar_2d_max(i,j) = ref_max
endif
enddo
enddo
!
! define the level of reflectivity for convective and
! stratiform region seperate
!
! Change dBZ to Z
do i = 1, nx
do j = 1, ny
if (radar_2d_max(i,j) .ne. r_miss) then
radar_2d_max(i,j) = 10.**(0.1*radar_2d_max(i,j))
endif
enddo
enddo
!
! interpolate to small resolution
!
do i = 1, nxx
do j = 1, nyy
ref_2d(i,j) = r_miss
icon(i,j) = 0
enddo
enddo
istep = (nxx-1)/(nx-1)
jstep = int(real(nxx-1)/real(nx-1)+0.0001)
if (istep .ne. jstep .or. istep .lt. 1) then
write(*,*) 'Error in subroutine get_con_str'
ier = 0
return
endif
do i = 1, nxx, istep
ii = 1+(i-1)/istep
do j = 1, nyy, istep
jj = 1+(j-1)/istep
ref_2d(i,j) = radar_2d_max(ii,jj)
enddo
enddo
if( istep .eq. 1) go to 101
!
! interpolate
!
do i = 1, nxx-istep, istep
i1 = 1+(i-1)/istep
i2 = i1 + 1
do j = 1, nyy-istep, istep
j1 = 1+(j-1)/istep
j2 = j1 + 1
if( radar_2d_max(i1,j1) .ne. r_miss .and.
1 radar_2d_max(i1,j2) .ne. r_miss .and.
1 radar_2d_max(i2,j1) .ne. r_miss .and.
1 radar_2d_max(i2,j2) .ne. r_miss) then
do ii = i+1, i+istep-1
idx = ii - i
a1 = (real(istep-idx)*radar_2d_max(i1,j1)+
1 real(idx)*radar_2d_max(i2,j1))/real(istep)
a2 = (real(istep-idx)*radar_2d_max(i1,j2)+
1 real(idx)*radar_2d_max(i2,j2))/real(istep)
do jj = j+1, j+istep-1
jdy = jj - j
ref_2d(ii,jj)= (real(istep-jdy)*a1+
1 real(jdy)*a2)/real(istep)
enddo
enddo
endif
enddo
enddo
101 continue
! Change Z to dBZ
do i = 1, nxx
do j = 1, nyy
if(ref_2d(i,j) .ne. r_miss) then
ref_2d(i,j) = 10.* alog10(ref_2d(i,j))
endif
enddo
enddo
do i = 1, nx
do j = 1, ny
if (radar_2d_max(i,j) .ne. r_miss) then
radar_2d_max(i,j) = 10.*alog10(radar_2d_max(i,j))
endif
enddo
enddo
call dfconstr(nxx,nyy,r_miss,ref_2d,icon,ierdf,dx1)
if (ierdf .eq. 0 ) then
write(*,*)'No radar echo to define convective region'
ier = 0
return
endif
!
! change convective index to original resolution
!
do i = 1, nxx, istep
ii = 1+(i-1)/istep
do j = 1, nyy, istep
jj = 1+(j-1)/istep
! if ( ii .eq. 1 .or. ii .eq. nx .or.
! 1 jj .eq. 1 .or. jj .eq. ny .or.
! 1 istep .eq. 1) then
str_con_index(ii,jj) = icon(i,j)
! else
! jstep = (istep+1)/2
! iconmax = 0
! icon0 = 0
! icon1 = 0
! icon2 = 0
! icont = 0
! do i1 = i-jstep, i+jstep
! do j1 = j-jstep, j+jstep
! icont = icont + 1
! if (icon(i1,j1) .eq. 2) then
! icon2 = icon2 + 1
! elseif (icon(i1,j1) .eq. 1) then
! icon1 = icon1 +1
! else
! icon0 = icon0 +1
! endif
! if( icon(i1,j1) .gt. iconmax) then
! iconmax = icon(i1,j1)
! endif
! enddo
! enddo
! if( icon(i,j) .eq. 0) then
! str_con_index(ii,jj) = 0
! elseif(icon(i,j) .eq. 1) then
! str_con_index(ii,jj) = 1
! elseif(icon(i,j) .eq. 2 .and.
! 1 (icon2 .gt. 2*icon1)) then
! str_con_index(ii,jj) = 2
! else
! str_con_index(ii,jj) = 1
! endif
! endif
enddo
enddo
call df_random_index(nx,ny,str_con_index,index_random,
1 devide_random)
return
end
subroutine df_random_index(nx,ny,str_con_index,index_random
1 ,devide_random)
!
! Subroutine/Function : df_random_index
!
! Usage : call df_random_index(nx,ny,str_con_index,index_random
! 1 ,devide_random)
!
! Description : To define random number index in convective and
! stratiform region
!
! Arguments :
! I/O/W name, type, description
! I nx integer x-dimension
! I ny integer y-dimension
! I str_con_index int array 2d conevction or stratiform index
! =0, missing data area
! =1, stratiform region
! =2, convective region
! O index_random int array 2d random number index
! =0, missing data area
! =1, smaller random number
! =2, larger random number
! I devide_random real number random number threshhold
!
implicit none
integer nx, ny
integer str_con_index(nx, ny)
integer index_random(nx, ny)
real devide_random
integer i, j, k
integer seed(1)
character*9 a9time
integer i4time
integer istatus
integer idate
real harver
integer count1
call get_systime(i4time, a9time, istatus)
read(a9time, '(i9)') idate
seed(1) = idate
count1 = seed(1)
call random_seed
call random_seed(size = k)
do i = 1, count1
call random_number(harver)
enddo
!
! get random number index in stratiform region
!
do j = 1, ny
do i = 1, nx
if(str_con_index(i,j) .eq. 1) then
call random_number(harver)
if(harver .lt. devide_random) then
index_random(i,j) = 1 ! probability = devide_random
else
index_random(i,j) = 2 ! probability = 1. - devide_random
endif
endif
enddo ! nx
enddo ! ny
!
! get random number index in convective region
!
do j = 1, ny
do i = 1, nx
if(str_con_index(i,j) .eq. 2) then
call random_number(harver)
if(harver .lt. devide_random) then
index_random(i,j) = 1 ! probability = devide_random
else
index_random(i,j) = 2 ! probability = 1. - devide_random
endif
endif
enddo ! nx
enddo ! ny
return
end
subroutine dfconstr(nx,ny,r_miss,ref_2d,icon,ier,dx1)
!
! Subroutine/Function : dfconstr
!
! Usage : call dfconstr(nx,ny,r_miss,ref_2d,icon,ier)
!
! Description : To define convective and stratiform region
!
! Arguments :
! I/O/W name, type, description
! I nx integer x-dimension
! I ny integer y-dimension
! I r_miss real missing value
! I ref_2d real array 2d reflectivity data
! O icon int array 2d conevction or stratiform index
! =0, missing data area
! =1, stratiform region
! =2, convective region
! O ier integer =0, failure
! =1, success
! I dx1 real grid size
! Original version: Shiow-Ming Deng
! Recently version: Jen-Hsin Teng in 15-Aug-2003
!
implicit none
integer nx, ny, ier
real r_miss
real ref_2d(nx,ny)
integer icon(nx,ny)
integer i, j, nn, ii, jj
real dzmax, dzmin, sumdz, detz, gdz
real dx1
integer irr
integer njump
ier = 0
njump = int(10000./dx1)
if( nx .lt. 3*njump .or. ny .lt. 3*njump) then
write(*,*) 'Error in subroutine dfconstr.'
write(*,*) 'Your Domain is too small.'
write(*,*) ' nx:',nx,' ny:',ny
return
endif
dzmax = 42.
dzmin = 20.
! Initial icon data
do j = 1,ny
do i = 1,nx
icon(i,j)=0
enddo
enddo
do 100 j = njump+1, ny-njump, 1
do 100 i = njump+1, nx-njump, 1
if(ref_2d(i,j) .eq. r_miss) go to 100
ier = 1
if(ref_2d(i,j) .lt. dzmin ) then
icon(i,j) = 1
go to 100
endif
if(ref_2d(i,j) .ge. dzmax ) then
icon(i,j) = 2
go to 100
endif
icon(i,j) = 1
sumdz = 0.
nn = 0
do jj = j-njump, j+njump, 1
do ii = i-njump, i+njump, 1
irr=(jj-j)**2+(ii-i)**2
if (irr .le. 100) then
nn = nn + 1
if( ref_2d(ii,jj) .ne. r_miss ) then
sumdz = sumdz + ref_2d(ii,jj)
else
sumdz = sumdz - 5.
endif
endif
enddo
enddo
if ( nn .gt. 0 ) then
gdz = sumdz/real(nn)
else
go to 100
endif
if ( gdz .lt. 0. ) then
detz = 12
else
detz = (12.-gdz**2./147.)
endif
if ( (ref_2d(i,j)-gdz) .gt. detz ) icon(i,j) = 2
100 continue
return
end
|
/-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
-/
import data.equiv.basic
import data.fun_like.embedding
import data.pprod
import data.set.basic
import data.sigma.basic
/-!
# Injective functions
-/
universes u v w x
namespace function
/-- `α ↪ β` is a bundled injective function. -/
@[nolint has_inhabited_instance] -- depending on cardinalities, an injective function may not exist
structure embedding (α : Sort*) (β : Sort*) :=
(to_fun : α → β)
(inj' : injective to_fun)
infixr ` ↪ `:25 := embedding
instance {α : Sort u} {β : Sort v} : has_coe_to_fun (α ↪ β) (λ _, α → β) := ⟨embedding.to_fun⟩
initialize_simps_projections embedding (to_fun → apply)
instance {α : Sort u} {β : Sort v} : embedding_like (α ↪ β) α β :=
{ coe := embedding.to_fun,
injective' := embedding.inj',
coe_injective' := λ f g h, by { cases f, cases g, congr' } }
end function
section equiv
variables {α : Sort u} {β : Sort v} (f : α ≃ β)
/-- Convert an `α ≃ β` to `α ↪ β`.
This is also available as a coercion `equiv.coe_embedding`.
The explicit `equiv.to_embedding` version is preferred though, since the coercion can have issues
inferring the type of the resulting embedding. For example:
```lean
-- Works:
example (s : finset (fin 3)) (f : equiv.perm (fin 3)) : s.map f.to_embedding = s.map f := by simp
-- Error, `f` has type `fin 3 ≃ fin 3` but is expected to have type `fin 3 ↪ ?m_1 : Type ?`
example (s : finset (fin 3)) (f : equiv.perm (fin 3)) : s.map f = s.map f.to_embedding := by simp
```
-/
@[simps] protected def equiv.to_embedding : α ↪ β := ⟨f, f.injective⟩
instance equiv.coe_embedding : has_coe (α ≃ β) (α ↪ β) := ⟨equiv.to_embedding⟩
@[reducible]
instance equiv.perm.coe_embedding : has_coe (equiv.perm α) (α ↪ α) := equiv.coe_embedding
@[simp] lemma equiv.coe_eq_to_embedding : ↑f = f.to_embedding := rfl
/-- Given an equivalence to a subtype, produce an embedding to the elements of the corresponding
set. -/
@[simps]
def equiv.as_embedding {p : β → Prop} (e : α ≃ subtype p) : α ↪ β :=
⟨coe ∘ e, subtype.coe_injective.comp e.injective⟩
@[simp]
lemma equiv.as_embedding_range {α β : Sort*} {p : β → Prop} (e : α ≃ subtype p) :
set.range e.as_embedding = set_of p :=
set.ext $ λ x, ⟨λ ⟨y, h⟩, h ▸ subtype.coe_prop (e y), λ hs, ⟨e.symm ⟨x, hs⟩, by simp⟩⟩
end equiv
namespace function
namespace embedding
lemma coe_injective {α β} : @function.injective (α ↪ β) (α → β) coe_fn := fun_like.coe_injective
@[ext] lemma ext {α β} {f g : embedding α β} (h : ∀ x, f x = g x) : f = g := fun_like.ext f g h
lemma ext_iff {α β} {f g : embedding α β} : (∀ x, f x = g x) ↔ f = g := fun_like.ext_iff.symm
@[simp] theorem to_fun_eq_coe {α β} (f : α ↪ β) : to_fun f = f := rfl
@[simp] theorem coe_fn_mk {α β} (f : α → β) (i) :
(@mk _ _ f i : α → β) = f := rfl
@[simp] lemma mk_coe {α β : Type*} (f : α ↪ β) (inj) : (⟨f, inj⟩ : α ↪ β) = f :=
by { ext, simp }
protected theorem injective {α β} (f : α ↪ β) : injective f := embedding_like.injective f
lemma apply_eq_iff_eq {α β} (f : α ↪ β) (x y : α) : f x = f y ↔ x = y :=
embedding_like.apply_eq_iff_eq f
/-- The identity map as a `function.embedding`. -/
@[refl, simps {simp_rhs := tt}]
protected def refl (α : Sort*) : α ↪ α :=
⟨id, injective_id⟩
/-- Composition of `f : α ↪ β` and `g : β ↪ γ`. -/
@[trans, simps {simp_rhs := tt}]
protected def trans {α β γ} (f : α ↪ β) (g : β ↪ γ) : α ↪ γ :=
⟨g ∘ f, g.injective.comp f.injective⟩
@[simp]
lemma equiv_to_embedding_trans_symm_to_embedding {α β : Sort*} (e : α ≃ β) :
e.to_embedding.trans e.symm.to_embedding = embedding.refl _ :=
by { ext, simp, }
@[simp]
lemma equiv_symm_to_embedding_trans_to_embedding {α β : Sort*} (e : α ≃ β) :
e.symm.to_embedding.trans e.to_embedding = embedding.refl _ :=
by { ext, simp, }
/-- Transfer an embedding along a pair of equivalences. -/
@[simps { fully_applied := ff }]
protected def congr {α : Sort u} {β : Sort v} {γ : Sort w} {δ : Sort x}
(e₁ : α ≃ β) (e₂ : γ ≃ δ) (f : α ↪ γ) : (β ↪ δ) :=
(equiv.to_embedding e₁.symm).trans (f.trans e₂.to_embedding)
/-- A right inverse `surj_inv` of a surjective function as an `embedding`. -/
protected noncomputable def of_surjective {α β} (f : β → α) (hf : surjective f) :
α ↪ β :=
⟨surj_inv hf, injective_surj_inv _⟩
/-- Convert a surjective `embedding` to an `equiv` -/
protected noncomputable def equiv_of_surjective {α β} (f : α ↪ β) (hf : surjective f) :
α ≃ β :=
equiv.of_bijective f ⟨f.injective, hf⟩
/-- There is always an embedding from an empty type. --/
protected def of_is_empty {α β} [is_empty α] : α ↪ β :=
⟨is_empty_elim, is_empty_elim⟩
/-- Change the value of an embedding `f` at one point. If the prescribed image
is already occupied by some `f a'`, then swap the values at these two points. -/
def set_value {α β} (f : α ↪ β) (a : α) (b : β) [∀ a', decidable (a' = a)]
[∀ a', decidable (f a' = b)] : α ↪ β :=
⟨λ a', if a' = a then b else if f a' = b then f a else f a',
begin
intros x y h,
dsimp at h,
split_ifs at h; try { substI b }; try { simp only [f.injective.eq_iff] at * }; cc
end⟩
theorem set_value_eq {α β} (f : α ↪ β) (a : α) (b : β) [∀ a', decidable (a' = a)]
[∀ a', decidable (f a' = b)] : set_value f a b a = b :=
by simp [set_value]
/-- Embedding into `option α` using `some`. -/
@[simps { fully_applied := ff }] protected def some {α} : α ↪ option α :=
⟨some, option.some_injective α⟩
/-- Embedding into `option α` using `coe`. Usually the correct synctatical form for `simp`. -/
@[simps { fully_applied := ff }]
def coe_option {α} : α ↪ option α := ⟨coe, option.some_injective α⟩
/-- Embedding into `with_top α`. -/
@[simps]
def coe_with_top {α} : α ↪ with_top α := { to_fun := coe, ..embedding.some}
/-- Given an embedding `f : α ↪ β` and a point outside of `set.range f`, construct an embedding
`option α ↪ β`. -/
@[simps] def option_elim {α β} (f : α ↪ β) (x : β) (h : x ∉ set.range f) :
option α ↪ β :=
⟨λ o, o.elim x f, option.injective_iff.2 ⟨f.2, h⟩⟩
/-- Embedding of a `subtype`. -/
def subtype {α} (p : α → Prop) : subtype p ↪ α :=
⟨coe, λ _ _, subtype.ext_val⟩
@[simp] lemma coe_subtype {α} (p : α → Prop) : ⇑(subtype p) = coe := rfl
/-- Choosing an element `b : β` gives an embedding of `punit` into `β`. -/
def punit {β : Sort*} (b : β) : punit ↪ β :=
⟨λ _, b, by { rintros ⟨⟩ ⟨⟩ _, refl, }⟩
/-- Fixing an element `b : β` gives an embedding `α ↪ α × β`. -/
def sectl (α : Sort*) {β : Sort*} (b : β) : α ↪ α × β :=
⟨λ a, (a, b), λ a a' h, congr_arg prod.fst h⟩
/-- Fixing an element `a : α` gives an embedding `β ↪ α × β`. -/
def sectr {α : Sort*} (a : α) (β : Sort*): β ↪ α × β :=
⟨λ b, (a, b), λ b b' h, congr_arg prod.snd h⟩
/-- Restrict the codomain of an embedding. -/
def cod_restrict {α β} (p : set β) (f : α ↪ β) (H : ∀ a, f a ∈ p) : α ↪ p :=
⟨λ a, ⟨f a, H a⟩, λ a b h, f.injective (@congr_arg _ _ _ _ subtype.val h)⟩
@[simp] theorem cod_restrict_apply {α β} (p) (f : α ↪ β) (H a) :
cod_restrict p f H a = ⟨f a, H a⟩ := rfl
/-- If `e₁` and `e₂` are embeddings, then so is `prod.map e₁ e₂ : (a, b) ↦ (e₁ a, e₂ b)`. -/
def prod_map {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α × γ ↪ β × δ :=
⟨prod.map e₁ e₂, e₁.injective.prod_map e₂.injective⟩
@[simp] lemma coe_prod_map {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) :
⇑(e₁.prod_map e₂) = prod.map e₁ e₂ :=
rfl
/-- If `e₁` and `e₂` are embeddings, then so is `λ ⟨a, b⟩, ⟨e₁ a, e₂ b⟩ : pprod α γ → pprod β δ`. -/
def pprod_map {α β γ δ : Sort*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : pprod α γ ↪ pprod β δ :=
⟨λ x, ⟨e₁ x.1, e₂ x.2⟩, e₁.injective.pprod_map e₂.injective⟩
section sum
open sum
/-- If `e₁` and `e₂` are embeddings, then so is `sum.map e₁ e₂`. -/
def sum_map {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α ⊕ γ ↪ β ⊕ δ :=
⟨sum.map e₁ e₂,
assume s₁ s₂ h, match s₁, s₂, h with
| inl a₁, inl a₂, h := congr_arg inl $ e₁.injective $ inl.inj h
| inr b₁, inr b₂, h := congr_arg inr $ e₂.injective $ inr.inj h
end⟩
@[simp] theorem coe_sum_map {α β γ δ} (e₁ : α ↪ β) (e₂ : γ ↪ δ) :
⇑(sum_map e₁ e₂) = sum.map e₁ e₂ :=
rfl
/-- The embedding of `α` into the sum `α ⊕ β`. -/
@[simps] def inl {α β : Type*} : α ↪ α ⊕ β :=
⟨sum.inl, λ a b, sum.inl.inj⟩
/-- The embedding of `β` into the sum `α ⊕ β`. -/
@[simps] def inr {α β : Type*} : β ↪ α ⊕ β :=
⟨sum.inr, λ a b, sum.inr.inj⟩
end sum
section sigma
variables {α α' : Type*} {β : α → Type*} {β' : α' → Type*}
/-- `sigma.mk` as an `function.embedding`. -/
@[simps apply] def sigma_mk (a : α) : β a ↪ Σ x, β x :=
⟨sigma.mk a, sigma_mk_injective⟩
/-- If `f : α ↪ α'` is an embedding and `g : Π a, β α ↪ β' (f α)` is a family
of embeddings, then `sigma.map f g` is an embedding. -/
@[simps apply] def sigma_map (f : α ↪ α') (g : Π a, β a ↪ β' (f a)) :
(Σ a, β a) ↪ Σ a', β' a' :=
⟨sigma.map f (λ a, g a), f.injective.sigma_map (λ a, (g a).injective)⟩
end sigma
/-- Define an embedding `(Π a : α, β a) ↪ (Π a : α, γ a)` from a family of embeddings
`e : Π a, (β a ↪ γ a)`. This embedding sends `f` to `λ a, e a (f a)`. -/
@[simps] def Pi_congr_right {α : Sort*} {β γ : α → Sort*} (e : ∀ a, β a ↪ γ a) :
(Π a, β a) ↪ (Π a, γ a) :=
⟨λf a, e a (f a), λ f₁ f₂ h, funext $ λ a, (e a).injective (congr_fun h a)⟩
/-- An embedding `e : α ↪ β` defines an embedding `(γ → α) ↪ (γ → β)` that sends each `f`
to `e ∘ f`. -/
def arrow_congr_right {α : Sort u} {β : Sort v} {γ : Sort w}
(e : α ↪ β) : (γ → α) ↪ (γ → β) :=
Pi_congr_right (λ _, e)
@[simp] lemma arrow_congr_right_apply {α : Sort u} {β : Sort v} {γ : Sort w}
(e : α ↪ β) (f : γ ↪ α) : arrow_congr_right e f = e ∘ f := rfl
/-- An embedding `e : α ↪ β` defines an embedding `(α → γ) ↪ (β → γ)` for any inhabited type `γ`.
This embedding sends each `f : α → γ` to a function `g : β → γ` such that `g ∘ e = f` and
`g y = default` whenever `y ∉ range e`. -/
noncomputable def arrow_congr_left {α : Sort u} {β : Sort v} {γ : Sort w} [inhabited γ]
(e : α ↪ β) : (α → γ) ↪ (β → γ) :=
⟨λ f, extend e f (λ _, default), λ f₁ f₂ h, funext $ λ x,
by simpa only [extend_apply e.injective] using congr_fun h (e x)⟩
/-- Restrict both domain and codomain of an embedding. -/
protected def subtype_map {α β} {p : α → Prop} {q : β → Prop} (f : α ↪ β)
(h : ∀{{x}}, p x → q (f x)) : {x : α // p x} ↪ {y : β // q y} :=
⟨subtype.map f h, subtype.map_injective h f.2⟩
open set
/-- `set.image` as an embedding `set α ↪ set β`. -/
@[simps apply] protected def image {α β} (f : α ↪ β) : set α ↪ set β :=
⟨image f, f.2.image_injective⟩
lemma swap_apply {α β : Type*} [decidable_eq α] [decidable_eq β] (f : α ↪ β) (x y z : α) :
equiv.swap (f x) (f y) (f z) = f (equiv.swap x y z) :=
f.injective.swap_apply x y z
lemma swap_comp {α β : Type*} [decidable_eq α] [decidable_eq β] (f : α ↪ β) (x y : α) :
equiv.swap (f x) (f y) ∘ f = f ∘ equiv.swap x y :=
f.injective.swap_comp x y
end embedding
end function
namespace equiv
open function.embedding
/-- The type of embeddings `α ↪ β` is equivalent to
the subtype of all injective functions `α → β`. -/
def subtype_injective_equiv_embedding (α β : Sort*) :
{f : α → β // function.injective f} ≃ (α ↪ β) :=
{ to_fun := λ f, ⟨f.val, f.property⟩,
inv_fun := λ f, ⟨f, f.injective⟩,
left_inv := λ f, by simp,
right_inv := λ f, by {ext, refl} }
/-- If `α₁ ≃ α₂` and `β₁ ≃ β₂`, then the type of embeddings `α₁ ↪ β₁`
is equivalent to the type of embeddings `α₂ ↪ β₂`. -/
@[congr, simps apply] def embedding_congr {α β γ δ : Sort*}
(h : α ≃ β) (h' : γ ≃ δ) : (α ↪ γ) ≃ (β ↪ δ) :=
{ to_fun := λ f, f.congr h h',
inv_fun := λ f, f.congr h.symm h'.symm,
left_inv := λ x, by {ext, simp},
right_inv := λ x, by {ext, simp} }
@[simp] lemma embedding_congr_refl {α β : Sort*} :
embedding_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α ↪ β) :=
by {ext, refl}
@[simp] lemma embedding_congr_trans {α₁ β₁ α₂ β₂ α₃ β₃ : Sort*}
(e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) :
embedding_congr (e₁.trans e₂) (e₁'.trans e₂') =
(embedding_congr e₁ e₁').trans (embedding_congr e₂ e₂') :=
rfl
@[simp] lemma embedding_congr_symm {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) :
(embedding_congr e₁ e₂).symm = embedding_congr e₁.symm e₂.symm :=
rfl
lemma embedding_congr_apply_trans {α₁ β₁ γ₁ α₂ β₂ γ₂ : Sort*}
(ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) (ec : γ₁ ≃ γ₂) (f : α₁ ↪ β₁) (g : β₁ ↪ γ₁) :
equiv.embedding_congr ea ec (f.trans g) =
(equiv.embedding_congr ea eb f).trans (equiv.embedding_congr eb ec g) :=
by {ext, simp}
@[simp]
lemma refl_to_embedding {α : Type*} : (equiv.refl α).to_embedding = function.embedding.refl α := rfl
@[simp]
lemma trans_to_embedding {α β γ : Type*} (e : α ≃ β) (f : β ≃ γ) :
(e.trans f).to_embedding = e.to_embedding.trans f.to_embedding := rfl
end equiv
namespace set
/-- The injection map is an embedding between subsets. -/
@[simps apply] def embedding_of_subset {α} (s t : set α) (h : s ⊆ t) : s ↪ t :=
⟨λ x, ⟨x.1, h x.2⟩, λ ⟨x, hx⟩ ⟨y, hy⟩ h, by { congr, injection h }⟩
end set
section subtype
variable {α : Type*}
/-- A subtype `{x // p x ∨ q x}` over a disjunction of `p q : α → Prop` can be injectively split
into a sum of subtypes `{x // p x} ⊕ {x // q x}` such that `¬ p x` is sent to the right. -/
def subtype_or_left_embedding (p q : α → Prop) [decidable_pred p] :
{x // p x ∨ q x} ↪ {x // p x} ⊕ {x // q x} :=
⟨λ x, if h : p x then sum.inl ⟨x, h⟩ else sum.inr ⟨x, x.prop.resolve_left h⟩,
begin
intros x y,
dsimp only,
split_ifs;
simp [subtype.ext_iff]
end⟩
lemma subtype_or_left_embedding_apply_left {p q : α → Prop} [decidable_pred p]
(x : {x // p x ∨ q x}) (hx : p x) : subtype_or_left_embedding p q x = sum.inl ⟨x, hx⟩ :=
dif_pos hx
lemma subtype_or_left_embedding_apply_right {p q : α → Prop} [decidable_pred p]
(x : {x // p x ∨ q x}) (hx : ¬ p x) :
subtype_or_left_embedding p q x = sum.inr ⟨x, x.prop.resolve_left hx⟩ :=
dif_neg hx
/-- A subtype `{x // p x}` can be injectively sent to into a subtype `{x // q x}`,
if `p x → q x` for all `x : α`. -/
@[simps] def subtype.imp_embedding (p q : α → Prop) (h : p ≤ q) :
{x // p x} ↪ {x // q x} :=
⟨λ x, ⟨x, h x x.prop⟩, λ x y, by simp [subtype.ext_iff]⟩
/-- A subtype `{x // p x ∨ q x}` over a disjunction of `p q : α → Prop` is equivalent to a sum of
subtypes `{x // p x} ⊕ {x // q x}` such that `¬ p x` is sent to the right, when
`disjoint p q`.
See also `equiv.sum_compl`, for when `is_compl p q`. -/
@[simps apply] def subtype_or_equiv (p q : α → Prop) [decidable_pred p] (h : disjoint p q) :
{x // p x ∨ q x} ≃ {x // p x} ⊕ {x // q x} :=
{ to_fun := subtype_or_left_embedding p q,
inv_fun := sum.elim
(subtype.imp_embedding _ _ (λ x hx, (or.inl hx : p x ∨ q x)))
(subtype.imp_embedding _ _ (λ x hx, (or.inr hx : p x ∨ q x))),
left_inv := λ x, begin
by_cases hx : p x,
{ rw subtype_or_left_embedding_apply_left _ hx,
simp [subtype.ext_iff] },
{ rw subtype_or_left_embedding_apply_right _ hx,
simp [subtype.ext_iff] },
end,
right_inv := λ x, begin
cases x,
{ simp only [sum.elim_inl],
rw subtype_or_left_embedding_apply_left,
{ simp },
{ simpa using x.prop } },
{ simp only [sum.elim_inr],
rw subtype_or_left_embedding_apply_right,
{ simp },
{ suffices : ¬ p x,
{ simpa },
intro hp,
simpa using h x ⟨hp, x.prop⟩ } }
end }
@[simp] lemma subtype_or_equiv_symm_inl (p q : α → Prop) [decidable_pred p] (h : disjoint p q)
(x : {x // p x}) : (subtype_or_equiv p q h).symm (sum.inl x) = ⟨x, or.inl x.prop⟩ :=
rfl
@[simp] lemma subtype_or_equiv_symm_inr (p q : α → Prop) [decidable_pred p] (h : disjoint p q)
(x : {x // q x}) : (subtype_or_equiv p q h).symm (sum.inr x) = ⟨x, or.inr x.prop⟩ :=
rfl
end subtype
|
widen_eltype(::Type{T}) where {T<:Number} = widen(T)
widen_eltype(::Type{SVector{N,T}}) where {N,T<:Number} = SVector{N,widen(T)}
widen_eltype(::Type{Vector{T}}) where {T<:Number} = Vector{widen(T)}
# We test the generic functionality of a domain.
# These tests check whether the given domain correctly implements the
# interface of a domain.
function test_generic_domain(d::Domain)
@test isreal(d) == isreal(eltype(d))
@test isreal(d) == isreal(numtype(d))
@test convert(Domain{eltype(d)}, d) == d
@test convert(Domain{widen_eltype(eltype(d))}, d) == d
@test prectype(convert_prectype(d, BigFloat)) == BigFloat
if !isempty(d)
x = point_in_domain(d)
@test x ∈ d
@test approx_in(x, d, 0.01)
@test_throws ErrorException approx_in(x, d, -1)
@test in.([x,x], d) == in.([x,x], Ref(d))
@test approx_in.([x,x], d, 0.01) == approx_in.([x,x], Ref(d), 0.01)
else
try
x = point_in_domain(d)
@test false
catch
end
end
@test canonicaldomain(DomainSets.Equal(), d) == d
if canonicaldomain(d) == d
@test mapto_canonical(d) == IdentityMap{eltype(d)}(dimension(d))
@test mapfrom_canonical(d) == IdentityMap{eltype(d)}(dimension(d))
else
cd = canonicaldomain(d)
@test mapfrom_canonical(d) == mapto(cd, d)
@test mapto_canonical(d) == mapto(d, cd)
end
if iscomposite(d)
@test ncomponents(d) == length(components(d))
els = components(d)
@test all([component(d,i) == els[i] for i in 1:ncomponents(d)])
end
end
@testset "generic domain interface" begin
domains = [
0..1,
UnitInterval(),
ChebyshevInterval(),
HalfLine(),
NegativeHalfLine(),
UnitInterval()^3,
(0..1) × (2.0..3) × (3..4),
UnitBall(),
VectorUnitBall(),
VectorUnitBall(8),
UnitDisk(),
VectorUnitDisk(),
UnitCircle(),
VectorUnitCircle(),
UnitSphere(),
VectorUnitSphere(),
UnitSimplex(Val(2)),
UnitSimplex(2),
DomainSets.WrappedDomain(0..2.0)
]
@testset "generic domains" begin
for domain in domains
test_generic_domain(domain)
end
end
@testset "generic functionality" begin
struct SomeDomain <: Domain{Float64}
end
@test_throws MethodError 0.5 ∈ SomeDomain()
@test_throws MethodError approx_in(0.5, SomeDomain())
if VERSION < v"1.6-"
@test_logs (:warn, "`in`: incompatible combination of point: Tuple{Float64,Float64} and domain eltype: SArray{Tuple{2},Float64,1,2}. Returning false.") (0.5,0.2) ∈ UnitCircle()
@test_logs (:warn, "`in`: incompatible combination of point: Tuple{Float64,Float64} and domain eltype: SArray{Tuple{2},Float64,1,2}. Returning false.") approx_in((0.5,0.2), UnitCircle())
else
@test_logs (:warn, "`in`: incompatible combination of point: Tuple{Float64, Float64} and domain eltype: SVector{2, Float64}. Returning false.") (0.5,0.2) ∈ UnitCircle()
@test_logs (:warn, "`in`: incompatible combination of point: Tuple{Float64, Float64} and domain eltype: SVector{2, Float64}. Returning false.") approx_in((0.5,0.2), UnitCircle())
end
# some functionality in broadcast
@test 2 * (1..2) == 2 .* (1..2)
@test (1..2) * 2 == (1..2) .* 2
@test (1..2) / 2 ≈ (0.5..1)
@test 2 \ (1..2) ≈ (0.5..1)
@test_throws MethodError (0..1) + 0.4
# promotion
@test DomainSets.promote_domains() == ()
s1 = Set([0..1,2..3,3..4.0])
@test s1 isa Set{<:Domain{Float64}}
@test DomainSets.promote_domains(s1) == s1
s2 = Set([0..1,2..3,3..4.0, Point(2)])
@test s2 isa Set{Domain}
@test DomainSets.promote_domains(s2) isa Set{<:Domain{Float64}}
@test DomainSets.promote(0..1.0, [1,2,3]) isa Tuple{Interval,Vector{Float64}}
@test DomainSets.promote([1,2,3], 0..1.0) isa Tuple{Vector{Float64},Interval}
# compatible point-domain pairs
@test DomainSets.iscompatiblepair(0.5, 0..1)
@test DomainSets.iscompatiblepair(0.5, 0..1.0)
@test !DomainSets.iscompatiblepair(0.5, UnitBall())
@test DomainSets.iscompatiblepair(0.5, [0.3])
@test DomainSets.iscompatiblepair(0, [0.3])
@test DomainSets.iscompatiblepair(0.5, [1, 2, 3])
@test DomainSets.iscompatiblepair(0, Set([1, 2, 3]))
@test DomainSets.iscompatiblepair(0.5, Set([1, 2, 3]))
@test DomainSets.iscompatiblepair(0, Set([1.0, 2, 3]))
@test DomainSets.convert_eltype(Float64, Set([1,2])) isa Set{Float64}
@test_throws ErrorException DomainSets.convert_eltype(Float64, (1,2)) isa NTuple{2,Float64}
@test DomainSets.convert_eltype(Int, (1,2)) == (1,2)
end
end
|
module Evens
public export
data IsEven : Nat -> Type where
ZEven : IsEven 0
SSEven : (n: Nat) -> IsEven n -> IsEven (S (S n))
twoEven : IsEven 2
twoEven = SSEven 0 ZEven
fourEven : IsEven 4
fourEven = SSEven 2 twoEven
half : (n: Nat) -> IsEven n -> Nat
half Z ZEven = 0
half (S (S k)) (SSEven k x) = S (half k x)
public export
double: Nat -> Nat
double Z = Z
double (S k) = S (S (double k))
doubleEven : (n: Nat) -> IsEven (double n)
doubleEven Z = ZEven
doubleEven (S k) = SSEven (double k) (doubleEven k)
halfDouble: Nat -> Nat
halfDouble n = half (double n) (doubleEven n)
oneOdd: IsEven 1 -> Void
oneOdd ZEven impossible
oneOdd (SSEven _ _) impossible
threeOdd : IsEven 3 -> Void
threeOdd (SSEven (S Z) ZEven) impossible
threeOdd (SSEven (S Z) (SSEven _ _)) impossible
nOrSnEven: (n: Nat) -> Either (IsEven n) (IsEven (S n))
nOrSnEven Z = Left ZEven
nOrSnEven (S k) = case (nOrSnEven k) of
(Left l) => Right (SSEven k l)
(Right r) => Left r
halfRoof: Nat -> Nat
halfRoof n = case (nOrSnEven n) of
(Left nEven) => half n nEven
(Right snEven) => half (S n) snEven
nSnNotBothEven: (n: Nat) -> (IsEven n) -> IsEven (S n) -> Void
nSnNotBothEven Z ZEven ZEven impossible
nSnNotBothEven Z ZEven (SSEven _ _) impossible
nSnNotBothEven (S (S k)) (SSEven k x) (SSEven (S k) y) = nSnNotBothEven k x y
notNandSnEven : (n: Nat) -> (IsEven n , IsEven (S n)) -> Void
notNandSnEven n (a, b) = nSnNotBothEven n a b
apNat : (f: Nat -> Nat) -> (n: Nat) -> (m: Nat) -> n = m -> f n = f m
apNat f m m Refl = Refl
byTwo : (n: Nat) -> IsEven n -> (k: Nat ** double k = n)
byTwo Z ZEven = (0 ** Refl)
byTwo (S (S k)) (SSEven k x) = step where
step = case (byTwo k x) of
(m ** pf) => ((S m) ** apNat (\l => S (S l)) (double m) k pf)
oneOddFamily : Nat -> Type
oneOddFamily Z = ()
oneOddFamily (S Z) = Void
oneOddFamily (S (S k)) = ()
oneOddProof : (n : Nat) -> IsEven n -> oneOddFamily n
oneOddProof Z ZEven = ()
oneOddProof (S (S k)) (SSEven k x) = ()
|
Formal statement is: lemma Cauchy_theorem_homotopic: assumes hom: "if atends then homotopic_paths S g h else homotopic_loops S g h" and "open S" and f: "f holomorphic_on S" and vpg: "valid_path g" and vph: "valid_path h" shows "contour_integral g f = contour_integral h f" Informal statement is: If $g$ and $h$ are homotopic paths or loops in an open set $S$, then $\int_g f = \int_h f$ for any holomorphic function $f$ on $S$. |
module Inigo.Async.Util
public export
toObject : String
toObject = "let toObject=((list)=>Object.fromEntries([...Array(list.h).keys()].map((i)=>{let x=list['a'+(i+1)];return [x.a1,x.a2]})));"
public export
toArray : String -> String
toArray str = "(function(){let toArray=(x)=>{if(x.h === 0){return []}else{return [x.a1].concat(toArray(x.a2))}};return " ++ str ++ "})()"
public export
promisifyPrim_ : String -> String
promisifyPrim_ str =
"(...args)=>{let [w,err,ok,...fargs]=args.reverse();return (" ++ str ++ ")(...fargs.reverse()).then((x)=>ok(x)(w),(e)=>err(e)(w))}"
public export
promisifyPrim: String -> String
promisifyPrim str =
"node:lambda:" ++ (promisifyPrim_ str)
public export
promisifyResolve: String -> String -> String
promisifyResolve res str =
"node:lambda:" ++ promisifyPrim_ ( "(...inner)=>{(" ++ str ++ ")(...inner);return Promise.resolve(" ++ res ++ ");}" )
|
\documentclass[10pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\begin{document}
\section{Stochastic Process}
A stochastic process is of the form
\begin{align}
X_{T+1}-X_{T} = \theta(T) X_{T} +f(t) +r_{T} \sigma(T),
\end{align}
where $r_T$ is a random variable drawn from the distribution $P(r,\vec{\lambda})$, where $\vec{\lambda}$ are the parameters that describe the distribution.
\begin{align}
P(X_T) &= \int dX_{T-\Delta T} \int dr_T \ P(X_T,X_{T-\Delta T},r), \\
&= \int dX_{T-\Delta T} \int dr_T \ P(X_T|X_{T-\Delta T},r)P(X_{T-\Delta T},r_T),
\end{align}
assuming that $X_{T-\Delta T}$ is independent of the random variable $r_T$, then this expression becomes
\begin{align}
P(X_T) &= \int dX_{T-\Delta T} \int dr_T \ P(X_T|X_{T-\Delta T},r_T)P(X_{T-\Delta T})P(r_T) .
\end{align}
Next, we apply the constraint where
\begin{align}
r_{T} = \frac{X_{T+1}-X_T -\theta(T) X_{T}-f(T) }{\sigma(T)},
\end{align}
this constraint is enforced through the function
\begin{align}
P(X_T|X_{T-\Delta T},r_T) = \delta\left(r_{T} -\frac{X_{T}-X_{T-1} -\theta(T-\Delta T) X_{T-\Delta T}-f(T) }{\sigma(T-\Delta T)} \right).
\end{align}
Carrying out the integral over $r_T$ results in
\begin{align}
P(X_T) &= \int dX_{T-\Delta T} P(X_{T-\Delta T})P\left(r_T = \frac{X_{T}-X_{T-1} -\theta(T-\Delta T) X_{T-\Delta T}-f(T-\Delta T) }{\sigma(T-\Delta T)}\right),
\end{align}
this last expression relates the probability distribution of the current value $X_T$ to the value at a time infinitesimally in the past. Carrying out this expression recursively we obtain
\begin{align}
P(X_T) &= \int dX_{T-\Delta T} \ P\left(\frac{X_{T}-X_{T-\Delta T}-f(T-\Delta T) -\theta(T-\Delta T) X_{T-\Delta T} }{\sigma(T-\Delta T)}\right) \notag\\
& \cdots \int dX_{0} \ P\left(\frac{X_{1}-X_{0}-f(T_0) -\theta(T_0) X_{0} }{\sigma(T_0)}\right)\delta(X_0 -x_0),
\end{align}
where $x_0$ is the position at the initial point $T_0$.\\
\section{Gaussian Noise}
Now we have the general forms of the stochastic integrals that we want to work with
\subsection{Fokker-Plank Equation}
\subsection{Path integrals}
This probability can also be expressed as a path integral of the form
\begin{align}
P(X_T) &= \int \mathcal{D}X \ \text{Exp}\left(\int\limits_{T_0}^T S(\dot{X},X,t) dt \right),
\end{align}
where the action is
\begin{align}
S(\dot{X},X,t) &= -\frac{1}{2\sigma^{2}(t)}\left( \dot{X}(t)-f(t)-\theta(t) X(t) \right)^2
\end{align}
\end{document} |
From Utils Require Import Env Tactics.
From Common Require Import Literal Primitive.
From Src Require Import Tree Fun_sem.
From CPS Require Import Tree Fun_sem.
(* Equi. *)
Require Import FunInd.
Open Scope list_scope.
Module ST := Src.Tree.
Module SV := Src.Fun_sem.
Module CT := CPS.Tree.
Module CV := CPS.Fun_sem.
Function cps_rec (nf : nat) (t : ST.term) (cnt : nat) {struct t} : nat * CT.term :=
match t with
| ST.Var n => (nf, CT.AppC1 cnt (CT.Var n))
| ST.Const l => (nf, CT.AppC1 cnt (CT.Lit l))
| ST.Let n t r =>
let (nf, cb) := cps_rec nf r cnt in
let cn := nf in
let (nf, t') := cps_rec (nf + 1) t cn in
(nf, CT.LetC (CT.Cnt1 cn n cb) t')
| ST.LetRec (ST.Fnt n a b) r =>
let c := nf in
let (nf, b') := cps_rec (nf + 1) b c in
let (nf, r') := cps_rec nf r cnt in
(nf, CT.LetF (CT.Fnt n c a b') r')
| ST.App f t =>
let ct := nf in
let ta := nf + 1 in
let af := nf + 2 in
let bt := CT.AppF (CT.Var af) cnt (CT.Var ta) in (* Once f and t have been computer, we call f *)
let cntt := CT.Cnt1 ct ta bt in
let (nf, t') := cps_rec (nf + 3) t ct in
let cf := nf in
let bf := CT.LetC cntt t' in (* Once we are done computing f, we compute t *)
let cntf := CT.Cnt1 cf af bf in
let (nf, f') := cps_rec (nf + 1) f cf in
let res := CT.LetC cntf f' in
(nf, res)
| ST.In =>
let res := CT.LetIn nf (CT.AppC1 cnt (CT.Var nf)) in
(nf + 1, res)
| ST.Out t =>
let c := nf in
let a := nf + 1 in
let n := nf + 2 in
let b := CT.LetOut n (CT.Var a) (CT.AppC1 cnt (CT.Var n)) in
let (nf, t') := cps_rec (nf + 3) t c in
let res := CT.LetC (CT.Cnt1 c a b) t' in
(nf, res)
| ST.Ite c t e =>
let ct := nf in
let (nf, bt) := cps_rec (nf + 1) t cnt in
let cntt := CT.Cnt0 ct bt in
let ce := nf in
let (nf, be) := cps_rec (nf + 1) e cnt in
let cnte := CT.Cnt0 ce be in
let cc := nf in
let ac := nf + 1 in
let bc := CT.LetC cntt (CT.LetC cnte (CT.Ite (CT.Var ac) ct ce)) in
let cntc := CT.Cnt1 cc ac bc in
let (nf, c') := cps_rec (nf + 2) c cc in
let res := CT.LetC cntc c' in
(nf, res)
| ST.BinaryOp op t1 t2 =>
let c2 := nf in
let a2 := nf + 1 in
let a1 := nf + 2 in
let n := nf + 3 in
let b2 := CT.LetB n op (CT.Var a1) (CT.Var a2) (CT.AppC1 cnt (CT.Var n)) in
let cnt2 := CT.Cnt1 c2 a2 b2 in
let (nf, t2') := cps_rec (nf + 4) t2 c2 in
let c1 := nf in
let b1 := CT.LetC cnt2 t2' in
let cnt1 := CT.Cnt1 c1 a1 b1 in (* When t1 is computed, we compute t2 *)
let (nf, t1') := cps_rec (nf + 1) t1 c1 in
let res := CT.LetC cnt1 t1' in
(nf, res)
| ST.UnaryOp op t =>
let c := nf in
let a := nf + 1 in
let n := nf + 2 in
let b := CT.LetU n op (CT.Var a) (CT.AppC1 cnt (CT.Var n)) in
let cntt := CT.Cnt1 c a b in
let (nf, t') := cps_rec (nf + 3) t c in
let res := CT.LetC cntt t' in
(nf, res)
| ST.Match s (la, lt) (ra, rt) =>
let cl := nf in
let (nf, lt') := cps_rec (nf + 1) lt cnt in
let cntl := CT.Cnt1 cl la lt' in
let cr := nf in
let (nf, rt') := cps_rec (nf + 1) rt cnt in
let cntr := CT.Cnt1 cr ra rt' in
let cs := nf in
let sa := nf + 1 in
let sb := CT.LetC cntl (CT.LetC cntr (CT.Match (CT.Var sa) cl cr)) in
let cnts := CT.Cnt1 cs sa sb in
let (nf, s') := cps_rec (nf + 2) s cs in
let res := CT.LetC cnts s' in
(nf, res)
end.
Create HintDb cps.
Ltac cps_rec_nf_monotone_ind IH :=
match goal with
| H : cps_rec ?nf ?t ?c = (?nf', ?t') |- _ =>
eapply IH in H; auto with lia
end.
Lemma cps_rec_nf_monotone_size : forall n t cnt nf nf' t', ST.size t < n ->
cps_rec nf t cnt = (nf', t') -> nf <= nf'.
Proof with eauto with lia.
induction n, t...
all: repeat reduce || destruct_match || cps_rec_nf_monotone_ind IHn...
Qed.
Lemma cps_rec_nf_monotone : forall nf t cnt nf' t',
cps_rec nf t cnt = (nf', t') -> nf <= nf'.
Proof.
eauto using cps_rec_nf_monotone_size.
Qed.
#[global]
Hint Resolve cps_rec_nf_monotone : cps.
Ltac cps_rec_nf_correct_ind IH :=
match goal with
| H : cps_rec ?nf ?t ?c = (?nf', ?t') |- _ =>
pose proof (cps_rec_nf_monotone _ _ _ _ _ H);
eapply IH in H; auto with lia; [idtac]
end.
Opaque Nat.max.
Lemma cps_rec_nf_correct_size : forall n t cnt nf nf' t', ST.size t < n ->
ST.next_free t <= nf -> cnt < nf ->
cps_rec nf t cnt = (nf', t') -> CT.next_free t' <= nf'.
Proof with auto with lia cps.
induction n, t; repeat reduce || simpl_lia.
all: try solve [
repeat destruct_match;
repeat cps_rec_nf_correct_ind IHn || simpl_lia || invert_constr;
unfold CT.next_free; fold CT.next_free; unfold CT.nf_atom;
repeat apply max_le || split; auto with lia].
Qed.
Lemma cps_rec_nf_correct : forall nf t cnt nf' t',
ST.next_free t <= nf -> cnt < nf ->
cps_rec nf t cnt = (nf', t') -> CT.next_free t' <= nf'.
Proof.
eauto using cps_rec_nf_correct_size.
Qed.
#[global]
Hint Resolve cps_rec_nf_correct : cps.
Definition cps nf t :=
let c := nf in
let a := nf + 1 in
let b := CT.Halt (CT.Var a) in
let cnt := CT.Cnt1 c a b in
let (_, t') := cps_rec (nf + 2) t c in
CT.LetC cnt t'.
Fixpoint cpsᵥ (nf : nat) (v : SV.value) {struct v} : nat * CV.value :=
match v with
| SV.Lit l => (nf, CV.Lit l)
| SV.Tuple v1 v2 =>
let (nf, v1') := cpsᵥ nf v1 in
let (nf, v2') := cpsᵥ nf v2 in
(nf, CV.Tuple v1' v2')
| SV.Left v =>
let (nf, v') := cpsᵥ nf v in
(nf, CV.Left v')
| SV.Right v =>
let (nf, v') := cpsᵥ nf v in
(nf, CV.Right v')
| SV.Fun (ST.Fnt fname farg fbody) env =>
let fix cps_rec_v_env nf env :=
match env with
| nil => (nf, nil)
| (n, v) :: env =>
let (nf, v') := cpsᵥ nf v in
let (nf, env) := cps_rec_v_env nf env in
(nf, (n, v') :: env)
end in
let (nf, env) := cps_rec_v_env nf env in
let c := nf in
let (nf, fbody) := cps_rec (nf + 1) fbody c in
(nf, CV.Fun (CT.Fnt fname c farg fbody) env)
end.
(* Definition equivᵥ v1 v2 := exists e, v1 = renameᵥ e v2.
Lemma cps_V_equiv' : forall v nf1 nf2,
let (nf1', v1) := cpsᵥ nf1 v in
let (nf2', v2) := cpsᵥ nf2 v in
exists e, (e = { } \/ (min e <= nf2 /\ nf2' < max e)) /\ v1 = renameᵥ e v2.
Proof.
induction v; repeat reduce || destruct_match.
- eexists; reduce.
- pose proof (IHv1 nf1 nf2).
pose proof (IHv2 n2 n1).
repeat reduce || destruct_match || destruct_and_H || destruct_or_H.
* eexists; reduce.
* exists x.
reduce. *)
Lemma cps_v_equiv : forall v nf1 nf2,
let (_, v1) := cpsᵥ nf1 v in
let (_, v2) := cpsᵥ nf2 v in
equivᵥ nf1 v1 v2.
Proof.
induction v; repeat reduce || destruct_match.
- eexists; reduce.
- pose proof (IHv1 nf1 nf2).
pose proof (IHv2 n2 n1).
repeat reduce || destruct_match.
unfold equivᵥ in H, H0.
repeat destruct_exist_H || destruct_and_H.
repeat destruct_or_H; subst.
* exists { }.
repeat rewrite rename_v_empty in *.
reduce.
*
Lemma cps_v_equiv : forall v nf1 nf2,
let (_, v1) := cpsᵥ nf1 v in
let (_, v2) := cpsᵥ nf2 v in
v1 ≡ᵥ v2.
Proof with eauto with equiv_cps.
induction v; repeat reduce || destruct_match...
- (* Tuple *)
specialize (IHv1 nf1 nf2).
specialize (IHv2 nf1 nf2).
repeat destruct_match || destruct_exist_H || reduce.
Fixpoint cps_envᵥ (nf : nat) (env : env SV.value) :=
match env with
| nil => (nf, nil)
| (n, v)::env =>
let (nf', v') := cpsᵥ nf v in
let (nf'', env') := cps_envᵥ nf' env in
(nf'', (n, v')::env')
end.
Lemma cps_env_keep_elem : forall env nf1 nf2 n v,
env ? n = Some v ->
let (_, env') := cps_envᵥ nf1 env in
let (_, v2) := cpsᵥ nf2 v in
exists v1 k,
env' ? n = Some v1 /\ v1 ≡ᵥ v2 @ k.
Proof.
induction env.
- (* nil *)
repeat reduce.
- destruct a; repeat reduce || destruct_match.
+ exists v.
Theorem cps_rec_correct : forall f f' t v io env io',
evalₛ f env t io = (Rval v, io', f') -> forall nf c a b cenvV cenvC,
ST.next_free_env env <= nf -> ST.next_free t <= nf ->
c < nf -> a < nf -> CT.next_free b <= nf ->
CV.next_free_envV cenvV <= nf -> CV.next_free_envC cenvC <= nf ->
let cnt := Cnt (Cnt1 c a b) cenvV cenvC in
let (nf', t') := cps_rec nf t c in
let (nf'', v') := cpsᵥ nf' v in
let (_, envV) := cps_envᵥ nf'' env in
forall f1 envC,
let (r1, io1) := evalₜ f1 envV (envC + (c, cnt)) t' io in
exists f2 k,
let (r2, io2) := evalₜ f2 (envV + (a, v')) (envC + (c, cnt)) b io in
io1 = io2 /\ r1 ≡ᵣ r2 @ k.
Proof.
induction f, t; inversion 1; repeat reduce || destruct_match.
- (* Var n *)
destruct f1 eqn:F; repeat reduce.
+ exists 0, 0; repeat reduce; auto with equiv_cps.
+ enough (c =? c = true).
rewrite H in *.
autorewrite*.
(*
Theorem cps_rec_correct_timeout : forall f t io env io', 0 < f ->
evalₛ f env t io = (SV.Rtimeout, io') -> forall nf cnt ca cb envV envC,
ST.next_free t <= nf -> next_free_env env <= nf -> cnt < nf ->
let (nf', env') := cps_envᵥ nf env in
let (_, t') := cps_rec nf' t cnt in
exists f', 0 < f' ->
evalₜ f' env' (empty + (cnt, Cnt (Cnt1 cnt ca cb) envV envC)) t' io = (Rtimeout, io').
Proof.
induction f, t; try lia.
all: repeat reduce || destruct_match || simpl_lia.
-
all: eexists.
Theorem cps_correct_ind : forall t v io env f io',
evalₛ f env t io = (Rval v, io') ->
ST.next_free t <= nf -> cnt < nf ->
Theorem cps_correct : forall t v io env f io',
let nf := max (next_free t) (max (next_free_env env) (next_freeᵥ v)) in
{ io | env } t ~>(f) { Rval v, io' } ->
exists v' f', snd (cpsᵥ nf v) ≡ᵥ v' /\
{ io | (snd (cps_envᵥ nf env), empty) } snd (cps nf t) ~>(f') { Rhalt v', io' }.
Proof.
intros.
induction H; simpl. *) |
Preparations are moving fast for the near net zero energy retrofit of 5 homes in Maldon, Essex, owned by social housing provider Moat. This will be the first UK pilot using the innovative Energiesprong model to be supported by E=0 project funding from the European Union. Preferred bidder ENGIE has just received the results of a detailed technical survey, so will now confirm the price of the work and help detail the ‘comfort plan’ to be offered to residents. Planning applications went in at the start of June.
Moat owns 34 semi-detached properties on Mundon Road, interspersed with privately owned homes bought under the UK ‘right to buy’ scheme. Potential participants have been shortlisted and now 4 or 5 are ready to proceed. Those that didn’t wish to participate mentioned reasons like intending to buy the property and owning a wood stove, which they wished to keep. Shortlisted households have higher than average energy bills and this is a very different group of residents to the Nottingham Energiesprong pilot earlier this year, including more multiple occupancy homes.
“The project is exciting and the finished result looks really smart but the best bit has to be the expected savings on energy costs”.
The presentations introduced ENGIE, shared examples from the UK Nottingham City pilot and presented the designs for the Maldon pilot by Gardner Stewart Architects. Ms Edwards, a resident attending the event, commented “The project is exciting and the finished result looks really smart but the best bit has to be the expected savings on energy costs”.
The proposed design uses a Mauer pre-fabricated, super insulated facade with a lightweight brick effect finish, triple glazed windows and high-performance doors. The architects and ENGIE visited the Mauer factory and were impressed with their versatile solution. Adding brick slips would add more weight, so this textured brick effect offers an advantage assuming the residents and planners like it.
The new highly insulated roof panel will come with integrated PV solar panels. New dormers with double glazed windows will be fitted to the front as planning requires them to be kept. Cement tiles will be fitted to give a consistent look. The redundant brick chimney will be capped and sealed.
A conditioned indoor climate (heating and ventilation) is proposed to be provided by a compact fully integrated Factory Zero energy module on each property. For the pilot, this will contain an air source heat pump, hot water tank, PV inverter and mechanical ventilation unit. The on-board monitoring kit will provide real time measurements at suitable levels of detail for keeping the energy supplier, landlord and occupant informed. The energy module will be sited on the back or side of the house so that the equipment inside it can be maintained without disturbing the residents.
Recent technical surveys covered a structural assessment of the pilot properties. This process established if the walls are strong enough to bolt on external wall panels. Without the required strength a trench would need to be dug and filled to provide a foundation to sit the panels on. The survey also looked at the roof to see if it is strong enough to support solar PV, plus whether there was any potential asbestos in the property to avoid. It looked at drains and cables in the ground to reveal if any could be problematic for the plans. It also looked at fine detail such as any impact the new facades might have on the opening of doors, especially in corners.
The final energy performance will be near net zero. This is largely driven by the fact that the whole roof will not be covered with solar. The energy performance of the homes is set to be guaranteed for 30 years, split into 10 year periods, assuring long term comfort and affordable warmth for Moat’s customers.
For more, see Energiesprong UK. |
module Graph
import Data.Vect
import Lemmas
%default total
||| 'Graph n' is the type of undirected graphs with no parallel edges and no self-loops with 'n' vertices.
||| Vertex '0' corresponds to the innermost AddVertex call in the graph expression.
||| Vertex '1' corresponds to the penultimate AddVertex call in the graph expression.
||| ...
||| Vertex 'n-1' corresponds to the outermost AddVertex call in the graph expression.
||| The second argument of AddVertex is a Vect of Bools, where the 'i'-th entry indicates whether
||| the current vertex should be connected to the 'i'-th vertex of the graph.
public export
data Graph : Nat -> Type where
Empty : Graph 0
AddVertex : Graph n -> Vect n Bool -> Graph (S n)
||| The complete graph on 'n' vertices.
export
completeGraph : (n : Nat) -> Graph n
completeGraph 0 = Empty
completeGraph (S k) = AddVertex (completeGraph k) (replicate k True)
||| The graph with one vertex. Same as 'completeGraph 1'.
export
singletonGraph : Graph 1
singletonGraph = AddVertex Empty []
||| A convenient representation of a graph cut.
||| The 'i'-th entry indicates the color of the 'i'-th vertex in the cut.
public export
Cut : Nat -> Type
Cut n = Vect n Bool
||| Helper function fot sizeCut
|||
||| color -- Color of the current vertex
||| cut -- Colors of the other vertices
||| edges -- Vect of edges between the current vertex and the others
||| output -- Number of edges between the current vertex and the other vertices of a different color
sizeCut' : (color : Bool) -> (cut : Vect n Bool) -> (edges : Vect n Bool) -> Nat
sizeCut' _ [] [] = 0
sizeCut' True (False :: cut) (True :: edges) = S (sizeCut' True cut edges)
sizeCut' False (True :: cut) (True :: edges) = S (sizeCut' False cut edges)
sizeCut' color (_::cut) (_::edges) = sizeCut' color cut edges
||| Compute the size of a cut of a graph.
|||
||| graph -- The input graph of the problem
||| cut -- The given cut
||| output -- The size of the cut
export
sizeCut : (graph : Graph n) -> (cut : Cut n) -> Nat
sizeCut Empty [] = 0
sizeCut (AddVertex graph edges) cut =
let x = last cut
smaller_cut = init cut
in sizeCut' x smaller_cut edges + sizeCut graph smaller_cut
||| Find the best cut of a graph among a vector of cuts (or the trivial cut if the vector is []).
|||
||| n -- The size of the input graph of the problem
||| graph -- The input graph of the problem
||| cuts -- Vector of cuts
||| output -- The best cut from the vector and its size
export
bestCut : {n : Nat} -> (graph : Graph n) -> (cuts : Vect k (Cut n)) -> (Cut n, Nat)
bestCut graph [] = (replicate n True, 0)
bestCut graph (cut::cuts) =
let (best, size) = bestCut graph cuts
s = sizeCut graph cut
in if s >= size then (cut, s) else (best,size)
|
= Geopyxis carbonaria =
|
{-# OPTIONS --without-K --safe #-}
module Definition.Typed.Consequences.NeTypeEq where
open import Definition.Untyped
open import Definition.Typed
open import Definition.Typed.Consequences.Syntactic
open import Definition.Typed.Consequences.Injectivity
open import Definition.Typed.Consequences.Substitution
open import Tools.Product
import Tools.PropositionalEquality as PE
-- Helper function for the same variable instance of a context have equal types.
varTypeEq′ : ∀ {n R T Γ} → n ∷ R ∈ Γ → n ∷ T ∈ Γ → R PE.≡ T
varTypeEq′ here here = PE.refl
varTypeEq′ (there n∷R) (there n∷T) rewrite varTypeEq′ n∷R n∷T = PE.refl
-- The same variable instance of a context have equal types.
varTypeEq : ∀ {x A B Γ} → Γ ⊢ A → Γ ⊢ B → x ∷ A ∈ Γ → x ∷ B ∈ Γ → Γ ⊢ A ≡ B
varTypeEq A B x∷A x∷B rewrite varTypeEq′ x∷A x∷B = refl A
-- The same neutral term have equal types.
neTypeEq : ∀ {t A B Γ} → Neutral t → Γ ⊢ t ∷ A → Γ ⊢ t ∷ B → Γ ⊢ A ≡ B
neTypeEq (var x) (var x₁ x₂) (var x₃ x₄) =
varTypeEq (syntacticTerm (var x₃ x₂)) (syntacticTerm (var x₃ x₄)) x₂ x₄
neTypeEq (∘ₙ neT) (t∷A ∘ⱼ t∷A₁) (t∷B ∘ⱼ t∷B₁) with neTypeEq neT t∷A t∷B
... | q = let w = proj₂ (injectivity q)
in substTypeEq w (refl t∷A₁)
neTypeEq (natrecₙ neT) (natrecⱼ x t∷A t∷A₁ t∷A₂) (natrecⱼ x₁ t∷B t∷B₁ t∷B₂) =
refl (substType x₁ t∷B₂)
neTypeEq x (conv t∷A x₁) t∷B = let q = neTypeEq x t∷A t∷B
in trans (sym x₁) q
neTypeEq x t∷A (conv t∷B x₃) = let q = neTypeEq x t∷A t∷B
in trans q x₃
|
(*
Title: Quantales with Converse
Author: Cameron Calk, Georg Struth
Maintainer: Georg Struth <g.struth at sheffield.ac.uk>
*)
section \<open>Quantales with Converse\<close>
theory Quantale_conv
imports Modal_Quantale MKA_conv
begin
subsection \<open>Involutive quantales\<close>
text \<open>The following axioms for involutive quantales are standard.\<close>
class involutive_quantale = quantale + invol_op +
assumes inv_invol: "(x\<^sup>\<circ>)\<^sup>\<circ> = x"
and inv_contrav: "(x \<cdot> y)\<^sup>\<circ> = y\<^sup>\<circ> \<cdot> x\<^sup>\<circ>"
and inv_sup: "(\<Squnion>X)\<^sup>\<circ> = \<Squnion>{x\<^sup>\<circ> |x. x \<in> X}"
context involutive_quantale
begin
lemma inv_iso: "x \<le> y \<Longrightarrow> x\<^sup>\<circ> \<le> y\<^sup>\<circ>"
by (smt (verit, ccfv_SIG) insertI1 insertI2 local.Sup_upper local.inv_sup local.sup.absorb1 local.sup_Sup mem_Collect_eq)
lemma inv_binsup: "(x \<squnion> y)\<^sup>\<circ> = x\<^sup>\<circ> \<squnion> y\<^sup>\<circ>"
apply (rule order.antisym)
apply (metis local.inv_invol local.inv_iso local.sup.cobounded1 local.sup.cobounded2 qdual.qd.add_least)
by (simp add: local.inv_iso)
end
sublocale involutive_quantale \<subseteq> invqka: involutive_kleene_algebra invol "1" "(\<cdot>)" "(\<squnion>)" "\<bottom>" "(\<le>)" "(<)" qstar
by (unfold_locales, simp_all add: local.inv_contrav inv_binsup inv_invol)
context involutive_quantale
begin
lemma inv_binf [simp]: "(x \<sqinter> y)\<^sup>\<circ> = x\<^sup>\<circ> \<sqinter> y\<^sup>\<circ>"
proof-
{fix z
have "(z \<le> (x \<sqinter> y)\<^sup>\<circ>) = (z\<^sup>\<circ> \<le> x \<sqinter> y)"
using invqka.inv_adj by blast
also have "\<dots> = (z\<^sup>\<circ> \<le> x \<and> z\<^sup>\<circ> \<le> y)"
by simp
also have "\<dots> = (z \<le> x\<^sup>\<circ> \<and> z \<le> y\<^sup>\<circ>)"
by (simp add: invqka.inv_adj)
also have "\<dots> = (z \<le> x\<^sup>\<circ> \<sqinter> y\<^sup>\<circ>)"
by simp
finally have "(z \<le> (x \<sqinter> y)\<^sup>\<circ>) = (z \<le> x\<^sup>\<circ> \<sqinter> y\<^sup>\<circ>)".}
thus ?thesis
using local.dual_order.antisym by blast
qed
lemma inv_inf [simp]: "(\<Sqinter>X)\<^sup>\<circ> = \<Sqinter>{x\<^sup>\<circ> |x. x \<in> X}"
apply (rule order.antisym)
using invqka.inv_adj local.Inf_lower local.le_Inf_iff apply auto[1]
by (metis (mono_tags, lifting) invqka.inv_adj local.Inf_greatest local.Inf_lower mem_Collect_eq)
lemma inv_top [simp]: "\<top>\<^sup>\<circ> = \<top>"
proof-
have a: "\<top>\<^sup>\<circ> \<le> \<top>"
by simp
hence "(\<top>\<^sup>\<circ>)\<^sup>\<circ> \<le> \<top>\<^sup>\<circ>"
using local.inv_iso by blast
hence "\<top> \<le> \<top>\<^sup>\<circ>"
by simp
thus ?thesis
by (simp add: local.top_le)
qed
lemma inv_qstar_aux [simp]: "(x^i)\<^sup>\<circ> = (x\<^sup>\<circ>) ^ i"
apply (induct i)
using local.inv_contrav local.power_Suc2 by auto
lemma inv_conjugate: "(x\<^sup>\<circ> \<sqinter> y = \<bottom>) = (x \<sqinter> y\<^sup>\<circ> = \<bottom>)"
using inv_binf invqka.inv_zero by fastforce
definition "do x = 1 \<sqinter> (x \<cdot> x\<^sup>\<circ>)"
definition "cd x = 1 \<sqinter> (x\<^sup>\<circ> \<cdot> x)"
lemma do_inv: "do (x\<^sup>\<circ>) = cd x"
proof-
have "do (x\<^sup>\<circ>) = 1 \<sqinter> (x\<^sup>\<circ> \<cdot> (x\<^sup>\<circ>)\<^sup>\<circ>)"
by (simp add: do_def)
also have "\<dots> = 1 \<sqinter> (x\<^sup>\<circ> \<cdot> x)"
by simp
also have "\<dots> = cd x"
by (simp add: cd_def)
finally show ?thesis.
qed
lemma cd_inv: "cd (x\<^sup>\<circ>) = do x"
by (simp add: cd_def do_def)
lemma do_le_top: "do x \<le> 1 \<sqinter> (x \<cdot> \<top>)"
using do_def local.inf_mono local.order_refl local.top_greatest qdual.qd.mult_iso by presburger
lemma do_subid: "do x \<le> 1"
by (simp add: do_def)
lemma do_bot [simp]: "do \<bottom> = \<bottom>"
by (simp add: do_def)
lemma do_iso: "x \<le> y \<Longrightarrow> do x \<le> do y"
using do_def local.eq_refl local.inf_mono local.inv_iso qdual.qd.dd.mult_iso by presburger
lemma do_subdist: "do x \<squnion> do y \<le> do (x \<squnion> y)"
proof-
have "do x \<le> do (x \<squnion> y)" and "do y \<le> do (x \<squnion> y)"
by (simp_all add: do_iso)
thus ?thesis
by simp
qed
lemma inv_do [simp]: "(do x)\<^sup>\<circ> = do x"
by (simp add: do_def)
lemma inv_cd [simp]: "(cd x)\<^sup>\<circ> = cd x"
by (metis do_inv inv_do)
text \<open>The strong Gelfand property (name by Palmigiano and Re) is important for dioids and Kleene algebras.\<close>
lemma strong_gelfand: "x \<le> x \<cdot> x\<^sup>\<circ> \<cdot> x"
nitpick (* counterexample *)
oops
text \<open>The modular law is a convenient axiom for relational quantales, in a setting where the underlying
lattice is not boolean.\<close>
lemma modular_law: "(x \<cdot> y) \<sqinter> z \<le> (x \<sqinter> (z \<cdot> y\<^sup>\<circ>)) \<cdot> y"
nitpick (* counterexample *)
oops
lemma dedekind: "(x \<cdot> y) \<sqinter> z \<le> (x \<sqinter> (z \<cdot> y\<^sup>\<circ>)) \<cdot> (y \<sqinter> (x\<^sup>\<circ> \<cdot> z))"
nitpick (* counterexample *)
oops
end
sublocale commutative_quantale \<subseteq> ciq: involutive_quantale id _ _ _ _ _ _ _ _ _ _
by (unfold_locales, simp_all add: mult_commute)
class distributive_involutive_quantale = involutive_quantale + distributive_quantale
class boolean_involutive_quantale = involutive_quantale + boolean_quantale
class quantale_converse = involutive_quantale +
assumes strong_gelfand: "x \<le> x \<cdot> x\<^sup>\<circ> \<cdot> x"
begin
lemma modular_law: "(x \<cdot> y) \<sqinter> z \<le> (x \<sqinter> (z \<cdot> y\<^sup>\<circ>)) \<cdot> y"
nitpick (* counterexample *)
oops
lemma peirce_1: "(x \<cdot> y) \<sqinter> z\<^sup>\<circ> = \<bottom> \<Longrightarrow> (y \<cdot> z) \<sqinter> x\<^sup>\<circ> = \<bottom>"
nitpick (* counterexample *)
oops
lemma dedekind: "(x \<cdot> y) \<sqinter> z \<le> (x \<sqinter> (z \<cdot> y\<^sup>\<circ>)) \<cdot> (y \<sqinter> (x\<^sup>\<circ> \<cdot> z))"
nitpick (* counterexample *)
oops
lemma do_gelfand [simp]: "do x \<cdot> do x \<cdot> do x = do x"
apply (rule order.antisym)
apply (metis local.do_def local.inf.cobounded1 local.mult_1_right qdual.qd.mult_iso qdual.qd.mult_isor)
by (metis local.inv_do local.strong_gelfand)
lemma cd_gelfand [simp]: "cd x \<cdot> cd x \<cdot> cd x = cd x"
by (metis do_gelfand local.do_inv)
lemma do_idem [simp]: "do x \<cdot> do x = do x"
proof (rule order.antisym)
show a: "do x \<cdot> do x \<le> do x"
using local.do_subid qdual.qd.mult_isor by fastforce
have "do x = do x \<cdot> do x \<cdot> do x"
by simp
thus "do x \<le> do x \<cdot> do x"
by (metis a qdual.qd.mult_isol)
qed
lemma cd_idem: "cd x \<cdot> cd x = cd x"
by (metis do_idem local.do_inv)
lemma dodo [simp]: "do (do x) = do x"
proof-
have "do (do x) = 1 \<sqinter> (do x \<cdot> do x)"
using local.do_def local.inv_do by force
also have "\<dots> = 1 \<sqinter> do x"
by simp
also have "\<dots> = do x"
by (simp add: local.do_def)
finally show ?thesis.
qed
lemma cdcd: "cd (cd x) = cd x"
using cd_idem local.cd_def local.inv_cd by force
lemma docd_compat [simp]: "do (cd x) = cd x"
proof-
have "do (cd x) = do (do (x\<^sup>\<circ>))"
by (simp add: local.do_inv)
also have "\<dots> = do (x\<^sup>\<circ>)"
by simp
also have "\<dots> = cd x"
by (simp add: local.do_inv)
finally show ?thesis.
qed
lemma cddo_compat [simp]: "cd (do x) = do x"
by (metis docd_compat local.cd_inv local.inv_do)
lemma "do x = 1 \<sqinter> (x \<cdot> \<top>)"
nitpick
oops
end
sublocale quantale_converse \<subseteq> convqka: kleene_algebra_converse invol "1" "(\<cdot>)" "(\<squnion>)" "\<bottom>" "(\<le>)" "(<)" qstar
by (unfold_locales, simp add: local.strong_gelfand)
class dedekind_quantale = involutive_quantale +
assumes modular_law: "(x \<cdot> y) \<sqinter> z \<le> (x \<sqinter> (z \<cdot> y\<^sup>\<circ>)) \<cdot> y"
subsection \<open>Dedekind quantales\<close>
sublocale dedekind_quantale \<subseteq> convdqka: kleene_algebra_converse invol "1" "(\<cdot>)" "(\<squnion>)" "\<bottom>" "(\<le>)" "(<)" qstar
by (unfold_locales, metis local.inf.absorb2 local.le_top local.modular_law local.top_greatest)
context dedekind_quantale
begin
subclass quantale_converse
apply unfold_locales
by (simp add: local.convdqka.strong_gelfand)
lemma modular_2 [simp]: "((x \<sqinter> (z \<cdot> y\<^sup>\<circ>)) \<cdot> y) \<sqinter> z = (x \<cdot> y) \<sqinter> z"
by (meson local.inf.cobounded1 local.inf_le2 local.inf_mono local.le_infI local.modular_law local.order_eq_iff qdual.qd.mult_iso)
lemma modular_1 [simp]: "(x \<cdot> (y \<sqinter> (x\<^sup>\<circ> \<cdot> z))) \<sqinter> z = (x \<cdot> y) \<sqinter> z"
by (metis local.inv_binf local.inv_contrav local.inv_invol modular_2)
lemma dedekind: "(x \<cdot> y) \<sqinter> z \<le> (x \<sqinter> (z \<cdot> y\<^sup>\<circ>)) \<cdot> (y \<sqinter> (x\<^sup>\<circ> \<cdot> z))"
by (smt (verit, ccfv_threshold) local.inf_commute local.inv_binf local.inv_contrav local.inv_invol local.modular_law modular_1)
lemma modular3: "(x \<cdot> y) \<sqinter> z \<le> x \<cdot> (y \<sqinter> (x\<^sup>\<circ> \<cdot> z))"
by (metis local.inf.cobounded1 modular_1)
lemma peirce: "((x \<cdot> y) \<sqinter> z\<^sup>\<circ> = \<bottom>) = ((y \<cdot> z) \<sqinter> x\<^sup>\<circ> = \<bottom>)"
by (metis local.bot_annil local.inf.commute local.inf_bot_right local.inv_conjugate local.inv_contrav modular_2)
lemma schroeder_1: "((x \<cdot> y) \<sqinter> z = \<bottom>) = (y \<sqinter> (x\<^sup>\<circ> \<cdot> z) = \<bottom>)"
by (metis local.inf.commute local.inv_conjugate local.inv_contrav local.inv_invol peirce)
lemma schroeder_2: "((x \<cdot> y) \<sqinter> z = \<bottom>) = (x \<sqinter> (z \<cdot> y\<^sup>\<circ>) = \<bottom>)"
by (metis local.bot_annil local.bot_unique local.inf.commute local.inv_invol local.modular_law)
lemma lla_top_aux: "p \<le> 1 \<Longrightarrow> ((x \<le> p \<cdot> x) = (x \<le> p \<cdot> \<top>))"
proof
assume h: "p \<le> 1"
and h1: "x \<le> p \<cdot> x"
thus "x \<le> p \<cdot> \<top>"
using local.order_trans local.top_greatest qdual.qd.mult_isor by blast
next
assume h: "p \<le> 1"
and "x \<le> p \<cdot> \<top>"
hence "x = (p \<cdot> \<top>) \<sqinter> x"
using local.inf.absorb_iff2 by auto
also have "\<dots> \<le> p \<cdot> (\<top> \<sqinter> (p\<^sup>\<circ> \<cdot> x))"
using modular3 by blast
also have "\<dots> = p \<cdot> p \<cdot> x"
by (simp add: h local.convdqka.subid_conv mult_assoc)
finally show "x \<le> p \<cdot> x"
by (metis h local.dual_order.trans local.mult_1_left qdual.qd.mult_isol)
qed
lemma lla: "p \<le> 1 \<Longrightarrow> ((do x \<le> p) = (x \<le> p \<cdot> \<top>))"
apply standard
apply (smt (verit) lla_top_aux local.do_def local.inf.assoc local.inf.cobounded2 local.inf.commute local.inf.idem local.inf.orderE modular_2 qdual.qd.oner)
proof -
assume a1: "x \<le> p \<cdot> \<top>"
assume a2: "p \<le> 1"
have f3: "x \<cdot> \<top> \<le> p \<cdot> \<top> \<cdot> \<top>"
using a1 qdual.qd.dd.mult_iso by auto
have f4: "p \<cdot> do x \<le> p"
by (metis (full_types) local.do_le_top local.inf.bounded_iff local.mult.monoid_axioms local.order.partial_preordering_axioms monoid.right_neutral partial_preordering.refl qdual.qd.dd.mult_iso)
have "x \<cdot> \<top> \<le> p \<cdot> \<top>"
using f3 by (simp add: local.mult.semigroup_axioms semigroup.assoc)
then show "do x \<le> p"
using f4 a2 lla_top_aux local.do_le_top local.inf.bounded_iff local.order_trans by blast
qed
lemma do_top: "do x = 1 \<sqinter> (x \<cdot> \<top>)"
proof-
have "1 \<sqinter> (x \<cdot> \<top>) = 1 \<sqinter> (x \<cdot> (\<top> \<sqinter> x\<^sup>\<circ> \<cdot> 1))"
by (metis local.inf.commute local.inf_top.left_neutral modular_1)
also have "\<dots> = do x"
by (simp add: local.do_def)
finally show ?thesis..
qed
lemma do_absorp: "x \<le> do x \<cdot> x"
proof-
have "x = x \<sqinter> (x \<cdot> 1)"
by simp
also have "\<dots> \<le> (1 \<sqinter> (x \<cdot> x\<^sup>\<circ>)) \<cdot> x"
using local.inf.absorb_iff2 modular_2 by force
also have "\<dots> = do x \<cdot> x"
by (simp add: local.do_def)
finally show ?thesis.
qed
lemma do_absorp_eq [simp]: "do x \<cdot> x = x"
by (metis do_absorp do_subid local.mult_1_left local.order.antisym qdual.qd.mult_isol)
lemma do_top2: "x \<cdot> \<top> = do x \<cdot> \<top>"
proof (rule order.antisym)
have "x \<cdot> \<top> = do x \<cdot> x \<cdot> \<top>"
by simp
also have "\<dots> \<le> do x \<cdot> \<top> \<cdot> \<top>"
using local.order_refl local.top_greatest qdual.qd.mult_iso by presburger
also have "\<dots> = do x \<cdot> \<top>"
by (simp add: local.mult.semigroup_axioms semigroup.assoc)
finally show "x \<cdot> \<top> \<le> do x \<cdot> \<top>".
have "do x \<cdot> \<top> = (1 \<sqinter> (x \<cdot> \<top>)) \<cdot> \<top>"
by (simp add: do_top)
also have "\<dots> \<le> (1 \<cdot> \<top>) \<sqinter> (x \<cdot> \<top> \<cdot> \<top>)"
using qdual.qd.mult_isol by auto
also have "\<dots> = x \<cdot> \<top>"
by (simp add: mult_assoc)
finally show "do x \<cdot> \<top> \<le> x \<cdot> \<top>".
qed
lemma do_local [simp]: "do (x \<cdot> do y) = do (x \<cdot> y)"
proof-
have "do (x \<cdot> do y) = 1 \<sqinter> (x \<cdot> do y \<cdot> \<top>)"
using do_top by force
also have "\<dots> = 1 \<sqinter> (x \<cdot> y \<cdot> \<top>)"
by (metis do_top2 local.qdual.mult_assoc)
also have "\<dots> = do (x \<cdot> y)"
by (simp add: do_top)
finally show ?thesis
by force
qed
lemma do_inf: "do (x \<sqinter> y) = 1 \<sqinter> (y \<cdot> x\<^sup>\<circ>)"
by (smt (z3) do_absorp_eq invqka.inv_one local.do_def local.inf_commute local.inv_binf local.inv_contrav local.inv_invol local.mult_1_right modular_1 modular_2 mult_assoc)
lemma "do (x \<squnion> y) \<le> do x \<squnion> do y"
unfolding do_top
nitpick (* no proof no counterexample *)
oops
lemma
fixes f::"'a \<Rightarrow> 'a" and g::"'a \<Rightarrow> 'a"
assumes f_absorb: "\<forall>x. x \<le> f x \<cdot> x"
and f_local: "\<forall>x y. f (x \<cdot> f y) = f (x \<cdot> y)"
and f_add: "\<forall>x y. f (x \<squnion> y) = f x \<squnion> f y"
and f_subid: "\<forall>x. f x \<le> \<top>"
and f_zero: "f \<bottom> = \<bottom>"
and g_absorb: "\<forall>x. x \<le> g x \<cdot> x"
and g_local: "\<forall>x y. g (x \<cdot> g y) = g (x \<cdot> y)"
and g_add: "\<forall>x y. g (x \<squnion> y) = g x \<squnion> g y"
and g_subid: "\<forall>x. g x \<le> \<top>"
and g_zero: "g \<bottom> = \<bottom>"
shows "f = g"
nitpick[show_all]
oops
end
class distributive_dedekind_quantale = distributive_quantale + dedekind_quantale
begin
text \<open>In distributive modular quantales we can derive all domain axioms.\<close>
lemma do_sup [simp]: "do (x \<squnion> y) = do x \<squnion> do y"
proof-
have "do (x \<squnion> y) = 1 \<sqinter> ((x \<squnion> y) \<cdot> \<top>)"
by (simp add: local.do_top)
also have "\<dots> = 1 \<sqinter> (x \<cdot> \<top> \<squnion> y \<cdot> \<top>)"
by (simp add: qdual.qd.distl)
also have "\<dots> = (1 \<sqinter> (x \<cdot> \<top>)) \<squnion> (1 \<sqinter> (y \<cdot> \<top>))"
by (simp add: local.inf_sup_distrib1)
also have "\<dots> = do x \<squnion> do y"
by (simp add: local.do_top)
finally show ?thesis.
qed
lemma
fixes f::"'a \<Rightarrow> 'a" and g::"'a \<Rightarrow> 'a"
assumes f_absorb: "\<forall>x. x \<le> f x \<cdot> x"
and f_local: "\<forall>x y. f (x \<cdot> f y) = f (x \<cdot> y)"
and f_add: "\<forall>x y. f (x \<squnion> y) = f x \<squnion> f y"
and f_subid: "\<forall>x. f x \<le> \<top>"
and f_zero: "f \<bottom> = \<bottom>"
and g_absorb: "\<forall>x. x \<le> g x \<cdot> x"
and g_local: "\<forall>x y. g (x \<cdot> g y) = g (x \<cdot> y)"
and g_add: "\<forall>x y. g (x \<squnion> y) = g x \<squnion> g y"
and g_subid: "\<forall>x. g x \<le> \<top>"
and g_zero: "g \<bottom> = \<bottom>"
shows "f = g"
nitpick[show_all]
oops
end
sublocale distributive_dedekind_quantale \<subseteq> modal_kleene_algebra "1" "(\<cdot>)" "(\<squnion>)" "\<bottom>" "(\<le>)" "(<)" qstar cd do
apply unfold_locales
apply (simp add: local.cd_def local.inf.absorb_iff2)
apply (metis local.do_inv local.do_local local.inv_contrav local.inv_do)
apply (metis local.do_inv local.do_sup local.inv_binsup)
apply (simp add: local.cd_def)+
apply (simp add: local.do_top local.inf_sup_distrib1 qdual.qd.distl)
by (simp_all add: local.do_subid)
class boolean_dedekind_quantale = boolean_quantale + dedekind_quantale
begin
lemma inv_neg: "(-x)\<^sup>\<circ> = -(x\<^sup>\<circ>)"
by (metis invqka.inv_sup invqka.inv_zero local.compl_unique local.inf_compl_bot local.inv_binf local.inv_top local.sup_compl_top)
lemma residuation: "x\<^sup>\<circ> \<cdot> -(x \<cdot> y) \<le> -y"
using local.compl_le_swap1 local.inf_compl_bot local.inf_shunt local.schroeder_1 by blast
end
lemma (in involutive_quantale) dedekind_modular:
assumes "(x \<cdot> y) \<sqinter> z \<le> (x \<sqinter> (z \<cdot> y\<^sup>\<circ>)) \<cdot> (y \<sqinter> (x\<^sup>\<circ> \<cdot> z))"
shows "(x \<cdot> y) \<sqinter> z \<le> (x \<sqinter> (z \<cdot> y\<^sup>\<circ>)) \<cdot> y"
using assms local.inf_le1 local.order_trans qdual.qd.mult_isor by blast
lemma (in distributive_involutive_quantale) schroeder_modular:
assumes "\<forall>x y z. ((x \<cdot> y) \<sqinter> z = \<bottom>) = (y \<sqinter> (x\<^sup>\<circ> \<cdot> z) = \<bottom>)"
and "\<forall>x y z. ((x \<cdot> y) \<sqinter> z = \<bottom>) = (x \<sqinter> (z \<cdot> y\<^sup>\<circ>) = \<bottom>)"
and "((x \<cdot> y) \<sqinter> z\<^sup>\<circ> = \<bottom>) = ((y \<cdot> z) \<sqinter> x\<^sup>\<circ> = \<bottom>)"
shows "\<forall>x y z. (x \<cdot> y) \<sqinter> z \<le> (x \<sqinter> (z \<cdot> y\<^sup>\<circ>)) \<cdot> y"
nitpick (* counterexample *)
oops
lemma (in involutive_quantale)
assumes "\<forall>x y z w. (y \<sqinter> (z \<cdot> x\<^sup>\<circ>) \<le> w \<longrightarrow> (y \<cdot> x) \<sqinter> z \<le> w \<cdot> x)"
shows "\<forall>x y z. (x \<cdot> y) \<sqinter> z \<le> (x \<sqinter> (z \<cdot> y\<^sup>\<circ>)) \<cdot> y"
using assms by blast
lemma (in involutive_quantale)
assumes "\<forall>x y z. (x \<cdot> y) \<sqinter> z \<le> (x \<sqinter> (z \<cdot> y\<^sup>\<circ>)) \<cdot> y"
shows "\<forall>w x y z. (y \<sqinter> (z \<cdot> x\<^sup>\<circ>) \<le> w \<longrightarrow> (y \<cdot> x) \<sqinter> z \<le> w \<cdot> x)"
using assms local.order_trans qdual.qd.mult_isol by blast
lemma (in boolean_involutive_quantale) res_peirce:
assumes "\<forall>x y. x\<^sup>\<circ> \<cdot> -(x \<cdot> y) \<le> -y"
shows "((x \<cdot> y) \<sqinter> z\<^sup>\<circ> = \<bottom>) = ((y \<cdot> z) \<sqinter> x\<^sup>\<circ> = \<bottom>)"
proof
assume "(x \<cdot> y) \<sqinter> z\<^sup>\<circ> = \<bottom>"
hence "z\<^sup>\<circ> \<le> -(x \<cdot> y)"
by (simp add: local.inf.commute local.inf_shunt)
thus "(y \<cdot> z) \<sqinter> x\<^sup>\<circ> = \<bottom>"
by (metis assms local.dual_order.trans local.inf_shunt local.inv_conjugate local.inv_contrav local.inv_invol qdual.qd.mult_isor)
next
assume "(y \<cdot> z) \<sqinter> x\<^sup>\<circ> = \<bottom>"
hence "x\<^sup>\<circ> \<le> -(y \<cdot> z)"
using local.compl_le_swap1 local.inf_shunt by blast
thus "(x \<cdot> y) \<sqinter> z\<^sup>\<circ> = \<bottom>"
by (smt (verit, ccfv_SIG) assms local.inf_shunt local.inv_conjugate local.inv_contrav local.le_sup_iff local.sup_absorb2 qdual.qd.distr)
qed
lemma (in boolean_involutive_quantale) res_schroeder1:
assumes "\<forall>x y. x\<^sup>\<circ> \<cdot> -(x \<cdot> y) \<le> -y"
shows "((x \<cdot> y) \<sqinter> z = \<bottom>) = (y \<sqinter> (x\<^sup>\<circ> \<cdot> z) = \<bottom>)"
proof
assume h: "(x \<cdot> y) \<sqinter> z = \<bottom>"
hence "z \<le> -(x \<cdot> y)"
by (simp add: local.inf.commute local.inf_shunt)
thus "y \<sqinter> (x\<^sup>\<circ> \<cdot> z) = \<bottom>"
by (meson assms local.compl_le_swap1 local.inf_shunt local.order_trans qdual.qd.mult_isor)
next
assume "y \<sqinter> (x\<^sup>\<circ> \<cdot> z) = \<bottom>"
hence "y \<le> -(x\<^sup>\<circ> \<cdot> z)"
by (simp add: local.inf_shunt)
thus "(x \<cdot> y) \<sqinter> z = \<bottom>"
by (metis assms local.inf_shunt local.inv_invol local.order_trans qdual.qd.mult_isor)
qed
lemma (in boolean_involutive_quantale) res_schroeder2:
assumes "\<forall>x y. x\<^sup>\<circ> \<cdot> -(x \<cdot> y) \<le> -y"
shows "((x \<cdot> y) \<sqinter> z = \<bottom>) = (x \<sqinter> (z \<cdot> y\<^sup>\<circ>) = \<bottom>)"
by (metis assms local.inv_invol local.res_peirce local.res_schroeder1)
lemma (in boolean_involutive_quantale) res_mod:
assumes "\<forall>x y. x\<^sup>\<circ> \<cdot> -(x \<cdot> y) \<le> -y"
shows "(x \<cdot> y) \<sqinter> z \<le> (x \<sqinter> (z \<cdot> y\<^sup>\<circ>)) \<cdot> y"
proof-
have "(x \<cdot> y) \<sqinter> z = ((x \<sqinter> ((z \<cdot> y\<^sup>\<circ>) \<squnion> -(z \<cdot> y\<^sup>\<circ>))) \<cdot> y) \<sqinter> z"
by simp
also have "\<dots> = (((x \<sqinter> (z \<cdot> y\<^sup>\<circ>)) \<cdot> y) \<sqinter> z) \<squnion> (((x \<sqinter> -(z \<cdot> y\<^sup>\<circ>)) \<cdot> y) \<sqinter> z)"
using local.inf_sup_distrib1 local.inf_sup_distrib2 qdual.qd.distl by presburger
also have "\<dots> \<le> ((x \<sqinter> (z \<cdot> y\<^sup>\<circ>)) \<cdot> y) \<squnion> ((x \<cdot> y) \<sqinter> (-(z \<cdot> y\<^sup>\<circ>)) \<cdot> y \<sqinter> z)"
by (metis assms local.inf.cobounded1 local.inf.commute local.inf_compl_bot_right local.res_schroeder2 local.sup_bot_right)
also have "\<dots> \<le> ((x \<sqinter> (z \<cdot> y\<^sup>\<circ>)) \<cdot> y) \<squnion> ((x \<cdot> y) \<sqinter> -z \<sqinter> z)"
by (metis assms local.inf.commute local.inf_compl_bot_right local.res_schroeder2 local.sup.cobounded1 local.sup_bot_right)
also have "\<dots> \<le> ((x \<sqinter> (z \<cdot> y\<^sup>\<circ>)) \<cdot> y)"
by (simp add: local.inf.commute)
finally show ?thesis.
qed
class involutive_modal_quantale = modal_quantale + involutive_quantale
sublocale involutive_modal_quantale \<subseteq> invmqmka: involutive_modal_kleene_algebra "1" "(\<cdot>)" "(\<squnion>)" "\<bottom>" "(\<le>)" "(<)" qstar invol cod dom..
context involutive_modal_quantale
begin
lemma "dom x \<le> x \<cdot> x\<^sup>\<circ>"
nitpick (* 3-element counterexample *)
oops
lemma "x \<le> x \<cdot> x\<^sup>\<circ> \<cdot> x \<Longrightarrow> dom x \<le> x \<cdot> x\<^sup>\<circ>"
nitpick (* 3-element counterexample *)
oops
lemma "dom (x\<^sup>\<circ>) = cod x"
nitpick (* 4-element counterexample *)
oops
lemma "dom x \<le> do x"
nitpick
oops
lemma do_approx_dom: "do x \<le> dom x"
proof -
have "do x = dom (do x) \<cdot> do x"
by simp
also have "\<dots> \<le> dom (1 \<sqinter> (x \<cdot> x\<^sup>\<circ>))"
by (metis local.do_def local.inf.cobounded1 local.mult_1_right qdual.qd.mult_isor)
also have "\<dots> \<le> dom 1 \<sqinter> dom (x \<cdot> x\<^sup>\<circ>)"
using local.dom_meet_sub by presburger
also have "\<dots> \<le> dom (x \<cdot> dom (x\<^sup>\<circ>))"
by simp
also have "\<dots> \<le> dom x"
using local.dom_meet local.dqmka.d_export_var local.inf.absorb_iff2 by presburger
finally show ?thesis.
qed
end
class modal_quantale_converse = involutive_modal_quantale + quantale_converse
sublocale modal_quantale_converse \<subseteq> invmqmka: modal_kleene_algebra_converse "1" "(\<cdot>)" "(\<squnion>)" "\<bottom>" "(\<le>)" "(<)" qstar invol cod dom
by (unfold_locales, simp add: local.strong_gelfand)
class modal_quantale_strong_converse = involutive_modal_quantale +
assumes weak_dom_def: "dom x \<le> x \<cdot> x\<^sup>\<circ>"
and weak_cod_def: "cod x \<le> x\<^sup>\<circ> \<cdot> x"
sublocale modal_quantale_strong_converse \<subseteq> invmqmka: modal_kleene_algebra_strong_converse "1" "(\<cdot>)" "(\<squnion>)" "\<bottom>" "(\<le>)" "(<)" qstar invol cod dom
by (unfold_locales, simp_all add: local.weak_dom_def local.weak_cod_def)
context modal_quantale_strong_converse
begin
lemma "(x \<cdot> y) \<sqinter> z \<le> (x \<sqinter> (z \<cdot> y\<^sup>\<circ>)) \<cdot> y"
nitpick (* 5-element counterexample *)
oops
lemma dom_def: "dom x = 1 \<sqinter> (x \<cdot> x\<^sup>\<circ>)"
apply (rule order.antisym)
apply (simp add: local.dom_subid local.weak_dom_def)
by (smt (verit, best) local.dom_subid local.dqmka.d_absorb_eq local.dqmka.d_iso local.dual_order.trans local.inf.cobounded1 local.inf.cobounded2 local.mqs.msrdual.cod_local local.mult_1_right qdual.qd.mult_isor)
lemma cod_def: "cod x = 1 \<sqinter> (x\<^sup>\<circ> \<cdot> x)"
by (metis invqka.inv_one local.cd_compat local.coddual.dqmka.d_absorb_eq local.coddual.dqmka.d_export_var local.dc_compat local.dom_def local.dqmka.d_absorb_eq local.dqmka.d_export local.inv_binf local.inv_contrav local.inv_invol)
lemma "do x = dom x"
by (simp add: local.do_def local.dom_def)
end
class dedekind_modal_distributive_quantale = involutive_modal_quantale + dedekind_quantale + distributive_quantale
begin
lemma "dom x = do x"
nitpick (* 3-element counterexample *)
oops
end
class dedekind_modal_boolean_quantale = involutive_modal_quantale + dedekind_quantale + boolean_quantale
begin
lemma subid_idem: "p \<le> 1 \<Longrightarrow> p \<cdot> p = p"
by (metis (full_types) local.convdqka.subid_conv local.do_absorp local.do_def local.dual_order.antisym local.eq_refl local.inf_absorb2 local.mult_1_right qdual.qd.dd.mult_iso)
lemma subid_comm: "p \<le> 1 \<Longrightarrow> q \<le> 1 \<Longrightarrow> p \<cdot> q = q \<cdot> p"
by (smt (verit, ccfv_SIG) local.dual_order.antisym local.dual_order.trans local.mult_1_left local.mult_1_right local.qdual.mult_assoc qdual.qd.mult_isol qdual.qd.mult_isor subid_idem)
lemma subid_meet_comp: "p \<le> 1 \<Longrightarrow> q \<le> 1 \<Longrightarrow> p \<sqinter> q = p \<cdot> q"
by (smt (verit, ccfv_SIG) local.inf.absorb2 local.inf.assoc local.inf.cobounded1 local.inf.cobounded2 local.inf.orderE local.mult_1_right qdual.qd.mult_isor subid_comm subid_idem)
lemma subid_dom: "p \<le> 1 \<Longrightarrow> dom p = p"
proof-
assume h: "p \<le> 1"
have a: "p \<squnion> (1 \<sqinter> -p) = 1"
using h local.sup.absorb_iff2 local.sup_inf_distrib1 by auto
have "(1 \<sqinter> -p) \<sqinter> p = \<bottom>"
by (simp add: local.inf.commute)
thus ?thesis
by (smt (verit, best) a h local.dom_subid local.dom_zero local.dqmka.d_absorb_eq local.dqmka.d_id local.dqmka.d_iso local.inf.absorb1 local.inf_le1 local.mqs.msrdual.cod_local qdual.qd.distr subid_comm subid_meet_comp)
qed
lemma do_prop: "(do x \<le> do y) = (x \<le> do y \<cdot> \<top>)"
by (metis local.do_absorp_eq local.do_top local.do_top2 local.inf_mono local.order_refl local.top_greatest local.top_top mult_assoc qdual.qd.mult_iso)
lemma "(do x \<le> do y) = (x \<le> do y \<cdot> x)"
by (smt (verit, del_insts) do_prop local.do_absorp_eq local.eq_refl local.inf.absorb2 local.inf.coboundedI1 local.top_greatest qdual.qd.mult_iso)
lemma lla_subid: "p \<le> 1 \<Longrightarrow> ((dom x \<le> p) = (x \<le> p \<cdot> x))"
by (metis local.dqmka.lla subid_dom)
lemma dom_do: "dom x = do x"
proof-
have "x \<le> do x \<cdot> x"
by simp
hence "dom x \<le> do x"
using lla_subid local.do_subid by auto
thus ?thesis
by (simp add: local.antisym_conv local.do_approx_dom)
qed
end
end
|
{-# OPTIONS --without-K --safe #-}
open import Categories.Category.Core
open import Categories.Comonad
-- verbatim dual of Categories.Adjoint.Construction.EilenbergMoore
module Categories.Adjoint.Construction.CoEilenbergMoore {o ℓ e} {C : Category o ℓ e} (M : Comonad C) where
open import Categories.Category.Construction.CoEilenbergMoore M
open import Categories.Adjoint
open import Categories.Functor
open import Categories.Functor.Properties
open import Categories.NaturalTransformation.NaturalIsomorphism using (niHelper)
open import Categories.NaturalTransformation.Core
open import Categories.NaturalTransformation.NaturalIsomorphism using (_≃_)
open import Categories.Morphism.Reasoning C
private
module C = Category C
module M = Comonad M
open M.F
open C
open HomReasoning
open Equiv
Forgetful : Functor CoEilenbergMoore C
Forgetful = record
{ F₀ = Comodule.A
; F₁ = Comodule⇒.arr
; identity = refl
; homomorphism = refl
; F-resp-≈ = λ eq → eq
}
Cofree : Functor C CoEilenbergMoore
Cofree = record
{ F₀ = λ A → record
{ A = F₀ A
; coaction = M.δ.η A
; commute = M.sym-assoc
; identity = Comonad.identityʳ M
}
; F₁ = λ f → record
{ arr = F₁ f
; commute = M.δ.commute f
}
; identity = identity
; homomorphism = homomorphism
; F-resp-≈ = F-resp-≈
}
UC≃M : Forgetful ∘F Cofree ≃ M.F
UC≃M = niHelper (record
{ η = λ _ → F₁ C.id
; η⁻¹ = λ _ → F₁ C.id
; commute = λ f → [ M.F ]-resp-square id-comm-sym
; iso = λ _ → record
{ isoˡ = elimˡ identity ○ identity
; isoʳ = elimˡ identity ○ identity
}
})
Forgetful⊣Cofree : Forgetful ⊣ Cofree
Forgetful⊣Cofree = record
{ unit = record
{ η = λ X → let module X = Comodule X
in record
{ arr = X.coaction
; commute = ⟺ X.commute
}
; commute = Comodule⇒.commute
; sym-commute = λ f → ⟺ (Comodule⇒.commute f)
}
; counit = record
{ η = M.ε.η
; commute = M.ε.commute
; sym-commute = M.ε.sym-commute
}
; zig = λ {A} → Comodule.identity A
; zag = λ {B} → Comonad.identityˡ M
} |
<a href="https://colab.research.google.com/github/NeuromatchAcademy/course-content/blob/master/tutorials/W3D1_RealNeurons/W3D1_Tutorial3.ipynb" target="_parent"></a>
# Neuromatch Academy: Week 3, Day 1, Tutorial 3
# Real Neurons: Synaptic transmission - Models of static and dynamic synapses
## Tutorial Objectives
Synapses connect neurons into neural networks or circuits. Specialized electrical synapses make direct, physical connections between neurons. In this tutorial, however, we will focus on chemical synapses, which are more common in the brain. These synapses do not physically join neurons. Instead, eliciting a spike in the presynaptic cell causes a chemical, or neurotransmitter, to be released into a small space between the neurons called the synaptic cleft. Once the chemical diffuses across that space, it causes changes in the membrane of the postsynaptic cell. In this tutorial, we will model chemical synaptic transmission and study some interesting effects produced by static synapses that do not change and dynamic ones that change their effects based on the spiking history of the presynaptic neurons.
First, we will start by writing code to simulate static synapses.
Next, we will extend the model to include synapses whose synaptic strength is dependent on the recent spike history: synapses can either progressively increase or decrease the size of their effects on the postsynaptic neuron, based on the recent firing rate of its pre-synaptic partners. This feature of synapses in the brain is called **Short-Term Plasticity** and causes synapses to undergo *Facilitation* or *Depression*.
Our goals for this tutorial are to:
- simulate static synapses and study how excitation and inhibition affect the patterns in the neurons' spiking output
- define mean- or fluctuation-driven regimes
- simulate short-term dynamics of synapses (facilitation and depression)
- study how a change in presynaptic firing history affects the synaptic weights (i.e., PSP amplitude)
# Setup
```python
# Imports
import matplotlib.pyplot as plt # import matplotlib
import numpy as np # import numpy
import time # import time
import ipywidgets as widgets # interactive display
from scipy.stats import pearsonr # import pearson correlation
```
```python
#@title Figure Settings
%matplotlib inline
fig_w, fig_h = (8, 6)
my_fontsize = 18
my_params = {'axes.labelsize': my_fontsize,
'axes.titlesize': my_fontsize,
'figure.figsize': [fig_w, fig_h],
'font.size': my_fontsize,
'legend.fontsize': my_fontsize-4,
'lines.markersize': 8.,
'lines.linewidth': 2.,
'xtick.labelsize': my_fontsize-2,
'ytick.labelsize': my_fontsize-2}
plt.rcParams.update(my_params)
my_layout = widgets.Layout()
```
```python
#@title Helper functions
def my_GWN(pars, mu, sig, myseed=False):
"""
Args:
pars : parameter dictionary
mu : noise baseline (mean)
sig : noise amplitute (standard deviation)
myseed : random seed. int or boolean
the same seed will give the same random number sequence
Returns:
I : Gaussian White Noise (GWN) input
"""
# Retrieve simulation parameters
dt, range_t = pars['dt'], pars['range_t']
Lt = range_t.size
# set random seed
# you can fix the seed of the random number generator so that the results
# are reliable. However, when you want to generate multiple realizations
# make sure that you change the seed for each new realization.
if myseed:
np.random.seed(seed=myseed)
else:
np.random.seed()
# generate GWN
# we divide here by 1000 to convert units to seconds.
I = mu + sig * np.random.randn(Lt) / np.sqrt(dt/1000.)
return I
def Poisson_generator(pars, rate, n, myseed=False):
"""
Generates poisson trains
Args:
pars : parameter dictionary
rate : noise amplitute [Hz]
n : number of Poisson trains
myseed : random seed. int or boolean
Returns:
pre_spike_train : spike train matrix, ith row represents whether
there is a spike in ith spike train over time
(1 if spike, 0 otherwise)
"""
# Retrieve simulation parameters
dt, range_t = pars['dt'], pars['range_t']
Lt = range_t.size
# set random seed
if myseed:
np.random.seed(seed=myseed)
else:
np.random.seed()
# generate uniformly distributed random variables
u_rand = np.random.rand(n, Lt)
# generate Poisson train
poisson_train = 1. * (u_rand<rate*dt/1000.)
return poisson_train
def my_illus_LIFSYN(pars, v_fmp, v):
"""
Illustartion of FMP and membrane voltage
Args:
pars : parameters dictionary
v_fmp : free membrane potential, mV
v : membrane voltage, mV
Returns:
plot of membrane voltage and FMP, alongside with the spiking threshold
and the mean FMP (dashed lines)
"""
plt.figure(figsize=(14., 5))
plt.plot(pars['range_t'], v_fmp, 'r', lw=1., label = 'Free mem. pot.', zorder=2)
plt.plot(pars['range_t'], v, 'b', lw=1., label = 'True mem. pot', zorder=1, alpha=0.7)
plt.axhline(-55, 0, 1, color='k', lw=2., ls='--',label = 'Spike Threshold', zorder=1)
plt.axhline(np.mean(v_fmp),0, 1, color='r', lw=2., ls='--',label = 'Mean Free Mem. Pot.', zorder=1)
plt.xlabel('Time (ms)')
plt.ylabel('V (mV)');
plt.legend(loc=[1.02, 0.68])
plt.show()
def my_illus_STD(Poi_or_reg=False, rate=20., U0=0.5, tau_d=100., tau_f=50., plot_out=True):
"""
Only for one presynaptic train
Args:
Poi_or_reg : Poisson or regular input spiking trains
rate : Rate of input spikes, Hz
U0 : synaptic release probability at rest
tau_d : synaptic depression time constant of x [ms]
tau_f : synaptic facilitation time constantr of u [ms]
plot_out : whether ot not to plot, True or False
Returns:
"""
T_simu = 10.0 * 1000/(1.0*rate) # 10 spikes in the time window
pars = default_pars(T=T_simu)
dt, range_t = pars['dt'], pars['range_t']
if Poi_or_reg:
# Poisson type spike train
pre_spike_train = Poisson_generator(pars, rate, n=1)
pre_spike_train = pre_spike_train.sum(axis=0)
else:
# Regular firing rate
isi_num = int((1e3/rate)/dt) # number of dt
pre_spike_train = np.zeros(len(pars['range_t']))
pre_spike_train[::isi_num] = 1.
u, R, g = dynamic_syn(g_bar=1.2, tau_syn=5., U0=U0, tau_d=tau_d, tau_f=tau_f,
pre_spike_train=pre_spike_train, dt=pars['dt'])
if plot_out:
plt.figure(figsize=(12, 6))
plt.subplot(2,2,1)
plt.plot(pars['range_t'], R, 'b', label='R')
plt.plot(pars['range_t'], u, 'r', label='u')
plt.legend(loc='best')
plt.xlim((0,pars['T']))
plt.ylabel(r'$R$ or $u$ (a.u)')
plt.subplot(2,2,3)
spT = pre_spike_train>0
t_sp = pars['range_t'][spT] #spike times
plt.plot(t_sp, 0.*np.ones(len(t_sp)), 'k|', ms=18, markeredgewidth=2)
plt.xlabel('Time (ms)');
plt.xlim((0,pars['T']))
plt.yticks([])
plt.title('Presynaptic spikes')
plt.subplot(1,2,2)
plt.plot(pars['range_t'], g, 'r', label='STP synapse')
plt.xlabel('Time (ms)')
plt.ylabel('g (nS)')
plt.xlim((0,pars['T']))
plt.tight_layout()
if not Poi_or_reg:
return g[isi_num], g[9*isi_num]
def plot_volt_trace(pars, v, sp):
"""
Plot trajetory of membrane potential for a single neuron
Args:
pars : parameter dictionary
v : volt trajetory
sp : spike train
Returns:
figure of the membrane potential trajetory for a single neuron
"""
V_th = pars['V_th']
dt, range_t = pars['dt'], pars['range_t']
if sp.size:
sp_num = (sp/dt).astype(int)-1
v[sp_num] += 10
plt.plot(pars['range_t'], v, 'b')
plt.axhline(V_th, 0, 1, color='k', ls='--', lw=1.)
plt.xlabel('Time (ms)')
plt.ylabel('V (mV)')
```
In the `Helper Function`:
- Gaussian white noise generator: `my_GWN(pars, mu, sig, myseed=False)`
- Poissonian spike train generator: `Poisson_generator(pars, rate, n, myseed=False)`
```python
#@title Default value function: `default_pars( **kwargs)`
def default_pars( **kwargs):
pars = {}
### typical neuron parameters###
pars['V_th'] = -55. # spike threshold [mV]
pars['V_reset'] = -75. #reset potential [mV]
pars['tau_m'] = 10. # membrane time constant [ms]
pars['g_L'] = 10. #leak conductance [nS]
pars['V_init'] = -65. # initial potential [mV]
pars['E_L'] = -75. #leak reversal potential [mV]
pars['tref'] = 2. # refractory time (ms)
### simulation parameters ###
pars['T'] = 400. # Total duration of simulation [ms]
pars['dt'] = .1 # Simulation time step [ms]
### external parameters if any ###
for k in kwargs:
pars[k] = kwargs[k]
pars['range_t'] = np.arange(0, pars['T'], pars['dt']) # Vector of discretized time points [ms]
return pars
```
## Static synapses
```python
#@title Video: Static and dynamic synapses
from IPython.display import YouTubeVideo
video = YouTubeVideo(id='S82kACA5P0M', width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video
```
Video available at https://youtube.com/watch?v=S82kACA5P0M
## Simulate synaptic conductance dynamics
The GWN input used in Tutorials 1 and 2 is quite unphysiological input compared to the inputs that a real neuron receives. Synaptic input _in vivo_ consists of a mixture of **excitatory** neurotransmitters, which depolarizes the cell and drives it towards spike threshold, and **inhibitory** neurotransmitters that hyperpolarize it, driving it away from spike threshold. Each of these chemicals cause specific ion channels on the postsynaptic neuron to open, resulting in a change in that neuron's conductance and therefore, the flow of current into or out of the cell.
This process can be modelled by assuming that the presynaptic neuron's spiking activity produces transient changes in the postsynaptic neuron's conductance ($g_{\rm syn}(t)$). Typically, the conductance transient is modelled as an exponential function.
Such conductance transients can be generated using a simple ordinary differential equation (ODE):
\begin{eqnarray}
\frac{dg_{\rm syn}(t)}{dt} &=& \bar{g}_{\rm syn} \sum_k \delta(t-t_k) -g_{\rm syn}(t)/\tau_{\rm syn}
\end{eqnarray}
where $\bar{g}_{\rm syn}$ is the maximum conductance elicited by each incoming spike -- this is often referred to as synaptic weight--and $\tau_{\rm syn}$ is the synaptic time constant. Note that the summation runs over all spikes received by the neuron at time $t_k$.
Ohm's law allows us to convert conductance changes into current as:
\begin{align}
I_{\rm syn}(t) = -g_{\rm syn}(t)(V(t)-E_{\rm syn}) \\
\end{align}
The reversal potential $E_{\rm syn}$ describes the direction of current flow and the excitatory or inhibitory nature of the synapse.
**Thus, incoming spikes are filtered by an exponential-shaped kernel, effectively low-pass filtering the input. In other words, synaptic input is not white noise but it is in fact colored noise, where the color (spectrum) of the noise is determined by the synaptic time constants of both excitatory and inhibitory synapses.**
In a neuronal network, the total synaptic input current $I_{\rm syn}$ is the sum of both excitatory and inhibitory inputs. Assuming the total excitatory and inhibitory conductances received at time $t$ are $g_E(t)$ and $g_I(t)$, and their corresponding reversal potentials are $E_E$ and $E_I$, respectively, then the total synaptic current can be described as:
\begin{align}
I_{\rm syn}(V(t),t) = -g_E(t) (V-E_E) - g_I(t) (V-E_I). \\
\end{align}
Accordingly, the membrane potential dynamics of the LIF neuron under synaptic current drive become:
\begin{align}
\tau_m\frac{dV(t)}{dt} = -(V(t)-E_L) - \frac{g_E(t)}{g_L} (V(t)-E_E) - \frac{g_I(t)}{g_L} (V(t)-E_I) + \frac{I_{\rm inj}}{g_L}.\quad (2)
\end{align}
$I_{\rm inj}$ is an external current injected in the neuron which is under experimental control; it can be GWN, DC or anything else.
We will use Eq. (2) to simulate the conductance-based LIF neuron model below.
In the previous tutorials, we saw how the output of a single neuron (spike count/rate and spike time irregularity), changed when we stimulated the neuron with DC and GWN, respectively. Now, we are in a position to study how the neuron behaves when it is bombarded with both excitatory and inhibitory spikes trains -- as happens *in vivo*.
What kind of input a neuron is receiving? When we do not know, we chose the simplest option. The simplest model of input spikes is given when every input spike arrives independently of other spikes, i.e., we assume that the input is Poissonian.
### Simulate LIF neuron with conductance-based synapses
We are now ready to simulate a LIF neuron with conductance-based synaptic inputs! The following code defines the LIF neuron with synaptic input modelled as conductance transients.
```python
#@title Conductance-based LIF: `run_LIF_cond`
def run_LIF_cond(pars, I_inj, pre_spike_train_ex, pre_spike_train_in):
"""conductance-based LIF dynamics
Rgs:
pars : parameter dictionary
I_inj : injected current [pA]. The injected current here can be a value or an array
pre_spike_train_ex : spike train input from presynaptic excitatory neuron
pre_spike_train_in : spike train input from presynaptic inhibitory neuron
Returns:
rec_spikes : spike times
rec_v : mebrane potential
gE : postsynaptic excitatory conductance
gI : postsynaptic inhibitory conductance
"""
# Retrieve parameters
V_th, V_reset = pars['V_th'], pars['V_reset']
tau_m, g_L = pars['tau_m'], pars['g_L']
V_init, E_L = pars['V_init'], pars['E_L']
gE_bar, gI_bar = pars['gE_bar'], pars['gI_bar']
VE, VI = pars['VE'], pars['VI']
tau_syn_E, tau_syn_I = pars['tau_syn_E'], pars['tau_syn_I']
tref = pars['tref']
dt, range_t = pars['dt'], pars['range_t']
Lt = range_t.size
# Initialize
tr = 0.
v = np.zeros(Lt)
v[0] = V_init
gE = np.zeros(Lt)
gI = np.zeros(Lt)
I = I_inj * np.ones(Lt) #ensure I has length Lt
if pre_spike_train_ex.max() == 0:
pre_spike_train_ex_total = np.zeros(Lt)
else:
pre_spike_train_ex_total = pre_spike_train_ex.sum(axis=0) * np.ones(Lt)
if pre_spike_train_in.max() == 0:
pre_spike_train_in_total = np.zeros(Lt)
else:
pre_spike_train_in_total = pre_spike_train_in.sum(axis=0) * np.ones(Lt)
# simulation
rec_spikes = [] # recording spike times
for it in range(Lt-1):
if tr > 0:
v[it] = V_reset
tr = tr-1
elif v[it] >= V_th: #reset voltage and record spike event
rec_spikes.append(it)
v[it] = V_reset
tr = tref/dt
#update the synaptic conductance
gE[it+1] = gE[it] - (dt/tau_syn_E)*gE[it] + gE_bar*pre_spike_train_ex_total[it+1]
gI[it+1] = gI[it] - (dt/tau_syn_I)*gI[it] + gI_bar*pre_spike_train_in_total[it+1]
#calculate the increment of the membrane potential
dv = (-(v[it]-E_L) - (gE[it+1]/g_L)*(v[it]-VE) - \
(gI[it+1]/g_L)*(v[it]-VI) + I[it]/g_L) * (dt/tau_m)
#update membrane potential
v[it+1] = v[it] + dv
rec_spikes = np.array(rec_spikes) * dt
return v, rec_spikes, gE, gI
```
#### Exercise 1: Measure the Mean free membrane potential
Let's simulate the conductance-based LIF neuron with presynaptic spike trains genetated by a `Poisson_generator` with rate 10 Hz for both excitatory and inhibitory inputs. Here, we choose 80 exictatory presynaptic spike trains and 20 inhibitory ones.
Previously, we've already learned that CV$_{\rm ISI}$ can describe the irregularity of the output spike pattern. Now, we will introduce the **Free Membrane Potential (FMP)**, which is the membrane potential of the neuron when its spike threshold is removed. Although this is completely artificial, calculating this quantity allows us to get an idea of how strong the input is. We are mostly interested in knowing the mean and standard deviation (std.) of the FMP.
```python
# Exercise 1
# To complete the exercise, uncomment the code and fill the missing parts (...)
pars = default_pars(T=1000.)
# Add parameters
pars['gE_bar'] = 2.4 # [nS]
pars['VE'] = 0. # [mV] excitatory reversal potential
pars['tau_syn_E'] = 2.4 # [ms]
pars['gI_bar'] = 3. # [nS]
pars['VI'] = -80. # [mV] inhibitory reversal potential
pars['tau_syn_I'] = 5. # [ms]
# generate presynaptic spike trains
pre_spike_train_ex = Poisson_generator(pars, rate=10, n=80)
pre_spike_train_in = Poisson_generator(pars, rate=10, n=20)
# simulate conductance-based LIF model
v, rec_spikes, gE, gI = run_LIF_cond(pars, 0, pre_spike_train_ex, pre_spike_train_in)
dt, range_t = pars['dt'], pars['range_t']
if rec_spikes.size:
sp_num = (rec_spikes/dt).astype(int)-1
v[sp_num] = 10 # draw nicer spikes
####################################################################
## TODO for students: Try to meansure the free membrane potential #
####################################################################
# In order to measure the free membrane potential, first,
# you should prevent the firing of the LIF neuron
# How to prevent a LIF neuron from firing? Increse the threshold pars['V_th'].
# pars['V_th'] = ...
# v_fmp, _, _, _ = ...
# comment this out when you've filled
#raise NotImplementedError("Student excercise: measure the FMP")
# uncomment when you have filled the excercise
# my_illus_LIFSYN(pars, v, v_fmp)
```
```python
# to_remove solutions
pars = default_pars(T=1000.)
#Add parameters
pars['gE_bar'] = 2.4 # [nS]
pars['VE'] = 0. # [mV] excitatory reversal potential
pars['tau_syn_E'] = 2. # [ms]
pars['gI_bar'] = 2.4 # [nS]
pars['VI'] = -80. # [mV] inhibitory reversal potential
pars['tau_syn_I'] = 5. # [ms]
#generate presynaptic spike trains
pre_spike_train_ex = Poisson_generator(pars, rate=10, n=80)
pre_spike_train_in = Poisson_generator(pars, rate=10, n=20)
# simulate conductance-based LIF model
v, rec_spikes, gE, gI = run_LIF_cond(pars, 0, pre_spike_train_ex, pre_spike_train_in)
dt, range_t = pars['dt'], pars['range_t']
if rec_spikes.size:
sp_num = (rec_spikes/dt).astype(int)-1
v[sp_num] = 10 # draw nicer spikes
#measure FMP
pars['V_th'] = 1e3
v_fmp, _, _, _ = run_LIF_cond(pars, 0, pre_spike_train_ex, pre_spike_train_in)
# plotting
with plt.xkcd():
my_illus_LIFSYN(pars, v_fmp, v)
```
### Parameter Exploration: different ratio of excitation and inhibition
In the following, we can investigate how varying the ratio of excitatory to inhibitory inputs changes the firing rate and the spike time regularity (see the output text).
To change the both the excitatory and inhibitory inputs we will vary their firing rates. *However, if you wish, you can vary the strength and/or the number of these connections as well.*
```python
#@title Conductance-based LIF Explorer with different E/I input
my_layout.width = '450px'
@widgets.interact(
inh_rate = widgets.FloatSlider(20., min=10., max=60., step=5., layout=my_layout),
exc_rate = widgets.FloatSlider(10., min=2., max=20., step=2., layout=my_layout)
)
def EI_isi_regularity(exc_rate, inh_rate):
pars = default_pars(T=1000.)
#Add parameters
pars['gE_bar'] = 3. # [nS]
pars['VE'] = 0. # [mV] excitatory reversal potential
pars['tau_syn_E'] = 2. # [ms]
pars['gI_bar'] = 3. # [nS]
pars['VI'] = -80. # [mV] inhibitory reversal potential
pars['tau_syn_I'] = 5. # [ms]
pre_spike_train_ex = Poisson_generator(pars, rate=exc_rate, n=80)
pre_spike_train_in = Poisson_generator(pars, rate=inh_rate, n=20) # 4:1
# Lets first simulate a neuron with identical input but with no spike threshold
# by setting the threshold to a very high value
# so that we can look at the free membrane potential
pars['V_th'] = 1e3
v_fmp, rec_spikes, gE, gI = run_LIF_cond(pars, 0, pre_spike_train_ex, pre_spike_train_in)
# Now simulate a LIP with a regular spike threshold
pars['V_th'] = -55.
v, rec_spikes, gE, gI = run_LIF_cond(pars, 0, pre_spike_train_ex, pre_spike_train_in)
dt, range_t = pars['dt'], pars['range_t']
if rec_spikes.size:
sp_num = (rec_spikes/dt).astype(int)-1
v[sp_num] = 10 #draw nicer spikes
spike_rate = 1e3*len(rec_spikes)/pars['T']
#print('Spike rate = %.3f (sp/s)' % spike_rate)
cv_isi = 0.
if len(rec_spikes)>3:
isi = np.diff(rec_spikes)
cv_isi = np.std(isi)/np.mean(isi)
#print('CV ISI = %.3f' % (cv_isi))
#print('Mean of Free Mem Pot = %.3f' % (np.mean(v_fmp)))
#print('STD of Free Mem Pot = %.3f' % (np.std(v_fmp)))
print('\n')
plt.figure(figsize=(15., 10))
plt.subplot(2,1,1)
plt.text(500, -35, 'Spike rate = %.3f (sp/s), Mean of Free Mem Pot = %.3f' % (spike_rate, np.mean(v_fmp)),
fontsize=16, fontweight='bold', horizontalalignment='center', verticalalignment='bottom')
plt.text(500, -38.5, 'CV ISI = %.3f, STD of Free Mem Pot = %.3f' % (cv_isi, np.std(v_fmp)),
fontsize=16, fontweight='bold', horizontalalignment='center', verticalalignment='bottom')
plt.plot(pars['range_t'], v_fmp, 'r', lw=1., label = 'Free mem. pot.', zorder=2)
plt.plot(pars['range_t'], v, 'b', lw=1., label = 'mem. pot with spk thr', zorder=1, alpha=0.7)
plt.axhline(pars['V_th'], 0, 1, color='k', lw=1., ls='--',label = 'Spike Threshold', zorder=1)
plt.axhline(np.mean(v_fmp),0, 1, color='r', lw=1., ls='--',label = 'Mean Free Mem. Pot.', zorder=1)
plt.ylim(-76, -39)
plt.xlabel('Time (ms)')
plt.ylabel('V (mV)')
plt.legend(loc=[1.02, 0.68])
plt.subplot(2,2,3)
plt.plot(pars['range_t'][::3], gE[::3], 'r', lw=1.)
plt.xlabel('Time (ms)')
plt.ylabel(r'$g_E$ (nS)')
plt.subplot(2,2,4)
plt.plot(pars['range_t'][::3], gI[::3], 'b', lw=1.)
plt.xlabel('Time (ms)')
plt.ylabel(r'$g_I$ (nS)')
plt.tight_layout()
#_ = widgets.interact(EI_isi_regularity, inh_rate = (10., 60., 5.), exc_rate = (5.,20.,2))
```
### Mean-driven and Fluctuation-driven regimes
If we look at the figure above, we note that when the mean FMP is above spike threshold, the fluctuations in the FMP are rather small and the neuron spikes in a fairly regular fashion. This regime when the mean FMP is above the spike threshold is called **mean-driven regime**.
When the mean FMP is below spike threshold, the fluctuations in the FMP are large and the neuron's spikes are driven by these fluctuations. As a consequence, the neuron spikes in more Poisson-like fashion. This regime when the mean FMP is below the spike threshold and spikes are driven by the fluctuations is called **fluctuation-driven regime**.
#### Think!
- How much can you increase the spike pattern variability? Under what condition(s) the neuron may also respond with Poisson-type spikes? Note that we injected Poisson-type spikes.
- Link to the balance of excitation and inhibition. One of the definition of excitation and inhibition balance is that mean free membrane potential remains constant as excitatory and inhibitory input rates are increased. What do you think happens to the neuron firing rate as we change excitatory and inhibitory rates while keeping the neuron in balance? See [Kuhn, Aertsen, and Rotter (2004)](https://www.jneurosci.org/content/jneuro/24/10/2345.full.pdf) for much more on this.
## Short-term synaptic plasticity
Short-term plasticity (STP) is a phenomenon in which synaptic efficacy changes over time in a way that reflects the history of presynaptic activity. Two types of STP, with opposite effects on synaptic efficacy, have been experimentally observed. They are known as Short-Term Depression (STD) and Short-Term Facilitation (STF).
The mathematical model of STP is based on the concept of a limited pool of synaptic resources available for transmission ($R$), such as, for example, the overall amount of synaptic vescicles at the presynaptic terminals. The amount of presynaptic resource changes in a dynamic fashion depending on the recent history of spikes.
Following a presynaptic spike, (i) the fraction $u$ (release probability) of the available pool to be utilized increases due to spike-induced calcium influx to the presynaptic terminal, after which (ii) $u$ is consumed to increase the post-synaptic conductance. Between spikes, $u$ decays back to zero with time constant $\tau_f$ and $R$ recovers to 1 with time constant $\tau_d$. In summary, the dynamics of excitatory (subscript E) STP is given by:
\begin{eqnarray}
&& \frac{du_E}{dt} &= -\frac{u_E}{\tau_f} + U_0(1-u_E^-)\delta(t-t_{\rm sp}) \\[.5mm]
&& \frac{dR_E}{dt} &= \frac{1-R_E}{\tau_d} - u_E^+ R_E^- \delta(t-t_{\rm sp}) \qquad (6)\\[.5mm]
&& \frac{dg_E(t)}{dt} &= -\frac{g_E}{\tau_E} + \bar{g}_E u_E^+ R_E^- \sum_k \delta(t-t_{\rm k}),
\end{eqnarray}
where $U_0$ is a constan determining the increment of $u$ produced by a spike. $u_E^-$ and $R_E^-$ denote the corresponding values just before the spike arrives, whereas $u_E^+$ refers to the moment right after the spike. $\bar{g}_E$ denotes the maximum excitatory conductane, and the calculation of $g_E(t)$ is calculated for all spiketimes $k$. Similarly, one can obtain the dynamics of inhibitory STP.
The interplay between the dynamics of $u$ and $x$ determines whether the joint effect of $ux$ is dominated by depression or facilitation. In the parameter regime of $\tau_d \gg \tau_f$ and large $U_0$, an initial spike incurs a large drop in $x$ that takes a long time to recover; therefore the synapse is STD-dominated. In the regime of $\tau_d \ll \tau_f$ and small $U_0$, the synaptic efficacy is increased gradually by spikes, and consequently, the synapse is STF-dominated. This phenomenological model successfully reproduces the kinetic dynamics of depressed and facilitated synapses observed in many cortical areas.
### Exercise 2: Compute $du$, $dR$ and $dg$
As we learned in several previous tutorials, the Euler numerical integration method involves the calculation of each derivative at step $n$:
\begin{eqnarray}
du_E &=& -\frac{u_E[t]}{\tau_f} dt + U_0(1-u_E[t])\cdot \text{sp_or_not[t+dt]} \\
dR_E &=& \frac{1-R_E[t]}{\tau_d} dt - u_E[t+dt]R_E[t]\cdot \text{sp_or_not[t+dt]} \\
dg_E &=& -\frac{g_E[t]}{\tau_{E}} dt + \bar{g}_Eu_E[t+dt]R_E[t]\cdot \text{sp_or_not[t+dt]}
\end{eqnarray}
where $\text{sp_or_not}=1$ if there's a spike in the time window $dt$, and $\text{sp_or_not}=0$ otherwise. In addition, note that any spike train generated by our `Poisson_generator` is binary. Then, the values are updated:
\begin{aligned}
\begin{eqnarray}
u_E[t+dt] = u_E[t] + du_E\\
R_E[t+dt] = R_E[t] + dR_E\\
g_E[t+dt] = g_E[t] + dg_E
\end{eqnarray}
\end{aligned}
Similarly, one can obtain the dynamics of inhibitory conductance.
```python
# Exercise 2
def dynamic_syn(g_bar, tau_syn, U0, tau_d, tau_f, pre_spike_train, dt):
"""
Short-term synaptic plasticity
Args:
g_bar : synaptic conductance strength
tau_syn : synaptic time constant [ms]
U0 : synaptic release probability at rest
tau_d : synaptic depression time constant of x [ms]
tau_f : synaptic facilitation time constantr of u [ms]
pre_spike_train : total spike train (number) input
from presynaptic neuron
dt : time step [ms]
Returns:
u : usage of releasable neurotransmitter
R : fraction of synaptic neurotransmitter resources available
g : postsynaptic conductance
"""
Lt = len(pre_spike_train)
# Initialize
u = np.zeros(Lt)
R = np.zeros(Lt)
R[0] = 1.
g = np.zeros(Lt)
# simulation
for it in range(Lt-1):
#########################################################################
## TODO for students: compute du, dx and dg, remove NotImplementedError #
#########################################################################
# Note pre_spike_train[i] is binary, which is sp_or_not in the $i$th timebin
# comment this out when you've finished filling this out.
raise NotImplementedError("Student excercise: compute the STP dynamics")
# du = ...
u[it+1] = u[it] + du
# dR = ...
R[it+1] = R[it] + dR
# dg = ...
g[it+1] = g[it] + dg
return u, R, g
# Uncomment this line after completing the dynamic_syn function
# _ = my_illus_STD(Poi_or_reg=False, rate=20., U0=0.5, tau_d=100., tau_f=50.) # Poi_or_reg=False:regular spike train
```
```python
# to_remove solution
def dynamic_syn(g_bar, tau_syn, U0, tau_d, tau_f, pre_spike_train, dt):
"""
Short-term synaptic plasticity
Args:
g_bar : synaptic conductance strength
tau_syn : synaptic time constant [ms]
U0 : synaptic release probability at rest
tau_d : synaptic depression time constant of x [ms]
tau_f : synaptic facilitation time constantr of u [ms]
pre_spike_train : total spike train (number) input
from presynaptic neuron
dt : time step [ms]
Returns:
u : usage of releasable neurotransmitter
R : fraction of synaptic neurotransmitter resources available
g : postsynaptic conductance
"""
Lt = len(pre_spike_train)
# Initialize
u = np.zeros(Lt)
R = np.zeros(Lt)
R[0] = 1.
g = np.zeros(Lt)
# simulation
for it in range(Lt-1):
du = - (dt/tau_f)*u[it] + U0 * (1.0-u[it]) * pre_spike_train[it+1]
u[it+1] = u[it] + du
dR = (dt/tau_d)*(1.0-R[it]) - u[it+1]*R[it] * pre_spike_train[it+1]
R[it+1] = R[it] + dR
dg = - (dt/tau_syn)*g[it] + g_bar*R[it]*u[it+1] * pre_spike_train[it+1]
g[it+1] = g[it] + dg
return u, R, g
with plt.xkcd():
_ = my_illus_STD(Poi_or_reg=False, rate=20., U0=0.5, tau_d=100., tau_f=50.)
```
### Parameter Exploration
Below, an interactive demo that shows how Short-term synaptic depression (STD) changes for different firing rate of the presynaptic spike train and how the amplitude synaptic conductance $g$ changes with every incoming spike until it reaches its stationary state.
Does it matter if the neuron fires in a Poisson manner, rather than regularly?
**Note:** `Poi_or_Reg=1`: for *Posisson type* and `Poi_or_Reg=0`: for *regular* presynaptic spikes.
```python
#@title STD Explorer with input rate
def my_STD_diff_rate(rate, Poi_or_Reg):
_ = my_illus_STD(Poi_or_reg=Poi_or_Reg, rate=rate)
_ = widgets.interact(my_STD_diff_rate, rate = (10., 100.1, 5.), Poi_or_Reg = (0, 1, 1))
```
### Synaptic depression and presynaptic firing rate
Once, I asked an experimentalist about the experimental values of the PSP amplitude produced by a connection between two neocortical excitatory neurons. She asked: "At what frequency?" I was confused, but you will understand her question now that you know that PSP amplitude depends on the spike history, and therefore on the spike rate of presynaptic neuron.
Hre, we will study how the ratio of the synaptic conductance corresponding to the first and last spike change as a function of the presynaptic firing rate.
For computational effciency, we assume that the presynaptic spikes are regular. This assumption means that we do not have to run multiple trials.
```python
#@title STD conductance ratio with different input rate
# Regular firing rate
input_rate = np.arange(5., 40.1, 5.)
g_1 = np.zeros(len(input_rate)) # record the the PSP at 1st spike
g_2 = np.zeros(len(input_rate)) # record the the PSP at 10th spike
for ii in range(len(input_rate)):
g_1[ii], g_2[ii] = my_illus_STD(Poi_or_reg=False, rate=input_rate[ii], \
plot_out=False, U0=0.5, tau_d=100., tau_f=50)
plt.figure(figsize=(11, 4.5))
plt.subplot(1,2,1)
plt.plot(input_rate,g_1,'m-o',label = '1st Spike')
plt.plot(input_rate,g_2,'c-o',label = '10th Spike')
plt.xlabel('Rate [Hz]')
plt.ylabel('Conductance [nS]')
plt.legend()
plt.subplot(1,2,2)
plt.plot(input_rate,g_2/g_1,'b-o',)
plt.xlabel('Rate [Hz]')
plt.ylabel(r'Conductance ratio $g_{10}/g_{1}$')
plt.tight_layout()
```
### Parameter Exploration of short-term synaptic facilitation (STF)
Below, we see an illustration of a short-term facilitation example. Take note of the change in the synaptic variables: `U_0`, `tau_d`, and `tau_f`.
- for STD, `U0=0.5, tau_d=100., tau_f=50.`
- for STP, `U0=0.2, tau_d=100., tau_f=750.`
Also notice how the input rate affects the STF.
```python
#@title STF Explorer with input rate
def my_STD_diff_rate(rate, Poi_or_Reg):
_ = my_illus_STD(Poi_or_reg=Poi_or_Reg, rate=rate, U0=0.2, tau_d=100., tau_f=750.)
_ = widgets.interact(my_STD_diff_rate, rate = (4., 40.1, 2.), Poi_or_Reg = (0, 1, 1))
```
### Synaptic facilitation and presynaptic firing rate
Here, we will study how the ratio of the synaptic conductance corresponding to the $1^{st}$ and $10^{th}$ spike changes as a function of the presynaptic rate.
```python
#@title STF conductance ratio with different input rate
# Regular firing rate
input_rate = np.arange(2., 40.1, 2.)
g_1 = np.zeros(len(input_rate)) # record the the PSP at 1st spike
g_2 = np.zeros(len(input_rate)) # record the the PSP at 10th spike
for ii in range(len(input_rate)):
g_1[ii], g_2[ii] = my_illus_STD(Poi_or_reg=False, rate=input_rate[ii], \
plot_out=False, U0=0.2, tau_d=100., tau_f=750.)
plt.figure(figsize=(11, 4.5))
plt.subplot(1,2,1)
plt.plot(input_rate,g_1,'m-o',label = '1st Spike')
plt.plot(input_rate,g_2,'c-o',label = '10th Spike')
plt.xlabel('Rate [Hz]')
plt.ylabel('Conductance [nS]')
plt.legend()
plt.subplot(1,2,2)
plt.plot(input_rate,g_2/g_1,'b-o',)
plt.xlabel('Rate [Hz]')
plt.ylabel(r'Conductance ratio $g_{10}/g_{1}$')
plt.tight_layout()
```
### Think!
Why does the ratio of the first and second-to-last spike conductance changes in a non-monotonic fashion for synapses with STF, even though it decreases monotonically for synapses with STD?
### Conductance-based LIF with STP
Previously, we looked only at how presynaptic firing rate affects the presynaptic resource availability and thereby the synaptic conductance. It is straightforward to imagine that, while the synaptic conductances are changing, the output of the postsynaptic neuron will change as well.
So, let's put the STP on synapses impinging on an LIF neuron and see what happens.
```python
#@title `run_LIF_cond_STP`
def run_LIF_cond_STP(pars, I_inj, pre_spike_train_ex, pre_spike_train_in):
'''
conductance-based LIF dynamics
Expects:
pars : parameter dictionary
I_inj : injected current [pA]. The injected current here can be a value or an array
pre_spike_train_ex : spike train input from presynaptic excitatory neuron (binary)
pre_spike_train_in : spike train input from presynaptic inhibitory neuron (binary)
Returns:
rec_spikes : spike times
rec_v : mebrane potential
gE : postsynaptic excitatory conductance
gI : postsynaptic inhibitory conductance
'''
# Retrieve parameters
V_th, V_reset = pars['V_th'], pars['V_reset']
tau_m, g_L = pars['tau_m'], pars['g_L']
V_init, V_L = pars['V_init'], pars['E_L']
gE_bar, gI_bar = pars['gE_bar'], pars['gI_bar']
U0E, tau_dE, tau_fE = pars['U0_E'], pars['tau_d_E'], pars['tau_f_E']
U0I, tau_dI, tau_fI = pars['U0_I'], pars['tau_d_I'], pars['tau_f_I']
VE, VI = pars['VE'], pars['VI']
tau_syn_E, tau_syn_I = pars['tau_syn_E'], pars['tau_syn_I']
tref = pars['tref']
dt, range_t = pars['dt'], pars['range_t']
Lt = range_t.size
nE = pre_spike_train_ex.shape[0]
nI = pre_spike_train_in.shape[0]
# compute conductance Excitatory synapses
uE = np.zeros((nE, Lt))
RE = np.zeros((nE, Lt))
gE = np.zeros((nE, Lt))
for ie in range(nE):
u, R, g = dynamic_syn(gE_bar, tau_syn_E, U0E, tau_dE, tau_fE,
pre_spike_train_ex[ie, :], dt)
uE[ie, :], RE[ie, :], gE[ie, :] = u, R, g
gE_total = gE.sum(axis=0)
# compute conductance Inhibitory synapses
uI = np.zeros((nI, Lt))
RI = np.zeros((nI, Lt))
gI = np.zeros((nI, Lt))
for ii in range(nI):
u, R, g = dynamic_syn(gI_bar, tau_syn_I, U0I, tau_dI, tau_fI,
pre_spike_train_in[ii, :], dt)
uI[ii, :], RI[ii, :], gI[ii, :] = u, R, g
gI_total = gI.sum(axis=0)
# Initialize
v = np.zeros(Lt)
v[0] = V_init
I = I_inj * np.ones(Lt) #ensure I has length Lt
# simulation
rec_spikes = [] # recording spike times
tr = 0.
for it in range(Lt-1):
if tr >0:
v[it] = V_reset
tr = tr-1
elif v[it] >= V_th: #reset voltage and record spike event
rec_spikes.append(it)
v[it] = V_reset
tr = tref/dt
#calculate the increment of the membrane potential
dv = (-(v[it]-V_L) - (gE_total[it+1]/g_L)*(v[it]-VE) - \
(gI_total[it+1]/g_L)*(v[it]-VI) + I[it]/g_L) * (dt/tau_m)
#update membrane potential
v[it+1] = v[it] + dv
rec_spikes = np.array(rec_spikes) * dt
return v, rec_spikes, uE, RE, gE, RI, RI, gI
```
### Simulation of a postsynaptic neuron with STP synapses driven by Poisson type spike trains
Here we have assumed that both excitatory and inhibitory synapses show short-term depression. Change the nature of synapses and study how spike pattern variability changes.
In the interactive demo, `tau_d = 500*tau_ratio (ms)` and `tau_f = 300*tau_ratio (ms)`.
You should compare the output of this neuron with what you observed in the previous turorial when synapses were assumed to be static.
_Note: it will take slighly longer time to run each case_
```python
#@title LIF_STP Explorer
def LIF_STP(tau_ratio):
pars = default_pars(T=1000)
pars['gE_bar'] = 1.2*4 #[nS]
pars['VE'] = 0. #[mV]
pars['tau_syn_E'] = 5. #[ms]
pars['gI_bar'] = 1.6*4 #[nS]
pars['VI'] = -80. #[ms]
pars['tau_syn_I'] = 10. #[ms]
# here we assume that both Exc and Inh synapses have synaptic depression
pars['U0_E'] = 0.45
pars['tau_d_E'] = 500. * tau_ratio #[ms]
pars['tau_f_E'] = 300. * tau_ratio #[ms]
pars['U0_I'] = 0.45
pars['tau_d_I'] = 500. * tau_ratio #[ms]
pars['tau_f_I'] = 300. * tau_ratio #[ms]
pre_spike_train_ex = Poisson_generator(pars, rate=15, n=80)
pre_spike_train_in = Poisson_generator(pars, rate=15, n=20) # 4:1
v, rec_spikes, uE, RE, gE, uI, RI, gI \
= run_LIF_cond_STP(pars, 0, pre_spike_train_ex, pre_spike_train_in)
t_plot_range = pars['range_t']>200
plt.figure(figsize=(11., 7))
plt.subplot(2,1,1)
plot_volt_trace(pars, v, rec_spikes)
plt.subplot(2,2,3)
plt.plot(pars['range_t'][t_plot_range], gE.sum(axis=0)[t_plot_range], 'r')
plt.xlabel('Time (ms)')
plt.ylabel(r'$g_E$ (nS)')
plt.subplot(2,2,4)
plt.plot(pars['range_t'][t_plot_range], gI.sum(axis=0)[t_plot_range], 'b')
plt.xlabel('Time (ms)')
plt.ylabel(r'$g_I$ (nS)')
plt.tight_layout()
_ = widgets.interact(LIF_STP, tau_ratio = (0.2, 1.1, 0.2))
```
### Optional
Vary the parameters of the above simulation and observe spiking pattern of the postsynaptic neuron.
Will the neuron show higher irregularity if the synapses have STP? If yes, what should be the nature of STP on static and dynamic synapses, respectively?
**Task**: Calculate the CV$_{\rm ISI}$ for different `tau_ratio` after simulating the LIF neuron with STP (Hint:`run_LIF_cond_STP` help you understand the irregularity).
### Functional impliations of short-term dynamics of synapses
As you have seen above, if the firing rate is stationary, the synaptic conductance quickly reaches a fixed point. On the other hand, if the firing rate transiently changes, synaptic conductance will vary -- even if the change is as short as a single inter-spike-interval. Such small changes can be observed in a single neuron when input spikes are regular and periodic. If the input spikes are Poissonian then one may have to perform an average over several neurons.
_Come up with other functions that short-term dynamics of synapses can be used to implement and implement them._
## Summary
Congratulations! You have just finished the Tutorial 3 (one to go!). Here, we saw how to model conductance-based synapses and also how to incorporate their short-term dynamics.
We covered the:
- static synapses and how excitation and inhibition affect the neuronal output
- mean- or fluctuation-driven regimes
- short-term dynamics of synapses (both facilitation and depression)
Finally, we incorporated all the aforementioned tools to study how a change in presynaptic firing history affects the synaptic weights!
Next, you will learn about another form of synaptic plasticity based on both pre- and postsynaptic spike times.
|
-- Andreas, 2012-09-15
-- Positive effects of making Agda recognize constant functions.
-- Arguments to constant functions are ignored in definitional equality.
{-# OPTIONS --copatterns #-}
module NonvariantPolarity where
open import Common.Equality
data ⊥ : Set where
record ⊤ : Set where
constructor trivial
data Bool : Set where
true false : Bool
True : Bool → Set
True true = ⊤
True false = ⊥
module IgnoreArg where
-- A function ignoring its first argument
knot : Bool → Bool → Bool
knot x true = false
knot x false = true
test : (y : Bool) → knot true y ≡ knot false y
test y = refl
module UnusedModulePar where
-- An unused module parameter
module M (x : Bool) where
not : Bool → Bool
not true = false
not false = true
open M true
open M false renaming (not to not′)
test : (y : Bool) → not y ≡ not′ y
test y = refl
module Absurd where
-- Absurd patterns do not count as matches; abort is constant in its 2nd arg.
abort : (A : Set) → ⊥ → A
abort A ()
test : (x y : ⊥) → abort Bool x ≡ abort Bool y
test x y = refl
module ProofIrrelevance where
-- Record and absurd patterns do not count as match.
fun : (b : Bool) → True b → Bool
fun true trivial = true
fun false ()
-- This gives us a kind of proof irrelevance.
test : (b : Bool) → (x y : True b) → fun b x ≡ fun b y
test b x y = refl
module CoinductiveUnit where
record Unit : Set where
coinductive
constructor delay
field force : Unit
open Unit
-- The identity on Unit does not match on its argument, so it is constant.
id : Unit → Unit
force (id x) = id (force x)
idConst : (x y : Unit) → id x ≡ id y
idConst x y = refl
-- That does not imply x ≡ y (needs bisimulation).
|
In the Republic of Ireland , counties form the basis of the system of local government . Counties Dublin , Cork , Limerick , Galway , Waterford and Tipperary have been broken up into smaller administrative areas . However , they are still treated as counties for cultural and some official purposes , for example postal addresses and by the Ordnance Survey Ireland . Counties in Northern Ireland are no longer used for local governmental purposes , but , as in the Republic , their traditional boundaries are still used for informal purposes such as sports leagues and in cultural or tourism contexts .
|
# -*- coding: utf-8 -*-
"""
Class providing graphical display and, optionally, a control interface
"""
from __future__ import print_function, division, unicode_literals
from __future__ import absolute_import
import numpy as np
import time
import sys
import multiprocessing as mp
import matplotlib
from PyQt5 import QtWidgets, QtGui, QtCore
matplotlib.use('Qt5Agg')
from PyQt5.QtWidgets import QMainWindow, QDesktopWidget, QPushButton, QLabel, QFileDialog # noqa: E402
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas # noqa: E402
import matplotlib.animation as anim # noqa: E402
class Display(QMainWindow):
"""
QWidget to display a dynamic matplotlib.pyplot in it
"""
def __init__(self, interval=0.1, config_dict=None, cmd_queue=None, data_queue=None):
"""
:argument:
interval: logging interval, eventually overwritten by entry in config_dict
config_dict: dictionary with configuration
cmd_queue: multiprocessing Queue for command transfer to caller
data_queue: multiprocessing Queue for data transfer
"""
# Setup a basic window
super().__init__()
self.setWindowTitle("PhyPiDAQ Display")
self.setMinimumSize(600, 300)
# Center the window on the window
qr = self.frameGeometry()
cp = QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
self._main = QtWidgets.QWidget()
self.setCentralWidget(self._main)
layout = QtWidgets.QVBoxLayout(self._main)
self.button_layout = QtWidgets.QHBoxLayout()
# Setup configuration
self.cmd_queue = cmd_queue
# Check if the data_queue is initialised and create one, if it is none
if data_queue is None:
self.data_queue = mp.Queue(1)
else:
self.data_queue = data_queue
if config_dict is not None:
self.config_dict = config_dict
else:
self.config_dict = {}
# Define an empty animation
self.animation = None
# Set default options for graphical display
if 'Interval' not in self.config_dict:
self.config_dict['Interval'] = interval
else:
interval = self.config_dict['Interval']
if interval < 0.05:
print(" !!! read-out intervals < 0.05 s not reliable, setting to 0.05 s")
self.config_dict['Interval'] = 0.05
interval = 0.5
self.interval = interval
# XY mode is by default off
if 'XYmode' not in self.config_dict:
self.config_dict['XYmode'] = False
# The default display is DataLogger
if 'DisplayModule' not in self.config_dict:
self.config_dict['DisplayModule'] = 'DataLogger'
# Default mode is paused
if 'startActive' not in self.config_dict:
self.config_dict['startActive'] = False
# No run control buttons by default
if 'DAQCntrl' not in self.config_dict:
self.config_dict['DAQCntrl'] = False
# Set channel properties
if 'NChannels' not in self.config_dict:
self.config_dict['NChannels'] = 1
NC = self.config_dict['NChannels']
if 'ChanLimits' not in self.config_dict:
self.config_dict['ChanLimits'] = [[0., 5.]] * NC
if 'ChanNams' not in self.config_dict:
self.config_dict['ChanNams'] = [''] * NC
if 'ChanUnits' not in self.config_dict:
self.config_dict['ChanUnits'] = ['V'] * NC
if 'ChanLabels' not in self.config_dict:
self.config_dict['ChanLabesl'] = [''] * NC
# Name of the display module
module_name = self.config_dict['DisplayModule']
# TODO: Check if there are safer ways for doing this
# import relevant library
try:
command = 'from .' + module_name + ' import *'
exec(command, globals(), locals())
except Exception as e:
print(' !!! Display: failed to import module - exiting')
print(str(e))
sys.exit(1)
try:
command = 'global DG; DG = ' + module_name + '(self.config_dict)'
exec(command, globals(), locals())
except Exception as e:
print(' !!! Display: failed to initialize module - exiting')
print(str(e))
sys.exit(1)
# Init the imported display module
DG.init()
# Get the figure from the display module and add it to the widget of the window
dynamic_canvas = FigureCanvas(DG.fig)
layout.addWidget(dynamic_canvas)
layout.addLayout(self.button_layout)
self.figure = DG.fig
button_h = 24
button_w = 100
if self.config_dict['startActive']:
self.button_resume = QPushButton("&Resume")
else:
self.button_resume = QPushButton("&Run")
self.button_resume.clicked.connect(self.cmd_resume)
self.button_resume.setFixedHeight(button_h)
self.button_resume.setFixedWidth(button_w)
self.button_resume.setShortcut('Shift+r')
self.button_resume.setShortcut('r')
self.button_pause = QPushButton("&Pause")
self.button_pause.clicked.connect(self.cmd_pause)
self.button_pause.setFixedHeight(button_h)
self.button_pause.setFixedWidth(button_w)
self.button_pause.setShortcut('Shift+p')
self.button_save_data = QPushButton("&Save Data")
self.button_save_data.clicked.connect(self.cmd_save_data)
self.button_save_data.setFixedHeight(button_h)
self.button_save_data.setFixedWidth(button_w)
self.button_save_data.setShortcut('S')
self.button_save_graph = QPushButton("&save Graph")
self.button_save_graph.clicked.connect(self.cmd_save_graph)
self.button_save_graph.setFixedHeight(button_h)
self.button_save_graph.setFixedWidth(button_w)
self.button_save_graph.setShortcut('s')
self.button_end = QPushButton("&End")
self.button_end.clicked.connect(self.cmd_end)
self.button_end.setFixedHeight(button_h)
self.button_end.setFixedWidth(button_w)
self.button_end.setShortcut('Shift+e')
self.button_end.setShortcut('e')
# Create a label for the passed time
self.time_label = QLabel("0s")
self.time_label.setFixedHeight(button_h)
self.time_label.setFixedWidth(button_w)
self.lagging_label = QLabel('')
self.lagging_label.setStyleSheet("color: red")
self.lagging_label.setFixedHeight(button_h)
self.lagging_label.setFixedWidth(button_w)
# Set the start time to a default value
self.start_time = QtCore.QDateTime.currentSecsSinceEpoch()
self.timer = QtCore.QTimer(self)
self.timer.setInterval(1000)
self.timer.timeout.connect(self.display_time)
# Start automatically, if there are no controls
self.started = False
if self.config_dict['DAQCntrl'] is False:
self.button_layout.addWidget(self.time_label)
self.button_layout.addWidget(self.lagging_label)
self.cmd_start()
else:
# Add the buttons to the layout
self.button_layout.addWidget(self.button_resume,
alignment=QtCore.Qt.AlignLeft)
self.button_layout.addWidget(self.button_pause,
alignment=QtCore.Qt.AlignLeft)
self.button_layout.addWidget(self.button_save_data,
alignment=QtCore.Qt.AlignLeft)
self.button_layout.addWidget(self.button_save_graph,
alignment=QtCore.Qt.AlignLeft)
self.button_layout.addWidget(self.button_end,
alignment=QtCore.Qt.AlignLeft)
self.button_layout.addWidget(self.time_label,
alignment=QtCore.Qt.AlignLeft)
self.button_layout.addWidget(self.lagging_label,
alignment=QtCore.Qt.AlignRight)
if self.config_dict['startActive']:
# Start the display
self.cmd_start()
else:
# Disable all buttons except the Run/Resume button
self.button_resume.setEnabled(True)
self.button_pause.setEnabled(False)
self.button_save_data.setEnabled(False)
self.button_save_graph.setEnabled(False)
self.button_end.setEnabled(False)
def cmd_start(self):
self.started = True
# Disable the Run/Resume button and rename it from Run to Resume
self.button_resume.setEnabled(False)
self.button_resume.setText("&Resume")
self.button_resume.setShortcut('Shift+r')
self.button_resume.setShortcut('r')
# Enable all others buttons
self.button_pause.setEnabled(True)
self.button_save_data.setEnabled(True)
self.button_save_graph.setEnabled(True)
self.button_end.setEnabled(True)
if self.config_dict['startActive'] is False:
# If the data acquisition wasn't active on window creation, then start it
self.cmd_queue.put('R')
# Set the start time
self.start_time = QtCore.QDateTime.currentSecsSinceEpoch()
# Start the timer to display the time
self.timer.start()
def yield_event_from_queue():
# Receive data via a Queue from package multiprocessing
cnt = 0
lagging = False
timestamp_last = time.time()
while True:
if not self.data_queue.empty():
data = self.data_queue.get()
if type(data) != np.ndarray:
break # Received end event
cnt += 1
yield cnt, data
else:
yield None # Send empty event if no new data
# Check timing precision
timestamp = time.time()
delta_time = timestamp - timestamp_last
if delta_time - self.interval < self.interval * 0.01:
if lagging:
lagging = False
self.lagging_label.setText('')
else:
if not lagging:
lagging = True
self.lagging_label.setText('! lagging !')
# Update the timestamp
timestamp_last = timestamp
# End of yieldEvt_fromQ
sys.exit()
self.animation = anim.FuncAnimation(DG.fig, DG, yield_event_from_queue,
interval=50, repeat=True, blit=True)
def cmd_end(self):
self.cmd_queue.put('E')
def cmd_pause(self):
self.cmd_queue.put('P')
self.button_pause.setEnabled(False)
self.button_resume.setEnabled(True)
# Stop the timer
self.timer.stop()
def cmd_resume(self):
if self.started:
self.cmd_queue.put('R')
self.button_resume.setEnabled(False)
self.button_pause.setEnabled(True)
# Reset the start time and restart the time
self.start_time = QtCore.QDateTime.currentSecsSinceEpoch()
self.time_label.setText("0s")
self.timer.start()
else:
self.cmd_start()
def cmd_save_data(self):
self.cmd_queue.put('s')
# Pause the plotting
self.cmd_pause()
def cmd_save_graph(self):
# Pause the plotting
self.cmd_pause()
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
file_name, _ = QFileDialog.getSaveFileName(self, "Save Graph", "plot.png", "PNG (*.png);;JPG (*.jpg *.jpeg)",
options=options)
if file_name:
if not (file_name.endswith(".png") or file_name.endswith(".jpg") or file_name.endswith(".jpeg")):
# If the file extension doesn't match or isn't set, add it
file_name = file_name + ".png"
try:
self.figure.savefig(file_name)
except Exception as e:
print(str(e))
pass
else:
print("Aborting graph saving as no file was selected")
def display_time(self):
"""
Method to update the passed time on the time label
:return: None
"""
diff = QtCore.QDateTime.currentSecsSinceEpoch() - self.start_time
self.time_label.setText(f"{diff}s")
def closeEvent(self, event: QtGui.QCloseEvent) -> None:
"""
Overriding the QMainWindow.closeEvent to handle the situations, when the users wants to close the window using
the default window button.
For further information on this method see:
https://stackoverflow.com/questions/9249500/pyside-pyqt-detect-if-user-trying-to-close-window
:param event: QtGui.QCloseEvent passed from the QApplication
:return: None
"""
self.cmd_end()
event.accept()
def close_display(self):
"""
Method to close the window
:return: None
"""
self.close()
|
Sorry… No latest news for rebels+REDS Artist TBA.
Never overpay for rebels+REDS Artist TBA tickets again!
Check CHARGED to stay up to date on rebels+REDS Artist TBA tickets! |
library(shiny)
library(shinydashboard)
shinyServer(
function(input, output) {
}
) |
# <p style="text-align: center;"> NISQAI: One-Qubit Quantum Classifier </p>
<p style="text-align: center;"> Ryan LaRose, Yousif Almulla, Nic Ezzell, Joe Iosue, Arkin Tikku </p>
<blockquote cite="">
"Quantum computing needs more quantum software engineers to implement, test, and optimize quantum algorithms."
-- Matthias Troyer.
</blockquote>
<blockquote cite="">
"Experimentation on quantum testbeds is needed." -- John Preskill.
</blockquote>
# What is NISQAI?
Quantum machine learning is an exciting but conjectural field that lacks testing on quantum computers. NISQAI is a library written to facilitate research in artificial intelligence on current quantum computers and NISQ (noisy intermediate-scale quantum) devices.
In this notebook, we demonstrate the steps toward a quantum neural network working as a simple classifier. We then demonstrate how easily the NISQAI library can facilitate this task.
# Requirements for this Notebook
Since you're reading this, you probably have a working installation of [Python](https://www.python.org/) and/or [Jupyter](http://jupyter.org/). In order to run this notebook, the following external packages are necessary. Installation instructions can be found by following the hyperlinks for each.
* [NumPy](http://www.numpy.org/)
* [SciPy](https://www.scipy.org/)
* [pyQuil](https://pyquil.readthedocs.io/en/stable/) >= v2.4.0.
* [Matplotlib](https://matplotlib.org/)
* [QuTiP](http://qutip.org/docs/4.1/index.html) (only for Bloch sphere visualization features)
Requires: Rigetti `qvm` to be running. This is commonly done by executing `qvm -S` in a terminal.
```python
# builtins
import time
# standard imports
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import minimize
# library imports
from pyquil import Program, get_qc
from pyquil import api
import pyquil.gates as ops
from qutip import Bloch, ket
# option for inline plotting
%matplotlib inline
```
# Quantum Neural Networks: A Five Step Process
To implement a neural network for classical data on a quantum computer (i.e., a _quantum neural network_), the following steps need to be performed.
1. Data encoding.
* Encode the classical data into a form suitable for the quantum circuit.
1. State preparation.
* Implement a quantum circuit preparing the state of a particular datum.
1. Unitary evolution.
* Implement a parameterized gate sequence to transform the data.
1. Measurement/non-linearity.
* Measure the state of the quantum data after unitary evolution to revert back to classical information. * Non-linearity can be introduced at this point via classical processing.
1. Training/cost function.
* Define a cost function and optimize the parameters of the unitary to minimize the cost.
In the rest of the notebook, we'll go over how to do each of these steps in turn for a simple classification problem. At the end of the notebook, we'll show how easily this can be done with the NISQAI library and discuss other features of NISQAI.
# Problem Description
The specific problem we look it in this notebook falls under the category of _supervised machine learning_. Specifically, we ask:
_Given $N$ data points $p = (x, y) \in \mathbb{R}^2$ with labels $z(p) = 1$ if $x \le 0.5$ and $z(p) = 0$ otherwise, learn the decision boundary and classify new points._
## 1. Data Encoding
In order to run a quantum neural network on classical data, the classical data needs to be suitably encoded to allow it to be "uploaded" to a quantum computer. We demonstrate a simple encoding scheme below for $(x, y)$ Cartesian coordinates distributed uniformly in a unit square.
### Generating data
First we generate a random set of classical data. For reproducibility, we'll seed our random number generator.
```python
# set random seed for reproducible results
SEED = 1059123109
np.random.seed(seed=SEED)
```
```python
# generate data points distributed uniformly at random in [0, 1) x [0, 1)
npoints = 100
data = np.random.rand(npoints, 2)
def predicate(point):
"""Returns true if the point satisfies the predicate, else false."""
return True if point[0] <= 0.5 else False
# separate the data with a linear boundary y = x
labels = np.array([1 if predicate(p) else 0 for p in data])
# plot the line y = x
xs = np.linspace(0, 1, 100)
ys = 0.5 * np.ones_like(xs)
plt.plot(ys, xs, '--k')
# plot the data with the color key BLUE = 0 = LEFT, GREEN = 1 = RIGHT
for i in range(npoints):
if labels[i] == 0:
ckey = 'g'
else:
ckey = 'b'
plt.scatter(data[i, 0], data[i, 1], color=ckey)
# title and axis lables
plt.title("Random Data Points in Unit Square", fontweight="bold", fontsize=16)
# put on a grid and show the plot
plt.grid()
plt.show()
```
### Qubit Encoding
Here we implement a method of data encoding that we call "qubit encoding." Qubit encoding works by writing two bits of classical information into one bit of quantum information. How is this done? Note that any qubit can be written
\begin{equation}
|\psi\rangle = \alpha |0\rangle + \beta |1\rangle
\end{equation}
where $\alpha, \beta \in \mathbb{C}$ satisfying $|\alpha|^2 + |\beta|^2 = 1$. Because of this normalization condition, we may equivalently write
\begin{equation}
|\psi\rangle = \cos(\theta / 2) |0\rangle + e^{i \phi} \sin(\theta / 2)|1\rangle
\end{equation}
We then encode information into the phases $0 \le \theta \le \pi$ and $ 0 \le \phi \le 2 \pi$.
For the $(x, y)$ coordinates of our points, we will use the encoding
\begin{align}
\theta &= \pi x \\
\phi &= 2 \pi y
\end{align}
This is a simple encoding, but the results of the classification will speak to it's effectivenss. Other encodings, for example
\begin{align}
\theta &= \frac{1}{2} \tan^{-1}\left( \frac{y}{x} \right) \\
\phi &= \pi (x^2 + y^2),
\end{align}
can be used for other data sets.
In code, we may make this transformation as follows:
```python
# encode the classical data via a simple linear "qubit encoding"
qdata = np.zeros_like(data)
for (index, point) in enumerate(data):
qdata[index][0] = np.pi * point[0]
qdata[index][1] = 2 * np.pi * point[1]
```
It's now possible to visualize the data as points on the surface of the Bloch sphere.
```python
# empty lists to store values
gxs = []
gys = []
gzs = []
bxs = []
bys = []
bzs = []
# loop over all points, convert to cartesian coords, and append to correct list
for (index, point) in enumerate(qdata):
theta = point[0]
phi = point[1]
sin = np.sin(theta)
# convert to cartesian coords for plotting
x = np.sin(theta) * np.cos(phi)
y = np.sin(theta) * np.sin(phi)
z = np.cos(theta)
if labels[index] == 0:
gxs.append(x)
gys.append(y)
gzs.append(z)
else:
bxs.append(x)
bys.append(y)
bzs.append(z)
# format points correctly for bloch sphere
lpoints = [gxs, gys, gzs]
rpoints = [bxs, bys, bzs]
# get a Bloch sphere
bloch = Bloch()
# options for Bloch sphere
bloch.frame_color = "grey"
bloch.sphere_color = "white"
bloch.point_size = [40]
bloch.sphere_alpha = 0.50
bloch.point_color = ["g", "b"]
bloch.point_marker = ["o"]
bloch.view = [-55, 10]
# add the points on the Bloch sphere
bloch.add_points(lpoints)
bloch.add_points(rpoints)
# show the Bloch sphere
bloch.show()
```
## 2. State Preparation
Now that we have encoded our data, we still need to prepare it in quantum form. Conventionally, all qubits start in the $|0\rangle$ state. The problem we have to solve is:
Given angles $\theta, \phi$, perform the mapping
\begin{equation}
S(\theta, \phi) |0\rangle \rightarrow |\psi\rangle = \cos(\theta / 2) |0\rangle + e^{i \phi} \sin(\theta / 2)|1\rangle
\end{equation}
We call $S$ a _state preparation unitary_ or _state preparation circuit_.
It is clear from the equation above that the matrix representation for $S$ in the computational basis is
\begin{equation}
S(\theta, \phi) = \left[ \begin{matrix}
\cos(\theta / 2) & e^{-i \phi} \sin(\theta / 2)\\
e^{i \phi} \sin(\theta / 2) & - \cos(\theta / 2) \\
\end{matrix} \right]
\end{equation}
On current NISQ computers, circuits need to be as short-depth as possible, meaning they contain as few gates as possible. The "qubit encoding" performed above allows for a constant-depth state preparation circuit for any given values of $\theta, \phi$.
Why is this? In general we need to perform some arbitrary unitary transformation $S \in SU(2)$. It is known that such a unitary can be implemented with five standard rotations that can be implemented by current quantum computers. Namely,
\begin{equation}
S = R_z(\gamma_1) R_x(\pi / 2) R_z(\gamma_2) R_x(\pi / 2) R_z(\gamma_3)
\end{equation}
where $0 \le \gamma_i \le 2 \pi$ for $i = 1, 2, 3$. We can define our gate $S$ above in pyquil and compile it to a sequence of five implementable rotations by using the Quil compiler. First we'll write a function to give us our state preparation matrix.
```python
# define the matrix S as a function of theta and phi
def state_prep_mtx(theta, phi):
"""Returns the state preparation matrix according to the qubit encoding above."""
return np.array([[np.cos(theta / 2), np.exp(-1j * phi) * np.sin(theta / 2)],
[np.exp(1j * phi) * np.sin(theta / 2), - np.cos(theta / 2)]])
```
Next we'll define this as a pyquil gate. We do this by first making a program then defining a gate for a particular encoded data point.
```python
# get a pyquil program
qprog = Program()
# pick a particular encoded data point
theta, phi = qdata[0]
# get the state prep matrix for this point
S = state_prep_mtx(theta, phi)
# define a gate in pyquil for the state preparation
qprog.defgate("S", state_prep_mtx(theta, phi))
```
<pyquil.quil.Program at 0x7fe51b70bcc0>
We can now use this gate in a quantum program to input our classical data into the quantum computer. To do this, we simply write:
```python
# prepare the first encoded data point in quantum form
qprog += ("S", 0)
```
To see our program, we can print it out:
```python
print(qprog)
```
DEFGATE S:
0.0767318819324465, 0.7019079174828263-0.7081225131783532i
0.7019079174828263+0.7081225131783532i, -0.0767318819324465
S 0
If we measure this qubit now, we get either a zero or a one with probability proportional to it's amplitudes. We'll add this measurement to our program and then run it many times to get an estimate of the probability distribution of it's outcome.
```python
# run the program many times
shots = 1000
qvm = get_qc('1q-qvm') # connect to QVM with 2 quibts
dist = qvm.run_and_measure(qprog, shots)
```
```python
%matplotlib inline
def histogram(dist):
"""Makes a histogram of the probability of obtaining 0 and 1."""
# get the zero and one probabilities
f0 = lambda x: x==0
f1 = lambda x: x==1
prob0 = len(list(filter(f0, dist[0]))) / shots
prob1 = len(list(filter(f1, dist[0]))) / shots
# make a bar plot
plt.bar([0, 1], [prob0, prob1])
# make it look nice
plt.grid()
plt.title("Output Probability Distribution", fontsize=16, fontweight="bold")
plt.xlabel("Measurement Outcomes", fontsize=14)
plt.ylabel("Probability", fontsize=14)
plt.ylim(0, 1)
plt.xticks([0, 1])
# show it
plt.show()
# make a histrogram of the output distribution
histogram(dist)
```
We want our output distribution to move towards either zero or one, depending on what label is assigned to that particular data point. To do this, we implement unitary evolution on the circuit, which corresponds to implementing another sequence of gates in our circuit.
## 3. Unitary Evolution
After the classical data has been encoded (step 1) and prepared into the quantum system (step 2), step 3 is to perform unitary evolution on the quantum state representing the data. In the language of classical learning theory, this corresponds to implementing a layer of the neural network.
In the quantum neural network case, we simply need to implement a sequence of parameterized gates.
First we write a function to easily implement such a unitary.
```python
def unitary(angles):
"""Returns a circuit implementing the unitary Rz(theta0) P Rz(theta1) P Rz(theta2)
where thetea0 = angles[0], theta1 = angles[1], and theta2 = angles[2] and
P = Rx(pi / 2) is a pi / 2 pulse.
"""
return Program(
ops.RZ(angles[0], 0),
ops.RX(np.pi / 2, 0),
ops.RZ(angles[1], 0),
ops.RX(np.pi / 2, 0)
)
```
Next we use it to add unitary evolution to our quantum neural network for some given angles.
```python
# test angles
angles = 2 * np.pi * np.random.rand(2)
# append the unitary circuit to our quantum neural network program
qprog += unitary(angles)
```
```python
print(qprog)
```
DEFGATE S:
0.0767318819324465, 0.7019079174828263-0.7081225131783532i
0.7019079174828263+0.7081225131783532i, -0.0767318819324465
S 0
RZ(0.3142835597303074) 0
RX(pi/2) 0
RZ(4.277790366298182) 0
RX(pi/2) 0
Now we'll run this new circuit with the unitary evolution implemented.
```python
# run the quantum neural network program
histogram(qvm.run_and_measure(qprog, shots))
```
Now we want to use this unitary evolution to move our output probability towards the desired label. We'll suppose for a moment that this point is supposed to be mapped to the 0 output. We'll define an objective function ```obj_simple(angles)``` to capture the amount of 1 outputs, then we'll train over the angles in the unitary to minimize the objective.
```python
def make_program(pangles, uangles):
"""Returns a pyquil program that prepares the state according
to pangles and applies the unitary according to uangles.
"""
# instantiate a program
qprog = Program()
# define a gate in pyquil for the state preparation
qprog.defgate("S", state_prep_mtx(pangles[0], pangles[1]))
# write the program
qprog += [("S", 0),
unitary(uangles)]
return qprog
def obj_simple(angles, shots=1000, verbose=False):
"""Returns the number of zero outputs of a single training example."""
# make the program
qprog = make_program([theta, phi], angles)
if verbose:
print(qprog)
dist = qvm.run_and_measure(qprog, shots)
f1 = lambda x: x == 1
obj = len(list(filter(f1, dist[0]))) / shots
print("The current value of the objective function is:", obj, end="\r")
return obj
```
Now we'll minimize the objective function `obj_simple` by using the modifed `Powell` algorithm builtin to SciPy. The minimization here should take no more than 30 seconds.
```python
out = minimize(obj_simple, x0=2 * np.pi * np.random.rand(2), method="Powell")
```
The current value of the objective function is: 0.001
Now we can verify that the output distribution skews this point towards the "zero bin."
```python
# do the circuit (neural network) with the optimal parameters
opt_angles = out['x']
qprog = make_program([theta, phi], opt_angles)
# show the output distribution
dist = qvm.run_and_measure(qprog, shots)
histogram(dist)
```
Indeed it does! Here we demonstrated that we can use our neural network to "steer" a point in a particular direction. The idea of training is to "steer" _all_ points in the desired direction. Before we train our quantum neural network, we first discuss the measurement process and it's importance in quantum neural network implementations.
## 4. Measurement
Measurement is used in our circuit above to translate from quantum to classical information. In other quantum neural networks, measurement can be used to introduce non-linearity.
NISQAI treats measurements as both a way to keep circuit-depth low (for implementations on current/near-term quantum computers) as well as introduce non-linearity between layers of a network. Specifically, measuremnets lead to (intermediate) classical data. On a classical computer, we can introduce any non-linear activation function we wish. The new classical data from the output of the activation function can then be prepared into quantum form again via steps 1 and 2 (data encoding and state preparation).
This intermediate classical post-processing is a trademark of NISQAI. It allows for:
1. Short-depth circuits suitable for NISQ computers.
1. Non-linearity between layers of a quantum neural network.
1. Deep learning (many layers) with shallow circuits.
In this simple binary classifier example, we'll restrict to just one layer of the neural network for simplicity.
## 5. Training
We saw above that it's easy to steer one point towards the output we want to get. But training the quantum neural network involves training over all points in the training set. For this, we need to define a cost function that captures the total loss over the entire training set.
To do this, define the _indicator function_ $I(z_i = \hat{z}_i)$ to be 0 if $z_i = \hat{z}_i$ and 1 otherwise. Here, $z_i$ is the exact label of the $i$th training data $(x_i, y_i)$ and $\hat{z}_i$ is the prediction of this label by our neural network. (In code, we use the variables `labels` for $z_i$ and `predictions` for $\hat{z}_i$.)
To define the cost now, we simply sum over all points (say there are $M$ points) in the training data:
\begin{equation}
C = \sum_{i = 1}^{M} I(z_i = \hat{z}_i)
\end{equation}
Note that the cost $C$ depends on the unitary evolution $U$, i.e. $C = C(U)$, because the prediction $\hat{z}_i$ depends on $U$.
We now need to define a cost (objective) function ```obj(...)``` that takes into account all data in the training set. This function will encapsulate everything we've done for a single training point, but now for all of them.
```python
# fraction of total data to use as training data
train_frac = 0.7
def obj(uangles):
"""Returns the objective function C defined above over all training data.
Args:
uangles [type: list<float>]
the angles in the unitary evolution.
rtype: float
"""
# grab some training data from the overall data set
tpoints = int(train_frac * len(qdata))
tdata = qdata[:tpoints]
tlabels = labels[:tpoints]
# initialize a variable to store the output predictions of the neural net
predictions = np.zeros_like(tlabels, dtype=int)
# loop over all training data to get the predictions
for i, pangles in enumerate(tdata):
# write the program
qprog = make_program(pangles, uangles)
# run the program
out = qvm.run_and_measure(qprog, 1000)
# get the output probabilities
f0 = lambda x: x==0
f1 = lambda x: x==1
p0 = len(list(filter(f0, out[0]))) / shots
p1 = len(list(filter(f1, out[0]))) / shots
# take the prediction to be max(p0, p1)
if p0 >= p1:
predictions[i] = 0
else:
predictions[i] = 1
# compute the difference of the labels and return the cost
cost = sum(abs(predictions - tlabels)) / tpoints
print("The current value of the cost function is:", cost, end="\r")
return cost
```
Now let's compute the objective function for some random test angles.
```python
# get some random angles
angs = 2 * np.pi * np.random.rand(2)
cost = obj(angs)
```
The current value of the cost function is: 0.24285714285714285
We don't want just any random angles for our unitary evolution, however. We want to compute the optimal angles, which we can do by minimizing the cost function. Again we'll use the modified ```Powell``` algorithm for minimization.
Training the neural network here will take more time than simply optimizing the output of a single point. On our computer, it takes around 15 seconds to evaluate the objective function for one set of angles. The `Powell` optimization algorithm generally takes on the order of 20-30 cost function evaluations--for us the optimization takes around 15 minutes on average. You can expect this training to take 15-20 minutes.
If you're in a hurry and don't want to wait for this training, we've saved a set of optimal angles from previous attempts. These angles are for a horizontal boundary $x = 0.5$ trained on 70/100 data points. They will only be optimal for the first set of random points generated by the given seed. We reiterate: _Only use these angles if you haven't changed anything in the notebook and only ran each cell once!_
```python
optimal_angles = [0.0, 0.0]
```
If you chose to skip the training, you should *not* execute the next two cells. Otherwise, continue through the notebook.
```python
# train the quantum neural network and time how long it takes
start = time.time()
out = minimize(fun=obj, x0=angs, method="Powell")
print("\nTotal training runtime took {} minutes.".format((time.time() - start) / 60))
```
The current value of the cost function is: 0.014285714285714285
Total training runtime took 8.968616827328999 minutes.
```python
# grab the optimal angles and minimal cost value
optimal_angles = out['x']
fval = out['fun']
# print them out
print(fval)
print(optimal_angles)
```
0.0
[0.32186503 0.17768155]
## Results
Now that we've trained on a subset of our data, we can see how the predictions do on the whole dataset.
First, we'll write a function that performs this task.
```python
def get_all_predictions(angles):
"""Returns a numpy array of all predictions."""
# initialize a variable to store the output predictions of the neural net
zhats = np.zeros_like(labels, dtype=int)
# loop over all data to get predictions
for i, pangles in enumerate(qdata):
# write the program
qprog = make_program(pangles, angles)
# run the program
out = qvm.run_and_measure(qprog, 1000)
# get the output probabilities
f0 = lambda x: x==0
f1 = lambda x: x==1
p0 = len(list(filter(f0, out[0]))) / shots
p1 = len(list(filter(f1, out[0]))) / shots
# take the prediction to be max(p0, p1)
if p0 >= p1:
zhats[i] = 0
else:
zhats[i] = 1
return zhats
```
Then we'll call the function to get the results.
```python
# compute all the predictions of the quantum neural network
predictions = get_all_predictions(optimal_angles)
```
We have now trained our neural network and classifeid all data points. Let's display the statistics below to see how our QNN performed.
```python
# compute statistics of the QNN
ntrain = int(train_frac * npoints)
ncorrect = npoints - sum(abs(predictions - labels))
acc = ncorrect / npoints * 100
# print them out
print(" Results of quantum neural network classification ".center(80, "="))
print("Out of {} total data points:".format(npoints))
print("The QNN was trained on {}% of the total data ({} training points).".format(train_frac * 100, ntrain))
print("The QNN classified {} data points correctly ({}% accuracy).".format(ncorrect, acc))
print("".center(80, "="))
# plot the points, line y = x, and prediction
plt.plot(ys, xs, '--k')
for i in range(npoints):
if predictions[i] == 0:
ckey = 'g'
else:
ckey = 'b'
plt.scatter(data[i, 0], data[i, 1], color=ckey)
plt.grid()
plt.title("QNN Predictions", fontsize=16, fontweight="bold")
plt.show()
```
# Discussion of Results
How did your quantum neural network perform? If you followed through this notebook sequentially, you should have seen 100% accuracy in the predictions of the network. A saved plot of our results obtained by running this notebook is included below:
Here, the exact decision boundary (not the learned one) is shown in the plot, and data points are colored according to the quantum neural network predictions. Blue means predicted left of the boundary (0 bin), and green means predicted right of the boundary (1 bin). As can be seen in our example results, all data points are correctly classified.
# Example Done with NISQAI
The above example involved five steps to implementing a neural network on a quantum computer. While the steps aren't hard, programming each one for every particular example is tedious and time consuming. More time could be spent testing quantum neural networks if there were a library to implement all of these steps.
This is where NISQAI comes in. NISQAI is to quantum machine learning what TensorFlow/pyTorch is to classical machine learning. Just like OpenFermion provides a library of code to simplify quantum chemistry on quantum computers, NISQAI provides a library of code to simplify neural networks and other machine learning algorithms on quantum computers.
The above classifier example in NISQAI could be done with the following few lines of code. Here, we assume that ```classical_data``` exists in the program.
## Prototype NISQAI Code
```
# imports
from nisqai import qnn
# get a quantum neural network
network = qnn.qnn(nodes=1, layers=1)
# encode the classical data into quantum form
network.encode(data=classical_data, scheme=qnn.encoding_schemes.SIMPLE_LINEAR)
# add the unitary evolution
network.add_unitary(qnn.ansatze.UNIVERSAL)
# add measurements to the network
network.add_measurements(basis=qnn.bases.Z)
# do the training on 70% of the total data
network.train(optimizer="Powell", fraction=0.7)
# test the neural network on all the data or on new input data
statistics = network.classify()
```
These few lines of code show the power of NISQAI. One of it's greatest strengths is the flexibility to research other quantum neural network implementations, not just the one qubit quantum classifier.
## Features of NISQAI
* Shatters domain barriers.
* Whether you're a machine learning researcher interested in quantum or a quantum researcher interested in machine learning, NISQAI is built for you.
* Powerful builtins.
* Numerous prototypes of quantum neural network architectures, including methods for data encoding, state preparation, unitary evolution, measurement, and training.
* Fully modular.
* For methods like `qnn.add_unitary(...)`, the user can write a function to specify whichever unitary ansatz is desired.
* Loaded with examples.
* Many instructive code snippets and notebooks to get you started in quantum machine learning.
* Open-source.
* NISQAI is currently under development with expected release in early 2019. After this, NISQAI will be free and open-source. Always.
* Cross platform.
* NISQAI works for Windows, Mac, and Linux.
# Conclusions
In this example, we've seen that a quantum neural network is able to successfully classify classical data in $\mathbb{R}^2$. The qubit encoding strategy is able to write two bits of classical information into one bit of quantum information. Additionally, the state preparation circuit for the qubit encoding is short-depth, particularly useful for NISQ computers. We've demonstrated how to train a quantum neural network using the modified Powell algorithm on a simple example. We've also discussed how the NISQAI library greatly simplifies quantum neural network implementations.
# Acknowledgements
The development of NISQAI is supported by the [unitary.fund](http://unitary.fund/). We thank [Will Zeng](https://twitter.com/wjzeng) for creating and running this program, as well as [John Hering](https://twitter.com/johnhering), Jeff Cordova, Nima Alidoust, and [PLOS](https://www.plos.org/) for sponsoring it.
|
Module Nats.
Fixpoint eqb (n m : nat) : bool :=
match n with
| O => match m with
| O => true
| S _ => false
end
| S n' => match m with
| O => false
| S m' => eqb n' m'
end
end.
Notation "x =? y" := (eqb x y) (at level 70).
End Nats.
Module Lists.
Import Nats.
Notation "x :: xs" := (cons x xs)(at level 60, right associativity).
Notation "[ ]" := nil.
Notation "[ x ; .. ; y ]" := (cons x .. (cons y nil) .. ).
Notation "x ++ y" := (app x y) (at level 60, right associativity).
Fixpoint rev {X: Type} (l: list X) : list X :=
match l with
| nil => nil
| x::xs => (rev xs) ++ [x]
end.
Fixpoint nth_err {X: Type} (l: list X) (n: nat) : option X :=
match l with
| [] => None
| x::xs => if n =? 0 then Some x else nth_err xs (pred n)
end.
Fixpoint split {X Y: Type} (l: list (X * Y))
: (list X) * (list Y) :=
match l with
| nil => (nil, nil)
| cons (x, y) ls => match (split ls) with
| (p, q) => (cons x p, cons y q)
end
end.
End Lists.
|
State Before: α : Type ?u.24677
V : Type u_1
P : Type u_2
W : Type ?u.24686
Q : Type ?u.24689
inst✝⁵ : SeminormedAddCommGroup V
inst✝⁴ : PseudoMetricSpace P
inst✝³ : NormedAddTorsor V P
inst✝² : NormedAddCommGroup W
inst✝¹ : MetricSpace Q
inst✝ : NormedAddTorsor W Q
p₁ p₂ p₃ p₄ : P
⊢ dist (p₁ -ᵥ p₂) (p₃ -ᵥ p₄) ≤ dist p₁ p₃ + dist p₂ p₄ State After: α : Type ?u.24677
V : Type u_1
P : Type u_2
W : Type ?u.24686
Q : Type ?u.24689
inst✝⁵ : SeminormedAddCommGroup V
inst✝⁴ : PseudoMetricSpace P
inst✝³ : NormedAddTorsor V P
inst✝² : NormedAddCommGroup W
inst✝¹ : MetricSpace Q
inst✝ : NormedAddTorsor W Q
p₁ p₂ p₃ p₄ : P
⊢ ‖p₁ -ᵥ p₃ - (p₂ -ᵥ p₄)‖ ≤ ‖p₁ -ᵥ p₃‖ + ‖p₂ -ᵥ p₄‖ Tactic: rw [dist_eq_norm, vsub_sub_vsub_comm, dist_eq_norm_vsub V, dist_eq_norm_vsub V] State Before: α : Type ?u.24677
V : Type u_1
P : Type u_2
W : Type ?u.24686
Q : Type ?u.24689
inst✝⁵ : SeminormedAddCommGroup V
inst✝⁴ : PseudoMetricSpace P
inst✝³ : NormedAddTorsor V P
inst✝² : NormedAddCommGroup W
inst✝¹ : MetricSpace Q
inst✝ : NormedAddTorsor W Q
p₁ p₂ p₃ p₄ : P
⊢ ‖p₁ -ᵥ p₃ - (p₂ -ᵥ p₄)‖ ≤ ‖p₁ -ᵥ p₃‖ + ‖p₂ -ᵥ p₄‖ State After: no goals Tactic: exact norm_sub_le _ _ |
At 06 : 30 the five German torpedo boats that the convoy had evaded the previous day were sighted by HMS Atherstone and Tynedale . The two destroyers turned toward them and opened fire at a range of 7 miles ( 11 km ) . After ten minutes the German boats turned away , making smoke . The destroyers sighted the MGB and two accompanying MLs soon after and transferred their casualties to the Atherstone . Not expecting any more boats to arrive , they headed for home . Just after 09 : 00 the Hunt @-@ class escort destroyers HMS Brocklesby and HMS Cleveland arrived , sent by Commander @-@ in @-@ Chief Plymouth . Shortly after this the ships were spotted by a Heinkel 115 floatplane of the Luftwaffe .
|
#' Fast fitting of Bayesian occupancy models
#'
#' The package implements the methods to fit Bayesian occupancy models as
#' described in Diana et al. (2021). The model performs estimate of temporal and
#' spatial trends in the occupancy probability and can incorporate covariates.
#' The inference is performed using the Polya-Gamma scheme for efficient inference.
#'
#' @details
#'
#' Example of the use of the package can be found in the vignette.
#'
#' @references Diana A., Dennis E., Matechou E. and B.J.T. Morgan.
#' Fast Bayesian inference for large occupancy datasets, using the Polya-Gamma scheme
#'
#' @useDynLib FastOccupancy
#' @importFrom Rcpp sourceCpp
#'
#' @examples
#' modelResults <- runModel(sampleData,
#' index_year = 1,
#' index_site = 2,
#' index_occ = 8,
#' index_spatial_x = 3,
#' index_spatial_y = 4,
#' covariates_psi_text = "5",
#' covariates_p_text = "6-7",
#' usingSpatial = TRUE,
#' gridStep = .2,
#' nchain = 1,
#' nburn = 100,
#' niter = 100)
#'
#' plotOccupancyIndex(modelResults)
#'
#' @docType package
#' @name FastOccupancy
NULL
#> NULL |
State Before: α : Type u_1
β : Type ?u.196902
inst✝¹ : LinearOrder α
inst✝ : LinearOrder β
f : α → β
a a₁ a₂ b b₁ b₂ c d : α
h : b₂ < b₁
⊢ Ioo a₁ b₁ ∩ Ioc a₂ b₂ = Ioc (max a₁ a₂) b₂ State After: no goals Tactic: rw [inter_comm, Ioc_inter_Ioo_of_left_lt h, max_comm] |
[STATEMENT]
lemma rt_fresh_asD1 [dest]:
assumes "rt1 \<approx>\<^bsub>dip\<^esub> rt2"
shows "rt1 \<sqsubseteq>\<^bsub>dip\<^esub> rt2"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. rt1 \<sqsubseteq>\<^bsub>dip\<^esub> rt2
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
rt1 \<approx>\<^bsub>dip\<^esub> rt2
goal (1 subgoal):
1. rt1 \<sqsubseteq>\<^bsub>dip\<^esub> rt2
[PROOF STEP]
unfolding rt_fresh_as_def
[PROOF STATE]
proof (prove)
using this:
rt1 \<sqsubseteq>\<^bsub>dip\<^esub> rt2 \<and> rt2 \<sqsubseteq>\<^bsub>dip\<^esub> rt1
goal (1 subgoal):
1. rt1 \<sqsubseteq>\<^bsub>dip\<^esub> rt2
[PROOF STEP]
by simp |
//
// Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// 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)
//
// Official repository: https://github.com/boostorg/beast
//
// Test that header file is self-contained.
#include <boost/beast/core/error.hpp>
#include <boost/beast/_experimental/unit_test/suite.hpp>
#include <memory>
namespace boost {
namespace beast {
class error_test : public unit_test::suite
{
public:
// no condition
void check(error e)
{
auto const ec = make_error_code(e);
ec.category().name();
BEAST_EXPECT(! ec.message().empty());
}
void check(condition c, error e)
{
{
auto const ec = make_error_code(e);
BEAST_EXPECT(ec.category().name() != nullptr);
BEAST_EXPECT(! ec.message().empty());
BEAST_EXPECT(ec == c);
}
{
auto ec = make_error_condition(c);
BEAST_EXPECT(ec.category().name() != nullptr);
BEAST_EXPECT(! ec.message().empty());
BEAST_EXPECT(ec == c);
}
}
void run() override
{
check(condition::timeout, error::timeout);
}
};
BEAST_DEFINE_TESTSUITE(beast,core,error);
} // beast
} // boost
|
//
// co_spawn.hpp
// ~~~~~~~~~~~~
//
// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// 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 BOOST_ASIO_CO_SPAWN_HPP
#define BOOST_ASIO_CO_SPAWN_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/config.hpp>
#if defined(BOOST_ASIO_HAS_CO_AWAIT) || defined(GENERATING_DOCUMENTATION)
#include <boost/asio/awaitable.hpp>
#include <boost/asio/execution_context.hpp>
#include <boost/asio/is_executor.hpp>
#include <boost/asio/detail/push_options.hpp>
namespace boost {
namespace asio {
namespace detail {
template <typename T>
struct awaitable_signature;
template <typename T, typename Executor>
struct awaitable_signature<awaitable<T, Executor>>
{
typedef void type(std::exception_ptr, T);
};
template <typename Executor>
struct awaitable_signature<awaitable<void, Executor>>
{
typedef void type(std::exception_ptr);
};
} // namespace detail
/// Spawn a new thread of execution.
/**
* The entry point function object @c f must have the signature:
*
* @code awaitable<void, E> f(); @endcode
*
* where @c E is convertible from @c Executor.
*/
template <typename Executor, typename F, typename CompletionToken>
BOOST_ASIO_INITFN_RESULT_TYPE(CompletionToken,
typename detail::awaitable_signature<typename result_of<F()>::type>::type)
co_spawn(const Executor& ex, F&& f, CompletionToken&& token,
typename enable_if<
is_executor<Executor>::value
>::type* = 0);
/// Spawn a new thread of execution.
/**
* The entry point function object @c f must have the signature:
*
* @code awaitable<void, E> f(); @endcode
*
* where @c E is convertible from @c ExecutionContext::executor_type.
*/
template <typename ExecutionContext, typename F, typename CompletionToken>
BOOST_ASIO_INITFN_RESULT_TYPE(CompletionToken,
typename detail::awaitable_signature<typename result_of<F()>::type>::type)
co_spawn(ExecutionContext& ctx, F&& f, CompletionToken&& token,
typename enable_if<
is_convertible<ExecutionContext&, execution_context&>::value
>::type* = 0);
} // namespace asio
} // namespace boost
#include <boost/asio/detail/pop_options.hpp>
#include <boost/asio/impl/co_spawn.hpp>
#endif // defined(BOOST_ASIO_HAS_CO_AWAIT) || defined(GENERATING_DOCUMENTATION)
#endif // BOOST_ASIO_CO_SPAWN_HPP
|
module Inigo.Async.Compress.Brotli
import Data.Buffer
import Extra.Buffer
import Inigo.Async.FS
import Inigo.Async.Promise
import Inigo.Async.Util
-- Compresses a String using Brotli, returning a Buffer
%foreign (promisifyPrim "(datum)=>{return require('util').promisify(require('zlib').brotliCompress)(datum)}")
brotli_compress__prim : Buffer -> promise Buffer
-- Decompresses a buffer encoded in Brotli, returning the original data
%foreign (promisifyPrim "(buf)=>require('util').promisify(require('zlib').brotliDecompress)(buf)")
brotli_decompress__prim : Buffer -> promise Buffer
export
compress: Buffer -> Promise Buffer
compress datum =
promisify (brotli_compress__prim datum)
export
decompress: Buffer -> Promise Buffer
decompress buf =
promisify (brotli_decompress__prim buf)
export
compressFile : String -> Promise Buffer
compressFile path =
do
contents <- fs_readFileBuf path
compress contents
|
#ifndef SUPERGENIUS_SRC_VERIFICATION_FINALITY_ROUND_STATE_HPP
#define SUPERGENIUS_SRC_VERIFICATION_FINALITY_ROUND_STATE_HPP
#include <boost/optional.hpp>
#include "verification/finality/structs.hpp"
namespace sgns::verification::finality {
/// Stores the current state of the round
struct RoundState {
/// last finalized block before playing round
BlockInfo last_finalized_block;
/**
* is calculated as ghost function on graph composed from received prevotes.
* Note: prevote_ghost is not necessary the prevote that created by the
* current peer
*/
Prevote best_prevote_candidate;
/**
* is the best possible block that could be finalized in current round.
* Always ancestor of `prevote_ghost` or equal to `prevote_ghost`
*/
BlockInfo best_final_candidate;
/**
* is the block that received supermajority on both prevotes and precommits
*/
boost::optional<BlockInfo> finalized;
inline bool operator==(const RoundState &round_state) const {
return std::tie(last_finalized_block,
best_prevote_candidate,
best_final_candidate,
finalized)
== std::tie(round_state.last_finalized_block,
round_state.best_prevote_candidate,
round_state.best_final_candidate,
round_state.finalized);
}
inline bool operator!=(const RoundState &round_state) const {
return !operator==(round_state);
}
};
template <class Stream,
typename = std::enable_if_t<Stream::is_encoder_stream>>
Stream &operator<<(Stream &s, const RoundState &state) {
return s << state.last_finalized_block << state.best_prevote_candidate
<< state.best_final_candidate << state.finalized;
}
template <class Stream,
typename = std::enable_if_t<Stream::is_decoder_stream>>
Stream &operator>>(Stream &s, RoundState &state) {
return s >> state.last_finalized_block >> state.best_prevote_candidate
>> state.best_final_candidate >> state.finalized;
}
} // namespace sgns::verification::finality
#endif // SUPERGENIUS_SRC_VERIFICATION_FINALITY_ROUND_STATE_HPP
|
(* * First-Order Logic *)
Require Import Definitions DecidabilityFacts EnumerabilityFacts ListEnumerabilityFacts ReducibilityFacts.
Require Import ListAutomation.
Import ListAutomationNotations.
From Coq Require Import Eqdep_dec.
Require Import Coq.Vectors.Vector.
Local Notation vec := t.
Require Export FO_Bi_Int_Syntax.
Set Default Proof Using "Type".
(* ** Discreteness *)
Require Import EqdepFacts.
Lemma inj_pair2_eq_dec' A :
eq_dec A -> forall (P : A -> Type) (p : A) (x y : P p), existT P p x = existT P p y -> x = y.
Proof.
apply Eqdep_dec.inj_pair2_eq_dec.
Qed.
Ltac resolve_existT := try
match goal with
| [ H2 : @existT ?X _ _ _ = existT _ _ _ |- _ ] => eapply Eqdep_dec.inj_pair2_eq_dec in H2;
[subst | try (eauto || now intros; decide equality)]
end.
Lemma dec_vec_in X n (v : vec X n) :
(forall x, vec_in x v -> forall y, dec (x = y)) -> forall v', dec (v = v').
Proof with subst; try (now left + (right; intros[=])).
intros Hv. induction v; intros v'.
- pattern v'. apply Vector.case0...
- apply (Vector.caseS' v'). clear v'. intros h0 v'.
destruct (Hv h (vec_inB h v) h0)... edestruct IHv.
+ intros x H. apply Hv. now right.
+ left. f_equal. apply e.
+ right. intros H. inversion H. resolve_existT. tauto.
Qed.
#[global]
Instance dec_vec X {HX : eq_dec X} n : eq_dec (vec X n).
Proof.
intros v. refine (dec_vec_in _ _ _ _).
Qed.
Section EqDec.
Context {Σ_funcs : funcs_signature}.
Context {Σ_preds : preds_signature}.
Context {ops : operators}.
Hypothesis eq_dec_Funcs : eq_dec syms.
Hypothesis eq_dec_Preds : eq_dec preds.
Hypothesis eq_dec_binop : eq_dec binop.
Hypothesis eq_dec_quantop : eq_dec quantop.
Global Instance dec_term : eq_dec term.
Proof with subst; try (now left + (right; intros[=]; resolve_existT; congruence))
using eq_dec_Funcs.
intros t. induction t as [ | ]; intros [|? v']...
- decide (x = n)...
- decide (F = f)... destruct (dec_vec_in _ _ _ X v')...
Qed.
End EqDec.
(* ** Enumerability *)
Section Enumerability.
Context {Σ_funcs : funcs_signature}.
Context {Σ_preds : preds_signature}.
Context {ops : operators}.
Variable list_Funcs : nat -> list syms.
Hypothesis enum_Funcs' : list_enumerator__T list_Funcs syms.
Variable list_Preds : nat -> list preds.
Hypothesis enum_Preds' : list_enumerator__T list_Preds preds.
Variable list_binop : nat -> list binop.
Hypothesis enum_binop' : list_enumerator__T list_binop binop.
Variable list_quantop : nat -> list quantop.
Hypothesis enum_quantop' : list_enumerator__T list_quantop quantop.
Fixpoint vecs_from X (A : list X) (n : nat) : list (vec X n) :=
match n with
| 0 => [Vector.nil X]
| S n => [ Vector.cons X x _ v | (x, v) ∈ (A × vecs_from X A n) ]
end.
Fixpoint L_term n : list term :=
match n with
| 0 => []
| S n => L_term n ++ var n :: concat ([ [ func F v | v ∈ vecs_from _ (L_term n) (ar_syms F) ] | F ∈ L_T n])
end.
Lemma L_term_cml :
cumulative L_term.
Proof.
intros ?; cbn; eauto.
Qed.
Lemma list_prod_in X Y (x : X * Y) A B :
x el (A × B) -> exists a b, x = (a , b) /\ a el A /\ b el B.
Proof.
induction A; cbn.
- intros [].
- intros [H | H] % in_app_or. 2: firstorder.
apply in_map_iff in H as (y & <- & Hel). exists a, y. tauto.
Qed.
Lemma vecs_from_correct X (A : list X) (n : nat) (v : vec X n) :
(forall x, vec_in x v -> x el A) <-> v el vecs_from X A n.
Proof.
induction n; cbn.
- split.
+ intros. left. pattern v. now apply Vector.case0.
+ intros [<- | []] x H. inv H.
- split.
+ intros. revert H. apply (Vector.caseS' v).
clear v. intros ? t0 H. in_collect (pair h t0); destruct (IHn t0).
eauto using vec_inB. apply H0. intros x Hx. apply H. now right.
+ intros Hv. apply in_map_iff in Hv as ([h v'] & <- & (? & ? & [= <- <-] & ? & ?) % list_prod_in).
intros x H. inv H; destruct (IHn v'); eauto. apply H2; trivial. now resolve_existT.
Qed.
Lemma vec_forall_cml X (L : nat -> list X) n (v : vec X n) :
cumulative L -> (forall x, vec_in x v -> exists m, x el L m) -> exists m, v el vecs_from _ (L m) n.
Proof.
intros HL Hv. induction v; cbn.
- exists 0. tauto.
- destruct IHv as [m H], (Hv h) as [m' H']. 1,3: eauto using vec_inB.
+ intros x Hx. apply Hv. now right.
+ exists (m + m'). in_collect (pair h v). 1: apply (cum_ge' (n:=m')); intuition lia.
apply vecs_from_correct. rewrite <- vecs_from_correct in H. intros x Hx.
apply (cum_ge' (n:=m)). all: eauto. lia.
Qed.
Lemma enum_term :
list_enumerator__T L_term term.
Proof with try (eapply cum_ge'; eauto; lia).
intros t. induction t using term_rect.
- exists (S x); cbn; eauto.
- apply vec_forall_cml in H as [m H]. 2: exact L_term_cml. destruct (el_T F) as [m' H'].
exists (S (m + m')); cbn. in_app 3. eapply in_concat_iff. eexists. split. 2: in_collect F...
apply in_map. rewrite <- vecs_from_correct in H |-*. intros x H''. specialize (H x H'')...
Qed.
Lemma enumT_term :
enumerable__T term.
Proof using enum_Funcs'.
apply enum_enumT. exists L_term. apply enum_term.
Qed.
Fixpoint L_form n : list form :=
match n with
| 0 => [⊥;⊤]
| S n => L_form n
++ concat ([ [ atom P v | v ∈ vecs_from _ (L_term n) (ar_preds P) ] | P ∈ L_T n])
++ concat ([ [ bin op phi psi | (phi, psi) ∈ (L_form n × L_form n) ] | op ∈ L_T n])
++ concat ([ [ quant op phi | phi ∈ L_form n ] | op ∈ L_T n])
end.
Lemma L_form_cml :
cumulative L_form.
Proof.
intros ?; cbn; eauto.
Qed.
Lemma enum_form :
list_enumerator__T L_form form.
Proof with (try eapply cum_ge'; eauto; lia).
intros phi. induction phi.
- exists 1. cbn; eauto.
- exists 1. cbn; eauto.
- rename t into v. destruct (el_T P) as [m Hm], (vec_forall_cml term L_term _ v) as [m' Hm']; eauto using enum_term.
exists (S (m + m')); cbn. in_app 2. eapply in_concat_iff. eexists. split.
2: in_collect P... eapply in_map. rewrite <- vecs_from_correct in *. intuition...
- destruct (el_T b) as [m Hm], IHphi1 as [m1], IHphi2 as [m2]. exists (1 + m + m1 + m2). cbn.
in_app 3. apply in_concat. eexists. split. apply in_map... in_collect (pair phi1 phi2)...
- destruct (el_T q) as [m Hm], IHphi as [m' Hm']. exists (1 + m + m'). cbn -[L_T].
in_app 4. apply in_concat. eexists. split. apply in_map... in_collect phi...
Qed.
Lemma enumT_form :
enumerable__T form.
Proof using enum_Funcs' enum_Preds' enum_binop' enum_quantop'.
apply enum_enumT. exists L_form. apply enum_form.
Defined.
End Enumerability.
|
lemma scaleR_le_0_iff: "a *\<^sub>R b \<le> 0 \<longleftrightarrow> 0 < a \<and> b \<le> 0 \<or> a < 0 \<and> 0 \<le> b \<or> a = 0" for b::"'a::ordered_real_vector" |
theory LFIs_border
imports "logical_consequence" "../conditions/conditions_relativized_infinitary"
begin
section \<open>Logics of Formal Inconsistency (LFIs)\<close>
(**The LFIs are a family of paraconsistent logics featuring a 'consistency' operator @{text "\<^bold>\<circ>"}
that can be used to recover some classical properties of negation (in particular ECQ).
We show a shallow semantical embedding of logics at least as strong as the LFI RmbC-ciw*)
(*Let us assume a concrete type w (for 'worlds' or 'points')*)
typedecl w
(*Let us assume the following primitive unary operation \<B> (intended as a border operator)*)
consts \<B>::"w \<sigma> \<Rightarrow> w \<sigma>"
(*From the topological cube of opposition:*)
abbreviation "\<C> \<equiv> (\<B>\<^sup>f\<^sup>p)\<^sup>-"
abbreviation "\<I> \<equiv> \<B>\<^sup>f\<^sup>p\<^sup>c"
lemma "\<C>\<^sup>- = \<B>\<^sup>f\<^sup>p" by (simp add: dualcompl_invol)
(*let us recall that: *)
lemma expn_cntr: "EXPN \<C> = CNTR \<B>" by (metis EXPN_CNTR_dual2 EXPN_fp ofp_comm_dc1)
(**For LFIs we use the negation previously defined as \<C>\<^sup>- = \<B>\<^sup>f\<^sup>p *)
abbreviation cneg ("\<^bold>\<not>_"[70]71) where "cneg \<equiv> \<B>\<^sup>f\<^sup>p"
(**In terms of the border operator the negation looks as follows:*)
lemma cneg_char: "CNTR \<B> \<longrightarrow> \<^bold>\<not>A \<approx> \<^bold>\<midarrow>A \<^bold>\<or> (\<B> A)" by (smt (verit, ccfv_threshold) CNTR_def compl_def dimpl_def join_def op_fixpoint_def setequ_def subset_def)
(**This negation is of course boldly paraconsistent (for both local and global consequence).*)
lemma "[a, \<^bold>\<not>a \<turnstile> b]" nitpick oops (*countermodel*)
lemma "[a, \<^bold>\<not>a \<turnstile> \<^bold>\<not>b]" nitpick oops (*countermodel*)
lemma "[a, \<^bold>\<not>a \<turnstile>\<^sub>g b]" nitpick oops (*countermodel*)
lemma "[a, \<^bold>\<not>a \<turnstile>\<^sub>g \<^bold>\<not>b]" nitpick oops (*countermodel*)
(**We define two pairs of in/consistency operators and show how they relate to each other.
Using LFIs terminology, the minimal logic so encoded corresponds to 'RmbC-ciw' (cf. @{cite RLFI}).*)
abbreviation op_inc_a::"w \<sigma> \<Rightarrow> w \<sigma>" ("\<bullet>\<^sup>A_" [57]58) (* \<bullet> as truth-glut *)
where "\<bullet>\<^sup>AA \<equiv> A \<^bold>\<and> \<^bold>\<not>A"
abbreviation op_con_a::"w \<sigma> \<Rightarrow> w \<sigma>" ("\<^bold>\<circ>\<^sup>A_" [57]58)
where "\<^bold>\<circ>\<^sup>AA \<equiv> \<^bold>\<midarrow>\<bullet>\<^sup>AA"
abbreviation op_inc_b::"w \<sigma> \<Rightarrow> w \<sigma>" ("\<bullet>\<^sup>B_" [57]58) (* \<bullet> as border *)
where "\<bullet>\<^sup>BA \<equiv> \<B> A"
abbreviation op_con_b::"w \<sigma> \<Rightarrow> w \<sigma>" ("\<^bold>\<circ>\<^sup>B_" [57]58)
where "\<^bold>\<circ>\<^sup>BA \<equiv> \<B>\<^sup>c A"
(**Observe that assumming CNTR \<B> are we allowed to exchange A and B variants.*)
lemma pincAB: "CNTR \<B> \<longrightarrow> \<bullet>\<^sup>AA \<approx> \<bullet>\<^sup>BA" by (smt (verit, ccfv_SIG) cneg_char dimpl_def join_def meet_def op_fixpoint_def setequ_def)
lemma pconAB: "CNTR \<B> \<longrightarrow> \<^bold>\<circ>\<^sup>AA \<approx> \<^bold>\<circ>\<^sup>BA" by (metis pincAB setequ_ext svfun_compl_def)
(**Variants A and B give us slightly different properties (there are countermodels for those not shown).*)
lemma Prop1: "\<^bold>\<circ>\<^sup>BA \<approx> \<I>\<^sup>f\<^sup>p A" by (simp add: ofp_comm_compl ofp_invol setequ_ext)
lemma Prop2: "\<^bold>\<circ>\<^sup>AA \<approx> A \<^bold>\<rightarrow> \<I> A" by (simp add: BA_deMorgan2 impl_char svfun_compl_def)
lemma Prop3: "fp \<C> A \<longleftrightarrow> \<^bold>\<circ>\<^sup>B\<^bold>\<midarrow>A \<approx> \<^bold>\<top>" by (metis Prop1 dual_compl_char2 fp_d_rel setequ_ext)
lemma Prop4a: "fp \<I> A \<longleftrightarrow> \<^bold>\<circ>\<^sup>BA \<approx> \<^bold>\<top>" by (simp add: fp_rel ofp_comm_compl ofp_invol)
lemma Prop4b: "fp \<I> A \<longrightarrow> \<^bold>\<circ>\<^sup>AA \<approx> \<^bold>\<top>" by (metis BA_impl Prop2 fixpoints_def setequ_char setequ_ext)
(**The 'principle of gentle explosion' works for both variants (both locally and globally)*)
lemma "[\<^bold>\<circ>\<^sup>Aa, a, \<^bold>\<not>a \<turnstile> b]" by (metis (mono_tags, lifting) compl_def meet_def subset_def)
lemma "[\<^bold>\<circ>\<^sup>Aa, a, \<^bold>\<not>a \<turnstile>\<^sub>g b]" by (metis compl_def meet_def)
lemma "[\<^bold>\<circ>\<^sup>Ba, a, \<^bold>\<not>a \<turnstile> b]" by (smt (z3) meet_def ofp_fixpoint_compl_def ofp_invol sdiff_def subset_def)
lemma "[\<^bold>\<circ>\<^sup>Ba, a, \<^bold>\<not>a \<turnstile>\<^sub>g b]" by (metis compl_def fixpoints_def fp_rel gtrue_def setequ_ext svfun_compl_def)
abbreviation "BORDER \<phi> \<equiv> nMULTr \<phi> \<and> CNTR \<phi> \<and> nDNRM \<phi> \<and> nIDEMr\<^sup>b \<phi>"
(**We show how all (local) contraposition variants (among others) can be recovered using the
consistency operators.*)
lemma "[\<^bold>\<circ>\<^sup>Ab, a \<^bold>\<rightarrow> b \<turnstile> \<^bold>\<not>b \<^bold>\<rightarrow> \<^bold>\<not>a]" nitpick oops
lemma cons_lcop1: "CNTR \<B> \<longrightarrow> [\<^bold>\<circ>\<^sup>Ab, a \<^bold>\<rightarrow> b \<turnstile> \<^bold>\<not>b \<^bold>\<rightarrow> \<^bold>\<not>a]" by (smt (verit, del_insts) cneg_char compl_def impl_char join_def meet_def setequ_ext subset_def)
lemma "[\<^bold>\<circ>\<^sup>Bb, a \<^bold>\<rightarrow> b \<turnstile> \<^bold>\<not>b \<^bold>\<rightarrow> \<^bold>\<not>a]" nitpick oops
lemma cons_lcop2: "CNTR \<B> \<longrightarrow> [\<^bold>\<circ>\<^sup>Bb, a \<^bold>\<rightarrow> b \<turnstile> \<^bold>\<not>b \<^bold>\<rightarrow> \<^bold>\<not>a]" by (metis cons_lcop1 pconAB setequ_ext)
(*.....*)
(**The following axioms are commonly employed in the literature on LFIs to obtain stronger logics.
We explore under which conditions they can be assumed while keeping the logic boldly paraconsistent.*)
abbreviation cf where "cf \<equiv> \<forall>P. [\<^bold>\<not>\<^bold>\<not>P \<turnstile> P]"
abbreviation ce where "ce \<equiv> \<forall>P. [P \<turnstile> \<^bold>\<not>\<^bold>\<not>P]"
abbreviation ciw_a where "ciw_a \<equiv> \<forall>P. [\<turnstile> \<^bold>\<circ>\<^sup>AP \<^bold>\<or> \<bullet>\<^sup>AP]"
abbreviation ciw_b where "ciw_b \<equiv> \<forall>P. [\<turnstile> \<^bold>\<circ>\<^sup>BP \<^bold>\<or> \<bullet>\<^sup>BP]"
abbreviation ci_a where "ci_a \<equiv> \<forall>P. [\<^bold>\<not>(\<^bold>\<circ>\<^sup>AP) \<turnstile> \<bullet>\<^sup>AP]"
abbreviation ci_b where "ci_b \<equiv> \<forall>P. [\<^bold>\<not>(\<^bold>\<circ>\<^sup>BP) \<turnstile> \<bullet>\<^sup>BP]"
abbreviation cl_a where "cl_a \<equiv> \<forall>P. [\<^bold>\<not>(\<bullet>\<^sup>AP) \<turnstile> \<^bold>\<circ>\<^sup>AP]"
abbreviation cl_b where "cl_b \<equiv> \<forall>P. [\<^bold>\<not>(\<bullet>\<^sup>BP) \<turnstile> \<^bold>\<circ>\<^sup>BP]"
abbreviation ca_conj_a where "ca_conj_a \<equiv> \<forall>P Q. [\<^bold>\<circ>\<^sup>AP,\<^bold>\<circ>\<^sup>AQ \<turnstile> \<^bold>\<circ>\<^sup>A(P \<^bold>\<and> Q)]"
abbreviation ca_conj_b where "ca_conj_b \<equiv> \<forall>P Q. [\<^bold>\<circ>\<^sup>BP,\<^bold>\<circ>\<^sup>BQ \<turnstile> \<^bold>\<circ>\<^sup>B(P \<^bold>\<and> Q)]"
abbreviation ca_disj_a where "ca_disj_a \<equiv> \<forall>P Q. [\<^bold>\<circ>\<^sup>AP,\<^bold>\<circ>\<^sup>AQ \<turnstile> \<^bold>\<circ>\<^sup>A(P \<^bold>\<or> Q)]"
abbreviation ca_disj_b where "ca_disj_b \<equiv> \<forall>P Q. [\<^bold>\<circ>\<^sup>BP,\<^bold>\<circ>\<^sup>BQ \<turnstile> \<^bold>\<circ>\<^sup>B(P \<^bold>\<or> Q)]"
abbreviation ca_impl_a where "ca_impl_a \<equiv> \<forall>P Q. [\<^bold>\<circ>\<^sup>AP,\<^bold>\<circ>\<^sup>AQ \<turnstile> \<^bold>\<circ>\<^sup>A(P \<^bold>\<rightarrow> Q)]"
abbreviation ca_impl_b where "ca_impl_b \<equiv> \<forall>P Q. [\<^bold>\<circ>\<^sup>BP,\<^bold>\<circ>\<^sup>BQ \<turnstile> \<^bold>\<circ>\<^sup>B(P \<^bold>\<rightarrow> Q)]"
abbreviation ca_a where "ca_a \<equiv> ca_conj_a \<and> ca_disj_a \<and> ca_impl_a"
abbreviation ca_b where "ca_b \<equiv> ca_conj_b \<and> ca_disj_b \<and> ca_impl_b"
(**cf*)
lemma "BORDER \<B> \<Longrightarrow> cf" nitpick oops (*countermodel*)
(**ce*)
lemma "BORDER \<B> \<Longrightarrow> ce" nitpick oops (*countermodel*)
(**ciw*)
lemma prop_ciw_a: "ciw_a" by (simp add: conn)
lemma prop_ciw_b: "ciw_b" by (simp add: conn svfun_compl_def)
(**ci*)
lemma "BORDER \<B> \<Longrightarrow> ci_a" nitpick oops (*countermodel*)
lemma "BORDER \<B> \<Longrightarrow> ci_b" nitpick oops (*countermodel*)
(**cl*)
lemma "BORDER \<B> \<Longrightarrow> cl_a" nitpick oops (*countermodel*)
lemma "BORDER \<B> \<Longrightarrow> cl_b" nitpick oops (*countermodel*)
(**ca_conj*)
lemma prop_ca_conj_b: "nMULT\<^sup>b \<B> = ca_conj_b" by (metis MULT_b_def nMULTb_compl sfun_compl_invol)
lemma prop_ca_conj_a: "nMULTr\<^sup>b \<B> = ca_conj_a" unfolding cond op_fixpoint_def by (smt (z3) compl_def dimpl_def join_def meet_def op_fixpoint_def subset_def subset_in_def)
(**ca_disj*)
lemma prop_ca_disj_b: "ADDI\<^sup>a \<B> = ca_disj_b" by (simp add: nADDI_a_def nADDIa_compl)
lemma prop_ca_disj_a: "nMULTr\<^sup>a \<B> = ca_disj_a" (*nitpick*) oops (*TODO: verify*)
(**ca_impl*)
lemma "BORDER \<B> \<Longrightarrow> ca_impl_a" nitpick oops (*countermodel*)
lemma "BORDER \<B> \<Longrightarrow> ca_impl_b" nitpick oops (*countermodel*)
end |
(* Title: Jinja/Compiler/Compiler.thy
Author: Tobias Nipkow
Copyright TUM 2003
*)
section \<open>Combining Stages 1 and 2\<close>
theory Compiler
imports Correctness1 Correctness2
begin
definition J2JVM :: "J_prog \<Rightarrow> jvm_prog"
where
"J2JVM \<equiv> compP\<^sub>2 \<circ> compP\<^sub>1"
theorem comp_correct:
assumes wwf: "wwf_J_prog P"
and "method": "P \<turnstile> C sees M:Ts\<rightarrow>T = (pns,body) in C"
and eval: "P \<turnstile> \<langle>body,(h,[this#pns [\<mapsto>] vs])\<rangle> \<Rightarrow> \<langle>e',(h',l')\<rangle>"
and sizes: "size vs = size pns + 1" "size rest = max_vars body"
shows "J2JVM P \<turnstile> (None,h,[([],vs@rest,C,M,0)]) -jvm\<rightarrow> (exception e',h',[])"
(*<*)
proof -
let ?P\<^sub>1 = "compP\<^sub>1 P"
have fv: "fv body \<subseteq> set (this#pns)"
using wwf "method" by(auto dest!:sees_wf_mdecl simp:wf_mdecl_def)
have init: "[this#pns [\<mapsto>] vs] \<subseteq>\<^sub>m [this#pns [\<mapsto>] vs@rest]"
using sizes by simp
have "?P\<^sub>1 \<turnstile> C sees M: Ts\<rightarrow>T = (compE\<^sub>1 (this#pns) body) in C"
using sees_method_compP[OF "method", of "\<lambda>(pns,e). compE\<^sub>1 (this#pns) e"]
by(simp)
moreover obtain ls' where
"?P\<^sub>1 \<turnstile>\<^sub>1 \<langle>compE\<^sub>1 (this#pns) body, (h, vs@rest)\<rangle> \<Rightarrow> \<langle>fin\<^sub>1 e', (h',ls')\<rangle>"
using eval\<^sub>1_eval[OF wwf eval fv init] sizes by auto
ultimately show ?thesis using comp\<^sub>2_correct eval_final[OF eval]
by(fastforce simp add:J2JVM_def final_def)
qed
(*>*)
end
|
\chapter{Interactive Workload}
\label{sec:interactive}
This workload consists of a set of relatively complex read-only queries, that touch a significant
amount of data -- often the two-step friendship neighbourhood and associated messages --, but typically in close proximity to a single node. Hence, the query complexity is sublinear to the dataset size.
The LDBC SNB Interactive workload consists of three query classes:
\begin{itemize}
\item \textbf{Complex read-only queries.} See \autoref{sec:interactive-complex-reads}.
\item \textbf{Short read-only queries.} See \autoref{sec:interactive-short-reads}.
\item \textbf{Transactional update queries inserting new entities.} See \autoref{sec:interactive-inserts}.
\end{itemize}
A detailed description of the workload (covering reads and inserts) is available in the paper published at \mbox{SIGMOD} 2015~\cite{DBLP:conf/sigmod/ErlingALCGPPB15}.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Complex Reads}
\label{sec:interactive-complex-reads}
\input{interactive-complex-reads}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Short Reads}
\label{sec:interactive-short-reads}
\input{interactive-short-reads}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Inserts (Formerly: Updates)}
\label{sec:interactive-inserts}
Each insert query inserts
\begin{enumerate}
\item either a single node of a certain type, along with its edges to other existing nodes
\item or a single edge of a certain type between two existing nodes.
\end{enumerate}
In versions 0.3.x, these operations were called ``Interactive updates''.
From 0.4.0 onwards, these are called ``Interactive inserts''.
\input{interactive-inserts}
|
\documentclass[a4paper, 11pt]{article}
\usepackage{preamble}
% \usepackage{fullpage}
\usepackage[paper=a4paper,margin=1.5in, includefoot, footskip=30pt]{geometry}
\usepackage{dsfont}
\usepackage{algorithm}
\usepackage{algorithmic}
\usepackage{paralist}
\usepackage{csvsimple}
\usepackage{longtable}
\usepackage{booktabs}
\usepackage{tikz}
\usepackage{afterpage}
\usepackage{multicol}
\sisetup{range-phrase=-}
\newcommand{\drawfrom}{\overset{\mathrm{d}}{=}}
\newcommand{\setfrom}{\overset{\mathrm{d}}{\leftarrow}}
\title{ \small
University of Oslo\\
FYS4411\\
Computational physics II: Quantum mechanical systems\\
\huge Project 1: Variational Monte Carlo on Bosonic Systems}
\author{\textsc{Bendik Samseth}}
\date{\today}
\begin{document}
\maketitle
\begin{abstract}
In this project we have applied Variational Monte Carlo (VMC) to systems of
trapped hard-sphere interacting bosons. We present the theoretical
background, including exact theoretical results for the idealized
non-interacting system. These results are used as benchmarks for the
implementation, and we find that the developed codes are able to reproduce
them all. Further we discuss two different methods of sampling positions
from the probability distribution given by the trial wavefunction, using
both standard approaches with the Metropolis algorithm, as well as a more
informed revision in an implementation of the Metropolis-Hastings algorithm.
We also discus approaches to optimizing the variational parameters, in
particular using the method of Gradient Decent. Finally we apply all tools
to the interacting systems, for a number of particles $N=10, 50$ and $100$,
and present results for both the ground state energies and the one-body
density plots. The validity and resolution of our results are limited
heavily by the large computational complexity of the calculating properties
of large interacting system, although we are able to extract some insights.
All material referenced in this report is available at
\url{https://github.com/bsamseth/FYS4411}.
\end{abstract}
\pagebreak
\newgeometry{margin=0.9in}
\tableofcontents
\begin{multicols}{2}
\nocite{DuBois-phys-rev, Nilsen-phys-rev, mhj-compphys-II}
\section{Introduction}
The aim of this project is to use the Variational Monte Carlo
(VMC) method and evaluate the ground state energy of a trapped, hard
sphere Bose gas for different numbers of particles with a specific
trial wave function. This trial wave function is used to study the sensitivity of
condensate and non-condensate properties to the hard sphere radius
and the number of particles.
\section{Theory}
\subsection{Physical System}
\textbf{The trap} we will use is a spherical (S)
or an elliptical (E) harmonic trap in one, two and finally three
dimensions, with the latter given by
\begin{equation}
V_{ext}(\mathbf{r}) =
\Bigg\{
\begin{array}{ll}
\frac{1}{2}m\omega_{ho}^2r^2 & (S)\\
\strut
\frac{1}{2}m[\omega_{ho}^2(x^2+y^2) + \omega_z^2z^2] & (E)
\label{trap_eqn}
\end{array}
\end{equation}
\textbf{The Hamiltonian} of the system will be
\begin{equation}
H = \sum_i^N \left(\frac{-\hbar^2}{2m}{\bigtriangledown }_{i}^2 +V_{ext}({\mathbf{r}}_i)\right) +
\sum_{i<j}^{N}
V_{int}({\mathbf{r}}_i,{\mathbf{r}}_j),\label{eq:Hamiltonian}
\end{equation}
Here $\omega_{ho}^2$ defines the trap potential strength. In the case of the
elliptical trap, $V_{ext}(x,y,z)$, $\omega_{ho}=\omega_{\perp}$ is the trap
frequency in the perpendicular or $xy$ plane and $\omega_z$ the frequency in
the $z$ direction. The mean square vibrational amplitude of a single boson at
$T=0K$ in the trap (\ref{trap_eqn}) is $\langle
x^2\rangle=(\hbar/2m\omega_{ho})$ so that $a_{ho} \equiv
(\hbar/m\omega_{ho})^{\frac{1}{2}}$ defines the characteristic length of the
trap. The ratio of the frequencies is denoted
$\lambda=\omega_z/\omega_{\perp}$ leading to a ratio of the trap lengths
$(a_{\perp}/a_z)=(\omega_z/\omega_{\perp})^{\frac{1}{2}} = \sqrt{\lambda}$.
\vspace{0.3cm}\hrule\vspace{0.2cm}
Note: In the rest of this report, as well as in accompanying source code, we
will use natural units with $\hbar = m = 1$.
\vspace{0.2cm}\hrule\vspace{0.3cm}
We will represent \textbf{the inter-boson interaction} by a pairwise,
repulsive potential:
\begin{equation}
V_{int}(|\mathbf{r}_i-\mathbf{r}_j|) = \Bigg\{
\begin{array}{ll}
\infty & {|\mathbf{r}_i-\mathbf{r}_j|} \leq {a}\\
0 & {|\mathbf{r}_i-_r\mathbf{r}_j|} > {a}
\end{array}
\end{equation}
where $a$ is the so-called hard-core diameter of the bosons.
Clearly, $V_{int}(|\mathbf{r}_i-\mathbf{r}_j|)$ is zero if the bosons are
separated by a distance $|\mathbf{r}_i-\mathbf{r}_j|$ greater than $a$ but
infinite if they attempt to come within a distance $|\mathbf{r}_i-\mathbf{r}_j| \leq a$.
\textbf{The trial wave function} for the ground state with $N$ atoms will be given by
\begin{align}
\begin{split}
\Psi_T(\mathbf{r})&=\Psi_T(\mathbf{r}_1, \mathbf{r}_2, \dots
\mathbf{r}_N,\alpha,\beta)\\
&=\prod_i g(\alpha,\beta,\mathbf{r}_i)\prod_{i<j}f(a,|\mathbf{r}_i-\mathbf{r}_j|),
\end{split}
\label{eq:trialwf}
\end{align}
where $\alpha$ and $\beta$ are variational parameters. We choose the
single-particle wave function to be proportional to the harmonic
oscillator function for the ground state, i.e., we define $g(\alpha,\beta,\mathbf{r}_i)$ as:
\begin{equation}
g(\alpha,\beta,\mathbf{r}_i)= \exp[-\alpha(x_i^2+y_i^2+\beta z_i^2)].
\end{equation}
For spherical traps we have $\beta = 1$ and for non-interacting
bosons ($a=0$) we have $\alpha = 1/2a_{ho}^2$ resulting in the exact wave
function. The correlation wave function is
\begin{equation}
f(a,|\mathbf{r}_i-\mathbf{r}_j|)=\Bigg\{
\begin{array}{ll}
0 & {|\mathbf{r}_i-\mathbf{r}_j|} \leq {a}\\
(1-\frac{a}{|\mathbf{r}_i-\mathbf{r}_j|}) & {|\mathbf{r}_i-\mathbf{r}_j|} > {a}.
\end{array}
\end{equation}
\subsubsection{Scaling the System}
We will use distances in units of $a_{ho}$ in this report, $\vec r'=\vec r /a_{ho}$.
Performing this substitution in the Hamiltonian \eqref{eq:Hamiltonian}, using
$\nabla^{\prime 2} = a_{ho}^2\laplacian$, we get:
\begin{align*}
H &= \sum_i^N\qty(-\frac{\hbar^2}{2m}\laplacian_i + V_{ext}(\vec r_i)) +
\sum_{i<j}^NV_{int}(\vec r_i, \vec r_j)\\
&= \sum_{i}^N\left(-\frac{\hbar^2}{2m}
\frac{1}{a_{ho}^2}\nabla_i^{\prime 2}\right.\\
&\,
\qqtext{ }+\left.\frac{m}{2}\qty[\omega_{ho}^2a_{ho}^2\qty(x_i^{\prime 2} +
y_i^{\prime 2}) +
\omega_z^2a_{ho}^2z_i^{\prime 2}]\right)\\
&\,
\qqtext{ }+ \sum_{i<j}^NV_{int}(\vec r_i, \vec r_j)\\
\begin{split}
&= \frac{\hbar\omega_{ho}}{2}\sum_{i}^N\qty(-\nabla_i^{\prime 2} +
x_i^{\prime 2} + y_i^{\prime 2} + \lambda^2z_i^{\prime 2})\\
&\,\qqtext{ }+ \sum_{i<j}^NV_{int}(\vec r_i, \vec r_j)
\end{split}\numberthis\label{eq:Hamiltonian-scaled}
\end{align*}
where once again $\lambda = \flatfrac{\omega_z}{\omega_{ho}}$ describes the
asymmetry in the trap. The interaction potential remains the same, as all
lengths are scaled, and only the relative distances are used.
There will also be a scaling factor for the single-particle wave functions,
\begin{align}
g(\alpha, \beta, \vec r_i) = \exp[-\alpha a_{ho}^2(x_i^{\prime 2} +
y_i^{\prime 2} + \beta z_i^{\prime 2})].
\end{align}
The correlation wave functions remains unaffected.
All energies will due to this be given in units of $\hbar\omega_{ho}$, and
lengths in units of $\alpha_{ho}$. We fix the value of $\omega_{ho}=1$ so that,
along with the use of the natural units of $\hbar=m=1$, we have
\begin{align}
a_{ho} = \sqrt{\frac{\hbar}{m\omega_{ho}}} = 1.
\end{align}
This means the scaling has no effect on the numbers we would get, but now we
have a well defined scale to relate the numbers to.
For notational sanity, the use of ticks to denote the scaled variables will be
omitted, and can be assumed in the remainder of this report.
\subsection{The Objective}
Our objective is to evaluate the expectation value of the Hamiltonian. We cannot do this
without the true wave function of the system, something we do not possess.
We can, however, approximate the energy with the trial wave function.
\begin{align}
E[H] = \expval{H} = \frac{\int \dd{\vec R} \Psi^*_T H \Psi_T}{\int
\Psi_T^*\Psi_T}.
\end{align}
where $\vec R$ is the matrix containing all the positions of the particles in
the system, $\vec R = [\vec r_1, \vec r_2, \dots, \vec r_N]$.
In order to numerically evaluate this integral we first manipulate it a bit.
The probability density at position $\vec R$, under the trial wave function, is
\begin{align}
P(\vec R, \vec \alpha) &= \frac{\abs{\Psi_T}^2}{\int \dd{\vec R}\abs{\Psi_T}^2}.
\end{align}
where $\vec \alpha$ is used for shorthand and represents the vector of all the variational parameters.
We finally define a new quantity, called \textbf{the local energy}:
\begin{align}
E_L(\vec R, \vec \alpha) &= \frac{1}{\Psi_T}H\Psi_T\label{eq:E_L}
\end{align}
Combining these two definitions we can now rewrite $\expval{H}$ as follows:
\begin{align}
\begin{split}
\expval{H} &= \int \dd{\vec R} P(\vec R,\vec\alpha) E_L(\vec R,\vec\alpha)\\
&\approx
\frac{1}{n}\sum_{i=1}^n E_L(\vec R_i,\vec\alpha),
\end{split}\label{eq:the-objective}
\end{align}
where $R_i$ are randomly drawn positions from the PDF $P(\vec R, \vec\alpha)$.
We have therefore that estimating the average value of $E_L$ yields an
approximated value for $\expval{H}$. This value is in turn be an upper bound on the
ground state energy, $E_0$. By the variational principle, if we minimize
$\expval{H}$ under the variational parameters, we find an estimate for the true
ground state energy of the system.
\subsubsection{Exact Result for Simple System}
It will be useful to be able to compare our results with exact analytical
results where we have these. In the case of the symmetric harmonic oscillator
trap, ignoring any iteractions between the bosons, we have an exact form for the
ground state energy:
\begin{align}
E_0 = \sum_{i=1}^N\sum_{d=1}^{D=\{1,2,3\}} \frac{\hbar \omega_{ho}}{2}
= \frac{N\times D}{2},\label{eq:exact-ground-state}
\end{align}
for $N$ independent bosons in $D$ dimensions (the two sums goes
over all the degrees of freedom in the system). This follows from the setting
$\alpha=\flatfrac{1}{2}$ (and $\beta=1$) in $\Psi_T$, and using $a=0$ (no
interaction).
We also have an exact value for the variance of the energy in this case:
\begin{align}
\begin{split}
\sigma_E^2 &= \expval{H^2} - \expval{H}^2\\
&= \expval{H^2}{\Psi}-\expval{H}{\Psi}^2\\
&= \expval{E^2}{\Psi}-\expval{E}{\Psi}^2\\
&= E^2\braket{\Psi} - \qty(E\braket{\Psi})^2= 0.
\end{split}\label{eq:var-zero-when-exact}
\end{align}
This follows when we have the exact wavefunction, which satisfies the time
independent Schrödinger equation, $H\ket{\Psi}=E\ket{\Psi}$.
\subsubsection{Gross-Pitaevskii Equation}
The interactive system under investigation here can be approximated by the
Gross-Pitaevskii equation, which is valid when the Bose-gas in question is
sufficiently dilute. The energy under this model is given
as\cite{Nilsen-phys-rev}:
\begin{align}
\begin{split}
&E_{\text{GP}}[\Psi]=
\int
d\vec{R}\bigg[\frac{1}{2}\norm{\nabla\Psi}^2+V_{ext}\abs{\Psi}^2+2\pi a\abs{\Psi}^4\bigg].
\label{eq:GP_integral}
\end{split}
\end{align}
If we insert the elliptical potential, and drop the Jastrow factor from the
wavefunction (i.e. solve for the non-interacting case, setting $a=0$), we solve
this analytically and obtain an exact formula for the energy in the elliptical
case as well. This will prove very useful as a benchmark for our
implementation. Evaluating the integral we end up with (assuming
$\omega_z=\beta$, which will also be used later)
\begin{align}
E_\text{GP} = N\cdot
\qty(\frac{1}{4\alpha}+\alpha)\cdot\qty(1+\frac{\beta}{2}),\label{eq:GP-final}
\end{align}
which we can see corresponds to \eqref{eq:exact-ground-state} when $\beta=1$.
\subsection{Calculating the Local Energy $E_L$}
As the local energy is the quantity we are interested in computing for a
large set of positions we would do well to consider how best to evaluate this
expression effectively. For this we have two alternative approaches,
\begin{inparaenum}[1)]
\item numerical differentiation and
\item finding an analytic, direct expression.
\end{inparaenum}
\subsubsection{Numerical differentiation}
We may set up an algorithm for the numerical approximation of the local energy
as shown in Algorithm~\ref{alg:E_L-numeric}.
\begin{algorithm}[H]
\caption{Calculate the local energy $E_L$ using numerical differentiation.}
\label{alg:E_L-numeric}
\begin{algorithmic}[1]
\REQUIRE $\vec R = [\vec r_1,\vec r_2,\dots,\vec r_N]$, $D=\text{dimensions}$
\ENSURE $y = E_L$
\STATE $y = -2\times N\times D\times \Psi_T(\vec R)$
\FOR{$i = 1$ \TO $N$}
\FOR{$d = 1$ \TO $D$}
\STATE $\vec R_+\leftarrow \vec R + h \vec e_{i, d}$
\STATE $\vec R_-\leftarrow \vec R - h \vec e_{i, d}$
\STATE $y\leftarrow y + \Psi_T(\vec R_+) + \Psi_T(\vec R_-)$
\ENDFOR
\ENDFOR
\STATE $y\leftarrow -\flatfrac{y}{2h^2}$
\STATE $y\leftarrow \flatfrac{y}{\Psi_T(\vec R)}+\sum_{i=1}^N V_{ext} + \sum_{i<j}^N V_{int} $
\end{algorithmic}
\end{algorithm}
An evaluation of $E_L$ using this algorithm would be $\mathcal{O}(N^3\times
D)=\mathcal{O}(N^3)$ with interaction, and $\mathcal{O}(N^2)$ without interaction, from
the complexity of $\Psi_T$.
\subsubsection{Finding an Analytical Expression for $E_L$}
Straight forward numerical differentiation is of course an
option, but this is likely to be quite time-expensive to do. We will here try to
speed up the calculation by producing a direct formula.
The hard part of the expression for $E_L$ is
\begin{align}
\frac{1}{\Psi_L}\sum_{k}^N\laplacian_k{\Psi_L}.
\end{align}
To get going, we rewrite the wave function as
\begin{align}
\Psi_L(\vec R) &= \prod_i \phi(\vec r_i)\exp(\sum_{i<j}u(r_{ij})),
\end{align}
where $r_{ij} = \norm{\vec r_{ij}} = \norm{\vec r_i - \vec r_j}$, $u(r_{ij}) =
\ln f(r_{ij})$, and $\phi(\vec r_i)=g(\alpha,\beta,\vec r_i)$.
Lets first evaluate the gradient with respect to particle $k$
\begin{align}
\begin{split}
\grad_k{\Psi_T(\vec r)}
&= \grad_k{\prod_i \phi(\vec r_i)\exp(\sum_{i<j}u(r_{ij}))}\\
&= \prod_{i\neq k} \phi(\vec r_i)\exp(\sum_{i<j}u(r_{ij}))\grad_k{\phi(\vec
r_k)}\\
&+ \prod_{i} \phi(\vec r_i)\grad_k{\exp(\sum_{i<j}u(r_{ij}))}\\
&= \Psi_T\qty[\frac{\grad_k \phi(\vec r_k)}{\phi(\vec r_k)} + \sum_{j\neq k}
\grad_k u(r_{kj})].
\end{split}\label{eq:grad-trail-wf}
\end{align}
The first term is evaluated quite simply:
\begin{align}
\begin{split}
\frac{\grad_k\phi(\vec r_k)}{\phi(\vec r_k)} &= \frac{\grad_k}{\phi(\vec r)}
\exp[-\alpha\qty(x_k^2 + y_k^2 + \beta z_k^2)]\\
&= -2\alpha\hat{\vec r}_k,
\end{split}\label{eq:grad-phi_k-over-phi_k}
\end{align}
where the notation $\hat{\vec r}_k = (x, y,\beta z)$ is introduced for brevity.
Note that in the 1D and 2D case we simply have $\hat{\vec r}_k = \vec r_k$.
The second term may be evaluated as follows:
\begin{align}
\begin{split}
\grad_k u(r_{kj}) &= u'(r_{kj})\grad_k \sqrt{\norm{\vec r_k - \vec r_j}^2} \\
&= \frac{u'(r_{kj})}{2r_{kj}}\grad_k\qty(\norm{\vec r_k}^2-2\vec r_k\vdot\vec
r_j+\norm{r_j}^2)\\
&= u'(r_{kj})\frac{\vec r_{kj}}{r_{kj}}\\
&= \pdv{}{r_{kj}}\qty[ \ln(1 - \frac{a}{r_{kj}})] \frac{\vec
r_{kj}}{r_{kj}}\\
&= \frac{\vec r_{kj}}{r_{kj}}\frac{a}{r_{kj}(r_{kj}-a)}.
\end{split}\label{eq:grad-u}
\end{align}
Now we can find the Laplacian by taking the divergence of
\eqref{eq:grad-trail-wf}:
\begin{align*}
\frac{\laplacian_k{\Psi_L}}{\Psi_L} &= \frac{1}{\Psi_L}\grad_k\vdot
\Psi_T\qty[\frac{\grad_k \phi(\vec r_k)}{\phi(\vec r_k)} + \sum_{j\neq k}
\grad u(r_{kj})] \\
&= \frac{\laplacian_k \phi(\vec r_k)}{\phi(\vec r_{k})}+\sum_{j\neq
k}\laplacian_k u(r_{kj})\\
&+ \frac{\grad_k\qty(\phi(\vec r_k)) \vdot \qty(\sum_{j\neq k} \grad_k
u(r_{kj}))}{\phi(\vec r_k)}\\
&+ \left[
\qty(\frac{\grad_k \phi(\vec r_{k})}{\phi(\vec r_k)}
+ \sum_{j\neq k}\grad_k u(r_{kj}) )\right.\\
&\left.\vdot
\qty(\sum_{j\neq k} \grad_k u(r_{kj}) )\right] \\
&= \frac{\laplacian_k \phi(\vec r_k)}{\phi(\vec r_k)}
+ 2 \frac{\grad_k \phi(\vec r_k)}{\phi(\vec r_k)}\vdot
\sum_{j\neq k}\qty( \frac{\vec r_{kj}}{r_{kj}}u'(r_{kj}))\\
&+ \sum_{i,j \neq k} \frac{\vec r_{ki}\vdot\vec r_{kj}}{r_{ki}r_{kj}}
u'(r_{ki})u'(r_{kj})
+ \sum_{j\neq k}\laplacian_k u(r_{kj}).\numberthis\label{eq:almost-done-EL}
\end{align*}
There are two new quantities here which need to be evaluated before we are done:
\begin{align}
\begin{split}
\frac{\laplacian_k \phi(\vec r_k)}{\phi(\vec r_k)} &=
2\alpha\qty[2\alpha \norm{\hat{\vec r}_k}^2 - d(\beta)],\\
&\text{with } d(\beta) = \begin{cases}
1 &\qfor \text{1D}\\
2 &\qfor \text{2D}\\
2 + \beta &\qfor \text{3D}
\end{cases},
\end{split}
\end{align}
and
\begin{align}
\begin{split}
\laplacian_k u(r_{kj}) &= \grad_k\vdot u'(r_{kj})\frac{\vec
r_{kj}}{r_{kj}} \\
&= u'(r_{kj})\frac{2}{r_{kj}} + \frac{\vec r_{kj}}{r_{kj}}\vdot \grad_k
u'(r_{kj})\\
&= u''(r_{kj}) + \frac{2}{r_{kj}}u'(r_{kj}),
\end{split}
\end{align}
where
\begin{align}
\begin{split}
u''(r_{ij}) &= \pdv[2]{}{r_{ij}} \ln(1-\frac{a}{r_{ij}})\\
&= \frac{a(a-2r_{ij})}{r_{ij}^2(r_{ij}-a)^2}.
\end{split}
\end{align}
Inserting all of this back into \eqref{eq:almost-done-EL} we get:
\begin{align}
\begin{split}
\frac{1}{\Psi_L}\laplacian_k{\Psi_L} &=
2\alpha\qty[2\alpha \norm{\hat{\vec r}_k}^2 - d(\beta)]\\
&- 4\alpha\hat{\vec r}_k \vdot
\qty[ \sum_{j\neq k} \frac{\vec r_{kj}}{r_{kj}}
\frac{a}{r_{kj}(r_{kj}-a)}]\\
&+ \sum_{i,j\neq k} \frac{\vec r_{ki}\vdot\vec r_{kj}}{r_{ki}r_{kj}}
\frac{a}{r_{ki}(r_{ki}-a)}\frac{a}{r_{kj}(r_{kj}-a)}\\
&+ \sum_{j\neq k} \qty(
\frac{a(a-2r_{kj})}{r_{kj}^2(r_{kj}-a)^2} +
\frac{2}{r_{kj}}\frac{a}{r_{kj}(r_{kj}-a)}).
\end{split} \label{eq:E_L-part-final}
\end{align}
We may note that without interactions ($a=0$), this simplifies to only the first
term, as all the other terms are proportional to $a$.
The complete expression for the local energy is then:
\begin{align*}
E_L &= \frac{1}{\Psi_T}H\Psi_T\\
&= \sum_{i}V_{ext}(\vec r_i) + \sum_{i<j}V_{int}(\vec r_i,\vec r_j)
- \frac{1}{2}\sum_k
\frac{1}{\Psi_T}\laplacian_k\Psi_T\numberthis\label{eq:E_L-final}
\end{align*}
where we substitute in \eqref{eq:E_L-part-final} in the final sum. A single
evaluation of the local energy is then $\mathcal{O}(N^3)$ with interaction,
and $\mathcal{O}(N)$ without.
We can see that without interaction we obtain a linear-time expression, compared
to quadratic-time using numerical differentiation. With interaction we have
not been able to improve the complexity in terms of Big-O. This does not,
however, mean that no improvement is obtained. A closer look shows that the
numerical approach uses more evaluations by a constant factor of about three.
This stems from the three wave function evaluations used in the central
difference approximation of the second derivative. The analytic approach is
closer to using a single evaluation, although the exact ratio is hard to define
as the wave function is not directly used here.
In summary, we will expect a significant speedup using the analytic expression
both with and without interaction enabled.
\subsection{Calculating the Quantum Drift Force}
Anticipating its later use, we will also find an expression for the so called
quantum drift force, which we shall use when we consider importance sampling.
For now, we just give its definition:
\begin{align}
\vec F_k = \frac{2\grad_k\Psi_T}{\Psi_T}\label{eq:Q-force-def}
\end{align}
This is interpreted as the force acting on particle $k$ due to the trap and/or
presence of other particles. As a physical justification for why $\vec F_k$
takes this form we can see that $\vec F_k$ is
proportional with the gradient of $\Psi_T$, which we can intuitively understand
as a force pushing the particle towards regions of space with higher
probability.
Luckily this can now be quickly evaluated due to
the results of the previous section,
\begin{align}
\vec F_k = 2\qty[\sum_{j\neq k}\frac{\vec r_{kj}}{r_{kj}}
\frac{a}{r_{kj}(r_{kj}-a)} - 2\alpha\hat{\vec
r}_k].\label{eq:Q-force-explicit}
\end{align}
With interaction this is $\mathcal{O}(N)$, and without ($a=0$) it simplifies to $\mathcal{O}(1)$.
For brevity, we may later use the notation $\vec F(\vec R) = [\vec F_1, \vec
F_2,\dots,\vec F_N]$, denoting the matrix of all the individual forces on each
particle.
\subsection{One-Body Density}
A quantity which is often of great interest is the one-body density. It is defined for particle $1$ as
\begin{align}
\rho(\vec r_1) = \int \dd{\vec r_2}\dd{\vec r_3}\dots\dd{\vec r_N} \abs{\Psi(\vec R)}^2\label{eq:one-body-def},
\end{align}
and similarly for particle $i = 2,3\dots, N$. All particles are indistinguishable, so which $i$ we consider is arbitrary.
The one-body density gives a measure of the distribution of particles in the
system. It can be read as: if we marginalize out the positions of all other
particles, what is the likelihood of finding particle $i$ in a given position?
The answer to this question is given by $\rho_(r_i)$.
For the non-interacting case we can evaluate this expression exactly, as the
wavefunction separates nicely.
\begin{align}
\begin{split}
\rho(\vec r_k)&=g(\vec r_k)\prod_{i\neq k}\iiint_{-\infty}^\infty
\dd{x_i}\dd{y_i}\dd{z_i}g(\vec r_i)\\
&= \qty(\frac{\pi^{3/2}}{2\sqrt{2}\alpha^{3/2}\sqrt{\beta}})^{N-1}
g(\vec r_k)\\
\end{split}\label{eq:one-body-exact}
\end{align}
The constant is of little importance to us, but what we want is the functional
form of $\rho(\vec r_k$, which we see follows the Gaussian shape of the
single-particle wavefunction.
In the non-interacting case this integral is far less friendly to us, and we have no
exact formula or shape. We shall therefore compute the integral numerically. However,
instead of going about this with straight forward Monte Carlo integration, we
shall take a more intuitive approach.
We split the position space into $M$ spheres\footnote{Or circles in 2D, and line
segments in 1D.} of increasing radii, $r_i=i * r_\text{step}$ for $i=1,\dots,M$,
all centered at the origin. The volume of the sphere with radius $r_{i+1}$, minus
the volume of the sphere with radius $r_i$, we call region $i+1$. The
illustration below shows this graphically, where region $i+1$ is the lightly
shaded region.
\begin{center}
\begin{tikzpicture}
\shade[ball color = gray!40, opacity = 0.4] (0,0) circle (3cm);
\draw (0,0) circle (3cm);
\draw (-3,0) arc (180:360:3 and 1.2);
\draw[dashed] (3,0) arc (0:180:3 and 1.2);
\fill[fill=black] (0,0) circle (1pt);
\shade[ball color = gray!50, opacity = 0.9] (0,0) circle (2cm);
\draw (0,0) circle (2cm);
\draw (-2,0) arc (180:360:2 and 0.6);
\draw[dashed] (2,0) arc (0:180:2 and 0.6);
\fill[fill=black] (0,0) circle (1pt);
\draw[dashed, ->] (0,0 ) -- node[above]{\Large $\vec r_i$} (2,0);
\draw[dashed, ->] (0,0 ) -- node[sloped, anchor=center, above]{\Large $\vec r_{i+1}$} (2.1213,2.1213);
\end{tikzpicture}
\end{center}
For each sampled position $\vec R$, we can note down which region particle $1$
(arbitrary choice) is within, and keep a running tally for each region. After
sampling many positions, we normalize each region count by both the number of
samples and the volume\footnote{Or area in 2D, and length in 1D} of the
region. Given a small enough $r_\text{step}$, and enough samples, we would then
plot the normalized region counts against their radii, and this would be expected
to approximate the one-body density well.
As a technical note, because the choice of which particle we observe is
arbitrary, we could have done this for any other particle. We could therefore do
it for all particles in parallel, by noting which region \textit{every} particle
lands in. Since they should all produce a similar result, we could average the
recorded counts across all particles. This should be roughly the same as if we
had $N$ times as many samples and only counted for one particle.
\section{Algorithms}
In \eqref{eq:the-objective} we reformulated our objective of estimating the ground state energy of the
system, $\expval{H}$, to minimizing the average local energy, $\expval{E_L(\vec \alpha)}$ w.r. to
the variational parameters $\vec \alpha = (\alpha, \beta)$. Key to this
reformulation was that the local energy had to be sampled with positions $\vec
R$ that where drawn from the PDF $P(\vec R, \vec\alpha)$. As $P$ is far from any
standard PDF with a known inverse CDF, we cannot trivially generate such
samples. In addition, the normalisation term in its denominator is
computationally expensive to compute. These limitations make the
\textit{Metropolis algorithm} the obvious choice to solve this problem. This
algorithm provides a way to generate random samples from a PDF where we only
know the probabilities up to a proportionality constant.
\subsection{Metropolis Algorithm}
The algorithm in its
simplest form is described in Algorithm~\ref{alg:metropolis-simple}.
\begin{algorithm}[H]
\caption{The Metropolis algorithm in its simplest form, as it
pertains to our specific application.}
\label{alg:metropolis-simple}
\begin{algorithmic}[1]
\REQUIRE $M$, generates $M\times N$ samples.
\ENSURE $\text{samples} \setfrom P(\vec R, \vec\alpha)$
\STATE $\text{samples} \leftarrow \text{empty list}$
\STATE $\vec R \leftarrow \text{randomly initialized matrix of positions}$
\FOR{$M$ iterations}
\FOR{every particle $i\in[1, N]$}
\STATE $\Delta \vec{r} \leftarrow \text{random perturbation vector}$
\STATE $\vec R^*\leftarrow \vec R $
\STATE $\vec R^*_i \leftarrow \vec R^{*}_i+ \Delta \vec{r}$
\STATE $q \leftarrow \flatfrac{\abs{\Psi_T(\vec R^*)}^2}{\abs{\Psi_T(\vec R)}^2}$
\STATE $r \setfrom \text{Unif}(0, 1)$
\IF{ $r\leq q$ }
\STATE $\vec R \leftarrow \vec R^*$
\ENDIF
\STATE Append $\vec R$ to samples
\ENDFOR
\ENDFOR
\end{algorithmic}
\end{algorithm}
In this algorithm we move around in position space randomly, accepting new
positions biased towards areas of space where $P(\vec R,\vec\alpha)$ is higher.
We choose to move one particle at a time based on computational efficiency, as
recalculating the local energy can be done more easily when we know only one
particle has moved\footnote{Not actually implemented yet.}.
With the generated list of positions we may produce and average for the local
energy, and therefore an estimate for an upper bound on the ground state energy,
as well as the one-body density, or any other quantity of interest.
\subsubsection{Limitations}
This algorithm has two major drawbacks. Firstly, the samples generated are not
independent. It is quite clear from the algorithm that the probability of
drawing a certain position is highly dependent on what position we were at
previously. The has implications on how we perform our statistical analysis, as
we must attempt to correct for this limitation. More on this in
section~\ref{sec:statistical-analisys}.
Secondly this algorithm will be quite ineffective in that a significant portion
of the suggested moves (new positions, $\vec R^*$ in
Algorithm~\ref{alg:metropolis-simple}) will be rejected. This is because the new
positions are generated at random, which might cause us to wander around in
regions of position space that are of very little significance, and it might
take a while before we (by chance) stumble upon a more high-probability region.
The effect is then a list of samples that may not be an accurate representation
of the PDF we were trying to approximate to begin with. This will be especially
true for smaller sample sizes, were these defects will account for a larger
proportion of the samples.
\subsection{Metropolis-Hastings Algorithm - Including Importance Sampling}
The first limitation of the simple algorithm (not i.i.d.) is inherent to this
kind of sampling, and is hard to avoid. We may, however, attempt to remedy the
second limitation by guiding the random walker towards more promising regions of
position space by proposing new positions in a smarter way than purely randomly.
\subsubsection{Physical Motivation of Results}
We will limit our selfs to a superficial derivation, focusing only on giving a
physical motivation for the results we end up using, as it is outside the scope
of this project to derive this rigorously.
\paragraph{Better generation of new positions:}$\,$\\
A reasonable assumption is to say that particles will tend towards regions of
space where $\abs{\Psi_T}^2$ is larger. We may say that this is the result of a
force, namely the quantum drift force given in \eqref{eq:Q-force-def}, as we
know this force pushes particles towards regions where $\Psi_T$ is large. In
addition, as this a quantum system, we expect some degree of random motion as
well. This intuitive view is exactly what is described by
the Langevin equation,
\begin{align}
\pdv{\vec r_k}{t} = D\vec F_k(\vec r_k) + \vec\eta,\label{eq:Langevin}
\end{align}
which describes how the position of a particle changes with time under the
influence of a drift force and random impulses. Here, $D$ is
a constant scalar referred to as the drift coefficient. We set
$D=\flatfrac{1}{2}$, originating from the same factor in the kinetic energy. The
term $\vec\eta$ is a vector of
uniformly distributed random values, giving the particle some random motion in each
dimension.
Solving the Langevin equation we can obtain new positions at some time
$t+\Delta t$. Using Euler's method we get:
\begin{align}
\vec r^* = \vec r + \frac{1}{2}\vec F_k(\vec r_k)\Delta t + \vec \xi\sqrt{\Delta
t}\label{eq:Langevin-solution},
\end{align}
given a time step $\Delta t$, and where $\vec \xi$ is the normally distributed
equivalent of $\vec \eta$.
\paragraph{Adjusting the acceptance probability:}$\,$\\
In Algorithm~\ref{alg:metropolis-simple} the acceptance probability for a new
position $\vec R^*$ was
\begin{align}
q(\vec R^*, \vec R) = \frac{\abs{\Psi_T(\vec R^*)}^2}{\abs{\Psi_T(\vec
R)}^2}\label{eq:q-simple}.
\end{align}
This was based on the transition probability for going to $\vec R^*$ from $\vec
R$ being uniform. When the transition probabilities are different depending on
where we are and where we want to go, the acceptance probability has to be
modified in order for the algorithm to work as advertised. In general, we have
the following form for $q(\vec R^*, \vec R)$ in our case:
\begin{align}
q(\vec R^*, \vec R) &= \frac{T_{j\rightarrow i}}{T_{i\rightarrow j}}\frac{\abs{\Psi_T(\vec R^*)}^2}{\abs{\Psi_T(\vec
R)}^2},\label{eq:q-full}
\end{align}
where $T_{i\rightarrow j}$ is the transition probability from the original state
$i$ into the new state $j$. We see that a uniform transition probability gives
us back \eqref{eq:q-simple}. We need therefore an expression for the transition
probabilities when we use the improved generation of new positions.
To this end, we consider the \textit{Fokker-Planck} equation, which for one
dimension and one particle can be written as
\begin{align}
\pdv{\Psi_T}{t} = D\pdv{}{x}\qty(\pdv{}{x} - F)\Psi_T,\label{eq:Fokker-Planck}
\end{align}
which describes the time-evolution of a probability distribution under the
influence of a drift force and random impulses. We let $\Psi_T$ play the role of the
probability distribution. The factor $D$ is as before, and $F$ is here the
one-dimensional, one-particle analog to $\vec F$. In
fact, this equation is the origin of the specific form of $\vec F$ presented in
\eqref{eq:Q-force-def}.
Equation \eqref{eq:Fokker-Planck} yields a solution given by
the following Green's function (for one particle):
\begin{align}
G(\vec r_k^*, \vec r_k, \Delta t) &\propto
\exp[- \frac{\norm{\vec r_k^* - \vec r_k - D\Delta t \vec F_k(\vec r_k)}^2}{4D\Delta t} ].
\end{align}
This is interpreted as the probability of transitioning to position $\vec r_k^*$
from position $\vec r_k$ in a time interval $\Delta t$. Replacing the transition
probabilities in Equation~\eqref{eq:q-full} we get the new acceptance
probability:
\begin{align}
q(\vec R^*, \vec R) &= \frac{G(\vec r_k, \vec r_k^*, \Delta t)}{G(\vec r_k^*, \vec r_k, \Delta t)}\frac{\abs{\Psi_T(\vec R^*)}^2}{\abs{\Psi_T(\vec
R)}^2},\label{eq:q-full-final}
\end{align}
\subsubsection{Improved Algorithm}
We are now ready to present the proper Metropolis-Hastings algorithm, with
importance sampling used to increase the number of accepted transitions.
\begin{algorithm}[H]
\caption{The Metropolis-Hastings algorithm, as it
pertains to our specific application.}
\label{alg:metropolis-importance}
\begin{algorithmic}[1]
\REQUIRE $M$, generates $M\times N$ samples.
\ENSURE $\text{samples} \setfrom P(\vec R, \vec\alpha)$
\STATE $\text{samples} \leftarrow \text{empty list}$
\STATE $\vec R \leftarrow \text{randomly initialized matrix of positions}$
\FOR{$M$ iterations}
\FOR{every particle $i\in[1, N]$}
\STATE $\Delta\vec r_i^* \leftarrow \frac{1}{2}\vec
F_i(\vec r_i)\Delta t + \vec \xi\sqrt{\Delta t}$
\STATE $\vec R^*\leftarrow \vec R $
\STATE $\vec R^*_i \leftarrow \vec R^{*}_i+ \Delta \vec r_i^*$
\STATE $q \leftarrow \flatfrac{\abs{\Psi_T(\vec R^*)}^2}{\abs{\Psi_T(\vec R)}^2}$
\STATE $q \leftarrow q \times \flatfrac{G(\vec r_k, \vec r_k^*,
\Delta t)}{G(\vec r_k^*, \vec r_k, \Delta t)}$
\STATE $r \setfrom \text{Unif}(0, 1)$
\IF{ $r\leq q$ }
\STATE $\vec R \leftarrow \vec R^*$
\ENDIF
\STATE Append $\vec R$ to samples
\ENDFOR
\ENDFOR
\end{algorithmic}
\end{algorithm}
\subsection{Optimizing the Variational Parameters}
The point of VMC is to vary the parameters of the wavefunction, here $\alpha$
and $\beta$, in such a way that the energy is minimized. This is in other words
a classic optimization problem, to which we can apply one of the many available
techniques. One of the simpler and more intuitive approaches is Gradient Decent,
which is the one we will apply. We could have\footnote{Perhaps even should have,
in hindsight.} opted for a better method, such as Conjugate Gradient, but
standard Gradient Decent was chosen for simplicity.
\subsubsection{Gradient Decent}
The intuition for Gradient Decent (along with most other techniques) is based on
the fact that extrema, $\vec x^*$, of a function $f(\vec x^*)$ have the property of zero gradient,
$\grad f(\vec x^*) = 0$. Using this, and starting at any initial guess $\vec
x_0$, we can update this guess to a point with \textit{smaller} gradient by
following the direction of $-\grad f(\vec x_0)$. In less words, the improved
guess $\vec x_1$ is given by
\begin{align}
\vec x_1 = \vec x_0 - \gamma \grad f(\vec x_0),
\end{align}
where $\gamma$ is a hyper-parameter referred to as the \textit{learning rate},
and typically $\gamma < 1$.
Following the same recipe, we can generate arbitrarily small gradients by
iterating
\begin{align}
\vec x_{i+1} = \vec x_i - \gamma \grad f(\vec x_i).
\end{align}
We are guaranteed, given a sufficiently small $\gamma$ and enough iterations, to
arrive at \textit{a} minimum with this technique. As with all numerical
optimization schemes, we are always having to consider the possibility of the
minimum only being local, and not the global one.
\paragraph{Defining the Gradient:}$\,$\\
In our case, the function we want to minimize is $E_0=\expval{H}$. The only
parameter we will treat as varying in this report is $\alpha$, as we shall fix
$\beta$ later on. Therefore, the gradient is
\begin{align}
\grad_\alpha \expval{H} = \pdv{\expval{H}}{\alpha}
\end{align}
With some algebraic massage we can rewrite this as
follows~\cite{mhj-compphys-II}:
\begin{align}
\grad_\alpha \expval{H} =
2\qty[\expval{\frac{E_L}{\Psi_T}\pdv{\Psi_T}{\alpha}} -
\expval{E_L}\expval{\frac{1}{\Psi_T}\pdv{\Psi_T}{\alpha}}]\label{eq:gradient-nice}
\end{align}
The derivative of the wavefunction with respect to $\alpha$ is found easily,
\begin{align}
\frac{1}{\Psi_T}\pdv{\Psi_T}{\alpha} = -\sum_{i}^N\qty(x_i^2 + y_i^2+\beta
z_i^2)
\end{align}
as dividing by $\Psi_T$ cancels the interaction factor. For 1D and 2D we simply
drop the other coordinate terms.
We can now compute the two expectation values in~\eqref{eq:gradient-nice} from
the sampled positions $\vec R_j$, and get an approximation for the gradient.
\paragraph{Limitations:}$\,$\\
Gradient Decent is wonderfully simple, but has its limitations. Firstly, the
results are highly dependent on on the hyper-parameters, which are the initial
guess $\vec x_0$ and the learning rate.
A bad guess can mean we spend a long time finding our way to the minimum. A bad
guess also increases the likelihood of getting stuck in local optima on the way.
The learning rate must also be just right. To low and we take forever to get
anywhere, and we very easily get stuck in small bumps in the function output
space. Make $\gamma$ to large and we have trouble actually converging to
anything. We may also end up with exploding gradients if we are so unlucky.
All in all there are tons of pitfalls, but we hope our energy function is
relatively well behaved, and that we can provide good values for the
hyper-parameters.
\section{Evaluating the Validity of Results}
\label{sec:statistical-analisys}
Once one of the above algorithms has been used to obtain numerical results,
these are of little use to us as scientist if we know nothing about the
certainty with which we can trust our the answers we get. To that end we would
like to make an estimate of the magnitude of the error in our results.
There are two main sources of errors that enter our results, namely
\begin{inparaenum}[1)]
\item systematic error and
\item statistical error.
\end{inparaenum}
The systematic error comes from our assumptions about how we model the quantum
mechanical system, i.e. the form of the Hamiltonian, the ansatz for our
wavefunction, the hyper-parameters used in the computation etc. This error is
intrinsic to our approach and is hard to both quantify and avoid.
More of interest to us is therefore the statistical error, as we \textit{can} in
fact make an estimate for this.
\subsection{Standard Estimate of the Standard Error of the Mean}
The quantity we are looking to estimate is the
standard error of the mean local energy, typically defined as
\begin{align}
\sigma_{\bar E_L} = \sqrt{\frac{\sigma_{E_L}^2}{n}}= \sqrt{\frac{1}{n}
\qty[\expval{E_L^2} - \expval{E_L}^2]} \label{eq:SE-def},
\end{align}
where $n$ denotes the number of samples\footnote{Upper case $N$ will be used for
the number of particles in the system, lower case $n$ for the number of
samples.}, and $\sigma_{E_L}^2$ is the true population variance for the local energy. We
do not know the underlying population variance, and so we estimate this by the
sample variance instead:
\begin{align}
\hat\sigma_{\bar E_L} = \sqrt{\frac{\hat\sigma_{E_L}^2}{n}}=
\sqrt{\frac{1}{n}
\qty[\widehat{\expval{E_L^2}} - \bar{E}_L^2]}
\label{eq:SE-est-def}.
\end{align}
There is, however, a complication that should be taken into account when we
estimate this quantity, namely that our $E_L$ samples will not be drawn
independently. The above estimation for the standard error is based on the
central limit theorem, and key to this is the assumption that the samples should
be independently drawn.
Inherent to the Monte Carlo sampling techniques is that the value
of a sample at one point in time is in fact correlated to the sample before it.
Figure~\ref{fig:time-series-example} shows an example of consecutive samples
obtained using Algorithm~\ref{alg:metropolis-importance}. Although the values
vary quite a bit, we still see that if the values are very low it takes some
time before it can get large again, and vice versa.
\end{multicols}
\begin{figure}[!h]
\centering
\includegraphics[width=0.8\linewidth]{../results/time-series-example.png}
\caption{Example time series of local energy values obtained from a
simulation using Algorithm~\ref{alg:metropolis-simple}. Energies shown
are a small snippet of energies obtained for a system of one boson in one
dimension, using $\alpha=0.55$ and a step size of $1$. The mean from the entire set of samples is shown for reference}
\label{fig:time-series-example}
\end{figure}
\begin{multicols}{2}
The effect of this is that using \eqref{eq:SE-est-def} directly as the measure for
the statistical error will tend to \textit{underestimate} its true value.
\subsection{Adjusting for Correlated Samples}
We can make the error estimate in \eqref{eq:SE-est-def} less biased by replacing
the sample variance by the sample \textit{covariance}:
\begin{align}
\begin{split}
\hat{\sigma}_{\bar{ E_L}} &= \sqrt{\frac{\text{Cov}(E_L)}{n}}\\
&= \sqrt{\frac{1}{n^2}\sum_{i,j}\qty(E_{L,i} - \bar{E}_L)\qty(E_{L,j}-\bar{E}_L)},
\end{split}
\label{eq:SE-est-covar-def}
\end{align}
which we can rewrite in terms of the uncorrelated and correlated contributions
to the error as follows:
\begin{align}
\begin{split}
\hat{\sigma}^2_{\bar{E_L}} &=
\frac{\hat{\sigma}^2_{E_L}}{n}
+ \frac{2}{n^2}\sum_{i<j}\qty(E_{L,i} - \bar{E}_L)\qty(E_{L,j}-\bar{E}_L).
\end{split}\label{eq:SE-est-covar-expanded}
\end{align}
We observe that if the energies are uncorrelated in time, we would just get back
\eqref{eq:SE-est-def}.
To simplify the notation on the way to the end result, we define following two
functions:
\begin{gather}
f_d = \frac{1}{n-d}\sum_{k=1}^{n-d} \qty(E_{L,k} -
\bar{E}_L)\qty(E_{L,k+d}-\bar{E}_L)\\
\kappa_d = \frac{f_d}{\hat{\sigma}^2_{E_L}}.
\end{gather}
The function $f_d$ describes the correlation of samples spaced by $d$. We have
$f_0=\sigma_{E_L}^2$, and for an uncorrelated system we have $f_d=0\
\forall\ d>0$.
Now \eqref{eq:SE-est-covar-expanded} can be written as
\begin{align}
\begin{split}
\hat{\sigma}^2_{\bar{E_L}} &= \frac{\hat{\sigma}^2_{E_L}}{n} +
\frac{2\hat{\sigma}^2_{E_L}}{n}\sum_{d=1}^{n-1}\kappa_d\\
&= \frac{\tau}{n}\ \hat{\sigma}^2_{\bar{E_L}},
\end{split}
\end{align}
where we have defined the \textit{autocorrelation time} $\tau$,
\begin{align}
\tau = 1 + 2\sum_{d=1}^{n-1}\kappa_d,\label{eq:autocorr-time-def}
\end{align}
which can be interpreted as the spacing between samples for which we no longer
observe any correlation. For a completely uncorrelated sample set we have $\tau
=1$, which again results in \eqref{eq:SE-est-def}. Also, any $\tau>1$ will lead
to an \textit{increase} in the estimated error.
This new estimate of the error will be a much more realistic estimate. However,
computing the autocorrelation time $\tau$ has time complexity $\mathcal{O}(n^2)$, which will prove
unfeasible when we plan on producing millions of samples.
\subsection{Methods for Improving the Error Estimate}
We look now at two methods of obtaining improved estimates for the standard
error, besides computing the autocorrelation time $\tau$ directly.
We will look at two such tools here,
\begin{inparaenum}[1)]
\item Bootstrap and
\item Blocking.
\end{inparaenum}
\subsubsection{Bootstrap}
The best way to improve statistical results is usually to simply generate more
data, as statistical estimates tend towards their true value as the number of
samples grow. So ideally, we would simply generate many more sample sets,
$\{E_L\}_b \qfor b=1, 2, \dots, B$, compute the mean for each and produce a
histogram of the results. That would then, for a sufficiently large $B$, serve as
a good estimate for the probability distribution for $\bar E_L$. We could then
compute the standard deviation of said distribution and call that the standard
error of the mean local energy. This would not strictly address the problem of
correlation directly, but averaging results over more data would lessen the
effect. Also, we would expect the individual sample sets to be uncorrelated with
each other, as long as they had differing random seeds.
In practice this is not feasible though, as producing each set of energies will be a
sizable computational task in it self, and not something we can repeat several
times. This is were Bootstrap comes in. The idea of Bootstrap is to simulate
the production of new sample sets by resampling, with replacement, from the
original data set. From the original set $\{E_L\}_1$ we draw $n$ samples with a
uniform probability to get new sets $\{E_L\}_b\qfor b = 2,3,\dots,B$.
As long as the original data set is a representative sample of the space of
energy values (i.e. not biased towards large/small values), and we use a large
enough value for $B$, this will produce a good approximation of the statistical
error.
This approach has to main limitations. First, it is computationally
expensive to do when the size of the data set is very large, and we need a large
$B$ value.
Second, Bootstrap is still meant to be used on iid. samples, and any estimates
for the error we get from it will still be an underestimate. This comes from the
fact that the original sample set won't be a fully representative sample of the
space, due to the correlations within it. Using Bootstrap will improve the
estimate, but it will still be biased.
\subsubsection{Blocking}
In some sense Blocking takes the complete opposite approach to that of
Bootstrap. Blocking takes the original samples and combines them to make less
data points.
The idea is to group consecutive samples into \textit{blocks} of a size such
that sample $i$ in block $j$ is uncorrelated with sample $i$ in block $j+1$.
Then, treating each block as a single sample (i.e. by computing the average
energy in each block), we have independent samples of the mean.
The only issue with this approach is determining how large the blocks need to be
in order for the blocks to become independent. A natural choice would be the
autocorrelation time $\tau$, but that just brings us back to the original
problem of computational infeasibility.
A simple, empirical solution to finding a suitable block size is to make a plot
of the standard deviation of the block means as a function of block
size. Because correlated samples meant we \textit{underestimated} the error (aka.
standard deviation of the sample mean), increasing the block size (i.e. making the
samples less correlated) should increase the observed error. This would keep
going until the block size is so large that the samples have become independent,
at which points it should plateau. Choosing the block size at the plateau point
would then be optimal.
Even better would be an automated way to determine the ideal block size. Such
methods do exists, and will for simplicity be used in this project, although the
manual way would work. The derivation of how this
works, however, will not be discussed any further in this report.
\section{Results for Non-Interacting System}
\subsection{Standard Metropolis Sampling}
\subsubsection{Comparison of Configurations of Parameters}
We now apply the standard Metropolis sampling algorithm described in
Algorithm\ref{alg:metropolis-simple} to a variety of different settings.
Table~\ref{tab:simple-metro} shows selected results obtained using
$\alpha=\flatfrac{1}{2}$, which corresponds to running with the exact
wavefunction.
We see that all the results have $\expval{E_L}$
equal (within numerical precision) to the exact result, following
\eqref{eq:exact-ground-state}. In addition, the variance is also equal to
or extremely close to zero, as we expect to observe when we use the correct form
for the exact wavefunction. This is strong evidence that the codes developed are
correct, at least for the non-interacting case.
We see a rather strong dependence on the step size used in the acceptance rates.
It appears we need smaller step sizes when $N$ increases. We would like to tune
the step size such that we have a significant portion accepted, but still not
run up into the$\sim \SI{100}{\percent}$ region. This is because at this point
we are just stuck in one place, with no real movement. This is not an issue in
the ideal case, because the energy here is actually not dependent on the
positions. But as soon as we move out of this ideal case, this will matter a
great deal. We conclude that a step of $1$ works well in most cases, but must be
lowered a bit for systems with $N \geq 100$.
Perhaps most interesting is to look at the time spent on each configuration. If
we compare the running times for $N=100$ and $N=500$ with analytical expressions
turned off, we see the time increasing by a factor of~$\sim 25$, which is the
square of the factor we increased $N$ by. Looking at the expressions involved in
Algorithm~\ref{alg:metropolis-simple}, we see that this is exactly what we would
expect, namely that the algorithm has time complexity $\mathcal{O}(N^2)$.
Similarly, comparing the run times when analytical expression is turned on, we observe
that time scales as $\mathcal{O}(N)$, resulting in a significantly reduced run
times. It is quite clear that the use of analytic expressions is far superior.
We can, however, expect the difference between the to approaches to be reduced
when we include interaction, as this reduced the analytical approach to the same
complexity as the numerical one.
\subsubsection{Varying the Variational Parameters}
Figure~\ref{fig:var-alpha-plot-noimp} shows a plot of the expected energy, and
corresponding variance, for a $1D$ system of one particle, using $5\cdot 10^4$ Monte
Carlo cycles, as a function of the variational parameter $\alpha$.
We can see a minimum in both graphs, both centered around the ideal value
$\alpha=\flatfrac{1}{2}$. The energy graph is, however, a bit jagged, and the
actual minimum has been found to be a little left of what we would expect. The
curve gets smoother as we increase the number of samples, and extending to
$10^5$ samples yield a {\lq perfect\rq} graph, and this is easily within our
computational reach. The relatively low value of $5\cdot 10^4$ was used to give a visual
difference to the result in the next section, when we include importance
sampling.
\end{multicols}
\begin{figure}[!h]
\centering
\includegraphics[width=0.9\linewidth]{../results/var-alpha-plot-noimp-50000.png}
\caption{Plot of average local energy and accompanying population variance,
as functions of the variational parameter $\alpha$. The minimum of both
graphs are marked, and is expected to be placed at
$\alpha=\flatfrac{1}{2}$. Results shown are for $1D$, one particle and
$5\cdot 10^{4}$ Monte Carlo cycles, using
Algorithm~\ref{alg:metropolis-simple}.}
\label{fig:var-alpha-plot-noimp}
\end{figure}
\begin{multicols}{2}
\subsection{Metropolis-Hastings Sampling}
\subsubsection{Comparison of Configurations of Parameters}
We now apply the improved Metropolis-Hastings sampling algorithm described in
Algorithm\ref{alg:metropolis-importance} to a variety of different settings.
Table~\ref{tab:importance-metro} shows selected results obtained using
$\alpha=\flatfrac{1}{2}$, which corresponds to running with the exact
wavefunction.
We see once again that all the results have $\expval{E_L}$
equal (within numerical precision) to the exact result, and very low variance,
indicating that the implementation works as it should.
Looking at the acceptance rates now we see ~$\sim\SI{100}{\percent}$ acceptance
of new moves, indicating that the proposed moves are quite probable and
therefore more likely to be accepted by the sampling algorithm. When $\Delta t$
is to large, however, the result become unstable, as before. At this point the
randomness in \eqref{eq:Langevin-solution} dominates, with steps larger than
what allows for convergence. We may tune this parameter as we wish, so choosing
a value that is small enough for the acceptance rate to be close to one, but
also not so small that we would need an excessive amount of MC cycles in order
to have any exploration in space. We will once again have to tune this parameter
depending on what system we look at, as we need a smaller step for larger
systems.
The run times reported have not changed in any significant way, as would be
expected, as adding importance sampling did not change the complexity of the algorithm.
\subsubsection{Varying the Variational Parameters}
Figure~\ref{fig:var-alpha-plot-imp} shows a plot of the expected energy, and
corresponding variance, for the same system and number of MC cycles as that
shown in Figure~\ref{fig:var-alpha-plot-noimp}. In this version we have enabled
importance sampling.
We can see a very similar result as before, with the notable exception that the
line is less jagged. This implies that the sampling results are more stable.
This is due to the improved exploration of the integration space which
importance sampling gives us. We conclude therefore that the improved algorithm
allows us better, more stable results, compared with the simple sampler. This
allows us to compute less MC samples in order to obtain good enough results,
something which is highly desired for an application where we are constantly
fighting against the large time complexity of this kind of system.
\end{multicols}
\begin{figure}[!h]
\centering
\includegraphics[width=0.9\linewidth]{../results/var-alpha-plot-imp-50000.png}
\caption{Plot of average local energy and accompanying population variance,
as functions of the variational parameter $\alpha$. The minimum of both
graphs are marked, and is expected to be placed at
$\alpha=\flatfrac{1}{2}$. Results shown are for $1D$, one particle and
$5\cdot 10^{4}$ Monte Carlo cycles, using
Algorithm~\ref{alg:metropolis-importance}}
\label{fig:var-alpha-plot-imp}
\end{figure}
\begin{multicols}{2}
To get a better view of the effect of $\Delta t$ on the Metropolis-Hastings
sampling algorithm, Figure~\ref{fig:var-alpha-plot-imp-dts} shows the same graph
as before, but for a set of different values for $\Delta t$. From this plot it
becomes very clear that choosing the correct value for this parameter will be
very important when we try to find the optimal variational parameters. We see
that the apparent minima appear on both the left and the right of the ideal
value.
All values are to some extent usable given enough MC samples, but an unrealistic
number might be needed for $\Delta t$ values far away from the optimum.
Figure~\ref{fig:var-alpha-plot-imp-dts} provides further evidence that $\Delta
t$ must be chosen with care.
\end{multicols}
\begin{figure}[!h]
\centering
\includegraphics[width=0.9\linewidth]{../results/var-alpha-plot-imp-dts-50000.png}
\caption{The same plot as shown in Figure~\ref{fig:var-alpha-plot-imp},
shown for multiple different values for $\Delta t$. We see that both too
large, and to small values yield less than ideal results.}
\label{fig:var-alpha-plot-imp-dts}
\end{figure}
\begin{multicols}{2}
\subsection{Statistical Error}
Figure~\ref{fig:errorbar} shows the results of a simulation on a system of one
boson in 3D, using $n=2^{14}$ Monte Carlo samples. On the graph, error bars are
included to visually express the certainty with which we know the results. The
magnitude of the error bars are given by the standard error, as determined by
the Blocking method. We see that the error estimate goes promptly to zero as we
approach the optimal $\alpha=\flatfrac{1}{2}$ value, and in fact we get exactly
zero as the standard error at this point. This is not that surprising, as using
the optimal value for $\alpha$ here means we are solving the exact system, and
therefore there should not be any doubt about the answer either.
The error estimates might be of higher importance as we traverse into the
interacting case.
\end{multicols}
\begin{figure}[!h]
\centering
\includegraphics[width=0.8\linewidth]{../results/error-plot-3D-2-pow-14.png}
\caption{Simulation results using Algorithm~\ref{alg:metropolis-importance},
running on a system of one boson in 3D, with $\Delta t=0.1$. Error bars have
been included, whose
magnitude are the standard error of the mean energy, as obtained by the
blocking method. In this simulation, $n=2^{14}$ Monte Carlo samples were
generated.}
\label{fig:errorbar}
\end{figure}
\begin{multicols}{2}
\subsection{One-Body Density}
It is also interesting to see how the calculated one-body density comes out for
the ideal non-interacting case. Figure~\ref{fig:density-ideal} shows the plot
for a system of 10 bosons in the 3D symmetric and elliptical harmonic oscillator
traps. Also drawn is the expected shape from \eqref{eq:one-body-exact}, for the
symmetric curve. All lines have been normalized so that they integrate to one,
as the constants are irrelevant to us here. To our delight the approximation
agrees very well with the expectation. The discrepancies around $r=0$ are due
the volumes of the smallest regions being very small, and hence their occupation
counts become somewhat unstable. We can still make out the trend though, which
again is in great agreement with the analytical result.
The elliptical curve deviates from that of the symmetrical (not surprising), and
we see that the effect is that particles tend to be closer to the origin. This
is understandable, as the parameters used here increase the $z$-component of the
potential by a factor $\sqrt{8}$. With a stronger confining potential, we would
expect exactly this behaviour
\end{multicols}
\begin{figure}[!h]
\centering
\includegraphics[width=0.8\linewidth]{../results/one-body-3D-N10-noniter.png}
\caption{One-Body density for a particle in a non-interacting system of 10
bosons in the 3D symmetric and elliptical harmonic oscillator traps. The results are with
$\alpha=\flatfrac{1}{2}$, using Algorithm~\ref{alg:metropolis-simple} with a
step length of $1$ and $10^6$ samples. For the elliptical trap,
$\beta=\omega_z=2.82843$ was used. For reference is the exact Gaussian
form expected (for the symmetric curve). All graphs have been normalized so that they integrate to 1.
The jagged shape around $r=0$ is an artifact of the approximation used,
where the volume of the regions become very small, and their counts become
less stable as a result. The $r$-axis is given in units of $a_{ho}$, and $\rho$ is
similarly dimensionless.}
\label{fig:density-ideal}
\end{figure}
\begin{multicols}{2}
\subsection{Optimization via Gradient Decent}
Even though we know the optimal value for $\alpha$ in the non-interacting case,
it will serve as a nice implementation test to verify that the algorithm is
capable of finding the minimum. Looking at \autoref{fig:var-alpha-plot-noimp}
and \ref{fig:var-alpha-plot-imp} we see that the energy function has a very
simple shape, with a single well defined minimum. Therefore we should expect to
be able to find the optimal $\alpha$, even with not so good guesses.
We will only state the observed results here. Many of them are reproduced in the
unit tests of the Gradient Decent method, if a source is desired.
We find that Gradient Decent is in fact able to find the minimum, and that to
arbitrary precision, given enough iterations. In the tests we used $10^4$ Monte
Carlo samples per iteration, which proved quite sufficient. This indicates that the
implementation works.
However, we observe it to be quite unstable with respect to the initial guess.
It works fine with guesses around $\alpha_0\in (0.3, 1)$, but if we start any
further away than this the results are unstable. This is likely due to the
gradient and variance increasing rapidly when we stray far from the optimum (as
seen in e.g. \autoref{fig:var-alpha-plot-noimp}).
\section{Results for Interacting System}
We now turn our attention to the elliptical trap with the repulsive interaction
activated. We shall in this report fix $\flatfrac{a}{a_{ho}}=0.0043$, and
$\beta=\gamma=2.82843\simeq\sqrt{8}$, as done in \cite{DuBois-phys-rev,
Nilsen-phys-rev}. We will consider systems with $N=10, 50$ and $100$ bosons.
\subsection{Varying the Variational Parameter}
\autoref{tab:inter-manual} shows results for all systems, using $\alpha$ values
in $[0.4, 0.6]$. \autoref{fig:interacting-energy-per-particle} Shows the
corresponding data in graphical form. We observe, as expected that the energy
per particle increases with increasing $N$. This makes sense, as there are more
bosons interacting, and hence the energy should also be higher.
Comparing our results to the exact solution for the non-interacting case
provided by \eqref{eq:GP-final}, we can
see that this is consistently \textit{underestimating} the energy, compared to
the VMC results. This is also as we expect. Adding particles, and considering
their interactions should only increase the energy compared to the ideal case.
The resolution of the data is too low to make any certain claims on where the
optimal value for $\alpha$ might be (it might even be outside the range tried
here). However with the data available we are suggested to believe that some
minimum exists in the range $\alpha\in [0.5, 0.6]$.
\end{multicols}
\begin{figure}[!h]
\centering
\includegraphics[width=0.8\linewidth]{../results/interacting-energy-per-particle.png}
\caption{Energy per particle, as a function of $\alpha$. We observe, as
expected, a higher energy per particle when we have more bosons in the
system. The plot has to low resolution to make any certain predictions about
where the optimal value might be. This would have been improved given
sufficient time.}
\label{fig:interacting-energy-per-particle}
\end{figure}
\begin{multicols}{2}
\subsection{Employing Gradient Decent}
After the initial scan made in the previous section Gradient Decent was applied
to the $N=10$ system. The full result is available on Github. The search was
started at $\alpha=0.55$, based on suspicions from the previous section. The
algorithm was given $10^4$ samples per iteration, and a learning rate of
$0.001$.
Interestingly the algorithm did not agree with the {\lq findings\rq} of the last
section. Quite quickly the algorithm reduced $\alpha$, and landed finally on
\begin{align}
\alpha_{N=10} \simeq 0.4978
\end{align}
The corresponding energy, calculated with $2^{20}$ samples was then found to be:
\begin{align}
E_{N=10} \simeq 24.3984 \pm 0.00080.
\end{align}
Ideally we would repeat the process for $N=50$ and $N=100$. However, due to the
bad complexity in $N$, the time needed to do this is more than was available at
the time. To achieve results in reasonable time, we would need to lower the
amount of samples per iteration significantly. Trying to do this however has
proved to yield unstable results for the gradients, and hence the algorithm is
not able to converge.
\subsection{One-Body Density}
\autoref{fig:one-body-interaction} shows the one-body densities for each of the
systems, with the ideal symmetrical curve for reference as before. We see a
trend very similar to that of \autoref{fig:density-ideal}, in that the
elliptical potential curve lines indicates that the stronger potential squeezes the
particle closer to the origin, compared with the ideal symmetrical case.
We would maybe expect the presence of interactions to spread the one-body
density out more, as the particles may not be allowed to be too close. There is
however not any clear visible difference to make out from these plots. The
jaggedness around the origin makes it a bit difficult to make out any potential
differences. We could have improved the resolution of these plots once again by
using more samples. However, there are limits to what we have CPU capacity to
do, and so the present data must suffice.
\end{multicols}
\begin{figure}[!h]
\centering
\includegraphics[width=0.8\linewidth]{../results/interacting-density.png}
\caption{One-body densities for the interacting case, drawn for all systems.
The $alpha$ used here is $\alpha=0.55$, same as in the apparent minimum seen
in \autoref{fig:interacting-energy-per-particle}.
We see a trend very similar to that of \autoref{fig:density-ideal}, where
the elliptical potential forces the particles closer than in the symmetric
case. There is no visual effect of adding the interaction in the
distributions shown. Again, the discrepancies around $r=0$ are artifacts of
the approximation, and should not be considered in depth.}
\label{fig:one-body-interaction}
\end{figure}
\begin{multicols}{2}
\section{Conclusion}
We have seen how a Variational Monte Carlo approach was able to accurately
reproduce the expected results for the simple, non-interacting system of bosons
in a harmonic oscillator potential. We could see this in both the calculated
energies, and in the one-body density.
We have looked at the differences in sampling technique, namely the difference
between the standard Metropolis algorithm, and the physically motivated version
of Metropolis-Hastings algorithm. We observed how using importance sampling was
able to produce significantly better results in terms of stability and accuracy,
for instance seen in the difference between \autoref{fig:var-alpha-plot-noimp}
and \ref{fig:var-alpha-plot-imp}. We also saw evidence that choosing an
appropriate step size was of great importance, and could greatly influence how
the algorithms perform.
Finally for the non-interacting system we implemented Gradient Decent, which was
able to easily reproduce the ideal $\alpha$, although this was largely dependent
(again) on appropriate hyper-parameters.
In the interacting regime we first and foremost observed the $\mathcal{O}(N^3)$
time complexity of our numerical approach. This made calculations
computationally very expensive to do, and heavily influenced the resolution of
the results we were able to produce.
The calculated energies per particle increased as $N$ increased, in accordance
with expectations. By comparing the energies we found to \eqref{eq:GP-final}, we
were able to see by how much the energies increased relative to the ideal case.
The effect was small for $N\leq 10$ particles, but became quite apparent for
larger $N$.
Results for the one-body density did not show any noticeable effects of the
interaction. However, whether this is actually the case or not is hard to
conclude from the precision we have obtained.
Gradient Decent was applied to $N=10$, with satisfactory results, obtaining an
energy which has not been subsided by any other parameter value. Due to time
constraints, and heavy CPU demand, Gradient decent was not successfully
implemented for the $N=50,100$ systems.
\section{Further Work}
It would be interesting to spend some more time optimizing the code, including
expanding to make use of MPI for parallelization. It would be very interesting
to see if the implementation was able to find good numbers for the larger
systems.
Due to a regrettable mistake in time estimation, rooted in unforeseen coding
complications, the resolution of the results for the interacting case are not as
good as desired. Regardless of the conclusions made here, I therefore intend to
revisit this project, at least by letting some week-long jobs run once the code
has gotten a little optimization facelift.
\printbibliography
\section{Table of Results}
\end{multicols}
\begin{center}
\begin{longtable}{|c|c|c|c|c|c|c|c|}
\caption{Selected results using the standard Metropolis sampling algorithm.
All runs have been made with $\alpha=\flatfrac{1}{2}$, $\beta=1$, with a
symmetric trap with strength $\omega_{ho}=1$ and 1000 MC cycles.}
\label{tab:simple-metro}\\
\hline
\multicolumn{1}{|c|}{Analytic} &
\multicolumn{1}{c|}{Dimensions} &
\multicolumn{1}{c|}{Particles} &
\multicolumn{1}{c|}{Step length} &
\multicolumn{1}{c|}{$\expval{H}$} &
\multicolumn{1}{c|}{$\text{Var}(E_L)$} &
\multicolumn{1}{c|}{Acceptance Rate} &
\multicolumn{1}{c|}{Time (s)} \\ \hline
\endfirsthead
\multicolumn{8}{c}%
{{\bfseries \tablename\ \thetable{} -- continued from previous page}} \\
\hline
\multicolumn{1}{|c|}{Analytic} &
\multicolumn{1}{c|}{Dimensions} &
\multicolumn{1}{c|}{Particles} &
\multicolumn{1}{c|}{Step length} &
\multicolumn{1}{c|}{$\expval{H}$} &
\multicolumn{1}{c|}{$\text{Var}(E_L)$} &
\multicolumn{1}{c|}{Acceptance Rate} &
\multicolumn{1}{c|}{Time (s)} \\ \hline
\endhead
\hline \multicolumn{8}{|r|}{{Continued on next page}} \\ \hline
\endfoot
\hline
\endlastfoot
\csvreader[head to column names]{../results/vmc_configurations.csv}{}
{\csvcoliii & \csvcoli & \csvcolii & \csvcoliv & \csvcolv & \csvcolvi &
\csvcolvii & \csvcolviii\\}
\end{longtable}
\end{center}
\begin{center}
\begin{longtable}{|c|c|c|c|c|c|c|c|}
\caption{Selected results using improved Metropolis-Hastings sampling algorithm.
All runs have been made with $\alpha=\flatfrac{1}{2}$, $\beta=1$, with a
symmetric trap with strength $\omega_{ho}=1$ and 1000 MC cycles.}
\label{tab:importance-metro} \\
\hline
\multicolumn{1}{|c|}{Analytic} &
\multicolumn{1}{c|}{Dimensions} &
\multicolumn{1}{c|}{Particles} &
\multicolumn{1}{c|}{$\Delta t$} &
\multicolumn{1}{c|}{$\expval{H}$} &
\multicolumn{1}{c|}{$\text{Var}(E_L)$} &
\multicolumn{1}{c|}{Acceptance Rate} &
\multicolumn{1}{c|}{Time (s)} \\ \hline
\endfirsthead
\multicolumn{8}{c}%
{{\bfseries \tablename\ \thetable{} -- continued from previous page}} \\
\hline
\multicolumn{1}{|c|}{Analytic} &
\multicolumn{1}{c|}{Dimensions} &
\multicolumn{1}{c|}{Particles} &
\multicolumn{1}{c|}{$\Delta t$} &
\multicolumn{1}{c|}{$\expval{H}$} &
\multicolumn{1}{c|}{$\text{Var}(E_L)$} &
\multicolumn{1}{c|}{Acceptance Rate} &
\multicolumn{1}{c|}{Time (s)} \\ \hline
\endhead
\hline \multicolumn{8}{|r|}{{Continued on next page}} \\ \hline
\endfoot
\hline
\endlastfoot
\csvreader[head to column names]{../results/vmc_imp_configurations.csv}{}
{\csvcoliii & \csvcoli & \csvcolii & \csvcoliv & \csvcolv & \csvcolvi &
\csvcolvii & \csvcolviii\\}
\end{longtable}
\end{center}
\clearpage
\begin{table*}
\center
\caption{Results for the interacting system. The energies have been
calculated for selected $\alpha$'s, and the standard error is as given by
the Blocking method. For reference is the exact result for the
non-interacting system.}
\label{tab:inter-manual}
\begin{tabular}{|c|c|c|}\hline
$\,$ & $N=10$ & $\,$ \\ \hline
$\alpha$ & VMC & GP\\ \hline
$0.40$ & $24.552 \pm 0.002865$ & $24.746$\\ \hline
$0.45$ & $24.994 \pm 0.006891$ & $24.276$\\ \hline
$0.50$ & $24.504 \pm 0.002704$ & $24.142$\\ \hline
$0.55$ & $24.400 \pm 0.000232$ & $24.252$\\ \hline
$0.60$ & $24.770 \pm 0.005075$ & $24.545$\\ \hline
\end{tabular}
\vspace{0.5cm}
\begin{tabular}{|c|c|c|}\hline
$\,$ & $N=50$ & $\,$ \\ \hline
$\alpha$ & VMC & GP\\ \hline
$0.40$ & $127.744 \pm 0.002530$ & $123.729$\\ \hline
$0.45$ & $130.019 \pm 0.006282$ & $121.381$\\ \hline
$0.50$ & $128.046 \pm 0.003077$ & $120.711$\\ \hline
$0.55$ & $127.234 \pm 0.000727$ & $121.259$\\ \hline
$0.60$ & $130.091 \pm 0.005271$ & $122.723$\\ \hline
\end{tabular}
\vspace{0.5cm}
\begin{tabular}{|c|c|c|}\hline
$\,$ & $N=100$ & $\,$ \\ \hline
$\alpha$ & VMC & GP\\ \hline
$0.40$ & $268.091 \pm 0.003828$ & $247.457$\\ \hline
$0.45$ & $271.952 \pm 0.008271$ & $242.763$\\ \hline
$0.50$ & $269.340 \pm 0.003764$ & $241.422$\\ \hline
$0.55$ & $267.476 \pm 0.001183$ & $242.519$\\ \hline
$0.60$ & $273.630 \pm 0.004904$ & $245.445$\\ \hline
\end{tabular}
\end{table*}
\end{document}
|
! H0 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
! H0 X
! H0 X libAtoms+QUIP: atomistic simulation library
! H0 X
! H0 X Portions of this code were written by
! H0 X Albert Bartok-Partay, Silvia Cereda, Gabor Csanyi, James Kermode,
! H0 X Ivan Solt, Wojciech Szlachta, Csilla Varnai, Steven Winfield.
! H0 X
! H0 X Copyright 2006-2010.
! H0 X
! H0 X These portions of the source code are released under the GNU General
! H0 X Public License, version 2, http://www.gnu.org/copyleft/gpl.html
! H0 X
! H0 X If you would like to license the source code under different terms,
! H0 X please contact Gabor Csanyi, [email protected]
! H0 X
! H0 X Portions of this code were written by Noam Bernstein as part of
! H0 X his employment for the U.S. Government, and are not subject
! H0 X to copyright in the USA.
! H0 X
! H0 X
! H0 X When using this software, please cite the following reference:
! H0 X
! H0 X http://www.libatoms.org
! H0 X
! H0 X Additional contributions by
! H0 X Alessio Comisso, Chiara Gattinoni, and Gianpietro Moras
! H0 X
! H0 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
!X
!X IPModel_Si_MEAM module
!X
!% Module for the Modified Embedded Atom Method potential for Si
!% The IPModel_Si_MEAM object contains all the parameters read
!% from an 'Si_MEAN_params' XML stanza.
!X
!XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
!XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
!
#include "error.inc"
module IPModel_Si_MEAM_module
use error_module
use system_module, only : dp, inoutput, print, verbosity_push_decrement, verbosity_pop, operator(//)
use dictionary_module
use paramreader_module
use linearalgebra_module
use spline_module
use atoms_types_module
use atoms_module
use mpi_context_module
use QUIP_Common_module
implicit none
private
type IPModel_Si_MEAM
integer :: n_types = 0
integer, allocatable :: atomic_num(:), type_of_atomic_num(:)
real(dp) :: cutoff = 0.0_dp
type(spline), dimension(:,:), allocatable :: phi
type(spline), dimension(:,:), allocatable :: rho
type(spline), dimension(:,:), allocatable :: f
type(spline), dimension(:), allocatable :: U
type(spline), dimension(:,:,:), allocatable :: g
real(dp), dimension(:,:), allocatable :: r_cut_phi
real(dp), dimension(:,:), allocatable :: r_cut_rho
real(dp), dimension(:,:), allocatable :: r_cut_f
character(len=STRING_LENGTH) :: label
endtype IPModel_Si_MEAM
interface Initialise
module procedure IPModel_Si_MEAM_Initialise_str
end interface Initialise
interface Finalise
module procedure IPModel_Si_MEAM_Finalise
end interface Finalise
interface Print
module procedure IPModel_Si_MEAM_Print
end interface Print
interface Calc
module procedure IPModel_Si_MEAM_Calc
end interface Calc
logical, private :: parse_in_ip, parse_matched_label
type(IPModel_Si_MEAM), private, pointer :: parse_ip
integer :: parse_cur_type_i, parse_cur_type_j, parse_cur_type_k, parse_cur_point, n_spline
real(dp) :: yp1, ypn
real(dp), dimension(:), allocatable :: spline_x, spline_y
character(len=100) :: spline_function
public :: IPModel_Si_MEAM, Initialise, Finalise, Print, Calc
contains
subroutine IPModel_Si_MEAM_Initialise_str(this, args_str, param_str)
type(IPModel_Si_MEAM), intent(inout) :: this
character(len=*), intent(in) :: args_str, param_str
type(Dictionary) :: params
call Finalise(this)
call initialise(params)
this%label=''
call param_register(params, 'label', '', this%label, help_string="No help yet. This source file was $LastChangedBy$")
if (.not. param_read_line(params, args_str, ignore_unknown=.true.,task='IPModel_Si_MEAM_Initialise_str args_str')) then
call system_abort("IPModel_Si_MEAM_Initialise_str failed to parse label from args_str="//trim(args_str))
endif
call finalise(params)
call IPModel_Si_MEAM_read_params_xml(this, param_str)
end subroutine IPModel_Si_MEAM_Initialise_str
subroutine IPModel_Si_MEAM_Finalise(this)
type(IPModel_Si_MEAM), intent(inout) :: this
integer :: ti, tj, tk
do ti=1, this%n_types
call finalise(this%U(ti))
do tj=1, this%n_types
call finalise(this%phi(ti,tj))
call finalise(this%rho(ti,tj))
call finalise(this%f(ti,tj))
do tk=1, this%n_types
call finalise(this%g(ti,tj,tk))
enddo
end do
end do
if(allocated(this%phi)) deallocate(this%phi)
if(allocated(this%rho)) deallocate(this%rho)
if(allocated(this%f)) deallocate(this%f)
if(allocated(this%U)) deallocate(this%U)
if(allocated(this%g)) deallocate(this%g)
if(allocated(this%atomic_num)) deallocate(this%atomic_num)
if(allocated(this%type_of_atomic_num)) deallocate(this%type_of_atomic_num)
if(allocated(this%r_cut_phi)) deallocate(this%r_cut_phi)
if(allocated(this%r_cut_rho)) deallocate(this%r_cut_rho)
if(allocated(this%r_cut_f)) deallocate(this%r_cut_f)
this%n_types = 0
this%label = ''
end subroutine IPModel_Si_MEAM_Finalise
subroutine IPModel_Si_MEAM_Calc(this, at, e, local_e, f, virial, local_virial, args_str, mpi, error)
type(IPModel_Si_MEAM), intent(inout) :: this
type(Atoms), intent(in) :: at
real(dp), intent(out), optional :: e !% \texttt{e} = System total energy
real(dp), dimension(:), intent(out), optional :: local_e !% \texttt{local_e} = energy of each atom, vector dimensioned as \texttt{at%N}.
real(dp), intent(out), optional :: f(:,:), local_virial(:,:) !% Forces, dimensioned as \texttt{f(3,at%N)}, local virials, dimensioned as \texttt{local_virial(9,at%N)}
real(dp), dimension(3,3), intent(out), optional :: virial !% Virial
character(len=*), optional :: args_str
type(MPI_Context), intent(in), optional :: mpi
integer, intent(out), optional :: error
!local
integer :: i, j, k, n, nn, ti, tj, tk
real(dp) :: r_ij, r_ik, n_i, f_ij, f_ik, theta_jik, g_jik, U_i, phi_ij, &
& dphi_ij, df_ij, df_ik, dg_jik, dU_i, drho_ij
real(dp), dimension(3) :: u_ij, u_ik, dn_i, dn_j, dn_i_dr_ij, diff_ij, diff_ik
real(dp), dimension(3,3) :: dn_i_drij_outer_rij
type(Dictionary) :: params
logical :: has_atom_mask_name
character(STRING_LENGTH) :: atom_mask_name
logical, dimension(:), pointer :: atom_mask_pointer
real(dp) :: r_scale, E_scale
logical :: do_rescale_r, do_rescale_E
INIT_ERROR(error)
if (present(e)) e = 0.0_dp
if (present(local_e)) then
call check_size('Local_E',local_e,(/at%N/),'IPModel_Si_MEAM_Calc', error)
local_e = 0.0_dp
endif
if (present(f)) then
call check_size('Force',f,(/3,at%Nbuffer/),'IPModel_Si_MEAM_Calc', error)
f = 0.0_dp
end if
if (present(virial)) virial = 0.0_dp
if (present(local_virial)) then
call check_size('Local_virial',local_virial,(/9,at%Nbuffer/),'IPModel_Si_MEAM_Calc', error)
local_virial = 0.0_dp
RAISE_ERROR("IPModel_Si_MEAM_Calc: local_virial calculation requested but not supported yet.", error)
endif
atom_mask_pointer => null()
if (present(args_str)) then
call initialise(params)
call param_register(params, 'atom_mask_name', 'NONE', atom_mask_name, has_value_target=has_atom_mask_name, help_string="Name of logical property used to mask atoms")
call param_register(params, 'r_scale', '1.0',r_scale, has_value_target=do_rescale_r, help_string="Recaling factor for distances. Default 1.0.")
call param_register(params, 'E_scale', '1.0',E_scale, has_value_target=do_rescale_E, help_string="Recaling factor for energy. Default 1.0.")
if(.not. param_read_line(params, args_str, ignore_unknown=.true.,task='IPModel_Si_MEAM_Calc args_str')) then
RAISE_ERROR("IPModel_Si_MEAM_Calc failed to parse args_str='"//trim(args_str)//"'",error)
endif
call finalise(params)
if(has_atom_mask_name) then
if (.not. assign_pointer(at, trim(atom_mask_name) , atom_mask_pointer)) &
call system_abort("IPModel_SW_Calc did not find "//trim(atom_mask_name)//" property in the atoms object.")
else
atom_mask_pointer => null()
endif
if (do_rescale_r .or. do_rescale_E) then
RAISE_ERROR("IPModel_Si_MEAM_Calc: rescaling of potential with r_scale and E_scale not yet implemented!", error)
end if
endif
!Loop over atoms
do i = 1, at%N
if (present(mpi)) then
if(mpi%active) then
if(mod(i-1, mpi%n_procs) /= mpi%my_proc) cycle
endif
endif
if(associated(atom_mask_pointer)) then
if(.not. atom_mask_pointer(i)) cycle
endif
ti = get_type(this%type_of_atomic_num, at%Z(i))
n_i = 0.0_dp
dn_i = 0.0_dp
dn_i_drij_outer_rij = 0.0_dp
!Loop over neighbours
do n = 1, n_neighbours(at,i)
j = neighbour(at, i, n, distance=r_ij, cosines=u_ij, diff=diff_ij) ! nth neighbour of atom i
tj = get_type(this%type_of_atomic_num, at%Z(j))
if( r_ij < this%r_cut_phi(ti,tj) ) then
if(present(local_e) .or. present(e)) phi_ij = spline_value(this%phi(ti,tj),r_ij)
if(present(local_e)) local_e(i) = local_e(i) + phi_ij*0.5_dp
if(present(e)) e = e + phi_ij*0.5_dp
if(present(f) .or. present(virial) ) dphi_ij = spline_deriv(this%phi(ti,tj),r_ij)
if(present(f)) then
f(:,i) = f(:,i) + 0.5_dp*dphi_ij*u_ij
f(:,j) = f(:,j) - 0.5_dp*dphi_ij*u_ij
endif
if(present(virial)) virial = virial - 0.5_dp * dphi_ij*(u_ij .outer. u_ij)*r_ij
endif
if( (r_ij >= this%r_cut_rho(ti,tj)).or.(r_ij >= this%r_cut_f(ti,tj)) ) cycle
n_i = n_i + spline_value(this%rho(ti,tj),r_ij)
if(present(f) .or. present(virial) ) then
dn_i_dr_ij = spline_deriv(this%rho(ti,tj),r_ij)*u_ij
if(present(f)) dn_i = dn_i + dn_i_dr_ij
if(present(virial)) dn_i_drij_outer_rij = dn_i_drij_outer_rij + (dn_i_dr_ij .outer. u_ij) * r_ij
endif
f_ij = spline_value(this%f(ti,tj),r_ij)
if(present(f) .or. present(virial)) df_ij = spline_deriv(this%f(ti,tj),r_ij)
do nn = 1, n_neighbours(at,i)
k = neighbour(at, i, nn, distance=r_ik, cosines=u_ik, diff=diff_ik)
tk = get_type(this%type_of_atomic_num, at%Z(k))
!if( j>=k ) cycle
if( norm(diff_ij-diff_ik) .feq. 0.0_dp ) cycle
if( r_ik >= this%r_cut_f(ti,tk) ) cycle
theta_jik = dot_product(u_ij,u_ik) !cosine( at, i, j, k )
f_ik = spline_value(this%f(ti,tk),r_ik)
if(present(f) .or. present(virial)) df_ik = spline_deriv(this%f(ti,tk),r_ik)
g_jik = spline_value(this%g(ti,tj,tk),theta_jik)
if(present(f) .or. present(virial)) dg_jik = spline_deriv(this%g(ti,tj,tk),theta_jik)
n_i = n_i + 0.5_dp * f_ij * f_ik * g_jik
if( present(f) ) &
& dn_i = dn_i + 0.5_dp * ( g_jik * &
& ( df_ij * f_ik * u_ij + &
& df_ik * f_ij * u_ik ) + &
& f_ij * f_ik * dg_jik * &
& ( u_ij / r_ik + u_ik / r_ij - &
& theta_jik * ( u_ij / r_ij + u_ik / r_ik ) ) )
if( present(virial) ) &
& dn_i_drij_outer_rij = dn_i_drij_outer_rij + &
& 0.5_dp * ( g_jik * ( df_ij * f_ik * (u_ij.outer.u_ij) * r_ij + &
df_ik * f_ij * (u_ik.outer.u_ik) * r_ik ) + &
& f_ij * f_ik * dg_jik * &
& ( (u_ij .outer. u_ik) - theta_jik * (u_ij .outer. u_ij) + &
& (u_ik .outer. u_ij) - theta_jik * (u_ik .outer. u_ik) ) )
enddo
enddo
if(present(local_e) .or. present(e)) U_i = spline_value(this%U(ti),n_i)
if(present(f) .or. present(virial)) dU_i = spline_deriv(this%U(ti),n_i)
if(present(local_e)) local_e(i) = local_e(i) + U_i
if(present(e)) e = e + U_i
if(present(f)) f(:,i) = f(:,i) + dU_i * dn_i
if(present(virial)) virial = virial - dU_i * dn_i_drij_outer_rij
if(present(f)) then
do n = 1, n_neighbours(at,i) !cross-terms
j = neighbour(at, i, n, distance=r_ij, cosines=u_ij, diff=diff_ij) ! nth neighbour of atom i
tj = get_type(this%type_of_atomic_num, at%Z(j))
if( (r_ij >= this%r_cut_rho(ti,tj)).or.(r_ij >= this%r_cut_f(ti,tj)) ) cycle
drho_ij = spline_deriv(this%rho(ti,tj),r_ij)
f(:,j) = f(:,j) - dU_i * drho_ij * u_ij
f_ij = spline_value(this%f(ti,tj),r_ij)
df_ij = spline_deriv(this%f(ti,tj),r_ij)
dn_j = 0.0_dp
do nn = 1, n_neighbours(at,i)
k = neighbour(at, i, nn, distance=r_ik, cosines=u_ik, diff=diff_ik)
tk = get_type(this%type_of_atomic_num, at%Z(k))
if( norm(diff_ij-diff_ik) .feq. 0.0_dp ) cycle
if( r_ik >= this%r_cut_f(ti,tk) ) cycle
theta_jik = dot_product(u_ij,u_ik) !cosine( at, i, j, k )
f_ik = spline_value(this%f(ti,tk),r_ik)
df_ik = spline_deriv(this%f(ti,tk),r_ik)
g_jik = spline_value(this%g(ti,tj,tk),theta_jik)
dg_jik = spline_deriv(this%g(ti,tj,tk),theta_jik)
dn_j = dn_j + df_ij * f_ik * g_jik * u_ij + &
& f_ij * f_ik * dg_jik * ( u_ik / r_ij - theta_jik * u_ij / r_ij )
enddo
f(:,j) = f(:,j) - dU_i * dn_j
enddo
endif
enddo
if (present(mpi)) then
if (present(e)) e = sum(mpi, e)
if (present(local_e)) call sum_in_place(mpi, local_e)
if (present(f)) call sum_in_place(mpi, f)
if (present(virial)) call sum_in_place(mpi, virial)
endif
endsubroutine IPModel_Si_MEAM_Calc
!XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
!X
!X XML param reader functions
!X
!XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
subroutine IPModel_startElement_handler(URI, localname, name, attributes)
character(len=*), intent(in) :: URI
character(len=*), intent(in) :: localname
character(len=*), intent(in) :: name
type(dictionary_t), intent(in) :: attributes
integer status
character(len=1024) :: value
integer :: ti, Zi, Zj, Zk
integer :: n_types
real(dp) :: v
if (name == 'Si_MEAM_params') then
if (parse_in_ip) &
call system_abort("IPModel_startElement_handler entered Si_MEAM_params with parse_in true. Probably a bug in FoX (4.0.1, e.g.)")
if (parse_matched_label) return ! we already found an exact match for this label
call QUIP_FoX_get_value(attributes, 'label', value, status)
if (status /= 0) value = ''
if (len(trim(parse_ip%label)) > 0) then ! we were passed in a label
if (value == parse_ip%label) then ! exact match
parse_matched_label = .true.
parse_in_ip = .true.
else ! no match
parse_in_ip = .false.
endif
else ! no label passed in
parse_in_ip = .true.
endif
if (parse_in_ip) then
if (parse_ip%n_types /= 0) then
call finalise(parse_ip)
endif
call QUIP_FoX_get_value(attributes, "n_types", value, status)
if (status /= 0) call system_abort ("IPModel_Si_MEAM_read_params_xml cannot find n_types")
read (value, *) parse_ip%n_types
n_types = parse_ip%n_types
allocate(parse_ip%atomic_num(parse_ip%n_types))
parse_ip%atomic_num = 0
allocate(parse_ip%r_cut_phi(n_types,n_types))
parse_ip%r_cut_phi = 0.0_dp
allocate(parse_ip%r_cut_rho(n_types,n_types))
parse_ip%r_cut_rho = 0.0_dp
allocate(parse_ip%r_cut_f(n_types,n_types))
parse_ip%r_cut_f = 0.0_dp
allocate( parse_ip%phi(n_types,n_types))
allocate( parse_ip%rho(n_types,n_types))
allocate( parse_ip%f(n_types,n_types))
allocate( parse_ip%U(n_types))
allocate( parse_ip%g(n_types,n_types,n_types))
endif
elseif (parse_in_ip .and. name == 'per_type_data') then
call QUIP_FoX_get_value(attributes, "type", value, status)
if (status /= 0) call system_abort ("IPModel_Si_MEAM_read_params_xml cannot find type")
read (value, *) ti
if (ti < 1 .or. ti > parse_ip%n_types) call system_abort("IPModel_Si_MEAM_read_params_xml got" // &
" per_type_data type out of range " // ti // " n_types " // parse_ip%n_types)
parse_cur_type_i = ti
call QUIP_FoX_get_value(attributes, "atomic_num", value, status)
if (status /= 0) call system_abort ("IPModel_Si_MEAM_read_params_xml cannot find atomic_num")
read (value, *) parse_ip%atomic_num(ti)
if (allocated(parse_ip%type_of_atomic_num)) deallocate(parse_ip%type_of_atomic_num)
allocate(parse_ip%type_of_atomic_num(maxval(parse_ip%atomic_num)))
parse_ip%type_of_atomic_num = 0
do ti=1, parse_ip%n_types
if (parse_ip%atomic_num(ti) > 0) &
parse_ip%type_of_atomic_num(parse_ip%atomic_num(ti)) = ti
end do
elseif (parse_in_ip .and. name == 'per_pair_data') then
call QUIP_FoX_get_value(attributes, "atomic_num_i", value, status)
if (status /= 0) call system_abort ("IPModel_Si_MEAM_read_params_xml cannot find atomic_num_i")
read (value, *) Zi
call QUIP_FoX_get_value(attributes, "atomic_num_j", value, status)
if (status /= 0) call system_abort ("IPModel_Si_MEAM_read_params_xml cannot find atomic_num_j")
read (value, *) Zj
parse_cur_type_i = get_type(parse_ip%type_of_atomic_num,Zi)
parse_cur_type_j = get_type(parse_ip%type_of_atomic_num,Zj)
call QUIP_FoX_get_value(attributes, "r_cut_phi", value, status)
if (status /= 0) call system_abort ("IPModel_Si_MEAM_read_params_xml cannot find r_cut_phi")
read (value, *) parse_ip%r_cut_phi(parse_cur_type_i, parse_cur_type_j)
call QUIP_FoX_get_value(attributes, "r_cut_rho", value, status)
if (status /= 0) call system_abort ("IPModel_Si_MEAM_read_params_xml cannot find r_cut_rho")
read (value, *) parse_ip%r_cut_rho(parse_cur_type_i, parse_cur_type_j)
call QUIP_FoX_get_value(attributes, "r_cut_f", value, status)
if (status /= 0) call system_abort ("IPModel_Si_MEAM_read_params_xml cannot find r_cut_f")
read (value, *) parse_ip%r_cut_f(parse_cur_type_i, parse_cur_type_j)
elseif (parse_in_ip .and. name == 'per_triplet_data') then
call QUIP_FoX_get_value(attributes, "atomic_num_i", value, status)
if (status /= 0) call system_abort ("IPModel_Si_MEAM_read_params_xml cannot find atomic_num_i")
read (value, *) Zi
call QUIP_FoX_get_value(attributes, "atomic_num_j", value, status)
if (status /= 0) call system_abort ("IPModel_Si_MEAM_read_params_xml cannot find atomic_num_j")
read (value, *) Zj
call QUIP_FoX_get_value(attributes, "atomic_num_k", value, status)
if (status /= 0) call system_abort ("IPModel_Si_MEAM_read_params_xml cannot find atomic_num_k")
read (value, *) Zk
parse_cur_type_i = get_type(parse_ip%type_of_atomic_num,Zi)
parse_cur_type_j = get_type(parse_ip%type_of_atomic_num,Zj)
parse_cur_type_k = get_type(parse_ip%type_of_atomic_num,Zk)
elseif (parse_in_ip .and. name == 'spline') then
call QUIP_FoX_get_value(attributes, "spline_function", value, status)
if (status /= 0) call system_abort ("IPModel_Si_MEAM_read_params_xml cannot find spline_function")
read (value, *) spline_function
call QUIP_FoX_get_value(attributes, "n_spline", value, status)
if (status /= 0) call system_abort ("IPModel_Si_MEAM_read_params_xml cannot find n_spline")
read (value, *) n_spline
call QUIP_FoX_get_value(attributes, "yp1", value, status)
if (status /= 0) call system_abort ("IPModel_Si_MEAM_read_params_xml cannot find yp1")
read (value, *) yp1
call QUIP_FoX_get_value(attributes, "ypn", value, status)
if (status /= 0) call system_abort ("IPModel_Si_MEAM_read_params_xml cannot find ypn")
read (value, *) ypn
allocate( spline_x(n_spline), spline_y(n_spline) )
parse_cur_point = 1
elseif (parse_in_ip .and. name == 'point') then
if (parse_cur_point > n_spline) call system_abort ("IPModel_Si_MEAM got too " // &
&"many points " // parse_cur_point // " type " // parse_cur_type_i // " " // parse_cur_type_j // &
& " in spline "// trim(spline_function))
call QUIP_FoX_get_value(attributes, "x", value, status)
if (status /= 0) call system_abort ("IPModel_EAM_Ercolessi_Adams_read_params_xml cannot find x")
read (value, *) v
spline_x(parse_cur_point) = v
call QUIP_FoX_get_value(attributes, "y", value, status)
if (status /= 0) call system_abort ("IPModel_EAM_Ercolessi_Adams_read_params_xml cannot find y")
read (value, *) v
spline_y(parse_cur_point) = v
parse_cur_point = parse_cur_point + 1
endif
end subroutine IPModel_startElement_handler
subroutine IPModel_endElement_handler(URI, localname, name)
character(len=*), intent(in) :: URI
character(len=*), intent(in) :: localname
character(len=*), intent(in) :: name
if (parse_in_ip) then
if (name == 'Si_MEAM_params') then
parse_in_ip = .false.
elseif (name == 'spline') then
selectcase(trim(spline_function))
case('phi')
call initialise(parse_ip%phi(parse_cur_type_i,parse_cur_type_j), spline_x, spline_y, yp1, ypn)
if( parse_cur_type_i /= parse_cur_type_j ) &
& call initialise(parse_ip%phi(parse_cur_type_j,parse_cur_type_i), spline_x, spline_y, yp1, ypn)
case('rho')
call initialise(parse_ip%rho(parse_cur_type_i,parse_cur_type_j), spline_x, spline_y, yp1, ypn)
if( parse_cur_type_i /= parse_cur_type_j ) &
& call initialise(parse_ip%rho(parse_cur_type_j,parse_cur_type_i), spline_x, spline_y, yp1, ypn)
case('f')
call initialise(parse_ip%f(parse_cur_type_i,parse_cur_type_j), spline_x, spline_y, yp1, ypn)
if( parse_cur_type_i /= parse_cur_type_j ) &
& call initialise(parse_ip%f(parse_cur_type_j,parse_cur_type_i), spline_x, spline_y, yp1, ypn)
case('U')
call initialise(parse_ip%U(parse_cur_type_i), spline_x, spline_y, yp1, ypn)
case('g')
call initialise(parse_ip%g(parse_cur_type_i,parse_cur_type_j,parse_cur_type_k), &
& spline_x, spline_y, yp1, ypn)
if( parse_cur_type_j /= parse_cur_type_k ) &
& call initialise(parse_ip%g(parse_cur_type_i,parse_cur_type_k,parse_cur_type_j), &
& spline_x, spline_y, yp1, ypn)
case default
call system_abort('')
endselect
deallocate(spline_x, spline_y)
endif
endif
end subroutine IPModel_endElement_handler
subroutine IPModel_Si_MEAM_read_params_xml(this, param_str)
type(IPModel_Si_MEAM), intent(inout), target :: this
character(len=*), intent(in) :: param_str
type (xml_t) :: fxml
if (len(trim(param_str)) <= 0) return
parse_ip => this
parse_in_ip = .false.
parse_matched_label = .false.
call open_xml_string(fxml, param_str)
call parse(fxml, &
startElement_handler = IPModel_startElement_handler, &
endElement_handler = IPModel_endElement_handler)
call close_xml_t(fxml)
if (this%n_types == 0) call system_abort("Si_MEAM Tried to parse, but n_types still 0")
parse_ip%cutoff = max(maxval(parse_ip%r_cut_phi),maxval(parse_ip%r_cut_rho),maxval(parse_ip%r_cut_f))
end subroutine IPModel_Si_MEAM_read_params_xml
!XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
!X
!% Printing of potential parameters: number of different types, cutoff radius, atomic numbers, ect.
!X
!XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
subroutine IPModel_Si_MEAM_Print (this, file)
type(IPModel_Si_MEAM), intent(in) :: this
type(Inoutput), intent(inout),optional :: file
integer :: ti, tj, tk
call Print("IPModel_Si_MEAM : n_types = " // this%n_types // " cutoff = " // this%cutoff, file=file)
do ti=1, this%n_types
call Print("IPModel_Si_MEAM : type " // ti // " atomic_num " // this%atomic_num(ti), file=file)
call verbosity_push_decrement()
call Print("IPModel_Si_MEAM : U ", file=file)
call Print(this%U(ti), file=file)
do tj=1, this%n_types
call Print("IPModel_Si_MEAM : pair "// ti // " " // tj // " r_cut_phi " // this%r_cut_phi(ti,tj), file=file)
call Print("IPModel_Si_MEAM : pair phi ", file=file)
call Print(this%phi(ti,tj), file=file)
call Print("IPModel_Si_MEAM : pair "// ti // " " // tj // " r_cut_rho " // this%r_cut_rho(ti,tj), file=file)
call Print("IPModel_Si_MEAM : pair rho ", file=file)
call Print(this%rho(ti,tj), file=file)
call Print("IPModel_Si_MEAM : pair "// ti // " " // tj // " r_cut_f " // this%r_cut_f(ti,tj), file=file)
call Print("IPModel_Si_MEAM : pair f ", file=file)
call Print(this%f(ti,tj), file=file)
do tk=1, this%n_types
call Print("IPModel_Si_MEAM : triplet g", file=file)
call Print(this%g(ti,tj,tk), file=file)
enddo
end do
call verbosity_pop()
end do
end subroutine IPModel_Si_MEAM_Print
endmodule IPModel_Si_MEAM_module
!<Si_MEAM_params n_types="1" label="">
!<!-- Thomas J Lenosky, Babak Sadigh, Eduardo Alonso, Vasily V Bulatov, Tomas Diaz de la Rubia -->
!<!-- Jeongnim Kim, Arthur F Voter and Joel D Kress -->
!<!-- Highly optimized empirical potential model of silicon -->
!<!-- Modelling Simul. Mater. Sci. Eng. 8 (2000) 825-841 -->
! <per_type_data atomic_num="14" type="1">
! <spline spline_function="U" n_spline="8" yp1="0.73514" ypn="0.61652">
! <point x="-1.7709300000" y="-1.0749300000" />
! <point x="-0.3881514286" y="-0.2004500000" />
! <point x=" 0.9946271429" y=" 0.4142200000" />
! <point x=" 2.3774057143" y=" 0.8793900000" />
! <point x=" 3.7601842857" y=" 1.2668900000" />
! <point x=" 5.1429628571" y=" 1.6299800000" />
! <point x=" 6.5257414286" y=" 1.9773800000" />
! <point x=" 7.9085200000" y=" 2.3961800000" />
! </spline>
! </per_type_data>
! <per_pair_data atomic_num_i="14" atomic_num_j="14" r_cut_phi="4.5" r_cut_rho="3.5" r_cut_f="3.5">
! <spline spline_function="phi" n_spline="10" yp1="-42.66967" ypn="0.00000">
! <point x="1.5000000000" y=" 6.9299400000" />
! <point x="1.8333333333" y="-0.4399500000" />
! <point x="2.1666666667" y="-1.7012300000" />
! <point x="2.5000000000" y="-1.6247300000" />
! <point x="2.8333333333" y="-0.9969600000" />
! <point x="3.1666666667" y="-0.2739100000" />
! <point x="3.5000000000" y="-0.0249900000" />
! <point x="3.8333333333" y="-0.0178400000" />
! <point x="4.1666666667" y="-0.0096100000" />
! <point x="4.5000000000" y=" 0.0000000000" />
! </spline>
! <spline spline_function="rho" n_spline="11" yp1="-1.00000" ypn="0.00000">
! <point x="1.5000000000" y=" 0.1374700000" />
! <point x="1.7000000000" y="-0.1483100000" />
! <point x="1.9000000000" y="-0.5597200000" />
! <point x="2.1000000000" y="-0.7311000000" />
! <point x="2.3000000000" y="-0.7628300000" />
! <point x="2.5000000000" y="-0.7291800000" />
! <point x="2.7000000000" y="-0.6662000000" />
! <point x="2.9000000000" y="-0.5732800000" />
! <point x="3.1000000000" y="-0.4069000000" />
! <point x="3.3000000000" y="-0.1666200000" />
! <point x="3.5000000000" y=" 0.0000000000" />
! </spline>
! <spline spline_function="f" n_spline="10" yp1="-3.61894" ypn="0.00000">
! <point x="1.5000000000" y="1.2503100000" />
! <point x="1.7222222222" y="0.8682100000" />
! <point x="1.9444444444" y="0.6084600000" />
! <point x="2.1666666667" y="0.4875600000" />
! <point x="2.3888888889" y="0.4416300000" />
! <point x="2.6111111111" y="0.3761000000" />
! <point x="2.8333333333" y="0.2714500000" />
! <point x="3.0555555556" y="0.1481400000" />
! <point x="3.2777777778" y="0.0485500000" />
! <point x="3.5000000000" y="0.0000000000" />
! </spline>
! </per_pair_data>
! <per_triplet_data atomic_num_i="14" atomic_num_j="14" atomic_num_k="14">
! <spline spline_function="g" n_spline="8" yp1="-13.95042" ypn="1.13462">
! <point x="-1.0000000000" y="5.2541600000" />
! <point x="-0.7428371429" y="2.3591500000" />
! <point x="-0.4856742857" y="1.1959500000" />
! <point x="-0.2285114286" y="1.2299500000" />
! <point x=" 0.0286514286" y="2.0356500000" />
! <point x=" 0.2858142857" y="3.4247400000" />
! <point x=" 0.5429771429" y="4.9485900000" />
! <point x=" 0.8001400000" y="5.6179900000" />
! </spline>
! </per_triplet_data>
!</Si_MEAM_params>
|
(* This Isabelle theory is produced using the TIP tool offered at the following website:
https://github.com/tip-org/tools
This file was originally provided as part of TIP benchmark at the following website:
https://github.com/tip-org/benchmarks
Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly
to make it compatible with Isabelle2017.
\:w
Some proofs were added by Yutaka Nagashima.*)
theory TIP_sort_nat_TSortCount
imports "../../Test_Base"
begin
datatype 'a list = nil2 | cons2 "'a" "'a list"
datatype Nat = Z | S "Nat"
datatype Tree = TNode "Tree" "Nat" "Tree" | TNil
fun plus :: "Nat => Nat => Nat" where
"plus (Z) y = y"
| "plus (S z) y = S (plus z y)"
fun le :: "Nat => Nat => bool" where
"le (Z) y = True"
| "le (S z) (Z) = False"
| "le (S z) (S x2) = le z x2"
fun flatten :: "Tree => Nat list => Nat list" where
"flatten (TNode q z r) y = flatten q (cons2 z (flatten r y))"
| "flatten (TNil) y = y"
fun count :: "'a => 'a list => Nat" where
"count x (nil2) = Z"
| "count x (cons2 z ys) =
(if (x = z) then plus (S Z) (count x ys) else count x ys)"
fun add :: "Nat => Tree => Tree" where
"add x (TNode q z r) =
(if le x z then TNode (add x q) z r else TNode q z (add x r))"
| "add x (TNil) = TNode TNil x TNil"
fun toTree :: "Nat list => Tree" where
"toTree (nil2) = TNil"
| "toTree (cons2 y xs) = add y (toTree xs)"
fun tsort :: "Nat list => Nat list" where
"tsort x = flatten (toTree x) (nil2)"
theorem property0 :
"((count x (tsort xs)) = (count x xs))"
oops
end
|
(*<*)
theory Framework
imports Main
begin
(*>*)
section\<open>{On the framework used \label{sec:Framework}}\<close>
text\<open>\noindent %
To start off, we shall give an overview on the framework this thesis was written in, that is,
enlist the relevant software components used and explain the core features of Isabelle/HOL since it is the most important component. \<close>
subsection\<open>{The components \label{subsec:Components}}\<close>
text\<open>
There are three main tools used to write this thesis:
\begin{description}
\item [Isabelle/HOL] A proof assistant that provides an environment to axiomatize and utilize deduction systems with which one can formulate
theorems and prove them. It was used to represent the Constitution's model on the computer and conduct reasoning with it.
\item [\LaTeX] A typesetting software. It is very convenient for mathematical formulas. Isabelle has an inbuilt tool to use \LaTeX. This was used
to typeset the code written with Isabelle.
\item [Git] Version control software to keep track of changes and return to older versions where necessary.
\end{description}
\<close>
subsection\<open>{Short introduction to Isabelle/HOL \label{subsec:Isabelle}}\<close>
text\<open>\noindent %
Depending on the context, the way Isabelle is used can vary greatly. The following shall illustrate how we will be using it%
\footnote{For a general introduction see the manual \cite{isabelle-reference}}.
First we give an outline of the steps taken and then illustrate those with examples.
\noindent Here is the outline:
\begin{enumerate}
\item Provide definitions of types, concepts, operators used.
\item State all assumptions in the form of axioms.
\item State theorems.
\item Test your theory by trying to refute/prove the theorems. Use tools Sledgehammer and Nitpick%
\footnote{See also the manuals on Sledgehammer \cite{isabelle-sledgehammer} and on Nitpick \cite{isabelle-nitpick}} to do so.
\end{enumerate}
\<close>
text\<open>\noindent %
\textbf{ 1. Provide definitions of types, concepts, operators used.}
\noindent We can define our own data types or work with predefined ones. Here we introduce a data type @{text "bvg"} (\emph{beverage}) and a type
@{text "temp"} (\emph{temperature}). The latter is just a synonym for predefined type @{text "int"}.
\<close>
datatype bvg = tea | coffee | juice
type_synonym temp="int"
text\<open>\noindent %
Next we define predicates and operators.\<close>
consts tempOf::"bvg\<Rightarrow>temp"
\<comment> \<open>determines temperature of bvg\<close>
definition totalTemp::"temp"
where "totalTemp \<equiv> (tempOf tea) + (tempOf coffee) + (tempOf juice)"
\<comment> \<open>determines total temperature of all bvg-instances\<close>
definition tooHot::"bvg\<Rightarrow>bool"
where "tooHot b \<equiv> if(b=juice)then(tempOf b > 5) else (tempOf b > 20)"
\<comment> \<open>determines if a beverage is too hot. For @{text "juice"} this is the case iff its temperature is @{text ">5"}, for @{text "tea"}
and @{text "coffee"} iff the temperature is @{text ">20"}\<close>
text\<open>\noindent %
\textbf{2. State all assumptions in the form of axioms.}
\noindent Note that we introduce a contradiction with the two axioms @{text "teaHot tea"} and @{text "tempOf tea = 10"}
\<close>
axiomatization where
teaHot: "tooHot tea" and
teaTemp10: "(tempOf tea)=10" and
coffeeTemp5:"(tempOf coffee)=5" and
juiceTemp2: "(tempOf juice)=2"
text\<open>\noindent %
\textbf{3. State theorems and 4. Test your theory by trying to refute/prove the theorems.}
\noindent These steps have to be conducted together since Isabelle requires theorems to be proven. It is not possible
to enumerate theorems without proofs unless you use keyword @{command "oops"} to signify that a theorem has not been proven yet.\\
\noindent \emph{Sledgehammer} can be used to find proofs and \emph{Nitpick} to find counter models and satisfying models.
\<close>
theorem totalTemp17:"totalTemp = 17" sledgehammer
by (simp add: coffeeTemp5 juiceTemp2 teaTemp10 totalTemp_def)
lemma basic_unsat:"False" using teaHot teaTemp10 tooHot_def sledgehammer
by simp
lemma basic_sat:"True" nitpick[show_all,user_axioms] oops
text\<open>\noindent %
Note that our axioms are inconsistent, so we can prove @{text "basic_unsat"}. Nitpick can neither find a counter model nor a satisfying one.
However, if we remove axiom @{text "teaHot"} or @{text "teaTemp10"} lemma @{text "basic_unsat"} becomes unprovable and Nitpick will find a
satisfying model for lemma @{text "basic_sat"}. To look for a satisfying model rather than a refuting one, we simply add option
@{text "satifsy"}.
\<close>
(*<*)
end
(*>*)
|
If $f$ and $g$ are measurable functions from a measurable space $M$ to the real numbers, then the function $x \mapsto f(x)^{g(x)}$ is measurable. |
function [data] = ft_datatype_raw(data, varargin)
% FT_DATATYPE_RAW describes the FieldTrip MATLAB structure for raw data
%
% The raw datatype represents sensor-level time-domain data typically
% obtained after calling FT_DEFINETRIAL and FT_PREPROCESSING. It contains
% one or multiple segments of data, each represented as Nchan X Ntime
% arrays.
%
% An example of a raw data structure with 151 MEG channels is
%
% label: {151x1 cell} the channel labels (e.g. 'MRC13')
% time: {1x266 cell} the timeaxis [1*Ntime double] per trial
% trial: {1x266 cell} the numeric data [151*Ntime double] per trial
% sampleinfo: [266x2 double] the begin and endsample of each trial relative to the recording on disk
% trialinfo: [266x1 double] optional trigger or condition codes for each trial
% hdr: [1x1 struct] the full header information of the original dataset on disk
% grad: [1x1 struct] information about the sensor array (for EEG it is called elec)
% cfg: [1x1 struct] the configuration used by the function that generated this data structure
%
% Required fields:
% - time, trial, label
%
% Optional fields:
% - sampleinfo, trialinfo, grad, elec, opto, hdr, cfg
%
% Deprecated fields:
% - fsample
%
% Obsoleted fields:
% - offset
%
% Revision history:
%
% (2011/latest) The description of the sensors has changed, see FT_DATATYPE_SENS
% for further information.
%
% (2010v2) The trialdef field has been replaced by the sampleinfo and
% trialinfo fields. The sampleinfo corresponds to trl(:,1:2), the trialinfo
% to trl(4:end).
%
% (2010v1) In 2010/Q3 it shortly contained the trialdef field which was a copy
% of the trial definition (trl) is generated by FT_DEFINETRIAL.
%
% (2007) It used to contain the offset field, which correcponds to trl(:,3).
% Since the offset field is redundant with the time axis, the offset field is
% from now on not present any more. It can be recreated if needed.
%
% (2003) The initial version was defined
%
% See also FT_DATATYPE, FT_DATATYPE_COMP, FT_DATATYPE_TIMELOCK, FT_DATATYPE_FREQ,
% FT_DATATYPE_SPIKE, FT_DATATYPE_SENS
% Copyright (C) 2011, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$
% get the optional input arguments, which should be specified as key-value pairs
version = ft_getopt(varargin, 'version', 'latest');
hassampleinfo = ft_getopt(varargin, 'hassampleinfo', 'ifmakessense'); % can be yes/no/ifmakessense
hastrialinfo = ft_getopt(varargin, 'hastrialinfo', 'ifmakessense'); % can be yes/no/ifmakessense
% do some sanity checks
assert(isfield(data, 'trial') && isfield(data, 'time') && isfield(data, 'label'), 'inconsistent raw data structure, some field is missing');
assert(length(data.trial)==length(data.time), 'inconsistent number of trials in raw data structure');
for i=1:length(data.trial)
assert(size(data.trial{i},2)==length(data.time{i}), 'inconsistent number of samples in trial %d', i);
assert(size(data.trial{i},1)==length(data.label), 'inconsistent number of channels in trial %d', i);
end
% convert it into true/false
if isequal(hassampleinfo, 'ifmakessense')
hassampleinfo = makessense(data, 'sampleinfo');
else
hassampleinfo = istrue(hassampleinfo);
end
if isequal(hastrialinfo, 'ifmakessense')
hastrialinfo = makessense(data, 'trialinfo');
else
hastrialinfo = istrue(hastrialinfo);
end
if strcmp(version, 'latest')
version = '2011';
end
if isempty(data)
return;
end
switch version
case '2011'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ensure that the sensor structures are up to date
if isfield(data, 'grad')
data.grad = ft_datatype_sens(data.grad);
end
if isfield(data, 'elec')
data.elec = ft_datatype_sens(data.elec);
end
if isfield(data, 'opto')
data.opto = ft_datatype_sens(data.opto);
end
if ~isfield(data, 'fsample')
for i=1:length(data.time)
if length(data.time{i})>1
data.fsample = 1/mean(diff(data.time{i}));
break
else
data.fsample = nan;
end
end
if isnan(data.fsample)
ft_warning('cannot determine sampling frequency');
end
end
if isfield(data, 'offset')
data = rmfield(data, 'offset');
end
% the trialdef field should be renamed into sampleinfo
if isfield(data, 'trialdef')
data.sampleinfo = data.trialdef;
data = rmfield(data, 'trialdef');
end
if (hassampleinfo && ~isfield(data, 'sampleinfo')) || (hastrialinfo && ~isfield(data, 'trialinfo'))
% try to reconstruct the sampleinfo and trialinfo
data = fixsampleinfo(data);
end
if ~hassampleinfo && isfield(data, 'sampleinfo')
data = rmfield(data, 'sampleinfo');
end
if ~hastrialinfo && isfield(data, 'trialinfo')
data = rmfield(data, 'trialinfo');
end
case '2010v2'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isfield(data, 'fsample')
data.fsample = 1/mean(diff(data.time{1}));
end
if isfield(data, 'offset')
data = rmfield(data, 'offset');
end
% the trialdef field should be renamed into sampleinfo
if isfield(data, 'trialdef')
data.sampleinfo = data.trialdef;
data = rmfield(data, 'trialdef');
end
if (hassampleinfo && ~isfield(data, 'sampleinfo')) || (hastrialinfo && ~isfield(data, 'trialinfo'))
% try to reconstruct the sampleinfo and trialinfo
data = fixsampleinfo(data);
end
if ~hassampleinfo && isfield(data, 'sampleinfo')
data = rmfield(data, 'sampleinfo');
end
if ~hastrialinfo && isfield(data, 'trialinfo')
data = rmfield(data, 'trialinfo');
end
case {'2010v1' '2010'}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isfield(data, 'fsample')
data.fsample = 1/mean(diff(data.time{1}));
end
if isfield(data, 'offset')
data = rmfield(data, 'offset');
end
if ~isfield(data, 'trialdef') && hascfg
% try to find it in the nested configuration history
data.trialdef = ft_findcfg(data.cfg, 'trl');
end
case '2007'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isfield(data, 'fsample')
data.fsample = 1/mean(diff(data.time{1}));
end
if isfield(data, 'offset')
data = rmfield(data, 'offset');
end
case '2003'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isfield(data, 'fsample')
data.fsample = 1/mean(diff(data.time{1}));
end
if ~isfield(data, 'offset')
data.offset = zeros(length(data.time),1);
for i=1:length(data.time);
data.offset(i) = round(data.time{i}(1)*data.fsample);
end
end
otherwise
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
ft_error('unsupported version "%s" for raw datatype', version);
end
% Numerical inaccuracies in the binary representations of floating point
% values may accumulate. The following code corrects for small inaccuracies
% in the time axes of the trials. See http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=1390
data = fixtimeaxes(data);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function data = fixtimeaxes(data)
if ~isfield(data, 'fsample')
fsample = 1/mean(diff(data.time{1}));
else
fsample = data.fsample;
end
begtime = nan(1, length(data.time));
endtime = nan(1, length(data.time));
numsample = zeros(1, length(data.time));
for i=1:length(data.time)
if ~isempty(data.time{i})
begtime(i) = data.time{i}(1);
endtime(i) = data.time{i}(end);
end
numsample(i) = length(data.time{i});
end
% compute the differences over trials and the tolerance
tolerance = 0.01*(1/fsample);
begdifference = abs(begtime-begtime(1));
enddifference = abs(endtime-endtime(1));
% check whether begin and/or end are identical, or close to identical
begidentical = all(begdifference==0);
endidentical = all(enddifference==0);
begsimilar = all(begdifference < tolerance);
endsimilar = all(enddifference < tolerance);
% Compute the offset of each trial relative to the first trial, and express
% that in samples. Non-integer numbers indicate that there is a slight skew
% in the time over trials. This works in case of variable length trials.
offset = fsample * (begtime-begtime(1));
skew = abs(offset - round(offset));
% try to determine all cases where a correction is needed
% note that this does not yet address all possible cases where a fix might be needed
needfix = false;
needfix = needfix || ~begidentical && begsimilar;
needfix = needfix || ~endidentical && endsimilar;
needfix = needfix || ~all(skew==0) && all(skew<0.01);
% if the skew is less than 1% it will be corrected
if needfix
ft_warning('correcting numerical inaccuracy in the time axes');
for i=1:length(data.time)
% reconstruct the time axis of each trial, using the begin latency of
% the first trial and the integer offset in samples of each trial
data.time{i} = begtime(1) + ((1:numsample(i)) - 1 + round(offset(i)))/fsample;
end
end
|
------------------------------------------------------------------------------
-- Testing the use of numeric literals
------------------------------------------------------------------------------
{-# OPTIONS --exact-split #-}
{-# OPTIONS --no-sized-types #-}
{-# OPTIONS --no-universe-polymorphism #-}
{-# OPTIONS --without-K #-}
module FOT.FOTC.Data.Nat.NumericLiterals where
open import FOTC.Base
open import FOTC.Data.Nat
------------------------------------------------------------------------------
data ℕ : Set where
z : ℕ
s : ℕ → ℕ
{-# BUILTIN NATURAL ℕ #-}
toD : ℕ → D
toD z = zero
toD (s n) = succ₁ (toD n)
ten : D
ten = toD 10
|
#run the viability classifier
run_viability <- function(input, values, session){
if (is.null(values$markerMapping)){
return (NULL)
}
#Read in the viability classifier
classifier <- readRDS(system.file("extdata", "Viability_classifier.RDS", package="cytoclops"))
housekeepers <- rownames(classifier$importance)
#extract the markers that we use
mark <- sapply(housekeepers,function(x)input[[paste0("Housekeeper_", x)]])
markers <- values$markerMapping[mark]
#add a progress bar
withProgress(message = 'Running viability classifier ... ',
detail = 'This may take a while...',
value = 0.0, {
#next process one sample at a time
lapply(1:length(values$flowset),
classify,
input,
values,
session,
markers,
mark,
housekeepers,
classifier)
})
#update the panels and lists
update_current_gate(session, input, values)
update_children_table(session, input, values)
replace_gating_list(input, values, session, selected = names(values$gatingPanels)[1])
}
#next process one sample at a time
classify <- function(idx, input, values, session,
markers, mark, housekeepers,
classifier){
#extract the right data
# + 1 to avoid median divisions by 0 and inf values generated by log2
mat <- exprs(values$flowset[[idx]])[,markers] + 1
colnames(mat) <- housekeepers
#transform the data (log2 + median centering)
mat <- log2(sweep(mat ,2,colMedians(mat),'/'))
#run the model,
pred <- predict(classifier, mat, type = "prob")
#extract the indices
indices <- (1:nrow(pred))[pred[, 2] > input$ViabilitySlider]
#drop all the gatings that have been done before
current_nam <- paste0('G',idx)
values$currentID <- (1:length(values$gatingPanels))[names(values$gatingPanels) == current_nam]
#remove all children of the current gate if there are any
if (length(values$gatingPanels[[values$currentID]]@children) > 0){
remove_child(input, values, session, values$currentID, paste0(current_nam,'_'))
}
#add a new gatingPanel with the viable cells
add_new_child(input,
values,
session,
indices = indices,
name = 'Viable cells',
xmarker = mark[1],
ymarker = mark[3])
#increment the progress bar
incProgress(amount = 1 / length(values$flowset))
} |
module Issue784.Values where
open import Data.Bool using (Bool; true; false; not)
open import Data.String public using (String)
open import Data.String.Properties public using (_≟_)
open import Function public
open import Data.List using (List; []; _∷_; _++_; [_]; filterᵇ) renaming (map to mapL)
open import Data.List.Relation.Unary.Any public using (Any; here; there) renaming (map to mapA; any to anyA)
open import Data.Product public using (Σ; Σ-syntax; proj₁; proj₂; _,_; _×_) renaming (map to mapΣ)
open import Data.Unit public using (⊤)
open import Data.Unit.NonEta public using (Unit; unit)
open import Data.Empty public using (⊥; ⊥-elim)
open import Relation.Binary.Core hiding (_⇔_) public
open import Relation.Nullary hiding (Irrelevant) public
import Level
open import Relation.Binary.PropositionalEquality public hiding ([_]) renaming (cong to ≡-cong; cong₂ to ≡-cong₂)
open import Relation.Binary.PropositionalEquality.Core public renaming (sym to ≡-sym; trans to ≡-trans)
{-
≢-sym : ∀ {ℓ} {A : Set ℓ} {x y : A} → x ≢ y → y ≢ x
≢-sym x≢y = x≢y ∘ ≡-sym
-}
≡-elim : ∀ {ℓ} {X Y : Set ℓ} → X ≡ Y → X → Y
≡-elim refl p = p
≡-elim′ : ∀ {a ℓ} {A : Set a} {x y : A} → (P : A → Set ℓ) → x ≡ y → P x → P y
≡-elim′ P = ≡-elim ∘ (≡-cong P)
Named : ∀ {ℓ} (A : Set ℓ) → Set ℓ
Named A = String × A
NamedType : ∀ ℓ → Set (Level.suc ℓ)
NamedType ℓ = Named (Set ℓ)
NamedValue : ∀ ℓ → Set (Level.suc ℓ)
NamedValue ℓ = Named (Σ[ A ∈ Set ℓ ] A)
Names : Set
Names = List String
Types : ∀ ℓ → Set (Level.suc ℓ)
Types ℓ = List (NamedType ℓ)
Values : ∀ ℓ → Set (Level.suc ℓ)
Values ℓ = List (NamedValue ℓ)
names : ∀ {ℓ} {A : Set ℓ} → List (Named A) → Names
names = mapL proj₁
types : ∀ {ℓ} → Values ℓ → Types ℓ
types = mapL (mapΣ id proj₁)
infix 4 _∈_ _∉_
_∈_ : ∀ {ℓ} {A : Set ℓ} → A → List A → Set ℓ
x ∈ xs = Any (_≡_ x) xs
_∉_ : ∀ {ℓ} {A : Set ℓ} → A → List A → Set ℓ
x ∉ xs = ¬ x ∈ xs
x∉y∷l⇒x≢y : ∀ {ℓ} {A : Set ℓ} {x y : A} {l : List A} → x ∉ y ∷ l → x ≢ y
x∉y∷l⇒x≢y x∉y∷l x≡y = x∉y∷l $ here x≡y
x∉y∷l⇒x∉l : ∀ {ℓ} {A : Set ℓ} {x y : A} {l : List A} → x ∉ y ∷ l → x ∉ l
x∉y∷l⇒x∉l x∉y∷l x∈l = x∉y∷l $ there x∈l
x≢y⇒x∉l⇒x∉y∷l : ∀ {ℓ} {A : Set ℓ} {x y : A} {l : List A} → x ≢ y → x ∉ l → x ∉ y ∷ l
x≢y⇒x∉l⇒x∉y∷l x≢y x∉l (here x≡y) = x≢y x≡y
x≢y⇒x∉l⇒x∉y∷l x≢y x∉l (there x∈l) = x∉l x∈l
infix 5 _∋!_ _∈?_
_∈?_ : (s : String) (n : Names) → Dec (s ∈ n)
s ∈? [] = no λ()
s ∈? (h ∷ t) with s ≟ h
... | yes s≡h = yes $ here s≡h
... | no s≢h with s ∈? t
... | yes s∈t = yes $ there s∈t
... | no s∉t = no $ x≢y⇒x∉l⇒x∉y∷l s≢h s∉t
_∋!_ : Names → String → Bool
l ∋! e with e ∈? l
... | yes _ = true
... | no _ = false
infix 4 _⊆_ _⊈_
_⊆_ : ∀ {ℓ} {A : Set ℓ} → List A → List A → Set ℓ
xs ⊆ ys = ∀ {x} → x ∈ xs → x ∈ ys
_⊈_ : ∀ {ℓ} {A : Set ℓ} → List A → List A → Set ℓ
xs ⊈ ys = ¬ xs ⊆ ys
infixl 5 _∪_
_∪_ : ∀ {ℓ} {A : Set ℓ} → List A → List A → List A
_∪_ = _++_
infixl 6 _∩_
_∩_ : Names → Names → Names
x ∩ y = filterᵇ (_∋!_ y) x
infixl 6 _∖_ _∖∖_
_∖_ : Names → Names → Names
_∖_ x y = filterᵇ (not ∘ _∋!_ y) x
_∖∖_ : ∀ {ℓ} {A : Set ℓ} → List (Named A) → Names → List (Named A)
_∖∖_ l n = filterᵇ (not ∘ _∋!_ n ∘ proj₁) l
filter-∈ : ∀ {ℓ} {A : Set ℓ} → List (Named A) → Names → List (Named A)
filter-∈ l n = filterᵇ (_∋!_ n ∘ proj₁) l
infixr 5 _∷_
data NonRepetitive {ℓ} {A : Set ℓ} : List A → Set ℓ where
[] : NonRepetitive []
_∷_ : ∀ {x xs} → x ∉ xs → NonRepetitive xs → NonRepetitive (x ∷ xs)
infix 4 _≋_
data _≋_ {ℓ} {A : Set ℓ} : List A → List A → Set ℓ where
refl : ∀ {l} → l ≋ l
perm : ∀ {l} l₁ x₁ x₂ l₂ → l ≋ l₁ ++ x₂ ∷ x₁ ∷ l₂ → l ≋ l₁ ++ x₁ ∷ x₂ ∷ l₂
NonRepetitiveNames : ∀ {ℓ} {A : Set ℓ} → List (Named A) → Set
NonRepetitiveNames = NonRepetitive ∘ names
NonRepetitiveTypes : ∀ ℓ → Set (Level.suc ℓ)
NonRepetitiveTypes ℓ = Σ[ t ∈ Types ℓ ] NonRepetitiveNames t
-- lemmas
∪-assoc : ∀ {l} {A : Set l} (x y z : List A) → (x ∪ y) ∪ z ≡ x ∪ (y ∪ z)
∪-assoc [] y z = refl
∪-assoc (x ∷ xs) y z = ≡-elim′ (λ e → x ∷ e ≡ (x ∷ xs) ∪ (y ∪ z)) (≡-sym $ ∪-assoc xs y z) refl
≡⇒≋ : ∀ {ℓ} {A : Set ℓ} {x y : List A} → x ≡ y → x ≋ y
≡⇒≋ refl = refl
private
∈-perm : ∀ {ℓ} {A : Set ℓ} {x : A} (l₁ : List A) (e₁ : A) (e₂ : A) (l₂ : List A) → x ∈ l₁ ++ e₁ ∷ e₂ ∷ l₂ → x ∈ l₁ ++ e₂ ∷ e₁ ∷ l₂
∈-perm [] e₁ e₂ l₂ (here .{e₁} .{e₂ ∷ l₂} px) = there $ here px
∈-perm [] e₁ e₂ l₂ (there .{e₁} .{e₂ ∷ l₂} (here .{e₂} .{l₂} px)) = here px
∈-perm [] e₁ e₂ l₂ (there .{e₁} .{e₂ ∷ l₂} (there .{e₂} .{l₂} pxs)) = there $ there pxs
∈-perm (h₁ ∷ t₁) e₁ e₂ l₂ (here .{h₁} .{t₁ ++ e₁ ∷ e₂ ∷ l₂} px) = here px
∈-perm (h₁ ∷ t₁) e₁ e₂ l₂ (there .{h₁} .{t₁ ++ e₁ ∷ e₂ ∷ l₂} pxs) = there $ ∈-perm t₁ e₁ e₂ l₂ pxs
≋⇒⊆ : ∀ {ℓ} {A : Set ℓ} {x y : List A} → x ≋ y → x ⊆ y
≋⇒⊆ refl p = p
≋⇒⊆ {x = x} {y = .(l₁ ++ x₁ ∷ x₂ ∷ l₂)} (perm l₁ x₁ x₂ l₂ p) {e} e∈x = ∈-perm l₁ x₂ x₁ l₂ $ ≋⇒⊆ p e∈x
≋-trans : ∀ {l} {A : Set l} {x y z : List A} → x ≋ y → y ≋ z → x ≋ z
≋-trans p refl = p
≋-trans p₁ (perm l₁ x₁ x₂ l₂ p₂) = perm l₁ x₁ x₂ l₂ $ ≋-trans p₁ p₂
≋-sym : ∀ {l} {A : Set l} {x y : List A} → x ≋ y → y ≋ x
≋-sym refl = refl
≋-sym (perm l₁ x₁ x₂ l₂ p) = ≋-trans (perm l₁ x₂ x₁ l₂ refl) (≋-sym p)
≋-del-ins-r : ∀ {l} {A : Set l} (l₁ : List A) (x : A) (l₂ l₃ : List A) → (l₁ ++ x ∷ l₂ ++ l₃) ≋ (l₁ ++ l₂ ++ x ∷ l₃)
≋-del-ins-r l₁ x [] l₃ = refl
≋-del-ins-r l₁ x (h ∷ t) l₃ = ≋-trans p₀ p₅
where p₀ : (l₁ ++ x ∷ h ∷ t ++ l₃) ≋ (l₁ ++ h ∷ x ∷ t ++ l₃)
p₀ = perm l₁ h x (t ++ l₃) refl
p₁ : ((l₁ ++ [ h ]) ++ x ∷ t ++ l₃) ≋ ((l₁ ++ [ h ]) ++ t ++ x ∷ l₃)
p₁ = ≋-del-ins-r (l₁ ++ [ h ]) x t l₃
p₂ : (l₁ ++ [ h ]) ++ t ++ x ∷ l₃ ≡ l₁ ++ h ∷ t ++ x ∷ l₃
p₂ = ∪-assoc l₁ [ h ] (t ++ x ∷ l₃)
p₃ : (l₁ ++ [ h ]) ++ x ∷ t ++ l₃ ≡ l₁ ++ h ∷ x ∷ t ++ l₃
p₃ = ∪-assoc l₁ [ h ] (x ∷ t ++ l₃)
p₄ : ((l₁ ++ [ h ]) ++ x ∷ t ++ l₃) ≋ (l₁ ++ h ∷ t ++ x ∷ l₃)
p₄ = ≡-elim′ (λ y → ((l₁ ++ [ h ]) ++ x ∷ t ++ l₃) ≋ y) p₂ p₁
p₅ : (l₁ ++ h ∷ x ∷ t ++ l₃) ≋ (l₁ ++ h ∷ t ++ x ∷ l₃)
p₅ = ≡-elim′ (λ y → y ≋ (l₁ ++ h ∷ t ++ x ∷ l₃)) p₃ p₄
≋-del-ins-l : ∀ {l} {A : Set l} (l₁ l₂ : List A) (x : A) (l₃ : List A) → (l₁ ++ l₂ ++ x ∷ l₃) ≋ (l₁ ++ x ∷ l₂ ++ l₃)
≋-del-ins-l l₁ l₂ x l₃ = ≋-sym $ ≋-del-ins-r l₁ x l₂ l₃
x∪[]≡x : ∀ {ℓ} {A : Set ℓ} (x : List A) → x ∪ [] ≡ x
x∪[]≡x [] = refl
x∪[]≡x (h ∷ t) = ≡-trans p₀ p₁
where p₀ : (h ∷ t) ++ [] ≡ h ∷ t ++ []
p₀ = ∪-assoc [ h ] t []
p₁ : h ∷ t ++ [] ≡ h ∷ t
p₁ = ≡-cong (λ x → h ∷ x) (x∪[]≡x t)
x∖[]≡x : (x : Names) → x ∖ [] ≡ x
x∖[]≡x [] = refl
x∖[]≡x (h ∷ t) = ≡-cong (_∷_ h) (x∖[]≡x t)
t∖[]≡t : ∀ {ℓ} {A : Set ℓ} (t : List (Named A)) → t ∖∖ [] ≡ t
t∖[]≡t [] = refl
t∖[]≡t (h ∷ t) = ≡-cong (_∷_ h) (t∖[]≡t t)
e∷x≋e∷y : ∀ {ℓ} {A : Set ℓ} (e : A) {x y : List A} → x ≋ y → e ∷ x ≋ e ∷ y
e∷x≋e∷y _ refl = refl
e∷x≋e∷y x (perm l₁ e₁ e₂ l₂ p) = perm (x ∷ l₁) e₁ e₂ l₂ (e∷x≋e∷y x p)
∪-sym : ∀ {ℓ} {A : Set ℓ} (x y : List A) → x ∪ y ≋ y ∪ x
∪-sym [] y = ≡-elim′ (λ z → y ≋ z) (≡-sym $ x∪[]≡x y) refl
∪-sym x [] = ≡-elim′ (λ z → z ≋ x) (≡-sym $ x∪[]≡x x) refl
∪-sym x (y ∷ ys) = ≡-elim′ (λ z → x ++ (y ∷ ys) ≋ z) p₃ (≋-trans p₁ p₂) where
p₁ : x ++ (y ∷ ys) ≋ y ∷ (x ++ ys)
p₁ = ≋-del-ins-l [] x y ys
p₂ : y ∷ (x ++ ys) ≋ y ∷ (ys ++ x)
p₂ = e∷x≋e∷y y $ ∪-sym x ys
p₃ : y ∷ (ys ++ x) ≡ (y ∷ ys) ++ x
p₃ = ∪-assoc [ y ] ys x
y≋ỳ⇒x∪y≋x∪ỳ : ∀ {ℓ} {A : Set ℓ} (x : List A) {y ỳ : List A} → y ≋ ỳ → x ∪ y ≋ x ∪ ỳ
y≋ỳ⇒x∪y≋x∪ỳ [] p = p
y≋ỳ⇒x∪y≋x∪ỳ (h ∷ t) p = e∷x≋e∷y h (y≋ỳ⇒x∪y≋x∪ỳ t p)
x≋x̀⇒x∪y≋x̀∪y : ∀ {ℓ} {A : Set ℓ} {x x̀ : List A} → x ≋ x̀ → (y : List A) → x ∪ y ≋ x̀ ∪ y
x≋x̀⇒x∪y≋x̀∪y {x = x} {x̀ = x̀} p y = ≋-trans (∪-sym x y) $ ≋-trans (y≋ỳ⇒x∪y≋x∪ỳ y p) (∪-sym y x̀)
x⊆y≋z : ∀ {ℓ} {A : Set ℓ} {x y z : List A} → x ⊆ y → y ≋ z → x ⊆ z
x⊆y≋z x⊆y refl = x⊆y
x⊆y≋z {x = x} {y = y} {z = .(l₁ ++ x₁ ∷ x₂ ∷ l₂)} x⊆y (perm l₁ x₁ x₂ l₂ p) = ∈-perm l₁ x₂ x₁ l₂ ∘ x⊆y≋z x⊆y p
x≋y⊆z : ∀ {ℓ} {A : Set ℓ} {x y z : List A} → x ≋ y → x ⊆ z → y ⊆ z
x≋y⊆z refl x⊆z = x⊆z
x≋y⊆z {y = .(l₁ ++ x₁ ∷ x₂ ∷ l₂)} {z = z} (perm l₁ x₁ x₂ l₂ p) x⊆z = x≋y⊆z p x⊆z ∘ ∈-perm l₁ x₁ x₂ l₂
x⊆x∪y : ∀ {ℓ} {A : Set ℓ} (x y : List A) → x ⊆ x ∪ y
x⊆x∪y .(x ∷ xs) y (here {x} {xs} px) = here px
x⊆x∪y .(x ∷ xs) y (there {x} {xs} pxs) = there $ x⊆x∪y xs y pxs
x∪y⊆z⇒x⊆z : ∀ {ℓ} {A : Set ℓ} (x y : List A) {z : List A} → x ∪ y ⊆ z → x ⊆ z
x∪y⊆z⇒x⊆z x y x∪y⊆z = x∪y⊆z ∘ x⊆x∪y x y
x∪y⊆z⇒y⊆z : ∀ {ℓ} {A : Set ℓ} (x y : List A) {z : List A} → x ∪ y ⊆ z → y ⊆ z
x∪y⊆z⇒y⊆z x y = x∪y⊆z⇒x⊆z y x ∘ x≋y⊆z (∪-sym x y)
n-x∪y : ∀ {ℓ} {A : Set ℓ} (x y : List (Named A)) → names (x ∪ y) ≡ names x ∪ names y
n-x∪y [] _ = refl
n-x∪y {ℓ} (x ∷ xs) y = ≡-trans p₁ p₂ where
nx = [ proj₁ x ]
nxs = names xs
ny = names y
p₁ : nx ∪ names (xs ∪ y) ≡ nx ∪ (nxs ∪ ny)
p₁ = ≡-cong (λ z → nx ∪ z) (n-x∪y xs y)
p₂ : nx ∪ (nxs ∪ ny) ≡ (nx ∪ nxs) ∪ ny
p₂ = ≡-sym $ ∪-assoc nx nxs ny
t-x∪y : ∀ {ℓ} (x y : Values ℓ) → types (x ∪ y) ≡ types x ∪ types y
t-x∪y [] _ = refl
t-x∪y (x ∷ xs) y = ≡-trans p₁ p₂ where
nx = types [ x ]
nxs = types xs
ny = types y
p₁ : nx ∪ types (xs ∪ y) ≡ nx ∪ (nxs ∪ ny)
p₁ = ≡-cong (λ z → nx ∪ z) (t-x∪y xs y)
p₂ : nx ∪ (nxs ∪ ny) ≡ (nx ∪ nxs) ∪ ny
p₂ = ≡-sym $ ∪-assoc nx nxs ny
n-x≋y : ∀ {ℓ} {A : Set ℓ} {x y : List (Named A)} → x ≋ y → names x ≋ names y
n-x≋y refl = refl
n-x≋y (perm {x} l₁ e₁ e₂ l₂ p) = p₃ where
n-l₁e₁e₂l₂ : ∀ e₁ e₂ → names (l₁ ++ e₁ ∷ e₂ ∷ l₂) ≡ names l₁ ++ names [ e₁ ] ++ names [ e₂ ] ++ names l₂
n-l₁e₁e₂l₂ e₁ e₂ = ≡-trans p₁ $ ≡-trans p₂ p₃ where
p₁ : names (l₁ ++ e₁ ∷ e₂ ∷ l₂) ≡ names l₁ ++ names (e₁ ∷ e₂ ∷ l₂)
p₁ = n-x∪y l₁ (e₁ ∷ e₂ ∷ l₂)
p₂ : names l₁ ++ names (e₁ ∷ e₂ ∷ l₂) ≡ names l₁ ++ names [ e₁ ] ++ names (e₂ ∷ l₂)
p₂ = ≡-cong (λ z → names l₁ ++ z) (n-x∪y [ e₁ ] (e₂ ∷ l₂))
p₃ : names l₁ ++ names [ e₁ ] ++ names (e₂ ∷ l₂) ≡ names l₁ ++ names [ e₁ ] ++ names [ e₂ ] ++ names l₂
p₃ = ≡-cong (λ z → names l₁ ++ names [ e₁ ] ++ z) (n-x∪y [ e₂ ] l₂)
p₁ : names x ≋ names l₁ ++ proj₁ e₂ ∷ proj₁ e₁ ∷ names l₂
p₁ = ≡-elim′ (λ z → names x ≋ z) (n-l₁e₁e₂l₂ e₂ e₁) (n-x≋y p)
p₂ : names x ≋ names l₁ ++ proj₁ e₁ ∷ proj₁ e₂ ∷ names l₂
p₂ = perm (names l₁) (proj₁ e₁) (proj₁ e₂) (names l₂) p₁
p₃ : names x ≋ names (l₁ ++ e₁ ∷ e₂ ∷ l₂)
p₃ = ≡-elim′ (λ z → names x ≋ z) (≡-sym $ n-l₁e₁e₂l₂ e₁ e₂) p₂
n-types : ∀ {ℓ} (x : Values ℓ) → names (types x) ≡ names x
n-types [] = refl
n-types (x ∷ xs) = ≡-cong (λ z → proj₁ x ∷ z) (n-types xs)
nr-x≋y : ∀ {ℓ} {A : Set ℓ} {x y : List A} → x ≋ y → NonRepetitive x → NonRepetitive y
nr-x≋y refl u = u
nr-x≋y {y = .(l₁ ++ e₁ ∷ e₂ ∷ l₂)} (perm l₁ e₁ e₂ l₂ p) u = ≋-step l₁ e₂ e₁ l₂ (nr-x≋y p u) where
∉-step : ∀ {ℓ} {A : Set ℓ} {x : A} (l₁ : List A) (e₁ : A) (e₂ : A) (l₂ : List A) → x ∉ l₁ ++ e₁ ∷ e₂ ∷ l₂ → x ∉ l₁ ++ e₂ ∷ e₁ ∷ l₂
∉-step l₁ e₁ e₂ l₂ x∉l x∈l = ⊥-elim $ x∉l $ ∈-perm l₁ e₂ e₁ l₂ x∈l
≋-step : ∀ {ℓ} {A : Set ℓ} (l₁ : List A) (e₁ : A) (e₂ : A) (l₂ : List A) → NonRepetitive (l₁ ++ e₁ ∷ e₂ ∷ l₂) → NonRepetitive (l₁ ++ e₂ ∷ e₁ ∷ l₂)
≋-step [] e₁ e₂ l₂ (_∷_ .{e₁} .{e₂ ∷ l₂} e₁∉e₂∷l₂ (_∷_ .{e₂} .{l₂} e₂∉l₂ pU)) = e₂∉e₁∷l₂ ∷ e₁∉l₂ ∷ pU where
e₁∉l₂ = e₁ ∉ l₂ ∋ x∉y∷l⇒x∉l e₁∉e₂∷l₂
e₂∉e₁∷l₂ = e₂ ∉ e₁ ∷ l₂ ∋ x≢y⇒x∉l⇒x∉y∷l (≢-sym $ x∉y∷l⇒x≢y e₁∉e₂∷l₂) e₂∉l₂
≋-step (h₁ ∷ t₁) e₁ e₂ l₂ (_∷_ .{h₁} .{t₁ ++ e₁ ∷ e₂ ∷ l₂} p∉ pU) = ∉-step t₁ e₁ e₂ l₂ p∉ ∷ ≋-step t₁ e₁ e₂ l₂ pU
nr-x⇒nr-t-x : ∀ {ℓ} {x : Values ℓ} → NonRepetitiveNames x → NonRepetitiveNames (types x)
nr-x⇒nr-t-x {x = x} = ≡-elim′ NonRepetitive (≡-sym $ n-types x)
n-x∖y : ∀ {ℓ} {A : Set ℓ} (x : List (Named A)) (y : Names) → names (x ∖∖ y) ≡ names x ∖ y
n-x∖y [] _ = refl
n-x∖y (x ∷ xs) ny with not $ ny ∋! proj₁ x
... | false = n-x∖y xs ny
... | true = ≡-trans p₁ p₂ where
p₁ : names (x ∷ (xs ∖∖ ny)) ≡ proj₁ x ∷ names (xs ∖∖ ny)
p₁ = n-x∪y [ x ] (xs ∖∖ ny)
p₂ : proj₁ x ∷ names (xs ∖∖ ny) ≡ proj₁ x ∷ (names xs ∖ ny)
p₂ = ≡-cong (λ z → proj₁ x ∷ z) (n-x∖y xs ny)
t-x∖y : ∀ {ℓ} (x : Values ℓ) (y : Names) → types (x ∖∖ y) ≡ types x ∖∖ y
t-x∖y [] _ = refl
t-x∖y (x ∷ xs) ny with not $ ny ∋! proj₁ x
... | false = t-x∖y xs ny
... | true = ≡-trans p₁ p₂ where
x̀ = types [ x ]
p₁ : types (x ∷ (xs ∖∖ ny)) ≡ x̀ ∪ types (xs ∖∖ ny)
p₁ = t-x∪y [ x ] (xs ∖∖ ny)
p₂ : x̀ ∪ types (xs ∖∖ ny) ≡ x̀ ∪ (types xs ∖∖ ny)
p₂ = ≡-cong (λ z → x̀ ∪ z) (t-x∖y xs ny)
n-filter-∈ : ∀ {ℓ} {A : Set ℓ} (x : List (Named A)) (y : Names) → names (filter-∈ x y) ≡ names x ∩ y
n-filter-∈ [] _ = refl
n-filter-∈ (x ∷ xs) ny with ny ∋! proj₁ x
... | false = n-filter-∈ xs ny
... | true = ≡-trans p₁ p₂ where
p₁ : names (x ∷ (filter-∈ xs ny)) ≡ proj₁ x ∷ names (filter-∈ xs ny)
p₁ = n-x∪y [ x ] (filter-∈ xs ny)
p₂ : proj₁ x ∷ names (filter-∈ xs ny) ≡ proj₁ x ∷ (names xs ∩ ny)
p₂ = ≡-cong (λ z → proj₁ x ∷ z) (n-filter-∈ xs ny)
t-filter-∈ : ∀ {ℓ} (x : Values ℓ) (y : Names) → types (filter-∈ x y) ≡ filter-∈ (types x) y
t-filter-∈ [] _ = refl
t-filter-∈ (x ∷ xs) ny with ny ∋! proj₁ x
... | false = t-filter-∈ xs ny
... | true = ≡-trans p₁ p₂ where
x̀ = types [ x ]
p₁ : types (x ∷ filter-∈ xs ny) ≡ x̀ ∪ types (filter-∈ xs ny)
p₁ = t-x∪y [ x ] (filter-∈ xs ny)
p₂ : x̀ ∪ types (filter-∈ xs ny) ≡ x̀ ∪ filter-∈ (types xs) ny
p₂ = ≡-cong (λ z → x̀ ∪ z) (t-filter-∈ xs ny)
[]⊆x : ∀ {ℓ} {A : Set ℓ} (x : List A) → [] ⊆ x
[]⊆x _ ()
∀x∉[] : ∀ {ℓ} {A : Set ℓ} {x : A} → x ∉ []
∀x∉[] ()
x⊆[]⇒x≡[] : ∀ {ℓ} {A : Set ℓ} {x : List A} → x ⊆ [] → x ≡ []
x⊆[]⇒x≡[] {x = []} _ = refl
x⊆[]⇒x≡[] {x = _ ∷ _} x⊆[] = ⊥-elim $ ∀x∉[] $ x⊆[] (here refl)
x∩y⊆x : ∀ {ℓ} {A : Set ℓ} (x : List (Named A)) (y : Names) → filter-∈ x y ⊆ x
x∩y⊆x [] _ = λ()
x∩y⊆x (h ∷ t) y with y ∋! proj₁ h
... | false = there ∘ x∩y⊆x t y
... | true = f where
f : h ∷ filter-∈ t y ⊆ h ∷ t
f (here {x = .h} p) = here p
f (there {xs = .(filter-∈ t y)} p) = there $ x∩y⊆x t y p
e∈x⇒e∈y∪x : ∀ {ℓ} {A : Set ℓ} {e : A} {x : List A} (y : List A) → e ∈ x → e ∈ y ∪ x
e∈x⇒e∈y∪x [] = id
e∈x⇒e∈y∪x (h ∷ t) = there ∘ e∈x⇒e∈y∪x t
e∈x⇒e∈x∪y : ∀ {ℓ} {A : Set ℓ} {e : A} {x : List A} (y : List A) → e ∈ x → e ∈ x ∪ y
e∈x⇒e∈x∪y {e = e} {x = x} y e∈x = x⊆y≋z f (∪-sym y x) (e ∈ [ e ] ∋ here refl) where
f : [ e ] ⊆ y ∪ x
f {è} (here {x = .e} p) = ≡-elim′ (λ z → z ∈ y ∪ x) (≡-sym p) (e∈x⇒e∈y∪x y e∈x)
f (there ())
x∪y⊆x̀∪ỳ : ∀ {ℓ} {A : Set ℓ} {x x̀ y ỳ : List A} → x ⊆ x̀ → y ⊆ ỳ → x ∪ y ⊆ x̀ ∪ ỳ
x∪y⊆x̀∪ỳ {x = []} {x̀ = []} _ y⊆ỳ = y⊆ỳ
x∪y⊆x̀∪ỳ {x = []} {x̀ = _ ∷ t̀} _ y⊆ỳ = there ∘ x∪y⊆x̀∪ỳ ([]⊆x t̀) y⊆ỳ
x∪y⊆x̀∪ỳ {x = h ∷ t} {x̀ = x̀} {y = y} {ỳ = ỳ} x⊆x̀ y⊆ỳ = f where
f : (h ∷ t) ∪ y ⊆ x̀ ∪ ỳ
f {e} (here {x = .h} e≡h) = e∈x⇒e∈x∪y ỳ (x⊆x̀ $ here e≡h)
f {e} (there {xs = .(t ∪ y)} p) = x∪y⊆x̀∪ỳ (x∪y⊆z⇒y⊆z [ h ] t x⊆x̀) y⊆ỳ p
x∖y⊆x : (x y : Names) → x ∖ y ⊆ x
x∖y⊆x [] _ = λ()
x∖y⊆x (h ∷ t) y with y ∋! h
... | true = there ∘ x∖y⊆x t y
... | false = x∪y⊆x̀∪ỳ (≋⇒⊆ $ ≡⇒≋ $ refl {x = [ h ]}) (x∖y⊆x t y)
t≋t∖n∪t∩n : ∀ {ℓ} {A : Set ℓ} (t : List (Named A)) (n : Names) → t ≋ (t ∖∖ n) ∪ filter-∈ t n
t≋t∖n∪t∩n [] _ = refl
t≋t∖n∪t∩n (h ∷ t) n with n ∋! proj₁ h
... | false = e∷x≋e∷y h $ t≋t∖n∪t∩n t n
... | true = ≋-trans p₁ p₂ where
p₁ : h ∷ t ≋ (h ∷ (t ∖∖ n)) ∪ filter-∈ t n
p₁ = e∷x≋e∷y h $ t≋t∖n∪t∩n t n
p₂ : (h ∷ (t ∖∖ n)) ∪ filter-∈ t n ≋ (t ∖∖ n) ∪ (h ∷ filter-∈ t n)
p₂ = ≋-del-ins-r [] h (t ∖∖ n) (filter-∈ t n)
e₁∈x⇒e₂∉x⇒e≢e₂ : ∀ {ℓ} {A : Set ℓ} {e₁ e₂ : A} {x : List A} → e₁ ∈ x → e₂ ∉ x → e₁ ≢ e₂
e₁∈x⇒e₂∉x⇒e≢e₂ e₁∈x e₂∉x refl = e₂∉x e₁∈x
e₁∈e₂∷x⇒e₁≢e₂⇒e₁∈x : ∀ {ℓ} {A : Set ℓ} {e₁ e₂ : A} {x : List A} → e₁ ∈ e₂ ∷ x → e₁ ≢ e₂ → e₁ ∈ x
e₁∈e₂∷x⇒e₁≢e₂⇒e₁∈x (here e₁≡e₂) e₁≢e₂ = ⊥-elim $ e₁≢e₂ e₁≡e₂
e₁∈e₂∷x⇒e₁≢e₂⇒e₁∈x (there e₁∈x) _ = e₁∈x
x⊆e∷y⇒e∉x⇒x⊆y : ∀ {ℓ} {A : Set ℓ} {e : A} {x y : List A} → x ⊆ e ∷ y → e ∉ x → x ⊆ y
x⊆e∷y⇒e∉x⇒x⊆y {e = e} {x = x} {y = y} x⊆e∷y e∉x {è} è∈x = e₁∈e₂∷x⇒e₁≢e₂⇒e₁∈x (x⊆e∷y è∈x) (e₁∈x⇒e₂∉x⇒e≢e₂ è∈x e∉x)
n-e∉l⇒e∉l : ∀ {ℓ} {A : Set ℓ} {e : Named A} {l : List (Named A)} → proj₁ e ∉ names l → e ∉ l
n-e∉l⇒e∉l {e = e} n-e∉l (here {x = è} p) = ⊥-elim $ n-e∉l $ here $ ≡-cong proj₁ p
n-e∉l⇒e∉l n-e∉l (there p) = n-e∉l⇒e∉l (x∉y∷l⇒x∉l n-e∉l) p
nr-names⇒nr : ∀ {ℓ} {A : Set ℓ} {l : List (Named A)} → NonRepetitiveNames l → NonRepetitive l
nr-names⇒nr {l = []} [] = []
nr-names⇒nr {l = _ ∷ _} (nh∉nt ∷ nr-t) = n-e∉l⇒e∉l nh∉nt ∷ nr-names⇒nr nr-t
e∉x⇒e∉y⇒e∉x∪y : ∀ {ℓ} {A : Set ℓ} {e : A} {x y : List A} → e ∉ x → e ∉ y → e ∉ x ∪ y
e∉x⇒e∉y⇒e∉x∪y {x = []} _ e∉y e∈y = ⊥-elim $ e∉y e∈y
e∉x⇒e∉y⇒e∉x∪y {x = h ∷ t} e∉x e∉y (here e≡h) = ⊥-elim $ e∉x $ here e≡h
e∉x⇒e∉y⇒e∉x∪y {x = h ∷ t} e∉x e∉y (there e∈t∪y) = e∉x⇒e∉y⇒e∉x∪y (x∉y∷l⇒x∉l e∉x) e∉y e∈t∪y
nr-x∖y∪y : {x y : Names} → NonRepetitive x → NonRepetitive y → NonRepetitive (x ∖ y ∪ y)
nr-x∖y∪y {x = []} _ nr-y = nr-y
nr-x∖y∪y {x = x ∷ xs} {y = y} (x∉xs ∷ nr-xs) nr-y with x ∈? y
... | yes x∈y = nr-x∖y∪y nr-xs nr-y
... | no x∉y = e∉x⇒e∉y⇒e∉x∪y (⊥-elim ∘ x∉xs ∘ x∖y⊆x xs y) x∉y ∷ nr-x∖y∪y nr-xs nr-y
e∉l∖[e] : (e : String) (l : Names) → e ∉ l ∖ [ e ]
e∉l∖[e] _ [] = λ()
e∉l∖[e] e (h ∷ t) with h ≟ e
... | yes _ = e∉l∖[e] e t
... | no h≢e = x≢y⇒x∉l⇒x∉y∷l (≢-sym h≢e) (e∉l∖[e] e t)
e∉l⇒l∖e≡l : {e : String} {l : Names} → e ∉ l → l ∖ [ e ] ≡ l
e∉l⇒l∖e≡l {e = e} {l = []} _ = refl
e∉l⇒l∖e≡l {e = e} {l = h ∷ t} e∉l with h ∈? [ e ]
... | yes h∈e = ⊥-elim $ x≢y⇒x∉l⇒x∉y∷l (≢-sym $ x∉y∷l⇒x≢y e∉l) (λ()) h∈e
... | no h∉e = ≡-cong (_∷_ h) (e∉l⇒l∖e≡l $ x∉y∷l⇒x∉l e∉l)
e∈l⇒nr-l⇒l∖e∪e≋l : {e : String} {l : Names} → e ∈ l → NonRepetitive l → l ∖ [ e ] ∪ [ e ] ≋ l
e∈l⇒nr-l⇒l∖e∪e≋l {l = []} () _
e∈l⇒nr-l⇒l∖e∪e≋l {e = e} {l = h ∷ t} e∈h∷t (h∉t ∷ nr-t) with h ∈? [ e ]
... | yes (here h≡e) = ≋-trans (≡⇒≋ $ ≡-trans p₁ p₂) (∪-sym t [ h ]) where
p₁ : t ∖ [ e ] ∪ [ e ] ≡ t ∖ [ h ] ∪ [ h ]
p₁ = ≡-cong (λ x → t ∖ [ x ] ∪ [ x ]) (≡-sym h≡e)
p₂ : t ∖ [ h ] ∪ [ h ] ≡ t ∪ [ h ]
p₂ = ≡-cong (λ x → x ∪ [ h ]) (e∉l⇒l∖e≡l h∉t)
... | yes (there ())
... | no h∉e with e∈h∷t
... | here e≡h = ⊥-elim ∘ h∉e ∘ here ∘ ≡-sym $ e≡h
... | there e∈t = e∷x≋e∷y _ $ e∈l⇒nr-l⇒l∖e∪e≋l e∈t nr-t
nr-x∖y : {x : Names} → NonRepetitive x → (y : Names) → NonRepetitive (x ∖ y)
nr-x∖y {x = []} _ _ = []
nr-x∖y {x = x ∷ xs} (x∉xs ∷ nr-xs) y with x ∈? y
... | yes x∈y = nr-x∖y nr-xs y
... | no x∉y = ⊥-elim ∘ x∉xs ∘ x∖y⊆x xs y ∷ nr-x∖y nr-xs y
x⊆y⇒e∉y⇒e∉x : ∀ {ℓ} {A : Set ℓ} {e : A} {x y : List A} → x ⊆ y → e ∉ y → e ∉ x
x⊆y⇒e∉y⇒e∉x x⊆y e∉y e∈x = e∉y $ x⊆y e∈x
e∈n-l⇒∃è,n-è≡e×è∈l : ∀ {ℓ} {A : Set ℓ} {e : String} {l : List (Named A)} → e ∈ names l → Σ[ è ∈ Named A ] (e ≡ proj₁ è × è ∈ l)
e∈n-l⇒∃è,n-è≡e×è∈l {l = []} ()
e∈n-l⇒∃è,n-è≡e×è∈l {l = h ∷ t} (here e≡n-h) = h , e≡n-h , here refl
e∈n-l⇒∃è,n-è≡e×è∈l {l = h ∷ t} (there e∈n-t) with e∈n-l⇒∃è,n-è≡e×è∈l e∈n-t
... | è , n-è≡e , è∈l = è , n-è≡e , there è∈l
x⊆y⇒nx⊆ny : ∀ {ℓ} {A : Set ℓ} {x y : List (Named A)} → x ⊆ y → names x ⊆ names y
x⊆y⇒nx⊆ny {x = x} {y = y} x⊆y {e} e∈n-x with e ∈? names y
... | yes e∈n-y = e∈n-y
... | no e∉n-y with e∈n-l⇒∃è,n-è≡e×è∈l e∈n-x
... | è , e≡n-è , è∈x = ⊥-elim $ x⊆y⇒e∉y⇒e∉x x⊆y (n-e∉l⇒e∉l $ ≡-elim′ (λ z → z ∉ names y) e≡n-è e∉n-y) è∈x
nr-x⇒nr-x∩y : ∀ {ℓ} {A : Set ℓ} {x : List (Named A)} → NonRepetitiveNames x → (y : Names) → NonRepetitiveNames (filter-∈ x y)
nr-x⇒nr-x∩y {x = []} _ _ = []
nr-x⇒nr-x∩y {x = h ∷ t} (h∉t ∷ nr-t) y with y ∋! proj₁ h
... | false = nr-x⇒nr-x∩y nr-t y
... | true = x⊆y⇒e∉y⇒e∉x (x⊆y⇒nx⊆ny $ x∩y⊆x t y) h∉t ∷ nr-x⇒nr-x∩y nr-t y
e∈l⇒[e]⊆l : ∀ {ℓ} {A : Set ℓ} {e : A} {l : List A} → e ∈ l → [ e ] ⊆ l
e∈l⇒[e]⊆l e∈l (here è≡e) = ≡-elim′ (λ x → x ∈ _) (≡-sym è≡e) e∈l
e∈l⇒[e]⊆l e∈l (there ())
a∈x⇒x≋y⇒a∈y : ∀ {ℓ} {A : Set ℓ} {x y : List A} {a : A} → a ∈ x → x ≋ y → a ∈ y
a∈x⇒x≋y⇒a∈y a∈x x≋y = x⊆y≋z (e∈l⇒[e]⊆l a∈x) x≋y (here refl)
x⊆z⇒y⊆z⇒x∪y⊆z : ∀ {ℓ} {A : Set ℓ} {x y z : List A} → x ⊆ z → y ⊆ z → x ∪ y ⊆ z
x⊆z⇒y⊆z⇒x∪y⊆z {x = []} _ y⊆z = y⊆z
x⊆z⇒y⊆z⇒x∪y⊆z {x = h ∷ t} {y = y} {z = z} x⊆z y⊆z = f where
f : (h ∷ t) ∪ y ⊆ z
f {e} (here e≡h) = x⊆z $ here e≡h
f {e} (there e∈t∪y) = x⊆z⇒y⊆z⇒x∪y⊆z (x∪y⊆z⇒y⊆z [ h ] t x⊆z) y⊆z e∈t∪y
x⊆x∖y∪y : (x y : Names) → x ⊆ x ∖ y ∪ y
x⊆x∖y∪y [] _ = []⊆x _
x⊆x∖y∪y (h ∷ t) y with h ∈? y
x⊆x∖y∪y (h ∷ t) y | yes h∈y = x⊆z⇒y⊆z⇒x∪y⊆z (e∈l⇒[e]⊆l $ e∈x⇒e∈y∪x (t ∖ y) h∈y) (x⊆x∖y∪y t y)
x⊆x∖y∪y (h ∷ t) y | no _ = x∪y⊆x̀∪ỳ ([ h ] ⊆ [ h ] ∋ ≋⇒⊆ refl) (x⊆x∖y∪y t y)
e₁∈l⇒e₁∉l∖e₂⇒e₁≡e₂ : {e₁ e₂ : String} {l : Names} → e₁ ∈ l → e₁ ∉ l ∖ [ e₂ ] → e₁ ≡ e₂
e₁∈l⇒e₁∉l∖e₂⇒e₁≡e₂ {e₁ = e₁} {e₂ = e₂} {l = l} e₁∈l e₁∉l∖e₂ with e₁ ≟ e₂
... | yes e₁≡e₂ = e₁≡e₂
... | no e₁≢e₂ = ⊥-elim $ p₄ e₁∈l where
p₁ : e₁ ∉ [ e₂ ] ∪ (l ∖ [ e₂ ])
p₁ = x≢y⇒x∉l⇒x∉y∷l e₁≢e₂ e₁∉l∖e₂
p₂ : [ e₂ ] ∪ (l ∖ [ e₂ ]) ≋ (l ∖ [ e₂ ]) ∪ [ e₂ ]
p₂ = ∪-sym [ e₂ ] (l ∖ [ e₂ ])
p₃ : e₁ ∉ (l ∖ [ e₂ ]) ∪ [ e₂ ]
p₃ = p₁ ∘ ≋⇒⊆ (∪-sym (l ∖ [ e₂ ]) [ e₂ ])
p₄ : e₁ ∉ l
p₄ = x⊆y⇒e∉y⇒e∉x (x⊆x∖y∪y l [ e₂ ]) p₃
e∉x⇒x∩y≋x∩y∖e : {e : String} {x : Names} (y : Names) → e ∉ x → x ∩ y ≡ x ∩ (y ∖ [ e ])
e∉x⇒x∩y≋x∩y∖e {x = []} _ _ = refl
e∉x⇒x∩y≋x∩y∖e {e = e} {x = h ∷ t} y e∉x with h ∈? y | h ∈? (y ∖ [ e ])
... | yes h∈y | yes h∈y∖e = ≡-cong (_∷_ h) $ e∉x⇒x∩y≋x∩y∖e y $ x∉y∷l⇒x∉l e∉x
... | yes h∈y | no h∉y∖e = ⊥-elim $ e∉x e∈x where
e∈x : e ∈ h ∷ t
e∈x = here $ ≡-sym $ e₁∈l⇒e₁∉l∖e₂⇒e₁≡e₂ h∈y h∉y∖e
... | no h∉y | yes h∈y∖e = ⊥-elim $ h∉y $ x∖y⊆x y [ e ] h∈y∖e
... | no h∉y | no h∉y∖e = e∉x⇒x∩y≋x∩y∖e y $ x∉y∷l⇒x∉l e∉x
y⊆x⇒x∩y≋y : {x y : Names} → NonRepetitive y → NonRepetitive x → y ⊆ x → x ∩ y ≋ y
y⊆x⇒x∩y≋y {x = []} _ _ y⊆[] = ≡⇒≋ $ ≡-elim′ (λ y → [] ∩ y ≡ y) (≡-sym $ x⊆[]⇒x≡[] y⊆[]) refl
y⊆x⇒x∩y≋y {x = h ∷ t} {y = y} nr-y (h∉t ∷ nr-t) y⊆h∷t with h ∈? y
... | yes h∈y = ≋-trans (∪-sym [ h ] (t ∩ y)) p₄ where
p₁ : t ∩ y ≋ t ∩ (y ∖ [ h ])
p₁ = ≡⇒≋ $ e∉x⇒x∩y≋x∩y∖e y h∉t
p₂ : t ∩ (y ∖ [ h ]) ≋ y ∖ [ h ]
p₂ = y⊆x⇒x∩y≋y (nr-x∖y nr-y [ h ]) nr-t $ x⊆e∷y⇒e∉x⇒x⊆y (y⊆h∷t ∘ x∖y⊆x y [ h ]) (e∉l∖[e] h y)
p₃ : y ∖ [ h ] ∪ [ h ] ≋ y
p₃ = e∈l⇒nr-l⇒l∖e∪e≋l h∈y nr-y
p₄ : t ∩ y ∪ [ h ] ≋ y
p₄ = ≋-trans (x≋x̀⇒x∪y≋x̀∪y (≋-trans p₁ p₂) [ h ]) p₃
... | no h∉y = y⊆x⇒x∩y≋y nr-y nr-t $ x⊆e∷y⇒e∉x⇒x⊆y y⊆h∷t h∉y
x∪y∖n≡x∖n∪y∖n : ∀ {ℓ} {A : Set ℓ} (x y : List (Named A)) (n : Names) → (x ∪ y) ∖∖ n ≡ (x ∖∖ n) ∪ (y ∖∖ n)
x∪y∖n≡x∖n∪y∖n [] _ _ = refl
x∪y∖n≡x∖n∪y∖n (h ∷ t) y n with proj₁ h ∈? n
... | yes _ = x∪y∖n≡x∖n∪y∖n t y n
... | no _ = ≡-cong (_∷_ h) (x∪y∖n≡x∖n∪y∖n t y n)
n-x⊆n⇒x∖n≡[] : ∀ {ℓ} {A : Set ℓ} (x : List (Named A)) (n : Names) → names x ⊆ n → x ∖∖ n ≡ []
n-x⊆n⇒x∖n≡[] [] _ _ = refl
n-x⊆n⇒x∖n≡[] (h ∷ t) n n-x⊆n with proj₁ h ∈? n
... | yes _ = n-x⊆n⇒x∖n≡[] t n $ x∪y⊆z⇒y⊆z [ proj₁ h ] (names t) (x≋y⊆z (≡⇒≋ $ n-x∪y [ h ] t) n-x⊆n)
... | no h∉n = ⊥-elim $ h∉n $ n-x⊆n (proj₁ h ∈ proj₁ h ∷ names t ∋ here refl)
x∖x≡[] : ∀ {ℓ} {A : Set ℓ} (x : List (Named A)) → x ∖∖ names x ≡ []
x∖x≡[] x = n-x⊆n⇒x∖n≡[] x (names x) (≋⇒⊆ refl)
nr-[a] : ∀ {ℓ} {A : Set ℓ} {a : A} → NonRepetitive [ a ]
nr-[a] = (λ()) ∷ []
x≋y⇒x∖n≋y∖n : ∀ {ℓ} {A : Set ℓ} {x y : List (Named A)} → x ≋ y → (n : Names) → x ∖∖ n ≋ y ∖∖ n
x≋y⇒x∖n≋y∖n refl _ = refl
x≋y⇒x∖n≋y∖n {x = x} (perm l₁ x₁ x₂ l₂ p) n = ≋-trans p₀ $ ≋-trans (≡⇒≋ p₅) $ ≋-trans pg (≡⇒≋ $ ≡-sym g₅) where
p₀ : x ∖∖ n ≋ (l₁ ++ x₂ ∷ x₁ ∷ l₂) ∖∖ n
p₀ = x≋y⇒x∖n≋y∖n p n
p₁ : (l₁ ++ [ x₂ ] ++ [ x₁ ] ++ l₂) ∖∖ n ≡ l₁ ∖∖ n ++ ([ x₂ ] ++ [ x₁ ] ++ l₂) ∖∖ n
p₁ = x∪y∖n≡x∖n∪y∖n l₁ ([ x₂ ] ++ [ x₁ ] ++ l₂) n
p₂ : l₁ ∖∖ n ++ ([ x₂ ] ++ [ x₁ ] ++ l₂) ∖∖ n ≡ l₁ ∖∖ n ++ [ x₂ ] ∖∖ n ++ ([ x₁ ] ++ l₂) ∖∖ n
p₂ = ≡-cong (λ z → l₁ ∖∖ n ++ z) (x∪y∖n≡x∖n∪y∖n [ x₂ ] ([ x₁ ] ++ l₂) n)
p₃ : l₁ ∖∖ n ++ [ x₂ ] ∖∖ n ++ ([ x₁ ] ++ l₂) ∖∖ n ≡ l₁ ∖∖ n ++ [ x₂ ] ∖∖ n ++ [ x₁ ] ∖∖ n ++ l₂ ∖∖ n
p₃ = ≡-cong (λ z → l₁ ∖∖ n ++ [ x₂ ] ∖∖ n ++ z) (x∪y∖n≡x∖n∪y∖n [ x₁ ] l₂ n)
p₄ : l₁ ∖∖ n ++ [ x₂ ] ∖∖ n ++ [ x₁ ] ∖∖ n ++ l₂ ∖∖ n ≡ l₁ ∖∖ n ++ ([ x₂ ] ∖∖ n ++ [ x₁ ] ∖∖ n) ++ l₂ ∖∖ n
p₄ = ≡-cong (λ z → l₁ ∖∖ n ++ z) (≡-sym $ ∪-assoc ([ x₂ ] ∖∖ n) ([ x₁ ] ∖∖ n) (l₂ ∖∖ n))
p₅ : (l₁ ++ [ x₂ ] ++ [ x₁ ] ++ l₂) ∖∖ n ≡ l₁ ∖∖ n ++ ([ x₂ ] ∖∖ n ++ [ x₁ ] ∖∖ n) ++ l₂ ∖∖ n
p₅ = ≡-trans p₁ $ ≡-trans p₂ $ ≡-trans p₃ p₄
pg : l₁ ∖∖ n ++ ([ x₂ ] ∖∖ n ++ [ x₁ ] ∖∖ n) ++ l₂ ∖∖ n ≋ l₁ ∖∖ n ++ ([ x₁ ] ∖∖ n ++ [ x₂ ] ∖∖ n) ++ l₂ ∖∖ n
pg = y≋ỳ⇒x∪y≋x∪ỳ (l₁ ∖∖ n) $ x≋x̀⇒x∪y≋x̀∪y (∪-sym ([ x₂ ] ∖∖ n) ([ x₁ ] ∖∖ n)) (l₂ ∖∖ n)
g₁ : (l₁ ++ [ x₁ ] ++ [ x₂ ] ++ l₂) ∖∖ n ≡ l₁ ∖∖ n ++ ([ x₁ ] ++ [ x₂ ] ++ l₂) ∖∖ n
g₁ = x∪y∖n≡x∖n∪y∖n l₁ ([ x₁ ] ++ [ x₂ ] ++ l₂) n
g₂ : l₁ ∖∖ n ++ ([ x₁ ] ++ [ x₂ ] ++ l₂) ∖∖ n ≡ l₁ ∖∖ n ++ [ x₁ ] ∖∖ n ++ ([ x₂ ] ++ l₂) ∖∖ n
g₂ = ≡-cong (λ z → l₁ ∖∖ n ++ z) (x∪y∖n≡x∖n∪y∖n [ x₁ ] ([ x₂ ] ++ l₂) n)
g₃ : l₁ ∖∖ n ++ [ x₁ ] ∖∖ n ++ ([ x₂ ] ++ l₂) ∖∖ n ≡ l₁ ∖∖ n ++ [ x₁ ] ∖∖ n ++ [ x₂ ] ∖∖ n ++ l₂ ∖∖ n
g₃ = ≡-cong (λ z → l₁ ∖∖ n ++ [ x₁ ] ∖∖ n ++ z) (x∪y∖n≡x∖n∪y∖n [ x₂ ] l₂ n)
g₄ : l₁ ∖∖ n ++ [ x₁ ] ∖∖ n ++ [ x₂ ] ∖∖ n ++ l₂ ∖∖ n ≡ l₁ ∖∖ n ++ ([ x₁ ] ∖∖ n ++ [ x₂ ] ∖∖ n) ++ l₂ ∖∖ n
g₄ = ≡-cong (λ z → l₁ ∖∖ n ++ z) (≡-sym $ ∪-assoc ([ x₁ ] ∖∖ n) ([ x₂ ] ∖∖ n) (l₂ ∖∖ n))
g₅ : (l₁ ++ [ x₁ ] ++ [ x₂ ] ++ l₂) ∖∖ n ≡ l₁ ∖∖ n ++ ([ x₁ ] ∖∖ n ++ [ x₂ ] ∖∖ n) ++ l₂ ∖∖ n
g₅ = ≡-trans g₁ $ ≡-trans g₂ $ ≡-trans g₃ g₄
nr-x∪y⇒e∈x⇒e∈y⇒⊥ : ∀ {ℓ} {A : Set ℓ} {e : A} {x y : List A} → NonRepetitive (x ∪ y) → e ∈ x → e ∈ y → ⊥
nr-x∪y⇒e∈x⇒e∈y⇒⊥ {x = []} _ ()
nr-x∪y⇒e∈x⇒e∈y⇒⊥ {x = h ∷ t} (h∉t∪y ∷ nr-t∪y) (here e≡h) = h∉t∪y ∘ e∈x⇒e∈y∪x t ∘ ≡-elim′ (λ x → x ∈ _) e≡h
nr-x∪y⇒e∈x⇒e∈y⇒⊥ {x = h ∷ t} (h∉t∪y ∷ nr-t∪y) (there e∈t) = nr-x∪y⇒e∈x⇒e∈y⇒⊥ nr-t∪y e∈t
nr-x∪y⇒x∖y≡x : ∀ {ℓ} {A : Set ℓ} (x y : List (Named A)) → NonRepetitiveNames (x ∪ y) → y ∖∖ names x ≡ y
nr-x∪y⇒x∖y≡x x y nr-x∪y = f₀ y (≋⇒⊆ refl) where
f₀ : ∀ t → t ⊆ y → t ∖∖ names x ≡ t
f₀ [] _ = refl
f₀ (h ∷ t) h∷t⊆y with proj₁ h ∈? names x
... | yes h∈x = ⊥-elim $ nr-x∪y⇒e∈x⇒e∈y⇒⊥ (≡-elim′ NonRepetitive (n-x∪y x y) nr-x∪y) h∈x (x⊆y⇒nx⊆ny h∷t⊆y $ here refl)
... | no _ = ≡-cong (_∷_ h) (f₀ t $ x∪y⊆z⇒y⊆z [ h ] t h∷t⊆y)
t≋t₁∪t₂⇒t∖t₁≋t₂ : ∀ {ℓ} {A : Set ℓ} {t : List (Named A)} → NonRepetitiveNames t → (t₁ t₂ : List (Named A)) → t ≋ t₁ ∪ t₂ → t ∖∖ names t₁ ≋ t₂
t≋t₁∪t₂⇒t∖t₁≋t₂ {t = t} nr-t t₁ t₂ t≋t₁∪t₂ = ≋-trans p₂ (≡⇒≋ $ nr-x∪y⇒x∖y≡x t₁ t₂ $ nr-x≋y (n-x≋y t≋t₁∪t₂) nr-t) where
n-t₁ = names t₁
p₁ : t ∖∖ n-t₁ ≋ (t₁ ∖∖ n-t₁) ∪ (t₂ ∖∖ n-t₁)
p₁ = ≋-trans (x≋y⇒x∖n≋y∖n t≋t₁∪t₂ n-t₁) (≡⇒≋ $ x∪y∖n≡x∖n∪y∖n t₁ t₂ n-t₁)
p₂ : t ∖∖ n-t₁ ≋ t₂ ∖∖ n-t₁
p₂ = ≡-elim′ (λ x → t ∖∖ n-t₁ ≋ x ∪ (t₂ ∖∖ n-t₁)) (x∖x≡[] t₁) p₁
x≋x̀⇒y≋ỳ⇒x∪y≋x̀∪ỳ : ∀ {ℓ} {A : Set ℓ} {x x̀ y ỳ : List A} → x ≋ x̀ → y ≋ ỳ → x ∪ y ≋ x̀ ∪ ỳ
x≋x̀⇒y≋ỳ⇒x∪y≋x̀∪ỳ x≋x̀ (refl {y}) = x≋x̀⇒x∪y≋x̀∪y x≋x̀ y
x≋x̀⇒y≋ỳ⇒x∪y≋x̀∪ỳ {x = x} {x̀ = x̀} {y = y} {ỳ = ._} x≋x̀ (perm l₁ x₁ x₂ l₂ y≋l₁x₂x₁l₂) = ≋-trans p₁ $ ≋-trans p₂ $ ≋-trans p₃ p₄ where
p₁ : x ∪ y ≋ x̀ ∪ (l₁ ++ x₂ ∷ x₁ ∷ l₂)
p₁ = x≋x̀⇒y≋ỳ⇒x∪y≋x̀∪ỳ x≋x̀ y≋l₁x₂x₁l₂
p₂ : x̀ ∪ (l₁ ++ x₂ ∷ x₁ ∷ l₂) ≋ (x̀ ∪ l₁) ++ x₂ ∷ x₁ ∷ l₂
p₂ = ≡⇒≋ $ ≡-sym $ ∪-assoc x̀ l₁ (x₂ ∷ x₁ ∷ l₂)
p₃ : (x̀ ∪ l₁) ++ x₂ ∷ x₁ ∷ l₂ ≋ (x̀ ∪ l₁) ++ x₁ ∷ x₂ ∷ l₂
p₃ = perm (x̀ ∪ l₁) x₁ x₂ l₂ refl
p₄ : (x̀ ∪ l₁) ++ x₁ ∷ x₂ ∷ l₂ ≋ x̀ ∪ (l₁ ++ x₁ ∷ x₂ ∷ l₂)
p₄ = ≡⇒≋ $ ∪-assoc x̀ l₁ (x₁ ∷ x₂ ∷ l₂)
x∖y∪y≋y∖x∪x : ∀ {ℓ} {A : Set ℓ} (x y : List (Named A)) →
let nx = names x
ny = names y
in filter-∈ x ny ≋ filter-∈ y nx → x ∖∖ ny ∪ y ≋ y ∖∖ nx ∪ x
x∖y∪y≋y∖x∪x x y p₀ = ≋-trans p₁ $ ≋-trans p₂ p₃ where
nx = names x
ny = names y
p₁ : x ∖∖ ny ∪ y ≋ x ∖∖ ny ∪ y ∖∖ nx ∪ filter-∈ y nx
p₁ = ≋-trans (y≋ỳ⇒x∪y≋x∪ỳ (x ∖∖ ny) (t≋t∖n∪t∩n y nx)) (≡⇒≋ $ ≡-sym $ ∪-assoc (x ∖∖ ny) (y ∖∖ nx) (filter-∈ y nx))
p₂ : (x ∖∖ ny ∪ y ∖∖ nx) ∪ filter-∈ y nx ≋ (y ∖∖ nx ∪ x ∖∖ ny) ∪ filter-∈ x ny
p₂ = x≋x̀⇒y≋ỳ⇒x∪y≋x̀∪ỳ (∪-sym (x ∖∖ ny) (y ∖∖ nx)) (≋-sym p₀)
p₃ : y ∖∖ nx ∪ x ∖∖ ny ∪ filter-∈ x ny ≋ y ∖∖ nx ∪ x
p₃ = ≋-trans (≡⇒≋ $ ∪-assoc (y ∖∖ nx) (x ∖∖ ny) (filter-∈ x ny)) (≋-sym $ y≋ỳ⇒x∪y≋x∪ỳ (y ∖∖ nx) (t≋t∖n∪t∩n x ny))
names⇒named : Names → List (Named Unit)
names⇒named = mapL (λ x → x , unit)
nn-x∪y≡nn-x∪nn-y : ∀ x y → names⇒named (x ∪ y) ≡ names⇒named x ∪ names⇒named y
nn-x∪y≡nn-x∪nn-y [] y = refl
nn-x∪y≡nn-x∪nn-y (h ∷ t) y = ≡-cong (_∷_ _) (nn-x∪y≡nn-x∪nn-y t y)
nn-x≡x : ∀ x → names (names⇒named x) ≡ x
nn-x≡x [] = refl
nn-x≡x (h ∷ t) = ≡-cong (_∷_ h) (nn-x≡x t)
x≋y⇒nn-x≋nn-y : ∀ {x y} → x ≋ y → names⇒named x ≋ names⇒named y
x≋y⇒nn-x≋nn-y refl = refl
x≋y⇒nn-x≋nn-y {x = x} {y = ._} (perm l₁ x₁ x₂ l₂ x≋l₁x₂x₁l₂) = ≋-trans p₁ p₂ where
p₁ : names⇒named x ≋ names⇒named l₁ ++ (x₂ , unit) ∷ (x₁ , unit) ∷ names⇒named l₂
p₁ = ≋-trans (x≋y⇒nn-x≋nn-y x≋l₁x₂x₁l₂) (≡⇒≋ $ nn-x∪y≡nn-x∪nn-y l₁ (x₂ ∷ x₁ ∷ l₂))
p₂ : names⇒named l₁ ++ (x₂ , unit) ∷ (x₁ , unit) ∷ names⇒named l₂ ≋ names⇒named (l₁ ++ x₁ ∷ x₂ ∷ l₂)
p₂ = ≋-trans (perm (names⇒named l₁) (x₁ , unit) (x₂ , unit) (names⇒named l₂) refl) (≡⇒≋ $ ≡-sym $ nn-x∪y≡nn-x∪nn-y l₁ (x₁ ∷ x₂ ∷ l₂))
x≋y∪z⇒x∖y≋z : {x : Names} → NonRepetitive x → (y z : Names) → x ≋ y ∪ z → x ∖ y ≋ z
x≋y∪z⇒x∖y≋z {x} nr-x y z x≋y∪z = ≋-trans (≡⇒≋ $ ≡-sym $ ≡-trans p₂ p₃) (≋-trans p₁ $ ≡⇒≋ $ nn-x≡x z) where
ux = names⇒named x
uy = names⇒named y
uz = names⇒named z
ux≋uy∪uz : ux ≋ uy ∪ uz
ux≋uy∪uz = ≋-trans (x≋y⇒nn-x≋nn-y x≋y∪z) (≡⇒≋ $ nn-x∪y≡nn-x∪nn-y y z)
p₁ : names (ux ∖∖ names uy) ≋ names uz
p₁ = n-x≋y $ t≋t₁∪t₂⇒t∖t₁≋t₂ (≡-elim′ NonRepetitive (≡-sym $ nn-x≡x x) nr-x) uy uz ux≋uy∪uz
p₂ : names (ux ∖∖ names uy) ≡ names ux ∖ names uy
p₂ = n-x∖y ux (names uy)
p₃ : names ux ∖ names uy ≡ x ∖ y
p₃ = ≡-cong₂ _∖_ (nn-x≡x x) (nn-x≡x y)
h∈x⇒∃t,x≋h∷t : ∀ {ℓ} {A : Set ℓ} {h : A} {x : List A} → h ∈ x → NonRepetitive x → Σ[ t ∈ List A ] x ≋ h ∷ t
h∈x⇒∃t,x≋h∷t {h = h} .{x = x ∷ xs} (here {x = x} {xs = xs} h≡x) (x∉xs ∷ nr-xs) = xs , ≡⇒≋ (≡-cong (λ z → z ∷ xs) (≡-sym h≡x))
h∈x⇒∃t,x≋h∷t {h = h} .{x = x ∷ xs} (there {x = x} {xs = xs} h∈xs) (x∉xs ∷ nr-xs) =
let t , xs≋h∷t = ((Σ[ t ∈ List _ ] xs ≋ h ∷ t) ∋ h∈x⇒∃t,x≋h∷t h∈xs nr-xs)
p₁ : x ∷ xs ≋ x ∷ h ∷ t
p₁ = y≋ỳ⇒x∪y≋x∪ỳ [ x ] xs≋h∷t
p₂ : x ∷ h ∷ t ≋ h ∷ x ∷ t
p₂ = ≋-del-ins-l [] [ x ] h t
in x ∷ t , ≋-trans p₁ p₂
nr-x∪y⇒nr-y : ∀ {ℓ} {A : Set ℓ} (x y : List A) → NonRepetitive (x ∪ y) → NonRepetitive y
nr-x∪y⇒nr-y [] _ nr-y = nr-y
nr-x∪y⇒nr-y (h ∷ t) y (_ ∷ nr-t∪y) = nr-x∪y⇒nr-y t y nr-t∪y
x⊆y⇒∃x̀,y≋x∪x̀ : ∀ {ℓ} {A : Set ℓ} {x y : List A} → NonRepetitive x → NonRepetitive y → x ⊆ y → Σ[ x̀ ∈ List A ] y ≋ x ∪ x̀
x⊆y⇒∃x̀,y≋x∪x̀ {x = []} {y = y} _ _ _ = y , refl
x⊆y⇒∃x̀,y≋x∪x̀ {x = h ∷ t} {y = y} (h∉t ∷ nr-t) nr-y h∷t⊆y =
let ỳ , y≋h∷ỳ = h∈x⇒∃t,x≋h∷t (h∷t⊆y (h ∈ h ∷ t ∋ here refl)) nr-y
p₁ : t ⊆ ỳ
p₁ = x⊆e∷y⇒e∉x⇒x⊆y (x⊆y≋z (x∪y⊆z⇒y⊆z [ h ] t h∷t⊆y) y≋h∷ỳ) h∉t
nr-ỳ = nr-x∪y⇒nr-y [ h ] ỳ $ nr-x≋y y≋h∷ỳ nr-y
t̀ , ỳ≋t∪t̀ = x⊆y⇒∃x̀,y≋x∪x̀ nr-t nr-ỳ p₁
p₂ : h ∷ ỳ ≋ (h ∷ t) ∪ t̀
p₂ = y≋ỳ⇒x∪y≋x∪ỳ [ h ] ỳ≋t∪t̀
in t̀ , ≋-trans y≋h∷ỳ p₂
t₁⊆t₂⇒t₂≋t₁∪t₂∖nt₁ : ∀ {ℓ} {A : Set ℓ} {t₁ t₂ : List (Named A)} → NonRepetitiveNames t₁ → NonRepetitiveNames t₂ → t₁ ⊆ t₂ → t₂ ≋ t₁ ∪ t₂ ∖∖ names t₁
t₁⊆t₂⇒t₂≋t₁∪t₂∖nt₁ {t₁ = t₁} {t₂ = t₂} nr-nt₁ nr-nt₂ t₁⊆t₂ = ≋-trans p₁ $ y≋ỳ⇒x∪y≋x∪ỳ t₁ p₆ where
n-t₁ = names t₁
nr-t₁ = nr-names⇒nr nr-nt₁
nr-t₂ = nr-names⇒nr nr-nt₂
t̀₁,t₁∪t̀₁≋t₂ = x⊆y⇒∃x̀,y≋x∪x̀ nr-t₁ nr-t₂ t₁⊆t₂
t̀₁ = proj₁ t̀₁,t₁∪t̀₁≋t₂
p₁ : t₂ ≋ t₁ ∪ t̀₁
p₁ = proj₂ t̀₁,t₁∪t̀₁≋t₂
p₂ : t₂ ∖∖ n-t₁ ≋ (t₁ ∪ t̀₁) ∖∖ n-t₁
p₂ = x≋y⇒x∖n≋y∖n p₁ n-t₁
p₃ : (t₁ ∪ t̀₁) ∖∖ n-t₁ ≡ t₁ ∖∖ n-t₁ ∪ t̀₁ ∖∖ n-t₁
p₃ = x∪y∖n≡x∖n∪y∖n t₁ t̀₁ n-t₁
p₄ : t₁ ∖∖ n-t₁ ∪ t̀₁ ∖∖ n-t₁ ≡ t̀₁ ∖∖ n-t₁
p₄ = ≡-cong (λ x → x ∪ t̀₁ ∖∖ n-t₁) (x∖x≡[] t₁)
p₅ : t̀₁ ∖∖ n-t₁ ≡ t̀₁
p₅ = nr-x∪y⇒x∖y≡x t₁ t̀₁ $ nr-x≋y (n-x≋y p₁) nr-nt₂
p₆ : t̀₁ ≋ t₂ ∖∖ n-t₁
p₆ = ≋-sym $ ≋-trans p₂ $ ≡⇒≋ $ ≡-trans p₃ $ ≡-trans p₄ p₅
t₁⊆t₂⇒t₁≋f∈-t₂-nt₁ : ∀ {ℓ} {A : Set ℓ} {t₁ t₂ : List (Named A)} → NonRepetitiveNames t₁ → NonRepetitiveNames t₂ → t₁ ⊆ t₂ → t₁ ≋ filter-∈ t₂ (names t₁)
t₁⊆t₂⇒t₁≋f∈-t₂-nt₁ {t₁ = t₁} {t₂ = t₂} nr-t₁ nr-t₂ t₁⊆t₂ = ≋-trans (≋-sym p₃) p₄ where
nt₁ = names t₁
p₁ : t₂ ≋ t₂ ∖∖ nt₁ ∪ t₁
p₁ = ≋-trans (t₁⊆t₂⇒t₂≋t₁∪t₂∖nt₁ nr-t₁ nr-t₂ t₁⊆t₂) (∪-sym t₁ (t₂ ∖∖ nt₁))
p₂ : t₂ ≋ t₂ ∖∖ nt₁ ∪ filter-∈ t₂ nt₁
p₂ = t≋t∖n∪t∩n t₂ nt₁
p₃ : t₂ ∖∖ names (t₂ ∖∖ nt₁) ≋ t₁
p₃ = t≋t₁∪t₂⇒t∖t₁≋t₂ nr-t₂ (t₂ ∖∖ nt₁) t₁ p₁
p₄ : t₂ ∖∖ names (t₂ ∖∖ nt₁) ≋ filter-∈ t₂ nt₁
p₄ = t≋t₁∪t₂⇒t∖t₁≋t₂ nr-t₂ (t₂ ∖∖ nt₁) (filter-∈ t₂ nt₁) p₂
-- /lemmas
-- assertions
infix 4 _s-≢!_
_s-≢!_ : String → String → Set
x s-≢! y with x ≟ y
... | yes _ = ⊥
... | no _ = ⊤
s-≢!⇒≢? : ∀ {x y} → x s-≢! y → x ≢ y
s-≢!⇒≢? {x} {y} x≢!y with x ≟ y
s-≢!⇒≢? () | yes _
s-≢!⇒≢? _ | no p = p
s-NonRepetitive? : (n : Names) → Dec (NonRepetitive n)
s-NonRepetitive? [] = yes []
s-NonRepetitive? (h ∷ t) with h ∈? t | s-NonRepetitive? t
... | no h∉t | yes nr-t = yes (h∉t ∷ nr-t)
... | yes h∈t | _ = no f where
f : NonRepetitive (_ ∷ _) → _
f (h∉t ∷ _) = h∉t h∈t
... | _ | no ¬nr-t = no f where
f : NonRepetitive (_ ∷ _) → _
f (_ ∷ nr-t) = ¬nr-t nr-t
s-NonRepetitive! : Names → Set
s-NonRepetitive! n with s-NonRepetitive? n
... | yes _ = ⊤
... | no _ = ⊥
NonRepetitiveNames! : ∀ {ℓ} {A : Set ℓ} → List (Named A) → Set
NonRepetitiveNames! = s-NonRepetitive! ∘ names
s-nr!⇒nr : {n : Names} → s-NonRepetitive! n → NonRepetitive n
s-nr!⇒nr {n = n} _ with s-NonRepetitive? n
s-nr!⇒nr _ | yes p = p
s-nr!⇒nr () | no _
-- /assertions
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Main where
import qualified Data.Foldable as Foldable
-- vector
import Data.Vector (Vector)
import qualified Data.Vector as Vector
-- Matrix
import Data.Matrix (Matrix)
import qualified Data.Matrix as Matrix
-- HMatrix
import qualified Numeric.LinearAlgebra.Data as HMatrix
import qualified Numeric.LinearAlgebra.HMatrix as HMatrix
-- bytestring
import Data.ByteString.Lazy (ByteString)
import qualified Data.ByteString.Lazy as ByteString
-- cassava
import Data.Csv
( DefaultOrdered(headerOrder)
, FromField(parseField)
, FromNamedRecord(parseNamedRecord)
, Header
, ToField(toField)
, ToNamedRecord(toNamedRecord)
, (.:)
, (.=)
)
import qualified Data.Csv as Cassava
-- text
import Data.Text (Text)
import qualified Data.Text.Encoding as Text
-- Exception
import Control.Exception
-- base
import qualified Control.Monad as Monad
import qualified System.Exit as Exit
import qualified Debug.Trace as Trace
data ComponentData =
ComponentData {
componentType :: ComponentType,
nodeK :: Int,
nodeM :: Int,
magnitude :: Double,
param1 :: Double,
param2 :: Double,
plot :: Int
}
deriving (Eq, Show)
data SimulationData =
SimulationData {
nodes :: Int,
voltageSources :: Int,
stepSize :: Double,
tmax :: Double
}
deriving (Eq, Show)
data ComponentType = Resistor | Capacitor | Inductor | EAC | EDC | Other Text deriving (Eq, Show)
type SimulationResults = (Vector Double, Matrix Double)
instance FromNamedRecord SimulationData where
parseNamedRecord m =
SimulationData
<$> m .: "Number of Nodes"
<*> m .: "Number of Voltages Sources"
<*> m .: "Step Size"
<*> m .: "Maximum time for simulation"
instance FromNamedRecord ComponentData where
parseNamedRecord m =
ComponentData
<$> m .: "Element Type"
<*> m .: "Node K"
<*> m .: "Node M"
<*> m .: "Value"
<*> m .: "Source param 1"
<*> m .: "Source param 2"
<*> m .: "Plot"
instance FromField ComponentType where
parseField "R" =
pure Resistor
parseField "L" =
pure Inductor
parseField "C" =
pure Capacitor
parseField "EDC" =
pure EDC
parseField "EAC" =
pure EAC
parseField otherType =
Other <$> parseField otherType
decodeItems :: ByteString -> Either String (Vector ComponentData)
decodeItems =
fmap snd . Cassava.decodeByName
decodeItemsFromFile :: FilePath -> IO (Either String (Vector ComponentData))
decodeItemsFromFile filePath =
catchShowIO (ByteString.readFile filePath)
>>= return . either Left decodeItems
decodeSimulation :: ByteString -> Either String (Vector SimulationData)
decodeSimulation =
fmap snd . Cassava.decodeByName
decodeSimulationFromFile :: FilePath -> IO (Either String (Vector SimulationData))
decodeSimulationFromFile filePath =
catchShowIO (ByteString.readFile filePath)
>>= return . either Left decodeSimulation
getSingleSimulationLine :: Vector SimulationData -> SimulationData
getSingleSimulationLine =
Vector.head
nhComponents :: [ComponentData] -> [ComponentData]
nhComponents =
filter (\r -> (componentType r == Capacitor) || (componentType r == Inductor))
filterEnergyStorageComponent :: Vector ComponentData -> Vector ComponentData
filterEnergyStorageComponent =
Vector.filter (\r -> (componentType r == Capacitor) || (componentType r == Inductor))
nh :: Vector ComponentData -> Int
nh components =
length $ filterEnergyStorageComponent components
-- filter ((== Zaal) . reviewLocation) reviews
filterSources :: Vector ComponentData -> Vector ComponentData
filterSources =
Vector.filter (\r -> (componentType r == EDC) || (componentType r == EAC))
condutance :: ComponentData -> Double -> Double
condutance component dt =
case componentType component of
Resistor -> 1.0 / (magnitude component)
Capacitor -> (magnitude component) * 0.000001 * 2 / dt
Inductor -> dt / (2 * 0.001 * (magnitude component))
_ -> 0.0
gkm :: Vector ComponentData -> Double -> Vector Double
gkm components dt =
Vector.map (\c -> condutance c dt) components
-- Matrix.colVector (Vector.map (\c -> condutance c dt) components)
-- Matrix.fromList (length components) 1 (Vector.toList (Vector.map (\c -> condutance c dt) components))
buildCompactGMatrix :: Double -> [ComponentData] -> Matrix Double -> Matrix Double
buildCompactGMatrix dt [] buffer = buffer
buildCompactGMatrix dt (component:cs) buffer =
case (nodeK component, nodeM component) of (0, m) -> buildCompactGMatrix dt cs (Matrix.setElem (Matrix.getElem m m buffer + condutance component dt) (m, m) buffer)
(k, 0) -> buildCompactGMatrix dt cs (Matrix.setElem (Matrix.getElem k k buffer + condutance component dt) (k, k) buffer)
(k, m) -> buildCompactGMatrix dt cs (Matrix.setElem (Matrix.getElem k k buffer + condutance component dt) (k, k) (Matrix.setElem (Matrix.getElem m m buffer + condutance component dt) (m, m) (Matrix.setElem (Matrix.getElem k m buffer - condutance component dt) (k, m) (Matrix.setElem (Matrix.getElem m k buffer - condutance component dt) (m, k) buffer))))
(_, _) -> buildCompactGMatrix dt cs buffer
buildGMatrixFromVector :: SimulationData -> Vector ComponentData -> Matrix Double
buildGMatrixFromVector simulation components =
buildCompactGMatrix (stepSize simulation) (Vector.toList components) (Matrix.zero (nodes simulation) (nodes simulation))
buildIhVector :: [ComponentData] -> Double -> Int -> [Double] -> [Double] -> Matrix Double -> Vector Double
buildIhVector [] _ _ _ ihnew _ = Vector.fromList ihnew
buildIhVector (component:cs) dt n (hold:ihold) ihnew vMatrix =
case (componentType component, nodeK component, nodeM component) of (Inductor, 0, m) -> buildIhVector cs dt n ihold (ihnew ++ [(2*(condutance component dt)*(Matrix.getElem m n vMatrix) + hold)]) vMatrix
(Inductor, k, 0) -> buildIhVector cs dt n ihold (ihnew ++ [(-2*(condutance component dt)*(Matrix.getElem k n vMatrix) + hold)]) vMatrix
(Inductor, k, m) -> buildIhVector cs dt n ihold (ihnew ++ [(-2*(condutance component dt)*((Matrix.getElem k n vMatrix) - (Matrix.getElem m n vMatrix)) + hold)]) vMatrix
(Capacitor, 0, m) -> buildIhVector cs dt n ihold (ihnew ++ [(-2*(condutance component dt)*(Matrix.getElem m n vMatrix) - hold)]) vMatrix
(Capacitor, k, 0) -> buildIhVector cs dt n ihold (ihnew ++ [(2*(condutance component dt)*(Matrix.getElem k n vMatrix) - hold)]) vMatrix
(Capacitor, k, m) -> buildIhVector cs dt n ihold (ihnew ++ [(2*(condutance component dt)*((Matrix.getElem k n vMatrix) - (Matrix.getElem m n vMatrix)) - hold)]) vMatrix
(_, _, _) -> buildIhVector cs dt n ihold ihnew vMatrix
buildVBVector :: [ComponentData] -> Double -> [Double] -> Vector Double
buildVBVector [] _ buffer = Vector.fromList buffer
buildVBVector (c:components) time buffer =
case (componentType c) of EDC -> buildVBVector components time ((magnitude c) : buffer)
EAC -> buildVBVector components time (((magnitude c * cos (2 * pi * param2 c * time + (param1 c * (pi/180))))) : buffer)
_ -> buildVBVector components time buffer
buildIVector :: [ComponentData] -> [Double] -> Vector Double -> Vector Double
buildIVector [] _ iVector = iVector
buildIVector (component:cs) (ihEl:ih) iVector =
case (componentType component, nodeK component, nodeM component) of (Inductor, k, 0) -> buildIVector cs ih (iVector Vector.// [((k - 1), ((iVector Vector.! (k-1)) + ihEl))])
(Inductor, 0, m) -> buildIVector cs ih (iVector Vector.// [((m - 1), ((iVector Vector.! (m-1)) - ihEl))])
(Inductor, k, m) -> buildIVector cs ih (iVector Vector.// [((m - 1), ((iVector Vector.! (m-1)) - ihEl)), ((k-1), ((iVector Vector.! (k-1)) + ihEl))])
(Capacitor, k, 0) -> buildIVector cs ih (iVector Vector.// [((k - 1), ((iVector Vector.! (k-1)) + ihEl))])
(Capacitor, 0, m) -> buildIVector cs ih (iVector Vector.// [((m - 1), ((iVector Vector.! (m-1)) - ihEl))])
(Capacitor, k, m) -> buildIVector cs ih (iVector Vector.// [((m - 1), ((iVector Vector.! (m-1)) - ihEl)), ((k-1), ((iVector Vector.! (k-1)) + ihEl))])
(_, _, _) -> buildIVector cs ih iVector
thtaControl :: Int -> Double -> Vector Double -> Vector Double -> SimulationData -> (Int, Vector Double, Double)
thtaControl thtactl time ihnew ih simulation
| thtactl <= 0 = (thtactl, ihnew, (stepSize simulation + time))
| thtactl < 3 = (thtactl + 1, (Vector.map (\i -> i/2) $ Vector.zipWith (+) ih ihnew), (time + (stepSize simulation/2)))
| otherwise = (0, ihnew, (stepSize simulation + time))
fromHMatrixTransformer :: HMatrix.Matrix Double -> Matrix Double
fromHMatrixTransformer matrix =
Matrix.fromLists $ HMatrix.toLists matrix
toHMatrixTransformer :: Matrix Double -> HMatrix.Matrix Double
toHMatrixTransformer matrix =
HMatrix.fromLists $ Matrix.toLists matrix
fromHMatrixVectorTransformer :: HMatrix.Vector Double -> Vector Double
fromHMatrixVectorTransformer vec =
Vector.fromList $ HMatrix.toList vec
toHMatrixVectorTransformer :: Vector Double -> HMatrix.Vector Double
toHMatrixVectorTransformer vec =
HMatrix.fromList $ Vector.toList vec
solver :: HMatrix.Vector Double -> HMatrix.Matrix Double -> HMatrix.Matrix Double -> HMatrix.Matrix Double -> HMatrix.Matrix Double -> HMatrix.Vector Double -> SimulationData -> (Vector Double, Vector Double)
solver iVector gaa gab gba gbb vb simulation =
let ia = HMatrix.subVector 0 ((nodes simulation) - (voltageSources simulation)) iVector
rhsa = ia - (gab HMatrix.#> vb)
va = gaa HMatrix.<\> rhsa
ib = (gba HMatrix.#> va) + (gbb HMatrix.#> vb)
iVec = HMatrix.vjoin [ia, ib]
vVec = HMatrix.vjoin [va, vb]
in
((fromHMatrixVectorTransformer iVec), (fromHMatrixVectorTransformer vVec))
thtaSimulationStep :: [ComponentData] -> Matrix Double -> SimulationData -> Int -> Int -> Double -> Vector Double -> Matrix Double -> Vector Double -> Vector Double -> SimulationResults
thtaSimulationStep _ _ _ _ 1 _ _ vMatrix _ iVector = (iVector, vMatrix)
thtaSimulationStep components condutances simulation thtactl n time ih vMatrix vbVector iVector =
let (gaa, gab, gba, gbb) = Matrix.splitBlocks (nodes simulation - voltageSources simulation) (nodes simulation - voltageSources simulation) condutances
ihBuffer = buildIhVector (nhComponents components) (stepSize simulation) n (Vector.toList ih) [] vMatrix
(thta, ihThta, timeThta) = thtaControl thtactl time ihBuffer ih simulation
vbVec = buildVBVector components timeThta []
iVec = buildIVector (nhComponents components) (Vector.toList ihThta) (Vector.replicate (nodes simulation) 0)
-- (iVecCalc, vVec) = Trace.trace ("Solver = \n" ++ show (solver (toHMatrixVectorTransformer iVec) (toHMatrixTransformer gaa) (toHMatrixTransformer gab) (toHMatrixTransformer gba) (toHMatrixTransformer gbb) (toHMatrixVectorTransformer vbVec) simulation)) solver (toHMatrixVectorTransformer iVec) (toHMatrixTransformer gaa) (toHMatrixTransformer gab) (toHMatrixTransformer gba) (toHMatrixTransformer gbb) (toHMatrixVectorTransformer vbVec) simulation
(iVecCalc, vVec) = solver (toHMatrixVectorTransformer iVec) (toHMatrixTransformer gaa) (toHMatrixTransformer gab) (toHMatrixTransformer gba) (toHMatrixTransformer gbb) (toHMatrixVectorTransformer vbVec) simulation
vMatr = Matrix.mapCol (\r _ -> vVec Vector.! (r - 1)) (n-1) vMatrix
in
thtaSimulationStep components condutances simulation thta (n-1) timeThta ihThta vMatr vbVec iVecCalc
thtaSimulation :: Vector ComponentData -> SimulationData -> SimulationResults
thtaSimulation components simulation =
thtaSimulationStep (Vector.toList components) (buildGMatrixFromVector simulation components) simulation 1 (npoints simulation) 0.0 (Vector.replicate (nh components) 0) (Matrix.zero (nodes simulation) (npoints simulation)) (Vector.replicate (voltageSources simulation) 0) (Vector.replicate (nodes simulation) 0)
npoints :: SimulationData -> Int
npoints sim =
round ((tmax sim)/(stepSize sim)) + 1
catchShowIO :: IO a -> IO (Either String a)
catchShowIO action =
fmap Right action
`catch` handleIOException
where
handleIOException :: IOException -> IO (Either String a)
handleIOException =
return . Left . show
main :: IO ()
main = do
eitherSimulation <-
fmap getSingleSimulationLine
<$> decodeSimulationFromFile "data/simulation.csv"
case eitherSimulation of
Left reason ->
Exit.die reason
Right simulation -> do
components_list <- decodeItemsFromFile "data/components.csv"
case components_list of
Left reason -> Exit.die reason
Right components -> do
let gmt = buildGMatrixFromVector simulation components
putStr "GMatrix: \n"
print (gmt)
let results = thtaSimulation components simulation
putStr "Simulation: \n"
print (results)
|
On August 10 , 2011 , against the Boston Red Sox , Nathan became the Twins all @-@ time saves leader with 255 , passing Rick Aguilera .
|
/-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
Theory of topological spaces.
Parts of the formalization is based on the books:
N. Bourbaki: General Topology
I. M. James: Topologies and Uniformities
A major difference is that this formalization is heavily based on the filter library.
-/
import order.filter data.set.countable tactic
open set filter lattice classical
local attribute [instance] prop_decidable
universes u v w
structure topological_space (α : Type u) :=
(is_open : set α → Prop)
(is_open_univ : is_open univ)
(is_open_inter : ∀s t, is_open s → is_open t → is_open (s ∩ t))
(is_open_sUnion : ∀s, (∀t∈s, is_open t) → is_open (⋃₀ s))
attribute [class] topological_space
section topological_space
variables {α : Type u} {β : Type v} {ι : Sort w} {a a₁ a₂ : α} {s s₁ s₂ : set α} {p p₁ p₂ : α → Prop}
lemma topological_space_eq : ∀ {f g : topological_space α}, f.is_open = g.is_open → f = g
| ⟨a, _, _, _⟩ ⟨b, _, _, _⟩ rfl := rfl
section
variables [t : topological_space α]
include t
/-- `is_open s` means that `s` is open in the ambient topological space on `α` -/
def is_open (s : set α) : Prop := topological_space.is_open t s
@[simp]
lemma is_open_univ : is_open (univ : set α) := topological_space.is_open_univ t
lemma is_open_inter (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∩ s₂) :=
topological_space.is_open_inter t s₁ s₂ h₁ h₂
lemma is_open_sUnion {s : set (set α)} (h : ∀t ∈ s, is_open t) : is_open (⋃₀ s) :=
topological_space.is_open_sUnion t s h
end
lemma is_open_fold {s : set α} {t : topological_space α} : t.is_open s = @is_open α t s :=
rfl
variables [topological_space α]
lemma is_open_union (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∪ s₂) :=
have (⋃₀ {s₁, s₂}) = (s₁ ∪ s₂), by simp [union_comm],
this ▸ is_open_sUnion $ show ∀(t : set α), t ∈ ({s₁, s₂} : set (set α)) → is_open t,
by finish
lemma is_open_Union {f : ι → set α} (h : ∀i, is_open (f i)) : is_open (⋃i, f i) :=
is_open_sUnion $ assume t ⟨i, (heq : t = f i)⟩, heq.symm ▸ h i
lemma is_open_bUnion {s : set β} {f : β → set α} (h : ∀i∈s, is_open (f i)) :
is_open (⋃i∈s, f i) :=
is_open_Union $ assume i, is_open_Union $ assume hi, h i hi
@[simp] lemma is_open_empty : is_open (∅ : set α) :=
have is_open (⋃₀ ∅ : set α), from is_open_sUnion (assume a, false.elim),
by simp at this; assumption
lemma is_open_sInter {s : set (set α)} (hs : finite s) : (∀t ∈ s, is_open t) → is_open (⋂₀ s) :=
finite.induction_on hs (by simp) $ λ a s has hs ih h, begin
suffices : is_open (a ∩ ⋂₀ s), { simpa },
exact is_open_inter (h _ $ mem_insert _ _) (ih $ assume t ht, h _ $ mem_insert_of_mem _ ht)
end
lemma is_open_bInter {s : set β} {f : β → set α} (hs : finite s) :
(∀i∈s, is_open (f i)) → is_open (⋂i∈s, f i) :=
finite.induction_on hs
(by simp)
(by simp [or_imp_distrib, _root_.is_open_inter, forall_and_distrib] {contextual := tt})
lemma is_open_const {p : Prop} : is_open {a : α | p} :=
by_cases
(assume : p, begin simp [*]; exact is_open_univ end)
(assume : ¬ p, begin simp [*]; exact is_open_empty end)
lemma is_open_and : is_open {a | p₁ a} → is_open {a | p₂ a} → is_open {a | p₁ a ∧ p₂ a} :=
is_open_inter
/-- A set is closed if its complement is open -/
def is_closed (s : set α) : Prop := is_open (-s)
@[simp] lemma is_closed_empty : is_closed (∅ : set α) := by simp [is_closed]
@[simp] lemma is_closed_univ : is_closed (univ : set α) := by simp [is_closed]
lemma is_closed_union : is_closed s₁ → is_closed s₂ → is_closed (s₁ ∪ s₂) :=
by simp [is_closed]; exact is_open_inter
lemma is_closed_sInter {s : set (set α)} : (∀t ∈ s, is_closed t) → is_closed (⋂₀ s) :=
by simp [is_closed, compl_sInter]; exact assume h, is_open_Union $ assume t, is_open_Union $ assume ht, h t ht
lemma is_closed_Inter {f : ι → set α} (h : ∀i, is_closed (f i)) : is_closed (⋂i, f i ) :=
is_closed_sInter $ assume t ⟨i, (heq : t = f i)⟩, heq.symm ▸ h i
@[simp] lemma is_open_compl_iff {s : set α} : is_open (-s) ↔ is_closed s := iff.rfl
@[simp] lemma is_closed_compl_iff {s : set α} : is_closed (-s) ↔ is_open s :=
by rw [←is_open_compl_iff, compl_compl]
lemma is_open_diff {s t : set α} (h₁ : is_open s) (h₂ : is_closed t) : is_open (s \ t) :=
is_open_inter h₁ $ is_open_compl_iff.mpr h₂
lemma is_closed_inter (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (s₁ ∩ s₂) :=
by rw [is_closed, compl_inter]; exact is_open_union h₁ h₂
lemma is_closed_Union {s : set β} {f : β → set α} (hs : finite s) :
(∀i∈s, is_closed (f i)) → is_closed (⋃i∈s, f i) :=
finite.induction_on hs
(by simp)
(by simp [or_imp_distrib, is_closed_union, forall_and_distrib] {contextual := tt})
lemma is_closed_imp [topological_space α] {p q : α → Prop}
(hp : is_open {x | p x}) (hq : is_closed {x | q x}) : is_closed {x | p x → q x} :=
have {x | p x → q x} = (- {x | p x}) ∪ {x | q x}, from set.ext $ by finish,
by rw [this]; exact is_closed_union (is_closed_compl_iff.mpr hp) hq
lemma is_open_neg : is_closed {a | p a} → is_open {a | ¬ p a} :=
is_open_compl_iff.mpr
/-- The interior of a set `s` is the largest open subset of `s`. -/
def interior (s : set α) : set α := ⋃₀ {t | is_open t ∧ t ⊆ s}
lemma mem_interior {s : set α} {x : α} :
x ∈ interior s ↔ ∃ t ⊆ s, is_open t ∧ x ∈ t :=
by simp [interior, and_comm, and.left_comm]
@[simp] lemma is_open_interior {s : set α} : is_open (interior s) :=
is_open_sUnion $ assume t ⟨h₁, h₂⟩, h₁
lemma interior_subset {s : set α} : interior s ⊆ s :=
sUnion_subset $ assume t ⟨h₁, h₂⟩, h₂
lemma interior_maximal {s t : set α} (h₁ : t ⊆ s) (h₂ : is_open t) : t ⊆ interior s :=
subset_sUnion_of_mem ⟨h₂, h₁⟩
lemma interior_eq_of_open {s : set α} (h : is_open s) : interior s = s :=
subset.antisymm interior_subset (interior_maximal (subset.refl s) h)
lemma interior_eq_iff_open {s : set α} : interior s = s ↔ is_open s :=
⟨assume h, h ▸ is_open_interior, interior_eq_of_open⟩
lemma subset_interior_iff_open {s : set α} : s ⊆ interior s ↔ is_open s :=
by simp [interior_eq_iff_open.symm, subset.antisymm_iff, interior_subset]
lemma subset_interior_iff_subset_of_open {s t : set α} (h₁ : is_open s) :
s ⊆ interior t ↔ s ⊆ t :=
⟨assume h, subset.trans h interior_subset, assume h₂, interior_maximal h₂ h₁⟩
lemma interior_mono {s t : set α} (h : s ⊆ t) : interior s ⊆ interior t :=
interior_maximal (subset.trans interior_subset h) is_open_interior
@[simp] lemma interior_empty : interior (∅ : set α) = ∅ :=
interior_eq_of_open is_open_empty
@[simp] lemma interior_univ : interior (univ : set α) = univ :=
interior_eq_of_open is_open_univ
@[simp] lemma interior_interior {s : set α} : interior (interior s) = interior s :=
interior_eq_of_open is_open_interior
@[simp] lemma interior_inter {s t : set α} : interior (s ∩ t) = interior s ∩ interior t :=
subset.antisymm
(subset_inter (interior_mono $ inter_subset_left s t) (interior_mono $ inter_subset_right s t))
(interior_maximal (inter_subset_inter interior_subset interior_subset) $ by simp [is_open_inter])
lemma interior_union_is_closed_of_interior_empty {s t : set α} (h₁ : is_closed s) (h₂ : interior t = ∅) :
interior (s ∪ t) = interior s :=
have interior (s ∪ t) ⊆ s, from
assume x ⟨u, ⟨(hu₁ : is_open u), (hu₂ : u ⊆ s ∪ t)⟩, (hx₁ : x ∈ u)⟩,
classical.by_contradiction $ assume hx₂ : x ∉ s,
have u \ s ⊆ t,
from assume x ⟨h₁, h₂⟩, or.resolve_left (hu₂ h₁) h₂,
have u \ s ⊆ interior t,
by simp [subset_interior_iff_subset_of_open, this, is_open_diff hu₁ h₁],
have u \ s ⊆ ∅,
by rw [h₂] at this; assumption,
this ⟨hx₁, hx₂⟩,
subset.antisymm
(interior_maximal this is_open_interior)
(interior_mono $ subset_union_left _ _)
lemma is_open_iff_forall_mem_open : is_open s ↔ ∀ x ∈ s, ∃ t ⊆ s, is_open t ∧ x ∈ t :=
by rw ← subset_interior_iff_open; simp [subset_def, mem_interior]
/-- The closure of `s` is the smallest closed set containing `s`. -/
def closure (s : set α) : set α := ⋂₀ {t | is_closed t ∧ s ⊆ t}
@[simp] lemma is_closed_closure {s : set α} : is_closed (closure s) :=
is_closed_sInter $ assume t ⟨h₁, h₂⟩, h₁
lemma subset_closure {s : set α} : s ⊆ closure s :=
subset_sInter $ assume t ⟨h₁, h₂⟩, h₂
lemma closure_minimal {s t : set α} (h₁ : s ⊆ t) (h₂ : is_closed t) : closure s ⊆ t :=
sInter_subset_of_mem ⟨h₂, h₁⟩
lemma closure_eq_of_is_closed {s : set α} (h : is_closed s) : closure s = s :=
subset.antisymm (closure_minimal (subset.refl s) h) subset_closure
lemma closure_eq_iff_is_closed {s : set α} : closure s = s ↔ is_closed s :=
⟨assume h, h ▸ is_closed_closure, closure_eq_of_is_closed⟩
lemma closure_subset_iff_subset_of_is_closed {s t : set α} (h₁ : is_closed t) :
closure s ⊆ t ↔ s ⊆ t :=
⟨subset.trans subset_closure, assume h, closure_minimal h h₁⟩
lemma closure_mono {s t : set α} (h : s ⊆ t) : closure s ⊆ closure t :=
closure_minimal (subset.trans h subset_closure) is_closed_closure
@[simp] lemma closure_empty : closure (∅ : set α) = ∅ :=
closure_eq_of_is_closed is_closed_empty
lemma closure_empty_iff (s : set α) : closure s = ∅ ↔ s = ∅ :=
begin
split ; intro h,
{ rw set.eq_empty_iff_forall_not_mem,
intros x H,
simpa [h] using subset_closure H },
{ exact (eq.symm h) ▸ closure_empty },
end
@[simp] lemma closure_univ : closure (univ : set α) = univ :=
closure_eq_of_is_closed is_closed_univ
@[simp] lemma closure_closure {s : set α} : closure (closure s) = closure s :=
closure_eq_of_is_closed is_closed_closure
@[simp] lemma closure_union {s t : set α} : closure (s ∪ t) = closure s ∪ closure t :=
subset.antisymm
(closure_minimal (union_subset_union subset_closure subset_closure) $ by simp [is_closed_union])
(union_subset (closure_mono $ subset_union_left _ _) (closure_mono $ subset_union_right _ _))
lemma interior_subset_closure {s : set α} : interior s ⊆ closure s :=
subset.trans interior_subset subset_closure
lemma closure_eq_compl_interior_compl {s : set α} : closure s = - interior (- s) :=
begin
simp [interior, closure],
rw [compl_sUnion, compl_image_set_of],
simp [compl_subset_compl]
end
@[simp] lemma interior_compl_eq {s : set α} : interior (- s) = - closure s :=
by simp [closure_eq_compl_interior_compl]
@[simp] lemma closure_compl_eq {s : set α} : closure (- s) = - interior s :=
by simp [closure_eq_compl_interior_compl]
lemma closure_compl {s : set α} : closure (-s) = - interior s :=
subset.antisymm
(by simp [closure_subset_iff_subset_of_is_closed, compl_subset_compl, subset.refl])
begin
rw [compl_subset_comm, subset_interior_iff_subset_of_open, compl_subset_comm],
exact subset_closure,
exact is_open_compl_iff.mpr is_closed_closure
end
lemma interior_compl {s : set α} : interior (-s) = - closure s :=
calc interior (- s) = - - interior (- s) : by simp
... = - closure (- (- s)) : by rw [closure_compl]
... = - closure s : by simp
theorem mem_closure_iff {s : set α} {a : α} : a ∈ closure s ↔ ∀ o, is_open o → a ∈ o → o ∩ s ≠ ∅ :=
⟨λ h o oo ao os,
have s ⊆ -o, from λ x xs xo, @ne_empty_of_mem α (o∩s) x ⟨xo, xs⟩ os,
closure_minimal this (is_closed_compl_iff.2 oo) h ao,
λ H c ⟨h₁, h₂⟩, classical.by_contradiction $ λ nc,
let ⟨x, hc, hs⟩ := exists_mem_of_ne_empty (H _ h₁ nc) in hc (h₂ hs)⟩
lemma dense_iff_inter_open {s : set α} : closure s = univ ↔ ∀ U, is_open U → U ≠ ∅ → U ∩ s ≠ ∅ :=
begin
split ; intro h,
{ intros U U_op U_ne,
cases exists_mem_of_ne_empty U_ne with x x_in,
exact mem_closure_iff.1 (by simp[h]) U U_op x_in },
{ ext x,
suffices : x ∈ closure s, by simp [this],
rw mem_closure_iff,
intros U U_op x_in,
exact h U U_op (ne_empty_of_mem x_in) },
end
/-- The frontier of a set is the set of points between the closure and interior. -/
def frontier (s : set α) : set α := closure s \ interior s
lemma frontier_eq_closure_inter_closure {s : set α} :
frontier s = closure s ∩ closure (- s) :=
by rw [closure_compl, frontier, diff_eq]
@[simp] lemma frontier_compl (s : set α) : frontier (-s) = frontier s :=
by simp [frontier_eq_closure_inter_closure, inter_comm]
/-- neighbourhood filter -/
def nhds (a : α) : filter α := (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, principal s)
lemma tendsto_nhds {m : β → α} {f : filter β} (h : ∀s, a ∈ s → is_open s → m ⁻¹' s ∈ f.sets) :
tendsto m f (nhds a) :=
show map m f ≤ (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, principal s),
from le_infi $ assume s, le_infi $ assume ⟨ha, hs⟩, le_principal_iff.mpr $ h s ha hs
lemma tendsto_const_nhds {a : α} {f : filter β} : tendsto (λb:β, a) f (nhds a) :=
tendsto_nhds $ assume s ha hs, univ_mem_sets' $ assume _, ha
lemma nhds_sets {a : α} : (nhds a).sets = {s | ∃t⊆s, is_open t ∧ a ∈ t} :=
calc (nhds a).sets = (⋃s∈{s : set α| a ∈ s ∧ is_open s}, (principal s).sets) : infi_sets_eq'
(assume x ⟨hx₁, hx₂⟩ y ⟨hy₁, hy₂⟩,
⟨x ∩ y, ⟨⟨hx₁, hy₁⟩, is_open_inter hx₂ hy₂⟩, by simp [ge]⟩)
⟨univ, by simp⟩
... = {s | ∃t⊆s, is_open t ∧ a ∈ t} :
le_antisymm
(supr_le $ assume i, supr_le $ assume ⟨hi₁, hi₂⟩ t ht, ⟨i, ht, hi₂, hi₁⟩)
(assume t ⟨i, hi₁, hi₂, hi₃⟩, by simp; exact ⟨i, ⟨hi₃, hi₂⟩, hi₁⟩)
lemma map_nhds {a : α} {f : α → β} :
map f (nhds a) = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, principal (image f s)) :=
calc map f (nhds a) = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, map f (principal s)) :
map_binfi_eq
(assume x ⟨hx₁, hx₂⟩ y ⟨hy₁, hy₂⟩,
⟨x ∩ y, ⟨⟨hx₁, hy₁⟩, is_open_inter hx₂ hy₂⟩, by simp [ge]⟩)
⟨univ, by simp⟩
... = _ : by simp
lemma mem_nhds_sets_iff {a : α} {s : set α} :
s ∈ (nhds a).sets ↔ ∃t⊆s, is_open t ∧ a ∈ t :=
by simp [nhds_sets]
lemma mem_of_nhds {a : α} {s : set α} : s ∈ (nhds a).sets → a ∈ s :=
by simp [mem_nhds_sets_iff]; exact assume t ht _ hs, ht hs
lemma mem_nhds_sets {a : α} {s : set α} (hs : is_open s) (ha : a ∈ s) :
s ∈ (nhds a).sets :=
by simp [nhds_sets]; exact ⟨s, subset.refl _, hs, ha⟩
lemma pure_le_nhds : pure ≤ (nhds : α → filter α) :=
assume a, le_infi $ assume s, le_infi $ assume ⟨h₁, _⟩, principal_mono.mpr $ by simp [h₁]
@[simp] lemma nhds_neq_bot {a : α} : nhds a ≠ ⊥ :=
assume : nhds a = ⊥,
have pure a = (⊥ : filter α),
from lattice.bot_unique $ this ▸ pure_le_nhds a,
pure_neq_bot this
lemma interior_eq_nhds {s : set α} : interior s = {a | nhds a ≤ principal s} :=
set.ext $ by simp [mem_interior, nhds_sets]
lemma mem_interior_iff_mem_nhds {s : set α} {a : α} :
a ∈ interior s ↔ s ∈ (nhds a).sets :=
by simp [interior_eq_nhds]
lemma is_open_iff_nhds {s : set α} : is_open s ↔ ∀a∈s, nhds a ≤ principal s :=
calc is_open s ↔ interior s = s : by rw [interior_eq_iff_open]
... ↔ s ⊆ interior s : ⟨assume h, by simp [*, subset.refl], subset.antisymm interior_subset⟩
... ↔ (∀a∈s, nhds a ≤ principal s) : by rw [interior_eq_nhds]; refl
lemma is_open_iff_mem_nhds {s : set α} : is_open s ↔ ∀a∈s, s ∈ (nhds a).sets :=
by simpa using @is_open_iff_nhds α _ _
lemma closure_eq_nhds {s : set α} : closure s = {a | nhds a ⊓ principal s ≠ ⊥} :=
calc closure s = - interior (- s) : closure_eq_compl_interior_compl
... = {a | ¬ nhds a ≤ principal (-s)} : by rw [interior_eq_nhds]; refl
... = {a | nhds a ⊓ principal s ≠ ⊥} : set.ext $ assume a, not_congr
(inf_eq_bot_iff_le_compl
(show principal s ⊔ principal (-s) = ⊤, by simp [principal_univ])
(by simp)).symm
theorem mem_closure_iff_nhds {s : set α} {a : α} : a ∈ closure s ↔ ∀ t ∈ (nhds a).sets, t ∩ s ≠ ∅ :=
mem_closure_iff.trans
⟨λ H t ht, subset_ne_empty
(inter_subset_inter_left _ interior_subset)
(H _ is_open_interior (mem_interior_iff_mem_nhds.2 ht)),
λ H o oo ao, H _ (mem_nhds_sets oo ao)⟩
lemma is_closed_iff_nhds {s : set α} : is_closed s ↔ ∀a, nhds a ⊓ principal s ≠ ⊥ → a ∈ s :=
calc is_closed s ↔ closure s = s : by rw [closure_eq_iff_is_closed]
... ↔ closure s ⊆ s : ⟨assume h, by simp [*, subset.refl], assume h, subset.antisymm h subset_closure⟩
... ↔ (∀a, nhds a ⊓ principal s ≠ ⊥ → a ∈ s) : by rw [closure_eq_nhds]; refl
lemma closure_inter_open {s t : set α} (h : is_open s) : s ∩ closure t ⊆ closure (s ∩ t) :=
assume a ⟨hs, ht⟩,
have s ∈ (nhds a).sets, from mem_nhds_sets h hs,
have nhds a ⊓ principal s = nhds a, from inf_of_le_left $ by simp [this],
have nhds a ⊓ principal (s ∩ t) ≠ ⊥,
from calc nhds a ⊓ principal (s ∩ t) = nhds a ⊓ (principal s ⊓ principal t) : by simp
... = nhds a ⊓ principal t : by rw [←inf_assoc, this]
... ≠ ⊥ : by rw [closure_eq_nhds] at ht; assumption,
by rw [closure_eq_nhds]; assumption
lemma closure_diff {s t : set α} : closure s - closure t ⊆ closure (s - t) :=
calc closure s \ closure t = (- closure t) ∩ closure s : by simp [diff_eq, inter_comm]
... ⊆ closure (- closure t ∩ s) : closure_inter_open $ is_open_compl_iff.mpr $ is_closed_closure
... = closure (s \ closure t) : by simp [diff_eq, inter_comm]
... ⊆ closure (s \ t) : closure_mono $ diff_subset_diff (subset.refl s) subset_closure
lemma mem_of_closed_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α}
(hb : b ≠ ⊥) (hf : tendsto f b (nhds a)) (hs : is_closed s) (h : f ⁻¹' s ∈ b.sets) : a ∈ s :=
have b.map f ≤ nhds a ⊓ principal s,
from le_trans (le_inf (le_refl _) (le_principal_iff.mpr h)) (inf_le_inf hf (le_refl _)),
is_closed_iff_nhds.mp hs a $ neq_bot_of_le_neq_bot (map_ne_bot hb) this
lemma mem_closure_of_tendsto {f : β → α} {x : filter β} {a : α} {s : set α}
(hf : tendsto f x (nhds a)) (hs : is_closed s) (h : x ⊓ principal (f ⁻¹' s) ≠ ⊥) : a ∈ s :=
is_closed_iff_nhds.mp hs _ $ neq_bot_of_le_neq_bot (@map_ne_bot _ _ _ f h) $
le_inf (le_trans (map_mono $ inf_le_left) hf) $
le_trans (map_mono $ inf_le_right_of_le $ by simp; exact subset.refl _) (@map_comap_le _ _ _ f)
/- locally finite family [General Topology (Bourbaki, 1995)] -/
section locally_finite
/-- A family of sets in `set α` is locally finite if at every point `x:α`,
there is a neighborhood of `x` which meets only finitely many sets in the family -/
def locally_finite (f : β → set α) :=
∀x:α, ∃t∈(nhds x).sets, finite {i | f i ∩ t ≠ ∅ }
lemma locally_finite_of_finite {f : β → set α} (h : finite (univ : set β)) : locally_finite f :=
assume x, ⟨univ, univ_mem_sets, finite_subset h $ by simp⟩
lemma locally_finite_subset
{f₁ f₂ : β → set α} (hf₂ : locally_finite f₂) (hf : ∀b, f₁ b ⊆ f₂ b) : locally_finite f₁ :=
assume a,
let ⟨t, ht₁, ht₂⟩ := hf₂ a in
⟨t, ht₁, finite_subset ht₂ $ assume i hi,
neq_bot_of_le_neq_bot hi $ inter_subset_inter (hf i) $ subset.refl _⟩
lemma is_closed_Union_of_locally_finite {f : β → set α}
(h₁ : locally_finite f) (h₂ : ∀i, is_closed (f i)) : is_closed (⋃i, f i) :=
is_open_iff_nhds.mpr $ assume a, assume h : a ∉ (⋃i, f i),
have ∀i, a ∈ -f i,
from assume i hi, by simp at h; exact h i hi,
have ∀i, - f i ∈ (nhds a).sets,
by rw [nhds_sets]; exact assume i, ⟨- f i, subset.refl _, h₂ i, this i⟩,
let ⟨t, h_sets, (h_fin : finite {i | f i ∩ t ≠ ∅ })⟩ := h₁ a in
calc nhds a ≤ principal (t ∩ (⋂ i∈{i | f i ∩ t ≠ ∅ }, - f i)) :
begin
rw [le_principal_iff],
apply @filter.inter_mem_sets _ (nhds a) _ _ h_sets,
apply @filter.Inter_mem_sets _ (nhds a) _ _ _ h_fin,
exact assume i h, this i
end
... ≤ principal (- ⋃i, f i) :
begin
simp only [principal_mono, subset_def, mem_compl_eq, mem_inter_eq,
mem_Inter, mem_set_of_eq, mem_Union, and_imp, not_exists,
not_eq_empty_iff_exists, exists_imp_distrib, (≠)],
exact assume x xt ht i xfi, ht i x xfi xt xfi
end
end locally_finite
/- compact sets -/
section compact
/-- A set `s` is compact if for every filter `f` that contains `s`,
every set of `f` also meets every neighborhood of some `a ∈ s`. -/
def compact (s : set α) := ∀f, f ≠ ⊥ → f ≤ principal s → ∃a∈s, f ⊓ nhds a ≠ ⊥
lemma compact_inter {s t : set α} (hs : compact s) (ht : is_closed t) : compact (s ∩ t) :=
assume f hnf hstf,
let ⟨a, hsa, (ha : f ⊓ nhds a ≠ ⊥)⟩ := hs f hnf (le_trans hstf (by simp)) in
have ∀a, principal t ⊓ nhds a ≠ ⊥ → a ∈ t,
by intro a; rw [inf_comm]; rw [is_closed_iff_nhds] at ht; exact ht a,
have a ∈ t,
from this a $ neq_bot_of_le_neq_bot ha $ inf_le_inf (le_trans hstf (by simp)) (le_refl _),
⟨a, ⟨hsa, this⟩, ha⟩
lemma compact_diff {s t : set α} (hs : compact s) (ht : is_open t) : compact (s \ t) :=
compact_inter hs (is_closed_compl_iff.mpr ht)
lemma compact_of_is_closed_subset {s t : set α}
(hs : compact s) (ht : is_closed t) (h : t ⊆ s) : compact t :=
by convert ← compact_inter hs ht; exact inter_eq_self_of_subset_right h
lemma compact_adherence_nhdset {s t : set α} {f : filter α}
(hs : compact s) (hf₂ : f ≤ principal s) (ht₁ : is_open t) (ht₂ : ∀a∈s, nhds a ⊓ f ≠ ⊥ → a ∈ t) :
t ∈ f.sets :=
classical.by_cases mem_sets_of_neq_bot $
assume : f ⊓ principal (- t) ≠ ⊥,
let ⟨a, ha, (hfa : f ⊓ principal (-t) ⊓ nhds a ≠ ⊥)⟩ := hs _ this $ inf_le_left_of_le hf₂ in
have a ∈ t,
from ht₂ a ha $ neq_bot_of_le_neq_bot hfa $ le_inf inf_le_right $ inf_le_left_of_le inf_le_left,
have nhds a ⊓ principal (-t) ≠ ⊥,
from neq_bot_of_le_neq_bot hfa $ le_inf inf_le_right $ inf_le_left_of_le inf_le_right,
have ∀s∈(nhds a ⊓ principal (-t)).sets, s ≠ ∅,
from forall_sets_neq_empty_iff_neq_bot.mpr this,
have false,
from this _ ⟨t, mem_nhds_sets ht₁ ‹a ∈ t›, -t, subset.refl _, subset.refl _⟩ (by simp),
by contradiction
lemma compact_iff_ultrafilter_le_nhds {s : set α} :
compact s ↔ (∀f, ultrafilter f → f ≤ principal s → ∃a∈s, f ≤ nhds a) :=
⟨assume hs : compact s, assume f hf hfs,
let ⟨a, ha, h⟩ := hs _ hf.left hfs in
⟨a, ha, le_of_ultrafilter hf h⟩,
assume hs : (∀f, ultrafilter f → f ≤ principal s → ∃a∈s, f ≤ nhds a),
assume f hf hfs,
let ⟨a, ha, (h : ultrafilter_of f ≤ nhds a)⟩ :=
hs (ultrafilter_of f) (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hfs) in
have ultrafilter_of f ⊓ nhds a ≠ ⊥,
by simp [inf_of_le_left, h]; exact (ultrafilter_ultrafilter_of hf).left,
⟨a, ha, neq_bot_of_le_neq_bot this (inf_le_inf ultrafilter_of_le (le_refl _))⟩⟩
lemma compact_elim_finite_subcover {s : set α} {c : set (set α)}
(hs : compact s) (hc₁ : ∀t∈c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃c'⊆c, finite c' ∧ s ⊆ ⋃₀ c' :=
classical.by_contradiction $ assume h,
have h : ∀{c'}, c' ⊆ c → finite c' → ¬ s ⊆ ⋃₀ c',
from assume c' h₁ h₂ h₃, h ⟨c', h₁, h₂, h₃⟩,
let
f : filter α := (⨅c':{c' : set (set α) // c' ⊆ c ∧ finite c'}, principal (s - ⋃₀ c')),
⟨a, ha⟩ := @exists_mem_of_ne_empty α s
(assume h', h (empty_subset _) finite_empty $ h'.symm ▸ empty_subset _)
in
have f ≠ ⊥, from infi_neq_bot_of_directed ⟨a⟩
(assume ⟨c₁, hc₁, hc'₁⟩ ⟨c₂, hc₂, hc'₂⟩, ⟨⟨c₁ ∪ c₂, union_subset hc₁ hc₂, finite_union hc'₁ hc'₂⟩,
principal_mono.mpr $ diff_subset_diff_right $ sUnion_mono $ subset_union_left _ _,
principal_mono.mpr $ diff_subset_diff_right $ sUnion_mono $ subset_union_right _ _⟩)
(assume ⟨c', hc'₁, hc'₂⟩, show principal (s \ _) ≠ ⊥, by simp [diff_eq_empty]; exact h hc'₁ hc'₂),
have f ≤ principal s, from infi_le_of_le ⟨∅, empty_subset _, finite_empty⟩ $
show principal (s \ ⋃₀∅) ≤ principal s, by simp; exact subset.refl s,
let
⟨a, ha, (h : f ⊓ nhds a ≠ ⊥)⟩ := hs f ‹f ≠ ⊥› this,
⟨t, ht₁, (ht₂ : a ∈ t)⟩ := hc₂ ha
in
have f ≤ principal (-t),
from infi_le_of_le ⟨{t}, by simp [ht₁], finite_insert _ finite_empty⟩ $
principal_mono.mpr $
show s - ⋃₀{t} ⊆ - t, begin simp; exact assume x ⟨_, hnt⟩, hnt end,
have is_closed (- t), from is_open_compl_iff.mp $ by simp; exact hc₁ t ht₁,
have a ∈ - t, from is_closed_iff_nhds.mp this _ $ neq_bot_of_le_neq_bot h $
le_inf inf_le_right (inf_le_left_of_le ‹f ≤ principal (- t)›),
this ‹a ∈ t›
lemma compact_elim_finite_subcover_image {s : set α} {b : set β} {c : β → set α}
(hs : compact s) (hc₁ : ∀i∈b, is_open (c i)) (hc₂ : s ⊆ ⋃i∈b, c i) :
∃b'⊆b, finite b' ∧ s ⊆ ⋃i∈b', c i :=
if h : b = ∅ then ⟨∅, by simp, by simp, h ▸ hc₂⟩ else
let ⟨i, hi⟩ := exists_mem_of_ne_empty h in
have hc'₁ : ∀i∈c '' b, is_open i, from assume i ⟨j, hj, h⟩, h ▸ hc₁ _ hj,
have hc'₂ : s ⊆ ⋃₀ (c '' b), by simpa,
let ⟨d, hd₁, hd₂, hd₃⟩ := compact_elim_finite_subcover hs hc'₁ hc'₂ in
have ∀x : d, ∃i, i ∈ b ∧ c i = x, from assume ⟨x, hx⟩, hd₁ hx,
let ⟨f', hf⟩ := axiom_of_choice this,
f := λx:set α, (if h : x ∈ d then f' ⟨x, h⟩ else i : β) in
have ∀(x : α) (i : set α), i ∈ d → x ∈ i → (∃ (i : β), i ∈ f '' d ∧ x ∈ c i),
from assume x i hid hxi, ⟨f i, mem_image_of_mem f hid,
by simpa [f, hid, (hf ⟨_, hid⟩).2] using hxi⟩,
⟨f '' d,
assume i ⟨j, hj, h⟩,
h ▸ by simpa [f, hj] using (hf ⟨_, hj⟩).1,
finite_image f hd₂,
subset.trans hd₃ $ by simpa [subset_def]⟩
lemma compact_of_finite_subcover {s : set α}
(h : ∀c, (∀t∈c, is_open t) → s ⊆ ⋃₀ c → ∃c'⊆c, finite c' ∧ s ⊆ ⋃₀ c') : compact s :=
assume f hfn hfs, classical.by_contradiction $ assume : ¬ (∃x∈s, f ⊓ nhds x ≠ ⊥),
have hf : ∀x∈s, nhds x ⊓ f = ⊥,
by simpa [not_and, inf_comm],
have ¬ ∃x∈s, ∀t∈f.sets, x ∈ closure t,
from assume ⟨x, hxs, hx⟩,
have ∅ ∈ (nhds x ⊓ f).sets, by rw [empty_in_sets_eq_bot, hf x hxs],
let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := by rw [mem_inf_sets] at this; exact this in
have ∅ ∈ (nhds x ⊓ principal t₂).sets,
from (nhds x ⊓ principal t₂).sets_of_superset (inter_mem_inf_sets ht₁ (subset.refl t₂)) ht,
have nhds x ⊓ principal t₂ = ⊥,
by rwa [empty_in_sets_eq_bot] at this,
by simp [closure_eq_nhds] at hx; exact hx t₂ ht₂ this,
have ∀x∈s, ∃t∈f.sets, x ∉ closure t, by simpa [_root_.not_forall],
let c := (λt, - closure t) '' f.sets, ⟨c', hcc', hcf, hsc'⟩ := h c
(assume t ⟨s, hs, h⟩, h ▸ is_closed_closure) (by simpa [subset_def]) in
let ⟨b, hb⟩ := axiom_of_choice $
show ∀s:c', ∃t, t ∈ f.sets ∧ - closure t = s,
from assume ⟨x, hx⟩, hcc' hx in
have (⋂s∈c', if h : s ∈ c' then b ⟨s, h⟩ else univ) ∈ f.sets,
from Inter_mem_sets hcf $ assume t ht, by rw [dif_pos ht]; exact (hb ⟨t, ht⟩).left,
have s ∩ (⋂s∈c', if h : s ∈ c' then b ⟨s, h⟩ else univ) ∈ f.sets,
from inter_mem_sets (by simp at hfs; assumption) this,
have ∅ ∈ f.sets,
from mem_sets_of_superset this $ assume x ⟨hxs, hxi⟩,
let ⟨t, htc', hxt⟩ := (show ∃t ∈ c', x ∈ t, by simpa using hsc' hxs) in
have -closure (b ⟨t, htc'⟩) = t, from (hb _).right,
have x ∈ - t,
from this ▸ (calc x ∈ b ⟨t, htc'⟩ : by simp at hxi; have h := hxi t htc'; rwa [dif_pos htc'] at h
... ⊆ closure (b ⟨t, htc'⟩) : subset_closure
... ⊆ - - closure (b ⟨t, htc'⟩) : by simp; exact subset.refl _),
show false, from this hxt,
hfn $ by rwa [empty_in_sets_eq_bot] at this
lemma compact_iff_finite_subcover {s : set α} :
compact s ↔ (∀c, (∀t∈c, is_open t) → s ⊆ ⋃₀ c → ∃c'⊆c, finite c' ∧ s ⊆ ⋃₀ c') :=
⟨assume hc c, compact_elim_finite_subcover hc, compact_of_finite_subcover⟩
lemma compact_empty : compact (∅ : set α) :=
assume f hnf hsf, not.elim hnf $
by simpa [empty_in_sets_eq_bot] using hsf
lemma compact_singleton {a : α} : compact ({a} : set α) :=
compact_of_finite_subcover $ assume c hc₁ hc₂,
let ⟨i, hic, hai⟩ := (show ∃i ∈ c, a ∈ i, by simpa using hc₂) in
⟨{i}, by simp [hic], finite_singleton _, by simp [hai]⟩
lemma compact_bUnion_of_compact {s : set β} {f : β → set α} (hs : finite s) :
(∀i ∈ s, compact (f i)) → compact (⋃i ∈ s, f i) :=
assume hf, compact_of_finite_subcover $ assume c c_open c_cover,
have ∀i : subtype s, ∃c' ⊆ c, finite c' ∧ f i ⊆ ⋃₀ c', from
assume ⟨i, hi⟩, compact_elim_finite_subcover (hf i hi) c_open
(calc f i ⊆ ⋃i ∈ s, f i : subset_bUnion_of_mem hi
... ⊆ ⋃₀ c : c_cover),
let ⟨finite_subcovers, h⟩ := axiom_of_choice this in
let c' := ⋃i, finite_subcovers i in
have c' ⊆ c, from Union_subset (λi, (h i).fst),
have finite c', from @finite_Union _ _ hs.fintype _ (λi, (h i).snd.1),
have (⋃i ∈ s, f i) ⊆ ⋃₀ c', from bUnion_subset $ λi hi, calc
f i ⊆ ⋃₀ finite_subcovers ⟨i,hi⟩ : (h ⟨i,hi⟩).snd.2
... ⊆ ⋃₀ c' : sUnion_mono (subset_Union _ _),
⟨c', ‹c' ⊆ c›, ‹finite c'›, this⟩
lemma compact_of_finite {s : set α} (hs : finite s) : compact s :=
let s' : set α := ⋃i ∈ s, {i} in
have e : s' = s, from ext $ λi, by simp,
have compact s', from compact_bUnion_of_compact hs (λ_ _, compact_singleton),
e ▸ this
end compact
/- separation axioms -/
section separation
/-- A T₁ space, also known as a Fréchet space, is a topological space
where for every pair `x ≠ y`, there is an open set containing `x` and not `y`.
Equivalently, every singleton set is closed. -/
class t1_space (α : Type u) [topological_space α] :=
(t1 : ∀x, is_closed ({x} : set α))
lemma is_closed_singleton [t1_space α] {x : α} : is_closed ({x} : set α) :=
t1_space.t1 x
lemma compl_singleton_mem_nhds [t1_space α] {x y : α} (h : y ≠ x) : - {x} ∈ (nhds y).sets :=
mem_nhds_sets is_closed_singleton $ by simp; exact h
@[simp] lemma closure_singleton [topological_space α] [t1_space α] {a : α} :
closure ({a} : set α) = {a} :=
closure_eq_of_is_closed is_closed_singleton
/-- A T₂ space, also known as a Hausdorff space, is one in which for every
`x ≠ y` there exists disjoint open sets around `x` and `y`. This is
the most widely used of the separation axioms. -/
class t2_space (α : Type u) [topological_space α] :=
(t2 : ∀x y, x ≠ y → ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅)
lemma t2_separation [t2_space α] {x y : α} (h : x ≠ y) :
∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅ :=
t2_space.t2 x y h
instance t2_space.t1_space [topological_space α] [t2_space α] : t1_space α :=
⟨assume x,
have ∀y, y ≠ x ↔ ∃ (i : set α), (x ∉ i ∧ is_open i) ∧ y ∈ i,
from assume y, ⟨assume h',
let ⟨u, v, hu, hv, hy, hx, h⟩ := t2_separation h' in
have x ∉ u,
from assume : x ∈ u,
have x ∈ u ∩ v, from ⟨this, hx⟩,
by rwa [h] at this,
⟨u, ⟨this, hu⟩, hy⟩,
assume ⟨s, ⟨hx, hs⟩, hy⟩ h, hx $ h ▸ hy⟩,
have (-{x} : set α) = (⋃s∈{s : set α | x ∉ s ∧ is_open s}, s),
by apply set.ext; simpa,
show is_open (- {x}),
by rw [this]; exact (is_open_Union $ assume s, is_open_Union $ assume ⟨_, hs⟩, hs)⟩
lemma eq_of_nhds_neq_bot [ht : t2_space α] {x y : α} (h : nhds x ⊓ nhds y ≠ ⊥) : x = y :=
classical.by_contradiction $ assume : x ≠ y,
let ⟨u, v, hu, hv, hx, hy, huv⟩ := t2_space.t2 x y this in
have u ∩ v ∈ (nhds x ⊓ nhds y).sets,
from inter_mem_inf_sets (mem_nhds_sets hu hx) (mem_nhds_sets hv hy),
h $ empty_in_sets_eq_bot.mp $ huv ▸ this
@[simp] lemma nhds_eq_nhds_iff {a b : α} [t2_space α] : nhds a = nhds b ↔ a = b :=
⟨assume h, eq_of_nhds_neq_bot $ by simp [h], assume h, h ▸ rfl⟩
@[simp] lemma nhds_le_nhds_iff {a b : α} [t2_space α] : nhds a ≤ nhds b ↔ a = b :=
⟨assume h, eq_of_nhds_neq_bot $ by simp [inf_of_le_left h], assume h, h ▸ le_refl _⟩
lemma tendsto_nhds_unique [t2_space α] {f : β → α} {l : filter β} {a b : α}
(hl : l ≠ ⊥) (ha : tendsto f l (nhds a)) (hb : tendsto f l (nhds b)) : a = b :=
eq_of_nhds_neq_bot $ neq_bot_of_le_neq_bot (map_ne_bot hl) $ le_inf ha hb
end separation
section regularity
/-- A T₃ space, also known as a regular space (although this condition sometimes
omits T₂), is one in which for every closed `C` and `x ∉ C`, there exist
disjoint open sets containing `x` and `C` respectively. -/
class regular_space (α : Type u) [topological_space α] extends t2_space α :=
(regular : ∀{s:set α} {a}, is_closed s → a ∉ s → ∃t, is_open t ∧ s ⊆ t ∧ nhds a ⊓ principal t = ⊥)
lemma nhds_is_closed [regular_space α] {a : α} {s : set α} (h : s ∈ (nhds a).sets) :
∃t∈(nhds a).sets, t ⊆ s ∧ is_closed t :=
let ⟨s', h₁, h₂, h₃⟩ := mem_nhds_sets_iff.mp h in
have ∃t, is_open t ∧ -s' ⊆ t ∧ nhds a ⊓ principal t = ⊥,
from regular_space.regular (is_closed_compl_iff.mpr h₂) (not_not_intro h₃),
let ⟨t, ht₁, ht₂, ht₃⟩ := this in
⟨-t,
mem_sets_of_neq_bot $ by simp; exact ht₃,
subset.trans (compl_subset_comm.1 ht₂) h₁,
is_closed_compl_iff.mpr ht₁⟩
end regularity
/- generating sets -/
end topological_space
namespace topological_space
variables {α : Type u}
/-- The least topology containing a collection of basic sets. -/
inductive generate_open (g : set (set α)) : set α → Prop
| basic : ∀s∈g, generate_open s
| univ : generate_open univ
| inter : ∀s t, generate_open s → generate_open t → generate_open (s ∩ t)
| sUnion : ∀k, (∀s∈k, generate_open s) → generate_open (⋃₀ k)
/-- The smallest topological space containing the collection `g` of basic sets -/
def generate_from (g : set (set α)) : topological_space α :=
{ is_open := generate_open g,
is_open_univ := generate_open.univ g,
is_open_inter := generate_open.inter,
is_open_sUnion := generate_open.sUnion }
lemma nhds_generate_from {g : set (set α)} {a : α} :
@nhds α (generate_from g) a = (⨅s∈{s | a ∈ s ∧ s ∈ g}, principal s) :=
le_antisymm
(infi_le_infi $ assume s, infi_le_infi_const $ assume ⟨as, sg⟩, ⟨as, generate_open.basic _ sg⟩)
(le_infi $ assume s, le_infi $ assume ⟨as, hs⟩,
have ∀s, generate_open g s → a ∈ s → (⨅s∈{s | a ∈ s ∧ s ∈ g}, principal s) ≤ principal s,
begin
intros s hs,
induction hs,
case generate_open.basic : s hs
{ exact assume as, infi_le_of_le s $ infi_le _ ⟨as, hs⟩ },
case generate_open.univ
{ rw [principal_univ],
exact assume _, le_top },
case generate_open.inter : s t hs' ht' hs ht
{ exact assume ⟨has, hat⟩, calc _ ≤ principal s ⊓ principal t : le_inf (hs has) (ht hat)
... = _ : by simp },
case generate_open.sUnion : k hk' hk
{ exact λ ⟨t, htk, hat⟩, calc _ ≤ principal t : hk t htk hat
... ≤ _ : begin simp; exact subset_sUnion_of_mem htk end }
end,
this s hs as)
lemma tendsto_nhds_generate_from {β : Type*} {m : α → β} {f : filter α} {g : set (set β)} {b : β}
(h : ∀s∈g, b ∈ s → m ⁻¹' s ∈ f.sets) : tendsto m f (@nhds β (generate_from g) b) :=
by rw [nhds_generate_from]; exact
(tendsto_infi.2 $ assume s, tendsto_infi.2 $ assume ⟨hbs, hsg⟩, tendsto_principal.2 $ h s hsg hbs)
protected def mk_of_nhds (n : α → filter α) : topological_space α :=
{ is_open := λs, ∀a∈s, s ∈ (n a).sets,
is_open_univ := assume x h, univ_mem_sets,
is_open_inter := assume s t hs ht x ⟨hxs, hxt⟩, inter_mem_sets (hs x hxs) (ht x hxt),
is_open_sUnion := assume s hs a ⟨x, hx, hxa⟩, mem_sets_of_superset (hs x hx _ hxa) (set.subset_sUnion_of_mem hx) }
lemma nhds_mk_of_nhds (n : α → filter α) (a : α)
(h₀ : pure ≤ n) (h₁ : ∀{a s}, s ∈ (n a).sets → ∃t∈(n a).sets, t ⊆ s ∧ ∀a'∈t, t ∈ (n a').sets) :
@nhds α (topological_space.mk_of_nhds n) a = n a :=
by letI := topological_space.mk_of_nhds n; from
(le_antisymm
(assume s hs, let ⟨t, ht, hst, h⟩ := h₁ hs in
have t ∈ (nhds a).sets, from mem_nhds_sets h (mem_pure_sets.1 $ h₀ a ht),
(nhds a).sets_of_superset this hst)
(assume s hs,
let ⟨t, hts, ht, hat⟩ := (@mem_nhds_sets_iff α (topological_space.mk_of_nhds n) _ _).1 hs in
(n a).sets_of_superset (ht _ hat) hts))
end topological_space
section lattice
variables {α : Type u} {β : Type v}
instance : partial_order (topological_space α) :=
{ le := λt s, t.is_open ≤ s.is_open,
le_antisymm := assume t s h₁ h₂, topological_space_eq $ le_antisymm h₁ h₂,
le_refl := assume t, le_refl t.is_open,
le_trans := assume a b c h₁ h₂, @le_trans _ _ a.is_open b.is_open c.is_open h₁ h₂ }
lemma generate_from_le_iff_subset_is_open {g : set (set α)} {t : topological_space α} :
topological_space.generate_from g ≤ t ↔ g ⊆ {s | t.is_open s} :=
iff.intro
(assume ht s hs, ht _ $ topological_space.generate_open.basic s hs)
(assume hg s hs, hs.rec_on (assume v hv, hg hv)
t.is_open_univ (assume u v _ _, t.is_open_inter u v) (assume k _, t.is_open_sUnion k))
protected def mk_of_closure (s : set (set α))
(hs : {u | (topological_space.generate_from s).is_open u} = s) : topological_space α :=
{ is_open := λu, u ∈ s,
is_open_univ := hs ▸ topological_space.generate_open.univ _,
is_open_inter := hs ▸ topological_space.generate_open.inter,
is_open_sUnion := hs ▸ topological_space.generate_open.sUnion }
lemma mk_of_closure_sets {s : set (set α)}
{hs : {u | (topological_space.generate_from s).is_open u} = s} :
mk_of_closure s hs = topological_space.generate_from s :=
topological_space_eq hs.symm
def gi_generate_from (α : Type*) :
galois_insertion topological_space.generate_from (λt:topological_space α, {s | t.is_open s}) :=
{ gc := assume g t, generate_from_le_iff_subset_is_open,
le_l_u := assume ts s hs, topological_space.generate_open.basic s hs,
choice := λg hg, mk_of_closure g
(subset.antisymm hg $ generate_from_le_iff_subset_is_open.1 $ le_refl _),
choice_eq := assume s hs, mk_of_closure_sets }
lemma generate_from_mono {α} {g₁ g₂ : set (set α)} (h : g₁ ⊆ g₂) :
topological_space.generate_from g₁ ≤ topological_space.generate_from g₂ :=
(gi_generate_from _).gc.monotone_l h
instance {α : Type u} : complete_lattice (topological_space α) :=
(gi_generate_from α).lift_complete_lattice
@[simp] lemma is_open_top {s : set α} : @is_open α ⊤ s := trivial
lemma le_of_nhds_le_nhds {t₁ t₂ : topological_space α} (h : ∀x, @nhds α t₂ x ≤ @nhds α t₁ x) :
t₁ ≤ t₂ :=
assume s, show @is_open α t₁ s → @is_open α t₂ s,
begin simp [is_open_iff_nhds]; exact assume hs a ha, h _ $ hs _ ha end
lemma eq_of_nhds_eq_nhds {t₁ t₂ : topological_space α} (h : ∀x, @nhds α t₂ x = @nhds α t₁ x) :
t₁ = t₂ :=
le_antisymm
(le_of_nhds_le_nhds $ assume x, le_of_eq $ h x)
(le_of_nhds_le_nhds $ assume x, le_of_eq $ (h x).symm)
end lattice
section galois_connection
variables {α : Type*} {β : Type*} {γ : Type*}
/-- Given `f : α → β` and a topology on `β`, the induced topology on `α` is the collection of
sets that are preimages of some open set in `β`. This is the coarsest topology that
makes `f` continuous. -/
def topological_space.induced {α : Type u} {β : Type v} (f : α → β) (t : topological_space β) :
topological_space α :=
{ is_open := λs, ∃s', t.is_open s' ∧ s = f ⁻¹' s',
is_open_univ := ⟨univ, by simp; exact t.is_open_univ⟩,
is_open_inter := assume s₁ s₂ ⟨s'₁, hs₁, eq₁⟩ ⟨s'₂, hs₂, eq₂⟩,
⟨s'₁ ∩ s'₂, by simp [eq₁, eq₂]; exact t.is_open_inter _ _ hs₁ hs₂⟩,
is_open_sUnion := assume s h,
begin
simp [classical.skolem] at h,
cases h with f hf,
apply exists.intro (⋃(x : set α) (h : x ∈ s), f x h),
simp [sUnion_eq_bUnion, (λx h, (hf x h).right.symm)],
exact (@is_open_Union β _ t _ $ assume i,
show is_open (⋃h, f i h), from @is_open_Union β _ t _ $ assume h, (hf i h).left)
end }
lemma is_closed_induced_iff [t : topological_space β] {s : set α} {f : α → β} :
@is_closed α (t.induced f) s ↔ (∃t, is_closed t ∧ s = f ⁻¹' t) :=
⟨assume ⟨t, ht, heq⟩, ⟨-t, by simp; assumption, by simp [preimage_compl, heq.symm]⟩,
assume ⟨t, ht, heq⟩, ⟨-t, ht, by simp [preimage_compl, heq.symm]⟩⟩
/-- Given `f : α → β` and a topology on `α`, the coinduced topology on `β` is defined
such that `s:set β` is open if the preimage of `s` is open. This is the finest topology that
makes `f` continuous. -/
def topological_space.coinduced {α : Type u} {β : Type v} (f : α → β) (t : topological_space α) :
topological_space β :=
{ is_open := λs, t.is_open (f ⁻¹' s),
is_open_univ := by simp; exact t.is_open_univ,
is_open_inter := assume s₁ s₂ h₁ h₂, by simp; exact t.is_open_inter _ _ h₁ h₂,
is_open_sUnion := assume s h, by rw [preimage_sUnion]; exact (@is_open_Union _ _ t _ $ assume i,
show is_open (⋃ (H : i ∈ s), f ⁻¹' i), from
@is_open_Union _ _ t _ $ assume hi, h i hi) }
variables {t t₁ t₂ : topological_space α} {t' : topological_space β} {f : α → β} {g : β → α}
lemma induced_le_iff_le_coinduced {f : α → β } {tα : topological_space α} {tβ : topological_space β} :
tβ.induced f ≤ tα ↔ tβ ≤ tα.coinduced f :=
iff.intro
(assume h s hs, show tα.is_open (f ⁻¹' s), from h _ ⟨s, hs, rfl⟩)
(assume h s ⟨t, ht, hst⟩, hst.symm ▸ h _ ht)
lemma gc_induced_coinduced (f : α → β) :
galois_connection (topological_space.induced f) (topological_space.coinduced f) :=
assume f g, induced_le_iff_le_coinduced
lemma induced_mono (h : t₁ ≤ t₂) : t₁.induced g ≤ t₂.induced g :=
(gc_induced_coinduced g).monotone_l h
lemma coinduced_mono (h : t₁ ≤ t₂) : t₁.coinduced f ≤ t₂.coinduced f :=
(gc_induced_coinduced f).monotone_u h
@[simp] lemma induced_bot : (⊥ : topological_space α).induced g = ⊥ :=
(gc_induced_coinduced g).l_bot
@[simp] lemma induced_sup : (t₁ ⊔ t₂).induced g = t₁.induced g ⊔ t₂.induced g :=
(gc_induced_coinduced g).l_sup
@[simp] lemma induced_supr {ι : Sort w} {t : ι → topological_space α} :
(⨆i, t i).induced g = (⨆i, (t i).induced g) :=
(gc_induced_coinduced g).l_supr
@[simp] lemma coinduced_top : (⊤ : topological_space α).coinduced f = ⊤ :=
(gc_induced_coinduced f).u_top
@[simp] lemma coinduced_inf : (t₁ ⊓ t₂).coinduced f = t₁.coinduced f ⊓ t₂.coinduced f :=
(gc_induced_coinduced f).u_inf
@[simp] lemma coinduced_infi {ι : Sort w} {t : ι → topological_space α} :
(⨅i, t i).coinduced f = (⨅i, (t i).coinduced f) :=
(gc_induced_coinduced f).u_infi
lemma induced_id [t : topological_space α] : t.induced id = t :=
topological_space_eq $ funext $ assume s, propext $
⟨assume ⟨s', hs, h⟩, h.symm ▸ hs, assume hs, ⟨s, hs, rfl⟩⟩
lemma induced_compose [tβ : topological_space β] [tγ : topological_space γ]
{f : α → β} {g : β → γ} : (tγ.induced g).induced f = tγ.induced (g ∘ f) :=
topological_space_eq $ funext $ assume s, propext $
⟨assume ⟨s', ⟨s, hs, h₂⟩, h₁⟩, h₁.symm ▸ h₂.symm ▸ ⟨s, hs, rfl⟩,
assume ⟨s, hs, h⟩, ⟨preimage g s, ⟨s, hs, rfl⟩, h ▸ rfl⟩⟩
lemma coinduced_id [t : topological_space α] : t.coinduced id = t :=
topological_space_eq rfl
lemma coinduced_compose [tα : topological_space α]
{f : α → β} {g : β → γ} : (tα.coinduced f).coinduced g = tα.coinduced (g ∘ f) :=
topological_space_eq rfl
end galois_connection
/- constructions using the complete lattice structure -/
section constructions
open topological_space
variables {α : Type u} {β : Type v}
instance inhabited_topological_space {α : Type u} : inhabited (topological_space α) :=
⟨⊤⟩
lemma t2_space_top : @t2_space α ⊤ :=
{ t2 := assume x y hxy, ⟨{x}, {y}, trivial, trivial, mem_insert _ _, mem_insert _ _,
eq_empty_iff_forall_not_mem.2 $ by intros z hz; simp at hz; cc⟩ }
instance : topological_space empty := ⊤
instance : topological_space unit := ⊤
instance : topological_space bool := ⊤
instance : topological_space ℕ := ⊤
instance : topological_space ℤ := ⊤
instance sierpinski_space : topological_space Prop :=
generate_from {{true}}
instance {p : α → Prop} [t : topological_space α] : topological_space (subtype p) :=
induced subtype.val t
instance {r : α → α → Prop} [t : topological_space α] : topological_space (quot r) :=
coinduced (quot.mk r) t
instance {s : setoid α} [t : topological_space α] : topological_space (quotient s) :=
coinduced quotient.mk t
instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α × β) :=
induced prod.fst t₁ ⊔ induced prod.snd t₂
instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α ⊕ β) :=
coinduced sum.inl t₁ ⊓ coinduced sum.inr t₂
instance {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (sigma β) :=
⨅a, coinduced (sigma.mk a) (t₂ a)
instance Pi.topological_space {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (Πa, β a) :=
⨆a, induced (λf, f a) (t₂ a)
instance [topological_space α] : topological_space (list α) :=
topological_space.mk_of_nhds (traverse nhds)
lemma nhds_list [topological_space α] (as : list α) : nhds as = traverse nhds as :=
begin
refine nhds_mk_of_nhds _ _ _ _,
{ assume l, induction l,
case list.nil { exact le_refl _ },
case list.cons : a l ih {
suffices : list.cons <$> pure a <*> pure l ≤ list.cons <$> nhds a <*> traverse nhds l,
{ simpa [-filter.pure_def] with functor_norm using this },
exact filter.seq_mono (filter.map_mono $ pure_le_nhds a) ih } },
{ assume l s hs,
rcases (mem_traverse_sets_iff _ _).1 hs with ⟨u, hu, hus⟩, clear as hs,
have : ∃v:list (set α), l.forall₂ (λa s, is_open s ∧ a ∈ s) v ∧ sequence v ⊆ s,
{ induction hu generalizing s,
case list.forall₂.nil : hs this { existsi [], simpa },
case list.forall₂.cons : a s as ss ht h ih t hts {
rcases mem_nhds_sets_iff.1 ht with ⟨u, hut, hu⟩,
rcases ih (subset.refl _) with ⟨v, hv, hvss⟩,
exact ⟨u::v, list.forall₂.cons hu hv,
subset.trans (set.seq_mono (set.image_subset _ hut) hvss) hts⟩ } },
rcases this with ⟨v, hv, hvs⟩,
refine ⟨sequence v, mem_traverse_sets _ _ _, hvs, _⟩,
{ exact hv.imp (assume a s ⟨hs, ha⟩, mem_nhds_sets hs ha) },
{ assume u hu,
have hu := (list.mem_traverse _ _).1 hu,
have : list.forall₂ (λa s, is_open s ∧ a ∈ s) u v,
{ refine list.forall₂.flip _,
replace hv := hv.flip,
simp [list.forall₂_and_left, flip] at ⊢ hv,
exact ⟨hv.1, hu.flip⟩ },
exact mem_traverse_sets _ _ (this.imp $ assume a s ⟨hs, ha⟩, mem_nhds_sets hs ha) } }
end
lemma quotient_dense_of_dense [setoid α] [topological_space α] {s : set α} (H : ∀ x, x ∈ closure s) :
closure (quotient.mk '' s) = univ :=
begin
ext x,
suffices : x ∈ closure (quotient.mk '' s), by simp [this],
rw mem_closure_iff,
intros U U_op x_in_U,
let V := quotient.mk ⁻¹' U,
cases quotient.exists_rep x with y y_x,
have y_in_V : y ∈ V, by simp [mem_preimage_eq, y_x, x_in_U],
have V_op : is_open V := U_op,
have : V ∩ s ≠ ∅ := mem_closure_iff.1 (H y) V V_op y_in_V,
rcases exists_mem_of_ne_empty this with ⟨w, w_in_V, w_in_range⟩,
exact ne_empty_of_mem ⟨by tauto, mem_image_of_mem quotient.mk w_in_range⟩
end
lemma generate_from_le {t : topological_space α} { g : set (set α) } (h : ∀s∈g, is_open s) :
generate_from g ≤ t :=
generate_from_le_iff_subset_is_open.2 h
protected def topological_space.nhds_adjoint (a : α) (f : filter α) : topological_space α :=
{ is_open := λs, a ∈ s → s ∈ f.sets,
is_open_univ := assume s, univ_mem_sets,
is_open_inter := assume s t hs ht ⟨has, hat⟩, inter_mem_sets (hs has) (ht hat),
is_open_sUnion := assume k hk ⟨u, hu, hau⟩, mem_sets_of_superset (hk u hu hau) (subset_sUnion_of_mem hu) }
lemma gc_nhds (a : α) :
@galois_connection _ (order_dual (filter α)) _ _ (λt, @nhds α t a) (topological_space.nhds_adjoint a) :=
assume t (f : filter α), show f ≤ @nhds α t a ↔ _, from iff.intro
(assume h s hs has, h $ @mem_nhds_sets α t a s hs has)
(assume h, le_infi $ assume u, le_infi $ assume ⟨hau, hu⟩, le_principal_iff.2 $ h _ hu hau)
lemma nhds_mono {t₁ t₂ : topological_space α} {a : α} (h : t₁ ≤ t₂) :
@nhds α t₂ a ≤ @nhds α t₁ a := (gc_nhds a).monotone_l h
lemma nhds_supr {ι : Sort*} {t : ι → topological_space α} {a : α} :
@nhds α (supr t) a = (⨅i, @nhds α (t i) a) := (gc_nhds a).l_supr
lemma nhds_Sup {s : set (topological_space α)} {a : α} :
@nhds α (Sup s) a = (⨅t∈s, @nhds α t a) := (gc_nhds a).l_Sup
lemma nhds_sup {t₁ t₂ : topological_space α} {a : α} :
@nhds α (t₁ ⊔ t₂) a = @nhds α t₁ a ⊓ @nhds α t₂ a := (gc_nhds a).l_sup
lemma nhds_bot {a : α} : @nhds α ⊥ a = ⊤ := (gc_nhds a).l_bot
private lemma separated_by_f
[tα : topological_space α] [tβ : topological_space β] [t2_space β]
(f : α → β) (hf : induced f tβ ≤ tα) {x y : α} (h : f x ≠ f y) :
∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅ :=
let ⟨u, v, uo, vo, xu, yv, uv⟩ := t2_separation h in
⟨f ⁻¹' u, f ⁻¹' v, hf _ ⟨u, uo, rfl⟩, hf _ ⟨v, vo, rfl⟩, xu, yv,
by rw [←preimage_inter, uv, preimage_empty]⟩
instance {p : α → Prop} [t : topological_space α] [t2_space α] : t2_space (subtype p) :=
⟨assume x y h,
separated_by_f subtype.val (le_refl _) (mt subtype.eq h)⟩
instance [t₁ : topological_space α] [t2_space α] [t₂ : topological_space β] [t2_space β] :
t2_space (α × β) :=
⟨assume ⟨x₁,x₂⟩ ⟨y₁,y₂⟩ h,
or.elim (not_and_distrib.mp (mt prod.ext_iff.mpr h))
(λ h₁, separated_by_f prod.fst le_sup_left h₁)
(λ h₂, separated_by_f prod.snd le_sup_right h₂)⟩
instance Pi.t2_space {β : α → Type v} [t₂ : Πa, topological_space (β a)] [Πa, t2_space (β a)] :
t2_space (Πa, β a) :=
⟨assume x y h,
let ⟨i, hi⟩ := not_forall.mp (mt funext h) in
separated_by_f (λz, z i) (le_supr _ i) hi⟩
end constructions
namespace topological_space
/- countability axioms
For our applications we are interested that there exists a countable basis, but we do not need the
concrete basis itself. This allows us to declare these type classes as `Prop` to use them as mixins.
-/
variables {α : Type u} [t : topological_space α]
include t
/-- A topological basis is one that satisfies the necessary conditions so that
it suffices to take unions of the basis sets to get a topology (without taking
finite intersections as well). -/
def is_topological_basis (s : set (set α)) : Prop :=
(∀t₁∈s, ∀t₂∈s, ∀ x ∈ t₁ ∩ t₂, ∃ t₃∈s, x ∈ t₃ ∧ t₃ ⊆ t₁ ∩ t₂) ∧
(⋃₀ s) = univ ∧
t = generate_from s
lemma is_topological_basis_of_subbasis {s : set (set α)} (hs : t = generate_from s) :
is_topological_basis ((λf, ⋂₀ f) '' {f:set (set α) | finite f ∧ f ⊆ s ∧ ⋂₀ f ≠ ∅}) :=
let b' := (λf, ⋂₀ f) '' {f:set (set α) | finite f ∧ f ⊆ s ∧ ⋂₀ f ≠ ∅} in
⟨assume s₁ ⟨t₁, ⟨hft₁, ht₁b, ht₁⟩, eq₁⟩ s₂ ⟨t₂, ⟨hft₂, ht₂b, ht₂⟩, eq₂⟩,
have ie : ⋂₀(t₁ ∪ t₂) = ⋂₀ t₁ ∩ ⋂₀ t₂, from Inf_union,
eq₁ ▸ eq₂ ▸ assume x h,
⟨_, ⟨t₁ ∪ t₂, ⟨finite_union hft₁ hft₂, union_subset ht₁b ht₂b,
by simpa [ie] using ne_empty_of_mem h⟩, ie⟩, h, subset.refl _⟩,
eq_univ_iff_forall.2 $ assume a, ⟨univ, ⟨∅, by simp; exact (@empty_ne_univ _ ⟨a⟩).symm⟩, mem_univ _⟩,
have generate_from s = generate_from b',
from le_antisymm
(generate_from_le $ assume s hs,
by_cases
(assume : s = ∅, by rw [this]; apply @is_open_empty _ _)
(assume : s ≠ ∅, generate_open.basic _ ⟨{s}, by simp [this, hs]⟩))
(generate_from_le $ assume u ⟨t, ⟨hft, htb, ne⟩, eq⟩,
eq ▸ @is_open_sInter _ (generate_from s) _ hft (assume s hs, generate_open.basic _ $ htb hs)),
this ▸ hs⟩
lemma is_topological_basis_of_open_of_nhds {s : set (set α)}
(h_open : ∀ u ∈ s, _root_.is_open u)
(h_nhds : ∀(a:α) (u : set α), a ∈ u → _root_.is_open u → ∃v ∈ s, a ∈ v ∧ v ⊆ u) :
is_topological_basis s :=
⟨assume t₁ ht₁ t₂ ht₂ x ⟨xt₁, xt₂⟩,
h_nhds x (t₁ ∩ t₂) ⟨xt₁, xt₂⟩
(is_open_inter _ _ _ (h_open _ ht₁) (h_open _ ht₂)),
eq_univ_iff_forall.2 $ assume a,
let ⟨u, h₁, h₂, _⟩ := h_nhds a univ trivial (is_open_univ _) in
⟨u, h₁, h₂⟩,
le_antisymm
(assume u hu,
(@is_open_iff_nhds α (generate_from _) _).mpr $ assume a hau,
let ⟨v, hvs, hav, hvu⟩ := h_nhds a u hau hu in
by rw nhds_generate_from; exact infi_le_of_le v (infi_le_of_le ⟨hav, hvs⟩ $ by simp [hvu]))
(generate_from_le h_open)⟩
lemma mem_nhds_of_is_topological_basis {a : α} {s : set α} {b : set (set α)}
(hb : is_topological_basis b) : s ∈ (nhds a).sets ↔ ∃t∈b, a ∈ t ∧ t ⊆ s :=
begin
rw [hb.2.2, nhds_generate_from, infi_sets_eq'],
{ simp [and_comm, and.left_comm] },
{ exact assume s ⟨hs₁, hs₂⟩ t ⟨ht₁, ht₂⟩,
have a ∈ s ∩ t, from ⟨hs₁, ht₁⟩,
let ⟨u, hu₁, hu₂, hu₃⟩ := hb.1 _ hs₂ _ ht₂ _ this in
⟨u, ⟨hu₂, hu₁⟩, by simpa [(≥)] using hu₃⟩ },
{ suffices : a ∈ (⋃₀ b), { simpa [and_comm] },
{ rw [hb.2.1], trivial } }
end
lemma is_open_of_is_topological_basis {s : set α} {b : set (set α)}
(hb : is_topological_basis b) (hs : s ∈ b) : _root_.is_open s :=
is_open_iff_mem_nhds.2 $ λ a as,
(mem_nhds_of_is_topological_basis hb).2 ⟨s, hs, as, subset.refl _⟩
lemma mem_basis_subset_of_mem_open {b : set (set α)}
(hb : is_topological_basis b) {a:α} {u : set α} (au : a ∈ u)
(ou : _root_.is_open u) : ∃v ∈ b, a ∈ v ∧ v ⊆ u :=
(mem_nhds_of_is_topological_basis hb).1 $ mem_nhds_sets ou au
lemma sUnion_basis_of_is_open {B : set (set α)}
(hB : is_topological_basis B) {u : set α} (ou : _root_.is_open u) :
∃ S ⊆ B, u = ⋃₀ S :=
⟨{s ∈ B | s ⊆ u}, λ s h, h.1, set.ext $ λ a,
⟨λ ha, let ⟨b, hb, ab, bu⟩ := mem_basis_subset_of_mem_open hB ha ou in
⟨b, ⟨hb, bu⟩, ab⟩,
λ ⟨b, ⟨hb, bu⟩, ab⟩, bu ab⟩⟩
lemma Union_basis_of_is_open {B : set (set α)}
(hB : is_topological_basis B) {u : set α} (ou : _root_.is_open u) :
∃ (β : Type u) (f : β → set α), u = (⋃ i, f i) ∧ ∀ i, f i ∈ B :=
let ⟨S, sb, su⟩ := sUnion_basis_of_is_open hB ou in
⟨S, subtype.val, su.trans set.sUnion_eq_Union, λ ⟨b, h⟩, sb h⟩
variables (α)
/-- A separable space is one with a countable dense subset. -/
class separable_space : Prop :=
(exists_countable_closure_eq_univ : ∃s:set α, countable s ∧ closure s = univ)
/-- A first-countable space is one in which every point has a
countable neighborhood basis. -/
class first_countable_topology : Prop :=
(nhds_generated_countable : ∀a:α, ∃s:set (set α), countable s ∧ nhds a = (⨅t∈s, principal t))
/-- A second-countable space is one with a countable basis. -/
class second_countable_topology : Prop :=
(is_open_generated_countable : ∃b:set (set α), countable b ∧ t = topological_space.generate_from b)
instance second_countable_topology.to_first_countable_topology
[second_countable_topology α] : first_countable_topology α :=
let ⟨b, hb, eq⟩ := second_countable_topology.is_open_generated_countable α in
⟨assume a, ⟨{s | a ∈ s ∧ s ∈ b},
countable_subset (assume x ⟨_, hx⟩, hx) hb, by rw [eq, nhds_generate_from]⟩⟩
lemma is_open_generated_countable_inter [second_countable_topology α] :
∃b:set (set α), countable b ∧ ∅ ∉ b ∧ is_topological_basis b :=
let ⟨b, hb₁, hb₂⟩ := second_countable_topology.is_open_generated_countable α in
let b' := (λs, ⋂₀ s) '' {s:set (set α) | finite s ∧ s ⊆ b ∧ ⋂₀ s ≠ ∅} in
⟨b',
countable_image _ $ countable_subset (by simp {contextual:=tt}) (countable_set_of_finite_subset hb₁),
assume ⟨s, ⟨_, _, hn⟩, hp⟩, hn hp,
is_topological_basis_of_subbasis hb₂⟩
instance second_countable_topology.to_separable_space
[second_countable_topology α] : separable_space α :=
let ⟨b, hb₁, hb₂, hb₃, hb₄, eq⟩ := is_open_generated_countable_inter α in
have nhds_eq : ∀a, nhds a = (⨅ s : {s : set α // a ∈ s ∧ s ∈ b}, principal s.val),
by intro a; rw [eq, nhds_generate_from]; simp [infi_subtype],
have ∀s∈b, ∃a, a ∈ s, from assume s hs, exists_mem_of_ne_empty $ assume eq, hb₂ $ eq ▸ hs,
have ∃f:∀s∈b, α, ∀s h, f s h ∈ s, by simp only [skolem] at this; exact this,
let ⟨f, hf⟩ := this in
⟨⟨(⋃s∈b, ⋃h:s∈b, {f s h}),
countable_bUnion hb₁ (by simp [countable_Union_Prop]),
set.ext $ assume a,
have a ∈ (⋃₀ b), by rw [hb₄]; exact trivial,
let ⟨t, ht₁, ht₂⟩ := this in
have w : {s : set α // a ∈ s ∧ s ∈ b}, from ⟨t, ht₂, ht₁⟩,
suffices (⨅ (x : {s // a ∈ s ∧ s ∈ b}), principal (x.val ∩ ⋃s (h₁ h₂ : s ∈ b), {f s h₂})) ≠ ⊥,
by simpa [closure_eq_nhds, nhds_eq, infi_inf w],
infi_neq_bot_of_directed ⟨a⟩
(assume ⟨s₁, has₁, hs₁⟩ ⟨s₂, has₂, hs₂⟩,
have a ∈ s₁ ∩ s₂, from ⟨has₁, has₂⟩,
let ⟨s₃, hs₃, has₃, hs⟩ := hb₃ _ hs₁ _ hs₂ _ this in
⟨⟨s₃, has₃, hs₃⟩, begin
simp only [le_principal_iff, mem_principal_sets, (≥)],
simp at hs, split; apply inter_subset_inter_left; simp [hs]
end⟩)
(assume ⟨s, has, hs⟩,
have s ∩ (⋃ (s : set α) (H h : s ∈ b), {f s h}) ≠ ∅,
from ne_empty_of_mem ⟨hf _ hs, mem_bUnion hs $ mem_Union.mpr ⟨hs, by simp⟩⟩,
by simp [this]) ⟩⟩
lemma is_open_sUnion_countable [second_countable_topology α]
(S : set (set α)) (H : ∀ s ∈ S, _root_.is_open s) :
∃ T : set (set α), countable T ∧ T ⊆ S ∧ ⋃₀ T = ⋃₀ S :=
let ⟨B, cB, _, bB⟩ := is_open_generated_countable_inter α in
begin
let B' := {b ∈ B | ∃ s ∈ S, b ⊆ s},
rcases axiom_of_choice (λ b:B', b.2.2) with ⟨f, hf⟩,
change B' → set α at f,
haveI : encodable B' := (countable_subset (sep_subset _ _) cB).to_encodable,
have : range f ⊆ S := range_subset_iff.2 (λ x, (hf x).fst),
exact ⟨_, countable_range f, this,
subset.antisymm (sUnion_subset_sUnion this) $
sUnion_subset $ λ s hs x xs,
let ⟨b, hb, xb, bs⟩ := mem_basis_subset_of_mem_open bB xs (H _ hs) in
⟨_, ⟨⟨_, hb, _, hs, bs⟩, rfl⟩, (hf _).snd xb⟩⟩
end
end topological_space
section limit
variables {α : Type u} [inhabited α] [topological_space α]
open classical
/-- If `f` is a filter, then `lim f` is a limit of the filter, if it exists. -/
noncomputable def lim (f : filter α) : α := epsilon $ λa, f ≤ nhds a
lemma lim_spec {f : filter α} (h : ∃a, f ≤ nhds a) : f ≤ nhds (lim f) := epsilon_spec h
variables [t2_space α] {f : filter α}
lemma lim_eq {a : α} (hf : f ≠ ⊥) (h : f ≤ nhds a) : lim f = a :=
eq_of_nhds_neq_bot $ neq_bot_of_le_neq_bot hf $ le_inf (lim_spec ⟨_, h⟩) h
@[simp] lemma lim_nhds_eq {a : α} : lim (nhds a) = a :=
lim_eq nhds_neq_bot (le_refl _)
@[simp] lemma lim_nhds_eq_of_closure {a : α} {s : set α} (h : a ∈ closure s) :
lim (nhds a ⊓ principal s) = a :=
lim_eq begin rw [closure_eq_nhds] at h, exact h end inf_le_left
end limit
|
! { dg-do run }
! pr35699 run-time abort writing zero sized section to direct access file
program directio
call qi0010 ( 10, 1, 2, 3, 4, 9, 2)
end
subroutine qi0010 (nf10, nf1, nf2, nf3, nf4,nf9, np2)
character(10) bda(nf10)
character(10) bda1(nf10), bval
integer j_len
bda1(1) = 'x'
do i = 2,10
bda1(i) = 'x'//bda1(i-1)
enddo
bda = 'unread'
inquire(iolength = j_len) bda1(nf1:nf10:nf2), bda1(nf4:nf3),
$ bda1(nf2:nf10:nf2)
open (unit=48,
$ access='direct',
$ status='scratch',
$ recl = j_len,
$ iostat = istat,
$ form='unformatted',
$ action='readwrite')
write (48,iostat = istat, rec = 3) bda1(nf1:nf10:nf2),
$ bda1(nf4:nf3), bda1(nf2:nf10:nf2)
if ( istat .ne. 0) then
STOP 1
endif
istat = -314
read (48,iostat = istat, rec = np2+1) bda(nf1:nf9:nf2),
$ bda(nf4:nf3), bda(nf2:nf10:nf2)
if ( istat .ne. 0) then
STOP 2
endif
do j1 = 1,10
bval = bda1(j1)
if (bda(j1) .ne. bval) STOP 3
enddo
end subroutine
|
[STATEMENT]
lemma simptm_nb[simp]: "tmbound n t \<Longrightarrow> tmbound n (simptm t)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. tmbound n t \<Longrightarrow> tmbound n (simptm t)
[PROOF STEP]
by (induct t rule: simptm.induct) (auto simp add: Let_def) |
/-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Yaël Dillies
-/
import order.locally_finite
/-!
# Intervals as finsets
This file provides basic results about all the `finset.Ixx`, which are defined in
`order.locally_finite`.
## TODO
This file was originally only about `finset.Ico a b` where `a b : ℕ`. No care has yet been taken to
generalize these lemmas properly and many lemmas about `Icc`, `Ioc`, `Ioo` are missing. In general,
what's to do is taking the lemmas in `data.x.intervals` and abstract away the concrete structure.
-/
variables {α : Type*}
namespace finset
section preorder
variables [preorder α] [locally_finite_order α] {a b : α}
@[simp] lemma nonempty_Icc : (Icc a b).nonempty ↔ a ≤ b :=
by rw [←coe_nonempty, coe_Icc, set.nonempty_Icc]
@[simp] lemma nonempty_Ico : (Ico a b).nonempty ↔ a < b :=
by rw [←coe_nonempty, coe_Ico, set.nonempty_Ico]
@[simp] lemma nonempty_Ioc : (Ioc a b).nonempty ↔ a < b :=
by rw [←coe_nonempty, coe_Ioc, set.nonempty_Ioc]
@[simp] lemma nonempty_Ioo [densely_ordered α] : (Ioo a b).nonempty ↔ a < b :=
by rw [←coe_nonempty, coe_Ioo, set.nonempty_Ioo]
@[simp] lemma Icc_eq_empty_iff : Icc a b = ∅ ↔ ¬a ≤ b :=
by rw [←coe_eq_empty, coe_Icc, set.Icc_eq_empty_iff]
@[simp] lemma Ico_eq_empty_iff : Ico a b = ∅ ↔ ¬a < b :=
by rw [←coe_eq_empty, coe_Ico, set.Ico_eq_empty_iff]
@[simp] lemma Ioc_eq_empty_iff : Ioc a b = ∅ ↔ ¬a < b :=
by rw [←coe_eq_empty, coe_Ioc, set.Ioc_eq_empty_iff]
@[simp] lemma Ioo_eq_empty_iff [densely_ordered α] : Ioo a b = ∅ ↔ ¬a < b :=
by rw [←coe_eq_empty, coe_Ioo, set.Ioo_eq_empty_iff]
alias Icc_eq_empty_iff ↔ _ finset.Icc_eq_empty
alias Ico_eq_empty_iff ↔ _ finset.Ico_eq_empty
alias Ioc_eq_empty_iff ↔ _ finset.Ioc_eq_empty
@[simp] lemma Ioo_eq_empty (h : ¬a < b) : Ioo a b = ∅ :=
eq_empty_iff_forall_not_mem.2 $ λ x hx, h ((mem_Ioo.1 hx).1.trans (mem_Ioo.1 hx).2)
@[simp] lemma Icc_eq_empty_of_lt (h : b < a) : Icc a b = ∅ := Icc_eq_empty h.not_le
@[simp] lemma Ico_eq_empty_of_le (h : b ≤ a) : Ico a b = ∅ := Ico_eq_empty h.not_lt
@[simp] lemma Ioc_eq_empty_of_le (h : b ≤ a) : Ioc a b = ∅ := Ioc_eq_empty h.not_lt
@[simp] lemma Ioo_eq_empty_of_le (h : b ≤ a) : Ioo a b = ∅ := Ioo_eq_empty h.not_lt
variables (a)
@[simp] lemma Ico_self : Ico a a = ∅ := by rw [←coe_eq_empty, coe_Ico, set.Ico_self]
@[simp] lemma Ioc_self : Ioc a a = ∅ := by rw [←coe_eq_empty, coe_Ioc, set.Ioc_self]
@[simp] lemma Ioo_self : Ioo a a = ∅ := by rw [←coe_eq_empty, coe_Ioo, set.Ioo_self]
variables {a b}
lemma left_mem_Icc : a ∈ Icc a b ↔ a ≤ b := by simp only [mem_Icc, true_and, le_refl]
lemma left_mem_Ico : a ∈ Ico a b ↔ a < b := by simp only [mem_Ico, true_and, le_refl]
lemma right_mem_Icc : b ∈ Icc a b ↔ a ≤ b := by simp only [mem_Icc, and_true, le_refl]
lemma right_mem_Ioc : b ∈ Ioc a b ↔ a < b := by simp only [mem_Ioc, and_true, le_refl]
@[simp] lemma left_not_mem_Ioc : a ∉ Ioc a b := λ h, lt_irrefl _ (mem_Ioc.1 h).1
@[simp] lemma left_not_mem_Ioo : a ∉ Ioo a b := λ h, lt_irrefl _ (mem_Ioo.1 h).1
@[simp] lemma right_not_mem_Ico : b ∉ Ico a b := λ h, lt_irrefl _ (mem_Ico.1 h).2
@[simp] lemma right_not_mem_Ioo : b ∉ Ioo a b := λ h, lt_irrefl _ (mem_Ioo.1 h).2
lemma Ico_filter_lt_of_le_left {a b c : α} [decidable_pred (< c)] (hca : c ≤ a) :
(Ico a b).filter (λ x, x < c) = ∅ :=
finset.filter_false_of_mem (λ x hx, (hca.trans (mem_Ico.1 hx).1).not_lt)
lemma Ico_filter_lt_of_right_le {a b c : α} [decidable_pred (< c)] (hbc : b ≤ c) :
(Ico a b).filter (λ x, x < c) = Ico a b :=
finset.filter_true_of_mem (λ x hx, (mem_Ico.1 hx).2.trans_le hbc)
lemma Ico_filter_lt_of_le_right {a b c : α} [decidable_pred (< c)] (hcb : c ≤ b) :
(Ico a b).filter (λ x, x < c) = Ico a c :=
begin
ext x,
rw [mem_filter, mem_Ico, mem_Ico, and.right_comm],
exact and_iff_left_of_imp (λ h, h.2.trans_le hcb),
end
lemma Ico_filter_le_of_le_left {a b c : α} [decidable_pred ((≤) c)] (hca : c ≤ a) :
(Ico a b).filter (λ x, c ≤ x) = Ico a b :=
finset.filter_true_of_mem (λ x hx, hca.trans (mem_Ico.1 hx).1)
lemma Ico_filter_le_of_right_le {a b : α} [decidable_pred ((≤) b)] :
(Ico a b).filter (λ x, b ≤ x) = ∅ :=
finset.filter_false_of_mem (λ x hx, (mem_Ico.1 hx).2.not_le)
lemma Ico_filter_le_of_left_le {a b c : α} [decidable_pred ((≤) c)] (hac : a ≤ c) :
(Ico a b).filter (λ x, c ≤ x) = Ico c b :=
begin
ext x,
rw [mem_filter, mem_Ico, mem_Ico, and_comm, and.left_comm],
exact and_iff_right_of_imp (λ h, hac.trans h.1),
end
/-- A set with upper and lower bounds in a locally finite order is a fintype -/
def _root_.set.fintype_of_mem_bounds {a b} {s : set α} [decidable_pred (∈ s)]
(ha : a ∈ lower_bounds s) (hb : b ∈ upper_bounds s) : fintype s :=
set.fintype_subset (set.Icc a b) $ λ x hx, ⟨ha hx, hb hx⟩
lemma _root_.bdd_below.finite_of_bdd_above {s : set α} (h₀ : bdd_below s) (h₁ : bdd_above s) :
s.finite :=
let ⟨a, ha⟩ := h₀, ⟨b, hb⟩ := h₁ in by { classical, exact ⟨set.fintype_of_mem_bounds ha hb⟩ }
end preorder
section partial_order
variables [partial_order α] [locally_finite_order α] {a b : α}
@[simp] lemma Icc_self (a : α) : Icc a a = {a} := by rw [←coe_eq_singleton, coe_Icc, set.Icc_self]
section decidable_eq
variables [decidable_eq α]
lemma Icc_erase_left : (Icc a b).erase a = Ioc a b :=
by rw [←coe_inj, coe_erase, coe_Icc, coe_Ioc, set.Icc_diff_left]
lemma Icc_erase_right : (Icc a b).erase b = Ico a b :=
by rw [←coe_inj, coe_erase, coe_Icc, coe_Ico, set.Icc_diff_right]
lemma Ico_insert_right (h : a ≤ b) : insert b (Ico a b) = Icc a b :=
by rw [←coe_inj, coe_insert, coe_Icc, coe_Ico, set.insert_eq, set.union_comm, set.Ico_union_right h]
lemma Ioo_insert_left (h : a < b) : insert a (Ioo a b) = Ico a b :=
by rw [←coe_inj, coe_insert, coe_Ioo, coe_Ico, set.insert_eq, set.union_comm, set.Ioo_union_left h]
@[simp] lemma Ico_inter_Ico_consecutive (a b c : α) : Ico a b ∩ Ico b c = ∅ :=
begin
refine eq_empty_of_forall_not_mem (λ x hx, _),
rw [mem_inter, mem_Ico, mem_Ico] at hx,
exact hx.1.2.not_le hx.2.1,
end
lemma Ico_disjoint_Ico_consecutive (a b c : α) : disjoint (Ico a b) (Ico b c) :=
le_of_eq $ Ico_inter_Ico_consecutive a b c
end decidable_eq
lemma Ico_filter_le_left {a b : α} [decidable_pred (≤ a)] (hab : a < b) :
(Ico a b).filter (λ x, x ≤ a) = {a} :=
begin
ext x,
rw [mem_filter, mem_Ico, mem_singleton, and.right_comm, ←le_antisymm_iff, eq_comm],
exact and_iff_left_of_imp (λ h, h.le.trans_lt hab),
end
lemma card_Ico_eq_card_Icc_sub_one (h : a ≤ b) : (Ico a b).card = (Icc a b).card - 1 :=
begin
classical,
rw [←Ico_insert_right h, card_insert_of_not_mem right_not_mem_Ico],
exact (nat.add_sub_cancel _ _).symm,
end
lemma card_Ioc_eq_card_Icc_sub_one (h : a ≤ b) : (Ioc a b).card = (Icc a b).card - 1 :=
@card_Ico_eq_card_Icc_sub_one (order_dual α) _ _ _ _ h
lemma card_Ioo_eq_card_Ico_sub_one (h : a ≤ b) : (Ioo a b).card = (Ico a b).card - 1 :=
begin
obtain rfl | h' := h.eq_or_lt,
{ rw [Ioo_self, Ico_self, card_empty] },
classical,
rw [←Ioo_insert_left h', card_insert_of_not_mem left_not_mem_Ioo],
exact (nat.add_sub_cancel _ _).symm,
end
lemma card_Ioo_eq_card_Icc_sub_two (h : a ≤ b) : (Ioo a b).card = (Icc a b).card - 2 :=
by { rw [card_Ioo_eq_card_Ico_sub_one h, card_Ico_eq_card_Icc_sub_one h], refl }
end partial_order
section linear_order
variables [linear_order α] [locally_finite_order α] {a b : α}
lemma Ico_subset_Ico_iff {a₁ b₁ a₂ b₂ : α} (h : a₁ < b₁) :
Ico a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ :=
by rw [←coe_subset, coe_Ico, coe_Ico, set.Ico_subset_Ico_iff h]
lemma Ico_union_Ico_eq_Ico {a b c : α} (hab : a ≤ b) (hbc : b ≤ c) :
Ico a b ∪ Ico b c = Ico a c :=
by rw [←coe_inj, coe_union, coe_Ico, coe_Ico, coe_Ico, set.Ico_union_Ico_eq_Ico hab hbc]
lemma Ico_union_Ico' {a b c d : α} (hcb : c ≤ b) (had : a ≤ d) :
Ico a b ∪ Ico c d = Ico (min a c) (max b d) :=
by rw [←coe_inj, coe_union, coe_Ico, coe_Ico, coe_Ico, set.Ico_union_Ico' hcb had]
lemma Ico_union_Ico {a b c d : α} (h₁ : min a b ≤ max c d) (h₂ : min c d ≤ max a b) :
Ico a b ∪ Ico c d = Ico (min a c) (max b d) :=
by rw [←coe_inj, coe_union, coe_Ico, coe_Ico, coe_Ico, set.Ico_union_Ico h₁ h₂]
lemma Ico_inter_Ico {a b c d : α} : Ico a b ∩ Ico c d = Ico (max a c) (min b d) :=
by rw [←coe_inj, coe_inter, coe_Ico, coe_Ico, coe_Ico, ←inf_eq_min, ←sup_eq_max, set.Ico_inter_Ico]
@[simp] lemma Ico_filter_lt (a b c : α) : (Ico a b).filter (λ x, x < c) = Ico a (min b c) :=
begin
cases le_total b c,
{ rw [Ico_filter_lt_of_right_le h, min_eq_left h] },
{ rw [Ico_filter_lt_of_le_right h, min_eq_right h] }
end
@[simp] lemma Ico_filter_le (a b c : α) : (Ico a b).filter (λ x, c ≤ x) = Ico (max a c) b :=
begin
cases le_total a c,
{ rw [Ico_filter_le_of_left_le h, max_eq_right h] },
{ rw [Ico_filter_le_of_le_left h, max_eq_left h] }
end
@[simp] lemma Ico_diff_Ico_left (a b c : α) : (Ico a b) \ (Ico a c) = Ico (max a c) b :=
begin
cases le_total a c,
{ ext x,
rw [mem_sdiff, mem_Ico, mem_Ico, mem_Ico, max_eq_right h, and.right_comm, not_and, not_lt],
exact and_congr_left' ⟨λ hx, hx.2 hx.1, λ hx, ⟨h.trans hx, λ _, hx⟩⟩ },
{ rw [Ico_eq_empty_of_le h, sdiff_empty, max_eq_left h] }
end
@[simp] lemma Ico_diff_Ico_right (a b c : α) : (Ico a b) \ (Ico c b) = Ico a (min b c) :=
begin
cases le_total b c,
{ rw [Ico_eq_empty_of_le h, sdiff_empty, min_eq_left h] },
{ ext x,
rw [mem_sdiff, mem_Ico, mem_Ico, mem_Ico, min_eq_right h, and_assoc, not_and', not_le],
exact and_congr_right' ⟨λ hx, hx.2 hx.1, λ hx, ⟨hx.trans_le h, λ _, hx⟩⟩ }
end
end linear_order
section order_top
variables [preorder α] [order_top α] [locally_finite_order α]
lemma _root_.bdd_below.finite {s : set α} (hs : bdd_below s) : s.finite :=
hs.finite_of_bdd_above $ order_top.bdd_above s
end order_top
section order_bot
variables [preorder α] [order_bot α] [locally_finite_order α]
lemma _root_.bdd_above.finite {s : set α} (hs : bdd_above s) : s.finite := hs.dual.finite
end order_bot
section ordered_cancel_add_comm_monoid
variables [ordered_cancel_add_comm_monoid α] [has_exists_add_of_le α] [decidable_eq α]
[locally_finite_order α]
lemma image_add_left_Icc (a b c : α) : (Icc a b).image ((+) c) = Icc (c + a) (c + b) :=
begin
ext x,
rw [mem_image, mem_Icc],
split,
{ rintro ⟨y, hy, rfl⟩,
rw mem_Icc at hy,
exact ⟨add_le_add_left hy.1 c, add_le_add_left hy.2 c⟩ },
{ intro hx,
obtain ⟨y, hy⟩ := exists_add_of_le hx.1,
rw add_assoc at hy,
rw hy at hx,
exact ⟨a + y, mem_Icc.2 ⟨le_of_add_le_add_left hx.1, le_of_add_le_add_left hx.2⟩, hy.symm⟩ }
end
lemma image_add_left_Ico (a b c : α) : (Ico a b).image ((+) c) = Ico (c + a) (c + b) :=
begin
ext x,
rw [mem_image, mem_Ico],
split,
{ rintro ⟨y, hy, rfl⟩,
rw mem_Ico at hy,
exact ⟨add_le_add_left hy.1 c, add_lt_add_left hy.2 c⟩ },
{ intro hx,
obtain ⟨y, hy⟩ := exists_add_of_le hx.1,
rw add_assoc at hy,
rw hy at hx,
exact ⟨a + y, mem_Ico.2 ⟨le_of_add_le_add_left hx.1, lt_of_add_lt_add_left hx.2⟩, hy.symm⟩ }
end
lemma image_add_left_Ioc (a b c : α) : (Ioc a b).image ((+) c) = Ioc (c + a) (c + b) :=
begin
ext x,
rw [mem_image, mem_Ioc],
refine ⟨_, λ hx, _⟩,
{ rintro ⟨y, hy, rfl⟩,
rw mem_Ioc at hy,
exact ⟨add_lt_add_left hy.1 c, add_le_add_left hy.2 c⟩ },
{ obtain ⟨y, hy⟩ := exists_add_of_le hx.1.le,
rw add_assoc at hy,
rw hy at hx,
exact ⟨a + y, mem_Ioc.2 ⟨lt_of_add_lt_add_left hx.1, le_of_add_le_add_left hx.2⟩, hy.symm⟩ }
end
lemma image_add_left_Ioo (a b c : α) : (Ioo a b).image ((+) c) = Ioo (c + a) (c + b) :=
begin
ext x,
rw [mem_image, mem_Ioo],
refine ⟨_, λ hx, _⟩,
{ rintro ⟨y, hy, rfl⟩,
rw mem_Ioo at hy,
exact ⟨add_lt_add_left hy.1 c, add_lt_add_left hy.2 c⟩ },
{ obtain ⟨y, hy⟩ := exists_add_of_le hx.1.le,
rw add_assoc at hy,
rw hy at hx,
exact ⟨a + y, mem_Ioo.2 ⟨lt_of_add_lt_add_left hx.1, lt_of_add_lt_add_left hx.2⟩, hy.symm⟩ }
end
lemma image_add_right_Icc (a b c : α) : (Icc a b).image (λ x, x + c) = Icc (a + c) (b + c) :=
by { simp_rw add_comm _ c, exact image_add_left_Icc a b c }
lemma image_add_right_Ico (a b c : α) : (Ico a b).image (λ x, x + c) = Ico (a + c) (b + c) :=
by { simp_rw add_comm _ c, exact image_add_left_Ico a b c }
lemma image_add_right_Ioc (a b c : α) : (Ioc a b).image (λ x, x + c) = Ioc (a + c) (b + c) :=
by { simp_rw add_comm _ c, exact image_add_left_Ioc a b c }
lemma image_add_right_Ioo (a b c : α) : (Ioo a b).image (λ x, x + c) = Ioo (a + c) (b + c) :=
by { simp_rw add_comm _ c, exact image_add_left_Ioo a b c }
end ordered_cancel_add_comm_monoid
end finset
|
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include <opencv2/opencv.hpp>
#include <fstream>
#include <vector>
#include <cmath>
#include <map>
#include <ctime>
#include <sstream>
#include <algorithm>
#include <boost/thread/thread.hpp>
#include <ros/ros.h>
#include "std_msgs/String.h"
#include <tf/transform_broadcaster.h>
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/Pose.h>
#include <geometry_msgs/Point.h>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include "colormod.h" // namespace Color
#include "keyboard.h"
#ifndef Included_MATH_HELPER_H
#define Included_MATH_HELPER_H
#include "math_helper.h"
#endif
#ifndef Included_STRING_CONVERTOR_H
#define Included_STRING_CONVERTOR_H
#include "string_convertor.h"
#endif
// MoveIt!
#include <moveit/robot_model_loader/robot_model_loader.h>
#include <moveit/robot_model/robot_model.h>
#include <moveit/robot_state/robot_state.h>
// Robot state publishing
#include <moveit/robot_state/conversions.h>
#include <moveit_msgs/DisplayRobotState.h>
// Kinematics
#include <moveit_msgs/GetPositionIK.h>
#include <geometry_msgs/Point.h>
#include <geometry_msgs/Pose.h>
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/Quaternion.h>
//wam
#include "wam_msgs/MatrixMN.h"
#include "wam_srvs/JointMove.h"
#include "sensor_msgs/JointState.h"
#include "pose_helper.h"
using namespace std;
bool commandLock = false;
Color::Modifier c_red(Color::FG_RED);
Color::Modifier c_yellow(Color::FG_YELLOW);
Color::Modifier c_green(Color::FG_GREEN);
Color::Modifier c_default(Color::FG_DEFAULT);
int dofNum = 7;
bool lock = false;
bool ready_signal1 = false;
bool ready_signal2 = false;
bool ready_signal3 = false;
double step_size = 0.02;//m
double current_pos[]={9999, 9999, 9999, 9999, 9999, 9999, 9999};//initialize as an invalid value set, stores the current pose
std::vector<double> joint_values; //IK solutions
moveit::core::RobotModelPtr kinematic_model;
wam_srvs::JointMove mv_srv;
ros::ServiceClient Joint_move_client ;
geometry_msgs::Pose thisPose;
ros::Publisher pubCommand;
cv::Mat readTransformation()
{
std::ifstream transform_file;
std::string transform_file_path = "/home/chris/catkin_ws/src/long_range_teleoperation/robot-side/3_Calibration_Solver/result.txt";
transform_file.open(transform_file_path.c_str(), std::ios_base::in | std::ios_base::binary);
if(!transform_file) {
std::cerr << "Can't open transform file" << std::endl;
std::exit(-1);
}
cv::Mat transformation(4,4,cv::DataType<double>::type);
std::string line;
int i = 0;
while(getline(transform_file, line) && i < 4) {
std::istringstream in(line);
double c1, c2, c3, c4;
in >> c1 >> c2 >> c3 >> c4;
transformation.at<double>(i,0) = c1;
transformation.at<double>(i,1) = c2;
transformation.at<double>(i,2) = c3;
transformation.at<double>(i,3) = c4;
++i;
}
std::cout <<"calibration solver result: "<<endl<< transformation <<std::endl;
return transformation;
}
std::vector<double> targetTransformation(double x, double y, double z)
{
cv::Mat transformationMatrix = readTransformation();
cv::Mat t(4,1,cv::DataType<double>::type);
t.at<double>(0,0) = x;
t.at<double>(1,0) = y;
t.at<double>(2,0) = z;
t.at<double>(3,0) = 1;
cv::Mat result = transformationMatrix * t;
std::vector<double> rv;
rv.push_back(result.at<double>(0,0)/result.at<double>(3,0));
rv.push_back(result.at<double>(1,0)/result.at<double>(3,0));
rv.push_back(result.at<double>(2,0)/result.at<double>(3,0));
return rv;
}
void wamPoseCallback(const geometry_msgs::PoseStamped::ConstPtr& msg)
{
//cout<<"wam msgs"<<endl;
thisPose = msg->pose;
ready_signal1 = true;
}
void wamJointsCallback(const sensor_msgs::JointState::ConstPtr& msg)
{
//cout<<"joint pose obtained:"<<endl;//<<initial_Joint_pose[1]<<endl;
//cout<<initial_Joint_pose[0]<<" "<<initial_Joint_pose[1]<<" "<<initial_Joint_pose[2]<<" "<<initial_Joint_pose[3]<<" "<< initial_Joint_pose[4]
// <<" "<<initial_Joint_pose[5]<<" "<<initial_Joint_pose[6]<<endl;
current_pos[0]=msg->position[0];
current_pos[1]=msg->position[1];
current_pos[2]=msg->position[2];
current_pos[3]=msg->position[3];
current_pos[4]=msg->position[4];
current_pos[5]=msg->position[5];
current_pos[6]=msg->position[6];
ready_signal2 = true;
}
void moveRobotJointValue(std::vector<double> joint_values_t)
{
lock=true;
std::vector<float> jnts;
for(size_t i=0;i<dofNum;i++)
{
float newJ = (float)(joint_values_t[i]);
jnts.push_back(newJ);
}
mv_srv.request.joints = jnts;
cout<<"send to robot to the position "<<endl;
string_convertor::printOutStdVector_f(jnts);
cout << "Press any key to move..." << endl;
getchar();
Joint_move_client.call(mv_srv);///////////////////////////////////////////////////
//boost::this_thread::sleep( boost::posix_time::milliseconds(1000) );
lock=false;
}
geometry_msgs::Pose comput_fk(double currentJoints[]) //get current end effector pose
{
robot_state::RobotStatePtr kinematic_state(new robot_state::RobotState(kinematic_model));
//fill in the seed
kinematic_state->setVariablePositions(currentJoints);
cout<<"compute fk current joints "<<currentJoints[0]<<", "<<currentJoints[1]<<", "<<currentJoints[2]<<endl;
kinematic_state->update();
const Eigen::Affine3d end_effector_state = kinematic_state->getGlobalLinkTransform("wam/wrist_palm_link");//table_base
ROS_INFO_STREAM("FK Translation: " << end_effector_state.translation());
Eigen::Quaterniond rot_q(end_effector_state.rotation());
ROS_INFO_STREAM("FK Rotation q x: " << rot_q.x());
ROS_INFO_STREAM("FK Rotation q y: " << rot_q.y());
ROS_INFO_STREAM("FK Rotation q z: " << rot_q.z());
ROS_INFO_STREAM("FK Rotation q w: " << rot_q.w());
geometry_msgs::Pose p;
p.position.x = end_effector_state.translation()(0);
p.position.y = end_effector_state.translation()(1);
p.position.z = end_effector_state.translation()(2);
p.orientation.x = rot_q.x();
p.orientation.y = rot_q.y();
p.orientation.z = rot_q.z();
p.orientation.w = rot_q.w();
return p;
}
bool comput_IK(geometry_msgs::Pose p, double referenceJoints[])
{
robot_state::RobotStatePtr kinematic_state(new robot_state::RobotState(kinematic_model));
const robot_state::JointModelGroup* joint_model_group = kinematic_model->getJointModelGroup("arm");//All, it's in the planning group name
// const std::vector<std::string> &joint_names2 = joint_model_group->getJointModelNames();
// joint_names2=string_convertor::safeRemoveStringVec(joint_names2,0);//first item of joint name is caused by mistake
// cout<<"joint names count "<<joint_names2.size()<<endl;//8
//fill in the seed
kinematic_state->setVariablePositions(referenceJoints);
cout<<"compute IK current joints "<<referenceJoints[0]<<", "<<referenceJoints[1]<<", "<<referenceJoints[2]<<endl;
kinematic_state->update();
bool found_ik = kinematic_state->setFromIK(joint_model_group, p, 10, 0.1);
// Now, we can print out the IK solution (if found):
if (found_ik)
{
kinematic_state->copyJointGroupPositions(joint_model_group, joint_values);
cout<<c_green<<"IK solution found: ";
for(std::size_t i=0; i < joint_values.size(); ++i)
{
ROS_INFO("IK solution Joint %s: %f", to_string(i+1).c_str(), joint_values[i]);
cout<<joint_values[i]<<",";
}
cout<<c_default<<endl;
}
else
{
ROS_INFO("Did not find IK solution");
}
return found_ik;
}
void test_IK_FK()
{
geometry_msgs::Pose pose = comput_fk(current_pos);
cout<<"using pose to test "<<endl;
cout<<"x "<<pose.position.x <<" y "<<pose.position.y<<" z "<<pose.position.z<<endl;
bool ik_found = comput_IK(pose, current_pos);
if(ik_found)
{
ROS_INFO("asdaf");
}
}
void printPose(geometry_msgs::Pose pose)
{
cout<<"x "<<pose.position.x <<" y "<<pose.position.y<<" z "<<pose.position.z<<endl;
cout<<"qx: "<<pose.orientation.x <<" qy: "<<pose.orientation.y<<" qz: "<<pose.orientation.z<<" qw: "<< pose.orientation.w<<endl;
}
void execute2target(geometry_msgs::Pose targetRobotPose)
{
cout<<c_red<<"New target: "<<endl;
printPose(targetRobotPose);
cout<<c_red<<"press key to continue"<<c_default<<endl;
ready_signal1=false;ready_signal2=false;
while(!ready_signal1&&!ready_signal2)
{
ros::spinOnce();
boost::this_thread::sleep( boost::posix_time::milliseconds(100) );
cout<<"wait for ready_signal1 and ready_signal2"<<endl;
}
cout<<"robot joints and poses values updated!"<<endl;
geometry_msgs::Pose initial_robot_pose = thisPose;
geometry_msgs::Pose initial_FK_pose = comput_fk(current_pos);
cout<<c_green<<" corr FK target is: "<<endl;
printPose(pose_helper::convert2FKtarget(initial_FK_pose, initial_robot_pose, targetRobotPose));
cout<<c_default;
cout<<"initial robot pose"<<endl;
printPose(initial_robot_pose);
cout<<"initial FK pose"<<endl;
printPose(initial_FK_pose);
int steps_num = pose_helper::get_steps_num(initial_robot_pose, targetRobotPose, step_size);
cout<<"steps Number for this target: "<<steps_num<<endl;
getchar();
for(int i=0; i< steps_num; i++)
{
geometry_msgs::Pose step_pose = pose_helper::next_step_pose(initial_FK_pose, initial_robot_pose, targetRobotPose, i+1, steps_num);
cout<<c_red;
cout<<"step "<<(i+1)<<" target, out of "<<steps_num<<endl;
printPose(step_pose);
cout<<c_default;
//this step_pose is represented in IK sovler's frame now.
bool ik_found = comput_IK(step_pose, current_pos);
if(ik_found)
{
moveRobotJointValue(joint_values);
cout<<c_yellow;
ROS_INFO("robot moved ");
cout<<c_default;
//update joint values
current_pos[0]=joint_values[0];
current_pos[1]=joint_values[1];
current_pos[2]=joint_values[2];
current_pos[3]=joint_values[3];
current_pos[4]=joint_values[4];
current_pos[5]=joint_values[5];
current_pos[6]=joint_values[6];
// ready_signal2 = false;
// while(!ready_signal2)
// {
// ros::spinOnce();
// boost::this_thread::sleep( boost::posix_time::milliseconds(100) );
// cout<<"wait for ready_signal2"<<endl;
// }
}
else
i = i -1;
cout<<"loop index : "<<i<<endl;
}
cout<<"haha, task accomplished!"<<endl;
}
void udpCommandCallback(const std_msgs::String::ConstPtr& msg)
{
if(commandLock)
{
cout<<c_red<<"command locked!"<<endl<<c_default;
return;
}
//send the command to remote robot
cout<<"recved: "<<msg->data<<endl;//<<msg->data<<endl;
if(msg->data.find("coarse_target_move") != std::string::npos && !commandLock) //fine our command
{
//execute command
commandLock = true;
std::vector<string> straa = string_convertor::split(msg->data, ':');
string datastr = straa[2];
std::vector<double> dataValues = string_convertor::split2double(datastr, ',');
std::vector<double> transformedResult = targetTransformation(dataValues[0], dataValues[1], dataValues[2]);
geometry_msgs::Pose target_robot_pose = pose_helper::construct_geometry_pose(transformedResult[0], transformedResult[1], transformedResult[2], (int)(dataValues[3]));
cout<<c_green<<"go to execution phase"<<endl<<c_default;
execute2target(target_robot_pose);
// std_msgs::String msg;
// msg.data = "";
// pubCommand.publish(msg); //clear the command buffer.
commandLock = false;
}
if(msg->data.find("way_point_move") != std::string::npos && !commandLock) //fine our command
{
//execute command
//way_point_move:1:x,y,z,qx,qy,qz,qw,.........
commandLock = true;
std::vector<string> straa = string_convertor::split(msg->data, ':');
string datastr = straa[2];
std::vector<double> dataValues = string_convertor::split2double(datastr, ',');
geometry_msgs::Pose target_robot_pose;
target_robot_pose.position.x = dataValues[0]
target_robot_pose.position.y = dataValues[1]
target_robot_pose.position.z = dataValues[2]
target_robot_pose.orientation.x = dataValues[3]
target_robot_pose.orientation.y = dataValues[4]
target_robot_pose.orientation.z = dataValues[5]
target_robot_pose.orientation.w = dataValues[6]
cout<<c_green<<"go to execution phase"<<endl<<c_default;
execute2target(target_robot_pose);
// std_msgs::String msg;
// msg.data = "";
// pubCommand.publish(msg); //clear the command buffer.
commandLock = false;
}
}
//===========================MAIN FUNCTION START===========================
int main(int argc, char* argv[]){
// Initialize the ROS system and become a node.
// if(argc==2)
// numThres = atoi(argv[1]);
ros::init(argc, argv, "tele_op");
ros::NodeHandle n("~");
ros::Subscriber subP = n.subscribe("/zeus/wam/pose", 1, wamPoseCallback);
ros::Subscriber wam_joints_sub=n.subscribe("/zeus/wam/joint_states",1, wamJointsCallback);
ros::Subscriber udp_tasks=n.subscribe("/udp/command",1, udpCommandCallback);
//pubCommand = n.advertise<std_msgs::String>("/udp/command", 1, true);
Joint_move_client = n.serviceClient<wam_srvs::JointMove>("/zeus/wam/joint_move");
robot_model_loader::RobotModelLoader robot_model_loader("robot_description");
kinematic_model = robot_model_loader.getModel();
ROS_INFO("Model frame: %s", kinematic_model->getModelFrame().c_str());
commandLock = true;
test_IK_FK();
//std::vector<double> testrestulst = targetTransformation(-0.0632346, 0.0754276, 0.728763);
//cout<<"target transofrmation: "<<testrestulst[0]<<" "<<testrestulst[1]<<" "<<testrestulst[2]<<endl;
cout<<"press key to continue"<<endl;
getchar();
while(!ready_signal1)
{
ros::spinOnce();
boost::this_thread::sleep( boost::posix_time::milliseconds(100) );
cout<<"wait for readySignal 1 in main"<<endl;
}
commandLock = false;
cout<<"readySignal1 Received! goto main loop. CommandLock set to false."<<endl;
// int presetMark = 3; //press button -0.08, -0.69, 0.17, 3./// handler 0.4, 0, 0.4, 1
// geometry_msgs::Pose target_robot_pose = pose_helper::construct_geometry_pose(0.4, 0, 0.4, 1);
// execute2target(target_robot_pose);
ros::spin();
ros::waitForShutdown();
}
|
/-
Copyright (c) 2020 The Xena project. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Buzzard.
Thanks: Imperial College London, leanprover-community
-/
-- Import levels 1 to 3
import complex.kb_solutions.Level_03_conj
/-!
# Level 4: Norms
Define `norm_sq : ℂ → ℝ` by defining `norm_sq(z)` to be
`re(z)*re(z)+im(z)*im(z)` and see what you can prove about it.
-/
namespace complex
/-- The real number which is the squared norm of z -/
def norm_sq (z : ℂ) : ℝ := re(z)*re(z)+im(z)*im(z)
local attribute [simp] ext_iff
-- next few proofs are are all mostl simp [norm_sq] so let's locally
-- tell simp about it for this section only
section simp_knows_norm_sq
local attribute [simp] norm_sq
/-! ## Behaviour with respect to 0, 1 and I -/
@[simp] lemma norm_sq_zero : norm_sq 0 = 0 := by simp
@[simp] lemma norm_sq_one : norm_sq 1 = 1 := by simp
@[simp] lemma norm_sq_I : norm_sq I = 1 := by simp
/-! ## Behaviour with respect to *, + and - -/
@[simp] lemma norm_sq_mul (z w : ℂ) : norm_sq (z * w) = norm_sq z * norm_sq w :=
by simp; ring
lemma norm_sq_add (z w : ℂ) : norm_sq (z + w) =
norm_sq z + norm_sq w + 2 * (z * conj w).re :=
by simp; ring
@[simp] lemma norm_sq_neg (z : ℂ) : norm_sq (-z) = norm_sq z :=
by simp
/-! ## Behaviour with respect to `conj` -/
@[simp] lemma norm_sq_conj (z : ℂ) : norm_sq (conj z) = norm_sq z :=
by simp
/-! ## Behaviour with respect to real numbers` -/
@[simp] lemma norm_sq_of_real (r : ℝ) : norm_sq r = r * r :=
by simp
theorem mul_conj (z : ℂ) : z * conj z = norm_sq z :=
by simp; ring
-- time to end the section; simp no longer knows about norm_sq
end simp_knows_norm_sq
/-! ## Behaviour with respect to real 0, ≤, < and so on -/
-- Warning: you will have to know something about Lean's API for
-- real numbers to solve these ones. If you turn the statements about
-- complex numbers into statements about real numbers, you'll find
-- they're of the form "prove $$x^2+y^2\geq0$$" with `x` and `y` real.
example (y : ℝ) : 0 ≤ y * y := mul_self_nonneg y
namespace realtac
lemma norm_nonneg (x y : ℝ) : 0 ≤ x * x + y * y :=
begin
nlinarith,
end
lemma norm_eq_zero_iff {x y : ℝ} : x * x + y * y = 0 ↔ x = 0 ∧ y = 0 :=
begin
split,
{ intro h,
rw add_eq_zero_iff' at h,
{ simp * at *},
{ apply mul_self_nonneg},
{ apply mul_self_nonneg}},
{ rintros ⟨rfl, rfl⟩,
simp,
}
end
lemma norm_nonpos_right {x y : ℝ} (h1 : x * x + y * y ≤ 0) : y = 0 :=
begin
suffices : x = 0 ∧ y = 0,
simp [this],
rw ←norm_eq_zero_iff,
linarith [norm_nonneg x y],
end
lemma norm_nonpos_left (x y : ℝ) (h1 : x * x + y * y ≤ 0) : x = 0 :=
begin
rw add_comm at h1,
apply norm_nonpos_right h1,
end
end realtac
-- back to the levels
lemma norm_sq_nonneg (z : ℂ) : 0 ≤ norm_sq z :=
begin
cases z with x y,
simp [norm_sq],
apply realtac.norm_nonneg,
end
@[simp] lemma norm_sq_eq_zero (z : ℂ) : norm_sq z = 0 ↔ z = 0 :=
begin
cases z with x y,
simp [norm_sq],
exact realtac.norm_eq_zero_iff
end
@[simp] lemma norm_sq_ne_zero {z : ℂ} : norm_sq z ≠ 0 ↔ z ≠ 0 :=
begin
have h := norm_sq_eq_zero z,
tauto!
end
@[simp] lemma norm_sq_pos {z : ℂ} : 0 < norm_sq z ↔ z ≠ 0 :=
begin
rw lt_iff_le_and_ne,
rw ne_comm,
simp [norm_sq_nonneg],
end
lemma re_sq_le_norm_sq (z : ℂ) : z.re * z.re ≤ norm_sq z :=
begin
simp [norm_sq],
apply mul_self_nonneg,
end
lemma im_sq_le_norm_sq (z : ℂ) : z.im * z.im ≤ norm_sq z :=
begin
simp [norm_sq],
apply mul_self_nonneg
end
end complex
|
module Avionics.Real where
open import Algebra.Definitions using (LeftIdentity; RightIdentity; Commutative)
open import Data.Bool using (Bool; _∧_)
open import Data.Float using (Float)
open import Data.Maybe using (Maybe; just; nothing)
open import Data.Nat using (ℕ)
open import Level using (0ℓ; _⊔_) renaming (suc to lsuc)
open import Relation.Binary using (Decidable; _Preserves_⟶_)
open import Relation.Binary.Definitions using (Transitive; Trans)
open import Relation.Binary.PropositionalEquality using (_≡_; refl)
open import Relation.Nullary using (Dec; yes; no)
open import Relation.Nullary.Decidable using (False; ⌊_⌋)
open import Relation.Unary using (Pred; _∈_)
infix 4 _<_ _≤_ _<ᵇ_ _≤ᵇ_
infixl 6 _+_ _-_
infixl 7 _*_
infix 4 _≟_
postulate
ℝ : Set
-- TODO: `fromFloat` should return `Maybe ℝ`
fromFloat : Float → ℝ
toFloat : ℝ → Float
fromℕ : ℕ → ℝ
_+_ _*_ _^_ : ℝ → ℝ → ℝ
-_ abs _^2 : ℝ → ℝ
e π 0ℝ 1ℝ -1/2 1/2 2ℝ : ℝ
-- This was inspired on how the standard library handles things.
-- See: https://plfa.github.io/Decidable/
_<_ _≤_ : ℝ → ℝ → Set
_≟_ : Decidable {A = ℝ} _≡_
_≤?_ : (m n : ℝ) → Dec (m ≤ n)
_<?_ : (m n : ℝ) → Dec (m < n)
_<ᵇ_ _≤ᵇ_ _≡ᵇ_ : ℝ → ℝ → Bool
p <ᵇ q = ⌊ p <? q ⌋
p ≤ᵇ q = ⌊ p ≤? q ⌋
p ≡ᵇ q = ⌊ p ≟ q ⌋
_≢0 : ℝ → Set
p ≢0 = False (p ≟ 0ℝ)
Subset : Set → Set _
Subset A = Pred A 0ℓ
-- Dangerous definitions, but necessary!
postulate
⟨0,∞⟩ [0,∞⟩ [0,1] : Subset ℝ
1/_ : (p : ℝ) → ℝ
√_ : (x : ℝ) → ℝ
_÷_ : (p q : ℝ) → ℝ
(p ÷ q) = p * (1/ q)
-- Dangerous definitions, but necessary!
postulate
m÷n<o≡m<o*n : ∀ m n o → (m ÷ n <ᵇ o) ≡ (m <ᵇ o * n)
m<o÷n≡m*n<o : ∀ m n o → (m <ᵇ o ÷ n) ≡ (m * n <ᵇ o)
_-_ : ℝ → ℝ → ℝ
p - q = p + (- q)
postulate
double-neg : ∀ (x y : ℝ) → y - (y - x) ≡ x
neg-involutive : ∀ x → -(- x) ≡ x
neg-distrib-+ : ∀ m n → - (m + n) ≡ (- m) + (- n)
neg-def : ∀ m → 0ℝ - m ≡ - m
m-m≡0 : ∀ m → m - m ≡ 0ℝ
neg-distribˡ-* : ∀ x y → - (x * y) ≡ (- x) * y
√x^2≡absx : ∀ x → √ (x ^2) ≡ abs x
>0→≢0 : ∀ {x : ℝ} → x ∈ ⟨0,∞⟩ → x ≢0
>0→≥0 : ∀ {x : ℝ} → x ∈ ⟨0,∞⟩ → x ∈ [0,∞⟩
>0*>0→>0 : ∀ {p q : ℝ} → p ∈ ⟨0,∞⟩ → q ∈ ⟨0,∞⟩ → (p * q) ∈ ⟨0,∞⟩
≢0*≢0→≢0 : ∀ {p q : ℝ} → p ≢0 → q ≢0 → (p * q) ≢0
2>0 : 2ℝ ∈ ⟨0,∞⟩
π>0 : π ∈ ⟨0,∞⟩
e^x>0 : (x : ℝ) → (e ^ x) ∈ ⟨0,∞⟩
x*x≡x^2 : ∀ x → x * x ≡ x ^2
x^2*y^2≡⟨xy⟩^2 : ∀ x y → (x ^2) * (y ^2) ≡ (x * y)^2
1/x^2≡⟨1/x⟩^2 : ∀ x → 1/ (x ^2) ≡ (1/ x)^2
--√q≥0 : (q : ℝ) → (0≤q : q ∈ [0,∞⟩) → (√ q) {0≤q} ∈ [0,∞⟩
--q>0→√q>0 : {q : ℝ} → (0<q : q ∈ ⟨0,∞⟩) → (√ q) {>0→≥0 0<q} ∈ ⟨0,∞⟩
0≤→[0,∞⟩ : {n : ℝ} → 0ℝ ≤ n → n ∈ [0,∞⟩
0<→⟨0,∞⟩ : {n : ℝ} → 0ℝ < n → n ∈ ⟨0,∞⟩
[0,∞⟩→0≤ : {n : ℝ} → n ∈ [0,∞⟩ → 0ℝ ≤ n
⟨0,∞⟩→0< : {n : ℝ} → n ∈ ⟨0,∞⟩ → 0ℝ < n
m≤n→m-p≤n-p : {m n p : ℝ} → m ≤ n → m - p ≤ n - p
m<n→m-p<n-p : {m n p : ℝ} → m < n → m - p < n - p
-- trans-≤ reduces to: {i j k : ℝ} → i ≤ j → j ≤ k → i ≤ k
trans-≤ : Transitive _≤_
<-transˡ : Trans _<_ _≤_ _<_
--+-identityˡ : LeftIdentity 0ℝ _+_
--+-identityʳ : RightIdentity 0ℝ _+_
+-identityˡ : ∀ x → 0ℝ + x ≡ x
+-identityʳ : ∀ x → x + 0ℝ ≡ x
--+-comm : Commutative _+_
+-comm : ∀ m n → m + n ≡ n + m
--+-assoc : Associative _+_
+-assoc : ∀ m n o → m + (n + o) ≡ (m + n) + o
*-comm : ∀ m n → m * n ≡ n * m
*-assoc : ∀ m n o → m * (n * o) ≡ (m * n) * o
--0ℝ ≟_
0≟0≡yes0≡0 : (0ℝ ≟ 0ℝ) ≡ yes refl
-- TODO: These properties should be written for _<_ instead of _<ᵇ_
abs<x→<x∧-x< : ∀ {u x} → (abs u <ᵇ x) ≡ ((u <ᵇ x) ∧ (- x <ᵇ u))
--neg-mono-<-> : -_ Preserves _<_ ⟶ (λ a b -> b < a)
neg-mono-<-> : ∀ m n → (m <ᵇ n) ≡ (- n <ᵇ - m)
--+-monoˡ-< : ∀ n → (_+ n) Preserves _<_ ⟶ _<_
+-monoˡ-< : ∀ n o p → (o <ᵇ p) ≡ (n + o <ᵇ n + p)
-- One of the weakest points in the whole library architecture!!!
-- This is wrong, really wrong, but useful
{-# COMPILE GHC ℝ = type Double #-}
{-# COMPILE GHC fromFloat = \x -> x #-}
{-# COMPILE GHC toFloat = \x -> x #-}
{-# COMPILE GHC fromℕ = fromIntegral #-}
{-# COMPILE GHC _<ᵇ_ = (<) #-}
{-# COMPILE GHC _≤ᵇ_ = (<=) #-}
{-# COMPILE GHC _≡ᵇ_ = (==) #-}
{-# COMPILE GHC _+_ = (+) #-}
{-# COMPILE GHC _-_ = (-) #-}
{-# COMPILE GHC _*_ = (*) #-}
{-# COMPILE GHC _^_ = (**) #-}
{-# COMPILE GHC _^2 = (**2) #-}
{-# COMPILE GHC e = 2.71828182845904523536 #-}
{-# COMPILE GHC π = 3.14159265358979323846 #-}
{-# COMPILE GHC 0ℝ = 0 #-}
{-# COMPILE GHC 1ℝ = 1 #-}
{-# COMPILE GHC 2ℝ = 2 #-}
{-# COMPILE GHC -1/2 = -1/2 #-}
-- REAAALY CAREFUL WITH THIS!
-- TODO: Add some runtime checking to this. Fail hard if divisor is zero
{-# COMPILE GHC 1/_ = \x -> (1/x) #-}
{-# COMPILE GHC _÷_ = \x y -> (x/y) #-}
{-# COMPILE GHC √_ = \x -> sqrt x #-}
|
$ Declare
SUBROUTINE ReadStressRanges (nr, ntot, sfile, ncc)
!
!
! Parameters
USE PublicPar
IMPLICIT NONE
!
INTEGER, INTENT(IN) :: nr ! Period number
DOUBLE PRECISION, INTENT(IN) :: ntot ! Number of cycles in that period
CHARACTER, INTENT(IN) :: sfile*100 ! File with stress range histogram for that period
INTEGER, INTENT(OUT) :: ncc ! Number of rows in that file
!
! Declarations
DOUBLE PRECISION :: factn, nfile
INTEGER :: i, j
!
! Initialise stress spectrum file
DO i = 1, 3
DO j = 1, 100
Spect (i,j,nr) = 0.D0
END DO
END DO
!
! Stress ranges
nfile = 0.D0
OPEN(8,file=sfile,status='old')
DO j = 1, 101
READ (8,*,END=99) Spect(1,j,nr), Spect(2,j,nr), Spect(3,j,nr)
nfile = nfile + Spect(1,j,nr)
IF (j.EQ.101) STOP 'Error in subroutine ReadStressRanges: Max. no of rows in stress spectrum file = 100'
END DO
99 CONTINUE
ncc = j-1
factn = ntot / nfile
write(*,*) factn, ntot, nfile
DO j = 1, ncc
Spect(1,j,nr) = Spect(1,j,nr) * factn
END DO
CLOSE(8)
!
! Einde subroutine
RETURN
END |
# An Intro to DifferentialEquations.jl
### Chris Rackauckas
## Basic Introduction Via Ordinary Differential Equations
This notebook will get you started with DifferentialEquations.jl by introducing you to the functionality for solving ordinary differential equations (ODEs). The corresponding documentation page is the [ODE tutorial](http://docs.juliadiffeq.org/latest/tutorials/ode_example.html). While some of the syntax may be different for other types of equations, the same general principles hold in each case. Our goal is to give a gentle and thorough introduction that highlights these principles in a way that will help you generalize what you have learned.
### Background
If you are new to the study of differential equations, it can be helpful to do a quick background read on [the definition of ordinary differential equations](https://en.wikipedia.org/wiki/Ordinary_differential_equation). We define an ordinary differential equation as an equation which describes the way that a variable $u$ changes, that is
$$u' = f(u,p,t)$$
where $p$ are the parameters of the model, $t$ is the time variable, and $f$ is the nonlinear model of how $u$ changes. The initial value problem also includes the information about the starting value:
$$u(t_0) = u_0$$
Together, if you know the starting value and you know how the value will change with time, then you know what the value will be at any time point in the future. This is the intuitive definition of a differential equation.
### First Model: Exponential Growth
Our first model will be the canonical exponential growth model. This model says that the rate of change is proportional to the current value, and is this:
$$u' = au$$
where we have a starting value $u(0)=u_0$. Let's say we put 1 dollar into Bitcoin which is increasing at a rate of $98\%$ per year. Then calling now $t=0$ and measuring time in years, our model is:
$$u' = 0.98u$$
and $u(0) = 1.0$. We encode this into Julia by noticing that, in this setup, we match the general form when
```julia
f(u,p,t) = 0.98u
```
with $ u_0 = 1.0 $. If we want to solve this model on a time span from `t=0.0` to `t=1.0`, then we define an `ODEProblem` by specifying this function `f`, this initial condition `u0`, and this time span as follows:
```julia
using DifferentialEquations
f(u,p,t) = 0.98u
u0 = 1.0
tspan = (0.0,1.0)
prob = ODEProblem(f,u0,tspan)
```
To solve our `ODEProblem` we use the command `solve`.
```julia
sol = solve(prob)
```
and that's it: we have succesfully solved our first ODE!
#### Analyzing the Solution
Of course, the solution type is not interesting in and of itself. We want to understand the solution! The documentation page which explains in detail the functions for analyzing the solution is the [Solution Handling](http://docs.juliadiffeq.org/latest/basics/solution.html) page. Here we will describe some of the basics. You can plot the solution using the plot recipe provided by [Plots.jl](http://docs.juliaplots.org/latest/):
```julia
using Plots; gr()
plot(sol)
```
From the picture we see that the solution is an exponential curve, which matches our intuition. As a plot recipe, we can annotate the result using any of the [Plots.jl attributes](http://docs.juliaplots.org/latest/attributes/). For example:
```julia
plot(sol,linewidth=5,title="Solution to the linear ODE with a thick line",
xaxis="Time (t)",yaxis="u(t) (in μm)",label="My Thick Line!") # legend=false
```
Using the mutating `plot!` command we can add other pieces to our plot. For this ODE we know that the true solution is $u(t) = u_0 exp(at)$, so let's add some of the true solution to our plot:
```julia
plot!(sol.t, t->1.0*exp(0.98t),lw=3,ls=:dash,label="True Solution!")
```
In the previous command I demonstrated `sol.t`, which grabs the array of time points that the solution was saved at:
```julia
sol.t
```
We can get the array of solution values using `sol.u`:
```julia
sol.u
```
`sol.u[i]` is the value of the solution at time `sol.t[i]`. We can compute arrays of functions of the solution values using standard comprehensions, like:
```julia
[t+u for (u,t) in tuples(sol)]
```
However, one interesting feature is that, by default, the solution is a continuous function. If we check the print out again:
```julia
sol
```
you see that it says that the solution has a order changing interpolation. The default algorithm automatically switches between methods in order to handle all types of problems. For non-stiff equations (like the one we are solving), it is a continuous function of 4th order accuracy. We can call the solution as a function of time `sol(t)`. For example, to get the value at `t=0.45`, we can use the command:
```julia
sol(0.45)
```
#### Controlling the Solver
DifferentialEquations.jl has a common set of solver controls among its algorithms which can be found [at the Common Solver Options](http://docs.juliadiffeq.org/latest/basics/common_solver_opts.html) page. We will detail some of the most widely used options.
The most useful options are the tolerances `abstol` and `reltol`. These tell the internal adaptive time stepping engine how precise of a solution you want. Generally, `reltol` is the relative accuracy while `abstol` is the accuracy when `u` is near zero. These tolerances are local tolerances and thus are not global guarantees. However, a good rule of thumb is that the total solution accuracy is 1-2 digits less than the relative tolerances. Thus for the defaults `abstol=1e-6` and `reltol=1e-3`, you can expect a global accuracy of about 1-2 digits. If we want to get around 6 digits of accuracy, we can use the commands:
```julia
sol = solve(prob,abstol=1e-8,reltol=1e-8)
```
Now we can see no visible difference against the true solution:
```julia
plot(sol)
plot!(sol.t, t->1.0*exp(0.98t),lw=3,ls=:dash,label="True Solution!")
```
Notice that by decreasing the tolerance, the number of steps the solver had to take was `9` instead of the previous `5`. There is a trade off between accuracy and speed, and it is up to you to determine what is the right balance for your problem.
Another common option is to use `saveat` to make the solver save at specific time points. For example, if we want the solution at an even grid of `t=0.1k` for integers `k`, we would use the command:
```julia
sol = solve(prob,saveat=0.1)
```
Notice that when `saveat` is used the continuous output variables are no longer saved and thus `sol(t)`, the interpolation, is only first order. We can save at an uneven grid of points by passing a collection of values to `saveat`. For example:
```julia
sol = solve(prob,saveat=[0.2,0.7,0.9])
```
If we need to reduce the amount of saving, we can also turn off the continuous output directly via `dense=false`:
```julia
sol = solve(prob,dense=false)
```
and to turn off all intermediate saving we can use `save_everystep=false`:
```julia
sol = solve(prob,save_everystep=false)
```
If we want to solve and only save the final value, we can even set `save_start=false`.
```julia
sol = solve(prob,save_everystep=false,save_start = false)
```
Note that similarly on the other side there is `save_end=false`.
More advanced saving behaviors, such as saving functionals of the solution, are handled via the `SavingCallback` in the [Callback Library](http://docs.juliadiffeq.org/latest/features/callback_library.html#SavingCallback-1) which will be addressed later in the tutorial.
#### Choosing Solver Algorithms
There is no best algorithm for numerically solving a differential equation. When you call `solve(prob)`, DifferentialEquations.jl makes a guess at a good algorithm for your problem, given the properties that you ask for (the tolerances, the saving information, etc.). However, in many cases you may want more direct control. A later notebook will help introduce the various *algorithms* in DifferentialEquations.jl, but for now let's introduce the *syntax*.
The most crucial determining factor in choosing a numerical method is the stiffness of the model. Stiffness is roughly characterized by a Jacobian `f` with large eigenvalues. That's quite mathematical, and we can think of it more intuitively: if you have big numbers in `f` (like parameters of order `1e5`), then it's probably stiff. Or, as the creator of the MATLAB ODE Suite, Lawrence Shampine, likes to define it, if the standard algorithms are slow, then it's stiff. We will go into more depth about diagnosing stiffness in a later tutorial, but for now note that if you believe your model may be stiff, you can hint this to the algorithm chooser via `alg_hints = [:stiff]`.
```julia
sol = solve(prob,alg_hints=[:stiff])
```
Stiff algorithms have to solve implicit equations and linear systems at each step so they should only be used when required.
If we want to choose an algorithm directly, you can pass the algorithm type after the problem as `solve(prob,alg)`. For example, let's solve this problem using the `Tsit5()` algorithm, and just for show let's change the relative tolerance to `1e-6` at the same time:
```julia
sol = solve(prob,Tsit5(),reltol=1e-6)
```
### Systems of ODEs: The Lorenz Equation
Now let's move to a system of ODEs. The [Lorenz equation](https://en.wikipedia.org/wiki/Lorenz_system) is the famous "butterfly attractor" that spawned chaos theory. It is defined by the system of ODEs:
$$
\begin{align}
\frac{dx}{dt} &= \sigma (y - x)\\
\frac{dy}{dt} &= x (\rho - z) -y\\
\frac{dz}{dt} &= xy - \beta z
\end{align}
$$
To define a system of differential equations in DifferentialEquations.jl, we define our `f` as a vector function with a vector initial condition. Thus, for the vector `u = [x,y,z]'`, we have the derivative function:
```julia
function lorenz!(du,u,p,t)
σ,ρ,β = p
du[1] = σ*(u[2]-u[1])
du[2] = u[1]*(ρ-u[3]) - u[2]
du[3] = u[1]*u[2] - β*u[3]
end
```
Notice here we used the in-place format which writes the output to the preallocated vector `du`. For systems of equations the in-place format is faster. We use the initial condition $u_0 = [1.0,0.0,0.0]$ as follows:
```julia
u0 = [1.0,0.0,0.0]
```
Lastly, for this model we made use of the parameters `p`. We need to set this value in the `ODEProblem` as well. For our model we want to solve using the parameters $\sigma = 10$, $\rho = 28$, and $\beta = 8/3$, and thus we build the parameter collection:
```julia
p = (10,28,8/3) # we could also make this an array, or any other type!
```
Now we generate the `ODEProblem` type. In this case, since we have parameters, we add the parameter values to the end of the constructor call. Let's solve this on a time span of `t=0` to `t=100`:
```julia
tspan = (0.0,100.0)
prob = ODEProblem(lorenz!,u0,tspan,p)
```
Now, just as before, we solve the problem:
```julia
sol = solve(prob)
```
The same solution handling features apply to this case. Thus `sol.t` stores the time points and `sol.u` is an array storing the solution at the corresponding time points.
However, there are a few extra features which are good to know when dealing with systems of equations. First of all, `sol` also acts like an array. `sol[i]` returns the solution at the `i`th time point.
```julia
sol.t[10],sol[10]
```
Additionally, the solution acts like a matrix where `sol[j,i]` is the value of the `j`th variable at time `i`:
```julia
sol[2,10]
```
We can get a real matrix by performing a conversion:
```julia
A = Array(sol)
```
This is the same as sol, i.e. `sol[i,j] = A[i,j]`, but now it's a true matrix. Plotting will by default show the time series for each variable:
```julia
plot(sol)
```
If we instead want to plot values against each other, we can use the `vars` command. Let's plot variable `1` against variable `2` against variable `3`:
```julia
plot(sol,vars=(1,2,3))
```
This is the classic Lorenz attractor plot, where the `x` axis is `u[1]`, the `y` axis is `u[2]`, and the `z` axis is `u[3]`. Note that the plot recipe by default uses the interpolation, but we can turn this off:
```julia
plot(sol,vars=(1,2,3),denseplot=false)
```
Yikes! This shows how calculating the continuous solution has saved a lot of computational effort by computing only a sparse solution and filling in the values! Note that in vars, `0=time`, and thus we can plot the time series of a single component like:
```julia
plot(sol,vars=(0,2))
```
### A DSL for Parameterized Functions
In many cases you may be defining a lot of functions with parameters. There exists the domain-specific language (DSL) defined by the `@ode_def` macro for helping with this common problem. For example, we can define the Lotka-Volterra equation:
$$
\begin{align}
\frac{dx}{dt} &= ax - bxy\\
\frac{dy}{dt} &= -cy + dxy
\end{align}
$$
as follows:
```julia
function lotka_volterra!(du,u,p,t)
du[1] = p[1]*u[1] - p[2]*u[1]*u[2]
du[2] = -p[3]*u[2] + p[4]*u[1]*u[2]
end
```
However, that can be hard to follow since there's a lot of "programming" getting in the way. Instead, you can use the `@ode_def` macro from ParameterizedFunctions.jl:
```julia
using ParameterizedFunctions
lv! = @ode_def LotkaVolterra begin
dx = a*x - b*x*y
dy = -c*y + d*x*y
end a b c d
```
We can then use the result just like an ODE function from before:
```julia
u0 = [1.0,1.0]
p = (1.5,1.0,3.0,1.0)
tspan = (0.0,10.0)
prob = ODEProblem(lv!,u0,tspan,p)
sol = solve(prob)
plot(sol)
```
Not only is the DSL convenient syntax, but it does some magic behind the scenes. For example, further parts of the tutorial will describe how solvers for stiff differential equations have to make use of the Jacobian in calculations. Here, the DSL uses symbolic differentiation to automatically derive that function:
```julia
lv!.Jex
```
The DSL can derive many other functions; this ability is used to speed up the solvers. An extension to DifferentialEquations.jl, [Latexify.jl](https://korsbo.github.io/Latexify.jl/latest/tutorials/parameterizedfunctions.html), allows you to extract these pieces as LaTeX expressions.
## Internal Types
The last basic user-interface feature to explore is the choice of types. DifferentialEquations.jl respects your input types to determine the internal types that are used. Thus since in the previous cases, when we used `Float64` values for the initial condition, this meant that the internal values would be solved using `Float64`. We made sure that time was specified via `Float64` values, meaning that time steps would utilize 64-bit floats as well. But, by simply changing these types we can change what is used internally.
As a quick example, let's say we want to solve an ODE defined by a matrix. To do this, we can simply use a matrix as input.
```julia
A = [1. 0 0 -5
4 -2 4 -3
-4 0 0 1
5 -2 2 3]
u0 = rand(4,2)
tspan = (0.0,1.0)
f(u,p,t) = A*u
prob = ODEProblem(f,u0,tspan)
sol = solve(prob)
```
There is no real difference from what we did before, but now in this case `u0` is a `4x2` matrix. Because of that, the solution at each time point is matrix:
```julia
sol[3]
```
In DifferentialEquations.jl, you can use any type that defines `+`, `-`, `*`, `/`, and has an appropriate `norm`. For example, if we want arbitrary precision floating point numbers, we can change the input to be a matrix of `BigFloat`:
```julia
big_u0 = big.(u0)
```
and we can solve the `ODEProblem` with arbitrary precision numbers by using that initial condition:
```julia
prob = ODEProblem(f,big_u0,tspan)
sol = solve(prob)
```
```julia
sol[1,3]
```
To really make use of this, we would want to change `abstol` and `reltol` to be small! Notice that the type for "time" is different than the type for the dependent variables, and this can be used to optimize the algorithm via keeping multiple precisions. We can convert time to be arbitrary precision as well by defining our time span with `BigFloat` variables:
```julia
prob = ODEProblem(f,big_u0,big.(tspan))
sol = solve(prob)
```
Let's end by showing a more complicated use of types. For small arrays, it's usually faster to do operations on static arrays via the package [StaticArrays.jl](https://github.com/JuliaArrays/StaticArrays.jl). The syntax is similar to that of normal arrays, but for these special arrays we utilize the `@SMatrix` macro to indicate we want to create a static array.
```julia
using StaticArrays
A = @SMatrix [ 1.0 0.0 0.0 -5.0
4.0 -2.0 4.0 -3.0
-4.0 0.0 0.0 1.0
5.0 -2.0 2.0 3.0]
u0 = @SMatrix rand(4,2)
tspan = (0.0,1.0)
f(u,p,t) = A*u
prob = ODEProblem(f,u0,tspan)
sol = solve(prob)
```
```julia
sol[3]
```
## Conclusion
These are the basic controls in DifferentialEquations.jl. All equations are defined via a problem type, and the `solve` command is used with an algorithm choice (or the default) to get a solution. Every solution acts the same, like an array `sol[i]` with `sol.t[i]`, and also like a continuous function `sol(t)` with a nice plot command `plot(sol)`. The Common Solver Options can be used to control the solver for any equation type. Lastly, the types used in the numerical solving are determined by the input types, and this can be used to solve with arbitrary precision and add additional optimizations (this can be used to solve via GPUs for example!). While this was shown on ODEs, these techniques generalize to other types of equations as well.
|
/** Fit a set of points to a model that is subject to rotation and translation.
*
* The model is defined by a set of primitive faces such as plane, cylinder, sphere, etc.
* The measured points are first translated by (xt, yt, zt),
* then rotated about x-y-z axes by g, b, a angles in sequence,
*
* These 6 parameters are the output of the fit.
*
* Author: Yuan Mei
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_multifit_nlinear.h>
#ifdef LINE_MAX
#undef LINE_MAX
#define LINE_MAX 4096
#endif
#ifndef LINE_MAX
#define LINE_MAX 4096
#endif
/** Check if the character is a field separator. */
#ifndef sepq
#define sepq(a) ((a)==' ' || (a)=='\t')
#endif
#define NDIM 3 /**< number of dimensions */
enum {
FACE_PLANE=1,
FACE_CYLINDER=2,
FACE_SPHERE=3,
FACE_LINE=12,
FACE_POINT=13
};
struct face {
int ftype; /**< type of face: plane, cylinder etc... */
double x0; /**< origin */
double y0;
double z0;
double nx; /**< normal vector */
double ny;
double nz;
double r; /**< radius */
};
struct data {
double pr; /**< probe radius */
const struct face *faces;
size_t n; /**< number of measured data points */
size_t *fid; /**< idx of face in the registered faces */
double *x; /**< measured point */
double *y;
double *z;
double *w; /**< weights */
double *x1; /**< after transformation */
double *y1;
double *z1;
};
/** Distance from measured point to face. */
int dist_f(const gsl_vector *p, void *data, gsl_vector *f)
{
double pr = ((struct data *)data)->pr;
const struct face *faces = ((struct data *)data)->faces;
size_t n = ((struct data *)data)->n;
size_t *fid = ((struct data *)data)->fid;
double *x = ((struct data *)data)->x;
double *y = ((struct data *)data)->y;
double *z = ((struct data *)data)->z;
double a = gsl_vector_get(p, 0), Ca = cos(a), Sa = sin(a);
double b = gsl_vector_get(p, 1), Cb = cos(b), Sb = sin(b);
double g = gsl_vector_get(p, 2), Cg = cos(g), Sg = sin(g);
double xt = gsl_vector_get(p, 3);
double yt = gsl_vector_get(p, 4);
double zt = gsl_vector_get(p, 5);
size_t i;
for (i = 0; i < n; i++) {
int ftype = faces[fid[i]].ftype;
double x0 = faces[fid[i]].x0;
double y0 = faces[fid[i]].y0;
double z0 = faces[fid[i]].z0;
double nx = faces[fid[i]].nx;
double ny = faces[fid[i]].ny;
double nz = faces[fid[i]].nz;
double r = faces[fid[i]].r;
double x1, y1, z1;
x1 = Ca*Cb * (x[i]+xt) + (Ca*Sb*Sg-Sa*Cg) * (y[i]+yt) + (Ca*Sb*Cg+Sa*Sg) * (z[i]+zt);
y1 = Sa*Cb * (x[i]+xt) + (Sa*Sb*Sg+Ca*Cg) * (y[i]+yt) + (Sa*Sb*Cg-Ca*Sg) * (z[i]+zt);
z1 = - Sb * (x[i]+xt) + Cb*Sg * (y[i]+yt) + Cb*Cg * (z[i]+zt);
((struct data *)data)->x1[i] = x1;
((struct data *)data)->y1[i] = y1;
((struct data *)data)->z1[i] = z1;
double d, dist=0.0;
switch (ftype) {
case FACE_PLANE:
d = -(nx*x0 + ny*y0 + nz*z0);
dist = fabs(nx*x1 + ny*y1 + nz*z1 + d)
/ sqrt(nx*nx + ny*ny + nz*nz);
dist -= pr;
break;
case FACE_CYLINDER:
case FACE_LINE:
{
double dx = x1 - x0, dy = y1 - y0, dz = z1 - z0;
double s1 = dy * nz - dz * ny, s2 = dz*nx - dx*nz, s3 = dx*ny - dy*nx;
dist = fabs(sqrt((s1*s1 + s2*s2 + s3*s3)/(nx*nx + ny*ny + nz*nz)) - r);
if (ftype == FACE_CYLINDER)
dist -= pr;
}
break;
case FACE_SPHERE:
case FACE_POINT:
dist = fabs(sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0) + (z1-z0)*(z1-z0)) - r);
if (ftype == FACE_SPHERE)
dist -= pr;
break;
default:
dist = 0.0;
break;
}
gsl_vector_set(f, i, dist);
}
return GSL_SUCCESS;
}
void callback(const size_t iter, void *params,
const gsl_multifit_nlinear_workspace *w)
{
gsl_vector *f = gsl_multifit_nlinear_residual(w);
gsl_vector *x = gsl_multifit_nlinear_position(w);
double rcond=0;
/* compute reciprocal condition number of J(x) */
/* cond(J) = %8.4f, 1.0 / rcond */
gsl_multifit_nlinear_rcond(&rcond, w);
fprintf(stderr, "iter %2zu: a = %7.4f, b = %7.4f, g = %7.4f, xt = %7.4f, yt = %7.4f, zt = %7.4f, |f(x)| = %.4f\n",
iter,
gsl_vector_get(x, 0),
gsl_vector_get(x, 1),
gsl_vector_get(x, 2),
gsl_vector_get(x, 3),
gsl_vector_get(x, 4),
gsl_vector_get(x, 5),
gsl_blas_dnrm2(f));
}
/** Read a long line from file.
* @param[inout] s string of the line, is allocated when s==NULL and n==0 and grown as needed.
* @param[inout] n current size of s
* @return s
*/
static char *file_read_long_line(char **s, size_t *n, FILE *fp)
{
const int bufsz = LINE_MAX;
char *p;
size_t cnt, sz;
if ( *s == NULL && *n == 0 ) {
*n = bufsz;
if ( (*s = calloc(*n, sizeof(char))) == NULL ) exit(-1);
}
p = *s;
sz = *n;
while ( 1 ) {
if ( fgets(p, sz, fp) == NULL ) return NULL;
cnt = strlen(*s);
if ( (*s)[cnt-1] == '\n' ) {
break;
} else { /* line too long, expand the buffer */
*n += bufsz;
if ( (*s = realloc(*s, (*n)*sizeof(char))) == NULL ) exit(-1);
p = *s + cnt;
sz = bufsz;
}
}
return *s;
}
/** Read face definition file.
*
* @param[inout] n number of faces read from file. If the given value
* *n > 0, *n is interpreted as the number of elements in the faces
* array and only up to *n faces will be read from file. However, if
* the file contains less than *n faces, *n will be updated to reflect
* the available number of elements.
*
* @param[inout] faces array of faces. If *faces != NULL, *faces will
* be used rather than allocated.
*/
int read_faces(const char *fname, size_t *n, struct face **faces)
{
char *linebuf = NULL;
size_t linen = 0;
FILE *fp;
if ((fp = fopen(fname, "r"))==NULL) {
perror(fname);
return -1;
}
struct face fc;
int fid;
size_t lid = 0;
ssize_t nelem = -1;
if (*faces == NULL) {
/* get number of elements in the file */
while (file_read_long_line(&linebuf, &linen, fp)) {
lid++;
if (linebuf[0] == '#' || linebuf[0] == '\n') continue;
int ret = sscanf(linebuf, "%d %d %lf %lf %lf %lf %lf %lf %lf", &fid, &fc.ftype,
&fc.x0, &fc.y0, &fc.z0, &fc.nx, &fc.ny, &fc.nz, &fc.r);
if (ret < 9 || fid < 0 || fc.ftype <= 0) {
fprintf(stderr, "Malformatted face at line %zd\n", lid);
} else {
if (fid > nelem) nelem = fid;
}
}
nelem++;
if (nelem == 0) {
fprintf(stderr, "No valid face in file.\n");
return -1;
} else {
fprintf(stderr, "%zd faces available in file.\n", nelem);
}
*n = nelem;
if ((*faces = calloc(nelem, sizeof(struct face))) == NULL) {
perror("calloc *faces");
return -1;
}
}
rewind(fp);
nelem = 0;
lid = 0;
while (file_read_long_line(&linebuf, &linen, fp) && (nelem < *n)) {
lid++;
if (linebuf[0] == '#' || linebuf[0] == '\n') continue;
int ret = sscanf(linebuf, "%d %d %lf %lf %lf %lf %lf %lf %lf", &fid, &fc.ftype,
&fc.x0, &fc.y0, &fc.z0, &fc.nx, &fc.ny, &fc.nz, &fc.r);
if (ret < 9 || fid < 0 || fc.ftype <= 0) {
fprintf(stderr, "Malformatted face at line %zd, skipped.\n", lid);
} else {
if (fid >= *n) break;
struct face *fc1 = *faces;
memcpy(&fc1[fid], &fc, sizeof(fc));
nelem++;
}
}
fprintf(stderr, "%zd faces constructed.\n", nelem);
free(linebuf);
fclose(fp);
return 0;
}
int read_points(const char *fname, size_t *n, struct data *data)
{
char *linebuf = NULL;
size_t linen = 0;
FILE *fp;
if ((fp = fopen(fname, "r"))==NULL) {
perror(fname);
return -1;
}
int fidmax = -1;
*n = 0;
size_t lid = 0;
while (file_read_long_line(&linebuf, &linen, fp)) {
lid++;
if (linebuf[0] == '#' || linebuf[0] == '\n') continue;
int ret = 0;
for (int i=0; i<linen; i++) { /* count number of ';' */
if (linebuf[i] == ';') ret++;
}
int fid;
sscanf(linebuf, "%*d;%d", &fid);
if (ret < 8 || fid < 0) {
fprintf(stderr, "Malformatted point at line %zd\n", lid);
} else {
(*n)++;
if (fid > fidmax) fidmax = fid;
}
}
fprintf(stderr, "%zd points in file. fidmax = %d\n", *n, fidmax);
data->n = *n;
data->fid = calloc(data->n, sizeof(size_t));
data->x = calloc(data->n, sizeof(double));
data->y = calloc(data->n, sizeof(double));
data->z = calloc(data->n, sizeof(double));
data->w = calloc(data->n, sizeof(double));
data->x1 = calloc(data->n, sizeof(double));
data->y1 = calloc(data->n, sizeof(double));
data->z1 = calloc(data->n, sizeof(double));
rewind(fp);
lid = 0;
size_t idx = 0;
while (file_read_long_line(&linebuf, &linen, fp)) {
lid++;
if (linebuf[0] == '#' || linebuf[0] == '\n') continue;
int fid = 0, ret = 0;
double x, y, z, s;
// ret = sscanf(linebuf, "%*d;%d;%*s ;%*d;%lf;%lf;%lf;;%lf", &fid, &x, &y, &z, &s);
char *buf = linebuf, *endptr;
for (; *buf != ';' ; buf++){;} buf++; /* find the next character past a ';' */
fid = strtol(buf, &endptr, 0); if (endptr > buf) ret++; buf = endptr++;
for (; *buf != ';' ; buf++){;} buf++;
for (; *buf != ';' ; buf++){;} buf++;
for (; *buf != ';' ; buf++){;} buf++;
x = strtod(buf, &endptr); if (endptr > buf) ret++; buf = endptr++;
for (; *buf != ';' ; buf++){;} buf++;
y = strtod(buf, &endptr); if (endptr > buf) ret++; buf = endptr++;
for (; *buf != ';' ; buf++){;} buf++;
z = strtod(buf, &endptr); if (endptr > buf) ret++; buf = endptr++;
for (; *buf != ';' ; buf++){;} buf++;
for (; *buf != ';' ; buf++){;} buf++;
s = strtod(buf, &endptr); if (endptr > buf) ret++; buf = endptr++;
if (ret < 5 || fid < 0) {
fprintf(stderr, "Malformatted point at line %zd, skipped.\n", lid);
} else {
data->fid[idx] = fid;
data->x[idx] = x;
data->y[idx] = y;
data->z[idx] = z;
data->w[idx] = (fabs(s)>1e-8) ? (1.0/(s*s)) : 1.0;
idx++;
}
}
fprintf(stderr, "%zd points read.\n", idx);
free(linebuf);
fclose(fp);
return 0;
}
int main(int argc, char **argv)
{
if (argc != 10) {
fprintf(stderr,
"Usage: %s faces_file points_file pr a b g xt yt zt\n\n"
" pr is the probe radius.\n"
" The last 6 parameters are initial guesses.\n"
" Points are first translated, then rotated about x(g), y(b), z(a).\n"
" The 2nd column in points_file shall be faceid,\n"
" which is the first column of faces_file.\n"
" The last column in points_file shall be measurement sigma.\n", argv[0]);
return EXIT_FAILURE;
}
size_t nfaces=0;
struct face *faces=NULL;
read_faces(argv[1], &nfaces, &faces);
size_t nd=0;
struct data data;
read_points(argv[2], &nd, &data);
data.faces = faces;
data.pr = atof(argv[3]);
#define np 6
double p_init[np] = {0}; /* starting values */
for (int i=0; i<np; i++) {
p_init[i] = atof(argv[4+i]);
}
const gsl_multifit_nlinear_type *T = gsl_multifit_nlinear_trust;
gsl_multifit_nlinear_workspace *w;
gsl_multifit_nlinear_fdf fdf;
gsl_multifit_nlinear_parameters fdf_params =
gsl_multifit_nlinear_default_parameters();
gsl_vector *f;
gsl_matrix *J;
gsl_matrix *covar = gsl_matrix_alloc(np, np);
gsl_vector_view params = gsl_vector_view_array(p_init, np);
gsl_vector_view wts = gsl_vector_view_array(data.w, nd);
gsl_rng *r;
double chisq, chisq0;
int status, info;
const double xtol = 1e-8;
const double gtol = 1e-8;
const double ftol = 1e-8;
gsl_rng_env_setup();
r = gsl_rng_alloc(gsl_rng_default);
/* define the function to be minimized */
fdf.f = dist_f;
fdf.df = NULL; /* set to NULL for finite-difference Jacobian */
fdf.fvv = NULL; /* not using geodesic acceleration */
fdf.n = nd;
fdf.p = np;
fdf.params = &data; /* `data' supplied to the penalty function */
/* allocate workspace with default parameters */
w = gsl_multifit_nlinear_alloc(T, &fdf_params, nd, np);
/* initialize solver with starting point and weights */
gsl_multifit_nlinear_winit(¶ms.vector, &wts.vector, &fdf, w);
/* compute initial cost function */
f = gsl_multifit_nlinear_residual(w);
gsl_blas_ddot(f, f, &chisq0);
/* solve the system with a maximum of 100 iterations */
status = gsl_multifit_nlinear_driver(100, xtol, gtol, ftol,
callback, NULL, &info, w);
/* compute covariance of best fit parameters */
J = gsl_multifit_nlinear_jac(w);
gsl_multifit_nlinear_covar(J, 0.0, covar);
/* compute final cost */
gsl_blas_ddot(f, f, &chisq);
#define FIT(i) gsl_vector_get(w->x, i)
#define ERR(i) sqrt(gsl_matrix_get(covar,i,i))
fprintf(stderr, "summary from method '%s/%s'\n",
gsl_multifit_nlinear_name(w),
gsl_multifit_nlinear_trs_name(w));
fprintf(stderr, "number of iterations: %zu\n",
gsl_multifit_nlinear_niter(w));
fprintf(stderr, "function evaluations: %zu\n", fdf.nevalf);
fprintf(stderr, "Jacobian evaluations: %zu\n", fdf.nevaldf);
fprintf(stderr, "reason for stopping: %s\n",
(info == 1) ? "small step size" : "small gradient");
fprintf(stderr, "initial |f(x)| = %f\n", sqrt(chisq0));
fprintf(stderr, "final |f(x)| = %f\n", sqrt(chisq));
{
double dof = nd - np;
double c = GSL_MAX_DBL(1, sqrt(chisq / dof));
fprintf(stderr, "chisq/dof = %g\n", chisq / dof);
fprintf(stderr, "a = %16g +/- %g\n", FIT(0), c*ERR(0));
fprintf(stderr, "b = %16g +/- %g\n", FIT(1), c*ERR(1));
fprintf(stderr, "g = %16g +/- %g\n", FIT(2), c*ERR(2));
fprintf(stderr, "xt = %16g +/- %g\n", FIT(3), c*ERR(3));
fprintf(stderr, "yt = %16g +/- %g\n", FIT(4), c*ERR(4));
fprintf(stderr, "zt = %16g +/- %g\n", FIT(5), c*ERR(5));
}
fprintf(stderr, "status = %s\n", gsl_strerror(status));
/* compute residual of every point */
dist_f(w->x, &data, f); // pure distance, no weights.
printf("# fid ftype distance x1 y1 z1\n");
for (int i=0; i<nd; i++) {
printf("%8zd %7d %9.6f %11.5f %11.5f %11.5f\n", data.fid[i], faces[data.fid[i]].ftype,
gsl_vector_get(f, i), data.x1[i], data.y1[i], data.z1[i]);
}
gsl_multifit_nlinear_free(w);
gsl_matrix_free(covar);
gsl_rng_free(r);
free(faces);
free(data.fid);
free(data.x);
free(data.y);
free(data.z);
free(data.w);
free(data.x1);
free(data.y1);
free(data.z1);
return EXIT_SUCCESS;
}
|
! RUN: %S/test_errors.sh %s %t %flang_fc1
! REQUIRES: shell
! case 1: ma_create_new_fun' was not declared a separate module procedure
module m1
integer :: i
interface ma
module function ma_create_fun( ) result(this)
integer this
end function
end interface
end module
submodule (m1) ma_submodule
integer :: j
contains
module function ma_create_fun() result(this)
integer this
i = 1
j = 2
end function
!ERROR: 'ma_create_new_fun' was not declared a separate module procedure
module function ma_create_new_fun() result(this)
integer :: this
i = 2
j = 1
print *, "Hello"
end function
end submodule
! case 2: 'mb_create_new_sub' was not declared a separate module procedure
module m2
integer :: i
interface mb
module subroutine mb_create_sub
end subroutine mb_create_sub
end interface
end module
submodule (m2) mb_submodule
integer :: j
contains
module subroutine mb_create_sub
integer this
i = 1
j = 2
end subroutine mb_create_sub
!ERROR: 'mb_create_new_sub' was not declared a separate module procedure
module SUBROUTINE mb_create_new_sub()
integer :: this
i = 2
j = 1
end SUBROUTINE mb_create_new_sub
end submodule
! case 3: separate module procedure without module prefix
module m3
interface mc
function mc_create( ) result(this)
integer :: this
end function
end interface
end module
submodule (m3) mc_submodule
contains
!ERROR: 'mc_create' was not declared a separate module procedure
module function mc_create() result(this)
integer :: this
end function
end submodule
! case 4: Submodule having separate module procedure rather than a module
module m4
interface
real module function func1() ! module procedure interface body for func1
end function
end interface
end module
submodule (m4) m4sub
interface
module function func2(b) ! module procedure interface body for func2
integer :: b
integer :: func2
end function
real module function func3() ! module procedure interface body for func3
end function
end interface
contains
real module function func1() ! implementation of func1 declared in m4
func1 = 20
end function
end submodule
submodule (m4:m4sub) m4sub2
contains
module function func2(b) ! implementation of func2 declared in m4sub
integer :: b
integer :: func2
func2 = b
end function
real module function func3() ! implementation of func3 declared in m4sub
func3 = 20
end function
end submodule
|
*deck ang2
subroutine ang2(ang,binom,crda,dfac,it,l,lit,lmlo,lmhi,lmf,lml,
& lmx,lmy,lmz,lmnv,mproju,xk,yk,zk,zlm)
c
c compute type 2 angular integrals
c
implicit real*8 (a-h,o-z)
parameter (a0=0.0d0, a1=1.0d0, a2=2.0d0, a3=3.0d0)
dimension ang(lit,mproju,*), binom(*), crda(lit,3), dfac(*),
& lmf(*), lml(*), lmx(*), lmy(*), lmz(*), lmnv(3,*), zlm(*)
c
call wzero(lit*mproju*lmhi,ang,1)
na1=lmnv(1,it)+1
la1=lmnv(2,it)+1
ma1=lmnv(3,it)+1
naind=(na1*(na1-1))/2
laind=(la1*(la1-1))/2
maind=(ma1*(ma1-1))/2
loc1=(l-1)**2
mhi=l+l-1
do 80 ia=1,na1
pab1=binom(naind+ia)*crda((na1+1)-ia,1)
if(pab1.eq.a0) go to 80
do 70 ib=1,la1
pab2=pab1*binom(laind+ib)*crda((la1+1)-ib,2)
if(pab2.eq.a0) go to 70
do 60 ic=1,ma1
pab3=pab2*binom(maind+ic)*crda((ma1+1)-ic,3)
if(pab3.eq.a0) go to 60
n=((ia-3)+ib)+ic
lamlo=max(l-n,lmlo+mod(l+n+lmlo,2))
lamhi=min(l+n,lmhi-mod(l+n+lmhi,2))
if(lamlo.gt.lamhi) go to 60
do 55 m=1,mhi
mstart=lmf(loc1+m)
mend=lml(loc1+m)
do 50 lam=lamlo,lamhi,2
l2=lam+lam-1
angt=a0
loc2=(lam-1)**2
do 40 mu=1,l2
istart=lmf(loc2+mu)
if(mod(ia+lmx(mstart)+lmx(istart),2).ne.1.or.
1 mod(ib+lmy(mstart)+lmy(istart),2).ne.1.or.
2 mod(ic+lmz(mstart)+lmz(istart),2).ne.1) go to 40
pre=a0
iend=lml(loc2+mu)
aint=a0
do 30 i=istart,iend
indx=lmx(i)
indy=lmy(i)
indz=lmz(i)
if(indx.eq.0) then
xkp=a1
else
xkp=xk**indx
endif
if(indy.eq.0) then
ykp=a1
else
ykp=yk**indy
endif
if(indz.eq.0) then
zkp=a1
else
zkp=zk**indz
endif
pre=pre+zlm(i)*xkp*ykp*zkp
do 20 j=mstart,mend
mndx=lmx(j)
mndy=lmy(j)
mndz=lmz(j)
aint=aint+zlm(i)*zlm(j)*
& dfac(ia+indx+mndx)*
& dfac(ib+indy+mndy)*
& dfac(ic+indz+mndz)/
& dfac(ia+indx+mndx+ib+indy+mndy+ic+indz+mndz)
20 continue
30 continue
angt=angt+pre*aint
40 continue
ang(n+1,m,lam)=ang(n+1,m,lam)+angt*pab3
50 continue
55 continue
60 continue
70 continue
80 continue
return
end
|
-- Check that unquoted functions are termination checked.
module _ where
open import Common.Prelude hiding (_>>=_)
open import Common.Reflection
`⊥ : Type
`⊥ = def (quote ⊥) []
{-
Generate
aux : ⊥
aux = aux
loop : ⊥
loop = aux
-}
makeLoop : QName → TC ⊤
makeLoop loop =
freshName "aux" >>= λ aux →
declareDef (vArg aux) `⊥ >>= λ _ →
defineFun aux (clause [] (def aux []) ∷ []) >>= λ _ →
declareDef (vArg loop) `⊥ >>= λ _ →
defineFun loop (clause [] (def aux []) ∷ [])
unquoteDecl loop = makeLoop loop
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 7 08:46:25 2022
This script calculates the 90th percentile threshold of climatological daily
maximum temperatures, centred on a 31 d window, for the base period 1981–2010.
This threshold is used in the calculation of heatwave magnitude index.
The threshold is calculated for each grid point from the 30-year climatology
and 31-day moving window (31 x 30 values).
The heatwave magnitude index is based on this paper:
https://iopscience.iop.org/article/10.1088/1748-9326/ab6398/meta
### NOTE!! ###
Currently the script calculates also 25th and 75th percentiles. This is probably
not necessary.
@author: mprantan
"""
import os
import s3fs
import xarray as xr
import numpy as np
from datetime import datetime
import io_utils
from scipy.ndimage.morphology import binary_dilation
import warnings
import time
start = time.time()
def save_as_dataarray(array, doy_values, da_t2max):
da = xr.DataArray(data=array, dims=["doy","latitude","longitude",],
coords={'doy':doy_values,
'longitude': da_t2max.longitude,
'latitude':da_t2max.latitude})
return da
# define the output data path to which the resulting percentiles are saved
outpath = '/projappl/project_2005030/climateatlas/heatwave_threshold.nc'
## define the climatology years. 1981-2010 are used in the literature
years = np.arange(1981,2011)
# Set up the S3 file system
access = os.getenv('S3_RESICLIM_ACCESS')
secret = os.getenv('S3_RESICLIM_SECRET')
fs = s3fs.S3FileSystem(anon=False, key=access, secret=secret,
client_kwargs={'endpoint_url': 'https://a3s.fi'})
files = fs.glob('resiclim/daily/2m_temperature_DMEA*')
#### READ RAW INPUT ERA5-Land #######
da_t2max = io_utils.read_daily_data_from_allas(fs, years, 'summer', '2m_temperature','DMAX')
# Width of the selection window (days)
struct = np.ones(31)
# Arrays for saving the result
p90_array = np.empty((366, np.shape(da_t2max)[1], np.shape(da_t2max)[2]))
#p75_array = np.empty((366, np.shape(da_t2max)[1], np.shape(da_t2max)[2]))
#p25_array = np.empty((366, np.shape(da_t2max)[1], np.shape(da_t2max)[2]))
doy_values = np.unique(da_t2max['time.dayofyear'].values)
for day in doy_values:
start2 = time.time()
print('Calculating thresholds for doy '+str(day))
dayofyear = da_t2max['time.dayofyear'] == day
# Pick 31 days around the target day from each year
selection = binary_dilation(dayofyear, structure=struct)
# ignore runtime warning
warnings.simplefilter("ignore", category=RuntimeWarning)
# Calculate the percentiles and save into arrays
p90_array[int(day)-1,:, :] = np.nanpercentile(da_t2max.sel(time=selection), 90, axis=0)
#p75_array[int(day)-1,:, :] = np.nanpercentile(da_t2max.sel(time=selection), 75, axis=0)
#p25_array[int(day)-1,:, :] = np.nanpercentile(da_t2max.sel(time=selection), 25, axis=0)
end2 = time.time()
print('Calculation lasted '+str(np.round(end2 - start2, 2))+' seconds')
p90_da = save_as_dataarray(p90_array, doy_values, da_t2max)
#p75_da = save_as_dataarray(p75_array, doy_values, da_t2max)
#p25_da = save_as_dataarray(p25_array, doy_values, da_t2max)
### Create dataset for the output variables
ds_out = p90_da.to_dataset(name='p90')
#ds_out['p75'] = p75_da
#ds_out['p25'] = p25_da
ds_out = ds_out.compute()
# add time attribute
ds_out.doy.attrs['long_name'] = "Day of year"
# add global attributes
ds_out.attrs['Conventions'] = 'CF-1.7'
ds_out.attrs['title'] = 'Heatwave thresholds'
ds_out.attrs['Institution'] = 'Finnish Meteorological Institute'
ds_out.attrs['source'] = 'ERA5-Land'
ds_out.attrs['history'] = datetime.utcnow().strftime(format='%Y-%m-%d %H:%M:%S') + ' Python'
# save the data as a netcdf file
ds_out.to_netcdf(outpath, format='NETCDF4')
print('Done!')
end = time.time()
print('Calculation took '+str(np.round(end - start, 2))+' seconds') |
module CommonTools
import ArgParse
import GLVisualize
import Rotations
import NearestNeighbors
import Parameters
import Reactive
import NamedTuples
import Images
import BenchmarkTools
import MeshIO
import FileIO
import DataStructures
import ColorTypes
import Optim
import GeometryTypes
import PyPlot
import LsqFit
# !isdefined(:my_full_name) && (my_full_name = @__FILE__)
# includeallafiles(my_full_name)
include("arrays.jl")
include("filesystem.jl")
include("ini.jl")
include("FPS.jl")
include("math.jl")
include("strings.jl")
include("functors.jl")
include("PM.jl")
#include("template_matching.jl")
function isinside(v, poly)
# See: http://www.sciencedirect.com/science/article/pii/S0925772101000128
# "The point in polygon problem for arbitrary polygons"
# An implementation of Hormann-Agathos (2001) Point in Polygon algorithm
c = false
r = v
detq(q1,q2) = (q1[1]-r[1])*(q2[2]-r[2])-(q2[1]-r[1])*(q1[2]-r[2])
N = length(poly)
for i=1:N
q1 = poly[i]
q2 = poly[(i%N) + 1]
(v == q1 || v == q2) && return false
if (q1[2] < r[2]) != (q2[2] < r[2]) # crossing
if q1[1] >= r[1]
if q2[1] > r[1]
c = !c
elseif ((detq(q1,q2) > 0) == (q2[2] > q1[2])) # right crossing
c = !c
end
elseif q2[1] > r[1]
if ((detq(q1,q2) > 0) == (q2[2] > q1[2])) # right crossing
c = !c
end
end
end
end
return c
end
export isinside
function mean_Rotation(a,b,t)
qa = Quat(a)
qb = Quat(b)
qa = [qa.w qa.x qa.y qa.z]
qb = [qb.w qb.x qb.y qb.z]
dot = qb*qa'
DOT_THRESHOLD = 0.995
if (dot[1] < 0.0)
qb = -qb;
dot = -dot;
end
abs_dot = abs.(dot)
if (abs_dot[1] > DOT_THRESHOLD)
result = qa.+ t.*(qb.-qa);
result = normalize([result]);
#return result;
return RotXYZ(Quat(result[1]...))
end
theta_0 = acos(dot[1]);
theta = theta_0*t;
qab = qb.-qa.*dot
qab = normalize([qab])
d = qa.*cos(theta)
e = qab.*sin.(theta)
slerp = d + e[1]
return RotXYZ(Quat(slerp...))
end
export mean_Rotation
function mean_Rotation_aux(R,len_R)
if len_R>1
log_len_R = Int(floor(log2(len_R)))
R = R[1:2^log_len_R]
len_R = length(R)
for i=1:log_len_R
Quat_list = []
for j=1:2:len_R
mean_tmp = mean_Rotation(R[j],R[j+1],0.5)
push!(Quat_list,mean_tmp[1:3,1:3])
end
R = Quat_list
len_R = length(R)
end
end
return R[1]
end
export mean_Rotation_aux
end
|
lemma power_eq_1_iff: fixes w :: "'a::real_normed_div_algebra" shows "w ^ n = 1 \<Longrightarrow> norm w = 1 \<or> n = 0" |
##############################################################################
##
## Object constructed by the user
##
##############################################################################
# Object constructed by the user
type InteractiveFixedEffectModel
id::Symbol
time::Symbol
rank::Int64
end
abstract AbstractFactorModel{T}
abstract AbstractFactorSolution{T}
##############################################################################
##
## Factor Model
##
##############################################################################
type FactorModel{Rank, W, Rid, Rtime} <: AbstractFactorModel{Rank}
y::Vector{Float64}
sqrtw::W
idrefs::Vector{Rid}
timerefs::Vector{Rtime}
end
function FactorModel{W, Rid, Rtime}(y::Vector{Float64}, sqrtw::W, idrefs::Vector{Rid}, timerefs::Vector{Rtime}, rank::Int)
FactorModel{rank, W, Rid, Rtime}(y, sqrtw, idrefs, timerefs)
end
rank{Rank}(::FactorModel{Rank}) = Rank
type FactorSolution{Rank, Tid, Ttime} <: AbstractFactorSolution{Rank}
idpool::Tid
timepool::Ttime
end
function FactorSolution{Tid, Ttime}(idpool::Tid, timepool::Ttime)
r = size(idpool, 2)
@assert r == size(timepool, 2)
FactorSolution{r, Tid, Ttime}(idpool, timepool)
end
function view(f::AbstractFactorSolution, I::Union{AbstractArray,Colon,Int64}...)
FactorSolution(view(f.idpool, I...), view(f.timepool, I...))
end
## subtract_factor! and subtract_b!
function subtract_factor!(fm::AbstractFactorModel, fs::AbstractFactorSolution)
for r in 1:rank(fm)
subtract_factor!(fm, view(fs, :, r))
end
end
function subtract_factor!(fm::AbstractFactorModel, fs::FactorSolution{1})
@inbounds @simd for i in 1:length(fm.y)
fm.y[i] -= fm.sqrtw[i] * fs.idpool[fm.idrefs[i]] * fs.timepool[fm.timerefs[i]]
end
end
## rescale a factor model
function reverse{R}(m::Matrix{R})
out = similar(m)
for j in 1:size(m, 2)
invj = size(m, 2) + 1 - j
@inbounds @simd for i in 1:size(m, 1)
out[i, j] = m[i, invj]
end
end
return out
end
function rescale!(fs::FactorSolution{1})
out = norm(fs.timepool)
scale!(fs.idpool, out)
scale!(fs.timepool, 1/out)
end
# normalize factors and loadings so that F'F = Id, Lambda'Lambda diagonal
function rescale!(newfs::AbstractFactorSolution, fs::AbstractFactorSolution)
U = eigfact!(Symmetric(At_mul_B(fs.timepool, fs.timepool)))
sqrtDx = diagm(sqrt(abs(U[:values])))
A_mul_B!(newfs.idpool, fs.idpool, U[:vectors] * sqrtDx)
V = eigfact!(At_mul_B(newfs.idpool, newfs.idpool))
A_mul_B!(newfs.idpool, fs.idpool, reverse(U[:vectors] * sqrtDx * V[:vectors]))
A_mul_B!(newfs.timepool, fs.timepool, reverse(U[:vectors] * (sqrtDx \ V[:vectors])))
return newfs
end
rescale(fs::FactorSolution) = rescale!(similar(fs), fs)
## Create dataframe from pooledfactors
function getfactors(fp::AbstractFactorModel, fs::AbstractFactorSolution)
# partial out Y and X with respect to i.id x factors and i.time x loadings
newfes = FixedEffect[]
for r in 1:rank(fp)
idinteraction = build_interaction(fp.timerefs, view(fs.timepool, :, r))
idfe = FixedEffect(fp.idrefs, size(fs.idpool, 1), fp.sqrtw, idinteraction, :id, :time, :(idxtime))
push!(newfes, idfe)
timeinteraction = build_interaction(fp.idrefs, view(fs.idpool, :, r))
timefe = FixedEffect(fp.timerefs, size(fs.timepool, 1), fp.sqrtw, timeinteraction, :time, :id, :(timexid))
push!(newfes, timefe)
end
# obtain the residuals and cross
return newfes
end
function build_interaction(refs::Vector, pool::AbstractVector)
interaction = Array(Float64, length(refs))
@inbounds @simd for i in 1:length(refs)
interaction[i] = pool[refs[i]]
end
return interaction
end
function DataFrame(fp::AbstractFactorModel, fs::AbstractFactorSolution, esample::BitVector)
df = DataFrame()
anyNA = all(esample)
for r in 1:rank(fp)
# loadings
df[convert(Symbol, "loadings$r")] = build_column(fp.idrefs, fs.idpool[:, r], esample)
df[convert(Symbol, "factors$r")] = build_column(fp.timerefs, fs.timepool[:, r], esample)
end
return df
end
function build_column(refs::Vector, pool::Vector, esample::BitVector)
T = eltype(refs)
newrefs = fill(zero(T), length(esample))
newrefs[esample] = refs
return PooledDataArray(RefArray(newrefs), pool)
end
##############################################################################
##
## Interactive Fixed Effect Models
##
##############################################################################
type InteractiveFixedEffectsModel{Rank, W, Rid, Rtime} <: AbstractFactorModel{Rank}
y::Vector{Float64}
sqrtw::W
X::Matrix{Float64}
idrefs::Vector{Rid}
timerefs::Vector{Rtime}
end
function InteractiveFixedEffectsModel{W, Rid, Rtime}(y::Vector{Float64}, sqrtw::W, X::Matrix{Float64}, idrefs::Vector{Rid}, timerefs::Vector{Rtime}, rank::Int)
InteractiveFixedEffectsModel{rank, W, Rid, Rtime}(y, sqrtw, X, idrefs, timerefs)
end
rank{Rank}(::InteractiveFixedEffectsModel{Rank}) = Rank
convert{Rank, W, Rid, Rtime}(::Type{FactorModel}, f::InteractiveFixedEffectsModel{Rank, W, Rid, Rtime}) = FactorModel{Rank, W, Rid, Rtime}(f.y, f.sqrtw, f.idrefs, f.timerefs)
type InteractiveFixedEffectsSolution{Rank, Tb, Tid, Ttime} <: AbstractFactorSolution{Rank}
b::Tb
idpool::Tid
timepool::Ttime
end
function InteractiveFixedEffectsSolution{Tb, Tid, Ttime}(b::Tb, idpool::Tid, timepool::Ttime)
r = size(idpool, 2)
r == size(timepool, 2) || throw("factors and loadings don't have same dimension")
InteractiveFixedEffectsSolution{r, Tb, Tid, Ttime}(b, idpool, timepool)
end
convert(::Type{FactorSolution}, f::InteractiveFixedEffectsSolution) = FactorSolution(f.idpool, f.timepool)
type InteractiveFixedEffectsSolutionT{Rank, Tb, Tid, Ttime} <: AbstractFactorSolution{Rank}
b::Tb
idpool::Tid
timepool::Ttime
end
function InteractiveFixedEffectsSolutionT{Tb, Tid, Ttime}(b::Tb, idpool::Tid, timepool::Ttime)
r = size(idpool, 1)
r == size(timepool, 1) || throw("factors and loadings don't have same dimension")
InteractiveFixedEffectsSolutionT{r, Tb, Tid, Ttime}(b, idpool, timepool)
end
function rescale(fs::InteractiveFixedEffectsSolution)
fss = FactorSolution(fs.idpool, fs.timepool)
newfss = similar(fss)
rescale!(newfss, fss)
InteractiveFixedEffectsSolution(fs.b, newfss.idpool, newfss.timepool)
end
type HalfInteractiveFixedEffectsModel{Rank, W, Rid, Rtime} <: AbstractFactorModel
y::Vector{Float64}
sqrtw::W
X::Matrix{Float64}
idrefs::Vector{Rid}
timerefs::Vector{Rtime}
timepool::Matrix{Float64}
size::Tuple{Int, Int}
end
function HalfInteractiveFixedEffectsModel{W, Rid, Rtime}(y::Vector{Float64}, sqrtw::W, X::Matrix{Float64}, idrefs::Vector{Rid}, timerefs::Vector{Rtime}, timepool::Matrix{Float64}, size, rank::Int)
HalfInteractiveFixedEffectsModel{rank, W, Rid, Rtime}(y, sqrtw, X, idrefs, timerefs, timepool, size)
end
type HalfInteractiveFixedEffectsSolution{Tb, Tid} <: AbstractFactorSolution
b::Tb
idpool::Tid
end
##############################################################################
##
## Results
##
##############################################################################'
type FactorResult
esample::BitVector
augmentdf::DataFrame
ess::Float64
iterations::Int64
converged::Bool
end
# result
type InteractiveFixedEffectsResult <: AbstractRegressionResult
coef::Vector{Float64} # Vector of coefficients
vcov::Matrix{Float64} # Covariance matrix
esample::BitVector # Is the row of the original dataframe part of the estimation sample?
augmentdf::DataFrame
coefnames::Vector # Name of coefficients
yname::Symbol # Name of dependent variable
formula::Formula # Original formula
nobs::Int64 # Number of observations
df_residual::Int64 # degree of freedoms
r2::Float64 # R squared
r2_a::Float64 # R squared adjusted
r2_within::Float64 # R within
ess::Float64
iterations::Int # Number of iterations
converged::Bool # Has the demeaning algorithm converged?
end
predict(::InteractiveFixedEffectsResult, ::AbstractDataFrame) = error("predict is not defined for linear factor models. Use the option save = true")
residuals(::InteractiveFixedEffectsResult, ::AbstractDataFrame) = error("residuals is not defined for linear factor models. Use the option save = true")
title(::InteractiveFixedEffectsResult) = "Linear Factor Model"
top(x::InteractiveFixedEffectsResult) = [
"Number of obs" sprint(showcompact, nobs(x));
"Degree of freedom" sprint(showcompact, nobs(x) - df_residual(x));
"R2" @sprintf("%.3f", x.r2);
"R2 within" @sprintf("%.3f", x.r2_within);
"Iterations" sprint(showcompact, x.iterations);
"Converged" sprint(showcompact, x.converged)
]
|
C Copyright (c) 2014, Sandia Corporation.
C Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
C the U.S. Government retains certain rights in this software.
C
C Redistribution and use in source and binary forms, with or without
C modification, are permitted provided that the following conditions are
C met:
C
C * Redistributions of source code must retain the above copyright
C notice, this list of conditions and the following disclaimer.
C
C * Redistributions in binary form must reproduce the above
C copyright notice, this list of conditions and the following
C disclaimer in the documentation and/or other materials provided
C with the distribution.
C
C * Neither the name of Sandia Corporation nor the names of its
C contributors may be used to endorse or promote products derived
C from this software without specific prior written permission.
C
C THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
C "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
C LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
C A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
C OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
C SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
C LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
C DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
C THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
C (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
C OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
C
C $Id: getwt.f,v 1.2 1991/03/21 15:44:49 gdsjaar Exp $
C $Log: getwt.f,v $
C Revision 1.2 1991/03/21 15:44:49 gdsjaar
C Changed all 3.14159... to atan2(0.0, -1.0)
C
c Revision 1.1.1.1 1990/11/30 11:08:53 gdsjaar
c FASTQ Version 2.0X
c
c Revision 1.1 90/11/30 11:08:51 gdsjaar
c Initial revision
c
C
CC* FILE: [.RENUM]GETWT.FOR
CC* MODIFIED BY: TED BLACKER
CC* MODIFICATION DATE: 7/6/90
CC* MODIFICATION: COMPLETED HEADER INFORMATION
C
SUBROUTINE GETWT (MP, ML, MXLPS, NIX, ILIST, XLIST, ILINE, LCON,
& LTYPE, COOR, LINKP, FRACT, ADDLNK, ERR)
C***********************************************************************
C
C SUBROUTINE GETWT = GETS A WEIGHT BASED ON A PERCENTAGE DISTANCE ALONG
C THE GIVEN SIDE LINE LIST.
C
C***********************************************************************
C
C SUBROUTINE CALLED BY:
C ADDWT = ADDS THE WEIGHTING FACTORS TO ANY NODES WITH
C FLAGS CONTAINING WEIGHTS
C
C***********************************************************************
C
C VARIABLES USED:
C FRACT = THE FRACTION OF TOTAL DISTANCE ALONG THE X AXIS
C (TAKES BACK THE WEIGHT OR Y VALUE AT THAT % DISTANCE)
C
C***********************************************************************
C
DIMENSION ILIST (MXLPS), XLIST (MXLPS)
DIMENSION ILINE (ML), LCON (3, ML), LTYPE (ML)
DIMENSION COOR (2, MP), LINKP (2, MP)
C
LOGICAL ADDLNK, ERR
C
ADDLNK = .FALSE.
ERR = .FALSE.
PI = ATAN2(0.0, -1.0)
TWOPI = 2.*PI
C
C GET THE X VALUE
C
X = FRACT* (XLIST (NIX)-XLIST (1))+XLIST (1)
C
C FIND THE LINE THIS BELONGS TO
C
DO 100 I = 1, NIX-1
IF ((X.LE.XLIST (I+1)).AND. (X.GE.XLIST (I))) THEN
IL = ILIST (I)
GOTO 110
ENDIF
100 CONTINUE
CALL MESAGE ('PROBLEMS IN GETWT - NO X SPAN FOUND')
ERR = .TRUE.
RETURN
C
110 CONTINUE
C
C NOW GET THE Y VALUE FOR THE X AND THE LINE (AND TYPE OF LINE) GIVEN
C
KT = LTYPE (IL)
CALL LTSORT (MP, LINKP, LCON (1, IL), IP1, ADDLNK)
CALL LTSORT (MP, LINKP, LCON (2, IL), IP2, ADDLNK)
CALL LTSORT (MP, LINKP, IABS (LCON (3, IL)), IP3, ADDLNK)
IF (LCON (3, IL).LT.0)IP3 = -IP3
C
C CHECK FOR EXACT LINE END PLACEMENT
C
EPS = ABS (XLIST (NIX)-XLIST (1))*.00001
IF (ABS (X-COOR (1, IP1)).LT.EPS) THEN
FRACT = COOR (2, IP1)
RETURN
ELSEIF (ABS (X-COOR (1, IP2)).LT.EPS) THEN
FRACT = COOR (2, IP2)
RETURN
ENDIF
C
C GET INTERMEDIATE Y VALUE BASED ON THE LINE TYPE
C
C FIRST - STRAIGHT LINES
C
IF (KT.EQ.1) THEN
IF (COOR (1, IP1).GT.COOR (1, IP2)) THEN
IHOLD = IP1
IP1 = IP2
IP2 = IHOLD
ENDIF
XFRACT = (X-COOR (1, IP1))/ (COOR (1, IP2)-COOR (1, IP1))
FRACT = (XFRACT* (COOR (2, IP2)-COOR (2, IP1)))+COOR (2, IP1)
C
C NEXT - CORNER LINES
C
ELSEIF (KT.EQ.2) THEN
IF (COOR (1, IP1).GT.COOR (1, IP2)) THEN
IHOLD = IP1
IP1 = IP2
IP2 = IHOLD
ENDIF
IF (COOR (1, IP3).GT.X) THEN
IP2 = IP3
XFRACT = (X-COOR (1, IP1))/ (COOR (1, IP2)-COOR (1, IP1))
FRACT = (XFRACT * (COOR (2, IP2) - COOR (2, IP1)))
& + COOR (2, IP1)
ELSEIF (COOR (1, IP3).LT.X) THEN
IP1 = IP3
XFRACT = (X-COOR (1, IP1))/ (COOR (1, IP2)-COOR (1, IP1))
FRACT = (XFRACT* (COOR (2, IP2) - COOR (2, IP1)))
& + COOR (2, IP1)
ELSE
FRACT = COOR (2, IP3)
ENDIF
C
C NEXT - ARCS
C
ELSEIF ((KT.EQ.3).OR. (KT.EQ.4).OR. (KT.EQ.6)) THEN
C
C ARCWITH CENTER GIVEN
C ARCGOES FROM 1ST POINT TO 2ND IN *COUNTER-CLOCKWISE* DIRECTION.
C
IF (KT.EQ.3) THEN
XCEN = COOR (1, IABS (IP3))
YCEN = COOR (2, IABS (IP3))
C
C CIRCLE WITH THIRD POINT ON ARC.
C
ELSEIF (KT.EQ.4) THEN
THETA1 = ATAN2 (COOR (2, IP3)-COOR (2, IP1), COOR (1, IP3)-
& COOR (1, IP1))+PI/2.0
THETA2 = ATAN2 (COOR (2, IP3)-COOR (2, IP2), COOR (1, IP3)-
& COOR (1, IP2))+PI/2.0
DET = -COS (THETA1)*SIN (THETA2)+COS (THETA2)*SIN (THETA1)
X1 = 0.5 * (COOR (1, IP1)+COOR (1, IP3))
Y1 = 0.5 * (COOR (2, IP1)+COOR (2, IP3))
X2 = 0.5 * (COOR (1, IP2)+COOR (1, IP3))
Y2 = 0.5 * (COOR (2, IP2)+COOR (2, IP3))
R = (-SIN (THETA2) * (X2-X1)+COS (THETA2) * (Y2-Y1))/DET
XCEN = X1 + R * COS (THETA1)
YCEN = Y1 + R * SIN (THETA1)
C
C CIRCLE WITH RADIUS GIVEN
C
ELSEIF (KT.EQ.6) THEN
DX = 0.5 * (COOR (1, IP2)-COOR (1, IP1))
DY = 0.5 * (COOR (2, IP2)-COOR (2, IP1))
CHORD = SQRT (DX*DX+DY*DY)
R = ABS (COOR (1, IABS (IP3)))
IF (R.LE.CHORD) THEN
XCEN = 0.5 * (COOR (1, IP1)+COOR (1, IP2))
YCEN = 0.5 * (COOR (2, IP1)+COOR (2, IP2))
ELSE
ARM = SQRT (R * R-CHORD * CHORD)
IF (IP3.LT.0) THEN
XCEN = COOR (1, IP1)+DX+ARM * DY/CHORD
YCEN = COOR (2, IP1)+DY-ARM * DX/CHORD
ELSE
XCEN = COOR (1, IP1)+DX-ARM * DY/CHORD
YCEN = COOR (2, IP1)+DY+ARM * DX/CHORD
ENDIF
ENDIF
ENDIF
R1 = SQRT ((COOR (1, IP1)-XCEN) **2 + (COOR (2, IP1)-YCEN) **2)
R2 = SQRT ((COOR (1, IP2)-XCEN) **2 + (COOR (2, IP2)-YCEN) **2)
IF ((R1.EQ.0.).OR. (R2.EQ.0.)) THEN
ERR = .TRUE.
WRITE (*, 10000)ILINE (IL)
RETURN
ENDIF
THETA1 = ATAN2 (COOR (2, IP1)-YCEN, COOR (1, IP1)-XCEN)
THETA2 = ATAN2 (COOR (2, IP2)-YCEN, COOR (1, IP2)-XCEN)
C
C ARCWITH THE CENTER GIVEN
C
IF (KT.EQ.3) THEN
IF ((IP3.GE.0).AND. (THETA2.LE.THETA1))THETA2 = THETA2+TWOPI
IF ((IP3.LT.0).AND. (THETA1.LE.THETA2))THETA1 = THETA1+TWOPI
TANG = THETA2-THETA1
C
C CIRCULAR ARC WITH 3RD POINT ON ARC - CLOCKWISE OR COUNTER-CLOCKWISE
C
ELSEIF (KT.EQ.4) THEN
THETA3 = ATAN2 (COOR (2, IP3)-YCEN, COOR (1, IP3)-XCEN)
IF (THETA2.LE.THETA1)THETA2 = THETA2+TWOPI
IF (THETA3.LE.THETA1)THETA3 = THETA3+TWOPI
TANG = THETA2-THETA1
IF (THETA3.GT.THETA2)TANG = - (TWOPI-TANG)
C
C CIRCULAR ARC WITH RADIUS GIVEN - CLOCKWISE OR COUNTER-CLOCKWISE
C
ELSEIF (KT.EQ.6) THEN
IF ((IP3.GE.0).AND. (THETA2.LE.THETA1))THETA2 = THETA2+TWOPI
IF ((IP3.LT.0).AND. (THETA1.LE.THETA2))THETA1 = THETA1+TWOPI
TANG = THETA2-THETA1
ENDIF
C
C NOW INTERATE UNTIL THE X VALUE IS WITHIN SOME EPSILON
C
AA = (LOG (R2/R1))/ (THETA2-THETA1)
BB = R2/EXP (AA * THETA2)
ANG = THETA1
EPS = ABS (COOR (1, IP1)-COOR (1, IP2)) * .000001
DO 140 I = 1, 10
DEL = TANG * .1
DO 120 J = 1, 10
ANG = ANG+DEL
RADIUS = BB * EXP (AA * ANG)
XTEST = XCEN+COS (ANG) * RADIUS
IF (EPS.GE.ABS (XTEST-X)) THEN
FRACT = YCEN+SIN (ANG) * RADIUS
GOTO 150
ELSEIF ((COOR (1, IP1) .LT. COOR (1, IP2))
& .AND. (XTEST .GT. X)) THEN
ANG = ANG-DEL
TANG = DEL
GOTO 130
ELSEIF ((COOR (1, IP1) .GT. COOR (1, IP2))
& .AND. (XTEST .LT. X)) THEN
ANG = ANG-DEL
TANG = DEL
GOTO 130
ENDIF
120 CONTINUE
130 CONTINUE
140 CONTINUE
ERR = .TRUE.
WRITE (*, 10010)ILINE (IL)
RETURN
150 CONTINUE
C
C FINALLY PARABOLAS
C
ELSEIF (KT.EQ.5) THEN
C
C CHECK LEGITIMACY OF DATA
C
IF (COOR (1, IP1).GT.COOR (1, IP2)) THEN
IJK = IP1
IP1 = IP2
IP2 = IJK
ENDIF
XMID = (COOR (1, IP1)+COOR (1, IP2)) * 0.5
YMID = (COOR (2, IP1)+COOR (2, IP2)) * 0.5
DOT = (COOR (1, IP2)-COOR (1, IP1)) * (COOR (1, IP3)-XMID)
& + (COOR (2, IP2)-COOR (2, IP1)) * (COOR (2, IP3)-YMID)
PERP = SQRT ((COOR (1, IP2)-COOR (1, IP1)) **2+ (COOR (2, IP2)-
& COOR (2, IP1)) **2) * SQRT ((COOR (1, IP3)-XMID) **2
& + (COOR (2, IP3) - YMID) **2)
IF (DOT.GE.0.05 * PERP) THEN
WRITE (*, 10020)ILINE (IL)
ERR = .TRUE.
RETURN
ENDIF
C
C GET TRANSFORMATION TO PARABOLA COORDINATE SYSTEM (Y = 4AX **2)
C
HALFW = SQRT ((COOR (1, IP2)-COOR (1, IP1)) **2 +
& (COOR (2, IP2) - COOR (2, IP1)) **2) *0.5
HEIGHT = SQRT ((XMID-COOR (1, IP3)) **2 +
& (YMID - COOR (2, IP3)) **2)
IF ((HEIGHT.EQ.0).OR. (HALFW.EQ.0.)) THEN
WRITE (*, 10030)ILINE (IL)
ERR = .TRUE.
RETURN
ENDIF
A = HEIGHT/ (HALFW **2)
XTOP = COOR (1, IP3)
YTOP = COOR (2, IP3)
THETA = ATAN2 (YMID-YTOP, XMID-XTOP)
SINT = SIN (THETA)
COST = COS (THETA)
IF (SINT.EQ.0.0) THEN
WRITE (*, 10040)ILINE (IL)
ERR = .TRUE.
RETURN
ENDIF
COTT = COST/SINT
C
C FIND THE EQUATION OF THE LINE FOR X = CONSTANT IN NEW COORDINATES
C
X0 = X-XTOP
B = - (SINT * X0)- (COTT * COST * X0)
C
C IF THE LINE HAS A ZERO SLOPE, THEN FIND THE SIMPLE SOLUTION
C
IF (COTT.EQ.0.0) THEN
YNEW = B
ELSE
DIVIS = 1.- (4. * COTT * A * B)
IF (DIVIS.LT.0.0) THEN
WRITE (*, 10050)ILINE (IL)
ERR = .TRUE.
RETURN
ENDIF
XDIVIS = SQRT (DIVIS)
Y1 = (1.+XDIVIS)/ (2. * COTT * A)
Y2 = (1.-XDIVIS)/ (2. * COTT * A)
IF ((ABS (Y1).LE.HALFW).AND. (ABS (Y2).GT.HALFW)) THEN
YNEW = Y1
ELSEIF ((ABS (Y2).LE.HALFW).AND. (ABS (Y1).GT.HALFW)) THEN
YNEW = Y2
ELSE
WRITE (*, 10060)ILINE (IL)
ENDIF
ENDIF
C
C TRANSLATE THIS XNEW TO A Y VALUE
C
XNEW = A * YNEW * YNEW
FRACT = (XNEW * SINT)+ (YNEW * COST)+YTOP
ENDIF
C
RETURN
C
10000 FORMAT (' POINTS GIVEN FOR LINE', I5, ' DO NOT DEFINE AN ARC')
10010 FORMAT (' NO X ON ARC LINE', I5, ' FOUND IN GETWT')
10020 FORMAT (' POINTS FOR LINE', I5, ' DOES NOT DEFINE A PARABOLA')
10030 FORMAT (' ZERO LINE LENGTH FOR PARABOLA LINE', I5, ' IN GETWT')
10040 FORMAT (' PARABOLA ALIGNMENT PROBLEMS FOR LINE', I5, ' IN GETWT')
10050 FORMAT (' PARABOLA INTERSECTION PROBLEMS FOR LINE', I5,
& ' IN GETWT')
10060 FORMAT (' PARABOLA SOLUTION PROBLEMS FOR LINE', I5, ' IN GETWT')
C
END
|
(************************************************************************)
(* * The Coq Proof Assistant / The Coq Development Team *)
(* v * Copyright INRIA, CNRS and contributors *)
(* <O___,, * (see version control and CREDITS file for authors & dates) *)
(* \VV/ **************************************************************)
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(* * (see LICENSE file for the text of the license) *)
(************************************************************************)
(** * MSetRBT : Implementation of MSetInterface via Red-Black trees *)
(** Initial author: Andrew W. Appel, 2011.
Extra modifications by: Pierre Letouzey
The design decisions behind this implementation are described here:
- Efficient Verified Red-Black Trees, by Andrew W. Appel, September 2011.
http://www.cs.princeton.edu/~appel/papers/redblack.pdf
Additional suggested reading:
- Red-Black Trees in a Functional Setting by Chris Okasaki.
Journal of Functional Programming, 9(4):471-477, July 1999.
http://www.eecs.usma.edu/webs/people/okasaki/jfp99redblack.pdf
- Red-black trees with types, by Stefan Kahrs.
Journal of Functional Programming, 11(4), 425-432, 2001.
- Functors for Proofs and Programs, by J.-C. Filliatre and P. Letouzey.
ESOP'04: European Symposium on Programming, pp. 370-384, 2004.
http://www.lri.fr/~filliatr/ftp/publis/fpp.ps.gz
*)
Require MSetGenTree.
Require Import Bool List BinPos Pnat Setoid SetoidList PeanoNat.
Local Open Scope list_scope.
(* For nicer extraction, we create induction principles
only when needed *)
Local Unset Elimination Schemes.
(** An extra function not (yet?) in MSetInterface.S *)
Module Type MSetRemoveMin (Import M:MSetInterface.S).
Parameter remove_min : t -> option (elt * t).
Axiom remove_min_spec1 : forall s k s',
remove_min s = Some (k,s') ->
min_elt s = Some k /\ remove k s [=] s'.
Axiom remove_min_spec2 : forall s, remove_min s = None -> Empty s.
End MSetRemoveMin.
(** The type of color annotation. *)
Inductive color := Red | Black.
Module Color.
Definition t := color.
End Color.
(** * Ops : the pure functions *)
Module Ops (X:Orders.OrderedType) <: MSetInterface.Ops X.
(** ** Generic trees instantiated with color *)
(** We reuse a generic definition of trees where the information
parameter is a color. Functions like mem or fold are also
provided by this generic functor. *)
Include MSetGenTree.Ops X Color.
Definition t := tree.
Local Notation Rd := (Node Red).
Local Notation Bk := (Node Black).
(** ** Basic tree *)
Inductive Intree (x : elt) : tree -> Prop :=
| IsRoottree : forall c l r y, x = y -> Intree x (Node c l y r)
| InLefttree : forall c l r y, Intree x l -> Intree x (Node c l y r)
| InRighttree : forall c l r y, Intree x r -> Intree x (Node c l y r).
Definition Intr := Intree.
Definition singleton (k: elt) : tree := Bk Leaf k Leaf.
(** ** Changing root color *)
Definition makeBlack t :=
match t with
| Leaf => Leaf
| Node _ a x b => Bk a x b
end.
Definition makeRed t :=
match t with
| Leaf => Leaf
| Node _ a x b => Rd a x b
end.
(** ** Balancing *)
(** We adapt when one side is not a true red-black tree.
Both sides have the same black depth. *)
Definition lbal l k r :=
match l with
| Rd (Rd a x b) y c => Rd (Bk a x b) y (Bk c k r)
| Rd a x (Rd b y c) => Rd (Bk a x b) y (Bk c k r)
| _ => Bk l k r
end.
Definition rbal l k r :=
match r with
| Rd (Rd b y c) z d => Rd (Bk l k b) y (Bk c z d)
| Rd b y (Rd c z d) => Rd (Bk l k b) y (Bk c z d)
| _ => Bk l k r
end.
(** A variant of [rbal], with reverse pattern order.
Is it really useful ? Should we always use it ? *)
Definition rbal' l k r :=
match r with
| Rd b y (Rd c z d) => Rd (Bk l k b) y (Bk c z d)
| Rd (Rd b y c) z d => Rd (Bk l k b) y (Bk c z d)
| _ => Bk l k r
end.
(** Balancing with different black depth.
One side is almost a red-black tree, while the other is
a true red-black tree, but with black depth + 1.
Used in deletion. *)
Definition lbalS l k r :=
match l with
| Rd a x b => Rd (Bk a x b) k r
| _ =>
match r with
| Bk a y b => rbal' l k (Rd a y b)
| Rd (Bk a y b) z c => Rd (Bk l k a) y (rbal' b z (makeRed c))
| _ => Rd l k r (* impossible *)
end
end.
Definition rbalS l k r :=
match r with
| Rd b y c => Rd l k (Bk b y c)
| _ =>
match l with
| Bk a x b => lbal (Rd a x b) k r
| Rd a x (Bk b y c) => Rd (lbal (makeRed a) x b) y (Bk c k r)
| _ => Rd l k r (* impossible *)
end
end.
(** ** Insertion *)
Fixpoint ins x s :=
match s with
| Leaf => Rd Leaf x Leaf
| Node c l y r =>
match X.compare x y with
| Eq => s
| Lt =>
match c with
| Red => Rd (ins x l) y r
| Black => lbal (ins x l) y r
end
| Gt =>
match c with
| Red => Rd l y (ins x r)
| Black => rbal l y (ins x r)
end
end
end.
Definition add x s := makeBlack (ins x s).
Fixpoint ins_tree x s :=
match s with
| Leaf => Rd Leaf x Leaf
| Node c l y r =>
match X.compare x y with
| Eq => Node c l x r
| Lt =>
match c with
| Red => Rd (ins_tree x l) y r
| Black => lbal (ins_tree x l) y r
end
| Gt =>
match c with
| Red => Rd l y (ins_tree x r)
| Black => rbal l y (ins_tree x r)
end
end
end.
Definition add_tree x s := makeBlack (ins_tree x s).
(** ** Deletion *)
Fixpoint append (l:tree) : tree -> tree :=
match l with
| Leaf => fun r => r
| Node lc ll lx lr =>
fix append_l (r:tree) : tree :=
match r with
| Leaf => l
| Node rc rl rx rr =>
match lc, rc with
| Red, Red =>
let lrl := append lr rl in
match lrl with
| Rd lr' x rl' => Rd (Rd ll lx lr') x (Rd rl' rx rr)
| _ => Rd ll lx (Rd lrl rx rr)
end
| Black, Black =>
let lrl := append lr rl in
match lrl with
| Rd lr' x rl' => Rd (Bk ll lx lr') x (Bk rl' rx rr)
| _ => lbalS ll lx (Bk lrl rx rr)
end
| Black, Red => Rd (append_l rl) rx rr
| Red, Black => Rd ll lx (append lr r)
end
end
end.
Fixpoint del x t :=
match t with
| Leaf => Leaf
| Node _ a y b =>
match X.compare x y with
| Eq => append a b
| Lt =>
match a with
| Bk _ _ _ => lbalS (del x a) y b
| _ => Rd (del x a) y b
end
| Gt =>
match b with
| Bk _ _ _ => rbalS a y (del x b)
| _ => Rd a y (del x b)
end
end
end.
Definition remove x t := makeBlack (del x t).
(** ** Removing minimal element *)
Fixpoint delmin l x r : (elt * tree) :=
match l with
| Leaf => (x,r)
| Node lc ll lx lr =>
let (k,l') := delmin ll lx lr in
match lc with
| Black => (k, lbalS l' x r)
| Red => (k, Rd l' x r)
end
end.
Definition remove_min t : option (elt * tree) :=
match t with
| Leaf => None
| Node _ l x r =>
let (k,t) := delmin l x r in
Some (k, makeBlack t)
end.
(** ** Tree-ification
We rebuild a tree of size [if pred then n-1 else n] as soon
as the list [l] has enough elements *)
Definition bogus : tree * list elt := (Leaf, nil).
Notation treeify_t := (list elt -> tree * list elt).
Definition treeify_zero : treeify_t :=
fun acc => (Leaf,acc).
Definition treeify_one : treeify_t :=
fun acc => match acc with
| x::acc => (Rd Leaf x Leaf, acc)
| _ => bogus
end.
Definition treeify_cont (f g : treeify_t) : treeify_t :=
fun acc =>
match f acc with
| (l, x::acc) =>
match g acc with
| (r, acc) => (Bk l x r, acc)
end
| _ => bogus
end.
Fixpoint treeify_aux (pred:bool)(n: positive) : treeify_t :=
match n with
| xH => if pred then treeify_zero else treeify_one
| xO n => treeify_cont (treeify_aux pred n) (treeify_aux true n)
| xI n => treeify_cont (treeify_aux false n) (treeify_aux pred n)
end.
Fixpoint plength_aux (l:list elt)(p:positive) := match l with
| nil => p
| _::l => plength_aux l (Pos.succ p)
end.
Definition plength l := plength_aux l 1.
Definition treeify (l:list elt) :=
fst (treeify_aux true (plength l) l).
(** ** Filtering *)
Fixpoint filter_aux (f: elt -> bool) s acc :=
match s with
| Leaf => acc
| Node _ l k r =>
let acc := filter_aux f r acc in
if f k then filter_aux f l (k::acc)
else filter_aux f l acc
end.
Definition filter (f: elt -> bool) (s: t) : t :=
treeify (filter_aux f s nil).
Fixpoint partition_aux (f: elt -> bool) s acc1 acc2 :=
match s with
| Leaf => (acc1,acc2)
| Node _ sl k sr =>
let (acc1, acc2) := partition_aux f sr acc1 acc2 in
if f k then partition_aux f sl (k::acc1) acc2
else partition_aux f sl acc1 (k::acc2)
end.
Definition partition (f: elt -> bool) (s:t) : t*t :=
let (ok,ko) := partition_aux f s nil nil in
(treeify ok, treeify ko).
(** ** Union, intersection, difference *)
(** union of the elements of [l1] and [l2] into a third [acc] list. *)
Fixpoint union_list l1 : list elt -> list elt -> list elt :=
match l1 with
| nil => @rev_append _
| x::l1' =>
fix union_l1 l2 acc :=
match l2 with
| nil => rev_append l1 acc
| y::l2' =>
match X.compare x y with
| Eq => union_list l1' l2' (x::acc)
| Lt => union_l1 l2' (y::acc)
| Gt => union_list l1' l2 (x::acc)
end
end
end.
Definition linear_union s1 s2 :=
treeify (union_list (rev_elements s1) (rev_elements s2) nil).
Fixpoint inter_list l1 : list elt -> list elt -> list elt :=
match l1 with
| nil => fun _ acc => acc
| x::l1' =>
fix inter_l1 l2 acc :=
match l2 with
| nil => acc
| y::l2' =>
match X.compare x y with
| Eq => inter_list l1' l2' (x::acc)
| Lt => inter_l1 l2' acc
| Gt => inter_list l1' l2 acc
end
end
end.
Definition linear_inter s1 s2 :=
treeify (inter_list (rev_elements s1) (rev_elements s2) nil).
Fixpoint diff_list l1 : list elt -> list elt -> list elt :=
match l1 with
| nil => fun _ acc => acc
| x::l1' =>
fix diff_l1 l2 acc :=
match l2 with
| nil => rev_append l1 acc
| y::l2' =>
match X.compare x y with
| Eq => diff_list l1' l2' acc
| Lt => diff_l1 l2' acc
| Gt => diff_list l1' l2 (x::acc)
end
end
end.
Definition linear_diff s1 s2 :=
treeify (diff_list (rev_elements s1) (rev_elements s2) nil).
(** [compare_height] returns:
- [Lt] if [height s2] is at least twice [height s1];
- [Gt] if [height s1] is at least twice [height s2];
- [Eq] if heights are approximately equal.
Warning: this is not an equivalence relation! but who cares.... *)
Definition skip_red t :=
match t with
| Rd t' _ _ => t'
| _ => t
end.
Definition skip_black t :=
match skip_red t with
| Bk t' _ _ => t'
| t' => t'
end.
Fixpoint compare_height (s1x s1 s2 s2x: tree) : comparison :=
match skip_red s1x, skip_red s1, skip_red s2, skip_red s2x with
| Node _ s1x' _ _, Node _ s1' _ _, Node _ s2' _ _, Node _ s2x' _ _ =>
compare_height (skip_black s1x') s1' s2' (skip_black s2x')
| _, Leaf, _, Node _ _ _ _ => Lt
| Node _ _ _ _, _, Leaf, _ => Gt
| Node _ s1x' _ _, Node _ s1' _ _, Node _ s2' _ _, Leaf =>
compare_height (skip_black s1x') s1' s2' Leaf
| Leaf, Node _ s1' _ _, Node _ s2' _ _, Node _ s2x' _ _ =>
compare_height Leaf s1' s2' (skip_black s2x')
| _, _, _, _ => Eq
end.
(** When one tree is quite smaller than the other, we simply
adds repeatively all its elements in the big one.
For trees of comparable height, we rather use [linear_union]. *)
Definition union (t1 t2: t) : t :=
match compare_height t1 t1 t2 t2 with
| Lt => fold add t1 t2
| Gt => fold add t2 t1
| Eq => linear_union t1 t2
end.
Definition diff (t1 t2: t) : t :=
match compare_height t1 t1 t2 t2 with
| Lt => filter (fun k => negb (mem k t2)) t1
| Gt => fold remove t2 t1
| Eq => linear_diff t1 t2
end.
Definition inter (t1 t2: t) : t :=
match compare_height t1 t1 t2 t2 with
| Lt => filter (fun k => mem k t2) t1
| Gt => filter (fun k => mem k t1) t2
| Eq => linear_inter t1 t2
end.
End Ops.
(** * MakeRaw : the pure functions and their specifications *)
Module Type MakeRaw (X:Orders.OrderedType) <: MSetInterface.RawSets X.
Include Ops X.
(** Generic definition of binary-search-trees and proofs of
specifications for generic functions such as mem or fold. *)
Include MSetGenTree.Props X Color.
Local Notation Rd := (Node Red).
Local Notation Bk := (Node Black).
Local Hint Immediate MX.eq_sym : core.
Local Hint Unfold In lt_tree gt_tree Ok : core.
Local Hint Constructors InT bst : core.
Local Hint Resolve MX.eq_refl MX.eq_trans MX.lt_trans ok : core.
Local Hint Resolve lt_leaf gt_leaf lt_tree_node gt_tree_node : core.
Local Hint Resolve lt_tree_not_in lt_tree_trans gt_tree_not_in gt_tree_trans : core.
Local Hint Resolve elements_spec2 : core.
(** This is new added part**)
(*Ltac clear_inversion H := inversion H; clear H; subst.
Ltac inv_ok := match goal with
| H:Ok (Node _ _ _ _) |- _ => clear_inversion H; inv_ok
| H:Ok Leaf |- _ => clear H; inv_ok
| H:bst ?x |- _ => change (Ok x) in H; inv_ok
| _ => idtac
end.
(** A tactic to repeat [inversion_clear] on all hyps of the
form [(f (Node _ _ _ _))] *)
Ltac is_tree_constr c :=
match c with
| Leaf => idtac
| Node _ _ _ _ => idtac
| _ => fail
end.
Ltac invtree f :=
match goal with
| H:f ?s |- _ => is_tree_constr s; clear_inversion H; invtree f
| H:f _ ?s |- _ => is_tree_constr s; clear_inversion H; invtree f
| H:f _ _ ?s |- _ => is_tree_constr s; clear_inversion H; invtree f
| _ => idtac
end.
*)
Ltac inv_tree := inv_ok; invtree Intree.
Ltac intuition_in_tree := repeat progress (intuition; inv_tree).
(** End new part **)
(** ** Singleton set *)
Lemma singleton_spec x y : InT y (singleton x) <-> X.eq y x.
Proof.
unfold singleton; intuition_in.
Qed.
#[global]
Instance singleton_ok x : Ok (singleton x).
Proof.
unfold singleton; auto.
Qed.
(** ** makeBlack, MakeRed *)
Lemma makeBlack_spec s x : InT x (makeBlack s) <-> InT x s.
Proof.
destruct s; simpl; intuition_in.
Qed.
Lemma makeBlack_spec_tree s x : Intree x (makeBlack s) <-> Intree x s.
Proof.
destruct s. simpl. intuition_in_tree. simpl. intuition_in. inversion H.
subst. constructor. auto. subst. apply InLefttree. auto. subst.
apply InRighttree. auto. inversion H. subst. constructor. auto. subst.
apply InLefttree. auto. subst. apply InRighttree. auto.
Qed.
Lemma makeRed_spec s x : InT x (makeRed s) <-> InT x s.
Proof.
destruct s. simpl. intuition_in. unfold makeRed. intuition eauto. intuition_in.
intuition_in.
Qed.
Lemma makeRed_spec_tree s x : Intree x (makeRed s) <-> Intree x s.
Proof.
destruct s. simpl. intuition_in. simpl. intuition_in. inversion H.
subst. constructor. auto. subst. apply InLefttree. auto. subst.
apply InRighttree. auto. inversion H. subst. constructor. auto. subst.
apply InLefttree. auto. subst. apply InRighttree. auto.
Qed.
Lemma Bk_Rd l x r y:
Intree y (Bk l x r) <-> Intree y (Rd l x r).
Proof. split. intros. inversion H. subst. constructor. auto. subst. apply InLefttree.
auto. subst. apply InRighttree. auto.
intros. inversion H. subst. constructor. auto. subst. apply InLefttree.
auto. subst. apply InRighttree. auto. Qed.
#[global]
Instance makeBlack_ok s `{Ok s} : Ok (makeBlack s).
Proof.
destruct s; simpl; ok.
Qed.
#[global]
Instance makeRed_ok s `{Ok s} : Ok (makeRed s).
Proof.
destruct s; simpl; ok.
Qed.
(** ** Generic handling for red-matching and red-red-matching *)
Definition isblack t :=
match t with Bk _ _ _ => True | _ => False end.
Definition notblack t :=
match t with Bk _ _ _ => False | _ => True end.
Definition notred t :=
match t with Rd _ _ _ => False | _ => True end.
Definition rcase {A} f g t : A :=
match t with
| Rd a x b => f a x b
| _ => g t
end.
Inductive rspec {A} f g : tree -> A -> Prop :=
| rred a x b : rspec f g (Rd a x b) (f a x b)
| relse t : notred t -> rspec f g t (g t).
Fact rmatch {A} f g t : rspec (A:=A) f g t (rcase f g t).
Proof.
destruct t as [|[|] l x r]; simpl; now constructor.
Qed.
Definition rrcase {A} f g t : A :=
match t with
| Rd (Rd a x b) y c => f a x b y c
| Rd a x (Rd b y c) => f a x b y c
| _ => g t
end.
Notation notredred := (rrcase (fun _ _ _ _ _ => False) (fun _ => True)).
Inductive rrspec {A} f g : tree -> A -> Prop :=
| rrleft a x b y c : rrspec f g (Rd (Rd a x b) y c) (f a x b y c)
| rrright a x b y c : rrspec f g (Rd a x (Rd b y c)) (f a x b y c)
| rrelse t : notredred t -> rrspec f g t (g t).
Fact rrmatch {A} f g t : rrspec (A:=A) f g t (rrcase f g t).
Proof.
destruct t as [|[|] l x r]; simpl; try now constructor.
destruct l as [|[|] ll lx lr], r as [|[|] rl rx rr]; now constructor.
Qed.
Definition rrcase' {A} f g t : A :=
match t with
| Rd a x (Rd b y c) => f a x b y c
| Rd (Rd a x b) y c => f a x b y c
| _ => g t
end.
Fact rrmatch' {A} f g t : rrspec (A:=A) f g t (rrcase' f g t).
Proof.
destruct t as [|[|] l x r]; simpl; try now constructor.
destruct l as [|[|] ll lx lr], r as [|[|] rl rx rr]; now constructor.
Qed.
(** Balancing operations are instances of generic match *)
Fact lbal_match l k r :
rrspec
(fun a x b y c => Rd (Bk a x b) y (Bk c k r))
(fun l => Bk l k r)
l
(lbal l k r).
Proof.
exact (rrmatch _ _ _).
Qed.
Fact rbal_match l k r :
rrspec
(fun a x b y c => Rd (Bk l k a) x (Bk b y c))
(fun r => Bk l k r)
r
(rbal l k r).
Proof.
exact (rrmatch _ _ _).
Qed.
Fact rbal'_match l k r :
rrspec
(fun a x b y c => Rd (Bk l k a) x (Bk b y c))
(fun r => Bk l k r)
r
(rbal' l k r).
Proof.
exact (rrmatch' _ _ _).
Qed.
Fact lbalS_match l x r :
rspec
(fun a y b => Rd (Bk a y b) x r)
(fun l =>
match r with
| Bk a y b => rbal' l x (Rd a y b)
| Rd (Bk a y b) z c => Rd (Bk l x a) y (rbal' b z (makeRed c))
| _ => Rd l x r
end)
l
(lbalS l x r).
Proof.
exact (rmatch _ _ _).
Qed.
Fact rbalS_match l x r :
rspec
(fun a y b => Rd l x (Bk a y b))
(fun r =>
match l with
| Bk a y b => lbal (Rd a y b) x r
| Rd a y (Bk b z c) => Rd (lbal (makeRed a) y b) z (Bk c x r)
| _ => Rd l x r
end)
r
(rbalS l x r).
Proof.
exact (rmatch _ _ _).
Qed.
(** ** Balancing for insertion *)
Lemma lbal_spec l x r y :
InT y (lbal l x r) <-> X.eq y x \/ InT y l \/ InT y r.
Proof.
case lbal_match; intuition_in.
Qed.
Lemma lbal_spec_tree l x r y :
Intree y (lbal l x r) <-> y = x \/ Intree y l \/ Intree y r.
Proof.
case lbal_match; intuition_in.
- inversion H.
* subst;right;left;constructor;auto.
* subst;right;left;apply InLefttree;apply Bk_Rd;auto.
* subst; inversion H1; subst; auto; subst;
right; left; apply InRighttree; auto; subst; auto.
- apply InRighttree. constructor. auto.
- inversion H.
* subst. constructor. auto.
* subst. apply InLefttree. apply Bk_Rd. auto.
* subst. apply InRighttree. apply InLefttree. auto.
- apply InRighttree. apply InRighttree. auto.
- inversion H.
* subst. right. left. apply InRighttree. constructor. auto.
* subst. right. left. inversion H1. subst. constructor. auto. subst.
apply InLefttree. auto. subst. apply InRighttree. apply InLefttree. auto.
* subst. inversion H1. subst. auto. subst.
right. left. apply InRighttree. apply InRighttree. auto. subst. auto.
- apply InRighttree. constructor. auto.
- inversion H.
* subst. apply InLefttree. constructor. auto.
* subst; apply InLefttree; apply InLefttree; auto.
* subst. inversion H1. subst. constructor. auto. subst.
apply InLefttree. apply InRighttree. auto. subst.
apply InRighttree. apply InLefttree. auto.
- apply InRighttree. apply InRighttree. auto.
- inversion H0. subst. auto. subst. right. left. auto. subst. right. right. auto.
- constructor. auto.
- apply InLefttree. auto.
- apply InRighttree. auto.
Qed.
#[global]
Instance lbal_ok l x r `(Ok l, Ok r, lt_tree x l, gt_tree x r) :
Ok (lbal l x r).
Proof.
destruct (lbal_match l x r); ok.
Qed.
Lemma rbal_spec l x r y :
InT y (rbal l x r) <-> X.eq y x \/ InT y l \/ InT y r.
Proof.
case rbal_match; intuition_in.
Qed.
Lemma rbal_spec_tree l x r y :
Intree y (rbal l x r) <-> y = x \/ Intree y l \/ Intree y r.
Proof.
case rbal_match; intuition_in_tree.
- right. right. apply InLefttree;constructor;auto.
- right. right. apply InLefttree;apply InLefttree;auto.
- right;right;constructor;auto.
- right;right;apply InLefttree;apply InRighttree;auto.
- right;right;apply InRighttree;auto.
- apply InLefttree;constructor;auto.
- apply InLefttree;apply InLefttree;auto.
- apply InRighttree;constructor;auto.
- constructor;auto.
- apply InLefttree;apply InRighttree;auto.
- apply InRighttree;apply InLefttree;auto.
- apply InRighttree;apply InRighttree;auto.
- right;right;constructor;auto.
- right;right;apply InLefttree;auto.
- right;right;apply InRighttree;constructor;auto.
- right;right;apply InRighttree;apply InLefttree;auto.
- right;right;apply InRighttree;apply InRighttree;auto.
- apply InLefttree;constructor;auto.
- apply InLefttree;apply InLefttree;auto.
- constructor;auto.
- apply InLefttree;apply InRighttree;auto.
- apply InRighttree;constructor;auto.
- apply InRighttree;apply InLefttree;auto.
- apply InRighttree;apply InRighttree;auto.
- constructor;auto.
- apply InLefttree;auto.
- apply InRighttree;auto.
Qed.
#[global]
Instance rbal_ok l x r `(Ok l, Ok r, lt_tree x l, gt_tree x r) :
Ok (rbal l x r).
Proof.
destruct (rbal_match l x r); ok.
Qed.
Lemma rbal'_spec l x r y :
InT y (rbal' l x r) <-> X.eq y x \/ InT y l \/ InT y r.
Proof.
case rbal'_match; intuition_in.
Qed.
Lemma rbal'_spec_tree l x r y :
Intree y (rbal' l x r) <-> y = x \/ Intree y l \/ Intree y r.
Proof.
case rbal'_match; intuition_in_tree.
- right. right. apply InLefttree;constructor;auto.
- right. right. apply InLefttree;apply InLefttree;auto.
- right;right;constructor;auto.
- right;right;apply InLefttree;apply InRighttree;auto.
- right;right;apply InRighttree;auto.
- apply InLefttree;constructor;auto.
- apply InLefttree;apply InLefttree;auto.
- apply InRighttree;constructor;auto.
- constructor;auto.
- apply InLefttree;apply InRighttree;auto.
- apply InRighttree;apply InLefttree;auto.
- apply InRighttree;apply InRighttree;auto.
- right;right;constructor;auto.
- right;right;apply InLefttree;auto.
- right;right;apply InRighttree;constructor;auto.
- right;right;apply InRighttree;apply InLefttree;auto.
- right;right;apply InRighttree;apply InRighttree;auto.
- apply InLefttree;constructor;auto.
- apply InLefttree;apply InLefttree;auto.
- constructor;auto.
- apply InLefttree;apply InRighttree;auto.
- apply InRighttree;constructor;auto.
- apply InRighttree;apply InLefttree;auto.
- apply InRighttree;apply InRighttree;auto.
- constructor;auto.
- apply InLefttree;auto.
- apply InRighttree;auto.
Qed.
#[global]
Instance rbal'_ok l x r `(Ok l, Ok r, lt_tree x l, gt_tree x r) :
Ok (rbal' l x r).
Proof.
destruct (rbal'_match l x r); ok.
Qed.
Hint Rewrite In_node_iff In_leaf_iff
makeRed_spec makeBlack_spec lbal_spec rbal_spec rbal'_spec : rb.
Hint Rewrite In_node_iff In_leaf_iff
makeRed_spec_tree makeBlack_spec_tree lbal_spec_tree rbal_spec_tree : rbtree.
Ltac descolor := destruct_all Color.t.
Ltac destree t := destruct t as [|[|] ? ? ?].
Ltac autorew := autorewrite with rb.
Ltac autorew_tree := autorewrite with rbtree.
Tactic Notation "autorew" "in" ident(H) := autorewrite with rb in H.
Tactic Notation "autorew_tree" "in" ident(H) := autorewrite with rbtree in H.
(** ** Insertion *)
Lemma ins_spec : forall s x y,
InT y (ins x s) <-> X.eq y x \/ InT y s.
Proof.
induct s x.
- intuition_in.
- intuition_in. setoid_replace y with x; eauto.
- descolor; autorew; rewrite IHl; intuition_in.
- descolor; autorew; rewrite IHr; intuition_in.
Qed.
Lemma ins_tree_spec_tree1 : forall s x y,
~X.eq x y /\ Intree y (ins_tree x s) -> Intree y s.
Proof.
induct s x.
- intuition_in_tree. destruct H0. auto.
- intuition_in_tree.
* destruct H1. auto.
* apply InLefttree;auto.
* apply InRighttree;auto.
- destruct i.
+ intuition_in_tree.
-- constructor. auto.
-- apply InLefttree. apply (IHl x). auto.
-- apply InRighttree. auto.
+ destruct H. apply lbal_spec_tree in H1. destruct H1.
** constructor. auto.
** destruct H1. apply InLefttree. apply (IHl x). auto. auto.
apply InRighttree. auto.
- destruct i.
+ intuition_in_tree.
-- constructor. auto.
-- apply InLefttree. auto.
-- apply InRighttree. apply (IHr x). auto.
+ destruct H. apply rbal_spec_tree in H1. destruct H1.
** constructor. auto.
** destruct H1. apply InLefttree. auto.
apply InRighttree. apply (IHr x). auto.
Qed.
Lemma ins_tree_spec_tree2 : forall s x y,
Intree y s/\~X.eq x y -> Intree y (ins_tree x s).
Proof.
induct s x.
- intuition_in_tree.
- intuition_in_tree.
* apply InLefttree;auto.
* apply InRighttree;auto.
- destruct H. destruct i. intuition_in_tree.
* constructor. auto.
* apply InLefttree;auto.
* apply InRighttree;auto.
* apply lbal_spec_tree. intuition_in_tree.
- destruct H. destruct i. intuition_in_tree.
* constructor. auto.
* apply InLefttree;auto.
* apply InRighttree;auto.
* apply rbal_spec_tree. intuition_in_tree.
Qed.
Lemma ins_spec0_tree : forall s x y,
~Intree y s -> Intree y (ins x s) -> x = y .
Proof.
induct s x.
- intuition_in_tree.
- intuition_in_tree.
- descolor. intuition_in_tree.
* assert(Intree x' (Rd l x' r)). constructor;auto. intuition_in_tree.
* apply IHl. intro. assert(Intree y (Rd l x' r)). apply InLefttree;auto. intuition_in_tree.
auto.
* assert(Intree y (Rd l x' r)). apply InRighttree;auto. intuition_in_tree.
* apply lbal_spec_tree in H0. intuition_in_tree.
+ assert(Intree y (Bk l x' r)). constructor. auto. intuition_in_tree.
+ apply IHl. intro. assert(Intree y (Bk l x' r)). apply InLefttree;auto. intuition_in_tree. auto.
+ assert(Intree y (Bk l x' r)). apply InRighttree;auto. intuition_in_tree.
- destruct i. intuition_in_tree.
* assert(Intree x' (Rd l x' r)). constructor;auto. intuition_in_tree.
* assert(Intree y (Rd l x' r)). apply InLefttree;auto. intuition_in_tree.
* apply IHr. intro. assert(Intree y (Rd l x' r)). apply InRighttree;auto. intuition_in_tree. auto.
* apply rbal_spec_tree in H0. intuition_in_tree.
+ assert(Intree y (Bk l x' r)). constructor. auto. intuition_in_tree.
+assert(Intree y (Bk l x' r)). apply InLefttree;auto. intuition_in_tree.
+ apply IHr. intro. assert(Intree y (Bk l x' r)). apply InRighttree;auto. intuition_in_tree. auto.
Qed.
Lemma ins_spec1_tree : forall s x y,
Intree y s -> Intree y (ins x s).
Proof.
induct s x.
- intuition_in_tree.
- intuition_in_tree.
- descolor. intuition_in_tree.
* constructor;auto.
* apply InLefttree;apply IHl;auto.
* apply InRighttree;auto.
* apply lbal_spec_tree. intuition_in_tree.
- descolor. intuition_in_tree.
* constructor;auto.
* apply InLefttree;auto.
* apply InRighttree;auto.
* apply rbal_spec_tree. intuition_in_tree.
Qed.
Lemma ins_spec2_tree : forall s x y,
~X.eq x y -> Intree y (ins x s) -> Intree y s.
Proof.
induct s x.
- intuition_in_tree. destruct H. auto.
- intuition_in_tree.
- descolor. intuition_in_tree.
* constructor;auto.
* apply IHl in H3. destruct H3.
** apply InLefttree;auto. constructor. auto.
** apply InLefttree;auto. apply InLefttree. auto.
** apply InLefttree;auto. apply InRighttree. auto.
** auto.
* apply InRighttree;auto.
* apply lbal_spec_tree in H0. intuition_in_tree.
+ constructor. auto.
+ apply IHl in H. destruct H.
*** apply InLefttree;auto. constructor. auto.
*** apply InLefttree;auto. apply InLefttree;auto.
*** apply InLefttree;auto. apply InRighttree;auto.
*** auto.
+ apply InRighttree;auto.
- destruct i. intuition_in_tree.
+ constructor. auto.
+apply InLefttree;auto.
+ apply InRighttree;auto. apply (IHr x). auto. auto.
+ apply rbal_spec_tree in H0. intuition_in_tree.
*** constructor. auto.
*** apply InLefttree;auto.
*** apply IHr in H0. apply InRighttree;auto. auto.
Qed.
Lemma ins_spec_tree : forall s x y,
not (InT x s) -> Intree y (ins x s) <-> x = y \/ Intree y s.
Proof.
induct s x.
- intuition_in_tree. constructor. auto.
- assert(Hr:~ InT x r). intro. destruct H. apply InRight. auto.
assert(Hl:~ InT x l). intro. destruct H. apply InLeft. auto.
split.
* intro H1. intuition_in_tree.
* intro H1. destruct H1.
+ subst. destruct H. constructor. auto.
+ destruct H. constructor. auto.
- assert(Hr:~ InT x r). intro. destruct H. apply InRight. auto.
assert(Hl:~ InT x l). intro. destruct H. apply InLeft. auto.
* destruct i.
+ split.
++ intro. inversion H1.
-- subst. right. constructor. auto.
-- subst. apply IHl in H3. destruct H3. auto.
right. apply InLefttree. auto. auto.
-- subst. right. apply InRighttree. auto.
++ intro. destruct H1. apply InLefttree. apply IHl. auto. auto.
inversion H1.
-- subst. constructor. auto.
-- subst. apply InLefttree. apply IHl. auto. auto.
-- subst. apply InRighttree. auto.
+ split.
++ intro. apply lbal_spec_tree in H1. destruct H1.
-- right. constructor. auto.
-- destruct H1. apply IHl in H1. destruct H1. auto. right.
apply InLefttree. auto. auto. right. apply InRighttree. auto.
++ intros. apply lbal_spec_tree. destruct H1.
-- right. left. apply IHl. auto. auto.
-- inversion H1.
+++ subst. auto.
+++ subst. right. left. apply IHl. auto. auto.
+++ subst. auto.
- assert(Hr:~ InT x r). intro. destruct H. apply InRight. auto.
assert(Hl:~ InT x l). intro. destruct H. apply InLeft. auto.
split.
* destruct i.
+ intro. inversion H1.
-- subst. right. constructor. auto.
-- subst. right. apply InLefttree. auto.
-- subst. apply IHr in H3. destruct H3. auto. right.
apply InRighttree. auto. auto.
+ intro. apply rbal_spec_tree in H1. destruct H1.
-- right. constructor. auto.
-- destruct H1. right. apply InLefttree. auto. apply IHr in H1.
destruct H1. auto. right. apply InRighttree;auto. auto.
* destruct i.
+ intro. destruct H1. apply InRighttree;auto. apply IHr. auto.
auto. inversion H1.
-- subst. constructor. auto.
-- subst. apply InLefttree. auto.
-- subst. apply InRighttree. apply IHr. auto. auto.
+ intro. apply rbal_spec_tree. destruct H1.
-- right. right. apply IHr. auto. auto.
-- inversion H1.
++ subst. auto.
++ subst. auto.
++ subst. right. right. apply IHr. auto. auto.
Qed.
Hint Rewrite ins_spec : rb.
Hint Rewrite ins_spec1_tree ins_spec2_tree : rbtree.
#[global]
Instance ins_ok s x `{Ok s} : Ok (ins x s).
Proof.
induct s x; auto; descolor;
(apply lbal_ok || apply rbal_ok || ok); auto;
intros y; autorew; intuition; order.
Qed.
Lemma add_spec' s x y :
InT y (add x s) <-> X.eq y x \/ InT y s.
Proof.
unfold add. now autorew.
Qed.
Lemma add_tree_spec'_tree s x y :
~X.eq x y -> Intree y (add_tree x s) <-> Intree y s.
Proof. unfold add_tree. rewrite makeBlack_spec_tree.
split. intros. apply ins_tree_spec_tree1 with (x:=x). auto.
intros. apply ins_tree_spec_tree2 with (x:=x). auto.
Qed.
Lemma add_spec'0_tree s x y :
~Intree y s -> Intree y (add x s) -> x = y.
Proof. unfold add. rewrite makeBlack_spec_tree.
apply ins_spec0_tree.
Qed.
Lemma add_spec'1_tree s x y :
Intree y s -> Intree y (add x s).
Proof. unfold add. rewrite makeBlack_spec_tree.
apply ins_spec1_tree.
Qed.
Lemma add_spec'2_tree s x y :
~X.eq x y -> Intree y (add x s) -> Intree y s.
Proof. unfold add. rewrite makeBlack_spec_tree.
apply ins_spec2_tree.
Qed.
Lemma add_spec'_tree s x y :
not (InT x s) -> Intree y (add x s) <-> x = y \/ Intree y s.
Proof. unfold add. rewrite makeBlack_spec_tree.
apply ins_spec_tree.
Qed.
Hint Rewrite add_spec' : rb.
Hint Rewrite add_spec'2_tree add_spec'1_tree: rbtree.
Lemma add_spec s x y `{Ok s} :
InT y (add x s) <-> X.eq y x \/ InT y s.
Proof.
apply add_spec'.
Qed.
Lemma add_spec_tree s x y `{Ok s} :
not (InT x s) -> Intree y (add x s) <-> x = y \/ Intree y s.
Proof.
apply add_spec'_tree.
Qed.
Lemma add_spec0_tree s x y `{Ok s} :
~Intree y s -> Intree y (add x s) -> x = y .
Proof.
apply add_spec'0_tree.
Qed.
Lemma add_spec1_tree s x y `{Ok s} :
Intree y s -> Intree y (add x s).
Proof.
apply add_spec'1_tree.
Qed.
Lemma add_spec2_tree s x y `{Ok s} :
~ X.eq x y -> Intree y (add x s) -> Intree y s.
Proof.
apply add_spec'2_tree.
Qed.
Lemma add_tree_spec_tree s x y `{Ok s} :
~ X.eq x y -> Intree y (add_tree x s) <-> Intree y s.
Proof.
apply add_tree_spec'_tree.
Qed.
#[global]
Instance add_ok s x `{Ok s} : Ok (add x s).
Proof.
unfold add; auto_tc.
Qed.
(** ** Balancing for deletion *)
Lemma lbalS_spec l x r y :
InT y (lbalS l x r) <-> X.eq y x \/ InT y l \/ InT y r.
Proof.
case lbalS_match.
- intros; autorew; intuition_in.
- clear l. intros l _.
destruct r as [|[|] rl rx rr].
* autorew. intuition_in.
* destree rl; autorew; intuition_in.
* autorew. intuition_in.
Qed.
Lemma lbalS_spec_tree l x r y :
Intree y (lbalS l x r) <-> y = x \/ Intree y l \/ Intree y r.
Proof.
case lbalS_match.
- intuition_in_tree.
* right;left;constructor;auto.
* right;left;apply InLefttree;auto.
* right;left;apply InRighttree;auto.
* constructor;auto.
* apply InLefttree;constructor;auto.
* apply InLefttree;apply InLefttree;auto.
* apply InLefttree; apply InRighttree;auto.
* apply InRighttree;auto.
- intros t _.
destruct l as [|[|] ll lx lr].
* intuition_in_tree.
+ destruct r.
{ inversion H. subst. auto. subst. auto. subst. inversion H1. }
{ destruct t0.
{ destruct r1.
{ inversion H. subst. auto. subst. auto. subst. auto. }
{ destruct t0. inversion H. subst. auto. subst. auto. subst. auto.
inversion H. subst.
inversion H. subst. right;right;apply InLefttree;constructor;auto.
subst. right;right;apply InLefttree;constructor;auto.
subst. right;right;apply InLefttree;constructor;auto.
subst. inversion H1. subst. auto. subst. auto. subst.
right;right;apply InLefttree;apply InLefttree;auto.
subst. apply rbal'_spec_tree in H1.
destruct H1. right;right;constructor;auto.
destruct H0. right;right;apply InLefttree;apply InRighttree;auto.
right;right;apply InRighttree;apply makeRed_spec_tree;auto. }
}
{ apply rbal'_spec_tree in H. destruct H. auto.
destruct H. auto. apply Bk_Rd in H. auto.
}
}
+ destruct r. constructor;auto. destruct t0.
destruct r1. constructor;auto. destruct t0.
constructor;auto. apply InLefttree;constructor;auto.
apply rbal'_spec_tree. auto.
+ destruct r. apply InLefttree;auto. destruct t0.
destruct r1. apply InLefttree;auto. destruct t0.
apply InLefttree;auto. apply InLefttree;apply InLefttree;auto.
apply rbal'_spec_tree. auto.
+ destruct r. inversion H. destruct t0.
destruct r1. apply InRighttree;auto. destruct t0.
apply InRighttree;auto. inversion H.
{ subst. apply InRighttree.
apply rbal'_spec_tree. auto. }
{ subst. inversion H1. subst. constructor. auto.
subst. apply InLefttree;apply InRighttree;auto.
subst. apply InRighttree.
apply rbal'_spec_tree. auto.
}
{ subst. apply InRighttree.
apply rbal'_spec_tree. apply makeRed_spec_tree in H1. auto. }
{ apply rbal'_spec_tree. apply Bk_Rd in H. auto. }
* intuition_in_tree.
+ destruct r.
{ inversion H. subst. auto. subst. auto. subst. inversion H1. }
{ destruct t0.
{ destruct r1.
{ inversion H. subst. auto. subst. auto. subst. auto. }
{ destruct t0. inversion H. subst. auto. subst. auto. subst. auto.
inversion H. subst.
inversion H. subst. right;right;apply InLefttree;constructor;auto.
subst. right;right;apply InLefttree;constructor;auto.
subst. right;right;apply InLefttree;constructor;auto.
subst. inversion H1. subst. auto. subst. auto. subst.
right;right;apply InLefttree;apply InLefttree;auto.
subst. apply rbal'_spec_tree in H1.
destruct H1. right;right;constructor;auto.
destruct H0. right;right;apply InLefttree;apply InRighttree;auto.
right;right;apply InRighttree;apply makeRed_spec_tree;auto. }
}
{ apply rbal'_spec_tree in H. destruct H. auto.
destruct H. auto. apply Bk_Rd in H. auto.
}
}
+ destruct r. constructor;auto. destruct t0.
destruct r1. constructor;auto. destruct t0.
constructor;auto. apply InLefttree;constructor;auto.
apply rbal'_spec_tree. auto.
+ destruct r. apply InLefttree;auto. destruct t0.
destruct r1. apply InLefttree;auto. destruct t0.
apply InLefttree;auto. apply InLefttree;apply InLefttree;auto.
apply rbal'_spec_tree. auto.
+ destruct r. inversion H. destruct t0.
destruct r1. apply InRighttree;auto. destruct t0.
apply InRighttree;auto. inversion H.
{ subst. apply InRighttree.
apply rbal'_spec_tree. auto. }
{ subst. inversion H1. subst. constructor. auto.
subst. apply InLefttree;apply InRighttree;auto.
subst. apply InRighttree.
apply rbal'_spec_tree. auto.
}
{ subst. apply InRighttree.
apply rbal'_spec_tree. apply makeRed_spec_tree in H1. auto. }
{ apply rbal'_spec_tree. apply Bk_Rd in H. auto. }
* intuition_in_tree.
+ destruct r.
{ inversion H. subst. auto. subst. auto. subst. inversion H1. }
{ destruct t0.
{ destruct r1.
{ inversion H. subst. auto. subst. auto. subst. auto. }
{ destruct t0. inversion H. subst. auto. subst. auto. subst. auto.
inversion H. subst.
inversion H. subst. right;right;apply InLefttree;constructor;auto.
subst. right;right;apply InLefttree;constructor;auto.
subst. right;right;apply InLefttree;constructor;auto.
subst. inversion H1. subst. auto. subst. auto. subst.
right;right;apply InLefttree;apply InLefttree;auto.
subst. apply rbal'_spec_tree in H1.
destruct H1. right;right;constructor;auto.
destruct H0. right;right;apply InLefttree;apply InRighttree;auto.
right;right;apply InRighttree;apply makeRed_spec_tree;auto. }
}
{ apply rbal'_spec_tree in H. destruct H. auto.
destruct H. auto. apply Bk_Rd in H. auto.
}
}
+ destruct r. constructor;auto. destruct t0.
destruct r1. constructor;auto. destruct t0.
constructor;auto. apply InLefttree;constructor;auto.
apply rbal'_spec_tree. auto.
+ destruct r. apply InLefttree;auto. destruct t0.
destruct r1. apply InLefttree;auto. destruct t0.
apply InLefttree;auto. apply InLefttree;apply InLefttree;auto.
apply rbal'_spec_tree. auto.
+ destruct r. inversion H. destruct t0.
destruct r1. apply InRighttree;auto. destruct t0.
apply InRighttree;auto. inversion H.
{ subst. apply InRighttree.
apply rbal'_spec_tree. auto. }
{ subst. inversion H1. subst. constructor. auto.
subst. apply InLefttree;apply InRighttree;auto.
subst. apply InRighttree.
apply rbal'_spec_tree. auto.
}
{ subst. apply InRighttree.
apply rbal'_spec_tree. apply makeRed_spec_tree in H1. auto. }
{ apply rbal'_spec_tree. apply Bk_Rd in H. auto. }
Qed.
#[global]
Instance lbalS_ok l x r :
forall `(Ok l, Ok r, lt_tree x l, gt_tree x r), Ok (lbalS l x r).
Proof.
case lbalS_match; intros.
- ok.
- destruct r as [|[|] rl rx rr].
* ok.
* destruct rl as [|[|] rll rlx rlr]; intros; ok.
+ apply rbal'_ok; ok.
intros w; autorew; auto.
+ intros w; autorew.
destruct 1 as [Hw|[Hw|Hw]]; try rewrite Hw; eauto.
* autorew. apply rbal'_ok; ok.
Qed.
Lemma rbalS_spec l x r y :
InT y (rbalS l x r) <-> X.eq y x \/ InT y l \/ InT y r.
Proof.
case rbalS_match.
- intros; autorew; intuition_in.
- intros t _.
destruct l as [|[|] ll lx lr].
* autorew. intuition_in.
* destruct lr as [|[|] lrl lrx lrr]; autorew; intuition_in.
* autorew. intuition_in.
Qed.
Lemma rbalS_spec_tree l x r y :
Intree y (rbalS l x r) <-> y = x \/ Intree y l \/ Intree y r.
Proof. split. {
case rbalS_match.
- intuition_in. inversion H. subst. auto. subst. right. left. auto.
subst. right. right. apply Bk_Rd. auto.
- intros t _.
destruct l as [|[|] ll lx lr].
* intuition_in. inversion H. subst. auto. subst. right. left. auto.
subst. right. right. auto.
* destruct lr as [|[|] lrl lrx lrr]; intuition_in.
-- inversion H. subst. auto. subst. right. left. auto. subst. right. right. auto.
-- inversion H. subst. auto. subst. right. left. auto. subst. right. right. auto.
-- inversion H. subst. right. left. apply InRighttree. constructor. auto. subst.
right. left. apply lbal_spec_tree in H1. destruct H1.
constructor. auto. destruct H0. apply InLefttree. apply makeRed_spec_tree.
auto. apply InRighttree. apply InLefttree. auto. subst.
inversion H1. subst. auto. subst. right. left. apply InRighttree.
apply InRighttree. auto. subst. right. right. auto.
* intuition_in. apply lbal_spec_tree in H. destruct H. auto.
destruct H. right. left. apply Bk_Rd. auto. right. right. auto.
}
{ case rbalS_match.
- intuition_in_tree. apply Bk_Rd. constructor. auto.
apply Bk_Rd. apply InLefttree. auto.
apply Bk_Rd. apply InRighttree. constructor. auto.
apply Bk_Rd. apply InRighttree. apply InLefttree. auto.
apply Bk_Rd. apply InRighttree. apply InRighttree. auto.
- intros t _.
destruct l as [|[|] ll lx lr].
* intuition_in_tree. constructor. auto. apply InRighttree. auto.
* destruct lr as [|[|] lrl lrx lrr]; intuition_in_tree.
+ constructor. auto.
+ apply InLefttree. constructor;auto.
+ apply InLefttree. apply InLefttree. auto.
+ apply InRighttree. auto.
+ constructor. auto.
+ apply InLefttree. constructor;auto.
+ apply InLefttree. apply InLefttree. auto.
+ apply InLefttree. apply InRighttree. constructor;auto.
+ apply InLefttree. apply InRighttree. apply InLefttree. auto.
+ apply InLefttree. apply InRighttree. apply InRighttree. auto.
+ apply InRighttree. auto.
+ apply InRighttree. constructor. auto.
+ apply InLefttree. apply lbal_spec_tree. auto.
+ apply InLefttree. apply lbal_spec_tree. right. left.
apply makeRed_spec_tree. auto.
+ constructor. auto.
+ apply InLefttree. apply lbal_spec_tree. auto.
+ apply InRighttree. apply InLefttree. auto.
+ apply InRighttree. apply InRighttree. auto.
* intuition_in_tree.
+ apply lbal_spec_tree. auto.
+ apply lbal_spec_tree. right. left. constructor;auto.
+ apply lbal_spec_tree. right. left. apply InLefttree. auto.
+ apply lbal_spec_tree. right. left. apply InRighttree. auto.
+ apply lbal_spec_tree. right. right. auto.
} Qed.
#[global]
Instance rbalS_ok l x r :
forall `(Ok l, Ok r, lt_tree x l, gt_tree x r), Ok (rbalS l x r).
Proof.
case rbalS_match; intros.
- ok.
- destruct l as [|[|] ll lx lr].
* ok.
* destruct lr as [|[|] lrl lrx lrr]; intros; ok.
+ apply lbal_ok; ok.
intros w; autorew; auto.
+ intros w; autorew.
destruct 1 as [Hw|[Hw|Hw]]; try rewrite Hw; eauto.
* apply lbal_ok; ok.
Qed.
Hint Rewrite lbalS_spec rbalS_spec : rb.
Hint Rewrite lbalS_spec_tree rbalS_spec_tree : rbtree.
(** ** Append for deletion *)
Ltac append_tac l r :=
induction l as [| lc ll _ lx lr IHlr];
[intro r; simpl
|induction r as [| rc rl IHrl rx rr _];
[simpl
|destruct lc, rc;
[specialize (IHlr rl); clear IHrl
|simpl;
assert (Hr:notred (Bk rl rx rr)) by (simpl; trivial);
set (r:=Bk rl rx rr) in *; clearbody r; clear IHrl rl rx rr;
specialize (IHlr r)
|change (append _ _) with (Rd (append (Bk ll lx lr) rl) rx rr);
assert (Hl:notred (Bk ll lx lr)) by (simpl; trivial);
set (l:=Bk ll lx lr) in *; clearbody l; clear IHlr ll lx lr
|specialize (IHlr rl); clear IHrl]]].
Fact append_rr_match ll lx lr rl rx rr :
rspec
(fun a x b => Rd (Rd ll lx a) x (Rd b rx rr))
(fun t => Rd ll lx (Rd t rx rr))
(append lr rl)
(append (Rd ll lx lr) (Rd rl rx rr)).
Proof.
exact (rmatch _ _ _).
Qed.
Fact append_bb_match ll lx lr rl rx rr :
rspec
(fun a x b => Rd (Bk ll lx a) x (Bk b rx rr))
(fun t => lbalS ll lx (Bk t rx rr))
(append lr rl)
(append (Bk ll lx lr) (Bk rl rx rr)).
Proof.
exact (rmatch _ _ _).
Qed.
Lemma append_spec l r x :
InT x (append l r) <-> InT x l \/ InT x r.
Proof.
revert r.
append_tac l r; autorew; try tauto.
- (* Red / Red *)
revert IHlr; case append_rr_match;
[intros a y b | intros t Ht]; autorew; tauto.
- (* Black / Black *)
revert IHlr; case append_bb_match;
[intros a y b | intros t Ht]; autorew; tauto.
Qed.
Lemma append_spec_tree l r x :
Intree x (append l r) <-> Intree x l \/ Intree x r.
Proof.
revert r.
append_tac l r; try tauto.
- intuition_in_tree.
- intuition_in_tree.
- (* Red / Red *)
revert IHlr; case append_rr_match;
[intros | intros t Ht].
+ intuition_in_tree.
* assert(Intree x0 (Rd a x0 b)). constructor. auto.
apply H in H0. destruct H0. left. apply InRighttree. auto.
right. apply InLefttree. auto.
* left. constructor. auto.
* left. apply InLefttree. auto.
* assert(Intree x (Rd a x0 b)). apply InLefttree. auto.
apply H in H0. destruct H0. left. apply InRighttree. auto.
right. apply InLefttree. auto.
* right. constructor. auto.
* assert(Intree x (Rd a x0 b)). apply InRighttree. auto.
apply H in H0. destruct H0. left. apply InRighttree. auto.
right. apply InLefttree. auto.
* right. apply InRighttree. auto.
* apply InLefttree. constructor. auto.
* apply InLefttree. apply InLefttree. auto.
* constructor. auto.
* apply InLefttree. apply InRighttree. auto.
* apply InRighttree. apply InLefttree. auto.
* constructor. auto.
* apply InLefttree. apply InRighttree. auto.
* constructor. auto.
* apply InLefttree. apply InRighttree. auto.
* apply InLefttree. apply InRighttree. auto.
* apply InLefttree. apply InRighttree. auto.
* apply InRighttree. apply InLefttree. auto.
* apply InRighttree. apply InLefttree. auto.
* apply InRighttree. apply InLefttree. auto.
* apply InRighttree. constructor. auto.
* constructor. auto.
* constructor. auto.
* constructor. auto.
* constructor. auto.
* apply InLefttree. apply InRighttree. auto.
* apply InLefttree. apply InRighttree. auto.
* constructor. auto.
* apply InLefttree. apply InRighttree. auto.
* apply InRighttree. apply InLefttree. auto.
* constructor. auto.
* apply InLefttree. apply InRighttree. auto.
* apply InRighttree. apply InLefttree. auto.
* apply InRighttree. apply InRighttree. auto.
+ intuition_in_tree.
* left. constructor. auto.
* left. apply InLefttree. auto.
* right. constructor. auto.
* left. apply InRighttree. auto.
* right. apply InLefttree. auto.
* right. apply InRighttree. auto.
* constructor. auto.
* apply InLefttree. auto.
* apply InRighttree. apply InLefttree. auto.
* apply InRighttree. apply InLefttree. auto.
* apply InRighttree. constructor. auto.
* apply InRighttree. apply InLefttree. auto.
* apply InRighttree. apply InLefttree. auto.
* apply InRighttree. apply InRighttree. auto.
- intuition_in_tree.
+ left. constructor. auto.
+ left. apply InLefttree. auto.
+ left. apply InRighttree. auto.
+ constructor. auto.
+ apply InLefttree. auto.
+ apply InRighttree. auto.
+ apply InRighttree. auto.
+ apply InRighttree. auto.
+ apply InRighttree. auto.
- intuition_in_tree.
+ right. constructor. auto.
+ right. apply InLefttree. auto.
+ right. apply InRighttree. auto.
+ apply InLefttree. auto.
+ apply InLefttree. auto.
+ constructor. auto.
+ apply InLefttree. auto.
+ apply InLefttree. auto.
+ apply InRighttree. auto.
- revert IHlr; case append_bb_match;
[intros | intros t Ht].
+ intuition_in_tree.
* assert(Intree x0 (Rd a x0 b)). constructor. auto.
apply H in H0. destruct H0. left. apply InRighttree. auto.
right. apply InLefttree. auto.
* left. constructor. auto.
* left. apply InLefttree. auto.
* assert(Intree x (Rd a x0 b)). apply InLefttree. auto.
apply H in H0. destruct H0. left. apply InRighttree. auto.
right. apply InLefttree. auto.
* right. constructor. auto.
* assert(Intree x (Rd a x0 b)). apply InRighttree. auto.
apply H in H0. destruct H0. left. apply InRighttree. auto.
right. apply InLefttree. auto.
* right. apply InRighttree. auto.
* apply InLefttree. constructor. auto.
* apply InLefttree. apply InLefttree. auto.
* constructor. auto.
* apply InLefttree. apply InRighttree. auto.
* apply InRighttree. apply InLefttree. auto.
* constructor. auto.
* apply InLefttree. apply InRighttree. auto.
* constructor. auto.
* apply InLefttree. apply InRighttree. auto.
* apply InLefttree. apply InRighttree. auto.
* apply InLefttree. apply InRighttree. auto.
* apply InRighttree. apply InLefttree. auto.
* apply InRighttree. apply InLefttree. auto.
* apply InRighttree. apply InLefttree. auto.
* apply InRighttree. constructor. auto.
* constructor. auto.
* constructor. auto.
* constructor. auto.
* constructor. auto.
* apply InLefttree. apply InRighttree. auto.
* apply InLefttree. apply InRighttree. auto.
* constructor. auto.
* apply InLefttree. apply InRighttree. auto.
* apply InRighttree. apply InLefttree. auto.
* constructor. auto.
* apply InLefttree. apply InRighttree. auto.
* apply InRighttree. apply InLefttree. auto.
* apply InRighttree. apply InRighttree. auto.
+ intuition_in_tree.
* apply lbalS_spec_tree in H0. destruct H0 as [H0 | H0 ]. left. constructor.
auto. destruct H0 as [H0 | H0 ]. left. apply InLefttree. auto.
intuition_in_tree. right. constructor. auto. left. apply InRighttree. auto.
right. apply InLefttree. auto. right. apply InRighttree. auto.
* apply lbalS_spec_tree. auto.
* apply lbalS_spec_tree. auto.
* apply lbalS_spec_tree. right. right. apply InLefttree. auto.
* apply lbalS_spec_tree. right. right. apply InLefttree. auto.
* apply lbalS_spec_tree. right. right. constructor. auto.
* apply lbalS_spec_tree. right. right. apply InLefttree. auto.
* apply lbalS_spec_tree. right. right. apply InLefttree. auto.
* apply lbalS_spec_tree. right. right. apply InRighttree. auto.
Qed.
Hint Rewrite append_spec : rb.
Hint Rewrite append_spec_tree : rbtree.
Lemma append_ok : forall x l r `{Ok l, Ok r},
lt_tree x l -> gt_tree x r -> Ok (append l r).
Proof.
append_tac l r.
- (* Leaf / _ *)
trivial.
- (* _ / Leaf *)
trivial.
- (* Red / Red *)
intros; inv.
assert (IH : Ok (append lr rl)) by (apply IHlr; eauto). clear IHlr.
assert (X.lt lx rx) by (transitivity x; eauto).
assert (G : gt_tree lx (append lr rl)).
{ intros w. autorew. destruct 1; [|transitivity x]; eauto. }
assert (L : lt_tree rx (append lr rl)).
{ intros w. autorew. destruct 1; [transitivity x|]; eauto. }
revert IH G L; case append_rr_match; intros; ok.
- (* Red / Black *)
intros; ok.
intros w; autorew; destruct 1; eauto.
- (* Black / Red *)
intros; ok.
intros w; autorew; destruct 1; eauto.
- (* Black / Black *)
intros; inv.
assert (IH : Ok (append lr rl)) by (apply IHlr; eauto). clear IHlr.
assert (X.lt lx rx) by (transitivity x; eauto).
assert (G : gt_tree lx (append lr rl)).
{ intros w. autorew. destruct 1; [|transitivity x]; eauto. }
assert (L : lt_tree rx (append lr rl)).
{ intros w. autorew. destruct 1; [transitivity x|]; eauto. }
revert IH G L; case append_bb_match; intros; ok.
apply lbalS_ok; ok.
Qed.
(** ** Deletion *)
Lemma del_spec : forall s x y `{Ok s},
InT y (del x s) <-> InT y s /\ ~X.eq y x.
Proof.
induct s x.
- intuition_in.
- autorew; intuition_in.
+ assert (X.lt y x') by eauto. order.
+ assert (X.lt x' y) by eauto. order.
+ order.
- destruct l as [|[|] ll lx lr]; autorew;
rewrite ?IHl by trivial; intuition_in; order.
- destruct r as [|[|] rl rx rr]; autorew;
rewrite ?IHr by trivial; intuition_in; order.
Qed.
Lemma Intree_InT s y :
Intree y s -> InT y s.
Proof.
induction s as [ | c l Hl x r Hr ]; simpl; auto.
- intuition. inversion H.
- intuition_in_tree.
Qed.
Lemma del_spec_tree : forall s x y `{Ok s},
Intree y (del x s) <-> Intree y s/\~X.eq x y.
Proof. split.
{
induction s.
- intuition_in_tree. inversion H0.
- intros. intuition_in_tree. simpl in H0.
destruct (X.compare x t1).
-- apply append_spec_tree in H0.
destruct H0.
+++ apply InLefttree. auto.
+++ apply InRighttree. auto.
-- destruct s1.
+++ inversion H0.
--- subst. constructor. auto.
--- subst. inversion H3.
--- subst. apply InRighttree. auto.
+++ destruct t2.
--- inversion H0. subst. constructor. auto.
subst. apply InLefttree. apply H. auto.
subst. apply InRighttree. auto.
--- intuition_in. apply lbalS_spec_tree in H0. destruct H0. constructor. auto.
destruct H0. apply InLefttree. apply H. auto.
apply InRighttree. auto.
-- destruct s2.
+++ inversion H0.
--- subst. constructor. auto.
--- subst. apply InLefttree. auto.
--- subst. inversion H3.
+++ destruct t2.
--- intuition_in_tree. constructor. auto.
apply InLefttree. auto.
apply InRighttree. constructor. auto. apply InRighttree.
apply InLefttree. auto. apply InRighttree. apply InRighttree. auto.
--- intuition_in_tree.
apply rbalS_spec_tree in H0. destruct H0. constructor. auto.
destruct H0. apply InLefttree. auto. apply InRighttree. apply H1.
auto.
-- apply Intree_InT in H0. apply del_spec in H0.
destruct H0. destruct H3. intuition_in_tree. auto.
}
{ induction s.
- intuition_in_tree.
- intros. intuition_in_tree. simpl.
destruct (X.compare x t1) eqn:Hc.
* destruct (X.compare_spec x t1). intuition_in_tree.
inversion Hc. inversion Hc.
* destruct s1.
+ simpl. constructor. auto.
+ destruct t2.
++ intuition_in_tree. constructor. auto.
++ apply lbalS_spec_tree. auto.
* destruct s2.
+ simpl. constructor. auto.
+ destruct t2.
++ constructor. auto.
++ intuition_in_tree. apply rbalS_spec_tree. auto.
* simpl. destruct (X.compare x t1) eqn:Hc.
+ destruct (X.compare_spec x t1). apply append_spec_tree.
auto. inversion Hc. inversion Hc.
+ destruct s1.
++ intuition_in_tree.
++ destruct t2.
+++ intuition_in_tree.
---- apply InLefttree. apply H3.
---- apply InLefttree. apply H3.
---- apply InLefttree. apply H3.
+++ apply lbalS_spec_tree. auto.
+ destruct s2.
++ apply InLefttree. auto.
++ destruct t2.
+++ apply InLefttree. auto.
+++ apply rbalS_spec_tree. auto.
* simpl. destruct (X.compare x t1) eqn:Hc.
++ apply append_spec_tree. auto.
++ destruct s1.
+++ apply InRighttree. auto.
+++ destruct t2.
---- apply InRighttree. auto.
---- apply lbalS_spec_tree. auto.
++ destruct s2.
+++ inversion H0.
+++ destruct t2.
---- apply InRighttree. auto.
---- apply rbalS_spec_tree. auto.
} Qed.
Hint Rewrite del_spec : rb.
#[global]
Instance del_ok s x `{Ok s} : Ok (del x s).
Proof.
induct s x.
- trivial.
- eapply append_ok; eauto.
- assert (lt_tree x' (del x l)).
{ intro w. autorew; trivial. destruct 1. eauto. }
destruct l as [|[|] ll lx lr]; auto_tc.
- assert (gt_tree x' (del x r)).
{ intro w. autorew; trivial. destruct 1. eauto. }
destruct r as [|[|] rl rx rr]; auto_tc.
Qed.
Lemma remove_spec s x y `{Ok s} :
InT y (remove x s) <-> InT y s /\ ~X.eq y x.
Proof.
unfold remove. rewrite makeBlack_spec. rewrite del_spec. split. auto. auto. auto.
Qed.
Lemma remove_spec_tree s x y `{Ok s} :
Intree y (remove x s) <-> Intree y s/\ ~X.eq x y.
Proof.
unfold remove. rewrite makeBlack_spec_tree. apply del_spec_tree. auto.
Qed.
Hint Rewrite remove_spec : rb.
#[global]
Instance remove_ok s x `{Ok s} : Ok (remove x s).
Proof.
unfold remove; auto_tc.
Qed.
(** Elements_tree **)
Lemma elements_spec1'_tree : forall s acc x,
List.In x (elements_aux acc s) <-> Intree x s \/ List.In x acc.
Proof.
induction s as [ | c l Hl x r Hr ]; simpl; auto.
- intuition.
inversion H0.
- intros.
rewrite Hl.
destruct (Hr acc x0); clear Hl Hr.
intuition_in; inversion_clear H3; intuition_in.
* subst. left. apply InLefttree. constructor. auto.
* left. apply InLefttree. apply InLefttree. auto.
* left. apply InLefttree. apply InRighttree. auto.
* subst. left. constructor. auto.
* left. apply InRighttree. auto.
* subst. simpl. auto.
Qed.
Lemma elements_spec_tree : forall s x, List.In x (elements s) <-> Intree x s.
Proof.
intros; generalize (elements_spec1'_tree s nil x); intuition.
inversion_clear H0.
Qed.
(** ** Removing the minimal element *)
Lemma delmin_spec l y r c x s' `{O : Ok (Node c l y r)} :
delmin l y r = (x,s') ->
min_elt (Node c l y r) = Some x /\ del x (Node c l y r) = s'.
Proof.
revert y r c x s' O.
induction l as [|lc ll IH ly lr _].
- simpl. intros y r _ x s' _. injection 1; intros; subst.
now rewrite MX.compare_refl.
- intros y r c x s' O.
simpl delmin.
specialize (IH ly lr). destruct delmin as (x0,s0).
destruct (IH lc x0 s0); clear IH; [ok|trivial|].
remember (Node lc ll ly lr) as l.
simpl min_elt in *.
intros E.
replace x0 with x in * by (destruct lc; now injection E).
split.
* subst l; intuition.
* assert (X.lt x y).
{ inversion_clear O.
assert (InT x l) by now apply min_elt_spec1. auto. }
simpl. case X.compare_spec; try order.
destruct lc; injection E; subst l s0; auto.
Qed.
Lemma remove_min_spec1 s x s' `{Ok s}:
remove_min s = Some (x,s') ->
min_elt s = Some x /\ remove x s = s'.
Proof.
unfold remove_min.
destruct s as [|c l y r]; try easy.
generalize (delmin_spec l y r c).
destruct delmin as (x0,s0). intros D.
destruct (D x0 s0) as (->,<-); auto.
fold (remove x0 (Node c l y r)).
inversion_clear 1; auto.
Qed.
Lemma remove_min_spec2 s : remove_min s = None -> Empty s.
Proof.
unfold remove_min.
destruct s as [|c l y r].
- easy.
- now destruct delmin.
Qed.
Lemma remove_min_ok (s:t) `{Ok s}:
match remove_min s with
| Some (_,s') => Ok s'
| None => True
end.
Proof.
generalize (remove_min_spec1 s).
destruct remove_min as [(x0,s0)|]; auto.
intros R. destruct (R x0 s0); auto. subst s0. auto_tc.
Qed.
(** ** Treeify *)
Notation ifpred p n := (if p then pred n else n%nat).
Definition treeify_invariant size (f:treeify_t) :=
forall acc,
size <= length acc ->
let (t,acc') := f acc in
cardinal t = size /\ acc = elements t ++ acc'.
Lemma treeify_zero_spec : treeify_invariant 0 treeify_zero.
Proof.
intro. simpl. auto.
Qed.
Lemma treeify_one_spec : treeify_invariant 1 treeify_one.
Proof.
intros [|x acc]; simpl; auto; inversion 1.
Qed.
Lemma treeify_cont_spec f g size1 size2 size :
treeify_invariant size1 f ->
treeify_invariant size2 g ->
size = S (size1 + size2) ->
treeify_invariant size (treeify_cont f g).
Proof.
intros Hf Hg EQ acc LE. unfold treeify_cont.
specialize (Hf acc).
destruct (f acc) as (t1,acc1).
destruct Hf as (Hf1,Hf2).
{ transitivity size; trivial. subst. rewrite <- Nat.add_succ_r. apply Nat.le_add_r. }
destruct acc1 as [|x acc1].
{ exfalso. revert LE. apply Nat.lt_nge. subst.
rewrite app_nil_r, <- elements_cardinal.
apply (Nat.succ_le_mono (cardinal t1)), Nat.le_add_r. }
specialize (Hg acc1).
destruct (g acc1) as (t2,acc2).
destruct Hg as (Hg1,Hg2).
{ revert LE. subst.
rewrite app_length, <- elements_cardinal. simpl.
rewrite Nat.add_succ_r, <- Nat.succ_le_mono.
apply Nat.add_le_mono_l. }
rewrite elements_node, app_ass. now subst.
Qed.
Lemma treeify_aux_spec n (p:bool) :
treeify_invariant (ifpred p (Pos.to_nat n)) (treeify_aux p n).
Proof.
revert p.
induction n as [n|n|]; intros p; simpl treeify_aux.
- eapply treeify_cont_spec; [ apply (IHn false) | apply (IHn p) | ].
rewrite Pos2Nat.inj_xI.
assert (H := Pos2Nat.is_pos n). apply Nat.neq_0_lt_0 in H.
destruct p; simpl; intros; rewrite Nat.add_0_r; trivial.
now rewrite <- Nat.add_succ_r, Nat.succ_pred; trivial.
- eapply treeify_cont_spec; [ apply (IHn p) | apply (IHn true) | ].
rewrite Pos2Nat.inj_xO.
assert (H := Pos2Nat.is_pos n). apply Nat.neq_0_lt_0 in H.
rewrite <- Nat.add_succ_r, Nat.succ_pred by trivial.
destruct p; simpl; intros; rewrite Nat.add_0_r; trivial.
symmetry. now apply Nat.add_pred_l.
- destruct p; [ apply treeify_zero_spec | apply treeify_one_spec ].
Qed.
Lemma plength_aux_spec l p :
Pos.to_nat (plength_aux l p) = length l + Pos.to_nat p.
Proof.
revert p. induction l; trivial. simpl plength_aux.
intros. now rewrite IHl, Pos2Nat.inj_succ, Nat.add_succ_r.
Qed.
Lemma plength_spec l : Pos.to_nat (plength l) = S (length l).
Proof.
unfold plength. rewrite plength_aux_spec. apply Nat.add_1_r.
Qed.
Lemma treeify_elements l : elements (treeify l) = l.
Proof.
assert (H := treeify_aux_spec (plength l) true l).
unfold treeify. destruct treeify_aux as (t,acc); simpl in *.
destruct H as (H,H'). { now rewrite plength_spec. }
subst l. rewrite plength_spec, app_length, <- elements_cardinal in *.
destruct acc.
* now rewrite app_nil_r.
* exfalso. revert H. simpl.
rewrite Nat.add_succ_r, Nat.add_comm.
apply Nat.succ_add_discr.
Qed.
Lemma treeify_spec x l : InT x (treeify l) <-> InA X.eq x l.
Proof.
intros. now rewrite <- elements_spec1, treeify_elements.
Qed.
Lemma treeify_ok l : sort X.lt l -> Ok (treeify l).
Proof.
intros. apply elements_sort_ok. rewrite treeify_elements; auto.
Qed.
(** ** Filter *)
#[deprecated(since="8.11",note="Lemma filter_app has been moved to module List.")]
Notation filter_app := List.filter_app.
Lemma filter_aux_elements s f acc :
filter_aux f s acc = List.filter f (elements s) ++ acc.
Proof.
revert acc.
induction s as [|c l IHl x r IHr]; trivial.
intros acc.
rewrite elements_node, List.filter_app. simpl.
destruct (f x); now rewrite IHl, IHr, app_ass.
Qed.
Lemma filter_elements s f :
elements (filter f s) = List.filter f (elements s).
Proof.
unfold filter.
now rewrite treeify_elements, filter_aux_elements, app_nil_r.
Qed.
Lemma filter_spec s x f :
Proper (X.eq==>Logic.eq) f ->
(InT x (filter f s) <-> InT x s /\ f x = true).
Proof.
intros Hf.
rewrite <- elements_spec1, filter_elements, filter_InA, elements_spec1;
now auto_tc.
Qed.
#[global]
Instance filter_ok s f `(Ok s) : Ok (filter f s).
Proof.
apply elements_sort_ok.
rewrite filter_elements.
apply filter_sort with X.eq; auto_tc.
Qed.
(** ** Partition *)
Lemma partition_aux_spec s f acc1 acc2 :
partition_aux f s acc1 acc2 =
(filter_aux f s acc1, filter_aux (fun x => negb (f x)) s acc2).
Proof.
revert acc1 acc2.
induction s as [ | c l Hl x r Hr ]; simpl.
- trivial.
- intros acc1 acc2.
destruct (f x); simpl; now rewrite Hr, Hl.
Qed.
Lemma partition_spec s f :
partition f s = (filter f s, filter (fun x => negb (f x)) s).
Proof.
unfold partition, filter. now rewrite partition_aux_spec.
Qed.
Lemma partition_spec1 s f :
Proper (X.eq==>Logic.eq) f ->
Equal (fst (partition f s)) (filter f s).
Proof. now rewrite partition_spec. Qed.
Lemma partition_spec2 s f :
Proper (X.eq==>Logic.eq) f ->
Equal (snd (partition f s)) (filter (fun x => negb (f x)) s).
Proof. now rewrite partition_spec. Qed.
#[global]
Instance partition_ok1 s f `(Ok s) : Ok (fst (partition f s)).
Proof. rewrite partition_spec; now apply filter_ok. Qed.
#[global]
Instance partition_ok2 s f `(Ok s) : Ok (snd (partition f s)).
Proof. rewrite partition_spec; now apply filter_ok. Qed.
(** ** An invariant for binary list functions with accumulator. *)
Ltac inA :=
rewrite ?InA_app_iff, ?InA_cons, ?InA_nil, ?InA_rev in *; auto_tc.
Record INV l1 l2 acc : Prop := {
l1_sorted : sort X.lt (rev l1);
l2_sorted : sort X.lt (rev l2);
acc_sorted : sort X.lt acc;
l1_lt_acc x y : InA X.eq x l1 -> InA X.eq y acc -> X.lt x y;
l2_lt_acc x y : InA X.eq x l2 -> InA X.eq y acc -> X.lt x y}.
Local Hint Resolve l1_sorted l2_sorted acc_sorted : core.
Lemma INV_init s1 s2 `(Ok s1, Ok s2) :
INV (rev_elements s1) (rev_elements s2) nil.
Proof.
rewrite !rev_elements_rev.
split; rewrite ?rev_involutive; auto; intros; now inA.
Qed.
Lemma INV_sym l1 l2 acc : INV l1 l2 acc -> INV l2 l1 acc.
Proof.
destruct 1; now split.
Qed.
Lemma INV_drop x1 l1 l2 acc :
INV (x1 :: l1) l2 acc -> INV l1 l2 acc.
Proof.
intros (l1s,l2s,accs,l1a,l2a). simpl in *.
destruct (sorted_app_inv _ _ l1s) as (U & V & W); auto.
split; auto.
Qed.
Lemma INV_eq x1 x2 l1 l2 acc :
INV (x1 :: l1) (x2 :: l2) acc -> X.eq x1 x2 ->
INV l1 l2 (x1 :: acc).
Proof.
intros (U,V,W,X,Y) EQ. simpl in *.
destruct (sorted_app_inv _ _ U) as (U1 & U2 & U3); auto.
destruct (sorted_app_inv _ _ V) as (V1 & V2 & V3); auto.
split; auto.
- constructor; auto. apply InA_InfA with X.eq; auto_tc.
- intros x y; inA; intros Hx [Hy|Hy].
+ apply U3; inA.
+ apply X; inA.
- intros x y; inA; intros Hx [Hy|Hy].
+ rewrite Hy, EQ; apply V3; inA.
+ apply Y; inA.
Qed.
Lemma INV_lt x1 x2 l1 l2 acc :
INV (x1 :: l1) (x2 :: l2) acc -> X.lt x1 x2 ->
INV (x1 :: l1) l2 (x2 :: acc).
Proof.
intros (U,V,W,X,Y) EQ. simpl in *.
destruct (sorted_app_inv _ _ U) as (U1 & U2 & U3); auto.
destruct (sorted_app_inv _ _ V) as (V1 & V2 & V3); auto.
split; auto.
- constructor; auto. apply InA_InfA with X.eq; auto_tc.
- intros x y; inA; intros Hx [Hy|Hy].
+ rewrite Hy; clear Hy. destruct Hx; [order|].
transitivity x1; auto. apply U3; inA.
+ apply X; inA.
- intros x y; inA; intros Hx [Hy|Hy].
+ rewrite Hy. apply V3; inA.
+ apply Y; inA.
Qed.
Lemma INV_rev l1 l2 acc :
INV l1 l2 acc -> Sorted X.lt (rev_append l1 acc).
Proof.
intros. rewrite rev_append_rev.
apply SortA_app with X.eq; eauto with *.
intros x y. inA. eapply @l1_lt_acc; eauto.
Qed.
(** ** union *)
Lemma union_list_ok l1 l2 acc :
INV l1 l2 acc -> sort X.lt (union_list l1 l2 acc).
Proof.
revert l2 acc.
induction l1 as [|x1 l1 IH1];
[intro l2|induction l2 as [|x2 l2 IH2]];
intros acc inv.
- eapply INV_rev, INV_sym; eauto.
- eapply INV_rev; eauto.
- simpl. case X.compare_spec; intro C.
* apply IH1. eapply INV_eq; eauto.
* apply (IH2 (x2::acc)). eapply INV_lt; eauto.
* apply IH1. eapply INV_sym, INV_lt; eauto. now apply INV_sym.
Qed.
#[global]
Instance linear_union_ok s1 s2 `(Ok s1, Ok s2) :
Ok (linear_union s1 s2).
Proof.
unfold linear_union. now apply treeify_ok, union_list_ok, INV_init.
Qed.
#[global]
Instance fold_add_ok s1 s2 `(Ok s1, Ok s2) :
Ok (fold add s1 s2).
Proof.
rewrite fold_spec, <- fold_left_rev_right.
unfold elt in *.
induction (rev (elements s1)); simpl; unfold flip in *; auto_tc.
Qed.
#[global]
Instance union_ok s1 s2 `(Ok s1, Ok s2) : Ok (union s1 s2).
Proof.
unfold union. destruct compare_height; auto_tc.
Qed.
Lemma union_list_spec x l1 l2 acc :
InA X.eq x (union_list l1 l2 acc) <->
InA X.eq x l1 \/ InA X.eq x l2 \/ InA X.eq x acc.
Proof.
revert l2 acc.
induction l1 as [|x1 l1 IH1].
- intros l2 acc; simpl. rewrite rev_append_rev. inA. tauto.
- induction l2 as [|x2 l2 IH2]; intros acc; simpl.
* rewrite rev_append_rev. inA. tauto.
* case X.compare_spec; intro C.
+ rewrite IH1, !InA_cons, C; tauto.
+ rewrite (IH2 (x2::acc)), !InA_cons. tauto.
+ rewrite IH1, !InA_cons; tauto.
Qed.
Lemma linear_union_spec s1 s2 x :
InT x (linear_union s1 s2) <-> InT x s1 \/ InT x s2.
Proof.
unfold linear_union.
rewrite treeify_spec, union_list_spec, !rev_elements_rev.
rewrite !InA_rev, InA_nil, !elements_spec1 by auto_tc.
tauto.
Qed.
Lemma fold_add_spec s1 s2 x :
InT x (fold add s1 s2) <-> InT x s1 \/ InT x s2.
Proof.
rewrite fold_spec, <- fold_left_rev_right.
rewrite <- (elements_spec1 s1), <- InA_rev by auto_tc.
unfold elt in *.
induction (rev (elements s1)); simpl.
- rewrite InA_nil. tauto.
- unfold flip. rewrite add_spec', IHl, InA_cons. tauto.
Qed.
Lemma union_spec' s1 s2 x :
InT x (union s1 s2) <-> InT x s1 \/ InT x s2.
Proof.
unfold union. destruct compare_height.
- apply linear_union_spec.
- apply fold_add_spec.
- rewrite fold_add_spec. tauto.
Qed.
Lemma union_spec : forall s1 s2 y `{Ok s1, Ok s2},
(InT y (union s1 s2) <-> InT y s1 \/ InT y s2).
Proof.
intros; apply union_spec'.
Qed.
(** ** inter *)
Lemma inter_list_ok l1 l2 acc :
INV l1 l2 acc -> sort X.lt (inter_list l1 l2 acc).
Proof.
revert l2 acc.
induction l1 as [|x1 l1 IH1]; [|induction l2 as [|x2 l2 IH2]]; simpl.
- eauto.
- eauto.
- intros acc inv.
case X.compare_spec; intro C.
* apply IH1. eapply INV_eq; eauto.
* apply (IH2 acc). eapply INV_sym, INV_drop, INV_sym; eauto.
* apply IH1. eapply INV_drop; eauto.
Qed.
#[global]
Instance linear_inter_ok s1 s2 `(Ok s1, Ok s2) :
Ok (linear_inter s1 s2).
Proof.
unfold linear_inter. now apply treeify_ok, inter_list_ok, INV_init.
Qed.
#[global]
Instance inter_ok s1 s2 `(Ok s1, Ok s2) : Ok (inter s1 s2).
Proof.
unfold inter. destruct compare_height; auto_tc.
Qed.
Lemma inter_list_spec x l1 l2 acc :
sort X.lt (rev l1) ->
sort X.lt (rev l2) ->
(InA X.eq x (inter_list l1 l2 acc) <->
(InA X.eq x l1 /\ InA X.eq x l2) \/ InA X.eq x acc).
Proof.
revert l2 acc.
induction l1 as [|x1 l1 IH1].
- intros l2 acc; simpl. inA. tauto.
- induction l2 as [|x2 l2 IH2]; intros acc.
* simpl. inA. tauto.
* simpl. intros U V.
destruct (sorted_app_inv _ _ U) as (U1 & U2 & U3); auto.
destruct (sorted_app_inv _ _ V) as (V1 & V2 & V3); auto.
case X.compare_spec; intro C.
+ rewrite IH1, !InA_cons, C; tauto.
+ rewrite (IH2 acc); auto. inA. intuition; try order.
assert (X.lt x x1) by (apply U3; inA). order.
+ rewrite IH1; auto. inA. intuition; try order.
assert (X.lt x x2) by (apply V3; inA). order.
Qed.
Lemma linear_inter_spec s1 s2 x `(Ok s1, Ok s2) :
InT x (linear_inter s1 s2) <-> InT x s1 /\ InT x s2.
Proof.
unfold linear_inter.
rewrite !rev_elements_rev, treeify_spec, inter_list_spec
by (rewrite rev_involutive; auto_tc).
rewrite !InA_rev, InA_nil, !elements_spec1 by auto_tc. tauto.
Qed.
Local Instance mem_proper s `(Ok s) :
Proper (X.eq ==> Logic.eq) (fun k => mem k s).
Proof.
intros x y EQ. apply Bool.eq_iff_eq_true; rewrite !mem_spec; auto.
now rewrite EQ.
Qed.
Lemma inter_spec s1 s2 y `{Ok s1, Ok s2} :
InT y (inter s1 s2) <-> InT y s1 /\ InT y s2.
Proof.
unfold inter. destruct compare_height.
- now apply linear_inter_spec.
- rewrite filter_spec, mem_spec by auto_tc; tauto.
- rewrite filter_spec, mem_spec by auto_tc; tauto.
Qed.
(** ** difference *)
Lemma diff_list_ok l1 l2 acc :
INV l1 l2 acc -> sort X.lt (diff_list l1 l2 acc).
Proof.
revert l2 acc.
induction l1 as [|x1 l1 IH1];
[intro l2|induction l2 as [|x2 l2 IH2]];
intros acc inv.
- eauto.
- unfold diff_list. eapply INV_rev; eauto.
- simpl. case X.compare_spec; intro C.
* apply IH1. eapply INV_drop, INV_sym, INV_drop, INV_sym; eauto.
* apply (IH2 acc). eapply INV_sym, INV_drop, INV_sym; eauto.
* apply IH1. eapply INV_sym, INV_lt; eauto. now apply INV_sym.
Qed.
#[global]
Instance diff_inter_ok s1 s2 `(Ok s1, Ok s2) :
Ok (linear_diff s1 s2).
Proof.
unfold linear_inter. now apply treeify_ok, diff_list_ok, INV_init.
Qed.
#[global]
Instance fold_remove_ok s1 s2 `(Ok s2) :
Ok (fold remove s1 s2).
Proof.
rewrite fold_spec, <- fold_left_rev_right.
unfold elt in *.
induction (rev (elements s1)); simpl; unfold flip in *; auto_tc.
Qed.
#[global]
Instance diff_ok s1 s2 `(Ok s1, Ok s2) : Ok (diff s1 s2).
Proof.
unfold diff. destruct compare_height; auto_tc.
Qed.
Lemma diff_list_spec x l1 l2 acc :
sort X.lt (rev l1) ->
sort X.lt (rev l2) ->
(InA X.eq x (diff_list l1 l2 acc) <->
(InA X.eq x l1 /\ ~InA X.eq x l2) \/ InA X.eq x acc).
Proof.
revert l2 acc.
induction l1 as [|x1 l1 IH1].
- intros l2 acc; simpl. inA. tauto.
- induction l2 as [|x2 l2 IH2]; intros acc.
+ intros; simpl. rewrite rev_append_rev. inA. tauto.
+ simpl. intros U V.
destruct (sorted_app_inv _ _ U) as (U1 & U2 & U3); auto.
destruct (sorted_app_inv _ _ V) as (V1 & V2 & V3); auto.
case X.compare_spec; intro C.
* rewrite IH1; auto. f_equiv. inA. intuition; try order.
assert (X.lt x x1) by (apply U3; inA). order.
* rewrite (IH2 acc); auto. f_equiv. inA. intuition; try order.
assert (X.lt x x1) by (apply U3; inA). order.
* rewrite IH1; auto. inA. intuition; try order.
left; split; auto. destruct 1.
-- order.
-- assert (X.lt x x2) by (apply V3; inA). order.
Qed.
Lemma linear_diff_spec s1 s2 x `(Ok s1, Ok s2) :
InT x (linear_diff s1 s2) <-> InT x s1 /\ ~InT x s2.
Proof.
unfold linear_diff.
rewrite !rev_elements_rev, treeify_spec, diff_list_spec
by (rewrite rev_involutive; auto_tc).
rewrite !InA_rev, InA_nil, !elements_spec1 by auto_tc. tauto.
Qed.
Lemma fold_remove_spec s1 s2 x `(Ok s2) :
InT x (fold remove s1 s2) <-> InT x s2 /\ ~InT x s1.
Proof.
rewrite fold_spec, <- fold_left_rev_right.
rewrite <- (elements_spec1 s1), <- InA_rev by auto_tc.
unfold elt in *.
induction (rev (elements s1)); simpl; intros.
- rewrite InA_nil. intuition.
- unfold flip in *. rewrite remove_spec, IHl, InA_cons.
+ tauto.
+ clear IHl. induction l; simpl; auto_tc.
Qed.
Lemma diff_spec s1 s2 y `{Ok s1, Ok s2} :
InT y (diff s1 s2) <-> InT y s1 /\ ~InT y s2.
Proof.
unfold diff. destruct compare_height.
- now apply linear_diff_spec.
- rewrite filter_spec, Bool.negb_true_iff,
<- Bool.not_true_iff_false, mem_spec;
intuition.
intros x1 x2 EQ. f_equal. now apply mem_proper.
- now apply fold_remove_spec.
Qed.
End MakeRaw.
(** * Balancing properties
We now prove that all operations preserve a red-black invariant,
and that trees have hence a logarithmic depth.
*)
Module BalanceProps(X:Orders.OrderedType)(Import M : MakeRaw X).
Local Notation Rd := (Node Red).
Local Notation Bk := (Node Black).
Import M.MX.
(** ** Red-Black invariants *)
(** In a red-black tree :
- a red node has no red children
- the black depth at each node is the same along all paths.
The black depth is here an argument of the predicate. *)
Inductive rbt : nat -> tree -> Prop :=
| RB_Leaf : rbt 0 Leaf
| RB_Rd n l k r :
notred l -> notred r -> rbt n l -> rbt n r -> rbt n (Rd l k r)
| RB_Bk n l k r : rbt n l -> rbt n r -> rbt (S n) (Bk l k r).
(** A red-red tree is almost a red-black tree, except that it has
a _red_ root node which _may_ have red children. Note that a
red-red tree is hence non-empty, and all its strict subtrees
are red-black. *)
Inductive rrt (n:nat) : tree -> Prop :=
| RR_Rd l k r : rbt n l -> rbt n r -> rrt n (Rd l k r).
(** An almost-red-black tree is almost a red-black tree, except that
it's permitted to have two red nodes in a row at the very root (only).
We implement this notion by saying that a quasi-red-black tree
is either a red-black tree or a red-red tree. *)
Inductive arbt (n:nat)(t:tree) : Prop :=
| ARB_RB : rbt n t -> arbt n t
| ARB_RR : rrt n t -> arbt n t.
(** The main exported invariant : being a red-black tree for some
black depth. *)
Class Rbt (t:tree) := RBT : exists d, rbt d t.
(** ** Basic tactics and results about red-black *)
Scheme rbt_ind := Induction for rbt Sort Prop.
Local Hint Constructors rbt rrt arbt : core.
Local Hint Extern 0 (notred _) => (exact I) : core.
Ltac invrb := intros; invtree rrt; invtree rbt; try contradiction.
Ltac desarb := match goal with H:arbt _ _ |- _ => destruct H end.
Ltac nonzero n := destruct n as [|n]; [try split; invrb|].
Lemma rr_nrr_rb n t :
rrt n t -> notredred t -> rbt n t.
Proof.
destruct 1 as [l x r Hl Hr].
destruct l, r; descolor; invrb; auto.
Qed.
Local Hint Resolve rr_nrr_rb : core.
Lemma arb_nrr_rb n t :
arbt n t -> notredred t -> rbt n t.
Proof.
destruct 1; auto.
Qed.
Lemma arb_nr_rb n t :
arbt n t -> notred t -> rbt n t.
Proof.
destruct 1; destruct t; descolor; invrb; auto.
Qed.
Local Hint Resolve arb_nrr_rb arb_nr_rb : core.
(** ** A Red-Black tree has indeed a logarithmic depth *)
Definition redcarac s := rcase (fun _ _ _ => 1) (fun _ => 0) s.
Lemma rb_maxdepth s n : rbt n s -> maxdepth s <= 2*n + redcarac s.
Proof.
induction 1.
- simpl; auto.
- replace (redcarac l) with 0 in * by now destree l.
replace (redcarac r) with 0 in * by now destree r.
simpl maxdepth. simpl redcarac.
rewrite Nat.add_succ_r, <- Nat.succ_le_mono.
now apply Nat.max_lub.
- simpl. rewrite <- Nat.succ_le_mono.
apply Nat.max_lub; eapply Nat.le_trans; eauto;
[destree l | destree r]; simpl;
rewrite !Nat.add_0_r, ?Nat.add_1_r, ?Nat.add_succ_r; auto.
Qed.
Lemma rb_mindepth s n : rbt n s -> n + redcarac s <= mindepth s.
Proof.
induction 1; simpl.
- trivial.
- rewrite Nat.add_succ_r.
apply -> Nat.succ_le_mono.
replace (redcarac l) with 0 in * by now destree l.
replace (redcarac r) with 0 in * by now destree r.
now apply Nat.min_glb.
- apply -> Nat.succ_le_mono. rewrite Nat.add_0_r.
apply Nat.min_glb.
+ refine (Nat.le_trans _ _ _ _ IHrbt1).
apply Nat.le_add_r.
+ refine (Nat.le_trans _ _ _ _ IHrbt2).
apply Nat.le_add_r.
Qed.
Lemma maxdepth_upperbound s : Rbt s ->
maxdepth s <= 2 * Nat.log2 (S (cardinal s)).
Proof.
intros (n,H).
eapply Nat.le_trans; [eapply rb_maxdepth; eauto|].
transitivity (2*(n+redcarac s)).
- rewrite Nat.mul_add_distr_l. apply Nat.add_le_mono_l.
rewrite <- Nat.mul_1_l at 1. apply Nat.mul_le_mono_r.
auto.
- apply Nat.mul_le_mono_l.
transitivity (mindepth s).
+ now apply rb_mindepth.
+ apply mindepth_log_cardinal.
Qed.
Lemma maxdepth_lowerbound s : s<>Leaf ->
Nat.log2 (cardinal s) < maxdepth s.
Proof.
apply maxdepth_log_cardinal.
Qed.
(** ** Singleton *)
Lemma singleton_rb x : Rbt (singleton x).
Proof.
unfold singleton. exists 1; auto.
Qed.
(** ** [makeBlack] and [makeRed] *)
Lemma makeBlack_rb n t : arbt n t -> Rbt (makeBlack t).
Proof.
destruct t as [|[|] l x r].
- exists 0; auto.
- destruct 1; invrb; exists (S n); simpl; auto.
- exists n; auto.
Qed.
Lemma makeRed_rr t n :
rbt (S n) t -> notred t -> rrt n (makeRed t).
Proof.
destruct t as [|[|] l x r]; invrb; simpl; auto.
Qed.
(** ** Balancing *)
Lemma lbal_rb n l k r :
arbt n l -> rbt n r -> rbt (S n) (lbal l k r).
Proof.
case lbal_match; intros; desarb; invrb; auto.
Qed.
Lemma rbal_rb n l k r :
rbt n l -> arbt n r -> rbt (S n) (rbal l k r).
Proof.
case rbal_match; intros; desarb; invrb; auto.
Qed.
Lemma rbal'_rb n l k r :
rbt n l -> arbt n r -> rbt (S n) (rbal' l k r).
Proof.
case rbal'_match; intros; desarb; invrb; auto.
Qed.
Lemma lbalS_rb n l x r :
arbt n l -> rbt (S n) r -> notred r -> rbt (S n) (lbalS l x r).
Proof.
intros Hl Hr Hr'.
destruct r as [|[|] rl rx rr]; invrb. clear Hr'.
revert Hl.
case lbalS_match.
- destruct 1; invrb; auto.
- intros. apply rbal'_rb; auto.
Qed.
Lemma lbalS_arb n l x r :
arbt n l -> rbt (S n) r -> arbt (S n) (lbalS l x r).
Proof.
case lbalS_match.
- destruct 1; invrb; auto.
- clear l. intros l Hl Hl' Hr.
destruct r as [|[|] rl rx rr]; invrb.
* destruct rl as [|[|] rll rlx rlr]; invrb.
right; auto using rbal'_rb, makeRed_rr.
* left; apply rbal'_rb; auto.
Qed.
Lemma rbalS_rb n l x r :
rbt (S n) l -> notred l -> arbt n r -> rbt (S n) (rbalS l x r).
Proof.
intros Hl Hl' Hr.
destruct l as [|[|] ll lx lr]; invrb. clear Hl'.
revert Hr.
case rbalS_match.
- destruct 1; invrb; auto.
- intros. apply lbal_rb; auto.
Qed.
Lemma rbalS_arb n l x r :
rbt (S n) l -> arbt n r -> arbt (S n) (rbalS l x r).
Proof.
case rbalS_match.
- destruct 2; invrb; auto.
- clear r. intros r Hr Hr' Hl.
destruct l as [|[|] ll lx lr]; invrb.
* destruct lr as [|[|] lrl lrx lrr]; invrb.
right; auto using lbal_rb, makeRed_rr.
* left; apply lbal_rb; auto.
Qed.
(** ** Insertion *)
(** The next lemmas combine simultaneous results about rbt and arbt.
A first solution here: statement with [if ... then ... else] *)
Definition ifred s (A B:Prop) := rcase (fun _ _ _ => A) (fun _ => B) s.
Lemma ifred_notred s A B : notred s -> (ifred s A B <-> B).
Proof.
destruct s; descolor; simpl; intuition.
Qed.
Lemma ifred_or s A B : ifred s A B -> A\/B.
Proof.
destruct s; descolor; simpl; intuition.
Qed.
Lemma ins_rr_rb x s n : rbt n s ->
ifred s (rrt n (ins x s)) (rbt n (ins x s)).
Proof.
induction 1 as [ | n l k r | n l k r Hl IHl Hr IHr ].
- simpl; auto.
- simpl. rewrite ifred_notred in * by trivial.
elim_compare x k; auto.
- rewrite ifred_notred by trivial.
unfold ins; fold ins. (* simpl is too much here ... *)
elim_compare x k.
* auto.
* apply lbal_rb; trivial. apply ifred_or in IHl; intuition.
* apply rbal_rb; trivial. apply ifred_or in IHr; intuition.
Qed.
Lemma ins_arb x s n : rbt n s -> arbt n (ins x s).
Proof.
intros H. apply (ins_rr_rb x), ifred_or in H. intuition.
Qed.
#[global]
Instance add_rb x s : Rbt s -> Rbt (add x s).
Proof.
intros (n,H). unfold add. now apply (makeBlack_rb n), ins_arb.
Qed.
(** ** Deletion *)
(** A second approach here: statement with ... /\ ... *)
Lemma append_arb_rb n l r : rbt n l -> rbt n r ->
(arbt n (append l r)) /\
(notred l -> notred r -> rbt n (append l r)).
Proof.
revert r n.
append_tac l r.
- split; auto.
- split; auto.
- (* Red / Red *)
intros n. invrb.
case (IHlr n); auto; clear IHlr.
case append_rr_match.
+ intros a x b _ H; split; invrb.
assert (rbt n (Rd a x b)) by auto. invrb. auto.
+ split; invrb; auto.
- (* Red / Black *)
split; invrb. destruct (IHlr n) as (_,IH); auto.
- (* Black / Red *)
split; invrb. destruct (IHrl n) as (_,IH); auto.
- (* Black / Black *)
nonzero n.
invrb.
destruct (IHlr n) as (IH,_); auto; clear IHlr.
revert IH.
case append_bb_match.
+ intros a x b IH; split; destruct IH; invrb; auto.
+ split; [left | invrb]; auto using lbalS_rb.
Qed.
(** A third approach : Lemma ... with ... *)
Lemma del_arb s x n : rbt (S n) s -> isblack s -> arbt n (del x s)
with del_rb s x n : rbt n s -> notblack s -> rbt n (del x s).
Proof.
{ revert n.
induct s x; try destruct c; try contradiction; invrb.
- apply append_arb_rb; assumption.
- assert (IHl' := del_rb l x). clear IHr del_arb del_rb.
destruct l as [|[|] ll lx lr]; auto.
nonzero n. apply lbalS_arb; auto.
- assert (IHr' := del_rb r x). clear IHl del_arb del_rb.
destruct r as [|[|] rl rx rr]; auto.
nonzero n. apply rbalS_arb; auto. }
{ revert n.
induct s x; try assumption; try destruct c; try contradiction; invrb.
- apply append_arb_rb; assumption.
- assert (IHl' := del_arb l x). clear IHr del_arb del_rb.
destruct l as [|[|] ll lx lr]; auto.
nonzero n. destruct n as [|n]; [invrb|]; apply lbalS_rb; auto.
- assert (IHr' := del_arb r x). clear IHl del_arb del_rb.
destruct r as [|[|] rl rx rr]; auto.
nonzero n. apply rbalS_rb; auto. }
Qed.
#[global]
Instance remove_rb s x : Rbt s -> Rbt (remove x s).
Proof.
intros (n,H). unfold remove.
destruct s as [|[|] l y r].
- apply (makeBlack_rb n). auto.
- apply (makeBlack_rb n). left. apply del_rb; simpl; auto.
- nonzero n. apply (makeBlack_rb n). apply del_arb; simpl; auto.
Qed.
(** ** Treeify *)
Definition treeify_rb_invariant size depth (f:treeify_t) :=
forall acc,
size <= length acc ->
rbt depth (fst (f acc)) /\
size + length (snd (f acc)) = length acc.
Lemma treeify_zero_rb : treeify_rb_invariant 0 0 treeify_zero.
Proof.
intros acc _; simpl; auto.
Qed.
Lemma treeify_one_rb : treeify_rb_invariant 1 0 treeify_one.
Proof.
intros [|x acc]; simpl; auto; inversion 1.
Qed.
Lemma treeify_cont_rb f g size1 size2 size d :
treeify_rb_invariant size1 d f ->
treeify_rb_invariant size2 d g ->
size = S (size1 + size2) ->
treeify_rb_invariant size (S d) (treeify_cont f g).
Proof.
intros Hf Hg H acc Hacc.
unfold treeify_cont.
specialize (Hf acc).
destruct (f acc) as (l, acc1). simpl in *.
destruct Hf as (Hf1, Hf2).
{ subst. refine (Nat.le_trans _ _ _ _ Hacc).
rewrite <- Nat.add_succ_r. apply Nat.le_add_r. }
destruct acc1 as [|x acc2]; simpl in *.
- exfalso. revert Hacc. apply Nat.lt_nge. rewrite H, <- Hf2.
rewrite Nat.add_0_r. apply (Nat.succ_le_mono size1), Nat.le_add_r.
- specialize (Hg acc2).
destruct (g acc2) as (r, acc3). simpl in *.
destruct Hg as (Hg1, Hg2).
{ revert Hacc.
rewrite H, <- Hf2, Nat.add_succ_r, <- Nat.succ_le_mono.
apply Nat.add_le_mono_l. }
split; auto.
now rewrite H, <- Hf2, <- Hg2, Nat.add_succ_r, Nat.add_assoc.
Qed.
Lemma treeify_aux_rb n :
exists d, forall (b:bool),
treeify_rb_invariant (ifpred b (Pos.to_nat n)) d (treeify_aux b n).
Proof.
induction n as [n (d,IHn)|n (d,IHn)| ].
- exists (S d). intros b.
eapply treeify_cont_rb; [ apply (IHn false) | apply (IHn b) | ].
rewrite Pos2Nat.inj_xI.
assert (H := Pos2Nat.is_pos n). apply Nat.neq_0_lt_0 in H.
destruct b; simpl; intros; rewrite Nat.add_0_r; trivial.
now rewrite <- Nat.add_succ_r, Nat.succ_pred; trivial.
- exists (S d). intros b.
eapply treeify_cont_rb; [ apply (IHn b) | apply (IHn true) | ].
rewrite Pos2Nat.inj_xO.
assert (H := Pos2Nat.is_pos n). apply Nat.neq_0_lt_0 in H.
rewrite <- Nat.add_succ_r, Nat.succ_pred by trivial.
destruct b; simpl; intros; rewrite Nat.add_0_r; trivial.
symmetry. now apply Nat.add_pred_l.
- exists 0; destruct b;
[ apply treeify_zero_rb | apply treeify_one_rb ].
Qed.
(** The black depth of [treeify l] is actually a log2, but
we don't need to mention that. *)
#[global]
Instance treeify_rb l : Rbt (treeify l).
Proof.
unfold treeify.
destruct (treeify_aux_rb (plength l)) as (d,H).
exists d.
apply H.
now rewrite plength_spec.
Qed.
(** ** Filtering *)
#[global]
Instance filter_rb f s : Rbt (filter f s).
Proof.
unfold filter; auto_tc.
Qed.
#[global]
Instance partition_rb1 f s : Rbt (fst (partition f s)).
Proof.
unfold partition. destruct partition_aux. simpl. auto_tc.
Qed.
#[global]
Instance partition_rb2 f s : Rbt (snd (partition f s)).
Proof.
unfold partition. destruct partition_aux. simpl. auto_tc.
Qed.
(** ** Union, intersection, difference *)
#[global]
Instance fold_add_rb s1 s2 : Rbt s2 -> Rbt (fold add s1 s2).
Proof.
intros. rewrite fold_spec, <- fold_left_rev_right. unfold elt in *.
induction (rev (elements s1)); simpl; unfold flip in *; auto_tc.
Qed.
#[global]
Instance fold_remove_rb s1 s2 : Rbt s2 -> Rbt (fold remove s1 s2).
Proof.
intros. rewrite fold_spec, <- fold_left_rev_right. unfold elt in *.
induction (rev (elements s1)); simpl; unfold flip in *; auto_tc.
Qed.
Lemma union_rb s1 s2 : Rbt s1 -> Rbt s2 -> Rbt (union s1 s2).
Proof.
intros. unfold union, linear_union. destruct compare_height; auto_tc.
Qed.
Lemma inter_rb s1 s2 : Rbt s1 -> Rbt s2 -> Rbt (inter s1 s2).
Proof.
intros. unfold inter, linear_inter. destruct compare_height; auto_tc.
Qed.
Lemma diff_rb s1 s2 : Rbt s1 -> Rbt s2 -> Rbt (diff s1 s2).
Proof.
intros. unfold diff, linear_diff. destruct compare_height; auto_tc.
Qed.
End BalanceProps.
(** * Final Encapsulation
Now, in order to really provide a functor implementing [S], we
need to encapsulate everything into a type of binary search trees.
They also happen to be well-balanced, but this has no influence
on the correctness of operations, so we won't state this here,
see [BalanceProps] if you need more than just the MSet interface.
*)
Module Type MSetInterface_S_Ext := MSetInterface.S <+ MSetRemoveMin.
Module Make (X: Orders.OrderedType) <:
MSetInterface_S_Ext with Module E := X.
Module Raw. Include MakeRaw X. End Raw.
Include MSetInterface.Raw2Sets X Raw.
Definition opt_ok (x:option (elt * Raw.t)) :=
match x with Some (_,s) => Raw.Ok s | None => True end.
Definition mk_opt_t (x: option (elt * Raw.t))(P: opt_ok x) :
option (elt * t) :=
match x as o return opt_ok o -> option (elt * t) with
| Some (k,s') => fun P : Raw.Ok s' => Some (k, Mkt s')
| None => fun _ => None
end P.
Definition remove_min s : option (elt * t) :=
mk_opt_t (Raw.remove_min (this s)) (Raw.remove_min_ok s).
Lemma remove_min_spec1 s x s' :
remove_min s = Some (x,s') ->
min_elt s = Some x /\ Equal (remove x s) s'.
Proof.
destruct s as (s,Hs).
unfold remove_min, mk_opt_t, min_elt, remove, Equal, In; simpl.
generalize (fun x s' => @Raw.remove_min_spec1 s x s' Hs).
set (P := Raw.remove_min_ok s). clearbody P.
destruct (Raw.remove_min s) as [(x0,s0)|]; try easy.
intros H [= -> <-]. simpl.
destruct (H x s0); auto. subst; intuition.
Qed.
Lemma remove_min_spec2 s : remove_min s = None -> Empty s.
Proof.
destruct s as (s,Hs).
unfold remove_min, mk_opt_t, Empty, In; simpl.
generalize (Raw.remove_min_spec2 s).
set (P := Raw.remove_min_ok s). clearbody P.
destruct (Raw.remove_min s) as [(x0,s0)|]; now intuition.
Qed.
End Make.
|
-- -------------------------------------------------------------- [ Common.idr ]
-- Module : Common.idr
-- Copyright : (c) Jan de Muijnck-Hughes
-- License : see LICENSE
-- --------------------------------------------------------------------- [ EOH ]
module GRL.Eval.Common
import GRL.Common
import GRL.Model
%access export
-- ------------------------------------------------------------- [ Eval Result ]
namespace EvalResult
public export
data EvalResult : Type where
Result : List GoalNode -> EvalResult
BadModel : EvalResult
public export
implementation Show EvalResult where
show BadModel = "Bad Model"
show (Result xs) = unlines $ map (mkPretty) xs
where
mkPretty : GoalNode -> String
mkPretty x = unwords [getNodeTitle x, show (fromMaybe NONE (getSValue x)), "\n"]
toString : EvalResult -> (GoalNode -> String) -> Maybe String
toString BadModel _ = Nothing
toString (Result xs) f = Just $ unlines (mkString xs)
where
mkString : List GoalNode -> List String
mkString Nil = Nil
mkString (x::xs) = f x :: mkString xs
-- --------------------------------------------------------------------- [ EOF ]
|
// Boost.TypeErasure library
//
// Copyright 2011 Steven Watanabe
//
// 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)
//
// $Id$
#include <boost/type_erasure/any.hpp>
#include <boost/type_erasure/tuple.hpp>
#include <boost/type_erasure/builtin.hpp>
#include <boost/type_erasure/operators.hpp>
#include <boost/type_erasure/any_cast.hpp>
#include <boost/mpl/vector.hpp>
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
using namespace boost::type_erasure;
template<class T = _self>
struct common : ::boost::mpl::vector<
copy_constructible<T>,
relaxed
> {};
BOOST_AUTO_TEST_CASE(test_typeid) {
any<common<> > val;
BOOST_CHECK(typeid_of(val) == typeid(void));
}
BOOST_AUTO_TEST_CASE(test_any_cast) {
any<common<> > val;
BOOST_CHECK_EQUAL(any_cast<void*>(&val), (void*)0);
BOOST_CHECK_EQUAL(any_cast<int*>(&val), (int*)0);
}
BOOST_AUTO_TEST_CASE(test_copy) {
any<common<> > val;
any<common<> > val2(val);
BOOST_CHECK(typeid_of(val2) == typeid(void));
}
|
[GOAL]
α : Type u_1
inst✝¹ : Add α
inst✝ : Small.{u_2, u_1} α
x y : Shrink α
⊢ ↑(equivShrink α).symm (x + y) = ↑(equivShrink α).symm x + ↑(equivShrink α).symm y
[PROOFSTEP]
rw [Equiv.add_def]
[GOAL]
α : Type u_1
inst✝¹ : Add α
inst✝ : Small.{u_2, u_1} α
x y : Shrink α
⊢ ↑(equivShrink α).symm (↑(equivShrink α).symm.symm (↑(equivShrink α).symm x + ↑(equivShrink α).symm y)) =
↑(equivShrink α).symm x + ↑(equivShrink α).symm y
[PROOFSTEP]
simp
[GOAL]
α : Type u_1
inst✝¹ : Add α
inst✝ : Small.{u_2, u_1} α
x y : α
⊢ ↑(equivShrink α) (x + y) = ↑(equivShrink α) x + ↑(equivShrink α) y
[PROOFSTEP]
rw [Equiv.add_def]
[GOAL]
α : Type u_1
inst✝¹ : Add α
inst✝ : Small.{u_2, u_1} α
x y : α
⊢ ↑(equivShrink α) (x + y) =
↑(equivShrink α).symm.symm (↑(equivShrink α).symm (↑(equivShrink α) x) + ↑(equivShrink α).symm (↑(equivShrink α) y))
[PROOFSTEP]
simp
[GOAL]
α : Type u_1
inst✝¹ : Mul α
inst✝ : Small.{u_2, u_1} α
x y : Shrink α
⊢ ↑(equivShrink α).symm (x * y) = ↑(equivShrink α).symm x * ↑(equivShrink α).symm y
[PROOFSTEP]
rw [Equiv.mul_def]
[GOAL]
α : Type u_1
inst✝¹ : Mul α
inst✝ : Small.{u_2, u_1} α
x y : Shrink α
⊢ ↑(equivShrink α).symm (↑(equivShrink α).symm.symm (↑(equivShrink α).symm x * ↑(equivShrink α).symm y)) =
↑(equivShrink α).symm x * ↑(equivShrink α).symm y
[PROOFSTEP]
simp
[GOAL]
α : Type u_1
inst✝¹ : Mul α
inst✝ : Small.{u_2, u_1} α
x y : α
⊢ ↑(equivShrink α) (x * y) = ↑(equivShrink α) x * ↑(equivShrink α) y
[PROOFSTEP]
rw [Equiv.mul_def]
[GOAL]
α : Type u_1
inst✝¹ : Mul α
inst✝ : Small.{u_2, u_1} α
x y : α
⊢ ↑(equivShrink α) (x * y) =
↑(equivShrink α).symm.symm (↑(equivShrink α).symm (↑(equivShrink α) x) * ↑(equivShrink α).symm (↑(equivShrink α) y))
[PROOFSTEP]
simp
[GOAL]
α : Type u_1
inst✝¹ : Sub α
inst✝ : Small.{u_2, u_1} α
x y : Shrink α
⊢ ↑(equivShrink α).symm (x - y) = ↑(equivShrink α).symm x - ↑(equivShrink α).symm y
[PROOFSTEP]
rw [Equiv.sub_def]
[GOAL]
α : Type u_1
inst✝¹ : Sub α
inst✝ : Small.{u_2, u_1} α
x y : Shrink α
⊢ ↑(equivShrink α).symm (↑(equivShrink α).symm.symm (↑(equivShrink α).symm x - ↑(equivShrink α).symm y)) =
↑(equivShrink α).symm x - ↑(equivShrink α).symm y
[PROOFSTEP]
simp
[GOAL]
α : Type u_1
inst✝¹ : Sub α
inst✝ : Small.{u_2, u_1} α
x y : α
⊢ ↑(equivShrink α) (x - y) = ↑(equivShrink α) x - ↑(equivShrink α) y
[PROOFSTEP]
rw [Equiv.sub_def]
[GOAL]
α : Type u_1
inst✝¹ : Sub α
inst✝ : Small.{u_2, u_1} α
x y : α
⊢ ↑(equivShrink α) (x - y) =
↑(equivShrink α).symm.symm (↑(equivShrink α).symm (↑(equivShrink α) x) - ↑(equivShrink α).symm (↑(equivShrink α) y))
[PROOFSTEP]
simp
[GOAL]
α : Type u_1
inst✝¹ : Div α
inst✝ : Small.{u_2, u_1} α
x y : Shrink α
⊢ ↑(equivShrink α).symm (x / y) = ↑(equivShrink α).symm x / ↑(equivShrink α).symm y
[PROOFSTEP]
rw [Equiv.div_def]
[GOAL]
α : Type u_1
inst✝¹ : Div α
inst✝ : Small.{u_2, u_1} α
x y : Shrink α
⊢ ↑(equivShrink α).symm (↑(equivShrink α).symm.symm (↑(equivShrink α).symm x / ↑(equivShrink α).symm y)) =
↑(equivShrink α).symm x / ↑(equivShrink α).symm y
[PROOFSTEP]
simp
[GOAL]
α : Type u_1
inst✝¹ : Div α
inst✝ : Small.{u_2, u_1} α
x y : α
⊢ ↑(equivShrink α) (x / y) = ↑(equivShrink α) x / ↑(equivShrink α) y
[PROOFSTEP]
rw [Equiv.div_def]
[GOAL]
α : Type u_1
inst✝¹ : Div α
inst✝ : Small.{u_2, u_1} α
x y : α
⊢ ↑(equivShrink α) (x / y) =
↑(equivShrink α).symm.symm (↑(equivShrink α).symm (↑(equivShrink α) x) / ↑(equivShrink α).symm (↑(equivShrink α) y))
[PROOFSTEP]
simp
[GOAL]
α : Type u_1
inst✝¹ : Neg α
inst✝ : Small.{u_2, u_1} α
x : Shrink α
⊢ ↑(equivShrink α).symm (-x) = -↑(equivShrink α).symm x
[PROOFSTEP]
rw [Equiv.neg_def]
[GOAL]
α : Type u_1
inst✝¹ : Neg α
inst✝ : Small.{u_2, u_1} α
x : Shrink α
⊢ ↑(equivShrink α).symm (↑(equivShrink α).symm.symm (-↑(equivShrink α).symm x)) = -↑(equivShrink α).symm x
[PROOFSTEP]
simp
[GOAL]
α : Type u_1
inst✝¹ : Neg α
inst✝ : Small.{u_2, u_1} α
x : α
⊢ ↑(equivShrink α) (-x) = -↑(equivShrink α) x
[PROOFSTEP]
rw [Equiv.neg_def]
[GOAL]
α : Type u_1
inst✝¹ : Neg α
inst✝ : Small.{u_2, u_1} α
x : α
⊢ ↑(equivShrink α) (-x) = ↑(equivShrink α).symm.symm (-↑(equivShrink α).symm (↑(equivShrink α) x))
[PROOFSTEP]
simp
[GOAL]
α : Type u_1
inst✝¹ : Inv α
inst✝ : Small.{u_2, u_1} α
x : Shrink α
⊢ ↑(equivShrink α).symm x⁻¹ = (↑(equivShrink α).symm x)⁻¹
[PROOFSTEP]
rw [Equiv.inv_def]
[GOAL]
α : Type u_1
inst✝¹ : Inv α
inst✝ : Small.{u_2, u_1} α
x : Shrink α
⊢ ↑(equivShrink α).symm (↑(equivShrink α).symm.symm (↑(equivShrink α).symm x)⁻¹) = (↑(equivShrink α).symm x)⁻¹
[PROOFSTEP]
simp
[GOAL]
α : Type u_1
inst✝¹ : Inv α
inst✝ : Small.{u_2, u_1} α
x : α
⊢ ↑(equivShrink α) x⁻¹ = (↑(equivShrink α) x)⁻¹
[PROOFSTEP]
rw [Equiv.inv_def]
[GOAL]
α : Type u_1
inst✝¹ : Inv α
inst✝ : Small.{u_2, u_1} α
x : α
⊢ ↑(equivShrink α) x⁻¹ = ↑(equivShrink α).symm.symm (↑(equivShrink α).symm (↑(equivShrink α) x))⁻¹
[PROOFSTEP]
simp
|
Require Import Equiv Properties.
(* Como teremos apenas um grupo podemos definir a classe Group bundled.
Para a classe ActionGroup e NominalSets seria interessante fazer
unbundled.
Exemplo de unbundled:
Group {A} {Setoid A} (null: A) (op: A -> A -> A) (inv: A -> A) := {
assoc: forall p1 p2 p3, op p1 (op p2 p3) == op (op p1 p2) p3;
left_inv: forall p, op p (inv p) == null
}.
Uma vantagem do unblundled é que podemos definir multiplas instâncias
diferentes de grupos para um mesmo tipo através de diferentes operações
e operadores. No bundled teremos problema de overlaping instances.
O problema deste método é que não temos como referenciar as operações,
e operadores: null, op e inv. Para isso é necessário definir
cada um como uma classe unitária:
Class GroupOp A := grp_op: A -> A -> A.
Exemplo bundled:
Group (A: Type) := {
grp_setoid :> Setoid A;
null: A;
grp_op: A -> A -> A;
grp_inv: A -> A;
assoc: forall p1 p2 p3, op p1 (op p2 p3) == op (op p1 p2) p3;
left_inv: forall p, op p (inv p) == null
}. *)
(** *Canonical names *)
Class Neutral A := neutral: A.
Class Binop A := b_op: A -> A -> A.
Class Negate A := negate: A -> A.
Typeclasses Transparent Neutral Binop Negate.
Infix "+" := b_op (at level 50, left associativity) : nominal_scope.
Notation "(+)" := b_op (only parsing) : nominal_scope.
Notation "( x +)" := (b_op x) (only parsing) : nominal_scope.
Notation "(+ x )" := (λ y, y + x) (only parsing) : nominal_scope.
Notation "- x" := (negate x) : nominal_scope.
Notation "(-)" := negate (only parsing) : nominal_scope.
Notation "x - y" := (x + -y)%nominal : nominal_scope.
Section GroupClass.
Context A {Ea: Equiv A}.
Class Group {GU: Neutral A} {GN: Negate A} {GOp: Binop A}: Prop :=
{ g_setoid :> Setoid A;
g_op_proper :> Proper ((=) ==> (=) ==> (=)) (+);
g_ne_proper :> Proper ((=) ==> (=)) (-);
g_assoc :> Associative (+);
g_left_id :> LeftIdentity (+) neutral;
g_right_id :> RightIdentity (+) neutral;
g_left_inv :> LeftInverse (+) (-) neutral;
g_right_inv :> RightInverse (+) (-) neutral
}.
End GroupClass.
Arguments g_op_proper {_ _ _ _ _ _}.
Arguments g_ne_proper {_ _ _ _ _ _}.
Arguments g_right_inv {_ _ _ _ _ _}.
Arguments g_left_inv {_ _ _ _ _ _}.
Section GroupProperties.
Context `{Group G}.
Global Instance negate_involutive: Involutive (-).
Proof.
intros x; rewrite <-(left_identity x) at 2;
rewrite <- (left_inverse (-x)), <- associativity,
left_inverse, right_identity.
reflexivity.
Qed.
Global Instance: Injective (-).
Proof.
repeat (split; try apply _);
intros x y E; rewrite <-(involutive x), <-(involutive y), E;
reflexivity.
Qed.
Lemma negate_neutral: -neutral = neutral.
Proof.
rewrite <-(left_inverse neutral) at 2; rewrite right_identity;
reflexivity.
Qed.
End GroupProperties.
(** *Group Action *)
Class Action `(Group A) X := action: A -> X -> X.
Infix "∙" := action (at level 50, left associativity): nominal_scope.
Notation "(∙)" := action (only parsing).
Typeclasses Transparent Action.
Section GroupAction.
(* Action of Group A over set X *)
Context `(Ga: Group A) X {Ex: Equiv X}.
(* Left group action *)
Class GroupAction {GAct: Action Ga X}: Prop :=
{ gct_setoid :> Setoid X;
gct_proper :> Proper ((=) ==> (=) ==> (=)) (∙);
gct_compat: forall p q r, p ∙ (q ∙ r) = (q + p) ∙ r;
gct_id :> LeftIdentity (∙) neutral }.
End GroupAction.
Arguments gct_proper {_ _ _ _ _ _ _ _ _ _}.
Arguments gct_compat {_ _ _ _ _ _ _ _ _ _}.
Arguments gct_id {_ _ _ _ _ _ _ _ _ _}.
|
# Extended Kalman filter for 3 DOF linear model
An Extended Kalman filter with a 3 DOF linear model as the predictor will be developed.
The filter is run on simulated data as well as real model test data.
```python
%load_ext autoreload
%autoreload 2
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from numpy.linalg import inv
import sympy as sp
import src.visualization.book_format as book_format
book_format.set_style()
from src.substitute_dynamic_symbols import lambdify
from sympy import Matrix
from sympy.physics.mechanics import (dynamicsymbols, ReferenceFrame,
Particle, Point)
from IPython.display import display, Math, Latex
from src.substitute_dynamic_symbols import run, lambdify
from sympy.physics.vector.printing import vpprint, vlatex
from src.data import mdl
from src.extended_kalman_filter import extended_kalman_filter, rts_smoother
import src.models.vmm_nonlinear_EOM as vmm
from docs.book.example_1 import ship_parameters, df_parameters
from src.symbols import *
from src import prime_system
p = df_parameters["symbol"]
from src.visualization.plot import track_plot, plot
import matplotlib.pyplot as plt
import os
if os.name == 'nt':
plt.style.use('../docs/book/book.mplstyle') # Windows
```
## 3DOF model
```python
X_eq = vmm.X_eq
Y_eq = vmm.Y_eq
N_eq = vmm.N_eq
A, b = sp.linear_eq_to_matrix([X_eq, Y_eq, N_eq], [u1d, v1d, r1d])
acceleration = sp.matrices.MutableDenseMatrix([u1d,v1d,r1d])
eq_simulator = sp.Eq(sp.UnevaluatedExpr(A)*sp.UnevaluatedExpr(acceleration),sp.UnevaluatedExpr(b))
eq_simulator
```
```python
A_inv = A.inv()
S = sp.symbols('S')
eq_S=sp.Eq(S,-sp.fraction(A_inv[1,1])[1])
A_inv_S = A_inv.subs(eq_S.rhs,S)
eq_acceleration_matrix_clean = sp.Eq(sp.UnevaluatedExpr(acceleration),sp.UnevaluatedExpr(A_inv_S)*sp.UnevaluatedExpr(b))
Math(vlatex(eq_acceleration_matrix_clean))
```
```python
u1d_function = sp.Function(r'\dot{u}')(u,v,r,delta)
v1d_function = sp.Function(r'\dot{v}')(u,v,r,delta)
r_function = sp.Function(r'\dot{r}')(u,v,r,delta)
subs_prime = [
(m,m/prime_system.df_prime.mass.denominator),
(I_z,I_z/prime_system.df_prime.inertia_moment.denominator),
(x_G,x_G/prime_system.df_prime.length.denominator),
(u, u/sp.sqrt(u**2+v**2)),
(v, v/sp.sqrt(u**2+v**2)),
(r, r/(sp.sqrt(u**2+v**2)/L)),
]
subs = [
(X_D, vmm.X_qs_eq.rhs),
(Y_D, vmm.Y_qs_eq.rhs),
(N_D, vmm.N_qs_eq.rhs),
]
subs = subs + subs_prime
A_SI = A.subs(subs)
b_SI = b.subs(subs)
x_dot = sympy.matrices.dense.matrix_multiply_elementwise(A_SI.inv()*b_SI,
sp.Matrix([(u**2+v**2)/L,(u**2+v**2)/L,(u**2+v**2)/(L**2)]))
```
```python
x_dot
```
```python
x_dot[1].args[2]
```
```python
x_ = sp.Matrix([u*sp.cos(psi)-v*sp.sin(psi),
u*sp.sin(psi)+v*sp.cos(psi),
r])
f_ = sp.Matrix.vstack(x_, x_dot)
subs = {value: key for key, value in p.items()}
subs[psi] = sp.symbols('psi')
lambda_f = lambdify(f_.subs(subs))
```
```python
import inspect
lines = inspect.getsource(lambda_f)
print(lines)
```
```python
from src.models.vmm import get_coefficients
eq = sp.Eq(sp.UnevaluatedExpr(acceleration), f_[5])
get_coefficients(eq)
```
```python
parameters=df_parameters['prime'].copy()
```
```python
%%time
lambda_f(**parameters)
```
```python
%%time
expr=f_.subs(subs)
lambda_f = lambdify(expr)
```
```python
subs = {value: key for key, value in p.items()}
keys = list(set(subs.keys()) & f_.free_symbols)
subs = {key : subs[key] for key in keys}
expr=f_.subs(subs)
```
```python
subs
```
```python
%%time
subs[psi] = sp.symbols('psi')
expr=f_.subs(subs)
sp.lambdify(list(expr.free_symbols), expr)
```
```python
sp.lambdify(list(f_.free_symbols), f_)
```
```python
lambda_f
```
```python
def lambda_f_constructor(parameters, ship_parameters):
def f(x, input):
psi=x[2]
u=x[3]
v=x[4]
r=x[5]
x_dot = run(lambda_f, **parameters, **ship_parameters, psi=psi, u=u, v=v, r=r, **input).reshape(x.shape)
return x_dot
return f
```
## Simulation
```python
def time_step(x_,u_):
psi=x_[2]
u=x_[3]
v=x_[4]
r=x_[5]
delta = u_
x_dot = run(lambda_f, **parameters, **ship_parameters, psi=psi, u=u, v=v, r=r, delta=delta).flatten()
return x_dot
def simulate(x0,E, ws, t, us):
simdata = np.zeros((6,len(t)))
x_=x0
Ed = h_ * E
for i,(u_,w_) in enumerate(zip(us,ws)):
w_ = w_.reshape(len(w_),1)
x_dot = lambda_f_(x_,u_) + Ed @ w_
x_=x_ + h_*x_dot
simdata[:,i] = x_.flatten()
df = pd.DataFrame(simdata.T, columns=["x0","y0","psi","u","v","r"], index=t)
df.index.name = 'time'
df['delta'] = us
return df
```
```python
parameters=df_parameters['prime'].copy()
lambda_f_ = lambda_f_constructor(parameters=parameters,
ship_parameters=ship_parameters)
N_ = 4000
t_ = np.linspace(0,50,N_)
h_ = float(t_[1]-t_[0])
us = np.deg2rad(30*np.concatenate((-1*np.ones(int(N_/4)),
1*np.ones(int(N_/4)),
-1*np.ones(int(N_/4)),
1*np.ones(int(N_/4)))))
x0_ = np.array([[0,0,0,3,0,0]]).T
no_states = len(x0_)
np.random.seed(42)
E = np.array([
[0,0,0],
[0,0,0],
[0,0,0],
[1,0,0],
[0,1,0],
[0,0,1],
],
)
process_noise_u = 0.01
process_noise_v = 0.01
process_noise_r = np.deg2rad(0.01)
ws = np.zeros((N_,3))
ws[:,0] = np.random.normal(loc=process_noise_u, size=N_)
ws[:,1] = np.random.normal(loc=process_noise_v, size=N_)
ws[:,2] = np.random.normal(loc=process_noise_r, size=N_)
df = simulate(x0=x0_, E=E, ws=ws, t=t_, us=us)
```
```python
a = np.array([1,2,3])
M = np.array([[1,1,1],[1,1,1]])
[email protected]
```
```python
w_ = ws[0]
E@w_+w_.reshape(3,1)
```
```python
track_plot(
df=df,
lpp=ship_parameters["L"],
beam=ship_parameters["B"],
color="green",
);
plot({'Simulation':df});
```
## Kalman filter
Implementation of the Kalman filter. The code is inspired of this Matlab implementation: [ExEKF.m](https://github.com/cybergalactic/MSS/blob/master/mssExamples/ExEKF.m).
```python
x, x1d = sp.symbols(r'\vec{x} \dot{\vec{x}}') # State vector
h = sp.symbols('h')
u_input = sp.symbols(r'u_{input}') # input vector
w_noise = sp.symbols(r'w_{noise}') # input vector
f = sp.Function('f')(x,u_input,w_noise)
eq_system = sp.Eq(x1d, f)
eq_system
```
```python
eq_x = sp.Eq(x, sp.UnevaluatedExpr(sp.Matrix([x_0, y_0, psi, u, v, r])))
eq_x
```
```python
jac = sp.eye(6,6) + f_.jacobian(eq_x.rhs.doit())*h
subs = {value: key for key, value in p.items()}
subs[psi] = sp.symbols('psi')
lambda_jacobian = lambdify(jac.subs(subs))
```
```python
lambda_jacobian
```
```python
def lambda_jacobian_constructor(parameters, ship_parameters, h):
def f(x, input):
psi=x[2]
u=x[3]
v=x[4]
r=x[5]
jacobian = run(lambda_jacobian, **parameters, **ship_parameters, psi=psi, u=u, v=v, r=r, h=h, **input)
return jacobian
return f
```
```python
lambda_jacobian_ = lambda_jacobian_constructor(parameters=parameters,
ship_parameters=ship_parameters, h=h_)
```
```python
df_measure = df.copy()
measurement_noise_psi_max = 3
measurement_noise_psi = np.deg2rad(measurement_noise_psi_max/3)
epsilon_psi = np.random.normal(scale=measurement_noise_psi, size=N_)
measurement_noise_xy_max=2
measurement_noise_xy = measurement_noise_xy_max/3
epsilon_x0 = np.random.normal(scale=measurement_noise_xy, size=N_)
epsilon_y0 = np.random.normal(scale=measurement_noise_xy, size=N_)
df_measure['psi'] = df['psi'] + epsilon_psi
df_measure['x0'] = df['x0'] + epsilon_x0
df_measure['y0'] = df['y0'] + epsilon_y0
```
```python
P_prd = np.diag([0.1, 0.1, np.deg2rad(0.01), 0.001, 0.001, np.deg2rad(0.001)])
Qd = np.diag([0.01, 0.01, np.deg2rad(0.1)]) #process variances: u,v,r
Rd = h_*np.diag([measurement_noise_xy**2, measurement_noise_xy**2, measurement_noise_psi**2]) #measurement variances: x0,y0,psi
ys = df_measure[['x0','y0','psi']].values
x0_ = np.array([[0,0,0,3,0,0]]).T
Cd = np.array([
[1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0],
])
E = np.array([
[0,0,0],
[0,0,0],
[0,0,0],
[1,0,0],
[0,1,0],
[0,0,1],
],
)
time_steps = extended_kalman_filter(
P_prd=P_prd,
lambda_f=lambda_f_,
lambda_jacobian=lambda_jacobian_,
#h=h_,
#us=us,
#ys=ys,
E=E,
Qd=Qd,
Rd=Rd,
Cd=Cd, data=df_measure)
x_hats = np.array([time_step["x_hat"].flatten() for time_step in time_steps]).T
time = np.array([time_step["time"] for time_step in time_steps]).T
Ks = np.array([time_step["K"] for time_step in time_steps]).T
variances = np.array([np.diagonal(time_step["P_hat"]) for time_step in time_steps]).T
stds = np.sqrt(variances)
```
```python
keys = ['x0','y0','psi','u','v','r']
fig,ax=plt.subplots()
for i,key in enumerate(keys):
ax.plot(time, variances[i,:], label=key)
ax.legend()
ax.set_ylabel('std')
ax.set_xlabel('time [s]')
ax.set_ylim(0,10*np.max(variances[:,-1]))
```
```python
df_kalman = pd.DataFrame(data=x_hats.T, index=time, columns=['x0','y0','psi','u','v','r'])
df_kalman['delta'] = us
dataframes = {
'Mesurement' : df_measure,
'Kalman filter' : df_kalman,
'Simulation' : df,
}
fig,ax=plt.subplots()
styles = {
'Mesurement' : {
'linestyle' : '',
'marker' : '.',
'ms' : 1,
},
'Kalman filter' : {
'lw' : 2,
},
'Simulation' : {
'lw' : 1,
'linestyle' : ':',
},
}
for label,df_ in dataframes.items():
track_plot(
df=df_,
lpp=ship_parameters["L"],
beam=ship_parameters["B"],
ax=ax,
label=label,
plot_boats=False,
**styles.get(label,{})
);
ax.legend()
plot(dataframes = dataframes, fig_size=(10,15), styles = ['-','-',':']);
```
# Real data
Using the developed Kalman filter on some real model test data
## Load test
```python
id=22773
df, units, meta_data = mdl.load(dir_path = '../data/raw', id=id)
df.index = df.index.total_seconds()
df.index-=df.index[0]
df['x0']-=df.iloc[0]['x0']
df['y0']-=df.iloc[0]['y0']
df['psi']-=df.iloc[0]['psi']
```
```python
fig,ax=plt.subplots()
fig.set_size_inches(10,10)
track_plot(df=df, lpp=meta_data.lpp, x_dataset='x0', y_dataset='y0', psi_dataset='psi', beam=meta_data.beam, ax=ax);
```
```python
sp.simplify(sp.Matrix([
[sp.cos(psi), -sp.sin(psi)],
[sp.sin(psi), sp.cos(psi)]]).inv())
```
```python
from numpy import cos as cos
from numpy import sin as sin
from src.data.lowpass_filter import lowpass_filter
df_lowpass = df.copy()
t = df_lowpass.index
ts = np.mean(np.diff(t))
fs = 1/ts
position_keys = ['x0','y0','psi']
for key in position_keys:
df_lowpass[key] = lowpass_filter(data=df_lowpass[key], fs=fs, cutoff=1, order=1)
df_lowpass['x01d_gradient'] = x1d_ = np.gradient(df_lowpass['x0'], t)
df_lowpass['y01d_gradient'] = y1d_ = np.gradient(df_lowpass['y0'], t)
df_lowpass['r'] = r_ = np.gradient(df_lowpass['psi'], t)
psi_ = df_lowpass['psi']
df_lowpass['u'] = x1d_*cos(psi_) + y1d_*sin(psi_)
df_lowpass['v'] = -x1d_*sin(psi_) + y1d_*cos(psi_)
velocity_keys = ['u','v','r']
for key in velocity_keys:
df_lowpass[key] = lowpass_filter(data=df_lowpass[key], fs=fs, cutoff=1, order=1)
```
```python
x1d_[0:10]
```
```python
for key in position_keys + velocity_keys:
fig,ax=plt.subplots()
fig.set_size_inches(12,3)
df_lowpass.plot(y=key, ax=ax, zorder=-10, label='filter')
if key in df:
df.plot(y=key, ax=ax, label='raw')
ax.set_ylabel(key)
```
```python
data = df.copy()
data['u'] = df_lowpass['u']
data['v'] = df_lowpass['v']
data['r'] = df_lowpass['r']
data=data.iloc[200:-100]
data.index-=data.index[0]
P_prd = np.diag([0.1, 0.1, np.deg2rad(0.01), 0.001, 0.001, np.deg2rad(0.001)])
Qd = np.diag([0.01, 0.01, np.deg2rad(0.1)]) #process variances: u,v,r
Cd = np.array([
[1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0],
])
E = np.array([
[0,0,0],
[0,0,0],
[0,0,0],
[1,0,0],
[0,1,0],
[0,0,1],
],
)
ys = data[['x0','y0','psi']].values
h_m = h_ = np.mean(np.diff(data.index))
x0_ = np.concatenate((
data.iloc[0][['x0','y0','psi']].values,
data.iloc[0][['u','v','r']].values))
us = data['delta'].values
error_max_pos = 0.05
sigma_pos = error_max_pos/3
variance_pos = sigma_pos**2
error_max_psi = np.deg2rad(0.5)
sigma_psi = error_max_psi/3
variance_psi = sigma_psi**2
Rd = np.diag([variance_pos, variance_pos, variance_psi])
time_steps = extended_kalman_filter(
no_states=6,
no_measurement_states=3,
x0=x0_,
P_prd=P_prd,
lambda_f=lambda_f_,
lambda_jacobian=lambda_jacobian_,
h=h_,
us=us,
ys=ys,
E=E,
Qd=Qd,
Rd=Rd,
Cd=Cd)
x_hats = np.array([time_step["x_hat"].flatten() for time_step in time_steps]).T
time = np.array([time_step["time"] for time_step in time_steps]).T
Ks = np.array([time_step["K"] for time_step in time_steps]).T
variances = np.array([np.diagonal(time_step["P_hat"]) for time_step in time_steps]).T
stds = np.sqrt(variances)
```
```python
keys = ['x0','y0','psi','u','v','r']
fig,ax=plt.subplots()
for i,key in enumerate(keys):
ax.plot(time, variances[i,:], label=key)
ax.legend()
ax.set_ylabel('std')
ax.set_xlabel('time [s]')
ax.set_ylim(0,3*np.max(variances[:,-1]))
```
```python
df_kalman = pd.DataFrame(data=x_hats.T, index=time, columns=['x0','y0','psi','u','v','r'])
df_kalman['delta'] = us
for key in ['u','v','r']:
df_kalman[f'{key}1d'] = np.gradient(df_kalman[key], df_kalman.index)
dataframes = {
'Mesurement' : data,
'Kalman filter' : df_kalman,
}
fig,ax=plt.subplots()
styles = {
'Mesurement' : {
'linestyle' : '',
'marker' : '.',
'ms' : 1,
'zorder':-10,
},
'Kalman filter' : {
'lw' : 2,
},
}
for label,df_ in dataframes.items():
track_plot(
df=df_,
lpp=ship_parameters["L"],
beam=ship_parameters["B"],
ax=ax,
label=label,
plot_boats=False,
**styles.get(label,{})
);
ax.legend()
plot(dataframes = dataframes,
fig_size=(10,15),
styles = ['-','-',':'],
keys=['x0','y0','psi','u','v','r','u1d','v1d','r1d']);
```
## RTS smoother
```python
smooth_time_steps = rts_smoother(
time_steps=time_steps,
us=us,
lambda_jacobian=lambda_jacobian_,
Qd=Qd,
lambda_f=lambda_f_, E=E,
)
## Post process rts smoother:
x_hats = np.array(
[time_step["x_hat"].flatten() for time_step in smooth_time_steps]
).T
time = np.array([time_step["time"] for time_step in smooth_time_steps]).T
df_rts = pd.DataFrame(data=x_hats.T, index=time, columns=['x0','y0','psi','u','v','r'])
df_rts["delta"] = us
for key in ['u','v','r']:
df_rts[f'{key}1d'] = np.gradient(df_rts[key], df_kalman.index)
```
```python
dataframes = {
'Mesurement' : data,
'Kalman filter' : df_kalman,
'RTS': df_rts,
}
fig,ax=plt.subplots()
styles = {
'Mesurement' : {
'linestyle' : '',
'marker' : '.',
'ms' : 1,
'zorder':-10,
},
'Kalman filter' : {
'lw' : 2,
},
}
for label,df_ in dataframes.items():
track_plot(
df=df_,
lpp=ship_parameters["L"],
beam=ship_parameters["B"],
ax=ax,
label=label,
plot_boats=False,
**styles.get(label,{})
);
ax.legend()
plot(dataframes = dataframes,
fig_size=(10,15),
styles = ['r-','g-','b-'],
keys=['x0','y0','psi','u','v','r','u1d','v1d','r1d']);
```
```python
data['thrust'] = data['Prop/PS/Thrust'] + data['Prop/SB/Thrust']
df_rts['thrust'] = data['thrust'].values
df_rts.to_csv('test.csv')
```
```python
smooth_time_steps[100]['P_hat']
```
```python
variances = np.array([np.diagonal(time_step["P_hat"]) for time_step in smooth_time_steps]).T
stds = np.sqrt(variances)
```
```python
keys = ['x0','y0','psi','u','v','r']
fig,ax=plt.subplots()
for i,key in enumerate(keys):
ax.plot(time, variances[i,:], label=key)
ax.legend()
ax.set_ylabel('std')
ax.set_xlabel('time [s]')
ax.set_ylim(0,3*np.max(variances[:,-1]))
```
```python
from scipy.stats import multivariate_normal
```
```python
likelihoods = np.zeros(len(time_steps))
for n,smooth_time_step in enumerate(smooth_time_steps):
cov = smooth_time_step['P_hat']
mean = smooth_time_step['x_hat'].flatten()
rv = multivariate_normal(mean=mean, cov=cov)
likelihoods[n] = rv.pdf(x=mean)
```
```python
fig,ax=plt.subplots()
ax.plot(likelihoods)
#ax.set_ylim(2.5*10**14,3*10**14)
```
```python
```
|
section \<open> Reactive Design Triples \<close>
theory utp_rdes_triples
imports utp_rdes_designs
begin
subsection \<open> Diamond notation\<close>
definition wait'_cond ::
"('t::trace,'\<alpha>,'\<beta>) rel_rp \<Rightarrow> ('t,'\<alpha>,'\<beta>) rel_rp \<Rightarrow> ('t,'\<alpha>,'\<beta>) rel_rp" (infixr "\<diamondop>" 60) where
[upred_defs]: "P \<diamondop> Q = (P \<triangleleft> $wait\<acute> \<triangleright> Q)"
utp_const wait'_cond
lemma wait'_cond_unrest [unrest]:
"\<lbrakk> out_var wait \<bowtie> x; x \<sharp> P; x \<sharp> Q \<rbrakk> \<Longrightarrow> x \<sharp> (P \<diamondop> Q)"
by (simp add: wait'_cond_def unrest)
lemma wait'_cond_subst [usubst]:
"$wait\<acute> \<sharp>\<^sub>s \<sigma> \<Longrightarrow> \<sigma> \<dagger> (P \<diamondop> Q) = (\<sigma> \<dagger> P) \<diamondop> (\<sigma> \<dagger> Q)"
by (simp add: wait'_cond_def usubst unrest usubst_apply_unrest)
lemma wait'_cond_left_false: "false \<diamondop> P = (\<not> $wait\<acute> \<and> P)"
by (rel_auto)
lemma wait'_cond_seq: "((P \<diamondop> Q) ;; R) = ((P ;; ($wait \<and> R)) \<or> (Q ;; (\<not>$wait \<and> R)))"
by (simp add: wait'_cond_def cond_def seqr_or_distl, rel_blast)
lemma wait'_cond_true: "(P \<diamondop> Q \<and> $wait\<acute>) = (P \<and> $wait\<acute>)"
by (rel_auto)
lemma wait'_cond_false: "(P \<diamondop> Q \<and> (\<not>$wait\<acute>)) = (Q \<and> (\<not>$wait\<acute>))"
by (rel_auto)
lemma wait'_cond_idem: "P \<diamondop> P = P"
by (rel_auto)
lemma wait'_cond_conj_exchange:
"((P \<diamondop> Q) \<and> (R \<diamondop> S)) = (P \<and> R) \<diamondop> (Q \<and> S)"
by (rel_auto)
lemma subst_wait'_cond_true [usubst]: "(P \<diamondop> Q)\<lbrakk>true/$wait\<acute>\<rbrakk> = P\<lbrakk>true/$wait\<acute>\<rbrakk>"
by (rel_auto)
lemma subst_wait'_cond_false [usubst]: "(P \<diamondop> Q)\<lbrakk>false/$wait\<acute>\<rbrakk> = Q\<lbrakk>false/$wait\<acute>\<rbrakk>"
by (rel_auto)
lemma subst_wait'_left_subst: "(P\<lbrakk>true/$wait\<acute>\<rbrakk> \<diamondop> Q) = (P \<diamondop> Q)"
by (rel_auto)
lemma subst_wait'_right_subst: "(P \<diamondop> Q\<lbrakk>false/$wait\<acute>\<rbrakk>) = (P \<diamondop> Q)"
by (rel_auto)
lemma wait'_cond_split: "P\<lbrakk>true/$wait\<acute>\<rbrakk> \<diamondop> P\<lbrakk>false/$wait\<acute>\<rbrakk> = P"
by (simp add: wait'_cond_def cond_var_split)
lemma wait_cond'_assoc [simp]: "P \<diamondop> Q \<diamondop> R = P \<diamondop> R"
by (rel_auto)
lemma wait_cond'_shadow: "(P \<diamondop> Q) \<diamondop> R = P \<diamondop> Q \<diamondop> R"
by (rel_auto)
lemma wait_cond'_conj [simp]: "P \<diamondop> (Q \<and> (R \<diamondop> S)) = P \<diamondop> (Q \<and> S)"
by (rel_auto)
lemma R1_wait'_cond: "R1(P \<diamondop> Q) = R1(P) \<diamondop> R1(Q)"
by (rel_auto)
lemma R2s_wait'_cond: "R2s(P \<diamondop> Q) = R2s(P) \<diamondop> R2s(Q)"
by (simp add: wait'_cond_def R2s_def R2s_def usubst)
lemma R2_wait'_cond: "R2(P \<diamondop> Q) = R2(P) \<diamondop> R2(Q)"
by (simp add: R2_def R2s_wait'_cond R1_wait'_cond)
lemma wait'_cond_R1_closed [closure]:
"\<lbrakk> P is R1; Q is R1 \<rbrakk> \<Longrightarrow> P \<diamondop> Q is R1"
by (simp add: Healthy_def R1_wait'_cond)
lemma wait'_cond_R2c_closed [closure]: "\<lbrakk> P is R2c; Q is R2c \<rbrakk> \<Longrightarrow> P \<diamondop> Q is R2c"
by (simp add: R2c_condr wait'_cond_def Healthy_def, rel_auto)
subsection \<open> Export laws \<close>
lemma RH_design_peri_R1: "\<^bold>R(P \<turnstile> R1(Q) \<diamondop> R) = \<^bold>R(P \<turnstile> Q \<diamondop> R)"
by (metis (no_types, lifting) R1_idem R1_wait'_cond RH_design_export_R1)
lemma RH_design_post_R1: "\<^bold>R(P \<turnstile> Q \<diamondop> R1(R)) = \<^bold>R(P \<turnstile> Q \<diamondop> R)"
by (metis R1_wait'_cond RH_design_export_R1 RH_design_peri_R1)
lemma RH_design_peri_R2s: "\<^bold>R(P \<turnstile> R2s(Q) \<diamondop> R) = \<^bold>R(P \<turnstile> Q \<diamondop> R)"
by (metis (no_types, lifting) R2s_idem R2s_wait'_cond RH_design_export_R2s)
lemma RH_design_post_R2s: "\<^bold>R(P \<turnstile> Q \<diamondop> R2s(R)) = \<^bold>R(P \<turnstile> Q \<diamondop> R)"
by (metis (no_types, lifting) R2s_idem R2s_wait'_cond RH_design_export_R2s)
lemma RH_design_peri_R2c: "\<^bold>R(P \<turnstile> R2c(Q) \<diamondop> R) = \<^bold>R(P \<turnstile> Q \<diamondop> R)"
by (metis R1_R2s_R2c RH_design_peri_R1 RH_design_peri_R2s)
lemma RHS_design_peri_R1: "\<^bold>R\<^sub>s(P \<turnstile> R1(Q) \<diamondop> R) = \<^bold>R\<^sub>s(P \<turnstile> Q \<diamondop> R)"
by (metis (no_types, lifting) R1_idem R1_wait'_cond RHS_design_export_R1)
lemma RHS_design_post_R1: "\<^bold>R\<^sub>s(P \<turnstile> Q \<diamondop> R1(R)) = \<^bold>R\<^sub>s(P \<turnstile> Q \<diamondop> R)"
by (metis R1_wait'_cond RHS_design_export_R1 RHS_design_peri_R1)
lemma RHS_design_peri_R2s: "\<^bold>R\<^sub>s(P \<turnstile> R2s(Q) \<diamondop> R) = \<^bold>R\<^sub>s(P \<turnstile> Q \<diamondop> R)"
by (metis (no_types, lifting) R2s_idem R2s_wait'_cond RHS_design_export_R2s)
lemma RHS_design_post_R2s: "\<^bold>R\<^sub>s(P \<turnstile> Q \<diamondop> R2s(R)) = \<^bold>R\<^sub>s(P \<turnstile> Q \<diamondop> R)"
by (metis R2s_wait'_cond RHS_design_export_R2s RHS_design_peri_R2s)
lemma RHS_design_peri_R2c: "\<^bold>R\<^sub>s(P \<turnstile> R2c(Q) \<diamondop> R) = \<^bold>R\<^sub>s(P \<turnstile> Q \<diamondop> R)"
by (metis R1_R2s_R2c RHS_design_peri_R1 RHS_design_peri_R2s)
lemma RH_design_lemma1:
"RH(P \<turnstile> (R1(R2c(Q)) \<or> R) \<diamondop> S) = RH(P \<turnstile> (Q \<or> R) \<diamondop> S)"
by (metis (no_types, lifting) R1_R2c_is_R2 R1_R2s_R2c R2_R1_form R2_disj R2c_idem RH_design_peri_R1 RH_design_peri_R2s)
lemma RHS_design_lemma1:
"RHS(P \<turnstile> (R1(R2c(Q)) \<or> R) \<diamondop> S) = RHS(P \<turnstile> (Q \<or> R) \<diamondop> S)"
by (metis (no_types, lifting) R1_R2c_is_R2 R1_R2s_R2c R2_R1_form R2_disj R2c_idem RHS_design_peri_R1 RHS_design_peri_R2s)
subsection \<open> Pre-, peri-, and postconditions \<close>
subsubsection \<open> Definitions \<close>
abbreviation "pre\<^sub>s \<equiv> [$ok \<mapsto>\<^sub>s true, $ok\<acute> \<mapsto>\<^sub>s false, $wait \<mapsto>\<^sub>s false]"
abbreviation "cmt\<^sub>s \<equiv> [$ok \<mapsto>\<^sub>s true, $ok\<acute> \<mapsto>\<^sub>s true, $wait \<mapsto>\<^sub>s false]"
abbreviation "peri\<^sub>s \<equiv> [$ok \<mapsto>\<^sub>s true, $ok\<acute> \<mapsto>\<^sub>s true, $wait \<mapsto>\<^sub>s false, $wait\<acute> \<mapsto>\<^sub>s true]"
abbreviation "post\<^sub>s \<equiv> [$ok \<mapsto>\<^sub>s true, $ok\<acute> \<mapsto>\<^sub>s true, $wait \<mapsto>\<^sub>s false, $wait\<acute> \<mapsto>\<^sub>s false]"
abbreviation "npre\<^sub>R(P) \<equiv> pre\<^sub>s \<dagger> P"
definition [upred_defs]: "pre\<^sub>R(P) = (\<not>\<^sub>r npre\<^sub>R(P))"
definition [upred_defs]: "cmt\<^sub>R(P) = R1(cmt\<^sub>s \<dagger> P)"
definition [upred_defs]: "peri\<^sub>R(P) = R1(peri\<^sub>s \<dagger> P)"
definition [upred_defs]: "post\<^sub>R(P) = R1(post\<^sub>s \<dagger> P)"
no_utp_lift pre\<^sub>R cmt\<^sub>R peri\<^sub>R post\<^sub>R npre\<^sub>R
subsubsection \<open> Unrestriction laws \<close>
lemma ok_pre_unrest [unrest]: "$ok \<sharp> pre\<^sub>R P"
by (simp add: pre\<^sub>R_def unrest usubst)
lemma ok_peri_unrest [unrest]: "$ok \<sharp> peri\<^sub>R P"
by (simp add: peri\<^sub>R_def unrest usubst)
lemma ok_post_unrest [unrest]: "$ok \<sharp> post\<^sub>R P"
by (simp add: post\<^sub>R_def unrest usubst)
lemma ok_cmt_unrest [unrest]: "$ok \<sharp> cmt\<^sub>R P"
by (simp add: cmt\<^sub>R_def unrest usubst)
lemma ok'_pre_unrest [unrest]: "$ok\<acute> \<sharp> pre\<^sub>R P"
by (simp add: pre\<^sub>R_def unrest usubst)
lemma ok'_peri_unrest [unrest]: "$ok\<acute> \<sharp> peri\<^sub>R P"
by (simp add: peri\<^sub>R_def unrest usubst)
lemma ok'_post_unrest [unrest]: "$ok\<acute> \<sharp> post\<^sub>R P"
by (simp add: post\<^sub>R_def unrest usubst)
lemma ok'_cmt_unrest [unrest]: "$ok\<acute> \<sharp> cmt\<^sub>R P"
by (simp add: cmt\<^sub>R_def unrest usubst)
lemma wait_pre_unrest [unrest]: "$wait \<sharp> pre\<^sub>R P"
by (simp add: pre\<^sub>R_def unrest usubst)
lemma wait_peri_unrest [unrest]: "$wait \<sharp> peri\<^sub>R P"
by (simp add: peri\<^sub>R_def unrest usubst)
lemma wait_post_unrest [unrest]: "$wait \<sharp> post\<^sub>R P"
by (simp add: post\<^sub>R_def unrest usubst)
lemma wait_cmt_unrest [unrest]: "$wait \<sharp> cmt\<^sub>R P"
by (simp add: cmt\<^sub>R_def unrest usubst)
lemma wait'_peri_unrest [unrest]: "$wait\<acute> \<sharp> peri\<^sub>R P"
by (simp add: peri\<^sub>R_def unrest usubst)
lemma wait'_post_unrest [unrest]: "$wait\<acute> \<sharp> post\<^sub>R P"
by (simp add: post\<^sub>R_def unrest usubst)
subsubsection \<open> Substitution laws \<close>
lemma pre\<^sub>s_design: "pre\<^sub>s \<dagger> (P \<turnstile> Q) = (\<not> pre\<^sub>s \<dagger> P)"
by (simp add: design_def pre\<^sub>R_def usubst)
lemma peri\<^sub>s_design: "peri\<^sub>s \<dagger> (P \<turnstile> Q \<diamondop> R) = peri\<^sub>s \<dagger> (P \<Rightarrow> Q)"
by (simp add: design_def usubst wait'_cond_def)
lemma post\<^sub>s_design: "post\<^sub>s \<dagger> (P \<turnstile> Q \<diamondop> R) = post\<^sub>s \<dagger> (P \<Rightarrow> R)"
by (simp add: design_def usubst wait'_cond_def)
lemma cmt\<^sub>s_design: "cmt\<^sub>s \<dagger> (P \<turnstile> Q) = cmt\<^sub>s \<dagger> (P \<Rightarrow> Q)"
by (simp add: design_def usubst wait'_cond_def)
lemma pre\<^sub>s_R1 [usubst]: "pre\<^sub>s \<dagger> R1(P) = R1(pre\<^sub>s \<dagger> P)"
by (simp add: R1_def usubst)
lemma pre\<^sub>s_R2c [usubst]: "pre\<^sub>s \<dagger> R2c(P) = R2c(pre\<^sub>s \<dagger> P)"
by (simp add: R2c_def R2s_def usubst)
lemma peri\<^sub>s_R1 [usubst]: "peri\<^sub>s \<dagger> R1(P) = R1(peri\<^sub>s \<dagger> P)"
by (simp add: R1_def usubst)
lemma peri\<^sub>s_R2c [usubst]: "peri\<^sub>s \<dagger> R2c(P) = R2c(peri\<^sub>s \<dagger> P)"
by (simp add: R2c_def R2s_def usubst)
lemma post\<^sub>s_R1 [usubst]: "post\<^sub>s \<dagger> R1(P) = R1(post\<^sub>s \<dagger> P)"
by (simp add: R1_def usubst)
lemma post\<^sub>s_R2c [usubst]: "post\<^sub>s \<dagger> R2c(P) = R2c(post\<^sub>s \<dagger> P)"
by (simp add: R2c_def R2s_def usubst)
lemma cmt\<^sub>s_R1 [usubst]: "cmt\<^sub>s \<dagger> R1(P) = R1(cmt\<^sub>s \<dagger> P)"
by (simp add: R1_def usubst)
lemma cmt\<^sub>s_R2c [usubst]: "cmt\<^sub>s \<dagger> R2c(P) = R2c(cmt\<^sub>s \<dagger> P)"
by (simp add: R2c_def R2s_def usubst)
lemma pre_wait_false:
"pre\<^sub>R(P\<lbrakk>false/$wait\<rbrakk>) = pre\<^sub>R(P)"
by (rel_auto)
lemma cmt_wait_false:
"cmt\<^sub>R(P\<lbrakk>false/$wait\<rbrakk>) = cmt\<^sub>R(P)"
by (rel_auto)
lemma rea_pre_RH_design: "pre\<^sub>R(\<^bold>R(P \<turnstile> Q)) = R1(R2c(pre\<^sub>s \<dagger> P))"
by (simp add: RH_def usubst R3c_def pre\<^sub>R_def pre\<^sub>s_design R1_negate_R1 R2c_not rea_not_def)
lemma rea_pre_RHS_design: "pre\<^sub>R(\<^bold>R\<^sub>s(P \<turnstile> Q)) = R1(R2c(pre\<^sub>s \<dagger> P))"
by (simp add: RHS_def usubst R3h_def pre\<^sub>R_def pre\<^sub>s_design R1_negate_R1 R2c_not rea_not_def)
lemma rea_cmt_RH_design: "cmt\<^sub>R(\<^bold>R(P \<turnstile> Q)) = R1(R2c(cmt\<^sub>s \<dagger> (P \<Rightarrow> Q)))"
by (simp add: RH_def usubst R3c_def cmt\<^sub>R_def cmt\<^sub>s_design R1_idem)
lemma rea_cmt_RHS_design: "cmt\<^sub>R(\<^bold>R\<^sub>s(P \<turnstile> Q)) = R1(R2c(cmt\<^sub>s \<dagger> (P \<Rightarrow> Q)))"
by (simp add: RHS_def usubst R3h_def cmt\<^sub>R_def cmt\<^sub>s_design R1_idem)
lemma rea_peri_RH_design: "peri\<^sub>R(\<^bold>R(P \<turnstile> Q \<diamondop> R)) = R1(R2c(peri\<^sub>s \<dagger> (P \<Rightarrow>\<^sub>r Q)))"
by rel_auto
lemma rea_peri_RHS_design: "peri\<^sub>R(\<^bold>R\<^sub>s(P \<turnstile> Q \<diamondop> R)) = R1(R2c(peri\<^sub>s \<dagger> (P \<Rightarrow>\<^sub>r Q)))"
by (simp add:RHS_def usubst peri\<^sub>R_def R3h_def peri\<^sub>s_design, rel_auto)
lemma rea_post_RH_design: "post\<^sub>R(\<^bold>R(P \<turnstile> Q \<diamondop> R)) = R1(R2c(post\<^sub>s \<dagger> (P \<Rightarrow>\<^sub>r R)))"
by rel_auto
lemma rea_post_RHS_design: "post\<^sub>R(\<^bold>R\<^sub>s(P \<turnstile> Q \<diamondop> R)) = R1(R2c(post\<^sub>s \<dagger> (P \<Rightarrow>\<^sub>r R)))"
by (simp add:RHS_def usubst post\<^sub>R_def R3h_def post\<^sub>s_design, rel_auto)
lemma peri_cmt_def: "peri\<^sub>R(P) = (cmt\<^sub>R(P))\<lbrakk>true/$wait\<acute>\<rbrakk>"
by (rel_auto)
lemma post_cmt_def: "post\<^sub>R(P) = (cmt\<^sub>R(P))\<lbrakk>false/$wait\<acute>\<rbrakk>"
by (rel_auto)
lemma rdes_export_cmt: "\<^bold>R\<^sub>s(P \<turnstile> cmt\<^sub>s \<dagger> Q) = \<^bold>R\<^sub>s(P \<turnstile> Q)"
by (rel_auto)
lemma rdes_export_pre: "\<^bold>R\<^sub>s((P\<lbrakk>true,false/$ok,$wait\<rbrakk>) \<turnstile> Q) = \<^bold>R\<^sub>s(P \<turnstile> Q)"
by (rel_auto)
subsubsection \<open> Healthiness laws \<close>
lemma wait'_unrest_pre_SRD [unrest]:
"$wait\<acute> \<sharp> pre\<^sub>R(P) \<Longrightarrow> $wait\<acute> \<sharp> pre\<^sub>R (SRD P)"
apply (rel_auto)
using least_zero apply blast+
done
lemma R1_R2s_cmt_SRD:
assumes "P is SRD"
shows "R1(R2s(cmt\<^sub>R(P))) = cmt\<^sub>R(P)"
by (metis (no_types, lifting) R1_R2c_commute R1_R2s_R2c R1_idem R2c_idem SRD_reactive_design assms rea_cmt_RHS_design)
lemma R1_R2s_peri_SRD:
assumes "P is SRD"
shows "R1(R2s(peri\<^sub>R(P))) = peri\<^sub>R(P)"
by (metis (no_types, opaque_lifting) Healthy_def R1_R2s_R2c R2_def R2_idem RHS_def SRD_RH_design_form assms R1_idem peri\<^sub>R_def peri\<^sub>s_R1 peri\<^sub>s_R2c)
lemma R1_peri_SRD:
assumes "P is SRD"
shows "R1(peri\<^sub>R(P)) = peri\<^sub>R(P)"
proof -
have "R1(peri\<^sub>R(P)) = R1(R1(R2s(peri\<^sub>R(P))))"
by (simp add: R1_R2s_peri_SRD assms)
also have "... = peri\<^sub>R(P)"
by (simp add: R1_idem, simp add: R1_R2s_peri_SRD assms)
finally show ?thesis .
qed
lemma R1_R2c_peri_RHS:
assumes "P is SRD"
shows "R1(R2c(peri\<^sub>R(P))) = peri\<^sub>R(P)"
by (metis R1_R2s_R2c R1_R2s_peri_SRD assms)
lemma R1_R2s_post_SRD:
assumes "P is SRD"
shows "R1(R2s(post\<^sub>R(P))) = post\<^sub>R(P)"
by (metis (no_types, opaque_lifting) Healthy_def R1_R2s_R2c R1_idem R2_def R2_idem RHS_def SRD_RH_design_form assms post\<^sub>R_def post\<^sub>s_R1 post\<^sub>s_R2c)
lemma R2c_peri_SRD:
assumes "P is SRD"
shows "R2c(peri\<^sub>R(P)) = peri\<^sub>R(P)"
by (metis R1_R2c_commute R1_R2c_peri_RHS R1_peri_SRD assms)
lemma R1_post_SRD:
assumes "P is SRD"
shows "R1(post\<^sub>R(P)) = post\<^sub>R(P)"
proof -
have "R1(post\<^sub>R(P)) = R1(R1(R2s(post\<^sub>R(P))))"
by (simp add: R1_R2s_post_SRD assms)
also have "... = post\<^sub>R(P)"
by (simp add: R1_idem, simp add: R1_R2s_post_SRD assms)
finally show ?thesis .
qed
lemma R2c_post_SRD:
assumes "P is SRD"
shows "R2c(post\<^sub>R(P)) = post\<^sub>R(P)"
by (metis R1_R2c_commute R1_R2s_R2c R1_R2s_post_SRD R1_post_SRD assms)
lemma R1_R2c_post_RHS:
assumes "P is SRD"
shows "R1(R2c(post\<^sub>R(P))) = post\<^sub>R(P)"
by (metis R1_R2s_R2c R1_R2s_post_SRD assms)
lemma R2_cmt_conj_wait':
"P is SRD \<Longrightarrow> R2(cmt\<^sub>R P \<and> \<not> $wait\<acute>) = (cmt\<^sub>R P \<and> \<not> $wait\<acute>)"
by (simp add: R2_def R2s_conj R2s_not R2s_wait' R1_extend_conj R1_R2s_cmt_SRD)
lemma R2c_preR:
"P is SRD \<Longrightarrow> R2c(pre\<^sub>R(P)) = pre\<^sub>R(P)"
by (metis (no_types, lifting) R1_R2c_commute R2c_idem SRD_reactive_design rea_pre_RHS_design)
lemma preR_R2_closed [closure]:
assumes "P is R2"
shows "pre\<^sub>R P is R2"
proof -
have "R2(pre\<^sub>R(R2(P))) = pre\<^sub>R(R2(P))"
by (rel_auto)
thus ?thesis
by (metis Healthy_def assms)
qed
lemma periR_R2_closed [closure]:
assumes "P is R2"
shows "peri\<^sub>R P is R2"
proof -
have "R2(peri\<^sub>R(R2(P))) = peri\<^sub>R(R2(P))"
by (rel_auto)
thus ?thesis
by (metis Healthy_def assms)
qed
lemma postR_R2_closed [closure]:
assumes "P is R2"
shows "post\<^sub>R P is R2"
proof -
have "R2(post\<^sub>R(R2(P))) = post\<^sub>R(R2(P))"
by (rel_auto)
thus ?thesis
by (metis Healthy_def assms)
qed
lemma postR_SRD_R1 [closure]: "P is SRD \<Longrightarrow> post\<^sub>R(P) is R1"
by (simp add: Healthy_def' R1_post_SRD)
lemma R2c_periR:
"P is SRD \<Longrightarrow> R2c(peri\<^sub>R(P)) = peri\<^sub>R(P)"
by (metis (no_types, lifting) R1_R2c_commute R1_R2s_R2c R1_R2s_peri_SRD R2c_idem)
lemma R2c_postR:
"P is SRD \<Longrightarrow> R2c(post\<^sub>R(P)) = post\<^sub>R(P)"
by (metis (no_types, opaque_lifting) R1_R2c_commute R1_R2c_is_R2 R1_R2s_post_SRD R2_def R2s_idem)
lemma periR_RR [closure]: "P is R2 \<Longrightarrow> peri\<^sub>R(P) is RR"
by (rule RR_intro, simp_all add: closure unrest)
lemma postR_RR [closure]: "P is R2 \<Longrightarrow> post\<^sub>R(P) is RR"
by (rule RR_intro, simp_all add: closure unrest)
lemma wpR_trace_ident_pre [wp]:
"($tr\<acute> =\<^sub>u $tr \<and> \<lceil>II\<rceil>\<^sub>R) wp\<^sub>r pre\<^sub>R P = pre\<^sub>R P"
by (rel_auto)
lemma R1_preR [closure]:
"pre\<^sub>R(P) is R1"
by (rel_auto)
lemma trace_ident_left_periR:
"($tr\<acute> =\<^sub>u $tr \<and> \<lceil>II\<rceil>\<^sub>R) ;; peri\<^sub>R(P) = peri\<^sub>R(P)"
by (rel_auto)
lemma trace_ident_left_postR:
"($tr\<acute> =\<^sub>u $tr \<and> \<lceil>II\<rceil>\<^sub>R) ;; post\<^sub>R(P) = post\<^sub>R(P)"
by (rel_auto)
lemma trace_ident_right_postR:
"post\<^sub>R(P) ;; ($tr\<acute> =\<^sub>u $tr \<and> \<lceil>II\<rceil>\<^sub>R) = post\<^sub>R(P)"
by (rel_auto)
subsubsection \<open> Calculation laws \<close>
lemma wait'_cond_peri_post_cmt [rdes]:
"cmt\<^sub>R P = peri\<^sub>R P \<diamondop> post\<^sub>R P"
by (rel_auto)
lemma preR_rdes [rdes]:
assumes "P is RR"
shows "pre\<^sub>R(\<^bold>R(P \<turnstile> Q \<diamondop> R)) = P"
by (simp add: rea_pre_RH_design unrest usubst assms Healthy_if RR_implies_R2c RR_implies_R1)
lemma preR_srdes [rdes]:
assumes "P is RR"
shows "pre\<^sub>R(\<^bold>R\<^sub>s(P \<turnstile> Q \<diamondop> R)) = P"
by (simp add: rea_pre_RHS_design unrest usubst assms Healthy_if RR_implies_R2c RR_implies_R1)
lemma periR_rdes [rdes]:
assumes "P is RR" "Q is RR"
shows "peri\<^sub>R(\<^bold>R(P \<turnstile> Q \<diamondop> R)) = (P \<Rightarrow>\<^sub>r Q)"
by (simp add: rea_peri_RH_design unrest usubst assms Healthy_if RR_implies_R2c closure)
lemma periR_srdes [rdes]:
assumes "P is RR" "Q is RR"
shows "peri\<^sub>R(\<^bold>R\<^sub>s(P \<turnstile> Q \<diamondop> R)) = (P \<Rightarrow>\<^sub>r Q)"
by (simp add: rea_peri_RHS_design unrest usubst assms Healthy_if RR_implies_R2c closure)
lemma postR_rdes [rdes]:
assumes "P is RR" "R is RR"
shows "post\<^sub>R(\<^bold>R(P \<turnstile> Q \<diamondop> R)) = (P \<Rightarrow>\<^sub>r R)"
by (simp add: rea_post_RH_design unrest usubst assms Healthy_if RR_implies_R2c closure)
lemma postR_srdes [rdes]:
assumes "P is RR" "R is RR"
shows "post\<^sub>R(\<^bold>R\<^sub>s(P \<turnstile> Q \<diamondop> R)) = (P \<Rightarrow>\<^sub>r R)"
by (simp add: rea_post_RHS_design unrest usubst assms Healthy_if RR_implies_R2c closure)
lemma preR_Chaos [rdes]: "pre\<^sub>R(Chaos) = false"
by (simp add: Chaos_def, rel_simp)
lemma periR_Chaos [rdes]: "peri\<^sub>R(Chaos) = true\<^sub>r"
by (simp add: Chaos_def, rel_simp)
lemma postR_Chaos [rdes]: "post\<^sub>R(Chaos) = true\<^sub>r"
by (simp add: Chaos_def, rel_simp)
lemma preR_Miracle [rdes]: "pre\<^sub>R(Miracle) = true\<^sub>r"
by (simp add: Miracle_def, rel_auto)
lemma periR_Miracle [rdes]: "peri\<^sub>R(Miracle) = false"
by (simp add: Miracle_def, rel_auto)
lemma postR_Miracle [rdes]: "post\<^sub>R(Miracle) = false"
by (simp add: Miracle_def, rel_auto)
lemma preR_srdes_skip [rdes]: "pre\<^sub>R(II\<^sub>R) = true\<^sub>r"
by (rel_auto)
lemma periR_srdes_skip [rdes]: "peri\<^sub>R(II\<^sub>R) = false"
by (rel_auto)
lemma postR_srdes_skip [rdes]: "post\<^sub>R(II\<^sub>R) = ($tr\<acute> =\<^sub>u $tr \<and> \<lceil>II\<rceil>\<^sub>R)"
by (rel_auto)
lemma preR_INF [rdes]: "A \<noteq> {} \<Longrightarrow> pre\<^sub>R(\<Sqinter> A) = (\<And> P\<in>A \<bullet> pre\<^sub>R(P))"
by (rel_auto)
lemma periR_INF [rdes]: "peri\<^sub>R(\<Sqinter> A) = (\<Or> P\<in>A \<bullet> peri\<^sub>R(P))"
by (rel_auto)
lemma postR_INF [rdes]: "post\<^sub>R(\<Sqinter> A) = (\<Or> P\<in>A \<bullet> post\<^sub>R(P))"
by (rel_auto)
lemma preR_UINF [rdes]: "pre\<^sub>R(\<Sqinter> i \<bullet> P(i)) = (\<Squnion> i \<bullet> pre\<^sub>R(P(i)))"
by (rel_auto)
lemma periR_UINF [rdes]: "peri\<^sub>R(\<Sqinter> i \<bullet> P(i)) = (\<Sqinter> i \<bullet> peri\<^sub>R(P(i)))"
by (rel_auto)
lemma postR_UINF [rdes]: "post\<^sub>R(\<Sqinter> i \<bullet> P(i)) = (\<Sqinter> i \<bullet> post\<^sub>R(P(i)))"
by (rel_auto)
lemma preR_UINF_member [rdes]: "A \<noteq> {} \<Longrightarrow> pre\<^sub>R(\<Sqinter> i\<in>A \<bullet> P(i)) = (\<Squnion> i\<in>A \<bullet> pre\<^sub>R(P(i)))"
by (rel_auto)
lemma preR_UINF_member_2 [rdes]: "A \<noteq> {} \<Longrightarrow> pre\<^sub>R(\<Sqinter> (i,j)\<in>A \<bullet> P i j) = (\<Squnion> (i,j)\<in>A \<bullet> pre\<^sub>R(P i j))"
by (rel_auto)
lemma preR_UINF_member_3 [rdes]: "A \<noteq> {} \<Longrightarrow> pre\<^sub>R(\<Sqinter> (i,j,k)\<in>A \<bullet> P i j k) = (\<Squnion> (i,j,k)\<in>A \<bullet> pre\<^sub>R(P i j k))"
by (rel_auto)
lemma periR_UINF_member [rdes]: "peri\<^sub>R(\<Sqinter> i\<in>A \<bullet> P(i)) = (\<Sqinter> i\<in>A \<bullet> peri\<^sub>R(P(i)))"
by (rel_auto)
lemma periR_UINF_member_2 [rdes]: "peri\<^sub>R(\<Sqinter> (i,j)\<in>A \<bullet> P i j) = (\<Sqinter> (i,j)\<in>A \<bullet> peri\<^sub>R(P i j))"
by (rel_auto)
lemma periR_UINF_member_3 [rdes]: "peri\<^sub>R(\<Sqinter> (i,j,k)\<in>A \<bullet> P i j k) = (\<Sqinter> (i,j,k)\<in>A \<bullet> peri\<^sub>R(P i j k))"
by (rel_auto)
lemma postR_UINF_member [rdes]: "post\<^sub>R(\<Sqinter> i\<in>A \<bullet> P(i)) = (\<Sqinter> i\<in>A \<bullet> post\<^sub>R(P(i)))"
by (rel_auto)
lemma postR_UINF_member_2 [rdes]: "post\<^sub>R(\<Sqinter> (i,j)\<in>A \<bullet> P i j) = (\<Sqinter> (i,j)\<in>A \<bullet> post\<^sub>R(P i j))"
by (rel_auto)
lemma postR_UINF_member_3 [rdes]: "post\<^sub>R(\<Sqinter> (i,j,k)\<in>A \<bullet> P i j k) = (\<Sqinter> (i,j,k)\<in>A \<bullet> post\<^sub>R(P i j k))"
by (rel_auto)
lemma preR_inf [rdes]: "pre\<^sub>R(P \<sqinter> Q) = (pre\<^sub>R(P) \<and> pre\<^sub>R(Q))"
by (rel_auto)
lemma periR_inf [rdes]: "peri\<^sub>R(P \<sqinter> Q) = (peri\<^sub>R(P) \<or> peri\<^sub>R(Q))"
by (rel_auto)
lemma postR_inf [rdes]: "post\<^sub>R(P \<sqinter> Q) = (post\<^sub>R(P) \<or> post\<^sub>R(Q))"
by (rel_auto)
lemma preR_SUP [rdes]: "pre\<^sub>R(\<Squnion> A) = (\<Or> P\<in>A \<bullet> pre\<^sub>R(P))"
by (rel_auto)
lemma periR_SUP [rdes]: "A \<noteq> {} \<Longrightarrow> peri\<^sub>R(\<Squnion> A) = (\<And> P\<in>A \<bullet> peri\<^sub>R(P))"
by (rel_auto)
lemma postR_SUP [rdes]: "A \<noteq> {} \<Longrightarrow> post\<^sub>R(\<Squnion> A) = (\<And> P\<in>A \<bullet> post\<^sub>R(P))"
by (rel_auto)
subsection \<open> Formation laws \<close>
subsubsection \<open> Regular \<close>
lemma rdes_skip_tri_design [rdes_def]: "II\<^sub>C = \<^bold>R(true\<^sub>r \<turnstile> false \<diamondop> II\<^sub>r)"
apply (simp add: skip_rea_def, rel_auto)
using minus_zero_eq apply blast+
done
lemma RH_tri_design_form:
assumes "P\<^sub>1 is RR" "P\<^sub>2 is RR" "P\<^sub>3 is RR"
shows "\<^bold>R(P\<^sub>1 \<turnstile> P\<^sub>2 \<diamondop> P\<^sub>3) = (II\<^sub>C \<triangleleft> $wait \<triangleright> (($ok \<and> P\<^sub>1) \<Rightarrow>\<^sub>r ($ok\<acute> \<and> (P\<^sub>2 \<diamondop> P\<^sub>3))))"
proof -
have "\<^bold>R(RR(P\<^sub>1) \<turnstile> RR(P\<^sub>2) \<diamondop> RR(P\<^sub>3)) = (II\<^sub>C \<triangleleft> $wait \<triangleright> (($ok \<and> RR(P\<^sub>1)) \<Rightarrow>\<^sub>r ($ok\<acute> \<and> (RR(P\<^sub>2) \<diamondop> RR(P\<^sub>3)))))"
apply (rel_auto) using minus_zero_eq by blast
thus ?thesis
by (simp add: Healthy_if assms)
qed
lemma RH_design_pre_post_form:
"\<^bold>R((\<not> P\<^sup>f\<^sub>f) \<turnstile> P\<^sup>t\<^sub>f) = \<^bold>R(pre\<^sub>R(P) \<turnstile> cmt\<^sub>R(P))"
proof -
have "\<^bold>R((\<not> P\<^sup>f\<^sub>f) \<turnstile> P\<^sup>t\<^sub>f) = \<^bold>R((\<not> P\<^sup>f\<^sub>f)\<lbrakk>true/$ok\<rbrakk> \<turnstile> P\<^sup>t\<^sub>f\<lbrakk>true/$ok\<rbrakk>)"
by (simp add: design_subst_ok)
also have "... = \<^bold>R(pre\<^sub>R(P) \<turnstile> cmt\<^sub>R(P))"
by (simp add: pre\<^sub>R_def cmt\<^sub>R_def usubst, rel_auto)
finally show ?thesis .
qed
lemma RD_as_reactive_design:
"RD(P) = \<^bold>R(pre\<^sub>R(P) \<turnstile> cmt\<^sub>R(P))"
by (simp add: RH_design_pre_post_form RD_RH_design_form)
lemma RD_reactive_design_alt:
assumes "P is RD"
shows "\<^bold>R(pre\<^sub>R(P) \<turnstile> cmt\<^sub>R(P)) = P"
proof -
have "\<^bold>R(pre\<^sub>R(P) \<turnstile> cmt\<^sub>R(P)) = \<^bold>R((\<not> P\<^sup>f\<^sub>f) \<turnstile> P\<^sup>t\<^sub>f)"
by (simp add: RH_design_pre_post_form)
thus ?thesis
by (simp add: RD_reactive_design assms)
qed
lemma RD_reactive_tri_design_lemma:
"RD(P) = \<^bold>R((\<not> P\<^sup>f\<^sub>f) \<turnstile> P\<^sup>t\<^sub>f\<lbrakk>true/$wait\<acute>\<rbrakk> \<diamondop> P\<^sup>t\<^sub>f\<lbrakk>false/$wait\<acute>\<rbrakk>)"
by (simp add: RD_RH_design_form wait'_cond_split)
lemma RD_as_reactive_tri_design:
"RD(P) = \<^bold>R(pre\<^sub>R(P) \<turnstile> peri\<^sub>R(P) \<diamondop> post\<^sub>R(P))"
proof -
have "RD(P) = \<^bold>R((\<not> P\<^sup>f\<^sub>f) \<turnstile> P\<^sup>t\<^sub>f\<lbrakk>true/$wait\<acute>\<rbrakk> \<diamondop> P\<^sup>t\<^sub>f\<lbrakk>false/$wait\<acute>\<rbrakk>)"
by (simp add: RD_RH_design_form wait'_cond_split)
also have "... = \<^bold>R(pre\<^sub>R(P) \<turnstile> peri\<^sub>R(P) \<diamondop> post\<^sub>R(P))"
by (rel_auto)
finally show ?thesis .
qed
lemma RD_reactive_tri_design:
assumes "P is RD"
shows "\<^bold>R(pre\<^sub>R(P) \<turnstile> peri\<^sub>R(P) \<diamondop> post\<^sub>R(P)) = P"
by (metis Healthy_if RD_as_reactive_tri_design assms)
lemma RD_elimination [RD_elim]: "\<lbrakk> P is RD; Q(\<^bold>R(pre\<^sub>R(P) \<turnstile> peri\<^sub>R(P) \<diamondop> post\<^sub>R(P))) \<rbrakk> \<Longrightarrow> Q(P)"
by (simp add: RD_reactive_tri_design)
lemma RH_tri_design_is_RD [closure]:
assumes "$ok\<acute> \<sharp> P" "$ok\<acute> \<sharp> Q" "$ok\<acute> \<sharp> R"
shows "\<^bold>R(P \<turnstile> Q \<diamondop> R) is RD"
by (rule RH_design_is_RD, simp_all add: unrest assms)
lemma RD_rdes_intro [closure]:
assumes "P is RR" "Q is RR" "R is RR"
shows "\<^bold>R(P \<turnstile> Q \<diamondop> R) is RD"
by (rule RH_tri_design_is_RD, simp_all add: unrest closure assms)
subsubsection \<open> Stateful \<close>
lemma srdes_skip_tri_design [rdes_def]: "II\<^sub>R = \<^bold>R\<^sub>s(true\<^sub>r \<turnstile> false \<diamondop> II\<^sub>r)"
by (simp add: srdes_skip_def, rel_auto)
lemma Chaos_tri_def [rdes_def]: "Chaos = \<^bold>R\<^sub>s(false \<turnstile> false \<diamondop> false)"
by (simp add: Chaos_def design_false_pre)
lemma Miracle_tri_def [rdes_def]: "Miracle = \<^bold>R\<^sub>s(true\<^sub>r \<turnstile> false \<diamondop> false)"
by (simp add: Miracle_def R1_design_R1_pre wait'_cond_idem)
lemma RHS_tri_design_form:
assumes "P\<^sub>1 is RR" "P\<^sub>2 is RR" "P\<^sub>3 is RR"
shows "\<^bold>R\<^sub>s(P\<^sub>1 \<turnstile> P\<^sub>2 \<diamondop> P\<^sub>3) = (II\<^sub>R \<triangleleft> $wait \<triangleright> (($ok \<and> P\<^sub>1) \<Rightarrow>\<^sub>r ($ok\<acute> \<and> (P\<^sub>2 \<diamondop> P\<^sub>3))))"
proof -
have "\<^bold>R\<^sub>s(RR(P\<^sub>1) \<turnstile> RR(P\<^sub>2) \<diamondop> RR(P\<^sub>3)) = (II\<^sub>R \<triangleleft> $wait \<triangleright> (($ok \<and> RR(P\<^sub>1)) \<Rightarrow>\<^sub>r ($ok\<acute> \<and> (RR(P\<^sub>2) \<diamondop> RR(P\<^sub>3)))))"
apply (rel_auto) using minus_zero_eq by blast
thus ?thesis
by (simp add: Healthy_if assms)
qed
lemma RHS_design_pre_post_form:
"\<^bold>R\<^sub>s((\<not> P\<^sup>f\<^sub>f) \<turnstile> P\<^sup>t\<^sub>f) = \<^bold>R\<^sub>s(pre\<^sub>R(P) \<turnstile> cmt\<^sub>R(P))"
proof -
have "\<^bold>R\<^sub>s((\<not> P\<^sup>f\<^sub>f) \<turnstile> P\<^sup>t\<^sub>f) = \<^bold>R\<^sub>s((\<not> P\<^sup>f\<^sub>f)\<lbrakk>true/$ok\<rbrakk> \<turnstile> P\<^sup>t\<^sub>f\<lbrakk>true/$ok\<rbrakk>)"
by (simp add: design_subst_ok)
also have "... = \<^bold>R\<^sub>s(pre\<^sub>R(P) \<turnstile> cmt\<^sub>R(P))"
by (simp add: pre\<^sub>R_def cmt\<^sub>R_def usubst, rel_auto)
finally show ?thesis .
qed
lemma SRD_as_reactive_design:
"SRD(P) = \<^bold>R\<^sub>s(pre\<^sub>R(P) \<turnstile> cmt\<^sub>R(P))"
by (simp add: RHS_design_pre_post_form SRD_RH_design_form)
lemma SRD_reactive_design_alt:
assumes "P is SRD"
shows "\<^bold>R\<^sub>s(pre\<^sub>R(P) \<turnstile> cmt\<^sub>R(P)) = P"
proof -
have "\<^bold>R\<^sub>s(pre\<^sub>R(P) \<turnstile> cmt\<^sub>R(P)) = \<^bold>R\<^sub>s((\<not> P\<^sup>f\<^sub>f) \<turnstile> P\<^sup>t\<^sub>f)"
by (simp add: RHS_design_pre_post_form)
thus ?thesis
by (simp add: SRD_reactive_design assms)
qed
lemma SRD_reactive_tri_design_lemma:
"SRD(P) = \<^bold>R\<^sub>s((\<not> P\<^sup>f\<^sub>f) \<turnstile> P\<^sup>t\<^sub>f\<lbrakk>true/$wait\<acute>\<rbrakk> \<diamondop> P\<^sup>t\<^sub>f\<lbrakk>false/$wait\<acute>\<rbrakk>)"
by (simp add: SRD_RH_design_form wait'_cond_split)
lemma SRD_as_reactive_tri_design:
"SRD(P) = \<^bold>R\<^sub>s(pre\<^sub>R(P) \<turnstile> peri\<^sub>R(P) \<diamondop> post\<^sub>R(P))"
proof -
have "SRD(P) = \<^bold>R\<^sub>s((\<not> P\<^sup>f\<^sub>f) \<turnstile> P\<^sup>t\<^sub>f\<lbrakk>true/$wait\<acute>\<rbrakk> \<diamondop> P\<^sup>t\<^sub>f\<lbrakk>false/$wait\<acute>\<rbrakk>)"
by (simp add: SRD_RH_design_form wait'_cond_split)
also have "... = \<^bold>R\<^sub>s(pre\<^sub>R(P) \<turnstile> peri\<^sub>R(P) \<diamondop> post\<^sub>R(P))"
apply (simp add: usubst)
apply (subst design_subst_ok_ok'[THEN sym])
apply (simp add: pre\<^sub>R_def peri\<^sub>R_def post\<^sub>R_def usubst unrest)
apply (rel_auto)
done
finally show ?thesis .
qed
lemma SRD_reactive_tri_design:
assumes "P is SRD"
shows "\<^bold>R\<^sub>s(pre\<^sub>R(P) \<turnstile> peri\<^sub>R(P) \<diamondop> post\<^sub>R(P)) = P"
by (metis Healthy_if SRD_as_reactive_tri_design assms)
lemma SRD_elim [RD_elim]: "\<lbrakk> P is SRD; Q(\<^bold>R\<^sub>s(pre\<^sub>R(P) \<turnstile> peri\<^sub>R(P) \<diamondop> post\<^sub>R(P))) \<rbrakk> \<Longrightarrow> Q(P)"
by (simp add: SRD_reactive_tri_design)
lemma RHS_tri_design_is_SRD [closure]:
assumes "$ok\<acute> \<sharp> P" "$ok\<acute> \<sharp> Q" "$ok\<acute> \<sharp> R"
shows "\<^bold>R\<^sub>s(P \<turnstile> Q \<diamondop> R) is SRD"
by (rule RHS_design_is_SRD, simp_all add: unrest assms)
lemma SRD_rdes_intro [closure]:
assumes "P is RR" "Q is RR" "R is RR"
shows "\<^bold>R\<^sub>s(P \<turnstile> Q \<diamondop> R) is SRD"
by (rule RHS_tri_design_is_SRD, simp_all add: unrest closure assms)
lemma USUP_R1_R2s_cmt_SRD:
assumes "A \<subseteq> \<lbrakk>SRD\<rbrakk>\<^sub>H"
shows "(\<Squnion> P \<in> A \<bullet> R1 (R2s (cmt\<^sub>R P))) = (\<Squnion> P \<in> A \<bullet> cmt\<^sub>R P)"
by (rule USUP_cong[of A], metis (mono_tags, lifting) Ball_Collect R1_R2s_cmt_SRD assms)
lemma UINF_R1_R2s_cmt_SRD:
assumes "A \<subseteq> \<lbrakk>SRD\<rbrakk>\<^sub>H"
shows "(\<Sqinter> P \<in> A \<bullet> R1 (R2s (cmt\<^sub>R P))) = (\<Sqinter> P \<in> A \<bullet> cmt\<^sub>R P)"
by (rule UINF_cong[of A], metis (mono_tags, lifting) Ball_Collect R1_R2s_cmt_SRD assms)
subsubsection \<open> Order laws \<close>
lemma preR_antitone: "P \<sqsubseteq> Q \<Longrightarrow> pre\<^sub>R(Q) \<sqsubseteq> pre\<^sub>R(P)"
by (rel_auto)
lemma periR_monotone: "P \<sqsubseteq> Q \<Longrightarrow> peri\<^sub>R(P) \<sqsubseteq> peri\<^sub>R(Q)"
by (rel_auto)
lemma postR_monotone: "P \<sqsubseteq> Q \<Longrightarrow> post\<^sub>R(P) \<sqsubseteq> post\<^sub>R(Q)"
by (rel_auto)
subsection \<open> Composition laws \<close>
theorem R1_design_composition_RR:
assumes "P is RR" "Q is RR" "R is RR" "S is RR"
shows
"(R1(P \<turnstile> Q) ;; R1(R \<turnstile> S)) = R1(((\<not>\<^sub>r P) wp\<^sub>r false \<and> Q wp\<^sub>r R) \<turnstile> (Q ;; S))"
apply (subst R1_design_composition)
apply (simp_all add: assms unrest wp_rea_def Healthy_if closure)
apply (rel_auto)
done
theorem R1_design_composition_RC:
assumes "P is RC" "Q is RR" "R is RR" "S is RR"
shows
"(R1(P \<turnstile> Q) ;; R1(R \<turnstile> S)) = R1((P \<and> Q wp\<^sub>r R) \<turnstile> (Q ;; S))"
by (simp add: R1_design_composition_RR assms unrest Healthy_if closure wp)
subsubsection \<open> Regular \<close>
theorem RH_tri_design_composition:
assumes "$ok\<acute> \<sharp> P" "$ok\<acute> \<sharp> Q\<^sub>1" "$ok\<acute> \<sharp> Q\<^sub>2" "$ok \<sharp> R" "$ok \<sharp> S\<^sub>1" "$ok \<sharp> S\<^sub>2"
"$wait \<sharp> R" "$wait\<acute> \<sharp> Q\<^sub>2" "$wait \<sharp> S\<^sub>1" "$wait \<sharp> S\<^sub>2"
shows "(\<^bold>R(P \<turnstile> Q\<^sub>1 \<diamondop> Q\<^sub>2) ;; \<^bold>R(R \<turnstile> S\<^sub>1 \<diamondop> S\<^sub>2)) =
\<^bold>R((\<not> (R1 (\<not> R2s P) ;; R1 true) \<and> \<not> (R1(R2s Q\<^sub>2) ;; R1 (\<not> R2s R))) \<turnstile>
((Q\<^sub>1 \<or> (R1 (R2s Q\<^sub>2) ;; R1 (R2s S\<^sub>1))) \<diamondop> ((R1 (R2s Q\<^sub>2) ;; R1 (R2s S\<^sub>2)))))"
proof -
have 1:"(\<not> ((R1 (R2s (Q\<^sub>1 \<diamondop> Q\<^sub>2)) \<and> \<not> $wait\<acute>) ;; R1 (\<not> R2s R))) =
(\<not> ((R1 (R2s Q\<^sub>2) \<and> \<not> $wait\<acute>) ;; R1 (\<not> R2s R)))"
by (metis (no_types, opaque_lifting) R1_extend_conj R2s_conj R2s_not R2s_wait' wait'_cond_false)
have 2: "(R1 (R2s (Q\<^sub>1 \<diamondop> Q\<^sub>2)) ;; (\<lceil>II\<rceil>\<^sub>D \<triangleleft> $wait \<triangleright> R1 (R2s (S\<^sub>1 \<diamondop> S\<^sub>2)))) =
(((R1 (R2s Q\<^sub>1)) \<or> (R1 (R2s Q\<^sub>2) ;; R1 (R2s S\<^sub>1))) \<diamondop> (R1 (R2s Q\<^sub>2) ;; R1 (R2s S\<^sub>2)))"
proof -
have "(R1 (R2s Q\<^sub>1) ;; ($wait \<and> (\<lceil>II\<rceil>\<^sub>D \<triangleleft> $wait \<triangleright> R1 (R2s S\<^sub>1) \<diamondop> R1 (R2s S\<^sub>2))))
= (((R1 (R2s Q\<^sub>1)) \<and> $wait\<acute>))"
proof -
have "(R1 (R2s Q\<^sub>1) ;; ($wait \<and> ((\<lceil>II\<rceil>\<^sub>D) \<triangleleft> $wait \<triangleright> R1 (R2s S\<^sub>1) \<diamondop> R1 (R2s S\<^sub>2))))
= (R1 (R2s Q\<^sub>1) ;; ($wait \<and> (\<lceil>II\<rceil>\<^sub>D)))"
by (rel_auto)
also have "... = ((R1 (R2s Q\<^sub>1) ;; \<lceil>II\<rceil>\<^sub>D) \<and> $wait\<acute>)"
by (rel_auto)
also from assms(2) have "... = ((R1 (R2s Q\<^sub>1)) \<and> $wait\<acute>)"
by (rel_auto, blast)
finally show ?thesis .
qed
moreover have "(R1 (R2s Q\<^sub>2) ;; (\<not> $wait \<and> ((\<lceil>II\<rceil>\<^sub>D) \<triangleleft> $wait \<triangleright> R1 (R2s S\<^sub>1) \<diamondop> R1 (R2s S\<^sub>2))))
= ((R1 (R2s Q\<^sub>2)) ;; (R1 (R2s S\<^sub>1) \<diamondop> R1 (R2s S\<^sub>2)))"
proof -
have "(R1 (R2s Q\<^sub>2) ;; (\<not> $wait \<and> (\<lceil>II\<rceil>\<^sub>D \<triangleleft> $wait \<triangleright> R1 (R2s S\<^sub>1) \<diamondop> R1 (R2s S\<^sub>2))))
= (R1 (R2s Q\<^sub>2) ;; (\<not> $wait \<and> (R1 (R2s S\<^sub>1) \<diamondop> R1 (R2s S\<^sub>2))))"
by (metis (no_types, lifting) cond_def conj_disj_not_abs utp_pred_laws.double_compl utp_pred_laws.inf.left_idem utp_pred_laws.sup_assoc utp_pred_laws.sup_inf_absorb)
also have "... = ((R1 (R2s Q\<^sub>2))\<lbrakk>false/$wait\<acute>\<rbrakk> ;; (R1 (R2s S\<^sub>1) \<diamondop> R1 (R2s S\<^sub>2))\<lbrakk>false/$wait\<rbrakk>)"
by (metis false_alt_def seqr_right_one_point upred_eq_false wait_vwb_lens)
also have "... = ((R1 (R2s Q\<^sub>2)) ;; (R1 (R2s S\<^sub>1) \<diamondop> R1 (R2s S\<^sub>2)))"
by (simp add: wait'_cond_def usubst unrest assms)
finally show ?thesis .
qed
moreover
have "((R1 (R2s Q\<^sub>1) \<and> $wait\<acute>) \<or> ((R1 (R2s Q\<^sub>2)) ;; (R1 (R2s S\<^sub>1) \<diamondop> R1 (R2s S\<^sub>2))))
= (R1 (R2s Q\<^sub>1) \<or> (R1 (R2s Q\<^sub>2) ;; R1 (R2s S\<^sub>1))) \<diamondop> ((R1 (R2s Q\<^sub>2) ;; R1 (R2s S\<^sub>2)))"
by (simp add: wait'_cond_def cond_seq_right_distr cond_and_T_integrate unrest)
ultimately show ?thesis
by (simp add: R2s_wait'_cond R1_wait'_cond wait'_cond_seq ex_conj_contr_right unrest)
qed
from assms(7,8) have 3: "(R1 (R2s Q\<^sub>2) \<and> \<not> $wait\<acute>) ;; R1 (\<not> R2s R) = R1 (R2s Q\<^sub>2) ;; R1 (\<not> R2s R)"
by (rel_auto, meson)
show ?thesis
by (simp add: RH_design_composition unrest assms 1 2 3, simp add: R1_R2s_R2c RH_design_lemma1)
qed
theorem RH_tri_design_composition_wp:
assumes "$ok\<acute> \<sharp> P" "$ok\<acute> \<sharp> Q\<^sub>1" "$ok\<acute> \<sharp> Q\<^sub>2" "$ok \<sharp> R" "$ok \<sharp> S\<^sub>1" "$ok \<sharp> S\<^sub>2"
"$wait \<sharp> R" "$wait\<acute> \<sharp> Q\<^sub>2" "$wait \<sharp> S\<^sub>1" "$wait \<sharp> S\<^sub>2"
"P is R2c" "Q\<^sub>1 is R1" "Q\<^sub>1 is R2c" "Q\<^sub>2 is R1" "Q\<^sub>2 is R2c"
"R is R2c" "S\<^sub>1 is R1" "S\<^sub>1 is R2c" "S\<^sub>2 is R1" "S\<^sub>2 is R2c"
shows "\<^bold>R(P \<turnstile> Q\<^sub>1 \<diamondop> Q\<^sub>2) ;; \<^bold>R(R \<turnstile> S\<^sub>1 \<diamondop> S\<^sub>2) =
\<^bold>R(((\<not>\<^sub>r P) wp\<^sub>r false \<and> Q\<^sub>2 wp\<^sub>r R) \<turnstile> ((Q\<^sub>1 \<sqinter> (Q\<^sub>2 ;; S\<^sub>1)) \<diamondop> (Q\<^sub>2 ;; S\<^sub>2)))" (is "?lhs = ?rhs")
proof -
have "?lhs = \<^bold>R ((\<not> R1 (\<not> P) ;; R1 true \<and> \<not> Q\<^sub>2 ;; R1 (\<not> R)) \<turnstile> (Q\<^sub>1 \<sqinter> (Q\<^sub>2 ;; S\<^sub>1)) \<diamondop> (Q\<^sub>2 ;; S\<^sub>2))"
by (simp add: RH_tri_design_composition assms Healthy_if R2c_healthy_R2s disj_upred_def)
(metis (no_types, opaque_lifting) R1_negate_R1 R2c_healthy_R2s assms(11,16))
also have "... = ?rhs"
by (rel_auto)
finally show ?thesis .
qed
theorem RH_tri_design_composition_RR_wp:
assumes "P is RR" "Q\<^sub>1 is RR" "Q\<^sub>2 is RR"
"R is RR" "S\<^sub>1 is RR" "S\<^sub>2 is RR"
shows "\<^bold>R(P \<turnstile> Q\<^sub>1 \<diamondop> Q\<^sub>2) ;; \<^bold>R(R \<turnstile> S\<^sub>1 \<diamondop> S\<^sub>2) =
\<^bold>R(((\<not>\<^sub>r P) wp\<^sub>r false \<and> Q\<^sub>2 wp\<^sub>r R) \<turnstile> ((Q\<^sub>1 \<sqinter> (Q\<^sub>2 ;; S\<^sub>1)) \<diamondop> (Q\<^sub>2 ;; S\<^sub>2)))" (is "?lhs = ?rhs")
by (simp add: RH_tri_design_composition_wp add: closure assms unrest RR_implies_R2c)
lemma RH_tri_normal_design_composition:
assumes
"$ok\<acute> \<sharp> P" "$ok\<acute> \<sharp> Q\<^sub>1" "$ok\<acute> \<sharp> Q\<^sub>2" "$ok \<sharp> R" "$ok \<sharp> S\<^sub>1" "$ok \<sharp> S\<^sub>2"
"$wait \<sharp> R" "$wait\<acute> \<sharp> Q\<^sub>2" "$wait \<sharp> S\<^sub>1" "$wait \<sharp> S\<^sub>2"
"P is R2c" "Q\<^sub>1 is R1" "Q\<^sub>1 is R2c" "Q\<^sub>2 is R1" "Q\<^sub>2 is R2c"
"R is R2c" "S\<^sub>1 is R1" "S\<^sub>1 is R2c" "S\<^sub>2 is R1" "S\<^sub>2 is R2c"
"R1 (\<not> P) ;; R1(true) = R1(\<not> P)"
shows "\<^bold>R(P \<turnstile> Q\<^sub>1 \<diamondop> Q\<^sub>2) ;; \<^bold>R(R \<turnstile> S\<^sub>1 \<diamondop> S\<^sub>2)
= \<^bold>R((P \<and> Q\<^sub>2 wp\<^sub>r R) \<turnstile> (Q\<^sub>1 \<or> (Q\<^sub>2 ;; S\<^sub>1)) \<diamondop> (Q\<^sub>2 ;; S\<^sub>2))"
proof -
have "\<^bold>R(P \<turnstile> Q\<^sub>1 \<diamondop> Q\<^sub>2) ;; \<^bold>R(R \<turnstile> S\<^sub>1 \<diamondop> S\<^sub>2) =
\<^bold>R((R1 (\<not> P) wp\<^sub>r false \<and> Q\<^sub>2 wp\<^sub>r R) \<turnstile> (Q\<^sub>1 \<sqinter> (Q\<^sub>2 ;; S\<^sub>1)) \<diamondop> (Q\<^sub>2 ;; S\<^sub>2))"
by (simp_all add: RH_tri_design_composition_wp rea_not_def assms unrest)
also have "... = \<^bold>R((P \<and> Q\<^sub>2 wp\<^sub>r R) \<turnstile> (Q\<^sub>1 \<or> (Q\<^sub>2 ;; S\<^sub>1)) \<diamondop> (Q\<^sub>2 ;; S\<^sub>2))"
by (simp add: assms wp_rea_def ex_unrest, rel_auto)
finally show ?thesis .
qed
lemma RH_tri_normal_design_composition' [rdes_def]:
assumes "P is RC" "Q\<^sub>1 is RR" "Q\<^sub>2 is RR" "R is RR" "S\<^sub>1 is RR" "S\<^sub>2 is RR"
shows "\<^bold>R(P \<turnstile> Q\<^sub>1 \<diamondop> Q\<^sub>2) ;; \<^bold>R(R \<turnstile> S\<^sub>1 \<diamondop> S\<^sub>2)
= \<^bold>R((P \<and> Q\<^sub>2 wp\<^sub>r R) \<turnstile> (Q\<^sub>1 \<or> (Q\<^sub>2 ;; S\<^sub>1)) \<diamondop> (Q\<^sub>2 ;; S\<^sub>2))"
proof -
have "R1 (\<not> P) ;; R1 true = R1(\<not> P)"
using RC_implies_RC1[OF assms(1)]
by (simp add: Healthy_def RC1_def rea_not_def)
(metis R1_negate_R1 R1_seqr utp_pred_laws.double_compl)
thus ?thesis
by (simp add: RH_tri_normal_design_composition assms closure unrest RR_implies_R2c)
qed
lemma RH_tri_design_right_unit_lemma:
assumes "$ok\<acute> \<sharp> P" "$ok\<acute> \<sharp> Q" "$ok\<acute> \<sharp> R" "$wait\<acute> \<sharp> R"
shows "\<^bold>R(P \<turnstile> Q \<diamondop> R) ;; II\<^sub>C = \<^bold>R((\<not>\<^sub>r (\<not>\<^sub>r P) ;; true\<^sub>r) \<turnstile> (Q \<diamondop> R))"
proof -
have "\<^bold>R(P \<turnstile> Q \<diamondop> R) ;; II\<^sub>C = \<^bold>R(P \<turnstile> Q \<diamondop> R) ;; \<^bold>R(true \<turnstile> false \<diamondop> ($tr\<acute> =\<^sub>u $tr \<and> \<lceil>II\<rceil>\<^sub>R))"
by (simp add: rdes_skip_tri_design, rel_auto)
also have "... = \<^bold>R ((\<not> R1 (\<not> R2s P) ;; R1 true) \<turnstile> Q \<diamondop> (R1 (R2s R) ;; R1 (R2s ($tr\<acute> =\<^sub>u $tr \<and> \<lceil>II\<rceil>\<^sub>R))))"
by (simp_all add: RH_tri_design_composition assms unrest R2s_true R1_false R2s_false)
also have "... = \<^bold>R ((\<not> R1 (\<not> R2s P) ;; R1 true) \<turnstile> Q \<diamondop> R1 (R2s R))"
proof -
from assms(3,4) have "(R1 (R2s R) ;; R1 (R2s ($tr\<acute> =\<^sub>u $tr \<and> \<lceil>II\<rceil>\<^sub>R))) = R1 (R2s R)"
by (rel_auto, metis (no_types, lifting) minus_zero_eq, meson order_refl trace_class.diff_cancel)
thus ?thesis
by simp
qed
also have "... = \<^bold>R((\<not> (\<not> P) ;; R1 true) \<turnstile> (Q \<diamondop> R))"
by (metis (no_types, lifting) R1_R2s_R1_true_lemma R1_R2s_R2c R2c_not RH_design_R2c_pre RH_design_neg_R1_pre RH_design_post_R1 RH_design_post_R2s)
also have "... = \<^bold>R((\<not>\<^sub>r (\<not>\<^sub>r P) ;; true\<^sub>r) \<turnstile> Q \<diamondop> R)"
by (rel_auto)
finally show ?thesis .
qed
subsubsection \<open> Stateful \<close>
theorem RHS_tri_design_composition:
assumes "$ok\<acute> \<sharp> P" "$ok\<acute> \<sharp> Q\<^sub>1" "$ok\<acute> \<sharp> Q\<^sub>2" "$ok \<sharp> R" "$ok \<sharp> S\<^sub>1" "$ok \<sharp> S\<^sub>2"
"$wait \<sharp> R" "$wait\<acute> \<sharp> Q\<^sub>2" "$wait \<sharp> S\<^sub>1" "$wait \<sharp> S\<^sub>2"
shows "(\<^bold>R\<^sub>s(P \<turnstile> Q\<^sub>1 \<diamondop> Q\<^sub>2) ;; \<^bold>R\<^sub>s(R \<turnstile> S\<^sub>1 \<diamondop> S\<^sub>2)) =
\<^bold>R\<^sub>s((\<not> (R1 (\<not> R2s P) ;; R1 true) \<and> \<not> (R1(R2s Q\<^sub>2) ;; R1 (\<not> R2s R))) \<turnstile>
(((\<exists> $st\<acute> \<bullet> Q\<^sub>1) \<or> (R1 (R2s Q\<^sub>2) ;; R1 (R2s S\<^sub>1))) \<diamondop> ((R1 (R2s Q\<^sub>2) ;; R1 (R2s S\<^sub>2)))))"
proof -
have 1:"(\<not> ((R1 (R2s (Q\<^sub>1 \<diamondop> Q\<^sub>2)) \<and> \<not> $wait\<acute>) ;; R1 (\<not> R2s R))) =
(\<not> ((R1 (R2s Q\<^sub>2) \<and> \<not> $wait\<acute>) ;; R1 (\<not> R2s R)))"
by (metis (no_types, opaque_lifting) R1_extend_conj R2s_conj R2s_not R2s_wait' wait'_cond_false)
have 2: "(R1 (R2s (Q\<^sub>1 \<diamondop> Q\<^sub>2)) ;; ((\<exists> $st \<bullet> \<lceil>II\<rceil>\<^sub>D) \<triangleleft> $wait \<triangleright> R1 (R2s (S\<^sub>1 \<diamondop> S\<^sub>2)))) =
(((\<exists> $st\<acute> \<bullet> R1 (R2s Q\<^sub>1)) \<or> (R1 (R2s Q\<^sub>2) ;; R1 (R2s S\<^sub>1))) \<diamondop> (R1 (R2s Q\<^sub>2) ;; R1 (R2s S\<^sub>2)))"
proof -
have "(R1 (R2s Q\<^sub>1) ;; ($wait \<and> ((\<exists> $st \<bullet> \<lceil>II\<rceil>\<^sub>D) \<triangleleft> $wait \<triangleright> R1 (R2s S\<^sub>1) \<diamondop> R1 (R2s S\<^sub>2))))
= (\<exists> $st\<acute> \<bullet> ((R1 (R2s Q\<^sub>1)) \<and> $wait\<acute>))"
proof -
have "(R1 (R2s Q\<^sub>1) ;; ($wait \<and> ((\<exists> $st \<bullet> \<lceil>II\<rceil>\<^sub>D) \<triangleleft> $wait \<triangleright> R1 (R2s S\<^sub>1) \<diamondop> R1 (R2s S\<^sub>2))))
= (R1 (R2s Q\<^sub>1) ;; ($wait \<and> (\<exists> $st \<bullet> \<lceil>II\<rceil>\<^sub>D)))"
by (rel_auto, blast+)
also have "... = ((R1 (R2s Q\<^sub>1) ;; (\<exists> $st \<bullet> \<lceil>II\<rceil>\<^sub>D)) \<and> $wait\<acute>)"
by (rel_auto)
also from assms(2) have "... = (\<exists> $st\<acute> \<bullet> ((R1 (R2s Q\<^sub>1)) \<and> $wait\<acute>))"
by (rel_auto, blast)
finally show ?thesis .
qed
moreover have "(R1 (R2s Q\<^sub>2) ;; (\<not> $wait \<and> ((\<exists> $st \<bullet> \<lceil>II\<rceil>\<^sub>D) \<triangleleft> $wait \<triangleright> R1 (R2s S\<^sub>1) \<diamondop> R1 (R2s S\<^sub>2))))
= ((R1 (R2s Q\<^sub>2)) ;; (R1 (R2s S\<^sub>1) \<diamondop> R1 (R2s S\<^sub>2)))"
proof -
have "(R1 (R2s Q\<^sub>2) ;; (\<not> $wait \<and> ((\<exists> $st \<bullet> \<lceil>II\<rceil>\<^sub>D) \<triangleleft> $wait \<triangleright> R1 (R2s S\<^sub>1) \<diamondop> R1 (R2s S\<^sub>2))))
= (R1 (R2s Q\<^sub>2) ;; (\<not> $wait \<and> (R1 (R2s S\<^sub>1) \<diamondop> R1 (R2s S\<^sub>2))))"
by (metis (no_types, lifting) cond_def conj_disj_not_abs utp_pred_laws.double_compl utp_pred_laws.inf.left_idem utp_pred_laws.sup_assoc utp_pred_laws.sup_inf_absorb)
also have "... = ((R1 (R2s Q\<^sub>2))\<lbrakk>false/$wait\<acute>\<rbrakk> ;; (R1 (R2s S\<^sub>1) \<diamondop> R1 (R2s S\<^sub>2))\<lbrakk>false/$wait\<rbrakk>)"
by (metis false_alt_def seqr_right_one_point upred_eq_false wait_vwb_lens)
also have "... = ((R1 (R2s Q\<^sub>2)) ;; (R1 (R2s S\<^sub>1) \<diamondop> R1 (R2s S\<^sub>2)))"
by (simp add: wait'_cond_def usubst unrest assms)
finally show ?thesis .
qed
moreover
have "((R1 (R2s Q\<^sub>1) \<and> $wait\<acute>) \<or> ((R1 (R2s Q\<^sub>2)) ;; (R1 (R2s S\<^sub>1) \<diamondop> R1 (R2s S\<^sub>2))))
= (R1 (R2s Q\<^sub>1) \<or> (R1 (R2s Q\<^sub>2) ;; R1 (R2s S\<^sub>1))) \<diamondop> ((R1 (R2s Q\<^sub>2) ;; R1 (R2s S\<^sub>2)))"
by (simp add: wait'_cond_def cond_seq_right_distr cond_and_T_integrate unrest)
ultimately show ?thesis
by (simp add: R2s_wait'_cond R1_wait'_cond wait'_cond_seq ex_conj_contr_right unrest)
(simp add: cond_and_T_integrate cond_seq_right_distr unrest_var wait'_cond_def)
qed
from assms(7,8) have 3: "(R1 (R2s Q\<^sub>2) \<and> \<not> $wait\<acute>) ;; R1 (\<not> R2s R) = R1 (R2s Q\<^sub>2) ;; R1 (\<not> R2s R)"
by (rel_auto, blast, meson)
show ?thesis
apply (subst RHS_design_composition)
apply (simp_all add: assms)
apply (simp add: assms wait'_cond_def unrest)
apply (simp add: assms wait'_cond_def unrest)
apply (simp add: 1 2 3)
apply (simp add: R1_R2s_R2c RHS_design_lemma1)
apply (metis R1_R2c_ex_st RHS_design_lemma1)
done
qed
theorem RHS_tri_design_composition_wp:
assumes "$ok\<acute> \<sharp> P" "$ok\<acute> \<sharp> Q\<^sub>1" "$ok\<acute> \<sharp> Q\<^sub>2" "$ok \<sharp> R" "$ok \<sharp> S\<^sub>1" "$ok \<sharp> S\<^sub>2"
"$wait \<sharp> R" "$wait\<acute> \<sharp> Q\<^sub>2" "$wait \<sharp> S\<^sub>1" "$wait \<sharp> S\<^sub>2"
"P is R2c" "Q\<^sub>1 is R1" "Q\<^sub>1 is R2c" "Q\<^sub>2 is R1" "Q\<^sub>2 is R2c"
"R is R2c" "S\<^sub>1 is R1" "S\<^sub>1 is R2c" "S\<^sub>2 is R1" "S\<^sub>2 is R2c"
shows "\<^bold>R\<^sub>s(P \<turnstile> Q\<^sub>1 \<diamondop> Q\<^sub>2) ;; \<^bold>R\<^sub>s(R \<turnstile> S\<^sub>1 \<diamondop> S\<^sub>2) =
\<^bold>R\<^sub>s(((\<not>\<^sub>r P) wp\<^sub>r false \<and> Q\<^sub>2 wp\<^sub>r R) \<turnstile> (((\<exists> $st\<acute> \<bullet> Q\<^sub>1) \<sqinter> (Q\<^sub>2 ;; S\<^sub>1)) \<diamondop> (Q\<^sub>2 ;; S\<^sub>2)))" (is "?lhs = ?rhs")
proof -
have "?lhs = \<^bold>R\<^sub>s ((\<not> R1 (\<not> P) ;; R1 true \<and> \<not> Q\<^sub>2 ;; R1 (\<not> R)) \<turnstile> ((\<exists> $st\<acute> \<bullet> Q\<^sub>1) \<sqinter> (Q\<^sub>2 ;; S\<^sub>1)) \<diamondop> (Q\<^sub>2 ;; S\<^sub>2))"
by (simp add: RHS_tri_design_composition assms Healthy_if R2c_healthy_R2s disj_upred_def)
(metis (no_types, opaque_lifting) R1_negate_R1 R2c_healthy_R2s assms(11,16))
also have "... = ?rhs"
by (rel_auto)
finally show ?thesis .
qed
theorem RHS_tri_design_composition_RR_wp:
assumes "P is RR" "Q\<^sub>1 is RR" "Q\<^sub>2 is RR"
"R is RR" "S\<^sub>1 is RR" "S\<^sub>2 is RR"
shows "\<^bold>R\<^sub>s(P \<turnstile> Q\<^sub>1 \<diamondop> Q\<^sub>2) ;; \<^bold>R\<^sub>s(R \<turnstile> S\<^sub>1 \<diamondop> S\<^sub>2) =
\<^bold>R\<^sub>s(((\<not>\<^sub>r P) wp\<^sub>r false \<and> Q\<^sub>2 wp\<^sub>r R) \<turnstile> (((\<exists> $st\<acute> \<bullet> Q\<^sub>1) \<sqinter> (Q\<^sub>2 ;; S\<^sub>1)) \<diamondop> (Q\<^sub>2 ;; S\<^sub>2)))" (is "?lhs = ?rhs")
by (simp add: RHS_tri_design_composition_wp add: closure assms unrest RR_implies_R2c)
lemma RHS_tri_normal_design_composition:
assumes
"$ok\<acute> \<sharp> P" "$ok\<acute> \<sharp> Q\<^sub>1" "$ok\<acute> \<sharp> Q\<^sub>2" "$ok \<sharp> R" "$ok \<sharp> S\<^sub>1" "$ok \<sharp> S\<^sub>2"
"$wait \<sharp> R" "$wait\<acute> \<sharp> Q\<^sub>2" "$wait \<sharp> S\<^sub>1" "$wait \<sharp> S\<^sub>2"
"P is R2c" "Q\<^sub>1 is R1" "Q\<^sub>1 is R2c" "Q\<^sub>2 is R1" "Q\<^sub>2 is R2c"
"R is R2c" "S\<^sub>1 is R1" "S\<^sub>1 is R2c" "S\<^sub>2 is R1" "S\<^sub>2 is R2c"
"R1 (\<not> P) ;; R1(true) = R1(\<not> P)" "$st\<acute> \<sharp> Q\<^sub>1"
shows "\<^bold>R\<^sub>s(P \<turnstile> Q\<^sub>1 \<diamondop> Q\<^sub>2) ;; \<^bold>R\<^sub>s(R \<turnstile> S\<^sub>1 \<diamondop> S\<^sub>2)
= \<^bold>R\<^sub>s((P \<and> Q\<^sub>2 wp\<^sub>r R) \<turnstile> (Q\<^sub>1 \<or> (Q\<^sub>2 ;; S\<^sub>1)) \<diamondop> (Q\<^sub>2 ;; S\<^sub>2))"
proof -
have "\<^bold>R\<^sub>s(P \<turnstile> Q\<^sub>1 \<diamondop> Q\<^sub>2) ;; \<^bold>R\<^sub>s(R \<turnstile> S\<^sub>1 \<diamondop> S\<^sub>2) =
\<^bold>R\<^sub>s ((R1 (\<not> P) wp\<^sub>r false \<and> Q\<^sub>2 wp\<^sub>r R) \<turnstile> ((\<exists> $st\<acute> \<bullet> Q\<^sub>1) \<sqinter> (Q\<^sub>2 ;; S\<^sub>1)) \<diamondop> (Q\<^sub>2 ;; S\<^sub>2))"
by (simp_all add: RHS_tri_design_composition_wp rea_not_def assms unrest)
also have "... = \<^bold>R\<^sub>s((P \<and> Q\<^sub>2 wp\<^sub>r R) \<turnstile> (Q\<^sub>1 \<or> (Q\<^sub>2 ;; S\<^sub>1)) \<diamondop> (Q\<^sub>2 ;; S\<^sub>2))"
by (simp add: assms wp_rea_def ex_unrest, rel_auto)
finally show ?thesis .
qed
lemma RHS_tri_normal_design_composition' [rdes_def]:
assumes "P is RC" "Q\<^sub>1 is RR" "$st\<acute> \<sharp> Q\<^sub>1" "Q\<^sub>2 is RR" "R is RR" "S\<^sub>1 is RR" "S\<^sub>2 is RR"
shows "\<^bold>R\<^sub>s(P \<turnstile> Q\<^sub>1 \<diamondop> Q\<^sub>2) ;; \<^bold>R\<^sub>s(R \<turnstile> S\<^sub>1 \<diamondop> S\<^sub>2)
= \<^bold>R\<^sub>s((P \<and> Q\<^sub>2 wp\<^sub>r R) \<turnstile> (Q\<^sub>1 \<or> (Q\<^sub>2 ;; S\<^sub>1)) \<diamondop> (Q\<^sub>2 ;; S\<^sub>2))"
proof -
have "R1 (\<not> P) ;; R1 true = R1(\<not> P)"
using RC_implies_RC1[OF assms(1)]
by (simp add: Healthy_def RC1_def rea_not_def)
(metis R1_negate_R1 R1_seqr utp_pred_laws.double_compl)
thus ?thesis
by (simp add: RHS_tri_normal_design_composition assms closure unrest RR_implies_R2c)
qed
lemma RHS_tri_design_right_unit_lemma:
assumes "$ok\<acute> \<sharp> P" "$ok\<acute> \<sharp> Q" "$ok\<acute> \<sharp> R" "$wait\<acute> \<sharp> R"
shows "\<^bold>R\<^sub>s(P \<turnstile> Q \<diamondop> R) ;; II\<^sub>R = \<^bold>R\<^sub>s((\<not>\<^sub>r (\<not>\<^sub>r P) ;; true\<^sub>r) \<turnstile> ((\<exists> $st\<acute> \<bullet> Q) \<diamondop> R))"
proof -
have "\<^bold>R\<^sub>s(P \<turnstile> Q \<diamondop> R) ;; II\<^sub>R = \<^bold>R\<^sub>s(P \<turnstile> Q \<diamondop> R) ;; \<^bold>R\<^sub>s(true \<turnstile> false \<diamondop> ($tr\<acute> =\<^sub>u $tr \<and> \<lceil>II\<rceil>\<^sub>R))"
by (simp add: srdes_skip_tri_design, rel_auto)
also have "... = \<^bold>R\<^sub>s ((\<not> R1 (\<not> R2s P) ;; R1 true) \<turnstile> (\<exists> $st\<acute> \<bullet> Q) \<diamondop> (R1 (R2s R) ;; R1 (R2s ($tr\<acute> =\<^sub>u $tr \<and> \<lceil>II\<rceil>\<^sub>R))))"
by (simp_all add: RHS_tri_design_composition assms unrest R2s_true R1_false R2s_false)
also have "... = \<^bold>R\<^sub>s ((\<not> R1 (\<not> R2s P) ;; R1 true) \<turnstile> (\<exists> $st\<acute> \<bullet> Q) \<diamondop> R1 (R2s R))"
proof -
from assms(3,4) have "(R1 (R2s R) ;; R1 (R2s ($tr\<acute> =\<^sub>u $tr \<and> \<lceil>II\<rceil>\<^sub>R))) = R1 (R2s R)"
by (rel_auto, metis (no_types, lifting) minus_zero_eq, meson order_refl trace_class.diff_cancel)
thus ?thesis
by simp
qed
also have "... = \<^bold>R\<^sub>s((\<not> (\<not> P) ;; R1 true) \<turnstile> ((\<exists> $st\<acute> \<bullet> Q) \<diamondop> R))"
by (metis (no_types, lifting) R1_R2s_R1_true_lemma R1_R2s_R2c R2c_not RHS_design_R2c_pre RHS_design_neg_R1_pre RHS_design_post_R1 RHS_design_post_R2s)
also have "... = \<^bold>R\<^sub>s((\<not>\<^sub>r (\<not>\<^sub>r P) ;; true\<^sub>r) \<turnstile> ((\<exists> $st\<acute> \<bullet> Q) \<diamondop> R))"
by (rel_auto)
finally show ?thesis .
qed
lemma RD_composition_wp:
assumes "P is RD" "Q is RD"
shows "(P ;; Q) = \<^bold>R (((\<not>\<^sub>r pre\<^sub>R P) wp\<^sub>r false \<and> post\<^sub>R P wp\<^sub>r pre\<^sub>R Q) \<turnstile>
(peri\<^sub>R P \<or> (post\<^sub>R P ;; peri\<^sub>R Q)) \<diamondop> (post\<^sub>R P ;; post\<^sub>R Q))"
(is "?lhs = ?rhs")
proof -
have "(P ;; Q) = (\<^bold>R(pre\<^sub>R(P) \<turnstile> peri\<^sub>R(P) \<diamondop> post\<^sub>R(P)) ;; \<^bold>R(pre\<^sub>R(Q) \<turnstile> peri\<^sub>R(Q) \<diamondop> post\<^sub>R(Q)))"
by (simp add: RD_reactive_tri_design assms(1) assms(2))
also from assms
have "... = ?rhs"
by (simp add: RH_tri_design_composition_wp unrest closure disj_upred_def)
finally show ?thesis .
qed
lemma SRD_composition_wp:
assumes "P is SRD" "Q is SRD"
shows "(P ;; Q) = \<^bold>R\<^sub>s (((\<not>\<^sub>r pre\<^sub>R P) wp\<^sub>r false \<and> post\<^sub>R P wp\<^sub>r pre\<^sub>R Q) \<turnstile>
((\<exists> $st\<acute> \<bullet> peri\<^sub>R P) \<or> (post\<^sub>R P ;; peri\<^sub>R Q)) \<diamondop> (post\<^sub>R P ;; post\<^sub>R Q))"
(is "?lhs = ?rhs")
proof -
have "(P ;; Q) = (\<^bold>R\<^sub>s(pre\<^sub>R(P) \<turnstile> peri\<^sub>R(P) \<diamondop> post\<^sub>R(P)) ;; \<^bold>R\<^sub>s(pre\<^sub>R(Q) \<turnstile> peri\<^sub>R(Q) \<diamondop> post\<^sub>R(Q)))"
by (simp add: SRD_reactive_tri_design assms(1) assms(2))
also from assms
have "... = ?rhs"
by (simp add: RHS_tri_design_composition_wp disj_upred_def unrest assms closure)
finally show ?thesis .
qed
subsection \<open> Refinement introduction laws \<close>
subsubsection \<open> Regular \<close>
lemma RH_tri_design_refine:
assumes "P\<^sub>1 is RR" "P\<^sub>2 is RR" "P\<^sub>3 is RR" "Q\<^sub>1 is RR" "Q\<^sub>2 is RR" "Q\<^sub>3 is RR"
shows "\<^bold>R(P\<^sub>1 \<turnstile> P\<^sub>2 \<diamondop> P\<^sub>3) \<sqsubseteq> \<^bold>R(Q\<^sub>1 \<turnstile> Q\<^sub>2 \<diamondop> Q\<^sub>3) \<longleftrightarrow> `P\<^sub>1 \<Rightarrow> Q\<^sub>1` \<and> `P\<^sub>1 \<and> Q\<^sub>2 \<Rightarrow> P\<^sub>2` \<and> `P\<^sub>1 \<and> Q\<^sub>3 \<Rightarrow> P\<^sub>3`"
(is "?lhs = ?rhs")
proof -
have "?lhs \<longleftrightarrow> `P\<^sub>1 \<Rightarrow> Q\<^sub>1` \<and> `P\<^sub>1 \<and> Q\<^sub>2 \<diamondop> Q\<^sub>3 \<Rightarrow> P\<^sub>2 \<diamondop> P\<^sub>3`"
by (simp add: RH_design_refine assms closure RR_implies_R2c unrest ex_unrest)
also have "... \<longleftrightarrow> `P\<^sub>1 \<Rightarrow> Q\<^sub>1` \<and> `(P\<^sub>1 \<and> Q\<^sub>2) \<diamondop> (P\<^sub>1 \<and> Q\<^sub>3) \<Rightarrow> P\<^sub>2 \<diamondop> P\<^sub>3`"
by (rel_auto)
also have "... \<longleftrightarrow> `P\<^sub>1 \<Rightarrow> Q\<^sub>1` \<and> `((P\<^sub>1 \<and> Q\<^sub>2) \<diamondop> (P\<^sub>1 \<and> Q\<^sub>3) \<Rightarrow> P\<^sub>2 \<diamondop> P\<^sub>3)\<lbrakk>true/$wait\<acute>\<rbrakk>` \<and> `((P\<^sub>1 \<and> Q\<^sub>2) \<diamondop> (P\<^sub>1 \<and> Q\<^sub>3) \<Rightarrow> P\<^sub>2 \<diamondop> P\<^sub>3)\<lbrakk>false/$wait\<acute>\<rbrakk>`"
by (rel_auto, metis)
also have "... \<longleftrightarrow> ?rhs"
by (simp add: usubst unrest assms)
finally show ?thesis .
qed
lemma RH_tri_design_refine':
assumes "P\<^sub>1 is RR" "P\<^sub>2 is RR" "P\<^sub>3 is RR" "Q\<^sub>1 is RR" "Q\<^sub>2 is RR" "Q\<^sub>3 is RR"
shows "\<^bold>R(P\<^sub>1 \<turnstile> P\<^sub>2 \<diamondop> P\<^sub>3) \<sqsubseteq> \<^bold>R(Q\<^sub>1 \<turnstile> Q\<^sub>2 \<diamondop> Q\<^sub>3) \<longleftrightarrow> (Q\<^sub>1 \<sqsubseteq> P\<^sub>1) \<and> (P\<^sub>2 \<sqsubseteq> (P\<^sub>1 \<and> Q\<^sub>2)) \<and> (P\<^sub>3 \<sqsubseteq> (P\<^sub>1 \<and> Q\<^sub>3))"
by (simp add: RH_tri_design_refine assms, rel_auto)
lemma rdes_tri_refine_intro:
assumes "`P\<^sub>1 \<Rightarrow> P\<^sub>2`" "`P\<^sub>1 \<and> Q\<^sub>2 \<Rightarrow> Q\<^sub>1`" "`P\<^sub>1 \<and> R\<^sub>2 \<Rightarrow> R\<^sub>1`"
shows "\<^bold>R(P\<^sub>1 \<turnstile> Q\<^sub>1 \<diamondop> R\<^sub>1) \<sqsubseteq> \<^bold>R(P\<^sub>2 \<turnstile> Q\<^sub>2 \<diamondop> R\<^sub>2)"
using assms
by (rule_tac rdes_refine_intro, simp_all, rel_auto)
lemma rdes_tri_refine_intro':
assumes "P\<^sub>2 \<sqsubseteq> P\<^sub>1" "Q\<^sub>1 \<sqsubseteq> (P\<^sub>1 \<and> Q\<^sub>2)" "R\<^sub>1 \<sqsubseteq> (P\<^sub>1 \<and> R\<^sub>2)"
shows "\<^bold>R(P\<^sub>1 \<turnstile> Q\<^sub>1 \<diamondop> R\<^sub>1) \<sqsubseteq> \<^bold>R(P\<^sub>2 \<turnstile> Q\<^sub>2 \<diamondop> R\<^sub>2)"
using assms
by (rule_tac rdes_tri_refine_intro, simp_all add: refBy_order)
subsubsection \<open> Stateful \<close>
lemma RHS_tri_design_refine:
assumes "P\<^sub>1 is RR" "P\<^sub>2 is RR" "P\<^sub>3 is RR" "Q\<^sub>1 is RR" "Q\<^sub>2 is RR" "Q\<^sub>3 is RR"
shows "\<^bold>R\<^sub>s(P\<^sub>1 \<turnstile> P\<^sub>2 \<diamondop> P\<^sub>3) \<sqsubseteq> \<^bold>R\<^sub>s(Q\<^sub>1 \<turnstile> Q\<^sub>2 \<diamondop> Q\<^sub>3) \<longleftrightarrow> `P\<^sub>1 \<Rightarrow> Q\<^sub>1` \<and> `P\<^sub>1 \<and> Q\<^sub>2 \<Rightarrow> P\<^sub>2` \<and> `P\<^sub>1 \<and> Q\<^sub>3 \<Rightarrow> P\<^sub>3`"
(is "?lhs = ?rhs")
proof -
have "?lhs \<longleftrightarrow> `P\<^sub>1 \<Rightarrow> Q\<^sub>1` \<and> `P\<^sub>1 \<and> Q\<^sub>2 \<diamondop> Q\<^sub>3 \<Rightarrow> P\<^sub>2 \<diamondop> P\<^sub>3`"
by (simp add: RHS_design_refine assms closure RR_implies_R2c unrest ex_unrest)
also have "... \<longleftrightarrow> `P\<^sub>1 \<Rightarrow> Q\<^sub>1` \<and> `(P\<^sub>1 \<and> Q\<^sub>2) \<diamondop> (P\<^sub>1 \<and> Q\<^sub>3) \<Rightarrow> P\<^sub>2 \<diamondop> P\<^sub>3`"
by (rel_auto)
also have "... \<longleftrightarrow> `P\<^sub>1 \<Rightarrow> Q\<^sub>1` \<and> `((P\<^sub>1 \<and> Q\<^sub>2) \<diamondop> (P\<^sub>1 \<and> Q\<^sub>3) \<Rightarrow> P\<^sub>2 \<diamondop> P\<^sub>3)\<lbrakk>true/$wait\<acute>\<rbrakk>` \<and> `((P\<^sub>1 \<and> Q\<^sub>2) \<diamondop> (P\<^sub>1 \<and> Q\<^sub>3) \<Rightarrow> P\<^sub>2 \<diamondop> P\<^sub>3)\<lbrakk>false/$wait\<acute>\<rbrakk>`"
by (rel_auto, metis)
also have "... \<longleftrightarrow> ?rhs"
by (simp add: usubst unrest assms)
finally show ?thesis .
qed
lemma RHS_tri_design_refine':
assumes "P\<^sub>1 is RR" "P\<^sub>2 is RR" "P\<^sub>3 is RR" "Q\<^sub>1 is RR" "Q\<^sub>2 is RR" "Q\<^sub>3 is RR"
shows "\<^bold>R\<^sub>s(P\<^sub>1 \<turnstile> P\<^sub>2 \<diamondop> P\<^sub>3) \<sqsubseteq> \<^bold>R\<^sub>s(Q\<^sub>1 \<turnstile> Q\<^sub>2 \<diamondop> Q\<^sub>3) \<longleftrightarrow> (Q\<^sub>1 \<sqsubseteq> P\<^sub>1) \<and> (P\<^sub>2 \<sqsubseteq> (P\<^sub>1 \<and> Q\<^sub>2)) \<and> (P\<^sub>3 \<sqsubseteq> (P\<^sub>1 \<and> Q\<^sub>3))"
by (simp add: RHS_tri_design_refine assms, rel_auto)
lemma srdes_tri_refine_intro:
assumes "`P\<^sub>1 \<Rightarrow> P\<^sub>2`" "`P\<^sub>1 \<and> Q\<^sub>2 \<Rightarrow> Q\<^sub>1`" "`P\<^sub>1 \<and> R\<^sub>2 \<Rightarrow> R\<^sub>1`"
shows "\<^bold>R\<^sub>s(P\<^sub>1 \<turnstile> Q\<^sub>1 \<diamondop> R\<^sub>1) \<sqsubseteq> \<^bold>R\<^sub>s(P\<^sub>2 \<turnstile> Q\<^sub>2 \<diamondop> R\<^sub>2)"
using assms
by (rule_tac srdes_refine_intro, simp_all, rel_auto)
lemma srdes_tri_refine_intro':
assumes "P\<^sub>2 \<sqsubseteq> P\<^sub>1" "Q\<^sub>1 \<sqsubseteq> (P\<^sub>1 \<and> Q\<^sub>2)" "R\<^sub>1 \<sqsubseteq> (P\<^sub>1 \<and> R\<^sub>2)"
shows "\<^bold>R\<^sub>s(P\<^sub>1 \<turnstile> Q\<^sub>1 \<diamondop> R\<^sub>1) \<sqsubseteq> \<^bold>R\<^sub>s(P\<^sub>2 \<turnstile> Q\<^sub>2 \<diamondop> R\<^sub>2)"
using assms
by (rule_tac srdes_tri_refine_intro, simp_all add: refBy_order)
lemma SRD_peri_under_pre:
assumes "P is SRD" "$wait\<acute> \<sharp> pre\<^sub>R(P)"
shows "(pre\<^sub>R(P) \<Rightarrow>\<^sub>r peri\<^sub>R(P)) = peri\<^sub>R(P)"
proof -
have "peri\<^sub>R(P) =
peri\<^sub>R(\<^bold>R\<^sub>s(pre\<^sub>R(P) \<turnstile> peri\<^sub>R(P) \<diamondop> post\<^sub>R(P)))"
by (simp add: SRD_reactive_tri_design assms)
also have "... = (pre\<^sub>R P \<Rightarrow>\<^sub>r peri\<^sub>R P)"
by (simp add: rea_pre_RHS_design rea_peri_RHS_design assms
unrest usubst R1_peri_SRD R2c_preR R1_rea_impl R2c_rea_impl R2c_periR)
finally show ?thesis ..
qed
lemma SRD_post_under_pre:
assumes "P is SRD" "$wait\<acute> \<sharp> pre\<^sub>R(P)"
shows "(pre\<^sub>R(P) \<Rightarrow>\<^sub>r post\<^sub>R(P)) = post\<^sub>R(P)"
proof -
have "post\<^sub>R(P) =
post\<^sub>R(\<^bold>R\<^sub>s(pre\<^sub>R(P) \<turnstile> peri\<^sub>R(P) \<diamondop> post\<^sub>R(P)))"
by (simp add: SRD_reactive_tri_design assms)
also have "... = (pre\<^sub>R P \<Rightarrow>\<^sub>r post\<^sub>R P)"
by (simp add: rea_pre_RHS_design rea_post_RHS_design assms
unrest usubst R1_post_SRD R2c_preR R1_rea_impl R2c_rea_impl R2c_postR)
finally show ?thesis ..
qed
lemma SRD_refine_intro:
assumes
"P is SRD" "Q is SRD"
"`pre\<^sub>R(P) \<Rightarrow> pre\<^sub>R(Q)`" "`pre\<^sub>R(P) \<and> peri\<^sub>R(Q) \<Rightarrow> peri\<^sub>R(P)`" "`pre\<^sub>R(P) \<and> post\<^sub>R(Q) \<Rightarrow> post\<^sub>R(P)`"
shows "P \<sqsubseteq> Q"
by (metis SRD_reactive_tri_design assms(1) assms(2) assms(3) assms(4) assms(5) srdes_tri_refine_intro)
lemma SRD_refine_intro':
assumes
"P is SRD" "Q is SRD"
"`pre\<^sub>R(P) \<Rightarrow> pre\<^sub>R(Q)`" "peri\<^sub>R(P) \<sqsubseteq> (pre\<^sub>R(P) \<and> peri\<^sub>R(Q))" "post\<^sub>R(P) \<sqsubseteq> (pre\<^sub>R(P) \<and> post\<^sub>R(Q))"
shows "P \<sqsubseteq> Q"
using assms by (rule_tac SRD_refine_intro, simp_all add: refBy_order)
lemma SRD_eq_intro:
assumes
"P is SRD" "Q is SRD" "pre\<^sub>R(P) = pre\<^sub>R(Q)" "peri\<^sub>R(P) = peri\<^sub>R(Q)" "post\<^sub>R(P) = post\<^sub>R(Q)"
shows "P = Q"
by (metis SRD_reactive_tri_design assms)
lemma srdes_tri_eq_iff:
assumes "P\<^sub>1 is RR" "P\<^sub>2 is RR" "P\<^sub>3 is RR" "Q\<^sub>1 is RR" "Q\<^sub>2 is RR" "Q\<^sub>3 is RR"
shows "\<^bold>R\<^sub>s(P\<^sub>1 \<turnstile> P\<^sub>2 \<diamondop> P\<^sub>3) = \<^bold>R\<^sub>s(Q\<^sub>1 \<turnstile> Q\<^sub>2 \<diamondop> Q\<^sub>3) \<longleftrightarrow> (P\<^sub>1 = Q\<^sub>1 \<and> (P\<^sub>1 \<and> Q\<^sub>2) = (Q\<^sub>1 \<and> P\<^sub>2) \<and> (P\<^sub>1 \<and> Q\<^sub>3) = (Q\<^sub>1 \<and> P\<^sub>3))"
proof -
have "\<^bold>R\<^sub>s(P\<^sub>1 \<turnstile> P\<^sub>2 \<diamondop> P\<^sub>3) = \<^bold>R\<^sub>s(Q\<^sub>1 \<turnstile> Q\<^sub>2 \<diamondop> Q\<^sub>3) \<longleftrightarrow>
(\<^bold>R\<^sub>s(P\<^sub>1 \<turnstile> P\<^sub>2 \<diamondop> P\<^sub>3) \<sqsubseteq> \<^bold>R\<^sub>s(Q\<^sub>1 \<turnstile> Q\<^sub>2 \<diamondop> Q\<^sub>3) \<and> \<^bold>R\<^sub>s(Q\<^sub>1 \<turnstile> Q\<^sub>2 \<diamondop> Q\<^sub>3) \<sqsubseteq> \<^bold>R\<^sub>s(P\<^sub>1 \<turnstile> P\<^sub>2 \<diamondop> P\<^sub>3))"
by fastforce
also have "... = (Q\<^sub>1 \<sqsubseteq> P\<^sub>1 \<and> P\<^sub>2 \<sqsubseteq> (P\<^sub>1 \<and> Q\<^sub>2) \<and> P\<^sub>3 \<sqsubseteq> (P\<^sub>1 \<and> Q\<^sub>3) \<and> P\<^sub>1 \<sqsubseteq> Q\<^sub>1 \<and> Q\<^sub>2 \<sqsubseteq> (Q\<^sub>1 \<and> P\<^sub>2) \<and> Q\<^sub>3 \<sqsubseteq> (Q\<^sub>1 \<and> P\<^sub>3))"
by (simp add: RHS_tri_design_refine' assms)
also have "... = (P\<^sub>1 = Q\<^sub>1 \<and> P\<^sub>2 \<sqsubseteq> (P\<^sub>1 \<and> Q\<^sub>2) \<and> P\<^sub>3 \<sqsubseteq> (P\<^sub>1 \<and> Q\<^sub>3) \<and> Q\<^sub>2 \<sqsubseteq> (Q\<^sub>1 \<and> P\<^sub>2) \<and> Q\<^sub>3 \<sqsubseteq> (Q\<^sub>1 \<and> P\<^sub>3))"
by fastforce
also have "... = (P\<^sub>1 = Q\<^sub>1 \<and> (P\<^sub>1 \<and> Q\<^sub>2) = (Q\<^sub>1 \<and> P\<^sub>2) \<and> (P\<^sub>1 \<and> Q\<^sub>3) = (Q\<^sub>1 \<and> P\<^sub>3))"
apply (safe, simp_all)
apply (meson eq_iff utp_pred_laws.inf_greatest utp_pred_laws.inf_le1)+
apply (metis utp_pred_laws.inf_le2)+
done
finally show ?thesis .
qed
lemma rdes_tri_eq_intro:
assumes "P\<^sub>1 = Q\<^sub>1" "(P\<^sub>1 \<and> Q\<^sub>2) = (Q\<^sub>1 \<and> P\<^sub>2)" "(P\<^sub>1 \<and> Q\<^sub>3) = (Q\<^sub>1 \<and> P\<^sub>3)"
shows "\<^bold>R(P\<^sub>1 \<turnstile> P\<^sub>2 \<diamondop> P\<^sub>3) = \<^bold>R(Q\<^sub>1 \<turnstile> Q\<^sub>2 \<diamondop> Q\<^sub>3)"
by (metis (no_types, opaque_lifting) assms(1) assms(2) assms(3) design_export_pre wait'_cond_conj_exchange wait'_cond_idem)
lemma srdes_tri_eq_intro:
assumes "P\<^sub>1 = Q\<^sub>1" "(P\<^sub>1 \<and> Q\<^sub>2) = (Q\<^sub>1 \<and> P\<^sub>2)" "(P\<^sub>1 \<and> Q\<^sub>3) = (Q\<^sub>1 \<and> P\<^sub>3)"
shows "\<^bold>R\<^sub>s(P\<^sub>1 \<turnstile> P\<^sub>2 \<diamondop> P\<^sub>3) = \<^bold>R\<^sub>s(Q\<^sub>1 \<turnstile> Q\<^sub>2 \<diamondop> Q\<^sub>3)"
by (metis (no_types, opaque_lifting) assms(1) assms(2) assms(3) design_export_pre wait'_cond_conj_exchange wait'_cond_idem)
lemma rdes_tri_eq_intro':
assumes "P\<^sub>1 = Q\<^sub>1" "P\<^sub>2 = Q\<^sub>2" "P\<^sub>3 = Q\<^sub>3"
shows "\<^bold>R(P\<^sub>1 \<turnstile> P\<^sub>2 \<diamondop> P\<^sub>3) = \<^bold>R(Q\<^sub>1 \<turnstile> Q\<^sub>2 \<diamondop> Q\<^sub>3)"
using assms by (simp)
lemma srdes_tri_eq_intro':
assumes "P\<^sub>1 = Q\<^sub>1" "P\<^sub>2 = Q\<^sub>2" "P\<^sub>3 = Q\<^sub>3"
shows "\<^bold>R\<^sub>s(P\<^sub>1 \<turnstile> P\<^sub>2 \<diamondop> P\<^sub>3) = \<^bold>R\<^sub>s(Q\<^sub>1 \<turnstile> Q\<^sub>2 \<diamondop> Q\<^sub>3)"
using assms by (simp)
subsection \<open> Closure laws \<close>
subsubsection \<open> Regular \<close>
lemma RD_srdes_skip [closure]: "II\<^sub>C is RD"
by (simp add: rdes_skip_def RH_design_is_RD unrest)
lemma RD_seqr_closure [closure]:
assumes "P is RD" "Q is RD"
shows "(P ;; Q) is RD"
proof -
have "(P ;; Q) = \<^bold>R (((\<not>\<^sub>r pre\<^sub>R P) wp\<^sub>r false \<and> post\<^sub>R P wp\<^sub>r pre\<^sub>R Q) \<turnstile>
(peri\<^sub>R P \<or> (post\<^sub>R P ;; peri\<^sub>R Q)) \<diamondop> (post\<^sub>R P ;; post\<^sub>R Q))"
by (simp add: RD_composition_wp assms(1) assms(2))
also have "... is RD"
by (rule RH_design_is_RD, simp_all add: wp_rea_def unrest)
finally show ?thesis .
qed
lemma RD_power_Suc [closure]: "P is RD \<Longrightarrow> P\<^bold>^(Suc n) is RD"
proof (induct n)
case 0
then show ?case
by (simp)
next
case (Suc n)
then show ?case
using RD_seqr_closure by (simp add: RD_seqr_closure upred_semiring.power_Suc)
qed
lemma RD_power_comp [closure]: "P is RD \<Longrightarrow> P ;; P\<^bold>^n is RD"
by (metis RD_power_Suc upred_semiring.power_Suc)
lemma uplus_RD_closed [closure]: "P is RD \<Longrightarrow> P\<^sup>+ is RD"
by (simp add: uplus_power_def closure)
subsubsection \<open> Stateful \<close>
lemma SRD_srdes_skip [closure]: "II\<^sub>R is SRD"
by (simp add: srdes_skip_def RHS_design_is_SRD unrest)
lemma SRD_seqr_closure [closure]:
assumes "P is SRD" "Q is SRD"
shows "(P ;; Q) is SRD"
proof -
have "(P ;; Q) = \<^bold>R\<^sub>s (((\<not>\<^sub>r pre\<^sub>R P) wp\<^sub>r false \<and> post\<^sub>R P wp\<^sub>r pre\<^sub>R Q) \<turnstile>
((\<exists> $st\<acute> \<bullet> peri\<^sub>R P) \<or> (post\<^sub>R P ;; peri\<^sub>R Q)) \<diamondop> (post\<^sub>R P ;; post\<^sub>R Q))"
by (simp add: SRD_composition_wp assms(1) assms(2))
also have "... is SRD"
by (rule RHS_design_is_SRD, simp_all add: wp_rea_def unrest)
finally show ?thesis .
qed
lemma SRD_power_Suc [closure]: "P is SRD \<Longrightarrow> P\<^bold>^(Suc n) is SRD"
proof (induct n)
case 0
then show ?case
by (simp)
next
case (Suc n)
then show ?case
using SRD_seqr_closure by (simp add: SRD_seqr_closure upred_semiring.power_Suc)
qed
lemma SRD_power_comp [closure]: "P is SRD \<Longrightarrow> P ;; P\<^bold>^n is SRD"
by (metis SRD_power_Suc upred_semiring.power_Suc)
lemma uplus_SRD_closed [closure]: "P is SRD \<Longrightarrow> P\<^sup>+ is SRD"
by (simp add: uplus_power_def closure)
lemma SRD_Sup_closure [closure]:
assumes "A \<subseteq> \<lbrakk>SRD\<rbrakk>\<^sub>H" "A \<noteq> {}"
shows "(\<Sqinter> A) is SRD"
proof -
have "SRD (\<Sqinter> A) = (\<Sqinter> (SRD `A))"
by (simp add: ContinuousD SRD_Continuous assms(2))
also have "... = (\<Sqinter> A)"
by (simp only: Healthy_carrier_image assms)
finally show ?thesis by (simp add: Healthy_def)
qed
subsection \<open> Distribution laws \<close>
lemma RHS_tri_design_choice [rdes_def]:
"\<^bold>R\<^sub>s(P\<^sub>1 \<turnstile> P\<^sub>2 \<diamondop> P\<^sub>3) \<sqinter> \<^bold>R\<^sub>s(Q\<^sub>1 \<turnstile> Q\<^sub>2 \<diamondop> Q\<^sub>3) = \<^bold>R\<^sub>s((P\<^sub>1 \<and> Q\<^sub>1) \<turnstile> (P\<^sub>2 \<or> Q\<^sub>2) \<diamondop> (P\<^sub>3 \<or> Q\<^sub>3))"
apply (simp add: RHS_design_choice)
apply (rule cong[of "\<^bold>R\<^sub>s" "\<^bold>R\<^sub>s"])
apply (simp)
apply (rel_auto)
done
lemma RHS_tri_design_disj [rdes_def]:
"(\<^bold>R\<^sub>s(P\<^sub>1 \<turnstile> P\<^sub>2 \<diamondop> P\<^sub>3) \<or> \<^bold>R\<^sub>s(Q\<^sub>1 \<turnstile> Q\<^sub>2 \<diamondop> Q\<^sub>3)) = \<^bold>R\<^sub>s((P\<^sub>1 \<and> Q\<^sub>1) \<turnstile> (P\<^sub>2 \<or> Q\<^sub>2) \<diamondop> (P\<^sub>3 \<or> Q\<^sub>3))"
by (simp add: RHS_tri_design_choice disj_upred_def)
lemma RHS_tri_design_sup [rdes_def]:
"\<^bold>R\<^sub>s(P\<^sub>1 \<turnstile> P\<^sub>2 \<diamondop> P\<^sub>3) \<squnion> \<^bold>R\<^sub>s(Q\<^sub>1 \<turnstile> Q\<^sub>2 \<diamondop> Q\<^sub>3) = \<^bold>R\<^sub>s((P\<^sub>1 \<or> Q\<^sub>1) \<turnstile> ((P\<^sub>1 \<Rightarrow>\<^sub>r P\<^sub>2) \<and> (Q\<^sub>1 \<Rightarrow>\<^sub>r Q\<^sub>2)) \<diamondop> ((P\<^sub>1 \<Rightarrow>\<^sub>r P\<^sub>3) \<and> (Q\<^sub>1 \<Rightarrow>\<^sub>r Q\<^sub>3)))"
by (simp add: RHS_design_sup, rel_auto)
lemma RHS_tri_design_conj [rdes_def]:
"(\<^bold>R\<^sub>s(P\<^sub>1 \<turnstile> P\<^sub>2 \<diamondop> P\<^sub>3) \<and> \<^bold>R\<^sub>s(Q\<^sub>1 \<turnstile> Q\<^sub>2 \<diamondop> Q\<^sub>3)) = \<^bold>R\<^sub>s((P\<^sub>1 \<or> Q\<^sub>1) \<turnstile> ((P\<^sub>1 \<Rightarrow>\<^sub>r P\<^sub>2) \<and> (Q\<^sub>1 \<Rightarrow>\<^sub>r Q\<^sub>2)) \<diamondop> ((P\<^sub>1 \<Rightarrow>\<^sub>r P\<^sub>3) \<and> (Q\<^sub>1 \<Rightarrow>\<^sub>r Q\<^sub>3)))"
by (simp add: RHS_tri_design_sup conj_upred_def)
lemma SRD_UINF [rdes_def]:
assumes "A \<noteq> {}" "A \<subseteq> \<lbrakk>SRD\<rbrakk>\<^sub>H"
shows "\<Sqinter> A = \<^bold>R\<^sub>s((\<And> P\<in>A \<bullet> pre\<^sub>R(P)) \<turnstile> (\<Or> P\<in>A \<bullet> peri\<^sub>R(P)) \<diamondop> (\<Or> P\<in>A \<bullet> post\<^sub>R(P)))"
proof -
have "\<Sqinter> A = \<^bold>R\<^sub>s(pre\<^sub>R(\<Sqinter> A) \<turnstile> peri\<^sub>R(\<Sqinter> A) \<diamondop> post\<^sub>R(\<Sqinter> A))"
by (metis SRD_as_reactive_tri_design assms srdes_theory.healthy_inf srdes_theory.healthy_inf_def)
also have "... = \<^bold>R\<^sub>s((\<And> P\<in>A \<bullet> pre\<^sub>R(P)) \<turnstile> (\<Or> P\<in>A \<bullet> peri\<^sub>R(P)) \<diamondop> (\<Or> P\<in>A \<bullet> post\<^sub>R(P)))"
by (simp add: preR_INF periR_INF postR_INF assms)
finally show ?thesis .
qed
lemma RHS_tri_design_USUP [rdes_def]:
assumes "A \<noteq> {}"
shows "(\<Sqinter> i \<in> A \<bullet> \<^bold>R\<^sub>s(P(i) \<turnstile> Q(i) \<diamondop> R(i))) = \<^bold>R\<^sub>s((\<Squnion> i \<in> A \<bullet> P(i)) \<turnstile> (\<Sqinter> i \<in> A \<bullet> Q(i)) \<diamondop> (\<Sqinter> i \<in> A \<bullet> R(i)))"
by (subst RHS_INF[OF assms, THEN sym], simp add: design_UINF_mem assms, rel_auto)
lemma SRD_UINF_mem:
assumes "A \<noteq> {}" "\<And> i. P i is SRD"
shows "(\<Sqinter> i\<in>A \<bullet> P i) = \<^bold>R\<^sub>s((\<And> i\<in>A \<bullet> pre\<^sub>R(P i)) \<turnstile> (\<Or> i\<in>A \<bullet> peri\<^sub>R(P i)) \<diamondop> (\<Or> i\<in>A \<bullet> post\<^sub>R(P i)))"
(is "?lhs = ?rhs")
proof -
have "?lhs = (\<Sqinter> (P ` A))"
by (rel_auto)
also have " ... = \<^bold>R\<^sub>s ((\<Squnion> Pa \<in> P ` A \<bullet> pre\<^sub>R Pa) \<turnstile> (\<Sqinter> Pa \<in> P ` A \<bullet> peri\<^sub>R Pa) \<diamondop> (\<Sqinter> Pa \<in> P ` A \<bullet> post\<^sub>R Pa))"
by (subst rdes_def, simp_all add: assms image_subsetI)
also have "... = ?rhs"
by (rel_auto)
finally show ?thesis .
qed
lemma RHS_tri_design_UINF_ind [rdes_def]:
"(\<Sqinter> i \<bullet> \<^bold>R\<^sub>s(P\<^sub>1(i) \<turnstile> P\<^sub>2(i) \<diamondop> P\<^sub>3(i))) = \<^bold>R\<^sub>s((\<And> i \<bullet> P\<^sub>1 i) \<turnstile> (\<Or> i \<bullet> P\<^sub>2(i)) \<diamondop> (\<Or> i \<bullet> P\<^sub>3(i)))"
by (rel_auto)
lemma cond_srea_form [rdes_def]:
"\<^bold>R\<^sub>s(P \<turnstile> Q\<^sub>1 \<diamondop> Q\<^sub>2) \<triangleleft> b \<triangleright>\<^sub>R \<^bold>R\<^sub>s(R \<turnstile> S\<^sub>1 \<diamondop> S\<^sub>2) =
\<^bold>R\<^sub>s((P \<triangleleft> b \<triangleright>\<^sub>R R) \<turnstile> (Q\<^sub>1 \<triangleleft> b \<triangleright>\<^sub>R S\<^sub>1) \<diamondop> (Q\<^sub>2 \<triangleleft> b \<triangleright>\<^sub>R S\<^sub>2))"
proof -
have "\<^bold>R\<^sub>s(P \<turnstile> Q\<^sub>1 \<diamondop> Q\<^sub>2) \<triangleleft> b \<triangleright>\<^sub>R \<^bold>R\<^sub>s(R \<turnstile> S\<^sub>1 \<diamondop> S\<^sub>2) = \<^bold>R\<^sub>s(P \<turnstile> Q\<^sub>1 \<diamondop> Q\<^sub>2) \<triangleleft> R2c(\<lceil>b\<rceil>\<^sub>S\<^sub><) \<triangleright> \<^bold>R\<^sub>s(R \<turnstile> S\<^sub>1 \<diamondop> S\<^sub>2)"
by (pred_auto)
also have "... = \<^bold>R\<^sub>s (P \<turnstile> Q\<^sub>1 \<diamondop> Q\<^sub>2 \<triangleleft> b \<triangleright>\<^sub>R R \<turnstile> S\<^sub>1 \<diamondop> S\<^sub>2)"
by (simp add: RHS_cond lift_cond_srea_def)
also have "... = \<^bold>R\<^sub>s ((P \<triangleleft> b \<triangleright>\<^sub>R R) \<turnstile> (Q\<^sub>1 \<diamondop> Q\<^sub>2 \<triangleleft> b \<triangleright>\<^sub>R S\<^sub>1 \<diamondop> S\<^sub>2))"
by (simp add: design_condr lift_cond_srea_def)
also have "... = \<^bold>R\<^sub>s((P \<triangleleft> b \<triangleright>\<^sub>R R) \<turnstile> (Q\<^sub>1 \<triangleleft> b \<triangleright>\<^sub>R S\<^sub>1) \<diamondop> (Q\<^sub>2 \<triangleleft> b \<triangleright>\<^sub>R S\<^sub>2))"
by (rule cong[of "\<^bold>R\<^sub>s" "\<^bold>R\<^sub>s"], simp, rel_auto)
finally show ?thesis .
qed
lemma SRD_cond_srea [closure]:
assumes "P is SRD" "Q is SRD"
shows "P \<triangleleft> b \<triangleright>\<^sub>R Q is SRD"
proof -
have "P \<triangleleft> b \<triangleright>\<^sub>R Q = \<^bold>R\<^sub>s(pre\<^sub>R(P) \<turnstile> peri\<^sub>R(P) \<diamondop> post\<^sub>R(P)) \<triangleleft> b \<triangleright>\<^sub>R \<^bold>R\<^sub>s(pre\<^sub>R(Q) \<turnstile> peri\<^sub>R(Q) \<diamondop> post\<^sub>R(Q))"
by (simp add: SRD_reactive_tri_design assms)
also have "... = \<^bold>R\<^sub>s ((pre\<^sub>R P \<triangleleft> b \<triangleright>\<^sub>R pre\<^sub>R Q) \<turnstile> (peri\<^sub>R P \<triangleleft> b \<triangleright>\<^sub>R peri\<^sub>R Q) \<diamondop> (post\<^sub>R P \<triangleleft> b \<triangleright>\<^sub>R post\<^sub>R Q))"
by (simp add: cond_srea_form)
also have "... is SRD"
by (simp add: RHS_tri_design_is_SRD lift_cond_srea_def unrest)
finally show ?thesis .
qed
subsection \<open> Algebraic laws \<close>
lemma RD_left_unit:
assumes "P is RD"
shows "II\<^sub>C ;; P = P"
by (simp add: RD1_left_unit RD_healths(1) RD_healths(4) assms)
lemma skip_rdes_self_unit [simp]:
"II\<^sub>C ;; II\<^sub>C = II\<^sub>C"
by (simp add: RD_left_unit closure)
lemma SRD_left_unit:
assumes "P is SRD"
shows "II\<^sub>R ;; P = P"
by (simp add: SRD_composition_wp closure rdes wp C1 R1_negate_R1 R1_false
rpred trace_ident_left_periR trace_ident_left_postR SRD_reactive_tri_design assms)
lemma skip_srea_self_unit [simp]:
"II\<^sub>R ;; II\<^sub>R = II\<^sub>R"
by (simp add: SRD_left_unit closure)
lemma SRD_right_unit_tri_lemma:
assumes "P is SRD"
shows "P ;; II\<^sub>R = \<^bold>R\<^sub>s ((\<not>\<^sub>r pre\<^sub>R P) wp\<^sub>r false \<turnstile> (\<exists> $st\<acute> \<bullet> peri\<^sub>R P) \<diamondop> post\<^sub>R P)"
by (simp add: SRD_composition_wp closure rdes wp rpred trace_ident_right_postR assms)
lemma Miracle_left_zero:
assumes "P is SRD"
shows "Miracle ;; P = Miracle"
proof -
have "Miracle ;; P = \<^bold>R\<^sub>s(true \<turnstile> false) ;; \<^bold>R\<^sub>s(pre\<^sub>R(P) \<turnstile> cmt\<^sub>R(P))"
by (simp add: Miracle_def SRD_reactive_design_alt assms)
also have "... = \<^bold>R\<^sub>s(true \<turnstile> false)"
by (simp add: RHS_design_composition unrest R1_false R2s_false R2s_true)
also have "... = Miracle"
by (simp add: Miracle_def)
finally show ?thesis .
qed
lemma Chaos_left_zero:
assumes "P is SRD"
shows "(Chaos ;; P) = Chaos"
proof -
have "Chaos ;; P = \<^bold>R\<^sub>s(false \<turnstile> true) ;; \<^bold>R\<^sub>s(pre\<^sub>R(P) \<turnstile> cmt\<^sub>R(P))"
by (simp add: Chaos_def SRD_reactive_design_alt assms)
also have "... = \<^bold>R\<^sub>s ((\<not> R1 true \<and> \<not> (R1 true \<and> \<not> $wait\<acute>) ;; R1 (\<not> R2s (pre\<^sub>R P))) \<turnstile>
R1 true ;; ((\<exists> $st \<bullet> \<lceil>II\<rceil>\<^sub>D) \<triangleleft> $wait \<triangleright> R1 (R2s (cmt\<^sub>R P))))"
by (simp add: RHS_design_composition unrest R2s_false R2s_true R1_false)
also have "... = \<^bold>R\<^sub>s ((false \<and> \<not> (R1 true \<and> \<not> $wait\<acute>) ;; R1 (\<not> R2s (pre\<^sub>R P))) \<turnstile>
R1 true ;; ((\<exists> $st \<bullet> \<lceil>II\<rceil>\<^sub>D) \<triangleleft> $wait \<triangleright> R1 (R2s (cmt\<^sub>R P))))"
by (simp add: RHS_design_conj_neg_R1_pre)
also have "... = \<^bold>R\<^sub>s(true)"
by (simp add: design_false_pre)
also have "... = \<^bold>R\<^sub>s(false \<turnstile> true)"
by (simp add: design_def)
also have "... = Chaos"
by (simp add: Chaos_def)
finally show ?thesis .
qed
lemma SRD_right_Chaos_tri_lemma:
assumes "P is SRD"
shows "P ;; Chaos = \<^bold>R\<^sub>s (((\<not>\<^sub>r pre\<^sub>R P) wp\<^sub>r false \<and> post\<^sub>R P wp\<^sub>r false) \<turnstile> (\<exists> $st\<acute> \<bullet> peri\<^sub>R P) \<diamondop> false)"
by (simp add: SRD_composition_wp closure rdes assms wp, rel_auto)
lemma SRD_right_Miracle_tri_lemma:
assumes "P is SRD"
shows "P ;; Miracle = \<^bold>R\<^sub>s ((\<not>\<^sub>r pre\<^sub>R P) wp\<^sub>r false \<turnstile> (\<exists> $st\<acute> \<bullet> peri\<^sub>R P) \<diamondop> false)"
by (simp add: SRD_composition_wp closure rdes assms wp, rel_auto)
text \<open> Reactive designs are left unital \<close>
interpretation rdes_left_unital: utp_theory_left_unital "RD" "II\<^sub>C"
by (unfold_locales, simp_all add: closure RD_left_unit)
text \<open> Stateful reactive designs are left unital \<close>
interpretation srdes_left_unital: utp_theory_left_unital "SRD" "II\<^sub>R"
by (unfold_locales, simp_all add: closure SRD_left_unit)
subsection \<open> Recursion laws \<close>
lemma mono_srd_iter:
assumes "mono F" "F \<in> \<lbrakk>SRD\<rbrakk>\<^sub>H \<rightarrow> \<lbrakk>SRD\<rbrakk>\<^sub>H"
shows "mono (\<lambda>X. \<^bold>R\<^sub>s(pre\<^sub>R(F X) \<turnstile> peri\<^sub>R(F X) \<diamondop> post\<^sub>R (F X)))"
apply (rule monoI)
apply (rule srdes_tri_refine_intro')
apply (meson assms(1) monoE preR_antitone utp_pred_laws.le_infI2)
apply (meson assms(1) monoE periR_monotone utp_pred_laws.le_infI2)
apply (meson assms(1) monoE postR_monotone utp_pred_laws.le_infI2)
done
lemma mu_srd_SRD:
assumes "mono F" "F \<in> \<lbrakk>SRD\<rbrakk>\<^sub>H \<rightarrow> \<lbrakk>SRD\<rbrakk>\<^sub>H"
shows "(\<mu> X \<bullet> \<^bold>R\<^sub>s (pre\<^sub>R (F X) \<turnstile> peri\<^sub>R (F X) \<diamondop> post\<^sub>R (F X))) is SRD"
apply (subst gfp_unfold)
apply (simp add: mono_srd_iter assms)
apply (rule RHS_tri_design_is_SRD)
apply (simp_all add: unrest)
done
lemma mu_srd_iter:
assumes "mono F" "F \<in> \<lbrakk>SRD\<rbrakk>\<^sub>H \<rightarrow> \<lbrakk>SRD\<rbrakk>\<^sub>H"
shows "(\<mu> X \<bullet> \<^bold>R\<^sub>s(pre\<^sub>R(F(X)) \<turnstile> peri\<^sub>R(F(X)) \<diamondop> post\<^sub>R(F(X)))) = F(\<mu> X \<bullet> \<^bold>R\<^sub>s(pre\<^sub>R(F(X)) \<turnstile> peri\<^sub>R(F(X)) \<diamondop> post\<^sub>R(F(X))))"
apply (subst gfp_unfold)
apply (simp add: mono_srd_iter assms)
apply (subst SRD_as_reactive_tri_design[THEN sym])
apply (simp add: Healthy_apply_closed SRD_as_reactive_design SRD_reactive_design_alt assms(1) assms(2) mu_srd_SRD)
done
lemma mu_srd_form:
assumes "mono F" "F \<in> \<lbrakk>SRD\<rbrakk>\<^sub>H \<rightarrow> \<lbrakk>SRD\<rbrakk>\<^sub>H"
shows "\<mu>\<^sub>R F = (\<mu> X \<bullet> \<^bold>R\<^sub>s(pre\<^sub>R(F(X)) \<turnstile> peri\<^sub>R(F(X)) \<diamondop> post\<^sub>R(F(X))))"
proof -
have 1: "F (\<mu> X \<bullet> \<^bold>R\<^sub>s(pre\<^sub>R (F X) \<turnstile> peri\<^sub>R(F X) \<diamondop> post\<^sub>R (F X))) is SRD"
by (simp add: Healthy_apply_closed assms(1) assms(2) mu_srd_SRD)
have 2:"Mono\<^bsub>utp_order SRD\<^esub> F"
by (simp add: assms(1) mono_Monotone_utp_order)
hence 3:"\<mu>\<^sub>R F = F (\<mu>\<^sub>R F)"
by (simp add: srdes_theory.LFP_unfold[THEN sym] assms)
hence "\<^bold>R\<^sub>s(pre\<^sub>R (F (F (\<mu>\<^sub>R F))) \<turnstile> peri\<^sub>R (F (F (\<mu>\<^sub>R F))) \<diamondop> post\<^sub>R (F (F (\<mu>\<^sub>R F)))) = \<mu>\<^sub>R F"
using SRD_reactive_tri_design by force
hence "(\<mu> X \<bullet> \<^bold>R\<^sub>s(pre\<^sub>R (F X) \<turnstile> peri\<^sub>R(F X) \<diamondop> post\<^sub>R (F X))) \<sqsubseteq> F (\<mu>\<^sub>R F)"
by (simp add: 2 srdes_theory.weak.LFP_lemma3 gfp_upperbound assms)
thus ?thesis
using assms 1 3 srdes_theory.weak.LFP_lowerbound eq_iff mu_srd_iter
by (metis (mono_tags, lifting))
qed
lemma Monotonic_SRD_comp [closure]: "Monotonic ((;;) P \<circ> SRD)"
by (simp add: mono_def R1_R2c_is_R2 R2_mono R3h_mono RD1_mono RD2_mono RHS_def SRD_def seqr_mono)
end |
lemma Zfun_le: "Zfun g F \<Longrightarrow> \<forall>x. norm (f x) \<le> norm (g x) \<Longrightarrow> Zfun f F" |
-- using Idris as a library to install new backends
-- build with: $ idris2 -p idris2 -p contrib -p network -o lazy-idris2 Lazy.idr
-- run with: $ ./build/exec/lazy-idris2 --cg lazy -o <output-exec> <File.idr>
module Main
import Core.Context
import Compiler.Common
import Idris.Driver -- mainWithCodegens
compile : Ref Ctxt Defs -> (tmpDir : String) -> (outputDir : String) -> ClosedTerm -> (outfile : String) -> Core (Maybe String)
compile defs tmpDir outputDir term file = do coreLift $ putStrLn "I'd rather not."
pure Nothing
execute : Ref Ctxt Defs -> (tmpDir : String) -> ClosedTerm -> Core ()
execute defs tmpDir term = do coreLift $ putStrLn "Maybe in an hour!"
lazyCodegen : Codegen
lazyCodegen = MkCG compile execute
main : IO ()
main = mainWithCodegens [("lazy", lazyCodegen)] |
We all agreed that having a broad vocabulary is very important and the key to doing well in Cambridge examinations.
We shared successful ways of helping and encouraging students to build vocabulary that will help them deal with the different tasks in the Cambridge exams.
We all agreed that students should not only read widely, but should try using new vocabulary immediately through either speaking or writing activities.
This entry was posted in Cambridge Exams by Lexis | Noosa. Bookmark the permalink. |
(* Title: HOL/Auth/n_flash_nodata_cub_lemma_on_inv__146.thy
Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
*)
header{*The n_flash_nodata_cub Protocol Case Study*}
theory n_flash_nodata_cub_lemma_on_inv__146 imports n_flash_nodata_cub_base
begin
section{*All lemmas on causal relation between inv__146 and some rule r*}
lemma n_PI_Remote_GetVsinv__146:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_PI_Remote_Get src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_PI_Remote_Get src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_PI_Remote_GetXVsinv__146:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_PI_Remote_GetX src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_PI_Remote_GetX src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_NakVsinv__146:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Nak dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Nak dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst=p__Inv3)\<or>(dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Nak__part__0Vsinv__146:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Nak__part__1Vsinv__146:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Nak__part__2Vsinv__146:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Get__part__0Vsinv__146:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Get__part__1Vsinv__146:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Put_HeadVsinv__146:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_GetX)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''HomeProc'')) (Const false))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Pending'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_PutVsinv__146:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Put_DirtyVsinv__146:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_Get_NakVsinv__146:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst=p__Inv3)\<or>(src=p__Inv3\<and>dst=p__Inv4)\<or>(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)\<or>(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_Get_PutVsinv__146:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst=p__Inv3)\<or>(src=p__Inv3\<and>dst=p__Inv4)\<or>(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)\<or>(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_Nak__part__0Vsinv__146:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_Nak__part__1Vsinv__146:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_Nak__part__2Vsinv__146:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_GetX__part__0Vsinv__146:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_GetX__part__1Vsinv__146:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const true))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_1Vsinv__146:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_2Vsinv__146:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_3Vsinv__146:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_4Vsinv__146:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_5Vsinv__146:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_6Vsinv__146:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7__part__0Vsinv__146:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7__part__1Vsinv__146:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__0Vsinv__146:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__1Vsinv__146:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_HomeVsinv__146:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_Home_NODE_GetVsinv__146:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8Vsinv__146:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp=p__Inv3)\<or>(src=p__Inv3\<and>pp=p__Inv4)\<or>(src=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv4)\<or>(src=p__Inv3\<and>pp~=p__Inv3\<and>pp~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>pp=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_NODE_GetVsinv__146:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp=p__Inv3)\<or>(src=p__Inv3\<and>pp=p__Inv4)\<or>(src=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv4)\<or>(src=p__Inv3\<and>pp~=p__Inv3\<and>pp~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>pp=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_9__part__0Vsinv__146:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_9__part__1Vsinv__146:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_10_HomeVsinv__146:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_10Vsinv__146:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp=p__Inv3)\<or>(src=p__Inv3\<and>pp=p__Inv4)\<or>(src=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv4)\<or>(src=p__Inv3\<and>pp~=p__Inv3\<and>pp~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>pp=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_11Vsinv__146:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_NakVsinv__146:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst=p__Inv3)\<or>(src=p__Inv3\<and>dst=p__Inv4)\<or>(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)\<or>(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_PutXVsinv__146:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst=p__Inv3)\<or>(src=p__Inv3\<and>dst=p__Inv4)\<or>(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)\<or>(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_PutVsinv__146:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Put dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Put dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst=p__Inv3)\<or>(dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_PutXVsinv__146:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_PutX dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_PutX dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst=p__Inv3)\<or>(dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_ReplaceVsinv__146:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Replace src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Replace src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "((formEval (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) s))\<or>((formEval (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) s))" by auto
moreover {
assume c1: "((formEval (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) s))"
have "?P2 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately have "invHoldForRule s f r (invariants N)" by satx
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_PI_Local_GetX_PutX_HeadVld__part__0Vsinv__146:
assumes a1: "(r=n_PI_Local_GetX_PutX_HeadVld__part__0 N )" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_PI_Local_GetX_PutX_HeadVld__part__1Vsinv__146:
assumes a1: "(r=n_PI_Local_GetX_PutX_HeadVld__part__1 N )" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_ShWbVsinv__146:
assumes a1: "(r=n_NI_ShWb N )" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4" apply fastforce done
have "((formEval (andForm (eqn (Const (index p__Inv4)) (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''Proc''))) (eqn (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''HomeProc'')) (Const false))) s))\<or>((formEval (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true)) s))\<or>((formEval (andForm (neg (eqn (Const (index p__Inv4)) (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''Proc'')))) (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''HomeProc'')) (Const false))) (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true)))) s))" by auto
moreover {
assume c1: "((formEval (andForm (eqn (Const (index p__Inv4)) (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''Proc''))) (eqn (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''HomeProc'')) (Const false))) s))"
have "?P3 s"
apply (cut_tac a1 a2 c1, simp, rule_tac x="(neg (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''Cmd'')) (Const SHWB_ShWb)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_GetX))) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''HomeProc'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true)) s))"
have "?P3 s"
apply (cut_tac a1 a2 c1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''Cmd'')) (Const SHWB_ShWb)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (neg (eqn (Const (index p__Inv4)) (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''Proc'')))) (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true)))) s))"
have "?P1 s"
proof(cut_tac a1 a2 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''HomeProc'')) (Const false))) (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true)))) s))"
have "?P1 s"
proof(cut_tac a1 a2 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_PutX_HomeVsinv__146:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_PutX_Home dst" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX__part__0Vsinv__146:
assumes a1: "r=n_PI_Local_GetX_PutX__part__0 " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_WbVsinv__146:
assumes a1: "r=n_NI_Wb " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_3Vsinv__146:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_3 N src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_1Vsinv__146:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_1 N src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_GetX__part__1Vsinv__146:
assumes a1: "r=n_PI_Local_GetX_GetX__part__1 " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_GetX__part__0Vsinv__146:
assumes a1: "r=n_PI_Local_GetX_GetX__part__0 " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_ReplaceVsinv__146:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_PI_Remote_Replace src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_ReplaceVsinv__146:
assumes a1: "r=n_PI_Local_Replace " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_existsVsinv__146:
assumes a1: "\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_InvAck_exists src pp" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_PutXVsinv__146:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_PI_Remote_PutX dst" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_Get_Put_HomeVsinv__146:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Put_Home dst" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvVsinv__146:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Inv dst" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_PutXVsinv__146:
assumes a1: "r=n_PI_Local_PutX " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_Get_PutVsinv__146:
assumes a1: "r=n_PI_Local_Get_Put " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_GetX_Nak_HomeVsinv__146:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_Nak_Home dst" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_PutXAcksDoneVsinv__146:
assumes a1: "r=n_NI_Local_PutXAcksDone " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX__part__1Vsinv__146:
assumes a1: "r=n_PI_Local_GetX_PutX__part__1 " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_Get_Nak_HomeVsinv__146:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Nak_Home dst" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_exists_HomeVsinv__146:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_exists_Home src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Replace_HomeVsinv__146:
assumes a1: "r=n_NI_Replace_Home " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_PutVsinv__146:
assumes a1: "r=n_NI_Local_Put " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Nak_ClearVsinv__146:
assumes a1: "r=n_NI_Nak_Clear " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_Get_GetVsinv__146:
assumes a1: "r=n_PI_Local_Get_Get " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Nak_HomeVsinv__146:
assumes a1: "r=n_NI_Nak_Home " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_2Vsinv__146:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_2 N src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_FAckVsinv__146:
assumes a1: "r=n_NI_FAck " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__146 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
end
|
[STATEMENT]
lemma sequence_number_increases:
"paodv i \<TTurnstile>\<^sub>A onll \<Gamma>\<^sub>A\<^sub>O\<^sub>D\<^sub>V (\<lambda>((\<xi>, _), _, (\<xi>', _)). sn \<xi> \<le> sn \<xi>')"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. paodv i \<TTurnstile>\<^sub>A onll \<Gamma>\<^sub>A\<^sub>O\<^sub>D\<^sub>V (\<lambda>((\<xi>, uu_), uu_, \<xi>', uu_). sn \<xi> \<le> sn \<xi>')
[PROOF STEP]
by inv_cterms |
Play pool with your favorite NFL team. Great way to enjoy your home pool table by using this cool NFL New York Giants Billiard Ball Set. Comes complete with NFL eight ball and cue ball.
You no longer have to play 8 ball with just solids and stripes, now you can play in style with this New York Giants Billiard Ball Set.
Combines home and away colors with the NFL cue ball, and the referee 8 ball to make a full New York Giants Billiard Ball Set.
The New York Giants Billiard Ball Set carries a 90 day manufacturer's warranty against defects. |
(* Copyright (c) Inria. All rights reserved. *)
Require Import Reals Psatz.
From Flocq Require Import Core Plus_error Relative Sterbenz Operations.
Require Import F2SumFLT.
Require Import mathcomp.ssreflect.ssreflect.
Set Implicit Arguments.
Section Fast2Sum.
Variable beta: radix.
Local Notation pow e := (bpow beta e).
Local Open Scope Z_scope.
Variables p : Z.
Hypothesis Hp : Z.lt 1 p.
Local Instance p_gt_0 : Prec_gt_0 p.
Proof. by apply:(Z.lt_trans _ 1). Qed.
Local Notation fexp := (FLX_exp p).
Local Notation format := (generic_format beta fexp).
Local Notation ce := (cexp beta fexp).
Local Notation mant := (scaled_mantissa beta fexp).
Variable choice : Z -> bool.
Local Notation rnd_p := (round beta fexp (Znearest choice)).
Hypothesis rnd_p_sym : forall x, (rnd_p (-x) = - rnd_p (x))%R.
Theorem cexp_bpow x e (xne0: x <> R0): ce (x * pow e) = ce x + e.
Proof. rewrite /ce mag_mult_bpow // /FLX_exp; ring. Qed.
Theorem mant_bpow x e : mant (x * pow e) = mant x.
Proof.
case: (Req_dec x 0) => [->|Zx]; first by rewrite Rmult_0_l.
rewrite /scaled_mantissa cexp_bpow // Rmult_assoc -bpow_plus.
by ring_simplify (e + - (ce x + e)).
Qed.
Theorem round_bpow x e: rnd_p (x * pow e) = (rnd_p x * pow e)%R.
Proof.
case: (Req_dec x 0) => [->|Zx] ; first by rewrite Rmult_0_l round_0 Rmult_0_l.
by rewrite /round /F2R /= mant_bpow cexp_bpow // bpow_plus Rmult_assoc.
Qed.
(* (* to move .... MoreFLXFlocq *) *)
(* cf FLX_format *)
Theorem FLX_mant_le x (Fx: format x): Z.abs (Ztrunc (mant x)) <= beta^p - 1.
Proof.
suff : (Z.abs (Ztrunc (mant x)) < beta ^ p)%Z by lia.
apply: lt_IZR; rewrite abs_IZR - scaled_mantissa_generic //.
rewrite IZR_Zpower; last lia.
have ->: pow p = pow (mag beta x - ce x) by rewrite /ce /fexp; congr bpow; ring.
exact : scaled_mantissa_lt_bpow.
Qed.
Definition pair_opp (p: R*R):= ((-(fst p))%R, (- (snd p))%R).
Section F2Sum.
Variables a b : R.
Hypothesis Fa : format a.
Hypothesis Fb : format b.
Notation s := (rnd_p (a + b)).
Notation z := (rnd_p (s - a)).
Notation t := (rnd_p (b - z)).
Hypothesis Hb3 : beta <= 3.
Variable fa : float beta.
Hypothesis exp_le: (a = F2R fa) /\ (ce b <= Fexp fa).
Notation ubemin x := ( mag beta x - p)%Z.
Fact Rle_pmabs emin x: (emin <= ubemin x)%Z -> x <> 0%R -> (pow (emin + p - 1) <= Rabs x)%R.
Proof.
move=> hemin xn0.
apply:(Rle_trans _ (pow ((mag beta x) - 1))).
apply:bpow_le; lia.
by apply: bpow_mag_le.
Qed.
Definition emin := (Z.min (ubemin a)
(Z.min (ubemin b)
(Z.min (ubemin s)
(Z.min (ubemin (a + b))
(Z.min (ubemin z)
(Z.min (ubemin (s - a))
(Z.min (ubemin (b - z))(ubemin t)))))))).
Fact getnum_fa: exists (fa : float beta),
(a = F2R fa) /\ (Z.abs (Fnum fa) <= beta^p - 1)
/\ (ce b <= Fexp fa).
Proof.
case:exp_le => h1 h2.
case:(Z_lt_le_dec ( ce a ) (ce b))=> h; last first.
rewrite Fa.
set f'a := (Float beta _ _).
exists f'a; split=>//; rewrite /fa /=; split =>//.
by apply:FLX_mant_le.
exists fa; split=>//; split =>//.
move:h1; rewrite Fa /F2R /=.
have -> : (Fexp fa) = ((Fexp fa) - (ce a)) + ce a by ring.
rewrite bpow_plus -Rmult_assoc.
move/Rmult_eq_reg_r.
have hh: pow (ce a) <> 0%R by move:(bpow_gt_0 beta (ce a)); lra.
move/(_ hh)=> h1.
apply:(Z.le_trans _ (Z.abs (Ztrunc (mant a)))); last by apply:FLX_mant_le.
apply:le_IZR.
rewrite !abs_IZR h1 Rabs_mult // -[X in (X <= _)%R]Rmult_1_r.
apply:Rmult_le_compat_l; first by apply: Rabs_pos.
rewrite Rabs_pos_eq ; last by apply:bpow_ge_0.
change ( pow 0 <= pow (Fexp fa - ce a))%R.
by apply:bpow_le; lia.
Qed.
(* Hypothesis ZNE : choice = fun n => negb (Z.even n). *)
Theorem Fast2Sum_correct_proof_aux : t = (a + b - s)%R.
Proof.
case:getnum_fa=>// fa' [fa'E [h1 h2]].
case:(Req_dec a 0)=>a0.
rewrite a0 !Rplus_0_l Rminus_0_r !round_generic //.
have ->: (b - b = 0)%R by ring.
by apply/generic_format_0.
have emin_a: (pow (emin + p - 1) <= Rabs a)%R.
apply:Rle_pmabs=>//.
by repeat (apply: Z.le_min_l || apply: (Z.le_trans _ _ _ (Z.le_min_r _ _))).
case:(Req_dec b 0)=>b0.
rewrite b0 !Rplus_0_r (round_generic _ _ _ a) //.
have ->: (a - a = 0)%R by ring.
by rewrite round_0 Rminus_0_r round_0 //.
have emin_b: (pow (emin + p - 1) <= Rabs b)%R.
apply:Rle_pmabs=>//.
by repeat (apply: Z.le_min_l || apply: (Z.le_trans _ _ _ (Z.le_min_r _ _))).
case:(Req_dec (a+b) 0)=>ab0.
rewrite ab0 round_0 Rminus_0_l Rminus_0_r.
rewrite rnd_p_sym (round_generic _ _ _ a) //.
have-> : (b - - a = a + b)%R by ring.
by rewrite ab0 round_0.
have emin_apb: (pow (emin + p - 1) <= Rabs (a+b))%R.
apply:Rle_pmabs=>//.
by repeat (apply: Z.le_min_l || apply: (Z.le_trans _ _ _ (Z.le_min_r _ _))).
case:(Req_dec (s - a) 0)=>sma0.
rewrite sma0 round_0 Rminus_0_r round_generic //; lra.
have emin_sma: (pow (emin + p - 1) <= Rabs (s-a))%R.
apply:Rle_pmabs=>//.
by repeat (apply: Z.le_min_l || apply: (Z.le_trans _ _ _ (Z.le_min_r _ _))).
case:(Req_dec (b - z) 0)=>bmz0.
(* pose emin := (Z.min (ubemin a) *)
(* (Z.min (ubemin b) (Z.min (ubemin (a + b)) (ubemin (s -a))))). *)
rewrite bmz0 round_0 -!(round_FLT_FLX _ emin)//.
have ->: (0%R = round beta (FLT_exp emin p) (Znearest choice) (b -z))%R.
by rewrite bmz0 round_0.
rewrite -!(round_FLT_FLX _ emin) //.
apply Fast2Sum_correct_proof_flt with (fa := fa')=>//.
+ by rewrite /Prec_gt_0; lia.
+ by apply:generic_format_FLT_FLX.
+ by apply:generic_format_FLT_FLX.
split=>//; split=>//.
by rewrite cexp_FLT_FLX.
by rewrite (round_FLT_FLX _ emin).
have emin_bmz: (pow (emin + p - 1) <= Rabs (b -z))%R.
apply:Rle_pmabs=>//.
by repeat (apply: Z.le_min_l || apply: (Z.le_trans _ _ _ (Z.le_min_r _ _))).
rewrite -!(round_FLT_FLX _ emin)//.
+ apply Fast2Sum_correct_proof_flt with (fa := fa')=>//.
- rewrite / Prec_gt_0; lia.
- by apply:generic_format_FLT_FLX.
- by apply:generic_format_FLT_FLX.
split=>//; split=>//.
by rewrite cexp_FLT_FLX.
+ by rewrite !(round_FLT_FLX _ emin).
+ by rewrite !(round_FLT_FLX _ emin).
+ by rewrite !(round_FLT_FLX _ emin).
Qed.
Definition Fast2Sum := (s, t).
Definition Fast2Sum_correct :=
let s := fst Fast2Sum in let t := snd Fast2Sum in t = (a+b -s)%R.
End F2Sum.
Fact Fast2Sum0f b (Fb:format b): (Fast2Sum 0 b ) = (b,0%R).
Proof.
rewrite /Fast2Sum !(Rplus_0_l, Rminus_0_r, round_0) !round_generic //;
ring_simplify(b-b)%R=>//.
by apply:generic_format_0.
Qed.
Fact Fast2Sumf0 a (Fa:format a): (Fast2Sum a 0 ) = (a,0%R).
Proof.
by rewrite /Fast2Sum !(Rplus_0_r, Rminus_0_l, round_0) !round_generic //;
ring_simplify(a-a)%R; rewrite ?Ropp_0 // ;
apply:generic_format_0.
Qed.
Hypothesis ZNE : choice = fun n => negb (Z.even n).
Fact Fast2Sum_asym a b : Fast2Sum (-a) (-b) = pair_opp (Fast2Sum a b).
Proof.
rewrite /Fast2Sum /pair_opp/=.
rewrite -!Ropp_plus_distr ZNE round_NE_opp -ZNE.
rewrite -2!Ropp_minus_distr Ropp_involutive -Ropp_minus_distr.
set rab := rnd_p (a + b).
have->: (-rab - - a = - (rab - a))%R by ring.
rewrite ZNE !round_NE_opp -ZNE.
by have->: ((- rnd_p (rab - a) - - b) = (b - rnd_p (rab - a)))%R by ring.
Qed.
Fact Fast2SumS x y e (Fx : format x) (Fy : format y):
Fast2Sum (x * pow e) (y * pow e) = ((fst (Fast2Sum x y) * pow e)%R,
(snd (Fast2Sum x y) * pow e)%R).
Proof.
rewrite /= /Fast2Sum.
by rewrite /= !(=^~ Rmult_plus_distr_r, round_bpow, =^~ Rmult_minus_distr_r).
Qed.
Hypothesis Hb3 : beta <= 3.
Notation ubemin x := ( mag beta x - p)%Z.
Theorem F2Sum_correct_proof a b (Fa : format a) (Fb : format b) :
(exists (fa:float beta), a = F2R fa /\ ce b <= Fexp fa )->
Fast2Sum_correct a b.
Proof.
case=> fa [faE hle].
case:(@getnum_fa a b Fa fa)=>// fa' [fa'E [h1 h2]].
rewrite /Fast2Sum_correct /=.
by rewrite (@Fast2Sum_correct_proof_aux _ _ Fa Fb Hb3 fa').
Qed.
Theorem F2Sum_correct_cexp a b (Fa : format a) (Fb : format b) :
ce b <= ce a -> Fast2Sum_correct a b.
Proof.
move=> cexp_le.
move:(Fa); rewrite /generic_format.
set Ma := Ztrunc _.
set fa := Float beta _ _.
move=> afE.
apply: (@Fast2Sum_correct_proof_aux _ _ _ _ _ fa)=>//.
Qed.
Theorem F2Sum_correct_abs a b (Fa : format a) (Fb : format b) :
(Rabs b <= Rabs a)%R -> Fast2Sum_correct a b.
Proof.
move=> abs_le.
move:(Fa); rewrite /generic_format.
set Ma := Ztrunc _.
set fa := Float beta _ _.
move=> afE.
case:(Req_dec b 0)=> [->|b0].
rewrite /Fast2Sum_correct Fast2Sumf0 //=; ring.
apply:F2Sum_correct_cexp=>//.
by apply/FLX_exp_monotone/mag_le_abs.
Qed.
Theorem F2Sum_correct_DW a b : Fast2Sum_correct a b ->
let s := fst (Fast2Sum a b) in let t := snd (Fast2Sum a b) in
(format s /\format t) /\ s = rnd_p (s + t).
Proof.
rewrite /Fast2Sum_correct.
case H: (Fast2Sum a b) => [s t] /=.
move: H; rewrite /Fast2Sum; case=> sE tE H.
split;first by split; rewrite -?sE -?tE; apply:generic_format_round.
by have -> : (s + t = a+b)%R; lra.
Qed.
End Fast2Sum.
|
[STATEMENT]
lemma aform_val_uminus_aform[simp]: "aform_val e (uminus_aform X) = - aform_val e X"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. aform_val e (uminus_aform X) = - aform_val e X
[PROOF STEP]
by (auto simp: uminus_aform_def aform_val_def) |
[STATEMENT]
lemma spanning_surjective_image:
assumes us: "UNIV \<subseteq> m1.span S"
and sf: "surj f"
shows "UNIV \<subseteq> m2.span (f ` S)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. UNIV \<subseteq> m2.span (f ` S)
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. UNIV \<subseteq> m2.span (f ` S)
[PROOF STEP]
have "UNIV \<subseteq> f ` UNIV"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. UNIV \<subseteq> range f
[PROOF STEP]
using sf
[PROOF STATE]
proof (prove)
using this:
surj f
goal (1 subgoal):
1. UNIV \<subseteq> range f
[PROOF STEP]
by (auto simp add: surj_def)
[PROOF STATE]
proof (state)
this:
UNIV \<subseteq> range f
goal (1 subgoal):
1. UNIV \<subseteq> m2.span (f ` S)
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
UNIV \<subseteq> range f
goal (1 subgoal):
1. UNIV \<subseteq> m2.span (f ` S)
[PROOF STEP]
have " \<dots> \<subseteq> m2.span (f ` S)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. range f \<subseteq> m2.span (f ` S)
[PROOF STEP]
using spans_image[OF us]
[PROOF STATE]
proof (prove)
using this:
range f \<subseteq> m2.span (f ` S)
goal (1 subgoal):
1. range f \<subseteq> m2.span (f ` S)
[PROOF STEP]
.
[PROOF STATE]
proof (state)
this:
range f \<subseteq> m2.span (f ` S)
goal (1 subgoal):
1. UNIV \<subseteq> m2.span (f ` S)
[PROOF STEP]
finally
[PROOF STATE]
proof (chain)
picking this:
UNIV \<subseteq> m2.span (f ` S)
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
UNIV \<subseteq> m2.span (f ` S)
goal (1 subgoal):
1. UNIV \<subseteq> m2.span (f ` S)
[PROOF STEP]
.
[PROOF STATE]
proof (state)
this:
UNIV \<subseteq> m2.span (f ` S)
goal:
No subgoals!
[PROOF STEP]
qed |
function f = vl_ertr(f) ;
% VL_ERTR Transpose exremal regions frames
% F = VL_ERTR(F) transposes the frames F as returned by VL_MSER(). This
% conversion is required as the VL_MSER algorithm considers the column
% index I as the frist image index, while according standard image
% convention the first coordinate is the abscissa X.
%
% See also: VL_MSER(), VL_HELP().
if size(f,1) ~= 5
error('F is not in the right format') ;
end
% adjust convention
f = f([2 1 5 4 3],:) ;
|
-- Exercises.idr
-- Solutions for exercises of chapter 1
module Exercises
-- Check if words are palindromes
||| Checks whether the given word is a palindrome
||| The check is case-insensitive
||| @str A string to be checked
export
palindrome : (str : String) -> Bool
palindrome str = let lstr = toLower str
rev = reverse lstr in
lstr == rev
||| Checks whether the given word is a palindrome
||| The check is case-insensitive and a minimum word
||| length is required.
||| @minLen Minimum required word length for palindrome
||| @str A string to be checked
export
palindromeMinLen : (minLen : Nat) -> (str : String) -> Bool
palindromeMinLen minLen str = let wordLength = length str
lstr = toLower str
rev = reverse lstr in
(wordLength > minLen) && (lstr == rev)
-- Count words & characters
||| Counts the number of words and characters of the given string.
||| Whitespace is ignored.
||| @str A string to be counted
export
counts : (str : String) -> (Nat, Nat)
counts str = let ww = words str
numWords = length ww
numChars = sum (map length ww) in
(numWords, numChars)
||| Counts the number of words and characters of the given string.
||| Whitespace is included..
||| @str A string to be counted
export
countWithSpace : (str : String) -> (Nat, Nat)
countWithSpace str = let ww = words str
numWords = length ww
numChars = length str in
(numWords, numChars)
-- Extract top 10 values
||| Extracts the 10 largest values from given list
||| ('top ten')
||| @l List with numeric values
export
top_ten : Ord a => (l : List a) -> List a
top_ten l = take 10 $ reverse $ sort l
-- Count strings over given length
||| Counts the number of strings wiht length
||| larger than given limit
||| @len A Nat of length limit
||| @strs A list of string
export
over_length : (len : Nat) -> (strs : List String) -> Nat
over_length len strs = length $ filter (\w => (length w) > len) strs
|
lemma image_affinity_interval: fixes c :: "'a::ordered_real_vector" shows "((\<lambda>x. m *\<^sub>R x + c) ` {a..b}) = (if {a..b}={} then {} else if 0 \<le> m then {m *\<^sub>R a + c .. m *\<^sub>R b + c} else {m *\<^sub>R b + c .. m *\<^sub>R a + c})" (is "?lhs = ?rhs") |
Require Import Category.Lib.
Require Import Category.Theory.Category.
Require Import Category.Theory.Functor.
Require Import Category.Structure.Initial.
Require Import Category.Construction.Comma.
Require Import Category.Functor.Diagonal.
Generalizable All Variables.
Section UniversalArrow.
Context `{C : Category}.
Context `{D : Category}.
(* A universal arrow is an initial object in the comma category (=(c) ↓ F). *)
Class UniversalArrow (c : C) (F : D ⟶ C) := {
arrow_initial : @Initial (=(c) ↓ F);
arrow_obj := snd (`1 (@initial_obj _ arrow_initial));
arrow : c ~> F arrow_obj := `2 (@initial_obj _ arrow_initial)
}.
Notation "c ⟿ F" := (UniversalArrow c F) (at level 20) : category_theory_scope.
(* The following UMP follows directly from the nature of initial objects in a
comma category. *)
Corollary ump_universal_arrows `(c ⟿ F) `(h : c ~> F d) :
∃! g : arrow_obj ~> d, h ≈ fmap[F] g ∘ arrow.
Proof.
unfold arrow_obj, arrow; simpl.
destruct (@zero _ arrow_initial ((ttt, d); h)), x.
simpl in *.
rewrite id_right in e.
exists h1.
- assumption.
- intros.
rewrite <- id_right in e.
rewrite <- id_right in X.
exact (snd (@zero_unique _ arrow_initial ((ttt, d); h)
((ttt, h1); e) ((ttt, v); X))).
Qed.
End UniversalArrow.
|
/-
Copyright (c) 2020 Aaron Anderson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson, Jalex Stark, Lu-Ming Zhang
-/
import combinatorics.simple_graph.basic
import data.rel
import linear_algebra.matrix.trace
import linear_algebra.matrix.symmetric
/-!
# Adjacency Matrices
This module defines the adjacency matrix of a graph, and provides theorems connecting graph
properties to computational properties of the matrix.
## Main definitions
* `matrix.is_adj_matrix`: `A : matrix V V α` is qualified as an "adjacency matrix" if
(1) every entry of `A` is `0` or `1`,
(2) `A` is symmetric,
(3) every diagonal entry of `A` is `0`.
* `matrix.is_adj_matrix.to_graph`: for `A : matrix V V α` and `h : A.is_adj_matrix`,
`h.to_graph` is the simple graph induced by `A`.
* `matrix.compl`: for `A : matrix V V α`, `A.compl` is supposed to be
the adjacency matrix of the complement graph of the graph induced by `A`.
* `simple_graph.adj_matrix`: the adjacency matrix of a `simple_graph`.
-/
open_locale big_operators matrix
open finset matrix simple_graph
variables {V α β : Type*}
namespace matrix
/-- `A : matrix V V α` is qualified as an "adjacency matrix" if
(1) every entry of `A` is `0` or `1`,
(2) `A` is symmetric,
(3) every diagonal entry of `A` is `0`. -/
structure is_adj_matrix [has_zero α] [has_one α] (A : matrix V V α) : Prop :=
(zero_or_one : ∀ i j, (A i j) = 0 ∨ (A i j) = 1 . obviously)
(symm : A.is_symm . obviously)
(apply_diag : ∀ i, A i i = 0 . obviously)
namespace is_adj_matrix
variables {A : matrix V V α}
@[simp]
lemma apply_diag_ne [mul_zero_one_class α] [nontrivial α] (h : is_adj_matrix A) (i : V) :
¬ A i i = 1 :=
by simp [h.apply_diag i]
@[simp]
lemma apply_ne_one_iff [mul_zero_one_class α] [nontrivial α] (h : is_adj_matrix A) (i j : V) :
¬ A i j = 1 ↔ A i j = 0 :=
by { obtain (h|h) := h.zero_or_one i j; simp [h] }
@[simp]
lemma apply_ne_zero_iff [mul_zero_one_class α] [nontrivial α] (h : is_adj_matrix A) (i j : V) :
¬ A i j = 0 ↔ A i j = 1 :=
by rw [←apply_ne_one_iff h, not_not]
/-- For `A : matrix V V α` and `h : is_adj_matrix A`,
`h.to_graph` is the simple graph whose adjacency matrix is `A`. -/
@[simps]
def to_graph [mul_zero_one_class α] [nontrivial α] (h : is_adj_matrix A) :
simple_graph V :=
{ adj := λ i j, A i j = 1,
symm := λ i j hij, by rwa h.symm.apply i j,
loopless := λ i, by simp [h] }
instance [mul_zero_one_class α] [nontrivial α] [decidable_eq α] (h : is_adj_matrix A) :
decidable_rel h.to_graph.adj :=
by { simp only [to_graph], apply_instance }
end is_adj_matrix
/-- For `A : matrix V V α`, `A.compl` is supposed to be the adjacency matrix of
the complement graph of the graph induced by `A.adj_matrix`. -/
def compl [has_zero α] [has_one α] [decidable_eq α] [decidable_eq V] (A : matrix V V α) :
matrix V V α :=
λ i j, ite (i = j) 0 (ite (A i j = 0) 1 0)
section compl
variables [decidable_eq α] [decidable_eq V] (A : matrix V V α)
@[simp]
lemma compl_apply_diag [has_zero α] [has_one α] (i : V) :
A.compl i i = 0 :=
by simp [compl]
@[simp]
lemma compl_apply [has_zero α] [has_one α] (i j : V) :
A.compl i j = 0 ∨ A.compl i j = 1 :=
by { unfold compl, split_ifs; simp, }
@[simp]
lemma is_symm_compl [has_zero α] [has_one α] (h : A.is_symm) :
A.compl.is_symm :=
by { ext, simp [compl, h.apply, eq_comm], }
@[simp]
lemma is_adj_matrix_compl [has_zero α] [has_one α] (h : A.is_symm) :
is_adj_matrix A.compl :=
{ symm := by simp [h] }
namespace is_adj_matrix
variable {A}
@[simp]
lemma compl [has_zero α] [has_one α] (h : is_adj_matrix A) :
is_adj_matrix A.compl :=
is_adj_matrix_compl A h.symm
lemma to_graph_compl_eq [mul_zero_one_class α] [nontrivial α] (h : is_adj_matrix A) :
h.compl.to_graph = (h.to_graph)ᶜ :=
begin
ext v w,
cases h.zero_or_one v w with h h;
by_cases hvw : v = w;
simp [matrix.compl, h, hvw]
end
end is_adj_matrix
end compl
end matrix
open matrix
namespace simple_graph
variables (G : simple_graph V) [decidable_rel G.adj]
variables (α)
/-- `adj_matrix G α` is the matrix `A` such that `A i j = (1 : α)` if `i` and `j` are
adjacent in the simple graph `G`, and otherwise `A i j = 0`. -/
def adj_matrix [has_zero α] [has_one α] : matrix V V α
| i j := if (G.adj i j) then 1 else 0
variable {α}
@[simp]
lemma adj_matrix_apply (v w : V) [has_zero α] [has_one α] :
G.adj_matrix α v w = if (G.adj v w) then 1 else 0 := rfl
@[simp]
theorem transpose_adj_matrix [has_zero α] [has_one α] :
(G.adj_matrix α)ᵀ = G.adj_matrix α :=
by { ext, simp [adj_comm] }
@[simp]
lemma is_symm_adj_matrix [has_zero α] [has_one α] :
(G.adj_matrix α).is_symm :=
transpose_adj_matrix G
variable (α)
/-- The adjacency matrix of `G` is an adjacency matrix. -/
@[simp]
lemma is_adj_matrix_adj_matrix [has_zero α] [has_one α] :
(G.adj_matrix α).is_adj_matrix :=
{ zero_or_one := λ i j, by by_cases G.adj i j; simp [h] }
/-- The graph induced by the adjacency matrix of `G` is `G` itself. -/
lemma to_graph_adj_matrix_eq [mul_zero_one_class α] [nontrivial α] :
(G.is_adj_matrix_adj_matrix α).to_graph = G :=
begin
ext,
simp only [is_adj_matrix.to_graph_adj, adj_matrix_apply, ite_eq_left_iff, zero_ne_one],
apply not_not,
end
variables {α} [fintype V]
@[simp]
lemma adj_matrix_dot_product [non_assoc_semiring α] (v : V) (vec : V → α) :
dot_product (G.adj_matrix α v) vec = ∑ u in G.neighbor_finset v, vec u :=
by simp [neighbor_finset_eq_filter, dot_product, sum_filter]
@[simp]
lemma dot_product_adj_matrix [non_assoc_semiring α] (v : V) (vec : V → α) :
dot_product vec (G.adj_matrix α v) = ∑ u in G.neighbor_finset v, vec u :=
by simp [neighbor_finset_eq_filter, dot_product, sum_filter, finset.sum_apply]
@[simp]
lemma adj_matrix_mul_vec_apply [non_assoc_semiring α] (v : V) (vec : V → α) :
((G.adj_matrix α).mul_vec vec) v = ∑ u in G.neighbor_finset v, vec u :=
by rw [mul_vec, adj_matrix_dot_product]
@[simp]
lemma adj_matrix_vec_mul_apply [non_assoc_semiring α] (v : V) (vec : V → α) :
((G.adj_matrix α).vec_mul vec) v = ∑ u in G.neighbor_finset v, vec u :=
begin
rw [← dot_product_adj_matrix, vec_mul],
refine congr rfl _, ext,
rw [← transpose_apply (adj_matrix α G) x v, transpose_adj_matrix],
end
@[simp]
lemma adj_matrix_mul_apply [non_assoc_semiring α] (M : matrix V V α) (v w : V) :
(G.adj_matrix α ⬝ M) v w = ∑ u in G.neighbor_finset v, M u w :=
by simp [mul_apply, neighbor_finset_eq_filter, sum_filter]
@[simp]
variable (α)
theorem trace_adj_matrix [non_assoc_semiring α] [semiring β] [module β α]:
matrix.trace _ β _ (G.adj_matrix α) = 0 :=
by simp
variable {α}
theorem adj_matrix_mul_self_apply_self [non_assoc_semiring α] (i : V) :
((G.adj_matrix α) ⬝ (G.adj_matrix α)) i i = degree G i :=
by simp [degree]
variable {G}
@[simp]
lemma adj_matrix_mul_vec_const_apply [semiring α] {a : α} {v : V} :
(G.adj_matrix α).mul_vec (function.const _ a) v = G.degree v * a :=
by simp [degree]
lemma adj_matrix_mul_vec_const_apply_of_regular [semiring α] {d : ℕ} {a : α}
(hd : G.is_regular_of_degree d) {v : V} :
(G.adj_matrix α).mul_vec (function.const _ a) v = (d * a) :=
by simp [hd v]
end simple_graph
namespace matrix.is_adj_matrix
variables [mul_zero_one_class α] [nontrivial α]
variables {A : matrix V V α} (h : is_adj_matrix A)
/-- If `A` is qualified as an adjacency matrix,
then the adjacency matrix of the graph induced by `A` is itself. -/
lemma adj_matrix_to_graph_eq [decidable_eq α] :
h.to_graph.adj_matrix α = A :=
begin
ext i j,
obtain (h'|h') := h.zero_or_one i j; simp [h'],
end
end matrix.is_adj_matrix
|
[GOAL]
R✝ : Type u_1
inst✝³ : AddMonoidWithOne R✝
inst✝² : CharZero R✝
R : Type u_2
inst✝¹ : Semiring R
inst✝ : CharZero R
q n : ℕ
hn : n ≠ 0
⊢ ↑q ^ n = 1 ↔ q = 1
[PROOFSTEP]
rw [← cast_pow, cast_eq_one]
[GOAL]
R✝ : Type u_1
inst✝³ : AddMonoidWithOne R✝
inst✝² : CharZero R✝
R : Type u_2
inst✝¹ : Semiring R
inst✝ : CharZero R
q n : ℕ
hn : n ≠ 0
⊢ q ^ n = 1 ↔ q = 1
[PROOFSTEP]
exact pow_eq_one_iff hn
[GOAL]
R : Type u_1
inst✝³ : AddMonoidWithOne R
inst✝² : CharZero R
k : Type u_2
inst✝¹ : DivisionSemiring k
inst✝ : CharZero k
m n : ℕ
n_dvd : n ∣ m
⊢ ↑(m / n) = ↑m / ↑n
[PROOFSTEP]
rcases eq_or_ne n 0 with (rfl | hn)
[GOAL]
case inl
R : Type u_1
inst✝³ : AddMonoidWithOne R
inst✝² : CharZero R
k : Type u_2
inst✝¹ : DivisionSemiring k
inst✝ : CharZero k
m : ℕ
n_dvd : 0 ∣ m
⊢ ↑(m / 0) = ↑m / ↑0
[PROOFSTEP]
simp
[GOAL]
case inr
R : Type u_1
inst✝³ : AddMonoidWithOne R
inst✝² : CharZero R
k : Type u_2
inst✝¹ : DivisionSemiring k
inst✝ : CharZero k
m n : ℕ
n_dvd : n ∣ m
hn : n ≠ 0
⊢ ↑(m / n) = ↑m / ↑n
[PROOFSTEP]
exact cast_div n_dvd (cast_ne_zero.2 hn)
[GOAL]
M : Type u_1
inst✝¹ : AddMonoidWithOne M
inst✝ : CharZero M
⊢ 2 ≠ 0
[PROOFSTEP]
have : ((2 : ℕ) : M) ≠ 0 := Nat.cast_ne_zero.2 (by decide)
[GOAL]
M : Type u_1
inst✝¹ : AddMonoidWithOne M
inst✝ : CharZero M
⊢ 2 ≠ 0
[PROOFSTEP]
decide
[GOAL]
M : Type u_1
inst✝¹ : AddMonoidWithOne M
inst✝ : CharZero M
this : ↑2 ≠ 0
⊢ 2 ≠ 0
[PROOFSTEP]
rwa [Nat.cast_two] at this
[GOAL]
R : Type u_1
inst✝² : NonAssocSemiring R
inst✝¹ : NoZeroDivisors R
inst✝ : CharZero R
a✝ a : R
⊢ a + a = 0 ↔ a = 0
[PROOFSTEP]
simp only [(two_mul a).symm, mul_eq_zero, two_ne_zero, false_or_iff]
[GOAL]
R : Type u_1
inst✝² : NonAssocSemiring R
inst✝¹ : NoZeroDivisors R
inst✝ : CharZero R
a✝ a : R
⊢ 0 = bit0 a ↔ a = 0
[PROOFSTEP]
rw [eq_comm]
[GOAL]
R : Type u_1
inst✝² : NonAssocSemiring R
inst✝¹ : NoZeroDivisors R
inst✝ : CharZero R
a✝ a : R
⊢ bit0 a = 0 ↔ a = 0
[PROOFSTEP]
exact bit0_eq_zero
[GOAL]
R : Type u_1
inst✝² : NonAssocRing R
inst✝¹ : NoZeroDivisors R
inst✝ : CharZero R
n : ℕ
a b : R
h : ↑n * a = ↑n * b
⊢ n = 0 ∨ a = b
[PROOFSTEP]
rw [← sub_eq_zero, ← mul_sub, mul_eq_zero, sub_eq_zero] at h
[GOAL]
R : Type u_1
inst✝² : NonAssocRing R
inst✝¹ : NoZeroDivisors R
inst✝ : CharZero R
n : ℕ
a b : R
h✝ : ↑n * a = ↑n * b
h : ↑n = 0 ∨ a = b
⊢ n = 0 ∨ a = b
[PROOFSTEP]
exact_mod_cast h
[GOAL]
R : Type u_1
inst✝² : NonAssocRing R
inst✝¹ : NoZeroDivisors R
inst✝ : CharZero R
n : ℕ
a b : R
h : ↑n * a = ↑n * b
w : n ≠ 0
⊢ a = b
[PROOFSTEP]
simpa [w] using nat_mul_inj h
[GOAL]
R : Type u_1
inst✝² : NonAssocRing R
inst✝¹ : NoZeroDivisors R
inst✝ : CharZero R
a b : R
h : bit0 a = bit0 b
⊢ a = b
[PROOFSTEP]
dsimp [bit0] at h
[GOAL]
R : Type u_1
inst✝² : NonAssocRing R
inst✝¹ : NoZeroDivisors R
inst✝ : CharZero R
a b : R
h : a + a = b + b
⊢ a = b
[PROOFSTEP]
simp only [(two_mul a).symm, (two_mul b).symm] at h
[GOAL]
R : Type u_1
inst✝² : NonAssocRing R
inst✝¹ : NoZeroDivisors R
inst✝ : CharZero R
a b : R
h : 2 * a = 2 * b
⊢ a = b
[PROOFSTEP]
refine' nat_mul_inj' _ two_ne_zero
[GOAL]
R : Type u_1
inst✝² : NonAssocRing R
inst✝¹ : NoZeroDivisors R
inst✝ : CharZero R
a b : R
h : 2 * a = 2 * b
⊢ ↑2 * a = ↑2 * b
[PROOFSTEP]
exact_mod_cast h
[GOAL]
R : Type u_1
inst✝² : NonAssocRing R
inst✝¹ : NoZeroDivisors R
inst✝ : CharZero R
a b : R
h : bit1 a = bit1 b
⊢ a = b
[PROOFSTEP]
simp only [bit1, add_left_inj] at h
[GOAL]
R : Type u_1
inst✝² : NonAssocRing R
inst✝¹ : NoZeroDivisors R
inst✝ : CharZero R
a b : R
h : bit0 a = bit0 b
⊢ a = b
[PROOFSTEP]
exact bit0_injective h
[GOAL]
R : Type u_1
inst✝² : NonAssocRing R
inst✝¹ : NoZeroDivisors R
inst✝ : CharZero R
a : R
⊢ bit1 a = 1 ↔ a = 0
[PROOFSTEP]
rw [show (1 : R) = bit1 0 by simp, bit1_eq_bit1]
[GOAL]
R : Type u_1
inst✝² : NonAssocRing R
inst✝¹ : NoZeroDivisors R
inst✝ : CharZero R
a : R
⊢ 1 = bit1 0
[PROOFSTEP]
simp
[GOAL]
R : Type u_1
inst✝² : NonAssocRing R
inst✝¹ : NoZeroDivisors R
inst✝ : CharZero R
a : R
⊢ 1 = bit1 a ↔ a = 0
[PROOFSTEP]
rw [eq_comm]
[GOAL]
R : Type u_1
inst✝² : NonAssocRing R
inst✝¹ : NoZeroDivisors R
inst✝ : CharZero R
a : R
⊢ bit1 a = 1 ↔ a = 0
[PROOFSTEP]
exact bit1_eq_one
[GOAL]
R : Type u_1
inst✝¹ : DivisionRing R
inst✝ : CharZero R
a : R
⊢ (a + a) / 2 = a
[PROOFSTEP]
rw [← mul_two, mul_div_cancel a two_ne_zero]
[GOAL]
R : Type u_1
inst✝¹ : DivisionRing R
inst✝ : CharZero R
a : R
⊢ a / 2 + a / 2 = a
[PROOFSTEP]
rw [← add_div, half_add_self]
[GOAL]
R : Type u_1
inst✝¹ : DivisionRing R
inst✝ : CharZero R
a : R
⊢ a - a / 2 = a / 2
[PROOFSTEP]
rw [sub_eq_iff_eq_add, add_halves']
[GOAL]
R : Type u_1
inst✝¹ : DivisionRing R
inst✝ : CharZero R
a : R
⊢ a / 2 - a = -(a / 2)
[PROOFSTEP]
rw [← neg_sub, sub_half]
[GOAL]
R : Type u_1
inst✝¹ : AddMonoidWithOne R
inst✝ : CharZero R
m n : ℕ
h : ↑m = ↑n
⊢ m = n
[PROOFSTEP]
rwa [← coe_nat, ← coe_nat n, coe_eq_coe, Nat.cast_inj] at h
[GOAL]
R : Type u_1
inst✝¹ : AddMonoidWithOne R
inst✝ : CharZero R
m n : ℕ
h : ↑m = ↑n
⊢ m = n
[PROOFSTEP]
rwa [← coe_nat, ← coe_nat n, coe_eq_coe, Nat.cast_inj] at h
[GOAL]
R : Type u_1
S : Type u_2
inst✝¹ : NonAssocSemiring R
inst✝ : NonAssocSemiring S
ϕ : R →+* S
hS : CharZero S
a b : ℕ
h : ↑a = ↑b
⊢ ↑a = ↑b
[PROOFSTEP]
rw [← map_natCast ϕ, ← map_natCast ϕ, h]
[GOAL]
R : Type u_1
S : Type u_2
inst✝¹ : NonAssocSemiring R
inst✝ : NonAssocSemiring S
ϕ : R →+* S
hϕ : Function.Injective ↑ϕ
hR : CharZero R
⊢ Function.Injective Nat.cast
[PROOFSTEP]
intro a b h
[GOAL]
R : Type u_1
S : Type u_2
inst✝¹ : NonAssocSemiring R
inst✝ : NonAssocSemiring S
ϕ : R →+* S
hϕ : Function.Injective ↑ϕ
hR : CharZero R
a b : ℕ
h : ↑a = ↑b
⊢ a = b
[PROOFSTEP]
rwa [← @Nat.cast_inj R, ← hϕ.eq_iff, map_natCast ϕ, map_natCast ϕ]
|
In 1971 , Erik Hornung published a study rebutting these views . He points out that in any given period many deities , even minor ones , were described as superior to all others . He also argues that the unspecified " god " in the wisdom texts is a generic term for whichever deity the reader chooses to revere . Although the combinations , manifestations , and iconographies of each god were constantly shifting , they were always restricted to a finite number of forms , never becoming fully interchangeable in a monotheistic or pantheistic way . <unk> , Hornung says , describes Egyptian religion better than other labels . An Egyptian could worship any deity at a particular time and credit it with supreme power in that moment , without denying the other gods or merging them all with the god that he or she focused on . Hornung concludes that the gods were fully unified only in myth , at the time before creation , after which the multitude of gods emerged from a uniform nonexistence .
|
import data.pfun
import phase2.approximation
import phase2.complete_orbit
import phase2.reduction
open cardinal quiver set sum with_bot
open_locale cardinal classical pointwise
universe u
namespace con_nf
variable [params.{u}]
/-!
# Weak approximations
-/
/-- Noncomputably eliminates a disjunction into a (possibly predicative) universe. -/
noncomputable def _root_.or.elim' {α : Sort*} {p q : Prop}
(h : p ∨ q) (f : p → α) (g : q → α) : α :=
if hp : p then f hp else g (h.resolve_left hp)
lemma _root_.or.elim'_left {α : Sort*} {p q : Prop}
(h : p ∨ q) (f : p → α) (g : q → α) (hp : p) : h.elim' f g = f hp :=
by rw [or.elim', dif_pos hp]
lemma _root_.or.elim'_right {α : Sort*} {p q : Prop}
(h : p ∨ q) (f : p → α) (g : q → α) (hp : ¬p) : h.elim' f g = g (h.resolve_left hp) :=
by rw [or.elim', dif_neg hp]
/-- A *weak near-litter approximation* is a partial function from atoms to atoms and a partial
function from litters to near-litters, both of which have small domain.
The image of a litter under the `litter_map` should be interpreted as the intended *precise* image
of this litter under an allowable permutation.
The atom and litter maps should be injective (in suitable senses) and cohere in the sense that
images of atoms in litters are mapped to atoms inside the corresponding near-litters. -/
@[ext] structure weak_near_litter_approx :=
(atom_map : atom →. atom)
(litter_map : litter →. near_litter)
(atom_map_dom_small : small atom_map.dom)
(litter_map_dom_small : small litter_map.dom)
(atom_map_injective : ∀ ⦃a b⦄ ha hb, (atom_map a).get ha = (atom_map b).get hb → a = b)
(litter_map_injective : ∀ ⦃L₁ L₂ : litter⦄ hL₁ hL₂,
(((litter_map L₁).get hL₁ : set atom) ∩ (litter_map L₂).get hL₂).nonempty → L₁ = L₂)
(atom_mem : ∀ (a : atom) ha L hL, a.1 = L ↔ (atom_map a).get ha ∈ (litter_map L).get hL)
/-- A `β`-weak structural approximation is a product that assigns a weak near-litter approximation
to each `β`-extended index. -/
def weak_struct_approx (β : type_index) := extended_index β → weak_near_litter_approx
namespace weak_near_litter_approx
variable (w : weak_near_litter_approx)
/-- A litter that is not allowed to be used as a sandbox because it appears somewhere that
we need to preserve. -/
@[mk_iff] inductive banned_litter : litter → Prop
| atom_dom (a : atom) : (w.atom_map a).dom → banned_litter a.1
| litter_dom (L : litter) : (w.litter_map L).dom → banned_litter L
| atom_map (a : atom) (h) : banned_litter ((w.atom_map a).get h).1
| litter_map (L : litter) (h) : banned_litter ((w.litter_map L).get h).1
| diff (L : litter) (h) (a : atom) :
a ∈ ((w.litter_map L).get h : set atom) \ litter_set ((w.litter_map L).get h).1 →
banned_litter a.1
lemma banned_litter.mem_map (a : atom) (L : litter) (hL)
(ha : a ∈ ((w.litter_map L).get hL : set atom)) : w.banned_litter a.1 :=
begin
by_cases a.1 = ((w.litter_map L).get hL).1,
{ rw h,
exact banned_litter.litter_map L hL, },
{ exact banned_litter.diff L hL a ⟨ha, h⟩, },
end
/-- There are only a small amount of banned litters. -/
lemma banned_litter_small : small {L | w.banned_litter L} :=
begin
simp only [banned_litter_iff, mem_diff, set_like.mem_coe, mem_litter_set],
refine small.union _ (small.union _ (small.union _ (small.union _ _))),
{ refine lt_of_le_of_lt _ w.atom_map_dom_small,
refine ⟨⟨λ a, ⟨_, a.prop.some_spec.1⟩, λ a₁ a₂ h, _⟩⟩,
simp only [subtype.mk_eq_mk, prod.mk.inj_iff] at h,
have := a₁.prop.some_spec.2,
rw h at this,
exact subtype.coe_injective (this.trans a₂.prop.some_spec.2.symm), },
{ refine lt_of_le_of_lt _ w.litter_map_dom_small,
refine ⟨⟨λ L, ⟨_, L.prop⟩, λ L₁ L₂ h, _⟩⟩,
simp only [subtype.mk_eq_mk, prod.mk.inj_iff] at h,
exact subtype.coe_injective h, },
{ refine lt_of_le_of_lt _ w.atom_map_dom_small,
refine ⟨⟨λ L, ⟨_, L.prop.some_spec.some⟩, λ L₁ L₂ h, _⟩⟩,
simp only [subtype.mk_eq_mk, prod.mk.inj_iff] at h,
have := L₁.prop.some_spec.some_spec,
simp_rw h at this,
exact subtype.coe_injective (this.trans L₂.prop.some_spec.some_spec.symm), },
{ refine lt_of_le_of_lt _ w.litter_map_dom_small,
refine ⟨⟨λ L, ⟨_, L.prop.some_spec.some⟩, λ L₁ L₂ h, _⟩⟩,
simp only [subtype.mk_eq_mk, prod.mk.inj_iff] at h,
have := L₁.prop.some_spec.some_spec,
simp_rw h at this,
exact subtype.coe_injective (this.trans L₂.prop.some_spec.some_spec.symm), },
{ have : small ⋃ (L : litter) (h : (w.litter_map L).dom),
((w.litter_map L).get h : set atom) \ litter_set ((w.litter_map L).get h).1,
{ refine small.bUnion _ _,
{ refine lt_of_le_of_lt _ w.litter_map_dom_small,
refine ⟨⟨λ N, ⟨_, N.prop⟩, λ N₁ N₂ h, _⟩⟩,
simp only [subtype.mk_eq_mk, prod.mk.inj_iff] at h,
exact subtype.coe_inj.mp h, },
{ intros L hL,
refine small.mono _ ((w.litter_map L).get hL).2.prop,
exact λ x hx, or.inr hx, }, },
refine lt_of_le_of_lt _ this,
refine ⟨⟨λ L, ⟨L.prop.some_spec.some_spec.some, _⟩, λ L₁ L₂ h, _⟩⟩,
{ simp only [mem_Union],
exact ⟨_, _, L.prop.some_spec.some_spec.some_spec.1⟩, },
simp only [subtype.mk_eq_mk, prod.mk.inj_iff] at h,
have := L₁.prop.some_spec.some_spec.some_spec.2,
rw h at this,
exact subtype.coe_injective
(this.trans L₂.prop.some_spec.some_spec.some_spec.2.symm), },
end
lemma mk_not_banned_litter : #{L | ¬w.banned_litter L} = #μ :=
begin
have := mk_sum_compl {L | w.banned_litter L},
rw [compl_set_of, mk_litter] at this,
rw [← this, add_eq_right],
{ by_contra' h,
have h' := add_le_add (le_of_lt w.banned_litter_small) h.le,
rw this at h',
refine not_lt_of_le h' _,
refine cardinal.add_lt_of_lt μ_strong_limit.is_limit.aleph_0_le κ_lt_μ _,
exact lt_of_le_of_lt κ_regular.aleph_0_le κ_lt_μ, },
{ by_contra' h,
have h' := add_le_add (le_of_lt w.banned_litter_small) h.le,
rw this at h',
refine not_lt_of_le h' _,
refine cardinal.add_lt_of_lt μ_strong_limit.is_limit.aleph_0_le κ_lt_μ _,
exact lt_trans w.banned_litter_small κ_lt_μ, },
end
lemma not_banned_litter_nonempty : nonempty {L | ¬w.banned_litter L} :=
by simp only [← mk_ne_zero_iff, mk_not_banned_litter, ne.def, mk_ne_zero, not_false_iff]
/-- The *sandbox litter* for a weak near-litter approximation is an arbitrarily chosen litter that
isn't banned. -/
noncomputable def sandbox_litter : litter := w.not_banned_litter_nonempty.some
lemma sandbox_litter_not_banned : ¬w.banned_litter w.sandbox_litter :=
w.not_banned_litter_nonempty.some.prop
/-- If `a` is in the domain, this is the atom map. Otherwise, this gives an arbitrary atom. -/
noncomputable def atom_map_or_else (a : atom) : atom := (w.atom_map a).get_or_else (arbitrary atom)
lemma atom_map_or_else_of_dom {a : atom} (ha : (w.atom_map a).dom) :
w.atom_map_or_else a = (w.atom_map a).get ha :=
by rw [atom_map_or_else, part.get_or_else_of_dom]
lemma mk_atom_map_image_le_mk_sandbox :
#(w.atom_map.dom ∆ (w.atom_map_or_else '' w.atom_map.dom) : set atom) ≤
#(litter_set w.sandbox_litter) :=
begin
rw mk_litter_set,
refine le_trans (mk_subtype_mono symm_diff_subset_union) (le_trans (mk_union_le _ _) _),
refine add_le_of_le κ_regular.aleph_0_le _ _,
exact le_of_lt w.atom_map_dom_small,
exact le_trans mk_image_le (le_of_lt w.atom_map_dom_small),
end
lemma disjoint_sandbox :
disjoint (w.atom_map.dom ∪ w.atom_map_or_else '' w.atom_map.dom) (litter_set w.sandbox_litter) :=
begin
rw [disjoint_iff_inter_eq_empty, eq_empty_iff_forall_not_mem],
rintros a ⟨ha₁, ha₂⟩,
rw mem_litter_set at ha₂,
have hnb := w.sandbox_litter_not_banned,
rw ← ha₂ at hnb,
cases ha₁,
{ exact hnb (banned_litter.atom_dom a ha₁), },
{ refine hnb _,
simp only [mem_image, pfun.mem_dom] at ha₁,
obtain ⟨b, ⟨_, hb, rfl⟩, rfl⟩ := ha₁,
rw w.atom_map_or_else_of_dom hb,
exact banned_litter.atom_map b hb, },
end
lemma atom_map_or_else_injective : inj_on w.atom_map_or_else w.atom_map.dom :=
begin
intros a ha b hb h,
rw [w.atom_map_or_else_of_dom ha, w.atom_map_or_else_of_dom hb] at h,
exact w.atom_map_injective ha hb h,
end
/-- If `L` is in the domain, this is the litter map.
Otherwise, this gives an arbitrary near-litter. -/
noncomputable def litter_map_or_else (L : litter) : near_litter :=
(w.litter_map L).get_or_else (arbitrary near_litter)
lemma litter_map_or_else_of_dom {L : litter} (hL : (w.litter_map L).dom) :
w.litter_map_or_else L = (w.litter_map L).get hL :=
by rw [litter_map_or_else, part.get_or_else_of_dom]
noncomputable def rough_litter_map_or_else (L : litter) : litter :=
(w.litter_map_or_else L).1
lemma rough_litter_map_or_else_of_dom {L : litter} (hL : (w.litter_map L).dom) :
w.rough_litter_map_or_else L = ((w.litter_map L).get hL).1 :=
by rw [rough_litter_map_or_else, litter_map_or_else_of_dom]
/-- The induced action of this weak approximation on near-litters. -/
noncomputable def near_litter_map_or_else (N : near_litter) : near_litter :=
⟨(w.litter_map_or_else N.fst).fst,
w.litter_map_or_else N.fst ∆ (w.atom_map_or_else '' litter_set N.fst ∆ N),
begin
rw [is_near_litter, is_near, ← symm_diff_assoc],
exact (w.litter_map_or_else N.fst).snd.prop.symm_diff (small.image N.2.prop),
end⟩
/-- A weak approximation is precise at a litter in its domain if all atoms in the symmetric
difference of its image are accounted for. -/
@[mk_iff] structure precise_at {L : litter} (hL : (w.litter_map L).dom) : Prop :=
(diff : ((w.litter_map L).get hL : set atom) ∆ litter_set ((w.litter_map L).get hL).1 ⊆
w.atom_map.ran)
(fwd : ∀ a ha, (w.atom_map a).get ha ∈ litter_set L → (w.atom_map ((w.atom_map a).get ha)).dom)
(back : w.atom_map.dom ∩ (w.litter_map L).get hL ⊆ w.atom_map.ran)
/-- A weak approximation is precise if it is precise at every litter in its domain. -/
def precise : Prop := ∀ ⦃L⦄ (hL : (w.litter_map L).dom), w.precise_at hL
/-!
## Induced litter permutation
-/
lemma mk_dom_symm_diff_le :
#↥(w.litter_map.dom ∆ (w.rough_litter_map_or_else '' w.litter_map.dom)) ≤
#{L : litter | ¬w.banned_litter L} :=
begin
rw mk_not_banned_litter,
refine le_trans (le_of_lt _) κ_le_μ,
exact small.symm_diff w.litter_map_dom_small w.litter_map_dom_small.image,
end
lemma aleph_0_le_not_banned_litter : ℵ₀ ≤ #{L | ¬w.banned_litter L} :=
begin
rw mk_not_banned_litter,
exact μ_strong_limit.is_limit.aleph_0_le,
end
lemma disjoint_dom_not_banned_litter :
disjoint (w.litter_map.dom ∪ w.rough_litter_map_or_else '' w.litter_map.dom)
{L : litter | ¬w.banned_litter L} :=
begin
simp only [set.disjoint_left, mem_union, pfun.mem_dom, mem_image, mem_set_of_eq, not_not],
rintros _ (⟨_, hL, rfl⟩ | ⟨L, ⟨_, hL, rfl⟩, rfl⟩),
{ exact banned_litter.litter_dom _ hL, },
{ rw w.rough_litter_map_or_else_of_dom hL,
exact banned_litter.litter_map _ hL, },
end
lemma rough_litter_map_or_else_inj_on : inj_on w.rough_litter_map_or_else w.litter_map.dom :=
begin
intros L₁ hL₁ L₂ hL₂ h,
rw [w.rough_litter_map_or_else_of_dom hL₁, w.rough_litter_map_or_else_of_dom hL₂] at h,
exact w.litter_map_injective hL₁ hL₂ (near_litter.inter_nonempty_of_fst_eq_fst h),
end
/-- A local permutation on the set of litters that occur in the domain or range of `w`.
This permutes both flexible and inflexible litters. -/
noncomputable def litter_perm' : local_perm litter :=
local_perm.complete
w.rough_litter_map_or_else
w.litter_map.dom
{L | ¬w.banned_litter L}
w.mk_dom_symm_diff_le
w.aleph_0_le_not_banned_litter
w.disjoint_dom_not_banned_litter
w.rough_litter_map_or_else_inj_on
def id_on_banned (s : set litter) : local_perm litter := {
to_fun := id,
inv_fun := id,
domain := {L | w.banned_litter L} \ s,
to_fun_domain' := λ L h, h,
inv_fun_domain' := λ L h, h,
left_inv' := λ L h, rfl,
right_inv' := λ L h, rfl,
}
noncomputable def litter_perm : local_perm litter :=
local_perm.piecewise w.litter_perm' (w.id_on_banned w.litter_perm'.domain)
(by rw ← set.subset_compl_iff_disjoint_left; exact λ L h, h.2)
lemma litter_perm'_apply_eq (L : litter) (hL : L ∈ w.litter_map.dom) :
w.litter_perm' L = w.rough_litter_map_or_else L :=
local_perm.complete_apply_eq _ _ _ hL
lemma litter_perm_apply_eq (L : litter) (hL : L ∈ w.litter_map.dom) :
w.litter_perm L = w.rough_litter_map_or_else L :=
begin
rw ← w.litter_perm'_apply_eq L hL,
exact local_perm.piecewise_apply_eq_left (or.inl (or.inl hL)),
end
lemma litter_perm'_domain_small : small w.litter_perm'.domain :=
begin
refine small.union (small.union w.litter_map_dom_small w.litter_map_dom_small.image) _,
rw small,
rw cardinal.mk_congr (local_perm.sandbox_subset_equiv _ _),
simp only [mk_sum, mk_prod, mk_denumerable, lift_aleph_0, lift_uzero, lift_id],
refine add_lt_of_lt κ_regular.aleph_0_le _ _;
refine (mul_lt_of_lt κ_regular.aleph_0_le (lt_of_le_of_lt Λ_limit.aleph_0_le Λ_lt_κ) _);
refine lt_of_le_of_lt (mk_subtype_mono (diff_subset _ _)) _,
exact w.litter_map_dom_small,
exact w.litter_map_dom_small.image,
end
lemma litter_perm_domain_small : small w.litter_perm.domain :=
small.union w.litter_perm'_domain_small (small.mono (diff_subset _ _) w.banned_litter_small)
variables {α : Λ} [position_data.{}] [phase_2_assumptions α] {β : Iio α} {A : extended_index β}
lemma mk_not_banned_litter_and_flexible : #{L | ¬w.banned_litter L ∧ flexible α L A} = #μ :=
begin
refine le_antisymm ((mk_subtype_le _).trans mk_litter.le) _,
by_contra,
rw not_le at h,
have h₁ := cardinal.le_mk_diff_add_mk {L | flexible α L A} {L | w.banned_litter L},
rw [mk_flexible, diff_eq, inter_comm] at h₁,
have h₂ := add_lt_of_lt μ_strong_limit.is_limit.aleph_0_le h
(lt_trans w.banned_litter_small κ_lt_μ),
exact h₁.not_lt h₂,
end
lemma mk_dom_inter_flexible_symm_diff_le :
#↥((w.litter_map.dom ∩ {L | flexible α L A}) ∆
(w.rough_litter_map_or_else '' (w.litter_map.dom ∩ {L | flexible α L A}))) ≤
#{L : litter | ¬w.banned_litter L ∧ flexible α L A} :=
begin
rw mk_not_banned_litter_and_flexible,
refine le_trans (le_of_lt _) κ_le_μ,
exact small.symm_diff
(small.mono (inter_subset_left _ _) w.litter_map_dom_small)
(small.mono (inter_subset_left _ _) w.litter_map_dom_small).image,
end
lemma aleph_0_le_not_banned_litter_and_flexible : ℵ₀ ≤ #{L | ¬w.banned_litter L ∧ flexible α L A} :=
begin
rw mk_not_banned_litter_and_flexible,
exact μ_strong_limit.is_limit.aleph_0_le,
end
lemma disjoint_dom_inter_flexible_not_banned_litter :
disjoint ((w.litter_map.dom ∩ {L | flexible α L A})
∪ w.rough_litter_map_or_else '' (w.litter_map.dom ∩ {L | flexible α L A}))
{L : litter | ¬w.banned_litter L ∧ flexible α L A} :=
begin
refine disjoint_of_subset _ (inter_subset_left _ _) w.disjoint_dom_not_banned_litter,
rintros a (ha | ⟨b, hb, rfl⟩),
exact or.inl ha.1,
exact or.inr ⟨b, hb.1, rfl⟩,
end
lemma rough_litter_map_or_else_inj_on_dom_inter_flexible :
inj_on w.rough_litter_map_or_else (w.litter_map.dom ∩ {L | flexible α L A}) :=
w.rough_litter_map_or_else_inj_on.mono (inter_subset_left _ _)
noncomputable def flexible_litter_perm (A : extended_index β) :
local_perm litter :=
local_perm.complete
w.rough_litter_map_or_else
(w.litter_map.dom ∩ {L | flexible α L A})
{L | ¬w.banned_litter L ∧ flexible α L A}
w.mk_dom_inter_flexible_symm_diff_le
w.aleph_0_le_not_banned_litter_and_flexible
w.disjoint_dom_inter_flexible_not_banned_litter
w.rough_litter_map_or_else_inj_on_dom_inter_flexible
lemma flexible_litter_perm_apply_eq (L : litter)
(hL₁ : L ∈ w.litter_map.dom) (hL₂ : flexible α L A) :
w.flexible_litter_perm A L = w.rough_litter_map_or_else L :=
local_perm.complete_apply_eq _ _ _ ⟨hL₁, hL₂⟩
lemma flexible_litter_perm_domain_small : small (w.flexible_litter_perm A).domain :=
begin
refine small.union (small.union _ _) _,
{ exact w.litter_map_dom_small.mono (inter_subset_left _ _) },
{ exact (w.litter_map_dom_small.mono (inter_subset_left _ _)).image, },
{ rw small,
rw cardinal.mk_congr (local_perm.sandbox_subset_equiv _ _),
simp only [mk_sum, mk_prod, mk_denumerable, lift_aleph_0, lift_uzero, lift_id],
refine add_lt_of_lt κ_regular.aleph_0_le _ _;
refine (mul_lt_of_lt κ_regular.aleph_0_le (lt_of_le_of_lt Λ_limit.aleph_0_le Λ_lt_κ) _);
refine lt_of_le_of_lt (mk_subtype_mono (diff_subset _ _)) _,
exact w.litter_map_dom_small.mono (inter_subset_left _ _),
exact (w.litter_map_dom_small.mono (inter_subset_left _ _)).image, },
end
/-!
# Completed permutations
-/
/-- A local permutation induced by completing the orbits of atoms in a weak near-litter
approximation. This function creates forward and backward images of atoms in the *sandbox litter*,
a litter which is away from the domain and range of the approximation in question, so it should
not interfere with other constructions. -/
noncomputable def complete_atom_perm : local_perm atom :=
local_perm.complete
w.atom_map_or_else
w.atom_map.dom
(litter_set w.sandbox_litter)
w.mk_atom_map_image_le_mk_sandbox
(by simpa only [mk_litter_set] using κ_regular.aleph_0_le)
w.disjoint_sandbox
w.atom_map_or_else_injective
lemma sandbox_subset_small : small (local_perm.sandbox_subset
w.mk_atom_map_image_le_mk_sandbox
(by simpa only [mk_litter_set] using κ_regular.aleph_0_le)) :=
begin
rw small,
rw cardinal.mk_congr (local_perm.sandbox_subset_equiv _ _),
simp only [mk_sum, mk_prod, mk_denumerable, lift_aleph_0, lift_uzero, lift_id],
refine add_lt_of_lt κ_regular.aleph_0_le _ _;
refine (mul_lt_of_lt κ_regular.aleph_0_le (lt_of_le_of_lt Λ_limit.aleph_0_le Λ_lt_κ) _);
refine lt_of_le_of_lt (mk_subtype_mono (diff_subset _ _)) _,
{ exact w.atom_map_dom_small, },
{ exact lt_of_le_of_lt mk_image_le w.atom_map_dom_small, },
end
lemma complete_atom_perm_domain_small : small w.complete_atom_perm.domain :=
small.union (small.union w.atom_map_dom_small
(lt_of_le_of_lt mk_image_le w.atom_map_dom_small)) w.sandbox_subset_small
/-- A near-litter approximation built from this weak near-litter approximation.
Its action on atoms matches that of the weak approximation, and its rough action on litters
matches the given litter permutation. -/
noncomputable def complete (A : extended_index β) : near_litter_approx := {
atom_perm := w.complete_atom_perm,
litter_perm := w.flexible_litter_perm A,
domain_small := λ L, small.mono (inter_subset_right _ _) w.complete_atom_perm_domain_small,
}
variable {litter_perm : local_perm litter}
lemma complete_atom_perm_apply_eq {a : atom} (ha : (w.atom_map a).dom) :
w.complete_atom_perm a = (w.atom_map a).get ha :=
by rwa [complete_atom_perm, local_perm.complete_apply_eq, atom_map_or_else_of_dom]
lemma complete_smul_atom_eq {a : atom} (ha : (w.atom_map a).dom) :
w.complete A • a = (w.atom_map a).get ha := w.complete_atom_perm_apply_eq ha
@[simp] lemma complete_smul_litter_eq (L : litter) :
w.complete A • L = w.flexible_litter_perm A L := rfl
lemma smul_atom_eq
{π : near_litter_perm} (hπ : (w.complete A).exactly_approximates π)
{a : atom} (ha : (w.atom_map a).dom) :
π • a = (w.atom_map a).get ha :=
by rw [← hπ.map_atom a (or.inl (or.inl ha)), w.complete_smul_atom_eq ha]
lemma smul_to_near_litter_eq_of_precise_at
{π : near_litter_perm} (hπ : (w.complete A).exactly_approximates π)
{L : litter} (hL : (w.litter_map L).dom) (hw : w.precise_at hL)
(hπL : π • L = ((w.litter_map L).get hL).1) :
π • L.to_near_litter = (w.litter_map L).get hL :=
begin
refine set_like.coe_injective _,
ext a : 1,
simp only [mem_smul_set_iff_inv_smul_mem, near_litter_perm.coe_smul, litter.coe_to_near_litter,
mem_litter_set, set_like.mem_coe],
split,
{ intro ha,
by_cases π.is_exception a,
{ suffices h' : π⁻¹ • a ∈ w.atom_map.dom,
{ rw w.atom_mem _ h' L hL at ha,
have := hπ.map_atom _ (or.inl (or.inl h')),
rw w.complete_smul_atom_eq h' at this,
rw [this, smul_inv_smul] at ha,
exact ha, },
rw ← hπ.symm_map_atom a (hπ.exception_mem _ h) at ha ⊢,
obtain ((hdom | hdom) | hdom) := (w.complete A).atom_perm.symm.map_domain
(hπ.exception_mem _ h),
{ exact hdom, },
{ obtain ⟨c, hc₁, hc₂⟩ := hdom,
rw w.atom_map_or_else_of_dom hc₁ at hc₂,
have := hw.fwd c hc₁ (by rwa hc₂),
rw hc₂ at this,
exact this, },
{ cases w.sandbox_litter_not_banned _,
rw ← eq_of_mem_litter_set_of_mem_litter_set ha
(local_perm.sandbox_subset_subset _ _ hdom),
exact banned_litter.litter_dom L hL, }, },
{ by_contradiction h',
simp only [near_litter_perm.is_exception, mem_litter_set, not_or_distrib, not_not, ha] at h,
obtain ⟨b, hb, rfl⟩ := hw.diff
(or.inr ⟨by rw [← hπL, h.2, smul_inv_smul, mem_litter_set], h'⟩),
refine h' ((w.atom_mem b hb L hL).mp _),
have := hπ.map_atom b (or.inl (or.inl hb)),
rw [w.complete_smul_atom_eq hb] at this,
rw [this, inv_smul_smul] at ha,
exact ha, }, },
{ intro ha,
-- TODO: probably possible to clean up `by_cases` into a `suffices`
by_cases π⁻¹ • a ∈ w.atom_map.dom,
{ rw w.atom_mem _ h L hL,
have := hπ.map_atom _ (or.inl (or.inl h)),
rw w.complete_smul_atom_eq h at this,
rw [this, smul_inv_smul],
exact ha, },
have haL : a ∈ litter_set ((w.litter_map L).get hL).fst,
{ by_contradiction h',
obtain ⟨b, hb, rfl⟩ := hw.diff (or.inl ⟨ha, h'⟩),
have := hπ.map_atom b (or.inl (or.inl hb)),
rw [w.complete_smul_atom_eq hb] at this,
rw [this, inv_smul_smul] at h,
exact h hb, },
by_contradiction h',
have hex : π.is_exception a,
{ refine or.inr (λ h'', h' (h''.trans _)),
rw [inv_smul_eq_iff, hπL],
exact haL, },
obtain ((hdom | ⟨b, hb₁, hb₂⟩) | hdom) := hπ.exception_mem a hex,
{ obtain ⟨b, hb₁, hb₂⟩ := hw.back ⟨hdom, ha⟩,
have := hπ.map_atom b (or.inl (or.inl hb₁)),
rw [w.complete_smul_atom_eq hb₁] at this,
rw [this, smul_eq_iff_eq_inv_smul] at hb₂,
rw hb₂ at hb₁,
exact h hb₁, },
{ rw w.atom_map_or_else_of_dom hb₁ at hb₂,
have := hπ.map_atom b (or.inl (or.inl hb₁)),
rw [w.complete_smul_atom_eq hb₁, hb₂, ← inv_smul_eq_iff] at this,
rw this at h,
exact h hb₁, },
{ refine w.sandbox_litter_not_banned _,
rw eq_of_mem_litter_set_of_mem_litter_set (local_perm.sandbox_subset_subset _ _ hdom) haL,
exact banned_litter.litter_map L hL, }, },
end
lemma smul_near_litter_eq_of_precise_at
{π : near_litter_perm} (hπ : (w.complete A).exactly_approximates π)
{N : near_litter} (hN : (w.litter_map N.1).dom) (hw : w.precise_at hN)
(hπL : π • N.1 = ((w.litter_map N.1).get hN).1) :
((π • N : near_litter) : set atom) = (w.litter_map N.1).get hN ∆ (π • (litter_set N.1 ∆ N)) :=
begin
refine (near_litter_perm.smul_near_litter_eq_smul_symm_diff_smul _ _).trans _,
rw ← w.smul_to_near_litter_eq_of_precise_at hπ hN hw hπL,
refl,
end
end weak_near_litter_approx
namespace weak_struct_approx
section
def precise {β : type_index} (w : weak_struct_approx β) : Prop := ∀ B, (w B).precise
variables {α : Λ} [position_data.{}] [phase_2_assumptions α] {β : Iio α} (w : weak_struct_approx β)
noncomputable def complete : struct_approx β :=
λ B, (w B).complete B
lemma smul_atom_eq
{π : struct_perm β} (hπ : w.complete.exactly_approximates π)
{a : atom} {B : extended_index β} (ha : ((w B).atom_map a).dom) :
struct_perm.derivative B π • a = ((w B).atom_map a).get ha :=
begin
have := (w B).smul_atom_eq (hπ B) ha,
rw struct_perm.of_bot_smul at this,
exact this,
end
lemma smul_to_near_litter_eq_of_precise (hw : w.precise)
{π : struct_perm β} (hπ : w.complete.exactly_approximates π)
{L : litter} {B : extended_index β} (hL : ((w B).litter_map L).dom)
(hπL : struct_perm.derivative B π • L = (((w B).litter_map L).get hL).1) :
struct_perm.derivative B π • L.to_near_litter = ((w B).litter_map L).get hL :=
begin
have := (w B).smul_to_near_litter_eq_of_precise_at (hπ B) hL (hw B hL) _,
{ rw struct_perm.of_bot_smul at this,
exact this, },
{ rw struct_perm.of_bot_smul,
exact hπL, },
end
lemma smul_near_litter_eq_of_precise (hw : w.precise)
{π : struct_perm β} (hπ : w.complete.exactly_approximates π)
{N : near_litter} {B : extended_index β} (hN : ((w B).litter_map N.1).dom)
(hπL : struct_perm.derivative B π • N.1 = (((w B).litter_map N.1).get hN).1) :
((struct_perm.derivative B π • N : near_litter) : set atom) =
((w B).litter_map N.1).get hN ∆ (struct_perm.derivative B π • (litter_set N.1 ∆ N)) :=
begin
have := (w B).smul_near_litter_eq_of_precise_at (hπ B) hN (hw B hN) _,
{ rw struct_perm.of_bot_smul at this,
exact this, },
{ rw struct_perm.of_bot_smul,
exact hπL, },
end
end
variables {α : Λ} [position_data.{}] [phase_2_assumptions α] {β : Iio α}
/-- A weak structural approximation *supports* a tangle if it defines an image for everything
in the reduction of its designated support. -/
structure supports (w : weak_struct_approx β) (t : tangle β) : Prop :=
(atom_mem : ∀ a B, (inl a, B) ∈ reduction α (designated_support t : set (support_condition β)) →
((w B).atom_map a).dom)
(litter_mem : ∀ (L : litter) B,
(inr L.to_near_litter, B) ∈ reduction α (designated_support t : set (support_condition β)) →
((w B).litter_map L).dom)
/-- Two weak structural approximations are *compatible* for a tangle if they both support the
tangle and agree on the reduction of its designated support. -/
structure compatible (w v : weak_struct_approx β) (t : tangle β) : Prop :=
(w_supports : w.supports t)
(v_supports : v.supports t)
(atom_map : ∀ a B ha, ((w B).atom_map a).get (w_supports.atom_mem a B ha) =
((v B).atom_map a).get (v_supports.atom_mem a B ha))
(litter_map : ∀ L B hL, ((w B).litter_map L).get (w_supports.litter_mem L B hL) =
((v B).litter_map L).get (v_supports.litter_mem L B hL))
/-- The action of a weak structural approximation on support conditions. -/
noncomputable def support_condition_map_or_else (w : weak_struct_approx β) :
support_condition β → support_condition β
| (inl a, B) := (inl ((w B).atom_map_or_else a), B)
| (inr N, B) := (inr ((w B).near_litter_map_or_else N), B)
def coherent_coe (w : weak_struct_approx β) (t : tangle β) : Prop :=
∀ {π : allowable β} (hπ : w.complete.exactly_approximates π.to_struct_perm)
(γ : Iic α) (δ ε : Iio α) (hδ : (δ : Λ) < γ) (hε : (ε : Λ) < γ) (hδε : δ ≠ ε)
(C : path (β : type_index) γ) (t' : tangle δ) (hL)
(hc₁ : ∃ (d : support_condition β), d ∈ (designated_support t).carrier ∧
relation.refl_trans_gen (constrains α β)
(inr (f_map (coe_ne_coe.mpr (coe_ne' hδε)) t').to_near_litter,
(C.cons (coe_lt hε)).cons (bot_lt_coe _)) d)
(hc₂ : ∀ (c : support_condition δ), c ∈ (designated_support t').carrier →
π • (show support_condition β, from (c.fst, (C.cons (coe_lt hδ)).comp c.snd)) =
w.support_condition_map_or_else (c.fst, (C.cons (coe_lt hδ)).comp c.snd)),
f_map (subtype.coe_injective.ne (Iio.coe_injective.ne hδε))
(show tangle δ, from
(show allowable δ, from allowable_derivative (γ : Iic_index α) δ (coe_lt_coe.mpr hδ)
(allowable.derivative
(show path ((β : Iic_index α) : type_index) (γ : Iic_index α), from C) π)) • t') =
(((w ((C.cons (coe_lt hε)).cons (bot_lt_coe _))).litter_map
(f_map (subtype.coe_injective.ne (Iio.coe_injective.ne hδε)) t')).get hL).fst
def coherent_bot (w : weak_struct_approx β) : Prop :=
∀ {π : allowable β} (hπ : w.complete.exactly_approximates π.to_struct_perm)
(γ : Iic α) (ε : Iio α) (hε : (ε : Λ) < γ)
(C : path (β : type_index) γ) (a : tangle ⊥) (hL)
(hc : struct_perm.derivative (C.cons (bot_lt_coe _)) π.to_struct_perm • a =
(w (C.cons (bot_lt_coe _))).atom_map_or_else a),
f_map (show ((⊥ : Iio_index α) : type_index) ≠ (ε : Iio_index α),
from subtype.coe_injective.ne Iio_index.bot_ne_coe)
((struct_perm.derivative (C.cons (bot_lt_coe _))) π.to_struct_perm • a) =
(((w ((C.cons (coe_lt hε)).cons (bot_lt_coe _))).litter_map
(f_map (show (⊥ : type_index) ≠ (ε : Λ), from bot_ne_coe) a)).get hL).fst
@[mk_iff] structure coherent (w : weak_struct_approx β) (t : tangle β) : Prop :=
(coe : w.coherent_coe t)
(bot : w.coherent_bot)
lemma smul_litter_eq_of_supports (w : weak_struct_approx β)
{π : allowable β} (hπ : w.complete.exactly_approximates π.to_struct_perm)
(t : tangle β) (hwc : w.coherent t) (hws : w.supports t)
(d : support_condition β) (hd : d ∈ designated_support t)
(B : extended_index β) (L : litter)
(ih : ∀ (e : support_condition β),
relation.trans_gen (constrains α β) e (inr L.to_near_litter, B) →
π • e = w.support_condition_map_or_else e)
(hc : relation.refl_trans_gen (constrains α β) (inr L.to_near_litter, B) d) :
struct_perm.derivative B π.to_struct_perm • L =
(((w B).litter_map L).get
(hws.litter_mem L B ⟨⟨d, hd, refl_trans_gen_near_litter hc⟩, reduced.mk_litter _ _⟩)).fst :=
begin
by_cases hflex : inflexible α L B,
rw inflexible_iff at hflex,
obtain (⟨γ, δ, ε, hδ, hε, hδε, C, t', rfl, rfl⟩ | ⟨γ, ε, hε, C, a, rfl, rfl⟩) := hflex,
{ have hc₂ := λ c hc, ih _ (relation.trans_gen.single $ constrains.f_map hδ hε hδε C t' c hc),
have := smul_f_map (δ : Iio_index α) ε _ _ (Iio.coe_injective.ne hδε)
(allowable.derivative
(show path ((β : Iic_index α) : type_index) (γ : Iic_index α), from C) π) t',
rw [← allowable.derivative_cons_apply, allowable.derivative_smul,
← struct_perm.derivative_bot_smul, ← struct_perm.derivative_cons] at this,
exact this.trans (hwc.coe hπ γ δ ε hδ hε hδε C t' _ ⟨d, hd, hc⟩ hc₂), },
{ have hc : (_, _) = (_, _) := ih _ (relation.trans_gen.single $ constrains.f_map_bot hε C a),
simp only [smul_inl, prod.mk.inj_iff, eq_self_iff_true, and_true] at hc,
have := smul_f_map (⊥ : Iio_index α) ε _ _ _
(allowable.derivative
(show path ((β : Iic_index α) : type_index) (γ : Iic_index α), from C) π) a,
rw [← allowable.derivative_cons_apply, allowable.derivative_smul,
← struct_perm.derivative_bot_smul, ← struct_perm.derivative_cons] at this,
rw ← hwc.bot hπ γ ε hε C a _ hc,
refine this.trans _,
swap 3,
refine congr_arg _ _,
swap 3,
{ rw ← allowable.derivative_cons_apply,
rw ← allowable.derivative_smul
(show path ((β : Iic_index α) : type_index) ((⊥ : Iic_index α) : type_index),
from C.cons (bot_lt_coe _)) π a,
congr,
sorry, },
all_goals { sorry, }, },
{ have := hws.litter_mem L B ⟨⟨d, hd, refl_trans_gen_near_litter hc⟩, reduced.mk_litter _ _⟩,
rw [← struct_perm.of_bot_smul, ← (hπ B).map_litter _ (or.inl (or.inl ⟨this, hflex⟩))],
refine ((w B).complete_smul_litter_eq L).trans _,
rw [(w B).flexible_litter_perm_apply_eq, (w B).rough_litter_map_or_else_of_dom],
exact this,
exact hflex, },
end
lemma smul_support_condition_eq (w : weak_struct_approx β) (hw : w.precise)
{π : allowable β} (hπ : w.complete.exactly_approximates π.to_struct_perm)
(t : tangle β) (hwc : w.coherent t) (hws : w.supports t)
(c d : support_condition β)
(hc : relation.refl_trans_gen (constrains α β) c d)
(hd : d ∈ designated_support t) :
π • c = w.support_condition_map_or_else c :=
begin
revert d,
refine (constrains_wf α β).trans_gen.induction c _,
rintros c ih d hc hd,
obtain ⟨a | N, B⟩ := c,
{ refine prod.ext _ rfl,
change inl _ = inl _,
refine congr_arg inl _,
rw [w.smul_atom_eq hπ (hws.atom_mem a B ⟨⟨d, hd, hc⟩, reduced.mk_atom a B⟩),
weak_near_litter_approx.atom_map_or_else_of_dom], },
refine prod.ext _ rfl,
change inr _ = inr _,
refine congr_arg inr (set_like.coe_injective _),
have ih' := λ e he, ih e (relation.trans_gen.single he) d
(relation.refl_trans_gen.head he hc) hd,
rw w.smul_near_litter_eq_of_precise hw hπ (hws.litter_mem N.1 B _) _,
{ simp only [weak_near_litter_approx.near_litter_map_or_else,
near_litter.coe_mk, subtype.coe_mk],
rw (w B).litter_map_or_else_of_dom (hws.litter_mem N.1 B _),
congr' 1,
ext a : 1,
rw [mem_smul_set, mem_image],
split,
{ rintro ⟨b, hb₁, hb₂⟩,
have : (_, _) = (_, _) := ih' _ (constrains.symm_diff N _ hb₁ B),
simp only [smul_inl, smul_inv_smul, prod.mk.inj_iff] at this,
rw this.1 at hb₂,
exact ⟨b, hb₁, hb₂⟩, },
{ rintro ⟨b, hb₁, hb₂⟩,
have : (_, _) = (_, _) := ih' _ (constrains.symm_diff N _ hb₁ B),
simp only [smul_inl, smul_inv_smul, prod.mk.inj_iff] at this,
rw ← this.1 at hb₂,
exact ⟨b, hb₁, hb₂⟩, },
{ exact ⟨⟨d, hd, refl_trans_gen_near_litter hc⟩, reduced.mk_litter _ _⟩, }, },
refine w.smul_litter_eq_of_supports hπ t hwc hws d hd B N.1 _ (refl_trans_gen_near_litter hc),
exact λ e he, ih e (trans_gen_near_litter he) d
(relation.refl_trans_gen.trans he.to_refl (refl_trans_gen_near_litter hc)) hd,
end
lemma smul_eq_smul_tangle (w v : weak_struct_approx β)
(hw : w.precise) (hv : v.precise)
(t : tangle β) (h : compatible w v t)
(hwc : w.coherent t) (hvc : v.coherent t)
{πw πv : allowable β} (hπw : w.complete.exactly_approximates πw.to_struct_perm)
(hπv : v.complete.exactly_approximates πv.to_struct_perm) :
πw • t = πv • t :=
begin
rw [smul_eq_iff_eq_inv_smul, smul_smul],
symmetry,
refine (designated_support t).supports _ _,
intros c hc,
rw [mul_smul, inv_smul_eq_iff],
symmetry,
rw smul_support_condition_eq w hw hπw t hwc h.w_supports c c relation.refl_trans_gen.refl hc,
rw smul_support_condition_eq v hv hπv t hvc h.v_supports c c relation.refl_trans_gen.refl hc,
obtain ⟨a | N, B⟩ := c,
{ simp only [support_condition_map_or_else, prod.mk.inj_iff, eq_self_iff_true, and_true],
rw [(w B).atom_map_or_else_of_dom, (v B).atom_map_or_else_of_dom],
refine h.atom_map a B _,
exact ⟨⟨_, hc, relation.refl_trans_gen.refl⟩, reduced.mk_atom _ _⟩, },
{ simp only [support_condition_map_or_else, prod.mk.inj_iff, eq_self_iff_true, and_true,
weak_near_litter_approx.near_litter_map_or_else],
refine set_like.coe_injective _,
simp only [near_litter.coe_mk, subtype.coe_mk],
congr' 1,
{ rw [(w B).litter_map_or_else_of_dom, (v B).litter_map_or_else_of_dom, h.litter_map N.1 B _],
exact ⟨⟨_, hc, refl_trans_gen_near_litter relation.refl_trans_gen.refl⟩,
reduced.mk_litter _ _⟩, },
{ ext a : 1,
rw [mem_image, mem_image],
split;
rintro ⟨b, hb₁, hb₂⟩;
refine ⟨b, hb₁, _⟩;
rw [← hb₂, (w B).atom_map_or_else_of_dom, (v B).atom_map_or_else_of_dom],
{ refine (h.atom_map b B _).symm,
exact ⟨⟨_, hc, relation.refl_trans_gen.single (constrains.symm_diff N b hb₁ B)⟩,
reduced.mk_atom _ _⟩, },
{ refine h.atom_map b B _,
exact ⟨⟨_, hc, relation.refl_trans_gen.single (constrains.symm_diff N b hb₁ B)⟩,
reduced.mk_atom _ _⟩, }, }, },
end
end weak_struct_approx
end con_nf
|
lemma non_extensible_Borsuk_map: fixes a :: "'a :: euclidean_space" assumes "compact s" and cin: "c \<in> components(- s)" and boc: "bounded c" and "a \<in> c" shows "\<not> (\<exists>g. continuous_on (s \<union> c) g \<and> g ` (s \<union> c) \<subseteq> sphere 0 1 \<and> (\<forall>x \<in> s. g x = inverse(norm(x - a)) *\<^sub>R (x - a)))" |
State Before: ι : Type ?u.804263
β : Type u
α : Type v
γ : Type w
s✝ s₁ s₂ : Finset α
a✝ : α
f✝ g : α → β
inst✝ : CommMonoid β
s : Finset α
f : α → β
a : α
hp : ∏ x in s, f x = 1
h1 : ∀ (x : α), x ∈ s → x ≠ a → f x = 1
⊢ ∀ (x : α), x ∈ s → f x = 1 State After: ι : Type ?u.804263
β : Type u
α : Type v
γ : Type w
s✝ s₁ s₂ : Finset α
a✝ : α
f✝ g : α → β
inst✝ : CommMonoid β
s : Finset α
f : α → β
a : α
hp : ∏ x in s, f x = 1
h1 : ∀ (x : α), x ∈ s → x ≠ a → f x = 1
x : α
hx : x ∈ s
⊢ f x = 1 Tactic: intro x hx State Before: ι : Type ?u.804263
β : Type u
α : Type v
γ : Type w
s✝ s₁ s₂ : Finset α
a✝ : α
f✝ g : α → β
inst✝ : CommMonoid β
s : Finset α
f : α → β
a : α
hp : ∏ x in s, f x = 1
h1 : ∀ (x : α), x ∈ s → x ≠ a → f x = 1
x : α
hx : x ∈ s
⊢ f x = 1 State After: case pos
ι : Type ?u.804263
β : Type u
α : Type v
γ : Type w
s✝ s₁ s₂ : Finset α
a✝ : α
f✝ g : α → β
inst✝ : CommMonoid β
s : Finset α
f : α → β
a : α
hp : ∏ x in s, f x = 1
h1 : ∀ (x : α), x ∈ s → x ≠ a → f x = 1
x : α
hx : x ∈ s
h : x = a
⊢ f x = 1
case neg
ι : Type ?u.804263
β : Type u
α : Type v
γ : Type w
s✝ s₁ s₂ : Finset α
a✝ : α
f✝ g : α → β
inst✝ : CommMonoid β
s : Finset α
f : α → β
a : α
hp : ∏ x in s, f x = 1
h1 : ∀ (x : α), x ∈ s → x ≠ a → f x = 1
x : α
hx : x ∈ s
h : ¬x = a
⊢ f x = 1 Tactic: by_cases h : x = a State Before: case pos
ι : Type ?u.804263
β : Type u
α : Type v
γ : Type w
s✝ s₁ s₂ : Finset α
a✝ : α
f✝ g : α → β
inst✝ : CommMonoid β
s : Finset α
f : α → β
a : α
hp : ∏ x in s, f x = 1
h1 : ∀ (x : α), x ∈ s → x ≠ a → f x = 1
x : α
hx : x ∈ s
h : x = a
⊢ f x = 1 State After: case pos
ι : Type ?u.804263
β : Type u
α : Type v
γ : Type w
s✝ s₁ s₂ : Finset α
a✝ : α
f✝ g : α → β
inst✝ : CommMonoid β
s : Finset α
f : α → β
a : α
hp : ∏ x in s, f x = 1
h1 : ∀ (x : α), x ∈ s → x ≠ a → f x = 1
x : α
hx : x ∈ s
h : x = a
⊢ f a = 1 Tactic: rw [h] State Before: case pos
ι : Type ?u.804263
β : Type u
α : Type v
γ : Type w
s✝ s₁ s₂ : Finset α
a✝ : α
f✝ g : α → β
inst✝ : CommMonoid β
s : Finset α
f : α → β
a : α
hp : ∏ x in s, f x = 1
h1 : ∀ (x : α), x ∈ s → x ≠ a → f x = 1
x : α
hx : x ∈ s
h : x = a
⊢ f a = 1 State After: case pos
ι : Type ?u.804263
β : Type u
α : Type v
γ : Type w
s✝ s₁ s₂ : Finset α
a✝ : α
f✝ g : α → β
inst✝ : CommMonoid β
s : Finset α
f : α → β
a : α
hp : ∏ x in s, f x = 1
h1 : ∀ (x : α), x ∈ s → x ≠ a → f x = 1
x : α
hx : a ∈ s
h : x = a
⊢ f a = 1 Tactic: rw [h] at hx State Before: case pos
ι : Type ?u.804263
β : Type u
α : Type v
γ : Type w
s✝ s₁ s₂ : Finset α
a✝ : α
f✝ g : α → β
inst✝ : CommMonoid β
s : Finset α
f : α → β
a : α
hp : ∏ x in s, f x = 1
h1 : ∀ (x : α), x ∈ s → x ≠ a → f x = 1
x : α
hx : a ∈ s
h : x = a
⊢ f a = 1 State After: case pos
ι : Type ?u.804263
β : Type u
α : Type v
γ : Type w
s✝ s₁ s₂ : Finset α
a✝ : α
f✝ g : α → β
inst✝ : CommMonoid β
s : Finset α
f : α → β
a : α
hp : f a = 1
h1 : ∀ (x : α), x ∈ s → x ≠ a → f x = 1
x : α
hx : a ∈ s
h : x = a
⊢ f a = 1 Tactic: rw [← prod_subset (singleton_subset_iff.2 hx) fun t ht ha => h1 t ht (not_mem_singleton.1 ha),
prod_singleton] at hp State Before: case pos
ι : Type ?u.804263
β : Type u
α : Type v
γ : Type w
s✝ s₁ s₂ : Finset α
a✝ : α
f✝ g : α → β
inst✝ : CommMonoid β
s : Finset α
f : α → β
a : α
hp : f a = 1
h1 : ∀ (x : α), x ∈ s → x ≠ a → f x = 1
x : α
hx : a ∈ s
h : x = a
⊢ f a = 1 State After: no goals Tactic: exact hp State Before: case neg
ι : Type ?u.804263
β : Type u
α : Type v
γ : Type w
s✝ s₁ s₂ : Finset α
a✝ : α
f✝ g : α → β
inst✝ : CommMonoid β
s : Finset α
f : α → β
a : α
hp : ∏ x in s, f x = 1
h1 : ∀ (x : α), x ∈ s → x ≠ a → f x = 1
x : α
hx : x ∈ s
h : ¬x = a
⊢ f x = 1 State After: no goals Tactic: exact h1 x hx h |
corollary path_connected_open_diff_countable: fixes S :: "'a::euclidean_space set" assumes "2 \<le> DIM('a)" "open S" "connected S" "countable T" shows "path_connected(S - T)" |
using Test, Yao
@testset "easybuld" begin
include("easybuild/easybuild.jl")
end |
from statistics import mean
import numpy as np
class CountKey:
def __init__(self, f, keys):
self.keys = keys
self.file = f+".txt"
self.count_key()
def count_key(self):
handle=open(self.file, 'r')
lines=handle.readlines()
for key in self.keys:
score=0
for line in lines:
tokens=line.strip().split()
for token in tokens:
if token == key:
score += 1
print("{} {} {}".format(self.file,key,score))
ck=CountKey("output_coco_nokey", ["man","toilet"])
ck=CountKey("output_coco_man", ["man","toilet"])
ck=CountKey("output_coco_toilet", ["man","toilet"])
ck=CountKey("output_coco_nokey2", ["man","toilet"])
ck=CountKey("output_coco_man2", ["man","toilet"])
ck=CountKey("output_coco_toilet2", ["man","toilet"])
ck=CountKey("output_enmini_nokey", ["good","bad"])
ck=CountKey("output_enmini_good", ["good","bad"])
ck=CountKey("output_enmini_bad", ["good","bad"])
ck=CountKey("output_enmini_nokey2", ["good","bad"])
ck=CountKey("output_enmini_good2", ["good","bad"])
ck=CountKey("output_enmini_bad2", ["good","bad"])
ck=CountKey("output_mr_nokey", ["good","bad"])
ck=CountKey("output_mr_good", ["good","bad"])
ck=CountKey("output_mr_bad", ["good","bad"])
ck=CountKey("output_mr_nokey2", ["good","bad"])
ck=CountKey("output_mr_good2", ["good","bad"])
ck=CountKey("output_mr_bad2", ["good","bad"])
|
And leaden @-@ eyed despairs ;
|
State Before: M✝ : Type ?u.27123
N✝ : Type ?u.27126
G : Type ?u.27129
A : Type ?u.27132
B : Type ?u.27135
α : Type ?u.27138
β : Type ?u.27141
γ : Type ?u.27144
δ : Type ?u.27147
M : Type u_1
N : Type u_2
inst✝² : MulOneClass N
inst✝¹ : SMul M N
inst✝ : IsScalarTower M N N
x : M
y : N
⊢ x • 1 * y = x • y State After: no goals Tactic: rw [smul_mul_assoc, one_mul] |
# James Rekow
# Example script for creating a meanOverDOC data frame and using the data frame to create some basic plots
library(ggplot2)
source("meanOverDOCCreatorOrderCheck.r")
source("meanDOCCreatorSubgroupsCheck.r")
# create data frames containing mean overlap values
# meanOverDOC = meanOverDOCCreatorOrderCheck()
# meanDOC = meanDOCCreatorSubgroupsCheck()
# read in data from file
meanOverDOC = read.csv("meanOverDOCOrderCheck.csv")
meanDOC = read.csv("meanDOC_SubgroupsCheck.csv")
# make meanOrder and numSubgroups factors for plotting purposes
meanOverDOC$meanOrder = as.factor(meanOverDOC$meanOrder)
meanDOC$numSubgroups = as.factor(meanDOC$numSubgroups)
## Using varying mean order from meanOverDOC
# Plot lambda / M vs. meanOver
p1 = ggplot(meanOverDOC, aes(x = lambdaOverM, y = meanOver, col = meanOrder)) +
geom_point() +
geom_smooth(method = "loess", se = FALSE) +
labs(title = "Mean Overlap VS lambda / M",
subtitle = "meanOrder is the Mean Order of the Vertices in the Random Connectivity Graph Related to Each DOC.
meanOrder = 2 * numEdges / numVertices")
## Plot fitCurve (1 - exp(-lambda / M)) vs. meanOver
p2 = ggplot(meanOverDOC, aes(x = fitCurve, y = meanOver, col = meanOrder)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE) +
labs(title = "Mean Overlap VS fitCurve = 1 - exp(-lambda / M)",
subtitle = "meanOrder is the Mean Order of the Vertices in the Random Connectivity Graph Related to Each DOC.
meanOrder = 2 * numEdges / numVertices")
## Using varying number of subgroups from meanDOC
# Plot lambda / M vs. meanOver
p3 = ggplot(meanDOC, aes(x = lambdaOverM, y = meanOver, col = numSubgroups)) +
geom_point() +
geom_smooth(method = "loess", se = FALSE) +
labs(title = "Mean Overlap VS lambda / M")
# Plot lambda / M vs. meanDiss
p4 = ggplot(meanDOC, aes(x = lambdaOverM, y = meanDiss, col = numSubgroups)) +
geom_point() +
geom_smooth(method = "loess", se = FALSE) +
labs(title = "Mean Dissimilarity VS lambda / M")
# plot the created ggplot objects
dev.new()
plot(p1)
dev.new()
plot(p2)
dev.new()
plot(p3)
dev.new()
plot(p4)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.