text
stringlengths 0
3.34M
|
---|
(* Title: An adaptation of the work on Presburger automata to the automata
defined here
Authors: Thomas Tuerk <[email protected]>
*)
section \<open> Presburger Adaptation \<close>
theory Presburger_Adapt
imports Main NFA DFA
"implementation/NFASpec"
"../Presburger-Automata/DFS"
"../Presburger-Automata/Presburger_Automata"
begin
text \<open> The translation of Presburger arithmetic to finite automata
defined in the AFP Library \emph{Presburger-Automata} consists of
building finite automata for Diophantine equations and inequations as well as
standard automata constructions. These automata constructions are
however defined on a datastructure which is well suited for the
specific automata used. Here, let's try to replace these specialised
finite automata with general ones. \<close>
subsection \<open> DFAs for Diophantine Equations and Inequations \<close>
subsubsection \<open> Definition \<close>
datatype pres_NFA_state =
pres_NFA_state_error
| pres_NFA_state_int int
fun pres_DFA_eq_ineq_trans_fun where
"pres_DFA_eq_ineq_trans_fun ineq ks pres_NFA_state_error _ = pres_NFA_state_error"
| "pres_DFA_eq_ineq_trans_fun ineq ks (pres_NFA_state_int j) bs =
(if (ineq \<or> (eval_dioph ks (map nat_of_bool bs)) mod 2 = j mod 2)
then pres_NFA_state_int ((j - (eval_dioph ks (map nat_of_bool bs))) div 2)
else pres_NFA_state_error)"
fun pres_DFA_is_node where
"pres_DFA_is_node ks l (pres_NFA_state_error) = True"
| "pres_DFA_is_node ks l (pres_NFA_state_int m) =
dioph_is_node ks l m"
lemma finite_pres_DFA_is_node_set [simp] :
"finite {q. pres_DFA_is_node ks l q}"
proof -
have set_eq: "{q. pres_DFA_is_node ks l q} =
insert pres_NFA_state_error
(pres_NFA_state_int ` {m. dioph_is_node ks l m})"
(is "?s1 = ?s2")
proof (intro set_eqI)
fix q
show "(q \<in> ?s1) = (q \<in> ?s2)"
proof (cases q)
case pres_NFA_state_error thus ?thesis by simp
next
case (pres_NFA_state_int m)
thus ?thesis by auto
qed
qed
show ?thesis
apply (simp add: set_eq)
apply (rule finite_imageI)
apply (insert Presburger_Automata.dioph_dfs.graph_finite)
apply simp
done
qed
definition pres_DFA_eq_ineq ::
"bool \<Rightarrow> nat \<Rightarrow> int list \<Rightarrow> int \<Rightarrow> (pres_NFA_state, bool list) NFA_rec" where
"pres_DFA_eq_ineq ineq n ks l =
\<lparr> \<Q> = {q. pres_DFA_is_node ks l q},
\<Sigma> = {bs . length bs = n},
\<Delta> = {(q, bs, pres_DFA_eq_ineq_trans_fun ineq ks q bs) | q bs.
pres_DFA_is_node ks l q \<and> length bs = n},
\<I> = {pres_NFA_state_int l},
\<F> = {pres_NFA_state_int m |m.
dioph_is_node ks l m \<and> 0 \<le> m \<and> (ineq \<or> m = 0)} \<rparr>"
subsubsection \<open> Properties \<close>
lemma pres_DFA_is_node___pres_DFA_eq_ineq_trans_fun :
assumes q_OK: "pres_DFA_is_node ks l q"
and bs_OK: "length bs = n"
shows "pres_DFA_is_node ks l (pres_DFA_eq_ineq_trans_fun i ks q bs)"
proof (cases "pres_DFA_eq_ineq_trans_fun i ks q bs")
case pres_NFA_state_error
thus ?thesis
unfolding pres_DFA_eq_ineq_def by simp
next
case (pres_NFA_state_int m')
note q'_eq = this
then obtain m where
q_eq : "q = pres_NFA_state_int m"
and m'_eq : "m' = (m - eval_dioph ks (map nat_of_bool bs)) div 2"
and cond: "i \<or> eval_dioph ks (map nat_of_bool bs) mod 2 = m mod 2"
apply (cases q, simp_all)
by (metis pres_NFA_state.inject pres_NFA_state.simps(3))
from q_OK q_eq have is_node_m: "dioph_is_node ks l m"
unfolding pres_DFA_eq_ineq_def
by simp
have "m' \<in> set (dioph_ineq_succs n ks m)"
using bs_OK
unfolding dioph_ineq_succs_def List.map_filter_def pres_DFA_eq_ineq_def
apply (simp add: o_def image_iff m'_eq Bex_def)
apply (rule_tac exI [where x = "map nat_of_bool bs"])
apply (simp add: nat_of_bool_mk_nat_vecs)
done
with dioph_ineq_dfs.succs_is_node [OF is_node_m]
show ?thesis
unfolding pres_DFA_eq_ineq_def q'_eq
by (simp add: list_all_iff)
qed
lemma pres_DFA_eq_ineq___is_well_formed :
"DFA (pres_DFA_eq_ineq i n ks l)"
unfolding DFA_alt_def NFA_full_def SemiAutomaton_is_complete_deterministic_def
proof (intro conjI allI impI)
show "\<I> (pres_DFA_eq_ineq i n ks l) \<subseteq> \<Q> (pres_DFA_eq_ineq i n ks l)"
unfolding pres_DFA_eq_ineq_def
by (simp add: dioph_is_node_def)
next
show "\<F> (pres_DFA_eq_ineq i n ks l) \<subseteq> \<Q> (pres_DFA_eq_ineq i n ks l)"
unfolding pres_DFA_eq_ineq_def
by (auto simp add: subset_iff)
next
let ?p = "pres_DFA_eq_ineq i n ks l"
show "finite (\<Sigma> ?p)"
unfolding pres_DFA_eq_ineq_def
by (simp, rule Presburger_Automata.finite_list)
moreover
show fin\<Q>: "finite (\<Q> ?p)"
unfolding pres_DFA_eq_ineq_def
by simp
moreover
{
fix q bs q'
assume in_D: "(q, bs, q') \<in> \<Delta> ?p"
then show "q \<in> \<Q> ?p"
and "bs \<in> \<Sigma> ?p"
and "q' \<in> \<Q> ?p"
using pres_DFA_is_node___pres_DFA_eq_ineq_trans_fun
unfolding pres_DFA_eq_ineq_def
by simp_all
}
hence "\<Delta> ?p \<subseteq> \<Q> ?p \<times> \<Sigma> ?p \<times> \<Q> ?p" by auto
ultimately show "finite (\<Delta> ?p)" using finite_subset by blast
next
show "\<exists>q0. \<I> (pres_DFA_eq_ineq i n ks l) = {q0}"
unfolding pres_DFA_eq_ineq_def
by simp
next
show "LTS_is_complete_deterministic (\<Q> (pres_DFA_eq_ineq i n ks l)) (\<Sigma> (pres_DFA_eq_ineq i n ks l))
(\<Delta> (pres_DFA_eq_ineq i n ks l))"
unfolding pres_DFA_eq_ineq_def LTS_is_complete_deterministic_def
LTS_is_deterministic_def LTS_is_complete_def
by (simp add: pres_DFA_is_node___pres_DFA_eq_ineq_trans_fun)
qed
interpretation pres_DFA_eq_ineq :
DFA "pres_DFA_eq_ineq i n ks l"
using pres_DFA_eq_ineq___is_well_formed[of i n ks l] .
lemma \<delta>_pres_DFA_eq_ineq :
"\<delta> (pres_DFA_eq_ineq i n ks l) (q, bs) =
(if (pres_DFA_is_node ks l q \<and> length bs = n) then
Some (pres_DFA_eq_ineq_trans_fun i ks q bs)
else None)"
using pres_DFA_eq_ineq.\<delta>_in_\<Delta>_iff [symmetric]
pres_DFA_eq_ineq.DetSemiAutomaton_\<delta>_is_none_iff
by (simp add: pres_DFA_eq_ineq_def)
lemma pres_DFA_eq_ineq_reach_error :
"list_all (is_alph n) bss \<Longrightarrow>
DLTS_reach (\<delta> (pres_DFA_eq_ineq i n ks l)) pres_NFA_state_error bss = Some (pres_NFA_state_error)"
proof (induct bss)
case Nil thus ?case by simp
next
case (Cons bs bss)
from Cons(2) have len_bs: "length bs = n" by (simp add: is_alph_def)
from Cons(2) have bss_OK: "list_all (is_alph n) bss" by simp
note ind_hyp = Cons(1) [OF bss_OK]
from len_bs
have step: "\<delta> (pres_DFA_eq_ineq i n ks l) (pres_NFA_state_error, bs) =
Some pres_NFA_state_error"
unfolding \<delta>_pres_DFA_eq_ineq
by simp
from step ind_hyp
show ?case by simp
qed
lemma eval_dioph_nats_of_boolss_eq:
"\<lbrakk>length bs = n; list_all (is_alph n) bss\<rbrakk> \<Longrightarrow>
eval_dioph ks (nats_of_boolss n (bs # bss)) = j \<longleftrightarrow>
eval_dioph ks (map nat_of_bool bs) mod 2 = j mod 2 \<and>
eval_dioph ks (nats_of_boolss n bss) = (j - eval_dioph ks (map nat_of_bool bs)) div 2"
apply (subst eval_dioph_div_mod)
apply (simp add: nats_of_boolss_mod2 nats_of_boolss_div2)
done
lemma pres_DFA_eq_ineq_reach_eq :
assumes "pres_NFA_state_int j \<in> \<Q> (pres_DFA_eq_ineq False n ks l)"
and "list_all (is_alph n) bss"
shows "DLTS_reach (\<delta> (pres_DFA_eq_ineq False n ks l)) (pres_NFA_state_int j) bss = Some (pres_NFA_state_int 0) \<longleftrightarrow>
eval_dioph ks (nats_of_boolss n bss) = j"
using assms
proof (induct bss arbitrary: j)
case Nil
thus ?case
by (simp add: eval_dioph_replicate_0)
next
case (Cons bs bss' j)
from Cons(3) have
bs_in: "length bs = n" and
bss'_in : "list_all (is_alph n) bss'"
by (simp_all add: is_alph_def)
note ind_hyp = Cons(1) [OF _ bss'_in]
note j_in_Q = Cons(2)
have \<delta>_j_bs_eq:
"\<delta> (pres_DFA_eq_ineq False n ks l) (pres_NFA_state_int j, bs) = Some (pres_DFA_eq_ineq_trans_fun False ks (pres_NFA_state_int j) bs)"
using j_in_Q bs_in
unfolding \<delta>_pres_DFA_eq_ineq
unfolding pres_DFA_eq_ineq_def
by simp
show ?case
proof (cases "eval_dioph ks (map nat_of_bool bs) mod 2 = j mod 2")
case False
thus ?thesis
by (simp add: pres_DFA_eq_ineq_reach_error
\<delta>_j_bs_eq eval_dioph_nats_of_boolss_eq bs_in bss'_in)
next
case True note cond_true = True
have j'_in_Q: "pres_DFA_eq_ineq_trans_fun False ks (pres_NFA_state_int j) bs \<in> \<Q> (pres_DFA_eq_ineq False n ks l)"
using bs_in j_in_Q pres_DFA_is_node___pres_DFA_eq_ineq_trans_fun [where i = False]
unfolding pres_DFA_eq_ineq_def
by (simp add: cond_true del: pres_DFA_eq_ineq_trans_fun.simps)
have j'_eq: "pres_DFA_eq_ineq_trans_fun False ks (pres_NFA_state_int j) bs =
pres_NFA_state_int ((j - eval_dioph ks (map nat_of_bool bs)) div 2)"
by (simp add: cond_true)
from ind_hyp [OF j'_in_Q [unfolded j'_eq]]
show ?thesis
by (simp add: pres_DFA_eq_ineq_reach_error
\<delta>_j_bs_eq eval_dioph_nats_of_boolss_eq bs_in bss'_in)
qed
qed
lemma pres_DFA_eq_correct :
assumes bss_OK: "list_all (is_alph n) bss"
shows "NFA_accept (pres_DFA_eq_ineq False n ks l) bss =
(eval_dioph ks (nats_of_boolss n bss) = l)"
proof -
have \<i>_eval: "\<i> (pres_DFA_eq_ineq False n ks l) = pres_NFA_state_int l"
unfolding pres_DFA_eq_ineq_def
by (simp add: \<i>_def)
have \<F>_eval: "\<F> (pres_DFA_eq_ineq False n ks l) = {pres_NFA_state_int 0}"
unfolding pres_DFA_eq_ineq_def
by (auto simp add: dioph_is_node_def)
from pres_DFA_eq_ineq.\<i>_is_state [of False n ks l]
have l_in_Q: "pres_NFA_state_int l \<in> \<Q> (pres_DFA_eq_ineq False n ks l)"
by (simp add: \<i>_eval)
note dioph_OK = pres_DFA_eq_ineq_reach_eq [OF l_in_Q bss_OK, symmetric]
have "DLTS_reach (\<delta> (pres_DFA_eq_ineq False n ks l)) (pres_NFA_state_int l) bss \<noteq> None"
using bss_OK
apply (simp add: pres_DFA_eq_ineq.DetSemiAutomaton_reach_is_none_iff)
apply (simp add: pres_DFA_eq_ineq_def is_alph_def in_lists_conv_set
dioph_is_node_def Ball_set_list_all)
done
thus ?thesis
by (auto simp add: pres_DFA_eq_ineq.DFA_accept_alt_def dioph_OK \<F>_eval \<i>_eval)
qed
lemma pres_DFA_eq_ineq_reach_ineq :
assumes "pres_NFA_state_int j \<in> \<Q> (pres_DFA_eq_ineq True n ks l)"
and "list_all (is_alph n) bss"
and "DLTS_reach (\<delta> (pres_DFA_eq_ineq True n ks l)) (pres_NFA_state_int j) bss = Some (pres_NFA_state_int j')"
shows "0 \<le> j' \<longleftrightarrow> eval_dioph ks (nats_of_boolss n bss) \<le> j"
using assms
proof (induct bss arbitrary: j j')
case Nil
thus ?case
by (simp add: eval_dioph_replicate_0)
next
case (Cons bs bss' j)
from Cons(3) have
bs_in: "length bs = n" and
bss'_in : "list_all (is_alph n) bss'"
by (simp_all add: is_alph_def)
note ind_hyp = Cons(1) [OF _ bss'_in]
note j_in_Q = Cons(2)
note reach_j_j' = Cons(4)
let ?j' = "(j - eval_dioph ks (map nat_of_bool bs)) div 2"
have \<delta>_j_bs_eq:
"\<delta> (pres_DFA_eq_ineq True n ks l) (pres_NFA_state_int j, bs) =
Some (pres_NFA_state_int ?j')"
using j_in_Q bs_in
unfolding \<delta>_pres_DFA_eq_ineq
unfolding pres_DFA_eq_ineq_def
by simp
have j'_in_Q: "pres_DFA_eq_ineq_trans_fun True ks (pres_NFA_state_int j) bs \<in> \<Q> (pres_DFA_eq_ineq True n ks l)"
using bs_in j_in_Q pres_DFA_is_node___pres_DFA_eq_ineq_trans_fun [where i = True]
unfolding pres_DFA_eq_ineq_def
by (simp del: pres_DFA_eq_ineq_trans_fun.simps)
have j'_eq: "pres_DFA_eq_ineq_trans_fun True ks (pres_NFA_state_int j) bs =
pres_NFA_state_int ?j'"
by simp
with ind_hyp [OF j'_in_Q [unfolded j'_eq]] reach_j_j'
show ?case
by (simp add: \<delta>_j_bs_eq
eval_dioph_ineq_div_mod [where xs = "nats_of_boolss n (bs#bss')"]
nats_of_boolss_div2 bs_in bss'_in nats_of_boolss_mod2)
qed
lemma pres_DFA_ineq_reach_exists :
"\<lbrakk>list_all (is_alph n) bss; dioph_is_node ks l j\<rbrakk> \<Longrightarrow>
\<exists>j'. DLTS_reach (\<delta> (pres_DFA_eq_ineq True n ks l)) (pres_NFA_state_int j) bss =
Some (pres_NFA_state_int j') \<and> dioph_is_node ks l j'"
proof (induct bss arbitrary: j)
case Nil thus ?case by simp
next
case (Cons bs bss')
let ?j' = "(j - eval_dioph ks (map nat_of_bool bs)) div 2"
have "pres_DFA_eq_ineq_trans_fun True ks (pres_NFA_state_int j) bs \<in> \<Q> (pres_DFA_eq_ineq False n ks l)"
using Cons pres_DFA_is_node___pres_DFA_eq_ineq_trans_fun [where i = True]
unfolding pres_DFA_eq_ineq_def
by (simp del: pres_DFA_eq_ineq_trans_fun.simps)
hence j'_is_node: "dioph_is_node ks l ?j'"
unfolding pres_DFA_eq_ineq_def
by simp
from Cons j'_is_node
show ?case
by (simp add: is_alph_def \<delta>_pres_DFA_eq_ineq)
qed
lemma pres_DFA_ineq_correct :
assumes bss_OK: "list_all (is_alph n) bss"
shows "NFA_accept (pres_DFA_eq_ineq True n ks l) bss =
(eval_dioph ks (nats_of_boolss n bss) \<le> l)"
proof -
have \<i>_eval: "\<i> (pres_DFA_eq_ineq True n ks l) = pres_NFA_state_int l"
unfolding pres_DFA_eq_ineq_def
by (simp add: \<i>_def)
have \<F>_eval: "\<F> (pres_DFA_eq_ineq True n ks l) = {pres_NFA_state_int m |m. dioph_is_node ks l m \<and> 0 \<le> m}"
unfolding pres_DFA_eq_ineq_def
by simp
obtain j' where reach_eq:
"DLTS_reach (\<delta> (pres_DFA_eq_ineq True n ks l)) (pres_NFA_state_int l) bss =
Some (pres_NFA_state_int j')"
and is_node_j': "dioph_is_node ks l j'"
using pres_DFA_ineq_reach_exists [OF bss_OK, of ks l l]
by (simp add: dioph_is_node_def, blast)
have l_in_Q: "pres_NFA_state_int l \<in> \<Q> (pres_DFA_eq_ineq True n ks l)"
unfolding pres_DFA_eq_ineq_def
by (simp add: dioph_is_node_def)
from pres_DFA_eq_ineq_reach_ineq [OF l_in_Q bss_OK reach_eq, symmetric]
show ?thesis
by (simp add: pres_DFA_eq_ineq.DFA_accept_alt_def \<i>_eval \<F>_eval
reach_eq is_node_j')
qed
subsubsection \<open> Efficiency \<close>
subsubsection \<open> Implementation \<close>
text \<open> For using these automata constructions let's replace
the new datatype for states with natural numbers and consider only
reachable states. \<close>
fun pres_NFA_state_to_nat where
"pres_NFA_state_to_nat pres_NFA_state_error = 0"
| "pres_NFA_state_to_nat (pres_NFA_state_int m) =
int_encode m + 1"
lemma pres_NFA_state_nat_eq_0 [simp] :
"(pres_NFA_state_to_nat q = 0) \<longleftrightarrow> q = pres_NFA_state_error"
by (cases q, auto)
lemma pres_NFA_state_nat_neq_0 [simp] :
"(pres_NFA_state_to_nat q = Suc m) \<longleftrightarrow> q = pres_NFA_state_int (int_decode m)"
by (cases q, auto)
lemma inj_pres_NFA_state_to_nat:
"inj_on pres_NFA_state_to_nat S"
unfolding inj_on_def Ball_def
proof (intro allI impI)
fix q1 q2
assume f_q1: "pres_NFA_state_to_nat q1 = pres_NFA_state_to_nat q2"
thus "q1 = q2"
by (cases "pres_NFA_state_to_nat q2", simp_all)
qed
definition efficient_pres_DFA_eq_ineq where
"efficient_pres_DFA_eq_ineq i n ks l =
NFA_rename_states (NFA_remove_unreachable_states (pres_DFA_eq_ineq i n ks l)) pres_NFA_state_to_nat"
lemma efficient_pres_DFA_eq_ineq___is_well_formed :
"DFA (efficient_pres_DFA_eq_ineq i n ks l)"
unfolding efficient_pres_DFA_eq_ineq_def
apply (intro DFA___inj_rename DFA___NFA_remove_unreachable_states)
apply (simp_all add: pres_DFA_eq_ineq___is_well_formed inj_pres_NFA_state_to_nat)
done
lemma pres_DFA_eq_ineq___isomorphic_wf :
"NFA_isomorphic_wf (NFA_remove_unreachable_states (pres_DFA_eq_ineq i n ks l))
(efficient_pres_DFA_eq_ineq i n ks l)"
unfolding efficient_pres_DFA_eq_ineq_def
by (intro NFA_isomorphic_wf___NFA_rename_states inj_pres_NFA_state_to_nat
NFA_remove_unreachable_states___is_well_formed pres_DFA_eq_ineq.NFA_axioms)
lemma efficient_pres_DFA_eq_ineq___NFA_accept [simp] :
"NFA_accept (efficient_pres_DFA_eq_ineq i n ks l) bss =
NFA_accept (pres_DFA_eq_ineq i n ks l) bss"
proof -
have equiv_f: "\<And>\<A>. NFA_is_equivalence_rename_fun \<A> pres_NFA_state_to_nat"
by (rule NFA_is_equivalence_rename_funI___inj_used, fact inj_pres_NFA_state_to_nat)
have wf_1 : "DFA (NFA_remove_unreachable_states (pres_DFA_eq_ineq i n ks l))"
by (intro DFA___NFA_remove_unreachable_states, fact pres_DFA_eq_ineq___is_well_formed)
hence wf_2: "NFA (NFA_remove_unreachable_states (pres_DFA_eq_ineq i n ks l))"
by (simp add: DFA_alt_def)
note NFA.NFA_rename_states___accept [OF wf_2 equiv_f]
thus ?thesis
unfolding efficient_pres_DFA_eq_ineq_def
by simp
qed
subsection \<open> Existential Quantification \<close>
type_synonym pres_NFA = "(nat, bool list) NFA_rec"
definition pres_DFA_labels_tl ::
"pres_NFA \<Rightarrow> pres_NFA" where
"pres_DFA_labels_tl \<A> = SemiAutomaton_rename_labels \<A> tl"
lemma pres_DFA_labels_tl___well_formed:
"NFA \<A> \<Longrightarrow> NFA (pres_DFA_labels_tl \<A>)"
by (simp add: pres_DFA_labels_tl_def
NFA.NFA_rename_labels___is_well_formed)
lemma pres_DFA_labels_tl___NFA_accept :
assumes wf_A: "NFA \<A>"
and \<Sigma>_A: "\<And>bs. bs \<in> \<Sigma> \<A> \<Longrightarrow> bs \<noteq> []"
shows "NFA_accept (pres_DFA_labels_tl \<A>) bss \<longleftrightarrow>
(\<exists>bs. length bs = length bss \<and> NFA_accept \<A> (insertll 0 bs bss))"
apply (simp add: pres_DFA_labels_tl_def NFA_accept___NFA_rename_labels_iff)
proof
assume "\<exists>bss'. bss = map tl bss' \<and> NFA_accept \<A> bss'"
then obtain bss' where
bss_eq: "bss = map tl bss'"
and bss'_acc: "NFA_accept \<A> bss'" by blast
have len_bs : "length (map hd bss') = length bss"
unfolding bss_eq by simp
from bss'_acc have "bss' \<in> lists (\<Sigma> \<A>)"
by (simp add: NFA.NFA_accept_wf_def[OF wf_A])
hence "insertll 0 (map hd bss') (map tl bss') = bss'"
proof (induct bss')
case Nil thus ?case by simp
next
case (Cons bs bss)
from Cons(1) have "bs \<noteq> []" using \<Sigma>_A by simp
then obtain bs_hd bs_tl where bs_eq: "bs = bs_hd # bs_tl"
by (cases bs, simp)
with Cons(3) show ?case
by (simp add: insertl_0_eq)
qed
hence "NFA_accept \<A> (insertll 0 (map hd bss') bss)"
unfolding bss_eq
using bss'_acc
by simp
with len_bs show "\<exists>bs. length bs = length bss \<and> NFA_accept \<A> (insertll 0 bs bss)" by blast
next
assume "\<exists>bs. length bs = length bss \<and> NFA_accept \<A> (insertll 0 bs bss)"
then obtain bs where
bss_acc: "NFA_accept \<A> (insertll 0 bs bss)"
and len_bs: "length bs = length bss" by blast
from len_bs
have "map tl (insertll 0 bs bss) = bss"
proof (induct bss arbitrary: bs)
case Nil thus ?case by simp
next
case (Cons bss_hd bss_tl bs)
thus ?case
by (cases bs, simp_all add: insertl_0_eq)
qed
with bss_acc show "\<exists>bss'. bss = map tl bss' \<and> NFA_accept \<A> bss'"
apply (rule_tac exI [where x = "insertll 0 bs bss"])
apply simp
done
qed
definition pres_DFA_exists ::
"nat \<Rightarrow> pres_NFA \<Rightarrow> pres_NFA" where
"pres_DFA_exists n \<A> = NFA_right_quotient_lists (pres_DFA_labels_tl \<A>)
{replicate n False}"
lemma pres_DFA_exists___well_formed:
"NFA \<A> \<Longrightarrow> NFA (pres_DFA_exists n \<A>)"
unfolding pres_DFA_exists_def
by (intro NFA_right_quotient___is_well_formed pres_DFA_labels_tl___well_formed, assumption)
lemma pres_DFA_exists___NFA_accept :
assumes wf_A: "NFA \<A>"
and \<Sigma>_A: "\<And>bs. bs \<in> \<Sigma> \<A> \<Longrightarrow> bs \<noteq> []"
shows "NFA_accept (pres_DFA_exists n \<A>) bss \<longleftrightarrow>
(\<exists>bs m. length bs = length bss + m \<and> NFA_accept \<A> (insertll 0 bs (bss @ zeros m n)))"
proof -
have lists_repl: "lists {replicate n False} = {zeros m n | m. True}" (is "?s1 = ?s2")
proof (intro set_eqI iffI)
fix bss
assume "bss \<in> ?s2"
thus "bss \<in> ?s1" by (auto simp add: zeros_def list_all_iff)
next
fix bss
assume "bss \<in> ?s1"
hence "\<And>bs. bs \<in> set bss \<Longrightarrow> bs = replicate n False" by (auto simp add: list_all_iff)
hence "bss = replicate (length bss) (replicate n False)"
by (induct bss, auto)
thus "bss \<in> ?s2" by (simp add: zeros_def, blast)
qed
note wf_ex = pres_DFA_labels_tl___well_formed [OF wf_A]
note NFA_accept = NFA.NFA_right_quotient___accepts [OF wf_ex, where L = "lists {replicate n False}"]
with lists_repl show ?thesis
by (simp del: ex_simps
add: pres_DFA_exists_def pres_DFA_labels_tl___NFA_accept [OF wf_A \<Sigma>_A]
ex_simps[symmetric] zeros_len)
qed
lemma nats_of_boolss_append_zeros :
assumes bss_in: "list_all (is_alph n) bss"
shows "nats_of_boolss n (bss @ zeros m n) = nats_of_boolss n bss"
proof -
have map_eq: "\<And>nl::nat list. map (\<lambda>(x, y). x + (2::nat) ^ length bss * y) (zip nl (replicate (length nl) 0)) = nl"
proof -
fix nl
show "map (\<lambda>(x::nat, y). x + 2 ^ length bss * y) (zip nl (replicate (length nl) 0)) = nl"
proof (induct nl)
case Nil thus ?case by simp
next
case (Cons x nl)
thus ?case by (simp)
qed
qed
from map_eq [of "nats_of_boolss n bss"]
nats_of_boolss_append [of n bss "zeros m n"]
show "nats_of_boolss n (bss @ zeros m n) = nats_of_boolss n bss"
by (simp add: bss_in zeros_is_alpha nats_of_boolss_zeros nats_of_boolss_length)
qed
lemma pres_DFA_exists___NFA_accept___nats :
assumes wf_A: "NFA \<A>"
and \<Sigma>_A: "\<Sigma> \<A> = {bs. length bs = Suc n}"
and acc_A: "\<And>bss. list_all (is_alph (Suc n)) bss \<Longrightarrow> NFA_accept \<A> bss \<longleftrightarrow> P (nats_of_boolss (Suc n) bss)"
and bss_in: "list_all (is_alph n) bss"
shows "NFA_accept (pres_DFA_exists n \<A>) bss =
(\<exists>x. P (x # nats_of_boolss n bss))"
proof -
have \<Sigma>_A': "\<And>bs. bs \<in> \<Sigma> \<A> \<Longrightarrow> bs \<noteq> []"
proof -
fix bs
assume "bs \<in> \<Sigma> \<A>"
with \<Sigma>_A have "length bs = Suc n" by simp
thus "bs \<noteq> []" by auto
qed
have "\<And>bs m. length bs = length bss + m \<Longrightarrow>
NFA_accept \<A> (insertll 0 bs (bss @ zeros m n)) =
P (nats_of_boolss (Suc n) (insertll 0 bs (bss @ zeros m n)))"
proof -
fix bs :: "bool list"
fix m
assume len_bs: "length bs = length bss + m"
with insertll_len2 [of n "bss @ (zeros m n)" bs 0]
acc_A
show "NFA_accept \<A> (insertll 0 bs (bss @ zeros m n)) =
P (nats_of_boolss (Suc n) (insertll 0 bs (bss @ zeros m n)))"
by (simp add: bss_in zeros_is_alpha zeros_len)
qed
hence step0:
"(\<exists>bs m. length bs = length bss + m \<and> NFA_accept \<A> (insertll 0 bs (bss @ zeros m n))) =
(\<exists>bs m. length bs = length bss + m \<and> P (nats_of_boolss (Suc n) (insertll 0 bs (bss @ zeros m n))))"
by auto
have "\<And>bs m. length bs = length bss + m \<Longrightarrow>
nats_of_boolss (Suc n) (insertll 0 bs (bss @ zeros m n)) =
nat_of_bools bs # nats_of_boolss n bss"
proof -
fix bs :: "bool list"
fix m
assume "length bs = length bss + m"
hence len_bs: "length bs = length (bss @ zeros m n)"
by (simp add: zeros_len)
have bss'_in: "list_all (is_alph n) (bss @ zeros m n)"
by (simp add: bss_in zeros_is_alpha)
from nats_of_boolss_insertll [of n "bss @ (zeros m n)" bs 0, OF bss'_in len_bs]
nats_of_boolss_append_zeros [of n bss m, OF bss_in]
show "nats_of_boolss (Suc n) (insertll 0 bs (bss @ zeros m n)) =
nat_of_bools bs # nats_of_boolss n bss"
by (simp add: insertl_0_eq)
qed
hence step1:
"(\<exists>bs m. length bs = length bss + m \<and> P (nats_of_boolss (Suc n) (insertll 0 bs (bss @ zeros m n)))) =
(\<exists>bs m. length bs = length bss + m \<and> P (nat_of_bools bs # nats_of_boolss n bss))"
by (metis (no_types))
have step2: "(\<exists>bs m. length bs = length bss + m \<and> P (nat_of_bools bs # nats_of_boolss n bss)) =
(\<exists>x. P (x # nats_of_boolss n bss))"
apply (rule iffI)
apply (erule exE conjE)+
apply (erule exI)
apply (erule exE)
apply (rule_tac x="bools_of_nat (length bss) x" in exI)
apply (rule_tac x="length (bools_of_nat (length bss) x) - length bss" in exI)
apply (simp add: bools_of_nat_inverse bools_of_nat_length)
done
from step0 step1 step2 show ?thesis
by (simp add: pres_DFA_exists___NFA_accept [OF wf_A \<Sigma>_A']
nats_of_boolss_insertll)
qed
definition pres_DFA_exists_min where
"pres_DFA_exists_min n \<A> = NFA_right_quotient_lists (
NFA_minimise (pres_DFA_labels_tl \<A>)) {replicate n False}"
find_theorems name: "NFA_right_quotient" name: "well_formed"
lemma pres_DFA_exists_min___well_formed :
assumes wf_A: "NFA \<A>"
shows "DFA (pres_DFA_exists_min n \<A>)"
unfolding pres_DFA_exists_min_def pres_DFA_labels_tl_def
by (metis NFA_right_quotient___is_well_formed_DFA NFA.NFA_rename_labels___is_well_formed
NFA_minimise_spec(3) assms DFA_is_minimal_gen_def)
lemma pres_DFA_exists_min___well_formed_DFA :
"DFA \<A> \<Longrightarrow> DFA (pres_DFA_exists_min n \<A>)"
using pres_DFA_exists_min___well_formed
by (metis DFA_alt_def)
lemma pres_DFA_exists_min___NFA_accept :
assumes wf_A: "DFA \<A>"
shows "NFA_accept (pres_DFA_exists_min n \<A>) bss \<longleftrightarrow>
NFA_accept (pres_DFA_exists n \<A>) bss"
proof -
let ?A1 = "pres_DFA_labels_tl \<A>"
let ?A2 = "NFA_minimise ?A1"
from wf_A have NFA_A: "NFA \<A>" by (simp add: DFA_alt_def)
have NFA_A1: "NFA ?A1"
unfolding pres_DFA_labels_tl_def
by (simp add: NFA.NFA_rename_labels___is_well_formed [OF NFA_A])
from NFA_minimise_spec(3)[OF NFA_A1]
have NFA_A2: "NFA ?A2" unfolding DFA_is_minimal_def DFA_alt_def by simp
from NFA_minimise_spec(1)[OF NFA_A1]
have NFA_accept_A2: "\<And>bss. NFA_accept ?A2 bss = NFA_accept ?A1 bss"
by (auto simp add: \<L>_def)
show ?thesis
unfolding pres_DFA_exists_min_def pres_DFA_exists_def
by (simp add: NFA.NFA_right_quotient___accepts NFA_A1 NFA_A2 NFA_accept_A2)
qed
lemma pres_DFA_exists_min___NFA_accept___nats :
assumes wf_A: "DFA \<A>"
and \<Sigma>_A: "\<Sigma> \<A> = {bs. length bs = Suc n}"
and acc_A: "\<And>bss. list_all (is_alph (Suc n)) bss \<Longrightarrow> NFA_accept \<A> bss \<longleftrightarrow> P (nats_of_boolss (Suc n) bss)"
and bss_in: "list_all (is_alph n) bss"
shows "NFA_accept (pres_DFA_exists_min n \<A>) bss =
(\<exists>x. P (x # nats_of_boolss n bss))"
proof -
have wf_A' : "NFA \<A>"
using wf_A unfolding DFA_alt_def by simp
show ?thesis by (metis pres_DFA_exists___NFA_accept___nats [OF wf_A' \<Sigma>_A acc_A bss_in]
pres_DFA_exists_min___NFA_accept [OF wf_A])
qed
lemma \<Sigma>_pres_DFA_exists_min :
"NFA \<A> \<Longrightarrow> \<Sigma> (pres_DFA_exists_min n \<A>) = tl ` \<Sigma> \<A>"
by (simp add: pres_DFA_exists_min_def pres_DFA_labels_tl_def NFA_minimise_spec(2)
NFA.NFA_rename_labels___is_well_formed)
subsection \<open> Universal Quantification \<close>
definition pres_DFA_forall_min where
"pres_DFA_forall_min n \<A> = DFA_complement (pres_DFA_exists_min n (DFA_complement \<A>))"
lemma pres_DFA_forall_min___well_formed_DFA :
"DFA \<A> \<Longrightarrow> DFA (pres_DFA_forall_min n \<A>)"
unfolding pres_DFA_forall_min_def
by (intro DFA_complement_of_DFA_is_DFA pres_DFA_exists_min___well_formed_DFA,
assumption)
lemma \<Sigma>_image_tl : "tl ` {bs::'a list. length bs = Suc n} = {bs. length bs = n}"
proof (intro set_eqI iffI)
fix bs :: "'a list"
assume "bs \<in> tl ` {bs. length bs = Suc n}"
thus "bs \<in> {bs. length bs = n}" by auto
next
fix bs :: "'a list"
assume "bs \<in> {bs. length bs = n}"
thus "bs \<in> tl ` {bs. length bs = Suc n}"
apply (simp add: image_iff)
apply (rule exI [where x = "e # bs"])
apply simp
done
qed
lemma pres_DFA_forall_min___NFA_accept___nats :
fixes \<A> :: pres_NFA
assumes wf_A: "DFA \<A>"
and \<Sigma>_A: "\<Sigma> \<A> = {bs. length bs = Suc n}"
and acc_A: "\<And>bss. list_all (is_alph (Suc n)) bss \<Longrightarrow> NFA_accept \<A> bss \<longleftrightarrow> P (nats_of_boolss (Suc n) bss)"
and bss_in: "list_all (is_alph n) bss"
shows "NFA_accept (pres_DFA_forall_min n \<A>) bss =
(\<forall>x. P (x # nats_of_boolss n bss))"
proof -
let ?cA = "DFA_complement \<A>"
note wf_ca = DFA_complement_of_DFA_is_DFA [OF wf_A]
hence wf'_ca: "NFA ?cA" unfolding DFA_alt_def by simp
have acc_cA: "\<And>bss. list_all (is_alph (Suc n)) bss \<Longrightarrow> NFA_accept ?cA bss \<longleftrightarrow> \<not>(P (nats_of_boolss (Suc n) bss))"
using DFA_complement_word [OF wf_A] \<Sigma>_A
by (simp add: list_all_iff in_lists_conv_set acc_A is_alph_def)
have acc : "NFA_accept (pres_DFA_forall_min n \<A>) bss \<longleftrightarrow>
\<not> (NFA_accept (pres_DFA_exists_min n ?cA) bss)"
unfolding pres_DFA_forall_min_def
apply (rule DFA_complement_word [OF pres_DFA_exists_min___well_formed_DFA [OF wf_ca]])
apply (insert bss_in)
apply (simp add: \<Sigma>_pres_DFA_exists_min[OF wf'_ca] \<Sigma>_A \<Sigma>_image_tl)
apply (simp add: list_all_iff is_alph_def in_lists_conv_set)
done
with pres_DFA_exists_min___NFA_accept___nats [OF wf_ca _ acc_cA bss_in] \<Sigma>_A
show ?thesis by simp
qed
lemma \<Sigma>_pres_DFA_forall_min :
"NFA \<A> \<Longrightarrow> \<Sigma> (pres_DFA_forall_min n \<A>) = tl ` \<Sigma> \<A>"
by (simp add: pres_DFA_forall_min_def \<Sigma>_pres_DFA_exists_min DFA_complement___is_well_formed)
subsection \<open> Translation \<close>
fun DFA_of_pf :: "nat \<Rightarrow> pf \<Rightarrow> pres_NFA" where
Eq: "DFA_of_pf n (Eq ks l) = efficient_pres_DFA_eq_ineq False n ks l"
| Le: "DFA_of_pf n (Le ks l) = efficient_pres_DFA_eq_ineq True n ks l"
| And: "DFA_of_pf n (And p q) = NFA_bool_comb (\<and>) (DFA_of_pf n p) (DFA_of_pf n q)"
| Or: "DFA_of_pf n (Or p q) = NFA_bool_comb (\<or>) (DFA_of_pf n p) (DFA_of_pf n q)"
| Imp: "DFA_of_pf n (Imp p q) = NFA_bool_comb (\<longrightarrow>) (DFA_of_pf n p) (DFA_of_pf n q)"
| Exists: "DFA_of_pf n (Exist p) = pres_DFA_exists_min n (DFA_of_pf (Suc n) p)"
| Forall: "DFA_of_pf n (Forall p) = pres_DFA_forall_min n (DFA_of_pf (Suc n) p)"
| Neg: "DFA_of_pf n (Neg p) = DFA_complement (DFA_of_pf n p)"
lemmas DFA_of_pf_induct =
DFA_of_pf.induct [case_names Eq Le And Or Imp Exist Forall Neg]
lemma DFA_of_pf___correct:
"DFA (DFA_of_pf n p) \<and>
\<Sigma> (DFA_of_pf n p) = {bs. length bs = n} \<and>
(\<forall>bss. list_all (is_alph n) bss \<longrightarrow>
NFA.NFA_accept (DFA_of_pf n p) bss = eval_pf p (nats_of_boolss n bss))"
(is "?P1 n p \<and> ?P2 n p \<and> ?P3 n p")
proof (induct n p rule: DFA_of_pf_induct)
case (Eq n ks l)
show ?case
apply (simp add: efficient_pres_DFA_eq_ineq___is_well_formed pres_DFA_eq_correct)
apply (simp add: efficient_pres_DFA_eq_ineq_def pres_DFA_eq_ineq_def)
done
next
case (Le n ks l)
show ?case
apply (simp add: efficient_pres_DFA_eq_ineq___is_well_formed pres_DFA_ineq_correct)
apply (simp add: efficient_pres_DFA_eq_ineq_def pres_DFA_eq_ineq_def)
done
next
case (And n p q)
thus ?case
by (simp add: NFA_bool_comb_DFA___NFA_accept NFA_bool_comb_DFA___is_well_formed
in_lists_conv_set list_all_iff is_alph_def)
next
case (Or n p q)
thus ?case
by (simp add: NFA_bool_comb_DFA___NFA_accept NFA_bool_comb_DFA___is_well_formed
in_lists_conv_set list_all_iff is_alph_def)
next
case (Imp n p q)
thus ?case
by (simp add: NFA_bool_comb_DFA___NFA_accept NFA_bool_comb_DFA___is_well_formed
in_lists_conv_set list_all_iff is_alph_def)
next
case (Neg n p)
thus ?case
by (simp add: DFA_complement_of_DFA_is_DFA DFA_complement_word
in_lists_conv_set list_all_iff is_alph_def)
next
case (Exist n p)
with pres_DFA_exists_min___NFA_accept___nats [where \<A> = "DFA_of_pf (Suc n) p" and n = n and P = "eval_pf p"]
show ?case
by (simp add: \<Sigma>_pres_DFA_exists_min \<Sigma>_image_tl pres_DFA_exists_min___well_formed_DFA)
next
case (Forall n p)
with pres_DFA_forall_min___NFA_accept___nats [where \<A> = "DFA_of_pf (Suc n) p" and n = n and P = "eval_pf p"]
show ?case
by (simp add: \<Sigma>_pres_DFA_forall_min \<Sigma>_image_tl pres_DFA_forall_min___well_formed_DFA)
qed
subsection \<open> Code Generation \<close>
text \<open> The automata used for presburger arithmetic have label sets that consist of all
bitvectors of a certain length. The following locale is used to cache these sets. \<close>
locale presburger_label_set_cache = set a_\<alpha> a_invar
for a_\<alpha> :: "'al_set \<Rightarrow> ('a list) set" and a_invar +
fixes c_\<alpha> :: "'cache \<Rightarrow> nat \<Rightarrow> 'cache \<times> 'al_set"
fixes c_invar :: "'cache \<Rightarrow> bool"
fixes init_cache :: "unit \<Rightarrow> 'cache"
assumes init_cache_OK :
"c_invar (init_cache ())"
assumes cache_correct :
"c_invar c \<Longrightarrow> c_invar (fst (c_\<alpha> c n))"
"c_invar c \<Longrightarrow> a_invar (snd (c_\<alpha> c n))"
"c_invar c \<Longrightarrow> a_\<alpha> (snd (c_\<alpha> c n)) = {bs. length bs = n}"
locale presburger_locale =
nfa: StdNFA nfa_ops +
presburger_label_set_cache a_\<alpha> a_invar c_\<alpha> c_invar c_init +
dfa_construct_no_enc_fun "nfa_op_\<alpha> nfa_ops" "nfa_op_invar nfa_ops" a_\<alpha> a_invar dfa_construct +
labels_gen: nfa_rename_labels_gen "nfa_op_\<alpha> nfa_ops" "nfa_op_invar nfa_ops"
"nfa_op_\<alpha> nfa_ops" "nfa_op_invar nfa_ops" a_\<alpha> a_invar rename_labels_gen
for a_\<alpha> :: "'bl_set \<Rightarrow> (bool list) set" and a_invar c_init and
c_\<alpha> :: "'cache \<Rightarrow> nat \<Rightarrow> ('cache \<times> 'bl_set)" and c_invar and
nfa_ops :: "('q::{automaton_states}, bool list, 'nfa) nfa_ops" and
dfa_construct :: "(pres_NFA_state,nat,bool list,'bl_set,'nfa) nfa_construct_fun" and
rename_labels_gen
begin
definition pres_DFA_eq_ineq_impl where
"pres_DFA_eq_ineq_impl A ineq n ks l =
dfa_construct pres_NFA_state_to_nat (pres_NFA_state_int l) A
(if ineq then
(\<lambda>q. case q of pres_NFA_state_error \<Rightarrow> False
| pres_NFA_state_int m \<Rightarrow> (0 \<le> m))
else
(\<lambda>q. case q of pres_NFA_state_error \<Rightarrow> False
| pres_NFA_state_int m \<Rightarrow> (m = 0)))
(pres_DFA_eq_ineq_trans_fun ineq ks)"
lemma pres_DFA_eq_ineq_impl_correct :
assumes A_OK: "a_invar A" "a_\<alpha> A = {bs. length bs = n}"
shows "nfa.invar (pres_DFA_eq_ineq_impl A ineq n ks l)"
"NFA_isomorphic_wf (nfa.\<alpha> (pres_DFA_eq_ineq_impl A ineq n ks l))
(efficient_pres_DFA_eq_ineq ineq n ks l)"
proof -
have "nfa.invar (pres_DFA_eq_ineq_impl A ineq n ks l) \<and>
NFA_isomorphic_wf (nfa.\<alpha> (pres_DFA_eq_ineq_impl A ineq n ks l))
(NFA_remove_unreachable_states (pres_DFA_eq_ineq ineq n ks l))"
unfolding pres_DFA_eq_ineq_impl_def
apply (rule dfa_construct_no_enc_fun_correct)
apply (rule pres_DFA_eq_ineq___is_well_formed)
apply (auto simp add: pres_DFA_eq_ineq_def A_OK inj_pres_NFA_state_to_nat
split: pres_NFA_state.split)
done
thus "nfa.invar (pres_DFA_eq_ineq_impl A ineq n ks l)"
"NFA_isomorphic_wf (nfa.\<alpha> (pres_DFA_eq_ineq_impl A ineq n ks l))
(efficient_pres_DFA_eq_ineq ineq n ks l)"
by (simp_all add: NFA_isomorphic_wf_trans[OF _ pres_DFA_eq_ineq___isomorphic_wf])
qed
definition pres_DFA_exists_min_impl where
"pres_DFA_exists_min_impl A AA =
nfa.right_quotient_lists (list_all (\<lambda>b. \<not> b)) (nfa.minimise_Hopcroft_NFA (rename_labels_gen AA A tl))"
lemma im_tl_eq: "tl ` {bl. length bl = Suc n} = {bl. length bl = n}"
apply (auto simp add: image_iff length_Suc_conv)[]
apply (simp add: ex_simps[symmetric] del: ex_simps)
done
lemma pres_DFA_exists_min_impl_correct_invar :
assumes "nfa.invar AA"
"a_invar A" "\<Sigma> (nfa.\<alpha> AA) = {bl. length bl = Suc n}"
"a_\<alpha> A = {bl. length bl = n}"
shows "nfa.invar (pres_DFA_exists_min_impl A AA)"
unfolding pres_DFA_exists_min_impl_def pres_DFA_exists_min_def pres_DFA_labels_tl_def
apply (insert assms)
apply (intro nfa.correct_isomorphic conjI labels_gen.rename_labels_gen_correct___isomorphic)+
apply (simp_all add: im_tl_eq)
done
lemma pres_DFA_exists_min_impl_correct_\<alpha> :
assumes "nfa.invar AA"
"NFA_isomorphic_wf (nfa.\<alpha> AA) \<A>"
"a_invar A" "\<Sigma> (nfa.\<alpha> AA) = {bl. length bl = Suc n}"
"a_\<alpha> A = {bl. length bl = n}"
shows "NFA_isomorphic_wf (nfa.\<alpha> (pres_DFA_exists_min_impl A AA)) (pres_DFA_exists_min n \<A>)"
unfolding pres_DFA_exists_min_impl_def pres_DFA_exists_min_def pres_DFA_labels_tl_def
apply (insert assms)
apply (intro nfa.correct_isomorphic conjI labels_gen.rename_labels_gen_correct___isomorphic)+
apply (simp_all add: im_tl_eq)
proof -
assume iso: "NFA_isomorphic_wf (nfa_op_\<alpha> nfa_ops AA) \<A>"
and \<Sigma>_eq: "\<Sigma> (nfa_op_\<alpha> nfa_ops AA) = {bl. length bl = Suc n}"
hence \<Sigma>_eq': "\<Sigma> \<A> = {bl. length bl = Suc n}"
by (simp add: NFA_isomorphic_wf_\<Sigma>)
from iso have "NFA \<A>" unfolding NFA_isomorphic_wf_alt_def by simp
hence \<Sigma>_min: "\<Sigma> (NFA_minimise (SemiAutomaton_rename_labels \<A> tl)) = {bl. length bl = n}"
by (simp add: NFA_minimise_spec(2) NFA.NFA_rename_labels___is_well_formed \<Sigma>_eq' im_tl_eq)
have "{replicate n False} \<inter> {bl. length bl = n} =
{a. list_all Not a} \<inter> {bl. length bl = n}"
apply (intro set_eqI iffI)
apply (induct n, simp_all)
apply (induct n, auto simp add: length_Suc_conv)
done
with \<Sigma>_min
show "{replicate n False} \<inter> \<Sigma> (NFA_minimise (SemiAutomaton_rename_labels \<A> tl)) =
{a. list_all Not a} \<inter> \<Sigma> (NFA_minimise (SemiAutomaton_rename_labels \<A> tl))"
by metis
qed
lemmas pres_DFA_exists_min_impl_correct =
pres_DFA_exists_min_impl_correct_invar pres_DFA_exists_min_impl_correct_\<alpha>
definition pres_DFA_forall_min_impl where
"pres_DFA_forall_min_impl A AA =
nfa.complement (pres_DFA_exists_min_impl A (nfa.complement AA))"
lemma pres_DFA_forall_min_impl_correct_invar :
assumes "nfa.invar AA"
"a_invar A" "\<Sigma> (nfa.\<alpha> AA) = {bl. length bl = Suc n}"
"a_\<alpha> A = {bl. length bl = n}"
shows "nfa.invar (pres_DFA_forall_min_impl A AA)"
unfolding pres_DFA_forall_min_impl_def pres_DFA_forall_min_def pres_DFA_labels_tl_def
apply (insert assms)
apply (intro nfa.correct_isomorphic conjI
pres_DFA_exists_min_impl_correct | assumption)+
apply (simp_all add: nfa.correct)
done
lemma pres_DFA_forall_min_impl_correct_\<alpha> :
assumes "nfa.invar AA"
"NFA_isomorphic_wf (nfa.\<alpha> AA) \<A>"
"a_invar A" "\<Sigma> (nfa.\<alpha> AA) = {bl. length bl = Suc n}"
"a_\<alpha> A = {bl. length bl = n}"
shows "NFA_isomorphic_wf (nfa.\<alpha> (pres_DFA_forall_min_impl A AA)) (pres_DFA_forall_min n \<A>)"
unfolding pres_DFA_forall_min_impl_def pres_DFA_forall_min_def pres_DFA_labels_tl_def
apply (insert assms)
apply (intro nfa.correct_isomorphic conjI
pres_DFA_exists_min_impl_correct | assumption)+
apply (simp_all add: nfa.correct)
done
lemmas pres_DFA_forall_min_impl_correct =
pres_DFA_forall_min_impl_correct_invar pres_DFA_forall_min_impl_correct_\<alpha>
fun nfa_of_pf :: "nat \<Rightarrow> pf \<Rightarrow> 'cache \<Rightarrow> 'nfa \<times> 'cache" where
Eq: "nfa_of_pf n (Eq ks l) c =
(let (c', A) = c_\<alpha> c n in
(pres_DFA_eq_ineq_impl A False n ks l, c'))"
| Le: "nfa_of_pf n (Le ks l) c =
(let (c', A) = c_\<alpha> c n in
(pres_DFA_eq_ineq_impl A True n ks l, c'))"
| And: "nfa_of_pf n (And p q) c =
(let (P, c') = nfa_of_pf n p c in
let (Q, c'') = nfa_of_pf n q c' in
(nfa.bool_comb (\<and>) P Q, c''))"
| Or: "nfa_of_pf n (Or p q) c =
(let (P, c') = nfa_of_pf n p c in
let (Q, c'') = nfa_of_pf n q c' in
(nfa.bool_comb (\<or>) P Q, c''))"
| Imp: "nfa_of_pf n (Imp p q) c =
(let (P, c') = nfa_of_pf n p c in
let (Q, c'') = nfa_of_pf n q c' in
(nfa.bool_comb (\<longrightarrow>) P Q, c''))"
| Exists: "nfa_of_pf n (Exist p) c =
(let (c', A) = c_\<alpha> c n in
let (P, c'') = nfa_of_pf (Suc n) p c' in
(pres_DFA_exists_min_impl A P, c''))"
| Forall: "nfa_of_pf n (Forall p) c =
(let (c', A) = c_\<alpha> c n in
let (P, c'') = nfa_of_pf (Suc n) p c' in
(pres_DFA_forall_min_impl A P, c''))"
| Neg: "nfa_of_pf n (Neg p) c =
(let (P, c') = nfa_of_pf n p c in
(nfa.complement P, c'))"
lemmas nfa_of_pf_induct =
nfa_of_pf.induct [case_names Eq Le And Or Imp Exist Forall Neg]
lemma nfa_of_pf___correct:
assumes "c_invar c"
shows "c_invar (snd (nfa_of_pf n p c)) \<and>
nfa.invar (fst (nfa_of_pf n p c)) \<and>
NFA_isomorphic_wf (nfa.\<alpha> (fst (nfa_of_pf n p c)))
(DFA_of_pf n p)"
using assms
proof (induct n p arbitrary: c rule: DFA_of_pf_induct )
case (Eq n ks l c) note invar_c = this
from cache_correct [OF invar_c, of n]
show ?case
by (auto simp add: pres_DFA_eq_ineq_impl_correct split: prod.split)
next
case (Le n ks l c) note invar_c = this
from cache_correct [OF invar_c, of n]
show ?case
by (auto simp add: pres_DFA_eq_ineq_impl_correct split: prod.split)
next
case (And n p q c)
obtain P c' where [simp]: "nfa_of_pf n p c = (P, c')" by (rule prod.exhaust)
obtain Q c'' where [simp]: "nfa_of_pf n q c' = (Q, c'')" by (rule prod.exhaust)
from And(1)[of c] And(2)[of c'] And(3)
show ?case
apply simp
apply (intro conjI nfa.correct_isomorphic)
apply simp_all
apply (metis NFA_isomorphic_wf_\<Sigma> DFA_of_pf___correct)+
done
next
case (Or n p q c)
obtain P c' where [simp]: "nfa_of_pf n p c = (P, c')" by (rule prod.exhaust)
obtain Q c'' where [simp]: "nfa_of_pf n q c' = (Q, c'')" by (rule prod.exhaust)
from Or(1)[of c] Or(2)[of c'] Or(3)
show ?case
apply simp
apply (intro conjI nfa.correct_isomorphic)
apply simp_all
apply (metis NFA_isomorphic_wf_\<Sigma> DFA_of_pf___correct)+
done
next
case (Imp n p q c)
obtain P c' where [simp]: "nfa_of_pf n p c = (P, c')" by (rule prod.exhaust)
obtain Q c'' where [simp]: "nfa_of_pf n q c' = (Q, c'')" by (rule prod.exhaust)
from Imp(1)[of c] Imp(2)[of c'] Imp(3)
show ?case
apply simp
apply (intro conjI nfa.correct_isomorphic)
apply simp_all
apply (metis NFA_isomorphic_wf_\<Sigma> DFA_of_pf___correct)+
done
next
case (Exist n p c)
obtain c' A where [simp]: "c_\<alpha> c n = (c', A)" by (rule prod.exhaust)
obtain P c'' where [simp]: "nfa_of_pf (Suc n) p c' = (P, c'')" by (rule prod.exhaust)
from Exist(1)[of c'] Exist(2) cache_correct [of c n]
show ?case
apply simp
apply (intro conjI pres_DFA_exists_min_impl_correct)
apply simp_all
apply (metis NFA_isomorphic_wf_\<Sigma> DFA_of_pf___correct)+
done
next
case (Forall n p c)
obtain c' A where [simp]: "c_\<alpha> c n = (c', A)" by (rule prod.exhaust)
obtain P c'' where [simp]: "nfa_of_pf (Suc n) p c' = (P, c'')" by (rule prod.exhaust)
from Forall(1)[of c'] Forall(2) cache_correct [of c n]
show ?case
apply simp
apply (intro conjI pres_DFA_forall_min_impl_correct)
apply simp_all
apply (metis NFA_isomorphic_wf_\<Sigma> DFA_of_pf___correct)+
done
next
case (Neg n p c)
obtain P c' where [simp]: "nfa_of_pf n p c = (P, c')" by (rule prod.exhaust)
from Neg(1)[of c] Neg(2)
show ?case
apply simp
apply (intro conjI nfa.correct_isomorphic)
apply simp_all
done
qed
definition pf_to_nfa where
"pf_to_nfa n pf = fst (nfa_of_pf n pf (c_init ()))"
lemma pf_to_nfa___correct:
shows "nfa.invar (pf_to_nfa n p)"
"NFA_isomorphic_wf (nfa.\<alpha> (pf_to_nfa n p)) (DFA_of_pf n p)"
using nfa_of_pf___correct [of "c_init ()" n p]
unfolding pf_to_nfa_def
by (simp_all add: init_cache_OK)
lemma eval_pf_impl :
"eval_pf pf [] = nfa.accept (pf_to_nfa 0 pf) []"
proof -
note equiv_wf = pf_to_nfa___correct [of 0 pf]
note NFA_accept_OK = nfa.accept_correct___isomorphic [OF equiv_wf, of "[]"]
with DFA_of_pf___correct [of 0 pf] NFA_accept_OK
show ?thesis by simp
qed
end
locale presburger_label_set_cache_by_map_set =
s: StdSet s_ops + m: StdMap m_ops +
set_image "set_op_\<alpha> s_ops" "set_op_invar s_ops" "set_op_\<alpha> s_ops" "set_op_invar s_ops" s_image
for s_ops :: "(bool list, 'bl, _) set_ops_scheme"
and m_ops :: "(nat, 'bl, 'm, _) map_ops_scheme"
and s_image
begin
definition c_invar where
"c_invar m \<equiv> m.invar m \<and>
(\<forall>n bl. m.\<alpha> m n = Some bl \<longrightarrow> s.invar bl \<and> s.\<alpha> bl = {bv . length bv = n})"
primrec c_\<alpha> where
"c_\<alpha> m 0 = (m, s.sng [])"
| "c_\<alpha> m (Suc n) =
(case (m.lookup (Suc n) m) of Some bl \<Rightarrow> (m, bl) | None =>
(let (m', bl) = c_\<alpha> m n in
let bl' = s.union (s_image (\<lambda>l. True # l) bl) (s_image (\<lambda>l. False # l) bl) in
let m'' = m.update (Suc n) bl' m' in
(m'', bl')))"
lemma c_\<alpha>_correct :
assumes "c_invar m"
shows "c_invar (fst (c_\<alpha> m n)) \<and>
s.invar (snd (c_\<alpha> m n)) \<and>
s.\<alpha> (snd (c_\<alpha> m n)) = {bs. length bs = n}"
using assms
proof (induct n arbitrary: m)
case 0 thus ?case by (simp add: s.correct)
next
case (Suc n m)
note ind_hyp = Suc(1)
note invar_m = Suc(2)
show ?case
proof (cases "m.lookup (Suc n) m")
case (Some bl)
thus ?thesis
apply (simp add: invar_m)
apply (insert invar_m)
apply (simp add: c_invar_def m.correct)
done
next
case None note lookup_eq_none[simp] = this
obtain m' bl where [simp]: "c_\<alpha> m n = (m', bl)" by (rule prod.exhaust)
define bl' where "bl' \<equiv> set_op_union s_ops (s_image ((#) True) bl) (s_image ((#) False) bl)"
from ind_hyp [OF invar_m]
have bl'_props: "s.invar bl'" "s.\<alpha> bl' = {bs. length bs = Suc n}" and invar_m': "c_invar m'"
apply (simp_all add: s.correct bl'_def image_correct)
apply (auto simp add: image_iff length_Suc_conv)
done
from invar_m'
show ?thesis
by (simp add: bl'_def[symmetric] bl'_props c_invar_def m.correct)
qed
qed
lemma presburger_label_set_cache_OK :
"presburger_label_set_cache s.\<alpha> s.invar c_\<alpha> c_invar m.empty"
unfolding presburger_label_set_cache_def
apply (simp add: c_\<alpha>_correct)
apply (simp add: c_invar_def m.correct)
done
end
end
|
import glob
import os
import datetime
from collections import OrderedDict
import pandas as pd
import numpy as np
from sklearn.manifold import TSNE
import scipy.stats as stats
import scipy.sparse as sparse
from sparse_dataframe import SparseDataFrame
def combine_sdf_files(run_folder, folders, verbose=False, **kwargs):
"""function for concatenating SparseDataFrames together"""
combined = SparseDataFrame()
combined.rows = []
columns = set()
for folder in folders:
filename = os.path.join(run_folder, folder, f'{folder}.mus.cell-gene.npz')
if verbose:
print(f'Reading {filename} ...')
sdf = SparseDataFrame(filename)
columns.add(tuple(sdf.columns))
combined.rows.extend(sdf.rows)
if combined.matrix is None:
combined.matrix = sdf.matrix
else:
combined.matrix = sparse.vstack((combined.matrix, sdf.matrix),
format='csr')
assert len(columns) == 1
combined.columns = columns.pop()
return combined
def combine_csv_files(folder, globber, verbose=False, **kwargs):
"""generic function for concatentating a bunch of csv files into a single
pandas Dataframe"""
dfs = []
for filename in glob.iglob(os.path.join(folder, globber)):
if verbose:
print(f'Reading {filename} ...')
df = pd.read_csv(filename, **kwargs)
dfs.append(df)
combined = pd.concat(dfs)
return combined
def maybe_to_numeric(series):
try:
return pd.to_numeric(series)
except ValueError:
return series
def clean_mapping_stats(mapping_stats_original, convert_to_percentage=None):
"""Remove whitespace from all values and convert to numbers"""
if convert_to_percentage is None:
convert_to_percentage = set()
mapping_stats_original = mapping_stats_original.applymap(
lambda x: (x.replace(',', '').strip().strip('%')
if isinstance(x, str) else x))
numeric = mapping_stats_original.apply(maybe_to_numeric)
numeric.columns = numeric.columns.map(str.strip)
# for 10X mapping stats
numeric.columns = numeric.columns.map(
lambda x: ('Percent {}'.format(x.replace('Fraction ', ''))
if x in convert_to_percentage else x)
)
return numeric
def diff_exp(matrix, group1, group2, index):
"""Computes differential expression between group 1 and group 2
for each column in the dataframe counts.
Returns a dataframe of Z-scores and p-values."""
g1 = matrix[group1, :]
g2 = matrix[group2, :]
g1mu = g1.mean(0)
g2mu = g2.mean(0)
mean_diff = np.asarray(g1mu - g2mu).flatten()
# E[X^2] - (E[X])^2
pooled_sd = np.sqrt(
((g1.power(2)).mean(0) - np.power(g1mu, 2)) / len(group1)
+ ((g2.power(2)).mean(0) - np.power(g2mu, 2)) / len(group2))
pooled_sd = np.asarray(pooled_sd).flatten()
z_scores = np.zeros_like(pooled_sd)
nz = pooled_sd > 0
z_scores[nz] = np.nan_to_num(mean_diff[nz] / pooled_sd[nz])
# t-test
p_vals = (1 - stats.norm.cdf(np.abs(z_scores))) * 2
df = pd.DataFrame(OrderedDict([('z', z_scores), ('p', p_vals)]),
index=index)
return df
class Plates(object):
# Names of commonly accessed columns
MEAN_READS_PER_CELL = 'Mean reads per well'
MEDIAN_GENES_PER_CELL = 'Median genes per well'
PERCENT_ERCC = 'Percent ERCC'
PERCENT_MAPPED_READS = 'Percent mapped to genome'
# maybe we should change this to the right thing
SAMPLE_MAPPING = 'WELL_MAPPING'
def __init__(self, data_folder, metadata, genes_to_drop='Rn45s',
verbose=False, nrows=None):
plates_folder = os.path.join(data_folder, 'plates')
counts = combine_csv_files(
plates_folder, '*.htseq-count-by-cell.csv',
index_col=[0, 1, 2, 3], verbose=verbose, nrows=nrows)
mapping_stats = combine_csv_files(
plates_folder, '*.log-by-cell.csv',
index_col=[0, 1, 2, 3], verbose=verbose)
self.genes, self.cell_metadata, self.mapping_stats = \
self.clean_and_reformat(counts, mapping_stats)
self.plate_summaries = self.calculate_plate_summaries()
original_metadata = pd.read_csv(metadata, index_col=0)
self.plate_metadata = self.clean_plate_metadata(original_metadata)
self.plate_metadata = self.plate_metadata.loc[
self.plate_summaries.index]
if not os.path.exists(os.path.join(data_folder, 'coords')):
os.mkdir(os.path.join(data_folder, 'coords'))
self.bulk_smushed_cache_file = os.path.join(data_folder, 'coords',
'bulk_smushed.csv')
self.cell_smushed_cache_file = os.path.join(data_folder, 'coords',
'cell_smushed.pickle')
self.bulk_smushed = self.compute_bulk_smushing()
self.cell_smushed = self.compute_cell_smushing()
self.gene_names = sorted(self.genes.columns)
self.plate_metadata_features = sorted(self.plate_metadata.columns)
# Remove pesky genes
self.genes = self.genes.drop(genes_to_drop, axis=1)
# Get a counts per million rescaling of the genes
self.counts_per_million = self.genes.divide(self.genes.sum(axis=1),
axis=0) * 1e6
self.top_genes = self.compute_top_genes_per_cell()
self.data = {'genes': self.genes,
'mapping_stats': self.mapping_stats,
'cell_metadata': self.cell_metadata,
'plate_metadata': self.plate_metadata,
'plate_summaries': self.plate_summaries}
def __repr__(self):
n_plates = self.plate_summaries.shape[0]
n_barcodes = self.genes.shape[0]
s = f'This is an object holding data for {n_plates} plates and ' \
f'{n_barcodes} barcodes.\nHere are the accessible dataframes:\n'
for name, df in self.data.items():
s += f'\t"{name}" table dimensions: ' + str(df.shape) + '\n'
return s
@staticmethod
def clean_and_reformat(counts, mapping_stats):
"""Move metadata information into separate dataframe and simplify ids
Parameters
----------
counts : pandas.DataFrame
A (samples, genes) dataframe of integer number of reads that mapped
to a gene in a cell, but also has extra columns of ERCC mapping and
htseq-count output that we want to remove
mapping_stats : pandas.DataFrame
A (samples, mapping_statistics) dataframe of the time the alignment
began, number of input reads, number of mapped reads, and other
information output by STAR, but everything is a string instead of
numbers which makes us sad
Returns
-------
genes : pandas.DataFrame
A (samples, genes) dataframe of integer number of reads that mapped
to a gene in a cell
cell_metadata : pandas.DataFrame
A (samples, sample_features) dataframe of number of detected genes,
total reads, ercc counts, and "WELL_MAPPING" (really,
plate mapping)
mapping_stats : pandas.DataFrame
A (samples, mapping_statistics) dataframe of the time the alignment
began, number of input reads, number of mapped reads, and other
information output by STAR, with numbers properly formatted
"""
mapping_stats = clean_mapping_stats(mapping_stats)
cell_metadata = counts.index.to_frame()
sample_ids = cell_metadata.index.droplevel([1, 2, 3])
cell_metadata.index = sample_ids
mapping_stats.index = sample_ids
counts.index = sample_ids
# Extract htseq-count outputs and save as separate files
cols = [x for x in counts if x.startswith('__')]
count_stats = counts[cols]
count_stats.columns = [x.strip('_') for x in count_stats]
# Separate spike-ins (ERCCs) and genes
ercc_names = [col for col in counts.columns[3:] if 'ERCC-' in col]
gene_names = [col for col in counts.columns[3:] if
'ERCC-' not in col and col[0] != '_']
cell_metadata['total_reads'] = counts.sum(axis=1)
# Separate counts of everything from genes-only
genes = counts[gene_names]
# Add mapping and ERCC counts to cell metadata
cell_metadata['n_genes'] = (genes > 0).sum(axis=1)
cell_metadata['mapped_reads'] = genes.sum(axis=1)
cell_metadata['ercc'] = counts[ercc_names].sum(axis=1)
cell_metadata = pd.concat([cell_metadata, count_stats], axis=1)
# Remove not useful columns
cell_metadata.drop(['too_low_aQual', 'not_aligned'], inplace=True,
axis=1)
return genes, cell_metadata, mapping_stats
def calculate_plate_summaries(self):
"""Get mean reads, percent mapping, etc summaries for each plate"""
well_map = self.cell_metadata.groupby(Plates.SAMPLE_MAPPING)
# these stats are from STAR mapping
star_cols = ['Number of input reads', 'Uniquely mapped reads number']
star_stats = self.mapping_stats[star_cols].groupby(
self.cell_metadata[Plates.SAMPLE_MAPPING]).sum()
total_reads = star_stats['Number of input reads']
unique_reads = star_stats['Uniquely mapped reads number']
percent_ercc = well_map.sum()['ercc'].divide(total_reads, axis=0)
percent_mapped_reads = unique_reads / total_reads - percent_ercc
plate_summaries = pd.DataFrame(OrderedDict([
(Plates.MEAN_READS_PER_CELL, total_reads / well_map.size()),
(Plates.MEDIAN_GENES_PER_CELL, well_map.median()['n_genes']),
('Percent not uniquely aligned', 100 * well_map.sum()['alignment_not_unique'].divide(total_reads, axis=0)),
(Plates.PERCENT_MAPPED_READS, 100 * percent_mapped_reads),
('Percent no feature', 100 * well_map.sum()['no_feature'].divide(total_reads, axis=0)),
('Percent Rn45s', 100 * self.genes['Rn45s'].groupby(
self.cell_metadata[Plates.SAMPLE_MAPPING]).sum() / total_reads),
(Plates.PERCENT_ERCC, 100 * percent_ercc),
('n_wells', well_map.size())
]))
return plate_summaries
@staticmethod
def clean_plate_metadata(plate_metadata):
# Remove whitespace from "tissue" column
plate_metadata.tissue = plate_metadata.tissue.map(
lambda x: x.strip() if isinstance(x, str) else x)
# Add a column with both tissue and subtissue
cleaned_subtissue = plate_metadata['subtissue'].map(
lambda x: ': ' + x.strip() if isinstance(x, str) else '')
plate_metadata['tissue_subtissue'] = plate_metadata['tissue'] \
+ cleaned_subtissue
# Hard-coded column name of 21_55_F is actually the sample id column
plate_metadata = plate_metadata.rename(
columns={'mouse.id': 'Sample ID'})
plate_metadata['Age (months)'] = plate_metadata['Sample ID'].map(
lambda x: x.split('_')[0] if isinstance(x, str) else '')
def parse_date(x):
if isinstance(x, str):
x = x.strip()
if not x:
return np.nan
if x.endswith('/2017'):
return datetime.datetime.strptime(x, '%m/%d/%Y')
elif x.endswith('/17'):
return datetime.datetime.strptime(x, '%m/%d/%y')
else:
return datetime.datetime.strptime(x, '%y%m%d')
elif isinstance(x, float):
return datetime.datetime.strptime(str(int(x)), '%y%m%d')
else:
raise TypeError
for col in plate_metadata.columns:
if 'date' in col.lower():
plate_metadata[col] = plate_metadata[col].map(
parse_date,
na_action='ignore'
)
# Use only the metadata for the plates that have been sequenced
plate_metadata = plate_metadata.dropna(how='all', axis=1)
return plate_metadata
def compute_bulk_smushing(self):
"""Get average signal from each plate ('bulk') and find 2d embedding"""
grouped = self.genes.groupby(self.cell_metadata[self.SAMPLE_MAPPING])
if os.path.exists(self.bulk_smushed_cache_file):
smushed = pd.read_csv(self.bulk_smushed_cache_file, names=[0, 1],
header=0, index_col=0)
# if the set of plates hasn't changed, return the cached version
if set(grouped.groups) == set(smushed.index):
return smushed
# if the cache was missing or invalid, compute a new projection
medians = grouped.median()
smusher = TSNE(random_state=0, perplexity=10, metric='cosine')
smushed = pd.DataFrame(smusher.fit_transform(medians),
index=medians.index)
smushed.to_csv(self.bulk_smushed_cache_file)
return smushed
def compute_cell_smushing(self):
"""Within each plate, find a 2d embedding of all cells"""
grouped = self.genes.groupby(self.cell_metadata[self.SAMPLE_MAPPING])
if os.path.exists(self.cell_smushed_cache_file):
smusheds = pd.read_pickle(self.cell_smushed_cache_file)
# if nothing is missing, return the cached version
if not set(grouped.groups) - set(smusheds):
return smusheds
else:
smusheds = {}
for plate_name, genes_subset in grouped:
if plate_name not in smusheds:
cell_smusher = TSNE(metric='cosine', random_state=0)
cell_smushed = pd.DataFrame(
cell_smusher.fit_transform(genes_subset),
index=genes_subset.index)
smusheds[plate_name] = cell_smushed
pd.to_pickle(smusheds, self.cell_smushed_cache_file)
return smusheds
def compute_top_genes_per_cell(self):
"""Get the most highly expressed genes in every cell
Returns
-------
top_genes : pandas.Series
A mapping of the cell barcode to a ranked list of the top 10 genes,
where the first item is the most highly expressed (e.g. Rn45s)
"""
ranks = self.genes.rank(axis=1, ascending=False)
in_top10 = ranks[ranks <= 10]
top_genes = in_top10.apply(
lambda x: x.sort_values().dropna().index.tolist(), axis=1)
return top_genes
class TenX_Runs(Plates):
# Names of commonly accessed columns
MEAN_READS_PER_CELL = 'Mean Reads per Cell'
MEDIAN_GENES_PER_CELL = 'Median Genes per Cell'
PERCENT_MAPPED_READS = 'Percent Reads Mapped Confidently to Transcriptome'
SAMPLE_MAPPING = 'CHANNEL_MAPPING'
COLUMNS_TO_CONVERT = {'Valid Barcodes',
'Reads Mapped Confidently to Transcriptome',
'Reads Mapped Confidently to Exonic Regions',
'Reads Mapped Confidently to Intronic Regions',
'Reads Mapped Confidently to Intergenic Regions',
'Reads Mapped Antisense to Gene',
'Sequencing Saturation',
'Q30 Bases in Barcode', 'Q30 Bases in RNA Read',
'Q30 Bases in Sample Index', 'Q30 Bases in UMI',
'Fraction Reads in Cells'}
def __init__(self, data_folder, genes_to_drop='Rn45s',
verbose=False, nrows=None, tissue=None,
channels_to_use=None, tissue_folder='tissues'):
run_folder = os.path.join(data_folder, '10x_data')
self.plate_metadata = combine_csv_files(run_folder,
'MACA_10X_P*.csv',
index_col=0)
if tissue is not None:
tissues = tissue.split(',')
folders = self.plate_metadata.index[self.plate_metadata['Tissue'].isin(tissues)]
else:
folders = self.plate_metadata.index
folders = [f for f in folders if os.path.exists(os.path.join(run_folder, f))]
if channels_to_use is not None:
folders = [f for f in folders if f in channels_to_use]
counts = combine_sdf_files(run_folder, folders,
verbose=verbose)
mapping_stats = self.combine_metrics_files(
run_folder, folders)
self.genes, self.cell_metadata, self.mapping_stats = \
self.clean_and_reformat(counts, mapping_stats)
self.plate_summaries = self.calculate_plate_summaries()
self.plate_metadata = self.plate_metadata.loc[
self.plate_summaries.index]
self.cell_metadata = self.cell_metadata.join(self.plate_metadata,
on=self.SAMPLE_MAPPING)
smushed_folder = os.path.join(run_folder, tissue_folder)
if not os.path.exists(smushed_folder):
os.mkdir(smushed_folder)
self.cell_smushed = self.read_tissue_smushed(smushed_folder, verbose,
tissue)
self.gene_names = sorted(self.genes.columns)
self.plate_metadata_features = sorted(self.plate_metadata.columns)
# Remove pesky genes
self.genes = self.genes.drop(genes_to_drop)
# Get a counts per million rescaling of the genes
# self.counts_per_million = self.genes.divide(self.genes.sum(axis=1),
# axis=0) * 1e6
# self.top_genes = self.compute_top_genes_per_cell()
self.data = {'genes': self.genes,
'mapping_stats': self.mapping_stats,
'cell_metadata': self.cell_metadata,
'plate_metadata': self.plate_metadata,
'plate_summaries': self.plate_summaries}
def __repr__(self):
n_channels = self.plate_summaries.shape[0]
n_barcodes = len(self.genes.rows)
s = f'This is an object holding data for {n_channels} 10X channels and ' \
f'{n_barcodes} barcodes.\nHere are the accessible dataframes:\n'
for name, df in self.data.items():
s += f'\t"{name}" table dimensions: ' + str(df.shape) + '\n'
return s
@staticmethod
def combine_cell_files(folder, globber, verbose=False):
dfs = []
for filename in glob.iglob(os.path.join(folder, globber)):
if verbose:
print(f'Reading {filename} ...')
channel = os.path.basename(os.path.dirname(filename))
df = pd.read_csv(filename, index_col=0)
df.index = pd.MultiIndex.from_product(([channel], df.index),
names=['channel', 'cell_id'])
dfs.append(df)
combined = pd.concat(dfs)
return combined
@staticmethod
def combine_metrics_files(run_folder, folders):
dfs = []
for folder in folders:
filename = os.path.join(run_folder, folder, 'metrics_summary.csv')
p_name = os.path.basename(os.path.dirname(filename))
df = pd.read_csv(filename)
df[TenX_Runs.SAMPLE_MAPPING] = p_name
dfs.append(df)
combined = pd.concat(dfs)
combined.set_index(TenX_Runs.SAMPLE_MAPPING, inplace=True)
return combined
@staticmethod
def clean_and_reformat(counts, mapping_stats):
"""Move metadata information into separate dataframe and simplify ids
Parameters
----------
counts : pandas.DataFrame
A (samples, genes) dataframe of integer number of reads that mapped
to a gene in a cell, but also has extra columns of ERCC mapping and
htseq-count output that we want to remove
mapping_stats : pandas.DataFrame
A (samples, mapping_statistics) dataframe of the time the alignment
began, number of input reads, number of mapped reads, and other
information output by STAR, but everything is a string instead of
numbers which makes us sad
Returns
-------
genes : SparseDataFrame
A (samples, genes) dataframe of integer number of reads that mapped
to a gene in a cell
cell_metadata : pandas.DataFrame
A (samples, sample_features) dataframe of number of detected genes,
total reads, ercc counts, and "WELL_MAPPING" (really,
plate mapping)
mapping_stats : pandas.DataFrame
A (samples, mapping_statistics) dataframe of the time the alignment
began, number of input reads, number of mapped reads, and other
information output by CellRanger, with numbers properly formatted
"""
# counts.sort_index(inplace=True)
# channel_ids = counts.index.get_level_values(0)
channel_ids = [c.rsplit('_', 1)[0] for c in counts.rows]
mapping_stats = clean_mapping_stats(
mapping_stats,
convert_to_percentage=TenX_Runs.COLUMNS_TO_CONVERT
)
sample_ids = pd.Series(counts.rows)
# '{}_{}'.format(channel, index) for channel, index in
# counts.index
# )
cell_metadata = pd.DataFrame(
index=sample_ids,
data={TenX_Runs.SAMPLE_MAPPING: channel_ids}
)
counts.index = sample_ids
# Separate spike-ins (ERCCs) and genes
ercc_names = [col for col in counts.columns if col.startswith('ERCC-')]
gene_names = [col for col in counts.columns if
not (col.startswith('ERCC-')
or col.endswith('_transgene'))]
# Separate counts of everything from genes-only
genes = SparseDataFrame()
genes.matrix = counts[gene_names]
genes.columns = gene_names[:]
genes.rows = counts.rows[:]
# Add mapping and ERCC counts to cell metadata
cell_metadata['total_reads'] = counts.matrix.sum(axis=1)
cell_metadata['n_genes'] = (genes.matrix > 0).sum(axis=1)
cell_metadata['mapped_reads'] = genes.matrix.sum(axis=1)
cell_metadata['ercc'] = counts[ercc_names].sum(axis=1)
return genes, cell_metadata, mapping_stats
def calculate_plate_summaries(self):
"""Get mean reads, percent mapping, etc summaries for each plate"""
channel_map = self.cell_metadata.groupby(TenX_Runs.SAMPLE_MAPPING)
total_reads = self.mapping_stats['Number of Reads']
# percent_rn45s = pd.Series(self.genes['Rn45s'].todense()).groupby(
# self.cell_metadata[TenX_Runs.SAMPLE_MAPPING]
# ).sum() / total_reads
percent_ercc = channel_map['ercc'].sum().divide(total_reads, axis=0)
plate_summaries = pd.concat(
[self.mapping_stats,
pd.DataFrame(OrderedDict([
# ('Percent Rn45s', percent_rn45s),
(TenX_Runs.PERCENT_ERCC, percent_ercc),
('n_barcodes', channel_map.size())
]))], axis=1
)
return plate_summaries
def read_tissue_smushed(self, folder, verbose=False, tissue=None):
smusheds = {}
if tissue is None:
globber = glob.iglob(os.path.join(folder, 'smushed-*'))
else:
globber = glob.iglob(os.path.join(folder, f'smushed-{tissue}*'))
for filename in globber:
if verbose:
print(f'Reading {filename} ...')
tissue = filename.split('smushed-')[-1].split('.')[0]
tissue = tissue.split('-')[0]
df = pd.read_csv(filename, index_col=0)
df.rename(columns={'0': 0, '1': 1}, inplace=True)
smusheds[tissue] = df
assert len(df.columns.difference([0, 1, 'cluster'])) == 0
return smusheds
|
[GOAL]
C : Type u₁
inst✝ : Category.{v₁, u₁} C
R : Cᵒᵖ ⥤ RingCat
P : PresheafOfModules R
X : Cᵒᵖ
⊢ map P (𝟙 X) = id'
[PROOFSTEP]
ext
[GOAL]
case h
C : Type u₁
inst✝ : Category.{v₁, u₁} C
R : Cᵒᵖ ⥤ RingCat
P : PresheafOfModules R
X : Cᵒᵖ
x✝ : ↑(obj P X)
⊢ ↑(map P (𝟙 X)) x✝ = ↑id' x✝
[PROOFSTEP]
simp
[GOAL]
C : Type u₁
inst✝ : Category.{v₁, u₁} C
R : Cᵒᵖ ⥤ RingCat
P : PresheafOfModules R
X Y Z : Cᵒᵖ
f : X ⟶ Y
g : Y ⟶ Z
⊢ map P (f ≫ g) = comp (map P g) (map P f)
[PROOFSTEP]
ext
[GOAL]
case h
C : Type u₁
inst✝ : Category.{v₁, u₁} C
R : Cᵒᵖ ⥤ RingCat
P : PresheafOfModules R
X Y Z : Cᵒᵖ
f : X ⟶ Y
g : Y ⟶ Z
x✝ : ↑(obj P X)
⊢ ↑(map P (f ≫ g)) x✝ = ↑(comp (map P g) (map P f)) x✝
[PROOFSTEP]
simp
[GOAL]
C : Type u₁
inst✝ : Category.{v₁, u₁} C
R✝ : Cᵒᵖ ⥤ RingCat
P Q R : PresheafOfModules R✝
f : Hom P Q
g : Hom Q R
x✝² : Cᵒᵖ
x✝¹ : ↑(R✝.obj x✝²)
x✝ : ↑(P.presheaf.obj x✝²)
⊢ ↑(NatTrans.app (f.hom ≫ g.hom) x✝²) (x✝¹ • x✝) = x✝¹ • ↑(NatTrans.app (f.hom ≫ g.hom) x✝²) x✝
[PROOFSTEP]
simp [Hom.map_smul]
[GOAL]
C : Type u₁
inst✝ : Category.{v₁, u₁} C
R : Cᵒᵖ ⥤ RingCat
P Q : PresheafOfModules R
f g : P ⟶ Q
w : ∀ (X : Cᵒᵖ), app f X = app g X
⊢ f = g
[PROOFSTEP]
cases f
[GOAL]
case mk
C : Type u₁
inst✝ : Category.{v₁, u₁} C
R : Cᵒᵖ ⥤ RingCat
P Q : PresheafOfModules R
g : P ⟶ Q
hom✝ : P.presheaf ⟶ Q.presheaf
map_smul✝ :
∀ (X : Cᵒᵖ) (r : ↑(R.obj X)) (x : ↑(P.presheaf.obj X)), ↑(NatTrans.app hom✝ X) (r • x) = r • ↑(NatTrans.app hom✝ X) x
w : ∀ (X : Cᵒᵖ), app { hom := hom✝, map_smul := map_smul✝ } X = app g X
⊢ { hom := hom✝, map_smul := map_smul✝ } = g
[PROOFSTEP]
cases g
[GOAL]
case mk.mk
C : Type u₁
inst✝ : Category.{v₁, u₁} C
R : Cᵒᵖ ⥤ RingCat
P Q : PresheafOfModules R
hom✝¹ : P.presheaf ⟶ Q.presheaf
map_smul✝¹ :
∀ (X : Cᵒᵖ) (r : ↑(R.obj X)) (x : ↑(P.presheaf.obj X)),
↑(NatTrans.app hom✝¹ X) (r • x) = r • ↑(NatTrans.app hom✝¹ X) x
hom✝ : P.presheaf ⟶ Q.presheaf
map_smul✝ :
∀ (X : Cᵒᵖ) (r : ↑(R.obj X)) (x : ↑(P.presheaf.obj X)), ↑(NatTrans.app hom✝ X) (r • x) = r • ↑(NatTrans.app hom✝ X) x
w : ∀ (X : Cᵒᵖ), app { hom := hom✝¹, map_smul := map_smul✝¹ } X = app { hom := hom✝, map_smul := map_smul✝ } X
⊢ { hom := hom✝¹, map_smul := map_smul✝¹ } = { hom := hom✝, map_smul := map_smul✝ }
[PROOFSTEP]
congr
[GOAL]
case mk.mk.e_hom
C : Type u₁
inst✝ : Category.{v₁, u₁} C
R : Cᵒᵖ ⥤ RingCat
P Q : PresheafOfModules R
hom✝¹ : P.presheaf ⟶ Q.presheaf
map_smul✝¹ :
∀ (X : Cᵒᵖ) (r : ↑(R.obj X)) (x : ↑(P.presheaf.obj X)),
↑(NatTrans.app hom✝¹ X) (r • x) = r • ↑(NatTrans.app hom✝¹ X) x
hom✝ : P.presheaf ⟶ Q.presheaf
map_smul✝ :
∀ (X : Cᵒᵖ) (r : ↑(R.obj X)) (x : ↑(P.presheaf.obj X)), ↑(NatTrans.app hom✝ X) (r • x) = r • ↑(NatTrans.app hom✝ X) x
w : ∀ (X : Cᵒᵖ), app { hom := hom✝¹, map_smul := map_smul✝¹ } X = app { hom := hom✝, map_smul := map_smul✝ } X
⊢ hom✝¹ = hom✝
[PROOFSTEP]
ext X x
[GOAL]
case mk.mk.e_hom.w.h.w
C : Type u₁
inst✝ : Category.{v₁, u₁} C
R : Cᵒᵖ ⥤ RingCat
P Q : PresheafOfModules R
hom✝¹ : P.presheaf ⟶ Q.presheaf
map_smul✝¹ :
∀ (X : Cᵒᵖ) (r : ↑(R.obj X)) (x : ↑(P.presheaf.obj X)),
↑(NatTrans.app hom✝¹ X) (r • x) = r • ↑(NatTrans.app hom✝¹ X) x
hom✝ : P.presheaf ⟶ Q.presheaf
map_smul✝ :
∀ (X : Cᵒᵖ) (r : ↑(R.obj X)) (x : ↑(P.presheaf.obj X)), ↑(NatTrans.app hom✝ X) (r • x) = r • ↑(NatTrans.app hom✝ X) x
w : ∀ (X : Cᵒᵖ), app { hom := hom✝¹, map_smul := map_smul✝¹ } X = app { hom := hom✝, map_smul := map_smul✝ } X
X : Cᵒᵖ
x : ↑(P.presheaf.obj X)
⊢ ↑(NatTrans.app hom✝¹ X) x = ↑(NatTrans.app hom✝ X) x
[PROOFSTEP]
exact LinearMap.congr_fun (w X) x
|
function r = acot(a)
%ACOT Taylor inverse cotangent acot(a)
%
%Thanks to George Corliss for providing the Taylor expansion
%
% written 06/03/09 S.M. Rump
% modified 08/26/12 S.M. Rump global variables removed
%
e = 1e-30;
if 1+e==1-e % fast check for rounding to nearest
rndold = 0;
else
rndold = getround;
setround(0)
end
K = getappdata(0,'INTLAB_TAYLOR_ORDER');
r = a;
ct = a.t;
N = size(a.t,2);
r.t(1,:) = acot(a.t(1,:));
ct1 = 1+a.t(1,:).^2; % 1+a^2
r.t(2,:) = -a.t(2,:) ./ ct1 ;
for j=2:K
ct(j,:) = sum( a.t(1:j,:).*a.t(j:-1:1,:) , 1 );
r.t(j+1,:) = ( j*a.t(j+1,:) + sum( repmat((1:j-1)',1,N).*r.t(2:j,:).*ct(j:-1:2,:) , 1 ) ) ./ ( (-j)*ct1 );
end
if rndold
setround(rndold)
end
|
-- ------------------------------------------------------------- [ Char.idr ]
-- Module : Lightyear.Testing
-- Description : Testing utilities.
--
-- This code is distributed under the BSD 2-clause license.
-- See the file LICENSE in the root directory for its full text.
--
-- --------------------------------------------------------------------- [ EOH ]
module Lightyear.Testing
import Data.Strings
import Lightyear
import Lightyear.Strings
-- %access export
%default total
||| Simple data structure to store the result of a parsing test.
export
data TestReport : Type where
Pass : (title : String) -> TestReport
ParseFailure : (title : String)
-> (report : String)
-> TestReport
ResultFailure : (title : String) -> (made : String) -> TestReport
||| Report a parsing failure with expected failure
AdvParseFailure : Show a
=> (title : String)
-> (input : String)
-> (expected : a)
-> (report : String)
-> TestReport
||| Report a wrong result failure with expected failure.
AdvResultFailure : Show a
=> (title : String)
-> (input : String)
-> (expected : a)
-> (actual : a)
-> TestReport
||| Run a parsing test that is expected to pass and discard result.
|||
||| @title Name of the test.
||| @p The parser to test.
||| @input The input string to parse.
export
parseTest : Show a
=> (title : String)
-> (p : Parser a)
-> (input : String)
-> TestReport
parseTest title p input = do
case parse p input of
Left err => ParseFailure title err
Right actual => Pass title
||| Run a parsing test that is expected to fail and discard result.
|||
||| @title Name of the test.
||| @p The parser to test.
||| @input The input string to parse.
export
parseTestNot : Show a
=> (title : String)
-> (p : Parser a)
-> (input : String)
-> TestReport
parseTestNot title p input = do
case parse p input of
Left err => Pass title
Right actual => ResultFailure title (show actual)
||| Run a parsing test that is expected to pass and compare result to
||| an expected value.
|||
||| @title Name of the test.
||| @p The parser to test.
||| @input The input string to parse.
||| @expected The expected output from a successful parsing.
||| @eq A comparison function.
export
parseTestCmp : Show a
=> (title : String)
-> (p : Parser a)
-> (eq : a -> a -> Bool)
-> (input : String)
-> (expected : a)
-> TestReport
parseTestCmp title p test input expected = do
case parse p input of
Left err => AdvParseFailure title input expected err
Right actual => if test actual expected
then Pass title
else AdvResultFailure title input expected actual
||| Run a parsing test that is expected to fail.
|||
||| @title Name of the test.
||| @p The parser to test.
||| @input The input string to parse.
||| @expected The expected parsing error message.
export
parseTestCmpNot : Show a
=> (title : String)
-> (p : Parser a)
-> (input : String)
-> (expected : String)
-> TestReport
parseTestCmpNot title p input expected = do
case parse p input of
Left actual => if trim actual == trim expected
then Pass title
else AdvParseFailure title input expected actual
Right result => AdvResultFailure title input result result
||| Run a parsing test that is expected to pass and compare showing
||| the result to an expected value.
|||
||| @title Name of the test.
||| @p The parser to test.
||| @input The input string to parse.
||| @expected The expected output from a successful parsing.
export
parseTestCmpShow : Show a
=> (title : String)
-> (p : Parser a)
-> (input : String)
-> (expected : String)
-> TestReport
parseTestCmpShow title p input expected = do
case parse p input of
Left err => ParseFailure title err
Right actual => if show actual == expected
then Pass title
else ResultFailure title (show actual)
||| Turn the test report into a string.
private
showReport : TestReport -> String
showReport (Pass title) = unwords ["[PASS]", title]
showReport (ParseFailure title report) =
unlines [ unwords ["[FAIL]", "[PARSING]", title]
, unwords ["\t", "Gave error:"]
, report
]
showReport (ResultFailure title made) =
unlines [ unwords ["[FAIL]", "[RESULT]", title]
, unwords ["\t", "I was able to parse, when I shouldn't and made:"]
, unwords ["\t\t", made]
]
showReport (AdvParseFailure title input expected report) =
unlines [ unwords ["[FAIL]", "[PARSING]", title]
, unwords ["\t", "Given input:"]
, unwords ["\t\t", input]
, unwords ["\t", "Gave error:"]
, report
]
showReport (AdvResultFailure title input expected actual) =
unlines $ head ++ footer
where
head : List String
head = [ unwords ["[FAIL]", "[RESULT]", title]
, unwords ["\t", "Given input:"]
, unwords ["\t\t", input]
]
footer : List String
footer = [ unwords ["\t", "I made:"]
, unwords ["\t\t", show actual]
, unwords ["\t", "But was expected to make:"]
, unwords ["\t\t", show expected]
]
||| Run an individual test.
export
runTest : TestReport -> IO ()
runTest = (putStrLn . showReport)
||| Run a sequence of tests.
export
runTests : List TestReport -> IO ()
runTests = traverse_ runTest
-- --------------------------------------------------------------------- [ EOF ]
|
/-
Copyright (c) 2021 Rémy Degenne. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Rémy Degenne
-/
import algebra.big_operators.intervals
import measure_theory.measure.measure_space
import measure_theory.pi_system
/-!
# Independence of sets of sets and measure spaces (σ-algebras)
* A family of sets of sets `π : ι → set (set α)` is independent with respect to a measure `μ` if for
any finite set of indices `s = {i_1, ..., i_n}`, for any sets `f i_1 ∈ π i_1, ..., f i_n ∈ π i_n`,
`μ (⋂ i in s, f i) = ∏ i in s, μ (f i) `. It will be used for families of π-systems.
* A family of measurable space structures (i.e. of σ-algebras) is independent with respect to a
measure `μ` (typically defined on a finer σ-algebra) if the family of sets of measurable sets they
define is independent. I.e., `m : ι → measurable_space α` is independent with respect to a
measure `μ` if for any finite set of indices `s = {i_1, ..., i_n}`, for any sets
`f i_1 ∈ m i_1, ..., f i_n ∈ m i_n`, then `μ (⋂ i in s, f i) = ∏ i in s, μ (f i)`.
* Independence of sets (or events in probabilistic parlance) is defined as independence of the
measurable space structures they generate: a set `s` generates the measurable space structure with
measurable sets `∅, s, sᶜ, univ`.
* Independence of functions (or random variables) is also defined as independence of the measurable
space structures they generate: a function `f` for which we have a measurable space `m` on the
codomain generates `measurable_space.comap f m`.
## Main statements
* TODO: `Indep_of_Indep_sets`: if π-systems are independent as sets of sets, then the
measurable space structures they generate are independent.
* `indep_of_indep_sets`: variant with two π-systems.
## Implementation notes
We provide one main definition of independence:
* `Indep_sets`: independence of a family of sets of sets `pi : ι → set (set α)`.
Three other independence notions are defined using `Indep_sets`:
* `Indep`: independence of a family of measurable space structures `m : ι → measurable_space α`,
* `Indep_set`: independence of a family of sets `s : ι → set α`,
* `Indep_fun`: independence of a family of functions. For measurable spaces
`m : Π (i : ι), measurable_space (β i)`, we consider functions `f : Π (i : ι), α → β i`.
Additionally, we provide four corresponding statements for two measurable space structures (resp.
sets of sets, sets, functions) instead of a family. These properties are denoted by the same names
as for a family, but without a capital letter, for example `indep_fun` is the version of `Indep_fun`
for two functions.
The definition of independence for `Indep_sets` uses finite sets (`finset`). An alternative and
equivalent way of defining independence would have been to use countable sets.
TODO: prove that equivalence.
Most of the definitions and lemma in this file list all variables instead of using the `variables`
keyword at the beginning of a section, for example
`lemma indep.symm {α} {m₁ m₂ : measurable_space α} [measurable_space α] {μ : measure α} ...` .
This is intentional, to be able to control the order of the `measurable_space` variables. Indeed
when defining `μ` in the example above, the measurable space used is the last one defined, here
`[measurable_space α]`, and not `m₁` or `m₂`.
## References
* Williams, David. Probability with martingales. Cambridge university press, 1991.
Part A, Chapter 4.
-/
open measure_theory measurable_space
open_locale big_operators classical
namespace probability_theory
section definitions
/-- A family of sets of sets `π : ι → set (set α)` is independent with respect to a measure `μ` if
for any finite set of indices `s = {i_1, ..., i_n}`, for any sets
`f i_1 ∈ π i_1, ..., f i_n ∈ π i_n`, then `μ (⋂ i in s, f i) = ∏ i in s, μ (f i) `.
It will be used for families of pi_systems. -/
def Indep_sets {α ι} [measurable_space α] (π : ι → set (set α)) (μ : measure α . volume_tac) :
Prop :=
∀ (s : finset ι) {f : ι → set α} (H : ∀ i, i ∈ s → f i ∈ π i), μ (⋂ i ∈ s, f i) = ∏ i in s, μ (f i)
/-- Two sets of sets `s₁, s₂` are independent with respect to a measure `μ` if for any sets
`t₁ ∈ p₁, t₂ ∈ s₂`, then `μ (t₁ ∩ t₂) = μ (t₁) * μ (t₂)` -/
def indep_sets {α} [measurable_space α] (s1 s2 : set (set α)) (μ : measure α . volume_tac) : Prop :=
∀ t1 t2 : set α, t1 ∈ s1 → t2 ∈ s2 → μ (t1 ∩ t2) = μ t1 * μ t2
/-- A family of measurable space structures (i.e. of σ-algebras) is independent with respect to a
measure `μ` (typically defined on a finer σ-algebra) if the family of sets of measurable sets they
define is independent. `m : ι → measurable_space α` is independent with respect to measure `μ` if
for any finite set of indices `s = {i_1, ..., i_n}`, for any sets
`f i_1 ∈ m i_1, ..., f i_n ∈ m i_n`, then `μ (⋂ i in s, f i) = ∏ i in s, μ (f i) `. -/
def Indep {α ι} (m : ι → measurable_space α) [measurable_space α] (μ : measure α . volume_tac) :
Prop :=
Indep_sets (λ x, (m x).measurable_set') μ
/-- Two measurable space structures (or σ-algebras) `m₁, m₂` are independent with respect to a
measure `μ` (defined on a third σ-algebra) if for any sets `t₁ ∈ m₁, t₂ ∈ m₂`,
`μ (t₁ ∩ t₂) = μ (t₁) * μ (t₂)` -/
def indep {α} (m₁ m₂ : measurable_space α) [measurable_space α] (μ : measure α . volume_tac) :
Prop :=
indep_sets (m₁.measurable_set') (m₂.measurable_set') μ
/-- A family of sets is independent if the family of measurable space structures they generate is
independent. For a set `s`, the generated measurable space has measurable sets `∅, s, sᶜ, univ`. -/
def Indep_set {α ι} [measurable_space α] (s : ι → set α) (μ : measure α . volume_tac) : Prop :=
Indep (λ i, generate_from {s i}) μ
/-- Two sets are independent if the two measurable space structures they generate are independent.
For a set `s`, the generated measurable space structure has measurable sets `∅, s, sᶜ, univ`. -/
def indep_set {α} [measurable_space α] (s t : set α) (μ : measure α . volume_tac) : Prop :=
indep (generate_from {s}) (generate_from {t}) μ
/-- A family of functions defined on the same space `α` and taking values in possibly different
spaces, each with a measurable space structure, is independent if the family of measurable space
structures they generate on `α` is independent. For a function `g` with codomain having measurable
space structure `m`, the generated measurable space structure is `measurable_space.comap g m`. -/
def Indep_fun {α ι} [measurable_space α] {β : ι → Type*} (m : Π (x : ι), measurable_space (β x))
(f : Π (x : ι), α → β x) (μ : measure α . volume_tac) : Prop :=
Indep (λ x, measurable_space.comap (f x) (m x)) μ
/-- Two functions are independent if the two measurable space structures they generate are
independent. For a function `f` with codomain having measurable space structure `m`, the generated
measurable space structure is `measurable_space.comap f m`. -/
def indep_fun {α β γ} [measurable_space α] [mβ : measurable_space β] [mγ : measurable_space γ]
(f : α → β) (g : α → γ) (μ : measure α . volume_tac) : Prop :=
indep (measurable_space.comap f mβ) (measurable_space.comap g mγ) μ
end definitions
section indep
lemma indep_sets.symm {α} {s₁ s₂ : set (set α)} [measurable_space α] {μ : measure α}
(h : indep_sets s₁ s₂ μ) :
indep_sets s₂ s₁ μ :=
by { intros t1 t2 ht1 ht2, rw [set.inter_comm, mul_comm], exact h t2 t1 ht2 ht1, }
lemma indep.symm {α} {m₁ m₂ : measurable_space α} [measurable_space α] {μ : measure α}
(h : indep m₁ m₂ μ) :
indep m₂ m₁ μ :=
indep_sets.symm h
lemma indep_sets_of_indep_sets_of_le_left {α} {s₁ s₂ s₃: set (set α)} [measurable_space α]
{μ : measure α} (h_indep : indep_sets s₁ s₂ μ) (h31 : s₃ ⊆ s₁) :
indep_sets s₃ s₂ μ :=
λ t1 t2 ht1 ht2, h_indep t1 t2 (set.mem_of_subset_of_mem h31 ht1) ht2
lemma indep_sets_of_indep_sets_of_le_right {α} {s₁ s₂ s₃: set (set α)} [measurable_space α]
{μ : measure α} (h_indep : indep_sets s₁ s₂ μ) (h32 : s₃ ⊆ s₂) :
indep_sets s₁ s₃ μ :=
λ t1 t2 ht1 ht2, h_indep t1 t2 ht1 (set.mem_of_subset_of_mem h32 ht2)
lemma indep_of_indep_of_le_left {α} {m₁ m₂ m₃: measurable_space α} [measurable_space α]
{μ : measure α} (h_indep : indep m₁ m₂ μ) (h31 : m₃ ≤ m₁) :
indep m₃ m₂ μ :=
λ t1 t2 ht1 ht2, h_indep t1 t2 (h31 _ ht1) ht2
lemma indep_of_indep_of_le_right {α} {m₁ m₂ m₃: measurable_space α} [measurable_space α]
{μ : measure α} (h_indep : indep m₁ m₂ μ) (h32 : m₃ ≤ m₂) :
indep m₁ m₃ μ :=
λ t1 t2 ht1 ht2, h_indep t1 t2 ht1 (h32 _ ht2)
lemma indep_sets.union {α} [measurable_space α] {s₁ s₂ s' : set (set α)} {μ : measure α}
(h₁ : indep_sets s₁ s' μ) (h₂ : indep_sets s₂ s' μ) :
indep_sets (s₁ ∪ s₂) s' μ :=
begin
intros t1 t2 ht1 ht2,
cases (set.mem_union _ _ _).mp ht1 with ht1₁ ht1₂,
{ exact h₁ t1 t2 ht1₁ ht2, },
{ exact h₂ t1 t2 ht1₂ ht2, },
end
@[simp] lemma indep_sets.union_iff {α} [measurable_space α] {s₁ s₂ s' : set (set α)}
{μ : measure α} :
indep_sets (s₁ ∪ s₂) s' μ ↔ indep_sets s₁ s' μ ∧ indep_sets s₂ s' μ :=
⟨λ h, ⟨indep_sets_of_indep_sets_of_le_left h (set.subset_union_left s₁ s₂),
indep_sets_of_indep_sets_of_le_left h (set.subset_union_right s₁ s₂)⟩,
λ h, indep_sets.union h.left h.right⟩
lemma indep_sets.Union {α ι} [measurable_space α] {s : ι → set (set α)} {s' : set (set α)}
{μ : measure α} (hyp : ∀ n, indep_sets (s n) s' μ) :
indep_sets (⋃ n, s n) s' μ :=
begin
intros t1 t2 ht1 ht2,
rw set.mem_Union at ht1,
cases ht1 with n ht1,
exact hyp n t1 t2 ht1 ht2,
end
lemma indep_sets.inter {α} [measurable_space α] {s₁ s' : set (set α)} (s₂ : set (set α))
{μ : measure α} (h₁ : indep_sets s₁ s' μ) :
indep_sets (s₁ ∩ s₂) s' μ :=
λ t1 t2 ht1 ht2, h₁ t1 t2 ((set.mem_inter_iff _ _ _).mp ht1).left ht2
lemma indep_sets.Inter {α ι} [measurable_space α] {s : ι → set (set α)} {s' : set (set α)}
{μ : measure α} (h : ∃ n, indep_sets (s n) s' μ) :
indep_sets (⋂ n, s n) s' μ :=
by {intros t1 t2 ht1 ht2, cases h with n h, exact h t1 t2 (set.mem_Inter.mp ht1 n) ht2 }
lemma indep_sets_singleton_iff {α} [measurable_space α] {s t : set α} {μ : measure α} :
indep_sets {s} {t} μ ↔ μ (s ∩ t) = μ s * μ t :=
⟨λ h, h s t rfl rfl,
λ h s1 t1 hs1 ht1, by rwa [set.mem_singleton_iff.mp hs1, set.mem_singleton_iff.mp ht1]⟩
end indep
/-! ### Deducing `indep` from `Indep` -/
section from_Indep_to_indep
lemma Indep_sets.indep_sets {α ι} {s : ι → set (set α)} [measurable_space α] {μ : measure α}
(h_indep : Indep_sets s μ) {i j : ι} (hij : i ≠ j) :
indep_sets (s i) (s j) μ :=
begin
intros t₁ t₂ ht₁ ht₂,
have hf_m : ∀ (x : ι), x ∈ {i, j} → (ite (x=i) t₁ t₂) ∈ s x,
{ intros x hx,
cases finset.mem_insert.mp hx with hx hx,
{ simp [hx, ht₁], },
{ simp [finset.mem_singleton.mp hx, hij.symm, ht₂], }, },
have h1 : t₁ = ite (i = i) t₁ t₂, by simp only [if_true, eq_self_iff_true],
have h2 : t₂ = ite (j = i) t₁ t₂, by simp only [hij.symm, if_false],
have h_inter : (⋂ (t : ι) (H : t ∈ ({i, j} : finset ι)), ite (t = i) t₁ t₂)
= (ite (i = i) t₁ t₂) ∩ (ite (j = i) t₁ t₂),
by simp only [finset.set_bInter_singleton, finset.set_bInter_insert],
have h_prod : (∏ (t : ι) in ({i, j} : finset ι), μ (ite (t = i) t₁ t₂))
= μ (ite (i = i) t₁ t₂) * μ (ite (j = i) t₁ t₂),
by simp only [hij, finset.prod_singleton, finset.prod_insert, not_false_iff,
finset.mem_singleton],
rw h1,
nth_rewrite 1 h2,
nth_rewrite 3 h2,
rw [←h_inter, ←h_prod, h_indep {i, j} hf_m],
end
lemma Indep.indep {α ι} {m : ι → measurable_space α} [measurable_space α] {μ : measure α}
(h_indep : Indep m μ) {i j : ι} (hij : i ≠ j) :
indep (m i) (m j) μ :=
begin
change indep_sets ((λ x, (m x).measurable_set') i) ((λ x, (m x).measurable_set') j) μ,
exact Indep_sets.indep_sets h_indep hij,
end
end from_Indep_to_indep
/-!
## π-system lemma
Independence of measurable spaces is equivalent to independence of generating π-systems.
-/
section from_measurable_spaces_to_sets_of_sets
/-! ### Independence of measurable space structures implies independence of generating π-systems -/
lemma Indep.Indep_sets {α ι} [measurable_space α] {μ : measure α} {m : ι → measurable_space α}
{s : ι → set (set α)} (hms : ∀ n, m n = measurable_space.generate_from (s n))
(h_indep : Indep m μ) :
Indep_sets s μ :=
begin
refine (λ S f hfs, h_indep S (λ x hxS, _)),
simp_rw hms x,
exact measurable_set_generate_from (hfs x hxS),
end
lemma indep.indep_sets {α} [measurable_space α] {μ : measure α} {s1 s2 : set (set α)}
(h_indep : indep (generate_from s1) (generate_from s2) μ) :
indep_sets s1 s2 μ :=
λ t1 t2 ht1 ht2, h_indep t1 t2 (measurable_set_generate_from ht1) (measurable_set_generate_from ht2)
end from_measurable_spaces_to_sets_of_sets
section from_pi_systems_to_measurable_spaces
/-! ### Independence of generating π-systems implies independence of measurable space structures -/
private lemma indep_sets.indep_aux {α} {m2 : measurable_space α}
{m : measurable_space α} {μ : measure α} [is_probability_measure μ] {p1 p2 : set (set α)}
(h2 : m2 ≤ m) (hp2 : is_pi_system p2) (hpm2 : m2 = generate_from p2)
(hyp : indep_sets p1 p2 μ) {t1 t2 : set α} (ht1 : t1 ∈ p1) (ht2m : m2.measurable_set' t2) :
μ (t1 ∩ t2) = μ t1 * μ t2 :=
begin
let μ_inter := μ.restrict t1,
let ν := (μ t1) • μ,
have h_univ : μ_inter set.univ = ν set.univ,
by rw [measure.restrict_apply_univ, measure.smul_apply, measure_univ, mul_one],
haveI : is_finite_measure μ_inter := @restrict.is_finite_measure α _ t1 μ ⟨measure_lt_top μ t1⟩,
rw [set.inter_comm, ←@measure.restrict_apply α _ μ t1 t2 (h2 t2 ht2m)],
refine ext_on_measurable_space_of_generate_finite m p2 (λ t ht, _) h2 hpm2 hp2 h_univ ht2m,
have ht2 : m.measurable_set' t,
{ refine h2 _ _,
rw hpm2,
exact measurable_set_generate_from ht, },
rw [measure.restrict_apply ht2, measure.smul_apply, set.inter_comm],
exact hyp t1 t ht1 ht,
end
lemma indep_sets.indep {α} {m1 m2 : measurable_space α} {m : measurable_space α}
{μ : measure α} [is_probability_measure μ] {p1 p2 : set (set α)} (h1 : m1 ≤ m) (h2 : m2 ≤ m)
(hp1 : is_pi_system p1) (hp2 : is_pi_system p2) (hpm1 : m1 = generate_from p1)
(hpm2 : m2 = generate_from p2) (hyp : indep_sets p1 p2 μ) :
indep m1 m2 μ :=
begin
intros t1 t2 ht1 ht2,
let μ_inter := μ.restrict t2,
let ν := (μ t2) • μ,
have h_univ : μ_inter set.univ = ν set.univ,
by rw [measure.restrict_apply_univ, measure.smul_apply, measure_univ, mul_one],
haveI : is_finite_measure μ_inter := @restrict.is_finite_measure α _ t2 μ ⟨measure_lt_top μ t2⟩,
rw [mul_comm, ←@measure.restrict_apply α _ μ t2 t1 (h1 t1 ht1)],
refine ext_on_measurable_space_of_generate_finite m p1 (λ t ht, _) h1 hpm1 hp1 h_univ ht1,
have ht1 : m.measurable_set' t,
{ refine h1 _ _,
rw hpm1,
exact measurable_set_generate_from ht, },
rw [measure.restrict_apply ht1, measure.smul_apply, mul_comm],
exact indep_sets.indep_aux h2 hp2 hpm2 hyp ht ht2,
end
end from_pi_systems_to_measurable_spaces
section indep_set
/-! ### Independence of measurable sets
We prove the following equivalences on `indep_set`, for measurable sets `s, t`.
* `indep_set s t μ ↔ μ (s ∩ t) = μ s * μ t`,
* `indep_set s t μ ↔ indep_sets {s} {t} μ`.
-/
variables {α : Type*} [measurable_space α] {s t : set α} (S T : set (set α))
lemma indep_set_iff_indep_sets_singleton (hs_meas : measurable_set s) (ht_meas : measurable_set t)
(μ : measure α . volume_tac) [is_probability_measure μ] :
indep_set s t μ ↔ indep_sets {s} {t} μ :=
⟨indep.indep_sets, λ h, indep_sets.indep
(generate_from_le (λ u hu, by rwa set.mem_singleton_iff.mp hu))
(generate_from_le (λ u hu, by rwa set.mem_singleton_iff.mp hu)) (is_pi_system.singleton s)
(is_pi_system.singleton t) rfl rfl h⟩
lemma indep_set_iff_measure_inter_eq_mul (hs_meas : measurable_set s) (ht_meas : measurable_set t)
(μ : measure α . volume_tac) [is_probability_measure μ] :
indep_set s t μ ↔ μ (s ∩ t) = μ s * μ t :=
(indep_set_iff_indep_sets_singleton hs_meas ht_meas μ).trans indep_sets_singleton_iff
lemma indep_sets.indep_set_of_mem (hs : s ∈ S) (ht : t ∈ T) (hs_meas : measurable_set s)
(ht_meas : measurable_set t) (μ : measure α . volume_tac) [is_probability_measure μ]
(h_indep : indep_sets S T μ) :
indep_set s t μ :=
(indep_set_iff_measure_inter_eq_mul hs_meas ht_meas μ).mpr (h_indep s t hs ht)
end indep_set
end probability_theory
|
(* Title: HOL/Auth/n_flash_lemma_on_inv__115.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__115 imports n_flash_base
begin
section{*All lemmas on causal relation between inv__115 and some rule r*}
lemma n_NI_Local_Get_Put_HeadVsinv__115:
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__115 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__115 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'') ''NakcMsg'') ''Cmd'')) (Const NAKC_Nakc)) (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 "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''NakcMsg'') ''Cmd'')) (Const NAKC_Nakc))))" in exI, auto) done
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__115:
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__115 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__115 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_Get)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''HomeProc'')) (Const false))) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''InvSet'') p__Inv4)) (Const true))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') src) ''Cmd'')) (Const UNI_Get)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') src) ''HomeProc'')) (Const false))) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''InvSet'') p__Inv4)) (Const true))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') src) ''Cmd'')) (Const UNI_Get)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') src) ''HomeProc'')) (Const false))) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''InvSet'') p__Inv4)) (Const true))))" in exI, auto) done
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__115:
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__115 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__115 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 "?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 (Para (Field (Field (Ident ''Sta'') ''Dir'') ''InvSet'') p__Inv4)) (Const true))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=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 (Para (Field (Field (Ident ''Sta'') ''Dir'') ''InvSet'') p__Inv4)) (Const true))))" in exI, auto) done
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__115:
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__115 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__115 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__115:
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__115 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__115 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__115:
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__115 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__115 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__115:
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__115 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__115 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__115:
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__115 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__115 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__115:
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__115 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__115 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__115:
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__115 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__115 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 "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) s))\<or>((formEval (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4)))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))" by auto
moreover {
assume c1: "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) s))"
have "?P3 s"
apply (cut_tac a1 a2 b1 c1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''NakcMsg'') ''Cmd'')) (Const NAKC_Nakc)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4)))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) 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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) 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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))"
have "?P1 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
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7__part__1Vsinv__115:
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__115 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__115 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 "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) s))\<or>((formEval (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4)))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))" by auto
moreover {
assume c1: "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) s))"
have "?P3 s"
apply (cut_tac a1 a2 b1 c1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''NakcMsg'') ''Cmd'')) (Const NAKC_Nakc)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4)))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) s))"
have "?P3 s"
apply (cut_tac a1 a2 b1 c1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''NakcMsg'') ''Cmd'')) (Const NAKC_Nakc)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Local'')) (Const true))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) 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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))"
have "?P1 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
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__0Vsinv__115:
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__115 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__115 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 "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) s))\<or>((formEval (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4)))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))" by auto
moreover {
assume c1: "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) s))"
have "?P3 s"
apply (cut_tac a1 a2 b1 c1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''NakcMsg'') ''Cmd'')) (Const NAKC_Nakc)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4)))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) 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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) 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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))"
have "?P1 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
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__1Vsinv__115:
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__115 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__115 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 "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) s))\<or>((formEval (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4)))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))" by auto
moreover {
assume c1: "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) s))"
have "?P3 s"
apply (cut_tac a1 a2 b1 c1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''NakcMsg'') ''Cmd'')) (Const NAKC_Nakc)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4)))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) s))"
have "?P3 s"
apply (cut_tac a1 a2 b1 c1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''NakcMsg'') ''Cmd'')) (Const NAKC_Nakc)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Local'')) (Const true))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) 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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))"
have "?P1 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
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_HomeVsinv__115:
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__115 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__115 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 "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) s))\<or>((formEval (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4)))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))" by auto
moreover {
assume c1: "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) s))"
have "?P3 s"
apply (cut_tac a1 a2 b1 c1, 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 c1: "((formEval (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4)))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) 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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) 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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))"
have "?P1 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
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_Home_NODE_GetVsinv__115:
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__115 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__115 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 "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) s))\<or>((formEval (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4)))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))" by auto
moreover {
assume c1: "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) s))"
have "?P3 s"
apply (cut_tac a1 a2 b1 c1, 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 c1: "((formEval (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4)))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) 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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) 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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))"
have "?P1 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
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8Vsinv__115:
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__115 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__115 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 "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) s))\<or>((formEval (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4)))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))" by auto
moreover {
assume c1: "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) s))"
have "?P3 s"
apply (cut_tac a1 a2 b1 c1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''NakcMsg'') ''Cmd'')) (Const NAKC_Nakc)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4)))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) 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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) 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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))"
have "?P1 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\<and>pp~=p__Inv4)"
have "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) s))\<or>((formEval (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4)))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))" by auto
moreover {
assume c1: "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) s))"
have "?P3 s"
apply (cut_tac a1 a2 b1 c1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''NakcMsg'') ''Cmd'')) (Const NAKC_Nakc)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4)))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) 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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) 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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))"
have "?P1 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
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_NODE_GetVsinv__115:
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__115 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__115 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 "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) s))\<or>((formEval (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4)))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))" by auto
moreover {
assume c1: "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) s))"
have "?P3 s"
apply (cut_tac a1 a2 b1 c1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''NakcMsg'') ''Cmd'')) (Const NAKC_Nakc)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4)))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) 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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) 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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))"
have "?P1 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\<and>pp~=p__Inv4)"
have "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) s))\<or>((formEval (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4)))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))" by auto
moreover {
assume c1: "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) s))"
have "?P3 s"
apply (cut_tac a1 a2 b1 c1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''NakcMsg'') ''Cmd'')) (Const NAKC_Nakc)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4)))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) 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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) 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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))"
have "?P1 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
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_9__part__0Vsinv__115:
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__115 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__115 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 "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) s))\<or>((formEval (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4)))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))" by auto
moreover {
assume c1: "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) s))"
have "?P3 s"
apply (cut_tac a1 a2 b1 c1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''NakcMsg'') ''Cmd'')) (Const NAKC_Nakc)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4)))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) 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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) 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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))"
have "?P1 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
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_9__part__1Vsinv__115:
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__115 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__115 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 "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) s))\<or>((formEval (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4)))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))" by auto
moreover {
assume c1: "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) s))"
have "?P3 s"
apply (cut_tac a1 a2 b1 c1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''NakcMsg'') ''Cmd'')) (Const NAKC_Nakc)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4)))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) s))"
have "?P3 s"
apply (cut_tac a1 a2 b1 c1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''NakcMsg'') ''Cmd'')) (Const NAKC_Nakc)) (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 c1: "((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) 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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))"
have "?P1 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
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_10_HomeVsinv__115:
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__115 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__115 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 "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) s))\<or>((formEval (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4)))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))" by auto
moreover {
assume c1: "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) s))"
have "?P3 s"
apply (cut_tac a1 a2 b1 c1, 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 c1: "((formEval (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4)))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) 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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) 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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))"
have "?P1 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
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_10Vsinv__115:
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__115 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__115 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 "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) s))\<or>((formEval (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4)))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))" by auto
moreover {
assume c1: "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) s))"
have "?P3 s"
apply (cut_tac a1 a2 b1 c1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''NakcMsg'') ''Cmd'')) (Const NAKC_Nakc)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4)))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) 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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) 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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))"
have "?P1 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\<and>pp~=p__Inv4)"
have "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) s))\<or>((formEval (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4)))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))" by auto
moreover {
assume c1: "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) s))"
have "?P3 s"
apply (cut_tac a1 a2 b1 c1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''NakcMsg'') ''Cmd'')) (Const NAKC_Nakc)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4)))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) 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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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 (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) 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 (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))"
have "?P1 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
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_11Vsinv__115:
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__115 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__115 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_NakVsinv__115:
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__115 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__115 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (andForm (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''InvSet'') p__Inv4)) (Const true)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_GetX))) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''HomeProc'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (andForm (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''InvSet'') p__Inv4)) (Const true)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') src) ''Cmd'')) (Const UNI_GetX))) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') src) ''HomeProc'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (andForm (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''InvSet'') p__Inv4)) (Const true)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') src) ''Cmd'')) (Const UNI_GetX))) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') src) ''HomeProc'')) (Const false))))" in exI, auto) done
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__115:
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__115 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__115 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 "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeUniMsg'') ''Cmd'')) (Const UNI_GetX)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''InvSet'') p__Inv4)) (Const true))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=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_GetX)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''InvSet'') p__Inv4)) (Const true))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_InvAck_exists_HomeVsinv__115:
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__115 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_InvAck_exists_Home src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__115 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_InvAck_existsVsinv__115:
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__115 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_InvAck_exists src pp" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__115 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 "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_InvAck_1Vsinv__115:
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__115 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_InvAck_1 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__115 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_InvAck_2Vsinv__115:
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__115 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_InvAck_2 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__115 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_InvAck_3Vsinv__115:
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__115 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_InvAck_3 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__115 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_ReplaceVsinv__115:
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__115 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__115 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_GetX_PutX_HeadVld__part__0Vsinv__115:
assumes a1: "(r=n_PI_Local_GetX_PutX_HeadVld__part__0 N )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__115 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__115 p__Inv4" apply fastforce done
have "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) s))\<or>((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))" by auto
moreover {
assume c1: "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (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'') ''NakcMsg'') ''Cmd'')) (Const NAKC_Nakc)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) s))"
have "?P3 s"
apply (cut_tac a1 a2 c1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''NakcMsg'') ''Cmd'')) (Const NAKC_Nakc)) (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 c1: "((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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 (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) 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 (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))"
have "?P1 s"
proof(cut_tac a1 a2 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_PI_Local_GetX_PutX_HeadVld__part__1Vsinv__115:
assumes a1: "(r=n_PI_Local_GetX_PutX_HeadVld__part__1 N )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__115 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__115 p__Inv4" apply fastforce done
have "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) s))\<or>((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) s))" by auto
moreover {
assume c1: "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) (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'') ''NakcMsg'') ''Cmd'')) (Const NAKC_Nakc)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false))) s))"
have "?P3 s"
apply (cut_tac a1 a2 c1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''NakcMsg'') ''Cmd'')) (Const NAKC_Nakc)) (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 c1: "((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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 (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadPtr'')) (Const (index p__Inv4))))) 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'') ''Dir'') ''ShrVld'')) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) 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 (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true))) (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeHeadPtr'')) (Const false)))) 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_Nak_ClearVsinv__115:
assumes a1: "(r=n_NI_Nak_Clear )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__115 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__115 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__115:
assumes a1: "(r=n_NI_ShWb N )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__115 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__115 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'') ''ShWbMsg'') ''Cmd'')) (Const SHWB_ShWb)) (eqn (IVar (Field (Field (Ident ''Sta'') ''NakcMsg'') ''Cmd'')) (Const NAKC_Nakc))))" 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 (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true)) (eqn (IVar (Field (Field (Ident ''Sta'') ''NakcMsg'') ''Cmd'')) (Const NAKC_Nakc))))" 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__115:
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__115 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_GetX_PutX_HomeVsinv__115:
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__115 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_GetVsinv__115:
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__115 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__115:
assumes a1: "r=n_PI_Local_GetX_PutX__part__0 " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__115 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_WbVsinv__115:
assumes a1: "r=n_NI_Wb " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__115 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_StoreVsinv__115:
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__115 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__115:
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__115 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__115:
assumes a1: "r=n_PI_Local_GetX_GetX__part__1 " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__115 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__115:
assumes a1: "r=n_PI_Local_GetX_GetX__part__0 " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__115 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_ReplaceVsinv__115:
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__115 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_Store_HomeVsinv__115:
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__115 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_ReplaceVsinv__115:
assumes a1: "r=n_PI_Local_Replace " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__115 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__115:
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__115 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__115:
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__115 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__115:
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__115 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__115:
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__115 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_PutXVsinv__115:
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__115 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__115:
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__115 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvVsinv__115:
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__115 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_PutXVsinv__115:
assumes a1: "r=n_PI_Local_PutX " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__115 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__115:
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__115 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__115:
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__115 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_Get_PutVsinv__115:
assumes a1: "r=n_PI_Local_Get_Put " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__115 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_PutXAcksDoneVsinv__115:
assumes a1: "r=n_NI_Local_PutXAcksDone " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__115 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_NakVsinv__115:
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__115 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_GetXVsinv__115:
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__115 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__115:
assumes a1: "r=n_PI_Local_GetX_PutX__part__1 " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__115 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_PutXVsinv__115:
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__115 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_PutVsinv__115:
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__115 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_PutVsinv__115:
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__115 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__115:
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__115 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Replace_HomeVsinv__115:
assumes a1: "r=n_NI_Replace_Home " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__115 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_GetX_PutXVsinv__115:
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__115 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_PutVsinv__115:
assumes a1: "r=n_NI_Local_Put " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__115 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__115:
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__115 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__115:
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__115 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_Get_GetVsinv__115:
assumes a1: "r=n_PI_Local_Get_Get " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__115 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_Get_PutVsinv__115:
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__115 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Nak_HomeVsinv__115:
assumes a1: "r=n_NI_Nak_Home " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__115 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_FAckVsinv__115:
assumes a1: "r=n_NI_FAck " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__115 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
end
|
# Welcome to Session 01
This is a [Google Colaboratory](https://colab.research.google.com/notebooks/welcome.ipynb) notebook file. Python programs are run directly in the browser—a great way to learn and use TensorFlow. To follow this tutorial, run the notebook in Google Colab by clicking the button at the top of this page.
1. In Colab, connect to a Python runtime: At the top-right of the menu bar, select *CONNECT*.
2. Run all the notebook code cells: Select *Runtime* > *Run all*.
```python
#@title ## Mounting Gdrive
USE_G_COLAB = True #@param {type:"boolean"}
if USE_G_COLAB:
from google.colab import drive
drive.mount('/content/drive', force_remount=True)
```
Mounted at /content/drive
```python
#@title ## Project Root
root_dir = ''
if USE_G_COLAB:
root_dir = '/content/drive/My Drive/workshops/2019_07_21/sessions_01/' #@param {type:"string"}
```
```python
#@title ## Installing requried packages
#@markdown ---
#@markdown - [TensorFlow 2.0-beta](https://www.tensorflow.org/install/gpu)
#@markdown - [Watermark](https://github.com/rasbt/watermark)
!pip install -q tensorflow-gpu==2.0.0-beta1
!pip install -qU watermark
```
```python
#@title ## Custom Matplotlib Style
mpl_style = "https://gist.githubusercontent.com/m3hrdadfi/af8aca01094afb7d3e5b46de9ad8d509/raw/871ec5d721a3b438c3c896718ea4aafc91ea9744/gadfly.mplstyle" #@param {type:"string"}
!wget -q $mpl_style -O /root/.config/matplotlib/matplotlibrc
```
```python
#@title ## General Paramas
#@markdown > A random seed is a number used to initialize a pseudorandom number generator. For a seed to be used in a pseudorandom number generator, it does not need to be random
RANDOM_SEED = 141 #@param {type:"integer"}
```
# Overview
$z_2 = XW_1$
$a_2 = f(z_2)$
$z_3 = a_2W_2$
$\hat{y} = softmax(z_3)$ # classification
*where*:
* $X$ = inputs | $\in \mathbb{R}^{NXD}$ ($D$ is the number of features)
* $W_1$ = 1st layer weights | $\in \mathbb{R}^{DXH}$ ($H$ is the number of hidden units in layer 1)
* $z_2$ = outputs from first layer's weights $\in \mathbb{R}^{NXH}$
* $f$ = non-linear activation function
* $a_2$ = activation applied first layer's outputs | $\in \mathbb{R}^{NXH}$
* $W_2$ = 2nd layer weights | $\in \mathbb{R}^{HXC}$ ($C$ is the number of classes)
* $\hat{y}$ = prediction | $\in \mathbb{R}^{NXC}$ ($N$ is the number of samples)
This is a simple two-layer MLP.
* **Objective:** Predict the probability of class $y$ given the inputs $X$. Non-linearity is introduced to model the complex, non-linear data.
* **Advantages:**
* Can model non-linear patterns in the data really well.
* **Disadvantages:**
* Overfits easily.
* Computationally intensive as network increases in size.
* Not easily interpretable.
* **Miscellaneous:** Future neural network architectures that we'll see use the MLP as a modular unit for feed forward operations (affine transformation (XW) followed by a non-linear operation).
## 7 Common Nonlinear Activation Functions and How to Choose an Activation Function
#### SIGMOID / LOGISTIC
*ADVANTAGES*
- Smooth gradient, preventing “jumps” in output values.
- Output values bound between 0 and 1, normalizing the output of each neuron.
- Clear predictions—For X above 2 or below -2, tends to bring the Y value (the prediction) to the edge of the curve, very close to 1 or 0. This enables clear predictions.
*DISADVANTAGES*
- Vanishing gradient—for very high or very low values of X, there is almost no change to the prediction, causing a vanishing gradient problem. This can result in the network refusing to learn further, or being too slow to reach an accurate prediction.
- Outputs not zero centered.
- Computationally expensive
<p align="center">
</p>
#### TANH / HYPERBOLIC TANGENT
*ADVANTAGES*
- Zero centered—making it easier to model inputs that have strongly negative, neutral, and strongly positive values.
- Otherwise like the Sigmoid function.
*DISADVANTAGES*
- Like the Sigmoid function
<p align="center">
</p>
#### RELU (RECTIFIED LINEAR UNIT)
*ADVANTAGES*
- Computationally efficient—allows the network to converge very quickly
- Non-linear—although it looks like a linear function, ReLU has a derivative function and allows for backpropagation.
*DISADVANTAGES*
- The Dying ReLU problem—when inputs approach zero, or are negative, the gradient of the function becomes zero, the network cannot perform backpropagation and cannot learn.
- Like the Sigmoid function
<p align="center">
</p>
#### LEAKY RELU
*ADVANTAGES*
- Prevents dying ReLU problem—this variation of ReLU has a small positive slope in the negative area, so it does enable backpropagation, even for negative input values
Otherwise like ReLU
*DISADVANTAGES*
Results not consistent—leaky ReLU does not provide consistent predictions for negative input values.
<p align="center">
</p>
#### PARAMETRIC RELU
*ADVANTAGES*
- Allows the negative slope to be learned—unlike leaky ReLU, this function provides the slope of the negative part of the function as an argument. It is, therefore, possible to perform backpropagation and learn the most appropriate value of α.
Otherwise like ReLU
*DISADVANTAGES*
May perform differently for different problems.
<p align="center">
$ f(x) = max( \alpha x,x)$
</p>
#### SOFTMAX
*ADVANTAGES*
- Able to handle multiple classes only one class in other activation functions—normalizes the outputs for each class between 0 and 1, and divides by their sum, giving the probability of the input value being in a specific class.
- Useful for output neurons—typically Softmax is used only for the output layer, for neural networks that need to classify inputs into multiple categories.
<p align="center">
$ \frac{ e^{ z_{j} } }{ \sum_{k=1}^c e^{ z_{k} } } $
</p>
#### SWISH
Swish is a new, self-gated activation function discovered by researchers at Google. According to their paper, it performs better than ReLU with a similar level of computational efficiency. In experiments on ImageNet with identical models running ReLU and Swish, the new function achieved top -1 classification accuracy 0.6-0.9% higher.
<p align="center">
</p>
# Training
*Steps*:
1. Randomly initialize the model's weights $W$ (we'll cover more effective initalization strategies in future lessons).
2. Feed inputs $X$ into the model to do the forward pass and receive the probabilities.
3. Compare the predictions $\hat{y}$ (ex. [0.3, 0.3, 0.4]]) with the actual target values $y$ (ex. class 2 would look like [0, 0, 1]) with the objective (cost) function to determine loss $J$. A common objective function for classification tasks is cross-entropy loss.
* $z_2 = XW_1$
* $a_2 = max(0, z_2)$ # ReLU activation
* $z_3 = a_2W_2$
* $\hat{y} = softmax(z_3)$
* $J(\theta) = - \sum_i y_i ln (\hat{y_i}) $
4. Calculate the gradient of loss $J(\theta)$ w.r.t to the model weights.
* $ \frac{\partial{J}}{\partial{W_{2j}}} = a_2\hat{y}, \frac{\partial{J}}{\partial{W_{2y}}} = a_2(\hat{y}-1) $
* $ \frac{\partial{J}}{\partial{W_1}} = \frac{\partial{J}}{\partial{\hat{y}}} \frac{\partial{\hat{y}}}{\partial{a_2}} \frac{\partial{a_2}}{\partial{z_2}} \frac{\partial{z_2}}{\partial{W_1}} = W_2(\partial{scores})(\partial{ReLU})X $
5. Apply backpropagation to update the weights $W$ using gradient descent. The updates will penalize the probabiltiy for the incorrect classes (j) and encourage a higher probability for the correct class (y).
* $W_i = W_i - \alpha\frac{\partial{J}}{\partial{W_i}}$
6. Repeat steps 2 - 4 until model performs well.
# Terminologies
## Neural Network Learning as Optimization
A deep learning neural network learns to map a set of inputs to a set of outputs from training data.
We cannot calculate the perfect weights for a neural network; there are too many unknowns. Instead, the problem of learning is cast as a search or optimization problem and an algorithm is used to navigate the space of possible sets of weights the model may use in order to make good or good enough predictions.
Typically, a neural network model is trained using the stochastic gradient descent optimization algorithm and weights are updated using the backpropagation of error algorithm.
The “gradient” in gradient descent refers to an error gradient. The model with a given set of weights is used to make predictions and the error for those predictions is calculated.
The gradient descent algorithm seeks to change the weights so that the next evaluation reduces the error, meaning the optimization algorithm is navigating down the gradient (or slope) of error.
Now that we know that training neural nets solves an optimization problem, we can look at how the error of a given set of weights is calculated.
## What Is a Loss Function and Loss?
In the context of an optimization algorithm, the function used to evaluate a candidate solution (i.e. a set of weights) is referred to as the objective function.
We may seek to maximize or minimize the objective function, meaning that we are searching for a candidate solution that has the highest or lowest score respectively.
Typically, with neural networks, we seek to minimize the error. As such, the objective function is often referred to as a cost function or a loss function and the value calculated by the loss function is referred to as simply “loss.”
The cost or loss function has an important job in that it must faithfully distill all aspects of the model down into a single number in such a way that improvements in that number are a sign of a better model.
We will review best practice or default values for each problem type with regard to the output layer and loss function.
## Regression Problem
A problem where you predict a real-value quantity.
Output Layer Configuration: One node with a linear activation unit.
Loss Function: Mean Squared Error (MSE).
## Binary Classification Problem
A problem where you classify an example as belonging to one of two classes.
The problem is framed as predicting the likelihood of an example belonging to class one, e.g. the class that you assign the integer value 1, whereas the other class is assigned the value 0.
Output Layer Configuration: One node with a sigmoid activation unit.
Loss Function: Cross-Entropy, also referred to as Logarithmic loss.
## Multi-Class Classification Problem
A problem where you classify an example as belonging to one of more than two classes.
The problem is framed as predicting the likelihood of an example belonging to each class.
Output Layer Configuration: One node for each class using the softmax activation function.
Loss Function: Cross-Entropy, also referred to as Logarithmic loss.
## How to Implement Loss Functions
In order to make the loss functions concrete, this section explains how each of the main types of loss function works.
## Mean Squared Error Loss
Mean Squared Error loss, or MSE for short, is calculated as the average of the squared differences between the predicted and actual values.
The result is always positive regardless of the sign of the predicted and actual values and a perfect value is 0.0. The loss value is minimized, although it can be used in a maximization optimization process by making the score negative.
## Cross-Entropy Loss (or Log Loss)
Cross-entropy loss is often simply referred to as “cross-entropy,” “logarithmic loss,” “logistic loss,” or “log loss” for short.
Each predicted probability is compared to the actual class output value (0 or 1) and a score is calculated that penalizes the probability based on the distance from the expected value. The penalty is logarithmic, offering a small score for small differences (0.1 or 0.2) and enormous score for a large difference (0.9 or 1.0).
Cross-entropy loss is minimized, where smaller values represent a better model than larger values. A model that predicts perfect probabilities has a cross entropy or log loss of 0.0.
Cross-entropy for a binary or two class prediction problem is actually calculated as the average cross entropy across all examples.
## An overview of gradient descent optimization algorithms
Gradient descent is one of the most popular algorithms to perform optimization and by far the most common way to optimize neural networks. At the same time, every state-of-the-art Deep Learning library contains implementations of various algorithms to optimize gradient descent. These algorithms, however, are often used as black-box optimizers, as practical explanations of their strengths and weaknesses are hard to come by.
## Gradient descent variants
There are three variants of gradient descent, which differ in how much data we use to compute the gradient of the objective function. Depending on the amount of data, we make a trade-off between the accuracy of the parameter update and the time it takes to perform an update.
## Batch gradient descent
Vanilla gradient descent, aka batch gradient descent, computes the gradient of the cost function w.r.t. to the parameters θ for the entire training dataset:
<p align="center">
$ \theta = \theta - \eta \nabla _{ \theta } J( \theta )$
</p>
We then update our parameters in the opposite direction of the gradients with the learning rate determining how big of an update we perform. Batch gradient descent is guaranteed to converge to the global minimum for convex error surfaces and to a local minimum for non-convex surfaces.
As we need to calculate the gradients for the whole dataset to perform just one update, batch gradient descent can be very slow and is intractable for datasets that don't fit in memory. Batch gradient descent also doesn't allow us to update our model online, i.e. with new examples on-the-fly.
## Stochastic gradient descent
Stochastic gradient descent (SGD) in contrast performs a parameter update for each training example x(i) and label y(i):
<p align="center">
$\theta = \theta - \eta \nabla _{ \theta } J( \theta; x^{i}; y^{i})$
</p>
Batch gradient descent performs redundant computations for large datasets, as it recomputes gradients for similar examples before each parameter update. SGD does away with this redundancy by performing one update at a time. It is therefore usually much faster and can also be used to learn online.
While batch gradient descent converges to the minimum of the basin the parameters are placed in, SGD's fluctuation, on the one hand, enables it to jump to new and potentially better local minima. On the other hand, this ultimately complicates convergence to the exact minimum, as SGD will keep overshooting. However, it has been shown that when we slowly decrease the learning rate, SGD shows the same convergence behaviour as batch gradient descent, almost certainly converging to a local or the global minimum for non-convex and convex optimization respectively.
## Mini-batch gradient descent
Mini-batch gradient descent finally takes the best of both worlds and performs an update for every mini-batch of n training examples:
<p align="center">
$\theta = \theta - \eta \nabla _{ \theta } J( \theta; x^{i:i+n}; y^{i:i+n})$
</p>
This way, it a) reduces the variance of the parameter updates, which can lead to more stable convergence; and b) can make use of highly optimized matrix optimizations common to state-of-the-art deep learning libraries that make computing the gradient w.r.t. a mini-batch very efficient. Common mini-batch sizes range between 50 and 256, but can vary for different applications. Mini-batch gradient descent is typically the algorithm of choice when training a neural network and the term SGD usually is employed also when mini-batches are used.
## Gradient descent optimization algorithms
- Momentum
- Nesterov accelerated gradient (NAG)
- Adagrad
- Adadelta
- RMSprop
- Adam
- AdaMax
- Nadam
- AMSGrad
<p align="center">
<br/>
</p>
## Which optimizer to use?
So, which optimizer should you now use? If your input data is sparse, then you likely achieve the best results using one of the adaptive learning-rate methods. An additional benefit is that you won't need to tune the learning rate but likely achieve the best results with the default value.
In summary, RMSprop is an extension of Adagrad that deals with its radically diminishing learning rates. It is identical to Adadelta, except that Adadelta uses the RMS of parameter updates in the numinator update rule. Adam, finally, adds bias-correction and momentum to RMSprop. Insofar, RMSprop, Adadelta, and Adam are very similar algorithms that do well in similar circumstances. It is shown that its bias-correction helps Adam slightly outperform RMSprop towards the end of optimization as gradients become sparser. Insofar, Adam might be the best overall choice.
## Hyperparameters
Model optimization is one of the toughest challenges in the implementation of machine learning solutions. Entire branches of machine learning and deep learning theory have been dedicated to the optimization of models. Typically, we think about model optimization as a process of regularly modifying the code of the model in order to minimize the testing error. However, deep learning optimization often entails fine tuning elements that live outside the model but that can heavily influence its behavior. Deep learning often refers to those hidden elements as hyperparameters as they are one of the most critical components of any machine learning application.
#### Some Examples of Hyperparameters
The number and diversity of hyperparameters in machine learning algorithms is very specific to each model. However, there some classic hyperparameters that we should always keep our eyes on and that should help you think about this aspect of machine learning solutions:
· Learning Rate: The mother of all hyperparameters, the learning rate quantifies the learning progress of a model in a way that can be used to optimize its capacity.
· Number of Hidden Units: A classic hyperparameter in deep learning algorithms, the number of hidden units is key to regulate the representational capacity of a model.
· Convolution Kernel Width: In convolutional Neural Networks(CNNs), the Kernel Width influences the number of parameters in a model which, in turns, influences its capacity.
## Metrics to Evaluate your Machine Learning Algorithm
Evaluating your machine learning algorithm is an essential part of any project. Your model may give you satisfying results when evaluated using a metric say accuracy_score but may give poor results when evaluated against other metrics such as logarithmic_loss or any other such metric. Most of the times we use classification accuracy to measure the performance of our model, however it is not enough to truly judge our model. In this post, we will cover different types of evaluation metrics available.
## Classification Accuracy
Classification Accuracy is what we usually mean, when we use the term accuracy. It is the ratio of number of correct predictions to the total number of input samples.
<p align="center">
$Accuracy = \frac{Number of Correct predictions}{Total Number of Predictions made}$
</p>
It works well only if there are equal number of samples belonging to each class.
For example, consider that there are 98% samples of class A and 2% samples of class B in our training set. Then our model can easily get 98% training accuracy by simply predicting every training sample belonging to class A.
When the same model is tested on a test set with 60% samples of class A and 40% samples of class B, then the test accuracy would drop down to 60%. Classification Accuracy is great, but gives us the false sense of achieving high accuracy.
The real problem arises, when the cost of misclassification of the minor class samples are very high. If we deal with a rare but fatal disease, the cost of failing to diagnose the disease of a sick person is much higher than the cost of sending a healthy person to more tests.
## Confusion Matrix
Confusion Matrix as the name suggests gives us a matrix as output and describes the complete performance of the model.
Lets assume we have a binary classification problem. We have some samples belonging to two classes : YES or NO. Also, we have our own classifier which predicts a class for a given input sample. On testing our model on 165 samples ,we get the following result.
<p align="center">
$LogLoss = - \frac{1}{n} \sum\limits_{i=1}^n [y_i \cdot log_e(\hat{y_i}) + (1-y_i) \cdot log_e(1-\hat{y_i}) ]$
</p>
where,
y_ij, indicates whether sample i belongs to class j or not
p_ij, indicates the probability of sample i belonging to class j
Log Loss has no upper bound and it exists on the range Log Loss nearer to 0 indicates higher accuracy, whereas if the Log Loss is away from 0 then it indicates lower accuracy.
In general, minimising Log Loss gives greater accuracy for the classifier.
| n=165 | Predicted: NO | Predicted: YES |
|---|---|---|
| Actual: NO | 50 | 10 |
| Actual: YES | 5 | 100 |
There are 4 important terms :
- True Positives : The cases in which we predicted YES and the actual output was also YES.
- True Negatives : The cases in which we predicted NO and the actual output was NO.
- False Positives : The cases in which we predicted YES and the actual output was NO.
- False Negatives : The cases in which we predicted NO and the actual output was YES.
Accuracy for the matrix can be calculated by taking average of the values lying across the “main diagonal” i.e
<p align="center">
$Accuracy = \frac{TruePositive+ TrueNegative}{Total Number of Samples}$
<br />
$Accuracy = \frac{100+50}{165} = 0.91$
</p>
Confusion Matrix forms the basis for the other types of metrics.
## Area Under Curve
Area Under Curve(AUC) is one of the most widely used metrics for evaluation. It is used for binary classification problem. AUC of a classifier is equal to the probability that the classifier will rank a randomly chosen positive example higher than a randomly chosen negative example. Before defining AUC, let us understand two basic terms :
- True Positive Rate (Sensitivity) : True Positive Rate is defined as TP/ (FN+TP). True Positive Rate corresponds to the proportion of positive data points that are correctly considered as positive, with respect to all positive data points.
<p align="center">
$TruePositiveRate = \frac{TruePositive}{FalseNegative+TruePositive}$
</p>
- False Positive Rate (Specificity) : False Positive Rate is defined as FP / (FP+TN). False Positive Rate corresponds to the proportion of negative data points that are mistakenly considered as positive, with respect to all negative data points.
<p align="center">
$FalsePositiveRate = \frac{FalsePositive}{TrueNegative+FalsePositive}$
</p>
False Positive Rate and True Positive Rate both have values in the range [0, 1]. FPR and TPR bot hare computed at threshold values such as (0.00, 0.02, 0.04, …., 1.00) and a graph is drawn. AUC is the area under the curve of plot False Positive Rate vs True Positive Rate at different points in [0, 1].
<p align="center">
</p>
As evident, AUC has a range of [0, 1]. The greater the value, the better is the performance of our model.
## F1 Score
F1 Score is used to measure a test’s accuracy
F1 Score is the Harmonic Mean between precision and recall. The range for F1 Score is [0, 1]. It tells you how precise your classifier is (how many instances it classifies correctly), as well as how robust it is (it does not miss a significant number of instances).
High precision but lower recall, gives you an extremely accurate, but it then misses a large number of instances that are difficult to classify. The greater the F1 Score, the better is the performance of our model. Mathematically, it can be expressed as :
<p align="center">
$F1 = 2*\frac{1}{\frac{1}{precision}+\frac{1}{recall}}$
</p>
- Precision : It is the number of correct positive results divided by the number of positive results predicted by the classifier.
<p align="center">
$Precision = 2*\frac{TruePositive}{TruePositive+FalsePositive}$
</p>
Recall : It is the number of correct positive results divided by the number of all relevant samples (all samples that should have been identified as positive).
<p align="center">
$Recall = 2*\frac{TruePositive}{TruePositive+FalsePositive}$
</p>
# Preparation
```python
#@title ## Import requried packages
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, confusion_matrix
import matplotlib as mpl
import matplotlib.pyplot as plt
import itertools
from datetime import datetime
from tqdm import tqdm
import os
%matplotlib inline
mpl.rc_file(mpl.matplotlib_fname())
```
```python
%reload_ext watermark
%watermark -m -n -p tensorflow,numpy,matplotlib,sklearn -g
```
Sun Jul 21 2019
tensorflow 2.0.0-beta1
numpy 1.16.4
matplotlib 3.0.3
sklearn 0.21.2
compiler : GCC 8.0.1 20180414 (experimental) [trunk revision 259383
system : Linux
release : 4.14.79+
machine : x86_64
processor : x86_64
CPU cores : 2
interpreter: 64bit
Git hash :
```python
#@title ## Random seed
np.random.seed(RANDOM_SEED)
```
# Data
We're going to first generate some non-linear data for a classification task.
**A spiral**: is a curve which emanates from a point, moving farther away as it revolves around the point.
\begin{align}
Spiral =\begin{cases} X_{1\theta} = r_{\theta} \cos(\theta) \\X_{2\theta} = r_{\theta} \sin(\theta)\end{cases}
\end{align}
```python
#@title ## Generate non-linear data [Spiral](https://en.wikipedia.org/wiki/Spiral)
def generate_data(num_samples, dimensions, num_classes):
""" Generate non-linear dataset.
Args:
num_samples (int): number of samples which we want to produce.
dimensions (int): the dimension of the data which we plan to produce ex. 2d.
num_classes (int): number of classes which the samples are going to generate ex. 2#.
Examples:
>>> x, y = generate_data(2, 2, 2)
(array([[ 0. , 0. ],
[-0.712528 , -0.70164368],
[-0. , -0. ],
[ 0.90006129, -0.43576333]]), array([0, 0, 1, 1], dtype=uint8))
Returns:
x (ndarray): a numpy array in a shape like this (num_samples, dimensions).
y (ndarray): a numpy array in a shape like this (num_samples, num_classes).
"""
x_origin = np.zeros((num_samples * num_classes, dimensions))
y = np.zeros(num_samples * num_classes, dtype='uint8')
for i in tqdm(range(num_classes), position=0):
idx = range(num_samples * i, num_samples * (i + 1))
radius = np.linspace(0.0, 1, num_samples)
theta = np.linspace(i * 4, (i + 1) * 4, num_samples) + np.random.randn(num_samples) * 0.2
x_origin[idx] = np.c_[radius * np.sin(theta), radius * np.cos(theta)]
y[idx] = i
x = np.hstack([x_origin])
return x, y
```
```python
#@title ## Generate x, y
num_samples = 500 #@param {type:"integer"}
dimensions = 2 #@param {type:"integer"}
num_classes = 3 #@param {type:"integer"}
x, y = generate_data(num_samples, dimensions, num_classes)
print()
print('x: %s' % str(x.shape))
print('y: %s' % str(y.shape))
```
100%|██████████| 3/3 [00:00<00:00, 1181.49it/s]
x: (1500, 2)
y: (1500,)
```python
#@title ## Visualize data
xfig = 12.0 #@param {type:"number"}
yfig = 8.0 #@param {type:"number"}
plt.figure(figsize=(xfig, yfig))
plt.title('Generated non-linear data')
plt.scatter(x[:, 0], x[:, 1], c=y)
plt.show()
```
## One-hot Encoding
Consider an array of 5 labels out of a set of 3 classes {0, 1, 2}:
```python
> labels
array([0, 2, 1, 2, 0])
```
**`to_categorical`** converts this into a matrix with as many
columns as there are classes. The number of rows
stays the same.
```python
> to_categorical(labels)
array([[ 1., 0., 0.],
[ 0., 0., 1.],
[ 0., 1., 0.],
[ 0., 0., 1.],
[ 1., 0., 0.]], dtype=float32)
```
---
**to_categorical**
```
tf.keras.utils.to_categorical(y, num_classes=None, dtype='float32')
```
Converts a class vector (integers) to binary class matrix.
**Arguments:**
- **`y`**: class vector to be converted into a matrix (integers from 0 to num_classes).
- **`num_classes`**: total number of classes.
- **`dtype`**: The data type expected by the input, as a string (float32, float64, int32...)
```python
#@title ## Preprocessing
```
# Linear Model
Before we get to our neural network, we're going to implement a linear model (logistic regression). We want to see why linear models won't suffice for our dataset.
```python
#@title ## Build linear model [Logistic Model](https://en.wikipedia.org/wiki/Multinomial_logistic_regression)
def build_linear(n_units, n_features):
model = None
return model
```
```python
#@title ## Create linear model
```
```python
#@title ## Fit linear model.
```
```python
#@title ## Evaluating
```
```python
#@title ## Plotting
```
```python
#@title ## Multiclass decision boundary
def plot_mc_decision_boundary(model, x, y, steps=1000):
""" Plot multiclass decision boundary,
Args:
model (keras.Model): a keras model.
x (ndarray): a numpy array.
y (ndarray): a numpy array.
steps (integer): number of linear spaces.
Returns:
None
"""
x_min, x_max = x[:, 0].min() - 0.1, x[:, 0].max() + 0.1
y_min, y_max = x[:, 1].min() - 0.1, x[:, 1].max() + 0.1
x_span = np.linspace(x_min, x_max, steps)
y_span = np.linspace(y_min, y_max, steps)
xx, yy = np.meshgrid(x_span, y_span)
y_pred = model.predict(np.c_[xx.ravel(), yy.ravel()])
y_pred = np.argmax(y_pred, axis=1)
y_pred = y_pred.reshape(xx.shape)
plt.contourf(xx, yy, y_pred, alpha=0.5)
plt.scatter(x[:, 0], x[:, 1], c=y)
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
return None
```
```python
#@title ## Visualize the decision boundary
```
```python
#@title ## Plot confusion matrix
def plot_confusion_matrix(cm, classes):
""" Plot confusion matrix
Args:
cm (ndarray): the input of confusion matrix.
classes (integer): number of classes.
Returns:
None
"""
cmap=plt.cm.Blues
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title("Confusion Matrix")
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
plt.grid(False)
fmt = 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.tight_layout()
return None
```
## Classification Report
`sklearn.metrics.classification_report`
Build a text report showing the main classification metrics
**Params:**
- `y_true` : 1d array-like, or label indicator array / sparse matrix
- `y_pred` : 1d array-like, or label indicator array / sparse matrix
**Output:**
```bash
precision recall f1-score support
1 1.00 0.67 0.80 3
2 0.00 0.00 0.00 0
3 0.00 0.00 0.00 0
micro avg 1.00 0.67 0.80 3
macro avg 0.33 0.22 0.27 3
weighted avg 1.00 0.67 0.80 3
```
```python
#@title ## Confusion matrix
```
# Non-linear Model
Now let's see how the MLP performs on the data. Note that the only difference is the addition of the non-linear activation function (we use $ReLU$ which is just $max(0, z))$.
```python
#@title ## Build non-linear model [MLP Model](https://en.wikipedia.org/wiki/Multilayer_perceptron)
def build_non_linear(n_classes, n_units, n_features):
model = None
return model
```
```python
#@title ## Create non-linear model
```
```python
#@title ## Fit non-linear model.
```
```python
#@title ## Evaluating
```
```python
#@title ## Plotting
```
```python
#@title ## Visualize the decision boundary
```
```python
#@title ## Confusion matrix
```
# Overfitting
Though neural networks are great at capturing non-linear relationships they are highly susceptible to overfitting to the training data and failing to generalize on test data. Just take a look at the example below where we generate completely random data and are able to fit a model with [$2*N*C + D$](https://arxiv.org/abs/1611.03530) hidden units. The training performance is great but the overfitting leads to very poor test performance. We'll be covering strategies to tackle overfitting in future lessons.
Let me define overfitting more formally. Overfitting refers to a model that models the “training data” too well. Overfitting happens when a model learns the detail and noise in the training data to the extent that it negatively impacts the performance of the model on new data.
# How do you know your NN is overfitting?
In practice, detecting that our model is overfitting is difficult. It’s not uncommon that our trained model is already in production and then we start to realize that something is wrong. In fact, it is only by confronting new data that you can make sure that everything is working properly. However, during the training we should try to reproduce the real conditions as much as possible. For this reason, it is good practice to divide our dataset into three parts - training set, dev set (also known as cross-validation or hold-out) and test set. Our model learns by seeing only the first of these parts. Hold-out is used to track our progress and draw conclusions to optimise the model. While, we use a test set at the end of the training process to evaluate the performance of our model. Using completely new data allows us to get an unbiased opinion on how well our algorithm works.
It is very important to make sure that your cross-validation and test set come from the same distribution as well as that they accurately reflect data that we expect to receive in the future. Only then we can be sure that the decisions we make during the learning process bring us closer to a better solution. I know what you are thinking about… “How should I divide my dataset?” Until recently, one of the most frequently recommended splits was 60/20/20, but in the era of big data, when our dataset can count millions of entries, those fixed proportions are no longer appropriate. In short, everything depends on the size of the dataset we work with. If we have millions of entries at our disposal, perhaps it would be better idea to divide them in 98/1/1 ratio. Our dev and test sets should be simply large enough to give us high confidence in the performance of our model.
<p align="center">
</p>
# Bias and Variance
To give us a better understanding of this some how complex issue, we will use a simple example, that hopefully allow us to develop a valuable intuition. Our dataset consisting of two classes of points, located in a two-dimensional space.
<p align="center">
</p>
The first model in the top right corner is very simple and therefore has a high bias, i.e. it is not able to find all significant links between features and result. This is understandable - our dataset has a lot of noise in it, and therefore simple linear regression, is not able to deal with it effectively. Neural networks performed much better, but the first one (shown in the lower left corner) fitted into the data too closely, which made it work significantly worse on the hold-out set. This means that it has a high variance - it fits into the noise and not into the intended output. This undesirable effect was mitigated, in the last model, by the use of regularisation.
<p align="center">
</p>
# Ways to prevent overfitting
### L1 and L2 Regularizations
One of the first methods we should try when we need to reduce overfitting is regularisation. It involves adding an extra element to the loss function, which punishes our model for being too complex or, in simple words, for using too high values in the weight matrix. This way we try to limit its flexibility, but also encourage it to build solutions based on multiple features. Two popular versions of this method are L1 - Least Absolute Deviations (LAD) and L2 - Least Square Errors (LS). Equations describing these regularisations are given below.
In most cases the use of L1 is preferable, because it reduces the weight values of less important features to zero, very often eliminating them completely from the calculations. In a way, it is a built-in mechanism for automatic featur selection. Moreover, L2 does not perform very well on datasets with a large number of outliers. The use of value squares results in the model minimizing the impact of outliers at the expense of more popular examples.
<p align="center">
$$
\begin{array}{rlrl}{J_{L 1}(W, b)} & {=\frac{1}{m} \sum_{i=1}^{m} L\left(\hat{y}^{(i)}, y^{(i)}\right)+\lambda\|w\|_{1}} & {\|w\|_{1}} & {=\sum_{j=1}^{n_{x}}\left|w_{j}\right|} \\ {J_{L 2}(W, b)} & {=\frac{1}{m} \sum_{i=1}^{m} L\left(\hat{y}^{(i)}, y^{(i)}\right)+\lambda\|w\|_{2}} & {\|w\|_{2}} & {=\sum_{j=1}^{n_{x}} w_{j}^{2}}\end{array}
$$
</p>
Increasing the λ value also increases the regularisation effect. Models with a very low λ coefficient value are very “turbulent”.
# Dropout
Another very popular method of regularization of neural networks is dropout. This idea is actually very simple - every unit of our neural network (except those belonging to the output layer) is given the probability p of being temporarily ignored in calculations. Hyper parameter p is called dropout rate and very often its default value is set to 0.5. Then, in each iteration, we randomly select the neurons that we drop according to the assigned probability. As a result, each time we work with a smaller neural network. The visualization below shows an example of a neural network subjected to a dropout. We can see how in each iteration random neurons from second and fourth layer are deactivated.
<p align="center">
</p>
# Early Stopping
The graph below shows the change in accuracy values calculated on the test and cross-validation sets during subsequent iterations of learning process. We see right away that the model we get at the end is not the best we could have possibly create. To be honest, it is much worse than what we have had after 150 epochs. Why not interrupt the learning process before the model starts overfitting? This observation inspired one of the popular overfitting reduction method, namely early stopping.
<p align="center">
</p>
```python
#@title ## Generate random x, y
ov_num_samples = 40 #@param {type:"integer"}
ov_dimensions = 2 #@param {type:"integer"}
ov_num_classes = 3 #@param {type:"integer"}
ov_x = np.random.randn(ov_num_samples * ov_num_classes, ov_dimensions)
ov_y = np.array([[i] * ov_num_samples for i in range(ov_num_classes)])
ov_y = ov_y.flatten()
print()
print('x: %s' % str(ov_x.shape))
print('y: %s' % str(ov_y.shape))
```
x: (120, 2)
y: (120,)
```python
#@title ## Preprocessing
```
```python
#@title ## Create non-linear model
```
```python
#@title ## Fit overfie model.
```
```python
#@title ## Evaluating
```
```python
#@title ## Plotting
```
```python
#@title ## Visualize the decision boundary
```
```python
#@title ## Confusion matrix
```
# Regularization
```python
#@title ## Build non-linear model [MLP Model](https://en.wikipedia.org/wiki/Multilayer_perceptron)
def build_non_linear_with_regularization(n_classes, n_units, n_features):
model = None
return model
```
```python
#@title ## Create non-linear model
```
```python
#@title ## Fit non-linear model with regularization.
```
```python
#@title ## Evaluating
```
```python
#@title ## Plotting
```
```python
#@title ## Visualize the decision boundary
```
```python
#@title ## Confusion matrix
```
# Dropout
A great technique to overcome overfitting is to increase the size of your data but this isn't always an option. Fortuntely, there are methods like regularization and dropout that can help create a more robust model. We've already seen regularization and we can easily add it in our optimizer to use it in PyTorch.
Dropout is a technique (used only during training) that allows us to zero the outputs of neurons. We do this for p% of the total neurons in each layer and it changes every batch. Dropout prevents units from co-adapting too much to the data and acts as a sampling strategy since we drop a different set of neurons each time.
```python
#@title ## Build non-linear model [MLP Model](https://en.wikipedia.org/wiki/Multilayer_perceptron)
def build_non_linear_with_dropout(n_classes, n_units, n_features):
model = None
return model
```
```python
#@title ## Create non-linear model
```
```python
#@title ## Fit non-linear model with dropout.
```
```python
#@title ## Evaluating
```
```python
#@title ## Plotting
```
```python
#@title ## Visualize the decision boundary
```
```python
#@title ## Confusion matrix
```
# Visualization
```python
#@title ## Build non-linear model [MLP Model](https://en.wikipedia.org/wiki/Multilayer_perceptron)
def build_non_linear_v2(n_classes, n_units, n_features):
model = None
return model
```
```python
#@title ## Create non-linear model
```
```python
#@title # Summary of the model
```
```python
#@title ## Model Arch
```
```python
#@title ## Tensorboard callbacks
```
```python
#@title ## Fit non-linear model.
```
```python
#@title ## Plotting
```
```python
#@title ## Visualize the decision boundary
```
```python
#@title ## Confusion matrix
```
# Tensorboard
```python
# %load_ext tensorboard
```
```python
# %tensorboard --logdir logs/scalars
```
```python
```
|
State Before: R : Type u
S : Type v
inst✝¹ : CommRing R
inst✝ : CommRing S
s t : Set (PrimeSpectrum R)
hs : IsClosed s
ht : IsClosed t
⊢ s ⊂ t ↔ vanishingIdeal t < vanishingIdeal s State After: no goals Tactic: rw [Set.ssubset_def, vanishingIdeal_anti_mono_iff hs, vanishingIdeal_anti_mono_iff ht,
lt_iff_le_not_le]
|
= = Early life and modeling career = =
|
%% LyX 2.1.2 created this file. For more info, see http://www.lyx.org/.
%% Do not edit unless you really know what you are doing.
\documentclass[12pt,oneside,english]{book}
\usepackage[T1]{fontenc}
\usepackage[latin9]{inputenc}
\usepackage[letterpaper]{geometry}
\geometry{verbose,tmargin=1in,bmargin=1.43in,lmargin=1in,rmargin=1in}
\pagestyle{plain}
\usepackage{babel}
\usepackage{url}
\usepackage{amsthm}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{graphicx}
\usepackage{setspace}
\doublespacing
\usepackage[unicode=true,pdfusetitle,
bookmarks=true,bookmarksnumbered=true,bookmarksopen=false,
breaklinks=true,pdfborder={0 0 0},backref=false,colorlinks=false]
{hyperref}
\makeatletter
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LyX specific LaTeX commands.
%% Because html converters don't know tabularnewline
\providecommand{\tabularnewline}{\\}
\@ifundefined{date}{}{\date{}}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% User specified LaTeX commands.
\makeatletter
\renewcommand*\l@chapter{\@dottedtocline{1}{0em}{1.5em}}
\makeatother
\makeatother
\begin{document}
\thispagestyle{empty}
\begin{spacing}{1.15}
\noindent \begin{center}
WASHINGTON UNIVERSITY IN ST. LOUIS\\
Division of Biology and Biomedical Sciences Neurosciences
\par\end{center}
\noindent \begin{center}
\vspace*{\fill}
\par\end{center}
\noindent \begin{center}
Dissertation Examination Committee:\\
Katherine Davidsen, Chair \\
Michael Randolf, Co-Chair \\
Richard Lewis \\
Hillary O\'Connell \\
Jack Taylor
\par\end{center}
\noindent \begin{center}
\vspace*{\fill}
\par\end{center}
\noindent \begin{center}
A Mock Thesis on the Proper Formatting of Dissertations and Theses
for Arts \& Sciences Graduate Students\\
by\\
Paige Turner
\par\end{center}
\noindent \begin{center}
\vspace*{\fill}
\par\end{center}
\noindent \begin{center}
A dissertation presented to the \\
Graduate School of Arts and Sciences\\
of Washington University in \\
partial fulfillment of the \\
requirements for the degree\\
of Doctor of Philosophy
\par\end{center}
\noindent \begin{center}
\vspace*{\fill}
\par\end{center}
\noindent \begin{center}
May 2015\\
St. Louis, Missouri
\par\end{center}
\end{spacing}
\clearpage{}
\pagenumbering{roman}
\thispagestyle{empty}
\vspace*{\fill}
\begin{center}
\copyright ~2015, Paige Turner
\par\end{center}
\vspace*{\fill}
\clearpage{}
\begin{spacing}{1.15}
\renewcommand*{\contentsname}{Table of Contents}
\begin{spacing}{1.15}
\tableofcontents{}
\end{spacing}
\clearpage{}
\phantomsection
\addcontentsline{toc}{chapter}{\numberline{}List of Figures}
\begin{spacing}{1.15}
\listoffigures
\end{spacing}
\clearpage{}
\phantomsection
\addcontentsline{toc}{chapter}{\numberline{}List of Tables}
\begin{spacing}{1.15}
\listoftables
\end{spacing}
\end{spacing}
\clearpage{}
\phantomsection
\addcontentsline{toc}{chapter}{\numberline{}Acknowledgements}
\chapter*{Acknowledgments}
An acknowledgments page must be included in your final dissertation
or thesis. If you wish to include a special dedication you can either
use it to close the acknowledgments page or place it on the page that
immediately follows. The acknowledgments page should be listed in
the table of contents. Place it after the final list used in the document,
and before any dedication, abstract, or epigraph that is included.
It is appropriate to acknowledge sources of academic and financial
support; some fellowships and grants require acknowledgment.
We offer special thanks to the Washington University School of Engineering
for allowing us to use their dissertation and thesis template as a
starting point for the development of this document.
\begin{flushright}
Paige Turner
\par\end{flushright}
\noindent Washington University in St. Louis
\noindent May 2015
\clearpage{}
\vspace*{\fill}
\begin{center}
Dedicated to my family.%
\footnote{If you include a special dedication as shown here be sure to keep
it brief and center it on the page both horizontally and vertically.
Alternatively, you may remove this page altogether, and a special
dedication can be placed as the final paragraph of your acknowledgments
page. Do not include the dedication page in your table of contents.%
}
\par\end{center}
\vspace*{\fill}
\clearpage{}
\phantomsection
\addcontentsline{toc}{chapter}{\numberline{}Abstract}
\noindent \begin{center}
ABSTRACT OF THE DISSERTATION
\par\end{center}
\noindent \begin{center}
A Mock Thesis on the Proper Formatting of Dissertations and Theses\\
for Arts \& Sciences Graduate Students\\
by\\
Paige Turner
\par\end{center}
\noindent \begin{center}
Doctor of Philosophy in Biology and Biomedical Sciences Neurosciences\\
Washington University in St. Louis, 2015\\
Professor Katherine Davidsen, Chair\\
Professor Michael Randolf, Co-Chair
\par\end{center}
After removing these comments, begin typing the body of your abstract
here, double-spaced. Your font should be 12-point (which is the text
of this sample paragraph). No part of the abstract should be bolded.
If this is for your master\textquoteright s degree, be sure to change
all occurrences of the word \textquotedblleft dissertation\textquotedblright{}
to display as \textquotedblleft thesis,\textquotedblright{} and change
\textquotedblleft Doctor of Philosophy\textquotedblright{} or \textquotedblleft Doctor
of Liberal Arts\textquotedblright{} to \textquotedblleft Master of
Arts,\textquotedblright{} \textquotedblleft Master of Liberal Arts,\textquotedblright{}
or \textquotedblleft Master of Fine Arts,\textquotedblright{} whichever
applies. In the abstract heading above, make sure you use the year
your degree is to be officially earned. Be sure to use your full name
as it is recorded in WebSTAC, your dissertation or thesis advisor\textquoteright s
full name(s) wherever appropriate, and the correct title of your degree
whenever referencing it. The title of your degree will not always
be the same as the title of your department or program, so please
check with your departmental administrative assistant and advisor(s)
to be sure you are using the correct degree title. Please note that
an abstract is required for all dissertation submissions in ProQuest.
An abstract is optional for master\textquoteright s thesis submissions.
\clearpage{}
\pagenumbering{arabic}
\chapter{Parts of the Dissertation}
This chapter describes the components of a dissertation or thesis.
You may not have to include all components described here, but you
must follow the prescribed order for the components you do include.
Table \ref{tab:The-following-items} lists the required and optional
components in the order that they should appear. Your manuscript should
include three main parts: the front matter, the body, and the back
matter. Each of these parts is described below.
\begin{table}[h]
\protect\caption{Required and Optional Components\label{tab:The-following-items}}
\begin{centering}
{\scriptsize{}}%
\begin{tabular}{ccccc}
\hline
{\scriptsize{}Major Part} & {\scriptsize{}Thesis Component} & {\scriptsize{}Required} & {\scriptsize{}Optional} & {\scriptsize{}Page Numbering}\tabularnewline
\hline
{\scriptsize{}Front Matter} & {\scriptsize{}Title page} & {\scriptsize{}$\checkmark$} & & {\scriptsize{}counted, not numbered}\tabularnewline
& {\scriptsize{}Copyright page} & & {\scriptsize{}$\checkmark$} & {\scriptsize{}neither counted, nor numbered}\tabularnewline
& {\scriptsize{}Table of Contents} & {\scriptsize{}$\checkmark$} & & {\scriptsize{}begins on a page numbered ii}\tabularnewline
& {\scriptsize{}List of Figures} & & {\scriptsize{}$\checkmark$} & {\scriptsize{}{[}lowercase Roman numerals continue{]}}\tabularnewline
& {\scriptsize{}List of Illustrations} & & {\scriptsize{}$\checkmark$} & {\scriptsize{}{[}lowercase Roman numerals continue{]}}\tabularnewline
& {\scriptsize{}List of Tables} & & {\scriptsize{}$\checkmark$} & {\scriptsize{}{[}lowercase Roman numerals continue{]}}\tabularnewline
& {\scriptsize{}List of Abbreviations} & & {\scriptsize{}$\checkmark$} & {\scriptsize{}{[}lowercase Roman numerals continue{]}}\tabularnewline
& {\scriptsize{}Acknowledgments} & {\scriptsize{}$\checkmark$} & & {\scriptsize{}{[}lowercase Roman numerals continue{]}}\tabularnewline
& {\scriptsize{}Dedication} & & {\scriptsize{}$\checkmark$} & {\scriptsize{}{[}lowercase Roman numerals continue{]}}\tabularnewline
& {\scriptsize{}Abstract page} & & {\scriptsize{}$\checkmark$} & {\scriptsize{}{[}lowercase Roman numerals continue{]}}\tabularnewline
& {\scriptsize{}Preface} & & {\scriptsize{}$\checkmark$} & {\scriptsize{}{[}lowercase Roman numerals continue{]}}\tabularnewline
{\scriptsize{}Body} & {\scriptsize{}Epigraph} & & {\scriptsize{}$\checkmark$} & {\scriptsize{}begins on a page numbered 1}\tabularnewline
& {\scriptsize{}Chapters} & {\scriptsize{}$\checkmark$} & & {\scriptsize{}{[}Arabic numerals begin or continue{]}}\tabularnewline
{\scriptsize{}Back Matter} & {\scriptsize{}References} & {\scriptsize{}$\checkmark$} & & {\scriptsize{}{[}Arabic numerals continue{]}}\tabularnewline
& {\scriptsize{}Appendices} & & {\scriptsize{}$\checkmark$} & {\scriptsize{}{[}Arabic numerals continue{]}}\tabularnewline
& {\scriptsize{}Curriculum Vitae} & & {\scriptsize{}$\checkmark$} & {\scriptsize{}{[}Arabic numerals continue{]}}\tabularnewline
\hline
\end{tabular}
\par\end{centering}{\scriptsize \par}
{\scriptsize{}The above items may be included in your dissertation
or thesis, in the order in which they are listed. Any optional components,
if used, must be included in the table of contents, unless noted below.
Do not include Dedication and Epigraph in the table of contents. There
are two options for the placement of references; they can be listed
at the end of each chapter, or at the end of the document. Do not
put your Social Security Number, birthdate, or birthplace on your
C.V.}
\end{table}
\section{Front Matter}
The front matter includes all material that appears before the beginning
of the body of the text. Number all front matter pages (except the
title page and the optional copyright page) with lowercase roman numerals,
starting with ii, centered just above the bottom margin. Each of the
following sections should begin on a new page.
\subsection{Title Page}
Format the title page so that it is centered vertically and horizontally
on the page with equal amounts of white space from top and bottom
margins. Include a 1 inch margin on all sides. Use a 12-point regular
font. If you are writing a thesis, substitute the word \textquotedblleft thesis\textquotedblright{}
wherever the word \textquotedblleft dissertation\textquotedblright{}
appears in this document; do not include your committee members. The
date on the title page should reflect the month and year the degree
is to be officially earned, and should be one of the following months:
December, May, or August. Do not include a number on the title page.
See Appendix for further details. In most cases your dissertation
title should be in \textquotedblleft Title Case\textquotedblright{}
unless a specific format is required by your discipline. Be certain
to use your own full name (as recorded in WebSTAC).
\subsection{Copyright Page }
It is always suggested that upon completion of the text, the student
add the copyright symbol \copyright ~ with the year and the student\textquoteright s
name on one line, on a page following the title page. Format your
copyright page exactly as it is shown in this template.
Example:
\noindent \begin{center}
\copyright ~ 2015, Paige Turner
\par\end{center}
Once you create a work, it is automatically protected by U.S. copyright
law with you as the author. You do not need to register the copyright
with the U.S. Copyright Office, though doing so provides certain advantages.
More information about copyright registration can be found at \url{http://libguides.wustl.edu/copyright/registration}.
\subsection{Table of Contents }
The words \textquotedblleft Table of Contents\textquotedblright{}
must appear in chapter title style at the top of the page. It must
include the page numbers of all front and back matter elements, unless
otherwise specified. The table of contents must include the page numbers
of all chapters and sections of your dissertation or thesis. In addition,
it may include the page numbers of all subsections. Chapter titles
may be typed in plain or bold font. All titles and headings must be
followed by a page number.
Make certain that any long titles align nicely with the body of text.
Multi-lined chapter titles or section titles should break at a logical
point and align in a manner allowing the titles to be read clearly,
without confusion. Sometimes this will mean forcing a line break at
a logical point and relies on your own good judgment.
\subsection{List of Figures }
If one or more figures are used in the document, there must be a list
of all figures. The list should be spaced at 1.15. Begin each listing
on a new line. Format the list of figures the same way the table of
contents is formatted, but put the words \textquotedblleft List of
Figures\textquotedblright{} in the heading.
\subsection{List of Tables }
If one or more tables are used in the document, there must be a list
of all tables. The list should be spaced at 1.15. Begin each listing
on a new line. Format the list of tables the same way the table of
contents is formatted, but put the words \textquotedblleft List of
Tables\textquotedblright{} in the heading.
\subsection{List of Abbreviations }
Include a list of abbreviations only if you use abbreviations that
are not common in your field. Arrange the list alphabetically. Type
the words \textquotedblleft List of Abbreviations\textquotedblright{}
in chapter title style at the top of your list.
\subsection{Acknowledgments }
An acknowledgments section must be included. Use it to thank those
who supported your research through contributions of time, money,
or other resources. Some grants require an acknowledgment. Type the
word \textquotedblleft Acknowledgments\textquotedblright{} in the
chapter title style at the top of your page. If the acknowledgments
fill more than one page, put the heading only on the first page.
\subsection{Dedication }
The dedication page is optional. If you decide to include a separate
dedication page, make it short and center it on the page, both horizontally
and vertically. Do not include it in your table of contents. See page
vii for more detailed information.
\subsection{Abstract}
Page An abstract page is optional in the dissertation or thesis, but
will be required when you submit your manuscript electronically. Format
the abstract page precisely as shown in the front matter of this document.
See Appendix for further details.
\subsection{Preface }
A preface is optional. If you include a preface, use it to explain
the motivation behind your work. Format the preface the same way the
acknowledgments section is formatted, but use the word \textquotedblleft Preface\textquotedblright{}
in the heading.
\section{Body of the Dissertation or Thesis }
The body of the dissertation or thesis should be divided into chapters,
sections, and subsections as required by your discipline, and should
be numbered as in this template. Divisions smaller than subsections
may be used, but they should not be labeled with numbers (see 2.5.1
for more information).
\section{Back Matter }
The back matter includes all material that appears after the body
of the text.
\subsection{References/Bibliography/Works Cited }
There are two options for the placement of references; they can be
listed at the end of each chapter or at the end of the document. What
you call this section and how you format it should follow the usual
convention of your discipline and be acceptable to your committee.
Depending on how you title and where you place this section, type
the appropriate words in either the section heading or chapter title
format at the top of a new page. Single space your citations and skip
a line between each one. Regardless of where you choose to place your
references, they must be listed in the table of contents. If placed
at the end of your document, this section should follow the conclusion
of the text.
\subsection{Appendices }
Appendices may be used for including reference material that is too
lengthy or inappropriate for the dissertation or thesis body. If one
appendix is included, an appendix title is optional. If more than
one appendix is included, each one should be titled and lettered.
In general, appendices should be formatted like chapters. However,
they may be single-spaced and/or include photocopied or scanned materials.
If these are used, you must add page numbers at the bottom, putting
those page numbers in square brackets to indicate that they are not
part of the original document.
\subsection{Curriculum Vitae }
Including a Curriculum Vitae (C.V.) with your dissertation or thesis
is optional. If you choose to include your C.V., it should include
your name, the month \& year you will be earning your degree, and
relevant academic and professional achievements. It may also include
your publications and professional society memberships. If included,
your vita should be the last page(s) of your document. Note that personally
identifiable information such as birth date, place of birth, and social
security number should NOT be included.
\clearpage{}
\chapter{Dissertation or Thesis Format }
The following guidelines offer you some degree of flexibility in formatting
your thesis or dissertation. Whichever options you choose to use,
you must use them consistently throughout the document.
\section{Margins }
Your printed output must reflect physically measurable top, bottom,
left, and right margins of 1 inch. Some systems\textquoteright{} settings
produce varying results when printing to different printers, so be
sure to measure your output. Remember, nothing, not even page numbers,
should print in the margins.
\section{Page Numbers }
All pages numbers should be placed on the center of each page immediately
above the bottom margin. Number all pages in your document except
for the title page and the optional copyright page which might follow
the title page. Number the \textquotedblleft front matter\textquotedblright{}
pages (i.e., the pages that come prior to the main body of text, prior
to chapter 1) with lowercase roman numerals, starting with ii (remember,
the title page is counted but not numbered, and the copyright page
is neither counted nor numbered). The body of the dissertation or
thesis should be numbered with Arabic numerals starting with 1 and
should begin on the epigraph page (optional), the introduction, if
one is used, or on the first page of the first chapter. Options are
summarized in Table 1.1 on page two.
\section{Text }
This template uses a 12-point, Times New Roman font throughout and
is recommended for your dissertation or thesis. However, should you
choose to use a different font, you should match the font size as
close as possible. Use double-spacing for body text. Use either left
justification with a ragged right edge or full justification.
\section{Chapter Titles }
Begin each chapter on a new page. You may start the chapter title
below the top margin or you may leave some space and start the chapter
title up to 3 inches from the top edge of the page. The font size
for chapter titles should be no larger than 24. There are two options
for formatting the chapter title:
\begin{enumerate}
\item Type the word \textquotedblleft Chapter\textquotedblright{} followed
by the chapter number, skip a line, and type the chapter title on
the following line; or
\item Type the chapter number followed by the chapter title, all on the
same line.
\end{enumerate}
\section{Section Headings \& Numbering }
Headings may be typed above or on the same line as the sections they
label. Type the chapter number and section number before the section
title. The font size for section headings should be no larger than
18.
\subsection{Subsection Headings \& Numbering }
This should follow the usual convention of your discipline and be
acceptable to your committee; if your discipline calls for them they
must be in included in the table of contents. Type the chapter number,
section number and subsection number before the subsection title.
The font size for subsection headings should be no larger than 14.
\subsection{Headings for Divisions Smaller than Subsections }
Do not number headings for divisions smaller than subsections. These
are not included in the table of contents. Headings may be typed above
or on the same line as the sections they label. Divisions smaller
than subsections should be the same font size as the body text.
\section{Figures and Tables }
There are two options for numbering your figures and tables; choose
one and be consistent in its use throughout your document. In either
case, the name and description of the figure or table should be single
spaced and can be a smaller font size.
\begin{enumerate}
\item Maintain a separate numbering sequence for your list of figures and
list of tables. Label figures with the word \textquotedblleft Figure\textquotedblright{}
and tables with the word \textquotedblleft Table\textquotedblright ;
or
\item Label both figures and tables with the word \textquotedblleft Figure\textquotedblright{}
and maintain one numbering sequence.
\end{enumerate}
Place figures and tables as close to their reference in the text as
possible. Do not let figures or tables spill out into the margins.
\begin{enumerate}
\item Place the figure number and title below each figure (or table labeled
as a figure).
\item Place the table number and title above each table labeled as a table.
\end{enumerate}
\begin{figure}[h]
\includegraphics[width=0.5\textwidth]{test_img}
\protect\caption{You can left justify your figure.}
\end{figure}
\begin{figure}[h]
\begin{centering}
\includegraphics[width=0.5\textwidth]{test_img}
\par\end{centering}
\protect\caption{You can center your figure.}
\end{figure}
\section{Lists }
You may include lettered, numbered, or bulleted lists in your document.
Use consistent punctuation and capitalization throughout each list.
Lists may be indented.
\section{Footnotes and Endnotes }
You may use footnotes or endnotes for brief notes that are not appropriate
for the body of the text.%
\footnote{The use of endnotes and footnotes should follow the usual convention
of your discipline and be acceptable to your committee.%
} Use either footnotes or endnotes consistently throughout your dissertation
or thesis. Endnotes are positioned at the end of each chapter. Single-space
within each footnote or endnote. Footnotes should be numbered consecutively
within a chapter; numbers should restart with each new chapter. Endnotes
should be numbered consecutively through the entire body of your dissertation
or thesis.
\section{Quotations }
You must use quotation marks and parenthetical references to indicate
words that are not your own. Put quotation marks around short quotes.
Put long quotes in separate single-spaced paragraphs, indented up
to 1 inch from the left margin (these are called block quotations).
Kate Turabian, editor of official publications and dissertation secretary
at the University of Chicago for over 25 years, distinguishes short
and long quotes as follows:
\begin{quote}
\begin{singlespace}
Short, direct prose quotations should be incorporated into the text
of the paper and enclosed in double quotation marks: \textquotedblleft One
small step for man; one giant leap for mankind.\textquotedblright{}
But in general a prose quotation of two or more sentences which at
the same time runs to four or more lines of text in a paper should
be set off from the text and indented in its entirety\dots {[}8{]} \end{singlespace}
\end{quote}
\section{Equations }
Equation numbering and formatting should follow the usual convention
of your discipline and be acceptable to your committee.
Equations may be set in-line with the text or numbered and placed
in separate paragraphs. Use the same numbering style for equations
as you would for figures and tables. Here is an example of an equation
set in-line with a paragraph: $E=mc^{2}$. Here is an example equation
placed in a separate paragraph:
\begin{equation}
E=mc^{2}
\end{equation}
\clearpage{}
\begin{spacing}{1}
\phantomsection
\addcontentsline{toc}{chapter}{\numberline{}Bibliography}
\bibliographystyle{ieeetr}
\nocite{*}
\bibliography{test}
\end{spacing}
\clearpage{}
\phantomsection
\addcontentsline{toc}{chapter}{\numberline{}Appendix}
\appendix
\chapter*{Appendix }
\section*{Title page }
The second line (or second and third lines) on the page must name
your administrative unit.
\begin{itemize}
\item If your degree is offered by one department of Arts \& Sciences on
the Danforth Campus, your unit is that department:
\end{itemize}
\begin{center}
Department of East Asian Languages \& Cultures
\par\end{center}
\begin{itemize}
\item For a co-sponsored degree such as English \& Comparative Literature,
credit both:
\end{itemize}
\noindent \begin{center}
Department of English
\par\end{center}
\noindent \begin{center}
Program in Comparative Literature
\par\end{center}
\begin{itemize}
\item For the Division of Biology \& Biomedical Sciences, credit DBBS and
your program:
\end{itemize}
\noindent \begin{center}
Division of Biology \& Biomedical Sciences Neurosciences
\par\end{center}
\begin{itemize}
\item Credit only the program for any of the non-DBBS PhDs on the Medical
Campus:
\end{itemize}
\noindent \begin{center}
Program in Movement Science \\
or \\
Program in Speech \& Hearing
\par\end{center}
\begin{itemize}
\item If you are in a department in Engineering, credit the School and the
department:
\end{itemize}
\noindent \begin{center}
School of Engineering \& Applied Science
\par\end{center}
\noindent \begin{center}
Department of Biomedical Engineering
\par\end{center}
\begin{itemize}
\item If you are in social work or business, your administrative unit is
the School:
\end{itemize}
\noindent \begin{center}
Brown School of Social Work\\
or \\
Olin Business School
\par\end{center}
\section*{Abstract page }
Frequent confusion occurs because your abstract heading names your
degree rather than your administrative unit, so it may \textendash{}
or may not \textendash{} match your title page in that respect.
\begin{itemize}
\item For the Division of Biology \& Biomedical Sciences:
\end{itemize}
\noindent \begin{center}
Doctor of Philosophy in Biology and Biomedical Sciences Neurosciences
\par\end{center}
\begin{itemize}
\item For a co-sponsored degree such as English \& Comparative Literature,
credit both:
\end{itemize}
\noindent \begin{center}
Doctor of Philosophy in English and Comparative Literature
\par\end{center}
\begin{itemize}
\item If your degree is offered by one department of Arts \& Sciences on
the Danforth Campus:
\end{itemize}
\noindent \begin{center}
Doctor of Philosophy in Chemistry
\par\end{center}
\end{document}
|
If $d > 0$, then there exists a neighborhood of $z$ contained in $A$ such that all points in this neighborhood are in the ball of radius $d$ around $z$.
|
{-
A parameterized family of structures S can be combined into a single structure:
X ↦ (a : A) → S a X
-}
{-# OPTIONS --cubical --no-import-sorts --safe #-}
module Cubical.Structures.Parameterized where
open import Cubical.Foundations.Prelude
open import Cubical.Foundations.Equiv
open import Cubical.Functions.FunExtEquiv
open import Cubical.Foundations.SIP
module _ {ℓ ℓ₁ ℓ₂} (A : Type ℓ) where
ParamStructure : (S : A → Type ℓ₁ → Type ℓ₂)
→ Type ℓ₁ → Type (ℓ-max ℓ ℓ₂)
ParamStructure S X = (a : A) → S a X
ParamEquivStr : {S : A → Type ℓ₁ → Type ℓ₂} {ℓ₃ : Level}
→ (∀ a → StrEquiv (S a) ℓ₃) → StrEquiv (ParamStructure S) (ℓ-max ℓ ℓ₃)
ParamEquivStr ι (X , l) (Y , m) e = ∀ a → ι a (X , l a) (Y , m a) e
ParamUnivalentStr : {S : A → Type ℓ₁ → Type ℓ₂} {ℓ₃ : Level}
(ι : ∀ a → StrEquiv (S a) ℓ₃) (θ : ∀ a → UnivalentStr (S a) (ι a))
→ UnivalentStr (ParamStructure S) (ParamEquivStr ι)
ParamUnivalentStr ι θ e = compEquiv (equivPi λ a → θ a e) funExtEquiv
|
/-
The goal of this file is to prove the main part of Proposition 7 of Bourbaki GT III 6.8 :
The completion hat K of a Hausdorff topological field is a field if the image under
the mapping x ↦ x⁻¹ of every Cauchy filter (with respect to the additive uniform structure)
which does not have a cluster point at 0 is a Cauchy filter
(with respect to the additive uniform structure).
Bourbaki does *not* prove this proposition, he refers to the general discussion of extending
function defined on a dense subset with values in a complete Hausdorff space. In particular
the subtlety about clustering at zero is totally left to readers.
All this is very general. The application we have in mind is extension of valuations.
In this application K will be equipped with a valuation and the topology on K will be the
nonarchimedean topology coming from v.
Note that the separated completion of a non-separated topological field is the zero ring, hence
the separation assumption is needed. Indeed the kernel of the completion map is the closure of
zero which is an ideal. Hence it's either zero (and the field is separated) or the full field,
which implies one is sent to zero and the completion ring is trivial.
-/
import topology.algebra.uniform_ring
import for_mathlib.topological_field
import for_mathlib.data.set.basic
import for_mathlib.filter
noncomputable theory
local attribute [instance, priority 0] classical.prop_decidable
open filter
set_option class.instance_max_depth 100
open set uniform_space uniform_space.completion filter
local attribute [instance] topological_add_group.to_uniform_space topological_add_group_is_uniform
local notation `𝓝` x:70 := nhds x
local notation `𝓤` := uniformity
variables {K : Type*} [discrete_field K] [topological_space K] [topological_ring K]
variables (K)
local notation `hat` := completion
def help_tc_search : uniform_space (hat K) := completion.uniform_space K
local attribute [instance] help_tc_search
def help_tc_search' : separated (hat K) := completion.separated K
local attribute [instance] help_tc_search'
def help_tc_search'' : complete_space (hat K) := completion.complete_space K
local attribute [instance] help_tc_search''
def help_tc_search''' : t1_space (hat K) := t2_space.t1_space
local attribute [instance] help_tc_search'''
instance [separated K] : nonzero_comm_ring (hat K) :=
{ zero_ne_one := assume h, zero_ne_one $ (uniform_embedding_coe K).inj h,
..completion.comm_ring K }
class completable_top_field : Prop :=
(separated : separated K)
(nice : ∀ F : filter K, cauchy F → 𝓝 0 ⊓ F = ⊥ → cauchy (map (λ x, x⁻¹) F))
local attribute [instance] completable_top_field.separated
variables [completable_top_field K] [topological_division_ring K] {K}
/-- extension of inversion to `hat K` -/
def hat_inv : hat K → hat K := dense_inducing_coe.extend (λ x : K, (coe x⁻¹ : hat K))
lemma continuous_hat_inv {x : hat K} (h : x ≠ 0) : continuous_at hat_inv x :=
begin
haveI : regular_space (hat K) := completion.regular_space K,
refine dense_inducing_coe.tendsto_extend _,
apply mem_sets_of_superset (compl_singleton_mem_nhds h),
intros y y_ne,
rw mem_compl_singleton_iff at y_ne,
dsimp,
apply complete_space.complete,
change cauchy (map (coe ∘ (λ (x : K), x⁻¹)) (comap coe (𝓝 y))),
rw ← filter.map_map,
apply cauchy_map (completion.uniform_continuous_coe K),
apply completable_top_field.nice,
{ apply cauchy_comap,
{ rw completion.comap_coe_eq_uniformity, exact le_refl _ },
{ exact cauchy_nhds },
{ exact dense_inducing_coe.comap_nhds_ne_bot } },
{ have eq_bot : 𝓝 ↑(0 : K) ⊓ 𝓝 y = ⊥,
{ by_contradiction h,
exact y_ne (eq_of_nhds_ne_bot h).symm },
rw [dense_inducing_coe.nhds_eq_comap (0 : K), ← comap_inf, eq_bot],
exact comap_bot },
end
lemma hat_inv_extends {x : K} (h : x ≠ 0) : hat_inv (x : hat K) = coe (x⁻¹ : K) :=
dense_inducing_coe.extend_e_eq _
((continuous_coe K).continuous_at.comp (topological_division_ring.continuous_inv x h))
lemma hat_inv_is_inv {x : hat K} (x_ne : x ≠ 0) : x*hat_inv x = 1 :=
begin
haveI : t1_space (hat K) := t2_space.t1_space,
let f := λ x : hat K, x*hat_inv x,
let c := (coe : K → hat K),
change f x = 1,
have cont : continuous_at f x,
{ letI : topological_space (hat K × hat K) := prod.topological_space,
have : continuous_at (λ y : hat K, ((y, hat_inv y) : hat K × hat K)) x,
from continuous_at.prod_mk continuous_id.continuous_at (continuous_hat_inv x_ne),
exact (_root_.continuous_mul.continuous_at.comp this : _) },
have clo : x ∈ closure (c '' -{0}),
{ have := dense_inducing_coe.dense x,
rw [← image_univ, show (univ : set K) = {0} ∪ -{0}, from (union_compl_self _).symm, image_union] at this,
apply mem_closure_union this,
rw image_singleton,
exact compl_singleton_mem_nhds x_ne },
have fxclo : f x ∈ closure (f '' (c '' -{0})) := mem_closure_image cont clo,
have : f '' (c '' -{0}) ⊆ {1},
{ rw image_image,
rintros _ ⟨z, z_ne, rfl⟩,
rw mem_singleton_iff,
rw mem_compl_singleton_iff at z_ne,
dsimp [c, f],
rw hat_inv_extends z_ne,
norm_cast,
rw mul_inv_cancel z_ne,
norm_cast },
replace fxclo := closure_mono this fxclo,
rwa [closure_singleton, mem_singleton_iff] at fxclo
end
/-
The value of `hat_inv` at zero is not really specified, although it's probably zero.
Here we explicitly enforce the `inv_zero` axiom.
-/
instance completion.has_inv : has_inv (hat K) := ⟨λ x, if x = 0 then 0 else hat_inv x⟩
@[move_cast]
lemma coe_inv (x : K) : ((x⁻¹ : K) : hat K)= (x : hat K)⁻¹ :=
begin
by_cases h : x = 0,
{ rw [h, inv_zero],
dsimp [has_inv.inv],
norm_cast,
simp [if_pos] },
{ conv_rhs { dsimp [has_inv.inv] },
norm_cast,
rw if_neg,
{ exact (hat_inv_extends h).symm },
{ exact λ H, h (completion.dense_embedding_coe.inj H) } }
end
instance : discrete_field (hat K) :=
{ zero_ne_one := assume h, discrete_field.zero_ne_one K ((uniform_embedding_coe K).inj h),
mul_inv_cancel := λ x x_ne, by { dsimp [has_inv.inv], simp [if_neg x_ne, hat_inv_is_inv x_ne], },
inv_mul_cancel := λ x x_ne, by { dsimp [has_inv.inv],
rw [mul_comm, if_neg x_ne, hat_inv_is_inv x_ne] },
inv_zero := show (0 : hat K)⁻¹ = (0 : hat K), by rw_mod_cast inv_zero,
has_decidable_eq := by apply_instance,
..completion.has_inv,
..(by apply_instance : comm_ring (hat K)) }
instance : topological_division_ring (hat K) :=
{ continuous_inv := begin
intros x x_ne,
have : {y | y⁻¹ = hat_inv y } ∈ 𝓝 x,
{ have : -{(0 : hat K)} ⊆ {y : hat K | y⁻¹ = hat_inv y },
{ intros y y_ne,
rw mem_compl_singleton_iff at y_ne,
dsimp [has_inv.inv],
rw if_neg y_ne },
exact mem_sets_of_superset (compl_singleton_mem_nhds x_ne) this },
rw continuous_at.congr this,
exact continuous_hat_inv x_ne
end,
..completion.top_ring_compl }
|
ply tires, air shocks. $400.
Awesome Tire And wheel combo.
trucks and SUV's with six bolt hubs.
|
Find := function(v, x)
local low, high, mid;
low := 1;
high := Length(v);
while low <= high do
mid := QuoInt(low + high, 2);
if v[mid] > x then
high := mid - 1;
elif v[mid] < x then
low := mid + 1;
else
return mid;
fi;
od;
return fail;
end;
u := [1..10]*7;
# [ 7, 14, 21, 28, 35, 42, 49, 56, 63, 70 ]
Find(u, 34);
# fail
Find(u, 35);
# 5
|
(*
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: mgga_exc *)
(* prefix:
mgga_c_tpss_params *params;
assert(p->params != NULL);
params = (mgga_c_tpss_params * )(p->params);
*)
(* beta is taken from the params *)
params_a_gamma := (1 - log(2))/Pi^2:
params_a_BB := 1:
$include "gga_c_pbe.mpl"
$include "tpss_c.mpl"
f := (rs, z, xt, xs0, xs1, us0, us1, ts0, ts1) ->
+ tpss_f(f_pbe, rs, z, xt, xs0, xs1, ts0, ts1):
|
% !TEX root = ../bigmpi.tex
\subsection{Vector-argument collectives}
Vector-argument collectives (henceforth v-collectives) are the generalization of,
for example, \texttt{MPI\_Scatter}, \texttt{MPI\_Gather}, and \texttt{MPI\_Alltoall}
when the count but not the datatype varies across processes.
When datatypes are used to support large counts, all these operations must be
mapped to \texttt{MPI\_Alltoallw} because each large count will be mapped
to a different user-defined datatype, and \texttt{MPI\_Alltoallw} is the only collective
that supports a vector of datatypes.
Using \texttt{MPI\_Alltoallw} to implement, for example, a large-count \texttt{MPI\_Scatterv} is
particularly inefficient because the former assumes inputs from every process,
whereas the latter uses only the input from the root.
However, the overhead of scanning a vector of counts where all but one is zero
is almost certainly inconsequential compared with the cost of transmitting a buffer
of $2^{31}$ bytes.
%Additionally, such vectors are unlikely to be particularly long since scattering
%a buffer that would run into large-count issues r
%All V-collectives turn into ALLTOALLW because different counts implies different large-count types.
The v-collectives encounter a second, more subtle issue due to the mapping to
\texttt{MPI\_Alltoallw}. Because this function takes a vector of datatypes, the
displacements into the input and output vectors are given in bytes,
not element count, and the type of this offset is a C integer.
This creates an overflow situation \textit{even
when the input buffer is less than 2 GiB} because a vector of 1 billion
alternating integers and floats may require an byte offset in excess of $2^{31}$.
Thus, \texttt{MPI\_Alltoallw} is not an acceptable solution for the large-count
v-collectives because of the likelihood of overflowing in the displacement vector.
The use of the C integer instead of \texttt{MPI\_Aint} for the displacement vector in
the collective operations added prior to MPI-3 is an unfortunate oversight that
cannot be rectified without breaking backward compatibility.
%ALLTOALLW displacements given in bytes are C int, and therefore it is impossible to offset more than 2GB into the buffer.
%NEIGHBOR\_ALLTOALLW to the rescue?!?!
%MPI\_Neighbor\_alltoallw displacements are MPI\_Aint not int. This is good.
%Neighborhood collectives require special communicators that must be created for each call (and possibly cached).
%Must allocate new argument vectors and, in the case of alltoall, we wastefully splat the same value in all locations.
Fortunately, the overflow issue with displacements in \texttt{MPI\_Alltoallw} is
resolved by using the neighborhood collectives introduced in MPI-3, which do
use \texttt{MPI\_Aint} for displacements.
On the other hand, neighborhood collectives require an appropriate
communicator, which must be constructed prior to calling \texttt{MPI\_Neighborhood\_alltoallw}.
BigMPI creates a distributed graph communicator using \texttt{MPI\_Dist\_graph\_adjacent}
on the fly for every invocation of the large-count v-collectives, which instead are assumed to incur
insignificant overhead compared with the data movement entailed in such an operation.
It is straightforward to optimize for the common cases of \texttt{MPI\_COMM\_WORLD} for
non-rooted collectives and \texttt{MPI\_COMM\_WORLD} with \texttt{root=0}, but this
is not currently implemented.
The implementation of large-count v-collectives using \texttt{MPI\_Neighborhood\_alltoallw}
requires two $O(n_{proc})$ setup steps. The first allocates and populates the vectors of
send and receive counts, displacements, and datatypes.
The second creates a distributed graph communicator.
Figures~\ref{code:BigMPI_Convert_vectors} and~\ref{code:BigMPI_Create_graph_comm}
show the implementation of these functions, which are included in their entirety to illustrate that
although the mapping from v-collectives to \texttt{MPI\_Neighborhood\_alltoallw} is feasible,
it is rather involved and in some cases unnatural.
Creating the vector of datatypes requires $O(n_{proc})$ calls to \texttt{BigMPI\_Type\_contiguous\_x},
which itself requires six MPI calls, although all of these are expected to be inexpensive.
% V-collectives using P2P and RMA
%One can follow the definition in MPI to implement all of the V-collectives using P2P.
%RMA (with win\_fence synchronization) also works for the V-collectives.
%Allgatherv using nproc calls to Bcast also works.
%Large-count definitely outside of recursive doubling regime so little to optimize...
An alternative approach to implementing large-count v-collectives is to map
these to point-to-point operations, although this works only for blocking operations
because of the inability to aggregate requests, as described above.
Since large-count v-collectives are well outside the regime where latency-oriented
optimizations such as recursive-doubling are important, this approach is unlikely to have a significant impact
on performance, and it eliminates the need for some of the $O(n_{proc})$ setup steps.
The MPI standard describes every collective in terms of its implementation
in terms of send-recv calls; the point-to-point BigMPI implementation
follows these recipes closely:
(1) nonblocking receives are preposted by the root or all ranks as appropriate;
(2) the root or all ranks then call nonblocking send;
and (3) all ranks then call Waitall.
Since the large-count BigMPI send-recv functions are used, there is no need for
$O(n_{proc})$ vectors of datatypes, and so forth---only a vector of \texttt{MPI\_Request}
objects for the nonblocking operations is required.
A third implementation of v-collectives is to use RMA (one-sided) that follows
the same traffic pattern as the point-to-point implementation.
In this case, an MPI window must be created associated with the source (target)
buffers and \texttt{MPI\_Get} (\texttt{MPI\_Put}) operations used for moving data.
The most appropriate synchronization mode for mapping collectives to RMA
is \texttt{MPI\_Win\_fence}, although one could use a passive target instead.
If a future version of the MPI standard introduces a nonblocking
equivalent of \texttt{MPI\_Win\_fence} or \texttt{MPI\_Win\_unlock\_all}, these
could be used to implement nonblocking v-collectives in terms of RMA;
at least within MPI-3, we are limited to the blocking case.
The RMA implementation was prototyped in BigMPI but is not currently implemented.
%because no performance benefit of one-sided is expected because of the current state
The current state of RMA implementations map one-sided operations to two-sided ones internally. Thus we would expect to see no performance benefit from BigMPI's RMA approach.
If RMA operations exploit RDMA hardware,
however, noticeable performance improvements may be
observed.
While not named as such, \texttt{MPI\_Reduce\_scatter} is a v-collective.
BigMPI currently does not yet support this function,
but it is straightforward to implement in terms of \texttt{MPI\_Reduce} and
\texttt{MPI\_Scatterv}, which will be the basis for the BigMPI implementation.
% V-collectives - nonblocking issues
%None of the aforementioned solutions works for nonblocking because:
%What request do we return in the case of P2P or RMA?
%Cannot free argument vectors until complete.
%Any solution involving generalized requests is untenable for users. BigMPI might use it.
Unfortunately, nonblocking v-collectives cannot be implemented by using the aforementioned approaches.
In the case of the neighborhood collective
implementation, we cannot free the vector temporaries holding the counts,
displacements, and datatypes until the operation has completed.
If callback functions associated with request completion were present in the
MPI standard (see \cite{ticket26} for a proposal of this), then it would
be possible to free the temporary buffers using this callback.
Since one cannot associate a single request with multiple
nonblocking operations, the point-to-point implementation is not viable
for the nonblocking v-collectives.
Moreover, all relevant forms of MPI RMA synchronization have blocking semantics
and thus cannot be used to implement nonblocking collectives.
\textit{We identify nonblocking v-collectives as the second example
where MPI-3 lacks the necessary features to support large counts.}
\begin{figure}
\begin{code}
void BigMPI_Convert_vectors(int num,
int splat_old_count,
const MPI_Count oldcount,
const MPI_Count oldcounts[],
int splat_old_type,
const MPI_Datatype oldtype,
const MPI_Datatype oldtypes[],
int zero_new_displs,
const MPI_Aint olddispls[],
int newcounts[],
MPI_Datatype newtypes[],
MPI_Aint newdispls[])
{
assert(splat_old_count || (oldcounts!=NULL));
assert(splat_old_type || (oldtypes!=NULL));
assert(zero_new_displs || (olddispls!=NULL));
MPI_Aint lb /* unused */, oldextent;
if (splat_old_type) {
MPI_Type_get_extent(oldtype, &lb, &oldextent);
} else {
/* !splat_old_type implies ALLTOALLW,
which implies no displacement zeroing. */
assert(!zero_new_displs);
}
for (int i=0; i<num; i++) {
/* counts */
newcounts[i] = 1;
/* types */
MPIX_Type_contiguous_x(oldcounts[i],
splat_old_type ? oldtype : oldtypes[i],
&newtypes[i]);
MPI_Type_commit(&newtypes[i]);
/* displacements */
MPI_Aint newextent;
/* If we are not splatting old type, it implies
* ALLTOALLW, which does not scale the
* displacement by the type extent,
* nor would we ever zero the displacements. */
if (splat_old_type) {
MPI_Type_get_extent(newtypes[i], &lb, &newextent);
newdispls[i] = (zero_new_displs ? 0 :
olddispls[i]*oldextent/newextent);
} else {
newdispls[i] = olddispls[i];
}
}
return;
}
\end{code}
\caption{Function for populating the vector inputs
for \texttt{MPI\_Neighborhood\_alltoallw} for the various v-collectives.}
\label{code:BigMPI_Convert_vectors}
\end{figure}
\begin{figure}
\begin{code}
int BigMPI_Create_graph_comm(MPI_Comm comm_old, int root,
MPI_Comm * comm_dist_graph)
{
int rank, size;
MPI_Comm_rank(comm_old, &rank);
MPI_Comm_size(comm_old, &size);
/* in the all case (root == -1), every rank is a
* destination for every other rank;
* otherwise, only the root is a destination. */
int indeg = (root == -1 || root==rank) ? size : 0;
/* in the all case (root == -1), every rank is a
* source for every other rank;
* otherwise, all non-root processes are the
* source for only one rank (the root). */
int outdeg = (root == -1 || root==rank) ? size : 1;
int * srcs = malloc(indegree*sizeof(int));
assert(srcs!=NULL);
int * dsts = malloc(outdegree*sizeof(int));
assert(dsts!=NULL);
for (int i=0; i<indegree; i++) {
srcs[i] = i;
}
for (int i=0; i<outdegree; i++) {
dsts[i] = (root == -1 || root==rank) ? i : root;
}
int empty = MPI_WEIGHTS_EMPTY;
int unwtd = MPI_UNWEIGHTED;
int rc = MPI_Dist_graph_create_adjacent(comm_old,
indeg, srcs, indeg==0 ? empty : unwtd,
outdeg, dsts, outdeg==0 ? empty : unwtd,
MPI_INFO_NULL, 0 /* reorder */,
comm_dist_graph);
free(srcs);
free(dsts);
return rc;
}
\end{code}
\caption{Function for constructing the distributed graph communicator
that allows the mapping of both rooted (e.g. \texttt{MPI\_Gatherv}) and
non-rooted (e.g. \texttt{MPI\_Allgatherv}) collectives to
\texttt{MPI\_Neighborhood\_alltoallw}.}
\label{code:BigMPI_Create_graph_comm}
\end{figure}
|
[STATEMENT]
lemma vsv_vimageE:
assumes "b \<in>\<^sub>\<circ> r `\<^sub>\<circ> A"
obtains x where "r\<lparr>x\<rparr> = b" and "x \<in>\<^sub>\<circ> A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>x. \<lbrakk>r\<lparr>x\<rparr> = b; x \<in>\<^sub>\<circ> A\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
using assms vsv_axioms vsv_ex1_app2
[PROOF STATE]
proof (prove)
using this:
b \<in>\<^sub>\<circ> r `\<^sub>\<circ> A
vsv r
?a \<in>\<^sub>\<circ> \<D>\<^sub>\<circ> r \<Longrightarrow> (r\<lparr>?a\<rparr> = ?b) = (\<langle>?a, ?b\<rangle> \<in>\<^sub>\<circ> r)
goal (1 subgoal):
1. (\<And>x. \<lbrakk>r\<lparr>x\<rparr> = b; x \<in>\<^sub>\<circ> A\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by blast
|
\section{More about Weierstrass' Elliptic Functions; Quotients}
\subsection{An Elliptic Curve}
We have seen two general constructions of Riemann surfaces with genus $1$:
The complex torus and the compactification of the Riemann surface associated with $w^2=z^3-z$.
These two constructions has to be related, but how?
Here, we shall prove that any complex torus is isomorphic to an algebraic construction.
This is a corollary of Proposition \ref{elliptic_wp}.
\begin{corollary}
Let $\mathbb C/\Lambda$ be a complex torus, then there are constants $g_2,g_3$ such that $\mathbb C/\Lambda$ is biholomorphic to a one-point compactification of the graph $X'=\{(x,y)\in\mathbb C^2:y^2=4x^3-g_2x-g_3\}$.
\end{corollary}
\begin{proof}[Sketch of proof]
Take $g_2,g_3$ exactly as in Proposition \ref{elliptic_wp}.
Turns out $X'$ can be compactified into a Riemann surface $X=X'\cup\{\infty\}$ with charts provided by coordinate projection.
Define $F:\mathbb C\to X$ via $z\mapsto(\wp(z),\wp^\prime(z))$ where $\wp=\wp_\Lambda$.
Now $\operatorname{Im}F\subset X$ by Proposition \ref{elliptic_wp} and $F$ is analytic as the charts are coordinate projections.
So via a quotient, we can use $F$ to induce $\Phi:\mathbb C/\Lambda\to X$.
It remains to show that $\Phi$ is a conformal equivalence.
As it is analytic, it suffices to show that it is bijective.
It is surjective as it is nonconstant and everything is compact.
To see it is injective, consider the period parallelogram centered at $0$, that is the parallelogram with vertices $(\omega_1+\omega_2)/2,(\omega_2-\omega_1)/2,(-\omega_1-\omega_2)/2,(\omega_1-\omega_2)/2$.
It suffices to show that $F$ is injective in the interior of $P$, which will imply injectivity of $\Phi$ in general due to the valency theorem.
Suppose $F(z)=F(z')$ for $z,z'\in P^\circ$, then $\wp(z)=\wp(z')$, so $z=\pm z'$ as $\wp$ is even and has degree $2$.
But also $\wp^\prime(z)=\wp^\prime(z')=\pm \wp^\prime(z)$ as $\wp$ is odd, so $z=z'$ as the zeros of $\wp^\prime$ are not in $P^\circ$.
This completes the proof.
\end{proof}
|
function [F,vars] = sort_internal(t,X,data);%ii,D,V);
% Hack to figure out all the sorted variables, not just this index.
% Sort is implemented in a slighlt different way (general feature in
% future versions) that allows one element in an operator to modell all
% elements. Reduces the number of calls to the operator code.
ii = data.i;
D = data.D;
V = data.V;
var_start = getvariables(t)-ii+1;
n = length(X);
var_end = getvariables(t)-ii+1 + n-1;
vars = var_start:var_end;
% Is this a location variable instead of the actuial sort variable. If so,
% shift everything back to get the indicies of the sorted variables.
if data.isthisloc == 1
vars = vars - n;
end
t = recover(vars);
loc = recover(vars+n);
[M,m] = derivebounds(X);
X = reshape(X,1,n);
% Standard model
F = (sum(D,1) == 1) + (sum(D,2) == 1);
F = F + (t == sum(V,2));
F = F + (diff(t) >= 0);
for i = 1:n
di = D(i,:);
vi = V(i,:);
F = F + (-(-m)'.*(1-di) <= X-vi <= (M)'.*(1-di));
F = F + (m'.*di <= vi <= M'.*di);
end
% Cuts
F = F + (X == sum(V,1));
F = F + (sum(t) == sum(X));
% Definition of location
F = F + (loc == D*[(1:n)']) + (1 <= loc <= n);
|
(* Title: HOL/NanoJava/Decl.thy
Author: David von Oheimb
Copyright 2001 Technische Universitaet Muenchen
*)
section "Types, class Declarations, and whole programs"
theory Decl imports Term begin
datatype ty
= NT \<comment> \<open>null type\<close>
| Class cname \<comment> \<open>class type\<close>
text\<open>Field declaration\<close>
type_synonym fdecl
= "fname \<times> ty"
record methd
= par :: ty
res :: ty
lcl ::"(vname \<times> ty) list"
bdy :: stmt
text\<open>Method declaration\<close>
type_synonym mdecl
= "mname \<times> methd"
record "class"
= super :: cname
flds ::"fdecl list"
methods ::"mdecl list"
text\<open>Class declaration\<close>
type_synonym cdecl
= "cname \<times> class"
type_synonym prog
= "cdecl list"
translations
(type) "fdecl" \<leftharpoondown> (type) "fname \<times> ty"
(type) "mdecl" \<leftharpoondown> (type) "mname \<times> ty \<times> ty \<times> stmt"
(type) "class" \<leftharpoondown> (type) "cname \<times> fdecl list \<times> mdecl list"
(type) "cdecl" \<leftharpoondown> (type) "cname \<times> class"
(type) "prog " \<leftharpoondown> (type) "cdecl list"
axiomatization
Prog :: prog \<comment> \<open>program as a global value\<close>
and
Object :: cname \<comment> \<open>name of root class\<close>
definition "class" :: "cname \<rightharpoonup> class" where
"class \<equiv> map_of Prog"
definition is_class :: "cname => bool" where
"is_class C \<equiv> class C \<noteq> None"
lemma finite_is_class: "finite {C. is_class C}"
apply (unfold is_class_def class_def)
apply (fold dom_def)
apply (rule finite_dom_map_of)
done
end
|
State Before: R : Type u
A : Type v
inst✝² : CommSemiring R
inst✝¹ : Ring A
inst✝ : Algebra R A
a : A
⊢ ¬0 ∈ σ a ↔ IsUnit a State After: no goals Tactic: rw [zero_mem_iff, Classical.not_not]
|
State Before: l : Type ?u.482923
m : Type u_2
n : Type u_1
o : Type ?u.482932
m' : o → Type ?u.482937
n' : o → Type ?u.482942
R : Type ?u.482945
S : Type ?u.482948
α : Type v
β : Type w
γ : Type ?u.482955
inst✝² : CommSemiring α
inst✝¹ : Fintype n
inst✝ : DecidableEq n
M : Matrix m n α
a : α
⊢ a • M = M ⬝ diagonal fun x => a State After: case a.h
l : Type ?u.482923
m : Type u_2
n : Type u_1
o : Type ?u.482932
m' : o → Type ?u.482937
n' : o → Type ?u.482942
R : Type ?u.482945
S : Type ?u.482948
α : Type v
β : Type w
γ : Type ?u.482955
inst✝² : CommSemiring α
inst✝¹ : Fintype n
inst✝ : DecidableEq n
M : Matrix m n α
a : α
i✝ : m
x✝ : n
⊢ (a • M) i✝ x✝ = (M ⬝ diagonal fun x => a) i✝ x✝ Tactic: ext State Before: case a.h
l : Type ?u.482923
m : Type u_2
n : Type u_1
o : Type ?u.482932
m' : o → Type ?u.482937
n' : o → Type ?u.482942
R : Type ?u.482945
S : Type ?u.482948
α : Type v
β : Type w
γ : Type ?u.482955
inst✝² : CommSemiring α
inst✝¹ : Fintype n
inst✝ : DecidableEq n
M : Matrix m n α
a : α
i✝ : m
x✝ : n
⊢ (a • M) i✝ x✝ = (M ⬝ diagonal fun x => a) i✝ x✝ State After: no goals Tactic: simp [mul_comm]
|
Looking ahead to chop down your investment to energize your startup business? Take a look through some of these to access the right value of cost reduction on your energy based resources while wheeling your business.
For almost every small-scale businesses, energy consumption has become a pretty big trouble to deal with nowadays. With an alarming increase in the price of the energy fuels motorizing heavy machinery in a factory or in a business project, maximum owners of the (Public Private Partnership Projects) PP projects are much inclined towards alternative sources of conventional sources of energy.
As it’s the only ways left for maximum small and medium scale business to reduce their investment cost and increase their revenue or profit from their businesses.
• Reducing their expenses for energizing the machinery and heavy power consuming equipment in their business projects, etc.
That’s why opting an alternative way to avoid the high-cost of availing the conventional source of energy is always considered as a wise treatment, when you are looking ahead to benchmark your business flawlessly.
Purchasing bulk electricity and natural gas a reliable retailer in a competitive market will always be a wise move from your side as you might unlock the chances to get a reduced price for availing one such source of energy. Often that might add the savings in your wallet and you might increase your revenue that you were expecting to drive for a specific financial year.
Often the business owners might switch their retail supplier of energy from one another whenever they hear about discount rates. Don’t follow this tradition, after all a business is just not about seeing your own profit, its also about building a congenial bond within your retailer or supplier chain too. Your reliability and trust upon your supplier are going to act truly when the market price of the entire energy sources and the gas rates are going to increase yet your long-term retailer is going to provide you a standard rate without making much change in the energy price they supply you.
Relying on the solar form of energy is always going to be a beneficial one in the long run, as its going to be the ultimate benefit for you when you are all set to save your hard earned bucks to minimize your investment. Solar power is considered one of the most trustworthy and reliable sources of energy consumption.
Through the years it had been like an artery providing life to various small and medium scale business projects located in different locations of Australia. With the rapid increase in the purchasing of the solar panels nowadays most of the bootstrap business are ready to set up in Australia are looking forward to implementing solar energy for maximizing their productivity in the business.
Planning to implement an economic way like solar energy cost reduction technique in business is always going to be a wise work idea as it not only helps you to reduce your input cost, rather it also checks your internal expenses too.
Hiring one expert for conducting a successful business benchmarking within your business is always going to be a wise move from your side as its’ always going to help you to operate your startup for a longer period of time.
Before hiring someone to benchmark your business undisputedly, always be careful about the profile or the portfolio of the individual you are hiring for one such job.
That will always assure you uncompromising result for the long run.
Known as one of the renowned benchmarking service providers in Australia benchmarksolutions.com.au is known for providing seamless services when it comes to benchmark your business, their inevitable support in running solar energy cost reduction has helped many medium and small-scale startups to energize their business with cost-effective benefits.
|
William James Nesbitt , OBE ( born 15 January 1965 ) is an actor and presenter from Northern Ireland . Born in Ballymena , County Antrim , Nesbitt grew up in the nearby village of <unk> , before moving to Coleraine , County Londonderry . He wanted to become a teacher like his father , so he began a degree in French at the University of Ulster . He dropped out after a year when he decided to become an actor , and transferred to the Central School of Speech and Drama in London . After graduating in 1987 , he spent seven years performing in plays that varied from the musical Up on the Roof ( 1987 , 1989 ) to the political drama Paddywack ( 1994 ) . He made his feature film debut playing talent agent Fintan O 'Donnell in Hear My Song ( 1991 ) .
|
module Intro
import Data.Vect
-- a term (object) with its type
three : Nat
three = 3
next: Nat -> Nat -- the type is a function type
next n = n + 1
-- a recursive definition
fct: Nat -> Nat
fct Z = 1
fct (S k) = (S k) * (fct k) -- this is primitive recursion
loop: Nat -> Nat
loop Z = Z
loop (S k) = loop k + (loop (k + 2)) -- this is horrible
fibPair: Nat -> (Nat, Nat)
fibPair Z = (1, 1)
fibPair (S k) = case fibPair k of
(a, b) => (b, a + b)
fibo: Nat -> Nat
fibo n = fst (fibPair n)
-- types are terms, i.e., first class, so have types
Naturals : Type
Naturals = Nat
natToNat : Type
natToNat = Nat -> Nat
anotherThree : Naturals
anotherThree = 3
add : Nat -> Nat -> Nat -- Curryed type
add m n = m + n
data BinTree : Type where
Leaf : BinTree
Node : (left: BinTree) -> (right: BinTree) -> BinTree
egTree: BinTree
egTree = Node (Node Leaf (Node Leaf Leaf)) Leaf
numberVertices : BinTree -> Nat
numberVertices Leaf = 1
numberVertices (Node left right) =
(numberVertices left) + (numberVertices right) + 1
-- a parametrized type (generic)
data LTree : Type -> Type where
LLeaf : (a: Type) -> (label: a) -> LTree a
LNode : (a : Type) -> (left : LTree a) -> (right : LTree a) -> LTree a
egLTree : LTree Nat
egLTree =
LNode Nat (
LNode Nat (LLeaf Nat 1) (LNode Nat (LLeaf Nat 3) (LLeaf Nat 4))
) (LLeaf Nat 7)
labels : (a: Type) -> LTree a -> List a
labels a (LLeaf a label) = [label]
labels a (LNode a left right) =
(labels a left) ++ (labels a right)
Tuple: Nat -> Type -- tuples of Natural numbers
Tuple Z = Unit
Tuple (S k) = (Nat, Tuple k)
egTuple : Tuple 2
egTuple = (3, (4, ()))
countdown : (n: Nat) -> Tuple n -- this is a dependent function
countdown Z = ()
countdown (S k) = (S k, countdown k)
cntd : (n: Nat) -> Vect (S n) Nat
cntd Z = [0]
cntd (S k) = (S k) :: (cntd k)
zipNat : (n: Nat) -> Vect n Nat -> Vect n Nat -> Vect n (Nat, Nat)
zipNat Z [] [] = []
zipNat (S len) (x :: xs) (y :: ys) = (x , y) :: (zipNat len xs ys)
zip : (n: Nat) -> (a: Type) -> (b: Type) -> Vect n a -> Vect n b -> Vect n (a, b)
zip Z a b [] [] = []
zip (S len) a b (x :: xs) (y :: ys) =
(x, y) :: (zip len a b xs ys)
append: (n: Nat) -> (a: Type) -> (x: a) -> Vect n a -> Vect (S n) a
append Z a x [] = [x]
append (S len) a x (y :: xs) =
y :: (append len a x xs)
filter: (n: Nat) -> (a: Type) -> (p: a -> Bool) -> Vect n a -> (m: Nat ** Vect m a)
filter Z a p [] = (Z ** [])
filter (S len) a p (x :: xs) =
(case p x of
False => filter len a p xs
True => (case filter len a p xs of
(m ** pf) =>
(S m ** x :: pf) ))
data Nothing : Type where
vacuous : (a: Type) -> Nothing -> a
-- some space
|
function [m2] = yd22m2(yd2)
% Convert area from square yards to square meters.
% Chad A. Greene 2012
m2 = yd2*0.83612736;
|
ceiling fan diagram wire ceiling fan no switch diagram ceiling fan wiring diagram uk ceiling fan connection diagram capacitors.
adhesive table cover marble contact paper roll vinyl contact paper marble table cover self adhesive covering vinyl adhesive table covers adhesive table top covers.
allium plants quick view opens a dialog a big.
carpet stretching san antonio carpet stretching carpet stretching.
night glow wall clocks glow wall clock in the dark clocks night for sale.
faux leather leggings target faux leather tummy control leggings.
acid wash patio acid stained patios best slate overlay acid stained patio of acid stained patios prettier acid wash stone patio acid wash new flagstone patio.
warehouse exterior lighting black outdoor light lighting emblem black inch outdoor wall light black exterior light warehouse builders warehouse outdoor lighting warehouse style outdoor lighting.
|
-- Andreas, 2015-09-12, Issue 1637, reported by Nisse.
-- {-# OPTIONS -v tc.display:100 -v reify.display:100 #-}
record R (X : Set₁) : Set₁ where
field
f : X
postulate
A : Set₁
P : A → Set
module M (_ : Set₁) where
Unrelated-function : R Set → Set
Unrelated-function Y = R.f Y -- eta expansion is necessary
open M Set
-- Here, the old implementation recursively added a display form
-- for R.f because the body of Unrelated-function has the right
-- form, looking as if it came from a module application.
-- adding display forms
-- Issue1637.M.Unrelated-function --> Issue1637._.Unrelated-function
-- Issue1637.R.f --> Issue1637._.Unrelated-function
-- If one restricts display forms to things that actually
-- come from a module applications, i.e., are a defCopy,
-- then this issue is fixed.
Foo : ((Z : R A) → P (R.f Z)) → Set₁
Foo f = f
-- The inferred type of f is (printed as?)
--
-- (Z : R A) → P Unrelated-function,
--
-- which is not a type-correct expression.
--
-- The bug exists in Agda 2.3.2, but not in Agda 2.3.0.1.
|
\documentclass[11pt, oneside]{article} % use "amsart" instead of "article" for AMSLaTeX format
\usepackage{geometry} % See geometry.pdf to learn the layout options. There are lots.
\geometry{letterpaper} % ... or a4paper or a5paper or ...
%\geometry{landscape} % Activate for for rotated page geometry
%\usepackage[parfill]{parskip} % Activate to begin paragraphs with an empty line rather than an indent
\usepackage{graphicx} % Use pdf, png, jpg, or eps§ with pdflatex; use eps in DVI mode
% TeX will automatically convert eps --> pdf in pdflatex
\usepackage{amssymb}
\title{Ecological model for GEOCLIM: the ECOWEB module}
\author{Yves Godd\'eris}
\date{March 2016} % Activate to display a given date or no date
\begin{document}
\maketitle
\section{Generality}
%*****************************************************
The model includes three trophic levels: primary producers, predators, and super predators. The ecological model uses the P input in each oceanic reservoir to calculate the uptake of P and C by the primary producers (entrance gate of those elements in the trophic chains). ECOWEB then sends this uptake back to the GEOCLIM model which stores it into the POC reservoir. Within ECOWEB, the exchange fluxes are in molC/yr, and the stocks in molC. Each species is thus represented by a carbon mass.
The number of species of the three trophic levels is fixed prior to any simulation.
\section{Mass balance for the primary producers}
%*****************************************************
At each time step, the mass of species $i$ is calculated by solving the following mass balance equation:
\begin{eqnarray}
%species budget
\frac{dy_{i}}{dt}=\alpha_{i}-\omega_{i}
\label{spbalance}
\end{eqnarray}
where $y_i$ is the biomass of species $i$ (mol C). $\alpha_i$ is the birth rate of species $i$, and $\omega_i$ is the sum of the death rate and grazing rate when applicable.
\subsection{Reproduction rate}
$\alpha_i$ (mol/yr) is dependent on the temperature of the reservoir $T$, on pH, and on the input of dissolved PO$_{4}^{2-}$ inside the oceanic reservoir.
\\
\begin{eqnarray}
%alpha calculation
\alpha_{i}=br_{i} \cdot a_{1}^{i} \cdot \exp{\left[ \frac {-\left(T-b_{1}^{i}\right)^{2}} {2\left(c_{1}^{i}\right)^{2}} \right]} \cdot
a_{2}^{i} \cdot \exp{\left[ \frac {-\left(pH-b_{2}^{i}\right)^{2}} {2\left(c_{2}^{i}\right)^{2}} \right]} \cdot
I_{i} \cdot F_{in}^{P}
\label{birth}
\end{eqnarray}
The two exponential factors are gaussian functions. $b_{1}^{i}$ and $b_{2}^{i}$ are respectively the optimum living temperature and pH for the species $i$. $c_{1}^{i}$ and $c_{2}^{i}$ define the temperature and pH tolerance of species $i$. $b_{1}^{i}$ is set to the averaged long term temperature, with a random noise between 0 and $\pm$5 degrees C around the optimum living temperature. The temperature tolerance for each species is randomly set a value between 0 and $\pm$4 degrees C around each respective optimum temperature $b_{1}^{i}$. Optimal living pH $b_{2}^{i}$ and tolerance $c_{2}^{i}$ are similarly randomly set. The interval goes from -0.1 to +0.1 for the noise added to the averaged long term pH of the surficial reservoir. Tolerance runs from $\pm$0.3 pH unit.
Finally, $I_{i}$ represents the potential competition for resources amongst the primary producers. For each species $i$, the existence of a competitive relationship is randomly fixed (yes/no). If the answer is no, $I_{i,j}$ is set to 1. Conversely, If the answer is yes, $I_{i,j}$ is calculated as follows for species $i$:
\\
\begin{eqnarray}
%competition
I_{i,j}=\frac{\left(\frac{y_i}{y_j}\right)} {1+\left(\frac{y_i}{y_j}\right)}
\label{competition}
\end{eqnarray}
For species $j$ with respect to species $i$, it is calculated as:
\\
\begin{eqnarray}
%competition
I_{j,i}=1-I_{i,j}
\label{competition2}
\end{eqnarray}
where $y_i$ and $y_j$ are respectively the biomasses of species $i$ and $j$. If the ratio between these two biomasses tends towards 0, then the efficiency of species $j$ in gathering resources leads to the extinction of $i$. If the biomass ratio turns at the advantage of species $i$, and the reproduction of {j) tends towards 0. The factor $I_i$ is calculated as the average of all the $I_i,j$, for $j$ covering the whole range of species in competition with $i$. This formalism implies that if a species is in competition with one or several others, its reproduction rate is somewhat reduced ($I_i$ is little than 1) compared to non-competing species.
\subsection{Death rate}
The death rate of each primary producer is equal to the sum of the natural death rate $D_i$ and the predation rate $G_{i,k}$ of species by the predator $k$ (both fuxes in moleC/year). The death rate is set proportional to the total mass of the primary producer himself:
\\
\begin{eqnarray}
%primary producer death rate
D_i=k_{death} \cdot y_i
\label{death_rate}
\end{eqnarray}
Several predators can feed on the same primary producer species $i$. The is fixed by drawing lots. Then the total loss of biomass of species $i$ due to predation is:
\\
\begin{eqnarray}
%primary producer death rate
G_i=\sum_k {G_(i,k)}=\sum_k {k_{pred}^{k,i} \cdot \frac{\frac{y_i}{y_k}}{10+\frac{y_i}{y_k}} \cdot y_k}
\label{predation_rate}
\end{eqnarray}
where the sum extends over all the predators ($k$) feeding on species $i$. $k_{pred}^{k,i}$ is a fix constant, but can also be randomly fixed. The relative predator biomass within the whole ecosystem depends on this (those) constant(s). The predation rate is also set proportional to the predator biomass (the more they are, the more they eat. But the proportionality is modulated by a Michaelis-Menten function of the prey/predator ratio. Overall, the second term of equation \ref{spbalance} can be written:
\\
\begin{eqnarray}
%species loss
\omega_{i}=D_i + G_i
\label{destruction}
\end{eqnarray}
\section{Mass balance for the predators}
%*****************************************************
The reproduction rate of predators is set to their grazing rate, following the principle that they are tight to the disponibility of ressources. The number of grazed species for each predator is fixed randomly. Some of them are thus specialist (feeding on few species), and other generalist (feeding on many species). Predators are allowed to feed on other predators. This is once again randomly fixed. The death rate of predator is calculated in the same way as the death rate of primary producers.
\section{Mass balance for the super predators}
%***************************************************
Predators of the trophic level 3 behave as predator of the trophic level 2, with the notable exception that they cannot feed on each other. The $D_i$ terms is thus the only term appearing in the calculation of $\omega_i$.
\section{Pelagic carbonate producers}
%***************************************************
A random number of primary producers are assumed to be carbonate shell producers. No more than 20\% of the primary producer species can be carbonate producers (this is an adjustable parameter). For each surficial oceanic reservoir, the ECOWEB module calculates the ratio between the biomass of primary producers building carbonate shells, and the total biomass of primary producers. This ratio is sent to GEOCLIM which translate it into a carbonate flux as a function of the saturation state of the seawater with respect to calcite. Note that if the surface water becomes undersaturated, the carbonate primary producers undergo extinction ($\alpha_i$ is set to zero).
\section{Extinction}
%----------------------
If, for any given reason, the biomass of a species falls below 1\% of its original steady-state value, the species undergoes extinction. $\alpha_i$ is set to zero, translating the fact that the critical threshold below which reproduction is not more possible has been reached. The threshold of 1\% is an adjustable parameter. $\alpha_i$ is maintained to zero even if favorable conditions are restores over the course of the simulation.
%ecoweb scheme
\begin{center}
\includegraphics[width=10cm]{/Users/yves/fortran/GEOCLIM2/description/biodiv_scheme.jpg}\\
\small{Schematic view of the ECOWEB module}\\
\end{center}
\end{document}
|
lemma islimpt_approachable_real: fixes s :: "real set" shows "x islimpt s \<longleftrightarrow> (\<forall>e>0. \<exists>x'\<in> s. x' \<noteq> x \<and> \<bar>x' - x\<bar> < e)"
|
-- ch3 example 3.16
import Statistics.Distribution
import Statistics.Distribution.Hypergeometric
h :: HypergeometricDistribution
h = hypergeometric m l k
where
m = 5 -- r
l = 20 -- N of population size
k = 10 -- n of samplie size
-- k elements chosen from
-- l population, with
-- m elements of one type and (l-m) of the other
main :: IO ()
main = do
putStrLn "Among 20, 10 are randomely selected from; what is the probability that the 10 include 5 best."
putStrLn $ "The syntax is m=r, l=N, k=r, y=k and:"
putStrLn $ "p 5 = " ++ show (probability h 5)
|
Lemma deMorgen: forall x y:Prop, not (x \/ y) <-> not x /\ not y.
Proof.
intros.
unfold not.
split.
- intros.
split.
+ intros.
apply H.
left.
exact H0.
+ intros.
apply H.
right.
assumption.
- intros.
destruct H.
destruct H0.
+ apply H.
assumption.
+ apply H1.
assumption.
Qed.
|
# Densenet decoder encoder with intermediate fully connected layers and dropout
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.nn.functional as F
import functools
from torch.autograd import gradcheck
from torch.autograd import Function
from torch.autograd import Variable
from torch.autograd import gradcheck
from torch.autograd import Function
import numpy as np
def add_coordConv_channels(t):
n,c,h,w=t.size()
xx_channel=np.ones((h, w))
xx_range=np.array(range(h))
xx_range=np.expand_dims(xx_range,-1)
xx_coord=xx_channel*xx_range
yy_coord=xx_coord.transpose()
xx_coord=xx_coord/(h-1)
yy_coord=yy_coord/(h-1)
xx_coord=xx_coord*2 - 1
yy_coord=yy_coord*2 - 1
xx_coord=torch.from_numpy(xx_coord).float()
yy_coord=torch.from_numpy(yy_coord).float()
if t.is_cuda:
xx_coord=xx_coord.cuda()
yy_coord=yy_coord.cuda()
xx_coord=xx_coord.unsqueeze(0).unsqueeze(0).repeat(n,1,1,1)
yy_coord=yy_coord.unsqueeze(0).unsqueeze(0).repeat(n,1,1,1)
t_cc=torch.cat((t,xx_coord,yy_coord),dim=1)
return t_cc
class DenseBlockEncoder(nn.Module):
def __init__(self, n_channels, n_convs, activation=nn.ReLU, args=[False]):
super(DenseBlockEncoder, self).__init__()
assert(n_convs > 0)
self.n_channels = n_channels
self.n_convs = n_convs
self.layers = nn.ModuleList()
for i in range(n_convs):
self.layers.append(nn.Sequential(
nn.BatchNorm2d(n_channels),
activation(*args),
nn.Conv2d(n_channels, n_channels, 3, stride=1, padding=1, bias=False),))
def forward(self, inputs):
outputs = []
for i, layer in enumerate(self.layers):
if i > 0:
next_output = 0
for no in outputs:
next_output = next_output + no
outputs.append(next_output)
else:
outputs.append(layer(inputs))
return outputs[-1]
# Dense block in encoder.
class DenseBlockDecoder(nn.Module):
def __init__(self, n_channels, n_convs, activation=nn.ReLU, args=[False]):
super(DenseBlockDecoder, self).__init__()
assert(n_convs > 0)
self.n_channels = n_channels
self.n_convs = n_convs
self.layers = nn.ModuleList()
for i in range(n_convs):
self.layers.append(nn.Sequential(
nn.BatchNorm2d(n_channels),
activation(*args),
nn.ConvTranspose2d(n_channels, n_channels, 3, stride=1, padding=1, bias=False),))
def forward(self, inputs):
outputs = []
for i, layer in enumerate(self.layers):
if i > 0:
next_output = 0
for no in outputs:
next_output = next_output + no
outputs.append(next_output)
else:
outputs.append(layer(inputs))
return outputs[-1]
class DenseTransitionBlockEncoder(nn.Module):
def __init__(self, n_channels_in, n_channels_out, mp, activation=nn.ReLU, args=[False]):
super(DenseTransitionBlockEncoder, self).__init__()
self.n_channels_in = n_channels_in
self.n_channels_out = n_channels_out
self.mp = mp
self.main = nn.Sequential(
nn.BatchNorm2d(n_channels_in),
activation(*args),
nn.Conv2d(n_channels_in, n_channels_out, 1, stride=1, padding=0, bias=False),
nn.MaxPool2d(mp),
)
def forward(self, inputs):
return self.main(inputs)
class DenseTransitionBlockDecoder(nn.Module):
def __init__(self, n_channels_in, n_channels_out, activation=nn.ReLU, args=[False]):
super(DenseTransitionBlockDecoder, self).__init__()
self.n_channels_in = n_channels_in
self.n_channels_out = n_channels_out
self.main = nn.Sequential(
nn.BatchNorm2d(n_channels_in),
activation(*args),
nn.ConvTranspose2d(n_channels_in, n_channels_out, 4, stride=2, padding=1, bias=False),
)
def forward(self, inputs):
return self.main(inputs)
## Dense encoders and decoders for image of size 128 128
class waspDenseEncoder128(nn.Module):
def __init__(self, nc=1, ndf = 32, ndim = 128, activation=nn.LeakyReLU, args=[0.2, False], f_activation=nn.Tanh, f_args=[]):
super(waspDenseEncoder128, self).__init__()
self.ndim = ndim
self.main = nn.Sequential(
# input is (nc) x 128 x 128
nn.BatchNorm2d(nc),
nn.ReLU(True),
nn.Conv2d(nc, ndf, 4, stride=2, padding=1),
# state size. (ndf) x 64 x 64
DenseBlockEncoder(ndf, 6),
DenseTransitionBlockEncoder(ndf, ndf*2, 2, activation=activation, args=args),
# state size. (ndf*2) x 32 x 32
DenseBlockEncoder(ndf*2, 12),
DenseTransitionBlockEncoder(ndf*2, ndf*4, 2, activation=activation, args=args),
# state size. (ndf*4) x 16 x 16
DenseBlockEncoder(ndf*4, 16),
DenseTransitionBlockEncoder(ndf*4, ndf*8, 2, activation=activation, args=args),
# state size. (ndf*4) x 8 x 8
DenseBlockEncoder(ndf*8, 16),
DenseTransitionBlockEncoder(ndf*8, ndf*8, 2, activation=activation, args=args),
# state size. (ndf*8) x 4 x 4
DenseBlockEncoder(ndf*8, 16),
DenseTransitionBlockEncoder(ndf*8, ndim, 4, activation=activation, args=args),
f_activation(*f_args),
)
def forward(self, input):
input=add_coordConv_channels(input)
output = self.main(input).view(-1,self.ndim)
#print(output.size())
return output
class waspDenseDecoder128(nn.Module):
def __init__(self, nz=128, nc=1, ngf=32, lb=0, ub=1, activation=nn.ReLU, args=[False], f_activation=nn.Hardtanh, f_args=[]):
super(waspDenseDecoder128, self).__init__()
self.main = nn.Sequential(
# input is Z, going into convolution
nn.BatchNorm2d(nz),
activation(*args),
nn.ConvTranspose2d(nz, ngf * 8, 4, 1, 0, bias=False),
# state size. (ngf*8) x 4 x 4
DenseBlockDecoder(ngf*8, 16),
DenseTransitionBlockDecoder(ngf*8, ngf*8),
# state size. (ngf*4) x 8 x 8
DenseBlockDecoder(ngf*8, 16),
DenseTransitionBlockDecoder(ngf*8, ngf*4),
# state size. (ngf*2) x 16 x 16
DenseBlockDecoder(ngf*4, 12),
DenseTransitionBlockDecoder(ngf*4, ngf*2),
# state size. (ngf) x 32 x 32
DenseBlockDecoder(ngf*2, 6),
DenseTransitionBlockDecoder(ngf*2, ngf),
# state size. (ngf) x 64 x 64
DenseBlockDecoder(ngf, 6),
DenseTransitionBlockDecoder(ngf, ngf),
# state size (ngf) x 128 x 128
nn.BatchNorm2d(ngf),
activation(*args),
nn.ConvTranspose2d(ngf, nc, 3, stride=1, padding=1, bias=False),
f_activation(*f_args),
)
# self.smooth=nn.Sequential(
# nn.Conv2d(nc, nc, 1, stride=1, padding=0, bias=False),
# f_activation(*f_args),
# )
def forward(self, inputs):
# return self.smooth(self.main(inputs))
return self.main(inputs)
class dnetccnl(nn.Module):
#in_channels -> nc | encoder first layer
#filters -> ndf | encoder first layer
#img_size(h,w) -> ndim
#out_channels -> optical flow (x,y)
def __init__(self, img_size=128, in_channels=1, out_channels=2, filters=32,fc_units=100):
super(dnetccnl, self).__init__()
self.nc=in_channels
self.nf=filters
self.ndim=img_size
self.oc=out_channels
self.fcu=fc_units
self.encoder=waspDenseEncoder128(nc=self.nc+2,ndf=self.nf,ndim=self.ndim)
self.decoder=waspDenseDecoder128(nz=self.ndim,nc=self.oc,ngf=self.nf)
# self.fc_layers= nn.Sequential(nn.Linear(self.ndim, self.fcu),
# nn.ReLU(True),
# nn.Dropout(0.25),
# nn.Linear(self.fcu,self.ndim),
# nn.ReLU(True),
# nn.Dropout(0.25),
# )
def forward(self, inputs):
encoded=self.encoder(inputs)
encoded=encoded.unsqueeze(-1).unsqueeze(-1)
decoded=self.decoder(encoded)
# print torch.max(decoded)
# print torch.min(decoded)
return decoded
|
"""Influence based model interpretation methods in NvTK.
Influence quantified the Feed Forward Modification/Nullification of input,
which measured the influence on each single task.
"""
import torch
import logging
import itertools
import numpy as np
import pandas as pd
__all__ = ["foldchange", "correlation_ratio",
"channel_target_influence", "layer_channel_combination_influence",
"input_channel_target_influence", "input_layer_channel_combination_influence"]
def foldchange(origin, modified):
"""caculate the fold change between modified and origin outputs."""
return modified / origin
# return np.square(modified - origin)
# hook
class ModifyOutputHook():
def __init__(self, module):
self.hook = module.register_forward_hook(self.hook_fn)
self.channels = None
self.channel = 0
def hook_fn(self, module, input, output):
for channel in self.channels:
self.channel = channel
if isinstance(module, torch.nn.modules.conv.Conv1d):
output_channel = output[:,self.channel,:]
output[:,self.channel,:] = torch.zeros_like(output_channel).to(output_channel.device)#output_channel.mean()
elif isinstance(module, torch.nn.modules.linear.Linear):
output_channel = output[:,self.channel]
output[:,self.channel] = torch.zeros_like(output_channel).to(output_channel.device)#output_channel.mean()
# logging.info(output_channel[:5].cpu().detach().numpy())
# logging.info(output_channel.mean().cpu().detach().numpy())
return output
def step_channel(self, idx):
if isinstance(idx, (list, tuple)):
self.channels = idx
elif isinstance(idx, int):
self.channels = [idx]
def get_current_channel(self):
return self.channel
def close(self):
self.hook.remove()
class ModifyInputHook():
def __init__(self, module):
self.hook = module.register_forward_pre_hook(self.hook_fn)
self.channels = None
self.channel = 0
def hook_fn(self, module, input):
for channel in self.channels:
self.channel = channel
if isinstance(module, torch.nn.modules.conv.Conv1d):
input_channel = input[0][:,self.channel,:]
input[0][:,self.channel,:] = torch.zeros_like(input_channel).to(input_channel.device)#input_channel.mean()
elif isinstance(module, torch.nn.modules.linear.Linear):
input_channel = input[0][:,self.channel]
input[0][:,self.channel] = torch.zeros_like(input_channel).to(input_channel.device)#input_channel.mean()
# logging.info(input_channel[:5].cpu().detach().numpy())
# logging.info(input_channel.mean().cpu().detach().numpy())
return input
def step_channel(self, idx):
if isinstance(idx, (list, tuple)):
self.channels = idx
elif isinstance(idx, int):
self.channels = [idx]
def get_current_channel(self):
return self.channel
def close(self):
self.hook.remove()
def channel_target_influence(model, hook_module, data_loader, device=torch.device("cuda")):
# criterion = torch.nn.BCELoss(reduction='none').to(device) # gene * cell
target, pred_orig, loss_orig, pred_modified_foldchange = [], [], [], []
# a normal feed-forward
model.eval()
with torch.no_grad():
for x_tensor, t in data_loader:
x_tensor = x_tensor.to(device)
t = t.to(device)
output = model(x_tensor)
# loss = criterion(output, t)
target.append(t.cpu().data.numpy())
pred_orig.append(output.cpu().data.numpy())
# loss_orig.append(loss.cpu().data.numpy())
target = np.vstack(target)
pred_orig = np.vstack(pred_orig)
# loss_orig = np.vstack(loss_orig)
# feed-forward with ModifyOutputHook
if isinstance(hook_module, torch.nn.modules.conv.Conv1d):
out_channels = hook_module.out_channels # must hook on conv layer
elif isinstance(hook_module, torch.nn.modules.linear.Linear):
out_channels = hook_module.out_features # must hook on linear layer
Modifier = ModifyOutputHook(hook_module)
for idx in range(out_channels):
logging.info("modifying channel_%d..." % idx)
pred_modified, loss_modified = [], []
Modifier.step_channel(idx)
for x_tensor, t in data_loader:
x_tensor = x_tensor.to(device)
t = t.to(device)
output = model(x_tensor) # batch_size * output_size
# loss = criterion(output, t)
pred_modified.append(output.cpu().data.numpy())
# loss_modified.append(loss.cpu().data.numpy())
pred_modified = np.vstack(pred_modified)
# loss_modified = np.vstack(loss_modified)
fc = foldchange(pred_orig, pred_modified).mean(0) # output_size
# fc = foldchange(loss_orig, loss_modified).mean(0) # output_size
pred_modified_foldchange.append(fc)
Modifier.close()
return np.vstack(pred_modified_foldchange)
def layer_channel_combination_influence(model, hook_module, data_loader, device=torch.device("cuda")):
pred_orig, pred_modified_foldchange = [], []
# a normal feed-forward
model.eval()
with torch.no_grad():
for x_tensor, _ in data_loader:
x_tensor = x_tensor.to(device)
output = model(x_tensor).cpu().data.numpy()
pred_orig.append(output)
pred_orig = np.vstack(pred_orig)
# feed-forward with ModifyOutputHook
if isinstance(hook_module, torch.nn.modules.conv.Conv1d):
out_channels = hook_module.out_channels # must hook on conv layer
elif isinstance(hook_module, torch.nn.modules.linear.Linear):
out_channels = hook_module.out_features # must hook on linear layer
Modifier = ModifyOutputHook(hook_module)
for idx in itertools.combinations(range(out_channels), 2):
logging.info("modifying channel_%d&%d..." % idx)
pred_modified = []
Modifier.step_channel(idx)
for x_tensor, _ in data_loader:
x_tensor = x_tensor.to(device)
output_modified = model(x_tensor).cpu().data.numpy() # batch_size * output_size
pred_modified.append(output_modified)
pred_modified = np.vstack(pred_modified)
fc = foldchange(pred_orig, pred_modified).mean(0) # output_size
pred_modified_foldchange.append(fc)
Modifier.close()
return np.vstack(pred_modified_foldchange)
def input_channel_target_influence(model, hook_module, data_loader, device=torch.device("cuda")):
pred_orig, pred_modified_foldchange = [], []
model.eval()
with torch.no_grad():
for x_tensor, _ in data_loader:
x_tensor = x_tensor.to(device)
output = model(x_tensor).cpu().data.numpy()
pred_orig.append(output)
pred_orig = np.vstack(pred_orig)
if isinstance(hook_module, torch.nn.modules.conv.Conv1d):
in_channels = hook_module.in_channels # must hook on conv layer
elif isinstance(hook_module, torch.nn.modules.linear.Linear):
in_channels = hook_module.in_features # must hook on linear layer
Modifier = ModifyInputHook(hook_module)
for idx in range(in_channels):
logging.info("modifying channel_%d..." % idx)
pred_modified = []
Modifier.step_channel(idx)
for x_tensor, _ in data_loader:
x_tensor = x_tensor.to(device)
output_modified = model(x_tensor).cpu().data.numpy() # batch_size * output_size
pred_modified.append(output_modified)
pred_modified = np.vstack(pred_modified)
fc = foldchange(pred_orig, pred_modified).mean(0)
pred_modified_foldchange.append(fc)
Modifier.close()
return np.vstack(pred_modified_foldchange)
def input_layer_channel_combination_influence(model, hook_module, data_loader, device=torch.device("cuda")):
pred_orig, pred_modified_foldchange = [], []
model.eval()
with torch.no_grad():
for x_tensor, _ in data_loader:
x_tensor = x_tensor.to(device)
output = model(x_tensor).cpu().data.numpy()
pred_orig.append(output)
pred_orig = np.vstack(pred_orig)
if isinstance(hook_module, torch.nn.modules.conv.Conv1d):
in_channels = hook_module.in_channels # must hook on conv layer
elif isinstance(hook_module, torch.nn.modules.linear.Linear):
in_channels = hook_module.in_features # must hook on linear layer
Modifier = ModifyInputHook(hook_module)
for idx in itertools.combinations(range(in_channels), 2):
logging.info("modifying channel_%d&%d..." % idx)
pred_modified = []
Modifier.step_channel(idx)
for x_tensor, _ in data_loader:
x_tensor = x_tensor.to(device)
output_modified = model(x_tensor).cpu().data.numpy() # batch_size * output_size
pred_modified.append(output_modified)
pred_modified = np.vstack(pred_modified)
fc = foldchange(pred_orig, pred_modified).mean(0)
pred_modified_foldchange.append(fc)
Modifier.close()
return np.vstack(pred_modified_foldchange)
def correlation_ratio(categories, measurements):
"""Correlation Ration (ETA) between categories and measurements."""
fcat, _ = pd.factorize(categories)
cat_num = np.max(fcat)+1
y_avg_array = np.zeros(cat_num)
n_array = np.zeros(cat_num)
for i in range(0,cat_num):
cat_measures = measurements[np.argwhere(fcat == i).flatten()]
n_array[i] = len(cat_measures)
y_avg_array[i] = np.average(cat_measures)
y_total_avg = np.sum(np.multiply(y_avg_array,n_array))/np.sum(n_array)
numerator = np.sum(np.multiply(n_array,np.power(np.subtract(y_avg_array,y_total_avg),2)))
denominator = np.sum(np.power(np.subtract(measurements,y_total_avg),2))
if numerator == 0:
eta = 0.0
else:
eta = numerator/denominator
return eta
|
[STATEMENT]
lemma rotate_toppos_inv:"rotate_toppos w1 w2 \<Longrightarrow> (kauff_mat w1) = (kauff_mat w2)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. rotate_toppos w1 w2 \<Longrightarrow> kauff_mat w1 = kauff_mat w2
[PROOF STEP]
unfolding rotate_toppos_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. w1 = basic [vert, over] \<circ> basic [cap, vert] \<and> w2 = basic [brick.under, vert] \<circ> basic [vert, cap] \<Longrightarrow> kauff_mat w1 = kauff_mat w2
[PROOF STEP]
using rotate_toppos_kauff_mat
[PROOF STATE]
proof (prove)
using this:
kauff_mat (basic [vert, over] \<circ> basic [cap, vert]) = kauff_mat (basic [brick.under, vert] \<circ> basic [vert, cap])
goal (1 subgoal):
1. w1 = basic [vert, over] \<circ> basic [cap, vert] \<and> w2 = basic [brick.under, vert] \<circ> basic [vert, cap] \<Longrightarrow> kauff_mat w1 = kauff_mat w2
[PROOF STEP]
by auto
|
# Autoregressive flows and RealNVP
```python
from IPython.display import Image
```
This reading contains an overview of normalising flows, and introduces two popular normalising flow models: masked autoregressive flow (MAF) and RealNVP.
You'll also learn about the considerations in different architectures and the tradeoff between computational complexity and learning power.
## Introduction
Before any theory, we'll discuss an example of how normalizing flows work. Suppose you have a standard normal distribution (mean 0, variance 1). It has a single mode at 0, so, even after scaling and shifting, can't be fit well to data with two modes. However, you've seen how bijectors applied to distributions can create other distributions. A natural question is then: can we create a bimodal distribution (one with two modes) from a bijector applied to a standard normal distribution? It turns out that this is possible with the `Softsign` bijector. This is a differentiable approximation to the sign function (1 if $x$ is nonnegative, -1 if $x$ is negative). Passing a standard normal distribution through this bijector transforms the probability distribution as follows:
```python
# Run this cell to download and view an example transformed distribution
!wget -q -O normal_to_bimodal.png --no-check-certificate "https://docs.google.com/uc?export=download&id=1H8hY33aWjmpoa_mqAKQ7Xma2yfR6vr2E"
Image("normal_to_bimodal.png", width=1000)
```
As you can see, the bijector created a bimodal distribution from a standard normal one! This is just one from a huge class of possible bijectors available in TensorFlow Probability. Furthermore, since you can chain them together, it's possible to create very complicated bijectors that change standard distributions (e.g. a normal) to very complicated ones. This is how a normalizing flow works: it creates a complicated distribution by applying a bijector to a simple, well-understood and computationally implemented distribution (such as a Gaussian). In this reading, you'll learn how this works and see some implementations from previous research.
## Normalizing flows
### The one-dimensional case
The main idea of normalizing flows is to create a random variable $X$ (with complicated distribution $P$) by applying a bijector $f$ to a random variable $Z$ (with a simple distribution). For example, suppose $Z \sim N(0, 1)$ has a standard normal distribution. The goal is to find a bijector $f$ so that $ X = f(Z) \sim P $ for some target distribution $P$. Under this transformation, we can calculate the log-density using the change of variables equation:
$$ \log p(x) = \log p(z) - \log \left| \frac{\partial f}{\partial z}(z) \right| $$
where $z = f^{-1}(x)$.
Finding an $f$ that changes the distribution as required is not trivial: if the target distribution $P$ is very complex, a simple $f$ (such as a scale or shift) won't do the trick. However, we know that composing bijectors with one another creates more bijectors. Hence, one approach is to combine multiple simple bijectors $f_k$ to create a more complicated $f$:
$$ f = f_K \circ f_{K-1} \circ \ldots \circ f_1. $$
This series, where a base distribution is transformed by a series of bijectors after each other, is called a *normalizing flow*:
$$ z_0 = z$$
$$ z_k = f_k(z_{k-1}) \quad k=1, \ldots, K. $$
$$ x = z_K $$
Furthermore, the log-probability can be calculated by summing the contributions from each of the bijectors:
$$ \log p(x) = \log p(z) - \sum_{k=1}^K \log \left| \frac{\partial f_k}{\partial z_{k-1}}(z_{k-1}) \right| $$
This, however, still doesn't answer the question of how to construct the $f_k$. Usually, this is done by giving each $f_k$ some simple functional form, such as a scale and shift followed by a simple nonlinearity such as a sigmoid or ReLU. Each $f_k$ will have some parameters (such as the scale and shift values), and these can be learned via standard methods such as maximum likelihood estimation given some training data.
### The higher-dimensional case
The results above generalise straightforwardly to higher dimensions. Suppose that $\mathbf{z} \sim N(0, \mathbf{I})$ is distributed according to a multivariate unit Gaussian. The normalizing flow is then
$$ \mathbf{z}_0 = \mathbf{z}$$
$$ \mathbf{z}_k = \mathbf{f}_k(\mathbf{z}_{k-1}) \quad k=1, \ldots, K. $$
The log-probability involves the determinant of the transformation, as you'll remember from an earlier reading:
$$ \log p(\mathbf{x}) = \log p(\mathbf{z}) - \sum_{k=1}^K \log \left(\left| \det \left( \frac{\partial \mathbf{f}_k}{\partial \mathbf{z}_{k-1}}(\mathbf{z}_{k-1}) \right) \right|\right) $$
where we use the shorthand notation $\frac{\partial \mathbf{a}}{\partial \mathbf{b}}$ for the matrix with components $\frac{\partial \mathbf{a}_i}{\partial \mathbf{b}_j}$, where $i$ and $j$ index the components of $\mathbf{a}$ and $\mathbf{b}$ respectively.
Let's see an example of this from an [early research paper](https://arxiv.org/abs/1505.05770). In the figure below, the left column is the density of the target distribution $P$, and the right columns are the normalizing flow approximations with $K$=2, 8 and 32 bijectors (each with a simple form and some trainable parameters).
```python
# Run this cell to download and view example normalising flow approximations
!wget -q -O normalising_flow.png --no-check-certificate "https://docs.google.com/uc?export=download&id=16t_qyKcx3PblwB2ZRo4D0PDSxPmEugvh"
Image("normalising_flow.png", width=600)
```
As you can see, the approximation improves as the number of bijectors in the flow increases.
The reason this is useful is that it allows us to "learn" a complex distribution from data and then manipulate it. For example, to draw a new sample from the learned distribution, simply draw $\mathbf{z}$ from a standard unit Gaussian and transform it to the correct space using the normalizing flow (the series of bijectors).
**Note**: Throughout this reading, we use the index $k$ to refer to the bijector in the normalizing flow and indices $i$ and $j$ to refer to dimensions of the probability space (from 1 to $D$). From here on, for clarity, we consider a normalizing flow formed of only one bijector (with $K=1$), so that we may drop the indices $k$. The equation becomes $\mathbf{x} = \mathbf{f}(\mathbf{z})$. The reason for doing this is that we now use indices to refer to components of the vectors (e.g. $\mathbf{x} = [x_1, \ldots, x_D]^T)$ where $D$ is the dimensionality. For normalizing flows with $K>1$, the results apply for each $k$.
### Computational concerns
The above theory provides, in principle, a framework to learn and manipulate complex distributions by building them up from a simple one. There is one key difficulty, however, when going to a practical implementation. This comes from the need to calculate the determinant $\left| \det \left( \frac{\partial \mathbf{f}}{\partial \mathbf{z}} \right) \right|$ to determine the density of the transformed variable $\mathbf{x}$. The computational cost (number of operations) to calculate a determinant for a general matrix with $D$ dimensions scales as $\mathcal{O}(D^3)$. This makes general normalizing flow density calculations intractable, and some simplifications, as outlined below, are required.
### Autoregressive flows
For some matrices, calculating a determinant is easy. For example, for a lower or upper triangular matrix, the determinant is the product of the diagonal elements, of which there are $D$, meaning the determinant calculation scales linearly. Hence, to attain a linear scaling of the determinant in the number of dimensions, it is enough to enforce that $\frac{\partial f_i}{\partial z_j} = 0$ whenever $j > i$. In other words, the component $f_i$ depends only on $z_1, \ldots z_i$.
Autoregressive models can be reinterpreted as normalising flows that fulfil this requirement. These are models that model the joint density $p(\mathbf{x})$ as the product of conditionals $\prod_i p(x_i \mid \mathbf{x}_{1:i-1})$. For example, the conditionals could be parameterised as Gaussians:
$$
\begin{align}
p(x_i \mid\mathbf{x}_{1:i-1}) &= \mathcal{N}(x_i\mid\mu_i, \exp(\sigma_i)^2),\\
\text{where}\qquad \mu_i &= f_{\mu_i}(\mathbf{x}_{1:i-1})\\
\text{and}\qquad \sigma_i &= f_{\sigma_i}(\mathbf{x}_{1:i-1}).
\end{align}
$$
In the above equations, the mean and standard deviations of each conditional distribution are computed using (parameterised) functions of all previous variables. The above can alternatively be written as:
$$ x_i = \mu_i(\mathbf{x}_{1:i-1}) + \exp(\sigma_i(\mathbf{x}_{1:i-1})) z_i \quad \quad i=1, \ldots, D$$
where $z_i \sim N(0, 1)$ is sampled from a unit Gaussian. This last equation shows how the autoregressive model can be viewed as a transformation $f$ from the random variables $\mathbf{z}\in\mathbb{R}^D$ to the data $\mathbf{x}\in\mathbb{R}^D$.
This is an example of an *autoregressive* process where $x_i$ depends only on the components of $\mathbf{z}$ that are lower than or equal to $i$ but not any of the higher ones. The dependence on lower dimensions of $\mathbf{z}$ happens indirectly through the $x_i$ dependence in the $f_{\mu_i}$ and $f_{\sigma_i}$.
## Implementations
### Masked Autoregressive Flow (MAF)
An implementation of the above autoregressive flow appears in the following paper:
- George Papamakarios, Theo Pavlakou, Iain Murray (2017). [Masked Autoregressive Flow for Density Estimation](http://papers.nips.cc/paper/6828-masked-autoregressive-flow-for-density-estimation.pdf). In *Advances in Neural Information Processing Systems*, 2017.
Here, the authors use the above equations, using a masked autoencoder for distribution estimation ([MADE](http://proceedings.mlr.press/v37/germain15.pdf)) to implement the functions $f_{\mu_i}$ and $f_{\sigma_i}$. For clarity, let's see how $\mathbf{x}$ is sampled. This is done as follows:
1. $x_1 = f_{\mu_1} + \exp(f_{\sigma_1})z_1$ for $z_1 \sim N(0, 1)$
2. $x_2 = f_{\mu_2}(x_1) + \exp(f_{\sigma_2}(x_1))z_2$ for $z_2 \sim N(0, 1)$
2. $x_3 = f_{\mu_3}(x_1, x_2) + \exp(f_{\sigma_3}(x_1, x_2))z_3$ for $z_3 \sim N(0, 1)$
and so on. For the $f_{\mu_i}$ and $f_{\sigma_i}$, they use the same MADE network across the $i$, but mask the weights so that $x_i$ depends on $x_j$ for all $j<i$ but not any others. By re-using the same network, weights can be shared and the total number of parameters is significantly lower.
A note on computational complexity: determining $\mathbf{x}$ from $\mathbf{z}$ is relatively slow, since this must be done sequentially: first $x_1$, then $x_2$, and so on up to $x_D$. However, determining $\mathbf{z}$ from $\mathbf{x}$ is fast: each of the above equations can be solved for $z_i$ at the same time:
$$ z_i = \frac{x_i - f_{\mu_i}}{\exp(f_{\sigma_i})} \quad \quad i=0, \ldots, D-1$$
Hence, the *forward* pass through the bijector (sampling $\mathbf{x}$) is relatively slow, but the *inverse* pass (determining $\mathbf{z}$), which is used in the likelihood calculations used to train the model, is fast.
### Inverse Autoregressive Flow (IAF)
The inverse autoregressive flow reverses the dependencies to make the forward pass parallelisable but the inverse pass sequential. Details can be found in the following paper:
- Diederik Kingma, Tim Salimans, Rafal Jozefowicz, Xi Chen, Ilya Sutskever, Max Welling (2016). [Improved Variational Inference with Inverse Autoregressive Flow](http://papers.nips.cc/paper/6581-improved-variational-inference-with-inverse-autoregressive-flow.pdf). In *Advances in Neural Information Processing Systems*, 2016.
It uses the same equations:
$$ x_i = \mu_i + \exp(\sigma_i) z_i \quad \quad i=1, \ldots, D$$
but has the scale and shift functions depend on the $z_i$ instead of the $x_i$:
$$ \mu_i = f_{\mu_i}(z_1, \ldots, z_{i-1}) \quad \quad \sigma_i = f_{\sigma_i}(z_1, \ldots, z_{i-1}).$$
Note that now the forward equation (determining $\mathbf{x}$ from $\mathbf{z}$) can be parallelised, but the reverse transformations require determining $z_1$, followed by $z_2$, etc. and must hence be solved in sequence.
### Real-NVP and NICE
A further simplification of these approaches can be found in these papers:
- Laurent Dinh, Jascha Sohl-Dickstein, Samy Bengio (2016). [Density estimation using Real NVP](https://arxiv.org/abs/1605.08803).
- Laurent Dinh, David Krueger, Yoshua Bengio (2014). [NICE: Non-linear Independent Components Estimation](https://arxiv.org/abs/1410.8516).
The first uses a reduced versions of the above equations, for some chosen $L$:
$$
\begin{align}
x_i &= z_i \qquad &i = 1, \ldots, d \\
x_i &= \mu_i + \exp(\sigma_i) z_i \qquad &i = d+1, \ldots D
\end{align}
$$
where
$$
\begin{align}
\mu_i &= f_{\mu_i}(z_1, \ldots, z_{d})\\
\sigma_i &= f_{\sigma_i}(z_1, \ldots, z_{d})
\end{align}
$$
Hence, nothing happens for the first $d$ dimensions, but the $z_i$ values across these values transform the $x_i$ values for remaining $D-d$. Note that, in this case, both the forward and backward pass of the flow can be done fully in parallel. The second paper is even simpler, and omits the scale term altogether.
There is, of course, a catch: such a simple form means the flow typically needs a lot of bijections (a high $K$ value) to be able to describe complicated distributions. Furthermore, the dimensions that are transformed ($D-L$ in total) and not transformed ($L$ in total) must be permuted in the different bijections: otherwise the first $L$ dimensions of $\mathbf{z}$ are never changed throughout the whole normalizing flow, which greatly limits the expressive power. You'll be creating such a normalizing flow in this week's programming assignment.
### Further reading and resources
Besides the papers cited above, there are two great blog posts that explain that material as well:
- [Normalizing Flows](http://akosiorek.github.io/ml/2018/04/03/norm_flows.html) by Adam Kosiorek
- [Normalizing Flows Tutorial](https://blog.evjang.com/2018/01/nf1.html) by Eric Jang.
Both of these offer slightly more detail than we have space for here. They also have some great visuals. Happy reading and have fun implementing these ideas in the next few lessons!
|
function[]=jlab_addpath
%JLAB_ADDPATH Adds JLAB and JDATA subdirectories to your Matlab search path.
%
% This script adds JLAB subdirectories to your Matlab search path, as
% well as the JDATA directory if it is found to exist.
% __________________________________________________________________
% This is part of JLAB --- type 'help jlab' for more information
% (C) 2015--2019 J.M. Lilly --- type 'help jlab_license' for details
%First, find the path to JLAB
fullpath=which('jlab_license');
jlab_path=fullpath(1:end-15);
bool=real(jlab_path)==real('\');
jlab_path(bool)='/';
%jlab_path
for k=1:2
if k==1
disp('Adding JLAB subdirectories to your Matlab search path.')
if exist(jlab_path)
jlab_addpath_subdirectories(jlab_path);
end
end
if k==2
jlab_path=[jlab_path(1:end-5) '/jdata'];
if exist(jlab_path)
disp('Looks like you have JDATA installed; adding this to your path also.')
addpath(jlab_path)
jlab_addpath_subdirectories(jlab_path);
end
end
end
clear i j k dirlist dirlisti jlab_path fullpath bool
function[]=jlab_addpath_subdirectories(path)
dirlist=dir(path);
for i=1:length(dirlist)
if dirlist(i).isdir
if ~strcmpi(dirlist(i).name(1),'.')
%dirlist(i).name
addpath([path '/' dirlist(i).name])
dirlisti=dir([path '/' dirlist(i).name]);
for j=1:length(dirlisti)
if dirlisti(j).isdir
if ~strcmpi(dirlisti(j).name(1),'.')
%[path '/' dirlist(i).name '/' dirlisti(j).name]
addpath([path '/' dirlist(i).name '/' dirlisti(j).name]);
end
end
end
end
end
end
|
#redirect Design Museum
|
library('meta')
# load all data
all_data <- read.csv('testsets/test_input.csv')
# get all outcomes
ocns = unique(all_data$outcome)
###########################################################
# Generate tests for OR fixed and random with MH/DL/nohak
###########################################################
# the final dataframe for output
df_rsts = data.frame()
# start count time
start_time <- Sys.time()
for (i in 1:length(ocns)) {
ocn = ocns[i]
df <- all_data[all_data$outcome == ocn, c('study', 'Et', 'Nt', 'Ec', 'Nc')]
# get the result of this study
r <- metabin(
Et,
Nt,
Ec,
Nc,
data = df,
studlab = study,
sm = "OR",
method = "MH",
method.tau = "DL",
prediction = FALSE,
hakn = FALSE
)
df_rst = data.frame(
"outcome" = c(paste(ocn)),
"sm" = c('OR'),
"TE.fixed" = c(r$TE.fixed),
"lower.fixed" = c(r$lower.fixed),
"upper.fixed" = c(r$upper.fixed),
"TE.random" = c(r$TE.random),
"lower.random" = c(r$lower.random),
"upper.random" = c(r$upper.random),
"I2" = c(r$I2),
"tau2" = c(r$tau2),
"pval.Q" = c(r$pval.Q)
)
# merge this record
df_rsts = rbind(df_rsts, df_rst)
}
end_time <- Sys.time()
print(paste0('Spent: ', end_time - start_time, ' for OR fixed and random'))
# print(df_rsts)
write.csv(
df_rsts,
file='testsets/test_result_OR.csv',
row.names = FALSE
)
###########################################################
# Generate tests for OR fixed and random with MH/DL/nohak
###########################################################
# the final dataframe for output
df_rsts = data.frame()
# start count time
start_time <- Sys.time()
for (i in 1:length(ocns)) {
ocn = ocns[i]
df <- all_data[all_data$outcome == ocn, c('study', 'Et', 'Nt', 'Ec', 'Nc')]
# get the result of this study
r <- metabin(
Et,
Nt,
Ec,
Nc,
data = df,
studlab = study,
sm = "RR",
method = "MH",
method.tau = "DL",
prediction = FALSE,
hakn = FALSE
)
df_rst = data.frame(
"outcome" = c(paste(ocn)),
"sm" = c('RR'),
"TE.fixed" = c(r$TE.fixed),
"lower.fixed" = c(r$lower.fixed),
"upper.fixed" = c(r$upper.fixed),
"TE.random" = c(r$TE.random),
"lower.random" = c(r$lower.random),
"upper.random" = c(r$upper.random),
"I2" = c(r$I2),
"tau2" = c(r$tau2),
"pval.Q" = c(r$pval.Q)
)
# merge this record
df_rsts = rbind(df_rsts, df_rst)
}
end_time <- Sys.time()
print(paste0('Spent: ', end_time - start_time, ' for RR fixed and random'))
# print(df_rsts)
write.csv(
df_rsts,
file='testsets/test_result_RR.csv',
row.names = FALSE
)
###########################################################
# Generate tests for INCD/PFT fixed and random with Inverse/DL/nohak
###########################################################
# the final dataframe for output
df_rsts = data.frame()
# start count time
start_time <- Sys.time()
for (i in 1:length(ocns)) {
ocn = ocns[i]
df <- all_data[all_data$outcome == ocn, c('study', 'Et', 'Nt', 'Ec', 'Nc')]
# get the result of this study
r <- metaprop(
Et,
Nt,
data = df,
studlab = study,
sm = "PFT",
method = "Inverse",
method.tau = "DL",
prediction = FALSE,
hakn = FALSE
)
df_rst = data.frame(
"outcome" = c(paste(ocn)),
"sm" = c('PFT'),
"TE.fixed" = c(r$TE.fixed),
"lower.fixed" = c(r$lower.fixed),
"upper.fixed" = c(r$upper.fixed),
"TE.random" = c(r$TE.random),
"lower.random" = c(r$lower.random),
"upper.random" = c(r$upper.random),
"I2" = c(r$I2),
"tau2" = c(r$tau2),
"pval.Q" = c(r$pval.Q)
)
# merge this record
df_rsts = rbind(df_rsts, df_rst)
}
end_time <- Sys.time()
print(paste0('Spent: ', end_time - start_time, ' for PFT fixed and random'))
# print(df_rsts)
write.csv(
df_rsts,
file='testsets/test_result_PFT.csv',
row.names = FALSE
)
|
While on a modelling assignment in India in 2009 , Fernandez successfully auditioned for Sujoy Ghosh 's fantasy drama Aladin , which marked her acting debut . Fernandez ' breakthrough role was in Mohit Suri 's psychological thriller Murder 2 ( 2011 ) , her first commercial success . This was followed by glamorous roles in the ensemble @-@ comedy Housefull 2 ( 2012 ) and its sequel Housefull 3 , and the action thriller Race 2 ( 2013 ) , all of which were box @-@ office successes . Her performance in the first of these garnered her an IIFA Award for Best Supporting Actress nomination . In 2014 , Fernandez played the leading lady in Sajid Nadiadwala 's Kick , which is one of the highest @-@ grossing Bollywood films of all time .
|
import phase0.litter
open cardinal
open_locale cardinal
universe u
namespace con_nf
variable [params.{u}]
/-- The type of sublitters. -/
structure sublitter : Type u :=
(litter : litter)
(carrier : set atom)
(subset : carrier ⊆ litter_set litter)
(diff_small : small (litter_set litter \ carrier))
namespace sublitter
variables {S S₁ S₂ : sublitter}
/-- Use sublitter.mk_eq_κ instead if possible. -/
lemma mk_S_eq_κ (S : sublitter) : #(S.carrier) = #κ :=
begin
have := mk_le_mk_of_subset S.subset,
rw mk_litter_set at this,
cases lt_or_eq_of_le this,
{ have := mk_diff_add_mk S.subset,
rw mk_litter_set at this,
cases (add_lt_of_lt κ_regular.aleph_0_le S.diff_small h).ne this, },
exact h,
end
instance : set_like sublitter atom :=
{ coe := λ S, S.carrier,
coe_injective' := begin
rintro ⟨i, N₁, h₁, h₂⟩ ⟨j, N₂, h₃, h₄⟩ (rfl : N₁ = N₂),
obtain ⟨e⟩ := cardinal.eq.mp (sublitter.mk_S_eq_κ ⟨i, N₁, h₁, h₂⟩),
have h₅ := h₁ (e.symm (arbitrary κ)).prop,
have h₆ := h₃ (e.symm (arbitrary κ)).prop,
rw mem_litter_set at h₅ h₆,
rw h₅ at h₆,
cases h₆,
refl,
end }
@[simp] lemma mk_eq_κ (S : sublitter) : #S = #κ := S.mk_S_eq_κ
@[simp] lemma mk_eq_κ' (S : sublitter) : #(S : set atom) = #κ := S.mk_S_eq_κ
@[simp] lemma carrier_eq_coe {S : sublitter} : S.carrier = S := rfl
@[simp] lemma coe_mk (L S subset diff_small) :
@coe sublitter (set atom) _ ⟨L, S, subset, diff_small⟩ = S := rfl
@[ext] lemma ext (h : (S₁ : set atom) = S₂) : S₁ = S₂ :=
set_like.coe_injective h
lemma fst_eq_of_mem {a : atom} (h : a ∈ S) : a.1 = S.litter := S.subset h
lemma mem_litter_set_of_mem {a : atom} (h : a ∈ S) : a ∈ litter_set S.litter := S.subset h
@[simp] lemma mem_mk {a : atom} {L S subset diff_small} :
a ∈ (⟨L, S, subset, diff_small⟩ : sublitter) ↔ a ∈ S := iff.rfl
@[simp] lemma litter_diff_eq (S : sublitter) : (S : set atom) \ litter_set S.litter = ∅ :=
set.eq_empty_of_forall_not_mem (λ a ha, ha.2 (S.subset ha.1))
lemma is_near_litter (S : sublitter) : is_near_litter S.litter S :=
begin
refine small.union S.diff_small _,
rw litter_diff_eq,
exact small_empty,
end
def to_near_litter (S : sublitter) : near_litter := ⟨S.litter, S, S.is_near_litter⟩
@[simp] lemma to_near_litter_litter (S : sublitter) : S.to_near_litter.1 = S.litter := rfl
@[simp] lemma coe_to_near_litter (S : sublitter) : (S.to_near_litter : set atom) = S := rfl
@[simp] lemma mem_to_near_litter (a : atom) : a ∈ S.to_near_litter ↔ a ∈ S := iff.rfl
lemma is_near_iff : is_near (S₁ : set atom) S₂ ↔ S₁.litter = S₂.litter :=
begin
refine ⟨λ h, _, λ h, _⟩,
{ obtain ⟨f⟩ := is_near.mk_inter h S₁.mk_eq_κ.symm.le,
rw [← fst_eq_of_mem (f (arbitrary κ)).prop.1, ← fst_eq_of_mem (f (arbitrary κ)).prop.2], },
{ refine S₁.is_near_litter.symm.trans _,
rw h,
exact S₂.is_near_litter, },
end
lemma inter_nonempty_iff : (S₁ ∩ S₂ : set atom).nonempty ↔ S₁.litter = S₂.litter :=
begin
refine ⟨λ h, _, λ h, _⟩,
{ obtain ⟨a, ha⟩ := h,
rw [← fst_eq_of_mem ha.1, fst_eq_of_mem ha.2], },
{ obtain ⟨f⟩ := is_near.mk_inter _ _,
exact ⟨_, (f (arbitrary κ)).prop⟩,
rw is_near_iff,
exact h,
rw mk_eq_κ', },
end
end sublitter
def litter.to_sublitter (L : litter) : sublitter :=
⟨L, litter_set L, subset_rfl, by rw [sdiff_self]; exact small_empty⟩
@[simp] lemma litter.litter_to_sublitter (L : litter) : L.to_sublitter.litter = L := rfl
@[simp] lemma litter.coe_to_sublitter (L : litter) :
(L.to_sublitter : set atom) = litter_set L := rfl
namespace sublitter
def rel_embedding (S : sublitter) :
((<) : S → S → Prop) ↪r ((<) : (litter_set S.litter) → (litter_set S.litter) → Prop) :=
⟨⟨λ a, ⟨a, S.subset a.prop⟩, λ a b h, subtype.coe_injective (subtype.mk_eq_mk.mp h)⟩,
λ a b, by simp only [function.embedding.coe_fn_mk, subtype.mk_lt_mk, subtype.coe_lt_coe]⟩
/-- The order type of a sublitter is `κ`. -/
lemma ordinal_type (S : sublitter) : ordinal.type ((<) : S → S → Prop) = (#κ).ord :=
begin
refine le_antisymm _ _,
{ rw ← S.litter.ordinal_type,
exact rel_embedding.ordinal_type_le S.rel_embedding, },
{ rw [cardinal.gc_ord_card, ordinal.card_type, mk_eq_κ], },
end
-- TODO: We can probably do this constructively, but this way is easier for now.
noncomputable def order_iso_κ (S : sublitter) : S ≃o κ :=
begin
refine order_iso.of_rel_iso_lt (nonempty.some _),
rw [← ordinal.type_eq, ordinal_type, ← κ_ord],
refl,
end
/-- There is a (unique) order isomorphism between any two sublitters. -/
noncomputable def order_iso (S T : sublitter) : S ≃o T :=
S.order_iso_κ.trans T.order_iso_κ.symm
@[simp] lemma order_iso_apply_mem {S T : sublitter} (a : S) : (S.order_iso T a : atom) ∈ T :=
(S.order_iso T a).prop
@[simp] lemma order_iso_apply_fst_eq {S T : sublitter} (a : S) :
(S.order_iso T a : atom).1 = T.litter :=
T.subset (S.order_iso T a).prop
lemma order_iso_congr_left {S T U : sublitter} (h : S = T) (a : S) :
(S.order_iso U a : atom) = T.order_iso U ⟨a, by rw ← h; exact a.2⟩ :=
by cases h; rw subtype.coe_eta
lemma order_iso_congr_right {S T U : sublitter} (h : T = U) (a : S) :
(S.order_iso T a : atom) = S.order_iso U a :=
by cases h; refl
def order_iso.subtype_iso {α β : Type*} [has_le α] [has_le β] (e : α ≃o β)
{p : α → Prop} {q : β → Prop} (hpq : ∀ a, p a ↔ q (e a)) :
{a // p a} ≃o {b // q b} :=
⟨e.subtype_equiv hpq, by simp only [rel_iso.coe_fn_to_equiv, equiv.subtype_equiv_apply,
subtype.mk_le_mk, order_iso.le_iff_le, subtype.coe_le_coe, iff_self, subtype.forall,
implies_true_iff]⟩
/-- There is a unique order isomorphism between corresponding subtypes of a well-order.
TODO: Can prove this without specialising to subtypes. -/
lemma order_iso.unique {α β : Type*}
[linear_order α] [αwf : well_founded ((<) : α → α → Prop)]
[linear_order β] [βwf : well_founded ((<) : β → β → Prop)]
(e : α ≃o β) {p : α → Prop} {q : β → Prop}
(hpq : ∀ a, p a ↔ q (e a)) (e' : {a // p a} ≃o {b // q b}) :
e' = e.subtype_iso hpq :=
begin
ext x,
obtain ⟨x, hx⟩ := x,
revert hx,
refine αwf.induction x _,
intros x ih hx,
rw subtype.coe_inj,
refine linarith.eq_of_not_lt_of_not_gt _ _ (λ h, _) (λ h, _),
{ have := ih ((e.subtype_iso hpq).symm (e' ⟨x, hx⟩)) _ _,
{ simp only [subtype.coe_eta, order_iso.apply_symm_apply, subtype.coe_inj,
order_iso.apply_eq_iff_eq, order_iso.symm_apply_eq] at this,
exact h.ne this, },
{ refine lt_of_lt_of_eq _ (subtype.coe_mk x hx),
have := (e.subtype_iso hpq).symm.strict_mono h,
rw order_iso.symm_apply_apply at this,
exact this, },
{ exact subtype.coe_prop _, }, },
{ have := ih (e'.symm (e.subtype_iso hpq ⟨x, hx⟩)) _ _,
{ simp only [subtype.coe_eta, order_iso.apply_symm_apply, subtype.coe_inj,
order_iso.apply_eq_iff_eq, order_iso.symm_apply_eq] at this,
have := h.trans_eq (congr_arg e' this),
rw order_iso.apply_symm_apply at this,
exact this.ne rfl, },
{ refine lt_of_lt_of_eq _ (subtype.coe_mk x hx),
have := e'.symm.strict_mono h,
rw order_iso.symm_apply_apply at this,
exact this, },
{ exact subtype.coe_prop _, }, },
end
/-- The intersection of two sublitters. -/
def meet (S T : sublitter) (h : S.litter = T.litter) : sublitter := {
litter := S.litter,
carrier := S ∩ T,
subset := (set.inter_subset_left _ _).trans S.subset,
diff_small := by rw set.diff_inter; exact small.union S.diff_small (h.symm ▸ T.diff_small),
}
/-- Transports the meet of sublitters `S` and `U` across the order isomorphism `S ≃o T`. -/
def order_iso_meet (S T U : sublitter) (h : S.litter = U.litter) : sublitter := {
litter := T.litter,
carrier := {a | ∃ (ha : a ∈ T), ((S.order_iso T).symm ⟨a, ha⟩ : atom) ∈ U},
subset := λ a ha, T.subset ha.some,
diff_small := begin
suffices : small ((T : set atom) \
{a | ∃ (ha : a ∈ T), ((S.order_iso T).symm ⟨a, ha⟩ : atom) ∈ U}),
{ refine small.mono (λ a ha, _) (small.union T.diff_small this),
by_cases a ∈ T,
exact or.inr ⟨h, ha.2⟩,
exact or.inl ⟨ha.1, h⟩, },
refine lt_of_le_of_lt _ U.diff_small,
refine ⟨⟨λ a, ⟨(S.order_iso T).symm ⟨a, a.prop.1⟩, _, _⟩, λ a b h, _⟩⟩,
{ rw ← h,
exact S.subset ((S.order_iso T).symm ⟨a, a.prop.1⟩).2, },
{ intro h,
exact a.prop.2 ⟨a.prop.1, h⟩, },
{ simpa only [subtype.mk_eq_mk, rel_iso.eq_iff_eq, subtype.coe_inj] using h, },
end,
}
end sublitter
end con_nf
|
# Copyright 2017-2019 Eric S. Tellez
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import StatsBase: predict, fit
export NearNeighborRegression, optimize!, predict, predict_proba
using Statistics
using SimilaritySearch:
Sequential, KnnResult, empty!
mutable struct NearNeighborRegression{IndexType,DataType}
dist::Function
X::IndexType
y::Vector{DataType}
k::Int
summarize::Function
function NearNeighborRegression(dist::Function, X::AbstractVector{ItemType}, y::AbstractVector{DataType}; summarize=mean, k::Int=1) where {ItemType, DataType}
index = fit(Sequential, X)
new{typeof(index), DataType}(dist, index, y, k, summarize)
end
end
function predict(nnc::NearNeighborRegression{IndexType,DataType}, vector) where {IndexType,DataType}
[predict_one(nnc, item) for item in vector]
end
function predict_one(nnc::NearNeighborRegression{IndexType,DataType}, item) where {IndexType,DataType}
res = KnnResult(nnc.k)
search(nnc.X, nnc.dist, item, res)
DataType[nnc.y[p.objID] for p in res] |> nnc.summarize
end
function _train_create_table_reg(dist::Function, train_X, train_y, test_X, k::Int)
index = fit(Sequential, train_X)
res = KnnResult(k)
function f(x)
empty!(res) # this is thread unsafe
search(index, dist, x, res)
[train_y[p.objID] for p in res]
end
f.(test_X)
end
function _train_predict(nnc::NearNeighborRegression{IndexType,DataType}, table, test_X, k) where {IndexType,DataType}
A = Vector{DataType}(undef, length(test_X))
for i in 1:length(test_X)
row = table[i]
A[i] = nnc.summarize(row[1:k])
end
A
end
function gmean(X)
prod(X)^(1/length(X))
end
function hmean(X)
d = 0.0
for x in X
d += 1.0 / x
end
length(X) / d
end
function optimize!(nnr::NearNeighborRegression, scorefun::Function; summarize_list=[mean, median, gmean, hmean], runs=3, trainratio=0.5, testratio=0.5, folds=0, shufflefolds=true)
mem = Dict{Tuple,Float64}()
function f(train_X, train_y, test_X, test_y)
_nnr = NearNeighborRegression(nnr.dist, train_X, train_y)
kmax = sqrt(length(train_y)) |> round |> Int
table = _train_create_table_reg(nnr.dist, train_X, train_y, test_X, kmax)
k = 2
while k <= kmax
_nnr.k = k - 1
for summarize in summarize_list
_nnr.summarize = summarize
pred_y = _train_predict(_nnr, table, test_X, _nnr.k)
score = scorefun(test_y, pred_y)
key = (k - 1, summarize)
mem[key] = get(mem, key, 0.0) + score
end
k += k
end
0
end
if folds > 1
kfolds(f, nnr.X.db, nnr.y, folds=folds, shuffle=shufflefolds)
bestlist = [(score/folds, conf) for (conf, score) in mem]
else
montecarlo(f, nnr.X.db, nnr.y, runs=runs, trainratio=trainratio, testratio=testratio)
bestlist = [(score/runs, conf) for (conf, score) in mem]
end
sort!(bestlist, by=x -> (-x[1], x[2][1]))
best = bestlist[1]
nnr.k = best[2][1]
nnr.summarize = best[2][2]
bestlist
end
|
r=0.68
https://sandbox.dams.library.ucdavis.edu/fcrepo/rest/collection/sherry-lehmann/catalogs/d7pp4q/media/images/d7pp4q-029/svc:tesseract/full/full/0.68/default.jpg Accept:application/hocr+xml
|
(* coq-robot (c) 2017 AIST and INRIA. License: LGPL-2.1-or-later. *)
From mathcomp Require Import all_ssreflect ssralg ssrint ssrnum rat.
From mathcomp Require Import closed_field polyrcf matrix mxalgebra mxpoly zmodp.
From mathcomp Require Import realalg complex fingroup perm.
From mathcomp.analysis Require Import boolp reals Rstruct classical_sets signed.
From mathcomp.analysis Require Import topology normedtype landau forms derive.
From mathcomp Require Import functions.
Require Import ssr_ext derive_matrix euclidean frame rot skew rigid.
(******************************************************************************)
(* This file is wip. It contains an on-going formalization of *)
(* [sciavicco] chap. 3. *)
(******************************************************************************)
(* contents:
5. Module BoundVect.
Module RFrame.
relative frame
(NB: to be moved to frame.v)
6. Section kinematics
velocity composition rule
7. Section link_velocity.
8. Lemma ang_vel_mx_Rz
example: angular velocity of Rz as a spinor
9. Section chain. (wip)
10. Section geometric_jacobian_computation.
geometric jacobian
11. Section scara_geometric_jacobian.
computation of SCARA's geometric jacobian
*)
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Import Order.TTheory GRing.Theory Num.Def Num.Theory.
Local Open Scope ring_scope.
Local Open Scope frame_scope.
Module BoundVect. (* i.e., point of application prescribed *)
Section bound_vector.
Variable T : ringType.
Record t (F : tframe T) := mk { endp : 'rV[T]_3 }.
Definition startp F (v : t F) : 'rV[T]_3 := \o{F}.
End bound_vector.
End BoundVect.
Notation bvec := BoundVect.t.
Coercion boundvectendp T (F : tframe T) (v : bvec F) := BoundVect.endp v.
Definition bvec0 T (F : tframe T) : bvec F := BoundVect.mk _ 0.
Reserved Notation "a \+b b" (at level 39).
Reserved Notation "a \-b b" (at level 39).
Section about_bound_vectors.
Variables (T : ringType) (F : tframe T).
Definition FramedVect_of_Bound (p : bvec F) : fvec F := `[ BoundVect.endp p $ F ].
Definition BoundVect_add (a b : bvec F) : bvec F :=
BoundVect.mk F (BoundVect.endp a + BoundVect.endp b).
Definition BoundFramed_add (a : bvec F) (b : fvec F) : bvec F :=
BoundVect.mk F (BoundVect.endp a + FramedVect.v b).
Local Notation "a \+b b" := (BoundFramed_add a b).
Lemma BoundFramed_addA (a : bvec F) (b c : fvec F) :
a \+b b \+b c = a \+b (b \+f c).
Proof. by rewrite /BoundFramed_add /= addrA. Qed.
Definition BoundVect_sub (F : tframe T) (a b : bvec F) : fvec F :=
`[ BoundVect.endp a - BoundVect.endp b $ F ].
Local Notation "a \-b b" := (BoundVect_sub a b).
Lemma bv_eq (a b : bvec F) : a = b :> 'rV[T]_3 -> a = b.
Proof. by move: a b => [a] [b] /= ->. Qed.
End about_bound_vectors.
Notation "a \+b b" := (BoundFramed_add a b).
Notation "a \-b b" := (BoundVect_sub a b).
Lemma derive1mx_BoundFramed_add (R : realFieldType) (F : tframe [ringType of R^o])
(Q : R -> bvec F) (Z : R -> fvec F) t :
derivable_mx (fun x => BoundVect.endp (Q x)) t 1 ->
derivable_mx (fun x => FramedVect.v (Z x)) t 1 ->
derive1mx (fun x => BoundVect.endp (Q x \+b Z x)) t =
derive1mx (fun x => BoundVect.endp (Q x)) t +
derive1mx (fun x => FramedVect.v (Z x)) t.
Proof.
move=> H H'.
rewrite (_ : (fun x : R => _) = (fun x : R => BoundVect.endp (Q x) +
(FramedVect.v (Z x)))); last by rewrite funeqE.
rewrite derive1mxD.
- by [].
- exact: H.
- exact H'.
Qed.
Module RFrame.
Section rframe.
Variable T : ringType.
Record t (F0 : tframe T) := mk {
o : bvec F0 ;
i : fvec F0 ;
j : fvec F0 ;
k : fvec F0 ;
F : tframe T ;
_ : BoundVect.endp o = \o{F} ;
_ : FramedVect.v i = F~i ;
_ : FramedVect.v j = F~j ;
_ : FramedVect.v k = F~k ;
}.
End rframe.
End RFrame.
Notation rframe := RFrame.t.
Coercion tframe_of_rframe R (F : tframe R) (F : rframe F) : tframe R := RFrame.F F.
Lemma RFrame_o T (F0 : tframe T) (F1 : rframe F0) :
BoundVect.endp (RFrame.o F1) = \o{RFrame.F F1}.
Proof. by destruct F1. Qed.
(* lemmas about relative frames *)
Lemma BoundVect0_fixed (R : realFieldType) T (F : tframe T) (F1 : R -> rframe F) t :
BoundVect.endp (bvec0 (F1 t)) = BoundVect.endp (bvec0 (F1 0)).
Proof. by []. Qed.
Section derivable_FromTo.
Lemma derivable_mx_FromTo' (R : realFieldType) (F : R -> tframe [ringType of R^o])
(G' : forall t, rframe (F t)) (G : forall t, rframe (F t)) t :
derivable_mx F t 1 -> derivable_mx G t 1 -> derivable_mx G' t 1 ->
derivable_mx (fun x => (G x) _R^ (G' x)) t 1.
Proof.
move=> HF HG HG' a b.
rewrite (_ : (fun x => _) = (fun x => row a (G x) *d row b (G' x))); last first.
by rewrite funeqE => t'; rewrite !mxE.
evar (f : 'I_3 -> R^o -> R^o).
rewrite (_ : (fun x => _) = \sum_i f i); last first.
rewrite funeqE => t'; rewrite dotmulE fct_sumE; apply: eq_bigr => /= i _.
rewrite !mxE /f; reflexivity.
rewrite {}/f.
apply: derivable_sum => i.
apply: derivableM; [exact: HG | exact: HG'].
Qed.
Lemma derivable_mx_FromTo (R : realFieldType) (F : R -> tframe [ringType of R^o])
(G : forall t, rframe (F t)) t :
derivable_mx F t 1 -> derivable_mx G t 1 ->
derivable_mx (fun x => (G x) _R^ (F x)) t 1.
Proof.
move=> HF HG a b.
have @G' : forall t0, rframe (F t0).
move=> t0.
exact: (@RFrame.mk _ _ (@BoundVect.mk _ _ \o{F t0}) `[(F t0)~i $ F t0] `[(F t0)~j $ F t0] `[(F t0)~k $ F t0] (F t0)).
apply: (@derivable_mx_FromTo' R F G' G).
by [].
by [].
rewrite {}/G' /=.
exact: HF.
Qed.
Lemma derivable_mx_FromTo_fixed (R : realFieldType)
(F : tframe [ringType of R^o]) (G : R -> rframe F) t :
derivable_mx G t 1 -> derivable_mx (fun x => (G x) _R^ F) t 1.
Proof.
move=> H; apply derivable_mx_FromTo; [move=> a b; exact: ex_derive | exact H].
Qed.
Lemma derivable_mx_FromTo_tr (R : realFieldType)
(F : tframe [ringType of R^o]) (G : R -> rframe F) t :
derivable_mx (fun x => F _R^ (G x)) t 1 = derivable_mx (fun x => F _R^ (G x)) t 1.
Proof. by rewrite trmx_derivable. Qed.
End derivable_FromTo.
(* the coordinate transformation of a point P1 from frame F1 to frame F
(eqn 2.33, 3.10) *)
Definition coortrans (R : realType) (F : tframe [ringType of R^o]) (F1 : rframe F)
(P1 : bvec F1) : bvec F :=
RFrame.o F1 \+b rmap F (FramedVect_of_Bound P1).
(* motion of P1 w.r.t. the fixed frame F (eqn B.2) *)
Definition motion (R : realType) (F : tframe [ringType of R^o]) (F1 : R -> rframe F)
(P1 : forall t, bvec (F1 t)) t : bvec F := coortrans (P1 t).
(* [sciavicco] p.351-352 *)
Section kinematics.
Variables (R : realType) (F : tframe [ringType of R^o]). (* fixed frame *)
Variable F1 : R -> rframe F. (* time-varying frame (origin and basis in F) *)
Hypothesis derivable_F1 : forall t, derivable_mx F1 t 1.
Hypothesis derivable_F1o : forall t, derivable_mx (@TFrame.o [ringType of R^o] \o F1) t 1.
Variable P1 : forall t, bvec (F1 t). (* point with coordinates in F1 *)
(* NB: compared with [sciavicco] p.351, P1 not necessarily fixed in F1 *)
Hypothesis derivable_mxP1 : forall t, derivable_mx (fun x => BoundVect.endp (P1 x)) t 1.
Let P : R -> bvec F := motion P1.
Variable Q1 : forall t, bvec (F1 t).
Hypothesis Q1_fixed_in_F1 : forall t, BoundVect.endp (Q1 t) = BoundVect.endp (Q1 0).
Let Q : R -> bvec F := motion Q1.
(* eqn B.3 *)
Lemma eqnB3 t : P t = Q t \+b rmap F (P1 t \-b Q1 t).
Proof.
rewrite /P /Q /motion /coortrans BoundFramed_addA; congr (_ \+b _).
apply fv_eq => /=; rewrite -mulmxDl; congr (_ *m _).
by rewrite addrCA subrr addr0.
Qed.
Lemma derivable_mx_Q t : derivable_mx (fun x => BoundVect.endp (Q x)) t 1.
Proof.
rewrite /Q /=; apply derivable_mxD.
move=> a b.
move: (@derivable_F1o t a b).
rewrite (_ : (fun x => \o{F1 x} a b) =
(fun x => BoundVect.endp (RFrame.o (F1 x)) a b)) // funeqE => x.
destruct (F1 x) => /=; by rewrite e.
apply derivable_mxM; last exact: derivable_mx_FromTo.
rewrite (_ : (fun x => _) = (fun _ => BoundVect.endp (Q1 0))); last first.
rewrite funeqE => x; by rewrite Q1_fixed_in_F1.
move=> a b; exact: ex_derive.
Qed.
Let Rot := fun t => (F1 t) _R^ F.
(* generalization of B.4 *)
Lemma velocity_composition_rule (t : R) :
derive1mx (fun x => BoundVect.endp (P x)) t =
derive1mx (fun x => BoundVect.endp (Q x)) t +
derive1mx P1 t *m Rot t (* rate of change of the coordinates P1 expressed in the frame F *) +
ang_vel Rot t *v FramedVect.v (P t \-b Q t).
Proof.
rewrite {1}(_ : P = fun t => Q t \+b rmap F (P1 t \-b Q1 t)); last first.
by rewrite funeqE => t'; rewrite eqnB3.
rewrite (derive1mx_BoundFramed_add (@derivable_mx_Q t)); last first.
apply derivable_mxM; last exact: derivable_mx_FromTo.
rewrite (_ : (fun x => _) = (fun x => FramedVect.v (FramedVect_of_Bound (P1 x)) -
FramedVect.v (FramedVect_of_Bound (Q1 0)))); last first.
rewrite funeqE => x; by rewrite /= Q1_fixed_in_F1.
apply: derivable_mxB => /=.
exact: derivable_mxP1.
move=> a b; exact: ex_derive.
rewrite -addrA; congr (_ + _).
rewrite [in LHS]/rmap [in LHS]/= derive1mxM; last 2 first.
rewrite {1}(_ : (fun x => _) = (fun x => BoundVect.endp (P1 x) -
BoundVect.endp (Q1 0))); last first.
by rewrite funeqE => ?; rewrite Q1_fixed_in_F1.
apply: derivable_mxB.
exact: derivable_mxP1.
move=> a b; exact: ex_derive.
exact: derivable_mx_FromTo.
rewrite derive1mxB; last 2 first.
exact: derivable_mxP1.
rewrite (_ : (fun x => _) = cst (BoundVect.endp (Q1 0))); last first.
by rewrite funeqE => x; rewrite Q1_fixed_in_F1.
exact: derivable_mx_cst.
congr (_*m _ + _).
rewrite [in X in _ + X = _](_ : (fun x => _) = cst (BoundVect.endp (Q1 0))); last first.
by rewrite funeqE => x; rewrite Q1_fixed_in_F1.
by rewrite derive1mx_cst subr0.
rewrite -spinE unspinK; last first.
rewrite ang_vel_mx_is_so; first by [].
move=> t'; by rewrite FromTo_is_O.
move=> t'; exact: derivable_mx_FromTo.
rewrite /ang_vel_mx mulmxA; congr (_ *m _).
rewrite /P /Q /= opprD addrACA subrr add0r mulmxBl -!mulmxA.
by rewrite orthogonal_mul_tr ?FromTo_is_O // !mulmx1.
Qed.
Hypothesis P1_fixed_in_F1 : forall t, BoundVect.endp (P1 t) = BoundVect.endp (P1 0).
(* eqn B.4 *)
Lemma velocity_composition_rule_spec (t : R) :
derive1mx (fun x => BoundVect.endp (P x)) t =
derive1mx (fun x => BoundVect.endp (Q x)) t +
ang_vel Rot t *v (FramedVect.v (P t \-b Q t)).
Proof.
rewrite velocity_composition_rule; congr (_ + _).
suff -> : derive1mx P1 t = 0 by rewrite mul0mx addr0.
apply/matrixP => a b; rewrite !mxE.
rewrite (_ : (fun x => _) = cst (P1 0 a b)); last first.
rewrite funeqE => x /=; by rewrite /boundvectendp (P1_fixed_in_F1 x).
by rewrite derive1_cst.
Qed.
End kinematics.
(* [sciavicco] p.81-82 *)
Section derivative_of_a_rotation_matrix_contd.
Variables (R : realType) (F : tframe [ringType of R^o]).
Variable F1 : R -> rframe F.
Hypothesis derivable_F1 : forall t, derivable_mx F1 t 1.
Variable p1 : forall t, bvec (F1 t).
Hypothesis derivable_mx_p1 : forall t, derivable_mx (fun x => BoundVect.endp (p1 x)) t 1.
Hypothesis derivable_F1o : forall t, derivable_mx (@TFrame.o [ringType of R^o] \o F1) t 1.
Definition p0 := motion p1.
Lemma eqn312 t :
derive1mx (fun x => BoundVect.endp (motion p1 x)) t =
derive1mx (fun x => BoundVect.endp (motion (fun=> bvec0 (F1 x)) t)) t +
derive1mx p1 t *m (F1 t) _R^ F +
ang_vel (fun t => (F1 t) _R^ F) t *v (p1 t *m (F1 t) _R^ F).
Proof.
rewrite (@velocity_composition_rule _ F _ derivable_F1 derivable_F1o p1 derivable_mx_p1
(fun t => bvec0 (F1 t)) (@BoundVect0_fixed _ _ _ F1)).
congr (_ + _ *v _).
by rewrite /= mul0mx addr0 addrAC subrr add0r.
Qed.
End derivative_of_a_rotation_matrix_contd.
Require Import screw.
(* [murray p.54] chapter 2, section 4.2*)
Section rigid_body_velocity.
Section spatial_velocity.
Variables (R : realType) (M : R -> 'M[R^o]_4).
Hypothesis derivableM : forall t, derivable_mx M t 1.
Hypothesis MSE : forall t, M t \in 'SE3[R].
Definition spatial_velocity t : 'M_4 := (M t)^-1 * derive1mx M t.
Definition spatial_lin_vel :=
let r : R -> 'M[R^o]_3 := @rot_of_hom _ \o M in
let p : R -> 'rV[R^o]_3:= @trans_of_hom _ \o M in
fun t => - p t *m (r t)^T *m derive1mx r t + derive1mx p t.
Lemma spatial_velocityE t :
let r : R -> 'M[R^o]_3 := @rot_of_hom _ \o M in
spatial_velocity t = block_mx (ang_vel_mx r t) 0 (spatial_lin_vel t) 0.
Proof.
move=> r.
rewrite /spatial_velocity.
transitivity (inv_hom (M t) * derive1mx M t) => //.
by rewrite inv_homE.
rewrite /inv_hom.
rewrite /hom.
rewrite derive1mx_SE //.
rewrite (_ : rot_of_hom (M t) = r t) // -/r.
rewrite -mulmxE.
rewrite (mulmx_block (r t)^T _ _ _ (derive1mx r t)).
rewrite !(mul0mx,add0r,mul1mx,mulmx0,trmx0,addr0,mulmx1).
by rewrite mulmxE -/(ang_vel_mx r t).
Qed.
Lemma spatial_velocity_in_se3 x : spatial_velocity x \in 'se3[[rcfType of R^o]].
Proof.
rewrite spatial_velocityE. set r := @rot_of_hom _.
rewrite qualifE block_mxKul block_mxKur block_mxKdr 2!eqxx 2!andbT.
rewrite ang_vel_mx_is_so // => t0.
by rewrite rotation_sub // rot_of_hom_is_SO.
exact: derivable_rot_of_hom.
Qed.
Lemma spatial_velocity_is_twist x :
let r : R -> 'M[R^o]_3 := @rot_of_hom _ \o M in
spatial_velocity x = wedge \T( spatial_lin_vel x , unspin (ang_vel_mx r x)).
Proof.
move=> r.
rewrite spatial_velocityE.
rewrite /wedge lin_tcoorE ang_tcoorE unspinK //.
rewrite ang_vel_mx_is_so // => t0.
by rewrite rotation_sub // rot_of_hom_is_SO.
exact: derivable_rot_of_hom.
Qed.
End spatial_velocity.
Section body_velocity.
Variables (R : realType) (M : R -> 'M[R^o]_4).
Hypothesis derivableM : forall t, derivable_mx M t 1.
Hypothesis MSE : forall t, M t \in 'SE3[R].
Definition body_velocity t : 'M_4 := derive1mx M t * (M t)^-1.
Definition body_lin_vel :=
let r : R -> 'M[R^o]_3 := @rot_of_hom _ \o M in
let p : R -> 'rV[R^o]_3:= @trans_of_hom _ \o M in
fun t => derive1mx p t *m (r t)^T.
Lemma body_ang_vel_is_so t : body_ang_vel_mx (@rot_of_hom _ \o M) t \is 'so[R]_3.
Proof.
rewrite /body_ang_vel_mx.
have : forall t, (@rot_of_hom [rcfType of R^o] \o M) t \is 'O[[ringType of R]]_3.
move=> t0; by rewrite rotation_sub // rot_of_hom_is_SO.
move/ang_vel_mx_is_so => /(_ (derivable_rot_of_hom derivableM))/(_ t).
rewrite /ang_vel_mx.
move/(conj_so (((rot_of_hom (T:=[rcfType of R^o]) \o M) t)^T)).
rewrite !mulmxA !trmxK orthogonal_mul_tr ?rotation_sub // ?rot_of_hom_is_SO //.
by rewrite mul1mx.
Qed.
Lemma body_velocityE t : let r : R -> 'M[R^o]_3 := @rot_of_hom _ \o M in
body_velocity t = block_mx (body_ang_vel_mx r t) 0 (body_lin_vel t) 0.
Proof.
move=> r.
rewrite /body_velocity.
transitivity (derive1mx M t * inv_hom (M t)).
by rewrite inv_homE.
rewrite /inv_hom.
rewrite /hom.
rewrite derive1mx_SE //.
rewrite (_ : rot_of_hom (M t) = r t) // -/r.
rewrite -mulmxE.
rewrite (mulmx_block (derive1mx r t) _ _ _ (r t)^T).
rewrite !(mul0mx,add0r,mul1mx,mulmx0,trmx0,addr0,mulmx1).
by rewrite -/(body_ang_vel_mx _) -/(body_lin_vel _).
Qed.
Lemma body_velocity_is_se x : body_velocity x \is 'se3[R].
Proof.
rewrite body_velocityE.
rewrite qualifE block_mxKul block_mxKur block_mxKdr 2!eqxx 2!andbT.
by rewrite body_ang_vel_is_so.
Qed.
End body_velocity.
Section spatial_body_adjoint.
Variables (R : realType) (M : R -> 'M[R^o]_4).
Hypothesis derivableM : forall t, derivable_mx M t 1.
Hypothesis MSE : forall t, M t \in 'SE3[R].
Lemma spatial_body_velocity x :
vee (spatial_velocity M x) = vee (body_velocity M x) *m Adjoint (M x).
Proof.
rewrite -/(SE3_action _ _) action_Adjoint; last by [].
congr vee; rewrite /spatial_velocity -mulmxE -mulmxA; congr (_ * _).
rewrite veeK; last by rewrite body_velocity_is_se.
by rewrite /body_velocity -mulmxA mulVmx ?mulmx1 // SE3_in_unitmx.
Qed.
End spatial_body_adjoint.
End rigid_body_velocity.
(* [sciavicco] p.83 *)
Section link_velocity.
Variables (R : realType) (F : tframe [ringType of R^o]).
Variable F1 : R -> rframe F.
Variable F2 : R -> rframe F.
Let o1 t : bvec F := RFrame.o (F1 t).
Let o2 t : bvec F := RFrame.o (F2 t).
Let r12 : forall t : R, bvec (F1 t) := fun t =>
BoundVect.mk (F1 t)
(FramedVect.v (rmap (F1 t) `[ \o{F2 t} - \o{F1 t} $ F ])).
Hypothesis derivable_F1 : forall t, derivable_mx F1 t 1.
Hypothesis derivable_F1o : forall t, derivable_mx (@TFrame.o [ringType of R^o] \o F1) t 1.
Hypothesis derivable_r12 : forall t, derivable_mx (fun x => BoundVect.endp (r12 x)) t 1.
Hypothesis derivable_F2 : forall t, derivable_mx F2 t 1.
Lemma eqn310' t : o2 t = o1 t \+b rmap F (FramedVect_of_Bound (r12 t)).
Proof.
rewrite /o2 /o1 /= /r12 /= /rmap /= /BoundFramed_add /=; apply bv_eq => /=.
rewrite -mulmxA FromTo_comp FromToI mulmx1 /= addrCA RFrame_o /=.
by rewrite subrr addr0 -RFrame_o.
Qed.
Definition w1 := ang_vel (fun t => (F1 t) _R^ F).
Lemma eqn314_helper t : FramedVect.v (rmap F `[r12 t $ F1 t]) = \o{F2 t} - \o{F1 t}.
Proof. by rewrite /= -mulmxA FromTo_comp FromToI mulmx1. Qed.
(* lin. vel. of Link i as a function of
the translational and rotational velocities of Link i-1 *)
Lemma eqn314 t : derive1mx o2 t = derive1mx o1 t +
FramedVect.v (rmap F `[derive1mx r12 t $ F1 t])
(* velocity of the origin of Frame i w.r.t. the origin of Frame i-1 *) +
w1 t *v (\o{F2 t} - \o{F1 t}).
Proof.
rewrite -eqn314_helper.
move: (@eqn312 _ F _ derivable_F1 _ derivable_r12 derivable_F1o t).
have -> : derive1mx (fun x => BoundVect.endp (motion r12 x)) t = derive1mx o2 t.
rewrite (_ : (fun x => BoundVect.endp (motion r12 x)) = o2) //.
rewrite funeqE => t' /=; rewrite -mulmxA FromTo_comp FromToI mulmx1.
rewrite addrCA RFrame_o subrr addr0.
by rewrite /o2 -RFrame_o.
move=> ->.
rewrite -!{1}addrA /=; apply: f_equal2; last by [].
rewrite (_ : (fun x => BoundVect.endp (motion (fun _ : R => bvec0 (F1 x)) t)) = o1) //.
rewrite funeqE => t'.
by rewrite /motion /= mul0mx addr0.
Qed.
Definition w2 : R -> 'rV_3 := ang_vel (fun t => (F2 t) _R^ F).
Definition w12 : R -> 'rV_3 := ang_vel (fun t => (F2 t) _R^ (F1 t)).
(* ang. vel. of Link i as a function of the ang. vel. of Link i-1 and of Link i w.r.t. Link i-1 *)
Lemma eqn316 t : w2 t = w1 t + w12 t *m ((F1 t) _R^ F).
Proof.
have : (fun t => (F2 t) _R^ F) = (fun t => ((F2 t) _R^ (F1 t)) *m ((F1 t) _R^ F)).
by rewrite funeqE => ?; rewrite FromTo_comp.
move/(congr1 (fun x => derive1mx x)).
rewrite funeqE.
move/(_ t).
rewrite derive1mxM; last 2 first.
move=> t'; exact: derivable_mx_FromTo'.
move=> t'; exact: derivable_mx_FromTo.
rewrite derive1mx_ang_vel; last 2 first.
move=> t'; by rewrite FromTo_is_O.
move=> t'; exact: derivable_mx_FromTo.
rewrite derive1mx_ang_vel; last 2 first.
move=> t'; by rewrite FromTo_is_O.
move=> t'; exact: derivable_mx_FromTo'.
rewrite derive1mx_ang_vel; last 2 first.
move=> t'; by rewrite FromTo_is_O.
move=> t'; exact: derivable_mx_FromTo.
rewrite ang_vel_mxE; last 2 first.
move=> t'; by rewrite FromTo_is_O.
move=> t'; exact: derivable_mx_FromTo.
rewrite ang_vel_mxE; last 2 first.
move=> t'; by rewrite FromTo_is_O.
move=> t'; exact: derivable_mx_FromTo'.
rewrite ang_vel_mxE; last 2 first.
move=> t'; by rewrite FromTo_is_O.
move=> t'; exact: derivable_mx_FromTo.
rewrite mulmxE -[in X in _ = X + _](mulr1 ((F2 t) _R^ (F1 t))).
rewrite -(@orthogonal_tr_mul _ _ (F _R^ (F1 t))) ?FromTo_is_O //.
rewrite -{2}(trmx_FromTo (F1 t) F).
rewrite -!mulrA.
rewrite (mulrA _ _ ((F1 t) _R^ F)).
rewrite (@spin_similarity _ ((F1 t) _R^ F)) ?FromTo_is_SO //.
rewrite mulrA -mulmxE.
rewrite trmx_FromTo.
rewrite FromTo_comp.
rewrite mulmxA.
rewrite FromTo_comp.
rewrite -mulmxDr.
rewrite -spinD.
rewrite -/w2 -/w1 -/w12.
rewrite mulmxE.
move/mulrI.
rewrite FromTo_unit => /(_ isT)/eqP.
rewrite spin_inj => /eqP.
by rewrite addrC.
Qed.
End link_velocity.
From mathcomp Require Import trigo.
Lemma derive1_cos (R : realType) (t : R) : derive1 (cos : _ -> R^o) t = - sin t.
Proof.
rewrite derive1E.
have u := is_derive_cos t.
by have := @derive_val _ _ _ _ _ _ _ u.
Qed.
Lemma derive1_sin (R : realType) (t : R) : derive1 (sin : _ -> R^o) t = cos t.
Proof.
rewrite derive1E.
have u := is_derive_sin t.
by have := @derive_val _ _ _ _ _ _ _ u.
Qed.
Lemma derivable_sin (R : realType) (t : R) : derivable (sin : R^o -> R^o) t 1.
Proof. exact: ex_derive. Qed.
Lemma derivable_cos (R : realType) (t : R) : derivable (cos : R^o -> R^o) t 1.
Proof. exact: ex_derive. Qed.
Lemma derivable_cos_comp (R : realType) (t : R) (a : R^o -> R^o) :
derivable a t 1 -> derivable (cos \o a : _ -> R^o) t 1.
Proof. by move=> /derivableP Hs; exact: ex_derive. Qed.
Lemma derivable_sin_comp (R : realType) (t : R) (a : R^o -> R^o) :
derivable a t 1 -> derivable ((sin : _ -> R^o) \o a) t 1.
Proof. by move=> /derivableP Hs; exact: ex_derive. Qed.
Lemma derive1_cos_comp (R : realType) t (a : R^o -> R^o) : derivable a t 1 ->
derive1 (cos \o a : _ -> R^o) t = - (derive1 a t) * sin (a t).
Proof.
move=> H; rewrite (derive1_comp H); last exact: derivable_cos.
by rewrite derive1_cos mulrC mulNr mulrN.
Qed.
Lemma derive1mx_RzE (R : realType) (a : R^o -> R^o) t : derivable a t 1 ->
derive1mx (fun x => Rz (a x) : 'M[R^o]__) t =
derive1 a t *: col_mx3 (row3 (- sin (a t)) (cos (a t)) 0)
(row3 (- cos (a t)) (- sin (a t)) 0)
0.
Proof.
move=> Ha.
apply/matrix3P/and9P; split; rewrite !mxE /=.
- rewrite (_ : (fun _ => _) = cos \o a); last by rewrite funeqE => x; rewrite !mxE.
rewrite (derive1_comp Ha); last exact/derivable_cos.
by rewrite derive1_cos mulrC.
- rewrite (_ : (fun _ => _) = sin \o a); last by rewrite funeqE => x; rewrite !mxE.
rewrite (derive1_comp Ha); last exact/derivable_sin.
by rewrite derive1_sin mulrC.
- rewrite (_ : (fun _ => _) = \0); last by rewrite funeqE => x; rewrite !mxE.
by rewrite derive1_cst mulr0.
- rewrite (_ : (fun _ => _) = - sin \o a); last by rewrite funeqE => x; rewrite !mxE.
rewrite (_ : - _ \o _ = - (sin \o a)) // derive1E deriveN; last first.
apply/derivable1_diffP/differentiable_comp.
exact/derivable1_diffP.
exact/derivable1_diffP/derivable_sin.
rewrite -derive1E (derive1_comp Ha); last exact/derivable_sin.
by rewrite derive1_sin mulrN mulrC.
- rewrite (_ : (fun _ => _) = cos \o a); last by rewrite funeqE => x; rewrite !mxE.
rewrite (derive1_comp Ha); last exact/derivable_cos.
by rewrite derive1_cos mulrN mulNr mulrC.
- rewrite (_ : (fun _ => _) = \0); last by rewrite funeqE => x; rewrite !mxE.
by rewrite derive1_cst mulr0.
- rewrite (_ : (fun _ => _) = \0); last by rewrite funeqE => x; rewrite !mxE.
by rewrite derive1_cst mulr0.
- rewrite (_ : (fun _ => _) = \0); last by rewrite funeqE => x; rewrite !mxE.
by rewrite derive1_cst mulr0.
- rewrite (_ : (fun _ => _) = cst 1); last by rewrite funeqE => x; rewrite !mxE.
by rewrite derive1_cst mulr0.
Qed.
(* example 3.1 [sciavicco]*)
(* rotational motion of one degree of freedom manipulator *)
Lemma ang_vel_mx_Rz (R : realType) (a : R^o -> R^o) t : derivable a t 1 ->
ang_vel_mx (@Rz _ \o a) t = \S(row3 0 0 (derive1 a t)).
Proof.
move=> Ha.
rewrite /ang_vel_mx trmx_Rz (derive1mx_RzE Ha) /Rz.
rewrite -!scalerAr -col_mx3_mul.
rewrite mulmx_row3_col3 scale0r addr0.
rewrite mulmx_row3_col3 scale0r addr0.
rewrite e2row mulmx_row3_col3 !(scale0r,scaler0,addr0).
rewrite !row3Z !(cosN,sinN,opprK,mulr0,mulrN,mulNr).
rewrite !row3D mulrC addrC subrr addr0.
rewrite -!expr2 cos2Dsin2 -opprD addrC cos2Dsin2.
by apply/matrix3P; rewrite !spinij !mxE /= !(eqxx,oppr0,mulr0,mulrN1,mulr1).
Qed.
(* see also the end of dh.v *)
Section chain.
Inductive joint (R : rcfType) :=
Revolute of (R^o -> (*angle*) R) | Prismatic of (R^o -> R).
Definition joint_variable (R : realType) (j : joint [rcfType of R]) : R^o -> R :=
fun t => match j with Revolute a => a t | Prismatic a => a t end.
Record chain (R : rcfType) n (* number of joints *) := mkChain {
joint_of_chain : 'I_n -> joint R ;
frame_of_chain : 'I_n.+1 -> (R^o -> tframe R) }.
End chain.
Section geometric_jacobian_computation.
Variables (n : nat) (R : realType) (c : chain [rcfType of R^o] n).
Definition prev_frame (i : 'I_n) : 'I_n.+1 := widen_ord (leqnSn n) i.
Definition next_frame (i : 'I_n) : 'I_n.+1 := fintype.lift ord0 i.
Lemma next_frameE i : next_frame i = i.+1 :> nat. Proof. by []. Qed.
Definition last_frame : 'I_n.+1 := ord_max.
Section geo_jac_row.
Variable i : 'I_n.
Let j : joint [rcfType of R^o] := joint_of_chain c i.
Let q : R^o -> R^o := joint_variable j.
Let Fim1 := frame_of_chain c (prev_frame i).
(*Let Fi := frame_of_chain c (next_frame i).*)
Let Fmax := frame_of_chain c last_frame.
(* contribution to the angular velocity *)
Definition geo_jac_ang t : 'rV_3 := if j is Revolute _ then (Fim1 t)~k else 0.
(* contribution to the linear velocity *)
Definition geo_jac_lin t : 'rV_3 :=
if j is Revolute _ then (Fim1 t)~k *v (\o{Fmax t} - \o{Fim1 t}) else (Fim1 t)~k.
End geo_jac_row.
Definition geo_jac t : 'M_(n, 6) :=
row_mx (\matrix_(i < n) geo_jac_lin i t) (\matrix_(i < n) geo_jac_ang i t).
End geometric_jacobian_computation.
Require Import scara.
Section scara_geometric_jacobian.
Variable R : realType.
Variable theta1 : R -> R.
Variable a1 : R.
Variable theta2 : R -> R.
Variable a2 : R.
Variable d3 : R -> R.
Variable theta4 : R -> R.
Variable d4 : R.
(* direct kinematics equation written in function of the joint variables,
from scara.v *)
Let rot t := scara_rot (theta1 t) (theta2 t) (theta4 t).
Let trans t := scara_trans (theta1 t) a1 (theta2 t) a2 (d3 t) d4.
Definition scara_end_effector t : 'M[R]_4 := hom (rot t) (trans t).
Let scara_lin_vel : R -> 'rV[R]_3 :=
derive1mx (@trans_of_hom [ringType of R^o] \o scara_end_effector).
Let scara_ang_vel : R -> 'rV[R]_3 :=
ang_vel (@rot_of_hom [ringType of R^o] \o scara_end_effector).
Definition scara_joints : 'I_4 -> joint R :=
[eta (fun=> Prismatic 0) with
0 |-> Revolute theta1,
1 |-> Revolute theta2,
2%:R |-> Prismatic d3,
3%:R |-> Revolute theta4].
Definition scara_joint_variables t : 'rV[R^o]_4 :=
\row_i (joint_variable (scara_joints i) t).
Let scara_joint_velocities : R -> 'rV[R^o]_4 := derive1mx scara_joint_variables.
(* specification of scara frames *)
Variables scara_frames : 'I_5 -> R -> tframe R.
Let Fim1 (i : 'I_4) := scara_frames (prev_frame i).
Let Fi (i : 'I_4) := scara_frames (next_frame i).
Let Fmax := scara_frames ord_max.
Hypothesis Hzvec : forall t i, (Fim1 i t)~k = 'e_2%:R.
Hypothesis o0E : forall t, \o{Fim1 0 t} = 0.
Hypothesis o1E : forall t, \o{Fim1 1 t} =
a1 * cos (theta1 t) *: 'e_0 + a1 * sin (theta1 t) *: 'e_1.
Hypothesis o2E : forall t, \o{Fim1 2%:R t} = \o{Fim1 1 t} +
(a2 * cos (theta1 t + theta2 t)) *: 'e_0 +
(a2 * sin (theta1 t + theta2 t)) *: 'e_1.
Hypothesis o3E : forall t, \o{Fim1 3%:R t} = \o{Fim1 2%:R t} + (d3 t) *: 'e_2.
Hypothesis o4E : forall t, \o{Fmax t} = \o{Fim1 3%:R t} + d4 *: 'e_2.
Lemma scale_realType (K : realType) (k1 : K) (k2 : K^o) : k1 *: k2 = k1 * k2.
Proof. by []. Qed.
Import rv3LieAlgebra.Exports.
Lemma scara_geometric_jacobian t :
derivable (theta1 : R^o -> R^o) t 1 ->
derivable (theta2 : R^o -> R^o) t 1 ->
derivable (d3 : R^o -> R^o) t 1 ->
derivable (theta4 : R^o -> R^o) t 1 ->
scara_joint_velocities t *m geo_jac (mkChain scara_joints scara_frames) t =
row_mx (scara_lin_vel t) (scara_ang_vel t).
Proof.
move=> H1 H2 H3 H4.
rewrite /geo_jac; set a := (X in _ *m @row_mx _ _ 3 3 X _).
rewrite (mul_mx_row _ a) {}/a; congr (@row_mx _ _ 3 3 _ _).
- rewrite /scara_lin_vel (_ : @trans_of_hom [rcfType of R] \o _ = trans); last first.
rewrite funeqE => x /=; exact: trans_of_hom_hom.
rewrite /trans /scara_trans derive1mxE [RHS]row3_proj /= ![in RHS]mxE [in RHS]/=.
transitivity (
derive1 (theta1 : R^o -> R^o) t *: (Fim1 0 t)~k *v (\o{Fmax t} - \o{Fim1 0 t}) +
derive1 (theta2 : R^o -> R^o) t *: (Fim1 1 t)~k *v (\o{Fmax t} - \o{Fim1 1 t}) +
derive1 (d3 : R^o -> R^o) t *: (Fim1 2 t)~k +
derive1 (theta4 : R^o -> R^o) t *: (Fim1 3%:R t)~k *v (\o{Fmax t} - \o{Fim1 3%:R t})).
rewrite /scara_joint_velocities /scara_joint_variables derive1mxE /geo_jac_lin /=.
apply/rowP => i; rewrite 3![in RHS]mxE [in LHS]mxE sum4E;
(repeat apply: f_equal2).
- by rewrite 2!mxE /= linearZl_LR [in RHS]mxE.
- by rewrite 2!mxE /= linearZl_LR [in RHS]mxE.
- by rewrite 2!mxE [in RHS]mxE.
- by rewrite 2!mxE /= linearZl_LR [in RHS]mxE.
rewrite o0E subr0.
rewrite {1}o4E.
rewrite linearDr /=.
rewrite (linearZr_LR _ _ _ 'e_2)
/= {2}Hzvec (linearZl_LR _ _ _ 'e_2) /= liexx 2!{1}scaler0 addr0.
rewrite (_ : \o{Fmax t} - \o{Fim1 1 t} =
(a2 * cos (theta1 t + theta2 t) *: 'e_0 +
(a1 * sin (theta1 t) + a2 * sin (theta1 t + theta2 t) - a1 * sin (theta1 t)) *: 'e_1 +
(d3 t + d4) *: 'e_2)); last first.
rewrite (addrC (a1 * sin _)) addrK.
rewrite o4E o3E o2E o1E.
set a := _ *: 'e_0 + _ *: 'e_1.
rewrite -3!addrA addrC 3!addrA subrK.
rewrite addrC -[in RHS]addrA; congr (_ + _).
by rewrite -addrA -scalerDl.
rewrite linearDr /=.
rewrite (linearZr_LR _ _ _ 'e_2) /= (linearZl_LR (crossmul_bilinear _) 'e_2)
{2}(Hzvec t 1) /= liexx 2!{1}scaler0 addr0.
rewrite (addrC (a1 * sin _)) addrK.
rewrite (_ : \o{Fmax t} - \o{Fim1 3%:R t} = d4 *: 'e_2%:R); last first.
by rewrite o4E -addrA addrC subrK.
rewrite (linearZr_LR _ _ _ 'e_2) /= (linearZl_LR (crossmul_bilinear _) 'e_2)
{1}(Hzvec t 3%:R) /= liexx 2!scaler0 addr0.
rewrite o3E.
rewrite linearDr /= (linearZr_LR _ _ _ 'e_2) (linearZl_LR _ 'e_2)
{2}(Hzvec t 0) /= liexx 2!scaler0 addr0.
rewrite {1}o2E {1}o1E.
rewrite (_ : (fun _ => _) =
(a2 \*: (cos \o (theta2 + theta1) : R^o -> R^o)) +
(a1 *: (cos \o theta1 : R^o -> R^o))) //.
rewrite (_ : (fun _ => _) = (a2 \*: (sin \o (theta2 + theta1) : _ -> R^o)) +
(a1 *: (sin \o theta1 : _ -> R^o))) //.
rewrite row3e2; congr (_ + _ *: _); last first.
- by rewrite Hzvec.
- rewrite [in RHS]derive1E [in RHS]deriveD; last 2 first.
exact: ex_derive.
exact: H3.
by rewrite deriveE // diff_cst add0r derive1E.
- rewrite !linearDr /= !(linearZr_LR (crossmul_bilinear _))
!(linearZl_LR (crossmul_bilinear _)) /= !Hzvec veckj vecki
!{1}scalerN.
rewrite -!addrA addrCA addrC -!addrA (addrCA (- _)) !addrA.
rewrite -2!addrA [in RHS]addrC; congr (_ + _).
- rewrite !scalerA -2!scalerDl row3e1; congr (_ *: _).
rewrite [in RHS]derive1E deriveD; last 2 first.
apply/derivableZ/derivable_sin_comp/derivableD; [exact H2 | exact H1].
exact/derivableZ/derivable_sin_comp.
rewrite deriveZ /=; last first.
apply/derivable_sin_comp/derivableD; [exact H2 | exact H1].
rewrite deriveZ /=; last exact/derivable_sin_comp.
rewrite -[in RHS]derive1E [in RHS]derive1_comp; last 2 first.
- by apply: derivableD; [exact: H2 | exact: H1].
- by apply: derivable_sin.
rewrite derive1_sin.
rewrite -derive1E [in RHS]derive1_comp; last 2 first.
- exact: H1.
- exact: derivable_sin.
rewrite derive1_sin -addrA addrC; congr (_ + _); last first.
by rewrite -mulrA.
rewrite -mulrDr [in RHS]derive1E deriveD; last 2 first.
exact: H2.
exact: H1.
rewrite -mulrA scale_realType; apply: f_equal2; first by [].
rewrite addrC; apply: f_equal2; first by [].
by rewrite addrC !derive1E.
- rewrite !{1}scalerA !addrA -3!{1}scaleNr -2!scalerDl row3e0.
congr (_ *: _).
rewrite [in RHS]derive1E deriveD; last 2 first.
by apply/derivableZ/derivable_cos_comp/derivableD; [exact H2 | exact H1].
by apply/derivableZ/derivable_cos_comp; exact H1.
rewrite deriveZ /=; last first.
by apply/derivable_cos_comp/derivableD.
rewrite deriveZ /=; last exact/derivable_cos_comp.
rewrite -derive1E [in RHS]derive1_comp; last 2 first.
- by apply: derivableD; [exact: H2 | exact: H1].
- exact: derivable_cos.
rewrite derive1_cos mulNr scalerN.
rewrite -derive1E [in RHS]derive1_comp; last 2 first.
- exact: H1.
- exact: derivable_cos.
rewrite derive1_cos mulNr scalerN; congr (_ - _); last first.
by rewrite -mulrA.
rewrite -opprD; congr (- _).
rewrite [in RHS]derive1E deriveD; last 2 first.
exact: H2.
exact: H1.
rewrite -mulrDr -!derive1E.
rewrite addrC (addrC (_^`() _)).
by rewrite !scalerAl.
- rewrite /scara_ang_vel (_ : @rot_of_hom [ringType of R^o] \o _ = rot); last first.
rewrite funeqE => x /=; exact: rot_of_hom_hom.
rewrite /rot /ang_vel /scara_rot.
rewrite (_ : (fun _ => _) = (@Rz _ \o (theta1 + theta2 + theta4))); last first.
by rewrite funeqE.
rewrite ang_vel_mx_Rz; last first.
apply derivableD; [apply/derivableD|by []].
exact: H1.
exact: H2.
rewrite [RHS]spinK.
transitivity (derive1 (theta1 : R^o -> R^o) t *: (Fim1 0 t)~k +
derive1 (theta2 : R^o -> R^o) t *: (Fim1 1 t)~k +
derive1 (theta4 : R^o -> R^o) t *: (Fim1 3%:R t)~k).
rewrite /scara_joint_velocities /scara_joint_variables derive1mxE /geo_jac_ang /=.
apply/rowP => i; rewrite !mxE sum4E !mxE {1}mulr0 addr0.
by rewrite -!/(Fim1 _) [Fim1 0 _]lock [Fim1 1 _]lock [Fim1 3%:R _]lock /= -!lock.
rewrite !Hzvec -2!scalerDl e2row row3Z mulr0 mulr1.
rewrite [in RHS]derive1E deriveD; [|apply/derivableD|by []]; last 2 first.
exact: H1.
exact: H2.
rewrite deriveD; [| exact: H1| exact H2].
by rewrite 3!derive1E.
Qed.
End scara_geometric_jacobian.
Section analytical_jacobian.
Variable n' : nat.
Let n := n'.+1.
Variable (R : realType) (p : 'rV[R^o]_n -> 'rV[R^o]_3).
Let Jp := jacobian p.
Variable (phi : 'rV[R^o]_n -> 'rV[R^o]_3).
Let Jphi := jacobian phi.
Lemma dp (q : R^o -> 'rV[R^o]_n) t :
derive1mx (p \o q) t = derive1mx q t *m Jp (q t). (* 3.56 *)
Proof.
rewrite /Jp /jacobian mul_rV_lin1.
rewrite /derive1mx.
Abort.
End analytical_jacobian.
(*Section tangent_vectors.
Variable R : realType.
Let vector := 'rV[R]_3.
Let point := 'rV[R]_3.
Implicit Types p : point.
(* tangent vector *)
Record tvec p := TVec {tvec_field :> vector}.
Definition vtvec p (v : tvec p) := let: TVec v := v in v.
Local Notation "p .-vec" := (tvec p) (at level 5).
Local Notation "u :@ p" := (TVec p u) (at level 11).
Definition addt (p : point) (u : p.-vec) (v : vector) : p.-vec :=
TVec p (tvec_field u + v).
Local Notation "p +@ u" := (addt p u) (at level 41).
End tangent_vectors.
Coercion vtvec_field_coercion := vtvec.
Notation "p .-vec" := (tvec p) (at level 5).
Notation "u :@ p" := (TVec p u) (at level 11).
Notation "p +@ u" := (addt p u) (at level 41).*)
|
How to Find the Right Wooden Doors for Your Home?
A wooden door can add appeal to your home. No matter whether you choose a classic or vintage style, it remains one of the oldest structures in the human history. You can find its significance in history where alder, cherry, timber, oak or mahogany was used for the protection of forts. Now customization on doors is available. You can customize a wood depending on your budget and the functional requirements. Wood doors add more charm to the overall look of your home. It is a practical choice to opt for wooden doors.
You should stay updated about various options to make it a good choice for you.
These doors feature a frame which is covered with a layer of wood or veneer on its both sides. Solid timber strips with its edges are also available in the market. The supports in between the face veneers provide the rigidity. Face veneers can also be availed in varnished or painted plywood. Different in-fills make it durable to the hollow core doors. A cardboard honeycomb is the most widely used type of such doors and easily available with wooden door suppliers. You can position a solid timber area at a specific height on one door side. You can use it to put the lock and handle. Hollow core doors come as an affordable option in comparison to the most solid wood doors. They are lighter and easier to install. The only disadvantage is that they cannot absorb sound effectively.
Flush doors have the thin sheets of hardwood veneer which is placed on the top of the core of particle board, wood or fiberboard. The veneer helps in protecting the door from stabilizing and warping. You can always enhance the face veneers using decorative panels. Two kinds of cores are used in flush doors. It includes stile and rail core and wood-stave block core. A wood-stave core has vertical wood strips of low-density. A stile and rail core includes wood blocks that are glued inside the rails and stiles. It comes with more reliability as compared to wood stave.
Panel doors are more popular nowadays. They feature a series of solid wood panels that are available in a variety of shapes and sizes. These panels are arranged next to each other. Panel doors have grooved frames coupled with thinner panels of pine, oak or beech. The moldings can be installed to ensure the panels remain in its place. The size and number of panels will depend on your requirements including the door and size you need. Four panels are the most common kinds of panel wooden doors these days.
Due to inset glass panels, the lited doors are in demand. There are doors with interior or exterior openings. For instance, the office doors or patio doors serve as the perfect example of the lited doors. Often wooden door manufacturers call doors lited doors because of the number of glass panels they have.
Welcome to D.P. Woodtech Pvt. Ltd, one of the India’s leading manufacturer, supplier, and exporter of high-quality wooden furniture for homes and offices.
|
{-# OPTIONS --cubical --safe #-}
module Data.List.Sugar where
open import Data.List.Base
open import Prelude
[_] : A → List A
[ x ] = x ∷ []
pure : A → List A
pure = [_]
_>>=_ : List A → (A → List B) → List B
_>>=_ = flip concatMap
_>>_ : List A → List B → List B
xs >> ys = xs >>= const ys
_<*>_ : List (A → B) → List A → List B
fs <*> xs = do
f ← fs
x ← xs
[ f x ]
guard : Bool → List ⊤
guard false = []
guard true = [ tt ]
|
State Before: A : Type u_1
B : Type u_2
inst✝³ : Field A
inst✝² : Ring B
inst✝¹ : IsDomain B
inst✝ : Algebra A B
x : B
hx : IsIntegral A x
⊢ Prime (minpoly A x) State After: A : Type u_1
B : Type u_2
inst✝³ : Field A
inst✝² : Ring B
inst✝¹ : IsDomain B
inst✝ : Algebra A B
x : B
hx : IsIntegral A x
⊢ ∀ (a b : A[X]), minpoly A x ∣ a * b → minpoly A x ∣ a ∨ minpoly A x ∣ b Tactic: refine' ⟨minpoly.ne_zero hx, not_isUnit A x, _⟩ State Before: A : Type u_1
B : Type u_2
inst✝³ : Field A
inst✝² : Ring B
inst✝¹ : IsDomain B
inst✝ : Algebra A B
x : B
hx : IsIntegral A x
⊢ ∀ (a b : A[X]), minpoly A x ∣ a * b → minpoly A x ∣ a ∨ minpoly A x ∣ b State After: case intro
A : Type u_1
B : Type u_2
inst✝³ : Field A
inst✝² : Ring B
inst✝¹ : IsDomain B
inst✝ : Algebra A B
x : B
hx : IsIntegral A x
p q d : A[X]
h : p * q = minpoly A x * d
⊢ minpoly A x ∣ p ∨ minpoly A x ∣ q Tactic: rintro p q ⟨d, h⟩ State Before: case intro
A : Type u_1
B : Type u_2
inst✝³ : Field A
inst✝² : Ring B
inst✝¹ : IsDomain B
inst✝ : Algebra A B
x : B
hx : IsIntegral A x
p q d : A[X]
h : p * q = minpoly A x * d
⊢ minpoly A x ∣ p ∨ minpoly A x ∣ q State After: case intro
A : Type u_1
B : Type u_2
inst✝³ : Field A
inst✝² : Ring B
inst✝¹ : IsDomain B
inst✝ : Algebra A B
x : B
hx : IsIntegral A x
p q d : A[X]
h : p * q = minpoly A x * d
this : ↑(Polynomial.aeval x) (p * q) = 0
⊢ minpoly A x ∣ p ∨ minpoly A x ∣ q Tactic: have : Polynomial.aeval x (p * q) = 0 := by simp [h, aeval A x] State Before: case intro
A : Type u_1
B : Type u_2
inst✝³ : Field A
inst✝² : Ring B
inst✝¹ : IsDomain B
inst✝ : Algebra A B
x : B
hx : IsIntegral A x
p q d : A[X]
h : p * q = minpoly A x * d
this : ↑(Polynomial.aeval x) (p * q) = 0
⊢ minpoly A x ∣ p ∨ minpoly A x ∣ q State After: case intro
A : Type u_1
B : Type u_2
inst✝³ : Field A
inst✝² : Ring B
inst✝¹ : IsDomain B
inst✝ : Algebra A B
x : B
hx : IsIntegral A x
p q d : A[X]
h : p * q = minpoly A x * d
this : ↑(Polynomial.aeval x) p = 0 ∨ ↑(Polynomial.aeval x) q = 0
⊢ minpoly A x ∣ p ∨ minpoly A x ∣ q Tactic: replace : Polynomial.aeval x p = 0 ∨ Polynomial.aeval x q = 0 := by simpa State Before: case intro
A : Type u_1
B : Type u_2
inst✝³ : Field A
inst✝² : Ring B
inst✝¹ : IsDomain B
inst✝ : Algebra A B
x : B
hx : IsIntegral A x
p q d : A[X]
h : p * q = minpoly A x * d
this : ↑(Polynomial.aeval x) p = 0 ∨ ↑(Polynomial.aeval x) q = 0
⊢ minpoly A x ∣ p ∨ minpoly A x ∣ q State After: no goals Tactic: exact Or.imp (dvd A x) (dvd A x) this State Before: A : Type u_1
B : Type u_2
inst✝³ : Field A
inst✝² : Ring B
inst✝¹ : IsDomain B
inst✝ : Algebra A B
x : B
hx : IsIntegral A x
p q d : A[X]
h : p * q = minpoly A x * d
⊢ ↑(Polynomial.aeval x) (p * q) = 0 State After: no goals Tactic: simp [h, aeval A x] State Before: A : Type u_1
B : Type u_2
inst✝³ : Field A
inst✝² : Ring B
inst✝¹ : IsDomain B
inst✝ : Algebra A B
x : B
hx : IsIntegral A x
p q d : A[X]
h : p * q = minpoly A x * d
this : ↑(Polynomial.aeval x) (p * q) = 0
⊢ ↑(Polynomial.aeval x) p = 0 ∨ ↑(Polynomial.aeval x) q = 0 State After: no goals Tactic: simpa
|
[STATEMENT]
lemma pi_ahs[proper_it]: "proper_it' ahs.iteratei ahs.iteratei"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. proper_it' ahs.iteratei ahs.iteratei
[PROOF STEP]
unfolding ahs.iteratei_def[abs_def]
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. proper_it' (\<lambda>S. it_to_it (ahs.list_it S)) (\<lambda>S. it_to_it (ahs.list_it S))
[PROOF STEP]
by (rule proper_it'I icf_proper_iteratorI)+
|
#include <iostream>
#include <boost/foreach.hpp>
#include <vector>
int main() {
std::vector<int> container;
container.resize(10);
BOOST_FOREACH(int& i, container) {
i = 100;
}
BOOST_FOREACH(int i, container) {
std::cout << i << std::endl;
}
}
|
## chose only file ending with "xls"
substrRight <- function(x, n){
substr(x, nchar(x)-n+1, nchar(x))
}
#Filesname = Filesname[END == substrRight(Filesname, 4) ]
Filesname = Filesname[!grepl(NEVERTHERE,Filesname)]
Filesname = Filesname[grepl(NECESSARY,Filesname)]
filechoosen=Filesname
|
State Before: ι : Type ?u.112982
α : Type u_1
inst✝¹ : PartialOrder α
inst✝ : LocallyFiniteOrder α
a✝ b✝ c a b : α
⊢ card (Ioo a b) = card (Icc a b) - 2 State After: ι : Type ?u.112982
α : Type u_1
inst✝¹ : PartialOrder α
inst✝ : LocallyFiniteOrder α
a✝ b✝ c a b : α
⊢ card (Icc a b) - 1 - 1 = card (Icc a b) - 2 Tactic: rw [card_Ioo_eq_card_Ico_sub_one, card_Ico_eq_card_Icc_sub_one] State Before: ι : Type ?u.112982
α : Type u_1
inst✝¹ : PartialOrder α
inst✝ : LocallyFiniteOrder α
a✝ b✝ c a b : α
⊢ card (Icc a b) - 1 - 1 = card (Icc a b) - 2 State After: no goals Tactic: rfl
|
section \<open>Lens Algebraic Operators\<close>
theory Lens_Algebra
imports Lens_Laws
begin
subsection \<open>Lens Composition, Plus, Unit, and Identity\<close>
text \<open>
\begin{figure}
\begin{center}
\includegraphics[width=7cm]{figures/Composition}
\end{center}
\vspace{-5ex}
\caption{Lens Composition}
\label{fig:Comp}
\end{figure}
We introduce the algebraic lens operators; for more information please see our paper~\cite{Foster16a}.
Lens composition, illustrated in Figure~\ref{fig:Comp}, constructs a lens by composing the source
of one lens with the view of another.\<close>
definition lens_comp :: "('a \<Longrightarrow> 'b) \<Rightarrow> ('b \<Longrightarrow> 'c) \<Rightarrow> ('a \<Longrightarrow> 'c)" (infixr ";\<^sub>L" 80) where
[lens_defs]: "lens_comp Y X = \<lparr> lens_get = lens_get Y \<circ> lens_get X
, lens_put = (\<lambda> \<sigma> v. lens_put X \<sigma> (lens_put Y (lens_get X \<sigma>) v)) \<rparr>"
text \<open>
\begin{figure}
\begin{center}
\includegraphics[width=7cm]{figures/Sum}
\end{center}
\vspace{-5ex}
\caption{Lens Sum}
\label{fig:Sum}
\end{figure}
Lens plus, as illustrated in Figure~\ref{fig:Sum} parallel composes two independent lenses,
resulting in a lens whose view is the product of the two underlying lens views.\<close>
definition lens_plus :: "('a \<Longrightarrow> 'c) \<Rightarrow> ('b \<Longrightarrow> 'c) \<Rightarrow> 'a \<times> 'b \<Longrightarrow> 'c" (infixr "+\<^sub>L" 75) where
[lens_defs]: "X +\<^sub>L Y = \<lparr> lens_get = (\<lambda> \<sigma>. (lens_get X \<sigma>, lens_get Y \<sigma>))
, lens_put = (\<lambda> \<sigma> (u, v). lens_put X (lens_put Y \<sigma> v) u) \<rparr>"
text \<open>The product functor lens similarly parallel composes two lenses, but in this case the lenses
have different sources and so the resulting source is also a product.\<close>
definition lens_prod :: "('a \<Longrightarrow> 'c) \<Rightarrow> ('b \<Longrightarrow> 'd) \<Rightarrow> ('a \<times> 'b \<Longrightarrow> 'c \<times> 'd)" (infixr "\<times>\<^sub>L" 85) where
[lens_defs]: "lens_prod X Y = \<lparr> lens_get = map_prod (get\<^bsub>X\<^esub>) (get\<^bsub>Y\<^esub>)
, lens_put = \<lambda> (u, v) (x, y). (put\<^bsub>X\<^esub> u x, put\<^bsub>Y\<^esub> v y) \<rparr>"
text \<open>The $\lfst$ and $\lsnd$ lenses project the first and second elements, respectively, of a
product source type.\<close>
definition fst_lens :: "'a \<Longrightarrow> 'a \<times> 'b" ("fst\<^sub>L") where
[lens_defs]: "fst\<^sub>L = \<lparr> lens_get = fst, lens_put = (\<lambda> (\<sigma>, \<rho>) u. (u, \<rho>)) \<rparr>"
definition snd_lens :: "'b \<Longrightarrow> 'a \<times> 'b" ("snd\<^sub>L") where
[lens_defs]: "snd\<^sub>L = \<lparr> lens_get = snd, lens_put = (\<lambda> (\<sigma>, \<rho>) u. (\<sigma>, u)) \<rparr>"
lemma get_fst_lens [simp]: "get\<^bsub>fst\<^sub>L\<^esub> (x, y) = x"
by (simp add: fst_lens_def)
lemma get_snd_lens [simp]: "get\<^bsub>snd\<^sub>L\<^esub> (x, y) = y"
by (simp add: snd_lens_def)
text \<open>The swap lens is a bijective lens which swaps over the elements of the product source type.\<close>
abbreviation swap_lens :: "'a \<times> 'b \<Longrightarrow> 'b \<times> 'a" ("swap\<^sub>L") where
"swap\<^sub>L \<equiv> snd\<^sub>L +\<^sub>L fst\<^sub>L"
text \<open>The zero lens is an ineffectual lens whose view is a unit type. This means the zero lens
cannot distinguish or change the source type.\<close>
definition zero_lens :: "unit \<Longrightarrow> 'a" ("0\<^sub>L") where
[lens_defs]: "0\<^sub>L = \<lparr> lens_get = (\<lambda> _. ()), lens_put = (\<lambda> \<sigma> x. \<sigma>) \<rparr>"
text \<open>The identity lens is a bijective lens where the source and view type are the same.\<close>
definition id_lens :: "'a \<Longrightarrow> 'a" ("1\<^sub>L") where
[lens_defs]: "1\<^sub>L = \<lparr> lens_get = id, lens_put = (\<lambda> _. id) \<rparr>"
text \<open>The quotient operator $X \lquot Y$ shortens lens $X$ by cutting off $Y$ from the end. It is
thus the dual of the composition operator.\<close>
definition lens_quotient :: "('a \<Longrightarrow> 'c) \<Rightarrow> ('b \<Longrightarrow> 'c) \<Rightarrow> 'a \<Longrightarrow> 'b" (infixr "'/\<^sub>L" 90) where
[lens_defs]: "X /\<^sub>L Y = \<lparr> lens_get = \<lambda> \<sigma>. (get\<^bsub>X\<^esub> (create\<^bsub>Y\<^esub> \<sigma>))
, lens_put = \<lambda> \<sigma> v. (get\<^bsub>Y\<^esub> (put\<^bsub>X\<^esub> (create\<^bsub>Y\<^esub> \<sigma>) v)) \<rparr>"
text \<open>Lens override uses a lens to replace part of a source type with a given value for the
corresponding view.\<close>
definition lens_override :: "'a \<Rightarrow> 'a \<Rightarrow> ('b \<Longrightarrow> 'a) \<Rightarrow> 'a" ("_ \<oplus>\<^sub>L _ on _" [95,0,96] 95) where
[lens_defs]: "S\<^sub>1 \<oplus>\<^sub>L S\<^sub>2 on X = put\<^bsub>X\<^esub> S\<^sub>1 (get\<^bsub>X\<^esub> S\<^sub>2)"
text \<open>Lens inverse take a bijective lens and swaps the source and view types.\<close>
definition lens_inv :: "('a \<Longrightarrow> 'b) \<Rightarrow> ('b \<Longrightarrow> 'a)" ("inv\<^sub>L") where
[lens_defs]: "lens_inv x = \<lparr> lens_get = create\<^bsub>x\<^esub>, lens_put = \<lambda> \<sigma>. get\<^bsub>x\<^esub> \<rparr>"
subsection \<open>Closure Poperties\<close>
text \<open>We show that the core lenses combinators defined above are closed under the key lens classes.\<close>
lemma id_wb_lens: "wb_lens 1\<^sub>L"
by (unfold_locales, simp_all add: id_lens_def)
lemma unit_wb_lens: "wb_lens 0\<^sub>L"
by (unfold_locales, simp_all add: zero_lens_def)
lemma comp_wb_lens: "\<lbrakk> wb_lens x; wb_lens y \<rbrakk> \<Longrightarrow> wb_lens (x ;\<^sub>L y)"
by (unfold_locales, simp_all add: lens_comp_def)
lemma comp_mwb_lens: "\<lbrakk> mwb_lens x; mwb_lens y \<rbrakk> \<Longrightarrow> mwb_lens (x ;\<^sub>L y)"
by (unfold_locales, simp_all add: lens_comp_def)
lemma id_vwb_lens [simp]: "vwb_lens 1\<^sub>L"
by (unfold_locales, simp_all add: id_lens_def)
lemma unit_vwb_lens [simp]: "vwb_lens 0\<^sub>L"
by (unfold_locales, simp_all add: zero_lens_def)
lemma comp_vwb_lens: "\<lbrakk> vwb_lens x; vwb_lens y \<rbrakk> \<Longrightarrow> vwb_lens (x ;\<^sub>L y)"
by (unfold_locales, simp_all add: lens_comp_def)
lemma unit_ief_lens: "ief_lens 0\<^sub>L"
by (unfold_locales, simp_all add: zero_lens_def)
text \<open>Lens plus requires that the lenses be independent to show closure.\<close>
lemma plus_mwb_lens:
assumes "mwb_lens x" "mwb_lens y" "x \<bowtie> y"
shows "mwb_lens (x +\<^sub>L y)"
using assms
apply (unfold_locales)
apply (simp_all add: lens_plus_def prod.case_eq_if lens_indep_sym)
apply (simp add: lens_indep_comm)
done
lemma plus_wb_lens:
assumes "wb_lens x" "wb_lens y" "x \<bowtie> y"
shows "wb_lens (x +\<^sub>L y)"
using assms
apply (unfold_locales, simp_all add: lens_plus_def)
apply (simp add: lens_indep_sym prod.case_eq_if)
done
lemma plus_vwb_lens:
assumes "vwb_lens x" "vwb_lens y" "x \<bowtie> y"
shows "vwb_lens (x +\<^sub>L y)"
using assms
apply (unfold_locales, simp_all add: lens_plus_def)
apply (simp add: lens_indep_sym prod.case_eq_if)
apply (simp add: lens_indep_comm prod.case_eq_if)
done
lemma prod_mwb_lens:
"\<lbrakk> mwb_lens X; mwb_lens Y \<rbrakk> \<Longrightarrow> mwb_lens (X \<times>\<^sub>L Y)"
by (unfold_locales, simp_all add: lens_prod_def prod.case_eq_if)
lemma prod_wb_lens:
"\<lbrakk> wb_lens X; wb_lens Y \<rbrakk> \<Longrightarrow> wb_lens (X \<times>\<^sub>L Y)"
by (unfold_locales, simp_all add: lens_prod_def prod.case_eq_if)
lemma prod_vwb_lens:
"\<lbrakk> vwb_lens X; vwb_lens Y \<rbrakk> \<Longrightarrow> vwb_lens (X \<times>\<^sub>L Y)"
by (unfold_locales, simp_all add: lens_prod_def prod.case_eq_if)
lemma prod_bij_lens:
"\<lbrakk> bij_lens X; bij_lens Y \<rbrakk> \<Longrightarrow> bij_lens (X \<times>\<^sub>L Y)"
by (unfold_locales, simp_all add: lens_prod_def prod.case_eq_if)
lemma fst_vwb_lens: "vwb_lens fst\<^sub>L"
by (unfold_locales, simp_all add: fst_lens_def prod.case_eq_if)
lemma snd_vwb_lens: "vwb_lens snd\<^sub>L"
by (unfold_locales, simp_all add: snd_lens_def prod.case_eq_if)
lemma id_bij_lens: "bij_lens 1\<^sub>L"
by (unfold_locales, simp_all add: id_lens_def)
lemma inv_id_lens: "inv\<^sub>L 1\<^sub>L = 1\<^sub>L"
by (auto simp add: lens_inv_def id_lens_def lens_create_def)
lemma lens_inv_bij: "bij_lens X \<Longrightarrow> bij_lens (inv\<^sub>L X)"
by (unfold_locales, simp_all add: lens_inv_def lens_create_def)
lemma swap_bij_lens: "bij_lens swap\<^sub>L"
by (unfold_locales, simp_all add: lens_plus_def prod.case_eq_if fst_lens_def snd_lens_def)
subsection \<open>Composition Laws\<close>
text \<open>Lens composition is monoidal, with unit @{term "1\<^sub>L"}, as the following theorems demonstrate.
It also has @{term "0\<^sub>L"} as a right annihilator. \<close>
lemma lens_comp_assoc: "(X ;\<^sub>L Y) ;\<^sub>L Z = X ;\<^sub>L (Y ;\<^sub>L Z)"
by (auto simp add: lens_comp_def)
lemma lens_comp_left_id [simp]: "1\<^sub>L ;\<^sub>L X = X"
by (simp add: id_lens_def lens_comp_def)
lemma lens_comp_right_id [simp]: "X ;\<^sub>L 1\<^sub>L = X"
by (simp add: id_lens_def lens_comp_def)
lemma lens_comp_anhil [simp]: "wb_lens X \<Longrightarrow> 0\<^sub>L ;\<^sub>L X = 0\<^sub>L"
by (simp add: zero_lens_def lens_comp_def comp_def)
subsection \<open>Independence Laws\<close>
text \<open>The zero lens @{term "0\<^sub>L"} is independent of any lens. This is because nothing can be observed
or changed using @{term "0\<^sub>L"}. \<close>
lemma zero_lens_indep [simp]: "0\<^sub>L \<bowtie> X"
by (auto simp add: zero_lens_def lens_indep_def)
lemma zero_lens_indep' [simp]: "X \<bowtie> 0\<^sub>L"
by (auto simp add: zero_lens_def lens_indep_def)
text \<open>Lens independence is irreflexive, but only for effectual lenses as otherwise nothing can
be observed.\<close>
lemma lens_indep_quasi_irrefl: "\<lbrakk> wb_lens x; eff_lens x \<rbrakk> \<Longrightarrow> \<not> (x \<bowtie> x)"
by (auto simp add: lens_indep_def ief_lens_def ief_lens_axioms_def, metis (full_types) wb_lens.get_put)
text \<open>Lens independence is a congruence with respect to composition, as the following properties demonstrate.\<close>
lemma lens_indep_left_comp [simp]:
"\<lbrakk> mwb_lens z; x \<bowtie> y \<rbrakk> \<Longrightarrow> (x ;\<^sub>L z) \<bowtie> (y ;\<^sub>L z)"
apply (rule lens_indepI)
apply (auto simp add: lens_comp_def)
apply (simp add: lens_indep_comm)
apply (simp add: lens_indep_sym)
done
lemma lens_indep_right_comp:
"y \<bowtie> z \<Longrightarrow> (x ;\<^sub>L y) \<bowtie> (x ;\<^sub>L z)"
apply (auto intro!: lens_indepI simp add: lens_comp_def)
using lens_indep_comm lens_indep_sym apply fastforce
apply (simp add: lens_indep_sym)
done
lemma lens_indep_left_ext [intro]:
"y \<bowtie> z \<Longrightarrow> (x ;\<^sub>L y) \<bowtie> z"
apply (auto intro!: lens_indepI simp add: lens_comp_def)
apply (simp add: lens_indep_comm)
apply (simp add: lens_indep_sym)
done
lemma lens_indep_right_ext [intro]:
"x \<bowtie> z \<Longrightarrow> x \<bowtie> (y ;\<^sub>L z)"
by (simp add: lens_indep_left_ext lens_indep_sym)
lemma lens_comp_indep_cong_left:
"\<lbrakk> mwb_lens Z; X ;\<^sub>L Z \<bowtie> Y ;\<^sub>L Z \<rbrakk> \<Longrightarrow> X \<bowtie> Y"
apply (rule lens_indepI)
apply (rename_tac u v \<sigma>)
apply (drule_tac u=u and v=v and \<sigma>="create\<^bsub>Z\<^esub> \<sigma>" in lens_indep_comm)
apply (simp add: lens_comp_def)
apply (meson mwb_lens_weak weak_lens.view_determination)
apply (rename_tac v \<sigma>)
apply (drule_tac v=v and \<sigma>="create\<^bsub>Z\<^esub> \<sigma>" in lens_indep_get)
apply (simp add: lens_comp_def)
apply (drule lens_indep_sym)
apply (rename_tac u \<sigma>)
apply (drule_tac v=u and \<sigma>="create\<^bsub>Z\<^esub> \<sigma>" in lens_indep_get)
apply (simp add: lens_comp_def)
done
lemma lens_comp_indep_cong:
"mwb_lens Z \<Longrightarrow> (X ;\<^sub>L Z) \<bowtie> (Y ;\<^sub>L Z) \<longleftrightarrow> X \<bowtie> Y"
using lens_comp_indep_cong_left lens_indep_left_comp by blast
text \<open>The first and second lenses are independent since the view different parts of a product source.\<close>
lemma fst_snd_lens_indep [simp]:
"fst\<^sub>L \<bowtie> snd\<^sub>L"
by (simp add: lens_indep_def fst_lens_def snd_lens_def)
lemma snd_fst_lens_indep [simp]:
"snd\<^sub>L \<bowtie> fst\<^sub>L"
by (simp add: lens_indep_def fst_lens_def snd_lens_def)
lemma split_prod_lens_indep:
assumes "mwb_lens X"
shows "(fst\<^sub>L ;\<^sub>L X) \<bowtie> (snd\<^sub>L ;\<^sub>L X)"
using assms fst_snd_lens_indep lens_indep_left_comp vwb_lens_mwb by blast
text \<open>Lens independence is preserved by summation.\<close>
lemma plus_pres_lens_indep [simp]: "\<lbrakk> X \<bowtie> Z; Y \<bowtie> Z \<rbrakk> \<Longrightarrow> (X +\<^sub>L Y) \<bowtie> Z"
apply (rule lens_indepI)
apply (simp_all add: lens_plus_def prod.case_eq_if)
apply (simp add: lens_indep_comm)
apply (simp add: lens_indep_sym)
done
lemma plus_pres_lens_indep' [simp]:
"\<lbrakk> X \<bowtie> Y; X \<bowtie> Z \<rbrakk> \<Longrightarrow> X \<bowtie> Y +\<^sub>L Z"
by (auto intro: lens_indep_sym plus_pres_lens_indep)
text \<open>Lens independence is preserved by product.\<close>
lemma lens_indep_prod:
"\<lbrakk> X\<^sub>1 \<bowtie> X\<^sub>2; Y\<^sub>1 \<bowtie> Y\<^sub>2 \<rbrakk> \<Longrightarrow> X\<^sub>1 \<times>\<^sub>L Y\<^sub>1 \<bowtie> X\<^sub>2 \<times>\<^sub>L Y\<^sub>2"
apply (rule lens_indepI)
apply (auto simp add: lens_prod_def prod.case_eq_if lens_indep_comm map_prod_def)
apply (simp_all add: lens_indep_sym)
done
subsection \<open>Algebraic Laws\<close>
text \<open>Lens plus distributes to the right through composition.\<close>
lemma plus_lens_distr: "mwb_lens Z \<Longrightarrow> (X +\<^sub>L Y) ;\<^sub>L Z = (X ;\<^sub>L Z) +\<^sub>L (Y ;\<^sub>L Z)"
by (auto simp add: lens_comp_def lens_plus_def comp_def)
text \<open>The first lens projects the first part of a summation.\<close>
lemma fst_lens_plus:
"wb_lens y \<Longrightarrow> fst\<^sub>L ;\<^sub>L (x +\<^sub>L y) = x"
by (simp add: fst_lens_def lens_plus_def lens_comp_def comp_def)
text \<open>The second law requires independence as we have to apply x first, before y\<close>
lemma snd_lens_plus:
"\<lbrakk> wb_lens x; x \<bowtie> y \<rbrakk> \<Longrightarrow> snd\<^sub>L ;\<^sub>L (x +\<^sub>L y) = y"
apply (simp add: snd_lens_def lens_plus_def lens_comp_def comp_def)
apply (subst lens_indep_comm)
apply (simp_all)
done
text \<open>The swap lens switches over a summation.\<close>
lemma lens_plus_swap:
"X \<bowtie> Y \<Longrightarrow> swap\<^sub>L ;\<^sub>L (X +\<^sub>L Y) = (Y +\<^sub>L X)"
by (auto simp add: lens_plus_def fst_lens_def snd_lens_def id_lens_def lens_comp_def lens_indep_comm)
text \<open>The first, second, and swap lenses are all closely related.\<close>
lemma fst_snd_id_lens: "fst\<^sub>L +\<^sub>L snd\<^sub>L = 1\<^sub>L"
by (auto simp add: lens_plus_def fst_lens_def snd_lens_def id_lens_def)
lemma swap_lens_idem: "swap\<^sub>L ;\<^sub>L swap\<^sub>L = 1\<^sub>L"
by (simp add: fst_snd_id_lens lens_indep_sym lens_plus_swap)
lemma swap_lens_fst: "fst\<^sub>L ;\<^sub>L swap\<^sub>L = snd\<^sub>L"
by (simp add: fst_lens_plus fst_vwb_lens)
lemma swap_lens_snd: "snd\<^sub>L ;\<^sub>L swap\<^sub>L = fst\<^sub>L"
by (simp add: lens_indep_sym snd_lens_plus snd_vwb_lens)
text \<open>The product lens can be rewritten as a sum lens.\<close>
lemma prod_as_plus: "X \<times>\<^sub>L Y = X ;\<^sub>L fst\<^sub>L +\<^sub>L Y ;\<^sub>L snd\<^sub>L"
by (auto simp add: lens_prod_def fst_lens_def snd_lens_def lens_comp_def lens_plus_def)
lemma prod_lens_id_equiv:
"1\<^sub>L \<times>\<^sub>L 1\<^sub>L = 1\<^sub>L"
by (auto simp add: lens_prod_def id_lens_def)
lemma prod_lens_comp_plus:
"X\<^sub>2 \<bowtie> Y\<^sub>2 \<Longrightarrow> ((X\<^sub>1 \<times>\<^sub>L Y\<^sub>1) ;\<^sub>L (X\<^sub>2 +\<^sub>L Y\<^sub>2)) = (X\<^sub>1 ;\<^sub>L X\<^sub>2) +\<^sub>L (Y\<^sub>1 ;\<^sub>L Y\<^sub>2)"
by (auto simp add: lens_comp_def lens_plus_def lens_prod_def prod.case_eq_if fun_eq_iff)
text \<open>The following laws about quotient are similar to their arithmetic analogues. Lens quotient
reverse the effect of a composition.\<close>
lemma lens_comp_quotient:
"weak_lens Y \<Longrightarrow> (X ;\<^sub>L Y) /\<^sub>L Y = X"
by (simp add: lens_quotient_def lens_comp_def)
lemma lens_quotient_id: "weak_lens X \<Longrightarrow> (X /\<^sub>L X) = 1\<^sub>L"
by (force simp add: lens_quotient_def id_lens_def)
lemma lens_quotient_id_denom: "X /\<^sub>L 1\<^sub>L = X"
by (simp add: lens_quotient_def id_lens_def lens_create_def)
lemma lens_quotient_unit: "weak_lens X \<Longrightarrow> (0\<^sub>L /\<^sub>L X) = 0\<^sub>L"
by (simp add: lens_quotient_def zero_lens_def)
end
|
Load "Hilbert1.v".
Section ORDERING.
(* Les axiomes d'ordre sont verifies. *)
(* B1 : If B is between A and C, then A, B, C are distinct points on a line, and also B is between C and A. *)
Lemma B1a : forall A B C, Between A B C -> A <> B.
Proof.
intros; immediate.
Qed.
Lemma B1b : forall A B C, Between A B C -> B <> C.
Proof.
intros; immediate.
Qed.
Lemma B1c : forall A B C, Between A B C -> C <> A.
Proof.
intros; immediate.
Qed.
Lemma B1d : forall A B C, Between A B C -> Collinear A B C.
Proof.
intros; immediate.
Qed.
Lemma B1e : forall A B C, Between A B C -> Between C B A.
Proof.
intros; immediate.
Qed.
(* B2 : For any two distinct points A, B, there exists a points C such that B is between A and C. *)
Lemma B2 : forall A B, A <> B -> exists C : Point, Between A B C.
Proof.
intros.
setSymmetric A B ipattern:C.
answerIs C.
Qed.
(* B3 : Given three distinct points on a line, one and only one of them is between the other two. *)
Lemma B3a : forall A B C, A <> B -> B <> C -> C <> A -> Collinear A B C ->
Between A B C \/ Between B C A \/ Between C A B.
Proof.
intros.
by3SegmentCases H2.
step H3.
step H4.
step H4.
Qed.
Lemma B3b : forall A B C, Between A B C -> ~Between B A C.
Proof.
intros A B C H H0.
from H0 (Between C A C).
since (C <> C).
absurdHyp H2.
Qed.
Lemma B3c : forall A B C, Between A B C -> ~Between A C B.
Proof.
intros A B C H H0.
from H (Between A B A).
since (A <> A).
absurdHyp H2.
Qed.
(* B4 : (Pasch). Let A, B, C be three noncollinear points, and let L be a line not containing any of A, B, C. If L contains a point D lying between A and B,
then it must contain either a point lying between A and C or a point lying between B and C, but not both. *)
Lemma B4a : forall A B C M N,
~Collinear A B C -> Between A M B -> ~Collinear A M N ->
~Collinear B M N -> ~Collinear C M N ->
(exists P : Point, Collinear M N P /\ Between A P C) \/
(exists P : Point, Collinear M N P /\ Between B P C).
Proof.
intros.
setLine M N ipattern:d.
byPaschCases A B C M d ipattern:P.
contrapose H1; step H1.
contrapose H2; step H2.
contrapose H3; step H3.
left; answerIs P; from H10 (Collinear M N P).
right; answerIs P; from H10 (Collinear M N P).
Qed.
Lemma B4b : forall A B C M N P Q,
~Collinear A B C -> Between A M B -> ~Collinear A M N -> ~Collinear B M N ->
~Collinear C M N -> Collinear M N P -> Between A P C -> Collinear M N Q ->
Between B Q C -> False.
Proof.
intros.
since (M <> P).
contrapose H.
since (Collinear A P C).
since (A <> P).
step H8.
step H.
since (M <> Q).
contrapose H.
since (B <> Q).
asWeHave (Collinear B Q C).
step H.
since (P <> Q).
contrapose H.
since (C <> Q).
asWeHave (Collinear B Q C).
step H.
destruct (B3a M P Q); try immediate.
since (M <> N).
step H6.
elim H; split; intro.
since (Clockwise A C B).
step H7.
step H5.
step H11.
step H0.
step H5.
contradict H12 H13.
since (Clockwise A B C).
step H5.
step H0.
step H11.
step H5.
step H7.
contradict H12 H13.
destruct H11.
elim H; split; intro.
since (Clockwise A C B).
step H5.
step H7.
right; step H11.
step H7.
step H0.
contradict H12 H13.
since (Clockwise A B C).
step H0.
step H7.
step H11.
step H7.
right; step H5.
contradict H12 H13.
elim H; split; intro.
since (Clockwise A C B).
step H0.
step H5.
step H11.
step H0.
step H7.
contradict H12 H13.
since (Clockwise A B C).
step H7.
step H0.
step H11.
step H5.
step H0.
contradict H12 H13.
Qed.
End ORDERING.
|
lemma holomorphic_on_paste_across_line: assumes S: "open S" and "d \<noteq> 0" and holf1: "f holomorphic_on (S \<inter> {z. d \<bullet> z < k})" and holf2: "f holomorphic_on (S \<inter> {z. k < d \<bullet> z})" and contf: "continuous_on S f" shows "f holomorphic_on S"
|
(*
* Copyright 2020, Data61, CSIRO (ABN 41 687 119 230)
*
* SPDX-License-Identifier: BSD-2-Clause
*)
theory Peterson_Atomicity
imports
Lib.Lib
Atomicity_Lib
begin
text \<open>
Preliminaries, a type of identities.
\<close>
datatype ident = A | B
primrec other_ident
where
"other_ident A = B"
| "other_ident B = A"
lemma other_ident_split:
"P (other_ident x) = ((x = A \<longrightarrow> P B) \<and> (x = B \<longrightarrow> P A))"
by (cases x, simp_all)
lemma neq_A_B[simp]:
"(x \<noteq> A) = (x = B)"
"(A \<noteq> x) = (x = B)"
"(x \<noteq> B) = (x = A)"
"(B \<noteq> x) = (x = A)"
by (simp | cases x)+
lemma forall_ident_eq:
"(\<forall>ident. P ident) = (P A \<and> P B)"
using ident.nchotomy
by metis
lemma other_other_ident_simps[simp]:
"other_ident (other_ident x) = x"
"(other_ident x = y) = (x \<noteq> y)"
"(x = other_ident y) = (x \<noteq> y)"
by (simp_all split: other_ident_split add: eq_commute)
text \<open>
The state of the algorithm. The variables A/B are condensed into
an ab_v variable, so we can parametrise by thread A/B. The priority
variable is t_v, and the critical section cs has two variable to
operate on, cs1_v and cs2_v.
Labels are needed to track where we're up to for the preconditions,
relies and guarantees.
\<close>
datatype label = Awaiting | Critical | Exited
record ('a, 'b) p_state =
ab_v :: "ident \<Rightarrow> bool"
ab_label :: "ident \<Rightarrow> label"
t_v :: "ident"
cs1_v :: "'a"
cs2_v :: "'b"
locale mx_locale =
fixes cs1 :: "'b \<Rightarrow> 'a"
and cs2 :: "(('a, 'b) p_state, unit) tmonad"
and csI :: "'b \<Rightarrow> bool"
begin
definition
set_ab :: "ident \<Rightarrow> bool \<Rightarrow> ('a, 'b) p_state \<Rightarrow> ('a, 'b) p_state"
where
"set_ab ident trying s = (s \<lparr> ab_v := (ab_v s) (ident := trying) \<rparr>)"
definition
set_label :: "ident \<Rightarrow> label \<Rightarrow> ('a, 'b) p_state \<Rightarrow> ('a, 'b) p_state"
where
"set_label ident label s = (s \<lparr> ab_label := (ab_label s) (ident := label) \<rparr>)"
definition
locked :: "ident \<Rightarrow> ('a, 'b) p_state \<Rightarrow> bool"
where
"locked ident s = (ab_v s (other_ident ident) \<longrightarrow> t_v s = ident)"
definition
acquire_lock :: "ident \<Rightarrow> (('a, 'b) p_state, unit) tmonad"
where
"acquire_lock ident = do
interference;
modify (set_ab ident True);
modify (\<lambda>s. s \<lparr> t_v := other_ident ident \<rparr>);
modify (set_label ident Awaiting);
interference;
Await (locked ident);
modify (set_label ident Critical)
od"
definition
release_lock :: "ident \<Rightarrow> (('a, 'b) p_state, unit) tmonad"
where
"release_lock ident = do
modify (set_ab ident False);
modify (set_label ident Exited);
interference;
return ()
od"
definition
abs_critical_section :: "(('a, 'b) p_state, unit) tmonad"
where
"abs_critical_section = do
interferences;
modify (\<lambda>s. s \<lparr> cs1_v := cs1 (cs2_v s) \<rparr>);
cs2;
interference
od"
definition
abs_peterson_proc ::
"ident \<Rightarrow> (('a, 'b) p_state, unit) tmonad"
where
"abs_peterson_proc ident = do
acquire_lock ident;
abs_critical_section;
release_lock ident
od"
definition
critical_section :: "(('a, 'b) p_state, unit) tmonad"
where
"critical_section = do
interference;
modify (\<lambda>s. s \<lparr> cs1_v := cs1 (cs2_v s) \<rparr>);
interference;
cs2;
interference
od"
definition
peterson_proc :: "ident \<Rightarrow> (('a, 'b) p_state, unit) tmonad"
where
"peterson_proc ident = do
acquire_lock ident;
critical_section;
release_lock ident
od"
abbreviation "critical label \<equiv> label = Critical"
text \<open>The required invariant. We can't both be in the critical section.
Whenever neither of us is in the critical section, its invariant holds.\<close>
definition
req_peterson_inv :: "('a, 'b) p_state \<Rightarrow> bool"
where
"req_peterson_inv s = (\<not> (critical (ab_label s A) \<and> critical (ab_label s B))
\<and> (critical (ab_label s A) \<or> critical (ab_label s B) \<or> csI (cs2_v s)))"
text \<open>The key invariant. We can't both be enabled, where that means
either we're in the critical section or waiting to enter with priority.
\<close>
abbreviation(input)
enabled :: "ident \<Rightarrow> ('a, 'b) p_state \<Rightarrow> bool"
where
"enabled ident s \<equiv> (critical (ab_label s ident)
\<or> (ab_label s ident = Awaiting \<and> t_v s = ident))"
definition
key_peterson_inv :: "('a, 'b) p_state \<Rightarrow> bool"
where
"key_peterson_inv s = (\<not> (enabled A s \<and> enabled B s))"
text \<open>Some trivia about labels and variables.\<close>
definition
local_peterson_inv :: "('a, 'b) p_state \<Rightarrow> bool"
where
"local_peterson_inv s
= (\<forall>ident. ab_label s ident \<noteq> Exited \<longrightarrow> ab_v s ident)"
definition
"invs s = (req_peterson_inv s
\<and> key_peterson_inv s \<and> local_peterson_inv s)"
lemmas invs_defs = req_peterson_inv_def key_peterson_inv_def local_peterson_inv_def
definition
peterson_rel :: "ident \<Rightarrow> ('a, 'b) p_state \<Rightarrow> ('a, 'b) p_state \<Rightarrow> bool"
where
"peterson_rel ident s_prior s = (\<comment> \<open>assume invs\<close> invs s_prior \<longrightarrow>
\<comment> \<open>invariants are preserved\<close>
(invs s
\<comment> \<open>I won't adjust your variables\<close>
\<and> (ab_v s (other_ident ident) = ab_v s_prior (other_ident ident))
\<and> (ab_label s (other_ident ident) = ab_label s_prior (other_ident ident))
\<comment> \<open>I will only ever give you priority\<close>
\<and> (t_v s_prior = other_ident ident \<longrightarrow> t_v s = other_ident ident)
\<comment> \<open>If you're in the critical section, I won't change cs2_v and cs1_v\<close>
\<and> (critical (ab_label s_prior (other_ident ident))
\<longrightarrow> cs2_v s = cs2_v s_prior \<and> cs1_v s = cs1_v s_prior)
))"
lemma peterson_rel_rtranclp[simp]:
"rtranclp (peterson_rel ident) = (peterson_rel ident)"
apply (rule rtranclp_id2)
apply (clarsimp simp: peterson_rel_def)
apply (clarsimp simp: peterson_rel_def)
done
lemma reflp_peterson_rel[simp]:
"reflp (peterson_rel x)"
apply (rule reflpI)
apply (clarsimp simp add: peterson_rel_def)
done
declare reflp_peterson_rel[THEN reflpD, simp]
lemma peterson_rel_imp_assume_invs:
"invs x \<Longrightarrow> (peterson_rel ident x y \<and> invs x \<and> invs y \<longrightarrow> P x y)
\<Longrightarrow> (peterson_rel ident x y \<longrightarrow> P x y)"
by (simp add: peterson_rel_def)
end
text \<open>
We assume validity for the underspecified critical section code represented by
@{text cs2}.
We also assume some basic sanity properties about the structure of @{text cs2}.
\<close>
locale mx_locale_wp = mx_locale cs1 cs2 csI for cs1 :: "'b \<Rightarrow> 'a" and cs2 and csI +
assumes
cs_wp: "\<forall>s c. I s \<and> lockf s \<longrightarrow> I s \<and> lockf (s \<lparr> cs2_v := c \<rparr>)
\<Longrightarrow>
\<lbrace> \<lambda>s0' s'. csI (cs2_v s') \<and> s0' = s0 \<and> s' = s \<and> I s \<and> lockf s
\<and> cs1_v s' = cs1 (cs2_v s') \<rbrace>,
\<lbrace> \<lambda>s0 s. I s0 \<and> lockf s0 \<longrightarrow> cs2_v s = cs2_v s0 \<and> I s \<and> lockf s
\<and> cs1_v s = cs1_v s0 \<rbrace>
cs2
\<lbrace> \<lambda>s0 s. I s0 \<longrightarrow> (\<exists>c. s = s0 \<lparr> cs2_v := c \<rparr>) \<and> I s \<and> lockf s \<rbrace>,
\<lbrace> \<lambda>_ s0' s'. \<exists>c. csI c \<and> s' = s \<lparr> cs2_v := c \<rparr>
\<and> (\<exists>c'. s0' = s0 \<or> s0' = s \<lparr> cs2_v := c' \<rparr>)
\<and> I s' \<and> lockf s' \<rbrace>"
and cs_closed: "prefix_closed cs2"
and cs_not_env_steps_first: "not_env_steps_first cs2"
begin
method_setup rev_drule = \<open>
Attrib.thms >> curry (fn (thms, ctxt)
=> SIMPLE_METHOD (dresolve_tac ctxt thms 1 #> Seq.list_of #> rev #> Seq.of_list))
\<close>
lemma cs2_wp_apply_peterson[wp]:
"\<lbrace> (\<lambda>s0 s. csI (cs2_v s)
\<and> invs s0 \<and> invs s \<and> critical (ab_label s ident)
\<and> cs1_v s = cs1 (cs2_v s)
\<and> (\<forall>s0' c' c. csI c \<longrightarrow> (\<exists>c'. s0' = s0 \<or> s0' = s \<lparr> cs2_v := c' \<rparr>)
\<longrightarrow> Q () s0' (s \<lparr> cs2_v := c\<rparr>))) \<rbrace>,
\<lbrace> peterson_rel (other_ident ident) \<rbrace>
cs2
\<lbrace> peterson_rel ident \<rbrace>,
\<lbrace> Q \<rbrace>"
apply (rule validI_name_pre[OF cs_closed], clarsimp simp del: imp_disjL)
apply (rule validI_weaken_pre)
apply (rule validI_well_behaved[OF cs_closed])
apply (rule validI_strengthen_post)
apply (rule_tac s=s and ?s0.0=s0
and lockf="\<lambda>s. critical (ab_label s ident)"
and I="invs" in cs_wp)
apply (clarsimp simp: invs_defs invs_def)
apply (clarsimp simp del: imp_disjL)
apply (simp only: imp_conjL[symmetric])
apply (thin_tac "\<forall>x. P x" for P)
apply (clarsimp simp: peterson_rel_def)
apply (thin_tac "\<forall>x. P x" for P)
apply (clarsimp simp: peterson_rel_def)
apply (cases ident; fastforce simp: invs_def key_peterson_inv_def)
apply clarsimp
done
lemma release_lock_mutual_excl:
"\<lbrace> \<lambda>s0 s. peterson_rel ident s0 s \<and> invs s
\<and> ab_label s ident = Critical \<and> csI (cs2_v s) \<rbrace>,
\<lbrace> peterson_rel (other_ident ident) \<rbrace>
release_lock ident
\<lbrace> peterson_rel ident \<rbrace>,
\<lbrace> \<lambda>rv s0 s. peterson_rel ident s0 s \<and> invs s
\<and> ab_label s ident = Exited \<rbrace>"
apply (simp add: release_lock_def)
apply (rule validI_weaken_pre)
apply wpsimp+
apply (strengthen peterson_rel_imp_assume_invs | simp)+
apply (cases ident)
apply (safe, simp_all)
by ((clarsimp simp: peterson_rel_def set_label_def
set_ab_def invs_defs
| rule invs_def[THEN iffD2] conjI
| rev_drule invs_def[THEN iffD1])+)
lemma abs_critical_section_mutual_excl:
"\<lbrace> \<lambda>s0 s. peterson_rel ident s0 s \<and> invs s \<and> invs s0
\<and> ab_label s ident = Critical \<and> csI (cs2_v s) \<rbrace>,
\<lbrace> peterson_rel (other_ident ident) \<rbrace>
abs_critical_section
\<lbrace> peterson_rel ident \<rbrace>,
\<lbrace> \<lambda>rv s0 s. peterson_rel ident s0 s \<and> invs s
\<and> ab_label s ident = Critical \<and> csI (cs2_v s) \<rbrace>"
apply (simp add: abs_critical_section_def)
apply (rule validI_weaken_pre)
apply wpsimp+
apply (strengthen peterson_rel_imp_assume_invs | simp)+
apply (cases ident)
apply (safe, simp_all)
by ((clarsimp simp: peterson_rel_def invs_defs
| rule invs_def[THEN iffD2] conjI
| rev_drule invs_def[THEN iffD1])+)
lemma acquire_lock_mutual_excl:
"\<lbrace> \<lambda>s0 s. peterson_rel ident s0 s \<and> invs s
\<and> ab_label s ident = Exited \<rbrace>,
\<lbrace> peterson_rel (other_ident ident) \<rbrace>
acquire_lock ident
\<lbrace> peterson_rel ident \<rbrace>,
\<lbrace> \<lambda>rv s0 s. peterson_rel ident s0 s \<and> invs s \<and> invs s0
\<and> ab_label s ident = Critical \<and> csI (cs2_v s) \<rbrace>"
apply (simp add: acquire_lock_def)
apply (rule validI_weaken_pre)
apply (wpsimp wp: Await_sync_twp)+
apply (strengthen peterson_rel_imp_assume_invs | simp)+
apply (cases ident)
apply (safe, simp_all)
by ((clarsimp simp: peterson_rel_def set_label_def set_ab_def
locked_def invs_defs
| rule invs_def[THEN iffD2] conjI
| rev_drule invs_def[THEN iffD1])+)
theorem abs_peterson_proc_mutual_excl:
"\<lbrace> \<lambda>s0 s. peterson_rel ident s0 s \<and> invs s
\<and> ab_label s ident = Exited \<rbrace>,
\<lbrace> peterson_rel (other_ident ident) \<rbrace>
abs_peterson_proc ident
\<lbrace> peterson_rel ident \<rbrace>,
\<lbrace> \<lambda>rv s0 s. peterson_rel ident s0 s \<and> invs s
\<and> ab_label s ident = Exited \<rbrace>"
apply (simp add: abs_peterson_proc_def bind_assoc)
apply (rule validI_weaken_pre)
apply (wpsimp wp: release_lock_mutual_excl acquire_lock_mutual_excl
abs_critical_section_mutual_excl)+
done
definition
peterson_sr :: "(('a, 'b) p_state \<Rightarrow> ('a, 'b) p_state \<Rightarrow> bool)"
where
"peterson_sr sa sc \<equiv>
t_v sa = t_v sc \<and> ab_v sa = ab_v sc
\<and> ab_label sa = ab_label sc \<and> cs2_v sa = cs2_v sc"
definition
peterson_sr' :: "(('a, 'b) p_state \<Rightarrow> ('a, 'b) p_state \<Rightarrow> bool)"
where
"peterson_sr' sa sc \<equiv> sa = sc \<lparr> cs1_v := cs1_v sa \<rparr>"
definition
peterson_sr_cs1 :: "(('a, 'b) p_state \<Rightarrow> ('a, 'b) p_state \<Rightarrow> bool)"
where
"peterson_sr_cs1 sa sc \<equiv> peterson_sr sa sc \<and> cs1_v sa = cs1_v sc"
end
text \<open>
Finally we assume that we can prove refinement for @{text cs2}, although this
may depend on being in a state where @{term cs1_v} has been correctly
initialised.
\<close>
locale mx_locale_refine = mx_locale_wp cs1 cs2 csI for cs1 :: "'b \<Rightarrow> 'a" and cs2 and csI +
assumes
cs_refine:
"prefix_refinement peterson_sr peterson_sr_cs1 peterson_sr \<top>\<top>
(\<lambda>_ s. cs1_v s = cs1 (cs2_v s)) \<top>\<top>
(peterson_rel (other_ident ident)) (peterson_rel (other_ident ident))
cs2 cs2"
begin
lemma
"peterson_sr = peterson_sr'"
by (auto simp: p_state.splits peterson_sr_def peterson_sr'_def intro!: ext)
lemma peterson_sr_set_ab[simp]:
"peterson_sr s t \<Longrightarrow> peterson_sr (set_ab ident v s) (set_ab ident v t)"
by (simp add: peterson_sr_def set_ab_def)
lemma env_stable_peterson_sr:
"env_stable AR R peterson_sr peterson_sr \<top>"
by (fastforce simp: env_stable_def rely_stable_def env_rely_stable_iosr_def peterson_sr_def)
lemmas prefix_refinement_interference_peterson =
prefix_refinement_interference[OF env_stable_peterson_sr]
lemma peterson_sr_reflp[simp]:
"reflp peterson_sr"
by (simp add: peterson_sr_def reflpI)
lemma peterson_sr_equivp[simp]:
"equivp peterson_sr"
by (auto simp: peterson_sr_def intro!: sympI equivpI transpI)
lemma peterson_sr_cs1_invs: "peterson_sr_cs1 s t \<Longrightarrow> invs s = invs t"
apply (auto simp: peterson_sr_def peterson_sr_cs1_def invs_def
req_peterson_inv_def key_peterson_inv_def
local_peterson_inv_def)[1]
done
lemma env_stable_peterson_sr_cs1:
"env_stable (peterson_rel (other_ident ident)) (peterson_rel (other_ident ident))
peterson_sr peterson_sr_cs1 (\<lambda>s. invs s \<and> critical (ab_label s ident))"
apply (simp add: env_stable_def rely_stable_def env_rely_stable_iosr_def
peterson_rel_def)
apply (rule conjI)
apply (auto simp: peterson_sr_def peterson_sr_cs1_def)[1]
apply (rule conjI)
apply clarsimp
apply (clarsimp simp: peterson_sr_cs1_invs)
apply (auto simp: peterson_sr_cs1_def peterson_sr_def)[1]
apply (auto simp: peterson_sr_cs1_def peterson_sr_def)[1]
done
lemmas prefix_refinement_interference_peterson_cs1 =
prefix_refinement_interference[OF env_stable_peterson_sr_cs1]
lemmas prefix_refinement_bind_2left_2right
= prefix_refinement_bind[where a="bind a a'" and c="bind c c'" for a a' c c', simplified bind_assoc]
lemmas rel_tr_refinement_bind_left_general_2left_2right
= rel_tr_refinement_bind_left_general[where f="bind f f'" and g="bind g g'" for f f' g g', simplified bind_assoc]
lemma peterson_rel_imp_invs:
"peterson_rel ident x y \<Longrightarrow> invs x \<Longrightarrow> invs y"
by (simp add: peterson_rel_def)
lemma peterson_rel_imp_label:
"peterson_rel (other_ident ident) x y \<Longrightarrow> invs x
\<Longrightarrow> ab_label x ident = ab_label y ident"
by (simp add: peterson_rel_def)
lemma peterson_rel_set_label:
"peterson_rel (other_ident ident) (set_label ident label s) s'
\<Longrightarrow> invs (set_label ident label s)
\<Longrightarrow> ab_label s' ident = label"
by (simp add: peterson_rel_def set_label_def)
lemma acquire_lock_refinement:
"prefix_refinement peterson_sr peterson_sr peterson_sr \<top>\<top>
\<top>\<top> \<top>\<top>
(peterson_rel (other_ident ident)) (peterson_rel (other_ident ident))
(acquire_lock ident) (acquire_lock ident)"
apply (unfold acquire_lock_def)
apply (rule prefix_refinement_weaken_pre)
apply (rule prefix_refinement_bind_sr)
apply (rule prefix_refinement_interference_peterson)
apply (simp add: modify_modify_bind)
apply (rule prefix_refinement_bind_sr)
apply (rule pfx_refn_modifyT)
apply (clarsimp simp add: peterson_sr_def set_label_def set_ab_def forall_ident_eq)
apply (rule prefix_refinement_bind_sr)
apply (rule prefix_refinement_interference_peterson)
apply (rule prefix_refinement_bind_sr)
apply (rule prefix_refinement_Await[OF env_stable_peterson_sr abs_rely_stableT])
apply (clarsimp simp add: peterson_sr_def locked_def)
apply (clarsimp simp add: peterson_sr_def locked_def)
apply (rule pfx_refn_modifyT)
apply (clarsimp simp add: peterson_sr_def set_label_def)
apply (wpsimp wp: Await_sync_twp)+
done
lemma peterson_sr_invs[simp]:
"peterson_sr as cs \<Longrightarrow> invs as \<Longrightarrow> invs cs"
by (simp add: peterson_sr_def invs_def invs_defs)
lemma peterson_sr_invs_sym:
"peterson_sr as cs \<Longrightarrow> invs cs \<Longrightarrow> invs as"
by (simp add: peterson_sr_def invs_def invs_defs)
lemma peterson_sr_ab_label:
"peterson_sr as cs \<Longrightarrow> ab_label as = ab_label cs"
by (simp add: peterson_sr_def)
lemma critical_section_refinement:
"prefix_refinement peterson_sr peterson_sr peterson_sr \<top>\<top>
(\<lambda>_ s. invs s \<and> ab_label s ident = Critical) \<top>\<top>
(peterson_rel (other_ident ident)) (peterson_rel (other_ident ident))
abs_critical_section critical_section"
apply (simp add: abs_critical_section_def critical_section_def)
apply (rule prefix_refinement_weaken_pre)
apply (rule prefix_refinement_interferences_split)
apply (rule prefix_refinement_bind_sr)
apply (rule prefix_refinement_interference_peterson)
(* reorder the interference and modify*)
apply (rule pfx_refinement_use_rel_tr_refinement_equivp
[where Q="\<lambda>s. invs s \<and> ab_label s (ident) = Critical"])
apply (rule rel_tr_refinement_bind_left_general_2left_2right)
apply simp
apply (rule disjI1,
clarsimp simp: not_env_steps_first_all
cs_not_env_steps_first release_lock_def)
apply (rule rshuttle_modify_interference)
apply (simp add: peterson_sr_def peterson_rel_def)
apply (clarsimp simp: peterson_rel_def)
apply (clarsimp simp: p_state.splits)
apply (clarsimp simp: peterson_rel_def invs_def invs_defs)
apply simp
apply (rule prefix_refinement_bind_sr)
apply (rule prefix_refinement_interference_peterson)
apply (rule prefix_refinement_bind[where intsr=peterson_sr_cs1])
apply (rule pfx_refn_modifyT)
apply (clarsimp simp add: peterson_sr_def peterson_sr_cs1_def)
apply (rule prefix_refinement_bind_sr)
apply (rule cs_refine)
apply (rule prefix_refinement_interference_peterson)
apply (wpsimp wp: validI_triv[OF cs_closed])+
apply (subst peterson_rel_imp_label[symmetric], assumption, simp)
apply (drule peterson_rel_imp_invs, simp)
apply (simp add: peterson_sr_ab_label)
done
lemma release_lock_refinement:
"prefix_refinement peterson_sr peterson_sr peterson_sr \<top>\<top>
\<top>\<top> \<top>\<top>
(peterson_rel (other_ident ident)) (peterson_rel (other_ident ident))
(release_lock ident) (release_lock ident)"
apply (unfold release_lock_def)
apply (rule prefix_refinement_weaken_pre)
apply (simp add: modify_modify_bind)
apply (rule prefix_refinement_bind_sr)
apply (rule pfx_refn_modifyT)
apply (clarsimp simp add: peterson_sr_def peterson_sr_cs1_def set_label_def set_ab_def)
apply (rule prefix_refinement_interference_peterson)
apply wpsimp+
done
lemma critical_section_prefix_closed[simp]:
"prefix_closed critical_section"
by (auto intro!: prefix_closed_bind
simp: cs_closed critical_section_def)
lemma abs_critical_section_prefix_closed[simp]:
"prefix_closed abs_critical_section"
by (auto intro!: prefix_closed_bind
simp: cs_closed abs_critical_section_def)
lemma peterson_rel_trans:
"peterson_rel ident x y \<Longrightarrow> peterson_rel ident y z \<Longrightarrow>
peterson_rel ident x z"
by (clarsimp simp: peterson_rel_def)
lemma invs_set_label_Critical:
"invs s \<Longrightarrow> locked ident s \<Longrightarrow> ab_label s ident = Awaiting
\<Longrightarrow> invs (set_label ident Critical s)"
by (auto simp: invs_def invs_defs set_label_def locked_def)
lemma acquire_lock_wp:
"\<lbrace> \<lambda>s0 s. invs s \<and> ab_label s ident = Exited \<rbrace>,
\<lbrace> peterson_rel (other_ident ident) \<rbrace>
acquire_lock ident
\<lbrace> \<top>\<top> \<rbrace>,
\<lbrace> \<lambda>rv s0 s. invs s \<and> ab_label s ident = Critical \<rbrace>"
apply (simp add: acquire_lock_def)
apply (rule validI_weaken_pre)
apply (wpsimp wp: Await_sync_twp)+
apply (subst (asm) peterson_rel_imp_label, assumption+)
apply (drule(1) peterson_rel_imp_invs)
apply (drule(1) peterson_rel_trans)
apply (thin_tac "peterson_rel (other_ident ident) s'a x")
apply (frule peterson_rel_set_label)
apply (fastforce simp: set_label_def set_ab_def
locked_def invs_def invs_defs)
apply (drule peterson_rel_imp_invs)
apply (fastforce simp: set_label_def set_ab_def
locked_def invs_def invs_defs)
apply (clarsimp simp: invs_set_label_Critical)
apply (clarsimp simp: set_label_def set_ab_def)
done
lemma acquire_lock_prefix_closed[simp]:
"prefix_closed (acquire_lock ident)"
by (auto intro!: prefix_closed_bind
simp: cs_closed acquire_lock_def)
theorem peterson_proc_refinement:
"prefix_refinement peterson_sr peterson_sr peterson_sr \<top>\<top>
(\<lambda>_ s. invs s \<and> ab_label s ident = Exited)
(\<lambda>_ s. invs s \<and> ab_label s ident = Exited)
(peterson_rel (other_ident ident)) (peterson_rel (other_ident ident))
(abs_peterson_proc ident)
(peterson_proc ident)"
apply (simp add: abs_peterson_proc_def peterson_proc_def)
apply (rule prefix_refinement_weaken_pre)
apply (rule prefix_refinement_bind_sr)
apply (rule acquire_lock_refinement)
apply (rule prefix_refinement_bind_sr)
apply (rule critical_section_refinement)
apply (rule release_lock_refinement)
apply (wpsimp wp: validI_triv acquire_lock_wp
simp: pred_conj_def)+
done
definition
peterson_rel2 :: "ident \<Rightarrow> ('a, 'b) p_state \<Rightarrow> ('a, 'b) p_state \<Rightarrow> bool"
where
"peterson_rel2 ident s_prior s = (\<comment> \<open>assume invs\<close> invs s_prior \<longrightarrow>
\<comment> \<open>If you're in the critical section, I won't change cs1_v\<close>
(critical (ab_label s_prior (other_ident ident))
\<longrightarrow> cs1_v s = cs1_v s_prior))"
definition
peterson_rel3 :: "ident \<Rightarrow> ('a, 'b) p_state \<Rightarrow> ('a, 'b) p_state \<Rightarrow> bool"
where
"peterson_rel3 ident s_prior s = (\<comment> \<open>assume invs\<close> invs s_prior \<longrightarrow>
\<comment> \<open>invariants are preserved\<close>
(invs s
\<comment> \<open>I won't adjust your variables\<close>
\<and> (ab_v s (other_ident ident) = ab_v s_prior (other_ident ident))
\<and> (ab_label s (other_ident ident) = ab_label s_prior (other_ident ident))
\<comment> \<open>I will only ever give you priority\<close>
\<and> (t_v s_prior = other_ident ident \<longrightarrow> t_v s = other_ident ident)
\<comment> \<open>If you're in the critical section, I won't change cs2_v\<close>
\<and> (critical (ab_label s_prior (other_ident ident))
\<longrightarrow> cs2_v s = cs2_v s_prior)))"
lemma peterson_rel_helpers:
"peterson_rel2 ident s0 s \<and> peterson_rel3 ident s0 s
\<longrightarrow> peterson_rel ident s0 s"
by (clarsimp simp: peterson_rel_def peterson_rel2_def peterson_rel3_def)
lemma peterson_rel_peterson_rel2:
"peterson_rel ident s0 s \<longrightarrow> peterson_rel2 ident s0 s"
by (clarsimp simp: peterson_rel_def peterson_rel2_def)
lemma peterson_sr_peterson_rel3:
"peterson_sr as0 cs0 \<Longrightarrow> peterson_sr as cs
\<Longrightarrow> peterson_rel ident as0 as \<Longrightarrow> peterson_rel3 ident cs0 cs"
apply (clarsimp simp: peterson_rel_def peterson_rel3_def invs_def
invs_defs peterson_sr_ab_label)
apply (clarsimp simp: peterson_sr_def)
done
lemma peterson_proc_prefix_closed[simp]:
"prefix_closed (peterson_proc ident)"
by (auto intro!: prefix_closed_bind
simp: cs_closed peterson_proc_def acquire_lock_def release_lock_def)
lemma peterson_proc_mutual_excl_helper:
"\<lbrace> \<lambda>s0 s. peterson_rel ident s0 s \<and> invs s
\<and> ab_label s ident = Exited \<rbrace>,
\<lbrace> peterson_rel (other_ident ident) \<rbrace>
peterson_proc ident
\<lbrace> peterson_rel3 ident \<rbrace>,
\<lbrace> \<lambda>rv s0 s. peterson_rel3 ident s0 s \<and> invs s
\<and> ab_label s ident = Exited \<rbrace>"
apply (rule prefix_refinement_validI')
apply (rule peterson_proc_refinement)
apply (rule abs_peterson_proc_mutual_excl)
apply (clarsimp simp: peterson_sr_peterson_rel3 peterson_sr_ab_label)
apply (clarsimp simp: peterson_sr_peterson_rel3)
apply clarsimp
apply (rule_tac x=t0 in exI)
apply (rule_tac x="t \<lparr>cs1_v := cs1_v t0\<rparr>" in exI)
apply (clarsimp simp: peterson_rel_def peterson_sr_def)
apply clarsimp
apply (rule_tac x="t \<lparr>cs1_v := cs1_v s0\<rparr>" in exI)
apply (clarsimp simp: peterson_rel_def peterson_sr_def invs_def invs_defs)
apply clarsimp
done
lemma peterson_proc_mutual_excl_helper':
"\<lbrace> \<lambda>s0 s. peterson_rel ident s0 s \<and> invs s
\<and> ab_label s ident = Exited \<rbrace>,
\<lbrace> peterson_rel (other_ident ident) \<rbrace>
peterson_proc ident
\<lbrace> peterson_rel2 ident \<rbrace>,
\<lbrace> \<lambda>rv s0 s. peterson_rel2 ident s0 s \<and> invs s
\<and> ab_label s ident = Exited \<rbrace>"
apply (simp add: peterson_proc_def acquire_lock_def release_lock_def
critical_section_def)
apply (rule validI_weaken_pre)
apply (wp Await_sync_twp | simp add: split_def
| rule validI_strengthen_guar[OF _ allI[OF allI[OF peterson_rel_peterson_rel2]]])+
apply (clarsimp simp: imp_conjL)
apply (strengthen peterson_rel_imp_assume_invs | simp)+
apply (cases ident)
apply (safe, simp_all)
by ((clarsimp simp: peterson_rel_def peterson_rel2_def forall_ident_eq
set_label_def set_ab_def locked_def invs_defs cs_closed
| rule invs_def[THEN iffD2] conjI
| rev_drule invs_def[THEN iffD1])+)
lemma peterson_proc_mutual_excl:
"\<lbrace> \<lambda>s0 s. peterson_rel ident s0 s \<and> invs s
\<and> ab_label s ident = Exited \<rbrace>,
\<lbrace> peterson_rel (other_ident ident) \<rbrace>
peterson_proc ident
\<lbrace> peterson_rel ident \<rbrace>,
\<lbrace> \<lambda>rv s0 s. peterson_rel ident s0 s \<and> invs s
\<and> ab_label s ident = Exited \<rbrace>"
apply (rule validI_strengthen_guar, rule validI_strengthen_post, rule validI_guar_post_conj_lift)
apply (rule peterson_proc_mutual_excl_helper)
apply (rule peterson_proc_mutual_excl_helper')
apply (clarsimp simp: peterson_rel_helpers)+
done
definition "abs_peterson_proc_system \<equiv>
parallel (do repeat (abs_peterson_proc A); interference od)
(do repeat (abs_peterson_proc B); interference od)"
lemma validI_repeat_interference:
"\<lbrace>P\<rbrace>, \<lbrace>R\<rbrace> f \<lbrace>G\<rbrace>, \<lbrace>\<lambda>_. P\<rbrace>
\<Longrightarrow> \<forall>s0 s. P s0 s \<longrightarrow> (\<forall>s'. R\<^sup>*\<^sup>* s s' \<longrightarrow> Q () s' s') \<and> G s0 s
\<Longrightarrow> \<lbrace>P\<rbrace>, \<lbrace>R\<rbrace> do repeat f; interference od \<lbrace>G\<rbrace>, \<lbrace>Q\<rbrace>"
apply (rule bind_twp)
apply simp
apply (rule interference_twp)
apply (rule validI_strengthen_post)
apply (rule repeat_validI, assumption)
apply simp
done
lemma abs_peterson_proc_system_mutual_excl:
"\<lbrace> \<lambda>s0 s. s0 = s \<and> invs s \<and> ab_label s = (\<lambda>_. Exited) \<rbrace>,
\<lbrace> \<lambda>s0 s. s0 = s \<rbrace>
abs_peterson_proc_system
\<lbrace> \<lambda>s0 s. invs s0 \<longrightarrow> invs s \<rbrace>,
\<lbrace> \<lambda>rv s0 s. invs s \<rbrace>"
apply (rule validI_weaken_pre, rule validI_strengthen_post)
apply (unfold abs_peterson_proc_system_def)
apply (rule rg_validI[where Qf="\<lambda>_ _. invs" and Qg="\<lambda>_ _. invs"])
apply (rule validI_repeat_interference[OF abs_peterson_proc_mutual_excl])
apply (clarsimp simp: peterson_rel_imp_invs)
apply (rule validI_repeat_interference[OF abs_peterson_proc_mutual_excl])
apply (clarsimp simp: peterson_rel_imp_invs)
apply (simp add: reflp_ge_eq)+
apply (clarsimp simp: peterson_rel_def)+
done
definition "peterson_proc_system \<equiv>
parallel (do repeat (peterson_proc A); interference od)
(do repeat (peterson_proc B); interference od)"
lemma abs_peterson_proc_prefix_closed[simp]:
"prefix_closed (abs_peterson_proc ident)"
by (auto intro!: prefix_closed_bind
simp: cs_closed abs_peterson_proc_def acquire_lock_def release_lock_def)
lemma peterson_repeat_refinement:
"prefix_refinement peterson_sr peterson_sr peterson_sr \<top>\<top>
(\<lambda>s0 s. peterson_rel ident s0 s \<and> invs s \<and> ab_label s ident = Exited)
(\<lambda>s0 s. peterson_rel ident s0 s \<and> invs s \<and> ab_label s ident = Exited)
(peterson_rel (other_ident ident)) (peterson_rel (other_ident ident))
(do repeat (abs_peterson_proc ident);
interference
od)
(do repeat (peterson_proc ident);
interference
od)"
apply (rule prefix_refinement_weaken_pre)
apply (rule prefix_refinement_bind_sr)
apply (rule prefix_refinement_repeat[rotated])
apply (rule abs_peterson_proc_mutual_excl[THEN validI_strengthen_guar])
apply simp
apply (rule peterson_proc_mutual_excl[THEN validI_strengthen_guar, THEN validI_weaken_pre])
apply simp+
apply (rule peterson_proc_refinement[THEN prefix_refinement_weaken_pre])
apply simp+
apply (rule prefix_refinement_interference_peterson)
apply (wpsimp wp: validI_triv)+
done
theorem peterson_proc_system_refinement:
"prefix_refinement peterson_sr peterson_sr peterson_sr \<top>\<top>
(\<lambda>s0 s. s0 = s \<and> invs s \<and> ab_label s = (\<lambda>_. Exited))
(\<lambda>t0 t. t0 = t \<and> invs t \<and> ab_label t = (\<lambda>_. Exited))
(\<lambda>s0 s. s0 = s) (\<lambda>t0 t. t0 = t)
abs_peterson_proc_system peterson_proc_system"
apply (unfold abs_peterson_proc_system_def peterson_proc_system_def)
apply (rule prefix_refinement_parallel')
apply (rule prefix_refinement_weaken_rely, rule prefix_refinement_weaken_pre)
apply (rule peterson_repeat_refinement)
apply simp
apply simp
apply (rule eq_refl, rule bipred_disj_op_eq, simp)
apply (rule eq_refl, rule bipred_disj_op_eq, simp)
apply (rule prefix_refinement_weaken_rely, rule prefix_refinement_weaken_pre)
apply (rule peterson_repeat_refinement)
apply simp
apply simp
apply (rule eq_refl, rule bipred_disj_op_eq, simp)
apply (rule eq_refl, rule bipred_disj_op_eq, simp)
apply (clarsimp intro!: par_tr_fin_bind par_tr_fin_interference)
apply (clarsimp intro!: par_tr_fin_bind par_tr_fin_interference)
apply (rule validI_weaken_pre, rule validI_weaken_rely)
apply (rule validI_repeat_interference; simp)
apply (rule peterson_proc_mutual_excl)
apply (simp+)[3]
apply (rule validI_weaken_pre, rule validI_weaken_rely)
apply (rule validI_repeat_interference; simp)
apply (rule peterson_proc_mutual_excl)
apply (simp+)[3]
apply (rule validI_weaken_pre, rule validI_weaken_rely)
apply (rule validI_repeat_interference; simp)
apply (rule abs_peterson_proc_mutual_excl)
apply (simp+)[3]
apply (rule validI_weaken_pre, rule validI_weaken_rely)
apply (rule validI_repeat_interference; simp)
apply (rule abs_peterson_proc_mutual_excl)
apply (simp+)[3]
done
lemma peterson_proc_system_prefix_closed[simp]:
"prefix_closed (peterson_proc_system)"
by (auto intro!: prefix_closed_bind parallel_prefix_closed
simp: cs_closed peterson_proc_system_def)
theorem peterson_proc_system_mutual_excl:
"\<lbrace> \<lambda>s0 s. s0 = s \<and> invs s \<and> ab_label s = (\<lambda>_. Exited) \<rbrace>,
\<lbrace> \<lambda>s0 s. s0 = s \<rbrace>
peterson_proc_system
\<lbrace> \<lambda>s0 s. invs s0 \<longrightarrow> invs s \<rbrace>,
\<lbrace> \<lambda>rv s0 s. invs s \<rbrace>"
apply (rule prefix_refinement_validI')
apply (rule peterson_proc_system_refinement)
apply (rule abs_peterson_proc_system_mutual_excl)
apply clarsimp
apply (clarsimp simp: peterson_sr_invs_sym )
apply (fastforce simp: peterson_rel_def peterson_sr_def)
apply clarsimp
apply (fastforce simp: peterson_sr_def)
done
end
end
|
If $p$ is a prime number greater than $2$, then $p$ is odd.
|
If $p$ is a prime number greater than $2$, then $p$ is odd.
|
State Before: F : Type ?u.837747
α : Type u_2
β : Type u_1
γ : Type ?u.837756
inst✝² : DecidableEq β
inst✝¹ : Group α
inst✝ : MulAction α β
s t : Finset β
a : α
b : β
⊢ a • s ⊆ t ↔ s ⊆ a⁻¹ • t State After: F : Type ?u.837747
α : Type u_2
β : Type u_1
γ : Type ?u.837756
inst✝² : DecidableEq β
inst✝¹ : Group α
inst✝ : MulAction α β
s t : Finset β
a : α
b : β
⊢ ↑(a • s) ⊆ ↑t ↔ ↑s ⊆ ↑(a⁻¹ • t) Tactic: simp_rw [← coe_subset] State Before: F : Type ?u.837747
α : Type u_2
β : Type u_1
γ : Type ?u.837756
inst✝² : DecidableEq β
inst✝¹ : Group α
inst✝ : MulAction α β
s t : Finset β
a : α
b : β
⊢ ↑(a • s) ⊆ ↑t ↔ ↑s ⊆ ↑(a⁻¹ • t) State After: F : Type ?u.837747
α : Type u_2
β : Type u_1
γ : Type ?u.837756
inst✝² : DecidableEq β
inst✝¹ : Group α
inst✝ : MulAction α β
s t : Finset β
a : α
b : β
⊢ a • ↑s ⊆ ↑t ↔ ↑s ⊆ a⁻¹ • ↑t Tactic: push_cast State Before: F : Type ?u.837747
α : Type u_2
β : Type u_1
γ : Type ?u.837756
inst✝² : DecidableEq β
inst✝¹ : Group α
inst✝ : MulAction α β
s t : Finset β
a : α
b : β
⊢ a • ↑s ⊆ ↑t ↔ ↑s ⊆ a⁻¹ • ↑t State After: no goals Tactic: exact Set.set_smul_subset_iff
|
/-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
! This file was ported from Lean 3 source module order.rel_iso.basic
! leanprover-community/mathlib commit 76171581280d5b5d1e2d1f4f37e5420357bdc636
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathlib.Data.FunLike.Basic
import Mathlib.Logic.Embedding.Basic
import Mathlib.Order.RelClasses
/-!
# Relation homomorphisms, embeddings, isomorphisms
This file defines relation homomorphisms, embeddings, isomorphisms and order embeddings and
isomorphisms.
## Main declarations
* `RelHom`: Relation homomorphism. A `RelHom r s` is a function `f : α → β` such that
`r a b → s (f a) (f b)`.
* `RelEmbedding`: Relation embedding. A `RelEmbedding r s` is an embedding `f : α ↪ β` such that
`r a b ↔ s (f a) (f b)`.
* `RelIso`: Relation isomorphism. A `RelIso r s` is an equivalence `f : α ≃ β` such that
`r a b ↔ s (f a) (f b)`.
* `sumLexCongr`, `prodLexCongr`: Creates a relation homomorphism between two `Sum.Lex` or two
`Prod.Lex` from relation homomorphisms between their arguments.
## Notation
* `→r`: `RelHom`
* `↪r`: `RelEmbedding`
* `≃r`: `RelIso`
-/
open Function
universe u v w
variable {α β γ δ : Type _} {r : α → α → Prop} {s : β → β → Prop}
{t : γ → γ → Prop} {u : δ → δ → Prop}
/-- A relation homomorphism with respect to a given pair of relations `r` and `s`
is a function `f : α → β` such that `r a b → s (f a) (f b)`. -/
structure RelHom {α β : Type _} (r : α → α → Prop) (s : β → β → Prop) where
/-- The underlying function of a `RelHom` -/
toFun : α → β
/-- A `RelHom` sends related elements to related elements -/
map_rel' : ∀ {a b}, r a b → s (toFun a) (toFun b)
#align rel_hom RelHom
/-- A relation homomorphism with respect to a given pair of relations `r` and `s`
is a function `f : α → β` such that `r a b → s (f a) (f b)`. -/
infixl:25 " →r " => RelHom
section
/-- `RelHomClass F r s` asserts that `F` is a type of functions such that all `f : F`
satisfy `r a b → s (f a) (f b)`.
The relations `r` and `s` are `outParam`s since figuring them out from a goal is a higher-order
matching problem that Lean usually can't do unaided.
-/
class RelHomClass (F : Type _) {α β : outParam <| Type _} (r : outParam <| α → α → Prop)
(s : outParam <| β → β → Prop) extends FunLike F α fun _ => β where
/-- A `RelHomClass` sends related elements to related elements -/
map_rel : ∀ (f : F) {a b}, r a b → s (f a) (f b)
#align rel_hom_class RelHomClass
export RelHomClass (map_rel)
end
namespace RelHomClass
variable {F : Type _}
protected theorem isIrrefl [RelHomClass F r s] (f : F) : ∀ [IsIrrefl β s], IsIrrefl α r
| ⟨H⟩ => ⟨fun _ h => H _ (map_rel f h)⟩
#align rel_hom_class.is_irrefl RelHomClass.isIrrefl
protected theorem isAsymm [RelHomClass F r s] (f : F) : ∀ [IsAsymm β s], IsAsymm α r
| ⟨H⟩ => ⟨fun _ _ h₁ h₂ => H _ _ (map_rel f h₁) (map_rel f h₂)⟩
#align rel_hom_class.is_asymm RelHomClass.isAsymm
protected theorem acc [RelHomClass F r s] (f : F) (a : α) : Acc s (f a) → Acc r a := by
generalize h : f a = b
intro ac
induction' ac with _ H IH generalizing a
subst h
exact ⟨_, fun a' h => IH (f a') (map_rel f h) _ rfl⟩
#align rel_hom_class.acc RelHomClass.acc
protected theorem wellFounded [RelHomClass F r s] (f : F) : ∀ _ : WellFounded s, WellFounded r
| ⟨H⟩ => ⟨fun _ => RelHomClass.acc f _ (H _)⟩
#align rel_hom_class.well_founded RelHomClass.wellFounded
end RelHomClass
namespace RelHom
instance : RelHomClass (r →r s) r s where
coe o := o.toFun
coe_injective' f g h := by
cases f
cases g
congr
map_rel := map_rel'
initialize_simps_projections RelHom (toFun → apply)
protected theorem map_rel (f : r →r s) {a b} : r a b → s (f a) (f b) :=
f.map_rel'
#align rel_hom.map_rel RelHom.map_rel
@[simp]
theorem coe_fn_toFun (f : r →r s) : f.toFun = (f : α → β) :=
rfl
#align rel_hom.coe_fn_to_fun RelHom.coe_fn_toFun
/-- The map `coe_fn : (r →r s) → (α → β)` is injective. -/
theorem coe_fn_injective : Injective fun (f : r →r s) => (f : α → β) :=
FunLike.coe_injective
#align rel_hom.coe_fn_injective RelHom.coe_fn_injective
@[ext]
theorem ext ⦃f g : r →r s⦄ (h : ∀ x, f x = g x) : f = g :=
FunLike.ext f g h
#align rel_hom.ext RelHom.ext
theorem ext_iff {f g : r →r s} : f = g ↔ ∀ x, f x = g x :=
FunLike.ext_iff
#align rel_hom.ext_iff RelHom.ext_iff
/-- Identity map is a relation homomorphism. -/
@[refl, simps]
protected def id (r : α → α → Prop) : r →r r :=
⟨fun x => x, fun x => x⟩
#align rel_hom.id RelHom.id
#align rel_hom.id_apply RelHom.id_apply
/-- Composition of two relation homomorphisms is a relation homomorphism. -/
@[simps]
protected def comp (g : s →r t) (f : r →r s) : r →r t :=
⟨fun x => g (f x), fun h => g.2 (f.2 h)⟩
#align rel_hom.comp RelHom.comp
#align rel_hom.comp_apply RelHom.comp_apply
/-- A relation homomorphism is also a relation homomorphism between dual relations. -/
protected def swap (f : r →r s) : swap r →r swap s :=
⟨f, f.map_rel⟩
#align rel_hom.swap RelHom.swap
/-- A function is a relation homomorphism from the preimage relation of `s` to `s`. -/
def preimage (f : α → β) (s : β → β → Prop) : f ⁻¹'o s →r s :=
⟨f, id⟩
#align rel_hom.preimage RelHom.preimage
end RelHom
/-- An increasing function is injective -/
theorem injective_of_increasing (r : α → α → Prop) (s : β → β → Prop) [IsTrichotomous α r]
[IsIrrefl β s] (f : α → β) (hf : ∀ {x y}, r x y → s (f x) (f y)) : Injective f := by
intro x y hxy
rcases trichotomous_of r x y with (h | h | h)
· have := hf h
rw [hxy] at this
exfalso
exact irrefl_of s (f y) this
· exact h
· have := hf h
rw [hxy] at this
exfalso
exact irrefl_of s (f y) this
#align injective_of_increasing injective_of_increasing
/-- An increasing function is injective -/
theorem RelHom.injective_of_increasing [IsTrichotomous α r] [IsIrrefl β s] (f : r →r s) :
Injective f :=
_root_.injective_of_increasing r s f f.map_rel
#align rel_hom.injective_of_increasing RelHom.injective_of_increasing
-- TODO: define a `RelIffClass` so we don't have to do all the `convert` trickery?
theorem Surjective.wellFounded_iff {f : α → β} (hf : Surjective f)
(o : ∀ {a b}, r a b ↔ s (f a) (f b)) :
WellFounded r ↔ WellFounded s :=
Iff.intro
(by
refine RelHomClass.wellFounded (RelHom.mk ?_ ?_ : s →r r)
· exact Classical.choose hf.hasRightInverse
intro a b h
apply o.2
convert h
iterate 2 apply Classical.choose_spec hf.hasRightInverse)
(RelHomClass.wellFounded (⟨f, o.1⟩ : r →r s))
#align surjective.well_founded_iff Surjective.wellFounded_iff
/-- A relation embedding with respect to a given pair of relations `r` and `s`
is an embedding `f : α ↪ β` such that `r a b ↔ s (f a) (f b)`. -/
structure RelEmbedding {α β : Type _} (r : α → α → Prop) (s : β → β → Prop) extends α ↪ β where
/-- Elements are related iff they are related after apply a `RelEmbedding` -/
map_rel_iff' : ∀ {a b}, s (toEmbedding a) (toEmbedding b) ↔ r a b
#align rel_embedding RelEmbedding
/-- A relation embedding with respect to a given pair of relations `r` and `s`
is an embedding `f : α ↪ β` such that `r a b ↔ s (f a) (f b)`. -/
infixl:25 " ↪r " => RelEmbedding
/-- The induced relation on a subtype is an embedding under the natural inclusion. -/
def Subtype.relEmbedding {X : Type _} (r : X → X → Prop) (p : X → Prop) :
(Subtype.val : Subtype p → X) ⁻¹'o r ↪r r :=
⟨Embedding.subtype p, Iff.rfl⟩
#align subtype.rel_embedding Subtype.relEmbedding
theorem preimage_equivalence {α β} (f : α → β) {s : β → β → Prop} (hs : Equivalence s) :
Equivalence (f ⁻¹'o s) :=
⟨fun _ => hs.1 _, fun h => hs.2 h, fun h₁ h₂ => hs.3 h₁ h₂⟩
#align preimage_equivalence preimage_equivalence
namespace RelEmbedding
/-- A relation embedding is also a relation homomorphism -/
def toRelHom (f : r ↪r s) : r →r s where
toFun := f.toEmbedding.toFun
map_rel' := (map_rel_iff' f).mpr
#align rel_embedding.to_rel_hom RelEmbedding.toRelHom
instance : Coe (r ↪r s) (r →r s) :=
⟨toRelHom⟩
-- see Note [function coercion]
instance : CoeFun (r ↪r s) fun _ => α → β :=
⟨fun o => o.toEmbedding⟩
-- TODO: define and instantiate a `RelEmbeddingClass` when `EmbeddingLike` is defined
instance : RelHomClass (r ↪r s) r s where
coe := fun x => x
coe_injective' f g h := by
rcases f with ⟨⟨⟩⟩
rcases g with ⟨⟨⟩⟩
congr
map_rel f a b := Iff.mpr (map_rel_iff' f)
/-- See Note [custom simps projection]. We specify this explicitly because we have a coercion not
given by the `FunLike` instance. Todo: remove that instance?
-/
def Simps.apply (h : r ↪r s) : α → β :=
h
initialize_simps_projections RelEmbedding (toFun → apply)
theorem injective (f : r ↪r s) : Injective f :=
f.inj'
#align rel_embedding.injective RelEmbedding.injective
theorem inj (f : r ↪r s) {a b} : f a = f b ↔ a = b :=
f.injective.eq_iff
#align rel_embedding.inj RelEmbedding.inj
theorem map_rel_iff (f : r ↪r s) {a b} : s (f a) (f b) ↔ r a b :=
f.map_rel_iff'
#align rel_embedding.map_rel_iff RelEmbedding.map_rel_iff
#noalign coe_fn_mk
#noalign coe_fn_to_embedding
/-- The map `coe_fn : (r ↪r s) → (α → β)` is injective. -/
theorem coe_fn_injective : Injective fun f : r ↪r s => (f : α → β) :=
FunLike.coe_injective
#align rel_embedding.coe_fn_injective RelEmbedding.coe_fn_injective
@[ext]
theorem ext ⦃f g : r ↪r s⦄ (h : ∀ x, f x = g x) : f = g :=
FunLike.ext _ _ h
#align rel_embedding.ext RelEmbedding.ext
theorem ext_iff {f g : r ↪r s} : f = g ↔ ∀ x, f x = g x :=
FunLike.ext_iff
#align rel_embedding.ext_iff RelEmbedding.ext_iff
/-- Identity map is a relation embedding. -/
@[refl, simps!]
protected def refl (r : α → α → Prop) : r ↪r r :=
⟨Embedding.refl _, Iff.rfl⟩
#align rel_embedding.refl RelEmbedding.refl
#align rel_embedding.refl_apply RelEmbedding.refl_apply
/-- Composition of two relation embeddings is a relation embedding. -/
protected def trans (f : r ↪r s) (g : s ↪r t) : r ↪r t :=
⟨f.1.trans g.1, by simp [f.map_rel_iff, g.map_rel_iff]⟩
#align rel_embedding.trans RelEmbedding.trans
instance (r : α → α → Prop) : Inhabited (r ↪r r) :=
⟨RelEmbedding.refl _⟩
theorem trans_apply (f : r ↪r s) (g : s ↪r t) (a : α) : (f.trans g) a = g (f a) :=
rfl
#align rel_embedding.trans_apply RelEmbedding.trans_apply
@[simp]
theorem coe_trans (f : r ↪r s) (g : s ↪r t) : (f.trans g) = g ∘ f :=
rfl
#align rel_embedding.coe_trans RelEmbedding.coe_trans
/-- A relation embedding is also a relation embedding between dual relations. -/
protected def swap (f : r ↪r s) : swap r ↪r swap s :=
⟨f.toEmbedding, f.map_rel_iff⟩
#align rel_embedding.swap RelEmbedding.swap
/-- If `f` is injective, then it is a relation embedding from the
preimage relation of `s` to `s`. -/
def preimage (f : α ↪ β) (s : β → β → Prop) : f ⁻¹'o s ↪r s :=
⟨f, Iff.rfl⟩
#align rel_embedding.preimage RelEmbedding.preimage
theorem eq_preimage (f : r ↪r s) : r = f ⁻¹'o s := by
ext (a b)
exact f.map_rel_iff.symm
#align rel_embedding.eq_preimage RelEmbedding.eq_preimage
protected theorem isIrrefl (f : r ↪r s) [IsIrrefl β s] : IsIrrefl α r :=
⟨fun a => mt f.map_rel_iff.2 (irrefl (f a))⟩
#align rel_embedding.is_irrefl RelEmbedding.isIrrefl
protected theorem isRefl (f : r ↪r s) [IsRefl β s] : IsRefl α r :=
⟨fun _ => f.map_rel_iff.1 <| refl _⟩
#align rel_embedding.is_refl RelEmbedding.isRefl
protected theorem isSymm (f : r ↪r s) [IsSymm β s] : IsSymm α r :=
⟨fun _ _ => imp_imp_imp f.map_rel_iff.2 f.map_rel_iff.1 symm⟩
#align rel_embedding.is_symm RelEmbedding.isSymm
protected theorem isAsymm (f : r ↪r s) [IsAsymm β s] : IsAsymm α r :=
⟨fun _ _ h₁ h₂ => asymm (f.map_rel_iff.2 h₁) (f.map_rel_iff.2 h₂)⟩
#align rel_embedding.is_asymm RelEmbedding.isAsymm
protected theorem isAntisymm : ∀ (_ : r ↪r s) [IsAntisymm β s], IsAntisymm α r
| ⟨f, o⟩, ⟨H⟩ => ⟨fun _ _ h₁ h₂ => f.inj' (H _ _ (o.2 h₁) (o.2 h₂))⟩
#align rel_embedding.is_antisymm RelEmbedding.isAntisymm
protected theorem isTrans : ∀ (_ : r ↪r s) [IsTrans β s], IsTrans α r
| ⟨_, o⟩, ⟨H⟩ => ⟨fun _ _ _ h₁ h₂ => o.1 (H _ _ _ (o.2 h₁) (o.2 h₂))⟩
#align rel_embedding.is_trans RelEmbedding.isTrans
protected theorem isTotal : ∀ (_ : r ↪r s) [IsTotal β s], IsTotal α r
| ⟨_, o⟩, ⟨H⟩ => ⟨fun _ _ => (or_congr o o).1 (H _ _)⟩
#align rel_embedding.is_total RelEmbedding.isTotal
protected theorem isPreorder : ∀ (_ : r ↪r s) [IsPreorder β s], IsPreorder α r
| f, _ => { f.isRefl, f.isTrans with }
#align rel_embedding.is_preorder RelEmbedding.isPreorder
protected theorem isPartialOrder : ∀ (_ : r ↪r s) [IsPartialOrder β s], IsPartialOrder α r
| f, _ => { f.isPreorder, f.isAntisymm with }
#align rel_embedding.is_partial_order RelEmbedding.isPartialOrder
protected theorem isLinearOrder : ∀ (_ : r ↪r s) [IsLinearOrder β s], IsLinearOrder α r
| f, _ => { f.isPartialOrder, f.isTotal with }
#align rel_embedding.is_linear_order RelEmbedding.isLinearOrder
protected theorem isStrictOrder : ∀ (_ : r ↪r s) [IsStrictOrder β s], IsStrictOrder α r
| f, _ => { f.isIrrefl, f.isTrans with }
#align rel_embedding.is_strict_order RelEmbedding.isStrictOrder
protected theorem isTrichotomous : ∀ (_ : r ↪r s) [IsTrichotomous β s], IsTrichotomous α r
| ⟨f, o⟩, ⟨H⟩ => ⟨fun _ _ => (or_congr o (or_congr f.inj'.eq_iff o)).1 (H _ _)⟩
#align rel_embedding.is_trichotomous RelEmbedding.isTrichotomous
protected theorem isStrictTotalOrder : ∀ (_ : r ↪r s) [IsStrictTotalOrder β s],
IsStrictTotalOrder α r
| f, _ => { f.isTrichotomous, f.isStrictOrder with }
#align rel_embedding.is_strict_total_order RelEmbedding.isStrictTotalOrder
protected theorem acc (f : r ↪r s) (a : α) : Acc s (f a) → Acc r a := by
generalize h : f a = b
intro ac
induction' ac with _ H IH generalizing a
subst h
exact ⟨_, fun a' h => IH (f a') (f.map_rel_iff.2 h) _ rfl⟩
#align rel_embedding.acc RelEmbedding.acc
protected theorem wellFounded : ∀ (_ : r ↪r s) (_ : WellFounded s), WellFounded r
| f, ⟨H⟩ => ⟨fun _ => f.acc _ (H _)⟩
#align rel_embedding.well_founded RelEmbedding.wellFounded
protected theorem isWellOrder : ∀ (_ : r ↪r s) [IsWellOrder β s], IsWellOrder α r
| f, H => { f.isStrictTotalOrder with wf := f.wellFounded H.wf }
#align rel_embedding.is_well_order RelEmbedding.isWellOrder
/-- `Quotient.out` as a relation embedding between the lift of a relation and the relation. -/
@[simps!]
noncomputable def _root_.Quotient.outRelEmbedding [s : Setoid α] {r : α → α → Prop}
(H : ∀ (a₁ b₁ a₂ b₂ : α), a₁ ≈ a₂ → b₁ ≈ b₂ → r a₁ b₁ = r a₂ b₂) : Quotient.lift₂ r H ↪r r :=
⟨Embedding.quotientOut α, by
refine' @fun x y => Quotient.inductionOn₂ x y fun a b => _
apply iff_iff_eq.2 (H _ _ _ _ _ _) <;> apply Quotient.mk_out⟩
#align quotient.out_rel_embedding Quotient.outRelEmbedding
#align quotient.out_rel_embedding_apply Quotient.outRelEmbedding_apply
/-- A relation is well founded iff its lift to a quotient is. -/
@[simp]
theorem _root_.wellFounded_lift₂_iff [s : Setoid α] {r : α → α → Prop}
{H : ∀ (a₁ b₁ a₂ b₂ : α), a₁ ≈ a₂ → b₁ ≈ b₂ → r a₁ b₁ = r a₂ b₂} :
WellFounded (Quotient.lift₂ r H) ↔ WellFounded r :=
⟨fun hr => by
suffices ∀ {x : Quotient s} {a : α}, ⟦a⟧ = x → Acc r a by exact ⟨fun a => this rfl⟩
· refine' @fun x => @WellFounded.induction _ _ hr
(fun y => ∀ (a : α), Quotient.mk s a = y → Acc r a) x _
rintro x IH a rfl
exact ⟨_, @fun b hb => IH ⟦b⟧ hb _ rfl⟩
,
(Quotient.outRelEmbedding H).wellFounded⟩
#align well_founded_lift₂_iff wellFounded_lift₂_iff
alias wellFounded_lift₂_iff ↔ _root_.WellFounded.of_quotient_lift₂ _root_.WellFounded.quotient_lift₂
/-- To define an relation embedding from an antisymmetric relation `r` to a reflexive relation `s`
it suffices to give a function together with a proof that it satisfies `s (f a) (f b) ↔ r a b`.
-/
def ofMapRelIff (f : α → β) [IsAntisymm α r] [IsRefl β s] (hf : ∀ a b, s (f a) (f b) ↔ r a b) :
r ↪r s where
toFun := f
inj' _ _ h := antisymm ((hf _ _).1 (h ▸ refl _)) ((hf _ _).1 (h ▸ refl _))
map_rel_iff' := hf _ _
#align rel_embedding.of_map_rel_iff RelEmbedding.ofMapRelIff
@[simp]
theorem ofMapRelIff_coe (f : α → β) [IsAntisymm α r] [IsRefl β s]
(hf : ∀ a b, s (f a) (f b) ↔ r a b) :
(ofMapRelIff f hf : r ↪r s) = f :=
rfl
#align rel_embedding.of_map_rel_iff_coe RelEmbedding.ofMapRelIff_coe
/-- It suffices to prove `f` is monotone between strict relations
to show it is a relation embedding. -/
def ofMonotone [IsTrichotomous α r] [IsAsymm β s] (f : α → β) (H : ∀ a b, r a b → s (f a) (f b)) :
r ↪r s := by
haveI := @IsAsymm.isIrrefl β s _
refine' ⟨⟨f, fun a b e => _⟩, @fun a b => ⟨fun h => _, H _ _⟩⟩
· refine' ((@trichotomous _ r _ a b).resolve_left _).resolve_right _ <;>
exact fun h => @irrefl _ s _ _ (by simpa [e] using H _ _ h)
· refine' (@trichotomous _ r _ a b).resolve_right (Or.rec (fun e => _) fun h' => _)
· subst e
exact irrefl _ h
· exact asymm (H _ _ h') h
#align rel_embedding.of_monotone RelEmbedding.ofMonotone
@[simp]
theorem ofMonotone_coe [IsTrichotomous α r] [IsAsymm β s] (f : α → β) (H) :
(@ofMonotone _ _ r s _ _ f H : α → β) = f :=
rfl
#align rel_embedding.of_monotone_coe RelEmbedding.ofMonotone_coe
/-- A relation embedding from an empty type. -/
def ofIsEmpty (r : α → α → Prop) (s : β → β → Prop) [IsEmpty α] : r ↪r s :=
⟨Embedding.ofIsEmpty, @fun a => isEmptyElim a⟩
#align rel_embedding.of_is_empty RelEmbedding.ofIsEmpty
/-- `Sum.inl` as a relation embedding into `Sum.LiftRel r s`. -/
@[simps]
def sumLiftRelInl (r : α → α → Prop) (s : β → β → Prop) : r ↪r Sum.LiftRel r s where
toFun := Sum.inl
inj' := Sum.inl_injective
map_rel_iff' := Sum.liftRel_inl_inl
#align rel_embedding.sum_lift_rel_inl RelEmbedding.sumLiftRelInl
#align rel_embedding.sum_lift_rel_inl_apply RelEmbedding.sumLiftRelInl_apply
/-- `Sum.inr` as a relation embedding into `Sum.LiftRel r s`. -/
@[simps]
def sumLiftRelInr (r : α → α → Prop) (s : β → β → Prop) : s ↪r Sum.LiftRel r s where
toFun := Sum.inr
inj' := Sum.inr_injective
map_rel_iff' := Sum.liftRel_inr_inr
#align rel_embedding.sum_lift_rel_inr RelEmbedding.sumLiftRelInr
#align rel_embedding.sum_lift_rel_inr_apply RelEmbedding.sumLiftRelInr_apply
/-- `Sum.map` as a relation embedding between `Sum.LiftRel` relations. -/
@[simps]
def sumLiftRelMap (f : r ↪r s) (g : t ↪r u) : Sum.LiftRel r t ↪r Sum.LiftRel s u where
toFun := Sum.map f g
inj' := f.injective.sum_map g.injective
map_rel_iff' := by rintro (a | b) (c | d) <;> simp [f.map_rel_iff, g.map_rel_iff]
#align rel_embedding.sum_lift_rel_map RelEmbedding.sumLiftRelMap
#align rel_embedding.sum_lift_rel_map_apply RelEmbedding.sumLiftRelMap_apply
/-- `Sum.inl` as a relation embedding into `Sum.Lex r s`. -/
@[simps]
def sumLexInl (r : α → α → Prop) (s : β → β → Prop) : r ↪r Sum.Lex r s where
toFun := Sum.inl
inj' := Sum.inl_injective
map_rel_iff' := Sum.lex_inl_inl
#align rel_embedding.sum_lex_inl RelEmbedding.sumLexInl
#align rel_embedding.sum_lex_inl_apply RelEmbedding.sumLexInl_apply
/-- `Sum.inr` as a relation embedding into `Sum.Lex r s`. -/
@[simps]
def sumLexInr (r : α → α → Prop) (s : β → β → Prop) : s ↪r Sum.Lex r s where
toFun := Sum.inr
inj' := Sum.inr_injective
map_rel_iff' := Sum.lex_inr_inr
#align rel_embedding.sum_lex_inr RelEmbedding.sumLexInr
#align rel_embedding.sum_lex_inr_apply RelEmbedding.sumLexInr_apply
/-- `Sum.map` as a relation embedding between `Sum.Lex` relations. -/
@[simps]
def sumLexMap (f : r ↪r s) (g : t ↪r u) : Sum.Lex r t ↪r Sum.Lex s u where
toFun := Sum.map f g
inj' := f.injective.sum_map g.injective
map_rel_iff' := by rintro (a | b) (c | d) <;> simp [f.map_rel_iff, g.map_rel_iff]
#align rel_embedding.sum_lex_map RelEmbedding.sumLexMap
#align rel_embedding.sum_lex_map_apply RelEmbedding.sumLexMap_apply
/-- `λ b, Prod.mk a b` as a relation embedding. -/
@[simps]
def prodLexMkLeft (s : β → β → Prop) {a : α} (h : ¬r a a) : s ↪r Prod.Lex r s where
toFun := Prod.mk a
inj' := Prod.mk.inj_left a
map_rel_iff' := by simp [Prod.lex_def, h]
#align rel_embedding.prod_lex_mk_left RelEmbedding.prodLexMkLeft
#align rel_embedding.prod_lex_mk_left_apply RelEmbedding.prodLexMkLeft_apply
/-- `λ a, Prod.mk a b` as a relation embedding. -/
@[simps]
def prodLexMkRight (r : α → α → Prop) {b : β} (h : ¬s b b) : r ↪r Prod.Lex r s where
toFun a := (a, b)
inj' := Prod.mk.inj_right b
map_rel_iff' := by simp [Prod.lex_def, h]
#align rel_embedding.prod_lex_mk_right RelEmbedding.prodLexMkRight
#align rel_embedding.prod_lex_mk_right_apply RelEmbedding.prodLexMkRight_apply
/-- `Prod.map` as a relation embedding. -/
@[simps]
def prodLexMap (f : r ↪r s) (g : t ↪r u) : Prod.Lex r t ↪r Prod.Lex s u where
toFun := Prod.map f g
inj' := f.injective.Prod_map g.injective
map_rel_iff' := by simp [Prod.lex_def, f.map_rel_iff, g.map_rel_iff]
#align rel_embedding.prod_lex_map RelEmbedding.prodLexMap
#align rel_embedding.prod_lex_map_apply RelEmbedding.prodLexMap_apply
end RelEmbedding
/-- A relation isomorphism is an equivalence that is also a relation embedding. -/
structure RelIso {α β : Type _} (r : α → α → Prop) (s : β → β → Prop) extends α ≃ β where
/-- Elements are related iff they are related after apply a `RelIso` -/
map_rel_iff' : ∀ {a b}, s (toEquiv a) (toEquiv b) ↔ r a b
#align rel_iso RelIso
/-- A relation isomorphism is an equivalence that is also a relation embedding. -/
infixl:25 " ≃r " => RelIso
namespace RelIso
/-- Convert an `RelIso` to a `RelEmbedding`. This function is also available as a coercion
but often it is easier to write `f.toRelEmbedding` than to write explicitly `r` and `s`
in the target type. -/
def toRelEmbedding (f : r ≃r s) : r ↪r s :=
⟨f.toEquiv.toEmbedding, f.map_rel_iff'⟩
#align rel_iso.to_rel_embedding RelIso.toRelEmbedding
theorem toEquiv_injective : Injective (toEquiv : r ≃r s → α ≃ β)
| ⟨e₁, o₁⟩, ⟨e₂, _⟩, h => by
congr
#align rel_iso.to_equiv_injective RelIso.toEquiv_injective
instance : CoeOut (r ≃r s) (r ↪r s) :=
⟨toRelEmbedding⟩
-- see Note [function coercion]
instance : CoeFun (r ≃r s) fun _ => α → β :=
⟨fun f => f⟩
-- TODO: define and instantiate a `RelIsoClass` when `EquivLike` is defined
instance : RelHomClass (r ≃r s) r s where
coe := fun x => x
coe_injective' := Equiv.coe_fn_injective.comp toEquiv_injective
map_rel f _ _ := Iff.mpr (map_rel_iff' f)
theorem map_rel_iff (f : r ≃r s) {a b} : s (f a) (f b) ↔ r a b :=
f.map_rel_iff'
#align rel_iso.map_rel_iff RelIso.map_rel_iff
@[simp]
theorem coe_fn_mk (f : α ≃ β) (o : ∀ ⦃a b⦄, s (f a) (f b) ↔ r a b) :
(RelIso.mk f @o : α → β) = f :=
rfl
#align rel_iso.coe_fn_mk RelIso.coe_fn_mk
@[simp]
theorem coe_fn_toEquiv (f : r ≃r s) : (f.toEquiv : α → β) = f :=
rfl
#align rel_iso.coe_fn_to_equiv RelIso.coe_fn_toEquiv
/-- The map `coe_fn : (r ≃r s) → (α → β)` is injective. Lean fails to parse
`function.injective (λ e : r ≃r s, (e : α → β))`, so we use a trick to say the same. -/
theorem coe_fn_injective : Injective fun f : r ≃r s => (f : α → β) :=
FunLike.coe_injective
#align rel_iso.coe_fn_injective RelIso.coe_fn_injective
@[ext]
theorem ext ⦃f g : r ≃r s⦄ (h : ∀ x, f x = g x) : f = g :=
FunLike.ext f g h
#align rel_iso.ext RelIso.ext
theorem ext_iff {f g : r ≃r s} : f = g ↔ ∀ x, f x = g x :=
FunLike.ext_iff
#align rel_iso.ext_iff RelIso.ext_iff
/-- Inverse map of a relation isomorphism is a relation isomorphism. -/
protected def symm (f : r ≃r s) : s ≃r r :=
⟨f.toEquiv.symm, @fun a b => by erw [← f.map_rel_iff, f.1.apply_symm_apply, f.1.apply_symm_apply]⟩
#align rel_iso.symm RelIso.symm
/-- See Note [custom simps projection]. We need to specify this projection explicitly in this case,
because `RelIso` defines custom coercions other than the ones given by `FunLike`. -/
def Simps.apply (h : r ≃r s) : α → β :=
h
#align rel_iso.simps.apply RelIso.Simps.apply
/-- See Note [custom simps projection]. -/
def Simps.symm_apply (h : r ≃r s) : β → α :=
h.symm
#align rel_iso.simps.symm_apply RelIso.Simps.symm_apply
initialize_simps_projections RelIso (toFun → apply, invFun → symm_apply)
/-- Identity map is a relation isomorphism. -/
@[refl, simps! apply]
protected def refl (r : α → α → Prop) : r ≃r r :=
⟨Equiv.refl _, Iff.rfl⟩
#align rel_iso.refl RelIso.refl
#align rel_iso.refl_apply RelIso.refl_apply
/-- Composition of two relation isomorphisms is a relation isomorphism. -/
@[simps! apply]
protected def trans (f₁ : r ≃r s) (f₂ : s ≃r t) : r ≃r t :=
⟨f₁.toEquiv.trans f₂.toEquiv, f₂.map_rel_iff.trans f₁.map_rel_iff⟩
#align rel_iso.trans RelIso.trans
#align rel_iso.trans_apply RelIso.trans_apply
instance (r : α → α → Prop) : Inhabited (r ≃r r) :=
⟨RelIso.refl _⟩
@[simp]
theorem default_def (r : α → α → Prop) : default = RelIso.refl r :=
rfl
#align rel_iso.default_def RelIso.default_def
/-- A relation isomorphism between equal relations on equal types. -/
@[simps! toEquiv apply]
protected def cast {α β : Type u} {r : α → α → Prop} {s : β → β → Prop} (h₁ : α = β)
(h₂ : HEq r s) : r ≃r s :=
⟨Equiv.cast h₁, @fun a b => by
subst h₁
rw [eq_of_heq h₂]
rfl⟩
#align rel_iso.cast RelIso.cast
#align rel_iso.cast_apply RelIso.cast_apply
#align rel_iso.cast_to_equiv RelIso.cast_toEquiv
@[simp]
protected theorem cast_symm {α β : Type u} {r : α → α → Prop} {s : β → β → Prop} (h₁ : α = β)
(h₂ : HEq r s) :
(RelIso.cast h₁ h₂).symm = RelIso.cast h₁.symm h₂.symm :=
rfl
#align rel_iso.cast_symm RelIso.cast_symm
@[simp]
protected theorem cast_refl {α : Type u} {r : α → α → Prop} (h₁ : α = α := rfl)
(h₂ : HEq r r := HEq.rfl) :
RelIso.cast h₁ h₂ = RelIso.refl r :=
rfl
#align rel_iso.cast_refl RelIso.cast_refl
@[simp]
protected theorem cast_trans {α β γ : Type u} {r : α → α → Prop} {s : β → β → Prop}
{t : γ → γ → Prop} (h₁ : α = β)
(h₁' : β = γ) (h₂ : HEq r s) (h₂' : HEq s t) :
(RelIso.cast h₁ h₂).trans (RelIso.cast h₁' h₂') = RelIso.cast (h₁.trans h₁') (h₂.trans h₂') :=
ext fun x => by subst h₁; rfl
#align rel_iso.cast_trans RelIso.cast_trans
/-- a relation isomorphism is also a relation isomorphism between dual relations. -/
protected def swap (f : r ≃r s) : swap r ≃r swap s :=
⟨f.toEquiv, f.map_rel_iff⟩
#align rel_iso.swap RelIso.swap
@[simp]
theorem coe_fn_symm_mk (f o) : ((@RelIso.mk _ _ r s f @o).symm : β → α) = f.symm :=
rfl
#align rel_iso.coe_fn_symm_mk RelIso.coe_fn_symm_mk
@[simp]
theorem apply_symm_apply (e : r ≃r s) (x : β) : e (e.symm x) = x :=
e.toEquiv.apply_symm_apply x
#align rel_iso.apply_symm_apply RelIso.apply_symm_apply
@[simp]
theorem symm_apply_apply (e : r ≃r s) (x : α) : e.symm (e x) = x :=
e.toEquiv.symm_apply_apply x
#align rel_iso.symm_apply_apply RelIso.symm_apply_apply
theorem rel_symm_apply (e : r ≃r s) {x y} : r x (e.symm y) ↔ s (e x) y :=
by rw [← e.map_rel_iff, e.apply_symm_apply]
#align rel_iso.rel_symm_apply RelIso.rel_symm_apply
theorem symm_apply_rel (e : r ≃r s) {x y} : r (e.symm x) y ↔ s x (e y) :=
by rw [← e.map_rel_iff, e.apply_symm_apply]
#align rel_iso.symm_apply_rel RelIso.symm_apply_rel
protected theorem bijective (e : r ≃r s) : Bijective e :=
e.toEquiv.bijective
#align rel_iso.bijective RelIso.bijective
protected theorem injective (e : r ≃r s) : Injective e :=
e.toEquiv.injective
#align rel_iso.injective RelIso.injective
protected theorem surjective (e : r ≃r s) : Surjective e :=
e.toEquiv.surjective
#align rel_iso.surjective RelIso.surjective
theorem eq_iff_eq (f : r ≃r s) {a b} : f a = f b ↔ a = b :=
f.injective.eq_iff
#align rel_iso.eq_iff_eq RelIso.eq_iff_eq
/-- Any equivalence lifts to a relation isomorphism between `s` and its preimage. -/
protected def preimage (f : α ≃ β) (s : β → β → Prop) : f ⁻¹'o s ≃r s :=
⟨f, Iff.rfl⟩
#align rel_iso.preimage RelIso.preimage
instance IsWellOrder.preimage {α : Type u} (r : α → α → Prop) [IsWellOrder α r] (f : β ≃ α) :
IsWellOrder β (f ⁻¹'o r) :=
@RelEmbedding.isWellOrder _ _ (f ⁻¹'o r) r (RelIso.preimage f r) _
#align rel_iso.is_well_order.preimage RelIso.IsWellOrder.preimage
instance IsWellOrder.ulift {α : Type u} (r : α → α → Prop) [IsWellOrder α r] :
IsWellOrder (ULift α) (ULift.down ⁻¹'o r) :=
IsWellOrder.preimage r Equiv.ulift
#align rel_iso.is_well_order.ulift RelIso.IsWellOrder.ulift
/-- A surjective relation embedding is a relation isomorphism. -/
@[simps! apply]
noncomputable def ofSurjective (f : r ↪r s) (H : Surjective f) : r ≃r s :=
⟨Equiv.ofBijective f ⟨f.injective, H⟩, f.map_rel_iff⟩
#align rel_iso.of_surjective RelIso.ofSurjective
#align rel_iso.of_surjective_apply RelIso.ofSurjective_apply
/-- Given relation isomorphisms `r₁ ≃r s₁` and `r₂ ≃r s₂`, construct a relation isomorphism for the
lexicographic orders on the sum.
-/
def sumLexCongr {α₁ α₂ β₁ β₂ r₁ r₂ s₁ s₂} (e₁ : @RelIso α₁ β₁ r₁ s₁) (e₂ : @RelIso α₂ β₂ r₂ s₂) :
Sum.Lex r₁ r₂ ≃r Sum.Lex s₁ s₂ :=
⟨Equiv.sumCongr e₁.toEquiv e₂.toEquiv, @fun a b => by
cases' e₁ with f hf ; cases' e₂ with g hg ; cases a <;> cases b <;> simp [hf, hg]⟩
#align rel_iso.sum_lex_congr RelIso.sumLexCongr
/-- Given relation isomorphisms `r₁ ≃r s₁` and `r₂ ≃r s₂`, construct a relation isomorphism for the
lexicographic orders on the product.
-/
def prodLexCongr {α₁ α₂ β₁ β₂ r₁ r₂ s₁ s₂} (e₁ : @RelIso α₁ β₁ r₁ s₁) (e₂ : @RelIso α₂ β₂ r₂ s₂) :
Prod.Lex r₁ r₂ ≃r Prod.Lex s₁ s₂ :=
⟨Equiv.prodCongr e₁.toEquiv e₂.toEquiv, by simp [Prod.lex_def, e₁.map_rel_iff, e₂.map_rel_iff]⟩
#align rel_iso.prod_lex_congr RelIso.prodLexCongr
/-- Two relations on empty types are isomorphic. -/
def relIsoOfIsEmpty (r : α → α → Prop) (s : β → β → Prop) [IsEmpty α] [IsEmpty β] : r ≃r s :=
⟨Equiv.equivOfIsEmpty α β, @fun a => isEmptyElim a⟩
#align rel_iso.rel_iso_of_is_empty RelIso.relIsoOfIsEmpty
/-- Two irreflexive relations on a unique type are isomorphic. -/
def relIsoOfUniqueOfIrrefl (r : α → α → Prop) (s : β → β → Prop) [IsIrrefl α r]
[IsIrrefl β s] [Unique α] [Unique β] : r ≃r s :=
⟨Equiv.equivOfUnique α β, iff_of_false (not_rel_of_subsingleton s _ _)
(not_rel_of_subsingleton r _ _) ⟩
#align rel_iso.rel_iso_of_unique_of_irrefl RelIso.relIsoOfUniqueOfIrrefl
/-- Two reflexive relations on a unique type are isomorphic. -/
def relIsoOfUniqueOfRefl (r : α → α → Prop) (s : β → β → Prop) [IsRefl α r] [IsRefl β s]
[Unique α] [Unique β] : r ≃r s :=
⟨Equiv.equivOfUnique α β, iff_of_true (rel_of_subsingleton s _ _) (rel_of_subsingleton r _ _)⟩
#align rel_iso.rel_iso_of_unique_of_refl RelIso.relIsoOfUniqueOfRefl
end RelIso
|
Formal statement is: lemma Bfun_def: "Bfun f F \<longleftrightarrow> (\<exists>K>0. eventually (\<lambda>x. norm (f x) \<le> K) F)" Informal statement is: A function $f$ is bounded on a filter $F$ if and only if there exists a constant $K > 0$ such that $|f(x)| \leq K$ for all $x$ in the filter $F$.
|
r=358.71
https://sandbox.dams.library.ucdavis.edu/fcrepo/rest/collection/sherry-lehmann/catalogs/d7xk57/media/images/d7xk57-010/svc:tesseract/full/full/358.71/default.jpg Accept:application/hocr+xml
|
[STATEMENT]
lemma iso_runit:
assumes "S.ide f"
shows "S.iso \<r>[f]"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. S.iso \<r>[f]
[PROOF STEP]
using assms characteristic_iso(4) runit_char R.reflects_iso
[PROOF STATE]
proof (prove)
using this:
S.ide f
S.ide ?f \<Longrightarrow> S.iso ((?f \<star> \<iota>) \<cdot>\<^sub>S \<a>[?f, a, a])
S.ide ?f \<Longrightarrow> \<guillemotleft>\<r>[?f] : R ?f \<Rightarrow>\<^sub>S ?f\<guillemotright>
S.ide ?f \<Longrightarrow> R \<r>[?f] = (?f \<star> \<iota>) \<cdot>\<^sub>S \<a>[?f, a, a]
S.ide ?f \<Longrightarrow> \<exists>!\<mu>. \<guillemotleft>\<mu> : R ?f \<Rightarrow>\<^sub>S ?f\<guillemotright> \<and> R \<mu> = (?f \<star> \<iota>) \<cdot>\<^sub>S \<a>[?f, a, a]
\<lbrakk>\<guillemotleft>?f : ?a' \<Rightarrow>\<^sub>S ?a\<guillemotright>; S.iso (R ?f)\<rbrakk> \<Longrightarrow> S.iso ?f
goal (1 subgoal):
1. S.iso \<r>[f]
[PROOF STEP]
by metis
|
function [h,filtertype] = gsp_jtv_filter_array(G,g,filtertype)
%GSP_JTV_FILTER_ARRAY Convert ts/js filters to -array filters
% Usage: [h,filtertype] = gsp_jtv_filter_array(G,g, filtertype)
%
% Input parameters:
% G : Graph
% g : Cell array of time-vertex filters
% filtertype : Filter domain (ts,js)
% Output parameters:
% h : Cell array of graph filterbank
% filtertype : Filter domain (ts-array,js-array)
%
% Convert ts/js filters to -array filters
%
% Author : Francesco Grassi, Nathanael Perraudin
% Date : September 2016
if ~iscell(g)
g = {g};
end
if ~gsp_check_filtertype(filtertype,{'ts','js'})
error('Invalid filtertype.');
end
T = G.jtv.T;
Nf = numel(g);
switch filtertype
case 'ts'
v = gsp_jtv_ta(G);
case 'js'
v = gsp_jtv_fa(G);
end
h = cell(Nf,T);
for n=1:Nf
for ii = 1:T
h{n,ii} = @(x) g{n}(x,v(ii));
end
end
filtertype = [filtertype '-array'];
end
|
module Linear.MultiSolver
--To make sure that all imports work, load in idris as
-- idris Linear.MultiSolver.idr -p contrib
import ZZ
import Data.Matrix.Numeric
import Data.Fin
import BaseN
import Rationals
%access public export
{-
Representing a system of linear equations in matrix form as AX = B,
the solution for X is X = A^(-1)B
Unique solutions exist if |A| != 0.
If |A| == 0, the system can be either inconsistent (no sol.),
or dependent (infinite sol.)
To Be Done:
- existence of solutions (depends on determinant)
- multiplication of matrices (Num interface defined)
- proof that solutions are correct
- etc.
-}
--Operations for (ZZ,ZZ) are defined, so that we can develop proofs
total
plusZZ : ZZPair -> ZZPair -> ZZPair
plusZZ x y = ((fst x)*(snd y) + (snd x)*(fst y), (snd x)*(snd y))
total
multZZ : ZZPair -> ZZPair -> ZZPair
multZZ x y = ((fst x)*(fst y), (snd x)*(snd y))
total
fromIntQ : Integer -> ZZPair
fromIntQ n = if n < 0
then (NegS $ fromInteger ((-n) - 1), Pos 1)
else (Pos $ fromInteger n, Pos 1)
--This allows arithmetic operations on ZZPair
implementation Num ZZPair where
(+) = plusZZ
(*) = multZZ
fromInteger = fromIntQ
mutual
implementation Neg ZZPair where
negate (Pos Z, x) = (Pos Z, x)
negate (Pos (S n), x) = (NegS n, x)
negate (NegS n, x) = (Pos (S n), x)
(-) = subZZ
subZZ : ZZPair -> ZZPair -> ZZPair
subZZ x y = plusZZ x (negate y)
--This can be used to check equality
(==) : ZZPair -> ZZPair -> Bool
(==) (a,b) (c,d) = (a*d) == (b*c)
--Minor for a term of a 1x1 Matrix (Not required, can be removed later)
total
minor1 : Fin 1 -> Fin 1 -> Matrix 1 1 ZZPair -> ZZPair
minor1 x y [[k]] = k
--Minor for a term of a 2x2 Matrix
total
minor2 : Fin 2 -> Fin 2 -> Matrix 2 2 ZZPair -> ZZPair
minor2 x y mat = indices 0 0 (subMatrix x y mat)
--Minor for a general matrix term (Indices are elements of Fin <size>)
minor : Fin (S n) -> Fin (S n) ->
Matrix (S n) (S n) ZZPair -> ZZPair
minor {n} x y mat = case n of
Z => minor1 x y mat
(S Z) => minor2 x y mat
(S (S k)) => simplifyRational (det (subMatrix x y mat))
--Cofactor terms for a matrix (defined using the minor)
cofactor : Fin (S n) -> Fin (S n) ->
Matrix (S n) (S n) ZZPair -> ZZPair
cofactor x y mat = case (modNat (finToNat x + finToNat y) 2) of
Z => minor x y mat
(S k) => (NegS 0, Pos 1) * (minor x y mat)
--To make calc simpler, I have defined the cofactor/determinant term, as
--this will be required for defining the inverse of a matrix
cofByDet : Fin (S n) -> Fin (S n) ->
Matrix (S n) (S n) ZZPair -> ZZPair
cofByDet {n} x y mat = case n of
Z => (snd (cofactor 0 0 mat), fst (cofactor 0 0 mat))
(S k) => simplifyRational
((cofactor x y mat) * (snd (det mat), fst (det mat)))
--Auxillary functions for defining an empty matrix, which will be updated
--with values of the inverse
--Given n, give a vector of length n, with each element (0,1)
total
empRow : (n : Nat) -> Vect n ZZPair
empRow Z = []
empRow (S k) = [(Pos Z, Pos 1)] ++ (empRow k)
--Given m,n, give an empty mxn matrix with (0,1) filled for every term.
--This is the null matrix (in rationals, we defined 0 as (0,1))
total
empMat : (m : Nat) -> (n : Nat) -> Vect m (Vect n ZZPair)
empMat Z n = []
empMat (S k) n = [(empRow n)] ++ (empMat k n)
--Defining the cofactor matrix requires updating the null matrix
--with values of the cofactor.
--This requires inducting twice on the row and column, hence has
--been broken down into two separate functions.
--Given the reqRow, gives the row of cofactors for the original matrix
--for that index.
--iter is a variable used to induct on, and does not serve any
--real purpose
--"replaceAt index elem Vect" replaces an element of Vect at index by elem
--embn is from BaseN, and embeds an element of Fin n in Fin (S n)
cofRow : (size : Nat) -> (reqRow : Fin size) -> Matrix size size ZZPair ->
(iter : Fin size) -> Vect size ZZPair
cofRow Z _ _ FZ impossible
cofRow Z _ _ (FS _) impossible
cofRow (S k) reqRow mat FZ =
replaceAt
0
(cofByDet reqRow 0 mat)
(empRow (S k))
cofRow (S k) reqRow mat (FS y) =
replaceAt
(FS y)
(cofByDet reqRow (FS y) mat)
(cofRow (S k) reqRow mat (embn k y))
--Now, we can construct the cofactor matrix from the formed cofactor rows.
--tofinNat is from BaseN, and converts an element of Nat to Fin.
cofMat : (size : Nat) -> Matrix size size ZZPair ->
(iter : Fin size) -> Matrix size size ZZPair
cofMat Z _ FZ impossible
cofMat Z _ (FS _) impossible
cofMat (S k) mat FZ =
replaceAt
0
(cofRow (S k) 0 mat (tofinNat (k) (S k)))
(empMat (S k) (S k))
cofMat (S k) mat (FS y) =
replaceAt
(FS y)
(cofRow (S k) (FS y) mat (tofinNat (k) (S k)))
(cofMat (S k) mat (embn k y))
--Inverse of a matrix is the transpose of the cofactor matrix
invMat : Matrix n n ZZPair -> Matrix n n ZZPair
invMat {n} mat = case n of
Z => []
(S k) => transpose (cofMat (S k) mat (tofinNat (k) (S k)))
{-
Solving a system of n linear equations:
a11*x1 + a12*x2 + ... + a1n*xn = b1
.
.
an1*x1 + an2*x2 + ... + ann*xn = bn
-}
--Solves a system ax = b.
--The operation <> is matrix multiplication, defined in Matrix.Numeric
solve : (n : Nat) -> (a : Matrix n n ZZPair) -> (b : Matrix n 1 ZZPair) ->
Matrix n 1 ZZPair
solve n a b = (invMat a) <> b
|
-- ---------------------------------------------------------------------
-- Ejercicio. Realizar las siguientes acciones:
-- 1. Importar la teoría data.set.lattice
-- 2. Importar la teoría data.nat.prime
-- 3. Abrir los espacios de nombre set y nat.
-- ----------------------------------------------------------------------
import data.set.lattice -- 1
import data.nat.prime -- 2
open set nat -- 3
-- ---------------------------------------------------------------------
-- Ejercicio. Definir el conjunto de los números primos.
-- ----------------------------------------------------------------------
def primes : set ℕ := {x | prime x}
-- ---------------------------------------------------------------------
-- Ejercicio. Demostrar que
-- (⋃ p ∈ primes, {x | p^2 ∣ x}) = {x | ∃ p ∈ primes, p^2 ∣ x} :=
-- ----------------------------------------------------------------------
-- 1ª demostración
-- ===============
example : (⋃ p ∈ primes, {x | p^2 ∣ x}) = {x | ∃ p ∈ primes, p^2 ∣ x} :=
begin
ext,
rw mem_bUnion_iff,
refl,
end
-- Prueba
-- ======
/-
⊢ (⋃ (p : ℕ) (H : p ∈ primes), {x : ℕ | p ^ 2 ∣ x}) =
{x : ℕ | ∃ (p : ℕ) (H : p ∈ primes), p ^ 2 ∣ x}
>> ext,
x : ℕ
⊢ (x ∈ ⋃ (p : ℕ) (H : p ∈ primes), {x : ℕ | p ^ 2 ∣ x}) ↔
x ∈ {x : ℕ | ∃ (p : ℕ) (H : p ∈ primes), p ^ 2 ∣ x}
>> rw mem_bUnion_iff,
⊢ (∃ (x_1 : ℕ) (H : x_1 ∈ primes), x ∈ {x : ℕ | x_1 ^ 2 ∣ x}) ↔
x ∈ {x : ℕ | ∃ (p : ℕ) (H : p ∈ primes), p ^ 2 ∣ x}
>> refl,
no goals
-/
-- Comentario: Se ha usado el lema
-- + mem_bUnion_iff : y ∈ (⋃ x ∈ s, t x) ↔ ∃ x ∈ s, y ∈ t x
-- Comprobación:
universes u v
variable α : Type u
variable β : Type v
variable s : set α
variable t : α → set β
variable y : β
-- #check @mem_bUnion_iff α β s t y
example : y ∈ (⋃ x ∈ s, t x) ↔ ∃ x ∈ s, y ∈ t x :=
mem_bUnion_iff
-- 2ª demostración
-- ===============
example : (⋃ p ∈ primes, {x | p^2 ∣ x}) = {x | ∃ p ∈ primes, p^2 ∣ x} :=
by { ext, rw mem_bUnion_iff, refl }
-- ---------------------------------------------------------------------
-- Ejercicio. Demostrar que
-- (⋃ p ∈ primes, {x | p^2 ∣ x}) = {x | ∃ p ∈ primes, p^2 ∣ x}
-- ----------------------------------------------------------------------
example : (⋃ p ∈ primes, {x | p^2 ∣ x}) = {x | ∃ p ∈ primes, p^2 ∣ x} :=
by { ext, simp }
-- ---------------------------------------------------------------------
-- Ejercicio. Demostrar que
-- (⋂ p ∈ primes, {x | ¬ p ∣ x}) ⊆ {x | x < 2}
-- ----------------------------------------------------------------------
example : (⋂ p ∈ primes, {x | ¬ p ∣ x}) ⊆ {x | x < 2} :=
begin
intro x,
contrapose!,
simp,
apply exists_prime_and_dvd,
end
-- Prueba
-- ======
/-
⊢ (⋂ (p : ℕ) (H : p ∈ primes), {x : ℕ | ¬p ∣ x}) ⊆ {x : ℕ | x < 2}
>> intro x,
x : ℕ
⊢ (x ∈ ⋂ (p : ℕ) (H : p ∈ primes), {x : ℕ | ¬p ∣ x}) → x ∈ {x : ℕ | x < 2}
>> contrapose!,
⊢ x ∉ {x : ℕ | x < 2} → (x ∉ ⋂ (p : ℕ) (H : p ∈ primes), {x : ℕ | ¬p ∣ x})
>> simp,
⊢ 2 ≤ x → (∃ (x_1 : ℕ), x_1 ∈ primes ∧ x_1 ∣ x)
>> apply exists_prime_and_dvd,
no goals
-/
-- Comentario: Se ha aplicado el lema
-- + exists_prime_and_dvd : 2 ≤ n → (∃ (p : ℕ), p.prime ∧ p ∣ n)
variable n : ℕ
-- #check @exists_prime_and_dvd n
-- ---------------------------------------------------------------------
-- Ejercicio. Demostrar que
-- (⋃ p ∈ primes, {x | x ≤ p}) = univ
-- ----------------------------------------------------------------------
example : (⋃ p ∈ primes, {x | x ≤ p}) = univ :=
begin
apply eq_univ_of_forall,
intro x,
simp,
rcases exists_infinite_primes x with ⟨p, pge, primep⟩,
use [p, primep, pge],
end
-- Prueba
-- ======
/-
⊢ (⋃ (p : ℕ) (H : p ∈ primes), {x : ℕ | x ≤ p}) = univ
>> apply eq_univ_of_forall,
⊢ ∀ (x : ℕ), x ∈ ⋃ (p : ℕ) (H : p ∈ primes), {x : ℕ | x ≤ p}
>> intro x,
x : ℕ
⊢ x ∈ ⋃ (p : ℕ) (H : p ∈ primes), {x : ℕ | x ≤ p}
>> simp,
⊢ ∃ (i : ℕ), i ∈ primes ∧ x ≤ i
>> rcases exists_infinite_primes x with ⟨p, pge, primep⟩,
x p : ℕ,
pge : x ≤ p,
primep : p.prime
⊢ ∃ (i : ℕ), i ∈ primes ∧ x ≤ i
>> use [p, primep, pge],
no goals
-/
-- Comentario: Se han usado los lemas
-- + eq_univ_of_forall : (∀ x, x ∈ s) → s = univ
-- + exists_infinite_primes : ∀ (n : ℕ), ∃ (p : ℕ), n ≤ p ∧ p.prime
-- variable α : Type*
-- variable s : set α
-- #check @eq_univ_of_forall α s
-- #check exists_infinite_primes
|
r=359.43
https://sandbox.dams.library.ucdavis.edu/fcrepo/rest/collection/sherry-lehmann/catalogs/d7xs3j/media/images/d7xs3j-016/svc:tesseract/full/full/359.43/default.jpg Accept:application/hocr+xml
|
State Before: α✝ : Type u_1
o : Option α✝
⊢ ¬isSome o = true ↔ o = none State After: no goals Tactic: cases o <;> simp
|
/******************************************\
* OpenMP/SSE/BLAS Optimized Matrix Library *
* *
* by *
* Elliott Forney *
* 3.9.2010 *
\******************************************/
/*
* Libraries
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
// cblas
#include <cblas.h>
// OpenMP
#include <omp.h>
// SSE 4.1 intrinsics
#include <smmintrin.h>
// SSE 2 intrinsics
// #include <pmmintrin.h>
//
#include "errcheck.h"
#include "matrix.h"
/*
* Macros
*/
//** Debugging level
#define DEBUG 0
//** Initialization
// max number of chars per line in input table
#define line_buff_size 1024
//** Access
// row major indexing
// expects stride and data to be set
#define data_at(r,c) data[r*stride+c]
//** Addition/Subtraction
// when number of values in matrix is
// larger than add_lim use big kernel
#define add_lim 10000
//** Transpose
#define trans_lim 22500
//#define trans_tile 64
/*
* Global variables
*/
unsigned rand_state = 8;
/*
* Function prototypes
*/
//
void build_drc(matrix *m);
// sigmoid function
float phi(const float v);
// derivative of sigmoid function given phi(v)
float phi_prime(const float z);
// addition kernel for small matrices
void add_small(float *a, float *b, float *c, const unsigned n);
// addition kernel for big matrices
void add_big(float *m, float *b, float *c, const unsigned n);
// subtraction kernel for small matrices
void sub_small(float *a, float *b, float *c, const unsigned n);
// subtraction kernel for big matrices
void sub_big(float *a, float *b, float *c, const unsigned n);
// pointwise square kernel for small matrices
void sqr_small(float *a, float *b, const unsigned n);
// pointwise square kernel for big matrices
void sqr_big(float *a, float *b, const unsigned n);
// scalar multiply kernel for small matrices
void scl_small(float *a, float b, float *c, const unsigned n);
// scalar multiply kernel for big matrices
void scl_big(float *a, float b, float *c, const unsigned n);
// scalar multiplication & pointwise addition kernel for small matrices
void scl_add_small(float *a, float b, float *c, float *d, const unsigned n);
// scalar multiplication & pointwise addition kernel for big matrices
void scl_add_big(float *a, float b, float *c, float *d, const unsigned n);
// pointwise multiplication for small matrices
void pmult_small(float *a, float *b, float *c, const unsigned n);
// pointwise multiplication for big matrices
void pmult_big(float *a, float *b, float *c, const unsigned n);
/*
* Function bodies
*/
// build row-col indices for double index
void build_drc(matrix *m)
{
// not done/needed yet
}
// sigmoid function
float phi(const float v)
{
// recommended by Lecun, find citation!!
const float scl = 2.0f/3.0f;
return 1.7159f * tanh( scl * v );
}
// derivative of sigmoid function given phi(v)
float phi_prime(const float z)
{
const float scl = 2.0f/3.0f;
return scl * (1.7159f - z*z);
}
// addition kernel for small matrices
void add_small(float *a, float *b, float *c, const unsigned n)
{
// pointer to last destination
const float *a_end = a+n;
// loop through each value in destination
while (a < a_end)
{
// four values from b and c into sse registers
__m128 mm_v1 = _mm_load_ps(b);
__m128 mm_v2 = _mm_load_ps(c);
// add our sse vectors
mm_v1 = _mm_add_ps(mm_v1, mm_v2);
// store result into a
_mm_store_ps(a, mm_v1);
// increment pointers by 4
a += 4; b += 4; c += 4;
}
}
// addition kernel for big matrices
void add_big(float *a, float *b, float *c, const unsigned n)
{
unsigned i;
// loop through a, b and c by 4 in parallel
#pragma omp parallel for
for (i = 0; i < n; i += 4)
{
// load four values into sse registers
__m128 mm_v1 = _mm_load_ps(b+i); // what if they have different strides!!! :(
__m128 mm_v2 = _mm_load_ps(c+i);
// add our sse vectors
mm_v1 = _mm_add_ps(mm_v1, mm_v2);
// store result into a
_mm_store_ps(a+i, mm_v1);
}
}
// subtraction kernel for small matrices
void sub_small(float *a, float *b, float *c, const unsigned n)
{
const float *a_end = a+n;
while (a < a_end)
{
__m128 mm_v1 = _mm_load_ps(b);
__m128 mm_v2 = _mm_load_ps(c);
mm_v1 = _mm_sub_ps(mm_v1, mm_v2);
_mm_store_ps(a, mm_v1);
a += 4; b += 4; c += 4;
}
}
// subtraction kernel for big matrices
void sub_big(float *a, float *b, float *c, const unsigned n)
{
unsigned i;
#pragma omp parallel for
for (i = 0; i < n; i += 4)
{
__m128 mm_v1 = _mm_load_ps(b+i);
__m128 mm_v2 = _mm_load_ps(c+i);
mm_v1 = _mm_sub_ps(mm_v1, mm_v2);
_mm_store_ps(a+i, mm_v1);
}
}
// pointwise square kernel for small matrices
void sqr_small(float *a, float *b, const unsigned n)
{
const float *a_end = a+n;
while (a < a_end)
{
__m128 mm_v = _mm_load_ps(b);
mm_v = _mm_mul_ps(mm_v, mm_v);
_mm_store_ps(a, mm_v);
a += 4; b += 4;
}
}
// pointwise square kernel for big matrices
void sqr_big(float *a, float *b, const unsigned n)
{
unsigned i;
#pragma omp parallel for
for (i = 0; i < n; i += 4)
{
__m128 mm_v = _mm_load_ps(b+i);
mm_v = _mm_mul_ps(mm_v, mm_v);
_mm_store_ps(a+i, mm_v);
}
}
// scalar multiplication kernel for small matrices
void scl_small(float *a, float b, float *c, const unsigned n)
{
const float *a_end = a+n;
__m128 mm_s = _mm_set1_ps(b);
while (a < a_end)
{
__m128 mm_v = _mm_load_ps(c);
mm_v = _mm_mul_ps(mm_s, mm_v);
_mm_store_ps(a, mm_v);
a += 4; c += 4;
}
}
// scalar multiplication kernel for big matrices
void scl_big(float *a, float b, float *c, const unsigned n)
{
unsigned i;
const __m128 mm_s = _mm_set1_ps(b);
#pragma omp parallel for
for (i = 0; i < n; i += 4)
{
__m128 mm_v = _mm_load_ps(c+i);
mm_v = _mm_mul_ps(mm_s, mm_v);
_mm_store_ps(a+i, mm_v);
}
}
// scalar multiplication & pointwise addition kernel for small matrices
void scl_add_small(float *a, float b, float *c, float *d, unsigned n)
{
const float *a_end = a+n;
__m128 mm_s = _mm_set1_ps(b);
while (a < a_end)
{
__m128 mm_v1 = _mm_load_ps(c);
__m128 mm_v2 = _mm_load_ps(d);
mm_v1 = _mm_mul_ps(mm_s, mm_v1);
mm_v1 = _mm_add_ps(mm_v1, mm_v2);
_mm_store_ps(a, mm_v1);
a += 4; c += 4; d += 4;
}
}
// scalar multiplication & pointwise addition kernel for big matrices
void scl_add_big(float *a, float b, float *c, float *d, unsigned n)
{
unsigned i;
const __m128 mm_s = _mm_set1_ps(b);
#pragma omp parallel for
for (i = 0; i < n; i += 4)
{
__m128 mm_v1 = _mm_load_ps(c+i);
__m128 mm_v2 = _mm_load_ps(d+i);
mm_v1 = _mm_mul_ps(mm_s, mm_v1);
mm_v1 = _mm_add_ps(mm_v1, mm_v2);
_mm_store_ps(a+i, mm_v1);
}
}
// pointwise multiplication kernel for small matrices
void pmult_small(float *a, float *b, float *c, const unsigned n)
{
// pointer to last destination
const float *a_end = a+n;
// loop through each value in destination
while (a < a_end)
{
// four values from b and c into sse registers
__m128 mm_v1 = _mm_load_ps(b);
__m128 mm_v2 = _mm_load_ps(c);
// mult our sse vectors
mm_v1 = _mm_mul_ps(mm_v1, mm_v2);
// store result into a
_mm_store_ps(a, mm_v1);
// increment pointers by 4
a += 4; b += 4; c += 4;
}
}
// pointwise multiplication kernel for big matrices
void pmult_big(float *a, float *b, float *c, const unsigned n)
{
unsigned i;
// loop through a, b and c by 4 in parallel
#pragma omp parallel for
for (i = 0; i < n; i += 4)
{
// load four values into sse registers
__m128 mm_v1 = _mm_load_ps(b+i);
__m128 mm_v2 = _mm_load_ps(c+i);
// mult our sse vectors
mm_v1 = _mm_mul_ps(mm_v1, mm_v2);
// store result into a
_mm_store_ps(a+i, mm_v1);
}
}
/*
* External function bodies
*/
//** Initialization & Destruction
// initialize matrix m of size r by c
void matrix_init(matrix *m, const unsigned r, const unsigned c)
{
// set matrix dimensions
m->r = r;
m->c = c;
// zero pad to nearest mult of 64, lcm 4 for sse, 64 for trans
// leave one extra row/col to append bias terms
// m->rstride = r + (64 - (r % 64)); // lcm(trans_tile, 4)
// m->cstride = c + (64 - (c % 64));
// 64 tiles speeds up transpose but hurts everything else
m->rstride = r + (4 - (r % 4));
m->cstride = c + (4 - (c % 4));
// allocate space for matrix, 16 byte aligned
m->cpu_data = (float*)_mm_malloc((m->rstride)*(m->cstride)*
sizeof(float), 16);
if (m->cpu_data == NULL)
errcheck_cpu();
// allocate space for last column holder
m->cv = (float*)malloc((m->r)*sizeof(float));
if (m->cv == NULL)
errcheck_cpu();
// zero out data for padding
memset(m->cpu_data, '\0', (m->rstride)*(m->cstride)*sizeof(float));
memset(m->cv, '\0', (m->r)*sizeof(float));
// build row-col indices
build_drc(m);
}
// initialize matrix m from ascii table
void matrix_init_file(matrix *m, char *file_name)
{
// will need to do this dynamically if
// we ever want to handle big tables!!!
float table_data[line_buff_size][line_buff_size];
unsigned r = 0, c = 0;
// open file & setup input buffer
FILE *table = fopen(file_name, "r");
char line_buffer[line_buff_size];
// check if we were even able to open table file
if (file_name == NULL)
errcheck_cpu();
// buckle-up, don't drink and code
memset(table_data, '\0', line_buff_size*line_buff_size*sizeof(float));
// for each line in table (row)
while (fgets(line_buffer, line_buff_size, table))
{
if (DEBUG > 5)
printf("line buffer: %s\n", line_buffer);
// set up string tokenizer on input buffer
char *cur_val = strtok(line_buffer, " "); // Note reentrant or thread safe!!
// don't increment num rows on blank line
if (cur_val != NULL)
{
c = 0; // new row, reset col counter
// for each token (col)
while (cur_val != NULL)
{
// convert from char to float
table_data[r][c] = atof(cur_val);
if (DEBUG > 5)
printf("converting %d %d %f\n", r, c, table_data[r][c]);
// get next token
cur_val = strtok(NULL, " ");
++c; // increment num cols
}
++r; // increment num rows
}
}
// close file descriptor
fclose(table);
// initialize m
matrix_init(m, r, c);
// setup for data_at
unsigned mr, mc;
float *data = m->cpu_data;
const unsigned stride = m->cstride;
// loop through collected data and put into m
for (mr = 0; mr < r; ++mr)
for (mc = 0; mc < c; ++mc)
data_at(mr,mc) = table_data[mr][mc];
}
// load zeros into matrix m
void matrix_load_zero(matrix m)
{
float *data = m.cpu_data;
const float *data_end = data + (m.rstride*m.cstride);
// loop through all values and set to zero
// memset?
while (data < data_end)
*(data++) = 0.0f;
}
// load values from an array
void matrix_load_array(matrix m, float *v)
{
unsigned r, c, i = 0;
// set data and stride for data_at
float *data = m.cpu_data;
const unsigned stride = m.cstride;
for (r = 0; r < m.r; ++r)
for (c = 0; c < m.c; ++c)
data_at(r,c) = v[i++];
}
// load values from the random uniform distribution
void matrix_load_runif(matrix m, float min, float max)
{
unsigned r, c;
// set data and stride for data_at
float *data = m.cpu_data;
const unsigned stride = m.cstride;
const float range = max - min;
// needs work to be multithreaded!
// set each non-padding value from random uniform
for (r = 0; r < m.r; ++r)
for (c = 0; c < m.c; ++c)
data_at(r,c) = rand_r(&rand_state) * range / RAND_MAX + min;
}
void matrix_load_testa(matrix m, unsigned n)
{
unsigned r, c;
// set data and stride for data_at
float *data = m.cpu_data;
const unsigned stride = m.cstride;
#pragma omp parallel for private(c)
for (r = 0; r < m.r; ++r)
for (c = 0; c < m.c; ++c)
//data_at(r,c) = (float)n * (float)r*c;
data_at(r,c) = (float)n;
}
void matrix_load_testb(matrix m)
{
unsigned r, c;
// set data and stride for data_at
float *data = m.cpu_data;
const unsigned stride = m.cstride;
#pragma omp parallel for private(c)
for (r = 0; r < m.r; ++r)
for (c = 0; c < m.c; ++c)
//data_at(r,c) = (float)r;
data_at(r,c) = 1.0f;
}
void matrix_load_testc(matrix m)
{
unsigned r, c;
// set data and stride for data_at
float *data = m.cpu_data;
const unsigned stride = m.cstride;
#pragma omp parallel for private(c)
for (r = 0; r < m.r; ++r)
for (c = 0; c < m.c; ++c)
//data_at(r,c) = (float)c;
data_at(r,c) = 1.0f;
}
// copy values to an array
void matrix_unload_array(matrix m, float *v)
{
unsigned r, c, i = 0;
float *data = m.cpu_data;
const unsigned stride = m.cstride;
for (r = 0; r < m.r; ++r)
for (c = 0; c < m.c; ++c)
v[i++] = data_at(r,c);
}
// write values to a file
void matrix_unload_file(matrix m, char *file_name)
{
unsigned r, c;
float *data = m.cpu_data;
const unsigned stride = m.cstride;
// open file for writing
FILE *table = fopen(file_name, "w");
// check if we were even able to open table file
if (file_name == NULL)
errcheck_cpu();
for (r = 0; r < m.r; ++r)
{
for (c = 0; c < m.c-1; ++c)
fprintf(table, "%.16f ", data_at(r,c));
fprintf(table, "%.16f\n", data_at(r,c));
}
fclose(table);
}
// destroy matrix m
void matrix_dest(matrix *m)
{
// free matrix data
free(m->cpu_data);
free(m->cv);
// free row/col indices
//free(m->drc);
// set everything to zero for safety
m->r = 0;
m->c = 0;
m->rstride = 0;
m->cstride = 0;
m->cpu_data = NULL;
}
//** Synchronization
// wait for asynchronous calls to finish
void matrix_wait()
{
// nada
}
//** Addition/Subtraction
// a = b + c
void matrix_add(matrix a, matrix b, matrix c)
{
#ifndef NO_ERRCHECK
if ( (a.r != b.r) || (b.r != c.r) ) {
fprintf(stderr, __FILE__ " %d: "
"Rows don't match for addition!\n", __LINE__);
exit(CPU_ERROR);
}
if ( (a.c != b.c) || (b.c != c.c) ) {
fprintf(stderr, __FILE__ " %d: "
"Cols don't match for addition!\n", __LINE__);
exit(CPU_ERROR);
}
#endif
const unsigned n = a.r * a.cstride;
/* naive
unsigned i;
float *aval = a.cpu_data;
float *bval = b.cpu_data;
float *cval = c.cpu_data;
for (i = 0; i < n; ++i)
aval[i] = bval[i] + cval[i]; */
if (n < add_lim)
add_small(a.cpu_data, b.cpu_data, c.cpu_data, n);
else
add_big(a.cpu_data, b.cpu_data, c.cpu_data, n);
}
// a = b - c
void matrix_sub(matrix a, matrix b, matrix c)
{
#ifndef NO_ERRCHECK
if ( (a.r != b.r) || (b.r != c.r) ) {
fprintf(stderr, __FILE__ " %d: "
"Rows don't match for subtraction!\n", __LINE__);
exit(CPU_ERROR);
}
if ( (a.c != b.c) || (b.c != c.c) ) {
fprintf(stderr, __FILE__ " %d: "
"Cols don't match for subtraction!\n", __LINE__);
exit(CPU_ERROR);
}
#endif
const unsigned n = a.r * a.cstride;
if (n < add_lim)
sub_small(a.cpu_data, b.cpu_data, c.cpu_data, n);
else
sub_big(a.cpu_data, b.cpu_data, c.cpu_data, n);
}
//** Multiplication
// a = b * c
void matrix_mult(matrix a, matrix b, matrix c)
{
#ifndef NO_ERRCHECK
if ( (b.c != c.r) || (a.r != b.r) || (a.c != c.c) ) {
fprintf(stderr, __FILE__ " %d: "
"Dimensions don't match for multiplication!\n", __LINE__);
exit(CPU_ERROR);
}
#endif
// use cblas for multiplication, not going to beat this.. for now ;)
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,
b.r, c.c, b.c, 1.0f,
b.cpu_data, b.cstride, c.cpu_data, c.cstride,
0.0f, a.cpu_data, a.cstride);
}
// a = phi(b * c)
void matrix_mult_phi(matrix a, matrix b, matrix c)
{
#ifndef NO_ERRCHECK
if ( (b.c != c.r) || (a.r != b.r) || (a.c != c.c) ) {
fprintf(stderr, __FILE__ " %d: "
"Dimensions don't match for mult_phi!\n", __LINE__);
exit(CPU_ERROR);
}
#endif
// use cblas for multiplication, not going to beat this.. for now ;)
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,
b.r, c.c, b.c, 1.0f,
b.cpu_data, b.cstride, c.cpu_data, c.cstride,
0.0f, a.cpu_data, a.cstride);
// apply phi
unsigned row, col;
float *adata = a.cpu_data;
const unsigned astride = a.cstride;
// need to optimize small kern and put into functions
if ((a.r*a.cstride) < add_lim)
{
const __m128 mm_s1 = _mm_set1_ps(1.7159f);
const __m128 mm_s2 = _mm_set1_ps(2.0f/3.0f);
for (row = 0; row < a.r; ++row)
for (col = 0; col < a.c; col += 4)
{
unsigned i;
const unsigned base = row*astride+col;
// inside scalar mult
__m128 mm_v = _mm_load_ps(adata+base);
mm_v = _mm_mul_ps(mm_v, mm_s2);
_mm_store_ps(adata+base, mm_v);
// apply tanh
for (i = base; i < base+4; ++i)
adata[i] = tanh(adata[i]);
// outside scalar mult
mm_v = _mm_load_ps(adata+base);
mm_v = _mm_mul_ps(mm_v, mm_s1);
_mm_store_ps(adata+base, mm_v);
}
}
else
{
const __m128 mm_s1 = _mm_set1_ps(1.7159f);
const __m128 mm_s2 = _mm_set1_ps(2.0f/3.0f);
#pragma omp parallel for private(col)
for (row = 0; row < a.r; ++row)
for (col = 0; col < a.c; col += 4)
{
unsigned i;
const unsigned base = row*astride+col;
// inside scalar mult
__m128 mm_v = _mm_load_ps(adata+base);
mm_v = _mm_mul_ps(mm_v, mm_s2);
_mm_store_ps(adata+base, mm_v);
// apply tanh
for (i = base; i < base+4; ++i)
adata[i] = tanh(adata[i]);
// outside scalar mult
mm_v = _mm_load_ps(adata+base);
mm_v = _mm_mul_ps(mm_v, mm_s1);
_mm_store_ps(adata+base, mm_v);
}
}
/*
unsigned i;
#pragma omp parallel for
for (i = 0; i < a.r*a.cstride; ++i)
adata[i] = phi(adata[i]);
*/
}
//** Transpose
// a = b^T
void matrix_trans(matrix a, matrix b)
{
#ifndef NO_ERRCHECK
if ( (a.r != b.c) || (a.c != b.r) ) {
fprintf(stderr, __FILE__ " %d: "
"Source and destination dimensions don't match for transpose!\n", __LINE__);
exit(CPU_ERROR);
}
#endif
unsigned r, c;
float *adata = a.cpu_data;
float *bdata = b.cpu_data;
const unsigned astride = a.cstride;
const unsigned bstride = b.cstride;
// need to seperate into smaller functions
if ((a.r*a.c) < trans_lim)
{
for (r = 0; r < a.r; r += 4)
for (c = 0; c < a.c; c += 4)
{
// load 4x4 tile
float *base = bdata + c*bstride+r;
__m128 mm_v1 = _mm_load_ps(base );
__m128 mm_v2 = _mm_load_ps(base + bstride);
__m128 mm_v3 = _mm_load_ps(base + 2*bstride);
__m128 mm_v4 = _mm_load_ps(base + 3*bstride);
// transpose 4x4 tile
_MM_TRANSPOSE4_PS(mm_v1, mm_v2, mm_v3, mm_v4);
// store 4x4 tile back into a
base = adata + r*astride+c;
_mm_store_ps(base, mm_v1);
_mm_store_ps(base + astride, mm_v2);
_mm_store_ps(base + 2*astride, mm_v3);
_mm_store_ps(base + 3*astride, mm_v4);
}
}
else
{
#pragma omp parallel for private(c)
for (r = 0; r < a.r; r += 4)
for (c = 0; c < a.c; c += 4)
{
// load 4x4 tile
float *base = bdata + c*bstride+r;
__m128 mm_v1 = _mm_load_ps(base );
__m128 mm_v2 = _mm_load_ps(base + bstride);
__m128 mm_v3 = _mm_load_ps(base + 2*bstride);
__m128 mm_v4 = _mm_load_ps(base + 3*bstride);
// transpose 4x4 tile
_MM_TRANSPOSE4_PS(mm_v1, mm_v2, mm_v3, mm_v4);
// store 4x4 tile back into a
base = adata + r*astride+c;
_mm_store_ps(base, mm_v1);
_mm_store_ps(base + astride, mm_v2);
_mm_store_ps(base + 2*astride, mm_v3);
_mm_store_ps(base + 3*astride, mm_v4);
}
}
/* tiled version, fast but big tiles hurt everything else
#pragma omp parallel for private(tc,r,c)
for (tr = 0; tr < a.r; tr += trans_tile)
for (tc = 0; tc < a.c; tc += trans_tile)
for (r = tr; r < tr+trans_tile; r += 4)
for (c = tc; c < tc+trans_tile; c += 4)
{
// load 4x4 tile
float *base = bdata + c*bstride+r;
__m128 mm_v1 = _mm_load_ps(base );
__m128 mm_v2 = _mm_load_ps(base + bstride);
__m128 mm_v3 = _mm_load_ps(base + 2*bstride);
__m128 mm_v4 = _mm_load_ps(base + 3*bstride);
// transpose 4x4 tile
_MM_TRANSPOSE4_PS(mm_v1, mm_v2, mm_v3, mm_v4);
// store 4x4 tile back into a
base = adata + r*astride+c;
_mm_store_ps(base, mm_v1);
_mm_store_ps(base + astride, mm_v2);
_mm_store_ps(base + 2*astride, mm_v3);
_mm_store_ps(base + 3*astride, mm_v4);
} */
}
//** Pointwise miscellaneous
// a = b^2
void matrix_sqr(matrix a, matrix b)
{
#ifndef NO_ERRCHECK
if ( (a.r != b.r) || (a.c != b.c) ) {
fprintf(stderr, __FILE__ " %d: "
"Source and destination dimensions don't match for square!\n", __LINE__);
exit(CPU_ERROR);
}
#endif
const unsigned n = a.r * a.cstride;
if (n < add_lim)
sqr_small(a.cpu_data, b.cpu_data, n);
else
sqr_big(a.cpu_data, b.cpu_data, n);
}
// scalar multiplication a = b*c
void matrix_scl(matrix a, float b, matrix c)
{
#ifndef NO_ERRCHECK
if ( (a.r != c.r) || (a.c != c.c) ) {
fprintf(stderr, __FILE__ " %d: "
"Source and destination dimensions don't match for scale!\n", __LINE__);
exit(CPU_ERROR);
}
#endif
const unsigned n = a.r * a.cstride;
if (n < add_lim)
scl_small(a.cpu_data, b, c.cpu_data, n);
else
scl_big(a.cpu_data, b, c.cpu_data, n);
}
// scalar multiplication & pointwise addition a = b.*c+d
void matrix_scl_add(matrix a, float b, matrix c, matrix d)
{
#ifndef NO_ERRCHECK
if ( (a.r != c.r) || (a.c != c.c) ) {
fprintf(stderr, __FILE__ " %d: "
"Source and destination dimensions don't match for scl_add!\n", __LINE__);
exit(CPU_ERROR);
}
if ( (a.r != d.r) || (a.c != d.c) ) {
fprintf(stderr, __FILE__ " %d: "
"Source and destination dimensions don't match for scl_add!\n", __LINE__);
exit(CPU_ERROR);
}
#endif
const unsigned n = a.r * a.cstride;
if (n < add_lim)
scl_add_small(a.cpu_data, b, c.cpu_data, d.cpu_data, n);
else
scl_add_big(a.cpu_data, b, c.cpu_data, d.cpu_data, n);
}
// pointwise multiplication a = b.*c
void matrix_pmult(matrix a, matrix b, matrix c)
{
#ifndef NO_ERRCHECK
if ( (a.r != b.r) || (b.r != c.r) ) {
fprintf(stderr, __FILE__ " %d: "
"Rows don't match for pmult!\n", __LINE__);
exit(CPU_ERROR);
}
if ( (a.c != b.c) || (b.c != c.c) ) {
fprintf(stderr, __FILE__ " %d: "
"Cols don't match for pmult!\n", __LINE__);
exit(CPU_ERROR);
}
#endif
const unsigned n = a.r * a.cstride;
if (n < add_lim)
pmult_small(a.cpu_data, b.cpu_data, c.cpu_data, n);
else
pmult_big(a.cpu_data, b.cpu_data, c.cpu_data, n);
}
//
void matrix_phi_prime(matrix a, matrix b)
{
unsigned r, c;
const unsigned astride = a.cstride;
const unsigned bstride = b.cstride;
float *adata = a.cpu_data;
float *bdata = b.cpu_data;
const __m128 mm_s1 = _mm_set1_ps(2.0f/3.0f);
const __m128 mm_s2 = _mm_set1_ps(1.7159f);
// need to optimize small kern and put into functions
if ((a.r*a.cstride) < add_lim)
{
for (r = 0; r < a.r; ++r)
for (c = 0; c < a.c; c += 4)
{
__m128 mm_v1 = _mm_load_ps(bdata + r*bstride+c);
mm_v1 = _mm_mul_ps(mm_v1, mm_v1);
mm_v1 = _mm_sub_ps(mm_s2, mm_v1);
mm_v1 = _mm_mul_ps(mm_s1, mm_v1);
_mm_store_ps(adata + r*astride+c, mm_v1);
}
}
else
{
#pragma omp parallel for private(c)
for (r = 0; r < a.r; ++r)
for (c = 0; c < a.c; c += 4)
{
__m128 mm_v1 = _mm_load_ps(bdata + r*bstride+c);
mm_v1 = _mm_mul_ps(mm_v1, mm_v1);
mm_v1 = _mm_sub_ps(mm_s2, mm_v1);
mm_v1 = _mm_mul_ps(mm_s1, mm_v1);
_mm_store_ps(adata + r*astride+c, mm_v1);
}
}
// const float scl = 2.0f/3.0f;
// return scl * (1.7159f - z*z);
/*
#pragma omp parallel for private(c)
for (r = 0; r < a.r; ++r)
for (c = 0; c < a.c; ++c)
adata[r*astride + c] =
phi_prime(bdata[r*bstride + c]);
*/
}
// a = b .* phi_prime(c)
void matrix_pmult_phi_prime(matrix a, matrix b, matrix c)
{
unsigned i;
float *adata = a.cpu_data;
float *bdata = b.cpu_data;
float *cdata = c.cpu_data;
const __m128 mm_s1 = _mm_set1_ps(2.0f/3.0f);
const __m128 mm_s2 = _mm_set1_ps(1.7159f);
#pragma omp parallel for
for (i = 0; i < a.r*a.cstride; i += 4)
{
__m128 mm_v1 = _mm_load_ps(bdata+i);
__m128 mm_v2 = _mm_load_ps(cdata+i);
mm_v2 = _mm_mul_ps(mm_v2, mm_v2);
mm_v2 = _mm_sub_ps(mm_s2, mm_v2);
mm_v2 = _mm_mul_ps(mm_s1, mm_v2);
mm_v2 = _mm_mul_ps(mm_v1, mm_v2);
_mm_store_ps(adata + i, mm_v2);
}
}
//
void matrix_delta(matrix delta, matrix y, matrix g)
{
unsigned r, c;
#ifndef NO_ERRCHECK
if ( (delta.r != y.r) || (y.r != g.r) ) {
fprintf(stderr, __FILE__ " %d: "
"Rows don't match for delta!\n", __LINE__);
exit(CPU_ERROR);
}
if ( (delta.c != y.c) || (y.c != g.c) ) {
fprintf(stderr, __FILE__ " %d: "
"Cols don't match for delta!\n", __LINE__);
exit(CPU_ERROR);
}
#endif
const unsigned dstride = delta.cstride;
const unsigned gstride = g.cstride;
const unsigned ystride = y.cstride;
float *ddata = delta.cpu_data;
float *gdata = g.cpu_data;
float *ydata = y.cpu_data;
// need to optimize small kern and put into functions
if ((delta.r*delta.cstride) < add_lim)
{
const __m128 mm_s = _mm_set1_ps(2.0f/(g.r*g.c));
for (r = 0; r < delta.r; ++r)
for (c = 0; c < delta.c; c += 4)
{
__m128 mm_v1 = _mm_load_ps(gdata + r*gstride+c);
__m128 mm_v2 = _mm_load_ps(ydata + r*ystride+c);
mm_v1 = _mm_sub_ps(mm_v2, mm_v1);
mm_v1 = _mm_mul_ps(mm_v1, mm_s);
_mm_store_ps(ddata + r*dstride+c, mm_v1);
}
}
else
{
const __m128 mm_s = _mm_set1_ps(2.0f/(g.r*g.c));
#pragma omp parallel for private (c)
for (r = 0; r < delta.r; ++r)
for (c = 0; c < delta.c; c += 4)
{
__m128 mm_v1 = _mm_load_ps(gdata + r*gstride+c);
__m128 mm_v2 = _mm_load_ps(ydata + r*ystride+c);
mm_v1 = _mm_sub_ps(mm_v2, mm_v1);
mm_v1 = _mm_mul_ps(mm_v1, mm_s);
_mm_store_ps(ddata + r*dstride+c, mm_v1);
}
}
/*
const float denom = 2.0f / (g.r*g.c);
#pragma omp parallel for private(c)
for (r = 0; r < delta.r; ++r)
for (c = 0; c < delta.c; ++c)
{
const float gval = gdata[r*gstride + c];
const float yval = ydata[r*ystride + c];
// wow, sse could be used all over here!
ddata[r*dstride + c] =
(yval - gval) * denom;
}
*/
}
//** Combination/Separation
// remove last row of m
void matrix_r0(matrix *m)
{
--(m->r);
float *data = (m->cpu_data)+((m->r)*(m->cstride));
const float *data_end = data + m->c;
while (data < data_end)
*(data++) = 0.0f;
}
// append a row of 1's to m
void matrix_r1(matrix *m)
{
float *data = (m->cpu_data)+((m->r)*(m->cstride));
const float *data_end = data + m->c;
while (data < data_end)
*(data++) = 1.0f;
++(m->r);
}
//** Error measurement
// rmse between values of actual and approx
float matrix_rmse(matrix actual, matrix approx)
{
// if dims don't match throw error!
unsigned r, c;
const unsigned stride = actual.cstride;
const unsigned len = actual.r*actual.c;
float *d1 = actual.cpu_data;
float *d2 = approx.cpu_data;
float err = 0.0f;
// need to use omp, maybe reduction?
for (r = 0; r < actual.r; ++r)
for (c = 0; c < actual.c; ++c)
{
const unsigned i = r*stride+c;
err += (d1[i] - d2[i])*(d1[i] - d2[i]);
}
return sqrt(err/len);
}
// remove and save last col of m
void matrix_c0v(matrix *m)
{
unsigned r;
const unsigned stride = m->cstride;
const unsigned c = --(m->c);
float *data = m->cpu_data;
for (r = 0; r < m->r; ++r)
{
float *cur = data + r*stride+c;
m->cv[r] = *cur;
*cur = 0.0f;
}
}
// restore last col of m
void matrix_cv(matrix *m)
{
unsigned r;
const unsigned stride = m->cstride;
const unsigned c = (m->c)++;
float *data = m->cpu_data;
for (r = 0; r < m->r; ++r)
data[r*stride+c] = m->cv[r];
}
//** Output
// print m to standard out
void matrix_print(matrix m)
{
unsigned r, c;
const unsigned stride = m.cstride;
float *data = m.cpu_data;
// print each value to stdout
for (r = 0; r < m.r; ++r)
{
for (c = 0; c < m.c; ++c)
printf("%f ", data_at(r,c));
printf("\n");
}
}
// print m including padding to standard out
void matrix_print_padded(matrix m)
{
unsigned r, c;
// set data and stride for data_at
const unsigned stride = m.cstride;
float *data = m.cpu_data;
// print each value to stdout
for (r = 0; r < m.rstride; ++r)
{
for (c = 0; c < m.cstride; ++c)
printf("%f ", data_at(r,c));
printf("\n");
}
}
|
\subsection{\acrshort{nrpa} adapt}%
\label{sub:nrpa_adapt}
The \gls{nrpa} adapt algorithm is used to adapt a policy to a given sequence.
We explained in section \ref{sub:nrpa_playout} that the policy is used during rollout to select actions and generate sequence.
Adapt a policy \(\pi\) to a sequence \(S\) means to give the policy a greater tendency to generate \(S\).
More formerly, is \(\Omega\) is the state of all sequences, then a policy \(\pi\) can be seen as a probability distribution over \(\Omega\).
If \(\pi\) is adapted to \(S\) resulting in \(\pi'\) then \(P(S|\pi) \leq P(S|\pi')\).
The adapt algorithm is given in algorithm~\ref{alg:nrpa_adapt}.
The algorithm starts by copying the policy (line 2) which can be avoided as explained with the generalized form of the \gls{nrpa}\cite{gnrpa}.
Then, for each move of the sequence (line 4), it starts by increasing the weight associated to the current move (line 5).
Next, it computes the sum of weights, taken to the exponential, of all legal moves for the current state (line 7-9).
Finally, it updates the weight of all considered actions according to the exponential of their weight divided by the sum (line 10-12).
The sum of weights is important to maintain the sum of probability to 1.
The adapt algorithm use a argument \(\alpha\) that represents the learning step of the adapt algorithm.
The bigger it is, the more closer the policy will be to the sequence after it has been adapted.
\(\alpha\) is problem-dependent and must be tune in order to obtain the best possible results.
It represents one of the difficulty of the \gls{nrpa}.
\begin{figure}[htpb]
\centering
\begin{minipage}{.7\linewidth}
\subimport{../../../algorithms/nrpa/}{adapt.tex}
\end{minipage}
\end{figure}
|
function [h, compUpV, compUp] = lfmComputeH4VP(gamma1_p, gamma1_m, sigma2, t1, ...
preFactor, preExp, mode)
% LFMCOMPUTEH4VP Helper function for computing part of the LFMVXLFM kernel.
% FORMAT
% DESC computes a portion of the LFMVXLFM kernel.
% ARG gamma1 : Gamma value for first system.
% ARG gamma2 : Gamma value for second system.
% ARG sigma2 : length scale of latent process.
% ARG t1 : first time input (number of time points x 1).
% ARG t2 : second time input (number of time points x 1).
% ARG mode: indicates in which way the vectors t1 and t2 must be transposed
% RETURN h : result of this subcomponent of the kernel for the given values.
%
% COPYRIGHT : Mauricio A. Alvarez, 2010
%
% SEEALSO : lfmComputeH4Hat, lfmXlfmKernCompute
% KERN
% This could also be used with str2func changing between 'lfm' and 'lfmvp'
if mode==0
if nargout > 1
[compUpV{1}, compUp{1}] = lfmvpComputeUpsilonVector(gamma1_p,sigma2, t1, 0);
[compUpV{2}, compUp{2}] = lfmvpComputeUpsilonVector(gamma1_m,sigma2, t1, 0);
h = compUpV{1}*( preExp(:,1)/preFactor(1) - preExp(:,2)/preFactor(2)).' ...
+ compUpV{2}*( preExp(:,2)/preFactor(3) - preExp(:,1)/preFactor(4)).';
else
h = lfmvpComputeUpsilonVector(gamma1_p,sigma2, t1, 0)*( preExp(:,1)/preFactor(1) - preExp(:,2)/preFactor(2)).' ...
+ lfmvpComputeUpsilonVector(gamma1_m,sigma2, t1, 0)*( preExp(:,2)/preFactor(3) - preExp(:,1)/preFactor(4)).';
end
else
if nargout > 1
compUp{1} = lfmComputeUpsilonVector(gamma1_p,sigma2, t1);
compUp{2} = lfmComputeUpsilonVector(gamma1_m,sigma2, t1);
h = compUp{1}*( preExp(:,2)/preFactor(2) - preExp(:,1)/preFactor(1)).' ...
+ compUp{2}*( preExp(:,1)/preFactor(4) - preExp(:,2)/preFactor(3)).';
compUpV = compUp;
else
h = lfmComputeUpsilonVector(gamma1_p,sigma2, t1)*( preExp(:,2)/preFactor(2) - preExp(:,1)/preFactor(1)).' ...
+ lfmComputeUpsilonVector(gamma1_m,sigma2, t1)*( preExp(:,1)/preFactor(4) - preExp(:,2)/preFactor(3)).';
end
end
|
Require Import yarn_config.
Inductive ResourceManager := Yarn.
Definition rm_config_type (rm: ResourceManager): Type :=
match rm with
| Yarn => YarnConfig
end.
|
# Bayesian Estimation of Orbital Scaling Parameters
## Introduction
These notes briefly outline a Bayesian approach to estimating the statistical distribution of the orbital scaling (or $\lambda$) parameters from NIST data and their associated experimental error bars. The atomic structure calculation can be viewed as a mapping $f$ from the true orbital scaling parameter $\lambda \in \mathbb{R}^m$ to a set of observable quantities of interest, $f(\lambda) \in \mathbb{R}^n$. The output of this mapping is measured experimentally, albeit with some error.
The simplest "observation model" is to assume that a _random_ error $E = [E_1,...,E_n]\in \mathbb{R}^n$ is added to the output $f(\lambda)$, yielding a _random_ observation
\begin{equation}
Y = f(\lambda) + E. \label{eq:observation_model}
\end{equation}
Other observation models are also possible.
Now, suppose we don't know the true value of $\lambda$, but that we have a vector $\vec y_{\text{nist}} = [y_1, y_2, ..., y_n]^T$ of actual NIST measurements of the energies and A-values. Due to the random measurement noise $E$, we cannot be certain that the observed values are the actual outputs $f(\lambda)$. To reflect our uncertainty, we estimate the true $\lambda$ by a random quantity $\Lambda$ whose distribution is consistent with the observations $y_{\text{nist}}$ and the statistical distribution of the error $E$. More specifically, we seek to estimate the conditional density function $\pi_{\Lambda|y_{\text{nist}}}$ given the NIST observations. Bayes formula allows us to express this density in terms of the likelihood $\pi_{Y|\Lambda}$ and a prior density $\pi_\Lambda$:
\begin{equation}\label{eq:bayes_formula}
\pi_{\Lambda|Y}(\lambda|y_{\text{nist}}) = \frac{\pi_\Lambda(\lambda)\pi_{Y|\Lambda}(y_{\text{nist}}|\lambda)}{\pi_{Y}(y_{\text{nist}})},
\end{equation}
provided $\pi_{Y}(y_{\text{nist}})\neq 0$.
### The Likelihood Function
If we have a density function for the measurement noise $\pi_E(e)$, then our given observation model \eqref{eq:observation_model} makes it easy to determine the likelihood. Indeed,
$$
\pi_{Y|\Lambda}(y_{\text{nist}}|\lambda)= \mathbb{P}(Y= y_{\text{nist}}|\Lambda=\lambda) = \mathbb{P}(E = y_{\text{nist}}-f(\lambda)) = \pi_E(y_{\text{nist}}-f(\lambda))
$$
#### The Noise Density
We now turn to estimating $\pi_E$. To this end we make the following simplifying assumption - it can be relaxed in principle.
> _Assumption:_ The measurement errors of the various energies and A-values are statistically independent.
The above assumption allows us to write the joint density function $\pi_{E}$ of the absolute errors $E = [E_1,...,E_n]$ as the product of univariate densities, i.e.
$$
\pi_{E}(e) = \prod_{i=1}^n \pi_{E_i}(e_i), \ \text{for } e = [e_1,...,e_n] \in \mathbb{R}^n.
$$
Let $\vec \eta = [\eta_1, ..., \eta_n]$ be the relative errors for each quantity of interest, reported in the NIST database. We use these to specify the statistical distribution of the absolute errors.
##### Uniform Errors
If assume that the NIST errors are uniformly distributed, we can use $\eta_i$ to find the range. Specifically, let $a_i = y_i - \eta_i y_i$ and $b_i=y_i + \eta_i y_i$, so that
$$
\pi_{E_i}(e_i) = \left\{
\begin{array}{ll}
\frac{1}{b_i-a_i}, & \text{if } a_i \leq e_i \leq b_i \\
0, &\text{otherwise}\end{array} \right. .
$$
The joint distribution is therefore
$$
\pi_{E}(e) = \prod_{i=1}^n \pi_{E_i}(e_i) = \left\{
\begin{array}{ll}
\prod_{i=1}^n \frac{1}{b_i-a_i}, & \text{if } a_i \leq e_i \leq b_i \text{ for } i=1,...,n \\
0, &\text{otherwise}\end{array} \right. .
$$
while its logarithm,
$$
\ln \pi_E(e) = \left\{ \begin{array}{ll} -\sum_{i=1}^n \ln(b_i-a_i), & \text{ if } a_i \leq e_i \leq b_i \text{ for } i=1,...,n \\
-\infty, &\text{otherwise}\end{array} \right. .
$$
##### Gaussian Errors
We can also assume that the NIST errors are Gaussian, in which case $\eta_i$ can be used to determine the standard deviations. Specifically, if we assume that the error range $[y_i-\eta_i y_i, y_i + \eta_i y_i]$ represents a 99.7\% confidence interval (corresponding to 3 standard deviations $\sigma_i$), we can compute $\sigma_i=\frac{2}{3}\eta_iy_i$. The densities are then given by
$$
\pi_{E_i}(e_i) = \frac{1}{\sqrt{2\pi}\sigma_i} \exp\left(-\frac{e_i^2}{2\sigma_i^2}\right).
$$
The joint distribution is
$$
\pi_E(e) = \prod_{i=1}^n \pi_{E_i}(e_i) = \prod_{i=1}^n \frac{1}{\sqrt{2\pi}\sigma_i} \exp\left(-\frac{e_i^2}{2\sigma_i^2}\right) = (2\pi)^{-n/2} \left(\prod_{i=1}^n \frac{1}{\sigma_i}\right) \exp\left(-\frac{1}{2}\sum_{i=1}^n \frac{e_i^2}{\sigma_i^2}\right)
$$
and its logarithm is
$$
\ln \pi_E(e) = -\frac{n}{2}\ln(2\pi) - \sum_{i=1}^n \ln(\sigma_i) - \frac{1}{2}\sum_{i=1}^n \left(\frac{e_i}{\sigma_i}\right)^2
$$
### The emcee package
Once we have the prior density and the likelihood function, we can use these to generate samples from the posterior density. This is usually achieved by means of a Monte Carlo Markov Chain (MCMC), which generates a random process (a Markov process) whose stationary (long term) distribution equals the desired posterior. The software library [emcee](http://dfm.io/emcee/current/) implements one form of the MCMC algorithm.
We first import the library:
```python
import emcee
import numpy as np
```
To test this package, we use a very simple example. Let $\lambda = [\lambda_1, \lambda_2]$ be two input parameters and consider the mapping
$$
f(\lambda) = \left[\begin{array}{c} \lambda_1^2 + \lambda_2^2 \\ \lambda_1 + 3\lambda_2 \end{array} \right].
$$
Here we define the mapping in python.
```python
def f(lmd):
"""
Forward Mapping
Inputs:
lmd: (2,) numpy array [lmd1, lmd2]
Outputs:
flmd: (2,) numpy array [lmd1^2 + lmd2^2, lmd1 + 3lmd2]
"""
lmd1, lmd2 = lmd
return np.array([lmd1**2 + lmd2**2, lmd1+3*lmd2])
```
Let's say the parameter's true value is $\lambda = [1,2]^T$. This results in an output $[5, 7]^T$, which we can use as our measurement. Suppose further that the measurements $Y_1, Y_2$ of the two output quantities of interest have associated errors, $E_i$, $i=1,2$ that are independent and normally distributed with $E_1 \sim N(0, 4)$ and $E_2 \sim N(0,1)$.
The `emcee` package requires logarithms of density functions as inputs. In our case, we can use the expresion for the Gaussian errors above to show that the likelihood function takes the form
$$
\pi_{Y|\Lambda}(y_{\text{obs}}|\lambda) = -\ln(2\pi) - \ln(4) -\ln(1) - \frac{1}{2} \left(\frac{5-f_1(\lambda)}{16}\right)^2 - \frac{1}{2}\left(\frac{7-f_2(\lambda)}{1}\right)^2
$$
This is how we define the log likelihood in Python.
```python
def ln_likelihood(lmd, y_obs, f):
"""
Returns the log-likelihood function for the given observations and forward mapping
Inputs:
lmd: (2,) numpy array - input parameter
y_obs: (2, ) numpy array - measurements
f: function, mapping from lambdas to output
Output: double, log(P(y_obs|lmd))
"""
f1, f2 = f(lmd)
return -np.log(8*np.pi) - 0.5*( (y_obs[0]-f1)**2/16 + (y_obs[1]-f2)**2/1 )
```
Let's specify the prior density for $\lambda$. We use a uniform prior for each component, with $\lambda_1 \sim U([0,3])$ and $\lambda_2 \sim U([1.5,2.5])$. The joint log-prior then takes the form
$$
\ln \pi_\Lambda(\lambda) = \left\{ \begin{array}{ll} -\ln(3), & \text{ if } \lambda \in [0,3]\times [1,3]\\
-\infty, & \text{otherwise} \end{array} \right.
$$
In Python it looks like this:
```python
def ln_prior(lmd):
"""
Compute the log prior density function at a parameter value lmd
"""
lmd1, lmd2 = lmd
if 0<=lmd1 and lmd1<=3 and 1.5<=lmd2 and lmd2<=2.5:
return -np.log(3)
else:
return -np.infty
#
# Try it out
#
# Point inside region
lmd = np.array([0.5,2.5])
print(ln_prior(lmd))
# Point outside region
lmd = np.array([-1,2.4])
print(ln_prior(lmd))
```
-1.0986122886681098
-inf
Recall that the posterior density is (up to a scaling constant) the product of the prior and the likelihood, so that the log posterior is the sum of their logs
```python
def ln_posterior(lmd, y_obs, f):
"""
Evaluate the log-posterior density function at a given lmd
Inputs:
lmd: input variable
y_obs: observed output
f: function, forward mapping
Output:
ln_prior + ln_likelihood
"""
return ln_prior(lmd) + ln_likelihood(lmd, y_obs, f)
```
We now run the MCMC algorithm
```python
# Specify the observation vector
y_obs = np.array([5,7])
# Specify the dimension of the input space and the number of starting points
n_dim, n_walkers = 2, 100
# Specify starting points for each Markov chain (in a tight ball around optimum)
pos = [np.array([1,2]) + 1e-4*np.random.randn(n_dim) for i in range(n_walkers)]
# Initialize the sampler
sampler = emcee.EnsembleSampler(n_walkers, n_dim, ln_posterior, args=(y_obs, f))
# Run the MCMC routine
sampler.run_mcmc(pos, 1000);
# The sampler.chain has shape (n_walkers, n_steps, n_dim) = (100, 1000, 2)
# Reshape into a (100'000,2) array of samples (but throw away initial sample -> (95'000,2)
samples = sampler.chain[:, 50:, :].reshape((-1, n_dim))
```
We plot the results using the package ```corner.py```
```python
import corner
```
```python
#
# Plot samples
#
corner.corner(samples, labels=["$\lambda_1$", "$\lambda_2$"], truths=[1, 2]);
```
## O6+
Here we try to estimate the $\lambda$ parameters for OVI+, in particular those corresponding to the 1s, 2s and 2p orbitals, i.e. $\lambda = [\lambda_{1s}, \lambda_{2s}, \lambda_{2p}]$. Our estimation is based on observations of various computable energies and/or A-values.
### Automating the Structure Calculations
The computation of each observable quantity for a single $\lambda$-value is achieved by means of an R-matrix structure calculation, encoded in the Perl script ```adas803.testern.pl```. Its inputs include, among others, an ```input.dat``` file in which the $\lambda$-values are stored.
To facilitate the evaluation of multiple such structure calculations corresponding to different $\lambda$-values, we have written a Python class ```LambdaPdf```, contained in the module ```scaling_parameters.py```. This class allows users to
- Run the structure calculations for a specific the $\lambda$-value, as well as specific observable quantities to be extracted from the ```adf04ic``` output file.
- Generate a linear interpolant, by running the structure calculations for every $\lambda$-point in a pre-specified grid, recording the resulting quantities of interest, and fitting a piecewise linear function to the data. The interpolant can be used as an approximation for the exact stucture calculation, leading to much faster sampling rates.
- Ultimately, this class is designed to store the statistical distribution of the lambda parameters.
### The NIST Data
The NIST data used for this calibration consists of energies 2-7 (to be found [here](https://physics.nist.gov/cgi-bin/ASD/energy1.pl)) and A-values 2,5, and 7 (to be found [here](https://physics.nist.gov/cgi-bin/ASD/lines1.pl?spectra=O6&limits_type=0&low_w=&upp_w=&unit=1&submit=Retrieve+Data&de=0&format=0&line_out=0&en_unit=0&output=0&bibrefs=1&page_size=15&show_obs_wl=1&show_calc_wl=1&unc_out=1&order_out=0&max_low_enrg=&show_av=2&max_upp_enrg=&tsb_value=0&min_str=&A_out=0&intens_out=on&max_str=&allowed_out=1&forbid_out=1&min_accur=&min_intens=&conf_out=on&term_out=on&enrg_out=on&J_out=on)). The NIST database entries for the energy levels list no error bounds. In our computations, we make them up by setting them to 'AAA'.
The NIST error ratings correspond to the following relative errors
| Rating | Relative Error |
| ---| ---|
|'AAA'| 0.003|
|'AA' | 0.01 |
|'A+' | 0.02 |
|'A' | 0.03 |
|'B+' | 0.07 |
|'B' | 0.1 |
|'C+' | 0.18 |
|'C' | 0.25 |
|'D+' | 0.4 |
|'D' | 0.5 |
|'E' | 0.5 |
In the code, each quantity of interest is initiated as a ```Qoi``` object, a class that store the NIST values, NIST errors, a search label for locating it in the output file, etc.
> __Example__ Here we initialize the A-value 2.
```python
#
# Import modules
#
import sys
sys.path.append('../src/')
from scaling_parameters import Qoi, LmdPdf
```
```python
#
# Initialize Quantity of Interest
#
a2 = Qoi(category='A-value', tag=2,
search_label=' 2 1',
nist_value=1.04e3, nist_rating='AA')
```
> __Example:__ We initialize a new $\lambda$-object with one output quantity: ```a2```.
```python
#
# Initialize lmd object
#
tags = ['1s', '2s', '2p'] # names
rng = np.array([[0.8, 1.2], [0.8, 1.2], [0.8, 1.2]]) # lower and upper bounds for each lambda
resolution = (2,2,2) # resolution of the grid in each direction
path_to_input = '/home/hans-werner/Dropbox/work/projects'+\
'/atomic_data_uncertainty/code/icft/o_6/'
output_qois = [a2]
lmd = LmdPdf(tags, rng, resolution, path_to_input, output_qois)
```
For the O6+ atom, all three $\lambda$-parameters are constrained within the interval $[0.8,1.2]$. We used a resolution of 20 sub-intervals in each direction, amounting to $20^3 = 8000$ forward calculations. We recorded this data and used it to construct a piecewise linear interpolant.
To prevent having to recompute the interpolant during every run, we use the ```pickle``` library, which allows us to store all sorts of objects. We load the saved $\lambda$-object as follows
```python
import pickle
with open('lmd_o6.pickle', 'rb') as f:
lmd = pickle.load(f)
```
The forward mapping
```python
def f_o6(point, lmd, qoi_indices):
"""
Returns the interpolated forward map
Inputs:
point: double, (3,) array of lambda values
qoi_indices: int, n-list of indices of output quantities
we want to use to estimate the lambda's
Outputs:
fi: double, (n,) array of outputs for the given input point
"""
# Compute the output for each listed output quantity
fv = [lmd.interpolants[i](point) for i in qoi_indices]
# Turn it into an array
fv = np.array(fv).ravel()
return fv
```
```python
# Display the output quantity names
for i in range(9):
print(lmd.qois[i].category, lmd.qois[i].tag, lmd.qois[i].nist_value,lmd.qois[i].nist_rating)
#
# Specify the indices of the desired output
#
# All
# qoi_indices = [i for i in range(9)]
# A-values
qoi_indices = [0,1,2,3,4,5]
#
# The observation vector
#
y_obs = np.array([lmd.qois[i].nist_value for i in qoi_indices])
```
Energy 2 4524640.0 AAA
Energy 3 4585620.0 AAA
Energy 4 4585680.0 AAA
Energy 5 4586230.0 AAA
Energy 6 4588380.0 AAA
Energy 7 4629201.0 AAA
A-value 2 1040.0 AA
A-value 5 331000.0 AA
A-value 7 3309000000000.0 AA
```python
a2.nist_value
```
1040.0
The Log likelihood
```python
def ln_likelihood_gauss(point, lmd, y_obs, f_o6, sgm, qoi_indices):
"""
"""
fv = f_o6(point, lmd, qoi_indices)
n = len(qoi_indices)
ln_p = -0.5*n*np.log(2*np.pi) - np.sum(np.log(sgm))
for i in range(n):
ln_p -= 0.5*((y_obs[i]-fv[i])/sgm[i])**2
return ln_p
#
# Get the standard deviations
#
sgm = []
rating_table = {'AAA': 0.003,
'AA' : 0.01,
'A+' : 0.02,
'A' : 0.03,
'B+' : 0.07,
'B' : 0.1,
'C+' : 0.18,
'C' : 0.25,
'D+' : 0.4,
'D' : 0.5,
'E' : 0.5}
for i in qoi_indices:
qoi = lmd.qois[i]
rel_error = rating_table[qoi.nist_rating]
# sgm.append(2/3*rel_error*qoi.nist_value)
sgm.append(rel_error*qoi.nist_value)
sgm = np.array(sgm)
#
# Check
#
point = np.array([0.8,0.9,1.1])
ln_likelihood_gauss(point, lmd, y_obs, f_o6, sgm, qoi_indices)
```
-63.3737760041114
```python
def ln_prior(point):
"""
Compute the log prior density function at a parameter value lmd
"""
x, y, z = point
if 0.8<=x and x<=1.2 and 0.8<=y and y<=1.2 and 0.8<=z and z<=1.2:
return -3*np.log(0.4)
else:
return -np.infty
```
```python
def ln_posterior(point, lmd, y_obs, f_o6, sgm, qoi_indices):
"""
Evaluate the log-posterior density function at a given lmd
Inputs:
lmd: input variable
y_obs: observed output
f: function, forward mapping
Output:
ln_prior + ln_likelihood
"""
lp = ln_prior(point)
if not np.isfinite(lp):
return -np.infty
else:
return lp + ln_likelihood_gauss(point, lmd, y_obs, f_o6, sgm, qoi_indices)
```
```python
# Specify the dimension of the input space and the number of starting points
n_dim, n_walkers = 3, 100
# Specify starting points for each Markov chain (in a tight ball around optimum)
pos = [np.array([1,1,1]) + 1e-4*np.random.randn(n_dim) for i in range(n_walkers)]
# Initialize the sampler
sampler = emcee.EnsembleSampler(n_walkers, n_dim, ln_posterior, args=(lmd, y_obs, f_o6, sgm, qoi_indices))
# Run the MCMC routine
sampler.run_mcmc(pos, 1000);
# The sampler.chain has shape (n_walkers, n_steps, n_dim) = (100, 1000, 2)
# Reshape into a (100'000,2) array of samples (but throw away initial sample -> (95'000,2)
samples = sampler.chain[:, 50:, :].reshape((-1, n_dim))
```
```python
#
# Plot samples
#
corner.corner(samples, labels=["$\lambda_{1s}$", "$\lambda_{2s}$", "$\lambda_{2p}$"]);
```
```python
```
|
lemma not_dvd_pderiv: fixes p :: "'a::{comm_semiring_1,semiring_no_zero_divisors,semiring_char_0} poly" assumes "degree p \<noteq> 0" shows "\<not> p dvd pderiv p"
|
[GOAL]
α : Type u_1
inst✝³ : CompleteLattice α
inst✝² : Group α
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
s✝ t s : Set α
⊢ sSup s⁻¹ = (sInf s)⁻¹
[PROOFSTEP]
rw [← image_inv, sSup_image]
[GOAL]
α : Type u_1
inst✝³ : CompleteLattice α
inst✝² : Group α
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
s✝ t s : Set α
⊢ ⨆ (a : α) (_ : a ∈ s), a⁻¹ = (sInf s)⁻¹
[PROOFSTEP]
exact ((OrderIso.inv α).map_sInf _).symm
[GOAL]
α : Type u_1
inst✝³ : CompleteLattice α
inst✝² : Group α
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
s✝ t s : Set α
⊢ sInf s⁻¹ = (sSup s)⁻¹
[PROOFSTEP]
rw [← image_inv, sInf_image]
[GOAL]
α : Type u_1
inst✝³ : CompleteLattice α
inst✝² : Group α
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
s✝ t s : Set α
⊢ ⨅ (a : α) (_ : a ∈ s), a⁻¹ = (sSup s)⁻¹
[PROOFSTEP]
exact ((OrderIso.inv α).map_sSup _).symm
[GOAL]
α : Type u_1
inst✝³ : CompleteLattice α
inst✝² : Group α
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
s t : Set α
⊢ sSup (s / t) = sSup s / sInf t
[PROOFSTEP]
simp_rw [div_eq_mul_inv, sSup_mul, sSup_inv]
[GOAL]
α : Type u_1
inst✝³ : CompleteLattice α
inst✝² : Group α
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
s t : Set α
⊢ sInf (s / t) = sInf s / sSup t
[PROOFSTEP]
simp_rw [div_eq_mul_inv, sInf_mul, sInf_inv]
[GOAL]
α : Type u_1
inst✝³ : ConditionallyCompleteLattice α
inst✝² : Group α
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
s t : Set α
hs₀ : Set.Nonempty s
hs₁ : BddBelow s
⊢ sSup s⁻¹ = (sInf s)⁻¹
[PROOFSTEP]
rw [← image_inv]
[GOAL]
α : Type u_1
inst✝³ : ConditionallyCompleteLattice α
inst✝² : Group α
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
s t : Set α
hs₀ : Set.Nonempty s
hs₁ : BddBelow s
⊢ sSup (Inv.inv '' s) = (sInf s)⁻¹
[PROOFSTEP]
exact ((OrderIso.inv α).map_csInf' hs₀ hs₁).symm
[GOAL]
α : Type u_1
inst✝³ : ConditionallyCompleteLattice α
inst✝² : Group α
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
s t : Set α
hs₀ : Set.Nonempty s
hs₁ : BddAbove s
⊢ sInf s⁻¹ = (sSup s)⁻¹
[PROOFSTEP]
rw [← image_inv]
[GOAL]
α : Type u_1
inst✝³ : ConditionallyCompleteLattice α
inst✝² : Group α
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
s t : Set α
hs₀ : Set.Nonempty s
hs₁ : BddAbove s
⊢ sInf (Inv.inv '' s) = (sSup s)⁻¹
[PROOFSTEP]
exact ((OrderIso.inv α).map_csSup' hs₀ hs₁).symm
[GOAL]
α : Type u_1
inst✝³ : ConditionallyCompleteLattice α
inst✝² : Group α
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
s t : Set α
hs₀ : Set.Nonempty s
hs₁ : BddAbove s
ht₀ : Set.Nonempty t
ht₁ : BddBelow t
⊢ sSup (s / t) = sSup s / sInf t
[PROOFSTEP]
rw [div_eq_mul_inv, csSup_mul hs₀ hs₁ ht₀.inv ht₁.inv, csSup_inv ht₀ ht₁, div_eq_mul_inv]
[GOAL]
α : Type u_1
inst✝³ : ConditionallyCompleteLattice α
inst✝² : Group α
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
s t : Set α
hs₀ : Set.Nonempty s
hs₁ : BddBelow s
ht₀ : Set.Nonempty t
ht₁ : BddAbove t
⊢ sInf (s / t) = sInf s / sSup t
[PROOFSTEP]
rw [div_eq_mul_inv, csInf_mul hs₀ hs₁ ht₀.inv ht₁.inv, csInf_inv ht₀ ht₁, div_eq_mul_inv]
[GOAL]
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
⊢ r • Ioo a b = Ioo (r • a) (r • b)
[PROOFSTEP]
ext x
[GOAL]
case h
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
⊢ x ∈ r • Ioo a b ↔ x ∈ Ioo (r • a) (r • b)
[PROOFSTEP]
simp only [mem_smul_set, smul_eq_mul, mem_Ioo]
[GOAL]
case h
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
⊢ (∃ y, (a < y ∧ y < b) ∧ r * y = x) ↔ r * a < x ∧ x < r * b
[PROOFSTEP]
constructor
[GOAL]
case h.mp
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
⊢ (∃ y, (a < y ∧ y < b) ∧ r * y = x) → r * a < x ∧ x < r * b
[PROOFSTEP]
rintro ⟨a, ⟨a_h_left_left, a_h_left_right⟩, rfl⟩
[GOAL]
case h.mp.intro.intro.intro
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a✝ b r : K
hr : 0 < r
a : K
a_h_left_left : a✝ < a
a_h_left_right : a < b
⊢ r * a✝ < r * a ∧ r * a < r * b
[PROOFSTEP]
constructor
[GOAL]
case h.mp.intro.intro.intro.left
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a✝ b r : K
hr : 0 < r
a : K
a_h_left_left : a✝ < a
a_h_left_right : a < b
⊢ r * a✝ < r * a
case h.mp.intro.intro.intro.right
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a✝ b r : K
hr : 0 < r
a : K
a_h_left_left : a✝ < a
a_h_left_right : a < b
⊢ r * a < r * b
[PROOFSTEP]
exact (mul_lt_mul_left hr).mpr a_h_left_left
[GOAL]
case h.mp.intro.intro.intro.right
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a✝ b r : K
hr : 0 < r
a : K
a_h_left_left : a✝ < a
a_h_left_right : a < b
⊢ r * a < r * b
[PROOFSTEP]
exact (mul_lt_mul_left hr).mpr a_h_left_right
[GOAL]
case h.mpr
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
⊢ r * a < x ∧ x < r * b → ∃ y, (a < y ∧ y < b) ∧ r * y = x
[PROOFSTEP]
rintro ⟨a_left, a_right⟩
[GOAL]
case h.mpr.intro
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
a_left : r * a < x
a_right : x < r * b
⊢ ∃ y, (a < y ∧ y < b) ∧ r * y = x
[PROOFSTEP]
use x / r
[GOAL]
case h
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
a_left : r * a < x
a_right : x < r * b
⊢ (a < x / r ∧ x / r < b) ∧ r * (x / r) = x
[PROOFSTEP]
refine' ⟨⟨(lt_div_iff' hr).mpr a_left, (div_lt_iff' hr).mpr a_right⟩, _⟩
[GOAL]
case h
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
a_left : r * a < x
a_right : x < r * b
⊢ r * (x / r) = x
[PROOFSTEP]
rw [mul_div_cancel' _ (ne_of_gt hr)]
[GOAL]
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
⊢ r • Icc a b = Icc (r • a) (r • b)
[PROOFSTEP]
ext x
[GOAL]
case h
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
⊢ x ∈ r • Icc a b ↔ x ∈ Icc (r • a) (r • b)
[PROOFSTEP]
simp only [mem_smul_set, smul_eq_mul, mem_Icc]
[GOAL]
case h
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
⊢ (∃ y, (a ≤ y ∧ y ≤ b) ∧ r * y = x) ↔ r * a ≤ x ∧ x ≤ r * b
[PROOFSTEP]
constructor
[GOAL]
case h.mp
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
⊢ (∃ y, (a ≤ y ∧ y ≤ b) ∧ r * y = x) → r * a ≤ x ∧ x ≤ r * b
[PROOFSTEP]
rintro ⟨a, ⟨a_h_left_left, a_h_left_right⟩, rfl⟩
[GOAL]
case h.mp.intro.intro.intro
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a✝ b r : K
hr : 0 < r
a : K
a_h_left_left : a✝ ≤ a
a_h_left_right : a ≤ b
⊢ r * a✝ ≤ r * a ∧ r * a ≤ r * b
[PROOFSTEP]
constructor
[GOAL]
case h.mp.intro.intro.intro.left
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a✝ b r : K
hr : 0 < r
a : K
a_h_left_left : a✝ ≤ a
a_h_left_right : a ≤ b
⊢ r * a✝ ≤ r * a
case h.mp.intro.intro.intro.right
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a✝ b r : K
hr : 0 < r
a : K
a_h_left_left : a✝ ≤ a
a_h_left_right : a ≤ b
⊢ r * a ≤ r * b
[PROOFSTEP]
exact (mul_le_mul_left hr).mpr a_h_left_left
[GOAL]
case h.mp.intro.intro.intro.right
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a✝ b r : K
hr : 0 < r
a : K
a_h_left_left : a✝ ≤ a
a_h_left_right : a ≤ b
⊢ r * a ≤ r * b
[PROOFSTEP]
exact (mul_le_mul_left hr).mpr a_h_left_right
[GOAL]
case h.mpr
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
⊢ r * a ≤ x ∧ x ≤ r * b → ∃ y, (a ≤ y ∧ y ≤ b) ∧ r * y = x
[PROOFSTEP]
rintro ⟨a_left, a_right⟩
[GOAL]
case h.mpr.intro
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
a_left : r * a ≤ x
a_right : x ≤ r * b
⊢ ∃ y, (a ≤ y ∧ y ≤ b) ∧ r * y = x
[PROOFSTEP]
use x / r
[GOAL]
case h
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
a_left : r * a ≤ x
a_right : x ≤ r * b
⊢ (a ≤ x / r ∧ x / r ≤ b) ∧ r * (x / r) = x
[PROOFSTEP]
refine' ⟨⟨(le_div_iff' hr).mpr a_left, (div_le_iff' hr).mpr a_right⟩, _⟩
[GOAL]
case h
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
a_left : r * a ≤ x
a_right : x ≤ r * b
⊢ r * (x / r) = x
[PROOFSTEP]
rw [mul_div_cancel' _ (ne_of_gt hr)]
[GOAL]
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
⊢ r • Ico a b = Ico (r • a) (r • b)
[PROOFSTEP]
ext x
[GOAL]
case h
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
⊢ x ∈ r • Ico a b ↔ x ∈ Ico (r • a) (r • b)
[PROOFSTEP]
simp only [mem_smul_set, smul_eq_mul, mem_Ico]
[GOAL]
case h
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
⊢ (∃ y, (a ≤ y ∧ y < b) ∧ r * y = x) ↔ r * a ≤ x ∧ x < r * b
[PROOFSTEP]
constructor
[GOAL]
case h.mp
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
⊢ (∃ y, (a ≤ y ∧ y < b) ∧ r * y = x) → r * a ≤ x ∧ x < r * b
[PROOFSTEP]
rintro ⟨a, ⟨a_h_left_left, a_h_left_right⟩, rfl⟩
[GOAL]
case h.mp.intro.intro.intro
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a✝ b r : K
hr : 0 < r
a : K
a_h_left_left : a✝ ≤ a
a_h_left_right : a < b
⊢ r * a✝ ≤ r * a ∧ r * a < r * b
[PROOFSTEP]
constructor
[GOAL]
case h.mp.intro.intro.intro.left
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a✝ b r : K
hr : 0 < r
a : K
a_h_left_left : a✝ ≤ a
a_h_left_right : a < b
⊢ r * a✝ ≤ r * a
case h.mp.intro.intro.intro.right
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a✝ b r : K
hr : 0 < r
a : K
a_h_left_left : a✝ ≤ a
a_h_left_right : a < b
⊢ r * a < r * b
[PROOFSTEP]
exact (mul_le_mul_left hr).mpr a_h_left_left
[GOAL]
case h.mp.intro.intro.intro.right
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a✝ b r : K
hr : 0 < r
a : K
a_h_left_left : a✝ ≤ a
a_h_left_right : a < b
⊢ r * a < r * b
[PROOFSTEP]
exact (mul_lt_mul_left hr).mpr a_h_left_right
[GOAL]
case h.mpr
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
⊢ r * a ≤ x ∧ x < r * b → ∃ y, (a ≤ y ∧ y < b) ∧ r * y = x
[PROOFSTEP]
rintro ⟨a_left, a_right⟩
[GOAL]
case h.mpr.intro
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
a_left : r * a ≤ x
a_right : x < r * b
⊢ ∃ y, (a ≤ y ∧ y < b) ∧ r * y = x
[PROOFSTEP]
use x / r
[GOAL]
case h
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
a_left : r * a ≤ x
a_right : x < r * b
⊢ (a ≤ x / r ∧ x / r < b) ∧ r * (x / r) = x
[PROOFSTEP]
refine' ⟨⟨(le_div_iff' hr).mpr a_left, (div_lt_iff' hr).mpr a_right⟩, _⟩
[GOAL]
case h
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
a_left : r * a ≤ x
a_right : x < r * b
⊢ r * (x / r) = x
[PROOFSTEP]
rw [mul_div_cancel' _ (ne_of_gt hr)]
[GOAL]
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
⊢ r • Ioc a b = Ioc (r • a) (r • b)
[PROOFSTEP]
ext x
[GOAL]
case h
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
⊢ x ∈ r • Ioc a b ↔ x ∈ Ioc (r • a) (r • b)
[PROOFSTEP]
simp only [mem_smul_set, smul_eq_mul, mem_Ioc]
[GOAL]
case h
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
⊢ (∃ y, (a < y ∧ y ≤ b) ∧ r * y = x) ↔ r * a < x ∧ x ≤ r * b
[PROOFSTEP]
constructor
[GOAL]
case h.mp
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
⊢ (∃ y, (a < y ∧ y ≤ b) ∧ r * y = x) → r * a < x ∧ x ≤ r * b
[PROOFSTEP]
rintro ⟨a, ⟨a_h_left_left, a_h_left_right⟩, rfl⟩
[GOAL]
case h.mp.intro.intro.intro
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a✝ b r : K
hr : 0 < r
a : K
a_h_left_left : a✝ < a
a_h_left_right : a ≤ b
⊢ r * a✝ < r * a ∧ r * a ≤ r * b
[PROOFSTEP]
constructor
[GOAL]
case h.mp.intro.intro.intro.left
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a✝ b r : K
hr : 0 < r
a : K
a_h_left_left : a✝ < a
a_h_left_right : a ≤ b
⊢ r * a✝ < r * a
case h.mp.intro.intro.intro.right
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a✝ b r : K
hr : 0 < r
a : K
a_h_left_left : a✝ < a
a_h_left_right : a ≤ b
⊢ r * a ≤ r * b
[PROOFSTEP]
exact (mul_lt_mul_left hr).mpr a_h_left_left
[GOAL]
case h.mp.intro.intro.intro.right
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a✝ b r : K
hr : 0 < r
a : K
a_h_left_left : a✝ < a
a_h_left_right : a ≤ b
⊢ r * a ≤ r * b
[PROOFSTEP]
exact (mul_le_mul_left hr).mpr a_h_left_right
[GOAL]
case h.mpr
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
⊢ r * a < x ∧ x ≤ r * b → ∃ y, (a < y ∧ y ≤ b) ∧ r * y = x
[PROOFSTEP]
rintro ⟨a_left, a_right⟩
[GOAL]
case h.mpr.intro
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
a_left : r * a < x
a_right : x ≤ r * b
⊢ ∃ y, (a < y ∧ y ≤ b) ∧ r * y = x
[PROOFSTEP]
use x / r
[GOAL]
case h
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
a_left : r * a < x
a_right : x ≤ r * b
⊢ (a < x / r ∧ x / r ≤ b) ∧ r * (x / r) = x
[PROOFSTEP]
refine' ⟨⟨(lt_div_iff' hr).mpr a_left, (div_le_iff' hr).mpr a_right⟩, _⟩
[GOAL]
case h
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
a_left : r * a < x
a_right : x ≤ r * b
⊢ r * (x / r) = x
[PROOFSTEP]
rw [mul_div_cancel' _ (ne_of_gt hr)]
[GOAL]
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
⊢ r • Ioi a = Ioi (r • a)
[PROOFSTEP]
ext x
[GOAL]
case h
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
⊢ x ∈ r • Ioi a ↔ x ∈ Ioi (r • a)
[PROOFSTEP]
simp only [mem_smul_set, smul_eq_mul, mem_Ioi]
[GOAL]
case h
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
⊢ (∃ y, a < y ∧ r * y = x) ↔ r * a < x
[PROOFSTEP]
constructor
[GOAL]
case h.mp
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
⊢ (∃ y, a < y ∧ r * y = x) → r * a < x
[PROOFSTEP]
rintro ⟨a_w, a_h_left, rfl⟩
[GOAL]
case h.mp.intro.intro
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
a_w : K
a_h_left : a < a_w
⊢ r * a < r * a_w
[PROOFSTEP]
exact (mul_lt_mul_left hr).mpr a_h_left
[GOAL]
case h.mpr
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
⊢ r * a < x → ∃ y, a < y ∧ r * y = x
[PROOFSTEP]
rintro h
[GOAL]
case h.mpr
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
h : r * a < x
⊢ ∃ y, a < y ∧ r * y = x
[PROOFSTEP]
use x / r
[GOAL]
case h
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
h : r * a < x
⊢ a < x / r ∧ r * (x / r) = x
[PROOFSTEP]
constructor
[GOAL]
case h.left
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
h : r * a < x
⊢ a < x / r
case h.right
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
h : r * a < x
⊢ r * (x / r) = x
[PROOFSTEP]
exact (lt_div_iff' hr).mpr h
[GOAL]
case h.right
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
h : r * a < x
⊢ r * (x / r) = x
[PROOFSTEP]
exact mul_div_cancel' _ (ne_of_gt hr)
[GOAL]
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
⊢ r • Iio a = Iio (r • a)
[PROOFSTEP]
ext x
[GOAL]
case h
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
⊢ x ∈ r • Iio a ↔ x ∈ Iio (r • a)
[PROOFSTEP]
simp only [mem_smul_set, smul_eq_mul, mem_Iio]
[GOAL]
case h
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
⊢ (∃ y, y < a ∧ r * y = x) ↔ x < r * a
[PROOFSTEP]
constructor
[GOAL]
case h.mp
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
⊢ (∃ y, y < a ∧ r * y = x) → x < r * a
[PROOFSTEP]
rintro ⟨a_w, a_h_left, rfl⟩
[GOAL]
case h.mp.intro.intro
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
a_w : K
a_h_left : a_w < a
⊢ r * a_w < r * a
[PROOFSTEP]
exact (mul_lt_mul_left hr).mpr a_h_left
[GOAL]
case h.mpr
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
⊢ x < r * a → ∃ y, y < a ∧ r * y = x
[PROOFSTEP]
rintro h
[GOAL]
case h.mpr
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
h : x < r * a
⊢ ∃ y, y < a ∧ r * y = x
[PROOFSTEP]
use x / r
[GOAL]
case h
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
h : x < r * a
⊢ x / r < a ∧ r * (x / r) = x
[PROOFSTEP]
constructor
[GOAL]
case h.left
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
h : x < r * a
⊢ x / r < a
case h.right
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
h : x < r * a
⊢ r * (x / r) = x
[PROOFSTEP]
exact (div_lt_iff' hr).mpr h
[GOAL]
case h.right
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
h : x < r * a
⊢ r * (x / r) = x
[PROOFSTEP]
exact mul_div_cancel' _ (ne_of_gt hr)
[GOAL]
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
⊢ r • Ici a = Ici (r • a)
[PROOFSTEP]
ext x
[GOAL]
case h
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
⊢ x ∈ r • Ici a ↔ x ∈ Ici (r • a)
[PROOFSTEP]
simp only [mem_smul_set, smul_eq_mul, mem_Ioi]
[GOAL]
case h
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
⊢ (∃ y, y ∈ Ici a ∧ r * y = x) ↔ x ∈ Ici (r * a)
[PROOFSTEP]
constructor
[GOAL]
case h.mp
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
⊢ (∃ y, y ∈ Ici a ∧ r * y = x) → x ∈ Ici (r * a)
[PROOFSTEP]
rintro ⟨a_w, a_h_left, rfl⟩
[GOAL]
case h.mp.intro.intro
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
a_w : K
a_h_left : a_w ∈ Ici a
⊢ r * a_w ∈ Ici (r * a)
[PROOFSTEP]
exact (mul_le_mul_left hr).mpr a_h_left
[GOAL]
case h.mpr
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
⊢ x ∈ Ici (r * a) → ∃ y, y ∈ Ici a ∧ r * y = x
[PROOFSTEP]
rintro h
[GOAL]
case h.mpr
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
h : x ∈ Ici (r * a)
⊢ ∃ y, y ∈ Ici a ∧ r * y = x
[PROOFSTEP]
use x / r
[GOAL]
case h
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
h : x ∈ Ici (r * a)
⊢ x / r ∈ Ici a ∧ r * (x / r) = x
[PROOFSTEP]
constructor
[GOAL]
case h.left
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
h : x ∈ Ici (r * a)
⊢ x / r ∈ Ici a
case h.right
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
h : x ∈ Ici (r * a)
⊢ r * (x / r) = x
[PROOFSTEP]
exact (le_div_iff' hr).mpr h
[GOAL]
case h.right
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
h : x ∈ Ici (r * a)
⊢ r * (x / r) = x
[PROOFSTEP]
exact mul_div_cancel' _ (ne_of_gt hr)
[GOAL]
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
⊢ r • Iic a = Iic (r • a)
[PROOFSTEP]
ext x
[GOAL]
case h
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
⊢ x ∈ r • Iic a ↔ x ∈ Iic (r • a)
[PROOFSTEP]
simp only [mem_smul_set, smul_eq_mul, mem_Iio]
[GOAL]
case h
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
⊢ (∃ y, y ∈ Iic a ∧ r * y = x) ↔ x ∈ Iic (r * a)
[PROOFSTEP]
constructor
[GOAL]
case h.mp
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
⊢ (∃ y, y ∈ Iic a ∧ r * y = x) → x ∈ Iic (r * a)
[PROOFSTEP]
rintro ⟨a_w, a_h_left, rfl⟩
[GOAL]
case h.mp.intro.intro
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
a_w : K
a_h_left : a_w ∈ Iic a
⊢ r * a_w ∈ Iic (r * a)
[PROOFSTEP]
exact (mul_le_mul_left hr).mpr a_h_left
[GOAL]
case h.mpr
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
⊢ x ∈ Iic (r * a) → ∃ y, y ∈ Iic a ∧ r * y = x
[PROOFSTEP]
rintro h
[GOAL]
case h.mpr
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
h : x ∈ Iic (r * a)
⊢ ∃ y, y ∈ Iic a ∧ r * y = x
[PROOFSTEP]
use x / r
[GOAL]
case h
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
h : x ∈ Iic (r * a)
⊢ x / r ∈ Iic a ∧ r * (x / r) = x
[PROOFSTEP]
constructor
[GOAL]
case h.left
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
h : x ∈ Iic (r * a)
⊢ x / r ∈ Iic a
case h.right
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
h : x ∈ Iic (r * a)
⊢ r * (x / r) = x
[PROOFSTEP]
exact (div_le_iff' hr).mpr h
[GOAL]
case h.right
α : Type u_1
K : Type u_2
inst✝ : LinearOrderedField K
a b r : K
hr : 0 < r
x : K
h : x ∈ Iic (r * a)
⊢ r * (x / r) = x
[PROOFSTEP]
exact mul_div_cancel' _ (ne_of_gt hr)
|
theory Tactic_Inline
imports RHL_Typed Hoare_Tactics Procs_Typed Legacy_Char
begin
(*definition "HIDDEN_EQ = (=)"
lemma HIDDEN_EQ_refl: "HIDDEN_EQ x x" unfolding HIDDEN_EQ_def ..
lemma HIDDEN_EQ_I': "HIDDEN_EQ a b \<Longrightarrow> a==b" by (simp add: HIDDEN_EQ_def)
lemma HIDDEN_EQ_ok:
shows "HIDDEN_EQ procargvars_empty procargvars_empty"
and "HIDDEN_EQ v w \<Longrightarrow> HIDDEN_EQ (procargvars_add (LVariable n) v) (procargvars_add (LVariable n) w)"
and "HIDDEN_EQ v w \<Longrightarrow> HIDDEN_EQ (procargvars_add (Variable n) v) (procargvars_add (Variable n) w)"
unfolding HIDDEN_EQ_def by simp_all *)
(* lemma obs_eq'_rename_variables_proc:
assumes "obs_eq' V (callproc x (rename_local_variables_proc ren prc) args) body"
shows "obs_eq' V (callproc x prc args) body"
using assms unfolding obs_eq'_def obs_eq_def rhoare_def denotation_callproc_rename_local_variables_proc .
thm obs_eq'_rename_variables_proc[of _ _ "[]"]
*)
locale callproc_conditions_simp begin
(* TODO remove ? *)
definition "filter_global' == filter vu_global"
definition "filter_local' == filter (\<lambda>x. \<not> vu_global x)"
lemma local_variable_name_renaming_nil: "local_variable_name_renaming [] ` x == x"
unfolding local_variable_name_renaming_def[THEN ext] by auto
(* lemma local_variable_name_renaming2: "local_variable_name_renaming (a#b) ` X == local_variable_name_renaming b ` local_variable_name_renaming1 a ` X"
unfolding local_variable_name_renaming_def
by (simp add: o_def image_image) *)
lemma local_variable_name_renaming_union: "local_variable_name_renaming (a#b) ` (A \<union> B) == local_variable_name_renaming (a#b) ` A \<union> local_variable_name_renaming (a#b) ` B"
by (simp add: image_Un)
lemma local_variable_name_renaming_insert: "local_variable_name_renaming (a#b) ` (insert x X) == insert (local_variable_name_renaming (a#b) x) (local_variable_name_renaming (a#b) ` X)"
by simp
lemma local_variable_name_renaming_set: "local_variable_name_renaming (a#b) ` (set X) == set (map (local_variable_name_renaming (a#b)) X)"
by simp
lemma local_variable_name_renaming_cons: "map (local_variable_name_renaming (a#b)) (x#X) == local_variable_name_renaming (a#b) x # map (local_variable_name_renaming (a#b)) X"
by simp
lemma local_variable_name_renaming_nil2: "map (local_variable_name_renaming R) [] == []"
by simp
lemma callproc_goal4: "local_variable_name_renaming ren ` filter_global X \<subseteq> Y \<union> Collect vu_global"
unfolding filter_global_def by auto
(*lemma callproc_conditions_simp1b: "local_variable_name_renaming ren ` filter_global X \<subseteq> Y \<union> Collect vu_global == True"
apply (rule eq_reflection) unfolding filter_global_def by auto
lemma callproc_conditions_simp1c: "local_variable_name_renaming1 ren ` filter_global X \<subseteq> Y \<union> Collect vu_global == True"
apply (rule eq_reflection)
by (auto simp: filter_global_def local_variable_name_renaming1_fix_globals)*)
lemma filter_global': "filter_global (set X) == set (filter_global' X)"
unfolding filter_global_def filter_global'_def by simp
lemma filter_local': "filter_local (set X) == set (filter_local' X)"
unfolding filter_local_def filter_local'_def by simp
lemma filter_global'_nil: "filter_global' [] == []"
unfolding filter_global'_def by simp
lemma filter_global_empty: "filter_global {} == {}"
unfolding filter_global_def by simp
lemma filter_global'_cons1: "filter_global' (mk_variable_untyped (Variable n :: 'a::prog_type variable) # X) ==
mk_variable_untyped (Variable n :: 'a variable) # filter_global' X"
unfolding filter_global'_def by auto
lemma filter_global_insert1: "filter_global (insert (mk_variable_untyped (Variable n :: 'a::prog_type variable)) X) ==
insert (mk_variable_untyped (Variable n :: 'a variable)) (filter_global X)"
apply (rule eq_reflection) unfolding filter_global_def by auto
lemma filter_global'_cons2: "filter_global' (mk_variable_untyped (LVariable n :: 'a::prog_type variable) # X) ==
filter_global' X"
unfolding filter_global'_def by auto
lemma filter_global_insert2: "filter_global (insert (mk_variable_untyped (LVariable n :: 'a::prog_type variable)) X) ==
filter_global X"
apply (rule eq_reflection) unfolding filter_global_def by auto
lemma filter_local'_nil: "filter_local' [] == []"
unfolding filter_local'_def by simp
(* lemma filter_local_empty: "filter_local {} == {}"
unfolding filter_local_def by simp *)
lemma filter_local'_cons1: "filter_local' (mk_variable_untyped (LVariable n :: 'a::prog_type variable) # X) ==
mk_variable_untyped (LVariable n :: 'a variable) # filter_local' X"
unfolding filter_local'_def by auto
(* lemma filter_local_insert1: "filter_local (insert (mk_variable_untyped (LVariable n :: 'a::prog_type variable)) X) ==
insert (mk_variable_untyped (LVariable n :: 'a variable)) (filter_local X)"
unfolding filter_local_def apply auto
by (smt Collect_cong LVariable_local insert_Collect) *)
lemma filter_local'_cons2: "filter_local' (mk_variable_untyped (Variable n :: 'a::prog_type variable) # X) ==
filter_local' X"
unfolding filter_local'_def by auto
(* lemma filter_local_insert2: "filter_local (insert (mk_variable_untyped (Variable n :: 'a::prog_type variable)) X) ==
filter_local X"
unfolding filter_local_def by auto *)
lemma filter_local_union: "filter_local (X \<union> Y) == filter_local X \<union> filter_local Y"
apply (rule eq_reflection) unfolding filter_local_def by auto
lemma filter_local_insert1: "filter_local (insert (mk_variable_untyped (LVariable n :: 'a::prog_type variable)) X) ==
insert (mk_variable_untyped (LVariable n :: 'a::prog_type variable)) (filter_local X)"
apply (rule eq_reflection) unfolding filter_local_def by auto
lemma filter_local_insert2: "filter_local (insert (mk_variable_untyped (Variable n)) X) == filter_local X"
apply (rule eq_reflection) unfolding filter_local_def by auto
lemma filter_local_empty: "filter_local {} == {}"
apply (rule eq_reflection) unfolding filter_local_def by auto
lemma local_variable_name_renaming_same:
"local_variable_name_renaming ((a,b)#X) (mk_variable_untyped (LVariable a :: 'a::prog_type variable))
== local_variable_name_renaming X (mk_variable_untyped (LVariable b :: 'a variable))"
by (subst Rep_rename_local_variables_var[symmetric], simp)
lemma local_variable_name_renaming_id:
"local_variable_name_renaming [] x == x"
unfolding local_variable_name_renaming_def by simp
lemma local_variable_name_renaming_notsame:
assumes "a\<noteq>x" and "b\<noteq>x"
shows "local_variable_name_renaming ((a,b)#X) (mk_variable_untyped (LVariable x :: 'a::prog_type variable))
== local_variable_name_renaming X (mk_variable_untyped (LVariable x :: 'a variable))"
apply (subst Rep_rename_local_variables_var[symmetric])
apply (subst rename_local_variables_var_notsame)
using assms by simp_all
(* lemmas callproc_conditions_simp =
filter_global' filter_global'_cons1 filter_global'_cons2
filter_global'_nil filter_local_union filter_local' vars_variable_pattern[THEN eq_reflection]
filter_local'_cons1 filter_local'_cons2 filter_local'_nil filter_local_insert1
filter_local_empty local_variable_name_renaming_insert local_variable_name_renaming_union
local_variable_name_renaming_nil local_variable_name_renaming_same image_empty[THEN eq_reflection]
vars_unit_pattern[THEN eq_reflection] vars_pair_pattern[THEN eq_reflection]
append_Cons[THEN eq_reflection] append_Nil[THEN eq_reflection]
rename_local_variables_pattern_id[THEN eq_reflection] local_variable_name_renaming_id
local_variable_name_renaming_set local_variable_name_renaming_cons
local_variable_name_renaming_nil2 local_variable_name_renaming_notsame
*)
end
ML_file "tactic_inline.ML"
method_setup inline = {*
Args.term >> (fn proc => fn ctx => (METHOD (fn facts => Tactic_Inline.inline_tac ctx facts proc 1)))
*} "inlines procedure body"
end
|
\section{Collocation}
A \textit{collocation\index{collocation}} is an expression consisting of two or more words, where one is main and the other are subordinative. \cite{colloc} Usually, collocation consists from 2 to 5 words. Subordinative words are connected to the main one by several types of links: coherence, management and adjunction.
\underline{Coherence\index{collocation!coherence}} between the main and the subordinative words lies in corellation of grammar forms. That means the subordinative word should correspond with the main one while the latter changes (i.e. case or gender). Thus, coherent link introduces a strong connection between the two words, so they change both when a primary link is established and when the word changes (declension or conjugation).
\textbf{Examples:}
- \textit{Lěpa žena - Lěpu ženu - Lěpoǐ ženě} (Beautiful woman in Nominative, Accusative and Dative)
- \textit{Sïlen věter - Sïlnoga větra - Sïlnomu větru} (Strong wind in Nominative, Genitive and Dative)
\underline{Management\index{collocation!management}} link has a weaker connection between the words. The word with a management link has a determined grammar form. So the subordinative word should be changed once when is connected to the main word and then it is not changed while the main word is declining or conjugating. The primary word form is managed by the main word within a rule-case. It can be of a determined case or a preposition to be used with.
\textbf{Examples:}
- \textit{Věnec života - Věnca života - Věncom života} (The culmination of life in Nominative, Genitive and Dative)
- \textit{Kniga o važlivom - Knigy o važlivom - V knigji o važlivom} (A book of something important in Nominative, Genitive and Locative)
\underline{Adjunction\index{collocation!adjunction}} means we simply add a subordinative word to the main one to form a collocation. We usually speak about this type while linking when we have immutable words.
\textbf{Examples:}
- \textit{Glųboko spati} (To have a deep sleep)
- \textit{Hoditi dalïko} (To walk far away)
Using proper cases in a collocation has a great importance for constructing an euphonious and understandable sentence. However, we cannot define all the cases of such links now, so you can feel-in the language to achieve this. If you are Slavic, simply try to use those cases or constructions that you use in your native language. If you are not, try to use English logic that is close to Novoslovnica in a number of cases.
|
The coefficient of $x^0$ in the product of a list of polynomials is the product of the coefficients of $x^0$ in each polynomial.
|
function engine = set_fields(engine, varargin)
% SET_FIELDS Set the fields for a generic engine
% engine = set_fields(engine, name/value pairs)
%
% e.g., engine = set_fields(engine, 'maximize', 1)
args = varargin;
nargs = length(args);
for i=1:2:nargs
switch args{i},
case 'maximize',
engine.maximize = args{i+1};
engine.jtree_engine = set_fields(engine.jtree_engine, 'maximize', args{i+1});
engine.jtree_engine1 = set_fields(engine.jtree_engine1, 'maximize', args{i+1});
end
end
|
Laboratory Furnace,Silicon Carbide (SiC),Muffle Furnace,Nanyang Xinyu Electric Components Co., Ltd.
Nanyang Xinyu Electric Components Co., Ltd. is located in Henan Nanyang National Economic & Technological Development Area. Our company has convenient transportation. Being an ISO9001 certified enterprise, our company owns advanced facilities and competent and excellent products. Our company is a new and high-tech enterprise engaged in developing, manufacturing and selling Sic heating elements and titanic products. The leading "Xinyu"-brand products enjoy a high reputation for the excellent quality at home and abroad. Our company mainly manufactures the products silicon carbide (SIC) heating elements and lab furnaces. With the advantages in technology, equipment, scale and management, our company is in the leading position of this trade. Owing to the keen consciousness of quality and commercial reputation, our products are exported to Germany, Japan, Korea, Ukraine and Iran. Products Range: 1). Muffle Furnaces, Chamber Furnaces, and Laboratory Furnaces 2). Tube Furnaces and Vacuum Tube Furnaces 3). Atmosphere Furnaces, Vacuum Furnaces and Producing Furnaces 4). Silicon Carbide Heating Elements and SIC Heating Elements 5). Molybdenum Disilicide Heating Elements and MoSi2 Heating Elements 6). Ceramic Fiber and Refractory Fiber 7). Thermocouples, SCR (Silicon Controlled Rectifiers) and Programmable Temperature Controllers 8). Alumina Tubes, Alumina Crucible, Zirconia Crucible and Magnesia Crucible 9). Molybdenum Sheets, Molybdenum Rods and Molybdenum Electrodes Our quality policy is "first-class Quality, first-class technology and sincere service to make customers satisfy". Our eternal faith is "living on quality, reputation on honesty, development on mutual benefit". We are looking forward to offering our best services to our friends from at home and abroad.
|
theory Exp
imports Main
begin
fun option_bind :: "'a option \<Rightarrow> ( 'a \<Rightarrow> 'b option ) \<Rightarrow> 'b option" where
"option_bind None _ = None" |
"option_bind ( Some a ) f = f a"
definition option_sum :: "int option \<Rightarrow> int option \<Rightarrow> int option" where
"(option_sum Mx My) = option_bind Mx (\<lambda>x . option_bind My (\<lambda> y . Some (x+y) ))"
definition option_mul :: "int option \<Rightarrow> int option \<Rightarrow> int option" where
"(option_mul Mx My) = option_bind Mx (\<lambda>x . option_bind My (\<lambda> y . Some (x*y) ))"
lemma [simp]: "option_mul (Some x) (Some y) = Some (x * y)"
apply ( simp add: option_mul_def )
done
datatype 'a exp =
Var 'a |
Cst int |
Add "'a exp" "'a exp" |
Mul "'a exp" "'a exp"
fun eval :: "'a exp \<Rightarrow> ('a \<Rightarrow> int option) \<Rightarrow> int option" where
"eval ( Var i ) v = ( v i )" |
"eval ( Cst x ) v = Some x" |
"eval ( Add e0 e1 ) v = option_sum ( eval e0 v ) ( eval e1 v )" |
"eval ( Mul e0 e1 ) v = option_mul ( eval e0 v ) ( eval e1 v )"
value "( Mult ( Add ( Var 0 ) ( Cst 0 ) ) Cst 3 )"
value "\<lambda> x. ( if x=0 then Some 2 else None )"
value "(eval
( Mult ( Add ( Var 0 ) ( Cst 0 ) ) Cst 3 )
(\<lambda> x. ( if x=0 then Some 3 else None )))"
fun evalp :: "int list \<Rightarrow> int \<Rightarrow> int" where
"evalp [] _ = 0" |
"evalp (c0 # cs) x = c0 + x * ( evalp cs x )"
fun sump :: "int list \<Rightarrow> int list \<Rightarrow> int list" where
"sump [] l1 = l1" |
"sump l0 [] = l0" |
"sump (x#xs) (y#ys) = (x+y) # ( sump xs ys )"
lemma [simp]: "evalp (sump xs ys ) n = evalp xs n + evalp ys n"
apply ( induction xs ys rule: sump.induct )
apply ( auto simp add: algebra_simps)
done
fun cmulp :: "int \<Rightarrow> int list \<Rightarrow> int list" where
"cmulp c [] = []" |
"cmulp c (p # ps) = (c*p) # (cmulp c ps)"
lemma [simp]: "evalp ( cmulp c ps ) n = c * evalp ps n"
apply ( induction ps )
apply ( auto simp add: algebra_simps )
done
fun mulp :: "int list \<Rightarrow> int list \<Rightarrow> int list" where
"mulp [] p = []" |
"mulp (a # as) p = sump (cmulp a p) (0 # (mulp as p))"
lemma [simp]: "evalp ( mulp xs ys ) n = evalp xs n * evalp ys n"
apply ( induction xs )
apply ( auto simp add: algebra_simps)
done
fun coeffs :: "unit exp \<Rightarrow> int list" where
"coeffs (Var ()) = [0, 1]" |
"coeffs (Cst c ) = [c]" |
"coeffs (Add e0 e1) = sump (coeffs e0) (coeffs e1)" |
"coeffs (Mul e0 e1) = mulp (coeffs e0) (coeffs e1)"
theorem "eval e (\<lambda> x . (Some n)) = Some ( evalp ( coeffs e ) n)"
apply ( induction e arbitrary:n )
apply ( auto simp add: algebra_simps )
done
end
|
[STATEMENT]
lemma snd_vimage_eq_Times: "snd -` S = UNIV \<times> S"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. snd -` S = UNIV \<times> S
[PROOF STEP]
by auto
|
/-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.multiset.nodup
/-!
# Erasing duplicates in a multiset.
-/
namespace multiset
open list
variables {α β : Type*} [decidable_eq α]
/-! ### dedup -/
/-- `dedup s` removes duplicates from `s`, yielding a `nodup` multiset. -/
def dedup (s : multiset α) : multiset α :=
quot.lift_on s (λ l, (l.dedup : multiset α))
(λ s t p, quot.sound p.dedup)
@[simp] theorem coe_dedup (l : list α) : @dedup α _ l = l.dedup := rfl
@[simp] theorem dedup_zero : @dedup α _ 0 = 0 := rfl
@[simp] theorem mem_dedup {a : α} {s : multiset α} : a ∈ dedup s ↔ a ∈ s :=
quot.induction_on s $ λ l, mem_dedup
@[simp] theorem dedup_cons_of_mem {a : α} {s : multiset α} : a ∈ s →
dedup (a ::ₘ s) = dedup s :=
quot.induction_on s $ λ l m, @congr_arg _ _ _ _ coe $ dedup_cons_of_mem m
@[simp] theorem dedup_cons_of_not_mem {a : α} {s : multiset α} : a ∉ s →
dedup (a ::ₘ s) = a ::ₘ dedup s :=
quot.induction_on s $ λ l m, congr_arg coe $ dedup_cons_of_not_mem m
theorem dedup_le (s : multiset α) : dedup s ≤ s :=
quot.induction_on s $ λ l, (dedup_sublist _).subperm
theorem dedup_subset (s : multiset α) : dedup s ⊆ s :=
subset_of_le $ dedup_le _
theorem subset_dedup (s : multiset α) : s ⊆ dedup s :=
λ a, mem_dedup.2
@[simp] theorem dedup_subset' {s t : multiset α} : dedup s ⊆ t ↔ s ⊆ t :=
⟨subset.trans (subset_dedup _), subset.trans (dedup_subset _)⟩
@[simp] theorem subset_dedup' {s t : multiset α} : s ⊆ dedup t ↔ s ⊆ t :=
⟨λ h, subset.trans h (dedup_subset _), λ h, subset.trans h (subset_dedup _)⟩
@[simp] theorem nodup_dedup (s : multiset α) : nodup (dedup s) :=
quot.induction_on s nodup_dedup
theorem dedup_eq_self {s : multiset α} : dedup s = s ↔ nodup s :=
⟨λ e, e ▸ nodup_dedup s,
quot.induction_on s $ λ l h, congr_arg coe h.dedup⟩
alias dedup_eq_self ↔ _ nodup.dedup
theorem dedup_eq_zero {s : multiset α} : dedup s = 0 ↔ s = 0 :=
⟨λ h, eq_zero_of_subset_zero $ h ▸ subset_dedup _,
λ h, h.symm ▸ dedup_zero⟩
@[simp] theorem dedup_singleton {a : α} : dedup ({a} : multiset α) = {a} :=
(nodup_singleton _).dedup
theorem le_dedup {s t : multiset α} : s ≤ dedup t ↔ s ≤ t ∧ nodup s :=
⟨λ h, ⟨le_trans h (dedup_le _), nodup_of_le h (nodup_dedup _)⟩,
λ ⟨l, d⟩, (le_iff_subset d).2 $ subset.trans (subset_of_le l) (subset_dedup _)⟩
theorem dedup_ext {s t : multiset α} : dedup s = dedup t ↔ ∀ a, a ∈ s ↔ a ∈ t :=
by simp [nodup.ext]
theorem dedup_map_dedup_eq [decidable_eq β] (f : α → β) (s : multiset α) :
dedup (map f (dedup s)) = dedup (map f s) := by simp [dedup_ext]
@[simp]
lemma dedup_nsmul {s : multiset α} {n : ℕ} (h0 : n ≠ 0) :
(n • s).dedup = s.dedup :=
begin
ext a,
by_cases h : a ∈ s;
simp [h,h0]
end
lemma nodup.le_dedup_iff_le {s t : multiset α} (hno : s.nodup) :
s ≤ t.dedup ↔ s ≤ t :=
by simp [le_dedup, hno]
end multiset
lemma multiset.nodup.le_nsmul_iff_le {α : Type*} {s t : multiset α}
{n : ℕ} (h : s.nodup) (hn : n ≠ 0) :
s ≤ n • t ↔ s ≤ t :=
begin
classical,
rw [← h.le_dedup_iff_le, iff.comm, ← h.le_dedup_iff_le],
simp [hn]
end
|
lemma [field_simps]: "c \<noteq> 0 \<Longrightarrow> a = b /\<^sub>R c \<longleftrightarrow> c *\<^sub>R a = b" "c \<noteq> 0 \<Longrightarrow> b /\<^sub>R c = a \<longleftrightarrow> b = c *\<^sub>R a" "c \<noteq> 0 \<Longrightarrow> a + b /\<^sub>R c = (c *\<^sub>R a + b) /\<^sub>R c" "c \<noteq> 0 \<Longrightarrow> a /\<^sub>R c + b = (a + c *\<^sub>R b) /\<^sub>R c" "c \<noteq> 0 \<Longrightarrow> a - b /\<^sub>R c = (c *\<^sub>R a - b) /\<^sub>R c" "c \<noteq> 0 \<Longrightarrow> a /\<^sub>R c - b = (a - c *\<^sub>R b) /\<^sub>R c" "c \<noteq> 0 \<Longrightarrow> - (a /\<^sub>R c) + b = (- a + c *\<^sub>R b) /\<^sub>R c" "c \<noteq> 0 \<Longrightarrow> - (a /\<^sub>R c) - b = (- a - c *\<^sub>R b) /\<^sub>R c" for a b :: "'a :: real_vector"
|
\section*{Appendix 1: Assessment matrix}
\begin{tabular}{|p{2cm}|p{4cm}|}
\hline
\glssymbol{lo} & Dublin descriptors \\
\hline
\glssymbol{abs} & 1, 2, 4\\
\hline
\glssymbol{learn}& 1, 4, 5\\
\hline
\glssymbol{enc} & 1, 2, 4\\
\hline
\glssymbol{type} & 1, 2, 4\\
\hline
\glssymbol{bhf} & 1, 2, 4\\
\hline
\end{tabular}
\vspace{1cm}
Dublin-descriptors:
\begin{enumerate}
\item Knowledge and understanding
\item Applying knowledge and understanding
\item Making judgments
\item Communication
\item Learning skills
\end{enumerate}
|
/-
Copyright (c) 2020 Kevin Lacker. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Lacker
-/
import algebra.group_power.identities
import data.int.nat_prime
import tactic.linarith
import tactic.norm_cast
import data.set.finite
/-!
# IMO 1969 Q1
Prove that there are infinitely many natural numbers $a$ with the following property:
the number $z = n^4 + a$ is not prime for any natural number $n$.
-/
open int nat
namespace imo1969_q1
/-- `good_nats` is the set of natural numbers satisfying the condition in the problem
statement, namely the `a : ℕ` such that `n^4 + a` is not prime for any `n : ℕ`. -/
def good_nats : set ℕ := {a : ℕ | ∀ n : ℕ, ¬ nat.prime (n^4 + a)}
/-!
The key to the solution is that you can factor $z$ into the product of two polynomials,
if $a = 4*m^4$. This is Sophie Germain's identity, called `pow_four_add_four_mul_pow_four`
in mathlib.
-/
lemma factorization {m n : ℤ} : ((n - m)^2 + m^2) * ((n + m)^2 + m^2) = n^4 + 4*m^4 :=
pow_four_add_four_mul_pow_four.symm
/-!
To show that the product is not prime, we need to show each of the factors is at least 2,
which `nlinarith` can solve since they are each expressed as a sum of squares.
-/
lemma left_factor_large {m : ℤ} (n : ℤ) (h : 1 < m) : 1 < ((n - m)^2 + m^2) := by nlinarith
lemma right_factor_large {m : ℤ} (n : ℤ) (h : 1 < m) : 1 < ((n + m)^2 + m^2) := by nlinarith
/-!
The factorization is over the integers, but we need the nonprimality over the natural numbers.
-/
lemma int_large {m : ℤ} (h : 1 < m) : 1 < m.nat_abs :=
by exact_mod_cast lt_of_lt_of_le h le_nat_abs
lemma not_prime_of_int_mul' {m n : ℤ} {c : ℕ}
(hm : 1 < m) (hn : 1 < n) (hc : m*n = (c : ℤ)) : ¬ nat.prime c :=
not_prime_of_int_mul (int_large hm) (int_large hn) hc
/-- Every natural number of the form `n^4 + 4*m^4` is not prime. -/
lemma polynomial_not_prime {m : ℕ} (h1 : 1 < m) (n : ℕ) : ¬ nat.prime (n^4 + 4*m^4) :=
have h2 : 1 < (m : ℤ), from coe_nat_lt.mpr h1,
begin
refine not_prime_of_int_mul' (left_factor_large (n : ℤ) h2) (right_factor_large (n : ℤ) h2) _,
exact_mod_cast factorization
end
/--
We define $a_{choice}(b) := 4*(2+b)^4$, so that we can take $m = 2+b$ in `polynomial_not_prime`.
-/
def a_choice (b : ℕ) : ℕ := 4*(2+b)^4
lemma a_choice_good (b : ℕ) : a_choice b ∈ good_nats :=
polynomial_not_prime (show 1 < 2+b, by linarith)
/-- `a_choice` is a strictly monotone function; this is easily proven by chaining together lemmas
in the `strict_mono` namespace. -/
lemma a_choice_strict_mono : strict_mono a_choice :=
((strict_mono_id.const_add 2).nat_pow (dec_trivial : 0 < 4)).const_mul (dec_trivial : 0 < 4)
end imo1969_q1
open imo1969_q1
/-- We conclude by using the fact that `a_choice` is an injective function from the natural numbers
to the set `good_nats`. -/
theorem imo1969_q1 : set.infinite {a : ℕ | ∀ n : ℕ, ¬ nat.prime (n^4 + a)} :=
set.infinite_of_injective_forall_mem a_choice_strict_mono.injective a_choice_good
|
\chapter{Results}\label{cha:Research}
%
% Ska följa som ett naturligt komplement till huvuddelen
In this chapter, the results are presented, so that in the next chapter, these results are analysed. %\todo{Flytta Insights som besvarar en Research Question till Discussion, och hänvisa till iteration. I Resultat vill vi bara ha Resultat, ej svar på forskningsfrågor, så spara svar på forskningsfrågor tills Diskussion.}
%\input{result/example}
\section{Developed Application}\label{developed-application}
\input{result/application}
In the following sections, you can read more about what data guided the development of the final app, as well as the results from the final app evaluation.
\section{Iteration 1: Uganda Coach Visit}
Here the results from the qualitative and quantitative data for iteration 1 are shown, together with conclusions.
\input{result/iteration1/iteration_1_opinions}
\input{result/iteration1/iteration_1_data}
\input{result/iteration1/iteration_1_together}
\section{Iteration 2: Zambia Coach Training}
Here the results from the qualitative and quantitative data for iteration 2 are shown, together with conclusions.
\input{result/iteration2/iteration_2_opinions}
\input{result/iteration2/iteration_2_data}
\input{result/iteration2/iteration_2_together}
\section{Iteration 3: Uganda Formative Test}
Here the results from the qualitative and quantitative data for iteration 3 are shown, together with conclusions. For the coach training in iteration 1, only assessment was okay, since Josefina could give feedback. But if assessing preparedness for a youth session, the app leaving the coach with not being ready is not viable. Given a coach having prepared for their youth session on week 9, and then only scoring 5/10, what should happen? In a similar way, what should happen if 9/10 correct answers? Clearly, if the coach has 9/10, this coach should get feedback to improve, and especially if the score has been 5/10.
\input{result/iteration3/iteration_3_opinions}
\input{result/iteration3/iteration_3_data}
\input{result/iteration3/iteration_3_workshops}
\input{result/iteration3/iteration_3_together}
\section{Iteration 4: Uganda Summative Test}
Here the results from the qualitative and quantitative data for iteration 4 are shown, together with conclusions.
\input{result/iteration4/iteration_4_opinions}
\input{result/iteration4/iteration_4_data}
%\input{result/iteration4/iteration_4_together}
%For Discussion, Conclusion and Future Work, see the coming chapters.
%\section{Qualitative Data}
%
% Here the results from the qualitative data for iteration 1, 2, %3 and 4 are shown.
%
% \input{result/iteration_1_opinions}
% \input{result/iteration_2_opinions}
% \input{result/iteration_3_opinions}
% \input{result/iteration_4_opinions}
%
%\section{Quantitative Data}
%
% Here the results from the quantitative data for iteration 1, 2, %3 and 4 are shown.
%
% \input{result/iteration_1_data}
% \input{result/iteration_2_data}
% \input{result/iteration_3_data}
% \input{result/iteration_4_data}
%
%\section{Insights}
%
% \input{result/iteration_1_together}
% \input{result/iteration_2_together}
% \input{result/iteration_3_together}
% \input{result/iteration_4_together}
%\begin{chapter-appendix}
%\input{appendix/proof_appendix}
%\end{chapter-appendix}
|
function T = convert_CPD_to_table_hidden_ps(CPD, self_val)
% CONVERT_CPD_TO_TABLE_HIDDEN_PS Convert a Gaussian CPD to a table
% function T = convert_CPD_to_table_hidden_ps(CPD, self_val)
%
% self_val must be a non-empty vector.
% All the parents are hidden.
%
% This is used by misc/convert_dbn_CPDs_to_tables
m = CPD.mean;
C = CPD.cov;
W = CPD.weights;
[ssz dpsize] = size(m);
T = zeros(dpsize, 1);
for i=1:dpsize
T(i) = gaussian_prob(self_val, m(:,i), C(:,:,i));
end
|
Describe Users/kellyfairless here.
20130123 15:25:24 nbsp Welcome to the Wiki, Kelly. All the information about the Ramble apartments can be found by clicking The Ramble Apartments. Hope this helps. Users/PeteB
|
#' Polygons
#'
#' Polygons are very similar to paths (as drawn by [geom_path()])
#' except that the start and end points are connected and the inside is
#' coloured by `fill`. The `group` aesthetic determines which cases
#' are connected together into a polygon. From R 3.6 and onwards it is possible
#' to draw polygons with holes by providing a subgroup aesthetic that
#' differentiates the outer ring points from those describing holes in the
#' polygon.
#'
#' @eval rd_aesthetics("geom", "polygon")
#' @seealso
#' [geom_path()] for an unfilled polygon,
#' [geom_ribbon()] for a polygon anchored on the x-axis
#' @export
#' @inheritParams layer
#' @inheritParams geom_point
#' @param rule Either `"evenodd"` or `"winding"`. If polygons with holes are
#' being drawn (using the `subgroup` aesthetic) this argument defines how the
#' hole coordinates are interpreted. See the examples in [grid::pathGrob()] for
#' an explanation.
#' @examples
#' # When using geom_polygon, you will typically need two data frames:
#' # one contains the coordinates of each polygon (positions), and the
#' # other the values associated with each polygon (values). An id
#' # variable links the two together
#'
#' ids <- factor(c("1.1", "2.1", "1.2", "2.2", "1.3", "2.3"))
#'
#' values <- data.frame(
#' id = ids,
#' value = c(3, 3.1, 3.1, 3.2, 3.15, 3.5)
#' )
#'
#' positions <- data.frame(
#' id = rep(ids, each = 4),
#' x = c(2, 1, 1.1, 2.2, 1, 0, 0.3, 1.1, 2.2, 1.1, 1.2, 2.5, 1.1, 0.3,
#' 0.5, 1.2, 2.5, 1.2, 1.3, 2.7, 1.2, 0.5, 0.6, 1.3),
#' y = c(-0.5, 0, 1, 0.5, 0, 0.5, 1.5, 1, 0.5, 1, 2.1, 1.7, 1, 1.5,
#' 2.2, 2.1, 1.7, 2.1, 3.2, 2.8, 2.1, 2.2, 3.3, 3.2)
#' )
#'
#' # Currently we need to manually merge the two together
#' datapoly <- merge(values, positions, by = c("id"))
#'
#' p <- ggplot(datapoly, aes(x = x, y = y)) +
#' geom_polygon(aes(fill = value, group = id))
#' p
#'
#' # Which seems like a lot of work, but then it's easy to add on
#' # other features in this coordinate system, e.g.:
#'
#' stream <- data.frame(
#' x = cumsum(runif(50, max = 0.1)),
#' y = cumsum(runif(50,max = 0.1))
#' )
#'
#' p + geom_line(data = stream, colour = "grey30", size = 5)
#'
#' # And if the positions are in longitude and latitude, you can use
#' # coord_map to produce different map projections.
#'
#' if (packageVersion("grid") >= "3.6") {
#' # As of R version 3.6 geom_polygon() supports polygons with holes
#' # Use the subgroup aesthetic to differentiate holes from the main polygon
#'
#' holes <- do.call(rbind, lapply(split(datapoly, datapoly$id), function(df) {
#' df$x <- df$x + 0.5 * (mean(df$x) - df$x)
#' df$y <- df$y + 0.5 * (mean(df$y) - df$y)
#' df
#' }))
#' datapoly$subid <- 1L
#' holes$subid <- 2L
#' datapoly <- rbind(datapoly, holes)
#'
#' p <- ggplot(datapoly, aes(x = x, y = y)) +
#' geom_polygon(aes(fill = value, group = id, subgroup = subid))
#' p
#' }
#'
geom_polygon <- function(mapping = NULL, data = NULL,
stat = "identity", position = "identity",
rule = "evenodd",
...,
na.rm = FALSE,
show.legend = NA,
inherit.aes = TRUE) {
layer(
data = data,
mapping = mapping,
stat = stat,
geom = GeomPolygon,
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
params = list(
na.rm = na.rm,
rule = rule,
...
)
)
}
#' @rdname ggplot2-ggproto
#' @format NULL
#' @usage NULL
#' @export
GeomPolygon <- ggproto("GeomPolygon", Geom,
draw_panel = function(data, panel_params, coord, rule = "evenodd") {
n <- nrow(data)
if (n == 1) return(zeroGrob())
munched <- coord_munch(coord, data, panel_params)
if (is.null(munched$subgroup)) {
# Sort by group to make sure that colors, fill, etc. come in same order
munched <- munched[order(munched$group), ]
# For gpar(), there is one entry per polygon (not one entry per point).
# We'll pull the first value from each group, and assume all these values
# are the same within each group.
first_idx <- !duplicated(munched$group)
first_rows <- munched[first_idx, ]
ggname(
"geom_polygon",
polygonGrob(
munched$x, munched$y, default.units = "native",
id = munched$group,
gp = gpar(
col = first_rows$colour,
fill = alpha(first_rows$fill, first_rows$alpha),
lwd = first_rows$size * .pt,
lty = first_rows$linetype
)
)
)
} else {
if (utils::packageVersion('grid') < "3.6") {
abort("Polygons with holes requires R 3.6 or above")
}
# Sort by group to make sure that colors, fill, etc. come in same order
munched <- munched[order(munched$group, munched$subgroup), ]
id <- match(munched$subgroup, unique(munched$subgroup))
# For gpar(), there is one entry per polygon (not one entry per point).
# We'll pull the first value from each group, and assume all these values
# are the same within each group.
first_idx <- !duplicated(munched$group)
first_rows <- munched[first_idx, ]
ggname(
"geom_polygon",
pathGrob(
munched$x, munched$y, default.units = "native",
id = id, pathId = munched$group,
rule = rule,
gp = gpar(
col = first_rows$colour,
fill = alpha(first_rows$fill, first_rows$alpha),
lwd = first_rows$size * .pt,
lty = first_rows$linetype
)
)
)
}
},
default_aes = aes(colour = NA, fill = "grey20", size = 0.5, linetype = 1,
alpha = NA, subgroup = NULL),
handle_na = function(data, params) {
data
},
required_aes = c("x", "y"),
draw_key = draw_key_polygon
)
|
Require Import notations.
Set Implicit Arguments.
Set Strict Implicit.
Set Asymmetric Patterns.
Set Universe Polymorphism.
Set Printing Universes.
(** Core Type and Functions **)
Section hlist.
Polymorphic Universe Ui Uv.
Context {iT : Type@{Ui}}.
Variable F : iT -> Type@{Uv}.
Inductive hlist : list iT -> Type :=
| Hnil : hlist nil
| Hcons : forall l ls, F l -> hlist ls -> hlist (l :: ls).
Local Open Scope list_scope.
Definition hlist_hd {a b} (hl : hlist (a :: b)) : F a :=
match hl in hlist x return match x with
| nil => unit
| l :: _ => F l
end with
| Hnil => tt
| Hcons _ _ x _ => x
end.
Definition hlist_tl {a b} (hl : hlist (a :: b)) : hlist b :=
match hl in hlist x return match x with
| nil => unit
| _ :: ls => hlist ls
end with
| Hnil => tt
| Hcons _ _ _ x => x
end.
Lemma hlist_eta : forall ls (h : hlist ls),
h = match ls as ls return hlist ls -> hlist ls with
| nil => fun _ => Hnil
| a :: b => fun h => Hcons (hlist_hd h) (hlist_tl h)
end h.
Proof.
intros. destruct h; auto.
Qed.
Fixpoint hlist_app ll lr (h : hlist ll) : hlist lr -> hlist (ll ++ lr) :=
match h in hlist ll return hlist lr -> hlist (ll ++ lr) with
| Hnil => fun x => x
| Hcons _ _ hd tl => fun r => Hcons hd (hlist_app tl r)
end.
End hlist.
Arguments Hnil {_ _}.
Arguments Hcons {_ _ _ _} _ _.
Eval compute in Hcons true Hnil.
Section hlist.
Inductive hlist (A:Type): list A -> Type :=
| HNil : hlist A nil
| HCons : forall (x:A)(ls:list A), F x -> hlist A ls -> hlist A (x::ls).
(* Implicit Arguments hlist [A F]. *)
Implicit Arguments HCons [A F x ls].
Implicit Arguments HNil [A F].
Print hlist.
Open Scope list_scope.
Eval compute in HCons true HNil.
Definition someTypes : list Set := nat :: nil.
Example someValues : hlist (Set) (fun T : Set => T) someTypes :=
HCons 2 HNil.
Example someValues : hlist (Set) (fun T : Set => T) someTypes :=
HCons 2 (HCons true nil nil HNil).
Eval compute in HCons true HNil.
Eval compute in HCons 2 (HCons true (HNil)).
Variable A : Type.
Variable B : A -> Type.
Inductive hlist : list A -> Type :=
| HNil : hlist nil
| HCons : forall (x:A)(ls:list A), B x -> hlist ls -> hlist (x::ls).
Variable elm: A.
Inductive member : list A -> Type :=
| HFirst : forall ls, member (elm :: ls)
| HNext : forall x ls, member ls -> member (x :: ls).
Print HNil.
(*
Arguments HNil [A B].
Implicit Arguments HCons [ A B x ls ]. *)
Open Scope list_scope.
Print hlist.
Implicit Arguments hlist [A].
Definition someTypes : list Set := nat :: bool :: nil.
Example someValues : hlist (fun T : Set => T) someTypes.
Print HCons.
Implicit Arguments HCons [x ls (B x)].
Print HCons.
Definition test : nat -> nat := fun x => 2.
Eval compute in HCons test 2 (HCons true (HNil)).
Implicit Arguments HCons [A B x ls].
Example someValues : hlist someTypes := HCons 2 (HCons true (HNil)).
Eval compute in HCons 2 (HCons true (HNil)).
End hlist.
|
'''Abstract NER tagging benchmark'''
from datasets import Dataset
import numpy as np
from typing import Tuple, Dict, List, Optional
import logging
from .token_classification import TokenClassificationBenchmark
from ...datasets import load_dataset
logger = logging.getLogger(__name__)
class NerBenchmark(TokenClassificationBenchmark):
'''Abstract NER tagging benchmark.
Args:
name (str):
The name of the dataset.
cache_dir (str, optional):
Where the downloaded models will be stored. Defaults to
'.benchmark_models'.
evaluate_train (bool, optional):
Whether the models should be evaluated on the training scores.
Defaults to False.
verbose (bool, optional):
Whether to print additional output during evaluation. Defaults to
False.
Attributes:
name (str): The name of the dataset.
task (str): The type of task to be benchmarked.
metric_names (dict): The names of the metrics.
id2label (dict or None): A dictionary converting indices to labels.
label2id (dict or None): A dictionary converting labels to indices.
num_labels (int or None): The number of labels in the dataset.
label_synonyms (list of lists of str): Synonyms of the dataset labels.
evaluate_train (bool): Whether the training set should be evaluated.
cache_dir (str): Directory where models are cached.
two_labels (bool): Whether two labels should be predicted.
split_point (int or None): Splitting point of `id2label` into labels.
verbose (bool): Whether to print additional output.
'''
def __init__(self,
name: str,
cache_dir: str = '.benchmark_models',
evaluate_train: bool = False,
verbose: bool = False):
id2label = ['B-LOC', 'I-LOC', 'B-ORG', 'I-ORG', 'B-PER',
'I-PER', 'B-MISC', 'I-MISC', 'O']
label_synonyms = [
['B-Location', 'B-location', 'B-place', 'B-GPE_LOC', 'B-LOC/ORG',
'B-LOCPRS', 'B-LOCORG', id2label[0]],
['I-Location', 'I-location', 'I-place', 'I-GPE_LOC', 'I-LOC/ORG',
'I-LOCPRS', 'I-LOCORG', id2label[1]],
['B-Organization', 'B-organization', 'B-inst', 'B-GPE_ORG',
'B-ORG/PRS', 'B-OBJ/ORG', 'B-ORGPRS', 'B-OBJORG', id2label[2]],
['I-Organization', 'I-organization', 'I-inst', 'I-GPE_ORG',
'I-ORG/PRS', 'I-OBJ/ORG', 'I-ORGPRS', 'I-OBJORG', id2label[3]],
['B-Person', 'B-person', id2label[4]],
['I-Person', 'I-person', id2label[5]],
['B-Miscellaneous', 'B-Misc', 'B-misc', id2label[6]],
['I-Miscellaneous', 'I-Misc', 'I-misc', id2label[7]],
['B-Date', 'B-date', 'I-Date', 'I-date',
'B-Time', 'B-time', 'I-Time', 'I-time',
'B-Money', 'B-money', 'I-Money', 'I-money',
'B-Percent', 'B-percent', 'I-Percent', 'I-percent',
id2label[8]]
]
super().__init__(name=name,
metric_names=dict(micro_f1='Micro-average F1-score',
micro_f1_no_misc='Micro-average '
'F1-score without '
'MISC tags'),
id2label=id2label,
label_synonyms=label_synonyms,
cache_dir=cache_dir,
evaluate_train=evaluate_train,
verbose=verbose)
def _load_data(self) -> Tuple[Dataset, Dataset]:
'''Load the datasets.
Returns:
A triple of HuggingFace datasets:
The train and test datasets.
'''
X_train, X_test, y_train, y_test = load_dataset(self.short_name)
train_dict = dict(doc=X_train['doc'],
tokens=X_train['tokens'],
orig_labels=y_train['ner_tags'])
test_dict = dict(doc=X_test['doc'],
tokens=X_test['tokens'],
orig_labels=y_test['ner_tags'])
train = Dataset.from_dict(train_dict)
test = Dataset.from_dict(test_dict)
# Check what labels are present in the dataset, and store if MISC tags
# are not present
labels_in_train = set([tag for tag_list in y_train['ner_tags'].tolist()
for tag in tag_list])
self.has_misc_tags = ('B-MISC' in labels_in_train and
'I-MISC' in labels_in_train)
return train, test
def _compute_metrics(self,
predictions_and_labels: tuple,
id2label: Optional[dict] = None) -> Dict[str, float]:
'''Compute the metrics needed for evaluation.
Args:
predictions_and_labels (pair of arrays):
The first array contains the probability predictions and the
second array contains the true labels.
id2label (list or None, optional):
Conversion of indices to labels. Defaults to None.
Returns:
dict:
A dictionary with the names of the metrics as keys and the
metric values as values.
'''
# Get the predictions from the model
predictions, labels = predictions_and_labels
if id2label is not None:
raw_predictions = np.argmax(predictions, axis=-1)
# Remove ignored index (special tokens)
predictions = [
[id2label[pred] for pred, lbl in zip(prediction, label)
if lbl != -100]
for prediction, label in zip(raw_predictions, labels)
]
labels = [
[id2label[lbl] for _, lbl in zip(prediction, label)
if lbl != -100]
for prediction, label in zip(raw_predictions, labels)
]
# Replace predicted tag with either MISC or O tags if they are not part
# of the dataset
labels_no_misc = set(self.id2label).difference({'B-MISC', 'I-MISC'})
for i, prediction_list in enumerate(predictions):
for j, ner_tag in enumerate(prediction_list):
if ner_tag not in labels_no_misc:
if self.has_misc_tags and ner_tag[:2] == 'B-':
predictions[i][j] = 'B-MISC'
elif self.has_misc_tags and ner_tag[:2] == 'I-':
predictions[i][j] = 'I-MISC'
else:
predictions[i][j] = 'O'
results = self._metric.compute(predictions=predictions,
references=labels)
# Remove MISC labels from predictions
for i, prediction_list in enumerate(predictions):
for j, ner_tag in enumerate(prediction_list):
if ner_tag[-4:] == 'MISC':
predictions[i][j] = 'O'
# Remove MISC labels from labels
for i, label_list in enumerate(labels):
for j, ner_tag in enumerate(label_list):
if ner_tag[-4:] == 'MISC':
labels[i][j] = 'O'
results_no_misc = self._metric.compute(predictions=predictions,
references=labels)
return dict(micro_f1=results["overall_f1"],
micro_f1_no_misc=results_no_misc['overall_f1'])
def _get_spacy_token_labels(self, processed) -> List[str]:
'''Get predictions from SpaCy model on dataset.
Args:
model (SpaCy model): The model.
dataset (HuggingFace dataset): The dataset.
Returns:
A list of strings:
The predicted NER labels.
'''
def get_ent(token) -> str:
'''Helper function that extracts the entity from a SpaCy token'''
# Deal with the O tag separately, as it is the only tag not of the
# form B-tag or I-tag
if token.ent_iob_ == 'O':
return 'O'
# In general return a tag of the form B-tag or I-tag
else:
# Extract tag from spaCy token
ent = f'{token.ent_iob_}-{token.ent_type_}'
# Convert the tag to the its canonical synonym
alt_idx = self.label2id[f'{token.ent_iob_}-MISC']
return self.id2label[self.label2id.get(ent, alt_idx)]
return [get_ent(token) for token in processed]
|
$
\newcommand{\ket}[1]{\lvert {#1}\rangle}
\newcommand{\ds}{\displaystyle}
$
# Shor's Algorithm
## Introduction
Problem
> Integer factorization
Use Case
> $n = p \cdot q$, where $p,q$ are large prime numbers, often used in cryptographic functions
Classical Solution
> **General Number Field Sieve** has best asymptotic behaviour
> Superpolynomial scaling:
> $\displaystyle O(e^{(\ln n)^\frac{1}{3}(\ln\ln n)^{\frac{2}{3}}})$
Shor's Algorthim
> Factorization algorithm with poylnomial complexity <br/>
> Partially on Quantum processor, pre & post processing is classical
> Quantum complexity: $O\big( (\log n)^2 (\log \log n) (\log \log \log n) \big)$
> Polynomial time achieved with Quantum Forier Transform
----
## Algorithm
### 1. Preconditions of $n$
Exit if $n$ is any of the following
- even
- prime
- prime power
### 2. Attempt brute-force solution
Pick a random integer $x \lt n$, and calculate $\gcd(x, n)$.
If this is not 1, then we have a factor of $n$.
### 3. Quantum Algorithm
1. Pick q as the smallest power of 2 where $n^2 \leq q \leq 2n^2$
2. Find the period $r$ of $x^a \mod n$
3. Measure $c$ which has property $\displaystyle \frac{c}{q} \approx \frac{d}{r}$, where $d \in \mathbb{N}$
### 4. Determine ratio
$r, d$ can be determined if $gcd(d, r) = 1$ using fraction expansion algorithm
### 5. Try to obtain factors
Return to step 2
> if $r$ is odd <br/>
> if $x^{\frac{r}{2}} \equiv -1 \mod n$
Factors are
>$\displaystyle p, q = \gcd(x^{\frac{r}{2}} \pm 1, n)$
----
### Quantum Fourier Transform (QFT)
Define QFT with respect to an ONB $\left\{\ket{x}\right\} = {\ket{0}, \dots, \ket{q-1}}$
> $\ds QFT: \ket{x} \mapsto \frac{1}{\sqrt{q}} \sum\limits_{y=0}^{q-1} \exp \left\{ \frac{2\pi i}{q}x \cdot y \right\} \ket{y} = \frac{1}{\sqrt{q}} \sum\limits_{y=0}^{q-1} \omega^{x \cdot y} \ket{y}$
Apply QFT to a general state $\ds\ket{\psi} = \sum_x \alpha_x\ket{x}$ :
> $\ds QFT(\ket{\psi}) = \frac{1}{\sqrt{q}} \sum\limits_{y=0}^{q-1} \beta_y\ket{y}$ <br/>
> where the $\beta_y$'s are the discrete Fourier tansform of the amplitudes $\alpha_x$
The QFT is unitary
> $QFT^\dagger QFT\ket{x} = \ket{x}$
----
## References
- [Lecture Notes - Shor's Algorithm][1]
- [Continued Fraction Expansion][2]
[1]: https://qudev.phys.ethz.ch/content/QSIT15/Shors%20Algorithm.pdf
[2]: https://www.math.u-bordeaux.fr/~pjaming/M1/exposes/MA2.pdf
----
## Addendum I - Euclidean Algorithm
$
\gcd(a,b) =
\Bigg\{\begin{split}
&b & \text{ if } a \bmod b = 0 \\
&\gcd(b, a \bmod b) & \text{ else } \\
\end{split}
$
### References
- [Euclidean Algorithm][1]
[1]: https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/the-euclidean-algorithm
```python
# Euclidian Algorithm
def gcd(a, b):
h,l = (max(a,b),min(a,b))
q = h % l
if q == 0:
return l
return gcd(l,q)
def is_coprime(a, b):
return (gcd(a, b) == 1)
```
----
$\newcommand{\ds}{\displaystyle}$
## Addendum II - Continued Fractions
Tools to approximate a Real number to a Rational number.
### Example 1 - 1 and 2
'1' can be written as a fraction
> $\ds1 = \frac{2}{3-1}$
and as a continued/infinite fraction
> $\ds1 = \frac{2}{3-\frac{2}{3-\frac{2}{3-\dots}}}$
interestingly, using 2 instead would suggest the contradiction $1=2$
> $\ds2 = \frac{2}{3-\frac{2}{3-\frac{2}{3-\dots}}}$
### Example 2 - $\sqrt{2}$
> $
\begin{split}
\sqrt{2} &= 1.414213 \\
&= 1 + 0.41421 \\
&= 1 + \frac{1}{\frac{1}{0.41421 }} \\
&= 1 + \frac{1}{2+ 0.41421 } \\
&= 1 + \frac{1}{2+ \frac{1}{2 + \frac{1}{2 + \dots}}} \\
\end{split}
$ <br/>
> Sequence `11111111...`
### Example 3 - $\phi$ (Golden Ratio)
> $
\begin{split}
\phi &= \frac{1 + \sqrt{5}}{2} \\
&= 1 + \frac{1}{1+ \frac{1}{1 + \frac{1}{1 + \dots}}}
\end{split}
$ <br/>
> Sequence `11111111...`
### Example 4 - $e$ (2.718)
> $
\begin{split}
e &= \frac{1 + \sqrt{5}}{2} \\
&= 2 + \frac{1}{1+ \frac{1}{2 + \frac{1}{1 + \frac{1}{1 + \frac{1}{4 + \dots}}}}}
\end{split}
$ <br/>
> Sequence - `2114116118...`
### Example 5 - Rational $\frac{1473}{50}$
*Rational numbers tend to be finite*
> $29 + \frac{1}{2 + \frac{1}{5 + \frac{1}{1 + \frac{1}{3}}}}$
### Example 5 -$\pi$
> $
\begin{split}
\pi &= 3.14159265358979 \\
&= 3 + \frac{1}{7+ \frac{1}{15 + \frac{1}{1 + \frac{1}{292 + \dots}}}} \\
3 &= 3.0 \\
3 + \frac{1}{7} = \frac{22}{7} &= 3.14 \\
3 + \frac{1}{7+\frac{1}{15}} = \frac{333}{106} &= 3.1415 \\
3 + \frac{1}{7+\frac{1}{15 + 1}} = \frac{355}{113} &= 3.141592 \\
3 + \frac{1}{7+\frac{1}{15 + \frac{1}{1 + \frac{1}{292}}}} = \frac{103993}{33102} &= 3.14159265 \\
\end{split}
$
----
## Addendum III - Example, Factoring n=21
### 1. Choose a random integer $x$, where $1 < x < n$
> if x *is **not** coprime* with n (i.e. x=6) <br/>
> $\gcd(x,n) = \gcd(6, 21) = 3$ <br/>
> $\therefore \frac{21}{3} = 7$ <br/>
> The factors are 7 and 3
> if x *is coprime* with n (i.e. x=11) <br/>
> $\gcd(11,21) = 1$ <br/>
> then continue...
### 2. Determine q
> Where q is the smallest power of 2 between $n^2$ and $2n^2$ <br/>
> $441 \leq q < 882 \land \log_2(q) = l : l \in \mathbb{N}$ <br/>
> $l=9, q=512$
> Initial state for 2 registers with length of 'l' <br/>
> $\ket{\Phi_i} = \ket{0}_{r_1} \ket{0}_{r_2} = \ket{0}^{\otimes 2^l}$
### 3. Initialize first register ($r_1$)
> Initialize first register with superposition of all stats $a \pmod{q}$
> $\ds\ket{\Phi_0} = \frac{1}{\sqrt{512}} \sum\limits_{a=0}^{511} \ket{a}\ket{0} $ <br/>
> therefore all bits are $\frac{1}{\sqrt{2}}\Big(\ket{0} + \ket{1}\Big)$
### 4. Initialize second register ($r_2$)
> Initialize Register with superposition of all states $x^a \pmod{n}$
> $\ds
\begin{split}
\ket{\Phi_1} &= \frac{1}{\sqrt{512}} \sum\limits_{a=0}^{511} \ket{a}\ket{11^a(\bmod{21})} \\
&= \frac{1}{\sqrt{512}} \Big( \ket{0}\ket{1} + \ket{1}\ket{11} + \ket{2}\ket{16} + \ket{3}\ket{8} \dots \Big)
\end{split}$ <br/><br/>
> The sequence looks like this
>$
\begin{matrix}
0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & \dots \\
1 & 11 & 16 & 8 & 4 & 2 & 1 & 11 & 16 & 8 & 4 & \dots \\
\end{matrix}
$ <br/>
> *The period is 6, but not yet observable*
### 5. Quantum Fourier Transform
> $\ds \overset{\sim}{\ket{\Phi}} = \frac{1}{512} \sum\limits_{a=0}^{511} \sum\limits_{c=0}^{511} e^{\big(\frac{1}{512} 2\pi i a c\big)} \ket{c}\ket{11^a(\bmod{21})}$
### 6. Measurement
> Probability for state $\ket{c, x^k\pmod{n}}$ e.g. $k=2 \rightarrow \ket{c,16}$ <br/>
> $\ds
\begin{split}
p(c) &= \Bigg| {\frac{1}{512}}_{a:11^a} \sum\limits_{\bmod{21}=16}^{511} e^{\big(\frac{1}{512} 2\pi iac\big)} \Bigg|^2 \\
&= \Bigg| {\frac{1}{512}}_{a:11^a} \sum\limits_{b} e^{\big(\frac{1}{512} 2\pi i(6b+2)c\big)} \Bigg|^2\\
\end{split}$ <br/>
>
> Simulation of the probability amplitude of a period of 6
```python
PERIOD=6
import sympy as sm
import numpy as np
import matplotlib.pyplot as plt
fig = plt.gcf()
fig.set_size_inches(8,5)
sm.var('x')
# This function is a simulation, it does not
# reflect a multi-modal normal distribution
f = lambda x: ((sm.cos((x*PERIOD*2*sm.pi)/512)+1)/2)**80/PERIOD
x = np.linspace(0,512,1000)
y = np.array([f(v) for v in x],dtype='float')
plt.title(r"Probaility Amplitudes with a period of 6 peaks fro $c =\frac{512}{6} \cdot d, d \in \mathbb{Z}$")
plt.plot(x,y,color='gray')
plt.fill_between(x,y,0,color='#c0f0c0')
plt.show()
```
### 7. Determine the period
Continued Fraction Expansion (determine r)
> $\ds \Bigg| \frac{c}{q} - \frac{d}{r} \Bigg| = \overset{!}{\leq} \frac{1}{1024}$ <br/><br/>
> Use continued fraction expansion <br/>
> $\ds
\begin{split}
\frac{c}{q} &= a_0 + \frac{1}{a_1 + \frac{1}{a_2 + \dots}} \\
\tfrac{d_0}{r_0} &= \tfrac{a_0}{1} \\
\tfrac{d_1}{r_1} &= \tfrac{1+a_0a_1}{a_1} \\
\tfrac{d_n}{r_n} &= \tfrac{a_nd_{n-1} + d_{n-2}}{a_nr_{n-1} + r_{n-2}} \\
&\dots \\
\end{split}
$
Assume the reading was **427** <br/>
> So <br/>
> e = $\ds \Bigg| \frac{427}{512} - \frac{d}{r} \Bigg| \overset{!}{\leq} \frac{1}{1024}$ <br/><br/>
> Use continued fraction expansion <br/>
> $\ds
\begin{split}
\frac{427}{512} &= 0.83398\dots \\
&= 0 + \frac{1}{1 + \frac{1}{5 + \frac{1}{42 + \frac{1}{2}}}} \\
\tfrac{d_0}{r_0} &= \tfrac{0}{1} = 0 \;\;\; &e = \tfrac{427}{512} > \tfrac{1}{1204} \text{ no match}\\
\tfrac{d_1}{r_1} &= \tfrac{1}{1} = 1 \;\;\; &e = \tfrac{85}{512} > \tfrac{1}{1204} \text{ no match}\\
\tfrac{d_2}{r_2} &= \tfrac{5}{6} = 0.8\dot{3} \;\;\; &e = \tfrac{2}{3072} < \tfrac{1}{1204} \text{ match!}\\
\tfrac{d_3}{r_3} &= \tfrac{427}{512} = 0.83398\dots \;\;\; &e = 0 \\
\end{split}
$ <br/><br/>
> $\frac{5}{6}$ is a match,   $d(427)$ and $r(6)$ are coprime,   therefore the period **r = 6**
Assume the reading was **171** <br/>
> we would get $\frac{d}{r} = \frac{1}{3}$,   $d(171)$ and $r(3)$ are *not* coprime, therefore this does not work, try again.
### 8. Check r (determine factors)
Check r is even
> $6 \pmod{2} = 0$
Check if $x^{\tfrac{r}{2}} \pmod{n} \ne -1$
> $11^{\tfrac{6}{2}} \pmod{21} = 11^3 \pmod{21} = 1331 \pmod{21} = 8 \ne 1330$
Calculate factors via $x^{\tfrac{r}{2}}\pmod{n} \pm 1$
> $1331 \pmod{21} - 1 = 7$ <br/>
> $1331 \pmod{21} + 1 = 9$ <br/>
```python
```
|
// Copyright Oliver Kowalke 2009.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_TASKS_SPIN_AUTO_RESET_EVENT_H
#define BOOST_TASKS_SPIN_AUTO_RESET_EVENT_H
#include <boost/atomic.hpp>
#include <boost/thread/thread_time.hpp>
#include <boost/utility.hpp>
namespace boost {
namespace tasks {
namespace spin {
class auto_reset_event : private noncopyable
{
private:
enum state
{
SET = 0,
RESET
};
atomic< state > state_;
public:
explicit auto_reset_event( bool = false);
void set();
void wait();
bool try_wait();
bool timed_wait( system_time const&);
template< typename TimeDuration >
bool timed_wait( TimeDuration const& rel_time)
{ return timed_wait( get_system_time() + rel_time); }
};
}}}
#endif // BOOST_TASKS_SPIN_AUTO_RESET_EVENT_H
|
/-
Copyright (c) 2019 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek, Robert Y. Lewis
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.string.defs
import Mathlib.tactic.derive_inhabited
import Mathlib.PostPort
namespace Mathlib
/-!
# Additional operations on expr and related types
This file defines basic operations on the types expr, name, declaration, level, environment.
This file is mostly for non-tactics. Tactics should generally be placed in `tactic.core`.
## Tags
expr, name, declaration, level, environment, meta, metaprogramming, tactic
-/
namespace binder_info
/-! ### Declarations about `binder_info` -/
protected instance inhabited : Inhabited binder_info :=
{ default := default }
/-- The brackets corresponding to a given binder_info. -/
def brackets : binder_info → string × string :=
sorry
end binder_info
namespace name
/-! ### Declarations about `name` -/
/-- Find the largest prefix `n` of a `name` such that `f n ≠ none`, then replace this prefix
with the value of `f n`. -/
def map_prefix (f : name → Option name) : name → name :=
sorry
/-- If `nm` is a simple name (having only one string component) starting with `_`, then
`deinternalize_field nm` removes the underscore. Otherwise, it does nothing. -/
/-- `get_nth_prefix nm n` removes the last `n` components from `nm` -/
/-- Auxilliary definition for `pop_nth_prefix` -/
/-- Pops the top `n` prefixes from the given name. -/
/-- Pop the prefix of a name -/
/-- Auxilliary definition for `from_components` -/
/-- Build a name from components. For example `from_components ["foo","bar"]` becomes
``` `foo.bar``` -/
def from_components : List string → name :=
from_components_aux anonymous
/-- `name`s can contain numeral pieces, which are not legal names
when typed/passed directly to the parser. We turn an arbitrary
name into a legal identifier name by turning the numbers to strings. -/
/-- Append a string to the last component of a name -/
def append_suffix : name → string → name :=
sorry
/-- The first component of a name, turning a number to a string -/
/-- Tests whether the first component of a name is `"_private"` -/
/-- Get the last component of a name, and convert it to a string. -/
/-- Returns the number of characters used to print all the string components of a name,
including periods between name segments. Ignores numerical parts of a name. -/
/-- Checks whether `nm` has a prefix (including itself) such that P is true -/
def has_prefix (P : name → Bool) : name → Bool :=
sorry
/-- Appends `'` to the end of a name. -/
/-- `last_string n` returns the rightmost component of `n`, ignoring numeral components.
For example, ``last_string `a.b.c.33`` will return `` `c ``. -/
def last_string : name → string :=
sorry
/--
Constructs a (non-simple) name from a string.
Example: ``name.from_string "foo.bar" = `foo.bar``
-/
/--
In surface Lean, we can write anonymous Π binders (i.e. binders where the
argument is not named) using the function arrow notation:
```lean
inductive test : Type
| intro : unit → test
```
After elaboration, however, every binder must have a name, so Lean generates
one. In the example, the binder in the type of `intro` is anonymous, so Lean
gives it the name `ᾰ`:
```lean
test.intro : ∀ (ᾰ : unit), test
```
When there are multiple anonymous binders, they are named `ᾰ_1`, `ᾰ_2` etc.
Thus, when we want to know whether the user named a binder, we can check whether
the name follows this scheme. Note, however, that this is not reliable. When the
user writes (for whatever reason)
```lean
inductive test : Type
| intro : ∀ (ᾰ : unit), test
```
we cannot tell that the binder was, in fact, named.
The function `name.is_likely_generated_binder_name` checks if
a name is of the form `ᾰ`, `ᾰ_1`, etc.
-/
/--
Check whether a simple name was likely generated by Lean to name an anonymous
binder. Such names are either `ᾰ` or `ᾰ_n` for some natural `n`. See
note [likely generated binder names].
-/
/--
Check whether a name was likely generated by Lean to name an anonymous binder.
Such names are either `ᾰ` or `ᾰ_n` for some natural `n`. See
note [likely generated binder names].
-/
end name
namespace level
/-! ### Declarations about `level` -/
/-- Tests whether a universe level is non-zero for all assignments of its variables -/
/--
`l.fold_mvar f` folds a function `f : name → α → α`
over each `n : name` appearing in a `level.mvar n` in `l`.
-/
end level
/-! ### Declarations about `binder` -/
/-- The type of binders containing a name, the binding info and the binding type -/
namespace binder
/-- Turn a binder into a string. Uses expr.to_string for the type. -/
end binder
/-!
### Converting between expressions and numerals
There are a number of ways to convert between expressions and numerals, depending on the input and
output types and whether you want to infer the necessary type classes.
See also the tactics `expr.of_nat`, `expr.of_int`, `expr.of_rat`.
-/
/--
`nat.mk_numeral n` embeds `n` as a numeral expression inside a type with 0, 1, and +.
`type`: an expression representing the target type. This must live in Type 0.
`has_zero`, `has_one`, `has_add`: expressions of the type `has_zero %%type`, etc.
-/
/--
`int.mk_numeral z` embeds `z` as a numeral expression inside a type with 0, 1, +, and -.
`type`: an expression representing the target type. This must live in Type 0.
`has_zero`, `has_one`, `has_add`, `has_neg`: expressions of the type `has_zero %%type`, etc.
-/
/--
`nat.to_pexpr n` creates a `pexpr` that will evaluate to `n`.
The `pexpr` does not hold any typing information:
`to_expr ``((%%(nat.to_pexpr 5) : ℤ))` will create a native integer numeral `(5 : ℤ)`.
-/
namespace expr
/--
Turns an expression into a natural number, assuming it is only built up from
`has_one.one`, `bit0`, `bit1`, `has_zero.zero`, `nat.zero`, and `nat.succ`.
-/
/--
Turns an expression into a integer, assuming it is only built up from
`has_one.one`, `bit0`, `bit1`, `has_zero.zero` and a optionally a single `has_neg.neg` as head.
-/
/--
`is_num_eq n1 n2` returns true if `n1` and `n2` are both numerals with the same numeral structure,
ignoring differences in type and type class arguments.
-/
end expr
/-! ### Declarations about `expr` -/
namespace expr
/-- List of names removed by `clean`. All these names must resolve to functions defeq `id`. -/
/-- Clean an expression by removing `id`s listed in `clean_ids`. -/
/-- `replace_with e s s'` replaces ocurrences of `s` with `s'` in `e`. -/
/-- Apply a function to each constant (inductive type, defined function etc) in an expression. -/
/-- Match a variable. -/
/-- Match a sort. -/
/-- Match a constant. -/
/-- Match a metavariable. -/
/-- Match a local constant. -/
/-- Match an application. -/
/-- Match an abstraction. -/
/-- Match a Π type. -/
/-- Match a let. -/
/-- Match a macro. -/
/-- Tests whether an expression is a meta-variable. -/
/-- Tests whether an expression is a sort. -/
/-- Get the universe levels of a `const` expression -/
/--
Replace any metavariables in the expression with underscores, in preparation for printing
`refine ...` statements.
-/
/-- If `e` is a local constant, `to_implicit_local_const e` changes the binder info of `e` to
`implicit`. See also `to_implicit_binder`, which also changes lambdas and pis. -/
/-- If `e` is a local constant, lamda, or pi expression, `to_implicit_binder e` changes the binder
info of `e` to `implicit`. See also `to_implicit_local_const`, which only changes local constants. -/
/-- Returns a list of all local constants in an expression (without duplicates). -/
/-- Returns the set of all local constants in an expression. -/
/-- Returns the unique names of all local constants in an expression. -/
/-- Returns a name_set of all constants in an expression. -/
/-- Returns a list of all meta-variables in an expression (without duplicates). -/
/-- Returns the set of all meta-variables in an expression. -/
/-- Returns a list of all universe meta-variables in an expression (without duplicates). -/
/--
Test `t` contains the specified subexpression `e`, or a metavariable.
This represents the notion that `e` "may occur" in `t`,
possibly after subsequent unification.
-/
-- We can't use `t.has_meta_var` here, as that detects universe metavariables, too.
/-- Returns a name_set of all constants in an expression starting with a certain prefix. -/
/-- Returns true if `e` contains a name `n` where `p n` is true.
Returns `true` if `p name.anonymous` is true. -/
/--
Returns true if `e` contains a `sorry`.
-/
/--
`app_symbol_in e l` returns true iff `e` is an application of a constant whose name is in `l`.
-/
/-- `get_simp_args e` returns the arguments of `e` that simp can reach via congruence lemmas. -/
-- `mk_specialized_congr_lemma_simp` throws an assertion violation if its argument is not an app
/-- Simplifies the expression `t` with the specified options.
The result is `(new_e, pr)` with the new expression `new_e` and a proof
`pr : e = new_e`. -/
/-- Definitionally simplifies the expression `t` with the specified options.
The result is the simplified expression. -/
/-- Get the names of the bound variables by a sequence of pis or lambdas. -/
/-- head-reduce a single let expression -/
/-- head-reduce all let expressions -/
/-- Instantiate lambdas in the second argument by expressions from the first. -/
/-- Repeatedly apply `expr.subst`. -/
/-- `instantiate_lambdas_or_apps es e` instantiates lambdas in `e` by expressions from `es`.
If the length of `es` is larger than the number of lambdas in `e`,
then the term is applied to the remaining terms.
Also reduces head let-expressions in `e`, including those after instantiating all lambdas.
This is very similar to `expr.substs`, but this also reduces head let-expressions. -/
/--
Some declarations work with open expressions, i.e. an expr that has free variables.
|
MoreThuente := module()
description "More-Thuente";
# Module defined as a package (i.e.) collection of procedures
option package, load = ModuleLoad, unload = ModuleUnLoad;
export lines, linesearch, esatta, AB_list, doplot, doplot2;
local ModuleLoad,
ModuleUnLoad,
_debug,
min_quadratic,
min_cubic,
xtol, ftol, gtol, stpmin, stpmax, maxfev,
stx, fx, dx, sty, fy, dy, stp, fp, dp, brackt,
max_iter, A_list, B_list;
uses LinearAlgebra;
ModuleUnLoad := proc()
printf("PotraShi unload\n");
NULL;
end proc:
ModuleLoad := proc()
printf("PotraShi load\n");
_debug := true;
rho := 0.25;
sigma := 0.75;
tau1 := 0.1;
tau2 := 0.49;
tau3 := 2.5;
Jbig := 2;
max_iter := 40;
NULL;
end proc;
# Explicitly call ModuleLoad here so the type is registered when this
# code is cut&pasted in. ModuleLoad gets called when the module is
# read from the repository, but the code used to define a module
# (like the command below) is not called at library read time.
ModuleLoad();
AB_list := proc()
A_list, B_list;
end proc;
min_quadratic := proc ( a, fa, Dfa, b, fb )
local t, delta; # A+B*(x-a)+C*(x-a)^2
# p = fa + Dfa*(x-a)+t*(x-a)^2
# p' = Dfa+2*t*(x-a)
##t := ((fb-fa)/(b-a)-Dfa)/(b-a);
##delta := -Dfa/(2*t);
t := (fb-fa)/(b-a)-Dfa;
delta := max(tau1,min(1-tau1,-Dfa/(2*t)));
a+(b-a)*delta;
end proc;
lines := proc( f0, df0, L )
[ [0,f0], [L,f0+L*rho*df0] ], [ [0,f0], [L,f0+L*sigma*df0] ];
end proc;
pqr := proc()
theta := 3*(fx - fp)/(stp - stx) + dx + dp;
s := max([abs(theta),abs(dx),abs(dp)]);
gamma := s*sqrt(max(0,(theta/s)^2 - (dx/s)*(dp/s)));
if stp > stx then
gamma = -gamma;
end;
p := (gamma - dp) + theta;
q := (gamma + (dx - dp)) + gamma;
r := p/q;
end proc:
Skip to content
Search or jump to…
Pull requests
Issues
Marketplace
Explore
@ebertolazzi
JuliaNLSolvers
/
LineSearches.jl
Public
6
69
26
Code
Issues
17
Pull requests
1
Actions
Projects
Wiki
Security
Insights
LineSearches.jl/src/morethuente.jl
@pkofod
pkofod Pkm/fix lse (#146)
…
Latest commit 0f5571e on Aug 18, 2020
History
6 contributors
@anriseth@pkofod@antoine-levitt@femtocleaner@mohamed82008@cortner
658 lines (594 sloc) 20.1 KB
# Translation of Matlab version by John Myles White
# Translation of minpack subroutine cvsrch
# Dianne O'Leary July 1991
#
# **********
#
# Subroutine cvsrch
#
# The purpose of cvsrch is to find a step which satisfies
# a sufficient decrease condition and a curvature condition.
# The user must provide a subroutine which calculates the
# function and the gradient.
#
# At each stage the subroutine updates an interval of
# uncertainty with endpoints stx and sty. The interval of
# uncertainty is initially chosen so that it contains a
# minimizer of the modified function
#
# f(x + stp * s) - f(x) - f_tol * stp * (gradf(x)' * s).
#
# If a step is obtained for which the modified function
# has a nonpositive function value and nonnegative derivative,
# then the interval of uncertainty is chosen so that it
# contains a minimizer of f(x + stp * s).
#
# The algorithm is designed to find a step which satisfies
# the sufficient decrease condition
#
# f(x + stp * s) <= f(x) + f_tol * stp * (gradf(x)' * s),
#
# and the curvature condition
#
# abs(gradf(x + stp * s)' * s)) <= gtol * abs(gradf(x)' * s).
#
# If f_tol is less than gtol and if, for example, the function
# is bounded below, then there is always a step which satisfies
# both conditions. If no step can be found which satisfies both
# conditions, then the algorithm usually stops when rounding
# errors prevent further progress. In this case stp only
# satisfies the sufficient decrease condition.
#
# The subroutine statement is
#
# subroutine cvsrch(df,n,x,f,s,stp,f_tol,gtol,x_tol,
# alphamin,alphamax,maxfev,info,nfev,wa)
#
# where
#
# df is the name of the user-supplied subroutine which
# calculates the function and the gradient. df must
# be declared in an external statement in the user
# calling program, and should be written as follows.
#
# function [f,g] = df(n,x) (Matlab)
# (10/2010 change in documentation)
# (derived from Fortran subroutine df(n,x,f,g))
# integer n
# f
# x(n),g(n)
#
# Calculate the function at x and
# return this value in the variable f.
# Calculate the gradient at x and
# return this vector in g.
#
# n is a positive integer input variable set to the number
# of variables.
#
# x is an Abstractarray of length n. On input it must contain the
# base point for the line search. On output it contains
# x + stp * s.
#
# f is a variable. On input it must contain the value of f
# at x. On output it contains the value of f at x + stp * s.
#
# g is an Abstractarray of length n. On input it must contain the
# gradient of f at x. On output it contains the gradient
# of f at x + stp * s.
#
# s is an input Abstractarray of length n which specifies the
# search direction.
#
# stp is a nonnegative variable. On input stp contains an
# initial estimate of a satisfactory step. On output
# stp contains the final estimate.
#
# f_tol and gtol are nonnegative input variables. Termination
# occurs when the sufficient decrease condition and the
# directional derivative condition are satisfied.
#
# x_tol is a nonnegative input variable. Termination occurs
# when the relative width of the interval of uncertainty
# is at most x_tol.
#
# alphamin and alphamax are nonnegative input variables which
# specify lower and upper bounds for the step.
#
# maxfev is a positive integer input variable. Termination
# occurs when the number of calls to df is at least
# maxfev by the end of an iteration.
#
# info is an integer output variable set as follows:
#
# info = 0 Improper input parameters.
#
# info = 1 The sufficient decrease condition and the
# directional derivative condition hold.
#
# info = 2 Relative width of the interval of uncertainty
# is at most x_tol.
#
# info = 3 Number of calls to df has reached maxfev.
#
# info = 4 The step is at the lower bound alphamin.
#
# info = 5 The step is at the upper bound alphamax.
#
# info = 6 Rounding errors prevent further progress.
# There may not be a step which satisfies the
# sufficient decrease and curvature conditions.
# Tolerances may be too small.
#
# nfev is an integer output variable set to the number of
# calls to df.
#
# Argonne National Laboratory. MINPACK Project. June 1983
# Jorge J. More', David J. Thuente
#
# **********
# Returns x, f, stp, info, nfev
# TODO: Decide whether to update x, f, g and info
# or just return step and nfev and let existing code do its job
"""
The line search implementation from:
Moré, Jorge J., and David J. Thuente
Line search algorithms with guaranteed sufficient decrease.
ACM Transactions on Mathematical Software (TOMS) 20.3 (1994): 286-307.
"""
@with_kw struct MoreThuente{T}
f_tol::T = 1e-4 # c_1 Wolfe sufficient decrease condition
gtol::T = 0.9 # c_2 Wolfe curvature condition (Recommend 0.1 for GradientDescent)
x_tol::T = 1e-8
alphamin::T = 1e-16
alphamax::T = 65536.0
maxfev::Int = 100
end
function (ls::MoreThuente)(df::AbstractObjective, x::AbstractArray{T},
s::AbstractArray{T}, alpha::Real, x_new::AbstractArray{T},
ϕ_0, dϕ_0) where T
ϕdϕ = make_ϕdϕ(df, x_new, x, s)
ls(ϕdϕ, alpha, ϕ_0, dϕ_0)
end
(ls::MoreThuente)(ϕ, dϕ, ϕdϕ, alpha, ϕ_0, dϕ_0) = ls(ϕdϕ, alpha, ϕ_0, dϕ_0)
# TODO: Should we deprecate the interface that only uses the ϕdϕ argument?
function (ls::MoreThuente)(ϕdϕ,
alpha::T,
ϕ_0,
dϕ_0) where T
@unpack f_tol, gtol, x_tol, alphamin, alphamax, maxfev = ls
iterfinitemax = -log2(eps(T))
info = 0
info_cstep = 1 # Info from step
zeroT = convert(T, 0)
#
# Check the input parameters for errors.
#
if alpha <= zeroT || f_tol < zeroT || gtol < zeroT ||
x_tol < zeroT || alphamin < zeroT || alphamax < alphamin || maxfev <= zeroT
throw(LineSearchException("Invalid parameters to MoreThuente.", 0))
end
if dϕ_0 >= zeroT
throw(LineSearchException("Search direction is not a direction of descent.", 0))
end
#
# Initialize local variables.
#
bracketed = false
stage1 = true
nfev = 0
finit = ϕ_0
dgtest = f_tol * dϕ_0
width = alphamax - alphamin
width1 = 2 * width
# Keep this across calls
#
# The variables stx, fx, dgx contain the values of the step,
# function, and directional derivative at the best step.
# The variables sty, fy, dgy contain the value of the step,
# function, and derivative at the other endpoint of
# the interval of uncertainty.
# The variables alpha, f, dg contain the values of the step,
# function, and derivative at the current step.
#
stx = zeroT
fx = finit
dgx = dϕ_0
sty = zeroT
fy = finit
dgy = dϕ_0
# START: Ensure that the initial step provides finite function values
# This is not part of the original FORTRAN code
if !isfinite(alpha)
alpha = one(T)
end
stmin = stx
stmax = alpha + 4 * (alpha - stx) # Why 4?
alpha = max(alpha, alphamin)
alpha = min(alpha, alphamax)
f, dg = ϕdϕ(alpha)
nfev += 1 # This includes calls to f() and g!()
iterfinite = 0
while (!isfinite(f) || !isfinite(dg)) && iterfinite < iterfinitemax
iterfinite += 1
alpha = alpha/2
f, dg = ϕdϕ(alpha)
nfev += 1 # This includes calls to f() and g!()
# Make stmax = (3/2)*alpha < 2alpha in the first iteration below
stx = (convert(T, 7)/8)*alpha
end
# END: Ensure that the initial step provides finite function values
while true
#
# Set the minimum and maximum steps to correspond
# to the present interval of uncertainty.
#
if bracketed
stmin = min(stx, sty)
stmax = max(stx, sty)
else
stmin = stx
stmax = alpha + 4 * (alpha - stx) # Why 4?
end
#
# Ensure stmin and stmax (used in cstep) don't violate alphamin and alphamax
# Not part of original FORTRAN translation
#
stmin = max(alphamin,stmin)
stmax = min(alphamax,stmax)
#
# Force the step to be within the bounds alphamax and alphamin
#
alpha = max(alpha, alphamin)
alpha = min(alpha, alphamax)
#
# If an unusual termination is to occur then let
# alpha be the lowest point obtained so far.
#
if (bracketed && (alpha <= stmin || alpha >= stmax)) ||
nfev >= maxfev-1 || info_cstep == 0 ||
(bracketed && stmax - stmin <= x_tol * stmax)
alpha = stx
end
#
# Evaluate the function and gradient at alpha
# and compute the directional derivative.
#
f, dg = ϕdϕ(alpha)
nfev += 1 # This includes calls to f() and g!()
if isapprox(dg, 0, atol=eps(T)) # Should add atol value to MoreThuente
return alpha, f
end
ftest1 = finit + alpha * dgtest
#
# Test for convergence.
#
# What does info_cstep stand for?
if (bracketed && (alpha <= stmin || alpha >= stmax)) || info_cstep == 0
info = 6
end
if alpha == alphamax && f <= ftest1 && dg <= dgtest
info = 5
end
if alpha == alphamin && (f > ftest1 || dg >= dgtest)
info = 4
end
if nfev >= maxfev
info = 3
end
if bracketed && stmax - stmin <= x_tol * stmax
info = 2
end
if f <= ftest1 && abs(dg) <= -gtol * dϕ_0
info = 1
end
#
# Check for termination.
#
if info != 0
return alpha, f
end
#
# In the first stage we seek a step for which the modified
# function has a nonpositive value and nonnegative derivative.
#
if stage1 && f <= ftest1 && dg >= min(f_tol, gtol) * dϕ_0
stage1 = false
end
#
# A modified function is used to predict the step only if
# we have not obtained a step for which the modified
# function has a nonpositive function value and nonnegative
# derivative, and if a lower function value has been
# obtained but the decrease is not sufficient.
#
if stage1 && f <= fx && f > ftest1
#
# Define the modified function and derivative values.
#
fm = f - alpha * dgtest
fxm = fx - stx * dgtest
fym = fy - sty * dgtest
dgm = dg - dgtest
dgxm = dgx - dgtest
dgym = dgy - dgtest
#
# Call cstep to update the interval of uncertainty
# and to compute the new step.
#
stx, fxm, dgxm,
sty, fym, dgym,
alpha, fm, dgm,
bracketed, info_cstep =
cstep(stx, fxm, dgxm, sty, fym, dgym,
alpha, fm, dgm, bracketed, stmin, stmax)
#
# Reset the function and gradient values for f.
#
fx = fxm + stx * dgtest
fy = fym + sty * dgtest
dgx = dgxm + dgtest
dgy = dgym + dgtest
else
#
# Call cstep to update the interval of uncertainty
# and to compute the new step.
#
stx, fx, dgx,
sty, fy, dgy,
alpha, f, dg,
bracketed, info_cstep =
cstep(stx, fx, dgx, sty, fy, dgy,
alpha, f, dg, bracketed, stmin, stmax)
end
#
# Force a sufficient decrease in the size of the
# interval of uncertainty.
#
if bracketed
if abs(sty - stx) >= (convert(T, 2)/3) * width1
alpha = stx + (sty - stx)/2
end
width1 = width
width = abs(sty - stx)
end
end # while
end # function
# Translation of minpack subroutine cstep
# Dianne O'Leary July 1991
#
# Subroutine cstep
#
# The purpose of cstep is to compute a safeguarded step for
# a linesearch and to update an interval of uncertainty for
# a minimizer of the function.
#
# The parameter stx contains the step with the least function
# value. The parameter stp contains the current step. It is
# assumed that the derivative at stx is negative in the
# direction of the step. If bracketed is set true then a
# minimizer has been bracketed in an interval of uncertainty
# with endpoints stx and sty.
#
# The subroutine statement is
#
# subroutine cstep(stx, fx, dgx,
# sty, fy, dgy,
# stp, f, dg,
# bracketed, alphamin, alphamax, info)
#
# where
#
# stx, fx, and dgx are variables which specify the step,
# the function, and the derivative at the best step obtained
# so far. The derivative must be negative in the direction
# of the step, that is, dgx and stp-stx must have opposite
# signs. On output these parameters are updated appropriately
#
# sty, fy, and dgy are variables which specify the step,
# the function, and the derivative at the other endpoint of
# the interval of uncertainty. On output these parameters are
# updated appropriately
#
# stp, f, and dg are variables which specify the step,
# the function, and the derivative at the current step.
# If bracketed is set true then on input stp must be
# between stx and sty. On output stp is set to the new step
#
# bracketed is a logical variable which specifies if a minimizer
# has been bracketed. If the minimizer has not been bracketed
# then on input bracketed must be set false. If the minimizer
# is bracketed then on output bracketed is set true
#
# alphamin and alphamax are input variables which specify lower
# and upper bounds for the step
#
# info is an integer output variable set as follows:
# If info = 1,2,3,4,5, then the step has been computed
# according to one of the five cases below. Otherwise
# info = 0, and this indicates improper input parameters
#
# Argonne National Laboratory. MINPACK Project. June 1983
# Jorge J. More', David J. Thuente
function cstep(stx::Real, fx::Real, dgx::Real,
sty::Real, fy::Real, dgy::Real,
alpha::Real, f::Real, dg::Real,
bracketed::Bool, alphamin::Real, alphamax::Real)
T = promote_type(typeof(stx), typeof(fx), typeof(dgx), typeof(sty), typeof(fy), typeof(dgy), typeof(alpha), typeof(f), typeof(dg), typeof(alphamin), typeof(alphamax))
zeroT = convert(T, 0)
info = 0
#
# Check the input parameters for error
#
if (bracketed && (alpha <= min(stx, sty) || alpha >= max(stx, sty))) ||
dgx * (alpha - stx) >= zeroT || alphamax < alphamin
throw(ArgumentError("Minimizer not bracketed"))
end
#
# Determine if the derivatives have opposite sign
#
sgnd = dg * (dgx / abs(dgx))
#
# First case. A higher function value.
# The minimum is bracketed. If the cubic step is closer
# to stx than the quadratic step, the cubic step is taken,
# else the average of the cubic and quadratic steps is taken
#
if f > fx
info = 1
bound = true
theta = 3 * (fx - f) / (alpha - stx) + dgx + dg
# Use s to prevent overflow/underflow of theta^2 and dgx * dg
s = max(abs(theta), abs(dgx), abs(dg))
gamma = s * sqrt((theta / s)^2 - (dgx / s) * (dg / s))
if alpha < stx
gamma = -gamma
end
p = gamma - dgx + theta
q = gamma - dgx + gamma + dg
r = p / q
alphac = stx + r * (alpha - stx)
alphaq = stx + (dgx / ((fx - f) / (alpha - stx) + dgx)) / 2 * (alpha - stx)
if abs(alphac - stx) < abs(alphaq - stx)
alphaf = alphac
else
alphaf = (alphac + alphaq) / 2
end
bracketed = true
#
# Second case. A lower function value and derivatives of
# opposite sign. The minimum is bracketed. If the cubic
# step is closer to stx than the quadratic (secant) step,
# the cubic step is taken, else the quadratic step is taken
#
elseif sgnd < zeroT
info = 2
bound = false
theta = 3 * (fx - f) / (alpha - stx) + dgx + dg
# Use s to prevent overflow/underflow of theta^2 and dgx * dg
s = max(abs(theta), abs(dgx), abs(dg))
gamma = s * sqrt((theta / s)^2 - (dgx / s) * (dg / s))
if alpha > stx
gamma = -gamma
end
p = gamma - dg + theta
q = gamma - dg + gamma + dgx
r = p / q
alphac = alpha + r * (stx - alpha)
alphaq = alpha + (dg / (dg - dgx)) * (stx - alpha)
if abs(alphac - alpha) > abs(alphaq - alpha)
alphaf = alphac
else
alphaf = alphaq
end
bracketed = true
#
# Third case. A lower function value, derivatives of the
# same sign, and the magnitude of the derivative decreases.
# The cubic step is only used if the cubic tends to infinity
# in the direction of the step or if the minimum of the cubic
# is beyond alpha. Otherwise the cubic step is defined to be
# either alphamin or alphamax. The quadratic (secant) step is also
# computed and if the minimum is bracketed then the the step
# closest to stx is taken, else the step farthest away is taken
#
elseif abs(dg) < abs(dgx)
info = 3
bound = true
theta = 3 * (fx - f) / (alpha - stx) + dgx + dg
# Use s to prevent overflow/underflow of theta^2 and dgx * dg
s = max(abs(theta), abs(dgx), abs(dg))
#
# The case gamma = 0 only arises if the cubic does not tend
# to infinity in the direction of the step
#
# # Use NaNMath in case s == zero(s)
gamma = s * sqrt(NaNMath.max(zero(s), (theta / s)^2 - (dgx / s) * (dg / s)))
if alpha > stx
gamma = -gamma
end
p = gamma - dg + theta
q = gamma + dgx - dg + gamma
r = p / q
if r < zeroT && gamma != zeroT
alphac = alpha + r * (stx - alpha)
elseif alpha > stx
alphac = alphamax
else
alphac = alphamin
end
alphaq = alpha + (dg / (dg - dgx)) * (stx - alpha)
if bracketed
if abs(alpha - alphac) < abs(alpha - alphaq)
alphaf = alphac
else
alphaf = alphaq
end
else
if abs(alpha - alphac) > abs(alpha - alphaq)
alphaf = alphac
else
alphaf = alphaq
end
end
#
# Fourth case. A lower function value, derivatives of the
# same sign, and the magnitude of the derivative does
# not decrease. If the minimum is not bracketed, the step
# is either alphamin or alphamax, else the cubic step is taken
#
else
info = 4
bound = false
if bracketed
theta = 3 * (f - fy) / (sty - alpha) + dgy + dg
# Use s to prevent overflow/underflow of theta^2 and dgy * dg
s = max(abs(theta), abs(dgy), abs(dg))
gamma = s * sqrt((theta / s)^2 - (dgy / s) * (dg / s))
if alpha > sty
gamma = -gamma
end
p = gamma - dg + theta
q = gamma - dg + gamma + dgy
r = p / q
alphac = alpha + r * (sty - alpha)
alphaf = alphac
elseif alpha > stx
alphaf = alphamax
else
alphaf = alphamin
end
end
#
# Update the interval of uncertainty. This update does not
# depend on the new step or the case analysis above
#
if f > fx
sty = alpha
fy = f
dgy = dg
else
if sgnd < zeroT
sty = stx
fy = fx
dgy = dgx
end
stx = alpha
fx = f
dgx = dg
end
#
# Compute the new step and safeguard it
#
alphaf = min(alphamax, alphaf)
alphaf = max(alphamin, alphaf)
alpha = alphaf
if bracketed && bound
if sty > stx
alpha = min(stx + (convert(T, 2)/3) * (sty - stx), alpha)
else
alpha = max(stx + (convert(T, 2)/3) * (sty - stx), alpha)
end
end
return stx, fx, dgx, sty, fy, dgy, alpha, f, dg, bracketed, info
end
esatta := proc( fun )
local res, alpha;
#res := Optimization[Minimize](
res := Optimization[NLPSolve](
fun(alpha),
{alpha >= 0, alpha <= 3},
#initialpoint={alpha=1},
iterationlimit=50
):
subs(res[2],alpha);
end proc:
doplot := proc( f_in, df_in, alpha, amax)
local f0, df0, x, AA, BB, CC, DD;
f0 := evalf(f_in(0));
df0 := evalf(df_in(0));
AA := plot(f_in(x),x=0..amax);
BB := plot([[0,f0],[amax,f0+amax*rho*df0]],color="LimeGreen");
CC := plot([[0,f0],[amax,f0+amax*sigma*df0]],color="blue");
DD := plot([[alpha,f_in(alpha)]],color="red",style = point);
display(AA,BB,CC,DD);
end;
doplot2 := proc( f_in, df_in, alpha, amax, A_list, B_list )
local i, f0, df0, x, AA, BB, CC, DD, EE;
f0 := evalf(f_in(0));
df0 := evalf(df_in(0));
AA := plot(f_in(x),x=0..amax);
BB := plot([[0,f0],[amax,f0+amax*rho*df0]],color="LimeGreen");
CC := plot([[0,f0],[amax,f0+amax*sigma*df0]],color="blue");
DD := plot([[alpha,f_in(alpha)]],color="red",style = point);
EE := plot([seq([[A_list[i],-i/5],[B_list[i],-i/5]],i=1..nops(A_list))],color="black");
display(AA,BB,CC,DD,EE);
end;
end module:
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% UMB-CS110-2015S: Introduction to Computing
% Copyright 2015 Pejman Ghorbanzade <[email protected]>
% Creative Commons Attribution-ShareAlike 4.0 International License
% More info: https://github.com/ghorbanzade/UMB-CS110-2015S
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\def \topDirectory {.}
\def \texDirectory {\topDirectory/src/main/tex}
\documentclass[12pt,letterpaper,twoside]{article}
\usepackage{\texDirectory/template/style/directives}
\usepackage{\texDirectory/template/style/assignment}
\input{\texDirectory/template/config}
\begin{document}
\doc{title}{Assignment 5}
\doc{date-pub}{Apr 19, 2015 at 00:00 AM}
\doc{date-due}{Apr 30, 2015 at 05:30 PM}
\doc{points}{8}
\prepare{header}
\section*{Question 1}
Write a program \texttt{FlightTest.java} that controls two airplanes, one \texttt{plane1} a commercial plane from \texttt{Eagle} company and one \texttt{plane2}, a fighter-bomber from \texttt{Dragon} company. All airplanes fly at some altitude and with some speed. They take off and land. Just as bombers may drop bomb (if they have any) while they are in sky, commercials can board passengers (as much as their capacity allows) while grounded.
Assuming all planes made by \texttt{Eagle} have 300 seats, fly at 39000 ft and 550 mph and all planes made by \texttt{Dragon} have 2 bomb bays and fly at 30000 ft and 1000 mph, develop classes \texttt{Aircraft}, \texttt{Bomber}, \texttt{Commercial}, \texttt{Eagle} and \texttt{Dragon} and use them in a program \texttt{FlightTest.java}.
\section*{Question 2}
Your manager has just learned basic concepts of interfaces and abstraction in Java and has asked you to implement the methods in the following interface in a class \texttt{ArraySort.java}. Write a program \texttt{ArraySortTest.java} to show him how to use your class to initialize, shuffle and sort an array. Attach a file \texttt{note.txt} to briefly explain why this is not a good practice and recommend a better alternative.
\lstset{language=java}
\begin{lstlisting}
public interface sortAndUnsort {
// sorts the array using insertion sort
public int[] sortInsertion(int[] array);
// shuffles the array
public int[] shuffle(int[] array);
// prints the array elements
public void print(int[] array);
// initialize array from firstElement to lastElement
public int[] init(int firstElement, int lastElement);
}
\end{lstlisting}
\prepare{footer}
\end{document}
|
function FN = flipped_normals(V,F)
%FLIPPED_NORMALS Compute the flipped normals of a triangle mesh
%
% FN = flipped_normals(V,F);
%
% Inputs:
% V,F triangle mesh
% Outputs:
% FN flipped normals of the mesh V,N
%Compute per-face normals.
N = normals(V,F);
N = N ./ normrow(V,F);
%Flip the per-face normals.
FN = -N;
end
|
If $f$ and $g$ are bounded functions on a set $S$, then the function $x \mapsto \|f(x) - g(x)\|$ is bounded on $S$.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.