text
stringlengths 0
3.34M
|
---|
## Plotting Sierpinski triangle. aev 4/1/17
## ord - order, fn - file name, ttl - plot title, clr - color
pSierpinskiT <- function(ord, fn="", ttl="", clr="navy") {
m=640; abbr="STR"; dftt="Sierpinski triangle";
n=2^ord; M <- matrix(c(0), ncol=n, nrow=n, byrow=TRUE);
cat(" *** START", abbr, date(), "\n");
if(fn=="") {pf=paste0(abbr,"o", ord)} else {pf=paste0(fn, ".png")};
if(ttl!="") {dftt=ttl}; ttl=paste0(dftt,", order ", ord);
cat(" *** Plot file:", pf,".png", "title:", ttl, "\n");
for(y in 1:n) {
for(x in 1:n) {
if(bitwAnd(x, y)==0) {M[x,y]=1}
##if(bitwAnd(x, y)>0) {M[x,y]=1} ## Try this for "reversed" ST
}}
plotmat(M, pf, clr, ttl);
cat(" *** END", abbr, date(), "\n");
}
## Executing:
pSierpinskiT(6,,,"red");
pSierpinskiT(8);
|
= SMS Zrínyi =
|
= = = Private property = = =
|
module nabarundeka.Odds
import Evens
import Intro
data IsOdd : (n : Nat) -> Type where
OneOdd : IsOdd 1
SSOdd : (n : Nat) -> IsOdd n -> IsOdd (S (S n))
threeOdd : IsOdd 3
threeOdd = SSOdd 1 OneOdd
twoNotOdd : IsOdd 2 -> Void
twoNotOdd OneOdd impossible
twoNotOdd (SSOdd Z OneOdd) impossible
twoNotOdd (SSOdd Z (SSOdd _ _)) impossible
nOddSnEven : (n : Nat) -> IsOdd n -> IsEven (S n)
nOddSnEven (S Z) OneOdd = SSEven 0 ZEven
nOddSnEven (S (S n)) (SSOdd n x) = SSEven (S n) (nOddSnEven n x)
nEvenSnOdd : (n : Nat) -> IsEven n -> IsOdd (S n)
nEvenSnOdd Z ZEven = OneOdd
nEvenSnOdd (S (S n)) (SSEven n x) = SSOdd (S n) (nEvenSnOdd n x)
nOddOrEven : (n : Nat) -> Either (IsEven n) (IsOdd n)
nOddOrEven Z = Left ZEven
nOddOrEven (S n) = case (nOddOrEven n) of
(Left l) => Right (nEvenSnOdd n l)
(Right r) => Left (nOddSnEven n r)
nNotOddEven : (n: Nat) -> (IsOdd n) -> (IsEven n) -> Void
nNotOddEven Z OneOdd ZEven impossible
nNotOddEven (S Z) OneOdd ZEven impossible
nNotOddEven (S (S n)) (SSOdd n x) (SSEven n y) = nNotOddEven n x y
nNotOddEvenBoth : (n : Nat) -> (IsOdd n, IsEven n) -> Void
nNotOddEvenBoth n (x,y) = nNotOddEven n x y
sumOddOdd : (n : Nat) -> (m : Nat) -> (IsOdd n) -> (IsOdd m) -> IsEven (add n m)
sumOddOdd (S Z) m OneOdd x = nOddSnEven m x
sumOddOdd (S (S n)) m (SSOdd n x) y = SSEven (add n m) (sumOddOdd n m x y)
apNat : (f: Nat -> Nat) -> (n: Nat) -> (m: Nat) -> n = m -> f n = f m
apNat f m m Refl = Refl
succOddDivByTwo : (n : Nat) -> IsOdd n -> (k : Nat ** (S(double k)) = n)
succOddDivByTwo (S Z) OneOdd = (Z ** Refl)
succOddDivByTwo (S (S k)) (SSOdd k x) = step where
step = case (succOddDivByTwo k x) of
(m ** pf) => ((S m) ** apNat (\l=> S (S l)) (S(double m)) k pf)
|
Coding. Learning. Engagement. Great websites.
This course will ask you to learn and adapt to new technologies, while also thinking about design and content creation. By its end, you should feel comfortable making websites from the ground-up, and utilizing your peers as learning tools in this creative community.
Some topics will lean more technical in nature, while others (albeit fewer) will be more design-based. Just as the content focus will shift, so too will the work amount. Some topics, especially those where new ideas are being introduced, have a heavier workload. The goal of this is to make you practice with these new technologies and techniques, while other areas will slow down and allow you to tinker at a more exploratory pace.
The main goal of this course is to allow you an opportunity to become comfortable with technologies used in web development. Another is to get you thinking about web design and possibilities for content creation via the web. |
(*
* Copyright (C) 2014 NICTA
* All rights reserved.
*)
(* Author: David Cock - [email protected] *)
section \<open>Continuity\<close>
theory Continuity imports Healthiness begin
text \<open>We rely on one additional healthiness property, continuity, which is shown here seperately,
as its proof relies, in general, on healthiness. It is only relevant when a program appears
in an inductive context i.e.~inside a loop.\<close>
text \<open>A continuous transformer preserves limits (or the suprema of ascending chains).\<close>
definition bd_cts :: "'s trans \<Rightarrow> bool"
where "bd_cts t = (\<forall>M. (\<forall>i. (M i \<tturnstile> M (Suc i)) \<and> sound (M i)) \<longrightarrow>
(\<exists>b. \<forall>i. bounded_by b (M i)) \<longrightarrow>
t (Sup_exp (range M)) = Sup_exp (range (t o M)))"
lemma bd_ctsD:
"\<lbrakk> bd_cts t; \<And>i. M i \<tturnstile> M (Suc i); \<And>i. sound (M i); \<And>i. bounded_by b (M i) \<rbrakk> \<Longrightarrow>
t (Sup_exp (range M)) = Sup_exp (range (t o M))"
unfolding bd_cts_def by(auto)
lemma bd_ctsI:
"(\<And>b M. (\<And>i. M i \<tturnstile> M (Suc i)) \<Longrightarrow> (\<And>i. sound (M i)) \<Longrightarrow> (\<And>i. bounded_by b (M i)) \<Longrightarrow>
t (Sup_exp (range M)) = Sup_exp (range (t o M))) \<Longrightarrow> bd_cts t"
unfolding bd_cts_def by(auto)
text \<open>A generalised property for transformers of transformers.\<close>
definition bd_cts_tr :: "('s trans \<Rightarrow> 's trans) \<Rightarrow> bool"
where "bd_cts_tr T = (\<forall>M. (\<forall>i. le_trans (M i) (M (Suc i)) \<and> feasible (M i)) \<longrightarrow>
equiv_trans (T (Sup_trans (M ` UNIV))) (Sup_trans ((T o M) ` UNIV)))"
lemma bd_cts_trD:
"\<lbrakk> bd_cts_tr T; \<And>i. le_trans (M i) (M (Suc i)); \<And>i. feasible (M i) \<rbrakk> \<Longrightarrow>
equiv_trans (T (Sup_trans (M ` UNIV))) (Sup_trans ((T o M) ` UNIV))"
by(simp add:bd_cts_tr_def)
lemma bd_cts_trI:
"(\<And>M. (\<And>i. le_trans (M i) (M (Suc i))) \<Longrightarrow> (\<And>i. feasible (M i)) \<Longrightarrow>
equiv_trans (T (Sup_trans (M ` UNIV))) (Sup_trans ((T o M) ` UNIV))) \<Longrightarrow> bd_cts_tr T"
by(simp add:bd_cts_tr_def)
subsection \<open>Continuity of Primitives\<close>
lemma cts_wp_Abort:
"bd_cts (wp (Abort::'s prog))"
proof -
have X: "range (\<lambda>(i::nat) (s::'s). 0) = {\<lambda>s. 0}" by(auto)
show ?thesis by(intro bd_ctsI, simp add:wp_eval o_def Sup_exp_def X)
qed
lemma cts_wp_Skip:
"bd_cts (wp Skip)"
by(rule bd_ctsI, simp add:wp_def Skip_def o_def)
lemma cts_wp_Apply:
"bd_cts (wp (Apply f))"
proof -
have X: "\<And>M s. {P (f s) |P. P \<in> range M} = {P s |P. P \<in> range (\<lambda>i s. M i (f s))}" by(auto)
show ?thesis by(intro bd_ctsI ext, simp add:wp_eval o_def Sup_exp_def X)
qed
lemma cts_wp_Bind:
fixes a::"'a \<Rightarrow> 's prog"
assumes ca: "\<And>s. bd_cts (wp (a (f s)))"
shows "bd_cts (wp (Bind f a))"
proof(rule bd_ctsI)
fix M::"nat \<Rightarrow> 's expect" and c::real
assume chain: "\<And>i. M i \<tturnstile> M (Suc i)" and sM: "\<And>i. sound (M i)"
and bM: "\<And>i. bounded_by c (M i)"
with bd_ctsD[OF ca]
have "\<And>s. wp (a (f s)) (Sup_exp (range M)) =
Sup_exp (range (wp (a (f s)) o M))"
by(auto)
moreover have "\<And>s. {fa s |fa. fa \<in> range (\<lambda>x. wp (a (f s)) (M x))} =
{fa s |fa. fa \<in> range (\<lambda>x s. wp (a (f s)) (M x) s)}"
by(auto)
ultimately show "wp (Bind f a) (Sup_exp (range M)) =
Sup_exp (range (wp (Bind f a) \<circ> M))"
by(simp add:wp_eval o_def Sup_exp_def)
qed
text \<open>The first nontrivial proof. We transform the suprema into limits, and appeal to the
continuity of the underlying operation (here infimum). This is typical of the remainder of the
nonrecursive elements.\<close>
lemma cts_wp_DC:
fixes a b::"'s prog"
assumes ca: "bd_cts (wp a)"
and cb: "bd_cts (wp b)"
and ha: "healthy (wp a)"
and hb: "healthy (wp b)"
shows "bd_cts (wp (a \<Sqinter> b))"
proof(rule bd_ctsI, rule antisym)
fix M::"nat \<Rightarrow> 's expect" and c::real
assume chain: "\<And>i. M i \<tturnstile> M (Suc i)" and sM: "\<And>i. sound (M i)"
and bM: "\<And>i. bounded_by c (M i)"
from ha hb have hab: "healthy (wp (a \<Sqinter> b))" by(rule healthy_intros)
from bM have leSup: "\<And>i. M i \<tturnstile> Sup_exp (range M)" by(auto intro:Sup_exp_upper)
from sM bM have sSup: "sound (Sup_exp (range M))" by(auto intro:Sup_exp_sound)
show "Sup_exp (range (wp (a \<Sqinter> b) \<circ> M)) \<tturnstile> wp (a \<Sqinter> b) (Sup_exp (range M))"
proof(rule Sup_exp_least, clarsimp, rule le_funI)
fix i s
from mono_transD[OF healthy_monoD[OF hab]] leSup sM sSup
have "wp (a \<Sqinter> b) (M i) \<tturnstile> wp (a \<Sqinter> b) (Sup_exp (range M))" by(auto)
thus "wp (a \<Sqinter> b) (M i) s \<le> wp (a \<Sqinter> b) (Sup_exp (range M)) s" by(auto)
from hab sSup have "sound (wp (a \<Sqinter> b) (Sup_exp (range M)))" by(auto)
thus "nneg (wp (a \<Sqinter> b) (Sup_exp (range M)))" by(auto)
qed
from sM bM ha have "\<And>i. bounded_by c (wp a (M i))" by(auto)
hence baM: "\<And>i s. wp a (M i) s \<le> c" by(auto)
from sM bM hb have "\<And>i. bounded_by c (wp b (M i))" by(auto)
hence bbM: "\<And>i s. wp b (M i) s \<le> c" by(auto)
show "wp (a \<Sqinter> b) (Sup_exp (range M)) \<tturnstile> Sup_exp (range (wp (a \<Sqinter> b) \<circ> M))"
proof(simp add:wp_eval o_def, rule le_funI)
fix s::'s
from bd_ctsD[OF ca, of M, OF chain sM bM] bd_ctsD[OF cb, of M, OF chain sM bM]
have "min (wp a (Sup_exp (range M)) s) (wp b (Sup_exp (range M)) s) =
min (Sup_exp (range (wp a o M)) s) (Sup_exp (range (wp b o M)) s)" by(simp)
also {
have "{f s |f. f \<in> range (\<lambda>x. wp a (M x))} = range (\<lambda>i. wp a (M i) s)"
"{f s |f. f \<in> range (\<lambda>x. wp b (M x))} = range (\<lambda>i. wp b (M i) s)"
by(auto)
hence "min (Sup_exp (range (wp a o M)) s) (Sup_exp (range (wp b o M)) s) =
min (Sup (range (\<lambda>i. wp a (M i) s))) (Sup (range (\<lambda>i. wp b (M i) s)))"
by(simp add:Sup_exp_def o_def)
}
also {
have "(\<lambda>i. wp a (M i) s) \<longlonglongrightarrow> Sup (range (\<lambda>i. wp a (M i) s))"
proof(rule increasing_LIMSEQ)
fix n
from mono_transD[OF healthy_monoD, OF ha] sM chain
show "wp a (M n) s \<le> wp a (M (Suc n)) s" by(auto intro:le_funD)
from baM show "wp a (M n) s \<le> Sup (range (\<lambda>i. wp a (M i) s))"
by(intro cSup_upper bdd_aboveI, auto)
fix e::real assume pe: "0 < e"
from baM have cSup: "Sup (range (\<lambda>i. wp a (M i) s)) \<in> closure (range (\<lambda>i. wp a (M i) s))"
by(blast intro:closure_contains_Sup)
with pe obtain y where yin: "y \<in> (range (\<lambda>i. wp a (M i) s))"
and dy: "dist y (Sup (range (\<lambda>i. wp a (M i) s))) < e"
by(blast dest:iffD1[OF closure_approachable])
from yin obtain i where "y = wp a (M i) s" by(auto)
with dy have "dist (wp a (M i) s) (Sup (range (\<lambda>i. wp a (M i) s))) < e"
by(simp)
moreover from baM have "wp a (M i) s \<le> Sup (range (\<lambda>i. wp a (M i) s))"
by(intro cSup_upper bdd_aboveI, auto)
ultimately have "Sup (range (\<lambda>i. wp a (M i) s)) \<le> wp a (M i) s + e"
by(simp add:dist_real_def)
thus "\<exists>i. Sup (range (\<lambda>i. wp a (M i) s)) \<le> wp a (M i) s + e" by(auto)
qed
moreover
have "(\<lambda>i. wp b (M i) s) \<longlonglongrightarrow> Sup (range (\<lambda>i. wp b (M i) s))"
proof(rule increasing_LIMSEQ)
fix n
from mono_transD[OF healthy_monoD, OF hb] sM chain
show "wp b (M n) s \<le> wp b (M (Suc n)) s" by(auto intro:le_funD)
from bbM show "wp b (M n) s \<le> Sup (range (\<lambda>i. wp b (M i) s))"
by(intro cSup_upper bdd_aboveI, auto)
fix e::real assume pe: "0 < e"
from bbM have cSup: "Sup (range (\<lambda>i. wp b (M i) s)) \<in> closure (range (\<lambda>i. wp b (M i) s))"
by(blast intro:closure_contains_Sup)
with pe obtain y where yin: "y \<in> (range (\<lambda>i. wp b (M i) s))"
and dy: "dist y (Sup (range (\<lambda>i. wp b (M i) s))) < e"
by(blast dest:iffD1[OF closure_approachable])
from yin obtain i where "y = wp b (M i) s" by(auto)
with dy have "dist (wp b (M i) s) (Sup (range (\<lambda>i. wp b (M i) s))) < e"
by(simp)
moreover from bbM have "wp b (M i) s \<le> Sup (range (\<lambda>i. wp b (M i) s))"
by(intro cSup_upper bdd_aboveI, auto)
ultimately have "Sup (range (\<lambda>i. wp b (M i) s)) \<le> wp b (M i) s + e"
by(simp add:dist_real_def)
thus "\<exists>i. Sup (range (\<lambda>i. wp b (M i) s)) \<le> wp b (M i) s + e" by(auto)
qed
ultimately have "(\<lambda>i. min (wp a (M i) s) (wp b (M i) s)) \<longlonglongrightarrow>
min (Sup (range (\<lambda>i. wp a (M i) s))) (Sup (range (\<lambda>i. wp b (M i) s)))"
by(rule tendsto_min)
moreover have "bdd_above (range (\<lambda>i. min (wp a (M i) s) (wp b (M i) s)))"
proof(intro bdd_aboveI, clarsimp)
fix i
have "min (wp a (M i) s) (wp b (M i) s) \<le> wp a (M i) s" by(auto)
also {
from ha sM bM have "bounded_by c (wp a (M i))" by(auto)
hence "wp a (M i) s \<le> c" by(auto)
}
finally show "min (wp a (M i) s) (wp b (M i) s) \<le> c" .
qed
ultimately
have "min (Sup (range (\<lambda>i. wp a (M i) s))) (Sup (range (\<lambda>i. wp b (M i) s))) \<le>
Sup (range (\<lambda>i. min (wp a (M i) s) (wp b (M i) s)))"
by(blast intro:LIMSEQ_le_const2 cSup_upper min.mono[OF baM bbM])
}
also {
have "range (\<lambda>i. min (wp a (M i) s) (wp b (M i) s)) =
{f s |f. f \<in> range (\<lambda>i s. min (wp a (M i) s) (wp b (M i) s))}"
by(auto)
hence "Sup (range (\<lambda>i. min (wp a (M i) s) (wp b (M i) s))) =
Sup_exp (range (\<lambda>i s. min (wp a (M i) s) (wp b (M i) s))) s"
by (simp add: Sup_exp_def cong del: SUP_cong_simp)
}
finally show "min (wp a (Sup_exp (range M)) s) (wp b (Sup_exp (range M)) s) \<le>
Sup_exp (range (\<lambda>i s. min (wp a (M i) s) (wp b (M i) s))) s" .
qed
qed
lemma cts_wp_Seq:
fixes a b::"'s prog"
assumes ca: "bd_cts (wp a)"
and cb: "bd_cts (wp b)"
and hb: "healthy (wp b)"
shows "bd_cts (wp (a ;; b))"
proof(rule bd_ctsI, simp add:o_def wp_eval)
fix M::"nat \<Rightarrow> 's expect" and c::real
assume chain: "\<And>i. M i \<tturnstile> M (Suc i)" and sM: "\<And>i. sound (M i)"
and bM: "\<And>i. bounded_by c (M i)"
hence "wp a (wp b (Sup_exp (range M))) = wp a (Sup_exp (range (wp b o M)))"
by(subst bd_ctsD[OF cb], auto)
also {
from sM hb have "\<And>i. sound ((wp b o M) i)" by(auto)
moreover from chain sM
have "\<And>i. (wp b o M) i \<tturnstile> (wp b o M) (Suc i)"
by(auto intro:mono_transD[OF healthy_monoD, OF hb])
moreover from sM bM hb have "\<And>i. bounded_by c ((wp b o M) i)" by(auto)
ultimately have "wp a (Sup_exp (range (wp b o M))) =
Sup_exp (range (wp a o (wp b o M)))"
by(subst bd_ctsD[OF ca], auto)
}
also have "Sup_exp (range (wp a o (wp b o M))) =
Sup_exp (range (\<lambda>i. wp a (wp b (M i))))"
by(simp add:o_def)
finally show "wp a (wp b (Sup_exp (range M))) =
Sup_exp (range (\<lambda>i. wp a (wp b (M i))))" .
qed
lemma cts_wp_PC:
fixes a b::"'s prog"
assumes ca: "bd_cts (wp a)"
and cb: "bd_cts (wp b)"
and ha: "healthy (wp a)"
and hb: "healthy (wp b)"
and up: "unitary p"
shows "bd_cts (wp (PC a p b))"
proof(rule bd_ctsI, rule ext, simp add:o_def wp_eval)
fix M::"nat \<Rightarrow> 's expect" and c::real and s::'s
assume chain: "\<And>i. M i \<tturnstile> M (Suc i)" and sM: "\<And>i. sound (M i)"
and bM: "\<And>i. bounded_by c (M i)"
from sM have "\<And>i. nneg (M i)" by(auto)
with bM have nc: "0 \<le> c" by(auto)
from chain sM bM have "wp a (Sup_exp (range M)) = Sup_exp (range (wp a o M))"
by(rule bd_ctsD[OF ca])
hence "wp a (Sup_exp (range M)) s = Sup_exp (range (wp a o M)) s"
by(simp)
also {
have "{f s |f. f \<in> range (\<lambda>x. wp a (M x))} = range (\<lambda>i. wp a (M i) s)"
by(auto)
hence "Sup_exp (range (wp a o M)) s = Sup (range (\<lambda>i. wp a (M i) s))"
by(simp add:Sup_exp_def o_def)
}
finally have "p s * wp a (Sup_exp (range M)) s =
p s * Sup (range (\<lambda>i. wp a (M i) s))" by(simp)
also have "... = Sup {p s * x |x. x \<in> range (\<lambda>i. wp a (M i) s)}"
proof(rule cSup_mult, blast, clarsimp)
from up show "0 \<le> p s" by(auto)
fix i
from sM bM ha have "bounded_by c (wp a (M i))" by(auto)
thus "wp a (M i) s \<le> c" by(auto)
qed
also {
have "{p s * x |x. x \<in> range (\<lambda>i. wp a (M i) s)} = range (\<lambda>i. p s * wp a (M i) s)"
by(auto)
hence "Sup {p s * x |x. x \<in> range (\<lambda>i. wp a (M i) s)} =
Sup (range (\<lambda>i. p s * wp a (M i) s))" by(simp)
}
finally have "p s * wp a (Sup_exp (range M)) s = Sup (range (\<lambda>i. p s * wp a (M i) s))" .
moreover {
from chain sM bM have "wp b (Sup_exp (range M)) = Sup_exp (range (wp b o M))"
by(rule bd_ctsD[OF cb])
hence "wp b (Sup_exp (range M)) s = Sup_exp (range (wp b o M)) s"
by(simp)
also {
have "{f s |f. f \<in> range (\<lambda>x. wp b (M x))} = range (\<lambda>i. wp b (M i) s)"
by(auto)
hence "Sup_exp (range (wp b o M)) s = Sup (range (\<lambda>i. wp b (M i) s))"
by(simp add:Sup_exp_def o_def)
}
finally have "(1 - p s) * wp b (Sup_exp (range M)) s =
(1 - p s) * Sup (range (\<lambda>i. wp b (M i) s))" by(simp)
also have "... = Sup {(1 - p s) * x |x. x \<in> range (\<lambda>i. wp b (M i) s)}"
proof(rule cSup_mult, blast, clarsimp)
from up show "0 \<le> 1 - p s"
by auto
fix i
from sM bM hb have "bounded_by c (wp b (M i))" by(auto)
thus "wp b (M i) s \<le> c" by(auto)
qed
also {
have "{(1 - p s) * x |x. x \<in> range (\<lambda>i. wp b (M i) s)} =
range (\<lambda>i. (1 - p s) * wp b (M i) s)"
by(auto)
hence "Sup {(1 - p s) * x |x. x \<in> range (\<lambda>i. wp b (M i) s)} =
Sup (range (\<lambda>i. (1 - p s) * wp b (M i) s))" by(simp)
}
finally have "(1 - p s) * wp b (Sup_exp (range M)) s =
Sup (range (\<lambda>i. (1 - p s) * wp b (M i) s))" .
}
ultimately
have "p s * wp a (Sup_exp (range M)) s + (1 - p s) * wp b (Sup_exp (range M)) s =
Sup (range (\<lambda>i. p s * wp a (M i) s)) + Sup (range (\<lambda>i. (1 - p s) * wp b (M i) s))"
by(simp)
also {
from bM sM ha have "\<And>i. bounded_by c (wp a (M i))" by(auto)
hence "\<And>i. wp a (M i) s \<le> c" by(auto)
moreover from up have "0 \<le> p s" by(auto)
ultimately have "\<And>i. p s * wp a (M i) s \<le> p s * c" by(auto intro:mult_left_mono)
also from up nc have "p s * c \<le> 1 * c" by(blast intro:mult_right_mono)
also have "... = c" by(simp)
finally have baM: "\<And>i. p s * wp a (M i) s \<le> c" .
have lima: "(\<lambda>i. p s * wp a (M i) s) \<longlonglongrightarrow> Sup (range (\<lambda>i. p s * wp a (M i) s))"
proof(rule increasing_LIMSEQ)
fix n
from sM chain healthy_monoD[OF ha] have "wp a (M n) \<tturnstile> wp a (M (Suc n))"
by(auto)
with up show "p s * wp a (M n) s \<le> p s * wp a (M (Suc n)) s"
by(blast intro:mult_left_mono)
from baM show "p s * wp a (M n) s \<le> Sup (range (\<lambda>i. p s * wp a (M i) s))"
by(intro cSup_upper bdd_aboveI, auto)
next
fix e::real
assume pe: "0 < e"
from baM have "Sup (range (\<lambda>i. p s * wp a (M i) s)) \<in>
closure (range (\<lambda>i. p s * wp a (M i) s))"
by(blast intro:closure_contains_Sup)
thm closure_approachable
with pe obtain y where yin: "y \<in> range (\<lambda>i. p s * wp a (M i) s)"
and dy: "dist y (Sup (range (\<lambda>i. p s * wp a (M i) s))) < e"
by(blast dest:iffD1[OF closure_approachable])
from yin obtain i where "y = p s * wp a (M i) s" by(auto)
with dy have "dist (p s * wp a (M i) s) (Sup (range (\<lambda>i. p s * wp a (M i) s))) < e"
by(simp)
moreover from baM have "p s * wp a (M i) s \<le> Sup (range (\<lambda>i. p s * wp a (M i) s))"
by(intro cSup_upper bdd_aboveI, auto)
ultimately have "Sup (range (\<lambda>i. p s * wp a (M i) s)) \<le> p s * wp a (M i) s + e"
by(simp add:dist_real_def)
thus "\<exists>i. Sup (range (\<lambda>i. p s * wp a (M i) s)) \<le> p s * wp a (M i) s + e" by(auto)
qed
from bM sM hb have "\<And>i. bounded_by c (wp b (M i))" by(auto)
hence "\<And>i. wp b (M i) s \<le> c" by(auto)
moreover from up have "0 \<le> (1 - p s)"
by auto
ultimately have "\<And>i. (1 - p s) * wp b (M i) s \<le> (1 - p s) * c" by(auto intro:mult_left_mono)
also {
from up have "1 - p s \<le> 1" by(auto)
with nc have "(1 - p s) * c \<le> 1 * c" by(blast intro:mult_right_mono)
}
also have "1 * c = c" by(simp)
finally have bbM: "\<And>i. (1 - p s) * wp b (M i) s \<le> c" .
have limb: "(\<lambda>i. (1 - p s) * wp b (M i) s) \<longlonglongrightarrow> Sup (range (\<lambda>i. (1 - p s) * wp b (M i) s))"
proof(rule increasing_LIMSEQ)
fix n
from sM chain healthy_monoD[OF hb] have "wp b (M n) \<tturnstile> wp b (M (Suc n))"
by(auto)
moreover from up have "0 \<le> 1 - p s"
by auto
ultimately show "(1 - p s) * wp b (M n) s \<le> (1 - p s) * wp b (M (Suc n)) s"
by(blast intro:mult_left_mono)
from bbM show "(1 - p s) * wp b (M n) s \<le> Sup (range (\<lambda>i. (1 - p s) * wp b (M i) s))"
by(intro cSup_upper bdd_aboveI, auto)
next
fix e::real
assume pe: "0 < e"
from bbM have "Sup (range (\<lambda>i. (1 - p s) * wp b (M i) s)) \<in>
closure (range (\<lambda>i. (1 - p s) * wp b (M i) s))"
by(blast intro:closure_contains_Sup)
with pe obtain y where yin: "y \<in> range (\<lambda>i. (1 - p s) * wp b (M i) s)"
and dy: "dist y (Sup (range (\<lambda>i. (1 - p s) * wp b (M i) s))) < e"
by(blast dest:iffD1[OF closure_approachable])
from yin obtain i where "y = (1 - p s) * wp b (M i) s" by(auto)
with dy have "dist ((1 - p s) * wp b (M i) s)
(Sup (range (\<lambda>i. (1 - p s) * wp b (M i) s))) < e"
by(simp)
moreover from bbM
have "(1 - p s) * wp b (M i) s \<le> Sup (range (\<lambda>i. (1 - p s) * wp b (M i) s))"
by(intro cSup_upper bdd_aboveI, auto)
ultimately have "Sup (range (\<lambda>i. (1 - p s) * wp b (M i) s)) \<le> (1 - p s) * wp b (M i) s + e"
by(simp add:dist_real_def)
thus "\<exists>i. Sup (range (\<lambda>i. (1 - p s) * wp b (M i) s)) \<le> (1 - p s) * wp b (M i) s + e" by(auto)
qed
from lima limb have "(\<lambda>i. p s * wp a (M i) s + (1 - p s) * wp b (M i) s) \<longlonglongrightarrow>
Sup (range (\<lambda>i. p s * wp a (M i) s)) + Sup (range (\<lambda>i. (1 - p s) * wp b (M i) s))"
by(rule tendsto_add)
moreover from add_mono[OF baM bbM]
have "\<And>i. p s * wp a (M i) s + (1 - p s) * wp b (M i) s \<le>
Sup (range (\<lambda>i. p s * wp a (M i) s + (1 - p s) * wp b (M i) s))"
by(intro cSup_upper bdd_aboveI, auto)
ultimately have "Sup (range (\<lambda>i. p s * wp a (M i) s)) +
Sup (range (\<lambda>i. (1 - p s) * wp b (M i) s)) \<le>
Sup (range (\<lambda>i. p s * wp a (M i) s + (1 - p s) * wp b (M i) s))"
by(blast intro: LIMSEQ_le_const2)
}
also {
have "range (\<lambda>i. p s * wp a (M i) s + (1 - p s) * wp b (M i) s) =
{f s |f. f \<in> range (\<lambda>x s. p s * wp a (M x) s + (1 - p s) * wp b (M x) s)}"
by(auto)
hence "Sup (range (\<lambda>i. p s * wp a (M i) s + (1 - p s) * wp b (M i) s)) =
Sup_exp (range (\<lambda>x s. p s * wp a (M x) s + (1 - p s) * wp b (M x) s)) s"
by (simp add: Sup_exp_def cong del: SUP_cong_simp)
}
finally
have "p s * wp a (Sup_exp (range M)) s + (1 - p s) * wp b (Sup_exp (range M)) s \<le>
Sup_exp (range (\<lambda>i s. p s * wp a (M i) s + (1 - p s) * wp b (M i) s)) s" .
moreover
have "Sup_exp (range (\<lambda>i s. p s * wp a (M i) s + (1 - p s) * wp b (M i) s)) s \<le>
p s * wp a (Sup_exp (range M)) s + (1 - p s) * wp b (Sup_exp (range M)) s"
proof(rule le_funD[OF Sup_exp_least], clarsimp, rule le_funI)
fix i::nat and s::'s
from bM have leSup: "M i \<tturnstile> Sup_exp (range M)"
by(blast intro: Sup_exp_upper)
moreover from sM bM have sSup: "sound (Sup_exp (range M))"
by(auto intro:Sup_exp_sound)
moreover note healthy_monoD[OF ha] sM
ultimately have "wp a (M i) \<tturnstile> wp a (Sup_exp (range M))" by(auto)
hence "wp a (M i) s \<le> wp a (Sup_exp (range M)) s" by(auto)
moreover {
from leSup sSup healthy_monoD[OF hb] sM
have "wp b (M i) \<tturnstile> wp b (Sup_exp (range M))" by(auto)
hence "wp b (M i) s \<le> wp b (Sup_exp (range M)) s" by(auto)
}
moreover from up have "0 \<le> p s" "0 \<le> 1 - p s"
by auto
ultimately
show "p s * wp a (M i) s + (1 - p s) * wp b (M i) s \<le>
p s * wp a (Sup_exp (range M)) s + (1 - p s) * wp b (Sup_exp (range M)) s"
by(blast intro:add_mono mult_left_mono)
from sSup ha hb have "sound (wp a (Sup_exp (range M)))"
"sound (wp b (Sup_exp (range M)))"
by(auto)
hence "\<And>s. 0 \<le> wp a (Sup_exp (range M)) s" "\<And>s. 0 \<le> wp b (Sup_exp (range M)) s"
by(auto)
moreover from up have "\<And>s. 0 \<le> p s" "\<And>s. 0 \<le> 1 - p s"
by auto
ultimately show "nneg (\<lambda>c. p c * wp a (Sup_exp (range M)) c +
(1 - p c) * wp b (Sup_exp (range M)) c)"
by(blast intro:add_nonneg_nonneg mult_nonneg_nonneg)
qed
ultimately show "p s * wp a (Sup_exp (range M)) s + (1 - p s) * wp b (Sup_exp (range M)) s =
Sup_exp (range (\<lambda>x s. p s * wp a (M x) s + (1 - p s) * wp b (M x) s)) s"
by(auto)
qed
text \<open>Both set-based choice operators are only continuous for finite sets (probabilistic choice
\emph{can} be extended infinitely, but we have not done so). The proofs for both are inductive,
and rely on the above results on binary operators.\<close>
lemma SetPC_Bind:
"SetPC a p = Bind p (\<lambda>p. SetPC a (\<lambda>_. p))"
by(intro ext, simp add:SetPC_def Bind_def Let_def)
lemma SetPC_remove:
assumes nz: "p x \<noteq> 0" and n1: "p x \<noteq> 1"
and fsupp: "finite (supp p)"
shows "SetPC a (\<lambda>_. p) = PC (a x) (\<lambda>_. p x) (SetPC a (\<lambda>_. dist_remove p x))"
proof(intro ext, simp add:SetPC_def PC_def)
fix ab P s
from nz have "x \<in> supp p" by(simp add:supp_def)
hence "supp p = insert x (supp p - {x})" by(auto)
hence "(\<Sum>x\<in>supp p. p x * a x ab P s) =
(\<Sum>x\<in>insert x (supp p - {x}). p x * a x ab P s)"
by(simp)
also from fsupp
have "... = p x * a x ab P s + (\<Sum>x\<in>supp p - {x}. p x * a x ab P s)"
by(blast intro:sum.insert)
also from n1
have "... = p x * a x ab P s + (1 - p x) * ((\<Sum>x\<in>supp p - {x}. p x * a x ab P s) / (1 - p x))"
by(simp add:field_simps)
also have "... = p x * a x ab P s +
(1 - p x) * ((\<Sum>y\<in>supp p - {x}. (p y / (1 - p x)) * a y ab P s))"
by(simp add:sum_divide_distrib)
also have "... = p x * a x ab P s +
(1 - p x) * ((\<Sum>y\<in>supp p - {x}. dist_remove p x y * a y ab P s))"
by(simp add:dist_remove_def)
also from nz n1
have "... = p x * a x ab P s +
(1 - p x) * ((\<Sum>y\<in>supp (dist_remove p x). dist_remove p x y * a y ab P s))"
by(simp add:supp_dist_remove)
finally show "(\<Sum>x\<in>supp p. p x * a x ab P s) =
p x * a x ab P s +
(1 - p x) * (\<Sum>y\<in>supp (dist_remove p x). dist_remove p x y * a y ab P s)" .
qed
lemma cts_bot:
"bd_cts (\<lambda>(P::'s expect) (s::'s). 0::real)"
proof -
have X: "\<And>s::'s. {(P::'s expect) s |P. P \<in> range (\<lambda>P s. 0)} = {0}" by(auto)
show ?thesis by(intro bd_ctsI, simp add:Sup_exp_def o_def X)
qed
lemma wp_SetPC_nil:
"wp (SetPC a (\<lambda>s a. 0)) = (\<lambda>P s. 0)"
by(intro ext, simp add:wp_eval)
lemma SetPC_sgl:
"supp p = {x} \<Longrightarrow> SetPC a (\<lambda>_. p) = (\<lambda>ab P s. p x * a x ab P s)"
by(simp add:SetPC_def)
lemma bd_cts_scale:
fixes a::"'s trans"
assumes ca: "bd_cts a"
and ha: "healthy a"
and nnc: "0 \<le> c"
shows "bd_cts (\<lambda>P s. c * a P s)"
proof(intro bd_ctsI ext, simp add:o_def)
fix M::"nat \<Rightarrow> 's expect" and d::real and s::'s
assume chain: "\<And>i. M i \<tturnstile> M (Suc i)" and sM: "\<And>i. sound (M i)"
and bM: "\<And>i. bounded_by d (M i)"
from sM have "\<And>i. nneg (M i)" by(auto)
with bM have nnd: "0 \<le> d" by(auto)
from sM bM have sSup: "sound (Sup_exp (range M))" by(auto intro:Sup_exp_sound)
with healthy_scalingD[OF ha] nnc
have "c * a (Sup_exp (range M)) s = a (\<lambda>s. c * Sup_exp (range M) s) s"
by(auto intro:scalingD)
also {
have "\<And>s. {f s |f. f \<in> range M} = range (\<lambda>i. M i s)" by(auto)
hence "a (\<lambda>s. c * Sup_exp (range M) s) s =
a (\<lambda>s. c * Sup (range (\<lambda>i. M i s))) s"
by(simp add:Sup_exp_def)
}
also {
from bM have "\<And>x s. x \<in> range (\<lambda>i. M i s) \<Longrightarrow> x \<le> d" by(auto)
with nnc have "a (\<lambda>s. c * Sup (range (\<lambda>i. M i s))) s =
a (\<lambda>s. Sup {c*x |x. x \<in> range (\<lambda>i. M i s)}) s"
by(subst cSup_mult, blast+)
}
also {
have X: "\<And>s. {c * x |x. x \<in> range (\<lambda>i. M i s)} = range (\<lambda>i. c * M i s)" by(auto)
have "a (\<lambda>s. Sup {c * x |x. x \<in> range (\<lambda>i. M i s)}) s =
a (\<lambda>s. Sup (range (\<lambda>i. c * M i s))) s" by(simp add:X)
}
also {
have "\<And>s. range (\<lambda>i. c * M i s) = {f s |f. f \<in> range (\<lambda>i s. c * M i s)}"
by(auto)
hence "(\<lambda>s. Sup (range (\<lambda>i. c * M i s))) = Sup_exp (range (\<lambda>i s. c * M i s))"
by (simp add: Sup_exp_def cong del: SUP_cong_simp)
hence "a (\<lambda>s. Sup (range (\<lambda>i. c * M i s))) s =
a (Sup_exp (range (\<lambda>i s. c * M i s))) s" by(simp)
}
also {
from le_funD[OF chain] nnc
have "\<And>i. (\<lambda>s. c * M i s) \<tturnstile> (\<lambda>s. c * M (Suc i) s)"
by(auto intro:le_funI[OF mult_left_mono])
moreover from sM nnc
have "\<And>i. sound (\<lambda>s. c * M i s)"
by(auto intro:sound_intros)
moreover from bM nnc
have "\<And>i. bounded_by (c * d) (\<lambda>s. c * M i s)"
by(auto intro:mult_left_mono)
ultimately
have "a (Sup_exp (range (\<lambda>i s. c * M i s))) =
Sup_exp (range (a o (\<lambda>i s. c * M i s)))"
by(rule bd_ctsD[OF ca])
hence "a (Sup_exp (range (\<lambda>i s. c * M i s))) s =
Sup_exp (range (a o (\<lambda>i s. c * M i s))) s"
by(auto)
}
also have "Sup_exp (range (a o (\<lambda>i s. c * M i s))) s =
Sup_exp (range (\<lambda>x. a (\<lambda>s. c * M x s))) s"
by(simp add:o_def)
also {
from nnc sM
have "\<And>x. a (\<lambda>s. c * M x s) = (\<lambda>s. c * a (M x) s)"
by(auto intro:scalingD[OF healthy_scalingD, OF ha, symmetric])
hence "Sup_exp (range (\<lambda>x. a (\<lambda>s. c * M x s))) s =
Sup_exp (range (\<lambda>x s. c * a (M x) s)) s"
by(simp)
}
finally show "c * a (Sup_exp (range M)) s = Sup_exp (range (\<lambda>x s. c * a (M x) s)) s" .
qed
lemma cts_wp_SetPC_const:
fixes a::"'a \<Rightarrow> 's prog"
assumes ca: "\<And>x. x \<in> (supp p) \<Longrightarrow> bd_cts (wp (a x))"
and ha: "\<And>x. x \<in> (supp p) \<Longrightarrow> healthy (wp (a x))"
and up: "unitary p"
and sump: "sum p (supp p) \<le> 1"
and fsupp: "finite (supp p)"
shows "bd_cts (wp (SetPC a (\<lambda>_. p)))"
proof(cases "supp p = {}", simp add:supp_empty SetPC_def wp_def cts_bot)
assume nesupp: "supp p \<noteq> {}"
from fsupp have "unitary p \<longrightarrow> sum p (supp p) \<le> 1 \<longrightarrow>
(\<forall>x\<in>supp p. bd_cts (wp (a x))) \<longrightarrow>
(\<forall>x\<in>supp p. healthy (wp (a x))) \<longrightarrow>
bd_cts (wp (SetPC a (\<lambda>_. p)))"
proof(induct "supp p" arbitrary:p, simp add:supp_empty wp_SetPC_nil cts_bot, clarify)
fix x::'a and F::"'a set" and p::"'a \<Rightarrow> real"
assume fF: "finite F"
assume "insert x F = supp p"
hence pstep: "supp p = insert x F" by(simp)
hence xin: "x \<in> supp p" by(auto)
assume up: "unitary p" and ca: "\<forall>x\<in>supp p. bd_cts (wp (a x))"
and ha: "\<forall>x\<in>supp p. healthy (wp (a x))"
and sump: "sum p (supp p) \<le> 1"
and xni: "x \<notin> F"
assume IH: "\<And>p. F = supp p \<Longrightarrow>
unitary p \<longrightarrow> sum p (supp p) \<le> 1 \<longrightarrow>
(\<forall>x\<in>supp p. bd_cts (wp (a x))) \<longrightarrow>
(\<forall>x\<in>supp p. healthy (wp (a x))) \<longrightarrow>
bd_cts (wp (SetPC a (\<lambda>_. p)))"
from fF pstep have fsupp: "finite (supp p)" by(auto)
from xin have nzp: "p x \<noteq> 0" by(simp add:supp_def)
have xy_le_sum:
"\<And>y. y \<in> supp p \<Longrightarrow> y \<noteq> x \<Longrightarrow> p x + p y \<le> sum p (supp p)"
proof -
fix y assume yin: "y \<in> supp p" and yne: "y \<noteq> x"
from up have "0 \<le> sum p (supp p - {x,y})"
by(auto intro:sum_nonneg)
hence "p x + p y \<le> p x + p y + sum p (supp p - {x,y})"
by(auto)
also {
from yin yne fsupp
have "p y + sum p (supp p - {x,y}) = sum p (supp p - {x})"
by(subst sum.insert[symmetric], (blast intro!:sum.cong)+)
moreover
from xin fsupp
have "p x + sum p (supp p - {x}) = sum p (supp p)"
by(subst sum.insert[symmetric], (blast intro!:sum.cong)+)
ultimately
have "p x + p y + sum p (supp p - {x, y}) = sum p (supp p)" by(simp)
}
finally show "p x + p y \<le> sum p (supp p)" .
qed
have n1p: "\<And>y. y \<in> supp p \<Longrightarrow> y \<noteq> x \<Longrightarrow> p x \<noteq> 1"
proof(rule ccontr, simp)
assume px1: "p x = 1"
fix y assume yin: "y \<in> supp p" and yne: "y \<noteq> x"
from up have "0 \<le> p y" by(auto)
with yin have "0 < p y" by(auto simp:supp_def)
hence "0 + p x < p y + p x" by(rule add_strict_right_mono)
with px1 have "1 < p x + p y" by(simp)
also from yin yne have "p x + p y \<le> sum p (supp p)"
by(rule xy_le_sum)
finally show False using sump by(simp)
qed
show "bd_cts (wp (SetPC a (\<lambda>_. p)))"
proof(cases "F = {}")
case True with pstep have "supp p = {x}" by(simp)
hence "wp (SetPC a (\<lambda>_. p)) = (\<lambda>P s. p x * wp (a x) P s)"
by(simp add:SetPC_sgl wp_def)
moreover {
from up ca ha xin have "bd_cts (wp (a x))" "healthy (wp (a x))" "0 \<le> p x"
by(auto)
hence "bd_cts (\<lambda>P s. p x * wp (a x) P s)"
by(rule bd_cts_scale)
}
ultimately show ?thesis by(simp)
next
assume neF: "F \<noteq> {}"
then obtain y where yinF: "y \<in> F" by(auto)
with xni have yne: "y \<noteq> x" by(auto)
from yinF pstep have yin: "y \<in> supp p" by(auto)
from supp_dist_remove[of p x, OF nzp n1p, OF yin yne]
have supp_sub: "supp (dist_remove p x) \<subseteq> supp p" by(auto)
from xin ca have cax: "bd_cts (wp (a x))" by(auto)
from xin ha have hax: "healthy (wp (a x))" by(auto)
from supp_sub ha have hra: "\<forall>x\<in>supp (dist_remove p x). healthy (wp (a x))"
by(auto)
from supp_sub ca have cra: "\<forall>x\<in>supp (dist_remove p x). bd_cts (wp (a x))"
by(auto)
from supp_dist_remove[of p x, OF nzp n1p, OF yin yne] pstep xni
have Fsupp: "F = supp (dist_remove p x)"
by(simp)
have udp: "unitary (dist_remove p x)"
proof(intro unitaryI2 nnegI bounded_byI)
fix y
show "0 \<le> dist_remove p x y"
proof(cases "y=x", simp_all add:dist_remove_def)
from up have "0 \<le> p y" "0 \<le> 1 - p x"
by auto
thus "0 \<le> p y / (1 - p x)"
by(rule divide_nonneg_nonneg)
qed
show "dist_remove p x y \<le> 1"
proof(cases "y=x", simp_all add:dist_remove_def,
cases "y\<in>supp p", simp_all add:nsupp_zero)
assume yne: "y \<noteq> x" and yin: "y \<in> supp p"
hence "p x + p y \<le> sum p (supp p)"
by(auto intro:xy_le_sum)
also note sump
finally have "p y \<le> 1 - p x" by(auto)
moreover from up have "p x \<le> 1" by(auto)
moreover from yin yne have "p x \<noteq> 1" by(rule n1p)
ultimately show "p y / (1 - p x) \<le> 1" by(auto)
qed
qed
from xin have pxn0: "p x \<noteq> 0" by(auto simp:supp_def)
from yin yne have pxn1: "p x \<noteq> 1" by(rule n1p)
from pxn0 pxn1 have "sum (dist_remove p x) (supp (dist_remove p x)) =
sum (dist_remove p x) (supp p - {x})"
by(simp add:supp_dist_remove)
also have "... = (\<Sum>y\<in>supp p - {x}. p y / (1 - p x))"
by(simp add:dist_remove_def)
also have "... = (\<Sum>y\<in>supp p - {x}. p y) / (1 - p x)"
by(simp add:sum_divide_distrib)
also {
from xin have "insert x (supp p) = supp p" by(auto)
with fsupp have "p x + (\<Sum>y\<in>supp p - {x}. p y) = sum p (supp p)"
by(simp add:sum.insert[symmetric])
also note sump
finally have "sum p (supp p - {x}) \<le> 1 - p x" by(auto)
moreover {
from up have "p x \<le> 1" by(auto)
with pxn1 have "p x < 1" by(auto)
hence "0 < 1 - p x" by(auto)
}
ultimately have "sum p (supp p - {x}) / (1 - p x) \<le> 1"
by(auto)
}
finally have sdp: "sum (dist_remove p x) (supp (dist_remove p x)) \<le> 1" .
from Fsupp udp sdp hra cra IH
have cts_dr: "bd_cts (wp (SetPC a (\<lambda>_. dist_remove p x)))"
by(auto)
from up have upx: "unitary (\<lambda>_. p x)" by(auto)
from pxn0 pxn1 fsupp hra show ?thesis
by(simp add:SetPC_remove,
blast intro:cts_wp_PC cax cts_dr hax healthy_intros
unitary_sound[OF udp] sdp upx)
qed
qed
with assms show ?thesis by(auto)
qed
lemma cts_wp_SetPC:
fixes a::"'a \<Rightarrow> 's prog"
assumes ca: "\<And>x s. x \<in> (supp (p s)) \<Longrightarrow> bd_cts (wp (a x))"
and ha: "\<And>x s. x \<in> (supp (p s)) \<Longrightarrow> healthy (wp (a x))"
and up: "\<And>s. unitary (p s)"
and sump: "\<And>s. sum (p s) (supp (p s)) \<le> 1"
and fsupp: "\<And>s. finite (supp (p s))"
shows "bd_cts (wp (SetPC a p))"
proof -
from assms have "bd_cts (wp (Bind p (\<lambda>p. SetPC a (\<lambda>_. p))))"
by(iprover intro!:cts_wp_Bind cts_wp_SetPC_const)
thus ?thesis by(simp add:SetPC_Bind[symmetric])
qed
lemma wp_SetDC_Bind:
"SetDC a S = Bind S (\<lambda>S. SetDC a (\<lambda>_. S))"
by(intro ext, simp add:SetDC_def Bind_def)
lemma SetDC_finite_insert:
assumes fS: "finite S"
and neS: "S \<noteq> {}"
shows "SetDC a (\<lambda>_. insert x S) = a x \<Sqinter> SetDC a (\<lambda>_. S)"
proof (intro ext, simp add: SetDC_def DC_def cong del: image_cong_simp cong add: INF_cong_simp)
fix ab P s
from fS have A: "finite (insert (a x ab P s) ((\<lambda>x. a x ab P s) ` S))"
and B: "finite (((\<lambda>x. a x ab P s) ` S))" by(auto)
from neS have C: "insert (a x ab P s) ((\<lambda>x. a x ab P s) ` S) \<noteq> {}"
and D: "(\<lambda>x. a x ab P s) ` S \<noteq> {}" by(auto)
from A C have "Inf (insert (a x ab P s) ((\<lambda>x. a x ab P s) ` S)) =
Min (insert (a x ab P s) ((\<lambda>x. a x ab P s) ` S))"
by(auto intro:cInf_eq_Min)
also from B D have "... = min (a x ab P s) (Min ((\<lambda>x. a x ab P s) ` S))"
by(auto intro:Min_insert)
also from B D have "... = min (a x ab P s) (Inf ((\<lambda>x. a x ab P s) ` S))"
by(simp add:cInf_eq_Min)
finally show "(INF x\<in>insert x S. a x ab P s) =
min (a x ab P s) (INF x\<in>S. a x ab P s)"
by (simp cong del: INF_cong_simp)
qed
lemma SetDC_singleton:
"SetDC a (\<lambda>_. {x}) = a x"
by (simp add: SetDC_def cong del: INF_cong_simp)
lemma cts_wp_SetDC_const:
fixes a::"'a \<Rightarrow> 's prog"
assumes ca: "\<And>x. x \<in> S \<Longrightarrow> bd_cts (wp (a x))"
and ha: "\<And>x. x \<in> S \<Longrightarrow> healthy (wp (a x))"
and fS: "finite S"
and neS: "S \<noteq> {}"
shows "bd_cts (wp (SetDC a (\<lambda>_. S)))"
proof -
have "finite S \<Longrightarrow> S \<noteq> {} \<Longrightarrow>
(\<forall>x\<in>S. bd_cts (wp (a x))) \<longrightarrow>
(\<forall>x\<in>S. healthy (wp (a x))) \<longrightarrow>
bd_cts (wp (SetDC a (\<lambda>_. S)))"
proof(induct S rule:finite_induct, simp, clarsimp)
fix x::'a and F::"'a set"
assume fF: "finite F"
and IH: "F \<noteq> {} \<Longrightarrow> bd_cts (wp (SetDC a (\<lambda>_. F)))"
and cax: "bd_cts (wp (a x))"
and hax: "healthy (wp (a x))"
and haF: "\<forall>x\<in>F. healthy (wp (a x))"
show "bd_cts (wp (SetDC a (\<lambda>_. insert x F)))"
proof(cases "F = {}", simp add:SetDC_singleton cax)
assume "F \<noteq> {}"
with fF cax hax haF IH show "bd_cts (wp (SetDC a (\<lambda>_. insert x F)))"
by(auto intro!:cts_wp_DC healthy_intros simp:SetDC_finite_insert)
qed
qed
with assms show ?thesis by(auto)
qed
lemma cts_wp_SetDC:
fixes a::"'a \<Rightarrow> 's prog"
assumes ca: "\<And>x s. x \<in> S s \<Longrightarrow> bd_cts (wp (a x))"
and ha: "\<And>x s. x \<in> S s \<Longrightarrow> healthy (wp (a x))"
and fS: "\<And>s. finite (S s)"
and neS: "\<And>s. S s \<noteq> {}"
shows "bd_cts (wp (SetDC a S))"
proof -
from assms have "bd_cts (wp (Bind S (\<lambda>S. SetDC a (\<lambda>_. S))))"
by(iprover intro!:cts_wp_Bind cts_wp_SetDC_const)
thus ?thesis by(simp add:wp_SetDC_Bind[symmetric])
qed
lemma cts_wp_repeat:
"bd_cts (wp a) \<Longrightarrow> healthy (wp a) \<Longrightarrow> bd_cts (wp (repeat n a))"
by(induct n, auto intro:cts_wp_Skip cts_wp_Seq healthy_intros)
lemma cts_wp_Embed:
"bd_cts t \<Longrightarrow> bd_cts (wp (Embed t))"
by(simp add:wp_eval)
subsection \<open>Continuity of a Single Loop Step\<close>
text \<open>A single loop iteration is continuous, in the more general sense defined above for
transformer transformers.\<close>
lemma cts_wp_loopstep:
fixes body::"'s prog"
assumes hb: "healthy (wp body)"
and cb: "bd_cts (wp body)"
shows "bd_cts_tr (\<lambda>x. wp (body ;; Embed x \<^bsub>\<guillemotleft> G \<guillemotright>\<^esub>\<oplus> Skip))" (is "bd_cts_tr ?F")
proof(rule bd_cts_trI, rule le_trans_antisym)
fix M::"nat \<Rightarrow> 's trans" and b::real
assume chain: "\<And>i. le_trans (M i) (M (Suc i))"
and fM: "\<And>i. feasible (M i)"
show fw: "le_trans (Sup_trans (range (?F o M))) (?F (Sup_trans (range M)))"
proof(rule le_transI[OF Sup_trans_least2], clarsimp)
fix P Q::"'s expect" and t
assume sP: "sound P"
assume nQ: "nneg Q" and bP: "bounded_by (bound_of P) Q"
hence sQ: "sound Q" by(auto)
from fM have fSup: "feasible (Sup_trans (range M))"
by(auto intro:feasible_Sup_trans)
from sQ fM have "M t Q \<tturnstile> Sup_trans (range M) Q"
by(auto intro:Sup_trans_upper2)
moreover from sQ fM fSup
have sMtP: "sound (M t Q)" "sound (Sup_trans (range M) Q)" by(auto)
ultimately have "wp body (M t Q) \<tturnstile> wp body (Sup_trans (range M) Q)"
using healthy_monoD[OF hb] by(auto)
hence "\<And>s. wp body (M t Q) s \<le> wp body (Sup_trans (range M) Q) s"
by(rule le_funD)
thus "?F (M t) Q \<tturnstile> ?F (Sup_trans (range M)) Q"
by(intro le_funI, simp add:wp_eval mult_left_mono)
show "nneg (wp (body ;; Embed (Sup_trans (range M)) \<^bsub>\<guillemotleft> G \<guillemotright>\<^esub>\<oplus> Skip) Q)"
proof(rule nnegI, simp add:wp_eval)
fix s::'s
from fSup sQ have "sound (Sup_trans (range M) Q)" by(auto)
with hb have "sound (wp body (Sup_trans (range M) Q))" by(auto)
hence "0 \<le> wp body (Sup_trans (range M) Q) s" by(auto)
moreover from sQ have "0 \<le> Q s" by(auto)
ultimately show "0 \<le> \<guillemotleft>G\<guillemotright> s * wp body (Sup_trans (range M) Q) s + (1 - \<guillemotleft>G\<guillemotright> s) * Q s"
by(auto intro:add_nonneg_nonneg mult_nonneg_nonneg)
qed
next
fix P::"'s expect" assume sP: "sound P"
thus "nneg P" "bounded_by (bound_of P) P" by(auto)
show "\<forall>u\<in>range ((\<lambda>x. wp (body ;; Embed x \<^bsub>\<guillemotleft> G \<guillemotright>\<^esub>\<oplus> Skip)) \<circ> M).
\<forall>R. nneg R \<and> bounded_by (bound_of P) R \<longrightarrow>
nneg (u R) \<and> bounded_by (bound_of P) (u R)"
proof(clarsimp, intro conjI nnegI bounded_byI, simp_all add:wp_eval)
fix u::nat and R::"'s expect" and s::'s
assume nR: "nneg R" and bR: "bounded_by (bound_of P) R"
hence sR: "sound R" by(auto)
with fM have sMuR: "sound (M u R)" by(auto)
with hb have "sound (wp body (M u R))" by(auto)
hence "0 \<le> wp body (M u R) s" by(auto)
moreover from nR have "0 \<le> R s" by(auto)
ultimately show "0 \<le> \<guillemotleft>G\<guillemotright> s * wp body (M u R) s + (1 - \<guillemotleft>G\<guillemotright> s) * R s"
by(auto intro:add_nonneg_nonneg mult_nonneg_nonneg)
from sR bR fM have "bounded_by (bound_of P) (M u R)" by(auto)
with sMuR hb have "bounded_by (bound_of P) (wp body (M u R))" by(auto)
hence "wp body (M u R) s \<le> bound_of P" by(auto)
moreover from bR have "R s \<le> bound_of P" by(auto)
ultimately have "\<guillemotleft>G\<guillemotright> s * wp body (M u R) s + (1 - \<guillemotleft>G\<guillemotright> s) * R s \<le>
\<guillemotleft>G\<guillemotright> s * bound_of P + (1 - \<guillemotleft>G\<guillemotright> s) * bound_of P"
by(auto intro:add_mono mult_left_mono)
also have "... = bound_of P" by(simp add:algebra_simps)
finally show "\<guillemotleft>G\<guillemotright> s * wp body (M u R) s + (1 - \<guillemotleft>G\<guillemotright> s) * R s \<le> bound_of P" .
qed
qed
show "le_trans (?F (Sup_trans (range M))) (Sup_trans (range (?F o M)))"
proof(rule le_transI, rule le_funI, simp add: wp_eval cong del: image_cong_simp)
fix P::"'s expect" and s::'s
assume sP: "sound P"
have "{t P |t. t \<in> range M} = range (\<lambda>i. M i P)"
by(blast)
hence "wp body (Sup_trans (range M) P) s = wp body (Sup_exp (range (\<lambda>i. M i P))) s"
by(simp add:Sup_trans_def)
also {
from sP fM have "\<And>i. sound (M i P)" by(auto)
moreover from sP chain have "\<And>i. M i P \<tturnstile> M (Suc i) P" by(auto)
moreover {
from sP have "bounded_by (bound_of P) P" by(auto)
with sP fM have "\<And>i. bounded_by (bound_of P) (M i P)" by(auto)
}
ultimately have "wp body (Sup_exp (range (\<lambda>i. M i P))) s =
Sup_exp (range (\<lambda>i. wp body (M i P))) s"
by(subst bd_ctsD[OF cb], auto simp:o_def)
}
also have "Sup_exp (range (\<lambda>i. wp body (M i P))) s =
Sup {f s |f. f \<in> range (\<lambda>i. wp body (M i P))}"
by(simp add:Sup_exp_def)
finally have "\<guillemotleft>G\<guillemotright> s * wp body (Sup_trans (range M) P) s + (1 - \<guillemotleft>G\<guillemotright> s) * P s =
\<guillemotleft>G\<guillemotright> s * Sup {f s |f. f \<in> range (\<lambda>i. wp body (M i P))} + (1 - \<guillemotleft>G\<guillemotright> s) * P s"
by(simp)
also {
from sP fM have "\<And>i. sound (M i P)" by(auto)
moreover from sP fM have "\<And>i. bounded_by (bound_of P) (M i P)" by(auto)
ultimately have "\<And>i. bounded_by (bound_of P) (wp body (M i P))" using hb by(auto)
hence bound: "\<And>i. wp body (M i P) s \<le> bound_of P" by(auto)
moreover
have "{\<guillemotleft> G \<guillemotright> s * x |x. x \<in> {f s |f. f \<in> range (\<lambda>i. wp body (M i P))}} =
{\<guillemotleft> G \<guillemotright> s * f s |f. f \<in> range (\<lambda>i. wp body (M i P))}"
by(blast)
ultimately
have "\<guillemotleft>G\<guillemotright> s * Sup {f s |f. f \<in> range (\<lambda>i. wp body (M i P))} =
Sup {\<guillemotleft>G\<guillemotright> s * f s |f. f \<in> range (\<lambda>i. wp body (M i P))}"
by(subst cSup_mult, auto)
moreover {
have "{x + (1-\<guillemotleft>G\<guillemotright> s) * P s |x.
x \<in> {\<guillemotleft>G\<guillemotright> s * f s |f. f \<in> range (\<lambda>i. wp body (M i P))}} =
{\<guillemotleft>G\<guillemotright> s * f s + (1-\<guillemotleft>G\<guillemotright> s) * P s |f. f \<in> range (\<lambda>i. wp body (M i P))}"
by(blast)
moreover from bound sP have "\<And>i. \<guillemotleft>G\<guillemotright> s * wp body (M i P) s \<le> bound_of P"
by(cases "G s", auto)
ultimately
have "Sup {\<guillemotleft>G\<guillemotright> s * f s |f. f \<in> range (\<lambda>i. wp body (M i P))} + (1-\<guillemotleft>G\<guillemotright> s) * P s =
Sup {\<guillemotleft>G\<guillemotright> s * f s + (1-\<guillemotleft>G\<guillemotright> s) * P s |f. f \<in> range (\<lambda>i. wp body (M i P))}"
by(subst cSup_add, auto)
}
ultimately
have "\<guillemotleft>G\<guillemotright> s * Sup {f s |f. f \<in> range (\<lambda>i. wp body (M i P))} + (1-\<guillemotleft>G\<guillemotright> s) * P s =
Sup {\<guillemotleft>G\<guillemotright> s * f s + (1-\<guillemotleft>G\<guillemotright> s) * P s |f. f \<in> range (\<lambda>i. wp body (M i P))}"
by(simp)
}
also {
have "\<And>i. \<guillemotleft>G\<guillemotright> s * wp body (M i P) s + (1-\<guillemotleft>G\<guillemotright> s) * P s =
((\<lambda>x. wp (body ;; Embed x \<^bsub>\<guillemotleft> G \<guillemotright>\<^esub>\<oplus> Skip)) \<circ> M) i P s"
by(simp add:wp_eval)
also have "\<And>i. ... i \<le>
Sup {f s |f. f \<in> {t P |t. t \<in> range ((\<lambda>x. wp (body ;; Embed x \<^bsub>\<guillemotleft> G \<guillemotright>\<^esub>\<oplus> Skip)) \<circ> M)}}"
proof(intro cSup_upper bdd_aboveI, blast, clarsimp simp:wp_eval)
fix i
from sP have bP: "bounded_by (bound_of P) P" by(auto)
with sP fM have "sound (M i P)" "bounded_by (bound_of P) (M i P)" by(auto)
with hb have "bounded_by (bound_of P) (wp body (M i P))" by(auto)
with bP have "wp body (M i P) s \<le> bound_of P" "P s \<le> bound_of P" by(auto)
hence "\<guillemotleft>G\<guillemotright> s * wp body (M i P) s + (1-\<guillemotleft>G\<guillemotright> s) * P s \<le>
\<guillemotleft>G\<guillemotright> s * (bound_of P) + (1-\<guillemotleft>G\<guillemotright> s) * (bound_of P)"
by(auto intro:add_mono mult_left_mono)
also have "... = bound_of P" by(simp add:algebra_simps)
finally show "\<guillemotleft>G\<guillemotright> s * wp body (M i P) s + (1-\<guillemotleft>G\<guillemotright> s) * P s \<le> bound_of P" .
qed
finally
have "Sup {\<guillemotleft>G\<guillemotright> s * f s + (1-\<guillemotleft>G\<guillemotright> s) * P s |f. f \<in> range (\<lambda>i. wp body (M i P))} \<le>
Sup {f s |f. f \<in> {t P |t. t \<in> range ((\<lambda>x. wp (body ;; Embed x \<^bsub>\<guillemotleft> G \<guillemotright>\<^esub>\<oplus> Skip)) \<circ> M)}}"
by(blast intro:cSup_least)
}
also have "Sup {f s |f. f \<in> {t P |t. t \<in> range ((\<lambda>x. wp (body ;; Embed x \<^bsub>\<guillemotleft> G \<guillemotright>\<^esub>\<oplus> Skip)) \<circ> M)}} =
Sup_trans (range ((\<lambda>x. wp (body ;; Embed x \<^bsub>\<guillemotleft> G \<guillemotright>\<^esub>\<oplus> Skip)) \<circ> M)) P s"
by(simp add:Sup_trans_def Sup_exp_def)
finally show "\<guillemotleft>G\<guillemotright> s * wp body (Sup_trans (range M) P) s + (1-\<guillemotleft>G\<guillemotright> s) * P s \<le>
Sup_trans (range ((\<lambda>x. wp (body ;; Embed x \<^bsub>\<guillemotleft> G \<guillemotright>\<^esub>\<oplus> Skip)) \<circ> M)) P s" .
qed
qed
end
|
-- Andreas, 2011-05-10
-- {-# OPTIONS -v tc.term.con:20 -v tc.meta:20 #-}
module Issue380 where
data _==_ {A : Set}(a : A) : A -> Set where
refl : a == a
record Sigma (A : Set)(B : A -> Set) : Set where
constructor _,_
field
fst : A
snd : B fst
open Sigma public
testProj : {A : Set}{B : A -> Set}(y z : Sigma A B) ->
let X : Sigma A B
X = _
in fst X == fst y -> snd X == snd z
testProj y z = refl , refl
{- OLD BEHAVIOR: Error message about telescope comparison unreadable
This ill-typed term produces a weird error message:
(z' : fst (fst z , _283 y z) == fst y) !=<
when checking that the expression refl , refl has type
fst (fst z , _283 y z) == fst y → snd (fst z , _283 y z) == snd z
-}
{- FIXED. Now it should complain that
Sigma (_47 y z == _47 y z) (_45 y z) !=<
fst (fst z , _43 y z) == fst y → snd (fst z , _43 y z) == snd z
when checking that the expression refl , refl has type
fst (fst z , _43 y z) == fst y → snd (fst z , _43 y z) == snd z
-}
|
PISearchByAttribute <- function(searchRoot = NULL, elementTemplate = NULL, webException = NULL, valueQueries = NULL) {
if (is.null(searchRoot) == FALSE) {
if (is.character(searchRoot) == FALSE) {
return (print(paste0("Error: searchRoot must be a string.")))
}
}
if (is.null(elementTemplate) == FALSE) {
if (is.character(elementTemplate) == FALSE) {
return (print(paste0("Error: elementTemplate must be a string.")))
}
}
if (is.null(webException) == FALSE) {
className <- attr(webException, "className")
if ((is.null(className)) || (className != "PIWebException")) {
return (print(paste0("Error: the class from the parameter webException should be PIWebException.")))
}
}
if (is.null(valueQueries) == FALSE) {
if (is.vector(valueQueries) == FALSE) {
return (print(paste0("Error: valueQueries must be a vector.")))
}
}
value <- list(
SearchRoot = searchRoot,
ElementTemplate = elementTemplate,
WebException = webException,
ValueQueries = valueQueries)
valueCleaned <- rmNullObs(value)
attr(valueCleaned, "className") <- "PISearchByAttribute"
return(valueCleaned)
}
|
"""RandomForestRegressionSklearn tests.
Scientific Machine Learning Benchmark:
A benchmark of regression models in chem- and materials informatics.
Matthias Rupp 2020, Citrine Informatics.
"""
import pytest
import numpy as np
skl = pytest.importorskip("sklearn")
import smlb
from learners.scikit_learn.random_forest_regression_sklearn import RandomForestRegressionSklearn
# todo: rework the example to be meaningful for random forests
def test_RandomForestRegressionSklearn_1():
"""Simple example: constant 1-d function."""
# MH: for constant labels, expected uncertainties are zero
train_data = smlb.TabularData(
data=np.array([[-4], [-3], [-2], [-1], [0], [1], [2], [3], [4]]),
labels=np.array([1, 1, 1, 1, 1, 1, 1, 1, 1]),
)
valid_data = smlb.TabularData(data=np.array([[-4], [-2], [0], [3], [4]]))
rf = RandomForestRegressionSklearn(random_state=1, uncertainties="naive")
preds = rf.fit(train_data).apply(valid_data)
mean, stddev = preds.mean, preds.stddev
assert np.allclose(mean, [1, 1, 1, 1, 1])
assert np.allclose(stddev, [0, 0, 0, 0, 0])
def test_RandomForestRegressionSklearn_2():
"""Simple examples: linear 1-d function."""
rf = RandomForestRegressionSklearn(random_state=1, uncertainties="naive")
train_data = smlb.TabularData(
data=np.array([[-2], [-1.5], [-1], [-0.5], [0], [0.5], [1], [1.5], [2]]),
labels=np.array([-2, -1.5, -1, -0.5, 0, 0.5, 1, 1.5, 2]),
)
rf.fit(train_data)
mean = rf.apply(smlb.TabularData(data=np.array([[-1], [0], [1]]))).mean
assert np.allclose(mean, [-1, 0, 1], atol=0.2)
stddev = rf.apply(smlb.TabularData(data=np.array([[-2], [0], [2]]))).stddev
assert stddev[0] > stddev[1] < stddev[2]
# without uncertainties
rf = RandomForestRegressionSklearn(random_state=1) # default for uncertainties is None
rf.fit(train_data)
preds = rf.apply(smlb.TabularData(data=np.array([[-1], [0], [1]])))
assert np.allclose(preds.mean, [-1, 0, 1], atol=0.2)
assert isinstance(preds, smlb.DeltaPredictiveDistribution)
def test_RandomForestRegressionSklearn_3():
"""Ensure predictions are identical independent of uncertainties method used."""
rf1 = RandomForestRegressionSklearn(random_state=1, uncertainties=None)
rf2 = RandomForestRegressionSklearn(random_state=1, uncertainties="naive")
train_data = smlb.TabularData(
data=np.array([[-2], [-1.5], [-1], [-0.5], [0], [0.5], [1], [1.5], [2]]),
labels=np.array([-2, -1.5, -1, -0.5, 0, 0.5, 1, 1.5, 2]),
)
rf1.fit(train_data)
rf2.fit(train_data)
test_data = np.array([[-3], [-1], [0], [0.5], [1], [2]])
mean1 = rf1.apply(smlb.TabularData(data=test_data)).mean
mean2 = rf2.apply(smlb.TabularData(data=test_data)).mean
assert np.allclose(mean1, mean2, atol=1e-6)
|
[STATEMENT]
lemma set_bit_uint16_code [code]:
"set_bit x n b = (if n < 16 then uint16_set_bit x (integer_of_nat n) b else x)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. set_bit_class.set_bit x n b = (if n < 16 then uint16_set_bit x (integer_of_nat n) b else x)
[PROOF STEP]
including undefined_transfer integer.lifting
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. set_bit_class.set_bit x n b = (if n < 16 then uint16_set_bit x (integer_of_nat n) b else x)
[PROOF STEP]
unfolding uint16_set_bit_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. set_bit_class.set_bit x n b = (if n < 16 then if integer_of_nat n < 0 \<or> 15 < integer_of_nat n then undefined set_bit_class.set_bit x (integer_of_nat n) b else set_bit_class.set_bit x (nat_of_integer (integer_of_nat n)) b else x)
[PROOF STEP]
by(transfer)(auto cong: conj_cong simp add: not_less set_bit_beyond word_size) |
import condensed.filtered_colimits_commute_with_finite_limits
import condensed.ab
import condensed.short_exact
import condensed.bd_ses_aux
import for_mathlib.nnreal_to_nat_colimit
import for_mathlib.pow_functor
open category_theory
open category_theory.limits
namespace Condensed
open_locale nnreal
open opposite
noncomputable theory
universes u
variables (F : CondensedSet.{u} ⥤ Condensed.{u} Ab.{u+1})
[preserves_filtered_colimits F] (A : CompHausFiltPseuNormGrp.{u})
(ι : ℕ →o ℝ≥0) (hι : ∀ r : ℝ≥0, ∃ n : ℕ, r ≤ ι n)
set_option pp.universes true
def as_nat_diagram : as_small.{u+1} ℕ ⥤ CondensedSet.{u} :=
restrict_diagram ι A.level_Condensed_diagram'
@[simp, reassoc]
lemma ι_colimit_iso_Condensed_obj (i) :
colimit.ι _ i ≫ A.colimit_iso_Condensed_obj.hom =
A.level_Condensed_diagram_cocone.ι.app _ :=
begin
dsimp [CompHausFiltPseuNormGrp.colimit_iso_Condensed_obj],
erw colimit.ι_desc_assoc,
apply CondensedSet_to_presheaf.map_injective,
dsimp [CompHausFiltPseuNormGrp.colimit_iso_Condensed_obj_aux_nat_iso],
ext S : 2, dsimp,
erw
((is_colimit_of_preserves.{u+1 u+1 u+1 u+1 u+2 u+2}
((category_theory.evaluation.{u u+1 u+1 u+2} Profinite.{u}ᵒᵖ
(Type (u+1))).obj S) (colimit.is_colimit.{u+1 u+1 u+1 u+2}
(A.level_Condensed_diagram' ⋙ Sheaf_to_presheaf.{u u+1 u+1 u+2}
proetale_topology.{u} (Type (u+1)))))).fac_assoc,
erw colimit.ι_desc_assoc,
refl,
end
def is_colimit_level_Condensed_diagram_cocone :
is_colimit A.level_Condensed_diagram_cocone :=
{ desc := λ S, A.colimit_iso_Condensed_obj.inv ≫ colimit.desc _ S,
fac' := begin
intros S j, rw ← category.assoc,
let t := _, change t ≫ _ = _,
have ht : t = colimit.ι _ _,
{ dsimp [t], rw [iso.comp_inv_eq, ι_colimit_iso_Condensed_obj] },
simp [ht],
end,
uniq' := begin
intros S m hm,
rw iso.eq_inv_comp,
apply colimit.hom_ext, intros j,
specialize hm j,
simpa,
end }
def as_nat_cocone : cocone (as_nat_diagram A ι) :=
restrict_cocone ι A.level_Condensed_diagram_cocone
def is_colimit_as_nat_cocone : is_colimit (as_nat_cocone A ι) :=
is_colimit_restrict_cocone ι hι _ (is_colimit_level_Condensed_diagram_cocone _)
/-- The map `∐ F(A_≤(n * c)) ⟶ F(A)`-/
def coproduct_presentation :
(∐ (λ i : as_small.{u+1} ℕ, F.obj ((as_nat_diagram A ι).obj i))) ⟶
F.obj (as_nat_cocone A ι).X :=
sigma.desc $ λ i, F.map ((as_nat_cocone A ι).ι.app i)
def presentation_point_isomorphism :
F.obj ((as_nat_cocone A ι).X) ≅ colimit (as_nat_diagram A ι ⋙ F) :=
(is_colimit_of_preserves F (is_colimit_as_nat_cocone A ι hι)).cocone_point_unique_up_to_iso
(colimit.is_colimit _)
lemma coproduct_presentation_eq :
coproduct_presentation F A ι ≫ (presentation_point_isomorphism F A ι hι).hom =
coproduct_to_colimit ((as_nat_diagram A ι ⋙ F)) :=
begin
apply colimit.hom_ext, intros j,
erw colimit.ι_desc,
erw colimit.ι_desc_assoc,
dsimp,
erw (is_colimit_of_preserves F (is_colimit_as_nat_cocone A ι hι)).fac,
refl,
end
theorem coproduct_to_colimit_short_exact_sequence (hι : ∀ r : ℝ≥0, ∃ n, r ≤ ι n):
short_exact (coproduct_to_coproduct (as_nat_diagram A ι ⋙ F) - 𝟙 _)
(coproduct_presentation F A ι) :=
{ mono := infer_instance,
epi := begin
have := coproduct_presentation_eq F A ι hι,
rw ← iso.eq_comp_inv at this, rw this,
apply_with epi_comp { instances := ff },
apply_instance,
apply_instance,
end,
exact := begin
have := coproduct_presentation_eq F A ι hι,
rw ← iso.eq_comp_inv at this, rw this,
rw exact_comp_iso,
exact (short_exact_sequence_aux (as_nat_diagram A ι ⋙ F)).exact,
end }
variables (n : ℕ)
/-- The map `(∐ i, F((A_≤ i * c)^n)) ⟶ F(A^n)`. -/
def coproduct_presentation_with_pow :
(∐ (λ i : as_small.{u+1} ℕ, F.obj (∏ λ (j : ulift.{u+1} (fin n)), (as_nat_diagram A ι).obj i))) ⟶
F.obj (∏ λ j : ulift.{u+1} (fin n), (as_nat_cocone A ι).X) :=
sigma.desc $ λ i, F.map (pi.map $ λ j, (as_nat_cocone A ι).ι.app i)
def as_nat_diagram_pow : as_small.{u+1} ℕ ⥤ CondensedSet.{u} :=
as_nat_diagram A ι ⋙ pow_functor _ (ulift.{u+1} (fin n))
def as_nat_cocone_pow : cocone (as_nat_diagram_pow A ι n) :=
(pow_functor _ (ulift.{u+1} (fin n))).map_cocone (as_nat_cocone A ι)
def is_colimit_as_nat_cocone_pow : is_colimit (as_nat_cocone_pow A ι n) :=
is_colimit_of_preserves _ (is_colimit_as_nat_cocone _ _ hι)
def presentation_point_isomorphism_with_pow :
F.obj (∏ λ (j : ulift.{u+1} (fin n)), (as_nat_cocone A ι).X) ≅
colimit (as_nat_diagram_pow A ι n ⋙ F) :=
(is_colimit_of_preserves F
(is_colimit_as_nat_cocone_pow A ι hι n)).cocone_point_unique_up_to_iso
(colimit.is_colimit _)
lemma coproduct_presentation_with_pow_eq :
coproduct_presentation_with_pow F A ι n =
coproduct_to_colimit (as_nat_diagram_pow A ι n ⋙ F) ≫
(presentation_point_isomorphism_with_pow F A ι hι n).inv :=
begin
apply colimit.hom_ext, intros j,
erw colimit.ι_desc,
erw colimit.ι_desc_assoc,
dsimp,
erw colimit.ι_desc,
refl,
end
/--
This is the short exact sequence of condensed abelian groups of the form
`0 → ∐ i, F((A_{c * i})^n) → ∐ i, F((A_{c * i})^n) → F(A^n) → 0`.
-/
lemma short_exact_sequence_with_pow (hι : ∀ r : ℝ≥0, ∃ n, r ≤ ι n) :
short_exact (coproduct_to_coproduct (as_nat_diagram_pow A ι n ⋙ F) - 𝟙 _)
(coproduct_presentation_with_pow F A ι n) :=
{ mono := infer_instance,
epi := begin
rw coproduct_presentation_with_pow_eq,
apply epi_comp,
apply hι,
end,
exact := begin
rw coproduct_presentation_with_pow_eq,
rw exact_comp_iso,
exact (short_exact_sequence_aux _).exact,
apply hι,
end }
end Condensed
|
% book : Signals and Systems Laboratory with MATLAB
% authors : Alex Palamides & Anastasia Veloni
%
%
%
% problem 2- graph of
% u(t+1)*u(t-1)
t1=-5:.1:1;
t2=1:.1:10;
x1=zeros(size(t1));
x2=ones(size(t2));
t=[t1 t2];
x=[x1 x2];
plot(t,x);
ylim([-0.1 1.1]);
figure
t=-5:.1:10;
x=heaviside(t+1).*heaviside(t-1) ;
plot(t,x);
ylim([-0.1 1.1]);
|
#' dmrff.pre
#'
#' Construct an object for including this dataset in a DMR meta-analysis.
#'
#' @param estimate Vector of association effect estimates
#' (corresponds to rows of \code{methylation}).
#' @param se Vector of standard errors of the effect estimates.
#' @param methylation Methylation matrix (rows=features, columns=samples).
#' @param chr Feature chromosome (corresponds to rows of \code{methylation}).
#' @param pos Feature chromosome position.
#' @param maxsize Maximum number of CpG sites in a DMR.
#' @param verbose If \code{TRUE} (default), then output status messages.
#' @return A list object containing all information needed for inclusion in a meta-analysis.
#'
#' @export
dmrff.pre <- function(estimate, se, methylation, chr, pos, maxsize=20, verbose=T) {
stopifnot(is.vector(estimate))
stopifnot(is.vector(se))
stopifnot(is.matrix(methylation))
stopifnot(is.vector(chr))
stopifnot(is.vector(pos))
stopifnot(length(estimate) == length(se))
stopifnot(length(estimate) == nrow(methylation))
stopifnot(length(estimate) == length(chr))
stopifnot(length(estimate) == length(pos))
# sort input by chromosomal position
idx <- order(chr,pos)
sorted <- identical(idx, 1:length(idx))
if (!sorted) {
estimate <- estimate[idx]
se <- se[idx]
chr <- chr[idx]
pos <- pos[idx]
methylation <- methylation[idx,,drop=F]
}
## calculate rho (CpG correlation matrix)
m <- methylation - rowMeans(methylation, na.rm=T)
mm <- rowSums(m^2, na.rm=T)
ss <- sqrt(mm)
rho <- do.call(cbind, parallel::mclapply(1:maxsize, function(size) {
sapply(1:length(chr), function(i) {
if (i + size <= length(idx)) {
numer <- sum(m[i,] * m[i+size,], na.rm=T)
denom <- ss[i] * ss[i+size]
numer/denom
}
else NA
})
}))
n <- rowSums(!is.na(m))
sd <- sqrt(mm/(n-1))
sites <- paste(chr, pos, sep=":")
list(sites=sites,
chr=chr,
pos=pos,
estimate=estimate,
se=se,
rho=rho,
sd=sd)
}
|
// Copyright Abel Sinkovics ([email protected]) 2013.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <mpllibs/version.hpp>
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_CASE(test_version)
{
// verifying that the version numbers coming from the build system are the
// same as the ones defined in the headers
BOOST_CHECK_EQUAL(MPLLIBS_MAJOR_VERSION, BUILD_MAJOR_VERSION);
BOOST_CHECK_EQUAL(MPLLIBS_MINOR_VERSION, BUILD_MINOR_VERSION);
BOOST_CHECK_EQUAL(MPLLIBS_PATCH_VERSION, BUILD_PATCH_VERSION);
}
|
||| A simple parser combinator library for String. Inspired by attoparsec zepto.
module Data.String.Parser
import public Control.Monad.Identity
import Control.Monad.Trans
import Data.String
import Data.Fin
import Data.List
import Data.List1
import Data.Vect
%default total
||| The input state, pos is position in the string and maxPos is the length of the input string.
public export
record State where
constructor S
input : String
pos : Int
maxPos : Int
Show State where
show s = "(" ++ show s.input ++ ", " ++ show s.pos ++ ", " ++ show s.maxPos ++ ")"
||| Result of applying a parser
public export
data Result a = Fail Int String | OK a State
Functor Result where
map f (Fail i err) = Fail i err
map f (OK r s) = OK (f r) s
public export
record ParseT (m : Type -> Type) (a : Type) where
constructor P
runParser : State -> m (Result a)
public export
Parser : Type -> Type
Parser = ParseT Identity
public export
Functor m => Functor (ParseT m) where
map f p = P $ \s => map (map f) (p.runParser s)
public export
Monad m => Applicative (ParseT m) where
pure x = P $ \s => pure $ OK x s
f <*> x = P $ \s => case !(f.runParser s) of
OK f' s' => map (map f') (x.runParser s')
Fail i err => pure $ Fail i err
public export
Monad m => Alternative (ParseT m) where
empty = P $ \s => pure $ Fail s.pos "no alternative left"
a <|> b = P $ \s => case !(a.runParser s) of
OK r s' => pure $ OK r s'
Fail _ _ => b.runParser s
public export
Monad m => Monad (ParseT m) where
m >>= k = P $ \s => case !(m.runParser s) of
OK a s' => (k a).runParser s'
Fail i err => pure $ Fail i err
public export
MonadTrans ParseT where
lift x = P $ \s => map (flip OK s) x
||| Run a parser in a monad
||| Returns a tuple of the result and final position on success.
||| Returns an error message on failure.
export
parseT : Functor m => ParseT m a -> String -> m (Either String (a, Int))
parseT p str = map (\case
OK r s => Right (r, s.pos)
Fail i err => Left $ fastAppend ["Parse failed at position ", show i, ": ", err])
(p.runParser (S str 0 (strLength str)))
||| Run a parser in a pure function
||| Returns a tuple of the result and final position on success.
||| Returns an error message on failure.
export
parse : Parser a -> String -> Either String (a, Int)
parse p str = runIdentity $ parseT p str
||| Combinator that replaces the error message on failure.
||| This allows combinators to output relevant errors
export
(<?>) : Functor m => ParseT m a -> String -> ParseT m a
(<?>) p msg = P $ \s => map (\case
OK r s' => OK r s'
Fail i _ => Fail i msg)
(p.runParser s)
infixl 0 <?>
||| Discards the result of a parser
export
skip : Functor m => ParseT m a -> ParseT m ()
skip = ignore
||| Maps the result of the parser `p` or returns `def` if it fails.
export
optionMap : Functor m => b -> (a -> b) -> ParseT m a -> ParseT m b
optionMap def f p = P $ \s => map (\case
OK r s' => OK (f r) s'
Fail _ _ => OK def s)
(p.runParser s)
||| Runs the result of the parser `p` or returns `def` if it fails.
export
option : Functor m => a -> ParseT m a -> ParseT m a
option def = optionMap def id
||| Returns a Bool indicating whether `p` succeeded
export
succeeds : Functor m => ParseT m a -> ParseT m Bool
succeeds = optionMap False (const True)
||| Returns a Maybe that contains the result of `p` if it succeeds or `Nothing` if it fails.
export
optional : Functor m => ParseT m a -> ParseT m (Maybe a)
optional = optionMap Nothing Just
||| Succeeds if and only if the argument parser fails.
|||
||| In Parsec, this combinator is called `notFollowedBy`.
export
requireFailure : Functor m => ParseT m a -> ParseT m ()
requireFailure (P runParser) = P $ \s => reverseResult s <$> runParser s
where
reverseResult : State -> Result a -> Result ()
reverseResult s (Fail _ _) = OK () s
reverseResult s (OK _ _) = Fail (pos s) "Purposefully changed OK to Fail"
||| Fail with some error message
export
fail : Applicative m => String -> ParseT m a
fail x = P $ \s => pure $ Fail s.pos x
||| Succeeds if the next char satisfies the predicate `f`
export
satisfy : Applicative m => (Char -> Bool) -> ParseT m Char
satisfy f = P $ \s => pure $ if s.pos < s.maxPos
then let ch = assert_total $ strIndex s.input s.pos in
if f ch
then OK ch (S s.input (s.pos + 1) s.maxPos)
else Fail s.pos "satisfy"
else Fail s.pos "satisfy"
||| Succeeds if the string `str` follows.
export
string : Applicative m => String -> ParseT m String
string str = P $ \s => pure $ let len = strLength str in
if s.pos+len <= s.maxPos
then let head = strSubstr s.pos len s.input in
if head == str
then OK str (S s.input (s.pos + len) s.maxPos)
else Fail s.pos ("string " ++ show str)
else Fail s.pos ("string " ++ show str)
||| Succeeds if the end of the string is reached.
export
eos : Applicative m => ParseT m ()
eos = P $ \s => pure $ if s.pos == s.maxPos
then OK () s
else Fail s.pos "expected the end of the string"
||| Succeeds if the next char is `c`
export
char : Applicative m => Char -> ParseT m Char
char c = satisfy (== c) <?> "char " ++ show c
||| Parses a space character
export
space : Applicative m => ParseT m Char
space = satisfy isSpace <?> "space"
||| Parses a letter or digit (a character between \'0\' and \'9\').
||| Returns the parsed character.
export
alphaNum : Applicative m => ParseT m Char
alphaNum = satisfy isAlphaNum <?> "letter or digit"
||| Parses a letter (an upper case or lower case character). Returns the
||| parsed character.
export
letter : Applicative m => ParseT m Char
letter = satisfy isAlpha <?> "letter"
mutual
||| Succeeds if `p` succeeds, will continue to match `p` until it fails
||| and accumulate the results in a list
export
covering
some : Monad m => ParseT m a -> ParseT m (List a)
some p = [| p :: many p |]
||| Always succeeds, will accumulate the results of `p` in a list until it fails.
export
covering
many : Monad m => ParseT m a -> ParseT m (List a)
many p = some p <|> pure []
||| Parse left-nested lists of the form `((init op arg) op arg) op arg`
export
covering
hchainl : Monad m => ParseT m init -> ParseT m (init -> arg -> init) -> ParseT m arg -> ParseT m init
hchainl pini pop parg = pini >>= go
where
covering
go : init -> ParseT m init
go x = (do op <- pop
arg <- parg
go $ op x arg) <|> pure x
||| Parse right-nested lists of the form `arg op (arg op (arg op end))`
export
covering
hchainr : Monad m => ParseT m arg -> ParseT m (arg -> end -> end) -> ParseT m end -> ParseT m end
hchainr parg pop pend = go id <*> pend
where
covering
go : (end -> end) -> ParseT m (end -> end)
go f = (do arg <- parg
op <- pop
go $ f . op arg) <|> pure f
||| Always succeeds, applies the predicate `f` on chars until it fails and creates a string
||| from the results.
export
covering
takeWhile : Monad m => (Char -> Bool) -> ParseT m String
takeWhile f = pack <$> many (satisfy f)
||| Similar to `takeWhile` but fails if the resulting string is empty.
export
covering
takeWhile1 : Monad m => (Char -> Bool) -> ParseT m String
takeWhile1 f = pack <$> some (satisfy f)
||| Parses zero or more space characters
export
covering
spaces : Monad m => ParseT m ()
spaces = skip (many space)
||| Parses one or more space characters
export
covering
spaces1 : Monad m => ParseT m ()
spaces1 = skip (some space) <?> "whitespaces"
||| Discards brackets around a matching parser
export
parens : Monad m => ParseT m a -> ParseT m a
parens p = char '(' *> p <* char ')'
||| Discards whitespace after a matching parser
export
covering
lexeme : Monad m => ParseT m a -> ParseT m a
lexeme p = p <* spaces
||| Matches a specific string, then skips following whitespace
export
covering
token : Monad m => String -> ParseT m ()
token s = lexeme (skip $ string s) <?> "token " ++ show s
||| Matches a single digit
export
digit : Monad m => ParseT m (Fin 10)
digit = do x <- satisfy isDigit
case lookup x digits of
Nothing => fail "not a digit"
Just y => pure y
where
digits : List (Char, Fin 10)
digits = [ ('0', 0)
, ('1', 1)
, ('2', 2)
, ('3', 3)
, ('4', 4)
, ('5', 5)
, ('6', 6)
, ('7', 7)
, ('8', 8)
, ('9', 9)
]
fromDigits : Num a => (Fin 10 -> a) -> List (Fin 10) -> a
fromDigits f xs = foldl addDigit 0 xs
where
addDigit : a -> Fin 10 -> a
addDigit num d = 10*num + f d
intFromDigits : List (Fin 10) -> Integer
intFromDigits = fromDigits finToInteger
natFromDigits : List (Fin 10) -> Nat
natFromDigits = fromDigits finToNat
||| Matches a natural number
export
covering
natural : Monad m => ParseT m Nat
natural = natFromDigits <$> some digit
||| Matches an integer, eg. "12", "-4"
export
covering
integer : Monad m => ParseT m Integer
integer = do minus <- succeeds (char '-')
x <- some digit
pure $ if minus then (intFromDigits x)*(-1) else intFromDigits x
||| Parse repeated instances of at least one `p`, separated by `s`,
||| returning a list of successes.
|||
||| @ p the parser for items
||| @ s the parser for separators
export
covering
sepBy1 : Monad m => (p : ParseT m a)
-> (s : ParseT m b)
-> ParseT m (List1 a)
sepBy1 p s = [| p ::: many (s *> p) |]
||| Parse zero or more `p`s, separated by `s`s, returning a list of
||| successes.
|||
||| @ p the parser for items
||| @ s the parser for separators
export
covering
sepBy : Monad m => (p : ParseT m a)
-> (s : ParseT m b)
-> ParseT m (List a)
sepBy p s = optionMap [] forget (p `sepBy1` s)
||| Parses /one/ or more occurrences of `p` separated by `comma`.
export
covering
commaSep1 : Monad m => ParseT m a -> ParseT m (List1 a)
commaSep1 p = p `sepBy1` (char ',')
||| Parses /zero/ or more occurrences of `p` separated by `comma`.
export
covering
commaSep : Monad m => ParseT m a -> ParseT m (List a)
commaSep p = p `sepBy` (char ',')
||| Run the specified parser precisely `n` times, returning a vector
||| of successes.
export
ntimes : Monad m => (n : Nat) -> ParseT m a -> ParseT m (Vect n a)
ntimes Z p = pure Vect.Nil
ntimes (S n) p = [| p :: (ntimes n p) |]
|
(*
Author: Alexander Katovsky
*)
section "Yoneda"
theory Yoneda
imports NatTrans SetCat
begin
definition "YFtorNT' C f \<equiv> \<lparr>NTDom = Hom\<^bsub>C\<^esub>[\<midarrow>,dom\<^bsub>C\<^esub> f] , NTCod = Hom\<^bsub>C\<^esub>[\<midarrow>,cod\<^bsub>C\<^esub> f] ,
NatTransMap = \<lambda> B . Hom\<^bsub>C\<^esub>[B,f]\<rparr>"
definition "YFtorNT C f \<equiv> MakeNT (YFtorNT' C f)"
lemmas YFtorNT_defs = YFtorNT'_def YFtorNT_def MakeNT_def
lemma YFtorNTCatDom: "NTCatDom (YFtorNT C f) = Op C"
by (simp add: YFtorNT_defs NTCatDom_def HomFtorContraDom)
lemma YFtorNTCatCod: "NTCatCod (YFtorNT C f) = SET"
by (simp add: YFtorNT_defs NTCatCod_def HomFtorContraCod)
lemma YFtorNTApp1: assumes "X \<in> Obj (NTCatDom (YFtorNT C f))" shows "(YFtorNT C f) $$ X = Hom\<^bsub>C\<^esub>[X,f]"
proof-
have "(YFtorNT C f) $$ X = (YFtorNT' C f) $$ X" using assms by (simp add: MakeNTApp YFtorNT_def)
thus ?thesis by (simp add: YFtorNT'_def)
qed
definition
"YFtor' C \<equiv> \<lparr>
CatDom = C ,
CatCod = CatExp (Op C) SET ,
MapM = \<lambda> f . YFtorNT C f
\<rparr>"
definition "YFtor C \<equiv> MakeFtor(YFtor' C)"
lemmas YFtor_defs = YFtor'_def YFtor_def MakeFtor_def
lemma YFtorNTNatTrans':
assumes "LSCategory C" and "f \<in> Mor C"
shows "NatTransP (YFtorNT' C f)"
proof(auto simp only: NatTransP_def)
have Fd: "Ftor (NTDom (YFtorNT' C f)) : (Op C) \<longrightarrow> SET" using assms
by (simp add: HomFtorContraFtor Category.Cdom YFtorNT'_def)
have Fc: "Ftor (NTCod (YFtorNT' C f)) : (Op C) \<longrightarrow> SET" using assms
by (simp add: HomFtorContraFtor Category.Ccod YFtorNT'_def)
show "Functor (NTDom (YFtorNT' C f))" using Fd by auto
show "Functor (NTCod (YFtorNT' C f))" using Fc by auto
show "NTCatDom (YFtorNT' C f) = CatDom (NTCod (YFtorNT' C f))"
by(simp add: YFtorNT'_def NTCatDom_def HomFtorContraDom)
show "NTCatCod (YFtorNT' C f) = CatCod (NTDom (YFtorNT' C f))"
by(simp add: YFtorNT'_def NTCatCod_def HomFtorContraCod)
{
fix X assume a: "X \<in> Obj (NTCatDom (YFtorNT' C f))"
show "(YFtorNT' C f) $$ X maps\<^bsub>NTCatCod (YFtorNT' C f)\<^esub> (NTDom (YFtorNT' C f) @@ X) to (NTCod (YFtorNT' C f) @@ X)"
proof-
have Obj: "X \<in> Obj C" using a by (simp add: NTCatDom_def YFtorNT'_def HomFtorContraDom OppositeCategory_def)
have H1: "(Hom\<^bsub>C\<^esub>[\<midarrow>,dom\<^bsub>C\<^esub> f]) @@ X = Hom\<^bsub>C \<^esub>X dom\<^bsub>C\<^esub> f " using assms Obj by(simp add: HomFtorOpObj Category.Cdom)
have H2: "(Hom\<^bsub>C\<^esub>[\<midarrow>,cod\<^bsub>C\<^esub> f]) @@ X = Hom\<^bsub>C \<^esub>X cod\<^bsub>C\<^esub> f " using assms Obj by(simp add: HomFtorOpObj Category.Ccod)
have "Hom\<^bsub>C\<^esub>[X,f] maps\<^bsub>SET\<^esub> (Hom\<^bsub>C \<^esub>X dom\<^bsub>C\<^esub> f) to (Hom\<^bsub>C \<^esub>X cod\<^bsub>C\<^esub> f)" using assms Obj by (simp add: HomFtorMapsTo)
thus ?thesis using H1 H2 by(simp add: YFtorNT'_def NTCatCod_def NTCatDom_def HomFtorContraCod)
qed
}
{
fix g X Y assume a: "g maps\<^bsub>NTCatDom (YFtorNT' C f)\<^esub> X to Y"
show "((NTDom (YFtorNT' C f)) ## g) ;;\<^bsub>NTCatCod (YFtorNT' C f) \<^esub>(YFtorNT' C f $$ Y) =
((YFtorNT' C f) $$ X) ;;\<^bsub>NTCatCod (YFtorNT' C f) \<^esub>(NTCod (YFtorNT' C f) ## g)"
proof-
have M1: "g maps\<^bsub>Op C\<^esub> X to Y" using a by (auto simp add: NTCatDom_def YFtorNT'_def HomFtorContraDom)
have D1: "dom\<^bsub>C\<^esub> g = Y" and C1: "cod\<^bsub>C\<^esub> g = X" using M1 by (auto simp add: OppositeCategory_def)
have morf: "f \<in> Mor C" and morg: "g \<in> Mor C" using assms M1 by (auto simp add: OppositeCategory_def)
have H1: "(HomC\<^bsub>C\<^esub>[g,dom\<^bsub>C\<^esub> f]) = (Hom\<^bsub>C\<^esub>[\<midarrow>,dom\<^bsub>C\<^esub> f]) ## g"
and H2: "(HomC\<^bsub>C\<^esub>[g,cod\<^bsub>C\<^esub> f]) = (Hom\<^bsub>C\<^esub>[\<midarrow>,cod\<^bsub>C\<^esub> f]) ## g" using M1
by (auto simp add: HomFtorContra_def HomFtorContra'_def MakeFtor_def)
have "(HomC\<^bsub>C\<^esub>[g,dom\<^bsub>C\<^esub> f]) ;;\<^bsub>SET\<^esub> (Hom\<^bsub>C\<^esub>[dom\<^bsub>C\<^esub> g,f]) = (Hom\<^bsub>C\<^esub>[cod\<^bsub>C\<^esub> g,f]) ;;\<^bsub>SET\<^esub> (HomC\<^bsub>C\<^esub>[g,cod\<^bsub>C\<^esub> f])" using assms morf morg
by (simp add: HomCHom)
hence "((Hom\<^bsub>C\<^esub>[\<midarrow>,dom\<^bsub>C\<^esub> f]) ## g) ;;\<^bsub>SET\<^esub> (Hom\<^bsub>C\<^esub>[Y,f]) = (Hom\<^bsub>C\<^esub>[X,f]) ;;\<^bsub>SET\<^esub> ((Hom\<^bsub>C\<^esub>[\<midarrow>,cod\<^bsub>C\<^esub> f]) ## g)"
using H1 H2 D1 C1 by simp
thus ?thesis by (simp add: YFtorNT'_def NTCatCod_def HomFtorContraCod)
qed
}
qed
lemma YFtorNTNatTrans:
assumes "LSCategory C" and "f \<in> Mor C"
shows "NatTrans (YFtorNT C f)"
by (simp add: assms YFtorNTNatTrans' YFtorNT_def MakeNT)
lemma YFtorNTMor:
assumes "LSCategory C" and "f \<in> Mor C"
shows "YFtorNT C f \<in> Mor (CatExp (Op C) SET)"
proof(auto simp add: CatExp_def CatExp'_def MakeCatMor)
have "f \<in> Mor C" using assms by auto
thus "NatTrans (YFtorNT C f)" using assms by (simp add: YFtorNTNatTrans)
show "NTCatDom (YFtorNT C f) = Op C" by (simp add: YFtorNTCatDom)
show "NTCatCod (YFtorNT C f) = SET" by (simp add: YFtorNTCatCod)
qed
lemma YFtorNtMapsTo:
assumes "LSCategory C" and "f \<in> Mor C"
shows "YFtorNT C f maps\<^bsub>CatExp (Op C) SET\<^esub> (Hom\<^bsub>C\<^esub>[\<midarrow>,dom\<^bsub>C\<^esub> f]) to (Hom\<^bsub>C\<^esub>[\<midarrow>,cod\<^bsub>C\<^esub> f])"
proof(rule MapsToI)
have "f \<in> Mor C" using assms by auto
thus 1: "YFtorNT C f \<in> mor\<^bsub>CatExp (Op C) SET\<^esub>" using assms by (simp add: YFtorNTMor)
show "dom\<^bsub>CatExp (Op C) SET\<^esub> YFtorNT C f = Hom\<^bsub>C\<^esub>[\<midarrow>,dom\<^bsub>C\<^esub> f]" using 1 by(simp add:CatExpDom YFtorNT_defs)
show "cod\<^bsub>CatExp (Op C) SET\<^esub> YFtorNT C f = Hom\<^bsub>C\<^esub>[\<midarrow>,cod\<^bsub>C\<^esub> f]" using 1 by(simp add:CatExpCod YFtorNT_defs)
qed
lemma YFtorNTCompDef:
assumes "LSCategory C" and "f \<approx>>\<^bsub>C\<^esub> g"
shows "YFtorNT C f \<approx>>\<^bsub>CatExp (Op C) SET\<^esub> YFtorNT C g"
proof(rule CompDefinedI)
have "f \<in> Mor C" and "g \<in> Mor C" using assms by auto
hence 1: "YFtorNT C f maps\<^bsub>CatExp (Op C) SET\<^esub> (Hom\<^bsub>C\<^esub>[\<midarrow>,dom\<^bsub>C\<^esub> f]) to (Hom\<^bsub>C\<^esub>[\<midarrow>,cod\<^bsub>C\<^esub> f])"
and 2: "YFtorNT C g maps\<^bsub>CatExp (Op C) SET\<^esub> (Hom\<^bsub>C\<^esub>[\<midarrow>,dom\<^bsub>C\<^esub> g]) to (Hom\<^bsub>C\<^esub>[\<midarrow>,cod\<^bsub>C\<^esub> g])"
using assms by (simp add: YFtorNtMapsTo)+
thus "YFtorNT C f \<in> mor\<^bsub>CatExp (Op C) SET\<^esub>"
and "YFtorNT C g \<in> mor\<^bsub>CatExp (Op C) SET\<^esub>" by auto
have "cod\<^bsub>CatExp (Op C) SET\<^esub> YFtorNT C f = (Hom\<^bsub>C\<^esub>[\<midarrow>,cod\<^bsub>C\<^esub> f])" using 1 by auto
moreover have "dom\<^bsub>CatExp (Op C) SET\<^esub> YFtorNT C g = (Hom\<^bsub>C\<^esub>[\<midarrow>,dom\<^bsub>C\<^esub> g])" using 2 by auto
moreover have "cod\<^bsub>C\<^esub> f = dom\<^bsub>C\<^esub> g" using assms by auto
ultimately show "cod\<^bsub>CatExp (Op C) SET\<^esub> YFtorNT C f = dom\<^bsub>CatExp (Op C) SET\<^esub> YFtorNT C g" by simp
qed
lemma PreSheafCat: "LSCategory C \<Longrightarrow> Category (CatExp (Op C) SET)"
by(simp add: YFtor'_def OpCatCat SETCategory CatExpCat)
lemma YFtor'Obj1:
assumes "X \<in> Obj (CatDom (YFtor' C))" and "LSCategory C"
shows "(YFtor' C) ## (Id (CatDom (YFtor' C)) X) = Id (CatCod (YFtor' C)) (Hom\<^bsub>C \<^esub>[\<midarrow>,X])"
proof(simp add: YFtor'_def, rule NatTransExt)
have Obj: "X \<in> Obj C" using assms by (simp add: YFtor'_def)
have HomObj: "(Hom\<^bsub>C\<^esub>[\<midarrow>,X]) \<in> Obj (CatExp (Op C) SET)" using assms Obj by(simp add: CatExp_defs HomFtorContraFtor)
hence Id: "Id (CatExp (Op C) SET) (Hom\<^bsub>C\<^esub>[\<midarrow>,X]) \<in> Mor (CatExp (Op C) SET)" using assms
by (simp add: PreSheafCat Category.CatIdInMor)
have CAT: "Category(CatExp (Op C) SET)" using assms by (simp add: PreSheafCat)
have HomObj: "(Hom\<^bsub>C\<^esub>[\<midarrow>,X]) \<in> Obj (CatExp (Op C) SET)" using assms Obj
by(simp add: CatExp_defs HomFtorContraFtor)
show "NatTrans (YFtorNT C (Id C X))"
proof(rule YFtorNTNatTrans)
show "LSCategory C" using assms(2) .
show "Id C X \<in> Mor C" using assms Obj by (simp add: Category.CatIdInMor)
qed
show "NatTrans(Id (CatExp (Op C) SET) (Hom\<^bsub>C\<^esub>[\<midarrow>,X]))" using Id by (simp add: CatExp_defs)
show "NTDom (YFtorNT C (Id C X)) = NTDom (Id (CatExp (Op C) SET) (Hom\<^bsub>C\<^esub>[\<midarrow>,X]))"
proof(simp add: YFtorNT_defs)
have "Hom\<^bsub>C\<^esub>[\<midarrow>,dom\<^bsub>C\<^esub> (Id C X)] = Hom\<^bsub>C\<^esub>[\<midarrow>,X]" using assms Obj by (simp add: Category.CatIdDomCod)
also have "... = dom\<^bsub>CatExp (Op C) SET\<^esub> (Id (CatExp (Op C) SET) (Hom\<^bsub>C\<^esub>[\<midarrow>,X]))" using CAT HomObj
by (simp add: Category.CatIdDomCod)
also have "... = NTDom (Id (CatExp (Op C) SET) (Hom\<^bsub>C\<^esub>[\<midarrow>,X]))" using Id by (simp add: CatExpDom)
finally show "Hom\<^bsub>C\<^esub>[\<midarrow>,dom\<^bsub>C\<^esub> (Id C X)] = NTDom (Id (CatExp (Op C) SET) (Hom\<^bsub>C\<^esub>[\<midarrow>,X]))" .
qed
show "NTCod (YFtorNT C (Id C X)) = NTCod (Id (CatExp (Op C) SET) (Hom\<^bsub>C\<^esub>[\<midarrow>,X]))"
proof(simp add: YFtorNT_defs)
have "Hom\<^bsub>C\<^esub>[\<midarrow>,cod\<^bsub>C\<^esub> (Id C X)] = Hom\<^bsub>C\<^esub>[\<midarrow>,X]" using assms Obj by (simp add: Category.CatIdDomCod)
also have "... = cod\<^bsub>CatExp (Op C) SET\<^esub> (Id (CatExp (Op C) SET) (Hom\<^bsub>C\<^esub>[\<midarrow>,X]))" using CAT HomObj
by (simp add: Category.CatIdDomCod)
also have "... = NTCod (Id (CatExp (Op C) SET) (Hom\<^bsub>C\<^esub>[\<midarrow>,X]))" using Id by (simp add: CatExpCod)
finally show "Hom\<^bsub>C\<^esub>[\<midarrow>,cod\<^bsub>C\<^esub> (Id C X)] = NTCod (Id (CatExp (Op C) SET) (Hom\<^bsub>C\<^esub>[\<midarrow>,X]))" .
qed
{
fix Y assume a: "Y \<in> Obj (NTCatDom (YFtorNT C (Id C X)))"
show "(YFtorNT C (Id C X)) $$ Y = (Id (CatExp (Op C) SET) (Hom\<^bsub>C\<^esub>[\<midarrow>,X])) $$ Y"
proof-
have CD: "CatDom (Hom\<^bsub>C\<^esub>[\<midarrow>,X]) = Op C" by (simp add: HomFtorContraDom)
have CC: "CatCod (Hom\<^bsub>C\<^esub>[\<midarrow>,X]) = SET" by (simp add: HomFtorContraCod)
have ObjY: "Y \<in> Obj C" and ObjYOp: "Y \<in> Obj (Op C)" using a by(simp add: YFtorNTCatDom OppositeCategory_def)+
have "(YFtorNT C (Id C X)) $$ Y = (Hom\<^bsub>C\<^esub>[Y,(Id C X)])" using a by (simp add: YFtorNTApp1)
also have "... = id\<^bsub>SET\<^esub> (Hom\<^bsub>C \<^esub>Y X)" using Obj ObjY assms by (simp add: HomFtorId)
also have "... = id\<^bsub>SET\<^esub> ((Hom\<^bsub>C\<^esub>[\<midarrow>,X]) @@ Y)" using Obj ObjY assms by (simp add: HomFtorOpObj )
also have "... = (IdNatTrans (Hom\<^bsub>C\<^esub>[\<midarrow>,X])) $$ Y" using CD CC ObjYOp by (simp add: IdNatTrans_map)
also have "... = (Id (CatExp (Op C) SET) (Hom\<^bsub>C\<^esub>[\<midarrow>,X])) $$ Y" using HomObj by (simp add: CatExpId)
finally show ?thesis .
qed
}
qed
lemma YFtorPreFtor:
assumes "LSCategory C"
shows "PreFunctor (YFtor' C)"
proof(auto simp only: PreFunctor_def)
have CAT: "Category(CatExp (Op C) SET)" using assms by (simp add: PreSheafCat)
{
fix f g assume a: "f \<approx>>\<^bsub>CatDom (YFtor' C)\<^esub> g"
show "(YFtor' C) ## (f ;;\<^bsub>CatDom (YFtor' C)\<^esub> g) = ((YFtor' C) ## f) ;;\<^bsub>CatCod (YFtor' C)\<^esub> ((YFtor' C) ## g)"
proof(simp add: YFtor'_def, rule NatTransExt)
have CD: "f \<approx>>\<^bsub>C\<^esub> g" using a by (simp add: YFtor'_def)
have CD2: "YFtorNT C f \<approx>>\<^bsub>CatExp (Op C) SET\<^esub> YFtorNT C g" using CD assms by (simp add: YFtorNTCompDef)
have Mor1: "YFtorNT C f ;;\<^bsub>CatExp (Op C) SET\<^esub> YFtorNT C g \<in> Mor (CatExp (Op C) SET)" using CAT CD2
by (simp add: Category.MapsToMorDomCod)
show "NatTrans (YFtorNT C (f ;;\<^bsub>C\<^esub> g))" using assms by (simp add: Category.MapsToMorDomCod CD YFtorNTNatTrans)
show "NatTrans (YFtorNT C f ;;\<^bsub>CatExp (Op C) SET\<^esub> YFtorNT C g)" using Mor1 by (simp add: CatExpMorNT)
show "NTDom (YFtorNT C (f ;;\<^bsub>C\<^esub> g)) = NTDom (YFtorNT C f ;;\<^bsub>CatExp (Op C) SET\<^esub> YFtorNT C g)"
proof-
have 1: "YFtorNT C f \<in> mor\<^bsub>CatExp (Op C) SET\<^esub>" using CD2 by auto
have "NTDom (YFtorNT C (f ;;\<^bsub>C\<^esub> g)) = Hom\<^bsub>C\<^esub>[\<midarrow>,dom\<^bsub>C\<^esub> (f ;;\<^bsub>C\<^esub> g)]" by (simp add: YFtorNT_defs)
also have "... = Hom\<^bsub>C\<^esub>[\<midarrow>,dom\<^bsub>C\<^esub> f]" using CD assms by (simp add: Category.MapsToMorDomCod)
also have "... = NTDom (YFtorNT C f)" by (simp add: YFtorNT_defs)
also have "... = dom\<^bsub>CatExp (Op C) SET\<^esub> (YFtorNT C f)" using 1 by (simp add: CatExpDom)
also have "... = dom\<^bsub>CatExp (Op C) SET\<^esub> (YFtorNT C f ;;\<^bsub>CatExp (Op C) SET\<^esub> YFtorNT C g)" using CD2 CAT
by (simp add: Category.MapsToMorDomCod)
finally show ?thesis using Mor1 by (simp add: CatExpDom)
qed
show "NTCod (YFtorNT C (f ;;\<^bsub>C\<^esub> g)) = NTCod (YFtorNT C f ;;\<^bsub>CatExp (Op C) SET\<^esub> YFtorNT C g)"
proof-
have 1: "YFtorNT C g \<in> mor\<^bsub>CatExp (Op C) SET\<^esub>" using CD2 by auto
have "NTCod (YFtorNT C (f ;;\<^bsub>C\<^esub> g)) = Hom\<^bsub>C\<^esub>[\<midarrow>,cod\<^bsub>C\<^esub> (f ;;\<^bsub>C\<^esub> g)]" by (simp add: YFtorNT_defs)
also have "... = Hom\<^bsub>C\<^esub>[\<midarrow>,cod\<^bsub>C\<^esub> g]" using CD assms by (simp add: Category.MapsToMorDomCod)
also have "... = NTCod (YFtorNT C g)" by (simp add: YFtorNT_defs)
also have "... = cod\<^bsub>CatExp (Op C) SET\<^esub> (YFtorNT C g)" using 1 by (simp add: CatExpCod)
also have "... = cod\<^bsub>CatExp (Op C) SET\<^esub> (YFtorNT C f ;;\<^bsub>CatExp (Op C) SET\<^esub> YFtorNT C g)" using CD2 CAT
by (simp add: Category.MapsToMorDomCod)
finally show ?thesis using Mor1 by (simp add: CatExpCod)
qed
{
fix X assume a: "X \<in> Obj (NTCatDom (YFtorNT C (f ;;\<^bsub>C\<^esub> g)))"
show "YFtorNT C (f ;;\<^bsub>C\<^esub> g) $$ X = (YFtorNT C f ;;\<^bsub>CatExp (Op C) SET\<^esub> YFtorNT C g) $$ X"
proof-
have Obj: "X \<in> Obj C" and ObjOp: "X \<in> Obj (Op C)" using a by (simp add: YFtorNTCatDom OppositeCategory_def)+
have App1: "(Hom\<^bsub>C\<^esub>[X,f]) = (YFtorNT C f) $$ X"
and App2: "(Hom\<^bsub>C\<^esub>[X,g]) = (YFtorNT C g) $$ X" using a by (simp add: YFtorNTApp1 YFtorNTCatDom)+
have "(YFtorNT C (f ;;\<^bsub>C\<^esub> g)) $$ X = (Hom\<^bsub>C\<^esub>[X,(f ;;\<^bsub>C\<^esub> g)])" using a by (simp add: YFtorNTApp1)
also have "... = (Hom\<^bsub>C\<^esub>[X,f]) ;;\<^bsub>SET\<^esub> (Hom\<^bsub>C\<^esub>[X,g])" using CD assms Obj by (simp add: HomFtorDist)
also have "... = ((YFtorNT C f) $$ X) ;;\<^bsub>SET\<^esub> ((YFtorNT C g) $$ X)" using App1 App2 by simp
finally show ?thesis using ObjOp CD2 by (simp add: CatExpDist)
qed
}
qed
}
{
fix X assume a: "X \<in> Obj (CatDom (YFtor' C))"
show "\<exists> Y \<in> Obj (CatCod (YFtor' C)) . YFtor' C ## (Id (CatDom (YFtor' C)) X) = Id (CatCod (YFtor' C)) Y"
proof(rule_tac x="Hom\<^bsub>C \<^esub>[\<midarrow>,X]" in Set.rev_bexI)
have "X \<in> Obj C" using a by(simp add: YFtor'_def)
thus "Hom\<^bsub>C \<^esub>[\<midarrow>,X] \<in> Obj (CatCod (YFtor' C))" using assms by(simp add: YFtor'_def CatExp_defs HomFtorContraFtor)
show "(YFtor' C) ## (Id (CatDom (YFtor' C)) X) = Id (CatCod (YFtor' C)) (Hom\<^bsub>C \<^esub>[\<midarrow>,X])" using a assms
by (simp add: YFtor'Obj1)
qed
}
show "Category (CatDom (YFtor' C))" using assms by (simp add: YFtor'_def)
show "Category (CatCod (YFtor' C))" using CAT by (simp add: YFtor'_def)
qed
lemma YFtor'Obj:
assumes "X \<in> Obj (CatDom (YFtor' C))"
and "LSCategory C"
shows "(YFtor' C) @@ X = Hom\<^bsub>C \<^esub>[\<midarrow>,X]"
proof(rule PreFunctor.FmToFo, simp_all add: assms YFtor'Obj1 YFtorPreFtor)
have "X \<in> Obj C" using assms by(simp add: YFtor'_def)
thus "Hom\<^bsub>C \<^esub>[\<midarrow>,X] \<in> Obj (CatCod (YFtor' C))" using assms by(simp add: YFtor'_def CatExp_defs HomFtorContraFtor)
qed
lemma YFtorFtor':
assumes "LSCategory C"
shows "FunctorM (YFtor' C)"
proof(auto simp only: FunctorM_def)
show "PreFunctor (YFtor' C)" using assms by (rule YFtorPreFtor)
show "FunctorM_axioms (YFtor' C)"
proof(auto simp add:FunctorM_axioms_def)
{
fix f X Y assume aa: "f maps\<^bsub>CatDom (YFtor' C) \<^esub>X to Y"
show "YFtor' C ## f maps\<^bsub>CatCod (YFtor' C)\<^esub> YFtor' C @@ X to YFtor' C @@ Y"
proof-
have Mor1: "f maps\<^bsub>C\<^esub> X to Y" using aa by (simp add: YFtor'_def)
have "Category (CatDom (YFtor' C))" using assms by (simp add: YFtor'_def)
hence Obj1: "X \<in> Obj (CatDom (YFtor' C))" and
Obj2: "Y \<in> Obj (CatDom (YFtor' C))" using aa assms by (simp add: Category.MapsToObj)+
have "(YFtor' C ## f) = YFtorNT C f" by (simp add: YFtor'_def)
moreover have "YFtor' C @@ X = Hom\<^bsub>C \<^esub>[\<midarrow>,X]"
and "YFtor' C @@ Y = Hom\<^bsub>C \<^esub>[\<midarrow>,Y]" using Obj1 Obj2 assms by (simp add: YFtor'Obj)+
moreover have "CatCod (YFtor' C) = CatExp (Op C) SET" by (simp add: YFtor'_def)
moreover have "YFtorNT C f maps\<^bsub>CatExp (Op C) SET\<^esub> (Hom\<^bsub>C \<^esub>[\<midarrow>,X]) to (Hom\<^bsub>C \<^esub>[\<midarrow>,Y])"
using assms Mor1 by (auto simp add: YFtorNtMapsTo)
ultimately show ?thesis by simp
qed
}
qed
qed
lemma YFtorFtor: assumes "LSCategory C" shows "Ftor (YFtor C) : C \<longrightarrow> (CatExp (Op C) SET)"
proof(auto simp only: functor_abbrev_def)
show "Functor (YFtor C)" using assms by(simp add: MakeFtor YFtor_def YFtorFtor')
show "CatDom (YFtor C) = C" and "CatCod (YFtor C) = (CatExp (Op C) SET)"
using assms by(simp add: MakeFtor_def YFtor_def YFtor'_def)+
qed
lemma YFtorObj:
assumes "LSCategory C" and "X \<in> Obj C"
shows "(YFtor C) @@ X = Hom\<^bsub>C \<^esub>[\<midarrow>,X]"
proof-
have "CatDom (YFtor' C) = C" by (simp add: YFtor'_def)
moreover hence "(YFtor' C) @@ X = Hom\<^bsub>C \<^esub>[\<midarrow>,X]" using assms by(simp add: YFtor'Obj)
moreover have "PreFunctor (YFtor' C)" using assms by (simp add: YFtorPreFtor)
ultimately show ?thesis using assms by (simp add: MakeFtorObj YFtor_def)
qed
lemma YFtorObj2:
assumes "LSCategory C" and "X \<in> Obj C" and "Y \<in> Obj C"
shows "((YFtor C) @@ Y) @@ X = Hom\<^bsub>C \<^esub>X Y"
proof-
have "Hom\<^bsub>C \<^esub>X Y = ((Hom\<^bsub>C\<^esub>[\<midarrow>,Y]) @@ X)" using assms by (simp add: HomFtorOpObj)
also have "... = ((YFtor C @@ Y) @@ X)" using assms by (simp add: YFtorObj)
finally show ?thesis by simp
qed
lemma YFtorMor: "\<lbrakk>LSCategory C ; f \<in> Mor C\<rbrakk> \<Longrightarrow> (YFtor C) ## f = YFtorNT C f"
by (simp add: YFtor_defs MakeFtorMor)
(*
We can't do this because the presheaf category may not be locally small
definition
NatHom ("Nat\<index> _ _") where
"NatHom C F G \<equiv> Hom\<^bsub>CatExp (Op C) SET\<^esub> F G"
*)
definition "YMap C X \<eta> \<equiv> (\<eta> $$ X) |@| (m2z\<^bsub>C\<^esub> (id\<^bsub>C \<^esub>X))"
definition "YMapInv' C X F x \<equiv> \<lparr>
NTDom = ((YFtor C) @@ X),
NTCod = F,
NatTransMap = \<lambda> B . ZFfun (Hom\<^bsub>C\<^esub> B X) (F @@ B) (\<lambda> f . (F ## (z2m\<^bsub>C\<^esub> f)) |@| x)
\<rparr>"
definition "YMapInv C X F x \<equiv> MakeNT (YMapInv' C X F x)"
lemma YMapInvApp:
assumes "X \<in> Obj C" and "B \<in> Obj C" and "LSCategory C"
shows "(YMapInv C X F x) $$ B = ZFfun (Hom\<^bsub>C\<^esub> B X) (F @@ B) (\<lambda> f . (F ## (z2m\<^bsub>C\<^esub> f)) |@| x)"
proof-
have "NTCatDom (MakeNT (YMapInv' C X F x)) = CatDom (NTDom (YMapInv' C X F x))" by (simp add: MakeNT_def NTCatDom_def)
also have "... = CatDom (Hom\<^bsub>C\<^esub>[\<midarrow>,X])" using assms by (simp add: YFtorObj YMapInv'_def)
also have "... = Op C" using assms HomFtorContraFtor[of C X] by auto
finally have "NTCatDom (MakeNT (YMapInv' C X F x)) = Op C" .
hence 1: "B \<in> Obj (NTCatDom (MakeNT (YMapInv' C X F x)))" using assms by (simp add: OppositeCategory_def)
have "(YMapInv C X F x) $$ B = (MakeNT (YMapInv' C X F x)) $$ B" by (simp add: YMapInv_def)
also have "... = (YMapInv' C X F x) $$ B" using 1 by(simp add: MakeNTApp)
finally show ?thesis by (simp add: YMapInv'_def)
qed
lemma YMapImage:
assumes "LSCategory C" and "Ftor F : (Op C) \<longrightarrow> SET" and "X \<in> Obj C"
and "NT \<eta> : (YFtor C @@ X) \<Longrightarrow> F"
shows "(YMap C X \<eta>) |\<in>| (F @@ X)"
proof(simp only: YMap_def)
have "(YFtor C @@ X) = (Hom\<^bsub>C\<^esub>[\<midarrow>,X])" using assms by (auto simp add: YFtorObj)
moreover have "Ftor (Hom\<^bsub>C\<^esub>[\<midarrow>,X]) : (Op C) \<longrightarrow> SET" using assms by (simp add: HomFtorContraFtor)
ultimately have "CatDom (YFtor C @@ X) = Op C" by auto
hence Obj: "X \<in> Obj (CatDom (YFtor C @@ X))" using assms by (simp add: OppositeCategory_def)
moreover have "CatCod F = SET" using assms by auto
moreover have "\<eta> $$ X maps\<^bsub>CatCod F \<^esub>((YFtor C @@ X) @@ X) to (F @@ X)" using assms Obj by (simp add: NatTransMapsTo)
ultimately have "\<eta> $$ X maps\<^bsub>SET\<^esub> ((YFtor C @@ X) @@ X) to (F @@ X)" by simp
moreover have "(m2z\<^bsub>C \<^esub>(Id C X)) |\<in>| ((YFtor C @@ X) @@ X)"
proof-
have "(Id C X) maps\<^bsub>C \<^esub>X to X" using assms by (simp add: Category.Simps)
moreover have "((YFtor C @@ X) @@ X) = Hom\<^bsub>C\<^esub> X X" using assms by (simp add: YFtorObj2)
ultimately show ?thesis using assms by (simp add: LSCategory.m2zz2m)
qed
ultimately show "((\<eta> $$ X) |@| (m2z\<^bsub>C \<^esub>(Id C X))) |\<in>| (F @@ X)" by (simp add: SETfunDomAppCod)
qed
lemma YMapInvNatTransP:
assumes "LSCategory C" and "Ftor F : (Op C) \<longrightarrow> SET" and xobj: "X \<in> Obj C" and xinF: "x |\<in>| (F @@ X)"
shows "NatTransP (YMapInv' C X F x)"
proof(auto simp only: NatTransP_def, simp_all add: YMapInv'_def NTCatCod_def NTCatDom_def)
have yf: "(YFtor C @@ X) = Hom\<^bsub>C\<^esub>[\<midarrow>,X]" using assms by (simp add: YFtorObj)
hence hf: "Ftor (YFtor C @@ X) : (Op C) \<longrightarrow> SET" using assms by (simp add: HomFtorContraFtor)
thus "Functor (YFtor C @@ X)" by auto
show ftf: "Functor F" using assms by auto
have df: "CatDom F = Op C" and cf: "CatCod F = SET" using assms by auto
have dy: "CatDom ((YFtor C) @@ X) = Op C" and cy: "CatCod ((YFtor C) @@ X) = SET" using hf by auto
show "CatDom ((YFtor C) @@ X) = CatDom F" using df dy by simp
show "CatCod F = CatCod ((YFtor C) @@ X)" using cf cy by simp
{
fix Y assume yobja: "Y \<in> Obj (CatDom ((YFtor C) @@ X))"
show "ZFfun (Hom\<^bsub>C\<^esub> Y X) (F @@ Y) (\<lambda>f. (F ## (z2m\<^bsub>C \<^esub>f)) |@| x) maps\<^bsub>CatCod F\<^esub> ((YFtor C @@ X) @@ Y) to (F @@ Y)"
proof(simp add: cf, rule MapsToI)
have yobj: "Y \<in> Obj C" using yobja dy by (simp add: OppositeCategory_def)
have zffun: "isZFfun (ZFfun (Hom\<^bsub>C\<^esub> Y X) (F @@ Y) (\<lambda>f. (F ## z2m\<^bsub>C\<^esub>f) |@| x))"
proof(rule SETfun, rule allI, rule impI)
{
fix y assume yhom: "y |\<in>| (Hom\<^bsub>C\<^esub> Y X)" show "(F ## (z2m\<^bsub>C \<^esub>y)) |@| x |\<in>| (F @@ Y)"
proof-
let ?f = "(F ## (z2m\<^bsub>C \<^esub>y))"
have "(z2m\<^bsub>C \<^esub>y) maps\<^bsub>C\<^esub> Y to X" using yhom yobj assms by (simp add: LSCategory.z2mm2z)
hence "(z2m\<^bsub>C \<^esub>y) maps\<^bsub>Op C\<^esub> X to Y" by (simp add: MapsToOp)
hence "?f maps\<^bsub>SET\<^esub> (F @@ X) to (F @@ Y)" using assms by (simp add: FunctorMapsTo)
hence "isZFfun (?f)" and "|dom| ?f = F @@ X" and "|cod| ?f = F @@ Y" by (simp add: SETmapsTo)+
thus "(?f |@| x) |\<in>| (F @@ Y)" using assms ZFfunDomAppCod[of ?f x] by simp
qed
}
qed
show "ZFfun (Hom\<^bsub>C\<^esub> Y X) (F @@ Y) (\<lambda>f. (F ## z2m\<^bsub>C\<^esub>f) |@| x) \<in> mor\<^bsub>SET\<^esub>" using zffun
by(simp add: SETmor)
show "cod\<^bsub>SET\<^esub> ZFfun (Hom\<^bsub>C\<^esub> Y X) (F @@ Y) (\<lambda>f. (F ## z2m\<^bsub>C\<^esub>f) |@| x) = F @@ Y" using zffun
by(simp add: SETcod)
have "(Hom\<^bsub>C\<^esub> Y X) = (YFtor C @@ X) @@ Y" using assms yobj by (simp add: YFtorObj2)
thus "dom\<^bsub>SET\<^esub> ZFfun (Hom\<^bsub>C\<^esub> Y X) (F @@ Y) (\<lambda>f. (F ## z2m\<^bsub>C\<^esub>f) |@| x) = (YFtor C @@ X) @@ Y" using zffun
by(simp add: SETdom)
qed
}
{
fix f Z Y assume fmaps: "f maps\<^bsub>CatDom ((YFtor C ) @@ X)\<^esub> Z to Y"
have fmapsa: "f maps\<^bsub>Op C\<^esub> Z to Y" using fmaps dy by simp
hence fmapsb: "f maps\<^bsub>C\<^esub> Y to Z" by (rule MapsToOpOp)
hence fmor: "f \<in> Mor C" and fdom: "dom\<^bsub>C\<^esub> f = Y" and fcod: "cod\<^bsub>C\<^esub> f = Z" by (auto simp add: OppositeCategory_def)
hence hc: "(Hom\<^bsub>C\<^esub>[\<midarrow>,X]) ## f = (HomC\<^bsub>C\<^esub>[f,X])" using assms by (simp add: HomContraMor)
have yobj: "Y \<in> Obj C" and zobj: "Z \<in> Obj C" using fmapsb assms by (simp add: Category.MapsToObj)+
have Ffmaps: "(F ## f) maps\<^bsub>SET\<^esub> (F @@ Z) to (F @@ Y)" using assms fmapsa by (simp add: FunctorMapsTo)
have Fzmaps: "\<And> h A B . \<lbrakk>h |\<in>| (Hom\<^bsub>C\<^esub> A B) ; A \<in> Obj C ; B \<in> Obj C\<rbrakk> \<Longrightarrow>
(F ## (z2m\<^bsub>C \<^esub>h)) maps\<^bsub>SET\<^esub> (F @@ B) to (F @@ A)"
proof-
fix h A B assume h: "h |\<in>| (Hom\<^bsub>C\<^esub> A B)" and oA: "A \<in> Obj C" and oB: "B \<in> Obj C"
have "(z2m\<^bsub>C \<^esub>h) maps\<^bsub>C\<^esub> A to B" using assms h oA oB by (simp add: LSCategory.z2mm2z)
hence "(z2m\<^bsub>C \<^esub>h) maps\<^bsub>Op C\<^esub> B to A" by (rule MapsToOp)
thus "(F ## (z2m\<^bsub>C \<^esub>h)) maps\<^bsub>SET\<^esub> (F @@ B) to (F @@ A)" using assms by (simp add: FunctorMapsTo)
qed
have hHomF: "\<And>h. h |\<in>| (Hom\<^bsub>C\<^esub> Z X) \<Longrightarrow> (F ## (z2m\<^bsub>C \<^esub>h)) |@| x |\<in>| (F @@ Z)" using xobj zobj xinF
proof-
fix h assume h: "h |\<in>| (Hom\<^bsub>C\<^esub> Z X)"
have "(F ## (z2m\<^bsub>C \<^esub>h)) maps\<^bsub>SET\<^esub> (F @@ X) to (F @@ Z)" using xobj zobj h by (simp add: Fzmaps)
thus "(F ## (z2m\<^bsub>C \<^esub>h)) |@| x |\<in>| (F @@ Z)" using assms by (simp add: SETfunDomAppCod)
qed
have Ff: "F ## f = ZFfun (F @@ Z) (F @@ Y) (\<lambda>h. (F ## f) |@| h)" using Ffmaps by (simp add: SETZFfun)
have compdefa: "ZFfun (Hom\<^bsub>C\<^esub> Z X) (Hom\<^bsub>C\<^esub> Y X) (\<lambda>h. m2z\<^bsub>C \<^esub>(f ;;\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>h))) \<approx>>\<^bsub>SET\<^esub>
ZFfun (Hom\<^bsub>C\<^esub> Y X) (F @@ Y) (\<lambda>h. (F ## (z2m\<^bsub>C \<^esub>h)) |@| x)"
proof(rule CompDefinedI, simp_all add: SETmor[THEN sym])
show "isZFfun (ZFfun (Hom\<^bsub>C\<^esub> Z X) (Hom\<^bsub>C\<^esub> Y X) (\<lambda>h. m2z\<^bsub>C \<^esub>(f ;;\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>h))))"
proof(rule SETfun, rule allI, rule impI)
fix h assume h: "h |\<in>| (Hom\<^bsub>C\<^esub> Z X)"
have "(z2m\<^bsub>C \<^esub>h) maps\<^bsub>C\<^esub> Z to X" using assms h xobj zobj by (simp add: LSCategory.z2mm2z)
hence "f ;;\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>h) maps\<^bsub>C\<^esub> Y to X" using fmapsb assms(1) by (simp add: Category.Ccompt)
thus "(m2z\<^bsub>C\<^esub> (f ;;\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>h))) |\<in>| (Hom\<^bsub>C\<^esub> Y X)" using assms by (simp add: LSCategory.m2zz2m)
qed
moreover show "isZFfun (ZFfun (Hom\<^bsub>C\<^esub> Y X) (F @@ Y) (\<lambda>h. (F ## (z2m\<^bsub>C \<^esub>h)) |@| x))"
proof(rule SETfun, rule allI, rule impI)
fix h assume h: "h |\<in>| (Hom\<^bsub>C\<^esub> Y X)"
have "(F ## (z2m\<^bsub>C \<^esub>h)) maps\<^bsub>SET\<^esub> (F @@ X) to (F @@ Y)" using xobj yobj h by (simp add: Fzmaps)
thus "(F ## (z2m\<^bsub>C \<^esub>h)) |@| x |\<in>| (F @@ Y)" using assms by (simp add: SETfunDomAppCod)
qed
ultimately show "cod\<^bsub>SET\<^esub>(ZFfun (Hom\<^bsub>C\<^esub> Z X) (Hom\<^bsub>C\<^esub> Y X) (\<lambda>h. m2z\<^bsub>C \<^esub>(f ;;\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>h)))) =
dom\<^bsub>SET\<^esub>(ZFfun (Hom\<^bsub>C\<^esub> Y X) (F @@ Y) (\<lambda>h. (F ## (z2m\<^bsub>C \<^esub>h)) |@| x))" by (simp add: SETcod SETdom)
qed
have compdefb: "ZFfun (Hom\<^bsub>C\<^esub> Z X) (F @@ Z) (\<lambda>h. (F ## (z2m\<^bsub>C \<^esub>h)) |@| x) \<approx>>\<^bsub>SET\<^esub>
ZFfun (F @@ Z) (F @@ Y) (\<lambda>h. (F ## f) |@| h)"
proof(rule CompDefinedI, simp_all add: SETmor[THEN sym])
show "isZFfun (ZFfun (Hom\<^bsub>C\<^esub> Z X) (F @@ Z) (\<lambda>h. (F ## (z2m\<^bsub>C \<^esub>h)) |@| x))" using hHomF by (simp add: SETfun)
moreover show "isZFfun (ZFfun (F @@ Z) (F @@ Y) (\<lambda>h. (F ## f) |@| h))"
proof(rule SETfun, rule allI, rule impI)
fix h assume h: "h |\<in>| (F @@ Z)"
have "F ## f maps\<^bsub>SET\<^esub> F @@ Z to F @@ Y" using Ffmaps .
thus "(F ## f) |@| h |\<in>| (F @@ Y)" using h by (simp add: SETfunDomAppCod)
qed
ultimately show "cod\<^bsub>SET\<^esub> (ZFfun (Hom\<^bsub>C\<^esub> Z X) (F @@ Z) (\<lambda>h. (F ## (z2m\<^bsub>C \<^esub>h)) |@| x)) =
dom\<^bsub>SET\<^esub> (ZFfun (F @@ Z) (F @@ Y) (\<lambda>h. (F ## f) |@| h))" by (simp add: SETcod SETdom)
qed
have "ZFfun (Hom\<^bsub>C\<^esub> Z X) (Hom\<^bsub>C\<^esub> Y X) (\<lambda>h. m2z\<^bsub>C \<^esub>(f ;;\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>h))) ;;\<^bsub>SET\<^esub>
ZFfun (Hom\<^bsub>C\<^esub> Y X) (F @@ Y) (\<lambda>h. (F ## (z2m\<^bsub>C \<^esub>h)) |@| x) =
ZFfun (Hom\<^bsub>C\<^esub> Z X) (Hom\<^bsub>C\<^esub> Y X) (\<lambda>h. m2z\<^bsub>C \<^esub>(f ;;\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>h))) |o|
ZFfun (Hom\<^bsub>C\<^esub> Y X) (F @@ Y) (\<lambda>h. (F ## (z2m\<^bsub>C \<^esub>h)) |@| x)" using Ff compdefa by (simp add: SETComp)
also have "... = ZFfun (Hom\<^bsub>C\<^esub> Z X) (F @@ Y) ((\<lambda>h. (F ## (z2m\<^bsub>C \<^esub>h)) |@| x) o (\<lambda>h. m2z\<^bsub>C \<^esub>(f ;;\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>h))))"
proof(rule ZFfunComp, rule allI, rule impI)
{
fix h assume h: "h |\<in>| (Hom\<^bsub>C\<^esub> Z X)"
show "(m2z\<^bsub>C \<^esub>(f ;;\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>h))) |\<in>| (Hom\<^bsub>C\<^esub> Y X)"
proof-
have "Z \<in> Obj C" using fmapsb assms by (simp add: Category.MapsToObj)
hence "(z2m\<^bsub>C \<^esub>h) maps\<^bsub>C\<^esub> Z to X" using assms h by (simp add: LSCategory.z2mm2z)
hence "f ;;\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>h) maps\<^bsub>C\<^esub> Y to X" using fmapsb assms(1) by (simp add: Category.Ccompt)
thus ?thesis using assms by (simp add: LSCategory.m2zz2m)
qed
}
qed
also have "... = ZFfun (Hom\<^bsub>C\<^esub> Z X) (F @@ Y) ((\<lambda>h. (F ## f) |@| h) o (\<lambda>h. (F ## (z2m\<^bsub>C \<^esub>h)) |@| x))"
proof(rule ZFfun_ext, rule allI, rule impI, simp)
{
fix h assume h: "h |\<in>| (Hom\<^bsub>C\<^esub> Z X)"
have zObj: "Z \<in> Obj C" using fmapsb assms by (simp add: Category.MapsToObj)
hence hmaps: "(z2m\<^bsub>C \<^esub>h) maps\<^bsub>C\<^esub> Z to X" using assms h by (simp add: LSCategory.z2mm2z)
hence "(z2m\<^bsub>C \<^esub>h) \<in> Mor C" and "dom\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>h) = cod\<^bsub>C\<^esub> f" using fcod by auto
hence CompDef_hf: "f \<approx>>\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>h)" using fmor by auto
hence CompDef_hfOp: "(z2m\<^bsub>C \<^esub>h) \<approx>>\<^bsub>Op C\<^esub> f" by (simp add: CompDefOp)
hence CompDef_FhfOp: "(F ## (z2m\<^bsub>C \<^esub>h)) \<approx>>\<^bsub>SET\<^esub> (F ## f)" using assms by (simp add: FunctorCompDef)
hence "(z2m\<^bsub>C \<^esub>h) maps\<^bsub>Op C\<^esub> X to Z" using hmaps by (simp add: MapsToOp)
hence "(F ## (z2m\<^bsub>C \<^esub>h)) maps\<^bsub>SET\<^esub> (F @@ X) to (F @@ Z)" using assms by (simp add: FunctorMapsTo)
hence xin: "x |\<in>| |dom|(F ## (z2m\<^bsub>C \<^esub>h))" using assms by (simp add: SETmapsTo)
have "(f ;;\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>h)) \<in> Mor C" using CompDef_hf assms by(simp add: Category.MapsToMorDomCod)
hence "(F ## (z2m\<^bsub>C \<^esub>(m2z\<^bsub>C \<^esub>(f ;;\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>h))))) |@| x = (F ## (f ;;\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>h))) |@| x"
using assms by (simp add: LSCategory.m2zz2mInv)
also have "... = (F ## ((z2m\<^bsub>C \<^esub>h) ;;\<^bsub>Op C\<^esub> f)) |@| x" by (simp add: OppositeCategory_def)
also have "... = ((F ## (z2m\<^bsub>C \<^esub>h)) ;;\<^bsub>SET \<^esub>(F ## f)) |@| x" using assms CompDef_hfOp by (simp add: FunctorComp)
also have "... = (F ## f) |@| ((F ## (z2m\<^bsub>C \<^esub>h)) |@| x)" using CompDef_FhfOp xin by(rule SETCompAt)
finally show "(F ## (z2m\<^bsub>C \<^esub>(m2z\<^bsub>C \<^esub>(f ;;\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>h))))) |@| x = (F ## f) |@| ((F ## (z2m\<^bsub>C \<^esub>h)) |@| x)" .
}
qed
also have "... = ZFfun (Hom\<^bsub>C\<^esub> Z X) (F @@ Z) (\<lambda>h. (F ## (z2m\<^bsub>C \<^esub>h)) |@| x) |o|
ZFfun (F @@ Z) (F @@ Y) (\<lambda>h. (F ## f) |@| h)"
by(rule ZFfunComp[THEN sym], rule allI, rule impI, simp add: hHomF)
also have "... = ZFfun (Hom\<^bsub>C\<^esub> Z X) (F @@ Z) (\<lambda>h. (F ## (z2m\<^bsub>C \<^esub>h)) |@| x) ;;\<^bsub>SET\<^esub> (F ## f)"
using Ff compdefb by (simp add: SETComp)
finally show "(((YFtor C) @@ X) ## f) ;;\<^bsub>CatCod F\<^esub> ZFfun (Hom\<^bsub>C\<^esub> Y X) (F @@ Y) (\<lambda>f. (F ## (z2m\<^bsub>C \<^esub>f)) |@| x) =
ZFfun (Hom\<^bsub>C\<^esub> Z X) (F @@ Z) (\<lambda>f. (F ## (z2m\<^bsub>C \<^esub>f)) |@| x) ;;\<^bsub>CatCod F\<^esub> (F ## f)"
by(simp add: cf yf hc fdom fcod HomFtorMapContra_def)
}
qed
lemma YMapInvNatTrans:
assumes "LSCategory C" and "Ftor F : (Op C) \<longrightarrow> SET" and "X \<in> Obj C" and "x |\<in>| (F @@ X)"
shows "NatTrans (YMapInv C X F x)"
by (simp add: assms YMapInv_def MakeNT YMapInvNatTransP)
lemma YMapInvImage:
assumes "LSCategory C" and "Ftor F : (Op C) \<longrightarrow> SET" and "X \<in> Obj C"
and "x |\<in>| (F @@ X)"
shows "NT (YMapInv C X F x) : (YFtor C @@ X) \<Longrightarrow> F"
proof(auto simp only: nt_abbrev_def)
show "NatTrans (YMapInv C X F x)" using assms by (simp add: YMapInvNatTrans)
show "NTDom (YMapInv C X F x) = YFtor C @@ X" by(simp add: YMapInv_def MakeNT_def YMapInv'_def)
show "NTCod (YMapInv C X F x) = F" by(simp add: YMapInv_def MakeNT_def YMapInv'_def)
qed
lemma YMap1:
assumes LSCat: "LSCategory C" and Fftor: "Ftor F : (Op C) \<longrightarrow> SET" and XObj: "X \<in> Obj C"
and NT: "NT \<eta> : (YFtor C @@ X) \<Longrightarrow> F"
shows "YMapInv C X F (YMap C X \<eta>) = \<eta>"
proof(rule NatTransExt)
have "(YMap C X \<eta>) |\<in>| (F @@ X)" using assms by (simp add: YMapImage)
hence 1: "NT (YMapInv C X F (YMap C X \<eta>)) : (YFtor C @@ X) \<Longrightarrow> F" using assms by (simp add: YMapInvImage)
thus "NatTrans (YMapInv C X F (YMap C X \<eta>))" by auto
show "NatTrans \<eta>" using assms by auto
have NTDYI: "NTDom (YMapInv C X F (YMap C X \<eta>)) = (YFtor C @@ X)" using 1 by auto
moreover have NTDeta: "NTDom \<eta> = (YFtor C @@ X)" using assms by auto
ultimately show "NTDom (YMapInv C X F (YMap C X \<eta>)) = NTDom \<eta>" by simp
have "NTCod (YMapInv C X F (YMap C X \<eta>)) = F" using 1 by auto
moreover have NTCeta: "NTCod \<eta> = F" using assms by auto
ultimately show "NTCod (YMapInv C X F (YMap C X \<eta>)) = NTCod \<eta>" by simp
{
fix Y assume Yobja: "Y \<in> Obj (NTCatDom (YMapInv C X F (YMap C X \<eta>)))"
have CCF: "CatCod F = SET" using assms by auto
have "Ftor (Hom\<^bsub>C\<^esub>[\<midarrow>,X]) : (Op C) \<longrightarrow> SET" using LSCat XObj by (simp add: HomFtorContraFtor)
hence CDH: "CatDom (Hom\<^bsub>C\<^esub>[\<midarrow>,X]) = Op C" by auto
hence CDYF: "CatDom (YFtor C @@ X) = Op C" using XObj LSCat by (auto simp add: YFtorObj)
hence "NTCatDom (YMapInv C X F (YMap C X \<eta>)) = Op C" using LSCat XObj NTDYI CDH by (simp add: NTCatDom_def)
hence YObjOp: "Y \<in> Obj (Op C)" using Yobja by simp
hence YObj: "Y \<in> Obj C" and XObjOp: "X \<in> Obj (Op C)" using XObj by (simp add: OppositeCategory_def)+
have yinv_mapsTo: "((YMapInv C X F (YMap C X \<eta>)) $$ Y) maps\<^bsub>SET\<^esub> (Hom\<^bsub>C \<^esub>Y X) to (F @@ Y)"
proof-
have "((YMapInv C X F (YMap C X \<eta>)) $$ Y) maps\<^bsub>SET\<^esub> ((YFtor C @@ X) @@ Y) to (F @@ Y)"
using 1 CCF CDYF YObjOp NatTransMapsTo[of "(YMapInv C X F (YMap C X \<eta>))" "(YFtor C @@ X)" F Y] by simp
thus ?thesis using LSCat XObj YObj by (simp add: YFtorObj2)
qed
have eta_mapsTo: "(\<eta> $$ Y) maps\<^bsub>SET\<^esub> (Hom\<^bsub>C \<^esub>Y X) to (F @@ Y)"
proof-
have "(\<eta> $$ Y) maps\<^bsub>SET\<^esub> ((YFtor C @@ X) @@ Y) to (F @@ Y)"
using NT CDYF CCF YObjOp NatTransMapsTo[of \<eta> "(YFtor C @@ X)" F Y] by simp
thus ?thesis using LSCat XObj YObj by (simp add: YFtorObj2)
qed
show "(YMapInv C X F (YMap C X \<eta>)) $$ Y = \<eta> $$ Y"
proof(rule ZFfunExt)
show "|dom|(YMapInv C X F (YMap C X \<eta>) $$ Y) = |dom|(\<eta> $$ Y)"
using yinv_mapsTo eta_mapsTo by (simp add: SETmapsTo)
show "|cod|(YMapInv C X F (YMap C X \<eta>) $$ Y) = |cod|(\<eta> $$ Y)"
using yinv_mapsTo eta_mapsTo by (simp add: SETmapsTo)
show "isZFfun (YMapInv C X F (YMap C X \<eta>) $$ Y)"
using yinv_mapsTo by (simp add: SETmapsTo)
show "isZFfun (\<eta> $$ Y)"
using eta_mapsTo by (simp add: SETmapsTo)
{
fix f assume fdomYinv: "f |\<in>| |dom|(YMapInv C X F (YMap C X \<eta>) $$ Y)"
have fHom: "f |\<in>| (Hom\<^bsub>C\<^esub> Y X)" using yinv_mapsTo fdomYinv by (simp add: SETmapsTo)
hence fMapsTo: "(z2m\<^bsub>C \<^esub>f) maps\<^bsub>C \<^esub>Y to X" using assms YObj by (simp add: LSCategory.z2mm2z)
hence fCod: "(cod\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>f)) = X" and fDom: "(dom\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>f)) = Y" and fMor: "(z2m\<^bsub>C \<^esub>f) \<in> Mor C" by auto
have "(YMapInv C X F (YMap C X \<eta>) $$ Y) |@| f =
(F ## (z2m\<^bsub>C \<^esub>f)) |@| ((\<eta> $$ X) |@| (m2z\<^bsub>C \<^esub>(Id C X)))"
using fHom assms YObj by (simp add: ZFfunApp YMapInvApp YMap_def)
also have "... = ((\<eta> $$ X) ;;\<^bsub>SET\<^esub> (F ## (z2m\<^bsub>C \<^esub>f))) |@| (m2z\<^bsub>C \<^esub>(Id C X))"
proof-
have aa: "(\<eta> $$ X) maps\<^bsub>SET\<^esub> ((YFtor C @@ X) @@ X) to (F @@ X)"
using NT CDYF CCF YObjOp XObjOp NatTransMapsTo[of \<eta> "(YFtor C @@ X)" F X] by simp
have bb: "(F ## (z2m\<^bsub>C \<^esub>f)) maps\<^bsub>SET\<^esub> (F @@ X) to (F @@ Y)"
using fMapsTo Fftor by (simp add: MapsToOp FunctorMapsTo)
have "(\<eta> $$ X) \<approx>>\<^bsub>SET\<^esub> (F ## (z2m\<^bsub>C \<^esub>f))" using aa bb by (simp add: MapsToCompDef)
moreover have "(m2z\<^bsub>C \<^esub>(Id C X)) |\<in>| |dom| (\<eta> $$ X)" using assms aa
by (simp add: SETmapsTo YFtorObj2 Category.Cidm LSCategory.m2zz2m)
ultimately show ?thesis by (simp add: SETCompAt)
qed
also have "... = ((HomC\<^bsub>C\<^esub>[z2m\<^bsub>C \<^esub>f,X]) ;;\<^bsub>SET\<^esub> (\<eta> $$ Y)) |@| (m2z\<^bsub>C \<^esub>(Id C X))"
proof-
have "NTDom \<eta> = (Hom\<^bsub>C\<^esub>[\<midarrow>,X])" using NTDeta assms by (simp add: YFtorObj)
moreover hence "NTCatDom \<eta> = Op C" by (simp add: NTCatDom_def HomFtorContraDom)
moreover have "NTCatCod \<eta> = SET" using assms by (auto simp add: NTCatCod_def)
moreover have "NatTrans \<eta>" and "NTCod \<eta> = F" using assms by auto
moreover have "(z2m\<^bsub>C \<^esub>f) maps\<^bsub>Op C \<^esub>X to Y"
using fMapsTo MapsToOp[where ?f = "(z2m\<^bsub>C \<^esub>f)" and ?X = Y and ?Y = X and ?C = C] by simp
ultimately have "(\<eta> $$ X) ;;\<^bsub>SET\<^esub> (F ## (z2m\<^bsub>C \<^esub>f)) = ((Hom\<^bsub>C\<^esub>[\<midarrow>,X]) ## (z2m\<^bsub>C \<^esub>f)) ;;\<^bsub>SET\<^esub> (\<eta> $$ Y)"
using NatTransP.NatTrans[of \<eta> "(z2m\<^bsub>C \<^esub>f)" X Y] by simp
moreover have "((Hom\<^bsub>C\<^esub>[\<midarrow>,X]) ## (z2m\<^bsub>C \<^esub>f)) = (HomC\<^bsub>C\<^esub>[(z2m\<^bsub>C \<^esub>f),X])" using assms fMor by (simp add: HomContraMor)
ultimately show ?thesis by simp
qed
also have "... = (\<eta> $$ Y) |@| ((HomC\<^bsub>C\<^esub>[z2m\<^bsub>C \<^esub>f,X]) |@| (m2z\<^bsub>C \<^esub>(Id C X)))"
proof-
have "(HomC\<^bsub>C\<^esub>[z2m\<^bsub>C \<^esub>f,X]) \<approx>>\<^bsub>SET\<^esub> (\<eta> $$ Y)"
using fCod fDom XObj LSCat fMor HomFtorContraMapsTo[of C X "z2m\<^bsub>C \<^esub>f"] eta_mapsTo by (simp add: MapsToCompDef)
moreover have "|dom| (HomC\<^bsub>C\<^esub>[z2m\<^bsub>C \<^esub>f,X]) = (Hom\<^bsub>C\<^esub> (cod\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>f)) X)"
by (simp add: ZFfunDom HomFtorMapContra_def)
moreover have "(m2z\<^bsub>C \<^esub>(Id C X)) |\<in>| (Hom\<^bsub>C\<^esub> (cod\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>f)) X)"
using assms fCod by (simp add: Category.Cidm LSCategory.m2zz2m)
ultimately show ?thesis by (simp add: SETCompAt)
qed
also have "... = (\<eta> $$ Y) |@| (m2z\<^bsub>C\<^esub> ((z2m\<^bsub>C \<^esub>f) ;;\<^bsub>C\<^esub> (z2m\<^bsub>C\<^esub> (m2z\<^bsub>C \<^esub>(Id C X)))))"
proof-
have "(Id C X) maps\<^bsub>C\<^esub> (cod\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>f)) to X" using assms fCod by (simp add: Category.Cidm)
hence "(m2z\<^bsub>C \<^esub>(Id C X)) |\<in>| (Hom\<^bsub>C\<^esub> (cod\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>f)) X)" using assms by (simp add: LSCategory.m2zz2m)
thus ?thesis by (simp add: HomContraAt)
qed
also have "... = (\<eta> $$ Y) |@| (m2z\<^bsub>C\<^esub> ((z2m\<^bsub>C \<^esub>f) ;;\<^bsub>C\<^esub> (Id C X)))"
using assms by (simp add: LSCategory.m2zz2mInv Category.CatIdInMor)
also have "... = (\<eta> $$ Y) |@| (m2z\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>f))" using assms(1) fCod fMor Category.Cidr[of C "(z2m\<^bsub>C \<^esub>f)"] by (simp)
also have "... = (\<eta> $$ Y) |@| f" using assms YObj fHom by (simp add: LSCategory.z2mm2z)
finally show "(YMapInv C X F (YMap C X \<eta>) $$ Y) |@| f = (\<eta> $$ Y) |@| f" .
}
qed
}
qed
lemma YMap2:
assumes "LSCategory C" and "Ftor F : (Op C) \<longrightarrow> SET" and "X \<in> Obj C"
and "x |\<in>| (F @@ X)"
shows "YMap C X (YMapInv C X F x) = x"
proof(simp only: YMap_def)
let ?\<eta> = "(YMapInv C X F x)"
have "(?\<eta> $$ X) = ZFfun (Hom\<^bsub>C\<^esub> X X) (F @@ X) (\<lambda> f . (F ## (z2m\<^bsub>C\<^esub> f)) |@| x)" using assms by (simp add: YMapInvApp)
moreover have "(m2z\<^bsub>C \<^esub>(Id C X)) |\<in>| (Hom\<^bsub>C\<^esub> X X)" using assms by (simp add: Category.Simps LSCategory.m2zz2m)
ultimately have "(?\<eta> $$ X) |@| (m2z\<^bsub>C \<^esub>(Id C X)) = (F ## (z2m\<^bsub>C\<^esub> (m2z\<^bsub>C \<^esub>(Id C X)))) |@| x"
by (simp add: ZFfunApp)
also have "... = (F ## (Id C X)) |@| x" using assms by (simp add: Category.CatIdInMor LSCategory.m2zz2mInv)
also have "... = (Id SET (F @@ X)) |@| x"
proof-
have "X \<in> Obj (Op C)" using assms by (auto simp add: OppositeCategory_def)
hence "(F ## (Id (Op C) X)) = (Id SET (F @@ X))"
using assms by(simp add: FunctorId)
moreover have "(Id (Op C) X) = (Id C X)" using assms by (auto simp add: OppositeCategory_def)
ultimately show ?thesis by simp
qed
also have "... = x" using assms by (simp add: SETId)
finally show "(?\<eta> $$ X) |@| (m2z\<^bsub>C \<^esub>(Id C X)) = x" .
qed
lemma YFtorNT_YMapInv:
assumes "LSCategory C" and "f maps\<^bsub>C\<^esub> X to Y"
shows "YFtorNT C f = YMapInv C X (Hom\<^bsub>C\<^esub>[\<midarrow>,Y]) (m2z\<^bsub>C\<^esub> f)"
proof(simp only: YFtorNT_def YMapInv_def, rule NatTransExt')
have Cf: "cod\<^bsub>C\<^esub> f = Y" and Df: "dom\<^bsub>C\<^esub> f = X" using assms by auto
thus "NTCod (YFtorNT' C f) = NTCod (YMapInv' C X (Hom\<^bsub>C\<^esub>[\<midarrow>,Y]) (m2z\<^bsub>C\<^esub>f))"
by(simp add: YFtorNT'_def YMapInv'_def )
have "Hom\<^bsub>C\<^esub>[\<midarrow>,dom\<^bsub>C\<^esub> f] = YFtor C @@ X" using Df assms by (simp add: YFtorObj Category.MapsToObj)
thus "NTDom (YFtorNT' C f) = NTDom (YMapInv' C X (Hom\<^bsub>C\<^esub>[\<midarrow>,Y]) (m2z\<^bsub>C\<^esub>f))"
by(simp add: YFtorNT'_def YMapInv'_def )
{
fix Z assume ObjZ1: "Z \<in> Obj (NTCatDom (YFtorNT' C f))"
have ObjZ2: "Z \<in> Obj C" using ObjZ1 by (simp add: YFtorNT'_def NTCatDom_def OppositeCategory_def HomFtorContraDom)
moreover have ObjX: "X \<in> Obj C" and ObjY: "Y \<in> Obj C" using assms by (simp add: Category.MapsToObj)+
moreover
{
fix x assume x: "x |\<in>| (Hom\<^bsub>C\<^esub> Z X)"
have "m2z\<^bsub>C \<^esub>((z2m\<^bsub>C \<^esub>x) ;;\<^bsub>C\<^esub> f) = ((Hom\<^bsub>C\<^esub>[\<midarrow>,Y]) ## (z2m\<^bsub>C \<^esub>x)) |@| (m2z\<^bsub>C\<^esub>f)"
proof-
have morf: "f \<in> Mor C" using assms by auto
have mapsx: "(z2m\<^bsub>C \<^esub>x) maps\<^bsub>C\<^esub> Z to X" using x assms(1) ObjZ2 ObjX by (simp add: LSCategory.z2mm2z)
hence morx: "(z2m\<^bsub>C \<^esub>x) \<in> Mor C" by auto
hence "(Hom\<^bsub>C\<^esub>[\<midarrow>,Y]) ## (z2m\<^bsub>C \<^esub>x) = (HomC\<^bsub>C\<^esub>[(z2m\<^bsub>C \<^esub>x),Y])" using assms by (simp add: HomContraMor)
moreover have "(HomC\<^bsub>C\<^esub>[(z2m\<^bsub>C \<^esub>x),Y]) |@| (m2z\<^bsub>C \<^esub>f) = m2z\<^bsub>C \<^esub>((z2m\<^bsub>C \<^esub>x) ;;\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>(m2z\<^bsub>C \<^esub>f)))"
proof (rule HomContraAt)
have "cod\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>x) = X" using mapsx by auto
thus "(m2z\<^bsub>C \<^esub>f) |\<in>| (Hom\<^bsub>C\<^esub> (cod\<^bsub>C\<^esub> (z2m\<^bsub>C \<^esub>x)) Y)" using assms by (simp add: LSCategory.m2zz2m)
qed
moreover have "(z2m\<^bsub>C \<^esub>(m2z\<^bsub>C \<^esub>f)) = f" using assms morf by (simp add: LSCategory.m2zz2mInv)
ultimately show ?thesis by simp
qed
}
ultimately show "(YFtorNT' C f) $$ Z = (YMapInv' C X (Hom\<^bsub>C\<^esub>[\<midarrow>,Y]) (m2z\<^bsub>C\<^esub>f)) $$ Z" using Cf Df assms
apply(simp add: YFtorNT'_def YMapInv'_def HomFtorMap_def HomFtorOpObj)
apply(rule ZFfun_ext, rule allI, rule impI, simp)
done
}
qed
lemma YMapYoneda:
assumes "LSCategory C" and "f maps\<^bsub>C\<^esub> X to Y"
shows "YFtor C ## f = YMapInv C X (YFtor C @@ Y) (m2z\<^bsub>C\<^esub> f)"
proof-
have "f \<in> Mor C" using assms by auto
moreover have "Y \<in> Obj C" using assms by (simp add: Category.MapsToObj)
moreover have "YFtorNT C f = YMapInv C X (Hom\<^bsub>C\<^esub>[\<midarrow>,Y]) (m2z\<^bsub>C\<^esub> f)" using assms by (simp add: YFtorNT_YMapInv)
ultimately show ?thesis using assms by (simp add: YFtorMor YFtorObj)
qed
lemma YonedaFull:
assumes "LSCategory C" and "X \<in> Obj C" and "Y \<in> Obj C"
and "NT \<eta> : (YFtor C @@ X) \<Longrightarrow> (YFtor C @@ Y)"
shows "YFtor C ## (z2m\<^bsub>C\<^esub> (YMap C X \<eta>)) = \<eta>"
and "z2m\<^bsub>C\<^esub> (YMap C X \<eta>) maps\<^bsub>C\<^esub> X to Y"
proof-
have ftor: "Ftor (YFtor C @@ Y) : (Op C) \<longrightarrow> SET" using assms by (simp add: YFtorObj HomFtorContraFtor)
hence "(YMap C X \<eta>) |\<in>| ((YFtor C @@ Y) @@ X)" using assms by (simp add: YMapImage)
hence yh: "(YMap C X \<eta>) |\<in>| (Hom\<^bsub>C\<^esub> X Y)" using assms by (simp add: YFtorObj2)
thus "(z2m\<^bsub>C\<^esub> (YMap C X \<eta>)) maps\<^bsub>C\<^esub> X to Y" using assms by (simp add: LSCategory.z2mm2z)
hence "YFtor C ## (z2m\<^bsub>C\<^esub> (YMap C X \<eta>)) = YMapInv C X (YFtor C @@ Y) (m2z\<^bsub>C\<^esub> (z2m\<^bsub>C\<^esub> (YMap C X \<eta>)))"
using assms yh by (simp add: YMapYoneda)
also have "... = YMapInv C X (YFtor C @@ Y) (YMap C X \<eta>)"
using assms yh by (simp add: LSCategory.z2mm2z)
finally show "YFtor C ## (z2m\<^bsub>C\<^esub> (YMap C X \<eta>)) = \<eta>" using assms ftor by (simp add: YMap1)
qed
lemma YonedaFaithful:
assumes "LSCategory C" and "f maps\<^bsub>C\<^esub> X to Y" and "g maps\<^bsub>C\<^esub> X to Y"
and "YFtor C ## f = YFtor C ## g"
shows "f = g"
proof-
have ObjX: "X \<in> Obj C" and ObjY: "Y \<in> Obj C" using assms by (simp add: Category.MapsToObj)+
have M2Zf: "(m2z\<^bsub>C\<^esub> f) |\<in>| ((YFtor C @@ Y) @@ X)" and M2Zg: "(m2z\<^bsub>C\<^esub> g) |\<in>| ((YFtor C @@ Y) @@ X)"
using assms ObjX ObjY by (simp add: LSCategory.m2zz2m YFtorObj2)+
have Ftor: "Ftor (YFtor C @@ Y) : (Op C) \<longrightarrow> SET" using assms ObjY by (simp add: YFtorObj HomFtorContraFtor)
have Morf: "f \<in> Mor C" and Morg: "g \<in> Mor C" using assms by auto
have "YMapInv C X (YFtor C @@ Y) (m2z\<^bsub>C\<^esub> f) = YMapInv C X (YFtor C @@ Y) (m2z\<^bsub>C\<^esub> g)"
using assms by (simp add: YMapYoneda)
hence "YMap C X (YMapInv C X (YFtor C @@ Y) (m2z\<^bsub>C\<^esub> f)) = YMap C X (YMapInv C X (YFtor C @@ Y) (m2z\<^bsub>C\<^esub> g))"
by simp
hence "(m2z\<^bsub>C\<^esub> f) = (m2z\<^bsub>C\<^esub> g)" using assms ObjX ObjY M2Zf M2Zg Ftor by (simp add: YMap2)
thus "f = g" using assms Morf Morg by (simp add: LSCategory.mor2ZFInj)
qed
lemma YonedaEmbedding:
assumes "LSCategory C" and "A \<in> Obj C" and "B \<in> Obj C" and "(YFtor C) @@ A = (YFtor C) @@ B"
shows "A = B"
proof-
have AObjOp: "A \<in> Obj (Op C)" and BObjOp: "B \<in> Obj (Op C)" using assms by (simp add: OppositeCategory_def)+
hence FtorA: "Ftor (Hom\<^bsub>C\<^esub>[\<midarrow>,A]) : (Op C) \<longrightarrow> SET" and FtorB: "Ftor (Hom\<^bsub>C\<^esub>[\<midarrow>,B]) : (Op C) \<longrightarrow> SET"
using assms by (simp add: HomFtorContraFtor)+
have "Hom\<^bsub>C\<^esub>[\<midarrow>,A] = Hom\<^bsub>C\<^esub>[\<midarrow>,B]" using assms by (simp add: YFtorObj)
hence "(Hom\<^bsub>C\<^esub>[\<midarrow>,A]) ## (Id (Op C) A) = (Hom\<^bsub>C\<^esub>[\<midarrow>,B]) ## (Id (Op C) A)" by simp
hence "Id SET ((Hom\<^bsub>C\<^esub>[\<midarrow>,A]) @@ A) = Id SET ((Hom\<^bsub>C\<^esub>[\<midarrow>,B]) @@ A)"
using AObjOp BObjOp FtorA FtorB by (simp add: FunctorId)
hence "Id SET (Hom\<^bsub>C \<^esub>A A) = Id SET (Hom\<^bsub>C \<^esub>A B)" using assms by (simp add: HomFtorOpObj)
hence "Hom\<^bsub>C \<^esub>A A = Hom\<^bsub>C \<^esub>A B" using SETCategory by (simp add: Category.IdInj SETobj[of "Hom\<^bsub>C \<^esub>A A"] SETobj[of "Hom\<^bsub>C \<^esub>A B"])
moreover have "(m2z\<^bsub>C\<^esub> (Id C A)) |\<in>| (Hom\<^bsub>C \<^esub>A A)" using assms by (simp add: Category.Cidm LSCategory.m2zz2m)
ultimately have "(m2z\<^bsub>C\<^esub> (Id C A)) |\<in>| (Hom\<^bsub>C \<^esub>A B)" by simp
hence "(z2m\<^bsub>C\<^esub> (m2z\<^bsub>C\<^esub> (Id C A))) maps\<^bsub>C\<^esub> A to B" using assms by (simp add: LSCategory.z2mm2z)
hence "(Id C A) maps\<^bsub>C\<^esub> A to B" using assms by (simp add: Category.CatIdInMor LSCategory.m2zz2mInv)
hence "cod\<^bsub>C\<^esub> (Id C A) = B" by auto
thus ?thesis using assms by (simp add: Category.CatIdDomCod)
qed
end
|
module Replica.Command.Run
import Data.List
import Data.String
import Replica.Help
import Replica.Option.Types
import public Replica.Option.Filter
import public Replica.Option.Global
import Replica.Other.Decorated
%default total
public export
record RunCommand' (f : Type -> Type) where
constructor MkRunCommand
workingDir : f String
interactive : f Bool
threads : f Nat
hideSuccess : f Bool
punitive : f Bool
filter : Filter' f
global : Global' f
public export
RunCommand : Type
RunCommand = Done RunCommand'
TyMap RunCommand' where
tyMap func x =
MkRunCommand
(func x.workingDir)
(func x.interactive)
(func x.threads)
(func x.hideSuccess)
(func x.punitive)
(tyMap func x.filter)
(tyMap func x.global)
TyTraversable RunCommand' where
tyTraverse func x = [|
MkRunCommand
(func x.workingDir)
(func x.interactive)
(func x.threads)
(func x.hideSuccess)
(func x.punitive)
(tyTraverse func x.filter)
(tyTraverse func x.global)
|]
export
Show RunCommand where
show x = unwords
[ "MkRunCommand"
, show x.workingDir
, show x.interactive
, show x.threads
, show x.hideSuccess
, show x.punitive
, show x.filter
, show x.global
]
interactivePart : Part (Builder RunCommand') Bool
interactivePart = inj $ MkOption
(singleton $ MkMod (singleton "interactive") ['i'] (Left True)
"(re)generate golden number if different/missing")
False
go
where
go : Bool -> Builder RunCommand' -> Either String (Builder RunCommand')
go = ifSame interactive
(\x => record {interactive = Right x})
(const $ const "Contradictory values for interactive")
workingDirPart : Part (Builder RunCommand') String
workingDirPart = inj $ MkOption
(singleton $ MkMod ("working-dir" ::: ["wdir"]) ['w']
(Right $ MkValue "DIR" Just)
"set where is the test working directory")
"."
go
where
go : String -> Builder RunCommand' -> Either String (Builder RunCommand')
go = one workingDir
(\x => record {workingDir = Right x})
(\x, y => "More than one working directony were given: \{y}, \{x}")
threadsPart : Part (Builder RunCommand') Nat
threadsPart = inj $ MkOption
(singleton $ MkMod (singleton "threads") ['n']
(Right $ MkValue "N" parsePositive)
"max number of threads (default 1; 0 for no thread limit)")
1
go
where
go : Nat -> Builder RunCommand' -> Either String (Builder RunCommand')
go = one threads
(\x => record {threads = Right x})
(\x, y => "More than one threads values were given: \{show y}, \{show x}")
punitivePart : Part (Builder RunCommand') Bool
punitivePart = inj $ MkOption
(singleton $ MkMod ("punitive" ::: ["fail-fast"]) ['p']
(Left True)
"fail fast mode: stops on the first test that fails")
False
go
where
go : Bool -> Builder RunCommand' -> Either String (Builder RunCommand')
go = ifSame punitive
(\x => record {punitive = Right x})
(const $ const "Contradictory values for punitive mode")
hideSuccessPart : Part (Builder RunCommand') Bool
hideSuccessPart = inj $ MkOption
(singleton $ MkMod (toList1 ["hide-success", "fail-only"]) []
(Left True)
"hide successful tests in the report")
False
go
where
go : Bool -> Builder RunCommand' -> Either String (Builder RunCommand')
go = ifSame hideSuccess
(\x => record {hideSuccess = Right x})
(const $ const "Contradictory values for hide success mode")
optParseRun : OptParse (Builder RunCommand') RunCommand
optParseRun =
[| MkRunCommand
(liftAp workingDirPart)
(liftAp interactivePart)
(liftAp threadsPart)
(liftAp hideSuccessPart)
(liftAp punitivePart)
(embed filter (\x => record {filter = x}) optParseFilter)
(embed global (\x => record {global = x}) optParseGlobal)
|]
defaultRun : Default RunCommand'
defaultRun = MkRunCommand
(defaultPart workingDirPart)
(defaultPart interactivePart)
(defaultPart threadsPart)
(defaultPart hideSuccessPart)
(defaultPart punitivePart)
defaultFilter
defaultGlobal
export
parseRun : List1 String -> ParseResult RunCommand
parseRun ("run":::xs) = do
case parse (initBuilder defaultRun) optParseRun xs of
InvalidMix reason => InvalidMix reason
InvalidOption ys => InvalidMix $ "Unknown option: " ++ ys.head
Done builder => maybe (InvalidMix "No test file given") Done $ build builder
parseRun xs = InvalidOption xs
export
helpRun : Help
helpRun = commandHelp {b = Builder RunCommand'}
"run" "Run tests from a Replica JSON file"
optParseRun
(Just "JSON_TEST_FILE")
|
Formal statement is: lemma setdist_unique: "\<lbrakk>a \<in> S; b \<in> T; \<And>x y. x \<in> S \<and> y \<in> T ==> dist a b \<le> dist x y\<rbrakk> \<Longrightarrow> setdist S T = dist a b" Informal statement is: If $a \in S$ and $b \<in> T$ are such that $dist(a,b) \leq dist(x,y)$ for all $x \in S$ and $y \in T$, then $setdist(S,T) = dist(a,b)$. |
main : IO ()
main = do
printLn $ exp 1.0
printLn $ log 2.7
printLn $ sin 3.14
printLn $ cos 3.14
printLn $ tan 1.57
printLn $ asin 0.01
printLn $ acos 0.01
printLn $ atan 0.01
printLn $ sqrt 1000.0
printLn $ floor 2.7
printLn $ ceiling 11.1
|
from nn.neuralnetwork import NeuralNetwork
import numpy as np
X=np.array([[0,0],[0,1],[1,0],[1,1]])
y=np.array([[0],[1],[1],[0]])
nn=NeuralNetwork([2,2,1],alpha=0.5)
nn.fit(X,y,epochs=20000)
for(x,target) in zip(X,y):
pred=nn.predict(x)[0][0]
step =1 if pred > 0.5 else 0
print("[INFO] dane={}, prawda podstawowa={}, pred={}, krok={} ".format(
x, target[0],pred,step)) |
lemma DERIV_pow2: "DERIV (\<lambda>x. x ^ Suc n) x :> real (Suc n) * (x ^ n)" |
## Copyright (c) 2018-2021, Carnegie Mellon University
## See LICENSE for details
Declare(simtBlockIdxX, simtBlockIdxY, simtBlockIdxZ);
Declare(simtThreadIdxX, simtThreadIdxY, simtThreadIdxZ);
Declare(simt_syncgrid, simt_syncblock, simt_synccluster);
Declare(ASIMTListDim);
# The basic assumption is that threads are organized in a 6-dimensional structure (a 3D grid of 3D blocks).
# A dimension tag is a list of (thread) ranges over a one or more Grid/Block dimensions.
# e.g., ASIMTGridDimX(32) refers to 32 blocks (indexed from 0 to 31) over the X grid dimension.
# A range can also be a subset of the whole set of allocated elements:
# e.g., ASIMTGridDimX(32, [4,8]) refers to 5 blocks (indexed from 4 to 8) over the X grid dimension.
# More than one ranges can also be expressed over the same dimension:
# e.g., ASIMTGridDimX(32, [0,3], [4,8])
# As well as over different ones:
# e.g., ASIMTListDim( ASIMTGridDimX(32, [4,8]), ASIMTGridDimY(96) )
# SIMT Grid/BLock Dimension tags
Class(ASIMTDim, ASingletonTag, rec(
isSIMTTag := true,
# When lowering to icode a dimension tag instantiates a dimension index
_idx := Ignore,
_build_gen_idx := (self, Idx, plist) >> ApplyFunc(Idx, plist),
simt_idx := (arg) >> let(self := arg[1], idx := Copy(self._idx), Cond(idx=Ignore, idx, Length(arg)>1, ApplyFunc(idx.set_rng, self.simt_range(arg[2])), ApplyFunc(idx.set_rng, self.simt_range(1)) ) ),
need_cond := (self, i) >> let(L := Length(self.params), i < L and L > 1 and (self.params[i+1] <> [0,self.params[1]-1]) ),
simt_cond := (self, i) >> let( rng := self.simt_range(i), When(
self.need_cond(i), Cond(
rng[1] = 0, leq(self._idx, V(Last(rng))),
Last(rng) = self.params[1]-1, geq(self._idx, V(rng[1])),
rng[1] = Last(rng), eq(self._idx, V(rng[1])),
logic_and(geq(self._idx, V(rng[1])), leq(self._idx, V(Last(rng))))
),
V(true)
)),
update_simt_range := meth(self, i, new_rng)
local pre, post, dim;
dim := self;
if ObjId(new_rng) = ObjId(dim) then
if Length(dim.params) < i then
dim.params := dim.params :: List([Length(dim.params)..i], p -> dim.simt_range(p));
fi;
pre := Take(dim.params, i);
post := When(Length(dim.params)>i+1, Drop(dim.params, i+1), []);
dim.params := pre::new_rng.simt_all_ranges()::post;
elif Length(dim.params) <= 2 and i = 1 then
dim := new_rng;
else
if Length(dim.params) < i then
dim.params := dim.params :: List([Length(dim.params)..i], p -> dim.simt_range(p));
fi;
pre := [ApplyFunc( ObjId(dim), Take(dim.params, i) ) ];
post := When(Length(dim.params)>i+1, [ApplyFunc( ObjId(dim), Drop(dim.params, i+1) )], []);
dim := ApplyFunc(ASIMTListDim, pre::[new_rng]::post);
fi;
return dim;
end,
simt_range := (self, i) >> When(Length(self.params) > i, self.params[i+1], [0, self.params[1]-1]),
simt_all_ranges := (self) >> When(Length(self.params) > 1, Drop(self.params,1), [ [0, self.params[1]-1] ]),
simt_sync := (self) >> skip(),
num_ranges := (self) >> Maximum(1, Length(self.params)-1)
));
Class(ASIMTGridDim, ASIMTDim, rec(
simt_sync := (self) >> simt_syncgrid()
));
Class(ASIMTGridDimX, ASIMTGridDim, rec(
updateParams := meth(self)
self._idx := self._build_gen_idx(simtBlockIdxX, self.params{[1]});
return self;
end,
));
Class(ASIMTGridDimY, ASIMTGridDim, rec(
updateParams := meth(self)
self._idx := self._build_gen_idx(simtBlockIdxY, self.params{[1]});
return self;
end,
));
Class(ASIMTGridDimZ, ASIMTGridDim, rec(
updateParams := meth(self)
self._idx := self._build_gen_idx(simtBlockIdxZ, self.params{[1]});
return self;
end,
));
Class(ASIMTBlockDim, ASIMTDim, rec(
simt_sync := (self) >> simt_syncblock()
));
Class(ASIMTBlockDimX, ASIMTBlockDim, rec(
simt_sync := (self) >> simt_synccluster(),
updateParams := meth(self)
self._idx := self._build_gen_idx(simtThreadIdxX, self.params{[1]});
return self;
end,
));
Class(ASIMTBlockDimY, ASIMTBlockDim, rec(
updateParams := meth(self)
self._idx := self._build_gen_idx(simtThreadIdxY, self.params{[1]});
return self;
end,
));
Class(ASIMTBlockDimZ, ASIMTBlockDim, rec(
updateParams := meth(self)
self._idx := self._build_gen_idx(simtThreadIdxZ, self.params{[1]});
return self;
end,
));
Class(ASIMTListDim, ASIMTDim, rec(
_point_to_rng := meth(self, i)
local p, curr, curr_nr;
curr := self.params[1];
curr_nr := curr.num_ranges();
p := 2;
while i > curr_nr and p <= Length(self.params) do
i := i - curr_nr;
curr := self.params[p];
curr_nr := curr.num_ranges();
p := p + 1;
od;
#[<inner-dim containing requested rng>, <pos of rng within inner-dim>, <pos of inner-dim in params>]
return [curr, i, p-1];
end,
simt_idx := (arg) >> let(self := arg[1], nump := Length(self.params),
When(Length(arg)>1, let( d_i := self._point_to_rng(arg[2]), d_i[1].simt_idx(d_i[2]) ),
List(self.params, p -> p.simt_idx())
) ),
need_cond := (self, i) >> let( d_i := self._point_to_rng(i), d_i[1].need_cond(d_i[2]) ),
simt_cond := (self, i) >> let( d_i := self._point_to_rng(i), d_i[1].simt_cond(d_i[2]) ),
update_simt_range := meth(self, i, new_rng)
local d_i;
d_i := self._point_to_rng(i);
self.params[d_i[3]] := d_i[1].update_simt_range(d_i[2], new_rng);
return self;
end,
num_ranges := (self) >> Sum(List(self.params, i -> i.num_ranges())),
simt_range := (self, i) >> let( d_i := self._point_to_rng(i), d_i[1].simt_range(d_i[2]) ),
simt_all_ranges := (self) >> let( numi := self.num_ranges(), List([1..numi], i -> self.simt_range(i)) ),
simt_sync := (self) >> Maximum( List(self.params, p -> p.simt_sync()) ),
simt_dim := (self, i) >> self.params[i],
simt_dim_at := (self, i) >> let( d_i := self._point_to_rng(i), d_i[1])
));
Class(ASIMTLoopDim, ASIMTDim, rec(
simt_range := (self, i) >> [],
simt_all_ranges := (self) >> [],
num_ranges := (self) >> 0,
update_simt_range := meth(self, i, new_rng)
local dim;
dim := self;
if ObjId(new_rng) <> ObjId(dim) then
dim := When(i=1, new_rng, ApplyFunc(ASIMTListDim, Replicate(i-1, dim)::[new_rng]) );
fi;
return dim;
end,
));
Class(ASIMTFlag, ASIMTDim, rec(
updateParams := meth(self)
self._simt_dim := self.params[1];
end,
simt_dim := (self) >> self._simt_dim,
simt_idx := (arg) >> let(self := arg[1], ApplyFunc(self._simt_dim.simt_idx, arg{[2..Length(arg)]}) ),
need_cond := (self, i) >> self._simt_dim.need_cond(i),
simt_cond := (self, i) >> self._simt_dim.simt_cond(i),
update_simt_range := meth(self, i, new_rng)
self._simt_dim := self._simt_dim.update_simt_range(i, new_rng);
return self;
end,
simt_range := (self, i) >> self._simt_dim.simt_range(i),
simt_all_ranges := (self) >> self._simt_dim.simt_all_ranges(),
simt_sync := (self) >> self._simt_dim.simt_sync(),
num_ranges := (self) >> self._simt_dim.num_ranges()
));
Class(ASIMTKernelFlag, ASIMTFlag);
Class(ASIMTFissionFlag, ASIMTFlag);
Class(ASIMTTileFlag, ASIMTFlag, rec(
updateParams := meth(self)
Inherited();
self._tsize := self.params[2];
end,
tsize := (self) >> self._tsize
));
IsASIMTDim := (tag) -> ObjId(tag) in ASIMTDim._all_descendants();
##### Wrapping ######
Class(PlaceHolderMat, BaseMat, rec(
abbrevs := [ (id, ttype, dims) -> [ rec(
id := id,
TType := Copy(ttype),
dimensions := Copy(dims) ) ] ],
new := (self, spl) >> let( is_spl := IsSPL(spl), SPL(WithBases(self, rec(
id := When(is_spl, var._id(""), spl.id),
TType := When(is_spl, Copy(spl.TType), spl.TType),
dimensions := When(is_spl, Copy(spl.dimensions), spl.dimensions) )))
),
from_rChildren := (self, rch) >> ApplyFunc(ObjId(self), rch).appendAobj(self),
rChildren := (self) >> [ self.id, self.TType, self.dimensions ],
rSetChild := rSetChildFields("id", "TType", "dimensions"),
rng := meth(self) local d;
d := [self.dimensions[1]];
if IsBound(self.a.t_out) then
return List(TransposedMat([self.a.t_out, d]), e -> TArray(e[1], e[2]));
else
return List(d, e -> TArray(self.TType, e));
fi;
end,
dmn := meth(self) local d;
d := [self.dimensions[2]];
if IsBound(self.a.t_in) then
return List(TransposedMat([self.a.t_in, d]), e -> TArray(e[1], e[2]));
else
return List(d, e -> TArray(self.TType, e));
fi;
end,
));
wrap_rule_apply := function(rules, wrapper)
local rule;
rules := Flat([rules]);
for rule in rules do
if IsNewRule(rule) then
rule._apply := rule.apply;
rule.apply := wrapper(rule);
else
rule._rule := rule.rule;
rule.rule := wrapper(rule);
fi;
od;
end;
unwrap_rule_apply := function(rules)
local rule;
rules := Flat([rules]);
for rule in rules do
if IsNewRule(rule) then
rule.apply := rule._apply;
else rule.rule := rule._rule;
fi;
od;
end;
_original_apply := (R, nt, children, nonterms) -> Checked(IsRule(R), IsSPL(nt),
When(IsNewRule(R),
R._apply(nt, children, nonterms),
When(NumGenArgs(R._rule)=2,
R._rule(nt.params, children),
R._rule(nt.params, children, nonterms)))
);
dummy_wrap := (R) -> ( (nt, c, cnt) -> let(PrintLine("Using wrapped rule."), _apply(R, nt, c, cnt)) );
_strl := (n, c) -> StringJoin("", Replicate(n, c));
TaggableOps := [Tensor, SUM, ISum, DirectSum, IDirSum, VStack, IterVStack, HStack1, IterHStack1];
wrap_apply := (R) -> function(arg)
local nt, c, cnt, simt_exp, simt_dims, phs, ss;
nt := arg[1]; c := arg[2]; cnt := arg[3];
# Use placeholders for children to prevent Collect from going beyond rule.apply's boundaries
phs := List(c, spl -> PlaceHolderMat(spl));
simt_exp := _original_apply(R, nt, phs, cnt); # This dispatches to right call: _rule (for Rules) or _apply (for NewRules)
ss := Collect(simt_exp, @(1, TaggableOps) );
simt_dims := let( cd := nt.getA("simt_dim", [ASIMTLoopDim()]),
Cond(cd=Ignore, [],
IsList(cd) and Length(cd) = 1, Replicate(Length(ss), cd[1]),
cd)
);
if Length(simt_dims) <> Length(ss) then
Error("Number of tags (", Length(simt_dims), ") <> number of taggable operators (", Length(ss), ")");
fi;
# PrintLine("@@@@@@@@@@@@@ Beg ", R, "@@@@@@@@@@@@@@@");
# PrintLine("NT >> ", nt);
# PrintLine("simt_dims >> ", simt_dims);
# PrintLine("simt_expr >>", simt_exp);
# PrintLine("phs >>", phs);
# PrintLine("ch >>", c);
# PrintLine("@@@@@@@@@@@@@ End ", R, "@@@@@@@@@@@@@@@");
for i in [1..Length(ss)] do
simt_exp := SubstTopDownNR(simt_exp, @(1, ObjId(ss[i])).cond(e->e=ss[i]),
e -> ApplyFunc(AllClasses.("SIMT"::ObjId(ss[i]).name), [simt_dims[i], ss[i]]));
od;
for i in [1..Length(c)] do
simt_exp := SubstTopDownNR(simt_exp, @(1).cond(e->e=phs[i]), e -> c[i] );
od;
return simt_exp;
end;
# Node of a TagTree
tag_rec := (tag, tag_list) -> rec(simt_dim := tag, ch_tags := tag_list);
# Merge RuleTree and TagTree
tmp_tag_rt := function(rt, dims, opts)
if dims = Ignore then
rt.node := rt.node.setA(["simt_dim", [ASIMTLoopDim()] ]);
DoForAll([1..Length(rt.children)], i -> tmp_tag_rt(rt.children[i], dims, opts) );
elif IsASIMTDim(dims) then
rt.node := rt.node.setA(["simt_dim", [dims] ]);
DoForAll([1..Length(rt.children)], i -> tmp_tag_rt(rt.children[i], Ignore, opts) );
elif IsList(dims) then
rt.node := rt.node.setA(["simt_dim", [ASIMTLoopDim()] ]);
DoForAll([1..Length(rt.children)], i -> tmp_tag_rt(rt.children[i], dims[i], opts) );
else
rt.node := rt.node.setA(["simt_dim", dims.simt_dim]);
DoForAll([1..Length(rt.children)], i -> tmp_tag_rt(rt.children[i], dims.ch_tags[i], opts) );
fi;
end;
|
# First Order Initial Value Problem
The more general form of a first order Ordinary Differential Equation is:
\begin{equation}
\label{general ODE}
y^{'}=f(t,y).
\end{equation}
This can be solved analytically by integrating both sides but this is not straight forward for most problems.
Numerical methods can be used to approximate the solution at discrete points.
## Euler method
The simplest one step numerical method is the Euler Method named after the most prolific of mathematicians [Leonhard Euler](https://en.wikipedia.org/wiki/Leonhard_Euler) (15 April 1707 – 18 September 1783) .
The general Euler formula to the first order equation
$$ y^{'} = f(t,y) $$
approximates the derivative at time point $t_i$
$$y^{'}(t_i) \approx \frac{w_{i+1}-w_i}{t_{i+1}-t_{i}} $$
where $w_i$ is the approximate solution of $y$ at time $t_i$.
This substitution changes the differential equation into a __difference__ equation of the form
$$
\frac{w_{i+1}-w_i}{t_{i+1}-t_{i}}=f(t_i,w_i) $$
Assuming uniform stepsize $t_{i+1}-t_{i}$ is replaced by $h$, re-arranging the equation gives
$$ w_{i+1}=w_i+hf(t_i,w_i),$$
This can be read as the future $w_{i+1}$ can be approximated by the present $w_i$ and the addition of the input to the system $f(t,y)$ times the time step.
```python
## Library
import numpy as np
import math
%matplotlib inline
import matplotlib.pyplot as plt # side-stepping mpl backend
import matplotlib.gridspec as gridspec # subplots
import warnings
warnings.filterwarnings("ignore")
```
## Population growth
The general form of the population growth differential equation is:
$$ y^{'}=\epsilon y $$
where $\epsilon$ is the growth rate. The initial population at time $a$ is
$$ y(a)=A $$
$$ a\leq t \leq b. $$
Integrating gives the general analytic (exact) solution:
$$ y=Ae^{\epsilon x}. $$
We will use this equation to illustrate the application of the Euler method.
## Discrete Interval
The continuous time $a\leq t \leq b $ is discretised into $N$ points seperated by a constant stepsize
$$ h=\frac{b-a}{N}.$$
Here the interval is $0\leq t \leq 2$
$$ h=\frac{2-0}{20}=0.1.$$
This gives the 21 discrete points:
$$ t_0=0, \ t_1=0.1, \ ... t_{20}=2. $$
This is generalised to
$$ t_i=0+i0.1, \ \ \ i=0,1,...,20.$$
The plot below shows the discrete time steps.
```python
### Setting up time
t_end=2.0
t_start=0
N=20
h=(t_end-t_start)/(N)
time=np.arange(t_start,t_end+0.01,h)
fig = plt.figure(figsize=(10,4))
plt.plot(time,0*time,'o:',color='red')
plt.xlim((0,2))
plt.title('Illustration of discrete time points for h=%s'%(h))
```
## Initial Condition
To get a specify solution to a first order initial value problem, an __initial condition__ is required.
For our population problem the intial condition is:
$$y(0)=10$$.
This gives the analytic solution
$$y=10e^{\epsilon t}$$.
### Growth rate
Let the growth rate $$\epsilon=0.5$$ giving the analytic solution.
$$y=10e^{0.5 t}$$.
The plot below shows the exact solution on the discrete time steps.
```python
## Analytic Solution y
y=10*np.exp(0.5*time)
fig = plt.figure(figsize=(10,4))
plt.plot(time,y,'o:',color='black')
plt.xlim((0,2))
plt.xlabel('time')
plt.ylabel('y')
plt.title('Analytic (Exact) solution')
```
## Numerical approximation of Population growth
The differential equation is transformed using the Euler method into a difference equation of the form
$$ w_{i+1}=w_{i}+h \epsilon w_i. $$
This approximates a series of of values $w_0, \ w_1, \ ..., w_{N}$.
For the specific example of the population equation the difference equation is
$$ w_{i+1}=w_{i}+h 0.5 w_i. $$
where $w_0=10$. From this initial condition the series is approximated.
The plot below shows the exact solution $y$ in black circles and Euler approximation $w$ in blue squares.
```python
w=np.zeros(N+1)
w[0]=10
for i in range (0,N):
w[i+1]=w[i]+h*(0.5)*w[i]
fig = plt.figure(figsize=(10,4))
plt.plot(time,y,'o:',color='black',label='exact')
plt.plot(time,w,'s:',color='blue',label='Euler')
plt.xlim((0,2))
plt.xlabel('time')
plt.legend(loc='best')
plt.title('Analytic and Euler solution')
```
## Error
With a numerical solution there are two types of error:
* local truncation error at one time step;
* global error which is the propagation of local error.
### Derivation of Euler Local truncation error
The left hand side of a initial value problem $\frac{dy}{dt}$ is approximated by __Taylors theorem__ expand about a point $t_0$ giving:
\begin{equation}y(t_1) = y(t_0)+(t_1-t_0)y^{'}(t_0) + \frac{(t_1-t_0)^2}{2!}y^{''}(\xi), \ \ \ \ \ \ \xi \in [t_0,t_1]. \end{equation}
Rearranging and letting $h=t_1-t_0$ the equation becomes
$$y^{'}(t_0)=\frac{y(t_1)-y(t_0)}{h}-\frac{h}{2}y^{''}(\xi). $$
From this the local truncation error is
$$\tau y^{'}(t_0)\leq \frac{h}{2}M $$
where $y^{''}(t) \leq M $.
#### Derivation of Euler Local truncation error for the Population Growth
In most cases $y$ is unknown but in our example problem there is an exact solution which can be used to estimate the local truncation
$$y'(t)=5e^{0.5 t}$$
$$y''(t)=2.5e^{0.5 t}$$
From this a maximum upper limit can be calculated for $y^{''} $ on the interval $[t_0,t_1]=[0,0.1]$
$$y''(0.1)=2.5e^{0.1\times 0.5}=2.63=M$$
$$\tau=\frac{h}{2}2.63=0.1315 $$
The plot below shows the exact local truncation error $|y-w|$ (red triangle) and the upper limit of the Truncation error (black v) for the first two time points $t_0$ and $t_1$.
```python
fig = plt.figure(figsize=(10,4))
plt.plot(time[0:2],np.abs(w[0:2]-y[0:2]),'^:'
,color='red',label='Error |y-w|')
plt.plot(time[0:2],0.1*2.63/2*np.ones(2),'v:'
,color='black',label='Upper Local Truncation')
plt.xlim((0,.15))
plt.xlabel('time')
plt.legend(loc='best')
plt.title('Local Truncation Error')
```
## Global Error
The error does not stay constant accross the time this is illustrated in the figure below for the population growth equation. The actual error (red triangles) increases over time while the local truncation error (black v) remains constant.
```python
fig = plt.figure(figsize=(10,4))
plt.plot(time,np.abs(w-y),'^:'
,color='red',label='Error |y-w|')
plt.plot(time,0.1*2.63/2*np.ones(N+1),'v:'
,color='black',label='Upper Local Truncation')
plt.xlim((0,2))
plt.xlabel('time')
plt.legend(loc='best')
plt.title('Why Local Truncation does not extend to global')
```
## Theorems
To theorem below proves an upper limit of the global truncation error.
### Euler Global Error
__Theorem Global Error__
Suppose $f$ is continuous and satisfies a Lipschitz Condition with constant
L on $D=\{(t,y)|a\leq t \leq b, -\infty < y < \infty \}$ and that a constant M
exists with the property that
$$ |y^{''}(t)|\leq M. $$
Let $y(t)$ denote the unique solution of the Initial Value Problem
$$ y^{'}=f(t,y) \ \ \ a\leq t \leq b \ \ \ y(a)=\alpha $$
and $w_0,w_1,...,w_N$ be the approx generated by the Euler method for some
positive integer N. Then for $i=0,1,...,N$
$$ |y(t_i)-w_i| \leq \frac{Mh}{2L}|e^{L(t_i-a)}-1|. $$
### Theorems about Ordinary Differential Equations
__Definition__
A function $f(t,y)$ is said to satisfy a __Lipschitz Condition__ in the variable $y$ on
the set $D \subset R^2$ if a constant $L>0$ exist with the property that
$$ |f(t,y_1)-f(t,y_2)| < L|y_1-y_2| $$
whenever $(t,y_1),(t,y_2) \in D$. The constant L is call the Lipschitz Condition
of $f$.
__Theorem__
Suppose $f(t,y)$ is defined on a convex set $D \subset R^2$. If a constant
$L>0$ exists with
$$ \left|\frac{\partial f(t,y)}{\partial y}\right|\leq L $$
then $f$ satisfies a Lipschitz Condition an $D$ in the variable $y$ with
Lipschitz constant L.
### Global truncation error for the population equation
For the population equation specific values $L$ and $M$ can be calculated.
In this case $f(t,y)=\epsilon y$ is continuous and satisfies a Lipschitz Condition with constant
$$ \left|\frac{\partial f(t,y)}{\partial y}\right|\leq L $$
$$ \left|\frac{\partial \epsilon y}{\partial y}\right|\leq \epsilon=0.5=L $$
on $D=\{(t,y)|0\leq t \leq 2, 10 < y < 30 \}$ and that a constant $M$
exists with the property that
$$ |y^{''}(t)|\leq M. $$
$$ |y^{''}(t)|=2.5e^{0.5\times 2} \leq 2.5 e=6.8. $$
Let $y(t)$ denote the unique solution of the Initial Value Problem
$$ y^{'}=0.5 y \ \ \ 0\leq t \leq 10 \ \ \ y(0)=10 $$
and $w_0,w_1,...,w_N$ be the approx generated by the Euler method for some
positive integer N. Then for $i=0,1,...,N$
$$ |y(t_i)-w_i| \leq \frac{6.8 h}{2\times 0.5}|e^{0.5(t_i-0)}-1| $$
The figure below shows the exact error $y-w$ in red triangles and the upper global error in black x's.
```python
fig = plt.figure(figsize=(10,4))
plt.plot(time,np.abs(w-y),'^:'
,color='red',label='Error |y-w|')
plt.plot(time,0.1*6.8*(np.exp(0.5*time)-1),'x:'
,color='black',label='Upper Global Truncation')
plt.xlim((0,2))
plt.xlabel('time')
plt.legend(loc='best')
plt.title('Global Truncation Error')
```
```python
```
|
[GOAL]
α : Type u
β : Type v
γ : Type w
ι : Sort x
inst✝² : Preorder α
inst✝¹ : Preorder β
inst✝ : Preorder γ
g : β → γ
f : α → β
s : Set α
x : α
h : IsLUB s x
⊢ IsLUB (id '' s) (id x)
[PROOFSTEP]
simpa only [image_id] using h
[GOAL]
α : Type u
β : Type v
γ : Type w
ι : Sort x
inst✝² : Preorder α
inst✝¹ : Preorder β
inst✝ : Preorder γ
g : β → γ
f : α → β
hf : LeftOrdContinuous f
a₁ a₂ : α
h : a₁ ≤ a₂
⊢ a₂ ∈ upperBounds {a₁, a₂}
[PROOFSTEP]
simp [*]
[GOAL]
α : Type u
β : Type v
γ : Type w
ι : Sort x
inst✝² : Preorder α
inst✝¹ : Preorder β
inst✝ : Preorder γ
g : β → γ
f : α → β
hg : LeftOrdContinuous g
hf : LeftOrdContinuous f
s : Set α
x : α
h : IsLUB s x
⊢ IsLUB (g ∘ f '' s) ((g ∘ f) x)
[PROOFSTEP]
simpa only [image_image] using hg (hf h)
[GOAL]
α : Type u
β : Type v
γ : Type w
ι : Sort x
inst✝² : Preorder α
inst✝¹ : Preorder β
inst✝ : Preorder γ
g : β → γ
f✝ : α → β
f : α → α
hf : LeftOrdContinuous f
n : ℕ
⊢ LeftOrdContinuous f^[n]
[PROOFSTEP]
induction n with
| zero => exact LeftOrdContinuous.id α
| succ n ihn => exact ihn.comp hf
[GOAL]
α : Type u
β : Type v
γ : Type w
ι : Sort x
inst✝² : Preorder α
inst✝¹ : Preorder β
inst✝ : Preorder γ
g : β → γ
f✝ : α → β
f : α → α
hf : LeftOrdContinuous f
n : ℕ
⊢ LeftOrdContinuous f^[n]
[PROOFSTEP]
induction n with
| zero => exact LeftOrdContinuous.id α
| succ n ihn => exact ihn.comp hf
[GOAL]
case zero
α : Type u
β : Type v
γ : Type w
ι : Sort x
inst✝² : Preorder α
inst✝¹ : Preorder β
inst✝ : Preorder γ
g : β → γ
f✝ : α → β
f : α → α
hf : LeftOrdContinuous f
⊢ LeftOrdContinuous f^[Nat.zero]
[PROOFSTEP]
| zero => exact LeftOrdContinuous.id α
[GOAL]
case zero
α : Type u
β : Type v
γ : Type w
ι : Sort x
inst✝² : Preorder α
inst✝¹ : Preorder β
inst✝ : Preorder γ
g : β → γ
f✝ : α → β
f : α → α
hf : LeftOrdContinuous f
⊢ LeftOrdContinuous f^[Nat.zero]
[PROOFSTEP]
exact LeftOrdContinuous.id α
[GOAL]
case succ
α : Type u
β : Type v
γ : Type w
ι : Sort x
inst✝² : Preorder α
inst✝¹ : Preorder β
inst✝ : Preorder γ
g : β → γ
f✝ : α → β
f : α → α
hf : LeftOrdContinuous f
n : ℕ
ihn : LeftOrdContinuous f^[n]
⊢ LeftOrdContinuous f^[Nat.succ n]
[PROOFSTEP]
| succ n ihn => exact ihn.comp hf
[GOAL]
case succ
α : Type u
β : Type v
γ : Type w
ι : Sort x
inst✝² : Preorder α
inst✝¹ : Preorder β
inst✝ : Preorder γ
g : β → γ
f✝ : α → β
f : α → α
hf : LeftOrdContinuous f
n : ℕ
ihn : LeftOrdContinuous f^[n]
⊢ LeftOrdContinuous f^[Nat.succ n]
[PROOFSTEP]
exact ihn.comp hf
[GOAL]
α : Type u
β : Type v
γ : Type w
ι : Sort x
inst✝¹ : SemilatticeSup α
inst✝ : SemilatticeSup β
f : α → β
hf : LeftOrdContinuous f
x y : α
⊢ IsLUB (f '' {x, y}) (f x ⊔ f y)
[PROOFSTEP]
simp only [image_pair, isLUB_pair]
[GOAL]
α : Type u
β : Type v
γ : Type w
ι : Sort x
inst✝¹ : SemilatticeSup α
inst✝ : SemilatticeSup β
f : α → β
hf : LeftOrdContinuous f
h : Injective f
x y : α
⊢ f x ≤ f y ↔ x ≤ y
[PROOFSTEP]
simp only [← sup_eq_right, ← hf.map_sup, h.eq_iff]
[GOAL]
α : Type u
β : Type v
γ : Type w
ι : Sort x
inst✝¹ : SemilatticeSup α
inst✝ : SemilatticeSup β
f : α → β
hf : LeftOrdContinuous f
h : Injective f
x y : α
⊢ f x < f y ↔ x < y
[PROOFSTEP]
simp only [lt_iff_le_not_le, hf.le_iff h]
[GOAL]
α : Type u
β : Type v
γ : Type w
ι : Sort x
inst✝¹ : CompleteLattice α
inst✝ : CompleteLattice β
f : α → β
hf : LeftOrdContinuous f
s : Set α
⊢ f (sSup s) = ⨆ (x : α) (_ : x ∈ s), f x
[PROOFSTEP]
rw [hf.map_sSup', sSup_image]
[GOAL]
α : Type u
β : Type v
γ : Type w
ι : Sort x
inst✝¹ : CompleteLattice α
inst✝ : CompleteLattice β
f : α → β
hf : LeftOrdContinuous f
g : ι → α
⊢ f (⨆ (i : ι), g i) = ⨆ (i : ι), f (g i)
[PROOFSTEP]
simp only [iSup, hf.map_sSup', ← range_comp]
[GOAL]
α : Type u
β : Type v
γ : Type w
ι : Sort x
inst✝¹ : CompleteLattice α
inst✝ : CompleteLattice β
f : α → β
hf : LeftOrdContinuous f
g : ι → α
⊢ sSup (range (f ∘ fun i => g i)) = sSup (range fun i => f (g i))
[PROOFSTEP]
rfl
[GOAL]
α : Type u
β : Type v
γ : Type w
ι : Sort x
inst✝² : ConditionallyCompleteLattice α
inst✝¹ : ConditionallyCompleteLattice β
inst✝ : Nonempty ι
f : α → β
hf : LeftOrdContinuous f
g : ι → α
hg : BddAbove (range g)
⊢ f (⨆ (i : ι), g i) = ⨆ (i : ι), f (g i)
[PROOFSTEP]
simp only [iSup, hf.map_csSup (range_nonempty _) hg, ← range_comp]
[GOAL]
α : Type u
β : Type v
γ : Type w
ι : Sort x
inst✝² : ConditionallyCompleteLattice α
inst✝¹ : ConditionallyCompleteLattice β
inst✝ : Nonempty ι
f : α → β
hf : LeftOrdContinuous f
g : ι → α
hg : BddAbove (range g)
⊢ sSup (range (f ∘ g)) = sSup (range fun i => f (g i))
[PROOFSTEP]
rfl
[GOAL]
α : Type u
β : Type v
γ : Type w
ι : Sort x
inst✝² : Preorder α
inst✝¹ : Preorder β
inst✝ : Preorder γ
g : β → γ
f : α → β
s : Set α
x : α
h : IsGLB s x
⊢ IsGLB (id '' s) (id x)
[PROOFSTEP]
simpa only [image_id] using h
|
[STATEMENT]
lemma inFr2_mono:
assumes "inFr2 ns tr t" and "ns \<subseteq> ns'"
shows "inFr2 ns' tr t"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. inFr2 ns' tr t
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
inFr2 ns tr t
ns \<subseteq> ns'
goal (1 subgoal):
1. inFr2 ns' tr t
[PROOF STEP]
apply(induct arbitrary: ns' rule: inFr2.induct)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<And>tr ns t ns'. \<lbrakk>root tr \<in> ns; Inl t \<in> cont tr; ns \<subseteq> ns'\<rbrakk> \<Longrightarrow> inFr2 ns' tr t
2. \<And>tr1 tr ns1 t ns'. \<lbrakk>Inr tr1 \<in> cont tr; inFr2 ns1 tr1 t; \<And>ns'. ns1 \<subseteq> ns' \<Longrightarrow> inFr2 ns' tr1 t; insert (root tr) ns1 \<subseteq> ns'\<rbrakk> \<Longrightarrow> inFr2 ns' tr t
[PROOF STEP]
using Base Ind
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>root ?tr \<in> ?ns; Inl ?t \<in> cont ?tr\<rbrakk> \<Longrightarrow> inFr2 ?ns ?tr ?t
\<lbrakk>Inr ?tr1.0 \<in> cont ?tr; inFr2 ?ns1.0 ?tr1.0 ?t\<rbrakk> \<Longrightarrow> inFr2 (insert (root ?tr) ?ns1.0) ?tr ?t
goal (2 subgoals):
1. \<And>tr ns t ns'. \<lbrakk>root tr \<in> ns; Inl t \<in> cont tr; ns \<subseteq> ns'\<rbrakk> \<Longrightarrow> inFr2 ns' tr t
2. \<And>tr1 tr ns1 t ns'. \<lbrakk>Inr tr1 \<in> cont tr; inFr2 ns1 tr1 t; \<And>ns'. ns1 \<subseteq> ns' \<Longrightarrow> inFr2 ns' tr1 t; insert (root tr) ns1 \<subseteq> ns'\<rbrakk> \<Longrightarrow> inFr2 ns' tr t
[PROOF STEP]
apply (metis subsetD)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>tr1 tr ns1 t ns'. \<lbrakk>Inr tr1 \<in> cont tr; inFr2 ns1 tr1 t; \<And>ns'. ns1 \<subseteq> ns' \<Longrightarrow> inFr2 ns' tr1 t; insert (root tr) ns1 \<subseteq> ns'\<rbrakk> \<Longrightarrow> inFr2 ns' tr t
[PROOF STEP]
by (metis inFr2.simps insert_absorb insert_subset) |
{-# OPTIONS --without-K --rewriting #-}
open import lib.Basics
open import lib.cubical.Square
open import lib.types.Bool
open import lib.types.Cofiber
open import lib.types.Lift
open import lib.types.Paths
open import lib.types.Pointed
open import lib.types.PushoutFmap
open import lib.types.Sigma
open import lib.types.Span
open import lib.types.Suspension
open import lib.types.Wedge
module lib.types.BigWedge where
module _ {i j} {A : Type i} where
{- the function for cofiber -}
bigwedge-f : (X : A → Ptd j) → A → Σ A (de⊙ ∘ X)
bigwedge-f X a = a , pt (X a)
bigwedge-span : (A → Ptd j) → Span
bigwedge-span X = cofiber-span (bigwedge-f X)
BigWedge : (A → Ptd j) → Type (lmax i j)
BigWedge X = Cofiber (bigwedge-f X)
bwbase : {X : A → Ptd j} → BigWedge X
bwbase = cfbase
bwin : {X : A → Ptd j} → (a : A) → de⊙ (X a) → BigWedge X
bwin = curry cfcod
⊙BigWedge : (A → Ptd j) → Ptd (lmax i j)
⊙BigWedge X = ⊙[ BigWedge X , bwbase ]
bwglue : {X : A → Ptd j} → (a : A) → bwbase {X} == bwin a (pt (X a))
bwglue = cfglue
⊙bwin : {X : A → Ptd j} → (a : A) → X a ⊙→ ⊙BigWedge X
⊙bwin a = (bwin a , ! (bwglue a))
module BigWedgeElim {X : A → Ptd j} {k} {P : BigWedge X → Type k}
(base* : P bwbase) (in* : (a : A) (x : de⊙ (X a)) → P (bwin a x))
(glue* : (a : A) → base* == in* a (pt (X a)) [ P ↓ bwglue a ])
= CofiberElim {f = bigwedge-f X} {P = P} base* (uncurry in*) glue*
BigWedge-elim = BigWedgeElim.f
module BigWedgeRec {X : A → Ptd j} {k} {C : Type k}
(base* : C) (in* : (a : A) → de⊙ (X a) → C)
(glue* : (a : A) → base* == in* a (pt (X a)))
= CofiberRec {f = bigwedge-f X} {C = C} base* (uncurry in*) glue*
module _ {i j₀ j₁} {A : Type i} {X₀ : A → Ptd j₀} {X₁ : A → Ptd j₁}
(Xeq : ∀ a → X₀ a ⊙≃ X₁ a) where
bigwedge-span-emap-r : SpanEquiv (cofiber-span (bigwedge-f X₀)) (cofiber-span (bigwedge-f X₁))
bigwedge-span-emap-r = span-map (idf _) (Σ-fmap-r λ a → fst (⊙–> (Xeq a))) (idf _)
(comm-sqr λ _ → idp) (comm-sqr λ a → pair= idp (⊙–>-pt (Xeq a))) ,
idf-is-equiv _ , Σ-isemap-r (λ a → snd (Xeq a)) , idf-is-equiv _
BigWedge-emap-r : BigWedge X₀ ≃ BigWedge X₁
BigWedge-emap-r = Pushout-emap bigwedge-span-emap-r
⊙BigWedge-emap-r : ⊙BigWedge X₀ ⊙≃ ⊙BigWedge X₁
⊙BigWedge-emap-r = ≃-to-⊙≃ BigWedge-emap-r idp
module _ {i₀ i₁ j} {A₀ : Type i₀} {A₁ : Type i₁}
(X : A₁ → Ptd j) (Aeq : A₀ ≃ A₁) where
bigwedge-span-emap-l : SpanEquiv (cofiber-span (bigwedge-f (X ∘ –> Aeq))) (cofiber-span (bigwedge-f X))
bigwedge-span-emap-l = span-map (idf _) (Σ-fmap-l (de⊙ ∘ X) (–> Aeq)) (–> Aeq)
(comm-sqr λ _ → idp) (comm-sqr λ _ → idp) ,
idf-is-equiv _ , Σ-isemap-l (de⊙ ∘ X) (snd Aeq) , snd Aeq
BigWedge-emap-l : BigWedge (X ∘ –> Aeq) ≃ BigWedge X
BigWedge-emap-l = Pushout-emap bigwedge-span-emap-l
⊙BigWedge-emap-l : ⊙BigWedge (X ∘ –> Aeq) ⊙≃ ⊙BigWedge X
⊙BigWedge-emap-l = ≃-to-⊙≃ BigWedge-emap-l idp
module _ {i j} {A : Type i} (X : A → Ptd j) where
extract-glue-from-BigWedge-is-const :
∀ bw → extract-glue {s = bigwedge-span X} bw == north
extract-glue-from-BigWedge-is-const = BigWedge-elim
idp
(λ x y → ! (merid x))
(↓-='-from-square ∘ λ x →
ExtractGlue.glue-β x ∙v⊡
tr-square (merid x)
⊡v∙ ! (ap-cst north (cfglue x)))
{- A BigWedge indexed by Bool is just a binary Wedge -}
module _ {i} (Pick : Bool → Ptd i) where
BigWedge-Bool-equiv-Wedge : BigWedge Pick ≃ Wedge (Pick true) (Pick false)
BigWedge-Bool-equiv-Wedge = equiv f g f-g g-f
where
module F = BigWedgeRec {X = Pick}
{C = Wedge (Pick true) (Pick false)}
(winl (pt (Pick true)))
(λ {true → winl; false → winr})
(λ {true → idp; false → wglue})
module G = WedgeRec {X = Pick true} {Y = Pick false}
{C = BigWedge Pick}
(bwin true)
(bwin false)
(! (bwglue true) ∙ bwglue false)
f = F.f
g = G.f
abstract
f-g : ∀ w → f (g w) == w
f-g = Wedge-elim
(λ _ → idp)
(λ _ → idp)
(↓-∘=idf-in' f g $
ap f (ap g wglue)
=⟨ ap (ap f) G.glue-β ⟩
ap f (! (bwglue true) ∙ bwglue false)
=⟨ ap-∙ f (! (bwglue true)) (bwglue false) ⟩
ap f (! (bwglue true)) ∙ ap f (bwglue false)
=⟨ ap-! f (bwglue true)
|in-ctx (λ w → w ∙ ap f (bwglue false)) ⟩
! (ap f (bwglue true)) ∙ ap f (bwglue false)
=⟨ F.glue-β true
|in-ctx (λ w → ! w ∙ ap f (bwglue false)) ⟩
ap f (bwglue false)
=⟨ F.glue-β false ⟩
wglue =∎)
g-f : ∀ bw → g (f bw) == bw
g-f = BigWedge-elim
(! (bwglue true))
(λ {true → λ _ → idp; false → λ _ → idp})
(λ {true → ↓-∘=idf-from-square g f $
ap (ap g) (F.glue-β true) ∙v⊡
bl-square (bwglue true);
false → ↓-∘=idf-from-square g f $
(ap (ap g) (F.glue-β false) ∙ G.glue-β) ∙v⊡
lt-square (! (bwglue true)) ⊡h vid-square})
module _ {i j} {A : Type i} (dec : has-dec-eq A) {X : Ptd j} where
{- The dependent version increases the complexity significantly
and we do not need it. -}
⊙bwproj-in : A → A → X ⊙→ X
⊙bwproj-in a a' with dec a a'
... | inl _ = ⊙idf _
... | inr _ = ⊙cst
module BigWedgeProj (a : A) = BigWedgeRec
{X = λ _ → X}
(pt X)
(λ a' → fst (⊙bwproj-in a a'))
(λ a' → ! (snd (⊙bwproj-in a a')))
bwproj : A → BigWedge (λ _ → X) → de⊙ X
bwproj = BigWedgeProj.f
⊙bwproj : A → ⊙BigWedge (λ _ → X) ⊙→ X
⊙bwproj a = bwproj a , idp
abstract
bwproj-bwin-diag : (a : A) → bwproj a ∘ bwin a ∼ idf (de⊙ X)
bwproj-bwin-diag a x with dec a a
... | inl _ = idp
... | inr a≠a with a≠a idp
... | ()
bwproj-bwin-≠ : {a a' : A} → a ≠ a' → bwproj a ∘ bwin a' ∼ cst (pt X)
bwproj-bwin-≠ {a} {a'} a≠a' x with dec a a'
... | inr _ = idp
... | inl a=a' with a≠a' a=a'
... | ()
module _ {i j k} {A : Type i} (dec : has-dec-eq A) {X : Ptd j} (a : A) where
abstract
private
bwproj-BigWedge-emap-r-lift-in : ∀ a'
→ bwproj dec {X = ⊙Lift {j = k} X} a ∘ bwin a' ∘ lift
∼ lift {j = k} ∘ bwproj dec {X = X} a ∘ bwin a'
bwproj-BigWedge-emap-r-lift-in a' with dec a a'
... | inl _ = λ _ → idp
... | inr _ = λ _ → idp
bwproj-BigWedge-emap-r-lift-glue' : ∀ (a' : A)
→ ap (lift {j = k}) (! (snd (⊙bwproj-in dec {X = X} a a')))
== ! (snd (⊙bwproj-in dec {X = ⊙Lift {j = k} X} a a')) ∙' bwproj-BigWedge-emap-r-lift-in a' (pt X)
bwproj-BigWedge-emap-r-lift-glue' a' with dec a a'
... | inl _ = idp
... | inr _ = idp
bwproj-BigWedge-emap-r-lift-glue : ∀ (a' : A)
→ idp == bwproj-BigWedge-emap-r-lift-in a' (pt X)
[ (λ x → bwproj dec {X = ⊙Lift {j = k} X} a (–> (BigWedge-emap-r (λ _ → ⊙lift-equiv {j = k})) x)
== lift {j = k} (bwproj dec {X = X} a x)) ↓ bwglue a' ]
bwproj-BigWedge-emap-r-lift-glue a' = ↓-='-in' $
ap (lift {j = k} ∘ bwproj dec a) (bwglue a')
=⟨ ap-∘ (lift {j = k}) (bwproj dec a) (bwglue a') ⟩
ap (lift {j = k}) (ap (bwproj dec a) (bwglue a'))
=⟨ ap (ap (lift {j = k})) $ BigWedgeProj.glue-β dec a a' ⟩
ap (lift {j = k}) (! (snd (⊙bwproj-in dec a a')))
=⟨ bwproj-BigWedge-emap-r-lift-glue' a' ⟩
! (snd (⊙bwproj-in dec a a')) ∙' bwproj-BigWedge-emap-r-lift-in a' (pt X)
=⟨ ap (_∙' bwproj-BigWedge-emap-r-lift-in a' (pt X)) $
( ! $ BigWedgeProj.glue-β dec a a') ⟩
ap (bwproj dec a) (bwglue a') ∙' bwproj-BigWedge-emap-r-lift-in a' (pt X)
=⟨ ap (λ p → ap (bwproj dec a) p
∙' bwproj-BigWedge-emap-r-lift-in a' (pt X)) $
(! $ PushoutFmap.glue-β (fst (bigwedge-span-emap-r (λ _ → ⊙lift-equiv {j = k}))) a') ⟩
ap (bwproj dec a) (ap (–> (BigWedge-emap-r (λ _ → ⊙lift-equiv {j = k}))) (bwglue a'))
∙' bwproj-BigWedge-emap-r-lift-in a' (pt X)
=⟨ ap (_∙' bwproj-BigWedge-emap-r-lift-in a' (pt X)) $
(∘-ap (bwproj dec a) (–> (BigWedge-emap-r (λ _ → ⊙lift-equiv {j = k}))) (bwglue a')) ⟩
ap (bwproj dec a ∘ –> (BigWedge-emap-r (λ _ → ⊙lift-equiv {j = k}))) (bwglue a')
∙' bwproj-BigWedge-emap-r-lift-in a' (pt X)
=∎
bwproj-BigWedge-emap-r-lift :
bwproj dec {X = ⊙Lift {j = k} X} a ∘ –> (BigWedge-emap-r (λ _ → ⊙lift-equiv {j = k}))
∼ lift {j = k} ∘ bwproj dec a
bwproj-BigWedge-emap-r-lift =
BigWedge-elim {X = λ _ → X} idp
bwproj-BigWedge-emap-r-lift-in
bwproj-BigWedge-emap-r-lift-glue
|
module Ids where
id : {A : Set} -> A -> A
id x = x
slow : {A : Set} -> A -> A
slow = id id id id id id id id id id id id id id id id id id
-- The example above is based on one in "Implementing Typed
-- Intermediate Languages" by Shao, League and Monnier.
|
\filetitle{isempty}{True if VAR based object is empty}{FAVAR/isempty}
\paragraph{Syntax}\label{syntax}
\begin{verbatim}
Flag = isempty(X)
\end{verbatim}
\paragraph{Input arguments}\label{input-arguments}
\begin{itemize}
\itemsep1pt\parskip0pt\parsep0pt
\item
\texttt{X} {[} VAR \textbar{} SVAR \textbar{} FAVAR {]} - VAR based
object.
\end{itemize}
\paragraph{Output argument}\label{output-argument}
\begin{itemize}
\itemsep1pt\parskip0pt\parsep0pt
\item
\texttt{Flag} {[} \texttt{true} \textbar{} \texttt{false} {]} - True
if the VAR based object, \texttt{X}, is empty.
\end{itemize}
\paragraph{Description}\label{description}
\paragraph{Example}\label{example}
|
lemma limitin_sequentially_offset: "limitin X f l sequentially \<Longrightarrow> limitin X (\<lambda>i. f (i + k)) l sequentially" |
module config_module
c***********************************************************************
c
c dl_poly module for defining simulation configuration data
c copyright - daresbury laboratory
c author - w. smith sep 2003
c
c***********************************************************************
use setup_module
use error_module
implicit none
character*1 cfgname(80)
character*1 sysname(80)
real(8) cell(9),rcell(9),celprp(10)
real(8) eta(9),stress(9),stresl(9),strcns(9),strbod(9)
character*8, allocatable :: atmnam(:)
real(8), allocatable :: xxx(:),yyy(:),zzz(:)
real(8), allocatable :: vxx(:),vyy(:),vzz(:)
real(8), allocatable :: fxx(:),fyy(:),fzz(:)
real(8), allocatable :: flx(:),fly(:),flz(:)
real(8), allocatable :: chge(:),weight(:),rmass(:)
integer, allocatable :: ltype(:),lstfrz(:)
integer, allocatable :: neulst(:),lstneu(:)
integer, allocatable :: lentry(:),list(:,:)
integer, allocatable :: lstout(:),link(:)
integer, allocatable :: lct(:),lst(:)
real(8), allocatable :: buffer(:)
save atmnam,neulst,lstneu,cfgname,sysname
save cell,xxx,yyy,zzz,vxx,vyy,vzz,fxx,fyy,fzz
save buffer,weight,chge,ltype,lstfrz,flx,fly,flz
save lentry,list,lstout,link,lct,lst,celprp,rmass
save eta,stress,stresl,strcns,rcell
contains
subroutine alloc_config_arrays(idnode,mxnode)
c***********************************************************************
c
c dl_poly subroutine for defining simulation configuration arrays
c copyright - daresbury laboratory
c author - w. smith sep 2003
c
c***********************************************************************
integer, parameter :: nnn=27
logical safe
integer i,fail,idnode,mxnode,numatm
dimension fail(nnn)
safe=.true.
numatm=mxatms*nbeads
c allocate arrays
fail(:)=0
allocate (xxx(numatm),stat=fail(1))
allocate (yyy(numatm),stat=fail(2))
allocate (zzz(numatm),stat=fail(3))
allocate (vxx(numatm),stat=fail(4))
allocate (vyy(numatm),stat=fail(5))
allocate (vzz(numatm),stat=fail(6))
allocate (fxx(numatm),stat=fail(7))
allocate (fyy(numatm),stat=fail(8))
allocate (fzz(numatm),stat=fail(9))
allocate (weight(numatm),stat=fail(11))
allocate (chge(numatm),stat=fail(12))
allocate (ltype(numatm),stat=fail(13))
allocate (lstfrz(numatm),stat=fail(14))
allocate (flx(numatm),stat=fail(15))
allocate (fly(numatm),stat=fail(16))
allocate (flz(numatm),stat=fail(17))
allocate (atmnam(numatm),stat=fail(18))
allocate (neulst(mxneut),stat=fail(19))
allocate (lstneu(numatm),stat=fail(20))
allocate (lstout(numatm),stat=fail(21))
allocate (lentry(mslist),stat=fail(22))
allocate (list(mslist,mxlist),stat=fail(23))
allocate (link(numatm),stat=fail(24))
allocate (lct(mxcell),stat=fail(25))
allocate (lst(mxcell),stat=fail(26))
allocate (rmass(numatm),stat=fail(27))
allocate (buffer(mxbuff),stat=fail(10))
if(any(fail.gt.0))safe=.false.
if(mxnode.gt.1)call gstate(safe)
if(.not.safe)then
if(idnode.eq.0)write(nrite,'(10i5)')fail
call error(idnode,1000)
endif
end subroutine alloc_config_arrays
end module config_module
|
(* Title: HOL/Auth/n_flash_nodata_cub_lemma_on_inv__9.thy
Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
*)
header{*The n_flash_nodata_cub Protocol Case Study*}
theory n_flash_nodata_cub_lemma_on_inv__9 imports n_flash_nodata_cub_base
begin
section{*All lemmas on causal relation between inv__9 and some rule r*}
lemma n_PI_Remote_GetVsinv__9:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_PI_Remote_Get src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_PI_Remote_Get src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_PI_Remote_GetXVsinv__9:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_PI_Remote_GetX src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_PI_Remote_GetX src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_NakVsinv__9:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Nak dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Nak dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst=p__Inv3)\<or>(dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Nak__part__0Vsinv__9:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Nak__part__1Vsinv__9:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Nak__part__2Vsinv__9:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Get__part__0Vsinv__9:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Get__part__1Vsinv__9:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Put_HeadVsinv__9:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_PutVsinv__9:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Put_DirtyVsinv__9:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_Get_NakVsinv__9:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst=p__Inv3)\<or>(src=p__Inv3\<and>dst=p__Inv4)\<or>(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)\<or>(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_Get_PutVsinv__9:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst=p__Inv3)\<or>(src=p__Inv3\<and>dst=p__Inv4)\<or>(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)\<or>(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_Nak__part__0Vsinv__9:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_Nak__part__1Vsinv__9:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_Nak__part__2Vsinv__9:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_GetX__part__0Vsinv__9:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_GetX__part__1Vsinv__9:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_1Vsinv__9:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_2Vsinv__9:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_3Vsinv__9:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_4Vsinv__9:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_5Vsinv__9:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_6Vsinv__9:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7__part__0Vsinv__9:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7__part__1Vsinv__9:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__0Vsinv__9:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__1Vsinv__9:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_HomeVsinv__9:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeShrSet'')) (Const true)))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeShrSet'')) (Const true)))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_Home_NODE_GetVsinv__9:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeShrSet'')) (Const true)))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeShrSet'')) (Const true)))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8Vsinv__9:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp=p__Inv3)\<or>(src=p__Inv3\<and>pp=p__Inv4)\<or>(src=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv4)\<or>(src=p__Inv3\<and>pp~=p__Inv3\<and>pp~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>pp=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_NODE_GetVsinv__9:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp=p__Inv3)\<or>(src=p__Inv3\<and>pp=p__Inv4)\<or>(src=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv4)\<or>(src=p__Inv3\<and>pp~=p__Inv3\<and>pp~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>pp=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_9__part__0Vsinv__9:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_9__part__1Vsinv__9:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_10_HomeVsinv__9:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeShrSet'')) (Const true)))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeShrSet'')) (Const true)))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_10Vsinv__9:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp=p__Inv3)\<or>(src=p__Inv3\<and>pp=p__Inv4)\<or>(src=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv4)\<or>(src=p__Inv3\<and>pp~=p__Inv3\<and>pp~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>pp=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_11Vsinv__9:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Local'')) (Const true)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Local'')) (Const true)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_NakVsinv__9:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst=p__Inv3)\<or>(src=p__Inv3\<and>dst=p__Inv4)\<or>(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)\<or>(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_PutXVsinv__9:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst=p__Inv3)\<or>(src=p__Inv3\<and>dst=p__Inv4)\<or>(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)\<or>(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv3) ''CacheState'')) (Const CACHE_E))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') dst) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') dst) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_PutVsinv__9:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Put dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Put dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst=p__Inv3)\<or>(dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_PutXVsinv__9:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_PutX dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_PutX dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst=p__Inv3)\<or>(dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_PutX_HomeVsinv__9:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_PutX_Home dst" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX__part__0Vsinv__9:
assumes a1: "r=n_PI_Local_GetX_PutX__part__0 " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_WbVsinv__9:
assumes a1: "r=n_NI_Wb " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_3Vsinv__9:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_3 N src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_1Vsinv__9:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_1 N src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_GetX__part__1Vsinv__9:
assumes a1: "r=n_PI_Local_GetX_GetX__part__1 " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_GetX__part__0Vsinv__9:
assumes a1: "r=n_PI_Local_GetX_GetX__part__0 " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_ReplaceVsinv__9:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_PI_Remote_Replace src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_ReplaceVsinv__9:
assumes a1: "r=n_PI_Local_Replace " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_existsVsinv__9:
assumes a1: "\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_InvAck_exists src pp" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_PutXVsinv__9:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_PI_Remote_PutX dst" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_Get_Put_HomeVsinv__9:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Put_Home dst" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvVsinv__9:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Inv dst" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_PutXVsinv__9:
assumes a1: "r=n_PI_Local_PutX " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_Get_PutVsinv__9:
assumes a1: "r=n_PI_Local_Get_Put " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_ShWbVsinv__9:
assumes a1: "r=n_NI_ShWb N " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX_HeadVld__part__0Vsinv__9:
assumes a1: "r=n_PI_Local_GetX_PutX_HeadVld__part__0 N " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_ReplaceVsinv__9:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Replace src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_GetX_Nak_HomeVsinv__9:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_Nak_Home dst" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_PutXAcksDoneVsinv__9:
assumes a1: "r=n_NI_Local_PutXAcksDone " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX__part__1Vsinv__9:
assumes a1: "r=n_PI_Local_GetX_PutX__part__1 " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_Get_Nak_HomeVsinv__9:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Nak_Home dst" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_exists_HomeVsinv__9:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_exists_Home src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Replace_HomeVsinv__9:
assumes a1: "r=n_NI_Replace_Home " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_PutVsinv__9:
assumes a1: "r=n_NI_Local_Put " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Nak_ClearVsinv__9:
assumes a1: "r=n_NI_Nak_Clear " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_Get_GetVsinv__9:
assumes a1: "r=n_PI_Local_Get_Get " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Nak_HomeVsinv__9:
assumes a1: "r=n_NI_Nak_Home " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_2Vsinv__9:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_2 N src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX_HeadVld__part__1Vsinv__9:
assumes a1: "r=n_PI_Local_GetX_PutX_HeadVld__part__1 N " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_FAckVsinv__9:
assumes a1: "r=n_NI_FAck " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__9 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
end
|
/-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
Additional equiv and encodable instances for lists and finsets.
-/
import data.equiv.denumerable data.nat.pairing order.order_iso
data.vector2 data.array.lemmas data.fintype
open nat list
namespace encodable
variables {α : Type*}
section list
variable [encodable α]
def encode_list : list α → ℕ
| [] := 0
| (a::l) := succ (mkpair (encode a) (encode_list l))
def decode_list : ℕ → option (list α)
| 0 := some []
| (succ v) := match unpair v, unpair_le_right v with
| (v₁, v₂), h :=
have v₂ < succ v, from lt_succ_of_le h,
(::) <$> decode α v₁ <*> decode_list v₂
end
instance list : encodable (list α) :=
⟨encode_list, decode_list, λ l,
by induction l with a l IH; simp [encode_list, decode_list, unpair_mkpair, encodek, *]⟩
@[simp] theorem encode_list_nil : encode (@nil α) = 0 := rfl
@[simp] theorem encode_list_cons (a : α) (l : list α) :
encode (a :: l) = succ (mkpair (encode a) (encode l)) := rfl
@[simp] theorem decode_list_zero : decode (list α) 0 = some [] := rfl
@[simp] theorem decode_list_succ (v : ℕ) :
decode (list α) (succ v) =
(::) <$> decode α v.unpair.1 <*> decode (list α) v.unpair.2 :=
show decode_list (succ v) = _, begin
cases e : unpair v with v₁ v₂,
simp [decode_list, e], refl
end
theorem length_le_encode : ∀ (l : list α), length l ≤ encode l
| [] := _root_.zero_le _
| (a :: l) := succ_le_succ $
le_trans (length_le_encode l) (le_mkpair_right _ _)
end list
section finset
variables [encodable α]
private def enle : α → α → Prop := encode ⁻¹'o (≤)
private lemma enle.is_linear_order : is_linear_order α enle :=
(order_embedding.preimage ⟨encode, encode_injective⟩ (≤)).is_linear_order
private def decidable_enle (a b : α) : decidable (enle a b) :=
by unfold enle order.preimage; apply_instance
local attribute [instance] enle.is_linear_order decidable_enle
def encode_multiset (s : multiset α) : ℕ :=
encode (s.sort enle)
def decode_multiset (n : ℕ) : option (multiset α) :=
coe <$> decode (list α) n
instance multiset : encodable (multiset α) :=
⟨encode_multiset, decode_multiset,
λ s, by simp [encode_multiset, decode_multiset, encodek]⟩
end finset
def encodable_of_list [decidable_eq α] (l : list α) (H : ∀ x, x ∈ l) : encodable α :=
⟨λ a, index_of a l, l.nth, λ a, index_of_nth (H _)⟩
def trunc_encodable_of_fintype (α : Type*) [decidable_eq α] [fintype α] : trunc (encodable α) :=
@@quot.rec_on_subsingleton _
(λ s : multiset α, (∀ x:α, x ∈ s) → trunc (encodable α)) _
finset.univ.1
(λ l H, trunc.mk $ encodable_of_list l H)
finset.mem_univ
instance vector [encodable α] {n} : encodable (vector α n) :=
encodable.subtype
instance fin_arrow [encodable α] {n} : encodable (fin n → α) :=
of_equiv _ (equiv.vector_equiv_fin _ _).symm
instance fin_pi (n) (π : fin n → Type*) [∀i, encodable (π i)] : encodable (Πi, π i) :=
of_equiv _ (equiv.pi_equiv_subtype_sigma (fin n) π)
instance array [encodable α] {n} : encodable (array n α) :=
of_equiv _ (equiv.array_equiv_fin _ _)
instance finset [encodable α] : encodable (finset α) :=
by haveI := decidable_eq_of_encodable α; exact
of_equiv {s : multiset α // s.nodup}
⟨λ ⟨a, b⟩, ⟨a, b⟩, λ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ⟨a, b⟩, rfl⟩
def fintype_arrow (α : Type*) (β : Type*) [fintype α] [decidable_eq α] [encodable β] :
trunc (encodable (α → β)) :=
(fintype.equiv_fin α).map $
λf, encodable.of_equiv (fin (fintype.card α) → β) $
equiv.arrow_congr f (equiv.refl _)
def fintype_pi (α : Type*) (π : α → Type*) [fintype α] [decidable_eq α] [∀a, encodable (π a)] :
trunc (encodable (Πa, π a)) :=
(encodable.trunc_encodable_of_fintype α).bind $ λa,
(@fintype_arrow α (Σa, π a) _ _ (@encodable.sigma _ _ a _)).bind $ λf,
trunc.mk $ @encodable.of_equiv _ _ (@encodable.subtype _ _ f _) (equiv.pi_equiv_subtype_sigma α π)
end encodable
namespace denumerable
variables {α : Type*} {β : Type*} [denumerable α] [denumerable β]
open encodable
section list
theorem denumerable_list_aux : ∀ n : ℕ,
∃ a ∈ @decode_list α _ n, encode_list a = n
| 0 := ⟨_, rfl, rfl⟩
| (succ v) := begin
cases e : unpair v with v₁ v₂,
have h := unpair_le_right v,
rw e at h,
rcases have v₂ < succ v, from lt_succ_of_le h,
denumerable_list_aux v₂ with ⟨a, h₁, h₂⟩,
simp at h₁,
simp [decode_list, e, h₂, h₁, encode_list, mkpair_unpair' e]
end
instance denumerable_list : denumerable (list α) := ⟨denumerable_list_aux⟩
@[simp] theorem list_of_nat_zero : of_nat (list α) 0 = [] := rfl
@[simp] theorem list_of_nat_succ (v : ℕ) :
of_nat (list α) (succ v) =
of_nat α v.unpair.1 :: of_nat (list α) v.unpair.2 :=
of_nat_of_decode $ show decode_list (succ v) = _,
begin
cases e : unpair v with v₁ v₂,
simp [decode_list, e],
rw [show decode_list v₂ = decode (list α) v₂,
from rfl, decode_eq_of_nat]; refl
end
end list
section multiset
def lower : list ℕ → ℕ → list ℕ
| [] n := []
| (m :: l) n := (m - n) :: lower l m
def raise : list ℕ → ℕ → list ℕ
| [] n := []
| (m :: l) n := (m + n) :: raise l (m + n)
lemma lower_raise : ∀ l n, lower (raise l n) n = l
| [] n := rfl
| (m :: l) n := by simp [raise, lower, nat.add_sub_cancel, lower_raise]
lemma raise_lower : ∀ {l n}, list.sorted (≤) (n :: l) → raise (lower l n) n = l
| [] n h := rfl
| (m :: l) n h :=
have n ≤ m, from list.rel_of_sorted_cons h _ (l.mem_cons_self _),
by simp [raise, lower, nat.add_sub_cancel' this,
raise_lower (list.sorted_of_sorted_cons h)]
lemma raise_chain : ∀ l n, list.chain (≤) n (raise l n)
| [] n := list.chain.nil _ _
| (m :: l) n := list.chain.cons (nat.le_add_left _ _) (raise_chain _ _)
lemma raise_sorted : ∀ l n, list.sorted (≤) (raise l n)
| [] n := list.sorted_nil
| (m :: l) n := (list.chain_iff_pairwise (@le_trans _ _)).1 (raise_chain _ _)
/- Warning: this is not the same encoding as used in `encodable` -/
instance multiset : denumerable (multiset α) := mk' ⟨
λ s : multiset α, encode $ lower ((s.map encode).sort (≤)) 0,
λ n, multiset.map (of_nat α) (raise (of_nat (list ℕ) n) 0),
λ s, by have := raise_lower
(list.sorted_cons.2 ⟨λ n _, zero_le n, (s.map encode).sort_sorted _⟩);
simp [-multiset.coe_map, this],
λ n, by simp [-multiset.coe_map, list.merge_sort_eq_self _ (raise_sorted _ _), lower_raise]⟩
end multiset
section finset
def lower' : list ℕ → ℕ → list ℕ
| [] n := []
| (m :: l) n := (m - n) :: lower' l (m + 1)
def raise' : list ℕ → ℕ → list ℕ
| [] n := []
| (m :: l) n := (m + n) :: raise' l (m + n + 1)
lemma lower_raise' : ∀ l n, lower' (raise' l n) n = l
| [] n := rfl
| (m :: l) n := by simp [raise', lower', nat.add_sub_cancel, lower_raise']
lemma raise_lower' : ∀ {l n}, (∀ m ∈ l, n ≤ m) → list.sorted (<) l → raise' (lower' l n) n = l
| [] n h₁ h₂ := rfl
| (m :: l) n h₁ h₂ :=
have n ≤ m, from h₁ _ (l.mem_cons_self _),
by simp [raise', lower', nat.add_sub_cancel' this, raise_lower'
(list.rel_of_sorted_cons h₂ : ∀ a ∈ l, m < a) (list.sorted_of_sorted_cons h₂)]
lemma raise'_chain : ∀ l {m n}, m < n → list.chain (<) m (raise' l n)
| [] m n h := list.chain.nil _ _
| (a :: l) m n h := list.chain.cons
(lt_of_lt_of_le h (nat.le_add_left _ _)) (raise'_chain _ (lt_succ_self _))
lemma raise'_sorted : ∀ l n, list.sorted (<) (raise' l n)
| [] n := list.sorted_nil
| (m :: l) n := (list.chain_iff_pairwise (@lt_trans _ _)).1
(raise'_chain _ (lt_succ_self _))
def raise'_finset (l : list ℕ) (n : ℕ) : finset ℕ :=
⟨raise' l n, (raise'_sorted _ _).imp (@ne_of_lt _ _)⟩
/- Warning: this is not the same encoding as used in `encodable` -/
instance finset : denumerable (finset α) := mk' ⟨
λ s : finset α, encode $ lower' ((s.map (eqv α).to_embedding).sort (≤)) 0,
λ n, finset.map (eqv α).symm.to_embedding (raise'_finset (of_nat (list ℕ) n) 0),
λ s, finset.eq_of_veq $ by simp [-multiset.coe_map, raise'_finset,
raise_lower' (λ n _, zero_le n) (finset.sort_sorted_lt _)],
λ n, by simp [-multiset.coe_map, finset.map, raise'_finset, finset.sort,
list.merge_sort_eq_self (≤) ((raise'_sorted _ _).imp (@le_of_lt _ _)),
lower_raise']⟩
end finset
end denumerable
namespace equiv
def list_nat_equiv_nat : list ℕ ≃ ℕ := denumerable.eqv _
def list_equiv_self_of_equiv_nat {α : Type} (e : α ≃ ℕ) : list α ≃ α :=
calc list α ≃ list ℕ : list_equiv_of_equiv e
... ≃ ℕ : list_nat_equiv_nat
... ≃ α : e.symm
end equiv
|
The Marquess of Queensberry , the father of Wilde 's lover Lord Alfred Douglas ( who was on holiday in Algiers at the time ) , had planned to disrupt the play by throwing a bouquet of rotten vegetables at the playwright when he took his bow at the end of the show . Wilde and Alexander learned of the plan , and the latter cancelled Queensberry 's ticket and arranged for policemen to bar his entrance . Nevertheless , he continued harassing Wilde , who eventually launched a private prosecution against the peer for criminal libel , triggering a series of trials ending in Wilde 's imprisonment for gross indecency . Alexander tried , unsuccessfully , to save the production by removing Wilde 's name from the billing , but the play had to close after only 86 performances .
|
"""
Auto()
Use this in the place of a tangent/cotangent in [`test_frule`](@ref) or
[`test_rrule`](@ref) to have that tangent/cotangent generated automatically based on the
primal. Uses `FiniteDifferences.rand_tangent`.
"""
struct Auto end
"""
PrimalAndTangent
A struct that represents a primal value paired with its tangent or cotangent.
For conciseness we refer to both tangent and cotangent as "tangent".
"""
struct PrimalAndTangent{P,D}
primal::P
tangent::D
end
primal(p::PrimalAndTangent) = p.primal
tangent(p::PrimalAndTangent) = p.tangent
"""
primal ⊢ tangent
Infix shorthand method to construct a `PrimalAndTangent`.
Enter via `\\vdash` + tab on supporting editors.
"""
const ⊢ = PrimalAndTangent
"""
auto_primal_and_tangent(primal; rng=Random.GLOBAL_RNG)
auto_primal_and_tangent(::PrimalAndTangent; rng=Random.GLOBAL_RNG)
Convience constructor for `PrimalAndTangent` where the primal is provided
This function is idempotent. If you pass it a `PrimalAndTangent` it doesn't change it.
"""
auto_primal_and_tangent(primal; rng=Random.GLOBAL_RNG) = primal ⊢ rand_tangent(rng, primal)
auto_primal_and_tangent(both::PrimalAndTangent; kwargs...) = both
|
#ifndef COMMAND_HPP
#define COMMAND_HPP
#include <memory>
#include <boost/filesystem.hpp>
#include "params_map.hpp"
typedef std::function<void(bool)> command_finish_handler;
class command
{
public:
virtual ~command() = default;
virtual void execute(const boost::filesystem::path &workspace_path, params_map &context_params, command_finish_handler finish_handler) = 0;
virtual std::string get_log() const = 0;
};
typedef std::shared_ptr<command> command_ptr;
typedef std::weak_ptr<command> command_wptr;
#endif // COMMAND_HPP
|
State Before: α : Type u_1
β : Type ?u.58480
ι : Type ?u.58483
inst✝ : DecidableEq α
s : Multiset α
⊢ (↑toFinsupp s).support = toFinset s State After: case a
α : Type u_1
β : Type ?u.58480
ι : Type ?u.58483
inst✝ : DecidableEq α
s : Multiset α
a✝ : α
⊢ a✝ ∈ (↑toFinsupp s).support ↔ a✝ ∈ toFinset s Tactic: ext State Before: case a
α : Type u_1
β : Type ?u.58480
ι : Type ?u.58483
inst✝ : DecidableEq α
s : Multiset α
a✝ : α
⊢ a✝ ∈ (↑toFinsupp s).support ↔ a✝ ∈ toFinset s State After: no goals Tactic: simp [toFinsupp] |
\chapter{Corpora for Bosnian, Croatian, and Serbian}
\label{Corpora for Bosnian, Croatian and Serbian}
\section{Introduction}
The goal of this chapter is to explain the choice of corpora used to extract linguistic evidence, formulate further hypotheses and find examples of the language structures in focus. As explained in the previous chapter our approach to CLs in BCS is primarily empirical and not oriented towards any particular working grammatical framework. Therefore, the role of data in our research is not limited to extracting examples confirming or contradicting the existing theories: we principally use corpora inductively to identify patterns which form regularities and exceptions concerning the behaviour of CLs.
The rest of this chapter is structured as follows: Section \ref{Some remarks on corpus types} discusses the double meaning of the term \textit{corpus} in linguistics and briefly summarises types of electronic text sources. In Section \ref{Overview of traditionally compiled corpora for BCS} we present an overview of the most important corpora for BCS with a special focus on web corpora in Section \ref{WAC}. Section \ref{Corpora for spoken BCS} discusses available corpora of spoken language. Section \ref{Discussion} presents some concluding remarks.
\section{Some remarks on corpus types}
\label{Some remarks on corpus types}
\subsection{The meanings of the term \textit{corpus} in modern linguistics}
In order to analyse the advantages and disadvantages of the available corpora we should first review the term corpus and discuss types of corpora, as this kind of collection of data forms a very heterogeneous group. Let us start from a very broad characteristic of the term corpus given by \citet[21]{McEneryWilson96}:
\begin{quotation} In principle, any collection of more than one text can be called a corpus: the term `corpus' is simply the Latin for `body', hence a corpus may be defined as any body of text. It need imply nothing more. But the term `corpus' when used in the context of modern linguistics tends most frequently to have more specific connotations than this simple definition provides for. These may be considered under four main headings:
\begin{itemize}
\item sampling and representativeness,
\item finite size,
\item machine-readable form,
\item a standard reference.
\end{itemize}
\end{quotation}
Thus, a corpus is a collection of naturally-occurring language documentation, gathered with respect to some particular framework. This framework can be either oriented towards characterising a particular type of language \citet[171]{Sinclair91} and results in both general reference corpora and small, specialised corpora, or towards studying a particular linguistic phenomenon, in which case often only particular types of structures are stored.
In order not to confuse these two approaches to data collection, we call the former type corpus\textsubscript{1}, whereas a corpus constructed in order to test a research hypothesis will be called corpus\textsubscript{2}.
These two approaches to data collection should be kept separate, as a corpus\textsubscript{1} can be a potential source of material for a corpus\textsubscript{2}. A corpus\textsubscript{2}, however, can rarely be used in the function of a corpus\textsubscript{1}, unless the linguistic phenomenon under study is a certain variety of a language as a whole.
Hence, in the present chapter we focus on the available corpora in the broader sense of corpus\textsubscript{1} in order to find out which of them can best serve the extraction of a representative collection of naturally occurring utterances, relevant to our project on CLs in BCS.
\subsection{Types of corpora as text collections}
When describing corpora as text collections, it is important to cover several parameters. First, whether the corpus contains written or spoken texts. Secondly, whether the corpus is monolingual or multilingual. Among multilingual varieties there are parallel corpora – where one piece of semantic content is represented in several languages (source language and one or more translations), and comparable corpora – where texts with similar characteristics (register, lexical content, style, genre) have been collected from several languages. In the case of comparable corpora it is important for the proportions of features according to which the stratification takes place to be preserved in all languages.
In the present study we focus on the microvariation of CLs in BCS, which excludes the use of parallel corpora as a source because of the interference from the source text. This is because “phenomena pertaining to the make-up of the source text tend to be transferred to the target text” \citep[275]{Toury95}. Therefore, in the next part we will focus on the description of monolingual corpora of BCS, including both written and spoken varieties.
The features important for linguistic studies are size, content and sampling principles, which allow to assess for what language varieties the given corpus is representative and which research questions can be studied with its help. In this respect modern corpora can be divided into traditional sources which follow certain priorly defined principles and criteria (stratified sample), and opportunistic collections compiled from what is easily available and accessible (convenience sample). Stratified samples are typical of reference and monitor corpora, whose task is to reflect the “real-life” state of language, and of small corpora compiled for specific research purposes.
However, most publicly available corpora are nowadays collected for purposes of computational linguistics and here corpus size is the deciding factor. As \citet[120]{ManningSchutze99} point out, “in Statistical NLP, one commonly receives as a corpus a certain amount of data from a certain domain of interests, without having any say how it is constructed.” The most popular solution is crawling the internet. We elaborate on this approach in Section \ref{WAC}.
In the overview below, we will describe both the smaller traditional and the more impressive in size opportunistic sources, and discuss their utility for studying microvation of CLs in BCS. The overview represents the state-of-the-art for the period 2015--2018 when the study data were retrieved. Due to rapid technological development, mainly the increase of storage possibilities and computational capacities, new resources appear very quickly, so some sources available now are not mentioned.
\section{Overview of traditionally compiled corpora for BCS}
\label{Overview of traditionally compiled corpora for BCS}
\subsection{Bosnian corpora}
Unfortunately, even now the range of available text collections for the Bosnian language is rather narrow.
\begin{table}
\caption{Bosnian corpora}
\label{table:bos1}
\centering
\begin{tabularx}{.97\textwidth}{lll>{\raggedright\arraybackslash}Xlll}
\lsptoprule
Corpus & Words & Text age & Text types & Lemm. & PoS & MSD \\
\midrule
OCBT & 1,500,000 & 1989--1997 &fiction, essays, newspapers, children's books, Islamic texts, legal texts, folklore & yes & no & no\\
\lspbottomrule
\end{tabularx}
\end{table}
The first widely available digital corpus of Bosnian is the Oslo Corpus of Bosnian Texts (OCBT, \citealt{Santos98}). It was the only larger corpus of Bosnian for a long time until recently, when bsWaC and SETimes \citep[30]{LjubesicKlubicka14} were compiled.
OCBT was created as a joint project of the Department for East European and Oriental Studies and the Text Laboratory of the University of Oslo. The main goal was to make Bosnian texts from the period 1989--1997 available for linguistic research \citep{Santos98}. The corpus is accessible for online search after registering for a free account. Table \ref{table:bos1} summarises the most important facts about the OCBT.\footnote{MSD stands for ``morphosyntactic descriptioons''.} The OCBT contains written texts belonging to different genres and its estimated size is 1,500,000 words \citep{Santos98}. It is searchable online through the Corpus Query Processor (CQP). The interface is rather simple, as it provides only concordances of words, phrases, suffixes, prefixes, or their combinations \citep{Santos98}. Functionalities often considered a standard, such as sorting and filtering, are not available. As to metainformation, the origins of texts are provided, which is a great advantage, but no morphosyntactic annotation is applied. Moreover, the OCBT is useful mostly for studies of standard language, as can be read from the content description in Table \ref{table:bos1}.
Summing up, it appears that the only traditionally compiled, monolingual source of Bosnian is the OCBT and therefore this language is definitely under-resourced. The Oslo Corpus of Bosnian Texts is certainly quite diversified with respect to the functional styles which it includes, but the texts are quite old, as they originate from the first development phase of standard Bosnian. However, the biggest objection to using this corpus in our study is that morphosyntactic annotation, which would allow efficient searching, is not available.
\subsection{Croatian corpora}
The two publicly available corpora of standard Croatian are \textit{Hrvatski nacionalni korpus} \citep{Tadic02, Tadic20}, that is, the Croatian National Corpus (CNC) and \textit{Hrvatska jezična riznica} \citep{CavarRoncevic11, CavarBrozovic12}, that is, the Croatian Language Corpus (Riznica). Table \ref{table:cro1} gives basic information about these sources.
\begin{table}
\caption{Croatian corpora}
\label{table:cro1}
\centering
\begin{tabularx}{.97\textwidth}{ll>{\raggedright\arraybackslash}X>{\raggedright\arraybackslash}Xlll}
\lsptoprule
Corpus & Words & Text age & Text types & Lemm. & PoS & MSD \\
\midrule
CNC & 2,559,160 & 1990-- &Croatian literature, journals, and newspapers, booklets, official letters & yes & yes & yes\\
Riznica & 84,536,657 & since 2\textsuperscript{nd} half of the 19\textsuperscript{th} century &Croatian literature, non-fiction: scientific publications, online journals, and newspapers & yes & yes & yes\\
\lspbottomrule
\end{tabularx}
\end{table}
CNC was the first widely available digital corpus of contemporary Croatian language. The most current, third version comprises 216.8 million tokens. It is available via a NoSketchEngine interface, which allows complex queries to be constructed using the syntax of Corpus Query Languages (CQL).
The main goal of the project initiated at the Department of Linguistics (University of Zagreb) was to construct a corpus which would be big enough to cover the whole scope of standard Croatian in order to generate a primary source of linguistic data for lexicographical, orthographical, morphological, syntactic, and semantic research on contemporary Croatian (\citealt[339]{Tadic98}). During compilation, special attention was paid to the desired ideal corpus structure, according to which reference corpora such as the British National Corpus are built. This aim has not been achieved yet, mainly because a spoken corpus has yet to be created \parencites[346]{Tadic98}[446]{Tadic02}.
The sampling frame was based on a variety of media, text types, genres, fields, and topics \citep[442]{Tadic02} according to the standards for text typologies \citep{eagles96}. It is important to emphasise that only texts from 1990 on were incorporated into the corpus since the Croatian language could only develop without any obstructions starting from that period \citep[442]{Tadic02}.
The CNC is lemmatised and morphosyntactically annotated. However, from the user perspective we have to make the objection that neither is it easy to find a description of the morphosyntactic tagset in use, nor to follow how attributes should be built.\footnote{\textcolor{black}{For a thorough insight into tagset visit} \url{http://nl.ijs.si/ME/V4/msd/html/msd-hr.html}.} In many cases the theoretically available opportunities fail, because for example overly long concordances in CQL seem to be too complex for the corpus.
Riznica was compiled at the Institute of Croatian Language and Linguistics in Zagreb.\footnote{\textcolor{black}{Over the period of the current project, Riznica went through an incredible change concerning metainformation and the corpus manager.}} The goal was to produce a publicly available linguistic resource on the Croatian language and to provide crucial information about the Croatian language standard \citep[51]{CavarBrozovic12}. The collection covers texts written in various functional domains and genres and dated from the second half of the 19\textsuperscript{th} century onwards.\footnote{The official description of the corpus states that it is compiled from texts from the period of the standardisation of Croatian (\citealt[52]{CavarBrozovic12}, \url{http://riznica.ihjj.hr/dokumentacija/index.en.html}). However, texts from previous centuries, such as \textit{Planine} by P. Zoranić, or \textit{Judita} by M. Marulić, may be found during querying.} It includes essential Croatian literature, including poetry, scientific publications from various domains, online journals, and newspapers. In contrast to the CNC, Riznica also contains translated literature from outstanding Croatian translators.\footnote{\textcolor{black}{For more information visit} \url{http://riznica.ihjj.hr/dokumentacija/index.en.html}.} Because of its rigorously selected texts, Riznica as a corpus could be an interesting object of linguistic research as long as the intention was to explore how the desired structures should behave in proper, standardised Croatian. Riznica only became an attractive source of standardised language in 2018, that is in the last phase of our study, when its new release allowed for part-of-speech searches as well as for queries concerning morphosyntactic structures.\footnote{According to the official description of the corpus, \textcolor{black}{the first release} should be annotated for lemma and word-class \citep[52]{CavarBrozovic12}; however, when queries are made through \url{http://riznica.ihjj.hr/index.hr.html} that kind of functionality is not available. The newest version was annotated with ReLDI tagger \citep{LjubesicErjavec16}, and is available \textcolor{black}{via CLARIN-Sl} at \url{https://www.clarin.si/noske/run.cgi/corp\_info?corpname=riznica\&struct\_attr\_stats=1}.}
\subsection{Serbian corpora}
Even though the range of available corpora of Serbian is not that narrow, in the literature we often find statements that Serbian is an under-resourced language with respect to the availability of electronic corpora \parencites[685]{Dobric12}[4106]{BSM14}. Table \ref{table:ser1} gives an overview of the best-known available digital corpora of the Serbian language.
\begin{table}
\caption{Serbian corpora}
\label{table:ser1}
\centering
\begin{tabularx}{.97\textwidth}{lY>{\raggedright\arraybackslash}X>{\raggedright\arraybackslash}Xlll}
\lsptoprule
Corpus & \multicolumn{1}{l}{Words} & Text age & Text types & Lemm. & PoS & MSD \\
\midrule
NETK & 22,000,000&since 1920&literature, scientific, and journalistic texts&no&no&no\\
SrpKor2003&22,000,000&since 1920&literature, scientific, and journalistic texts&no&no&no\\
SrpKor2013&122,000,000&from 20\textsuperscript{th} and 21\textsuperscript{st} century&literature, scientific, publicistic, administrative, and other texts&yes&yes&no\\
SrpLemKor&3,763,352&from 20\textsuperscript{th} and 21\textsuperscript{st} century&general fiction, literature, scientific, and legislative texts&yes&yes&no\\
KSJ&11,000,000&from 12\textsuperscript{th} up to 20\textsuperscript{th} century&literature, scientific, and legislative texts&yes&yes&yes\\
\lspbottomrule
\end{tabularx}
\end{table}
\textit{Korpus savremenog srpskog jezika}, that is the Corpus of contemporary Serbian (SrpKor2003), has been accessible online since 2002 \citep[41a]{Utvic11}. Its first version, NETK, lacked information about text sources, which was incorporated into the newer version. Both corpora are still available online; nevertheless, authorisation is required to use them. NETK and SrpKor2003 are monolingual corpora of raw texts written in the 20\textsuperscript{th} century and belonging to different functional styles \citep{KrstevVitas05}.\footnote{\textcolor{black}{It is important to emphasise that both corpora are available only} without an annotation layer.} They contain 22,000,000 words. The concepts which were important for the development of these corpora are described in \citet{VKP00}.
\begin{sloppypar}
The latest version, SrpKor2013, was released in 2013. It can be queried through an interface available for non-commercial purposes after registration. SrpKor2013 contains 122,000,000 words and it is the largest corpus of Serbian compiled in a traditional way. SrpKor2013 is lemmatised, and annotated for parts-of-speech. The markup scheme contains 16 tags \citep[43a]{Utvic11}. The existing documentation is very limited, so it is hard to draw many conclusions about the existence of further, for instance morphosyntactic, markup. SrpKor2013 is composed exclusively of written language and its texts can be divided into five functional styles (literary, scientific, publicistic, administrative, and others) \citep[42a]{Utvic11}. Bibliographic metainformation is provided for all texts and searches may only be performed separately for individual styles. From the description of the corpus it may be concluded that it also contains translation and some texts from online portals. Nonetheless, local experts consider the existing version of the Corpus of contemporary Serbian to be insufficient. In their opinion, in a new release more attention should be paid to achieving a balance between registers \citep[42a]{Utvic11}.
\end{sloppypar}
One part of SrpKor2013 has been extracted as a separate corpus under the name SrpLemKor. It is a lemmatised and PoS annotated corpus which consists of 3,763,352 words. This is the only part of the corpus for which the proportions of texts from particular registers are given in the documentation.
Korpus srpskog jezika (KSJ) is well described in \citet{Kostic03}. It comprises 11,000,000 words. \citet[47]{Dobric09} emphasises its diachronic dimension, which is reflected in the inclusion of texts dating back to the 12\textsuperscript{th} century. On the other hand, KSJ does not cover spoken language or many contemporary texts. Additionally no clear line can be drawn between Croatian, Serbian, and Serbo-Croatian where texts originating from the second half of the 20\textsuperscript{th} century are concerned. Undoubtedly the biggest advantage of KSJ is its detailed annotation, consisting of the grammatical status of each word, number of graphemes, syllable division and phonological structure, which was completed manually. Nevertheless, the main problem with KSJ is its accessibility. In personal communication with Dušica Filipović Đurđević and Aleksandar Kostić, son of the corpus compiler Dorđe Kostić, we found out that querying the corpus is possible only indirectly. One has to contact Aleksandar Kostić with a precise description of the data necessary and then the members of the Department of Psychology of the University of Belgrade extract concordances and send them back. Needless to say, first, such a mode of work is not very convenient and secondly, it is very likely that only simple queries are possible.
\begin{sloppypar}
Summing up, considerable resources exist for Serbian, but similarly to other BCS corpora, they suffer from certain drawbacks. First, the annotation and searchability do not fulfil current standards. In this respect, the biggest problem seems to be the extremely limited possibility of using morphosyntactic annotation in queries. Secondly, many sources also contain diachronic data, or possibly include other varieties of BCS which remain unannotated.
\end{sloppypar}
\section{\{bs,hr,sr\}WaC}
\label{WAC}
\subsection{The concept of the Web as a Corpus}
\{bs,hr,sr\}WaC \citep{LjubesicKlubicka14, LjubesicErjavec16c, LjubesicErjavec16a, LjubesicErjavec16b} belong to the Web as Corpus family of corpora, first popularized by WaCky \citep{BBFZ09}. The idea of using the internet as a source of linguistic data was controversial at first and generated a discussion about the content of web pages, since in such cases the acquisition of material is less controlled than in the case of traditional corpora. However, within the last decade the concept has become more and more popular, in particular because it is faster and cheaper in comparison to the traditional way of compiling a corpus \citep[43]{Benko17}.
The lack of resources for most of the South Slavic languages, which we hope we managed to demonstrate above, has also been recognised by the group of linguists behind the Regional Linguistic Data Initiative ReLDI. Furthermore, for smaller languages we do not have the luxury of text sampling, since the amount of data written in these languages is limited by their population, in comparison to, for example, English or Spanish. On the other hand, this can be a point in favour of web data since a large part of all writings are available online and can be turned into a language corpus \citep{LjubesicErjavec11}. Therefore, treating web corpora as fully-fledged language resources is certainly appropriate in the case of South Slavic languages.
We will now provide the key data about \{bs,hr,sr\}WaC, and discuss the problems and limitations of these three corpora.
\subsection{\{bs,hr,sr\}WaC in a nutshell}
The \{bs,hr,sr\}WaC corpora are undoubtedly the largest existing corpora for each of the three languages. Some key statistical data are presented below in Table~\ref{table:wac1}.
\begin{table}
\caption{\{bs,hr,sr\}WaC corpora\label{table:wac1}}
\begin{tabular}{lrrrr}
\lsptoprule
Corpus & Words & Tokens & Documents & Compiled\\
\midrule
bsWaC& 248,478,730 & 286,865,790 & 896,059 & 10/28/2017 17:23:26\\
hrWaC& 1,210,021,198 & 1,397,757,548 & 3,611,090 & 10/28/2017 01:27:08\\
srWaC& 476,888,297 & 554,627,647 & 1,353,238 & 10/28/2017 04:17:28\\
\lspbottomrule
\end{tabular}
\end{table}
Numerical data show that hrWaC is definitely the biggest of them, as it is more than double the size of srWaC and nearly five times bigger than bsWaC. We can identify several reasons for this state of affairs. First, the size of the Croatian economy and market. Second, the proportion of content written in closely related languages which appears in the Bosnian web and which had to be eliminated. And last but not least, the fact that the authors of the project are Croatians, and therefore may be more dedicated to the development of tools for studying Croatian.
\begin{sloppypar}
\{bs,hr,sr\}WaC are a family of top-level-domain corpora of Bosnian, Croatian, and Serbian, which are available for download and online work via the NoSketchEngine concordancer.\footnote{Other top-level-domains are: .ba, .hr, .rs, .biz, .com, .eu, .info, .net.} They are currently accessible through the same platform as the latest version of Riznica. Like Riznica, they have been automatically lemmatised and morphosyntactically annotated with the unified tagset pattern according to MULTEXT-East Morphosyntactic Specifications.\footnote{\textcolor{black}{For more information visit} \url{http://nl.ijs.si/ME/V5/msd/html/msd-hr.html}. The newest version has been released in 2019, see \url{http://nl.ijs.si/ME/V6/msd/html/msd-hbs.html\#msd.msds-hbs}.} The tagsets for Croatian and Serbian are identical on the morphosyntactic level, apart from one additional subset of tags for the synthetic future tense in Serbian \citep[31]{LjubesicKlubicka14}.
\end{sloppypar}
The morphological annotation was performed automatically with an accuracy estimated at 92.5\%, which fulfils the current standards in NLP \citep[4269]{LKAJ16}
\subsection{WaC content}
\label{WaC content}
The main problem of corpora compiled from the web is the lack of metadata on corpus composition. This applies to all possible categories which are used to characterise traditionally compiled corpora (sociolinguistic information, text age, style, genre, and register). Web corpora can be characterised with technical information (domain, URL, date of update or upload, and size), and, if additionally processed, with internal linguistic factors such as size of lexicon and frequency of grammatical features. Such analyses are nevertheless time-consuming and can usually, due to the massive volume of data, explain only part of variance. Additionally, in order to evaluate web corpora as a source, similar analysis must be performed on traditionally compiled, representative sources, which, as stated above, barely exist in BCS.
\citet{Benko17} shows that, regardless of problems with characterising their exact content, web corpora should not be treated as an inferior type of data, but simply a different one. Furthermore, experiments conducted for English \citep{BiberEgbert16} and Czech \citep{Cvrcek18} show that as far as internal linguistic features are in question, web data and traditional corpora overlap to a large extent.
\citet[62f]{Gato14} observes that although web corpora cannot cover all possible registers, they provide quite a wide spectrum, starting with formal legal texts on the one hand, and ending with informal blogs, and chat rooms on the other. It seems that the web contains both traditional genres adapted to the new medium, like newspaper and academic articles, and entirely new ones, such as tweets or Facebook entries, rarely included in traditionally compiled sources.
Finally, \citet[106]{SchafferBildhauer13}, authors of the German web corpus, come to the conclusion that web corpora do not generally perform noticeably worse than traditional ones of the same size. In addition, since size matters, it has to be said that large web corpora frequently outperform smaller traditional corpora \citep[106]{SchafferBildhauer13}. In other words, although the contents of web corpora cannot be described in traditional terms, there are good reasons to assume that with respect to linguistic structure a massive corpus is better than a small one.
\subsection{Sources of noise}
\subsubsection{Closely related languages}
Another point of critique towards web corpora is noisy data. The creators of South-Slavic WaC corpora indicate two main sources of noise: first, documents written in other, closely related languages and secondly, texts of low quality \citep[29]{LjubesicKlubicka14}.
In order to solve the problem of closely related languages, the creators used two classifiers: a blacklist classifier and unigram-level language models \citep[32]{LjubesicKlubicka14}. Table \ref{table:dist} shows what share of documents in each corpus was identified as written in a closely related language \citep[cf.][33]{LjubesicKlubicka14}. The authors used a ternary classifier in bsWaC, where the share of foreign documents was the highest, and assumed that a binary classifier for hrWaC and srWac, which distinguishes only between Serbian and Croatian, is sufficiently informative.
\begin{table}
\caption{Distribution of identified languages through the three corpora}
\label{table:dist}
\centering
\begin{tabularx}{.5\textwidth}{lYYY}
\lsptoprule
& bs & hr & sr\\
\midrule
bsWaC & 78.0\% & 16.5\% & 5.5\%\\
hrWaC & - &99.7\% & 0.3\%\\
srWaC & - & 1.3\% & 98.7\%\\
\lspbottomrule
\end{tabularx}
\end{table}
Nonetheless, although most documents in \{bs,hr,sr\}WaC are classified cor\-rect\-ly, one should be aware that single paragraphs in closely related languages might still appear. This is mostly the result of reader comments, where the content of the document is generated by many users. Still, we think that such appearances should not affect our results because all unexpected occurrences can be checked manually before they are included in the data set.
An issue that is linked to content written in closely related languages is the occasional appearance of lexical elements from other South Slavic varieties. We must point out that even strictly monitored corpora such as the CNC contain words which, according to handbooks, do not belong to the Croatian standard, such as: \textit{opšti} `general' (\textit{opći} in Croatian), \textit{januar} `January' (\textit{siječanj} in Croatian), \textit{sveštenik} `priest' (\textit{svećenik} in Croatian), \textit{tačka} `dot, point' (\textit{točka} in Croatian). Although the authors of the CNC tried to minimise this phenomenon by selecting texts written after 1990, such word forms are present, for instance because academic texts which discuss differences between Croatian and Serbian have been included. Similar evidence of non-Croatian word forms can be found also in Riznica, where the lemma \textit{tačka} typical of Serbian is attested not only in academic texts, but also in texts by 19\textsuperscript{th} century Croatian writers. In the same manner, Croatian word forms such as \textit{nogomet} `football' (\textit{fudbal} in Serbian), \textit{glazba} `music' (\textit{muzika} in Serbian) and \textit{zrakoplov} `aircraft' (\textit{vazduhoplov}, \textit{avion} in Serbian) can be found in SrpLemKor. A similar problem applies to web corpora, but on a larger scale.
\subsubsection{Non-standard language use and low quality data}
The authors of the corpora approach the problem of low quality data with the assumption that most of the content of each web corpus can be qualified as good \citep[33]{LjubesicKlubicka14}. In order to easily detect low quality text the most frequent types of deviation must be identified and classified. Above all, non-standard usage of the upper case, lower case and punctuation, and usage of non-standard language, understood as slang and dialects, belong here \citep[33]{LjubesicKlubicka14}.
Not all these problems are easy to solve, but during the procedure of noise removal from the first release of \{bs,hr,sr\}WaC, it was postulated that a low percentage of diacritic characters should reflect less standard language usage and this assumption was used as a very simple estimate of text quality \citep[34]{LjubesicKlubicka14}. In the second release, the REDI tool was used to restore diacritics, so that the texts could be correctly lemmatised and part-of-speech annotated.\footnote{The REDI tool is available at \url{https://github.com/clarinsi/redi}.}
To this we can add the problem of avoiding standard punctuation, which can be partly related to specific writing style. It is commonly known that some texts, for instance those written on discussion fora, are characterised by a relaxed approach to punctuation and the use of symbols so even when those texts are built of several sentences they can contain hardly any periods at all \citep[90]{SchafferBildhauer13}. \citet[43]{Gato14} also points out that online texts often contain misspelled words and grammatical mistakes, or include improper usage by non-natives.
Non-standard data could be an interesting object of CL research as they represent a very spontaneous, non-planned channel of communication, but they must be approached cautiously. Hence, results arising from non-standard language used online must always be checked manually to decide whether a particular divergence is caused by the relaxed use of language or carelessness of the language user, or else whether its source is non-native language use.
The second kind of low quality data typical of web documents are URLs, automatic translations, words split into fragments, and emoticons, but they do not affect our research much as they can be easily filtered out.
\section{Corpora for spoken BCS}
\label{Corpora for spoken BCS}
\subsection{Bosnian}
In the area of spoken varieties the availability of resources is even lower than for written varieties. Building spoken corpora is related to higher costs understood in terms such as time, money, and manpower. Moreover, the workflow is more complicated since compiling a corpus of spoken data requires the same steps as in the case of written varieties, but additionally recordings must be obtained and transcribed. Spoken data is also further from theoretical language models and normative description, so many structures not included in normative descriptions, such as (dis)fluencemes, occur.\footnote{\textcolor{black}{For more information on such structures} see Section \ref{Principles of analysis of spoken language}.} This poses a challenge for both human annotators and automatic taggers and lemmatisers. It comes as no surprise that only a handful of spoken corpora, compiled mainly for specific research purposes, are currently available.
The only corpus of Bosnian that we found was a corpus of narrative interviews compiled within the DFG-funded project \textit{Corpus-based} \textit{analysis} \textit{of} \textit{local} \textit{and} \textit{temporal} \textit{deictics} \textit{in} \textit{(spontaneously)} \textit{spoken} \textit{and} \textit{(reflected)} \textit{written} \textit{language}. The corpus is called Bosnian Interviews \citep{RaeckeStevanovic01} and was mainly transcribed and annotated by Slavica Stevanović. It used to be available for searches through an online interface, but currently access to its XML files can be obtained only on request. The data consist of 13 narrative conversation-situations with Bosnian refugees. The corpus is neither PoS annotated nor lemmatised, but tagging of v/t/n-deictics was performed for purposes of the above-mentioned research goal. An additional meta-layer of regional pronunciation is also featured. The formal description of the corpus is, nevertheless, very vague as, for example, the size of the corpus is not stated. We provide more details on this corpus in Chapter \ref{Clitics in a corpus of a spoken variety}.
\subsection{Croatian}
The Croatian Adult Spoken Language Corpus HrAL \citep{KuvacHrzica16} was built by sampling spontaneous conversations of 617 speakers from all Croatian counties, and it comprises over 250,000 tokens and over 100,000 types in 165 transcripts annotated with the ages and genders of the speakers, as well as the location of the conversation. It was compiled in three periods: 2010--2012, 2014--2015 and 2016. Croatian speakers from different parts of Croatia with access to groups of speakers (friends and families) were recruited and trained to collect samples of spoken language. Sampling was performed in informal situations, predominantly spontaneous conversations among friends, relatives or acquaintances during family meals, informal gatherings, and socialising. Thus the corpus contains rather short, often interrupted utterances.
\subsection{Serbian}
We are not aware of any publicly available, electronically stored corpus of spoken Serbian. Nevertheless, this gap might be filled in the near future, as some efforts towards building both Serbian and Bosnian spoken sources are being made, e.g. in a project at Humboldt-Universität zu Berlin.\footnote{\textcolor{black}{For more information visit} \url{https://www.slawistik.hu-berlin.de/de/fachgebiete/suedslawsw/colabnet/projects/spoc/spoc}.}
\section{Discussion}
\label{Discussion}
\subsection{The scope of available data}
This section compares the properties of traditionally compiled corpora and web corpora for BCS with the goals of the study. As shown above, sources for corpus analysis in BCS are certainly limited. On the one hand, we have at our disposal rather sparse traditionally compiled corpora. They mostly represent language strongly influenced by normative prescription. Additionally, the languages are not equally represented if we compare size and type of data and the extent of annotation, which implies an individual approach to working with each corpus. The worst situation is in the area of spoken language and dialects, where little or no data can be identified.\footnote{\textcolor{black}{Some corpora such as \citet[]{Vukovic21} were developed after our project was finished.}}
On the other hand, large data sets of unknown composition obtained from the web can be easily accessed and processed in a comparable way for all three South Slavic varieties in question. Although the language of web corpora cannot be described in traditional terms, a considerable share of the language represented in web corpora is not influenced by normative prescription, but is probably not worse as concerns linguistic richness than traditional data, as we hope we have shown in Section \ref{WaC content}.
Additionally, the analysis of url domain lists shows that web corpora not only cover texts typically included in corpora of standard language such as literary, journalistic, administrative, academic, and popular scientific texts, but also contain very new registers and genres that appear in user-generated content such as blogs and fora which are much closer to spontaneous language, even though written and not spoken \citep[4]{SchafferBildhauer13}. This type of data is a valuable source of colloquial language and as such certainly relevant for studies of microvariation. Next to the available meta-information (allowing to track where the texts come from), size, and accessibility, such variety of data is a great advantage of web corpora which, at the same time, is hard to obtain from traditional sources.\footnote{We are aware that the internet is often criticized for poor quality of texts, which includes numerous spelling errors, omission of diacritic signs and non-standard use of the upper and lower case and that this critique also pertains to texts from \{bs, hr, sr\}WaC. However, we would like to point out that for us these corpora are a source of authentic, spontaneously produced written texts, which were not under strict influence of the norm or externally corrected to look like prescribed standard Bosnian, Croatian or Serbian.}
The question of the extent to which the available data can be considered representative appears. Following \citet[243]{Biber05}, “representativeness refers to the extent to which a sample includes the full range of variability in population”. Ironic as it may seem, ideal representativeness is not possible to achieve. This is because however much corpus constructors try, they can only create a corpus which is the representation of itself, \citet[1]{KilgarriffGrefenstette03} claim.\footnote{\citet[8f]{KilgarriffGrefenstette03} list several reasons why corpora fail to represent real language usage. They draw attention to the arbitrariness which dominates in the text sampling, i.e. it is literally impossible to include all text types and topics \citep[cf.][9]{KilgarriffGrefenstette03}.} Furthermore, the representativeness criterion seems useless nowadays, because web corpora do not contain that sort of metadata. Therefore, neither is it possible to check the range of text types they cover, nor can one be sure about the population of text types themselves, since the web covers a considerable, but not systematised, share of texts. Nonetheless, its variety and particularly its size counterbalance the limited information about its representativeness \citep[45]{Gato14}.
\citet[120]{ManningSchutze99} argue that “having more training data is normally more useful than any concerns of balance, and one should simply use all the text that is available”. Furthermore, we agree with what Kilgarriff already noticed, namely that “it is the web that presents the most provocative questions about the nature of language” \citep[cf.][344]{Kilgarriff01}.
Therefore, we follow \citet{ManningSchutze99} and try to use a possibly broad scope of available corpora according to our goals. Apart from providing naturally-occurring, non-externally normativised and proofread language, corpora benefit our work on two topics. The first is CL placement and inventory in spoken varieties (see Part \ref{part2}). The second is an empirical approach to CC (see Part \ref{part3}), a controversial topic which has so far been studied exclusively in terms of theoretical syntax. In the two sections below we explain our choices as to the studied sources.
It is important to remember that currently digital sources develop very dynamically. During the period when the current project was conducted, some significant changes could be observed, such as the improvements in the morphosyntactic tagger for BCS and the new release of Riznica. Due to practical reasons, primarily time constraints, we could not benefit from all the advancements. Some parts of study were conducted on the old versions. Some corpora were rejected due to their poor quality at the time.
\subsection{Variation in spoken BCS}
\label{Parameters of variation in spoken BCS}
As presented in Section \ref{Corpora for spoken BCS}, the most under-resourced area of BCS is spoken sources. Thus, making statements about CL behaviour in spoken varieties and dialects based on corpus data is barely possible at the moment. The available spoken sources neither meet the standards applied to written corpora with regard to morphosyntactic annotation level, nor are they preprocessed with regard to transcript standards.
Work with both the Bosnian Interviews and HrAL corpora would require performing a high load of additional preprocessing. Importantly, the two corpora are not comparable. While Croatian transcripts contain mostly conversations, Bosnian Interviews are rather spoken narratives. As a consequence studying CLs is more feasible in the case of Bosnian data. Therefore, we decided that the first attempt to study the behaviour and distribution of CLs would be in spoken Bosnian, in particular concerning the influence of discourse structuring elements and disfluencemes on CL placement.\footnote{\textcolor{black}{For more information on discourse structuring elements and disfluencemes} see Section \ref{Principles of analysis of spoken language}.} The results of this study, as well as a more detailed description of the corpus, based on our own explorations, are described in Chapter \ref{Clitics in a corpus of a spoken variety}.
Given the lack of sufficient spoken dialectological corpora, we decided to work with the written sources described in detail in Chapter \ref{Clitics in dialects}.
\subsection{Clitic climbing in BCS}
\label{Clitic climbing in BCS}
In order to study the variation in constructions featuring verbal embeddings in the three South-Slavic varieties, a similar kind of data should be acquired for each variety. In that respect \{bs,hr,sr\}WaC are superior to other sources because, as explained above, a quite similar type of language variety is represented in all three web corpora. Additionally, the tagset and the query syntax are identical, so the results of searches are also comparable. Comparison in that respect across standard varieties on the basis of traditionally compiled corpora is barely possible, mainly due to the very limited searchability.
Web corpora are also unbeatable in terms of size. This increases the chances that even very rare variants of studied constructions will occur. For this reason they provide the best environment for examining the possibilities of CC from \textit{da}\textsubscript{2}-complements in Serbian, as described in Chapter \ref{A corpus-based study on CC in da constructions and the raising-control distinction (Serbian)} and in \citet*{JHK17b}.
Finally, as already mentioned, web corpora include user-generated content which represents spontaneous, non-edited, and thus very authentic language typical of ordinary users, present in fora, blogs, and reader comments. This type of language is not represented in the traditionally compiled corpora of BCS.\footnote{In some languages, e.g. Czech, this type of language is steadily coming to be incorporated also in monitor corpora, e.g. Koditex \citep{Zasina18}.} Since WaC are in a sense anonymous, as we rarely have access to sociolinguistic metadata, the possibilities for in-depth study of sociolinguistic variation are extremely limited. On the other hand, because Riznica has been available on the same online platform as hrWaC since spring 2018 and since it uses the same tagset as WaC, some conclusions can be drawn as to the factor of standard vs colloquial variety. Therefore in Chapter \ref{A corpus-based study on clitic climbing in infinitive complements in relation to the raising-control dichotomy and diaphasic variation (Croatian)} we study CC from infinitive complements in Croatian in the forum.hr URL domain and in Riznica.
|
#include "../include/server_config.hpp"
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
namespace PousseyServer
{
server_config_t::server_config_t( server_settings_t settings_ ) :
settings( settings_.configPath, settings_.checkingConfiguration, settings_.usingDaemon ),
errorFlag( false )
{
InitializeServerConfig();
}
bool server_config_t::HasError() const { return errorFlag; }
std::string server_config_t::Error() const { return error; }
void server_config_t::InitializeServerConfig()
{
if ( !settings.configPath.empty() ){
this->environmentVariables.insert( { "CONFIG_DIR", settings.configPath.string() } );
}
else {
this->UseDefaultConfigOptions();
}
try {
this->ReadConfigurationFile( settings.configPath.string() );
}
catch ( std::exception const & error ){
this->error = error.what();
this->errorFlag = true;
}
}
void server_config_t::UseDefaultConfigOptions()
{
paths.serverConfigPath = settings.configPath = boost::filesystem::path{ POUSSEY_DIR"/config/" };
paths.serverLogFilepath = boost::filesystem::path{ POUSSEY_DIR"/config/" };
paths.serverErrorFilepath = boost::filesystem::path{ POUSSEY_DIR"/config/" };
paths.serverExploitFilepath = boost::filesystem::path{ POUSSEY_DIR"/config/" };
serverVersion = container::string{ POUSSEY_SERVER_VERSION };
}
void server_config_t::ReadConfigurationFile( std::string const & path )
{
std::string const configurationFilename{ "/server_config.json" };
boost::filesystem::path fullConfigurationPath{ path + configurationFilename };
if ( !boost::filesystem::exists( fullConfigurationPath ) ){
throw std::exception{ "Configuration file/directory does not exist." };
}
boost::filesystem::ifstream file{ fullConfigurationPath };
if ( !file ){
throw std::exception{ "Unable to read the configuration file, make sure you have accessed privilege." };
}
this->ActivateServerRecord( file );
// if we are here, all is well and good.
if ( settings.checkingConfiguration ){
PousseyServer::Helper::LogErrorThenExit( "Server configurations correctly verified." );
}
}
void server_config_t::ActivateServerRecord( boost::filesystem::ifstream & file )
{
boost::property_tree::ptree ptree;
try {
boost::property_tree::json_parser::read_json( file, ptree );
}
catch ( boost::property_tree::json_parser_error const & parserError ){
std::ostringstream ss;
ss << "In " << parserError.filename() << ", line: " << parserError.line() << ", "
<< parserError.what();
BOOST_RETHROW std::exception{ ss.str().c_str() };
}
for ( auto const & keyValue : ptree )
{
auto key = keyValue.first;
if ( key == std::string{ "Binding" } ){
auto bindingValues = keyValue.second;
for ( auto const & bindings : bindingValues )
{
server_binding_t serverBinding;
serverBinding.bindingName = bindings.first;
for ( auto & bindingKeyValues : bindings.second )
{
auto const key = bindingKeyValues.first;
auto const value = bindingKeyValues.second.data();
if ( key == std::string{ "Interface" } ){
serverBinding.bindingIPAddress = value;
}
else if ( key == std::string{ "Port" } ) {
serverBinding.bindingPort = static_cast< unsigned short >( std::stoul( value ) );
}
else if ( key == std::string{ "MaxKeepAlive" } ){
serverBinding.bindingMaximumKeepAlive = std::stoul( value );
}
else if ( key == std::string{ "MaxRequestSize" } ){
serverBinding.bindingMaximumRequestSize = std::stoul( value );
}
else if ( key == std::string{ "MaxUploadSize" } ){
serverBinding.bindingMaximumUploadSize = std::stoull( value );
}
else {
throw std::runtime_error{ "Invalid key used in binding parameter: " + key };
}
}
configBindings.push_back( serverBinding );
}
}
else if ( key == std::string{ "Hostname" } ){
hostName = keyValue.second.data();
}
else if ( key == std::string{ "LogFile" } ){
paths.serverLogFilepath = keyValue.second.data();
}
else if ( key == std::string{ "ErrorLog" } ){
paths.serverErrorFilepath = keyValue.second.data();
}
else if ( key == std::string{ "DatabasePath" } ){
paths.serverDatabaseFilepath = keyValue.second.data();
}
else {
throw std::runtime_error{ "Invalid key found." };
}
}
BOOST_ASSERT( !hostName.empty() );
}
server_t::server_t( server_settings_t settings, boost::asio::io_service &service ):
serverConfigurationPtr(nullptr),
ioService( service )
{
serverConfigurationPtr.reset( new server_config_t{ settings } );
if ( serverConfigurationPtr->HasError() ){
PousseyServer::Helper::LogErrorThenExit( serverConfigurationPtr->Error() );
}
this->StartServer();
}
void server_t::StartServer()
{
std::fprintf( stderr, "Server started" );
unsigned short defaultPort = DEFAULT_PORT;
std::vector<boost::asio::ip::tcp::endpoint> hostEndpoints;
auto & bindings = serverConfigurationPtr->configBindings;
for ( unsigned int index = 0; index != bindings.size(); ++index ){
if ( bindings[ index ].bindingIPAddress.empty() )
{
bindings[ index ].bindingIPAddress = serverConfigurationPtr->hostName;
}
if ( 0 == bindings[ index ].bindingPort )
{
bindings[ index ].bindingPort = defaultPort++;
}
hostEndpoints.emplace_back( boost::asio::ip::address::from_string( bindings[ index ].bindingIPAddress ),
bindings[ index ].bindingPort );
}
try {
auto acceptor = std::make_shared<boost::asio::ip::tcp::acceptor>( ioService, hostEndpoints[0] );
acceptor->set_option( boost::asio::socket_base::reuse_address( true ) );
std::fprintf( stderr, "%s, %d\n", acceptor->local_endpoint().address().to_string().c_str(),
acceptor->local_endpoint().port() );
this->StartAcceptingIncomingConnection( acceptor );
ioService.run();
}
catch ( boost::system::system_error const & errorCode )
{
Helper::LogErrorThenExit( errorCode.what() );
}
}
void server_t::StartAcceptingIncomingConnection( std::shared_ptr<boost::asio::ip::tcp::acceptor> acceptor )
{
auto httpSocket = std::make_shared<boost::asio::ip::tcp::socket>( ioService );
auto functor = [this, httpSocket, acceptor] ( boost::system::error_code const & errorCode )
{
this->StartAcceptingIncomingConnection( acceptor );
if ( !errorCode )
{
boost::asio::ip::tcp::no_delay option( true );
httpSocket->set_option( option );
this->StartReadingRequests( httpSocket );
}
};
acceptor->async_accept( *httpSocket, functor );
}
void server_t::StartReadingRequests( std::shared_ptr<boost::asio::ip::tcp::socket> socket )
{
auto request = std::make_shared<http::request_t>();
request->ReadRemoteEndpointData( *socket );
boost::asio::async_read_until( *socket, request->content.stream_buffer, "\r\n\r\n",
boost::bind( &server_t::OnReadCompleted, this, _1, _2, socket, request ) );
}
// ToDo
void server_t::OnReadCompleted( boost::system::error_code const & errorCode,
size_t bytesTransferred, server_t::http_socket_ptr_t socket, std::shared_ptr<http::request_t> request )
{
}
} |
<center>
# Shenfun - High-Performance Computing platform for the Spectral Galerkin method
<div></div>
# Shenfun - facts
1. Shenfun is named in honour of <strong>Professor Jie Shen</strong> for his seminal work on the spectral Galerkin method:-)
2. Shenfun is a high performance computing platform for solving partial differential equations (PDEs) with the spectral Galerkin method.
3. Shenfun has been run with 65,000 processors on a Cray XC40.
4. Shenfun is a high-level <strong>Python</strong> package originally developed for pseudo-spectral turbulence simulations.
<p style="clear: both;">
# The Spectral Galerkin method
## Advantages
- Accuracy (spectral)
- Sparsity - very low memory use for coefficient matrices
- Efficiency - Very fast linear algebra solvers due to sparsity
- Robustness (round-off errors) - condition numbers much lower than for collocation methods
## Disadvantages
- No complex grids. Structured tensor product grids only
- Nonlinear terms must be implemented explicitly (pseudospectral)
- Generally considered more difficult to implement since we solve equations in spectral space
# The Spectral Galerkin method (in a nutshell)
approximates solutions $u(x)$ using global <strong>trial</strong> functions $\phi_k(x)$ and unknown expansion coefficients $\hat{u}_k$
$$
u(x) = \sum_{k=0}^{N-1}\hat{u}_k \phi_k(x)
$$
Multidimensional solutions are formed from outer (tensor) products of 1D bases
$$
u(x, y) = \sum_{k=0}^{N_0-1}\sum_{l=0}^{N_1-1}\hat{u}_{kl} \phi_{kl}(x, y)\quad \text{ or }\quad
u(x, y, z) = \sum_{k=0}^{N_0-1}\sum_{l=0}^{N_1-1} \sum_{m=0}^{N_2-1}\hat{u}_{klm} \phi_{klm}(x, y, z)
$$
where, for example
$$
\begin{align}
\phi_{kl}(x, y) &= T_k(x) L_l(y)\\
\phi_{klm}(x, y, z) &= T_k(x) L_l(y) \exp(\text{i}mz)
\end{align}
$$
$T_k$ and $L_k$ are Chebyshev and Legendre polynomials.
# The Spectral Galerkin method
solves PDEs, like Poisson's equation
\begin{align}
\nabla^2 u(x) &= f(x), \quad x \in [-1, 1] \\
u(\pm 1) &= 0
\end{align}
using variational forms by the <strong>method of weighted residuals</strong>. I.e., multiply PDE by a test function $v$ and integrate over the domain. For Poisson this leads to the problem:
Find $u \in H^1_0$ such that
$$(\nabla u, \nabla v)_w^N = -(f, v)_w^N \quad \forall v \in H^1_0$$
Here $(u, v)_w^{N}$ is a weighted inner product and $v(=\phi_j)$ is a <strong>test</strong> function.
# Weighted inner products
The weighted inner product is defined as
$$
(u, v)_w = \int_{\Omega} u \overline{v} w \, d\Omega,
$$
where $w(\mathbf{x})$ is a weight associated with the chosen basis (different bases have different weights). The overline represents a complex conjugate (for Fourier).
$\Omega$ is a Cartesian product domain spanned by the chosen 1D bases.
# In Shenfun quadrature is used for the integrals
1D with Chebyshev basis:
$$
(u, v)_w ^N = \sum_{i=0}^{N-1} u(x_i) v(x_i) \omega_i \approx \int_{-1}^1 \frac{u v}{\sqrt{1-x^2}} \, {dx},
$$
where $\{\omega_i\}_{i=0}^{N-1}$ are the quadrature weights associated with the chosen basis and quadrature rule. The associated quadrature points are denoted as $\{x_i\}_{i=0}^{N-1}$.
2D with mixed Chebyshev-Fourier:
$$
(u, v)_w^N = \int_{-1}^1\int_{0}^{2\pi} \frac{u \overline{v}}{2\pi\sqrt{1-x^2}} \, {dxdy} \approx \sum_{i=0}^{N_0-1}\sum_{j=0}^{N_1-1} u(x_i, y_j) \overline{v}(x_i, y_j) \omega^{(x)}_i \omega_j^{(y)} ,
$$
# Spectral Galerkin solution procedure
1. Choose function space(s) satisfying the correct boundary conditions
2. Transform PDEs to variational forms using inner products
3. Assemble variational forms and solve resulting linear algebra systems
# Orthogonal bases
<p style="margin-bottom:1cm;">
| Family | Basis | Weight | Domain |
| :---: | :---: | :---: | :---: |
| Chebyshev | $$\{T_k\}_{k=0}^{N-1}$$ | $$1/\sqrt{1-x^2}$$ | $$[-1, 1]$$ |
| Legendre | $$\{L_k\}_{k=0}^{N-1}$$ | 1 |$$[-1, 1]$$ |
| Jacobi | $$\{J_k^{(\alpha,\beta)}\}_{k=0}^{N-1}$$ | $$(1-x)^{\alpha}(1+x)^{\beta}$$ | $$[-1, 1]$$ |
| Fourier | $$\{\exp(\text{i}kx)\}_{k=-N/2}^{N/2-1}$$| $$1/(2\pi)$$ |$$[0, 2\pi]$$ |
| Hermite | $$\{H_k\}_{k=0}^{N-1}$$ | $$e^{-x^2/2}$$ | $$[-\infty, \infty]$$|
| Laguerre | $$\{La_k\}_{k=0}^{N-1}$$ | $e^{-x/2}$ | $$[0, \infty]$$ |
```python
from shenfun import *
N = 8
C = FunctionSpace(N, 'Chebyshev', quad='GC', domain=[-2, 2])
L = FunctionSpace(N, 'Legendre')
x, w = C.points_and_weights()
print(C.points_and_weights())
C.sympy_basis(4)
```
# Jie Shen's bases with Dirichlet bcs
<p style="margin-bottom:1cm;">
| family | Basis | Boundary condition |
|-----------|-----------------------|----------|
| Chebyshev | $$\{T_k-T_{k+2}\}_{k=0}^{N-3}$$ | $$u(\pm 1) = 0$$ |
| Legendre | $$\{L_k-L_{k+2}\}_{k=0}^{N-3}$$ | $$u(\pm 1) = 0$$ |
| Hermite | $$\exp(-x^2)\{H_k\}_{k=0}^{N-1}$$ | $$u(\pm \infty) = 0$$ |
| Laguerre | $$\exp(-x/2)\{La_k-La_{k+1}\}_{k=0}^{N-2}$$| $$u(0) = u(\infty) = 0$$ |
Composite bases are implemented using a stencil matrix, such that
$$
\phi_i = \sum_{j=0}^{N-1} K_{ij}Q_j
$$
where $K$ is the stencil matrix and $\{Q_j\}_{j=0}^{N-1}$ are the orthogonal polynomials, like $T_j$ or $L_j$.
```python
N = 8
C0 = FunctionSpace(N, 'Chebyshev', bc=(0, 0))
L0 = FunctionSpace(N, 'Legendre', bc=(0, 0))
H0 = FunctionSpace(N, 'Hermite')
La = FunctionSpace(N, 'Laguerre', bc=(0, 0))
L0.stencil_matrix().diags().toarray()
```
# Shen's bases with Neumann $u'(\pm 1) = 0$
<p style="margin-bottom:1cm;">
| family | Basis |
|-----------|-----------------------|
| Chebyshev | $$\left\{T_k-\frac{k^2}{(k+2)^2}T_{k+2}\right\}_{k=0}^{N-3}$$ |
| Legendre | $$\left\{L_k-\frac{k(k+1)}{(k+2)(k+3)}L_{k+2}\right\}_{k=0}^{N-3}$$ |
```python
CN = FunctionSpace(N, 'Chebyshev', bc={'left': ('N', 0), 'right': ('N', 0)})
LN = FunctionSpace(N, 'Legendre', bc={'left': ('N', 0), 'right': ('N', 0)})
dict(CN.stencil_matrix())
```
# Shen's biharmonic bases $u(\pm 1) = u'(\pm 1) = 0$
<p style="margin-bottom:1cm;">
| family | Basis |
|-----------| :-----------------: |
| Chebyshev | $$\left\{T_k-\frac{2(k+2)}{k+3}T_{k+2}+\frac{k+1}{k+3} T_{k+4}\right\}_{k=0}^{N-5}$$ |
| Legendre | $$\left\{L_k-\frac{2(2k+5)}{(2k+7)}L_{k+2}+\frac{2k+3}{2k+7}L_{k+4}\right\}_{k=0}^{N-5}$$ |
```python
CB = FunctionSpace(N, 'Chebyshev', bc=(0, 0, 0, 0))
LB = FunctionSpace(N, 'Legendre', bc=(0, 0, 0, 0))
dict(CB.stencil_matrix())
```
# Multidimensional tensor product spaces
<p style="margin-bottom:0.5cm;">
$$
\begin{align}
L_0 &= \{L_k(x)-L_{k+2}(x)\}_{k=0}^{N-3} \\
C_0 &= \{T_k(x)-T_{k+2}(x)\}_{k=0}^{N-3} \\
L_1 &= \{L_l(y)\}_{l=0}^{N-1} \\
LL(x, y) &= L_0(x) \otimes L_1(y) \\
CL(x, y) &= C_0(x) \otimes L_1(y)
\end{align}
$$
```python
L0 = FunctionSpace(N, 'Legendre', bc=(0, 0))
C0 = FunctionSpace(N, 'Chebyshev', bc=(0, 0))
L1 = FunctionSpace(N, 'Legendre')
LL = TensorProductSpace(comm, (L0, L1)) # comm is MPI.COMM_WORLD
CL = TensorProductSpace(comm, (C0, L1))
V = VectorSpace(LL) # For vector valued functions
f = Array(LL)
```
# Operators in shenfun
Act on instances of a `TestFunction`, `TrialFunction` or `Function`
- div
- grad
- curl
- Dx (for a partial derivative)
# Assembly
- project
- inner
```python
L0 = FunctionSpace(N, 'Legendre', bc=(0, 0))
L1 = FunctionSpace(N, 'Legendre')
u = TrialFunction(L0)
v = TestFunction(L0)
uh = Function(L0)
g = Array(L0)
du = grad(u) # vector valued expression
h = div(du) # scalar valued expression
A = inner(Dx(u, 0, 2), v)
dict(A)
```
# The shenfun `Function` represents the solution
`uh = Function(L0)`
$$
u_h(x) = \sum_{k=0}^{N-1} \hat{u}_k \phi_{k}(x)
$$
The function evaluated for all quadrature points, $\{x_j\}_{j=0}^{N-1}$, is an `Array`
`uj = Array(L0)`
There is a (fast) `backward` transform for moving from `Function` to `Array`, and a `forward` transform to go the other way.
```python
uj = Array(L0)
uj = uh.backward(uj)
uh = uj.forward(uh)
```
# Projections
Project $g(\mathbf{x})$ to $V$:
Find $u$ in $V$ such that:
$$(u, v)_w = (I^Ng, v)_w \quad \text{for} \, v \in V $$
where $I^Ng$ is $\{g(x_j)\}_{j=0}^{N-1}$, i.e., $g(x)$ evaluated on the quadrature mesh.
Works if $g(x)$ is
- an `Array`, which is exactly a `Function` evaluated on the mesh
- an expression involving a `Function`, like `div(grad(uh))`
- a `sympy` expression, like `sin(x)`
```python
dudx = project(Dx(uh, 0, 1), L1) # Compute du/dx
wh = project(uj, L1)
import sympy as sp
x, y = sp.symbols('x,y')
ws = project(sp.sin(4*x), L1)
ws.eval(np.array([0.51]))
```
# Implementation matches mathematics
<p style="margin-bottom:1cm;">
$$
A = (\nabla u, \nabla v)_w^N
$$
```python
A = inner(grad(u), grad(v))
```
```python
dict(A)
```
```python
print(A.diags().todense())
```
A diagonal stiffness matrix!
# Complete Poisson solver with error verification in 1D
```python
# Solve Poisson's equation
import matplotlib.pyplot as plt
from sympy import symbols, sin, cos, lambdify
from shenfun import *
# Use sympy to compute manufactured solution
x, y = symbols("x,y")
ue = sin(6*sp.pi*x)*(1-x**2) # `ue` is the manufactured solution
fe = ue.diff(x, 2) # `fe` is Poisson's right hand side for `ue`
SD = FunctionSpace(50, 'L', bc=(0, 0))
u = TrialFunction(SD)
v = TestFunction(SD)
b = inner(v, Array(SD, buffer=fe)) # Array is initialized with `fe`
A = inner(v, div(grad(u)))
uh = Function(SD)
uh = A.solve(b, uh)
ue = Array(SD, buffer=ue)
print("L2-error = ", np.sqrt(inner(1, (uh.backward()-ue)**2)))
```
```python
fe
```
```python
plt.plot(SD.mesh(), uh.backward(), SD.mesh(), ue)
```
# 2D - still closely matching mathematics
```python
L0 = FunctionSpace(N, 'Legendre', bc=(0, 0))
F1 = FunctionSpace(N, 'Fourier', dtype='d')
TP = TensorProductSpace(comm, (L0, F1))
u = TrialFunction(TP)
v = TestFunction(TP)
A = inner(grad(u), grad(v))
```
```python
print(A)
```
# ?
A is a list of two TPMatrix objects???
# `TPMatrix` is a Tensor Product matrix
A `TPMatrix` is the outer product of smaller matrices (2 in 2D, 3 in 3D etc).
Consider the inner product:
$$
\begin{align}
(\nabla u, \nabla v)_w &= \frac{1}{2\pi}\int_{-1}^{1}\int_{0}^{2\pi} \left(\frac{\partial u}{\partial x}, \frac{\partial u}{\partial y}\right) \cdot \left(\frac{\partial \overline{v}}{\partial x}, \frac{\partial \overline{v}}{\partial y}\right) {dxdy} \\
(\nabla u, \nabla v)_w &= \frac{1}{2\pi}\int_{-1}^1 \int_{0}^{2\pi} \frac{\partial u}{\partial x}\frac{\partial \overline{v}}{\partial x} {dxdy} + \int_{-1}^1 \int_{0}^{2\pi} \frac{\partial u}{\partial y}\frac{\partial \overline{v}}{\partial y} {dxdy}
\end{align}
$$
which, like `A`, is a sum of two terms. These two terms are the two `TPMatrix`es returned by `inner` above.
Now each one of these two terms can be written as the outer product of two smaller matrices.
Consider the first, inserting for test and trial functions
$$
\begin{align}
v &= \phi_{kl} = (L_k(x)-L_{k+2}(x))\exp(\text{i}ly) \\
u &= \phi_{mn}
\end{align}
$$
The first term becomes
$$
\small
\begin{align}
\int_{-1}^1 \int_{0}^{2\pi} \frac{\partial u}{\partial x}\frac{\partial \overline{v}}{\partial x} \frac{dxdy}{2\pi} &= \underbrace{\int_{-1}^1 \frac{\partial (L_m-L_{m+2})}{\partial x}\frac{\partial (L_k-L_{k+2})}{\partial x} {dx}}_{a_{km}} \underbrace{\int_{0}^{2\pi} \exp(iny) \exp(-ily) \frac{dy}{2\pi}}_{\delta_{ln}} \\
&= a_{km} \delta_{ln}
\end{align}
$$
and the second
$$
\small
\begin{align}
\int_{-1}^1 \int_{0}^{2\pi} \frac{\partial u}{\partial y}\frac{\partial \overline{v}}{\partial y} \frac{dxdy}{2\pi} &= \underbrace{\int_{-1}^1 (L_m-L_{m+2})(L_k-L_{k+2}) {dx}}_{b_{km}} \underbrace{\int_{0}^{2\pi} ln \exp(iny) \exp(-ily)\frac{dy}{2\pi}}_{l^2\delta_{ln}} \\
&= l^2 b_{km} \delta_{ln}
\end{align}
$$
All in all:
$$
(\nabla u, \nabla v)_w = \left(a_{km} \delta_{ln} + l^2 b_{km} \delta_{ln}\right)
$$
The sum of two tensor product matrices!
```python
A = inner(grad(u), grad(v)) # <- list of two TPMatrices
for mat in A[1].mats: # a_{km} and \delta_{ln}
print(mat.diags().todense())
```
```python
plt.spy(A[1].diags(), markersize=1)
```
# 3D Poisson (with MPI and Fourier x 2)
```python
from sympy import symbols, sin, cos, lambdify
from shenfun import *
# Use sympy to compute manufactured solution
x, y, z = symbols("x,y,z")
ue = (cos(4*x) + sin(2*y) + sin(4*z))*(1-x**2)
fe = ue.diff(x, 2) + ue.diff(y, 2) + ue.diff(z, 2)
C0 = FunctionSpace(32, 'Chebyshev', bc=(0, 0))
F1 = FunctionSpace(32, 'Fourier', dtype='D')
F2 = FunctionSpace(32, 'Fourier', dtype='d')
T = TensorProductSpace(comm, (C0, F1, F2))
u = TrialFunction(T)
v = TestFunction(T)
# Assemble left and right hand
f_hat = inner(v, Array(T, buffer=fe))
A = inner(v, div(grad(u)))
# Solve
solver = chebyshev.la.Helmholtz(*A) # Very fast solver due to Jie Shen
u_hat = Function(T)
u_hat = solver(f_hat, u_hat)
assert np.linalg.norm(u_hat.backward()-Array(T, buffer=ue)) < 1e-12
print(u_hat.shape)
```
# Contour plot of slice with constant y
```python
X = T.local_mesh()
ua = u_hat.backward()
plt.contourf(X[2][0, 0, :], X[0][:, 0, 0], ua[:, 2], 100)
plt.colorbar()
```
# Run with MPI distribution of arrays
Here we would normally run from a bash shell
<p style="margin-bottom:0.5cm;">
<div style="color:black"> <strong>[bash shell] mpirun -np 4 python poisson3D.py </strong> </div>
Since we are in a Jupyter notebook, lets actually do this from python in a live cell:-) The exclamation mark '!' is a magic command to run bash scripts in Jupyter.
```python
!mpirun -np 8 python poisson3D.py
```
Note that Fourier bases are especially attractive because of features easily handled with MPI:
- diagonal matrices
- fast transforms
# Nonlinearities (convolution)
All treated with pseudo-spectral techniques
$$
\begin{align}
\hat{w}_k &= \widehat{u^2}_k
\end{align}
$$
That is, transform `Function`s to real space `Array`s, perform the nonlinear operation there and transform the nonlinear product back to spectral space (to a `Function`).
3/2-rule or 2/3-rule is possible for dealiasing with Fourier. Not for the remaining bases.
```python
uj = Array(SD)
#uj[:] = np.random.random(uj.shape)
uj = uh.backward(uj)
wh = Function(SD)
wh = SD.forward(uj*uj, wh)
```
# Mixed tensor product spaces
Solve several equations simultaneously
- Coupled equations
- Block matrices and vectors
- Tensor spaces of vectors, like velocity $u \in [\mathbb{R}^3]^3$
# Stokes equations
### lid-driven cavity - coupled solver
<p style="margin-bottom:0.25cm;">
$$
\begin{align*}
\nabla^2 \mathbf{u} - \nabla p &= \mathbf{f} \quad \text{in } \Omega, \quad \quad \Omega = [-1, 1]\times[-1, 1]\\
\nabla \cdot \mathbf{u} &= h \quad \text{in } \Omega \\
\int_{\Omega} p dx &= 0 \\
\mathbf{u}(\pm 1, y) = \mathbf{u}(x, -1) = (0, 0) &\text{ and }\mathbf{u}(x, 1) = (1, 0) \text{ or } ((1-x^2)(1+x^2), 0)
\end{align*}
$$
Given appropriate spaces $V$ and $Q$ a variational form reads: find $(\mathbf{u}, p) \in V \times Q$ such that
$$
\begin{equation}
a((\mathbf{u}, p), (\mathbf{v}, q)) = L((\mathbf{v}, q)) \quad \forall (\mathbf{v}, q) \in V \times Q
\end{equation}
$$
where bilinear and linear forms are, respectively
$$
\begin{equation}
a((\mathbf{u}, p), (\mathbf{v}, q)) = \int_{\Omega} (\nabla^2 \mathbf{u} - \nabla p) \cdot {\mathbf{v}} \, dx_w + \int_{\Omega} \nabla \cdot \mathbf{u} \, {q} \, dx_w,
\end{equation}
$$
$$
\begin{equation}
L((\mathbf{v}, q)) = \int_{\Omega} \mathbf{f} \cdot {\mathbf{v}}\, dx_w + \int_{\Omega} h {q} \, dx_w
\end{equation}
$$
Using integration by parts for Legendre
$$
\begin{equation}
a((\mathbf{u}, p), (\mathbf{v}, q)) = -\int_{\Omega} \nabla \mathbf{u} \cdot \nabla{\mathbf{v}} \, dx_w + \int_{\Omega} \nabla \cdot \mathbf{v} \, {p} \, dx_w + \int_{\Omega} \nabla \cdot \mathbf{u} \, {q} \, dx_w,
\end{equation}
$$
# Implementation of spaces, basis functions
```python
N = (40, 40)
family = 'Legendre'
D0X = FunctionSpace(N[0], 'Legendre', bc=(0, 0))
#D1Y = FunctionSpace(N[1], 'Legendre', bc=(1, 0)) # Regular lid
D1Y = FunctionSpace(N[1], 'Legendre', bc=(0, (1-x)**2*(1+x)**2)) # Regularized lid
D0Y = FunctionSpace(N[1], 'Legendre', bc=(0, 0))
PX = FunctionSpace(N[0], 'Legendre')
PY = FunctionSpace(N[1], 'Legendre')
# All required spaces
V1 = TensorProductSpace(comm, (D0X, D1Y))
V0 = TensorProductSpace(comm, (D0X, D0Y))
Q = TensorProductSpace(comm, (PX, PY), modify_spaces_inplace=True)
V = VectorSpace([V1, V0])
W = CompositeSpace([V0, V0])
VQ = CompositeSpace([V, Q])
# For inf-sup use P_N - P_{N-2} for velocity-pressure
PX.slice = lambda: slice(0, PX.N-2)
PY.slice = lambda: slice(0, PY.N-2)
# All required test and trial functions
up = TrialFunction(VQ)
vq = TestFunction(VQ)
u, p = up
v, q = vq
```
# Implementation Stokes - matrices and solve
```python
# Assemble matrices
A = inner(grad(v), -grad(u))
G = inner(div(v), p)
D = inner(q, div(u))
# Create Block matrix
sol = la.BlockMatrixSolver(A+G+D)
# Functions to hold solution and rhs
up_hat = Function(VQ)
fh_hat = Function(VQ)
# Solve Stokes problem. Note constraint for pressure
up_hat = sol(fh_hat, u=up_hat, constraints=((2, 0, 0),))
# Move solution to Array in real space
up = up_hat.backward()
u_, p_ = up
```
```python
X = Q.local_mesh(True)
plt.quiver(X[0], X[1], u_[0], u_[1])
```
# Sparsity pattern of block matrix
$$
M =
\begin{bmatrix}
A[0]+A[1] & 0 & G[0] \\
0 & A[2]+A[3] & G[1] \\
D[0] & D[1] & 0
\end{bmatrix}
$$
```python
%matplotlib notebook
plt.figure(figsize=(6,4))
plt.spy(sol.mat.diags(), markersize=0.5)
```
# Block matrix
$$
M =
\begin{bmatrix}
A[0]+A[1] & 0 & G[0] \\
0 & A[2]+A[3] & G[1] \\
D[0] & D[1] & 0
\end{bmatrix}
$$
where $D = G^T$ for the Legendre basis, making $M$ symmetric. For Chebyshev $M$ will not be symmetric.
Solver through [scipy.sparse.linalg](https://docs.scipy.org/doc/scipy/reference/sparse.linalg.html)
For Navier-Stokes of the lid-driven cavity, see https://github.com/spectralDNS/shenfun/blob/master/demo/NavierStokesDrivenCavity.py
|
5 . The trihalides SbF
|
function [imageCha, ssim_map, metrics] = algo_FCSA_WaTMRI_2D_real( obj,input )
% 2D variant of WaTMRI
% based on Huang et al. paper on WaTMRI
%
% input:
% obj CS reconstruction object (holding all parameters)
% input struct containing recon parameters and image
%
% output:
% imageCha reconstructed channel individual image
% ssim_map structural similarity map
% metrics evaluation metrics
%
% (c) Marc Fischer, Thomas Kuestner, May 2015
% -------------------------------------------------------------------------
%%
timer_WaT = tic;
%% variables:
% internal flags
flag_wavetree = true;
flag_fast = true;
flag_extendImage = true;
% internal variables:
mue = 0.001;
L = 1;
t_old = 1;
NLTV_struct.kernelratio = 3;
NLTV_struct.windowratio = 6;
NLTV_struct.nThreads = 1; % mind this option if used with -singleCompThread on BWCluster
itrNLTV = obj.iNINNER - 5;
% chambolle tv:
parsin.MAXITER=100; parsin.tv='iso'; % 'iso' or 'l1'
% from obj:
maxitr = obj.iNINNER;
% n1 = obj.measPara.dim(1);
% n2 = obj.measPara.dim(2);
n1 = input.n1;
n2 = input.n2;
% nSlices = obj.measPara.dim(3);
nCha = obj.measPara.dim(5);
lambdaWave = obj.lambda;
lambdaTV = obj.lambdaTV;
lambdaGroup = obj.lambdaGroup;
NLTV_struct.filterstrength = obj.lambdaNLTV_h; % 0.03 % converted from NLTV h = 0.01 %old: used: 3e-10
lambdaNLTV = obj.lambdaNLTV;
lambdaNLTV_h = obj.lambdaNLTV_h;
regularizerWeights = obj.regularizerWeights;
flagTV = obj.flagTV;
flagTV_iso = obj.flagTV_iso;
flagWave = obj.flagWave;
flagGroup = obj.flagGroup;
flagNLTV = obj.flagNLTV;
flagSBNLTV = obj.flagSBNLTV;
waveletStages = obj.trafo.waveletStages;
waveletFilterName_l1 = obj.trafo.waveletFilterName_l1;
waveletFilterName_l12 = obj.trafo.waveletFilterName_l12;
% from input:
b=input.b;
mask = input.mask;
G_wat = input.G_wat;
Gt_wat = input.Gt_wat;
% groupnorm_index = input.groupnorm_index;
waveS_l1 = input.waveS_l1;
waveS_l12 = input.waveS_l12;
waveS_WaT = input.waveS_WaT;
WaT_extend_y = waveS_WaT(waveletStages+2,1) - waveS_l12(waveletStages+2,1);
WaT_extend_x = waveS_WaT(waveletStages+2,2) - waveS_l12(waveletStages+2,2);
z_WaT = cell(1,nCha);
% im_ref = input.im_ref;
% im_ref_full = zeros(n1,n2);
% for j = 1:nCha
% im_ref_full = im_ref_full + abs(im_ref{1,j}).^2;
% end;
% im_ref_full = sqrt(im_ref_full);
clear input
% initialize cells/vectors
for j=1:nCha
FTb{1,j} = real(iFFT2D(b{1,j}));
% y{1,j} = real(FTb{1,j});
% y{1,j+nCha} = imag(FTb{1,j});
end;
z = FTb; % starting point
y = z;
x_wave = cell(1,nCha);
x_helper = x_wave;
x_wave_helper = x_wave;
x_tv = x_wave;
x_nltv = x_wave;
for j=1:nCha
x_nltv{1,j} = 0;
end;
x_g = x_wave;
x_g_helper = x_wave;
x_g_WaT = x_wave;
%% MAD dependent lambdas:
flag_MAD = true;
if flag_MAD
x_wavedec = cell(1,nCha);
threshold = zeros(1:nCha);
for j=1:nCha % 2*nCha
x_wavedec{1,j} = wavedec2(z{1,j},waveletStages,waveletFilterName_l1); % atm only based on l1-daubechie
x_wave_fine_scale = size(x_wavedec{1,j},2) - (3*waveS_l1(waveletStages+1,1)*waveS_l1(waveletStages+1,2));
threshold(j) = mad(x_wavedec{1,j}(x_wave_fine_scale:end),1);
end;
clear x_wavedec
else
threshold(1:nCha) = 1;
end;
threshold_wave(j) = lambdaWave * threshold(j) * 2/L;
threshold_TV(j) = lambdaTV * threshold(j) * 2/L;
threshold_group(j) = lambdaGroup * threshold(j) * 2/L;
threshold_NLTV(j) = lambdaNLTV; % * threshold(j) * 2/L;
threshold_NLTV_h(j) = lambdaNLTV_h; %*threshold(j); % adjust carefully or NLTV won't find a solution. lambdaNLTV_h should be < 0.01
for j = 1:nCha
x_max(j) = max(max(z{1,1}))*1.0;
x_min(j) = min(min(z{1,1}))*1.0;
end;
%% initialize metrics:
itr = 0;
metrics.xtime(itr+1)= 0;
% [metrics, ssim_map{1,1}] = get_metrics_itr( im_ref, im_ref_full, z, itr, maxitr, nCha, n1, n2, metrics, obj.K_1, obj.K_2, obj.W_size, obj.W_sigma );
ssim_map = [];
%% recon
dispProgress('Proximal Average', 0, maxitr);
for itr = 1:maxitr % total iter counter
t_new = (1+sqrt(1+4*t_old^2))/2;
t_old = t_new;
y_old = z; % y_old = y for complex case
%% WaTMRI-Step
if itr > 1
if flagGroup
for j = 1:nCha
if flag_extendImage
z_WaT{1,j} = extend_image(y{1,j}, waveS_WaT, waveletStages, WaT_extend_y, WaT_extend_x);
x_g_helper{1,j} = wavedec2(z_WaT{1,j},waveletStages,waveletFilterName_l12);
else
x_g_helper{1,j} = wavedec2(z{1,j},waveletStages,waveletFilterName_l12);
end;
if flag_wavetree
x_g_helper{2,j} = (G_wat*x_g_helper{1,j}')';
else
x_g_helper{2,j} = zeros(1,size(x_g_helper{1,j},2));
end;
end;
x_g_helper = softthresh_group_2vec(x_g_helper,threshold_group(j),nCha); % threshold_wave(j)/threshold_group(j) acc. to author
for j = 1:nCha
x_g_WaT{1,j} = waverec2(x_g_helper{1,j}+(Gt_wat*x_g_helper{2,j}')',waveS_WaT,waveletFilterName_l12);
x_g{1,j} = x_g_WaT{1,j}(1:end-WaT_extend_y,1:end-WaT_extend_x);
end;
end;
else
for j = 1:nCha
x_g{1,j} = zeros(n1,n2);
z_WaT{1,j} = zeros(n1,n2);
end;
end;
%% landweber step + WaTMRI-part
for j = 1:nCha
x_helper{1,j} = real(iFFT2D(FFT2D_mask(z{1,j},mask))) -FTb{1,j} ;
if itr > 1 % Phi'*G'*G*Phi*z{1,j}
z_WaT{1,j} = extend_image(z{1,j}, waveS_WaT, waveletStages, WaT_extend_y, WaT_extend_x);
z_WaT{1,j} = trafo_WaT(z_WaT{1,j},waveletStages,waveletFilterName_l12,G_wat,Gt_wat);
z_WaT{1,j} = z_WaT{1,j}(1:end-WaT_extend_y,1:end-WaT_extend_x);
end;
z{1,j} = z{1,j} - (x_helper{1,j} + mue*(z_WaT{1,j} - x_g{1,j}))/L; % mue used as tradeoff parameter.
end;
%% l1-Wavelet
if flagWave
for j = 1:nCha % 2*nCha
x_wave_helper{1,j} = wavedec2(z{1,j},waveletStages,waveletFilterName_l1);
x_wave_helper{1,j} = softthresh_real(x_wave_helper{1,j},threshold_wave(j));
x_wave{1,j} = waverec2(x_wave_helper{1,j},waveS_l1,waveletFilterName_l1);
end;
end;
%% TV
if flagTV
if ~flagTV_iso
for j = 1:nCha
x_tv{1,j} = MTV_2D(z{1,j},threshold_TV(j),n1,n2);
end;
else
for j = 1:nCha
if (itr==1)
[x_tv{1,j}, P]=denoise_TV_One((z{1,j}), threshold_TV(j),-inf,inf,[],parsin);
else
[x_tv{1,j}, P]=denoise_TV_One((z{1,j}), threshold_TV(j),-inf,inf,P,parsin);
end;
end;
end;
end;
%% NLTV
if flagNLTV
if itr >= itrNLTV
if flagSBNLTV
for j = 1:nCha
x_nltv{1,j} = SB_NLTVfunc_slim_rescale(z{1,j},n1,n2, threshold_NLTV(j), threshold_NLTV_h(j) );
end;
else
for j = 1:nCha
% if mod(itr,5) == 0 || itr == 1
x_nltv{1,j} = NLMF(z{1,j},NLTV_struct);
x_nltv{1,j} = (L.*z{1,j} + 2*threshold_NLTV(j)*x_nltv{1,j})./(L+2*threshold_NLTV(j));
% end;
end;
end;
else
x_nltv{1,j} = 0;
end;
end;
%% add prox(.)
for j = 1:nCha
y{1,j} = zeros(n1,n2);
if flagWave y{1,j} = y{1,j} + x_wave{1,j}.*regularizerWeights(1); end;
if flagTV y{1,j} = y{1,j} + x_tv{1,j}.*regularizerWeights(2); end;
% if flagGroup y{1,j} = y{1,j} + x_g{1,j}.*regularizerWeights(3); end;
if flagNLTV y{1,j} = y{1,j} + x_nltv{1,j}.*regularizerWeights(4); end;
if ~flagWave && ~flagTV && ~flagNLTV
y{1,j} = z{1,j};
y{1,j}(y{1,j} > x_max(j)) = x_max;
y{1,j}(y{1,j} < x_min(j)) = x_min;
else
if itr < itrNLTV
y{1,j} = y{1,j}/(flagTV.*regularizerWeights(2) + flagWave.*regularizerWeights(1)); % flagGroup.*regularizerWeights(3));
else
y{1,j} = y{1,j}/(flagTV.*regularizerWeights(2) + flagNLTV.*regularizerWeights(4) + flagWave.*regularizerWeights(1)); % + flagGroup.*regularizerWeights(3));
end;
end;
flag_fast = true;
if flag_fast
z{1,j}=y{1,j}+((t_old-1)/t_new).*(y{1,j}-y_old{1,j});
end;
end;
%% metrics of current itr:
% disp(itr);
dispProgress('Proximal Average', itr/maxitr);
metrics.xtime(itr+1)= toc(timer_WaT);
for j = 1:nCha
z{1,j} = z{1,j};
end;
% [metrics, ssim_map{1,2}] = get_metrics_itr( im_ref, im_ref_full, z, itr, maxitr, nCha, n1, n2, metrics, obj.K_1, obj.K_2, obj.W_size, obj.W_sigma );
end;
dispProgress('Proximal Average', 'Close');
imageCha = z;
for j = 1:nCha
imageCha{1,j} = turn_image( imageCha{1,j} );
end;
% for j = 1:nCha+1
% ssim_map{1,1}{1,j} = turn_image( ssim_map{1,1}{1,j} );
% ssim_map{1,2}{1,j} = turn_image( ssim_map{1,2}{1,j} );
% end;
end
|
(* Author: Tobias Nipkow
Copyright 1998 TUM
To generate a regular expression, the alphabet must be finite.
regexp needs to be supplied with an 'a list for a unique order
add_Atom d i j r a = (if d a i = j then Union r (Atom a) else r)
atoms d i j as = foldl (add_Atom d i j) Empty as
regexp as d i j 0 = (if i=j then Union (Star Empty) (atoms d i j as)
else atoms d i j as
*)
header "From deterministic automata to regular sets"
theory RegSet_of_nat_DA
imports "../Regular-Sets/Regular_Set" DA
begin
type_synonym 'a nat_next = "'a => nat => nat"
abbreviation
deltas :: "'a nat_next => 'a list => nat => nat" where
"deltas == foldl2"
primrec trace :: "'a nat_next => nat => 'a list => nat list" where
"trace d i [] = []" |
"trace d i (x#xs) = d x i # trace d (d x i) xs"
(* conversion a la Warshall *)
primrec regset :: "'a nat_next => nat => nat => nat => 'a list set" where
"regset d i j 0 = (if i=j then insert [] {[a] | a. d a i = j}
else {[a] | a. d a i = j})" |
"regset d i j (Suc k) =
regset d i j k Un
(regset d i k k) @@ (star(regset d k k k)) @@ (regset d k j k)"
definition
regset_of_DA :: "('a,nat)da => nat => 'a list set" where
"regset_of_DA A k = (UN j:{j. j<k & fin A j}. regset (next A) (start A) j k)"
definition
bounded :: "'a nat_next => nat => bool" where
"bounded d k = (!n. n < k --> (!x. d x n < k))"
declare
in_set_butlast_appendI[simp,intro] less_SucI[simp] image_eqI[simp]
(* Lists *)
lemma butlast_empty[iff]:
"(butlast xs = []) = (case xs of [] => True | y#ys => ys=[])"
by (cases xs) simp_all
lemma in_set_butlast_concatI:
"x:set(butlast xs) ==> xs:set xss ==> x:set(butlast(concat xss))"
apply (induct "xss")
apply simp
apply (simp add: butlast_append del: ball_simps)
apply (rule conjI)
apply (clarify)
apply (erule disjE)
apply (blast)
apply (subgoal_tac "xs=[]")
apply simp
apply (blast)
apply (blast dest: in_set_butlastD)
done
(* Regular sets *)
(* The main lemma:
how to decompose a trace into a prefix, a list of loops and a suffix.
*)
lemma decompose[rule_format]:
"!i. k : set(trace d i xs) --> (EX pref mids suf.
xs = pref @ concat mids @ suf &
deltas d pref i = k & (!n:set(butlast(trace d i pref)). n ~= k) &
(!mid:set mids. (deltas d mid k = k) &
(!n:set(butlast(trace d k mid)). n ~= k)) &
(!n:set(butlast(trace d k suf)). n ~= k))"
apply (induct "xs")
apply (simp)
apply (rename_tac a as)
apply (intro strip)
apply (case_tac "d a i = k")
apply (rule_tac x = "[a]" in exI)
apply simp
apply (case_tac "k : set(trace d (d a i) as)")
apply (erule allE)
apply (erule impE)
apply (assumption)
apply (erule exE)+
apply (rule_tac x = "pref#mids" in exI)
apply (rule_tac x = "suf" in exI)
apply simp
apply (rule_tac x = "[]" in exI)
apply (rule_tac x = "as" in exI)
apply simp
apply (blast dest: in_set_butlastD)
apply simp
apply (erule allE)
apply (erule impE)
apply (assumption)
apply (erule exE)+
apply (rule_tac x = "a#pref" in exI)
apply (rule_tac x = "mids" in exI)
apply (rule_tac x = "suf" in exI)
apply simp
done
lemma length_trace[simp]: "!!i. length(trace d i xs) = length xs"
by (induct "xs") simp_all
lemma deltas_append[simp]:
"!!i. deltas d (xs@ys) i = deltas d ys (deltas d xs i)"
by (induct "xs") simp_all
lemma trace_append[simp]:
"!!i. trace d i (xs@ys) = trace d i xs @ trace d (deltas d xs i) ys"
by (induct "xs") simp_all
lemma trace_concat[simp]:
"(!xs: set xss. deltas d xs i = i) ==>
trace d i (concat xss) = concat (map (trace d i) xss)"
by (induct "xss") simp_all
lemma trace_is_Nil[simp]: "!!i. (trace d i xs = []) = (xs = [])"
by (case_tac "xs") simp_all
lemma trace_is_Cons_conv[simp]:
"(trace d i xs = n#ns) =
(case xs of [] => False | y#ys => n = d y i & ns = trace d n ys)"
apply (case_tac "xs")
apply simp_all
apply (blast)
done
lemma set_trace_conv:
"!!i. set(trace d i xs) =
(if xs=[] then {} else insert(deltas d xs i)(set(butlast(trace d i xs))))"
apply (induct "xs")
apply (simp)
apply (simp add: insert_commute)
done
lemma deltas_concat[simp]:
"(!mid:set mids. deltas d mid k = k) ==> deltas d (concat mids) k = k"
by (induct mids) simp_all
lemma lem: "[| n < Suc k; n ~= k |] ==> n < k"
by arith
lemma regset_spec:
"!!i j xs. xs : regset d i j k =
((!n:set(butlast(trace d i xs)). n < k) & deltas d xs i = j)"
apply (induct k)
apply(simp split: list.split)
apply(fastforce)
apply (simp add: conc_def)
apply (rule iffI)
apply (erule disjE)
apply simp
apply (erule exE conjE)+
apply simp
apply (subgoal_tac
"(!m:set(butlast(trace d k xsb)). m < Suc k) & deltas d xsb k = k")
apply (simp add: set_trace_conv butlast_append ball_Un)
apply (erule star_induct)
apply (simp)
apply (simp add: set_trace_conv butlast_append ball_Un)
apply (case_tac "k : set(butlast(trace d i xs))")
prefer 2 apply (rule disjI1)
apply (blast intro:lem)
apply (rule disjI2)
apply (drule in_set_butlastD[THEN decompose])
apply (clarify)
apply (rule_tac x = "pref" in exI)
apply simp
apply (rule conjI)
apply (rule ballI)
apply (rule lem)
prefer 2 apply simp
apply (drule bspec) prefer 2 apply assumption
apply simp
apply (rule_tac x = "concat mids" in exI)
apply (simp)
apply (rule conjI)
apply (rule concat_in_star)
apply (clarsimp simp: subset_iff)
apply (rule lem)
prefer 2 apply simp
apply (drule bspec) prefer 2 apply assumption
apply (simp add: image_eqI in_set_butlast_concatI)
apply (rule ballI)
apply (rule lem)
apply auto
done
lemma trace_below:
"bounded d k ==> !i. i < k --> (!n:set(trace d i xs). n < k)"
apply (unfold bounded_def)
apply (induct "xs")
apply simp
apply (simp (no_asm))
apply (blast)
done
lemma regset_below:
"[| bounded d k; i < k; j < k |] ==>
regset d i j k = {xs. deltas d xs i = j}"
apply (rule set_eqI)
apply (simp add: regset_spec)
apply (blast dest: trace_below in_set_butlastD)
done
lemma deltas_below:
"!!i. bounded d k ==> i < k ==> deltas d w i < k"
apply (unfold bounded_def)
apply (induct "w")
apply simp_all
done
lemma regset_DA_equiv:
"[| bounded (next A) k; start A < k; j < k |] ==>
w : regset_of_DA A k = accepts A w"
apply(unfold regset_of_DA_def)
apply (simp cong: conj_cong
add: regset_below deltas_below accepts_def delta_def)
done
end
|
__precompile__(true)
"""
Module `Parallel.jl` -- LazySets algorithms that are parallelized.
"""
module Parallel
using LazySets
using SharedArrays: SharedMatrix, SharedVector, indexpids
using Distributed: remotecall_wait, procs
#=======================================================
Utility functions for distribution of tasks in parallel
=======================================================#
include("distribute.jl")
#==================================================
Approximations using boxes implemented in parallel
==================================================#
include("box_approximations.jl")
end # module
|
module Extra.Buffer
import Data.Buffer
%foreign "node:lambda:(buf)=>buf.toString('base64')"
enc64__prim : Buffer -> PrimIO String
%foreign "node:lambda:(str)=>Buffer.from(str, 'base64')"
dec64__prim : String -> PrimIO Buffer
%foreign "node:lambda:(str)=>Buffer.from(str, 'utf-8')"
fromString__prim : String -> PrimIO Buffer
%foreign "node:lambda:(buf,char)=>buf.indexOf(char)"
indexOf__prim : Buffer -> Char -> PrimIO Int
export
enc64 : HasIO io => Buffer -> io String
enc64 =
primIO . enc64__prim
export
dec64 : HasIO io => String -> io Buffer
dec64 =
primIO . dec64__prim
export
fromString : HasIO io => String -> io Buffer
fromString =
primIO . fromString__prim
export
indexOf : HasIO io => Char -> Buffer -> io (Maybe Int)
indexOf char buf =
do
res <- primIO (indexOf__prim buf char)
if res < 0
then pure $ Nothing
else pure $ Just res
export
readAll : HasIO io => Buffer -> io String
readAll buf =
do
len <- rawSize buf
x <- getString buf 0 len
pure x
export
readLine : HasIO io => Buffer -> io (String, Maybe Buffer)
readLine buf =
do
Just index <- indexOf '\n' buf
| Nothing => do
contents <- readAll buf
pure $ (contents, Nothing)
Just (line, rest) <- splitBuffer buf (index + 1)
| Nothing => pure $ ( "", Just buf ) -- Shrug
contents <- readAll line
pure $ (contents, Just rest)
|
%+========================================================================+
%| |
%| This script uses the GYPSILAB toolbox for Matlab |
%| |
%| COPYRIGHT : Matthieu Aussal (c) 2017-2018. |
%| PROPERTY : Centre de Mathematiques Appliquees, Ecole polytechnique, |
%| route de Saclay, 91128 Palaiseau, France. All rights reserved. |
%| LICENCE : This program is free software, distributed in the hope that|
%| it will be useful, but WITHOUT ANY WARRANTY. Natively, you can use, |
%| redistribute and/or modify it under the terms of the GNU General Public|
%| License, as published by the Free Software Foundation (version 3 or |
%| later, http://www.gnu.org/licenses). For private use, dual licencing |
%| is available, please contact us to activate a "pay for remove" option. |
%| CONTACT : [email protected] |
%| WEBSITE : www.cmap.polytechnique.fr/~aussal/gypsilab |
%| |
%| Please acknowledge the gypsilab toolbox in programs or publications in |
%| which you use it. |
%|________________________________________________________________________|
%| '&` | |
%| # | FILE : nrtRayTheatre.m |
%| # | VERSION : 0.41 |
%| _#_ | AUTHOR(S) : Matthieu Aussal |
%| ( # ) | CREATION : 14.03.2017 |
%| / 0 \ | LAST MODIF : 01.04.2018 |
%| ( === ) | SYNOPSIS : Ray tracing with theatre |
%| `---' | |
%+========================================================================+
% Cleaning
clear all
close all
clc
% Gypsilab path
run('../../addpathGypsilab.m')
% Parameters
Xsrc = [0 8 1.7];
Xmes = [0 -20 8];
Nray = 1e5
rad = 1
% Read mesh
mesh = msh('theatre.mesh');
mesh.col(:) = 100; % Rough concrete (Bobran, 1973)
% Extract toit
ctr = mesh.ctr;
mesh = mesh.sub(ctr(:,3)<14);
% Initialize ray
ray1 = ray(mesh,Xsrc,Nray);
% Graphical sphere
[X,Y,Z] = sphere(50);
X = Xmes(1) + rad*X; Y = Xmes(2) + rad*Y; Z = Xmes(3) + rad*Z;
% Graphical representation
figure
plot(mesh,'w')
hold on
plot(ray1)
surf(X,Y,Z,ones(size(X)))
axis equal
xlabel('X'); ylabel('Y'); zlabel('Z');
view(0,45)
alpha(0.5)
% Maximum distances
r1000 = rad/2 * sqrt(Nray/1000);
r100 = rad/2 * sqrt(Nray/100);
r10 = rad/2 * sqrt(Nray/10);
rMax = rad/2 * sqrt(Nray/2);
% Ray-tracing
tic
ray1 = ray1.tracer(30,rMax);
toc
% plot(ray1)
% Images sources
tic
[img,nrg] = ray1.image(Xmes,rad,rMax);
toc
% Data
r = sqrt(sum(img.^2,2));
sol = mean(nrg,2);
% Impacts
ray2 = ray(mesh,Xmes,img);
ray2 = ray2.tracer;
plot(ray2)
plot(msh(ray2.pos{2},(1:length(ray2))',10*log10(sol)));
axis equal
colorbar
% Energy in dB
figure
plot(r,10*log10(sol),'+b')
hold on
plot([r1000 r1000],[-60,0],'k--')
text(r1000,-55,' n = 1000')
plot([r100 r100],[-60,0],'k--')
text(r100,-57,' n = 100')
plot([r10 r10],[-60,0],'k--')
text(r10,-55,' n = 10')
plot([rMax rMax],[-60,0],'k--')
text(rMax,-55,' n = 1')
xlabel('Distance source mesure')
ylabel('Energie mesuree (dB)')
title('Energie mesuree selon la distance de mesure')
grid on
% Audio file
[audio,fs] = audioread('anechoicVoice.wav');
% Fir from images
T = floor(r/340*fs) + 1;
for i = 1:size(nrg,2)
fir8(:,i) = accumarray(T,nrg(:,i),[max(T) 1]);
end
% Bank filtering
dir8 = ray1.bank(256,fs);
rir = 0;
for i = 1:size(dir8,2)
rir = rir + fftfilt(dir8(:,i),fir8(:,i));
end
% Graphical representation
figure
plot(rir)
% Audio rendering (5 seconds)
out = fftfilt(rir,audio(1:5*fs));
% sound(out,fs)
disp('~~> Michto gypsilab !')
|
## 9-1. 古典エラー
データ蓄積の方法は時間ともに初期化されてしまう揮発性のものと、原則としてほぼ劣化しない不揮発性のものに分類される。ここでは揮発性のメモリの一種であるDRAMのメモリセルを考える。
現代の計算機は0,1のバイナリ情報を、コンデンサに蓄えらえれた電子の量が多いか少ないかというアナログな連続量で表現する。(通信ならある周波数帯や時間区間に含まれる光子の数で表現する。)
ここではエネルギーが蓄えられた状態を1、エネルギーが完全に放出された状態を0とする。
こうしたアナログな量は、外部との相互作用により常に一定値にいることはない。電子は時間とともにトランジスタのリーク電流などによってあるレートで放出される。
従って、1の状態はしばらくたつと0の状態に変化してしまう。この変化は現代のデバイスではおよそ秒未満の無視できないスケールで起きる。
これは「操作の有無に寄らず時間の変化によって一定レートで起きるエラー」である。
こうしたエラーは古典デバイスでは「0,1が判定不能になるより十分前に、一定時間おきに残電子量を読み出し、その数に応じて充電しなおす」ことで訂正されている。
この操作はリフレッシュと呼ばれ、ユーザが意図せずとも定期的に行われる。当然、電源が落ちるとリフレッシュは行われなくなる。このことを指しDRAMを揮発メモリと呼ぶ。
リフレッシュが行われリークによる影響が無視できるとき、次に重要となるエラーの要因は中性子線によるトランジスタの誤動作である。
中性子線は宇宙線の一種であり、金属などを貫通するために防護が困難である。この中性子線がトランジスタを通過するとき、生じた電荷がトランジスタを誤動作させることがある。
従って、中性子線エラーは「何らかの操作がトリガーとなり、単発的に起きるエラー」である。
読み出しタイミングでないときトランジスタが動作しゲートが解放されると、コンデンサの状態はbit lineの状態に合わせて変化し意図しないものになってしまう。
このエラーによってビットが反転される確率は一般のユーザには無視できるほど小さいが、規模が非常に大きな計算では無視できなくなる。
仮に単位ビット当たりに単位時間で中性子線が衝突し誤動作する確率を$p$とすると、$n$ビットのメモリに$t$秒間の間1ビットも変化しない確率は
$q = (1-p)^{nt}$である。$n=10^{12}$で$t=10^{3}$とし、$q=0.99$を実現するためには、$p\sim 10^{-18}$でなければならない。
中性子線エラーのリークとの大きな違いは、リークはすぐさま確認すれば0,1の中間的な状態にあるため復帰が可能なものの、中性子線は生じた後にはもとはどの状態であったか知ることができない点にある。
このため、中性子線エラーが問題となる領域での応用では、誤り訂正機能の付いたECCメモリが利用される。ECCメモリでは後述の誤り訂正を行い、1bitまでのエラーを小さなオーバーヘッドで訂正する。
### 古典エラー訂正: 多数決
最も単純な符号は多数決である。多数決では個々のビットを$d$倍にコピーする。この時、$k$ビットの情報を$n:=dk$ビットで表現することになる。多数決の引き分けを防ぐため、$d$は奇数とする。
現実に存在する$n$ビットのことを物理ビット、実態として表現している$k$ビットのことを論理ビットと呼ぶ。
多数決では以下のように誤りの検知と訂正を行う。個々の論理ビットについて複製した$d$ビットの情報を読み出し、0,1のどちらが多いかを数える。そして、頻度が高かった値がその論理ビットの値であったと判定する。初期の値がどうあれ、符号化された状態は全ての値が同じであるから、$d$ビットの値が一つでも一致していない場合、何らかのエラーが生じていることが確信できる。従って$n$ビットが丸ごと反転しない限り必ず誤りを検知することができる。
誤りを訂正したい場合は半数以上のビットが正しい値を保持していれば正しい結果を得ることができる。それぞれのビットに1より十分小さい確率$p$でエラーが生じるとすると、半数以上のビットがエラーを起こす確率はおよそ$p^{\lfloor d/2 \rfloor+1}$である。
従って、$d$を2増やすごとに、多数決が失敗する確率はオーダーで$p$倍小さくなることがわかる。
最も単純な$k=1$の場合をシミュレートするコードを書くと以下のようになる。
```python
import numpy as np
data = 1
d = 31
p = 0.01
print("original bit: {}".format(data))
state = np.repeat(data, d)
is_flipped = (np.random.rand(d)<p).astype(np.int)
state = (state + is_flipped)%2
if np.sum(state==0) < np.sum(state==1):
majority = 1
else:
majority = 0
print("decoded bit: {}".format(majority))
```
original bit: 1
decoded bit: 1
上記はランダムに成功不成功が変わるが、成功する確率は確率$p$に関する二項分布の累積として知ることができる。
横軸を各ビットのエラー確率、縦軸を復号の成功確率として、様々な奇数の$d$についてプロットすると以下のようになる。
```python
import numpy as np
d = 31
fail_prob_list = []
p_list = np.linspace(0,1,21)
for p in p_list:
fail_prob = []
binomial = [1]
for m in np.arange(2,d+2):
nbin = np.zeros(m)
for i in range(m):
if i!=0:
nbin[i] += binomial[i-1]*p
if i+1<m:
nbin[i] += binomial[i]*(1-p)
binomial = nbin
if m%2==0:
fail = np.sum(binomial[m//2:])
fail_prob.append(fail)
fail_prob_list.append(fail_prob)
fail_prob_list = np.array(fail_prob_list).T
import matplotlib.pyplot as plt
plt.figure(figsize=(12,8))
plt.subplot(1,2,1)
for index,line in enumerate(fail_prob_list[:6]):
plt.plot(p_list, line, label = "n={}".format(2*index+1))
plt.ylim(0,1)
plt.xlim(0,1)
plt.xlabel("Error probability per each bit")
plt.ylabel("Failure probability")
plt.legend()
plt.subplot(1,2,2)
for index,line in enumerate(fail_prob_list.T[:7]):
if index==0:
continue
distance_list = np.arange((d+1)//2)*2+1
plt.plot(distance_list,line, label = "p={:.3}".format(p_list[index]))
plt.ylim(1e-5,0.5)
plt.yscale("log")
plt.xlabel("distance")
plt.ylabel("Failure probability")
plt.legend()
plt.show()
```
左のグラフから$p$がある一定値(今回は0.5)以下であれば、$d$を大きくすればするほど性能が良くなることがわかる。
一方、$p$がある値以上の場合、$d$を増やすとよくなるどころかむしろ性能が悪化してしまう。
このことから、多数決で誤り訂正を行うには、少なくとも各デバイスがある誤り率以下であることが必要条件となることがわかる。
このふるまいは量子符号を含むスケールする符号にたびたび見られる性質であり、このしきいとなるエラー確率のことをエラーしきい値(error threshold)と呼ぶ。一般の古典誤り訂正はエラーしきい値よりはるかに小さい値で行われるが、量子誤り訂正では現状のエラーがこのしきい値付近であるため、たびたび言及される。
右のグラフは$p$をしきい値以下の一定値に固定し、$d$を大きくしたときにどの程度復号の失敗確率が減少するかを指数プロットしたものである。$p$がしきい値より十分小さい場合、$d$を大きくすることで概ね指数的に復号の失敗確率が減少していくことがわかる。
### 線形符号
上記の多数決の枠組みは線形符号という符号の一種である。下記では線形符号の枠組みで多数決を解説する。
ある$k$ビットの情報$v$を$n=dk$ビットの情報$v'$に冗長化する操作は、$k \times n$の行列$G$を以下のように構成し、$v' = vG$という計算を行うと言い換えることができる。
```python
import numpy as np
k = 4
m = 3
n = k*m
v = np.random.randint(2,size=k)
print("original vector: v\n{}".format(v))
G = np.zeros((k,n),dtype=np.int)
for y in range(k):
G[y,y*m:(y+1)*m]=1
print("generator matrix: G\n{}".format(G))
vd = (v@G)%2
print("encoded vector: v' = vG\n{}".format(vd))
```
original vector: v
[0 1 0 1]
generator matrix: G
[[1 1 1 0 0 0 0 0 0 0 0 0]
[0 0 0 1 1 1 0 0 0 0 0 0]
[0 0 0 0 0 0 1 1 1 0 0 0]
[0 0 0 0 0 0 0 0 0 1 1 1]]
encoded vector: v' = vG
[0 0 0 1 1 1 0 0 0 1 1 1]
この行列$G$は生成行列という。
生成される$2^n$パターンの$n$ビット列のうち、$vG$の形で作られる高々$2^k$個の$n$ビット列を符号語と呼ぶ。符号語の集合を$W$としたとき、$w \neq w'$となる二つの符号語でハミング距離が短いもののハミング距離のことを符号の距離(distance)と呼ぶ。今の多数決の構成では、符号の距離は個々の論理ビットを複製する数$d$である。距離$d$以上の数のビットが一斉に反転してしまうとある符号語から別の符号語に変化してしまうため、現在の符号が正しく生成されたのか、他の符号にエラーが載ったものなのか区別がつかなくなる。このことから、エラーが生じるビット数が距離$d$未満であることがエラーが検知できる条件であることが分かる。
次に、mod 2のもとで$GH_c = 0$となり、かつ各行ベクトルが独立になるような$n \times (n-k)$行列$H_c$を考える。今回の場合、3ビットごとに二つの隣接したパリティを見る以下のような$H_c$が条件を満たす。
```python
Hc = np.zeros((n,n-k),dtype=np.int)
for x in range(n-k):
Hc[x//2*m+x%2:x//2*m+x%2+2,x]=1
print("check matrix: H\n{}".format(Hc))
print("G Hc = \n{}".format( (G@Hc)%2))
```
check matrix: H
[[1 0 0 0 0 0 0 0]
[1 1 0 0 0 0 0 0]
[0 1 0 0 0 0 0 0]
[0 0 1 0 0 0 0 0]
[0 0 1 1 0 0 0 0]
[0 0 0 1 0 0 0 0]
[0 0 0 0 1 0 0 0]
[0 0 0 0 1 1 0 0]
[0 0 0 0 0 1 0 0]
[0 0 0 0 0 0 1 0]
[0 0 0 0 0 0 1 1]
[0 0 0 0 0 0 0 1]]
G Hc =
[[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]]
$H_c$の列ベクトルは独立であるため、$2^n$パターンの$n$ビット列$w$のうち、$w H_c = 0$を満たすパターンは$2^n / 2^{n-k} = 2^k$個である。また、符号語の集合$W$に属する符号語$w$は、$w H_c = v G H_c = 0$である。したがって、符号語の集合$W$とは、$w H_c = 0$を満たすビット列の集合と言い換えることもできる。同時に$n$ビット列$w$が符号語ではない$(w \neq W)$ことは、$w H_c \neq 0$であることに等しい。この符号語に属している($w \in W$)ときかつその時に限り$0$になるベクトル$s = w H_c$のことを$w$のシンドロームと呼ぶ。
まとめると、符号語の集合$W$は二つの行列$G,H_c$のいずれでも特徴づけることができ、
\begin{align}
W &= \left\{w \in \{0,1\}^n \mathrel{}\middle|\mathrel{} \exists v \in \{0,1\}^k , w = vG \right\} \\
W &= \left\{w \in \{0,1\}^n \mathrel{}\middle|\mathrel{} w H_c = 0 \right\}
\end{align}
である。
符号化した後にエラー$e$が生じた場合、エラーが起きた後の符号の状態は$v'+e$となった状態である。
この時、$v'+e$のシンドローム値$s = (v'+e)H_c$がすべて0であるかどうかを調べることで、エラーの検出を行える。
シンドローム値が一つでも0でない場合、何らかのエラーが生じている。シンドローム値がすべて0の場合、エラーは生じていないか、検知不可能な$d$ビット以上のエラーが生じていることがわかる。
```python
p = 0.05
print("encoded vector: v'\n{}".format(vd))
e = np.random.choice([0,1],size=len(vd),p = [1-p,p])
print("error vector: e\n{}".format(e))
vde = (vd+e)%2
print("encoded vector with noise: v'+e\n{}".format(vde))
s = (vde@Hc)%2
print("syndrome values: s = (v'+e)Hc\n{}".format(s))
```
encoded vector: v'
[0 0 0 1 1 1 0 0 0 1 1 1]
error vector: e
[0 0 0 0 0 0 0 0 0 0 0 0]
encoded vector with noise: v'+e
[0 0 0 1 1 1 0 0 0 1 1 1]
syndrome values: s = (v'+e)Hc
[0 0 0 0 0 0 0 0]
$GH_c=0$という性質から、$s =(v'+e)H_c = vGH_c + eH_c = eH_c$となる。つまり、シンドローム値は初期状態のベクトル$v$と独立であることが分かる。
$n$ビットの多数決は$v'+e$を左から$m$個ずつ見て多数決を行えばよい。
```python
p = 0.1
print("encoded vector: v'\n{}".format(vd))
e = np.random.choice([0,1],size=len(vd),p = [1-p,p])
print("error vector: e\n{}".format(e))
vde = (vd+e)%2
print("encoded vector with noise: v'+e\n{}".format(vde))
s = (vde@Hc)%2
print("syndrome values: s = (v'+e)Hc\n{}".format(s))
def decode(vde,k,m):
for x in range(k):
subset = vde[x*m:(x+1)*m]
val = np.argmax(np.bincount(subset))
vde[x*m:(x+1)*m] = val
return vde
vde_recovery = decode(vde,k,m)
print("recovered vector: \n{}".format(vde_recovery))
```
encoded vector: v'
[0 0 0 1 1 1 0 0 0 1 1 1]
error vector: e
[0 0 0 0 0 0 0 0 0 0 0 1]
encoded vector with noise: v'+e
[0 0 0 1 1 1 0 0 0 1 1 0]
syndrome values: s = (v'+e)Hc
[0 0 0 0 0 0 0 1]
recovered vector:
[0 0 0 1 1 1 0 0 0 1 1 1]
上記の復号はエラーを大きくしていくと、$m$の半数以上が間違えて訂正に失敗することがあることが分かる。
$e H_c=0$となる$0$でないベクトル$e$が生じた場合、そのようなエラーは訂正することができない。すなわち、符号の距離$d$は検査行列$H_c$にに対して
$$
d := \min w(e) \, \text{s.t.} \, H_e e = 0
$$
という値だと考えることもできる。
### 水平垂直パリティ検査符号
現実の誤り訂正では多数決の手法はあまり性能が良くないためそれほど使われない。ここでは現実の誤り訂正でよく使われるパリティ検査符号の一例として、水平垂直パリティ検査符号の枠組みを学ぶ。
パリティとは、与えられた複数のビットの和を2で割った余り、すなわち1の数の偶奇を意味する。(1,1,1)のパリティは1、(0,1,1)のパリティは0である。
パリティ検査符号は、元の情報のデータについてのいくつかのパリティを保持することで誤りの検知や訂正を可能にする。
元の情報やパリティにエラーが生じた場合、パリティの値と元の情報に整合性が保たれなくなるためエラーを検出することができる。
最もシンプルなパリティ検査符号はチェックサムである。チェックサムは小さなブロック$(x_1,\ldots, x_b)$ごとに、ブロックに含まれるビット列のパリティ$p= \sum_i x_i \bmod 2$をチェックサムとして記入しておく。
もし、伝送の途中でブロック中のビットやチェックサムのビットの記入を高々1bit誤った場合、ブロックに含まれるビット列のパリティを再計算すると保持するパリティ$p$と整合性が取れなくなる。
従って、ブロックかパリティのどこかにビットエラーが生じたことがわかる。ただし、この方法はどこでエラーが生じたかを知ることはできないし、2ビットエラーが生じた場合はエラーを検知することもできない。
```python
import numpy as np
length = 16
p = 0.05
# set random bitarray
bitstring = np.random.randint(2,size = length)
checksum = np.sum(bitstring)%2
print("original bitarray: {}". format(bitstring))
print("checksum: {}".format(checksum))
# error occurs
error = np.random.choice([0,1], size = length, p = [1-p, p])
print("error: {}". format(error))
bitstring = (bitstring + error)%2
print("noisy bitarray: {}". format(bitstring))
new_checksum = np.sum(bitstring)%2
print("checksum: {}".format(new_checksum))
# verify checksum
if checksum == new_checksum:
print("No error detected")
else:
print("Error detected!")
```
original bitarray: [0 1 0 1 1 1 1 1 0 1 1 1 0 0 0 0]
checksum: 1
error: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1]
noisy bitarray: [0 1 0 1 1 1 1 1 0 1 1 1 0 0 0 1]
checksum: 0
Error detected!
1ビットのビットエラーの検知だけでなく訂正を行うには、どこでエラーが生じたかを分かるようにしなければいけない。
これを実現するナイーブな手法は、水平垂直パリティ検査という手法である。
保護する対象を$k=16$ビットをベクトルとし、これを$4*4$の行列に配置する。
ここで、各行のベクトルのパリティと各列のベクトルのパリティを$8$ビット保存しておく。
この場合、もし$k$ビットの中でエラーが生じると、一つの列と行のパリティと整合が取れなくなる。この場合、整合が取れない列と行に一致するデータビットが反転したと判定する。
もし、行のパリティビットにエラーが生じた場合、列のパリティは全て整合が取れているはずである。このように一方のパリティだけにエラーがある場合、パリティが反転したと結論付ける。列のエラーも同様である。
こうすることで、どの場所でビットエラーが生じてもそれが1ビットであれば原因を特定できる。このコードの距離は3ビットであり$[24,16,3]$である。一般には$[w^2+2w,w^2,3]$である。
```python
import numpy as np
width = 4
height = 4
size = width*height
p = 0.03
def show(bitmatrix, vertical_parity, horizontal_parity):
for y in range(height):
print("{} | {}".format(bitmatrix[y,:], horizontal_parity[y] ))
print("-"*width*2)
print("{}".format(vertical_parity ))
print()
# set random bitarray
bitstring = np.random.randint(2,size=size)
print("original bitarray: {}". format(bitstring))
# check horizontal and vertical parity
bitmatrix = bitstring.reshape( (height,width) )
vertical_parity = np.sum(bitmatrix, axis = 0)%2
horizontal_parity = np.sum(bitmatrix, axis = 1)%2
print("stored as : ")
show(bitmatrix,vertical_parity, horizontal_parity)
# error occurs
encoded_size = size + width + height
error = np.random.choice([0,1], size = encoded_size, p = [1-p, p])
bitmatrix = (bitmatrix + error[:size].reshape((height,width)))%2
vertical_parity = (vertical_parity + error[size:size+width])%2
horziontal_parity = (vertical_parity + error[size+width:])%2
# result
print("result is : ")
show(bitmatrix,vertical_parity, horizontal_parity)
# verify checksum
result_vertical_parity = np.sum(bitmatrix, axis = 0)%2
result_horizontal_parity = np.sum(bitmatrix, axis = 1)%2
vertical_flip_count = np.sum((result_vertical_parity + vertical_parity)%2)
horizontal_flip_count = np.sum((result_horizontal_parity + horizontal_parity)%2)
if vertical_flip_count == 0 and horizontal_flip_count == 0:
print("No error detected")
print("decoded bitarray: ")
show(bitmatrix, result_vertical_parity, result_horizontal_parity)
elif vertical_flip_count == 1 and horizontal_flip_count == 0:
print("Error occurs on vertical parity")
print("decoded bitarray: ")
show(bitmatrix, result_vertical_parity, result_horizontal_parity)
elif vertical_flip_count == 0 and horizontal_flip_count == 1:
print("Error occurs on horizontal parity")
print("decoded bitarray: ")
show(bitmatrix, result_vertical_parity, result_horizontal_parity)
elif vertical_flip_count == 1 and horizontal_flip_count == 1:
print("Error occurs on data bit")
print("decoded bitarray: ")
x = np.argmax((result_vertical_parity + vertical_parity)%2)
y = np.argmax((result_horizontal_parity + horizontal_parity)%2)
bitmatrix[y,x] = (bitmatrix[y,x]+1)%2
show(bitmatrix, vertical_parity, horizontal_parity)
else:
print("Too many error occurs")
```
original bitarray: [1 0 0 1 0 0 0 1 0 0 1 1 1 0 0 0]
stored as :
[1 0 0 1] | 0
[0 0 0 1] | 1
[0 0 1 1] | 0
[1 0 0 0] | 1
--------
[0 0 1 1]
result is :
[1 1 0 1] | 0
[0 0 0 1] | 1
[0 1 1 1] | 0
[1 0 0 0] | 1
--------
[0 0 1 1]
Too many error occurs
水平垂直パリティ検査符号も多数決と同様に生成行列と検査行列を考えることができる。
簡単のために、$2 \times 3$の6ビットに対する水平垂直パリティ検査の場合を例に考える。
水平垂直パリティ検査で符号化するビットの横ベクトルを$v$とする。この時、$(1,2,3)$番目のパリティを観測する計算は、$1,2,3$番目のみが1で他が0となっているベクトル$w = (1,1,1,0,0,0)$を用意し、ベクトル間の内積$v w^{\rm T} \bmod 2$を計算することに等しい。従って、元のデータに追加されるパリティビットは以下のような行列$A$をmod 2のもとで作用することで生成できる。なお、以降のバイナリビット間の演算では特に断りが無い限りはmod 2を省略する。
```python
A = np.array([
[1 , 0 , 1 , 0 , 0],
[1 , 0 , 0 , 1 , 0],
[1 , 0 , 0 , 0 , 1],
[0 , 1 , 1 , 0 , 0],
[0 , 1 , 0 , 1 , 0],
[0 , 1 , 0 , 0 , 1]
])
print(A)
```
[[1 0 1 0 0]
[1 0 0 1 0]
[1 0 0 0 1]
[0 1 1 0 0]
[0 1 0 1 0]
[0 1 0 0 1]]
この時、パリティの値を並べたベクトル$p$は$p = vA$であり、符号化後のバイナリベクトルは$v' = (v,p)$である。従って生成行列として$k \times n$行列$G$を$G = (I, A)$と置けば、$v' = v G$という形にできる。
符号化したバイナリベクトルにはエラー$e$が生じる。この時、$e$のうちデータ部に生じたエラーを$e_v$、パリティ部に生じたエラーを$e_p$とする。エラーが生じた後のバイナリベクトルは$v'+e = (v+e_v, p+e_p)$となる。水平垂直パリティ検査では、エラーが生じた後にパリティ値が一致しているかどうかをもとにエラーが生じたかを判断する。このことを式で書くと、
$$
(v + e_v)A = p + e_p
$$
が成り立つか否かが、エラーを検知するかどうかの判定に等しい。$p=vA$を用いて上記の等式を整理すると、エラーが検知されない条件は
$$
e_v A + e_p = (e_v, e_p) \left(\begin{matrix} A \\ I \end{matrix}\right) = 0
$$
である。行列$H_c$を$H_c = \left( \begin{matrix} A \\ I \end{matrix} \right)$と置くと、
$$
G H_c = (I, A) \left(\begin{matrix} A \\ I \end{matrix}\right) = A + A = 0
$$
である。
```python
G = np.hstack( (np.eye(A.shape[0]), A) )
Hc = np.vstack( (A, np.eye(A.shape[1])) )
print("generator matrix: G\n{}\n".format(G))
print("check matrix: Hc \n{}\n".format(Hc))
print("GHc = \n{}\n".format( (G@Hc)%2 ))
```
generator matrix: G
[[1. 0. 0. 0. 0. 0. 1. 0. 1. 0. 0.]
[0. 1. 0. 0. 0. 0. 1. 0. 0. 1. 0.]
[0. 0. 1. 0. 0. 0. 1. 0. 0. 0. 1.]
[0. 0. 0. 1. 0. 0. 0. 1. 1. 0. 0.]
[0. 0. 0. 0. 1. 0. 0. 1. 0. 1. 0.]
[0. 0. 0. 0. 0. 1. 0. 1. 0. 0. 1.]]
check matrix: Hc
[[1. 0. 1. 0. 0.]
[1. 0. 0. 1. 0.]
[1. 0. 0. 0. 1.]
[0. 1. 1. 0. 0.]
[0. 1. 0. 1. 0.]
[0. 1. 0. 0. 1.]
[1. 0. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 0. 1.]]
GHc =
[[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.]]
数値的にも確かに$GH_c = 0$となることが分かる。$H_c$は$n \times (n-k)$行列で、かつ列ベクトルは単位行列の部分行列を持つことから明らかに列ごとに独立であり、確かに検査行列の性質を満たしている。
このとき、シンドローム値$s$は$s = e H_c$となる。シンドローム値が全て0の時、符号はエラーが生じていないと判定する。もちろん、大きなエラーが生じている場合、エラーが生じているにもかかわらず$s=0$となりエラーが無いと判定されることもある。
$s \neq 0$である場合、何らかのエラーが起きていることはわかる。この状態でエラーを訂正するには、$(v'+e)$の値から符号化前の$v$を推測しなければならない。今回の場合、冒頭のコードで示したような方法でエラーが一つまでならデータビットとパリティビットのどこにエラーがあるのかを$O(1)$で特定することができる。
パリティ検査符号の枠組みをまとめると以下のようになる。
- 符号:生成行列$G$と検査行列$H_c$で特徴づけられる。これらは$GH_c = 0$を満たす。
- 符号化前:$k$-bitの横ベクトルデータ $v$ がある。
- 符号化: $k \times n$の生成行列$G$を用いて、符号化した状態$v'$は$v'=vG$となる。
- エラー: 符号化後の$v'$にランダムに$n$-bit列 $e$ が足される。
- エラー検査: $n \times (n-k)$の検査行列$H_c$を用いてシンドローム$s = e H_c$が得られる。$s \neq 0$ならばエラーがあると検知できる。$s=0$ならば、エラーが生じていないか、検査できる限界以上のエラーが生じている。
- エラー訂正: $(v'+e)$の値に従って、$k$-bitの横ベクトルデータ $v$ を推測する。$v'+e$から$v$を求めるアルゴリズムを復号アルゴリズムと呼ぶ。
- 距離: $e H_c = 0$となる$e$の最小weightが符号の距離$d$である。
パリティ検査符号は非常に広い枠組みであり、例えばECCメモリではハミング符号と呼ばれるパリティ検査行列の一種が用いられている。
### 一般の線形符号のケース
上記では多数決、チェックサム、水平垂直検査という特定の例を挙げたが、実際に使用する際には目的に対し最も性能の良い符号がほしい。しかし、一般に与えられた$(n,k,d)$に対して最適な線形符号$G,H_c$を求めることは組み合わせ論の問題となり、一般に困難である。
また、仮に最適な$(G,H_c)$という符号を与えられても復号に関して問題がある。ナイーブな復号アルゴリズムの例は、シンドローム$s$を観測した時、$s = e'H_c$を満たすような$e'$のうち、最も少ないビットにエラーを起こすものを起きたエラーとみなし、$(v' + e + e')$が正しい符号語になると期待して復元を試みる最小距離複合である。上記の最適化は
$$
\min_{e \in \{0,1\}^n} w(e') \, \text{s.t.} \, s = e' H_c
$$
という$n$-bitの0,1計画問題となるため、最小距離複合は一般には符号のサイズに対してNP困難である。しかも、この復号は実際には最適な復号とと一致するとは限らない。一方、符号や起きるエラーの種類を限定すると効率的に最小距離複合が実施でき、かつ多くの場合この復号方法は最適に近い複合である。例えば多数決は常に最小距離複合が可能であり、水平垂直パリティ検査符号では生じるエラーを $w(e)=1$ に限定すれば$O(1)$で最小距離複合が可能である。
### 線形符号上での演算
ノイジーな通信路に情報を通す場合はパリティ検査符号で符号化された情報を転送するだけである場合でよい。しかし、計算機自体がノイジーな場合、パリティ検査符号で符号化した状態で計算を行わなければならない。例えば、CPU自体がノイジーであり、符号化した状態のままで計算を行いたい場合は、計算のたびに復号してしまっては符号化の意味がない。
上記の水平垂直パリティ検査を用いる場合、行列の$(i,j)$要素に対するビット反転操作を行う場合、この操作がエラーとして検知されないようにするには関連するパリティの値も更新しなくてはいけない。つまり、$1$ビットを更新する目には、符号化されたビット列に対して$3$ビットの操作が必要となる。
より一般的には、$v$に対するビット反転操作$o$を考えると、$v \rightarrow v+o$とするには、符号化された空間で$oB$のビット反転が必要になる。操作のコストを考えると、ある論理ビットを操作するときに実際に操作せねばならないビットの数は少なければ少ないほど良い。
この時、論理ビットの反転のために実際に反転しなければいけないビットの数は高々$\max_i w(G_i)$である。ただし、$G_i$は$G$の$i$行ベクトルである。水平垂直パリティ検査では$G$の行のweightはすべて3である。
### 低密度パリティ検査符号
宇宙との通信など通信できる時間が限られていたり通信路が劣悪にならざるを得ない場合、できるだけ限界に近いレートで大量のデータを送りたい。このことが、符号化や復号にかかる計算コストは大きくとも良いので、符号化するビット数あたりの論理誤り率が最も小さくなる符号を作るモチベーションとなる。
通信路のノイズが既知である場合、ノイズのある通信路で送信可能な情報量のレートの限界はシャノン限界として計算できる。このレートはこれは構成することができる符号の性能の限界を意味する。低密度パリティ検査符号はこのシャノン限界に近い性能を実現する符号である。
低密度パリティ検査符号では、検査行列$H_c$が疎行列となるパリティ検査符号の総称である。ここでいう疎行列とは、各列に含まれる$1$の数が高々$O(k)$程度であることを意味する。すなわち、個々のシンドローム値は$O(k)$個のビットのエラーのパリティで表現できるということである。
低密度パリティ検査符号の利点はその性能がシャノン限界に近い点である。一方、低密度パリティ検査符号の欠点は、復号の計算量的な困難さである。この困難を回避するため、信頼伝播法といった近似アルゴリズムが復号のためにしばしば用いられる。
信頼伝播法では、次のようなグラフを考える。符号化後のビットをノードとみなす。あるパリティ値があるデータビットのエラーをパリティの一部に含むとき、対応するパリティビットのノードからデータビットのノードへ無向エッジを張る。こうして、$n$頂点が$nO(k)$個の辺で繋がれたの無向グラフ$G(V,E)$が完成する。信頼伝播法はこのグラフ上での逐次的な最適化を状態が符号後となるまで繰り返す。
信頼伝播法の性能はグラフ$G$における最小のループが大きければ大きいほど良いことが知られている。したがって、そのようなグラフを構築するべく、様々な低密度パリティ検査符号の構築方法が提案されている。
|
(* Property from Case-Analysis for Rippling and Inductive Proof,
Moa Johansson, Lucas Dixon and Alan Bundy, ITP 2010.
This Isabelle theory is produced using the TIP tool offered at the following website:
https://github.com/tip-org/tools
This file was originally provided as part of TIP benchmark at the following website:
https://github.com/tip-org/benchmarks
Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly
to make it compatible with Isabelle2017.
Some proofs were added by Yutaka Nagashima.*)
theory TIP_prop_79
imports "../../Test_Base"
begin
datatype Nat = Z | S "Nat"
fun t2 :: "Nat => Nat => Nat" where
"t2 (Z) y = Z"
| "t2 (S z) (Z) = S z"
| "t2 (S z) (S x2) = t2 z x2"
theorem property0 :
"((t2 (t2 (S m) n) (S k)) = (t2 (t2 m n) k))"
oops
end
|
Formal statement is: lemma pderiv_smult: "pderiv (smult a p) = smult a (pderiv p)" Informal statement is: The derivative of a polynomial multiplied by a constant is the derivative of the polynomial multiplied by the same constant. |
State Before: α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
⊢ (∫⁻ (a : α), f a + g a ∂μ) = ∫⁻ (a : α), (⨆ (n : ℕ), ↑(eapprox f n) a) + ⨆ (n : ℕ), ↑(eapprox g n) a ∂μ State After: no goals Tactic: simp only [iSup_eapprox_apply, hf, hg] State Before: α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
⊢ (∫⁻ (a : α), (⨆ (n : ℕ), ↑(eapprox f n) a) + ⨆ (n : ℕ), ↑(eapprox g n) a ∂μ) =
∫⁻ (a : α), ⨆ (n : ℕ), (↑(eapprox f n) + ↑(eapprox g n)) a ∂μ State After: case e_f
α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
⊢ (fun a => (⨆ (n : ℕ), ↑(eapprox f n) a) + ⨆ (n : ℕ), ↑(eapprox g n) a) = fun a =>
⨆ (n : ℕ), (↑(eapprox f n) + ↑(eapprox g n)) a Tactic: congr State Before: case e_f
α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
⊢ (fun a => (⨆ (n : ℕ), ↑(eapprox f n) a) + ⨆ (n : ℕ), ↑(eapprox g n) a) = fun a =>
⨆ (n : ℕ), (↑(eapprox f n) + ↑(eapprox g n)) a State After: case e_f.h
α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
a : α
⊢ ((⨆ (n : ℕ), ↑(eapprox f n) a) + ⨆ (n : ℕ), ↑(eapprox g n) a) = ⨆ (n : ℕ), (↑(eapprox f n) + ↑(eapprox g n)) a Tactic: funext a State Before: case e_f.h
α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
a : α
⊢ ((⨆ (n : ℕ), ↑(eapprox f n) a) + ⨆ (n : ℕ), ↑(eapprox g n) a) = ⨆ (n : ℕ), (↑(eapprox f n) + ↑(eapprox g n)) a State After: case e_f.h
α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
a : α
⊢ (⨆ (a_1 : ℕ), ↑(eapprox f a_1) a + ↑(eapprox g a_1) a) = ⨆ (n : ℕ), (↑(eapprox f n) + ↑(eapprox g n)) a
case e_f.h.hf
α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
a : α
⊢ Monotone fun n => ↑(eapprox f n) a
case e_f.h.hg
α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
a : α
⊢ Monotone fun n => ↑(eapprox g n) a Tactic: rw [ENNReal.iSup_add_iSup_of_monotone] State Before: case e_f.h
α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
a : α
⊢ (⨆ (a_1 : ℕ), ↑(eapprox f a_1) a + ↑(eapprox g a_1) a) = ⨆ (n : ℕ), (↑(eapprox f n) + ↑(eapprox g n)) a State After: no goals Tactic: rfl State Before: case e_f.h.hf
α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
a : α
⊢ Monotone fun n => ↑(eapprox f n) a State After: case e_f.h.hf
α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
a : α
i j : ℕ
h : i ≤ j
⊢ (fun n => ↑(eapprox f n) a) i ≤ (fun n => ↑(eapprox f n) a) j Tactic: intro i j h State Before: case e_f.h.hf
α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
a : α
i j : ℕ
h : i ≤ j
⊢ (fun n => ↑(eapprox f n) a) i ≤ (fun n => ↑(eapprox f n) a) j State After: no goals Tactic: exact monotone_eapprox _ h a State Before: case e_f.h.hg
α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
a : α
⊢ Monotone fun n => ↑(eapprox g n) a State After: case e_f.h.hg
α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
a : α
i j : ℕ
h : i ≤ j
⊢ (fun n => ↑(eapprox g n) a) i ≤ (fun n => ↑(eapprox g n) a) j Tactic: intro i j h State Before: case e_f.h.hg
α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
a : α
i j : ℕ
h : i ≤ j
⊢ (fun n => ↑(eapprox g n) a) i ≤ (fun n => ↑(eapprox g n) a) j State After: no goals Tactic: exact monotone_eapprox _ h a State Before: α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
⊢ (∫⁻ (a : α), ⨆ (n : ℕ), (↑(eapprox f n) + ↑(eapprox g n)) a ∂μ) =
⨆ (n : ℕ), SimpleFunc.lintegral (eapprox f n) μ + SimpleFunc.lintegral (eapprox g n) μ State After: α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
⊢ (⨆ (n : ℕ), ∫⁻ (a : α), (↑(eapprox f n) + ↑(eapprox g n)) a ∂μ) =
⨆ (n : ℕ), SimpleFunc.lintegral (eapprox f n) μ + SimpleFunc.lintegral (eapprox g n) μ
case hf
α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
⊢ ∀ (n : ℕ), Measurable fun a => (↑(eapprox f n) + ↑(eapprox g n)) a
case h_mono
α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
⊢ Monotone fun n a => (↑(eapprox f n) + ↑(eapprox g n)) a Tactic: rw [lintegral_iSup] State Before: α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
⊢ (⨆ (n : ℕ), ∫⁻ (a : α), (↑(eapprox f n) + ↑(eapprox g n)) a ∂μ) =
⨆ (n : ℕ), SimpleFunc.lintegral (eapprox f n) μ + SimpleFunc.lintegral (eapprox g n) μ State After: case e_s
α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
⊢ (fun n => ∫⁻ (a : α), (↑(eapprox f n) + ↑(eapprox g n)) a ∂μ) = fun n =>
SimpleFunc.lintegral (eapprox f n) μ + SimpleFunc.lintegral (eapprox g n) μ Tactic: congr State Before: case e_s
α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
⊢ (fun n => ∫⁻ (a : α), (↑(eapprox f n) + ↑(eapprox g n)) a ∂μ) = fun n =>
SimpleFunc.lintegral (eapprox f n) μ + SimpleFunc.lintegral (eapprox g n) μ State After: case e_s.h
α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
n : ℕ
⊢ (∫⁻ (a : α), (↑(eapprox f n) + ↑(eapprox g n)) a ∂μ) =
SimpleFunc.lintegral (eapprox f n) μ + SimpleFunc.lintegral (eapprox g n) μ Tactic: funext n State Before: case e_s.h
α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
n : ℕ
⊢ (∫⁻ (a : α), (↑(eapprox f n) + ↑(eapprox g n)) a ∂μ) =
SimpleFunc.lintegral (eapprox f n) μ + SimpleFunc.lintegral (eapprox g n) μ State After: case e_s.h
α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
n : ℕ
⊢ (∫⁻ (a : α), (↑(eapprox f n) + ↑(eapprox g n)) a ∂μ) = ∫⁻ (a : α), ↑(eapprox f n + eapprox g n) a ∂μ Tactic: rw [← SimpleFunc.add_lintegral, ← SimpleFunc.lintegral_eq_lintegral] State Before: case e_s.h
α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
n : ℕ
⊢ (∫⁻ (a : α), (↑(eapprox f n) + ↑(eapprox g n)) a ∂μ) = ∫⁻ (a : α), ↑(eapprox f n + eapprox g n) a ∂μ State After: no goals Tactic: rfl State Before: case hf
α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
⊢ ∀ (n : ℕ), Measurable fun a => (↑(eapprox f n) + ↑(eapprox g n)) a State After: no goals Tactic: measurability State Before: case h_mono
α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
⊢ Monotone fun n a => (↑(eapprox f n) + ↑(eapprox g n)) a State After: case h_mono
α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
i j : ℕ
h : i ≤ j
a : α
⊢ (fun n a => (↑(eapprox f n) + ↑(eapprox g n)) a) i a ≤ (fun n a => (↑(eapprox f n) + ↑(eapprox g n)) a) j a Tactic: intro i j h a State Before: case h_mono
α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
i j : ℕ
h : i ≤ j
a : α
⊢ (fun n a => (↑(eapprox f n) + ↑(eapprox g n)) a) i a ≤ (fun n a => (↑(eapprox f n) + ↑(eapprox g n)) a) j a State After: no goals Tactic: exact add_le_add (monotone_eapprox _ h _) (monotone_eapprox _ h _) State Before: case refine'_2
α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
⊢ Monotone fun n => SimpleFunc.lintegral (eapprox g n) μ State After: case refine'_2
α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
i j : ℕ
h : i ≤ j
⊢ (fun n => SimpleFunc.lintegral (eapprox g n) μ) i ≤ (fun n => SimpleFunc.lintegral (eapprox g n) μ) j Tactic: intro i j h State Before: case refine'_2
α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
i j : ℕ
h : i ≤ j
⊢ (fun n => SimpleFunc.lintegral (eapprox g n) μ) i ≤ (fun n => SimpleFunc.lintegral (eapprox g n) μ) j State After: no goals Tactic: exact SimpleFunc.lintegral_mono (monotone_eapprox _ h) (le_refl μ) State Before: α : Type u_1
β : Type ?u.853934
γ : Type ?u.853937
δ : Type ?u.853940
m : MeasurableSpace α
μ ν : Measure α
f g : α → ℝ≥0∞
hf : Measurable f
hg : Measurable g
⊢ ((⨆ (n : ℕ), SimpleFunc.lintegral (eapprox f n) μ) + ⨆ (n : ℕ), SimpleFunc.lintegral (eapprox g n) μ) =
(∫⁻ (a : α), f a ∂μ) + ∫⁻ (a : α), g a ∂μ State After: no goals Tactic: rw [lintegral_eq_iSup_eapprox_lintegral hf, lintegral_eq_iSup_eapprox_lintegral hg] |
module LibCImPlot
using CImPlot_jll
#export CImPlot_jll
using CEnum
import CImGui: ImVec2, ImVec4, ImGuiMouseButton, ImGuiKeyModFlags
import CImGui.LibCImGui: ImGuiContext
include("libcimplot_common.jl")
include("libcimplot_api.jl")
for i in [ImPlotFlags, ImPlotAxisFlags]
for j in instances(i)
@eval export $(Symbol(j))
end
end
export CreateContext, DestroyContext, SetImGuiContext
end # module
|
The components of a topological space are nonempty. |
!========================================================================
!
! S P E C F E M 2 D Version 7 . 0
! --------------------------------
!
! Main historical authors: Dimitri Komatitsch and Jeroen Tromp
! CNRS, France
! and Princeton University, USA
! (there are currently many more authors!)
! (c) October 2017
!
! This software is a computer program whose purpose is to solve
! the two-dimensional viscoelastic anisotropic or poroelastic wave equation
! using a spectral-element method (SEM).
!
! This program is free software; you can redistribute it and/or modify
! it under the terms of the GNU General Public License as published by
! the Free Software Foundation; either version 3 of the License, or
! (at your option) any later version.
!
! This program is distributed in the hope that it will be useful,
! but WITHOUT ANY WARRANTY; without even the implied warranty of
! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
! GNU General Public License for more details.
!
! You should have received a copy of the GNU General Public License along
! with this program; if not, write to the Free Software Foundation, Inc.,
! 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
!
! The full text of the license is available in file "LICENSE".
!
!========================================================================
subroutine compute_arrays_source(ispec_selected_source,xi_source,gamma_source,sourcearray, &
Mxx,Mzz,Mxz,xix,xiz,gammax,gammaz,xigll,zigll,nspec)
use constants, only: CUSTOM_REAL,NGLLX,NGLLZ,NGLJ,NDIM,ZERO
use specfem_par, only: AXISYM,is_on_the_axis,xiglj
implicit none
integer,intent(in) :: ispec_selected_source
integer,intent(in) :: nspec
double precision,intent(in) :: xi_source,gamma_source
double precision,intent(in) :: Mxx,Mzz,Mxz
real(kind=CUSTOM_REAL), dimension(NGLLX,NGLLZ,nspec) :: xix,xiz,gammax,gammaz
real(kind=CUSTOM_REAL), dimension(NDIM,NGLLX,NGLLZ) :: sourcearray
double precision :: xixd,xizd,gammaxd,gammazd
! Gauss-Lobatto-Legendre points of integration and weights
double precision, dimension(NGLLX) :: xigll
double precision, dimension(NGLLZ) :: zigll
! source arrays
double precision, dimension(NGLLX) :: hxis,hpxis
double precision, dimension(NGLLZ) :: hgammas,hpgammas
integer :: k,m
double precision :: hlagrange
double precision :: dsrc_dx,dsrc_dz
double precision :: dxis_dx,dgammas_dx
double precision :: dxis_dz,dgammas_dz
! compute Lagrange polynomials at the source location
! the source does not necessarily correspond to a Gauss-Lobatto point
if (AXISYM) then
if (is_on_the_axis(ispec_selected_source)) then ! TODO verify if we have to add : .and. myrank == islice_selected_source(i)
call lagrange_any(xi_source,NGLJ,xiglj,hxis,hpxis)
else
call lagrange_any(xi_source,NGLLX,xigll,hxis,hpxis)
endif
else
call lagrange_any(xi_source,NGLLX,xigll,hxis,hpxis)
endif
call lagrange_any(gamma_source,NGLLZ,zigll,hgammas,hpgammas)
dxis_dx = ZERO
dxis_dz = ZERO
dgammas_dx = ZERO
dgammas_dz = ZERO
do m = 1,NGLLZ
do k = 1,NGLLX
xixd = xix(k,m,ispec_selected_source)
xizd = xiz(k,m,ispec_selected_source)
gammaxd = gammax(k,m,ispec_selected_source)
gammazd = gammaz(k,m,ispec_selected_source)
hlagrange = hxis(k) * hgammas(m)
dxis_dx = dxis_dx + hlagrange * xixd
dxis_dz = dxis_dz + hlagrange * xizd
dgammas_dx = dgammas_dx + hlagrange * gammaxd
dgammas_dz = dgammas_dz + hlagrange * gammazd
enddo
enddo
! calculate source array
sourcearray(:,:,:) = ZERO
do m = 1,NGLLZ
do k = 1,NGLLX
dsrc_dx = (hpxis(k)*dxis_dx)*hgammas(m) + hxis(k)*(hpgammas(m)*dgammas_dx)
dsrc_dz = (hpxis(k)*dxis_dz)*hgammas(m) + hxis(k)*(hpgammas(m)*dgammas_dz)
sourcearray(1,k,m) = sourcearray(1,k,m) + real(Mxx*dsrc_dx + Mxz*dsrc_dx,kind=CUSTOM_REAL)
sourcearray(2,k,m) = sourcearray(2,k,m) + real(Mxz*dsrc_dx + Mzz*dsrc_dz,kind=CUSTOM_REAL)
enddo
enddo
end subroutine compute_arrays_source
!
!-----------------------------------------------------------------------------------------
!
subroutine read_adj_source(irec_local,adj_source_file)
! reads in adjoint source file
use constants, only: IIN,MAX_STRING_LEN,CUSTOM_REAL,NDIM,mygroup
! use specfem_par, only: myrank,NSTEP,P_SV,seismotype,source_adjoint
use specfem_par
implicit none
integer,intent(in) :: irec_local
character(len=MAX_STRING_LEN),intent(in) :: adj_source_file
! local parameters
integer :: icomp, itime
integer :: ier
double precision :: junk
double precision,dimension(NSTEP,3) :: adj_src_s
character(len=3) :: comp(3)
character(len=MAX_STRING_LEN) :: filename, path_to_add
! initializes temporary array
! note: we need to explicitly initialize the full array,
! otherwise it can lead to a floating overflow problem (with intel compiler 15.x)
! when copying the temporary array into the actual storage array adj_sourcearray
adj_src_s(:,:) = 0.d0
if (seismotype == 1 .or. seismotype == 2 .or. seismotype == 3) then
! displacement/velocity/acceleration
comp = (/"BXX","BXY","BXZ"/)
! reads corresponding components
do icomp = 1,3
! skips unnecessary components
if (P_SV) then
! P_SV-case: skips BXY component
if (icomp == 2) cycle
else
! SH-case: skips BXX and BXZ components
if (icomp == 1 .or. icomp == 3) cycle
endif
! reads in ascii adjoint source files **.adj
filename = 'SEM/'//trim(adj_source_file) // '.'// comp(icomp) // '.adj'
!-----------------------------------------------------------------------------
! this section added by dj 12/11/2018
! see if we are running several independent runs in parallel
! if so, add the right directory for that run
! (group numbers start at zero, but directory names start at run0001, thus we add one)
! a negative value for "mygroup" is a convention that indicates that groups (i.e. sub-communicators, one per run) are off
if (NUMBER_OF_SIMULTANEOUS_RUNS > 1 .and. mygroup >= 0) then
write(path_to_add,"('run',i4.4,'/')") mygroup + 1
filename = path_to_add(1:len_trim(path_to_add))//filename(1:len_trim(filename))
endif
!----------------------------------------------------------------------------
open(unit = IIN, file = trim(filename), iostat = ier)
if (ier /= 0) then
print *,'Error: could not find adjoint source file ',trim(filename)
print *,'Please check if file exists...'
call exit_MPI(myrank,'file '//trim(filename)//' does not exist')
endif
do itime = 1, NSTEP
read(IIN,*) junk, adj_src_s(itime,icomp)
enddo
close(IIN)
enddo
else if (seismotype == 4) then
! pressure
! reads in ascii adjoint source files **.PRE.adj
filename = 'SEM/'//trim(adj_source_file) // '.PRE.adj'
open(unit = IIN, file = trim(filename), iostat = ier)
if (ier /= 0) call exit_MPI(myrank,'file '//trim(filename)//' does not exist')
! reads only single component
do itime = 1, NSTEP
read(IIN,*) junk, adj_src_s(itime,1)
enddo
close(IIN)
else if (seismotype == 6) then
! potential
! reads in ascii adjoint source files **.POT.adj
filename = 'SEM/'//trim(adj_source_file) // '.POT.adj'
open(unit = IIN, file = trim(filename), iostat = ier)
if (ier /= 0) call exit_MPI(myrank,'file '//trim(filename)//' does not exist')
! reads only single component
do itime = 1, NSTEP
read(IIN,*) junk, adj_src_s(itime,1)
enddo
close(IIN)
endif
if (P_SV) then
! P_SV-case
source_adjoint(irec_local,:,1) = real(adj_src_s(:,1),kind=CUSTOM_REAL)
source_adjoint(irec_local,:,2) = real(adj_src_s(:,3),kind=CUSTOM_REAL)
else
! SH-case
source_adjoint(irec_local,:,1) = real(adj_src_s(:,2),kind=CUSTOM_REAL)
endif
end subroutine read_adj_source
!
!-----------------------------------------------------------------------------------------
!
subroutine read_adj_source_SU(seismotype)
! reads in all adjoint sources in SU-file format
use constants, only: CUSTOM_REAL,MAX_STRING_LEN,NDIM,mygroup
use specfem_par, only: myrank, NSTEP, nrec, &
islice_selected_rec, P_SV,source_adjoint,NUMBER_OF_SIMULTANEOUS_RUNS
implicit none
integer,intent(in) :: seismotype
! local parameters
integer :: irec, irec_local, ier
character(len=MAX_STRING_LEN) :: filename, path_to_add
! SU
integer(kind=4) :: r4head(60)
integer(kind=2) :: header2(2)
real(kind=4),dimension(:,:),allocatable :: adj_src_s
! opens adjoint source files in SU format
if (seismotype == 4 .or. seismotype == 6) then
! pressure/potential type
write(filename, "('./SEM/Up_file_single.su.adj')")
open(111,file=trim(filename),access='direct',recl=240+4*NSTEP,iostat = ier)
if (ier /= 0) call exit_MPI(myrank,'file '//trim(filename)//' does not exist')
else
! displacement/velocity/acceleration type
if (P_SV) then
! P_SV-case
write(filename, "('./SEM/Ux_file_single.su.adj')")
!----------------------------------------------------
! added by dj 12/11/2018, see above for comments
if (NUMBER_OF_SIMULTANEOUS_RUNS > 1 .and. mygroup >= 0) then
write(path_to_add,"('run',i4.4,'/')") mygroup + 1
filename = path_to_add(1:len_trim(path_to_add))//filename(1:len_trim(filename))
endif
!----------------------------------------------------
open(111,file=trim(filename),access='direct',recl=240+4*NSTEP,iostat = ier)
if (ier /= 0) call exit_MPI(myrank,'file '//trim(filename)//' does not exist')
write(filename, "('./SEM/Uz_file_single.su.adj')")
!----------------------------------------------------
! added by dj 12/11/2018, see above for comments
if (NUMBER_OF_SIMULTANEOUS_RUNS > 1 .and. mygroup >= 0) then
write(path_to_add,"('run',i4.4,'/')") mygroup + 1
filename = path_to_add(1:len_trim(path_to_add))//filename(1:len_trim(filename))
endif
!---------------------------------------------------
open(113,file=trim(filename),access='direct',recl=240+4*NSTEP,iostat = ier)
if (ier /= 0) call exit_MPI(myrank,'file '//trim(filename)//' does not exist')
else
! SH-case
write(filename, "('./SEM/Uy_file_single.su.adj')")
!--------------------------------------------------
! added by dj 12/11/2018, see above for comments
if (NUMBER_OF_SIMULTANEOUS_RUNS > 1 .and. mygroup >= 0) then
write(path_to_add,"('run',i4.4,'/')") mygroup + 1
filename = path_to_add(1:len_trim(path_to_add))//filename(1:len_trim(filename))
endif
!--------------------------------------------------
open(112,file=trim(filename),access='direct',recl=240+4*NSTEP,iostat = ier)
if (ier /= 0) call exit_MPI(myrank,'file '//trim(filename)//' does not exist')
endif
endif
! allocates temporary array
allocate(adj_src_s(NSTEP,NDIM))
irec_local = 0
do irec = 1, nrec
! only process/slice holding receiver
if (myrank == islice_selected_rec(irec)) then
irec_local = irec_local + 1
adj_src_s(:,:) = 0.0
if (seismotype == 4 .or. seismotype == 6) then
! pressure/potential
! single component
read(111,rec=irec,iostat=ier) r4head, adj_src_s(:,1)
if (ier /= 0) call exit_MPI(myrank,'file '//trim(filename)//' read error')
else
! displacement/velocity/acceleration
if (P_SV) then
! P_SV-case
read(111,rec=irec,iostat=ier) r4head, adj_src_s(:,1)
if (ier /= 0) call exit_MPI(myrank,'file '//trim(filename)//' read error')
read(113,rec=irec,iostat=ier) r4head, adj_src_s(:,2)
if (ier /= 0) call exit_MPI(myrank,'file '//trim(filename)//' read error')
else
! SH-case
read(112,rec=irec,iostat=ier) r4head, adj_src_s(:,1)
if (ier /= 0) call exit_MPI(myrank,'file '//trim(filename)//' read error')
endif
endif
header2 = int(r4head(29), kind=2)
if (P_SV) then
! P_SV-case
source_adjoint(irec_local,:,1) = real(adj_src_s(:,1),kind=CUSTOM_REAL)
source_adjoint(irec_local,:,2) = real(adj_src_s(:,2),kind=CUSTOM_REAL)
else
! SH-case
source_adjoint(irec_local,:,1) = real(adj_src_s(:,1),kind=CUSTOM_REAL)
endif
endif ! if (myrank == islice_selected_rec(irec))
enddo ! irec
! closes files
if (seismotype == 4) then
close(111)
else
if (P_SV) then
! P_SV-case
close(111)
close(113)
else
! SH-case
close(112)
endif
endif
! frees memory
deallocate(adj_src_s)
end subroutine read_adj_source_SU
|
/-
The goal of this assignment is to formalize a proof that there are infinitely many
primes.
-/
import tools.super -- provides some automation
/-
The statement
-/
namespace nat
protected def dvd (m n : ℕ) : Prop := ∃ k, n = m * k
instance : has_dvd nat := ⟨nat.dvd⟩
-- remember, type "dvd" with \|
def prime (n : ℕ) : Prop := n ≥ 2 ∧ ∀ m, m ∣ n → m = 1 ∨ m = n
-- this is what you need to prove:
check ∀ n, ∃ p, prime p ∧ p > n
end nat
/-
Some useful things
(You can use these also as examples.)
-/
namespace nat
theorem dvd_refl (m : ℕ) : m ∣ m :=
⟨1, by rw mul_one⟩
theorem dvd_trans : ∀ {m n k : ℕ}, m ∣ n → n ∣ k → m ∣ k
| m ._ ._ ⟨u, rfl⟩ ⟨v, rfl⟩ := ⟨u * v, by simp⟩
theorem dvd_mul_left (m n : ℕ) : m ∣ m * n :=
⟨n, rfl⟩
theorem dvd_mul_right (m n : ℕ) : m ∣ n * m :=
⟨n, by simp⟩
theorem dvd_add : ∀ {m n k : ℕ}, m ∣ n → m ∣ k → m ∣ (n + k)
| m ._ ._ ⟨u, rfl⟩ ⟨v, rfl⟩ := ⟨u + v, by simp [mul_add]⟩
theorem eq_sub_of_add_eq {m n k : ℕ} (h : m + n = k) : m = k - n :=
calc
m = m + n - n : by rw nat.add_sub_cancel
... = k - n : by rw h
theorem mul_sub (n m k : ℕ) : n * (m - k) = n * m - n * k :=
or.elim (le_or_gt m k)
(assume h : m ≤ k,
have n * m ≤ n * k, from mul_le_mul_left _ h,
by simp [sub_eq_zero_of_le h, sub_eq_zero_of_le this])
(suppose m > k,
have m ≥ k, from le_of_lt this,
eq_sub_of_add_eq begin rw [-mul_add, nat.sub_add_cancel this] end)
theorem dvd_sub : ∀ {m n k : ℕ}, m ∣ n → m ∣ k → m ∣ (n - k)
| m ._ ._ ⟨u, rfl⟩ ⟨v, rfl⟩ := begin rw -nat.mul_sub, apply dvd_mul_left end
theorem eq_or_ge_succ_of_ge {n m : ℕ} (h : n ≥ m) : n = m ∨ n ≥ succ m :=
begin
cases (lt_or_eq_of_le h) with h₁ h₂,
{ right, assumption },
left, symmetry, assumption
end
theorem eq_zero_or_eq_one_or_ge_2 (n : ℕ) : n = 0 ∨ n = 1 ∨ n ≥ 2 :=
begin
cases (nat.eq_or_lt_of_le (zero_le n)) with h₀ h₁,
{ left, symmetry, assumption},
cases (nat.eq_or_lt_of_le h₁) with h₁ h₂,
{ right, left, symmetry, assumption},
right, right, exact h₂
end
def ge_2_of_prime {p : ℕ} (h : prime p) : p ≥ 2 := h^.left
-- a nice bit of automation!
theorem has_divisor_of_not_prime {n : ℕ} (h₁ : n ≥ 2) (h₂ : ¬ prime n) :
∃ m, m ∣ n ∧ m ≠ 1 ∧ m ≠ n :=
by super
def complete_induction_on (n : ℕ) {p : ℕ → Prop} (h : ∀ n, (∀ m < n, p m) → p n) : p n :=
suffices ∀ n, ∀ m < n, p m, from this (succ n) _ (lt_succ_self n),
take n,
nat.induction_on n
(take m, suppose m < 0, absurd this (not_lt_zero m))
(take n,
assume ih : ∀ m < n, p m,
take m,
suppose m < succ n,
or.elim (lt_or_eq_of_le (le_of_lt_succ this))
(ih m)
(suppose m = n,
begin rw this, apply h, exact ih end))
theorem le_of_dvd {m n : ℕ} (h : m ∣ n) (h' : n ≠ 0) : m ≤ n :=
let ⟨k, hk⟩ := h in
have k ≠ 0, begin intro h, rw [h, mul_zero] at hk, contradiction end,
begin
rw [-(mul_one m), hk], apply mul_le_mul_left,
cases eq_or_ge_succ_of_ge (zero_le k),
{ contradiction },
assumption
end
theorem le_or_eq_succ_of_le_succ {m n : ℕ} (h : m ≤ succ n) : m ≤ n ∨ m = succ n :=
begin
cases m,
{ left, apply zero_le },
cases lt_or_eq_of_le (le_of_succ_le_succ h),
{ left, assumption },
right, apply congr_arg, assumption
end
end nat
/-
Here is an outline of my solution. You do not need to follow it.
If you succeed and are looking for more to do, try (stating and) proving that there are
infinitely many primes congruent to 3 modulo 4.
-/
open nat
-- This requires a fair bit of work. I used complete induction on n.
theorem has_prime_divisor (n : ℕ) : n ≥ 2 → ∃ p, prime p ∧ p ∣ n := sorry
def fact : ℕ → ℕ
| 0 := 1
| (n+1) := (n+1) * fact n
theorem fact_ge_1 : ∀ n, fact n ≥ 1 := sorry
theorem fact_ge_self {n : ℕ} (nnz : n ≠ 0) : fact n ≥ n := sorry
theorem dvd_fact_of_le : ∀ n, ∀ m ≤ n, m > 0 → m ∣ fact n := sorry
-- lots of intermediate steps are deleted!
theorem infinitely_many_primes : ∀ n, ∃ p, prime p ∧ p > n :=
suffices h : ∀ n, n ≥ 2 → ∃ p, prime p ∧ p > n, from sorry,
take n,
assume nge2 : n ≥ 2,
have fact n + 1 ≥ 2, from succ_le_succ (fact_ge_1 n),
match has_prime_divisor _ this with
| ⟨p, primep, pdvd⟩ :=
have p > n, from lt_of_not_ge
(suppose p ≤ n,
have p ≤ fact n, from sorry,
have p > 0, from lt_of_lt_of_le dec_trivial (ge_2_of_prime primep),
have p ∣ fact n, from sorry,
have p ∣ fact n + 1 - fact n, from sorry,
have p ∣ 1, from sorry,
have p ≤ 1, from sorry,
have 2 ≤ 1, from sorry,
show false, from absurd this dec_trivial),
⟨p, primep, this⟩
end
|
<center>
<h1> INF285 - Computación Científica </h1>
<h2> Polynomial Interpolation: Vandermonde matrix, Lagrange interpolation, Barycentric interpolation, Newton's divided differences, Chebyshev points. </h2>
<h2> <a href="#acknowledgements"> [S]cientific [C]omputing [T]eam </a> </h2>
<h2> Version: 1.30</h2>
</center>
<div id='toc' />
## Table of Contents
* [Introduction](#intro)
* [Vandermonde Matrix](#vander)
* [Lagrange Interpolation](#lagrange)
* [Plotting $L_i(x)$](#LiLagrange)
* [Barycentric interpolation](#barycentric)
* [Newton's Divided Difference](#DDN)
* [Interpolation Error](#Error)
* [Runge Phenomenon](#runge)
* [Chebyshev Interpolation](#cheby)
* [Python Modules and Functions](#py)
* [Acknowledgements](#acknowledgements)
```python
import numpy as np
import matplotlib.pyplot as plt
import sympy as sym
from functools import reduce
import matplotlib as mpl
mpl.rcParams['font.size'] = 14
mpl.rcParams['axes.labelsize'] = 20
mpl.rcParams['xtick.labelsize'] = 14
mpl.rcParams['ytick.labelsize'] = 14
%matplotlib inline
from ipywidgets import interact, fixed, IntSlider, interact_manual, Checkbox, RadioButtons
sym.init_printing()
```
<div id='intro' />
## Introduction
[Back to TOC](#toc)
Hello! In this notebook we will learn how to interpolate 1D data with polynomials.
A polynomial interpolation consists in finding a polynomial that fits a discrete set of known data points, allowing us to construct new data points within the range of the data.
Formally, a polynomial $p(x)$ interpolate the data $(x_1,y_1),...,(x_n,y_n)$ if $p(x_i)=y_i$ for all $i$ in $1,...,n$.
```python
# Function that evaluates the xi's points in the polynomial
def EvaluateInterpolant(D, xx):
if D['Method']=='Vandermonde':
p = lambda x: np.dot(D['PrecomputedData'],np.power(x,np.arange(D['n'])))
elif D['Method']=='Lagrange':
p = lambda x: np.dot(D['PrecomputedData'],[np.prod(x - np.delete(D['x'],j)) for j in range(D['n'])])
elif D['Method']=='Barycentric':
wi = D['PrecomputedData']
xi = D['x']
yi = D['y']
p = lambda x: np.sum(yi*wi/(x-xi))/np.sum(wi/(x-xi)) if len(xi[xi == x])==0 else np.ndarray.item(yi[xi == x])
elif D['Method']=='Newton':
p = lambda x: np.dot(D['PrecomputedData'],np.append([1],[np.prod(x-D['x'][:j]) for j in range(1,D['n'])]))
return np.array([p(x) for x in xx])
# Function that shows the data points and the function that interpolates them.
def PlotInterpolant(D,ylim=None):
xi = np.linspace(min(D['x']),max(D['x']),1000)
yi = EvaluateInterpolant(D,xi)
plt.figure(figsize=(8,8))
plt.plot(D['x'],D['y'],'ro',label='Interpolation points')
plt.plot(xi,yi,'b-',label='$p(x)$')
plt.xlim(min(xi)-0.5, max(xi)+0.5)
if ylim:
plt.ylim(ylim[0], ylim[1])
else:
plt.ylim(min(yi)-0.5, max(yi)+0.5)
plt.grid(True)
plt.legend(loc='best')
plt.xlabel('$x$')
#plt.ylabel('$P(x)$')
plt.show()
```
<div id='vander' />
## Vandermonde Matrix
[Back to TOC](#toc)
First, we are going to learn the Vandermonde matrix method.
This is a $n \times n$ matrix (with $n$ being the cardinality of the set of known data points) with the terms of a geometric progression in each row.
It allows us to construct a system of linear equations with the objective of find the coefficients of the polynomial function that interpolates our data.
Example:
Given the set of known data points: $(x_1,y_1),(x_2,y_2),(x_3,y_3)$
Our system of linear equations will be:
$$ \begin{bmatrix}
1 & x_1 & x_1^2 \\[0.3em]
1 & x_2 & x_2^2 \\[0.3em]
1 & x_3 & x_3^2 \end{bmatrix}
\begin{bmatrix}
a_0 \\[0.3em]
a_1 \\[0.3em]
a_2 \end{bmatrix} =
\begin{bmatrix}
y_1 \\[0.3em]
y_2 \\[0.3em]
y_3 \end{bmatrix}$$
And by solving it we will find the coefficients $a_0,a_1,a_2$ that we need to construct the polynomial, $$p(x)=a_0+a_1\,x+a_2\,x^2,$$
that interpolates our data.
```python
def Vandermonde(x, y, show=False):
# We construct the matrix and solve the system of linear equations
# A = np.array([xi**np.arange(len(x)) for xi in x]) # OLDER VERSION
A = np.vander(x, increasing=True)
b = y
coefficients = np.linalg.solve(A,b)
n = len(x)
# The function shows the data if the flag is true
if show:
print('Data Points: '); print([(x[i],y[i]) for i in range(n)])
print('A = '); print(np.array_str(A, precision=2, suppress_small=True))
print("cond(A) = "+str(np.linalg.cond(A)))
print('b = '); print(np.array_str(b, precision=2, suppress_small=True))
print('x = '); print(np.array_str(coefficients, precision=2, suppress_small=True))
xS = sym.Symbol('x')
F = np.dot(xS**np.arange(len(x)),coefficients)
print('Interpolation Function: ')
print('F(x) = ')
print(F)
# Finally, we return a data structure with our interpolating polynomial
D = {'Method': 'Vandermonde',
'PrecomputedData': coefficients,
'x': x,
'y': y,
'n': n}
return D
```
The following example shows the output of a polynomial interpolation with the provided data.
We use an epsilon value on the thrid interpolation point ($x_3=3+\varepsilon$) and then we control it with a intercat widget, this way we can evaluate what will happen to the interpolation when two collocation points gets close to each other.
This behavior is obtained as soon as the third point is to close to $x_2=2$ by setting the value of $\varepsilon$ equal to $-1$, or making it close to the forth point $x_4$ by setting $\varepsilon$ equal to $2$.
```python
def show_time_Vandermonde(epsilon=0):
x = np.array([0.0,2.0,3.0+epsilon,4.0,5.0,6.0])
y = np.array([1.0,3.0,0.0,6.0,8.0,4.0])
D = Vandermonde(x,y,True)
PlotInterpolant(D)
interact(show_time_Vandermonde,epsilon=(-1,1,0.1))
```
interactive(children=(FloatSlider(value=0.0, description='epsilon', max=1.0, min=-1.0), Output()), _dom_classe…
<function __main__.show_time_Vandermonde(epsilon=0)>
As the numerical experiment show, the interpolated polynomial shows larger and larger oscilations as two points get close to each other.
Notice however that the function still interpolates the data.
<div id='lagrange' />
## Lagrange Interpolation
[Back to TOC](#toc)
With this method, we can interpolate data thanks to the Lagrange basis polynomials. Given a set of $n$ data points $(x_1,y_1),...,(x_n,y_n)$, the Lagrange interpolation polynomial is the following:
$$ p(x) = \sum^n_{i=1} y_i\,L_i(x),$$
where $L_i(x)$ are the Lagrange basis polynomials:
$$ L_i(x) = \prod^n_{j=1,j \neq i} \frac{x-x_j}{x_i-x_j} = \frac{x-x_1}{x_i-x_1} \cdot ... \cdot \frac{x-x_{i-1}}{x_i-x_{i-1}} \cdot \frac{x-x_{i+1}}{x_i-x_{i+1}} \cdot ... \cdot \frac{x-x_n}{x_i-x_n}$$
or simply $L_i(x)=\dfrac{l_i(x)}{l_i(x_i)}$, where $l_i(x)=\displaystyle{\prod^n_{j=1,j \neq i} (x-x_j)}$.
The key properties of these basis polynomials are the followings:
$$ L_i(x_i) = 1 $$
$$ L_{j \neq i}(x_i) = 0 $$
So, we assure that $L(x_i) = y_i$, which indeed interpolates the data.
```python
def Lagrange(x, y, show=False):
# We calculate the li's
n = len(x)
p = np.array([y[i]/np.prod(x[i] - np.delete(x,i)) for i in range(n)])
# The function shows the data if the flag is true
if show:
print('Data Points: '); print([(x[i],y[i]) for i in range(n)])
xS = sym.Symbol('x')
L = np.dot(np.array([np.prod(xS - np.delete(x,i))/np.prod(x[i] - np.delete(x,i)) for i in range(n)]),y)
print('Interpolation Function: ');
print(L)
# Finally, we return a data structure with our interpolating polynomial
D = {'Method': 'Lagrange',
'PrecomputedData': p,
'x': x,
'y': y,
'n': n}
return D
```
The following numerical experiment follows the same idea of the previous numerical experiment with the Vandermonde matrix.
```python
def show_time_Lagrange(epsilon=0):
x = np.array([0.0,2.0,3.0+epsilon,4.0,5.0,6.0])
y = np.array([1.0,3.0,0.0,6.0,8.0,4.0])
D = Lagrange(x,y,True)
PlotInterpolant(D)
interact(show_time_Lagrange,epsilon=(-1,1,0.1))
```
interactive(children=(FloatSlider(value=0.0, description='epsilon', max=1.0, min=-1.0), Output()), _dom_classe…
<function __main__.show_time_Lagrange(epsilon=0)>
<div id='LiLagrange' />
### Plotting $L_i(x)$
[Back to TOC](#toc)
The next cell shows what $L_i(x)$ looks like.
It basically shows how a polynomial looks like when it is one at $x_i$ and zero at all the other interpolation nodes.
```python
def show_time_Li(i=0, N=7):
x = np.arange(N+1)
y = np.zeros(N+1)
y[i]=1
D = Lagrange(x,y,True)
PlotInterpolant(D,[-1,2])
i_widget = IntSlider(min=0, max=7, step=1, value=0)
N_widget = IntSlider(min=1, max=20, step=1, value=7)
def update_i_range(*args):
i_widget.max = N_widget.value
N_widget.observe(update_i_range, 'value')
interact(show_time_Li,i=i_widget,N=N_widget)
```
interactive(children=(IntSlider(value=0, description='i', max=7), IntSlider(value=7, description='N', max=20, …
<function __main__.show_time_Li(i=0, N=7)>
The following example show all the $L_i(x)$ for $i\in\{1,2,\dots,N\}$ at once.
This was included thank to an inclass question!
```python
def show_time_all_Li(N=3, ShowLegend=False):
x = np.arange(1,N+1)
xx = np.linspace(1,N,1000)
for i in range(N):
y = np.zeros(N)
y[i]=1
D = Lagrange(x,y)
yy=EvaluateInterpolant(D, xx)
plt.plot(xx,yy,label=r'$L_{0}(x)$'.format(i+1))
if ShowLegend:
plt.legend(loc='best')
plt.grid(True)
interact(show_time_all_Li,N=(2,20,1), ShowLegend=Checkbox(value=False, description="Include legend"))
```
interactive(children=(IntSlider(value=3, description='N', max=20, min=2), Checkbox(value=False, description='I…
<function __main__.show_time_all_Li(N=3, ShowLegend=False)>
Here you get some questions about Lagrange Interpolation:
- Explain what happens with the interpolator polynomial when you add a new point to the set of points to interpolate. **Answer: We need to recalculate the polynomial**
- Why it is not a good idea to use Lagrange interpolation for a set of points which is constantly changing? **A: Because we need to compute the whole interpolation again**
- What is the operation count of obtaining the interpolator polynomial using Lagrange? What happens with the error?
#### As an additional example we show the $\text{sinc}(x)$ function.
This function is a relative of $L_i(x)$ from Lagrange interpolation, the only difference is that it is one at one point and zero over an infinite grid.
This could be alse use for interpolation, you only need to shift it a bit and you good to go!
This is not an polynomial interpolation but it may be a good alternative.
```python
xD = np.arange(-10,11)
yD = np.zeros_like(xD)
yD[10] = 1
xi = np.linspace(-10,10,1000)
yi = np.sinc(xi)
plt.figure(figsize=(8,8))
plt.plot(xD,yD,'ro',label='Interpolation points')
plt.plot(xi,yi,'b-',label='sinc$(x)$')
plt.xlim(min(xi)-0.5, max(xi)+0.5)
plt.ylim(min(yi)-0.5, max(yi)+0.5)
plt.grid(True)
plt.legend(loc='best')
plt.xlabel('$x$')
#plt.ylabel('$P(x)$')
plt.show()
```
<div id='barycentric' />
## Barycentric interpolation
[Back to TOC](#toc)
The barycentric interpolation for interpolation $n$ data points $(x_1,y_1),...,(x_n,y_n)$ is of the following form:
$$ p(x) = \dfrac{\displaystyle{\sum_{i=1}^n y_i\dfrac{w_i}{(x-x_i)}}}{\displaystyle{\sum_{i=1}^n \dfrac{w_i}{(x-x_i)}}},$$
where $w_i=\dfrac{1}{l_i(x)}$ and $l_i(x)=\displaystyle{\prod_{k=1,i\neq k}^n(x-x_k)}$.
```python
def Barycentric(x, y, show=False):
W = np.subtract.outer(x, x)
wi = 1/np.prod(W, axis=1, where = W!=0)
n = len(x)
# The function shows the data if the flag is true
if show:
print('Data Points: '); print([(x[i],y[i]) for i in range(n)])
xS = sym.Symbol('x')
N = np.sum(y*wi/(xS-x))/np.sum(wi/(xS-x))
print('Interpolation Function: ');
print(N)
# Finally, we return a data structure with our interpolating polynomial
D = {'Method':'Barycentric',
'PrecomputedData': wi,
'x': x,
'y': y,
'n': n}
return D
```
```python
def show_time_Barycentric(epsilon=0):
x = np.array([0.0,2.0,3.0+epsilon,4.0,5.0,6.0])
y = np.array([1.0,3.0,0.0,6.0,8.0,4.0])
D = Barycentric(x,y,True)
PlotInterpolant(D)
interact(show_time_Barycentric,epsilon=(-1,1,0.1))
```
interactive(children=(FloatSlider(value=0.0, description='epsilon', max=1.0, min=-1.0), Output()), _dom_classe…
<function __main__.show_time_Barycentric(epsilon=0)>
<div id='DDN' />
## Newton's Divided Difference
[Back to TOC](#toc)
In this interpolation method we will use divided differences to calculate the coefficients of our interpolation polynomial. Given a set of $n$ data points $(x_1,y_1),...,(x_n,y_n)$, the Newton polynomial is:
$$ p(x) = \sum^n_{i=1} (f[x_1 ... x_i] \cdot \prod^{i-1}_{j=1} (x-x_j)) ,$$
where $ \prod^{0}_{j=1} (x-x_j) = 0 $, and:
$$ f[x_i] = y_i $$
$$ f[x_j...x_i] = \frac{f[x_{j+1}...x_i]-f[x_j...x_{i-1}]}{x_i-x_j}$$
```python
def Divided_Differences(x, y):
dd = np.array([y])
n = len(x)
for i in range(n-1):
ddi = []
for a in range(n-i-1):
ddi.append((dd[i][a+1]-dd[i][a])/(x[a+i+1]-x[a]))
ddi = np.append(ddi,np.full((n-len(ddi),),0.0))
dd = np.append(dd,[ddi],axis=0)
return np.array(dd)
def Newton(x, y, show=False):
# We calculate the divided differences and store them in a data structure
dd = Divided_Differences(x,y)
n = len(x)
# The function shows the data if the flag is true
if show:
print('Data Points: '); print([(x[i],y[i]) for i in range(n)])
xS = sym.Symbol('x')
N = np.dot(dd[:,0],np.append([1],[np.prod(xS-x[:i]) for i in range(1,n)]))
print('Interpolation Function: ');
print(N)
# Finally, we return a data structure with our interpolating polynomial
D = {'Method':'Newton',
'PrecomputedData': dd[:,0],
'x': x,
'y': y,
'n': n}
return D
```
```python
def show_time_Newton(epsilon=0):
x = np.array([0.0,2.0,3.0+epsilon,4.0,5.0,6.0])
y = np.array([1.0,3.0,0.0,6.0,8.0,4.0])
D = Newton(x,y,True)
PlotInterpolant(D)
interact(show_time_Newton,epsilon=(-1,1,0.1))
```
interactive(children=(FloatSlider(value=0.0, description='epsilon', max=1.0, min=-1.0), Output()), _dom_classe…
<function __main__.show_time_Newton(epsilon=0)>
Questions about Newton's DD:
- What is the main problem using this method (and Lagrange)? How can you fix it? **A: A problem with polynomial interpolation with equispaced date is the Runge phenomenon and can be handle with Chebyshev points**
- What to do when a new point is added? **A: Pro, is not necessary re-calculate the whole polynomial only a small piece**
<div id='Error' />
## Polynomial Interpolation Error
[Back to TOC](#toc)
The interpolation error is given by:
$$ f(x)-p(x) = \frac{(x-x_1) \, (x-x_2) \, \dots \, (x-x_n)}{n!} \, f^{(n)}(c),$$
where $c$ is within the interval defined by $[\min(x,x_1,\dots,x_n),\max(x,x_1,\dots,x_n)]$.
```python
def Error(f, n, xmin, xmax, method=Lagrange, points=np.linspace, plot_flag=True):
# This function plots f(x), the interpolating polynomial, and the associated error
# points can be np.linspace to equidistant points or Chebyshev to get Chebyshev points
# This two lines generate the data that will be used in the interpolation
x = points(xmin,xmax,n)
y = f(x)
# This two lines compute the exact value of the function being interpolated on a finer grid
xe = np.linspace(xmin,xmax,100)
ye = f(xe)
# This two lines build the interpolant chosen, where the name of the method is
# passed as parameter usign the variable 'method'.
D = method(x,y)
yi = EvaluateInterpolant(D, xe)
if plot_flag:
plt.figure(figsize=(5,10))
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(15,5), sharey = False)
ax1.plot(xe, ye,'r-', label='f(x)')
ax1.plot(x, y,'ro', label='Interpolation points')
ax1.plot(xe, yi,'b-', label='Interpolation')
ax1.set_xlim(xmin-0.5,xmax+0.5)
ax1.set_ylim(min(yi)-0.5,max(yi)+0.5)
ax1.set_title('Interpolation')
ax1.grid(True)
ax1.set_xlabel('$x$')
ax1.legend(loc='best')
ax2.semilogy(xe, abs(ye-yi),'b-', label='Absolute Error')
ax2.set_xlim(xmin-0.5,xmax+0.5)
ax2.set_title('Absolute Error')
ax2.set_xlabel('$x$')
ax2.grid(True)
plt.show()
return max(abs(ye-yi))
```
```python
def test_error_Newton(n=5):
# Example 1
#me = Error(lambda x: np.sin(x)**3, n, 1, 7, Newton)
# Example 2
me = Error(lambda x: (1/(1+12*x**2)), n, -1, 1, Newton)
print("Max Error:", me)
```
```python
interact(test_error_Newton,n=(5,25))
```
interactive(children=(IntSlider(value=5, description='n', max=25, min=5), Output()), _dom_classes=('widget-int…
<function __main__.test_error_Newton(n=5)>
<div id='runge' />
## **Runge's Phenomenon**: It is a problem of oscillation of polynomials at the edges of the interval.
[Back to TOC](#toc)
We are interpolating a data that is 0 almost everywhere and 1 at the middle point.
Notice that as $n$ increases the oscilations increase and all the red dots seems to be at 0 in the plot but this is just an artifact due to the scale on the left.
The oscillations you see at the end of the interval is the Runge phenomenon.
This is due to the use of equalspaced point.
```python
def Runge(n=9):
x = np.linspace(0,1,n)
y = np.zeros(n)
y[int((n-1.0)/2.)]=1
D = Newton(x,y,False)
PlotInterpolant(D)
interact(Runge,n=(5,25,2))
```
interactive(children=(IntSlider(value=9, description='n', max=25, min=5, step=2), Output()), _dom_classes=('wi…
<function __main__.Runge(n=9)>
<div id='cheby' />
## Chebyshev Interpolation
[Back to TOC](#toc)
From the interpolation error defined previously, we notice on the right hand side that the only term we can actually control (besides $n$) is the actual value used for the $x_i$, for $i\in\{1,2,\dots,n\}$.
Thus, with the objective of reducing the error of the polynomial interpolation, we need to find the values of $x_1,x_2,...,x_n$ that minimize the following expression:
$$(x-x_1) \, (x-x_2) \, ... \, (x-x_n).$$
To choose these values we select the canonical interval $[-1,1]$, in particular, we expect the points to be in $-1 \leq x_1,x_2,...,x_n \leq 1$ (to use another interval we just need to do a change of variables).
This probles was already studied by Chebyshev, thus we will use the roots of the Chebyshev polynomials, also called **Chebyshev nodes** (of the first kind), which are defined by:
$$ x_i = \cos\left(\frac{(2i-1)\pi}{2n}\right), i\in\{1,2,\dots,n\} $$
```python
def Chebyshev(xmin,xmax,n=5):
# This function calculates the n Chebyshev points and plots or returns them depending on ax
ns = np.arange(1,n+1)
x = np.cos((2*ns-1)*np.pi/(2*n))
y = np.sin((2*ns-1)*np.pi/(2*n))
plt.figure(figsize=(10,5))
plt.ylim(-0.1,1.1)
plt.xlim(-1.1,1.1)
plt.plot(np.cos(np.linspace(0,np.pi)),np.sin(np.linspace(0,np.pi)),'k-')
plt.plot([-2,2],[0,0],'k-')
plt.plot([0,0],[-1,2],'k-')
for i in range(len(y)):
plt.plot([x[i],x[i]],[0,y[i]],'r-')
plt.plot([0,x[i]],[0,y[i]],'r-')
plt.plot(x,[0]*len(x),'bo',label='Chebyshev points')
plt.plot(x,y,'ro')
plt.xlabel('$x$')
plt.title('n = '+str(n))
plt.grid(True)
plt.legend(loc='best')
plt.show()
def Chebyshev_points(xmin,xmax,n):
ns = np.arange(1,n+1)
x = np.cos((2*ns-1)*np.pi/(2*n))
#y = np.sin((2*ns-1)*np.pi/(2*n))
return (xmin+xmax)/2 + (xmax-xmin)*x/2
def Chebyshev_points_histogram(n=50,nbins=20):
xCheb=Chebyshev_points(-1,1,n)
#plt.figure()
#plt.hist(xCheb,bins=nbins,density=True,cumulative=True)
#plt.grid(True)
#plt.show()
plt.figure(figsize=(5,10))
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(15,5), sharey = False)
ax1.hist(xCheb,bins=nbins,density=True)
ax1.grid(True)
ax2.hist(xCheb,bins=nbins,density=True,cumulative=True)
ax2.grid(True)
plt.show()
```
The next plot shows a graphical interpretation of the Chebyshev nodes, in particular, they are the projection on the $x$-axis from equalspaced point on the unit sphere.
The angle used for defining the equalspaced point on the unit sphere are: $\theta_i=\frac{(2i-1)\pi}{2n}$, for $i\in\{1,2,\dots,n\}$.
```python
interact(Chebyshev,xmin=fixed(-1),xmax=fixed(1),n=(2,50))
```
interactive(children=(IntSlider(value=5, description='n', max=50, min=2), Output()), _dom_classes=('widget-int…
<function __main__.Chebyshev(xmin, xmax, n=5)>
The next plot shows an histogram to explicitly show that the Chebychev nodes cluster at each end of the interval.
The left plot is an explicit histogram and the plot on the right is the cumulative distribution function.
```python
interact_manual(Chebyshev_points_histogram,n=(20,10000),nbins=(20,200))
```
interactive(children=(IntSlider(value=50, description='n', max=10000, min=20), IntSlider(value=20, description…
<function __main__.Chebyshev_points_histogram(n=50, nbins=20)>
Moreover, these points have the an explicit expresion for the term we want to minimize,
this means,
$$ (x-x_1) \, (x-x_2) \, ... \, (x-x_n) = \dfrac{1}{2^{n-1}} \, T_n(x), $$
where $T_n(x) = \cos (n \, \arccos (x))$ is the n-th Chebyshev polynomial.
$$
\begin{align*}
T_0(x) &= 1, \\
T_1(x) &= x, \\
T_2(x) &= 2x^2 -1,\\
\vdots
\end{align*}
$$
It also has a recurrence relation,
$$ T_{n+1}(x) = 2 \cdot x \cdot T_n(x) - T_{n-1}(x).$$
The importance of the first identity showed in this cell is that we can bound the left-hand-side when using Chebychev points.
This is not possible when using equalspaced points.
For instance, when using Chebychehv points we have the following bound,
$$|(x-x_1) \, (x-x_2) \, ... \, (x-x_n)| = \left|\dfrac{1}{2^{n-1}} \, T_n(x)\right|\leq \dfrac{1}{2^{n-1}}.$$
This is true since $T(x) = \cos (n \, \arccos (x))$ and $|\cos(x)|\leq 1$.
This is useful when one wants to find the number of points required to interpolate a funcion to a required error.
In this case the error would become,
$$
\begin{align*}
|f(x)-p(x)| &= \left|\frac{(x-x_1) \, (x-x_2) \, \dots \, (x-x_n)}{n!} \, f^{(n)}(c)\right|\\
&\leq \frac{1}{2^{n-1}\,n!} \, \left|f^{(n)}(c)\right|,
\end{align*}
$$
which is very nice!
We only need to pay attention to find a bound for $\left|f^{(n)}(c)\right|$ on the interval we want to interpolate the function.
In the next cell, for completeness, we plot the Chebyshev polynomials $T_n(x)$.
```python
# Recursive function that returns the n-th Chebyshev polynomial evaluated at x
def T(n,x):
if n == 0:
return x**0
elif n == 1:
return x
else:
return 2*x*T(n-1,x)-T(n-2,x)
# This function plots the first n Chebyshev polynomials
def Chebyshev_Polynomials(n=2, Flag_All_Tn=False):
x = np.linspace(-1,1,1000)
plt.figure(figsize=(10,5))
plt.xlim(-1, 1)
plt.ylim(-1.1, 1.1)
if Flag_All_Tn:
for i in np.arange(n+1):
y = T(i,x)
plt.plot(x,y,label='$T_{'+str(i)+'}(x)$')
else:
y = T(n,x)
plt.plot(x,y,label='$T_{'+str(n)+'}(x)$')
plt.legend(loc='right')
plt.grid(True)
plt.xlabel('$x$')
plt.show()
```
```python
interact(Chebyshev_Polynomials,n=(0,12),Flag_All_Tn=True)
```
interactive(children=(IntSlider(value=2, description='n', max=12), Checkbox(value=True, description='Flag_All_…
<function __main__.Chebyshev_Polynomials(n=2, Flag_All_Tn=False)>
The follwing function compares the error obtain by interpolation a function with equalspaced points and Chebychev points.
```python
def test_error_chebyshev(n=5):
mee = Error(lambda x: (1/(1+12*x**2)), n, -1, 1, Lagrange)
mec = Error(lambda x: (1/(1+12*x**2)), n, -1, 1, method=Lagrange, points=Chebyshev_points)
print("Max error (equidistants points):", mee)
print("Max error (Chebyshev nodes):", mec)
```
The plots on the left show the actual function and the corresponding interpolation.
The plots in the right show the error in $\log_{10}$ scale.
Notice that we interpolation polynomial goes by the interpolation nodes exactly, this induce an error equal to $0$ and these nodes.
This behaviour explain the down spikes on the logaritmic scales, but we care about the worst case.
In the worst case the equalspaced polynomial behaves very badly, this is way polynomial interpolation with Chebyshev points is so useful.
```python
interact(test_error_chebyshev,n=(5,100,2))
```
interactive(children=(IntSlider(value=5, description='n', min=5, step=2), Output()), _dom_classes=('widget-int…
<function __main__.test_error_chebyshev(n=5)>
Questions about Chebyshev:
- How can you calculate the Chebyshev points in the interval [a,b] instead of [-1,1]? **A: Using a change of variable**
## Convergence analysis
The next set of experiments show a convergence analysis comparing equalspaced points to Chebychev points.
The $x$-axis is the number of points used and the $y$-axis is the maxmimum error obtain on the interval in logarithmic scale.
The experiment are the followings:
1. $f(x)=x^{10}$. In this case both sets of points perform similarly, however there is a significant drop in the error when $n$ is equal to $11$. This means, the error reach a minimum of $10^{-14}$ app at that number points. Why?
2. $f(x)=|x^3|$. This looks like a naive function but it is not. The equalspace points start to decrease from an error of $10^{0}$ until an error app $10^{-3}$ with approximately 10 points, it then start to increase the error. On the other hand, the Chebychev points show a decresing behavior upto $n=50$ but it only reaches an error of app $10^{-5}$, which is too high. What is the issue with this funcion?
3. $f(x)=\exp(-(x^{-2}))$. This is also a tricky function bevcause involves a division by $0$ when we evaluate it at $x=0$, but it is well defined at that points. Similarly to the first example, the equalspaced points reduce the error upto $n=10$, and then start to increase. For the Chebychev points, they decrease upto 40 points and the also show a slight increment in the error. What is the value of $f(x)$ at $x=0$?
4. $f(x)=\dfrac{1}{1+x^2}$. In this case both cases decrease the error but faster for the Chebyshev points. The main difference is that the minimum error reached for equalspaced points is about $10^{-8}$ and $10^{-13}$ for the Chebyshev points, in both cases about $n=37$.
5. $f(x)=\sin^3(x)$. In this case both cases reached an error $10^{-14}$ with $n=20$, then for equalspaced points start to increase the error right away but for Chebyshev points it starts to increase at $n=40$.
Answers to the previous questions:
1. The reason is that when $n=11$ we will be interpolation an polynomial of degree $10$ with a polynomial of degree $10$, so we can reproduce it exactly! This is why the error is $0$. When $n$ was lower, we only had an approximation. It is interesting that the error increases as we increase the number of points after $n=10$. Would it be useful to change the algorihtm used?
2. The issue is that the function is not analytic, this is because it involves the absolute value. Recall that expression for the error requires the computation of the $n$-th derivative of $f(x)$ at a $c$ point, so if the function is not differentiable, in this case the issues is at $x=0$, we could expect a bad behavior. The probles can be easily solve if we interpolate the function with a polynomial defined on $[-1,0]$ and another on $[0,1]$, ensurring the are equal at $x=0$. In this case we only need two polynomials of degree $3$ and we will be able to reproduce the function exactly! The issue is to notice this when we only have access to the computational implementation of $f(x)$ and not to the function itself.
3. 0
4. -
5. -
**We strongly suggest you to try different functions and play around!**
```python
my_functions=[lambda x: x**10,
lambda x: np.abs(x**3),
lambda x: np.exp(-(x**-2)),
lambda x: 1/(1+x**2),
lambda x: np.sin(x)**3]
labels = ["x^{10}",
"|x^3|",
"\exp(-x^{-2})",
"1/(1+x^2)",
"\sin^3(x)"]
data=zip(labels,my_functions)
radio_button_function=RadioButtons(
options=list(data),
description='Function:',
disabled=False
)
radio_button_interpolation_algorithm=RadioButtons(
options=[('Vandermonde',Vandermonde),('Lagrange',Lagrange),('Barycentric',Barycentric),('Newton',Newton)],
value=Newton,
description='Algorithm:',
disabled=False
)
def convergence_study(my_function, method):
n=100
shift=1
n_points=np.arange(shift,n)
max_error=np.zeros(n-shift)
max_error_es=np.zeros(n-shift)
for i in n_points:
max_error[i-shift] = Error(my_function, i, -1, 1, method, Chebyshev_points, plot_flag=False)
max_error_es[i-shift] = Error(my_function, i, -1, 1, method, points=np.linspace, plot_flag=False)
axis=plt.figure(figsize=(8,8))
plt.semilogy(n_points,max_error,'bd',label='Chebyshev points',markersize=10)
plt.semilogy(n_points,max_error_es,'r.',label='Equalspaced poins',markersize=16)
plt.ylim(10**-16,10**4)
plt.grid(True)
plt.title('Interpolation Error')
plt.xlabel('Number of points used in the interpolation')
plt.ylabel('Max error on domain')
plt.legend(loc='best')
plt.show()
interact(convergence_study,my_function=radio_button_function, method=radio_button_interpolation_algorithm)
```
interactive(children=(RadioButtons(description='Function:', options=(('x^{10}', <function <lambda> at 0x7ff830…
<function __main__.convergence_study(my_function, method)>
<div id='py' />
## Python Modules and Functions
[Back to TOC](#toc)
Interpolation:
https://numpy.org/doc/stable/reference/generated/numpy.polyfit.html
Vandermonde Matrix:
https://numpy.org/doc/stable/reference/generated/numpy.vander.html
Lagrange Interpolator:
https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.lagrange.html
Barycentric Interpolator:
https://people.maths.ox.ac.uk/trefethen/barycentric.pdf
https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.BarycentricInterpolator.html
Chebyshev Points for the First Kind:
https://numpy.org/doc/stable/reference/generated/numpy.polynomial.chebyshev.chebroots.html
<div id='acknowledgements' />
# Acknowledgements
[Back to TOC](#toc)
* _Material created by professor Claudio Torres_ (`[email protected]`) _and assistants: Laura Bermeo, Alvaro Salinas, Axel Simonsen and Martín Villanueva. DI UTFSM. April 2016._
* _Material modified by Cristopher Arenas. May 2017._
* _Material modified by Claudio Torres. May 2017._
* _Bug fixed by Cristobal Carmona. April 2018._
* _Update June 2020 - v1.25 - C.Torres_ : Fixing formatting issues.
* _Update June 2020 - v1.26 - C.Torres_ : Adding "ylim" argumento to Interpolation_Plot(D,ylim=None) and addint "show_time_Li".
* _Update June 2020 - v1.27 - C.Torres_ : Adding comment that the Chebyshev nodes used are of the first kind and "Chebyshev_points_histogram".
* _Update May 2021 - v1.28 - C.Torres_ : Improving format, adding cumulative histogram in "Chebyshev_points_histogram", updating Python modules links, implementing Barycentric interpolation, changing functions names: Interpolation_Plot->PlotInterpolant, Y->EvaluateInterpolant; adding field 'n' to data structure 'D' used for building interpolant, several changes everywhere adding more explanations.
* _Update May 2021 - v1.29 - C.Torres_ : Adding "show_time_all_Li" thanks to Felipe Samur question during class. Thanks Felipe! Changing reference tu sympy from 'sp' to 'sym'.
* _Update May 2021 - v1.30 - C.Torres_ : Adding radio buttons to last examples.
```python
```
|
/-
Copyright (c) 2020 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import data.stream.init
import data.part
import data.nat.upto
/-!
# Fixed point
This module defines a generic `fix` operator for defining recursive
computations that are not necessarily well-founded or productive.
An instance is defined for `part`.
## Main definition
* class `has_fix`
* `part.fix`
-/
universes u v
open_locale classical
variables {α : Type*} {β : α → Type*}
/-- `has_fix α` gives us a way to calculate the fixed point
of function of type `α → α`. -/
class has_fix (α : Type*) :=
(fix : (α → α) → α)
namespace part
open part nat nat.upto
section basic
variables (f : (Π a, part $ β a) → (Π a, part $ β a))
/-- A series of successive, finite approximation of the fixed point of `f`, defined by
`approx f n = f^[n] ⊥`. The limit of this chain is the fixed point of `f`. -/
def fix.approx : stream $ Π a, part $ β a
| 0 := ⊥
| (nat.succ i) := f (fix.approx i)
/-- loop body for finding the fixed point of `f` -/
def fix_aux {p : ℕ → Prop} (i : nat.upto p)
(g : Π j : nat.upto p, i < j → Π a, part $ β a) : Π a, part $ β a :=
f $ λ x : α,
assert (¬p (i.val)) $ λ h : ¬ p (i.val),
g (i.succ h) (nat.lt_succ_self _) x
/-- The least fixed point of `f`.
If `f` is a continuous function (according to complete partial orders),
it satisfies the equations:
1. `fix f = f (fix f)` (is a fixed point)
2. `∀ X, f X ≤ X → fix f ≤ X` (least fixed point)
-/
protected def fix (x : α) : part $ β x :=
part.assert (∃ i, (fix.approx f i x).dom) $ λ h,
well_founded.fix.{1} (nat.upto.wf h) (fix_aux f) nat.upto.zero x
protected lemma fix_def {x : α} (h' : ∃ i, (fix.approx f i x).dom) :
part.fix f x = fix.approx f (nat.succ $ nat.find h') x :=
begin
let p := λ (i : ℕ), (fix.approx f i x).dom,
have : p (nat.find h') := nat.find_spec h',
generalize hk : nat.find h' = k,
replace hk : nat.find h' = k + (@upto.zero p).val := hk,
rw hk at this,
revert hk,
dsimp [part.fix], rw assert_pos h', revert this,
generalize : upto.zero = z, intros,
suffices : ∀ x',
well_founded.fix (fix._proof_1 f x h') (fix_aux f) z x' = fix.approx f (succ k) x',
from this _,
induction k generalizing z; intro,
{ rw [fix.approx,well_founded.fix_eq,fix_aux],
congr, ext : 1, rw assert_neg, refl,
rw nat.zero_add at this,
simpa only [not_not, subtype.val_eq_coe] },
{ rw [fix.approx,well_founded.fix_eq,fix_aux],
congr, ext : 1,
have hh : ¬(fix.approx f (z.val) x).dom,
{ apply nat.find_min h',
rw [hk,nat.succ_add,← nat.add_succ],
apply nat.lt_of_succ_le,
apply nat.le_add_left },
rw succ_add_eq_succ_add at this hk,
rw [assert_pos hh, k_ih (upto.succ z hh) this hk] }
end
end basic
end part
namespace part
instance : has_fix (part α) :=
⟨λ f, part.fix (λ x u, f (x u)) ()⟩
end part
open sigma
namespace pi
instance part.has_fix {β} : has_fix (α → part β) := ⟨part.fix⟩
end pi
|
(*
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: work_gga_c *)
(* prefix:
gga_c_zvpbeint_params *params;
assert(p->params != NULL);
params = (gga_c_zvpbeint_params * )(p->params);
*)
params_a_gamma := (1 - log(2))/Pi^2:
params_a_BB := 1:
$include "gga_c_pbe.mpl"
nu := (rs, z, t) ->
t*mphi(z)*(3/rs)^(1/6):
ff := (rs, z, t) ->
exp(-params_a_alpha*nu(rs, z, t)^3*m_abs(1*z)^params_a_omega):
f := (rs, z, xt, xs0, xs1) ->
f_pw(rs, z) + ff(rs, z, tp(rs, z, xt))*fH(rs, z, tp(rs, z, xt)):
|
from __future__ import print_function, division
from time import sleep
import arnold as ar
from subprocess import Popen
import os
import numpy as np
import pandas as pd
def mesh_and_show(mesh_file, d_cyl, l_cyl, r_outer, length_factor=0.4):
"""
Creates a spherical bulk mesh with a centered cylindrical inclusion and shows the mesh afterwards
Args:
mesh_file(str): File path to save mesh file (add .msh ending)
d_cyl(float): Diameter of the cylindrical inclusion (in µm)
l_cyl(float): Length of the cylindrical inclusion (in µm)
r_outer(float): Outer radius of the bulk mesh (in µm)
length_factor(float): Mesh element size is determined by curvature and then multipled with this factor
"""
ar.mesh.cylindrical_inclusion(mesh_file, d_cyl, l_cyl, r_outer, length_factor)
ar.mesh.show_mesh(mesh_file)
return
def cylindrical_inclusion_mesh_and_simulation(mesh_file, d_cyl, l_cyl, r_outer, length_factor, simulation_folder,
strain, material, logfile = False, iterations= 300 , step=0.3, conv_crit = 1e-11):
"""
Creates a spherical bulk mesh with a centered cylindrical inclusion and simulates a symetric contraction
(with constant strain) of the cylindric inclusion
Args:
mesh_file(str): File path to save mesh file (add .msh ending)
d_cyl(float): Diameter of the cylindrical inclusion (in µm)
l_cyl(float): Length of the cylindrical inclusion (in µm)
r_outer(float): Outer radius of the bulk mesh (in µm)
length_factor(float): Mesh element size is determined by curvature and then multipled with this factor
simulation_folder(str): File path to save simulation results
strain(float): Strain as (Length_base - Length_contracted)/Length_base.
Deformation is applied in x-direction and split equally to both poles,
from which defomation-size decreases linearly to the center (symetric contraction with constant strain).
Deformation can be determed as (Length_base - Length_contracted)
material (dict): Material properties in the form {'K_0': X, 'D_0':X, 'L_S': X, 'D_S': X}, see materials)
logfile(boolean): If True a reduced logfile of the saeno system output is stored. Default: False.
iterations(float): The maximal number of iterations for the saeno simulation. Default: 300.
step(float): Step width parameter for saeno regularization. Higher values lead to a faster but less robust convergence. Default: 0.3.
conv_crit(float): Saeno stops if the relative standard deviation of the residuum is below given threshold. Default: 1e-11.
"""
ar.mesh.cylindrical_inclusion(mesh_file, d_cyl, l_cyl, r_outer, length_factor)
# wait a bit longer until mesh is stored
sleep(5)
ar.simulation.cylindric_contraction(simulation_folder, mesh_file, d_cyl, l_cyl, r_outer, strain, material,
logfile = logfile, iterations= iterations , step=step, conv_crit = conv_crit)
return
def cylindrical_inclusion_mesh_simulation_and_contractility(mesh_file, d_cyl, l_cyl, r_outer, length_factor, simulation_folder,
strain, material, logfile = False, iterations= 300 , step=0.3, conv_crit = 1e-11, scalef = 1000, scaleu = 1, scaleb = 1):
"""
Creates a spherical bulk mesh with a centered cylindrical inclusion and simulates a symetric contraction
(with constant strain) of the cylindric inclusion and computes the contractile forces.
Args:
mesh_file(str): File path to save mesh file (add .msh ending)
d_cyl(float): Diameter of the cylindrical inclusion (in µm)
l_cyl(float): Length of the cylindrical inclusion (in µm)
r_outer(float): Outer radius of the bulk mesh (in µm)
length_factor(float): Mesh element size is determined by curvature and then multipled with this factor
simulation_folder(str): File path to save simulation results
strain(float): Strain as (Length_base - Length_contracted)/Length_base.
Deformation is applied in x-direction and split equally to both poles,
from which defomation-size decreases linearly to the center (symetric contraction with constant strain).
material (dict): Material properties in the form {'K_0': X, 'D_0':X, 'L_S': X, 'D_S': X}, see materials)
logfile(boolean): If True a reduced logfile of the saeno system output is stored. Default: False.
iterations(float): The maximal number of iterations for the saeno simulation. Default: 300.
step(float): Step width parameter for saeno regularization. Higher values lead to a faster but less robust convergence. Default: 0.3.
conv_crit(float): Saeno stops if the relative standard deviation of the residuum is below given threshold. Default: 1e-11.
scalef ,scalu, scaleb: To scale the arrows for deformation , force and
boundary cond. in quiver plot - only visually no impact on valeus
"""
#build mesh
ar.mesh.cylindrical_inclusion(mesh_file, d_cyl, l_cyl, r_outer, length_factor)
#wait a bit longer until mesh is stored
sleep(5)
#start saeno simulation
ar.simulation.cylindric_contraction(simulation_folder, mesh_file, d_cyl, l_cyl, r_outer, strain, material,
logfile = logfile, iterations= iterations , step=step, conv_crit = conv_crit)
#wait a bit
sleep(3)
# compute individual contractilities
ar.force.reconstruct_contractility(simulation_folder, d_cyl, l_cyl, r_outer, scalef = scalef, scaleu = scaleu, scaleb = scaleu)
return
def cylindrical_inclusion_simulation_and_contractility(mesh_file, d_cyl, l_cyl, r_outer, simulation_folder,
strain, material, logfile = False, iterations= 300 , step=0.3, conv_crit = 1e-11):
"""
Simulates a symetric contraction (with constant strain) of the cylindric inclusion and
computes the contractile forces.
Args:
mesh_file(str): File path to save mesh file (add .msh ending)
d_cyl(float): Diameter of the cylindrical inclusion (in µm)
l_cyl(float): Length of the cylindrical inclusion (in µm)
r_outer(float): Outer radius of the bulk mesh (in µm)
simulation_folder(str): File path to save simulation results
strain(float): Strain as (Length_base - Length_contracted)/Length_base.
Deformation is applied in x-direction and split equally to both poles,
from which defomation-size decreases linearly to the center (symetric contraction with constant strain).
material (dict): Material properties in the form {'K_0': X, 'D_0':X, 'L_S': X, 'D_S': X}, see materials)
logfile(boolean): If True a reduced logfile of the saeno system output is stored. Default: False.
iterations(float): The maximal number of iterations for the saeno simulation. Default: 300.
step(float): Step width parameter for saeno regularization. Higher values lead to a faster but less robust convergence. Default: 0.3.
conv_crit(float): Saeno stops if the relative standard deviation of the residuum is below given threshold. Default: 1e-11.
"""
ar.simulation.cylindric_contraction(simulation_folder, mesh_file, d_cyl, l_cyl, r_outer, strain, material,
logfile = logfile, iterations= iterations , step=step, conv_crit = conv_crit)
ar.force.reconstruct_contractility(simulation_folder, d_cyl, l_cyl, r_outer)
return
def simulation_series_lengths(d_cyl, l_cyl_min, l_cyl_max, n, r_outer, length_factor, simulation_folder, strain, material,
log_scaling=True, n_cores=None, dec=10, logfile = True, iterations= 300 , step=0.3, conv_crit = 1e-11):
"""
Starts a series of simulation for different fiber lengths and evaluates fiber contractility
Args:
d_cyl(float): Diameter of the cylindrical inclusion (in µm)
l_cyl_min(float): Minmal length of the cylindrical inclusion (in µm)
l_cyl_max(float): Maximal length of the cylindrical inclusion (in µm)
n(float): Number of simulates to be made between minimal and maximal length
r_outer(float): Outer radius of the bulk mesh (in µm)
length_factor(float): Mesh element size is determined by curvature and then multipled with this factor
simulation_folder(str): File path to save simulation results
strain(float): Strain as (Length_base - Length_contracted)/Length_base.
Deformation is applied in x-direction and split equally to both poles,
from which defomation-size decreases linearly to the center (symetric contraction with constant strain).
log_scaling(boolean): Logarithmic or Linear scaling between cell lengths
n_cores(float): Amount of simultanious processes to be started, default detects the amount of CPU cores
dec(int): Decimal value to round the lengths, default is 10
material (dict): Material properties in the form {'K_0': X, 'D_0':X, 'L_S': X, 'D_S': X}, see materials)
logfile(boolean): If True a reduced logfile of the saeno system output is stored. Default: True.
iterations(float): The maximal number of iterations for the saeno simulation. Default: 300.
step(float): Step width parameter for saeno regularization. Higher values lead to a faster but less robust convergence. Default: 0.3.
conv_crit(float): Saeno stops if the relative standard deviation of the residuum is below given threshold. Default: 1e-11.
"""
# detect number of cores for paralell computing
if n_cores is None:
n_cores = os.cpu_count()
print(str(n_cores)+' cores detected')
# List of lengths in logarithmic steps to start simulation
if log_scaling:
L = np.logspace(np.log10(l_cyl_min), np.log10(l_cyl_max), num=n, endpoint=True)
# List of lengths in linear steps to start simulation
else:
L = np.linspace(l_cyl_min, l_cyl_max, num=n, endpoint=True)
# Limit decimal
L = np.around(L, decimals=dec)
print('Lengths: '+str(L))
L = list(L)
# create output folder if it doesn't exist
if not os.path.exists(simulation_folder):
os.makedirs(simulation_folder)
# Start single simulations in paralell
processes = []
while True:
if len(L) == 0:
break
if len(processes) < n_cores:
command = '''python -c "import arnold as ar; ar.experiment.cylindrical_inclusion_mesh_simulation_and_contractility(r'{}',{},{},{},{},r'{}',{},{},{},{},{},{})"'''.format(simulation_folder+'\\'+str(L[0])+'.msh', d_cyl,
L[0], r_outer, length_factor, simulation_folder+'\\'+str(L[0]), strain, material,
logfile, iterations , step, conv_crit )
processes.append(Popen(command))
del L[0]
sleep(1.)
processes = [p for p in processes if p.poll() is None]
def simulation_series_diameter(d_cyl_min, d_cyl_max, l_cyl, n, r_outer, length_factor, simulation_folder, strain, material,
log_scaling=True, n_cores=None, dec=2 , logfile = True, iterations= 300 , step=0.3, conv_crit = 1e-11):
"""
Starts a series of simulation for different fiber diameters and evaluates the fiber contractility
Args:
d_cyl_min(float): Minimal diameter of the cylindrical inclusion (in µm)
d_cyl_max(float): Maximal diameter of the cylindrical inclusion (in µm)
l_cyl(float): Length of the cylindrical inclusion (in µm)
n(float): Number of simulates to be made between minimal and maximal length
r_outer(float): Outer radius of the bulk mesh (in µm)
length_factor(float): Mesh element size is determined by curvature and then multipled with this factor
simulation_folder(str): File path to save simulation results
Strain(float): Strain applied on the muscle fiber (Length_base - Length_contracted/Length_base)
# Total deformation of the cylindric inclusion (in µm). Deformation is applied in x-direction
# and split equally to both poles, from which defomation-size decreases linearly to the center
# (symetric contraction with constant strain). Positive values denote a contraction.
# Deformation can be determed as (Length_base - Length_contracted)
log_scaling(boolean): Logarithmic or Linear scaling between cell lengths
n_cores(float): Amount of simultanious processes to be started, default detects the amount of CPU cores
dec(int): Decimal value to round the lengths, default is 10
material (dict): Material properties in the form {'K_0': X, 'D_0':X, 'L_S': X, 'D_S': X}, see materials)
logfile(boolean): If True a reduced logfile of the saeno system output is stored. Default: True.
iterations(float): The maximal number of iterations for the saeno simulation. Default: 300.
step(float): Step width parameter for saeno regularization. Higher values lead to a faster but less robust convergence. Default: 0.3.
conv_crit(float): Saeno stops if the relative standard deviation of the residuum is below given threshold. Default: 1e-11.
"""
# detect number of cores for paralell computing
if n_cores is None:
n_cores = os.cpu_count()
print(str(n_cores)+' cores detected')
# List of lengths in logarithmic steps to start simulation
if log_scaling:
d = np.logspace(np.log10(d_cyl_min), np.log10(d_cyl_max), num=n, endpoint=True)
# List of lengths in linear steps to start simulation
else:
d = np.linspace(d_cyl_min, d_cyl_max, num=n, endpoint=True)
# Limit decimal
d = np.around(d, decimals=dec)
print('Diameters: '+str(d))
d = list(d)
# create output folder if it doesn't exist
if not os.path.exists(simulation_folder):
os.makedirs(simulation_folder)
# Start single simulations in paralell
processes = []
while True:
if len(d) == 0:
break
if len(processes) < n_cores:
command = '''python -c "import arnold as ar; ar.experiment.cylindrical_inclusion_mesh_simulation_and_contractility(r'{}',{},{},{},{},r'{}',{},{},{},{},{},{})"'''.format(simulation_folder+'\\'+str(d[0])+'.msh', d[0], l_cyl, r_outer,
length_factor, simulation_folder+'\\'+str(d[0]), strain, material,
logfile, iterations , step, conv_crit )
processes.append(Popen(command))
del d[0]
sleep(1.)
processes = [p for p in processes if p.poll() is None]
def simulation_series_strain(d_cyl, l_cyl, n, r_outer, length_factor, simulation_folder, strain_min, strain_max, material,
log_scaling=True, n_cores=None, dec=2 , logfile = True, iterations= 300 , step=0.3, conv_crit = 1e-11):
"""
Starts a series of simulation for different cell lengths and evaluates cell contractility
Args:
d_cyl(float): Diameter of the cylindrical inclusion (in µm)
l_cyl(float): Length of the cylindrical inclusion (in µm)
n(float): Number of simulates to be made between minimal and maximal Diameter
r_outer(float): Outer radius of the bulk mesh (in µm)
length_factor(float): Mesh element size is determined by curvature and then multipled with this factor
simulation_folder(str): File path to save simulation results
strain_min(float): Minimal strain applied on the muscle fiber (Length_base - Length_contracted/Length_base)
strain_max(float): Maximal strain applied on the muscle fiber (Length_base - Length_contracted/Length_base)
# Total deformation of the cylindric inclusion (in µm). Deformation is applied in x-direction
# and split equally to both poles, from which defomation-size decreases linearly to the center
# (symetric contraction with constant strain). Positive values denote a contraction.
# Deformation can be determed as (Length_base - Length_contracted)
log_scaling(boolean): Logarithmic or Linear scaling between cell lengths
n_cores(float): Amount of simultanious processes to be started, default detects the amount of CPU cores
dec(int): Decimal value to round the lengths, default is 10
material (dict): Material properties in the form {'K_0': X, 'D_0':X, 'L_S': X, 'D_S': X}, see materials)
logfile(boolean): If True a reduced logfile of the saeno system output is stored. Default: True.
iterations(float): The maximal number of iterations for the saeno simulation. Default: 300.
step(float): Step width parameter for saeno regularization. Higher values lead to a faster but less robust convergence. Default: 0.3.
conv_crit(float): Saeno stops if the relative standard deviation of the residuum is below given threshold. Default: 1e-11.
"""
# detect number of cores for paralell computing
if n_cores is None:
n_cores = os.cpu_count()
print(str(n_cores)+' cores detected')
# List of lengths in logarithmic steps to start simulation
if log_scaling:
e = np.logspace(np.log10(strain_min), np.log10(strain_max), num=n, endpoint=True)
# List of lengths in linear steps to start simulation
else:
e = np.linspace(strain_min, strain_max, num=n, endpoint=True)
# Limit decimal
e = np.around(e, decimals=dec)
print('Strains: '+str(e))
# create output folder if it doesn't exist DOPPELT
if not os.path.exists(simulation_folder):
os.makedirs(simulation_folder)
e = list(e)
# Start single simulations in paralell
processes = []
while True:
if len(e) == 0:
break
if len(processes) < n_cores:
command = '''python -c "import arnold as ar; ar.experiment.cylindrical_inclusion_mesh_simulation_and_contractility(r'{}',{},{},{},{},r'{}',{},{},{},{},{},{})"'''.format(simulation_folder+'\\'+str(e[0])+'.msh', d_cyl, l_cyl,
r_outer, length_factor, simulation_folder+'\\'+str(e[0]), e[0], material,
logfile, iterations , step, conv_crit )
processes.append(Popen(command))
del e[0]
sleep(1.)
processes = [p for p in processes if p.poll() is None]
def simulation_series_stiffness(d_cyl, l_cyl, n, r_outer, length_factor, simulation_folder, strain, material_min, material_max,
log_scaling=True, n_cores=None, dec=2 , logfile = True, iterations= 300 , step=0.3, conv_crit = 1e-11):
"""
Starts a series of simulation for different cell lengths and evaluates cell contractility
Args:
d_cyl(float): Diameter of the cylindrical inclusion (in µm)
l_cyl(float): Length of the cylindrical inclusion (in µm)
n(float): Number of simulates to be made between minimal and maximal Diameter
r_outer(float): Outer radius of the bulk mesh (in µm)
length_factor(float): Mesh element size is determined by curvature and then multipled with this factor
simulation_folder(str): File path to save simulation results
strain_(float): Strain applied on the muscle fiber (Length_base - Length_contracted/Length_base)
# Total deformation of the cylindric inclusion (in µm). Deformation is applied in x-direction
# and split equally to both poles, from which defomation-size decreases linearly to the center
# (symetric contraction with constant strain). Positive values denote a contraction.
# Deformation can be determed as (Length_base - Length_contracted)
log_scaling(boolean): Logarithmic or Linear scaling between cell lengths
n_cores(float): Amount of simultanious processes to be started, default detects the amount of CPU cores
dec(int): Decimal value to round the lengths, default is 10
material_min (dict): Material properties in the form {'K_0': X, 'D_0':X, 'L_S': X, 'D_S': X}, see materials) ranging from min K_0 stiffness to max K_0 stiffness
material_max (dict): Material properties in the form {'K_0': X, 'D_0':X, 'L_S': X, 'D_S': X}, see materials) ranging from min K_0 stiffness to max K_0 stiffness
logfile(boolean): If True a reduced logfile of the saeno system output is stored. Default: True.
iterations(float): The maximal number of iterations for the saeno simulation. Default: 300.
step(float): Step width parameter for saeno regularization. Higher values lead to a faster but less robust convergence. Default: 0.3.
conv_crit(float): Saeno stops if the relative standard deviation of the residuum is below given threshold. Default: 1e-11.
"""
# detect number of cores for paralell computing
if n_cores is None:
n_cores = os.cpu_count()
print(str(n_cores)+' cores detected')
# List of lengths in logarithmic steps to start simulation
if log_scaling:
k = np.logspace(np.log10(material_min['K_0']), np.log10(material_max['K_0']), num=n, endpoint=True)
# List of lengths in linear steps to start simulation
else:
k = np.linspace(material_min['K_0'], material_max['K_0'], num=n, endpoint=True)
# Limit decimal
k = np.around(k, decimals=dec)
print('Strains: '+str(k))
# create output folder if it doesn't exist
if not os.path.exists(simulation_folder):
os.makedirs(simulation_folder)
k = list(k)
# Start single simulations in paralell
processes = []
while True:
if len(k) == 0:
break
if len(processes) < n_cores:
material_min['K_0'] = str(k[0])
command = '''python -c "import arnold as ar; ar.experiment.cylindrical_inclusion_mesh_simulation_and_contractility(r'{}',{},{},{},{},r'{}',{},{},{},{},{},{})"'''.format(simulation_folder+'\\'+str(k[0])+'.msh', d_cyl,
l_cyl, r_outer, length_factor, simulation_folder+'\\'+str(k[0]), strain, material_min,
logfile, iterations , step, conv_crit )
processes.append(Popen(command))
del k[0]
sleep(1.)
processes = [p for p in processes if p.poll() is None]
def evaluate_series(path, comment=''):
"""
Evaluates several simulations and stores a overview in an excel file
Args:
path(str): File path to search subfolders for simulations
comment(str): Comment which is added to the evaluation file containing all simulations of all found subfolders
"""
# initialize summary dictionary
results = {'Diameter [µm]': [], 'Length [µm]': [], 'Strain [%]': [],'Contractility Absolute (mean) [N]': [], 'Contractility x-components (mean) [N]': [],
'Residuum Forces [N]': [], 'K_0': [], 'D_0': [],'L_S': [],'D_S': [], 'Deformation [µm]': [], 'Simulation Folder': []}
print ('Files found:')
for root, dirs, files in os.walk(path):
for name in files:
if name.endswith(("Contractilities.xlsx")):
print (str(root)+"\\parameters.txt")
print (str(root)+"\\Contractilities.xlsx")
pd.set_option('display.max_colwidth', -1) # use full length strings in pandas
Parameters = pd.read_csv(root+"\\parameters.txt", delimiter='=' , encoding = "ISO-8859-1", header=None)
Parameters.columns = ['name','value']
# Append values from parameter.txt
results['K_0'].append(float(Parameters[Parameters['name'].str.contains('K_0')]['value'])) # K0 value
results['D_0'].append(float(Parameters[Parameters['name'].str.contains('D_0')]['value']))
results['L_S'].append(float(Parameters[Parameters['name'].str.contains('L_S')]['value']))
results['D_S'].append(float(Parameters[Parameters['name'].str.contains('D_S')]['value']))
results['Diameter [µm]'].append(float(str(Parameters[Parameters['name'].str.contains('d_cyl')]['value']).split()[1])) # one more split needed due to um string inside..
length = float(str(Parameters[Parameters['name'].str.contains('l_cyl')]['value']).split()[1])
results['Length [µm]'].append(length)
deformation = float(str(Parameters[Parameters['name'].str.contains('deformation')]['value']).split()[1])
results['Deformation [µm]'].append(deformation) # one more split needed due to um string inside..
results['Strain [%]'].append((deformation/length)*100)
#results['Simulation Folder'].append(str(Parameters[Parameters['name'].str.contains('Output_folder')]['value']).split()[1]) #simulation folder from paramteres
results['Simulation Folder'].append(str(root)) # in case the name is manually changed after simulation
# Append values from Contractilities.xlsx
Contractilities = pd.read_excel(root+"\\Contractilities.xlsx")
results['Contractility Absolute (mean) [N]'].append(float(Contractilities['Contractility Absolute (mean) [N]']))
results['Contractility x-components (mean) [N]'].append(float(Contractilities['Contractility x-components (mean) [N]']))
results['Residuum Forces [N]'].append(float(Contractilities['Residuum Forces [N]']))
df = pd.DataFrame.from_dict(results)
df.columns = ['Diameter [µm]',
'Length [µm]',
'Strain [%]',
'Contractility Absolute (mean) [N]',
'Contractility x-components (mean) [N]',
'Residuum Forces [N]',
'K_0',
'D_0',
'L_S',
'D_S',
'Deformation [µm]',
'Simulation Folder']
df.to_excel(path+"\\series_evaluation_"+str(comment)+".xlsx")
return df
|
If $f$ and $g$ converge to $a$ and $b$, respectively, then $f - g$ converges to $a - b$. |
{-# LANGUAGE TemplateHaskell, RankNTypes #-}
module Geometry.LRS (
-- * Types
Dictionary,
-- * Functions
getDictionary,
selectPivot,
reverseRS,
lrs,
polytope2LiftedCone,
liftedCone2polyotpe,
lrsFacetEnumeration,
colFromList
)
where
import Geometry.Vertex
import Geometry.Matrix
import Data.Matrix as M hiding (trace)
import qualified Data.Vector as V
import Data.Maybe
import Data.List
import Util
import Control.Lens
import Debug.Trace
import Numeric.LinearProgramming hiding (simplex)
import Numeric.LinearAlgebra.HMatrix as HM
import Data.List
type Row = M.Matrix Rational
type Col = M.Matrix Rational
data Dictionary = Dict {
__B :: [Int],
__N :: [Int],
_dict :: M.Matrix Rational
}
deriving (Show, Eq)
makeLenses ''Dictionary
numRows :: Dictionary -> Int
numRows dictionary = nrows $ dictionary^.dict
numCols :: Dictionary -> Int
numCols dictionary = ncols $ dictionary^.dict
(|*|) = multStrassen
colFromList :: [a] -> M.Matrix a
colFromList = colVector . V.fromList
rowFromList :: [a] -> M.Matrix a
rowFromList = rowVector . V.fromList
-- | Wrapper of submatrix function. This function works for indices starting from 0 rather than 1 in the submatrix function
submatrix' ::
(Int, Int) -- ^ Rows indices
-> (Int, Int) -- ^ Cols indices
-> M.Matrix a
-> M.Matrix a
submatrix' (ro,rk) (co,ck) m = submatrix (ro+1) (rk+1) (co+1) (ck+1) m
-- | Lens for columns
colAt :: Int -> Lens' (M.Matrix Rational) Col
colAt j = lens (getCol' j) (\m c -> setCol' j c m)
getCol' :: Int -> M.Matrix a -> M.Matrix a
getCol' idx = colVector . (getCol (idx+1))
setCol' :: Int -> Col -> M.Matrix Rational -> M.Matrix Rational
setCol' idx col mat
| idx == 0 = col <|> right
| idx == (ncols mat) - 1 = left <|> col
| otherwise = left <|> col <|> right
where
left = submatrix' (0,(nrows mat)-1) (0,idx-1) mat
right = submatrix' (0,(nrows mat)-1) (idx+1, (ncols mat)-1) mat
-- | Lens for rows
rowAt :: Int -> Lens' (M.Matrix Rational) Row
rowAt i = lens (getRow' i) (\m r -> setRow' i r m)
getRow' :: Int -> M.Matrix a -> M.Matrix a
getRow' idx = rowVector . (getRow (idx+1))
setRow' :: Int -> Col -> M.Matrix Rational -> M.Matrix Rational
setRow' idx row mat
| idx == 0 = row <-> down
| idx == (nrows mat) - 1 = up <-> row
| otherwise = up <-> row <-> down
where
up = submatrix' (0,idx-1) (0,(ncols mat)-1) mat
down = submatrix' (idx+1, (nrows mat)-1) (0,(ncols mat)-1) mat
-- | Lens for accessing elements
elemAt :: (Int, Int) -> Lens' (M.Matrix a) a
elemAt (i, j) = lens (getElem' (i,j)) (\m x -> setElem' x (i,j) m)
getElem' :: (Int, Int) -> M.Matrix a -> a
getElem' (row, col) = getElem (row+1) (col+1)
setElem' :: a -> (Int, Int) -> M.Matrix a -> M.Matrix a
setElem' elem (row, col) mat
| row < 0 || col < 0 || row >= nrows mat || col >= ncols mat = error ("setElem': Trying to set at (" ++ show row ++ "," ++ show col ++ ") in a " ++ show (nrows mat) ++ "x" ++ show (ncols mat) ++ " matrix.")
| otherwise = setElem elem (row+1, col+1) mat
mapCol' :: (Int -> a -> a) -> Int -> M.Matrix a -> M.Matrix a
mapCol' f col m
| col < 0 || col > (ncols m)-1 = error "mapCol': index out of bounds"
| otherwise = mapCol f (col+1) m
mapRow' :: (Int -> a -> a) -> Int -> M.Matrix a -> M.Matrix a
mapRow' f row m
| row < 0 || row > (nrows m)-1 = error "mapCol': index out of bounds"
| otherwise = mapRow f (row+1) m
getOptimumVertex :: M.Matrix Rational -> Col -> Maybe Vertex
getOptimumVertex mat col = fmap (map toRational) $ feasNOpt result
where
problem = Maximize $ replicate (ncols mat) (-1)
constraints = Dense $ safeZipWith (:<=:) (map (map fromRational) $ M.toLists mat) (map fromRational $ concat $ M.toLists col)
result = exact problem constraints (map Free [1..ncols mat])
feasNOpt (Optimal (_, vertex)) = Just vertex
feasNOpt _ = Nothing
{-
Dictionary form
p21 p31
invA_b
p22 p32
-}
toHMatrix :: M.Matrix Rational -> HM.Matrix Double
toHMatrix matrix = HM.matrix cols (map (fromRational) (concat $ M.toLists matrix))
where
cols = ncols matrix
findBasis :: (Maybe (M.Matrix Rational), Maybe (M.Matrix Rational)) -> M.Matrix Rational -> Int -> (Maybe (M.Matrix Rational), Maybe (M.Matrix Rational))
findBasis (basic, cobasic) original colNum
| currRank == rows && colNum < cols = findBasis (basic, Just newCobasic) original (colNum + 1)-- Just ((fromJust cobasic) <|> (submatrix' (0,rows-1) (colNum, (ncols original)-1) original)) )
| currRank == rows = (basic, cobasic)-- Just ((fromJust cobasic) <|> (submatrix' (0,rows-1) (colNum, (ncols original)-1) original)) )
| currRank == candRank = findBasis (basic, Just newCobasic) original (colNum + 1)
| currRank < candRank = findBasis (Just newBasic, cobasic) original (colNum + 1)
where
rows = nrows original
cols = ncols original
currRank = if isNothing basic then 0 else rank (toHMatrix $ fromJust basic)
candVec = original ^. colAt colNum
candMat = if isNothing basic then candVec else (fromJust basic) <|> candVec
candRank = rank $ toHMatrix candMat
newBasic = if isNothing basic then candVec else (fromJust basic) <|> candVec
newCobasic = if isNothing cobasic then candVec else (fromJust cobasic) <|> candVec
sortSystem :: M.Matrix Rational -> (M.Matrix Rational, M.Matrix Rational)
sortSystem matrix = trace ("Matrix : "++ show matrix ++ "\n\nSorted " ++ show (findBasis (Nothing, Nothing) matrix 0) ) (((,) <$> (fromJust . fst) <*> (fromJust . snd)) (findBasis (Nothing, Nothing) matrix 0))
-- sortSystem :: M.Matrix Rational -> Col -> Vertex -> (M.Matrix Rational, Col)
-- sortSystem mat col vertex
-- | cols /= (rows `div` 2) = (,) mat col
-- | otherwise = (trace $ show $ M.fromLists (upper ++ lower)) (,) (M.fromLists (upper ++ lower)) col
-- where
-- matLists = M.toLists mat
-- rows = nrows mat
-- cols = ncols mat
-- slackMatr = submatrix' (0,rows-1) (0, rows - cols -2) $ identity rows
-- lower = getIndependent matLists [] 0 rows slackMatr
-- upper = matLists \\ lower
-- getDictionary :: Matrix Rational -> Col -> Vertex -> Dictionary
-- getDictionary _A b vertex = trace ("In dictionary" ++ show (rows,cols, nrows dictionary, ncols dictionary) ++ show newDict) Dict [0..rows] [rows+1..rows+cols] newDict
-- -- trace ("In dictionary" ++ show _A_B)
-- where
-- (newA, newb) = sortSystem _A b vertex
-- rows = nrows newA
-- cols = ncols newA
-- slack = identity rows
-- -- dictionary = newA <|> slack
-- topRow = rowFromList $ 1 : replicate rows 0 ++ replicate cols (1)
-- leftCol = colFromList $ replicate rows 0
-- dictionary = topRow <-> (leftCol <|> slack <|> newA )
-- -- c_B = submatrix' (0,0) (1,rows) topRow
-- -- c_N = submatrix' (0,0) (rows+1, rows+cols) topRow
-- -- _A_B = submatrix' (0,rows-1) (0,rows-1) dictionary
-- -- _A_N = submatrix' (0,rows-1) (rows, rows+cols-1) dictionary
-- _A_B = submatrix' (0,rows) (0,rows) dictionary
-- _A_N = submatrix' (0,rows) (rows+1, rows+cols) dictionary
-- Right invA_B = inverse _A_B
-- p2 = - invA_B |*| _A_N
-- p3 = invA_B |*| newb
-- -- p21 = (c_N - c_B |*| invA_B |*| _A_N)
-- -- p22 = invA_B |*| _A_N
-- -- p31 = -c_B |*| invA_B |*| newb
-- -- p32 = invA_B |*| newb
-- newDict = ((identity (rows+1)) <|> p2 <|> p3)
-- | Constructs initial dictionary given a set of inequalities and an optimum initial vertex
-- getDictionary :: M.Matrix Rational -> Col -> Vertex -> Dictionary
-- getDictionary _A b vertex = Dict [0..rows] [rows+1..rows+cols] newDict
-- where
-- -- (newA, newb) = sortSystem _A b vertex
-- initialDict = _A <|> slack
-- (basic, cobasic) = sortSystem initialDict
-- (newA, newb) = (,) _A b
-- rows = nrows newA
-- cols = ncols newA
-- slack = identity rows
-- dictionary = newA <|> slack
-- topRow = rowFromList $ 1 : replicate rows 0 ++ replicate cols 1
-- c_B = submatrix' (0,0) (1,rows) topRow
-- c_N = submatrix' (0,0) (rows+1, rows+cols) topRow
-- _A_B = submatrix' (0,rows-1) (0,rows-1) dictionary
-- _A_N = submatrix' (0,rows-1) (rows, rows+cols-1) dictionary
-- Right invA_B = inverse _A_B
-- p21 = (c_N - c_B |*| invA_B |*| _A_N)
-- p22 = invA_B |*| _A_N
-- p31 = -c_B |*| invA_B |*| newb
-- p32 = invA_B |*| newb
-- newDict = ((identity (rows+1)) <|> (p21 <-> p22) <|> (p31 <-> p32))
getDictionary :: M.Matrix Rational -> Col -> Vertex -> Dictionary
getDictionary _A b vertex = Dict [0..rows] [rows+1..rows+cols] newDict
where
-- (newA, newb) = sortSystem _A b vertex
initialDict = _A <|> slack
(basic, cobasic) = sortSystem initialDict
(newA, newb) = (,) _A b
rows = nrows newA
cols = ncols newA
slack = identity rows
-- dictionary = newA <|> slack
topRow = rowFromList $ 1 : replicate rows 0 ++ replicate cols 1
c_B = submatrix' (0,0) (1,rows) topRow
c_N = submatrix' (0,0) (rows+1, rows+cols) topRow
_A_B = basic --submatrix' (0,rows-1) (0,rows-1) dictionary
_A_N = cobasic --submatrix' (0,rows-1) (rows, rows+cols-1) dictionary
Right invA_B = inverse _A_B
p21 = (c_N - c_B |*| invA_B |*| _A_N)
p22 = invA_B |*| _A_N
p31 = -c_B |*| invA_B |*| newb
p32 = invA_B |*| newb
newDict = ((identity (rows+1)) <|> (p21 <-> p22) <|> (p31 <-> p32))
enteringVariable :: Dictionary -> Maybe Int
enteringVariable dictionary
| null negs = Nothing
| otherwise = trace ("ENTERINGVAR\nBASE: " ++ show (dictionary^._B) ++ "\nCOBASE: " ++ show (dictionary^._N)) (Just $ (fst.head.sort) negs)
where
rows = nrows $ dictionary^.dict
cobasic_0 = zip (dictionary^._N) (map (\j -> dictionary^.dict.elemAt (0,j)) [rows..])
negs = filter (\(_,value) -> value < 0) cobasic_0
lexMinRatio :: Dictionary -> Int -> Int
lexMinRatio dictionary s
| dim+1 == rows = 0
| null indexed_s = 0
| otherwise = trace ("LEXMINRATIO\nBASE: " ++ show (dictionary^._B) ++ "\nCOBASE: " ++ show (dictionary^._N)) (dictionary ^. _B) !! (fst $ indexed_s !! (fromJust $ elemIndex (minimum ratios) ratios))
where
rows = numRows dictionary
cols = numCols dictionary
dim = cols - rows - 1
dictMatrix = dictionary^.dict
col_s = dictMatrix ^. colAt s
_D = (dictMatrix ^. colAt (cols-1)) <|> submatrix' (0,rows-1) (0, rows-1) dictMatrix
slice_s = (concat.M.toLists) $ submatrix' (dim+1, rows-1) (0,0) col_s
indexed_s = filter (snd.(fmap (>0))) $ safeZipWith (,) [dim+1..rows-1] slice_s
sub_D = map (head . M.toLists . (\i -> _D ^. rowAt i) . fst) indexed_s
ratios = safeZipWith (map $) (map ((flip (/)) . snd) indexed_s) sub_D
-- | Selects entering and leaving variables for the next pivot in the dictionary
selectPivot :: Dictionary -> Maybe (Int, Int)
selectPivot dictionary
| s == Nothing = Nothing
| otherwise = Just (r, fromJust s)
where
s = enteringVariable dictionary
r = lexMinRatio dictionary (fromJust s)
pivot :: Int ->Int -> Dictionary -> Dictionary
pivot r s dictionary = Dict new_B new_N (_E |*| dictMatrix)
where
dictMatrix = dictionary ^. dict
col_s = dictMatrix ^. colAt (s)
t = fromJust $ elemIndex r (dictionary ^. _B) -- idxR
idxS = fromJust $ elemIndex s (dictionary ^. _N)
a_t = col_s ^. elemAt (t,0)
eta = (mapCol' (\_ x -> -x/a_t) 0 col_s) & elemAt (t,0) .~ (1/a_t)
_E = (identity (nrows dictMatrix)) & colAt t .~ eta
new_B = dictionary^._B & element t .~ s
new_N = dictionary^._N & element idxS .~ r
simplex :: Dictionary -> Dictionary
simplex dictionary
| idxsToPivot == Nothing = dictionary
| otherwise = simplex $ uncurry pivot (fromJust idxsToPivot) dictionary
where
idxsToPivot = selectPivot dictionary
-- | Reverse search.
reverseRS ::
Dictionary
-> Int -- ^ element in N
-> Maybe Int
reverseRS dictionary v
| conditions == False = trace ("REVERSE RS: " ++ show [firstCondition, sndCondition, lastCondition]) Nothing
| conditions == True = trace ("REVERSE RS: " ++ show v) Just u
where
dictMatrix = dictionary^.dict
rows = nrows dictMatrix
v_col = dictMatrix ^. colAt (v)
w_row_0 = dictMatrix ^. rowAt 0
u = lexMinRatio dictionary v
i = fromJust $ elemIndex u (dictionary ^. _B)
w_row_i = mapRow' (\_ x -> (v_col ^. elemAt (0,0))/(v_col ^. elemAt (i,0)) * x) 0 $ dictMatrix ^. rowAt (i)
diff_ws = (head.M.toLists) $ w_row_0 - w_row_i
firstCondition = (w_row_0 ^. elemAt (0,v)) > 0
sndCondition = u /= 0
lastCondition = all (>=0) [(diff_ws!!(snd idx))|idx <- (zip (dictionary^._N) [rows..]), (fst idx) < u ]
conditions = firstCondition && sndCondition && lastCondition -- Proposition 6.1
-- reverseRS :: -- reverse with pivot and selectPivot
-- Dictionary ->
-- Int ->
-- Maybe Int
-- reverseRS dictionary v
-- | newPivots == Nothing = Nothing
-- | condition == False = Nothing
-- | condition == True = Just u
-- where
-- u = lexMinRatio dictionary v
-- prev_B = pivot u v dictionary
-- newPivots = selectPivot prev_B
-- condition = fst (fromJust newPivots) == v && (snd (fromJust newPivots)) == u
getVertex :: Dictionary -> Vertex
getVertex dictionary = concat $ M.toLists $ submatrix' (1,dim) (cols-1, cols-1) (dictionary^.dict)
where
rows = numRows dictionary
cols = numCols dictionary
dim = cols - rows - 1
revSearch :: Dictionary -> [Vertex]
revSearch dictionary@(Dict _B _N dictMatrix) -- = getVertex dictionary : concatMap revSearch pivoted
| (not.null) possibleRay = possibleRay ++ (concatMap revSearch pivoted)
| otherwise = getVertex dictionary : concatMap revSearch pivoted
where
rows = numRows dictionary
cols = numCols dictionary
valid_N = [i | i <- _N, (reverseRS dictionary i) /= Nothing]
valid_B = map (lexMinRatio dictionary) valid_N
pivoted = map (\(r, s) -> pivot r s dictionary) $ zip valid_B valid_N
possibleRay = hasRay dictionary
-- lexMin :: Dictionary -> Maybe Extremal
-- lexMin dictionary
hasRay :: Dictionary -> [Vertex]
hasRay dictionary = trace ("RAYS: " ++ show (map snd rays) ++ "\n\n" ++ show (map fst rays) ++ "\n" ++ show (dictionary ^. dict) ++ "\n\n") (map snd rays)
-- idxsPivot == Nothing = Nothing
-- r == 0 = Just ray
-- otherwise = Nothing
where
dictMatrix = dictionary ^. dict
rows = numRows dictionary
dim = cols - rows - 1
cols = numCols dictionary
nonPositive column = all (<=0) ((concat.M.toLists) column)
colsWithRays = if dim+1 == rows then
[(j, dictMatrix^.colAt j) | j <- [rows..cols-2]]
else [(j, dictMatrix^.colAt j) | j <- [rows..cols-2], nonPositive (submatrix' (dim+1,rows-1) (j,j) dictMatrix )]
rays = zip (map fst colsWithRays) (map (concat . M.toLists . (submatrix' (1,dim) (0,0)) . snd ) colsWithRays)
-- | Implementation of Lexicographic Reverse Search
lrs :: M.Matrix Rational -> Col -> Vertex-> [Vertex]
lrs matrix b vertex = (sort.nub) $ revSearch dictionary
where
dictionary = simplex $ getDictionary matrix b vertex
-- | Transforms a V polytope into a H pointed cone
polytope2LiftedCone :: [Vertex] -> (M.Matrix Rational, Col)
polytope2LiftedCone points = (colOnes <|> hMatrix , colZeros)
where
nrows = length points
colOnes = colFromList $ replicate nrows 1
hMatrix = M.fromLists points
colZeros = colFromList $ replicate nrows 0
-- | Transforms a V pointed cone into a H polyotpe
liftedCone2polyotpe :: [Vertex] -> (M.Matrix Rational, Col)
liftedCone2polyotpe points = (hMatrix, b)
where
dim = length (points !! 0)
rays = points \\ [(replicate dim 0)] -- remove vertex at the origin
b = colFromList $ map (negate.head) rays
hMatrix = M.fromLists $ map tail rays
-- | Implementation of Lexicographic Reverse Search for Facet Enumeration
lrsFacetEnumeration :: [IVertex] -> (M.Matrix Rational, Col)
lrsFacetEnumeration ipoints = hPolytope
where
points = map (map toRational) ipoints
cols = length (points!!0)
initialVertex = replicate (cols + 1) 0
hLiftedCone@(matrix, b) = polytope2LiftedCone points
vLiftedCone = lrs matrix b initialVertex
hPolytope = liftedCone2polyotpe vLiftedCone
|
"""
RasterDataSource
Abstract supertype for raster data collections.
"""
abstract type RasterDataSource end
"""
RasterDataSet
Abstract supertype for datasets that belong to a [`RasterDataSource`](@ref).
"""
abstract type RasterDataSet end
"""
BioClim <: RasterDataSet
BioClim datasets. Usually containing layers from `1:19`.
These can also be accessed with `:bioX`, e.g. `:bio5`.
They do not usually use `month` or `date` keywords, but may use
`date` in past/future scenarios.
Currently implemented for WorldClim and CHELSA as `WorldClim{BioClim}`,
`CHELSA{BioClim}` and `CHELSA{Future{BioClim, args..}}`.
See the [`getraster`](@ref) docs for implementation details.
"""
struct BioClim <: RasterDataSet end
# Bioclim has standardised layers for all data sources
layers(::Type{BioClim}) = values(bioclim_lookup)
layerkeys(T::Type{BioClim}) = keys(bioclim_lookup)
layerkeys(T::Type{BioClim}, layer) = bioclim_key(layer)
layerkeys(T::Type{BioClim}, layers::Tuple) = map(l -> bioclim_key(l), layers)
const bioclim_lookup = (
bio1 = 1,
bio2 = 2,
bio3 = 3,
bio4 = 4,
bio5 = 5,
bio6 = 6,
bio7 = 7,
bio8 = 8,
bio9 = 9,
bio10 = 10,
bio11 = 11,
bio12 = 12,
bio13 = 13,
bio14 = 14,
bio15 = 15,
bio16 = 16,
bio17 = 17,
bio18 = 18,
bio19 = 19,
)
# We allow a range of bioclim keys, as they are listed with
# a lot of variants on CHELSA and WorldClim
bioclim_key(k::Symbol) = bioclim_key(string(k))
bioclim_key(k::AbstractString) = Symbol(replace(lowercase(k), "_" => ""))
bioclim_key(k::Integer) = keys(bioclim_lookup)[k]
bioclim_int(k::Integer) = k
bioclim_int(k::Symbol) = bioclim_lookup[bioclim_key(k)]
"""
Climate <: RasterDataSet
Climate datasets. These are usually months of the year, not specific dates,
and use a `month` keyword in `getraster`. They also use `date` in past/future scenarios.
Currently implemented for WorldClim and CHELSA as `WorldClim{Climate}`,
`CHELSA{Climate}` and `CHELSA{Future{Climate, args..}}`.
See the [`getraster`](@ref) docs for implementation details.
"""
struct Climate <: RasterDataSet end
months(::Type{Climate}) = ntuple(identity, Val{12})
"""
Weather <: RasterDataSet
Weather datasets. These are usually large time-series of specific dates,
and use a `date` keyword in `getraster`.
Currently implemented for WorldClim and CHELSA as `WorldClim{Weather}`,
and `CHELSA{Weather}`
See the [`getraster`](@ref) docs for implementation details.
"""
struct Weather <: RasterDataSet end
"""
LandCover <: RasterDataSet
Land-cover datasets.
Currently implemented for EarthEnv as `EarchEnv{LandCover}`.
See the [`getraster`](@ref) docs for implementation details.
"""
struct LandCover{X} <: RasterDataSet end
"""
HabitatHeterogeneity <: RasterDataSet
Habitat heterogeneity datasets.
Currently implemented for EarchEnv as `EarchEnv{HabitatHeterogeneity}`.
See the [`getraster`](@ref) docs for implementation details.
"""
struct HabitatHeterogeneity <: RasterDataSet end
"""
ClimateModel
Abstract supertype for climate models use in [`Future`](@ref) datasets.
"""
abstract type ClimateModel end
struct ACCESS1 <: ClimateModel end
struct BNUESM <: ClimateModel end
struct CCSM4 <: ClimateModel end
struct CESM1BGC <: ClimateModel end
struct CESM1CAM5 <: ClimateModel end
struct CMCCCMS <: ClimateModel end
struct CMCCCM <: ClimateModel end
struct CNRMCM5 <: ClimateModel end
struct CSIROMk3 <: ClimateModel end
struct CanESM2 <: ClimateModel end
struct FGOALS <: ClimateModel end
struct FIOESM <: ClimateModel end
struct GFDLCM3 <: ClimateModel end
struct GFDLESM2G <: ClimateModel end
struct GFDLESM2M <: ClimateModel end
struct GISSE2HCC <: ClimateModel end
struct GISSE2H <: ClimateModel end
struct GISSE2RCC <: ClimateModel end
struct GISSE2R <: ClimateModel end
struct HadGEM2AO <: ClimateModel end
struct HadGEM2CC <: ClimateModel end
struct IPSLCM5ALR <: ClimateModel end
struct IPSLCM5AMR <: ClimateModel end
struct MIROCESMCHEM <: ClimateModel end
struct MIROCESM <: ClimateModel end
struct MIROC5 <: ClimateModel end
struct MPIESMLR <: ClimateModel end
struct MPIESMMR <: ClimateModel end
struct MRICGCM3 <: ClimateModel end
struct MRIESM1 <: ClimateModel end
struct NorESM1M <: ClimateModel end
struct BCCCSM1 <: ClimateModel end
struct Inmcm4 <: ClimateModel end
struct BCCCSM2MR <: ClimateModel end
struct CNRMCM61 <: ClimateModel end
struct CNRMESM21 <: ClimateModel end
struct CanESM5 <: ClimateModel end
struct GFDLESM4 <: ClimateModel end
struct IPSLCM6ALR <: ClimateModel end
struct MIROCES2L <: ClimateModel end
struct MIROC6 <: ClimateModel end
struct MRIESM2 <: ClimateModel end
struct UKESM <: ClimateModel end
struct MPIESMHR <: ClimateModel end
"""
CMIPphase
Abstract supertype for phases of the CMIP,
the Coupled Model Intercomparison Project.
Subtypes are `CMIP5` and `CMIP6`.
"""
abstract type CMIPphase end
"""
CMIP5 <: CMIPphase
The Coupled Model Intercomparison Project, Phase 5.
"""
struct CMIP5 <: CMIPphase end
"""
CMIP6 <: CMIPphase
The Coupled Model Intercomparison Project, Phase 6.
"""
struct CMIP6 <: CMIPphase end
"""
ClimateScenario
Abstract supertype for scenarios used in [`CMIPphase`](@ref) models.
"""
abstract type ClimateScenario end
"""
RepresentativeConcentrationPathway
Abstract supertype for Representative Concentration Pathways (RCPs) for [`CMIP5`](@ref).
Subtypes are: `RCP26`, `RCP45`, `RCP60`, `RCP85`
"""
abstract type RepresentativeConcentrationPathway <: ClimateScenario end
struct RCP26 <: RepresentativeConcentrationPathway end
struct RCP45 <: RepresentativeConcentrationPathway end
struct RCP60 <: RepresentativeConcentrationPathway end
struct RCP85 <: RepresentativeConcentrationPathway end
"""
SharedSocioeconomicPathway
Abstract supertype for Shared Socio-economic Pathways (SSPs) for [`CMIP6`](@ref).
Subtypes are: `SSP126`, `SSP245`, SSP370`, SSP585`
"""
abstract type SharedSocioeconomicPathway <: ClimateScenario end
struct SSP126 <: SharedSocioeconomicPathway end
struct SSP245 <: SharedSocioeconomicPathway end
struct SSP370 <: SharedSocioeconomicPathway end
struct SSP585 <: SharedSocioeconomicPathway end
"""
Future{<:RasterDataSet,<:CMIPphase,<:ClimateModel,<:ClimateScenario}
Future climate datasets specified with a dataset, phase, model, and scenario.
## Type Parameters
#### `RasterDataSet`
Currently [`BioClim`](@ref) and [`Climate`](@ref) are implemented
for the [`CHELSA`](@ref) data source.
#### `CMIPphase`
Can be either [`CMIP5`](@ref) or [`CMIP6`](@ref).
#### `ClimateModel`
Climate models can be chosen from:
`ACCESS1`, `BNUESM`, `CCSM4`, `CESM1BGC`, `CESM1CAM5`, `CMCCCMS`, `CMCCCM`,
`CNRMCM5`, `CSIROMk3`, `CanESM2`, `FGOALS`, `FIOESM`, `GFDLCM3`, `GFDLESM2G`,
`GFDLESM2M`, `GISSE2HCC`, `GISSE2H`, `GISSE2RCC`, `GISSE2R`, `HadGEM2AO`,
`HadGEM2CC`, `IPSLCM5ALR`, `IPSLCM5AMR`, `MIROCESMCHEM`, `MIROCESM`, `MIROC5`,
`MPIESMLR`, `MPIESMMR`, `MRICGCM3`, `MRIESM1`, `NorESM1M`, `BCCCSM1`, `Inmcm4`,
`BCCCSM2MR`, `CNRMCM61`, `CNRMESM21`, `CanESM5`, `MIROCES2L`, `MIROC6` for CMIP5;
`UKESM`, `MPIESMHR` `IPSLCM6ALR` `MRIESM2`, `GFDLESM4` for `CMIP6`.
#### `ClimateScenario`
CMIP5 Climate scenarios are all [`RepresentativeConcentrationPathway`](@ref)
and can be chosen from: `RCP26`, `RCP45`, `RCP60`, `RCP85`
CMIP6 Climate scenarios are all [`SharedSocioeconomicPathway`](@ref) and
can be chosen from: `SSP126`, `SSP245`, SSP370`, SSP585`
## Example
```jldoctest future
using RasterDataSources
dataset = Future{BioClim, CMIP5, BNUESM, RCP45}
# output
Future{BioClim, CMIP5, BNUESM, RCP45}
```
Currently `Future` is only implented for `CHELSA`
```jldoctest future
datasource = CHELSA{Future{BioClim, CMIP5, BNUESM, RCP45}}
```
"""
struct Future{D<:RasterDataSet,C<:CMIPphase,M<:ClimateModel,S<:ClimateScenario} end
_dataset(::Type{<:Future{D}}) where D = D
_phase(::Type{<:Future{<:Any,P}}) where P = P
_model(::Type{<:Future{<:Any,<:Any,M}}) where M = M
_scenario(::Type{<:Future{<:Any,<:Any,<:Any,S}}) where S = S
|
module PQ.FFI.Types
import Generics.Derive
%default total
%language ElabReflection
--------------------------------------------------------------------------------
-- ConnStatusType
--------------------------------------------------------------------------------
||| `ConnStatusType` from `libpq-fe.h` but without the
||| `CONNECTION_` prefix.
public export
data ConnStatusType =
OK
| BAD
| STARTED
| MADE
| AWAITING_RESPONSE
| AUTH_OK
| SETENV
| SSL_STARTUP
| NEEDED
| CHECK_WRITABLE
| CONSUME
| GSS_STARTUP
| CHECK_TARGET
| CONN_STATUS_OTHER Bits8
%runElab derive "ConnStatusType" [Generic,Meta,Show,Eq,Ord]
namespace ConnStatusType
public export
fromBits8 : Bits8 -> ConnStatusType
fromBits8 0 = OK
fromBits8 1 = BAD
fromBits8 2 = STARTED
fromBits8 3 = MADE
fromBits8 4 = AWAITING_RESPONSE
fromBits8 5 = AUTH_OK
fromBits8 6 = SETENV
fromBits8 7 = SSL_STARTUP
fromBits8 8 = NEEDED
fromBits8 9 = CHECK_WRITABLE
fromBits8 10 = CONSUME
fromBits8 11 = GSS_STARTUP
fromBits8 12 = CHECK_TARGET
fromBits8 n = CONN_STATUS_OTHER n
--------------------------------------------------------------------------------
-- ExecStatusType
--------------------------------------------------------------------------------
public export
data ExecStatusType =
EMPTY_QUERY
| COMMAND_OK
| TUPLES_OK
| COPY_OUT
| COPY_IN
| BAD_RESPONSE
| NONFATAL_ERROR
| FATAL_ERROR
| COPY_BOTH
| SINGLE_TUPLE
| EXEC_STATUS_OTHER Bits8
%runElab derive "ExecStatusType" [Generic,Meta,Show,Eq,Ord]
namespace ExecStatusType
public export
fromBits8 : Bits8 -> ExecStatusType
fromBits8 0 = EMPTY_QUERY
fromBits8 1 = COMMAND_OK
fromBits8 2 = TUPLES_OK
fromBits8 3 = COPY_OUT
fromBits8 4 = COPY_IN
fromBits8 5 = BAD_RESPONSE
fromBits8 6 = NONFATAL_ERROR
fromBits8 7 = FATAL_ERROR
fromBits8 8 = COPY_BOTH
fromBits8 9 = SINGLE_TUPLE
fromBits8 n = EXEC_STATUS_OTHER n
--------------------------------------------------------------------------------
-- Errors
--------------------------------------------------------------------------------
public export
data SQLError : Type where
ConnectionError : (type : ConnStatusType) -> (msg : String) -> SQLError
ExecError : (type : ExecStatusType) -> (msg : String) -> SQLError
QueryError : (expectedNumerOfColumns : Bits32)
-> (numberOfColumns : Bits32)
-> SQLError
ReadError : (name : String)
-> (row : Bits32)
-> (column : Bits32)
-> (value : String)
-> SQLError
%runElab derive "SQLError" [Generic,Meta,Show,Eq]
|
library(psych)
region_cells_BE <- read.csv('../data/train_BE/region_cells.csv')
subset_BE <- region_cells_BE[which(region_cells_BE$density>0 & region_cells_BE$density<30),]
biserial(region_cells_BE$density, region_cells_BE$hasstop) # 0.1756958
biserial(subset_BE$density, subset_BE$hasstop) # 0.4397582
# Outliers distort the correlation a lot!
# We only take a subset_BE of the data, with which we get a correlation of 0.4397582
boxplot(density~hasstop, data=subset_BE)
region_cells_NL <- read.csv('../data/train_NL/region_cells.csv')
subset_NL <- region_cells_NL[which(region_cells_NL$density>0 & region_cells_NL$density<6.3),]
biserial(region_cells_NL$density, region_cells_NL$hasstop) # 0.8780911
biserial(subset_NL$density, subset_NL$hasstop) # 0.4599671
# Outliers distort the correlation a lot!
# We only take a subset_NL of the data, with which we get a correlation of 0.4397582
boxplot(density~hasstop, data=subset_NL) |
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝ : Monoid M
⊢ ∀ (b : M), 1 • b = b
[PROOFSTEP]
simp only [units_smul_def, ofConjAct_one, Units.val_one, one_mul, inv_one, mul_one, forall_const]
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝ : Monoid M
⊢ ∀ (x y : ConjAct Mˣ) (b : M), (x * y) • b = x • y • b
[PROOFSTEP]
simp only [units_smul_def]
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝ : Monoid M
⊢ ∀ (x y : ConjAct Mˣ) (b : M),
↑(↑ofConjAct (x * y)) * b * ↑(↑ofConjAct (x * y))⁻¹ =
↑(↑ofConjAct x) * (↑(↑ofConjAct y) * b * ↑(↑ofConjAct y)⁻¹) * ↑(↑ofConjAct x)⁻¹
[PROOFSTEP]
simp only [map_mul, Units.val_mul, mul_assoc, mul_inv_rev, forall_const, forall]
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝ : Monoid M
⊢ ∀ (r : ConjAct Mˣ) (x y : M), r • (x * y) = r • x * r • y
[PROOFSTEP]
simp only [units_smul_def]
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝ : Monoid M
⊢ ∀ (r : ConjAct Mˣ) (x y : M),
↑(↑ofConjAct r) * (x * y) * ↑(↑ofConjAct r)⁻¹ =
↑(↑ofConjAct r) * x * ↑(↑ofConjAct r)⁻¹ * (↑(↑ofConjAct r) * y * ↑(↑ofConjAct r)⁻¹)
[PROOFSTEP]
simp only [mul_assoc, Units.inv_mul_cancel_left, forall_const, forall]
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝ : Monoid M
⊢ ∀ (r : ConjAct Mˣ), r • 1 = 1
[PROOFSTEP]
simp [units_smul_def, mul_one, Units.mul_inv, forall, forall_const]
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝³ : Monoid M
inst✝² : SMul α M
inst✝¹ : SMulCommClass α M M
inst✝ : IsScalarTower α M M
a : α
um : ConjAct Mˣ
m : M
⊢ a • um • m = um • a • m
[PROOFSTEP]
rw [units_smul_def, units_smul_def, mul_smul_comm, smul_mul_assoc]
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝ : Semiring R
src✝ : MulDistribMulAction (ConjAct Rˣ) R := unitsMulDistribMulAction
⊢ ∀ (a : ConjAct Rˣ), a • 0 = 0
[PROOFSTEP]
simp only [units_smul_def, mul_zero, zero_mul, forall, forall_const]
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝ : Semiring R
src✝ : MulDistribMulAction (ConjAct Rˣ) R := unitsMulDistribMulAction
⊢ ∀ (a : ConjAct Rˣ) (x y : R), a • (x + y) = a • x + a • y
[PROOFSTEP]
simp only [units_smul_def]
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝ : Semiring R
src✝ : MulDistribMulAction (ConjAct Rˣ) R := unitsMulDistribMulAction
⊢ ∀ (a : ConjAct Rˣ) (x y : R),
↑(↑ofConjAct a) * (x + y) * ↑(↑ofConjAct a)⁻¹ =
↑(↑ofConjAct a) * x * ↑(↑ofConjAct a)⁻¹ + ↑(↑ofConjAct a) * y * ↑(↑ofConjAct a)⁻¹
[PROOFSTEP]
simp only [mul_add, add_mul, forall_const, forall]
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝ : GroupWithZero G₀
⊢ ∀ (b : G₀), 1 • b = b
[PROOFSTEP]
simp only [smul_def]
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝ : GroupWithZero G₀
⊢ ∀ (b : G₀), ↑ofConjAct 1 * b * (↑ofConjAct 1)⁻¹ = b
[PROOFSTEP]
simp only [map_one, one_mul, inv_one, mul_one, forall_const]
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝ : GroupWithZero G₀
⊢ ∀ (x y : ConjAct G₀) (b : G₀), (x * y) • b = x • y • b
[PROOFSTEP]
simp only [smul_def]
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝ : GroupWithZero G₀
⊢ ∀ (x y : ConjAct G₀) (b : G₀),
↑ofConjAct (x * y) * b * (↑ofConjAct (x * y))⁻¹ =
↑ofConjAct x * (↑ofConjAct y * b * (↑ofConjAct y)⁻¹) * (↑ofConjAct x)⁻¹
[PROOFSTEP]
simp only [map_mul, mul_assoc, mul_inv_rev, forall_const, forall]
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝³ : GroupWithZero G₀
inst✝² : SMul α G₀
inst✝¹ : SMulCommClass α G₀ G₀
inst✝ : IsScalarTower α G₀ G₀
a : α
ug : ConjAct G₀
g : G₀
⊢ a • ug • g = ug • a • g
[PROOFSTEP]
rw [smul_def, smul_def, mul_smul_comm, smul_mul_assoc]
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝ : DivisionRing K
src✝ : MulAction (ConjAct K) K := mulAction₀
⊢ ∀ (a : ConjAct K), a • 0 = 0
[PROOFSTEP]
simp only [smul_def]
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝ : DivisionRing K
src✝ : MulAction (ConjAct K) K := mulAction₀
⊢ ∀ (a : ConjAct K), ↑ofConjAct a * 0 * (↑ofConjAct a)⁻¹ = 0
[PROOFSTEP]
simp only [mul_zero, zero_mul, forall, forall_const]
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝ : DivisionRing K
src✝ : MulAction (ConjAct K) K := mulAction₀
⊢ ∀ (a : ConjAct K) (x y : K), a • (x + y) = a • x + a • y
[PROOFSTEP]
simp only [smul_def]
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝ : DivisionRing K
src✝ : MulAction (ConjAct K) K := mulAction₀
⊢ ∀ (a : ConjAct K) (x y : K),
↑ofConjAct a * (x + y) * (↑ofConjAct a)⁻¹ =
↑ofConjAct a * x * (↑ofConjAct a)⁻¹ + ↑ofConjAct a * y * (↑ofConjAct a)⁻¹
[PROOFSTEP]
simp only [mul_add, add_mul, forall_const, forall]
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝ : Group G
⊢ ∀ (b : G), 1 • b = b
[PROOFSTEP]
simp only [smul_def, ofConjAct_one, one_mul, inv_one, mul_one, forall_const]
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝ : Group G
⊢ ∀ (x y : ConjAct G) (b : G), (x * y) • b = x • y • b
[PROOFSTEP]
simp only [smul_def]
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝ : Group G
⊢ ∀ (x y : ConjAct G) (b : G),
↑ofConjAct (x * y) * b * (↑ofConjAct (x * y))⁻¹ =
↑ofConjAct x * (↑ofConjAct y * b * (↑ofConjAct y)⁻¹) * (↑ofConjAct x)⁻¹
[PROOFSTEP]
simp only [map_mul, mul_assoc, mul_inv_rev, forall_const, forall]
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝ : Group G
⊢ ∀ (r : ConjAct G) (x y : G), r • (x * y) = r • x * r • y
[PROOFSTEP]
simp only [smul_def]
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝ : Group G
⊢ ∀ (r : ConjAct G) (x y : G),
↑ofConjAct r * (x * y) * (↑ofConjAct r)⁻¹ =
↑ofConjAct r * x * (↑ofConjAct r)⁻¹ * (↑ofConjAct r * y * (↑ofConjAct r)⁻¹)
[PROOFSTEP]
simp only [mul_assoc, inv_mul_cancel_left, forall_const, forall]
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝ : Group G
⊢ ∀ (r : ConjAct G), r • 1 = 1
[PROOFSTEP]
simp only [smul_def, mul_one, mul_right_inv, forall, forall_const]
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝³ : Group G
inst✝² : SMul α G
inst✝¹ : SMulCommClass α G G
inst✝ : IsScalarTower α G G
a : α
ug : ConjAct G
g : G
⊢ a • ug • g = ug • a • g
[PROOFSTEP]
rw [smul_def, smul_def, mul_smul_comm, smul_mul_assoc]
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝ : Group G
⊢ fixedPoints (ConjAct G) G = ↑(center G)
[PROOFSTEP]
ext x
[GOAL]
case h
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝ : Group G
x : G
⊢ x ∈ fixedPoints (ConjAct G) G ↔ x ∈ ↑(center G)
[PROOFSTEP]
simp [mem_center_iff, smul_def, mul_inv_eq_iff_eq_mul]
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝ : Group G
g h : G
⊢ g ∈ orbit (ConjAct G) h ↔ IsConj g h
[PROOFSTEP]
rw [isConj_comm, isConj_iff, mem_orbit_iff]
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝ : Group G
g h : G
⊢ (∃ x, x • h = g) ↔ ∃ c, c * h * c⁻¹ = g
[PROOFSTEP]
rfl
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝ : Group G
g h : G
⊢ Setoid.Rel (orbitRel (ConjAct G) G) g h = IsConj g h
[PROOFSTEP]
rw [orbitRel_apply, mem_orbit_conjAct]
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝¹ inst✝ : Group G
g : G
⊢ orbit (ConjAct G) g = ConjClasses.carrier (ConjClasses.mk g)
[PROOFSTEP]
ext h
[GOAL]
case h
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝¹ inst✝ : Group G
g h : G
⊢ h ∈ orbit (ConjAct G) g ↔ h ∈ ConjClasses.carrier (ConjClasses.mk g)
[PROOFSTEP]
rw [ConjClasses.mem_carrier_iff_mk_eq, ConjClasses.mk_eq_mk_iff_isConj, mem_orbit_conjAct]
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝¹ : Group G
H : Subgroup G
inst✝ : Normal H
g : G
h : { x // x ∈ H }
⊢ ↑(↑(MulEquiv.symm (↑MulAut.conjNormal g)) h) = g⁻¹ * ↑h * g
[PROOFSTEP]
change _ * _⁻¹⁻¹ = _
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝¹ : Group G
H : Subgroup G
inst✝ : Normal H
g : G
h : { x // x ∈ H }
⊢ ↑ofConjAct (↑(MulEquiv.toMonoidHom toConjAct) g)⁻¹ * ↑h * (↑(MulEquiv.toMonoidHom toConjAct) g)⁻¹⁻¹ = g⁻¹ * ↑h * g
[PROOFSTEP]
rw [inv_inv]
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K : Type u_6
inst✝¹ : Group G
H : Subgroup G
inst✝ : Normal H
g : G
h : { x // x ∈ H }
⊢ ↑ofConjAct (↑(MulEquiv.toMonoidHom toConjAct) g)⁻¹ * ↑h * ↑(MulEquiv.toMonoidHom toConjAct) g = g⁻¹ * ↑h * g
[PROOFSTEP]
rfl
[GOAL]
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K✝ : Type u_6
inst✝ : Group G
H : Subgroup G
hH : Normal H
K : Subgroup { x // x ∈ H }
h : Characteristic K
a : G
ha : a ∈ map (Subgroup.subtype H) K
b : G
⊢ b * a * b⁻¹ ∈ map (Subgroup.subtype H) K
[PROOFSTEP]
obtain ⟨a, ha, rfl⟩ := ha
[GOAL]
case intro.intro
α : Type u_1
M : Type u_2
G : Type u_3
G₀ : Type u_4
R : Type u_5
K✝ : Type u_6
inst✝ : Group G
H : Subgroup G
hH : Normal H
K : Subgroup { x // x ∈ H }
h : Characteristic K
b : G
a : { x // x ∈ H }
ha : a ∈ ↑K
⊢ b * ↑(Subgroup.subtype H) a * b⁻¹ ∈ map (Subgroup.subtype H) K
[PROOFSTEP]
exact K.apply_coe_mem_map H.subtype ⟨_, (SetLike.ext_iff.mp (h.fixed (MulAut.conjNormal b)) a).mpr ha⟩
|
lemma AE_I': "N \<in> null_sets M \<Longrightarrow> {x\<in>space M. \<not> P x} \<subseteq> N \<Longrightarrow> (AE x in M. P x)" |
from flask.helpers import make_response
from slugify.slugify import slugify
from mljob.jobs import path_friendly_jobname, launch_job, retrieve_job_folder,retrieve_results,job_info_list,valid_results_filename,results_file_dir,job_exists,retrieve_job_info,generate_job_id, job_status_codes, retrieve_job_outputs
from werkzeug.exceptions import InternalServerError
from flask import request, render_template, jsonify, session, redirect, url_for, flash, send_file, Markup, abort,send_from_directory
from app.forms import ValidateForm, JobLookupForm
from app import app
from mljob import geneplexus # models
geneplexus.data_path = app.config.get("DATA_PATH")
import os
import numpy as np
import pandas as pd
@app.route("/", methods=['GET'])
@app.route("/index", methods=['GET'])
def index():
if request.method == 'GET':
session_args = create_sidenav_kwargs()
return render_template("index.html", **session_args)
@app.route("/geneset", methods=['GET'])
def geneset():
if request.method == 'GET':
session_args = create_sidenav_kwargs()
return render_template("validation.html", **session_args)
@app.route("/about", methods=['GET'])
def about():
if request.method == 'GET':
session_args = create_sidenav_kwargs()
return render_template("about.html", **session_args)
@app.route("/help", methods=['GET'])
def help():
if request.method == 'GET':
session_args = create_sidenav_kwargs()
return render_template("help.html", **session_args)
@app.route("/contact", methods=['GET'])
def contact():
session_args = create_sidenav_kwargs()
return render_template("contact.html", **session_args)
@app.route("/jobs/", methods=['GET', 'POST'])
def jobs():
""" list jobs in session, show form, or show message from submit"""
form = JobLookupForm(request.form)
jobname = form.jobname.data
if request.method == 'POST' and form.lookup.data:
if retrieve_job_folder(jobname, app.config):
return(redirect(url_for('job',jobname=jobname)))
else:
flash(f"Sorry, the job '{jobname}'' was not found")
jobnames = []
joblist = {}
if 'jobs' in session:
jobnames = session['jobs']
# jobnames = list_all_jobs(app.config.get('JOB_PATH'))
if jobnames:
joblist = job_info_list(jobnames, app.config)
session_args = create_sidenav_kwargs()
return render_template("jobs.html", jobs = jobnames,
joblist = joblist,
form=form, **session_args)
def html_output_table(df, id = "", row_limit = 500):
""" given a data frame, create an html output table for job template for a subset of top rows.
This assumes the data frame is already in the correct sort order
returns : string of html or empty string if not a data frame
"""
#TODO this needs to go away and we need a jinja template macro to build tables instead
# this is formattibng code which does not belong in the view or anywhere execpt for a template
if isinstance(df, pd.DataFrame):
html_table = df.head(row_limit).to_html(index=False, classes="table table-striped table-bordered width:100%",table_id = id )
return(html_table)
else:
#TODO log that this is not a dataframe
return("")
@app.route("/jobs/<jobname>", methods=['GET'])
def job(jobname):
""" show info about job: results if there are some but otherwise basic job information"""
# sanitize. if this is an actual jobname this will be idempotent
jobname = path_friendly_jobname(jobname)
#TODO check valid job and 404 if not
if not job_exists(jobname, app.config):
abort(404)
job_info = retrieve_job_info(jobname, app.config)
if job_info and job_info['has_results']:
job_output = retrieve_job_outputs(jobname, app.config)
else:
job_output = {}
return render_template("jobresults.html",
jobexists = job_exists(jobname, app.config),
jobname=jobname,
job_info = job_info,
job_output = job_output)
@app.route("/jobs/<jobname>", methods = ["POST"])
def update_job(jobname):
""" update the job info and possibly notify of new jobs status. Used by external job runner. """
request_data = request.get_json()
job_status = request_data.get('status')
# sanitize. if this is an actual jobname this will be idempotent
jobname = path_friendly_jobname(jobname)
# TODO read the data that was posted! to see the event code
job_config = retrieve_job_info(jobname, app.config)
job_config['job_url'] = url_for('job', jobname=jobname ,_external=True)
notifyaddress = job_config.get('notifyaddress')
if notifyaddress:
if job_status_codes.get(job_status ).lower() == "completed":
resp = app.notifier.notify_completed(job_config)
else:
resp = app.notifier.notify(notifyaddress, job_config, job_status)
app.logger.info(f"job completed email initiated to {job_config['notifyaddress']} with response {resp}")
return {'notification response': resp}, resp
else:
return {'notifiation response': 202}, 202
@app.route("/jobs/<jobname>/results",methods=['GET'])
def jobresults_content(jobname):
""" read the results into memory and return """
results_content = retrieve_results(jobname, app.config)
if results_content:
return(results_content) # or in future, send this html to a template wrapper
else:
return(f'<html><body><h3 style="padding-top:50px"> No results yet for the job "{jobname}"</h3></body><html>')
# @app.route("/jobs/<jobname>/job_output",methods=['GET'])
# def jobresults_content(jobname):
# """ get all the ouptut from the job and render tables and visualization """
# if not job_exists(jobname, app.config):
# flash(f"No job exists {jobname}")
# redirect('/', code=404)
# # dictionary of stuff
# job_info = retrieve_job_info(jobname, app.config)
# return render_template("job_output.html", jobname=jobname, job_info = job_info,
# probs_table=job_info['df_probs'].head(row_limit).to_html(index=False, classes='table table-striped table-bordered" style="width: 100%;" id = "probstable"'),
# go_table=job_info['df_GO'].head(row_limit).to_html(index=False,classes='table table-striped table-bordered nowrap" style="width: 100%;" id = "gotable"'),
# dis_table=job_info['df_dis'].head(row_limit).to_html(index=False, classes='table table-striped table-bordered" style="width: 100%;" id = "distable"'),
# validate_results=job_info['df_convert_out_subset'].head(row_limit).to_html(index=False,classes='table table-striped table-bordered" style="width: 100%;" id = "validateresults"'),
# graph=job_info['graph'],
# **session_args )
# # get all of this from job_info dictionary
# # network=net_type,
# # features=features,
# # negativeclass=GSC,
# # avgps=avgps,
# # input_count=input_count,
# # positive_genes=positive_genes,
# download results file
@app.route("/jobs/<jobname>/results/download/<results_file_name>",methods=['GET'])
def jobresults_download(jobname,results_file_name):
"""get the contents of one of the results outputs and iniate a download. If no file name or results type is sent
as a parameter, by default just sent the rendered html.
"""
# sanitize the filename using a method for job module
results_file_name = valid_results_filename(results_file_name)
# results_file_name = valid_results_filename(request.values.get('resultsfile', ''))
# if there is any filename left after sanitizing...
if ( results_file_name ):
# retrieve the file_path, or nothing if the job or file does not exist
results_directory = results_file_dir(jobname, app.config,results_file_name)
if(results_directory):
return send_from_directory(results_directory, results_file_name, as_attachment=True)
# nothing found, return 404
abort(404)
@app.route("/results", methods=['GET','POST'])
def results():
if request.method == 'GET':
session['genes'] = request.form['genes']
return render_template("results.html")
@app.route("/cleargenes", methods=['POST'])
def cleargenes():
session.pop('genes', None)
session.pop('pos', None)
session.pop('df_convert_out', None)
session.pop('table_summary', None)
session.pop('jobid', None)
@app.route("/validate", methods=['GET','POST'])
def validate():
form = ValidateForm()
app.logger.info('validate button')
string = request.form['genesInput'] # read in the file
# convert the FileStorage object to a string
#string = f.stream.read().decode("UTF8")
# remove any single quotes if they exist
no_quotes = string.translate(str.maketrans({"'": None}))
input_genes_list = no_quotes.splitlines() # turn into a list
input_genes_list = list(filter(lambda x: x != '', input_genes_list))
if len(input_genes_list) == 0:
flash("You need to input at least one positive gene", "error")
return redirect('index')
input_genes_upper = np.array([item.upper() for item in input_genes_list])
# remove any whitespace
session['genes'] = [x.strip(' ') for x in input_genes_upper]
input_genes = session['genes']
# run all the components of the model and pass to the results form
convert_IDs, df_convert_out = geneplexus.intial_ID_convert(input_genes)
jobid = generate_job_id()
form.jobid.data = jobid
df_convert_out, table_summary, input_count = geneplexus.make_validation_df(df_convert_out)
pos = min([ sub['PositiveGenes'] for sub in table_summary ])
session['jobid'] = jobid
session['pos'] = pos
session['df_convert_out'] = df_convert_out.to_dict()
session['table_summary'] = table_summary
return redirect('geneset')
#return render_template("validation.html", valid_form=form, pos=pos, table_summary=table_summary, existing_genes=input_genes,
# validate_table=df_convert_out.to_html(index=False,
# classes='table table-striped table-bordered" id = "validatetable'))
@app.route('/uploads/<path:filename>', methods=['GET', 'POST'])
def uploads(filename):
# Appending app path to upload folder path within app root folder
uploads = os.path.join(app.root_path, 'static', filename)
# Returning file from appended path
return send_file(uploads, as_attachment=True)
@app.route('/get_slugified_text', methods=['POST'])
def get_slugified_text():
prefix = request.get_json()['prefix']
clean_text = slugify(prefix.lower())
return jsonify(success=True, clean_text=clean_text, prefix_too_long=(len(clean_text) > app.config['MAX_PREFIX_LENGTH']), too_long_by=(len(clean_text) - app.config['MAX_PREFIX_LENGTH']))
@app.route("/run_model", methods=['POST'])
def run_model():
"""post-only route to run model locally or trigger cloud, depending on button """
form = ValidateForm()
# 'genes' exists as a session variable, use that data for subsequent requests
# if it doesn't, no data has been loaded yet so get the data from a selected file
if 'genes' in session:
# save session data to variable
input_genes = session['genes']
# remove the current genelist from session
# why remove the geneset from session -- what if someone wants to run a second job with same geneset?
#session.pop('genes')
else: # no genes in session
# if genes are not in the session, 500 server error? read in genes?
flash("No geneset seems to be selected - please select a geneset to run the model", "error")
return redirect('index')
# grab the assigned job ID
jobid = form.jobid.data
# Regenerate JobID in the session (not the form)
# avoid collisions if someone immediately resubmits a job
session['jobid'] = generate_job_id()
# if the optional prefix has been added, concatenate
# the two fields together. Otherwise the jobname is the jobid
if form.prefix.data != '':
friendly_prefix = slugify(form.prefix.data.lower())
if len(friendly_prefix) > app.config['MAX_PREFIX_LENGTH']:
friendly_prefix = friendly_prefix[:app.config['MAX_PREFIX_LENGTH']]
jobname = f'{friendly_prefix}-{jobid}'
else:
jobname = jobid
jobname = path_friendly_jobname(jobname)
# this means someone clicked the form to run the batch job.
if form.runbatch.data :
# create dictionary for easy parameter passing
job_config = {
'net_type' : form.network.data,
'features' : form.features.data,
'GSC': form.negativeclass.data,
'jobname': jobname,
'jobid': jobid,
'job_url': url_for('job', jobname=jobname ,_external=True),
'notifyaddress': '' # default is empty string for notification email
}
if form.notifyaddress.data != '': # user has supplied an email address
# check if the email supplied matched basic pattern
if form.notifyaddress.validate(form):
job_config['notifyaddress'] = form.notifyaddress.data
else:
flash("The job notification email address you provided is not a valid email. No job notification will be sent", category = "error")
print("launching job with job config =")
print(job_config)
job_response = launch_job(input_genes, job_config, app.config)
app.logger.info(f"job {job_config['jobid']} launched with response {job_response}")
if 'jobs' not in session or session['jobs'] is None:
sessionjobs = []
else:
sessionjobs = session['jobs']
sessionjobs.append(jobname)
session['jobs'] = sessionjobs
job_submit_message = f"Job {jobname} submitted! The completed job will be available on <a href='{job_config['job_url'] }'>{job_config['job_url']}</a>"
if job_config.get('notifyaddress'):
email_response = app.notifier.notify_accepted(job_config) # notify(job_url, job_email = job_config['notifyaddress'], config = app.config)
app.logger.info(f"email initiated to {job_config['notifyaddress']} with response {email_response}")
job_submit_message = job_submit_message + f" and notification sent to {job_config['notifyaddress']}"
flash(Markup(job_submit_message), category = 'success')
return redirect('jobs')
# this option is for testing, and not usually available as a button on the website
# if form.runlocal.data :
# # this runs the model on the spot and simply returns the results as HTML file
# app.logger.info('running model, jobname %s', jobname)
# results_html = geneplexus.run_and_render(input_genes, net_type, features, GSC, jobname)
# app.logger.info('model complete, rendering template')
# return(results_html)
# we reach here if the submit button value is neither possibility
return("invalid form data ")
@app.route("/clearinput", methods=['GET','POST'])
def clearinput():
try:
session.pop('genes')
except KeyError:
pass
return jsonify(success=True)
@app.route("/postgenes", methods=['GET','POST'])
def postgenes():
try:
session.pop('genes')
except KeyError:
pass
genes = request.form['genes']
no_quotes = genes.translate(str.maketrans({"'": None})) # remove any single quotes if they exist
# input_genes_list = no_quotes.split(",") # turn into a list
input_genes_list = no_quotes.splitlines() # turn into a list
input_genes_upper = np.array([item.upper() for item in input_genes_list])
session['genes'] = [x.strip(' ') for x in input_genes_upper] # remove any whitespace
return jsonify(success=True, filename=None)
@app.route("/uploadgenes", methods=['POST'])
def uploadgenes():
# remove genes from session
session.pop('genes', None)
file = request.files['formData'].filename
try:
string = request.files['formData'].stream.read().decode("UTF8")
no_quotes = string.translate(str.maketrans({"'": None}))
input_genes_list = no_quotes.splitlines() # turn into a list
input_genes_upper = np.array([item.upper() for item in input_genes_list])
# remove any whitespace
toReturn = [x.strip(' ') for x in input_genes_upper]
return jsonify(success=True, data=toReturn)
except Exception as e:
print(e)
return jsonify(success=False, filename=None)
@app.errorhandler(InternalServerError)
def handle_500(e):
original = getattr(e, "original_exception", None)
if original is None:
# direct 500 error, such as abort(500)
return render_template("/redirects/500.html"), 500
# wrapped unhandled error
return render_template("/redirects/500_unhandled.html", e=original), 500
@app.context_processor
def inject_template_scope():
injections = dict()
def cookies_check():
value = request.cookies.get('cookie_consent')
return value == 'true'
injections.update(cookies_check=cookies_check)
return injections
def create_sidenav_kwargs():
if 'genes' in session and \
'jobid' in session and \
'pos' in session and \
'df_convert_out' in session and \
'table_summary' in session:
form = ValidateForm()
form.jobid.data = session['jobid']
validate_df = pd.DataFrame(session['df_convert_out'])[['Original ID', 'Entrez ID', 'In BioGRID?', 'In STRING?', 'In STRING-EXP?', 'In GIANT-TN?']]
validate_html = validate_df.to_html(index=False,
classes='table table-striped table-bordered" id = "validatetable')
return {'existing_genes': session['genes'], 'pos': session['pos'],
'table_summary': session['table_summary'], 'validate_table': validate_html, 'valid_form': form,
'prefix_limit': app.config['MAX_PREFIX_LENGTH']}
return {} |
-- Pruebas de (x + y) + z = (x + z) + y
-- ====================================
-- ----------------------------------------------------
-- Ej. 1. Demostrar que para todo x, y, z en ℤ se tiene
-- (x + y) + z = (x + z) + y
-- ----------------------------------------------------
import tactic
import data.int.basic
variables (x y z : ℤ)
-- 1ª demostración
example : (x + y) + z = (x + z) + y :=
calc
(x + y) + z = x + (y + z) : add_assoc x y z
... = x + (z + y) : eq.subst (add_comm y z) rfl
... = (x + z) + y : eq.symm (add_assoc x z y)
-- 2ª demostración
example : (x + y) + z = (x + z) + y :=
calc
(x + y) + z = x + (y + z) : by rw add_assoc
... = x + (z + y) : by rw [add_comm y z]
... = (x + z) + y : by rw add_assoc
-- 3ª demostración
example : (x + y) + z = (x + z) + y :=
begin
rw add_assoc,
rw add_comm y z,
rw add_assoc,
end
example : (x + y) + z = (x + z) + y :=
begin
rw [add_assoc, add_comm y z, add_assoc],
end
-- 4ª demostración
example : (x + y) + z = (x + z) + y :=
by rw [add_assoc, add_comm y z, add_assoc]
-- 5ª demostración
example : (x + y) + z = (x + z) + y :=
-- by library_search
add_right_comm x y z
-- 6ª demostración
example : (x + y) + z = (x + z) + y :=
-- by hint
by omega
-- 7ª demostración
example : (x + y) + z = (x + z) + y :=
by linarith
-- 8ª demostración
example : (x + y) + z = (x + z) + y :=
by nlinarith
-- 9ª demostración
example : (x + y) + z = (x + z) + y :=
by ring
-- 10ª demostración
example : (x + y) + z = (x + z) + y :=
by finish
|
Loves kitties, horsies, collects tattoos, picks brains, queer radical feminist. Lives with the Crazy Cat Lady Users/MarieBoisvert Marie Boisvert.
Davis semilocal since...well, birth. Went to UC Davis back in the midtolate 90s.
Friends with REAL townies such as Tyson Nichols, Sarah Bloch, Dan Thatcher.
|
The product of a negative number and a positive number is negative. |
module Main
import Sixel
partial
main : IO ()
main = do
Right decoder <- MkDecoder
| Left error => putStrLn getAdditionalMessage
Right _ <- setOpt decoder OptFlagInput "lena512.sixel"
| Left error => putStrLn getAdditionalMessage
Right _ <- setOpt decoder OptFlagOutput "lena512.bmp"
| Left error => putStrLn getAdditionalMessage
Right _ <- decode decoder
| Left error => putStrLn getAdditionalMessage
pure ()
|
lemma tendsto_of_real_iff: "((\<lambda>x. of_real (f x) :: 'a::real_normed_div_algebra) \<longlongrightarrow> of_real c) F \<longleftrightarrow> (f \<longlongrightarrow> c) F" |
\documentclass{beamer}
\usetheme{CambridgeUS}
\usepackage[utf8]{inputenc}
\usepackage{xcolor}
\usepackage{minted}
\usepackage{caption}
\captionsetup[figure]{labelformat=empty}% redefines the caption setup of the figures environment in the beamer class.
\usemintedstyle{friendly}
\title[iCLIP data analysis with iCount]
{Analysis of iCLIP data with the iCount python module}
\subtitle{
A short tutorial
}
\author[Tomaž Curk]{
Tomaž Curk\\
\small{[email protected]}
}
\institute[UL FRI]{
University of Ljubljana\\
Faculty of Computer and Information Science
}
\titlegraphic{\includegraphics[height=2cm]{images/ul-fri.png}}
\date[The Crick Institute, 14. 7. 2017]
{The Crick Institute, July 2017}
\newif\ifplacelogo % create a new conditional
\placelogofalse % set it to false
\logo{\ifplacelogo\includegraphics[height=0.8cm]{images/ul-fri.png}\fi}
\begin{document}
\frame{\titlepage}
\section{Background}
\begin{frame}
\frametitle{History and acknowledgements for iCount}
From its start in late 2008, a great number of people contributed to the development of
iCount.
In mid-2016, Jure Zmrzlikar from Genialis helped to improve the code, which is now available on
github.
\begin{itemize}
\item Tomaž Curk
\item Gregor Rot
\item Črtomir Gorup
\item Julian Konig
\item Yoichiro Sugimoto
\item Nejc Haberman
\item Goran Bobojević
\item Jure Zmrzlikar
\item Christian Hauer
\item Matthias Hentze
\item Blaž Zupan
\item Jernej Ule
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{Pipeline}
\begin{figure}
\begin{center}
\includegraphics[width=0.85\linewidth]{images/pipeline.png}
\caption{Main steps in the cross-link mapping and annotation pipeline.}
\end{center}
\end{figure}
\end{frame}
\begin{frame}
\frametitle{Finding cross-linked sites}
\begin{figure}
\begin{center}
\includegraphics[width=0.85\linewidth]{images/mapping.png}
\caption{The most crucial step is site indetification and quantification.}
\end{center}
\end{figure}
\end{frame}
\begin{frame}
\frametitle{The old web interface}
\begin{figure}
\begin{center}
\centering
\includegraphics[width=0.85\linewidth]{images/old_webinterface.png}
\caption{This interface is still in use.\\
It will be replaced soon by an implementation by Genialis.}
\end{center}
\end{figure}
\end{frame}
\begin{frame}
\frametitle{The old iCount - impact}
\begin{itemize}
\item 100+ users
\item 40+ institutions: UCL, MRC LMB, EMBL, mpi-cbg.de, …
\item 2M+ EUR cost of sequencing alone
\item 80+ proteins (8\% of known human RBPs)
\item 5000+ experiments (iCLIP, CLIP, pA-Seq, mRNA-seq,…)
\item 800+ user-defined groupings of experiments
\item 10 species
\item 33000 analyses
\item (Co)authors of over 25 publications using results from iCount.
\end{itemize}
\end{frame}
\section{Today}
\begin{frame}
\frametitle{iCount is available on github!}
\begin{figure}
\begin{center}
\includegraphics[width=0.6\linewidth]{images/github.png}
\caption{http://github.com/tomazc/iCount\\
Comments and PR are welcome!}
\end{center}
\end{figure}
\end{frame}
\section{Tutorial}
\begin{frame}
\frametitle{Tutorial}
\begin{figure}
\begin{center}
\includegraphics[width=0.65\linewidth]{images/tutorial.png}
\caption{http://icount.readthedocs.io/en/latest/tutorial.html}
\end{center}
\end{figure}
\end{frame}
\section{Conclusion}
\placelogotrue
\begin{frame}
\frametitle{Use and contribute to iCount}
\centering
In case of problems, post an issue on github or contact: [email protected]
Welcome to contribute to http://github.com/tomazc/iCount
\end{frame}
\end{document} |
This has multiple meanings. (Yeah, I hate wiki:WikiPedia:TLA TLAs just as much as you do.) You are probably looking for information on one of the following:
Davis Fire Crew
Davis Food CoOp
You might also be looking for UC Davis Fencing Club UC Davis Fencing Club (UCDFC)
This is a Disambiguation disambiguation page a navigational aid which lists other pages that might otherwise share the same title. If an article link referred you here, you might want to go back and fix it to point directly to the intended page.
|
// Copyright (C) by Josh Blum. See LICENSE.txt for licensing information.
#include <gras/factory.hpp>
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include <boost/thread/mutex.hpp>
#include <stdexcept>
#include <iostream>
#include <cstdio>
#include <fstream>
#include <map>
//defined in module loader
std::string get_gras_runtime_include_path(void);
#ifdef HAVE_CLANG
#include <clang/CodeGen/CodeGenAction.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Frontend/CompilerInvocation.h>
#include <clang/Frontend/TextDiagnosticPrinter.h>
#include <clang/Driver/Compilation.h>
#include <clang/Driver/Driver.h>
#include <clang/Driver/ArgList.h>
#endif //HAVE_CLANG
#ifdef HAVE_LLVM
#include <llvm/LLVMContext.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Bitcode/ReaderWriter.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/Support/MemoryBuffer.h>
#include <llvm/ExecutionEngine/JIT.h>
#include <llvm/Support/system_error.h>
#include <llvm/Support/Host.h>
#include <llvm/Support/Program.h>
#include <llvm/Module.h>
#endif //HAVE_LLVM
/***********************************************************************
* Storage for execution engines
**********************************************************************/
#ifdef HAVE_LLVM
struct ExecutionEngineMonitor
{
ExecutionEngineMonitor(void)
{
boost::mutex::scoped_lock l(mutex);
}
~ExecutionEngineMonitor(void)
{
boost::mutex::scoped_lock l(mutex);
for (size_t i = 0; i < ees.size(); i++)
{
ees[i]->runStaticConstructorsDestructors(true);
ees[i].reset();
}
ees.clear();
}
void add(boost::shared_ptr<llvm::ExecutionEngine> ee)
{
boost::mutex::scoped_lock l(mutex);
ee->runStaticConstructorsDestructors(false);
ees.push_back(ee);
}
llvm::LLVMContext &get_context(void)
{
return context;
}
boost::mutex mutex;
llvm::LLVMContext context;
std::vector<boost::shared_ptr<llvm::ExecutionEngine> > ees;
};
static ExecutionEngineMonitor &get_eemon(void)
{
static ExecutionEngineMonitor eemon;
return eemon;
}
#endif //HAVE_LLVM
/***********************************************************************
* Helper function to call a clang compliation -- execs clang
**********************************************************************/
#ifdef HAVE_LLVM
static llvm::Module *call_clang_exe(const std::string &source_file, const std::vector<std::string> &flags)
{
//make up bitcode file path
char bitcode_file[L_tmpnam];
if (std::tmpnam(bitcode_file) == NULL) throw std::runtime_error("GRAS compiler: tmp bitcode file path failed");
//begin command setup
std::vector<std::string> cmd;
llvm::sys::Path clangPath = llvm::sys::Program::FindProgramByName("clang");
cmd.push_back(clangPath.str());
cmd.push_back("-emit-llvm");
//inject source
cmd.push_back("-c");
cmd.push_back("-x");
cmd.push_back("c++");
cmd.push_back(source_file);
//inject output
cmd.push_back("-o");
cmd.push_back(bitcode_file);
//inject args...
BOOST_FOREACH(const std::string &flag, flags)
{
cmd.push_back(flag.c_str());
}
//format command string
std::string command;
BOOST_FOREACH(const std::string &c, cmd)
{
command += c + " ";
}
std::cout << " " << command << std::endl;
const int ret = system(command.c_str());
if (ret != 0)
{
throw std::runtime_error("GRAS compiler: error system exec clang");
}
//readback bitcode for result
std::ifstream bitcode_fstream(bitcode_file);
const std::string bitcode((std::istreambuf_iterator<char>(bitcode_fstream)), std::istreambuf_iterator<char>());
//create a memory buffer from the bitcode
boost::shared_ptr<llvm::MemoryBuffer> buffer(llvm::MemoryBuffer::getMemBuffer(bitcode));
//parse the bitcode into a module
std::string error;
llvm::Module *module = llvm::ParseBitcodeFile(buffer.get(), get_eemon().get_context(), &error);
if (not error.empty()) throw std::runtime_error("GRAS compiler: ParseBitcodeFile " + error);
return module;
}
#endif //HAVE_LLVM
/***********************************************************************
* Helper function to call a clang compliation -- uses clang API
**********************************************************************/
/*
#ifdef HAVE_CLANG
static llvm::Module *call_clang_api(const std::string &source_file, const std::vector<std::string> &flags)
{
//begin command setup
std::vector<const char *> args;
//inject source
args.push_back("-c");
args.push_back("-x");
args.push_back("c++");
args.push_back(source_file.c_str());
//inject args...
BOOST_FOREACH(const std::string &flag, flags)
{
args.push_back(flag.c_str());
}
//http://fdiv.net/2012/08/15/compiling-code-clang-api
// The compiler invocation needs a DiagnosticsEngine so it can report problems
clang::DiagnosticOptions *DiagOpts = new clang::DiagnosticOptions();
clang::TextDiagnosticPrinter *DiagClient = new clang::TextDiagnosticPrinter(llvm::errs(), DiagOpts);
llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> DiagID(new clang::DiagnosticIDs());
clang::DiagnosticsEngine Diags(DiagID, DiagOpts, DiagClient);
// Create the compiler invocation
clang::LangOptions LangOpts;
llvm::OwningPtr<clang::CompilerInvocation> CI(new clang::CompilerInvocation());
//CI->setLangDefaults(LangOpts, clang::IK_CXX, clang::LangStandard::lang_gnucxx98);
clang::CompilerInvocation::CreateFromArgs(*CI, &args[0], &args[0] + args.size(), Diags);
// Print the argument list
std::cout << "clang ";
BOOST_FOREACH(const char *arg, args)
{
std::cout << arg << " ";
}
std::cout << std::endl;
// Create the compiler instance
clang::CompilerInstance Clang;
Clang.setInvocation(CI.take());
// Get ready to report problems
Clang.createDiagnostics(args.size(), &args[0]);
if (not Clang.hasDiagnostics()) throw std::runtime_error("ClangBlock::createDiagnostics");
// Create an action and make the compiler instance carry it out
clang::CodeGenAction *Act = new clang::EmitLLVMOnlyAction();
if (not Clang.ExecuteAction(*Act)) throw std::runtime_error("ClangBlock::EmitLLVMOnlyAction");
return Act->takeModule();
}
#endif //HAVE_CLANG
*/
/***********************************************************************
* factory compile implementation
**********************************************************************/
#ifdef HAVE_LLVM
void gras::jit_factory(const std::string &source, const std::vector<std::string> &flags_)
{
//write source to tmp file
char source_file[L_tmpnam];
if (std::tmpnam(source_file) == NULL) throw std::runtime_error("GRAS compiler: tmp source file path failed");
std::ofstream source_fstream(source_file);
source_fstream << source;
source_fstream.close();
llvm::InitializeNativeTarget();
llvm::llvm_start_multithreaded();
//use clang to compile source into bitcode
std::cout << "GRAS compiler: compile source into bitcode..." << std::endl;
std::vector<std::string> flags = flags_;
flags.push_back("-I"+get_gras_runtime_include_path()); //add root include path
llvm::Module *module = call_clang_exe(source_file, flags);
//create execution engine
std::string error;
boost::shared_ptr<llvm::ExecutionEngine> ee(llvm::ExecutionEngine::create(module, false, &error));
if (not error.empty()) throw std::runtime_error("GRAS compiler: ExecutionEngine " + error);
std::cout << "GRAS compiler: execute static constructors..." << std::endl;
get_eemon().add(ee);
}
#else //HAVE_LLVM
void gras::jit_factory(const std::string &, const std::vector<std::string> &)
{
throw std::runtime_error("GRAS compiler not built with Clang support!");
}
#endif //HAVE_LLVM
|
Require Export SmallCat SigTCategory.
Set Implicit Arguments.
Generalizable All Variables.
Set Asymmetric Patterns.
Set Universe Polymorphism.
Section SmallCat.
Let eq_dec_on_cat `(C : @SpecializedCategory objC) := forall x y : objC, {x = y} + {x <> y}.
Definition SmallCatDec := SpecializedCategory_sigT_obj SmallCat (fun C => eq_dec_on_cat C).
Definition LocallySmallCatDec := SpecializedCategory_sigT_obj LocallySmallCat (fun C => eq_dec_on_cat C).
End SmallCat.
|
```python
from sympy import *
y, x, a, s, u = symbols('ry rx amp sigma2 mu')
simplify(diff((y-(a*exp(-(x-u)**2/(2*s**2))))**2, s, u))
```
2*amp*(mu - rx)*(2*sigma2**2*(amp - ry*exp((mu - rx)**2/(2*sigma2**2))) - (2*amp - ry*exp((mu - rx)**2/(2*sigma2**2)))*(mu - rx)**2)*exp(-(mu - rx)**2/sigma2**2)/sigma2**5
```python
if 1:
y, x, a, s, u = symbols('ly lx amp sigma1 mu')
else:
y, x, a, s, u = symbols('ry rx amp sigma2 mu')
hessian((y-(a*exp(-(x-u)**2/(2*s**2))))**2, (a, s, u))
```
Matrix([
[ 2*exp(-(lx - mu)**2/sigma1**2), 2*amp*(lx - mu)**2*exp(-(lx - mu)**2/sigma1**2)/sigma1**3 - 2*(lx - mu)**2*(-amp*exp(-(lx - mu)**2/(2*sigma1**2)) + ly)*exp(-(lx - mu)**2/(2*sigma1**2))/sigma1**3, -amp*(-2*lx + 2*mu)*exp(-(lx - mu)**2/sigma1**2)/sigma1**2 + (-2*lx + 2*mu)*(-amp*exp(-(lx - mu)**2/(2*sigma1**2)) + ly)*exp(-(lx - mu)**2/(2*sigma1**2))/sigma1**2],
[ 2*amp*(lx - mu)**2*exp(-(lx - mu)**2/sigma1**2)/sigma1**3 - 2*(lx - mu)**2*(-amp*exp(-(lx - mu)**2/(2*sigma1**2)) + ly)*exp(-(lx - mu)**2/(2*sigma1**2))/sigma1**3, 2*amp**2*(lx - mu)**4*exp(-(lx - mu)**2/sigma1**2)/sigma1**6 + 6*amp*(lx - mu)**2*(-amp*exp(-(lx - mu)**2/(2*sigma1**2)) + ly)*exp(-(lx - mu)**2/(2*sigma1**2))/sigma1**4 - 2*amp*(lx - mu)**4*(-amp*exp(-(lx - mu)**2/(2*sigma1**2)) + ly)*exp(-(lx - mu)**2/(2*sigma1**2))/sigma1**6, -amp**2*(-2*lx + 2*mu)*(lx - mu)**2*exp(-(lx - mu)**2/sigma1**2)/sigma1**5 - 2*amp*(-2*lx + 2*mu)*(-amp*exp(-(lx - mu)**2/(2*sigma1**2)) + ly)*exp(-(lx - mu)**2/(2*sigma1**2))/sigma1**3 + amp*(-2*lx + 2*mu)*(lx - mu)**2*(-amp*exp(-(lx - mu)**2/(2*sigma1**2)) + ly)*exp(-(lx - mu)**2/(2*sigma1**2))/sigma1**5],
[-amp*(-2*lx + 2*mu)*exp(-(lx - mu)**2/sigma1**2)/sigma1**2 + (-2*lx + 2*mu)*(-amp*exp(-(lx - mu)**2/(2*sigma1**2)) + ly)*exp(-(lx - mu)**2/(2*sigma1**2))/sigma1**2, -amp**2*(-2*lx + 2*mu)*(lx - mu)**2*exp(-(lx - mu)**2/sigma1**2)/sigma1**5 - 2*amp*(-2*lx + 2*mu)*(-amp*exp(-(lx - mu)**2/(2*sigma1**2)) + ly)*exp(-(lx - mu)**2/(2*sigma1**2))/sigma1**3 + amp*(-2*lx + 2*mu)*(lx - mu)**2*(-amp*exp(-(lx - mu)**2/(2*sigma1**2)) + ly)*exp(-(lx - mu)**2/(2*sigma1**2))/sigma1**5, amp**2*(-2*lx + 2*mu)**2*exp(-(lx - mu)**2/sigma1**2)/(2*sigma1**4) + 2*amp*(-amp*exp(-(lx - mu)**2/(2*sigma1**2)) + ly)*exp(-(lx - mu)**2/(2*sigma1**2))/sigma1**2 - amp*(-2*lx + 2*mu)**2*(-amp*exp(-(lx - mu)**2/(2*sigma1**2)) + ly)*exp(-(lx - mu)**2/(2*sigma1**2))/(2*sigma1**4)]])
```python
if 0:
y, x, a, s, u = symbols('ly lx amp sigma1 mu')
else:
y, x, a, s, u = symbols('ry rx amp sigma2 mu')
hessian((y-(a*exp(-(x-u)**2/(2*s**2))))**2, (a, s, u))
```
Matrix([
[ 2*exp(-(-mu + rx)**2/sigma2**2), 2*amp*(-mu + rx)**2*exp(-(-mu + rx)**2/sigma2**2)/sigma2**3 - 2*(-mu + rx)**2*(-amp*exp(-(-mu + rx)**2/(2*sigma2**2)) + ry)*exp(-(-mu + rx)**2/(2*sigma2**2))/sigma2**3, -amp*(2*mu - 2*rx)*exp(-(-mu + rx)**2/sigma2**2)/sigma2**2 + (2*mu - 2*rx)*(-amp*exp(-(-mu + rx)**2/(2*sigma2**2)) + ry)*exp(-(-mu + rx)**2/(2*sigma2**2))/sigma2**2],
[2*amp*(-mu + rx)**2*exp(-(-mu + rx)**2/sigma2**2)/sigma2**3 - 2*(-mu + rx)**2*(-amp*exp(-(-mu + rx)**2/(2*sigma2**2)) + ry)*exp(-(-mu + rx)**2/(2*sigma2**2))/sigma2**3, 2*amp**2*(-mu + rx)**4*exp(-(-mu + rx)**2/sigma2**2)/sigma2**6 + 6*amp*(-mu + rx)**2*(-amp*exp(-(-mu + rx)**2/(2*sigma2**2)) + ry)*exp(-(-mu + rx)**2/(2*sigma2**2))/sigma2**4 - 2*amp*(-mu + rx)**4*(-amp*exp(-(-mu + rx)**2/(2*sigma2**2)) + ry)*exp(-(-mu + rx)**2/(2*sigma2**2))/sigma2**6, -amp**2*(-mu + rx)**2*(2*mu - 2*rx)*exp(-(-mu + rx)**2/sigma2**2)/sigma2**5 - 2*amp*(2*mu - 2*rx)*(-amp*exp(-(-mu + rx)**2/(2*sigma2**2)) + ry)*exp(-(-mu + rx)**2/(2*sigma2**2))/sigma2**3 + amp*(-mu + rx)**2*(2*mu - 2*rx)*(-amp*exp(-(-mu + rx)**2/(2*sigma2**2)) + ry)*exp(-(-mu + rx)**2/(2*sigma2**2))/sigma2**5],
[ -amp*(2*mu - 2*rx)*exp(-(-mu + rx)**2/sigma2**2)/sigma2**2 + (2*mu - 2*rx)*(-amp*exp(-(-mu + rx)**2/(2*sigma2**2)) + ry)*exp(-(-mu + rx)**2/(2*sigma2**2))/sigma2**2, -amp**2*(-mu + rx)**2*(2*mu - 2*rx)*exp(-(-mu + rx)**2/sigma2**2)/sigma2**5 - 2*amp*(2*mu - 2*rx)*(-amp*exp(-(-mu + rx)**2/(2*sigma2**2)) + ry)*exp(-(-mu + rx)**2/(2*sigma2**2))/sigma2**3 + amp*(-mu + rx)**2*(2*mu - 2*rx)*(-amp*exp(-(-mu + rx)**2/(2*sigma2**2)) + ry)*exp(-(-mu + rx)**2/(2*sigma2**2))/sigma2**5, amp**2*(2*mu - 2*rx)**2*exp(-(-mu + rx)**2/sigma2**2)/(2*sigma2**4) + 2*amp*(-amp*exp(-(-mu + rx)**2/(2*sigma2**2)) + ry)*exp(-(-mu + rx)**2/(2*sigma2**2))/sigma2**2 - amp*(2*mu - 2*rx)**2*(-amp*exp(-(-mu + rx)**2/(2*sigma2**2)) + ry)*exp(-(-mu + rx)**2/(2*sigma2**2))/(2*sigma2**4)]])
|
Formal statement is: proposition Stone_Weierstrass_uniform_limit: fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space" assumes S: "compact S" and f: "continuous_on S f" obtains g where "uniform_limit S g f sequentially" "\<And>n. polynomial_function (g n)" Informal statement is: Suppose $f$ is a continuous function defined on a compact set $S$. Then there exists a sequence of polynomial functions $g_n$ such that $g_n$ converges uniformly to $f$ on $S$. |
Require Import List.
Require Import Relations.
Require Import list.
(* inductive predicate expressing the fact that two lists are obtained from
each other, by the permutation of two consecutive elements *)
Inductive Transpose {A:Type} : list A -> list A -> Prop :=
| transp_refl : forall (l: list A), Transpose l l
| transp_pair : forall(x y:A), Transpose (x::y::nil) (y::x::nil)
| transp_gen : forall (l m l1 l2 : list A),
Transpose l m -> Transpose (l1++l++l2) (l1++m++l2).
(* one common issue with this sort of definition is that constructors of the
inductive predicates are akin to 'axioms', and it is very easy to define the
wrong thing, or things that are inconsistent, or incomplete etc *)
(* Here is another way to go about it *)
Definition Transpose' {A:Type} (l: list A) (m:list A) : Prop :=
l = m \/ (exists (l1 l2:list A) (x y:A),
l = l1++(x::y::nil)++l2 /\ m = l1++(y::x::nil)++l2).
(* Transpose' is a reflexive relation on list A *)
Lemma Transpose_refl': forall (A:Type), reflexive (list A) Transpose'.
Proof.
intros A. unfold reflexive. intros l. unfold Transpose'. left. reflexivity.
Qed.
(* ideally, you want to check the equivalence between Transpose and Transpose' *)
Lemma Transpose_check: forall (A:Type),
same_relation (list A) Transpose Transpose'.
Proof.
intros A. unfold same_relation. split.
unfold inclusion.
intros l m. intro H. generalize H. elim H.
clear H l m. intros l H. clear H. apply Transpose_refl'.
clear H l m. intros x y H. clear H. unfold Transpose'. right.
exists nil, nil, x, y. split; reflexivity.
clear H l m. intros l m l1 l2 H0 H1 H2. clear H2.
cut (Transpose' l m). clear H0 H1. intro H.
unfold Transpose' in H. elim H.
clear H. intro H. rewrite H. apply Transpose_refl'.
clear H. intro H. elim H.
clear H. intros l3 H. elim H.
clear H. intros l4 H. elim H.
clear H. intros x H. elim H.
clear H. intros y H. unfold Transpose'. right.
exists (l1++l3), (l4++l2), x, y. elim H.
clear H. intros H0 H1. split.
rewrite H0. set (k:= x::y::nil).
rewrite <- app_assoc, <- app_assoc, <- app_assoc. reflexivity.
rewrite H1. set (k:= y::x::nil).
rewrite <- app_assoc, <- app_assoc, <- app_assoc. reflexivity.
apply H1. exact H0.
unfold inclusion.
intros l m H. unfold Transpose' in H. elim H.
clear H. intro H. rewrite H. apply transp_refl.
clear H. intro H. elim H.
clear H. intros l1 H. elim H.
clear H. intros l2 H. elim H.
clear H. intros x H. elim H.
clear H. intros y H. elim H.
clear H. intros Hl Hm. rewrite Hl, Hm.
apply transp_gen. apply transp_pair.
Qed.
(* This version of the lemma can be handy for rewrites *)
Lemma Transpose_check': forall (A:Type) (l m: list A),
Transpose l m <-> Transpose' l m.
Proof.
intros A l m. split.
intro H. apply Transpose_check. exact H.
intro H. apply Transpose_check. exact H.
Qed.
(* Transpose is a reflexive relation on list A *)
Lemma Transpose_refl: forall (A:Type), reflexive (list A) Transpose.
Proof.
intros A. unfold reflexive. intros l. apply transp_refl.
Qed.
(* Transpose is a symmetric relation on list A *)
Lemma Transpose_sym: forall (A:Type), symmetric (list A) Transpose.
Proof.
intros A. unfold symmetric. intros l m H. generalize H. elim H.
clear H l m. intros. apply transp_refl.
clear H l m. intros. apply transp_pair.
clear H l m. intros l m l1 l2 H0 H1 H2. clear H2.
apply transp_gen. apply H1. exact H0.
Qed.
(* Two lists which are transpositions of one another have same length *)
Lemma Transpose_imp_eq_length: forall (A:Type)(l m:list A),
Transpose l m -> length l = length m.
Proof.
intros A l m H. generalize H. elim H.
clear H l m. intros. simpl. reflexivity.
clear H l m. intros. simpl. reflexivity.
clear H l m. intros l m l1 l2 H0 H1 H2. clear H2.
rewrite app_length, app_length, app_length, app_length.
rewrite H1. reflexivity. exact H0.
Qed.
Lemma Transpose_l_nil: forall (A:Type)(l:list A),
Transpose l nil -> l = nil.
Proof.
intros A l H. apply length_zero_iff_nil.
apply Transpose_imp_eq_length with (m:=nil). exact H.
Qed.
Lemma Transpose_cons: forall (A:Type)(l m:list A)(a: A),
Transpose l m -> Transpose (a::l) (a::m).
Proof.
intros A l m a H.
cut (a::l = (a::nil) ++ l ++ nil).
cut (a::m = (a::nil) ++ m ++ nil).
intros Hm Hl. rewrite Hm, Hl. apply transp_gen. exact H.
rewrite <- app_comm_cons. rewrite app_nil_l. rewrite app_nil_r. reflexivity.
rewrite <- app_comm_cons. rewrite app_nil_l. rewrite app_nil_r. reflexivity.
Qed.
Lemma Transpose_cons_reverse: forall (A:Type)(l m:list A)(a:A),
Transpose (a::l) (a::m) -> Transpose l m.
Proof.
intros A l m a.
cut (forall (l' m':list A),
l' = a::l -> m' = a::m -> Transpose l' m' -> Transpose l m). eauto.
intros l' m' Hl Hm H. generalize H Hl Hm.
clear Hl Hm. generalize l m a. clear l m a. elim H.
clear H l' m'. intros k l m a H0 H1 H2. clear H0.
rewrite H1 in H2. clear H1. injection H2. intros H0.
rewrite H0. apply Transpose_refl.
clear H l' m'. intros x y l m a H0 H1 H2. clear H0.
injection H1. clear H1. injection H2. clear H2.
intros H0 H1 H2 H3.
rewrite H3 in H0. clear H3. rewrite H1 in H2. clear H1.
rewrite H2 in H0. clear H2. rewrite H0. apply Transpose_refl.
clear H l' m'. intros l m l1 l2 H0 H1 l' m' a H2 H3 H4.
generalize (destruct_list l1). intro H5. elim H5.
clear H5. intro H5. elim H5. clear H5. intros x H5. elim H5.
clear H5. intros k1 H5. rewrite H5 in H3. rewrite H5 in H4.
rewrite <- app_comm_cons in H3. rewrite <- app_comm_cons in H4.
injection H3. injection H4. clear H3 H4 H5. intros H3 H4. clear H4.
intros H4 H5. clear H5. rewrite <- H3, <- H4. clear H3 H4.
apply transp_gen. exact H0.
clear H5. intro H5. rewrite H5 in H3. rewrite H5 in H4.
rewrite app_nil_l in H3. rewrite app_nil_l in H4. clear H2 H5.
generalize (destruct_list l). generalize (destruct_list m).
intros H5 H6. elim H5.
clear H5. intro H5. elim H5. clear H5. intros b H5. elim H5.
clear H5. clear l1. intros l1 H5. rewrite H5 in H4.
rewrite <- app_comm_cons in H4. injection H4. clear H4.
intro H4. intro H7. rewrite H7 in H5. clear H7 b. elim H6.
clear H6. intro H6. elim H6. clear H6. intros b H6. elim H6.
clear H6. intros k1 H6. rewrite H6 in H3.
rewrite <- app_comm_cons in H3. injection H3. clear H3.
intro H3. intro H7. rewrite H7 in H6. clear H7 b.
rewrite <- app_nil_l with (l:=k1++l2) in H3. rewrite <- H3.
rewrite <- app_nil_l with (l:=l1++l2) in H4. rewrite <- H4.
apply transp_gen. apply H1 with (a:=a). exact H0.
exact H6. exact H5.
clear H6. intro H6. rewrite H6 in H0. apply Transpose_sym in H0.
apply Transpose_l_nil in H0. rewrite H0 in H5. discriminate H5.
clear H5. intro H5. rewrite H5 in H0. apply Transpose_l_nil in H0.
rewrite H0 in H3. rewrite app_nil_l in H3.
rewrite H5 in H4. rewrite app_nil_l in H4. rewrite H3 in H4.
injection H4. clear H4. intro H4. rewrite H4. apply Transpose_refl.
Qed.
(* This inductive predicate expresses the fact that two
lists are permutation of one another *)
Inductive Permute {A:Type} : list A -> list A -> Prop :=
| perm_refl : forall l:list A, Permute l l
| perm_next : forall l l' m: list A,
Permute l l' -> Transpose l' m -> Permute l m.
(* Permute is a reflexive relation on list A *)
Lemma Permute_refl : forall (A:Type), reflexive (list A) Permute.
Proof.
intros A. unfold reflexive. intros l. apply perm_refl.
Qed.
(* As defined, the Permute relation is such that if l1 is
a permutation of l2 and l2 is a transposition of l3, then
l1 is deemed a permutation of l3. In order to prove that
the Permute relation is symmetric, we need to be able to
argue the other way around, namely that if l1 is a
transposition of l2 and l2 is a permutation of l3, then
l1 is also a permutation of l3. This result is obvious
once we have established the symmetry of both Transpose
and Permute, but we are not there yet. *)
Lemma Transpose_first: forall (A:Type) (l l' m:list A),
Transpose l l' -> Permute l' m -> Permute l m.
Proof.
intros A l l' m H0 H1. generalize H0. clear H0. generalize H1 l.
elim H1. clear H1 l l' m. intros m. intro H. clear H. intro l.
intro H. apply perm_next with (l':=l). apply perm_refl. exact H.
clear H1 l l' m. intros l l' m H0 H1 H3 H4 k H5.
eapply perm_next. apply H1. exact H0. exact H5. exact H3.
(* dont understand why normal 'apply ... with' was failing *)
Qed.
(* We are now in a position to prove the symmetry of Permute *)
Lemma Permute_sym: forall (A:Type), symmetric (list A) Permute.
Proof.
intro A. unfold symmetric.
intros l m H. generalize H. elim H. auto. clear H m l.
intros l l' m H0 H1 H2 H3. apply Transpose_first with (l':=l').
apply Transpose_sym. exact H2. apply H1. exact H0.
Qed.
(* Permute is also a transitive relation on list A *)
Lemma Permute_trans: forall (A:Type), transitive (list A) Permute.
Proof.
intros A. unfold transitive.
intros l m k H. generalize H k. clear k. elim H. auto.
clear H l m. intros l l' m H0 H1 H2 H3 k H4.
apply H1. exact H0. apply Transpose_first with (l':=m).
exact H2. exact H4.
Qed.
(* Two lists which are permutation of one another have same length *)
Lemma Permute_imp_eq_length: forall (A:Type)(l m:list A),
Permute l m -> length l = length m.
Proof.
intros A l m H. generalize H. elim H.
clear H l m. intros. reflexivity.
clear H l m. intros l l' m H0 H1 H2 H3. clear H3.
apply eq_trans with (y:=length l').
apply H1. exact H0. apply Transpose_imp_eq_length. exact H2.
Qed.
Lemma Permute_cons: forall (A:Type)(l m: list A)(a: A),
Permute l m -> Permute (a::l) (a::m).
Proof.
intros A l m a H. generalize H. generalize a. clear a. elim H.
clear H l m. intros. apply perm_refl.
clear H l m. intros l l' m H0 H1 H2 a H3.
apply (Permute_trans A (a::l) (a::l') (a::m)). apply H1. exact H0.
apply (perm_next (a::l') (a::l') (a::m)). apply perm_refl.
apply Transpose_cons. exact H2.
Qed.
Definition SubSet {A:Type}(l m:list A) : Prop :=
forall (x:A), In x l -> In x m.
Definition EqSet {A:Type}(l m: list A) : Prop :=
SubSet l m /\ SubSet m l.
Lemma SubSet_refl: forall (A:Type), reflexive (list A) SubSet.
Proof.
intros A. unfold reflexive. intro l. unfold SubSet. auto.
Qed.
Lemma SubSet_trans: forall (A: Type), transitive (list A) SubSet.
Proof.
intros A. unfold transitive.
intros l m k H0 H1. unfold SubSet. intros x H2.
apply H1. apply H0. exact H2.
Qed.
Lemma Transpose_imp_SubSet: forall (A:Type),
inclusion (list A) Transpose SubSet.
Proof.
intros A. unfold inclusion.
intros l m H. generalize H. elim H.
clear H l m. intros. apply SubSet_refl.
clear H l m. intros x y H0. clear H0. unfold SubSet.
intros z H0. simpl. simpl in H0. elim H0.
clear H0. intro H0. right. left. exact H0.
clear H0. intro H0. elim H0. clear H0. intro H0. left. exact H0.
apply False_ind.
clear H l m. intros l m l1 l2 H0 H1 H2. clear H2. unfold SubSet.
intros x H2. simpl. rewrite in_app_iff, in_app_iff.
rewrite in_app_iff, in_app_iff in H2. elim H2.
clear H2. intro H2. left. exact H2.
clear H2. intro H2. elim H2. clear H2. intro H2. right. left.
apply H1. exact H0. exact H2.
clear H2. intro H2. right. right. exact H2.
Qed.
Lemma Transpose_imp_EqSet: forall (A:Type),
inclusion (list A) Transpose EqSet.
Proof.
intros A. unfold inclusion.
intros l m H. unfold EqSet. split.
apply Transpose_imp_SubSet. exact H.
apply Transpose_imp_SubSet. apply Transpose_sym. exact H.
Qed.
Lemma Permute_imp_SubSet: forall (A:Type),
inclusion (list A) Permute SubSet.
Proof.
intros A. unfold inclusion.
intros l m H. generalize H. elim H.
clear H l m. intros. apply SubSet_refl.
clear H l m. intros l l' m H0 H1 H2 H3. clear H3.
apply (SubSet_trans A l l' m). apply H1. exact H0.
apply Transpose_imp_SubSet. exact H2.
Qed.
Lemma Permute_imp_EqSet: forall (A:Type),
inclusion (list A) Permute EqSet.
Proof.
intros A. unfold inclusion.
intros l m H. unfold EqSet. split.
apply Permute_imp_SubSet. exact H.
apply Permute_imp_SubSet. apply Permute_sym. exact H.
Qed.
Lemma Permute_cons_reverse: forall (A:Type)(l m:list A)(a:A),
Permute (a::l) (a::m) -> Permute l m.
Proof.
intros A l m a.
cut (forall (l' m':list A),
l' = a::l -> m' = a::m -> Permute l' m' -> Permute l m). eauto.
intros l' m' Hl Hm H. generalize H Hl Hm.
clear Hl Hm. generalize l m a. clear l m a. elim H.
clear H l' m'. intros l m' m a H0 H1 H2. clear H0.
rewrite H2 in H1. clear H2. injection H1. clear H1.
intro H0. rewrite H0. apply perm_refl.
clear H l' m'. intros l' k' m' H0 H1 H3 l m a H4 H5 H6.
|
library(DirichletReg)
x<-c(0.1,1,2,3,4,5,10)
x<-x/sum(x)
n<-10
pSum<-17
alfa<-x*pSum
xx<-rdirichlet(n,alfa)
round(x,3)
round(xx,3)
apply(xx,1,sum)
ddirichlet(xx, x*pSum, log = T, sum.up = FALSE)
ddirichlet(xx, x*pSum, log = T, sum.up = T)
one<-xx[1,]
sum(one)
logSumP<-lgamma(sum(alfa))
loggamma<-sum(lgamma(one))
pPowStom<-sum((alfa-1)*log(one))
logLike<-logSumP-loggamma+pPowStom
logLike
-logLike |
include("../emi.jl")
using EMI
using EMI.Draw, EMI.Gmsh
# Something like this with circular
# ^
# / \
# [ ]
# \ /
# U
const R, dx, dy = 1, 0.2, 0.3
loop = Loop([Line(Point(0, R+dy+dx), Point(0, R+dy)),
Line(Point(0, R+dy), Point(dy, R+dy)),
CircleArc(Point(dy, R+dy), Point(R+dy, R+dy), Point(R+dy, dy)),
Line(Point(R+dy, dy), Point(R+dy, 0)),
Line(Point(R+dy, 0), Point(R+dy+dx, 0)),
Line(Point(R+dy+dx, 0), Point(R+dy+dx, dy)),
CircleArc(Point(R+dy+dx, dy), Point(R+dy+dx, R+dy), Point(2R+dy+dx, R+dy)),
Line(Point(2R+dy+dx, R+dy), Point(2R+2*dy+dx, R+dy)),
Line(Point(2R+2*dy+dx, R+dy), Point(2R+2*dy+dx, R+dy+dx)),
Line(Point(2R+2*dy+dx, R+dy+dx), Point(2R+dy+dx, R+dy+dx)),
CircleArc(Point(2R+dy+dx, R+dy+dx), Point(R+dy+dx, R+dy+dx), Point(R+dy+dx, 2R+dy+dx)),
Line(Point(R+dy+dx, 2R+dy+dx), Point(R+dy+dx, 2R+2*dy+dx)),
Line(Point(R+dy+dx, 2R+2*dy+dx), Point(R+dy, 2R+2*dy+dx)),
Line(Point(R+dy, 2R+2*dy+dx), Point(R+dy, 2R+dy+dx)),
CircleArc(Point(R+dy, 2R+dy+dx), Point(R+dy, R+dy+dx), Point(dy, R+dy+dx)),
Line(Point(dy, R+dy+dx), Point(0, R+dy+dx))])
canvas = Canvas()
canvas = canvas + loop
set_bbox!(canvas, 0.2, 0.3)
gmsh_script(canvas, 0.2)
|
import os
import json
import unittest
import numpy as np
import pandas as pd
from komapy.chart import Chart
from komapy.cache import ResolverCache
from komapy.decorators import counter
from komapy.series import Series
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
FIXTURE_DIR = os.path.join(BASE_DIR, 'fixtures')
@counter
def bma_fetch_resource(series, **kwargs):
"""
Mock BMA API name resolver.
"""
path = os.path.join(FIXTURE_DIR, 'tiltmeter_selokopo.json')
with open(path, 'r') as f:
data = json.load(f)
return pd.DataFrame(data)
@counter
def csv_fetch_resource(series, **kwargs):
"""
Mock CSV resolver.
"""
path = os.path.join(FIXTURE_DIR, 'tiltmeter_selokopo.csv')
return pd.read_csv(path, **series.csv_params)
class BMAChart(Chart):
def _fetch_resource(self, series, **kwargs):
return bma_fetch_resource(series, **kwargs)
class CSVChart(Chart):
def _fetch_resource(self, series, **kwargs):
return csv_fetch_resource(series, **kwargs)
class FetchResourceCacheTest(unittest.TestCase):
def test_fetch_resource_with_bma_api_name(self):
config = {
'use_cache': True,
'layout': {
'data': [
{
'series': {
'name': 'tiltmeter',
'query_params': {
'timestamp__gte': '2019-10-01',
'timestamp__lt': '2019-11-01',
'station': 'selokopo',
'nolimit': True
},
'plot_params': {
'zorder': 2,
'label': 'X'
},
'fields': ['timestamp', 'x'],
'xaxis_date': True,
}
},
{
'series': {
'name': 'tiltmeter',
'query_params': {
'timestamp__gte': '2019-10-01',
'timestamp__lt': '2019-11-01',
'station': 'selokopo',
'nolimit': True
},
'plot_params': {
'zorder': 2,
'label': 'Y'
},
'fields': ['timestamp', 'y'],
'xaxis_date': True,
}
},
{
'series': {
'name': 'tiltmeter',
'query_params': {
'timestamp__gte': '2019-10-01',
'timestamp__lt': '2019-11-01',
'station': 'selokopo',
'nolimit': True
},
'plot_params': {
'zorder': 2,
'label': 'Temperature'
},
'fields': ['timestamp', 'temperature'],
'xaxis_date': True,
}
},
]
}
}
chart = BMAChart(config)
chart.render()
self.assertEqual(bma_fetch_resource.count, 1)
def test_fetch_resource_with_csv(self):
config = {
'use_cache': True,
'layout': {
'data': [
{
'series': {
'csv': 'http://api.example.com/data.csv',
'csv_params': {
'delimiter': ',',
'header': 0,
},
'plot_params': {
'marker': 'o',
'markersize': 6,
'linewidth': 1,
'label': 'X'
},
'fields': ['timestamp', 'x'],
'xaxis_date': True
}
},
{
'series': {
'csv': 'http://api.example.com/data.csv',
'csv_params': {
'delimiter': ',',
'header': 0,
},
'plot_params': {
'marker': 'o',
'markersize': 6,
'linewidth': 1,
'label': 'Y'
},
'fields': ['timestamp', 'y'],
'xaxis_date': True
}
},
{
'series': {
'csv': 'http://api.example.com/data.csv',
'csv_params': {
'delimiter': ',',
'header': 0,
},
'plot_params': {
'marker': 'o',
'markersize': 6,
'linewidth': 1,
'label': 'Temperature'
},
'fields': ['timestamp', 'temperature'],
'xaxis_date': True
}
},
]
}
}
chart = CSVChart(config)
chart.render()
self.assertEqual(csv_fetch_resource.count, 1)
class ResolverCacheTest(unittest.TestCase):
def test_cache_config_with_bma_name(self):
config = {
'name': 'seismicity',
'eventdate__gte': '2019-10-01 12:00:00',
'eventdate__lt': '2019-10-30 12:00:00',
'eventtype': 'MP',
'nolimit': True,
}
another_config = {
'eventdate__lt': '2019-10-30 12:00:00',
'name': 'seismicity',
'nolimit': True,
'eventdate__gte': '2019-10-01 12:00:00',
'eventtype': 'MP',
}
cache = ResolverCache(config)
another_cache = ResolverCache(another_config)
self.assertEqual(hash(cache), hash(another_cache))
def test_cache_config_with_csv(self):
config = {
'csv': 'http://api.example.com/data.csv',
'delimiter': ';',
'columns': ['timestamp', 'x', 'y', 'temperature']
}
another_config = {
'columns': ['timestamp', 'x', 'y', 'temperature'],
'delimiter': ';',
'csv': 'http://api.example.com/data.csv',
}
cache = ResolverCache(config)
another_cache = ResolverCache(another_config)
self.assertEqual(hash(cache), hash(another_cache))
def test_cache_config_with_url(self):
config = {
'url': 'http://api.example.com/data/',
'timestamp__gte': '2019-11-01 12:00:00',
'timestamp__lt': '2019-11-05 12:00:00',
'type': 'json',
}
another_config = {
'timestamp__gte': '2019-11-01 12:00:00',
'type': 'json',
'url': 'http://api.example.com/data/',
'timestamp__lt': '2019-11-05 12:00:00',
}
cache = ResolverCache(config)
another_cache = ResolverCache(another_config)
self.assertEqual(hash(cache), hash(another_cache))
class ResolverCacheInstanceCreationTest(unittest.TestCase):
def test_create_instance_from_series(self):
series = Series(
type='bar',
name='seismicity',
query_params={
'eventdate__gte': '2019-10-01',
'eventdate__lt': '2019-10-30',
'eventtype': 'MP',
'nolimit': True,
},
fields=['timestamp', 'count'],
xaxis_date=True,
)
instance = ResolverCache.create_instance_from_series(series)
self.assertTrue(isinstance(instance, ResolverCache))
def test_create_key_from_series(self):
series = Series(
type='bar',
name='seismicity',
query_params={
'eventdate__gte': '2019-10-01',
'eventdate__lt': '2019-10-30',
'eventtype': 'ROCKFALL',
'nolimit': True,
},
fields=['timestamp', 'count'],
xaxis_date=True,
)
key = ResolverCache.create_key_from_series(series)
instance = ResolverCache(
ResolverCache.get_resolver_cache_config(series))
self.assertEqual(key, hash(instance))
if __name__ == '__main__':
unittest.main()
|
You can post for sale and for rent advertisements for free. You need to register an account to post advertisements.
(1) Click Register in the right upper corner.
(2) Select normal account or agency account.
(3) Fill all fields and click SIGN UP.
(1) Log in to your account, go to Dashboard.
(2) Click Post New Advertisement.
(3) You can post new advertisement by choosing for sale or for rent.
Difference between normal account and agency account?
There are two account types at iMyanmarHouse.com They are as follows.
oth account tyes can post advertisements for free. But agency account has more features.
(a) In the right side of advertisements posted by agency account, facts about that agency (address, phone no etc) are described.
(c) Each agency account has their own page.
(d) For sale or for rent advertisements posted by agency account can be searched easily.
Normal account can be upgraded to agency account.
How to add photos in advertisement?
If you add photos in your advertisement, it will be more interesting.
(1) You can add photos in third step of posting advertisement. Follow instructions.
(3) Click for sale or for rent.
How to delete photos from advertisements you have posted?
If you want to delete photos from advertisements you have posted, you can delete them.
(4) Click Delete Image.You can delete photo as you like.
How to edit advertisements you have posted?
If something goes wrong with your advertisement (eg. missing price, wrong tyes etc), you can edit it.
How to delete advertisements you have posted?
If your property advertisement have been sold out or rented, you can delete it.
Difference between deleting advertisements and marking as sold out or rented?
(2) can be marked as sold out or rented.
(1) If you delete your advertisement, detail facts about your advertisement cannot be seen by viewers. It will only be displayed as It has been deleted.
(2) If you mark as sold out or rented, detail facts about your advertisement will be still visible for viewers. The advantage of marking sold out or rented is viewers can ask you about your other advertisements. For example... if you mark your advertisement for sale at Avenue Road as sold out, viewers can ask you whether you have any other advertisements for sale at Avenue Road.
If You Forgot Your Password.What Should you do?
If you forget password to log in to your account, you can reset it.
(2) Type your email and click RESET.A new password will be sent to your email.
(3) Login to your email and get new password.
How to update company information for agency account?
You can update information about your agency company.
(3) Click Update Company Information.
How to upload company logo for agency account?
You can upload company logo for your agency company.
(3) Click Update Company Logo. |
Carbahal & Company offers Davis B2B Business Services including:
Management Advisory Services
Tax Services
Accounting Services
Financial Statements
Carbahal & Company won the the Davis Chamber of Commerces Bill Streng Business of the Year Award for 2009.
Davis contains many companies providing business to business services.
|
theory LetSimple2
imports "../Nominal2"
begin
atom_decl name
nominal_datatype trm =
Var "name"
| App "trm" "trm"
| Let as::"assn" t::"trm" binds "bn as" in t
and assn =
Assn "name" "trm"
binder
bn
where
"bn (Assn x t) = [atom x]"
print_theorems
thm bn_raw.simps
thm permute_bn_raw.simps
thm trm_assn.perm_bn_alpha
thm trm_assn.permute_bn
thm trm_assn.fv_defs
thm trm_assn.eq_iff
thm trm_assn.bn_defs
thm trm_assn.bn_inducts
thm trm_assn.perm_simps
thm trm_assn.induct
thm trm_assn.inducts
thm trm_assn.distinct
thm trm_assn.supp
thm trm_assn.fresh
thm trm_assn.exhaust
thm trm_assn.strong_exhaust
thm trm_assn.perm_bn_simps
thm alpha_bn_raw.cases
thm trm_assn.alpha_refl
thm trm_assn.alpha_sym
thm trm_assn.alpha_trans
lemmas alpha_bn_cases[consumes 1] = alpha_bn_raw.cases[quot_lifted]
lemma alpha_bn_refl: "alpha_bn x x"
by(rule trm_assn.alpha_refl)
lemma alpha_bn_sym: "alpha_bn x y \<Longrightarrow> alpha_bn y x"
by (rule trm_assn.alpha_sym)
lemma alpha_bn_trans: "alpha_bn x y \<Longrightarrow> alpha_bn y z \<Longrightarrow> alpha_bn x z"
using trm_assn.alpha_trans by metis
lemma fv_bn_finite[simp]:
"finite (fv_bn as)"
apply(case_tac as rule: trm_assn.exhaust(2))
apply(simp add: trm_assn.supp finite_supp)
done
lemma k: "A \<Longrightarrow> A \<and> A" by blast
section {* definition with helper functions *}
function
apply_assn
where
"apply_assn f (Assn x t) = (f t)"
apply(case_tac x)
apply(simp)
apply(case_tac b rule: trm_assn.exhaust(2))
apply(blast)
apply(simp)
done
termination
by lexicographic_order
function
apply_assn2
where
"apply_assn2 f (Assn x t) = Assn x (f t)"
apply(case_tac x)
apply(simp)
apply(case_tac b rule: trm_assn.exhaust(2))
apply(blast)
apply(simp)
done
termination
by lexicographic_order
lemma [eqvt]:
shows "p \<bullet> (apply_assn f as) = apply_assn (p \<bullet> f) (p \<bullet> as)"
apply(induct f as rule: apply_assn.induct)
apply(simp)
apply(perm_simp)
apply(rule)
done
lemma [eqvt]:
shows "p \<bullet> (apply_assn2 f as) = apply_assn2 (p \<bullet> f) (p \<bullet> as)"
apply(induct f as rule: apply_assn.induct)
apply(simp)
apply(perm_simp)
apply(rule)
done
nominal_function
height_trm :: "trm \<Rightarrow> nat"
where
"height_trm (Var x) = 1"
| "height_trm (App l r) = max (height_trm l) (height_trm r)"
| "height_trm (Let as b) = max (apply_assn height_trm as) (height_trm b)"
apply (simp only: eqvt_def height_trm_graph_def)
apply (rule, perm_simp)
apply(rule)
apply(rule TrueI)
apply (case_tac x rule: trm_assn.exhaust(1))
apply (auto simp add: alpha_bn_refl)[3]
apply (drule_tac x="assn" in meta_spec)
apply (drule_tac x="trm" in meta_spec)
apply(simp add: alpha_bn_refl)
apply(simp_all)[5]
apply(simp)
apply(erule conjE)+
apply(erule alpha_bn_cases)
apply(simp)
apply (subgoal_tac "height_trm_sumC b = height_trm_sumC ba")
apply simp
apply(simp add: trm_assn.bn_defs)
apply(erule_tac c="()" in Abs_lst_fcb2)
apply(simp_all add: pure_fresh fresh_star_def)[3]
apply(simp_all add: eqvt_at_def)
done
(* assn-function prevents automatic discharge
termination by lexicographic_order
*)
nominal_function
subst_trm :: "trm \<Rightarrow> name \<Rightarrow> trm \<Rightarrow> trm" ("_ [_ ::= _]" [90, 90, 90] 90)
where
"(Var x)[y ::= s] = (if x = y then s else (Var x))"
| "(App t1 t2)[y ::= s] = App (t1[y ::= s]) (t2[y ::= s])"
| "(set (bn as)) \<sharp>* (y, s) \<Longrightarrow>
(Let as t)[y ::= s] = Let (apply_assn2 (\<lambda>t. t[y ::=s]) as) (t[y ::= s])"
apply (simp only: eqvt_def subst_trm_graph_def)
apply (rule, perm_simp)
apply(rule)
apply(rule TrueI)
apply(case_tac x)
apply(simp)
apply (rule_tac y="a" and c="(b,c)" in trm_assn.strong_exhaust(1))
apply (auto simp add: alpha_bn_refl)[3]
apply(simp_all)[5]
apply(simp)
apply(erule conjE)+
apply(erule alpha_bn_cases)
apply(simp)
apply(simp add: trm_assn.bn_defs)
apply(erule_tac c="(ya,sa)" in Abs_lst1_fcb2)
apply(simp add: Abs_fresh_iff fresh_star_def)
apply(simp add: fresh_star_def)
apply(simp_all add: eqvt_at_def perm_supp_eq fresh_star_Pair)[2]
done
section {* direct definitions --- problems *}
lemma cheat: "P" sorry
definition
"eqvt_at_bn f as \<equiv> \<forall>p. (p \<bullet> (f as)) = f (permute_bn p as)"
definition
"alpha_bn_preserve f as \<equiv> \<forall>p. f as = f (permute_bn p as)"
lemma
fixes as::"assn"
assumes "eqvt_at f as"
shows "eqvt_at_bn f as"
using assms
unfolding eqvt_at_bn_def
apply(rule_tac allI)
apply(drule k)
apply(erule conjE)
apply(subst (asm) eqvt_at_def)
apply(simp)
oops
nominal_function
<<<<<<< variant A
(invariant "\<lambda>x y. case x of Inl x1 \<Rightarrow> True | Inr x2 \<Rightarrow> alpha_bn_preserve (height_assn2::assn \<Rightarrow> nat) x2")
>>>>>>> variant B
####### Ancestor
(invariant "\<lambda>x y. case x of Inl x1 \<Rightarrow> True | Inr x2 \<Rightarrow> \<forall>p. (permute_bn p x2) = x2 \<longrightarrow> (p \<bullet> y) = y")
======= end
height_trm2 :: "trm \<Rightarrow> nat"
and height_assn2 :: "assn \<Rightarrow> nat"
where
"height_trm2 (Var x) = 1"
| "height_trm2 (App l r) = max (height_trm2 l) (height_trm2 r)"
| "set (bn as) \<sharp>* fv_bn as \<Longrightarrow> height_trm2 (Let as b) = max (height_assn2 as) (height_trm2 b)"
| "height_assn2 (Assn x t) = (height_trm2 t)"
thm height_trm2_height_assn2_graph.intros[no_vars]
thm height_trm2_height_assn2_graph_def
apply (simp only: eqvt_def height_trm2_height_assn2_graph_def)
apply (rule, perm_simp, rule)
-- "invariant"
apply(simp)
<<<<<<< variant A
apply(simp)
apply(simp)
apply(simp)
apply(simp add: alpha_bn_preserve_def)
apply(simp add: height_assn2_def)
apply(simp add: trm_assn.perm_bn_simps)
apply(rule allI)
thm height_trm2_height_assn2_graph.intros[no_vars]
thm height_trm2_height_assn2_sumC_def
apply(rule cheat)
apply -
>>>>>>> variant B
####### Ancestor
apply(simp)
apply(simp)
apply(simp)
apply(rule cheat)
apply -
======= end
--"completeness"
apply (case_tac x)
apply(simp)
apply (rule_tac y="a" and c="a" in trm_assn.strong_exhaust(1))
apply (auto simp add: alpha_bn_refl)[3]
apply (drule_tac x="assn" in meta_spec)
apply (drule_tac x="trm" in meta_spec)
apply(simp add: alpha_bn_refl)
apply(rotate_tac 3)
apply(drule meta_mp)
apply(simp add: fresh_star_def trm_assn.fresh)
apply(simp add: fresh_def)
apply(subst supp_finite_atom_set)
apply(simp)
apply(simp)
apply(simp)
apply (case_tac b rule: trm_assn.exhaust(2))
apply (auto)[1]
apply(simp_all)[7]
prefer 2
apply(simp)
prefer 2
apply(simp)
--"let case"
apply (simp only: meta_eq_to_obj_eq[OF height_trm2_def, symmetric, unfolded fun_eq_iff])
apply (simp only: meta_eq_to_obj_eq[OF height_assn2_def, symmetric, unfolded fun_eq_iff])
apply (subgoal_tac "eqvt_at height_assn2 as")
apply (subgoal_tac "eqvt_at height_assn2 asa")
apply (subgoal_tac "eqvt_at height_trm2 b")
apply (subgoal_tac "eqvt_at height_trm2 ba")
apply (thin_tac "eqvt_at height_trm2_height_assn2_sumC (Inr as)")
apply (thin_tac "eqvt_at height_trm2_height_assn2_sumC (Inr asa)")
apply (thin_tac "eqvt_at height_trm2_height_assn2_sumC (Inl b)")
apply (thin_tac "eqvt_at height_trm2_height_assn2_sumC (Inl ba)")
defer
apply (simp add: eqvt_at_def height_trm2_def)
apply (simp add: eqvt_at_def height_trm2_def)
apply (simp add: eqvt_at_def height_assn2_def)
apply (simp add: eqvt_at_def height_assn2_def)
apply (subgoal_tac "height_assn2 as = height_assn2 asa")
apply (subgoal_tac "height_trm2 b = height_trm2 ba")
apply simp
apply(simp)
apply(erule conjE)+
apply(erule alpha_bn_cases)
apply(simp)
apply(simp add: trm_assn.bn_defs)
apply(erule_tac c="()" in Abs_lst_fcb2)
apply(simp_all add: fresh_star_def pure_fresh)[3]
apply(simp add: eqvt_at_def)
apply(simp add: eqvt_at_def)
apply(drule Inl_inject)
apply(simp (no_asm_use))
apply(clarify)
apply(erule alpha_bn_cases)
apply(simp del: trm_assn.eq_iff)
apply(simp only: trm_assn.bn_defs)
<<<<<<< variant A
apply(erule_tac c="()" in Abs_lst1_fcb2')
apply(simp_all add: fresh_star_def pure_fresh)[3]
apply(simp add: eqvt_at_bn_def)
apply(simp add: trm_assn.perm_bn_simps)
apply(simp add: eqvt_at_bn_def)
apply(simp add: trm_assn.perm_bn_simps)
done
>>>>>>> variant B
apply(erule_tac c="(trm_rawa)" in Abs_lst1_fcb2')
apply(simp_all add: fresh_star_def pure_fresh)[2]
apply(simp add: trm_assn.supp)
apply(simp add: fresh_def)
apply(subst (asm) supp_finite_atom_set)
apply(simp add: finite_supp)
apply(subst (asm) supp_finite_atom_set)
apply(simp add: finite_supp)
apply(simp)
apply(simp add: eqvt_at_def perm_supp_eq)
apply(simp add: eqvt_at_def perm_supp_eq)
done
####### Ancestor
apply(erule_tac c="()" in Abs_lst1_fcb2')
apply(simp_all add: fresh_star_def pure_fresh)[3]
oops
======= end
termination by lexicographic_order
lemma ww1:
shows "finite (fv_trm t)"
and "finite (fv_bn as)"
apply(induct t and as rule: trm_assn.inducts)
apply(simp_all add: trm_assn.fv_defs supp_at_base)
done
text {* works, but only because no recursion in as *}
nominal_function (invariant "\<lambda>x (y::atom set). finite y")
frees_set :: "trm \<Rightarrow> atom set"
where
"frees_set (Var x) = {atom x}"
| "frees_set (App t1 t2) = frees_set t1 \<union> frees_set t2"
| "frees_set (Let as t) = (frees_set t) - (set (bn as)) \<union> (fv_bn as)"
apply(simp add: eqvt_def frees_set_graph_def)
apply(rule, perm_simp, rule)
apply(erule frees_set_graph.induct)
apply(auto simp add: ww1)[3]
apply(rule_tac y="x" in trm_assn.exhaust(1))
apply(auto simp add: alpha_bn_refl)[3]
apply(drule_tac x="assn" in meta_spec)
apply(drule_tac x="trm" in meta_spec)
apply(simp add: alpha_bn_refl)
apply(simp_all)[5]
apply(simp)
apply(erule conjE)
apply(erule alpha_bn_cases)
apply(simp add: trm_assn.bn_defs)
apply(simp add: trm_assn.fv_defs)
(* apply(erule_tac c="(trm_rawa)" in Abs_lst1_fcb2) *)
apply(subgoal_tac " frees_set_sumC t - {atom name} = frees_set_sumC ta - {atom namea}")
apply(simp)
apply(erule_tac c="()" in Abs_lst1_fcb2)
apply(simp add: fresh_minus_atom_set)
apply(simp add: fresh_star_def fresh_Unit)
apply(simp add: Diff_eqvt eqvt_at_def, perm_simp, rule refl)
apply(simp add: Diff_eqvt eqvt_at_def, perm_simp, rule refl)
done
termination
by lexicographic_order
lemma test:
assumes a: "\<exists>y. f x = Inl y"
shows "(p \<bullet> (Sum_Type.Projl (f x))) = Sum_Type.Projl ((p \<bullet> f) (p \<bullet> x))"
using a
apply clarify
apply(frule_tac p="p" in permute_boolI)
apply(simp (no_asm_use) only: eqvts)
apply(subst (asm) permute_fun_app_eq)
back
apply(simp)
done
nominal_function (default "sum_case (\<lambda>x. Inl undefined) (\<lambda>x. Inr undefined)")
subst_trm2 :: "trm \<Rightarrow> name \<Rightarrow> trm \<Rightarrow> trm" ("_ [_ ::trm2= _]" [90, 90, 90] 90) and
subst_assn2 :: "assn \<Rightarrow> name \<Rightarrow> trm \<Rightarrow> assn" ("_ [_ ::assn2= _]" [90, 90, 90] 90)
where
"(Var x)[y ::trm2= s] = (if x = y then s else (Var x))"
| "(App t1 t2)[y ::trm2= s] = App (t1[y ::trm2= s]) (t2[y ::trm2= s])"
| "(set (bn as)) \<sharp>* (y, s, fv_bn as) \<Longrightarrow> (Let as t)[y ::trm2= s] = Let (ast[y ::assn2= s]) (t[y ::trm2= s])"
| "(Assn x t)[y ::assn2= s] = Assn x (t[y ::trm2= s])"
apply(subgoal_tac "\<And>p x r. subst_trm2_subst_assn2_graph x r \<Longrightarrow> subst_trm2_subst_assn2_graph (p \<bullet> x) (p \<bullet> r)")
apply(simp add: eqvt_def)
apply(rule allI)
apply(simp add: permute_fun_def permute_bool_def)
apply(rule ext)
apply(rule ext)
apply(rule iffI)
apply(drule_tac x="p" in meta_spec)
apply(drule_tac x="- p \<bullet> x" in meta_spec)
apply(drule_tac x="- p \<bullet> xa" in meta_spec)
apply(simp)
apply(drule_tac x="-p" in meta_spec)
apply(drule_tac x="x" in meta_spec)
apply(drule_tac x="xa" in meta_spec)
apply(simp)
--"Eqvt One way"
defer
apply(rule TrueI)
apply(case_tac x)
apply(simp)
apply(case_tac a)
apply(simp)
apply(rule_tac y="aa" and c="(b, c, aa)" in trm_assn.strong_exhaust(1))
apply(blast)+
apply(simp)
apply(drule_tac x="assn" in meta_spec)
apply(drule_tac x="b" in meta_spec)
apply(drule_tac x="c" in meta_spec)
apply(drule_tac x="trm" in meta_spec)
apply(simp add: trm_assn.alpha_refl)
apply(rotate_tac 5)
apply(drule meta_mp)
apply(simp add: fresh_star_Pair)
apply(simp add: fresh_star_def trm_assn.fresh)
apply(simp add: fresh_def)
apply(subst supp_finite_atom_set)
apply(simp)
apply(simp)
apply(simp)
apply(case_tac b)
apply(simp)
apply(rule_tac y="a" in trm_assn.exhaust(2))
apply(simp)
apply(blast)
--"compatibility"
apply(all_trivials)
apply(simp)
apply(simp)
prefer 2
apply(simp)
apply(drule Inl_inject)
apply(rule arg_cong)
back
apply (simp only: meta_eq_to_obj_eq[OF subst_trm2_def, symmetric, unfolded fun_eq_iff])
apply (simp only: meta_eq_to_obj_eq[OF subst_assn2_def, symmetric, unfolded fun_eq_iff])
apply (subgoal_tac "eqvt_at (\<lambda>ast. subst_assn2 ast ya sa) ast")
apply (subgoal_tac "eqvt_at (\<lambda>asta. subst_assn2 asta ya sa) asta")
apply (subgoal_tac "eqvt_at (\<lambda>t. subst_trm2 t ya sa) t")
apply (subgoal_tac "eqvt_at (\<lambda>ta. subst_trm2 ta ya sa) ta")
apply (thin_tac "eqvt_at subst_trm2_subst_assn2_sumC (Inr (ast, y, s))")
apply (thin_tac "eqvt_at subst_trm2_subst_assn2_sumC (Inr (asta, ya, sa))")
apply (thin_tac "eqvt_at subst_trm2_subst_assn2_sumC (Inl (t, y, s))")
apply (thin_tac "eqvt_at subst_trm2_subst_assn2_sumC (Inl (ta, ya, sa))")
apply(simp)
(* HERE *)
apply (subgoal_tac "subst_assn2 ast y s= subst_assn2 asta ya sa")
apply (subgoal_tac "subst_trm2 t y s = subst_trm2 ta ya sa")
apply(simp)
apply(simp)
apply(erule_tac conjE)+
apply(erule alpha_bn_cases)
apply(simp add: trm_assn.bn_defs)
apply(rotate_tac 7)
apply (erule_tac c="(ya,sa)" in Abs_lst1_fcb2)
apply(erule fresh_eqvt_at)
thm fresh_eqvt_at
apply(simp add: Abs_fresh_iff)
apply(simp add: fresh_star_def fresh_Pair)
apply(simp add: eqvt_at_def atom_eqvt fresh_star_Pair perm_supp_eq)
apply(simp add: eqvt_at_def atom_eqvt fresh_star_Pair perm_supp_eq)
apply(simp_all add: fresh_star_def fresh_Pair_elim)[1]
apply(blast)
apply(simp_all)[5]
apply(simp (no_asm_use))
apply(simp)
apply(erule conjE)+
apply (erule_tac c="(ya,sa)" in Abs_lst1_fcb2)
apply(simp add: Abs_fresh_iff)
apply(simp add: fresh_star_def fresh_Pair)
apply(simp add: eqvt_at_def atom_eqvt fresh_star_Pair perm_supp_eq)
apply(simp add: eqvt_at_def atom_eqvt fresh_star_Pair perm_supp_eq)
done
end
|
--
-- FullConnLayer : fully connected layer
--
module CNN.FullConnLayer (
initFilterF
, zeroFilterF
, connect
, deconnect
, reverseFullConnFilter
, updateFullConnFilter
) where
import Control.Monad hiding (msum)
--import Data.List
import Data.Maybe
import Debug.Trace
import Numeric.LinearAlgebra
import System.Random.Mersenne as MT
import CNN.Algebra
import CNN.Image
import CNN.LayerType
{- |
initFilterF
IN : #kernel
#channel
OUT: filter of fully connected layer
OUT: filter of fully connected layer
>>> f <- initFilterF 3 20
>>> rows f
3
>>> cols f
21
-}
initFilterF :: Int -> Int -> IO FilterF
initFilterF k c = do
rs <- forM [1..k] $ \i -> do
w <- forM [1..c] $ \j -> do
r <- MT.randomIO :: IO Double
return ((r * 2.0 - 1.0) * a)
return (0.0:w)
return $ fromLists rs
where
--a = 1.0 / fromIntegral c
a = 4.0 * sqrt (6.0 / fromIntegral (c + k))
--a = sqrt (6.0 / fromIntegral (c + k))
zeroFilterF :: Int -> Int -> IO FilterF
zeroFilterF k c = return $ (k><(c+1)) $ repeat 0.0
--
{- |
connect
IN : filter of fully connected layer
image
OUT: updated image
>>> let fs = fromLists [[0.5,1.0,2.0,3.0],[0.1,4.0,5.0,6.0]]
>>> let im = [fromLists [[9.0,8.0,7.0]]]
>>> connect fs im
[(1><2)
[ 46.5, 118.1 ]]
>>> connect fs []
*** Exception: invalid Image
CallStack (from HasCallStack):
error, called at CNN/FullConnLayer.hs:82:16 in main:CNN.FullConnLayer
-}
connect :: FilterF -> Image -> Image
connect _ [] = error "invalid Image"
connect fs [im] = [reshape (rows fs) $ fs #> v]
where
v = vjoin [konst 1.0 1, flatten im]
-- back prop
{- |
deconnect
IN : filter of fully connected layer
image
difference from previous layer
OUT: difference and updated layer
>>> let im = [fromLists [[1.0, 2.0, 3.0]]]
>>> let delta = [fromLists [[1.0, 2.0]]]
>>> let fs = fromLists [[1.0, 2.0],[3.0,4.0],[5.0,6.0]]
>>> let (d,l) = deconnect fs im delta
>>> d
[(1><2)
[ 11.0, 17.0 ]]
>>> l
Just FullConnLayer:(2><4)
[ 1.0, 1.0, 2.0, 3.0
, 2.0, 2.0, 4.0, 6.0 ]
-}
deconnect :: FilterF -> Image -> Delta -> (Delta, Maybe Layer)
deconnect fs im delta = ([reshape (rows fs') $ fs' #> dl]
, Just (FullConnLayer $ outer dl im'))
where
dl = flatten $ head delta -- to Vector
fs' = dropRows 1 fs
im' = vjoin [konst 1.0 1, flatten $ head im]
-- reverse
reverseFullConnFilter :: FilterF -> Layer
reverseFullConnFilter fs = FullConnLayer $ tr' fs
-- update filter
updateFullConnFilter :: FilterF -> Double -> [Maybe Layer] -> Layer
updateFullConnFilter fs lr dl
| dl' == [] = FullConnLayer fs
| otherwise = FullConnLayer fs'
where
dl' = catMaybes dl
delta = mscale (lr / fromIntegral (length dl')) (msum $ strip dl')
fs' = msub fs delta
strip :: [Layer] -> [FilterF]
strip [] = []
strip (FullConnLayer fs:ds) = fs:strip ds
strip (_:ds) = strip ds
|
module Properties.Contradiction where
data ⊥ : Set where
¬ : Set → Set
¬ A = A → ⊥
CONTRADICTION : ∀ {A : Set} → ⊥ → A
CONTRADICTION ()
|
State Before: 𝕜 : Type u_1
E : Type ?u.86645
F : Type ?u.86648
β : Type u_2
inst✝⁷ : OrderedSemiring 𝕜
inst✝⁶ : AddCommMonoid E
inst✝⁵ : AddCommMonoid F
inst✝⁴ : Module 𝕜 E
inst✝³ : Module 𝕜 F
s : Set E
x : E
inst✝² : OrderedCancelAddCommMonoid β
inst✝¹ : Module 𝕜 β
inst✝ : OrderedSMul 𝕜 β
r : β
⊢ Convex 𝕜 (Iio r) State After: 𝕜 : Type u_1
E : Type ?u.86645
F : Type ?u.86648
β : Type u_2
inst✝⁷ : OrderedSemiring 𝕜
inst✝⁶ : AddCommMonoid E
inst✝⁵ : AddCommMonoid F
inst✝⁴ : Module 𝕜 E
inst✝³ : Module 𝕜 F
s : Set E
x✝ : E
inst✝² : OrderedCancelAddCommMonoid β
inst✝¹ : Module 𝕜 β
inst✝ : OrderedSMul 𝕜 β
r x : β
hx : x ∈ Iio r
y : β
hy : y ∈ Iio r
a b : 𝕜
ha : 0 ≤ a
hb : 0 ≤ b
hab : a + b = 1
⊢ a • x + b • y ∈ Iio r Tactic: intro x hx y hy a b ha hb hab State Before: 𝕜 : Type u_1
E : Type ?u.86645
F : Type ?u.86648
β : Type u_2
inst✝⁷ : OrderedSemiring 𝕜
inst✝⁶ : AddCommMonoid E
inst✝⁵ : AddCommMonoid F
inst✝⁴ : Module 𝕜 E
inst✝³ : Module 𝕜 F
s : Set E
x✝ : E
inst✝² : OrderedCancelAddCommMonoid β
inst✝¹ : Module 𝕜 β
inst✝ : OrderedSMul 𝕜 β
r x : β
hx : x ∈ Iio r
y : β
hy : y ∈ Iio r
a b : 𝕜
ha : 0 ≤ a
hb : 0 ≤ b
hab : a + b = 1
⊢ a • x + b • y ∈ Iio r State After: case inl
𝕜 : Type u_1
E : Type ?u.86645
F : Type ?u.86648
β : Type u_2
inst✝⁷ : OrderedSemiring 𝕜
inst✝⁶ : AddCommMonoid E
inst✝⁵ : AddCommMonoid F
inst✝⁴ : Module 𝕜 E
inst✝³ : Module 𝕜 F
s : Set E
x✝ : E
inst✝² : OrderedCancelAddCommMonoid β
inst✝¹ : Module 𝕜 β
inst✝ : OrderedSMul 𝕜 β
r x : β
hx : x ∈ Iio r
y : β
hy : y ∈ Iio r
b : 𝕜
hb : 0 ≤ b
ha : 0 ≤ 0
hab : 0 + b = 1
⊢ 0 • x + b • y ∈ Iio r
case inr
𝕜 : Type u_1
E : Type ?u.86645
F : Type ?u.86648
β : Type u_2
inst✝⁷ : OrderedSemiring 𝕜
inst✝⁶ : AddCommMonoid E
inst✝⁵ : AddCommMonoid F
inst✝⁴ : Module 𝕜 E
inst✝³ : Module 𝕜 F
s : Set E
x✝ : E
inst✝² : OrderedCancelAddCommMonoid β
inst✝¹ : Module 𝕜 β
inst✝ : OrderedSMul 𝕜 β
r x : β
hx : x ∈ Iio r
y : β
hy : y ∈ Iio r
a b : 𝕜
ha : 0 ≤ a
hb : 0 ≤ b
hab : a + b = 1
ha' : 0 < a
⊢ a • x + b • y ∈ Iio r Tactic: obtain rfl | ha' := ha.eq_or_lt State Before: case inr
𝕜 : Type u_1
E : Type ?u.86645
F : Type ?u.86648
β : Type u_2
inst✝⁷ : OrderedSemiring 𝕜
inst✝⁶ : AddCommMonoid E
inst✝⁵ : AddCommMonoid F
inst✝⁴ : Module 𝕜 E
inst✝³ : Module 𝕜 F
s : Set E
x✝ : E
inst✝² : OrderedCancelAddCommMonoid β
inst✝¹ : Module 𝕜 β
inst✝ : OrderedSMul 𝕜 β
r x : β
hx : x ∈ Iio r
y : β
hy : y ∈ Iio r
a b : 𝕜
ha : 0 ≤ a
hb : 0 ≤ b
hab : a + b = 1
ha' : 0 < a
⊢ a • x + b • y ∈ Iio r State After: case inr
𝕜 : Type u_1
E : Type ?u.86645
F : Type ?u.86648
β : Type u_2
inst✝⁷ : OrderedSemiring 𝕜
inst✝⁶ : AddCommMonoid E
inst✝⁵ : AddCommMonoid F
inst✝⁴ : Module 𝕜 E
inst✝³ : Module 𝕜 F
s : Set E
x✝ : E
inst✝² : OrderedCancelAddCommMonoid β
inst✝¹ : Module 𝕜 β
inst✝ : OrderedSMul 𝕜 β
r x : β
hx : x < r
y : β
hy : y < r
a b : 𝕜
ha : 0 ≤ a
hb : 0 ≤ b
hab : a + b = 1
ha' : 0 < a
⊢ a • x + b • y ∈ Iio r Tactic: rw [mem_Iio] at hx hy State Before: case inr
𝕜 : Type u_1
E : Type ?u.86645
F : Type ?u.86648
β : Type u_2
inst✝⁷ : OrderedSemiring 𝕜
inst✝⁶ : AddCommMonoid E
inst✝⁵ : AddCommMonoid F
inst✝⁴ : Module 𝕜 E
inst✝³ : Module 𝕜 F
s : Set E
x✝ : E
inst✝² : OrderedCancelAddCommMonoid β
inst✝¹ : Module 𝕜 β
inst✝ : OrderedSMul 𝕜 β
r x : β
hx : x < r
y : β
hy : y < r
a b : 𝕜
ha : 0 ≤ a
hb : 0 ≤ b
hab : a + b = 1
ha' : 0 < a
⊢ a • x + b • y ∈ Iio r State After: no goals Tactic: calc
a • x + b • y < a • r + b • r :=
add_lt_add_of_lt_of_le (smul_lt_smul_of_pos hx ha') (smul_le_smul_of_nonneg hy.le hb)
_ = r := Convex.combo_self hab _ State Before: case inl
𝕜 : Type u_1
E : Type ?u.86645
F : Type ?u.86648
β : Type u_2
inst✝⁷ : OrderedSemiring 𝕜
inst✝⁶ : AddCommMonoid E
inst✝⁵ : AddCommMonoid F
inst✝⁴ : Module 𝕜 E
inst✝³ : Module 𝕜 F
s : Set E
x✝ : E
inst✝² : OrderedCancelAddCommMonoid β
inst✝¹ : Module 𝕜 β
inst✝ : OrderedSMul 𝕜 β
r x : β
hx : x ∈ Iio r
y : β
hy : y ∈ Iio r
b : 𝕜
hb : 0 ≤ b
ha : 0 ≤ 0
hab : 0 + b = 1
⊢ 0 • x + b • y ∈ Iio r State After: case inl
𝕜 : Type u_1
E : Type ?u.86645
F : Type ?u.86648
β : Type u_2
inst✝⁷ : OrderedSemiring 𝕜
inst✝⁶ : AddCommMonoid E
inst✝⁵ : AddCommMonoid F
inst✝⁴ : Module 𝕜 E
inst✝³ : Module 𝕜 F
s : Set E
x✝ : E
inst✝² : OrderedCancelAddCommMonoid β
inst✝¹ : Module 𝕜 β
inst✝ : OrderedSMul 𝕜 β
r x : β
hx : x ∈ Iio r
y : β
hy : y ∈ Iio r
b : 𝕜
hb : 0 ≤ b
ha : 0 ≤ 0
hab : b = 1
⊢ 0 • x + b • y ∈ Iio r Tactic: rw [zero_add] at hab State Before: case inl
𝕜 : Type u_1
E : Type ?u.86645
F : Type ?u.86648
β : Type u_2
inst✝⁷ : OrderedSemiring 𝕜
inst✝⁶ : AddCommMonoid E
inst✝⁵ : AddCommMonoid F
inst✝⁴ : Module 𝕜 E
inst✝³ : Module 𝕜 F
s : Set E
x✝ : E
inst✝² : OrderedCancelAddCommMonoid β
inst✝¹ : Module 𝕜 β
inst✝ : OrderedSMul 𝕜 β
r x : β
hx : x ∈ Iio r
y : β
hy : y ∈ Iio r
b : 𝕜
hb : 0 ≤ b
ha : 0 ≤ 0
hab : b = 1
⊢ 0 • x + b • y ∈ Iio r State After: no goals Tactic: rwa [zero_smul, zero_add, hab, one_smul] |
% ---------------------------------------------------
% Date: 12.12.2018
% Version: v0.1
% Autor: Felix Faltin <ffaltin91[at]gmail.com>
% Repository: https://github.com/faltfe/iodhbwm
% ---------------------------------------------------
% --- --- --- --- -- Class options -- --- --- --- ---
% ---------------------------------------------------
\documentclass[
add-bibliography-, % Include bibliography (needs biber run) wihout a bibliography
bib-file = biblatex-examples.bib, % Set bibliography file
biblatex/style = authoryear, % Change used biblatex style
language = ngerman, % Set main language
debug % Provide \lipsum, \blindtext
]{iodhbwm}
\usepackage[T1]{fontenc}
% ---------------------------------------------------
% --- --- --- --- Begin actual content -- --- --- ---
% ---------------------------------------------------
\begin{document}
\chapter{Zitat als Fußnote}
\blindtext \footcite{doody}
\blindtext \footfullcite{doody}
\end{document}
|
[STATEMENT]
lemma d_restrict_top:
"x \<le> d(x) * top \<squnion> Z"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. x \<le> d x * top \<squnion> Z
[PROOF STEP]
by (metis sup_left_isotone d_restrict mult_right_isotone order_trans top_greatest) |
[GOAL]
α : Type u
β✝ : Type u_1
inst✝³ : OrderedCommMonoid α
β : Type u_2
inst✝² : One β
inst✝¹ : Mul β
inst✝ : Pow β ℕ
f : β → α
hf : Injective f
one : f 1 = 1
mul : ∀ (x y : β), f (x * y) = f x * f y
npow : ∀ (x : β) (n : ℕ), f (x ^ n) = f x ^ n
src✝¹ : PartialOrder β := PartialOrder.lift f hf
src✝ : CommMonoid β := Injective.commMonoid f hf one mul npow
a b : β
ab : a ≤ b
c : β
⊢ f (c * a) ≤ f (c * b)
[PROOFSTEP]
rw [mul, mul]
[GOAL]
α : Type u
β✝ : Type u_1
inst✝³ : OrderedCommMonoid α
β : Type u_2
inst✝² : One β
inst✝¹ : Mul β
inst✝ : Pow β ℕ
f : β → α
hf : Injective f
one : f 1 = 1
mul : ∀ (x y : β), f (x * y) = f x * f y
npow : ∀ (x : β) (n : ℕ), f (x ^ n) = f x ^ n
src✝¹ : PartialOrder β := PartialOrder.lift f hf
src✝ : CommMonoid β := Injective.commMonoid f hf one mul npow
a b : β
ab : a ≤ b
c : β
⊢ f c * f a ≤ f c * f b
[PROOFSTEP]
apply mul_le_mul_left'
[GOAL]
case bc
α : Type u
β✝ : Type u_1
inst✝³ : OrderedCommMonoid α
β : Type u_2
inst✝² : One β
inst✝¹ : Mul β
inst✝ : Pow β ℕ
f : β → α
hf : Injective f
one : f 1 = 1
mul : ∀ (x y : β), f (x * y) = f x * f y
npow : ∀ (x : β) (n : ℕ), f (x ^ n) = f x ^ n
src✝¹ : PartialOrder β := PartialOrder.lift f hf
src✝ : CommMonoid β := Injective.commMonoid f hf one mul npow
a b : β
ab : a ≤ b
c : β
⊢ f a ≤ f b
[PROOFSTEP]
exact ab
[GOAL]
α : Type u
β : Type u_1
inst✝⁴ : Mul α
inst✝³ : LinearOrder α
inst✝² : CovariantClass α α (fun x x_1 => x * x_1) fun x x_1 => x ≤ x_1
inst✝¹ : CovariantClass α α (swap fun x x_1 => x * x_1) fun x x_1 => x < x_1
inst✝ : ContravariantClass α α (fun x x_1 => x * x_1) fun x x_1 => x ≤ x_1
a b a0 b0 : α
ha : a0 ≤ a
hb : b0 ≤ b
ab : a * b ≤ a0 * b0
⊢ a = a0 ∧ b = b0
[PROOFSTEP]
haveI := Mul.to_covariantClass_right α
[GOAL]
α : Type u
β : Type u_1
inst✝⁴ : Mul α
inst✝³ : LinearOrder α
inst✝² : CovariantClass α α (fun x x_1 => x * x_1) fun x x_1 => x ≤ x_1
inst✝¹ : CovariantClass α α (swap fun x x_1 => x * x_1) fun x x_1 => x < x_1
inst✝ : ContravariantClass α α (fun x x_1 => x * x_1) fun x x_1 => x ≤ x_1
a b a0 b0 : α
ha : a0 ≤ a
hb : b0 ≤ b
ab : a * b ≤ a0 * b0
this : CovariantClass α α (swap fun x x_1 => x * x_1) fun x x_1 => x ≤ x_1
⊢ a = a0 ∧ b = b0
[PROOFSTEP]
have ha' : ¬a0 * b0 < a * b → ¬a0 < a := mt (mul_lt_mul_of_lt_of_le · hb)
[GOAL]
α : Type u
β : Type u_1
inst✝⁴ : Mul α
inst✝³ : LinearOrder α
inst✝² : CovariantClass α α (fun x x_1 => x * x_1) fun x x_1 => x ≤ x_1
inst✝¹ : CovariantClass α α (swap fun x x_1 => x * x_1) fun x x_1 => x < x_1
inst✝ : ContravariantClass α α (fun x x_1 => x * x_1) fun x x_1 => x ≤ x_1
a b a0 b0 : α
ha : a0 ≤ a
hb : b0 ≤ b
ab : a * b ≤ a0 * b0
this : CovariantClass α α (swap fun x x_1 => x * x_1) fun x x_1 => x ≤ x_1
ha' : ¬a0 * b0 < a * b → ¬a0 < a
⊢ a = a0 ∧ b = b0
[PROOFSTEP]
have hb' : ¬a0 * b0 < a * b → ¬b0 < b := mt (mul_lt_mul_of_le_of_lt ha ·)
[GOAL]
α : Type u
β : Type u_1
inst✝⁴ : Mul α
inst✝³ : LinearOrder α
inst✝² : CovariantClass α α (fun x x_1 => x * x_1) fun x x_1 => x ≤ x_1
inst✝¹ : CovariantClass α α (swap fun x x_1 => x * x_1) fun x x_1 => x < x_1
inst✝ : ContravariantClass α α (fun x x_1 => x * x_1) fun x x_1 => x ≤ x_1
a b a0 b0 : α
ha : a0 ≤ a
hb : b0 ≤ b
ab : a * b ≤ a0 * b0
this : CovariantClass α α (swap fun x x_1 => x * x_1) fun x x_1 => x ≤ x_1
ha' : ¬a0 * b0 < a * b → ¬a0 < a
hb' : ¬a0 * b0 < a * b → ¬b0 < b
⊢ a = a0 ∧ b = b0
[PROOFSTEP]
push_neg at ha' hb'
[GOAL]
α : Type u
β : Type u_1
inst✝⁴ : Mul α
inst✝³ : LinearOrder α
inst✝² : CovariantClass α α (fun x x_1 => x * x_1) fun x x_1 => x ≤ x_1
inst✝¹ : CovariantClass α α (swap fun x x_1 => x * x_1) fun x x_1 => x < x_1
inst✝ : ContravariantClass α α (fun x x_1 => x * x_1) fun x x_1 => x ≤ x_1
a b a0 b0 : α
ha : a0 ≤ a
hb : b0 ≤ b
ab : a * b ≤ a0 * b0
this : CovariantClass α α (swap fun x x_1 => x * x_1) fun x x_1 => x ≤ x_1
ha' : a * b ≤ a0 * b0 → a ≤ a0
hb' : a * b ≤ a0 * b0 → b ≤ b0
⊢ a = a0 ∧ b = b0
[PROOFSTEP]
exact ⟨ha.antisymm' (ha' ab), hb.antisymm' (hb' ab)⟩
|
One of my guilty pleasures in photography is to capture images of masterworks from some of my favorite painters. But with a twist. Rather than reproduce the entirety of the painting with my camera, I will find a discrete composition within the painting and then capture it. I also enhance the colors, tweak shadows, add contrast where necessary, and generally give it a richer look. Over hundreds of years, these paintings fade and crack. I love “restoring” them in post processing.
This painting, “Consecration of the Emperor Napoleon I and Coronation of the Empress Josephine in the Cathedral of Notre-Dame de Paris,” was completed in 1808 by Jacques-Louis David, who was the official painter of Napoleon. He was a brilliant painter. This painting, which is located at the Louvre, measures about 32 feet wide by 20 feet tall. It’s a true masterpiece and a sight to behold. Still, within this painting there were several compositions, including the vertical composition you see here. All eyes were on Napoleon and Josephine and I chose to zero in on the two of them.
I invite you to check out the entire painting. Do a Google search or visit it in person at the Louvre in Paris. You’ll be able to see what I was thinking with my composition and you’ll see whether I stayed true to the color palette in this oil painting. One of the most difficult parts of capturing this image was the glare from the light in the Louvre. To minimize the glare, I stood on a bench and lifted my iPhone above my head when I captured it.
Captured with my iPhone 6+ and a 60mm Moment lens.
Note: for private use only. Image not for sale. |
module PkgOptionsLoader
using Base: PkgId, package_slug, slug, _crc32c
using Pkg: TOML
macro return_if_nothing(ex)
quote
ans = $(esc(ex))
ans === nothing && return nothing
ans
end
end
project_slug() = slug(_crc32c(@return_if_nothing Base.active_project()), 5)
optionsdir() =
joinpath(Base.DEPOT_PATH[1], "options", @return_if_nothing project_slug())
optionspath(pkg::PkgId) =
joinpath(@return_if_nothing(optionsdir()),
package_slug(pkg.uuid),
pkg.name * ".toml")
function load(mod)
pkg = PkgId(mod)
if pkg.uuid === nothing
error("Cannot load package options in a non-package module ", mod)
end
tomlpath = optionspath(pkg)
if tomlpath === nothing || !isfile(tomlpath)
return Dict{String,Any}()
end
# Editing this TOML file should invalidate the cache:
Base.include_dependency(tomlpath)
return TOML.parsefile(tomlpath)
end
"""
PkgOptionsLoader.@load
Load package options for current module at _expansion time_. It
evaluates to a Dict. It is recommended to load it at the top level of
your package module:
```julia
const pkgoptions = PkgOptionsLoader.@load
```
It also is a good idea to verify options and then assign it to a `const`:
```julia
get!(pkgoptions, "FEATURE_FLAG", false) # default
if !(pkgoptions["FEATURE_FLAG"] isa Bool)
error("some helpful error message")
end
const FEATURE_FLAG::Bool = pkgoptions["FEATURE_FLAG"]
```
"""
macro load()
load(__module__)
end
end # module
|
Learn to Read from Reading Eggs, developed by Blake eLearning, who have done a fantastic job with their innovation for learning! Kids have so much fun Learning that you wouldn’t believe it! A program for Children, easy to follow, have fun and Learn to Read quickly! What more could a parent ask for when it comes to their children!
From the testimonials I have read, reviews, and now, I will be buying it for my daughter too! I just cannot compliment this program enough, and if my viewers are seeing this and Reading it, I strongly recommend you get on board and test it!
My name is Tom Cullen, I am the President and CEO of Tucker Tek Inc. I am absolutely impressed with this program, and it deserves A Five Star Rating!
Blake eLearning is a highly experienced team that specializes in creating high-quality literacy products for schools and educators throughout the world. Our educational books are successful in all major English speaking markets. Our company is a recognized leader in creating innovative, exciting programs that both teachers and children enjoy using.
The Reading Eggs program has been developed by a highly experienced team of teachers, educational writers, animators and web developers. The Reading Eggs program focuses on a core reading curriculum of skills and strategies essential for sustained reading success. It completely supports what children learn at school and will help to improve your child’s school results. |
(*
* Copyright 2020, Data61, CSIRO (ABN 41 687 119 230)
*
* SPDX-License-Identifier: GPL-2.0-only
*)
(*
Top level architecture related proofs.
*)
theory Arch_R
imports Untyped_R Finalise_R
begin
lemmas [datatype_schematic] = cap.sel list.sel(1) list.sel(3)
context begin interpretation Arch . (*FIXME: arch_split*)
declare arch_cap.sel [datatype_schematic]
declare is_aligned_shiftl [intro!]
declare is_aligned_shiftr [intro!]
definition
"asid_ci_map i \<equiv>
case i of RISCV64_A.MakePool frame slot parent base \<Rightarrow>
RISCV64_H.MakePool frame (cte_map slot) (cte_map parent) (ucast base)"
definition
"valid_aci' aci \<equiv> case aci of MakePool frame slot parent base \<Rightarrow>
\<lambda>s. cte_wp_at' (\<lambda>c. cteCap c = NullCap) slot s \<and>
cte_wp_at' (\<lambda>cte. \<exists>idx. cteCap cte = UntypedCap False frame pageBits idx) parent s \<and>
descendants_of' parent (ctes_of s) = {} \<and>
slot \<noteq> parent \<and>
ex_cte_cap_to' slot s \<and>
sch_act_simple s \<and>
is_aligned base asid_low_bits \<and> asid_wf base"
lemma vp_strgs':
"valid_pspace' s \<longrightarrow> pspace_distinct' s"
"valid_pspace' s \<longrightarrow> pspace_aligned' s"
"valid_pspace' s \<longrightarrow> valid_mdb' s"
by auto
lemma safe_parent_strg':
"cte_wp_at' (\<lambda>cte. cteCap cte = UntypedCap False frame pageBits idx) p s \<and>
descendants_of' p (ctes_of s) = {} \<and>
valid_pspace' s
\<longrightarrow> safe_parent_for' (ctes_of s) p (ArchObjectCap (ASIDPoolCap frame base))"
apply (clarsimp simp: safe_parent_for'_def cte_wp_at_ctes_of)
apply (case_tac cte)
apply (simp add: isCap_simps)
apply (subst conj_comms)
apply (rule context_conjI)
apply (drule ctes_of_valid_cap', fastforce)
apply (clarsimp simp: valid_cap'_def capAligned_def)
apply (drule is_aligned_no_overflow)
apply (clarsimp simp: capRange_def asid_low_bits_def bit_simps)
apply (clarsimp simp: sameRegionAs_def2 isCap_simps capRange_def asid_low_bits_def bit_simps)
done
lemma descendants_of'_helper:
"\<lbrace>P\<rbrace> f \<lbrace>\<lambda>r s. Q (descendants_of' t (null_filter' (ctes_of s)))\<rbrace>
\<Longrightarrow> \<lbrace>P\<rbrace> f \<lbrace>\<lambda>r s. Q (descendants_of' t (ctes_of s))\<rbrace>"
apply (clarsimp simp:valid_def)
apply (subst null_filter_descendants_of')
prefer 2
apply fastforce
apply simp
done
lemma createObject_typ_at':
"\<lbrace>\<lambda>s. koTypeOf ty = otype \<and> is_aligned ptr (objBitsKO ty) \<and>
pspace_aligned' s \<and> pspace_no_overlap' ptr (objBitsKO ty) s\<rbrace>
createObjects' ptr (Suc 0) ty 0
\<lbrace>\<lambda>rv s. typ_at' otype ptr s\<rbrace>"
supply
is_aligned_neg_mask_eq[simp del]
is_aligned_neg_mask_weaken[simp del]
apply (clarsimp simp:createObjects'_def alignError_def split_def | wp hoare_unless_wp | wpc )+
apply (clarsimp simp:obj_at'_def ko_wp_at'_def typ_at'_def pspace_distinct'_def)+
apply (subgoal_tac "ps_clear ptr (objBitsKO ty)
(s\<lparr>ksPSpace := \<lambda>a. if a = ptr then Some ty else ksPSpace s a\<rparr>)")
apply (simp add:ps_clear_def)+
apply (rule ccontr)
apply (drule int_not_emptyD)
apply clarsimp
apply (unfold pspace_no_overlap'_def)
apply (erule allE)+
apply (erule(1) impE)
apply (subgoal_tac "x \<in> mask_range x (objBitsKO y)")
apply (fastforce simp: is_aligned_neg_mask_eq)
apply (drule(1) pspace_alignedD')
apply (clarsimp simp: is_aligned_no_overflow_mask)
done
lemma retype_region2_ext_retype_region_ArchObject:
"retype_region ptr n us (ArchObject x)=
retype_region2 ptr n us (ArchObject x)"
apply (rule ext)
apply (simp add: retype_region_def retype_region2_def bind_assoc
retype_region2_ext_def retype_region_ext_def default_ext_def)
apply (rule ext)
apply (intro monad_eq_split_tail ext)+
apply simp
apply simp
apply (simp add:gets_def get_def bind_def return_def simpler_modify_def )
apply (rule_tac x = xc in fun_cong)
apply (rule_tac f = do_extended_op in arg_cong)
apply (rule ext)
apply simp
apply simp
done
lemma set_cap_device_and_range_aligned:
"is_aligned ptr sz \<Longrightarrow> \<lbrace>\<lambda>_. True\<rbrace>
set_cap
(cap.UntypedCap dev ptr sz idx)
aref
\<lbrace>\<lambda>rv s.
\<exists>slot.
cte_wp_at
(\<lambda>c. cap_is_device c = dev \<and>
up_aligned_area ptr sz \<subseteq> cap_range c)
slot s\<rbrace>"
apply (subst is_aligned_neg_mask_eq[symmetric])
apply simp
apply (wp set_cap_device_and_range)
done
lemma pac_corres:
"asid_ci_map i = i' \<Longrightarrow>
corres dc
(einvs and ct_active and valid_aci i)
(invs' and ct_active' and valid_aci' i')
(perform_asid_control_invocation i)
(performASIDControlInvocation i')"
supply
is_aligned_neg_mask_eq[simp del]
is_aligned_neg_mask_weaken[simp del]
apply (cases i)
apply (rename_tac word1 prod1 prod2 word2)
apply (clarsimp simp: asid_ci_map_def)
apply (simp add: perform_asid_control_invocation_def placeNewObject_def2
performASIDControlInvocation_def)
apply (rule corres_name_pre)
apply (clarsimp simp:valid_aci_def valid_aci'_def cte_wp_at_ctes_of cte_wp_at_caps_of_state)
apply (subgoal_tac "valid_cap' (capability.UntypedCap False word1 pageBits idx) s'")
prefer 2
apply (case_tac ctea)
apply clarsimp
apply (erule ctes_of_valid_cap')
apply fastforce
apply (frule valid_capAligned)
apply (clarsimp simp: capAligned_def page_bits_def)
apply (rule corres_guard_imp)
apply (rule corres_split)
prefer 2
apply (erule detype_corres)
apply (simp add:pageBits_def)
apply (rule corres_split[OF _ getSlotCap_corres])
apply (rule_tac F = " pcap = (cap.UntypedCap False word1 pageBits idxa)" in corres_gen_asm)
apply (rule corres_split[OF _ updateFreeIndex_corres])
apply (rule corres_split)
prefer 2
apply (simp add: retype_region2_ext_retype_region_ArchObject )
apply (rule corres_retype [where ty="Inl (KOArch (KOASIDPool F))" for F,
unfolded APIType_map2_def makeObjectKO_def,
THEN createObjects_corres',simplified,
where val = "makeObject::asidpool"])
apply simp
apply (simp add: objBits_simps obj_bits_api_def arch_kobj_size_def
default_arch_object_def)+
apply (simp add: obj_relation_retype_def default_object_def
default_arch_object_def objBits_simps)
apply (simp add: other_obj_relation_def asid_pool_relation_def)
apply (simp add: makeObject_asidpool const_def inv_def)
apply (rule range_cover_full)
apply (simp add:obj_bits_api_def arch_kobj_size_def default_arch_object_def)+
apply (rule corres_split)
prefer 2
apply (rule cins_corres_simple, simp, rule refl, rule refl)
apply (rule_tac F="asid_low_bits_of word2 = 0" in corres_gen_asm)
apply (simp add: is_aligned_mask dc_def[symmetric])
apply (rule corres_split [where P=\<top> and P'=\<top> and r'="\<lambda>t t'. t = t' o ucast"])
prefer 2
apply (clarsimp simp: state_relation_def arch_state_relation_def)
apply (rule corres_trivial)
apply (rule corres_modify)
apply (thin_tac "x \<in> state_relation" for x)
apply (clarsimp simp: state_relation_def arch_state_relation_def o_def)
apply (rule ext)
apply (clarsimp simp: up_ucast_inj_eq)
apply wp+
apply (strengthen safe_parent_strg[where idx = "2^pageBits"])
apply (strengthen invs_valid_objs invs_distinct
invs_psp_aligned invs_mdb
| simp cong:conj_cong)+
apply (wp retype_region_plain_invs[where sz = pageBits]
retype_cte_wp_at[where sz = pageBits])+
apply (strengthen vp_strgs'
safe_parent_strg'[where idx = "2^pageBits"])
apply (simp cong: conj_cong)
apply (wp createObjects_valid_pspace'
[where sz = pageBits and ty="Inl (KOArch (KOASIDPool undefined))"])
apply (simp add: makeObjectKO_def)+
apply (simp add:objBits_simps range_cover_full valid_cap'_def)+
apply (fastforce intro!: canonical_address_neq_mask simp: kernel_mappings_canonical)
apply (rule in_kernel_mappings_neq_mask, (simp add: valid_cap'_def bit_simps)+)[1]
apply (clarsimp simp:valid_cap'_def)
apply (wp createObject_typ_at'
createObjects_orig_cte_wp_at'[where sz = pageBits])
apply (rule descendants_of'_helper)
apply (wp createObjects_null_filter'
[where sz = pageBits and ty="Inl (KOArch (KOASIDPool undefined))"])
apply (clarsimp simp:is_cap_simps)
apply (simp add: free_index_of_def)
apply (clarsimp simp: conj_comms obj_bits_api_def arch_kobj_size_def
objBits_simps default_arch_object_def pred_conj_def)
apply (clarsimp simp: conj_comms
| strengthen invs_mdb invs_valid_pspace)+
apply (simp add:region_in_kernel_window_def)
apply (wp set_untyped_cap_invs_simple[where sz = pageBits]
set_cap_cte_wp_at
set_cap_caps_no_overlap[where sz = pageBits]
set_cap_no_overlap
set_cap_device_and_range_aligned[where dev = False,simplified]
set_untyped_cap_caps_overlap_reserved[where sz = pageBits])+
apply (clarsimp simp: conj_comms obj_bits_api_def arch_kobj_size_def
objBits_simps default_arch_object_def
makeObjectKO_def range_cover_full
simp del: capFreeIndex_update.simps
| strengthen invs_valid_pspace' invs_pspace_aligned'
invs_pspace_distinct'
exI[where x="makeObject :: asidpool"])+
apply (wp updateFreeIndex_forward_invs'
updateFreeIndex_pspace_no_overlap'
updateFreeIndex_caps_no_overlap''
updateFreeIndex_descendants_of2
updateFreeIndex_cte_wp_at
updateFreeIndex_caps_overlap_reserved
| simp add: descendants_of_null_filter' split del: if_split)+
apply (wp get_cap_wp)+
apply (subgoal_tac "word1 && ~~ mask pageBits = word1 \<and> pageBits \<le> word_bits \<and> word_size_bits \<le> pageBits")
prefer 2
apply (clarsimp simp:bit_simps word_bits_def is_aligned_neg_mask_eq)
apply (simp only:delete_objects_rewrite)
apply wp+
apply (clarsimp simp: conj_comms)
apply (clarsimp simp: conj_comms ex_disj_distrib
| strengthen invs_valid_pspace' invs_pspace_aligned'
invs_pspace_distinct')+
apply (wp deleteObjects_invs'[where p="makePoolParent i'"]
deleteObjects_cte_wp_at'
deleteObjects_descendants[where p="makePoolParent i'"])
apply (clarsimp split del: if_split simp:valid_cap'_def)
apply (wp hoare_vcg_ex_lift
deleteObjects_caps_no_overlap''[where slot="makePoolParent i'"]
deleteObject_no_overlap
deleteObjects_ct_active'[where cref="makePoolParent i'"])
apply (clarsimp simp: is_simple_cap_def valid_cap'_def max_free_index_def is_cap_simps
cong: conj_cong)
apply (strengthen empty_descendants_range_in')
apply (wp deleteObjects_descendants[where p="makePoolParent i'"]
deleteObjects_cte_wp_at'
deleteObjects_null_filter[where p="makePoolParent i'"])
apply (clarsimp simp:invs_mdb max_free_index_def invs_untyped_children)
apply (subgoal_tac "detype_locale x y sa" for x y)
prefer 2
apply (simp add:detype_locale_def)
apply (fastforce simp:cte_wp_at_caps_of_state descendants_range_def2
empty_descendants_range_in invs_untyped_children)
apply (intro conjI)
apply (clarsimp)
apply (erule(1) caps_of_state_valid)
subgoal by (fastforce simp:cte_wp_at_caps_of_state descendants_range_def2 empty_descendants_range_in)
apply (fold_subgoals (prefix))[2]
subgoal premises prems using prems by (clarsimp simp:invs_def valid_state_def)+
apply (clarsimp simp:cte_wp_at_caps_of_state)
apply (drule detype_locale.non_null_present)
apply (fastforce simp:cte_wp_at_caps_of_state)
apply simp
apply (frule_tac ptr = "(aa,ba)" in detype_invariants [rotated 3])
apply fastforce
apply simp
apply (simp add: cte_wp_at_caps_of_state)
apply (simp add: is_cap_simps)
apply (simp add:empty_descendants_range_in descendants_range_def2)
apply (frule intvl_range_conv[where bits = pageBits])
apply (clarsimp simp:pageBits_def word_bits_def)
apply (clarsimp simp: invs_valid_objs cte_wp_at_caps_of_state range_cover_full
invs_psp_aligned invs_distinct cap_master_cap_simps is_cap_simps
is_simple_cap_def)
apply (clarsimp simp: conj_comms)
apply (rule conjI, clarsimp simp: is_aligned_asid_low_bits_of_zero)
apply (frule ex_cte_cap_protects)
apply (simp add:cte_wp_at_caps_of_state)
apply (simp add:empty_descendants_range_in)
apply fastforce
apply (rule subset_refl)
apply fastforce
apply (clarsimp simp: is_simple_cap_arch_def)
apply (rule conjI, clarsimp)
apply (rule conjI, clarsimp simp: clear_um_def)
apply (simp add:detype_clear_um_independent)
apply (rule conjI)
apply clarsimp
apply (drule_tac p = "(aa,ba)" in cap_refs_in_kernel_windowD2[OF caps_of_state_cteD])
apply fastforce
apply (clarsimp simp: region_in_kernel_window_def valid_cap_def
cap_aligned_def is_aligned_neg_mask_eq detype_def clear_um_def)
apply fastforce
apply (rule conjI,erule caps_no_overlap_detype[OF descendants_range_caps_no_overlapI])
apply (clarsimp simp:is_aligned_neg_mask_eq cte_wp_at_caps_of_state)
apply (simp add:empty_descendants_range_in)+
apply (rule conjI, rule pspace_no_overlap_subset,
rule pspace_no_overlap_detype[OF caps_of_state_valid])
apply (simp add:invs_psp_aligned invs_valid_objs is_aligned_neg_mask_eq)+
apply (clarsimp simp: detype_def clear_um_def detype_ext_def valid_sched_def valid_etcbs_def
st_tcb_at_kh_def obj_at_kh_def st_tcb_at_def obj_at_def is_etcb_at_def)
apply (simp add: detype_def clear_um_def)
apply (drule_tac x = "cte_map (aa,ba)" in pspace_relation_cte_wp_atI[OF state_relation_pspace_relation])
apply (simp add:invs_valid_objs)+
apply clarsimp
apply (drule cte_map_inj_eq)
apply ((fastforce simp:cte_wp_at_caps_of_state)+)[5]
apply (clarsimp simp:cte_wp_at_caps_of_state invs_valid_pspace' conj_comms cte_wp_at_ctes_of
valid_cap_simps')
apply (strengthen refl)
apply clarsimp
apply (frule empty_descendants_range_in')
apply (intro conjI,
simp_all add: is_simple_cap'_def isCap_simps descendants_range'_def2
null_filter_descendants_of'[OF null_filter_simp']
capAligned_def asid_low_bits_def)
apply (erule descendants_range_caps_no_overlapI')
apply (fastforce simp:cte_wp_at_ctes_of is_aligned_neg_mask_eq)
apply (simp add:empty_descendants_range_in')
apply (simp add:word_bits_def bit_simps)
apply (rule is_aligned_weaken)
apply (rule is_aligned_shiftl_self[unfolded shiftl_t2n,where p = 1,simplified])
apply (simp add:pageBits_def)
apply clarsimp
apply (drule(1) cte_cap_in_untyped_range)
apply (fastforce simp:cte_wp_at_ctes_of)
apply assumption+
apply fastforce
apply simp
apply clarsimp
apply (drule (1) cte_cap_in_untyped_range)
apply (fastforce simp add: cte_wp_at_ctes_of)
apply assumption+
apply (clarsimp simp: invs'_def valid_state'_def if_unsafe_then_cap'_def cte_wp_at_ctes_of)
apply fastforce
apply simp
done
definition
archinv_relation :: "arch_invocation \<Rightarrow> Arch.invocation \<Rightarrow> bool"
where
"archinv_relation ai ai' \<equiv> case ai of
arch_invocation.InvokePageTable pti \<Rightarrow>
\<exists>pti'. ai' = InvokePageTable pti' \<and> page_table_invocation_map pti pti'
| arch_invocation.InvokePage pgi \<Rightarrow>
\<exists>pgi'. ai' = InvokePage pgi' \<and> page_invocation_map pgi pgi'
| arch_invocation.InvokeASIDControl aci \<Rightarrow>
\<exists>aci'. ai' = InvokeASIDControl aci' \<and> aci' = asid_ci_map aci
| arch_invocation.InvokeASIDPool ap \<Rightarrow>
\<exists>ap'. ai' = InvokeASIDPool ap' \<and> ap' = asid_pool_invocation_map ap"
definition
valid_arch_inv' :: "Arch.invocation \<Rightarrow> kernel_state \<Rightarrow> bool"
where
"valid_arch_inv' ai \<equiv> case ai of
InvokePageTable pti \<Rightarrow> valid_pti' pti
| InvokePage pgi \<Rightarrow> valid_page_inv' pgi
| InvokeASIDControl aci \<Rightarrow> valid_aci' aci
| InvokeASIDPool ap \<Rightarrow> valid_apinv' ap"
lemma mask_vmrights_corres:
"maskVMRights (vmrights_map R) (rightsFromWord d) =
vmrights_map (mask_vm_rights R (data_to_rights d))"
by (clarsimp simp: rightsFromWord_def data_to_rights_def
vmrights_map_def Let_def maskVMRights_def
mask_vm_rights_def nth_ucast
validate_vm_rights_def vm_read_write_def
vm_kernel_only_def vm_read_only_def
split: bool.splits)
lemma vm_attributes_corres:
"vmattributes_map (attribs_from_word w) = attribsFromWord w"
by (clarsimp simp: attribsFromWord_def attribs_from_word_def
Let_def vmattributes_map_def)
lemma check_vp_corres:
"corres (ser \<oplus> dc) \<top> \<top>
(check_vp_alignment sz w)
(checkVPAlignment sz w)"
apply (simp add: check_vp_alignment_def checkVPAlignment_def)
apply (cases sz, simp_all add: corres_returnOk unlessE_whenE is_aligned_mask)
apply ((rule corres_guard_imp, rule corres_whenE, rule refl, auto)[1])+
done
lemma checkVP_wpR [wp]:
"\<lbrace>\<lambda>s. vmsz_aligned w sz \<longrightarrow> P () s\<rbrace>
checkVPAlignment sz w \<lbrace>P\<rbrace>, -"
apply (simp add: checkVPAlignment_def unlessE_whenE cong: vmpage_size.case_cong)
apply (rule hoare_pre)
apply (wp hoare_whenE_wp|wpc)+
apply (simp add: is_aligned_mask vmsz_aligned_def)
done
lemma asidHighBits [simp]:
"asidHighBits = asid_high_bits"
by (simp add: asidHighBits_def asid_high_bits_def)
declare word_unat_power [symmetric, simp del]
lemma case_option_corresE:
assumes nonec: "corres r Pn Qn (nc >>=E f) (nc' >>=E g)"
and somec: "\<And>v'. corres r (Ps v') (Qs v') (sc v' >>=E f) (sc' v' >>=E g)"
shows "corres r (case_option Pn Ps v) (case_option Qn Qs v) (case_option nc sc v >>=E f) (case_option nc' sc' v >>=E g)"
apply (cases v)
apply simp
apply (rule nonec)
apply simp
apply (rule somec)
done
lemma cap_relation_Untyped_eq:
"cap_relation c (UntypedCap d p sz f) = (c = cap.UntypedCap d p sz f)"
by (cases c) auto
declare check_vp_alignment_inv[wp del]
lemma select_ext_fa:
"free_asid_select asid_tbl \<in> S
\<Longrightarrow> ((select_ext (\<lambda>_. free_asid_select asid_tbl) S) :: _ det_ext_monad)
= return (free_asid_select asid_tbl)"
by (simp add: select_ext_def get_def gets_def bind_def assert_def return_def fail_def)
lemma select_ext_fap:
"free_asid_pool_select p b \<in> S
\<Longrightarrow> ((select_ext (\<lambda>_. free_asid_pool_select p b) S) :: _ det_ext_monad)
= return (free_asid_pool_select p b)"
by (simp add: select_ext_def get_def gets_def bind_def assert_def return_def)
lemmas vmsz_aligned_imp_aligned
= vmsz_aligned_def[THEN meta_eq_to_obj_eq, THEN iffD1, THEN is_aligned_weaken]
lemma check_slot_corres:
"(\<And>pte pte'. pte_relation' pte pte' \<Longrightarrow> test' pte' = test pte) \<Longrightarrow>
corres (ser \<oplus> dc)
(pte_at p and pspace_aligned and pspace_distinct) \<top>
(check_slot p test)
(checkSlot p test')"
apply (simp add: check_slot_def checkSlot_def unlessE_whenE liftE_bindE)
apply (rule corres_guard_imp)
apply (rule corres_split[OF _ get_pte_corres])
apply (rule corres_whenE, simp)
apply (rule corres_trivial, simp)
apply simp
apply wpsimp+
done
lemma vmrights_map_vm_kernel_only[simp]:
"vmrights_map vm_kernel_only = VMKernelOnly"
by (simp add: vmrights_map_def vm_kernel_only_def)
lemma not_in_vm_kernel_only[simp]:
"x \<notin> vm_kernel_only"
by (simp add: vm_kernel_only_def)
lemma vmrights_map_VMKernelOnly:
"vmrights_map (mask_vm_rights R r) = VMKernelOnly \<Longrightarrow> mask_vm_rights R r = vm_kernel_only"
by (auto simp: vmrights_map_def mask_vm_rights_def validate_vm_rights_def vm_read_write_def
vm_read_only_def split: if_splits)
lemma machine_word_len_pageBits_shift[simp]:
"UCAST(pte_ppn_len \<rightarrow> machine_word_len) (UCAST(machine_word_len \<rightarrow> pte_ppn_len) (p >> pageBits))
= p >> pageBits"
apply (simp add: ucast_ucast_mask pageBits_def)
apply word_bitwise
apply (simp add: word_size)
done
lemma pte_relation_make_user[simp]:
"pte_relation'
(make_user_pte p (attribs_from_word a) (mask_vm_rights R (data_to_rights r)))
(makeUserPTE p (\<not>attribsFromWord a) (maskVMRights (vmrights_map R) (rightsFromWord r)))"
by (auto simp: make_user_pte_def makeUserPTE_def attribs_from_word_def user_attr_def
attribsFromWord_def mask_vmrights_corres vmrights_map_VMKernelOnly)
lemma below_user_vtop_in_user_region:
"p < user_vtop \<Longrightarrow> p \<in> user_region"
apply (simp add: user_region_def canonical_user_def user_vtop_def pptrUserTop_def RISCV64.pptrUserTop_def)
apply (simp add: bit_simps is_aligned_mask canonical_bit_def)
by (word_bitwise, clarsimp simp: word_size)
lemma vmsz_aligned_user_region:
"\<lbrakk> vmsz_aligned p sz; p + (2 ^ pageBitsForSize sz - 1) < RISCV64_H.pptrUserTop \<rbrakk>
\<Longrightarrow> p \<in> user_region"
using pbfs_atleast_pageBits[of sz]
apply (simp flip: mask_2pm1 add: vmsz_aligned_def)
apply (simp add: user_region_def canonical_user_def pptrUserTop_def RISCV64.pptrUserTop_def)
apply (simp add: bit_simps is_aligned_mask canonical_bit_def word_plus_and_or_coroll)
by (word_bitwise, clarsimp simp: word_size)
lemma decode_page_inv_corres:
"\<lbrakk>cap = arch_cap.FrameCap p R sz d opt; acap_relation cap cap';
list_all2 cap_relation (map fst excaps) (map fst excaps');
list_all2 (\<lambda>s s'. s' = cte_map s) (map snd excaps) (map snd excaps') \<rbrakk> \<Longrightarrow>
corres (ser \<oplus> archinv_relation)
(invs and valid_cap (cap.ArchObjectCap cap) and
cte_wp_at ((=) (cap.ArchObjectCap cap)) slot and
(\<lambda>s. \<forall>x\<in>set excaps. s \<turnstile> fst x \<and> cte_wp_at (\<lambda>_. True) (snd x) s))
(invs' and valid_cap' (capability.ArchObjectCap cap') and
(\<lambda>s. \<forall>x\<in>set excaps'. valid_cap' (fst x) s \<and> cte_wp_at' (\<lambda>_. True) (snd x) s))
(decode_frame_invocation l args slot cap excaps)
(decodeRISCVFrameInvocation l args (cte_map slot) cap' excaps')"
apply (simp add: decode_frame_invocation_def decodeRISCVFrameInvocation_def Let_def isCap_simps
split del: if_split)
apply (cases "invocation_type l = ArchInvocationLabel RISCVPageMap")
apply (case_tac "\<not>(2 < length args \<and> excaps \<noteq> [])")
apply (auto simp: decode_fr_inv_map_def split: list.split)[1]
apply (simp add: decode_fr_inv_map_def Let_def neq_Nil_conv)
apply (elim exE conjE)
apply (simp split: list.split, intro conjI impI allI, simp_all)[1]
apply (simp add: decodeRISCVFrameInvocationMap_def)
apply (simp split: cap.split, intro conjI impI allI, simp_all)[1]
apply (rename_tac arch_capa)
apply (case_tac arch_capa, simp_all)[1]
apply (rename_tac wd opt')
apply (case_tac opt'; simp add: mdata_map_def)
apply (rename_tac av, case_tac av, simp)
apply (rename_tac a v)
apply (rule corres_guard_imp)
apply (rule corres_splitEE)
prefer 2
apply (rule corres_lookup_error)
apply (rule find_vspace_for_asid_corres[OF refl])
apply (rule whenE_throwError_corres, simp, simp)
apply (rule corres_splitEE[where r'=dc])
prefer 2
apply (rule corres_whenE)
apply (simp add: pptr_base_def user_vtop_def pptrUserTop_def shiftl_t2n mask_def)
apply (rule corres_trivial, simp)
apply simp
apply (rule corres_splitEE[where r'=dc])
prefer 2
apply (rule check_vp_corres)
apply (rule corres_splitEE)
prefer 2
apply (simp only: corres_liftE_rel_sum)
apply (rule lookup_pt_slot_corres)
apply (clarsimp simp: unlessE_whenE)
apply (rule corres_splitEE[where r'=dc])
prefer 2
apply datatype_schem
apply (rule corres_whenE, simp)
apply (rule corres_trivial, clarsimp simp: lookup_failure_map_def)
apply simp
apply (rule corres_splitEE[where r'=dc])
prefer 2
apply (cases opt; clarsimp)
apply (fold ser_def)
apply (rule check_slot_corres)
apply fastforce
apply (rule corres_guard_imp)
apply (rule whenE_throwError_corres)
apply fastforce
apply (rule up_ucast_inj_eq[THEN arg_cong_Not, symmetric], simp)
apply (rule whenE_throwError_corres)
apply fastforce
apply presburger
apply (rule check_slot_corres)
apply (case_tac pte; simp add: is_PageTablePTE_def RISCV64_H.isPageTablePTE_def)
apply blast
apply blast
apply (rule corres_trivial, rule corres_returnOk)
apply (clarsimp simp: archinv_relation_def page_invocation_map_def mapping_map_def)
apply (wpsimp simp: if_apply_def2
wp: validE_validE_R[OF find_vspace_for_asid_wp, simplified])+
apply (clarsimp simp: invs_psp_aligned invs_distinct invs_vspace_objs invs_valid_asid_table
cte_wp_at_caps_of_state is_cap_simps)
apply (rule conjI; clarsimp?)
apply (clarsimp simp: valid_cap_def wellformed_mapdata_def)
apply (rule conjI)
apply (rule exI)+
apply (rule conjI, erule vspace_for_asid_vs_lookup, simp)
apply (rule conjI)
apply (simp add: not_le vmsz_aligned_user_region[unfolded pptrUserTop_def] mask_def user_vtop_def)
apply clarsimp
apply (drule (1) pt_lookup_slot_vs_lookup_slotI, clarsimp)
apply (erule vs_lookup_slot_pte_at; assumption?)
apply (simp add: not_le vmsz_aligned_user_region[unfolded pptrUserTop_def] mask_def user_vtop_def)
apply fastforce
\<comment> \<open>PageUnmap\<close>
apply (simp split del: if_split)
apply (cases "invocation_type l = ArchInvocationLabel RISCVPageUnmap")
apply simp
apply (rule corres_returnOk)
apply (clarsimp simp: archinv_relation_def page_invocation_map_def)
\<comment> \<open>PageGetAddress\<close>
apply (cases "invocation_type l = ArchInvocationLabel RISCVPageGetAddress")
apply simp
apply (rule corres_returnOk)
apply (clarsimp simp: archinv_relation_def page_invocation_map_def)
by (clarsimp split: invocation_label.splits arch_invocation_label.splits split del: if_split)
lemma VMReadWrite_vmrights_map[simp]: "vmrights_map vm_read_write = VMReadWrite"
by (simp add: vmrights_map_def vm_read_write_def)
lemma gets_vspace_for_asid_is_catch:
"gets (vspace_for_asid a) = ((liftME Some (find_vspace_for_asid a)) <catch> const (return None))"
apply (simp add: find_vspace_for_asid_def liftME_def liftE_bindE catch_def)
apply (rule ext)
apply (clarsimp simp: bind_def simpler_gets_def throw_opt_def bindE_def throwError_def return_def
returnOk_def
split: option.splits)
done
lemma maybeVSpaceForASID_corres:
"a' = ucast a \<Longrightarrow>
corres (=)
(valid_vspace_objs and valid_asid_table and pspace_aligned and pspace_distinct
and K (0 < a))
no_0_obj'
(gets (vspace_for_asid a)) (maybeVSpaceForASID a')"
apply (simp add: maybeVSpaceForASID_def gets_vspace_for_asid_is_catch)
apply (rule corres_guard_imp)
apply (rule corres_split_catch)
apply (rule corres_trivial, simp)
apply (simp add: o_def)
apply (rule find_vspace_for_asid_corres, simp)
apply wpsimp+
done
crunches isFinalCapability
for no_0_obj'[wp]: no_0_obj'
(simp: crunch_simps wp: crunch_wps)
lemma decode_page_table_inv_corres:
"\<lbrakk>cap = arch_cap.PageTableCap p opt; acap_relation cap cap';
list_all2 cap_relation (map fst excaps) (map fst excaps');
list_all2 (\<lambda>s s'. s' = cte_map s) (map snd excaps) (map snd excaps') \<rbrakk> \<Longrightarrow>
corres (ser \<oplus> archinv_relation)
(invs and valid_cap (cap.ArchObjectCap cap) and
cte_wp_at ((=) (cap.ArchObjectCap cap)) slot and
(\<lambda>s. \<forall>x\<in>set excaps. s \<turnstile> fst x \<and> cte_wp_at (\<lambda>_. True) (snd x) s))
(invs' and valid_cap' (capability.ArchObjectCap cap') and
(\<lambda>s. \<forall>x\<in>set excaps'. valid_cap' (fst x) s \<and> cte_wp_at' (\<lambda>_. True) (snd x) s))
(decode_page_table_invocation l args slot cap excaps)
(decodeRISCVPageTableInvocation l args (cte_map slot) cap' excaps')"
apply (simp add: decode_page_table_invocation_def decodeRISCVPageTableInvocation_def Let_def
isCap_simps
split del: if_split)
apply (cases "invocation_type l = ArchInvocationLabel RISCVPageTableMap")
apply (simp add: decode_pt_inv_map_def
split: invocation_label.split arch_invocation_label.splits split del: if_split)
apply (simp split: list.split, intro conjI impI allI, simp_all)[1]
apply (clarsimp simp: neq_Nil_conv Let_def decodeRISCVPageTableInvocationMap_def)
apply (rule whenE_throwError_corres_initial; (fastforce simp: mdata_map_def)?)
apply (simp split: cap.split arch_cap.split option.split,
intro conjI allI impI, simp_all)[1]
apply (rule whenE_throwError_corres_initial; simp?)
apply (simp add: user_vtop_def pptrUserTop_def)
apply (rule corres_guard_imp)
apply (rule corres_splitEE)
prefer 2
apply (rule corres_lookup_error)
apply (rule find_vspace_for_asid_corres[OF refl])
apply (rule whenE_throwError_corres, simp, simp)
apply (rule corres_splitEE)
prefer 2
apply (simp)
apply (rule lookup_pt_slot_corres)
apply clarsimp
apply (rule corres_splitEE)
prefer 2
apply simp
apply datatype_schem
apply (rule get_pte_corres)
apply (simp add: unlessE_whenE)
apply (rule corres_splitEE[where r'=dc])
prefer 2
apply (rule corres_whenE)
apply clarsimp
apply (case_tac old_pte; simp)
apply (rule corres_trivial, simp)
apply simp
apply (rule corres_trivial, rule corres_returnOk)
apply (clarsimp simp: archinv_relation_def page_table_invocation_map_def
ucast_ucast_mask)
apply (subst word_le_mask_eq; simp?)
apply (rule leq_mask_shift)
apply (simp add: bit_simps le_mask_high_bits word_size)
apply ((clarsimp cong: if_cong
| wp hoare_whenE_wp hoare_vcg_all_lift_R getPTE_wp get_pte_wp
| wp (once) hoare_drop_imps)+)
apply (clarsimp simp: invs_vspace_objs invs_valid_asid_table invs_psp_aligned invs_distinct)
apply (clarsimp simp: valid_cap_def wellformed_mapdata_def not_le below_user_vtop_in_user_region)
apply (rule conjI)
apply (rule exI)+
apply (rule conjI, erule vspace_for_asid_vs_lookup, simp)
apply clarsimp
apply (drule (1) pt_lookup_slot_vs_lookup_slotI, clarsimp)
apply (erule vs_lookup_slot_pte_at; simp add: below_user_vtop_in_user_region)
apply fastforce
\<comment> \<open>PageTableUnmap\<close>
apply (clarsimp simp: isCap_simps)+
apply (cases "invocation_type l = ArchInvocationLabel RISCVPageTableUnmap")
apply (clarsimp simp: unlessE_whenE liftE_bindE)
apply (rule stronger_corres_guard_imp)
apply (rule corres_symb_exec_r_conj)
apply (rule_tac F="isArchCap isPageTableCap (cteCap cteVal)"
in corres_gen_asm2)
apply (rule corres_split[OF _ final_cap_corres[where ptr=slot]])
apply (drule mp)
apply (clarsimp simp: isCap_simps final_matters'_def)
apply (rule whenE_throwError_corres; simp)
apply (rule option_corres)
apply (cases opt; simp add: mdata_map_def)
apply (rule corres_trivial, simp add: returnOk_def archinv_relation_def
page_table_invocation_map_def)
apply (cases opt, clarsimp simp: mdata_map_def)
apply (clarsimp simp: bind_bindE_assoc)
apply (rule corres_split)
prefer 2
apply datatype_schem
apply (rule maybeVSpaceForASID_corres, simp)
apply (rule whenE_throwError_corres; simp)
apply (rule corres_trivial, simp add: returnOk_def archinv_relation_def
page_table_invocation_map_def)
apply (simp|wp)+
apply (cases opt; simp add: mdata_map_def)
apply (simp | wp getCTE_wp' | wp (once) hoare_drop_imps)+
apply (clarsimp)
apply (rule no_fail_pre, rule no_fail_getCTE)
apply (erule conjunct2)
apply (clarsimp simp: cte_wp_at_caps_of_state invs_vspace_objs
invs_valid_asid_table invs_psp_aligned invs_distinct)
apply (clarsimp simp: valid_cap_def wellformed_mapdata_def)
apply (clarsimp simp: cte_wp_at_ctes_of cap_rights_update_def acap_rights_update_def
cte_wp_at_caps_of_state)
apply (drule pspace_relation_ctes_ofI[OF _ caps_of_state_cteD, rotated],
erule invs_pspace_aligned', clarsimp+)
apply (simp add: isCap_simps invs_no_0_obj')
apply (simp add: isCap_simps split del: if_split)
by (clarsimp split: invocation_label.splits arch_invocation_label.splits)
lemma dec_arch_inv_corres:
notes check_vp_inv[wp del] check_vp_wpR[wp]
(* FIXME: check_vp_inv shadowed check_vp_wpR. Instead,
check_vp_wpR should probably be generalised to replace check_vp_inv. *)
shows
"\<lbrakk> acap_relation arch_cap arch_cap';
list_all2 cap_relation (map fst excaps) (map fst excaps');
list_all2 (\<lambda>s s'. s' = cte_map s) (map snd excaps) (map snd excaps') \<rbrakk> \<Longrightarrow>
corres
(ser \<oplus> archinv_relation)
(invs and valid_cap (cap.ArchObjectCap arch_cap) and
cte_wp_at ((=) (cap.ArchObjectCap arch_cap)) slot and
(\<lambda>s. \<forall>x\<in>set excaps. s \<turnstile> fst x \<and> cte_at (snd x) s))
(invs' and valid_cap' (capability.ArchObjectCap arch_cap') and
(\<lambda>s. \<forall>x\<in>set excaps'. s \<turnstile>' fst x \<and> cte_at' (snd x) s))
(arch_decode_invocation (mi_label mi) args (to_bl cptr') slot
arch_cap excaps)
(Arch.decodeInvocation (mi_label mi) args cptr'
(cte_map slot) arch_cap' excaps')"
apply (simp add: arch_decode_invocation_def
RISCV64_H.decodeInvocation_def
decodeRISCVMMUInvocation_def
split del: if_split)
apply (cases arch_cap)
\<comment> \<open>ASIDPoolCap\<close>
apply (simp add: isCap_simps decodeRISCVMMUInvocation_def decode_asid_pool_invocation_def
decodeRISCVASIDPoolInvocation_def Let_def
split del: if_split)
apply (cases "invocation_type (mi_label mi) \<noteq> ArchInvocationLabel RISCVASIDPoolAssign")
apply (simp split: invocation_label.split arch_invocation_label.split)
apply (rename_tac word1 word2)
apply (cases "excaps", simp)
apply (cases "excaps'", simp)
apply clarsimp
apply (case_tac a, simp_all)[1]
apply (rename_tac arch_capa)
apply (case_tac arch_capa, simp_all)[1]
apply (rename_tac word3 option)
apply (case_tac option, simp_all add: mdata_map_def)[1]
apply (rule corres_guard_imp)
apply (rule corres_splitEE)
prefer 2
apply (rule corres_trivial [where r="ser \<oplus> (\<lambda>p p'. p = p' o ucast)"])
apply (clarsimp simp: state_relation_def arch_state_relation_def)
apply (rule whenE_throwError_corres, simp)
apply (simp add: lookup_failure_map_def)
apply simp
apply (rule_tac P="\<lambda>s. (asid_table (asid_high_bits_of word2) = Some word1 \<longrightarrow> asid_pool_at word1 s) \<and>
pspace_aligned s \<and> pspace_distinct s \<and> is_aligned word2 asid_low_bits" and
P'="\<top>" in corres_inst)
apply (simp add: liftME_return)
apply (rule whenE_throwError_corres_initial, simp)
apply auto[1]
apply (rule corres_guard_imp)
apply (rule corres_splitEE)
prefer 2
apply simp
apply (rule get_asid_pool_corres_inv'[OF refl])
apply (simp add: bindE_assoc)
apply (rule_tac F="is_aligned word2 asid_low_bits" in corres_gen_asm)
apply (rule corres_splitEE)
prefer 2
apply (rule corres_whenE)
apply (subst conj_assoc [symmetric])
apply (subst assocs_empty_dom_comp [symmetric])
apply (erule dom_ucast_eq)
apply (rule corres_trivial)
apply simp
apply simp
apply (rule_tac F="- dom pool \<inter> {x. ucast x + word2 \<noteq> 0} \<noteq> {}" in corres_gen_asm)
apply (frule dom_hd_assocsD)
apply (simp add: select_ext_fap[simplified free_asid_pool_select_def]
free_asid_pool_select_def)
apply (simp add: returnOk_liftE[symmetric])
apply (rule corres_returnOk)
apply (simp add: archinv_relation_def asid_pool_invocation_map_def)
apply (rule hoare_pre, wp hoare_whenE_wp)
apply (clarsimp simp: ucast_fst_hd_assocs)
apply (wp hoareE_TrueI hoare_whenE_wp getASID_wp | simp)+
apply ((clarsimp simp: p2_low_bits_max | rule TrueI impI)+)[2]
apply (wp hoare_whenE_wp getASID_wp)+
apply (auto simp: valid_cap_def)[1]
apply auto[1]
\<comment> \<open>ASIDControlCap\<close>
apply (simp add: isCap_simps decodeRISCVMMUInvocation_def decode_asid_control_invocation_def
Let_def decodeRISCVASIDControlInvocation_def
split del: if_split)
apply (cases "invocation_type (mi_label mi) \<noteq> ArchInvocationLabel RISCVASIDControlMakePool")
apply (simp split: invocation_label.split arch_invocation_label.split)
apply (subgoal_tac "length excaps' = length excaps")
prefer 2
apply (simp add: list_all2_iff)
apply (cases args, simp)
apply (rename_tac a0 as)
apply (case_tac as, simp)
apply (rename_tac a1 as')
apply (cases excaps, simp)
apply (rename_tac excap0 exs)
apply (case_tac exs)
apply (auto split: list.split)[1]
apply (rename_tac excap1 exss)
apply (case_tac excap0)
apply (rename_tac c0 slot0)
apply (case_tac excap1)
apply (rename_tac c1 slot1)
apply (clarsimp simp: Let_def split del: if_split)
apply (cases excaps', simp)
apply (case_tac list, simp)
apply (rename_tac c0' exs' c1' exss')
apply (clarsimp split del: if_split)
apply (rule corres_guard_imp)
apply (rule corres_splitEE [where r'="\<lambda>p p'. p = p' o ucast"])
prefer 2
apply (rule corres_trivial)
apply (clarsimp simp: state_relation_def arch_state_relation_def)
apply (rule corres_splitEE)
prefer 2
apply (rule corres_whenE)
apply (subst assocs_empty_dom_comp [symmetric])
apply (simp add: o_def)
apply (rule dom_ucast_eq_8)
apply (rule corres_trivial, simp, simp)
apply (simp split del: if_split)
apply (rule_tac F="- dom (asidTable \<circ> ucast) \<inter> {x. x \<le> 2 ^ asid_high_bits - 1} \<noteq> {}" in corres_gen_asm)
apply (drule dom_hd_assocsD)
apply (simp add: select_ext_fa[simplified free_asid_select_def]
free_asid_select_def o_def returnOk_liftE[symmetric] split del: if_split)
apply (thin_tac "fst a \<notin> b \<and> P" for a b P)
apply (case_tac "isUntypedCap a \<and> capBlockSize a = objBits (makeObject::asidpool) \<and> \<not> capIsDevice a")
prefer 2
apply (rule corres_guard_imp)
apply (rule corres_trivial)
apply (case_tac ad; simp add: isCap_simps split del: if_split)
apply (case_tac x21; simp split del: if_split)
apply (clarsimp simp: objBits_simps split del: if_split)
apply clarsimp
apply (rule TrueI)+
apply (clarsimp simp: isCap_simps cap_relation_Untyped_eq lookupTargetSlot_def
objBits_simps bindE_assoc split_def)
apply (rule corres_splitEE)
prefer 2
apply (rule ensure_no_children_corres, rule refl)
apply (rule corres_splitEE)
prefer 2
apply (erule lsfc_corres, rule refl)
apply (rule corres_splitEE)
prefer 2
apply (rule ensure_empty_corres)
apply clarsimp
apply (rule corres_returnOk[where P="\<top>"])
apply (clarsimp simp add: archinv_relation_def asid_ci_map_def split_def)
apply (clarsimp simp add: ucast_assocs[unfolded o_def] split_def
filter_map asid_high_bits_def)
apply (simp add: ord_le_eq_trans [OF word_n1_ge])
apply (wp hoare_drop_imps)+
apply (simp add: o_def validE_R_def)
apply (fastforce simp: asid_high_bits_def)
apply clarsimp
apply (simp add: null_def split_def asid_high_bits_def word_le_make_less)
apply (subst hd_map, assumption)
(* need abstract guard to show list nonempty *)
apply (simp add: word_le_make_less)
apply (simp add: ucast_ucast_mask2 is_down)
apply (frule hd_in_set)
apply clarsimp
apply (prop_tac "\<forall>x::machine_word. x < 2^asid_high_bits \<longrightarrow> x && mask asid_high_bits = x")
apply (clarsimp simp: and_mask_eq_iff_le_mask le_mask_iff_lt_2n[THEN iffD1] asid_high_bits_def)
apply (simp add: asid_high_bits_def)
apply (erule allE, erule (1) impE)
apply (simp add: ucast_shiftl)
apply (subst ucast_ucast_len)
apply (drule hd_in_set)
apply (rule shiftl_less_t2n; simp add: asid_low_bits_def)
apply (fastforce)
\<comment> \<open>PageCap\<close>
apply (rename_tac word cap_rights vmpage_size option)
apply (simp add: isCap_simps decodeRISCVMMUInvocation_def Let_def split del: if_split)
apply (rule decode_page_inv_corres; simp)
\<comment> \<open>PageTableCap\<close>
apply (simp add: isCap_simps decodeRISCVMMUInvocation_def Let_def split del: if_split)
apply (rule decode_page_table_inv_corres; simp)
done
lemma inv_arch_corres:
"archinv_relation ai ai' \<Longrightarrow>
corres (intr \<oplus> (=))
(einvs and ct_active and valid_arch_inv ai)
(invs' and ct_active' and valid_arch_inv' ai')
(arch_perform_invocation ai) (Arch.performInvocation ai')"
apply (clarsimp simp: arch_perform_invocation_def
RISCV64_H.performInvocation_def
performRISCVMMUInvocation_def)
apply (clarsimp simp: archinv_relation_def)
apply (cases ai)
apply (clarsimp simp: archinv_relation_def performRISCVMMUInvocation_def)
apply (rule corres_guard_imp, rule corres_split_nor, rule corres_trivial, simp)
apply (rule perform_page_table_corres; wpsimp)
apply wpsimp+
apply (fastforce simp: valid_arch_inv_def)
apply (fastforce simp: valid_arch_inv'_def)
apply (clarsimp simp: archinv_relation_def)
apply (rule corres_guard_imp, rule corres_split_nor, rule corres_trivial, simp)
apply (rule perform_page_corres; wpsimp)
apply wpsimp+
apply (fastforce simp: valid_arch_inv_def)
apply (fastforce simp: valid_arch_inv'_def)
apply (clarsimp simp: archinv_relation_def)
apply (rule corres_guard_imp, rule corres_split_nor, rule corres_trivial, simp)
apply (rule pac_corres; wpsimp)
apply wpsimp+
apply (fastforce simp: valid_arch_inv_def)
apply (fastforce simp: valid_arch_inv'_def)
apply (clarsimp simp: archinv_relation_def)
apply (rule corres_guard_imp, rule corres_split_nor, rule corres_trivial, simp)
apply (rule pap_corres; wpsimp)
apply wpsimp+
apply (fastforce simp: valid_arch_inv_def)
apply (fastforce simp: valid_arch_inv'_def)
done
lemma asid_pool_typ_at_ext':
"asid_pool_at' = obj_at' (\<top>::asidpool \<Rightarrow> bool)"
apply (rule ext)+
apply (simp add: typ_at_to_obj_at_arches)
done
lemma st_tcb_strg':
"st_tcb_at' P p s \<longrightarrow> tcb_at' p s"
by (auto simp: pred_tcb_at')
lemma performASIDControlInvocation_tcb_at':
"\<lbrace>st_tcb_at' active' p and invs' and ct_active' and valid_aci' aci\<rbrace>
performASIDControlInvocation aci
\<lbrace>\<lambda>y. tcb_at' p\<rbrace>"
apply (rule hoare_name_pre_state)
apply (clarsimp simp: performASIDControlInvocation_def split: asidcontrol_invocation.splits)
apply (clarsimp simp: valid_aci'_def cte_wp_at_ctes_of cong: conj_cong)
apply (wp static_imp_wp |simp add:placeNewObject_def2)+
apply (wp createObjects_orig_obj_at2' updateFreeIndex_pspace_no_overlap' getSlotCap_wp static_imp_wp)+
apply (clarsimp simp: projectKO_opts_defs)
apply (strengthen st_tcb_strg' [where P=\<top>])
apply (wp deleteObjects_invs_derivatives[where p="makePoolParent aci"]
hoare_vcg_ex_lift deleteObjects_cte_wp_at'[where d=False]
deleteObjects_st_tcb_at'[where p="makePoolParent aci"] static_imp_wp
updateFreeIndex_pspace_no_overlap' deleteObject_no_overlap[where d=False])+
apply (case_tac ctea)
apply (clarsimp)
apply (frule ctes_of_valid_cap')
apply (simp add:invs_valid_objs')+
apply (clarsimp simp:valid_cap'_def capAligned_def cte_wp_at_ctes_of)
apply (strengthen refl order_refl
pred_tcb'_weakenE[mk_strg I E])
apply (clarsimp simp: conj_comms invs_valid_pspace' isCap_simps
descendants_range'_def2 empty_descendants_range_in')
apply (frule ctes_of_valid', clarsimp, simp,
drule capFreeIndex_update_valid_cap'[where fb="2 ^ pageBits", rotated -1],
simp_all)
apply (simp add: pageBits_def is_aligned_def untypedBits_defs)
apply (simp add: valid_cap_simps' range_cover_def objBits_simps untypedBits_defs
capAligned_def unat_eq_0 and_mask_eq_iff_shiftr_0[symmetric]
word_bw_assocs)
apply clarsimp
apply (drule(1) cte_cap_in_untyped_range,
fastforce simp add: cte_wp_at_ctes_of, assumption, simp_all)
apply (clarsimp simp: invs'_def valid_state'_def if_unsafe_then_cap'_def cte_wp_at_ctes_of)
apply clarsimp
done
lemma invokeArch_tcb_at':
"\<lbrace>invs' and valid_arch_inv' ai and ct_active' and st_tcb_at' active' p\<rbrace>
Arch.performInvocation ai
\<lbrace>\<lambda>rv. tcb_at' p\<rbrace>"
apply (simp add: RISCV64_H.performInvocation_def performRISCVMMUInvocation_def)
apply (wpsimp simp: performRISCVMMUInvocation_def pred_tcb_at' valid_arch_inv'_def
wp: performASIDControlInvocation_tcb_at')
done
lemma pspace_no_overlap_queuesL1 [simp]:
"pspace_no_overlap' w sz (ksReadyQueuesL1Bitmap_update f s) = pspace_no_overlap' w sz s"
by (simp add: pspace_no_overlap'_def)
lemma pspace_no_overlap_queuesL2 [simp]:
"pspace_no_overlap' w sz (ksReadyQueuesL2Bitmap_update f s) = pspace_no_overlap' w sz s"
by (simp add: pspace_no_overlap'_def)
crunch pspace_no_overlap'[wp]: setThreadState "pspace_no_overlap' w s"
(simp: unless_def)
lemma sts_cte_cap_to'[wp]:
"\<lbrace>ex_cte_cap_to' p\<rbrace> setThreadState st t \<lbrace>\<lambda>rv. ex_cte_cap_to' p\<rbrace>"
by (wp ex_cte_cap_to'_pres)
lemma sts_valid_arch_inv':
"\<lbrace>valid_arch_inv' ai\<rbrace> setThreadState st t \<lbrace>\<lambda>rv. valid_arch_inv' ai\<rbrace>"
apply (cases ai, simp_all add: valid_arch_inv'_def)
apply (clarsimp simp: valid_pti'_def split: page_table_invocation.splits)
apply (rule conjI|clarsimp|wpsimp)+
apply (rename_tac page_invocation)
apply (case_tac page_invocation, simp_all add: valid_page_inv'_def)[1]
apply (wp |simp)+
apply (clarsimp simp: valid_aci'_def split: asidcontrol_invocation.splits)
apply (clarsimp simp: cte_wp_at_ctes_of)
apply (rule hoare_pre, wp)
apply clarsimp
apply (clarsimp simp: valid_apinv'_def split: asidpool_invocation.splits)
apply (rule hoare_pre, wp)
apply simp
done
lemma inv_ASIDPool: "inv ASIDPool = (\<lambda>v. case v of ASIDPool a \<Rightarrow> a)"
apply (rule ext)
apply (case_tac v)
apply simp
apply (rule inv_f_f, rule inj_onI)
apply simp
done
lemma eq_arch_update':
"ArchObjectCap cp = cteCap cte \<Longrightarrow> is_arch_update' (ArchObjectCap cp) cte"
by (clarsimp simp: is_arch_update'_def isCap_simps)
lemma decode_page_inv_wf[wp]:
"cap = (arch_capability.FrameCap word vmrights vmpage_size d option) \<Longrightarrow>
\<lbrace>invs' and valid_cap' (capability.ArchObjectCap cap ) and
cte_wp_at' ((=) (capability.ArchObjectCap cap) \<circ> cteCap) slot and
(\<lambda>s. \<forall>x\<in>set excaps. cte_wp_at' ((=) (fst x) \<circ> cteCap) (snd x) s) and
sch_act_simple\<rbrace>
decodeRISCVFrameInvocation label args slot cap excaps
\<lbrace>valid_arch_inv'\<rbrace>, -"
apply (simp add: decodeRISCVFrameInvocation_def Let_def isCap_simps
cong: if_cong split del: if_split)
apply (wpsimp simp: decodeRISCVFrameInvocationMap_def valid_arch_inv'_def valid_page_inv'_def
checkSlot_def if_apply_def2
wp: getPTE_wp hoare_vcg_all_lift lookupPTSlot_inv
| wp (once) hoare_drop_imps)+
apply ((rule conjI; clarsimp)+;
(clarsimp simp: cte_wp_at_ctes_of,
(drule_tac t="cteCap _" in sym)+,
(drule ctes_of_valid', fastforce)+,
clarsimp simp: valid_cap'_def ptBits_def pageBits_def
is_arch_update'_def isCap_simps capAligned_def wellformed_mapdata'_def
vmsz_aligned_user_region not_le))
done
lemma below_pptrUserTop_in_user_region:
"p < RISCV64_H.pptrUserTop \<Longrightarrow> p \<in> user_region"
apply (simp add: user_region_def canonical_user_def pptrUserTop_def RISCV64.pptrUserTop_def)
apply (simp add: bit_simps is_aligned_mask canonical_bit_def)
by (word_bitwise, clarsimp simp: word_size)
lemma decode_page_table_inv_wf[wp]:
"arch_cap = PageTableCap word option \<Longrightarrow>
\<lbrace>invs' and valid_cap' (capability.ArchObjectCap arch_cap) and
cte_wp_at' ((=) (capability.ArchObjectCap arch_cap) \<circ> cteCap) slot and
(\<lambda>s. \<forall>x\<in>set excaps. cte_wp_at' ((=) (fst x) \<circ> cteCap) (snd x) s) and
sch_act_simple\<rbrace>
decodeRISCVPageTableInvocation label args slot arch_cap excaps
\<lbrace>valid_arch_inv'\<rbrace>, - "
supply if_cong[cong] if_split [split del]
apply (clarsimp simp: decodeRISCVPageTableInvocation_def Let_def isCap_simps)
apply (wpsimp simp: decodeRISCVPageTableInvocationMap_def valid_arch_inv'_def valid_pti'_def
maybeVSpaceForASID_def o_def if_apply_def2
wp: getPTE_wp hoare_vcg_all_lift hoare_vcg_const_imp_lift
lookupPTSlot_inv isFinalCapability_inv
| wp (once) hoare_drop_imps)+
apply (clarsimp simp: not_le isCap_simps cte_wp_at_ctes_of eq_arch_update')
apply (drule_tac t="cteCap cte" in sym)
apply (simp add: valid_cap'_def capAligned_def)
apply (clarsimp simp: is_arch_update'_def isCap_simps
split: if_split)
apply (rule conjI; clarsimp)
apply (drule_tac t="cteCap ctea" in sym)
apply (drule ctes_of_valid', fastforce)+
apply (clarsimp simp: valid_cap'_def)
apply (simp add: wellformed_mapdata'_def below_pptrUserTop_in_user_region neg_mask_user_region)
done
lemma capMaster_isPageTableCap:
"capMasterCap cap' = capMasterCap cap \<Longrightarrow>
isArchCap isPageTableCap cap' = isArchCap isPageTableCap cap"
by (simp add: capMasterCap_def isArchCap_def isPageTableCap_def
split: capability.splits arch_capability.splits)
lemma arch_decodeInvocation_wf[wp]:
shows "\<lbrace>invs' and valid_cap' (ArchObjectCap arch_cap) and
cte_wp_at' ((=) (ArchObjectCap arch_cap) o cteCap) slot and
(\<lambda>s. \<forall>x \<in> set excaps. cte_wp_at' ((=) (fst x) o cteCap) (snd x) s) and
(\<lambda>s. \<forall>x \<in> set excaps. \<forall>r \<in> cte_refs' (fst x) (irq_node' s). ex_cte_cap_to' r s) and
(\<lambda>s. \<forall>x \<in> set excaps. s \<turnstile>' fst x) and
sch_act_simple\<rbrace>
Arch.decodeInvocation label args cap_index slot arch_cap excaps
\<lbrace>valid_arch_inv'\<rbrace>,-"
apply (cases arch_cap)
apply (simp add: decodeRISCVMMUInvocation_def RISCV64_H.decodeInvocation_def
Let_def split_def isCap_simps decodeRISCVASIDControlInvocation_def
cong: if_cong invocation_label.case_cong arch_invocation_label.case_cong list.case_cong prod.case_cong
split del: if_split)
apply (rule hoare_pre)
apply ((wp whenE_throwError_wp ensureEmptySlot_stronger|
wpc|
simp add: valid_arch_inv'_def valid_aci'_def is_aligned_shiftl_self
split del: if_split)+)[1]
apply (rule_tac Q'=
"\<lambda>rv. K (fst (hd [p\<leftarrow>assocs asidTable . fst p \<le> 2 ^ asid_high_bits - 1 \<and> snd p = None])
<< asid_low_bits \<le> 2 ^ asid_bits - 1) and
real_cte_at' rv and
ex_cte_cap_to' rv and
cte_wp_at' (\<lambda>cte. \<exists>idx. cteCap cte = (UntypedCap False frame pageBits idx)) (snd (excaps!0)) and
sch_act_simple and
(\<lambda>s. descendants_of' (snd (excaps!0)) (ctes_of s) = {}) "
in hoare_post_imp_R)
apply (simp add: lookupTargetSlot_def)
apply wp
apply (clarsimp simp: cte_wp_at_ctes_of asid_wf_def mask_def)
apply (simp split del: if_split)
apply (wp ensureNoChildren_sp whenE_throwError_wp|wpc)+
apply clarsimp
apply (rule conjI)
apply (clarsimp simp: null_def neq_Nil_conv)
apply (drule filter_eq_ConsD)
apply clarsimp
apply (rule shiftl_less_t2n)
apply (simp add: asid_bits_def asid_low_bits_def asid_high_bits_def)
apply unat_arith
apply (simp add: asid_bits_def)
apply clarsimp
apply (rule conjI, fastforce)
apply (clarsimp simp: cte_wp_at_ctes_of objBits_simps)
\<comment> \<open>ASIDPool cap\<close>
apply (simp add: decodeRISCVMMUInvocation_def RISCV64_H.decodeInvocation_def
Let_def split_def isCap_simps decodeRISCVASIDPoolInvocation_def
cong: if_cong split del: if_split)
apply (wpsimp simp: valid_arch_inv'_def valid_apinv'_def wp: getASID_wp cong: if_cong)
apply (clarsimp simp: word_neq_0_conv valid_cap'_def valid_arch_inv'_def valid_apinv'_def)
apply (rule conjI)
apply (erule cte_wp_at_weakenE')
apply (simp, drule_tac t="cteCap c" in sym, simp add: isCap_simps)
apply (subst (asm) conj_assoc [symmetric])
apply (subst (asm) assocs_empty_dom_comp [symmetric])
apply (drule dom_hd_assocsD)
apply (simp add: capAligned_def asid_wf_def mask_def)
apply (elim conjE)
apply (subst field_simps, erule is_aligned_add_less_t2n)
apply assumption
apply (simp add: asid_low_bits_def asid_bits_def)
apply assumption
\<comment> \<open>PageCap\<close>
apply (simp add: decodeRISCVMMUInvocation_def isCap_simps RISCV64_H.decodeInvocation_def
cong: if_cong split del: if_split)
apply (wp, simp+)
\<comment> \<open>PageTableCap\<close>
apply (simp add: decodeRISCVMMUInvocation_def isCap_simps RISCV64_H.decodeInvocation_def
cong: if_cong split del: if_split)
apply (wpsimp, simp+)
done
crunch nosch[wp]: setMRs "\<lambda>s. P (ksSchedulerAction s)"
(ignore: getRestartPC setRegister transferCapsToSlots
wp: hoare_drop_imps hoare_vcg_split_case_option
mapM_wp'
simp: split_def zipWithM_x_mapM)
crunch nosch [wp]: performRISCVMMUInvocation "\<lambda>s. P (ksSchedulerAction s)"
(simp: crunch_simps
wp: crunch_wps getObject_cte_inv getASID_wp)
lemmas setObject_cte_st_tcb_at' [wp] = setCTE_pred_tcb_at' [unfolded setCTE_def]
crunch st_tcb_at': performPageTableInvocation,
performPageInvocation,
performASIDPoolInvocation "st_tcb_at' P t"
(wp: crunch_wps getASID_wp getObject_cte_inv simp: crunch_simps pteAtIndex_def)
lemma performASIDControlInvocation_st_tcb_at':
"\<lbrace>st_tcb_at' (P and (\<noteq>) Inactive and (\<noteq>) IdleThreadState) t and
valid_aci' aci and invs' and ct_active'\<rbrace>
performASIDControlInvocation aci
\<lbrace>\<lambda>y. st_tcb_at' P t\<rbrace>"
apply (rule hoare_name_pre_state)
apply (clarsimp simp: performASIDControlInvocation_def split: asidcontrol_invocation.splits)
apply (clarsimp simp: valid_aci'_def cte_wp_at_ctes_of cong: conj_cong)
apply (rule hoare_pre)
apply (wp createObjects_orig_obj_at'[where P="P \<circ> tcbState", folded st_tcb_at'_def]
updateFreeIndex_pspace_no_overlap' getSlotCap_wp
hoare_vcg_ex_lift
deleteObjects_cte_wp_at' deleteObjects_invs_derivatives
deleteObjects_st_tcb_at'
static_imp_wp
| simp add: placeNewObject_def2)+
apply (case_tac ctea)
apply (clarsimp)
apply (frule ctes_of_valid_cap')
apply (simp add:invs_valid_objs')+
apply (clarsimp simp:valid_cap'_def capAligned_def cte_wp_at_ctes_of)
apply (rule conjI)
apply clarsimp
apply (drule (1) cte_cap_in_untyped_range)
apply (fastforce simp add: cte_wp_at_ctes_of)
apply assumption+
subgoal by (clarsimp simp: invs'_def valid_state'_def if_unsafe_then_cap'_def cte_wp_at_ctes_of)
subgoal by fastforce
apply simp
apply (rule conjI,assumption)
apply (clarsimp simp:invs_valid_pspace' objBits_simps range_cover_full descendants_range'_def2
isCap_simps)
apply (intro conjI)
apply (fastforce simp:empty_descendants_range_in')+
apply clarsimp
apply (drule (1) cte_cap_in_untyped_range)
apply (fastforce simp add: cte_wp_at_ctes_of)
apply assumption+
apply (clarsimp simp: invs'_def valid_state'_def if_unsafe_then_cap'_def cte_wp_at_ctes_of)
apply fastforce
apply simp
apply auto
done
lemmas arch_finalise_cap_aligned' = ArchRetypeDecls_H_RISCV64_H_finaliseCap_aligned'
lemmas arch_finalise_cap_distinct' = ArchRetypeDecls_H_RISCV64_H_finaliseCap_distinct'
crunch st_tcb_at' [wp]: "Arch.finaliseCap" "st_tcb_at' P t"
(wp: crunch_wps getASID_wp simp: crunch_simps)
lemma invs_asid_table_strengthen':
"invs' s \<and> asid_pool_at' ap s \<and> asid \<le> 2 ^ asid_high_bits - 1 \<longrightarrow>
invs' (s\<lparr>ksArchState :=
riscvKSASIDTable_update (\<lambda>_. (riscvKSASIDTable \<circ> ksArchState) s(asid \<mapsto> ap)) (ksArchState s)\<rparr>)"
apply (clarsimp simp: invs'_def valid_state'_def)
apply (rule conjI)
apply (clarsimp simp: valid_global_refs'_def global_refs'_def)
apply (clarsimp simp: valid_arch_state'_def)
apply (clarsimp simp: valid_asid_table'_def ran_def mask_def)
apply (rule conjI)
apply (clarsimp split: if_split_asm)
apply (fastforce simp: mask_def)
apply (rule conjI)
apply (clarsimp simp: valid_pspace'_def)
apply (simp add: valid_machine_state'_def)
done
lemma ex_cte_not_in_untyped_range:
"\<lbrakk>(ctes_of s) cref = Some (CTE (capability.UntypedCap d ptr bits idx) mnode);
descendants_of' cref (ctes_of s) = {}; invs' s;
ex_cte_cap_wp_to' (\<lambda>_. True) x s; valid_global_refs' s\<rbrakk>
\<Longrightarrow> x \<notin> mask_range ptr bits"
apply clarsimp
apply (drule(1) cte_cap_in_untyped_range)
apply (fastforce simp:cte_wp_at_ctes_of)+
done
lemma kernel_mappings_canonical_pt_base:
"x \<in> kernel_mappings \<Longrightarrow> canonical_address (table_base x)"
apply (simp add: kernel_mappings_def pptr_base_def RISCV64.pptrBase_def canonical_address_range
canonical_bit_def bit_simps)
apply (word_bitwise, clarsimp simp: word_size)
done
lemma performASIDControlInvocation_invs' [wp]:
"\<lbrace>invs' and ct_active' and valid_aci' aci\<rbrace>
performASIDControlInvocation aci \<lbrace>\<lambda>y. invs'\<rbrace>"
apply (rule hoare_name_pre_state)
apply (clarsimp simp: performASIDControlInvocation_def valid_aci'_def
placeNewObject_def2 cte_wp_at_ctes_of
split: asidcontrol_invocation.splits)
apply (rename_tac w1 w2 w3 w4 cte ctea idx)
apply (case_tac ctea)
apply (clarsimp)
apply (frule ctes_of_valid_cap')
apply fastforce
apply (rule hoare_pre)
apply (wp hoare_vcg_const_imp_lift)
apply (strengthen invs_asid_table_strengthen')
apply (wp cteInsert_simple_invs)
apply (wp createObjects'_wp_subst[OF
createObjects_no_cte_invs[where sz = pageBits and ty="Inl (KOArch (KOASIDPool pool))" for pool]]
createObjects_orig_cte_wp_at'[where sz = pageBits] hoare_vcg_const_imp_lift
|simp add: makeObjectKO_def asid_pool_typ_at_ext' valid_cap'_def cong: rev_conj_cong
|strengthen safe_parent_strg'[where idx= "2^ pageBits"])+
apply (rule hoare_vcg_conj_lift)
apply (rule descendants_of'_helper)
apply (wp createObjects_null_filter'
[where sz = pageBits and ty="Inl (KOArch (KOASIDPool ap))" for ap]
createObjects_valid_pspace'
[where sz = pageBits and ty="Inl (KOArch (KOASIDPool ap))" for ap]
| simp add: makeObjectKO_def asid_pool_typ_at_ext' valid_cap'_def
cong: rev_conj_cong)+
apply (simp add: objBits_simps valid_cap'_def capAligned_def range_cover_full)
apply (wp createObjects'_wp_subst[OF createObjects_ex_cte_cap_to[where sz = pageBits]]
createObjects_orig_cte_wp_at'[where sz = pageBits]
hoare_vcg_const_imp_lift
|simp add: makeObjectKO_def asid_pool_typ_at_ext' valid_cap'_def
isCap_simps
canonical_address_neq_mask
cong: rev_conj_cong
|strengthen safe_parent_strg'[where idx = "2^ pageBits"]
| rule in_kernel_mappings_neq_mask
| simp add: bit_simps kernel_mappings_canonical_pt_base[unfolded bit_simps])+
apply (simp add:asid_pool_typ_at_ext'[symmetric])
apply (wp createObject_typ_at')
apply (simp add: objBits_simps valid_cap'_def
capAligned_def range_cover_full makeObjectKO_def
asid_pool_typ_at_ext'
cong: rev_conj_cong)
apply (clarsimp simp:conj_comms
descendants_of_null_filter'
| strengthen invs_pspace_aligned' invs_pspace_distinct'
invs_pspace_aligned' invs_valid_pspace')+
apply (wp updateFreeIndex_forward_invs'
updateFreeIndex_cte_wp_at
updateFreeIndex_pspace_no_overlap'
updateFreeIndex_caps_no_overlap''
updateFreeIndex_descendants_of2
updateFreeIndex_caps_overlap_reserved
updateCap_cte_wp_at_cases static_imp_wp
getSlotCap_wp)+
apply (clarsimp simp:conj_comms ex_disj_distrib is_aligned_mask
| strengthen invs_valid_pspace' invs_pspace_aligned'
invs_pspace_distinct' empty_descendants_range_in')+
apply (wp deleteObjects_invs'[where p="makePoolParent aci"]
hoare_vcg_ex_lift
deleteObjects_caps_no_overlap''[where slot="makePoolParent aci"]
deleteObject_no_overlap
deleteObjects_cap_to'[where p="makePoolParent aci"]
deleteObjects_ct_active'[where cref="makePoolParent aci"]
deleteObjects_descendants[where p="makePoolParent aci"]
deleteObjects_cte_wp_at'
deleteObjects_null_filter[where p="makePoolParent aci"])
apply (frule valid_capAligned)
apply (clarsimp simp: invs_mdb' invs_valid_pspace' capAligned_def
cte_wp_at_ctes_of is_simple_cap'_def isCap_simps)
apply (strengthen refl ctes_of_valid_cap'[mk_strg I E])
apply (clarsimp simp: conj_comms invs_valid_objs')
apply (frule_tac ptr="w1" in descendants_range_caps_no_overlapI'[where sz = pageBits])
apply (fastforce simp: cte_wp_at_ctes_of)
apply (simp add:empty_descendants_range_in')
apply (frule(1) if_unsafe_then_capD'[OF _ invs_unsafe_then_cap',rotated])
apply (fastforce simp:cte_wp_at_ctes_of)
apply (drule ex_cte_not_in_untyped_range[rotated -2])
apply (simp add:invs_valid_global')+
apply (drule ex_cte_not_in_untyped_range[rotated -2])
apply (simp add:invs_valid_global')+
apply (subgoal_tac "is_aligned (2 ^ pageBits) minUntypedSizeBits")
prefer 2
apply (rule is_aligned_weaken)
apply (rule is_aligned_shiftl_self[unfolded shiftl_t2n,where p = 1, simplified])
apply (simp add: pageBits_def untypedBits_defs)
apply (frule_tac cte="CTE (capability.UntypedCap False a b c) m" for a b c m in valid_global_refsD', clarsimp)
apply (simp add: Int_commute)
by (auto simp:empty_descendants_range_in' objBits_simps max_free_index_def
asid_low_bits_def word_bits_def
range_cover_full descendants_range'_def2 is_aligned_mask
null_filter_descendants_of'[OF null_filter_simp'] bit_simps
valid_cap_simps' mask_def kernel_mappings_canonical)
lemma arch_performInvocation_invs':
"\<lbrace>invs' and ct_active' and valid_arch_inv' invocation\<rbrace>
Arch.performInvocation invocation
\<lbrace>\<lambda>rv. invs'\<rbrace>"
unfolding RISCV64_H.performInvocation_def
by (cases invocation, simp_all add: performRISCVMMUInvocation_def valid_arch_inv'_def; wpsimp)
end
end
|
# Problem set 1: Financial Frictions, Liquidity and the Business Cycle.
This notebook sums up relevant information on the setup for the exercises. If further suggests what to think about, before going to exercise classes. The solution follows from "PS1.ipynb".
```python
import numpy as np
import math
import itertools
from scipy import optimize
import scipy.stats as stats
import PS1 as func
# For plots:
import matplotlib.pyplot as plt
import matplotlib as mpl
%matplotlib inline
plt.style.use('seaborn-whitegrid')
mpl.style.use('seaborn')
prop_cycle = plt.rcParams["axes.prop_cycle"]
colors = prop_cycle.by_key()["color"]
import ipywidgets as widgets
from ipywidgets import interact, interact_manual
```
# Exercise 3.5 in JT (The Theory of Corporate Finance)
Consider the continuous the continuous investment model with decreasing returns to scale outlined in chapter 3 of JT. The core of the model is as follows:
- Let $I\in[0, \infty)$ be the level of investment in a given project.
- Entrepreneur proposes a project. If successful the project generates income $R(I)$; if not the project generates $0$.
- The probability of success depends on the behavior of the entrepreneur. If E behaves $(b)$ then probability of success is $p_H\in(0,1)$. If E does not behave $(nb)$ then the probability of success is $p_L$ where $0\leq p_L<p_H$.
- The entrepreneur has an incentive to not behave $(nb)$, as he receives $BI$ in private benefits in this case.
- The entrepreneur is endowed with A in assets.
- No investment project is profitable, if entrepreneur chooses not to behave.
- The entrepreneur's technology obeys the following conditions:
1. Positive, but decreasing returns to investments: $R'(I)>0, R''(I)<0$.
2. *Regularity condition 1:* Under perfect information a positive investment level would be optimal, i.e. $R'(0)>1/p_H$.
3. *Regularity condition 2:* Under perfect information a finite level of investment is optiaml, i.e. $ lim_{I\rightarrow \infty} R'(I) < 1/p_H$.
- Assume perfect competition between lenders.
- We will consider loan agreements where the entrepreneur *pledges income* $R(I)-R_b(I)$, to the lender. This leaves the entrepreneur with $R_b(I)$ if the project is successful.
### Suggestions before exercise class:
1. Write up the utility for an entrepreneur, in the case where he behaves $(u_b)$ and in the case where he does not $(u_{nb})$.
2. Write up the *incentive compatibility constraint* (IC) stating what level of $R_b(I)$ is needed, for the entrepreneur to choose to behave.
3. Write up the *individual rationality constraint* (IR) for the lender, ensuring that he will agree to the loan contract.
4. What does the *perfect competition* amongst lenders imply, for the contract the entrepreneur will offer?
5. Given that lenders are profit maximizing, what does this imply for the level $R_b(I)$ in the loan contract? (Hint: Think about the (IC) constraint).
*NB: You may initialize a version of the model by calling the class contInvest. This has two plotting features that you might find usefull. See below*
```python
Model_exercise35 = func.contInvest() # If you are interested in what resides in the model-instance "Model_exercise35" you can write 'Model_exercise35.__dict__' for an overview.
Model_exercise35.plot_eu() # This plots the function w. default parameter-values. For non-default parameters, see below:
```
*If you want to change parameters and run the model again, use the built-in 'upd_par' function as follows:*
```python
par = {'pL': 0.1,
'pH': 0.9,
'B': 1} # New parameter-values. There are more parameters that you can change; this is only a selection of them.
Model_exercise35.upd_par(par)
Model_exercise35.plot_eu()
```
On a grid of assets the next plot shows:
1. the 'unconstrained' solution (where there is no moral hazard),
2. the level of investment there the IC constraint (that induces 'good' behavior) is exactly binding), and
3. the equilibrium outcome.
```python
Model_exercise35.plot_interactive_sol()
```
interactive(children=(SelectionSlider(description='Probability, $p_H$', options=(0.6, 0.61, 0.62, 0.64, 0.65, …
# Exercise 6.1 in JT: Privately known private benefit and market breakdown
Let us start with a brief outline of the setup (from section 6.2), compared to exercise 3.5 (a lot of is the same, will not be repeated here):
* Two types of entrepreneurs: Good and bad types with private benefits of not behaving $B_H>B_L$. (good type has $B_L$)
* No equity (A=0),
* Investment is not continuous, but either 0 or I.
* Investment is either successfull (return R) or not (return 0).
* Capital markets put probability $\alpha\in(0,1)$ on type 'good' and $1-\alpha$ on type 'bad'.
* Regularity conditions:
$$ \begin{align}
p_H\left(R-\dfrac{B_H}{\Delta p}\right)<I<p_H\left(R-\dfrac{B_L}{\Delta p}\right), && \text{and} && p_LR<I.
\end{align} $$
Recall that the IC condition for an entrpreneur was **behave if**: $\Delta p R_b \geq B$.
The regularity conditions thus state that:
1. It is not profitable for lenders to invest in project with 'bad' entrepreneurs **and** making sure that they behave. (first inequality)
2. It is profitable to invest in 'good type' entrepreneur **and** making sure that he behaves (second inequality).
3. It is not profitable to invest in **any** project, where the entrepreneur mis-behaves (third inequality).
### Suggestions before exercise class:
1. Interpret the three regularity conditions (the three inequalities).
2. If the first inequality holds and $R_b=B_H\Delta p$, what will the two entrepreneurs do (behave/not behave)? When negotiating contract with lender, what will the two types have an incentive to reveal about their type?
3. Same scenario for the second inequality?
# Exercise 6.2 in JT: More on pooling in credit markets.
Compared to before, alter the setup as follows:
* Continuum of types instead of good/bad. For entrepreneur $i$ the value $B_i$ is distributed according to the CDF function $H(B)$, with support on $[0, \bar{B}]$
* Monopoly lender offers credit to borrowers (entrepreneurs).
The lender offers $R_b$ for a successfull investment, otherwise 0. Borrower $i$ then behaves **if** the IC constraint holds: $B_i\leq \Delta p R_b$. The expected profits from offering the contract is then defined by:
$$\begin{align}
\pi(R_b) = H\big(\Delta p R_b\big)p_H(R-R_b)+\left[1-H\big(\Delta p R_b\big)\right] p_L(R-R_b)-I, \tag{Profits}
\end{align} $$
where $H(\Delta p R_b)$ measures the share of borrowers that behave, i.e. with $B_i<\Delta R_b$. From this note:
* The share of high-quality borrowers increase with $R_b$ (bad types start to behave).
* Same dynamics as before: Adverse selection reduces quality of lending, induces cross-subsidies between types.
### Suggestions before exercise class:
Make sure you understand the profit function. To help you along, you can experiment with the *expected profits* function below.
```python
par_62 = {'pL': 0.5,
'pH': 0.8,
'R': 10,
'I': 2, # investment cost
'Lower': 0, # lower bound on distribution of B
'Upper': 10} # upper bound on distribution of B
Model_exercise62 = func.poolingCredit(name='standard',**par_62)
Model_exercise62.plot_exp_profits()
```
You can change parameters by using the 'upd_par' function. Here, as a for instance, we lower $p_L$ and increase $p_H$:
```python
par_update = {'pL': 0.2,
'pH': 0.9}
Model_exercise62.upd_par(par)
Model_exercise62.plot_exp_profits()
```
# Exercise 13.1 JT: Improved governance
The setup in this exercise:
* Two period model, $t=0,1$.
* Continuum of entrepreneurs with initial wealth $(A)$ distributed with the CDF $G(A)$ with support on $[0,I]$.
* At time $t=0$: Entrepreneurs can invest $I$ and borrow $(I-A)$ or invest in other firms.
* Entrepreneurs are risk neutral and thus have utility $u_e=c_0+c_1$.
* As before: Receive $R$ is investment is successful, with probability $p_H$ if entrepreneur behaves or $p_L$ if he shirks (misbehaves). Shirking yields private benefits of $B$.
* Now add consumers: Behavior results in an increasing savings function $S(r)$, with $S(r)=0$ for $r<0$.
### Suggestions before exercise class:
State (similarly to other exercises) (1) the (IC) constraint, (2) the profits when the (IC) constraint exactly holds and (3) the (IR) constraint for the lender.
# Exercise from PS: Adverse selection with heterogenous ability
## The setup:
* Continuum of risk-neutral entrepreneurs (same initial $A$)
* Investment cost $I$ (where $I>A$) yields $R$ in return w. probability $p$. Otherwise $0$ return.
* Agents differ in the probability of success $p$. Is distributed on $[0,1]$ according to the pdf function $f(p_i)$. (As usual $F(p)$ is the share of agents with $p_i\leq p$. $f(p)$ is the marginal change in that probability around $p_i=p$.)
* Total supply of loanable funds is simply presented by the increasing function $S(r)$.
* This $S(r)$ is supplied by a competetive market (e.g. banks).
* Assume perfect information: This means that loan contracts **can depend on the probability of sucess p**.
* Compared to before: No assumption of private benefits from not behaving.
### Suggestions before exercise class:
The same basic things:
1. What is the (IR) constraint of an entrepreneur that has the option of (1) entering into agreement recceiving $R-R_b(p)$ if the project suceeds (zero otherwise) or (2) depositing the wealth $A$ and getting a *normal return* of r?
2. What is the zero profits condition for a bank that receives the $pR_b(p)$ if the project is successful (0 otherwise), by investing $I-A$?
|
Formal statement is: lemma fixes f :: "complex fps" and r :: ereal assumes "\<And>z. ereal (norm z) < r \<Longrightarrow> eval_fps f z \<noteq> 0" shows fps_conv_radius_inverse: "fps_conv_radius (inverse f) \<ge> min r (fps_conv_radius f)" and eval_fps_inverse: "\<And>z. ereal (norm z) < fps_conv_radius f \<Longrightarrow> ereal (norm z) < r \<Longrightarrow> eval_fps (inverse f) z = inverse (eval_fps f z)" Informal statement is: If $f$ is a complex power series such that $f(z) \neq 0$ for all $z$ with $|z| < r$, then the radius of convergence of $f^{-1}$ is at least $\min(r, \text{radius of convergence of } f)$. Moreover, if $|z| < \text{radius of convergence of } f$ and $|z| < r$, then $f^{-1}(z) = 1/f(z)$. |
(* Title: HOL/Auth/n_flash_lemma_on_inv__86.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__86 imports n_flash_base
begin
section{*All lemmas on causal relation between inv__86 and some rule r*}
lemma n_NI_Local_Get_Put_HeadVsinv__86:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeUniMsg'') ''Cmd'')) (Const UNI_Get)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Pending'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_Get_Nak_HomeVsinv__86:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Nak_Home dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Get_Nak_Home dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_Get_Put_HomeVsinv__86:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Put_Home dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Get_Put_Home dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_1Vsinv__86:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_2Vsinv__86:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_3Vsinv__86:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_4Vsinv__86:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_5Vsinv__86:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_6Vsinv__86:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7__part__0Vsinv__86:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7__part__1Vsinv__86:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__0Vsinv__86:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__1Vsinv__86:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_HomeVsinv__86:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_Home_NODE_GetVsinv__86:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8Vsinv__86:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_NODE_GetVsinv__86:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_9__part__0Vsinv__86:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_9__part__1Vsinv__86:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_10_HomeVsinv__86:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_10Vsinv__86:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_11Vsinv__86:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_Nak_HomeVsinv__86:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_Nak_Home dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_GetX_Nak_Home dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_PutX_HomeVsinv__86:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_PutX_Home dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_GetX_PutX_Home dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_ReplaceVsinv__86:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Replace src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Replace src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "((formEval (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) s))\<or>((formEval (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) s))" by auto
moreover {
assume c1: "((formEval (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) s))"
have "?P2 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately have "invHoldForRule s f r (invariants N)" by satx
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_PI_Local_Get_GetVsinv__86:
assumes a1: "(r=n_PI_Local_Get_Get )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "?P3 s"
apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const true))))" in exI, auto) done
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_PI_Local_GetX_GetX__part__0Vsinv__86:
assumes a1: "(r=n_PI_Local_GetX_GetX__part__0 )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_PI_Local_GetX_GetX__part__1Vsinv__86:
assumes a1: "(r=n_PI_Local_GetX_GetX__part__1 )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_PI_Local_GetX_PutX_HeadVld__part__0Vsinv__86:
assumes a1: "(r=n_PI_Local_GetX_PutX_HeadVld__part__0 N )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_PI_Local_GetX_PutX_HeadVld__part__1Vsinv__86:
assumes a1: "(r=n_PI_Local_GetX_PutX_HeadVld__part__1 N )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_Nak_HomeVsinv__86:
assumes a1: "(r=n_NI_Nak_Home )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_Local_PutVsinv__86:
assumes a1: "(r=n_NI_Local_Put )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_Local_PutXAcksDoneVsinv__86:
assumes a1: "(r=n_NI_Local_PutXAcksDone )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_ShWbVsinv__86:
assumes a1: "(r=n_NI_ShWb N )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__86 p__Inv4" apply fastforce done
have "((formEval (andForm (eqn (Const (index p__Inv4)) (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''Proc''))) (eqn (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''HomeProc'')) (Const false))) s))\<or>((formEval (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true)) s))\<or>((formEval (andForm (neg (eqn (Const (index p__Inv4)) (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''Proc'')))) (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''HomeProc'')) (Const false))) (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true)))) s))" by auto
moreover {
assume c1: "((formEval (andForm (eqn (Const (index p__Inv4)) (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''Proc''))) (eqn (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''HomeProc'')) (Const false))) s))"
have "?P3 s"
apply (cut_tac a1 a2 c1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeUniMsg'') ''Cmd'')) (Const UNI_Get)) (eqn (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''Cmd'')) (Const SHWB_ShWb))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true)) s))"
have "?P3 s"
apply (cut_tac a1 a2 c1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeUniMsg'') ''Cmd'')) (Const UNI_Get)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (neg (eqn (Const (index p__Inv4)) (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''Proc'')))) (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true)))) s))"
have "?P1 s"
proof(cut_tac a1 a2 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''HomeProc'')) (Const false))) (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true)))) s))"
have "?P1 s"
proof(cut_tac a1 a2 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Get__part__1Vsinv__86:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_GetVsinv__86:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_PI_Remote_Get src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX__part__0Vsinv__86:
assumes a1: "r=n_PI_Local_GetX_PutX__part__0 " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_WbVsinv__86:
assumes a1: "r=n_NI_Wb " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_StoreVsinv__86:
assumes a1: "\<exists> src data. src\<le>N\<and>data\<le>N\<and>r=n_Store src data" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_GetX__part__1Vsinv__86:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_3Vsinv__86:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_3 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_1Vsinv__86:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_1 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_ReplaceVsinv__86:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_PI_Remote_Replace src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_Store_HomeVsinv__86:
assumes a1: "\<exists> data. data\<le>N\<and>r=n_Store_Home data" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_ReplaceVsinv__86:
assumes a1: "r=n_PI_Local_Replace " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_Nak__part__1Vsinv__86:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_Nak__part__1Vsinv__86:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_Get__part__0Vsinv__86:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_existsVsinv__86:
assumes a1: "\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_InvAck_exists src pp" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_Nak__part__2Vsinv__86:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_PutXVsinv__86:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_PI_Remote_PutX dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvVsinv__86:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Inv dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_PutXVsinv__86:
assumes a1: "r=n_PI_Local_PutX " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_Nak__part__2Vsinv__86:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_GetX__part__0Vsinv__86:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_Get_PutVsinv__86:
assumes a1: "r=n_PI_Local_Get_Put " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_GetX_NakVsinv__86:
assumes a1: "\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_NakVsinv__86:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Nak dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_GetXVsinv__86:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_PI_Remote_GetX src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX__part__1Vsinv__86:
assumes a1: "r=n_PI_Local_GetX_PutX__part__1 " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_PutXVsinv__86:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_PutX dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_PutVsinv__86:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Put dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_PutVsinv__86:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_Nak__part__0Vsinv__86:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_exists_HomeVsinv__86:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_exists_Home src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Replace_HomeVsinv__86:
assumes a1: "r=n_NI_Replace_Home " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_GetX_PutXVsinv__86:
assumes a1: "\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_Get_NakVsinv__86:
assumes a1: "\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Nak_ClearVsinv__86:
assumes a1: "r=n_NI_Nak_Clear " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_Put_DirtyVsinv__86:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_Nak__part__0Vsinv__86:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_Get_PutVsinv__86:
assumes a1: "\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_2Vsinv__86:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_2 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_FAckVsinv__86:
assumes a1: "r=n_NI_FAck " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__86 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
end
|
[STATEMENT]
lemma keys_Const\<^sub>0: "keys (Const\<^sub>0 c) = (if c = 0 then {} else {0})"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. keys (Const\<^sub>0 c) = (if c = (0::'b) then {} else {0})
[PROOF STEP]
unfolding Const\<^sub>0_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. keys (Poly_Mapping.single 0 c) = (if c = (0::'b) then {} else {0})
[PROOF STEP]
by transfer' auto |
theory Submission
imports Defs
begin
fun find_pfx :: "nat list \<Rightarrow> nat \<Rightarrow> nat list" where
"find_pfx [] v = []" |
"find_pfx (x#xs) v = (if x = v then [x] else x#(find_pfx xs v))"
value "find_pfx [1::nat,2,3] 2 = [1,2]"
value "find_pfx [] (1::nat) = []"
lemma find_pfx_append:
"(find_pfx (xs1 @ [x] @ xs2) x) = (find_pfx (xs1 @ [x]) x)"
by(induction xs1, auto)
lemma find_pfx_not_empty: "x \<in> set xs \<Longrightarrow> length (find_pfx xs x) > 0"
by(induction xs, auto)
lemma last_find_pfx_val:
"last (find_pfx (xs @ [x]) x) = x"
using find_pfx_not_empty by(induction xs, auto)
lemma find_pfx_suff[simp]: "x \<in> set xs \<Longrightarrow> find_pfx (xs @ ys) x = find_pfx xs x"
by(induction xs, auto)
lemma pfx_append_same: "x \<in> set xs \<Longrightarrow> find_pfx (xs @ xs) x = find_pfx xs x"
by simp
end |
[GOAL]
𝕜 : 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_4
inst✝⁷ : NormedAddCommGroup G
inst✝⁶ : NormedSpace 𝕜 G
G' : Type u_5
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
𝕜' : Type u_6
inst✝³ : NontriviallyNormedField 𝕜'
inst✝² : NormedAlgebra 𝕜 𝕜'
inst✝¹ : NormedSpace 𝕜' F
inst✝ : IsScalarTower 𝕜 𝕜' F
c : E → 𝕜'
c' : E →L[𝕜] 𝕜'
hc : HasStrictFDerivAt c c' x
f : F
⊢ HasStrictFDerivAt (fun y => c y • f) (smulRight c' f) x
[PROOFSTEP]
simpa only [smul_zero, zero_add] using hc.smul (hasStrictFDerivAt_const f x)
[GOAL]
𝕜 : 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_4
inst✝⁷ : NormedAddCommGroup G
inst✝⁶ : NormedSpace 𝕜 G
G' : Type u_5
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
𝕜' : Type u_6
inst✝³ : NontriviallyNormedField 𝕜'
inst✝² : NormedAlgebra 𝕜 𝕜'
inst✝¹ : NormedSpace 𝕜' F
inst✝ : IsScalarTower 𝕜 𝕜' F
c : E → 𝕜'
c' : E →L[𝕜] 𝕜'
hc : HasFDerivWithinAt c c' s x
f : F
⊢ HasFDerivWithinAt (fun y => c y • f) (smulRight c' f) s x
[PROOFSTEP]
simpa only [smul_zero, zero_add] using hc.smul (hasFDerivWithinAt_const f x s)
[GOAL]
𝕜 : 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_4
inst✝⁷ : NormedAddCommGroup G
inst✝⁶ : NormedSpace 𝕜 G
G' : Type u_5
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
𝕜' : Type u_6
inst✝³ : NontriviallyNormedField 𝕜'
inst✝² : NormedAlgebra 𝕜 𝕜'
inst✝¹ : NormedSpace 𝕜' F
inst✝ : IsScalarTower 𝕜 𝕜' F
c : E → 𝕜'
c' : E →L[𝕜] 𝕜'
hc : HasFDerivAt c c' x
f : F
⊢ HasFDerivAt (fun y => c y • f) (smulRight c' f) x
[PROOFSTEP]
simpa only [smul_zero, zero_add] using hc.smul (hasFDerivAt_const f x)
[GOAL]
𝕜 : 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_4
inst✝⁷ : NormedAddCommGroup G
inst✝⁶ : NormedSpace 𝕜 G
G' : Type u_5
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
𝔸 : Type u_6
𝔸' : Type u_7
inst✝³ : NormedRing 𝔸
inst✝² : NormedCommRing 𝔸'
inst✝¹ : NormedAlgebra 𝕜 𝔸
inst✝ : NormedAlgebra 𝕜 𝔸'
a b : E → 𝔸
a' b' : E →L[𝕜] 𝔸
c d : E → 𝔸'
c' d' : E →L[𝕜] 𝔸'
hc : HasStrictFDerivAt c c' x
hd : HasStrictFDerivAt d d' x
⊢ HasStrictFDerivAt (fun y => c y * d y) (c x • d' + d x • c') x
[PROOFSTEP]
convert hc.mul' hd
[GOAL]
case h.e'_10.h.e'_6
𝕜 : 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_4
inst✝⁷ : NormedAddCommGroup G
inst✝⁶ : NormedSpace 𝕜 G
G' : Type u_5
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
𝔸 : Type u_6
𝔸' : Type u_7
inst✝³ : NormedRing 𝔸
inst✝² : NormedCommRing 𝔸'
inst✝¹ : NormedAlgebra 𝕜 𝔸
inst✝ : NormedAlgebra 𝕜 𝔸'
a b : E → 𝔸
a' b' : E →L[𝕜] 𝔸
c d : E → 𝔸'
c' d' : E →L[𝕜] 𝔸'
hc : HasStrictFDerivAt c c' x
hd : HasStrictFDerivAt d d' x
⊢ d x • c' = smulRight c' (d x)
[PROOFSTEP]
ext z
[GOAL]
case h.e'_10.h.e'_6.h
𝕜 : 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_4
inst✝⁷ : NormedAddCommGroup G
inst✝⁶ : NormedSpace 𝕜 G
G' : Type u_5
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
𝔸 : Type u_6
𝔸' : Type u_7
inst✝³ : NormedRing 𝔸
inst✝² : NormedCommRing 𝔸'
inst✝¹ : NormedAlgebra 𝕜 𝔸
inst✝ : NormedAlgebra 𝕜 𝔸'
a b : E → 𝔸
a' b' : E →L[𝕜] 𝔸
c d : E → 𝔸'
c' d' : E →L[𝕜] 𝔸'
hc : HasStrictFDerivAt c c' x
hd : HasStrictFDerivAt d d' x
z : E
⊢ ↑(d x • c') z = ↑(smulRight c' (d x)) z
[PROOFSTEP]
apply mul_comm
[GOAL]
𝕜 : 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_4
inst✝⁷ : NormedAddCommGroup G
inst✝⁶ : NormedSpace 𝕜 G
G' : Type u_5
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
𝔸 : Type u_6
𝔸' : Type u_7
inst✝³ : NormedRing 𝔸
inst✝² : NormedCommRing 𝔸'
inst✝¹ : NormedAlgebra 𝕜 𝔸
inst✝ : NormedAlgebra 𝕜 𝔸'
a b : E → 𝔸
a' b' : E →L[𝕜] 𝔸
c d : E → 𝔸'
c' d' : E →L[𝕜] 𝔸'
hc : HasFDerivWithinAt c c' s x
hd : HasFDerivWithinAt d d' s x
⊢ HasFDerivWithinAt (fun y => c y * d y) (c x • d' + d x • c') s x
[PROOFSTEP]
convert hc.mul' hd
[GOAL]
case h.e'_10.h.e'_6
𝕜 : 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_4
inst✝⁷ : NormedAddCommGroup G
inst✝⁶ : NormedSpace 𝕜 G
G' : Type u_5
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
𝔸 : Type u_6
𝔸' : Type u_7
inst✝³ : NormedRing 𝔸
inst✝² : NormedCommRing 𝔸'
inst✝¹ : NormedAlgebra 𝕜 𝔸
inst✝ : NormedAlgebra 𝕜 𝔸'
a b : E → 𝔸
a' b' : E →L[𝕜] 𝔸
c d : E → 𝔸'
c' d' : E →L[𝕜] 𝔸'
hc : HasFDerivWithinAt c c' s x
hd : HasFDerivWithinAt d d' s x
⊢ d x • c' = smulRight c' (d x)
[PROOFSTEP]
ext z
[GOAL]
case h.e'_10.h.e'_6.h
𝕜 : 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_4
inst✝⁷ : NormedAddCommGroup G
inst✝⁶ : NormedSpace 𝕜 G
G' : Type u_5
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
𝔸 : Type u_6
𝔸' : Type u_7
inst✝³ : NormedRing 𝔸
inst✝² : NormedCommRing 𝔸'
inst✝¹ : NormedAlgebra 𝕜 𝔸
inst✝ : NormedAlgebra 𝕜 𝔸'
a b : E → 𝔸
a' b' : E →L[𝕜] 𝔸
c d : E → 𝔸'
c' d' : E →L[𝕜] 𝔸'
hc : HasFDerivWithinAt c c' s x
hd : HasFDerivWithinAt d d' s x
z : E
⊢ ↑(d x • c') z = ↑(smulRight c' (d x)) z
[PROOFSTEP]
apply mul_comm
[GOAL]
𝕜 : 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_4
inst✝⁷ : NormedAddCommGroup G
inst✝⁶ : NormedSpace 𝕜 G
G' : Type u_5
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
𝔸 : Type u_6
𝔸' : Type u_7
inst✝³ : NormedRing 𝔸
inst✝² : NormedCommRing 𝔸'
inst✝¹ : NormedAlgebra 𝕜 𝔸
inst✝ : NormedAlgebra 𝕜 𝔸'
a b : E → 𝔸
a' b' : E →L[𝕜] 𝔸
c d : E → 𝔸'
c' d' : E →L[𝕜] 𝔸'
hc : HasFDerivAt c c' x
hd : HasFDerivAt d d' x
⊢ HasFDerivAt (fun y => c y * d y) (c x • d' + d x • c') x
[PROOFSTEP]
convert hc.mul' hd
[GOAL]
case h.e'_10.h.e'_6
𝕜 : 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_4
inst✝⁷ : NormedAddCommGroup G
inst✝⁶ : NormedSpace 𝕜 G
G' : Type u_5
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
𝔸 : Type u_6
𝔸' : Type u_7
inst✝³ : NormedRing 𝔸
inst✝² : NormedCommRing 𝔸'
inst✝¹ : NormedAlgebra 𝕜 𝔸
inst✝ : NormedAlgebra 𝕜 𝔸'
a b : E → 𝔸
a' b' : E →L[𝕜] 𝔸
c d : E → 𝔸'
c' d' : E →L[𝕜] 𝔸'
hc : HasFDerivAt c c' x
hd : HasFDerivAt d d' x
⊢ d x • c' = smulRight c' (d x)
[PROOFSTEP]
ext z
[GOAL]
case h.e'_10.h.e'_6.h
𝕜 : 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_4
inst✝⁷ : NormedAddCommGroup G
inst✝⁶ : NormedSpace 𝕜 G
G' : Type u_5
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
𝔸 : Type u_6
𝔸' : Type u_7
inst✝³ : NormedRing 𝔸
inst✝² : NormedCommRing 𝔸'
inst✝¹ : NormedAlgebra 𝕜 𝔸
inst✝ : NormedAlgebra 𝕜 𝔸'
a b : E → 𝔸
a' b' : E →L[𝕜] 𝔸
c d : E → 𝔸'
c' d' : E →L[𝕜] 𝔸'
hc : HasFDerivAt c c' x
hd : HasFDerivAt d d' x
z : E
⊢ ↑(d x • c') z = ↑(smulRight c' (d x)) z
[PROOFSTEP]
apply mul_comm
[GOAL]
𝕜 : 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_4
inst✝⁷ : NormedAddCommGroup G
inst✝⁶ : NormedSpace 𝕜 G
G' : Type u_5
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
𝔸 : Type u_6
𝔸' : Type u_7
inst✝³ : NormedRing 𝔸
inst✝² : NormedCommRing 𝔸'
inst✝¹ : NormedAlgebra 𝕜 𝔸
inst✝ : NormedAlgebra 𝕜 𝔸'
a b : E → 𝔸
a' b' : E →L[𝕜] 𝔸
c d : E → 𝔸'
c' d' : E →L[𝕜] 𝔸'
ha : DifferentiableWithinAt 𝕜 a s x
⊢ DifferentiableWithinAt 𝕜 (fun x => a x ^ 0) s x
[PROOFSTEP]
simp only [pow_zero, differentiableWithinAt_const]
[GOAL]
𝕜 : 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_4
inst✝⁷ : NormedAddCommGroup G
inst✝⁶ : NormedSpace 𝕜 G
G' : Type u_5
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
𝔸 : Type u_6
𝔸' : Type u_7
inst✝³ : NormedRing 𝔸
inst✝² : NormedCommRing 𝔸'
inst✝¹ : NormedAlgebra 𝕜 𝔸
inst✝ : NormedAlgebra 𝕜 𝔸'
a b : E → 𝔸
a' b' : E →L[𝕜] 𝔸
c d : E → 𝔸'
c' d' : E →L[𝕜] 𝔸'
ha : DifferentiableWithinAt 𝕜 a s x
n : ℕ
⊢ DifferentiableWithinAt 𝕜 (fun x => a x ^ (n + 1)) s x
[PROOFSTEP]
simp only [pow_succ, DifferentiableWithinAt.pow ha n, ha.mul]
[GOAL]
𝕜 : 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_4
inst✝⁷ : NormedAddCommGroup G
inst✝⁶ : NormedSpace 𝕜 G
G' : Type u_5
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
𝔸 : Type u_6
𝔸' : Type u_7
inst✝³ : NormedRing 𝔸
inst✝² : NormedCommRing 𝔸'
inst✝¹ : NormedAlgebra 𝕜 𝔸
inst✝ : NormedAlgebra 𝕜 𝔸'
a b : E → 𝔸
a' b' : E →L[𝕜] 𝔸
c d✝ : E → 𝔸'
c' d' : E →L[𝕜] 𝔸'
hc : HasStrictFDerivAt c c' x
d : 𝔸'
⊢ HasStrictFDerivAt (fun y => c y * d) (d • c') x
[PROOFSTEP]
convert hc.mul_const' d
[GOAL]
case h.e'_10
𝕜 : 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_4
inst✝⁷ : NormedAddCommGroup G
inst✝⁶ : NormedSpace 𝕜 G
G' : Type u_5
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
𝔸 : Type u_6
𝔸' : Type u_7
inst✝³ : NormedRing 𝔸
inst✝² : NormedCommRing 𝔸'
inst✝¹ : NormedAlgebra 𝕜 𝔸
inst✝ : NormedAlgebra 𝕜 𝔸'
a b : E → 𝔸
a' b' : E →L[𝕜] 𝔸
c d✝ : E → 𝔸'
c' d' : E →L[𝕜] 𝔸'
hc : HasStrictFDerivAt c c' x
d : 𝔸'
⊢ d • c' = smulRight c' d
[PROOFSTEP]
ext z
[GOAL]
case h.e'_10.h
𝕜 : 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_4
inst✝⁷ : NormedAddCommGroup G
inst✝⁶ : NormedSpace 𝕜 G
G' : Type u_5
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
𝔸 : Type u_6
𝔸' : Type u_7
inst✝³ : NormedRing 𝔸
inst✝² : NormedCommRing 𝔸'
inst✝¹ : NormedAlgebra 𝕜 𝔸
inst✝ : NormedAlgebra 𝕜 𝔸'
a b : E → 𝔸
a' b' : E →L[𝕜] 𝔸
c d✝ : E → 𝔸'
c' d' : E →L[𝕜] 𝔸'
hc : HasStrictFDerivAt c c' x
d : 𝔸'
z : E
⊢ ↑(d • c') z = ↑(smulRight c' d) z
[PROOFSTEP]
apply mul_comm
[GOAL]
𝕜 : 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_4
inst✝⁷ : NormedAddCommGroup G
inst✝⁶ : NormedSpace 𝕜 G
G' : Type u_5
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
𝔸 : Type u_6
𝔸' : Type u_7
inst✝³ : NormedRing 𝔸
inst✝² : NormedCommRing 𝔸'
inst✝¹ : NormedAlgebra 𝕜 𝔸
inst✝ : NormedAlgebra 𝕜 𝔸'
a b : E → 𝔸
a' b' : E →L[𝕜] 𝔸
c d✝ : E → 𝔸'
c' d' : E →L[𝕜] 𝔸'
hc : HasFDerivWithinAt c c' s x
d : 𝔸'
⊢ HasFDerivWithinAt (fun y => c y * d) (d • c') s x
[PROOFSTEP]
convert hc.mul_const' d
[GOAL]
case h.e'_10
𝕜 : 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_4
inst✝⁷ : NormedAddCommGroup G
inst✝⁶ : NormedSpace 𝕜 G
G' : Type u_5
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
𝔸 : Type u_6
𝔸' : Type u_7
inst✝³ : NormedRing 𝔸
inst✝² : NormedCommRing 𝔸'
inst✝¹ : NormedAlgebra 𝕜 𝔸
inst✝ : NormedAlgebra 𝕜 𝔸'
a b : E → 𝔸
a' b' : E →L[𝕜] 𝔸
c d✝ : E → 𝔸'
c' d' : E →L[𝕜] 𝔸'
hc : HasFDerivWithinAt c c' s x
d : 𝔸'
⊢ d • c' = smulRight c' d
[PROOFSTEP]
ext z
[GOAL]
case h.e'_10.h
𝕜 : 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_4
inst✝⁷ : NormedAddCommGroup G
inst✝⁶ : NormedSpace 𝕜 G
G' : Type u_5
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
𝔸 : Type u_6
𝔸' : Type u_7
inst✝³ : NormedRing 𝔸
inst✝² : NormedCommRing 𝔸'
inst✝¹ : NormedAlgebra 𝕜 𝔸
inst✝ : NormedAlgebra 𝕜 𝔸'
a b : E → 𝔸
a' b' : E →L[𝕜] 𝔸
c d✝ : E → 𝔸'
c' d' : E →L[𝕜] 𝔸'
hc : HasFDerivWithinAt c c' s x
d : 𝔸'
z : E
⊢ ↑(d • c') z = ↑(smulRight c' d) z
[PROOFSTEP]
apply mul_comm
[GOAL]
𝕜 : 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_4
inst✝⁷ : NormedAddCommGroup G
inst✝⁶ : NormedSpace 𝕜 G
G' : Type u_5
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
𝔸 : Type u_6
𝔸' : Type u_7
inst✝³ : NormedRing 𝔸
inst✝² : NormedCommRing 𝔸'
inst✝¹ : NormedAlgebra 𝕜 𝔸
inst✝ : NormedAlgebra 𝕜 𝔸'
a b : E → 𝔸
a' b' : E →L[𝕜] 𝔸
c d✝ : E → 𝔸'
c' d' : E →L[𝕜] 𝔸'
hc : HasFDerivAt c c' x
d : 𝔸'
⊢ HasFDerivAt (fun y => c y * d) (d • c') x
[PROOFSTEP]
convert hc.mul_const' d
[GOAL]
case h.e'_10
𝕜 : 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_4
inst✝⁷ : NormedAddCommGroup G
inst✝⁶ : NormedSpace 𝕜 G
G' : Type u_5
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
𝔸 : Type u_6
𝔸' : Type u_7
inst✝³ : NormedRing 𝔸
inst✝² : NormedCommRing 𝔸'
inst✝¹ : NormedAlgebra 𝕜 𝔸
inst✝ : NormedAlgebra 𝕜 𝔸'
a b : E → 𝔸
a' b' : E →L[𝕜] 𝔸
c d✝ : E → 𝔸'
c' d' : E →L[𝕜] 𝔸'
hc : HasFDerivAt c c' x
d : 𝔸'
⊢ d • c' = smulRight c' d
[PROOFSTEP]
ext z
[GOAL]
case h.e'_10.h
𝕜 : 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_4
inst✝⁷ : NormedAddCommGroup G
inst✝⁶ : NormedSpace 𝕜 G
G' : Type u_5
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
𝔸 : Type u_6
𝔸' : Type u_7
inst✝³ : NormedRing 𝔸
inst✝² : NormedCommRing 𝔸'
inst✝¹ : NormedAlgebra 𝕜 𝔸
inst✝ : NormedAlgebra 𝕜 𝔸'
a b : E → 𝔸
a' b' : E →L[𝕜] 𝔸
c d✝ : E → 𝔸'
c' d' : E →L[𝕜] 𝔸'
hc : HasFDerivAt c c' x
d : 𝔸'
z : E
⊢ ↑(d • c') z = ↑(smulRight c' d) z
[PROOFSTEP]
apply mul_comm
[GOAL]
𝕜 : 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_4
inst✝⁶ : NormedAddCommGroup G
inst✝⁵ : NormedSpace 𝕜 G
G' : Type u_5
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
R : Type u_6
inst✝² : NormedRing R
inst✝¹ : NormedAlgebra 𝕜 R
inst✝ : CompleteSpace R
x : Rˣ
this : (fun t => Ring.inverse (↑x + t) - ↑x⁻¹ + ↑x⁻¹ * t * ↑x⁻¹) =o[𝓝 0] _root_.id
⊢ HasFDerivAt Ring.inverse (-↑(↑(mulLeftRight 𝕜 R) ↑x⁻¹) ↑x⁻¹) ↑x
[PROOFSTEP]
simpa [hasFDerivAt_iff_isLittleO_nhds_zero] using this
[GOAL]
𝕜 : 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_4
inst✝⁶ : NormedAddCommGroup G
inst✝⁵ : NormedSpace 𝕜 G
G' : Type u_5
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
R : Type u_6
inst✝² : NormedDivisionRing R
inst✝¹ : NormedAlgebra 𝕜 R
inst✝ : CompleteSpace R
x : R
hx : x ≠ 0
⊢ HasFDerivAt Inv.inv (-↑(↑(mulLeftRight 𝕜 R) x⁻¹) x⁻¹) x
[PROOFSTEP]
simpa using hasFDerivAt_ring_inverse (Units.mk0 _ hx)
[GOAL]
𝕜 : 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_4
inst✝⁶ : NormedAddCommGroup G
inst✝⁵ : NormedSpace 𝕜 G
G' : Type u_5
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
R : Type u_6
inst✝² : NormedDivisionRing R
inst✝¹ : NormedAlgebra 𝕜 R
inst✝ : CompleteSpace R
s : Set R
x : R
hx : x ≠ 0
hxs : UniqueDiffWithinAt 𝕜 s x
⊢ fderivWithin 𝕜 (fun x => x⁻¹) s x = -↑(↑(mulLeftRight 𝕜 R) x⁻¹) x⁻¹
[PROOFSTEP]
rw [DifferentiableAt.fderivWithin (differentiableAt_inv' hx) hxs]
[GOAL]
𝕜 : 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_4
inst✝⁶ : NormedAddCommGroup G
inst✝⁵ : NormedSpace 𝕜 G
G' : Type u_5
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
R : Type u_6
inst✝² : NormedDivisionRing R
inst✝¹ : NormedAlgebra 𝕜 R
inst✝ : CompleteSpace R
s : Set R
x : R
hx : x ≠ 0
hxs : UniqueDiffWithinAt 𝕜 s x
⊢ fderiv 𝕜 Inv.inv x = -↑(↑(mulLeftRight 𝕜 R) x⁻¹) x⁻¹
[PROOFSTEP]
exact fderiv_inv' hx
|
```javascript
%%javascript
MathJax.Hub.Config({TeX: { equationNumbers: { autoNumber: "AMS" } }});
```
<IPython.core.display.Javascript object>
# WFLC - Weighted Fourier Linear Combiner
The WFLC is an extension of the FLC algorithm first presented in this [paper](http://ieeexplore.ieee.org/document/686791/), and like the FLC it models the tremor input as a dynamic truncated Fourier series. Where the FLC works on a preset fixed frequency, the WFLC can adapt the frequency of the model as well as its Fourier coefficients. The WFLC can, therefore, compensate for approximately periodic disturbance of unknown frequency and amplitude. The WFLC does not filter away the voluntary movement when used for estimating a tremor signal, and in the [paper](http://ieeexplore.ieee.org/document/686791/), a bandpass prefilter with passband 7-13 Hz was used before the WFLC to filter away voluntary motion. The bandpass filter has a small phase lag, so the estimated frequency from the WFLC is sent to an FLC with no prefiltering to get a zero-phase tremor estimation.
The equations for the WFLC filter are as follows
\begin{equation}
y_k=\sum_{r=0}^{n}a_{rk}\sin(r\omega_{0_k} k )+b_{rk}\cos(r\omega_{0_k}k)
\end{equation}
\begin{align}
\textbf{x}_k&=
\begin{bmatrix}
[\sin(\omega_{0_k}k)&\sin(2\omega_{0_k}k)&\cdots&\sin(n\omega_{0_k}k)]^T \\
[\cos(\omega_{0_k}k)&\cos(2\omega_{0_k}k)&\cdots&\cos(n\omega_{0_k}k)]^T
\end{bmatrix}\\
\textbf{w}_k&=\begin{bmatrix}
[a_{1k}&a_{2k}&\cdots & a_{nk}]^T\\
[b_{1k}&b_{2k}&\cdots & b_{nk}]^T
\end{bmatrix} \\
y_k&=\textbf{w}_k^T\textbf{x}_k\\
\varepsilon_k&=s_k-y_k=s_k-\textbf{w}_k^T\textbf{x}_k\\
\textbf{w}_{k+1}&=\textbf{w}_k+2\mu\textbf{x}_k\epsilon_k
\end{align}
The fundamental angular frequency, $\omega_{0_k}$, is updated using a modified LSM algorithm, with its own adaptive gain, $\mu_0$
\begin{equation}\label{eq:w0k}
\omega_{0_{k+1}}=\omega_{0_k}+2\mu_0\varepsilon_k\sum_{r=1}^{n}r\left[a_{rk}\cos(r\omega_{0_k}k)-b_{rk}\sin(r\omega_{0_k}k) \right]
\end{equation}
Input amplitude and phase are estimated by the adaptive weight vector $\textbf{w}_k$, as in FLC, while $\omega_{0_k}$ estimates the input frequency. If $\mu_0=0$, the WFLC reduces to the FLC.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.