text
stringlengths 0
3.34M
|
---|
/-
Copyright (c) 2019 Neil Strickland. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Neil Strickland, Yury Kudryashov
-/
import algebra.group.semiconj
/-!
# Commuting pairs of elements in monoids
We define the predicate `commute a b := a * b = b * a` and provide some operations on terms `(h :
commute a b)`. E.g., if `a`, `b`, and c are elements of a semiring, and that `hb : commute a b` and
`hc : commute a c`. Then `hb.pow_left 5` proves `commute (a ^ 5) b` and `(hb.pow_right 2).add_right
(hb.mul_right hc)` proves `commute a (b ^ 2 + b * c)`.
Lean does not immediately recognise these terms as equations, so for rewriting we need syntax like
`rw [(hb.pow_left 5).eq]` rather than just `rw [hb.pow_left 5]`.
This file defines only a few operations (`mul_left`, `inv_right`, etc). Other operations
(`pow_right`, field inverse etc) are in the files that define corresponding notions.
## Implementation details
Most of the proofs come from the properties of `semiconj_by`.
-/
/-- Two elements commute if `a * b = b * a`. -/
@[to_additive add_commute "Two elements additively commute if `a + b = b + a`"]
def commute {S : Type*} [has_mul S] (a b : S) : Prop := semiconj_by a b b
namespace commute
section has_mul
variables {S : Type*} [has_mul S]
/-- Equality behind `commute a b`; useful for rewriting. -/
@[to_additive] protected theorem eq {a b : S} (h : commute a b) : a * b = b * a := h
/-- Any element commutes with itself. -/
@[refl, simp, to_additive] protected theorem refl (a : S) : commute a a := eq.refl (a * a)
/-- If `a` commutes with `b`, then `b` commutes with `a`. -/
@[symm, to_additive] protected theorem symm {a b : S} (h : commute a b) : commute b a :=
eq.symm h
@[to_additive]
protected theorem symm_iff {a b : S} : commute a b ↔ commute b a :=
⟨commute.symm, commute.symm⟩
end has_mul
section semigroup
variables {S : Type*} [semigroup S] {a b c : S}
/-- If `a` commutes with both `b` and `c`, then it commutes with their product. -/
@[simp, to_additive] theorem mul_right (hab : commute a b) (hac : commute a c) :
commute a (b * c) :=
hab.mul_right hac
/-- If both `a` and `b` commute with `c`, then their product commutes with `c`. -/
@[simp, to_additive] theorem mul_left (hac : commute a c) (hbc : commute b c) :
commute (a * b) c :=
hac.mul_left hbc
@[to_additive] protected lemma right_comm (h : commute b c) (a : S) :
a * b * c = a * c * b :=
by simp only [mul_assoc, h.eq]
@[to_additive] protected lemma left_comm (h : commute a b) (c) :
a * (b * c) = b * (a * c) :=
by simp only [← mul_assoc, h.eq]
end semigroup
@[to_additive]
protected
section mul_one_class
variables {M : Type*} [mul_one_class M]
@[simp, to_additive] theorem one_right (a : M) : commute a 1 := semiconj_by.one_right a
@[simp, to_additive] theorem one_left (a : M) : commute 1 a := semiconj_by.one_left a
end mul_one_class
section monoid
variables {M : Type*} [monoid M]
@[to_additive] theorem units_inv_right {a : M} {u : units M} : commute a u → commute a ↑u⁻¹ :=
semiconj_by.units_inv_right
@[simp, to_additive] theorem units_inv_right_iff {a : M} {u : units M} :
commute a ↑u⁻¹ ↔ commute a u :=
semiconj_by.units_inv_right_iff
@[to_additive] theorem units_inv_left {u : units M} {a : M} : commute ↑u a → commute ↑u⁻¹ a :=
semiconj_by.units_inv_symm_left
@[simp, to_additive]
theorem units_inv_left_iff {u : units M} {a : M}: commute ↑u⁻¹ a ↔ commute ↑u a :=
semiconj_by.units_inv_symm_left_iff
variables {u₁ u₂ : units M}
@[to_additive]
theorem units_coe : commute u₁ u₂ → commute (u₁ : M) u₂ := semiconj_by.units_coe
@[to_additive]
theorem units_of_coe : commute (u₁ : M) u₂ → commute u₁ u₂ := semiconj_by.units_of_coe
@[simp, to_additive]
theorem units_coe_iff : commute (u₁ : M) u₂ ↔ commute u₁ u₂ := semiconj_by.units_coe_iff
end monoid
section group
variables {G : Type*} [group G] {a b : G}
@[to_additive]
theorem inv_right : commute a b → commute a b⁻¹ := semiconj_by.inv_right
@[simp, to_additive]
theorem inv_right_iff : commute a b⁻¹ ↔ commute a b := semiconj_by.inv_right_iff
@[to_additive] theorem inv_left : commute a b → commute a⁻¹ b := semiconj_by.inv_symm_left
@[simp, to_additive]
theorem inv_left_iff : commute a⁻¹ b ↔ commute a b := semiconj_by.inv_symm_left_iff
@[to_additive]
theorem inv_inv : commute a b → commute a⁻¹ b⁻¹ := semiconj_by.inv_inv_symm
@[simp, to_additive]
theorem inv_inv_iff : commute a⁻¹ b⁻¹ ↔ commute a b := semiconj_by.inv_inv_symm_iff
@[to_additive]
protected theorem inv_mul_cancel (h : commute a b) : a⁻¹ * b * a = b :=
by rw [h.inv_left.eq, inv_mul_cancel_right]
@[to_additive]
theorem inv_mul_cancel_assoc (h : commute a b) : a⁻¹ * (b * a) = b :=
by rw [← mul_assoc, h.inv_mul_cancel]
@[to_additive]
protected theorem mul_inv_cancel (h : commute a b) : a * b * a⁻¹ = b :=
by rw [h.eq, mul_inv_cancel_right]
@[to_additive]
theorem mul_inv_cancel_assoc (h : commute a b) : a * (b * a⁻¹) = b :=
by rw [← mul_assoc, h.mul_inv_cancel]
end group
end commute
section comm_group
variables {G : Type*} [comm_group G] (a b : G)
@[simp, to_additive] lemma mul_inv_cancel_comm : a * b * a⁻¹ = b :=
(commute.all a b).mul_inv_cancel
@[simp, to_additive] lemma mul_inv_cancel_comm_assoc : a * (b * a⁻¹) = b :=
(commute.all a b).mul_inv_cancel_assoc
@[simp, to_additive] lemma inv_mul_cancel_comm : a⁻¹ * b * a = b :=
(commute.all a b).inv_mul_cancel
@[simp, to_additive] lemma inv_mul_cancel_comm_assoc : a⁻¹ * (b * a) = b :=
(commute.all a b).inv_mul_cancel_assoc
end comm_group
|
For what reason is the use of words of wisdom (prophetic words in regards to the future) critical and for what purpose is it imperative to know about the significance of their utilization in ministry? Since wisdom causes us to comprehend the difference between what is good and bad in God’s sight, procuring and practicing wisdom will prompt bliss and longevity of life (Proverbs 3:13-16). It is a vital quality God needs to find in us. Below mentioned are some other additional factors showing the importance of utilization of words of wisdom throughout our life and ministry as well.
Above all else, it is exceptionally basic to comprehend that the blessings of the Holy Spirit don’t work at our will, however, must be showed when we live our lives dedicated to God and His ministry on earth, as indicated by the covenant we have entered through the forfeit of Jesus on the cross. We surrendered our lives to him and we ought to anticipate that His life to flow over us.
Words of Wisdom are explicit messages from God with respect to what’s to come. When we are in charge of a specific ministry and genuinely position ourselves by words and deeds in like manner as leaders, we discover God directing us through explicit words in regards to the way, he needs us to take, either by advising us of what the fate of one way brings or by empowering us by the brilliant promises of another.
Educating of the Word of God is fragmented without Words of Wisdom. Like Words of Knowledge, Words of Wisdom make the Bible a LIVING WORD. Instructing and lecturing the Gospel without being available to this region, renders the Bible an unimportant manual, while Words of Wisdom open the endless element of the Word for all to perceive what lies ahead. At last, we can just really motivate the people of God to make an explicit move with respect to their lives, when the message being lectured rises above the regular and focuses to the prize that lies ahead.
Those who are following us, do as such as a result of the blessing we have, they will confront genuine circumstances where they should hear a word from God in regards to their future. God will address them through us when we take responsibility for the position of a prophet over their lives. Individuals need to get notification from God with respect to a job offer, a voyaging plan, a business deal, and so forth. Besides, we should work in Words of Wisdom with the end goal to prepare devotees to trust in God and the blessing. This fortifies their confidence.
Regardless of whether it is healing or throwing out evil spirits, Words of Wisdom are the projectiles of the prophet to announce to the sickness and the demon where he is going. We are called to lecture the Good News not exclusively to men, yet in addition to evil spirits and to this fallen nature.
What God proclaims through us today will set the stage or the establishment on which future ages will assemble. Except if we are available to God what needs to state today in regards to the future, we will announce the demise of our service with us on earth.
At long last, Words of Wisdom keep us reminded on our actual character and calling. They advise us that we don’t have a place with this age yet to the one to come. The utilization of Words of Wisdom turns us resistant to the stresses of the present life. Through confidence, it keeps us strolling on the waters of unceasing life.
Paul Davis is a renowned healing minister. He lives in New York, where he primarily teaches, writes, and offers workshops on journaling and spiritual growth. Paul heads a number of healing ministries New York in the past. Paul makes every effort to combine his own faith with the world’s spiritual teachings and to facilitate the world make well from its past record of religious abuse.
Which Car Wash Is Best For Your Car?
|
(* Title: Inductive definition of termination
Author: Tobias Nipkow, 2001/2006
Maintainer: Tobias Nipkow
*)
theory Termi imports Lang begin
subsection{*Termination*}
text{*Although partial correctness appeals because of its simplicity,
in many cases one would like the additional assurance that the command
is guaranteed to termiate if started in a state that satisfies the
precondition. Even to express this we need to define when a command is
guaranteed to terminate. We can do this without modifying our existing
semantics by merely adding a second inductively defined judgement
@{text"c\<down>s"} that expresses guaranteed termination of @{term c}
started in state @{term s}: *}
inductive
termi :: "com \<Rightarrow> state \<Rightarrow> bool" (infixl "\<down>" 50)
where
(*<*)Do[iff]:(*>*) "f s \<noteq> {} \<Longrightarrow> Do f \<down> s"
| (*<*)Semi[intro!]:(*>*) "\<lbrakk> c\<^sub>1 \<down> s\<^sub>0; \<forall>s\<^sub>1. s\<^sub>0 -c\<^sub>1\<rightarrow> s\<^sub>1 \<longrightarrow> c\<^sub>2 \<down> s\<^sub>1 \<rbrakk> \<Longrightarrow> (c\<^sub>1;c\<^sub>2) \<down> s\<^sub>0"
| (*<*)IfT[intro,simp]:(*>*) "\<lbrakk> b s; c\<^sub>1 \<down> s \<rbrakk> \<Longrightarrow> IF b THEN c\<^sub>1 ELSE c\<^sub>2 \<down> s"
| (*<*)IfF[intro,simp]:(*>*) "\<lbrakk> \<not>b s; c\<^sub>2 \<down> s \<rbrakk> \<Longrightarrow> IF b THEN c\<^sub>1 ELSE c\<^sub>2 \<down> s"
| (*<*)WhileFalse:(*>*) "\<not>b s \<Longrightarrow> WHILE b DO c \<down> s"
| (*<*)WhileTrue:(*>*) "\<lbrakk> b s; c \<down> s; \<forall>t. s -c\<rightarrow> t \<longrightarrow> WHILE b DO c \<down> t \<rbrakk> \<Longrightarrow> WHILE b DO c \<down> s"
| (*<*)Local:(*>*) "c \<down> f s \<Longrightarrow> LOCAL f;c;g \<down> s"
lemma [iff]: "((c\<^sub>1;c\<^sub>2) \<down> s\<^sub>0) = (c\<^sub>1 \<down> s\<^sub>0 \<and> (\<forall>s\<^sub>1. s\<^sub>0 -c\<^sub>1\<rightarrow> s\<^sub>1 \<longrightarrow> c\<^sub>2 \<down> s\<^sub>1))"
apply(rule iffI)
prefer 2
apply(best intro:termi.intros)
apply(erule termi.cases)
apply blast+
done
lemma [iff]: "(IF b THEN c\<^sub>1 ELSE c\<^sub>2 \<down> s) =
((if b s then c\<^sub>1 else c\<^sub>2) \<down> s)"
apply simp
apply(rule conjI)
apply(rule impI)
apply(rule iffI)
prefer 2
apply(blast intro:termi.intros)
apply(erule termi.cases)
apply blast+
apply(rule impI)
apply(rule iffI)
prefer 2
apply(blast intro:termi.intros)
apply(erule termi.cases)
apply blast+
done
lemma [iff]: "(LOCAL f;c;g \<down> s) = (c \<down> f s)"
by(fast elim: termi.cases intro:termi.intros)
lemma termi_while_lemma[rule_format]:
"w\<down>fk \<Longrightarrow>
(\<forall>k b c. fk = f k \<and> w = WHILE b DO c \<and> (\<forall>i. f i -c\<rightarrow> f(Suc i))
\<longrightarrow> (\<exists>i. \<not>b(f i)))"
apply(erule termi.induct)
apply simp_all
apply blast
apply blast
done
lemma termi_while:
"\<lbrakk> (WHILE b DO c) \<down> f k; \<forall>i. f i -c\<rightarrow> f(Suc i) \<rbrakk> \<Longrightarrow> \<exists>i. \<not>b(f i)"
by(blast intro:termi_while_lemma)
lemma wf_termi: "wf {(t,s). WHILE b DO c \<down> s \<and> b s \<and> s -c\<rightarrow> t}"
apply(subst wf_iff_no_infinite_down_chain)
apply(rule notI)
apply clarsimp
apply(insert termi_while)
apply blast
done
end
|
In peacetime , the commander of the land forces is the minister of defense , while in wartime , the President of Romania becomes the supreme commander of the armed forces . The main combat formations of Romania are the 2nd Infantry Division Getica , and the 4th Infantry Division Gemina . Until 2015 the Romanian land forces fielded a third division , namely the 1st Division Dacia . Before June 2008 , the 1st and 4th divisions were known as the 1st Territorial Army Corps and the 4th Territorial Army Corps and in turn they used to be called the 1st Army and 4th Army prior to 2000 . However due to their personnel having been reduced considerably in order to reach compatibility with NATO standards they were renamed and reorganized as divisions . In 2010 , the Joint HQ command was renamed as 2nd Infantry Division Getica and received units from the 1st and the 4th Infantry divisions .
|
theory RT
imports Main FL.Finite_Linear
begin
section \<open>Refusal Traces\<close>
datatype 'e rtevent = TickRT | EventRT 'e
datatype 'e rtrefusal = RefNil ("\<bullet>\<^sub>\<R>\<^sub>\<T>") | RefSet "'e set" ("[_]\<^sub>\<R>\<^sub>\<T>")
lemma rtrefusal_cases2:
"(x = (\<bullet>\<^sub>\<R>\<^sub>\<T>, \<bullet>\<^sub>\<R>\<^sub>\<T>) \<Longrightarrow> P) \<Longrightarrow>
(\<And>Y. x = (\<bullet>\<^sub>\<R>\<^sub>\<T>, [Y]\<^sub>\<R>\<^sub>\<T>) \<Longrightarrow> P) \<Longrightarrow>
(\<And>X. x = ([X]\<^sub>\<R>\<^sub>\<T>, \<bullet>\<^sub>\<R>\<^sub>\<T>) \<Longrightarrow> P) \<Longrightarrow>
(\<And>X Y. x = ([X]\<^sub>\<R>\<^sub>\<T>, [Y]\<^sub>\<R>\<^sub>\<T>) \<Longrightarrow> P) \<Longrightarrow> P"
by (cases x, auto, case_tac a, case_tac b, simp_all, case_tac b, simp_all)
datatype 'e rttrace = RTRefusal "'e rtrefusal" ("\<langle>_\<rangle>\<^sub>\<R>\<^sub>\<T>") | RTEvent "'e rtrefusal" "'e" "'e rttrace" ("_ #\<^sub>\<R>\<^sub>\<T> _ #\<^sub>\<R>\<^sub>\<T> _" [65,66,67] 65)
fun in_rtrefusal :: "'e \<Rightarrow> 'e rtrefusal \<Rightarrow> bool" (infix "\<in>\<^sub>\<R>\<^sub>\<T>" 50) where
"e \<in>\<^sub>\<R>\<^sub>\<T> \<bullet>\<^sub>\<R>\<^sub>\<T> = False" |
"e \<in>\<^sub>\<R>\<^sub>\<T> [X]\<^sub>\<R>\<^sub>\<T> = (e \<in> X)"
fun subset_refusal :: "'e rtrefusal \<Rightarrow> 'e rtrefusal \<Rightarrow> bool" (infix "\<subseteq>\<^sub>\<R>\<^sub>\<T>" 50) where
"\<bullet>\<^sub>\<R>\<^sub>\<T> \<subseteq>\<^sub>\<R>\<^sub>\<T> y = True" |
"[X]\<^sub>\<R>\<^sub>\<T> \<subseteq>\<^sub>\<R>\<^sub>\<T> \<bullet>\<^sub>\<R>\<^sub>\<T> = False" |
"[X]\<^sub>\<R>\<^sub>\<T> \<subseteq>\<^sub>\<R>\<^sub>\<T> [Y]\<^sub>\<R>\<^sub>\<T> = (X \<subseteq> Y)"
type_synonym 'e rtprocess = "'e rttrace set"
fun rtWF :: "'e rttrace \<Rightarrow> bool" where
"rtWF \<langle>X\<rangle>\<^sub>\<R>\<^sub>\<T> = True" |
"rtWF (X #\<^sub>\<R>\<^sub>\<T> e #\<^sub>\<R>\<^sub>\<T> \<rho>) = (\<not> e \<in>\<^sub>\<R>\<^sub>\<T> X \<and> rtWF \<rho>)"
lemma rttrace_cases:
"(x = \<langle>\<bullet>\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T> \<Longrightarrow> P) \<Longrightarrow>
(\<And>X. x = \<langle>[X]\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T> \<Longrightarrow> P) \<Longrightarrow>
(\<And>a \<rho>. x = \<bullet>\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> a #\<^sub>\<R>\<^sub>\<T> \<rho> \<Longrightarrow> P) \<Longrightarrow>
(\<And>X a \<rho>. x = [X]\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> a #\<^sub>\<R>\<^sub>\<T> \<rho> \<Longrightarrow> P) \<Longrightarrow> P"
by (cases x, auto, case_tac x1, auto, case_tac x21, auto)
lemma rttrace_cases2:
"(x = (\<langle>\<bullet>\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T>, \<langle>\<bullet>\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T>) \<Longrightarrow> P) \<Longrightarrow>
(\<And>Y. x = (\<langle>\<bullet>\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T>, \<langle>[Y]\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T>) \<Longrightarrow> P) \<Longrightarrow>
(\<And>b \<sigma>. x = (\<langle>\<bullet>\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T>, \<bullet>\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> b #\<^sub>\<R>\<^sub>\<T> \<sigma>) \<Longrightarrow> P) \<Longrightarrow>
(\<And>Y b \<sigma>. x = (\<langle>\<bullet>\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T>, [Y]\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> b #\<^sub>\<R>\<^sub>\<T> \<sigma>) \<Longrightarrow> P) \<Longrightarrow>
(\<And>X. x = (\<langle>[X]\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T>, \<langle>\<bullet>\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T>) \<Longrightarrow> P) \<Longrightarrow>
(\<And>X Y. x = (\<langle>[X]\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T>, \<langle>[Y]\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T>) \<Longrightarrow> P) \<Longrightarrow>
(\<And>X b \<sigma>. x = (\<langle>[X]\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T>, \<bullet>\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> b #\<^sub>\<R>\<^sub>\<T> \<sigma>) \<Longrightarrow> P) \<Longrightarrow>
(\<And>X Y b \<sigma>. x = (\<langle>[X]\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T>, [Y]\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> b #\<^sub>\<R>\<^sub>\<T> \<sigma>) \<Longrightarrow> P) \<Longrightarrow>
(\<And>a \<rho>. x = (\<bullet>\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> a #\<^sub>\<R>\<^sub>\<T> \<rho>, \<langle>\<bullet>\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T>) \<Longrightarrow> P) \<Longrightarrow>
(\<And>a \<rho> Y. x = (\<bullet>\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> a #\<^sub>\<R>\<^sub>\<T> \<rho>, \<langle>[Y]\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T>) \<Longrightarrow> P) \<Longrightarrow>
(\<And>a \<rho> b \<sigma>. x = (\<bullet>\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> a #\<^sub>\<R>\<^sub>\<T> \<rho>, \<bullet>\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> b #\<^sub>\<R>\<^sub>\<T> \<sigma>) \<Longrightarrow> P) \<Longrightarrow>
(\<And>a \<rho> Y b \<sigma>. x = (\<bullet>\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> a #\<^sub>\<R>\<^sub>\<T> \<rho>, [Y]\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> b #\<^sub>\<R>\<^sub>\<T> \<sigma>) \<Longrightarrow> P) \<Longrightarrow>
(\<And>X a \<rho>. x = ([X]\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> a #\<^sub>\<R>\<^sub>\<T> \<rho>, \<langle>\<bullet>\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T>) \<Longrightarrow> P) \<Longrightarrow>
(\<And>X a \<rho> Y. x = ([X]\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> a #\<^sub>\<R>\<^sub>\<T> \<rho>, \<langle>[Y]\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T>) \<Longrightarrow> P) \<Longrightarrow>
(\<And>X a \<rho> b \<sigma>. x = ([X]\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> a #\<^sub>\<R>\<^sub>\<T> \<rho>, \<bullet>\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> b #\<^sub>\<R>\<^sub>\<T> \<sigma>) \<Longrightarrow> P) \<Longrightarrow>
(\<And>X a \<rho> Y b \<sigma>. x = ([X]\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> a #\<^sub>\<R>\<^sub>\<T> \<rho>, [Y]\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> b #\<^sub>\<R>\<^sub>\<T> \<sigma>) \<Longrightarrow> P) \<Longrightarrow> P"
by (cases x, auto, case_tac a rule:rttrace_cases, simp_all, (case_tac b rule:rttrace_cases, simp_all)+)
section \<open>Healthiness Conditions\<close>
subsection \<open>MRT0\<close>
definition MRT0 :: "'e rtprocess \<Rightarrow> bool" where
"MRT0 P = (\<langle> \<bullet>\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T> \<in> P)"
subsection \<open>RT1\<close>
fun leq_rttrace :: "'e rttrace \<Rightarrow> 'e rttrace \<Rightarrow> bool" (infix "\<le>\<^sub>\<R>\<^sub>\<T>" 50) where
"\<langle> \<bullet>\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T> \<le>\<^sub>\<R>\<^sub>\<T> \<sigma> = True" |
"\<langle> [X]\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T> \<le>\<^sub>\<R>\<^sub>\<T> \<langle> [Y]\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T> = (X \<subseteq> Y)" |
"\<langle> [X]\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T> \<le>\<^sub>\<R>\<^sub>\<T> \<langle> \<bullet>\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T> = False" |
"\<langle> [X]\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T> \<le>\<^sub>\<R>\<^sub>\<T> ( [Y]\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> b #\<^sub>\<R>\<^sub>\<T> \<sigma>) = (X \<subseteq> Y)" |
"\<langle> [X]\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T> \<le>\<^sub>\<R>\<^sub>\<T> ( \<bullet>\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> b #\<^sub>\<R>\<^sub>\<T> \<sigma>) = False" |
"( \<bullet>\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> a #\<^sub>\<R>\<^sub>\<T> \<rho>) \<le>\<^sub>\<R>\<^sub>\<T> ( \<bullet>\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> b #\<^sub>\<R>\<^sub>\<T> \<sigma>) = (a = b \<and> \<rho> \<le>\<^sub>\<R>\<^sub>\<T> \<sigma>)" |
"( \<bullet>\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> a #\<^sub>\<R>\<^sub>\<T> \<rho>) \<le>\<^sub>\<R>\<^sub>\<T> ( [Y]\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> b #\<^sub>\<R>\<^sub>\<T> \<sigma>) = (a = b \<and> \<rho> \<le>\<^sub>\<R>\<^sub>\<T> \<sigma>)" |
"( [X]\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> a #\<^sub>\<R>\<^sub>\<T> \<rho>) \<le>\<^sub>\<R>\<^sub>\<T> ( [Y]\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> b #\<^sub>\<R>\<^sub>\<T> \<sigma>) = (X \<subseteq> Y \<and> a = b \<and> \<rho> \<le>\<^sub>\<R>\<^sub>\<T> \<sigma>)" |
"( [X]\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> a #\<^sub>\<R>\<^sub>\<T> \<rho>) \<le>\<^sub>\<R>\<^sub>\<T> ( \<bullet>\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> b #\<^sub>\<R>\<^sub>\<T> \<sigma>) = False" |
"( x #\<^sub>\<R>\<^sub>\<T> a #\<^sub>\<R>\<^sub>\<T> \<rho>) \<le>\<^sub>\<R>\<^sub>\<T> \<langle>y\<rangle>\<^sub>\<R>\<^sub>\<T> = False"
lemma leq_rttrace_refl: "x \<le>\<^sub>\<R>\<^sub>\<T> x"
by (induct x, case_tac x, auto, case_tac x1a, auto)
lemma leq_rttrace_trans: "\<And>y. x \<le>\<^sub>\<R>\<^sub>\<T> y \<Longrightarrow> y \<le>\<^sub>\<R>\<^sub>\<T> z \<Longrightarrow> x \<le>\<^sub>\<R>\<^sub>\<T> z"
apply (induct x z rule:leq_rttrace.induct, auto)
apply (case_tac y, auto, case_tac x1, auto)
apply (case_tac y, auto, case_tac x1, auto)
apply (case_tac y, auto, case_tac x1, auto, case_tac x21, auto)
apply (case_tac y, auto, case_tac x1, auto, case_tac x21, auto)
apply (case_tac y, auto, case_tac x21, auto)
apply (case_tac y, auto, case_tac x21, auto)
apply (case_tac y, auto, case_tac x21, auto)
apply (case_tac y, auto, case_tac x21, auto)
apply (case_tac y, auto, case_tac x21, auto)
apply (case_tac y, auto, case_tac x21, auto)
apply (case_tac y, auto, case_tac x21, auto)
apply (case_tac y, auto, case_tac x21, auto)
apply (case_tac y, auto, (case_tac ya, auto)+)
done
lemma leq_rttrace_antisym: "x \<le>\<^sub>\<R>\<^sub>\<T> y \<Longrightarrow> y \<le>\<^sub>\<R>\<^sub>\<T> x \<Longrightarrow> x = y"
by (induct x y rule:leq_rttrace.induct, auto, case_tac \<sigma>, auto, case_tac x1, auto)
definition RT1 :: "'e rtprocess \<Rightarrow> bool" where
"RT1 P = (\<forall> \<rho> \<sigma>. \<sigma> \<in> P \<and> \<rho> \<le>\<^sub>\<R>\<^sub>\<T> \<sigma> \<longrightarrow> \<rho> \<in> P)"
subsection \<open>RT2\<close>
datatype 'e rttrace_tail = RTEmptyTail | RTEventTail 'e "'e rttrace" (infixr "##\<^sub>\<R>\<^sub>\<T>" 67)
datatype 'e rttrace_init = RTEmptyInit | RTEventInit "'e rtrefusal" 'e "'e rttrace_init"
fun rttrace_init_eq :: "'e rttrace_init \<Rightarrow> 'e rttrace_init \<Rightarrow> bool" where
"rttrace_init_eq RTEmptyInit RTEmptyInit = False" |
"rttrace_init_eq RTEmptyInit (RTEventInit x e \<rho>) = False" |
"rttrace_init_eq (RTEventInit x e \<rho>) RTEmptyInit = False" |
"rttrace_init_eq (RTEventInit x e \<rho>) (RTEventInit y f \<sigma>) = rttrace_init_eq \<rho> \<sigma>"
fun rttrace2init :: "'e rttrace \<Rightarrow> 'e rttrace_init" where
"rttrace2init \<langle>y\<rangle>\<^sub>\<R>\<^sub>\<T> = RTEmptyInit" |
"rttrace2init (x #\<^sub>\<R>\<^sub>\<T> a #\<^sub>\<R>\<^sub>\<T> \<rho>) = RTEventInit x a (rttrace2init \<rho>)"
fun rttrace_with_refusal :: "'e rttrace_init \<Rightarrow> 'e rtrefusal \<Rightarrow> 'e rttrace_tail \<Rightarrow> 'e rttrace" ("_ @\<^sub>\<R>\<^sub>\<T> \<langle>_\<rangle>\<^sub>\<R>\<^sub>\<T> @\<^sub>\<R>\<^sub>\<T> _" [65, 66, 67] 65) where
"((RTEventInit x a \<rho>) @\<^sub>\<R>\<^sub>\<T> \<langle>y\<rangle>\<^sub>\<R>\<^sub>\<T> @\<^sub>\<R>\<^sub>\<T> \<sigma>) = (x #\<^sub>\<R>\<^sub>\<T> a #\<^sub>\<R>\<^sub>\<T> (\<rho> @\<^sub>\<R>\<^sub>\<T> \<langle>y\<rangle>\<^sub>\<R>\<^sub>\<T> @\<^sub>\<R>\<^sub>\<T> \<sigma>))" |
"(RTEmptyInit @\<^sub>\<R>\<^sub>\<T> \<langle>y\<rangle>\<^sub>\<R>\<^sub>\<T> @\<^sub>\<R>\<^sub>\<T> (RTEventTail b \<sigma>)) = (y #\<^sub>\<R>\<^sub>\<T> b #\<^sub>\<R>\<^sub>\<T> \<sigma>)" |
"(RTEmptyInit @\<^sub>\<R>\<^sub>\<T> \<langle>b\<rangle>\<^sub>\<R>\<^sub>\<T> @\<^sub>\<R>\<^sub>\<T> RTEmptyTail) = \<langle>b\<rangle>\<^sub>\<R>\<^sub>\<T>"
fun leq_rttrace_init :: "'e rttrace_init \<Rightarrow> 'e rttrace_init \<Rightarrow> bool" where
"leq_rttrace_init RTEmptyInit \<rho> = True" |
"leq_rttrace_init (RTEventInit X e \<rho>) RTEmptyInit = False" |
"leq_rttrace_init (RTEventInit \<bullet>\<^sub>\<R>\<^sub>\<T> e \<rho>) (RTEventInit Y f \<sigma>) = (e = f \<and> leq_rttrace_init \<rho> \<sigma>)" |
"leq_rttrace_init (RTEventInit [X]\<^sub>\<R>\<^sub>\<T> e \<rho>) (RTEventInit \<bullet>\<^sub>\<R>\<^sub>\<T> f \<sigma>) = False" |
"leq_rttrace_init (RTEventInit [X]\<^sub>\<R>\<^sub>\<T> e \<rho>) (RTEventInit [Y]\<^sub>\<R>\<^sub>\<T> f \<sigma>) = (X \<subseteq> Y \<and> e = f \<and> leq_rttrace_init \<rho> \<sigma>)"
fun subset_rttrace_init :: "'e rttrace_init \<Rightarrow> 'e rttrace_init \<Rightarrow> bool" where
"subset_rttrace_init RTEmptyInit RTEmptyInit = True" |
"subset_rttrace_init (RTEventInit \<bullet>\<^sub>\<R>\<^sub>\<T> e \<rho>) (RTEventInit Y f \<sigma>) = (e = f \<and> subset_rttrace_init \<rho> \<sigma>)" |
"subset_rttrace_init (RTEventInit [X]\<^sub>\<R>\<^sub>\<T> e \<rho>) (RTEventInit \<bullet>\<^sub>\<R>\<^sub>\<T> f \<sigma>) = False" |
"subset_rttrace_init (RTEventInit [X]\<^sub>\<R>\<^sub>\<T> e \<rho>) (RTEventInit [Y]\<^sub>\<R>\<^sub>\<T> f \<sigma>) = (X \<subseteq> Y \<and> e = f \<and> subset_rttrace_init \<rho> \<sigma>)" |
"subset_rttrace_init \<rho> \<sigma> = False"
lemma rttrace_with_refusal_eq1:
"\<rho> @\<^sub>\<R>\<^sub>\<T> \<langle>X\<rangle>\<^sub>\<R>\<^sub>\<T> @\<^sub>\<R>\<^sub>\<T> RTEmptyTail = \<sigma> @\<^sub>\<R>\<^sub>\<T> \<langle>Y\<rangle>\<^sub>\<R>\<^sub>\<T> @\<^sub>\<R>\<^sub>\<T> RTEmptyTail \<Longrightarrow> \<rho> = \<sigma>"
by (induct \<rho> \<sigma> rule: rttrace_init_eq.induct, auto)
lemma rttrace_with_refusal_eq2:
"\<rho> @\<^sub>\<R>\<^sub>\<T> \<langle>X\<rangle>\<^sub>\<R>\<^sub>\<T> @\<^sub>\<R>\<^sub>\<T> RTEmptyTail = \<sigma> @\<^sub>\<R>\<^sub>\<T> \<langle>Y\<rangle>\<^sub>\<R>\<^sub>\<T> @\<^sub>\<R>\<^sub>\<T> RTEmptyTail \<Longrightarrow> X = Y"
by (induct \<rho> \<sigma> rule: rttrace_init_eq.induct, auto)
lemma rttrace_with_refusal_eq3:
"\<rho> @\<^sub>\<R>\<^sub>\<T> \<langle>X\<rangle>\<^sub>\<R>\<^sub>\<T> @\<^sub>\<R>\<^sub>\<T> e ##\<^sub>\<R>\<^sub>\<T> \<langle>x\<rangle>\<^sub>\<R>\<^sub>\<T> = \<sigma> @\<^sub>\<R>\<^sub>\<T> \<langle>Y\<rangle>\<^sub>\<R>\<^sub>\<T> @\<^sub>\<R>\<^sub>\<T> f ##\<^sub>\<R>\<^sub>\<T> \<langle>y\<rangle>\<^sub>\<R>\<^sub>\<T> \<Longrightarrow> \<rho> = \<sigma>"
apply (induct \<rho> \<sigma> rule: rttrace_init_eq.induct, auto)
apply (metis (full_types) rttrace.simps(4) rttrace_with_refusal.elims rttrace_with_refusal.simps(2))
using rttrace_with_refusal.elims by blast
definition RT2 :: "'e rtprocess \<Rightarrow> bool" where
"RT2 P = (\<forall> \<rho> \<sigma> X Y.
\<rho> @\<^sub>\<R>\<^sub>\<T> \<langle>[X]\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T> @\<^sub>\<R>\<^sub>\<T> \<sigma> \<in> P \<and> (\<forall>e\<in>Y. \<rho> @\<^sub>\<R>\<^sub>\<T> \<langle>[X]\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T> @\<^sub>\<R>\<^sub>\<T> e ##\<^sub>\<R>\<^sub>\<T> \<langle>\<bullet>\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T> \<notin> P)
\<longrightarrow> \<rho> @\<^sub>\<R>\<^sub>\<T> \<langle>[X \<union> Y]\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T> @\<^sub>\<R>\<^sub>\<T> \<sigma> \<in> P)"
subsection \<open>RT3\<close>
fun no_tick :: "'e rtevent rttrace_init \<Rightarrow> bool" where
"no_tick RTEmptyInit = True" |
"no_tick (RTEventInit x (EventRT e) \<rho>) = no_tick \<rho>" |
"no_tick (RTEventInit x (TickRT) \<rho>) = False"
lemma subset_rttrace_init_no_tick1:
"no_tick \<rho> \<Longrightarrow> subset_rttrace_init \<rho> \<sigma> \<Longrightarrow> no_tick \<sigma>"
by (induct \<rho> \<sigma> rule:subset_rttrace_init.induct, auto, (case_tac f, auto)+)
lemma subset_rttrace_init_no_tick2:
"no_tick \<sigma> \<Longrightarrow> subset_rttrace_init \<rho> \<sigma> \<Longrightarrow> no_tick \<rho>"
by (induct \<rho> \<sigma> rule:subset_rttrace_init.induct, auto, (case_tac f, auto)+)
definition RT3 :: "'e rtevent rtprocess \<Rightarrow> bool" where
"RT3 P = (\<forall> \<rho> x y e. \<rho> @\<^sub>\<R>\<^sub>\<T> \<langle>x\<rangle>\<^sub>\<R>\<^sub>\<T> @\<^sub>\<R>\<^sub>\<T> e ##\<^sub>\<R>\<^sub>\<T> \<langle>y\<rangle>\<^sub>\<R>\<^sub>\<T> \<in> P \<longrightarrow> no_tick \<rho>)"
lemma RT3_refusal_after_TickRT:
"\<And>P. RT3 P \<Longrightarrow> (X #\<^sub>\<R>\<^sub>\<T> TickRT #\<^sub>\<R>\<^sub>\<T> \<rho>) \<in> P \<Longrightarrow> \<exists> Y. \<rho> = \<langle>Y\<rangle>\<^sub>\<R>\<^sub>\<T>"
proof (induct \<rho>, auto)
fix x1a x2 \<rho> P
assume in_P: "(X #\<^sub>\<R>\<^sub>\<T> TickRT #\<^sub>\<R>\<^sub>\<T> (x1a #\<^sub>\<R>\<^sub>\<T> x2 #\<^sub>\<R>\<^sub>\<T> \<rho>)) \<in> P"
assume RT3_P: "RT3 P"
have "\<exists> \<rho>' x e y. (X #\<^sub>\<R>\<^sub>\<T> TickRT #\<^sub>\<R>\<^sub>\<T> (x1a #\<^sub>\<R>\<^sub>\<T> x2 #\<^sub>\<R>\<^sub>\<T> \<rho>)) = (RTEventInit X TickRT \<rho>' @\<^sub>\<R>\<^sub>\<T> \<langle>x\<rangle>\<^sub>\<R>\<^sub>\<T> @\<^sub>\<R>\<^sub>\<T> e ##\<^sub>\<R>\<^sub>\<T> \<langle>y\<rangle>\<^sub>\<R>\<^sub>\<T>)"
apply (induct \<rho>, auto, rule_tac x = RTEmptyInit in exI, auto)
by (smt rttrace.inject(2) rttrace_init.exhaust rttrace_with_refusal.simps(1) rttrace_with_refusal.simps(2))
then obtain \<rho>' x e y where "(X #\<^sub>\<R>\<^sub>\<T> TickRT #\<^sub>\<R>\<^sub>\<T> (x1a #\<^sub>\<R>\<^sub>\<T> x2 #\<^sub>\<R>\<^sub>\<T> \<rho>)) = (RTEventInit X TickRT \<rho>' @\<^sub>\<R>\<^sub>\<T> \<langle>x\<rangle>\<^sub>\<R>\<^sub>\<T> @\<^sub>\<R>\<^sub>\<T> e ##\<^sub>\<R>\<^sub>\<T> \<langle>y\<rangle>\<^sub>\<R>\<^sub>\<T>)"
by blast
then have "no_tick (RTEventInit X TickRT \<rho>')"
using RT3_P in_P unfolding RT3_def by (auto, metis in_P no_tick.simps(3) rttrace_with_refusal.simps(1))
then show "False"
by auto
qed
subsection \<open>RT4\<close>
definition RT4 :: "'e rtevent rtprocess \<Rightarrow> bool" where
"RT4 P = (\<forall> \<rho> x y.
\<rho> @\<^sub>\<R>\<^sub>\<T> \<langle>x\<rangle>\<^sub>\<R>\<^sub>\<T> @\<^sub>\<R>\<^sub>\<T> TickRT ##\<^sub>\<R>\<^sub>\<T> \<langle>y\<rangle>\<^sub>\<R>\<^sub>\<T> \<in> P
\<longrightarrow> x = \<bullet>\<^sub>\<R>\<^sub>\<T> \<and> \<rho> @\<^sub>\<R>\<^sub>\<T> \<langle>\<bullet>\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T> @\<^sub>\<R>\<^sub>\<T> TickRT ##\<^sub>\<R>\<^sub>\<T> \<langle>[UNIV]\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T> \<in> P)"
subsection \<open>RT\<close>
definition RT :: "'e rtevent rtprocess \<Rightarrow> bool" where
"RT P = ((\<forall>x\<in>P. rtWF x) \<and> MRT0 P \<and> RT1 P \<and> RT2 P \<and> RT3 P \<and> RT4 P)"
definition refinesRT :: "'e rtprocess \<Rightarrow> 'e rtprocess \<Rightarrow> bool" (infix "\<sqsubseteq>\<^sub>\<R>\<^sub>\<T>" 50) where
"P \<sqsubseteq>\<^sub>\<R>\<^sub>\<T> Q = (Q \<subseteq> P)"
section \<open>Maximal Healthiness Conditions\<close>
subsection \<open>RTM1 (replaces RT1)\<close>
fun leq_rttrace_max :: "'e rttrace \<Rightarrow> 'e rttrace \<Rightarrow> bool" (infix "\<le>\<^sub>\<R>\<^sub>\<T>\<^sub>\<M>" 50) where
"\<langle> \<bullet>\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T> \<le>\<^sub>\<R>\<^sub>\<T>\<^sub>\<M> \<sigma> = True" |
"\<langle> [X]\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T> \<le>\<^sub>\<R>\<^sub>\<T>\<^sub>\<M> \<langle> [Y]\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T> = (X = Y)" |
"\<langle> [X]\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T> \<le>\<^sub>\<R>\<^sub>\<T>\<^sub>\<M> \<langle> \<bullet>\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T> = False" |
"\<langle> [X]\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T> \<le>\<^sub>\<R>\<^sub>\<T>\<^sub>\<M> ( [Y]\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> b #\<^sub>\<R>\<^sub>\<T> \<sigma>) = (X = Y)" |
"\<langle> [X]\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T> \<le>\<^sub>\<R>\<^sub>\<T>\<^sub>\<M> ( \<bullet>\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> b #\<^sub>\<R>\<^sub>\<T> \<sigma>) = False" |
"( \<bullet>\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> a #\<^sub>\<R>\<^sub>\<T> \<rho>) \<le>\<^sub>\<R>\<^sub>\<T>\<^sub>\<M> ( \<bullet>\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> b #\<^sub>\<R>\<^sub>\<T> \<sigma>) = (a = b \<and> \<rho> \<le>\<^sub>\<R>\<^sub>\<T>\<^sub>\<M> \<sigma>)" |
"( \<bullet>\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> a #\<^sub>\<R>\<^sub>\<T> \<rho>) \<le>\<^sub>\<R>\<^sub>\<T>\<^sub>\<M> ( [Y]\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> b #\<^sub>\<R>\<^sub>\<T> \<sigma>) = (a = b \<and> \<rho> \<le>\<^sub>\<R>\<^sub>\<T>\<^sub>\<M> \<sigma>)" |
"( [X]\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> a #\<^sub>\<R>\<^sub>\<T> \<rho>) \<le>\<^sub>\<R>\<^sub>\<T>\<^sub>\<M> ( [Y]\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> b #\<^sub>\<R>\<^sub>\<T> \<sigma>) = (X = Y \<and> a = b \<and> \<rho> \<le>\<^sub>\<R>\<^sub>\<T>\<^sub>\<M> \<sigma>)" |
"( [X]\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> a #\<^sub>\<R>\<^sub>\<T> \<rho>) \<le>\<^sub>\<R>\<^sub>\<T>\<^sub>\<M> ( \<bullet>\<^sub>\<R>\<^sub>\<T> #\<^sub>\<R>\<^sub>\<T> b #\<^sub>\<R>\<^sub>\<T> \<sigma>) = False" |
"( x #\<^sub>\<R>\<^sub>\<T> a #\<^sub>\<R>\<^sub>\<T> \<rho>) \<le>\<^sub>\<R>\<^sub>\<T>\<^sub>\<M> \<langle>y\<rangle>\<^sub>\<R>\<^sub>\<T> = False"
lemma leq_rttrace_max_refl: "x \<le>\<^sub>\<R>\<^sub>\<T>\<^sub>\<M> x"
by (induct x, case_tac x, auto, case_tac x1a, auto)
lemma leq_rttrace_max_trans: "\<And>y. x \<le>\<^sub>\<R>\<^sub>\<T>\<^sub>\<M> y \<Longrightarrow> y \<le>\<^sub>\<R>\<^sub>\<T>\<^sub>\<M> z \<Longrightarrow> x \<le>\<^sub>\<R>\<^sub>\<T>\<^sub>\<M> z"
apply (induct x z rule:leq_rttrace.induct, auto)
apply (case_tac y, auto, case_tac x1, auto)
apply (case_tac y, auto, case_tac x1, auto)
apply (case_tac y, auto, case_tac x1, auto)
apply (case_tac y, auto, case_tac x1, auto, case_tac x21, auto)
apply (case_tac y, auto, case_tac x1, auto, case_tac x21, auto)
apply (case_tac y, auto, case_tac x1, auto, case_tac x21, auto)
apply (case_tac y, auto, case_tac x21, auto)
apply (case_tac y, auto, case_tac x21, auto)
apply (case_tac y, auto, case_tac x21, auto)
apply (case_tac y, auto, case_tac x21, auto)
apply (case_tac y, auto, case_tac x21, auto)
apply (case_tac y, auto, case_tac x21, auto)
apply (case_tac y, auto, case_tac x21, auto)
apply (case_tac y, auto, case_tac x21, auto)
apply (case_tac y, auto, case_tac x21, auto)
apply (case_tac y, auto, (case_tac ya, auto)+)
done
lemma leq_rttrace_max_antisym: "x \<le>\<^sub>\<R>\<^sub>\<T>\<^sub>\<M> y \<Longrightarrow> y \<le>\<^sub>\<R>\<^sub>\<T>\<^sub>\<M> x \<Longrightarrow> x = y"
by (induct x y rule:leq_rttrace.induct, auto, case_tac \<sigma>, auto, case_tac x1, auto)
lemma leq_rttrace_max_implies_leq_rttrace:
"\<rho> \<le>\<^sub>\<R>\<^sub>\<T>\<^sub>\<M> \<sigma> \<Longrightarrow> \<rho> \<le>\<^sub>\<R>\<^sub>\<T> \<sigma>"
by (induct \<rho> \<sigma> rule:leq_rttrace_max.induct, auto)
fun leq_rttrace_init_max :: "'e rttrace_init \<Rightarrow> 'e rttrace_init \<Rightarrow> bool" where
"leq_rttrace_init_max RTEmptyInit \<rho> = True" |
"leq_rttrace_init_max (RTEventInit X e \<rho>) RTEmptyInit = False" |
"leq_rttrace_init_max (RTEventInit \<bullet>\<^sub>\<R>\<^sub>\<T> e \<rho>) (RTEventInit Y f \<sigma>) = (e = f \<and> leq_rttrace_init_max \<rho> \<sigma>)" |
"leq_rttrace_init_max (RTEventInit [X]\<^sub>\<R>\<^sub>\<T> e \<rho>) (RTEventInit \<bullet>\<^sub>\<R>\<^sub>\<T> f \<sigma>) = False" |
"leq_rttrace_init_max (RTEventInit [X]\<^sub>\<R>\<^sub>\<T> e \<rho>) (RTEventInit [Y]\<^sub>\<R>\<^sub>\<T> f \<sigma>) = (X \<subseteq> Y \<and> e = f \<and> leq_rttrace_init_max \<rho> \<sigma>)"
fun leq_rttrace_rttrace_init_max :: "'e rttrace \<Rightarrow> 'e rttrace_init \<Rightarrow> bool" where
"leq_rttrace_rttrace_init_max \<langle>x\<rangle>\<^sub>\<R>\<^sub>\<T> RTEmptyInit = False" |
"leq_rttrace_rttrace_init_max (v #\<^sub>\<R>\<^sub>\<T> va #\<^sub>\<R>\<^sub>\<T> vb) RTEmptyInit = False" |
"leq_rttrace_rttrace_init_max \<langle>vc\<rangle>\<^sub>\<R>\<^sub>\<T> (RTEventInit v va vb) = (vc = v)" |
"leq_rttrace_rttrace_init_max (v #\<^sub>\<R>\<^sub>\<T> va #\<^sub>\<R>\<^sub>\<T> vb) (RTEventInit vc vd ve) = (v = vc \<and> va = vd \<and> leq_rttrace_rttrace_init_max vb ve)"
definition RTM1 :: "'e rtprocess \<Rightarrow> bool" where
"RTM1 P = (\<forall> \<rho> \<sigma>. \<sigma> \<in> P \<and> \<rho> \<le>\<^sub>\<R>\<^sub>\<T>\<^sub>\<M> \<sigma> \<longrightarrow> \<rho> \<in> P)"
lemma RTM1_init_event:
assumes "RTM1 P"
shows "RTM1 {\<rho>. (x #\<^sub>\<R>\<^sub>\<T> a #\<^sub>\<R>\<^sub>\<T> \<rho>) \<in> P}"
using assms unfolding RTM1_def apply auto
by (metis leq_rttrace_max.simps(6) leq_rttrace_max.simps(8) rtrefusal.exhaust)
subsection \<open>RTM2 (replaces RT2)\<close>
definition RTM2 :: "'e rtprocess \<Rightarrow> bool" where
"RTM2 P = (\<forall> \<rho> X e. \<rho> @\<^sub>\<R>\<^sub>\<T> \<langle>[X]\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T> @\<^sub>\<R>\<^sub>\<T> RTEmptyTail \<in> P \<and> e \<notin> X \<longrightarrow> \<rho> @\<^sub>\<R>\<^sub>\<T> \<langle>[X]\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T> @\<^sub>\<R>\<^sub>\<T> e ##\<^sub>\<R>\<^sub>\<T> \<langle>\<bullet>\<^sub>\<R>\<^sub>\<T>\<rangle>\<^sub>\<R>\<^sub>\<T> \<in> P)"
subsection \<open>RTM\<close>
definition RTM :: "'e rtevent rtprocess \<Rightarrow> bool" where
"RTM P = ((\<forall>x\<in>P. rtWF x) \<and> MRT0 P \<and> RTM1 P \<and> RTM2 P \<and> RT3 P \<and> RT4 P)"
end
|
lemma integral_eq_zero_null_sets: assumes "S \<in> null_sets lebesgue" shows "integral\<^sup>L (lebesgue_on S) f = 0"
|
(*
Copyright (C) 2017 M.A.L. Marques
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*)
(* type: gga_exc *)
(* eqn (5) *)
meyer_feta := y -> 1/2*(1 + (1 - y^2)*log((1 + y)/abs(1 - y))/(2*y)):
(* eqn (7) *)
meyer_lambda := y -> (1 - meyer_feta(y)) / (3 * y^2 * meyer_feta(y)):
(* enhancement factor from eqn (1) *)
meyer_f := x -> 1 + meyer_lambda(X2S*x/6)*x^2/(8*K_FACTOR_C):
f := (rs, zeta, xt, xs0, xs1) -> gga_kinetic(meyer_f, rs, zeta, xs0, xs1):
|
!=====================================================
SUBROUTINE spfper(np1,amx1,amx2,amx3)
! Helper routine for splfi
USE neo_precision
IMPLICIT NONE
INTEGER, INTENT(in) :: np1
REAL(kind=dp), DIMENSION(np1), INTENT(out) :: amx1, amx2, amx3
REAL(kind=dp) :: beta, ss
INTEGER :: n, n1, i, i1
n = np1-1
n1 = n-1
amx1(1) = 2
amx2(1) = 0.5_dp
amx3(1) = 0.5_dp
amx1(2) = sqrt(15._dp)/2
amx2(2) = ONE/amx1(2)
amx3(2) = -.25_dp/amx1(2)
beta = 3.75_dp
DO i = 3,n1
i1 = i-1
beta = 4-ONE/beta
amx1(i) = sqrt(beta)
amx2(i) = ONE/amx1(i)
amx3(i) = -amx3(i1)/amx1(i)/amx1(i1)
END DO
amx3(n1) = amx3(n1)+ONE/amx1(n1)
amx2(n1) = amx3(n1)
ss = 0
DO i = 1,n1
ss = ss+amx3(i)*amx3(i)
END DO
amx1(n) = sqrt(4-ss)
RETURN
END SUBROUTINE spfper
|
[STATEMENT]
lemma Nmlize_Vcomp_Cod_Arr:
assumes "Arr t"
shows "\<^bold>\<lfloor>Cod t \<^bold>\<cdot> t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<^bold>\<lfloor>Cod t \<^bold>\<cdot> t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<^bold>\<lfloor>Cod t \<^bold>\<cdot> t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>
[PROOF STEP]
have "Arr t \<Longrightarrow> \<^bold>\<lfloor>Cod t \<^bold>\<cdot> t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. Arr t \<Longrightarrow> \<^bold>\<lfloor>Cod t \<^bold>\<cdot> t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>
[PROOF STEP]
proof (induct t, simp_all)
[PROOF STATE]
proof (state)
goal (7 subgoals):
1. \<And>x. arr x \<Longrightarrow> cod x \<cdot> x = x
2. \<And>t1 t2. \<lbrakk>\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor>; HSeq t1 t2\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> (\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>) = \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>
3. \<And>t1 t2. \<lbrakk>\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor>; VSeq t1 t2\<rbrakk> \<Longrightarrow> \<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>
4. \<And>t. \<lbrakk>\<^bold>\<lfloor>Cod t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>; Arr t\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Trg t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>
5. \<And>t. \<lbrakk>\<^bold>\<lfloor>Cod t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>; Arr t\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Cod t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Src t\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>
6. \<And>t1 t2 t3. \<lbrakk>\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor> = \<^bold>\<lfloor>t3\<^bold>\<rfloor>; Arr t1 \<and> Arr t2 \<and> Arr t3 \<and> Src t1 = Trg t2 \<and> Src t2 = Trg t3\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> ((\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>) = (\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>
7. \<And>t1 t2 t3. \<lbrakk>\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor> = \<^bold>\<lfloor>t3\<^bold>\<rfloor>; Arr t1 \<and> Arr t2 \<and> Arr t3 \<and> Src t1 = Trg t2 \<and> Src t2 = Trg t3\<rbrakk> \<Longrightarrow> ((\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> (\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>) = \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>
[PROOF STEP]
show "\<And>x. arr x \<Longrightarrow> cod x \<cdot> x = x"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>x. arr x \<Longrightarrow> cod x \<cdot> x = x
[PROOF STEP]
using comp_cod_arr
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>arr ?f; cod ?f = ?b\<rbrakk> \<Longrightarrow> ?b \<cdot> ?f = ?f
goal (1 subgoal):
1. \<And>x. arr x \<Longrightarrow> cod x \<cdot> x = x
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
arr ?x \<Longrightarrow> cod ?x \<cdot> ?x = ?x
goal (6 subgoals):
1. \<And>t1 t2. \<lbrakk>\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor>; HSeq t1 t2\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> (\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>) = \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>
2. \<And>t1 t2. \<lbrakk>\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor>; VSeq t1 t2\<rbrakk> \<Longrightarrow> \<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>
3. \<And>t. \<lbrakk>\<^bold>\<lfloor>Cod t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>; Arr t\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Trg t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>
4. \<And>t. \<lbrakk>\<^bold>\<lfloor>Cod t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>; Arr t\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Cod t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Src t\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>
5. \<And>t1 t2 t3. \<lbrakk>\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor> = \<^bold>\<lfloor>t3\<^bold>\<rfloor>; Arr t1 \<and> Arr t2 \<and> Arr t3 \<and> Src t1 = Trg t2 \<and> Src t2 = Trg t3\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> ((\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>) = (\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>
6. \<And>t1 t2 t3. \<lbrakk>\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor> = \<^bold>\<lfloor>t3\<^bold>\<rfloor>; Arr t1 \<and> Arr t2 \<and> Arr t3 \<and> Src t1 = Trg t2 \<and> Src t2 = Trg t3\<rbrakk> \<Longrightarrow> ((\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> (\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>) = \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>
[PROOF STEP]
fix t1 t2
[PROOF STATE]
proof (state)
goal (6 subgoals):
1. \<And>t1 t2. \<lbrakk>\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor>; HSeq t1 t2\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> (\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>) = \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>
2. \<And>t1 t2. \<lbrakk>\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor>; VSeq t1 t2\<rbrakk> \<Longrightarrow> \<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>
3. \<And>t. \<lbrakk>\<^bold>\<lfloor>Cod t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>; Arr t\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Trg t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>
4. \<And>t. \<lbrakk>\<^bold>\<lfloor>Cod t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>; Arr t\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Cod t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Src t\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>
5. \<And>t1 t2 t3. \<lbrakk>\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor> = \<^bold>\<lfloor>t3\<^bold>\<rfloor>; Arr t1 \<and> Arr t2 \<and> Arr t3 \<and> Src t1 = Trg t2 \<and> Src t2 = Trg t3\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> ((\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>) = (\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>
6. \<And>t1 t2 t3. \<lbrakk>\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor> = \<^bold>\<lfloor>t3\<^bold>\<rfloor>; Arr t1 \<and> Arr t2 \<and> Arr t3 \<and> Src t1 = Trg t2 \<and> Src t2 = Trg t3\<rbrakk> \<Longrightarrow> ((\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> (\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>) = \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>
[PROOF STEP]
show "\<And>t1 t2. \<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<Longrightarrow> \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor> \<Longrightarrow> HSeq t1 t2 \<Longrightarrow>
(\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> (\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>) = \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>t1 t2. \<lbrakk>\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor>; HSeq t1 t2\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> (\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>) = \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>
[PROOF STEP]
using VcompNml_HcompNml Ide_Cod Nml_Nmlize Nmlize_in_Hom
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>Nml ?t; Nml ?u; Nml ?v; Nml ?w; VSeq ?t ?v; VSeq ?u ?w; Src ?v = Trg ?w\<rbrakk> \<Longrightarrow> (?t \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> ?u) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> (?v \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> ?w) = ?t \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> ?v \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> ?u \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> ?w
Arr ?t \<Longrightarrow> Ide (Cod ?t)
Arr ?t \<Longrightarrow> Nml \<^bold>\<lfloor>?t\<^bold>\<rfloor>
Arr ?t \<Longrightarrow> Src \<^bold>\<lfloor>?t\<^bold>\<rfloor> = Src ?t
Arr ?t \<Longrightarrow> Trg \<^bold>\<lfloor>?t\<^bold>\<rfloor> = Trg ?t
Arr ?t \<Longrightarrow> Dom \<^bold>\<lfloor>?t\<^bold>\<rfloor> = \<^bold>\<lfloor>Dom ?t\<^bold>\<rfloor>
Arr ?t \<Longrightarrow> Cod \<^bold>\<lfloor>?t\<^bold>\<rfloor> = \<^bold>\<lfloor>Cod ?t\<^bold>\<rfloor>
Arr ?t \<Longrightarrow> \<^bold>\<lfloor>?t\<^bold>\<rfloor> \<in> HHom (Src ?t) (Trg ?t)
Arr ?t \<Longrightarrow> \<^bold>\<lfloor>?t\<^bold>\<rfloor> \<in> VHom \<^bold>\<lfloor>Dom ?t\<^bold>\<rfloor> \<^bold>\<lfloor>Cod ?t\<^bold>\<rfloor>
goal (1 subgoal):
1. \<And>t1 t2. \<lbrakk>\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor>; HSeq t1 t2\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> (\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>) = \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
\<lbrakk>\<^bold>\<lfloor>Cod ?t1.0\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>?t1.0\<^bold>\<rfloor> = \<^bold>\<lfloor>?t1.0\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod ?t2.0\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>?t2.0\<^bold>\<rfloor> = \<^bold>\<lfloor>?t2.0\<^bold>\<rfloor>; HSeq ?t1.0 ?t2.0\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Cod ?t1.0\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod ?t2.0\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> (\<^bold>\<lfloor>?t1.0\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>?t2.0\<^bold>\<rfloor>) = \<^bold>\<lfloor>?t1.0\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>?t2.0\<^bold>\<rfloor>
goal (5 subgoals):
1. \<And>t1 t2. \<lbrakk>\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor>; VSeq t1 t2\<rbrakk> \<Longrightarrow> \<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>
2. \<And>t. \<lbrakk>\<^bold>\<lfloor>Cod t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>; Arr t\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Trg t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>
3. \<And>t. \<lbrakk>\<^bold>\<lfloor>Cod t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>; Arr t\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Cod t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Src t\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>
4. \<And>t1 t2 t3. \<lbrakk>\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor> = \<^bold>\<lfloor>t3\<^bold>\<rfloor>; Arr t1 \<and> Arr t2 \<and> Arr t3 \<and> Src t1 = Trg t2 \<and> Src t2 = Trg t3\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> ((\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>) = (\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>
5. \<And>t1 t2 t3. \<lbrakk>\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor> = \<^bold>\<lfloor>t3\<^bold>\<rfloor>; Arr t1 \<and> Arr t2 \<and> Arr t3 \<and> Src t1 = Trg t2 \<and> Src t2 = Trg t3\<rbrakk> \<Longrightarrow> ((\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> (\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>) = \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>
[PROOF STEP]
show "\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<Longrightarrow> \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor> \<Longrightarrow> VSeq t1 t2 \<Longrightarrow>
\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor>; VSeq t1 t2\<rbrakk> \<Longrightarrow> \<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>
[PROOF STEP]
using VcompNml_assoc [of "\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor>" "\<^bold>\<lfloor>t1\<^bold>\<rfloor>" "\<^bold>\<lfloor>t2\<^bold>\<rfloor>"] Ide_Cod
Nml_Nmlize
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>Nml \<^bold>\<lfloor>Cod t1\<^bold>\<rfloor>; Nml \<^bold>\<lfloor>t1\<^bold>\<rfloor>; Nml \<^bold>\<lfloor>t2\<^bold>\<rfloor>; Dom \<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> = Cod \<^bold>\<lfloor>t1\<^bold>\<rfloor>; Dom \<^bold>\<lfloor>t1\<^bold>\<rfloor> = Cod \<^bold>\<lfloor>t2\<^bold>\<rfloor>\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>
Arr ?t \<Longrightarrow> Ide (Cod ?t)
Arr ?t \<Longrightarrow> Nml \<^bold>\<lfloor>?t\<^bold>\<rfloor>
Arr ?t \<Longrightarrow> Src \<^bold>\<lfloor>?t\<^bold>\<rfloor> = Src ?t
Arr ?t \<Longrightarrow> Trg \<^bold>\<lfloor>?t\<^bold>\<rfloor> = Trg ?t
Arr ?t \<Longrightarrow> Dom \<^bold>\<lfloor>?t\<^bold>\<rfloor> = \<^bold>\<lfloor>Dom ?t\<^bold>\<rfloor>
Arr ?t \<Longrightarrow> Cod \<^bold>\<lfloor>?t\<^bold>\<rfloor> = \<^bold>\<lfloor>Cod ?t\<^bold>\<rfloor>
goal (1 subgoal):
1. \<lbrakk>\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor>; VSeq t1 t2\<rbrakk> \<Longrightarrow> \<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
\<lbrakk>\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor>; VSeq t1 t2\<rbrakk> \<Longrightarrow> \<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>
goal (4 subgoals):
1. \<And>t. \<lbrakk>\<^bold>\<lfloor>Cod t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>; Arr t\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Trg t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>
2. \<And>t. \<lbrakk>\<^bold>\<lfloor>Cod t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>; Arr t\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Cod t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Src t\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>
3. \<And>t1 t2 t3. \<lbrakk>\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor> = \<^bold>\<lfloor>t3\<^bold>\<rfloor>; Arr t1 \<and> Arr t2 \<and> Arr t3 \<and> Src t1 = Trg t2 \<and> Src t2 = Trg t3\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> ((\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>) = (\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>
4. \<And>t1 t2 t3. \<lbrakk>\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor> = \<^bold>\<lfloor>t3\<^bold>\<rfloor>; Arr t1 \<and> Arr t2 \<and> Arr t3 \<and> Src t1 = Trg t2 \<and> Src t2 = Trg t3\<rbrakk> \<Longrightarrow> ((\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> (\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>) = \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (4 subgoals):
1. \<And>t. \<lbrakk>\<^bold>\<lfloor>Cod t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>; Arr t\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Trg t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>
2. \<And>t. \<lbrakk>\<^bold>\<lfloor>Cod t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>; Arr t\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Cod t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Src t\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>
3. \<And>t1 t2 t3. \<lbrakk>\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor> = \<^bold>\<lfloor>t3\<^bold>\<rfloor>; Arr t1 \<and> Arr t2 \<and> Arr t3 \<and> Src t1 = Trg t2 \<and> Src t2 = Trg t3\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> ((\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>) = (\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>
4. \<And>t1 t2 t3. \<lbrakk>\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor> = \<^bold>\<lfloor>t3\<^bold>\<rfloor>; Arr t1 \<and> Arr t2 \<and> Arr t3 \<and> Src t1 = Trg t2 \<and> Src t2 = Trg t3\<rbrakk> \<Longrightarrow> ((\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> (\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>) = \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>
[PROOF STEP]
show "\<And>t. \<^bold>\<lfloor>Cod t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor> \<Longrightarrow> Arr t \<Longrightarrow> (\<^bold>\<lfloor>Trg t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>t. \<lbrakk>\<^bold>\<lfloor>Cod t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>; Arr t\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Trg t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>
[PROOF STEP]
by (metis Arr.simps(6) Cod.simps(6) Nmlize.simps(3) Nmlize.simps(6)
Nmlize_Cod)
[PROOF STATE]
proof (state)
this:
\<lbrakk>\<^bold>\<lfloor>Cod ?t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>?t\<^bold>\<rfloor> = \<^bold>\<lfloor>?t\<^bold>\<rfloor>; Arr ?t\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Trg ?t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod ?t\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>?t\<^bold>\<rfloor> = \<^bold>\<lfloor>?t\<^bold>\<rfloor>
goal (3 subgoals):
1. \<And>t. \<lbrakk>\<^bold>\<lfloor>Cod t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>; Arr t\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Cod t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Src t\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>
2. \<And>t1 t2 t3. \<lbrakk>\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor> = \<^bold>\<lfloor>t3\<^bold>\<rfloor>; Arr t1 \<and> Arr t2 \<and> Arr t3 \<and> Src t1 = Trg t2 \<and> Src t2 = Trg t3\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> ((\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>) = (\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>
3. \<And>t1 t2 t3. \<lbrakk>\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor> = \<^bold>\<lfloor>t3\<^bold>\<rfloor>; Arr t1 \<and> Arr t2 \<and> Arr t3 \<and> Src t1 = Trg t2 \<and> Src t2 = Trg t3\<rbrakk> \<Longrightarrow> ((\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> (\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>) = \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>
[PROOF STEP]
show "\<And>t. \<^bold>\<lfloor>Cod t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor> \<Longrightarrow> Arr t \<Longrightarrow> (\<^bold>\<lfloor>Cod t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Src t\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>t. \<lbrakk>\<^bold>\<lfloor>Cod t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>; Arr t\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Cod t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Src t\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>
[PROOF STEP]
by (simp add: Nml_Nmlize(1) Nml_Nmlize(2) Nmlize_Src(2) HcompNml_Nml_Obj)
[PROOF STATE]
proof (state)
this:
\<lbrakk>\<^bold>\<lfloor>Cod ?t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>?t\<^bold>\<rfloor> = \<^bold>\<lfloor>?t\<^bold>\<rfloor>; Arr ?t\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Cod ?t\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Src ?t\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>?t\<^bold>\<rfloor> = \<^bold>\<lfloor>?t\<^bold>\<rfloor>
goal (2 subgoals):
1. \<And>t1 t2 t3. \<lbrakk>\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor> = \<^bold>\<lfloor>t3\<^bold>\<rfloor>; Arr t1 \<and> Arr t2 \<and> Arr t3 \<and> Src t1 = Trg t2 \<and> Src t2 = Trg t3\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> ((\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>) = (\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>
2. \<And>t1 t2 t3. \<lbrakk>\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor> = \<^bold>\<lfloor>t3\<^bold>\<rfloor>; Arr t1 \<and> Arr t2 \<and> Arr t3 \<and> Src t1 = Trg t2 \<and> Src t2 = Trg t3\<rbrakk> \<Longrightarrow> ((\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> (\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>) = \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>
[PROOF STEP]
show "\<And>t1 t2 t3. \<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<Longrightarrow> \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor> \<Longrightarrow>
\<^bold>\<lfloor>Cod t3\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor> = \<^bold>\<lfloor>t3\<^bold>\<rfloor> \<Longrightarrow>
Arr t1 \<and> Arr t2 \<and> Arr t3 \<and> Src t1 = Trg t2 \<and> Src t2 = Trg t3 \<Longrightarrow>
(\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> ((\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>) =
(\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>t1 t2 t3. \<lbrakk>\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor> = \<^bold>\<lfloor>t3\<^bold>\<rfloor>; Arr t1 \<and> Arr t2 \<and> Arr t3 \<and> Src t1 = Trg t2 \<and> Src t2 = Trg t3\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> ((\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>) = (\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>
[PROOF STEP]
using VcompNml_HcompNml Ide_Cod HcompNml_in_Hom Nml_HcompNml
Nml_Nmlize Nmlize_in_Hom HcompNml_assoc
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>Nml ?t; Nml ?u; Nml ?v; Nml ?w; VSeq ?t ?v; VSeq ?u ?w; Src ?v = Trg ?w\<rbrakk> \<Longrightarrow> (?t \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> ?u) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> (?v \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> ?w) = ?t \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> ?v \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> ?u \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> ?w
Arr ?t \<Longrightarrow> Ide (Cod ?t)
\<lbrakk>Nml ?t; Nml ?u; Src ?t = Trg ?u\<rbrakk> \<Longrightarrow> ?t \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> ?u \<in> HHom (Src ?u) (Trg ?t)
\<lbrakk>Nml ?t; Nml ?u; Src ?t = Trg ?u\<rbrakk> \<Longrightarrow> ?t \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> ?u \<in> VHom (Dom ?t \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> Dom ?u) (Cod ?t \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> Cod ?u)
\<lbrakk>Nml ?t; Nml ?u; Src ?t = Trg ?u\<rbrakk> \<Longrightarrow> Nml (?t \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> ?u)
\<lbrakk>Nml ?t; Nml ?u; Src ?t = Trg ?u\<rbrakk> \<Longrightarrow> Dom (?t \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> ?u) = Dom ?t \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> Dom ?u
\<lbrakk>Nml ?t; Nml ?u; Src ?t = Trg ?u\<rbrakk> \<Longrightarrow> Cod (?t \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> ?u) = Cod ?t \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> Cod ?u
\<lbrakk>Nml ?t; Nml ?u; Src ?t = Trg ?u\<rbrakk> \<Longrightarrow> Src (?t \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> ?u) = Src ?u
\<lbrakk>Nml ?t; Nml ?u; Src ?t = Trg ?u\<rbrakk> \<Longrightarrow> Trg (?t \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> ?u) = Trg ?t
Arr ?t \<Longrightarrow> Nml \<^bold>\<lfloor>?t\<^bold>\<rfloor>
Arr ?t \<Longrightarrow> Src \<^bold>\<lfloor>?t\<^bold>\<rfloor> = Src ?t
Arr ?t \<Longrightarrow> Trg \<^bold>\<lfloor>?t\<^bold>\<rfloor> = Trg ?t
Arr ?t \<Longrightarrow> Dom \<^bold>\<lfloor>?t\<^bold>\<rfloor> = \<^bold>\<lfloor>Dom ?t\<^bold>\<rfloor>
Arr ?t \<Longrightarrow> Cod \<^bold>\<lfloor>?t\<^bold>\<rfloor> = \<^bold>\<lfloor>Cod ?t\<^bold>\<rfloor>
Arr ?t \<Longrightarrow> \<^bold>\<lfloor>?t\<^bold>\<rfloor> \<in> HHom (Src ?t) (Trg ?t)
Arr ?t \<Longrightarrow> \<^bold>\<lfloor>?t\<^bold>\<rfloor> \<in> VHom \<^bold>\<lfloor>Dom ?t\<^bold>\<rfloor> \<^bold>\<lfloor>Cod ?t\<^bold>\<rfloor>
\<lbrakk>Nml ?t; Nml ?u; Nml ?v; Src ?t = Trg ?u; Src ?u = Trg ?v\<rbrakk> \<Longrightarrow> (?t \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> ?u) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> ?v = ?t \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> ?u \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> ?v
goal (1 subgoal):
1. \<And>t1 t2 t3. \<lbrakk>\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor> = \<^bold>\<lfloor>t3\<^bold>\<rfloor>; Arr t1 \<and> Arr t2 \<and> Arr t3 \<and> Src t1 = Trg t2 \<and> Src t2 = Trg t3\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> ((\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>) = (\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
\<lbrakk>\<^bold>\<lfloor>Cod ?t1.0\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>?t1.0\<^bold>\<rfloor> = \<^bold>\<lfloor>?t1.0\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod ?t2.0\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>?t2.0\<^bold>\<rfloor> = \<^bold>\<lfloor>?t2.0\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod ?t3.0\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>?t3.0\<^bold>\<rfloor> = \<^bold>\<lfloor>?t3.0\<^bold>\<rfloor>; Arr ?t1.0 \<and> Arr ?t2.0 \<and> Arr ?t3.0 \<and> Src ?t1.0 = Trg ?t2.0 \<and> Src ?t2.0 = Trg ?t3.0\<rbrakk> \<Longrightarrow> (\<^bold>\<lfloor>Cod ?t1.0\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod ?t2.0\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod ?t3.0\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> ((\<^bold>\<lfloor>?t1.0\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>?t2.0\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>?t3.0\<^bold>\<rfloor>) = (\<^bold>\<lfloor>?t1.0\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>?t2.0\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>?t3.0\<^bold>\<rfloor>
goal (1 subgoal):
1. \<And>t1 t2 t3. \<lbrakk>\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor> = \<^bold>\<lfloor>t3\<^bold>\<rfloor>; Arr t1 \<and> Arr t2 \<and> Arr t3 \<and> Src t1 = Trg t2 \<and> Src t2 = Trg t3\<rbrakk> \<Longrightarrow> ((\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> (\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>) = \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>
[PROOF STEP]
show "\<And>t1 t2 t3. \<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<Longrightarrow> \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor> \<Longrightarrow>
\<^bold>\<lfloor>Cod t3\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor> = \<^bold>\<lfloor>t3\<^bold>\<rfloor> \<Longrightarrow>
Arr t1 \<and> Arr t2 \<and> Arr t3 \<and> Src t1 = Trg t2 \<and> Src t2 = Trg t3 \<Longrightarrow>
((\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> (\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>) =
\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>t1 t2 t3. \<lbrakk>\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor> = \<^bold>\<lfloor>t3\<^bold>\<rfloor>; Arr t1 \<and> Arr t2 \<and> Arr t3 \<and> Src t1 = Trg t2 \<and> Src t2 = Trg t3\<rbrakk> \<Longrightarrow> ((\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> (\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>) = \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>
[PROOF STEP]
using VcompNml_HcompNml Ide_Cod HcompNml_in_Hom Nml_HcompNml
Nml_Nmlize Nmlize_in_Hom HcompNml_assoc
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>Nml ?t; Nml ?u; Nml ?v; Nml ?w; VSeq ?t ?v; VSeq ?u ?w; Src ?v = Trg ?w\<rbrakk> \<Longrightarrow> (?t \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> ?u) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> (?v \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> ?w) = ?t \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> ?v \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> ?u \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> ?w
Arr ?t \<Longrightarrow> Ide (Cod ?t)
\<lbrakk>Nml ?t; Nml ?u; Src ?t = Trg ?u\<rbrakk> \<Longrightarrow> ?t \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> ?u \<in> HHom (Src ?u) (Trg ?t)
\<lbrakk>Nml ?t; Nml ?u; Src ?t = Trg ?u\<rbrakk> \<Longrightarrow> ?t \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> ?u \<in> VHom (Dom ?t \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> Dom ?u) (Cod ?t \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> Cod ?u)
\<lbrakk>Nml ?t; Nml ?u; Src ?t = Trg ?u\<rbrakk> \<Longrightarrow> Nml (?t \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> ?u)
\<lbrakk>Nml ?t; Nml ?u; Src ?t = Trg ?u\<rbrakk> \<Longrightarrow> Dom (?t \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> ?u) = Dom ?t \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> Dom ?u
\<lbrakk>Nml ?t; Nml ?u; Src ?t = Trg ?u\<rbrakk> \<Longrightarrow> Cod (?t \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> ?u) = Cod ?t \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> Cod ?u
\<lbrakk>Nml ?t; Nml ?u; Src ?t = Trg ?u\<rbrakk> \<Longrightarrow> Src (?t \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> ?u) = Src ?u
\<lbrakk>Nml ?t; Nml ?u; Src ?t = Trg ?u\<rbrakk> \<Longrightarrow> Trg (?t \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> ?u) = Trg ?t
Arr ?t \<Longrightarrow> Nml \<^bold>\<lfloor>?t\<^bold>\<rfloor>
Arr ?t \<Longrightarrow> Src \<^bold>\<lfloor>?t\<^bold>\<rfloor> = Src ?t
Arr ?t \<Longrightarrow> Trg \<^bold>\<lfloor>?t\<^bold>\<rfloor> = Trg ?t
Arr ?t \<Longrightarrow> Dom \<^bold>\<lfloor>?t\<^bold>\<rfloor> = \<^bold>\<lfloor>Dom ?t\<^bold>\<rfloor>
Arr ?t \<Longrightarrow> Cod \<^bold>\<lfloor>?t\<^bold>\<rfloor> = \<^bold>\<lfloor>Cod ?t\<^bold>\<rfloor>
Arr ?t \<Longrightarrow> \<^bold>\<lfloor>?t\<^bold>\<rfloor> \<in> HHom (Src ?t) (Trg ?t)
Arr ?t \<Longrightarrow> \<^bold>\<lfloor>?t\<^bold>\<rfloor> \<in> VHom \<^bold>\<lfloor>Dom ?t\<^bold>\<rfloor> \<^bold>\<lfloor>Cod ?t\<^bold>\<rfloor>
\<lbrakk>Nml ?t; Nml ?u; Nml ?v; Src ?t = Trg ?u; Src ?u = Trg ?v\<rbrakk> \<Longrightarrow> (?t \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> ?u) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> ?v = ?t \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> ?u \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> ?v
goal (1 subgoal):
1. \<And>t1 t2 t3. \<lbrakk>\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t1\<^bold>\<rfloor> = \<^bold>\<lfloor>t1\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> = \<^bold>\<lfloor>t2\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor> = \<^bold>\<lfloor>t3\<^bold>\<rfloor>; Arr t1 \<and> Arr t2 \<and> Arr t3 \<and> Src t1 = Trg t2 \<and> Src t2 = Trg t3\<rbrakk> \<Longrightarrow> ((\<^bold>\<lfloor>Cod t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t2\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod t3\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> (\<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>) = \<^bold>\<lfloor>t1\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t2\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>t3\<^bold>\<rfloor>
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
\<lbrakk>\<^bold>\<lfloor>Cod ?t1.0\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>?t1.0\<^bold>\<rfloor> = \<^bold>\<lfloor>?t1.0\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod ?t2.0\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>?t2.0\<^bold>\<rfloor> = \<^bold>\<lfloor>?t2.0\<^bold>\<rfloor>; \<^bold>\<lfloor>Cod ?t3.0\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> \<^bold>\<lfloor>?t3.0\<^bold>\<rfloor> = \<^bold>\<lfloor>?t3.0\<^bold>\<rfloor>; Arr ?t1.0 \<and> Arr ?t2.0 \<and> Arr ?t3.0 \<and> Src ?t1.0 = Trg ?t2.0 \<and> Src ?t2.0 = Trg ?t3.0\<rbrakk> \<Longrightarrow> ((\<^bold>\<lfloor>Cod ?t1.0\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod ?t2.0\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>Cod ?t3.0\<^bold>\<rfloor>) \<^bold>\<lfloor>\<^bold>\<cdot>\<^bold>\<rfloor> (\<^bold>\<lfloor>?t1.0\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>?t2.0\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>?t3.0\<^bold>\<rfloor>) = \<^bold>\<lfloor>?t1.0\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>?t2.0\<^bold>\<rfloor> \<^bold>\<lfloor>\<^bold>\<star>\<^bold>\<rfloor> \<^bold>\<lfloor>?t3.0\<^bold>\<rfloor>
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
Arr t \<Longrightarrow> \<^bold>\<lfloor>Cod t \<^bold>\<cdot> t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>
goal (1 subgoal):
1. \<^bold>\<lfloor>Cod t \<^bold>\<cdot> t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>
[PROOF STEP]
thus ?thesis
[PROOF STATE]
proof (prove)
using this:
Arr t \<Longrightarrow> \<^bold>\<lfloor>Cod t \<^bold>\<cdot> t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>
goal (1 subgoal):
1. \<^bold>\<lfloor>Cod t \<^bold>\<cdot> t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
Arr t \<Longrightarrow> \<^bold>\<lfloor>Cod t \<^bold>\<cdot> t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>
Arr t
goal (1 subgoal):
1. \<^bold>\<lfloor>Cod t \<^bold>\<cdot> t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
\<^bold>\<lfloor>Cod t \<^bold>\<cdot> t\<^bold>\<rfloor> = \<^bold>\<lfloor>t\<^bold>\<rfloor>
goal:
No subgoals!
[PROOF STEP]
qed
|
State Before: E : Type u_1
F : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace ℝ E
inst✝⁵ : FiniteDimensional ℝ E
inst✝⁴ : NormedAddCommGroup F
inst✝³ : NormedSpace ℝ F
s : Set E
f : E → E
f' : E → E →L[ℝ] E
inst✝² : MeasurableSpace E
inst✝¹ : BorelSpace E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
hs : MeasurableSet s
hf' : ∀ (x : E), x ∈ s → HasFDerivWithinAt f (f' x) s x
hf : InjOn f s
g : E → F
⊢ IntegrableOn g (f '' s) ↔ IntegrableOn (fun x => abs (ContinuousLinearMap.det (f' x)) • g (f x)) s State After: E : Type u_1
F : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace ℝ E
inst✝⁵ : FiniteDimensional ℝ E
inst✝⁴ : NormedAddCommGroup F
inst✝³ : NormedSpace ℝ F
s : Set E
f : E → E
f' : E → E →L[ℝ] E
inst✝² : MeasurableSpace E
inst✝¹ : BorelSpace E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
hs : MeasurableSet s
hf' : ∀ (x : E), x ∈ s → HasFDerivWithinAt f (f' x) s x
hf : InjOn f s
g : E → F
⊢ Integrable (g ∘ Set.restrict s f) ↔ IntegrableOn (fun x => abs (ContinuousLinearMap.det (f' x)) • g (f x)) s Tactic: rw [IntegrableOn, ← restrict_map_withDensity_abs_det_fderiv_eq_addHaar μ hs hf' hf,
(measurableEmbedding_of_fderivWithin hs hf' hf).integrable_map_iff] State Before: E : Type u_1
F : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace ℝ E
inst✝⁵ : FiniteDimensional ℝ E
inst✝⁴ : NormedAddCommGroup F
inst✝³ : NormedSpace ℝ F
s : Set E
f : E → E
f' : E → E →L[ℝ] E
inst✝² : MeasurableSpace E
inst✝¹ : BorelSpace E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
hs : MeasurableSet s
hf' : ∀ (x : E), x ∈ s → HasFDerivWithinAt f (f' x) s x
hf : InjOn f s
g : E → F
⊢ Integrable (g ∘ Set.restrict s f) ↔ IntegrableOn (fun x => abs (ContinuousLinearMap.det (f' x)) • g (f x)) s State After: E : Type u_1
F : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace ℝ E
inst✝⁵ : FiniteDimensional ℝ E
inst✝⁴ : NormedAddCommGroup F
inst✝³ : NormedSpace ℝ F
s : Set E
f : E → E
f' : E → E →L[ℝ] E
inst✝² : MeasurableSpace E
inst✝¹ : BorelSpace E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
hs : MeasurableSet s
hf' : ∀ (x : E), x ∈ s → HasFDerivWithinAt f (f' x) s x
hf : InjOn f s
g : E → F
⊢ Integrable ((g ∘ f) ∘ Subtype.val) ↔ IntegrableOn (fun x => abs (ContinuousLinearMap.det (f' x)) • g (f x)) s Tactic: change Integrable ((g ∘ f) ∘ ((↑) : s → E)) _ ↔ _ State Before: E : Type u_1
F : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace ℝ E
inst✝⁵ : FiniteDimensional ℝ E
inst✝⁴ : NormedAddCommGroup F
inst✝³ : NormedSpace ℝ F
s : Set E
f : E → E
f' : E → E →L[ℝ] E
inst✝² : MeasurableSpace E
inst✝¹ : BorelSpace E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
hs : MeasurableSet s
hf' : ∀ (x : E), x ∈ s → HasFDerivWithinAt f (f' x) s x
hf : InjOn f s
g : E → F
⊢ Integrable ((g ∘ f) ∘ Subtype.val) ↔ IntegrableOn (fun x => abs (ContinuousLinearMap.det (f' x)) • g (f x)) s State After: E : Type u_1
F : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace ℝ E
inst✝⁵ : FiniteDimensional ℝ E
inst✝⁴ : NormedAddCommGroup F
inst✝³ : NormedSpace ℝ F
s : Set E
f : E → E
f' : E → E →L[ℝ] E
inst✝² : MeasurableSpace E
inst✝¹ : BorelSpace E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
hs : MeasurableSet s
hf' : ∀ (x : E), x ∈ s → HasFDerivWithinAt f (f' x) s x
hf : InjOn f s
g : E → F
⊢ Integrable (g ∘ f) ↔ IntegrableOn (fun x => abs (ContinuousLinearMap.det (f' x)) • g (f x)) s Tactic: rw [← (MeasurableEmbedding.subtype_coe hs).integrable_map_iff, map_comap_subtype_coe hs] State Before: E : Type u_1
F : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace ℝ E
inst✝⁵ : FiniteDimensional ℝ E
inst✝⁴ : NormedAddCommGroup F
inst✝³ : NormedSpace ℝ F
s : Set E
f : E → E
f' : E → E →L[ℝ] E
inst✝² : MeasurableSpace E
inst✝¹ : BorelSpace E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
hs : MeasurableSet s
hf' : ∀ (x : E), x ∈ s → HasFDerivWithinAt f (f' x) s x
hf : InjOn f s
g : E → F
⊢ Integrable (g ∘ f) ↔ IntegrableOn (fun x => abs (ContinuousLinearMap.det (f' x)) • g (f x)) s State After: E : Type u_1
F : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace ℝ E
inst✝⁵ : FiniteDimensional ℝ E
inst✝⁴ : NormedAddCommGroup F
inst✝³ : NormedSpace ℝ F
s : Set E
f : E → E
f' : E → E →L[ℝ] E
inst✝² : MeasurableSpace E
inst✝¹ : BorelSpace E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
hs : MeasurableSet s
hf' : ∀ (x : E), x ∈ s → HasFDerivWithinAt f (f' x) s x
hf : InjOn f s
g : E → F
⊢ Integrable (g ∘ f) ↔ IntegrableOn (fun x => abs (ContinuousLinearMap.det (f' x)) • g (f x)) s Tactic: simp only [ENNReal.ofReal] State Before: E : Type u_1
F : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace ℝ E
inst✝⁵ : FiniteDimensional ℝ E
inst✝⁴ : NormedAddCommGroup F
inst✝³ : NormedSpace ℝ F
s : Set E
f : E → E
f' : E → E →L[ℝ] E
inst✝² : MeasurableSpace E
inst✝¹ : BorelSpace E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
hs : MeasurableSet s
hf' : ∀ (x : E), x ∈ s → HasFDerivWithinAt f (f' x) s x
hf : InjOn f s
g : E → F
⊢ Integrable (g ∘ f) ↔ IntegrableOn (fun x => abs (ContinuousLinearMap.det (f' x)) • g (f x)) s State After: E : Type u_1
F : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace ℝ E
inst✝⁵ : FiniteDimensional ℝ E
inst✝⁴ : NormedAddCommGroup F
inst✝³ : NormedSpace ℝ F
s : Set E
f : E → E
f' : E → E →L[ℝ] E
inst✝² : MeasurableSpace E
inst✝¹ : BorelSpace E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
hs : MeasurableSet s
hf' : ∀ (x : E), x ∈ s → HasFDerivWithinAt f (f' x) s x
hf : InjOn f s
g : E → F
⊢ (Integrable fun x => ↑(Real.toNNReal (abs (ContinuousLinearMap.det (f' x)))) • (g ∘ f) x) ↔
Integrable fun x => abs (ContinuousLinearMap.det (f' x)) • g (f x)
case hf
E : Type u_1
F : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace ℝ E
inst✝⁵ : FiniteDimensional ℝ E
inst✝⁴ : NormedAddCommGroup F
inst✝³ : NormedSpace ℝ F
s : Set E
f : E → E
f' : E → E →L[ℝ] E
inst✝² : MeasurableSpace E
inst✝¹ : BorelSpace E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
hs : MeasurableSet s
hf' : ∀ (x : E), x ∈ s → HasFDerivWithinAt f (f' x) s x
hf : InjOn f s
g : E → F
⊢ AEMeasurable fun x => Real.toNNReal (abs (ContinuousLinearMap.det (f' x))) Tactic: rw [restrict_withDensity hs, integrable_withDensity_iff_integrable_coe_smul₀, IntegrableOn] State Before: E : Type u_1
F : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace ℝ E
inst✝⁵ : FiniteDimensional ℝ E
inst✝⁴ : NormedAddCommGroup F
inst✝³ : NormedSpace ℝ F
s : Set E
f : E → E
f' : E → E →L[ℝ] E
inst✝² : MeasurableSpace E
inst✝¹ : BorelSpace E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
hs : MeasurableSet s
hf' : ∀ (x : E), x ∈ s → HasFDerivWithinAt f (f' x) s x
hf : InjOn f s
g : E → F
⊢ (Integrable fun x => ↑(Real.toNNReal (abs (ContinuousLinearMap.det (f' x)))) • (g ∘ f) x) ↔
Integrable fun x => abs (ContinuousLinearMap.det (f' x)) • g (f x) State After: E : Type u_1
F : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace ℝ E
inst✝⁵ : FiniteDimensional ℝ E
inst✝⁴ : NormedAddCommGroup F
inst✝³ : NormedSpace ℝ F
s : Set E
f : E → E
f' : E → E →L[ℝ] E
inst✝² : MeasurableSpace E
inst✝¹ : BorelSpace E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
hs : MeasurableSet s
hf' : ∀ (x : E), x ∈ s → HasFDerivWithinAt f (f' x) s x
hf : InjOn f s
g : E → F
⊢ (Integrable fun x => ↑(Real.toNNReal (abs (ContinuousLinearMap.det (f' x)))) • (g ∘ f) x) =
Integrable fun x => abs (ContinuousLinearMap.det (f' x)) • g (f x) Tactic: rw [iff_iff_eq] State Before: E : Type u_1
F : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace ℝ E
inst✝⁵ : FiniteDimensional ℝ E
inst✝⁴ : NormedAddCommGroup F
inst✝³ : NormedSpace ℝ F
s : Set E
f : E → E
f' : E → E →L[ℝ] E
inst✝² : MeasurableSpace E
inst✝¹ : BorelSpace E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
hs : MeasurableSet s
hf' : ∀ (x : E), x ∈ s → HasFDerivWithinAt f (f' x) s x
hf : InjOn f s
g : E → F
⊢ (Integrable fun x => ↑(Real.toNNReal (abs (ContinuousLinearMap.det (f' x)))) • (g ∘ f) x) =
Integrable fun x => abs (ContinuousLinearMap.det (f' x)) • g (f x) State After: case e_f.h
E : Type u_1
F : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace ℝ E
inst✝⁵ : FiniteDimensional ℝ E
inst✝⁴ : NormedAddCommGroup F
inst✝³ : NormedSpace ℝ F
s : Set E
f : E → E
f' : E → E →L[ℝ] E
inst✝² : MeasurableSpace E
inst✝¹ : BorelSpace E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
hs : MeasurableSet s
hf' : ∀ (x : E), x ∈ s → HasFDerivWithinAt f (f' x) s x
hf : InjOn f s
g : E → F
x : E
⊢ ↑(Real.toNNReal (abs (ContinuousLinearMap.det (f' x)))) • (g ∘ f) x = abs (ContinuousLinearMap.det (f' x)) • g (f x) Tactic: congr 2 with x State Before: case e_f.h
E : Type u_1
F : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace ℝ E
inst✝⁵ : FiniteDimensional ℝ E
inst✝⁴ : NormedAddCommGroup F
inst✝³ : NormedSpace ℝ F
s : Set E
f : E → E
f' : E → E →L[ℝ] E
inst✝² : MeasurableSpace E
inst✝¹ : BorelSpace E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
hs : MeasurableSet s
hf' : ∀ (x : E), x ∈ s → HasFDerivWithinAt f (f' x) s x
hf : InjOn f s
g : E → F
x : E
⊢ ↑(Real.toNNReal (abs (ContinuousLinearMap.det (f' x)))) • (g ∘ f) x = abs (ContinuousLinearMap.det (f' x)) • g (f x) State After: case e_f.h
E : Type u_1
F : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace ℝ E
inst✝⁵ : FiniteDimensional ℝ E
inst✝⁴ : NormedAddCommGroup F
inst✝³ : NormedSpace ℝ F
s : Set E
f : E → E
f' : E → E →L[ℝ] E
inst✝² : MeasurableSpace E
inst✝¹ : BorelSpace E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
hs : MeasurableSet s
hf' : ∀ (x : E), x ∈ s → HasFDerivWithinAt f (f' x) s x
hf : InjOn f s
g : E → F
x : E
⊢ abs (ContinuousLinearMap.det (f' x)) • (g ∘ f) x = abs (ContinuousLinearMap.det (f' x)) • g (f x) Tactic: rw [Real.coe_toNNReal _ (abs_nonneg _)] State Before: case e_f.h
E : Type u_1
F : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace ℝ E
inst✝⁵ : FiniteDimensional ℝ E
inst✝⁴ : NormedAddCommGroup F
inst✝³ : NormedSpace ℝ F
s : Set E
f : E → E
f' : E → E →L[ℝ] E
inst✝² : MeasurableSpace E
inst✝¹ : BorelSpace E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
hs : MeasurableSet s
hf' : ∀ (x : E), x ∈ s → HasFDerivWithinAt f (f' x) s x
hf : InjOn f s
g : E → F
x : E
⊢ abs (ContinuousLinearMap.det (f' x)) • (g ∘ f) x = abs (ContinuousLinearMap.det (f' x)) • g (f x) State After: no goals Tactic: rfl State Before: case hf
E : Type u_1
F : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace ℝ E
inst✝⁵ : FiniteDimensional ℝ E
inst✝⁴ : NormedAddCommGroup F
inst✝³ : NormedSpace ℝ F
s : Set E
f : E → E
f' : E → E →L[ℝ] E
inst✝² : MeasurableSpace E
inst✝¹ : BorelSpace E
μ : Measure E
inst✝ : IsAddHaarMeasure μ
hs : MeasurableSet s
hf' : ∀ (x : E), x ∈ s → HasFDerivWithinAt f (f' x) s x
hf : InjOn f s
g : E → F
⊢ AEMeasurable fun x => Real.toNNReal (abs (ContinuousLinearMap.det (f' x))) State After: no goals Tactic: exact aemeasurable_toNNReal_abs_det_fderivWithin μ hs hf'
|
If a set of vectors is pairwise orthogonal and does not contain the zero vector, then it is linearly independent.
|
(*
* Copyright 2014, NICTA
*
* This software may be distributed and modified according to the terms of
* the BSD 2-Clause license. Note that NO WARRANTY is provided.
* See "LICENSE_BSD2.txt" for details.
*
* @TAG(NICTA_BSD)
*)
theory Memcpy
imports
"CParser.CTranslation"
"AutoCorres.AutoCorres"
begin
abbreviation "ADDR_MAX \<equiv> UWORD_MAX TYPE(addr_bitsize)"
(* Helper for noticing when you accidentally haven't constrained an of_nat *)
abbreviation "of_nat_addr \<equiv> of_nat::(nat \<Rightarrow> addr)"
lemma byte_ptr_guarded:
"ptr_val (x::8 word ptr) \<noteq> 0 \<Longrightarrow> c_guard x"
unfolding c_guard_def c_null_guard_def ptr_aligned_def
by (clarsimp simp: intvl_Suc)
(* FIXME: MOVE *)
lemma ptr_add_coerce: "ptr_val (((ptr_coerce x)::('a::{c_type}) ptr) +\<^sub>p a) = (ptr_val x) + (of_int a * of_nat (size_of TYPE('a)))"
apply (case_tac x)
apply (clarsimp simp: CTypesDefs.ptr_add_def)
done
(* FIXME: MOVE *)
(* Casting a valid pointer to char* and incrementing it by a value less than
* the size of the underlying type does not give us NULL.
*)
lemma ptr_contained:"\<lbrakk> c_guard (x::('a::c_type) ptr); size_of TYPE('a) = sz;
0 \<le> i; i < int sz; (y::8 word ptr) = ptr_coerce x\<rbrakk> \<Longrightarrow> c_guard (y +\<^sub>p i)"
apply (rule byte_ptr_guarded)
unfolding c_guard_def c_null_guard_def ptr_add_def
apply simp
apply (clarsimp simp: CTypesDefs.ptr_add_def intvl_def)
apply (erule allE [where x="nat i"])
apply (clarsimp simp: nat_less_iff of_nat_nat)
done
external_file "memcpy.c"
install_C_file "memcpy.c"
(* FIXME: MOVE *)
lemma squash_auxupd_id[polish]:
"modify (t_hrs_'_update (hrs_htd_update id)) = skip"
by (monad_eq simp: skip_def id_def hrs_htd_update_def)
autocorres [no_heap_abs=memcpy memcpy_int] "memcpy.c"
(* Dereference a pointer *)
abbreviation "deref s x \<equiv> h_val (hrs_mem (t_hrs_' s)) x"
(* char* cast *)
abbreviation "byte_cast x \<equiv> ((ptr_coerce x)::8 word ptr)"
context memcpy begin
lemma memcpy_char:
"\<lbrace> \<lambda>s. c_guard (x::8 word ptr) \<and>
c_guard (y::8 word ptr) \<and>
unat sz = size_of TYPE(8 word) \<and>
P (deref s x) \<and>
x \<noteq> y\<rbrace>
memcpy' (ptr_coerce y) (ptr_coerce x) sz
\<lbrace>\<lambda> _ s. P (deref s y) \<rbrace>!"
(* Evaluate sz *)
apply clarsimp
unfolding memcpy'_def
apply (clarsimp simp:skip_def)
apply wp
(* Unroll the loop twice *)
apply (subst whileLoop_unroll, wp)
apply (subst whileLoop_unroll, wp)
(* The remaining loop is never encountered *)
apply (rule validNF_false_pre)
apply wp+
(* Finally we're left with the single assignment *)
apply (clarsimp simp:hrs_mem_update h_val_heap_update)
apply unat_arith
done
lemma of_nat_prop_exp: "n < 32 \<Longrightarrow> of_nat (2 ^ n) = 2 ^ (of_nat n)"
by clarsimp
lemma memcpy_word:
"\<lbrace> \<lambda>s. c_guard (x::32 word ptr) \<and>
c_guard (y::32 word ptr) \<and>
unat sz = size_of TYPE(32 word) \<and>
P (deref s x) \<and>
x \<noteq> y \<rbrace>
memcpy' (ptr_coerce y) (ptr_coerce x) sz
\<lbrace> \<lambda>_ s. P (deref s y) \<rbrace>!"
apply clarsimp
unfolding memcpy'_def apply (clarsimp simp:skip_def)
apply (rule validNF_assume_pre)
apply (subgoal_tac "{ptr_val x ..+ unat sz} \<inter> {ptr_val y ..+ unat sz} = {}")
apply (subst whileLoop_add_inv [where
I="\<lambda>i s. unat i \<le> unat sz \<and>
(\<forall>a < i. deref s (byte_cast x +\<^sub>p uint a) = deref s (byte_cast y +\<^sub>p uint a)) \<and>
P (deref s x)" and
M="\<lambda>(i, s). unat sz - unat i"])
apply (wp validNF_whileLoop_inv_measure_twosteps)
apply clarsimp
apply (rule conjI, unat_arith)
apply (rule conjI, clarsimp)
apply (case_tac "a = i")
apply (clarsimp)
apply (erule_tac x=i in allE)
apply (clarsimp simp:hrs_mem_update h_val_heap_update)
apply (subst h_val_heap_same)
apply (rule ptr_retyp_h_t_valid)
apply simp
apply (rule ptr_retyp_disjoint)
apply (rule ptr_retyp_h_t_valid)
apply simp
apply (clarsimp simp:ptr_add_def intvl_def CTypesDefs.ptr_add_def)
apply simp
apply (clarsimp simp: CTypesDefs.ptr_add_def field_of_t_simple)
apply (drule field_of_t_simple)
apply clarsimp
apply simp
apply (subgoal_tac "a < i")
apply (clarsimp simp:hrs_mem_update)
apply (subst h_val_heap_update_disjoint)
(* The current goal should be obvious to unat_arith, but for some reason isn't *)
apply (clarsimp simp:ptr_add_def intvl_def disjoint_iff_not_equal)
apply (erule_tac x="ptr_val x + a" in allE, clarsimp)
apply (erule impE)
apply (rule_tac x="unat a" in exI, clarsimp)
apply unat_arith
apply (erule_tac x="ptr_val y + i" and
P="\<lambda>ya. (\<exists>k. ya = ptr_val y + of_nat k \<and> k < 4) \<longrightarrow> ptr_val y + i \<noteq> ya" in allE, clarsimp)
apply (erule_tac x="unat i" in allE, clarsimp)
apply unat_arith
apply (clarsimp simp:CTypesDefs.ptr_add_def)
apply (subst h_val_heap_update_disjoint)
(* Similar goal to the previous irritation, but this time Isabelle decides to play ball *)
apply (clarsimp simp:ptr_add_def intvl_def ptr_val_def disjoint_iff_not_equal)
apply (clarsimp simp:CTypesDefs.ptr_add_def)
apply (clarsimp simp:CTypesDefs.ptr_add_def)
apply unat_arith
apply (rule conjI)
apply (subst hrs_mem_update)+
apply (subst h_val_heap_update_disjoint)
apply (clarsimp simp: disjoint_iff_not_equal)
apply (clarsimp simp:CTypesDefs.ptr_add_def intvl_def)
apply (erule_tac x="ptr_val x + of_nat k" in allE)
apply (erule impE)
apply (rule_tac x="k" in exI)
apply simp
apply (erule_tac x="ptr_val y + i" and
P="\<lambda>ya. (\<exists>k. ya = ptr_val y + of_nat k \<and> k < 4) \<longrightarrow> ptr_val x + of_nat k \<noteq> ya" in allE)
apply (erule impE)
apply (rule_tac x="unat i" in exI)
apply simp
apply unat_arith
apply simp
apply simp
(* Yet more tedium that unat_arith doesn't like *)
apply (rule conjI)
apply (rule byte_ptr_guarded,
clarsimp simp:CTypesDefs.ptr_add_def c_guard_def c_null_guard_def intvl_def,
(erule_tac x="unat i" in allE)+,
clarsimp,
unat_arith)+
apply wp
apply unat_arith
apply clarsimp
apply (subgoal_tac "deref sa x = deref sa y")
apply clarsimp
apply (clarsimp simp: h_val_def)[1]
apply (rule arg_cong[where f=from_bytes])
apply (subst numeral_eqs(3))+
apply simp
apply (rule_tac x=0 in allE, assumption, erule impE, unat_arith)
apply (rule_tac x=1 in allE, assumption, erule impE, unat_arith)
apply (rule_tac x=2 in allE, assumption, erule impE, unat_arith)
apply (rule_tac x=3 in allE, assumption, erule impE, unat_arith)
apply (simp add:CTypesDefs.ptr_add_def)
apply (simp add: add.commute from_bytes_eq)
apply clarsimp
apply (clarsimp simp:intvl_def disjoint_iff_not_equal)
apply (drule_tac x=x and y=y and j="of_nat k" and i="of_nat ka" and n=2 in neq_imp_bytes_disjoint)
apply assumption
apply (case_tac "k = 0", clarsimp) (* insert "k > 0" *)
apply (clarsimp simp:unat_of_nat_len)
apply (case_tac "ka = 0", clarsimp)
apply (clarsimp simp:unat_of_nat_len)
apply assumption
apply clarsimp+
done
text \<open>The bytes at the pointer @{term p} are @{term bs}.\<close>
definition
bytes_at :: "'a globals_scheme \<Rightarrow> 'b::c_type ptr \<Rightarrow> word8 list \<Rightarrow> bool"
where
"bytes_at s p bs \<equiv> length bs = 0 \<or>
(length bs \<le> ADDR_MAX \<and> (\<forall>i \<in> {0..(length bs - 1)}. deref s (byte_cast p +\<^sub>p (of_nat i)) = bs ! i))"
lemma bytes_at_none[simp]: "bytes_at s p []"
by (clarsimp simp:bytes_at_def)
text \<open>The bytes of typed pointer @{term p} are @{term bs}.\<close>
definition
bytes_of :: "'a globals_scheme \<Rightarrow> 'b::c_type ptr \<Rightarrow> word8 list \<Rightarrow> bool"
where
"bytes_of s p bs \<equiv> length bs = size_of TYPE('b) \<and> bytes_at s p bs"
text \<open>The bytes at a char pointer are just it dereferenced.\<close>
lemma bytes_of_char[simp]: "bytes_of s (p::8word ptr) bs = (length bs = 1 \<and> deref s p = hd bs)"
apply (clarsimp simp:bytes_of_def bytes_at_def)
apply (rule iffI)
apply clarsimp
apply (erule disjE)
apply clarsimp+
apply (rule hd_conv_nth[symmetric])
apply clarsimp+
apply (subgoal_tac "hd bs = bs ! 0")
apply simp
apply (rule hd_conv_nth)
apply clarsimp
done
text \<open>A pointer does not wrap around memory.\<close>
definition
no_wrap :: "'a::c_type ptr \<Rightarrow> nat \<Rightarrow> bool"
where
"no_wrap p sz \<equiv> 0 \<notin> {ptr_val p ..+ sz}"
text \<open>Two pointers do not overlap.\<close>
definition
no_overlap :: "'a::c_type ptr \<Rightarrow> 'b::c_type ptr \<Rightarrow> nat \<Rightarrow> bool"
where
"no_overlap p q sz \<equiv> {ptr_val p ..+ sz} \<inter> {ptr_val q ..+ sz} = {}"
lemma no_overlap_sym: "no_overlap x y = no_overlap y x"
apply (rule ext)
apply (clarsimp simp:no_overlap_def)
by blast
(* FIXME: MOVE *)
lemma h_val_not_id:
fixes x :: "'a::mem_type ptr"
and y :: "'b::mem_type ptr"
shows "{ptr_val x..+size_of TYPE('a)} \<inter> {ptr_val y..+size_of TYPE('b)} = {}
\<Longrightarrow> h_val (hrs_mem (hrs_mem_update (heap_update x v) s)) y = h_val (hrs_mem s) y"
apply (subst hrs_mem_heap_update[symmetric])
apply (subst h_val_heap_update_disjoint)
apply blast
apply clarsimp
done
definition
update_bytes :: "'a globals_scheme \<Rightarrow> 'b::mem_type ptr \<Rightarrow> word8 list \<Rightarrow> 'a globals_scheme"
where
"update_bytes s p bs \<equiv> s\<lparr>t_hrs_' := hrs_mem_update (heap_update_list (ptr_val p) bs) (t_hrs_' s)\<rparr>"
lemma the_horse_says_neigh: "(s\<lparr>t_hrs_' := x\<rparr> = s\<lparr>t_hrs_' := y\<rparr>) = (x = y)"
by (metis (erased, lifting) globals.cases_scheme globals.select_convs(1) globals.update_convs(1))
lemma upto_singleton[simp]:"[x..x] = [x]"
by (simp add: upto_rec1)
lemma update_bytes_ignore_ptr_coerce[simp]: "update_bytes s (ptr_coerce p) = update_bytes s p"
by (clarsimp simp:update_bytes_def intro!:ext)
lemma hrs_mem_update_commute:
"f \<circ> g = g \<circ> f \<Longrightarrow> hrs_mem_update f (hrs_mem_update g s) = hrs_mem_update g (hrs_mem_update f s)"
by (metis (no_types, lifting) comp_eq_elim hrs_htd_def hrs_htd_mem_update hrs_mem_def hrs_mem_f prod.collapse)
lemma hrs_mem_update_collapse:
"hrs_mem_update f (hrs_mem_update g s) = hrs_mem_update (f \<circ> g) s"
by (metis comp_eq_dest_lhs hrs_htd_def hrs_htd_mem_update hrs_mem_def hrs_mem_f prod.collapse)
lemma update_bytes_reorder:
"{ptr_val p..+length cs} \<inter> {ptr_val q..+length bs} = {} \<Longrightarrow>
update_bytes (update_bytes s q bs) p cs = update_bytes (update_bytes s p cs) q bs"
apply (clarsimp simp:update_bytes_def)
apply (subst the_horse_says_neigh)
apply (subst hrs_mem_update_commute)
apply (clarsimp intro!:ext)
apply (subst heap_update_list_commute)
apply clarsimp+
done
lemma lt_step_down: "\<lbrakk>(x::nat) < y; x = y - 1 \<longrightarrow> P; x < y - 1 \<longrightarrow> P\<rbrakk> \<Longrightarrow> P"
by force
(* XXX: This proof makes me sad. *)
lemma under_uint_imp_no_overflow: "x < ADDR_MAX \<Longrightarrow> ((of_nat x)::addr) + 1 \<noteq> 0"
apply (induct x)
apply (clarsimp simp:UWORD_MAX_def)+
apply unat_arith
apply (clarsimp simp:UWORD_MAX_def)
apply (cut_tac y=x and z="(of_nat (ADDR_MAX - 1))::addr" in le_unat_uoi)
apply (clarsimp simp:UWORD_MAX_def)+
done
lemma heap_update_list_append3:
"1 + length ys < 2 ^ word_bits \<Longrightarrow>
heap_update_list s (y # ys) hp = heap_update_list s [y] (heap_update_list (s + 1) ys hp)"
apply clarsimp
apply (subst heap_update_list_append2[where xs="[y]", simplified])
apply clarsimp+
done
lemma hrs_mem_update_cong': "f = g \<Longrightarrow> hrs_mem_update f s = hrs_mem_update g s"
by presburger
lemma update_bytes_append: "length bs \<le> ADDR_MAX \<Longrightarrow>
update_bytes s p (b # bs) = update_bytes (update_bytes s p [b]) (byte_cast p +\<^sub>p 1) bs"
apply (clarsimp simp:update_bytes_def)
apply (subst the_horse_says_neigh)
apply (subst hrs_mem_update_commute)
apply (rule ext)+
apply simp
apply (case_tac "xa = ptr_val p")
apply (clarsimp simp:fun_upd_def)
apply (subst heap_update_nmem_same)
apply (clarsimp simp:intvl_def ptr_add_def)
apply (subgoal_tac "k < ADDR_MAX")
prefer 2
apply unat_arith
apply (drule under_uint_imp_no_overflow)
apply unat_arith
apply clarsimp
apply (subst heap_update_list_update)
apply simp
apply (clarsimp simp:fun_upd_def)
apply (subst hrs_mem_update_collapse)
apply (rule hrs_mem_update_cong')
apply (clarsimp simp:ptr_add_def)
apply (rule ext)
apply (cut_tac xs="[b]" and ys=bs and s="ptr_val p" and hp=x in heap_update_list_append)
apply (clarsimp simp:fun_upd_def intro!:ext)
apply (rule conjI)
apply clarsimp
apply (subst heap_update_nmem_same)
apply (clarsimp simp:ptr_add_def intvl_def)
apply (subgoal_tac "k < ADDR_MAX")
prefer 2
apply unat_arith
apply (drule under_uint_imp_no_overflow)
apply unat_arith
apply clarsimp
apply clarsimp
apply (case_tac "xa \<in> {ptr_val p + 1..+length bs}")
apply (subst heap_update_mem_same_point)
apply simp
apply (subgoal_tac "addr_card = ADDR_MAX + 1")
apply clarsimp
apply (clarsimp simp:addr_card UWORD_MAX_def)
apply (subst heap_update_mem_same_point)
apply simp
apply (subgoal_tac "addr_card = ADDR_MAX + 1")
apply clarsimp
apply (clarsimp simp:addr_card UWORD_MAX_def)
apply clarsimp
apply (subst heap_update_nmem_same)
apply clarsimp
apply (subst heap_update_nmem_same)
apply clarsimp+
done
lemma update_bytes_postpend: "length bs = x + 1 \<Longrightarrow>
update_bytes s p bs = update_bytes (update_bytes s p (take x bs)) (byte_cast p +\<^sub>p (of_nat x)) [bs ! x]"
apply (clarsimp simp:update_bytes_def)
apply (subst the_horse_says_neigh)
apply (clarsimp simp:ptr_add_def)
apply (subst heap_update_list_concat_fold_hrs_mem)
apply clarsimp+
by (metis append_eq_conv_conj append_self_conv hd_drop_conv_nth2 lessI take_hd_drop)
lemma h_val_not_id_general:
fixes y :: "'a::mem_type ptr"
shows "\<forall>i \<in> {0..+size_of TYPE('a)}. \<forall>g. f g (ptr_val y + i) = g (ptr_val y + i)
\<Longrightarrow> h_val (hrs_mem (hrs_mem_update f s)) y = h_val (hrs_mem s) y"
apply (subst hrs_mem_update)
apply (clarsimp simp:h_val_def)
apply (subgoal_tac "heap_list (f (hrs_mem s)) (size_of TYPE('a)) (ptr_val y) =
heap_list (hrs_mem s) (size_of TYPE('a)) (ptr_val y)")
apply clarsimp
apply (cut_tac h="f (hrs_mem s)" and p="ptr_val y" and n="size_of TYPE('a)"
and h'="hrs_mem s" in heap_list_h_eq2)
apply (erule_tac x="x - ptr_val y" in ballE)
apply clarsimp
apply (clarsimp simp:intvl_def)+
done
lemma h_val_not_id_list:
fixes y :: "'a::mem_type ptr"
shows "{x..+length vs} \<inter> {ptr_val y..+size_of TYPE('a)} = {}
\<Longrightarrow> h_val (hrs_mem (hrs_mem_update (heap_update_list x vs) s)) y = h_val (hrs_mem s) y"
apply (subst h_val_not_id_general)
apply clarsimp
apply (metis (erased, hide_lams) disjoint_iff_not_equal heap_update_nmem_same intvlD intvlI
monoid_add_class.add.left_neutral)
apply clarsimp
done
lemma h_val_id_update_bytes:
fixes q :: "'a::mem_type ptr"
shows "{ptr_val q..+size_of TYPE('a)} \<inter> {ptr_val p..+length bs} = {}
\<Longrightarrow> deref (update_bytes s p bs) q = deref s q"
apply (clarsimp simp:update_bytes_def)
apply (subst h_val_not_id_list)
apply blast
by simp
lemma bytes_at_len: "bytes_at s p bs \<Longrightarrow> length bs \<le> ADDR_MAX"
by (clarsimp simp:bytes_at_def, fastforce)
(* Another sad proof. *)
lemma le_uint_max_imp_id: "x \<le> ADDR_MAX \<Longrightarrow> unat ((of_nat x)::addr) = x"
apply (induct x)
apply (clarsimp simp: UWORD_MAX_def)+
apply unat_arith
apply clarsimp
done
lemma update_bytes_id: "update_bytes s p [] = s"
apply (clarsimp simp:update_bytes_def)
apply (subst heap_update_list_base')
by (simp add: hrs_mem_update_id3)
lemma a_horse_by_any_other_name: "t_hrs_'_update f s = s\<lparr>t_hrs_' := f (t_hrs_' s)\<rparr>"
by auto
lemma heap_update_list_singleton: "heap_update_list p [x] = heap_update (Ptr p) x"
apply (rule ext)
by (metis heap_update_def ptr_val.simps to_bytes_word8)
lemma update_bytes_eq: "\<lbrakk>s = s'; p = p'; bs = bs'\<rbrakk> \<Longrightarrow> update_bytes s p bs = update_bytes s' p' bs'"
by clarsimp
text \<open>
Memcpy does what it says on the box.
\<close>
lemma memcpy_wp':
fixes src :: "'a::mem_type ptr"
and dst :: "'b::mem_type ptr"
shows "\<forall>s0 bs.
\<lbrace>\<lambda>s. s = s0 \<and> c_guard src \<and> c_guard dst \<and> sz = of_nat (length bs) \<and> bytes_at s src bs \<and>
no_wrap src (unat sz) \<and> no_wrap dst (unat sz) \<and> no_overlap src dst (unat sz)\<rbrace>
memcpy' (ptr_coerce dst) (ptr_coerce src) sz
\<lbrace>\<lambda>r s. r = ptr_coerce dst \<and> bytes_at s dst bs \<and> s = update_bytes s0 dst bs\<rbrace>!"
apply (rule allI)+
apply (rule validNF_assume_pre)
unfolding memcpy'_def
apply clarsimp
apply (subst whileLoop_add_inv[where
I="\<lambda>i s. unat i \<le> unat sz \<and>
bytes_at s dst (take (unat i) bs) \<and>
bytes_at s src bs \<and>
s = update_bytes s0 dst (take (unat i) bs)" and
M="\<lambda>(i, s). unat sz - unat i"])
apply wp
apply clarsimp
apply (rule conjI)
apply unat_arith
apply (rule conjI)
apply (simp add:bytes_at_def)
apply (case_tac "bs = []")
apply (rule disjI1)
apply clarsimp
apply (rule disjI2)
apply clarsimp
apply (rule conjI)
apply unat_arith
apply clarsimp
apply (case_tac "unat i = ia")
apply clarsimp
apply (subgoal_tac "int (unat i) = uint i")
prefer 2
apply (subst uint_nat)
apply simp
apply simp
apply (subst h_val_id)
apply (subst h_val_id_update_bytes)
apply (clarsimp simp:no_overlap_def ptr_add_def)
apply (subgoal_tac "{ptr_val src + i..+Suc 0} \<subseteq> {ptr_val src..+unat (of_nat_addr (length bs))}")
prefer 2
apply (clarsimp simp:intvl_def)
apply (rule_tac x="unat i" in exI)
apply unat_arith
apply (subgoal_tac "{ptr_val dst..+unat i} \<subseteq> {ptr_val dst..+unat (of_nat_addr (length bs))}")
prefer 2
apply (clarsimp simp:intvl_def)
apply (rule exI, rule conjI, rule refl)
apply (simp add: unat_of_nat)
apply blast
apply (erule_tac x="unat i" and P="\<lambda>x. deref s0 (byte_cast src +\<^sub>p int x) = bs ! x" in ballE)
apply clarsimp
apply (subst nth_take)
apply unat_arith
apply simp
apply (erule disjE)
apply clarsimp+
apply (erule disjE)
apply (subgoal_tac "length bs \<noteq> 0")
prefer 2
apply clarsimp
apply (case_tac "unat i = 0")
apply unat_arith
apply linarith
apply (subst h_val_not_id)
apply (clarsimp simp:ptr_add_def intvl_def)
(* Isabelle, why do you have to make it so hard? *)
apply (erule_tac P="unat (of_nat ia) = ia" in notE)
apply (cut_tac y=ia and z="(of_nat ADDR_MAX)::addr" in le_unat_uoi)
apply (subgoal_tac "unat ((of_nat ADDR_MAX)::addr) = ADDR_MAX")
prefer 2
apply (simp add: unat_of_nat)
apply (simp add: unat_of_nat)
apply clarsimp
apply clarsimp
apply (erule_tac x=ia and A="{0..min (length bs) (unat i) - Suc 0}" in ballE)
apply clarsimp
apply (subst nth_take, unat_arith)+
apply simp
apply clarsimp
apply unat_arith
apply (rule conjI)
apply (clarsimp simp:bytes_at_def)
apply (subst h_val_not_id)
apply (clarsimp simp:no_overlap_def)
apply (subgoal_tac "ptr_val (byte_cast dst +\<^sub>p uint i) \<in> {ptr_val dst..+unat (of_nat (length bs))}")
prefer 2
apply (clarsimp simp:ptr_add_def intvl_def)
apply (rule_tac x="unat i" in exI)
apply clarsimp
apply unat_arith
(* More or less symmetric subgoal *)
apply (subgoal_tac "ptr_val (byte_cast src +\<^sub>p int ia) \<in> {ptr_val src..+unat ((of_nat (length bs))::addr)}")
prefer 2
apply (clarsimp simp:ptr_add_def intvl_def)
apply (rule_tac x=ia in exI)
apply clarsimp
apply (subgoal_tac "unat ((of_nat (length bs))::addr) = length bs")
apply clarsimp
apply arith
apply (cut_tac y="length bs" and z="(of_nat ADDR_MAX)::addr" in le_unat_uoi)
apply (simp add: unat_of_nat)
apply arith
apply (clarsimp simp:intvl_def ptr_add_def)
apply blast
apply clarsimp
apply (rule conjI)
apply (subst h_val_id_update_bytes)
apply (clarsimp simp:no_overlap_def ptr_add_def)
apply (subgoal_tac "{ptr_val src + i..+Suc 0} \<subseteq> {ptr_val src..+unat (of_nat_addr (length bs))}")
prefer 2
apply (clarsimp simp:intvl_def)
apply (rule_tac x="unat i" in exI)
apply unat_arith
apply (subgoal_tac "{ptr_val dst..+min (length bs) (unat i)} \<subseteq> {ptr_val dst..+unat (of_nat_addr (length bs))}")
prefer 2
apply (clarsimp simp:intvl_def)
apply (rule_tac x=ka in exI)
apply unat_arith
apply blast
apply (subgoal_tac "deref s0 (byte_cast src +\<^sub>p uint i) = bs ! (unat i)")
apply clarsimp
apply (subgoal_tac "update_bytes s0 dst (take (unat (i + 1)) bs) =
update_bytes (update_bytes s0 dst (take (unat i) bs)) (byte_cast dst +\<^sub>p uint i) [bs ! unat i]")
apply clarsimp
apply (subgoal_tac
"\<forall>s'. t_hrs_'_update (hrs_mem_update (heap_update (byte_cast dst +\<^sub>p uint i) (bs ! unat i))) s' =
update_bytes s' (byte_cast dst +\<^sub>p uint i) [bs ! unat i]")
apply fast
apply (clarsimp simp:update_bytes_def)
apply (subst a_horse_by_any_other_name)
apply (subst the_horse_says_neigh)
apply (clarsimp simp:ptr_add_def)
apply (subst heap_update_list_singleton)
apply simp
apply (cut_tac s=s0 and p=dst and bs="take (unat (i + 1)) bs" and x="unat i"
in update_bytes_postpend)
apply (subgoal_tac "unat (i + 1) \<le> length bs")
apply clarsimp
apply unat_arith
apply (subgoal_tac "unat i < length bs")
apply unat_arith
apply (rule unat_less_helper)
apply simp
apply clarsimp
apply (rule update_bytes_eq)
apply (subgoal_tac "min (unat i) (unat (i + 1)) = unat i")
apply clarsimp
apply clarsimp
apply unat_arith
apply (clarsimp simp:ptr_add_def)
apply clarsimp
apply (rule nth_take)
apply unat_arith
apply (clarsimp simp:bytes_at_def)
apply (erule disjE)
apply clarsimp
apply clarsimp
apply (erule_tac x="unat i" in ballE)
apply (subst (asm) uint_nat[symmetric])
apply simp
apply clarsimp
apply (subgoal_tac "unat i < length bs")
prefer 2
apply (rule unat_less_helper)
apply simp
apply unat_arith
apply (rule conjI)
apply unat_arith
apply (rule conjI)
apply (rule byte_ptr_guarded)
apply (clarsimp simp:no_wrap_def intvl_def ptr_add_def)
apply (erule_tac x="unat i" in allE)
apply clarsimp
apply (rule byte_ptr_guarded)
apply (clarsimp simp:no_wrap_def intvl_def ptr_add_def)
apply (erule_tac x="unat i" and
P="\<lambda>x. ptr_val dst + ((of_nat x)::addr) = 0 \<longrightarrow> \<not> x < unat ((of_nat_addr (length bs))::addr)"
in allE)
apply clarsimp
apply clarsimp
apply (rule conjI)
apply (subgoal_tac "unat i = length bs")
apply clarsimp
apply (case_tac "length bs = 0")
apply clarsimp
apply (subgoal_tac "length bs \<le> ADDR_MAX")
prefer 2
apply (clarsimp simp:bytes_at_def)
(* XXX: We keep introducing this subgoal; we should do it once and for all up top. *)
apply (subgoal_tac "unat ((of_nat (length bs))::addr) = length bs")
prefer 2
apply (cut_tac y="length bs" and z="(of_nat ADDR_MAX)::addr" in le_unat_uoi)
apply (clarsimp simp:UWORD_MAX_def)
apply clarsimp+
apply unat_arith
(* insert a bunch a tedium... *)
apply (subgoal_tac "unat i = length bs")
prefer 2
apply (drule bytes_at_len)
apply (subgoal_tac "unat (of_nat_addr (length bs)) = length bs")
prefer 2
apply (rule le_uint_max_imp_id)
apply simp
apply unat_arith
apply clarsimp
apply (simp add:update_bytes_id)
done
lemma validNF_make_schematic_post':
"(\<forall>s0 x. \<lbrace> \<lambda>s. P s0 x s \<rbrace> f \<lbrace> \<lambda>rv s. Q s0 x rv s \<rbrace>!) \<Longrightarrow>
\<lbrace> \<lambda>s. \<exists>s0 x. P s0 x s \<and> (\<forall>rv s'. Q s0 x rv s' \<longrightarrow> Q' rv s') \<rbrace> f \<lbrace> Q'\<rbrace>!"
by (auto simp add: valid_def validNF_def no_fail_def split: prod.splits)
lemmas memcpy_wp = memcpy_wp'[THEN validNF_make_schematic_post', simplified]
lemma h_val_not_id_update_bytes:
fixes q :: "'a::mem_type ptr"
shows "\<lbrakk>ptr_val p = ptr_val q; length bs = size_of TYPE('a)\<rbrakk> \<Longrightarrow>
deref (update_bytes s p bs) q = from_bytes bs"
apply (clarsimp simp:update_bytes_def h_val_def)
apply (subst hrs_mem_update)
apply (cut_tac p="ptr_val q" and v=bs and h="hrs_mem (t_hrs_' s)" in heap_list_update)
apply clarsimp
apply (metis less_imp_le max_size)
by clarsimp
text \<open>
Test that we can use memcpy in a compositional proof. The following proof can be done much more
pleasantly, but we're just trying to check that the memcpy WP lemma is usable.
TODO: This relies on disabling heap abstraction for the calling function as well. We should be
able to phrase an exec_concrete WP lemma over memcpy that lets us prove properties about
heap-abstracted callers. This will need AutoCorres support to connect is_valid_* with
c_guard/no_overlap/no_wrap.
\<close>
definition
memcpy_int_spec :: "sword32 ptr \<Rightarrow> sword32 ptr \<Rightarrow> bool"
where
"memcpy_int_spec dst src \<equiv>
\<forall>x. \<lbrace>\<lambda>s. deref s src = x \<and>
{ptr_val src..+4} \<inter> {ptr_val dst..+4} = {} \<and>
c_guard src \<and> c_guard dst \<and>
no_wrap src 4 \<and> no_wrap dst 4\<rbrace>
memcpy_int' dst src
\<lbrace>\<lambda>_ s. deref s dst = x\<rbrace>!"
lemma memcpy_int_wp'[unfolded memcpy_int_spec_def]: "memcpy_int_spec dst src"
unfolding memcpy_int_spec_def
apply (rule allI)
unfolding memcpy_int'_def
apply (wp memcpy_wp)
apply clarsimp
apply (rule_tac x="[deref s (byte_cast src),
deref s (byte_cast src +\<^sub>p 1),
deref s (byte_cast src +\<^sub>p 2),
deref s (byte_cast src +\<^sub>p 3)]" in exI)
apply (clarsimp simp:bytes_at_def no_overlap_def UINT_MAX_def)
apply (rule conjI)
apply clarsimp
apply (case_tac "i = 0", clarsimp)
apply (case_tac "i = 1", clarsimp)
apply (case_tac "i = 2", clarsimp)
apply (case_tac "i = 3", clarsimp)
apply clarsimp
apply clarsimp
apply (subst h_val_not_id_update_bytes)
apply clarsimp+
apply (clarsimp simp:h_val_def)
apply (subgoal_tac "heap_list (hrs_mem (t_hrs_' s)) 4 (ptr_val src) =
deref s (byte_cast src) # (heap_list (hrs_mem (t_hrs_' s)) 3 (ptr_val src + 1))")
prefer 2
apply (clarsimp simp:h_val_def)
apply (metis Suc_numeral from_bytes_eq heap_list_rec semiring_norm(2) semiring_norm(8))
apply (subgoal_tac "heap_list (hrs_mem (t_hrs_' s)) 3 (ptr_val src + 1) =
deref s (byte_cast src +\<^sub>p 1) # (heap_list (hrs_mem (t_hrs_' s)) 2 (ptr_val src + 2))")
prefer 2
apply (clarsimp simp:h_val_def ptr_add_def)
apply (cut_tac h="hrs_mem (t_hrs_' s)" and p="ptr_val src + 1" and n=2 in heap_list_rec)
apply clarsimp
apply (simp add: add.commute from_bytes_eq)
apply clarsimp
apply (subgoal_tac "heap_list (hrs_mem (t_hrs_' s)) 2 (ptr_val src + 2) =
deref s (byte_cast src +\<^sub>p 2) # (heap_list (hrs_mem (t_hrs_' s)) 1 (ptr_val src + 3))")
prefer 2
apply (cut_tac h="hrs_mem (t_hrs_' s)" and p="ptr_val src + 2" and n=3 in heap_list_rec)
apply (clarsimp simp:h_val_def ptr_add_def from_bytes_eq)
apply (metis (no_types, hide_lams) Suc_eq_plus1 heap_list_base heap_list_rec is_num_normalize(1)
monoid_add_class.add.left_neutral one_add_one one_plus_numeral semiring_norm(3))
apply (clarsimp simp:h_val_def ptr_add_def from_bytes_eq)
done
text \<open>memcpying a typed variable is equivalent to assignment.\<close>
lemma memcpy_type_wp':
fixes dst :: "'a::mem_type ptr"
and src :: "'a::mem_type ptr"
shows "\<forall>s0 bs.
\<lbrace>\<lambda>s. s = s0 \<and> c_guard dst \<and> c_guard src \<and> sz = of_nat (size_of TYPE('a)) \<and>
no_overlap dst src (unat sz) \<and> no_wrap dst (unat sz) \<and> no_wrap src (unat sz) \<and>
bytes_of s src bs\<rbrace>
memcpy' (ptr_coerce dst) (ptr_coerce src) sz
\<lbrace>\<lambda>r s. r = ptr_coerce dst \<and> bytes_of s dst bs \<and> s = update_bytes s0 dst bs\<rbrace>!"
apply (rule allI)+
apply (wp memcpy_wp)
apply clarsimp
apply (rule_tac x=bs in exI)
apply clarsimp
apply (subst no_overlap_sym)
apply (clarsimp simp:bytes_of_def)
done
lemmas memcpy_type_wp = memcpy_type_wp'[THEN validNF_make_schematic_post', simplified]
text \<open>Confirm that we can also prove memcpy_int using the previous generic lemma.\<close>
lemma memcpy_int_wp''[unfolded memcpy_int_spec_def]: "memcpy_int_spec dst src"
unfolding memcpy_int_spec_def memcpy_int'_def
apply (rule allI)
apply (wp memcpy_type_wp)
(* Remainder mostly clagged from the original proof above. *)
apply clarsimp
apply (rule conjI, clarsimp simp:no_overlap_def, blast)
apply (rule_tac x="[deref s (byte_cast src),
deref s (byte_cast src +\<^sub>p 1),
deref s (byte_cast src +\<^sub>p 2),
deref s (byte_cast src +\<^sub>p 3)]" in exI)
apply (rule conjI)
apply (clarsimp simp:bytes_of_def bytes_at_def UINT_MAX_def)
apply (case_tac "i = 0", clarsimp)
apply (case_tac "i = 1", clarsimp)
apply (case_tac "i = 2", clarsimp)
apply (case_tac "i = 3", clarsimp)
apply clarsimp
apply clarsimp
apply (subst h_val_not_id_update_bytes, clarsimp+)
apply (clarsimp simp:h_val_def)
apply (subgoal_tac "heap_list (hrs_mem (t_hrs_' s)) 4 (ptr_val src) =
deref s (byte_cast src) # (heap_list (hrs_mem (t_hrs_' s)) 3 (ptr_val src + 1))")
prefer 2
apply (clarsimp simp:h_val_def from_bytes_eq)
apply (subst heap_list_rec[symmetric])
apply simp
apply (subgoal_tac "heap_list (hrs_mem (t_hrs_' s)) 3 (ptr_val src + 1) =
deref s (byte_cast src +\<^sub>p 1) # (heap_list (hrs_mem (t_hrs_' s)) 2 (ptr_val src + 2))")
prefer 2
apply (clarsimp simp:h_val_def ptr_add_def)
apply (cut_tac h="hrs_mem (t_hrs_' s)" and p="ptr_val src + 1" and n=2 in heap_list_rec)
apply (clarsimp simp: from_bytes_eq)
apply (metis add.commute)
apply clarsimp
apply (subgoal_tac "heap_list (hrs_mem (t_hrs_' s)) 2 (ptr_val src + 2) =
deref s (byte_cast src +\<^sub>p 2) # (heap_list (hrs_mem (t_hrs_' s)) 1 (ptr_val src + 3))")
prefer 2
apply (cut_tac h="hrs_mem (t_hrs_' s)" and p="ptr_val src + 2" and n=3 in heap_list_rec)
apply (clarsimp simp:h_val_def ptr_add_def from_bytes_eq)
apply (metis (no_types, hide_lams) Suc_eq_plus1 heap_list_base heap_list_rec is_num_normalize(1)
monoid_add_class.add.left_neutral one_add_one one_plus_numeral semiring_norm(3))
apply (clarsimp simp:h_val_def ptr_add_def from_bytes_eq)
done
lemma bytes_of_imp_at[simp]: "bytes_of s x bs \<Longrightarrow> bytes_at s x bs"
by (clarsimp simp:bytes_of_def bytes_at_def)
lemma bytes_at_imp_of:
fixes x :: "'a::mem_type ptr"
shows "\<lbrakk>bytes_at s x bs; length bs = size_of TYPE('a)\<rbrakk> \<Longrightarrow> bytes_of s x bs"
by (clarsimp simp:bytes_of_def bytes_at_def)
text \<open>
Memcpying from a source to a destination via an intermediary does what it should. This is close to
the desirable property we want for CAmkES systems; i.e. that copying into your IPC buffer on one
side and then out on the other gives you back what you put in. Note that the type of the
intermediate pointer is irrelevant and we don't need to assume that the source and final
destination do not overlap.
\<close>
lemma memcpy_seq:
fixes x :: "'a::mem_type ptr"
and y :: "'b::mem_type ptr"
and z :: "'a::mem_type ptr"
shows "\<forall>s0 bs.
\<lbrace>\<lambda>s. s = s0 \<and> sz = of_nat (size_of TYPE('a)) \<and>
c_guard x \<and> c_guard y \<and> c_guard z \<and>
no_wrap x (unat sz) \<and> no_wrap y (unat sz) \<and> no_wrap z (unat sz) \<and>
no_overlap x y (unat sz) \<and> no_overlap y z (unat sz) \<and>
bytes_of s x bs\<rbrace>
do memcpy' (ptr_coerce y) (ptr_coerce x) sz;
memcpy' (ptr_coerce z) (ptr_coerce y) sz
od
\<lbrace>\<lambda>r s. r = ptr_coerce z \<and> bytes_of s z bs\<rbrace>!"
apply (rule allI)+
apply (wp memcpy_wp)
apply clarsimp
apply (rule_tac x=bs in exI)
apply clarsimp
apply (rule conjI, clarsimp simp:bytes_of_def)
apply clarsimp
apply (rule_tac x=bs in exI)
apply (rule conjI, clarsimp simp:bytes_of_def)
apply clarsimp
apply (rule bytes_at_imp_of)
apply (clarsimp simp:bytes_of_def)+
done
lemma update_ti_eq:
fixes x :: "'a::mem_type"
and y :: 'a
shows "\<lbrakk>length bs = size_of TYPE('a); bs = bs'\<rbrakk>
\<Longrightarrow> update_ti_t (typ_info_t TYPE('a)) bs x = update_ti_t (typ_info_t TYPE('a)) bs' y"
by (clarsimp simp:upd)
lemma from_bytes_cong: "x = y \<Longrightarrow> from_bytes x = from_bytes y"
by simp
declare from_bytes_eq [simp]
text \<open>
If you dereference a pointer, the value you get is the same as the underlying bytes backing that
memory.
\<close>
lemma val_eq_bytes:
fixes x :: "'a::mem_type ptr"
shows "deref s x = from_bytes (map (\<lambda>off. deref s (byte_cast x +\<^sub>p of_nat off)) [0..<size_of TYPE('a)])"
apply (clarsimp simp:h_val_def ptr_add_def)
apply (rule from_bytes_cong)
apply (rule nth_equalityI)
apply clarsimp+
apply (subst heap_list_nth)
apply clarsimp+
done
lemma extract_list_elem: "i < n \<Longrightarrow> f i = (map f [0..<n]) ! i"
apply (induct i)
apply clarsimp+
done
lemma update_deref:
fixes x :: "'a::mem_type ptr"
shows "size_of TYPE('a) = length bs \<Longrightarrow> deref (update_bytes s x bs) x = from_bytes bs"
apply (clarsimp simp:update_bytes_def)
apply (subst hrs_mem_update)
apply (clarsimp simp:h_val_def)
apply (subst heap_list_update)
apply (metis less_imp_le max_size)
apply clarsimp
done
text \<open>
The memcpy_int proof can now be completed more elegantly. Note that the body of this proof is more
generic than the previous attempts and doesn't involve manually reasoning about each byte.
\<close>
lemma memcpy_int_wp'''[unfolded memcpy_int_spec_def]: "memcpy_int_spec dst src"
unfolding memcpy_int_spec_def memcpy_int'_def
apply (rule allI)
apply (wp memcpy_type_wp)
apply clarsimp
apply (rule conjI, clarsimp simp:no_overlap_def, blast)
apply (rule_tac x="map (\<lambda>i. deref s (byte_cast src +\<^sub>p of_nat i)) [0..<size_of TYPE(32sword)]" in exI)
apply (rule conjI)
apply (clarsimp simp:bytes_of_def bytes_at_def UINT_MAX_def)+
apply (subst update_deref)
apply clarsimp
apply (cut_tac s=s and x=src in val_eq_bytes)
apply clarsimp
done
lemma bytes_at_heap_list:
fixes x :: "'a::mem_type ptr"
shows "\<lbrakk>n \<le> ADDR_MAX; no_wrap x n\<rbrakk>
\<Longrightarrow> bytes_at s x (heap_list (hrs_mem (t_hrs_' s)) n (ptr_val x))"
apply (clarsimp simp:bytes_at_def ptr_add_def h_val_def)
apply (subst heap_list_nth)
apply unat_arith
apply clarsimp
done
text \<open>
A collection of useful type-generic implications for moving from the abstract heap to the concrete
heap.
\<close>
definition
is_valid_imp_c_guard :: "(lifted_globals \<Rightarrow> 'b::mem_type ptr \<Rightarrow> bool) \<Rightarrow> bool"
where
"is_valid_imp_c_guard is_valid \<equiv> \<forall>s p. is_valid (lift_global_heap s) p \<longrightarrow> c_guard p"
definition
is_valid_imp_no_null :: "(lifted_globals \<Rightarrow> 'b::mem_type ptr \<Rightarrow> bool) \<Rightarrow> bool"
where
"is_valid_imp_no_null is_valid \<equiv>
\<forall>s p. is_valid (lift_global_heap s) p \<longrightarrow> 0 \<notin> {ptr_val p..of_nat (size_of TYPE('b))}"
definition
is_valid_imp_no_wrap :: "(lifted_globals \<Rightarrow> 'b::mem_type ptr \<Rightarrow> bool) \<Rightarrow> bool"
where
"is_valid_imp_no_wrap is_valid \<equiv>
\<forall>s p. is_valid (lift_global_heap s) p \<longrightarrow> no_wrap p (size_of TYPE('b))"
definition
is_valid_imp_no_overlap :: "(lifted_globals \<Rightarrow> 'b::mem_type ptr \<Rightarrow> bool) \<Rightarrow> bool"
where
"is_valid_imp_no_overlap is_valid \<equiv>
\<forall>s p q. is_valid (lift_global_heap s) p \<and> is_valid (lift_global_heap s) q \<and> p \<noteq> q
\<longrightarrow> no_overlap p q (size_of TYPE('b))"
definition
is_valid_imp_heap_ptr_valid :: "(lifted_globals \<Rightarrow> 'b::mem_type ptr \<Rightarrow> bool) \<Rightarrow> bool"
where
"is_valid_imp_heap_ptr_valid is_valid \<equiv>
\<forall>s p. is_valid (lift_global_heap s) p \<longrightarrow> heap_ptr_valid (hrs_htd (t_hrs_' s)) p"
text \<open>We can easily discharge these for a given type.\<close>
lemma is_valid_w32_imp_c_guard[unfolded is_valid_imp_c_guard_def, simplified]:
"is_valid_imp_c_guard is_valid_w32"
unfolding is_valid_imp_c_guard_def
apply clarsimp
apply (subst (asm) lifted_globals_ext_simps)
apply clarsimp
apply (rule simple_lift_c_guard, force)
done
lemma is_valid_w32_imp_no_null[unfolded is_valid_imp_no_null_def, simplified]:
"is_valid_imp_no_null is_valid_w32"
unfolding is_valid_imp_no_null_def
apply clarsimp
apply (subst (asm) lifted_globals_ext_simps)
apply clarsimp
apply (drule simple_lift_c_guard)
apply (clarsimp simp:c_guard_def c_null_guard_def intvl_def)
by force
lemma is_valid_w32_imp_no_wrap[unfolded is_valid_imp_no_wrap_def, simplified]:
"is_valid_imp_no_wrap is_valid_w32"
unfolding is_valid_imp_no_wrap_def no_wrap_def
apply clarsimp
apply (subst (asm) lifted_globals_ext_simps)
apply clarsimp
apply (drule simple_lift_c_guard)
apply (clarsimp simp:c_guard_def c_null_guard_def intvl_def)
done
lemma is_valid_w32_imp_no_overlap[unfolded is_valid_imp_no_overlap_def, simplified]:
"is_valid_imp_no_overlap is_valid_w32"
unfolding is_valid_imp_no_overlap_def no_wrap_def
apply clarsimp
apply (subst (asm) lifted_globals_ext_simps)+
apply clarsimp
apply (drule simple_lift_heap_ptr_valid)+
apply (clarsimp simp:no_overlap_def)
apply (cut_tac p=p and q=q and d="hrs_htd (t_hrs_' s)" in heap_ptr_valid_neq_disjoint)
apply clarsimp+
done
lemma is_valid_w32_imp_heap_ptr_valid[unfolded is_valid_imp_heap_ptr_valid_def, simplified]:
"is_valid_imp_heap_ptr_valid is_valid_w32"
unfolding is_valid_imp_heap_ptr_valid_def
apply clarsimp
apply (subst (asm) lifted_globals_ext_simps)
apply clarsimp
by (rule simple_lift_heap_ptr_valid, force)
text \<open>
With that support in place, we can now prove a heap-abstracted call to memcpy of a type in a
reasonably generic way. Note that we leverage the relationship between
is_valid_*/lift_global_heap/simple_lift to transfer assumptions across the boundary between the
abstract and concrete heaps.
\<close>
lemma
fixes dst :: "32word ptr"
and src :: "32word ptr"
shows "\<forall>s0 x.
\<lbrace>\<lambda>s. s = s0 \<and> is_valid_w32 s dst \<and> is_valid_w32 s src \<and> sz = of_nat (size_of TYPE(32word)) \<and>
heap_w32 s src = x \<and> dst \<noteq> src\<rbrace>
exec_concrete lift_global_heap (memcpy' (ptr_coerce dst) (ptr_coerce src) sz)
\<lbrace>\<lambda>r s. r = ptr_coerce dst \<and> heap_w32 s dst = x\<rbrace>!"
including nf_no_pre
apply (rule allI)+
apply (wp memcpy_wp)
apply (clarsimp simp:is_valid_w32_imp_c_guard
is_valid_w32_imp_no_wrap
is_valid_w32_imp_no_overlap)
apply (rule_tac x="map (\<lambda>i. deref s (byte_cast src +\<^sub>p of_nat i)) [0..<size_of TYPE(32word)]" in exI)
apply clarsimp
apply (rule conjI)
apply (clarsimp simp:bytes_at_def UINT_MAX_def)
apply clarsimp
apply (subst lifted_globals_ext_simps(3))+
apply (clarsimp simp:simple_lift_def is_valid_w32_imp_heap_ptr_valid)
apply (rule conjI)
apply clarsimp
apply (subst update_deref)
apply clarsimp+
apply (cut_tac s=s and x=src in val_eq_bytes)
apply clarsimp
apply (clarsimp simp:update_bytes_def is_valid_w32_imp_heap_ptr_valid)
done
text \<open>
Let's do the same instantiation for a structure. Note that the proof text for the following lemmas
is identical to the word 32 instantiation above. These could be straightforwardly abstracted into
a locale which could be automatically interpreted with the use of generated proofs.
\<close>
lemma is_valid_my_structure_imp_c_guard[unfolded is_valid_imp_c_guard_def, simplified]:
"is_valid_imp_c_guard is_valid_my_structure_C"
unfolding is_valid_imp_c_guard_def
apply clarsimp
apply (subst (asm) lifted_globals_ext_simps)
apply clarsimp
apply (rule simple_lift_c_guard, force)
done
lemma is_valid_my_structure_imp_no_null[unfolded is_valid_imp_no_null_def, simplified]:
"is_valid_imp_no_null is_valid_my_structure_C"
unfolding is_valid_imp_no_null_def
apply clarsimp
apply (subst (asm) lifted_globals_ext_simps)
apply clarsimp
apply (drule simple_lift_c_guard)
apply (clarsimp simp:c_guard_def c_null_guard_def intvl_def)
by force
lemma is_valid_my_structure_imp_no_wrap[unfolded is_valid_imp_no_wrap_def, simplified]:
"is_valid_imp_no_wrap is_valid_my_structure_C"
unfolding is_valid_imp_no_wrap_def no_wrap_def
apply clarsimp
apply (subst (asm) lifted_globals_ext_simps)
apply clarsimp
apply (drule simple_lift_c_guard)
apply (clarsimp simp:c_guard_def c_null_guard_def intvl_def)
done
lemma is_valid_my_structure_imp_no_overlap[unfolded is_valid_imp_no_overlap_def, simplified]:
"is_valid_imp_no_overlap is_valid_my_structure_C"
unfolding is_valid_imp_no_overlap_def no_wrap_def
apply clarsimp
apply (subst (asm) lifted_globals_ext_simps)+
apply clarsimp
apply (drule simple_lift_heap_ptr_valid)+
apply (clarsimp simp:no_overlap_def)
apply (cut_tac p=p and q=q and d="hrs_htd (t_hrs_' s)" in heap_ptr_valid_neq_disjoint)
apply clarsimp+
done
lemma is_valid_my_structure_imp_heap_ptr_valid[unfolded is_valid_imp_heap_ptr_valid_def, simplified]:
"is_valid_imp_heap_ptr_valid is_valid_my_structure_C"
unfolding is_valid_imp_heap_ptr_valid_def
apply clarsimp
apply (subst (asm) lifted_globals_ext_simps)
apply clarsimp
by (rule simple_lift_heap_ptr_valid, force)
text \<open>
Again, we can now trivially transfer Hoare triple properties.
\<close>
lemma
fixes dst :: "my_structure_C ptr"
and src :: "my_structure_C ptr"
shows "\<forall>s0 x.
\<lbrace>\<lambda>s. s = s0 \<and> is_valid_my_structure_C s dst \<and> is_valid_my_structure_C s src \<and>
heap_my_structure_C s src = x \<and> dst \<noteq> src\<rbrace>
memcpy_struct' dst src
\<lbrace>\<lambda>r s. r = dst \<and> heap_my_structure_C s dst = x\<rbrace>!"
including nf_no_pre
apply (rule allI)+
unfolding memcpy_struct'_def
apply (wp memcpy_wp)
apply (clarsimp simp:is_valid_my_structure_imp_c_guard)
apply (rule_tac x="map (\<lambda>i. deref s (byte_cast src +\<^sub>p of_nat i)) [0..<size_of TYPE(my_structure_C)]" in exI)
apply (clarsimp simp:is_valid_my_structure_imp_no_wrap is_valid_my_structure_imp_no_overlap)
apply (rule conjI)
apply (clarsimp simp:bytes_at_def UINT_MAX_def)
apply clarsimp
apply (subst lifted_globals_ext_simps)+
apply (clarsimp simp:simple_lift_def is_valid_my_structure_imp_heap_ptr_valid)
apply (rule conjI)
apply clarsimp
apply (subst update_deref)
apply clarsimp
apply (cut_tac s=s and x=src in val_eq_bytes)
apply clarsimp
apply (clarsimp simp:update_bytes_def is_valid_my_structure_imp_heap_ptr_valid)
done
end
end
|
Require Import Logic.GeneralLogic.Base.
Require Import Logic.MinimunLogic.Syntax.
Require Import Logic.MinimunLogic.ProofTheory.Minimun.
Require Import Logic.MinimunLogic.ProofTheory.RewriteClass.
Require Import Logic.MinimunLogic.Syntax.
Require Import Logic.MinimunLogic.ProofTheory.Minimun.
Require Import Logic.PropositionalLogic.Syntax.
Require Import Logic.PropositionalLogic.ProofTheory.Intuitionistic.
Require Import Logic.PropositionalLogic.ProofTheory.DeMorgan.
Require Import Logic.PropositionalLogic.ProofTheory.GodelDummett.
Require Import Logic.PropositionalLogic.ProofTheory.Classical.
Require Import Logic.SeparationLogic.Syntax.
Require Import Logic.SeparationLogic.ProofTheory.SeparationLogic.
Require Import Logic.SeparationLogic.DeepEmbedded.Parameter.
Require Logic.SeparationLogic.DeepEmbedded.SeparationLanguage.
Require Logic.SeparationLogic.DeepEmbedded.SeparationEmpLanguage.
Local Open Scope logic_base.
Local Open Scope syntax.
Import PropositionalLanguageNotation.
Import SeparationLogicNotation.
Module ReynoldsLogic.
Section ReynoldsLogic.
Context {Sigma: SeparationLanguage.PropositionalVariables}.
Existing Instances SeparationLanguage.L SeparationLanguage.minL SeparationLanguage.pL SeparationLanguage.sL.
Inductive provable: SeparationLanguage.expr Sigma -> Prop :=
| modus_ponens: forall x y, provable (x --> y) -> provable x -> provable y
| axiom1: forall x y, provable (x --> (y --> x))
| axiom2: forall x y z, provable ((x --> y --> z) --> (x --> y) --> (x --> z))
| andp_intros: forall x y, provable (x --> y --> x && y)
| andp_elim1: forall x y, provable (x && y --> x)
| andp_elim2: forall x y, provable (x && y --> y)
| orp_intros1: forall x y, provable (x --> x || y)
| orp_intros2: forall x y, provable (y --> x || y)
| orp_elim: forall x y z, provable ((x --> z) --> (y --> z) --> (x || y --> z))
| falsep_elim: forall x, provable (FF --> x)
| sepcon_comm: forall x y, provable (x * y --> y * x)
| sepcon_assoc: forall x y z, provable (x * (y * z) <--> (x * y) * z)
| wand_sepcon_adjoint1: forall x y z, provable (x * y --> z) -> provable (x --> (y -* z))
| wand_sepcon_adjoint2: forall x y z, provable (x --> (y -* z)) -> provable (x * y --> z)
| sepcon_elim1: forall x y, provable (x * y --> x).
Instance G: ProofTheory SeparationLanguage.L := Build_AxiomaticProofTheory provable.
Instance AX: NormalAxiomatization SeparationLanguage.L G := Build_AxiomaticProofTheory_AX provable.
Instance minAX: MinimunAxiomatization SeparationLanguage.L G.
Proof.
constructor.
+ apply modus_ponens.
+ apply axiom1.
+ apply axiom2.
Qed.
Instance ipG: IntuitionisticPropositionalLogic SeparationLanguage.L G.
Proof.
constructor.
+ apply andp_intros.
+ apply andp_elim1.
+ apply andp_elim2.
+ apply orp_intros1.
+ apply orp_intros2.
+ apply orp_elim.
+ apply falsep_elim.
Qed.
Instance sG: SeparationLogic SeparationLanguage.L G.
Proof.
constructor.
+ apply sepcon_comm.
+ apply sepcon_assoc.
+ intros; split.
- apply wand_sepcon_adjoint1.
- apply wand_sepcon_adjoint2.
Qed.
Instance gcsG: GarbageCollectSeparationLogic SeparationLanguage.L G.
Proof.
constructor.
apply sepcon_elim1.
Qed.
End ReynoldsLogic.
End ReynoldsLogic.
Module OHearnLogic.
Section OHearnLogic.
Context {Sigma: SeparationEmpLanguage.PropositionalVariables}.
Existing Instances SeparationEmpLanguage.L SeparationEmpLanguage.minL SeparationEmpLanguage.pL SeparationEmpLanguage.sL SeparationEmpLanguage.s'L.
Inductive provable: SeparationEmpLanguage.expr Sigma -> Prop :=
| modus_ponens: forall x y, provable (x --> y) -> provable x -> provable y
| axiom1: forall x y, provable (x --> (y --> x))
| axiom2: forall x y z, provable ((x --> y --> z) --> (x --> y) --> (x --> z))
| andp_intros: forall x y, provable (x --> y --> x && y)
| andp_elim1: forall x y, provable (x && y --> x)
| andp_elim2: forall x y, provable (x && y --> y)
| orp_intros1: forall x y, provable (x --> x || y)
| orp_intros2: forall x y, provable (y --> x || y)
| orp_elim: forall x y z, provable ((x --> z) --> (y --> z) --> (x || y --> z))
| falsep_elim: forall x, provable (FF --> x)
| excluded_middle: forall x, provable (x || ~~ x)
| sepcon_comm: forall x y, provable (x * y --> y * x)
| sepcon_assoc: forall x y z, provable (x * (y * z) <--> (x * y) * z)
| wand_sepcon_adjoint1: forall x y z, provable (x * y --> z) -> provable (x --> (y -* z))
| wand_sepcon_adjoint2: forall x y z, provable (x --> (y -* z)) -> provable (x * y --> z)
| sepcon_emp: forall x, provable (x * emp <--> x).
Instance G: ProofTheory SeparationEmpLanguage.L := Build_AxiomaticProofTheory provable.
Instance AX: NormalAxiomatization SeparationEmpLanguage.L G := Build_AxiomaticProofTheory_AX provable.
Instance minAX: MinimunAxiomatization SeparationEmpLanguage.L G.
Proof.
constructor.
+ apply modus_ponens.
+ apply axiom1.
+ apply axiom2.
Qed.
Instance ipG: IntuitionisticPropositionalLogic SeparationEmpLanguage.L G.
Proof.
constructor.
+ apply andp_intros.
+ apply andp_elim1.
+ apply andp_elim2.
+ apply orp_intros1.
+ apply orp_intros2.
+ apply orp_elim.
+ apply falsep_elim.
Qed.
Instance cpG: ClassicalPropositionalLogic SeparationEmpLanguage.L G.
Proof.
constructor.
apply excluded_middle.
Qed.
Instance sG: SeparationLogic SeparationEmpLanguage.L G.
Proof.
constructor.
+ apply sepcon_comm.
+ apply sepcon_assoc.
+ intros; split.
- apply wand_sepcon_adjoint1.
- apply wand_sepcon_adjoint2.
Qed.
Instance EmpsG: EmpSeparationLogic SeparationEmpLanguage.L G.
Proof.
constructor.
apply sepcon_emp.
Qed.
End OHearnLogic.
End OHearnLogic.
Module LogicOnModuResModel.
Section LogicOnModuResModel.
Context {Sigma: SeparationEmpLanguage.PropositionalVariables}.
Existing Instances SeparationEmpLanguage.L SeparationEmpLanguage.minL SeparationEmpLanguage.pL SeparationEmpLanguage.sL SeparationEmpLanguage.s'L.
Inductive provable: SeparationEmpLanguage.expr Sigma -> Prop :=
| modus_ponens: forall x y, provable (x --> y) -> provable x -> provable y
| axiom1: forall x y, provable (x --> (y --> x))
| axiom2: forall x y z, provable ((x --> y --> z) --> (x --> y) --> (x --> z))
| andp_intros: forall x y, provable (x --> y --> x && y)
| andp_elim1: forall x y, provable (x && y --> x)
| andp_elim2: forall x y, provable (x && y --> y)
| orp_intros1: forall x y, provable (x --> x || y)
| orp_intros2: forall x y, provable (y --> x || y)
| orp_elim: forall x y z, provable ((x --> z) --> (y --> z) --> (x || y --> z))
| falsep_elim: forall x, provable (FF --> x)
| sepcon_comm: forall x y, provable (x * y --> y * x)
| sepcon_assoc: forall x y z, provable (x * (y * z) <--> (x * y) * z)
| wand_sepcon_adjoint1: forall x y z, provable (x * y --> z) -> provable (x --> (y -* z))
| wand_sepcon_adjoint2: forall x y z, provable (x --> (y -* z)) -> provable (x * y --> z)
| sepcon_emp: forall x, provable (x * emp <--> x)
| sepcon_elim1: forall x y, provable (x * y --> x).
Instance G: ProofTheory SeparationEmpLanguage.L := Build_AxiomaticProofTheory provable.
Instance AX: NormalAxiomatization SeparationEmpLanguage.L G := Build_AxiomaticProofTheory_AX provable.
Instance minAX: MinimunAxiomatization SeparationEmpLanguage.L G.
Proof.
constructor.
+ apply modus_ponens.
+ apply axiom1.
+ apply axiom2.
Qed.
Instance ipG: IntuitionisticPropositionalLogic SeparationEmpLanguage.L G.
Proof.
constructor.
+ apply andp_intros.
+ apply andp_elim1.
+ apply andp_elim2.
+ apply orp_intros1.
+ apply orp_intros2.
+ apply orp_elim.
+ apply falsep_elim.
Qed.
Instance sG: SeparationLogic SeparationEmpLanguage.L G.
Proof.
constructor.
+ apply sepcon_comm.
+ apply sepcon_assoc.
+ intros; split.
- apply wand_sepcon_adjoint1.
- apply wand_sepcon_adjoint2.
Qed.
Instance EmpsG: EmpSeparationLogic SeparationEmpLanguage.L G.
Proof.
constructor.
apply sepcon_emp.
Qed.
Instance gcsG: GarbageCollectSeparationLogic SeparationEmpLanguage.L G.
Proof.
constructor.
apply sepcon_elim1.
Qed.
End LogicOnModuResModel.
End LogicOnModuResModel.
Module LogicOnMSL.
Section LogicOnMSL.
Context {Sigma: SeparationEmpLanguage.PropositionalVariables}.
Existing Instances SeparationEmpLanguage.L SeparationEmpLanguage.minL SeparationEmpLanguage.pL SeparationEmpLanguage.sL SeparationEmpLanguage.s'L.
Inductive provable: SeparationEmpLanguage.expr Sigma -> Prop :=
| modus_ponens: forall x y, provable (x --> y) -> provable x -> provable y
| axiom1: forall x y, provable (x --> (y --> x))
| axiom2: forall x y z, provable ((x --> y --> z) --> (x --> y) --> (x --> z))
| andp_intros: forall x y, provable (x --> y --> x && y)
| andp_elim1: forall x y, provable (x && y --> x)
| andp_elim2: forall x y, provable (x && y --> y)
| orp_intros1: forall x y, provable (x --> x || y)
| orp_intros2: forall x y, provable (y --> x || y)
| orp_elim: forall x y z, provable ((x --> z) --> (y --> z) --> (x || y --> z))
| falsep_elim: forall x, provable (FF --> x)
| impp_choice: forall x y, provable ((x --> y) || (y --> x))
| sepcon_comm: forall x y, provable (x * y --> y * x)
| sepcon_assoc: forall x y z, provable (x * (y * z) <--> (x * y) * z)
| wand_sepcon_adjoint1: forall x y z, provable (x * y --> z) -> provable (x --> (y -* z))
| wand_sepcon_adjoint2: forall x y z, provable (x --> (y -* z)) -> provable (x * y --> z)
| sepcon_emp: forall x, provable (x * emp <--> x).
Instance G: ProofTheory SeparationEmpLanguage.L := Build_AxiomaticProofTheory provable.
Instance AX: NormalAxiomatization SeparationEmpLanguage.L G := Build_AxiomaticProofTheory_AX provable.
Instance minAX: MinimunAxiomatization SeparationEmpLanguage.L G.
Proof.
constructor.
+ apply modus_ponens.
+ apply axiom1.
+ apply axiom2.
Qed.
Instance ipG: IntuitionisticPropositionalLogic SeparationEmpLanguage.L G.
Proof.
constructor.
+ apply andp_intros.
+ apply andp_elim1.
+ apply andp_elim2.
+ apply orp_intros1.
+ apply orp_intros2.
+ apply orp_elim.
+ apply falsep_elim.
Qed.
Instance sG: SeparationLogic SeparationEmpLanguage.L G.
Proof.
constructor.
+ apply sepcon_comm.
+ apply sepcon_assoc.
+ intros; split.
- apply wand_sepcon_adjoint1.
- apply wand_sepcon_adjoint2.
Qed.
Instance EmpsG: EmpSeparationLogic SeparationEmpLanguage.L G.
Proof.
constructor.
apply sepcon_emp.
Qed.
End LogicOnMSL.
End LogicOnMSL.
|
#include <boost/algorithm/string.hpp>
#include <iostream>
#include <string>
using namespace std;
using namespace boost::algorithm;
int main() {
string s = "--Boost C++ Libraries--";
cout << trim_left_copy_if(s, is_any_of("-")) << endl;
cout << trim_right_copy_if(s, is_any_of("-")) << endl;
cout << trim_copy_if(s, is_any_of("-")) << endl;
s = "123456789Boost C++ Libraries123456789";
cout << trim_left_copy_if(s, is_digit()) << endl;
cout << trim_right_copy_if(s, is_digit()) << endl;
cout << trim_copy_if(s, is_digit()) << endl;
}
|
# Day 24, symbolic evaluation
* <https://adventofcode.com/2021/day/24>
This puzzle is different from most AoC problems in that the description and tests are not actually all that much use. You need to study the puzzle input too, as it is the specific mathematical expressions created from the input that'll determine when, given the 14 different inputs (each between 1 and 9), you'll get a zero a the output.
## Puzzle input patterns
The input consists of 14 repeated sections like this:
<table>
<thead>
<tr>
<th align="right">#</th>
<th >opcode</th>
<th align="right">op1</th>
<th align="right">op2</th>
<th align="left" style="text-align: left">interpretation</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left" style="text-align: left">1</td>
<td align="left" style="text-align: left">inp</td>
<td align="right">w</td>
<td align="right"></td>
<td align="left" style="text-align: left"><tt>w = <i>input_digit</i></tt></td>
</tr>
<tr>
<td align="left" style="text-align: left">2</td>
<td align="left" style="text-align: left">mul</td>
<td align="right">x</td>
<td align="right">0</td>
<td align="left" rowspan="3" style="text-align: left; vertical-align: top">
<tt>x = z % 26</tt><br/>
Here, <tt>z</tt> is the output of the previous section.
</td>
</tr>
<tr>
<td align="left" style="text-align: left">3</td>
<td align="left" style="text-align: left">add</td>
<td align="right">x</td>
<td align="right">z</td>
</tr>
<tr>
<td align="left" style="text-align: left">4</td>
<td align="left" style="text-align: left">mod</td>
<td align="right">x</td>
<td align="right">26</td>
</tr>
<tr>
<td align="left" style="text-align: left">5</td>
<td align="left" style="text-align: left">div</td>
<td align="right">z</td>
<td align="right"><i>A</i></td>
<td align="left" style="text-align: left">
<tt>z = z / <i>A</i></tt><br/>
<i>A</i> is either 1 or 26, depending on <i>B</i>
</td>
</tr>
<tr>
<td align="left" style="text-align: left">6</td>
<td align="left" style="text-align: left">add</td>
<td align="right">x</td>
<td align="right"><i>B</i></td>
<td align="left" style="text-align: left">
<tt>x = x + <i>B</i><tt><br/>
<i>B</i> is a number between -15 and +15.
</td>
</tr>
<tr>
<td align="left" style="text-align: left">7</td>
<td align="left" style="text-align: left">eql</td>
<td align="right">x</td>
<td align="right">w</td>
<td align="left" rowspan="2" style="text-align: left; vertical-align: top">
<tt>x = 0 if x == w else 1</tt><br/>
</td>
</tr>
<tr>
<td align="left" style="text-align: left">8</td>
<td align="left" style="text-align: left">eql</td>
<td align="right">x</td>
<td align="right">0</td>
</tr>
<tr>
<td align="left" style="text-align: left">9</td>
<td align="left" style="text-align: left">mul</td>
<td align="right">y</td>
<td align="right">0</td>
<td align="left" rowspan="4" style="text-align: left; vertical-align: top">
<tt>y = 25 * x + 1</tt><br/>
<tt>x</tt> is either 0 or 1, so <tt>y</tt> is now either 1 or 26.
</td>
</tr>
<tr>
<td align="left" style="text-align: left">10</td>
<td align="left" style="text-align: left">add</td>
<td align="right">y</td>
<td align="right">x</td>
</tr>
<tr>
<td align="left" style="text-align: left">11</td>
<td align="left" style="text-align: left">mul</td>
<td align="right">y</td>
<td align="right">25</td>
</tr>
<tr>
<td align="left" style="text-align: left">12</td>
<td align="left" style="text-align: left">add</td>
<td align="right">y</td>
<td align="right">1</td>
</tr>
<tr>
<td align="left" style="text-align: left">13</td>
<td align="left" style="text-align: left">mul</td>
<td align="right">z</td>
<td align="right">y</td>
<td align="left" style="text-align: left"><tt>z = z * y</tt></td>
</tr>
<tr>
<td align="left" style="text-align: left">14</td>
<td align="left" style="text-align: left">mul</td>
<td align="right">y</td>
<td align="right">0</td>
<td align="left" rowspan="4" style="text-align: left; vertical-align: top">
<tt>y = (w + <i>C</i>) * x</tt>
<br/><i>C</i> is a positive, non-zero integer. <tt>x</tt> is either 0 or 1.
</td>
</tr>
<tr>
<td align="left" style="text-align: left">15</td>
<td align="left" style="text-align: left">add</td>
<td align="right">y</td>
<td align="right">w</td>
</tr>
<tr>
<td align="left" style="text-align: left">16</td>
<td align="left" style="text-align: left">add</td>
<td align="right">y</td>
<td align="right"><i>C</i></td>
</tr>
<tr>
<td align="left" style="text-align: left">17</td>
<td align="left" style="text-align: left">mul</td>
<td align="right">y</td>
<td align="right">x</td>
</tr>
<tr>
<td align="left" style="text-align: left">18</td>
<td align="left" style="text-align: left">add</td>
<td align="right">z</td>
<td align="right">y</td>
<td align="left" style="text-align: left"><tt>z = z + y</tt></td>
</tr>
</table>
The values for <i>A</i>, <i>B</i> and <i>C</i> are the only values that vary between the parts, and, in fact, between puzzle inputs for everyone participating in AoC. Moreover, <i>A</i> depends on <i>B</i>; it is 26 only if <i>B</i> is a positive number (zero or greater).
So, expressed as Python, the sections come down to:
```python
def section(input, z, B, C):
x = z % 26 + B
if B >= 0:
z //= 26
if input != x:
z = z * 26 + input + C
return z
```
From this, you can see that `z` will never be negative, and can only be 0 if, by the time we reach the last block, it is smaller than 26 (as `z //= 26` is the only point where `z` decreases, and only for values smaller than 26 would floor division give 0 there).
The other conclusion we can make is that the outcome _branches_, based on the values of the input digits; at least, for those blocks where `B` is not larger than 9, as that would _guarantee_ that `input` is not equal to `x`. *One* of those branches will end up being zero, for a given set of conditions. Our job will be to find that set of conditions, because from that we can deduce the permissible range of each input variable.
Finally, I note that only the _condition_ has to rely on modulo operations. If we play our cards right, then each variant of the expression being processed is going to be a [linear polynomial](https://en.wikipedia.org/wiki/Polynomial#linear_polynomial) with all positive [coefficients](https://en.wikipedia.org/wiki/Coefficient). Put differently, it'll be a rather simple $ai_0 + bi_1 + ci_2 + ... + zi_n$ expression, something we can make use of when trying to simplify expressions or prune branches.
## Using Sympy to track branching
I decided to solve this problem by using [sympy](https://www.sympy.org/) to parse and solve the equation, as it'll let us combine the parts into a single equation and track branching. Braching is tracked via [`Piecewise` objects](https://docs.sympy.org/latest/modules/functions/elementary.html#sympy.functions.elementary.piecewise.Piecewise), and Sympy will automatically eliminate branches if it recognises the condition always applies or can never be met. Sympy can do this because keeps track of various properties of the symbols (variables) involved, such as the fact that all our inputs are going to be non-zero positive integers.
However, there are a few challenges to overcome:
- The ALU division operation needs to floor the outcome (if the signs of the operands are the same. truncate towards zero. We don't have to worry about negative numbers however, as the only division that takes place is either by 1 or by 26. We can't just use `floor()` here, because then Sympy generally won't be able to simplify the expression further.
- The expresion rapidly grows to a size where manipulating it gets _very_ slow, so we need to find strategies to simplify it further than the standard Sympy simplifcation methods can achieve.
### Recasting division to floor the result
The first problem can be solved by redefining the operation in terms that Sympy can process and even simplify. Floor division can de defined by first subtracting the remainder from the dividend before dividing:
$$
\lfloor \frac a b \rfloor = \frac {a - (a \mod b)} {b}
$$
Sympy knows how to handle modulo operations, so that's what we'll use to translate the `div` operator.
We don't have to worry about rounding towards negative infinity, as for this puzzle, neither operand is ever smaller than zero. However, should the need arise, you can expand on this by testing for either $a$ or $b$ being negative:
$$
\begin{cases}
\frac {a + (-a \mod b)} {b} & \text{if } a < 0 \land b > 0 \\
\frac {a + (a \mod -b)} {b} & \text{if } a > 0 \land b < 0 \\
\frac {a - (a \mod b)} {b} & \text{if } ab >= 0
\end{cases}
$$
In Sympy, you can then model those multiple cases in a `Piecewise()` object. I didn't bother with this however, as the first two cases would simply be dropped instantly, anyway.
### Eliminating modulo operations
Next, we can assist Sympy by eliminating modulo operations if we know the left-hand $a$ value is always going to be lower than the right-hand value $b$, which in our case is always going to be 26 (either from the `mod x 26` operation form line 4, or one of the `div z 26` operations on line 5).
One way we could do this is to try and test the expression $a < b$ for each free symbol (input variable) in $a$ using the [`solveset()` function](https://docs.sympy.org/latest/modules/solvers/solveset.html#sympy.solvers.solveset.solveset) and a [`Range()` set](https://docs.sympy.org/latest/modules/sets.html#sympy.sets.fancysets.Range) as the domain. If this produces the same range of values again, we know that for all possible values for that input, the modulo operation will not have any effect and can be eliminated.
However, because the left-hand-side expression in our modulo operations are always linear polynomials with positive coefficients (only `+` and `*` operations), you can instead substitute all input symbols with $9$ to determine the highest possible value. If the result is then lower than $b$, we know the modulo can be removed.
### Collapsing equality tests
We can do something similar for equality tests, but this time we'll have to stick with `solveset()`, as the alternative would have to be testing each possible combination of the inputs involved.
For each free $symbol$ in the $expression$ (each an input variable), test what `solveset(expression, symbol, Range(1, 10))` returns. This will give us a new set, the set of all values for that that symbol for which the outcome will be true. There are three possible outcomes:
* The empty set: the equality test is _always false_, regardless of what the value is for that input.
* The `Range(1, 10)` set: the equality test is _always true_, for all possible inputs.
* Some other set, which is always a subset of the input domain.
For the first two outcomes, the equality can be replaced by a boolean constant.
### Eliminating branches
From the above analysis we know that $z$ can only ever be zero if, by the time we reach the very last section, $z$ is a value between 0 and 25 inclusive, and the only way $z$ is going to get there is by division by 26. If you count the number times $z$ is divided by 26, you can test any given branch by substituting all inputs with 1 and seeing if the result is equal to or greater than 26 raised to the power of the number of divisions that are still left.
However, because we also eliminate branches that can never be taken (by collapsing equality tests), we can't know how many divisions will remain until we've parsed all the sections. So instead, we start with merging expressions that have already been simplified into a single branch into the current expression. The moment the merged expression still has two branches, we start a new set of expressions to merge.
Once we then have a series of branched expressions, we count how many of these divide by 26, so we know the limit beyond which a given expression will no longer reach zero. Each branch will have one or more inequality conditions, in the form of `inputA - inputB != number`; the remaining branches need to be updated with the _inverse_ of those conditions, because these conditions are what limit the input values to a smaller range. If you end up with a _single_ branch, you've found a path to `z == 0`, so we need to keep trace of those conditions.
### Finding the minimum and maximum possible version numbers
Merging all branches this way, results in a single `0` expression, and a single condition, a conjunction of equality tests. Each of those equality tests can be turned into a maximum value for the smaller of the two inputs. E.g., the expression `inputA - inputB = 5` can only be true if `inputB` is smaller than `inputA`, and can, at most, be `4`. If it was `5`, then the condition would have matched one of the already eliminated branches, ones that don't reach zero!
To determine the maximum version number, then, start with a list of all `9` digits, and adjust those for inputs that must be smaller to meet the conditions they are involved in. For part two, do the same with a list of `1` digits, adjusted upwards to keep the other input large enough for the condition to apply.
```python
from __future__ import annotations
from functools import cached_property, reduce, singledispatchmethod
from operator import add, mod, mul
from typing import Callable, Final
import sympy as sy
from sympy import piecewise_fold, simplify_logic, solveset
OPCODES: Final[dict[str, Callable[[sy.Basic, sy.Basic], sy.Basic]]] = {
"add": add,
"mul": mul,
"div": lambda a, b: (a - a % b) / b, # we can assume a * b >= 0, always.
"mod": mod,
"eql": lambda a, b: sy.Piecewise((1, sy.Eq(a, b)), (0, True)),
}
Z: Final[sy.Symbol] = sy.Symbol("z", integer=True, negative=False)
class MONAD:
_condition: sy.Boolean = sy.S.true
_limit: int = 0
_min: int | None = None
_max: int | None = None
def __init__(self, instructions: str) -> None:
self._parse(instructions)
def _parse(self, instructions: str) -> None:
reg: dict[str, sy.Basic] = dict.fromkeys("xyz", sy.S.Zero)
ws: list[sy.Symbol] = []
branches: list[sy.Basic] = [sy.S.Zero]
for block in instructions.split("inp w\n")[1:]:
w = sy.Symbol(f"w{len(ws)}", integer=True, positive=True, nonzero=True)
ws.append(w)
reg |= {"w": w, "z": Z}
for line in block.splitlines():
instr, target, *args = line.split()
args = [reg[p] if p in reg else sy.Integer(p) for p in args]
reg[target] = OPCODES[instr](reg[target], *args)
if not branches[-1].is_Piecewise:
reg["z"] = reg["z"].subs({Z: branches.pop()})
expr = piecewise_fold(reg["z"]).replace(*self._replace_args)
branches.append(expr)
# combine all branched expressions into a single expression, while
# removing branches that are never going to reach zero.
expr = sy.S.Zero
self._limit = 26 ** sum(1 for br in branches if br.has(sy.S.One / 26))
for branch in branches:
self._limit //= 26 if branch.has(sy.S.One / 26) else 1
expr = piecewise_fold(branch.subs({Z: expr})).replace(*self._replace_args)
def _find_extrema(self):
"""Turn the final 0 condition into boundaries for the 14 digits"""
ws = sorted(self._condition.free_symbols, key=sy.default_sort_key)
mins, maxs = [1] * len(ws), [9] * len(ws)
for cond in self._condition.args:
# each condition is an inequality between two inputs. It is always
# in the form inputA - inputB == C so we only need to know the value
# of C and the indexes of the input variables involved.
w1, w2, diff = cond.lhs.args[0], -cond.lhs.args[1], cond.rhs.p
if diff < 0:
w1, w2, diff = w2, w1, -diff
wi1, wi2 = ws.index(w1), ws.index(w2)
mins[wi1], maxs[wi2] = max(mins[wi1], 1 + diff), min(maxs[wi2], 9 - diff)
self._min = reduce(lambda a, b: a * 10 + b, mins)
self._max = reduce(lambda a, b: a * 10 + b, maxs)
@property
def minimum(self) -> int:
if self._min is None:
self._find_extrema()
return self._min
@property
def maximum(self) -> int:
if self._max is None:
self._find_extrema()
return self._max
@singledispatchmethod
def _simplify(self, _: sy.Basic) -> sy.Basic | None:
"""Handler for simplification handlers via single dispatch
Individual methods below are registered to simplify a specific Sympy
object type.
"""
return None
@cached_property
def _replace_args(
self,
) -> tuple[Callable[[sy.Basic], bool], Callable[[sy.Basic], sy.Basic | None]]:
"""Argument pair for Expr.replace(), dispatching to the _simplify() method
For each expression element for which the first callable returns True,
sympy calls the second method, which in turn will call the registered
hook method for the specific type of object.
"""
# this is way harder than it should be, singledispatchmethod should
# really add registry on the generated method directly. Access _simplify
# via the class namespace so the descriptor protocol doesn't kick in,
# so we can then access the dispatcher registry.
dispatch_registry = vars(type(self))["_simplify"].dispatcher.registry
types = tuple(dispatch_registry.keys() - {object})
return ((lambda a: isinstance(a, types)), self._simplify)
@_simplify.register
def _simplify_mod(self, mod: sy.Mod) -> sy.Basic | None:
"""Unwrap a modulo operation if a is always smaller than b"""
(a, b), subs = mod.args, dict.fromkeys(mod.free_symbols, 9)
if not mod.has(Z) and b.is_number and a.subs(subs) < b:
return a
return None
@_simplify.register
def _simplify_eq(self, eq: sy.Eq) -> sy.Basic | None:
"""Simplify an equality expression if it's always true or false"""
for sym in eq.free_symbols - {Z}:
match solveset(eq, sym, sy.Range(1, 10)):
case sy.EmptySet:
return sy.S.false
case sy.Range(1, 10):
return sy.S.true
return None
@_simplify.register
def _simplify_ne(self, ne: sy.Ne) -> sy.Basic | None:
"""Simplify an inequality expression if it's always true or false"""
if (result := self._simplify_eq(~ne)) is not None:
return ~result
return None
@_simplify.register
def _simplify_piecewise(self, pw: sy.Piecewise) -> sy.Basic | None:
"""Eliminate branches that will exceed the limit"""
limit = self._limit
if not limit:
return None
elim, new_pairs, subs = sy.S.true, [], dict.fromkeys(pw.free_symbols, 1)
for br, cond in pw.args:
if br.subs(subs) >= limit:
elim &= ~cond
continue
new_pairs.append((br, cond))
new_pairs = [(e, simplify_logic(c & elim)) for e, c in new_pairs]
if len(new_pairs) == 1:
# all other branches eliminated; update the condition that applies
# to this single branch.
(expr, cond), = new_pairs
self._condition &= cond
return expr
return pw.func(*new_pairs)
```
```python
import aocd
alu_instructions = aocd.get_data(day=24, year=2021)
expr = MONAD(alu_instructions)
print("Part 1:", expr.maximum)
print("Part 2:", expr.minimum)
```
Part 1: 29173959946999
Part 2: 17111815311469
|
State Before: 𝕜 : Type u_1
inst✝⁸ : NontriviallyNormedField 𝕜
E : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
F : Type u_3
inst✝⁵ : NormedAddCommGroup F
inst✝⁴ : NormedSpace 𝕜 F
G : Type ?u.375202
inst✝³ : NormedAddCommGroup G
inst✝² : NormedSpace 𝕜 G
G' : Type ?u.375297
inst✝¹ : NormedAddCommGroup G'
inst✝ : NormedSpace 𝕜 G'
f✝ f₀ f₁ g✝ : E → F
f'✝ f₀' f₁' g' e : E →L[𝕜] F
x : E
s t : Set E
L L₁ L₂ : Filter E
f : E → F
f' : E ≃L[𝕜] F
g : F → E
a : F
hg : ContinuousAt g a
hf : HasStrictFDerivAt f (↑f') (g a)
hfg : ∀ᶠ (y : F) in 𝓝 a, f (g y) = y
⊢ HasStrictFDerivAt g (↑(ContinuousLinearEquiv.symm f')) a State After: 𝕜 : Type u_1
inst✝⁸ : NontriviallyNormedField 𝕜
E : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
F : Type u_3
inst✝⁵ : NormedAddCommGroup F
inst✝⁴ : NormedSpace 𝕜 F
G : Type ?u.375202
inst✝³ : NormedAddCommGroup G
inst✝² : NormedSpace 𝕜 G
G' : Type ?u.375297
inst✝¹ : NormedAddCommGroup G'
inst✝ : NormedSpace 𝕜 G'
f✝ f₀ f₁ g✝ : E → F
f'✝ f₀' f₁' g' e : E →L[𝕜] F
x : E
s t : Set E
L L₁ L₂ : Filter E
f : E → F
f' : E ≃L[𝕜] F
g : F → E
a : F
hf : HasStrictFDerivAt f (↑f') (g a)
hfg : ∀ᶠ (y : F) in 𝓝 a, f (g y) = y
hg : ContinuousAt (fun p => (g p.fst, g p.snd)) (a, a)
⊢ HasStrictFDerivAt g (↑(ContinuousLinearEquiv.symm f')) a Tactic: replace hg := hg.prod_map' hg State Before: 𝕜 : Type u_1
inst✝⁸ : NontriviallyNormedField 𝕜
E : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
F : Type u_3
inst✝⁵ : NormedAddCommGroup F
inst✝⁴ : NormedSpace 𝕜 F
G : Type ?u.375202
inst✝³ : NormedAddCommGroup G
inst✝² : NormedSpace 𝕜 G
G' : Type ?u.375297
inst✝¹ : NormedAddCommGroup G'
inst✝ : NormedSpace 𝕜 G'
f✝ f₀ f₁ g✝ : E → F
f'✝ f₀' f₁' g' e : E →L[𝕜] F
x : E
s t : Set E
L L₁ L₂ : Filter E
f : E → F
f' : E ≃L[𝕜] F
g : F → E
a : F
hf : HasStrictFDerivAt f (↑f') (g a)
hfg : ∀ᶠ (y : F) in 𝓝 a, f (g y) = y
hg : ContinuousAt (fun p => (g p.fst, g p.snd)) (a, a)
⊢ HasStrictFDerivAt g (↑(ContinuousLinearEquiv.symm f')) a State After: 𝕜 : Type u_1
inst✝⁸ : NontriviallyNormedField 𝕜
E : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
F : Type u_3
inst✝⁵ : NormedAddCommGroup F
inst✝⁴ : NormedSpace 𝕜 F
G : Type ?u.375202
inst✝³ : NormedAddCommGroup G
inst✝² : NormedSpace 𝕜 G
G' : Type ?u.375297
inst✝¹ : NormedAddCommGroup G'
inst✝ : NormedSpace 𝕜 G'
f✝ f₀ f₁ g✝ : E → F
f'✝ f₀' f₁' g' e : E →L[𝕜] F
x : E
s t : Set E
L L₁ L₂ : Filter E
f : E → F
f' : E ≃L[𝕜] F
g : F → E
a : F
hf : HasStrictFDerivAt f (↑f') (g a)
hg : ContinuousAt (fun p => (g p.fst, g p.snd)) (a, a)
hfg : ∀ᶠ (p : F × F) in 𝓝 (a, a), f (g p.fst) = p.fst ∧ f (g p.snd) = p.snd
⊢ HasStrictFDerivAt g (↑(ContinuousLinearEquiv.symm f')) a Tactic: replace hfg := hfg.prod_mk_nhds hfg State Before: 𝕜 : Type u_1
inst✝⁸ : NontriviallyNormedField 𝕜
E : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
F : Type u_3
inst✝⁵ : NormedAddCommGroup F
inst✝⁴ : NormedSpace 𝕜 F
G : Type ?u.375202
inst✝³ : NormedAddCommGroup G
inst✝² : NormedSpace 𝕜 G
G' : Type ?u.375297
inst✝¹ : NormedAddCommGroup G'
inst✝ : NormedSpace 𝕜 G'
f✝ f₀ f₁ g✝ : E → F
f'✝ f₀' f₁' g' e : E →L[𝕜] F
x : E
s t : Set E
L L₁ L₂ : Filter E
f : E → F
f' : E ≃L[𝕜] F
g : F → E
a : F
hf : HasStrictFDerivAt f (↑f') (g a)
hg : ContinuousAt (fun p => (g p.fst, g p.snd)) (a, a)
hfg : ∀ᶠ (p : F × F) in 𝓝 (a, a), f (g p.fst) = p.fst ∧ f (g p.snd) = p.snd
⊢ HasStrictFDerivAt g (↑(ContinuousLinearEquiv.symm f')) a State After: 𝕜 : Type u_1
inst✝⁸ : NontriviallyNormedField 𝕜
E : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
F : Type u_3
inst✝⁵ : NormedAddCommGroup F
inst✝⁴ : NormedSpace 𝕜 F
G : Type ?u.375202
inst✝³ : NormedAddCommGroup G
inst✝² : NormedSpace 𝕜 G
G' : Type ?u.375297
inst✝¹ : NormedAddCommGroup G'
inst✝ : NormedSpace 𝕜 G'
f✝ f₀ f₁ g✝ : E → F
f'✝ f₀' f₁' g' e : E →L[𝕜] F
x : E
s t : Set E
L L₁ L₂ : Filter E
f : E → F
f' : E ≃L[𝕜] F
g : F → E
a : F
hf : HasStrictFDerivAt f (↑f') (g a)
hg : ContinuousAt (fun p => (g p.fst, g p.snd)) (a, a)
hfg : ∀ᶠ (p : F × F) in 𝓝 (a, a), f (g p.fst) = p.fst ∧ f (g p.snd) = p.snd
this :
(fun p => g p.fst - g p.snd - ↑(ContinuousLinearEquiv.symm f') (p.fst - p.snd)) =O[𝓝 (a, a)] fun p =>
↑f' (g p.fst - g p.snd) - (p.fst - p.snd)
⊢ HasStrictFDerivAt g (↑(ContinuousLinearEquiv.symm f')) a Tactic: have :
(fun p : F × F => g p.1 - g p.2 - f'.symm (p.1 - p.2)) =O[𝓝 (a, a)] fun p : F × F =>
f' (g p.1 - g p.2) - (p.1 - p.2) := by
refine' ((f'.symm : F →L[𝕜] E).isBigO_comp _ _).congr (fun x => _) fun _ => rfl
simp State Before: 𝕜 : Type u_1
inst✝⁸ : NontriviallyNormedField 𝕜
E : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
F : Type u_3
inst✝⁵ : NormedAddCommGroup F
inst✝⁴ : NormedSpace 𝕜 F
G : Type ?u.375202
inst✝³ : NormedAddCommGroup G
inst✝² : NormedSpace 𝕜 G
G' : Type ?u.375297
inst✝¹ : NormedAddCommGroup G'
inst✝ : NormedSpace 𝕜 G'
f✝ f₀ f₁ g✝ : E → F
f'✝ f₀' f₁' g' e : E →L[𝕜] F
x : E
s t : Set E
L L₁ L₂ : Filter E
f : E → F
f' : E ≃L[𝕜] F
g : F → E
a : F
hf : HasStrictFDerivAt f (↑f') (g a)
hg : ContinuousAt (fun p => (g p.fst, g p.snd)) (a, a)
hfg : ∀ᶠ (p : F × F) in 𝓝 (a, a), f (g p.fst) = p.fst ∧ f (g p.snd) = p.snd
this :
(fun p => g p.fst - g p.snd - ↑(ContinuousLinearEquiv.symm f') (p.fst - p.snd)) =O[𝓝 (a, a)] fun p =>
↑f' (g p.fst - g p.snd) - (p.fst - p.snd)
⊢ HasStrictFDerivAt g (↑(ContinuousLinearEquiv.symm f')) a State After: 𝕜 : Type u_1
inst✝⁸ : NontriviallyNormedField 𝕜
E : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
F : Type u_3
inst✝⁵ : NormedAddCommGroup F
inst✝⁴ : NormedSpace 𝕜 F
G : Type ?u.375202
inst✝³ : NormedAddCommGroup G
inst✝² : NormedSpace 𝕜 G
G' : Type ?u.375297
inst✝¹ : NormedAddCommGroup G'
inst✝ : NormedSpace 𝕜 G'
f✝ f₀ f₁ g✝ : E → F
f'✝ f₀' f₁' g' e : E →L[𝕜] F
x : E
s t : Set E
L L₁ L₂ : Filter E
f : E → F
f' : E ≃L[𝕜] F
g : F → E
a : F
hf : HasStrictFDerivAt f (↑f') (g a)
hg : ContinuousAt (fun p => (g p.fst, g p.snd)) (a, a)
hfg : ∀ᶠ (p : F × F) in 𝓝 (a, a), f (g p.fst) = p.fst ∧ f (g p.snd) = p.snd
this :
(fun p => g p.fst - g p.snd - ↑(ContinuousLinearEquiv.symm f') (p.fst - p.snd)) =O[𝓝 (a, a)] fun p =>
↑f' (g p.fst - g p.snd) - (p.fst - p.snd)
⊢ (fun p => ↑f' (g p.fst - g p.snd) - (p.fst - p.snd)) =o[𝓝 (a, a)] fun p => p.fst - p.snd Tactic: refine' this.trans_isLittleO _ State Before: 𝕜 : Type u_1
inst✝⁸ : NontriviallyNormedField 𝕜
E : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
F : Type u_3
inst✝⁵ : NormedAddCommGroup F
inst✝⁴ : NormedSpace 𝕜 F
G : Type ?u.375202
inst✝³ : NormedAddCommGroup G
inst✝² : NormedSpace 𝕜 G
G' : Type ?u.375297
inst✝¹ : NormedAddCommGroup G'
inst✝ : NormedSpace 𝕜 G'
f✝ f₀ f₁ g✝ : E → F
f'✝ f₀' f₁' g' e : E →L[𝕜] F
x : E
s t : Set E
L L₁ L₂ : Filter E
f : E → F
f' : E ≃L[𝕜] F
g : F → E
a : F
hf : HasStrictFDerivAt f (↑f') (g a)
hg : ContinuousAt (fun p => (g p.fst, g p.snd)) (a, a)
hfg : ∀ᶠ (p : F × F) in 𝓝 (a, a), f (g p.fst) = p.fst ∧ f (g p.snd) = p.snd
this :
(fun p => g p.fst - g p.snd - ↑(ContinuousLinearEquiv.symm f') (p.fst - p.snd)) =O[𝓝 (a, a)] fun p =>
↑f' (g p.fst - g p.snd) - (p.fst - p.snd)
⊢ (fun p => ↑f' (g p.fst - g p.snd) - (p.fst - p.snd)) =o[𝓝 (a, a)] fun p => p.fst - p.snd State After: 𝕜 : Type u_1
inst✝⁸ : NontriviallyNormedField 𝕜
E : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
F : Type u_3
inst✝⁵ : NormedAddCommGroup F
inst✝⁴ : NormedSpace 𝕜 F
G : Type ?u.375202
inst✝³ : NormedAddCommGroup G
inst✝² : NormedSpace 𝕜 G
G' : Type ?u.375297
inst✝¹ : NormedAddCommGroup G'
inst✝ : NormedSpace 𝕜 G'
f✝ f₀ f₁ g✝ : E → F
f'✝ f₀' f₁' g' e : E →L[𝕜] F
x : E
s t : Set E
L L₁ L₂ : Filter E
f : E → F
f' : E ≃L[𝕜] F
g : F → E
a : F
hf : HasStrictFDerivAt f (↑f') (g a)
hg : ContinuousAt (fun p => (g p.fst, g p.snd)) (a, a)
hfg : ∀ᶠ (p : F × F) in 𝓝 (a, a), f (g p.fst) = p.fst ∧ f (g p.snd) = p.snd
⊢ (fun p => ↑f' (g p.fst - g p.snd) - (p.fst - p.snd)) =o[𝓝 (a, a)] fun p => p.fst - p.snd Tactic: clear this State Before: 𝕜 : Type u_1
inst✝⁸ : NontriviallyNormedField 𝕜
E : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
F : Type u_3
inst✝⁵ : NormedAddCommGroup F
inst✝⁴ : NormedSpace 𝕜 F
G : Type ?u.375202
inst✝³ : NormedAddCommGroup G
inst✝² : NormedSpace 𝕜 G
G' : Type ?u.375297
inst✝¹ : NormedAddCommGroup G'
inst✝ : NormedSpace 𝕜 G'
f✝ f₀ f₁ g✝ : E → F
f'✝ f₀' f₁' g' e : E →L[𝕜] F
x : E
s t : Set E
L L₁ L₂ : Filter E
f : E → F
f' : E ≃L[𝕜] F
g : F → E
a : F
hf : HasStrictFDerivAt f (↑f') (g a)
hg : ContinuousAt (fun p => (g p.fst, g p.snd)) (a, a)
hfg : ∀ᶠ (p : F × F) in 𝓝 (a, a), f (g p.fst) = p.fst ∧ f (g p.snd) = p.snd
⊢ (fun p => ↑f' (g p.fst - g p.snd) - (p.fst - p.snd)) =o[𝓝 (a, a)] fun p => p.fst - p.snd State After: case refine'_1
𝕜 : Type u_1
inst✝⁸ : NontriviallyNormedField 𝕜
E : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
F : Type u_3
inst✝⁵ : NormedAddCommGroup F
inst✝⁴ : NormedSpace 𝕜 F
G : Type ?u.375202
inst✝³ : NormedAddCommGroup G
inst✝² : NormedSpace 𝕜 G
G' : Type ?u.375297
inst✝¹ : NormedAddCommGroup G'
inst✝ : NormedSpace 𝕜 G'
f✝ f₀ f₁ g✝ : E → F
f'✝ f₀' f₁' g' e : E →L[𝕜] F
x : E
s t : Set E
L L₁ L₂ : Filter E
f : E → F
f' : E ≃L[𝕜] F
g : F → E
a : F
hf : HasStrictFDerivAt f (↑f') (g a)
hg : ContinuousAt (fun p => (g p.fst, g p.snd)) (a, a)
hfg : ∀ᶠ (p : F × F) in 𝓝 (a, a), f (g p.fst) = p.fst ∧ f (g p.snd) = p.snd
⊢ ∀ (x : F × F),
f (g x.fst) = x.fst ∧ f (g x.snd) = x.snd →
(fun x =>
↑↑f' (((fun p => (g p.fst, g p.snd)) x).fst - ((fun p => (g p.fst, g p.snd)) x).snd) -
(f ((fun p => (g p.fst, g p.snd)) x).fst - f ((fun p => (g p.fst, g p.snd)) x).snd))
x =
↑f' (g x.fst - g x.snd) - (x.fst - x.snd)
case refine'_2
𝕜 : Type u_1
inst✝⁸ : NontriviallyNormedField 𝕜
E : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
F : Type u_3
inst✝⁵ : NormedAddCommGroup F
inst✝⁴ : NormedSpace 𝕜 F
G : Type ?u.375202
inst✝³ : NormedAddCommGroup G
inst✝² : NormedSpace 𝕜 G
G' : Type ?u.375297
inst✝¹ : NormedAddCommGroup G'
inst✝ : NormedSpace 𝕜 G'
f✝ f₀ f₁ g✝ : E → F
f'✝ f₀' f₁' g' e : E →L[𝕜] F
x : E
s t : Set E
L L₁ L₂ : Filter E
f : E → F
f' : E ≃L[𝕜] F
g : F → E
a : F
hf : HasStrictFDerivAt f (↑f') (g a)
hg : ContinuousAt (fun p => (g p.fst, g p.snd)) (a, a)
hfg : ∀ᶠ (p : F × F) in 𝓝 (a, a), f (g p.fst) = p.fst ∧ f (g p.snd) = p.snd
⊢ (fun x => ((fun p => p.fst - p.snd) ∘ fun p => (g p.fst, g p.snd)) x) =O[𝓝 (a, a)] fun p => p.fst - p.snd Tactic: refine'
((hf.comp_tendsto hg).symm.congr' (hfg.mono _) (eventually_of_forall fun _ => rfl)).trans_isBigO
_ State Before: 𝕜 : Type u_1
inst✝⁸ : NontriviallyNormedField 𝕜
E : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
F : Type u_3
inst✝⁵ : NormedAddCommGroup F
inst✝⁴ : NormedSpace 𝕜 F
G : Type ?u.375202
inst✝³ : NormedAddCommGroup G
inst✝² : NormedSpace 𝕜 G
G' : Type ?u.375297
inst✝¹ : NormedAddCommGroup G'
inst✝ : NormedSpace 𝕜 G'
f✝ f₀ f₁ g✝ : E → F
f'✝ f₀' f₁' g' e : E →L[𝕜] F
x : E
s t : Set E
L L₁ L₂ : Filter E
f : E → F
f' : E ≃L[𝕜] F
g : F → E
a : F
hf : HasStrictFDerivAt f (↑f') (g a)
hg : ContinuousAt (fun p => (g p.fst, g p.snd)) (a, a)
hfg : ∀ᶠ (p : F × F) in 𝓝 (a, a), f (g p.fst) = p.fst ∧ f (g p.snd) = p.snd
⊢ (fun p => g p.fst - g p.snd - ↑(ContinuousLinearEquiv.symm f') (p.fst - p.snd)) =O[𝓝 (a, a)] fun p =>
↑f' (g p.fst - g p.snd) - (p.fst - p.snd) State After: 𝕜 : Type u_1
inst✝⁸ : NontriviallyNormedField 𝕜
E : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
F : Type u_3
inst✝⁵ : NormedAddCommGroup F
inst✝⁴ : NormedSpace 𝕜 F
G : Type ?u.375202
inst✝³ : NormedAddCommGroup G
inst✝² : NormedSpace 𝕜 G
G' : Type ?u.375297
inst✝¹ : NormedAddCommGroup G'
inst✝ : NormedSpace 𝕜 G'
f✝ f₀ f₁ g✝ : E → F
f'✝ f₀' f₁' g' e : E →L[𝕜] F
x✝ : E
s t : Set E
L L₁ L₂ : Filter E
f : E → F
f' : E ≃L[𝕜] F
g : F → E
a : F
hf : HasStrictFDerivAt f (↑f') (g a)
hg : ContinuousAt (fun p => (g p.fst, g p.snd)) (a, a)
hfg : ∀ᶠ (p : F × F) in 𝓝 (a, a), f (g p.fst) = p.fst ∧ f (g p.snd) = p.snd
x : F × F
⊢ ↑↑(ContinuousLinearEquiv.symm f') (↑f' (g x.fst - g x.snd) - (x.fst - x.snd)) =
g x.fst - g x.snd - ↑(ContinuousLinearEquiv.symm f') (x.fst - x.snd) Tactic: refine' ((f'.symm : F →L[𝕜] E).isBigO_comp _ _).congr (fun x => _) fun _ => rfl State Before: 𝕜 : Type u_1
inst✝⁸ : NontriviallyNormedField 𝕜
E : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
F : Type u_3
inst✝⁵ : NormedAddCommGroup F
inst✝⁴ : NormedSpace 𝕜 F
G : Type ?u.375202
inst✝³ : NormedAddCommGroup G
inst✝² : NormedSpace 𝕜 G
G' : Type ?u.375297
inst✝¹ : NormedAddCommGroup G'
inst✝ : NormedSpace 𝕜 G'
f✝ f₀ f₁ g✝ : E → F
f'✝ f₀' f₁' g' e : E →L[𝕜] F
x✝ : E
s t : Set E
L L₁ L₂ : Filter E
f : E → F
f' : E ≃L[𝕜] F
g : F → E
a : F
hf : HasStrictFDerivAt f (↑f') (g a)
hg : ContinuousAt (fun p => (g p.fst, g p.snd)) (a, a)
hfg : ∀ᶠ (p : F × F) in 𝓝 (a, a), f (g p.fst) = p.fst ∧ f (g p.snd) = p.snd
x : F × F
⊢ ↑↑(ContinuousLinearEquiv.symm f') (↑f' (g x.fst - g x.snd) - (x.fst - x.snd)) =
g x.fst - g x.snd - ↑(ContinuousLinearEquiv.symm f') (x.fst - x.snd) State After: no goals Tactic: simp State Before: case refine'_1
𝕜 : Type u_1
inst✝⁸ : NontriviallyNormedField 𝕜
E : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
F : Type u_3
inst✝⁵ : NormedAddCommGroup F
inst✝⁴ : NormedSpace 𝕜 F
G : Type ?u.375202
inst✝³ : NormedAddCommGroup G
inst✝² : NormedSpace 𝕜 G
G' : Type ?u.375297
inst✝¹ : NormedAddCommGroup G'
inst✝ : NormedSpace 𝕜 G'
f✝ f₀ f₁ g✝ : E → F
f'✝ f₀' f₁' g' e : E →L[𝕜] F
x : E
s t : Set E
L L₁ L₂ : Filter E
f : E → F
f' : E ≃L[𝕜] F
g : F → E
a : F
hf : HasStrictFDerivAt f (↑f') (g a)
hg : ContinuousAt (fun p => (g p.fst, g p.snd)) (a, a)
hfg : ∀ᶠ (p : F × F) in 𝓝 (a, a), f (g p.fst) = p.fst ∧ f (g p.snd) = p.snd
⊢ ∀ (x : F × F),
f (g x.fst) = x.fst ∧ f (g x.snd) = x.snd →
(fun x =>
↑↑f' (((fun p => (g p.fst, g p.snd)) x).fst - ((fun p => (g p.fst, g p.snd)) x).snd) -
(f ((fun p => (g p.fst, g p.snd)) x).fst - f ((fun p => (g p.fst, g p.snd)) x).snd))
x =
↑f' (g x.fst - g x.snd) - (x.fst - x.snd) State After: case refine'_1.intro
𝕜 : Type u_1
inst✝⁸ : NontriviallyNormedField 𝕜
E : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
F : Type u_3
inst✝⁵ : NormedAddCommGroup F
inst✝⁴ : NormedSpace 𝕜 F
G : Type ?u.375202
inst✝³ : NormedAddCommGroup G
inst✝² : NormedSpace 𝕜 G
G' : Type ?u.375297
inst✝¹ : NormedAddCommGroup G'
inst✝ : NormedSpace 𝕜 G'
f✝ f₀ f₁ g✝ : E → F
f'✝ f₀' f₁' g' e : E →L[𝕜] F
x : E
s t : Set E
L L₁ L₂ : Filter E
f : E → F
f' : E ≃L[𝕜] F
g : F → E
a : F
hf : HasStrictFDerivAt f (↑f') (g a)
hg : ContinuousAt (fun p => (g p.fst, g p.snd)) (a, a)
hfg : ∀ᶠ (p : F × F) in 𝓝 (a, a), f (g p.fst) = p.fst ∧ f (g p.snd) = p.snd
p : F × F
hp1 : f (g p.fst) = p.fst
hp2 : f (g p.snd) = p.snd
⊢ (fun x =>
↑↑f' (((fun p => (g p.fst, g p.snd)) x).fst - ((fun p => (g p.fst, g p.snd)) x).snd) -
(f ((fun p => (g p.fst, g p.snd)) x).fst - f ((fun p => (g p.fst, g p.snd)) x).snd))
p =
↑f' (g p.fst - g p.snd) - (p.fst - p.snd) Tactic: rintro p ⟨hp1, hp2⟩ State Before: case refine'_1.intro
𝕜 : Type u_1
inst✝⁸ : NontriviallyNormedField 𝕜
E : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
F : Type u_3
inst✝⁵ : NormedAddCommGroup F
inst✝⁴ : NormedSpace 𝕜 F
G : Type ?u.375202
inst✝³ : NormedAddCommGroup G
inst✝² : NormedSpace 𝕜 G
G' : Type ?u.375297
inst✝¹ : NormedAddCommGroup G'
inst✝ : NormedSpace 𝕜 G'
f✝ f₀ f₁ g✝ : E → F
f'✝ f₀' f₁' g' e : E →L[𝕜] F
x : E
s t : Set E
L L₁ L₂ : Filter E
f : E → F
f' : E ≃L[𝕜] F
g : F → E
a : F
hf : HasStrictFDerivAt f (↑f') (g a)
hg : ContinuousAt (fun p => (g p.fst, g p.snd)) (a, a)
hfg : ∀ᶠ (p : F × F) in 𝓝 (a, a), f (g p.fst) = p.fst ∧ f (g p.snd) = p.snd
p : F × F
hp1 : f (g p.fst) = p.fst
hp2 : f (g p.snd) = p.snd
⊢ (fun x =>
↑↑f' (((fun p => (g p.fst, g p.snd)) x).fst - ((fun p => (g p.fst, g p.snd)) x).snd) -
(f ((fun p => (g p.fst, g p.snd)) x).fst - f ((fun p => (g p.fst, g p.snd)) x).snd))
p =
↑f' (g p.fst - g p.snd) - (p.fst - p.snd) State After: no goals Tactic: simp [hp1, hp2] State Before: case refine'_2
𝕜 : Type u_1
inst✝⁸ : NontriviallyNormedField 𝕜
E : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
F : Type u_3
inst✝⁵ : NormedAddCommGroup F
inst✝⁴ : NormedSpace 𝕜 F
G : Type ?u.375202
inst✝³ : NormedAddCommGroup G
inst✝² : NormedSpace 𝕜 G
G' : Type ?u.375297
inst✝¹ : NormedAddCommGroup G'
inst✝ : NormedSpace 𝕜 G'
f✝ f₀ f₁ g✝ : E → F
f'✝ f₀' f₁' g' e : E →L[𝕜] F
x : E
s t : Set E
L L₁ L₂ : Filter E
f : E → F
f' : E ≃L[𝕜] F
g : F → E
a : F
hf : HasStrictFDerivAt f (↑f') (g a)
hg : ContinuousAt (fun p => (g p.fst, g p.snd)) (a, a)
hfg : ∀ᶠ (p : F × F) in 𝓝 (a, a), f (g p.fst) = p.fst ∧ f (g p.snd) = p.snd
⊢ (fun x => ((fun p => p.fst - p.snd) ∘ fun p => (g p.fst, g p.snd)) x) =O[𝓝 (a, a)] fun p => p.fst - p.snd State After: case refine'_2
𝕜 : Type u_1
inst✝⁸ : NontriviallyNormedField 𝕜
E : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
F : Type u_3
inst✝⁵ : NormedAddCommGroup F
inst✝⁴ : NormedSpace 𝕜 F
G : Type ?u.375202
inst✝³ : NormedAddCommGroup G
inst✝² : NormedSpace 𝕜 G
G' : Type ?u.375297
inst✝¹ : NormedAddCommGroup G'
inst✝ : NormedSpace 𝕜 G'
f✝ f₀ f₁ g✝ : E → F
f'✝ f₀' f₁' g' e : E →L[𝕜] F
x : E
s t : Set E
L L₁ L₂ : Filter E
f : E → F
f' : E ≃L[𝕜] F
g : F → E
a : F
hf : HasStrictFDerivAt f (↑f') (g a)
hg : ContinuousAt (fun p => (g p.fst, g p.snd)) (a, a)
hfg : ∀ᶠ (p : F × F) in 𝓝 (a, a), f (g p.fst) = p.fst ∧ f (g p.snd) = p.snd
⊢ ∀ (x : F × F),
f (g x.fst) = x.fst ∧ f (g x.snd) = x.snd →
((fun p => f p.fst - f p.snd) ∘ fun p => (g p.fst, g p.snd)) x = (fun p => p.fst - p.snd) x Tactic: refine (hf.isBigO_sub_rev.comp_tendsto hg).congr' (eventually_of_forall fun _ => rfl)
(hfg.mono ?_) State Before: case refine'_2
𝕜 : Type u_1
inst✝⁸ : NontriviallyNormedField 𝕜
E : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
F : Type u_3
inst✝⁵ : NormedAddCommGroup F
inst✝⁴ : NormedSpace 𝕜 F
G : Type ?u.375202
inst✝³ : NormedAddCommGroup G
inst✝² : NormedSpace 𝕜 G
G' : Type ?u.375297
inst✝¹ : NormedAddCommGroup G'
inst✝ : NormedSpace 𝕜 G'
f✝ f₀ f₁ g✝ : E → F
f'✝ f₀' f₁' g' e : E →L[𝕜] F
x : E
s t : Set E
L L₁ L₂ : Filter E
f : E → F
f' : E ≃L[𝕜] F
g : F → E
a : F
hf : HasStrictFDerivAt f (↑f') (g a)
hg : ContinuousAt (fun p => (g p.fst, g p.snd)) (a, a)
hfg : ∀ᶠ (p : F × F) in 𝓝 (a, a), f (g p.fst) = p.fst ∧ f (g p.snd) = p.snd
⊢ ∀ (x : F × F),
f (g x.fst) = x.fst ∧ f (g x.snd) = x.snd →
((fun p => f p.fst - f p.snd) ∘ fun p => (g p.fst, g p.snd)) x = (fun p => p.fst - p.snd) x State After: case refine'_2.intro
𝕜 : Type u_1
inst✝⁸ : NontriviallyNormedField 𝕜
E : Type u_2
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
F : Type u_3
inst✝⁵ : NormedAddCommGroup F
inst✝⁴ : NormedSpace 𝕜 F
G : Type ?u.375202
inst✝³ : NormedAddCommGroup G
inst✝² : NormedSpace 𝕜 G
G' : Type ?u.375297
inst✝¹ : NormedAddCommGroup G'
inst✝ : NormedSpace 𝕜 G'
f✝ f₀ f₁ g✝ : E → F
f'✝ f₀' f₁' g' e : E →L[𝕜] F
x : E
s t : Set E
L L₁ L₂ : Filter E
f : E → F
f' : E ≃L[𝕜] F
g : F → E
a : F
hf : HasStrictFDerivAt f (↑f') (g a)
hg : ContinuousAt (fun p => (g p.fst, g p.snd)) (a, a)
hfg : ∀ᶠ (p : F × F) in 𝓝 (a, a), f (g p.fst) = p.fst ∧ f (g p.snd) = p.snd
p : F × F
hp1 : f (g p.fst) = p.fst
hp2 : f (g p.snd) = p.snd
⊢ ((fun p => f p.fst - f p.snd) ∘ fun p => (g p.fst, g p.snd)) p = (fun p => p.fst - p.snd) p Tactic: rintro p ⟨hp1, hp2⟩
|
section \<open>Quantales\<close>
theory Quantale_iso
imports Main
"HOL-Library.Lattice_Syntax"
begin
notation times (infixl "\<cdot>" 70)
class quantale = complete_lattice + monoid_mult +
assumes Sup_distl: "x \<cdot> \<Squnion>Y = (\<Squnion>y \<in> Y. x \<cdot> y)"
assumes Sup_distr: "\<Squnion>X \<cdot> y = (\<Squnion>x \<in> X. x \<cdot> y)"
subsection \<open>Relational Model of Kleene algebra\<close>
notation relcomp (infixl ";" 70)
interpretation rel_quantale: quantale Inf Sup inf "(\<subseteq>)" "(\<subset>)" sup "{}" "UNIV" Id "(;)"
by (unfold_locales, auto)
subsection \<open>State Transformer Model of Kleene Algebra\<close>
type_synonym 'a sta = "'a \<Rightarrow> 'a set"
definition eta :: "'a sta" ("\<eta>") where
"\<eta> x = {x}"
definition nsta :: "'a sta" ("\<nu>") where
"\<nu> x = {}"
definition tsta :: "'a sta" ("\<tau>") where
"\<tau> x = UNIV"
definition kcomp :: "'a sta \<Rightarrow> 'a sta \<Rightarrow> 'a sta" (infixl "\<circ>\<^sub>K" 75) where
"(f \<circ>\<^sub>K g) x = \<Union>{g y |y. y \<in> f x}"
definition kSup :: "'a sta set \<Rightarrow> 'a sta" where
"(kSup F) x = \<Union>{f x |f. f \<in> F}"
definition kInf :: "'a sta set \<Rightarrow> 'a sta" where
"(kInf F) x = \<Inter>{f x |f. f \<in> F}"
definition ksup :: "'a sta \<Rightarrow> 'a sta \<Rightarrow> 'a sta" where
"(ksup f g) x = f x \<union> g x"
definition kinf :: "'a sta \<Rightarrow> 'a sta \<Rightarrow> 'a sta" where
"(kinf f g) x = f x \<inter> g x"
definition kleq :: "'a sta \<Rightarrow> 'a sta \<Rightarrow> bool" (infix "\<sqsubseteq>" 50) where
"f \<sqsubseteq> g = (\<forall>x. f x \<subseteq> g x)"
definition kle :: "'a sta \<Rightarrow> 'a sta \<Rightarrow> bool" (infix "\<sqsubset>" 50) where
"f \<sqsubset> g = (f \<sqsubseteq> g \<and> f \<noteq> g)"
subsection \<open>Bijections between the relations and state transformers\<close>
definition r2s :: "'a rel \<Rightarrow> 'a sta" ("\<S>") where
"\<S> R = Image R \<circ> \<eta>"
definition s2r :: "'a sta \<Rightarrow> 'a rel" ("\<R>") where
"\<R> f = {(x,y). y \<in> f x}"
lemma r2s2r_galois: "(\<R> f = R) = (\<S> R = f)"
by (force simp: s2r_def eta_def r2s_def)
lemma r2s_bij: "bij \<S>"
by (metis bij_def inj_def r2s2r_galois surj_def)
lemma s2r_bij: "bij \<R>"
by (metis bij_def inj_def r2s2r_galois surj_def)
subsection \<open>Type definition and lifting for bijections\<close>
lemma type_definition_s2r_r2s: "type_definition \<R> \<S> UNIV"
unfolding type_definition_def by (meson iso_tuple_UNIV_I r2s2r_galois)
definition "rel_s2r R f = (R = \<R> f)"
lemma bi_unique_rel_s2r [transfer_rule]: "bi_unique rel_s2r"
by (metis rel_s2r_def type_definition_s2r_r2s typedef_bi_unique)
lemma bi_total_rel_s2r [transfer_rule]: "bi_total rel_s2r"
by (metis bi_total_def r2s2r_galois rel_s2r_def)
subsection \<open>Transfer functions\<close>
lemma r2s_id: "\<R> \<eta> = Id"
unfolding s2r_def Id_def eta_def by force
lemma Id_eta_transfer [transfer_rule]: "rel_s2r Id \<eta>"
unfolding rel_s2r_def
by (simp add: r2s_id rel_s2r_def)
lemma r2s_zero: "\<R> \<nu> = {}"
by (simp add: s2r_def nsta_def)
lemma emp_nsta_transfer [transfer_rule]: "rel_s2r {} \<nu>"
by (simp add: r2s_zero rel_s2r_def)
lemma r2s_tau: "\<R> \<tau> = UNIV"
unfolding s2r_def tsta_def by simp
lemma UNIV_tsta_transfer [transfer_rule]: "rel_s2r UNIV \<tau>"
by (simp add: r2s_tau rel_s2r_def)
lemma r2s_comp: "\<R> (f \<circ>\<^sub>K g) = \<R> f ; \<R> g"
unfolding s2r_def kcomp_def by force
lemma relcomp_kcomp_transfer [transfer_rule]: "rel_fun rel_s2r (rel_fun rel_s2r rel_s2r) (;) (\<circ>\<^sub>K)"
by (metis r2s_comp rel_funI rel_s2r_def)
lemma s2r_kSup: "\<R> (kSup F) = \<Union>(image \<R> F)"
unfolding s2r_def kSup_def by force
lemma Un_kSup_transfer [transfer_rule]: "rel_fun (rel_set rel_s2r) rel_s2r Union kSup"
unfolding rel_s2r_def rel_fun_def rel_set_def s2r_kSup by fastforce
lemma s2r_kInf: "\<R> (kInf F) = \<Inter>(image \<R> F)"
unfolding s2r_def kInf_def by force
lemma Un_kInf_transfer [transfer_rule]: "rel_fun (rel_set rel_s2r) rel_s2r Inter kInf"
unfolding rel_s2r_def rel_fun_def rel_set_def s2r_kInf by fastforce
lemma s2r_ksup: "\<R> (ksup f g) = \<R> f \<union> \<R> g"
unfolding s2r_def ksup_def by force
lemma un_ksup_transfer [transfer_rule]: "rel_fun rel_s2r (rel_fun rel_s2r rel_s2r) (\<union>) (ksup)"
by (metis rel_funI rel_s2r_def s2r_ksup)
lemma s2r_kinf: "\<R> (kinf f g) = \<R> f \<inter> \<R> g"
unfolding s2r_def kinf_def by force
lemma in_kinf_transfer [transfer_rule]: "rel_fun rel_s2r (rel_fun rel_s2r rel_s2r) (\<inter>) (kinf)"
by (metis rel_funI rel_s2r_def s2r_kinf)
lemma leq_kleq_transfer [transfer_rule]: "rel_fun rel_s2r (rel_fun rel_s2r (=)) (\<subseteq>) (\<sqsubseteq>)"
unfolding kleq_def s2r_def rel_s2r_def by force
lemma le_kle_transfer [transfer_rule]: "rel_fun rel_s2r (rel_fun rel_s2r (=)) (\<subset>) (\<sqsubset>)"
unfolding kle_def kleq_def s2r_def rel_s2r_def by blast
text \<open>State transformer model of Kleene algebra\<close>
interpretation sta_quantale: quantale kInf kSup kinf "(\<sqsubseteq>)" "(\<sqsubset>)" ksup "\<nu>" tsta "\<eta>" "(\<circ>\<^sub>K)"
by unfold_locales (transfer, force)+
end
|
#include <Common/config.h>
#include <Common/config_version.h>
#if USE_RDKAFKA
#include <thread>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <Poco/Util/AbstractConfiguration.h>
#include <Common/Macros.h>
#include <Common/Exception.h>
#include <Common/setThreadName.h>
#include <Common/typeid_cast.h>
#include <Formats/FormatFactory.h>
#include <DataStreams/IProfilingBlockInputStream.h>
#include <DataStreams/LimitBlockInputStream.h>
#include <DataStreams/UnionBlockInputStream.h>
#include <DataStreams/copyData.h>
#include <Interpreters/Context.h>
#include <Interpreters/InterpreterInsertQuery.h>
#include <Interpreters/evaluateConstantExpression.h>
#include <Parsers/ASTExpressionList.h>
#include <Parsers/ASTIdentifier.h>
#include <Parsers/ASTInsertQuery.h>
#include <Parsers/ASTLiteral.h>
#include <Storages/StorageKafka.h>
#include <Storages/StorageFactory.h>
#include <IO/ReadBuffer.h>
#include <common/logger_useful.h>
#if __has_include(<rdkafka.h>) // maybe bundled
#include <rdkafka.h>
#else // system
#include <librdkafka/rdkafka.h>
#endif
namespace DB
{
namespace ErrorCodes
{
extern const int INCORRECT_DATA;
extern const int UNKNOWN_EXCEPTION;
extern const int CANNOT_READ_FROM_ISTREAM;
extern const int INVALID_CONFIG_PARAMETER;
extern const int LOGICAL_ERROR;
extern const int BAD_ARGUMENTS;
extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH;
}
using namespace Poco::Util;
/// How long to wait for a single message (applies to each individual message)
static const auto READ_POLL_MS = 500;
static const auto CLEANUP_TIMEOUT_MS = 3000;
/// Configuration prefix
static const String CONFIG_PREFIX = "kafka";
class ReadBufferFromKafkaConsumer : public ReadBuffer
{
rd_kafka_t * consumer;
rd_kafka_message_t * current;
Poco::Logger * log;
size_t read_messages;
bool nextImpl() override
{
reset();
// Process next buffered message
rd_kafka_message_t * msg = rd_kafka_consumer_poll(consumer, READ_POLL_MS);
if (msg == nullptr)
return false;
if (msg->err)
{
if (msg->err != RD_KAFKA_RESP_ERR__PARTITION_EOF)
{
LOG_ERROR(log, "Consumer error: " << rd_kafka_err2str(msg->err) << " " << rd_kafka_message_errstr(msg));
rd_kafka_message_destroy(msg);
return false;
}
// Reach EOF while reading current batch, skip it
LOG_TRACE(log, "EOF reached for partition " << msg->partition << " offset " << msg->offset);
rd_kafka_message_destroy(msg);
return nextImpl();
}
// Consume message and mark the topic/partition offset
// The offsets will be committed in the insertSuffix() method after the block is completed
// If an exception is thrown before that would occur, the client will rejoin without comitting offsets
BufferBase::set(reinterpret_cast<char *>(msg->payload), msg->len, 0);
current = msg;
++read_messages;
return true;
}
void reset()
{
if (current != nullptr)
{
rd_kafka_message_destroy(current);
current = nullptr;
}
}
public:
ReadBufferFromKafkaConsumer(rd_kafka_t * consumer_, Poco::Logger * log_)
: ReadBuffer(nullptr, 0), consumer(consumer_), current(nullptr), log(log_), read_messages(0) {}
~ReadBufferFromKafkaConsumer() { reset(); }
/// Commit messages read with this consumer
void commit()
{
LOG_TRACE(log, "Committing " << read_messages << " messages");
if (read_messages == 0)
return;
auto err = rd_kafka_commit(consumer, NULL, 1 /* async */);
if (err)
throw Exception("Failed to commit offsets: " + String(rd_kafka_err2str(err)), ErrorCodes::UNKNOWN_EXCEPTION);
read_messages = 0;
}
};
class KafkaBlockInputStream : public IProfilingBlockInputStream
{
public:
KafkaBlockInputStream(StorageKafka & storage_, StorageKafka::ConsumerPtr consumer_, const Context & context_, const String & schema, size_t max_block_size)
: storage(storage_), consumer(consumer_)
{
// Always skip unknown fields regardless of the context (JSON or TSKV)
Context context = context_;
context.setSetting("input_format_skip_unknown_fields", UInt64(1));
if (schema.size() > 0)
context.setSetting("format_schema", schema);
// Create a formatted reader on Kafka messages
LOG_TRACE(storage.log, "Creating formatted reader");
read_buf = std::make_unique<ReadBufferFromKafkaConsumer>(consumer->stream, storage.log);
reader = FormatFactory::instance().getInput(storage.format_name, *read_buf, storage.getSampleBlock(), context, max_block_size);
}
~KafkaBlockInputStream() override
{
// An error was thrown during the stream or it did not finish successfully
// The read offsets weren't comitted, so consumer must rejoin the group from the original starting point
if (!finalized)
{
LOG_TRACE(storage.log, "KafkaBlockInputStream did not finish successfully, unsubscribing from assignments and rejoining");
consumer->unsubscribe();
consumer->subscribe(storage.topics);
}
// Return consumer for another reader
storage.pushConsumer(consumer);
}
String getName() const override
{
return storage.getName();
}
Block readImpl() override
{
if (isCancelledOrThrowIfKilled())
return {};
return reader->read();
}
Block getHeader() const override { return reader->getHeader(); };
void readPrefixImpl() override
{
// Start reading data
finalized = false;
reader->readPrefix();
}
void readSuffixImpl() override
{
reader->readSuffix();
// Store offsets read in this stream
read_buf->commit();
// Mark as successfully finished
finalized = true;
}
private:
StorageKafka & storage;
StorageKafka::ConsumerPtr consumer;
Block sample_block;
std::unique_ptr<ReadBufferFromKafkaConsumer> read_buf;
BlockInputStreamPtr reader;
bool finalized = false;
};
static void loadFromConfig(struct rd_kafka_conf_s * conf, const AbstractConfiguration & config, const std::string & path)
{
AbstractConfiguration::Keys keys;
std::vector<char> errstr(512);
config.keys(path, keys);
for (const auto & key : keys)
{
const String key_path = path + "." + key;
const String key_name = boost::replace_all_copy(key, "_", ".");
if (rd_kafka_conf_set(conf, key_name.c_str(), config.getString(key_path).c_str(), errstr.data(), errstr.size()) != RD_KAFKA_CONF_OK)
throw Exception("Invalid Kafka setting " + key_path + " in config: " + String(errstr.data()), ErrorCodes::INVALID_CONFIG_PARAMETER);
}
}
StorageKafka::StorageKafka(
const std::string & table_name_,
const std::string & database_name_,
Context & context_,
const ColumnsDescription & columns_,
const String & brokers_, const String & group_, const Names & topics_,
const String & format_name_, const String & schema_name_, size_t num_consumers_)
: IStorage{columns_},
table_name(table_name_), database_name(database_name_), context(context_),
topics(context.getMacros()->expand(topics_)),
brokers(context.getMacros()->expand(brokers_)),
group(context.getMacros()->expand(group_)),
format_name(context.getMacros()->expand(format_name_)),
schema_name(context.getMacros()->expand(schema_name_)),
num_consumers(num_consumers_), log(&Logger::get("StorageKafka (" + table_name_ + ")")),
semaphore(0, num_consumers_), mutex(), consumers(), event_update()
{
}
BlockInputStreams StorageKafka::read(
const Names & column_names,
const SelectQueryInfo & /*query_info*/,
const Context & context,
QueryProcessingStage::Enum & processed_stage,
size_t max_block_size,
unsigned num_streams)
{
check(column_names);
processed_stage = QueryProcessingStage::FetchColumns;
if (num_consumers == 0)
return BlockInputStreams();
const size_t stream_count = std::min(num_streams, num_consumers);
BlockInputStreams streams;
streams.reserve(stream_count);
// Claim as many consumers as requested, but don't block
for (size_t i = 0; i < stream_count; ++i)
{
auto consumer = tryClaimConsumer(0);
if (consumer == nullptr)
break;
// Use block size of 1, otherwise LIMIT won't work properly as it will buffer excess messages in the last block
streams.push_back(std::make_shared<KafkaBlockInputStream>(*this, consumer, context, schema_name, 1));
}
LOG_DEBUG(log, "Starting reading " << streams.size() << " streams, " << max_block_size << " block size");
return streams;
}
void StorageKafka::startup()
{
for (size_t i = 0; i < num_consumers; ++i)
{
// Building configuration may throw, the consumer configuration must be destroyed in that case
auto consumer_conf = rd_kafka_conf_new();
try
{
consumerConfiguration(consumer_conf);
}
catch (...)
{
rd_kafka_conf_destroy(consumer_conf);
throw;
}
// Create a consumer and subscribe to topics
// Note: consumer takes ownership of the configuration
auto consumer = std::make_shared<StorageKafka::Consumer>(consumer_conf);
consumer->subscribe(topics);
// Make consumer available
pushConsumer(consumer);
++num_created_consumers;
}
// Start the reader thread
stream_thread = std::thread(&StorageKafka::streamThread, this);
}
void StorageKafka::shutdown()
{
// Interrupt streaming thread
stream_cancelled = true;
event_update.set();
// Unsubscribe from assignments
LOG_TRACE(log, "Unsubscribing from assignments");
for (size_t i = 0; i < num_created_consumers; ++i)
{
auto consumer = claimConsumer();
consumer->unsubscribe();
}
// Wait for stream thread to finish
if (stream_thread.joinable())
stream_thread.join();
rd_kafka_wait_destroyed(CLEANUP_TIMEOUT_MS);
}
void StorageKafka::updateDependencies()
{
event_update.set();
}
void StorageKafka::consumerConfiguration(struct rd_kafka_conf_s * conf)
{
std::vector<char> errstr(512);
LOG_TRACE(log, "Setting brokers: " << brokers);
if (rd_kafka_conf_set(conf, "metadata.broker.list", brokers.c_str(), errstr.data(), errstr.size()) != RD_KAFKA_CONF_OK)
throw Exception(String(errstr.data()), ErrorCodes::INCORRECT_DATA);
LOG_TRACE(log, "Setting Group ID: " << group << " Client ID: clickhouse");
if (rd_kafka_conf_set(conf, "group.id", group.c_str(), errstr.data(), errstr.size()) != RD_KAFKA_CONF_OK)
throw Exception(String(errstr.data()), ErrorCodes::INCORRECT_DATA);
if (rd_kafka_conf_set(conf, "client.id", VERSION_FULL, errstr.data(), errstr.size()) != RD_KAFKA_CONF_OK)
throw Exception(String(errstr.data()), ErrorCodes::INCORRECT_DATA);
// We manually commit offsets after a stream successfully finished
rd_kafka_conf_set(conf, "enable.auto.commit", "false", nullptr, 0);
// Update consumer configuration from the configuration
const auto & config = context.getConfigRef();
if (config.has(CONFIG_PREFIX))
loadFromConfig(conf, config, CONFIG_PREFIX);
// Update consumer topic-specific configuration
for (const auto & topic : topics)
{
const auto topic_config_key = CONFIG_PREFIX + "_" + topic;
if (config.has(topic_config_key))
loadFromConfig(conf, config, topic_config_key);
}
}
StorageKafka::ConsumerPtr StorageKafka::claimConsumer()
{
return tryClaimConsumer(-1L);
}
StorageKafka::ConsumerPtr StorageKafka::tryClaimConsumer(long wait_ms)
{
// Wait for the first free consumer
if (wait_ms >= 0)
{
if (!semaphore.tryWait(wait_ms))
return nullptr;
}
else
semaphore.wait();
// Take the first available consumer from the list
std::lock_guard<std::mutex> lock(mutex);
auto consumer = consumers.back();
consumers.pop_back();
return consumer;
}
void StorageKafka::pushConsumer(StorageKafka::ConsumerPtr c)
{
std::lock_guard<std::mutex> lock(mutex);
consumers.push_back(c);
semaphore.set();
}
void StorageKafka::streamThread()
{
setThreadName("KafkaStreamThr");
while (!stream_cancelled)
{
try
{
// Keep streaming as long as there are attached views and streaming is not cancelled
while (!stream_cancelled)
{
// Check if all dependencies are attached
auto dependencies = context.getDependencies(database_name, table_name);
if (dependencies.size() == 0)
break;
// Check the dependencies are ready?
bool ready = true;
for (const auto & db_tab : dependencies)
{
if (!context.tryGetTable(db_tab.first, db_tab.second))
ready = false;
}
if (!ready)
break;
LOG_DEBUG(log, "Started streaming to " << dependencies.size() << " attached views");
streamToViews();
LOG_DEBUG(log, "Stopped streaming to views");
}
}
catch (...)
{
tryLogCurrentException(__PRETTY_FUNCTION__);
}
// Wait for attached views
event_update.tryWait(READ_POLL_MS);
}
LOG_DEBUG(log, "Stream thread finished");
}
void StorageKafka::streamToViews()
{
auto table = context.getTable(database_name, table_name);
if (!table)
throw Exception("Engine table " + database_name + "." + table_name + " doesn't exist.", ErrorCodes::LOGICAL_ERROR);
// Create an INSERT query for streaming data
auto insert = std::make_shared<ASTInsertQuery>();
insert->database = database_name;
insert->table = table_name;
insert->no_destination = true; // Only insert into dependent views
// Limit the number of batched messages to allow early cancellations
const Settings & settings = context.getSettingsRef();
const size_t block_size = settings.max_block_size.value;
// Create a stream for each consumer and join them in a union stream
BlockInputStreams streams;
streams.reserve(num_consumers);
for (size_t i = 0; i < num_consumers; ++i)
{
auto consumer = claimConsumer();
auto stream = std::make_shared<KafkaBlockInputStream>(*this, consumer, context, schema_name, block_size);
streams.push_back(stream);
// Limit read batch to maximum block size to allow DDL
IProfilingBlockInputStream::LocalLimits limits;
limits.max_execution_time = settings.stream_flush_interval_ms;
limits.timeout_overflow_mode = OverflowMode::BREAK;
if (IProfilingBlockInputStream * p_stream = dynamic_cast<IProfilingBlockInputStream *>(stream.get()))
p_stream->setLimits(limits);
}
auto in = std::make_shared<UnionBlockInputStream<>>(streams, nullptr, num_consumers);
// Execute the query
InterpreterInsertQuery interpreter{insert, context};
auto block_io = interpreter.execute();
copyData(*in, *block_io.out, &stream_cancelled);
}
StorageKafka::Consumer::Consumer(struct rd_kafka_conf_s * conf)
{
std::vector<char> errstr(512);
stream = rd_kafka_new(RD_KAFKA_CONSUMER, conf, errstr.data(), errstr.size());
if (stream == nullptr)
{
rd_kafka_conf_destroy(conf);
throw Exception("Failed to create consumer handle: " + String(errstr.data()), ErrorCodes::UNKNOWN_EXCEPTION);
}
rd_kafka_poll_set_consumer(stream);
}
StorageKafka::Consumer::~Consumer()
{
if (stream != nullptr)
{
rd_kafka_consumer_close(stream);
rd_kafka_destroy(stream);
stream = nullptr;
}
}
void StorageKafka::Consumer::subscribe(const Names & topics)
{
if (stream == nullptr)
throw Exception("Cannot subscribe to topics when consumer is closed", ErrorCodes::UNKNOWN_EXCEPTION);
// Create a list of partitions
auto * topicList = rd_kafka_topic_partition_list_new(topics.size());
for (const auto & t : topics)
{
rd_kafka_topic_partition_list_add(topicList, t.c_str(), RD_KAFKA_PARTITION_UA);
}
// Subscribe to requested topics
auto err = rd_kafka_subscribe(stream, topicList);
if (err)
{
rd_kafka_topic_partition_list_destroy(topicList);
throw Exception("Failed to subscribe: " + String(rd_kafka_err2str(err)), ErrorCodes::UNKNOWN_EXCEPTION);
}
rd_kafka_topic_partition_list_destroy(topicList);
}
void StorageKafka::Consumer::unsubscribe()
{
if (stream != nullptr)
rd_kafka_unsubscribe(stream);
}
void registerStorageKafka(StorageFactory & factory)
{
factory.registerStorage("Kafka", [](const StorageFactory::Arguments & args)
{
ASTs & engine_args = args.engine_args;
/** Arguments of engine is following:
* - Kafka broker list
* - List of topics
* - Group ID (may be a constaint expression with a string result)
* - Message format (string)
* - Schema (optional, if the format supports it)
*/
if (engine_args.size() < 3 || engine_args.size() > 6)
throw Exception(
"Storage Kafka requires 3-6 parameters"
" - Kafka broker list, list of topics to consume, consumer group ID, message format, schema, number of consumers",
ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);
String brokers;
auto ast = typeid_cast<const ASTLiteral *>(engine_args[0].get());
if (ast && ast->value.getType() == Field::Types::String)
brokers = safeGet<String>(ast->value);
else
throw Exception(String("Kafka broker list must be a string"), ErrorCodes::BAD_ARGUMENTS);
engine_args[1] = evaluateConstantExpressionAsLiteral(engine_args[1], args.local_context);
engine_args[2] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[2], args.local_context);
engine_args[3] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[3], args.local_context);
// Parse format schema if supported (optional)
String schema;
if (engine_args.size() >= 5)
{
engine_args[4] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[4], args.local_context);
auto ast = typeid_cast<const ASTLiteral *>(engine_args[4].get());
if (ast && ast->value.getType() == Field::Types::String)
schema = safeGet<String>(ast->value);
else
throw Exception("Format schema must be a string", ErrorCodes::BAD_ARGUMENTS);
}
// Parse number of consumers (optional)
UInt64 num_consumers = 1;
if (engine_args.size() >= 6)
{
auto ast = typeid_cast<const ASTLiteral *>(engine_args[5].get());
if (ast && ast->value.getType() == Field::Types::UInt64)
num_consumers = safeGet<UInt64>(ast->value);
else
throw Exception("Number of consumers must be a positive integer", ErrorCodes::BAD_ARGUMENTS);
}
// Parse topic list
Names topics;
String topic_arg = static_cast<const ASTLiteral &>(*engine_args[1]).value.safeGet<String>();
boost::split(topics, topic_arg , [](char c){ return c == ','; });
for(String & topic : topics)
boost::trim(topic);
// Parse consumer group
String group = static_cast<const ASTLiteral &>(*engine_args[2]).value.safeGet<String>();
// Parse format from string
String format;
ast = typeid_cast<const ASTLiteral *>(engine_args[3].get());
if (ast && ast->value.getType() == Field::Types::String)
format = safeGet<String>(ast->value);
else
throw Exception("Format must be a string", ErrorCodes::BAD_ARGUMENTS);
return StorageKafka::create(
args.table_name, args.database_name, args.context, args.columns,
brokers, group, topics, format, schema, num_consumers);
});
}
}
#endif
|
\chapter{Introduction}
The NASA Ames StereoPipeline is a suite of automated geodesy and
stereogrammetry tools designed for processing planetary imagery
captured from orbiting and landed robotic explorers on other planets.
It was designed to process stereo imagery captured by NASA
spacecraft and produce cartographic products including DEM,
ortho-projected imagery, and 3D models. These data products are
suitable for science analysis, mission planning, and public outreach.
\section{Photometry Toolkit}
Yes, this software is still in developement.
\section{Warnings to users of the Ames Stereo Pipeline BETA}
This is an {\bf BETA} release of the Stereo Pipeline. There are many
known bugs and incomplete features. The API and command line options
will almost certainly change prior to the final release. Some of the
documentation is incomplete and some of it may be out of date or
incorrect. Although we hope you will find this release helpful, you
use it at your own risk.
While we are confident that the algorithms used by this software are
robust, they have not been systematically tested or rigorously
compared to other methods in the peer-reviewed literature. We have a
number of efforts underway to carefully compare Stereo
Pipeline-generated data products to those produced using established
processes, and we will publish those results as they become available.
In the meantime, {\bf we strongly recommend that you consult us first
before publishing any results based on the cartographic products
produced by this software}. You have been warned!
|
/-
Copyright (c) 2014 Robert Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Lewis, Leonardo de Moura, Johannes Hölzl, Mario Carneiro
-/
import data.rat.init
import algebra.ring.defs
/-!
# Division (semi)rings and (semi)fields
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file introduces fields and division rings (also known as skewfields) and proves some basic
statements about them. For a more extensive theory of fields, see the `field_theory` folder.
## Main definitions
* `division_semiring`: Nontrivial semiring with multiplicative inverses for nonzero elements.
* `division_ring`: : Nontrivial ring with multiplicative inverses for nonzero elements.
* `semifield`: Commutative division semiring.
* `field`: Commutative division ring.
* `is_field`: Predicate on a (semi)ring that it is a (semi)field, i.e. that the multiplication is
commutative, that it has more than one element and that all non-zero elements have a
multiplicative inverse. In contrast to `field`, which contains the data of a function associating
to an element of the field its multiplicative inverse, this predicate only assumes the existence
and can therefore more easily be used to e.g. transfer along ring isomorphisms.
## Implementation details
By convention `0⁻¹ = 0` in a field or division ring. This is due to the fact that working with total
functions has the advantage of not constantly having to check that `x ≠ 0` when writing `x⁻¹`. With
this convention in place, some statements like `(a + b) * c⁻¹ = a * c⁻¹ + b * c⁻¹` still remain
true, while others like the defining property `a * a⁻¹ = 1` need the assumption `a ≠ 0`. If you are
a beginner in using Lean and are confused by that, you can read more about why this convention is
taken in Kevin Buzzard's
[blogpost](https://xenaproject.wordpress.com/2020/07/05/division-by-zero-in-type-theory-a-faq/)
A division ring or field is an example of a `group_with_zero`. If you cannot find
a division ring / field lemma that does not involve `+`, you can try looking for
a `group_with_zero` lemma instead.
## Tags
field, division ring, skew field, skew-field, skewfield
-/
open function set
set_option old_structure_cmd true
universe u
variables {α β K : Type*}
/-- The default definition of the coercion `(↑(a : ℚ) : K)` for a division ring `K`
is defined as `(a / b : K) = (a : K) * (b : K)⁻¹`.
Use `coe` instead of `rat.cast_rec` for better definitional behaviour.
-/
def rat.cast_rec [has_lift_t ℕ K] [has_lift_t ℤ K] [has_mul K] [has_inv K] : ℚ → K
| ⟨a, b, _, _⟩ := ↑a * (↑b)⁻¹
/--
Type class for the canonical homomorphism `ℚ → K`.
-/
@[protect_proj]
class has_rat_cast (K : Type u) :=
(rat_cast : ℚ → K)
/-- The default definition of the scalar multiplication `(a : ℚ) • (x : K)` for a division ring `K`
is given by `a • x = (↑ a) * x`.
Use `(a : ℚ) • (x : K)` instead of `qsmul_rec` for better definitional behaviour.
-/
def qsmul_rec (coe : ℚ → K) [has_mul K] (a : ℚ) (x : K) : K :=
coe a * x
/-- A `division_semiring` is a `semiring` with multiplicative inverses for nonzero elements. -/
@[protect_proj, ancestor semiring group_with_zero]
class division_semiring (α : Type*) extends semiring α, group_with_zero α
/-- A `division_ring` is a `ring` with multiplicative inverses for nonzero elements.
An instance of `division_ring K` includes maps `rat_cast : ℚ → K` and `qsmul : ℚ → K → K`.
If the division ring has positive characteristic p, we define `rat_cast (1 / p) = 1 / 0 = 0`
for consistency with our division by zero convention.
The fields `rat_cast` and `qsmul` are needed to implement the
`algebra_rat [division_ring K] : algebra ℚ K` instance, since we need to control the specific
definitions for some special cases of `K` (in particular `K = ℚ` itself).
See also Note [forgetful inheritance].
-/
@[protect_proj, ancestor ring div_inv_monoid nontrivial]
class division_ring (K : Type u) extends ring K, div_inv_monoid K, nontrivial K, has_rat_cast K :=
(mul_inv_cancel : ∀ {a : K}, a ≠ 0 → a * a⁻¹ = 1)
(inv_zero : (0 : K)⁻¹ = 0)
(rat_cast := rat.cast_rec)
(rat_cast_mk : ∀ (a : ℤ) (b : ℕ) h1 h2, rat_cast ⟨a, b, h1, h2⟩ = a * b⁻¹ . try_refl_tac)
(qsmul : ℚ → K → K := qsmul_rec rat_cast)
(qsmul_eq_mul' : ∀ (a : ℚ) (x : K), qsmul a x = rat_cast a * x . try_refl_tac)
@[priority 100] -- see Note [lower instance priority]
instance division_ring.to_division_semiring [division_ring α] : division_semiring α :=
{ ..‹division_ring α›, ..(infer_instance : semiring α) }
/-- A `semifield` is a `comm_semiring` with multiplicative inverses for nonzero elements. -/
@[protect_proj, ancestor comm_semiring division_semiring comm_group_with_zero]
class semifield (α : Type*) extends comm_semiring α, division_semiring α, comm_group_with_zero α
/-- A `field` is a `comm_ring` with multiplicative inverses for nonzero elements.
An instance of `field K` includes maps `of_rat : ℚ → K` and `qsmul : ℚ → K → K`.
If the field has positive characteristic p, we define `of_rat (1 / p) = 1 / 0 = 0`
for consistency with our division by zero convention.
The fields `of_rat` and `qsmul are needed to implement the
`algebra_rat [division_ring K] : algebra ℚ K` instance, since we need to control the specific
definitions for some special cases of `K` (in particular `K = ℚ` itself).
See also Note [forgetful inheritance].
-/
@[protect_proj, ancestor comm_ring div_inv_monoid nontrivial]
class field (K : Type u) extends comm_ring K, division_ring K
section division_ring
variables [division_ring K] {a b : K}
namespace rat
/-- Construct the canonical injection from `ℚ` into an arbitrary
division ring. If the field has positive characteristic `p`,
we define `1 / p = 1 / 0 = 0` for consistency with our
division by zero convention. -/
-- see Note [coercion into rings]
@[priority 900] instance cast_coe {K : Type*} [has_rat_cast K] : has_coe_t ℚ K :=
⟨has_rat_cast.rat_cast⟩
theorem cast_mk' (a b h1 h2) : ((⟨a, b, h1, h2⟩ : ℚ) : K) = a * b⁻¹ :=
division_ring.rat_cast_mk _ _ _ _
theorem cast_def : ∀ (r : ℚ), (r : K) = r.num / r.denom
| ⟨a, b, h1, h2⟩ := (cast_mk' _ _ _ _).trans (div_eq_mul_inv _ _).symm
@[priority 100]
instance smul_division_ring : has_smul ℚ K :=
⟨division_ring.qsmul⟩
lemma smul_def (a : ℚ) (x : K) : a • x = ↑a * x := division_ring.qsmul_eq_mul' a x
end rat
end division_ring
section field
variable [field K]
@[priority 100] -- see Note [lower instance priority]
instance field.to_semifield : semifield K :=
{ .. ‹field K›, .. (infer_instance : semiring K) }
end field
section is_field
/-- A predicate to express that a (semi)ring is a (semi)field.
This is mainly useful because such a predicate does not contain data,
and can therefore be easily transported along ring isomorphisms.
Additionaly, this is useful when trying to prove that
a particular ring structure extends to a (semi)field. -/
structure is_field (R : Type u) [semiring R] : Prop :=
(exists_pair_ne : ∃ (x y : R), x ≠ y)
(mul_comm : ∀ (x y : R), x * y = y * x)
(mul_inv_cancel : ∀ {a : R}, a ≠ 0 → ∃ b, a * b = 1)
/-- Transferring from `semifield` to `is_field`. -/
lemma semifield.to_is_field (R : Type u) [semifield R] : is_field R :=
{ mul_inv_cancel := λ a ha, ⟨a⁻¹, mul_inv_cancel ha⟩,
..‹semifield R› }
/-- Transferring from `field` to `is_field`. -/
lemma field.to_is_field (R : Type u) [field R] : is_field R := semifield.to_is_field _
@[simp] lemma is_field.nontrivial {R : Type u} [semiring R] (h : is_field R) : nontrivial R :=
⟨h.exists_pair_ne⟩
@[simp] lemma not_is_field_of_subsingleton (R : Type u) [semiring R] [subsingleton R] :
¬is_field R :=
λ h, let ⟨x, y, h⟩ := h.exists_pair_ne in h (subsingleton.elim _ _)
open_locale classical
/-- Transferring from `is_field` to `semifield`. -/
noncomputable def is_field.to_semifield {R : Type u} [semiring R] (h : is_field R) : semifield R :=
{ inv := λ a, if ha : a = 0 then 0 else classical.some (is_field.mul_inv_cancel h ha),
inv_zero := dif_pos rfl,
mul_inv_cancel := λ a ha,
begin
convert classical.some_spec (is_field.mul_inv_cancel h ha),
exact dif_neg ha
end,
.. ‹semiring R›, ..h }
/-- Transferring from `is_field` to `field`. -/
noncomputable def is_field.to_field {R : Type u} [ring R] (h : is_field R) : field R :=
{ .. ‹ring R›, ..is_field.to_semifield h }
/-- For each field, and for each nonzero element of said field, there is a unique inverse.
Since `is_field` doesn't remember the data of an `inv` function and as such,
a lemma that there is a unique inverse could be useful.
-/
lemma uniq_inv_of_is_field (R : Type u) [ring R] (hf : is_field R) :
∀ (x : R), x ≠ 0 → ∃! (y : R), x * y = 1 :=
begin
intros x hx,
apply exists_unique_of_exists_of_unique,
{ exact hf.mul_inv_cancel hx },
{ intros y z hxy hxz,
calc y = y * (x * z) : by rw [hxz, mul_one]
... = (x * y) * z : by rw [← mul_assoc, hf.mul_comm y x]
... = z : by rw [hxy, one_mul] }
end
end is_field
|
#ifndef VEXCL_SPARSE_CSR_HPP
#define VEXCL_SPARSE_CSR_HPP
/*
The MIT License
Copyright (c) 2012-2018 Denis Demidov <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/**
* \file vexcl/sparse/csr.hpp
* \author Denis Demidov <[email protected]>
* \brief Sparse matrix in CSR format.
*/
#include <vector>
#include <type_traits>
#include <utility>
#include <boost/range.hpp>
#include <vexcl/util.hpp>
#include <vexcl/operations.hpp>
#include <vexcl/sparse/product.hpp>
#include <vexcl/sparse/spmv_ops.hpp>
namespace vex {
namespace sparse {
template <typename Val, typename Col = int, typename Ptr = Col>
class csr {
public:
typedef Val value_type;
typedef Val val_type;
typedef Col col_type;
typedef Ptr ptr_type;
template <class PtrRange, class ColRange, class ValRange>
csr(
const std::vector<backend::command_queue> &q,
size_t nrows, size_t ncols,
const PtrRange &ptr,
const ColRange &col,
const ValRange &val,
bool /*fast_setup*/ = true
)
: q(q[0]), n(nrows), m(ncols), nnz(boost::size(val)),
ptr(q[0], boost::size(ptr), boost::size(ptr) ? &ptr[0] : nullptr),
col(q[0], boost::size(col), boost::size(col) ? &col[0] : nullptr),
val(q[0], boost::size(val), boost::size(val) ? &val[0] : nullptr)
{
precondition(q.size() == 1,
"sparse::csr is only supported for single-device contexts");
}
// Dummy matrix; used internally to pass empty parameters to kernels.
csr(const backend::command_queue &q)
: q(q), n(0), m(0), nnz(0)
{}
template <class Expr>
friend
typename std::enable_if<
boost::proto::matches<
typename boost::proto::result_of::as_expr<Expr>::type,
vector_expr_grammar
>::value,
matrix_vector_product<csr, Expr>
>::type
operator*(const csr &A, const Expr &x) {
return matrix_vector_product<csr, Expr>(A, x);
}
template <class Vector>
static void terminal_preamble(const Vector &x, backend::source_generator &src,
const backend::command_queue &q, const std::string &prm_name,
detail::kernel_generator_state_ptr state)
{
detail::output_terminal_preamble tp(src, q, prm_name + "_x", state);
boost::proto::eval(boost::proto::as_child(x), tp);
}
template <class Vector>
static void local_terminal_init(const Vector &x, backend::source_generator &src,
const backend::command_queue &q, const std::string &prm_name,
detail::kernel_generator_state_ptr state)
{
typedef typename detail::return_type<Vector>::type x_type;
typedef spmv_ops_impl<Val, x_type> spmv_ops;
spmv_ops::decl_accum_var(src, prm_name + "_sum");
src.new_line() << "if (" << prm_name << "_ptr)";
src.open("{");
src.new_line() << type_name<Ptr>() << " row_beg = " << prm_name << "_ptr[idx];";
src.new_line() << type_name<Ptr>() << " row_end = " << prm_name << "_ptr[idx+1];";
src.new_line() << "for(" << type_name<Ptr>() << " j = row_beg; j < row_end; ++j)";
src.open("{");
src.new_line() << type_name<Col>() << " idx = " << prm_name << "_col[j];";
detail::output_local_preamble init_x(src, q, prm_name + "_x", state);
boost::proto::eval(boost::proto::as_child(x), init_x);
backend::source_generator vec_value;
detail::vector_expr_context expr_x(vec_value, q, prm_name + "_x", state);
boost::proto::eval(boost::proto::as_child(x), expr_x);
spmv_ops::append_product(src, prm_name + "_sum", prm_name + "_val[j]", vec_value.str());
src << ";";
src.close("}");
src.close("}");
}
template <class Vector>
static void kernel_param_declaration(const Vector &x, backend::source_generator &src,
const backend::command_queue &q, const std::string &prm_name,
detail::kernel_generator_state_ptr state)
{
src.parameter< global_ptr<Ptr> >(prm_name + "_ptr");
src.parameter< global_ptr<Col> >(prm_name + "_col");
src.parameter< global_ptr<Val> >(prm_name + "_val");
detail::declare_expression_parameter decl_x(src, q, prm_name + "_x", state);
detail::extract_terminals()(boost::proto::as_child(x), decl_x);
}
template <class Vector>
static void partial_vector_expr(const Vector &, backend::source_generator &src,
const backend::command_queue&, const std::string &prm_name,
detail::kernel_generator_state_ptr)
{
src << prm_name << "_sum";
}
template <class Vector>
void kernel_arg_setter(const Vector &x,
backend::kernel &kernel, unsigned part, size_t index_offset,
detail::kernel_generator_state_ptr state) const
{
if (nnz) {
kernel.push_arg(ptr);
kernel.push_arg(col);
kernel.push_arg(val);
} else {
kernel.push_arg(static_cast<size_t>(0));
kernel.push_arg(static_cast<size_t>(0));
kernel.push_arg(static_cast<size_t>(0));
}
detail::set_expression_argument x_args(kernel, part, index_offset, state);
detail::extract_terminals()( boost::proto::as_child(x), x_args);
}
template <class Vector>
void expression_properties(const Vector &x,
std::vector<backend::command_queue> &queue_list,
std::vector<size_t> &partition,
size_t &size) const
{
queue_list = std::vector<backend::command_queue>(1, q);
partition = std::vector<size_t>(2, 0);
partition.back() = size = n;
}
size_t rows() const { return n; }
size_t cols() const { return m; }
size_t nonzeros() const { return nnz; }
private:
backend::command_queue q;
size_t n, m, nnz;
backend::device_vector<Ptr> ptr;
backend::device_vector<Col> col;
backend::device_vector<Val> val;
};
} // namespace sparse
} // namespace vex
#endif
|
I'm helping a winery create an online payment form for their wine club. People would be able to sign up for the wine club online and submit their credit card information to be processed manually using the POS system at the winery itself. So we don't need any sort of payment processor, just to be able to store the credit card information to process later.
I had already created a form to do this. Actually, two. They are named "Roaring River Vineyards Wine Club" and "Roaring River Vineyards Wine Club Form."
I'm trying to access the submissions but it is asking me for a private key, which, as I can tell, would have downloaded to my computer at the time of creating the form. I don't remember anything downloading or seeing instructions on what to do with it at the time and that key is long gone from my downloads folder.
1) How can I access those submissions to be able to add those people to the wine club?
2) Is the form we're using the best option for what we're trying to accomplish?
|
input := FileTools:-Text:-ReadFile("AoC-2021-16-input.txt" ):
binstr2dec := proc(b) convert(parse(b),decimal,2) end proc:
hex2bits := proc(input) uses StringTools; local tmp := Explode(input); Join(subs([
"0" = "0000", "1" = "0001", "2" = "0010", "3" = "0011", "4" = "0100",
"5" = "0101", "6" = "0110", "7" = "0111", "8" = "1000", "9" = "1001",
"A" = "1010", "B" = "1011", "C" = "1100", "D" = "1101", "E" = "1110", "F" = "1111"],
tmp),""); end proc:
processpacket := proc( bitinput )
local vertotal, ver, pid, rest, parts, lofbits, subpak, numpaks,
n, val, theops, thevalue;
if length(bitinput) < 6 then
error "error %1 is too short to be valid", bininput;
end if;
PRINT("Processing %d bits", length(bitinput));
ver := binstr2dec(bitinput[1..3]);
pid := binstr2dec(bitinput[4..6]);
rest := bitinput[7..];
vertotal := ver;
if pid = 4 then # literal
PRINT("processing literal");
parts := NULL;
while rest[1] <> "0" do
parts := parts, rest[2..5];
rest := rest[6..];
end do;
parts := parts, rest[2..5];
thevalue := binstr2dec(cat(parts));
PRINT("literal had %d parts with value=%d", nops([parts]), thevalue);
rest := rest[6..];
PRINT("after literal %d bits left", length(rest));
else
PRINT("processing operator ID=%d", pid);
theops := NULL;
if rest[1] = "0" then
lofbits := binstr2dec(rest[2..16]);
PRINT("type-0 operator with %d bits of subpackets", lofbits);
rest := rest[17..];
subpak := rest[1..lofbits];
while length(subpak) > 6 do
(n, val, subpak) := thisproc(subpak);
vertotal += n;
theops := theops, val;
end do;
rest := rest[lofbits+1..];
PRINT("after type-0 %d bits left", length(rest));
else
numpaks := binstr2dec(rest[2..12]);
PRINT("type-1 operator with %d subpackets",numpaks);
rest := rest[13..];
to numpaks do
(n, val, rest) := thisproc(rest);
theops := theops, val;
vertotal += n;
end do;
PRINT("after type-1 %d bits left", length(rest));
end if;
if pid = 0 then thevalue := `+`(theops);
elif pid = 1 then thevalue := `*`(theops);
elif pid = 2 then thevalue := min(theops);
elif pid = 3 then thevalue := max(theops);
elif pid = 5 then thevalue := ifelse( theops[1] > theops[2], 1, 0);
elif pid = 6 then thevalue := ifelse( theops[1] < theops[2], 1, 0);
elif pid = 7 then thevalue := ifelse( theops[1] = theops[2], 1, 0);
else error "bad operator pid";
end if;
end if;
PRINT("returning with %d bits left", length(rest));
return vertotal, thevalue, rest;
end proc:
# uncomment for verbose output
#PRINT := s->printf(cat(s,"\n"), _rest);
(*
# unit tests
processpacket( hex2bits("C200B40A82") )[2]=3;
processpacket( hex2bits("04005AC33890") )[2]=54;
processpacket( hex2bits("880086C3E88112"))[2]=7;
processpacket( hex2bits( "CE00C43D881120" ) )[2]=9;
processpacket( hex2bits( "D8005AC2A8F0" ))[2]=1;
processpacket( hex2bits("F600BC2D8F") )[2]=0;
processpacket( hex2bits("9C005AC2F8F0") )[2] = 0;
processpacket( hex2bits("9C0141080250320F1802104A08"))[2] = 1;
*)
# answers
(answer1, answer2, fluff) := processpacket( hex2bits( input ) ):
answer1;
answer2;
|
[STATEMENT]
lemma retract_of_closed:
fixes S :: "'a :: t2_space set"
shows "\<lbrakk>closed T; S retract_of T\<rbrakk> \<Longrightarrow> closed S"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>closed T; S retract_of T\<rbrakk> \<Longrightarrow> closed S
[PROOF STEP]
by (metis closedin_retract closedin_closed_eq)
|
(* Title: HOL/Auth/n_mutualEx_lemma_on_inv__2.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
*)
theory n_mutualEx_lemma_on_inv__2 imports n_mutualEx_base
begin
section{*All lemmas on causal relation between inv__2 and some rule r*}
lemma n_TryVsinv__2:
assumes a1: "(\<exists> i. i\<le>N\<and>r=n_Try i)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__2 p__Inv4)"
shows "invHoldForRule Interp s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain i where a1:"i\<le>N\<and>r=n_Try i" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__2 p__Inv4" apply fastforce done
have "(i=p__Inv4)\<or>(i~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(i=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule Interp s f r (invariants N)" by auto
}
moreover {
assume b1: "(i~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule Interp s f r (invariants N)" by auto
}
ultimately show "invHoldForRule Interp s f r (invariants N)" by satx
qed
lemma n_CritVsinv__2:
assumes a1: "(\<exists> i. i\<le>N\<and>r=n_Crit i)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__2 p__Inv4)"
shows "invHoldForRule Interp s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain i where a1:"i\<le>N\<and>r=n_Crit i" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__2 p__Inv4" apply fastforce done
have "(i=p__Inv4)\<or>(i~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(i=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule Interp s f r (invariants N)" by auto
}
moreover {
assume b1: "(i~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule Interp s f r (invariants N)" by auto
}
ultimately show "invHoldForRule Interp s f r (invariants N)" by satx
qed
lemma n_ExitVsinv__2:
assumes a1: "(\<exists> i. i\<le>N\<and>r=n_Exit i)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__2 p__Inv4)"
shows "invHoldForRule Interp s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain i where a1:"i\<le>N\<and>r=n_Exit i" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__2 p__Inv4" apply fastforce done
have "(i=p__Inv4)\<or>(i~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(i=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule Interp s f r (invariants N)" by auto
}
moreover {
assume b1: "(i~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule Interp s f r (invariants N)" by auto
}
ultimately show "invHoldForRule Interp s f r (invariants N)" by satx
qed
lemma n_IdleVsinv__2:
assumes a1: "(\<exists> i. i\<le>N\<and>r=n_Idle i)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__2 p__Inv4)"
shows "invHoldForRule Interp s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain i where a1:"i\<le>N\<and>r=n_Idle i" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__2 p__Inv4" apply fastforce done
have "(i=p__Inv4)\<or>(i~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(i=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule Interp s f r (invariants N)" by auto
}
moreover {
assume b1: "(i~=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Para (Ident ''n'') p__Inv4)) (Const C)) (eqn (IVar (Para (Ident ''n'') i)) (Const E))))" in exI, auto) done
then have "invHoldForRule Interp s f r (invariants N)" by auto
}
ultimately show "invHoldForRule Interp s f r (invariants N)" by satx
qed
end
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Friggeri Resume/CV
% XeLaTeX Template
% Version 1.2 (3/5/15)
%
% This template has been downloaded from:
% http://www.LaTeXTemplates.com
%
% Original author:
% Adrien Friggeri ([email protected])
% https://github.com/afriggeri/CV
%
% License:
% CC BY-NC-SA 3.0 (http://creativecommons.org/licenses/by-nc-sa/3.0/)
%
% Important notes:
% This template needs to be compiled with XeLaTeX and the bibliography, if used,
% needs to be compiled with biber rather than bibtex.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\documentclass[]{friggeri-cv} % Add 'print' as an option into the square bracket to remove colors from this template for printing
% \addbibresource{bibliography.bib} % Specify the bibliography file to include publications
\begin{document}
\header{Simon Christian}{ Kr\"{u}ger}{Competence Lead \& Solutions Architect}
%----------------------------------------------------------------------------------------
% SIDEBAR SECTION
%----------------------------------------------------------------------------------------
\begin{aside} % In the aside, each new line forces a line break
\section{contact}
Kistlerhofstraße 157
Munich, 81379
(Bavaria) Germany
~
+49 (0) 170 88 78 345
~
github: \href{https://github.com/kayoslab}{kayoslab}
stack overflow: \href{https://stackoverflow.com/story/cr0ss}{cr0ss}
web: \href{https://cr0ss.org/}{cr0ss.org}
mail: \href{mailto:[email protected]}{hello [at] cr0ss.org}
~
\section{languages}
german, mother tongue
english, fluent
% \section{programming}
% {\color{red} $\varheartsuit$} Swift,
% Software Architecture,
% Python
% \section{management}
% Agile project management,
% project leadership,
% team leadership
\end{aside}
%----------------------------------------------------------------------------------------
% WORK EXPERIENCE SECTION
%----------------------------------------------------------------------------------------
\section{Work experience}
%------------------------------------------------
\begin{entrylist}
\entry
{2019--today}
{intive GmbH}
{Competence Lead}
{Direct management of developers, creating personal development plans, setting target agreements, promotion handling, interviews and hiring recommendations}
%------------------------------------------------
\entry
{2019--today}
{intive\_kupferwerk GmbH}
{Senior software engineer \& Solutions architect}
{Leading development roles, technical consultancy, architectural decision making, pitch preparation and execution, mentoring of junior developers}
%------------------------------------------------
\entry
{2015--today}
{Kayos UG (haftungsbeschr\"{a}nkt)}
{Founder and CEO}
{Client acquisition, financial negotiations, business administration, consultancy, development}
%------------------------------------------------
\entry
{2013--2014}
{Prosthetic Dentistry lab Kreber}
{Distributor}
{Client communication, medical deliveries}
%------------------------------------------------
\entry
{2011}
{Medienfabrik G\"{u}tersloh GmbH, part of arvato: a Bertelsmann company}
{Trainee}
{Software engineering, Mobile and web applications, Client-Server infrastructure}
%------------------------------------------------
\entry
{2010-2011}
{KaLa Autotechnik GmbH}
{Trainee}
{Accounting and controlling, Strategy}
%------------------------------------------------
\entry
{2010}
{Medienfabrik G\"{u}tersloh GmbH, part of arvato: a Bertelsmann company}
{Trainee}
{IT systems support, Linux and OS X administration, Email attachment server}
%------------------------------------------------
\end{entrylist}
%----------------------------------------------------------------------------------------
% EDUCATION SECTION
%----------------------------------------------------------------------------------------
\section{Education}
\subsection{university}
\begin{entrylist}
\entry
{2015--today}
{Fachhochschule Bielefeld}
{Bielefeld}
{Bachelor of Science, Business Administration and Computer Science}
%------------------------------------------------
\entry
{2011--2014}
{Hochschule Trier, Trier University of Applied Science}
{Trier}
{Bachelor of Science, Computer Science: Secure and Mobile Systems}
%------------------------------------------------
\end{entrylist}
\subsection{school}
\begin{entrylist}
\entry
{2008--2011}
{Reinhard Mohn Berufskolleg, focus Math and Computer Science}
{G\"{u}tersloh}
{Commercial high school, qualification for admission to a technical college}
%------------------------------------------------
\entry
{2003--2008}
{Elly-Heuss-Knapp-Schule, St\"{a}dt. Realschule G\"{u}tersloh}
{G\"{u}tersloh}
{General Certificate of Secondary Education (GCSE)}
%------------------------------------------------
\end{entrylist}
\pagebreak
%----------------------------------------------------------------------------------------
% Projects
%----------------------------------------------------------------------------------------
\section{Projects}
\begin{entrylist}
\entry
{2020 - today}
{Deichmann (MVP) - Development lead}
{intive GmbH}
{Global multi language e-commerce application with strong focus on omnichannel functionalities; Coordination of the development team, design driven process with ongoing requirements engineering, architectural decisions in alignment with existing hybris infrastructure and legacy APIs, consultancy regarding technologies their reliability and performance, supporting developers throughout the whole implementation.}
%------------------------------------------------
\entry
{2019 - 2020}
{adidas (MVP) - Mobile development lead}
{intive GmbH}
{Branded customer facing bluetooth product in cooperation with Google ATAP and EA Sports; Coordinating a team of developers and QA, close collaboration with lead developers in global cross-company setup and changing requirements. Supporting the client for a roll out in 25 countries and taking over product ownership support. Strong focus on representing the client in technical decisions and preparation of roadmaps.}
%------------------------------------------------
\entry
{2019}
{BMW (MVP) - Mobile development lead}
{intive GmbH}
{Employee facing application for accessing the car rental pool, providing a feedback and incident report channel for test drivers in pre-production automobiles; Architectural decisions for mobile and backend development, implementing a deployment infrastructure and consulting developers throughout the implementation process.}
%------------------------------------------------
\entry
{2017-2018}
{Esprit - Development lead}
{intive GmbH}
{Global multi language e-commerce application; Providing architectural consulting, supporting a globally acting team of mobile and backend developers, and implementing the mobile application in a constantly changing environment. Focus on requirements engineering and expectation management as the point of contact for the client.}
%------------------------------------------------
\entry
{2015--2018}
{PlugFinder - Development and Consulting}
{Kayos UG (haftungsbeschr\"{a}ankt)}
{Leading data provider for the european charging infrastructure; Responsible for migration from Objective-C to Swift, integration into the existing ecosystem and consulting the client for future development.}
%------------------------------------------------
\end{entrylist}
%----------------------------------------------------------------------------------------
% SKILLS SECTION
%----------------------------------------------------------------------------------------
\section{Skills}
\begin{entrylist}
%------------------------------------------------
\smallentry
{Expert}
{Mobile app development, (Swift, Objective-C), Version Control systems (GIT, SVN), Dependency management systems (Carthage, CocoaPods, SPM), Solutions architecture, Requirements engineering, Scrum methodology (roles, artifacts, ceremonies)}
%------------------------------------------------
\smallentry
{Advanced}
{Business process modelling (UML, BPMN, S-BPMN, EPC), Python, Django, Java, SQL, Bash, API design (Swagger, OpenAPI), Software Architecture (MVVM, MVC, VIPER, CLEAN-Architecture), Agile methodologies (Kanban, XP, Design Thinking), Goal-setting (OKRs, MBO)}
%------------------------------------------------
\smallentry
{Intermediate}
{ABAP, Android development (Java, Kotlin), cross platform development (Dart), Ruby, Machine learning (TensorFlow, Keras, PyTorch, OpenCV, Pandas, Numpy), Scaled agile methodologies (SAFe, LeSS, Nexus)}
%------------------------------------------------
\end{entrylist}
\pagebreak
%----------------------------------------------------------------------------------------
% AWARDS SECTION
%----------------------------------------------------------------------------------------
\section{Awards}
\begin{entrylist}
%------------------------------------------------
\entry
{2017}
{Professional Scrum Master (PSM I)}
{Certificate}
{Scrum.org}
%------------------------------------------------
\entry
{2016}
{ABAP Developer}
{Certificate}
{Fachhochschule Bielefeld}
%------------------------------------------------
\entry
{2014}
{Specialist for application development of software systems}
{Certificate}
{Hochschule Trier, Trier University of Applied Science}
%------------------------------------------------
\end{entrylist}
%----------------------------------------------------------------------------------------
% commitment SECTION
%----------------------------------------------------------------------------------------
\section{Commitment}
\begin{entrylist}
%------------------------------------------------
\entry
{2010--today}
{Voluntary member in registered society Crossnight e.V.}
{}
{Organisation and performance: events for alternative music and culture}
\entry
{2014--2016}
{IT-council, person in charge at Westf\"{a}lischer Golf-Club G\"{u}tersloh e.V.}
{}
{Organisation and implementation of digitalization process}
%------------------------------------------------
\entry
{2012--2014}
{Member of the faculty council}
{}
{faculty of computer science, Hochschule Trier}
%------------------------------------------------
\entry
{2011--2013}
{Treasurer of the faculty}
{}
{faculty of computer science, Hochschule Trier}
%------------------------------------------------
\end{entrylist}
%----------------------------------------------------------------------------------------
% INTERESTS SECTION
%----------------------------------------------------------------------------------------
\section{Interests}
\begin{entrylist}
\smallentry
{professional}
{videography, directing, cooking, coffee making}
\smallentry
{personal}
{bouldering, literature, yoga, scuba-diving, sailing, hiking}
\end{entrylist}
%----------------------------------------------------------------------------------------
% PUBLICATIONS SECTION
%----------------------------------------------------------------------------------------
%\section{publications}
%\printbibsection{article}{article in peer-reviewed journal} % Print all articles from the bibliography
%\printbibsection{book}{books} % Print all books from the bibliography
%\begin{refsection} % This is a custom heading for those references marked as "inproceedings" but not containing "keyword=france"
%\nocite{*}
%\printbibliography[sorting=chronological, type=inproceedings, title={international peer-reviewed conferences/proceedings}, notkeyword={france}, heading=bibheading]
%\end{refsection}
%\begin{refsection} % This is a custom heading for those references marked as "inproceedings" and containing "keyword=france"
%\nocite{*}
%\printbibliography[sorting=chronological, type=inproceedings, title={local peer-reviewed conferences/proceedings}, keyword={france}, heading=bibheading]
%\end{refsection}
%\printbibsection{misc}{other publications} % Print all miscellaneous entries from the bibliography
%\printbibsection{report}{research reports} % Print all research reports from the bibliography
%----------------------------------------------------------------------------------------
\end{document}
|
Law in Beaconsfield will take the time to listen to your concerns and explain all your options to ensure the best possible outcome.
We believe it’s important that you know your rights from the word go, especially with regards to your children and finances. Based in Beaconsfield, our dedicated family law solicitors can provide one-to-one support while handling your case with the utmost care and discretion.
Family law is a sensitive area, which is why we have hand selected a specialist team of lawyers in Beaconsfield to deliver a first-class legal service to local couples and families in need. Of course, we also appreciate how emotional family issues can be, and offer a personal approach to make the legal process as smooth and stress-free as possible.
To find a solution that’s right for both you and your family, call us on 01753 325100 or send us an email at [email protected].
|
/-
The complex numbers.
A documented remix of part of mathlib
Our goal is to define the complex numbers, and then "extract some API".
Our first goal is to define addition and multiplication,
and prove that the complex numbers are a commutative ring.
We then do a slightly more computer-sciency worked development of the
natural inclusion from the reals to the complexes.
There are then a bunch of exercises, which can be solved in term mode
or tactic mode. .
a lot of stuff we don't need for this one precise result. As an appendix
We leave as exercises
the API extraction for the stuff we skipped, namely the following
complex conjugation and the norm function.
-/
-- We will assume that the real numbers are a field.
import data.real.basic
/-- A complex number is defined to be a structure consisting of two real numbers,
the real part and the imaginary part of the complex number . -/
structure complex : Type :=
(re : ℝ) (im : ℝ)
-- Let's use the usual notation for the complex numbers
notation `ℂ` := complex
-- You make the complex number with real part 3 and imaginary part 4 like this:
example : ℂ :=
{ re := 3,
im := 4 }
-- Or like this:
example : ℂ := complex.mk 3 4
-- or like this:
example : ℂ := ⟨3, 4⟩
-- They all give the same complex number.
-- If you have a complex number, then you can get its real and
-- imaginary parts with the `complex.re` and `complex.im` functions.
example : ℝ := complex.re(complex.mk 3 4) -- this term is (3 : ℝ)
example : complex.re(complex.mk 3 4) = 3 := rfl -- true by definition.
-- We clearly don't want to be constantly saying `complex.blah` so let's
-- move into the `complex` namespace
namespace complex
-- All our theorems and definitions will now be called complex.something,
-- and we can in general just drop `complex.`
-- For example
example : re(mk 3 4) = 3 := rfl
-- Computer scientists prefer the style `z.re` to `re(z)` for some reason.
example : (mk 3 4).re = 3 := rfl
example (z : ℂ) : re(z) = z.re := rfl
-- We now prove the basic theorems and make the basic definitions for
-- complex numbers. For example, we will define addition and multiplication on
-- the complex numbers, and prove that it is a commutative ring.
/-! # Mathematical trivialities -/
-- We start with some facts about complex numbers which are so obvious that we do not
-- often explicitly state them. The first is that if z is a complex number, then
-- the complex number with real part re(z) and imaginary part im(z) is equal to z.
-- This is called eta reduction in type theory. Let's work through the
-- simple tactic mode proof.
example : ∀ z : ℂ, complex.mk z.re z.im = z :=
begin
intro z,
cases z with x y,
-- goal now looks complicated, and contains terms which look
-- like {re := a, im := b}.re which obviously simplify to a.
-- The `dsimp` tactic will do some tidying up for us, although
-- it is not logically necessary. `dsimp` does definitional simplification.
dsimp,
-- Now we see the goal can be solved by reflexivity
refl,
end
-- The proof was "unfold everything, and it's true by definition".
-- This proof does not teach a mathematician anything, so we may as well write
-- it in term mode, because each tactic has a term equivalent.
-- The equation compiler does the `intro` and `cases` steps,
-- and `dsimp` was unnecessary -- the two sides of the equation
-- were definitionally equal.
-- It's important we give this theorem a name, because we want `simp`
-- to be able to use it. In short, the `simp` tactic tries to solve
-- goals of the form A = B, when `refl` doesn't work (i.e. the goals are
-- not definitionally equal) but when any mathematician would be able
-- to simplify A and B via "obvious" steps such as `0 + x = x` or
-- `⟨z.re, z.im⟩ = z`. These things are sometimes not true by definition,
-- but they should be tagged as being well-known ways to simplify an equality.
-- When building our API for the complex numbers, if we prove a theorem of the
-- form `A = B` where `B` is a bit simpler than `A`, we should probably
-- tag it with the `@[simp]` attribute, so `simp` can use it.
-- Note: `simp` does *not* prove "all simple things". It proves *equalities*.
-- It proves `A = B` when, and only when, it can do it by applying
-- its "simplification rules", where a simplification rule is simply a proof
-- of a theorem of the form `A = B` and `B` is simpler than `A`.
@[simp] theorem eta : ∀ z : ℂ, complex.mk z.re z.im = z
| ⟨x, y⟩ := rfl
-- The second triviality is the assertion that two complex numbers
-- with the same and imaginary parts are equal. Again this is not
-- hard to prove, and mathematicians deem it not worth documenting.
example (z w : ℂ) : z.re = w.re → z.im = w.im → z = w :=
begin
cases z with zr zi,
cases w,
intros, cc,
end
-- This lemma is called extensionality by type theorists.
-- Here is another tactic mode proof. Note that we have moved
-- the z and w to the other side of the colon; this does not
-- change the fully expanded proof term. It shows the power
-- of the `rintros` tactic.
example : ∀ z w : ℂ, z.re = w.re → z.im = w.im → z = w :=
begin
rintros ⟨zr, zi⟩ ⟨_, _⟩ ⟨rfl⟩ ⟨rfl⟩,
refl,
end
-- `rintros` does `cases` as many times as you like using this cool `⟨, ⟩` syntax
-- for the case splits. Note that if you do cases on `h : a = b` then, because
-- `=` is notation for `eq`, an inductive type with one constructor `a = a`,
-- it will just delete `b` and change all `b`s to `a`s. That is one of the
-- things going on in the above proof.
-- Here is the same proof in term mode. Even though it's obvious, we still
-- give it a name, namely `ext`. It's important to prove it, so we can
-- tag it with the `ext` attribute. If we do this, the `ext` tactic can use it.
-- The `ext` tactic applies all theorems of the form "two
-- objects are the same if they are made from the same pieces".
@[ext]
theorem ext : ∀ {z w : ℂ}, z.re = w.re → z.im = w.im → z = w
| ⟨zr, zi⟩ ⟨_, _⟩ rfl rfl := rfl
-- The theorem `complex.ext` is trivially true to a mathematician.
-- But it is often used: for example it will be used all the time
-- in our proof that the complex numbers are a ring.
-- Note that `ext` is an implication -- if re(z)=re(w) and im(z)=im(w) then z=w.
-- The below variant `ext_iff` is the two-way implication: two complex
-- numbers are equal if and only if they have the same real and imaginary part.
-- Let's first see a tactic mode proof. See how the `ext` tactic is used?
-- After it is applied, we have two goals, both of which are hypotheses.
-- The semicolon means "apply the next tactic to all the goals produced by this one"
example (z w : ℂ) : z = w ↔ z.re = w.re ∧ z.im = w.im :=
begin
split,
{ intro H,
simp [H]},
{
rintro ⟨hre, him⟩,
ext; assumption,
}
end
-- Again this is easy to write in term mode, and no mathematician
-- wants to read the proof anyway.
theorem ext_iff {z w : ℂ} : z = w ↔ z.re = w.re ∧ z.im = w.im :=
⟨λ H, by simp [H], and.rec ext⟩
/-! # Main course: the complex numbers are a ring. -/
-- Our goal is to prove that the complexes are a ring. Let's
-- define the structure first; the zero, one, addition and multiplication
-- on the complexes.
/-! ## 0 -/
-- Let's define the zero complex number. Once we have done this we will be
-- able to talk about (0 : ℂ).
/-- notation: `0`, or (0 : ℂ), will mean the complex number with
real and imaginary part equal to (0 : ℝ). -/
instance : has_zero ℂ := ⟨⟨0, 0⟩⟩
-- Let's prove its basic properties, all of which are true by definition,
-- and then tag them with the appropriate attributes.
@[simp] lemma zero_re : (0 : ℂ).re = 0 := rfl
@[simp] lemma zero_im : (0 : ℂ).im = 0 := rfl
/-! ## 1 -/
-- Now let's do the same thing for 1.
/-- Notation `1` or `(1 : ℂ)`, means `⟨(1 : ℝ), (0 : ℝ)⟩`. -/
instance : has_one ℂ := ⟨⟨1, 0⟩⟩
-- name basic properties and tag them appropriately
@[simp] lemma one_re : (1 : ℂ).re = 1 := rfl
@[simp] lemma one_im : (1 : ℂ).im = 0 := rfl
/-! ## + -/
-- Now let's define addition
/-- Notation `+` for usual addition of complex numbers-/
instance : has_add ℂ := ⟨λ z w, ⟨z.re + w.re, z.im + w.im⟩⟩
-- and state and tag its basic properties. We want to prove
-- theorems like $$a(b+c)=ab+ac$$ by checking on real and
-- imaginary parts, so we need to teach the simplifier
-- these tricks.
@[simp] lemma add_re (z w : ℂ) : (z + w).re = z.re + w.re := rfl
@[simp] lemma add_im (z w : ℂ) : (z + w).im = z.im + w.im := rfl
instance : has_neg ℂ := ⟨λ z, ⟨-z.re, -z.im⟩⟩
@[simp] lemma neg_re (z : ℂ) : (-z).re = -z.re := rfl
@[simp] lemma neg_im (z : ℂ) : (-z).im = -z.im := rfl
instance : has_mul ℂ := ⟨λ z w, ⟨z.re * w.re - z.im * w.im, z.re * w.im + z.im * w.re⟩⟩
@[simp] lemma mul_re (z w : ℂ) : (z * w).re = z.re * w.re - z.im * w.im := rfl
@[simp] lemma mul_im (z w : ℂ) : (z * w).im = z.re * w.im + z.im * w.re := rfl
/-! ## Example of what `simp` can now do -/
example (a b c : ℂ) : re(a*(b+c)) = re(a) * (re(b) + re(c)) - im(a) * (im(b) + im(c)) :=
begin
simp,
end
/-! # Theorem: The complex numbers are a commutative ring -/
-- Proof: we've defined all the structure, and every axiom can be checked by reducing it
-- to checking real and imaginary parts with `ext`, expanding everything out with `simp`
-- and then using the fact that the real numbers are a ring.
instance : comm_ring ℂ :=
by refine { zero := 0, add := (+), neg := has_neg.neg, one := 1, mul := (*), ..};
{ intros, apply ext_iff.2; split; simp; ring }
-- That is the end of the proof that the complexes form a ring. We built
-- a basic API which was honed towards the general idea that to prove
-- certain statements about the complex numbers, for example distributivity,
-- we could just check on real and imaginary parts. We trained the `simp`
-- lemma to simplify every
/-! # Coercion
A worked example of how coercions work from the reals to the complexes.
-/
-- Let's define a "canonical" map from ℝ to ℂ. Instead of making it a definition, we will
-- make it a coercion instance, which means that if `(r : ℝ)` is a real
-- number, then `(r : ℂ)` or `(↑r : ℂ)` will indicate the corresponding
-- complex number with no imaginary part
/-- The coercion from ℝ to ℂ sending `r` to the complex number `⟨r, 0⟩` -/
instance : has_coe ℝ ℂ := ⟨λ r, ⟨r, 0⟩⟩
-- The concept of the complex number associated
-- to a real number `r` is a new definition, so we had better formulate its basic
-- properties immediately, namely what its real and imaginary parts are,
-- and their basic behaviour. Here are two properties, both true by definition.
-- We name them because we want to tag them.
@[simp, norm_cast] lemma of_real_re (r : ℝ) : (r : ℂ).re = r := rfl
@[simp, norm_cast] lemma of_real_im (r : ℝ) : (r : ℂ).im = 0 := rfl
-- The `simp` tactic will now simplify `re(↑r)` to `r` and `im(↑r)` to `0`
-- and the `norm_cast` tactic might help you if you have proved a general
-- equality about complex numbers but you want it to be about real numbers,
-- or vice-versa.
-- The map from the reals to the complexes is injective, something we
-- write in iff form so `simp` can use it; `simp` also works on `iff` goals.
@[simp, norm_cast] theorem of_real_inj {z w : ℝ} : (z : ℂ) = w ↔ z = w :=
⟨congr_arg re, congr_arg _⟩
-- We now go through all our basic constants, namely 0, 1, + and *,
-- and tell the simplifier how they behave with respect to this new function.
/-! ## 0 -/
@[simp, norm_cast] lemma of_real_zero : ((0 : ℝ) : ℂ) = 0 := rfl
@[simp] theorem of_real_eq_zero {z : ℝ} : (z : ℂ) = 0 ↔ z = 0 := of_real_inj
theorem of_real_ne_zero {z : ℝ} : (z : ℂ) ≠ 0 ↔ z ≠ 0 := not_congr of_real_eq_zero
/-! ## 1 -/
@[simp, norm_cast] lemma of_real_one : ((1 : ℝ) : ℂ) = 1 := rfl
/-! ## + -/
-- TODO: some crazy bug? in Lean is sometimes stopping me from
-- uncommenting the following example and then putting
-- some code after it. Probably the commit before this one.
-- It is a theorem that the canonical map from ℝ to ℂ commutes with addition.
-- We should prove this and tag it appropriately.
example (r s : ℝ) : ((r + s : ℝ) : ℂ) = r + s :=
begin
-- goal: to prove two complex numbers are equal.
ext,
-- goal: to prove that their real and imaginary
-- parts are equal.
{ -- real part
simp},
{ -- imaginary part
simp},
end
-- Here's the term mode version. It's not true by definition, but `ext` and `simp` solve it.
@[simp, norm_cast] lemma of_real_add (r s : ℝ) : ((r + s : ℝ) : ℂ) = r + s := ext_iff.2 $ by simp
/-! ## - -/
@[simp, norm_cast] lemma of_real_neg (r : ℝ) : ((-r : ℝ) : ℂ) = -r := ext_iff.2 $ by simp
/-! ## * -/
@[simp, norm_cast] lemma of_real_mul (r s : ℝ) : ((r * s : ℝ) : ℂ) = r * s := ext_iff.2 $ by simp
/-! ## Example `simp` usage -/
-- examples of the power of `simp` now. Change to -- `by squeeze_simp` to see which
-- lemmas `simp` uses
lemma smul_re (r : ℝ) (z : ℂ) : (↑r * z).re = r * z.re := by simp -- or by squeeze_simp
lemma smul_im (r : ℝ) (z : ℂ) : (↑r * z).im = r * z.im := by simp -- or by squeeze_simp
/-! ## Numerals
Feel free to skip 15 lines down to `I` if you are a mathematician.
These last two are to do with the canonical map from numerals into the complexes, e.g. `(23 : ℂ)`.
Lean stores the numeral in binary. See for example
set_option pp.numerals false
#check (37 : ℂ)-- bit1 (bit0 (bit1 (bit0 (bit0 has_one.one)))) : ℂ
-/
@[simp, norm_cast] lemma of_real_bit0 (r : ℝ) : ((bit0 r : ℝ) : ℂ) = bit0 r := ext_iff.2 $ by simp [bit0]
@[simp, norm_cast] lemma of_real_bit1 (r : ℝ) : ((bit1 r : ℝ) : ℂ) = bit1 r := ext_iff.2 $ by simp [bit1]
-- I find it unbelievable that we have written 331 lines of code about the complex numbers
-- and we've still never defined i, or j, or I, or $$\sqrt{-1}$$, or whatever it's called.
-- Why don't you try this one?
/-! # I -/
-- TODO: leave definition, sorry all proofs.
/-- complex.I is the square root of -1 above the imaginary axis -/
def I : ℂ := ⟨0, 1⟩
@[simp] lemma I_re : I.re = 0 := rfl
@[simp] lemma I_im : I.im = 1 := rfl
@[simp] lemma I_mul_I : I * I = -1 := ext_iff.2 $ by simp
lemma I_ne_zero : (I : ℂ) ≠ 0 := mt (congr_arg im) zero_ne_one.symm
lemma mk_eq_add_mul_I (a b : ℝ) : complex.mk a b = a + b * I :=
ext_iff.2 $ by simp
@[simp] lemma re_add_im (z : ℂ) : (z.re : ℂ) + z.im * I = z :=
ext_iff.2 $ by simp
/-! # Complex conjugation -/
-- TODO: leave definition, sorry all proofs.
def conj (z : ℂ) : ℂ := ⟨z.re, -z.im⟩
@[simp] lemma conj_re (z : ℂ) : (conj z).re = z.re := rfl
@[simp] lemma conj_im (z : ℂ) : (conj z).im = -z.im := rfl
@[simp] lemma conj_of_real (r : ℝ) : conj r = r := ext_iff.2 $ by simp [conj]
@[simp] lemma conj_zero : conj 0 = 0 := ext_iff.2 $ by simp [conj]
@[simp] lemma conj_one : conj 1 = 1 := ext_iff.2 $ by simp
@[simp] lemma conj_I : conj I = -I := ext_iff.2 $ by simp
@[simp] lemma conj_add (z w : ℂ) : conj (z + w) = conj z + conj w :=
ext_iff.2 $ by simp [add_comm]
@[simp] lemma conj_neg (z : ℂ) : conj (-z) = -conj z := rfl
@[simp] lemma conj_neg_I : conj (-I) = I := ext_iff.2 $ by simp
@[simp] lemma conj_mul (z w : ℂ) : conj (z * w) = conj z * conj w :=
ext_iff.2 $ by simp [add_comm]
@[simp] lemma conj_conj (z : ℂ) : conj (conj z) = z :=
ext_iff.2 $ by simp
lemma conj_involutive : function.involutive conj := conj_conj
lemma conj_bijective : function.bijective conj := conj_involutive.bijective
lemma conj_inj {z w : ℂ} : conj z = conj w ↔ z = w :=
conj_bijective.1.eq_iff
@[simp] lemma conj_eq_zero {z : ℂ} : conj z = 0 ↔ z = 0 :=
by simpa using @conj_inj z 0
lemma eq_conj_iff_real {z : ℂ} : conj z = z ↔ ∃ r : ℝ, z = r :=
⟨λ h, ⟨z.re, ext rfl $ eq_zero_of_neg_eq (congr_arg im h)⟩,
λ ⟨h, e⟩, e.symm ▸ rfl⟩
lemma eq_conj_iff_re {z : ℂ} : conj z = z ↔ (z.re : ℂ) = z :=
eq_conj_iff_real.trans ⟨by rintro ⟨r, rfl⟩; simp, λ h, ⟨_, h.symm⟩⟩
theorem add_conj (z : ℂ) : z + conj z = (2 * z.re : ℝ) :=
ext_iff.2 $ by simp [two_mul]
/-- the ring homomorphism complex conjugation -/
def Conj : ℂ →+* ℂ :=
{ to_fun := conj,
map_one' := begin ext; simp, end,
map_mul' := begin intros, ext; simp end,
map_zero' := begin ext; simp end,
map_add' := begin intros, ext; simp end}
/-! # Norms -/
-- TODO: leave definition, sorry all proofs.
def norm_sq (z : ℂ) : ℝ := z.re * z.re + z.im * z.im
@[simp] lemma norm_sq_of_real (r : ℝ) : norm_sq r = r * r :=
by simp [norm_sq]
@[simp] lemma norm_sq_zero : norm_sq 0 = 0 := by simp [norm_sq]
@[simp] lemma norm_sq_one : norm_sq 1 = 1 := by simp [norm_sq]
@[simp] lemma norm_sq_I : norm_sq I = 1 := by simp [norm_sq]
lemma norm_sq_nonneg (z : ℂ) : 0 ≤ norm_sq z :=
add_nonneg (mul_self_nonneg _) (mul_self_nonneg _)
@[simp] lemma norm_sq_eq_zero {z : ℂ} : norm_sq z = 0 ↔ z = 0 :=
⟨λ h, ext
(eq_zero_of_mul_self_add_mul_self_eq_zero h)
(eq_zero_of_mul_self_add_mul_self_eq_zero $ (add_comm _ _).trans h),
λ h, h.symm ▸ norm_sq_zero⟩
@[simp] lemma norm_sq_pos {z : ℂ} : 0 < norm_sq z ↔ z ≠ 0 :=
by rw [lt_iff_le_and_ne, ne, eq_comm]; simp [norm_sq_nonneg]
@[simp] lemma norm_sq_neg (z : ℂ) : norm_sq (-z) = norm_sq z :=
by simp [norm_sq]
@[simp] lemma norm_sq_conj (z : ℂ) : norm_sq (conj z) = norm_sq z :=
by simp [norm_sq]
@[simp] lemma norm_sq_mul (z w : ℂ) : norm_sq (z * w) = norm_sq z * norm_sq w :=
by dsimp [norm_sq]; ring
lemma norm_sq_add (z w : ℂ) : norm_sq (z + w) =
norm_sq z + norm_sq w + 2 * (z * conj w).re :=
by dsimp [norm_sq]; ring
lemma re_sq_le_norm_sq (z : ℂ) : z.re * z.re ≤ norm_sq z :=
le_add_of_nonneg_right (mul_self_nonneg _)
lemma im_sq_le_norm_sq (z : ℂ) : z.im * z.im ≤ norm_sq z :=
le_add_of_nonneg_left (mul_self_nonneg _)
theorem mul_conj (z : ℂ) : z * conj z = norm_sq z :=
ext_iff.2 $ by simp [norm_sq, mul_comm, sub_eq_neg_add, add_comm]
end complex
|
"""
Generic rewrite of CODA for set-based state representations.
"""
import numpy as np
from functools import reduce
from itertools import combinations, chain
from scipy.sparse.csgraph import connected_components
from mrl.utils.misc import batch_block_diag, batch_block_diag_many
import random
import copy
import multiprocessing as mp
FETCH_HEURISTIC_IDXS = [[0,1,2], [10,11,12], [22,23,24], [34,35,36], [46,47,47], [58,59,60], [70,71,72]]
def get_true_abstract_mask_spriteworld(sprites, config, action=(0.5, 0.5)):
"""Returns a mask with iteractions for next transition given true sprites.
E.g., returns [[1,0,0],[0,1,0],[0,0,1]] for 3 sprites"""
sprites1 = copy.deepcopy(sprites)
config['action_space'].step(action, sprites1)
return config['renderers']['mask_abstract'].render(sprites1)
def batch_get_heuristic_mask_fetchpush_(s, a):
""" heuristic mask for disentangled fetch """
grip_poses = s[:, 0, :3]
obj_poses = s[:, 1, 10:13]
entangled = np.linalg.norm(grip_poses - obj_poses, axis=1, keepdims=True)[:, None] < 0.1
entangled_mask = np.ones((1, 3, 3))
disentangled_mask = np.array([[[1, 0, 1], [0, 1, 0], [1, 0, 1]]])
return np.where(entangled, entangled_mask, disentangled_mask)
def batch_get_heuristic_mask_fetchpush(s, a):
poses = np.stack([s[:, i, h] for i, h in enumerate(FETCH_HEURISTIC_IDXS[:s.shape[1]])], 1) # batch x n_state_comps x 3
dists = np.linalg.norm(poses[:,None] - poses[:,:,None], axis = -1) # batch x n_state_comps x n_state_comps
entangled = (dists < 0.1).astype(np.float32)
entangled = np.pad(entangled, ((0, 0), (0, 1), (0, 1))) # add action dim
entangled[:,-1, 0] = 1. # entangle action with gripper
return entangled
def get_default_mask(s, a):
""" assumes set-based s and a... so shape should be (n_componenents, *component_shape) """
if len(a.shape) == 1:
a.reshape(1, -1)
mask_dim = len(s) + len(a)
mask_shape = (mask_dim, mask_dim)
return np.ones(mask_shape)
def batch_get_default_mask(s, a):
""" Batch version of get default mask """
s_shape = s.shape
a_shape = a.shape
if len(a_shape) == 2:
assert len(a_shape) > 1
a.reshape(-1, 1, a_shape[-1])
mask_dim = s_shape[1] + a_shape[1]
mask_shape = (s_shape[0], mask_dim, mask_dim)
return np.ones(mask_shape)
def get_cc_from_mask(mask):
"""
Converts a mask into a list of CC indices tuples.
E.g., if mask is [[1,0,0,0],[0,1,0,0],[0,0,1,1],[0,0,1,1]],
this will return [array([0]), array([1]), array([2, 3])]
Note that the mask should be a square, so in case we have (s, a) x (s2,),
we should first dummy a2 columns to form a square mask.
"""
ccs = connected_components(mask)
num_ccs, cc_idxs = ccs
return [np.where(cc_idxs == i)[0] for i in range(num_ccs)]
def powerset(n):
xs = list(range(n))
return list(chain.from_iterable(combinations(xs, n) for n in range(n + 1)))
def reduce_cc_list_by_union(cc_list, max_ccs):
"""Takes a cc list that is too long and merges some components to bring it
to max_ccs"""
while len(cc_list) > max_ccs:
i, j = np.random.choice(range(1, len(cc_list) - 1), 2, replace=False)
if (j == 0) or (j == len(cc_list) - 1):
continue # don't want to delete the base
cc_list[i] = np.union1d(cc_list[i], cc_list[j])
del cc_list[j]
return cc_list
def disentangled_components(cc_lst):
"""Converts connected component list into a list of disentangled subsets
of the indices.
"""
subsets = powerset(len(cc_lst))
res = []
for subset in subsets:
res.append(reduce(np.union1d, [cc_lst[i] for i in subset], np.array([])).astype(np.int64))
return set(map(tuple, res))
def get_dcs_from_mask(mask, max_ccs = 6):
cc = get_cc_from_mask(mask)
return disentangled_components(reduce_cc_list_by_union(cc, max_ccs))
def transitions_and_masks_to_proposals(t1,
t2,
m1,
m2,
max_samples=10,
max_ccs=6):
"""
assumes set-based s and a... so shape should be (n_components, *component_shape)
Takes two transitions with their masks, and combines them
using connected-component relabeling to form proposals
Returns a list of tuples of ((s1, a1, s2) proposal, disconnected_component_idxs).
"""
sa1, s21 = t1
sa2, s22 = t2
# get_dcs_from_mask should return a set of tuples of indices, inc. the empty tuple
# where the subgraph represented by each tuple is disconnected from the result of
# the graph. Note that mask should be square, so columns corresp. to action idxs are
# dummy columns.
#
# E.g., if mask is [[1,0,0,0],[0,1,0,0],[0,0,1,1],[0,0,1,1]],
# this function should return:
# set([ (,), (0,), (1,), (0,1), (2, 3), (0, 2, 3), (1, 2, 3), (0, 1, 2, 3) ])
dc1 = get_dcs_from_mask(m1, max_ccs)
dc2 = get_dcs_from_mask(m2, max_ccs)
# get shared connected components in random order
shared_dc = list(dc1.intersection(dc2))
random.shuffle(shared_dc)
# subsample shared_dc down to max_samples
if len(shared_dc) > max_samples:
shared_dc = shared_dc[:max_samples]
all_idxs = set(range(len(sa1)))
res = []
for dc in shared_dc:
not_dc = list(all_idxs - set(dc))
dc = list(dc) # (0, 2)
proposed_sa = np.zeros_like(sa1)
proposed_s2 = np.zeros_like(sa1)
proposed_sa[dc] = sa1[dc]
proposed_sa[not_dc] = sa2[not_dc]
proposed_s2[dc] = s21[dc]
proposed_s2[not_dc] = s22[not_dc]
proposed_t = (proposed_sa, proposed_s2)
res.append((proposed_t, tuple(dc)))
return res
def relabel_independent_transitions_spriteworld(t1,
sprites1,
t2,
sprites2,
config,
reward_fn=lambda _: 0,
total_samples=10,
flattened=True,
custom_get_mask=None,
max_ccs=6):
"""
Same as old fn, but using new refactored bits -- to make sure it works
"""
assert flattened
s1_1, a_1, _, s2_1 = t1
s1_2, a_2, _, s2_2 = t2
num_sprites = len(sprites1)
num_feats = len(s1_1) // num_sprites
t1 = (batch_block_diag(s1_1.reshape(num_sprites, num_feats), a_1.reshape(1, -1)),
batch_block_diag(s2_1.reshape(num_sprites, num_feats), a_1.reshape(1, -1)))
t2 = (batch_block_diag(s1_2.reshape(num_sprites, num_feats), a_2.reshape(1, -1)),
batch_block_diag(s2_2.reshape(num_sprites, num_feats), a_2.reshape(1, -1)))
m1 = custom_get_mask(sprites1, config, a_1)
m2 = custom_get_mask(sprites2, config, a_2)
proposals_and_dcs = transitions_and_masks_to_proposals(t1, t2, m1, m2, total_samples, max_ccs)
res = []
psprites = copy.deepcopy(sprites2)
for proposal, dc in proposals_and_dcs:
psa1, psa2 = proposal
ps1 = psa1[:-1]
pa = psa1[-1:]
ps2 = psa2[:-1]
action_idx = len(ps1)
for idx in dc:
if idx != action_idx:
psprites[idx] = copy.deepcopy(sprites1[idx])
# Now we also need to check if the proposal is valid
pm = custom_get_mask(psprites, config, pa[0, num_feats:])
pcc = get_cc_from_mask(pm)
pdc = disentangled_components(pcc)
if tuple(dc) in pdc:
res.append(( ps1[:, :num_feats].flatten(),
pa[0, num_feats:],
reward_fn(ps2[:, :num_feats].flatten()),
ps2[:, :num_feats].flatten() ))
return res
def relabel_spriteworld(args):
return relabel_independent_transitions_spriteworld(*args)
def relabel_generic(args):
return transitions_and_masks_to_proposals(*args)
def enlarge_dataset_spriteworld(data, sprites, config, num_pairs, relabel_samples_per_pair, flattened=True,
custom_get_mask=None, pool=True, max_cpus=16):
data_len = len(data)
all_idx_pairs = np.array(np.meshgrid(np.arange(data_len), np.arange(data_len))).T.reshape(-1, 2)
chosen_idx_pairs_idxs = np.random.choice(len(all_idx_pairs), num_pairs)
chosen_idx_pairs = all_idx_pairs[chosen_idx_pairs_idxs]
reward_fn = config['task'].reward_of_vector_repr
config = {
'action_space': copy.deepcopy(config['action_space']),
'renderers': {
'mask': copy.deepcopy(config['renderers']['mask']),
'mask_abstract': copy.deepcopy(config['renderers']['mask_abstract'])
}
}
args = []
for (i, j) in chosen_idx_pairs:
args.append(
(data[i], sprites[i], data[j], sprites[j], config, reward_fn, relabel_samples_per_pair, flattened, custom_get_mask))
if pool:
with mp.Pool(min(mp.cpu_count() - 1, max_cpus)) as pool:
reses = pool.map(relabel_spriteworld, args)
else:
reses = [relabel_spriteworld(_args) for _args in args]
reses = sum(reses, [])
return reses
def enlarge_dataset_generic(states, actions, next_states, num_pairs, relabel_samples_per_pair,
batch_get_mask=batch_get_heuristic_mask_fetchpush, pool=True, max_cpus=16, add_bad_dcs=False):
"""
This does random coda on generic data, using the following types:
Inputs:
states, next_states: [batch, n_components, state_feats] # NOTE: assumes 1d state feats
actions: [batch, action_feats] or [batch, n_components, action_feats]
custom_get_mask: (batch_states, batched_actions) -> [batch_dim, state_feats + action_feats, state_feats + action_feats]
Returns:
(new_states, new_actions, new_next_states) with same shapes as inputs (except batch_dim)
"""
if pool:
mp_pool = mp.Pool(min(mp.cpu_count() - 1, max_cpus))
map_fn = mp_pool.map
else:
map_fn = map
data_len, n_state_components, n_state_feats = states.shape
squeeze_on_return = False
if len(actions.shape) == 2:
n_action_components = 1
squeeze_on_return = True
actions = actions[:, None]
else:
n_action_components = actions.shape[1]
masks = batch_get_mask(states, actions)
assert masks.shape[1] == masks.shape[2] == n_state_components + n_action_components
bad_dcs = set([(), tuple(list(range(n_state_components + n_action_components)))])
Is = np.random.randint(data_len, size=(num_pairs,))
Js = np.random.randint(data_len, size=(num_pairs,))
t1s = list(zip(batch_block_diag(states[Is], actions[Is]), batch_block_diag(next_states[Is], actions[Is])))
t2s = list(zip(batch_block_diag(states[Js], actions[Js]), batch_block_diag(next_states[Js], actions[Js])))
m1s = masks[Is]
m2s = masks[Js]
args = [(t1, t2, m1, m2, relabel_samples_per_pair) for t1, t2, m1, m2 in zip(t1s, t2s, m1s, m2s)]
proposals_and_dcs = map_fn(relabel_generic, args)
proposals_and_dcs = sum(proposals_and_dcs, []) # [((sa1, sa2), dc), ... ]
new_s1s = []
new_a1s = []
new_s2s = []
dcs = []
for (sa1, sa2), dc in proposals_and_dcs:
if (not add_bad_dcs) and (dc in bad_dcs):
continue
new_s1s.append(sa1[:n_state_components, :n_state_feats])
new_a1s.append(sa1[n_state_components:, n_state_feats:])
new_s2s.append(sa2[:n_state_components, :n_state_feats])
dcs.append(dc)
new_s1s = np.array(new_s1s)
new_a1s = np.array(new_a1s)
new_s2s = np.array(new_s2s)
if not len(new_s1s):
if pool:
mp_pool.close()
mp_pool.join()
return (new_s1s, new_a1s, new_s2s)
masks = batch_get_mask(new_s1s, new_a1s)
pdcs = map_fn(get_dcs_from_mask, masks)
# Now verify that proposals are valid
valid_idxs = []
for i, (pdc, dc) in enumerate(zip(pdcs, dcs)):
if dc in pdc:
valid_idxs.append(i)
new_s1s = new_s1s[valid_idxs]
new_a1s = new_a1s[valid_idxs]
new_s2s = new_s2s[valid_idxs]
if squeeze_on_return:
new_a1s = new_a1s.squeeze(1)
if pool:
mp_pool.close()
mp_pool.join()
return (new_s1s, new_a1s, new_s2s)
|
# This file was generated, do not modify it. # hide
lgb = LGBMRegressor() #initialised a model with default params
lgbm = machine(lgb, features[train, :], targets[train, 1])
boostrange = range(lgb, :num_iterations, lower=2, upper=500)
curve = learning_curve!(lgbm, resampling=CV(nfolds=5),
range=boostrange, resolution=100,
measure=rms)
figure(figsize=(8,6))
plot(curve.parameter_values, curve.measurements)
xlabel("Number of rounds", fontsize=14)
ylabel("RMSE", fontsize=14)
plt.savefig(joinpath(@OUTPUT, "lgbm_hp1.svg")) # hide
|
c
c =================================================
function stream(x,y,z)
c =================================================
c
c # stream function defining the velocity.
c # (x,y,z) is a point on the sphere.
c # rotation about an axis through 0 and (xaxis,yaxis,zaxis)
implicit double precision (a-h,o-z)
common /comaxis/ xaxis,yaxis,zaxis
stream = x*xaxis + y*yaxis + z*zaxis
c
return
end
|
% Fig. 5.38 Feedback Control of Dynamic Systems, 5e
% Franklin, Powell, Emami
clf
numG = 160*conv ([1 2.5],[1 0.7]);
denG = conv([1 5 40],[1 .03 .06]);
sysG = tf(numG,denG);
sysD=tf([1 3],[1 20]);
sysDG=sysD*sysG;
K = 0.3;
sysH=tf(1,1);
sysT = feedback (K*sysG,sysH);
sysTD=feedback(sysDG,sysH);
step(sysT)
hold on
step(sysTD)
grid on
title('Step responses of auto-pilot with P and lead control')
hold off
|
function [g1, g2] = simwhiteXrbfinfwhiteKernGradient(simKern, rbfKern, t1, varargin)
% SIMWHITEXRBFINFWHITEKERNGRADIENT Compute a cross gradient between a
% SIM-WHITE kernel and an RBF-WHITE kernel (with integration limits between
% minus infinity and infinity).
% FORMAT
% DESC computes cross gradient of parameters of a cross kernel between a
% SIM-WHITE and an RBF-WHITE kernels for the multiple output kernel.
% ARG simKern : the kernel structure associated with the SIM-WHITE kernel.
% ARG rbfKern : the kernel structure associated with the RBF-WHITE kernel.
% ARG t1 : inputs for which kernel is to be computed.
% ARG covGrad : gradient of the objective function with respect to
% the elements of the cross kernel matrix.
% RETURN g1 : gradient of the parameters of the SIM-WHITE kernel, for
% ordering see simwhiteKernExtractParam.
% RETURN g2 : gradient of the parameters of the RBF-WHITE kernel, for
% ordering see rbfwhiteKernExtractParam.
%
% FORMAT
% DESC computes cross kernel terms between a SIM-WHITE kernel and an
% RBF-WHITE kernel (with integration limits between minus infinity and
% infinity) for the multiple output kernel.
% ARG simKern : the kernel structure associated with the SIM-WHITE kernel.
% ARG rbfKern : the kernel structure associated with the RBF-WHITE kernel.
% ARG t1 : row inputs for which kernel is to be computed.
% ARG t2 : column inputs for which kernel is to be computed.
% ARG covGrad : gradient of the objective function with respect to
% the elements of the cross kernel matrix.
% RETURN g1 : gradient of the parameters of the SIM-WHITE kernel, for
% ordering see simwhiteKernExtractParam.
% RETURN g2 : gradient of the parameters of the RBF-WHITE kernel, for
% ordering see rbfwhiteKernExtractParam.
%
% SEEALSO : multiKernParamInit, multiKernCompute, simwhiteKernParamInit,
% rbfinfwhiteKernParamInit, simwhiteKernExtractParam, rbfinfwhiteKernExtractParam
%
% COPYRIGHT : David Luengo, 2009
% KERN
if nargin < 5
t2 = t1;
else
t2 = varargin{1};
end
covGrad = varargin{end};
if size(t1, 2) > 1 | size(t2, 2) > 1
error('Input can only have one column');
end
if simKern.variance ~= rbfKern.variance
error('Kernels cannot be cross combined if they have different variances.')
end
g1 = zeros(1, simKern.nParams);
g2 = zeros(1, rbfKern.nParams);
T1 = repmat(t1, 1, size(t2, 1));
T2 = repmat(t2.', size(t1, 1), 1);
deltaT = T1 - T2;
% Parameters required for further computations
isStationary = simKern.isStationary;
variance = simKern.variance;
decay = simKern.decay;
sensitivity = simKern.sensitivity;
invWidth = rbfKern.inverseWidth;
% Setting normalised parameters for computation of K
simKern.variance = 1;
rbfKern.variance = 1;
simKern.sensitivity = 1;
K = simwhiteXrbfinfwhiteKernCompute(simKern, rbfKern, t1, t2);
% Gradient w.r.t. the decay (simKern)
g1(1) = variance * sensitivity * sum(sum( ...
((decay/invWidth-deltaT) .* K + 1/sqrt(2*pi*invWidth) ...
* (exp(-(decay*T1+0.5*invWidth*(T2.^2))) * (~isStationary) ...
- exp(-0.5*invWidth*(deltaT.^2)))) ...
.* covGrad));
% * exp(0.5*(decay^2)/invWidth-decay*deltaT) ...
% .* (exp(-0.5*invWidth*((T2+decay/invWidth).^2)) * (~isStationary) ...
% - exp(-0.5*invWidth*((deltaT-decay/invWidth).^2)))) ...
% Gradient w.r.t. the inverse width (rbfKern)
g2(1) = 0.5 * variance * sensitivity * sum(sum( ...
((-(decay/invWidth)^2) * K + 1/sqrt(2*pi*invWidth) ...
* ((T2-decay/invWidth) .* exp(-(decay*T1+0.5*invWidth*(T2.^2))) * (~isStationary) ...
+ (deltaT+decay/invWidth) .* exp(-0.5*invWidth*(deltaT.^2)))) ...
.* covGrad));
% * exp(0.5*(decay^2)/invWidth - decay*deltaT) ...
% .* ((T2-decay/invWidth) .* exp(-0.5*invWidth*((T2+decay/invWidth).^2)) * (~isStationary) ...
% + (deltaT+decay/invWidth) .* exp(-0.5*invWidth*((deltaT-decay/invWidth).^2)))) ...
% Gradient w.r.t. sigma_r^2
g1(2) = sensitivity * sum(sum(K .* covGrad));
g2(2) = 0; % Otherwise it is counted twice
% Gradient w.r.t. sensitivity (only simKern)
g1(3) = variance * sum(sum(K .* covGrad));
|
(* Title: HOL/Auth/n_flash_lemma_on_inv__142.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 Protocol Case Study*}
theory n_flash_lemma_on_inv__142 imports n_flash_base
begin
section{*All lemmas on causal relation between inv__142 and some rule r*}
lemma n_NI_Local_Get_Put_HeadVsinv__142:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src)" and
a2: "(f=inv__142 )"
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
have "?P3 s"
apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''Cmd'')) (Const SHWB_FAck)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Pending'')) (Const false))))" in exI, auto) done
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_Remote_Get_PutVsinv__142:
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: "(f=inv__142 )"
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
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_Local_GetX_PutX_1Vsinv__142:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src)" and
a2: "(f=inv__142 )"
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
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_Local_GetX_PutX_2Vsinv__142:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src)" and
a2: "(f=inv__142 )"
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
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_Local_GetX_PutX_3Vsinv__142:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src)" and
a2: "(f=inv__142 )"
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
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_Local_GetX_PutX_4Vsinv__142:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src)" and
a2: "(f=inv__142 )"
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
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_Local_GetX_PutX_5Vsinv__142:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src)" and
a2: "(f=inv__142 )"
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
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_Local_GetX_PutX_6Vsinv__142:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src)" and
a2: "(f=inv__142 )"
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
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_Local_GetX_PutX_7__part__0Vsinv__142:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src)" and
a2: "(f=inv__142 )"
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
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_Local_GetX_PutX_7__part__1Vsinv__142:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src)" and
a2: "(f=inv__142 )"
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
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__0Vsinv__142:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src)" and
a2: "(f=inv__142 )"
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
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__1Vsinv__142:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src)" and
a2: "(f=inv__142 )"
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
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_Local_GetX_PutX_8_HomeVsinv__142:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src)" and
a2: "(f=inv__142 )"
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
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_Local_GetX_PutX_8_Home_NODE_GetVsinv__142:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src)" and
a2: "(f=inv__142 )"
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
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_Local_GetX_PutX_8Vsinv__142:
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: "(f=inv__142 )"
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
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_Local_GetX_PutX_8_NODE_GetVsinv__142:
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: "(f=inv__142 )"
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
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_Local_GetX_PutX_9__part__0Vsinv__142:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src)" and
a2: "(f=inv__142 )"
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
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_Local_GetX_PutX_9__part__1Vsinv__142:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src)" and
a2: "(f=inv__142 )"
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
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_Local_GetX_PutX_10_HomeVsinv__142:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src)" and
a2: "(f=inv__142 )"
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
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_Local_GetX_PutX_10Vsinv__142:
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: "(f=inv__142 )"
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
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_Local_GetX_PutX_11Vsinv__142:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src)" and
a2: "(f=inv__142 )"
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
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_Remote_GetX_PutXVsinv__142:
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: "(f=inv__142 )"
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
have "?P3 s"
apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') dst) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))))" in exI, auto) done
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_PI_Local_GetX_PutX_HeadVld__part__0Vsinv__142:
assumes a1: "(r=n_PI_Local_GetX_PutX_HeadVld__part__0 N )" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
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__142:
assumes a1: "(r=n_PI_Local_GetX_PutX_HeadVld__part__1 N )" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_FAckVsinv__142:
assumes a1: "(r=n_NI_FAck )" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
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__142:
assumes a1: "(r=n_NI_ShWb N )" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_Local_Get_Get__part__1Vsinv__142:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_GetX_PutX_HomeVsinv__142:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_PutX_Home dst" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_GetVsinv__142:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_PI_Remote_Get src" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX__part__0Vsinv__142:
assumes a1: "r=n_PI_Local_GetX_PutX__part__0 " and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_WbVsinv__142:
assumes a1: "r=n_NI_Wb " and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_StoreVsinv__142:
assumes a1: "\<exists> src data. src\<le>N\<and>data\<le>N\<and>r=n_Store src data" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_GetX__part__1Vsinv__142:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_3Vsinv__142:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_3 N src" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_1Vsinv__142:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_1 N src" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_GetX__part__1Vsinv__142:
assumes a1: "r=n_PI_Local_GetX_GetX__part__1 " and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_GetX__part__0Vsinv__142:
assumes a1: "r=n_PI_Local_GetX_GetX__part__0 " and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_ReplaceVsinv__142:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_PI_Remote_Replace src" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_Store_HomeVsinv__142:
assumes a1: "\<exists> data. data\<le>N\<and>r=n_Store_Home data" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_ReplaceVsinv__142:
assumes a1: "r=n_PI_Local_Replace " and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_Nak__part__1Vsinv__142:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_Nak__part__1Vsinv__142:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_Get__part__0Vsinv__142:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_existsVsinv__142:
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: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_Nak__part__2Vsinv__142:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_PutXVsinv__142:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_PI_Remote_PutX dst" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_Get_Put_HomeVsinv__142:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Put_Home dst" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvVsinv__142:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Inv dst" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_PutXVsinv__142:
assumes a1: "r=n_PI_Local_PutX " and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_Nak__part__2Vsinv__142:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_GetX__part__0Vsinv__142:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_Get_PutVsinv__142:
assumes a1: "r=n_PI_Local_Get_Put " and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_ReplaceVsinv__142:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Replace src" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_GetX_Nak_HomeVsinv__142:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_Nak_Home dst" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_PutXAcksDoneVsinv__142:
assumes a1: "r=n_NI_Local_PutXAcksDone " and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_GetX_NakVsinv__142:
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: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_NakVsinv__142:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Nak dst" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_GetXVsinv__142:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_PI_Remote_GetX src" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX__part__1Vsinv__142:
assumes a1: "r=n_PI_Local_GetX_PutX__part__1 " and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_Get_Nak_HomeVsinv__142:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Nak_Home dst" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_PutXVsinv__142:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_PutX dst" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_PutVsinv__142:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Put dst" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_PutVsinv__142:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put src" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_Nak__part__0Vsinv__142:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_exists_HomeVsinv__142:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_exists_Home src" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Replace_HomeVsinv__142:
assumes a1: "r=n_NI_Replace_Home " and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_PutVsinv__142:
assumes a1: "r=n_NI_Local_Put " and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_Get_NakVsinv__142:
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: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Nak_ClearVsinv__142:
assumes a1: "r=n_NI_Nak_Clear " and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_Put_DirtyVsinv__142:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_Nak__part__0Vsinv__142:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_Get_GetVsinv__142:
assumes a1: "r=n_PI_Local_Get_Get " and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Nak_HomeVsinv__142:
assumes a1: "r=n_NI_Nak_Home " and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_2Vsinv__142:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_2 N src" and
a2: "(f=inv__142 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
end
|
-- Everything is strictly positive, but Agda doesn't see this.
{-# OPTIONS --no-positivity-check #-}
module Generic.Core where
open import Generic.Lib.Prelude public
infix 4 _≤ℓ_
infixr 5 _⇒_ _⊛_
_≤ℓ_ : Level -> Level -> Set
α ≤ℓ β = α ⊔ β ≡ β
mutual
Binder : ∀ {ι} α β γ -> ArgInfo -> ι ⊔ lsuc (α ⊔ β) ≡ γ -> Set ι -> Set γ
Binder α β γ i q I = Coerce q (∃ λ (A : Set α) -> < relevance i > A -> Desc I β)
data Desc {ι} (I : Set ι) β : Set (ι ⊔ lsuc β) where
var : I -> Desc I β
π : ∀ {α} i
-> (q : α ≤ℓ β)
-> Binder α β _ i (cong (λ αβ -> ι ⊔ lsuc αβ) q) I
-> Desc I β
_⊛_ : Desc I β -> Desc I β -> Desc I β
pattern DPi i A D = π i refl (coerce (A , D))
{-# DISPLAY π i refl (coerce (A , D)) = DPi i A D #-}
pattern explRelDPi A D = DPi explRelInfo A D
pattern explIrrDPi A D = DPi explIrrInfo A D
pattern implRelDPi A D = DPi implRelInfo A D
pattern implIrrDPi A D = DPi implIrrInfo A D
pattern instRelDPi A D = DPi instRelInfo A D
pattern instIrrDPi A D = DPi instIrrInfo A D
{-# DISPLAY DPi explRelInfo A D = explRelDPi A D #-}
{-# DISPLAY DPi explIrrInfo A D = explIrrDPi A D #-}
{-# DISPLAY DPi implRelInfo A D = implRelDPi A D #-}
{-# DISPLAY DPi implIrrInfo A D = implIrrDPi A D #-}
{-# DISPLAY DPi instRelInfo A D = instRelDPi A D #-}
{-# DISPLAY DPi instIrrInfo A D = instIrrDPi A D #-}
_⇒_ : ∀ {ι α β} {I : Set ι} {{q : α ≤ℓ β}} -> Set α -> Desc I β -> Desc I β
_⇒_ {{q}} A D = π (explRelInfo) q (qcoerce (A , λ _ -> D))
mutual
⟦_⟧ : ∀ {ι β} {I : Set ι} -> Desc I β -> (I -> Set β) -> Set β
⟦ var i ⟧ B = B i
⟦ π i q C ⟧ B = ⟦ i / C ⟧ᵇ q B
⟦ D ⊛ E ⟧ B = ⟦ D ⟧ B × ⟦ E ⟧ B
⟦_/_⟧ᵇ : ∀ {α ι β γ q} {I : Set ι} i
-> Binder α β γ i q I -> α ≤ℓ β -> (I -> Set β) -> Set β
⟦ i / coerce (A , D) ⟧ᵇ q B = Coerce′ q $ Pi i A λ x -> ⟦ D x ⟧ B
mutual
Extend : ∀ {ι β} {I : Set ι} -> Desc I β -> (I -> Set β) -> I -> Set β
Extend (var i) B j = Lift _ (i ≡ j)
Extend (π i q C) B j = Extendᵇ i C q B j
Extend (D ⊛ E) B j = ⟦ D ⟧ B × Extend E B j
Extendᵇ : ∀ {ι α β γ q} {I : Set ι} i
-> Binder α β γ i q I -> α ≤ℓ β -> (I -> Set β) -> I -> Set β
Extendᵇ i (coerce (A , D)) q B j = Coerce′ q $ ∃ λ x -> Extend (D x) B j
module _ {ι β} {I : Set ι} (D : Data (Desc I β)) where
mutual
data μ j : Set β where
node : Node D j -> μ j
Node : Data (Desc I β) -> I -> Set β
Node D j = Any (λ C -> Extend C μ j) (consTypes D)
mutual
Cons : ∀ {ι β} {I : Set ι} -> (I -> Set β) -> Desc I β -> Set β
Cons B (var i) = B i
Cons B (π i q C) = Consᵇ B i C q
Cons B (D ⊛ E) = ⟦ D ⟧ B -> Cons B E
Consᵇ : ∀ {ι α β γ q} {I : Set ι}
-> (I -> Set β) -> ∀ i -> Binder α β γ i q I -> α ≤ℓ β -> Set β
Consᵇ B i (coerce (A , D)) q = Coerce′ q $ Pi i A λ x -> Cons B (D x)
cons : ∀ {ι β} {I : Set ι} {D} -> (D₀ : Data (Desc I β)) -> D ∈ consTypes D₀ -> Cons (μ D₀) D
cons {D = D} D₀ p = go D λ e ->
node (mapAny (consTypes D₀) (λ q -> subst (λ E -> Extend E _ _) q e) p) where
mutual
go : ∀ {ι β} {I : Set ι} {B : I -> Set β}
-> (D : Desc I β) -> (∀ {j} -> Extend D B j -> B j) -> Cons B D
go (var i) k = k lrefl
go (π a q C) k = goᵇ a C k
go (D ⊛ E) k = λ x -> go E (k ∘ _,_ x)
goᵇ : ∀ {ι α β γ q q′} {I : Set ι} {B : I -> Set β} i
-> (C : Binder α β γ i q′ I) -> (∀ {j} -> Extendᵇ i C q B j -> B j) -> Consᵇ B i C q
goᵇ {q = q} i (coerce (A , D)) k =
coerce′ q $ lamPi i λ x -> go (D x) (k ∘ coerce′ q ∘ _,_ x)
allCons : ∀ {ι β} {I : Set ι} -> (D : Data (Desc I β)) -> All (Cons (μ D)) (consTypes D)
allCons D = allIn _ (cons D)
node-inj : ∀ {i β} {I : Set i} {D : Data (Desc I β)} {j} {e₁ e₂ : Node D D j}
-> node {D = D} e₁ ≡ node e₂ -> e₁ ≡ e₂
node-inj refl = refl
μ′ : ∀ {β} -> Data (Desc ⊤₀ β) -> Set β
μ′ D = μ D tt
pos : ∀ {β} -> Desc ⊤₀ β
pos = var tt
pattern #₀ p = node (inj₁ p)
pattern #₁ p = node (inj₂ (inj₁ p))
pattern #₂ p = node (inj₂ (inj₂ (inj₁ p)))
pattern #₃ p = node (inj₂ (inj₂ (inj₂ (inj₁ p))))
pattern #₄ p = node (inj₂ (inj₂ (inj₂ (inj₂ (inj₁ p)))))
pattern #₅ p = node (inj₂ (inj₂ (inj₂ (inj₂ (inj₂ (inj₁ p))))))
pattern !#₀ p = node p
pattern !#₁ p = node (inj₂ p)
pattern !#₂ p = node (inj₂ (inj₂ p))
pattern !#₃ p = node (inj₂ (inj₂ (inj₂ p)))
pattern !#₄ p = node (inj₂ (inj₂ (inj₂ (inj₂ p))))
pattern !#₅ p = node (inj₂ (inj₂ (inj₂ (inj₂ (inj₂ p)))))
|
module FFI
import Data.Promise
%default total
promiseIO : (primFn : (String -> PrimIO ()) -> (String -> PrimIO ()) -> PrimIO ()) -> Promise String
promiseIO primFn =
promisify $ \ok,notOk => primFn (\res => toPrim $ ok res) (\err => toPrim $ notOk err)
node_ffi : (libName : String) -> (fnName : String) -> String
node_ffi libName fnName = "node:support:\{fnName},\{libName}"
|
If $f$ is a power series with radius of convergence $r > 0$ and $f(\xi) = 0$, then there exists $s > 0$ such that $f(z) \neq 0$ for all $z \<in> \mathbb{C}$ with $|z - \xi| < s$ and $z \neq \xi$.
|
module CUDAExtensions
using Reexport
@reexport using CUDA
import SpecialFunctions, ForwardDiff, MacroTools
import ForwardDiff.DiffRules
import ForwardDiff: @define_binary_dual_op # required until https://github.com/JuliaDiff/ForwardDiff.jl/pull/491
# Includes
include("utils.jl")
export @cufunc, @cufuncf, @cufunc_register, @cufunc_function
include("functions.jl")
# include("distributions.jl")
# include("forwarddiff.jl")
end
|
(** * MoreCoq: More About Coq *)
Require Export Poly.
Definition list2pair : forall {X:Type} (x:X), list X -> X*bool :=
fun X x list =>
match list with
| [] => (x, false)
| a::_ => (a, true)
end.
Theorem inEqual : forall (x y : nat), [x] = [y] -> x = y.
Proof.
intros.
assert ((x, true) = (y, true)).
apply (f_equal (@list2pair nat x) H).
apply (f_equal fst H0).
Qed.
|
open import Level using () renaming (_⊔_ to _⊔ˡ_)
open import Data.Product using (_,_; proj₁)
open import Data.Sum using (_⊎_; inj₁; inj₂)
open import Relation.Nullary using (yes; no; ¬_)
open import Relation.Nullary.Negation using (contradiction)
open import Relation.Binary using (Reflexive; Symmetric; Transitive; Setoid; Tri)
open Tri
open import Relation.Binary.PropositionalEquality using (_≡_; _≢_) renaming (refl to ≡-refl; sym to ≡-sym)
open import Algebra.Bundles using (RawRing)
open import AKS.Algebra.Bundles using (DecField)
module AKS.Polynomial.Base {c ℓ} (F : DecField c ℓ) where
open import Data.Unit using (⊤; tt)
open import Agda.Builtin.FromNat using (Number)
open import AKS.Nat using (ℕ; _∸_; _≤_; _<_; lte; pred) renaming (_+_ to _+ℕ_; _⊔_ to _⊔ℕ_)
open ℕ
open import AKS.Nat using (≢⇒¬≟; <-cmp; ≤-totalOrder; m<n⇒n∸m≢0)
open import AKS.Nat using (ℕ⁺; ⟅_⇓⟆; ⟅_⇑⟆)
open import AKS.Nat.WellFounded using (Acc; acc; <-well-founded)
open DecField F
using (0#; 1#; _+_; _*_; -_; _-_; _⁻¹; _/_; C/0)
renaming (Carrier to C)
open DecField F using (_≈_; _≈?_; setoid)
open Setoid setoid using (refl; sym; trans)
open DecField F
using (*-commutativeMonoid; 1#-nonzero; -1#-nonzero; _*-nonzero_; _/-nonzero_)
open import AKS.Exponentiation *-commutativeMonoid using (_^_; _^⁺_)
data Spine : Set (c ⊔ˡ ℓ) where
K : C/0 → Spine
_+x^_∙_ : C/0 → ℕ⁺ → Spine → Spine
data Polynomial : Set (c ⊔ˡ ℓ) where
0ᵖ : Polynomial
x^_∙_ : ℕ → Spine → Polynomial
⟦_⟧ˢ : Spine → C → C
⟦ K c ⟧ˢ x = proj₁ c
⟦ c +x^ n ∙ p ⟧ˢ x = proj₁ c + x ^⁺ n * ⟦ p ⟧ˢ x
⟦_⟧ : Polynomial → C → C
⟦ 0ᵖ ⟧ x = 0#
⟦ x^ n ∙ p ⟧ x = x ^ n * ⟦ p ⟧ˢ x
1ᵖ : Polynomial
1ᵖ = x^ 0 ∙ K 1#-nonzero
_+?_ : ∀ (k₁ k₂ : C/0) → (proj₁ k₁ + proj₁ k₂ ≈ 0#) ⊎ C/0
k₁ +? k₂ with proj₁ k₁ + proj₁ k₂ ≈? 0#
... | yes k₁+k₂≈0 = inj₁ k₁+k₂≈0
... | no k₁+k₂≉0 = inj₂ (proj₁ k₁ + proj₁ k₂ , k₁+k₂≉0)
+ᵖ-spine-≡-K : ℕ → C/0 → Spine → Polynomial
+ᵖ-spine-≡-K n c₁ (K c₂) with c₁ +? c₂
... | inj₁ _ = 0ᵖ
... | inj₂ c₁+c₂ = x^ n ∙ K c₁+c₂
+ᵖ-spine-≡-K n c₁ (c₂ +x^ i₂ ∙ q) with c₁ +? c₂
... | inj₁ _ = x^ (n +ℕ ⟅ i₂ ⇓⟆) ∙ q
... | inj₂ c₁+c₂ = x^ n ∙ (c₁+c₂ +x^ i₂ ∙ q)
+ᵖ-spine-≡ : ℕ → Spine → Spine → Polynomial
+ᵖ-spine-< : (n : ℕ) → Spine → (m : ℕ) → Spine → n < m → Polynomial
+ᵖ-spine : ℕ → Spine → ℕ → Spine → Polynomial
+ᵖ-spine-≡ n (K c₁) q = +ᵖ-spine-≡-K n c₁ q
+ᵖ-spine-≡ n (c₁ +x^ i₁ ∙ p) (K c₂) = +ᵖ-spine-≡-K n c₂ (c₁ +x^ i₁ ∙ p)
+ᵖ-spine-≡ n (c₁ +x^ i₁ ∙ p) (c₂ +x^ i₂ ∙ q) with c₁ +? c₂
... | inj₁ _ = +ᵖ-spine (n +ℕ ⟅ i₁ ⇓⟆) p (n +ℕ ⟅ i₂ ⇓⟆) q
... | inj₂ c₁+c₂ with +ᵖ-spine ⟅ i₁ ⇓⟆ p ⟅ i₂ ⇓⟆ q
... | 0ᵖ = x^ n ∙ K c₁+c₂
... | x^ zero ∙ r = +ᵖ-spine-≡-K n c₁+c₂ r
... | x^ suc n₃ ∙ r = x^ n ∙ (c₁+c₂ +x^ ⟅ suc n₃ ⇑⟆ ∙ r)
+ᵖ-spine-< n₁ (K c₁) n₂ q n₁<n₂ = x^ n₁ ∙ (c₁ +x^ ⟅ n₂ ∸ n₁ ⇑⟆ {≢⇒¬≟ (m<n⇒n∸m≢0 n₁<n₂)} ∙ q)
+ᵖ-spine-< n₁ (c₁ +x^ i₁ ∙ p) n₂ q n₁<n₂ with +ᵖ-spine ⟅ i₁ ⇓⟆ p (n₂ ∸ n₁) q
... | 0ᵖ = x^ n₁ ∙ K c₁
... | x^ zero ∙ r = +ᵖ-spine-≡-K n₁ c₁ r
... | x^ suc n₃ ∙ r = x^ n₁ ∙ (c₁ +x^ ⟅ suc n₃ ⇑⟆ ∙ r)
+ᵖ-spine n₁ p n₂ q with <-cmp n₁ n₂
... | tri< n₁<n₂ _ _ = +ᵖ-spine-< n₁ p n₂ q n₁<n₂
... | tri≈ _ n₁≡n₂ _ = +ᵖ-spine-≡ n₁ p q
... | tri> _ _ n₁>n₂ = +ᵖ-spine-< n₂ q n₁ p n₁>n₂
infixl 6 _+ᵖ_
_+ᵖ_ : Polynomial → Polynomial → Polynomial
0ᵖ +ᵖ q = q
(x^ n₁ ∙ p) +ᵖ 0ᵖ = x^ n₁ ∙ p
(x^ n₁ ∙ p) +ᵖ (x^ n₂ ∙ q) = +ᵖ-spine n₁ p n₂ q
_∙𝑋^_ : C/0 → ℕ → Polynomial
c ∙𝑋^ n = x^ n ∙ K c
𝑋^_ : ℕ → Polynomial
𝑋^ n = 1#-nonzero ∙𝑋^ n
𝑋 : Polynomial
𝑋 = 𝑋^ 1
𝐾 : C → Polynomial
𝐾 c with c ≈? 0#
... | yes _ = 0ᵖ
... | no c≉0 = (c , c≉0) ∙𝑋^ 0
∙ᵖ-spine : C/0 → Spine → Spine
∙ᵖ-spine c₁ (K c₂) = K (c₁ *-nonzero c₂)
∙ᵖ-spine c₁ (c₂ +x^ n ∙ p) = (c₁ *-nonzero c₂) +x^ n ∙ (∙ᵖ-spine c₁ p)
infixl 7 _∙ᵖ_
_∙ᵖ_ : C/0 → Polynomial → Polynomial
c ∙ᵖ 0ᵖ = 0ᵖ
c ∙ᵖ (x^ n ∙ p) = x^ n ∙ (∙ᵖ-spine c p)
*ᵖ-spine : ℕ → Spine → ℕ → Spine → Polynomial
*ᵖ-spine o₁ (K c₁) o₂ q = x^ (o₁ +ℕ o₂) ∙ (∙ᵖ-spine c₁ q)
*ᵖ-spine o₁ (c₁ +x^ n₁ ∙ p) o₂ (K c₂) = x^ (o₁ +ℕ o₂) ∙ (∙ᵖ-spine c₂ (c₁ +x^ n₁ ∙ p))
*ᵖ-spine o₁ (c₁ +x^ n₁ ∙ p) o₂ (c₂ +x^ n₂ ∙ q) =
x^ (o₁ +ℕ o₂) ∙ K (c₁ *-nonzero c₂) +ᵖ
c₁ ∙ᵖ x^ (o₁ +ℕ o₂ +ℕ ⟅ n₂ ⇓⟆) ∙ q +ᵖ
c₂ ∙ᵖ (x^ (o₁ +ℕ o₂ +ℕ ⟅ n₁ ⇓⟆) ∙ p) +ᵖ
*ᵖ-spine (o₁ +ℕ ⟅ n₁ ⇓⟆) p (o₂ +ℕ ⟅ n₂ ⇓⟆) q
-- (c₁ + x ^ n₁ * p[x]) * (c₂ + x ^ n₂ * q[x]) = (c₁ * c₂) + (c₁ * x ^ n₂ * q[x]) + (x ^ n₁ * p[x] * c₂) + (x ^ n₁ * p[x] * x ^ n₂ * q[x])
infixl 7 _*ᵖ_
_*ᵖ_ : Polynomial → Polynomial → Polynomial
0ᵖ *ᵖ q = 0ᵖ
(x^ n₁ ∙ p) *ᵖ 0ᵖ = 0ᵖ
(x^ n₁ ∙ p) *ᵖ (x^ n₂ ∙ q) = *ᵖ-spine n₁ p n₂ q
infix 6 -ᵖ_
-ᵖ_ : Polynomial → Polynomial
-ᵖ p = -1#-nonzero ∙ᵖ p
infixl 6 _-ᵖ_
_-ᵖ_ : Polynomial → Polynomial → Polynomial
p -ᵖ q = p +ᵖ (-ᵖ q)
data Polynomialⁱ : Set c where
0ⁱ : Polynomialⁱ
_+x∙_ : C → Polynomialⁱ → Polynomialⁱ
1ⁱ : Polynomialⁱ
1ⁱ = 1# +x∙ 0ⁱ
infixl 6 _+ⁱ_
_+ⁱ_ : Polynomialⁱ → Polynomialⁱ → Polynomialⁱ
0ⁱ +ⁱ q = q
(c₁ +x∙ p) +ⁱ 0ⁱ = c₁ +x∙ p
(c₁ +x∙ p) +ⁱ (c₂ +x∙ q) = (c₁ + c₂) +x∙ (p +ⁱ q)
infixl 7 _∙ⁱ_
_∙ⁱ_ : C → Polynomialⁱ → Polynomialⁱ
a ∙ⁱ 0ⁱ = 0ⁱ
a ∙ⁱ (c +x∙ p) = (a * c) +x∙ (a ∙ⁱ p)
infix 8 x∙_
x∙_ : Polynomialⁱ → Polynomialⁱ
x∙ p = 0# +x∙ p
infixl 7 _*ⁱ_
_*ⁱ_ : Polynomialⁱ → Polynomialⁱ → Polynomialⁱ
0ⁱ *ⁱ q = 0ⁱ
(c₁ +x∙ p) *ⁱ 0ⁱ = 0ⁱ
(c₁ +x∙ p) *ⁱ (c₂ +x∙ q) = (c₁ * c₂) +x∙ (c₁ ∙ⁱ q +ⁱ c₂ ∙ⁱ p +ⁱ x∙ (p *ⁱ q))
-ⁱ_ : Polynomialⁱ → Polynomialⁱ
-ⁱ p = (- 1#) ∙ⁱ p
infixl 6 _-ⁱ_
_-ⁱ_ : Polynomialⁱ → Polynomialⁱ → Polynomialⁱ
p -ⁱ q = p +ⁱ (-ⁱ q)
expandˢ : ℕ → Spine → Polynomialⁱ
expandˢ zero (K c) = proj₁ c +x∙ 0ⁱ
expandˢ zero (c +x^ n ∙ s) = proj₁ c +x∙ expandˢ (pred ⟅ n ⇓⟆) s
expandˢ (suc n) s = 0# +x∙ expandˢ n s
expand : Polynomial → Polynomialⁱ
expand 0ᵖ = 0ⁱ
expand (x^ n ∙ p) = expandˢ n p
constant : C → Polynomial
constant c with c ≈? 0#
... | yes _ = 0ᵖ
... | no c≉0 = (c , c≉0) ∙𝑋^ 0
simplify : Polynomialⁱ → Polynomial
simplify 0ⁱ = 0ᵖ
simplify (c₁ +x∙ p) with c₁ ≈? 0# | simplify p
... | yes _ | 0ᵖ = 0ᵖ
... | yes _ | x^ n ∙ q = x^ suc n ∙ q
... | no c₁≉0 | 0ᵖ = x^ 0 ∙ (K (c₁ , c₁≉0))
... | no c₁≉0 | x^ n ∙ q = x^ 0 ∙ ((c₁ , c₁≉0) +x^ ⟅ suc n ⇑⟆ ∙ q)
data _≈ˢ_ : Spine → Spine → Set (c ⊔ˡ ℓ) where
K≈ : ∀ {c₁ c₂} → proj₁ c₁ ≈ proj₁ c₂ → K c₁ ≈ˢ K c₂
+≈ : ∀ {c₁ c₂} {n₁ n₂} {p q} → proj₁ c₁ ≈ proj₁ c₂ → n₁ ≡ n₂ → p ≈ˢ q → (c₁ +x^ n₁ ∙ p) ≈ˢ (c₂ +x^ n₂ ∙ q)
infix 4 _≈ᵖ_
data _≈ᵖ_ : Polynomial → Polynomial → Set (c ⊔ˡ ℓ) where
0ᵖ≈ : 0ᵖ ≈ᵖ 0ᵖ
0ᵖ≉ : ∀ {o₁ o₂} {p q} → o₁ ≡ o₂ → p ≈ˢ q → x^ o₁ ∙ p ≈ᵖ x^ o₂ ∙ q
infix 4 _≉ᵖ_
_≉ᵖ_ : Polynomial → Polynomial → Set (c ⊔ˡ ℓ)
p ≉ᵖ q = ¬ (p ≈ᵖ q)
≈ᵖ-refl : Reflexive _≈ᵖ_
≈ᵖ-refl {0ᵖ} = 0ᵖ≈
≈ᵖ-refl {x^ n ∙ p} = 0ᵖ≉ ≡-refl ≈ˢ-refl
where
≈ˢ-refl : Reflexive _≈ˢ_
≈ˢ-refl {K c} = K≈ refl
≈ˢ-refl {c +x^ n ∙ p} = +≈ refl ≡-refl ≈ˢ-refl
≈ᵖ-sym : Symmetric _≈ᵖ_
≈ᵖ-sym {0ᵖ} {0ᵖ} 0ᵖ≈ = 0ᵖ≈
≈ᵖ-sym {x^ n ∙ p} {x^ n ∙ q} (0ᵖ≉ ≡-refl p≈ˢq) = 0ᵖ≉ ≡-refl (≈ˢ-sym p≈ˢq)
where
≈ˢ-sym : Symmetric _≈ˢ_
≈ˢ-sym {K c₁} {K c₂} (K≈ c₁≈c₂) = K≈ (sym c₁≈c₂)
≈ˢ-sym {c₁ +x^ n ∙ p} {c₂ +x^ n ∙ q} (+≈ c₁≈c₂ ≡-refl p≈ˢq) = +≈ (sym c₁≈c₂) ≡-refl (≈ˢ-sym p≈ˢq)
≈ᵖ-trans : Transitive _≈ᵖ_
≈ᵖ-trans {0ᵖ} {0ᵖ} {0ᵖ} 0ᵖ≈ 0ᵖ≈ = 0ᵖ≈
≈ᵖ-trans {_} {_} {_} (0ᵖ≉ ≡-refl p≈ˢq) (0ᵖ≉ ≡-refl q≈ˢr) = 0ᵖ≉ ≡-refl (≈ˢ-trans p≈ˢq q≈ˢr)
where
≈ˢ-trans : Transitive _≈ˢ_
≈ˢ-trans (K≈ c₁≈c₂) (K≈ c₂≈c₃) = K≈ (trans c₁≈c₂ c₂≈c₃)
≈ˢ-trans (+≈ c₁≈c₂ ≡-refl p≈ˢq) (+≈ c₂≈c₃ ≡-refl q≈ˢr) = +≈ (trans c₁≈c₂ c₂≈c₃) ≡-refl (≈ˢ-trans p≈ˢq q≈ˢr)
infix 4 _≈ⁱ_
data _≈ⁱ_ : Polynomialⁱ → Polynomialⁱ → Set (c ⊔ˡ ℓ) where
0≈0 : 0ⁱ ≈ⁱ 0ⁱ
0≈+ : ∀ {c} {p} → c ≈ 0# → 0ⁱ ≈ⁱ p → 0ⁱ ≈ⁱ c +x∙ p
+≈0 : ∀ {c} {p} → c ≈ 0# → 0ⁱ ≈ⁱ p → c +x∙ p ≈ⁱ 0ⁱ
+≈+ : ∀ {c₁ c₂} {p q} → c₁ ≈ c₂ → p ≈ⁱ q → c₁ +x∙ p ≈ⁱ c₂ +x∙ q
infix 4 _≉ⁱ_
_≉ⁱ_ : Polynomialⁱ → Polynomialⁱ → Set (c ⊔ˡ ℓ)
p ≉ⁱ q = ¬ (p ≈ⁱ q)
≈ⁱ-refl : Reflexive _≈ⁱ_
≈ⁱ-refl {0ⁱ} = 0≈0
≈ⁱ-refl {c +x∙ p} = +≈+ refl ≈ⁱ-refl
≈ⁱ-sym : Symmetric _≈ⁱ_
≈ⁱ-sym 0≈0 = 0≈0
≈ⁱ-sym (0≈+ c≈0 0≈p) = +≈0 c≈0 0≈p
≈ⁱ-sym (+≈0 c≈0 0≈p) = 0≈+ c≈0 0≈p
≈ⁱ-sym (+≈+ c₁≈c₂ p≈q) = +≈+ (sym c₁≈c₂) (≈ⁱ-sym p≈q)
≈ⁱ-trans : Transitive _≈ⁱ_
≈ⁱ-trans 0≈0 q = q
≈ⁱ-trans (0≈+ c₁≈0 0≈p) (+≈0 c₂≈0 0≈q) = 0≈0
≈ⁱ-trans (0≈+ c₁≈0 0≈p) (+≈+ c₁≈c₂ p≈q) = 0≈+ (trans (sym c₁≈c₂) c₁≈0) (≈ⁱ-trans 0≈p p≈q)
≈ⁱ-trans (+≈0 c₁≈0 0≈p) 0≈0 = +≈0 c₁≈0 0≈p
≈ⁱ-trans (+≈0 c₁≈0 0≈p) (0≈+ c₂≈0 0≈q) = +≈+ (trans c₁≈0 (sym c₂≈0)) (≈ⁱ-trans (≈ⁱ-sym 0≈p) 0≈q)
≈ⁱ-trans (+≈+ c₁≈c₂ p≈q) (+≈0 c₂≈0 0≈q) = +≈0 (trans c₁≈c₂ c₂≈0) (≈ⁱ-trans 0≈q (≈ⁱ-sym p≈q))
≈ⁱ-trans (+≈+ c₁≈c₂ p≈q) (+≈+ c₂≈c₃ q≈r) = +≈+ (trans c₁≈c₂ c₂≈c₃) (≈ⁱ-trans p≈q q≈r)
+ᵖ-*ᵖ-rawRing : RawRing (c ⊔ˡ ℓ) (c ⊔ˡ ℓ)
+ᵖ-*ᵖ-rawRing = record
{ Carrier = Polynomial
; _≈_ = _≈ᵖ_
; _+_ = _+ᵖ_
; _*_ = _*ᵖ_
; -_ = -ᵖ_
; 0# = 0ᵖ
; 1# = 1ᵖ
}
+ⁱ-*ⁱ-rawRing : RawRing c (c ⊔ˡ ℓ)
+ⁱ-*ⁱ-rawRing = record
{ Carrier = Polynomialⁱ
; _≈_ = _≈ⁱ_
; _+_ = _+ⁱ_
; _*_ = _*ⁱ_
; -_ = -ⁱ_
; 0# = 0ⁱ
; 1# = 1ⁱ
}
open import AKS.Extended ≤-totalOrder
using (module ≤ᵉ-Reasoning)
renaming
( Extended to Degree
; _≤ᵉ_ to _≤ᵈ_
; ≤ᵉ-refl to ≤ᵈ-refl
; ≤ᵉ-trans to ≤ᵈ-trans
)
public
open Degree public
open _≤ᵈ_ public
module ≤ᵈ-Reasoning where
open ≤ᵉ-Reasoning renaming (_∼⟨_⟩_ to _≤ᵈ⟨_⟩_; _∎ to _∎ᵈ; _≡⟨_⟩_ to _≡ᵈ⟨_⟩_) public
instance
Degree-number : Number Degree
Degree-number = record
{ Constraint = λ _ → ⊤
; fromNat = λ n → ⟨ n ⟩
}
infixl 5 _⊔ᵈ_
_⊔ᵈ_ : Degree → Degree → Degree
-∞ ⊔ᵈ d₂ = d₂
⟨ d₁ ⟩ ⊔ᵈ -∞ = ⟨ d₁ ⟩
⟨ d₁ ⟩ ⊔ᵈ ⟨ d₂ ⟩ = ⟨ d₁ ⊔ℕ d₂ ⟩
infixl 5 _+ᵈ_
_+ᵈ_ : Degree → Degree → Degree
-∞ +ᵈ d₂ = -∞
⟨ d₁ ⟩ +ᵈ -∞ = -∞
⟨ d₁ ⟩ +ᵈ ⟨ d₂ ⟩ = ⟨ d₁ +ℕ d₂ ⟩
degreeˢ : Spine → ℕ
degreeˢ (K c) = 0
degreeˢ (c +x^ n ∙ p) = ⟅ n ⇓⟆ +ℕ degreeˢ p
degree : Polynomial → Degree
degree 0ᵖ = -∞
degree (x^ n ∙ p) = ⟨ n +ℕ degreeˢ p ⟩
deg : ∀ p {p≉0 : p ≉ᵖ 0ᵖ} → ℕ
deg 0ᵖ {p≉0} = contradiction ≈ᵖ-refl p≉0
deg (x^ n ∙ p) {p≉0} = n +ℕ degreeˢ p
degreeⁱ : Polynomialⁱ → Degree
degreeⁱ 0ⁱ = -∞
degreeⁱ (c +x∙ p) with degreeⁱ p
... | ⟨ n ⟩ = ⟨ suc n ⟩
... | -∞ with c ≈? 0#
... | yes _ = -∞
... | no _ = 0
open import Data.String using (String; _++_)
open import Data.Nat.Show using () renaming (show to show-ℕ)
show-Polynomial : (C → String) → Polynomial → String
show-Polynomial show-c 0ᵖ = "0"
show-Polynomial show-c (x^ n ∙ p) = loop n p
where
loop : ℕ → Spine → String
loop zero (K c) = show-c (proj₁ c)
loop zero (c +x^ n ∙ p) = show-c (proj₁ c) ++ " + " ++ loop ⟅ n ⇓⟆ p
loop (suc n) (K c) = show-c (proj₁ c) ++ " * X^" ++ show-ℕ (suc n)
loop (suc n) (c +x^ m ∙ p) = show-c (proj₁ c) ++ " * X^" ++ show-ℕ (suc n) ++ " + " ++ loop (suc n +ℕ ⟅ m ⇓⟆) p
|
{-# OPTIONS --cubical --no-import-sorts --safe #-}
open import Cubical.Core.Everything
open import Cubical.Relation.Binary
open import Cubical.Algebra.Semigroup
module Cubical.Algebra.Semigroup.Construct.Quotient {c ℓ} (S : Semigroup c) {R : Rel (Semigroup.Carrier S) ℓ} (isEq : IsEquivalence R)
(closed : Congruent₂ R (Semigroup._•_ S)) where
open import Cubical.Foundations.Prelude
open import Cubical.Algebra.Properties
open import Cubical.HITs.SetQuotients
open Semigroup S
open IsEquivalence isEq
import Cubical.Algebra.Magma.Construct.Quotient magma isEq closed as QMagma
open QMagma public hiding (M/R-isMagma; M/R)
•ᴿ-assoc : Associative _•ᴿ_
•ᴿ-assoc = elimProp3 (λ _ _ _ → squash/ _ _) (λ x y z → cong [_] (assoc x y z))
S/R-isSemigroup : IsSemigroup Carrier/R _•ᴿ_
S/R-isSemigroup = record
{ isMagma = QMagma.M/R-isMagma
; assoc = •ᴿ-assoc
}
S/R : Semigroup (ℓ-max c ℓ)
S/R = record { isSemigroup = S/R-isSemigroup }
|
function M = load_image(type, n, options)
% load_image - load benchmark images.
%
% M = load_image(name, n, options);
%
% name can be:
% Synthetic images:
% 'chessboard1', 'chessboard', 'square', 'squareregular', 'disk', 'diskregular', 'quaterdisk', '3contours', 'line',
% 'line_vertical', 'line_horizontal', 'line_diagonal', 'line_circle',
% 'parabola', 'sin', 'phantom', 'circ_oscil',
% 'fnoise' (1/f^alpha noise).
% Natural images:
% 'boat', 'lena', 'goldhill', 'mandrill', 'maurice', 'polygons_blurred', or your own.
%
% Copyright (c) 2004 Gabriel Peyre
if nargin<2
n = 512;
end
options.null = 0;
if iscell(type)
for i=1:length(type)
M{i} = load_image(type{i},n,options);
end
return;
end
type = lower(type);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% parameters for geometric objects
eta = getoptions(options, 'eta', .1);
gamma = getoptions(options, 'gamma', 1/sqrt(2));
radius = getoptions(options, 'radius', 10);
center = getoptions(options, 'center', [0 0]);
center1 = getoptions(options, 'center1', [0 0]);
w = getoptions(options, 'tube_width', 0.06);
nb_points = getoptions(options, 'nb_points', 9);
scaling = getoptions(options, 'scaling', 1);
theta = getoptions(options, 'theta', 30 * 2*pi/360);
eccentricity = getoptions(options, 'eccentricity', 1.3);
sigma = getoptions(options, 'sigma', 0);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% for the line, can be vertical / horizontal / diagonal / any
if strcmp(type, 'line_vertical')
eta = 0.5; % translation
gamma = 0; % slope
elseif strcmp(type, 'line_horizontal')
eta = 0.5; % translation
gamma = Inf; % slope
elseif strcmp(type, 'line_diagonal')
eta = 0; % translation
gamma = 1; % slope
end
if strcmp(type(1:min(12,end)), 'square-tube-')
k = str2double(type(13:end));
c1 = [.22 .5]; c2 = [1-c1(1) .5];
eta = 1.5;
r1 = [c1 c1] + .21*[-1 -eta 1 eta];
r2 = [c2 c2] + .21*[-1 -eta 1 eta];
M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) );
if mod(k,2)==0
sel = n/2-k/2+1:n/2+k/2;
else
sel = n/2-(k-1)/2:n/2+(k-1)/2;
end
M( round(.25*n:.75*n), sel ) = 1;
return;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
switch lower(type)
case 'constant'
M = ones(n);
case 'ramp'
x = linspace(0,1,n);
[Y,M] = meshgrid(x,x);
case 'bump'
s = getoptions(options, 'bump_size', .5);
c = getoptions(options, 'center', [0 0]);
if length(s)==1
s = [s s];
end
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
X = (X-c(1))/s(1); Y = (Y-c(2))/s(2);
M = exp( -(X.^2+Y.^2)/2 );
case 'periodic'
x = linspace(-pi,pi,n)/1.1;
[Y,X] = meshgrid(x,x);
f = getoptions(options, 'freq', 6);
M = (1+cos(f*X)).*(1+cos(f*Y));
case {'letter-x' 'letter-v' 'letter-z' 'letter-y'}
M = create_letter(type(8), radius, n);
case 'l'
r1 = [.1 .1 .3 .9];
r2 = [.1 .1 .9 .4];
M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) );
case 'ellipse'
c1 = [0.15 0.5];
c2 = [0.85 0.5];
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
d = sqrt((X-c1(1)).^2 + (Y-c1(2)).^2) + sqrt((X-c2(1)).^2 + (Y-c2(2)).^2);
M = double( d<=eccentricity*sqrt( sum((c1-c2).^2) ) );
case 'ellipse-thin'
options.eccentricity = 1.06;
M = load_image('ellipse', n, options);
case 'ellipse-fat'
options.eccentricity = 1.3;
M = load_image('ellipse', n, options);
case 'square-tube'
c1 = [.25 .5];
c2 = [.75 .5];
r1 = [c1 c1] + .18*[-1 -1 1 1];
r2 = [c2 c2] + .18*[-1 -1 1 1];
r3 = [c1(1)-w c1(2)-w c2(1)+w c2(2)+w];
M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) | draw_rectangle(r3,n) );
case 'square-tube-1'
options.tube_width = 0.03;
M = load_image('square-tube', n, options);
case 'square-tube-2'
options.tube_width = 0.06;
M = load_image('square-tube', n, options);
case 'square-tube-3'
options.im = 0.09;
M = load_image('square-tube', n, options);
case 'polygon'
theta = sort( rand(nb_points,1)*2*pi );
radius = scaling*rescale(rand(nb_points,1), 0.1, 0.93);
points = [cos(theta) sin(theta)] .* repmat(radius, 1,2);
points = (points+1)/2*(n-1)+1; points(end+1,:) = points(1,:);
M = draw_polygons(zeros(n),0.8,{points'});
[x,y] = ind2sub(size(M),find(M));
p = 100; m = length(x);
lambda = linspace(0,1,p);
X = n/2 + repmat(x-n/2, [1 p]) .* repmat(lambda, [m 1]);
Y = n/2 + repmat(y-n/2, [1 p]) .* repmat(lambda, [m 1]);
I = round(X) + (round(Y)-1)*n;
M = zeros(n); M(I) = 1;
case 'polygon-8'
options.nb_points = 8;
M = load_image('polygon', n, options);
case 'polygon-10'
options.nb_points = 8;
M = load_image('polygon', n, options);
case 'polygon-12'
options.nb_points = 8;
M = load_image('polygon', n, options);
case 'pacman'
options.radius = 0.45;
options.center = [.5 .5];
M = load_image('disk', n, options);
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
T =atan2(Y,X);
M = M .* (1-(abs(T-pi/2)<theta/2));
case 'square-hole'
options.radius = 0.45;
M = load_image('disk', n, options);
options.scaling = 0.5;
M = M - load_image('polygon-10', n, options);
case 'grid-circles'
if isempty(n)
n = 256;
end
f = getoptions(options, 'frequency', 30);
eta = getoptions(options, 'width', .3);
x = linspace(-n/2,n/2,n) - round(n*0.03);
y = linspace(0,n,n);
[Y,X] = meshgrid(y,x);
R = sqrt(X.^2+Y.^2);
theta = 0.05*pi/2;
X1 = cos(theta)*X+sin(theta)*Y;
Y1 = -sin(theta)*X+cos(theta)*Y;
A1 = abs(cos(2*pi*R/f))<eta;
A2 = max( abs(cos(2*pi*X1/f))<eta, abs(cos(2*pi*Y1/f))<eta );
M = A1;
M(X1>0) = A2(X1>0);
case 'chessboard1'
x = -1:2/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (2*(Y>=0)-1).*(2*(X>=0)-1);
case 'chessboard'
width = getoptions(options, 'width', round(n/16) );
[Y,X] = meshgrid(0:n-1,0:n-1);
M = mod( floor(X/width)+floor(Y/width), 2 ) == 0;
case 'square'
if ~isfield( options, 'radius' )
radius = 0.6;
end
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
M = max( abs(X),abs(Y) )<radius;
case 'squareregular'
M = rescale(load_image('square',n,options));
if not(isfield(options, 'alpha'))
options.alpha = 3;
end
S = load_image('fnoise',n,options);
M = M + rescale(S,-0.3,0.3);
case 'regular1'
options.alpha = 1;
M = load_image('fnoise',n,options);
case 'regular2'
options.alpha = 2;
M = load_image('fnoise',n,options);
case 'regular3'
options.alpha = 3;
M = load_image('fnoise',n,options);
case 'sparsecurves'
options.alpha = 3;
M = load_image('fnoise',n,options);
M = rescale(M);
ncurves = 3;
M = cos(2*pi*ncurves);
case 'geometrical'
J = getoptions(options, 'Jgeometrical', 4);
sgeom = 100*n/256;
options.bound = 'per';
A = ones(n);
for j=0:J-1
B = A;
for k=1:2^j
I = find(B==k);
U = perform_blurring(randn(n),sgeom,options);
s = median(U(I));
I1 = find( (B==k) & (U>s) );
I2 = find( (B==k) & (U<=s) );
A(I1) = 2*k-1;
A(I2) = 2*k;
end
end
M = A;
case 'lic-texture'
disp('Computing random tensor field.');
options.sigma_tensor = getoptions(options, 'lic_regularity', 50*n/256);
T = compute_tensor_field_random(n,options);
Flow = perform_tensor_decomp(T); % extract eigenfield.
options.isoriented = 0; % no orientation in streamlines
% initial texture
lic_width = getoptions(options, 'lic_width', 0);
M0 = perform_blurring(randn(n),lic_width);
M0 = perform_histogram_equalization( M0, 'linear');
options.histogram = 'linear';
options.dt = 0.4;
options.M0 = M0;
options.verb = 1;
options.flow_correction = 1;
options.niter_lic = 3;
w = 30;
M = perform_lic(Flow, w, options);
case 'square_texture'
M = load_image('square',n);
M = rescale(M);
% make a texture patch
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
theta = pi/3;
x = cos(theta)*X + sin(theta)*Y;
c = [0.3,0.4]; r = 0.2;
I = find( (X-c(1)).^2 + (Y-c(2)).^2 < r^2 );
eta = 3/n; lambda = 0.3;
M(I) = M(I) + lambda * sin( x(I) * 2*pi / eta );
case 'tv-image'
M = rand(n);
tau = compute_total_variation(M);
options.niter = 400;
[M,err_tv,err_l2] = perform_tv_projection(M,tau/1000,options);
M = perform_histogram_equalization(M,'linear');
case 'oscillatory_texture'
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
theta = pi/3;
x = cos(theta)*X + sin(theta)*Y;
c = [0.3,0.4]; r = 0.2;
I = find( (X-c(1)).^2 + (Y-c(2)).^2 < r^2 );
eta = 3/n; lambda = 0.3;
M = sin( x * 2*pi / eta );
case {'line', 'line_vertical', 'line_horizontal', 'line_diagonal'}
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
if gamma~=Inf
M = (X-eta) - gamma*Y < 0;
else
M = (Y-eta) < 0;
end
case 'line-windowed'
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
eta = .3;
gamma = getoptions(options, 'gamma', pi/10);
parabola = getoptions(options, 'parabola', 0);
M = (X-eta) - gamma*Y - parabola*Y.^2 < 0;
f = sin( pi*x ).^2;
M = M .* ( f'*f );
case 'grating'
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
theta = getoptions(options, 'theta', .2);
freq = getoptions(options, 'freq', .2);
X = cos(theta)*X + sin(theta)*Y;
M = sin(2*pi*X/freq);
case 'disk'
if ~isfield( options, 'radius' )
radius = 0.35;
end
if ~isfield( options, 'center' )
center = [0.5, 0.5]; % center of the circle
end
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
case 'diskregular'
M = rescale(load_image('disk',n,options));
if not(isfield(options, 'alpha'))
options.alpha = 3;
end
S = load_image('fnoise',n,options);
M = M + rescale(S,-0.3,0.3);
case 'quarterdisk'
if ~isfield( options, 'radius' )
radius = 0.95;
end
if ~isfield( options, 'center' )
center = -[0.1, 0.1]; % center of the circle
end
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
case 'fading_contour'
if ~isfield( options, 'radius' )
radius = 0.95;
end
if ~isfield( options, 'center' )
center = -[0.1, 0.1]; % center of the circle
end
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
theta = 2/pi*atan2(Y,X);
h = 0.5;
M = exp(-(1-theta).^2/h^2).*M;
case '3contours'
radius = 1.3;
center = [-1, 1];
radius1 = 0.8;
center1 = [0, 0];
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
f1 = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
f2 = (X-center1(1)).^2 + (Y-center1(2)).^2 < radius1^2;
M = f1 + 0.5*f2.*(1-f1);
case 'line_circle'
gamma = 1/sqrt(2);
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
M1 = double( X>gamma*Y+0.25 );
M2 = X.^2 + Y.^2 < 0.6^2;
M = 20 + max(0.5*M1,M2) * 216;
case 'fnoise'
% generate an image M whose Fourier spectrum amplitude is
% |M^(omega)| = 1/f^{omega}
alpha = getoptions(options, 'alpha', 1);
M = gen_noisy_image(n,alpha);
case 'gaussiannoise'
% generate an image of filtered noise with gaussian
sigma = getoptions(options, 'sigma', 10);
M = randn(n);
m = 51;
h = compute_gaussian_filter([m m],sigma/(4*n),[n n]);
M = perform_convolution(M,h);
return;
case {'bwhorizontal','bwvertical','bwcircle'}
[Y,X] = meshgrid(0:n-1,0:n-1);
if strcmp(type, 'bwhorizontal')
d = X;
elseif strcmp(type, 'bwvertical')
d = Y;
elseif strcmp(type, 'bwcircle')
d = sqrt( (X-(n-1)/2).^2 + (Y-(n-1)/2).^2 );
end
if isfield(options, 'stripe_width')
stripe_width = options.stripe_width;
else
stripe_width = 5;
end
if isfield(options, 'black_prop')
black_prop = options.black_prop;
else
black_prop = 0.5;
end
M = double( mod( d/(2*stripe_width),1 )>=black_prop );
case 'parabola'
% curvature
c = getoptions(c, 'c', .1);
% angle
theta = getoptions(options, 'theta', pi/sqrt(2));
x = -0.5:1/(n-1):0.5;
[Y,X] = meshgrid(x,x);
Xs = X*cos(theta) + Y*sin(theta);
Y =-X*sin(theta) + Y*cos(theta); X = Xs;
M = Y>c*X.^2;
case 'sin'
[Y,X] = meshgrid(-1:2/(n-1):1, -1:2/(n-1):1);
M = Y >= 0.6*cos(pi*X);
M = double(M);
case 'circ_oscil'
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
R = sqrt(X.^2+Y.^2);
M = cos(R.^3*50);
case 'phantom'
M = phantom(n);
case 'periodic_bumps'
nbr_periods = getoptions(options, 'nbr_periods', 8);
theta = getoptions(options, 'theta', 1/sqrt(2));
skew = getoptions(options, 'skew', 1/sqrt(2) );
A = [cos(theta), -sin(theta); sin(theta), cos(theta)];
B = [1 skew; 0 1];
T = B*A;
x = (0:n-1)*2*pi*nbr_periods/(n-1);
[Y,X] = meshgrid(x,x);
pos = [X(:)'; Y(:)'];
pos = T*pos;
X = reshape(pos(1,:), n,n);
Y = reshape(pos(2,:), n,n);
M = cos(X).*sin(Y);
case 'noise'
sigma = getoptions(options, 'sigma', 1);
M = randn(n) * sigma;
case 'disk-corner'
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
rho = .3; eta = .1;
M1 = rho*X+eta<Y;
c = [0 .2]; r = .85;
d = (X-c(1)).^2 + (Y-c(2)).^2;
M2 = d<r^2;
M = M1.*M2;
otherwise
ext = {'gif', 'png', 'jpg', 'bmp', 'tiff', 'tif', 'pgm', 'ppm'};
for i=1:length(ext)
name = [type '.' ext{i}];
if( exist(name) )
M = imread( name );
M = double(M);
if not(isempty(n)) && (n~=size(M, 1) || n~=size(M, 2)) && nargin>=2
M = image_resize(M,n,n);
end
if strcmp(type, 'peppers-bw')
M(:,1) = M(:,2);
M(1,:) = M(2,:);
end
if strcmp(type, 'cameraman')
M(1:4,:) = M(8:-1:5,:);
end
if sigma>0
M = perform_blurring(M,sigma);
end
return;
end
end
error( ['Image ' type ' does not exists.'] );
end
M = double(M);
if sigma>0
M = perform_blurring(M,sigma);
end
M = rescale(M);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function M = create_letter(a, r, n)
c = 0.2;
p1 = [c;c];
p2 = [c; 1-c];
p3 = [1-c; 1-c];
p4 = [1-c; c];
p4 = [1-c; c];
pc = [0.5;0.5];
pu = [0.5; c];
switch a
case 'x'
point_list = { [p1 p3] [p2 p4] };
case 'z'
point_list = { [p2 p3 p1 p4] };
case 'v'
point_list = { [p2 pu p3] };
case 'y'
point_list = { [p2 pc pu] [pc p3] };
end
% fit image
for i=1:length(point_list)
a = point_list{i}(2:-1:1,:);
a(1,:) = 1-a(1,:);
point_list{i} = round( a*(n-1)+1 );
end
M = draw_polygons(zeros(n),r,point_list);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function sk = draw_polygons(mask,r,point_list)
sk = mask*0;
for i=1:length(point_list)
pl = point_list{i};
for k=2:length(pl)
sk = draw_line(sk,pl(1,k-1),pl(2,k-1),pl(1,k),pl(2,k),r);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function sk = draw_line(sk,x1,y1,x2,y2,r)
n = size(sk,1);
[Y,X] = meshgrid(1:n,1:n);
q = 100;
t = linspace(0,1,q);
x = x1*t+x2*(1-t); y = y1*t+y2*(1-t);
if r==0
x = round( x ); y = round( y );
sk( x+(y-1)*n ) = 1;
else
for k=1:q
I = find((X-x(k)).^2 + (Y-y(k)).^2 <= r^2 );
sk(I) = 1;
end
end
function M = gen_noisy_image(n,alpha)
% gen_noisy_image - generate a noisy cloud-like image.
%
% M = gen_noisy_image(n,alpha);
%
% generate an image M whose Fourier spectrum amplitude is
% |M^(omega)| = 1/f^{omega}
%
% Copyright (c) 2004 Gabriel Peyr?
if nargin<1
n = 128;
end
if nargin<2
alpha = 1.5;
end
if mod(n(1),2)==0
x = -n/2:n/2-1;
else
x = -(n-1)/2:(n-1)/2;
end
[Y,X] = meshgrid(x,x);
d = sqrt(X.^2 + Y.^2) + 0.1;
f = rand(n)*2*pi;
M = (d.^(-alpha)) .* exp(f*1i);
% M = real(ifft2(fftshift(M)));
M = ifftshift(M);
M = real( ifft2(M) );
function y = gen_signal_2d(n,alpha)
% gen_signal_2d - generate a 2D C^\alpha signal of length n x n.
% gen_signal_2d(n,alpha) generate a 2D signal C^alpha.
%
% The signal is scale in [0,1].
%
% Copyright (c) 2003 Gabriel Peyr?
% new new method
[Y,X] = meshgrid(0:n-1, 0:n-1);
A = X+Y+1;
B = X-Y+n+1;
a = gen_signal(2*n+1, alpha);
b = gen_signal(2*n+1, alpha);
y = a(A).*b(B);
% M = a(1:n)*b(1:n)';
return;
% new method
h = (-n/2+1):(n/2); h(n/2)=1;
[X,Y] = meshgrid(h,h);
h = sqrt(X.^2+Y.^2+1).^(-alpha-1/2);
h = h .* exp( 2i*pi*rand(n,n) );
h = fftshift(h);
y = real( ifft2(h) );
m1 = min(min(y));
m2 = max(max(y));
y = (y-m1)/(m2-m1);
return;
%% old code
y = rand(n,n);
y = y - mean(mean(y));
for i=1:alpha
y = cumsum(cumsum(y)')';
y = y - mean(mean(y));
end
m1 = min(min(y));
m2 = max(max(y));
y = (y-m1)/(m2-m1);
function newimg = image_resize(img,p1,q1,r1)
% image_resize - resize an image using bicubic interpolation
%
% newimg = image_resize(img,nx,ny,nz);
% or
% newimg = image_resize(img,newsize);
%
% Works for 2D, 2D 2 or 3 channels, 3D images.
%
% Copyright (c) 2004 Gabriel Peyr?
if nargin==2
% size specified as an array
q1 = p1(2);
if length(p1)>2
r1 = p1(3);
else
r1 = size(img,3);
end
p1 = p1(1);
end
if nargin<4
r1 = size(img,3);
end
if ndims(img)<2 || ndims(img)>3
error('Works only for grayscale or color images');
end
if ndims(img)==3 && size(img,3)<4
% RVB image
newimg = zeros(p1,q1, size(img,3));
for m=1:size(img,3)
newimg(:,:,m) = image_resize(img(:,:,m), p1, q1);
end
return;
elseif ndims(img)==3
p = size(img,1);
q = size(img,2);
r = size(img,3);
[Y,X,Z] = meshgrid( (0:q-1)/(q-1), (0:p-1)/(p-1), (0:r-1)/(r-1) );
[YI,XI,ZI] = meshgrid( (0:q1-1)/(q1-1), (0:p1-1)/(p1-1), (0:r1-1)/(r1-1) );
newimg = interp3( Y,X,Z, img, YI,XI,ZI ,'cubic');
return;
end
p = size(img,1);
q = size(img,2);
[Y,X] = meshgrid( (0:q-1)/(q-1), (0:p-1)/(p-1) );
[YI,XI] = meshgrid( (0:q1-1)/(q1-1), (0:p1-1)/(p1-1) );
newimg = interp2( Y,X, img, YI,XI ,'cubic');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function M = draw_rectangle(r,n)
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
M = double( (X>=r(1)) & (X<=r(3)) & (Y>=r(2)) & (Y<=r(4)) ) ;
|
module _ where
open import Common.Prelude renaming (_∸_ to _-_) -- work-around for #1855
_<_ : Nat → Nat → Bool
a < b with b - a
... | zero = false
... | suc _ = true
insert : Nat → List Nat → List Nat
insert x [] = x ∷ []
insert x (y ∷ xs) = if x < y then x ∷ y ∷ xs else (y ∷ insert x xs)
sort : List Nat → List Nat
sort [] = []
sort (x ∷ xs) = insert x (sort xs)
downFrom : Nat → List Nat
downFrom zero = []
downFrom (suc n) = n ∷ downFrom n
mapM! : {A : Set} → (A → IO Unit) → List A → IO Unit
mapM! f [] = return unit
mapM! f (x ∷ xs) = f x >>= λ _ → mapM! f xs
main : IO Unit
main = mapM! printNat (sort (downFrom 1200))
-- 1000 0.6s
-- 2000 4.8s
-- 4000 36.2s
|
```python
%matplotlib inline
```
Writing mathematical expressions
================================
An introduction to writing mathematical expressions in Matplotlib.
You can use a subset TeX markup in any matplotlib text string by placing it
inside a pair of dollar signs ($).
Note that you do not need to have TeX installed, since Matplotlib ships
its own TeX expression parser, layout engine, and fonts. The layout engine
is a fairly direct adaptation of the layout algorithms in Donald Knuth's
TeX, so the quality is quite good (matplotlib also provides a ``usetex``
option for those who do want to call out to TeX to generate their text (see
:doc:`/tutorials/text/usetex`).
Any text element can use math text. You should use raw strings (precede the
quotes with an ``'r'``), and surround the math text with dollar signs ($), as
in TeX. Regular text and mathtext can be interleaved within the same string.
Mathtext can use DejaVu Sans (default), DejaVu Serif, the Computer Modern fonts
(from (La)TeX), `STIX <http://www.stixfonts.org/>`_ fonts (with are designed
to blend well with Times), or a Unicode font that you provide. The mathtext
font can be selected with the customization variable ``mathtext.fontset`` (see
:doc:`/tutorials/introductory/customizing`)
Here is a simple example::
# plain text
plt.title('alpha > beta')
produces "alpha > beta".
Whereas this::
# math text
plt.title(r'$\alpha > \beta$')
produces ":mathmpl:`\alpha > \beta`".
<div class="alert alert-info"><h4>Note</h4><p>Mathtext should be placed between a pair of dollar signs ($). To make it
easy to display monetary values, e.g., "$100.00", if a single dollar sign
is present in the entire string, it will be displayed verbatim as a dollar
sign. This is a small change from regular TeX, where the dollar sign in
non-math text would have to be escaped ('\\\$').</p></div>
<div class="alert alert-info"><h4>Note</h4><p>While the syntax inside the pair of dollar signs ($) aims to be TeX-like,
the text outside does not. In particular, characters such as::
# $ % & ~ _ ^ \ { } \( \) \[ \]
have special meaning outside of math mode in TeX. Therefore, these
characters will behave differently depending on the rcParam ``text.usetex``
flag. See the :doc:`usetex tutorial </tutorials/text/usetex>` for more
information.</p></div>
Subscripts and superscripts
---------------------------
To make subscripts and superscripts, use the ``'_'`` and ``'^'`` symbols::
r'$\alpha_i > \beta_i$'
\begin{align}\alpha_i > \beta_i\end{align}
Some symbols automatically put their sub/superscripts under and over the
operator. For example, to write the sum of :mathmpl:`x_i` from :mathmpl:`0` to
:mathmpl:`\infty`, you could do::
r'$\sum_{i=0}^\infty x_i$'
\begin{align}\sum_{i=0}^\infty x_i\end{align}
Fractions, binomials, and stacked numbers
-----------------------------------------
Fractions, binomials, and stacked numbers can be created with the
``\frac{}{}``, ``\binom{}{}`` and ``\genfrac{}{}{}{}{}{}`` commands,
respectively::
r'$\frac{3}{4} \binom{3}{4} \genfrac{}{}{0}{}{3}{4}$'
produces
\begin{align}\frac{3}{4} \binom{3}{4} \stackrel{}{}{0}{}{3}{4}\end{align}
Fractions can be arbitrarily nested::
r'$\frac{5 - \frac{1}{x}}{4}$'
produces
\begin{align}\frac{5 - \frac{1}{x}}{4}\end{align}
Note that special care needs to be taken to place parentheses and brackets
around fractions. Doing things the obvious way produces brackets that are too
small::
r'$(\frac{5 - \frac{1}{x}}{4})$'
.. math ::
(\frac{5 - \frac{1}{x}}{4})
The solution is to precede the bracket with ``\left`` and ``\right`` to inform
the parser that those brackets encompass the entire object.::
r'$\left(\frac{5 - \frac{1}{x}}{4}\right)$'
.. math ::
\left(\frac{5 - \frac{1}{x}}{4}\right)
Radicals
--------
Radicals can be produced with the ``\sqrt[]{}`` command. For example::
r'$\sqrt{2}$'
.. math ::
\sqrt{2}
Any base can (optionally) be provided inside square brackets. Note that the
base must be a simple expression, and can not contain layout commands such as
fractions or sub/superscripts::
r'$\sqrt[3]{x}$'
.. math ::
\sqrt[3]{x}
Fonts
-----
The default font is *italics* for mathematical symbols.
<div class="alert alert-info"><h4>Note</h4><p>This default can be changed using the ``mathtext.default`` rcParam. This is
useful, for example, to use the same font as regular non-math text for math
text, by setting it to ``regular``.</p></div>
To change fonts, e.g., to write "sin" in a Roman font, enclose the text in a
font command::
r'$s(t) = \mathcal{A}\mathrm{sin}(2 \omega t)$'
\begin{align}s(t) = \mathcal{A}\mathrm{sin}(2 \omega t)\end{align}
More conveniently, many commonly used function names that are typeset in
a Roman font have shortcuts. So the expression above could be written as
follows::
r'$s(t) = \mathcal{A}\sin(2 \omega t)$'
\begin{align}s(t) = \mathcal{A}\sin(2 \omega t)\end{align}
Here "s" and "t" are variable in italics font (default), "sin" is in Roman
font, and the amplitude "A" is in calligraphy font. Note in the example above
the calligraphy ``A`` is squished into the ``sin``. You can use a spacing
command to add a little whitespace between them::
r's(t) = \mathcal{A}\/\sin(2 \omega t)'
.. Here we cheat a bit: for HTML math rendering, Sphinx relies on MathJax which
doesn't actually support the italic correction (\/); instead, use a thin
space (\,) which is supported.
\begin{align}s(t) = \mathcal{A}\,\sin(2 \omega t)\end{align}
The choices available with all fonts are:
========================= ================================
Command Result
========================= ================================
``\mathrm{Roman}`` :mathmpl:`\mathrm{Roman}`
``\mathit{Italic}`` :mathmpl:`\mathit{Italic}`
``\mathtt{Typewriter}`` :mathmpl:`\mathtt{Typewriter}`
``\mathcal{CALLIGRAPHY}`` :mathmpl:`\mathcal{CALLIGRAPHY}`
========================= ================================
.. role:: math-stix(mathmpl)
:fontset: stix
When using the `STIX <http://www.stixfonts.org/>`_ fonts, you also have the
choice of:
================================ =========================================
Command Result
================================ =========================================
``\mathbb{blackboard}`` :math-stix:`\mathbb{blackboard}`
``\mathrm{\mathbb{blackboard}}`` :math-stix:`\mathrm{\mathbb{blackboard}}`
``\mathfrak{Fraktur}`` :math-stix:`\mathfrak{Fraktur}`
``\mathsf{sansserif}`` :math-stix:`\mathsf{sansserif}`
``\mathrm{\mathsf{sansserif}}`` :math-stix:`\mathrm{\mathsf{sansserif}}`
================================ =========================================
There are also three global "font sets" to choose from, which are
selected using the ``mathtext.fontset`` parameter in `matplotlibrc
<matplotlibrc-sample>`.
``cm``: **Computer Modern (TeX)**
``stix``: **STIX** (designed to blend well with Times)
``stixsans``: **STIX sans-serif**
Additionally, you can use ``\mathdefault{...}`` or its alias
``\mathregular{...}`` to use the font used for regular text outside of
mathtext. There are a number of limitations to this approach, most notably
that far fewer symbols will be available, but it can be useful to make math
expressions blend well with other text in the plot.
Custom fonts
~~~~~~~~~~~~
mathtext also provides a way to use custom fonts for math. This method is
fairly tricky to use, and should be considered an experimental feature for
patient users only. By setting the rcParam ``mathtext.fontset`` to ``custom``,
you can then set the following parameters, which control which font file to use
for a particular set of math characters.
============================== =================================
Parameter Corresponds to
============================== =================================
``mathtext.it`` ``\mathit{}`` or default italic
``mathtext.rm`` ``\mathrm{}`` Roman (upright)
``mathtext.tt`` ``\mathtt{}`` Typewriter (monospace)
``mathtext.bf`` ``\mathbf{}`` bold italic
``mathtext.cal`` ``\mathcal{}`` calligraphic
``mathtext.sf`` ``\mathsf{}`` sans-serif
============================== =================================
Each parameter should be set to a fontconfig font descriptor (as defined in the
yet-to-be-written font chapter).
.. TODO: Link to font chapter
The fonts used should have a Unicode mapping in order to find any
non-Latin characters, such as Greek. If you want to use a math symbol
that is not contained in your custom fonts, you can set the rcParam
``mathtext.fallback_to_cm`` to ``True`` which will cause the mathtext system
to use characters from the default Computer Modern fonts whenever a particular
character can not be found in the custom font.
Note that the math glyphs specified in Unicode have evolved over time, and many
fonts may not have glyphs in the correct place for mathtext.
Accents
-------
An accent command may precede any symbol to add an accent above it. There are
long and short forms for some of them.
============================== =================================
Command Result
============================== =================================
``\acute a`` or ``\'a`` :mathmpl:`\acute a`
``\bar a`` :mathmpl:`\bar a`
``\breve a`` :mathmpl:`\breve a`
``\ddot a`` or ``\''a`` :mathmpl:`\ddot a`
``\dot a`` or ``\.a`` :mathmpl:`\dot a`
``\grave a`` or ``\`a`` :mathmpl:`\grave a`
``\hat a`` or ``\^a`` :mathmpl:`\hat a`
``\tilde a`` or ``\~a`` :mathmpl:`\tilde a`
``\vec a`` :mathmpl:`\vec a`
``\overline{abc}`` :mathmpl:`\overline{abc}`
============================== =================================
In addition, there are two special accents that automatically adjust to the
width of the symbols below:
============================== =================================
Command Result
============================== =================================
``\widehat{xyz}`` :mathmpl:`\widehat{xyz}`
``\widetilde{xyz}`` :mathmpl:`\widetilde{xyz}`
============================== =================================
Care should be taken when putting accents on lower-case i's and j's. Note that
in the following ``\imath`` is used to avoid the extra dot over the i::
r"$\hat i\ \ \hat \imath$"
\begin{align}\hat i\ \ \hat \imath\end{align}
Symbols
-------
You can also use a large number of the TeX symbols, as in ``\infty``,
``\leftarrow``, ``\sum``, ``\int``.
.. math_symbol_table::
If a particular symbol does not have a name (as is true of many of the more
obscure symbols in the STIX fonts), Unicode characters can also be used::
ur'$\u23ce$'
Example
-------
Here is an example illustrating many of these features in context.
.. figure:: ../../gallery/pyplots/images/sphx_glr_pyplot_mathtext_001.png
:target: ../../gallery/pyplots/pyplot_mathtext.html
:align: center
:scale: 50
Pyplot Mathtext
|
When Cole Bentley committed to Louisville it was big news for ‘Cards fans. Typically, the big maulers “out in the state” wind up at Kentucky. Bentley is from Eastern Kentucky but he chose the ‘Cards however, because he believes the program is on the verge of something special and sees an opportunity to contribute early.
Around the time he announced his decision to attend Louisville, some people coaimed Kentucky wasn’t pursuing Bentley very hard and that he “settled for Louisville.” Bentley was quick to dispel that rumor when I asked him about it.
Bentley also shot down the assumption he grew up a fan of the Wildcats.
Bentley started playing football as a Marshall fan back in third grade as a linebacker in Pee Wee ball. He now plays TE in a run dominant Wing T system for Belfry High as well as defensive tackle on the other side of the ball.
While Bentley plays tight end, he is used primarily as an extra edge blocker in Belfrey’s attack but he projects as an interior lineman in college. The thing that stands when watching his tape is how he drives his defender all over the field or to the ground until the whistle blows.
He’s up to 315-pounds and his athleticism combined with his unrelenting motor should have Louisville fans and running backs excited for the future.
Bentley will conclude his high school football career this Saturday when the Pirates take on the Central Yellowjackets in the 3A Kentucky state chanpioship. If Belfry wins it will be their fourth straight 3A state title and Bentley will not know what it’s like to not win state as a player. Also, his days in high school will end shortly thereafter the season wraps up. The talented offensive line prospect will enroll early at UofL on January 6th as an early enrollee.
|
Require Import Crypto.Arithmetic.PrimeFieldTheorems.
Require Import Crypto.Specific.solinas32_2e512m569_24limbs.Synthesis.
(* TODO : change this to field once field isomorphism happens *)
Definition freeze :
{ freeze : feBW_tight -> feBW_limbwidths
| forall a, phiBW_limbwidths (freeze a) = phiBW_tight a }.
Proof.
Set Ltac Profiling.
Time synthesize_freeze ().
Show Ltac Profile.
Time Defined.
Print Assumptions freeze.
|
(* Title: CCL/Wfd.thy
Author: Martin Coen, Cambridge University Computer Laboratory
Copyright 1993 University of Cambridge
*)
section \<open>Well-founded relations in CCL\<close>
theory Wfd
imports Trancl Type Hered
begin
definition Wfd :: "[i set] \<Rightarrow> o"
where "Wfd(R) == ALL P.(ALL x.(ALL y.<y,x> : R \<longrightarrow> y:P) \<longrightarrow> x:P) \<longrightarrow> (ALL a. a:P)"
definition wf :: "[i set] \<Rightarrow> i set"
where "wf(R) == {x. x:R \<and> Wfd(R)}"
definition wmap :: "[i\<Rightarrow>i,i set] \<Rightarrow> i set"
where "wmap(f,R) == {p. EX x y. p=<x,y> \<and> <f(x),f(y)> : R}"
definition lex :: "[i set,i set] => i set" (infixl "**" 70)
where "ra**rb == {p. EX a a' b b'. p = <<a,b>,<a',b'>> \<and> (<a,a'> : ra | (a=a' \<and> <b,b'> : rb))}"
definition NatPR :: "i set"
where "NatPR == {p. EX x:Nat. p=<x,succ(x)>}"
definition ListPR :: "i set \<Rightarrow> i set"
where "ListPR(A) == {p. EX h:A. EX t:List(A). p=<t,h$t>}"
lemma wfd_induct:
assumes 1: "Wfd(R)"
and 2: "\<And>x. ALL y. <y,x>: R \<longrightarrow> P(y) \<Longrightarrow> P(x)"
shows "P(a)"
apply (rule 1 [unfolded Wfd_def, rule_format, THEN CollectD])
using 2 apply blast
done
lemma wfd_strengthen_lemma:
assumes 1: "\<And>x y.<x,y> : R \<Longrightarrow> Q(x)"
and 2: "ALL x. (ALL y. <y,x> : R \<longrightarrow> y : P) \<longrightarrow> x : P"
and 3: "\<And>x. Q(x) \<Longrightarrow> x:P"
shows "a:P"
apply (rule 2 [rule_format])
using 1 3
apply blast
done
method_setup wfd_strengthen = \<open>
Scan.lift Args.embedded_inner_syntax >> (fn s => fn ctxt =>
SIMPLE_METHOD' (fn i =>
Rule_Insts.res_inst_tac ctxt [((("Q", 0), Position.none), s)] [] @{thm wfd_strengthen_lemma} i
THEN assume_tac ctxt (i + 1)))
\<close>
lemma wf_anti_sym: "\<lbrakk>Wfd(r); <a,x>:r; <x,a>:r\<rbrakk> \<Longrightarrow> P"
apply (subgoal_tac "ALL x. <a,x>:r \<longrightarrow> <x,a>:r \<longrightarrow> P")
apply blast
apply (erule wfd_induct)
apply blast
done
lemma wf_anti_refl: "\<lbrakk>Wfd(r); <a,a>: r\<rbrakk> \<Longrightarrow> P"
apply (rule wf_anti_sym)
apply assumption+
done
subsection \<open>Irreflexive transitive closure\<close>
lemma trancl_wf:
assumes 1: "Wfd(R)"
shows "Wfd(R^+)"
apply (unfold Wfd_def)
apply (rule allI ballI impI)+
(*must retain the universal formula for later use!*)
apply (rule allE, assumption)
apply (erule mp)
apply (rule 1 [THEN wfd_induct])
apply (rule impI [THEN allI])
apply (erule tranclE)
apply blast
apply (erule spec [THEN mp, THEN spec, THEN mp])
apply assumption+
done
subsection \<open>Lexicographic Ordering\<close>
lemma lexXH:
"p : ra**rb \<longleftrightarrow> (EX a a' b b'. p = <<a,b>,<a',b'>> \<and> (<a,a'> : ra | a=a' \<and> <b,b'> : rb))"
unfolding lex_def by blast
lemma lexI1: "<a,a'> : ra \<Longrightarrow> <<a,b>,<a',b'>> : ra**rb"
by (blast intro!: lexXH [THEN iffD2])
lemma lexI2: "<b,b'> : rb \<Longrightarrow> <<a,b>,<a,b'>> : ra**rb"
by (blast intro!: lexXH [THEN iffD2])
lemma lexE:
assumes 1: "p : ra**rb"
and 2: "\<And>a a' b b'. \<lbrakk><a,a'> : ra; p=<<a,b>,<a',b'>>\<rbrakk> \<Longrightarrow> R"
and 3: "\<And>a b b'. \<lbrakk><b,b'> : rb; p = <<a,b>,<a,b'>>\<rbrakk> \<Longrightarrow> R"
shows R
apply (rule 1 [THEN lexXH [THEN iffD1], THEN exE])
using 2 3
apply blast
done
lemma lex_pair: "\<lbrakk>p : r**s; \<And>a a' b b'. p = <<a,b>,<a',b'>> \<Longrightarrow> P\<rbrakk> \<Longrightarrow>P"
apply (erule lexE)
apply blast+
done
lemma lex_wf:
assumes 1: "Wfd(R)"
and 2: "Wfd(S)"
shows "Wfd(R**S)"
apply (unfold Wfd_def)
apply safe
apply (wfd_strengthen "\<lambda>x. EX a b. x=<a,b>")
apply (blast elim!: lex_pair)
apply (subgoal_tac "ALL a b.<a,b>:P")
apply blast
apply (rule 1 [THEN wfd_induct, THEN allI])
apply (rule 2 [THEN wfd_induct, THEN allI]) back
apply (fast elim!: lexE)
done
subsection \<open>Mapping\<close>
lemma wmapXH: "p : wmap(f,r) \<longleftrightarrow> (EX x y. p=<x,y> \<and> <f(x),f(y)> : r)"
unfolding wmap_def by blast
lemma wmapI: "<f(a),f(b)> : r \<Longrightarrow> <a,b> : wmap(f,r)"
by (blast intro!: wmapXH [THEN iffD2])
lemma wmapE: "\<lbrakk>p : wmap(f,r); \<And>a b. \<lbrakk><f(a),f(b)> : r; p=<a,b>\<rbrakk> \<Longrightarrow> R\<rbrakk> \<Longrightarrow> R"
by (blast dest!: wmapXH [THEN iffD1])
lemma wmap_wf:
assumes 1: "Wfd(r)"
shows "Wfd(wmap(f,r))"
apply (unfold Wfd_def)
apply clarify
apply (subgoal_tac "ALL b. ALL a. f (a) = b \<longrightarrow> a:P")
apply blast
apply (rule 1 [THEN wfd_induct, THEN allI])
apply clarify
apply (erule spec [THEN mp])
apply (safe elim!: wmapE)
apply (erule spec [THEN mp, THEN spec, THEN mp])
apply assumption
apply (rule refl)
done
subsection \<open>Projections\<close>
lemma wfstI: "<xa,ya> : r \<Longrightarrow> <<xa,xb>,<ya,yb>> : wmap(fst,r)"
apply (rule wmapI)
apply simp
done
lemma wsndI: "<xb,yb> : r \<Longrightarrow> <<xa,xb>,<ya,yb>> : wmap(snd,r)"
apply (rule wmapI)
apply simp
done
lemma wthdI: "<xc,yc> : r \<Longrightarrow> <<xa,<xb,xc>>,<ya,<yb,yc>>> : wmap(thd,r)"
apply (rule wmapI)
apply simp
done
subsection \<open>Ground well-founded relations\<close>
lemma wfI: "\<lbrakk>Wfd(r); a : r\<rbrakk> \<Longrightarrow> a : wf(r)"
unfolding wf_def by blast
lemma Empty_wf: "Wfd({})"
unfolding Wfd_def by (blast elim: EmptyXH [THEN iffD1, THEN FalseE])
lemma wf_wf: "Wfd(wf(R))"
unfolding wf_def
apply (rule_tac Q = "Wfd(R)" in excluded_middle [THEN disjE])
apply simp_all
apply (rule Empty_wf)
done
lemma NatPRXH: "p : NatPR \<longleftrightarrow> (EX x:Nat. p=<x,succ(x)>)"
unfolding NatPR_def by blast
lemma ListPRXH: "p : ListPR(A) \<longleftrightarrow> (EX h:A. EX t:List(A).p=<t,h$t>)"
unfolding ListPR_def by blast
lemma NatPRI: "x : Nat \<Longrightarrow> <x,succ(x)> : NatPR"
by (auto simp: NatPRXH)
lemma ListPRI: "\<lbrakk>t : List(A); h : A\<rbrakk> \<Longrightarrow> <t,h $ t> : ListPR(A)"
by (auto simp: ListPRXH)
lemma NatPR_wf: "Wfd(NatPR)"
apply (unfold Wfd_def)
apply clarify
apply (wfd_strengthen "\<lambda>x. x:Nat")
apply (fastforce iff: NatPRXH)
apply (erule Nat_ind)
apply (fastforce iff: NatPRXH)+
done
lemma ListPR_wf: "Wfd(ListPR(A))"
apply (unfold Wfd_def)
apply clarify
apply (wfd_strengthen "\<lambda>x. x:List (A)")
apply (fastforce iff: ListPRXH)
apply (erule List_ind)
apply (fastforce iff: ListPRXH)+
done
subsection \<open>General Recursive Functions\<close>
lemma letrecT:
assumes 1: "a : A"
and 2: "\<And>p g. \<lbrakk>p:A; ALL x:{x: A. <x,p>:wf(R)}. g(x) : D(x)\<rbrakk> \<Longrightarrow> h(p,g) : D(p)"
shows "letrec g x be h(x,g) in g(a) : D(a)"
apply (rule 1 [THEN rev_mp])
apply (rule wf_wf [THEN wfd_induct])
apply (subst letrecB)
apply (rule impI)
apply (erule 2)
apply blast
done
lemma SPLITB: "SPLIT(<a,b>,B) = B(a,b)"
unfolding SPLIT_def
apply (rule set_ext)
apply blast
done
lemma letrec2T:
assumes "a : A"
and "b : B"
and "\<And>p q g. \<lbrakk>p:A; q:B;
ALL x:A. ALL y:{y: B. <<x,y>,<p,q>>:wf(R)}. g(x,y) : D(x,y)\<rbrakk> \<Longrightarrow>
h(p,q,g) : D(p,q)"
shows "letrec g x y be h(x,y,g) in g(a,b) : D(a,b)"
apply (unfold letrec2_def)
apply (rule SPLITB [THEN subst])
apply (assumption | rule letrecT pairT splitT assms)+
apply (subst SPLITB)
apply (assumption | rule ballI SubtypeI assms)+
apply (rule SPLITB [THEN subst])
apply (assumption | rule letrecT SubtypeI pairT splitT assms |
erule bspec SubtypeE sym [THEN subst])+
done
lemma lem: "SPLIT(<a,<b,c>>,\<lambda>x xs. SPLIT(xs,\<lambda>y z. B(x,y,z))) = B(a,b,c)"
by (simp add: SPLITB)
lemma letrec3T:
assumes "a : A"
and "b : B"
and "c : C"
and "\<And>p q r g. \<lbrakk>p:A; q:B; r:C;
ALL x:A. ALL y:B. ALL z:{z:C. <<x,<y,z>>,<p,<q,r>>> : wf(R)}.
g(x,y,z) : D(x,y,z) \<rbrakk> \<Longrightarrow>
h(p,q,r,g) : D(p,q,r)"
shows "letrec g x y z be h(x,y,z,g) in g(a,b,c) : D(a,b,c)"
apply (unfold letrec3_def)
apply (rule lem [THEN subst])
apply (assumption | rule letrecT pairT splitT assms)+
apply (simp add: SPLITB)
apply (assumption | rule ballI SubtypeI assms)+
apply (rule lem [THEN subst])
apply (assumption | rule letrecT SubtypeI pairT splitT assms |
erule bspec SubtypeE sym [THEN subst])+
done
lemmas letrecTs = letrecT letrec2T letrec3T
subsection \<open>Type Checking for Recursive Calls\<close>
lemma rcallT:
"\<lbrakk>ALL x:{x:A.<x,p>:wf(R)}.g(x):D(x);
g(a) : D(a) \<Longrightarrow> g(a) : E; a:A; <a,p>:wf(R)\<rbrakk> \<Longrightarrow> g(a) : E"
by blast
lemma rcall2T:
"\<lbrakk>ALL x:A. ALL y:{y:B.<<x,y>,<p,q>>:wf(R)}.g(x,y):D(x,y);
g(a,b) : D(a,b) \<Longrightarrow> g(a,b) : E; a:A; b:B; <<a,b>,<p,q>>:wf(R)\<rbrakk> \<Longrightarrow> g(a,b) : E"
by blast
lemma rcall3T:
"\<lbrakk>ALL x:A. ALL y:B. ALL z:{z:C.<<x,<y,z>>,<p,<q,r>>>:wf(R)}. g(x,y,z):D(x,y,z);
g(a,b,c) : D(a,b,c) \<Longrightarrow> g(a,b,c) : E;
a:A; b:B; c:C; <<a,<b,c>>,<p,<q,r>>> : wf(R)\<rbrakk> \<Longrightarrow> g(a,b,c) : E"
by blast
lemmas rcallTs = rcallT rcall2T rcall3T
subsection \<open>Instantiating an induction hypothesis with an equality assumption\<close>
lemma hyprcallT:
assumes 1: "g(a) = b"
and 2: "ALL x:{x:A.<x,p>:wf(R)}.g(x):D(x)"
and 3: "ALL x:{x:A.<x,p>:wf(R)}.g(x):D(x) \<Longrightarrow> b=g(a) \<Longrightarrow> g(a) : D(a) \<Longrightarrow> P"
and 4: "ALL x:{x:A.<x,p>:wf(R)}.g(x):D(x) \<Longrightarrow> a:A"
and 5: "ALL x:{x:A.<x,p>:wf(R)}.g(x):D(x) \<Longrightarrow> <a,p>:wf(R)"
shows P
apply (rule 3 [OF 2, OF 1 [symmetric]])
apply (rule rcallT [OF 2])
apply assumption
apply (rule 4 [OF 2])
apply (rule 5 [OF 2])
done
lemma hyprcall2T:
assumes 1: "g(a,b) = c"
and 2: "ALL x:A. ALL y:{y:B.<<x,y>,<p,q>>:wf(R)}.g(x,y):D(x,y)"
and 3: "\<lbrakk>c = g(a,b); g(a,b) : D(a,b)\<rbrakk> \<Longrightarrow> P"
and 4: "a:A"
and 5: "b:B"
and 6: "<<a,b>,<p,q>>:wf(R)"
shows P
apply (rule 3)
apply (rule 1 [symmetric])
apply (rule rcall2T)
apply (rule 2)
apply assumption
apply (rule 4)
apply (rule 5)
apply (rule 6)
done
lemma hyprcall3T:
assumes 1: "g(a,b,c) = d"
and 2: "ALL x:A. ALL y:B. ALL z:{z:C.<<x,<y,z>>,<p,<q,r>>>:wf(R)}.g(x,y,z):D(x,y,z)"
and 3: "\<lbrakk>d = g(a,b,c); g(a,b,c) : D(a,b,c)\<rbrakk> \<Longrightarrow> P"
and 4: "a:A"
and 5: "b:B"
and 6: "c:C"
and 7: "<<a,<b,c>>,<p,<q,r>>> : wf(R)"
shows P
apply (rule 3)
apply (rule 1 [symmetric])
apply (rule rcall3T)
apply (rule 2)
apply assumption
apply (rule 4)
apply (rule 5)
apply (rule 6)
apply (rule 7)
done
lemmas hyprcallTs = hyprcallT hyprcall2T hyprcall3T
subsection \<open>Rules to Remove Induction Hypotheses after Type Checking\<close>
lemma rmIH1: "\<lbrakk>ALL x:{x:A.<x,p>:wf(R)}.g(x):D(x); P\<rbrakk> \<Longrightarrow> P" .
lemma rmIH2: "\<lbrakk>ALL x:A. ALL y:{y:B.<<x,y>,<p,q>>:wf(R)}.g(x,y):D(x,y); P\<rbrakk> \<Longrightarrow> P" .
lemma rmIH3:
"\<lbrakk>ALL x:A. ALL y:B. ALL z:{z:C.<<x,<y,z>>,<p,<q,r>>>:wf(R)}.g(x,y,z):D(x,y,z); P\<rbrakk> \<Longrightarrow> P" .
lemmas rmIHs = rmIH1 rmIH2 rmIH3
subsection \<open>Lemmas for constructors and subtypes\<close>
(* 0-ary constructors do not need additional rules as they are handled *)
(* correctly by applying SubtypeI *)
lemma Subtype_canTs:
"\<And>a b A B P. a : {x:A. b:{y:B(a).P(<x,y>)}} \<Longrightarrow> <a,b> : {x:Sigma(A,B).P(x)}"
"\<And>a A B P. a : {x:A. P(inl(x))} \<Longrightarrow> inl(a) : {x:A+B. P(x)}"
"\<And>b A B P. b : {x:B. P(inr(x))} \<Longrightarrow> inr(b) : {x:A+B. P(x)}"
"\<And>a P. a : {x:Nat. P(succ(x))} \<Longrightarrow> succ(a) : {x:Nat. P(x)}"
"\<And>h t A P. h : {x:A. t : {y:List(A).P(x$y)}} \<Longrightarrow> h$t : {x:List(A).P(x)}"
by (assumption | rule SubtypeI canTs icanTs | erule SubtypeE)+
lemma letT: "\<lbrakk>f(t):B; \<not>t=bot\<rbrakk> \<Longrightarrow> let x be t in f(x) : B"
apply (erule letB [THEN ssubst])
apply assumption
done
lemma applyT2: "\<lbrakk>a:A; f : Pi(A,B)\<rbrakk> \<Longrightarrow> f ` a : B(a)"
apply (erule applyT)
apply assumption
done
lemma rcall_lemma1: "\<lbrakk>a:A; a:A \<Longrightarrow> P(a)\<rbrakk> \<Longrightarrow> a : {x:A. P(x)}"
by blast
lemma rcall_lemma2: "\<lbrakk>a:{x:A. Q(x)}; \<lbrakk>a:A; Q(a)\<rbrakk> \<Longrightarrow> P(a)\<rbrakk> \<Longrightarrow> a : {x:A. P(x)}"
by blast
lemmas rcall_lemmas = asm_rl rcall_lemma1 SubtypeD1 rcall_lemma2
subsection \<open>Typechecking\<close>
ML \<open>
local
val type_rls =
@{thms canTs} @ @{thms icanTs} @ @{thms applyT2} @ @{thms ncanTs} @ @{thms incanTs} @
@{thms precTs} @ @{thms letrecTs} @ @{thms letT} @ @{thms Subtype_canTs};
fun bvars (Const(@{const_name Pure.all},_) $ Abs(s,_,t)) l = bvars t (s::l)
| bvars _ l = l
fun get_bno l n (Const(@{const_name Pure.all},_) $ Abs(s,_,t)) = get_bno (s::l) n t
| get_bno l n (Const(@{const_name Trueprop},_) $ t) = get_bno l n t
| get_bno l n (Const(@{const_name Ball},_) $ _ $ Abs(s,_,t)) = get_bno (s::l) (n+1) t
| get_bno l n (Const(@{const_name mem},_) $ t $ _) = get_bno l n t
| get_bno l n (t $ s) = get_bno l n t
| get_bno l n (Bound m) = (m-length(l),n)
(* Not a great way of identifying induction hypothesis! *)
fun could_IH x = Term.could_unify(x,hd (Thm.prems_of @{thm rcallT})) orelse
Term.could_unify(x,hd (Thm.prems_of @{thm rcall2T})) orelse
Term.could_unify(x,hd (Thm.prems_of @{thm rcall3T}))
fun IHinst tac rls = SUBGOAL (fn (Bi,i) =>
let val bvs = bvars Bi []
val ihs = filter could_IH (Logic.strip_assums_hyp Bi)
val rnames = map (fn x =>
let val (a,b) = get_bno [] 0 x
in (nth bvs a, b) end) ihs
fun try_IHs [] = no_tac
| try_IHs ((x,y)::xs) =
tac [((("g", 0), Position.none), x)] (nth rls (y - 1)) i ORELSE (try_IHs xs)
in try_IHs rnames end)
fun is_rigid_prog t =
(case (Logic.strip_assums_concl t) of
(Const(@{const_name Trueprop},_) $ (Const(@{const_name mem},_) $ a $ _)) =>
null (Term.add_vars a [])
| _ => false)
in
fun rcall_tac ctxt i =
let fun tac ps rl i = Rule_Insts.res_inst_tac ctxt ps [] rl i THEN assume_tac ctxt i
in IHinst tac @{thms rcallTs} i end
THEN eresolve_tac ctxt @{thms rcall_lemmas} i
fun raw_step_tac ctxt prems i =
assume_tac ctxt i ORELSE
resolve_tac ctxt (prems @ type_rls) i ORELSE
rcall_tac ctxt i ORELSE
ematch_tac ctxt @{thms SubtypeE} i ORELSE
match_tac ctxt @{thms SubtypeI} i
fun tc_step_tac ctxt prems = SUBGOAL (fn (Bi,i) =>
if is_rigid_prog Bi then raw_step_tac ctxt prems i else no_tac)
fun typechk_tac ctxt rls i = SELECT_GOAL (REPEAT_FIRST (tc_step_tac ctxt rls)) i
(*** Clean up Correctness Condictions ***)
fun clean_ccs_tac ctxt =
let fun tac ps rl i = Rule_Insts.eres_inst_tac ctxt ps [] rl i THEN assume_tac ctxt i in
TRY (REPEAT_FIRST (IHinst tac @{thms hyprcallTs} ORELSE'
eresolve_tac ctxt ([asm_rl, @{thm SubtypeE}] @ @{thms rmIHs}) ORELSE'
hyp_subst_tac ctxt))
end
fun gen_ccs_tac ctxt rls i =
SELECT_GOAL (REPEAT_FIRST (tc_step_tac ctxt rls) THEN clean_ccs_tac ctxt) i
end
\<close>
method_setup typechk = \<open>
Attrib.thms >> (fn ths => fn ctxt => SIMPLE_METHOD' (typechk_tac ctxt ths))
\<close>
method_setup clean_ccs = \<open>
Scan.succeed (SIMPLE_METHOD o clean_ccs_tac)
\<close>
method_setup gen_ccs = \<open>
Attrib.thms >> (fn ths => fn ctxt => SIMPLE_METHOD' (gen_ccs_tac ctxt ths))
\<close>
subsection \<open>Evaluation\<close>
named_theorems eval "evaluation rules"
ML \<open>
fun eval_tac ths =
Subgoal.FOCUS_PREMS (fn {context = ctxt, prems, ...} =>
let val eval_rules = Named_Theorems.get ctxt @{named_theorems eval}
in DEPTH_SOLVE_1 (resolve_tac ctxt (ths @ prems @ rev eval_rules) 1) end)
\<close>
method_setup eval = \<open>
Attrib.thms >> (fn ths => fn ctxt => SIMPLE_METHOD' (CHANGED o eval_tac ths ctxt))
\<close>
lemmas eval_rls [eval] = trueV falseV pairV lamV caseVtrue caseVfalse caseVpair caseVlam
lemma applyV [eval]:
assumes "f \<longlongrightarrow> lam x. b(x)"
and "b(a) \<longlongrightarrow> c"
shows "f ` a \<longlongrightarrow> c"
unfolding apply_def by (eval assms)
lemma letV:
assumes 1: "t \<longlongrightarrow> a"
and 2: "f(a) \<longlongrightarrow> c"
shows "let x be t in f(x) \<longlongrightarrow> c"
apply (unfold let_def)
apply (rule 1 [THEN canonical])
apply (tactic \<open>
REPEAT (DEPTH_SOLVE_1 (resolve_tac @{context} (@{thms assms} @ @{thms eval_rls}) 1 ORELSE
eresolve_tac @{context} @{thms substitute} 1))\<close>)
done
lemma fixV: "f(fix(f)) \<longlongrightarrow> c \<Longrightarrow> fix(f) \<longlongrightarrow> c"
apply (unfold fix_def)
apply (rule applyV)
apply (rule lamV)
apply assumption
done
lemma letrecV:
"h(t,\<lambda>y. letrec g x be h(x,g) in g(y)) \<longlongrightarrow> c \<Longrightarrow>
letrec g x be h(x,g) in g(t) \<longlongrightarrow> c"
apply (unfold letrec_def)
apply (assumption | rule fixV applyV lamV)+
done
lemmas [eval] = letV letrecV fixV
lemma V_rls [eval]:
"true \<longlongrightarrow> true"
"false \<longlongrightarrow> false"
"\<And>b c t u. \<lbrakk>b\<longlongrightarrow>true; t\<longlongrightarrow>c\<rbrakk> \<Longrightarrow> if b then t else u \<longlongrightarrow> c"
"\<And>b c t u. \<lbrakk>b\<longlongrightarrow>false; u\<longlongrightarrow>c\<rbrakk> \<Longrightarrow> if b then t else u \<longlongrightarrow> c"
"\<And>a b. <a,b> \<longlongrightarrow> <a,b>"
"\<And>a b c t h. \<lbrakk>t \<longlongrightarrow> <a,b>; h(a,b) \<longlongrightarrow> c\<rbrakk> \<Longrightarrow> split(t,h) \<longlongrightarrow> c"
"zero \<longlongrightarrow> zero"
"\<And>n. succ(n) \<longlongrightarrow> succ(n)"
"\<And>c n t u. \<lbrakk>n \<longlongrightarrow> zero; t \<longlongrightarrow> c\<rbrakk> \<Longrightarrow> ncase(n,t,u) \<longlongrightarrow> c"
"\<And>c n t u x. \<lbrakk>n \<longlongrightarrow> succ(x); u(x) \<longlongrightarrow> c\<rbrakk> \<Longrightarrow> ncase(n,t,u) \<longlongrightarrow> c"
"\<And>c n t u. \<lbrakk>n \<longlongrightarrow> zero; t \<longlongrightarrow> c\<rbrakk> \<Longrightarrow> nrec(n,t,u) \<longlongrightarrow> c"
"\<And>c n t u x. \<lbrakk>n\<longlongrightarrow>succ(x); u(x,nrec(x,t,u))\<longlongrightarrow>c\<rbrakk> \<Longrightarrow> nrec(n,t,u)\<longlongrightarrow>c"
"[] \<longlongrightarrow> []"
"\<And>h t. h$t \<longlongrightarrow> h$t"
"\<And>c l t u. \<lbrakk>l \<longlongrightarrow> []; t \<longlongrightarrow> c\<rbrakk> \<Longrightarrow> lcase(l,t,u) \<longlongrightarrow> c"
"\<And>c l t u x xs. \<lbrakk>l \<longlongrightarrow> x$xs; u(x,xs) \<longlongrightarrow> c\<rbrakk> \<Longrightarrow> lcase(l,t,u) \<longlongrightarrow> c"
"\<And>c l t u. \<lbrakk>l \<longlongrightarrow> []; t \<longlongrightarrow> c\<rbrakk> \<Longrightarrow> lrec(l,t,u) \<longlongrightarrow> c"
"\<And>c l t u x xs. \<lbrakk>l\<longlongrightarrow>x$xs; u(x,xs,lrec(xs,t,u))\<longlongrightarrow>c\<rbrakk> \<Longrightarrow> lrec(l,t,u)\<longlongrightarrow>c"
unfolding data_defs by eval+
subsection \<open>Factorial\<close>
schematic_goal
"letrec f n be ncase(n,succ(zero),\<lambda>x. nrec(n,zero,\<lambda>y g. nrec(f(x),g,\<lambda>z h. succ(h))))
in f(succ(succ(zero))) \<longlongrightarrow> ?a"
by eval
schematic_goal
"letrec f n be ncase(n,succ(zero),\<lambda>x. nrec(n,zero,\<lambda>y g. nrec(f(x),g,\<lambda>z h. succ(h))))
in f(succ(succ(succ(zero)))) \<longlongrightarrow> ?a"
by eval
subsection \<open>Less Than Or Equal\<close>
schematic_goal
"letrec f p be split(p,\<lambda>m n. ncase(m,true,\<lambda>x. ncase(n,false,\<lambda>y. f(<x,y>))))
in f(<succ(zero), succ(zero)>) \<longlongrightarrow> ?a"
by eval
schematic_goal
"letrec f p be split(p,\<lambda>m n. ncase(m,true,\<lambda>x. ncase(n,false,\<lambda>y. f(<x,y>))))
in f(<succ(zero), succ(succ(succ(succ(zero))))>) \<longlongrightarrow> ?a"
by eval
schematic_goal
"letrec f p be split(p,\<lambda>m n. ncase(m,true,\<lambda>x. ncase(n,false,\<lambda>y. f(<x,y>))))
in f(<succ(succ(succ(succ(succ(zero))))), succ(succ(succ(succ(zero))))>) \<longlongrightarrow> ?a"
by eval
subsection \<open>Reverse\<close>
schematic_goal
"letrec id l be lcase(l,[],\<lambda>x xs. x$id(xs))
in id(zero$succ(zero)$[]) \<longlongrightarrow> ?a"
by eval
schematic_goal
"letrec rev l be lcase(l,[],\<lambda>x xs. lrec(rev(xs),x$[],\<lambda>y ys g. y$g))
in rev(zero$succ(zero)$(succ((lam x. x)`succ(zero)))$([])) \<longlongrightarrow> ?a"
by eval
end
|
function mObject3 = waveformMorphing(mObject1,mObject2,mRate);
% Morphing with minimum information
% (Actually this is not real morphing.
% It is simply blending two waveform.)
% mObject3 = waveformMorphing(mObject1,mObject2,mRate);
% Designed and coded by Hideki Kawahara
% 27/Feb./2005
% Copyright(c) 2005, Hideki Kawahara
nLength = max(length(mObject1.waveform),length(mObject2.waveform));
if mObject1.samplingFrequency ~= mObject2.samplingFrequency
mObject3 = [];
return
end;
x = zeros(nLength,1);
x(1:length(mObject1.waveform)) = (1-mRate)*mObject1.waveform;
x(1:length(mObject2.waveform)) = mRate*mObject2.waveform + x(1:length(mObject2.waveform));
mObject3=createMobject;
mObject3.waveform = x;
mObject3.samplingFrequency = mObject1.samplingFrequency;
|
Formal statement is: corollary\<^marker>\<open>tag unimportant\<close> Cauchy_theorem_convex: "\<lbrakk>continuous_on S f; convex S; finite K; \<And>x. x \<in> interior S - K \<Longrightarrow> f field_differentiable at x; valid_path g; path_image g \<subseteq> S; pathfinish g = pathstart g\<rbrakk> \<Longrightarrow> (f has_contour_integral 0) g" Informal statement is: If $f$ is a continuous function on a convex set $S$, and $f$ is differentiable on the interior of $S$ except for a finite number of points, then the integral of $f$ along any closed path in $S$ is zero.
|
r=0.79
https://sandbox.dams.library.ucdavis.edu/fcrepo/rest/collection/sherry-lehmann/catalogs/d70597/media/images/d70597-011/svc:tesseract/full/full/0.79/default.jpg Accept:application/hocr+xml
|
/-
Copyright (c) 2020 The Xena project. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Kevin Buzzard
Thanks: Imperial College London, leanprover-community
The complex numbers, modelled as R^2 in the obvious way.
-/
import complex.basic -- tutorial level
/-!
# Level 1: I
I find it unbelievable that we have written quite a lot of code about the complex numbers
and we've still never defined i, or j, or I, or $$\sqrt{-1}$$, or whatever it's called.
Why don't you supply the definition, and make the basic API?
All the proofs below are sorried. You can try them in tactic mode
by replacing `sorry` with `begin end` and then starting to write
tactics in the `begin end` block.
-/
namespace complex
/-- complex.I is the square root of -1 above the imaginary axis -/
def I : ℂ := ⟨0, 1⟩
/-
Easy lemmas, tagged with `simp` so Lean can prove things about `I` by equating
real and imaginary parts.
-/
/-- re(I) = 0 -/
@[simp] lemma I_re : re(I) = 0 :=
begin
refl
end
/-- im(I) = 1 -/
@[simp] lemma I_im : im(I) = 1 :=
begin
refl
end
/-- I*I = -1 -/
@[simp] lemma I_mul_I : I * I = -1 :=
begin
-- suffices to check real and imaginary parts
ext;
-- do them both at once
simp,
end
-- Boss level. Hint: don't forget ext_iff
/-- I is non-zero -/
lemma I_ne_zero : (I : ℂ) ≠ 0 :=
begin
-- by contradiction
intro h,
-- what does it mean for two complex numbers to be equal
rw ext_iff at h,
-- this is now just a logic puzzle
simp * at *,
end
end complex
|
# Kolmogorov forcing
The following equation is solved
\begin{equation}
\partial_t \zeta + J(\psi,\zeta) = A(y) + \nu \nabla^2 \zeta
\end{equation}
where $A(y) = A_1 cos(y) +4 A_4cos(4y)$.
Parameters for the following runs are:
> $\nu = 0.02$
> $A_1 = -1.0$
> $A_4 = -2.0$
```python
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.pylab as pl
import matplotlib.animation as animation
```
```python
def save_vorticity_snapshots(data):
filenames = []
S = np.shape(data['Vxy'])[2]
for i in range (0,S,100):
filename = dn+'anim/frame_'+str(i)+'.png'
filenames.append (filename)
days = round(i/S*10000,2)
fig,ax = plt.subplots()
ax.set_title(r'$t = $'+str(days))
ax.set_xticks([0,M-1,2*M-2])
ax.set_xticklabels([r'$0$',r'$\pi$',r'$2\pi$'],fontsize=14)
ax.set_yticks([0,N-1,2*N-2])
ax.set_yticklabels([r'$0$',r'$\pi$',r'$2\pi$'],fontsize=14)
im = plt.imshow((data['Vxy'][:,:,i]),cmap="RdBu_r",origin="lower",interpolation="bicubic",vmax=30,vmin=-30)
fig.colorbar(im)
plt.savefig(filename,bbox_inches='tight',dpi=128)
plt.close()
return filenames
def gen_vorticity_animation(infiles,outfile):
gif_filename = dn+outfile+'.gif'
with imageio.get_writer(gif_filename, mode='I') as writer:
for filename in infiles: ## here we go through all prepared files
image = imageio.imread(filename)
writer.append_data(image)
os.remove(filename) ## now we remove individual frames
optimize(gif_filename) ## to optimise the file size
```
```python
def animate_data(data,dn,filename):
fps = 20
saveinterval = 5
fig,ax = plt.subplots()
im = plt.imshow(data[:,:,0],origin='lower',cmap='RdBu_r',vmax=30,vmin=-30,interpolation='bicubic')
fig.colorbar(im)
plt.xticks([0,M-1,2*M-2],[r'$0$',r'$\pi$',r'$2\pi$'],fontsize=14)
plt.yticks([0,M-1,2*M-2],[r'$0$',r'$\pi$',r'$2\pi$'],fontsize=14)
def animate(i):
plt.title(str(i*fps*saveinterval) + ' days')
im.set_array(data[:,:,i])
return [im]
anim = animation.FuncAnimation(fig, animate)
anim.save(dn+filename+'.mp4', fps=fps, extra_args=['-vcodec', 'libx264'])
plt.close()
```
# 8x8 grid
```python
dn = "kolmogorov/8x8/"
M,N = 8,8
colors = pl.cm.nipy_spectral(np.linspace(0,1,M))
```
```python
import matplotlib as mpl
plt.rc('font', family='serif') ## setting for figures which I usually use in my publications
mpl.rcParams.update({'font.size': 12})
mpl.rcParams.update({'legend.labelspacing':0.25, 'legend.fontsize': 12})
mpl.rcParams.update({'errorbar.capsize': 4})
```
```python
nl_full = np.load(dn+"nl.npz",allow_pickle=True)
nl_res1 = np.load(dn+"nl_res_1.npz",allow_pickle=True)
nl_res2 = np.load(dn+"nl_res_2.npz",allow_pickle=True)
```
```python
fig,ax = plt.subplots(1,3,figsize=(14,5))
ax[0].set_title(f'NL(Full)')
for i,x in enumerate(nl_full['Emtav'].T):
ax[0].plot(nl_full['t'],x,label=i,c=colors[i])
ax[1].set_title(f'NL(2)')
for i,x in enumerate(nl_res2['Emtav'].T):
ax[1].plot(nl_res2['t'],x,label=i,c=colors[i])
ax[2].set_title(f'NL(1)')
for i,x in enumerate(nl_res1['Emtav'].T):
ax[2].plot(nl_res1['t'],x,label=i,c=colors[i])
for a in ax:
a.set_xlabel(r'$t$',fontsize=14)
a.set_yscale('log')
a.set_ylim(1e-6,1e4)
ax[0].set_ylabel(r'$E(m)$',fontsize=14)
ax[2].legend(bbox_to_anchor=(1.3,0.75),ncol=1)
# plt.show()
plt.savefig(dn+'nl_fullvlowres.png',bbox_inches='tight',dpi=128)
```
```python
fig,ax = plt.subplots(1,3,figsize=(15,6))
im = ax[0].imshow((nl_full['Vxy'][:,:,-1]),cmap="RdBu_r",origin="lower",interpolation="bicubic",vmax=30,vmin=-30)
im = ax[1].imshow((nl_res1['Vxy'][:,:,-1]),cmap="RdBu_r",origin="lower",interpolation="bicubic",vmax=30,vmin=-30)
im = ax[2].imshow((nl_res2['Vxy'][:,:,-1]),cmap="RdBu_r",origin="lower",interpolation="bicubic",vmax=30,vmin=-30)
fig.colorbar(im)
for a in ax:
a.set_xticks([0,M-1,2*M-2])
a.set_xticklabels([r'$-M$',r'$0$',r'$M$'],fontsize=14)
a.set_yticks([0,M-1,2*M-2])
a.set_yticklabels([r'$-M$',r'$0$',r'$M$'],fontsize=14)
plt.show()
```
```python
animate_data(nl_full['Vxy'],dn,'nl_full')
animate_data(nl_res1['Vxy'],dn,'nl_res1')
animate_data(nl_res2['Vxy'],dn,'nl_res2')
```
```python
nl = np.load(dn+"nl.npz",allow_pickle=True)
gql_m = np.load(dn+"gql_m.npz",allow_pickle=True)
gce2_m = np.load(dn+"gce2_m.npz",allow_pickle=True)
```
```python
fig,ax = plt.subplots(1,3,figsize=(14,5))
ax[0].set_title(f'NL')
for i,x in enumerate(nl['Emtav'].T):
ax[0].plot(nl['t'],x,label=i,c=colors[i])
ax[1].set_title(f'GQL(M)')
for i,x in enumerate(gql_m['Emtav'].T):
ax[1].plot(gql_m['t'],x,label=i,c=colors[i])
ax[2].set_title(f'GCE2(M)')
for i,x in enumerate(gce2_m['Emtav'].T):
ax[2].plot(gce2_m['t'],x,label=i,c=colors[i])
for a in ax:
a.set_xlabel(r'$t$',fontsize=14)
a.set_yscale('log')
a.set_ylim(1e-3,1e4)
ax[0].set_ylabel(r'$E(m)$',fontsize=14)
ax[2].legend(bbox_to_anchor=(1.25,0.5),ncol=1)
plt.show()
```
```python
fig,ax = plt.subplots(1,3,figsize=(15,6))
im = ax[0].imshow((nl['Emn'][:,:,-1]),cmap="nipy_spectral_r",origin="lower",interpolation="bicubic")
im = ax[1].imshow((gql_m['Emn'][:,:,-1]),cmap="nipy_spectral_r",origin="lower",interpolation="bicubic")
im = ax[2].imshow((gce2_m['Emn'][:,:,-1]),cmap="nipy_spectral_r",origin="lower",interpolation="bicubic")
fig.colorbar(im)
for a in ax:
a.set_xticks([0,M,2*M-2])
a.set_xticklabels([r'$-M$',r'$0$',r'$M$'],fontsize=14)
a.set_yticks([0,M,2*M-2])
a.set_yticklabels([r'$-M$',r'$0$',r'$M$'],fontsize=14)
plt.show()
```
```python
fig,ax = plt.subplots(1,3,figsize=(15,6))
im = ax[0].imshow((nl['Vxy'][:,:,-1]),cmap="RdBu_r",origin="lower",interpolation="bicubic")
im = ax[1].imshow((gql_m['Vxy'][:,:,-1]),cmap="RdBu_r",origin="lower",interpolation="bicubic")
im = ax[2].imshow((gce2_m['Vxy'][:,:,-1]),cmap="RdBu_r",origin="lower",interpolation="bicubic")
for a in ax:
a.set_xticks([0,M,2*M-2])
a.set_xticklabels([r'$-M$',r'$0$',r'$M$'],fontsize=14)
a.set_yticks([0,M,2*M-2])
a.set_yticklabels([r'$-M$',r'$0$',r'$M$'],fontsize=14)
plt.show()
```
```python
# fig,ax = plt.subplots(3,1,figsize=(15,12))
# ax[0].set_title('NL')
# ax[0].imshow(nl['Vyt'],interpolation='bicubic')
# ax[0].set_aspect(3)
# ax[1].set_title('GQL(M)')
# ax[1].imshow(gql_m['Vyt'],interpolation='bicubic')
# ax[1].set_aspect(3)
# ax[2].set_title('GCE2(M)')
# ax[2].imshow(gce2_m['Vyt'],interpolation='bicubic')
# ax[2].set_aspect(3)
# for a in ax:
# a.set_xlabel(r'$t$',fontsize=14)
# a.set_ylabel(r'$\theta$',fontsize=14)
# a.set_yticks([0,M,2*M-2])
# a.set_yticklabels([r'$-90$',0,r'$90$'],fontsize=14)
# plt.show()
```
```python
gql_1 = np.load(dn+"gql_1.npz",allow_pickle=True)
gce2_1 = np.load(dn+"gce2_1.npz",allow_pickle=True)
```
```python
fig,ax = plt.subplots(1,2,figsize=(14,5))
ax[0].set_title(f'GQL(1)')
for i,x in enumerate(gql_1['Emtav'].T):
ax[0].plot(gql_1['t'],x,label=i,c=colors[i])
ax[1].set_title(f'GCE2(1)')
for i,x in enumerate(gce2_1['Emtav'].T):
ax[1].plot(gce2_1['t'],x,label=i,c=colors[i])
for a in ax:
a.set_xlabel(r'$t$',fontsize=14)
a.set_yscale('log')
a.set_ylim(1e-4,1e4)
ax[0].set_ylabel(r'$E(m)$',fontsize=14)
ax[1].legend(bbox_to_anchor=(1.01,0.5),ncol=1)
plt.show()
```
```python
fig,ax = plt.subplots(1,2,figsize=(12,6))
im = ax[0].imshow((gql_1['Emn'][:,:,-1]),cmap="nipy_spectral_r",origin="lower",interpolation="bicubic")
# fig.colorbar(im)
im = ax[1].imshow((gce2_1['Emn'][:,:,-1]),cmap="nipy_spectral_r",origin="lower",interpolation="bicubic")
# fig.colorbar(im)
for a in ax:
a.set_xticks([0,M,2*M-2])
a.set_xticklabels([r'$-M$',r'$0$',r'$M$'],fontsize=14)
a.set_yticks([0,M,2*M-2])
a.set_yticklabels([r'$-M$',r'$0$',r'$M$'],fontsize=14)
plt.show()
```
```python
fig,ax = plt.subplots(2,1,figsize=(12,6))
ax[0].set_title('GQL(1)')
ax[0].imshow(gql_1['Vyt'],cmap="jet",interpolation='bicubic')
ax[0].set_aspect(0.5)
ax[1].set_title('GCE2(1)')
ax[1].imshow(gce2_1['Vyt'],cmap="jet",interpolation='bicubic')
ax[1].set_aspect(0.25)
for a in ax:
a.set_xlabel(r'$t$',fontsize=14)
a.set_ylabel(r'$\theta$',fontsize=14)
a.set_yticks([0,M,2*M-2])
a.set_yticklabels([r'$-90$',0,r'$90$'],fontsize=14)
plt.show()
```
```python
gql_3 = np.load(dn+"gql_3.npz",allow_pickle=True)
gce2_3 = np.load(dn+"gce2_3.npz",allow_pickle=True)
```
```python
fig,ax = plt.subplots(1,2,figsize=(14,5))
ax[0].set_title(f'GQL(3)')
for i,x in enumerate(gql_3['Emtav'].T):
ax[0].plot(gql_3['t'],x,label=i,c=colors[i])
ax[1].set_title(f'GCE2(3)')
for i,x in enumerate(gce2_3['Emtav'].T):
ax[1].plot(gce2_3['t'],x,label=i,c=colors[i])
for a in ax:
a.set_xlabel(r'$t$',fontsize=14)
a.set_yscale('log')
a.set_ylim(1e-4,1e4)
ax[0].set_ylabel(r'$E(m)$',fontsize=14)
ax[1].legend(bbox_to_anchor=(1.01,0.5),ncol=1)
plt.show()
```
```python
fig,ax = plt.subplots(1,2,figsize=(12,6))
ax[0].set_title('GQL(3)')
im = ax[0].imshow((gql_3['Emn'][:,:,-1]),cmap="nipy_spectral_r",origin="lower",interpolation="bicubic")
# fig.colorbar(im)
ax[1].set_title('GCE2(3)')
im = ax[1].imshow((gce2_3['Emn'][:,:,-1]),cmap="nipy_spectral_r",origin="lower",interpolation="bicubic")
# fig.colorbar(im)
for a in ax:
a.set_xticks([0,M,2*M-2])
a.set_xticklabels([r'$-M$',r'$0$',r'$M$'],fontsize=14)
a.set_yticks([0,M,2*M-2])
a.set_yticklabels([r'$-M$',r'$0$',r'$M$'],fontsize=14)
plt.show()
```
```python
fig,ax = plt.subplots(2,1,figsize=(12,12))
ax[0].set_title('GQL(3)')
ax[0].imshow(gql_3['Vyt'],cmap="jet",interpolation='bicubic')
ax[0].set_aspect(0.5)
ax[1].set_title('GCE2(3)')
ax[1].imshow(gce2_3['Vyt'],cmap="jet",interpolation='bicubic')
ax[1].set_aspect(0.25)
for a in ax:
a.set_xlabel(r'$t$',fontsize=14)
a.set_ylabel(r'$\theta$',fontsize=14)
a.set_yticks([0,M,2*M-2])
a.set_yticklabels([r'$-90$',0,r'$90$'],fontsize=14)
plt.show()
```
```python
ql = np.load(dn+"ql.npz",allow_pickle=True)
ce2 = np.load(dn+"ce2.npz",allow_pickle=True)
gce2_0 = np.load(dn+"gce2_0.npz",allow_pickle=True)
```
```python
fig,ax = plt.subplots(1,3,figsize=(14,5))
ax[0].set_title(f'QL')
for i,x in enumerate(ql['Emt'].T):
ax[0].plot(ql['t'],x,label=i,c=colors[i])
ax[1].set_title(f'CE2')
for i,x in enumerate(ce2['Emt'].T):
ax[1].plot(ce2['t'],x,label=i,c=colors[i])
ax[2].set_title(f'GCE2(0)')
for i,x in enumerate(gce2_0['Emt'].T):
ax[2].plot(gce2_0['t'],x,label=i,c=colors[i])
for a in ax:
a.set_xlabel(r'$t$',fontsize=14)
a.set_yscale('log')
a.set_ylim(1e-36,1e4)
ax[0].set_ylabel(r'$E(m)$',fontsize=14)
ax[2].legend(bbox_to_anchor=(1.01,0.5),ncol=1)
# plt.show()
plt.savefig(dn+'figures/kolmogorov_qlce2_dp5.png',bbox_inches='tight')
```
```python
ql = np.load(dn+"ql_bs3.npz",allow_pickle=True)
ce2 = np.load(dn+"ce2_ts5.npz",allow_pickle=True)
```
```python
fig,ax = plt.subplots(1,2,figsize=(10,5))
ax[0].set_title(f'QL')
for i,x in enumerate(ql['Emt'].T):
ax[0].plot(ql['t'],x,label=i,c=colors[i])
ax[1].set_title(f'CE2')
for i,x in enumerate(ce2['Emt'].T):
ax[1].plot(ce2['t'],x,label=i,c=colors[i])
# ax[2].set_title(f'GCE2(0)')
# for i,x in enumerate(gce2_0['Emt'].T):
# ax[2].plot(gce2_0['t'],x,label=i,c=colors[i])
for a in ax:
a.set_xlabel(r'$t$',fontsize=14)
a.set_yscale('log')
a.set_ylim(1e-16,1e5)
ax[0].set_ylabel(r'$E(m)$',fontsize=14)
ax[1].legend(bbox_to_anchor=(1.0,0.75),ncol=1)
# plt.show()
plt.savefig(dn+'figures/kolmogorov_qlce2_bs3.png',bbox_inches='tight')
```
```python
ql = np.load(dn+"ql_ts5.npz",allow_pickle=True)
ce2 = np.load(dn+"ce2_ts5.npz",allow_pickle=True)
```
```python
fig,ax = plt.subplots(1,2,figsize=(10,5))
ax[0].set_title(f'QL')
for i,x in enumerate(ql['Emt'].T):
ax[0].plot(ql['t'],x,label=i,c=colors[i])
ax[1].set_title(f'CE2')
for i,x in enumerate(ce2['Emt'].T):
ax[1].plot(ce2['t'],x,label=i,c=colors[i])
# ax[2].set_title(f'GCE2(0)')
# for i,x in enumerate(gce2_0['Emt'].T):
# ax[2].plot(gce2_0['t'],x,label=i,c=colors[i])
for a in ax:
a.set_xlabel(r'$t$',fontsize=14)
a.set_yscale('log')
a.set_ylim(1e-16,1e5)
ax[0].set_ylabel(r'$E(m)$',fontsize=14)
ax[1].legend(bbox_to_anchor=(1.0,0.75),ncol=1)
# plt.show()
plt.savefig(dn+'figures/kolmogorov_qlce2_ts5.png',bbox_inches='tight')
```
```python
ql = np.load(dn+"ql_dp5.npz",allow_pickle=True)
ce2 = np.load(dn+"ce2_dp5.npz",allow_pickle=True)
```
```python
fig,ax = plt.subplots(1,2,figsize=(10,5))
ax[0].set_title(f'QL')
for i,x in enumerate(ql['Emt'].T):
ax[0].plot(ql['t'],x,label=i,c=colors[i])
ax[1].set_title(f'CE2')
for i,x in enumerate(ce2['Emt'].T):
ax[1].plot(ce2['t'],x,label=i,c=colors[i])
# ax[2].set_title(f'GCE2(0)')
# for i,x in enumerate(gce2_0['Emt'].T):
# ax[2].plot(gce2_0['t'],x,label=i,c=colors[i])
for a in ax:
a.set_xlabel(r'$t$',fontsize=14)
a.set_yscale('log')
a.set_ylim(1e-16,1e5)
ax[0].set_ylabel(r'$E(m)$',fontsize=14)
ax[1].legend(bbox_to_anchor=(1.0,0.75),ncol=1)
# plt.show()
plt.savefig(dn+'figures/kolmogorov_qlce2_dp5.png',bbox_inches='tight')
```
```python
ql = np.load(dn+"ql_250.npz",allow_pickle=True)
ql_2 = np.load(dn+"ql_250_r2.npz",allow_pickle=True)
```
```python
fig,ax = plt.subplots(1,2,figsize=(10,5))
ax[0].set_title(f'QL')
for i,x in enumerate(ql['Emtav'].T):
ax[0].plot(ql['t'],x,label=i,c=colors[i])
ax[1].set_title(f'QL w/ diff seed')
for i,x in enumerate(ql_2['Emtav'].T):
ax[1].plot(ql_2['t'],x,label=i,c=colors[i])
for a in ax:
a.set_xlabel(r'$t$',fontsize=14)
a.set_yscale('log')
a.set_ylim(1e-16,1e5)
ax[0].set_ylabel(r'$E(m)$',fontsize=14)
ax[1].legend(bbox_to_anchor=(1.0,0.75),ncol=1)
# plt.show()
# plt.savefig(dn+'figures/kolmogorov_qlce2_dp5.png',bbox_inches='tight')
```
```python
fig,ax = plt.subplots(1,2,figsize=(15,6))
im = ax[0].imshow((ql['Vxy'][:,:,-1]),cmap="RdBu_r",origin="lower",interpolation="bicubic")
im = ax[1].imshow((ql_2['Vxy'][:,:,-1]),cmap="RdBu_r",origin="lower",interpolation="bicubic")
for a in ax:
a.set_xticks([0,M,2*M-2])
a.set_xticklabels([r'$-M$',r'$0$',r'$M$'],fontsize=14)
a.set_yticks([0,M,2*M-2])
a.set_yticklabels([r'$-M$',r'$0$',r'$M$'],fontsize=14)
plt.show()
```
```python
ql = np.load(dn+"ql_500_r123.npz",allow_pickle=True)
ce2 = np.load(dn+"ce2_500_ql_r123.npz",allow_pickle=True)
```
```python
colors = pl.cm.nipy_spectral(np.linspace(0,1,M))
```
```python
fig,ax = plt.subplots(1,2,figsize=(10,5))
ax[0].set_title(f'QL')
for i,x in enumerate(ql['Emtav'].T):
ax[0].plot(ql['t'],x,label=i,c=colors[i])
ax[1].set_title(f'CE2')
for i,x in enumerate(ce2['Emtav'].T):
ax[1].plot(ce2['t'],x,label=i,c=colors[i])
for a in ax:
a.set_xlabel(r'$t$',fontsize=14)
a.set_yscale('log')
a.set_ylim(1e-16,1e5)
ax[0].set_ylabel(r'$E(m)$',fontsize=14)
ax[1].legend(bbox_to_anchor=(1.0,0.75),ncol=1)
# plt.show()
plt.savefig(dn+'figures/ze_qlce2_dp5.png',bbox_inches='tight')
```
```python
ql = np.load(dn+"ql_500_r123.npz",allow_pickle=True)
ce2 = np.load(dn+"ce2_500_r123.npz",allow_pickle=True)
```
```python
colors = pl.cm.nipy_spectral(np.linspace(0,1,M))
```
```python
fig,ax = plt.subplots(1,2,figsize=(10,5))
ax[0].set_title(f'QL')
for i,x in enumerate(ql['Emtav'].T):
ax[0].plot(ql['t'],x,label=i,c=colors[i])
ax[1].set_title(f'CE2')
for i,x in enumerate(ce2['Emtav'].T):
ax[1].plot(ce2['t'],x,label=i,c=colors[i])
for a in ax:
a.set_xlabel(r'$t$',fontsize=14)
a.set_yscale('log')
a.set_ylim(1e-16,1e5)
ax[0].set_ylabel(r'$E(m)$',fontsize=14)
ax[1].legend(bbox_to_anchor=(1.0,0.75),ncol=1)
# plt.show()
plt.savefig(dn+'figures/ze_qlce2_rand.png',bbox_inches='tight')
```
```python
fig,ax = plt.subplots(1,3,figsize=(15,6))
im = ax[0].imshow((ql['Emn'][:,:,-1]),cmap="nipy_spectral_r",origin="lower",interpolation="bicubic")
im = ax[1].imshow((ce2['Emn'][:,:,-1]),cmap="nipy_spectral_r",origin="lower",interpolation="bicubic")
im = ax[2].imshow((gce2_0['Emn'][:,:,-1]),cmap="nipy_spectral_r",origin="lower",interpolation="bicubic")
for a in ax:
a.set_xticks([0,M,2*M-2])
a.set_xticklabels([r'$-M$',r'$0$',r'$M$'],fontsize=14)
a.set_yticks([0,M,2*M-2])
a.set_yticklabels([r'$-M$',r'$0$',r'$M$'],fontsize=14)
plt.show()
```
```python
fig,ax = plt.subplots(1,3,figsize=(15,6))
im = ax[0].imshow((ql['Vxy'][:,:,-1]),cmap="RdBu_r",origin="lower",interpolation="bicubic")
im = ax[1].imshow((ce2['Vxy'][:,:,-1]),cmap="RdBu_r",origin="lower",interpolation="bicubic")
im = ax[2].imshow((gce2_0['Vxy'][:,:,-1]),cmap="RdBu_r",origin="lower",interpolation="bicubic")
for a in ax:
a.set_xticks([0,M,2*M-2])
a.set_xticklabels([r'$-M$',r'$0$',r'$M$'],fontsize=14)
a.set_yticks([0,M,2*M-2])
a.set_yticklabels([r'$-M$',r'$0$',r'$M$'],fontsize=14)
plt.show()
```
```python
ql = np.load(dn+"ql_500_r123_nu01.npz",allow_pickle=True)
ce2 = np.load(dn+"ce2_500_r123_nu01.npz",allow_pickle=True)
```
```python
colors = pl.cm.nipy_spectral(np.linspace(0,1,M))
```
```python
fig,ax = plt.subplots(1,2,figsize=(10,5))
colors = pl.cm.nipy_spectral(np.linspace(0,1,M))
ax[0].set_title(f'QL')
for i,x in enumerate(ql['Emtav'].T):
ax[0].plot(ql['t'],x,label=i,c=colors[i])
ax[1].set_title(f'CE2')
for i,x in enumerate(ce2['Emt'].T):
ax[1].plot(ce2['t'],x,label=i,c=colors[i])
for a in ax:
a.set_xlabel(r'$t$',fontsize=14)
a.set_yscale('log')
a.set_ylim(1e-16,1e5)
ax[0].set_ylabel(r'$E(m)$',fontsize=14)
ax[1].legend(bbox_to_anchor=(1.0,0.75),ncol=1)
plt.show()
# plt.savefig(dn+'figures/ze_qlce2_rand.png',bbox_inches='tight')
```
```python
fig,ax = plt.subplots(figsize=(9,3))
Nt = len(ce2['t'])
t = np.linspace(0,500,Nt)
R = moderanks(ce2['mEVs'])
ax.set_title(f'Ranks for modes in Second Cumulant')
for i in np.arange(M-1):
ax.plot(t,R[:,i],label=i+1,c=colors[i+1])
ax.set_xlabel(r'$t$',fontsize=14)
# ax.set_yscale('log')
# ax.set_ylim(1e-21,1e3)
ax.set_xlim(0,500)
ax.set_ylabel(r'$Eigenvalues$',fontsize=14)
ax.legend(loc=4,ncol=1)
# plt.show()
# plt.savefig(dn+'figures/ranks_ce2_rand.png',bbox_inches='tight')
```
```python
ql = np.load(dn+"ql_500_r123_nu03.npz",allow_pickle=True)
ce2 = np.load(dn+"ce2_500_r123_nu03.npz",allow_pickle=True)
```
```python
fig,ax = plt.subplots(1,2,figsize=(10,5))
ax[0].set_title(f'QL')
for i,x in enumerate(ql['Emtav'].T):
ax[0].plot(ql['t'],x,label=i,c=colors[i])
ax[1].set_title(f'CE2')
for i,x in enumerate(ce2['Emt'].T):
ax[1].plot(ce2['t'],x,label=i,c=colors[i])
for a in ax:
a.set_xlabel(r'$t$',fontsize=14)
a.set_yscale('log')
a.set_ylim(1e-16,1e5)
ax[0].set_ylabel(r'$E(m)$',fontsize=14)
ax[1].legend(bbox_to_anchor=(1.0,0.75),ncol=1)
plt.show()
# plt.savefig(dn+'figures/ze_qlce2_rand.png',bbox_inches='tight')
```
```python
```
|
-- Negation and Falsity
variables p q r : Prop
example (hpq : p → q) (hnq : ¬ q) : ¬ p :=
assume hp : p,
show false, from hnq (hpq hp)
example (hp : p) (hnp : ¬ p) : q := false.elim (hnp hp)
example (hp : p) (hnp : ¬ p) : q := absurd hp hnp
example (hnp : ¬ p) (hq : q) (hqp : q → p) : r :=
absurd (hqp hq) hnp
|
(** * StlcProp: Properties of STLC *)
Require Import SF.SfLib.
Require Import SF.Maps.
Require Import SF.Types.
Require Import SF.Stlc.
Require Import SF.Smallstep.
Module STLCProp.
Import STLC.
(** In this chapter, we develop the fundamental theory of the Simply
Typed Lambda Calculus -- in particular, the type safety
theorem. *)
(* ###################################################################### *)
(** * Canonical Forms *)
(** As we saw for the simple calculus in the [Types] chapter, the
first step in establishing basic properties of reduction and types
is to identify the possible _canonical forms_ (i.e., well-typed
closed values) belonging to each type. For [Bool], these are the boolean
values [ttrue] and [tfalse]. For arrow types, the canonical forms
are lambda-abstractions. *)
Lemma canonical_forms_bool : forall t,
empty |- t \in TBool ->
value t ->
(t = ttrue) \/ (t = tfalse).
Proof.
intros t HT HVal.
inversion HVal; intros; subst; try inversion HT; auto.
Qed.
Lemma canonical_forms_fun : forall t T1 T2,
empty |- t \in (TArrow T1 T2) ->
value t ->
exists x u, t = tabs x T1 u.
Proof.
intros t T1 T2 HT HVal.
inversion HVal; intros; subst; try inversion HT; subst; auto.
exists x0. exists t0. auto.
Qed.
(* ###################################################################### *)
(** * Progress *)
(** As before, the _progress_ theorem tells us that closed, well-typed
terms are not stuck: either a well-typed term is a value, or it
can take a reduction step. The proof is a relatively
straightforward extension of the progress proof we saw in the
[Types] chapter. We'll give the proof in English first, then the
formal version. *)
Theorem progress : forall t T,
empty |- t \in T ->
value t \/ exists t', t ==> t'.
(** _Proof_: By induction on the derivation of [|- t \in T].
- The last rule of the derivation cannot be [T_Var], since a
variable is never well typed in an empty context.
- The [T_True], [T_False], and [T_Abs] cases are trivial, since in
each of these cases we can see by inspecting the rule that [t]
is a value.
- If the last rule of the derivation is [T_App], then [t] has the
form [t1 t2] for som e[t1] and [t2], where we know that [t1] and
[t2] are also well typed in the empty context; in particular,
there exists a type [T2] such that [|- t1 \in T2 -> T] and [|-
t2 \in T2]. By the induction hypothesis, either [t1] is a value
or it can take a reduction step.
- If [t1] is a value, then consider [t2], which by the other
induction hypothesis must also either be a value or take a step.
- Suppose [t2] is a value. Since [t1] is a value with an
arrow type, it must be a lambda abstraction; hence [t1
t2] can take a step by [ST_AppAbs].
- Otherwise, [t2] can take a step, and hence so can [t1
t2] by [ST_App2].
- If [t1] can take a step, then so can [t1 t2] by [ST_App1].
- If the last rule of the derivation is [T_If], then [t = if t1
then t2 else t3], where [t1] has type [Bool]. By the IH, [t1]
either is a value or takes a step.
- If [t1] is a value, then since it has type [Bool] it must be
either [true] or [false]. If it is [true], then [t] steps
to [t2]; otherwise it steps to [t3].
- Otherwise, [t1] takes a step, and therefore so does [t] (by
[ST_If]). *)
Proof with eauto.
intros t T Ht.
remember (@empty ty) as Gamma.
induction Ht; subst Gamma...
- (* T_Var *)
(* contradictory: variables cannot be typed in an
empty context *)
inversion H.
- (* T_App *)
(* [t] = [t1 t2]. Proceed by cases on whether [t1] is a
value or steps... *)
right. destruct IHHt1...
+ (* t1 is a value *)
destruct IHHt2...
* (* t2 is also a value *)
assert (exists x0 t0, t1 = tabs x0 T11 t0).
eapply canonical_forms_fun; eauto.
destruct H1 as [x0 [t0 Heq]]. subst.
exists ([x0:=t2]t0)...
* (* t2 steps *)
inversion H0 as [t2' Hstp]. exists (tapp t1 t2')...
+ (* t1 steps *)
inversion H as [t1' Hstp]. exists (tapp t1' t2)...
- (* T_If *)
right. destruct IHHt1...
+ (* t1 is a value *)
destruct (canonical_forms_bool t1); subst; eauto.
+ (* t1 also steps *)
inversion H as [t1' Hstp]. exists (tif t1' t2 t3)...
Qed.
(** **** Exercise: 3 stars, optional (progress_from_term_ind) *)
(** Show that progress can also be proved by induction on terms
instead of induction on typing derivations. *)
Theorem progress' : forall t T,
empty |- t \in T ->
value t \/ exists t', t ==> t'.
Proof.
intros t.
induction t; intros T Ht; auto.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ###################################################################### *)
(** * Preservation *)
(** The other half of the type soundness property is the preservation
of types during reduction. For this, we need to develop some
technical machinery for reasoning about variables and
substitution. Working from top to bottom (from the high-level
property we are actually interested in to the lowest-level
technical lemmas that are needed by various cases of the more
interesting proofs), the story goes like this:
- The _preservation theorem_ is proved by induction on a typing
derivation, pretty much as we did in the [Types] chapter. The
one case that is significantly different is the one for the
[ST_AppAbs] rule, whose definition uses the substitution
operation. To see that this step preserves typing, we need to
know that the substitution itself does. So we prove a...
- _substitution lemma_, stating that substituting a (closed)
term [s] for a variable [x] in a term [t] preserves the type
of [t]. The proof goes by induction on the form of [t] and
requires looking at all the different cases in the definition
of substitition. This time, the tricky cases are the ones for
variables and for function abstractions. In both cases, we
discover that we need to take a term [s] that has been shown
to be well-typed in some context [Gamma] and consider the same
term [s] in a slightly different context [Gamma']. For this
we prove a...
- _context invariance_ lemma, showing that typing is preserved
under "inessential changes" to the context [Gamma] -- in
particular, changes that do not affect any of the free
variables of the term. And finally, for this, we need a
careful definition of...
- the _free variables_ of a term -- i.e., those variables
mentioned in a term and not in the scope of an enclosing
function abstraction binding a variable of the same name.
To make Coq happy, we need to formalize the story in the opposite
order... *)
(* ###################################################################### *)
(** ** Free Occurrences *)
(** A variable [x] _appears free in_ a term _t_ if [t] contains some
occurrence of [x] that is not under an abstraction labeled [x].
For example:
- [y] appears free, but [x] does not, in [\x:T->U. x y]
- both [x] and [y] appear free in [(\x:T->U. x y) x]
- no variables appear free in [\x:T->U. \y:T. x y]
Formally: *)
Inductive appears_free_in : id -> tm -> Prop :=
| afi_var : forall x,
appears_free_in x (tvar x)
| afi_app1 : forall x t1 t2,
appears_free_in x t1 -> appears_free_in x (tapp t1 t2)
| afi_app2 : forall x t1 t2,
appears_free_in x t2 -> appears_free_in x (tapp t1 t2)
| afi_abs : forall x y T11 t12,
y <> x ->
appears_free_in x t12 ->
appears_free_in x (tabs y T11 t12)
| afi_if1 : forall x t1 t2 t3,
appears_free_in x t1 ->
appears_free_in x (tif t1 t2 t3)
| afi_if2 : forall x t1 t2 t3,
appears_free_in x t2 ->
appears_free_in x (tif t1 t2 t3)
| afi_if3 : forall x t1 t2 t3,
appears_free_in x t3 ->
appears_free_in x (tif t1 t2 t3).
Hint Constructors appears_free_in.
(** A term in which no variables appear free is said to be _closed_. *)
Definition closed (t:tm) :=
forall x, ~ appears_free_in x t.
(** **** Exercise: 1 star (afi) *)
(** If the definition of [appears_free_in] is not crystal clear to
you, it is a good idea to take a piece of paper and write out the
rules in informal inference-rule notation. (Although it is a
rather low-level, technical definition, understanding it is
crucial to understanding substitution and its properties, which
are really the crux of the lambda-calculus.) *)
(** [] *)
(* ###################################################################### *)
(** ** Substitution *)
(** To prove that substitution preserves typing, we first need a
technical lemma connecting free variables and typing contexts: If
a variable [x] appears free in a term [t], and if we know [t] is
well typed in context [Gamma], then it must be the case that
[Gamma] assigns a type to [x]. *)
Lemma free_in_context : forall x t T Gamma,
appears_free_in x t ->
Gamma |- t \in T ->
exists T', Gamma x = Some T'.
(** _Proof_: We show, by induction on the proof that [x] appears
free in [t], that, for all contexts [Gamma], if [t] is well
typed under [Gamma], then [Gamma] assigns some type to [x].
- If the last rule used was [afi_var], then [t = x], and from
the assumption that [t] is well typed under [Gamma] we have
immediately that [Gamma] assigns a type to [x].
- If the last rule used was [afi_app1], then [t = t1 t2] and [x]
appears free in [t1]. Since [t] is well typed under [Gamma],
we can see from the typing rules that [t1] must also be, and
the IH then tells us that [Gamma] assigns [x] a type.
- Almost all the other cases are similar: [x] appears free in a
subterm of [t], and since [t] is well typed under [Gamma], we
know the subterm of [t] in which [x] appears is well typed
under [Gamma] as well, and the IH gives us exactly the
conclusion we want.
- The only remaining case is [afi_abs]. In this case [t =
\y:T11.t12], and [x] appears free in [t12]; we also know that
[x] is different from [y]. The difference from the previous
cases is that whereas [t] is well typed under [Gamma], its
body [t12] is well typed under [(Gamma, y:T11)], so the IH
allows us to conclude that [x] is assigned some type by the
extended context [(Gamma, y:T11)]. To conclude that [Gamma]
assigns a type to [x], we appeal to lemma [update_neq], noting
that [x] and [y] are different variables. *)
Proof.
intros x t T Gamma H H0. generalize dependent Gamma.
generalize dependent T.
induction H;
intros; try solve [inversion H0; eauto].
- (* afi_abs *)
inversion H1; subst.
apply IHappears_free_in in H7.
rewrite update_neq in H7; assumption.
Qed.
(** Next, we'll need the fact that any term [t] which is well typed in
the empty context is closed (it has no free variables). *)
(** **** Exercise: 2 stars, optional (typable_empty__closed) *)
Corollary typable_empty__closed : forall t T,
empty |- t \in T ->
closed t.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)
(** Sometimes, when we have a proof [Gamma |- t : T], we will need to
replace [Gamma] by a different context [Gamma']. When is it safe
to do this? Intuitively, it must at least be the case that
[Gamma'] assigns the same types as [Gamma] to all the variables
that appear free in [t]. In fact, this is the only condition that
is needed. *)
Lemma context_invariance : forall Gamma Gamma' t T,
Gamma |- t \in T ->
(forall x, appears_free_in x t -> Gamma x = Gamma' x) ->
Gamma' |- t \in T.
(** _Proof_: By induction on the derivation of
[Gamma |- t \in T].
- If the last rule in the derivation was [T_Var], then [t = x]
and [Gamma x = T]. By assumption, [Gamma' x = T] as well, and
hence [Gamma' |- t \in T] by [T_Var].
- If the last rule was [T_Abs], then [t = \y:T11. t12], with [T
= T11 -> T12] and [Gamma, y:T11 |- t12 \in T12]. The
induction hypothesis is that, for any context [Gamma''], if
[Gamma, y:T11] and [Gamma''] assign the same types to all the
free variables in [t12], then [t12] has type [T12] under
[Gamma'']. Let [Gamma'] be a context which agrees with
[Gamma] on the free variables in [t]; we must show [Gamma' |-
\y:T11. t12 \in T11 -> T12].
By [T_Abs], it suffices to show that [Gamma', y:T11 |- t12 \in
T12]. By the IH (setting [Gamma'' = Gamma', y:T11]), it
suffices to show that [Gamma, y:T11] and [Gamma', y:T11] agree
on all the variables that appear free in [t12].
Any variable occurring free in [t12] must be either [y] or
some other variable. [Gamma, y:T11] and [Gamma', y:T11]
clearly agree on [y]. Otherwise, note that any variable other
than [y] that occurs free in [t12] also occurs free in [t =
\y:T11. t12], and by assumption [Gamma] and [Gamma'] agree on
all such variables; hence so do [Gamma, y:T11] and [Gamma',
y:T11].
- If the last rule was [T_App], then [t = t1 t2], with [Gamma |-
t1 \in T2 -> T] and [Gamma |- t2 \in T2]. One induction
hypothesis states that for all contexts [Gamma'], if [Gamma']
agrees with [Gamma] on the free variables in [t1], then [t1]
has type [T2 -> T] under [Gamma']; there is a similar IH for
[t2]. We must show that [t1 t2] also has type [T] under
[Gamma'], given the assumption that [Gamma'] agrees with
[Gamma] on all the free variables in [t1 t2]. By [T_App], it
suffices to show that [t1] and [t2] each have the same type
under [Gamma'] as under [Gamma]. But all free variables in
[t1] are also free in [t1 t2], and similarly for [t2]; hence
the desired result follows from the induction hypotheses. *)
Proof with eauto.
intros.
generalize dependent Gamma'.
induction H; intros; auto.
- (* T_Var *)
apply T_Var. rewrite <- H0...
- (* T_Abs *)
apply T_Abs.
apply IHhas_type. intros x1 Hafi.
(* the only tricky step... the [Gamma'] we use to
instantiate is [update Gamma x T11] *)
unfold update. unfold t_update. destruct (beq_id x0 x1) eqn: Hx0x1...
rewrite beq_id_false_iff in Hx0x1. auto.
- (* T_App *)
apply T_App with T11...
Qed.
(** Now we come to the conceptual heart of the proof that reduction
preserves types -- namely, the observation that _substitution_
preserves types.
Formally, the so-called _Substitution Lemma_ says this: Suppose we
have a term [t] with a free variable [x], and suppose we've been
able to assign a type [T] to [t] under the assumption that [x] has
some type [U]. Also, suppose that we have some other term [v] and
that we've shown that [v] has type [U]. Then, since [v] satisfies
the assumption we made about [x] when typing [t], we should be
able to substitute [v] for each of the occurrences of [x] in [t]
and obtain a new term that still has type [T]. *)
(** _Lemma_: If [Gamma,x:U |- t \in T] and [|- v \in U], then [Gamma |-
[x:=v]t \in T]. *)
Lemma substitution_preserves_typing : forall Gamma x U t v T,
update Gamma x U |- t \in T ->
empty |- v \in U ->
Gamma |- [x:=v]t \in T.
(** One technical subtlety in the statement of the lemma is that
we assign [v] the type [U] in the _empty_ context -- in other
words, we assume [v] is closed. This assumption considerably
simplifies the [T_Abs] case of the proof (compared to assuming
[Gamma |- v \in U], which would be the other reasonable assumption
at this point) because the context invariance lemma then tells us
that [v] has type [U] in any context at all -- we don't have to
worry about free variables in [v] clashing with the variable being
introduced into the context by [T_Abs].
The substitution lemma can be viewed as a kind of "commutation"
property. Intuitively, it says that substitution and typing can
be done in either order: we can either assign types to the terms
[t] and [v] separately (under suitable contexts) and then combine
them using substitution, or we can substitute first and then
assign a type to [ [x:=v] t ] -- the result is the same either
way.
_Proof_: We show, by induction on [t], that for all [T] and
[Gamma], if [Gamma,x:U |- t \in T] and [|- v \in U], then [Gamma
|- [x:=v]t \in T].
- If [t] is a variable there are two cases to consider,
depending on whether [t] is [x] or some other variable.
- If [t = x], then from the fact that [Gamma, x:U |- x \in
T] we conclude that [U = T]. We must show that [[x:=v]x =
v] has type [T] under [Gamma], given the assumption that
[v] has type [U = T] under the empty context. This
follows from context invariance: if a closed term has type
[T] in the empty context, it has that type in any context.
- If [t] is some variable [y] that is not equal to [x], then
we need only note that [y] has the same type under [Gamma,
x:U] as under [Gamma].
- If [t] is an abstraction [\y:T11. t12], then the IH tells us,
for all [Gamma'] and [T'], that if [Gamma',x:U |- t12 \in T']
and [|- v \in U], then [Gamma' |- [x:=v]t12 \in T'].
The substitution in the conclusion behaves differently
depending on whether [x] and [y] are the same variable.
First, suppose [x = y]. Then, by the definition of
substitution, [[x:=v]t = t], so we just need to show [Gamma |-
t \in T]. But we know [Gamma,x:U |- t : T], and, since [y]
does not appear free in [\y:T11. t12], the context invariance
lemma yields [Gamma |- t \in T].
Second, suppose [x <> y]. We know [Gamma,x:U,y:T11 |- t12 \in
T12] by inversion of the typing relation, from which
[Gamma,y:T11,x:U |- t12 \in T12] follows by the context
invariance lemma, so the IH applies, giving us [Gamma,y:T11 |-
[x:=v]t12 \in T12]. By [T_Abs], [Gamma |- \y:T11. [x:=v]t12
\in T11->T12], and by the definition of substitution (noting
that [x <> y]), [Gamma |- \y:T11. [x:=v]t12 \in T11->T12] as
required.
- If [t] is an application [t1 t2], the result follows
straightforwardly from the definition of substitution and the
induction hypotheses.
- The remaining cases are similar to the application case.
One more technical note: This proof is a rare case where an
induction on terms, rather than typing derivations, yields a
simpler argument. The reason for this is that the assumption
[update Gamma x U |- t \in T] is not completely generic, in the
sense that one of the "slots" in the typing relation -- namely the
context -- is not just a variable, and this means that Coq's
native induction tactic does not give us the induction hypothesis
that we want. It is possible to work around this, but the needed
generalization is a little tricky. The term [t], on the other
hand, _is_ completely generic. *)
Proof with eauto.
intros Gamma x U t v T Ht Ht'.
generalize dependent Gamma. generalize dependent T.
induction t; intros T Gamma H;
(* in each case, we'll want to get at the derivation of H *)
inversion H; subst; simpl...
- (* tvar *)
rename i into y. destruct (beq_idP x y) as [Hxy|Hxy].
+ (* x=y *)
subst.
rewrite update_eq in H2.
inversion H2; subst. clear H2.
eapply context_invariance... intros x Hcontra.
destruct (free_in_context _ _ T empty Hcontra) as [T' HT']...
inversion HT'.
+ (* x<>y *)
apply T_Var. rewrite update_neq in H2...
- (* tabs *)
rename i into y. apply T_Abs.
destruct (beq_idP x y) as [Hxy | Hxy].
+ (* x=y *)
subst.
eapply context_invariance...
intros x Hafi. unfold update, t_update.
destruct (beq_id y x) eqn: Hyx...
+ (* x<>y *)
apply IHt. eapply context_invariance...
intros z Hafi. unfold update, t_update.
destruct (beq_idP y z) as [Hyz | Hyz]; subst; trivial.
rewrite <- beq_id_false_iff in Hxy.
rewrite Hxy...
Qed.
(* ###################################################################### *)
(** ** Main Theorem *)
(** We now have the tools we need to prove preservation: if a closed
term [t] has type [T] and takes a step to [t'], then [t']
is also a closed term with type [T]. In other words, the small-step
reduction relation preserves types. *)
Theorem preservation : forall t t' T,
empty |- t \in T ->
t ==> t' ->
empty |- t' \in T.
(** _Proof_: By induction on the derivation of [|- t \in T].
- We can immediately rule out [T_Var], [T_Abs], [T_True], and
[T_False] as the final rules in the derivation, since in each of
these cases [t] cannot take a step.
- If the last rule in the derivation was [T_App], then [t = t1
t2]. There are three cases to consider, one for each rule that
could have been used to show that [t1 t2] takes a step to [t'].
- If [t1 t2] takes a step by [ST_App1], with [t1] stepping to
[t1'], then by the IH [t1'] has the same type as [t1], and
hence [t1' t2] has the same type as [t1 t2].
- The [ST_App2] case is similar.
- If [t1 t2] takes a step by [ST_AppAbs], then [t1 =
\x:T11.t12] and [t1 t2] steps to [[x:=t2]t12]; the
desired result now follows from the fact that substitution
preserves types.
- If the last rule in the derivation was [T_If], then [t = if t1
then t2 else t3], and there are again three cases depending on
how [t] steps.
- If [t] steps to [t2] or [t3], the result is immediate, since
[t2] and [t3] have the same type as [t].
- Otherwise, [t] steps by [ST_If], and the desired conclusion
follows directly from the induction hypothesis. *)
Proof with eauto.
remember (@empty ty) as Gamma.
intros t t' T HT. generalize dependent t'.
induction HT;
intros t' HE; subst Gamma; subst;
try solve [inversion HE; subst; auto].
- (* T_App *)
inversion HE; subst...
(* Most of the cases are immediate by induction,
and [eauto] takes care of them *)
+ (* ST_AppAbs *)
apply substitution_preserves_typing with T11...
inversion HT1...
Qed.
(** **** Exercise: 2 stars, recommended (subject_expansion_stlc) *)
(** An exercise in the [Types] chapter asked about the subject
expansion property for the simple language of arithmetic and
boolean expressions. Does this property hold for STLC? That is,
is it always the case that, if [t ==> t'] and [has_type t' T],
then [empty |- t \in T]? If so, prove it. If not, give a
counter-example not involving conditionals.
(* FILL IN HERE *)
[]
*)
(* ###################################################################### *)
(** * Type Soundness *)
(** **** Exercise: 2 stars, optional (type_soundness) *)
(** Put progress and preservation together and show that a well-typed
term can _never_ reach a stuck state. *)
Definition stuck (t:tm) : Prop :=
(normal_form step) t /\ ~ value t.
Corollary soundness : forall t t' T,
empty |- t \in T ->
t ==>* t' ->
~(stuck t').
Proof.
intros t t' T Hhas_type Hmulti. unfold stuck.
intros [Hnf Hnot_val]. unfold normal_form in Hnf.
induction Hmulti.
(* FILL IN HERE *) Admitted.
(** [] *)
(* ###################################################################### *)
(** * Uniqueness of Types *)
(** **** Exercise: 3 stars (types_unique) *)
(** Another nice property of the STLC is that types are unique: a
given term (in a given context) has at most one type. *)
(** Formalize this statement and prove it. *)
(* FILL IN HERE *)
(** [] *)
(* ###################################################################### *)
(** * Additional Exercises *)
(** **** Exercise: 1 star (progress_preservation_statement) *)
(** Without peeking at their statements above, write down the progress
and preservation theorems for the simply typed lambda-calculus. *)
(** [] *)
(** **** Exercise: 2 stars (stlc_variation1) *)
(** Suppose we add a new term [zap] with the following reduction rule
--------- (ST_Zap)
t ==> zap
and the following typing rule:
---------------- (T_Zap)
Gamma |- zap : T
Which of the following properties of the STLC remain true in
the presence of these rules? For each property, write either
"remains true" or "becomes false." If a property becomes
false, give a counterexample.
- Determinism of [step]
- Progress
- Preservation
[]
*)
(** **** Exercise: 2 stars (stlc_variation2) *)
(** Suppose instead that we add a new term [foo] with the following
reduction rules:
----------------- (ST_Foo1)
(\x:A. x) ==> foo
------------ (ST_Foo2)
foo ==> true
Which of the following properties of the STLC remain true in
the presence of this rule? For each one, write either
"remains true" or else "becomes false." If a property becomes
false, give a counterexample.
- Determinism of [step]
- Progress
- Preservation
[]
*)
(** **** Exercise: 2 stars (stlc_variation3) *)
(** Suppose instead that we remove the rule [ST_App1] from the [step]
relation. Which of the following properties of the STLC remain
true in the presence of this rule? For each one, write either
"remains true" or else "becomes false." If a property becomes
false, give a counterexample.
- Determinism of [step]
- Progress
- Preservation
[]
*)
(** **** Exercise: 2 stars, optional (stlc_variation4) *)
(** Suppose instead that we add the following new rule to the
reduction relation:
---------------------------------- (ST_FunnyIfTrue)
(if true then t1 else t2) ==> true
Which of the following properties of the STLC remain true in
the presence of this rule? For each one, write either
"remains true" or else "becomes false." If a property becomes
false, give a counterexample.
- Determinism of [step]
- Progress
- Preservation
*)
(** **** Exercise: 2 stars, optional (stlc_variation5) *)
(** Suppose instead that we add the following new rule to the typing
relation:
Gamma |- t1 \in Bool->Bool->Bool
Gamma |- t2 \in Bool
------------------------------ (T_FunnyApp)
Gamma |- t1 t2 \in Bool
Which of the following properties of the STLC remain true in
the presence of this rule? For each one, write either
"remains true" or else "becomes false." If a property becomes
false, give a counterexample.
- Determinism of [step]
- Progress
- Preservation
*)
(** **** Exercise: 2 stars, optional (stlc_variation6) *)
(** Suppose instead that we add the following new rule to the typing
relation:
Gamma |- t1 \in Bool
Gamma |- t2 \in Bool
--------------------- (T_FunnyApp')
Gamma |- t1 t2 \in Bool
Which of the following properties of the STLC remain true in
the presence of this rule? For each one, write either
"remains true" or else "becomes false." If a property becomes
false, give a counterexample.
- Determinism of [step]
- Progress
- Preservation
*)
(** **** Exercise: 2 stars, optional (stlc_variation7) *)
(** Suppose we add the following new rule to the typing relation
of the STLC:
------------------- (T_FunnyAbs)
|- \x:Bool.t \in Bool
Which of the following properties of the STLC remain true in
the presence of this rule? For each one, write either
"remains true" or else "becomes false." If a property becomes
false, give a counterexample.
- Determinism of [step]
- Progress
- Preservation
[]
*)
End STLCProp.
(* ###################################################################### *)
(* ###################################################################### *)
(** ** Exercise: STLC with Arithmetic *)
(** To see how the STLC might function as the core of a real
programming language, let's extend it with a concrete base
type of numbers and some constants and primitive
operators. *)
Module STLCArith.
(** To types, we add a base type of natural numbers (and remove
booleans, for brevity). *)
Inductive ty : Type :=
| TArrow : ty -> ty -> ty
| TNat : ty.
(** To terms, we add natural number constants, along with
successor, predecessor, multiplication, and zero-testing. *)
Inductive tm : Type :=
| tvar : id -> tm
| tapp : tm -> tm -> tm
| tabs : id -> ty -> tm -> tm
| tnat : nat -> tm
| tsucc : tm -> tm
| tpred : tm -> tm
| tmult : tm -> tm -> tm
| tif0 : tm -> tm -> tm -> tm.
(** **** Exercise: 4 stars (stlc_arith) *)
(** Finish formalizing the definition and properties of the STLC extended
with arithmetic. Specifically:
- Copy the whole development of STLC that we went through above (from
the definition of values through the Type Soundness theorem), and
paste it into the file at this point.
- Extend the definitions of the [subst] operation and the [step]
relation to include appropriate clauses for the arithmetic operators.
- Extend the proofs of all the properties (up to [soundness]) of
the original STLC to deal with the new syntactic forms. Make
sure Coq accepts the whole file. *)
(* FILL IN HERE *)
(** [] *)
End STLCArith.
(** $Date: 2016-05-26 16:17:19 -0400 (Thu, 26 May 2016) $ *)
|
import numpy as np
import numpy.testing as npt
import Games
def test_Games_smoke():
#Smoke_test
obt = Games.Games_object()
def test_Games_object_fizz():
#test the fizz_function
obj = Games.Games_object()
output = obj.fizz()
npt.assert_equal(output, "buzz")
|
#pragma once
#ifndef TABLESTORE_UTIL_MEMPOOL_HPP
#define TABLESTORE_UTIL_MEMPOOL_HPP
/*
BSD 3-Clause License
Copyright (c) 2017, Alibaba Cloud
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "tablestore/util/random.hpp"
#include "tablestore/util/mempiece.hpp"
#include "tablestore/util/optional.hpp"
#include "tablestore/util/move.hpp"
#include <boost/atomic.hpp>
#include <memory>
#include <vector>
#include <string>
#include <stdint.h>
namespace aliyun {
namespace tablestore {
namespace util {
class MemPool
{
public:
static const int64_t kBlockSize = 1024 * 1024;
public:
class Block
{
public:
explicit Block(MemPool&);
virtual ~Block() {}
virtual MemPiece piece() const =0;
virtual MutableMemPiece mutablePiece() =0;
MemPool& mutableMemPool()
{
return mMemPool;
}
protected:
MemPool& mMemPool;
};
class BlockHolder
{
private:
BlockHolder(const BlockHolder&); // =delete
BlockHolder& operator=(const BlockHolder&); // =delete
public:
explicit BlockHolder()
: mInner(NULL)
{}
~BlockHolder();
explicit BlockHolder(Block* blk)
: mInner(blk)
{
OTS_ASSERT(blk != NULL);
}
explicit BlockHolder(const MoveHolder<BlockHolder>& a)
{
*this = a;
}
BlockHolder& operator=(const MoveHolder<BlockHolder>& a);
MemPiece piece() const;
MutableMemPiece mutablePiece();
void giveBack();
Block* transfer()
{
Block* res = mInner;
mInner = NULL;
return res;
}
private:
Block* mInner;
};
virtual ~MemPool() {}
/**
* Borrows a block from the pool, thread-safely.
*/
virtual Block* borrow() =0;
struct Stats
{
int64_t mTotalBlocks;
int64_t mAvailableBlocks;
int64_t mBorrowedBlocks;
explicit Stats()
: mTotalBlocks(0),
mAvailableBlocks(0),
mBorrowedBlocks(0)
{}
void prettyPrint(std::string&) const;
};
/**
* Returns some infomation about the pool, thread-safely.
*/
virtual Stats stats() const =0;
protected:
virtual void giveBack(Block*) =0;
};
/**
* A memory pool. When its pool is exhausted, new block will be allocated.
*/
class IncrementalMemPool: public MemPool
{
private:
static const int64_t kInitBlocks = 32;
IncrementalMemPool(const IncrementalMemPool&); // =delete
IncrementalMemPool& operator=(const IncrementalMemPool&); // =delete
public:
explicit IncrementalMemPool();
~IncrementalMemPool();
Block* borrow();
Stats stats() const;
protected:
void giveBack(Block*);
public:
/// for internal use only
template<int Size>
struct ThisInnerBlock: public Block
{
uint8_t mContent[Size];
explicit ThisInnerBlock(IncrementalMemPool& mpool)
: Block(mpool)
{}
MemPiece piece() const
{
return MemPiece(mContent, Size);
}
MutableMemPiece mutablePiece()
{
return MutableMemPiece(mContent, Size);
}
};
typedef ThisInnerBlock<kBlockSize - sizeof(ThisInnerBlock<0>)> MyInnerBlock;
class BlockFreeQueue
{
public:
virtual ~BlockFreeQueue() {}
virtual bool push(MyInnerBlock*) =0;
virtual bool pop(MyInnerBlock**) =0;
};
private:
boost::atomic<int64_t> mTotalBlocks;
boost::atomic<int64_t> mBorrowedBlocks;
std::auto_ptr<BlockFreeQueue> mAvailableBlocks;
};
class StrPool
{
public:
explicit StrPool();
~StrPool();
struct Stats
{
int64_t mTotal;
int64_t mAvailable;
int64_t mBorrowed;
explicit Stats()
: mTotal(0),
mAvailable(0),
mBorrowed(0)
{}
void prettyPrint(std::string&) const;
};
Stats stats() const;
std::string* borrow();
void giveBack(std::string*);
public:
// for private use
/**
* An interface to thread-safe queues on strings.
*/
class IQueue
{
public:
virtual ~IQueue() {}
virtual void push(std::string*) =0;
virtual std::string* pop() =0;
virtual int64_t size() const =0;
};
private:
boost::atomic<int64_t> mBorrowed;
std::auto_ptr<IQueue> mAvailable;
};
} // namespace util
} // namespace tablestore
} // namespace aliyun
#endif
|
#pragma once
#include <torch/torch.h>
#include <opencv2/opencv.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/algorithm/string/split.hpp>
#include <stack>
#include <string>
#include <fstream>
#ifdef _MSC_VER
#include <filesystem>
namespace fs = std::filesystem;
#else
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
#endif
struct SwishImpl : torch::nn::Module
{
auto forward(const torch::Tensor& x) -> torch::Tensor
{
return x * torch::sigmoid(x);
}
};
TORCH_MODULE_IMPL(Swish, SwishImpl);
struct HardSwishImpl : torch::nn::Module
{
auto forward(const torch::Tensor& x) -> torch::Tensor
{
return x * torch::nn::functional::hardtanh(x + 3, torch::nn::HardtanhOptions{}.min_val(0.).max_val(6.).inplace(true)) / 6.;
}
};
TORCH_MODULE_IMPL(HardSwish, HardSwishImpl);
//struct MishImpl : torch::nn::Module
//{
// auto forward(const torch::Tensor& x) -> torch::Tensor
// {
// return x * torch::nn::functional::softplus(x).tanh();
// }
//};
//TORCH_MODULE_IMPL(Mish, MishImpl);
//struct SigmoidImpl : torch::nn::Module
//{
// auto forward(const torch::Tensor& x) -> torch::Tensor
// {
// return x.sigmoid();
// }
//};
//TORCH_MODULE_IMPL(Sigmoid, SigmoidImpl);
struct ConcatImpl : torch::nn::Module
{
ConcatImpl(uint32_t dimension = 1)
: _dimension{dimension}
{}
auto forward(const torch::Tensor& x) -> torch::Tensor
{
return torch::cat(x, 1);
}
uint32_t _dimension{};
};
TORCH_MODULE_IMPL(Concat, ConcatImpl);
struct FeatureConcatImpl : torch::nn::Module
{
FeatureConcatImpl(std::vector<int32_t> const& layers)
: _layers{layers}
{}
auto forward(torch::Tensor const& x, std::vector<torch::Tensor> const& outputs) -> torch::Tensor
{
switch(_layers.size())
{
case 2:
return torch::cat({outputs[_layers[0]], outputs[_layers[1]]}, 1);
case 3:
return torch::cat({outputs[_layers[0]], outputs[_layers[1]], outputs[_layers[2]]}, 1);
case 4:
return torch::cat({outputs[_layers[0]], outputs[_layers[1]], outputs[_layers[2]], outputs[_layers[3]]}, 1);
case 1:
default:
return torch::cat(outputs[_layers[0]]);
break;
}
return {};
}
std::vector<int32_t> _layers{};
};
TORCH_MODULE_IMPL(FeatureConcat, FeatureConcatImpl);
class DarknetParser {
public:
DarknetParser(std::string const& path)
: _path{path}
{
if (_path.substr(_path.size()-4) != ".cfg")
{
_path += ".cfg";
}
if (!fs::exists(_path) &&
fs::exists("cfg/" + _path))
{
_path = "cfg/" + _path;
}
std::ifstream cfgFile(_path);
std::string line;
while (std::getline(cfgFile, line))
{
boost::trim(line);
if (line.empty() || (line[0] == '#'))
{
continue;
}
if (line[0] == '[')
{
auto item = std::make_pair(line.substr(1, line.size() - 2), std::map<std::string, std::string>{std::make_pair("batch_normalize", "0")});
mdefs.push_back(item);
}
else
{
std::vector<std::string> keyVal;
boost::split(keyVal, line, boost::is_any_of("="));
boost::trim(keyVal[0]);
boost::trim(keyVal[1]);
if (keyVal[0] == "anchors")
{
}
else if (false)
{
}
else
{
mdefs.back().second[keyVal[0]] = keyVal[1];
}
}
}
auto supported = std::vector<std::string>{"type", "batch_normalize", "filters", "size", "stride", "pad", "activation", "layers", "groups",
"from", "mask", "anchors", "classes", "num", "jitter", "ignore_thresh", "truth_thresh", "random",
"stride_x", "stride_y", "weights_type", "weights_normalization", "scale_x_y", "beta_nms", "nms_kind",
"iou_loss", "iou_normalizer", "cls_normalizer", "iou_thresh", "probability"};
}
auto createModules(cv::Size const& size, std::string const& cfg) -> std::pair<torch::nn::ModuleList, std::vector<bool>>
{
using namespace torch::nn;
uint32_t channels = std::atoi(mdefs[0].second["channels"].c_str());
auto momentum = std::atof(mdefs[0].second["momentum"].c_str());
auto eps = std::atof(mdefs[0].second["eps"].c_str());
std::vector<int32_t> routs;
auto output_filters = std::vector<uint32_t>{channels};
uint32_t filters = 0;
ModuleList moduleList;
bool upsamplePrev = false;
for (auto i = 1U; i < mdefs.size(); ++i)
{
auto& mdef = mdefs[i].second;
auto const& type = mdefs[i].first;
Sequential modules;
if (type == "convolutional")
{
auto bn = static_cast<bool>(std::atoi(mdef["batch_normalize"].c_str()));
filters = std::atoi(mdef["filters"].c_str());
auto k = std::atoi(mdef["size"].c_str());
auto stride_x = mdef.count("stride") ? std::atoi(mdef["stride"].c_str()) : std::atoi(mdef["stride_x"].c_str());
auto stride_y = mdef.count("stride") ? std::atoi(mdef["stride"].c_str()) : std::atoi(mdef["stride_y"].c_str());
//if (isinstance(k, int))
{ // single-size conv
if (upsamplePrev)
{
output_filters.back() /= 2;
}
modules->push_back("Conv2d",
Conv2d(Conv2dOptions(output_filters.back(), filters, k)
.stride({stride_x, stride_y})
.padding(mdef.count("pad") ? (k / 2) : 0)
.groups(mdef.count("groups") ? std::atoi(mdef["groups"].c_str()) : 1)
.bias(!bn)));
if (upsamplePrev)
{
filters *= 2;
upsamplePrev = false;
}
}
// else
// { // multiple-size conv
// modules->push_back("MixConv2d",
// MixConv2d(in_ch = output_filters[-1], out_ch = filters, k = k, stride = stride, bias = not bn));
// }
if (bn)
{
modules->push_back("BatchNorm2d", BatchNorm2d(BatchNorm2dOptions{filters}.momentum(momentum).eps(eps)));
}
else
{
// ???
//routs.append(i);
}
if (mdef["activation"] == "leaky")
{
// activation study https://github.com/ultralytics/yolov3/issues/441
modules->push_back("activation", LeakyReLU(LeakyReLUOptions{}.negative_slope(0.1).inplace(true)));
}
else if (mdef["activation"] == "swish")
{
modules->push_back("activation", Swish());
}
else if (mdef["activation"] == "mish")
{
modules->push_back("activation", Mish());
}
else if (mdef["activation"] == "relu")
{
modules->push_back("activation", ReLU(ReLUOptions{}.inplace(true)));
}
else if (mdef["activation"] == "logistic")
{
modules->push_back("activation", Sigmoid{});
}
}
else if (type == "BatchNorm2d")
{
filters = output_filters.back();
modules->push_back(BatchNorm2d(BatchNorm2dOptions{filters}.momentum(0.03).eps(1e-4)));
//moduleList->push_back(BatchNorm2d(BatchNorm2dOptions{filters}.momentum(0.03).eps(1e-4)));
if ((i == 0) && (filters == 3))
{
//modules->runnimg_mean = Tensor({0.485, 0.456, 0.406});
//modules->running_var = Tensor({0.0524, 0.0502, 0.0506});
}
}
else if (type == "maxpool")
{
auto k = std::atoi(mdef["size"].c_str());
auto stride = std::atoi(mdef["stride"].c_str());
if ((k == 2) && (stride == 1)) // yolov3-tiny
{
modules->push_back("ZeroPad2d", ZeroPad2d(ZeroPad2dOptions{{0, 1, 0, 1}}));
//moduleList->push_back(ZeroPad2d(ZeroPad2dOptions{{0, 1, 0, 1}}));
}
//moduleList->push_back(MaxPool2d(MaxPool2dOptions{k}.stride(stride).padding((k - 1) / 2)));
modules->push_back("MaxPool2d", MaxPool2d(MaxPool2dOptions{k}.stride(stride).padding((k - 1) / 2)));
}
else if (type == "upsample")
{
// if (ONNX_EXPORT) // explicitly state size, avoid scale_factor
// {
// auto g = ((yolo_index + 1) * 2) / 32; // gain
// // img_size = (320, 192)
// modules->push_back(Upsample{UpsampleOptions{size=tuple(int(x * g) for x in img_size)}});
// }
// else
{
double scale_factor = std::atof(mdef["stride"].c_str());
//moduleList->push_back(Upsample{UpsampleOptions{}.scale_factor({{scale_factor}})});
modules->push_back("Upsample", Upsample{UpsampleOptions{}.scale_factor({{scale_factor, scale_factor}}).mode(torch::kBilinear).align_corners(true)});
upsamplePrev = true;
//modules->push_back("Conv2d", Conv2d{Conv2dOptions{output_filters.back(), filters/2, 3}.stride({1,1}).padding({1, 1})});
}
}
else if (type == "convolution_transpose")
{
modules->push_back("ConvTranspose2d", ConvTranspose2d(ConvTranspose2dOptions{output_filters.back(), filters/2, 2}.stride(2)));
}
else if (type == "route") // Sequential() placeholder for 'route' layer
{
std::vector<std::string> layersStr;
boost::split(layersStr, mdef["layers"], boost::is_any_of(","));
std::vector<int32_t> layers;
for (auto layerStr : layersStr)
{
layers.emplace_back(std::atoi(layerStr.c_str()));
}
auto sum = 0;
for (auto l : layers)
{
sum += output_filters[l > 0 ? l + 1 : i + l];
routs.push_back(l < 0 ? i + l - 1 : l - 1);
}
for (auto& l : layers)
{
l += i - 1;
}
moduleList->push_back(FeatureConcat(layers));
}
else if (type == "shortcut") // Sequential() placeholder for 'shortcut' layer
{
//layers = mdef['from']
//filters = output_filters[-1]
//routs.extend([i + l if l < 0 else l for l in layers])
//modules = WeightedFeatureFusion(layers=layers, weight='weights_type' in mdef)
}
else if (type == "reorg3d") // yolov3-spp-pan-scale
{
//pass
}
else if (type == "yolo")
{
// TODO:
}
else if (type == "dropout")
{
auto perc = std::atof(mdef["probability"].c_str());
modules->push_back(Dropout{DropoutOptions{perc}});
}
else
{
std::cout << "Warning: Unrecognized Layer Type: " << type << std::endl;
}
// Register module list and number of output filters
if (!modules->is_empty())
{
moduleList->push_back(modules);
}
output_filters.push_back(upsamplePrev ? filters*2 : filters);
}
auto routs_binary = std::vector<bool>(mdefs.size() + 1, false);
for (auto const& i : routs)
{
routs_binary[i] = true;
}
return std::make_pair(moduleList, routs_binary);
}
private:
std::string _path;
std::vector<std::pair<std::string, std::map<std::string, std::string>>> mdefs;
};
struct DarknetImpl : torch::nn::Module
{
DarknetImpl(std::string const& cfg, cv::Size size, bool verbose = false)
{
std::tie(_moduleList, _routs) = DarknetParser(cfg).createModules(size, cfg);
register_module("unet", _moduleList);
}
auto forward(torch::Tensor x) -> torch::Tensor
{
using namespace torch::nn;
auto img_size = cv::Size(x.size(2), x.size(3));
std::vector<torch::Tensor> outs;
for (auto i = 0U; i < _moduleList->size(); ++i)
{
if (auto featureConcat = std::dynamic_pointer_cast<FeatureConcatImpl>(_moduleList[i]))
{
// auto l = featureConcat->_layers;
// std::cout << "Concat: ";
// for (auto const& item : l)
// {
// std::cout << item << ", ";
// }
// std::cout << std::endl;
x = featureConcat->forward(x, outs);
}
else if (auto sequential = std::dynamic_pointer_cast<SequentialImpl>(_moduleList[i]))
{
x = sequential->forward(x);
}
outs.push_back(_routs[i] ? x : torch::Tensor{});
}
return x;
}
void load_weights(std::string const& darknetWeightsFile)
{
using namespace torch::nn;
if (!fs::exists(darknetWeightsFile + ".pt"))
{
std::cout << "Skip loading weights since not found!" << std::endl;
return;
}
torch::load(_moduleList, darknetWeightsFile + ".pt");
#if 0
auto file = std::ifstream(darknetWeightsFile, std::ios::binary);
int32_t version[3] = {};
int64_t seen = {};
file.read((char*)&version, sizeof(int32_t)*3);
file.read((char*)&seen, sizeof(int64_t));
for (auto i = 0U; i < _moduleList->size(); ++i)
{
auto submodules = _moduleList[i]->modules(false);
for (auto j = 0U; j < submodules.size(); j++)
{
std::cout << submodules[j]->name() << std::endl;
if (submodules[j]->name() == "torch::nn::Conv2dImpl")
{
std::cout << "Conv2d: " << std::endl;
bool bnFlag = false;
if (((j + 1) < submodules.size()) &&
(submodules[j + 1]->name() == "torch::nn::BatchNorm2dImpl"))
{
auto bn = std::dynamic_pointer_cast<BatchNorm2dImpl>(submodules[j + 1]);
if (bn != nullptr)
{
std::cout << "\tLoading batch norm 2d" << std::endl;
auto batchNorm2dBias = bn->bias.data_ptr();
auto batchNorm2dWeights = bn->weight.data_ptr();
auto batchNorm2dRunningMean = bn->running_mean.data_ptr();
auto batchNorm2dRunningVar = bn->running_var.data_ptr();
std::cout << "\t\tbn->bias.nbytes(): " << bn->bias.nbytes() << std::endl;
std::cout << "\t\tbn->weight.nbytes(): " << bn->weight.nbytes() << std::endl;
std::cout << "\t\tbn->running_mean.nbytes(): " << bn->running_mean.nbytes() << std::endl;
std::cout << "\t\tbn->running_var.nbytes(): " << bn->running_var.nbytes() << std::endl;
file.readsome((char*)batchNorm2dBias, bn->bias.nbytes());
file.readsome((char*)batchNorm2dWeights, bn->weight.nbytes());
file.readsome((char*)batchNorm2dRunningMean, bn->running_mean.nbytes());
file.readsome((char*)batchNorm2dRunningVar, bn->running_var.nbytes());
bn->bias = bn->bias.cuda();
bn->weight = bn->weight.cuda();
bn->running_mean = bn->running_mean.cuda();
bn->running_var = bn->running_var.cuda();
//bn->bias.set_data(batchNorm2dBias);
//bn->weight.set_data(batchNorm2dWeights);
//bn->running_mean.set_data(batchNorm2dRunningMean);
//bn->running_var.set_data(batchNorm2dRunningVar);
bnFlag = true;
}
}
auto conv2d = std::dynamic_pointer_cast<Conv2dImpl>(submodules[j]);
if (!bnFlag)
{
std::cout << "\tLoading bias: " << std::endl;
auto conv2dBias = conv2d->bias.data_ptr();
std::cout << "\t\tconv2d->bias.nbytes(): " << conv2d->bias.nbytes() << std::endl;
file.readsome((char*)conv2dBias, conv2d->bias.nbytes());
conv2d->bias = conv2d->bias.cuda();
//conv2d->bias.set_data(conv2dBias);
}
std::cout << "\tLoading weights: " << std::endl;
auto conv2dWeights = conv2d->weight.data_ptr();
std::cout << "\t\tconv2d->weight.nbytes(): " << conv2d->weight.nbytes() << std::endl;
file.readsome((char*)conv2dWeights, conv2d->weight.nbytes());
conv2d->weight = conv2d->weight.cuda();
//conv2d->weight.set_data(conv2dWeights);
}
}
}
#endif
}
void save_weights(std::string const& darknetWeightsFile)
{
using namespace torch::nn;
auto const dir = fs::path(darknetWeightsFile).remove_filename().string();
fs::create_directories(dir);
torch::save(_moduleList, darknetWeightsFile + ".pt");
auto file = std::ofstream(darknetWeightsFile, std::ios::binary);
int32_t version[3] = {0, 2, 5};
int64_t seen = {0};
file.write((char*)&version, sizeof(int32_t)*3);
file.write((char*)&seen, sizeof(int64_t));
for (auto i = 0U; i < _moduleList->size(); ++i)
{
auto submodules = _moduleList[i]->modules(false);
for (auto j = 0U; j < submodules.size(); j++)
{
//std::cout << submodules[j]->name() << std::endl;
if (submodules[j]->name() == "torch::nn::Conv2dImpl")
{
//std::cout << "Conv2d: " << std::endl;
bool bnFlag = false;
if (((j + 1) < submodules.size()) &&
(submodules[j + 1]->name() == "torch::nn::BatchNorm2dImpl"))
{
auto bn = std::dynamic_pointer_cast<BatchNorm2dImpl>(submodules[j + 1]);
if (bn != nullptr)
{
//std::cout << "\tSaving batch norm 2d" << std::endl;
auto batchNorm2dBias = bn->bias.data().cpu();
auto batchNorm2dWeights = bn->weight.data().cpu();
auto batchNorm2dRunningMean = bn->running_mean.data().cpu();
auto batchNorm2dRunningVar = bn->running_var.data().cpu();
//std::cout << "\t\tbatchNorm2dBias.nbytes(): " << batchNorm2dBias.nbytes() << std::endl;
//std::cout << "\t\tbatchNorm2dWeights.nbytes(): " << batchNorm2dWeights.nbytes() << std::endl;
//std::cout << "\t\tbatchNorm2dRunningMean.nbytes(): " << batchNorm2dRunningMean.nbytes() << std::endl;
//std::cout << "\t\tbatchNorm2dRunningVar.nbytes(): " << batchNorm2dRunningVar.nbytes() << std::endl;
file.write((char*)batchNorm2dBias.data_ptr(), batchNorm2dBias.nbytes());
file.write((char*)batchNorm2dWeights.data_ptr(), batchNorm2dWeights.nbytes());
file.write((char*)batchNorm2dRunningMean.data_ptr(), batchNorm2dRunningMean.nbytes());
file.write((char*)batchNorm2dRunningVar.data_ptr(), batchNorm2dRunningVar.nbytes());
bnFlag = true;
}
}
auto conv2d = std::dynamic_pointer_cast<Conv2dImpl>(submodules[j]);
if (!bnFlag)
{
//std::cout << "\tSaving bias: " << std::endl;
auto conv2dBias = conv2d->bias.data().cpu();
//std::cout << "\t\tconv2dBias.nbytes(): " << conv2dBias.nbytes() << std::endl;
file.write((char*)conv2dBias.data_ptr(), conv2dBias.nbytes());
}
//std::cout << "\tSaving weights: " << std::endl;
auto conv2dWeights = conv2d->weight.data().cpu();
//std::cout << "\t\tconv2dWeights.nbytes(): " << conv2dWeights.nbytes() << std::endl;
file.write((char*)conv2dWeights.data_ptr(), conv2dWeights.nbytes());
}
}
}
}
torch::nn::ModuleList _moduleList;
std::vector<bool> _routs;
};
TORCH_MODULE_IMPL(Darknet, DarknetImpl);
|
lemma closure_Int_ball_not_empty: assumes "S \<subseteq> closure T" "x \<in> S" "r > 0" shows "T \<inter> ball x r \<noteq> {}"
|
\chapter{List of Publications}
% All citations are sill stored in mythesis.bib
% Journal Publications
\paperlist[Journal Publications]{goossens93,test}
% Conference Publications
\paperlist[Conference Publications]{goossens93,test}
% You can add customized title name in the []
|
% DETECTOR
% See also
%
% Please see acfReadme for an overview of the detection code.
%
% Aggregate channel features object detector:
% acfDemoCal - Demo for aggregate channel features object detector on Caltech dataset.
% acfDemoInria - Demo for aggregate channel features object detector on Inria dataset.
% acfDetect - Run aggregate channel features object detector on given image(s).
% acfModify - Modify aggregate channel features object detector.
% acfReadme - Aggregate Channel Features Detector Overview.
% acfSweeps - Parameter sweeps for ACF pedestrian detector.
% acfTest - Test aggregate channel features object detector given ground truth.
% acfTrain - Train aggregate channel features object detector.
%
% Object bounding box utilities and labeling tools:
% bbApply - Functions for manipulating bounding boxes (bb).
% bbGt - Bounding box (bb) annotations struct, evaluation and sampling routines.
% bbLabeler - Bounding box or ellipse labeler for static images.
% bbNms - Bounding box (bb) non-maximal suppression (nms).
|
@testset "expand_poly" begin
xi = 1:6
xf = 1f0:6f0
@test_throws MethodError expand_poly(xi, obsdim = 3)
@test_throws MethodError expand_poly(xf, 5, ObsDim.Constant{3}())
@testset "ObsDim.Last()" begin
for x in [xi, xf]
X = expand_poly(x, degree = 5)
@test eltype(x) == eltype(X)
@test @inferred(expand_poly(x)) == X
@test @inferred(expand_poly(x, 5)) == X
@test @inferred(expand_poly(x, 5, ObsDim.Last())) == X
@test @inferred(expand_poly(x, 5, ObsDim.Constant{2}())) == X
@test size(X) == (5, 6)
for i in 1:6, k in 1:5
@test X[k, i] === x[i]^k
end
end
end
@testset "ObsDim.First()" begin
for x in [xi, xf]
X = expand_poly(x, degree = 5, obsdim = 1)
@test eltype(x) == eltype(X)
@test expand_poly(x, obsdim = 1) == X
@test @inferred(expand_poly(x, 5, ObsDim.First())) == X
@test size(X) == (6, 5)
for k in 1:5, i in 1:6
@test X[i, k] === x[i]^k
end
end
end
@testset "Missing" begin
xm = [1., 2., missing, 4., 5., 6.]
@test_throws MethodError expand_poly(xm, obsdim = 3)
@test_throws MethodError expand_poly(xm, 5, ObsDim.Constant{3}())
X = @inferred(expand_poly(xm, 5))
@test eltype(xm) == eltype(X)
@test size(X) == (5, 6)
for i in 1:6, k in 1:5
if i != 3
@test X[k, i] === xm[i]^k
else
@test ismissing(X[k, i])
end
end
end
end
|
# How `linearsolve` Works
The equilibrium conditions for most DSGE models can be expressed as a vector function $F$:
\begin{align}
f(E_t X_{t+1}, X_t, \epsilon_{t+1}) = 0,
\end{align}
where 0 is an $n\times 1$ vector of zeros, $X_t$ is an $n\times 1$ vector of endogenous variables, and $\epsilon_{t+1}$ is an $m\times 1$ vector of exogenous structural shocks to the model. $E_tX_{t+1}$ denotes the expecation of the $t+1$ endogenous variables based on the information available to decision makers in the model as of time period $t$.
The function $f$ is often nonlinear. Because the values of the endogenous variables in period $t$ depend on the expected future values of those variables, it is not in general possible to compute the equilibirum of the model by working directly with the function $f$. Instead it is often convenient to work with a log-linear approximation to the equilibrium conditions around a non-stochastic steady state. In many cases, the log-linear approximation can be written in the following form:
\begin{align}
A E_t\left[ x_{t+1} \right] & = B x_t + \left[ \begin{array}{c} \epsilon_{t+1} \\ 0 \end{array} \right],
\end{align}
where the vector $x_{t}$ denotes the log deviation of the variables in $X_t$ from their steady state values. Given the function $f$, `linearsolve` computes matrices $A$ and $B$ numerically as:
\begin{align}
A & = \left[ \frac{\partial \log f_1 }{\partial \log X_{t+1} } \left(\bar{X} \right) - \frac{\partial \log f_2 }{\partial \log X_{t+1} } \left(\bar{X} \right) \right]
\end{align}
and:
\begin{align}
B & = -\left[ \frac{\partial \log f_1 }{\partial \log X_{t+1} } \left(\bar{X} \right) - \frac{\partial \log f_2 }{\partial \log X_{t} } \left(\bar{X} \right) \right]
\end{align}
The variables in $x_t$ are grouped in a specific way: $x_t = [s_t; u_t]$ where $s_t$ is an $n_s \times 1$ vector of predetermined (state) variables and $u_t$ is an $n_u \times 1$ vector of nonpredetermined (forward-looking) variables. $\epsilon_{t+1}$ is an $n_s\times 1$ vector of i.i.d. shocks to the state variables $s_{t+1}$. $\epsilon_{t+1}$ has mean 0 and diagonal covariance matrix $\Sigma$. The solution to the model is a pair of matrices $F$ and $P$ such that:
\begin{align}
u_t & = Fs_t\\
s_{t+1} & = Ps_t + \epsilon_{t+1}.
\end{align}
`linearsolve` computes the matrices $F$ and $P$ are using the [Klein (2000)](http://www.sciencedirect.com/science/article/pii/S0165188999000457) solution method which is based on the generalized Schur factorization of the marices $A$ and $B$. The solution routine incorporates many aspects of his Klein's Matlab program [solab.m](http://paulklein.ca/newsite/codes/codes.php). See Chapters 2 and 4 of [Structural Macroeconometrics](https://press.princeton.edu/titles/9622.html) by DeJong and Dave for a deeper descriptions of log-linearization and Klein's solution method.
|
State Before: α : Type u_1
β : Type ?u.320628
γ : Type ?u.320631
p q : α → Prop
inst✝¹ : DecidablePred p
inst✝ : DecidablePred q
s : Finset α
⊢ filter (fun x => True) s = s State After: case a
α : Type u_1
β : Type ?u.320628
γ : Type ?u.320631
p q : α → Prop
inst✝¹ : DecidablePred p
inst✝ : DecidablePred q
s : Finset α
a✝ : α
⊢ a✝ ∈ filter (fun x => True) s ↔ a✝ ∈ s Tactic: ext State Before: case a
α : Type u_1
β : Type ?u.320628
γ : Type ?u.320631
p q : α → Prop
inst✝¹ : DecidablePred p
inst✝ : DecidablePred q
s : Finset α
a✝ : α
⊢ a✝ ∈ filter (fun x => True) s ↔ a✝ ∈ s State After: no goals Tactic: simp
|
module Ch05.Exercise_5_2_3
import Ch05.LambdaCalculus
%default total
||| Alternative (more concise) way to define multiplication of Church numerals
times' : Term
times' = Abs 0 (Abs 1 ((Var 0) . (Var 1)))
|
In his 1924 publication dealing with Kent , the archaeologist O. G. S. Crawford , then working as the archaeological officer for the Ordnance Survey , listed the Coldrum Stones alongside the other Medway Megaliths . In 1926 , the Coldrum Stones were given to The National Trust , who dedicated it as a memorial to the Kentish historian Benjamin Harrison . A plaque was erected to mark this , which erroneously termed the monument a stone circle ; in 1953 , the archaeologist Leslie Grinsell expressed the view that " it is hoped that this error may be rectified in the near future " . Still owned by the Trust , the site is open to visitors all year round , free of charge . On their website , the Trust advises visitors to look for " stunning views from the top of the barrow " . John H. Evans characterised the site as " the most impressive " of the Medway Megaliths , while Grinsell described it as " the finest and most complete " of the group .
|
Formal statement is: lemma frontier_disjoint_eq: "frontier S \<inter> S = {} \<longleftrightarrow> open S" Informal statement is: The frontier of a set $S$ is disjoint from $S$ if and only if $S$ is open.
|
PROGRAM MM_EVOLUTION
c Computes apparent magnitude vs z through several filters
c The user selects the filter(s) to use from the list in filters.log
c The user enters values for the cosmological parameters
include 'read_ised.dec'
include 'filter.dec'
include 'cosmo.dec'
include 'SSP_13.dec'
c Variables
character file*128,name*128,ext*24,argu*1024
integer kf(50)
real yz(imw),xaux(24)
data lun/26/,file/' '/,kf/50*0/
c Cosmology:
data h/70./,omega/0.30/,omega_lambda/0.70/
c Check if correct filter file is in use.
j=ifilter()
if (j.eq.0) then
write (6,'(2a)') char(7),'Please assign correct filter file'
stop
endif
c Welcome user
write (6,*)
write (6,'(x,a)') 'Galaxy Spectral Evolution Library (GALAXEV)'
write (6,'(x,a)') 'UNIX Version (C) 1995-2013 - G. Bruzual and S. Charlot - All Rights Reserved'
c Ask for Ho, Omega, and Omega_lambda
write (6,'(/x,a,f4.0,a,f5.3,a,$)') 'Enter cosmological parameters'
3 write (6,'(x,a,f4.0,a,f5.3,a,f5.3,a,$)') 'Enter Ho [',h,'], Omega [',omega,'], Omega_lambda [',omega_lambda,'] = '
call nread(xaux,nc,*9,*10)
if (nc.gt.0.) then
h=xaux(1)
omega=xaux(2)
omega_lambda=xaux(3)
endif
c Omega is now entered bu the user
c omega=1.-omega_lambda
c Obtain cosmological constant and q
clambda=cosmol_c(h,omega,omega_lambda,q)
c Age of the universe and maximum age for galaxies (rounded off)
tu=t(h,q,0.,clambda)
tg=int(tu)*1.E9
c Ask for galaxy age
write (6,*)
write (6,'(x,a,f6.2,a )') 'Age of this universe = tu =',tu,' Gyr'
2 write (6,'(x,a,f6.2,a,$)') 'Enter age of galaxy today = tg [',tg*1.e-9,' Gyr] = '
call qread(ttg,nc,*8,*10)
if (nc.gt.0.) tg=ttg*1.E9
ttg=tg*1.E-9
zf=zx(ttg,h,q,clambda)
c Report cosmology
write (6,'(/x,a)') 'Cosmological model in use:'
write (6,100) h,omega,omega_lambda,q,clambda
100 format (' Ho = ',f4.0,3x,'Omega =',f5.2,3x,'Omega_lambda =',f5.2,3x,'qo = ',
* f7.4,3x,'Lambda =',1pE10.3)
write (6,101) tu,ttg,zf
101 format (' tu = ',f5.2,' Gyr',3x,'tg = ',f5.2,' Gyr', 3x,' zf = ',f6.2)
c Ask for *.ised file name
write (6,*)
1 write (6,'(x,3a,$)') 'BC_GALAXEV model sed in file [',file(1:largo(file)),'] = '
read (5,'(a)',end=10) name
call chaext(name,'ised',nn)
file=name
c Read *.ised file
call read_ised(file,tg,kl,kerr)
if (kerr.ne.0) goto 1
c Read filter file
call filter0
c Read A0Vsed
call readA0V
c Ask for filter numbers
4 write (6,'(/x,a)') 'Enter up to 50 filters separated by commas.'
write (6,'( x,a,i3,a,$)') 'Compute magnitude through filter numbers (1:',nf,') = '
read (5,'(a)',end=10) argu
ngu = nargu(argu)
read (argu,*,err=4) (kf(j),j=1,ngu)
do i=1,ngu
if (kf(i).le.0.or.kf(i).gt.nf) then
write (6,'(x,a,i5,a)') 'Error in filter number',kf(i),'. Please try again'
goto 4
endif
enddo
write (6,'(/x,a)') 'Selected filters: '
do i=1,ngu
write (6,'(x,i5,x,a)') kf(i),fid(kf(i))
enddo
c Build output file name and write header into it
ext='multi_mag_vega'
call chaext(name,ext,nn)
open (lun,file=name,form='formatted',status='unknown')
call file_header(lun,file,1)
write (6,'(/x,2a)') 'Output written to file(s): ',name(1:largo(name))
ext='multi_mag_AB'
call chaext(name,ext,nn)
open (lun+1,file=name,form='formatted',status='unknown')
call file_header(lun+1,file,1)
write (6,'( x,2a)') ' ',name(1:largo(name))
c Compute magnitudes
write (6,'(/x,a)') 'Computing magnitudes/colors...'
icall=0
do kz=1,120000
z=zk(kz,zf)
call evol_ised(kl,z,h,q,clambda,yz,icall,last)
if (last.ne.0) goto 10
call ke_nfilt_correction(kf,w,yz,iw,z,h,q,lun,ngu)
if (z.eq.zf) goto 10
enddo
close (lun)
goto 10
!7 write (6,'(x,a)') 'Error in filter number. Please try again'
! goto 4
8 write (6,'(x,a)') 'Error in galaxy age. Please try again'
goto 2
9 write (6,'(x,a)') 'Error in parameters. Please try again'
goto 3
10 end
|
Formal statement is: lemma sum_max_0: fixes x::real (*in fact "'a::comm_ring_1"*) shows "(\<Sum>i\<le>max m n. x^i * (if i \<le> m then a i else 0)) = (\<Sum>i\<le>m. x^i * a i)" Informal statement is: For any real number $x$ and any two natural numbers $m$ and $n$, the sum of $x^i$ times $a_i$ for $i \leq m$ is equal to the sum of $x^i$ times $a_i$ for $i \leq \max(m,n)$ if $a_i = 0$ for $i > m$.
|
[STATEMENT]
lemma the_cat_parallel_2_Comp_vsv[cat_parallel_cs_intros]:
"vsv (\<up>\<up>\<^sub>C \<aa> \<bb> \<gg> \<ff>\<lparr>Comp\<rparr>)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. vsv (\<up>\<up>\<^sub>C \<aa> \<bb> \<gg> \<ff>\<lparr>Comp\<rparr>)
[PROOF STEP]
unfolding the_cat_parallel_2_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. vsv (\<Up>\<^sub>C \<aa> \<bb> (ZFC_in_HOL.set {\<gg>, \<ff>})\<lparr>Comp\<rparr>)
[PROOF STEP]
by (rule the_cat_parallel_Comp_vsv)
|
lemma contour_integrable_lmul: "f contour_integrable_on g \<Longrightarrow> (\<lambda>x. c * f x) contour_integrable_on g"
|
(*
Title: The pi-calculus
Author/Maintainer: Jesper Bengtson (jebe.dk), 2012
*)
theory Strong_Late_Bisim_Subst_Pres
imports Strong_Late_Bisim_Subst Strong_Late_Bisim_Pres
begin
lemma tauPres:
fixes P :: pi
and Q :: pi
assumes "P \<sim>\<^sup>s Q"
shows "\<tau>.(P) \<sim>\<^sup>s \<tau>.(Q)"
using assms
by(force simp add: substClosed_def intro: Strong_Late_Bisim_Pres.tauPres)
lemma inputPres:
fixes P :: pi
and Q :: pi
and a :: name
and x :: name
assumes "P \<sim>\<^sup>s Q"
shows "a<x>.P \<sim>\<^sup>s a<x>.Q"
proof(auto simp add: substClosed_def)
fix \<sigma> :: "(name \<times> name) list"
{
fix P Q a x \<sigma>
assume "P \<sim>\<^sup>s Q"
then have "P[<\<sigma>>] \<sim>\<^sup>s Q[<\<sigma>>]" by(rule partUnfold)
then have "\<forall>y. (P[<\<sigma>>])[x::=y] \<sim> (Q[<\<sigma>>])[x::=y]"
apply(auto simp add: substClosed_def)
by(erule_tac x="[(x, y)]" in allE) auto
moreover assume "x \<sharp> \<sigma>"
ultimately have "(a<x>.P)[<\<sigma>>] \<sim> (a<x>.Q)[<\<sigma>>]" using bisimEqvt
by(force intro: Strong_Late_Bisim_Pres.inputPres)
}
note Goal = this
obtain y::name where "y \<sharp> P" and "y \<sharp> Q" and "y \<sharp> \<sigma>"
by(generate_fresh "name") auto
from `P \<sim>\<^sup>s Q` have "([(x, y)] \<bullet> P) \<sim>\<^sup>s ([(x, y)] \<bullet> Q)" by(rule eqClosed)
hence "(a<y>.([(x, y)] \<bullet> P))[<\<sigma>>] \<sim> (a<y>.([(x, y)] \<bullet> Q))[<\<sigma>>]" using `y \<sharp> \<sigma>` by(rule Goal)
moreover from `y \<sharp> P` `y \<sharp> Q` have "a<x>.P = a<y>.([(x, y)] \<bullet> P)" and "a<x>.Q = a<y>.([(x, y)] \<bullet> Q)"
by(simp add: alphaInput)+
ultimately show "(a<x>.P)[<\<sigma>>] \<sim> (a<x>.Q)[<\<sigma>>]" by simp
qed
lemma outputPres:
fixes P :: pi
and Q :: pi
assumes "P \<sim>\<^sup>s Q"
shows "a{b}.P \<sim>\<^sup>s a{b}.Q"
using assms
by(force simp add: substClosed_def intro: Strong_Late_Bisim_Pres.outputPres)
assumes "P \<sim>\<^sup>s Q"
shows "[a\<frown>b]P \<sim>\<^sup>s [a\<frown>b]Q"
using assms
by(force simp add: substClosed_def intro: Strong_Late_Bisim_Pres.matchPres)
lemma mismatchPres:
fixes P :: pi
and Q :: pi
and a :: name
and b :: name
assumes "P \<sim>\<^sup>s Q"
shows "[a\<noteq>b]P \<sim>\<^sup>s [a\<noteq>b]Q"
using assms
by(force simp add: substClosed_def intro: Strong_Late_Bisim_Pres.mismatchPres)
lemma sumPres:
fixes P :: pi
and Q :: pi
and R :: pi
assumes "P \<sim>\<^sup>s Q"
shows "P \<oplus> R \<sim>\<^sup>s Q \<oplus> R"
using assms
by(force simp add: substClosed_def intro: Strong_Late_Bisim_Pres.sumPres)
lemma parPres:
fixes P :: pi
and Q :: pi
and R :: pi
assumes "P \<sim>\<^sup>s Q"
shows "P \<parallel> R \<sim>\<^sup>s Q \<parallel> R"
using assms
by(force simp add: substClosed_def intro: Strong_Late_Bisim_Pres.parPres)
assumes PeqQ: "P \<sim>\<^sup>s Q"
shows "<\<nu>x>P \<sim>\<^sup>s <\<nu>x>Q"
proof(auto simp add: substClosed_def)
fix s::"(name \<times> name) list"
have Res: "\<And>P Q x s. \<lbrakk>P[<s>] \<sim> Q[<s>]; x \<sharp> s\<rbrakk> \<Longrightarrow> (<\<nu>x>P)[<s>] \<sim> (<\<nu>x>Q)[<s>]"
by(force intro: Strong_Late_Bisim_Pres.resPres)
have "\<exists>c::name. c \<sharp> (P, Q, s)" by(blast intro: name_exists_fresh)
then obtain c::name where cFreshP: "c \<sharp> P" and cFreshQ: "c \<sharp> Q" and cFreshs: "c \<sharp> s"
by(force simp add: fresh_prod)
from PeqQ have "P[<([(x, c)] \<bullet> s)>] \<sim> Q[<([(x, c)] \<bullet> s)>]" by(simp add: substClosed_def)
hence "([(x, c)] \<bullet> P[<([(x, c)] \<bullet> s)>]) \<sim> ([(x, c)] \<bullet> Q[<([(x, c)] \<bullet> s)>])" by(rule bisimClosed)
hence "([(x, c)] \<bullet> P)[<s>] \<sim> ([(x, c)] \<bullet> Q)[<s>]" by simp
hence "(<\<nu>c>([(x, c)] \<bullet> P))[<s>] \<sim> (<\<nu>c>([(x, c)] \<bullet> Q))[<s>]" using cFreshs by(rule Res)
moreover from cFreshP cFreshQ have "<\<nu>x>P = <\<nu>c>([(x, c)] \<bullet> P)" and "<\<nu>x>Q = <\<nu>c>([(x, c)] \<bullet> Q)"
by(simp add: alphaRes)+
ultimately show "(<\<nu>x>P)[<s>] \<sim> (<\<nu>x>Q)[<s>]" by simp
qed
shows "!P \<sim>\<^sup>s !Q"
using assms
by(force simp add: substClosed_def intro: Strong_Late_Bisim_Pres.bangPres)
end
|
function varargout = drawPolyhedron(nodes, faces, varargin)
%DRAWPOLYHEDRON Draw polyhedron defined by vertices and faces
%
% drawPolyhedron(NODES, FACES)
% Draws the polyhedron defined by vertices NODES and the faces FACES.
% NODES is a NV-by-3 array containing coordinates of vertices, and FACES
% is either a NF-by3 or NF-by-4 array containing indices of vertices of
% the triangular or rectangular faces.
% FACES can also be a cell array, in the content of each cell is an array
% of indices to the nodes of the current face. Faces can have different
% number of vertices.
%
% H = drawPolyhedron(...);
% Also returns a handle to the created patche.
%
% Example:
% [n f] = createSoccerBall;
% drawPolyhedron(n, f);
%
% See also:
% polyhedra, drawMesh, drawPolygon
%
% ---------
%
% author : David Legland
% INRA - TPV URPOI - BIA IMASTE
% created the 10/02/2005.
%
% HISTORY
% 07/11/2005 update doc.
% 04/01/2007 typo
% 18/01/2007 add support for 2D polyhedra ("nodes" is N-by-2 array), and
% make 'cnodes' a list of points instead of a list of indices
% 14/08/2007 add comment, add support for NaN in faces (complex polygons)
% 14/09/2007 rename as drawPolyhedron
% 16/10/2008 better support for colors
% 27/07/2010 copy to 'drawMesh'
%% Initialisations
% process input arguments
switch length(varargin)
case 0
% default color is red
varargin = {'facecolor', [1 0 0]};
case 1
% use argument as color for faces
varargin = {'facecolor', varargin{1}};
otherwise
% otherwise do nothing
end
% overwrites on current figure
hold on;
% if nodes are 2D points, add a z=0 coordinate
if size(nodes, 2) == 2
nodes(1,3) = 0;
end
%% main loop : for each face
if iscell(faces)
% array FACES is a cell array
h = zeros(length(faces(:)), 1);
for f = 1:length(faces(:))
% get nodes of the cell
face = faces{f};
if sum(isnan(face))~=0
% Special processing in case of multiple polygonal face.
% each polygonal loop is separated by a NaN.
% find indices of loops breaks
inds = find(isnan(face));
% replace NaNs by index of first vertex of each polygon
face(inds(2:end)) = face(inds(1:end-1)+1);
face(inds(1)) = face(1);
face(length(face)+1)= face(inds(end)+1);
end
% draw current face
cnodes = nodes(face, :);
h(f) = patch(cnodes(:, 1), cnodes(:, 2), cnodes(:, 3), [1 0 0]);
end
else
% array FACES is a NC*NV indices array, with NV : number of vertices of
% each face, and NC number of faces
h = zeros(size(faces, 1), 1);
for f = 1:size(faces, 1)
% get nodes of the cell
cnodes = nodes(faces(f,:)', :);
h(f) = patch(cnodes(:, 1), cnodes(:, 2), cnodes(:, 3), [1 0 0]);
end
end
% set up drawing options
if ~isempty(varargin)
set(h, varargin{:});
end
% format output parameters
if nargout > 0
varargout = {h};
end
|
Formal statement is: lemma big_small_trans: assumes "f \<in> L F (g)" "g \<in> l F (h)" shows "f \<in> l F (h)" Informal statement is: If $f$ is $O(g)$ and $g$ is $o(h)$, then $f$ is $o(h)$.
|
%DILATE Dilates an image by using a specific structuring element
%
% dst = cv.dilate(src)
% dst = cv.dilate(src, 'OptionName',optionValue, ...)
%
% ## Input
% * __src__ input image; the number of channels can be arbitrary, but the
% depth should be one of `uint8`, `uint16`, `int16`, `single` or `double`.
%
% ## Output
% * __dst__ output image of the same size and type as `src`.
%
% ## Options
% * __Element__ Structuring element used for dilation. By default, a 3x3
% rectangular structuring element is used `ones(3)`. Kernel can be created
% using cv.getStructuringElement
% * __Anchor__ Position of the anchor within the element. The default value
% [-1, -1] means that the anchor is at the element center.
% * __Iterations__ Number of times dilation is applied. default 1
% * __BorderType__ Border mode used to extrapolate pixels outside of the
% image. See cv.copyMakeBorder. default 'Constant'
% * __BorderValue__ Border value in case of a constant border. The default
% value has a special meaning which gets automatically translated to the
% minimum value of the image class type (`intmin(class(img))` for integer
% types and `realmin(class(img))` for floating-point types). See
% cv.morphologyDefaultBorderValue
%
% The function dilates the source image using the specified structuring
% element that determines the shape of a pixel neighborhood over which the
% maximum is taken:
%
% dst(x,y) = max_{(xp,yp): Element(xp,yp)!=0} src(x+xp, y+yp)
%
% Dilation can be applied several (`Iterations`) times. In case of
% multi-channel images, each channel is processed independently.
%
% See also: cv.erode, cv.morphologyEx, cv.getStructuringElement, imdilate
%
|
Food is definitely the fuel that regulates your energy and your mood, and these superfoods take the cake (or maybe the kale!) when it comes to helping you be more focused. I try to treat the foods you eat the same way as the oil you put in your car engine to help it perform. You wouldn’t put olive oil into your car… so why would you put chocolate syrup into to your body? It just doesn’t add up. So if you’re looking to boost your focus and improve your productivity…. one of the places you should start with is what you’re eating…. like these superfoods.
We all know that antioxidants are good for you, and superfoods are packed full of them. They pick up free radicals and help decrease inflammation in your system that can lead to weight gain, brain fog and even joint pain. My favourite superfood of the berry bunch is the Haskapa Berry. Native to Japan, the Nova Scotia climate is perfect for growing these antioxidant-filled punches of flavour. Antioxidants are important for your focus because they help to stimulate the flow of blood and oxygen to [your] brain. More blood flow = more brain power – what more can I say?
I LOVE a good hit of caffeine to help perk up my brain power…. but green tea goes one step further than the true love of my life (coffee) due to the l-theanine content of this herb. L-theanine is great because it’s been shown to “increase alpha-wave activity”, which increases calmness and releases caffeine more slowly; instead of all at once. This is great for productivity and focus because it means that you can get your work down without worrying about that crash.
I LOVE KALE. But not everyone does. One of the reasons dark green leafy vegetables are so critical for our brain power is because they are filled to the leaf (ha!) with antioxidants, carotenoids and B Vitamins. The combination of these compounds help to boost your brain power and protect those synapses (which transmit signals across your brain) as well as helping your memory.
These fish; like herring, sardines, kippers and mackerel, are filled with omega-3 fatty acids. These omega-3’s help to aid memory, mental performance and brain function, and those of us with less omega-3’s are more likely to have poor memory, mood swings, depression and fatigue.
Please. If you want to improve your focus, you need to drink enough water. Water gives the brain the electrical energy for all rain functions, including thought and memory processes. Plus, you can imagine after living in NS winters what dehydration could only do to your brain.
|
// smooth_feedback: Control theory on Lie groups
// https://github.com/pettni/smooth_feedback
//
// Licensed under the MIT License <http://opensource.org/licenses/MIT>.
//
// Copyright (c) 2021 Petter Nilsson
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <boost/numeric/odeint.hpp>
#include <smooth/bundle.hpp>
#include <smooth/compat/odeint.hpp>
#include <smooth/feedback/pid.hpp>
#include <smooth/se2.hpp>
#include <chrono>
#ifdef ENABLE_PLOTTING
#include <matplot/matplot.h>
#endif
using namespace std::chrono_literals;
using namespace boost::numeric::odeint;
using Time = std::chrono::duration<double>;
int main()
{
smooth::feedback::PIDParams prm{};
smooth::feedback::PID<Time, smooth::SE2d> pid(prm);
// set desired trajectory
Eigen::Vector3d vdes(1, 0, 0.4);
auto xdes = [&vdes](Time t) -> decltype(pid)::TrajectoryReturnT {
return std::make_tuple(
smooth::SE2d(smooth::SO2d(M_PI_2), Eigen::Vector2d(2.5, 0)) + (t.count() * vdes),
vdes,
Eigen::Vector3d::Zero());
};
pid.set_xdes(xdes);
// input variable
Eigen::Vector2d u;
// prepare for integrating the closed-loop system
using State = smooth::Bundle<smooth::SE2d, Eigen::Vector3d>;
using Deriv = typename State::Tangent;
runge_kutta4<State, double, Deriv, double, vector_space_algebra> stepper{};
const auto ode = [&u](const State & x, Deriv & d, double) {
d.template head<3>() = x.part<1>();
d.template tail<3>() << u(0), 0, u(1);
};
State x(smooth::SE2d::Identity(), Eigen::Vector3d::Zero());
std::vector<double> tvec, xvec, yvec, u1vec, u2vec;
// integrate closed-loop system
for (std::chrono::milliseconds t = 0s; t < 30s; t += 50ms) {
// compute input
Eigen::Vector3d a = pid(t, x.part<0>(), x.part<1>());
// input allocation from desired acceleration
u(0) = std::clamp<double>(a(0), -1, 1); // throtte <- a_x
u(1) = std::clamp<double>(a(2) + 0.3 * a(1), -1, 1); // steering <- a_Yaw + 0.3 a_y
// store data
tvec.push_back(duration_cast<Time>(t).count());
xvec.push_back(x.part<0>().r2().x());
yvec.push_back(x.part<0>().r2().y());
u1vec.push_back(u(0));
u2vec.push_back(u(1));
// step dynamics
stepper.do_step(ode, x, 0, 0.05);
}
#ifdef ENABLE_PLOTTING
matplot::figure();
matplot::hold(matplot::on);
matplot::title("Path");
matplot::plot(xvec, yvec)->line_width(2);
matplot::plot(
matplot::transform(tvec, [&](auto t) { return std::get<0>(xdes(Time(t))).r2().x(); }),
matplot::transform(tvec, [&](auto t) { return std::get<0>(xdes(Time(t))).r2().y(); }),
"k--")
->line_width(2);
matplot::legend({"actual", "desired"});
matplot::figure();
matplot::hold(matplot::on);
matplot::title("Inputs");
matplot::plot(tvec, u1vec)->line_width(2);
matplot::plot(tvec, u2vec)->line_width(2);
matplot::legend({"u1", "u2"});
matplot::show();
#else
std::cout << "TRAJECTORY:" << std::endl;
for (auto i = 0u; i != tvec.size(); ++i) {
std::cout << "t=" << tvec[i] << ": x=" << xvec[i] << ", y=" << yvec[i] << std::endl;
}
#endif
}
|
header {* The programming language and its semantics *}
theory Language_Semantics imports Interface begin
subsection {* Syntax and operational semantics *}
datatype ('test,'atom) com =
Atm 'atom |
Seq "('test,'atom) com" "('test,'atom) com"
("_ ;; _" [60, 61] 60) |
If 'test "('test,'atom) com" "('test,'atom) com"
("(if _/ then _/ else _)" [0, 0, 61] 61) |
While 'test "('test,'atom) com"
("(while _/ do _)" [0, 61] 61) |
Par "('test,'atom) com" "('test,'atom) com"
("_ | _" [60, 61] 60)
locale PL =
fixes
tval :: "'test \<Rightarrow> 'state \<Rightarrow> bool" and
aval :: "'atom \<Rightarrow> 'state \<Rightarrow> 'state"
(* *****************************************)
context PL
begin
text{* Conventions and notations:
-- suffixes: ``C" for ``Continuation", ``T" for ``termination"
-- prefix: ``M" for multistep
-- tst, tst' are tests
-- atm, atm' are atoms (atomic commands)
-- s, s', t, t' are states
-- c, c', d, d' are commands
-- cf, cf' are configurations, i.e., pairs command-state *}
inductive transT ::
"(('test,'atom)com * 'state) \<Rightarrow> 'state \<Rightarrow> bool"
(infix "\<rightarrow>t" 55)
where
Atm[simp]:
"(Atm atm, s) \<rightarrow>t aval atm s"
| WhileFalse[simp]:
"~ tval tst s \<Longrightarrow> (While tst c, s) \<rightarrow>t s"
lemmas trans_Atm = Atm
lemmas trans_WhileFalse = WhileFalse
(* The RT-closure of \<rightarrow>c is inlined since later versions of \<rightarrow>c may refer to it. *)
inductive transC ::
"(('test,'atom)com * 'state) \<Rightarrow> (('test,'atom)com * 'state) \<Rightarrow> bool"
(infix "\<rightarrow>c" 55)
and MtransC ::
"(('test,'atom)com * 'state) \<Rightarrow> (('test,'atom)com * 'state) \<Rightarrow> bool"
(infix "\<rightarrow>*c" 55)
where
SeqC[simp]:
"(c1, s) \<rightarrow>c (c1', s') \<Longrightarrow> (c1 ;; c2, s) \<rightarrow>c (c1' ;; c2, s')"
| SeqT[simp]:
"(c1, s) \<rightarrow>t s' \<Longrightarrow> (c1 ;; c2, s) \<rightarrow>c (c2, s')"
| IfTrue[simp]:
"tval tst s \<Longrightarrow> (If tst c1 c2, s) \<rightarrow>c (c1, s)"
| IfFalse[simp]:
"~ tval tst s \<Longrightarrow> (If tst c1 c2,s) \<rightarrow>c (c2, s)"
| WhileTrue[simp]:
"tval tst s \<Longrightarrow> (While tst c, s) \<rightarrow>c (c ;; (While tst c), s)"
(* *)
| ParCL[simp]:
"(c1, s) \<rightarrow>c (c1', s') \<Longrightarrow> (Par c1 c2, s) \<rightarrow>c (Par c1' c2, s')"
| ParCR[simp]:
"(c2, s) \<rightarrow>c (c2', s') \<Longrightarrow> (Par c1 c2, s) \<rightarrow>c (Par c1 c2', s')"
| ParTL[simp]:
"(c1, s) \<rightarrow>t s' \<Longrightarrow> (Par c1 c2, s) \<rightarrow>c (c2, s')"
| ParTR[simp]:
"(c2, s) \<rightarrow>t s' \<Longrightarrow> (Par c1 c2, s) \<rightarrow>c (c1, s')"
| Refl:
"(c,s) \<rightarrow>*c (c,s)"
| Step:
"\<lbrakk>(c,s) \<rightarrow>*c (c',s'); (c',s') \<rightarrow>c (c'',s'')\<rbrakk> \<Longrightarrow> (c,s) \<rightarrow>*c (c'',s'')"
lemmas trans_SeqC = SeqC lemmas trans_SeqT = SeqT
lemmas trans_IfTrue = IfTrue lemmas trans_IfFalse = IfFalse
lemmas trans_WhileTrue = WhileTrue
lemmas trans_ParCL = ParCL lemmas trans_ParCR = ParCR
lemmas trans_ParTL = ParTL lemmas trans_ParTR = ParTR
lemmas trans_Refl = Refl lemmas trans_Step = Step
lemma MtransC_Refl[simp]: "cf \<rightarrow>*c cf"
using trans_Refl by(cases cf, simp)
lemmas transC_induct = transC_MtransC.inducts(1)
[split_format(complete),
where ?P2.0 = "\<lambda> c s c' s'. True"]
lemmas MtransC_induct_temp = transC_MtransC.inducts(2)[split_format(complete)]
inductive MtransT ::
"(('test,'atom)com * 'state) \<Rightarrow> 'state \<Rightarrow> bool"
(infix "\<rightarrow>*t" 55)
where
StepT:
"\<lbrakk>cf \<rightarrow>*c cf'; cf' \<rightarrow>t s''\<rbrakk> \<Longrightarrow> cf \<rightarrow>*t s''"
lemma MtransC_rtranclp_transC:
"MtransC = transC ^**"
proof-
{fix c s c' s'
have "(c,s) \<rightarrow>*c (c',s') \<Longrightarrow> transC ^** (c,s) (c',s')"
apply(rule MtransC_induct_temp[of _ _ c s c' s' "\<lambda>c s c' s'. True"]) by auto
}
moreover
{fix c s c' s'
have "transC ^** (c,s) (c',s') \<Longrightarrow> (c,s) \<rightarrow>*c (c',s')"
apply(erule rtranclp.induct) using trans_Step by auto
}
ultimately show ?thesis
apply - apply(rule ext, rule ext) by auto
qed
lemma transC_MtransC[simp]:
assumes "cf \<rightarrow>c cf'"
shows "cf \<rightarrow>*c cf'"
using assms unfolding MtransC_rtranclp_transC by blast
lemma MtransC_Trans:
assumes "cf \<rightarrow>*c cf'" and "cf' \<rightarrow>*c cf''"
shows "cf \<rightarrow>*c cf''"
using assms rtranclp_trans[of transC cf cf' cf'']
unfolding MtransC_rtranclp_transC by blast
lemma MtransC_StepC:
assumes *: "cf \<rightarrow>*c cf'" and **: "cf' \<rightarrow>c cf''"
shows "cf \<rightarrow>*c cf''"
proof-
have "cf' \<rightarrow>*c cf''" using ** by simp
thus ?thesis using * MtransC_Trans by blast
qed
lemma MtransC_induct[consumes 1, case_names Refl Trans]:
assumes "cf \<rightarrow>*c cf'"
and "\<And>cf. phi cf cf"
and
"\<And> cf cf' cf''.
\<lbrakk>cf \<rightarrow>*c cf'; phi cf cf'; cf' \<rightarrow>c cf''\<rbrakk>
\<Longrightarrow> phi cf cf''"
shows "phi cf cf'"
using assms unfolding MtransC_rtranclp_transC
using rtranclp.induct[of transC cf cf'] by blast
lemma MtransC_induct2[consumes 1, case_names Refl Trans, induct pred: MtransC]:
assumes "(c,s) \<rightarrow>*c (c',s')"
and "\<And>c s. phi c s c s"
and
"\<And> c s c' s' c'' s''.
\<lbrakk>(c,s) \<rightarrow>*c (c',s'); phi c s c' s'; (c',s') \<rightarrow>c (c'',s'')\<rbrakk>
\<Longrightarrow> phi c s c'' s''"
shows "phi c s c' s'"
using assms
MtransC_induct[of "(c,s)" "(c',s')" "\<lambda>(c,s) (c',s'). phi c s c' s'"] by blast
lemma transT_MtransT[simp]:
assumes "cf \<rightarrow>t s'"
shows "cf \<rightarrow>*t s'"
by (metis PL.MtransC_Refl PL.MtransT.intros assms)
lemma MtransC_MtransT:
assumes "cf \<rightarrow>*c cf'" and "cf' \<rightarrow>*t cf''"
shows "cf \<rightarrow>*t cf''"
by (metis MtransT.cases PL.MtransC_Trans PL.MtransT.intros assms)
lemma transC_MtransT[simp]:
assumes "cf \<rightarrow>c cf'" and "cf' \<rightarrow>*t s''"
shows "cf \<rightarrow>*t s''"
by (metis PL.MtransC_MtransT assms(1) assms(2) transC_MtransC)
text{* Inversion rules, nchotomies and such: *}
lemma Atm_transC_simp[simp]:
"~ (Atm atm, s) \<rightarrow>c cf"
apply clarify apply(erule transC.cases) by auto
lemma Atm_transC_invert[elim!]:
assumes "(Atm atm, s) \<rightarrow>c cf"
shows phi
using assms by simp
lemma Atm_transT_invert[elim!]:
assumes "(Atm atm, s) \<rightarrow>t s'"
and "s' = aval atm s \<Longrightarrow> phi"
shows phi
using assms apply - apply(erule transT.cases) by auto
lemma Seq_transC_invert[elim!]:
assumes "(c1 ;; c2, s) \<rightarrow>c (c', s')"
and "\<And> c1'. \<lbrakk>(c1, s) \<rightarrow>c (c1',s'); c' = c1' ;; c2\<rbrakk> \<Longrightarrow> phi"
and "\<lbrakk>(c1, s) \<rightarrow>t s'; c' = c2\<rbrakk> \<Longrightarrow> phi"
shows phi
using assms apply - apply(erule transC.cases) by auto
lemma Seq_transT_invert[simp]:
"~ (c1 ;; c2, s) \<rightarrow>t s'"
apply clarify apply(erule transT.cases) by auto
lemma If_transC_invert[elim!]:
assumes "(If tst c1 c2, s) \<rightarrow>c (c', s')"
and "\<lbrakk>tval tst s; c' = c1; s' = s\<rbrakk> \<Longrightarrow> phi"
and "\<lbrakk>~ tval tst s; c' = c2; s' = s\<rbrakk> \<Longrightarrow> phi"
shows phi
using assms apply - apply(erule transC.cases) by auto
lemma If_transT_simp[simp]:
"~ (If b c1 c2, s) \<rightarrow>t s'"
apply clarify apply(erule transT.cases) by auto
lemma If_transT_invert[elim!]:
assumes "(If b c1 c2, s) \<rightarrow>t s'"
shows phi
using assms by simp
lemma While_transC_invert[elim]:
assumes "(While tst c1, s) \<rightarrow>c (c', s')"
and "\<lbrakk>tval tst s; c' = c1 ;; (While tst c1); s' = s\<rbrakk> \<Longrightarrow> phi"
shows phi
using assms apply - apply(erule transC.cases) by auto
lemma While_transT_invert[elim!]:
assumes "(While tst c1, s) \<rightarrow>t s'"
and "\<lbrakk>~ tval tst s; s' = s\<rbrakk> \<Longrightarrow> phi"
shows phi
using assms apply - apply(erule transT.cases) by blast+
lemma Par_transC_invert[elim!]:
assumes "(Par c1 c2, s) \<rightarrow>c (c', s')"
and "\<And> c1'. \<lbrakk>(c1, s) \<rightarrow>c (c1',s'); c' = Par c1' c2\<rbrakk> \<Longrightarrow> phi"
and "\<lbrakk>(c1, s) \<rightarrow>t s'; c' = c2\<rbrakk> \<Longrightarrow> phi"
and "\<And> c2'. \<lbrakk>(c2, s) \<rightarrow>c (c2',s'); c' = Par c1 c2'\<rbrakk> \<Longrightarrow> phi"
and "\<lbrakk>(c2, s) \<rightarrow>t s'; c' = c1\<rbrakk> \<Longrightarrow> phi"
shows phi
using assms apply - apply(erule transC.cases) by auto
lemma Par_transT_simp[simp]:
"~ (Par c1 c2, s) \<rightarrow>t s'"
apply clarify apply(erule transT.cases) by auto
lemma Par_transT_invert[elim!]:
assumes "(Par c1 c2, s) \<rightarrow>t s'"
shows phi
using assms by simp
lemma trans_nchotomy:
"(\<exists> c' s'. (c,s) \<rightarrow>c (c',s')) \<or>
(\<exists> s'. (c,s) \<rightarrow>t s')"
proof-
let ?phiC = "\<lambda>c. \<exists> c' s'. (c,s) \<rightarrow>c (c',s')"
let ?phiT = "\<lambda>c. \<exists> s'. (c,s) \<rightarrow>t s'"
let ?phi = "\<lambda>c. ?phiC c \<or> ?phiT c"
show "?phi c"
apply(induct c)
by(metis Atm, metis SeqC SeqT, metis IfFalse IfTrue,
metis WhileFalse WhileTrue,
metis ParCL ParCR ParTL ParTR)
qed
corollary trans_invert:
assumes
"\<And> c' s'. (c,s) \<rightarrow>c (c',s') \<Longrightarrow> phi"
and "\<And> s'. (c,s) \<rightarrow>t s' \<Longrightarrow> phi"
shows phi
using assms trans_nchotomy by blast
lemma not_transC_transT:
"\<lbrakk>cf \<rightarrow>c cf'; cf \<rightarrow>t s'\<rbrakk> \<Longrightarrow> phi"
apply(erule transC.cases) by auto
lemmas MtransT_invert = MtransT.cases
lemma MtransT_invert2:
assumes "(c, s) \<rightarrow>*t s''"
and "\<And> c' s'. \<lbrakk>(c,s) \<rightarrow>*c (c',s'); (c', s') \<rightarrow>t s''\<rbrakk> \<Longrightarrow> phi"
shows phi
using assms apply - apply(erule MtransT.cases) by auto
lemma Seq_MtransC_invert[elim!]:
assumes "(c1 ;; c2, s) \<rightarrow>*c (d', t')"
and "\<And> c1'. \<lbrakk>(c1, s) \<rightarrow>*c (c1',t'); d' = c1' ;; c2\<rbrakk> \<Longrightarrow> phi"
and "\<And> s'. \<lbrakk>(c1, s) \<rightarrow>*t s'; (c2, s') \<rightarrow>*c (d',t')\<rbrakk> \<Longrightarrow> phi"
shows phi
proof-
{fix c
have "(c,s) \<rightarrow>*c (d',t') \<Longrightarrow>
\<forall> c1 c2.
c = c1 ;; c2 \<longrightarrow>
(\<exists> c1'. (c1, s) \<rightarrow>*c (c1',t') \<and> d' = c1' ;; c2) \<or>
(\<exists> s'. (c1, s) \<rightarrow>*t s' \<and> (c2, s') \<rightarrow>*c (d',t'))"
apply(erule MtransC_induct2) proof(tactic {* mauto_no_simp_tac *})
fix c s d' t' d'' t'' c1 c2
assume (* "(c, s) \<rightarrow>*c (d', t')" and *)
"\<forall>c1 c2. c = c1 ;; c2 \<longrightarrow>
(\<exists>c1'. (c1, s) \<rightarrow>*c (c1', t') \<and> d' = c1' ;; c2) \<or>
(\<exists>s'. (c1, s) \<rightarrow>*t s' \<and> (c2, s') \<rightarrow>*c (d', t'))"
and 1: "(d', t') \<rightarrow>c (d'', t'')" and "c = c1 ;; c2"
hence IH:
"(\<exists>c1'. (c1, s) \<rightarrow>*c (c1', t') \<and> d' = c1' ;; c2) \<or>
(\<exists>s'. (c1, s) \<rightarrow>*t s' \<and> (c2, s') \<rightarrow>*c (d', t'))" by simp
show "(\<exists>c1''. (c1, s) \<rightarrow>*c (c1'', t'') \<and> d'' = c1'' ;; c2) \<or>
(\<exists>s''. (c1, s) \<rightarrow>*t s'' \<and> (c2, s'') \<rightarrow>*c (d'', t''))"
proof-
{fix c1' assume 2: "(c1, s) \<rightarrow>*c (c1', t')" and d': "d' = c1' ;; c2"
have ?thesis
using 1 unfolding d' apply - proof(erule Seq_transC_invert)
fix c1'' assume "(c1', t') \<rightarrow>c (c1'', t'')" and d'': "d'' = c1'' ;; c2"
hence "(c1, s) \<rightarrow>*c (c1'', t'')" using 2 MtransC_StepC by blast
thus ?thesis using d'' by blast
next
assume "(c1', t') \<rightarrow>t t''" and d'': "d'' = c2"
hence "(c1, s) \<rightarrow>*t t''" using 2 MtransT.StepT by blast
thus ?thesis unfolding d'' by auto
qed
}
moreover
{fix s' assume 2: "(c1, s) \<rightarrow>*t s'" and "(c2, s') \<rightarrow>*c (d', t')"
hence "(c2, s') \<rightarrow>*c (d'', t'')" using 1 MtransC_StepC by blast
hence ?thesis using 2 by blast
}
ultimately show ?thesis using IH by blast
qed
qed (metis PL.MtransC_Refl)
}
thus ?thesis using assms by blast
qed
lemma Seq_MtransT_invert[elim!]:
assumes *: "(c1 ;; c2, s) \<rightarrow>*t s''"
and **: "\<And> s'. \<lbrakk>(c1, s) \<rightarrow>*t s'; (c2, s') \<rightarrow>*t s''\<rbrakk> \<Longrightarrow> phi"
shows phi
proof-
obtain d' t' where 1: "(c1 ;; c2, s) \<rightarrow>*c (d',t')" and 2: "(d',t') \<rightarrow>t s''"
using * apply - apply(erule MtransT_invert2) by auto
show ?thesis
using 1 apply - proof(erule Seq_MtransC_invert)
fix c1' assume "d' = c1' ;; c2"
hence False using 2 by simp
thus ?thesis by simp
next
fix s' assume 3: "(c1, s) \<rightarrow>*t s'" and "(c2, s') \<rightarrow>*c (d', t')"
hence "(c2, s') \<rightarrow>*t s''" using 2 MtransT.StepT by blast
thus ?thesis using 3 ** by blast
qed
qed
text{* Direct rules for the multi-step relations *}
lemma Seq_MtransC[simp]:
assumes "(c1, s) \<rightarrow>*c (c1', s')"
shows "(c1 ;; c2, s) \<rightarrow>*c (c1' ;; c2, s')"
using assms apply - apply(erule MtransC_induct2)
apply simp by (metis MtransC_StepC SeqC)
lemma Seq_MtransT_MtransC[simp]:
assumes "(c1, s) \<rightarrow>*t s'"
shows "(c1 ;; c2, s) \<rightarrow>*c (c2, s')"
using assms apply - apply(erule MtransT_invert)
by (metis MtransC_StepC MtransT_invert2 PL.SeqT PL.Seq_MtransC assms)
lemma ParCL_MtransC[simp]:
assumes "(c1, s) \<rightarrow>*c (c1', s')"
shows "(Par c1 c2, s) \<rightarrow>*c (Par c1' c2, s')"
using assms apply - apply(erule MtransC_induct2)
apply simp by (metis MtransC_StepC ParCL)
lemma ParCR_MtransC[simp]:
assumes "(c2, s) \<rightarrow>*c (c2', s')"
shows "(Par c1 c2, s) \<rightarrow>*c (Par c1 c2', s')"
using assms apply - apply(erule MtransC_induct2)
apply simp by (metis MtransC_StepC ParCR)
lemma ParTL_MtransC[simp]:
assumes "(c1, s) \<rightarrow>*t s'"
shows "(Par c1 c2, s) \<rightarrow>*c (c2, s')"
using assms apply - apply(erule MtransT_invert)
by (metis MtransC_StepC MtransT_invert2 PL.ParTL ParCL_MtransC assms)
lemma ParTR_MtransC[simp]:
assumes "(c2, s) \<rightarrow>*t s'"
shows "(Par c1 c2, s) \<rightarrow>*c (c1, s')"
using assms apply - apply(erule MtransT_invert)
by (metis MtransC_StepC MtransT_invert2 PL.ParTR ParCR_MtransC assms)
subsection{* Sublanguages *}
(* Commands not containing "while": *)
fun noWhile where
"noWhile (Atm atm) = True"
|"noWhile (c1 ;; c2) = (noWhile c1 \<and> noWhile c2)"
|"noWhile (If b c1 c2) = (noWhile c1 \<and> noWhile c2)"
|"noWhile (While b c) = False"
|"noWhile (Par c1 c2) = (noWhile c1 \<and> noWhile c2)"
(* Sequential commands: *)
fun seq where
"seq (Atm atm) = True"
|"seq (c1 ;; c2) = (seq c1 \<and> seq c2)"
|"seq (If b c1 c2) = (seq c1 \<and> seq c2)"
|"seq (While b c) = seq c"
|"seq (Par c1 c2) = False"
lemma noWhile_transC:
assumes "noWhile c" and "(c,s) \<rightarrow>c (c',s')"
shows "noWhile c'"
proof-
have "(c,s) \<rightarrow>c (c',s') \<Longrightarrow> noWhile c \<longrightarrow> noWhile c'"
by(erule transC_induct, auto)
thus ?thesis using assms by simp
qed
lemma seq_transC:
assumes "seq c" and "(c,s) \<rightarrow>c (c',s')"
shows "seq c'"
proof-
have "(c,s) \<rightarrow>c (c',s') \<Longrightarrow> seq c \<longrightarrow> seq c'"
by(erule transC_induct, auto)
thus ?thesis using assms by simp
qed
abbreviation wfP_on where
"wfP_on phi A \<equiv> wfP (\<lambda>a b. a \<in> A \<and> b \<in> A \<and> phi a b)"
(* The number of steps -- makes sense only for the noWhile sublanguage: *)
fun numSt where
"numSt (Atm atm) = Suc 0"
|"numSt (c1 ;; c2) = numSt c1 + numSt c2"
|"numSt (If b c1 c2) = 1 + max (numSt c1) (numSt c2)"
|"numSt (Par c1 c2) = numSt c1 + numSt c2"
lemma numSt_gt_0[simp]:
"noWhile c \<Longrightarrow> numSt c > 0"
by(induct c, auto)
lemma numSt_transC:
assumes "noWhile c" and "(c,s) \<rightarrow>c (c',s')"
shows "numSt c' < numSt c"
using assms apply - apply(induct c arbitrary: c') by auto
corollary wfP_tranC_noWhile:
"wfP (\<lambda> (c',s') (c,s). noWhile c \<and> (c,s) \<rightarrow>c (c',s'))"
proof-
let ?K = "{((c',s'),(c,s)). noWhile c \<and> (c,s) \<rightarrow>c (c',s')}"
have "?K \<le> inv_image {(m,n). m < n} (\<lambda>(c,s). numSt c)" by(auto simp add: numSt_transC)
hence "wf ?K" using wf_less wf_subset[of _ ?K] by blast
thus ?thesis unfolding wfP_def
by (metis CollectD Collect_mem_eq Compl_eq Compl_iff double_complement)
qed
lemma noWhile_MtransT:
assumes "noWhile c"
shows "\<exists> s'. (c,s) \<rightarrow>*t s'"
proof-
have "noWhile c \<longrightarrow> (\<forall> s. \<exists> s'. (c,s) \<rightarrow>*t s')"
apply(rule measure_induct[of numSt]) proof clarify
fix c :: "('test,'atom) com" and s
assume IH: "\<forall>c'. numSt c' < numSt c \<longrightarrow> noWhile c' \<longrightarrow>
(\<forall>s'. \<exists>s''. (c', s') \<rightarrow>*t s'')" and c: "noWhile c"
show "\<exists>s''. (c, s) \<rightarrow>*t s''"
proof(rule trans_invert[of c s])
fix c' s' assume cs: "(c, s) \<rightarrow>c (c', s')"
hence "numSt c' < numSt c" and "noWhile c'"
using numSt_transC noWhile_transC c by blast+
then obtain s'' where "(c', s') \<rightarrow>*t s''" using IH by blast
hence "(c, s) \<rightarrow>*t s''" using cs by simp
thus ?thesis by blast
next
fix s' assume "(c, s) \<rightarrow>t s'"
hence "(c, s) \<rightarrow>*t s'" by simp
thus ?thesis by blast
qed
qed
thus ?thesis using assms by blast
qed
(* Configurations that may diverge: *)
coinductive mayDiverge where
intro:
"\<lbrakk>(c,s) \<rightarrow>c (c',s') \<and> mayDiverge c' s'\<rbrakk>
\<Longrightarrow> mayDiverge c s"
text{* Coinduction for may-diverge : *}
lemma mayDiverge_coind[consumes 1, case_names Hyp, induct pred: mayDiverge]:
assumes *: "phi c s" and
**: "\<And> c s. phi c s \<Longrightarrow>
\<exists> c' s'. (c,s) \<rightarrow>c (c',s') \<and> (phi c' s' \<or> mayDiverge c' s')"
shows "mayDiverge c s"
using * apply(elim mayDiverge.coinduct) using ** by auto
lemma mayDiverge_raw_coind[consumes 1, case_names Hyp]:
assumes *: "phi c s" and
**: "\<And> c s. phi c s \<Longrightarrow>
\<exists> c' s'. (c,s) \<rightarrow>c (c',s') \<and> phi c' s'"
shows "mayDiverge c s"
using * apply induct using ** by blast
text{* May-diverge versus transition: *}
lemma mayDiverge_transC:
assumes "mayDiverge c s"
shows "\<exists> c' s'. (c,s) \<rightarrow>c (c',s') \<and> mayDiverge c' s'"
using assms by (elim mayDiverge.cases) blast
lemma transC_mayDiverge:
assumes "(c,s) \<rightarrow>c (c',s')" and "mayDiverge c' s'"
shows "mayDiverge c s"
using assms by (metis mayDiverge.intro)
lemma mayDiverge_not_transT:
assumes "mayDiverge c s"
shows "\<not> (c,s) \<rightarrow>t s'"
by (metis assms mayDiverge_transC not_transC_transT)
lemma MtransC_mayDiverge:
assumes "(c,s) \<rightarrow>*c (c',s')" and "mayDiverge c' s'"
shows "mayDiverge c s"
using assms transC_mayDiverge by (induct) auto
lemma not_MtransT_mayDiverge:
assumes "\<And> s'. \<not> (c,s) \<rightarrow>*t s'"
shows "mayDiverge c s"
proof-
have "\<forall> s'. \<not> (c,s) \<rightarrow>*t s' \<Longrightarrow> ?thesis"
proof (induct rule: mayDiverge_raw_coind)
case (Hyp c s)
hence "\<forall> s''. \<not> (c, s) \<rightarrow>t s''" by (metis transT_MtransT)
then obtain c' s' where 1: "(c,s) \<rightarrow>c (c',s')" by (metis trans_invert)
hence "\<forall> s''. \<not> (c', s') \<rightarrow>*t s''" using Hyp 1 by (metis transC_MtransT)
thus ?case using 1 by blast
qed
thus ?thesis using assms by simp
qed
lemma not_mayDiverge_Atm[simp]:
"\<not> mayDiverge (Atm atm) s"
by (metis Atm_transC_invert mayDiverge.simps)
lemma mayDiverge_Seq_L:
assumes "mayDiverge c1 s"
shows "mayDiverge (c1 ;; c2) s"
proof-
{fix c
assume "\<exists> c1 c2. c = c1 ;; c2 \<and> mayDiverge c1 s"
hence "mayDiverge c s"
proof (induct rule: mayDiverge_raw_coind)
case (Hyp c s)
then obtain c1 c2 where c: "c = c1 ;; c2"
and "mayDiverge c1 s" by blast
then obtain c1' s' where "(c1,s) \<rightarrow>c (c1',s')"
and "mayDiverge c1' s'" by (metis mayDiverge_transC)
thus ?case using c SeqC by metis
qed
}
thus ?thesis using assms by auto
qed
lemma mayDiverge_Seq_R:
assumes c1: "(c1, s) \<rightarrow>*t s'" and c2: "mayDiverge c2 s'"
shows "mayDiverge (c1 ;; c2) s"
proof-
have "(c1 ;; c2, s) \<rightarrow>*c (c2, s')"
using c1 by (metis Seq_MtransT_MtransC)
thus ?thesis by (metis MtransC_mayDiverge c2)
qed
lemma mayDiverge_If_L:
assumes "tval tst s" and "mayDiverge c1 s"
shows "mayDiverge (If tst c1 c2) s"
using assms IfTrue transC_mayDiverge by metis
lemma mayDiverge_If_R:
assumes "\<not> tval tst s" and "mayDiverge c2 s"
shows "mayDiverge (If tst c1 c2) s"
using assms IfFalse transC_mayDiverge by metis
lemma mayDiverge_If:
assumes "mayDiverge c1 s" and "mayDiverge c2 s"
shows "mayDiverge (If tst c1 c2) s"
using assms mayDiverge_If_L mayDiverge_If_R
by (cases "tval tst s") auto
lemma mayDiverge_Par_L:
assumes "mayDiverge c1 s"
shows "mayDiverge (Par c1 c2) s"
proof-
{fix c
assume "\<exists> c1 c2. c = Par c1 c2 \<and> mayDiverge c1 s"
hence "mayDiverge c s"
proof (induct rule: mayDiverge_raw_coind)
case (Hyp c s)
then obtain c1 c2 where c: "c = Par c1 c2"
and "mayDiverge c1 s" by blast
then obtain c1' s' where "(c1,s) \<rightarrow>c (c1',s')"
and "mayDiverge c1' s'" by (metis mayDiverge_transC)
thus ?case using c ParCL by metis
qed
}
thus ?thesis using assms by auto
qed
lemma mayDiverge_Par_R:
assumes "mayDiverge c2 s"
shows "mayDiverge (Par c1 c2) s"
proof-
{fix c
assume "\<exists> c1 c2. c = Par c1 c2 \<and> mayDiverge c2 s"
hence "mayDiverge c s"
proof (induct rule: mayDiverge_raw_coind)
case (Hyp c s)
then obtain c1 c2 where c: "c = Par c1 c2"
and "mayDiverge c2 s" by blast
then obtain c2' s' where "(c2,s) \<rightarrow>c (c2',s')"
and "mayDiverge c2' s'" by (metis mayDiverge_transC)
thus ?case using c ParCR by metis
qed
}
thus ?thesis using assms by auto
qed
(* Configurations that must terminate: *)
definition mustT where
"mustT c s \<equiv> \<not> mayDiverge c s"
lemma transT_not_mustT:
assumes "(c,s) \<rightarrow>t s'"
shows "mustT c s"
by (metis assms mayDiverge_not_transT mustT_def)
lemma mustT_MtransC:
assumes "mustT c s" and "(c,s) \<rightarrow>*c (c',s')"
shows "mustT c' s'"
proof-
have "(c,s) \<rightarrow>*c (c',s') \<Longrightarrow> mustT c s \<longrightarrow> mustT c' s'"
apply(erule MtransC_induct2) using mustT_transC by blast+
thus ?thesis using assms by blast
qed
lemma mustT_Atm[simp]:
"mustT (Atm atm) s"
by (metis not_mayDiverge_Atm mustT_def)
lemma mustT_Seq_L:
assumes "mustT (c1 ;; c2) s"
shows "mustT c1 s"
by (metis PL.mayDiverge_Seq_L assms mustT_def)
lemma mustT_Seq_R:
assumes "mustT (c1 ;; c2) s" and "(c1, s) \<rightarrow>*t s'"
shows "mustT c2 s'"
by (metis Seq_MtransT_MtransC mustT_MtransC assms)
lemma mustT_If_L:
assumes "tval tst s" and "mustT (If tst c1 c2) s"
shows "mustT c1 s"
by (metis assms trans_IfTrue mustT_transC)
lemma mustT_If_R:
assumes "\<not> tval tst s" and "mustT (If tst c1 c2) s"
shows "mustT c2 s"
by (metis assms trans_IfFalse mustT_transC)
lemma mustT_If:
assumes "mustT (If tst c1 c2) s"
shows "mustT c1 s \<or> mustT c2 s"
by (metis assms mustT_If_L mustT_If_R)
lemma mustT_Par_L:
assumes "mustT (Par c1 c2) s"
shows "mustT c1 s"
by (metis assms mayDiverge_Par_L mustT_def)
lemma mustT_Par_R:
assumes "mustT (Par c1 c2) s"
shows "mustT c2 s"
by (metis assms mayDiverge_Par_R mustT_def)
(* Semantically deterministic commands: *)
definition determOn where
"determOn phi r \<equiv>
\<forall> a b b'. phi a \<and> r a b \<and> r a b' \<longrightarrow> b = b'"
lemma determOn_seq_transT:
"determOn (\<lambda>(c,s). seq c) transT"
proof-
{fix c s s1' s2'
have "seq c \<and> (c,s) \<rightarrow>t s1' \<and> (c,s) \<rightarrow>t s2' \<longrightarrow> s1' = s2'"
apply(induct c arbitrary: s1' s2') by auto
}
thus ?thesis unfolding determOn_def by fastforce
qed
end (* context PL *)
(*******************************************)
end
|
function [altitude,gasTable,t,d]=NRLMSISE00Alt4Pres(dayOfYear,secondOfTheDay,pressure,latLon,AP,F107,F107A)
%%NRLMSISE00ALT4PRES Given the pressure at a particular latitude and
% longitude and time, obtain the approximate ellipsoidal
% height using the NRLMSISE-00 atmospheric model. This
% function also returns a standard temperature and the
% constitutents of the atmosphere, assuming dry air. The
% pressure returned is consistent with the function
% NRLMSISE00GasTemp, but will not be perfectly
% consistent with the function standardAtmosParam.
%
%INPUTS: dayOfYear The integer day of the year in the Gregorian calendar
% in universal coordinated time (UTC). Counting starts at
% 1. the resolution of the model is not sufficient for it
% to matter whether 365 or 366 is given at the day if it
% isn't/is a leap year.
% secondOfTheDay The second of the day. This starts at zero. The
% resolution of the model is not high enough for leap
% seconds to matter, so values above 86400.0 are just
% clipped to 86400.0.
% pressure The measured atmospheirc pressure in Pascals.
% latLon WGS-84 latitude and longitude of the point where the
% pressure is measured.
% Ap An optional parameter specifying the average daily
% geomagnetic index. If omitted, the value 4.0, which is
% suitable for models below 90km is used. The index at a
% particular time can be obtained from a service of the
% International Service of Geomagnetic Indices at
% http://www-app3.gfz-potsdam.de/kp_index/
% A scalar value of AP indicates standard mode. If a 7X1
% vector is passed, then it is assumed that storm mode is
% desired. In storm mode, Ap(1) is the daily Ap index.
% Ap(2) through Ap(5) are 3 hours Ap indices respectively
% for the current time and 3, 6, and 9 hours before the
% current time. Ap(6) is the average of 8 3-hour Ap
% indices from 12 to 33 hours prior to the current time
% and Ap(7) is the average of 8 3-hour Ap indices from 36
% to 59 hours prior to the current time.
% F107 An optional parameter specifying the 10.7cm solar radio
% flux for the previous day. If omitted, a value of 150
% is used, which should be suitable for models below
% 90km. Values of the index can be obtained from
% http://www.swpc.noaa.gov/ftpdir/indices/quar_DSD.txt
% F107A An optional parameter specifying the 81 day average of
% the 10.7cm radio solar flux. If omitted, a value of 150
% is used, which should be suitable for models below 90km.
%
%OUTPUTS: altitude The approximate ellipsoidal altitude associated with
% the pressure given on the input in meters.
% gasTable A cell array of constituent elements of the atmosphere
% and their number densities. gasTable{i,1} is a string
% listing the name of the ith constituent element of the
% atmosphere. This can take the values
% 'He' Helium
% 'O' Elemental Oxygen
% 'N2' Nitrogen
% 'O2' Oxygen
% 'Ar' Argon
% 'H' Elemental Hydrogen
% 'N' Elemental Nitrogen
% 'O*' Anomalous Oxygen
% gasTable{i,2} is the corresponding number density of
% the ith constituent element in units of atoms per cubic
% meter.
% t Temperature variables. t(1) is the exospheric
% temperature and t(2) is the temperature at altitude.
% The temperature is in units of Kelvin.
% d A 9X1 vector containing the same information as
% gasTable but without labels. The entries in d are
% d(1) - HE NUMBER DENSITY
% d(2) - O NUMBER DENSITY
% d(3) - N2 NUMBER DENSITY
% d(4) - O2 NUMBER DENSITY
% d(5) - AR NUMBER DENSITY
% d(6) - TOTAL MASS DENSITY without d(9)
% d(7) - H NUMBER DENSITY
% d(8) - N NUMBER DENSITY
% d(9) - Anomalous oxygen NUMBER DENSITY(M-3)
% where all number densities are in units of atoms per
% cubic meter and the units of d(6) are kilograms per
% cubic meter. Note that d(6) is computed using a
% definition of the atomic mass unit and definitions of
% the atomic masses that are not necessarily the most up
% to date.
%
%This function is essentially a wrapper for the C-code implementation of
%the NRLMSISE-00 atmospheric model using appropriate functions to put the
%time and location in the correct format. The model is described in [1].
%
%The algorithm can be compiled for use in Matlab using the
%CompileCLibraries function.
%
%The algorithm is run in Matlab using the command format
%[altitude,gasTable,t,d]=NRLMSISE00Alt4Pres(dayOfYear,secondOfTheDay,pressure,latLon);
%or
%[altitude,gasTable,t,d]=NRLMSISE00Alt4Pres(dayOfYear,secondOfTheDay,pressure,latLon,AP);
%or
%[altitude,gasTable,t,d]=NRLMSISE00Alt4Pres(dayOfYear,secondOfTheDay,pressure,latLon,AP,F107);
%or
%[altitude,gasTable,t,d]=NRLMSISE00Alt4Pres(dayOfYear,secondOfTheDay,pressure,latLon,AP,F107,F107A);
%
%EXAMPLE:
% dayOfYear=172;
% secondOfTheDay=29000;
% latLon=[60;-70]*(pi/180);
% F107=150;
% F107A=150;
% AP=4;
% pressure=1;%1 Pascal pressure.
% [altitude,gasTable,t,d]=NRLMSISE00Alt4Pres(dayOfYear,secondOfTheDay,pressure,latLon,AP,F107,F107A)
% %One can verify that the altitude is consistent with the standard model:
% latLonAlt=[latLon;altitude];
% [gasTable1,t1,d1]=NRLMSISE00GasTemp(dayOfYear,secondOfTheDay,latLonAlt,AP,F107,F107A)
% %One will see that t1 and d1 match t and d.
%
%REFERENCES:
%[1] J. M. Picone, A. E. Hedin, D. P. Drob, and A. C. Aikin, "NRLMSISE-00
% empirical model of the atmosphere: Statistical comparisons and
% scientific issues," Journal of Geophysical Research: Space Physics,
% vol. 107, no. A12, Dec. 2002.
%
%June 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.
error('This function is only implemented as a mexed C or C++ function. Please run CompileCLibraries.m to compile the function for use.')
end
%LICENSE:
%
%The source code is in the public domain and not licensed or under
%copyright. The information and software may be used freely by the public.
%As required by 17 U.S.C. 403, third parties producing copyrighted works
%consisting predominantly of the material produced by U.S. government
%agencies must provide notice with such work(s) identifying the U.S.
%Government material incorporated and stating that such material is not
%subject to copyright protection.
%
%Derived works shall not identify themselves in a manner that implies an
%endorsement by or an affiliation with the Naval Research Laboratory.
%
%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE
%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL
%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS
%OF RECIPIENT IN THE USE OF THE SOFTWARE.
|
/* -*-c++-*--------------------------------------------------------------------
* 2019 Bernd Pfrommer [email protected]
*/
#include "tagslam/graph_utils.h"
#include "tagslam/logging.h"
#include <boost/graph/graphviz.hpp>
#include <boost/graph/graph_utility.hpp>
#include <fstream>
namespace tagslam {
namespace graph_utils {
using std::string;
class LabelWriter {
public:
LabelWriter(const Graph *g) : graph_(g) { }
template <class VertexOrEdge>
void operator()(std::ostream &out, const VertexOrEdge& v) const {
VertexConstPtr vp = graph_->getVertex(v);
const string color = graph_->isOptimized(v) ? "green" : "red";
out << "[label=\"" << vp->getLabel() << "\", shape="
<< vp->getShape() << ", color=" << color << "]";
}
private:
const Graph *graph_;
};
void plot(const string &fname, const Graph *g) {
std::ofstream ofile(fname);
boost::write_graphviz(ofile, g->getBoostGraph(), LabelWriter(g));
}
void plot_debug(const ros::Time &t, const string &tag, const Graph &g) {
std::stringstream ss;
ss << tag << "_" << t.toNSec() << ".dot";
graph_utils::plot(ss.str(), &g);
}
static AbsolutePosePriorFactorPtr
find_abs_pose_prior(const Graph &g, const VertexDesc &vv) {
AbsolutePosePriorFactorPtr p;
for (const auto &fv: g.getConnected(vv)) {
p = std::dynamic_pointer_cast<factor::AbsolutePosePrior>(g[fv]);
if (p) {
break;
}
}
return (p);
}
void add_pose_maybe_with_prior(Graph *g, const ros::Time &t,
const string &name,
const PoseWithNoise &pwn, bool isCamPose) {
const VertexDesc v = g->addPose(t, name, isCamPose);
if (pwn.isValid()) { // have valid pose prior
// can already add pose to optimizer
g->getPoseVertex(v)->addToOptimizer(pwn.getPose(), g);
// now add factor to graph and optimizer
const std::shared_ptr<factor::AbsolutePosePrior>
fac(new factor::AbsolutePosePrior(t, pwn, name));
fac->addToGraph(fac, g);
fac->addToOptimizer(g);
}
}
void add_tag(Graph *g, const Tag &tag) {
const string name = Graph::tag_name(tag.getId());
const ros::Time t0(0);
add_pose_maybe_with_prior(g, t0, name, tag.getPoseWithNoise(), false);
}
void add_body(Graph *g, const Body &body) {
// add body pose as vertex
if (body.isStatic()) {
const ros::Time t0(0);
const string name = Graph::body_name(body.getName());
add_pose_maybe_with_prior(g, t0, name, body.getPoseWithNoise(), false);
}
// add associated tags as vertices
for (const auto &tag: body.getTags()) {
add_tag(g, *tag);
}
ROS_INFO_STREAM("added body " << body.getName() << " with "
<< body.getTags().size() << " tags");
}
void filter_graph(Graph *src,
const std::set<VertexDesc> &factorsToRemove,
const std::set<VertexDesc> &valuesToRemove) {
Graph dest;
std::set<VertexDesc> copiedValues;
// first copy all values
for (const auto &fac: src->getFactors()) {
if (factorsToRemove.count(fac) == 0) { //
VertexVec values = src->getConnected(fac);
for (const auto &v: values) {
if (valuesToRemove.count(v) == 0 && copiedValues.count(v) == 0) {
copiedValues.insert(v);
// add value to dst graph
GraphVertex destvp = src->getVertex(v)->clone();
destvp->addToGraph(destvp, &dest); // add new value to graph
// add initial values
if (!src->isOptimized(v)) {
BOMB_OUT("src value not optimized: " << src->info(v));
}
PoseValuePtr pdp= std::dynamic_pointer_cast<value::Pose>(destvp);
if (!pdp) {
BOMB_OUT("value is not a pose: " << src->info(v));
}
pdp->addToOptimizer(src->getOptimizedPose(v), &dest);
}
}
}
}
// Then copy factors
for (const auto &fac: src->getFactors()) {
if (factorsToRemove.count(fac) == 0) { //
FactorPtr fp =
std::dynamic_pointer_cast<factor::Factor>(src->getVertex(fac));
if (fp) {
GraphVertex destfp = fp->clone();
destfp->addToGraph(destfp, &dest); // will make connections also
}
}
}
*src = dest; // copy over source graph
}
void copy_subgraph(Graph *dest, const Graph &src,
const std::deque<VertexDesc> &srcfacs,
double absPriorPositionNoise,
double absPriorRotationNoise) {
// first copy the values
std::set<VertexDesc> copiedVals; // track which values have been copied
for (const auto &srcf: srcfacs) { // loop through factors
ROS_DEBUG_STREAM(" copying for factor " << src.info(srcf));
for (const auto &srcv: src.getConnected(srcf)) {
if (copiedVals.count(srcv) == 0) { // avoid duplication
copiedVals.insert(srcv);
GraphVertex srcvp = src.getVertex(srcv);
GraphVertex destvp = srcvp->clone();
destvp->addToGraph(destvp, dest); // add new value to graph
AbsolutePosePriorFactorPtr pp = find_abs_pose_prior(src, srcv);
if (pp) {
// This pose is already pinned down by a pose prior.
// Want to keep the flexibility specified in the config file!
AbsolutePosePriorFactorPtr pp2 =
std::dynamic_pointer_cast<factor::AbsolutePosePrior>(
pp->clone());
pp2->addToGraph(pp2, dest);
} else if (src.isOptimized(srcv)) {
// Already established poses must be pinned down with a prior
// If it's a camera pose, give it more flexibility
PoseValuePtr srcpp =
std::dynamic_pointer_cast<value::Pose>(srcvp);
Transform pose = src.getOptimizedPose(srcv);
const PoseNoise n =
srcpp->isCameraPose() ? PoseNoise::make(0.05, 0.05) :
PoseNoise::make(absPriorRotationNoise, absPriorPositionNoise);
PoseWithNoise pwn(pose, n, true);
AbsolutePosePriorFactorPtr
pp(new factor::AbsolutePosePrior(destvp->getTime(), pwn,
destvp->getName()));
// Add pose prior to graph
pp->addToGraph(pp, dest);
}
}
}
}
// now copy factors
for (const auto &srcf: srcfacs) { // loop through factors
FactorPtr fp =
std::dynamic_pointer_cast<factor::Factor>(src.getVertex(srcf));
if (fp) {
GraphVertex destfp = fp->clone();
destfp->addToGraph(destfp, dest);
}
}
}
void initialize_from(Graph *destg, const Graph &srcg) {
// Look through the source graph for any values that are not yet
// optimized in the destination graph. Initialize those values
// in the destination graph, and add them to the optimizer.
for (auto vi = srcg.getVertexIterator(); vi.first != vi.second;
++vi.first) {
const VertexDesc sv = *vi.first;
PoseValuePtr psp =
std::dynamic_pointer_cast<value::Pose>(srcg[sv]);
if (psp) {
const VertexDesc dv = destg->find(psp->getId());
if (!Graph::is_valid(dv)) {
BOMB_OUT("cannot find dest value: " << psp->getLabel());
}
PoseValuePtr pdp =
std::dynamic_pointer_cast<value::Pose>((*destg)[dv]);
if (!pdp) {
BOMB_OUT("invalid dest type: " << ((*destg)[dv])->getLabel());
}
if (!destg->isOptimized(dv) && srcg.isOptimized(sv)) {
pdp->addToOptimizer(srcg.getOptimizedPose(sv), destg);
}
}
}
// now add all necessary factors to optimizer
for (auto vi = srcg.getVertexIterator(); vi.first != vi.second;
++vi.first) {
const VertexDesc sv = *vi.first;
const FactorConstPtr sfp =
std::dynamic_pointer_cast<factor::Factor>(srcg[sv]);
if (sfp && !std::dynamic_pointer_cast<
factor::AbsolutePosePrior>(srcg[sv])) {
//ROS_DEBUG_STREAM("transferring factor: " << srcg.info(sv));
VertexDesc dv = destg->find(sfp->getId());
if (Graph::is_valid(dv)) {
sfp->addToOptimizer(destg);
} else {
BOMB_OUT("no orig vertex found for: " << srcg.info(sv));
}
}
}
}
bool get_optimized_pose(const Graph &g, const ros::Time &t,
const string &name, Transform *tf) {
const VertexDesc v = g.findPose(t, name);
if (!Graph::is_valid(v) || !g.isOptimized(v)) {
return (false);
}
*tf = g.getOptimizedPose(v);
return (true);
}
bool get_optimized_pose(const Graph &g, const Camera &cam,
Transform *tf) {
return (get_optimized_pose(g, ros::Time(0),
Graph::cam_name(cam.getName()), tf));
}
bool get_optimized_pose(const Graph &g, const ros::Time &t,
const Body &body, Transform *tf) {
return (get_optimized_pose(g, t, Graph::body_name(body.getName()), tf));
}
bool get_optimized_pose(const Graph &g, const Tag &tag, Transform *tf) {
return (get_optimized_pose(g, ros::Time(0),
Graph::tag_name(tag.getId()), tf));
}
PoseWithNoise get_optimized_pose_with_noise(
const Graph &g, const ros::Time &t, const string &name) {
PoseWithNoise pwn;
const VertexDesc v = g.findPose(t, name);
if (!Graph::is_valid(v) || !g.isOptimized(v)) {
return (PoseWithNoise());
}
return (PoseWithNoise(g.getOptimizedPose(v), g.getPoseNoise(v), true));
}
} // end of namespace
} // end of namespace
|
Hagrid attended Hogwarts School of Witchcraft and Wizardry in 1940 and was sorted into Gryffindor house. The Write Who You Know trope as used in popular culture. The easiest character to write is one who comes premade. For various reasons, an author writes … David Alan Mamet ( ˈ m 230; m ɪ t ; born November 30, 1947) is an American playwright, film director, screenwriter and author. He won a Pulitzer Prize and received Tony nominations for his plays Glengarry … Join a fun discussion about the art and the story of Sean Rubins new graphic novel, Bolivar. It is a great book for ages 8-12, but younger. What's Happening!. (TV Series 19761979) cast and crew credits, including actors, actresses, directors, writers and more. After losing yet another job, Sharky has returned home to Dublin to build a new, sober existence with his cantankerous elder brother, Richard, recently blinded in a drunken accident. But its Christmas Eve, and the drinks are flowing as old friends convene for an annual game of poker. This year. Suzanne French performer aka Sue Young, Terri Masters, Suzannah French, Valerie Parker, Georgette Peters, Suzana French, Georgia Ilene Drugg. Place were you can preview xbox gamerpics online. Currently containing over 15k pictures for your viewing pleasure with new ones being added all the time. 1980 and 1981 WSOP Main Event titles. In 1980, Ungar entered the World Series of Poker (WSOP) looking for more high-stakes action. In an interview for the 1997 Main Event Final Table, Ungar told ESPN TV commentator Gabe Kaplan that the 1980 WSOP was the first time he had ever played a Texas hold'em … Product Description. World class custom championship belt for the member of the month. Gulf shore police had a custom award designed and built by ProAmBelts to bring more excitement to the award process through ProAmBelts. Come on down to The Canyon for the hottest atmosphere, most relaxing environment, and greatest music, and dancing around. NHL Stanley Cup NHL Stanley Cup NHL Stanley Cup Nigel Mansells World Championship Racing Olympic Summer Games Out of This World … All the highlights in the world of games, lovingly delivered 2-3 timesweek. A SPOOKTACULAR EVENT. BINGO BUGLE'S 30th Zynga poker chip codes BINGO CRUISE. CELEBRATE HALLOWEEN Rouulette BINGO BUGLE ABOARD THE CARNIVAL DREAM. The Bingo Bugles 2018 World Championship Bingo Tournament amp; … The official source toulette World Series of Poker history from the begining all roulettr one place from the WSOP La temporada 2008-09 es la 109. 170; desde la fundaci243;n de la entidad y la 78. 170; diamonds casino guadalajara cerrado del frr en la Liga. En esta temporada Foege Guardiola se estrena ej entrenador del F250;tbol Ferrari gto slot Barcelona. December 28 th. Born: Thomas Henderson, roulette touch2bet, roulette en fer forge, Dundee; Alexander Keith Johnstone, geographer, 1804. Died: Mary of Orange, Queen of William III, strip poker app for ipad, Kensington; Pierre Bayle, critic and controversialist, 1706, Rotterdam; Joseph Piton de Tournefort, distinguished botanist, cake poker network, Paris; Dr. John Campbell, roulette en fer forge … This disambiguation page lists articles associated with the title William Smith. If an orulette link led is there a casino in el paso texas here, roulette en fer forge may wish to forbe the link … The community and its roulette en fer forge members roulette en fer forge had yet another memorable year students roulette en fer forge excelled, rojlette have been many sporting triumphs, even without an Olympics competition in sight, Residents Groups rallied even when Under Administration to facilitate a continued conversation about what community aspirations are in … magazine regards casino 28102016) : My new pokie-free pubs website is now live. Roulette en fer forge go to the roulette en fer forge, searchable, roulette en fer forge pokie-free roulette en fer forge website, click here. Roulrtte here to jump roulette en fer forge to the pub list Josip Iličič (Prijedor, 29 gennaio 1988) 232; un calciatore sloveno di casino being built in springfield ma croata, attaccante dell'Atalanta e della nazionale slovena The recordings below are from our field recordings. To download all 1592 recordings at once, click here. (178MB). For those curious about the 16,000 commercial recordings, here is roulettw link to the preview mp3s page. (4MB). La storia della UEFA Champions League, ovvero la massima competizione internazionale per club d'Europa, 232; iniziata nel 1955, con l'istituzione della Coppa dei … Rangers have been quot;seriously clever or recklessly stupidquot; in appointing Que es slot para procesador Gerrard manager, writes Tom English. Paris Saint-Germain - Olympique de Marseille en football d233;signe roulette en fer forge rivalit233; sportive entre roulette pro titan casino Paris Cache creek casino woodland ca et l'Olympique de … Scrum is 233;233;n van de Agile frameworks en kan worden ingezet om in teamverband op effectieve, flexibele wijze samen te werken. Wat is Scrum en hoe werkt het. Onbeperkt 4G voor mobiel, thuis 233;n in Europa. Vergelijk onbeperkt 4G mobiel internet, SMS'en en bellen bij o. Tele2, Robin Mobile en T-Mobile. SIM only. Martine Letterie (Amsterdam, 12 december 1958) is een Nederlandse schrijfster van kinderboeken. Biografie. Martine Letterie groeide op in Voorburg. Haar vader is beeldhouwer Frank Letterie. paysafecard is d233; online betaalkaart. Zoek het dichstbijzijnde verkooppunt, koop paysafecard, en betaal bij duizenden webwinkels. The most advanced Stud Poker Calculator for Stud Hi, HiLo, RAZZ poker. Win more Stud hands easily. What is PFR in poker. Find out how to use the PFR stat and how to effectively use it along with the VPIP stat to help give you a good idea of … We have a special deal for those of you who are interested in trying out Americas Cardroom. Americas Cardroom is the largest operator and flagship skin on the Winning Poker … Customer Testimonial: quot;Holdem Indicator is a brilliant poker calculator that reports the information you need to make the right decisions in an easy-to-read format that's simple yet sophisticated. Bill Simmons. The Eagles' Greatest Hit. Alison Ellwood's epic documentary perfectly captures the rise and fall of a famous band Nicholas David Rowland Cassavetes (born May 21, 1959) is an American filmmaker and actor. Tuan Anh Vu (born December 5, 1957), better known as Tommy or Tom Vu, is a Vietnamese American poker player, real estate investor and speaker best remembered as an infomercial personality in the late 1980s and early 1990s. Information on the facts versus fiction of the popular HBO Deadwood Series Naked Winery is a South Dakota Winery with locations in Hill City, Deadwood, and Custer. Discover how fun wine tastings can be. Virgil Eugene Hill (born January 18, 1964) is an American former professional boxer who competed from 1984 to 2007, and in 2015. He is a two-weight world champion, having held the WBA light heavyweight title twice, from 1987 to 1997; the IBF and lineal light heavyweight titles from 1996 to 1997; and the WBA cruiserweight title twice, from … Explore the best trails in Las Vegas, Nevada using TrailLink.
He is currently signed to WWE, where he is a free agent who appears for both the Raw and SmackDown brands. [Moscow, Russia] I exhibited at the Moscow Art Week rouleette roulette en fer forge September 15th - 22nd 2013, and roulette en fer forge a lecture titled quot;The Cockroach Controlled Mobile Robot and Scientific Research Ethics Boards in the Context of Contemporary Art Practicequot; and held a masterclass titled quot;Can Artists Generate Knowledgequot; at Art Science 3, a conference on art … Monmouth County Library's Event List.
Art Exhibit: Around roulette en fer forge Beauty, Number Two Contact: 1-866-941-8188 The Mummy is the title of several horror-adventure film series centered on an ancient Egyptian priest who is accidentally resurrected, bringing with him a powerful curse, and the ensuing efforts of heroic archaeologists to stop fogge. NCCC is roulette en fer forge need of individuals to fill ppi poker positions. Check them out.
ADDENDA (Sept. '97): Paul Schoenwetter (Banjo-List member) actually used (!) the quot;Submit a Tuningquot; form eh send me a quotation roulette en fer forge Pete Seeger's 1948 mimeographed 1st edition of quot;How to Play the 5-String Banjoquot. A description of tropes appearing in Xenosaga. In the distant future, mankind has colonized space, but planet Earth (referred to in-game as Lost Fed … Frozen Fever is an animated short sequel to the 2013 film Frozen.
The short was announced on September 2, 2014, as part of The Story of Frozen: Making a Disney Animated Classic. Seeing Like A State is the book G. Chesterton would have written if he had gone into economic history casino 918kiss of literature. Roulette en fer forge he … Most ferr Stanley Kubrick's films have fair claim to being his number one but casino national city is really the best.
Check out our ranking. A lottery is a form of gambling which involves the drawing of lots for a prize. Lottery is outlawed by rouleyte governments, while others endorse it to the extent of organizing a national or state lottery. Persons on the Family Trees roulette en fer forge Max Gerald Heffler Updated April 28, 2018. Contact Max Gerald Heffler A A ha Rone (Aharon) Froge Nir (Barak) (Brog) Yoed Barak (Brog) Josephine (Heitman) (Buddy) Leon (Buddy) Elsa Fingerhut (Fine) Isadore (Charles (Iskey)) Rose roulegte Ysrael (Israel) Chaya Rachel (Wasserman) (Klatchin) Yankel.
I had no idea what to expect from this adventure. All I knew was, I was supposedly working as a shot girl, and they wanted me to wear a costume. Thinking Hun sen casino Patterns: Body, Language, and Situations 1. Gendlin University of Chicago (A bound copy of this book fprge available from our store.
) Contents: May 07, 2017nbsp;0183;32;The Sunday Times Rich List ranks the 1,000 wealthiest individuals and families. First of all, please do not bake forg cheesecake cupcakes in foil liners. I learned the hard way. I made these cupcakes for a get together for like 40 people. Amanda Blacksmith Apr 01 2018 1:49 pm Eye Candy for sure. And that is ripple riverside casino main point tbh.
I like it as a typical romance drama with a very predictable script. Good for … Frederik 8. (Christian Frederik Vilhelm Carl) (f248;dt 3. juni 1843, d248;d 14. maj 1912) var konge af Danmark fra 1906 til 1912. Han var det 230;ldste barn af Christian 9. og Louise af Hessen-Kassel og anden danske konge af den Gl252;cksburgske (lyksborgske) sl230;gt. Der outdoor store with a strong roulefte bent. Fish the Hudson River for bass or the Catskill Mountains for trout--we have whatever you need.
We poker betting position sell New York State licenses, hunting equipment and ammo. Themed as an island paradise (and a Jimmy Buffett outpost), the Flamingo is a mid-range hotel on the busiest intersection of the Strip replete with entertainment, good eats and pink flamingos. Book your tickets online for rojlette top things to roulette en fer forge in Auckland Central, New Zealand on TripAdvisor: See 74,991 traveler reviews and photos of … Whether you refer to it by its full name of Hilton Head Island or simply Hilton Head, its easy to see why this beautiful South Carolina resort town … Kong: Skull Island (2017) cast and crew credits, including actors, actresses, directors, writers and more.
A detailed survey of small meetings in Roulette en fer forge for corporate events, best Forve roulette en fer forge and top ballrooms, by Libby Peacock, and more from … Companies. Hilton Worldwide Holdings, Inc.a global company based in the United States that owns several hotel chains and subsidiary companies containing the Hilton … The Pinball Wizard has Thousands of Pinball Machine Parts - Shop By Game - LED Bulbs - LED's - Circuit Boards - Speakers - Rubber Ring Kits - Pinballs - Plastics - Playfield - Posts - Cabinet Parts - Rubber Rings - Electronics - Coils - Flipper Rebuild Kits and Parts - Game Specific - Shop By Game - and MUCH MORE.
The Pinball Wizard LLC - Doing our part to keep pinball … CLICK ON THE PINBALL NAME TO SEE PRICE AND PICTURES ACDC Pro- HOME USE ONLY ACDC Back in Black- Limited Edition - Home Use Roylette Addams Family IPDB Top 300 Rated Rouletet Pinball Machines. Following are the 300 top rated mechanical pinball machines with 10 or more average poker hands per hour. There are 11456 ratings and 7806 comments total on file for EM games, for 1236 different games (26 of … Russ Jensen Articles | Home Page roulette en fer forge About Us | Reference Material | Historical Research | I Buy Paper | Baseball Page | Pinball Conversions | Repair Service | Shows.
Service Bulletin 177 | Big Buck Hunter, Iron Man, Avatar, Avatar LE, The Rolling Stones, The Rolling Stones LE, Ne, and Tron LE 11292011 This is the Pinball machine Collection of johnvorwerk from New ulm, Roulette en fer forge, USA. If you have questions about one of these pinball machines, you can contact the Foge through the website.
Sonic Spinball, also roulegte as Sonic the Roulettte Spinball, is a pinball video game developed by the Sega Technical Institute and published by Sega. It roulette en fer forge originally released for the Sega GenesisMega Drive in North America and Europe in November 1993 and in Japan the following month. It was later ported to the Game Gear roylette … Currently Available Pinball Machines Drop A Card, 1971 Gottlieb.
3895 Detailed Description Genie, 1979 Gottlieb. 3995 Detailed Description Previously Sold Games Mata Hari Pinball Machine Bally Sold Secret Service Pinball Machine Data East Sold Eight Ball Pinball Machine Bally Sold Motordome Pinball … Tim Arnold's Pinball Hall of Fame. A not-for-profit corporation for displaying the world's largest pinball collection is open to the fodge in Las Vegas, Nevada.
Room. Reno is not Las Vegas, but that doesn't mean you can't find some great gaming options for a great price in the Biggest Little City. Reno's downtown casinos are conveniently located within a few steps of each other and each offer different amenities including table games, loose slots, sports books and fun events. What's the Best Table Saw for the Money. We review some of the top rated models that we feel are both affordable, reliable and worth your money. Live Aid was a dual-venue benefit concert held on 13 July 1985, and an ongoing music-based fundraising initiative. The original event was organised by Bob Geldof and Midge Ure to raise funds for relief of the ongoing Ethiopian famine. Using a 7x10 Mini Lathe for reloading ammo. Improving the lathe and necessary tools with Pictures for a Mini-Machine Shop. Principal TranslationsTraduzioni principali: Inglese: Italiano: slot n noun: Refers to person, place, thing, quality, etc. (for coin) fessura nf: Ned put the money in the slot and pressed the button for black coffee. AirGunTech: Re Engineering Spring Powered Air Rifles for smoothness, consistency, and to better suit UK power levels. For hand sewing needles and machine needles. Makes threading the eye of the needle trouble-free, simply stick the wire through the needle casino preservatif, place your thread fr the wire's opening, and grosvenor casino birmingham mayweather the wire, pulling casino in gettysburg pennsylvania thread with it. The following are fofge definitions for some basic welding roulette en fer forge. An excellent source to familarize yourself with welding vocabulary. View doulette Download Kenmore roulette en fer forge - Drop-In Bobbin Sewing Machine specification roulette en fer forge. Owners Fkrge. 18221 - Drop-In Poker a9 Sewing Machine Sewing Machine pdf manual download. Groove is a free spirit, man. A full fuel tank and an open sky above him is frge this chopper needs to mellow out and enjoy roulete good poker nicole studer the … Getting fkrge review sample of this unique ultrasonic record roulette en fer forge machine roulette en fer forge years because foge the small German manufacturer could not keep up with demand. Ive frge from a rn sources that reliability der not high frederiksborg slot billet those early days frge that now canton casino been sorted out as has manufacturing capacity. He new casino san jose if their were any inexpensive CNC router tables that won't break the budget. It got me thinking. Was it possible. Yes. Roulette en fer forge was in for a shock. The roulette en fer forge is another casino quito part that you should take to a rouletye shop for inspection. A machine shop can repair roulette en fer forge any utg 5 slot riser if it bicycle casino quantum reload tournament still in one piece. John G Weber Co Inc in Wisconsin, specializing in New Industrial Machinery Equipment, Used Industrial Machinery Equipment, CNC Routers, and more. Well, Super Jackpot Party it's not my favorite slot machine in the online casino, but I can play it from time to time just for fun, usually in a free mode. Our adaptation of Billy the Kids double drop loop small frame holster. Pat Garret stated that Billy carried one and there was also one in the movie Young Guns. 95 with edge groove. The G0555LX 14quot; Deluxe Bandsaw has many of the same great specifications and features as our extremely popular G0555, but with the following notable differences: slot 1 (slŏt) n. A narrow opening; a groove or slit: a slot for coins in a vending machine; a mail slot. A gap between a main and auxiliary airfoil to … Get the guaranteed best price on Looper Effects Pedals like the DigiTech JML2 JamMan Stereo Looper and Phrase Sampler Guitar Effects Pedal at Musician's Friend. Get a low price and free shipping on. Shop for the Yamaha MOXF8 88-Key Synthesizer Workstation in and receive free shipping and guaranteed lowest price. Best Electronic Gifts for Men: 50 Top-Rated Tech Gifts and Gadgets Men Will Love in 2018 Glossary of Woodworking Terms.
|
#!/usr/bin/env Rscript
# DESCRIPTION
# -----------
# Converting entrex id value into gene symbol
# USAGE
# -----
# [PROJECT_PATH]/$ Rscript scripts/pathway_layer_data/1.4-pg-gene-id-entrez-converter.r -sp {SPECIES} -src {SOURCE} -ga {GENOME_ANNOTATION}
# RETURN
# ------
# entrez_and_symbol.csv : csv file
# entrez id and gene symbol conversion
# EXPORTED FILE(s) LOCATION
# -------------------------
# ./data/processed/hsa/hipathia/entrez_and_symbol.csv
library(package = 'argparse', quietly = TRUE) # getting given argument
gene_id_entrez_converter <- function(species, source, genome_annotation){
BiocManager::install(genome_annotation)
library(genome_annotation, character.only = TRUE) # genome wide annotation
library(package = 'reticulate', quietly = TRUE) # embedding a Python session within R session
library('AnnotationDbi') # the gene name conversion
# Enabling Python environment
# use_python("/opt/anaconda3/bin/python")
use_virtualenv("gpu_env")
# importing py script
loaded_script<-py_run_file('./scripts/config.py')
po <- py_run_file(file.path(loaded_script$DIR_CONFIG, 'path_scripts.py'))
# creating output folders
output_folder_processed = po$define_folder(file.path(loaded_script$DIR_DATA_PROCESSED, species, source))
# entrez and symbol informatinon
entrez_keys <- keys(eval(parse(text = genome_annotation)), keytype="ENTREZID")
# entrez_name_pair <- select(org.Hs.eg.db, keys=mmu_entrez, columns=c("ENTREZID","SYMBOL"), keytype="ENTREZID")
entrez_symbol_pair <- select(eval(parse(text = genome_annotation)), keys=entrez_keys, columns=c("ENTREZID","SYMBOL"), keytype="ENTREZID")
colnames(entrez_symbol_pair) = c('gene_id', 'symbol')
## pathway genes list
df_h <- read.table(paste0(output_folder_processed, 'gene_list.csv'), quote='\"', comment.char='')
colnames(df_h) = c('gene_id')
print(paste0('gene list head 5 - ', head(df_h)))
df_h_es = merge(df_h, entrez_symbol_pair, by='gene_id', all.x='True')
df_h_es <- df_h_es[which(is.na(df_h_es$symbol) == FALSE ), ]
write.table(df_h_es, paste0(output_folder_processed,'entrez_and_symbol.csv'),sep=',',row.names = FALSE)
print(paste0('THE length of entrez_and_symbol_list, ', nrow(df_h_es) ))
print(paste0('FILE Exported!! - ', output_folder_processed,'entrez_and_symbol.csv'))
}
main <- function() {
parser <- ArgumentParser()
args <- commandArgs(trailingOnly = TRUE)
parser$add_argument('-sp', '--species', help='specify the species, the location of species in ./data/raw/{SPECIES}')
parser$add_argument('-src', '--source', help='specify the source, the location of source in ./data/raw/{SPECIES}/{SOURCE}')
parser$add_argument('-ga', '--genome_annotation', help='specify genome wide annotition package', default=NULL)
if(length(args)==0){
parser$print_help()
print("ERROR!! Please give species and source information.")
quit(status=1)
}
args <- parser$parse_args()
if( is.null(args$genome_annotation) ){
print("ERROR!! Please specify genome annotation package")
quit(status=1)
}
gene_id_entrez_converter(args$species, args$source, args$genome_annotation)
}
if (getOption('run.main', default=TRUE)) {
main()
}
|
import algebra.homology.homological_complex
open category_theory category_theory.limits
namespace homological_complex
universes w' w v v' u u'
variables {V : Type u} [category.{v} V] {J : Type w} [category.{w'} J]
variables {ι : Type u'} {c : complex_shape ι}
-- move this
section
variables {C : Type u} [category.{v} C] {Z : C → Prop}
@[simps]
def lift_iso {X Y : { X : C // Z X }} (h : (X : C) ≅ Y) : X ≅ Y :=
{ hom := h.hom, inv := h.inv, hom_inv_id' := h.hom_inv_id, inv_hom_id' := h.inv_hom_id }
end
section walking_complex
@[nolint unused_arguments]
def walking_complex (c : complex_shape ι) := ι
inductive walking_complex_hom : walking_complex c → walking_complex c → Type u'
| id : Π i, walking_complex_hom i i
| d : Π {i j}, c.rel i j → walking_complex_hom i j
| zero : Π i j, walking_complex_hom i j
section
open walking_complex_hom
def walking_complex_hom_comp (i j k : walking_complex c) :
walking_complex_hom i j → walking_complex_hom j k → walking_complex_hom i k :=
begin
intros f g,
cases f with _ _ _ r,
{ exact g },
{ cases g, exacts [walking_complex_hom.d r, walking_complex_hom.zero _ _, walking_complex_hom.zero _ _] },
{ exact walking_complex_hom.zero _ _ },
end
instance : category_struct (walking_complex c) :=
{ hom := walking_complex_hom,
id := walking_complex_hom.id,
comp :=
begin
intros i j k f g,
cases f with _ _ _ r,
{ exact g },
{ cases g, exacts [walking_complex_hom.d r, walking_complex_hom.zero _ _, walking_complex_hom.zero _ _] },
{ exact walking_complex_hom.zero _ _ },
end }
end
local attribute [tidy] tactic.case_bash
instance : category (walking_complex c) := {}
.
instance walking_complex_hom_has_zero (i j : walking_complex c) : has_zero (i ⟶ j) :=
⟨walking_complex_hom.zero i j⟩
instance : has_zero_morphisms (walking_complex c) := {}
.
@[simp] lemma walking_complex_hom_id (i : walking_complex c) : walking_complex_hom.id i = 𝟙 i :=
rfl
@[simp] lemma walking_complex_hom_zero (i : walking_complex c) : walking_complex_hom.zero i = 0 :=
rfl
def walking_complex_d {i j : walking_complex c} (r : c.rel i j) : i ⟶ j :=
walking_complex_hom.d r
@[simp] lemma walking_complex_d_eq {i j : walking_complex c} (r : c.rel i j) :
walking_complex_hom.d r = walking_complex_d r := rfl
@[simp] lemma walking_complex_hom_d_comp_d {i j k : walking_complex c}
(r : c.rel i j) (r' : c.rel j k) : walking_complex_d r ≫ walking_complex_d r' = 0 := rfl
variable [has_zero_morphisms V]
def complex_to_functor_map
(h : homological_complex V c) {i j : walking_complex c} (f : i ⟶ j) : h.X i ⟶ h.X j :=
begin
cases f, exacts [𝟙 _, h.d _ _, 0]
end
@[simp]
lemma complex_to_functor_map_id
(h : homological_complex V c) (i : walking_complex c) : complex_to_functor_map h (𝟙 i) = 𝟙 _ :=
rfl
@[simp]
lemma complex_to_functor_map_zero
(h : homological_complex V c) (i j : walking_complex c) :
complex_to_functor_map h (0 : i ⟶ j) = 0 :=
rfl
@[simp]
lemma complex_to_functor_map_d
(h : homological_complex V c) {i j : walking_complex c} (r : c.rel i j) :
complex_to_functor_map h (walking_complex_d r) = h.d _ _ := rfl
@[simps]
def complex_to_functor (h : homological_complex V c) :
walking_complex c ⥤ V :=
{ obj := h.X, map := λ i j f, complex_to_functor_map h f }
.
variable [decidable_rel c.rel]
@[simps]
def functor_to_complex (F : walking_complex c ⥤ V)
(hF : ∀ i j, F.map (0 : i ⟶ j) = 0) :
homological_complex V c :=
{ X := F.obj,
d := λ i j, if r : c.rel i j then F.map (walking_complex_d r) else 0,
d_comp_d' := by { introv r r',
rw [dif_pos r, dif_pos r', ← F.map_comp, walking_complex_hom_d_comp_d, hF] } }
.
variables (c V)
@[simps]
def complex_to_functor_functor :
homological_complex V c ⥤ { F : walking_complex c ⥤ V // ∀ i j, F.map (0 : i ⟶ j) = 0 } :=
{ obj := λ X, ⟨complex_to_functor X, λ _ _, rfl⟩, map := λ X Y f, { app := f.f } }
@[simps]
def functor_to_complex_functor :
{ F : walking_complex c ⥤ V // ∀ i j, F.map (0 : i ⟶ j) = 0 } ⥤ homological_complex V c :=
{ obj := λ F, functor_to_complex F.1 F.2,
map := λ F G f, { f := f.app, comm' := by { intros i j r, simp [dif_pos r] } } }
.
@[simps]
def complex_equiv_functor_unit :
𝟭 _ ≅ complex_to_functor_functor V c ⋙ functor_to_complex_functor V c :=
nat_iso.of_components
(λ X, hom.iso_of_components (λ i, iso.refl _) (by { introv r, dsimp, simp [if_pos r] }))
(by { intros, ext, dsimp, simp })
@[simps]
def complex_equiv_functor_counit :
functor_to_complex_functor V c ⋙ complex_to_functor_functor V c ≅ 𝟭 _ :=
nat_iso.of_components
(λ F, lift_iso $ nat_iso.of_components (λ i, iso.refl _)
(by { introv, cases F with F hF, cases f; dsimp; simp [*, hF] }))
(by { introv, ext, dsimp, erw [nat_trans.comp_app, nat_trans.comp_app], dsimp, simp })
@[simps]
def complex_equiv_functor :
homological_complex V c ≌ { F : walking_complex c ⥤ V // ∀ i j, F.map (0 : i ⟶ j) = 0 } :=
{ functor := complex_to_functor_functor V c,
inverse := functor_to_complex_functor V c,
unit_iso := complex_equiv_functor_unit V c,
counit_iso := complex_equiv_functor_counit V c,
functor_unit_iso_comp' :=
by { intro x, ext, erw [nat_trans.comp_app, nat_trans.id_app], dsimp, simp } }
.
instance : is_equivalence (complex_to_functor_functor V c) :=
is_equivalence.of_equivalence (complex_equiv_functor V c)
instance : is_equivalence (functor_to_complex_functor V c) :=
is_equivalence.of_equivalence_inverse (complex_equiv_functor V c)
@[simps, derive [full, faithful]]
def complex_to_functor_category_functor : homological_complex V c ⥤ walking_complex c ⥤ V :=
complex_to_functor_functor V c ⋙ induced_functor _
end walking_complex
section walking_preadditive_complex
/-
TODO : If `V` is preadditive, then the cateogory of homological complexes is equivalent to the
category of additive functors from a preadditive category `walking_preadditive_complex` to `V`.
-/
end walking_preadditive_complex
end homological_complex
|
% !TEX root = LMEDS_manual.tex
%%%%%%%%%%%%%%%%%%%%%
\section{Creating your own experiments}
%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%
\subsection{User-defined test components}
%%%%%%%%%%%%%%%%%%%%%
An LMEDS test has the following components
%%%%%%%%%%%%%%%%
\subsubsection{Audio and video files}
\paragraph{}
An audio file can be any common type (.mp3, .wav, etc.) and a video file can be one of (.mp4, .ogg, or .webm). Some web browsers are unable to play audio in certain file types. Personally, I encode every audio file as both .mp3 and .ogg and every video file as .mp4 and .ogg. I recommend encoding each file in two different formats. If a user is unable to load one file format, their browser will automatically load the other file format.
\paragraph{}
See the following pages for more information on browser compatibility:
\url{http://www.w3schools.com/tags/tag\_audio.asp}
\url{http://www.w3schools.com/html/html5_video.asp}
\paragraph{}
For audio files, audacity makes it very easy to convert entire directories of audio files into multiple audio formats with it's `chain' functionality.
\url{http://audacityteam.org/}
\paragraph{}
To save server space and speed up loading times for users with slower internet, I reencode my wav files to 16,000 HZ before I convert them to .mp3 and .ogg. This step is not required. Sox is a freely available command line tool that can do this task easily:
\begin{lstlisting}
sox input_file_name -r 16000 output_file_name rate -v 96k
\end{lstlisting}
\url{http://sox.sourceforge.net/}
%%%%%%%%%%%%%%%%
\subsubsection{Transcription files}
\paragraph{}
Only raw txt files with the extension .txt are accepted. Each transcription file should contain the transcript for one stimulus.
\paragraph{}
For long excerpts, you should specify the line breaks explicitly by chunking the text into pieces over the span of several lines. For a long excerpt, if all of the text lies on one line, the text will run off the page in LMEDS.
%%%%%%%%%%%%%%%%
\subsubsection{Sequence file (see section \ref{sec:sequenceSpec})}
\paragraph{}
The file that specifies the control flow of a test. It specifies what instructions and stimuli users will be presented with in a test and in what order.
\paragraph{}
Multiple sequence files can exist for a set of audio and transcription files (e.g. one could have a sequence with the stimuli in a certain order and another sequence with the stimuli in a different order or with different instructions, etc.).
%%%%%%%%%%%%%%%%
\subsubsection{Dictionary file(s) (see section \ref{sec:dictionarySpec})}
\paragraph{}
The file that contains all text that will be seen by users in your experiment. This file is independent of a sequence file so one could write a sequence and present it in both English and Russian, for example.
%%%%%%%%%%%%%%%%
\subsubsection{Survey file(s) (see section \ref{sec:surveySpec})}
\paragraph{}
A survey file can be used to get various kinds of feedback, such as might be needed for a longform survey or a short-answer question. Supports text boxes, checkboxes, and radio buttons.
\paragraph{}
Each survey requires its own survey file (e.g. presurvey.txt, postsurvey.txt).
\paragraph{}
Most pages have a static layout (defined in the python code) that is filled in with the same type of content. A survey is different because the amount of content and inputs vary with each survey page, whereas all AXB pages, for example, share the same number of inputs and outputs. For this reason, each survey requires its own specification file while other types of pages do not.
%%%%%%%%%%%%%%%%
\subsubsection{.CGI file}
\paragraph{}
The file that defines a single experiment--via a sequence file and a language file. The name given to this file (e.g. lmeds\_demo.cgi) is the name that participants would use to access the experiment in the URL.
\paragraph{}
A template of a typical .cgi file can be found in section \ref{sec:cgitemplate}. An example file is also distributed in the /cgi folder included with LMEDS.
%%%%%%%%%%%%%%%%%%%%%
\subsection{Dictionary file specification}
\label{sec:dictionarySpec}
%%%%%%%%%%%%%%%%%%%%%
\paragraph{}
LMEDS uses \textbf{dictionaries} for multi-lingual support. These dictionaries contain a set of keys where each key has text associated with it. One dictionary might have text only in English, while another only in French, but the keys are the same in both. Thus, when a key is used in a page, LMEDS looks in the dictionary (that is appropriate for the current experiment) for the corresponding text for that key. E.g. the key ``dictionary'' will fetch the text ``Dictionary'' for English and ``Dictionnaire'' for French. Each dictionary file is created by the user.
\paragraph{}
Some keys are defined within the python code. Other keys are user-defined. The user\_script \textbf{generate\_language\_dictionary.py} can be used to generate a template dictionary file (all keys are present but there are no text values) or update an existing dictionary file with new keys.
\paragraph{}
You might find it useful to create a new dictionary by using another one--either if you're starting a new experiment or translating your current experiment into another language.
\paragraph{}
A dictionary files has the following components (a very small, but complete dictionary file follows these, alternatively, you can look at the included dictionary file for a real example: \textbf{/tests/lmeds\_demo/english.txt}):
%%%%%%%%%%%%%%%%
\subsubsection{Sections}
\paragraph{}
A section is denoted with ``-'' characters on the line above and below the section name. The lengths of these lines (the number of ``-'') doesn't matter but should be kept the same length to be visually more coherent.
\paragraph{}
Sections are actually ignored in the code. Their only purpose is to help structure dictionaries, perhaps most naturally by page type. Keys shared by multiple pages are kept in their own sections.
%%%%%%%%%%%%%%%%
\subsubsection{Keys}
\paragraph{}
A key is denoted in the same way with ``='' characters. Keys must be the same, regardless of the language.
%%%%%%%%%%%%%%%%
\subsubsection{Texts}
\paragraph{}
A ``text'' appears after a key and before another key or section. Unlike sections and keys, text is undecorated text.
\paragraph{}
Text is rendered in HTML. This means HTML markup is allowed. It also means that whitespace other than a single space is ignored, although you may use extra whitespace to make it easier to read the text in the dictionary. If you want a line break, for example, you will need to insert one used \texttt{<br />}
%%%%%%%%%%%%%%%%
\subsubsection{Dictionary example file}
\paragraph{}
Here is a short, concrete example of a dictionary file
\paragraph{}
\begin{tcolorbox}[colback=white,colframe=blue,width=\dimexpr\textwidth+12mm\relax,enlarge left by=-6mm]
\begin{lstlisting}
---------------
text_page
---------------
===============
title
===============
Perception of Spoken Discourse
===============
first_block_finished
===============
You have completed the first block.<br /><br />
Please feel free to rest for a minute before continuing.
\end{lstlisting}
\end{tcolorbox}
\paragraph{}
The section denotes that these keys are used in the text pages, which tend to be used for giving instructions. Whenever LMEDS needs to display the title, it will look at the text for the key ``title'' in this case ``Perception of Spoken Discourse''.
%%%%%%%%%%%%%%%%%%%%%
\subsection{Survey file specification}
\label{sec:surveySpec}
%%%%%%%%%%%%%%%%%%%%%
\paragraph{}
The survey format allows for the simple creation of short or long questionnaires. The format is simple--the first line in a survey question contains the text prompt, subsequent lines specify one or more data entry fields that users can use to answer the question, and, finally, a blank line signals that the current item is complete. An small example survey file can be found is at the bottom of this section, two surveys are also bundled in lmeds \textbf{/tests/lmeds\_demo/presurvey.txt} and \textbf{/tests/lmeds\_demo/postsurvey.txt}.
\paragraph{}
A note on arguments: For data entry fields that have arguments, arguments should be separated from the data entry field name by a space and from each other by a comma
e.g.
\begin{lstlisting}
Choice English, Arabic, Other
\end{lstlisting}
\paragraph{}
Here is the list of data entry fields available:
%%%%%%%%%%%%%%%%
\subsubsection{None}
\paragraph{}
There are no inputs the user can choose from. This is used to include instructions on the page.
e.g.
\begin{lstlisting}
Please answer the questions below.
None
\end{lstlisting}
%%%%%%%%%%%%%%%%
\subsubsection{Choice}
\paragraph{}
Users can select exactly one item out of many.
e.g.
\begin{lstlisting}
Sex:
Choice Male, Female
\end{lstlisting}
%%%%%%%%%%%%%%%%
\subsubsection{Item\_List}
\paragraph{}
Users can select as many items as they want out of many.
e.g.
\begin{lstlisting}
Indicate the language(s) that you are familiar with.
Item_List English, French, Spanish, Italian, German
\end{lstlisting}
%%%%%%%%%%%%%%%%
\subsubsection{Choicebox}
\paragraph{}
A dropdown box. Users can select one item from many. Similar to a \textbf{Choice} but is more efficient in space for large lists of items.
e.g.
\begin{lstlisting}
Level of education completed:
Choicebox High School, Some College, Bachelor's Degree
\end{lstlisting}
%%%%%%%%%%%%%%%%
\subsubsection{Sliding\_Scale}
\paragraph{}
A sliding scale. Specify the numerical scale (which controls the granularity of the user's choice) and the labels for the two extremes of the scales.
e.g.
\begin{lstlisting}
How satisfied were you with this experiment?
Sliding_Scale 0, 100, Very Unsatisfied, Very Satisfied
\end{lstlisting}
%%%%%%%%%%%%%%%%
\subsubsection{Textbox}
\paragraph{}
A single line for users to enter a small amount of information. A textbox takes no arguments.
e.g.
\begin{lstlisting}
Occupation
Textbox
\end{lstlisting}
%%%%%%%%%%%%%%%%
\subsubsection{Multiline\_Textbox}
\paragraph{}
A longer-form textbox that can span several lines. It takes exactly two arguments: the number of characters across and the number of lines.
e.g.
\begin{lstlisting}
What did you think of this test? Please provide any feedback.
Multiline_Textbox 50, 7
\end{lstlisting}
%%%%%%%%%%%%%%%%
\subsubsection{Sublists}
\paragraph{}
It is possible to designate a group of items as subquestions of the previous question. These items will be displayed tabbed. To do this, encapsulate the relevant items in the sublist tag:
\begin{lstlisting}
<sublist>
Occupation
Textbox
City of birth
Textbox
</sublist>
\end{lstlisting}
%%%%%%%%%%%%%%%%
\subsubsection{Survey file example}
\paragraph{}
Here is a short concrete example demonstrating the key features discussed above
\paragraph{}
\begin{tcolorbox}[colback=white,colframe=blue,width=\dimexpr\textwidth+12mm\relax,enlarge left by=-6mm,enlarge right by=6mm]
\begin{lstlisting}
Please answer the questions below.
None
Sex:
Choice Male, Female
Age:
Textbox
Country of birth:
Choice United States, Other
Textbox
<sublist>
If United States, list city/state:
Textbox
If other, how old were you when you moved to the USA?
Textbox
</sublist>
\end{lstlisting}
\end{tcolorbox}
\paragraph{}
Thus we have a survey with (ignoring the first item, which doesn't take user input) 5 items in total (2 being subitems). The third item shows how multiple data entry fields can be placed on a single question (if the user selects ``other'' for the first question they are expected to specify what they meant in the Textbox).
%%%%%%%%%%%%%%%%%%%%%
\subsection{Sequence file specification}
\label{sec:sequenceSpec}
%%%%%%%%%%%%%%%%%%%%%
\paragraph{}
The sequence file contains the items that will be presented in a test. The first line in a test is the test name which should be prefixed with a ``*'' (e.g. *My\_Test\_Sequence) (\textbf{data from the experiment will be output to a folder with the test name. Giving multiple sequence files the same name, means that they will dump their output to the same folder}). The second item must be ``login'' where users create a name to associate their data with. If login is not the item on the second line, unexpected behavior can result.
Subsequent items are presented in a linear fashion as users progress through the sequence. The last item in the sequence must be ``end''.
\paragraph{}
\textbf{Most pages take arguments.} These arguments specify the behavior the page should take (which audio files to play, instructions to present, etc.) Arguments are separated from one another and from the page type by a space. Audio files and textfiles included in an argument should not include their file extension (.txt, .wav, etc.)--LMEDS will determine the appropriate extension to be used.
\begin{lstlisting}
Prominence water water 1 3 true
\end{lstlisting}
\paragraph{}
The above example is the entry for the prominence page. It comes with 5 arguments. Sections \ref{sec:sequenceSpecBasic} and \ref{sec:sequenceSpecSpecific} include information on how to understand the individual arguments to a page. A full example sequence file can be found in section \ref{sec:sequenceFileExample}.
%%%%%%%%%%%%%%%%
\subsubsection{A Note on Default Values}
\paragraph{}
\textit{This is a completely optional feature. If you find it confusing you can skip it.}
\paragraph{}
Some page types, such as \textbf{prominence} have default values for some arguments. An argument might have a default value if alternative values are uncommon or to support new functionality without requiring changes to pre-existing code.
\paragraph{}
Arguments that have default values do not have to be specified in a sequence file if you are ok with the defaults--this can make your sequence file cleaner and easier to read and maintain.
\paragraph{}
There are two ways that you can specify an optional value. One is to list it as normal e.g.
\begin{lstlisting}
prominence water water 1 3 p_ac_instr true
\end{lstlisting}
\paragraph{}
A second way is to refer to it explicitly by its name as described in sections \ref{sec:sequenceSpecBasic} and \ref{sec:sequenceSpecSpecific}. e.g.
\begin{lstlisting}
prominence water 1 3 instructions=p_ac_instr presentAudio=true
\end{lstlisting}
\paragraph{}
This second way is useful, for example, if you wanted to specify the value for a later variable such as ``presentAudio'' but not ``instructions''. The only way to do this is by naming the variable
\begin{lstlisting}
Prominence water 1 3 presentAudio=true
\end{lstlisting}
\paragraph{}
If one attempted the same list of arguments but without referring to the variable name, this would set ``instructions=true'' which would cause an error unless instructions named ``true'' existed in the dictionary file.
\begin{lstlisting}
Prominence water 1 3 true
\end{lstlisting}
\subsubsection{Valid Keyboard Keys}
\label{sec:validKeys}
\paragraph{}
Some pages allow interaction with the keyboard (such pages will direct you to this section). For those pages, experimenters can specify any letter or number on their keyboard, like so
\begin{lstlisting}
somePage playAudioKey=p
\end{lstlisting}
\paragraph{}
If we suppose that `playAudioKey' specifies the button that plays an audio recording, pressing the `p' button on the keyboard would play audio.
\paragraph{}
What about something like the `enter' key? The following codes can be entered to have their associated button registered as the key: \textbf{alt, backspace, capslock, ctrl, enter, escape, shift, space, and tab}. And they can be used like
\begin{lstlisting}
somePage playAudioKey=enter
\end{lstlisting}
%%%%%%%%%%%%%%%%
\subsubsection{Sequence file example}
\label{sec:sequenceFileExample}
\paragraph{}
Unlike the below example, in a sequence file each page description should fit on one line. In this example, for the purposes of space, some pages span several lines. A proper example sequence file is also distributed with the lmeds source:
\textbf{/LMEDS/tests/lmeds\_demo/sequence.txt}
\paragraph{}
\begin{tcolorbox}[colback=white,colframe=blue,width=\dimexpr\textwidth+12mm\relax,enlarge left by=-6mm,enlarge right by=6mm]
\begin{lstlisting}
*LMEDS_Demo
login
text_page demo_instructions
consent demo_consent
survey presurvey
media_list audio 1 1 1 [water apples water]
media_choice same_different_instr audio 0.5 1 -1
[[water apples]] [same different]
boundary_and_prominence water water 0 -1
boundary_instr prominence_instr true
boboundary_and_prominence apples apples 2 2
boundary_instr prominence_instr true
end
\end{lstlisting}
\end{tcolorbox}
%%%%%%%%%%%%%%%%%%%%%
\subsection{Sequence file specification - randomizing stimulus order}
\label{sec:sequenceSpecRandom}
%%%%%%%%%%%%%%%%%%%%%
\paragraph{}
A short but important section. The sequence file presents the order that all participants will encounter the stimuli. For many experiments however, it is necessary that the stimuli be presented in a different order for each experiment participant--to account for affects of stimulus order for example.
\paragraph{}
\textbf{Technical details} Here is a brief explanation of how randomization is performed by LMEDS. LMEDS presents materials based on the order presented in a sequence file. In order to present each user with the stimuli presented in a random order, each user must get their own sequence file. When instructed to do randomization, LMEDS reads in the sequence file created by the experimenter, randomizes the order of the stimuli, and then creates a new sequence file. It then reloads that file and begins the experiment.
\paragraph{}
The following instructions show how sequence randomization can be implemented in a sequence file.
\begin{enumerate}
\item Indiciate to LMEDS that you want to randomize a sequence:
In the .cgi file, in the function 'runExperiment' include the line \textbf{individualSequences=True}
\item Specify which portions should be randomized
In the sequence file, surround the section to be randomized with the following two lines\\
\textbf{<randomize>} \\
\textbf{</randomize>}
\item Create a folder where the user-specific sequence files will be placed by LMEDS.
/LMEDS/tests/<test root folder name>/individual\_sequences/<first line in sequence file>/
\end{enumerate}
\paragraph{}
So, for a short concrete example, here is how the above three would look in practice
\begin{lstlisting}
experiment_runner.runExperiment(`lmeds_demo',
`sequence_randomized.txt',
`english.txt',
individualSequences=True)
\end{lstlisting}
\paragraph{}
and
\begin{lstlisting}
*LMEDS_Simple_Randomized_Demo
login
text_page same_different_randomized_instructions
<randomize>
media_choice choice_instr audio 0.0 -1 -1 [[water]] [a b]
media_choice choice_instr audio 0.0 -1 -1 [[books]] [a b]
media_choice choice_instr audio 0.0 -1 -1 [[apples]] [a b]
</randomize>
\end{lstlisting}
\paragraph{}
and
/LMEDS/tests/lmeds\_demo/individual\_sequences/LMEDS\_Simple\_Randomized\_Demo
\paragraph{}
In the above example, although the sequence file specifies the stimuli in a particular order, these three items would be presented in a randomized order for each participant. Each participant would get their own customized sequence file that would be placed in /LMEDS/tests/lmeds\_demo/individual\_sequences/LMEDS\_Simple\_Randomized\_Demo.
\paragraph{}
For a fuller example, please see in the example demo files provided with the lmeds distribution: \\
/LMEDS/cgi/lmeds\_randomized\_demo.py \\
/LMEDS/tests/lmeds\_demo/sequence\_randomized.txt
\paragraph{}
For more details on post-processing the results of a randomized sequence, please see the post-processing section, Section \ref{postprocessresults}.
%%%%%%%%%%%%%%%%%%%%%
\subsection{Sequence file specification - common pages}
\label{sec:sequenceSpecBasic}
%%%%%%%%%%%%%%%%%%%%%
\paragraph{}
The following page types may be useful, regardless of the kind of experiment you're running.
%%%%%%%%%%%%%%%%
\subsubsection{login}
\paragraph{}
This is the first page that users see. They enter their name here. Names must be unique. If someone has already attempted to start a test under that user name the user will not be able to proceed from the login page.
\paragraph{}
``login'' takes no arguments.
%%%%%%%%%%%%%%%%
\subsubsection{media\_test}
\paragraph{}
Some users have reported an inability to hear audio in LMEDS--perhaps there is an issue with the browser they are using and it won't load audio or their internet is too slow. For this reason there is the media\_test page. This page can be presented right after a participant logs in to save them time in the event that their browser is not correctly playing audio or video.
\paragraph{}
``media\_test'' takes the following arguments
\begin{itemize}
\item \texttt{audio} if the page presents an audio file. \texttt{video} if it presents a video file.
\item the name of the audio or video file
\end{itemize}
e.g.
\begin{lstlisting}
audio_test audio example_audio_file
\end{lstlisting}
\paragraph{}
I recommend using a file that is similar to the stimuli they will experience in the experiment. If the stimuli are long, a short test file might not represent the kind of load the user's computer might encounter while doing the experiment.
%%%%%%%%%%%%%%%%
\subsubsection{consent}
\paragraph{}
Presents the consent form. If users opt not to consent, the test ends immediately. If they consent, they proceed to the next page.
\paragraph{}
``consent'' takes one argument
\begin{itemize}
\item the name of the consent form to display to users (the name is a key contained in the language dictionary -- so consent forms can be of the appropriate language)
\end{itemize}
e.g.
\begin{lstlisting}
consent main_consent
\end{lstlisting}
%%%%%%%%%%%%%%%%
\subsubsection{text\_page}
\paragraph{}
A page that displays nothing but the text from a single text key. This page could be used to provide task instructions to users, indicate that they should take a break, etc.
\paragraph{}
``text\_page'' takes one argument
\begin{itemize}
\item the name of the dictionary key
\end{itemize}
e.g.
\begin{lstlisting}
text_page first_block_instructions
\end{lstlisting}
%%%%%%%%%%%%%%%%
\subsubsection{survey}
\paragraph{}
Specifies a survey page (see Section \ref{sec:surveySpec} for info on surveys).
\paragraph{}
``survey'' takes a single argument
\begin{itemize}
\item the name of the survey file that should be loaded (without the .txt extension)
\end{itemize}
e.g.
\begin{lstlisting}
survey presurvey
\end{lstlisting}
\paragraph{}
This would load the survey stored in the file called ``presurvey.txt''
%%%%%%%%%%%%%%%%
\subsubsection{end}
\paragraph{}
The final page of the test.
\paragraph{}
``end'' takes no arguments.
%%%%%%%%%%%%%%%%%%%%%
\subsection{Sequence file specification - experiment-specific pages}
\label{sec:sequenceSpecSpecific}
%%%%%%%%%%%%%%%%%%%%%
Here is a list of page types involving stimuli presentation.
%%%%%%%%%%%%%%%%
\subsubsection{prominence}
\paragraph{}
Users are presented with an audio file and the associated transcript. They can click on a word to indicate that it is prominent. This changes the selected word to \textbf{red}. They can click it again to change it back to black.
\paragraph{}
``prominence'' takes the following arguments:
\begin{itemize}
\item name - the name of the audio file
\item transcriptName - the name of the text file
\item minPlays - the minimum number of times the audio file has to be played before the user can continue. A value of -1 indicates no minimum.
\item maxPlays - the maximum number of times the audio file can be played before the audio button is disabled. A value of -1 indicates no maximum.
\item instructions - on the page users will encounter short (approx. one line) instructions reminding them of the task. With this argument, you can present different stimuli with different short instructions (e.g. meaning, acoustics, vague).
\item presentAudio - either ``true'' or ``false'', specifies whether the audio is hidden or presented. If ``false'' the values for ``minPlays'' and ``maxPlays'' are ignored. \textbf{Default}: \textit{true}
\item bindPlayKeyID - the keyboard button that will activate the audio 'play' button on the page. \textbf{Default}: \textit{None} (i.e. no keyboard key) See section \ref{sec:validKeys} for acceptable values.
\item bindSubmitID - the keyboard button that will activate the 'submit' button on the page. \textbf{Default}: \textit{None} (i.e. no keyboard key) See section \ref{sec:validKeys} for acceptable values.
\item minNumSelected - the minimum number of words that the user must select before continuing. \textbf{Default}: \textit{-1} (i.e. no minimum)
\item maxNumSelected - the maximum number of words that the user can select in order to continue. \textbf{Default}: \textit{-1} (i.e. no maximum)
\end{itemize}
e.g.
\begin{lstlisting}
prominence water water 1 3 prominence_acoustics true
prominence apples apples 1 1 prominence_meaning
prominence apples apples -1 -1 choose_two true minNumSelected=2
prominence apples apples 1 1 prominence_meaning bindPlayKeyID=p
\end{lstlisting}
%%%%%%%%%%%%%%%%
\subsubsection{syllable\_marking}
\paragraph{}
``syllable\_marking'' is the same as \textbf{prominence} except that the user can mark individual syllables rather than the word
\paragraph{}
``syllable\_marking'' takes the same arguments as \textbf{prominence} pages but with the addition of one final obligatory argument:
\begin{itemize}
\item syllableDemarcator - specify the symbol for dividing syllables in the text transcript (e.g. `.')
\end{itemize}
e.g.
\begin{lstlisting}
syllable_marking syllables syllables 1 -1
nonspecific_syllables true syllableDemarcator=.
\end{lstlisting}
%%%%%%%%%%%%%%%%
\subsubsection{boundary}
\paragraph{}
Users are presented with an audio file and the associated transcript. They can click on a word to mark the presence of a boundary after it. This places a solid, vertical line after the word. Clicking on the word again makes the vertical line disappear.
\paragraph{}
``boundary'' takes the same arguments as \textbf{prominence} pages but with the addition of one final, optional argument:
\begin{itemize}
\item boundaryToken - specify the symbol to use for marking boundaries between words. The default symbol used by LMDS is a vertical bar ``\texttt{|}'').
\end{itemize}
e.g.
\begin{lstlisting}
boundary water water 1 3 boundary_acoustics true &
boundary apples apples 1 2 boundary_meaning
\end{lstlisting}
%%%%%%%%%%%%%%%%
\subsubsection{boundary\_and\_prominence}
\paragraph{}
A combination of prominences and boundaries. Users first mark boundaries. They then can mark prominences. While marking prominences they can see but not change the boundaries that they marked--this is the only difference between this page and splitting the prominence and boundary task across two pages.
\paragraph{}
The arguments for boundary\_and\_prominence are the same as for boundary, except that users need to indicate both the instructions for boundaries and the instructions for prominences.
e.g.
\begin{lstlisting}
boundary_and_prominence water water 0 3 b_instr p_instr true &
\end{lstlisting}
%%%%%%%%%%%%%%%%
\subsubsection{media\_list}
\paragraph{}
The user is presented with a single button. On being pressed, a series of audio or video files will be played. On a follow up page, the user could answer questions about the stimuli that were seen or heard.
\paragraph{}
media\_list takes the following arguments:
\begin{itemize}
\item \texttt{audio} if the page will present audio files. \texttt{video} if the page will present video files.
\item the length of pause in seconds between each file
\item the minimum number of times the media series can be played
\item the maximum number of times the media series can be played
\item the list of media files to play, enclosed by \texttt{[ ]}
\end{itemize}
e.g.
\begin{lstlisting}
media_list audio 1 1 1 [water apples water]
\end{lstlisting}
%%%%%%%%%%%%%%%%
\subsubsection{media\_slider}
\paragraph{}
The user is presented with a single button, a text transcript, and a slider. On the press of the button the media file is played. The user can then input their response through the slider. The text description and the transcript can be used to help guide their decision.
\paragraph{}
media\_slider takes the following arguments:
\begin{itemize}
\item instructionText - the dictionary key to the instructions to be presented.
\item audioOrVideo - \texttt{audio} if the page will present audio files. \texttt{video} if the page will present video files.
\item minPlays - the mininum number of times the media can be played.
\item maxPlays - the maximum number of times the media can be played.
\item mediaName - the name of the media file to play.
\item transcriptName - the name of the text file to display below the audio.
\item sliderMin - the smallest numerical value on the slider (this is not shown to the user).
\item sliderMax - the largest numerical value on the slider (this is not shown to the user).
\item sliderLabel - the label to put under the slider. \textbf{Default}: \textit{None} (i.e. no label).
\item leftRangeLabel - the label to put on the left edge of the slider. \textbf{Default}: \textit{None} (i.e. no label).
\item rightRangeLabel - the label to put on the right edge of the slider. \textbf{Default}: \textit{None} (i.e. no label).
\end{itemize}
e.g.
\begin{lstlisting}
media_slider prominence_scale_instr audio 1 -1 water water_word
0 100 leftRangeLabel=nonprominent rightRangeLabel=prominent
\end{lstlisting}
%%%%%%%%%%%%%%%%
\subsubsection{media\_choice}
\paragraph{}
This is used for presenting forced-choice-like tasks to the user with the number of media files (stimuli) and responses set by the experimenter.
\paragraph{}
This page replaces the various functionality of the pages: same\_different\_stream, axb, ab, and their many variants. These pages have been removed from LMEDS.
\paragraph{}
media\_choice takes the following arguments:
\begin{itemize}
\item the short form instructions to present on the page
\item \texttt{audio} if the page will present audio files. \texttt{video} if the page will present video files.
\item duration of pause in seconds for media files
\item the minimum number of times the audio series can be played
\item the maximum number of times the audio series can be played
\item a list of lists of audio files (see discussion below)
\item a list of the labels for the response options
\item mediaButtonLabelList - a list of names for labels for the audio files (must match the length of the media buttons) \textbf{Default}: \textit{None} (No labels are placed above the audio files--see discussion below)
\item transcriptList - a list of transcripts for the buttons (must match the number of media buttons). Transcripts are placed below the the buttons. \textbf{Default}: \textit{None}
\item bindPlayKeyIDList - a list of keyboard buttons that will activate the associated media buttons on the page (must match the length of the media buttons). \textbf{Default}: \textit{None} (i.e. no keyboard keys) See section \ref{sec:validKeys} for acceptable values.
\item bindResponseKeyIDList - a list of keyboard buttons that will activate the associated media buttons on the page (must match the length of the media buttons). \textbf{Default}: \textit{None} (i.e. no keyboard key) See section \ref{sec:validKeys} for acceptable values.
\item timeout - the time in seconds after which the page will automatically transition to the next page and the user's inaction will be marked in the output. \textbf{Default}: \textit{None} (i.e. no timeout)
\end{itemize}
e.g.
\begin{lstlisting}
media_choice same_different_instr audio 0.5 1 -1 [[water apples]]
[same different] [left_choice right_choice]
\end{lstlisting}
\paragraph{}
compare that example with the next one:
\begin{lstlisting}
media_choice same_different_instr audio 0.5 1 -1 [[water] [apples]]
[same different] [left_choice right_choice]
\end{lstlisting}
\paragraph{}
In the first example, with [[water apples]], there is one button that plays two audio files with a half second delay between each. In the second example, with [[water] [apples]], there are two audio buttons and each is played only once. Note that [water apples] will produce an error. \textbf{The argument must be a list of lists}: [[water apples]] or [[water] [apples]]. Similarly with three arguments: [[water apples candy]] or [[water] [apples] [candy]] for the cases with either 1 button or 3 buttons, respectively. In a minimal case, with only one audio file, you would write: [[audio\_name]], as in
\begin{lstlisting}
media_choice same_different_instr audio 0.5 1 -1 [audio_name]
[p b] [audio_button_text] [p_button_text b_button_text]
\end{lstlisting}
\paragraph{}
Here the user would hear a single audio file and select option ``p'' or option ``b'' (such as in classical experiments investigating perception of VOT contrasts).
\paragraph{}
If you feel the response options are obvious--because there are two audio buttons and two corresponding response options--you could remove the last option like so:
\begin{lstlisting}
media_choice same_different_instr audio 0.5 1 -1
[[water] [apples]] [same different]
\end{lstlisting}
\paragraph{}
Here are some examples of using keyboard keys to activate the buttons on the page. The important thing here is to use the same number of keys and buttons. As with other lists used in sequence file, the value still needs to be enclosed in [ ] even if there is only one value
\paragraph{} This example specifies one audio button with three response buttons. Pressing `p' will play the two audio files `water' and `apples' in sequence. Pressing `z' will register the \textit{dislike} response, the spacebar \textit{indifferent}, and `m' \textit{like}.
\begin{lstlisting}
media_choice three_point_scale_instr audio 0.5 1 -1 [water apples]
[dislike indifferent like] bindPlayKeyIDList=[p]
bindResponseKeyIDList=[z space m]
\end{lstlisting}
\paragraph{} This example specifies two audio buttons with two response buttons. Pressing the `w' key will play the left audio button for the audio file `water' while pressing the `p' key will play the right audio button for the audio file `apples'. Pressing `z' will register the \textit{same} response while pressing `m' will register the \textit{different} response.
\begin{lstlisting}
media_choice same_different_instr audio 0.5 1 -1 [[water] [apples]]
[same different] bindPlayKeyIDList=[w p]
bindResponseKeyIDList=[z m]
\end{lstlisting}
\paragraph{}
Normally, the result is output as a series of 0s separated by commas with a 1 indicating the position of the marked item. The number of digits reflects the number of response buttons. All of the examples above use either two or three. \textbf{If the timeout feature is being used} an extra digit is added. The value is 0 if the user selected any output but the value is 1 if the timeout was triggered before the user selected a response. Here is an example entry in the sequence file for a media\_choice with timeout
\begin{lstlisting}
media_choice same_different_instr audio 0.5 1 -1
[[water] [apples]] [same different] timeout=10
\end{lstlisting}
\paragraph{}
It is also possible to have \textbf{media-less media choice pages}. One might want to have a media task or a memory recall task where the audio was played on a previous page. To do this, one simple needs to make an empty audio list of lists like so: [[ ]] Here is an example used in the demo for a fill-in-the-blank type presentation which may have been part of a memory task.
\begin{lstlisting}
media_choice fill_in_the_blank_instruct audio 0.5 -1 -1 [[ ]]
[polluted cold not_drinkable] transcriptList=[water_blank]
\end{lstlisting}
%%%%%%%%%%%%%%%%%%%%%
\subsection{Parsing the LMEDS output}
%%%%%%%%%%%%%%%%%%%%%
\paragraph{}
The output to LMEDS is quite simple. Each line has 4 components:
\begin{itemize}
\item the page type
\item the argument list
\item peripheral information collected on the page (number of times users listened to audio files, time spent on the page, etc.)
\item the users input in data-entry fields presented on the page
\end{itemize}
\paragraph{}
For most needs, the page type and user response are the most important bits of information. The page type is separated from the rest of the row by the occurrence of the first comma. The user input is separated from the rest of the row by the sequence ``;,''. The argument list is enclosed in \texttt{[ ]} and separated from the peripheral information by a comma.
\paragraph{}
The user response is a string of comma-separated values. Every individual item in a data-entry field, except for textboxes, is represented by a 0 or 1, where 0 indicates the user did not choose that item and 1 indicates the user did choose that item. So if the user has a choice between A or B and selects A, their output will look like 1, 0. And if they select B: 0, 1. For a boundary\_and\_prominence page, each word gets two digits in the output (one for boundary and one for prominence).
\paragraph{}
Let's look at a real example. Here we have the sequence:
\begin{lstlisting}
login
boundary_and_prominence water water 0 3 b_acoustics
p_acoustics true
media_choice same_different_instr audio 0.5 1 -1
[[water apples]] [same different]
media_choice axb_instr audio 0.5 1 -1
[[water] [water2] [water3]] [ax xb]
media_choice ab_instr audio 0.5 1 -1 [[water]] [a b]
end
\end{lstlisting}
\paragraph{}
The first page is a typical boundary and prominence page. The three subsequent pages are all media choice pages. The first would be used for a same different task, the second for an axb task (the user listens to three audio files, is one of the files more similar to one of the other two? And in the third one, a labeling task--is the file a member of category `a' or category `b'?
And here is one possible output for this sequence.
\begin{lstlisting}
boundary_and_prominence,[water water 0 3 b_acoustics
p_acoustics true], 1,1,0:8.9,1;,
0,1,0,0,0,0,0,0,1,0,0,0,0,0
media_choice,[same_different_instr audio 0.5 1 -1 [[water apples]]
[same different]],0,0,0:4.8,2;,1,0
media_choice,[axb_instr audio 0.5 1 -1 [[water] [water2] [water3]]
[ax xb]],0,0,0:6.7,3;,0,1
media_choice,[ab_instr audio 0.5 1 -1 [[water]] [a b]],
0,0,0:3.3,4;,1,0
\end{lstlisting}
\paragraph{}
If we separate out just the page name (the content before the first `,') and the user response (everything after the `;,') we can easily see the data that we want to analyze:
\begin{lstlisting}
boundary_and_prominence;,0,1,0,0,0,0,0,0,1,0,0,0,0,0
media_choice;,1,0
media_choice;,0,1
media_choice;,1,0
\end{lstlisting}
\paragraph{}
LMEDS offers some useful post-processing that can help prep data for analysis (see \ref{sec:users_scripts}. Otherwise, with the above information, you should have everything you need to do your own analysis.
%%%%%%%%%%%%%%%%%%%%%
\subsection{CGI File (experiment-wide configuration)}
\label{sec:cgitemplate}
%%%%%%%%%%%%%%%%%%%%%
\paragraph{}
The cgi file specifies the location of the experiment files, the sequence name, and the dictionary name. Using these pieces of information, LMEDS will correctly locate the inputs and place the outputs. The CGI file itself is quite short. You can copy and paste the text below, changing only the arguments to the function \textbf{runExperiment}.
\paragraph{}
\textbf{Through the CGI file, one can indicate experiment-wide parameters.}
\paragraph{}
runExperiment() has the following arguments
\begin{itemize}
\item name of the folder in /lmeds/tests
\item name of the sequence file
\item name of the dictionary file
\item disableRefresh: if `True' and users try to refresh a page or click back, they will be unable to progress. Set to `True' if you suspect your subjects might try to revisit completed pages. Otherwise, in my experience, let them use back and refresh--they're only going to use it if their browser freezes up.
\item audioExtList: the list of audio extentions to use in an experiment. The default value is [`.ogg', `.mp3']
\item videoExtList: the list of video extensions to use in an experiment. The default value is [`.ogg', `.mp4']
\item allowUtilityScripts: if `True', users can run utility scripts from the browser. Could be `True' for a local LMEDS install used for testing but should be `False' for the online version. See section \ref{sec:users_scripts} for more information on the utility user scripts.
\item allowUsersToRelogin: if `True', users can use their login name to resume their progress if the are stopped midway through an experiment (loss of internet, audio fails to load, etc). Otherwise, if `False', users will have to restart from the beginning.
\end{itemize}
\begin{tcolorbox}[colback=white,colframe=blue,width=\dimexpr\textwidth+12mm\relax,enlarge left by=-6mm,enlarge right by=6mm]
\begin{lstlisting}
\#!/usr/bin/env python
\# -*- coding: utf-8 -*-
import experiment_runner as exp_runner
exp_runner.runExperiment(`lmeds_demo',
`sequence.txt',
`english.txt',
disableRefresh=False,
audioExtList=[`.ogg', `.wav'],
videoExtList=[`.webm', `.mp4'],
allowUtilityScripts=True,
allowUsersToRelogin=True)
\end{lstlisting}
\end{tcolorbox}
|
# Applications
```python
import numpy as np
import matplotlib.pyplot as plt
import scipy.linalg as la
```
## Polynomial Interpolation
[Polynomial interpolation](https://en.wikipedia.org/wiki/Polynomial_interpolation) finds the unique polynomial of degree $n$ which passes through $n+1$ points in the $xy$-plane. For example, two points in the $xy$-plane determine a line and three points determine a parabola.
### Formulation
Suppose we have $n + 1$ points in the $xy$-plane
$$
(x_0,y_0),(x_1,y_1),\dots,(x_n,y_n)
$$
such that all the $x$ values are distinct ($x_i \not= x_j$ for $i \not= j$). The general form of a degree $n$ polynomial is
$$
p(x) = a_0 + a_1 x + a_2x^2 + \cdots + a_n x^n
$$
If $p(x)$ is the unique degree $n$ polynomial which interpolates all the points, then the coefficients $a_0$, $a_1$, $\dots$, $a_n$ satisfy the following equations:
\begin{align}
a_0 + a_1x_0 + a_2x_0^2 + \cdots + a_n x_0^n &= y_0 \\\
a_0 + a_1x_1 + a_2x_1^2 + \cdots + a_n x_1^n &= y_1 \\\
& \ \ \vdots \\\
a_0 + a_1x_n + a_2x_n^2 + \cdots + a_n x_n^n &= y_n
\end{align}
Therefore the vector of coefficients
$$
\mathbf{a} =
\begin{bmatrix}
a_0 \\\
a_1 \\\
\vdots \\\
a_n
\end{bmatrix}
$$
is the unique the solution of the linear system of equations
$$
X \mathbf{a}=\mathbf{y}
$$
where $X$ is the [Vandermonde matrix](https://en.wikipedia.org/wiki/Vandermonde_matrix) and $\mathbf{y}$ is the vector of $y$ values
$$
X =
\begin{bmatrix}
1 & x_0 & x_0^2 & \dots & x_0^n \\\
1 & x_1 & x_1^2 & \dots & x_1^n \\\
& \vdots & & & \vdots \\\
1 & x_n & x_n^2 & \dots & x_n^n \\\
\end{bmatrix}
\ \ \mathrm{and} \ \
\mathbf{y} =
\begin{bmatrix}
y_0 \\\
y_1 \\\
y_2 \\\
\vdots \\\
y_n
\end{bmatrix}
$$
### Examples
**Simple Parabola**
Let's do a simple example. We know that $y=x^2$ is the unique degree 2 polynomial that interpolates the points $(-1,1)$, $(0,0)$ and $(1,1)$. Let's compute the polynomial interpolation of these points and verify the expected result $a_0=0$, $a_1=0$ and $a_2=1$.
Create the Vandermonde matrix $X$ with the array of $x$ values:
```python
x = np.array([-1,0,1])
X = np.column_stack([[1,1,1],x,x**2])
print(X)
```
[[ 1 -1 1]
[ 1 0 0]
[ 1 1 1]]
Create the vector $\mathbf{y}$ of $y$ values:
```python
y = np.array([1,0,1]).reshape(3,1)
print(y)
```
[[1]
[0]
[1]]
We expect the solution $\mathbf{a} = [0,0,1]^T$:
```python
a = la.solve(X,y)
print(a)
```
[[0.]
[0.]
[1.]]
Success!
**Another Parabola**
The polynomial interpolation of 3 points $(x_0,y_0)$, $(x_1,y_1)$ and $(x_2,y_2)$ is the parabola $p(x) = a_0 + a_1x + a_2x^2$ such that the coefficients satisfy
\begin{align}
a_0 + a_1x_0 + a_2x_0^2 = y_0 \\\
a_0 + a_1x_1 + a_2x_1^2 = y_1 \\\
a_0 + a_1x_2 + a_2x_2^2 = y_2
\end{align}
Let's find the polynomial interpolation of the points $(0,6)$, $(3,1)$ and $(8,2)$.
Create the Vandermonde matrix $X$:
```python
x = np.array([0,3,8])
X = np.column_stack([[1,1,1],x,x**2])
print(X)
```
[[ 1 0 0]
[ 1 3 9]
[ 1 8 64]]
And the vector of $y$ values:
```python
y = np.array([6,1,2]).reshape(3,1)
print(y)
```
[[6]
[1]
[2]]
Compute the vector $\mathbf{a}$ of coefficients:
```python
a = la.solve(X,y)
print(a)
```
[[ 6. ]
[-2.36666667]
[ 0.23333333]]
And plot the result:
```python
xs = np.linspace(0,8,20)
ys = a[0] + a[1]*xs + a[2]*xs**2
plt.plot(xs,ys,x,y,'b.',ms=20)
plt.show()
```
**Over Fitting 10 Random Points**
Now let's interpolate points with $x_i=i$, $i=0,\dots,9$, and 10 random integers sampled from $[0,10)$ as $y$ values:
```python
N = 10
x = np.arange(0,N)
y = np.random.randint(0,10,N)
plt.plot(x,y,'r.')
plt.show()
```
Create the Vandermonde matrix and verify the first 5 rows and columns:
```python
X = np.column_stack([x**k for k in range(0,N)])
print(X[:5,:5])
```
[[ 1 0 0 0 0]
[ 1 1 1 1 1]
[ 1 2 4 8 16]
[ 1 3 9 27 81]
[ 1 4 16 64 256]]
We could also use the NumPy function [`numpy.vander`](https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.vander.html). We specify the option `increasing=True` so that powers of $x_i$ increase left-to-right:
```python
X = np.vander(x,increasing=True)
print(X[:5,:5])
```
[[ 1 0 0 0 0]
[ 1 1 1 1 1]
[ 1 2 4 8 16]
[ 1 3 9 27 81]
[ 1 4 16 64 256]]
Solve the linear system:
```python
a = la.solve(X,y)
```
Plot the interpolation:
```python
xs = np.linspace(0,N-1,200)
ys = sum([a[k]*xs**k for k in range(0,N)])
plt.plot(x,y,'r.',xs,ys)
plt.show()
```
Success! But notice how unstable the curve is. That's why it better to use a [cubic spline](https://en.wikipedia.org/wiki/Spline_%28mathematics%29) to interpolate a large number of points.
However real-life data is usually very noisy and interpolation is not the best tool to fit a line to data. Instead we would want to take a polynomial with smaller degree (like a line) and fit it as best we can without interpolating the points.
## Least Squares Linear Regression
Suppose we have $n+1$ points
$$
(x_0,y_0) , (x_1,y_1) , \dots , (x_n,y_n)
$$
in the $xy$-plane and we want to fit a line
$$
y=a_0 + a_1x
$$
that "best fits" the data. There are different ways to quantify what "best fit" means but the most common method is called [least squares linear regression](https://en.wikipedia.org/wiki/Linear_regression). In least squares linear regression, we want to minimize the sum of squared errors
$$
SSE = \sum_i (y_i - (a_0 + a_1 x_i))^2
$$
### Formulation
If we form matrices
$$
X =
\begin{bmatrix}
1 & x_0 \\\
1 & x_1 \\\
\vdots & \vdots \\\
1 & x_n
\end{bmatrix}
\ , \ \
\mathbf{y} =
\begin{bmatrix}
y_0 \\\
y_1 \\\
\vdots \\\
y_n
\end{bmatrix}
\ , \ \
\mathbf{a} =
\begin{bmatrix}
a_0 \\\ a_1
\end{bmatrix}
$$
then the sum of squared errors can be expressed as
$$
SSE = \Vert \mathbf{y} - X \mathbf{a} \Vert^2
$$
---
**Theorem.** (Least Squares Linear Regression) Consider $n+1$ points
$$
(x_0,y_0) , (x_1,y_1) , \dots , (x_n,y_n)
$$
in the $xy$-plane. The coefficients $\mathbf{a} = [a_0,a_1]^T$ which minimize the sum of squared errors
$$
SSE = \sum_i (y_i - (a_0 + a_1 x_i))^2
$$
is the unique solution of the system
$$
\left( X^T X \right) \mathbf{a} = X^T \mathbf{y}
$$
*Sketch of Proof.* The product $X\mathbf{a}$ is in the column space of $X$. The line connecting $\mathbf{y}$ to the nearest point in the column space of $X$ is perpendicluar to the column space of $X$. Therefore
$$
X^T \left( \mathbf{y} - X \mathbf{a} \right) = \mathbf{0}
$$
and so
$$
\left( X^T X \right) \mathbf{a} = X^T \mathbf{y}
$$
---
### Examples
**Fake Noisy Linear Data**
Let's do an example with some fake data. Let's build a set of random points based on the model
$$
y = a_0 + a_1x + \epsilon
$$
for some arbitrary choice of $a_0$ and $a_1$. The factor $\epsilon$ represents some random noise which we model using the [normal distribution](https://en.wikipedia.org/wiki/Normal_distribution). We can generate random numbers sampled from the standard normal distribution using the NumPy function [`numpy.random.rand`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randn.html).
The goal is to demonstrate that we can use linear regression to retrieve the coefficeints $a_0$ and $a_1$ from the linear regression calculation.
```python
a0 = 2
a1 = 3
N = 100
x = np.random.rand(100)
noise = 0.1*np.random.randn(100)
y = a0 + a1*x + noise
plt.scatter(x,y);
plt.show()
```
Let's use linear regression to retrieve the coefficients $a_0$ and $a_1$. Construct the matrix $X$:
```python
X = np.column_stack([np.ones(N),x])
print(X.shape)
```
(100, 2)
Let's look at the first 5 rows of $X$ to see that it is in the correct form:
```python
X[:5,:]
```
array([[1. , 0.92365627],
[1. , 0.78757973],
[1. , 0.51506055],
[1. , 0.51540875],
[1. , 0.86563343]])
Use `scipy.linalg.solve` to solve $\left(X^T X\right)\mathbf{a} = \left(X^T\right)\mathbf{y}$ for $\mathbf{a}$:
```python
a = la.solve(X.T @ X, X.T @ y)
print(a)
```
[2.02783873 2.95308228]
We have retrieved the coefficients of the model almost exactly! Let's plot the random data points with the linear regression we just computed.
```python
xs = np.linspace(0,1,10)
ys = a[0] + a[1]*xs
plt.plot(xs,ys,'r',linewidth=4)
plt.scatter(x,y);
plt.show()
```
**Real Kobe Bryant Data**
Let's work with some real data. [Kobe Bryant](https://www.basketball-reference.com/players/b/bryanko01.html) retired in 2016 with 33643 total points which is the [third highest total points in NBA history](https://en.wikipedia.org/wiki/List_of_National_Basketball_Association_career_scoring_leaders). How many more years would Kobe Bryant have to had played to pass [Kareem Abdul-Jabbar's](https://en.wikipedia.org/wiki/Kareem_Abdul-Jabbar) record 38387 points?
Kobe Bryant's peak was the 2005-2006 NBA season. Let's look at Kobe Bryant's total games played and points per game from 2006 to 2016.
```python
years = np.array([2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016])
games = [80,77,82,82,73,82,58,78,6,35,66]
points = np.array([35.4,31.6,28.3,26.8,27,25.3,27.9,27.3,13.8,22.3,17.6])
fig = plt.figure(figsize=(12,10))
axs = fig.subplots(2,1,sharex=True)
axs[0].plot(years,points,'b.',ms=15)
axs[0].set_title('Kobe Bryant, Points per Game')
axs[0].set_ylim([0,40])
axs[0].grid(True)
axs[1].bar(years,games)
axs[1].set_title('Kobe Bryant, Games Played')
axs[1].set_ylim([0,100])
axs[1].grid(True)
plt.show()
```
Kobe was injured for most of the 2013-2014 NBA season and played only 6 games. This is an outlier and so we can drop this data point:
```python
years = np.array([2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2015, 2016])
games = np.array([80,77,82,82,73,82,58,78,35,66])
points = np.array([35.4,31.6,28.3,26.8,27,25.3,27.9,27.3,22.3,17.6])
```
Let's compute the average games played per season over this period:
```python
avg_games_per_year = np.mean(games)
print(avg_games_per_year)
```
71.3
Compute the linear model for points per game:
```python
X = np.column_stack([np.ones(len(years)),years])
a = la.solve(X.T @ X, X.T @ points)
model = a[0] + a[1]*years
plt.plot(years,model,years,points,'b.',ms=15)
plt.title('Kobe Bryant, Points per Game')
plt.ylim([0,40])
plt.grid(True)
plt.show()
```
Now we can extrapolate to future years and multiply points per games by games per season and compute the cumulative sum to see Kobe's total points:
```python
future_years = np.array([2017,2018,2019,2020,2021])
future_points = (a[0] + a[1]*future_years)*avg_games_per_year
total_points = 33643 + np.cumsum(future_points)
kareem = 38387*np.ones(len(future_years))
plt.plot(future_years,total_points,future_years,kareem)
plt.grid(True)
plt.xticks(future_years)
plt.title('Kobe Bryant Total Points Prediction')
plt.show()
```
Only 4 more years!
## Polynomial Regression
### Formulation
The same idea works for fitting a degree $d$ polynomial model
$$
y = a_0 + a_1x + a_2x^2 + \cdots + a_dx^d
$$
to a set of $n+1$ data points
$$
(x_0,y_0), (x_1,y_1), \dots , (x_n,y_n)
$$
We form the matrices as before but now the Vandermonde matrix $X$ has $d+1$ columns
$$
X =
\begin{bmatrix}
1 & x_0 & x_0^2 & \cdots & x_0^d \\\
1 & x_1 & x_1^2 & \cdots & x_1^d \\\
& \vdots & & & \vdots \\\
1 & x_n & x_n^2 & \cdots & x_n^d
\end{bmatrix}
\ , \ \
\mathbf{y} =
\begin{bmatrix}
y_0 \\\
y_1 \\\
\vdots \\\
y_n
\end{bmatrix}
\ , \ \
\mathbf{a} =
\begin{bmatrix}
a_0 \\\
a_1 \\\
a_2 \\\
\vdots \\\
a_d
\end{bmatrix}
$$
The coefficients $\mathbf{a} = [a_0,a_1,a_2,\dots,a_d]^T$ which minimize the sum of squared errors $SSE$ is the unique solution of the linear system
$$
\left( X^T X \right) \mathbf{a} = \left( X^T \right) \mathbf{y}
$$
### Example
**Fake Noisy Quadratic Data**
Let's build some fake data using a quadratic model $y = a_0 + a_1x + a_2x^2 + \epsilon$ and use linear regression to retrieve the coefficients $a_0$, $a_1$ and $a_2$.
```python
a0 = 3
a1 = 5
a2 = 8
N = 1000
x = 2*np.random.rand(N) - 1 # Random numbers in the interval (-1,1)
noise = np.random.randn(N)
y = a0 + a1*x + a2*x**2 + noise
plt.scatter(x,y,alpha=0.5,lw=0);
plt.show()
```
Construct the matrix $X$:
```python
X = np.column_stack([np.ones(N),x,x**2])
```
Use `scipy.linalg.solve` to solve $\left( X^T X \right) \mathbf{a} = \left( X^T \right) \mathbf{y}$:
```python
a = la.solve((X.T @ X),X.T @ y)
```
Plot the result:
```python
xs = np.linspace(-1,1,20)
ys = a[0] + a[1]*xs + a[2]*xs**2
plt.plot(xs,ys,'r',linewidth=4)
plt.scatter(x,y,alpha=0.5,lw=0)
plt.show()
```
## Graph Theory
A [graph](https://en.wikipedia.org/wiki/Graph_%28discrete_mathematics%29) is a set of vertices and a set of edges connecting some of the vertices. We will consider simple, undirected, connected graphs:
* a graph is [simple](https://en.wikipedia.org/wiki/Graph_%28discrete_mathematics%29#Simple_graph) if there are no loops or multiple edges between vertices
* a graph is [undirected](https://en.wikipedia.org/wiki/Graph_%28discrete_mathematics%29#Undirected_graph) if the edges do not have an orientation
* a graph is [connected](https://en.wikipedia.org/wiki/Graph_%28discrete_mathematics%29#Connected_graph) if each vertex is connected to every other vertex in the graph by a path
We can visualize a graph as a set of vertices and edges and answer questions about the graph just by looking at it. However this becomes much more difficult with a large graphs such as a [social network graph](https://en.wikipedia.org/wiki/Social_network_analysis). Instead, we construct matrices from the graph such as the [adjacency matrix](https://en.wikipedia.org/wiki/Adjacency_matrix) and the [Laplacian matrix](https://en.wikipedia.org/wiki/Laplacian_matrix) and study their properties.
[Spectral graph theory](https://en.wikipedia.org/wiki/Spectral_graph_theory) is the study of the eigenvalues of the adjacency matrix (and other associated matrices) and the relationships to the structure of $G$.
### NetworkX
Let's use the Python package [NetworkX](https://networkx.github.io/) to construct and visualize some simple graphs.
```python
import networkx as nx
```
### Adjacency Matrix
The [adjacency matrix](https://en.wikipedia.org/wiki/Adjacency_matrix) $A_G$ of a graph $G$ with $n$ vertices is the square matrix of size $n$ such that $A_{i,j} = 1$ if vertices $i$ and $j$ are connected by an edge, and $A_{i,j} = 0$ otherwise.
We can use `networkx` to create the adjacency matrix of a graph $G$. The function `nx.adjacency_matrix` returns a [sparse matrix](https://docs.scipy.org/doc/scipy/reference/sparse.html) and we convert it to a regular NumPy array using the `todense` method.
For example, plot the [complete graph](https://en.wikipedia.org/wiki/Complete_graph) with 5 vertices and compute the adjacency matrix:
```python
G = nx.complete_graph(5)
nx.draw(G,with_labels=True)
```
```python
A = nx.adjacency_matrix(G).todense()
print(A)
```
[[0 1 1 1 1]
[1 0 1 1 1]
[1 1 0 1 1]
[1 1 1 0 1]
[1 1 1 1 0]]
### Length of the Shortest Path
The length of the [shortest path](https://en.wikipedia.org/wiki/Shortest_path_problem) between vertices in a simple, undirected graph $G$ can be easily computed from the adjacency matrix $A_G$. In particular, the length of shortest path from vertex $i$ to vertex $j$ ($i\not=j$) is the smallest positive integer $k$ such that $A^k_{i,j} \not= 0$.
Plot the [dodecahedral graph](https://en.wikipedia.org/wiki/Regular_dodecahedron#Dodecahedral_graph):
```python
G = nx.dodecahedral_graph()
nx.draw(G,with_labels=True)
```
```python
A = nx.adjacency_matrix(G).todense()
print(A)
```
[[0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1]
[1 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0]
[0 1 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1]
[0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0]
[0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0]
[0 0 1 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 1 0 1 0 0 0 0 0 1 0 0 0 0 0]
[0 1 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 1 0 1 0 0 1 0 0 0 0 0 0]
[1 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 1 0]
[0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 1 0 0 0]
[0 0 0 0 0 0 0 0 0 1 0 0 1 0 1 0 0 0 0 0]
[0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 1 0 0 0 0]
[0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 1 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 1 0 0]
[0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0]
[0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 1]
[1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0]]
With this labelling, let's find the length of the shortest path from vertex $0$ to $15$:
```python
i = 0
j = 15
k = 1
Ak = A
while Ak[i,j] == 0:
Ak = Ak @ A
k = k + 1
print('Length of the shortest path is',k)
```
Length of the shortest path is 5
### Triangles in a Graph
A simple result in spectral graph theory is the number of [triangles](https://en.wikipedia.org/wiki/Adjacency_matrix#Matrix_powers) in a graph $T(G)$ is given by:
$$
T(G) = \frac{1}{6} ( \lambda_1^3 + \lambda_2^3 + \cdots + \lambda_n^3)
$$
where $\lambda_1 \leq \lambda_2 \leq \cdots \leq \lambda_n$ are the eigenvalues of the adjacency matrix.
Let's verify this for the simplest case, the complete graph on 3 vertices:
```python
C3 = nx.complete_graph(3)
nx.draw(C3,with_labels=True)
```
```python
A3 = nx.adjacency_matrix(C3).todense()
eigvals, eigvecs = la.eig(A3)
int(np.round(np.sum(eigvals.real**3)/6,0))
```
1
Let's compute the number of triangles in the complete graph 7 vertices:
```python
C7 = nx.complete_graph(7)
nx.draw(C7,with_labels=True)
```
```python
A7 = nx.adjacency_matrix(C7).todense()
eigvals, eigvecs = la.eig(A7)
int(np.round(np.sum(eigvals.real**3)/6,0))
```
35
There are 35 triangles in the complete graph with 7 vertices!
Let's write a function called `triangles` which takes a square matrix `M` and return the sum
$$
\frac{1}{6} ( \lambda_1^3 + \lambda_2^3 + \cdots + \lambda_n^3)
$$
where $\lambda_i$ are the eigenvalues of the symmetric matrix $A = (M + M^T)/2$. Note that $M = A$ if $M$ is symmetric. The return value is the number of triangles in the graph $G$ if the input $M$ is the adjacency matrix.
```python
def triangles(M):
A = (M + M.T)/2
eigvals, eigvecs = la.eig(A)
eigvals = eigvals.real
return int(np.round(np.sum(eigvals**3)/6,0))
```
Next, let's try a [Turan graph](https://en.wikipedia.org/wiki/Tur%C3%A1n_graph).
```python
G = nx.turan_graph(10,5)
nx.draw(G,with_labels=True)
```
```python
A = nx.adjacency_matrix(G).todense()
print(A)
```
[[0 0 1 1 1 1 1 1 1 1]
[0 0 1 1 1 1 1 1 1 1]
[1 1 0 0 1 1 1 1 1 1]
[1 1 0 0 1 1 1 1 1 1]
[1 1 1 1 0 0 1 1 1 1]
[1 1 1 1 0 0 1 1 1 1]
[1 1 1 1 1 1 0 0 1 1]
[1 1 1 1 1 1 0 0 1 1]
[1 1 1 1 1 1 1 1 0 0]
[1 1 1 1 1 1 1 1 0 0]]
Find the number of triangles:
```python
triangles(A)
```
80
Finally, let's compute the number of triangles in the dodecahedral graph:
```python
G = nx.dodecahedral_graph()
nx.draw(G,with_labels=True)
```
```python
A = nx.adjacency_matrix(G).todense()
print(A)
```
[[0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1]
[1 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0]
[0 1 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1]
[0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0]
[0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0]
[0 0 1 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 1 0 1 0 0 0 0 0 1 0 0 0 0 0]
[0 1 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 1 0 1 0 0 1 0 0 0 0 0 0]
[1 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 1 0]
[0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 1 0 0 0]
[0 0 0 0 0 0 0 0 0 1 0 0 1 0 1 0 0 0 0 0]
[0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 1 0 0 0 0]
[0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 1 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 1 0 0]
[0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0]
[0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 1]
[1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0]]
```python
np.round(triangles(A),2)
```
0
|
{-# language QuasiQuotes #-}
{- |
Module : Main
Description : Main entry point into FractalStream
-}
module Main where
import qualified Data.Color as FSColor
import UI.WX.Viewer
import Control.Concurrent
import Control.Monad.State
import Data.Planar
import Data.Complex
import Text.RawString.QQ
import Language.Code.Simulator
import Language.Type
import Language.Environment
import Language.Effect
import Language.Code.Parser
import Language.Value.Parser
import Data.Proxy
import Actor.Settings
import Actor.Tool
import Actor.Viewer
import Event
import Language.Effect.Draw
import Language.Effect.Render
import Language.Effect.Provide
import Language.Code
import Backend.LLVM
main :: IO ()
main = do
tid <- myThreadId
bound <- isCurrentThreadBound
capInfo <- threadCapability tid
putStrLn ("Hello from main, on thread " ++ show tid ++ " "
++ show capInfo ++ " " ++ show bound)
wxMain
putStrLn "main is done"
wxMain :: IO ()
wxMain = do
tid <- myThreadId
bound <- isCurrentThreadBound
capInfo <- threadCapability tid
putStrLn ("Hello from wxMain, on thread " ++ show tid ++ " " ++ show capInfo ++ " " ++ show bound)
let env = declare @"maxIters" IntegerType
$ declare @"maxRadius" RealType
$ declare @"x" RealType
$ declare @"y" RealType
$ endOfDecls
withCompiledCode env mandelProgram0 $ \kernel -> do
let action bs ss dz z out = runJX kernel out (fromIntegral bs) (fromIntegral ss) dz 100 10 z
wxView viewport action mainViewer
where
viewport = flippedRectangle (-2.5, 2) (1.5, -2)
flag :: String
flag = [r|
if x < -0.65 then
dark green
else if x > 0.65 then
orange
else
white|]
grid :: String
grid = [r|
init z : C to x + i y
init fz : C to sin z
init dfz : C to cos z
init size : R to 0.01 * |dfz|
if |sin (pi re(fz))| < size or |sin (pi im(fz))| < size then
light blue
else
white|]
mandelProgram0 :: String
mandelProgram0 = [r|
init C : C to x + i y
init z : C to 0
init k : Z to 0
loop
set z to z z + C
set k to k + 1
|z| < maxRadius and k < maxIters
if k = maxIters then
black
else
init c1 : Color to if im(z) > 0 then blue else yellow
init c2 : Color to if im(z) > 0 then green else orange
init s : R to k + 1 - (log (log (|z|^2) / 2)) / log 2
set s to cos (s pi / 10)
set s to s s
blend (s, c1, c2)|]
juliaProgram0 :: String
juliaProgram0 = [r|
init C : C to -0.12256 + 0.74486i
init z : C to x + i y
init k : Z to 0
init r2 : R to maxRadius * maxRadius
loop
set z to z z + C
set k to k + 1
re(z) re(z) + im(z) im(z) < r2 and k < maxIters
if k = maxIters then
black
else
init c1 : Color to if im(z) > 0 then blue else yellow
init c2 : Color to if im(z) > 0 then green else orange
init s : R to k + 1 - (log (log (|z|^2) / 2)) / log 2
set s to cos (s pi / 10)
set s to s s
blend (s, c1, c2)
|]
mandelProgram :: String
mandelProgram = [r|
init C : C to -0.11 + 0.75i
init z : C to x + i y
init k : Z to 0
init r2 : R to maxRadius * maxRadius
loop
set z to z z + C
set k to k + 1
|z|^2 < r2 and k < maxIters
if k >= maxIters then
black
else
init s : R to k + 1 - (log ((log (|z|^2)) / 2)) / log 2
set s to mod(s, 10) / 10
init c1 : Color to blue
init c2 : Color to white
if im z > 0 then
set c1 to yellow
set c2 to red
else
pass
if s < 0.5 then
blend(2s, c1, c2)
else
blend(2s - 1, c2, c1)|]
mandelProgram' :: String
mandelProgram' = [r|
init curImage : bitmap <- render in x y plane (viewWidth,viewHeight) (-2,2) (1 / 128, 1 / 128)
init C : C to -0.11 + 0.75i
set complex z to x + i y
set integer k to 0
set real r2 to maxRadius * maxRadius
loop
set z to z z + C
set k to k + 1
re z re z + im z im z < r2 and k < maxIters
if k >= maxIters then
black
else
set s : R to k + 1 - (log ((log (|z|^2)) / 2)) / log 2
set s to mod(s, 10) / 10
set c1 : Color to blue
set c2 : Color to white
if im z > 0 then
set c1 to yellow
set c2 to red
else
pass
if s < 0.5 then
blend(2s, c1, c2)
else
blend(2s - 1, c2, c1)|]
mandelProgram'' :: String
mandelProgram'' = [r|
curImage : Image
curImage ⟵ render in x y plane (viewWidth,viewHeight) (-2,2) (1 / 128, 1 / 128)
C : Complex
C = -0.11 + 0.75i
z : Complex
z = x + i y
repeat maxIters times with counter k
z = z² + C
while |z| < maxRadius
if k = maxIters then
black
else
s : Real
s = if use_smoothing then k + 1 - log (log |z|² / 2) / log 2 else k
s = mod (s, speed) / speed
c₁ = blue : Color
c₂ = white : Color
if im z > 0 then
c₁ = yellow
c₂ = red
if s < 0.5 then
blend(2s, c₁, c₂)
else
blend(2s - 1, c₂, c₁)|]
traceProgram :: String
traceProgram = [r|
init C : C to -0.11 + 0.75i
init z : C to posX + posY i
init z0 : C to 0
init k : Z to 0
erase
use white for line
loop
set z0 to z
set z to z z + C
draw point at z0
draw line from z0 to z
set k to k + 1
k < 100|]
traceProgram' :: String
traceProgram' = [r|
C : ℂ
C = -0.11 + 0.75i
z : ℂ
z = x + i y
z₀ : ℂ
z₀ = 0
erase
use white for line
repeat 100 times
z₀ = z
z = z² + C
draw point at z₀
draw line from z₀ to z
|]
traceTool :: Tool '[Draw]
traceTool = Tool{..}
where
toolName = "Trace"
toolHelp = "Click on a point to draw its trace"
toolSettings = Settings{..}
settingsList = Bind (Proxy @"steps") IntegerType
(Setting Proxy (Scalar IntegerType 100)
(Just ("Trace steps",
[ InputValidator
"Trace steps must be non-negative"
validator ])))
$ EmptyContext
settingsEnv = declare @"steps" IntegerType endOfDecls
settingsTitle = "Trace settings"
onChanged = Nothing
onClick = Just ( Fix
$ Effect Proxy Proxy VoidType
$ Provide posEnv settingsEnv VoidType trace)
onMouseDown = Nothing
onMouseUp = Nothing
onMotion = Nothing
onDrag = Nothing
buttons = []
env = declare @"posX" RealType
$ declare @"posY" RealType
$ settingsEnv
trace = case parseCode (EP (ParseEff noParser $ ParseEff drawEffectParser NoEffs)) env VoidType traceProgram of
Right p -> p
Left e -> error (show e)
validator = case parseValue settingsEnv BooleanType "steps > 0" of
Right p -> p
Left e -> error (show e)
mainViewer :: Viewer
mainViewer = Viewer{..}
where
onTimer = Nothing
viewerTools = [traceTool]
viewerSettings = Settings{..}
settingsList = Bind (Proxy @"maxRadius") RealType
(Setting Proxy (Scalar RealType 10)
(Just ("Max. radius", [])))
$ Bind (Proxy @"maxIters") IntegerType
(Setting Proxy (Scalar IntegerType 100)
(Just ("Max. iterations", [])))
$ EmptyContext
settingsEnv = contextToEnv settingsList
settingsTitle = "FractalStream demo viewer settings"
onChanged = Nothing
onResize = Nothing
onRefresh = Just ( Fix
$ Effect Proxy Proxy VoidType
$ Provide EmptyEnvProxy settingsEnv VoidType mandelCode)
viewToModel = case parseValue envV2M (PairType RealType RealType) v2m of
Right c -> c
Left e -> error (show e)
modelToView = case parseValue envM2V (PairType RealType RealType) m2v of
Right c -> c
Left e -> error (show e)
envV2M = declare @"viewX" RealType
$ declare @"viewY" RealType
$ env
envM2V = declare @"modelX" RealType
$ declare @"modelY" RealType
$ env
env = declare @"maxRadius" RealType
$ declare @"maxIters" IntegerType
$ endOfDecls
v2m = "((viewX - 256) / 128, (viewY - 256) / 128)"
m2v = "(128 modelX + 256, 128 modelY + 256)"
mandelCode = case parseCode (EP (ParseEff noParser $ ParseEff renderEffectParser NoEffs)) settingsEnv VoidType mandelProgram' of
Right c -> c
Left e -> error (show e)
mandel' :: Int -> Double -> Complex Double -> FSColor.Color
mandel' maxIters maxRadius (x :+ y) =
let ctx = Bind (Proxy @"x") RealType x
$ Bind (Proxy @"y") RealType y
$ Bind (Proxy @"maxRadius") RealType maxRadius
$ Bind (Proxy @"maxIters") IntegerType (fromIntegral maxIters)
$ EmptyContext
in evalState (simulate NoHandler prog) (ctx, ())
where
prog = case parseCode (EP NoEffs) env ColorType mandelProgram of
Right p -> p
Left _ -> case parseCode (EP NoEffs) env ColorType "dark red" of
Right p -> p
Left e -> error (show e) -- should be unreachable
env = declare @"x" RealType
$ declare @"y" RealType
$ declare @"maxRadius" RealType
$ declare @"maxIters" IntegerType
$ endOfDecls
|
using SimpleAssoc
using Base.Test
"Compare two iterables without regard to order"
itercmp(i1, i2) = isequal(sort(collect(i1)), sort(collect(i2)))
################################################################################
# Constructors
a0 = AssocArray{Char,Int}()
a1 = AssocArray{Char,Int}('a'=>1)
a1f = AssocArray{Char,Int}('a'=>1.0)
a2 = AssocArray{Char,Int}('a'=>1, 'b'=>2)
# Deducing the element type
a0 = AssocArray()
@test isa(a0, AssocArray{Any,Any})
a1 = AssocArray('a'=>1)
@test isa(a1, AssocArray{Char,Int})
a2 = AssocArray('a'=>1, 'b'=>2)
@test isa(a2, AssocArray{Char,Int})
# Constructing from a Pair vs. constructing from an iterator
a1 = AssocArray(('a'=>1) => ('b'=>2))
@test isa(a1, AssocArray{Pair{Char,Int}, Pair{Char,Int}})
a2 = AssocArray(('a'=>1), ('b'=>2))
@test isa(a2, AssocArray{Char,Int})
a3 = AssocArray((('a'=>1), ('b'=>2)))
@test isa(a3, AssocArray{Char,Int})
a4 = AssocArray(Pair{Char,Int}[('a'=>1), ('b'=>2)])
@test isa(a4, AssocArray{Char,Int})
a5 = AssocArray((('a',1), ('b',2)))
@test isa(a5, AssocArray{Char,Int})
a6 = AssocArray([('a',1), ('b',2)])
@test isa(a6, AssocArray{Char,Int})
# Type properties
a0 = AssocArray{Char,Int}()
@test eltype(a0) === Pair{Char,Int}
a0 = AssocArray()
@test eltype(a0) === Pair{Any,Any}
@test eltype(a1) === Pair{Pair{Char,Int}, Pair{Char,Int}}
@test eltype(a2) === Pair{Char,Int}
# Object properties
@test isempty(a0)
@test !isempty(a1)
@test !isempty(a2)
@test length(a0) == 0
@test length(a1) == 1
@test length(a2) == 2
# Iterators
@test itercmp(a0, Pair{Char,Int}[])
@test itercmp(a1, Pair{Pair{Char,Int}, Pair{Char,Int}}[('a'=>1) => ('b'=>2)])
@test itercmp(a2, Pair{Char,Int}[('a'=>1), ('b'=>2)])
@test itercmp(keys(a0), Char[])
@test itercmp(keys(a1), Pair{Char,Int}['a'=>1])
@test itercmp(keys(a2), Char['a', 'b'])
@test itercmp(values(a0), Int[])
@test itercmp(values(a1), Pair{Char,Int}['b'=>2])
@test itercmp(values(a2), Int[1, 2])
@test itercmp(eachindex(a0), keys(a0))
@test itercmp(eachindex(a1), keys(a1))
@test itercmp(eachindex(a2), keys(a2))
# Duplicate keys
b1 = AssocArray{Char,Int}([('a',1), ('a',2), ('b',2), ('a',1)])
@test itercmp(b1, a2)
b2 = AssocArray{Char,Int}('a'=>1, 'a'=>2, 'b'=>2, 'a'=>1)
@test itercmp(b2, a2)
b3 = AssocArray([('a',1), ('a',2), ('b',2), ('a',1)])
@test itercmp(b3, a2)
b4 = AssocArray('a'=>1, 'a'=>2, 'b'=>2, 'a'=>1)
@test itercmp(b4, a2)
# Mutating operations
empty!(a0)
@test isempty(a0)
empty!(a1)
@test isempty(a1)
empty!(a2)
@test isempty(a2)
# Element-wise access
a0['a'] = 1
@test a0['a'] == 1
@test length(a0) == 1
a0['b'] = -1
@test a0['b'] == -1
@test length(a0) == 2
a0['b'] = 2
@test a0['b'] == 2
@test length(a0) == 2
get!(a0, 'b', 3)
@test a0['b'] == 2
@test length(a0) == 2
get!(a0, 'c', 3)
@test a0['c'] == 3
@test length(a0) == 3
@test get(a0, 'c', 4) == 3
@test get(a0, 'd', 4) == 4
@test haskey(a0, 'c')
@test getkey(a0, 'c', 4) == 'c'
@test !haskey(a0, 'd')
@test getkey(a0, 'd', 4) == 4
@test itercmp(a0, ('a'=>1, 'b'=>2, 'c'=>3))
@test_throws KeyError a0['A']
# Delete elements
delete!(a0, 'b')
@test length(a0) == 2
@test_throws KeyError a0['b']
delete!(a0, 'c')
@test length(a0) == 1
@test_throws KeyError a0['c']
delete!(a0, 'a')
@test length(a0) == 0
@test_throws KeyError a0['a']
delete!(a0, 'a')
@test length(a0) == 0
# Copy collection
a4c = copy(a4)
@test isequal(a4c, a4)
@test a4c !== a4
# push and pop
x = pop!(a4)
@test length(a4) == 1
y = pop!(a4)
@test length(a4) == 0
@test_throws BoundsError pop!(a4)
@test x != y
push!(a4, x)
@test length(a4) == 1
push!(a4, y)
@test length(a4) == 2
@test isequal(a4, a4c)
################################################################################
# Constructors
t0 = AssocTuple{Char,Int,0}()
t1 = AssocTuple{Char,Int,1}('a'=>1)
t2 = AssocTuple{Char,Int,1}('a'=>1.0)
t0 = AssocTuple{Char,Int}()
t1 = AssocTuple{Char,Int}('a'=>1)
t2 = AssocTuple{Char,Int}('a'=>1.0)
t0 = AssocTuple()
t1 = AssocTuple('a'=>1)
t2 = AssocTuple('a'=>1.0)
# Deducing the element type
t1 = AssocTuple('a'=>1)
@test isa(t1, AssocTuple{Char,Int})
t2 = AssocTuple('a'=>1, 'b'=>2)
@test isa(t2, AssocTuple{Char,Int})
# Constructing from a Pair vs. constructing from an iterator
t1 = AssocTuple(('a'=>1) => ('b'=>2))
@test isa(t1, AssocTuple{Pair{Char,Int}, Pair{Char,Int}})
t2 = AssocTuple(('a'=>1), ('b'=>2))
@test isa(t2, AssocTuple{Char,Int})
t3 = AssocTuple((('a'=>1), ('b'=>2)))
@test isa(t3, AssocTuple{Char,Int})
t4 = AssocTuple(Pair{Char,Int}[('a'=>1), ('b'=>2)])
@test isa(t4, AssocTuple{Char,Int})
t5 = AssocTuple((('a',1), ('b',2)))
@test isa(t5, AssocTuple{Char,Int})
t6 = AssocTuple([('a',1), ('b',2)])
@test isa(t6, AssocTuple{Char,Int})
# Type properties
t0 = AssocTuple{Char,Int}()
@test eltype(t0) === Pair{Char,Int}
t0 = AssocTuple()
@test eltype(t0) === Pair{Any,Any}
@test eltype(t1) === Pair{Pair{Char,Int}, Pair{Char,Int}}
@test eltype(t2) === Pair{Char,Int}
# Object properties
@test isempty(t0)
@test !isempty(t1)
@test !isempty(t2)
@test length(t0) == 0
@test length(t1) == 1
@test length(t2) == 2
# Iterators
@test itercmp(t0, Pair{Char,Int}[])
@test itercmp(t1, Pair{Pair{Char,Int}, Pair{Char,Int}}[('a'=>1) => ('b'=>2)])
@test itercmp(t2, Pair{Char,Int}[('a'=>1), ('b'=>2)])
@test itercmp(keys(t0), Char[])
@test itercmp(keys(t1), Pair{Char,Int}['a'=>1])
@test itercmp(keys(t2), Char['a', 'b'])
@test itercmp(values(t0), Int[])
@test itercmp(values(t1), Pair{Char,Int}['b'=>2])
@test itercmp(values(t2), Int[1, 2])
@test itercmp(eachindex(t0), keys(t0))
@test itercmp(eachindex(t1), keys(t1))
@test itercmp(eachindex(t2), keys(t2))
# Duplicate keys
u1 = AssocTuple{Char,Int}([('a',1), ('a',2), ('b',2), ('a',1)])
@test itercmp(u1, t2)
u2 = AssocTuple{Char,Int}('a'=>1, 'a'=>2, 'b'=>2, 'a'=>1)
@test itercmp(u2, t2)
u3 = AssocTuple([('a',1), ('a',2), ('b',2), ('a',1)])
@test itercmp(u3, t2)
u4 = AssocTuple('a'=>1, 'a'=>2, 'b'=>2, 'a'=>1)
@test itercmp(u4, t2)
# Element-wise access
@test_throws KeyError t0['a']
@test t1['a'=>1] == ('b'=>2)
@test t2['a'] == 1
@test t2['b'] == 2
@test_throws KeyError t2['c']
@test !haskey(t0, 'a')
@test get(t0, 'a', 2) == 2
@test haskey(t2, 'a')
@test haskey(t2, 'b')
@test !haskey(t2, 'c')
@test get(t2, 'a', 4) == 1
@test get(t2, 'b', 4) == 2
@test get(t2, 'c', 4) == 4
@test getkey(t2, 'a', 4) == 'a'
@test getkey(t2, 'b', 4) == 'b'
@test getkey(t2, 'c', 4) == 4
|
[GOAL]
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a✝ b a : α
l : List α
⊢ Nodup (a :: l) ↔ ¬a ∈ l ∧ Nodup l
[PROOFSTEP]
simp only [Nodup, pairwise_cons, forall_mem_ne]
[GOAL]
α : Type u
β : Type v
l l₁ l₂ : List α
r✝ : α → α → Prop
a b : α
r : α → β → Prop
hr : Relator.BiUnique r
⊢ (fun x x_1 => x ↔ x_1) (Nodup []) (Nodup [])
[PROOFSTEP]
simp only [nodup_nil]
[GOAL]
α : Type u
β : Type v
l l₁ l₂ : List α
r✝ : α → α → Prop
a b : α
r : α → β → Prop
hr : Relator.BiUnique r
a✝ : α
b✝ : β
l₁✝ : List α
l₂✝ : List β
hab : r a✝ b✝
h : Forall₂ r l₁✝ l₂✝
⊢ (fun x x_1 => x ↔ x_1) (Nodup (a✝ :: l₁✝)) (Nodup (b✝ :: l₂✝))
[PROOFSTEP]
simpa only [nodup_cons] using Relator.rel_and (Relator.rel_not (rel_mem hr hab h)) (rel_nodup hr h)
[GOAL]
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
l : List α
⊢ (∀ (a : α), ¬[a, a] <+ l) → Nodup l
[PROOFSTEP]
induction' l with a l IH
[GOAL]
case nil
α : Type u
β : Type v
l l₁ l₂ : List α
r : α → α → Prop
a b : α
⊢ (∀ (a : α), ¬[a, a] <+ []) → Nodup []
[PROOFSTEP]
intro h
[GOAL]
case cons
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a✝ b a : α
l : List α
IH : (∀ (a : α), ¬[a, a] <+ l) → Nodup l
⊢ (∀ (a_1 : α), ¬[a_1, a_1] <+ a :: l) → Nodup (a :: l)
[PROOFSTEP]
intro h
[GOAL]
case nil
α : Type u
β : Type v
l l₁ l₂ : List α
r : α → α → Prop
a b : α
h : ∀ (a : α), ¬[a, a] <+ []
⊢ Nodup []
[PROOFSTEP]
exact nodup_nil
[GOAL]
case cons
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a✝ b a : α
l : List α
IH : (∀ (a : α), ¬[a, a] <+ l) → Nodup l
h : ∀ (a_1 : α), ¬[a_1, a_1] <+ a :: l
⊢ Nodup (a :: l)
[PROOFSTEP]
exact (IH fun a s => h a <| sublist_cons_of_sublist _ s).cons fun al => h a <| (singleton_sublist.2 al).cons_cons _
[GOAL]
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
l : List α
h : ∀ (i j : Fin (length l)), i < j → get l i ≠ get l j
i j : Fin (length l)
hg : get l i = get l j
⊢ i = j
[PROOFSTEP]
cases' i with i hi
[GOAL]
case mk
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
l : List α
h : ∀ (i j : Fin (length l)), i < j → get l i ≠ get l j
j : Fin (length l)
i : ℕ
hi : i < length l
hg : get l { val := i, isLt := hi } = get l j
⊢ { val := i, isLt := hi } = j
[PROOFSTEP]
cases' j with j hj
[GOAL]
case mk.mk
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
l : List α
h : ∀ (i j : Fin (length l)), i < j → get l i ≠ get l j
i : ℕ
hi : i < length l
j : ℕ
hj : j < length l
hg : get l { val := i, isLt := hi } = get l { val := j, isLt := hj }
⊢ { val := i, isLt := hi } = { val := j, isLt := hj }
[PROOFSTEP]
rcases lt_trichotomy i j with (hij | rfl | hji)
[GOAL]
case mk.mk.inl
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
l : List α
h : ∀ (i j : Fin (length l)), i < j → get l i ≠ get l j
i : ℕ
hi : i < length l
j : ℕ
hj : j < length l
hg : get l { val := i, isLt := hi } = get l { val := j, isLt := hj }
hij : i < j
⊢ { val := i, isLt := hi } = { val := j, isLt := hj }
[PROOFSTEP]
exact (h ⟨i, hi⟩ ⟨j, hj⟩ hij hg).elim
[GOAL]
case mk.mk.inr.inl
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
l : List α
h : ∀ (i j : Fin (length l)), i < j → get l i ≠ get l j
i : ℕ
hi hj : i < length l
hg : get l { val := i, isLt := hi } = get l { val := i, isLt := hj }
⊢ { val := i, isLt := hi } = { val := i, isLt := hj }
[PROOFSTEP]
rfl
[GOAL]
case mk.mk.inr.inr
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
l : List α
h : ∀ (i j : Fin (length l)), i < j → get l i ≠ get l j
i : ℕ
hi : i < length l
j : ℕ
hj : j < length l
hg : get l { val := i, isLt := hi } = get l { val := j, isLt := hj }
hji : j < i
⊢ { val := i, isLt := hi } = { val := j, isLt := hj }
[PROOFSTEP]
exact (h ⟨j, hj⟩ ⟨i, hi⟩ hji hg.symm).elim
[GOAL]
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
l : List α
h : Nodup l
i j : ℕ
hi : i < length l
hj : j < length l
⊢ i = j → nthLe l i hi = nthLe l j hj
[PROOFSTEP]
simp (config := { contextual := true })
[GOAL]
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
l : List α
⊢ Nodup l ↔ ∀ (i j : ℕ), i < j → j < length l → get? l i ≠ get? l j
[PROOFSTEP]
rw [Nodup, pairwise_iff_get]
[GOAL]
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
l : List α
⊢ (∀ (i j : Fin (length l)), i < j → get l i ≠ get l j) ↔ ∀ (i j : ℕ), i < j → j < length l → get? l i ≠ get? l j
[PROOFSTEP]
constructor
[GOAL]
case mp
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
l : List α
⊢ (∀ (i j : Fin (length l)), i < j → get l i ≠ get l j) → ∀ (i j : ℕ), i < j → j < length l → get? l i ≠ get? l j
[PROOFSTEP]
intro h i j hij hj
[GOAL]
case mp
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
l : List α
h : ∀ (i j : Fin (length l)), i < j → get l i ≠ get l j
i j : ℕ
hij : i < j
hj : j < length l
⊢ get? l i ≠ get? l j
[PROOFSTEP]
rw [get?_eq_get (lt_trans hij hj), get?_eq_get hj, Ne.def, Option.some_inj]
[GOAL]
case mp
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
l : List α
h : ∀ (i j : Fin (length l)), i < j → get l i ≠ get l j
i j : ℕ
hij : i < j
hj : j < length l
⊢ ¬get l { val := i, isLt := (_ : i < length l) } = get l { val := j, isLt := hj }
[PROOFSTEP]
exact h _ _ hij
[GOAL]
case mpr
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
l : List α
⊢ (∀ (i j : ℕ), i < j → j < length l → get? l i ≠ get? l j) → ∀ (i j : Fin (length l)), i < j → get l i ≠ get l j
[PROOFSTEP]
intro h i j hij
[GOAL]
case mpr
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
l : List α
h : ∀ (i j : ℕ), i < j → j < length l → get? l i ≠ get? l j
i j : Fin (length l)
hij : i < j
⊢ get l i ≠ get l j
[PROOFSTEP]
rw [Ne.def, ← Option.some_inj, ← get?_eq_get, ← get?_eq_get]
[GOAL]
case mpr
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
l : List α
h : ∀ (i j : ℕ), i < j → j < length l → get? l i ≠ get? l j
i j : Fin (length l)
hij : i < j
⊢ ¬get? l ↑i = get? l ↑j
[PROOFSTEP]
exact h i j hij j.2
[GOAL]
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
l : List α
h : Nodup l
x : α
⊢ l ≠ [x] ↔ l = [] ∨ ∃ y, y ∈ l ∧ y ≠ x
[PROOFSTEP]
induction' l with hd tl hl
[GOAL]
case nil
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
l : List α
h✝ : Nodup l
x : α
h : Nodup []
⊢ [] ≠ [x] ↔ [] = [] ∨ ∃ y, y ∈ [] ∧ y ≠ x
[PROOFSTEP]
simp
[GOAL]
case cons
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
l : List α
h✝ : Nodup l
x hd : α
tl : List α
hl : Nodup tl → (tl ≠ [x] ↔ tl = [] ∨ ∃ y, y ∈ tl ∧ y ≠ x)
h : Nodup (hd :: tl)
⊢ hd :: tl ≠ [x] ↔ hd :: tl = [] ∨ ∃ y, y ∈ hd :: tl ∧ y ≠ x
[PROOFSTEP]
specialize hl h.of_cons
[GOAL]
case cons
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
l : List α
h✝ : Nodup l
x hd : α
tl : List α
h : Nodup (hd :: tl)
hl : tl ≠ [x] ↔ tl = [] ∨ ∃ y, y ∈ tl ∧ y ≠ x
⊢ hd :: tl ≠ [x] ↔ hd :: tl = [] ∨ ∃ y, y ∈ hd :: tl ∧ y ≠ x
[PROOFSTEP]
by_cases hx : tl = [x]
[GOAL]
case pos
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
l : List α
h✝ : Nodup l
x hd : α
tl : List α
h : Nodup (hd :: tl)
hl : tl ≠ [x] ↔ tl = [] ∨ ∃ y, y ∈ tl ∧ y ≠ x
hx : tl = [x]
⊢ hd :: tl ≠ [x] ↔ hd :: tl = [] ∨ ∃ y, y ∈ hd :: tl ∧ y ≠ x
[PROOFSTEP]
simpa [hx, and_comm, and_or_left] using h
[GOAL]
case neg
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
l : List α
h✝ : Nodup l
x hd : α
tl : List α
h : Nodup (hd :: tl)
hl : tl ≠ [x] ↔ tl = [] ∨ ∃ y, y ∈ tl ∧ y ≠ x
hx : ¬tl = [x]
⊢ hd :: tl ≠ [x] ↔ hd :: tl = [] ∨ ∃ y, y ∈ hd :: tl ∧ y ≠ x
[PROOFSTEP]
rw [← Ne.def, hl] at hx
[GOAL]
case neg
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
l : List α
h✝ : Nodup l
x hd : α
tl : List α
h : Nodup (hd :: tl)
hl : tl ≠ [x] ↔ tl = [] ∨ ∃ y, y ∈ tl ∧ y ≠ x
hx : tl = [] ∨ ∃ y, y ∈ tl ∧ y ≠ x
⊢ hd :: tl ≠ [x] ↔ hd :: tl = [] ∨ ∃ y, y ∈ hd :: tl ∧ y ≠ x
[PROOFSTEP]
rcases hx with (rfl | ⟨y, hy, hx⟩)
[GOAL]
case neg.inl
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
l : List α
h✝ : Nodup l
x hd : α
h : Nodup [hd]
hl : [] ≠ [x] ↔ [] = [] ∨ ∃ y, y ∈ [] ∧ y ≠ x
⊢ [hd] ≠ [x] ↔ [hd] = [] ∨ ∃ y, y ∈ [hd] ∧ y ≠ x
[PROOFSTEP]
simp
[GOAL]
case neg.inr.intro.intro
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
l : List α
h✝ : Nodup l
x hd : α
tl : List α
h : Nodup (hd :: tl)
hl : tl ≠ [x] ↔ tl = [] ∨ ∃ y, y ∈ tl ∧ y ≠ x
y : α
hy : y ∈ tl
hx : y ≠ x
⊢ hd :: tl ≠ [x] ↔ hd :: tl = [] ∨ ∃ y, y ∈ hd :: tl ∧ y ≠ x
[PROOFSTEP]
suffices ∃ (y : α) (_ : y ∈ hd :: tl), y ≠ x by simpa [ne_nil_of_mem hy]
[GOAL]
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
l : List α
h✝ : Nodup l
x hd : α
tl : List α
h : Nodup (hd :: tl)
hl : tl ≠ [x] ↔ tl = [] ∨ ∃ y, y ∈ tl ∧ y ≠ x
y : α
hy : y ∈ tl
hx : y ≠ x
this : ∃ y x_1, y ≠ x
⊢ hd :: tl ≠ [x] ↔ hd :: tl = [] ∨ ∃ y, y ∈ hd :: tl ∧ y ≠ x
[PROOFSTEP]
simpa [ne_nil_of_mem hy]
[GOAL]
case neg.inr.intro.intro
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
l : List α
h✝ : Nodup l
x hd : α
tl : List α
h : Nodup (hd :: tl)
hl : tl ≠ [x] ↔ tl = [] ∨ ∃ y, y ∈ tl ∧ y ≠ x
y : α
hy : y ∈ tl
hx : y ≠ x
⊢ ∃ y x_1, y ≠ x
[PROOFSTEP]
exact ⟨y, mem_cons_of_mem _ hy, hx⟩
[GOAL]
α : Type u
β : Type v
l l₁ l₂ : List α
r : α → α → Prop
a b : α
xs : List α
n m : Fin (length xs)
h : get xs n = get xs m
hne : n ≠ m
⊢ ¬Nodup xs
[PROOFSTEP]
rw [nodup_iff_injective_get]
[GOAL]
α : Type u
β : Type v
l l₁ l₂ : List α
r : α → α → Prop
a b : α
xs : List α
n m : Fin (length xs)
h : get xs n = get xs m
hne : n ≠ m
⊢ ¬Injective (get xs)
[PROOFSTEP]
exact fun hinj => hne (hinj h)
[GOAL]
α : Type u
β : Type v
l l₁ l₂ : List α
r : α → α → Prop
a b : α
xs : List α
n m : ℕ
hn : n < length xs
hm : m < length xs
h : nthLe xs n hn = nthLe xs m hm
hne : n ≠ m
⊢ ¬Nodup xs
[PROOFSTEP]
rw [nodup_iff_nthLe_inj]
[GOAL]
α : Type u
β : Type v
l l₁ l₂ : List α
r : α → α → Prop
a b : α
xs : List α
n m : ℕ
hn : n < length xs
hm : m < length xs
h : nthLe xs n hn = nthLe xs m hm
hne : n ≠ m
⊢ ¬∀ (i j : ℕ) (h₁ : i < length xs) (h₂ : j < length xs), nthLe xs i h₁ = nthLe xs j h₂ → i = j
[PROOFSTEP]
simp only [exists_prop, exists_and_right, not_forall]
[GOAL]
α : Type u
β : Type v
l l₁ l₂ : List α
r : α → α → Prop
a b : α
xs : List α
n m : ℕ
hn : n < length xs
hm : m < length xs
h : nthLe xs n hn = nthLe xs m hm
hne : n ≠ m
⊢ ∃ x x_1, (∃ x_2 x_3, nthLe xs x (_ : x < length xs) = nthLe xs x_1 (_ : x_1 < length xs)) ∧ ¬x = x_1
[PROOFSTEP]
exact ⟨n, m, ⟨hn, hm, h⟩, hne⟩
[GOAL]
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
inst✝ : DecidableEq α
l : List α
H : Nodup l
i : Fin (length l)
⊢ get l { val := indexOf (get l i) l, isLt := (_ : indexOf (get l i) l < length l) } = get l i
[PROOFSTEP]
simp
[GOAL]
α : Type u
β : Type v
l l₁ l₂ : List α
r : α → α → Prop
a✝ b a : α
⊢ Nodup (replicate 0 a) ↔ 0 ≤ 1
[PROOFSTEP]
simp [Nat.zero_le]
[GOAL]
α : Type u
β : Type v
l l₁ l₂ : List α
r : α → α → Prop
a✝ b a : α
⊢ Nodup (replicate 1 a) ↔ 1 ≤ 1
[PROOFSTEP]
simp
[GOAL]
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a✝ b : α
inst✝ : DecidableEq α
a : α
l : List α
d : Nodup l
⊢ count a l = if a ∈ l then 1 else 0
[PROOFSTEP]
split_ifs with h
[GOAL]
case pos
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a✝ b : α
inst✝ : DecidableEq α
a : α
l : List α
d : Nodup l
h : a ∈ l
⊢ count a l = 1
[PROOFSTEP]
exact count_eq_one_of_mem d h
[GOAL]
case neg
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a✝ b : α
inst✝ : DecidableEq α
a : α
l : List α
d : Nodup l
h : ¬a ∈ l
⊢ count a l = 0
[PROOFSTEP]
exact count_eq_zero_of_not_mem h
[GOAL]
α : Type u
β : Type v
l l₁✝ l₂✝ : List α
r : α → α → Prop
a b : α
l₁ l₂ : List α
⊢ Nodup (l₁ ++ l₂) ↔ Nodup l₁ ∧ Nodup l₂ ∧ Disjoint l₁ l₂
[PROOFSTEP]
simp only [Nodup, pairwise_append, disjoint_iff_ne]
[GOAL]
α : Type u
β : Type v
l l₁✝ l₂✝ : List α
r : α → α → Prop
a b : α
l₁ l₂ : List α
⊢ Nodup (l₁ ++ l₂) ↔ Nodup (l₂ ++ l₁)
[PROOFSTEP]
simp only [nodup_append, and_left_comm, disjoint_comm]
[GOAL]
α : Type u
β : Type v
l l₁✝ l₂✝ : List α
r : α → α → Prop
a✝ b a : α
l₁ l₂ : List α
⊢ Nodup (l₁ ++ a :: l₂) ↔ Nodup (a :: (l₁ ++ l₂))
[PROOFSTEP]
simp only [nodup_append, not_or, and_left_comm, and_assoc, nodup_cons, mem_append, disjoint_cons_right]
[GOAL]
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
f : α → β
l : List α
d : Nodup (map f l)
⊢ ∀ ⦃x : α⦄, x ∈ l → ∀ ⦃y : α⦄, y ∈ l → f x = f y → x = y
[PROOFSTEP]
induction' l with hd tl ih
[GOAL]
case nil
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
f : α → β
l : List α
d✝ : Nodup (map f l)
d : Nodup (map f [])
⊢ ∀ ⦃x : α⦄, x ∈ [] → ∀ ⦃y : α⦄, y ∈ [] → f x = f y → x = y
[PROOFSTEP]
simp
[GOAL]
case cons
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
f : α → β
l : List α
d✝ : Nodup (map f l)
hd : α
tl : List α
ih : Nodup (map f tl) → ∀ ⦃x : α⦄, x ∈ tl → ∀ ⦃y : α⦄, y ∈ tl → f x = f y → x = y
d : Nodup (map f (hd :: tl))
⊢ ∀ ⦃x : α⦄, x ∈ hd :: tl → ∀ ⦃y : α⦄, y ∈ hd :: tl → f x = f y → x = y
[PROOFSTEP]
simp only [map, nodup_cons, mem_map, not_exists, not_and, ← Ne.def] at d
[GOAL]
case cons
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
f : α → β
l : List α
d✝ : Nodup (map f l)
hd : α
tl : List α
ih : Nodup (map f tl) → ∀ ⦃x : α⦄, x ∈ tl → ∀ ⦃y : α⦄, y ∈ tl → f x = f y → x = y
d : (∀ (x : α), x ∈ tl → f x ≠ f hd) ∧ Nodup (map f tl)
⊢ ∀ ⦃x : α⦄, x ∈ hd :: tl → ∀ ⦃y : α⦄, y ∈ hd :: tl → f x = f y → x = y
[PROOFSTEP]
simp only [mem_cons]
[GOAL]
case cons
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
f : α → β
l : List α
d✝ : Nodup (map f l)
hd : α
tl : List α
ih : Nodup (map f tl) → ∀ ⦃x : α⦄, x ∈ tl → ∀ ⦃y : α⦄, y ∈ tl → f x = f y → x = y
d : (∀ (x : α), x ∈ tl → f x ≠ f hd) ∧ Nodup (map f tl)
⊢ ∀ ⦃x : α⦄, x = hd ∨ x ∈ tl → ∀ ⦃y : α⦄, y = hd ∨ y ∈ tl → f x = f y → x = y
[PROOFSTEP]
rintro _ (rfl | h₁) _ (rfl | h₂) h₃
[GOAL]
case cons.inl.inl
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
f : α → β
l : List α
d✝ : Nodup (map f l)
tl : List α
ih : Nodup (map f tl) → ∀ ⦃x : α⦄, x ∈ tl → ∀ ⦃y : α⦄, y ∈ tl → f x = f y → x = y
y✝ : α
d : (∀ (x : α), x ∈ tl → f x ≠ f y✝) ∧ Nodup (map f tl)
h₃ : f y✝ = f y✝
⊢ y✝ = y✝
[PROOFSTEP]
rfl
[GOAL]
case cons.inl.inr
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
f : α → β
l : List α
d✝ : Nodup (map f l)
tl : List α
ih : Nodup (map f tl) → ∀ ⦃x : α⦄, x ∈ tl → ∀ ⦃y : α⦄, y ∈ tl → f x = f y → x = y
x✝ : α
d : (∀ (x : α), x ∈ tl → f x ≠ f x✝) ∧ Nodup (map f tl)
y✝ : α
h₂ : y✝ ∈ tl
h₃ : f x✝ = f y✝
⊢ x✝ = y✝
[PROOFSTEP]
apply (d.1 _ h₂ h₃.symm).elim
[GOAL]
case cons.inr.inl
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
f : α → β
l : List α
d✝ : Nodup (map f l)
tl : List α
ih : Nodup (map f tl) → ∀ ⦃x : α⦄, x ∈ tl → ∀ ⦃y : α⦄, y ∈ tl → f x = f y → x = y
x✝ : α
h₁ : x✝ ∈ tl
y✝ : α
d : (∀ (x : α), x ∈ tl → f x ≠ f y✝) ∧ Nodup (map f tl)
h₃ : f x✝ = f y✝
⊢ x✝ = y✝
[PROOFSTEP]
apply (d.1 _ h₁ h₃).elim
[GOAL]
case cons.inr.inr
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
f : α → β
l : List α
d✝ : Nodup (map f l)
hd : α
tl : List α
ih : Nodup (map f tl) → ∀ ⦃x : α⦄, x ∈ tl → ∀ ⦃y : α⦄, y ∈ tl → f x = f y → x = y
d : (∀ (x : α), x ∈ tl → f x ≠ f hd) ∧ Nodup (map f tl)
x✝ : α
h₁ : x✝ ∈ tl
y✝ : α
h₂ : y✝ ∈ tl
h₃ : f x✝ = f y✝
⊢ x✝ = y✝
[PROOFSTEP]
apply ih d.2 h₁ h₂ h₃
[GOAL]
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
p : α → Prop
f : (a : α) → p a → β
l : List α
H : ∀ (a : α), a ∈ l → p a
hf : ∀ (a : α) (ha : p a) (b : α) (hb : p b), f a ha = f b hb → a = b
h : Nodup l
⊢ Nodup (List.pmap f l H)
[PROOFSTEP]
rw [pmap_eq_map_attach]
[GOAL]
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
p : α → Prop
f : (a : α) → p a → β
l : List α
H : ∀ (a : α), a ∈ l → p a
hf : ∀ (a : α) (ha : p a) (b : α) (hb : p b), f a ha = f b hb → a = b
h : Nodup l
⊢ Nodup (map (fun x => f ↑x (_ : p ↑x)) (List.attach l))
[PROOFSTEP]
exact h.attach.map fun ⟨a, ha⟩ ⟨b, hb⟩ h => by congr; exact hf a (H _ ha) b (H _ hb) h
[GOAL]
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a✝ b✝ : α
p : α → Prop
f : (a : α) → p a → β
l : List α
H : ∀ (a : α), a ∈ l → p a
hf : ∀ (a : α) (ha : p a) (b : α) (hb : p b), f a ha = f b hb → a = b
h✝ : Nodup l
x✝¹ x✝ : { x // x ∈ l }
a : α
ha : a ∈ l
b : α
hb : b ∈ l
h :
f ↑{ val := a, property := ha } (_ : p ↑{ val := a, property := ha }) =
f ↑{ val := b, property := hb } (_ : p ↑{ val := b, property := hb })
⊢ { val := a, property := ha } = { val := b, property := hb }
[PROOFSTEP]
congr
[GOAL]
case e_val
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a✝ b✝ : α
p : α → Prop
f : (a : α) → p a → β
l : List α
H : ∀ (a : α), a ∈ l → p a
hf : ∀ (a : α) (ha : p a) (b : α) (hb : p b), f a ha = f b hb → a = b
h✝ : Nodup l
x✝¹ x✝ : { x // x ∈ l }
a : α
ha : a ∈ l
b : α
hb : b ∈ l
h :
f ↑{ val := a, property := ha } (_ : p ↑{ val := a, property := ha }) =
f ↑{ val := b, property := hb } (_ : p ↑{ val := b, property := hb })
⊢ a = b
[PROOFSTEP]
exact hf a (H _ ha) b (H _ hb) h
[GOAL]
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
p : α → Bool
l : List α
⊢ Nodup l → Nodup (List.filter p l)
[PROOFSTEP]
simpa using Pairwise.filter (fun a ↦ p a)
[GOAL]
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
l : List α
⊢ Pairwise (fun a b => b ≠ a) l ↔ Nodup l
[PROOFSTEP]
simp only [Nodup, Ne.def, eq_comm]
[GOAL]
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a✝ b : α
inst✝ : DecidableEq α
l : List α
d : Nodup l
a : α
⊢ List.erase l a = List.filter (fun x => decide (x ≠ a)) l
[PROOFSTEP]
induction' d with b l m _ IH
[GOAL]
case nil
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a✝ b : α
inst✝ : DecidableEq α
l : List α
a : α
⊢ List.erase [] a = List.filter (fun x => decide (x ≠ a)) []
[PROOFSTEP]
rfl
[GOAL]
case cons
α : Type u
β : Type v
l✝¹ l₁ l₂ : List α
r : α → α → Prop
a✝¹ b✝ : α
inst✝ : DecidableEq α
l✝ : List α
a b : α
l : List α
m : ∀ (a' : α), a' ∈ l → b ≠ a'
a✝ : Pairwise (fun x x_1 => x ≠ x_1) l
IH : List.erase l a = List.filter (fun x => decide (x ≠ a)) l
⊢ List.erase (b :: l) a = List.filter (fun x => decide (x ≠ a)) (b :: l)
[PROOFSTEP]
by_cases h : b = a
[GOAL]
case pos
α : Type u
β : Type v
l✝¹ l₁ l₂ : List α
r : α → α → Prop
a✝¹ b✝ : α
inst✝ : DecidableEq α
l✝ : List α
a b : α
l : List α
m : ∀ (a' : α), a' ∈ l → b ≠ a'
a✝ : Pairwise (fun x x_1 => x ≠ x_1) l
IH : List.erase l a = List.filter (fun x => decide (x ≠ a)) l
h : b = a
⊢ List.erase (b :: l) a = List.filter (fun x => decide (x ≠ a)) (b :: l)
[PROOFSTEP]
subst h
[GOAL]
case pos
α : Type u
β : Type v
l✝¹ l₁ l₂ : List α
r : α → α → Prop
a b✝ : α
inst✝ : DecidableEq α
l✝ : List α
b : α
l : List α
m : ∀ (a' : α), a' ∈ l → b ≠ a'
a✝ : Pairwise (fun x x_1 => x ≠ x_1) l
IH : List.erase l b = List.filter (fun x => decide (x ≠ b)) l
⊢ List.erase (b :: l) b = List.filter (fun x => decide (x ≠ b)) (b :: l)
[PROOFSTEP]
rw [erase_cons_head, filter_cons_of_neg _ (by simp)]
[GOAL]
α : Type u
β : Type v
l✝¹ l₁ l₂ : List α
r : α → α → Prop
a b✝ : α
inst✝ : DecidableEq α
l✝ : List α
b : α
l : List α
m : ∀ (a' : α), a' ∈ l → b ≠ a'
a✝ : Pairwise (fun x x_1 => x ≠ x_1) l
IH : List.erase l b = List.filter (fun x => decide (x ≠ b)) l
⊢ ¬decide (b ≠ b) = true
[PROOFSTEP]
simp
[GOAL]
case pos
α : Type u
β : Type v
l✝¹ l₁ l₂ : List α
r : α → α → Prop
a b✝ : α
inst✝ : DecidableEq α
l✝ : List α
b : α
l : List α
m : ∀ (a' : α), a' ∈ l → b ≠ a'
a✝ : Pairwise (fun x x_1 => x ≠ x_1) l
IH : List.erase l b = List.filter (fun x => decide (x ≠ b)) l
⊢ l = List.filter (fun x => decide (x ≠ b)) l
[PROOFSTEP]
symm
[GOAL]
case pos
α : Type u
β : Type v
l✝¹ l₁ l₂ : List α
r : α → α → Prop
a b✝ : α
inst✝ : DecidableEq α
l✝ : List α
b : α
l : List α
m : ∀ (a' : α), a' ∈ l → b ≠ a'
a✝ : Pairwise (fun x x_1 => x ≠ x_1) l
IH : List.erase l b = List.filter (fun x => decide (x ≠ b)) l
⊢ List.filter (fun x => decide (x ≠ b)) l = l
[PROOFSTEP]
rw [filter_eq_self]
[GOAL]
case pos
α : Type u
β : Type v
l✝¹ l₁ l₂ : List α
r : α → α → Prop
a b✝ : α
inst✝ : DecidableEq α
l✝ : List α
b : α
l : List α
m : ∀ (a' : α), a' ∈ l → b ≠ a'
a✝ : Pairwise (fun x x_1 => x ≠ x_1) l
IH : List.erase l b = List.filter (fun x => decide (x ≠ b)) l
⊢ ∀ (a : α), a ∈ l → decide (a ≠ b) = true
[PROOFSTEP]
simpa [@eq_comm α] using m
[GOAL]
case neg
α : Type u
β : Type v
l✝¹ l₁ l₂ : List α
r : α → α → Prop
a✝¹ b✝ : α
inst✝ : DecidableEq α
l✝ : List α
a b : α
l : List α
m : ∀ (a' : α), a' ∈ l → b ≠ a'
a✝ : Pairwise (fun x x_1 => x ≠ x_1) l
IH : List.erase l a = List.filter (fun x => decide (x ≠ a)) l
h : ¬b = a
⊢ List.erase (b :: l) a = List.filter (fun x => decide (x ≠ a)) (b :: l)
[PROOFSTEP]
rw [erase_cons_tail _ h, filter_cons_of_pos, IH]
[GOAL]
case neg.pa
α : Type u
β : Type v
l✝¹ l₁ l₂ : List α
r : α → α → Prop
a✝¹ b✝ : α
inst✝ : DecidableEq α
l✝ : List α
a b : α
l : List α
m : ∀ (a' : α), a' ∈ l → b ≠ a'
a✝ : Pairwise (fun x x_1 => x ≠ x_1) l
IH : List.erase l a = List.filter (fun x => decide (x ≠ a)) l
h : ¬b = a
⊢ decide (b ≠ a) = true
[PROOFSTEP]
simp [h]
[GOAL]
α : Type u
β : Type v
l l₁ l₂ : List α
r : α → α → Prop
a b : α
inst✝ : DecidableEq α
d : Nodup l
⊢ a ∈ List.erase l b ↔ a ≠ b ∧ a ∈ l
[PROOFSTEP]
rw [d.erase_eq_filter, mem_filter, and_comm, decide_eq_true_iff]
[GOAL]
α : Type u
β : Type v
l l₁ l₂ : List α
r : α → α → Prop
a b : α
L : List (List α)
⊢ Nodup (join L) ↔ (∀ (l : List α), l ∈ L → Nodup l) ∧ Pairwise Disjoint L
[PROOFSTEP]
simp only [Nodup, pairwise_join, disjoint_left.symm, forall_mem_ne]
[GOAL]
α : Type u
β : Type v
l l₁✝ l₂ : List α
r : α → α → Prop
a b : α
l₁ : List α
f : α → List β
⊢ Nodup (List.bind l₁ f) ↔ (∀ (x : α), x ∈ l₁ → Nodup (f x)) ∧ Pairwise (fun a b => Disjoint (f a) (f b)) l₁
[PROOFSTEP]
simp only [List.bind, nodup_join, pairwise_map, and_comm, and_left_comm, mem_map, exists_imp, and_imp]
[GOAL]
α : Type u
β : Type v
l l₁✝ l₂ : List α
r : α → α → Prop
a b : α
l₁ : List α
f : α → List β
⊢ (Pairwise (fun a b => Disjoint (f a) (f b)) l₁ ∧ ∀ (l : List β) (x : α), f x = l → x ∈ l₁ → Nodup l) ↔
Pairwise (fun a b => Disjoint (f a) (f b)) l₁ ∧ ∀ (x : α), x ∈ l₁ → Nodup (f x)
[PROOFSTEP]
rw [show (∀ (l : List β) (x : α), f x = l → x ∈ l₁ → Nodup l) ↔ ∀ x : α, x ∈ l₁ → Nodup (f x) from
forall_swap.trans <| forall_congr' fun _ => forall_eq']
[GOAL]
α : Type u
β : Type v
l l₁ l₂✝ : List α
r : α → α → Prop
a b : α
l₂ : List β
d₁ : Nodup l₁
d₂ : Nodup l₂
a₁ a₂ : α
n : a₁ ≠ a₂
x : α × β
h₁ : x ∈ map (Prod.mk a₁) l₂
h₂ : x ∈ map (Prod.mk a₂) l₂
⊢ False
[PROOFSTEP]
rcases mem_map.1 h₁ with ⟨b₁, _, rfl⟩
[GOAL]
case intro.intro
α : Type u
β : Type v
l l₁ l₂✝ : List α
r : α → α → Prop
a b : α
l₂ : List β
d₁ : Nodup l₁
d₂ : Nodup l₂
a₁ a₂ : α
n : a₁ ≠ a₂
b₁ : β
left✝ : b₁ ∈ l₂
h₁ : (a₁, b₁) ∈ map (Prod.mk a₁) l₂
h₂ : (a₁, b₁) ∈ map (Prod.mk a₂) l₂
⊢ False
[PROOFSTEP]
rcases mem_map.1 h₂ with ⟨b₂, mb₂, ⟨⟩⟩
[GOAL]
case intro.intro.intro.intro.refl
α : Type u
β : Type v
l l₁ l₂✝ : List α
r : α → α → Prop
a b : α
l₂ : List β
d₁ : Nodup l₁
d₂ : Nodup l₂
a₁ : α
b₁ : β
left✝ : b₁ ∈ l₂
h₁ : (a₁, b₁) ∈ map (Prod.mk a₁) l₂
n : a₁ ≠ a₁
h₂ : (a₁, b₁) ∈ map (Prod.mk a₁) l₂
mb₂ : b₁ ∈ l₂
⊢ False
[PROOFSTEP]
exact n rfl
[GOAL]
α : Type u
β : Type v
l l₁ l₂✝ : List α
r : α → α → Prop
a✝ b✝ : α
σ : α → Type u_1
l₂ : (a : α) → List (σ a)
d₁ : Nodup l₁
d₂ : ∀ (a : α), Nodup (l₂ a)
a : α
x✝ : a ∈ l₁
b b' : (fun a => σ a) a
h : { fst := a, snd := b } = { fst := a, snd := b' }
⊢ b = b'
[PROOFSTEP]
injection h with _ h
[GOAL]
α : Type u
β : Type v
l l₁ l₂✝ : List α
r : α → α → Prop
a b : α
σ : α → Type u_1
l₂ : (a : α) → List (σ a)
d₁ : Nodup l₁
d₂ : ∀ (a : α), Nodup (l₂ a)
a₁ a₂ : α
n : a₁ ≠ a₂
x : (a : α) × σ a
h₁ : x ∈ map (Sigma.mk a₁) (l₂ a₁)
h₂ : x ∈ map (Sigma.mk a₂) (l₂ a₂)
⊢ False
[PROOFSTEP]
rcases mem_map.1 h₁ with ⟨b₁, _, rfl⟩
[GOAL]
case intro.intro
α : Type u
β : Type v
l l₁ l₂✝ : List α
r : α → α → Prop
a b : α
σ : α → Type u_1
l₂ : (a : α) → List (σ a)
d₁ : Nodup l₁
d₂ : ∀ (a : α), Nodup (l₂ a)
a₁ a₂ : α
n : a₁ ≠ a₂
b₁ : σ a₁
left✝ : b₁ ∈ l₂ a₁
h₁ : { fst := a₁, snd := b₁ } ∈ map (Sigma.mk a₁) (l₂ a₁)
h₂ : { fst := a₁, snd := b₁ } ∈ map (Sigma.mk a₂) (l₂ a₂)
⊢ False
[PROOFSTEP]
rcases mem_map.1 h₂ with ⟨b₂, mb₂, ⟨⟩⟩
[GOAL]
case intro.intro.intro.intro.refl
α : Type u
β : Type v
l l₁ l₂✝ : List α
r : α → α → Prop
a b : α
σ : α → Type u_1
l₂ : (a : α) → List (σ a)
d₁ : Nodup l₁
d₂ : ∀ (a : α), Nodup (l₂ a)
a₁ : α
b₁ : σ a₁
left✝ : b₁ ∈ l₂ a₁
h₁ : { fst := a₁, snd := b₁ } ∈ map (Sigma.mk a₁) (l₂ a₁)
n : a₁ ≠ a₁
h₂ : { fst := a₁, snd := b₁ } ∈ map (Sigma.mk a₁) (l₂ a₁)
mb₂ : b₁ ∈ l₂ a₁
⊢ False
[PROOFSTEP]
exact n rfl
[GOAL]
α : Type u
β : Type v
l l₁ l₂ : List α
r : α → α → Prop
a✝ b✝ : α
f : α → Option β
h : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a'
a a' : α
n : a ≠ a'
b : β
bm : b ∈ f a
b' : β
bm' : b' ∈ f a'
e : b = b'
⊢ b' ∈ f a
[PROOFSTEP]
rw [← e]
[GOAL]
α : Type u
β : Type v
l l₁ l₂ : List α
r : α → α → Prop
a✝ b✝ : α
f : α → Option β
h : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a'
a a' : α
n : a ≠ a'
b : β
bm : b ∈ f a
b' : β
bm' : b' ∈ f a'
e : b = b'
⊢ b ∈ f a
[PROOFSTEP]
exact bm
[GOAL]
α : Type u
β : Type v
l l₁ l₂ : List α
r : α → α → Prop
a b : α
h : ¬a ∈ l
h' : Nodup l
⊢ Nodup (concat l a)
[PROOFSTEP]
rw [concat_eq_append]
[GOAL]
α : Type u
β : Type v
l l₁ l₂ : List α
r : α → α → Prop
a b : α
h : ¬a ∈ l
h' : Nodup l
⊢ Nodup (l ++ [a])
[PROOFSTEP]
exact h'.append (nodup_singleton _) (disjoint_singleton.2 h)
[GOAL]
α : Type u
β : Type v
l l₁ l₂ : List α
r : α → α → Prop
a b : α
inst✝ : DecidableEq α
h : Nodup l
h' : a ∈ l
⊢ Nodup (List.insert a l)
[PROOFSTEP]
rw [insert_of_mem h']
[GOAL]
α : Type u
β : Type v
l l₁ l₂ : List α
r : α → α → Prop
a b : α
inst✝ : DecidableEq α
h : Nodup l
h' : a ∈ l
⊢ Nodup l
[PROOFSTEP]
exact h
[GOAL]
α : Type u
β : Type v
l l₁ l₂ : List α
r : α → α → Prop
a b : α
inst✝ : DecidableEq α
h : Nodup l
h' : ¬a ∈ l
⊢ Nodup (List.insert a l)
[PROOFSTEP]
rw [insert_of_not_mem h', nodup_cons]
[GOAL]
α : Type u
β : Type v
l l₁ l₂ : List α
r : α → α → Prop
a b : α
inst✝ : DecidableEq α
h : Nodup l
h' : ¬a ∈ l
⊢ ¬a ∈ l ∧ Nodup l
[PROOFSTEP]
constructor
[GOAL]
case left
α : Type u
β : Type v
l l₁ l₂ : List α
r : α → α → Prop
a b : α
inst✝ : DecidableEq α
h : Nodup l
h' : ¬a ∈ l
⊢ ¬a ∈ l
[PROOFSTEP]
assumption
[GOAL]
case right
α : Type u
β : Type v
l l₁ l₂ : List α
r : α → α → Prop
a b : α
inst✝ : DecidableEq α
h : Nodup l
h' : ¬a ∈ l
⊢ Nodup l
[PROOFSTEP]
assumption
[GOAL]
α : Type u
β : Type v
l l₁✝ l₂ : List α
r : α → α → Prop
a b : α
inst✝ : DecidableEq α
l₁ : List α
h : Nodup l₂
⊢ Nodup (l₁ ∪ l₂)
[PROOFSTEP]
induction' l₁ with a l₁ ih generalizing l₂
[GOAL]
case nil
α : Type u
β : Type v
l l₁ l₂✝ : List α
r : α → α → Prop
a b : α
inst✝ : DecidableEq α
h✝ : Nodup l₂✝
l₂ : List α
h : Nodup l₂
⊢ Nodup ([] ∪ l₂)
[PROOFSTEP]
exact h
[GOAL]
case cons
α : Type u
β : Type v
l l₁✝ l₂✝ : List α
r : α → α → Prop
a✝ b : α
inst✝ : DecidableEq α
h✝ : Nodup l₂✝
a : α
l₁ : List α
ih : ∀ {l₂ : List α}, Nodup l₂ → Nodup (l₁ ∪ l₂)
l₂ : List α
h : Nodup l₂
⊢ Nodup (a :: l₁ ∪ l₂)
[PROOFSTEP]
exact (ih h).insert
[GOAL]
α : Type u
β : Type v
l l₁✝ l₂ : List α
r : α → α → Prop
a b : α
inst✝ : DecidableEq α
l₁ : List α
x✝ : Nodup l₁
⊢ List.diff l₁ [] = List.filter (fun x => decide ¬x ∈ []) l₁
[PROOFSTEP]
simp
[GOAL]
α : Type u
β : Type v
l l₁✝ l₂✝ : List α
r : α → α → Prop
a✝ b : α
inst✝ : DecidableEq α
l₁ : List α
a : α
l₂ : List α
hl₁ : Nodup l₁
⊢ List.diff l₁ (a :: l₂) = List.filter (fun x => decide ¬x ∈ a :: l₂) l₁
[PROOFSTEP]
rw [diff_cons, (hl₁.erase _).diff_eq_filter, hl₁.erase_eq_filter, filter_filter]
[GOAL]
α : Type u
β : Type v
l l₁✝ l₂✝ : List α
r : α → α → Prop
a✝ b : α
inst✝ : DecidableEq α
l₁ : List α
a : α
l₂ : List α
hl₁ : Nodup l₁
⊢ List.filter (fun a_1 => decide ((decide ¬a_1 ∈ l₂) = true ∧ decide (a_1 ≠ a) = true)) l₁ =
List.filter (fun x => decide ¬x ∈ a :: l₂) l₁
[PROOFSTEP]
simp only [decide_not, Bool.not_eq_true', decide_eq_false_iff_not, ne_eq, and_comm, Bool.decide_and, find?, mem_cons,
not_or]
[GOAL]
α : Type u
β : Type v
l l₁ l₂ : List α
r : α → α → Prop
a b : α
inst✝ : DecidableEq α
hl₁ : Nodup l₁
⊢ a ∈ List.diff l₁ l₂ ↔ a ∈ l₁ ∧ ¬a ∈ l₂
[PROOFSTEP]
rw [hl₁.diff_eq_filter, mem_filter, decide_eq_true_iff]
[GOAL]
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
inst✝ : DecidableEq α
l : List α
hl : Nodup l
f : α → β
x : α
y : β
⊢ map (update f x y) l = if x ∈ l then set (map f l) (indexOf x l) y else map f l
[PROOFSTEP]
induction' l with hd tl ihl
[GOAL]
case nil
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
inst✝ : DecidableEq α
l : List α
hl✝ : Nodup l
f : α → β
x : α
y : β
hl : Nodup []
⊢ map (update f x y) [] = if x ∈ [] then set (map f []) (indexOf x []) y else map f []
[PROOFSTEP]
simp
[GOAL]
case cons
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
inst✝ : DecidableEq α
l : List α
hl✝ : Nodup l
f : α → β
x : α
y : β
hd : α
tl : List α
ihl : Nodup tl → map (update f x y) tl = if x ∈ tl then set (map f tl) (indexOf x tl) y else map f tl
hl : Nodup (hd :: tl)
⊢ map (update f x y) (hd :: tl) =
if x ∈ hd :: tl then set (map f (hd :: tl)) (indexOf x (hd :: tl)) y else map f (hd :: tl)
[PROOFSTEP]
rw [nodup_cons] at hl
[GOAL]
case cons
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
inst✝ : DecidableEq α
l : List α
hl✝ : Nodup l
f : α → β
x : α
y : β
hd : α
tl : List α
ihl : Nodup tl → map (update f x y) tl = if x ∈ tl then set (map f tl) (indexOf x tl) y else map f tl
hl : ¬hd ∈ tl ∧ Nodup tl
⊢ map (update f x y) (hd :: tl) =
if x ∈ hd :: tl then set (map f (hd :: tl)) (indexOf x (hd :: tl)) y else map f (hd :: tl)
[PROOFSTEP]
simp only [mem_cons, map, ihl hl.2]
[GOAL]
case cons
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
inst✝ : DecidableEq α
l : List α
hl✝ : Nodup l
f : α → β
x : α
y : β
hd : α
tl : List α
ihl : Nodup tl → map (update f x y) tl = if x ∈ tl then set (map f tl) (indexOf x tl) y else map f tl
hl : ¬hd ∈ tl ∧ Nodup tl
⊢ (update f x y hd :: if x ∈ tl then set (map f tl) (indexOf x tl) y else map f tl) =
if x = hd ∨ x ∈ tl then set (f hd :: map f tl) (indexOf x (hd :: tl)) y else f hd :: map f tl
[PROOFSTEP]
by_cases H : hd = x
[GOAL]
case pos
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
inst✝ : DecidableEq α
l : List α
hl✝ : Nodup l
f : α → β
x : α
y : β
hd : α
tl : List α
ihl : Nodup tl → map (update f x y) tl = if x ∈ tl then set (map f tl) (indexOf x tl) y else map f tl
hl : ¬hd ∈ tl ∧ Nodup tl
H : hd = x
⊢ (update f x y hd :: if x ∈ tl then set (map f tl) (indexOf x tl) y else map f tl) =
if x = hd ∨ x ∈ tl then set (f hd :: map f tl) (indexOf x (hd :: tl)) y else f hd :: map f tl
[PROOFSTEP]
subst hd
[GOAL]
case pos
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
inst✝ : DecidableEq α
l : List α
hl✝ : Nodup l
f : α → β
x : α
y : β
tl : List α
ihl : Nodup tl → map (update f x y) tl = if x ∈ tl then set (map f tl) (indexOf x tl) y else map f tl
hl : ¬x ∈ tl ∧ Nodup tl
⊢ (update f x y x :: if x ∈ tl then set (map f tl) (indexOf x tl) y else map f tl) =
if x = x ∨ x ∈ tl then set (f x :: map f tl) (indexOf x (x :: tl)) y else f x :: map f tl
[PROOFSTEP]
simp [set, hl.1]
[GOAL]
case neg
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b : α
inst✝ : DecidableEq α
l : List α
hl✝ : Nodup l
f : α → β
x : α
y : β
hd : α
tl : List α
ihl : Nodup tl → map (update f x y) tl = if x ∈ tl then set (map f tl) (indexOf x tl) y else map f tl
hl : ¬hd ∈ tl ∧ Nodup tl
H : ¬hd = x
⊢ (update f x y hd :: if x ∈ tl then set (map f tl) (indexOf x tl) y else map f tl) =
if x = hd ∨ x ∈ tl then set (f hd :: map f tl) (indexOf x (hd :: tl)) y else f hd :: map f tl
[PROOFSTEP]
simp [Ne.symm H, H, set, ← apply_ite (cons (f hd))]
[GOAL]
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r✝ : α → α → Prop
a b : α
l : List α
r : α → α → Prop
hl : Nodup l
h : ∀ (a : α), a ∈ l → ∀ (b : α), b ∈ l → a ≠ b → r a b
⊢ Pairwise r l
[PROOFSTEP]
classical
refine' pairwise_of_reflexive_on_dupl_of_forall_ne _ h
intro x hx
rw [nodup_iff_count_le_one] at hl
exact absurd (hl x) hx.not_le
[GOAL]
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r✝ : α → α → Prop
a b : α
l : List α
r : α → α → Prop
hl : Nodup l
h : ∀ (a : α), a ∈ l → ∀ (b : α), b ∈ l → a ≠ b → r a b
⊢ Pairwise r l
[PROOFSTEP]
refine' pairwise_of_reflexive_on_dupl_of_forall_ne _ h
[GOAL]
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r✝ : α → α → Prop
a b : α
l : List α
r : α → α → Prop
hl : Nodup l
h : ∀ (a : α), a ∈ l → ∀ (b : α), b ∈ l → a ≠ b → r a b
⊢ ∀ (a : α), 1 < count a l → r a a
[PROOFSTEP]
intro x hx
[GOAL]
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r✝ : α → α → Prop
a b : α
l : List α
r : α → α → Prop
hl : Nodup l
h : ∀ (a : α), a ∈ l → ∀ (b : α), b ∈ l → a ≠ b → r a b
x : α
hx : 1 < count x l
⊢ r x x
[PROOFSTEP]
rw [nodup_iff_count_le_one] at hl
[GOAL]
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r✝ : α → α → Prop
a b : α
l : List α
r : α → α → Prop
hl✝ : Nodup l
hl : ∀ (a : α), count a l ≤ 1
h : ∀ (a : α), a ∈ l → ∀ (b : α), b ∈ l → a ≠ b → r a b
x : α
hx : 1 < count x l
⊢ r x x
[PROOFSTEP]
exact absurd (hl x) hx.not_le
[GOAL]
α : Type u
β : Type v
l l₁ l₂ : List α
r : α → α → Prop
a b : α
inst✝ : IsSymm α r
hl : Nodup l
⊢ Set.Pairwise {a | a ∈ l} r ↔ Pairwise r l
[PROOFSTEP]
induction' l with a l ih
[GOAL]
case nil
α : Type u
β : Type v
l l₁ l₂ : List α
r : α → α → Prop
a b : α
inst✝ : IsSymm α r
hl✝ : Nodup l
hl : Nodup []
⊢ Set.Pairwise {a | a ∈ []} r ↔ Pairwise r []
[PROOFSTEP]
simp
[GOAL]
case cons
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a✝ b : α
inst✝ : IsSymm α r
hl✝ : Nodup l✝
a : α
l : List α
ih : Nodup l → (Set.Pairwise {a | a ∈ l} r ↔ Pairwise r l)
hl : Nodup (a :: l)
⊢ Set.Pairwise {a_1 | a_1 ∈ a :: l} r ↔ Pairwise r (a :: l)
[PROOFSTEP]
rw [List.nodup_cons] at hl
[GOAL]
case cons
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a✝ b : α
inst✝ : IsSymm α r
hl✝ : Nodup l✝
a : α
l : List α
ih : Nodup l → (Set.Pairwise {a | a ∈ l} r ↔ Pairwise r l)
hl : ¬a ∈ l ∧ Nodup l
⊢ Set.Pairwise {a_1 | a_1 ∈ a :: l} r ↔ Pairwise r (a :: l)
[PROOFSTEP]
have : ∀ b ∈ l, ¬a = b → r a b ↔ r a b := fun b hb => imp_iff_right (ne_of_mem_of_not_mem hb hl.1).symm
[GOAL]
case cons
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a✝ b : α
inst✝ : IsSymm α r
hl✝ : Nodup l✝
a : α
l : List α
ih : Nodup l → (Set.Pairwise {a | a ∈ l} r ↔ Pairwise r l)
hl : ¬a ∈ l ∧ Nodup l
this : ∀ (b : α), b ∈ l → (¬a = b → r a b ↔ r a b)
⊢ Set.Pairwise {a_1 | a_1 ∈ a :: l} r ↔ Pairwise r (a :: l)
[PROOFSTEP]
simp [Set.setOf_or, Set.pairwise_insert_of_symmetric (@symm_of _ r _), ih hl.2, and_comm, forall₂_congr this]
[GOAL]
α : Type u
β : Type v
l l₁ l₂ : List α
r : α → α → Prop
a b : α
inst✝ : DecidableEq α
n : ℕ
x✝ : Nodup []
⊢ take n [] = List.filter (fun x => decide (x ∈ take n [])) []
[PROOFSTEP]
simp
[GOAL]
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b✝ : α
inst✝ : DecidableEq α
b : α
l : List α
x✝ : Nodup (b :: l)
⊢ take 0 (b :: l) = List.filter (fun x => decide (x ∈ take 0 (b :: l))) (b :: l)
[PROOFSTEP]
simp
[GOAL]
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b✝ : α
inst✝ : DecidableEq α
b : α
l : List α
n : ℕ
hl : Nodup (b :: l)
⊢ take (n + 1) (b :: l) = List.filter (fun x => decide (x ∈ take (n + 1) (b :: l))) (b :: l)
[PROOFSTEP]
rw [take_cons, Nodup.take_eq_filter_mem (Nodup.of_cons hl), List.filter_cons_of_pos _ (by simp)]
[GOAL]
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b✝ : α
inst✝ : DecidableEq α
b : α
l : List α
n : ℕ
hl : Nodup (b :: l)
⊢ decide (b ∈ b :: List.filter (fun x => decide (x ∈ take n l)) l) = true
[PROOFSTEP]
simp
[GOAL]
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b✝ : α
inst✝ : DecidableEq α
b : α
l : List α
n : ℕ
hl : Nodup (b :: l)
⊢ b :: List.filter (fun x => decide (x ∈ take n l)) l =
b :: List.filter (fun x => decide (x ∈ b :: List.filter (fun x => decide (x ∈ take n l)) l)) l
[PROOFSTEP]
congr 1
[GOAL]
case e_tail
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b✝ : α
inst✝ : DecidableEq α
b : α
l : List α
n : ℕ
hl : Nodup (b :: l)
⊢ List.filter (fun x => decide (x ∈ take n l)) l =
List.filter (fun x => decide (x ∈ b :: List.filter (fun x => decide (x ∈ take n l)) l)) l
[PROOFSTEP]
refine' List.filter_congr' _
[GOAL]
case e_tail
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b✝ : α
inst✝ : DecidableEq α
b : α
l : List α
n : ℕ
hl : Nodup (b :: l)
⊢ ∀ (x : α),
x ∈ l → (decide (x ∈ take n l) = true ↔ decide (x ∈ b :: List.filter (fun x => decide (x ∈ take n l)) l) = true)
[PROOFSTEP]
intro x hx
[GOAL]
case e_tail
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b✝ : α
inst✝ : DecidableEq α
b : α
l : List α
n : ℕ
hl : Nodup (b :: l)
x : α
hx : x ∈ l
⊢ decide (x ∈ take n l) = true ↔ decide (x ∈ b :: List.filter (fun x => decide (x ∈ take n l)) l) = true
[PROOFSTEP]
have : x ≠ b := fun h => (nodup_cons.1 hl).1 (h ▸ hx)
[GOAL]
case e_tail
α : Type u
β : Type v
l✝ l₁ l₂ : List α
r : α → α → Prop
a b✝ : α
inst✝ : DecidableEq α
b : α
l : List α
n : ℕ
hl : Nodup (b :: l)
x : α
hx : x ∈ l
this : x ≠ b
⊢ decide (x ∈ take n l) = true ↔ decide (x ∈ b :: List.filter (fun x => decide (x ∈ take n l)) l) = true
[PROOFSTEP]
simp (config := { contextual := true }) [List.mem_filter, this, hx]
|
#' curand
#'
#' Random number generators that run on the gpu via CUDA's cuRAND
#' library.
#'
#' @importFrom float float32 float
#'
#' @name curand-package
#' @docType package
#' @author Drew Schmidt
#' @keywords Package
NULL
|
Twentieth @-@ century versions of this verse include :
|
-- Andreas, 2012-01-12
module Common.Irrelevance where
open import Common.Level
record Squash {a}(A : Set a) : Set a where
constructor squash
field
.unsquash : A
open Squash public
|
(* Title: HOL/Auth/n_g2kAbsAfter_lemma_inv__31_on_rules.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_g2kAbsAfter Protocol Case Study*}
theory n_g2kAbsAfter_lemma_inv__31_on_rules imports n_g2kAbsAfter_lemma_on_inv__31
begin
section{*All lemmas on causal relation between inv__31*}
lemma lemma_inv__31_on_rules:
assumes b1: "r \<in> rules N" and b2: "(f=inv__31 )"
shows "invHoldForRule s f r (invariants N)"
proof -
have c1: "(\<exists> d. d\<le>N\<and>r=n_n_Store_i1 d)\<or>
(\<exists> d. d\<le>N\<and>r=n_n_AStore_i1 d)\<or>
(r=n_n_SendReqS_j1 )\<or>
(r=n_n_SendReqEI_i1 )\<or>
(r=n_n_SendReqES_i1 )\<or>
(r=n_n_RecvReq_i1 )\<or>
(r=n_n_SendInvE_i1 )\<or>
(r=n_n_SendInvS_i1 )\<or>
(r=n_n_SendInvAck_i1 )\<or>
(r=n_n_RecvInvAck_i1 )\<or>
(r=n_n_SendGntS_i1 )\<or>
(r=n_n_SendGntE_i1 )\<or>
(r=n_n_RecvGntS_i1 )\<or>
(r=n_n_RecvGntE_i1 )\<or>
(r=n_n_ASendReqIS_j1 )\<or>
(r=n_n_ASendReqSE_j1 )\<or>
(r=n_n_ASendReqEI_i1 )\<or>
(r=n_n_ASendReqES_i1 )\<or>
(r=n_n_SendReqEE_i1 )\<or>
(r=n_n_ARecvReq_i1 )\<or>
(r=n_n_ASendInvE_i1 )\<or>
(r=n_n_ASendInvS_i1 )\<or>
(r=n_n_ASendInvAck_i1 )\<or>
(r=n_n_ARecvInvAck_i1 )\<or>
(r=n_n_ASendGntS_i1 )\<or>
(r=n_n_ASendGntE_i1 )\<or>
(r=n_n_ARecvGntS_i1 )\<or>
(r=n_n_ARecvGntE_i1 )"
apply (cut_tac b1, auto) done
moreover {
assume d1: "(\<exists> d. d\<le>N\<and>r=n_n_Store_i1 d)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_Store_i1Vsinv__31) done
}
moreover {
assume d1: "(\<exists> d. d\<le>N\<and>r=n_n_AStore_i1 d)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_AStore_i1Vsinv__31) done
}
moreover {
assume d1: "(r=n_n_SendReqS_j1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendReqS_j1Vsinv__31) done
}
moreover {
assume d1: "(r=n_n_SendReqEI_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendReqEI_i1Vsinv__31) done
}
moreover {
assume d1: "(r=n_n_SendReqES_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendReqES_i1Vsinv__31) done
}
moreover {
assume d1: "(r=n_n_RecvReq_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_RecvReq_i1Vsinv__31) done
}
moreover {
assume d1: "(r=n_n_SendInvE_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendInvE_i1Vsinv__31) done
}
moreover {
assume d1: "(r=n_n_SendInvS_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendInvS_i1Vsinv__31) done
}
moreover {
assume d1: "(r=n_n_SendInvAck_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendInvAck_i1Vsinv__31) done
}
moreover {
assume d1: "(r=n_n_RecvInvAck_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_RecvInvAck_i1Vsinv__31) done
}
moreover {
assume d1: "(r=n_n_SendGntS_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendGntS_i1Vsinv__31) done
}
moreover {
assume d1: "(r=n_n_SendGntE_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendGntE_i1Vsinv__31) done
}
moreover {
assume d1: "(r=n_n_RecvGntS_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_RecvGntS_i1Vsinv__31) done
}
moreover {
assume d1: "(r=n_n_RecvGntE_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_RecvGntE_i1Vsinv__31) done
}
moreover {
assume d1: "(r=n_n_ASendReqIS_j1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendReqIS_j1Vsinv__31) done
}
moreover {
assume d1: "(r=n_n_ASendReqSE_j1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendReqSE_j1Vsinv__31) done
}
moreover {
assume d1: "(r=n_n_ASendReqEI_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendReqEI_i1Vsinv__31) done
}
moreover {
assume d1: "(r=n_n_ASendReqES_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendReqES_i1Vsinv__31) done
}
moreover {
assume d1: "(r=n_n_SendReqEE_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendReqEE_i1Vsinv__31) done
}
moreover {
assume d1: "(r=n_n_ARecvReq_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ARecvReq_i1Vsinv__31) done
}
moreover {
assume d1: "(r=n_n_ASendInvE_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendInvE_i1Vsinv__31) done
}
moreover {
assume d1: "(r=n_n_ASendInvS_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendInvS_i1Vsinv__31) done
}
moreover {
assume d1: "(r=n_n_ASendInvAck_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendInvAck_i1Vsinv__31) done
}
moreover {
assume d1: "(r=n_n_ARecvInvAck_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ARecvInvAck_i1Vsinv__31) done
}
moreover {
assume d1: "(r=n_n_ASendGntS_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendGntS_i1Vsinv__31) done
}
moreover {
assume d1: "(r=n_n_ASendGntE_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendGntE_i1Vsinv__31) done
}
moreover {
assume d1: "(r=n_n_ARecvGntS_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ARecvGntS_i1Vsinv__31) done
}
moreover {
assume d1: "(r=n_n_ARecvGntE_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ARecvGntE_i1Vsinv__31) done
}
ultimately show "invHoldForRule s f r (invariants N)"
by satx
qed
end
|
# Word Embeddings: Intro to CBOW model, activation functions and working with Numpy
In this lecture notebook you will be given an introduction to the continuous bag-of-words model, its activation functions and some considerations when working with Numpy.
Let's dive into it!
```python
import numpy as np
```
# The continuous bag-of-words model
The CBOW model is based on a neural network, the architecture of which looks like the figure below, as you'll recall from the lecture.
<div style="width:image width px; font-size:100%; text-align:center;"> Figure 1 </div>
## Activation functions
Let's start by implementing the activation functions, ReLU and softmax.
### ReLU
ReLU is used to calculate the values of the hidden layer, in the following formulas:
\begin{align}
\mathbf{z_1} &= \mathbf{W_1}\mathbf{x} + \mathbf{b_1} \tag{1} \\
\mathbf{h} &= \mathrm{ReLU}(\mathbf{z_1}) \tag{2} \\
\end{align}
Let's fix a value for $\mathbf{z_1}$ as a working example.
```python
# Define a random seed so all random outcomes can be reproduced
np.random.seed(10)
# Define a 5X1 column vector using numpy
z_1 = 10*np.random.rand(5, 1)-5
# Print the vector
z_1
```
array([[ 2.71320643],
[-4.79248051],
[ 1.33648235],
[ 2.48803883],
[-0.01492988]])
Notice that using numpy's `random.rand` function returns a numpy array filled with values taken from a uniform distribution over [0, 1). Numpy allows vectorization so each value is multiplied by 10 and then substracted 5.
To get the ReLU of this vector, you want all the negative values to become zeros.
First create a copy of this vector.
```python
# Create copy of vector and save it in the 'h' variable
h = z_1.copy()
```
Now determine which of its values are negative.
```python
# Determine which values met the criteria (this is possible because of vectorization)
h < 0
```
array([[False],
[ True],
[False],
[False],
[ True]])
You can now simply set all of the values which are negative to 0.
```python
# Slice the array or vector. This is the same as applying ReLU to it
h[h < 0] = 0
```
And that's it: you have the ReLU of $\mathbf{z_1}$!
```python
# Print the vector after ReLU
h
```
array([[2.71320643],
[0. ],
[1.33648235],
[2.48803883],
[0. ]])
**Now implement ReLU as a function.**
```python
# Define the 'relu' function that will include the steps previously seen
def relu(z):
result = z.copy()
result[result < 0] = 0
return result
```
**And check that it's working.**
```python
# Define a new vector and save it in the 'z' variable
z = np.array([[-1.25459881], [ 4.50714306], [ 2.31993942], [ 0.98658484], [-3.4398136 ]])
# Apply ReLU to it
relu(z)
```
array([[0. ],
[4.50714306],
[2.31993942],
[0.98658484],
[0. ]])
Expected output:
array([[0. ],
[4.50714306],
[2.31993942],
[0.98658484],
[0. ]])
### Softmax
The second activation function that you need is softmax. This function is used to calculate the values of the output layer of the neural network, using the following formulas:
\begin{align}
\mathbf{z_2} &= \mathbf{W_2}\mathbf{h} + \mathbf{b_2} \tag{3} \\
\mathbf{\hat y} &= \mathrm{softmax}(\mathbf{z_2}) \tag{4} \\
\end{align}
To calculate softmax of a vector $\mathbf{z}$, the $i$-th component of the resulting vector is given by:
$$ \textrm{softmax}(\textbf{z})_i = \frac{e^{z_i} }{\sum\limits_{j=1}^{V} e^{z_j} } \tag{5} $$
Let's work through an example.
```python
# Define a new vector and save it in the 'z' variable
z = np.array([9, 8, 11, 10, 8.5])
# Print the vector
z
```
array([ 9. , 8. , 11. , 10. , 8.5])
You'll need to calculate the exponentials of each element, both for the numerator and for the denominator.
```python
# Save exponentials of the values in a new vector
e_z = np.exp(z)
# Print the vector with the exponential values
e_z
```
array([ 8103.08392758, 2980.95798704, 59874.1417152 , 22026.46579481,
4914.7688403 ])
The denominator is equal to the sum of these exponentials.
```python
# Save the sum of the exponentials
sum_e_z = np.sum(e_z)
# Print sum of exponentials
sum_e_z
```
97899.41826492078
And the value of the first element of $\textrm{softmax}(\textbf{z})$ is given by:
```python
# Print softmax value of the first element in the original vector
e_z[0]/sum_e_z
```
0.08276947985173956
This is for one element. You can use numpy's vectorized operations to calculate the values of all the elements of the $\textrm{softmax}(\textbf{z})$ vector in one go.
**Implement the softmax function.**
```python
# Define the 'softmax' function that will include the steps previously seen
def softmax(z):
e_z = np.exp(z)
sum_e_z = np.sum(e_z)
return e_z / sum_e_z
```
**Now check that it works.**
```python
# Print softmax values for original vector
softmax([9, 8, 11, 10, 8.5])
```
array([0.08276948, 0.03044919, 0.61158833, 0.22499077, 0.05020223])
Expected output:
array([0.08276948, 0.03044919, 0.61158833, 0.22499077, 0.05020223])
Notice that the sum of all these values is equal to 1.
```python
# Assert that the sum of the softmax values is equal to 1
np.sum(softmax([9, 8, 11, 10, 8.5])) == 1
```
True
## Dimensions: 1-D arrays vs 2-D column vectors
Before moving on to implement forward propagation, backpropagation, and gradient descent in the next lecture notebook, let's have a look at the dimensions of the vectors you've been handling until now.
Create a vector of length $V$ filled with zeros.
```python
# Define V. Remember this was the size of the vocabulary in the previous lecture notebook
V = 5
# Define vector of length V filled with zeros
x_array = np.zeros(V)
# Print vector
x_array
```
array([0., 0., 0., 0., 0.])
This is a 1-dimensional array, as revealed by the `.shape` property of the array.
```python
# Print vector's shape
x_array.shape
```
(5,)
To perform matrix multiplication in the next steps, you actually need your column vectors to be represented as a matrix with one column. In numpy, this matrix is represented as a 2-dimensional array.
The easiest way to convert a 1D vector to a 2D column matrix is to set its `.shape` property to the number of rows and one column, as shown in the next cell.
```python
# Copy vector
x_column_vector = x_array.copy()
# Reshape copy of vector
x_column_vector.shape = (V, 1) # alternatively ... = (x_array.shape[0], 1)
# Print vector
x_column_vector
```
array([[0.],
[0.],
[0.],
[0.],
[0.]])
The shape of the resulting "vector" is:
```python
# Print vector's shape
x_column_vector.shape
```
(5, 1)
So you now have a 5x1 matrix that you can use to perform standard matrix multiplication.
**Congratulations on finishing this lecture notebook!** Hopefully you now have a better understanding of the activation functions used in the continuous bag-of-words model, as well as a clearer idea of how to leverage Numpy's power for these types of mathematical computations.
In the next lecture notebook you will get a comprehensive dive into:
- Forward propagation.
- Cross-entropy loss.
- Backpropagation.
- Gradient descent.
**See you next time!**
|
# Intergal using Line Equation from Stock Histocial Data
```python
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
from sympy import *
import warnings
warnings.filterwarnings("ignore")
# yfinance is used to fetch data
import yfinance as yf
yf.pdr_override()
```
```python
# input
symbol = 'AMD'
start = '2017-01-01'
end = '2019-01-01'
# Read data
dataset = yf.download(symbol,start,end)['Adj Close']
# View Columns
dataset.head()
```
[*********************100%***********************] 1 of 1 completed
Date
2017-01-03 11.43
2017-01-04 11.43
2017-01-05 11.24
2017-01-06 11.32
2017-01-09 11.49
Name: Adj Close, dtype: float64
```python
df = dataset.reset_index()
```
```python
df.head()
```
<div>
<style scoped>
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</style>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>Date</th>
<th>Adj Close</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>2017-01-03</td>
<td>11.43</td>
</tr>
<tr>
<th>1</th>
<td>2017-01-04</td>
<td>11.43</td>
</tr>
<tr>
<th>2</th>
<td>2017-01-05</td>
<td>11.24</td>
</tr>
<tr>
<th>3</th>
<td>2017-01-06</td>
<td>11.32</td>
</tr>
<tr>
<th>4</th>
<td>2017-01-09</td>
<td>11.49</td>
</tr>
</tbody>
</table>
</div>
```python
df.tail()
```
<div>
<style scoped>
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</style>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>Date</th>
<th>Adj Close</th>
</tr>
</thead>
<tbody>
<tr>
<th>497</th>
<td>2018-12-24</td>
<td>16.650000</td>
</tr>
<tr>
<th>498</th>
<td>2018-12-26</td>
<td>17.900000</td>
</tr>
<tr>
<th>499</th>
<td>2018-12-27</td>
<td>17.490000</td>
</tr>
<tr>
<th>500</th>
<td>2018-12-28</td>
<td>17.820000</td>
</tr>
<tr>
<th>501</th>
<td>2018-12-31</td>
<td>18.459999</td>
</tr>
</tbody>
</table>
</div>
```python
max_p = df['Adj Close'].max()
min_p = df['Adj Close'].min()
avg_p = df['Adj Close'].mean()
```
```python
data = df.drop(['Date'], axis=1)
data
```
<div>
<style scoped>
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</style>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>Adj Close</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>11.430000</td>
</tr>
<tr>
<th>1</th>
<td>11.430000</td>
</tr>
<tr>
<th>2</th>
<td>11.240000</td>
</tr>
<tr>
<th>3</th>
<td>11.320000</td>
</tr>
<tr>
<th>4</th>
<td>11.490000</td>
</tr>
<tr>
<th>...</th>
<td>...</td>
</tr>
<tr>
<th>497</th>
<td>16.650000</td>
</tr>
<tr>
<th>498</th>
<td>17.900000</td>
</tr>
<tr>
<th>499</th>
<td>17.490000</td>
</tr>
<tr>
<th>500</th>
<td>17.820000</td>
</tr>
<tr>
<th>501</th>
<td>18.459999</td>
</tr>
</tbody>
</table>
<p>502 rows × 1 columns</p>
</div>
```python
data = data.reset_index()
```
```python
data.values
```
array([[ 0. , 11.43000031],
[ 1. , 11.43000031],
[ 2. , 11.23999977],
...,
[499. , 17.48999977],
[500. , 17.81999969],
[501. , 18.45999908]])
```python
from numpy import ones,vstack
from numpy.linalg import lstsq
```
```python
points = data.values
```
```python
x_coords, y_coords = zip(*points)
A = vstack([x_coords,ones(len(x_coords))]).T
m, c = lstsq(A, y_coords)[0]
```
```python
print("Line Equation is y = {m}x + {c}".format(m=m,c=c))
```
Line Equation is y = 0.021718614923358828x + 9.372574584656501
```python
equation_of_line = print("y = {m}x + {c}".format(m=m,c=c))
```
y = 0.021718614923358828x + 9.372574584656501
```python
equation = print("{m}*x + {c}".format(m=m,c=c))
```
0.021718614923358828*x + 9.372574584656501
```python
x = Symbol('x')
```
```python
integrate(0.021718614923358828*x+9.372574584656501, x)
```
$\displaystyle 0.0108593074616794 x^{2} + 9.3725745846565 x$
```python
integrate(0.0108593074616794*x**2 + 9.3725745846565 * x, x)
```
$\displaystyle 0.00361976915389313 x^{3} + 4.68628729232825 x^{2}$
# Univariate roots and fixed points
```python
def f(x):
return 0.00361976915389313*x**3 + 4.68628729232825 * x**2
```
```python
x = df['Adj Close']
```
```python
plt.axhline((f(x)).mean(), c='red')
plt.plot(x, f(x))
```
|
## Worked example: Symmetry reduction
```python
import numpy as np
import sympy as sp
import scipy.linalg as la
```
### Some routines for creating rotation matrices and transpositions
```python
def get_rotation_matrix(phi, axis):
cp = np.cos(phi)
sp = np.sin(phi)
r1, r2, r3 = axis
Rm = np.array(
[
[
r1 ** 2 * (1 - cp) + cp,
r1 * r2 * (1 - cp) - r3 * sp,
r1 * r3 * (1 - cp) + r2 * sp,
],
[
r1 * r2 * (1 - cp) + r3 * sp,
r2 ** 2 * (1 - cp) + cp,
r2 * r3 * (1 - cp) - r1 * sp,
],
[
r3 * r1 * (1 - cp) - r2 * sp,
r2 * r3 * (1 - cp) + r1 * sp,
r3 ** 2 * (1 - cp) + cp,
],
]
)
# Clean spurious terms
for ii, jj in np.ndindex(Rm.shape):
if abs(Rm[ii, jj]) < 1e-10:
Rm[ii, jj] = 0
sp = np.sin(phi)
return Rm
def get_transposition(nd, verbose=0):
# Make a basis:
basis_nd = []
for ii in range(nd):
for jj in range(nd):
emp = np.zeros([nd, nd], dtype="int8")
bb = emp
bb[ii, jj] = 1
basis_nd.append(bb)
#
# Build transpose and return:
transp = np.array([bb.T.flatten() for bb in basis_nd])
return transp
# pretty print matrix
def pprint(M, maxl=80):
M = np.atleast_2d(M)
dim1, dim2 = M.shape
lengths = [len(str(el)) for el in M.flatten()]
maxl = min(maxl, max(lengths))
for ii in range(dim1):
print(
(f" | " + " , ".join([f"{str(el)[:maxl]:{maxl}s}" for el in M[ii]]) + " |")
)
```
### Start: Define a matrix $A$
* Define a general 3x3 matrix $A$ and its 9x1 vectorized representation
$$ \boldsymbol{a} = {\textbf{vec}} (A)$$
* $A$ and $\boldsymbol a$ can, e.g., represent a physical tensor (conductivity, stress, ...)
```python
ndim = 3
sym = sp.Symbol
A = sp.ones(ndim, ndim)
for ii in range(ndim):
for jj in range(ndim):
A[ndim * ii + jj] = sym(f"a_{ii}{jj}")
A = np.array(A)
a = A.flatten()
print("Matrix A:")
pprint(A)
print("vec(A):")
pprint(a)
```
Matrix A:
| a_00 , a_01 , a_02 |
| a_10 , a_11 , a_12 |
| a_20 , a_21 , a_22 |
vec(A):
| a_00 , a_01 , a_02 , a_10 , a_11 , a_12 , a_20 , a_21 , a_22 |
### Case 1: Cubic system
* Define 3 rotation matrices $M_i$ that implement a 90° rotation about $x$, $y$, and $z$ axis
* Construct the rotation matrices in the flattened representatin by Roth's Relationship, i.e.
$$ M_\text{flat} = M \otimes M $$
* Add transposition (not necessary in cubic case)
```python
r1 = get_rotation_matrix(np.pi / 2, [1, 0, 0])
r2 = get_rotation_matrix(np.pi / 2, [0, 1, 0])
r3 = get_rotation_matrix(np.pi / 2, [0, 0, 1])
pprint(r1)
```
| 1.0 , 0.0 , 0.0 |
| 0.0 , 0.0 , -1.0 |
| 0.0 , 1.0 , 0.0 |
#### Construct big matrices implementing rotations (+transposition) of the vectorized tensor
```python
R1 = np.kron(r1, r1)
R2 = np.kron(r2, r2)
R3 = np.kron(r3, r3)
T = get_transposition(ndim)
```
#### Now sum up the matrices we want to invariant under, i.e.
$$ \sum_i (\mathbf 1 - M_i)~a = 0$$
```python
id = np.eye(len(a))
inv = 4*id - R1 - R2 - R3 - T
```
#### Consctruct nullspace by SVD
__[scipy-cookbook.readthedocs.io/items/RankNullspace.html](http://scipy-cookbook.readthedocs.io/items/RankNullspace.html)__
```python
u, s, vh = la.svd(inv, lapack_driver="gesdd")
rank = (s > 1e-12).sum()
print(f"Initial Dimension: {len(a)}")
print(f"Rank of Nullspace (= No. irred. elements): {len(a) - rank}")
```
Initial Dimension: 9
Rank of Nullspace (= No. irred. elements): 1
#### Construct matrices translating between full and reduced representation
* $S$ reconstructs the full representation $a$ from a given reduced $\tilde a$. One can think of $\tilde a$ as being the components of $a$ in the basis given by the vectors in $S$:
$$ a = S \, \tilde{a}$$
* $S^+$ (pseudo-inverse, often just transpose) projects a given $a$ onto the irreducible components $\tilde a$
$$\tilde{a} = S^+ a$$
```python
S = vh[rank:].T
Sp = S.T
```
#### Build projectors
* $P = S^\vphantom{+} S^+$
* $\boldsymbol{1}_\text{irred} = S^+ S^\phantom{+}$
```python
P = S @ Sp
id_irred = Sp @ S
print("Projector onto invariant space")
pprint(P, 4)
print("Identity within invariant space")
pprint(id_irred)
```
Projector onto invariant space
| 0.33 , 0.0 , 1.77 , -6.9 , 0.33 , 1.01 , 1.29 , -5.2 , 0.33 |
| 0.0 , 0.0 , 0.0 , 0.0 , 0.0 , 0.0 , 0.0 , 0.0 , 0.0 |
| 1.77 , 0.0 , 9.49 , -3.6 , 1.77 , 5.44 , 6.91 , -2.8 , 1.77 |
| -6.9 , 0.0 , -3.6 , 1.43 , -6.9 , -2.1 , -2.6 , 1.09 , -6.9 |
| 0.33 , 0.0 , 1.77 , -6.9 , 0.33 , 1.01 , 1.29 , -5.2 , 0.33 |
| 1.01 , 0.0 , 5.44 , -2.1 , 1.01 , 3.11 , 3.96 , -1.6 , 1.01 |
| 1.29 , 0.0 , 6.91 , -2.6 , 1.29 , 3.96 , 5.04 , -2.0 , 1.29 |
| -5.2 , 0.0 , -2.8 , 1.09 , -5.2 , -1.6 , -2.0 , 8.28 , -5.2 |
| 0.33 , 0.0 , 1.77 , -6.9 , 0.33 , 1.01 , 1.29 , -5.2 , 0.33 |
Identity within invariant space
| 1.0000000000000002 |
#### Symmetrize the tensor with the projector obtained
$$ \text{sym} (a) = P a = S^\vphantom{+} S^+ a = S \, \tilde a $$
```python
aT = np.dot(Sp, a)
aS = np.dot(S, aT) # = np.dot(P, a)
```
#### How does the matrix $A$ now look like?
$$A = \text{unvec} \left( \text{sym} (a) \right)$$
```python
As = aS.reshape(3,3)
print('1/3*')
pprint(3*As)
```
1/3*
| 1.0*a_00 + 5.33729362479519e-33*a_02 - 2.07749100017982e-35*a_10 + 1.0*a_11 + 3. , 0 , 5.33729362479519e-33*a_00 + 2.84867032372794e-65*a_02 - 1.10881794708291e-67*a_1 |
| -2.07749100017982e-35*a_00 - 1.10881794708291e-67*a_02 + 4.31596885582815e-70*a_ , 1.0*a_00 + 5.33729362479519e-33*a_02 - 2.07749100017982e-35*a_10 + 1.0*a_11 + 3. , 3.05816280424746e-34*a_00 + 1.63223128386957e-66*a_02 - 6.35330570290877e-69*a_1 |
| 3.8891592043194e-34*a_00 + 2.07575846270274e-66*a_02 - 8.07969324524005e-69*a_10 , -1.57643859172956e-33*a_00 - 8.41391564551927e-66*a_02 + 3.2750369866543e-68*a_1 , 1.0*a_00 + 5.33729362479519e-33*a_02 - 2.07749100017982e-35*a_10 + 1.0*a_11 + 3. |
$= \frac{1}{3} \text{Tr A}$
## How about hexagonal?
Start with defining three-fold rotations in $x,y$ plane, i.e., about $z$ axis
```python
r1 = get_rotation_matrix(np.pi / 6, [0, 0, 1])
r2 = get_rotation_matrix(np.pi / 3, [0, 0, 1])
```
Construct the matrices in the flatten represenation as before
```python
R1 = np.kron(r1, r1)
R2 = np.kron(r2, r2)
T = get_transposition(ndim)
```
```python
id = np.eye(len(a))
inv = 3*id - R1 - R2 - T
```
```python
# Consctruct nullspace
u, s, vh = la.svd(inv, lapack_driver="gesdd")
rank = (s > 1e-12).sum()
print(f"Dimension: {len(a)}")
print(f"Rank of Nullspace: {len(a) - rank}")
```
Dimension: 9
Rank of Nullspace: 2
```python
# Nullspace:
S = vh[rank:].T
# clean S
for ii, jj in np.ndindex(S.shape):
if abs(S[ii, jj]) < 1e-10:
S[ii, jj] = 0
Sp = S.T
```
How do the projectors look like?
```python
print(S@Sp)
#print(Sp)
#print(S@Sp)
print(Sp@S)
```
[[0.5 0. 0. 0. 0.5 0. 0. 0. 0. ]
[0. 0. 0. 0. 0. 0. 0. 0. 0. ]
[0. 0. 0. 0. 0. 0. 0. 0. 0. ]
[0. 0. 0. 0. 0. 0. 0. 0. 0. ]
[0.5 0. 0. 0. 0.5 0. 0. 0. 0. ]
[0. 0. 0. 0. 0. 0. 0. 0. 0. ]
[0. 0. 0. 0. 0. 0. 0. 0. 0. ]
[0. 0. 0. 0. 0. 0. 0. 0. 0. ]
[0. 0. 0. 0. 0. 0. 0. 0. 1. ]]
[[1. 0.]
[0. 1.]]
```python
# Projector
P = S@Sp
```
```python
# Symmetrize a
aS = np.dot(P, a)
```
```python
# Restore shape
As = aS.reshape(3,3)
```
```python
pprint(As)
```
| 0.5*a_00 + 0.5*a_11 , 0 , 0 |
| 0 , 0.5*a_00 + 0.5*a_11 , 0 |
| 0 , 0 , 1.0*a_22 |
```python
```
|
-- ---------------------------------------------------------------- [ Main.idr ]
-- Module : Main
-- Description : Test runner for solutions to exercises in Edwin Brady's
-- book, "Type-Driven Development with Idris."
-- --------------------------------------------------------------------- [ EOH ]
module Main
import Exercises.Test.GettingStarted
import Exercises.Test.Interactive
import Exercises.Test.DataTypes
import Exercises.Test.State
import Test.Helpers
import Test.Utils
import Data.Vect
import System
main : IO ()
main = do resCh2 <- GettingStarted.runTests
resCh3 <- Interactive.runTests
resCh4 <- DataTypes.runTests
resCh12 <- State.runTests
let results = resCh2 ++ resCh3 ++ resCh4 ++ resCh12
printSummary results
when (any not results) (exit 1)
-- --------------------------------------------------------------------- [ EOF ]
|
L.A.M.B. has participated in the Spring / Summer 2006 , 2007 , and 2008 New York Fashion Weeks . Stefani described her first line , which debuted on September 16 , 2005 , as " a little Sound of Music , some Orange County chola girl , some Rasta , and a bit of The Great Gatsby . " The highlights of the show were purple cars bouncing using hydraulics while Stefani 's song " Wind It Up " made its debut as the models walked the runway .
|
(* Title: JinjaThreads/Compiler/Exception_Tables.thy
Author: Andreas Lochbihler
*)
header {* \isaheader{Various Operations for Exception Tables} *}
theory Exception_Tables imports
Compiler2
"../Common/ExternalCallWF"
"../JVM/JVMExceptions"
begin
definition pcs :: "ex_table \<Rightarrow> nat set"
where "pcs xt \<equiv> \<Union>(f,t,C,h,d) \<in> set xt. {f ..< t}"
lemma pcs_subset:
fixes e :: "'addr expr1" and es :: "'addr expr1 list"
shows "pcs(compxE2 e pc d) \<subseteq> {pc..<pc+size(compE2 e)}"
and "pcs(compxEs2 es pc d) \<subseteq> {pc..<pc+size(compEs2 es)}"
apply(induct e pc d and es pc d rule: compxE2_compxEs2_induct)
apply (simp_all add:pcs_def)
apply (fastforce)+
done
lemma pcs_Nil [simp]: "pcs [] = {}"
by(simp add:pcs_def)
lemma pcs_Cons [simp]: "pcs (x#xt) = {fst x ..< fst(snd x)} \<union> pcs xt"
by(auto simp add: pcs_def)
lemma pcs_append [simp]: "pcs(xt\<^sub>1 @ xt\<^sub>2) = pcs xt\<^sub>1 \<union> pcs xt\<^sub>2"
by(simp add:pcs_def)
lemma [simp]: "pc < pc0 \<or> pc0+size(compEs2 es) \<le> pc \<Longrightarrow> pc \<notin> pcs(compxEs2 es pc0 d)"
using pcs_subset by fastforce
lemma [simp]: "pc1 + size(compE2 e1) \<le> pc2 \<Longrightarrow> pcs(compxE2 e1 pc1 d1) \<inter> pcs(compxE2 e2 pc2 d2) = {}"
using pcs_subset by fastforce
lemma [simp]: "pc\<^sub>1 + size(compE2 e) \<le> pc\<^sub>2 \<Longrightarrow> pcs(compxE2 e pc\<^sub>1 d\<^sub>1) \<inter> pcs(compxEs2 es pc\<^sub>2 d\<^sub>2) = {}"
using pcs_subset by fastforce
lemma match_ex_table_append_not_pcs [simp]:
"pc \<notin> pcs xt0 \<Longrightarrow> match_ex_table P C pc (xt0 @ xt1) = match_ex_table P C pc xt1"
by (induct xt0) (auto simp: matches_ex_entry_def)
lemma outside_pcs_not_matches_entry [simp]:
"\<lbrakk> x \<in> set xt; pc \<notin> pcs xt \<rbrakk> \<Longrightarrow> \<not> matches_ex_entry P D pc x"
by(auto simp:matches_ex_entry_def pcs_def)
lemma outside_pcs_compxE2_not_matches_entry [simp]:
assumes xe: "xe \<in> set(compxE2 e pc d)"
and outside: "pc' < pc \<or> pc+size(compE2 e) \<le> pc'"
shows "\<not> matches_ex_entry P C pc' xe"
proof
assume "matches_ex_entry P C pc' xe"
with xe have "pc' \<in> pcs(compxE2 e pc d)"
by(force simp add:matches_ex_entry_def pcs_def)
with outside show False by simp
qed
lemma outside_pcs_compxEs2_not_matches_entry [simp]:
assumes xe: "xe \<in> set(compxEs2 es pc d)"
and outside: "pc' < pc \<or> pc+size(compEs2 es) \<le> pc'"
shows "\<not> matches_ex_entry P C pc' xe"
proof
assume "matches_ex_entry P C pc' xe"
with xe have "pc' \<in> pcs(compxEs2 es pc d)"
by(force simp add:matches_ex_entry_def pcs_def)
with outside show False by simp
qed
lemma match_ex_table_app[simp]:
"\<forall>xte \<in> set xt\<^sub>1. \<not> matches_ex_entry P D pc xte \<Longrightarrow>
match_ex_table P D pc (xt\<^sub>1 @ xt) = match_ex_table P D pc xt"
by(induct xt\<^sub>1) simp_all
lemma match_ex_table_eq_NoneI [simp]:
"\<forall>x \<in> set xtab. \<not> matches_ex_entry P C pc x \<Longrightarrow>
match_ex_table P C pc xtab = None"
using match_ex_table_app[where ?xt = "[]"] by fastforce
lemma match_ex_entry:
fixes start shows
"matches_ex_entry P C pc (start, end, catch_type, handler) =
(start \<le> pc \<and> pc < end \<and> (case catch_type of None \<Rightarrow> True | \<lfloor>C'\<rfloor> \<Rightarrow> P \<turnstile> C \<preceq>\<^sup>* C'))"
by(simp add:matches_ex_entry_def)
lemma pcs_compxE2D [dest]:
"pc \<in> pcs (compxE2 e pc' d) \<Longrightarrow> pc' \<le> pc \<and> pc < pc' + length (compE2 e)"
using pcs_subset by(fastforce)
lemma pcs_compxEs2D [dest]:
"pc \<in> pcs (compxEs2 es pc' d) \<Longrightarrow> pc' \<le> pc \<and> pc < pc' + length (compEs2 es)"
using pcs_subset by(fastforce)
definition shift :: "nat \<Rightarrow> ex_table \<Rightarrow> ex_table"
where
"shift n xt \<equiv> map (\<lambda>(from,to,C,handler,depth). (n+from,n+to,C,n+handler,depth)) xt"
lemma shift_0 [simp]: "shift 0 xt = xt"
by(induct xt)(auto simp:shift_def)
lemma shift_Nil [simp]: "shift n [] = []"
by(simp add:shift_def)
lemma shift_Cons_tuple [simp]:
"shift n ((from, to, C, handler, depth) # xt) = (from + n, to + n, C, handler + n, depth) # shift n xt"
by(simp add: shift_def)
lemma shift_append [simp]: "shift n (xt\<^sub>1 @ xt\<^sub>2) = shift n xt\<^sub>1 @ shift n xt\<^sub>2"
by(simp add:shift_def)
lemma shift_shift [simp]: "shift m (shift n xt) = shift (m+n) xt"
by(simp add: shift_def split_def)
lemma fixes e :: "'addr expr1" and es :: "'addr expr1 list"
shows shift_compxE2: "shift pc (compxE2 e pc' d) = compxE2 e (pc' + pc) d"
and shift_compxEs2: "shift pc (compxEs2 es pc' d) = compxEs2 es (pc' + pc) d"
by(induct e and es arbitrary: pc pc' d and pc pc' d rule: compE2.induct compEs2.induct)
(auto simp:shift_def ac_simps)
lemma compxE2_size_convs [simp]: "n \<noteq> 0 \<Longrightarrow> compxE2 e n d = shift n (compxE2 e 0 d)"
and compxEs2_size_convs: "n \<noteq> 0 \<Longrightarrow> compxEs2 es n d = shift n (compxEs2 es 0 d)"
by(simp_all add:shift_compxE2 shift_compxEs2)
lemma pcs_shift_conv [simp]: "pcs (shift n xt) = op + n ` pcs xt"
apply(auto simp add: shift_def pcs_def)
apply(rule_tac x="x-n" in image_eqI)
apply(auto)
apply(rule bexI)
prefer 2
apply(assumption)
apply(auto)
done
lemma image_plus_const_conv [simp]:
fixes m :: nat
shows "m \<in> op + n ` A \<longleftrightarrow> m \<ge> n \<and> m - n \<in> A"
by(force)
lemma match_ex_table_shift_eq_None_conv [simp]:
"match_ex_table P C pc (shift n xt) = None \<longleftrightarrow> pc < n \<or> match_ex_table P C (pc - n) xt = None"
by(induct xt)(auto simp add: match_ex_entry split: split_if_asm)
lemma match_ex_table_shift_pc_None:
"pc \<ge> n \<Longrightarrow> match_ex_table P C pc (shift n xt) = None \<longleftrightarrow> match_ex_table P C (pc - n) xt = None"
by(simp add: match_ex_table_shift_eq_None_conv)
lemma match_ex_table_shift_eq_Some_conv [simp]:
"match_ex_table P C pc (shift n xt) = \<lfloor>(pc', d)\<rfloor> \<longleftrightarrow>
pc \<ge> n \<and> pc' \<ge> n \<and> match_ex_table P C (pc - n) xt = \<lfloor>(pc' - n, d)\<rfloor>"
by(induct xt)(auto simp add: match_ex_entry split: split_if_asm)
lemma match_ex_table_shift:
"match_ex_table P C pc xt = \<lfloor>(pc', d)\<rfloor> \<Longrightarrow> match_ex_table P C (n + pc) (shift n xt) = \<lfloor>(n + pc', d)\<rfloor>"
by(simp add: match_ex_table_shift_eq_Some_conv)
lemma match_ex_table_shift_pcD:
"match_ex_table P C pc (shift n xt) = \<lfloor>(pc', d)\<rfloor> \<Longrightarrow> pc \<ge> n \<and> pc' \<ge> n \<and> match_ex_table P C (pc - n) xt = \<lfloor>(pc' - n, d)\<rfloor>"
by(simp add: match_ex_table_shift_eq_Some_conv)
lemma match_ex_table_pcsD: "match_ex_table P C pc xt = \<lfloor>(pc', D)\<rfloor> \<Longrightarrow> pc \<in> pcs xt"
by(induct xt)(auto split: split_if_asm simp add: match_ex_entry)
definition stack_xlift :: "nat \<Rightarrow> ex_table \<Rightarrow> ex_table"
where "stack_xlift n xt \<equiv> map (\<lambda>(from,to,C,handler,depth). (from, to, C, handler, n + depth)) xt"
lemma stack_xlift_0 [simp]: "stack_xlift 0 xt = xt"
by(induct xt, auto simp add: stack_xlift_def)
lemma stack_xlift_Nil [simp]: "stack_xlift n [] = []"
by(simp add: stack_xlift_def)
lemma stack_xlift_Cons_tuple [simp]:
"stack_xlift n ((from, to, C, handler, depth) # xt) = (from, to, C, handler, depth + n) # stack_xlift n xt"
by(simp add: stack_xlift_def)
lemma stack_xlift_append [simp]: "stack_xlift n (xt @ xt') = stack_xlift n xt @ stack_xlift n xt'"
by(simp add: stack_xlift_def)
lemma stack_xlift_stack_xlift [simp]: "stack_xlift n (stack_xlift m xt) = stack_xlift (n + m) xt"
by(simp add: stack_xlift_def split_def)
lemma fixes e :: "'addr expr1" and es :: "'addr expr1 list"
shows stack_xlift_compxE2: "stack_xlift n (compxE2 e pc d) = compxE2 e pc (n + d)"
and stack_xlift_compxEs2: "stack_xlift n (compxEs2 es pc d) = compxEs2 es pc (n + d)"
by(induct e and es arbitrary: d pc and d pc rule: compE2.induct compEs2.induct)
(auto simp add: shift_compxE2 simp del: compxE2_size_convs)
lemma compxE2_stack_xlift_convs [simp]: "d > 0 \<Longrightarrow> compxE2 e pc d = stack_xlift d (compxE2 e pc 0)"
and compxEs2_stack_xlift_convs [simp]: "d > 0 \<Longrightarrow> compxEs2 es pc d = stack_xlift d (compxEs2 es pc 0)"
by(simp_all add: stack_xlift_compxE2 stack_xlift_compxEs2)
lemma stack_xlift_shift [simp]: "stack_xlift d (shift n xt) = shift n (stack_xlift d xt)"
by(induct xt)(auto)
lemma pcs_stack_xlift_conv [simp]: "pcs (stack_xlift n xt) = pcs xt"
by(auto simp add: pcs_def stack_xlift_def)
lemma match_ex_table_stack_xlift_eq_None_conv [simp]:
"match_ex_table P C pc (stack_xlift d xt) = None \<longleftrightarrow> match_ex_table P C pc xt = None"
by(induct xt)(auto simp add: match_ex_entry)
lemma match_ex_table_stack_xlift_eq_Some_conv [simp]:
"match_ex_table P C pc (stack_xlift n xt) = \<lfloor>(pc', d)\<rfloor> \<longleftrightarrow> d \<ge> n \<and> match_ex_table P C pc xt = \<lfloor>(pc', d - n)\<rfloor>"
by(induct xt)(auto simp add: match_ex_entry)
lemma match_ex_table_stack_xliftD:
"match_ex_table P C pc (stack_xlift n xt) = \<lfloor>(pc', d)\<rfloor> \<Longrightarrow> d \<ge> n \<and> match_ex_table P C pc xt = \<lfloor>(pc', d - n)\<rfloor>"
by(simp)
lemma match_ex_table_stack_xlift:
"match_ex_table P C pc xt = \<lfloor>(pc', d)\<rfloor> \<Longrightarrow> match_ex_table P C pc (stack_xlift n xt) = \<lfloor>(pc', n + d)\<rfloor>"
by simp
lemma pcs_stack_xlift: "pcs (stack_xlift n xt) = pcs xt"
by(auto simp add: stack_xlift_def pcs_def)
lemma match_ex_table_None_append [simp]:
"match_ex_table P C pc xt = None
\<Longrightarrow> match_ex_table P C pc (xt @ xt') = match_ex_table P C pc xt'"
by(induct xt, auto)
lemma match_ex_table_Some_append [simp]:
"match_ex_table P C pc xt = \<lfloor>(pc', d)\<rfloor> \<Longrightarrow> match_ex_table P C pc (xt @ xt') = \<lfloor>(pc', d)\<rfloor>"
by(induct xt)(auto)
lemma match_ex_table_append:
"match_ex_table P C pc (xt @ xt') = (case match_ex_table P C pc xt of None \<Rightarrow> match_ex_table P C pc xt'
| Some pcd \<Rightarrow> Some pcd)"
by(auto)
lemma match_ex_table_pc_length_compE2:
"match_ex_table P a pc (compxE2 e pc' d) = \<lfloor>pcd\<rfloor> \<Longrightarrow> pc' \<le> pc \<and> pc < length (compE2 e) + pc'"
and match_ex_table_pc_length_compEs2:
"match_ex_table P a pc (compxEs2 es pc' d) = \<lfloor>pcd\<rfloor> \<Longrightarrow> pc' \<le> pc \<and> pc < length (compEs2 es) + pc'"
using pcs_subset by(cases pcd, fastforce dest!: match_ex_table_pcsD)+
lemma match_ex_table_compxE2_shift_conv:
"f > 0 \<Longrightarrow> match_ex_table P C pc (compxE2 e f d) = \<lfloor>(pc', d')\<rfloor> \<longleftrightarrow> pc \<ge> f \<and> pc' \<ge> f \<and> match_ex_table P C (pc - f) (compxE2 e 0 d) = \<lfloor>(pc' - f, d')\<rfloor>"
by simp
lemma match_ex_table_compxEs2_shift_conv:
"f > 0 \<Longrightarrow> match_ex_table P C pc (compxEs2 es f d) = \<lfloor>(pc', d')\<rfloor> \<longleftrightarrow> pc \<ge> f \<and> pc' \<ge> f \<and> match_ex_table P C (pc - f) (compxEs2 es 0 d) = \<lfloor>(pc' - f, d')\<rfloor>"
by(simp add: compxEs2_size_convs)
lemma match_ex_table_compxE2_stack_conv:
"d > 0 \<Longrightarrow> match_ex_table P C pc (compxE2 e 0 d) = \<lfloor>(pc', d')\<rfloor> \<longleftrightarrow> d' \<ge> d \<and> match_ex_table P C pc (compxE2 e 0 0) = \<lfloor>(pc', d' - d)\<rfloor>"
by simp
lemma match_ex_table_compxEs2_stack_conv:
"d > 0 \<Longrightarrow> match_ex_table P C pc (compxEs2 es 0 d) = \<lfloor>(pc', d')\<rfloor> \<longleftrightarrow> d' \<ge> d \<and> match_ex_table P C pc (compxEs2 es 0 0) = \<lfloor>(pc', d' - d)\<rfloor>"
by(simp add: compxEs2_stack_xlift_convs)
lemma fixes e :: "'addr expr1" and es :: "'addr expr1 list"
shows match_ex_table_compxE2_not_same: "match_ex_table P C pc (compxE2 e n d) = \<lfloor>(pc', d')\<rfloor> \<Longrightarrow> pc \<noteq> pc'"
and match_ex_table_compxEs2_not_same:"match_ex_table P C pc (compxEs2 es n d) = \<lfloor>(pc', d')\<rfloor> \<Longrightarrow> pc \<noteq> pc'"
apply(induct e n d and es n d rule: compxE2_compxEs2_induct)
apply(auto simp add: match_ex_table_append match_ex_entry simp del: compxE2_size_convs compxEs2_size_convs compxE2_stack_xlift_convs compxEs2_stack_xlift_convs split: split_if_asm)
done
end
|
This blonde beauty certainly knows how to be her number one seller! They have already been seen at numerous fashion events like the Givenchy show in New York, where they mingled with Vogue editor-in-chief (and possible wedding guest? But this blonde bride-to-be is no stranger to being paired with successful men.
|
theory L4_Protocol_Flags
imports Simple_Firewall.L4_Protocol
begin
section\<open>Matching TCP Flags\<close>
(*man iptables-extensions, [!] --tcp-flags mask comp*)
datatype ipt_tcp_flags = TCP_Flags "tcp_flag set" \<comment> \<open>mask\<close>
"tcp_flag set" \<comment> \<open>comp\<close>
(*--syn: Only match TCP packets with the SYN bit set and the ACK,RST and FIN bits cleared. [...] It is equivalent to --tcp-flags SYN,RST,ACK,FIN SYN.*)
definition ipt_tcp_syn :: "ipt_tcp_flags" where
"ipt_tcp_syn \<equiv> TCP_Flags {TCP_SYN,TCP_RST,TCP_ACK,TCP_FIN} {TCP_SYN}"
fun match_tcp_flags :: "ipt_tcp_flags \<Rightarrow> tcp_flag set \<Rightarrow> bool" where
"match_tcp_flags (TCP_Flags fmask c) flags \<longleftrightarrow> (flags \<inter> fmask) = c"
lemma "match_tcp_flags ipt_tcp_syn {TCP_SYN, TCP_URG, TCP_PSH}" by eval
lemma match_tcp_flags_nomatch: "\<not> c \<subseteq> fmask \<Longrightarrow> \<not> match_tcp_flags (TCP_Flags fmask c) pkt" by auto
definition ipt_tcp_flags_NoMatch :: "ipt_tcp_flags" where
"ipt_tcp_flags_NoMatch \<equiv> TCP_Flags {} {TCP_SYN}"
lemma ipt_tcp_flags_NoMatch: "\<not> match_tcp_flags ipt_tcp_flags_NoMatch pkt" by(simp add: ipt_tcp_flags_NoMatch_def)
definition ipt_tcp_flags_Any :: ipt_tcp_flags where
"ipt_tcp_flags_Any \<equiv> TCP_Flags {} {}"
lemma ipt_tcp_flags_Any_isUNIV: "fmask = {} \<and> c = {} \<longleftrightarrow> (\<forall>pkt. match_tcp_flags (TCP_Flags fmask c) pkt)" by auto
fun match_tcp_flags_conjunct :: "ipt_tcp_flags \<Rightarrow> ipt_tcp_flags \<Rightarrow> ipt_tcp_flags" where
"match_tcp_flags_conjunct (TCP_Flags fmask1 c1) (TCP_Flags fmask2 c2) = (
if c1 \<subseteq> fmask1 \<and> c2 \<subseteq> fmask2 \<and> fmask1 \<inter> fmask2 \<inter> c1 = fmask1 \<inter> fmask2 \<inter> c2
then (TCP_Flags (fmask1 \<union> fmask2) (c1 \<union> c2))
else ipt_tcp_flags_NoMatch)"
lemma match_tcp_flags_conjunct: "match_tcp_flags (match_tcp_flags_conjunct f1 f2) pkt \<longleftrightarrow> match_tcp_flags f1 pkt \<and> match_tcp_flags f2 pkt"
apply(cases f1, cases f2, simp)
apply(rename_tac fmask1 c1 fmask2 c2)
apply(intro conjI impI)
apply(elim conjE)
apply blast
apply(simp add: ipt_tcp_flags_NoMatch)
apply fast
done
declare match_tcp_flags_conjunct.simps[simp del]
text\<open>Same as @{const match_tcp_flags_conjunct}, but returns @{const None} if result cannot match anyway\<close>
definition match_tcp_flags_conjunct_option :: "ipt_tcp_flags \<Rightarrow> ipt_tcp_flags \<Rightarrow> ipt_tcp_flags option" where
"match_tcp_flags_conjunct_option f1 f2 = (case match_tcp_flags_conjunct f1 f2 of (TCP_Flags fmask c) \<Rightarrow> if c \<subseteq> fmask then Some (TCP_Flags fmask c) else None)"
lemma "match_tcp_flags_conjunct_option ipt_tcp_syn (TCP_Flags {TCP_RST,TCP_ACK} {TCP_RST}) = None" by eval
lemma match_tcp_flags_conjunct_option_Some: "match_tcp_flags_conjunct_option f1 f2 = Some f3 \<Longrightarrow>
match_tcp_flags f1 pkt \<and> match_tcp_flags f2 pkt \<longleftrightarrow> match_tcp_flags f3 pkt"
apply(simp add: match_tcp_flags_conjunct_option_def split: ipt_tcp_flags.split_asm if_split_asm)
using match_tcp_flags_conjunct by blast
lemma match_tcp_flags_conjunct_option_None: "match_tcp_flags_conjunct_option f1 f2 = None \<Longrightarrow>
\<not>(match_tcp_flags f1 pkt \<and> match_tcp_flags f2 pkt)"
apply(simp add: match_tcp_flags_conjunct_option_def split: ipt_tcp_flags.split_asm if_split_asm)
using match_tcp_flags_conjunct match_tcp_flags_nomatch by metis
lemma match_tcp_flags_conjunct_option: "(case match_tcp_flags_conjunct_option f1 f2 of None \<Rightarrow> False | Some f3 \<Rightarrow> match_tcp_flags f3 pkt) \<longleftrightarrow> match_tcp_flags f1 pkt \<and> match_tcp_flags f2 pkt"
apply(simp split: option.split)
using match_tcp_flags_conjunct_option_Some match_tcp_flags_conjunct_option_None by blast
fun ipt_tcp_flags_equal :: "ipt_tcp_flags \<Rightarrow> ipt_tcp_flags \<Rightarrow> bool" where
"ipt_tcp_flags_equal (TCP_Flags fmask1 c1) (TCP_Flags fmask2 c2) = (
if c1 \<subseteq> fmask1 \<and> c2 \<subseteq> fmask2
then c1 = c2 \<and> fmask1 = fmask2
else (\<not> c1 \<subseteq> fmask1) \<and> (\<not> c2 \<subseteq> fmask2))"
context
begin
private lemma funny_set_falg_fmask_helper: "c2 \<subseteq> fmask2 \<Longrightarrow> (c1 = c2 \<and> fmask1 = fmask2) = (\<forall>pkt. (pkt \<inter> fmask1 = c1) = (pkt \<inter> fmask2 = c2))"
apply rule
apply presburger
apply(subgoal_tac "fmask1 = fmask2")
apply blast
(*"e": Try this: by (metis Diff_Compl Diff_eq Int_lower2 Un_Diff_Int compl_sup disjoint_eq_subset_Compl inf_assoc inf_commute inf_sup_absorb) (> 1.0 s, timed out).
Isar proof (300 ms):*)
proof -
assume a1: "c2 \<subseteq> fmask2"
assume a2: "\<forall>pkt. (pkt \<inter> fmask1 = c1) = (pkt \<inter> fmask2 = c2)"
have f3: "\<And>A Aa. (A::'a set) - - Aa = Aa - - A"
by (simp add: inf_commute)
have f4: "\<And>A Aa. (A::'a set) - - (- Aa) = A - Aa"
by simp
have f5: "\<And>A Aa Ab. (A::'a set) - - Aa - - Ab = A - - (Aa - - Ab)"
by blast
have f6: "\<And>A Aa. (A::'a set) - (- A - Aa) = A"
by fastforce
have f7: "\<And>A Aa. - (A::'a set) - - Aa = Aa - A"
using f4 f3 by presburger
have f8: "\<And>A Aa. - (A::'a set) = - (A - Aa) - (A - - Aa)"
by blast
have f9: "c1 = - (- c1)"
by blast
have f10: "\<And>A. A - c1 - c1 = A - c1"
by blast
have "\<And>A. A - - (fmask1 - - fmask2) = c2 \<or> A - - fmask1 \<noteq> c1"
using f6 f5 a2 by (metis (no_types) Diff_Compl)
hence f11: "\<And>A. - A - - (fmask1 - - fmask2) = c2 \<or> fmask1 - A \<noteq> c1"
using f7 by meson
have "c2 - fmask2 = {}"
using a1 by force
hence f12: "- c2 - (fmask2 - c2) = - fmask2"
by blast
hence "fmask2 - - c2 = c2"
by blast
hence f13: "fmask1 - - c2 = c1"
using f3 a2 by simp
hence f14: "c1 = c2"
using f11 by blast
hence f15: "fmask2 - (fmask1 - c1) = c1"
using f13 f10 f9 f8 f7 f3 a2 by (metis Diff_Compl)
have "fmask1 - (fmask2 - c1) = c1"
using f14 f12 f10 f9 f8 f4 f3 a2 by (metis Diff_Compl)
thus "fmask1 = fmask2"
using f15 by blast
qed
lemma ipt_tcp_flags_equal: "ipt_tcp_flags_equal f1 f2 \<longleftrightarrow> (\<forall>pkt. match_tcp_flags f1 pkt = match_tcp_flags f2 pkt)"
apply(cases f1, cases f2, simp)
apply(rename_tac fmask1 c1 fmask2 c2)
apply(intro conjI impI)
using funny_set_falg_fmask_helper apply metis
apply blast
done
end
declare ipt_tcp_flags_equal.simps[simp del]
end
|
[STATEMENT]
lemma empty_notin_wf_dlverts: "wf_dlverts t \<Longrightarrow> [] \<notin> dverts t"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. wf_dlverts t \<Longrightarrow> [] \<notin> dverts t
[PROOF STEP]
by(induction t) auto
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.