text
stringlengths 0
3.34M
|
---|
Formal statement is: lemma eucl_rel_poly_add_left: assumes "eucl_rel_poly x y (q, r)" assumes "eucl_rel_poly x' y (q', r')" shows "eucl_rel_poly (x + x') y (q + q', r + r')" Informal statement is: If $x$ and $x'$ are both related to $y$ by the Euclidean relation, then $x + x'$ is related to $y$ by the Euclidean relation. |
[STATEMENT]
lemma pickQFreshEnv_card_of:
assumes Vvar: "|V| <o |UNIV :: 'var set|" and XSvar: "|XS| <o |UNIV :: 'var set|" and
good: "\<forall> X \<in> XS. qGood X" and
Rhovar: "|Rho| <o |UNIV :: 'var set|" and RhoGood: "\<forall> rho \<in> Rho. qGoodEnv rho"
shows
"pickQFreshEnv xs V XS Rho \<notin> V \<and>
(\<forall> X \<in> XS. qFresh xs (pickQFreshEnv xs V XS Rho) X) \<and>
(\<forall> rho \<in> Rho. qFreshEnv xs (pickQFreshEnv xs V XS Rho) rho)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. pickQFreshEnv xs V XS Rho \<notin> V \<and> (\<forall>X\<in>XS. qFresh xs (pickQFreshEnv xs V XS Rho) X) \<and> (\<forall>rho\<in>Rho. qFreshEnv xs (pickQFreshEnv xs V XS Rho) rho)
[PROOF STEP]
proof-
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. pickQFreshEnv xs V XS Rho \<notin> V \<and> (\<forall>X\<in>XS. qFresh xs (pickQFreshEnv xs V XS Rho) X) \<and> (\<forall>rho\<in>Rho. qFreshEnv xs (pickQFreshEnv xs V XS Rho) rho)
[PROOF STEP]
let ?z =" pickQFreshEnv xs V XS Rho"
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. pickQFreshEnv xs V XS Rho \<notin> V \<and> (\<forall>X\<in>XS. qFresh xs (pickQFreshEnv xs V XS Rho) X) \<and> (\<forall>rho\<in>Rho. qFreshEnv xs (pickQFreshEnv xs V XS Rho) rho)
[PROOF STEP]
let ?V2 = "\<Union> rho \<in> Rho. {x. rho xs x \<noteq> None}"
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. pickQFreshEnv xs V XS Rho \<notin> V \<and> (\<forall>X\<in>XS. qFresh xs (pickQFreshEnv xs V XS Rho) X) \<and> (\<forall>rho\<in>Rho. qFreshEnv xs (pickQFreshEnv xs V XS Rho) rho)
[PROOF STEP]
let ?W = "V \<union> ?V2"
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. pickQFreshEnv xs V XS Rho \<notin> V \<and> (\<forall>X\<in>XS. qFresh xs (pickQFreshEnv xs V XS Rho) X) \<and> (\<forall>rho\<in>Rho. qFreshEnv xs (pickQFreshEnv xs V XS Rho) rho)
[PROOF STEP]
let ?XS2 = "\<Union> rho \<in> Rho. {X. \<exists> ys y. rho ys y = Some X}"
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. pickQFreshEnv xs V XS Rho \<notin> V \<and> (\<forall>X\<in>XS. qFresh xs (pickQFreshEnv xs V XS Rho) X) \<and> (\<forall>rho\<in>Rho. qFreshEnv xs (pickQFreshEnv xs V XS Rho) rho)
[PROOF STEP]
let ?YS = "XS \<union> ?XS2"
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. pickQFreshEnv xs V XS Rho \<notin> V \<and> (\<forall>X\<in>XS. qFresh xs (pickQFreshEnv xs V XS Rho) X) \<and> (\<forall>rho\<in>Rho. qFreshEnv xs (pickQFreshEnv xs V XS Rho) rho)
[PROOF STEP]
have "|?W| <o |UNIV :: 'var set|"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. |V \<union> (\<Union>rho\<in>Rho. {x. rho xs x \<noteq> None})| <o |UNIV|
[PROOF STEP]
proof-
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. |V \<union> (\<Union>rho\<in>Rho. {x. rho xs x \<noteq> None})| <o |UNIV|
[PROOF STEP]
have "\<forall> rho \<in> Rho. |{x. rho xs x \<noteq> None}| <o |UNIV :: 'var set|"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>rho\<in>Rho. |{x. rho xs x \<noteq> None}| <o |UNIV|
[PROOF STEP]
using RhoGood
[PROOF STATE]
proof (prove)
using this:
Ball Rho qGoodEnv
goal (1 subgoal):
1. \<forall>rho\<in>Rho. |{x. rho xs x \<noteq> None}| <o |UNIV|
[PROOF STEP]
unfolding qGoodEnv_iff
[PROOF STATE]
proof (prove)
using this:
\<forall>rho\<in>Rho. (\<forall>xs. liftAll qGood (rho xs)) \<and> (\<forall>ys. |{y. rho ys y \<noteq> None}| <o |UNIV|) \<and> |{X. \<exists>ys y. rho ys y = Some X}| <o |UNIV|
goal (1 subgoal):
1. \<forall>rho\<in>Rho. |{x. rho xs x \<noteq> None}| <o |UNIV|
[PROOF STEP]
using qGoodEnv_iff
[PROOF STATE]
proof (prove)
using this:
\<forall>rho\<in>Rho. (\<forall>xs. liftAll qGood (rho xs)) \<and> (\<forall>ys. |{y. rho ys y \<noteq> None}| <o |UNIV|) \<and> |{X. \<exists>ys y. rho ys y = Some X}| <o |UNIV|
qGoodEnv ?rho = ((\<forall>xs. liftAll qGood (?rho xs)) \<and> (\<forall>ys. |{y. ?rho ys y \<noteq> None}| <o |UNIV|) \<and> |{X. \<exists>ys y. ?rho ys y = Some X}| <o |UNIV|)
goal (1 subgoal):
1. \<forall>rho\<in>Rho. |{x. rho xs x \<noteq> None}| <o |UNIV|
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
\<forall>rho\<in>Rho. |{x. rho xs x \<noteq> None}| <o |UNIV|
goal (1 subgoal):
1. |V \<union> (\<Union>rho\<in>Rho. {x. rho xs x \<noteq> None})| <o |UNIV|
[PROOF STEP]
hence "|?V2| <o |UNIV :: 'var set|"
[PROOF STATE]
proof (prove)
using this:
\<forall>rho\<in>Rho. |{x. rho xs x \<noteq> None}| <o |UNIV|
goal (1 subgoal):
1. |\<Union>rho\<in>Rho. {x. rho xs x \<noteq> None}| <o |UNIV|
[PROOF STEP]
using var_regular_INNER Rhovar
[PROOF STATE]
proof (prove)
using this:
\<forall>rho\<in>Rho. |{x. rho xs x \<noteq> None}| <o |UNIV|
regular |UNIV|
|Rho| <o |UNIV|
goal (1 subgoal):
1. |\<Union>rho\<in>Rho. {x. rho xs x \<noteq> None}| <o |UNIV|
[PROOF STEP]
by (auto simp add: regular_UNION)
[PROOF STATE]
proof (state)
this:
|\<Union>rho\<in>Rho. {x. rho xs x \<noteq> None}| <o |UNIV|
goal (1 subgoal):
1. |V \<union> (\<Union>rho\<in>Rho. {x. rho xs x \<noteq> None})| <o |UNIV|
[PROOF STEP]
thus ?thesis
[PROOF STATE]
proof (prove)
using this:
|\<Union>rho\<in>Rho. {x. rho xs x \<noteq> None}| <o |UNIV|
goal (1 subgoal):
1. |V \<union> (\<Union>rho\<in>Rho. {x. rho xs x \<noteq> None})| <o |UNIV|
[PROOF STEP]
using var_infinite_INNER Vvar card_of_Un_ordLess_infinite
[PROOF STATE]
proof (prove)
using this:
|\<Union>rho\<in>Rho. {x. rho xs x \<noteq> None}| <o |UNIV|
infinite UNIV
|V| <o |UNIV|
\<lbrakk>infinite ?C; |?A| <o |?C|; |?B| <o |?C|\<rbrakk> \<Longrightarrow> |?A \<union> ?B| <o |?C|
goal (1 subgoal):
1. |V \<union> (\<Union>rho\<in>Rho. {x. rho xs x \<noteq> None})| <o |UNIV|
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
|V \<union> (\<Union>rho\<in>Rho. {x. rho xs x \<noteq> None})| <o |UNIV|
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
|V \<union> (\<Union>rho\<in>Rho. {x. rho xs x \<noteq> None})| <o |UNIV|
goal (1 subgoal):
1. pickQFreshEnv xs V XS Rho \<notin> V \<and> (\<forall>X\<in>XS. qFresh xs (pickQFreshEnv xs V XS Rho) X) \<and> (\<forall>rho\<in>Rho. qFreshEnv xs (pickQFreshEnv xs V XS Rho) rho)
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
|V \<union> (\<Union>rho\<in>Rho. {x. rho xs x \<noteq> None})| <o |UNIV|
goal (1 subgoal):
1. pickQFreshEnv xs V XS Rho \<notin> V \<and> (\<forall>X\<in>XS. qFresh xs (pickQFreshEnv xs V XS Rho) X) \<and> (\<forall>rho\<in>Rho. qFreshEnv xs (pickQFreshEnv xs V XS Rho) rho)
[PROOF STEP]
have "|?YS| <o |UNIV :: 'var set|"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. |XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X})| <o |UNIV|
[PROOF STEP]
proof-
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. |XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X})| <o |UNIV|
[PROOF STEP]
have "\<forall> rho \<in> Rho. |{X. \<exists> ys y. rho ys y = Some X}| <o |UNIV :: 'var set|"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>rho\<in>Rho. |{X. \<exists>ys y. rho ys y = Some X}| <o |UNIV|
[PROOF STEP]
using RhoGood
[PROOF STATE]
proof (prove)
using this:
Ball Rho qGoodEnv
goal (1 subgoal):
1. \<forall>rho\<in>Rho. |{X. \<exists>ys y. rho ys y = Some X}| <o |UNIV|
[PROOF STEP]
unfolding qGoodEnv_iff
[PROOF STATE]
proof (prove)
using this:
\<forall>rho\<in>Rho. (\<forall>xs. liftAll qGood (rho xs)) \<and> (\<forall>ys. |{y. rho ys y \<noteq> None}| <o |UNIV|) \<and> |{X. \<exists>ys y. rho ys y = Some X}| <o |UNIV|
goal (1 subgoal):
1. \<forall>rho\<in>Rho. |{X. \<exists>ys y. rho ys y = Some X}| <o |UNIV|
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
\<forall>rho\<in>Rho. |{X. \<exists>ys y. rho ys y = Some X}| <o |UNIV|
goal (1 subgoal):
1. |XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X})| <o |UNIV|
[PROOF STEP]
hence "|?XS2| <o |UNIV :: 'var set|"
[PROOF STATE]
proof (prove)
using this:
\<forall>rho\<in>Rho. |{X. \<exists>ys y. rho ys y = Some X}| <o |UNIV|
goal (1 subgoal):
1. |\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X}| <o |UNIV|
[PROOF STEP]
using var_regular_INNER Rhovar
[PROOF STATE]
proof (prove)
using this:
\<forall>rho\<in>Rho. |{X. \<exists>ys y. rho ys y = Some X}| <o |UNIV|
regular |UNIV|
|Rho| <o |UNIV|
goal (1 subgoal):
1. |\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X}| <o |UNIV|
[PROOF STEP]
by (auto simp add: regular_UNION)
[PROOF STATE]
proof (state)
this:
|\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X}| <o |UNIV|
goal (1 subgoal):
1. |XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X})| <o |UNIV|
[PROOF STEP]
thus ?thesis
[PROOF STATE]
proof (prove)
using this:
|\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X}| <o |UNIV|
goal (1 subgoal):
1. |XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X})| <o |UNIV|
[PROOF STEP]
using var_infinite_INNER XSvar card_of_Un_ordLess_infinite
[PROOF STATE]
proof (prove)
using this:
|\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X}| <o |UNIV|
infinite UNIV
|XS| <o |UNIV|
\<lbrakk>infinite ?C; |?A| <o |?C|; |?B| <o |?C|\<rbrakk> \<Longrightarrow> |?A \<union> ?B| <o |?C|
goal (1 subgoal):
1. |XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X})| <o |UNIV|
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
|XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X})| <o |UNIV|
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
|XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X})| <o |UNIV|
goal (1 subgoal):
1. pickQFreshEnv xs V XS Rho \<notin> V \<and> (\<forall>X\<in>XS. qFresh xs (pickQFreshEnv xs V XS Rho) X) \<and> (\<forall>rho\<in>Rho. qFreshEnv xs (pickQFreshEnv xs V XS Rho) rho)
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
|XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X})| <o |UNIV|
goal (1 subgoal):
1. pickQFreshEnv xs V XS Rho \<notin> V \<and> (\<forall>X\<in>XS. qFresh xs (pickQFreshEnv xs V XS Rho) X) \<and> (\<forall>rho\<in>Rho. qFreshEnv xs (pickQFreshEnv xs V XS Rho) rho)
[PROOF STEP]
have "\<forall> Y \<in> ?YS. qGood Y"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. Ball (XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X})) qGood
[PROOF STEP]
using good RhoGood
[PROOF STATE]
proof (prove)
using this:
Ball XS qGood
Ball Rho qGoodEnv
goal (1 subgoal):
1. Ball (XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X})) qGood
[PROOF STEP]
unfolding qGoodEnv_iff liftAll_def
[PROOF STATE]
proof (prove)
using this:
Ball XS qGood
\<forall>rho\<in>Rho. (\<forall>xs i v. rho xs i = Some v \<longrightarrow> qGood v) \<and> (\<forall>ys. |{y. rho ys y \<noteq> None}| <o |UNIV|) \<and> |{X. \<exists>ys y. rho ys y = Some X}| <o |UNIV|
goal (1 subgoal):
1. Ball (XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X})) qGood
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
Ball (XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X})) qGood
goal (1 subgoal):
1. pickQFreshEnv xs V XS Rho \<notin> V \<and> (\<forall>X\<in>XS. qFresh xs (pickQFreshEnv xs V XS Rho) X) \<and> (\<forall>rho\<in>Rho. qFreshEnv xs (pickQFreshEnv xs V XS Rho) rho)
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
|V \<union> (\<Union>rho\<in>Rho. {x. rho xs x \<noteq> None})| <o |UNIV|
|XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X})| <o |UNIV|
Ball (XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X})) qGood
[PROOF STEP]
have "?z \<notin> ?W \<and> (\<forall> Y \<in> ?YS. qFresh xs ?z Y)"
[PROOF STATE]
proof (prove)
using this:
|V \<union> (\<Union>rho\<in>Rho. {x. rho xs x \<noteq> None})| <o |UNIV|
|XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X})| <o |UNIV|
Ball (XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X})) qGood
goal (1 subgoal):
1. pickQFreshEnv xs V XS Rho \<notin> V \<union> (\<Union>rho\<in>Rho. {x. rho xs x \<noteq> None}) \<and> (\<forall>Y\<in>XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X}). qFresh xs (pickQFreshEnv xs V XS Rho) Y)
[PROOF STEP]
unfolding pickQFreshEnv_def
[PROOF STATE]
proof (prove)
using this:
|V \<union> (\<Union>rho\<in>Rho. {x. rho xs x \<noteq> None})| <o |UNIV|
|XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X})| <o |UNIV|
Ball (XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X})) qGood
goal (1 subgoal):
1. pickQFresh xs (V \<union> (\<Union>rho\<in>Rho. {x. rho xs x \<noteq> None})) (XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X})) \<notin> V \<union> (\<Union>rho\<in>Rho. {x. rho xs x \<noteq> None}) \<and> (\<forall>Y\<in>XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X}). qFresh xs (pickQFresh xs (V \<union> (\<Union>rho\<in>Rho. {x. rho xs x \<noteq> None})) (XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X}))) Y)
[PROOF STEP]
using pickQFresh_card_of[of ?W ?YS]
[PROOF STATE]
proof (prove)
using this:
|V \<union> (\<Union>rho\<in>Rho. {x. rho xs x \<noteq> None})| <o |UNIV|
|XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X})| <o |UNIV|
Ball (XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X})) qGood
\<lbrakk>|V \<union> (\<Union>rho\<in>Rho. {x. rho xs x \<noteq> None})| <o |UNIV|; |XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X})| <o |UNIV|; Ball (XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X})) qGood\<rbrakk> \<Longrightarrow> pickQFresh ?xs (V \<union> (\<Union>rho\<in>Rho. {x. rho xs x \<noteq> None})) (XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X})) \<notin> V \<union> (\<Union>rho\<in>Rho. {x. rho xs x \<noteq> None}) \<and> (\<forall>X\<in>XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X}). qAFresh ?xs (pickQFresh ?xs (V \<union> (\<Union>rho\<in>Rho. {x. rho xs x \<noteq> None})) (XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X}))) X \<and> qFresh ?xs (pickQFresh ?xs (V \<union> (\<Union>rho\<in>Rho. {x. rho xs x \<noteq> None})) (XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X}))) X)
goal (1 subgoal):
1. pickQFresh xs (V \<union> (\<Union>rho\<in>Rho. {x. rho xs x \<noteq> None})) (XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X})) \<notin> V \<union> (\<Union>rho\<in>Rho. {x. rho xs x \<noteq> None}) \<and> (\<forall>Y\<in>XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X}). qFresh xs (pickQFresh xs (V \<union> (\<Union>rho\<in>Rho. {x. rho xs x \<noteq> None})) (XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X}))) Y)
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
pickQFreshEnv xs V XS Rho \<notin> V \<union> (\<Union>rho\<in>Rho. {x. rho xs x \<noteq> None}) \<and> (\<forall>Y\<in>XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X}). qFresh xs (pickQFreshEnv xs V XS Rho) Y)
goal (1 subgoal):
1. pickQFreshEnv xs V XS Rho \<notin> V \<and> (\<forall>X\<in>XS. qFresh xs (pickQFreshEnv xs V XS Rho) X) \<and> (\<forall>rho\<in>Rho. qFreshEnv xs (pickQFreshEnv xs V XS Rho) rho)
[PROOF STEP]
thus ?thesis
[PROOF STATE]
proof (prove)
using this:
pickQFreshEnv xs V XS Rho \<notin> V \<union> (\<Union>rho\<in>Rho. {x. rho xs x \<noteq> None}) \<and> (\<forall>Y\<in>XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X}). qFresh xs (pickQFreshEnv xs V XS Rho) Y)
goal (1 subgoal):
1. pickQFreshEnv xs V XS Rho \<notin> V \<and> (\<forall>X\<in>XS. qFresh xs (pickQFreshEnv xs V XS Rho) X) \<and> (\<forall>rho\<in>Rho. qFreshEnv xs (pickQFreshEnv xs V XS Rho) rho)
[PROOF STEP]
unfolding qFreshEnv_def liftAll_def
[PROOF STATE]
proof (prove)
using this:
pickQFreshEnv xs V XS Rho \<notin> V \<union> (\<Union>rho\<in>Rho. {x. rho xs x \<noteq> None}) \<and> (\<forall>Y\<in>XS \<union> (\<Union>rho\<in>Rho. {X. \<exists>ys y. rho ys y = Some X}). qFresh xs (pickQFreshEnv xs V XS Rho) Y)
goal (1 subgoal):
1. pickQFreshEnv xs V XS Rho \<notin> V \<and> (\<forall>X\<in>XS. qFresh xs (pickQFreshEnv xs V XS Rho) X) \<and> (\<forall>rho\<in>Rho. rho xs (pickQFreshEnv xs V XS Rho) = None \<and> (\<forall>xsa i v. rho xsa i = Some v \<longrightarrow> qFresh xs (pickQFreshEnv xs V XS Rho) v))
[PROOF STEP]
by(auto)
[PROOF STATE]
proof (state)
this:
pickQFreshEnv xs V XS Rho \<notin> V \<and> (\<forall>X\<in>XS. qFresh xs (pickQFreshEnv xs V XS Rho) X) \<and> (\<forall>rho\<in>Rho. qFreshEnv xs (pickQFreshEnv xs V XS Rho) rho)
goal:
No subgoals!
[PROOF STEP]
qed |
/*----------------------------------------------------------------------------
/
/ Filename: fits_wavelet.c
/ Author: Jay Billings
/ Author's email: [email protected]
/ Description: This program will perform a Debauchies wavelet transform on
/ an input image and turn off the wavelet coefficients up to
/ a certain percentage of the total size.
/
/ Usage:
/ ./fits_wavelet <image> <limit>
/
/ <image> should be an image in FITS format and <limit>
/ should be a number between 0.0 and 1.0.
/
/ Output:
/ filtered_<image>
/
/ The output image is also in the FITS format and is readily
/ viewable in FV, available from the NASA website, or the
/ Sky Image Processor, useable as a java applet from Dr.
/ John Simonetti, Virginia Tech,
/
/ http://www.phys.vt.edu/~jhs/SIP.
/
/ This code requires the CFITSIO library and the GNU Scientific
/ Library. Both are freely available on the internet. This code
/ compiles fine with gcc-4.1.2 using
/
/ gcc -o fits_wavelet fits_wavelet.c -lm -lgsl -lgslcblas
/ -lcfitiso
/
/ Copyright (c) 2008 Jay Jay Billings
/
/ This program is free software; you can redistribute it and/or modify
/ it under the terms of the GNU General Public License as published by
/ the Free Software Foundation; either version 2 of the License, or
/ (at your option) any later version.
/
/ This program is distributed in the hope that it will be useful,
/ but WITHOUT ANY WARRANTY; without even the implied warranty of
/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/ GNU General Public License for more details.
/
/ You should have received a copy of the GNU General Public License
/ along with this program; if not, write to the Free Software
/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
/
/ The license is also available at:
/
/ http://www.gnu.org/copyleft/gpl.html .
/
/ Date: 2008/03/24
/
*///--------------------------------------------------------------------------
#include <string.h>
#include <stdio.h>
#include <fitsio.h>
#include <gsl/gsl_wavelet.h>
#include <gsl/gsl_sort.h>
#include <math.h>
void read_image(double *,char *,int []);
void write_image(double *, char *, int []);
int main(int argc, char *argv[]) {
int i, j, size[3], a;
double f, limit, *pixels, *pixels_copy;
gsl_wavelet *w;
gsl_wavelet_workspace *work;
size_t *p;
// Check to make sure that the inputs are OK.
if (argc < 3) {
printf("You need to specify a file! \n\nUsage: ");
printf("\t fits_wavelet <input_file> <limit>\n\n");
exit(0);
}
f = atof(argv[2]);
if (f >= 1.0) {
printf("The limit must be between 0.0 and 1.0!\n\n");
printf("Try something else! (Like 0.85...)\n");
exit(0);
}
// Allocate some storage arrays. The maximum size is currently
// set at 1024*1024, or 2^20, initilized to zero.
if (!(pixels = calloc(1024*1024,sizeof(double)))) {
printf("Memory allocation error\n");
exit(0);
}
if (!(pixels_copy = calloc(1024*1024,sizeof(double)))) {
printf("Memory allocation error\n");
exit(0);
}
if (!(p = malloc(1024*1024*sizeof(size_t)))) {
printf("Memory allocation error\n");
exit(0);
}
// Read the image into the pixels array.
read_image(pixels,argv[1],size);
// Allocate the wavelet workspace.
w = gsl_wavelet_alloc(gsl_wavelet_daubechies,20);
work = gsl_wavelet_workspace_alloc(1024*1024);
// Perform the wavelet transfer.
gsl_wavelet_transform_forward(w,pixels,1,1024,work);
// Make a copy of the pixels array and sort it.
for (i = 0; i < size[2]; ++i) {
pixels_copy[i] = fabs(pixels[i]);
}
gsl_sort_index(p,pixels_copy,1,size[0]*size[1]);
// Loop over the wavelet coefficients and turn them off
// up to a certain limit.
limit = (double) size[2] * f;
for (i = 0; i < (int) limit; ++i) {
pixels[p[i]] = 0.0;
}
// Perform the inverse transform.
gsl_wavelet_transform_inverse(w,pixels,1,1024,work);
// Write the image.
write_image(pixels,argv[1],size);
// Free all the memory and exit.
gsl_wavelet_free(w);
gsl_wavelet_workspace_free(work);
free(pixels);free(pixels_copy);free(p);
return 0;
}
// This subroutine was adapted from documentation provided on the FITSIO website.
void read_image(double *pixels_vector, char *filename, int size[3])
{
fitsfile *fptr; /* FITS file pointer, defined in fitsio.h */
int status = 0; /* CFITSIO status value MUST be initialized to zero! */
int bitpix, naxis, ii, anynul,a;
long naxes[2] = {1,1}, fpixel[2] = {1,1};
double *pixels;
char format[20], hdformat[20];
/*if (argc != 2) {
printf("Usage: imlist filename[ext][section filter] \n");
printf("\n");
printf("List the the pixel values in a FITS image \n");
printf("\n");
printf("Example: \n");
printf(" imlist image.fits - list the whole image\n");
printf(" imlist image.fits[100:110,400:410] - list a section\n");
printf(" imlist table.fits[2][bin (x,y) = 32] - list the pixels in\n");
printf(" an image constructed from a 2D histogram of X and Y\n");
printf(" columns in a table with a binning factor = 32\n");
return(0);
}*/
if (!fits_open_file(&fptr, filename, READONLY, &status))
{
if (!fits_get_img_param(fptr, 2, &bitpix, &naxis, naxes, &status) )
{
if (naxis > 2 || naxis == 0)
printf("Error: only 1D or 2D images are supported\n");
else
{
/* get memory for 1 row */
if (!(pixels = malloc(naxes[0] * sizeof(double)))) {
printf("Memory allocation error\n");
exit(0);
}
if (bitpix > 0) { /* set the default output format string */
strcpy(hdformat, " %7d");
strcpy(format, " %7.0f");
} else {
strcpy(hdformat, " %15d");
strcpy(format, " %15.5f");
}
//printf("\n "); /* print column header */
//for (ii = 1; ii <= naxes[0]; ii++)
// printf(hdformat, ii);
//printf("\n"); /* terminate header line */
/* loop over all the rows in the image, top to bottom */
a = 0;
for (fpixel[1] = naxes[1]; fpixel[1] >= 1; fpixel[1]--)
{
if (fits_read_pix(fptr, TDOUBLE, fpixel, naxes[0], NULL,
pixels, NULL, &status) ) /* read row of pixels */
break; /* jump out of loop on error */
// printf(" %4d \n",fpixel[1]); /* print row number */
for (ii = 0; ii < naxes[0]; ii++) {
pixels_vector[a] = pixels[ii];
// printf(format, pixels_vector[a]); /* print each value */
// printf(" %d\n",a); /* terminate line */
++a;
}
}
size[0] = naxes[0];
size[1] = naxes[1];
size[2] = naxes[0]*naxes[1];
free(pixels);
}
}
fits_close_file(fptr, &status);
}
if (status) {
fits_report_error(stderr, status); /* print any error message */
exit(0);
}
//return(status);
return;
}
void write_image(double *pixels_vector, char *f1, int size[3]) {
fitsfile *infptr, *outfptr; /* FITS file pointer, defined in fitsio.h */
int status = 0; /* CFITSIO status value MUST be initialized to zero! */
int ii = 1;
char f2[200];
long size_l[2], fpixel[2] = {1,1};
void *pix_ptr = &pixels_vector;
size_l[0] = (long) size[0];
size_l[1] = (long) size[1];
sprintf(f2,"filtered_%s",f1);
/* Create the output file */
if (!fits_create_file(&outfptr, f2, &status) ) {
if (!fits_create_img(outfptr,32,2,size_l,&status)) {
if (!fits_write_pix(outfptr,TDOUBLE,fpixel,(long) size[2],pixels_vector \
,&status)) {
if (status == END_OF_FILE) status = 0;
}
//printf("Write status: %d \n",status);
}
fits_close_file(outfptr, &status);
}
return;
}
|
[STATEMENT]
lemma bits_one_mod_two_eq_one [simp]:
\<open>1 mod 2 = 1\<close>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (1::'a) mod (2::'a) = (1::'a)
[PROOF STEP]
by (simp add: mod2_eq_if) |
(*
* Copyright 2014, NICTA
*
* This software may be distributed and modified according to the terms of
* the GNU General Public License version 2. Note that NO WARRANTY is provided.
* See "LICENSE_GPLv2.txt" for details.
*
* @TAG(NICTA_GPL)
*)
theory Corres_C
imports
CCorresLemmas
"../../proof/crefine/$L4V_ARCH/SR_lemmas_C"
begin
abbreviation
"return_C \<equiv> CTranslation.creturn global_exn_var_'_update"
lemmas return_C_def = creturn_def
abbreviation
"return_void_C \<equiv> CTranslation.creturn_void global_exn_var_'_update"
lemmas return_void_C_def = creturn_void_def
abbreviation
"break_C \<equiv> CTranslation.cbreak global_exn_var_'_update"
lemmas breakk_C_def = cbreak_def
abbreviation
"catchbrk_C \<equiv> CTranslation.ccatchbrk global_exn_var_'"
lemmas catchbrk_C_def = ccatchbrk_def
(* This is to avoid typing this all the time \<dots> *)
abbreviation (in kernel)
"modifies_spec f \<equiv> \<forall>s. \<Gamma> \<turnstile>\<^bsub>/UNIV\<^esub> {s} Call f {t. t may_not_modify_globals s}"
section "Error monad"
(* Dealing with THROW in a nice fashion --- it is always going to be catching break or skip at the end of the function.
In retrospect, if ccatchbrk is always if ... then SKIP else THROW we are OK without the globals_update thing *)
definition
wfhandlers :: "rf_com list \<Rightarrow> bool"
where
"wfhandlers hs \<equiv> \<forall>\<Gamma> s t n. global_exn_var_' s = Return
\<and> \<Gamma> \<turnstile>\<^sub>h \<langle>hs, s\<rangle> \<Rightarrow> (n, t) \<longrightarrow> t = Normal s"
lemma wfhandlers_ccatchbrk:
"wfhandlers (catchbrk_C # hs) = wfhandlers hs"
unfolding wfhandlers_def ccatchbrk_def
apply rule
apply (intro allI impI)
apply (drule_tac x = \<Gamma> in spec)
apply ((drule spec)+, erule mp)
apply simp
apply (rule EHAbrupt)
apply rule
apply simp
apply rule
apply fastforce
apply (intro allI impI)
apply (drule_tac x = \<Gamma> in spec)
apply ((drule spec)+, erule mp)
apply simp
apply (erule conjE)
apply (erule exec_handlers.cases)
apply (fastforce elim: exec_Normal_elim_cases)+
done
lemma wfhandlers_skip:
"wfhandlers (SKIP # hs)"
unfolding wfhandlers_def
apply (intro allI impI)
apply (erule conjE)
apply (erule exec_handlers.cases)
apply (auto elim: exec_Normal_elim_cases)
done
lemmas wfhandlers_simps [simp] = wfhandlers_skip wfhandlers_ccatchbrk
lemma wfhandlersD:
"\<lbrakk>wfhandlers hs; \<Gamma> \<turnstile>\<^sub>h \<langle>hs, s\<rangle> \<Rightarrow> (n, t); global_exn_var_' s = Return\<rbrakk> \<Longrightarrow> t = Normal s"
unfolding wfhandlers_def by auto
record 'b exxf =
exflag :: word32
exstate :: errtype
exvalue :: 'b
definition
liftxf :: "(cstate \<Rightarrow> errtype) \<Rightarrow> ('a \<Rightarrow> word32) \<Rightarrow> ('a \<Rightarrow> 'b) \<Rightarrow> (cstate \<Rightarrow> 'a) \<Rightarrow> cstate \<Rightarrow> 'b exxf"
where
"liftxf et ef vf xf \<equiv> \<lambda>s. \<lparr> exflag = ef (xf s), exstate = et s, exvalue = vf (xf s) \<rparr>"
lemma exflag_liftxf [simp]:
"exflag (liftxf es sf vf xf s) = sf (xf s)"
unfolding liftxf_def by simp
lemma exstate_liftxf [simp]:
"exstate (liftxf es sf vf xf s) = es s"
unfolding liftxf_def by simp
lemma exvalue_liftxf [simp]:
"exvalue (liftxf es sf vf xf s) = vf (xf s)"
unfolding liftxf_def by simp
(* This is more or less ccorres specific, so it goes here *)
primrec
crel_sum_comb :: "('a \<Rightarrow> word32 \<Rightarrow> errtype \<Rightarrow> bool) \<Rightarrow> ('c \<Rightarrow> 'b \<Rightarrow> bool)
\<Rightarrow> ('a + 'c \<Rightarrow> 'b exxf \<Rightarrow> bool)" (infixl "\<currency>" 95)
where
"(f \<currency> g) (Inr x) y = (exflag y = scast EXCEPTION_NONE \<and> g x (exvalue y))"
| "(f \<currency> g) (Inl x) y = (exflag y \<noteq> scast EXCEPTION_NONE \<and> f x (exflag y) (exstate y))"
lemma ccorres_split_nothrowE:
fixes R' :: "cstate set"
assumes ac: "ccorres_underlying sr \<Gamma>
(f' \<currency> r') (liftxf es ef' vf' xf')
(f' \<currency> r') (liftxf es ef' vf' xf')
P P' hs a c"
and ceqv: "\<And>rv' t t'. ceqv \<Gamma> xf' rv' t t' d (d' rv')"
and bd: "\<And>rv rv'. \<lbrakk> r' rv (vf' rv'); ef' rv' = scast EXCEPTION_NONE \<rbrakk>
\<Longrightarrow> ccorres_underlying sr \<Gamma> r xf arrel axf (Q rv) (Q' rv rv') hs (b rv) (d' rv')"
and err: "\<And>err rv' err'. \<lbrakk>ef' rv' \<noteq> scast EXCEPTION_NONE; f' err (ef' rv') err' \<rbrakk>
\<Longrightarrow> ccorres_underlying sr \<Gamma> r xf arrel axf (QE err) (Q'' err rv' err') hs
(throwError err) (d' rv')"
and valid: "\<lbrace>R\<rbrace> a \<lbrace>Q\<rbrace>,\<lbrace>QE\<rbrace>"
and valid': "\<Gamma> \<turnstile>\<^bsub>/F\<^esub> R' c ({s. (ef' (xf' s) = scast EXCEPTION_NONE \<longrightarrow> (\<forall>rv. r' rv (vf' (xf' s)) \<longrightarrow> s \<in> Q' rv (xf' s))) \<and>
(ef' (xf' s) \<noteq> scast EXCEPTION_NONE \<longrightarrow> (\<forall>err. f' err (ef' (xf' s)) (es s) \<longrightarrow> s \<in> Q'' err (xf' s) (es s)))})" (is "\<Gamma> \<turnstile>\<^bsub>/F\<^esub> R' c {s. ?Q'' s}")
shows "ccorres_underlying sr \<Gamma> r xf arrel axf (P and R) (P' \<inter> R') hs
(a >>=E (\<lambda>rv. b rv)) (c ;; d)"
unfolding bindE_def
apply (rule_tac R="case_sum QE Q"
and R'="\<lambda>rv. {s. s \<in> case_sum QE' QR' rv (xf' s)}" for QE' QR'
in ccorres_master_split_hs)
apply (rule ac)
apply (rule ccorres_abstract[OF ceqv])
apply (case_tac rv, simp_all add: lift_def)
apply (rule ccorres_abstract[where xf'=es, OF ceqv_refl])
apply (rule ccorres_gen_asm2)
apply (rule ccorres_gen_asm2)
apply (rule_tac err'=rv'a in err)
apply assumption+
apply (rule ccorres_gen_asm2)
apply (rule ccorres_gen_asm2)
apply (erule(1) bd)
apply (rule ccorres_empty[where P=\<top>])
apply (rule hoare_strengthen_post, rule valid[unfolded validE_def])
apply (simp split: sum.split_asm)
apply (rule exec_handlers_Hoare_Post,
rule exec_handlers_Hoare_from_vcg_nofail[OF valid', where A="{}"])
apply (auto simp: ccHoarePost_def split: sum.split)
done
lemma ccorres_split_nothrow_novcgE:
fixes R' :: "cstate set"
assumes ac: "ccorres_underlying sr \<Gamma>
(f' \<currency> r') (liftxf es ef' vf' xf')
(f' \<currency> r') (liftxf es ef' vf' xf')
P P' [] a c"
and ceqv: "\<And>rv' t t'. ceqv \<Gamma> xf' rv' t t' d (d' rv')"
and bd: "\<And>rv rv'. \<lbrakk> r' rv (vf' rv'); ef' rv' = scast EXCEPTION_NONE \<rbrakk>
\<Longrightarrow> ccorres_underlying sr \<Gamma> r xf arrel axf (Q rv) (Q' rv rv') hs (b rv) (d' rv')"
and err: "\<And>err rv' err'. \<lbrakk> ef' rv' \<noteq> scast EXCEPTION_NONE; f' err (ef' rv') err' \<rbrakk>
\<Longrightarrow> ccorres_underlying sr \<Gamma> r xf arrel axf
(QE err) (Q'' err rv' err') hs (throwError err) (d' rv')"
and valid: "\<lbrace>R\<rbrace> a \<lbrace>Q\<rbrace>,\<lbrace>QE\<rbrace>"
and novcg: "guard_is_UNIV (\<lambda>rv rv'. r' rv (vf' rv'))
xf' (\<lambda>rv rv'. {s. ef' rv' = scast EXCEPTION_NONE \<longrightarrow> s \<in> Q' rv rv'})"
-- "hack"
and novcg_err: "\<And>err. guard_is_UNIV (\<lambda>rv. f' err (ef' rv)) es
(\<lambda>rv rv'. {s. ef' (xf' s) \<noteq> scast EXCEPTION_NONE \<longrightarrow> s \<in> Q'' err rv rv'})"
shows "ccorres_underlying sr \<Gamma> r xf arrel axf (P and R) P' hs (a >>=E (\<lambda>rv. b rv)) (c ;; d)"
unfolding bindE_def
apply (rule_tac R="case_sum QE Q"
and R'="\<lambda>rv. {s. s \<in> case_sum QE' QR' rv (xf' s)}" for QE' QR'
in ccorres_master_split_nohs_UNIV)
apply (rule ac)
apply (rule ccorres_abstract[OF ceqv])
apply (case_tac rv, simp_all add: lift_def)
apply (rule ccorres_abstract[where xf'=es, OF ceqv_refl])
apply (rule ccorres_gen_asm2)
apply (rule ccorres_gen_asm2)
apply (rule_tac err'=rv'a in err)
apply assumption+
apply (rule ccorres_gen_asm2)
apply (rule ccorres_gen_asm2)
apply (erule(1) bd)
apply (rule hoare_strengthen_post, rule valid[unfolded validE_def])
apply (simp split: sum.split_asm)
apply (insert novcg novcg_err)
apply (clarsimp simp: guard_is_UNIV_def split: sum.split)
done
(* Unit would be more appropriate, but the record package will simplify xfdc to () *)
definition
"xfdc (t :: cstate) \<equiv> (0 :: nat)"
lemma xfdc_equal [simp]:
"xfdc t = xfdc s"
unfolding xfdc_def by simp
lemmas ccorres_split_nothrow_novcg_dc
= ccorres_split_nothrow_novcg[where r'=dc and xf'=xfdc, OF _ ceqv_refl]
abbreviation
"exfdc \<equiv> liftxf undefined (\<lambda>_. scast EXCEPTION_NONE) id xfdc"
lemma ccorres_return_C':
assumes xfc: "\<And>s. (xf (global_exn_var_'_update (\<lambda>_. Return) (xfu (\<lambda>_. v s) s))) = v s"
and wfh: "wfhandlers hs"
and srv: "\<And>s s'. (s, s') \<in> sr \<Longrightarrow>
(s, global_exn_var_'_update (\<lambda>_. Return) (xfu (\<lambda>_. v s') s')) \<in> sr"
shows "ccorres_underlying sr \<Gamma> r rvxf arrel xf \<top> {s. arrel rv (v s)} hs
(return rv) (return_C xfu v)"
using wfh
unfolding creturn_def
apply -
apply (rule ccorresI')
apply (erule exec_handlers.cases)
apply clarsimp
apply (clarsimp elim!: exec_Normal_elim_cases)
apply (drule (1) wfhandlersD)
apply simp
apply (frule exec_handlers_less2, clarsimp)
apply (clarsimp simp: return_def unif_rrel_def xfc)
apply (auto elim!: srv)[1]
apply (clarsimp elim!: exec_Normal_elim_cases)
apply simp
done
lemma ccorres_return_CE':
assumes xfc: "\<And>s. xf (global_exn_var_'_update (\<lambda>_. Return)
(xfu (\<lambda>_. v s) s)) = v s"
and wfh: "wfhandlers hs"
and srv: "\<And>s s'. (s, s') \<in> sr \<Longrightarrow> (s, global_exn_var_'_update (\<lambda>_. Return) (xfu (\<lambda>_. v s') s')) \<in> sr"
shows "ccorres_underlying sr \<Gamma> rvr rvxf (f \<currency> r) (liftxf es sf vf xf)
\<top> {s. sf (v s) = scast EXCEPTION_NONE \<and> r rv (vf (v s))} hs
(returnOk rv) (return_C xfu v)"
using wfh
unfolding creturn_def
apply -
apply (rule ccorresI')
apply (erule exec_handlers.cases)
apply clarsimp
apply (clarsimp elim!: exec_Normal_elim_cases)
apply (drule (1) wfhandlersD)
apply simp
apply (simp add: returnOk_def return_def)
apply (drule exec_handlers_less2, clarsimp+)
apply (auto simp: unif_rrel_def xfc elim!: srv)[1]
apply (clarsimp elim!: exec_Normal_elim_cases)
apply simp
done
lemma ccorres_return_C_errorE':
assumes xfc: "\<And>s. xf (global_exn_var_'_update (\<lambda>_. Return) (xfu (\<lambda>_. v s) s)) = v s"
and esc: "\<And>s. es (global_exn_var_'_update (\<lambda>_. Return) (xfu (\<lambda>_. v s) s)) = es s"
and wfh: "wfhandlers hs"
and srv: "\<And>s s'. (s, s') \<in> sr \<Longrightarrow> (s, global_exn_var_'_update (\<lambda>_. Return) (xfu (\<lambda>_. v s') s')) \<in> sr"
shows "ccorres_underlying sr \<Gamma> rvr rvxf (f \<currency> r) (liftxf es sf vf xf)
\<top> {s. sf (v s) \<noteq> scast EXCEPTION_NONE \<and> f rv (sf (v s)) (es s)} hs
(throwError rv) (return_C xfu v)"
using wfh
unfolding creturn_def
apply -
apply (rule ccorresI')
apply (erule exec_handlers.cases)
apply clarsimp
apply (clarsimp elim!: exec_Normal_elim_cases)
apply (drule (1) wfhandlersD)
apply simp
apply (simp add: throwError_def return_def)
apply (drule exec_handlers_less2, clarsimp+)
apply (auto simp: unif_rrel_def xfc esc elim!: srv)[1]
apply (clarsimp elim!: exec_Normal_elim_cases)
apply simp
done
context kernel
begin
abbreviation
"ccorres r xf \<equiv> ccorres_underlying rf_sr \<Gamma> r xf r xf"
lemma ccorres_basic_srnoop:
assumes asm: "ccorres_underlying rf_sr Gamm r xf arrel axf G G' hs a c"
and gsr: "\<And>s'. globals (g s') = globals s'"
and gG: "\<And>s'. s' \<in> G' \<Longrightarrow> g s' \<in> G'"
shows "ccorres_underlying rf_sr Gamm r xf arrel axf G G' hs a (Basic g ;; c)"
using asm unfolding rf_sr_def
apply (rule ccorres_basic_srnoop)
apply (simp add: gsr)
apply (erule gG)
done
lemma ccorres_basic_srnoop2:
assumes gsr: "\<And>s'. globals (g s') = globals s'"
assumes asm: "ccorres_underlying rf_sr Gamm r xf arrel axf G G' hs a c"
shows "ccorres_underlying rf_sr Gamm r xf arrel axf G {s. g s \<in> G'} hs a (Basic g ;; c)"
apply (rule ccorres_guard_imp2)
apply (rule ccorres_symb_exec_r)
apply (rule asm)
apply vcg
apply (rule conseqPre, vcg, clarsimp simp: rf_sr_def gsr)
apply clarsimp
done
(* The naming convention here is that xf', xfr, and xfru are the terms we instantiate *)
lemma ccorres_call:
assumes cul: "ccorres_underlying rf_sr \<Gamma> r xf'' r xf'' A C' [] a (Call f)"
and ggl: "\<And>x y s. globals (g x y s) = globals s"
and xfg: "\<And>a s t. (xf' (g a t (s\<lparr>globals := globals t\<rparr>))) = xf'' t"
and igl: "\<And>s. globals (i s) = globals s"
shows "ccorres_underlying rf_sr \<Gamma> r xf' arrel axf
A {s. i s \<in> C'} hs a (call i f (\<lambda>s t. s\<lparr>globals := globals t\<rparr>) (\<lambda>x y. Basic (g x y)))"
using cul
unfolding rf_sr_def
apply -
apply (rule ccorres_call)
apply (erule ccorres_guard_imp)
apply simp
apply clarsimp
apply (simp add: ggl)
apply (simp add: xfg)
apply (clarsimp simp: igl)
done
lemma ccorres_callE:
"\<lbrakk> ccorres_underlying rf_sr \<Gamma> r (liftxf es sf vf xf'')
r (liftxf es sf vf xf'') A C' [] a (Call f);
\<And>x y s. globals (g x y s) = globals s;
\<And>a s t. es (g a t (s\<lparr>globals := globals t\<rparr>)) = es t;
\<And>a s t. xf' (g a t (s\<lparr>globals := globals t\<rparr>)) = xf'' t;
\<And>s. globals (i s) = globals s
\<rbrakk>
\<Longrightarrow> ccorres_underlying rf_sr \<Gamma> r (liftxf es sf vf xf') arrel axf A {s. i s \<in> C'} hs a
(call i f (\<lambda>s t. s\<lparr>globals := globals t\<rparr>) (\<lambda>x y. Basic (g x y)))"
apply (erule ccorres_call)
apply assumption
apply (simp add: liftxf_def)
apply assumption
done
lemma ccorres_call_record:
assumes cul: "ccorres_underlying rf_sr \<Gamma> r xf'' r xf'' A C' [] a (Call f)"
and ggl: "\<And>f s. globals (xfu' f s) = globals s"
and xfxfu: "\<And>v s. xf' (xfu' (\<lambda>_. v) s) = v"
and xfrxfru: "\<And>v s. xfr (xfru (\<lambda>_. v) s) = v"
and igl: "\<And>s. globals (i s) = globals s"
shows "ccorres_underlying rf_sr \<Gamma> r (xfr \<circ> xf') arrel axf
A {s. i s \<in> C'} hs a (call i f (\<lambda>s t. s\<lparr>globals := globals t\<rparr>)
(\<lambda>_ t. Basic (xfu' (\<lambda>_. xfru (\<lambda>_. xf'' t) oldv))))"
apply (rule ccorres_call)
apply (rule cul)
apply (rule ggl)
apply (simp add: xfrxfru xfxfu)
apply (rule igl)
done
lemmas ccorres_split_nothrow_call = ccorres_split_nothrow [OF ccorres_call]
lemmas ccorres_split_nothrow_callE = ccorres_split_nothrowE [OF ccorres_callE]
lemma ccorres_split_nothrow_call_novcg:
assumes ac: "ccorres r' xf'' P P' [] a (Call f)"
and gg: "\<And>x y s. globals (g x y s) = globals s"
and xfxf: "\<And>a s t. xf' (g a t (s\<lparr>globals := globals t\<rparr>)) = xf'' t"
and gi: "\<And>s. globals (i s) = globals s"
and ceqv: "\<And>rv' t t'. ceqv \<Gamma> xf' rv' t t' d (d' rv')"
and bd: "\<And>rv rv'. r' rv rv' \<Longrightarrow> ccorres_underlying rf_sr \<Gamma> r xf arrel axf (Q rv) (Q' rv rv') hs (b rv) (d' rv')"
and valid: "\<lbrace>R\<rbrace> a \<lbrace>Q\<rbrace>"
shows "ccorres_underlying rf_sr \<Gamma> r xf arrel axf (P and R) ({s. i s \<in> P'} \<inter>
{s'. (\<forall>t rv. r' rv (xf'' t) \<longrightarrow> g s' t (s'\<lparr>globals := globals t\<rparr>) \<in> Q' rv (xf'' t))})
hs (a >>= (\<lambda>rv. b rv))
(call i f (\<lambda>s t. s\<lparr>globals := globals t\<rparr>) (\<lambda>x y. Basic (g x y)) ;; d)" (is "ccorres_underlying rf_sr \<Gamma> r xf arrel axf ?P (?Q1 \<inter> ?Q2) hs ?A ?B")
apply (rule ccorres_master_split_nohs)
apply (rule ccorres_call [OF ac])
apply (rule gg)
apply (rule xfxf)
apply (rule gi)
apply (rule ccorres_abstract[OF ceqv])
apply (rule ccorres_gen_asm2)
apply (erule bd)
apply (simp add: valid)
apply (rule exec_handlers_Hoare_call_Basic)
apply (clarsimp simp: ccHoarePost_def xfxf)
apply simp
done
definition
errstate :: "cstate \<Rightarrow> errtype"
where
"errstate s \<equiv> \<lparr> errfault = seL4_Fault_lift (current_fault_' (globals s)),
errlookup_fault = lookup_fault_lift (current_lookup_fault_' (globals s)),
errsyscall = current_syscall_error_' (globals s) \<rparr>"
lemma errstate_state_update [simp]:
assumes f: "\<And>s. current_fault_' (globals (g s)) = current_fault_' (globals s)"
and lf: "\<And>s. current_lookup_fault_' (globals (g s)) = current_lookup_fault_' (globals s)"
and se: "\<And>s. current_syscall_error_' (globals (g s)) = current_syscall_error_' (globals s)"
shows "errstate (g s) = errstate s"
by (simp add: f lf se errstate_def)
lemma ccorres_split_nothrow_call_novcgE:
assumes ac: "ccorres (f' \<currency> r') (liftxf errstate ef' vf' xf'') P P' [] a (Call f)"
and gg: "\<And>x y s. globals (g x y s) = globals s"
and xfxf: "\<And>a s t. xf' (g a t (s\<lparr>globals := globals t\<rparr>)) = xf'' t"
and gi: "\<And>s. globals (i s) = globals s"
and ceqv: "\<And>rv' t t'. ceqv \<Gamma> xf' rv' t t' d (d' rv')"
and bd: "\<And>rv rv'. \<lbrakk>r' rv (vf' rv'); ef' rv' = scast EXCEPTION_NONE\<rbrakk>
\<Longrightarrow> ccorres_underlying rf_sr \<Gamma> (fl \<currency> r) xf arrel axf
(Q rv) (Q' rv rv') hs (b rv) (d' rv')"
and err: "\<And>err rv' err'. \<lbrakk>ef' rv' \<noteq> scast EXCEPTION_NONE; f' err (ef' rv') err'\<rbrakk>
\<Longrightarrow> ccorres_underlying rf_sr \<Gamma> (fl \<currency> r) xf arrel axf
(QE err) (Q'' err rv' err') hs (throwError err) (d' rv')"
and valid: "\<lbrace>R\<rbrace> a \<lbrace>Q\<rbrace>, \<lbrace>QE\<rbrace>"
shows "ccorres_underlying rf_sr \<Gamma> (fl \<currency> r) xf arrel axf (P and R) ({s. i s \<in> P'} \<inter>
{s. \<forall>t. (ef' (xf'' t) = scast EXCEPTION_NONE \<longrightarrow> (\<forall>rv. r' rv (vf' (xf'' t)) \<longrightarrow> g s t (s\<lparr>globals := globals t\<rparr>) \<in> Q' rv (xf'' t))) \<and>
(ef' (xf'' t) \<noteq> scast EXCEPTION_NONE \<longrightarrow>
(\<forall>err. f' err (ef' (xf'' t)) (errstate t) \<longrightarrow> g s t (s\<lparr>globals := globals t\<rparr>) \<in> Q'' err (xf'' t) (errstate t)))}
) hs (a >>=E b) (call i f (\<lambda>s t. s\<lparr>globals := globals t\<rparr>) (\<lambda>x y. Basic (g x y));;
d)" (is "ccorres_underlying rf_sr \<Gamma> ?r ?xf arrel axf ?P (?Q1 \<inter> ?Q2) hs ?A ?B")
unfolding bindE_def
apply (rule_tac R="case_sum QE Q"
and R'="\<lambda>rv. {s. s \<in> case_sum QE' QR' rv (xf' s)}" for QE' QR'
in ccorres_master_split_nohs)
apply (rule ccorres_callE [OF ac])
apply (rule gg)
apply (rule errstate_state_update)
apply (simp add: gg)+
apply (rule xfxf)
apply (rule gi)
apply (rule ccorres_abstract[OF ceqv])
apply (case_tac rv, simp_all add: lift_def)
apply (rule_tac xf'=errstate in ccorres_abstract[OF ceqv_refl])
apply (rule ccorres_gen_asm2)
apply (rule ccorres_gen_asm2)
apply (erule_tac err'1=rv'a in err, assumption)
apply (rule ccorres_gen_asm2)
apply (rule ccorres_gen_asm2)
apply (erule(1) bd)
apply (rule hoare_strengthen_post)
apply (rule valid [unfolded validE_def])
apply (simp split: sum.split_asm)
apply (rule exec_handlers_Hoare_call_Basic)
apply (clarsimp simp: ccHoarePost_def xfxf gg errstate_def
split: sum.split)
apply simp
done
lemma ccorres_split_nothrow_call_record:
assumes ac: "ccorres r' xf'' P P' [] a (Call f)"
and ceqv: "\<And>rv' t t'. ceqv \<Gamma> xf' rv' t t' d (d' rv')"
and bd: "\<And>rv rv'. r' rv rv' \<Longrightarrow> ccorres_underlying rf_sr \<Gamma> r xf arrel axf (Q rv) (Q' rv rv') hs (b rv) (d' (xfru (\<lambda>_. rv') oldv))"
and ggl: "\<And>f s. globals (xfu' f s) = globals s"
and xfxfu: "\<And>v s. xf' (xfu' (\<lambda>_. v) s) = v"
and xfrxfru: "\<And>v s. xfr (xfru (\<lambda>_. v) s) = v"
and igl: "\<And>s. globals (i s) = globals s"
and valid: "\<lbrace>R\<rbrace> a \<lbrace>Q\<rbrace>"
and valid': "\<Gamma> \<turnstile>\<^bsub>/F\<^esub> R' call i f (\<lambda>s t. s\<lparr>globals := globals t\<rparr>) (\<lambda>_ t. Basic (xfu' (\<lambda>_. xfru (\<lambda>_. xf'' t) oldv)))
{s. xf' s = xfru (\<lambda>_. (xfr \<circ> xf') s) oldv \<and> (\<forall>rv. r' rv ((xfr \<circ> xf') s) \<longrightarrow> s \<in> Q' rv ((xfr \<circ> xf') s))}"
shows "ccorres_underlying rf_sr \<Gamma> r xf arrel axf (P and R) ({s. i s \<in> P'} \<inter> R') hs (a >>= (\<lambda>rv. b rv)) (call i f (\<lambda>s t. s\<lparr>globals := globals t\<rparr>)
(\<lambda>_ t. Basic (xfu' (\<lambda>_. xfru (\<lambda>_. xf'' t) oldv))) ;; d)"
using ac ggl xfxfu xfrxfru igl ceqv
apply (rule ccorres_split_nothrow_record [OF ccorres_call_record])
apply (erule bd)
apply (rule valid)
apply (rule valid')
done
lemma ccorres_split_nothrow_call_record_novcg:
assumes ac: "ccorres r' xf'' P P' [] a (Call f)"
and ceqv: "\<And>rv' t t'. ceqv \<Gamma> xf' rv' t t' d (d' rv')"
and bd: "\<And>rv rv'. r' rv rv' \<Longrightarrow> ccorres_underlying rf_sr \<Gamma> r xf arrel axf (Q rv) (Q' rv rv') hs (b rv) (d' (xfru (\<lambda>_. rv') oldv))"
and ggl: "\<And>f s. globals (xfu' f s) = globals s"
and xfxfu: "\<And>v s. xf' (xfu' (\<lambda>_. v) s) = v"
and xfrxfru: "\<And>v s. xfr (xfru (\<lambda>_. v) s) = v"
and igl: "\<And>s. globals (i s) = globals s"
and valid: "\<lbrace>R\<rbrace> a \<lbrace>Q\<rbrace>"
and novcg: "guard_is_UNIV r' (xfr \<circ> xf') Q'"
-- "This might cause problems \<dots> has to be preserved across c in vcg case, but we can't do that"
and xfoldv: "\<And>s. xf' s = xfru (\<lambda>_. (xfr \<circ> xf') s) oldv"
shows "ccorres_underlying rf_sr \<Gamma> r xf arrel axf (P and R) ({s. i s \<in> P'}) hs (a >>= (\<lambda>rv. b rv)) (call i f (\<lambda>s t. s\<lparr>globals := globals t\<rparr>)
(\<lambda>_ t. Basic (xfu' (\<lambda>_. xfru (\<lambda>_. xf'' t) oldv))) ;; d)"
using ac ggl xfxfu xfrxfru igl ceqv
apply (rule ccorres_split_nothrow_record_novcg [OF ccorres_call_record])
apply (erule bd)
apply (rule valid)
apply (rule novcg)
apply (rule xfoldv)
done
lemma ccorres_return_C:
assumes xf1: "\<And>s f. xf (global_exn_var_'_update f (xfu (\<lambda>_. v s) s)) = v s"
and xfu: "\<And>s f. globals (xfu f s) = globals s"
and wfh: "wfhandlers hs"
shows "ccorres_underlying rf_sr \<Gamma> r rvxf arrel xf \<top> {s. arrel rv (v s)}
hs (return rv) (return_C xfu v)"
apply (rule ccorres_guard_imp2, rule ccorres_return_C')
apply (simp add: xf1)
apply (rule wfh)
apply (simp add: xfu rf_sr_def cong: cstate_relation_only_t_hrs)
apply simp
done
lemma ccorres_return_CE:
assumes xf1: "\<And>s f. xf (global_exn_var_'_update f (xfu (\<lambda>_. v s) s)) = v s"
and xfu: "\<And>s f. globals (xfu f s) = globals s"
and wfh: "wfhandlers hs"
shows "ccorres_underlying rf_sr \<Gamma> rvr rxf (f \<currency> r) (liftxf es sf vf xf)
\<top> {s. sf (v s) = scast EXCEPTION_NONE \<and> r rv (vf (v s))} hs
(returnOk rv) (return_C xfu v)"
apply (rule ccorres_guard_imp2, rule ccorres_return_CE')
apply (simp add: xf1)
apply (rule wfh)
apply (simp add: xfu rf_sr_def cong: cstate_relation_only_t_hrs)
apply simp
done
lemma ccorres_return_C_errorE:
assumes xfc: "\<And>s. xf (global_exn_var_'_update (\<lambda>_. Return) (xfu (\<lambda>_. v s) s)) = v s"
and esc: "\<And>s. es (global_exn_var_'_update (\<lambda>_. Return) (xfu (\<lambda>_. v s) s)) = es s"
and xfu: "\<And>s f. globals (xfu f s) = globals s"
and wfh: "wfhandlers hs"
shows "ccorres_underlying rf_sr \<Gamma> rvr rvxf (f \<currency> r) (liftxf es sf vf xf)
\<top> {s. sf (v s) \<noteq> scast EXCEPTION_NONE \<and> f rv (sf (v s)) (es s)} hs
(throwError rv) (return_C xfu v)"
apply (rule ccorres_guard_imp2, rule ccorres_return_C_errorE')
apply (rule xfc)
apply (rule esc)
apply (rule wfh)
apply (simp add: xfu rf_sr_def cong: cstate_relation_only_t_hrs)
apply simp
done
(* Generalise *)
(* c can't fail here, so no /F *)
lemma ccorres_noop:
assumes nop: "\<forall>s. \<Gamma> \<turnstile> {s} c {t. t may_not_modify_globals s}"
shows "ccorres_underlying rf_sr \<Gamma> dc xf arrel axf \<top> UNIV hs (return ()) c"
apply (rule ccorres_from_vcg, rule allI, simp add: return_def)
apply (rule HoarePartial.conseq_exploit_pre)
apply simp
apply (intro allI impI)
apply (rule HoarePartial.conseq)
apply (rule nop)
apply clarsimp
apply (erule iffD1 [OF rf_sr_upd, rotated -1])
apply (clarsimp simp: meq_def mex_def)+
done
lemma ccorres_noop_spec:
assumes s: "\<forall>s. \<Gamma> \<turnstile> (P s) c (R s), (A s)"
and nop: "\<forall>s. \<Gamma> \<turnstile>\<^bsub>/F\<^esub> {s} c {t. t may_not_modify_globals s}"
shows "ccorres_underlying rf_sr \<Gamma> dc xf arrel axf \<top> {s. s \<in> P s} hs (return ()) c"
apply (rule ccorres_from_vcg, rule allI, simp add: return_def)
apply (rule HoarePartial.conseq_exploit_pre)
apply simp
apply (intro allI impI)
apply (rule HoarePartial.conseq)
apply (rule allI)
apply (rule HoarePartialProps.Merge_PostConj)
apply (rule_tac P = "{s} \<inter> P s" in conseqPre)
apply (rule_tac x = s in spec [OF s])
apply clarsimp
apply (rule_tac x = s in spec [OF nop])
apply simp
apply clarsimp
apply clarsimp
apply (erule iffD2 [OF rf_sr_upd, rotated -1])
apply (clarsimp simp: meq_def mex_def)+
done
(* FIXME: MOVE *)
lemma ccorres_symb_exec_r2:
assumes cul: "ccorres_underlying rf_sr \<Gamma> r xf arrel axf R Q' hs a d"
and ex: "\<Gamma> \<turnstile> R' c Q'"
and pres: "\<forall>s. \<Gamma> \<turnstile>\<^bsub>/F\<^esub> {s} c {t. t may_not_modify_globals s}"
shows "ccorres_underlying rf_sr \<Gamma> r xf arrel axf R R' hs a (c ;; d)"
apply (rule ccorres_add_return)
apply (rule ccorres_guard_imp2)
apply (rule ccorres_split_nothrow')
apply (rule ccorres_noop_spec)
apply (rule allI)
apply (rule ex)
apply (rule pres)
apply simp
apply (rule cul)
apply wp
apply (rule HoarePartialProps.augment_Faults [OF ex])
apply simp
apply simp
done
lemma ccorres_trim_redundant_throw:
"\<lbrakk>ccorres_underlying rf_sr \<Gamma> arrel axf arrel axf G G' (SKIP # hs) a c;
\<And>s f. axf (global_exn_var_'_update f s) = axf s \<rbrakk>
\<Longrightarrow> ccorres_underlying rf_sr \<Gamma> r xf arrel axf G G' (SKIP # hs)
a (c;; Basic (global_exn_var_'_update (\<lambda>_. Return));; THROW)"
apply -
apply (rule ccorres_trim_redundant_throw')
apply simp
apply simp
apply (simp add: rf_sr_upd_safe)
done
end
lemmas in_magnitude_check' =
in_magnitude_check [where v = "fst z" and s' = "snd z" for z, folded surjective_pairing]
(* Defined in terms of access_ti for convenience *)
lemma fd_cons_update_accessD:
"\<lbrakk> fd_cons_update_access d n; length bs = n \<rbrakk> \<Longrightarrow> field_update d (field_access d v bs) v = v"
unfolding fd_cons_update_access_def by simp
lemma fd_cons_access_updateD:
"\<lbrakk> fd_cons_access_update d n; length bs = n; length bs' = n\<rbrakk> \<Longrightarrow> field_access d (field_update d bs v) bs' = field_access d (field_update d bs v') bs'"
unfolding fd_cons_access_update_def by clarsimp
context kernel
begin
(* Tests *)
lemma cte_C_cap_C_tcb_C':
fixes val :: "cap_C" and ptr :: "cte_C ptr"
assumes cl: "clift hp ptr = Some z"
shows "(clift (hrs_mem_update (heap_update (Ptr &(ptr\<rightarrow>[''cap_C''])) val) hp)) =
(clift hp :: tcb_C typ_heap)"
using cl
by (simp add: typ_heap_simps)
lemma cte_C_cap_C_update:
fixes val :: "cap_C" and ptr :: "cte_C ptr"
assumes cl: "clift hp ptr = Some z"
shows "(clift (hrs_mem_update (heap_update (Ptr &(ptr\<rightarrow>[''cap_C''])) val) hp)) =
clift hp(ptr \<mapsto> cte_C.cap_C_update (\<lambda>_. val) z)"
using cl
by (simp add: clift_field_update)
abbreviation
"modifies_heap_spec f \<equiv> \<forall>s. \<Gamma> \<turnstile>\<^bsub>/UNIV\<^esub> {s} Call f {t. t may_only_modify_globals s in [t_hrs]}"
(* Used for bitfield lemmas. Note that this doesn't follow the usual schematic merging: we generally need concrete G and G' *)
lemma ccorres_from_spec_modifies_heap:
assumes spec: "\<forall>s. \<Gamma>\<turnstile> \<lbrace>s. P s\<rbrace> Call f {t. Q s t}"
and mod: "modifies_heap_spec f"
and xfg: "\<And>f s. xf (globals_update f s) = xf s"
and Pimp: "\<And>s s'. \<lbrakk> G s; s' \<in> G'; (s, s') \<in> rf_sr \<rbrakk> \<Longrightarrow> P s'"
and rl: "\<And>s s' t'. \<lbrakk>G s; s' \<in> G'; (s, s') \<in> rf_sr; Q s' t'\<rbrakk>
\<Longrightarrow> \<exists>(rv, t) \<in> fst (a s).
(t, t'\<lparr>globals := globals s'\<lparr>t_hrs_' := t_hrs_' (globals t')\<rparr>\<rparr>) \<in> rf_sr
\<and> r rv (xf t')"
shows "ccorres_underlying rf_sr \<Gamma> r xf arrel axf G G' [] a (Call f)"
apply (rule ccorres_Call_call_for_vcg)
apply (rule ccorres_from_vcg)
apply (rule allI, rule conseqPre)
apply (rule HoarePartial.ProcModifyReturnNoAbr
[where return' = "\<lambda>s t. t\<lparr> globals := globals s\<lparr>t_hrs_' := t_hrs_' (globals t) \<rparr>\<rparr>"])
apply (rule HoarePartial.ProcSpecNoAbrupt [OF _ _ spec])
apply (rule subset_refl)
apply vcg
prefer 2
apply (rule mod)
apply (clarsimp simp: mex_def meq_def)
apply (clarsimp simp: split_beta Pimp)
apply (subst bex_cong [OF refl])
apply (rule arg_cong2 [where f = "op \<and>"])
apply (rule_tac y = "t\<lparr>globals := globals x\<lparr>t_hrs_' := t_hrs_' (globals t)\<rparr>\<rparr>" in rf_sr_upd, simp_all)
apply (drule (3) rl)
apply (clarsimp simp: xfg elim!: bexI [rotated])
done
(* Used for bitfield lemmas *)
lemma ccorres_from_spec_modifies:
assumes spec: "\<forall>s. \<Gamma>\<turnstile> \<lbrace>s. P s\<rbrace> Call f {t. Q s t}"
and mod: "modifies_spec f"
and xfg: "\<And>f s. xf (globals_update f s) = xf s"
and Pimp: "\<And>s s'. \<lbrakk> G s; s' \<in> G'; (s, s') \<in> rf_sr \<rbrakk> \<Longrightarrow> P s'"
and rl: "\<And>s s' t'. \<lbrakk>G s; s' \<in> G'; (s, s') \<in> rf_sr; Q s' t'\<rbrakk>
\<Longrightarrow> \<exists>(rv, t) \<in> fst (a s). (t, s') \<in> rf_sr \<and> r rv (xf t')"
shows "ccorres_underlying rf_sr \<Gamma> r xf arrel axf G G' [] a (Call f)"
apply (rule ccorres_Call_call_for_vcg)
apply (rule ccorres_from_vcg)
apply (rule allI, rule conseqPre)
apply (rule HoarePartial.ProcModifyReturnNoAbr
[where return' = "\<lambda>s t. t\<lparr> globals := globals s \<rparr>"])
apply (rule HoarePartial.ProcSpecNoAbrupt [OF _ _ spec])
apply (rule subset_refl)
apply vcg
prefer 2
apply (rule mod)
apply (clarsimp simp: mex_def meq_def)
apply (clarsimp simp: split_beta Pimp)
apply (subst bex_cong [OF refl])
apply (rule arg_cong2 [where f = "op \<and>"])
apply (rule_tac y = "x" in rf_sr_upd, simp_all)
apply (drule (3) rl)
apply (clarsimp simp: xfg elim!: bexI [rotated])
done
lemma ccorres_trim_return:
assumes fg: "\<And>s. xfu (\<lambda>_. axf s) s = s"
and xfu: "\<And>f s. axf (global_exn_var_'_update f s) = axf s"
and cc: "ccorres_underlying rf_sr \<Gamma> arrel axf arrel axf G G' (SKIP # hs) a c"
shows "ccorres_underlying rf_sr \<Gamma> r xf arrel axf G G' (SKIP # hs) a (c ;; return_C xfu axf)"
using fg unfolding creturn_def
apply -
apply (rule ccorres_rhs_assoc2)+
apply (rule ccorres_trim_redundant_throw)
apply (clarsimp split del: if_split)
apply (rule iffD2 [OF ccorres_semantic_equiv, OF _ cc])
apply (rule semantic_equivI)
apply (case_tac s')
apply (auto elim!: exec_Normal_elim_cases exec_elim_cases intro!: exec.intros)[4]
apply (rule xfu)
done
lemma rf_sr_globals_exn_var:
"((s, global_exn_var_'_update f s') \<in> rf_sr)
= ((s, s') \<in> rf_sr)"
by (rule rf_sr_upd, simp_all)
lemma ccorres_trim_returnE:
assumes fg: "\<And>s. xfu (\<lambda>_. axf s) s = s"
and xfu: "\<And>f s. axf (global_exn_var_'_update f s) = axf s"
and cc: "ccorres r (liftxf errstate ef vf axf)
G G' (SKIP # hs) a c"
shows "ccorres_underlying rf_sr \<Gamma> rvr rvxf r (liftxf errstate ef vf axf)
G G' (SKIP # hs) a (c ;; return_C xfu axf)"
unfolding creturn_def
apply (rule ccorres_rhs_assoc2)+
apply (rule ccorres_trim_redundant_throw')
apply (simp add: fg)
apply (rule iffD2 [OF ccorres_semantic_equiv, OF _ cc])
apply (rule semantic_equivI)
apply (case_tac s')
apply (auto elim!: exec_Normal_elim_cases exec_elim_cases intro!: exec.intros)[4]
apply (simp add: liftxf_def xfu)
apply (simp add: rf_sr_globals_exn_var)
done
lemma ccorres_sequence_while_genQ:
fixes i :: "nat" and xf :: "globals myvars \<Rightarrow> ('c :: len) word"
assumes one: "\<And>n ys. \<lbrakk> n < length xs \<rbrakk> \<Longrightarrow>
ccorres (\<lambda>rv rv'. r' (ys @ [rv]) rv') xf'
(F (n * j)) ({s. xf s = of_nat (i + n * j) \<and> r' ys (xf' s)} \<inter> Q) hs
(xs ! n) body"
and pn: "\<And>n. P n = (n < of_nat (i + length xs * j))"
and bodyi: "\<forall>s. xf s < of_nat (i + length xs * j)
\<longrightarrow> \<Gamma> \<turnstile>\<^bsub>/UNIV\<^esub> ({s} \<inter> Q) body {t. xf t = xf s \<and> xf_update (\<lambda>x. xf t + of_nat j) t \<in> Q}"
and hi: "\<And>n. Suc n < length xs \<Longrightarrow> \<lbrace> F (n * j) \<rbrace> (xs ! n) \<lbrace>\<lambda>_. F (Suc n * j)\<rbrace>"
and lxs: "i + length xs * j< 2 ^ len_of TYPE('c)"
and xf: "\<forall>s f. xf (xf_update f s) = f (xf s) \<and> globals (xf_update f s) = globals s"
and xf': "\<forall>s f. xf' (xf_update f s) = (xf' s)"
and j: "j > 0"
shows "ccorres (\<lambda>rv (i', rv'). r' rv rv' \<and> i' = of_nat (i + length xs * of_nat j))
(\<lambda>s. (xf s, xf' s))
(\<lambda>s. P 0 \<longrightarrow> F 0 s) ({s. xf s = of_nat i \<and> r' [] (xf' s)} \<inter> Q) hs
(sequence xs)
(While {s. P (xf s)}
(body ;; Basic (\<lambda>s. xf_update (\<lambda>_. xf s + of_nat j) s)))"
(is "ccorres ?r' ?xf' ?G (?G' \<inter> _) hs (sequence xs) ?body")
apply (rule ccorres_sequence_while_genQ' [OF one pn bodyi hi lxs xf xf'])
apply simp
apply simp
apply (clarsimp simp: rf_sr_def xf)
apply (simp add: j)
done
lemma ccorres_sequence_while_gen':
fixes i :: "nat" and xf :: "globals myvars \<Rightarrow> ('c :: len) word"
assumes one: "\<And>n ys. \<lbrakk> n < length xs \<rbrakk> \<Longrightarrow>
ccorres (\<lambda>rv rv'. r' (ys @ [rv]) rv') xf'
(F (n * j)) {s. xf s = of_nat (i + n * j) \<and> r' ys (xf' s)} hs
(xs ! n) body"
and pn: "\<And>n. P n = (n < of_nat (i + length xs * j))"
and bodyi: "\<forall>s. \<Gamma> \<turnstile>\<^bsub>/UNIV\<^esub> {s} body {t. xf t = xf s}"
and hi: "\<And>n. Suc n < length xs \<Longrightarrow> \<lbrace> F (n * j) \<rbrace> (xs ! n) \<lbrace>\<lambda>_. F (Suc n * j)\<rbrace>"
and lxs: "i + length xs * j< 2 ^ len_of TYPE('c)"
and xf: "\<forall>s f. xf (xf_update f s) = f (xf s) \<and> globals (xf_update f s) = globals s"
and xf': "\<forall>s f. xf' (xf_update f s) = (xf' s)"
and j: "j > 0"
shows "ccorres (\<lambda>rv (i', rv'). r' rv rv' \<and> i' = of_nat (i + length xs * of_nat j))
(\<lambda>s. (xf s, xf' s))
(F 0) ({s. xf s = of_nat i \<and> r' [] (xf' s)}) hs
(sequence xs)
(While {s. P (xf s)}
(body ;; Basic (\<lambda>s. xf_update (\<lambda>_. xf s + of_nat j) s)))"
(is "ccorres ?r' ?xf' ?G ?G' hs (sequence xs) ?body")
using assms
apply -
apply (rule ccorres_guard_imp2)
apply (rule ccorres_sequence_while_genQ [where Q=UNIV])
apply (assumption|simp)+
done
lemma ccorres_sequence_x_while_genQ':
fixes xf :: "globals myvars \<Rightarrow> ('c :: len) word"
shows
"\<lbrakk>\<And>n. n < length xs \<Longrightarrow> ccorres dc xfdc (F (n * j)) ({s. xf s = of_nat (i + n * j)} \<inter> Q) hs (xs ! n) body;
\<And>n. P n = (n < of_nat (i + length xs * j));
\<forall>s. xf s < of_nat (i + length xs * j)
\<longrightarrow> \<Gamma>\<turnstile>\<^bsub>/UNIV\<^esub> ({s} \<inter> Q) body {t. xf t = xf s \<and> xf_update (\<lambda>x. xf t + of_nat j) t \<in> Q};
\<And>n. Suc n < length xs \<Longrightarrow> \<lbrace>F (n * j)\<rbrace> xs ! n \<lbrace>\<lambda>_. F (Suc n * j)\<rbrace>; i + length xs * j < 2 ^ len_of TYPE('c);
\<forall>s f. xf (xf_update f s) = f (xf s) \<and> globals (xf_update f s) = globals s; j > 0 \<rbrakk>
\<Longrightarrow> ccorres (\<lambda>rv i'. i' = of_nat (i + length xs * of_nat j)) xf (\<lambda>s. P 0 \<longrightarrow> F 0 s) ({s. xf s = of_nat i} \<inter> Q) hs
(NonDetMonad.sequence_x xs)
(While {s. P (xf s)} (body;;
Basic (\<lambda>s. xf_update (\<lambda>_. xf s + of_nat j) s)))"
apply (simp add: sequence_x_sequence liftM_def[symmetric]
ccorres_liftM_simp)
apply (rule ccorres_rel_imp)
apply (rule ccorres_sequence_while_genQ
[where xf'=xfdc and r'=dc and xf_update=xf_update, simplified],
(simp add: dc_def)+)
done
lemma ccorres_sequence_x_while_gen':
fixes xf :: "globals myvars \<Rightarrow> ('c :: len) word"
shows
"\<lbrakk>\<And>n ys. n < length xs \<Longrightarrow> ccorres dc xfdc (F (n * j)) {s. xf s = of_nat (i + n * j)} hs (xs ! n) body;
\<And>n. P n = (n < of_nat (i + length xs * j)); \<forall>s. \<Gamma>\<turnstile>\<^bsub>/UNIV\<^esub> {s} body {t. xf t = xf s};
\<And>n. Suc n < length xs \<Longrightarrow> \<lbrace>F (n * j)\<rbrace> xs ! n \<lbrace>\<lambda>_. F (Suc n * j)\<rbrace>; i + length xs * j < 2 ^ len_of TYPE('c);
\<forall>s f. xf (xf_update f s) = f (xf s) \<and> globals (xf_update f s) = globals s; 0 < j \<rbrakk>
\<Longrightarrow> ccorres (\<lambda>rv i'. i' = of_nat (i + length xs * of_nat j)) xf (F 0) {s. xf s = of_nat i} hs
(NonDetMonad.sequence_x xs)
(While {s. P (xf s)} (body;;
Basic (\<lambda>s. xf_update (\<lambda>_. xf s + of_nat j) s)))"
apply (simp add: sequence_x_sequence liftM_def[symmetric]
ccorres_liftM_simp)
apply (rule ccorres_rel_imp)
apply (rule ccorres_sequence_while_gen'
[where xf'=xfdc and r'=dc and xf_update=xf_update, simplified],
(simp add: dc_def)+)
done
lemma i_xf_for_sequence:
"\<forall>s f. i_' (i_'_update f s) = f (i_' s) \<and> globals (i_'_update f s) = globals s"
by simp
lemmas ccorres_sequence_x_while'
= ccorres_sequence_x_while_gen' [OF _ _ _ _ _ i_xf_for_sequence, folded word_bits_def,
where j=1, simplified]
lemma ccorres_sequence_x_while_genQ:
fixes xf :: "globals myvars \<Rightarrow> ('c :: len) word"
assumes one: "\<forall>n < length xs. ccorres dc xfdc (F (n * j) ) ({s. xf s = of_nat n * of_nat j} \<inter> Q) hs (xs ! n) body"
and pn: "\<And>n. P n = (n < of_nat (length xs * j))"
and bodyi: "\<forall>s. xf s < of_nat (length xs * j)
\<longrightarrow> \<Gamma> \<turnstile>\<^bsub>/UNIV\<^esub> ({s} \<inter> Q) body {t. xf t = xf s \<and> xf_update (\<lambda>x. xf t + of_nat j) t \<in> Q}"
and hi: "\<And>n. Suc n < length xs \<Longrightarrow> \<lbrace> F (n * j) \<rbrace> (xs ! n) \<lbrace>\<lambda>_. F (Suc n * j)\<rbrace>"
and lxs: "length xs * j < 2 ^ len_of TYPE('c)"
and xf: "\<forall>s f. xf (xf_update f s) = f (xf s) \<and> globals (xf_update f s) = globals s"
and j: "0 < j"
shows "ccorres (\<lambda>rv rv'. rv' = of_nat (length xs) * of_nat j) xf (\<lambda>s. P 0 \<longrightarrow> F 0 s)
{s. xf_update (\<lambda>_. 0) s \<in> Q} hs
(sequence_x xs)
(Basic (\<lambda>s. xf_update (\<lambda>_. 0) s);;
(While {s. P (xf s)}
(body ;; Basic (\<lambda>s. xf_update (\<lambda>_. xf s + of_nat j) s))))"
apply (rule ccorres_symb_exec_r)
apply (rule ccorres_sequence_x_while_genQ' [where i=0 and xf_update=xf_update and Q=Q, simplified])
apply (simp add: assms hi[simplified])+
apply (rule conseqPre, vcg)
apply (clarsimp simp add: xf)
apply (rule conseqPre, vcg)
apply (simp add: xf rf_sr_def)
done
lemma ccorres_sequence_x_while_gen:
fixes xf :: "globals myvars \<Rightarrow> ('c :: len) word"
assumes one: "\<forall>n < length xs. ccorres dc xfdc (F (n * j)) {s. xf s = of_nat n * of_nat j} hs (xs ! n) body"
and pn: "\<And>n. P n = (n < of_nat (length xs * j))"
and bodyi: "\<forall>s. \<Gamma> \<turnstile>\<^bsub>/UNIV\<^esub> {s} body {t. xf t = xf s}"
and hi: "\<And>n. Suc n < length xs \<Longrightarrow> \<lbrace> F (n * j) \<rbrace> (xs ! n) \<lbrace>\<lambda>_. F (Suc n * j)\<rbrace>"
and lxs: "length xs * j < 2 ^ len_of TYPE('c)"
and xf: "\<forall>s f. xf (xf_update f s) = f (xf s) \<and> globals (xf_update f s) = globals s"
and j: "0 < j"
shows "ccorres (\<lambda>rv rv'. rv' = of_nat (length xs) * of_nat j) xf (F 0) UNIV hs
(sequence_x xs)
(Basic (\<lambda>s. xf_update (\<lambda>_. 0) s);;
(While {s. P (xf s)}
(body ;; Basic (\<lambda>s. xf_update (\<lambda>_. xf s + of_nat j) s))))"
apply (rule ccorres_symb_exec_r)
apply (rule ccorres_sequence_x_while_gen' [where i=0 and xf_update=xf_update, simplified])
apply (simp add: assms hi[simplified])+
apply vcg
apply (simp add: xf)
apply vcg
apply (simp add: xf rf_sr_def)
done
lemmas ccorres_sequence_x_while
= ccorres_sequence_x_while_gen [OF _ _ _ _ _ i_xf_for_sequence, folded word_bits_def,
where j=1, simplified]
lemmas ccorres_sequence_x_whileQ
= ccorres_sequence_x_while_genQ [OF _ _ _ _ _ i_xf_for_sequence, folded word_bits_def,
where j=1, simplified]
lemma ccorres_mapM_x_while_gen:
fixes xf :: "globals myvars \<Rightarrow> ('c :: len) word"
assumes rl: "\<forall>n. n < length xs \<longrightarrow> ccorres dc xfdc (F (n * j)) {s. xf s = of_nat n * of_nat j} hs (f (xs ! n)) body"
and guard: "\<And>n. P n = (n < of_nat (length xs * j))"
and bodyi: "\<forall>s. \<Gamma>\<turnstile>\<^bsub>/UNIV\<^esub> {s} body {s'. xf s' = xf s}"
and hi: "\<And>n. Suc n < length xs \<Longrightarrow> \<lbrace>F (n * j)\<rbrace> f (xs ! n) \<lbrace>\<lambda>_. F (Suc n * j)\<rbrace>"
and wb: "length xs * j < 2 ^ len_of TYPE('c)"
and xf: "\<forall>s f. xf (xf_update f s) = f (xf s) \<and> globals (xf_update f s) = globals s"
and j: "0 < j"
shows "ccorres (\<lambda>rv rv'. rv' = of_nat (length xs) * of_nat j) xf (F (0 :: nat)) UNIV hs
(mapM_x f xs)
(Basic (\<lambda>s. xf_update (\<lambda>_. 0) s);;
(While {s. P (xf s)}
(body ;; Basic (\<lambda>s. xf_update (\<lambda>_. xf s + of_nat j) s))))"
unfolding mapM_x_def
apply (rule ccorres_rel_imp)
apply (rule ccorres_sequence_x_while_gen[where xf_update=xf_update])
apply (simp add: assms hi[simplified])+
done
lemmas ccorres_mapM_x_while
= ccorres_mapM_x_while_gen [OF _ _ _ _ _ i_xf_for_sequence, folded word_bits_def,
where j=1, simplified]
lemma ccorres_mapM_x_while_genQ:
fixes xf :: "globals myvars \<Rightarrow> ('c :: len) word"
assumes rl: "\<forall>n. n < length xs \<longrightarrow> ccorres dc xfdc (F (n * j)) ({s. xf s = of_nat n * of_nat j} \<inter> Q) hs (f (xs ! n)) body"
and guard: "\<And>n. P n = (n < of_nat (length xs * j))"
and bodyi: "\<forall>s. xf s < of_nat (length xs * j)
\<longrightarrow> \<Gamma>\<turnstile>\<^bsub>/UNIV\<^esub> ({s} \<inter> Q) body {t. xf t = xf s \<and> xf_update (\<lambda>x. xf t + of_nat j) t \<in> Q}"
and hi: "\<And>n. Suc n < length xs \<Longrightarrow> \<lbrace>F (n * j)\<rbrace> f (xs ! n) \<lbrace>\<lambda>_. F (Suc n * j)\<rbrace>"
and wb: "length xs * j < 2 ^ len_of TYPE('c)"
and xf: "\<forall>s f. xf (xf_update f s) = f (xf s) \<and> globals (xf_update f s) = globals s"
and j: "0 < j"
shows "ccorres (\<lambda>rv rv'. rv' = of_nat (length xs) * of_nat j) xf (\<lambda>s. P 0 \<longrightarrow> F (0 :: nat) s)
{s. xf_update (\<lambda>_. 0) s \<in> Q} hs
(mapM_x f xs)
(Basic (\<lambda>s. xf_update (\<lambda>_. 0) s);;
(While {s. P (xf s)}
(body ;; Basic (\<lambda>s. xf_update (\<lambda>_. xf s + of_nat j) s))))"
unfolding mapM_x_def
apply (rule ccorres_rel_imp)
apply (rule ccorres_sequence_x_while_genQ[where xf_update=xf_update])
apply (simp add: assms hi[simplified])+
done
lemmas ccorres_mapM_x_whileQ
= ccorres_mapM_x_while_genQ [OF _ _ _ _ _ i_xf_for_sequence, folded word_bits_def,
where j=1, simplified]
lemma ccorres_mapM_x_while_gen':
fixes xf :: "globals myvars \<Rightarrow> ('c :: len) word"
assumes rl: "\<forall>n. n < length xs \<longrightarrow>
ccorres dc xfdc (F (n * j)) {s. xf s = of_nat (i + n * j)} hs (f (xs ! n)) body"
and guard: "\<And>n. P n = (n < of_nat (i + length xs * j))"
and bodyi: "\<forall>s. \<Gamma>\<turnstile>\<^bsub>/UNIV\<^esub> {s} body {s'. xf s' = xf s}"
and hi: "\<And>n. Suc n < length xs \<Longrightarrow> \<lbrace>F (n *j)\<rbrace> f (xs ! n) \<lbrace>\<lambda>_. F (Suc n * j)\<rbrace>"
and wb: "i + length xs * j < 2 ^ len_of TYPE('c)"
and xf: "\<forall>s f. xf (xf_update f s) = f (xf s) \<and> globals (xf_update f s) = globals s"
and j: "0 < j"
shows "ccorres (\<lambda>rv rv'. rv' = of_nat (i + length xs * j)) xf
(F (0 :: nat)) {s. xf s = of_nat i} hs
(mapM_x f xs)
(While {s. P (xf s)}
(body ;; Basic (\<lambda>s. xf_update (\<lambda>_. xf s + of_nat j) s)))"
unfolding mapM_x_def
apply (rule ccorres_rel_imp)
apply (rule ccorres_sequence_x_while_gen'[where xf_update=xf_update])
apply (clarsimp simp only: length_map nth_map rl)
apply (simp add: assms hi[simplified])+
done
lemmas ccorres_mapM_x_while'
= ccorres_mapM_x_while_gen' [OF _ _ _ _ _ i_xf_for_sequence, folded word_bits_def,
where j=1, simplified]
lemma ccorres_zipWithM_x_while_genQ:
fixes xf :: "globals myvars \<Rightarrow> ('c :: len) word"
assumes rl: "\<forall>n. n < length xs \<and> n < length ys \<longrightarrow> ccorres dc xfdc (F (n * j)) ({s. xf s = of_nat n * of_nat j} \<inter> Q)
hs (f (xs ! n) (ys ! n)) body"
and guard: "\<And>n. P n = (n < of_nat (min (length xs) (length ys)) * of_nat j)"
and bodyi: "\<forall>s. xf s < of_nat (min (length xs) (length ys)) * of_nat j
\<longrightarrow> \<Gamma>\<turnstile>\<^bsub>/UNIV\<^esub> ({s} \<inter> Q) body {t. xf t = xf s \<and> xf_update (\<lambda>x. xf t + of_nat j) t \<in> Q}"
and hi: "\<And>n. Suc n < length xs \<and> Suc n < length ys \<Longrightarrow> \<lbrace>F (n * j)\<rbrace> f (xs ! n) (ys ! n) \<lbrace>\<lambda>_. F (Suc n * j)\<rbrace>"
and wb: "min (length xs) (length ys) * j < 2 ^ len_of TYPE('c)"
and xf: "\<forall>s f. xf (xf_update f s) = f (xf s) \<and> globals (xf_update f s) = globals s"
and j: "0 < j"
shows "ccorres (\<lambda>rv rv'. rv' = of_nat (min (length xs) (length ys) * j)) xf
(F (0 :: nat)) {s. xf_update (\<lambda>_. 0) s \<in> Q} hs
(zipWithM_x f xs ys)
(Basic (\<lambda>s. xf_update (\<lambda>_. 0) s);;
(While {s. P (xf s)}
(body ;; Basic (\<lambda>s. xf_update (\<lambda>_. xf s + of_nat j) s))))"
unfolding zipWithM_x_def
apply (rule ccorres_guard_imp)
apply (rule ccorres_rel_imp [OF ccorres_sequence_x_while_genQ[where F=F, OF _ _ _ _ _ xf j]],
simp_all add: length_zipWith)
apply (simp add: length_zipWith zipWith_nth)
apply (rule rl)
apply (rule guard)
apply (rule bodyi)
apply (simp add: zipWith_nth hi[simplified])
apply (rule wb)
done
lemmas ccorres_zipWithM_x_while_gen = ccorres_zipWithM_x_while_genQ[where Q=UNIV, simplified]
lemmas ccorres_zipWithM_x_while
= ccorres_zipWithM_x_while_gen[OF _ _ _ _ _ i_xf_for_sequence, folded word_bits_def,
where j=1, simplified]
end
lemma ccorres_sequenceE_while_gen_either_way:
fixes xf :: "globals myvars \<Rightarrow> ('c :: len) word"
assumes one: "\<And>n ys. \<lbrakk> n < length xs; n = length ys \<rbrakk> \<Longrightarrow>
ccorres_underlying sr \<Gamma> (inr_rrel (\<lambda>rv rv'. r' (ys @ [rv]) rv')) xf'
(inl_rrel arrel) axf
(F n) (Q \<inter> {s. xf s = xfrel n \<and> r' ys (xf' s)}) hs
(xs ! n) body"
and pn: "\<And>n. (n < length xs \<longrightarrow> P (xfrel n)) \<and> \<not> P (xfrel (length xs))"
and xfrel_u: "\<And>n. xfrel_upd (xfrel n) = xfrel (Suc n)"
and bodyi: "\<And>s. s \<in> Q \<Longrightarrow> \<Gamma> \<turnstile>\<^bsub>/UNIV\<^esub> {s} body (Q \<inter> {t. xf t = xf s}), UNIV"
and hi: "\<And>n. n < length xs \<Longrightarrow> \<lbrace> F n \<rbrace> (xs ! n) \<lbrace>\<lambda>_. F (Suc n)\<rbrace>,-"
and xf: "\<forall>s f. xf (xf_update f s) = f (xf s)"
and xf': "\<forall>s f. xf' (xf_update f s) = (xf' s)
\<and> ((xf_update f s \<in> Q) = (s \<in> Q))
\<and> (\<forall>s'. ((s', xf_update f s) \<in> sr) = ((s', s) \<in> sr))"
shows "ccorres_underlying sr \<Gamma> (inr_rrel (\<lambda>rv (i', rv'). r' rv rv' \<and> i' = xfrel (length xs)))
(\<lambda>s. (xf s, xf' s)) arrel axf
(F 0) (Q \<inter> {s. xf s = xfrel 0 \<and> r' [] (xf' s)}) hs
(sequenceE xs)
(While {s. P (xf s)}
(body ;; Basic (\<lambda>s. xf_update (\<lambda>_. xfrel_upd (xf s)) s)))"
(is "ccorres_underlying sr \<Gamma> (inr_rrel ?r') ?xf' arrel axf ?G ?G' hs (sequenceE xs) ?body")
proof -
def init_xs \<equiv> xs
have rl: "xs = drop (length init_xs - length xs) init_xs" unfolding init_xs_def
by fastforce
note pn' = pn [folded init_xs_def]
note one' = one [folded init_xs_def]
note hi' = hi [folded init_xs_def]
let ?Q = "\<lambda>xs. F (length init_xs - length xs)"
let ?Q' = "\<lambda>xs zs. Q \<inter> {s. (xf s) = xfrel (length init_xs - length xs)
\<and> r' zs (xf' s)}"
let ?r'' = "\<lambda>zs rv (i', rv'). r' (zs @ rv) rv'
\<and> i' = xfrel (length init_xs)"
have "\<forall>zs. length zs = length init_xs - length xs \<longrightarrow>
ccorres_underlying sr \<Gamma> (inr_rrel (?r'' zs)) ?xf' (inl_rrel arrel) axf
(?Q xs) (?Q' xs zs) hs
(sequenceE xs) ?body"
using rl
proof (induct xs)
case Nil
thus ?case
apply clarsimp
apply (rule iffD1 [OF ccorres_expand_while_iff])
apply (simp add: sequenceE_def returnOk_def)
apply (rule ccorres_guard_imp2)
apply (rule ccorres_cond_false)
apply (rule ccorres_return_Skip')
apply (simp add: pn')
done
next
case (Cons y ys)
from Cons.prems have ly: "length (y # ys) \<le> length init_xs" by simp
hence ln: "(length init_xs - length ys) = Suc (length init_xs - length (y # ys))" by simp
hence yv: "y = init_xs ! (length init_xs - length (y # ys))" using Cons.prems
by (fastforce simp add: drop_Suc_nth not_le)
have lt0: "0 < length init_xs" using ly by clarsimp
hence ly': "length init_xs - length (y # ys) < length init_xs" by simp
note one'' = one'[OF ly', simplified yv[symmetric]]
have ys_eq: "ys = drop (length init_xs - length ys) init_xs"
using ln Cons.prems
by (fastforce simp add: drop_Suc_nth not_le)
note ih = Cons.hyps [OF ys_eq, rule_format]
note hi'' = hi' [OF ly', folded yv]
show ?case
apply (clarsimp simp: sequenceE_Cons)
apply (rule ccorres_guard_imp2)
apply (rule iffD1 [OF ccorres_expand_while_iff])
apply (rule ccorres_cond_true)
apply (rule ccorres_rhs_assoc)+
apply (rule ccorres_splitE)
apply (simp add: inl_rrel_inl_rrel)
apply (rule_tac ys="zs" in one'')
apply simp
apply (rule ceqv_refl)
apply (rule ccorres_symb_exec_r)
apply (simp add: liftME_def[symmetric] liftME_liftM)
apply (rule ccorres_rel_imp2, rule_tac zs="zs @ [rv]" in ih)
apply (cut_tac ly, simp)
apply (clarsimp elim!: inl_inrE)
apply (clarsimp elim!: inl_inrE)
apply vcg
apply (rule conseqPre)
apply vcg
apply (clarsimp simp: xf xf')
apply (subst ln)
apply (rule hi'')
apply (rule HoarePartialDef.Conseq [where P = "Q \<inter> {s. xfrel_upd (xf s) = xfrel (length init_xs - length ys)}"])
apply (intro ballI exI)
apply (rule conjI)
apply (rule_tac s=s in bodyi)
apply simp
apply (clarsimp simp: xf xf' ccHoarePost_def elim!: inl_inrE)
apply (clarsimp simp: ln pn' xfrel_u diff_Suc_less[OF lt0])
done
qed
thus ?thesis
by (clarsimp simp: init_xs_def dest!: spec[where x=Nil]
elim!: ccorres_rel_imp2 inl_inrE)
qed
lemma ccorres_sequenceE_while_down:
fixes xf :: "globals myvars \<Rightarrow> ('c :: len) word"
assumes one: "\<And>n ys. \<lbrakk> n < length xs; n = length ys \<rbrakk> \<Longrightarrow>
ccorres_underlying sr \<Gamma> (inr_rrel (\<lambda>rv rv'. r' (ys @ [rv]) rv')) xf'
(inl_rrel arrel) axf
(F n) (Q \<inter> {s. xf s = (startv - of_nat n) \<and> r' ys (xf' s)}) hs
(xs ! n) body"
and pn: "\<And>n. (n < length xs \<longrightarrow> P (startv - of_nat n)) \<and> \<not> P (startv - of_nat (length xs))"
and bodyi: "\<And>s. s \<in> Q \<Longrightarrow> \<Gamma> \<turnstile>\<^bsub>/UNIV\<^esub> {s} body (Q \<inter> {t. xf t = xf s}), UNIV"
and hi: "\<And>n. n < length xs \<Longrightarrow> \<lbrace> F n \<rbrace> (xs ! n) \<lbrace>\<lambda>_. F (Suc n)\<rbrace>,-"
and xf: "\<forall>s f. xf (xf_update f s) = f (xf s)"
and xf': "\<forall>s f. xf' (xf_update f s) = (xf' s)
\<and> ((xf_update f s \<in> Q) = (s \<in> Q))
\<and> (\<forall>s'. ((s', xf_update f s) \<in> sr) = ((s', s) \<in> sr))"
shows "ccorres_underlying sr \<Gamma> (inr_rrel (\<lambda>rv (i', rv'). r' rv rv' \<and> i' = (startv - of_nat (length xs))))
(\<lambda>s. (xf s, xf' s)) arrel axf
(F 0) (Q \<inter> {s. xf s = (startv - of_nat 0) \<and> r' [] (xf' s)}) hs
(sequenceE xs)
(While {s. P (xf s)}
(body ;; Basic (\<lambda>s. xf_update (\<lambda>_. xf s - 1) s)))"
(is "ccorres_underlying sr \<Gamma> (inr_rrel ?r') ?xf' arrel axf ?G ?G' hs (sequenceE xs) ?body")
by (rule ccorres_sequenceE_while_gen_either_way
[OF one, where xf_update=xf_update],
simp_all add: bodyi hi xf xf' pn)
lemma ccorres_sequenceE_while_gen':
fixes i :: "nat" and xf :: "globals myvars \<Rightarrow> ('c :: len) word"
assumes one: "\<And>n ys. \<lbrakk> n < length xs; n = length ys \<rbrakk> \<Longrightarrow>
ccorres_underlying sr \<Gamma> (inr_rrel (\<lambda>rv rv'. r' (ys @ [rv]) rv')) xf'
(inl_rrel arrel) axf
(F n) (Q \<inter> {s. xf s = of_nat (i + n) \<and> r' ys (xf' s)}) hs
(xs ! n) body"
and pn: "\<And>n. P n = (n < of_nat (i + length xs))"
and bodyi: "\<And>s. s \<in> Q \<Longrightarrow> \<Gamma> \<turnstile>\<^bsub>/UNIV\<^esub> {s} body (Q \<inter> {t. xf t = xf s}), UNIV"
and hi: "\<And>n. n < length xs \<Longrightarrow> \<lbrace> F n \<rbrace> (xs ! n) \<lbrace>\<lambda>_. F (Suc n)\<rbrace>,-"
and lxs: "i + length xs < 2 ^ len_of TYPE('c)"
and xf: "\<forall>s f. xf (xf_update f s) = f (xf s)"
and xf': "\<forall>s f. xf' (xf_update f s) = (xf' s)
\<and> ((xf_update f s \<in> Q) = (s \<in> Q))
\<and> (\<forall>s'. ((s', xf_update f s) \<in> sr) = ((s', s) \<in> sr))"
shows "ccorres_underlying sr \<Gamma> (inr_rrel (\<lambda>rv (i', rv'). r' rv rv' \<and> i' = of_nat (i + length xs)))
(\<lambda>s. (xf s, xf' s)) arrel axf
(F 0) (Q \<inter> {s. xf s = of_nat i \<and> r' [] (xf' s)}) hs
(sequenceE xs)
(While {s. P (xf s)}
(body ;; Basic (\<lambda>s. xf_update (\<lambda>_. xf s + 1) s)))"
(is "ccorres_underlying sr \<Gamma> (inr_rrel ?r') ?xf' arrel axf ?G ?G' hs (sequenceE xs) ?body")
apply (rule ccorres_sequenceE_while_gen_either_way
[OF one, where xf_update=xf_update, simplified add_0_right],
simp_all add: bodyi hi lxs xf xf' pn)
apply clarsimp
apply (simp only: Abs_fnat_hom_add, rule of_nat_mono_maybe)
apply (rule lxs)
apply simp
done
lemma ccorres_sequenceE_while:
fixes axf :: "globals myvars \<Rightarrow> 'e" shows
"\<lbrakk>\<And>ys. length ys < length xs \<Longrightarrow>
ccorres_underlying sr \<Gamma> (inr_rrel (\<lambda>rv rv'. r' (ys @ [rv]) rv')) xf'
(inl_rrel arrel) axf
(F (length ys)) (Q \<inter> {s. i_' s = of_nat (length ys) \<and> r' ys (xf' s)}) hs
(xs ! length ys) body;
\<And>n. P n = (n < of_nat (length xs));
\<And>s. s \<in> Q \<Longrightarrow> \<Gamma>\<turnstile>\<^bsub>/UNIV\<^esub> {s} body (Q \<inter> {t. i_' t = i_' s}),UNIV;
\<And>n. n < length xs \<Longrightarrow> \<lbrace>F n\<rbrace> xs ! n \<lbrace>\<lambda>_. F (Suc n)\<rbrace>, -;
length xs < 2 ^ word_bits;
\<forall>s f. xf' (i_'_update f s) = xf' s
\<and> ((i_'_update f s \<in> Q) = (s \<in> Q))
\<and> (\<forall>s'. ((s', i_'_update f s) \<in> sr) = ((s', s) \<in> sr)) \<rbrakk>
\<Longrightarrow> ccorres_underlying sr \<Gamma> (inr_rrel (\<lambda>rv (i', rv'). r' rv rv' \<and> i' = of_nat (length xs)))
(\<lambda>s. (i_' s, xf' s)) arrel axf
(F 0) (Q \<inter> {s. r' [] (xf' s)}) hs
(sequenceE xs)
(Basic (\<lambda>s. i_'_update (\<lambda>_. 0) s) ;;
While {s. P (i_' s)} (body;;
Basic (\<lambda>s. i_'_update (\<lambda>_. i_' s + 1) s)))"
apply (rule ccorres_guard_imp2)
apply (rule ccorres_symb_exec_r)
apply (rule ccorres_sequenceE_while_gen'[where i=0, simplified, where xf_update=i_'_update],
(assumption | simp)+)
apply (simp add: word_bits_def)
apply simp+
apply vcg
apply (rule conseqPre, vcg)
apply clarsimp
apply simp
done
context kernel begin
lemma ccorres_split_nothrow_novcg_case_sum:
"\<lbrakk>ccorresG sr \<Gamma> (f' \<currency> r') (liftxf es ef' vf' xf') P P' [] a c;
\<And>rv' t t'. ceqv \<Gamma> xf' rv' t t' d (d' rv');
\<And>rv rv'. \<lbrakk> r' rv (vf' rv'); ef' rv' = scast EXCEPTION_NONE \<rbrakk>
\<Longrightarrow> ccorres_underlying sr \<Gamma> r xf arrel axf (Q rv) (Q' rv rv') hs (b rv) (d' rv');
\<And>err rv' err'.
\<lbrakk> ef' rv' \<noteq> scast EXCEPTION_NONE; f' err (ef' rv') err' \<rbrakk>
\<Longrightarrow> ccorres_underlying sr \<Gamma> r xf arrel axf (QE err) (Q'' err rv' err') hs (e err) (d' rv');
\<lbrace>R\<rbrace> a \<lbrace>Q\<rbrace>, \<lbrace>QE\<rbrace>; guard_is_UNIV (\<lambda>rv rv'. r' rv (vf' rv')) xf'
(\<lambda>rv rv'. {s. ef' rv' = scast EXCEPTION_NONE \<longrightarrow> s \<in> Q' rv rv'});
\<And>err. guard_is_UNIV (\<lambda>rv. f' err (ef' rv)) es
(\<lambda>rv rv'. {s. ef' (xf' s) \<noteq> scast EXCEPTION_NONE \<longrightarrow> s \<in> Q'' err rv rv'})\<rbrakk>
\<Longrightarrow> ccorres_underlying sr \<Gamma> r xf arrel axf (P and R) P' hs (a >>= case_sum e b) (c;;d)"
apply (rule_tac R="case_sum QE Q" and R'="case_sum QE' QR'" for QE' QR'
in ccorres_master_split_nohs_UNIV)
apply assumption
apply (case_tac rv, simp_all)[1]
apply (erule ccorres_abstract)
apply (rule ccorres_abstract[where xf'=es], rule ceqv_refl)
apply (rule_tac P="ef' rv' \<noteq> scast EXCEPTION_NONE" in ccorres_gen_asm2)
apply (rule_tac P="f' aa (ef' rv') rv'a" in ccorres_gen_asm2)
apply assumption
apply (erule ccorres_abstract)
apply (rule_tac P="r' ba (vf' rv')" in ccorres_gen_asm2)
apply (rule_tac P="ef' rv' = scast EXCEPTION_NONE" in ccorres_gen_asm2)
apply assumption
apply (simp add: validE_def)
apply (erule hoare_strengthen_post, simp split: sum.split_asm)
apply (clarsimp simp: guard_is_UNIV_def
split: sum.split)
done
lemma ccorres_split_nothrow_case_sum:
"\<lbrakk>ccorresG sr \<Gamma> (f' \<currency> r') (liftxf es ef' vf' xf') P P' hs a c;
\<And>rv' t t'. ceqv \<Gamma> xf' rv' t t' d (d' rv');
\<And>rv rv'. \<lbrakk> r' rv (vf' rv'); ef' rv' = scast EXCEPTION_NONE \<rbrakk>
\<Longrightarrow> ccorres_underlying sr \<Gamma> r xf arrel axf (Q rv) (Q' rv rv') hs (b rv) (d' rv');
\<And>err rv' err'.
\<lbrakk> ef' rv' \<noteq> scast EXCEPTION_NONE; f' err (ef' rv') err' \<rbrakk>
\<Longrightarrow> ccorres_underlying sr \<Gamma> r xf arrel axf (QE err) (Q'' err rv' err') hs (e err) (d' rv');
\<lbrace>R\<rbrace> a \<lbrace>Q\<rbrace>, \<lbrace>QE\<rbrace>; \<Gamma> \<turnstile>\<^bsub>/UNIV\<^esub> R' c {s. (\<forall>rv'. ef' (xf' s) = scast EXCEPTION_NONE \<longrightarrow> r' rv' (vf' (xf' s))
\<longrightarrow> s \<in> Q' rv' (xf' s))
\<and> (\<forall>ft. ef' (xf' s) \<noteq> scast EXCEPTION_NONE \<longrightarrow> f' ft (ef' (xf' s)) (es s)
\<longrightarrow> s \<in> Q'' ft (xf' s) (es s))} \<rbrakk>
\<Longrightarrow> ccorres_underlying sr \<Gamma> r xf arrel axf (P and R) (P' \<inter> R') hs (a >>= case_sum e b) (c;;d)"
apply (erule_tac R="case_sum QE Q" and R'="case_sum QE' QR'" for QE' QR'
in ccorres_master_split_hs)
apply (case_tac rv, simp_all)[1]
apply (erule ccorres_abstract)
apply (rule ccorres_abstract[where xf'=es], rule ceqv_refl)
apply (rule_tac P="ef' rv' \<noteq> scast EXCEPTION_NONE" in ccorres_gen_asm2)
apply (rule_tac P="f' aa (ef' rv') rv'a" in ccorres_gen_asm2)
apply assumption
apply (erule ccorres_abstract)
apply (rule_tac P="r' ba (vf' rv')" in ccorres_gen_asm2)
apply (rule_tac P="ef' rv' = scast EXCEPTION_NONE" in ccorres_gen_asm2)
apply assumption
apply (rule ccorres_empty[where P=\<top>])
apply (simp add: validE_def)
apply (erule hoare_strengthen_post, simp split: sum.split_asm)
apply (drule exec_handlers_Hoare_from_vcg_nofail)
apply (erule exec_handlers_Hoare_Post [OF _ _ subset_refl])
apply (clarsimp simp: ccHoarePost_def split: sum.split)
done
end
end
|
lemma simply_connected_imp_connected: fixes S :: "_::real_normed_vector set" shows "simply_connected S \<Longrightarrow> connected S" |
// Copyright (C) 2011 Tim Blechmann
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/lockfree/queue.hpp>
#include <boost/thread.hpp>
#define BOOST_TEST_MAIN
#ifdef BOOST_LOCKFREE_INCLUDE_TESTS
#include <boost/test/included/unit_test.hpp>
#else
#include <boost/test/unit_test.hpp>
#endif
#include <memory>
using namespace boost;
using namespace boost::lockfree;
using namespace std;
BOOST_AUTO_TEST_CASE( simple_queue_test )
{
queue<int> f(64);
BOOST_WARN(f.is_lock_free());
BOOST_REQUIRE(f.empty());
f.push(1);
f.push(2);
int i1(0), i2(0);
BOOST_REQUIRE(f.pop(i1));
BOOST_REQUIRE_EQUAL(i1, 1);
BOOST_REQUIRE(f.pop(i2));
BOOST_REQUIRE_EQUAL(i2, 2);
BOOST_REQUIRE(f.empty());
}
BOOST_AUTO_TEST_CASE( simple_queue_test_capacity )
{
queue<int, capacity<64> > f;
BOOST_WARN(f.is_lock_free());
BOOST_REQUIRE(f.empty());
f.push(1);
f.push(2);
int i1(0), i2(0);
BOOST_REQUIRE(f.pop(i1));
BOOST_REQUIRE_EQUAL(i1, 1);
BOOST_REQUIRE(f.pop(i2));
BOOST_REQUIRE_EQUAL(i2, 2);
BOOST_REQUIRE(f.empty());
}
BOOST_AUTO_TEST_CASE( unsafe_queue_test )
{
queue<int> f(64);
BOOST_WARN(f.is_lock_free());
BOOST_REQUIRE(f.empty());
int i1(0), i2(0);
f.unsynchronized_push(1);
f.unsynchronized_push(2);
BOOST_REQUIRE(f.unsynchronized_pop(i1));
BOOST_REQUIRE_EQUAL(i1, 1);
BOOST_REQUIRE(f.unsynchronized_pop(i2));
BOOST_REQUIRE_EQUAL(i2, 2);
BOOST_REQUIRE(f.empty());
}
BOOST_AUTO_TEST_CASE( queue_convert_pop_test )
{
queue<int*> f(128);
BOOST_REQUIRE(f.empty());
f.push(new int(1));
f.push(new int(2));
f.push(new int(3));
f.push(new int(4));
{
int * i1;
BOOST_REQUIRE(f.pop(i1));
BOOST_REQUIRE_EQUAL(*i1, 1);
delete i1;
}
{
boost::shared_ptr<int> i2;
BOOST_REQUIRE(f.pop(i2));
BOOST_REQUIRE_EQUAL(*i2, 2);
}
{
auto_ptr<int> i3;
BOOST_REQUIRE(f.pop(i3));
BOOST_REQUIRE_EQUAL(*i3, 3);
}
{
boost::shared_ptr<int> i4;
BOOST_REQUIRE(f.pop(i4));
BOOST_REQUIRE_EQUAL(*i4, 4);
}
BOOST_REQUIRE(f.empty());
}
|
"""
Polar jet
North Pole is set at theta=0 and phi=0, with param.lat_pole_shift
"""
import numpy as np
from parameters import Param
from grid import Grid
from rsw import RSW
pi = np.pi
sin = np.sin
cos = np.cos
arccos = np.arccos
a = 6.37122e6
Omega = 7.292e-5
g = 9.860616
day = 86400.
param = Param()
reso = 2
param.expname = "polar"
param.phi = [-pi/4, pi/4]
param.theta = [-pi/4, pi/4]
param.nz = 1
param.ny = 50*reso
param.nx = 50*reso
param.geometry = "closed"
param.coordinates = "spherical"
param.lat_pole_shift = -pi/2.
param.timeunit = day
param.dt = 200./reso
param.tend = 50*day # 100*param.dt
param.plotvar = "pv"
param.freq_plot = 100
param.freq_his = day
param.plot_interactive = True
param.colorscheme = "auto"
param.timestepping = "RK3_SSP"
param.g = g
param.H = 4000.
param.u0 = 0.2
param.r0 = 0.95
param.amp = 0.05
param.sigma = 0.05
param.Omega = Omega
param.sphere_radius = a
param.noslip = False
param.var_to_save = ["h", "vor", "pv", "u"]
grid = Grid(param)
ic, jc = grid.ic, grid.jc
ie, je = grid.ie, grid.je
grid.finalize()
model = RSW(param, grid)
h = model.state.h
u = model.state.ux
v = model.state.uy
area = grid.arrays.vol.view("i")
alpha = param.lat_pole_shift
h0 = param.H
u0 = param.u0
def hprofile(r, r0,sigma):
""" gaussian profile
r is a radial coordinate from the domain center
watch out r = 1 at the origin and decreases with the distance
"""
return np.exp( -(r-r0)**2/(2*sigma**2))
theta = grid.coord.theta(jc, ic)
lambd = grid.coord.phi(jc, ic)
r = cos(lambd)*cos(theta)
h[0] = h0*(1+param.amp*hprofile(r, param.r0, param.sigma))
h[0] *= area
theta = grid.coord.theta(je, ie)
lambd = grid.coord.phi(je, ie)
r = cos(lambd)*cos(theta)
hF = model.state.vor
hF[0] = h0*(1+param.amp*hprofile(r, param.r0, param.sigma))
def grad(phi, dphidx, dphidy):
phi.setview("i")
dphidx.setview("i")
dphidx[:] = phi[..., 1:]-phi[..., :-1]
phi.setview("j")
dphidy.setview("j")
dphidy[:] = phi[..., 1:]-phi[..., :-1]
u[:] = 0.
v[:] = 0.
# then take the rotated gradient of it
grad(hF, v, u)
theta = grid.coord.theta(jc, ie)
lambd = grid.coord.phi(jc, ie)
r = cos(lambd)*cos(theta)
u = model.state.ux.view("i")
u[0] *= -g/(param.Omega*2*r)
theta = grid.coord.theta(je, ic)
lambd = grid.coord.phi(je, ic)
r = cos(lambd)*cos(theta)
u = model.state.uy.view("i")
v[0] *= +g/(param.Omega*2*r)
u = model.state.ux.view("i")
v = model.state.uy.view("j")
msk = grid.arrays.msk.view("i")
h = model.state.h.view("i")
msku = grid.msku()
mskv = grid.mskv()
for k in range(param.nz):
u[k] *= msku
v[k] *= mskv
h[k][msk == 0] = param.H*area[msk == 0]
hF[:] = 0.
model.run()
|
= = Ninth commandment = =
|
inductive aexpr : Type
| const : ℕ → aexpr
| var : ℕ → aexpr
| plus : aexpr → aexpr → aexpr
| times : aexpr → aexpr → aexpr
open aexpr
def sample_aexpr : aexpr :=
plus (times (var 0) (const 7)) (times (const 2) (var 1))
-- BEGIN
def aeval (v : ℕ → ℕ) : aexpr → ℕ
| (const n) := n
| (var n) := v n
| (plus e₁ e₂) := (aeval e₁) + (aeval e₂)
| (times e₁ e₂) := (aeval e₁) * (aeval e₂)
def sample_val : ℕ → ℕ
| 0 := 5
| 1 := 6
| _ := 0
-- Try it out. You should get 47 here.
#eval aeval sample_val sample_aexpr
-- END
-- BEGIN
def simp_const : aexpr → aexpr
| (plus (const n₁) (const n₂)) := const (n₁ + n₂)
| (times (const n₁) (const n₂)) := const (n₁ * n₂)
| e := e
def fuse : aexpr → aexpr
| (plus e₁ e₂) := simp_const (plus (fuse e₁) (fuse e₂))
| (times e₁ e₂) := simp_const (times (fuse e₁) (fuse e₂))
| e := e
#eval aeval sample_val (fuse sample_aexpr)
theorem simp_const_eq (v : ℕ → ℕ) :
∀ e : aexpr, aeval v (simp_const e) = aeval v e
| (const n) := rfl
| (var n) := rfl
| (plus e1 e2) := begin
cases e1, {
cases e2, reflexivity,
repeat { dsimp [simp_const], reflexivity }
},
repeat {
dsimp [simp_const], reflexivity
}
end
| (times e1 e2) := begin
cases e1, {
cases e2, reflexivity,
repeat { dsimp [simp_const], reflexivity }
},
repeat {
dsimp [simp_const], reflexivity
}
end
theorem fuse_eq (v : ℕ → ℕ) :
∀ e : aexpr, aeval v (fuse e) = aeval v e
| (plus e1 e2) := begin
dsimp [fuse],
simp [simp_const_eq],
dsimp [aeval],
simp [fuse_eq e1, fuse_eq e2],
end
| (times e1 e2) := begin
dsimp [fuse],
simp [simp_const_eq],
dsimp [aeval],
simp [fuse_eq e1, fuse_eq e2],
end
| (const _) := rfl
| (var _) := rfl
-- END
|
(*
* Copyright 2014, General Dynamics C4 Systems
*
* SPDX-License-Identifier: GPL-2.0-only
*)
theory CSpace_C
imports CSpaceAcc_C Machine_C
begin
unbundle l4v_word_context
context kernel_m
begin
lemma maskCapRights_cap_cases:
"return (maskCapRights R c) =
(case c of
ArchObjectCap ac \<Rightarrow> return (Arch.maskCapRights R ac)
| EndpointCap _ _ _ _ _ _ \<Rightarrow>
return (capEPCanGrantReply_update (\<lambda>_. capEPCanGrantReply c \<and> capAllowGrantReply R)
(capEPCanGrant_update (\<lambda>_. capEPCanGrant c \<and> capAllowGrant R)
(capEPCanReceive_update (\<lambda>_. capEPCanReceive c \<and> capAllowRead R)
(capEPCanSend_update (\<lambda>_. capEPCanSend c \<and> capAllowWrite R) c))))
| NotificationCap _ _ _ _ \<Rightarrow>
return (capNtfnCanReceive_update
(\<lambda>_. capNtfnCanReceive c \<and> capAllowRead R)
(capNtfnCanSend_update
(\<lambda>_. capNtfnCanSend c \<and> capAllowWrite R) c))
| ReplyCap _ _ _ \<Rightarrow>
return (capReplyCanGrant_update
(\<lambda>_. capReplyCanGrant c \<and> capAllowGrant R) c)
| _ \<Rightarrow> return c)"
apply (simp add: maskCapRights_def Let_def split del: if_split)
apply (cases c; simp add: isCap_simps split del: if_split)
done
(* FIXME x64: ucast? see how it goes *)
lemma wordFromVMRights_spec:
"\<forall>s. \<Gamma> \<turnstile> {s} Call wordFromVMRights_'proc \<lbrace>\<acute>ret__unsigned_long = \<^bsup>s\<^esup>vm_rights\<rbrace>"
by vcg simp?
(* FIXME x64: ucast? see how it goes *)
lemma vmRightsFromWord_spec:
"\<forall>s. \<Gamma> \<turnstile> {s} Call vmRightsFromWord_'proc \<lbrace>\<acute>ret__unsigned_long = \<^bsup>s\<^esup>w\<rbrace>"
by vcg simp?
lemmas vmrights_defs =
Kernel_C.VMReadOnly_def
Kernel_C.VMKernelOnly_def
Kernel_C.VMReadWrite_def
lemma maskVMRights_spec:
"\<forall>s. \<Gamma> \<turnstile> ({s} \<inter>
\<lbrace> \<acute>vm_rights && mask 2 = \<acute>vm_rights \<rbrace>)
Call maskVMRights_'proc
\<lbrace> vmrights_to_H \<acute>ret__unsigned_long =
maskVMRights (vmrights_to_H \<^bsup>s\<^esup>vm_rights) (cap_rights_to_H (seL4_CapRights_lift \<^bsup>s\<^esup>cap_rights_mask)) \<and>
\<acute>ret__unsigned_long && mask 2 = \<acute>ret__unsigned_long \<and>
\<acute>ret__unsigned_long \<noteq> 0 \<rbrace>"
apply vcg
apply clarsimp
apply (rule conjI)
apply ((auto simp: vmrights_to_H_def maskVMRights_def vmrights_defs
cap_rights_to_H_def to_bool_def
split: bool.split
| simp add: mask_def
| word_bitwise)+)[1]
apply clarsimp
apply (subgoal_tac "vm_rights = 0 \<or> vm_rights = 1 \<or> vm_rights = 2 \<or> vm_rights = 3")
apply (auto simp: vmrights_to_H_def maskVMRights_def vmrights_defs
cap_rights_to_H_def seL4_CapRights_lift_def
to_bool_def mask_def
split: bool.splits)[1]
apply (subst(asm) mask_eq_iff_w2p)
apply (simp add: word_size)
apply (rule ccontr, clarsimp)
apply (drule inc_le, simp, drule(1) order_le_neq_trans [OF _ not_sym])+
apply (drule inc_le, simp)
done
lemma frame_cap_rights [simp]:
"cap_get_tag cap = scast cap_frame_cap
\<Longrightarrow> cap_frame_cap_CL.capFVMRights_CL (cap_frame_cap_lift cap) && mask 2 =
cap_frame_cap_CL.capFVMRights_CL (cap_frame_cap_lift cap)"
apply (simp add: cap_frame_cap_lift_def)
by (simp add: cap_lift_def cap_tag_defs mask_def word_bw_assocs)
lemma Arch_maskCapRights_ccorres [corres]:
"ccorres ccap_relation ret__struct_cap_C_'
\<top>
(UNIV \<inter> \<lbrace>ccap_relation (ArchObjectCap arch_cap) \<acute>cap\<rbrace> \<inter>
\<lbrace>ccap_rights_relation R \<acute>cap_rights_mask\<rbrace>)
[]
(return (Arch.maskCapRights R arch_cap))
(Call Arch_maskCapRights_'proc)"
apply (cinit' lift: cap_' cap_rights_mask_')
apply csymbr
apply (unfold X64_H.maskCapRights_def)
apply (simp only: Let_def)
apply (case_tac "cap_get_tag cap = scast cap_frame_cap")
apply (clarsimp simp add: ccorres_cond_iffs cap_get_tag_isCap isCap_simps split del: if_splits)
apply (rule ccorres_from_vcg_throws [where P=\<top> and P'=UNIV])
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp: cap_get_tag_isCap isCap_simps)
apply (clarsimp simp: return_def)
apply (unfold ccap_relation_def)[1]
apply (simp add: cap_frame_cap_lift [THEN iffD1])
apply (clarsimp simp: cap_to_H_def)
apply (simp add: map_option_case split: option.splits)
apply (clarsimp simp: cap_to_H_def Let_def split: cap_CL.splits if_split_asm)
apply (clarsimp simp: cap_frame_cap_lift_def)
apply (clarsimp simp: ccap_rights_relation_def cap_frame_cap_lift c_valid_cap_def
cl_valid_cap_def mask_eq_iff word_less_alt
split: option.splits cap_CL.splits)
apply (clarsimp simp: cap_frame_cap_lift_def)
apply (clarsimp simp: ccap_rights_relation_def c_valid_cap_def cap_frame_cap_lift
cl_valid_cap_def mask_eq_iff word_less_alt)
apply (clarsimp simp add: cap_get_tag_isCap isCap_simps simp del: not_ex)
apply (rule conjI, clarsimp)
apply (simp add: ccorres_cond_iffs)
apply (rule ccorres_from_vcg_throws)
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp add: return_def simp del: not_ex)
apply (cases arch_cap)
by (fastforce simp add: cap_get_tag_isCap isCap_simps simp del: not_ex simp_thms(44))+
lemma to_bool_mask_to_bool_bf:
"to_bool (x && 1) = to_bool_bf (x::machine_word)"
by (simp add: to_bool_bf_def to_bool_def)
lemma to_bool_cap_rights_bf:
"to_bool (capAllowRead_CL (seL4_CapRights_lift R)) =
to_bool_bf (capAllowRead_CL (seL4_CapRights_lift R))"
"to_bool (capAllowWrite_CL (seL4_CapRights_lift R)) =
to_bool_bf (capAllowWrite_CL (seL4_CapRights_lift R))"
"to_bool (capAllowGrant_CL (seL4_CapRights_lift R)) =
to_bool_bf (capAllowGrant_CL (seL4_CapRights_lift R))"
"to_bool (capAllowGrantReply_CL (seL4_CapRights_lift R)) =
to_bool_bf (capAllowGrantReply_CL (seL4_CapRights_lift R))"
by (subst to_bool_bf_to_bool_mask,
simp add: seL4_CapRights_lift_def mask_def word_bw_assocs, simp)+
lemma to_bool_ntfn_cap_bf:
"cap_lift c = Some (Cap_notification_cap cap) \<Longrightarrow>
to_bool (capNtfnCanSend_CL cap) = to_bool_bf (capNtfnCanSend_CL cap) \<and>
to_bool (capNtfnCanReceive_CL cap) = to_bool_bf (capNtfnCanReceive_CL cap)"
apply (simp add:cap_lift_def Let_def split: if_split_asm)
apply (subst to_bool_bf_to_bool_mask,
clarsimp simp: cap_lift_thread_cap mask_def word_bw_assocs)+
apply simp
done
lemma to_bool_reply_cap_bf:
"cap_lift c = Some (Cap_reply_cap cap)
\<Longrightarrow> to_bool (capReplyMaster_CL cap) = to_bool_bf (capReplyMaster_CL cap)
\<and> to_bool (capReplyCanGrant_CL cap) = to_bool_bf (capReplyCanGrant_CL cap)"
apply (simp add: cap_lift_def Let_def split: if_split_asm)
apply (subst to_bool_bf_to_bool_mask,
clarsimp simp: cap_lift_thread_cap mask_def word_bw_assocs)+
apply simp
done
lemma to_bool_ep_cap_bf:
"cap_lift c = Some (Cap_endpoint_cap cap) \<Longrightarrow>
to_bool (capCanSend_CL cap) = to_bool_bf (capCanSend_CL cap) \<and>
to_bool (capCanReceive_CL cap) = to_bool_bf (capCanReceive_CL cap) \<and>
to_bool (capCanGrant_CL cap) = to_bool_bf (capCanGrant_CL cap) \<and>
to_bool (capCanGrantReply_CL cap) = to_bool_bf (capCanGrantReply_CL cap)"
apply (simp add:cap_lift_def Let_def split: if_split_asm)
apply (subst to_bool_bf_to_bool_mask,
clarsimp simp: cap_lift_thread_cap mask_def word_bw_assocs)+
apply simp
done
lemma isArchCap_spec:
"\<forall>s. \<Gamma>\<turnstile> {s} Call isArchCap_'proc \<lbrace>\<acute>ret__unsigned_long = from_bool (isArchCap_tag (cap_get_tag (cap_' s)))\<rbrace>"
apply vcg
apply (clarsimp simp: from_bool_def isArchCap_tag_def bool.split)
done
lemma maskCapRights_ccorres [corres]:
"ccorres ccap_relation ret__struct_cap_C_'
\<top>
(UNIV \<inter> \<lbrace>ccap_relation cap \<acute>cap\<rbrace> \<inter> \<lbrace>ccap_rights_relation R \<acute>cap_rights\<rbrace>)
[]
(return (RetypeDecls_H.maskCapRights R cap)) (Call maskCapRights_'proc)"
apply (cinit' lift: cap_' cap_rights_')
apply csymbr
apply (simp add: maskCapRights_cap_cases cap_get_tag_isCap del: Collect_const)
apply wpc
apply (simp add: Collect_const_mem from_bool_def)
apply csymbr
apply (simp add: cap_get_tag_isCap isCap_simps del: Collect_const)
apply (simp add: ccorres_cond_iffs)
apply (rule ccorres_from_vcg_throws [where P=\<top> and P'=UNIV])
apply (rule allI)
apply (rule conseqPre)
apply vcg
apply clarsimp
apply (simp add: cap_get_tag_isCap isCap_simps return_def)
apply (simp add: Collect_const_mem from_bool_def)
apply csymbr
apply (simp add: cap_get_tag_isCap isCap_simps del: Collect_const)
apply (simp add: ccorres_cond_iffs)
apply (rule ccorres_from_vcg_throws [where P=\<top> and P'=UNIV])
apply (rule allI)
apply (rule conseqPre)
apply vcg
apply (clarsimp simp: return_def)
apply (simp add: Collect_const_mem from_bool_def)
apply csymbr
apply (simp add: cap_get_tag_isCap isCap_simps del: Collect_const)
apply (simp add: ccorres_cond_iffs)
apply (rule ccorres_from_vcg_throws [where P=\<top> and P'=UNIV])
apply (rule allI)
apply (rule conseqPre)
apply vcg
apply clarsimp
apply (simp add: cap_get_tag_isCap isCap_simps return_def)
apply (rule imp_ignore)
apply (rule imp_ignore)
apply (rule imp_ignore)
apply (rule imp_ignore)
apply (rule imp_ignore)
apply clarsimp
apply (unfold ccap_relation_def)[1]
apply (simp add: cap_notification_cap_lift [THEN iffD1])
apply (clarsimp simp: cap_to_H_def)
apply (simp add: map_option_case split: option.splits)
apply (clarsimp simp add: cap_to_H_def Let_def
split: cap_CL.splits if_split_asm)
apply (simp add: cap_notification_cap_lift_def)
apply (simp add: ccap_rights_relation_def cap_rights_to_H_def
to_bool_ntfn_cap_bf
to_bool_mask_to_bool_bf to_bool_cap_rights_bf)
apply (simp add: Collect_const_mem from_bool_def)
apply csymbr
apply (simp add: cap_get_tag_isCap isCap_simps ccorres_cond_iffs)
apply (rule ccorres_from_vcg_throws [where P=\<top> and P'=UNIV])
apply (rule allI)
apply (rule conseqPre)
apply vcg
apply (clarsimp simp: cap_get_tag_isCap isCap_simps return_def)
apply (simp add: Collect_const_mem from_bool_def)
apply csymbr
apply (simp add: cap_get_tag_isCap isCap_simps ccorres_cond_iffs)
apply (rule ccorres_from_vcg_throws [where P=\<top> and P'=UNIV])
apply (rule allI)
apply (rule conseqPre)
apply vcg
apply clarsimp
apply (simp add: cap_get_tag_isCap isCap_simps return_def)
apply (rule imp_ignore)
apply (rule imp_ignore)
apply (rule imp_ignore)
apply (rule imp_ignore)
apply (rule imp_ignore)
apply (rule imp_ignore)
apply (rule imp_ignore)
apply (rule imp_ignore)
apply clarsimp
apply (unfold ccap_relation_def)[1]
apply (simp add: cap_endpoint_cap_lift [THEN iffD1])
apply (clarsimp simp: cap_to_H_def)
apply (simp add: map_option_case split: option.splits)
apply (clarsimp simp add: cap_to_H_def Let_def
split: cap_CL.splits if_split_asm)
apply (simp add: cap_endpoint_cap_lift_def)
apply (simp add: ccap_rights_relation_def cap_rights_to_H_def
to_bool_ep_cap_bf
to_bool_mask_to_bool_bf to_bool_cap_rights_bf)
apply (simp add: Collect_const_mem from_bool_def)
apply csymbr
apply (simp add: cap_get_tag_isCap isCap_simps del: Collect_const)
apply (simp add: ccorres_cond_iffs)
apply (rule ccorres_from_vcg_throws [where P=\<top> and P'=UNIV])
apply (rule allI)
apply (rule conseqPre)
apply vcg
apply (clarsimp simp: return_def)
apply (simp add: Collect_const_mem from_bool_def)
apply csymbr
apply (simp add: cap_get_tag_isCap isCap_simps ccorres_cond_iffs)
apply (rule ccorres_from_vcg_throws [where P=\<top> and P'=UNIV])
apply (rule allI)
apply (rule conseqPre)
apply vcg
apply (clarsimp simp: cap_get_tag_isCap isCap_simps return_def)
apply (simp add: Collect_const_mem from_bool_def)
apply (subst bind_return [symmetric])
apply (rule ccorres_split_throws)
apply ctac
apply (rule_tac P=\<top> and P'="\<lbrace>\<acute>ret__struct_cap_C = ret__struct_cap_C\<rbrace>" in ccorres_inst)
apply (rule ccorres_from_vcg_throws)
apply (clarsimp simp: return_def)
apply (rule conseqPre)
apply vcg
apply clarsimp
apply wp
apply vcg
apply vcg
apply (simp add: Collect_const_mem from_bool_def)
apply csymbr
apply (simp add: cap_get_tag_isCap isCap_simps del: Collect_const)
apply ccorres_rewrite
apply (rule ccorres_from_vcg_throws [where P=\<top> and P'=UNIV])
apply (rule allI)
apply (rule conseqPre)
apply vcg
apply (simp add: cap_get_tag_isCap isCap_simps return_def)
apply clarsimp
apply (unfold ccap_relation_def)[1]
apply (simp add: cap_reply_cap_lift [THEN iffD1])
apply (clarsimp simp: cap_to_H_def)
apply (simp add: map_option_case split: option.splits)
apply (clarsimp simp add: cap_to_H_def Let_def
split: cap_CL.splits if_split_asm)
apply (simp add: cap_reply_cap_lift_def)
apply (simp add: ccap_rights_relation_def cap_rights_to_H_def
to_bool_reply_cap_bf
to_bool_mask_to_bool_bf[simplified] to_bool_cap_rights_bf)
apply (simp add: Collect_const_mem from_bool_def)
apply csymbr
apply (simp add: cap_get_tag_isCap isCap_simps del: Collect_const)
apply (simp add: ccorres_cond_iffs)
apply (rule ccorres_from_vcg_throws [where P=\<top> and P'=UNIV])
apply (rule allI)
apply (rule conseqPre)
apply vcg
apply (clarsimp simp: return_def)
apply (simp add: Collect_const_mem from_bool_def)
apply csymbr
apply (simp add: cap_get_tag_isCap isCap_simps del: Collect_const)
apply (simp add: ccorres_cond_iffs)
apply (rule ccorres_from_vcg_throws [where P=\<top> and P'=UNIV])
apply (rule allI)
apply (rule conseqPre)
apply vcg
apply clarsimp
apply (simp add: cap_get_tag_isCap isCap_simps return_def)
apply (simp add: Collect_const_mem from_bool_def)
apply csymbr
apply (simp add: cap_get_tag_isCap isCap_simps del: Collect_const)
apply (simp add: ccorres_cond_iffs)
apply (rule ccorres_from_vcg_throws [where P=\<top> and P'=UNIV])
apply (rule allI)
apply (rule conseqPre)
apply vcg
apply (clarsimp simp: return_def)
apply clarsimp
done
abbreviation
"lookupCap_xf \<equiv> liftxf errstate lookupCap_ret_C.status_C lookupCap_ret_C.cap_C ret__struct_lookupCap_ret_C_'"
lemma ccorres_return_cte_cteCap [corres]:
fixes ptr' :: "cstate \<Rightarrow> cte_C ptr"
assumes r1: "\<And>s s' g. (s, s') \<in> rf_sr \<Longrightarrow> (s, xfu g s') \<in> rf_sr"
and xf_xfu: "\<And>s g. xf (xfu g s) = g s"
shows "ccorres ccap_relation xf
(\<lambda>s. ctes_of s ptr = Some cte) {s. ptr_val (ptr' s) = ptr} hs
(return (cteCap cte))
(Basic (\<lambda>s. xfu (\<lambda>_. h_val (hrs_mem (t_hrs_' (globals s)))
(Ptr &(ptr' s \<rightarrow>[''cap_C'']))) s))"
apply (rule ccorres_return)
apply (rule conseqPre)
apply vcg
apply (clarsimp simp: xf_xfu ccap_relation_def)
apply rule
apply (erule r1)
apply (drule (1) rf_sr_ctes_of_clift)
apply (clarsimp simp: typ_heap_simps)
apply (simp add: c_valid_cte_def)
done
lemma ccorres_return_cte_mdbnode [corres]:
fixes ptr' :: "cstate \<Rightarrow> cte_C ptr"
assumes r1: "\<And>s s' g. (s, s') \<in> rf_sr \<Longrightarrow> (s, xfu g s') \<in> rf_sr"
and xf_xfu: "\<And>s g. xf (xfu g s) = g s"
shows "ccorres cmdbnode_relation xf
(\<lambda>s. ctes_of s ptr = Some cte) {s. ptr_val (ptr' s) = ptr} hs
(return (cteMDBNode cte))
(Basic (\<lambda>s. xfu (\<lambda>_. h_val (hrs_mem (t_hrs_' (globals s)))
(Ptr &(ptr' s \<rightarrow>[''cteMDBNode_C'']))) s))"
apply (rule ccorres_from_vcg)
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp add: return_def xf_xfu)
apply (frule (1) rf_sr_ctes_of_clift)
apply (clarsimp simp: typ_heap_simps)
apply (erule r1)
done
(* FIXME: MOVE *)
lemma heap_update_field_ext:
"\<lbrakk>field_ti TYPE('a :: packed_type) f = Some t; c_guard p;
export_uinfo t = export_uinfo (typ_info_t TYPE('b :: packed_type))\<rbrakk>
\<Longrightarrow> heap_update (Ptr &(p\<rightarrow>f) :: 'b ptr) =
(\<lambda>v hp. heap_update p (update_ti t (to_bytes_p v) (h_val hp p)) hp)"
apply (rule ext, rule ext)
apply (erule (2) heap_update_field)
done
lemma ccorres_updateCap [corres]:
fixes ptr :: "cstate \<Rightarrow> cte_C ptr" and val :: "cstate \<Rightarrow> cap_C"
shows "ccorres dc xfdc \<top>
({s. ccap_relation cap (val s)} \<inter> {s. ptr s = Ptr dest}) hs
(updateCap dest cap)
(Basic
(\<lambda>s. globals_update
(t_hrs_'_update
(hrs_mem_update (heap_update (Ptr &(ptr s\<rightarrow>[''cap_C''])) (val s)))) s))"
unfolding updateCap_def
apply (cinitlift ptr)
apply (erule ssubst)
apply (rule ccorres_guard_imp2)
apply (rule ccorres_pre_getCTE)
apply (rule_tac P = "\<lambda>s. ctes_of s dest = Some rva" in
ccorres_from_vcg [where P' = "{s. ccap_relation cap (val s)}"])
apply (rule allI)
apply (rule conseqPre)
apply vcg
apply clarsimp
apply (rule fst_setCTE [OF ctes_of_cte_at], assumption)
apply (erule bexI [rotated])
apply (clarsimp simp: cte_wp_at_ctes_of)
apply (frule (1) rf_sr_ctes_of_clift)
apply (clarsimp simp add: rf_sr_def cstate_relation_def
Let_def cpspace_relation_def
cvariable_array_map_const_add_map_option[where f="tcb_no_ctes_proj"])
apply (simp add:typ_heap_simps)
apply (rule conjI)
apply (erule (3) cpspace_cte_relation_upd_capI)
apply (frule_tac f="ksPSpace" in arg_cong)
apply (erule_tac t = s' in ssubst)
apply simp
apply (simp add: heap_to_user_data_def heap_to_device_data_def)
apply (rule conjI)
apply (erule (1) setCTE_tcb_case)
by (auto simp: carch_state_relation_def cmachine_state_relation_def
global_ioport_bitmap_heap_update_tag_disj_simps
fpu_null_state_heap_update_tag_disj_simps)
lemma ccorres_updateMDB_const [corres]:
fixes ptr :: "cstate \<Rightarrow> cte_C ptr" and val :: "cstate \<Rightarrow> mdb_node_C"
shows "ccorres dc xfdc (\<lambda>_. dest \<noteq> 0)
({s. cmdbnode_relation m (val s)} \<inter> {s. ptr s = Ptr dest}) hs
(updateMDB dest (const m))
(Basic
(\<lambda>s. globals_update
(t_hrs_'_update
(hrs_mem_update (heap_update (Ptr &(ptr s\<rightarrow>[''cteMDBNode_C''])) (val s)))) s))"
unfolding updateMDB_def
apply (cinitlift ptr)
apply (erule ssubst)
apply (rule ccorres_gen_asm [where G = \<top>, simplified])
apply (simp only: Let_def)
apply simp
apply (rule ccorres_guard_imp2)
apply (rule ccorres_pre_getCTE)
apply (rule_tac P = "\<lambda>s. ctes_of s dest = Some cte" in ccorres_from_vcg [where P' = "{s. cmdbnode_relation m (val s)}"])
apply (rule allI)
apply (rule conseqPre)
apply vcg
apply clarsimp
apply (rule fst_setCTE [OF ctes_of_cte_at], assumption )
apply (erule bexI [rotated])
apply (frule (1) rf_sr_ctes_of_clift)
apply (clarsimp simp add: rf_sr_def cstate_relation_def typ_heap_simps
Let_def cpspace_relation_def
cvariable_array_map_const_add_map_option[where f="tcb_no_ctes_proj"])
apply (rule conjI)
apply (erule (3) cspace_cte_relation_upd_mdbI)
apply (erule_tac t = s' in ssubst)
apply (simp add: heap_to_user_data_def)
apply (rule conjI)
apply (erule (1) setCTE_tcb_case)
by (auto simp: carch_state_relation_def cmachine_state_relation_def
global_ioport_bitmap_heap_update_tag_disj_simps
fpu_null_state_heap_update_tag_disj_simps)
(* 64 == badgeBits *)
lemma cap_lift_capNtfnBadge_mask_eq:
"cap_lift cap = Some (Cap_notification_cap ec)
\<Longrightarrow> capNtfnBadge_CL ec && mask 64 = capNtfnBadge_CL ec"
unfolding cap_lift_def
by (fastforce simp: Let_def mask_def word_bw_assocs split: if_split_asm)
lemma cap_lift_capEPBadge_mask_eq:
"cap_lift cap = Some (Cap_endpoint_cap ec)
\<Longrightarrow> capEPBadge_CL ec && mask 64 = capEPBadge_CL ec"
unfolding cap_lift_def
by (fastforce simp: Let_def mask_def word_bw_assocs split: if_split_asm)
lemma Arch_isCapRevocable_spec:
"\<forall>s. \<Gamma>\<turnstile> {\<sigma>. s = \<sigma> \<and> True}
Call Arch_isCapRevocable_'proc
{t. \<forall>c c'. ccap_relation c (derivedCap_' s) \<and> ccap_relation c' (srcCap_' s)
\<longrightarrow> ret__unsigned_long_' t = from_bool (Arch.isCapRevocable c c')}"
apply vcg
by (auto simp: false_def from_bool_def X64_H.isCapRevocable_def
cap_get_tag_isCap_unfolded_H_cap cap_tag_defs isCap_simps
cap_get_tag_isCap[unfolded cap_io_port_control_cap_def, simplified]
split: capability.splits arch_capability.splits bool.splits)
lemmas isCapRevocable_simps[simp] = Retype_H.isCapRevocable_def[split_simps capability.split]
context begin (* revokable_ccorres *)
private method revokable'_hammer = solves \<open>(
simp add: cap_get_tag_isCap isCap_simps ccorres_cond_iffs from_bool_def true_def false_def,
rule ccorres_guard_imp,
rule ccorres_return_C; clarsimp)\<close>
lemma revokable_ccorres:
"ccorres (\<lambda>a c. from_bool a = c) ret__unsigned_long_'
(\<lambda>_. capMasterCap cap = capMasterCap parent \<or> is_simple_cap' cap)
(UNIV \<inter> {s. ccap_relation cap (derivedCap_' s)} \<inter> {s. ccap_relation parent (srcCap_' s)}) hs
(return (isCapRevocable cap parent))
(Call isCapRevocable_'proc)"
apply (rule ccorres_gen_asm[where G=\<top>, simplified])
apply (cinit' lift: derivedCap_' srcCap_')
\<comment> \<open>Clear up Arch cap case\<close>
apply csymbr
apply (clarsimp simp: cap_get_tag_isCap simp del: Collect_const)
apply (rule ccorres_Cond_rhs_Seq)
apply (rule ccorres_rhs_assoc)
apply (clarsimp simp: isCap_simps)
apply csymbr
apply (drule spec, drule spec, drule mp, fastforce)
apply ccorres_rewrite
apply (drule sym, simp only:)
apply (rule ccorres_return_C, clarsimp+)
apply csymbr
apply (rule_tac P'=UNIV and P=\<top> in ccorres_inst)
apply (cases cap)
\<comment> \<open>Uninteresting caps\<close>
apply revokable'_hammer+
\<comment> \<open>NotificationCap\<close>
apply (simp add: cap_get_tag_isCap isCap_simps ccorres_cond_iffs from_bool_def true_def false_def)
apply (rule ccorres_guard_imp, (rule ccorres_rhs_assoc)+, csymbr, csymbr)
apply (rule ccorres_return_C, clarsimp+)
apply (frule_tac cap'1=srcCap in cap_get_tag_NotificationCap[THEN iffD1])
apply (clarsimp simp: cap_get_tag_isCap isCap_simps is_simple_cap'_def)
apply (frule_tac cap'1=derivedCap in cap_get_tag_NotificationCap[THEN iffD1])
apply (clarsimp simp: cap_get_tag_isCap isCap_simps)
apply (fastforce simp: cap_get_tag_isCap isCap_simps)
\<comment> \<open>IRQHandlerCap\<close>
apply (simp add: cap_get_tag_isCap isCap_simps ccorres_cond_iffs from_bool_def true_def false_def)
apply (rule ccorres_guard_imp, csymbr)
apply (rule ccorres_return_C, clarsimp+)
apply (fastforce simp: cap_get_tag_isCap isCap_simps)
\<comment> \<open>EndpointCap\<close>
apply (simp add: cap_get_tag_isCap isCap_simps ccorres_cond_iffs from_bool_def true_def false_def)
apply (rule ccorres_guard_imp, (rule ccorres_rhs_assoc)+, csymbr, csymbr)
apply (rule ccorres_return_C, clarsimp+)
apply (frule_tac cap'1=srcCap in cap_get_tag_EndpointCap[THEN iffD1])
apply (clarsimp simp: cap_get_tag_isCap isCap_simps is_simple_cap'_def)
apply (frule_tac cap'1=derivedCap in cap_get_tag_EndpointCap[THEN iffD1])
apply (clarsimp simp: cap_get_tag_isCap isCap_simps)
apply (fastforce simp: cap_get_tag_isCap isCap_simps)
\<comment> \<open>Other Caps\<close>
by (revokable'_hammer | fastforce simp: isCap_simps)+
end (* revokable_ccorres *)
lemma cteInsert_ccorres_mdb_helper:
"\<lbrakk>cmdbnode_relation rva srcMDB; from_bool rvc = (newCapIsRevocable :: machine_word); srcSlot = Ptr src\<rbrakk>
\<Longrightarrow> ccorres cmdbnode_relation newMDB_' (K (is_aligned src 3))
UNIV hs
(return
(mdbFirstBadged_update (\<lambda>_. rvc)
(mdbRevocable_update (\<lambda>_. rvc)
(mdbPrev_update (\<lambda>_. src) rva))))
(\<acute>newMDB :== CALL mdb_node_set_mdbPrev(srcMDB,
ptr_val srcSlot);;
\<acute>newMDB :== CALL mdb_node_set_mdbRevocable(\<acute>newMDB,
newCapIsRevocable);;
\<acute>newMDB :== CALL mdb_node_set_mdbFirstBadged(\<acute>newMDB,
newCapIsRevocable))"
apply (rule ccorres_from_vcg)
apply (rule allI)
apply (rule conseqPre)
apply vcg
apply (clarsimp simp: return_def cmdbnode_relation_def mask_def)
done
lemma ccorres_updateMDB_set_mdbNext [corres]:
"src=src' \<Longrightarrow>
ccorres dc xfdc ((\<lambda>_. src \<noteq> 0 \<and> is_aligned dest cteSizeBits \<and> canonical_address dest))
({s. mdb_node_ptr_' s = Ptr &((Ptr src' :: cte_C ptr)\<rightarrow>[''cteMDBNode_C''])} \<inter>
{s. v64_' s = dest}) []
(updateMDB src (mdbNext_update (\<lambda>_. dest)))
(Call mdb_node_ptr_set_mdbNext_'proc)"
unfolding updateMDB_def
apply (hypsubst)
apply (rule ccorres_gen_asm [where G = \<top>, simplified])
apply (simp only: Let_def)
apply simp
apply (rule ccorres_guard_imp2)
apply (rule ccorres_pre_getCTE
[where P = "\<lambda>cte s. ctes_of s src' = Some cte"
and P'= "\<lambda>_. (\<lbrace>\<acute>mdb_node_ptr = Ptr &((Ptr src' :: cte_C ptr)\<rightarrow>[''cteMDBNode_C''])\<rbrace>
\<inter> \<lbrace>\<acute>v64 = dest\<rbrace>)"])
apply (rule ccorres_from_spec_modifies_heap)
apply (rule mdb_node_ptr_set_mdbNext_spec)
apply (rule mdb_node_ptr_set_mdbNext_modifies)
apply simp
apply clarsimp
apply (rule rf_sr_cte_at_valid)
apply simp
apply (erule ctes_of_cte_at)
apply assumption
apply clarsimp
apply (frule (1) rf_sr_ctes_of_clift)
apply (clarsimp simp: typ_heap_simps)
apply (rule fst_setCTE [OF ctes_of_cte_at], assumption)
apply (erule bexI [rotated])
apply (clarsimp simp: rf_sr_def cstate_relation_def
Let_def cpspace_relation_def cte_wp_at_ctes_of heap_to_user_data_def
cvariable_array_map_const_add_map_option[where f="tcb_no_ctes_proj"]
typ_heap_simps')
apply (rule conjI)
apply (erule (2) cspace_cte_relation_upd_mdbI)
apply (simp add: cmdbnode_relation_def)
apply (intro arg_cong[where f="\<lambda>f. mdbNext_update f mdb" for mdb] ext word_eqI)
apply (simp add: sign_extend_bitwise_if' neg_mask_test_bit word_size)
apply (match premises in C: "canonical_address _" and A: "is_aligned _ _" (multi) \<Rightarrow>
\<open>match premises in H[thin]: _ (multi) \<Rightarrow> \<open>insert C A\<close>\<close>)
apply (drule is_aligned_weaken[where y=2], simp add: objBits_defs)
apply (case_tac "n < 2"; case_tac "n \<le> 47";
clarsimp simp: linorder_not_less linorder_not_le is_aligned_nth[THEN iffD1])
apply (fastforce simp: word_size dest: canonical_address_high_bits)
apply (erule_tac t = s'a in ssubst)
apply simp
apply (rule conjI)
apply (erule (1) setCTE_tcb_case)
by (auto simp: carch_state_relation_def cmachine_state_relation_def
global_ioport_bitmap_heap_update_tag_disj_simps
fpu_null_state_heap_update_tag_disj_simps)
lemma ccorres_updateMDB_set_mdbPrev [corres]:
"src=src' \<Longrightarrow>
ccorres dc xfdc (\<lambda>_. src \<noteq> 0 \<and> is_aligned dest cteSizeBits)
({s. mdb_node_ptr_' s = Ptr &((Ptr src' :: cte_C ptr)\<rightarrow>[''cteMDBNode_C''])} \<inter>
{s. v64_' s = dest}) []
(updateMDB src (mdbPrev_update (\<lambda>_. dest)))
(Call mdb_node_ptr_set_mdbPrev_'proc)"
unfolding updateMDB_def
apply (hypsubst)
apply (rule ccorres_gen_asm [where G = \<top>, simplified])
apply (simp only: Let_def)
apply simp
apply (rule ccorres_guard_imp2)
apply (rule ccorres_pre_getCTE
[where P = "\<lambda>cte s. ctes_of s src' = Some cte"
and P' = "\<lambda>_. (\<lbrace>\<acute>mdb_node_ptr = Ptr &((Ptr src' :: cte_C ptr)\<rightarrow>[''cteMDBNode_C''])\<rbrace>
\<inter> \<lbrace>\<acute>v64 = dest\<rbrace>)"])
apply (rule ccorres_from_spec_modifies_heap)
apply (rule mdb_node_ptr_set_mdbPrev_spec)
apply (rule mdb_node_ptr_set_mdbPrev_modifies)
apply simp
apply clarsimp
apply (rule rf_sr_cte_at_valid)
apply simp
apply (erule ctes_of_cte_at)
apply assumption
apply (clarsimp simp: cte_wp_at_ctes_of)
apply (frule (1) rf_sr_ctes_of_clift)
apply (clarsimp simp: typ_heap_simps)
apply (rule fst_setCTE [OF ctes_of_cte_at], assumption)
apply (erule bexI[rotated])
apply (clarsimp simp: rf_sr_def cstate_relation_def
Let_def cpspace_relation_def cte_wp_at_ctes_of heap_to_user_data_def
cvariable_array_map_const_add_map_option[where f="tcb_no_ctes_proj"]
typ_heap_simps')
apply (rule conjI)
apply (erule (2) cspace_cte_relation_upd_mdbI)
apply (simp add: cmdbnode_relation_def mask_def)
apply (erule_tac t = s'a in ssubst)
apply (simp add: carch_state_relation_def cmachine_state_relation_def
fpu_null_state_heap_update_tag_disj_simps
global_ioport_bitmap_heap_update_tag_disj_simps)
apply (erule (1) setCTE_tcb_case)
by clarsimp
lemma ccorres_updateMDB_skip:
"ccorres dc xfdc (\<top> and (\<lambda>_. n = 0)) UNIV hs (updateMDB n f) SKIP"
unfolding updateMDB_def
apply (rule ccorres_gen_asm)
apply simp
apply (rule ccorres_return)
apply simp
apply vcg
done
definition
"is_simple_cap_tag (tag :: machine_word) \<equiv>
tag \<noteq> scast cap_null_cap \<and> tag \<noteq> scast cap_irq_control_cap
\<and> tag \<noteq> scast cap_untyped_cap \<and> tag \<noteq> scast cap_reply_cap
\<and> tag \<noteq> scast cap_endpoint_cap \<and> tag \<noteq> scast cap_notification_cap
\<and> tag \<noteq> scast cap_thread_cap \<and> tag \<noteq> scast cap_cnode_cap
\<and> tag \<noteq> scast cap_zombie_cap \<and> tag \<noteq> scast cap_io_port_control_cap
\<and> tag \<noteq> scast cap_frame_cap"
(* Useful:
apply (tactic {* let val _ = reset CtacImpl.trace_ceqv; val _ = reset CtacImpl.trace_ctac in all_tac end; *})
*)
declare word_neq_0_conv [simp del]
schematic_goal ccap_relation_tag_Master:
"\<And>ccap. \<lbrakk> ccap_relation cap ccap \<rbrakk>
\<Longrightarrow> cap_get_tag ccap =
case_capability ?a ?b ?c ?d ?e ?f ?g
(case_arch_capability ?aa ?ab ?ac
?ad ?ae ?af ?ag ?ah ?ai) ?h ?i ?j ?k
(capMasterCap cap)"
by (fastforce simp: ccap_relation_def map_option_Some_eq2
Let_def cap_lift_def cap_to_H_def
split: if_split_asm)
lemma ccap_relation_is_derived_tag_equal:
"\<lbrakk> is_derived' cs p cap cap'; ccap_relation cap ccap; ccap_relation cap' ccap' \<rbrakk>
\<Longrightarrow> cap_get_tag ccap' = cap_get_tag ccap"
unfolding badge_derived'_def is_derived'_def
by (clarsimp simp: ccap_relation_tag_Master)
lemma ccap_relation_Master_tags_eq:
"\<lbrakk> capMasterCap cap = capMasterCap cap'; ccap_relation cap ccap; ccap_relation cap' ccap' \<rbrakk>
\<Longrightarrow> cap_get_tag ccap' = cap_get_tag ccap"
by (clarsimp simp: ccap_relation_tag_Master)
lemma is_simple_cap_get_tag_relation:
"ccap_relation cap ccap
\<Longrightarrow> is_simple_cap_tag (cap_get_tag ccap) = is_simple_cap' cap"
apply (simp add: is_simple_cap_tag_def is_simple_cap'_def
cap_get_tag_isCap)
apply (auto simp: isCap_simps)
done
lemma setUntypedCapAsFull_cte_at_wp [wp]:
"\<lbrace> cte_at' x \<rbrace> setUntypedCapAsFull rvb cap src \<lbrace> \<lambda>_. cte_at' x \<rbrace>"
apply (clarsimp simp: setUntypedCapAsFull_def)
apply wp
done
lemma valid_cap_untyped_inv:
"valid_cap' (UntypedCap d r n f) s \<Longrightarrow>
n \<ge> minUntypedSizeBits \<and> is_aligned (of_nat f :: machine_word) minUntypedSizeBits
\<and> n \<le> maxUntypedSizeBits \<and> n < word_bits"
apply (clarsimp simp:valid_cap'_def capAligned_def)
done
lemma update_freeIndex':
assumes i'_align: "is_aligned (of_nat i' :: machine_word) minUntypedSizeBits"
assumes sz_bound: "sz \<le> maxUntypedSizeBits"
assumes i'_bound: "i'\<le> 2^sz"
shows "ccorres dc xfdc
(cte_wp_at' (\<lambda>cte. \<exists>i. cteCap cte = capability.UntypedCap d p sz i) srcSlot)
(UNIV \<inter> \<lbrace>\<acute>cap_ptr = cap_Ptr &(cte_Ptr srcSlot\<rightarrow>[''cap_C''])\<rbrace>
\<inter> \<lbrace>\<acute>v64 = of_nat i' >> minUntypedSizeBits\<rbrace>) []
(updateCap srcSlot (capability.UntypedCap d p sz i'))
(Call cap_untyped_cap_ptr_set_capFreeIndex_'proc)"
proof -
note i'_bound_concrete
= order_trans[OF i'_bound power_increasing[OF sz_bound], simplified untypedBits_defs, simplified]
have i'_bound_word: "(of_nat i' :: machine_word) \<le> 2 ^ maxUntypedSizeBits"
using order_trans[OF i'_bound power_increasing[OF sz_bound], simplified]
by (simp add: word_of_nat_le untypedBits_defs)
show ?thesis
apply (cinit lift: cap_ptr_' v64_')
apply (rule ccorres_pre_getCTE)
apply (rule_tac P="\<lambda>s. ctes_of s srcSlot = Some rv \<and> (\<exists>i. cteCap rv = UntypedCap d p sz i)"
in ccorres_from_vcg[where P' = UNIV])
apply (rule allI)
apply (rule conseqPre)
apply vcg
apply (clarsimp simp: guard_simps)
apply (intro conjI)
apply (frule (1) rf_sr_ctes_of_clift)
apply (clarsimp simp: typ_heap_simps)
apply (frule (1) rf_sr_ctes_of_clift)
apply (clarsimp simp: split_def)
apply (simp add: hrs_htd_def typ_heap_simps)
apply (rule fst_setCTE[OF ctes_of_cte_at], assumption)
apply (erule bexI[rotated], clarsimp)
apply (frule (1) rf_sr_ctes_of_clift)
apply (clarsimp simp: rf_sr_def cstate_relation_def Let_def
cvariable_array_map_const_add_map_option[where f="tcb_no_ctes_proj"])
apply (simp add: cpspace_relation_def)
apply (clarsimp simp: typ_heap_simps')
apply (rule conjI)
apply (erule (2) cpspace_cte_relation_upd_capI)
apply (simp only: cte_lift_def split: option.splits; simp)
apply (simp add: cap_to_H_def Let_def split: cap_CL.splits if_split_asm)
apply (case_tac y)
apply (simp add: cap_lift_def Let_def split: if_split_asm)
apply (case_tac cte', simp)
apply (clarsimp simp: ccap_relation_def cap_lift_def cap_get_tag_def cap_to_H_def)
apply (thin_tac _)+
apply (simp add: mask_def to_bool_and_1 nth_shiftr word_ao_dist and.assoc)
apply (rule inj_onD[OF word_unat.Abs_inj_on[where 'a=machine_word_len]], simp)
apply (cut_tac i'_align i'_bound_word)
apply (simp add: is_aligned_mask)
apply word_bitwise
subgoal by (simp add: word_size untypedBits_defs mask_def)
apply (cut_tac i'_bound_concrete)
subgoal by (simp add: unats_def)
subgoal by (simp add: word_unat.Rep[where 'a=machine_word_len, simplified])
apply (erule_tac t = s' in ssubst)
apply clarsimp
apply (rule conjI)
subgoal by (erule (1) setCTE_tcb_case)
apply (clarsimp simp: carch_state_relation_def cmachine_state_relation_def
fpu_null_state_heap_update_tag_disj_simps
global_ioport_bitmap_heap_update_tag_disj_simps
packed_heap_update_collapse_hrs)
by (clarsimp simp: cte_wp_at_ctes_of)
qed
lemma update_freeIndex:
"ccorres dc xfdc
(valid_objs' and cte_wp_at' (\<lambda>cte. \<exists>i. cteCap cte = UntypedCap d p sz i) srcSlot
and (\<lambda>_. is_aligned (of_nat i' :: machine_word) minUntypedSizeBits \<and> i' \<le> 2 ^ sz))
(UNIV \<inter> \<lbrace>\<acute>cap_ptr = cap_Ptr &(cte_Ptr srcSlot\<rightarrow>[''cap_C''])\<rbrace>
\<inter> \<lbrace>\<acute>v64 = of_nat i' >> minUntypedSizeBits\<rbrace>) []
(updateCap srcSlot (UntypedCap d p sz i'))
(Call cap_untyped_cap_ptr_set_capFreeIndex_'proc)"
apply (rule ccorres_assume_pre, rule ccorres_guard_imp)
apply (rule update_freeIndex'; clarsimp simp: cte_wp_at_ctes_of)
apply (case_tac cte; clarsimp dest!: ctes_of_valid_cap' simp: valid_cap'_def)
by auto
(* FIXME: move *)
lemma ccorres_cases:
assumes P: " P \<Longrightarrow> ccorres r xf G G' hs a b"
assumes notP: "\<not>P \<Longrightarrow> ccorres r xf H H' hs a b"
shows "ccorres r xf (\<lambda>s. (P \<longrightarrow> G s) \<and> (\<not>P \<longrightarrow> H s))
({s. P \<longrightarrow> s \<in> G'} \<inter> {s. \<not>P \<longrightarrow> s \<in> H'})
hs a b"
apply (cases P, auto simp: P notP)
done
lemma capBlockSize_CL_maxSize:
" \<lbrakk> cap_get_tag c = scast cap_untyped_cap \<rbrakk> \<Longrightarrow> capBlockSize_CL (cap_untyped_cap_lift c) < 0x40"
apply (clarsimp simp: cap_untyped_cap_lift_def)
apply (clarsimp simp: cap_lift_def)
apply (clarsimp simp: cap_untyped_cap_def cap_null_cap_def)
apply (rule word_and_less')
apply (simp add: mask_def)
done
lemma setUntypedCapAsFull_ccorres [corres]:
notes if_split [split del]
notes Collect_const [simp del]
notes Collect_True [simp] Collect_False [simp]
shows
"ccorres dc xfdc
((cte_wp_at' (\<lambda>c. (cteCap c) = srcCap) srcSlot) and valid_mdb' and pspace_aligned' and valid_objs'
and (K (isUntypedCap newCap \<longrightarrow> (minUntypedSizeBits \<le> capBlockSize newCap)))
and (K (isUntypedCap srcCap \<longrightarrow> (minUntypedSizeBits \<le> capBlockSize srcCap))))
(UNIV \<inter> {s. ccap_relation srcCap (srcCap_' s)}
\<inter> {s. ccap_relation newCap (newCap_' s)}
\<inter> {s. srcSlot_' s = Ptr srcSlot})
[]
(setUntypedCapAsFull srcCap newCap srcSlot)
(Call setUntypedCapAsFull_'proc)"
apply (cinit lift: srcCap_' newCap_' srcSlot_')
apply (rule ccorres_if_lhs)
apply (clarsimp simp: isCap_simps)
apply csymbr
apply csymbr
apply (simp add: if_then_0_else_1 if_then_1_else_0 cap_get_tag_isCap_unfolded_H_cap)
apply (rule ccorres_rhs_assoc)+
apply csymbr
apply csymbr
apply (simp add: cap_get_tag_isCap_unfolded_H_cap ccorres_cond_univ_iff)
apply (rule ccorres_rhs_assoc)+
apply csymbr
apply csymbr
apply csymbr
apply (frule cap_get_tag_to_H(9))
apply (simp add: cap_get_tag_isCap_unfolded_H_cap)
apply (rotate_tac 1)
apply (frule cap_get_tag_to_H(9))
apply (simp add: cap_get_tag_isCap_unfolded_H_cap)
apply simp
apply (rule ccorres_rhs_assoc)+
apply csymbr
apply csymbr
apply csymbr
apply (simp add: ccorres_cond_univ_iff)
apply csymbr+
apply (rule ccorres_move_c_guard_cte)
apply (rule ccorres_Guard)
apply (rule ccorres_call)
apply (rule update_freeIndex [unfolded dc_def])
apply simp
apply simp
apply simp
apply clarsimp
apply (csymbr)
apply (csymbr)
apply (simp add: cap_get_tag_isCap)
apply (rule ccorres_Cond_rhs_Seq)
apply (rule ccorres_rhs_assoc)+
apply csymbr
apply csymbr
apply (simp add: cap_get_tag_isCap)
apply (rule ccorres_Cond_rhs)
apply (rule ccorres_rhs_assoc)+
apply csymbr
apply csymbr
apply csymbr
apply (rule ccorres_cases [where P="capPtr srcCap = capPtr newCap"])
apply (clarsimp simp: cap_get_tag_isCap[symmetric] cap_get_tag_UntypedCap split: if_split_asm)
apply (rule ccorres_rhs_assoc)+
apply csymbr
apply csymbr
apply csymbr
apply (clarsimp simp: cap_get_tag_to_H cap_get_tag_UntypedCap split: if_split_asm)
apply (rule ccorres_cond_false)
apply (rule ccorres_return_Skip [unfolded dc_def])
apply (clarsimp simp: cap_get_tag_isCap[symmetric] cap_get_tag_UntypedCap split: if_split_asm)
apply (rule ccorres_cond_false)
apply (rule ccorres_return_Skip [unfolded dc_def])
apply (rule ccorres_return_Skip [unfolded dc_def])
apply clarsimp
apply (rule ccorres_cond_false)
apply (rule ccorres_return_Skip [unfolded dc_def])
apply (clarsimp simp: cap_get_tag_isCap[symmetric] cap_get_tag_UntypedCap)
apply (frule(1) cte_wp_at_valid_objs_valid_cap')
apply (clarsimp simp: untypedBits_defs)
apply (intro conjI impI allI)
apply (erule cte_wp_at_weakenE')
apply (clarsimp simp: cap_get_tag_isCap[symmetric] cap_get_tag_UntypedCap split: if_split_asm)
apply clarsimp
apply (drule valid_cap_untyped_inv,clarsimp simp:max_free_index_def)
apply (rule is_aligned_weaken)
apply (rule is_aligned_shiftl_self[unfolded shiftl_t2n,where p = 1,simplified])
apply assumption
apply (clarsimp simp: max_free_index_def shiftL_nat valid_cap'_def capAligned_def)
apply (simp add:power_minus_is_div unat_sub word_le_nat_alt t2p_shiftr)
apply clarsimp
apply (erule cte_wp_at_weakenE', simp)
apply clarsimp
apply (drule valid_cap_untyped_inv)
apply (clarsimp simp: max_free_index_def t2p_shiftr unat_sub word_le_nat_alt word_bits_def)
apply (rule word_less_imp_diff_less)
apply (subst (asm) eq_commute, fastforce simp: unat_sub word_le_nat_alt)
apply (rule capBlockSize_CL_maxSize)
apply (clarsimp simp: cap_get_tag_UntypedCap)
apply (clarsimp simp: cap_get_tag_isCap_unfolded_H_cap)
done
lemma ccte_lift:
"\<lbrakk>(s, s') \<in> rf_sr; cslift s' (cte_Ptr p) = Some cte';
cte_lift cte' = Some y; c_valid_cte cte'\<rbrakk>
\<Longrightarrow> ctes_of s p = Some (cte_to_H (the (cte_lift cte')))"
apply (clarsimp simp:rf_sr_def cstate_relation_def Let_def cpspace_relation_def)
apply (drule(1) cmap_relation_cs_atD)
apply simp
apply (clarsimp simp:ccte_relation_def)
done
lemma cmdb_node_relation_mdbNext:
"cmdbnode_relation n n'
\<Longrightarrow> mdbNext_CL (mdb_node_lift n') = mdbNext n"
by (simp add:cmdbnode_relation_def)
lemma cslift_ptr_safe:
"cslift x ptr = Some a
\<Longrightarrow> ptr_safe ptr (hrs_htd (t_hrs_' (globals x)))"
apply (rule_tac h = "fst (t_hrs_' (globals x))"
in lift_t_ptr_safe[where g = c_guard])
apply (fastforce simp add:typ_heap_simps hrs_htd_def)
done
lemma ccorres_move_ptr_safe:
"ccorres_underlying rf_sr \<Gamma> r xf arrel axf A C' hs a c \<Longrightarrow>
ccorres_underlying rf_sr \<Gamma> r xf arrel axf
(A and K (dest = cte_Ptr (ptr_val dest)) and cte_wp_at' (\<lambda>_. True) (ptr_val dest))
(C' \<inter> \<lbrace>True\<rbrace>) hs a (Guard MemorySafety \<lbrace>ptr_safe (dest) (hrs_htd \<acute>t_hrs) \<rbrace> c)"
apply (rule ccorres_guard_imp2)
apply (rule ccorres_Guard)
apply simp
apply (clarsimp simp:cte_wp_at_ctes_of)
apply (drule(1) rf_sr_ctes_of_clift)
apply (case_tac dest)
apply (clarsimp simp:ptr_coerce_def)
apply (erule cslift_ptr_safe)
done
lemma ccorres_move_ptr_safe_Seq:
"ccorres_underlying rf_sr \<Gamma> r xf arrel axf A C' hs a (c;;d) \<Longrightarrow>
ccorres_underlying rf_sr \<Gamma> r xf arrel axf
(A and cte_wp_at' (\<lambda>_. True) (ptr_val dest) and K (dest = cte_Ptr (ptr_val dest)))
(C' \<inter> \<lbrace>True\<rbrace>) hs a
(Guard MemorySafety \<lbrace>ptr_safe (dest) (hrs_htd \<acute>t_hrs) \<rbrace> c;;d)"
apply (rule ccorres_guard_imp2)
apply (rule ccorres_Guard_Seq)
apply simp
apply (clarsimp simp:cte_wp_at_ctes_of)
apply (drule(1) rf_sr_ctes_of_clift)
apply clarsimp
apply (erule cslift_ptr_safe)
done
lemmas ccorres_move_guard_ptr_safe = ccorres_move_ptr_safe_Seq ccorres_move_ptr_safe
lemma cteInsert_ccorres:
"ccorres dc xfdc
(cte_wp_at' (\<lambda>scte. capMasterCap (cteCap scte) = capMasterCap cap \<or> is_simple_cap' cap) src
and valid_mdb' and valid_objs' and pspace_aligned' and pspace_canonical'
and (valid_cap' cap))
(UNIV \<inter> {s. destSlot_' s = Ptr dest}
\<inter> {s. srcSlot_' s = Ptr src}
\<inter> {s. ccap_relation cap (newCap_' s)}) []
(cteInsert cap src dest)
(Call cteInsert_'proc)"
supply ctes_of_aligned_bits[simp]
apply (cinit (no_ignore_call) lift: destSlot_' srcSlot_' newCap_'
simp del: return_bind simp add: Collect_const)
apply (rule ccorres_move_c_guard_cte)
apply (ctac pre: ccorres_pre_getCTE)
apply (rule ccorres_move_c_guard_cte)
apply (ctac pre: ccorres_pre_getCTE)
apply (ctac (no_vcg) add: revokable_ccorres)
apply (ctac (c_lines 3) add: cteInsert_ccorres_mdb_helper)
apply (simp del: Collect_const)
apply (rule ccorres_pre_getCTE ccorres_assert)+
apply (ctac add: setUntypedCapAsFull_ccorres)
apply (rule ccorres_move_c_guard_cte)
apply (ctac)
apply (rule ccorres_move_c_guard_cte)
apply ctac
apply (rule ccorres_move_c_guard_cte)
apply (ctac(no_vcg))
apply csymbr
apply (erule_tac t = ret__unsigned_longlong in ssubst)
apply (rule ccorres_cond_both [where R = \<top>, simplified])
apply (erule mdbNext_not_zero_eq)
apply csymbr
apply simp
apply (rule ccorres_move_c_guard_cte)
apply (simp add:dc_def[symmetric])
apply (ctac ccorres:ccorres_updateMDB_set_mdbPrev)
apply (simp add:dc_def[symmetric])
apply (ctac ccorres: ccorres_updateMDB_skip)
apply (wp static_imp_wp)+
apply (clarsimp simp: Collect_const_mem dc_def split del: if_split)
apply vcg
apply (wp static_imp_wp)
apply (clarsimp simp: Collect_const_mem dc_def split del: if_split)
apply vcg
apply (clarsimp simp:cmdb_node_relation_mdbNext)
apply (wp setUntypedCapAsFull_cte_at_wp static_imp_wp)
apply (clarsimp simp: Collect_const_mem dc_def split del: if_split)
apply (vcg exspec=setUntypedCapAsFull_modifies)
apply wp
apply vcg
apply wp
apply wp
apply vcg
apply wp
apply vcg
apply (simp add: Collect_const_mem split del: if_split) \<comment> \<open>Takes a while\<close>
apply (rule conjI)
apply (clarsimp simp: conj_comms cte_wp_at_ctes_of)
apply (intro conjI)
apply clarsimp
apply simp
apply simp
apply (clarsimp simp: ctes_of_canonical objBits_defs cte_level_bits_def)
apply (rule conjI)
apply (clarsimp simp: isUntypedCap_def split: capability.split_asm)
apply (frule valid_cap_untyped_inv)
apply clarsimp
apply (rule conjI)
apply (case_tac ctea)
apply (clarsimp simp: isUntypedCap_def split: capability.splits)
apply (frule valid_cap_untyped_inv[OF ctes_of_valid_cap'])
apply fastforce
apply clarsimp+
apply (drule valid_dlist_nextD)
apply (simp add:valid_mdb'_def valid_mdb_ctes_def)
apply simp
apply clarsimp
apply (clarsimp simp: map_comp_Some_iff cte_wp_at_ctes_of
split del: if_split)
apply (clarsimp simp: typ_heap_simps c_guard_clift split_def)
apply (clarsimp simp: is_simple_cap_get_tag_relation ccte_relation_ccap_relation cmdb_node_relation_mdbNext[symmetric])
done
(****************************************************************************)
(* *)
(* Lemmas dealing with updateMDB on Haskell side and IF-THEN-ELSE on C side *)
(* *)
(****************************************************************************)
lemma updateMDB_mdbNext_set_mdbPrev:
"\<lbrakk> slotc = Ptr slota; cmdbnode_relation mdba mdbc\<rbrakk> \<Longrightarrow>
ccorres dc xfdc
(\<lambda>s. is_aligned slota cteSizeBits)
UNIV hs
(updateMDB (mdbNext mdba) (mdbPrev_update (\<lambda>_. slota)))
(IF mdbNext_CL (mdb_node_lift mdbc) \<noteq> 0
THEN Guard C_Guard \<lbrace>hrs_htd \<acute>t_hrs \<Turnstile>\<^sub>t (Ptr (mdbNext_CL (mdb_node_lift mdbc)) :: cte_C ptr)\<rbrace>
(call (\<lambda>ta. ta(| mdb_node_ptr_' := Ptr &(Ptr (mdbNext_CL (mdb_node_lift mdbc)):: cte_C ptr
\<rightarrow>[''cteMDBNode_C'']),
v64_' := ptr_val slotc |))
mdb_node_ptr_set_mdbPrev_'proc
(\<lambda>s t. s\<lparr> globals := globals t \<rparr>) (\<lambda>ta s'. Basic (\<lambda>a. a)))
FI)"
apply (rule ccorres_guard_imp2)
apply (rule ccorres_cond_both[where R=\<top>, simplified])
apply (erule mdbNext_not_zero_eq)
apply (rule ccorres_updateMDB_cte_at)
apply (ctac add: ccorres_updateMDB_set_mdbPrev)
apply (ctac ccorres: ccorres_updateMDB_skip)
apply (clarsimp simp: cmdbnode_relation_def cte_wp_at_ctes_of)
done
lemma updateMDB_mdbPrev_set_mdbNext:
"\<lbrakk> slotc = Ptr slota; cmdbnode_relation mdba mdbc\<rbrakk> \<Longrightarrow>
ccorres dc xfdc
(\<lambda>s. is_aligned slota cteSizeBits \<and> canonical_address slota)
UNIV hs
(updateMDB (mdbPrev mdba) (mdbNext_update (\<lambda>_. slota)))
(IF mdbPrev_CL (mdb_node_lift mdbc) \<noteq> 0
THEN Guard C_Guard \<lbrace>hrs_htd \<acute>t_hrs \<Turnstile>\<^sub>t (Ptr (mdbPrev_CL (mdb_node_lift mdbc)):: cte_C ptr)\<rbrace>
(call (\<lambda>ta. ta(| mdb_node_ptr_' := Ptr &(Ptr (mdbPrev_CL (mdb_node_lift mdbc)):: cte_C ptr
\<rightarrow>[''cteMDBNode_C'']),
v64_' := ptr_val slotc |))
mdb_node_ptr_set_mdbNext_'proc
(\<lambda>s t. s\<lparr> globals := globals t \<rparr>) (\<lambda>ta s'. Basic (\<lambda>a. a)))
FI)"
apply (rule ccorres_guard_imp2)
apply (rule ccorres_cond_both[where R=\<top>, simplified])
apply (erule mdbPrev_not_zero_eq)
apply (rule ccorres_updateMDB_cte_at)
apply (ctac add: ccorres_updateMDB_set_mdbNext)
apply (ctac ccorres: ccorres_updateMDB_skip)
apply (clarsimp simp: cte_wp_at_ctes_of cmdbnode_relation_def)
done
(************************************************************************)
(* *)
(* cteMove_ccorres ******************************************************)
(* *)
(************************************************************************)
(* FIXME: rename *)
lemma is_aligned_3_prev:
"\<lbrakk> valid_mdb' s; pspace_aligned' s; ctes_of s p = Some cte \<rbrakk>
\<Longrightarrow> is_aligned (mdbPrev (cteMDBNode cte)) cteSizeBits"
apply (cases "mdbPrev (cteMDBNode cte) = 0", simp)
apply (drule (2) valid_mdb_ctes_of_prev)
apply (clarsimp simp: cte_wp_at_ctes_of cteSizeBits_eq ctes_of_aligned_bits)
done
(* FIXME: rename *)
lemma is_aligned_3_next:
"\<lbrakk> valid_mdb' s; pspace_aligned' s; ctes_of s p = Some cte \<rbrakk>
\<Longrightarrow> is_aligned (mdbNext (cteMDBNode cte)) cteSizeBits"
apply (cases "mdbNext (cteMDBNode cte) = 0", simp)
apply (drule (2) valid_mdb_ctes_of_next)
apply (clarsimp simp: cte_wp_at_ctes_of cteSizeBits_eq ctes_of_aligned_bits)
done
lemma cteMove_ccorres:
"ccorres dc xfdc
(valid_mdb' and pspace_aligned' and pspace_canonical')
(UNIV \<inter> {s. destSlot_' s = Ptr dest}
\<inter> {s. srcSlot_' s = Ptr src}
\<inter> {s. ccap_relation cap (newCap_' s)}) []
(cteMove cap src dest)
(Call cteMove_'proc)"
apply (cinit (no_ignore_call) lift: destSlot_' srcSlot_' newCap_' simp del: return_bind)
apply (ctac pre: ccorres_pre_getCTE ccorres_assert)
apply (ctac+, csymbr+)+
apply (erule_tac t=ret__unsigned_longlong in ssubst)
apply (ctac add: updateMDB_mdbPrev_set_mdbNext)
apply csymbr
apply csymbr
apply (erule_tac t=ret__unsigned_longlong in ssubst)
apply (rule updateMDB_mdbNext_set_mdbPrev)
apply simp+
apply (wp, vcg)+
apply (rule conjI)
apply (clarsimp simp: cte_wp_at_ctes_of cteSizeBits_eq ctes_of_canonical ctes_of_aligned_bits)
apply assumption
apply (clarsimp simp: ccap_relation_NullCap_iff cmdbnode_relation_def
mdb_node_to_H_def nullMDBNode_def false_def)
done
(************************************************************************)
(* *)
(* lemmas used in cteSwap_ccorres ***************************************)
(* *)
(************************************************************************)
(*---------------------------------------------------------------------------------------*)
(* corres lemma for return of mdbnode but 'safer' than ccorres_return_cte_mdbnode ------ *)
(*---------------------------------------------------------------------------------------*)
lemma ccorres_return_cte_mdbnode_safer:
fixes ptr' :: "cstate \<Rightarrow> cte_C ptr"
assumes r1: "\<And>s s' g. (s, s') \<in> rf_sr \<Longrightarrow> (s, xfu g s') \<in> rf_sr"
and xf_xfu: "\<And>s g. xf (xfu g s) = g s"
shows "ccorres cmdbnode_relation xf
(\<lambda>s. \<exists> cte'. ctes_of s ptr = Some cte' \<and> cteMDBNode cte = cteMDBNode cte') {s. ptr_val (ptr' s) = ptr} hs
(return (cteMDBNode cte))
(Basic (\<lambda>s. xfu (\<lambda>_. h_val (hrs_mem (t_hrs_' (globals s)))
(Ptr &(ptr' s \<rightarrow>[''cteMDBNode_C'']))) s))"
apply (rule ccorres_from_vcg)
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp add: return_def)
apply rule
apply (erule r1)
apply (simp add: xf_xfu)
apply (drule (1) rf_sr_ctes_of_clift)
apply (clarsimp simp: typ_heap_simps)
done
(*-----------------------------------------------------------------------*)
(* lemmas about map and hrs_mem -----------------------------------------*)
(*-----------------------------------------------------------------------*)
declare modify_map_exists_cte[simp]
(*------------------------------------------------------------------------------*)
(* lemmas about pointer equality given valid_mdb (prev\<noteq>next, prev\<noteq>myself, etc) *)
(*------------------------------------------------------------------------------*)
lemma valid_mdb_Prev_neq_Next:
"\<lbrakk> valid_mdb' s; ctes_of s p = Some cte; mdbPrev (cteMDBNode cte) \<noteq> 0 \<rbrakk> \<Longrightarrow>
(mdbNext (cteMDBNode cte)) \<noteq> (mdbPrev (cteMDBNode cte))"
apply (simp add: valid_mdb'_def)
apply (simp add: valid_mdb_ctes_def)
apply (elim conjE)
apply (drule (1) mdb_chain_0_no_loops)
apply (simp add: valid_dlist_def)
apply (erule_tac x=p in allE)
apply (erule_tac x=cte in allE)
apply (simp add: Let_def)
apply clarsimp
apply (drule_tac s="mdbNext (cteMDBNode cte)" in sym)
apply simp
apply (simp add: no_loops_def)
apply (erule_tac x= "(mdbNext (cteMDBNode cte))" in allE)
apply (erule notE, rule trancl_trans)
apply (rule r_into_trancl)
apply (simp add: mdb_next_unfold)
apply (rule r_into_trancl)
apply (simp add: mdb_next_unfold)
done
lemma valid_mdb_Prev_neq_itself:
"\<lbrakk> valid_mdb' s; ctes_of s p = Some cte \<rbrakk> \<Longrightarrow>
(mdbPrev (cteMDBNode cte)) \<noteq> p"
apply (unfold valid_mdb'_def)
apply (simp add: CSpace_I.no_self_loop_prev)
done
lemma valid_mdb_Next_neq_itself:
"\<lbrakk> valid_mdb' s; ctes_of s p = Some cte \<rbrakk> \<Longrightarrow>
(mdbNext (cteMDBNode cte)) \<noteq> p"
apply (unfold valid_mdb'_def)
apply (simp add: CSpace_I.no_self_loop_next)
done
lemma valid_mdb_not_same_Next :
"\<lbrakk> valid_mdb' s; p\<noteq>p'; ctes_of s p = Some cte; ctes_of s p' = Some cte';
(mdbNext (cteMDBNode cte))\<noteq>0 \<or> (mdbNext (cteMDBNode cte'))\<noteq>0 \<rbrakk> \<Longrightarrow>
(mdbNext (cteMDBNode cte)) \<noteq> (mdbNext (cteMDBNode cte')) "
apply (clarsimp)
apply (case_tac cte, clarsimp)
apply (rename_tac capability mdbnode)
apply (case_tac cte', clarsimp)
apply (subgoal_tac "mdb_ptr (ctes_of s) p capability mdbnode")
apply (drule (2) mdb_ptr.p_nextD)
apply clarsimp
apply (unfold mdb_ptr_def vmdb_def mdb_ptr_axioms_def valid_mdb'_def, simp)
done
lemma valid_mdb_not_same_Prev :
"\<lbrakk> valid_mdb' s; p\<noteq>p'; ctes_of s p = Some cte; ctes_of s p' = Some cte';
(mdbPrev (cteMDBNode cte))\<noteq>0 \<or> (mdbPrev (cteMDBNode cte'))\<noteq>0 \<rbrakk> \<Longrightarrow>
(mdbPrev (cteMDBNode cte)) \<noteq> (mdbPrev (cteMDBNode cte')) "
apply (clarsimp)
apply (case_tac cte, clarsimp)
apply (rename_tac capability mdbnode)
apply (case_tac cte', clarsimp)
apply (subgoal_tac "mdb_ptr (ctes_of s) p capability mdbnode")
apply (drule (2) mdb_ptr.p_prevD)
apply clarsimp
apply (unfold mdb_ptr_def vmdb_def mdb_ptr_axioms_def valid_mdb'_def, simp)
done
(*---------------------------------------------------------------------------------*)
(* lemmas to simplify the big last goal on C side to avoid proving things twice ---*)
(*---------------------------------------------------------------------------------*)
lemma c_guard_and_h_t_valid_eq_h_t_valid:
"(POINTER \<noteq> 0 \<longrightarrow>
c_guard ((Ptr &(Ptr POINTER ::cte_C ptr \<rightarrow>[''cteMDBNode_C''])) ::mdb_node_C ptr) \<and>
s' \<Turnstile>\<^sub>c (Ptr (POINTER)::cte_C ptr)) =
(POINTER \<noteq> 0 \<longrightarrow>
s' \<Turnstile>\<^sub>c (Ptr (POINTER)::cte_C ptr))"
apply (rule iffI, clarsimp+)
apply (rule c_guard_field_lvalue)
apply (rule c_guard_h_t_valid, assumption)
apply (fastforce simp: typ_uinfo_t_def)+
done
lemma c_guard_and_h_t_valid_and_rest_eq_h_t_valid_and_rest:
"(POINTER \<noteq> 0 \<longrightarrow>
c_guard ((Ptr &(Ptr POINTER ::cte_C ptr \<rightarrow>[''cteMDBNode_C''])) ::mdb_node_C ptr) \<and>
s' \<Turnstile>\<^sub>c (Ptr (POINTER)::cte_C ptr) \<and> REST) =
(POINTER \<noteq> 0 \<longrightarrow>
s' \<Turnstile>\<^sub>c (Ptr (POINTER)::cte_C ptr) \<and> REST)"
apply (rule iffI, clarsimp+)
apply (rule c_guard_field_lvalue)
apply (rule c_guard_h_t_valid, assumption)
apply (fastforce simp: typ_uinfo_t_def)+
done
(************************************************************************)
(* *)
(* cteSwap_ccorres ******************************************************)
(* *)
(************************************************************************)
lemma cteSwap_ccorres:
"ccorres dc xfdc
(valid_mdb' and pspace_aligned' and pspace_canonical'
and (\<lambda>_. slot1 \<noteq> slot2))
(UNIV \<inter> {s. slot1_' s = Ptr slot1}
\<inter> {s. slot2_' s = Ptr slot2}
\<inter> {s. ccap_relation cap1 (cap1_' s)}
\<inter> {s. ccap_relation cap2 (cap2_' s)})
[]
(cteSwap cap1 slot1 cap2 slot2)
(Call cteSwap_'proc)"
supply ctes_of_aligned_bits[simp]
apply (cinit (no_ignore_call) lift: slot1_' slot2_' cap1_' cap2_' simp del: return_bind)
apply (ctac (no_vcg) pre: ccorres_pre_getCTE ccorres_move_guard_ptr_safe)
apply (rule ccorres_updateCap_cte_at)
apply (ctac (no_vcg) add: ccorres_return_cte_mdbnode_safer [where ptr=slot1])+
apply csymbr
apply csymbr
apply (erule_tac t=ret__unsigned_longlong in ssubst)
apply (ctac (no_vcg) add: updateMDB_mdbPrev_set_mdbNext)
apply csymbr
apply csymbr
apply (erule_tac t=ret__unsigned_longlong in ssubst)
apply (ctac (no_vcg) add: updateMDB_mdbNext_set_mdbPrev)
apply (rule ccorres_move_c_guard_cte)
apply (ctac (no_vcg) pre: ccorres_getCTE ccorres_move_guard_ptr_safe
add: ccorres_return_cte_mdbnode[where ptr=slot2]
ccorres_move_guard_ptr_safe)+
apply csymbr
apply csymbr
apply (erule_tac t=ret__unsigned_longlong in ssubst)
apply (ctac (no_vcg) add: updateMDB_mdbPrev_set_mdbNext)
apply csymbr
apply csymbr
apply (erule_tac t=ret__unsigned_longlong in ssubst)
apply (ctac (no_vcg) add: updateMDB_mdbNext_set_mdbPrev)
apply wp
apply simp
apply wp
apply simp
apply wp
apply simp
apply wp
apply simp
apply (clarsimp simp : cte_wp_at_ctes_of)
apply wp
apply simp
apply wp
apply simp
apply wp
apply simp
apply (clarsimp simp : cte_wp_at_ctes_of)
apply (wp updateCap_ctes_of_wp)
apply simp
apply (clarsimp simp : cte_wp_at_ctes_of)
apply (wp updateCap_ctes_of_wp)
apply simp
apply (clarsimp simp: cte_wp_at_ctes_of)
apply (apply_conjunct \<open>match conclusion in \<open>no_0 _\<close>
\<Rightarrow> \<open>simp add: valid_mdb'_def, erule (1) valid_mdb_ctesE\<close>\<close>)
apply (case_tac cte; simp add: modify_map_if ctes_of_canonical)
done
(* todo change in cteMove (\<lambda>s. ctes_of s src = Some scte) *)
(************************************************************************)
(* *)
(* lemmas used in emptySlot_ccorres *************************************)
(* *)
(************************************************************************)
declare if_split [split del]
(* rq CALL mdb_node_ptr_set_mdbNext_'proc \<dots>) is a printing bug
one should write CALL mdb_node_ptr_set_mdbNext
*)
lemma not_NullCap_eq_not_cap_null_cap:
" \<lbrakk>ccap_relation cap cap' ; (s, s') \<in> rf_sr \<rbrakk> \<Longrightarrow>
(cap \<noteq> NullCap) = (s' \<in> {_. (cap_get_tag cap' \<noteq> scast cap_null_cap)})"
apply (rule iffI)
apply (case_tac "cap_get_tag cap' \<noteq> scast cap_null_cap", clarsimp+)
apply (erule notE)
apply (simp add: cap_get_tag_NullCap)
apply (case_tac "cap_get_tag cap' \<noteq> scast cap_null_cap")
apply (rule notI)
apply (erule notE)
apply (simp add: cap_get_tag_NullCap)
apply clarsimp
done
lemma emptySlot_helper:
fixes mdbNode
defines "nextmdb \<equiv> Ptr &(Ptr ((mdbNext_CL (mdb_node_lift mdbNode)))::cte_C ptr\<rightarrow>[''cteMDBNode_C'']) :: mdb_node_C ptr"
defines "nextcte \<equiv> Ptr ((mdbNext_CL (mdb_node_lift mdbNode)))::cte_C ptr"
shows "\<lbrakk>cmdbnode_relation rva mdbNode\<rbrakk>
\<Longrightarrow> ccorres dc xfdc \<top> UNIV hs
(updateMDB (mdbNext rva)
(\<lambda>mdb. mdbFirstBadged_update (\<lambda>_. mdbFirstBadged mdb \<or> mdbFirstBadged rva) (mdbPrev_update (\<lambda>_. mdbPrev rva) mdb)))
(IF mdbNext_CL (mdb_node_lift mdbNode) \<noteq> 0 THEN
Guard C_Guard \<lbrace>hrs_htd \<acute>t_hrs \<Turnstile>\<^sub>t nextcte\<rbrace>
(CALL mdb_node_ptr_set_mdbPrev(nextmdb, ptr_val (Ptr (mdbPrev_CL (mdb_node_lift mdbNode)))))
FI;;
IF mdbNext_CL (mdb_node_lift mdbNode) \<noteq> 0 THEN
Guard C_Guard \<lbrace>hrs_htd \<acute>t_hrs \<Turnstile>\<^sub>t nextcte\<rbrace>
(\<acute>ret__unsigned_longlong :== CALL mdb_node_get_mdbFirstBadged(h_val (hrs_mem \<acute>t_hrs) nextmdb));;
\<acute>ret__int :== (if \<acute>ret__unsigned_longlong \<noteq> 0 then 1 else 0);;
IF \<acute>ret__int \<noteq> 0 THEN
SKIP
ELSE
\<acute>ret__unsigned_longlong :== CALL mdb_node_get_mdbFirstBadged(mdbNode);;
\<acute>ret__int :== (if \<acute>ret__unsigned_longlong \<noteq> 0 then 1 else 0)
FI;;
Guard C_Guard \<lbrace>hrs_htd \<acute>t_hrs \<Turnstile>\<^sub>t nextcte\<rbrace>
(CALL mdb_node_ptr_set_mdbFirstBadged(nextmdb,scast \<acute>ret__int))
FI)"
apply (rule ccorres_guard_imp2)
apply (rule ccorres_updateMDB_cte_at)
apply (subgoal_tac "mdbNext rva=(mdbNext_CL (mdb_node_lift mdbNode))")
prefer 2
apply (simp add: cmdbnode_relation_def)
apply (case_tac "mdbNext rva \<noteq> 0")
apply (case_tac "mdbNext_CL (mdb_node_lift mdbNode) = 0", simp)
\<comment> \<open>case where mdbNext rva \<noteq> 0 and mdbNext_CL (mdb_node_lift mdbNode) \<noteq> 0\<close>
apply (unfold updateMDB_def)
apply (clarsimp simp: Let_def)
apply (rule ccorres_pre_getCTE [where P = "\<lambda>cte s. ctes_of s (mdbNext rva) = Some cte" and P' = "\<lambda>_. UNIV"])
apply (rule ccorres_from_vcg)
apply (rule allI)
apply (rule conseqPre, vcg)
apply clarsimp
apply (frule(1) rf_sr_ctes_of_clift)
apply (clarsimp simp: typ_heap_simps' nextmdb_def nextcte_def)
apply (intro conjI impI allI)
\<comment> \<open>\<dots> \<exists>x\<in>fst \<dots>\<close>
apply clarsimp
apply (rule fst_setCTE [OF ctes_of_cte_at], assumption )
apply (erule bexI [rotated])
apply (frule (1) rf_sr_ctes_of_clift)
apply (clarsimp simp add: rf_sr_def cstate_relation_def typ_heap_simps
Let_def cpspace_relation_def)
apply (rule conjI)
prefer 2
apply (erule_tac t = s' in ssubst)
apply (simp add: carch_state_relation_def cmachine_state_relation_def
fpu_null_state_heap_update_tag_disj_simps
cvariable_array_map_const_add_map_option[where f="tcb_no_ctes_proj"]
h_t_valid_clift_Some_iff typ_heap_simps'
cong: lifth_update)
apply (erule (1) setCTE_tcb_case)
apply (erule (2) cspace_cte_relation_upd_mdbI)
apply (simp add: cmdbnode_relation_def)
apply (simp add: mdb_node_to_H_def)
apply (subgoal_tac "mdbFirstBadged_CL (mdb_node_lift mdbNode) && mask (Suc 0) =
mdbFirstBadged_CL (mdb_node_lift mdbNode)")
prefer 2
subgoal by (simp add: mdb_node_lift_def mask_def word_bw_assocs)
apply (subgoal_tac "mdbFirstBadged_CL (cteMDBNode_CL y) && mask (Suc 0) =
mdbFirstBadged_CL (cteMDBNode_CL y)")
prefer 2
apply (drule cteMDBNode_CL_lift [symmetric])
subgoal by (simp add: mdb_node_lift_def mask_def word_bw_assocs)
subgoal by (simp add: to_bool_def mask_def)
\<comment> \<open>\<dots> \<exists>x\<in>fst \<dots>\<close>
apply clarsimp
apply (rule fst_setCTE [OF ctes_of_cte_at], assumption )
apply (erule bexI [rotated])
apply (frule (1) rf_sr_ctes_of_clift)
apply (clarsimp simp add: rf_sr_def cstate_relation_def typ_heap_simps
Let_def cpspace_relation_def)
apply (rule conjI)
prefer 2
apply (erule_tac t = s' in ssubst)
apply (simp add: carch_state_relation_def cmachine_state_relation_def
fpu_null_state_heap_update_tag_disj_simps
cvariable_array_map_const_add_map_option[where f="tcb_no_ctes_proj"]
typ_heap_simps' h_t_valid_clift_Some_iff
cong: lifth_update)
apply (erule (1) setCTE_tcb_case)
apply (erule (2) cspace_cte_relation_upd_mdbI)
apply (simp add: cmdbnode_relation_def)
apply (simp add: mdb_node_to_H_def)
apply (subgoal_tac "mdbFirstBadged_CL (mdb_node_lift mdbNode) && mask (Suc 0) =
mdbFirstBadged_CL (mdb_node_lift mdbNode)")
prefer 2
subgoal by (simp add: mdb_node_lift_def mask_def word_bw_assocs)
apply (subgoal_tac "mdbFirstBadged_CL (cteMDBNode_CL y) && mask (Suc 0) =
mdbFirstBadged_CL (cteMDBNode_CL y)")
prefer 2
apply (drule cteMDBNode_CL_lift [symmetric])
subgoal by (simp add: mdb_node_lift_def mask_def word_bw_assocs)
apply (simp add: to_bool_def mask_def split: if_split)
\<comment> \<open>trivial case where mdbNext rva = 0\<close>
apply (simp add:ccorres_cond_empty_iff)
apply (rule ccorres_guard_imp2)
apply (rule ccorres_return_Skip)
apply simp
apply (clarsimp simp: cmdbnode_relation_def)
done
(************************************************************************)
(* *)
(* emptySlot_ccorres ****************************************************)
(* *)
(************************************************************************)
(* ML "set CtacImpl.trace_ctac"*)
lemma mdbNext_CL_mdb_node_lift_eq_mdbNext:
"cmdbnode_relation n n' \<Longrightarrow> (mdbNext_CL (mdb_node_lift n')) =(mdbNext n)"
by (erule cmdbnode_relationE, fastforce simp: mdbNext_to_H)
lemma mdbPrev_CL_mdb_node_lift_eq_mdbPrev:
"cmdbnode_relation n n' \<Longrightarrow> (mdbPrev_CL (mdb_node_lift n')) =(mdbPrev n)"
by (erule cmdbnode_relationE, fastforce simp: mdbNext_to_H)
lemma mdbNext_not_zero_eq_simpler:
"cmdbnode_relation n n' \<Longrightarrow> (mdbNext n \<noteq> 0) = (mdbNext_CL (mdb_node_lift n') \<noteq> 0)"
apply clarsimp
apply (erule cmdbnode_relationE)
apply (fastforce simp: mdbNext_to_H)
done
lemma mdbPrev_not_zero_eq_simpler:
"cmdbnode_relation n n' \<Longrightarrow> (mdbPrev n \<noteq> 0) = (mdbPrev_CL (mdb_node_lift n') \<noteq> 0)"
apply clarsimp
apply (erule cmdbnode_relationE)
apply (fastforce simp: mdbPrev_to_H)
done
lemma h_t_valid_and_cslift_and_c_guard_field_mdbPrev_CL:
" \<lbrakk>(s, s') \<in> rf_sr; cte_at' slot s; valid_mdb' s; cslift s' (Ptr slot) = Some cte'\<rbrakk>
\<Longrightarrow> (mdbPrev_CL (mdb_node_lift (cteMDBNode_C cte')) \<noteq> 0) \<longrightarrow>
s' \<Turnstile>\<^sub>c ( Ptr (mdbPrev_CL (mdb_node_lift (cteMDBNode_C cte'))) :: cte_C ptr) \<and>
(\<exists> cten. cslift s' (Ptr (mdbPrev_CL (mdb_node_lift (cteMDBNode_C cte'))) :: cte_C ptr) = Some cten) \<and>
c_guard (Ptr &(Ptr (mdbPrev_CL (mdb_node_lift (cteMDBNode_C cte')))::cte_C ptr\<rightarrow>[''cteMDBNode_C'']) :: mdb_node_C ptr)"
apply (clarsimp simp: cte_wp_at_ctes_of)
apply (drule (1) valid_mdb_ctes_of_prev)
apply (frule (2) rf_sr_cte_relation)
apply (drule ccte_relation_cmdbnode_relation)
apply (simp add: mdbPrev_not_zero_eq_simpler)
apply (clarsimp simp: cte_wp_at_ctes_of)
apply (drule (1) rf_sr_ctes_of_clift [rotated])+
apply (clarsimp simp: typ_heap_simps)
apply (rule c_guard_field_lvalue [rotated])
apply (fastforce simp: typ_uinfo_t_def)+
apply (rule c_guard_clift)
apply (simp add: typ_heap_simps)
done
lemma h_t_valid_and_cslift_and_c_guard_field_mdbNext_CL:
" \<lbrakk>(s, s') \<in> rf_sr; cte_at' slot s; valid_mdb' s; cslift s' (Ptr slot) = Some cte'\<rbrakk>
\<Longrightarrow> (mdbNext_CL (mdb_node_lift (cteMDBNode_C cte')) \<noteq> 0) \<longrightarrow>
s' \<Turnstile>\<^sub>c ( Ptr (mdbNext_CL (mdb_node_lift (cteMDBNode_C cte'))) :: cte_C ptr) \<and>
(\<exists> cten. cslift s' (Ptr (mdbNext_CL (mdb_node_lift (cteMDBNode_C cte'))) :: cte_C ptr) = Some cten) \<and>
c_guard (Ptr &(Ptr (mdbNext_CL (mdb_node_lift (cteMDBNode_C cte')))::cte_C ptr\<rightarrow>[''cteMDBNode_C'']) :: mdb_node_C ptr)"
apply (clarsimp simp: cte_wp_at_ctes_of)
apply (drule (1) valid_mdb_ctes_of_next)
apply (frule (2) rf_sr_cte_relation)
apply (drule ccte_relation_cmdbnode_relation)
apply (simp add: mdbNext_not_zero_eq_simpler)
apply (clarsimp simp: cte_wp_at_ctes_of)
apply (drule (1) rf_sr_ctes_of_clift [rotated])+
apply (clarsimp simp: typ_heap_simps)
apply (rule c_guard_field_lvalue [rotated])
apply (fastforce simp: typ_uinfo_t_def)+
apply (rule c_guard_clift)
apply (simp add: typ_heap_simps)
done
lemma valid_mdb_Prev_neq_Next_better:
"\<lbrakk> valid_mdb' s; ctes_of s p = Some cte \<rbrakk> \<Longrightarrow> mdbPrev (cteMDBNode cte) \<noteq> 0 \<longrightarrow>
(mdbNext (cteMDBNode cte)) \<noteq> (mdbPrev (cteMDBNode cte))"
apply (rule impI)
apply (simp add: valid_mdb'_def)
apply (simp add: valid_mdb_ctes_def)
apply (elim conjE)
apply (drule (1) mdb_chain_0_no_loops)
apply (simp add: valid_dlist_def)
apply (erule_tac x=p in allE)
apply (erule_tac x=cte in allE)
apply (simp add: Let_def)
apply clarsimp
apply (drule_tac s="mdbNext (cteMDBNode cte)" in sym)
apply simp
apply (simp add: no_loops_def)
apply (erule_tac x= "(mdbNext (cteMDBNode cte))" in allE)
apply (erule notE, rule trancl_trans)
apply (rule r_into_trancl)
apply (simp add: mdb_next_unfold)
apply (rule r_into_trancl)
apply (simp add: mdb_next_unfold)
done
(* TODO: move *)
definition
irq_opt_relation_def:
"irq_opt_relation (airq :: (8 word) option) (cirq :: machine_word) \<equiv>
case airq of
Some irq \<Rightarrow> (cirq = ucast irq \<and>
irq \<noteq> ucast irqInvalid \<and>
ucast irq \<le> UCAST(32 signed \<rightarrow> 8) Kernel_C.maxIRQ)
| None \<Rightarrow> cirq = ucast irqInvalid"
declare unat_ucast_up_simp[simp]
lemma setIRQState_ccorres:
"ccorres dc xfdc
(\<top> and (\<lambda>s. ucast irq \<le> (ucast Kernel_C.maxIRQ :: machine_word)))
(UNIV \<inter> {s. irqState_' s = irqstate_to_C irqState}
\<inter> {s. irq_' s = ucast irq})
[]
(setIRQState irqState irq)
(Call setIRQState_'proc )"
apply (rule ccorres_gen_asm)
apply (cinit simp del: return_bind)
apply (rule ccorres_symb_exec_l)
apply simp
apply (rule_tac r'="dc" and xf'="xfdc" in ccorres_split_nothrow)
apply (rule_tac P= "\<lambda>s. st = (ksInterruptState s)"
and P'= "(UNIV \<inter> {s. irqState_' s = irqstate_to_C irqState}
\<inter> {s. irq_' s = ucast irq} )"
in ccorres_from_vcg)
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp: setInterruptState_def)
apply (clarsimp simp: simpler_modify_def)
apply (clarsimp simp: rf_sr_def cstate_relation_def Let_def
carch_state_relation_def cmachine_state_relation_def)
apply (simp add: cinterrupt_relation_def Kernel_C.maxIRQ_def)
apply (clarsimp simp: word_sless_msb_less order_le_less_trans
unat_ucast_no_overflow_le word_le_nat_alt ucast_ucast_b
split: if_split )
apply ceqv
apply (ctac add: maskInterrupt_ccorres)
apply wp
apply vcg
apply wp
apply (simp add: getInterruptState_def gets_def)
apply wp
apply (simp add: empty_fail_def getInterruptState_def simpler_gets_def)
apply clarsimp
apply (simp add: from_bool_def)
apply (cases irqState, simp_all)
apply (simp add: Kernel_C.IRQSignal_def Kernel_C.IRQInactive_def)
apply (simp add: Kernel_C.IRQTimer_def Kernel_C.IRQInactive_def)
apply (simp add: Kernel_C.IRQInactive_def Kernel_C.IRQReserved_def)
done
lemma deletedIRQHandler_ccorres:
"ccorres dc xfdc
(\<lambda>s. ucast irq \<le> (ucast Kernel_C.maxIRQ :: machine_word))
(UNIV \<inter> {s. irq_' s = ucast irq}) []
(deletedIRQHandler irq)
(Call deletedIRQHandler_'proc)"
apply (cinit simp del: return_bind)
apply (ctac add: setIRQState_ccorres)
apply clarsimp
done
lemmas ccorres_split_noop_lhs
= ccorres_split_nothrow[where c=Skip, OF _ ceqv_refl _ _ hoarep.Skip,
simplified ccorres_seq_skip]
(* FIXME: to SR_Lemmas *)
lemma region_is_bytes_subset:
"region_is_bytes' ptr sz htd
\<Longrightarrow> {ptr' ..+ sz'} \<subseteq> {ptr ..+ sz}
\<Longrightarrow> region_is_bytes' ptr' sz' htd"
by (auto simp: region_is_bytes'_def)
lemma region_actually_is_bytes_subset:
"region_actually_is_bytes' ptr sz htd
\<Longrightarrow> {ptr' ..+ sz'} \<subseteq> {ptr ..+ sz}
\<Longrightarrow> region_actually_is_bytes' ptr' sz' htd"
by (auto simp: region_actually_is_bytes'_def)
lemma intvl_both_le:
"\<lbrakk> a \<le> x; unat x + y \<le> unat a + b \<rbrakk>
\<Longrightarrow> {x ..+ y} \<le> {a ..+ b}"
apply (rule order_trans[OF _ intvl_sub_offset[where x="x - a"]])
apply (simp, rule order_refl)
apply unat_arith
done
lemma untypedZeroRange_idx_forward_helper:
"isUntypedCap cap
\<Longrightarrow> capFreeIndex cap \<le> idx
\<Longrightarrow> idx \<le> 2 ^ capBlockSize cap
\<Longrightarrow> valid_cap' cap s
\<Longrightarrow> (case (untypedZeroRange cap, untypedZeroRange (capFreeIndex_update (\<lambda>_. idx) cap))
of (Some (a, b), Some (a', b')) \<Rightarrow> {a' ..+ unat (b' + 1 - a')} \<subseteq> {a ..+ unat (b + 1 - a)}
| _ \<Rightarrow> True)"
apply (clarsimp split: option.split)
apply (clarsimp simp: untypedZeroRange_def max_free_index_def Let_def
isCap_simps valid_cap_simps' capAligned_def untypedBits_defs
split: if_split_asm)
apply (erule subsetD[rotated], rule intvl_both_le)
apply (clarsimp simp: getFreeRef_def)
apply (rule word_plus_mono_right)
apply (rule PackedTypes.of_nat_mono_maybe_le)
apply (erule order_le_less_trans, rule power_strict_increasing, simp_all)
apply (erule is_aligned_no_wrap')
apply (rule word_of_nat_less, simp)
apply (simp add: getFreeRef_def)
apply (simp add: unat_plus_simple[THEN iffD1, OF is_aligned_no_wrap']
word_of_nat_less)
apply (simp add: word_of_nat_le unat_sub
order_le_less_trans[OF _ power_strict_increasing]
unat_of_nat_eq[where 'a=machine_word_len, folded word_bits_def])
done
lemma intvl_close_Un:
"y = x + of_nat n
\<Longrightarrow> ({x ..+ n} \<union> {y ..+ m}) = {x ..+ n + m}"
apply ((simp add: intvl_def, safe, simp_all,
simp_all only: of_nat_add[symmetric]); (rule exI, strengthen refl))
apply simp_all
apply (rule ccontr)
apply (drule_tac x="k - n" in spec)
apply simp
done
lemma untypedZeroRange_idx_backward_helper:
"isUntypedCap cap
\<Longrightarrow> idx \<le> capFreeIndex cap
\<Longrightarrow> idx \<le> 2 ^ capBlockSize cap
\<Longrightarrow> valid_cap' cap s
\<Longrightarrow> (case untypedZeroRange (capFreeIndex_update (\<lambda>_. idx) cap)
of None \<Rightarrow> True | Some (a', b') \<Rightarrow>
{a' ..+ unat (b' + 1 - a')} \<subseteq> {capPtr cap + of_nat idx ..+ (capFreeIndex cap - idx)}
\<union> (case untypedZeroRange cap
of Some (a, b) \<Rightarrow> {a ..+ unat (b + 1 - a)}
| None \<Rightarrow> {})
)"
apply (clarsimp split: option.split, intro impI conjI allI)
apply (rule intvl_both_le; clarsimp simp: untypedZeroRange_def
max_free_index_def Let_def
isCap_simps valid_cap_simps' capAligned_def
split: if_split_asm)
apply (clarsimp simp: getFreeRef_def)
apply (clarsimp simp: getFreeRef_def)
apply (simp add: word_of_nat_le unat_sub
order_le_less_trans[OF _ power_strict_increasing]
unat_of_nat_eq[where 'a=machine_word_len, folded word_bits_def])
apply (subst intvl_close_Un)
apply (clarsimp simp: untypedZeroRange_def
max_free_index_def Let_def
getFreeRef_def
split: if_split_asm)
apply (clarsimp simp: untypedZeroRange_def
max_free_index_def Let_def
getFreeRef_def isCap_simps valid_cap_simps'
split: if_split_asm)
apply (simp add: word_of_nat_le unat_sub capAligned_def
order_le_less_trans[OF _ power_strict_increasing]
order_le_less_trans[where x=idx]
unat_of_nat_eq[where 'a=machine_word_len, folded word_bits_def])
done
lemma ctes_of_untyped_zero_rf_sr_case:
"\<lbrakk> ctes_of s p = Some cte; (s, s') \<in> rf_sr;
untyped_ranges_zero' s \<rbrakk>
\<Longrightarrow> case untypedZeroRange (cteCap cte)
of None \<Rightarrow> True
| Some (start, end) \<Rightarrow> region_actually_is_zero_bytes start (unat ((end + 1) - start)) s'"
by (simp split: option.split add: ctes_of_untyped_zero_rf_sr)
lemma gsUntypedZeroRanges_update_helper:
"(\<sigma>, s) \<in> rf_sr
\<Longrightarrow> (zero_ranges_are_zero (gsUntypedZeroRanges \<sigma>) (t_hrs_' (globals s))
\<longrightarrow> zero_ranges_are_zero (f (gsUntypedZeroRanges \<sigma>)) (t_hrs_' (globals s)))
\<Longrightarrow> (gsUntypedZeroRanges_update f \<sigma>, s) \<in> rf_sr"
by (clarsimp simp: rf_sr_def cstate_relation_def Let_def)
lemma heap_list_zero_Ball_intvl:
"heap_list_is_zero hmem ptr n = (\<forall>x \<in> {ptr ..+ n}. hmem x = 0)"
apply safe
apply (erule heap_list_h_eq_better)
apply (simp add: heap_list_rpbs)
apply (rule trans[OF heap_list_h_eq2 heap_list_rpbs])
apply simp
done
lemma untypedZeroRange_not_device:
"untypedZeroRange cap = Some r
\<Longrightarrow> \<not> capIsDevice cap"
by (clarsimp simp: untypedZeroRange_def cong: if_cong)
lemma updateTrackedFreeIndex_noop_ccorres:
"ccorres dc xfdc (cte_wp_at' ((\<lambda>cap. isUntypedCap cap
\<and> idx \<le> 2 ^ capBlockSize cap
\<and> (capFreeIndex cap \<le> idx \<or> cap' = cap)) o cteCap) slot
and valid_objs' and untyped_ranges_zero')
{s. \<not> capIsDevice cap' \<longrightarrow> region_actually_is_zero_bytes (capPtr cap' + of_nat idx) (capFreeIndex cap' - idx) s} hs
(updateTrackedFreeIndex slot idx) Skip"
(is "ccorres dc xfdc ?P ?P' _ _ _")
apply (simp add: updateTrackedFreeIndex_def getSlotCap_def)
apply (rule ccorres_guard_imp)
apply (rule ccorres_pre_getCTE[where P="\<lambda>rv.
cte_wp_at' ((=) rv) slot and ?P" and P'="K ?P'"])
apply (rule ccorres_from_vcg)
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp: cte_wp_at_ctes_of)
apply (frule(1) ctes_of_valid')
apply (frule(2) ctes_of_untyped_zero_rf_sr_case)
apply (clarsimp simp: simpler_modify_def bind_def cte_wp_at_ctes_of)
apply (erule gsUntypedZeroRanges_update_helper)
apply (clarsimp simp: zero_ranges_are_zero_def
split: if_split)
apply (case_tac "(a, b) \<in> gsUntypedZeroRanges \<sigma>")
apply (drule(1) bspec, simp)
apply (erule disjE_L)
apply (frule(3) untypedZeroRange_idx_forward_helper)
apply (clarsimp simp: isCap_simps valid_cap_simps')
apply (case_tac "untypedZeroRange (cteCap cte)")
apply (clarsimp simp: untypedZeroRange_def
valid_cap_simps'
max_free_index_def Let_def
split: if_split_asm)
apply clarsimp
apply (thin_tac "\<not> capIsDevice cap' \<longrightarrow> P" for P)
apply (clarsimp split: option.split_asm)
apply (subst region_actually_is_bytes_subset, simp+)
apply (subst heap_list_is_zero_mono2, simp+)
apply (frule untypedZeroRange_idx_backward_helper[where idx=idx],
simp+)
apply (clarsimp simp: isCap_simps valid_cap_simps')
apply (clarsimp split: option.split_asm)
apply (clarsimp dest!: untypedZeroRange_not_device)
apply (subst region_actually_is_bytes_subset, simp+)
apply (subst heap_list_is_zero_mono2, simp+)
apply (simp add: region_actually_is_bytes'_def heap_list_zero_Ball_intvl)
apply (clarsimp dest!: untypedZeroRange_not_device)
apply blast
apply (clarsimp simp: cte_wp_at_ctes_of)
apply clarsimp
done
lemma updateTrackedFreeIndex_forward_noop_ccorres:
"ccorres dc xfdc (cte_wp_at' ((\<lambda>cap. isUntypedCap cap
\<and> capFreeIndex cap \<le> idx \<and> idx \<le> 2 ^ capBlockSize cap) o cteCap) slot
and valid_objs' and untyped_ranges_zero') UNIV hs
(updateTrackedFreeIndex slot idx) Skip"
(is "ccorres dc xfdc ?P UNIV _ _ _")
apply (rule ccorres_name_pre)
apply (rule ccorres_guard_imp2,
rule_tac cap'="cteCap (the (ctes_of s slot))" in updateTrackedFreeIndex_noop_ccorres)
apply (clarsimp simp: cte_wp_at_ctes_of region_actually_is_bytes'_def)
done
lemma clearUntypedFreeIndex_noop_ccorres:
"ccorres dc xfdc (valid_objs' and untyped_ranges_zero') UNIV hs
(clearUntypedFreeIndex p) Skip"
apply (simp add: clearUntypedFreeIndex_def getSlotCap_def)
apply (rule ccorres_guard_imp)
apply (rule ccorres_pre_getCTE[where P="\<lambda>rv. cte_wp_at' ((=) rv) p
and valid_objs' and untyped_ranges_zero'" and P'="K UNIV"])
apply (case_tac "cteCap cte", simp_all add: ccorres_guard_imp[OF ccorres_return_Skip])[1]
apply (rule ccorres_guard_imp, rule updateTrackedFreeIndex_forward_noop_ccorres)
apply (clarsimp simp: cte_wp_at_ctes_of max_free_index_def)
apply (frule(1) Finalise_R.ctes_of_valid')
apply (clarsimp simp: valid_cap_simps')
apply simp
apply (clarsimp simp: cte_wp_at_ctes_of)
apply simp
done
lemma canonical_address_mdbNext_CL:
"canonical_address (mdbNext_CL (mdb_node_lift (cteMDBNode_C cte')))"
by (simp add: mdb_node_lift_def canonical_address_sign_extended sign_extended_sign_extend)
lemma canonical_address_mdbNext':
"ccte_relation cte cte' \<Longrightarrow> canonical_address (mdbNext (cteMDBNode cte))"
apply (rule rsubst[where P=canonical_address, OF canonical_address_mdbNext_CL])
apply (rule cmdb_node_relation_mdbNext)
apply (erule ccte_relation_cmdbnode_relation)
done
lemma canonical_address_mdbNext:
"\<lbrakk> (s, s') \<in> rf_sr; ctes_of s slot = Some cte \<rbrakk> \<Longrightarrow> canonical_address (mdbNext (cteMDBNode cte))"
apply (drule cmap_relation_cte)
apply (erule (1) cmap_relationE1)
apply (erule canonical_address_mdbNext')
done
definition
arch_cleanup_info_wf' :: "arch_capability \<Rightarrow> bool"
where
"arch_cleanup_info_wf' acap \<equiv> case acap of IOPortCap f l \<Rightarrow> f \<le> l | _ \<Rightarrow> True"
definition
cleanup_info_wf' :: "capability \<Rightarrow> bool"
where
"cleanup_info_wf' cap \<equiv> case cap of
IRQHandlerCap irq \<Rightarrow>
UCAST(8\<rightarrow>machine_word_len) irq \<le> SCAST(32 signed\<rightarrow>machine_word_len) Kernel_C.maxIRQ
| ArchObjectCap acap \<Rightarrow> arch_cleanup_info_wf' acap
| _ \<Rightarrow> True"
(* FIXME: move *)
lemma hrs_mem_update_compose:
"hrs_mem_update f (hrs_mem_update g h) = hrs_mem_update (f \<circ> g) h"
by (auto simp: hrs_mem_update_def split: prod.split)
(* FIXME: move *)
lemma packed_heap_update_collapse':
fixes p :: "'a::packed_type ptr"
shows "heap_update p v \<circ> heap_update p u = heap_update p v"
by (auto simp: packed_heap_update_collapse)
(* FIXME: move *)
lemma access_array_from_elements:
fixes v :: "'a::packed_type['b::finite]"
assumes "\<forall>i < CARD('b). h_val h (array_ptr_index p False i) = v.[i]"
shows "h_val h p = v"
by (rule cart_eq[THEN iffD2]) (simp add: assms heap_access_Array_element')
(* FIXME: move *)
lemma h_val_foldr_heap_update:
fixes v :: "'i \<Rightarrow> 'a::mem_type"
assumes "\<forall>x y. {x,y} \<subseteq> set xs \<longrightarrow> x \<noteq> y \<longrightarrow> ptr_span (p x) \<inter> ptr_span (p y) = {}"
assumes "distinct xs" "i \<in> set xs"
shows "h_val (foldr (\<lambda>i. heap_update (p i) (v i)) xs h) (p i) = v i"
using assms by (induct xs arbitrary: h;
fastforce simp: h_val_heap_update h_val_update_regions_disjoint)
(* FIXME: move *)
lemma ptr_span_array_ptr_index_disjoint:
fixes p :: "('a::packed_type['b::finite]) ptr"
assumes s: "CARD('b) * size_of TYPE('a) \<le> 2 ^ addr_bitsize"
assumes b: "x < CARD('b)" "y < CARD('b)"
assumes n: "x \<noteq> y"
shows "ptr_span (array_ptr_index p False x) \<inter> ptr_span (array_ptr_index p False y) = {}"
proof -
have l: "CARD('b) * size_of TYPE('a) \<le> 2 ^ LENGTH(64)" using s by simp
have p: "\<And>x k. x < CARD('b) \<Longrightarrow> k < size_of TYPE('a)
\<Longrightarrow> x * size_of TYPE('a) + k < 2 ^ LENGTH(64)"
by (metis less_le_trans[OF _ l] less_imp_not_less mod_lemma mult.commute nat_mod_lem neq0_conv)
show ?thesis
apply (clarsimp simp: array_ptr_index_def ptr_add_def intvl_disj_offset)
apply (rule disjointI)
apply (clarsimp simp: intvl_def)
apply (subst (asm) of_nat_mult[symmetric])+
apply (subst (asm) of_nat_add[symmetric])+
apply (subst (asm) of_nat_inj[OF p p]; (simp add: b)?)
apply (drule arg_cong[where f="\<lambda>x. x div size_of TYPE('a)"]; simp add: n)
done
qed
(* FIXME: move *)
lemma h_val_heap_update_Array:
fixes v :: "'a::packed_type['b::finite]"
assumes s: "CARD('b) * size_of TYPE('a) \<le> 2 ^ addr_bitsize"
shows "h_val (heap_update p v h) p = v"
apply (rule access_array_from_elements)
apply (clarsimp simp: heap_update_Array foldl_conv_foldr)
apply (rule h_val_foldr_heap_update; clarsimp simp: ptr_span_array_ptr_index_disjoint[OF s])
done
(* FIXME: move *)
lemma foldr_heap_update_commute:
assumes "\<forall>y. y \<in> set xs \<longrightarrow> ptr_span q \<inter> ptr_span (p y) = {}"
shows "foldr (\<lambda>i. heap_update (p i) (v i)) xs (heap_update q u h)
= heap_update q u (foldr (\<lambda>i. heap_update (p i) (v i)) xs h)"
using assms by (induct xs) (auto simp: LemmaBucket_C.heap_update_commute)
(* FIXME: move *)
lemma foldr_packed_heap_update_collapse:
fixes u v :: "'i \<Rightarrow> 'a::packed_type"
assumes "\<forall>x y. {x,y} \<subseteq> set xs \<longrightarrow> y \<noteq> x \<longrightarrow> ptr_span (p x) \<inter> ptr_span (p y) = {}"
assumes "distinct xs"
shows "foldr (\<lambda>i. heap_update (p i) (v i)) xs (foldr (\<lambda>i. heap_update (p i) (u i)) xs h)
= foldr (\<lambda>i. heap_update (p i) (v i)) xs h"
using assms
apply -
apply (induct xs arbitrary: h; clarsimp; rename_tac x xs h)
apply (drule_tac x=x in spec; clarsimp)
apply (subst foldr_heap_update_commute; clarsimp simp: packed_heap_update_collapse)
apply (drule_tac x=y in spec; clarsimp)
done
(* FIXME: move *)
lemma packed_Array_heap_update_collapse:
fixes p :: "('a::packed_type['b::finite]) ptr"
assumes s: "CARD('b) * size_of TYPE('a) \<le> 2 ^ addr_bitsize"
shows "heap_update p v (heap_update p u h) = heap_update p v h"
by (simp add: heap_update_Array foldl_conv_foldr foldr_packed_heap_update_collapse
ptr_span_array_ptr_index_disjoint[OF s])
(* FIXME: move *)
lemma packed_Array_heap_update_collapse':
fixes p :: "('a::packed_type['b::finite]) ptr"
assumes s: "CARD('b) * size_of TYPE('a) \<le> 2 ^ addr_bitsize"
shows "heap_update p v \<circ> heap_update p u = heap_update p v"
by (auto simp: packed_Array_heap_update_collapse[OF s])
(* FIXME: move *)
definition
heap_modify :: "'a::c_type ptr \<Rightarrow> ('a \<Rightarrow> 'a) \<Rightarrow> heap_mem \<Rightarrow> heap_mem"
where
"heap_modify p f \<equiv> \<lambda>h. heap_update p (f (h_val h p)) h"
(* FIXME: move *)
lemma heap_modify_def2:
"heap_modify (p::'a::c_type ptr) f \<equiv>
\<lambda>h. let bytes = heap_list h (size_of TYPE('a)) (ptr_val p) in
heap_update_list (ptr_val p) (to_bytes (f (from_bytes bytes)) bytes) h"
by (simp add: heap_modify_def Let_def heap_update_def h_val_def)
(* FIXME: move *)
lemma heap_modify_compose:
fixes p :: "'a::packed_type ptr"
shows "heap_modify p f \<circ> heap_modify p g = heap_modify p (f \<circ> g)"
and "heap_modify p f (heap_modify p g h) = heap_modify p (f \<circ> g) h"
by (auto simp: heap_modify_def h_val_heap_update packed_heap_update_collapse)
(* FIXME: move *)
lemma heap_modify_compose_Array:
fixes p :: "('a::packed_type['b::finite]) ptr"
assumes s: "CARD('b) * size_of TYPE('a) \<le> 2 ^ addr_bitsize"
shows "heap_modify p f \<circ> heap_modify p g = heap_modify p (f \<circ> g)"
and "heap_modify p f (heap_modify p g h) = heap_modify p (f \<circ> g) h"
by (auto simp: heap_modify_def h_val_heap_update_Array[OF s]
packed_Array_heap_update_collapse[OF s])
(* FIXME: move *)
lemma fold_heap_modify_commute:
fixes p :: "'a::packed_type ptr"
shows "fold (heap_modify p \<circ> f) upds = heap_modify p (fold f upds)"
apply (induction upds)
apply (simp add: heap_modify_def heap_update_id)
apply (clarsimp simp: heap_modify_compose[THEN fun_cong, simplified] o_def)
done
(* FIXME: move *)
lemma fold_heap_modify_commute_Array:
fixes p :: "('a::packed_type['b::finite]) ptr"
assumes s: "CARD('b) * size_of TYPE('a) \<le> 2 ^ addr_bitsize"
shows "fold (heap_modify p \<circ> f) upds = heap_modify p (fold f upds)"
apply (induction upds)
apply (simp add: heap_modify_def heap_update_id_Array)
apply (clarsimp simp: heap_modify_compose_Array[OF s, THEN fun_cong, simplified] o_def)
done
lemma make_pattern_spec:
defines "bits \<equiv> 0x40 :: 32 sword"
notes word_less_imp_less_0 = revcut_rl[OF word_less_imp_sless[OF _ word_msb_0]]
notes word_le_imp_le_0 = revcut_rl[OF word_le_imp_sle[OF _ word_msb_0]]
shows
"\<forall>\<sigma>. \<Gamma> \<turnstile>
{s. s = \<sigma> \<and> start___int_' s < end___int_' s
\<and> end___int_' s \<le> bits }
Call make_pattern_'proc
{t. ret__unsigned_long_' t =
mask (unat (end___int_' \<sigma>)) && ~~ mask (unat (start___int_' \<sigma>))}"
apply (rule allI, rule conseqPre, hoare_rule HoarePartial.ProcNoRec1, vcg, clarsimp)
apply (fold bits_def)
subgoal for \<sigma>
apply (frule (1) word_sandwich1[of "start___int_' \<sigma>" "end___int_' \<sigma>" bits]; clarsimp)
apply (frule (1) word_sandwich2[of "end___int_' \<sigma> - start___int_' \<sigma>" bits])
apply (subgoal_tac "\<not> msb bits")
prefer 2 subgoal by (simp add: bits_def)
apply (frule (1) neg_msb_le_mono[of "end___int_' \<sigma>"])
apply (frule (1) neg_msb_less_mono[of "start___int_' \<sigma>"])
apply (frule (1) neg_msb_le_mono[of "end___int_' \<sigma> - start___int_' \<sigma>"])
apply (frule (1) neg_msb_less_mono[of "bits - (end___int_' \<sigma> - start___int_' \<sigma>)"])
apply (rule word_le_imp_le_0[of "start___int_' \<sigma>"], simp, simp)
apply (frule (2) word_less_imp_sless[of "start___int_' \<sigma>" "end___int_' \<sigma>"])
apply (frule (2) word_le_imp_sle[of "end___int_' \<sigma>" bits])
apply (rule word_less_imp_less_0[of "end___int_' \<sigma> - start___int_' \<sigma>"], simp, simp)
apply (frule (2) word_le_imp_sle[of "end___int_' \<sigma> - start___int_' \<sigma>" bits])
apply (rule word_le_imp_le_0[of "bits - (end___int_' \<sigma> - start___int_' \<sigma>)"], simp, simp)
apply (frule (2) word_less_imp_sless[of "bits - (end___int_' \<sigma> - start___int_' \<sigma>)" bits])
apply (intro conjI; (fastforce simp: word_sle_def word_sless_def bits_def | simp)?)
apply (subgoal_tac "start___int_' \<sigma> \<le> bits - (end___int_' \<sigma> - start___int_' \<sigma>)")
prefer 2
apply (meson le_minus_minus order.strict_implies_order order_trans word_le_minus_mono_left)
apply (simp add: shiftr_shiftl1 word_le_nat_alt[symmetric] unat_sub[symmetric] max_word_mask)
apply (subst shiftr_mask2, simp)
apply (simp add: unat_sub word_le_nat_alt bits_def)
done
done
definition
word_set_or_clear :: "bool \<Rightarrow> 'a::len word \<Rightarrow> 'a::len word \<Rightarrow> 'a::len word"
where
"word_set_or_clear s p w \<equiv> if s then w || p else w && ~~ p"
lemma apply_pattern_spec:
"\<forall>\<sigma>. \<Gamma> \<turnstile>
{s. s = \<sigma> \<and> s \<Turnstile>\<^sub>c w___ptr_to_unsigned_long_' \<sigma>}
Call apply_pattern_'proc
{globals_update
(t_hrs_'_update
(hrs_mem_update
(heap_update (w___ptr_to_unsigned_long_' \<sigma>)
(word_set_or_clear (to_bool (set_' \<sigma>))
(pattern_' \<sigma>)
(h_val (hrs_mem (t_hrs_' (globals \<sigma>)))
(w___ptr_to_unsigned_long_' \<sigma>)))))) \<sigma>}"
apply (rule allI, rule conseqPre, hoare_rule HoarePartial.ProcNoRec1, vcg)
apply (clarsimp simp: word_set_or_clear_def to_bool_def)
done
(* FIXME: move *)
lemma whileAnno_subst_invariant:
"whileAnno b I' V c = whileAnno b I V c"
by (simp add: whileAnno_def)
abbreviation
ioport_table_ptr_coerce :: "'a ptr \<Rightarrow> ioport_table_C ptr"
where
"ioport_table_ptr_coerce \<equiv> ptr_coerce"
lemma hoarep_conseq_spec_state:
fixes \<Gamma> :: "'p \<Rightarrow> ('s,'p,'f) com option"
assumes "\<forall>\<sigma>. \<Gamma> \<turnstile> {s. s = \<sigma> \<and> P s} c (Q \<sigma>)"
assumes "\<forall>\<sigma>. \<sigma> \<in> P' \<longrightarrow> P \<sigma> \<and> Q \<sigma> \<subseteq> Q'"
shows "\<Gamma> \<turnstile> P' c Q'"
using assms by (fastforce intro: hoarep.Conseq)
lemma hrs_simps:
"hrs_mem (mem, htd) = mem"
"hrs_mem_update f (mem, htd) = (f mem, htd)"
"hrs_htd (mem, htd) = htd"
"hrs_htd_update g (mem, htd) = (mem, g htd)"
by (auto simp: hrs_mem_def hrs_mem_update_def hrs_htd_def hrs_htd_update_def)
lemma clift_heap_modify_same:
fixes p :: "'a :: mem_type ptr"
assumes "hrs_htd hp \<Turnstile>\<^sub>t p"
assumes "typ_uinfo_t TYPE('a) \<bottom>\<^sub>t typ_uinfo_t TYPE('b)"
shows "clift (hrs_mem_update (heap_modify p f) hp) = (clift hp :: 'b :: mem_type typ_heap)"
using assms unfolding hrs_mem_update_def
apply (cases hp)
apply (simp add: split_def hrs_htd_def heap_modify_def)
apply (erule lift_t_heap_update_same)
apply simp
done
lemma zero_ranges_are_zero_modify[simp]:
"h_t_valid (hrs_htd hrs) c_guard (ptr :: 'a ptr)
\<Longrightarrow> typ_uinfo_t TYPE('a :: wf_type) \<noteq> typ_uinfo_t TYPE(word8)
\<Longrightarrow> zero_ranges_are_zero rs (hrs_mem_update (heap_modify ptr f) hrs)
= zero_ranges_are_zero rs hrs"
apply (clarsimp simp: zero_ranges_are_zero_def hrs_mem_update
intro!: ball_cong[OF refl] conj_cong[OF refl])
apply (drule region_actually_is_bytes)
apply (drule(2) region_is_bytes_disjoint)
apply (simp add: heap_modify_def heap_update_def heap_list_update_disjoint_same Int_commute)
done
lemma h_val_heap_modify:
fixes p :: "'a::mem_type ptr"
shows "h_val (heap_modify p f h) p = f (h_val h p)"
by (simp add: heap_modify_def h_val_heap_update)
lemma array_fupdate_index:
fixes arr :: "'a::c_type['b::finite]"
assumes "i < CARD('b)" "j < CARD('b)"
shows "fupdate i f arr.[j] = (if i = j then f (arr.[i]) else arr.[j])"
using assms by (cases "i = j"; simp add: fupdate_def)
lemma foldl_map_pair_constant:
"foldl (\<lambda>acc p. f acc (fst p) (snd p)) z (map (\<lambda>x. (x,v)) xs) = foldl (\<lambda>acc x. f acc x v) z xs"
by (induct xs arbitrary: z) auto
lemma word_set_or_clear_test_bit:
fixes w :: "'a::len word"
shows "i < LENGTH('a) \<Longrightarrow> word_set_or_clear b p w !! i = (if p !! i then b else w !! i)"
by (auto simp: word_set_or_clear_def word_ops_nth_size word_size split: if_splits)
lemma heap_modify_fold:
"heap_update p (f (h_val h p)) h = heap_modify p f h"
by (simp add: heap_modify_def)
lemma fold_array_update_index:
fixes arr :: "'a::c_type['b::finite]"
assumes "i < CARD('b)"
shows "fold (\<lambda>i arr. Arrays.update arr i (f i)) is arr.[i] = (if i \<in> set is then f i else arr.[i])"
using assms by (induct "is" arbitrary: arr) (auto split: if_splits)
lemma t_hrs_'_update_heap_modify_fold:
"gs\<lparr> t_hrs_' := hrs_mem_update (heap_update p (f (h_val (hrs_mem (t_hrs_' gs)) p))) (t_hrs_' gs) \<rparr>
= t_hrs_'_update (hrs_mem_update (heap_modify p f)) gs"
by (clarsimp simp: heap_modify_def hrs_mem_update_def hrs_mem_def split: prod.splits)
lemma heap_modify_Array_element:
fixes p :: "'a::packed_type ptr"
fixes p' :: "('a['b::finite]) ptr"
assumes "p = ptr_coerce p' +\<^sub>p int n"
assumes "n < CARD('b)"
assumes "CARD('b) * size_of TYPE('a) < 2 ^ addr_bitsize"
shows "heap_modify p f = heap_modify p' (fupdate n f)"
using assms by (simp add: heap_access_Array_element heap_update_Array_element'
heap_modify_def fupdate_def)
lemma fupdate_word_set_or_clear_max_word:
"fupdate i (word_set_or_clear b max_word) arr = Arrays.update arr i (if b then max_word else 0)"
by (simp add: fupdate_def word_set_or_clear_def cong: if_cong)
lemma h_t_valid_Array_element':
"\<lbrakk> htd \<Turnstile>\<^sub>t (p :: (('a :: mem_type)['b :: finite]) ptr); 0 \<le> n; n < int CARD('b) \<rbrakk>
\<Longrightarrow> htd \<Turnstile>\<^sub>t ((ptr_coerce p :: 'a ptr) +\<^sub>p n)"
by (fact h_t_valid_Array_element)
lemma setIOPortMask_spec:
notes ucast_mask = ucast_and_mask[where n=6, simplified mask_def, simplified]
notes not_max_word_simps = and_not_max_word shiftr_not_max_word and_mask_not_max_word
notes ucast_cmp_ucast = ucast_le_ucast ucast_less_ucast_weak
notes array_assert = array_assertion_shrink_right[OF array_ptr_valid_array_assertionD]
notes word_unat.Rep_inject[simp del]
shows
"\<forall>\<sigma>. \<Gamma> \<turnstile>
{s. s = \<sigma> \<and> low_' s \<le> high_' s \<and> s \<Turnstile>\<^sub>c ioport_table_ptr_coerce (ioport_bitmap_' s)}
Call setIOPortMask_'proc
{t. globals t = t_hrs_'_update
(hrs_mem_update
(heap_modify
(ioport_table_ptr_coerce (ioport_bitmap_' \<sigma>))
(let low_word = low_' \<sigma> >> wordRadix;
high_word = high_' \<sigma> >> wordRadix;
low_mask = ~~ mask (unat (low_' \<sigma> && mask wordRadix));
high_mask = mask (Suc (unat (high_' \<sigma> && mask wordRadix)));
b = to_bool (set_' \<sigma>) in
if low_word = high_word
then fupdate (unat low_word) (word_set_or_clear b (high_mask && low_mask))
else fupdate (unat high_word) (word_set_or_clear b high_mask)
\<circ> fold (\<lambda>i arr. Arrays.update arr i (if b then max_word else 0))
([Suc (unat low_word) ..< unat high_word])
\<circ> fupdate (unat low_word) (word_set_or_clear b low_mask))))
(globals \<sigma>)}"
apply (rule allI)
apply (hoare_rule HoarePartial.ProcNoRec1)
apply (simp add: scast_ucast_up_eq_ucast word_upcast_shiftr[symmetric] ucast_mask[symmetric]
word_upcast_0_sle)
apply (rule ssubst[where P="\<lambda>c. hoarep \<Gamma> {} {} P (Catch (c1;; (Cond b c2 (c3;; c;; c4;; c5))) Skip) Q A"
for P c1 b c2 c3 c4 c5 Q A],
rule_tac I="{s. s \<Turnstile>\<^sub>c ioport_table_ptr_coerce (bitmap_' s)
\<and> bitmap_' s = ptr_coerce (ioport_bitmap_' \<sigma>)
\<and> ucast (low_' \<sigma> >> wordRadix) < low_word_' s
\<and> low_word_' s <= high_word_' s
\<and> high_word_' s = ucast (high_' \<sigma> >> wordRadix)
\<and> high_index_' s = ucast (high_' \<sigma> && mask wordRadix)
\<and> set_' s = set_' \<sigma>
\<and> globals s = t_hrs_'_update
(hrs_mem_update
(heap_modify
(ioport_table_ptr_coerce (ioport_bitmap_' \<sigma>))
(fold (\<lambda>i arr. Arrays.update arr i (if to_bool (set_' \<sigma>) then max_word else 0))
([Suc (unat (low_' \<sigma> >> wordRadix)) ..< unat (low_word_' s)])
\<circ> fupdate
(unat (low_' \<sigma> >> wordRadix))
(word_set_or_clear
(to_bool (set_' \<sigma>))
(~~ mask (unat (low_' \<sigma> && mask wordRadix)))))))
(globals \<sigma>)}"
in whileAnno_subst_invariant)
supply Word.of_nat_unat[simp del]
apply (rule conseqPre, vcg)
apply (all \<open>clarsimp simp: Let_def wordRadix_def hrs_simps is_up is_down
unat_ucast_upcast uint_up_ucast sint_ucast_eq_uint up_ucast_inj_eq
not_max_word_simps[THEN ucast_increment]
ucast_cmp_ucast ucast_cmp_ucast[where 'a=16 and y="0x40", simplified]
heap_modify_fold t_hrs_'_update_heap_modify_fold
cong: conj_cong\<close>)
subgoal for mem htd ioport_bitmap high set low low_word
(* Loop invariant is preserved. *)
apply (frule neg_msb_le_mono[OF _ word_upcast_neg_msb];
simp add: word_sless_iff_less[OF _ word_upcast_neg_msb] sint_eq_uint unat_arith_simps)
apply (frule less_trans[OF _ unat_shiftr_less_2p[where m=10]]; simp)
apply (frule h_t_valid_Array_element[where n="uint low_word"];
simp add: uint_nat heap_modify_compose o_def fupdate_word_set_or_clear_max_word
heap_modify_Array_element[where 'b=1024 and p'="ptr_coerce ioport_bitmap"])
apply (clarsimp elim!: array_assertion_shrink_right dest!: array_ptr_valid_array_assertionD)
done
subgoal for mem htd ioport_bitmap high set low low_word
(* Invariant plus loop termination condition is sufficient to establish VCG postcondition. *)
apply (frule neg_msb_le_mono[OF _ word_upcast_neg_msb];
simp add: word_sless_iff_less[OF _ word_upcast_neg_msb] sint_eq_uint unat_arith_simps)
apply (cut_tac unat_and_mask_less_2p[of 6 high]; simp)
apply (cut_tac unat_shiftr_less_2p[of 6 10 high]; simp)
apply (frule h_t_valid_Array_element[where n="uint low_word"];
simp add: uint_nat heap_modify_compose o_def fupdate_word_set_or_clear_max_word
heap_modify_Array_element[where 'b=1024 and p'="ptr_coerce ioport_bitmap"])
apply (clarsimp elim!: array_assertion_shrink_right dest!: array_ptr_valid_array_assertionD)
done
subgoal for \<sigma>'
(* VCG precondition is sufficient to establish loop invariant. *)
apply (frule word_le_split_mask[where n=6, THEN iffD1])
apply (simp add: unat_arith_simps)
apply (cut_tac unat_shiftr_less_2p[of 6 10 "low_' \<sigma>'"]; simp)
apply (cut_tac unat_shiftr_less_2p[of 6 10 "high_' \<sigma>'"]; simp)
apply (cut_tac unat_and_mask_less_2p[of 6 "low_' \<sigma>'"]; simp)
apply (cut_tac unat_and_mask_less_2p[of 6 "high_' \<sigma>'"]; simp)
apply (simp add: uint_nat mask_def[where n=6] mask_def[where n=64] less_Suc_eq_le Suc_le_eq
heap_modify_Array_element[where 'b=1024 and p'="ptr_coerce (ioport_bitmap_' \<sigma>')"])
apply (frule h_t_valid_Array_element[where n="uint (low_' \<sigma>' >> 6)"]; simp add: uint_nat)
apply (frule h_t_valid_Array_element[where n="uint (high_' \<sigma>' >> 6)"]; simp add: uint_nat)
apply (frule array_assert[where n'="unat (low_' \<sigma>' >> 6)"]; simp)
apply (frule array_assert[where n'="unat (high_' \<sigma>' >> 6)"]; simp)
by auto
done
lemma setIOPortMask_ccorres:
notes Collect_const[simp del] if_cong[cong]
shows
"ccorres dc xfdc
(\<lambda>_. f \<le> l)
(UNIV \<inter> \<lbrace>\<acute>ioport_bitmap = Ptr (symbol_table ''x86KSAllocatedIOPorts'')\<rbrace>
\<inter> \<lbrace>\<acute>low = f\<rbrace>
\<inter> \<lbrace>\<acute>high = l\<rbrace>
\<inter> \<lbrace>\<acute>set = from_bool b\<rbrace>) hs
(setIOPortMask f l b)
(Call setIOPortMask_'proc)"
apply (intro ccorres_from_vcg hoarep_conseq_spec_state[OF setIOPortMask_spec] allI)
apply (clarsimp simp: rf_sr_def cstate_relation_def carch_state_relation_def Let_def
global_ioport_bitmap_relation_def2
setIOPortMask_def gets_def get_def modify_def put_def
monad_simps in_monad
hrs_mem_update h_val_heap_modify
clift_heap_modify_same tag_disj_via_td_name
cpspace_relation_def carch_globals_def cmachine_state_relation_def
fpu_null_state_relation_def)
apply (match premises in H: \<open>cioport_bitmap_to_H _ = _\<close> and O: \<open>low_' s \<le> high_' s\<close> for s
\<Rightarrow> \<open>match premises in _[thin]: _(multi) \<Rightarrow> \<open>insert O H\<close>\<close>)
apply (clarsimp simp: cioport_bitmap_to_H_def wordRadix_def, rule ext, drule_tac x=port in fun_cong)
apply (clarsimp simp: foldl_map_pair_constant foldl_fun_upd_value)
apply (rule ssubst[where P="\<lambda>f. test_bit f i = e" for e i, OF if_distrib[where f="\<lambda>c. c v.[i]" for v i]])
apply (simp add: array_fupdate_index fold_array_update_index word_set_or_clear_test_bit
if_distrib[where f="\<lambda>c. test_bit c i" for i] word_ops_nth_size word_size
unat_shiftr_less_2p[of 6 10, simplified] unat_and_mask_less_2p[of 6, simplified]
less_Suc_eq_le Suc_le_eq not_less unat_arith_simps(1,2)[symmetric]
if_if_same_output if_if_if_same_output less_Suc_eq_le[where n=63, symmetric])
apply (thin_tac "_ = _")
apply (rule if_weak_cong)
apply (rule ssubst[OF word_le_split_mask[where n=6], where P="\<lambda>f. e \<longleftrightarrow> f \<and> c" for e c])
apply (rule ssubst[OF word_le_split_mask[where n=6], where P="\<lambda>f. e \<longleftrightarrow> c \<and> f" for e c])
apply (drule word_le_split_mask[where n=6, THEN iffD1])
by auto
lemma freeIOPortRange_ccorres:
"ccorres dc xfdc (\<top> and (\<lambda>s. f \<le> l))
(UNIV \<inter> {s. first_port_' s = f} \<inter> {s. last_port_' s = l}) hs
(freeIOPortRange f l)
(Call freeIOPortRange_'proc)"
apply (cinit lift: first_port_' last_port_')
apply (rule ccorres_Guard)
apply (ctac add: setIOPortMask_ccorres)
by (clarsimp simp: false_def rf_sr_def cstate_relation_def Let_def carch_state_relation_def
global_ioport_bitmap_relation_def typ_heap_simps
split: if_splits)
lemma Arch_postCapDeletion_ccorres:
"ccorres dc xfdc
(\<top> and (\<lambda>s. arch_cleanup_info_wf' acap))
(UNIV \<inter> {s. ccap_relation (ArchObjectCap acap) (cap_' s)}) hs
(X64_H.postCapDeletion acap)
(Call Arch_postCapDeletion_'proc)"
apply (cinit lift: cap_')
apply csymbr
apply (wpc; clarsimp simp: cap_get_tag_isCap_unfolded_H_cap cap_tag_defs; ccorres_rewrite)
prefer 3 (* IOPort case *)
apply (rule ccorres_rhs_assoc)+
apply csymbr+
apply (ctac add: freeIOPortRange_ccorres[simplified dc_def])
apply (rule ccorres_return_Skip[simplified dc_def])+
apply (clarsimp simp: arch_cleanup_info_wf'_def split: arch_capability.splits)
apply (frule cap_get_tag_isCap_unfolded_H_cap)
by (clarsimp simp: ccap_relation_def cap_io_port_cap_lift cap_to_H_def)
lemma not_irq_or_arch_cap_case:
"\<lbrakk>\<not>isIRQHandlerCap cap; \<not> isArchCap \<top> cap\<rbrakk> \<Longrightarrow>
(case cap of IRQHandlerCap irq \<Rightarrow> f irq | ArchObjectCap acap \<Rightarrow> g acap | _ \<Rightarrow> h) = h"
by (case_tac cap; clarsimp simp: isCap_simps)
lemma postCapDeletion_ccorres:
"cleanup_info_wf' cap \<Longrightarrow>
ccorres dc xfdc
\<top> (UNIV \<inter> {s. ccap_relation cap (cap_' s)}) hs
(postCapDeletion cap)
(Call postCapDeletion_'proc)"
supply Collect_const[simp del]
apply (cinit lift: cap_' simp: Retype_H.postCapDeletion_def)
apply csymbr
apply (clarsimp simp: cap_get_tag_isCap)
apply (rule ccorres_Cond_rhs)
apply (clarsimp simp: isCap_simps )
apply (rule ccorres_symb_exec_r)
apply (rule_tac xf'=irq_' in ccorres_abstract, ceqv)
apply (rule_tac P="rv' = ucast (capIRQ cap)" in ccorres_gen_asm2)
apply (fold dc_def)
apply (frule cap_get_tag_to_H, solves \<open>clarsimp simp: cap_get_tag_isCap_unfolded_H_cap\<close>)
apply (clarsimp simp: cap_irq_handler_cap_lift)
apply (ctac(no_vcg) add: deletedIRQHandler_ccorres)
apply vcg
apply (rule conseqPre, vcg)
apply clarsimp
apply csymbr
apply (clarsimp simp: cap_get_tag_isCap)
apply (rule ccorres_Cond_rhs)
apply (wpc; clarsimp simp: isCap_simps)
apply (ctac(no_vcg) add: Arch_postCapDeletion_ccorres[unfolded dc_def])
apply (simp add: not_irq_or_arch_cap_case)
apply (rule ccorres_return_Skip[unfolded dc_def])+
apply clarsimp
apply (rule conjI, clarsimp simp: isCap_simps Kernel_C.maxIRQ_def)
apply (frule cap_get_tag_isCap_unfolded_H_cap(5))
apply (clarsimp simp: cap_irq_handler_cap_lift ccap_relation_def cap_to_H_def
cleanup_info_wf'_def maxIRQ_def Kernel_C.maxIRQ_def)
(* apply word_bitwise *)
apply (rule conjI, clarsimp simp: isCap_simps cleanup_info_wf'_def)
apply (rule conjI[rotated], clarsimp simp: isCap_simps)
apply (clarsimp simp: isCap_simps)
apply (frule cap_get_tag_isCap_unfolded_H_cap(5))
apply (clarsimp simp: cap_irq_handler_cap_lift ccap_relation_def cap_to_H_def
cleanup_info_wf'_def c_valid_cap_def cl_valid_cap_def mask_def
)
apply (rule mask_eq_ucast_eq[where 'a="8" and 'b="64" and 'c="64", symmetric, simplified])
by (simp add: mask_def)
lemma emptySlot_ccorres:
"ccorres dc xfdc
(valid_mdb' and valid_objs' and pspace_aligned' and untyped_ranges_zero')
(UNIV \<inter> {s. slot_' s = Ptr slot}
\<inter> {s. ccap_relation info (cleanupInfo_' s) \<and> cleanup_info_wf' info} )
[]
(emptySlot slot info)
(Call emptySlot_'proc)"
supply if_cong[cong]
apply (cinit lift: slot_' cleanupInfo_' simp: case_Null_If)
\<comment> \<open>--- handle the clearUntypedFreeIndex\<close>
apply (rule ccorres_split_noop_lhs, rule clearUntypedFreeIndex_noop_ccorres)
\<comment> \<open>--- instruction: newCTE \<leftarrow> getCTE slot; ---\<close>
apply (rule ccorres_pre_getCTE)
\<comment> \<open>--- instruction: CALL on C side\<close>
apply (rule ccorres_move_c_guard_cte)
apply csymbr
apply (rule ccorres_abstract_cleanup)
apply (rename_tac cap_tag)
apply (rule_tac P="(cap_tag = scast cap_null_cap)
= (cteCap newCTE = NullCap)" in ccorres_gen_asm2)
apply (simp del: Collect_const)
\<comment> \<open>--- instruction: if-then-else / IF-THEN-ELSE\<close>
apply (rule ccorres_cond2'[where R=\<top>])
\<comment> \<open>*** link between abstract and concrete conditionals ***\<close>
apply (clarsimp split: if_split)
\<comment> \<open>*** proof for the 'else' branch (return () and SKIP) ***\<close>
prefer 2
apply (ctac add: ccorres_return_Skip[unfolded dc_def])
\<comment> \<open>*** proof for the 'then' branch ***\<close>
\<comment> \<open>---instructions: multiple on C side, including mdbNode fetch\<close>
apply (rule ccorres_rhs_assoc)+
\<comment> \<open>we have to do it here because the first assoc did not apply inside the then block\<close>
apply (rule ccorres_move_c_guard_cte | csymbr)+
apply (rule ccorres_symb_exec_r)
apply (rule_tac xf'="mdbNode_'" in ccorres_abstract, ceqv)
apply (rename_tac "cmdbNode")
apply (rule_tac P="cmdbnode_relation (cteMDBNode newCTE) cmdbNode"
in ccorres_gen_asm2)
apply csymbr+
\<comment> \<open>--- instruction: updateMDB (mdbPrev rva) (mdbNext_update \<dots>) but with Ptr\<dots>\<noteq> NULL on C side\<close>
apply (simp only:Ptr_not_null_pointer_not_zero) \<comment> \<open>replaces Ptr p \<noteq> NULL with p\<noteq>0\<close>
\<comment> \<open>--- instruction: y \<leftarrow> updateMDB (mdbPrev rva) (mdbNext_update (\<lambda>_. mdbNext rva))\<close>
apply (ctac (no_simp, no_vcg) pre:ccorres_move_guard_ptr_safe
add: updateMDB_mdbPrev_set_mdbNext)
\<comment> \<open>here ctac alone does not apply because the subgoal generated
by the rule are not solvable by simp\<close>
\<comment> \<open>so we have to use (no_simp) (or apply (rule ccorres_split_nothrow))\<close>
apply (simp add: cmdbnode_relation_def)
apply assumption
\<comment> \<open>*** Main goal ***\<close>
\<comment> \<open>--- instruction: updateMDB (mdbNext rva)
(\<lambda>mdb. mdbFirstBadged_update (\<lambda>_. mdbFirstBadged mdb \<or> mdbFirstBadged rva)
(mdbPrev_update (\<lambda>_. mdbPrev rva) mdb));\<close>
apply (rule ccorres_rhs_assoc2 ) \<comment> \<open>to group the 2 first C instrutions together\<close>
apply (ctac (no_vcg) add: emptySlot_helper)
\<comment> \<open>--- instruction: y \<leftarrow> updateCap slot capability.NullCap;\<close>
apply (simp del: Collect_const)
apply csymbr
apply (ctac (no_vcg) pre:ccorres_move_guard_ptr_safe)
apply csymbr
apply (rule ccorres_move_c_guard_cte)
\<comment> \<open>--- instruction y \<leftarrow> updateMDB slot (\<lambda>a. nullMDBNode);\<close>
apply (ctac (no_vcg) pre: ccorres_move_guard_ptr_safe
add: ccorres_updateMDB_const [unfolded const_def])
\<comment> \<open>the post_cap_deletion case\<close>
apply (ctac(no_vcg) add: postCapDeletion_ccorres [unfolded dc_def])
\<comment> \<open>Haskell pre/post for y \<leftarrow> updateMDB slot (\<lambda>a. nullMDBNode);\<close>
apply wp
\<comment> \<open>C pre/post for y \<leftarrow> updateMDB slot (\<lambda>a. nullMDBNode);\<close>
apply simp
\<comment> \<open>C pre/post for the 2nd CALL\<close>
\<comment> \<open>Haskell pre/post for y \<leftarrow> updateCap slot capability.NullCap;\<close>
apply wp
\<comment> \<open>C pre/post for y \<leftarrow> updateCap slot capability.NullCap;\<close>
apply (simp add: Collect_const_mem cmdbnode_relation_def mdb_node_to_H_def nullMDBNode_def false_def)
\<comment> \<open>Haskell pre/post for the two nested updates\<close>
apply wp
\<comment> \<open>C pre/post for the two nested updates\<close>
apply (simp add: Collect_const_mem ccap_relation_NullCap_iff)
\<comment> \<open>Haskell pre/post for (updateMDB (mdbPrev rva) (mdbNext_update (\<lambda>_. mdbNext rva)))\<close>
apply (simp, wp)
\<comment> \<open>C pre/post for (updateMDB (mdbPrev rva) (mdbNext_update (\<lambda>_. mdbNext rva)))\<close>
apply simp+
apply vcg
apply (rule conseqPre, vcg)
apply clarsimp
apply simp
apply (wp hoare_vcg_all_lift hoare_vcg_imp_lift)
\<comment> \<open>final precondition proof\<close>
apply (clarsimp simp: typ_heap_simps Collect_const_mem
cte_wp_at_ctes_of)
apply (rule conjI)
\<comment> \<open>Haskell side\<close>
apply (simp add: is_aligned_3_next canonical_address_mdbNext)
\<comment> \<open>C side\<close>
apply (clarsimp simp: map_comp_Some_iff typ_heap_simps)
apply (subst cap_get_tag_isCap)
apply (rule ccte_relation_ccap_relation)
apply (simp add: ccte_relation_def c_valid_cte_def
cl_valid_cte_def c_valid_cap_def)
apply simp
done
(************************************************************************)
(* *)
(* capSwapForDelete_ccorres *********************************************)
(* *)
(************************************************************************)
lemma ccorres_return_void_C:
"ccorres dc xfdc \<top> UNIV (SKIP # hs) (return rv) (return_void_C)"
apply (rule ccorres_from_vcg_throws)
apply (simp add: return_def)
apply (rule allI, rule conseqPre)
apply vcg
apply simp
done
declare Collect_const [simp del]
lemma capSwapForDelete_ccorres:
"ccorres dc xfdc
(valid_mdb' and pspace_aligned' and pspace_canonical')
(UNIV \<inter> {s. slot1_' s = Ptr slot1}
\<inter> {s. slot2_' s = Ptr slot2})
[]
(capSwapForDelete slot1 slot2)
(Call capSwapForDelete_'proc)"
apply (cinit lift: slot1_' slot2_' simp del: return_bind)
\<comment> \<open>***Main goal***\<close>
\<comment> \<open>--- instruction: when (slot1 \<noteq> slot2) \<dots> / IF Ptr slot1 = Ptr slot2 THEN \<dots>\<close>
apply (simp add:when_def)
apply (rule ccorres_if_cond_throws2 [where Q = \<top> and Q' = \<top>])
apply (case_tac "slot1=slot2", simp+)
apply (rule ccorres_return_void_C [simplified dc_def])
\<comment> \<open>***Main goal***\<close>
\<comment> \<open>--- ccorres goal with 2 affectations (cap1 and cap2) on both on Haskell and C\<close>
\<comment> \<open>--- \<Longrightarrow> execute each part independently\<close>
apply (simp add: liftM_def cong: call_ignore_cong)
apply (rule ccorres_pre_getCTE)+
apply (rule ccorres_move_c_guard_cte, rule ccorres_symb_exec_r)+
\<comment> \<open>***Main goal***\<close>
apply (ctac (no_vcg) add: cteSwap_ccorres [unfolded dc_def] )
\<comment> \<open>C Hoare triple for \<acute>cap2 :== \<dots>\<close>
apply vcg
\<comment> \<open>C existential Hoare triple for \<acute>cap2 :== \<dots>\<close>
apply simp
apply (rule conseqPre)
apply vcg
apply simp
\<comment> \<open>C Hoare triple for \<acute>cap1 :== \<dots>\<close>
apply vcg
\<comment> \<open>C existential Hoare triple for \<acute>cap1 :== \<dots>\<close>
apply simp
apply (rule conseqPre)
apply vcg
apply simp
\<comment> \<open>Hoare triple for return_void\<close>
apply vcg
\<comment> \<open>***Generalized preconditions***\<close>
apply simp
apply (clarsimp simp: cte_wp_at_ctes_of map_comp_Some_iff
typ_heap_simps ccap_relation_def)
apply (simp add: cl_valid_cte_def c_valid_cap_def)
done
declare Collect_const [simp add]
(************************************************************************)
(* *)
(* Arch_sameRegionAs_ccorres ********************************************)
(* *)
(************************************************************************)
lemma cap_get_tag_PageCap_frame:
"ccap_relation cap cap' \<Longrightarrow>
(cap_get_tag cap' = scast cap_frame_cap) =
(cap =
capability.ArchObjectCap
(PageCap (cap_frame_cap_CL.capFBasePtr_CL (cap_frame_cap_lift cap'))
(vmrights_to_H (cap_frame_cap_CL.capFVMRights_CL (cap_frame_cap_lift cap')))
(maptype_to_H (cap_frame_cap_CL.capFMapType_CL (cap_frame_cap_lift cap')))
(framesize_to_H (capFSize_CL (cap_frame_cap_lift cap')))
(to_bool (cap_frame_cap_CL.capFIsDevice_CL (cap_frame_cap_lift cap')))
(if cap_frame_cap_CL.capFMappedASID_CL (cap_frame_cap_lift cap') = 0
then None else
Some ((cap_frame_cap_CL.capFMappedASID_CL (cap_frame_cap_lift cap')),
cap_frame_cap_CL.capFMappedAddress_CL (cap_frame_cap_lift cap')))))"
apply (rule iffI)
apply (erule ccap_relationE)
apply (clarsimp simp add: cap_lifts cap_to_H_def Let_def split: if_split)
apply (simp add: cap_get_tag_isCap isCap_simps pageSize_def)
done
lemma fff_is_pageBits:
"(0xFFF :: machine_word) = 2 ^ pageBits - 1"
by (simp add: pageBits_def)
(* used? *)
lemma valid_cap'_PageCap_is_aligned:
"valid_cap' (ArchObjectCap (arch_capability.PageCap w r mt sz d option)) t \<Longrightarrow>
is_aligned w (pageBitsForSize sz)"
apply (simp add: valid_cap'_def capAligned_def)
done
lemma Arch_sameRegionAs_spec:
notes cap_get_tag = ccap_rel_cap_get_tag_cases_arch'
notes if_cong[cong]
shows
"\<forall>capa capb. \<Gamma> \<turnstile> \<lbrace> ccap_relation (ArchObjectCap capa) \<acute>cap_a \<and>
ccap_relation (ArchObjectCap capb) \<acute>cap_b \<rbrace>
Call Arch_sameRegionAs_'proc
\<lbrace> \<acute>ret__unsigned_long = from_bool (Arch.sameRegionAs capa capb) \<rbrace>"
apply vcg
apply clarsimp
apply (simp add: X64_H.sameRegionAs_def)
subgoal for capa capb cap_b cap_a
apply (cases capa; cases capb;
frule (1) cap_get_tag[where cap'=cap_a]; (frule cap_lifts[where c=cap_a, THEN iffD1])?;
frule (1) cap_get_tag[where cap'=cap_b]; (frule cap_lifts[where c=cap_b, THEN iffD1])?)
apply (simp_all add: cap_tag_defs isCap_simps from_bool_def true_def false_def if_0_1_eq)
apply (all \<open>clarsimp simp: ccap_relation_def cap_to_H_def
c_valid_cap_def cl_valid_cap_def Let_def\<close>)
apply (simp add: cap_io_port_cap_lift_def'[simplified cap_tag_defs] mask_def
ucast_le_ucast_eq[OF and_mask_less' and_mask_less'] split: bool.splits)
apply (intro conjI impI; clarsimp; word_bitwise; auto)
apply (clarsimp simp: cap_frame_cap_lift_def'[simplified cap_tag_defs]
framesize_to_H_def pageBitsForSize_def field_simps
X86_SmallPage_def X86_LargePage_def pageBits_def ptTranslationBits_def
split: vmpage_size.splits if_splits)
done
done
(* combination of cap_get_capSizeBits + cap_get_archCapSizeBits from C *)
definition
get_capSizeBits_CL :: "cap_CL option \<Rightarrow> nat" where
"get_capSizeBits_CL \<equiv> \<lambda>cap. case cap of
Some (Cap_untyped_cap c) \<Rightarrow> unat (cap_untyped_cap_CL.capBlockSize_CL c)
| Some (Cap_endpoint_cap c) \<Rightarrow> epSizeBits
| Some (Cap_notification_cap c) \<Rightarrow> ntfnSizeBits
| Some (Cap_cnode_cap c) \<Rightarrow> unat (capCNodeRadix_CL c) + cteSizeBits
| Some (Cap_thread_cap c) \<Rightarrow> tcbBlockSizeBits
| Some (Cap_frame_cap c) \<Rightarrow> pageBitsForSize (framesize_to_H $ cap_frame_cap_CL.capFSize_CL c)
| Some (Cap_page_table_cap c) \<Rightarrow> 12
| Some (Cap_page_directory_cap c) \<Rightarrow> 12
| Some (Cap_pdpt_cap c) \<Rightarrow> 12
| Some (Cap_pml4_cap c) \<Rightarrow> 12
| Some (Cap_asid_pool_cap c) \<Rightarrow> 12
| Some (Cap_zombie_cap c) \<Rightarrow>
let type = cap_zombie_cap_CL.capZombieType_CL c in
if isZombieTCB_C type
then tcbBlockSizeBits
else unat (type && mask wordRadix) + cteSizeBits
| _ \<Rightarrow> 0"
lemma frame_cap_size [simp]:
"cap_get_tag cap = scast cap_frame_cap
\<Longrightarrow> cap_frame_cap_CL.capFSize_CL (cap_frame_cap_lift cap) && mask 2 =
cap_frame_cap_CL.capFSize_CL (cap_frame_cap_lift cap)"
apply (simp add: cap_frame_cap_lift_def)
by (simp add: cap_lift_def cap_tag_defs)
lemma cap_get_tag_bound:
"cap_get_tag x < 32"
apply (simp add: cap_get_tag_def mask_def)
by word_bitwise
lemma cap_get_tag_scast:
"UCAST(64 \<rightarrow> 32 signed) (cap_get_tag cap) = tag \<longleftrightarrow> cap_get_tag cap = SCAST(32 signed \<rightarrow> 64) tag"
apply (rule iffI; simp add: cap_get_tag_def)
apply (drule sym; simp add: ucast_and_mask scast_eq_ucast msb_nth ucast_ucast_mask mask_twice)
done
lemma cap_get_capSizeBits_spec:
"\<forall>s. \<Gamma> \<turnstile> \<lbrace>s. c_valid_cap (cap_' s)\<rbrace>
\<acute>ret__unsigned_long :== PROC cap_get_capSizeBits(\<acute>cap)
\<lbrace>\<acute>ret__unsigned_long = of_nat (get_capSizeBits_CL (cap_lift \<^bsup>s\<^esup>cap))\<rbrace>"
apply vcg
apply (clarsimp simp: get_capSizeBits_CL_def)
apply (intro conjI impI;
clarsimp simp: cap_lifts
cap_lift_asid_control_cap
cap_lift_irq_control_cap cap_lift_null_cap
Kernel_C.asidLowBits_def asid_low_bits_def
word_sle_def Let_def mask_def
isZombieTCB_C_def ZombieTCB_C_def
cap_lift_domain_cap cap_get_tag_scast
objBits_defs wordRadix_def
c_valid_cap_def cl_valid_cap_def
cong: option.case_cong[cong]
dest!: sym [where t = "ucast (cap_get_tag cap)" for cap])
apply (clarsimp split: option.splits cap_CL.splits dest!: cap_lift_Some_CapD)
done
lemma ccap_relation_get_capSizeBits_physical:
"\<lbrakk> ccap_relation hcap ccap; capClass hcap = PhysicalClass; capAligned hcap \<rbrakk>
\<Longrightarrow> 2 ^ get_capSizeBits_CL (cap_lift ccap) = capUntypedSize hcap"
supply if_cong[cong]
apply (cases hcap;
(match premises in "hcap = ArchObjectCap c" for c \<Rightarrow> \<open>cases c\<close>)?;
(frule (1) ccap_rel_cap_get_tag_cases_generic)?;
(frule (2) ccap_rel_cap_get_tag_cases_arch)?;
(frule cap_lifts[THEN iffD1])?)
apply (all \<open>clarsimp simp: get_capSizeBits_CL_def objBits_simps Let_def X64_H.capUntypedSize_def
asid_low_bits_def\<close>)
(* Zombie, Page, Untyped, CNode caps remain. *)
apply (all \<open>thin_tac \<open>hcap = _\<close>\<close>)
apply (all \<open>rule arg_cong[where f="\<lambda>s. 2 ^ s"]\<close>)
apply (all \<open>simp add: ccap_relation_def cap_lift_defs cap_lift_def cap_tag_defs cap_to_H_def\<close>)
(* Now just Zombie caps *)
apply (clarsimp simp: Let_def objBits_simps' wordRadix_def capAligned_def
word_bits_def word_less_nat_alt
intro!: less_mask_eq
split: if_splits)
done
lemma ccap_relation_get_capSizeBits_untyped:
"\<lbrakk> ccap_relation (UntypedCap d word bits idx) ccap \<rbrakk> \<Longrightarrow>
get_capSizeBits_CL (cap_lift ccap) = bits"
apply (frule cap_get_tag_isCap_unfolded_H_cap)
by (clarsimp simp: get_capSizeBits_CL_def ccap_relation_def
map_option_case cap_to_H_def cap_lift_def cap_tag_defs)
definition
get_capZombieBits_CL :: "cap_zombie_cap_CL \<Rightarrow> machine_word" where
"get_capZombieBits_CL \<equiv> \<lambda>cap.
let type = cap_zombie_cap_CL.capZombieType_CL cap in
if isZombieTCB_C type then 4 else type && mask 6"
lemma get_capSizeBits_valid_shift:
"\<lbrakk> ccap_relation hcap ccap; capAligned hcap \<rbrakk> \<Longrightarrow>
get_capSizeBits_CL (cap_lift ccap) < 64"
apply (cases hcap;
(match premises in "hcap = ArchObjectCap c" for c \<Rightarrow> \<open>cases c\<close>)?;
(frule (1) ccap_rel_cap_get_tag_cases_generic)?;
(frule (2) ccap_rel_cap_get_tag_cases_arch)?;
(frule cap_lifts[THEN iffD1])?)
(* Deal with simple cases quickly. *)
apply (all \<open>clarsimp simp: get_capSizeBits_CL_def objBits_simps' wordRadix_def Let_def
split: option.splits if_splits;
thin_tac \<open>hcap = _\<close>\<close>)
(* Deal with non-physical caps quickly. *)
apply (all \<open>(match conclusion in "case_cap_CL _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ < _" \<Rightarrow>
\<open>clarsimp simp: cap_lift_def cap_tag_defs\<close>)?\<close>)
(* Slow cases: Zombie, Page, Untyped and CNode caps. *)
apply (all \<open>clarsimp simp: cap_lift_def cap_lift_defs cap_tag_defs
ccap_relation_def cap_to_H_def Let_def
capAligned_def objBits_simps' word_bits_def
unat_ucast_less_no_overflow_simp\<close>)
(* Zombie arithmetic. *)
apply (subst less_mask_eq[where n=6]; clarsimp elim!: less_trans)
done
lemma get_capSizeBits_valid_shift_word:
"\<lbrakk> ccap_relation hcap ccap; capAligned hcap \<rbrakk> \<Longrightarrow>
of_nat (get_capSizeBits_CL (cap_lift ccap)) < (0x40::machine_word)"
apply (subgoal_tac "of_nat (get_capSizeBits_CL (cap_lift ccap)) < (of_nat 64::machine_word)", simp)
apply (rule of_nat_mono_maybe, simp+)
apply (simp add: get_capSizeBits_valid_shift)
done
lemma cap_zombie_cap_get_capZombieBits_spec:
"\<forall>s. \<Gamma> \<turnstile> \<lbrace>s. cap_get_tag \<acute>cap = scast cap_zombie_cap \<rbrace>
\<acute>ret__unsigned_long :== PROC cap_zombie_cap_get_capZombieBits(\<acute>cap)
\<lbrace>\<acute>ret__unsigned_long = get_capZombieBits_CL (cap_zombie_cap_lift \<^bsup>s\<^esup>cap)\<rbrace>"
apply vcg
apply (clarsimp simp: get_capZombieBits_CL_def word_sle_def mask_def
isZombieTCB_C_def ZombieTCB_C_def Let_def)
done
definition
get_capZombiePtr_CL :: "cap_zombie_cap_CL \<Rightarrow> machine_word" where
"get_capZombiePtr_CL \<equiv> \<lambda>cap.
let radix = unat (get_capZombieBits_CL cap) in
cap_zombie_cap_CL.capZombieID_CL cap && ~~ (mask (radix+1))"
lemma cap_zombie_cap_get_capZombiePtr_spec:
"\<forall>s. \<Gamma> \<turnstile> \<lbrace>s. cap_get_tag \<acute>cap = scast cap_zombie_cap
\<and> get_capZombieBits_CL (cap_zombie_cap_lift \<acute>cap) < 0x3F \<rbrace>
\<acute>ret__unsigned_long :== PROC cap_zombie_cap_get_capZombiePtr(\<acute>cap)
\<lbrace>\<acute>ret__unsigned_long = get_capZombiePtr_CL (cap_zombie_cap_lift \<^bsup>s\<^esup>cap)\<rbrace>"
apply vcg
apply (clarsimp simp: get_capZombiePtr_CL_def word_sle_def mask_def
isZombieTCB_C_def ZombieTCB_C_def Let_def)
apply (intro conjI)
apply (simp add: word_add_less_mono1[where k=1 and j="0x3F", simplified])
apply (subst unat_plus_if_size)
apply (clarsimp split: if_split)
apply (clarsimp simp: get_capZombieBits_CL_def Let_def word_size
split: if_split if_split_asm)
apply (subgoal_tac "unat (capZombieType_CL (cap_zombie_cap_lift cap) && mask 6)
< unat ((2::machine_word) ^ 6)")
apply (clarsimp simp: shiftl_eq_mult)
apply (rule unat_mono)
apply (rule and_mask_less_size)
apply (clarsimp simp: word_size)
done
definition
get_capPtr_CL :: "cap_CL option \<Rightarrow> unit ptr" where
"get_capPtr_CL \<equiv> \<lambda>cap. Ptr (case cap of
Some (Cap_untyped_cap c) \<Rightarrow> cap_untyped_cap_CL.capPtr_CL c
| Some (Cap_endpoint_cap c) \<Rightarrow> cap_endpoint_cap_CL.capEPPtr_CL c
| Some (Cap_notification_cap c) \<Rightarrow> cap_notification_cap_CL.capNtfnPtr_CL c
| Some (Cap_cnode_cap c) \<Rightarrow> cap_cnode_cap_CL.capCNodePtr_CL c
| Some (Cap_thread_cap c) \<Rightarrow> (cap_thread_cap_CL.capTCBPtr_CL c && ~~ mask (objBits (undefined :: tcb)))
| Some (Cap_frame_cap c) \<Rightarrow> cap_frame_cap_CL.capFBasePtr_CL c
| Some (Cap_page_table_cap c) \<Rightarrow> cap_page_table_cap_CL.capPTBasePtr_CL c
| Some (Cap_page_directory_cap c) \<Rightarrow> cap_page_directory_cap_CL.capPDBasePtr_CL c
| Some (Cap_pdpt_cap c) \<Rightarrow> cap_pdpt_cap_CL.capPDPTBasePtr_CL c
| Some (Cap_pml4_cap c) \<Rightarrow> cap_pml4_cap_CL.capPML4BasePtr_CL c
| Some (Cap_asid_pool_cap c) \<Rightarrow> cap_asid_pool_cap_CL.capASIDPool_CL c
| Some (Cap_zombie_cap c) \<Rightarrow> get_capZombiePtr_CL c
| _ \<Rightarrow> 0)"
lemma cap_get_capPtr_spec:
"\<forall>s. \<Gamma> \<turnstile> \<lbrace>s. (cap_get_tag \<acute>cap = scast cap_zombie_cap
\<longrightarrow> get_capZombieBits_CL (cap_zombie_cap_lift \<acute>cap) < 0x3F)\<rbrace>
\<acute>ret__ptr_to_void :== PROC cap_get_capPtr(\<acute>cap)
\<lbrace>\<acute>ret__ptr_to_void = get_capPtr_CL (cap_lift \<^bsup>s\<^esup>cap)\<rbrace>"
apply vcg
apply (clarsimp simp: get_capPtr_CL_def)
apply (intro impI conjI)
apply (clarsimp simp: cap_lifts pageBitsForSize_def
cap_lift_asid_control_cap word_sle_def
cap_lift_irq_control_cap cap_lift_null_cap
mask_def objBits_simps' cap_lift_domain_cap
ptr_add_assertion_positive cap_get_tag_scast
dest!: sym [where t = "ucast (cap_get_tag cap)" for cap]
split: vmpage_size.splits)+
(* XXX: slow. there should be a rule for this *)
by (case_tac "cap_lift cap", simp_all, case_tac "a",
auto simp: cap_lift_def cap_lift_defs cap_tag_defs Let_def
split: if_split_asm)
definition get_capIsPhysical_CL :: "cap_CL option \<Rightarrow> bool"
where
"get_capIsPhysical_CL \<equiv> \<lambda>cap. (case cap of
Some (Cap_untyped_cap c) \<Rightarrow> True
| Some (Cap_endpoint_cap c) \<Rightarrow> True
| Some (Cap_notification_cap c) \<Rightarrow> True
| Some (Cap_cnode_cap c) \<Rightarrow> True
| Some (Cap_thread_cap c) \<Rightarrow> True
| Some (Cap_frame_cap c) \<Rightarrow> True
| Some (Cap_page_table_cap c) \<Rightarrow> True
| Some (Cap_page_directory_cap c) \<Rightarrow> True
| Some (Cap_pdpt_cap c) \<Rightarrow> True
| Some (Cap_pml4_cap c) \<Rightarrow> True
| Some (Cap_asid_pool_cap c) \<Rightarrow> True
| Some (Cap_zombie_cap c) \<Rightarrow> True
| _ \<Rightarrow> False)"
lemma cap_get_capIsPhysical_spec:
"\<forall>s. \<Gamma> \<turnstile> {s}
Call cap_get_capIsPhysical_'proc
\<lbrace>\<acute>ret__unsigned_long = from_bool (get_capIsPhysical_CL (cap_lift \<^bsup>s\<^esup>cap))\<rbrace>"
apply vcg
apply (clarsimp simp: get_capIsPhysical_CL_def)
apply (intro impI conjI)
apply (clarsimp simp: cap_lifts pageBitsForSize_def
cap_lift_asid_control_cap word_sle_def
cap_lift_irq_control_cap cap_lift_null_cap
mask_def objBits_simps cap_lift_domain_cap
ptr_add_assertion_positive from_bool_def
true_def false_def cap_get_tag_scast
dest!: sym [where t = "ucast (cap_get_tag cap)" for cap]
split: vmpage_size.splits)+
(* XXX: slow. there should be a rule for this *)
by (case_tac "cap_lift cap", simp_all, case_tac a,
auto simp: cap_lift_def cap_lift_defs cap_tag_defs Let_def
split: if_split_asm)
lemma ccap_relation_get_capPtr_not_physical:
"\<lbrakk> ccap_relation hcap ccap; capClass hcap \<noteq> PhysicalClass \<rbrakk> \<Longrightarrow>
get_capPtr_CL (cap_lift ccap) = Ptr 0"
by (clarsimp simp: ccap_relation_def get_capPtr_CL_def cap_to_H_def Let_def
split: option.split cap_CL.split_asm if_split_asm)
lemma ccap_relation_get_capIsPhysical:
"ccap_relation hcap ccap \<Longrightarrow> isPhysicalCap hcap = get_capIsPhysical_CL (cap_lift ccap)"
apply (case_tac hcap; clarsimp simp: cap_lifts cap_lift_domain_cap cap_lift_null_cap
cap_lift_irq_control_cap cap_to_H_def
get_capIsPhysical_CL_def
dest!: cap_get_tag_isCap_unfolded_H_cap)
apply (rename_tac arch_cap)
apply (case_tac arch_cap; clarsimp simp: cap_lifts cap_lift_asid_control_cap cap_lift_io_port_control_cap
dest!: cap_get_tag_isCap_unfolded_H_cap)
done
lemma ctcb_ptr_to_tcb_ptr_mask':
"is_aligned (ctcb_ptr_to_tcb_ptr (tcb_Ptr x)) (objBits (undefined :: tcb)) \<Longrightarrow>
ctcb_ptr_to_tcb_ptr (tcb_Ptr x) = x && ~~ mask (objBits (undefined :: tcb))"
apply (simp add: ctcb_ptr_to_tcb_ptr_def)
apply (drule_tac d=ctcb_offset in is_aligned_add_helper)
apply (simp add: objBits_simps' ctcb_offset_defs)
apply simp
done
lemmas ctcb_ptr_to_tcb_ptr_mask
= ctcb_ptr_to_tcb_ptr_mask'[simplified objBits_simps, simplified]
lemma ccap_relation_get_capPtr_physical:
"\<lbrakk> ccap_relation hcap ccap; capClass hcap = PhysicalClass; capAligned hcap \<rbrakk> \<Longrightarrow>
get_capPtr_CL (cap_lift ccap)
= Ptr (capUntypedPtr hcap)"
apply (cases hcap;
(match premises in "hcap = ArchObjectCap c" for c \<Rightarrow> \<open>cases c\<close>)?;
(frule (1) ccap_rel_cap_get_tag_cases_generic)?;
(frule (2) ccap_rel_cap_get_tag_cases_arch)?;
(frule cap_lifts[THEN iffD1])?)
apply (all \<open>clarsimp simp: get_capPtr_CL_def get_capZombiePtr_CL_def get_capZombieBits_CL_def
objBits_simps ccap_relation_def cap_to_H_def Let_def capAligned_def
ctcb_ptr_to_tcb_ptr_mask
split: if_splits;
thin_tac \<open>hcap = _\<close>\<close>)
apply (rule arg_cong[OF less_mask_eq])
apply (clarsimp simp: cap_lift_def cap_lift_defs Let_def cap_tag_defs word_less_nat_alt
word_bits_conv)
done
lemma ccap_relation_get_capPtr_untyped:
"\<lbrakk> ccap_relation (UntypedCap d word bits idx) ccap \<rbrakk> \<Longrightarrow>
get_capPtr_CL (cap_lift ccap) = Ptr word"
apply (frule cap_get_tag_isCap_unfolded_H_cap)
by (clarsimp simp: get_capPtr_CL_def ccap_relation_def
map_option_case cap_to_H_def cap_lift_def cap_tag_defs)
lemma cap_get_tag_isArchCap_unfolded_H_cap:
"ccap_relation (capability.ArchObjectCap a_cap) cap' \<Longrightarrow>
(isArchCap_tag (cap_get_tag cap'))"
apply (frule cap_get_tag_isCap(11), simp)
done
lemmas ccap_rel_cap_get_tag_cases_generic' =
ccap_rel_cap_get_tag_cases_generic
cap_get_tag_isArchCap_unfolded_H_cap[OF back_subst[of "\<lambda>cap. ccap_relation cap cap'" for cap']]
lemma sameRegionAs_spec:
notes cap_get_tag = ccap_rel_cap_get_tag_cases_generic'
shows
"\<forall>capa capb. \<Gamma> \<turnstile> \<lbrace>ccap_relation capa \<acute>cap_a \<and> ccap_relation capb \<acute>cap_b \<and> capAligned capb\<rbrace>
Call sameRegionAs_'proc
\<lbrace> \<acute>ret__unsigned_long = from_bool (sameRegionAs capa capb) \<rbrace>"
apply vcg
apply clarsimp
apply (simp add: sameRegionAs_def isArchCap_tag_def2 ccap_relation_c_valid_cap)
apply (case_tac capa, simp_all add: cap_get_tag_isCap_unfolded_H_cap isCap_simps)
\<comment> \<open>capa is a ThreadCap\<close>
apply (case_tac capb, simp_all add: cap_get_tag_isCap_unfolded_H_cap
isCap_simps cap_tag_defs from_bool_def false_def)[1]
apply (frule_tac cap'=cap_a in cap_get_tag_isCap_unfolded_H_cap(1))
apply (frule_tac cap'=cap_b in cap_get_tag_isCap_unfolded_H_cap(1))
apply (simp add: ccap_relation_def map_option_case)
apply (simp add: cap_thread_cap_lift)
apply (simp add: cap_to_H_def)
apply (clarsimp simp: case_bool_If ctcb_ptr_to_tcb_ptr_def if_distrib
cong: if_cong)
apply (frule_tac cap'=cap_b in cap_get_tag_isArchCap_unfolded_H_cap)
apply (clarsimp simp: isArchCap_tag_def2)
\<comment> \<open>capa is a NullCap\<close>
apply (simp add: cap_tag_defs from_bool_def false_def)
\<comment> \<open>capa is an NotificationCap\<close>
apply (case_tac capb, simp_all add: cap_get_tag_isCap_unfolded_H_cap
isCap_simps cap_tag_defs from_bool_def false_def)[1]
apply (frule_tac cap'=cap_a in cap_get_tag_isCap_unfolded_H_cap(3))
apply (frule_tac cap'=cap_b in cap_get_tag_isCap_unfolded_H_cap(3))
apply (simp add: ccap_relation_def map_option_case)
apply (simp add: cap_notification_cap_lift)
apply (simp add: cap_to_H_def)
apply (clarsimp split: if_split)
apply (frule_tac cap'=cap_b in cap_get_tag_isArchCap_unfolded_H_cap)
apply (clarsimp simp: isArchCap_tag_def2)
\<comment> \<open>capa is an IRQHandlerCap\<close>
apply (case_tac capb, simp_all add: cap_get_tag_isCap_unfolded_H_cap
isCap_simps cap_tag_defs from_bool_def false_def)[1]
apply (frule_tac cap'=cap_a in cap_get_tag_isCap_unfolded_H_cap(5))
apply (frule_tac cap'=cap_b in cap_get_tag_isCap_unfolded_H_cap(5))
apply (simp add: ccap_relation_def map_option_case)
apply (simp add: cap_irq_handler_cap_lift)
apply (simp add: cap_to_H_def)
apply (clarsimp simp: up_ucast_inj_eq c_valid_cap_def ucast_eq_mask
cl_valid_cap_def mask_twice
split: if_split bool.split
| intro impI conjI
| simp)
apply (frule_tac cap'=cap_b in cap_get_tag_isArchCap_unfolded_H_cap)
apply (clarsimp simp: isArchCap_tag_def2)
\<comment> \<open>capa is an EndpointCap\<close>
apply (case_tac capb, simp_all add: cap_get_tag_isCap_unfolded_H_cap
isCap_simps cap_tag_defs from_bool_def false_def)[1]
apply (frule_tac cap'=cap_a in cap_get_tag_isCap_unfolded_H_cap(4))
apply (frule_tac cap'=cap_b in cap_get_tag_isCap_unfolded_H_cap(4))
apply (simp add: ccap_relation_def map_option_case)
apply (simp add: cap_endpoint_cap_lift)
apply (simp add: cap_to_H_def)
apply (clarsimp split: if_split)
apply (frule_tac cap'=cap_b in cap_get_tag_isArchCap_unfolded_H_cap)
apply (clarsimp simp: isArchCap_tag_def2)
\<comment> \<open>capa is a DomainCap\<close>
apply (case_tac capb, simp_all add: cap_get_tag_isCap_unfolded_H_cap
isCap_simps cap_tag_defs from_bool_def false_def true_def)[1]
apply (frule_tac cap'=cap_b in cap_get_tag_isArchCap_unfolded_H_cap)
apply (fastforce simp: isArchCap_tag_def2 split: if_split)
\<comment> \<open>capa is a Zombie\<close>
apply (simp add: cap_tag_defs from_bool_def false_def)
\<comment> \<open>capa is an Arch object cap\<close>
apply (frule_tac cap'=cap_a in cap_get_tag_isArchCap_unfolded_H_cap)
apply (clarsimp simp: isArchCap_tag_def2 cap_tag_defs linorder_not_less [THEN sym])
apply (rule conjI, clarsimp, rule impI)+
apply (case_tac capb, simp_all add: cap_get_tag_isCap_unfolded_H_cap
isCap_simps cap_tag_defs from_bool_def false_def)[1]
\<comment> \<open>capb is an Arch object cap\<close>
apply (frule_tac cap'=cap_b in cap_get_tag_isArchCap_unfolded_H_cap)
apply (fastforce simp: isArchCap_tag_def2 cap_tag_defs linorder_not_less [THEN sym])
\<comment> \<open>capa is a ReplyCap\<close>
apply (case_tac capb, simp_all add: cap_get_tag_isCap_unfolded_H_cap
isCap_simps cap_tag_defs from_bool_def false_def)[1]
apply (frule_tac cap'=cap_b in cap_get_tag_isArchCap_unfolded_H_cap)
apply (clarsimp simp: isArchCap_tag_def2)
apply (frule_tac cap'=cap_a in cap_get_tag_isCap_unfolded_H_cap(8))
apply (frule_tac cap'=cap_b in cap_get_tag_isCap_unfolded_H_cap(8))
apply (simp add: ccap_relation_def map_option_case)
apply (simp add: cap_reply_cap_lift)
apply (simp add: cap_to_H_def ctcb_ptr_to_tcb_ptr_def)
apply (clarsimp split: if_split)
\<comment> \<open>capa is an UntypedCap\<close>
apply (frule_tac cap'=cap_a in cap_get_tag_isCap_unfolded_H_cap(9))
apply (intro conjI)
apply (rule impI, intro conjI)
apply (rule impI, drule(1) cap_get_tag_to_H)+
apply (clarsimp simp: capAligned_def word_bits_conv
objBits_simps' get_capZombieBits_CL_def
Let_def word_less_nat_alt
less_mask_eq true_def
split: if_split_asm)
apply (subgoal_tac "capBlockSize_CL (cap_untyped_cap_lift cap_a) \<le> 0x3F")
apply (simp add: word_le_make_less)
apply (simp add: cap_untyped_cap_lift_def cap_lift_def
cap_tag_defs word_and_le1 mask_def)
apply (clarsimp simp: get_capSizeBits_valid_shift_word)
apply (clarsimp simp: from_bool_def Let_def split: if_split bool.splits)
apply (subst unat_of_nat64,
clarsimp simp: unat_of_nat64 word_bits_def
dest!: get_capSizeBits_valid_shift)+
apply (clarsimp simp: ccap_relation_get_capPtr_physical
ccap_relation_get_capPtr_untyped
ccap_relation_get_capIsPhysical[symmetric]
ccap_relation_get_capSizeBits_physical
ccap_relation_get_capSizeBits_untyped)
apply (intro conjI impI)
apply ((clarsimp simp: ccap_relation_def map_option_case
cap_untyped_cap_lift cap_to_H_def
field_simps valid_cap'_def)+)[4]
apply (rule impI, simp add: from_bool_0 ccap_relation_get_capIsPhysical[symmetric])
apply (simp add: from_bool_def false_def)
\<comment> \<open>capa is a CNodeCap\<close>
apply (case_tac capb, simp_all add: cap_get_tag_isCap_unfolded_H_cap
isCap_simps cap_tag_defs from_bool_def false_def)[1]
apply (frule_tac cap'=cap_b in cap_get_tag_isArchCap_unfolded_H_cap)
apply (clarsimp simp: isArchCap_tag_def2)
apply (frule_tac cap'=cap_a in cap_get_tag_isCap_unfolded_H_cap(10))
apply (frule_tac cap'=cap_b in cap_get_tag_isCap_unfolded_H_cap(10))
apply (simp add: ccap_relation_def map_option_case)
apply (simp add: cap_cnode_cap_lift)
apply (simp add: cap_to_H_def)
apply (clarsimp split: if_split bool.split)
\<comment> \<open>capa is an IRQControlCap\<close>
apply (case_tac capb, simp_all add: cap_get_tag_isCap_unfolded_H_cap
isCap_simps cap_tag_defs from_bool_def false_def true_def)[1]
apply (frule_tac cap'=cap_b in cap_get_tag_isArchCap_unfolded_H_cap)
apply (fastforce simp: isArchCap_tag_def2 split: if_split)
done
lemma framesize_to_H_eq:
"\<lbrakk> a \<le> 2; b \<le> 2 \<rbrakk> \<Longrightarrow>
(framesize_to_H a = framesize_to_H b) = (a = b)"
by (fastforce simp: framesize_to_H_def Kernel_C.X86_SmallPage_def
Kernel_C.X86_LargePage_def Kernel_C.X64_HugePage_def
word_le_make_less
split: if_split
dest: word_less_cases)
lemma capFSize_range:
"\<And>cap. cap_get_tag cap = scast cap_frame_cap \<Longrightarrow> c_valid_cap cap \<Longrightarrow>
capFSize_CL (cap_frame_cap_lift cap) \<le> 2"
apply (simp add: cap_frame_cap_lift_def c_valid_cap_def cl_valid_cap_def cong: option.case_cong)
apply (clarsimp simp: cap_frame_cap_lift)
apply (drule word_less_sub_1, simp)
done
lemma ccap_relation_PageCap_BasePtr:
"ccap_relation (ArchObjectCap (PageCap p r t s d m)) ccap
\<Longrightarrow> capFBasePtr_CL (cap_frame_cap_lift ccap) = p"
apply (frule cap_get_tag_isCap_unfolded_H_cap)
by (clarsimp simp: ccap_relation_def cap_to_H_def cap_lift_def cap_lift_defs cap_tag_defs
Let_def)
lemma ccap_relation_PageCap_IsDevice:
"ccap_relation (ArchObjectCap (PageCap p r t s d m)) ccap
\<Longrightarrow> capFIsDevice_CL (cap_frame_cap_lift ccap) = (if d then 1 else 0)"
apply (frule cap_get_tag_isCap_unfolded_H_cap)
apply (clarsimp simp: ccap_relation_def cap_to_H_def cap_lift_def cap_lift_defs cap_tag_defs
Let_def)
apply (thin_tac _)+
by (clarsimp simp: to_bool_def mask_def word_and_1 split: if_splits)
lemma ccap_relation_PageCap_Size:
"ccap_relation (ArchObjectCap (PageCap p r t s d m)) ccap
\<Longrightarrow> capFSize_CL (cap_frame_cap_lift ccap) = framesize_from_H s"
apply (frule cap_get_tag_isCap_unfolded_H_cap)
apply (clarsimp simp: ccap_relation_def cap_to_H_def cap_lift_def cap_lift_defs cap_tag_defs
Let_def c_valid_cap_def cl_valid_cap_def)
apply (thin_tac "p = _", thin_tac "r = _", thin_tac "t = _", thin_tac "d = _", thin_tac "m = _")
apply (cases s; clarsimp simp: framesize_to_H_def framesize_from_H_def
X86_SmallPage_def X86_LargePage_def X64_HugePage_def
split: if_splits cong: conj_cong)
apply (word_bitwise, simp)
done
lemma ccap_relation_PageCap_MappedASID:
"ccap_relation (ArchObjectCap (PageCap p r t s d (Some (a, b)))) ccap
\<Longrightarrow> capFMappedASID_CL (cap_frame_cap_lift ccap) = a"
apply (frule cap_get_tag_isCap_unfolded_H_cap)
apply (frule cap_get_tag_PageCap_frame)
apply (clarsimp split: if_split_asm)
done
lemma ccap_relation_PageCap_MappedAddress:
"ccap_relation (ArchObjectCap (PageCap p r t s d (Some (a, b)))) ccap
\<Longrightarrow> capFMappedAddress_CL (cap_frame_cap_lift ccap) = b"
apply (frule cap_get_tag_isCap_unfolded_H_cap)
apply (frule cap_get_tag_PageCap_frame)
apply (clarsimp split: if_split_asm)
done
lemmas ccap_relation_PageCap_fields =
ccap_relation_PageCap_BasePtr ccap_relation_PageCap_IsDevice ccap_relation_PageCap_Size
lemma case_bool_of_nat_eq:
defines "cases_of c \<equiv> case c of True \<Rightarrow> of_nat 1 | False \<Rightarrow> of_nat 0"
shows "(cases_of c = 0) = (\<not> c)"
"(cases_of c = 1) = c"
"(cases_of c = cases_of d) = (c = d)"
by (cases c; simp add: cases_of_def; cases d; simp)+
lemma Arch_sameObjectAs_spec:
"\<forall>capa capb. \<Gamma> \<turnstile> \<lbrace>ccap_relation (ArchObjectCap capa) \<acute>cap_a \<and>
ccap_relation (ArchObjectCap capb) \<acute>cap_b \<and>
capAligned (ArchObjectCap capa) \<and>
capAligned (ArchObjectCap capb) \<rbrace>
Call Arch_sameObjectAs_'proc
\<lbrace> \<acute>ret__unsigned_long = from_bool (Arch.sameObjectAs capa capb) \<rbrace>"
proof -
note cap_get_tag = ccap_rel_cap_get_tag_cases_arch'
note case_bool_of_nat_eq[simp]
have [simp]: "(\<forall>d. d) = False" "(\<forall>d. \<not>d) = False" by auto
show ?thesis
apply vcg
apply (clarsimp simp: X64_H.sameObjectAs_def)
subgoal for capa capb cap_b cap_a
apply (cases capa)
apply (all \<open>frule (1) cap_get_tag[where cap'=cap_a]\<close>)
apply (all \<open>(frule cap_lifts[where c=cap_a, THEN iffD1])?\<close>)
apply (all \<open>clarsimp simp: cap_tag_defs isCap_simps from_bool_def true_def false_def if_0_1_eq
split: if_splits\<close>)
apply (all \<open>fastforce?\<close>)
(* IO ports and frames remain. *)
apply (all \<open>cases capb\<close>)
apply (all \<open>frule (1) cap_get_tag[where cap'=cap_b]\<close>)
apply (all \<open>(frule cap_lifts[where c=cap_b, THEN iffD1])?\<close>)
apply (all \<open>clarsimp simp: cap_tag_defs isCap_simps from_bool_def true_def false_def if_0_1_eq
ccap_relation_PageCap_fields framesize_from_H_eq capAligned_def
split: if_splits\<close>)
apply (all \<open>(fastforce simp: X64_H.sameRegionAs_def isCap_simps)?\<close>)
done
done
qed
lemma sameObjectAs_spec:
"\<forall>capa capb. \<Gamma> \<turnstile> \<lbrace>ccap_relation capa \<acute>cap_a \<and>
ccap_relation capb \<acute>cap_b \<and>
capAligned capa \<and> capAligned capb \<and> (\<exists>s. s \<turnstile>' capa)\<rbrace>
Call sameObjectAs_'proc
\<lbrace> \<acute>ret__unsigned_long = from_bool (sameObjectAs capa capb) \<rbrace>"
apply vcg
apply (clarsimp simp: sameObjectAs_def isArchCap_tag_def2)
apply (case_tac capa, simp_all add: cap_get_tag_isCap_unfolded_H_cap
isCap_simps cap_tag_defs
from_bool_def false_def)
apply fastforce+
\<comment> \<open>capa is an arch cap\<close>
apply (frule cap_get_tag_isArchCap_unfolded_H_cap)
apply (simp add: isArchCap_tag_def2)
apply (rule conjI, rule impI, clarsimp, rule impI)+
apply (case_tac capb, simp_all add: cap_get_tag_isCap_unfolded_H_cap
isCap_simps cap_tag_defs)[1]
apply ((fastforce)+)[7]
\<comment> \<open>capb is an arch cap\<close>
apply (frule_tac cap'=cap_b in cap_get_tag_isArchCap_unfolded_H_cap)
apply (fastforce simp: isArchCap_tag_def2 linorder_not_less [symmetric])+
\<comment> \<open>capa is an irq handler cap\<close>
apply (case_tac capb, simp_all add: cap_get_tag_isCap_unfolded_H_cap
isCap_simps cap_tag_defs)
apply fastforce+
\<comment> \<open>capb is an arch cap\<close>
apply (frule cap_get_tag_isArchCap_unfolded_H_cap)
apply (fastforce simp: isArchCap_tag_def2)+
done
lemma sameRegionAs_EndpointCap:
shows "\<lbrakk>ccap_relation capa capc;
RetypeDecls_H.sameRegionAs (capability.EndpointCap p b cs cr cg cgr) capa\<rbrakk>
\<Longrightarrow> cap_get_tag capc = scast cap_endpoint_cap"
apply (simp add: sameRegionAs_def Let_def)
apply (case_tac capa;
simp add: isUntypedCap_def isEndpointCap_def isNotificationCap_def
isCNodeCap_def isThreadCap_def isReplyCap_def isIRQControlCap_def
isIRQHandlerCap_def isArchObjectCap_def)
apply (clarsimp simp: ccap_relation_def map_option_case)
apply (case_tac "cap_lift capc"; simp)
apply (simp add: cap_to_H_def)
apply (case_tac a; simp)
apply (simp add:cap_endpoint_cap_lift cap_endpoint_cap_lift_def)
apply (rename_tac zombie_cap)
apply (case_tac "isZombieTCB_C (capZombieType_CL zombie_cap)"; simp add: Let_def)
done
lemma sameRegionAs_NotificationCap:
shows "\<lbrakk>ccap_relation capa capc;
RetypeDecls_H.sameRegionAs
(capability.NotificationCap x y z u ) capa\<rbrakk>
\<Longrightarrow> cap_get_tag capc = scast cap_notification_cap"
apply (simp add: sameRegionAs_def Let_def)
apply (case_tac capa;
simp add: isUntypedCap_def isEndpointCap_def isNotificationCap_def
isCNodeCap_def isThreadCap_def isReplyCap_def isIRQControlCap_def
isIRQHandlerCap_def isArchObjectCap_def)
apply (clarsimp simp: ccap_relation_def map_option_case)
apply (case_tac "cap_lift capc"; simp)
apply (simp add: cap_to_H_def)
apply (case_tac a; simp)
apply (simp add: cap_notification_cap_lift cap_notification_cap_lift_def)
apply (rename_tac zombie_cap)
apply (case_tac "isZombieTCB_C (capZombieType_CL zombie_cap)"; simp add: Let_def)
done
lemma isMDBParentOf_spec:
notes option.case_cong_weak[cong] if_cong[cong]
shows "\<forall>ctea cte_a cteb cte_b.
\<Gamma> \<turnstile> {s. cslift s (cte_a_' s) = Some cte_a \<and>
ccte_relation ctea cte_a \<and>
cslift s (cte_b_' s) = Some cte_b \<and>
ccte_relation cteb cte_b \<and>
capAligned (cteCap cteb) \<and>
(\<exists>s. s \<turnstile>' (cteCap ctea)) }
Call isMDBParentOf_'proc
\<lbrace> \<acute>ret__unsigned_long = from_bool (isMDBParentOf ctea cteb) \<rbrace>"
apply (intro allI, rule conseqPre)
apply vcg
apply (clarsimp simp: isMDBParentOf_def)
apply (frule_tac cte=ctea in ccte_relation_ccap_relation)
apply (frule_tac cte=cteb in ccte_relation_ccap_relation)
apply (rule conjI, clarsimp simp: typ_heap_simps dest!: lift_t_g)
apply (intro conjI impI)
apply (simp add: ccte_relation_def map_option_case)
apply (simp add: cte_lift_def)
apply (clarsimp simp: cte_to_H_def mdb_node_to_H_def split: option.split_asm)
apply (clarsimp simp: Let_def false_def from_bool_def to_bool_def
split: if_split bool.splits)
apply ((clarsimp simp: typ_heap_simps dest!: lift_t_g)+)[3]
apply (rule_tac x="cteCap ctea" in exI, rule conjI)
apply (clarsimp simp: ccte_relation_ccap_relation typ_heap_simps
dest!: lift_t_g)
apply (rule_tac x="cteCap cteb" in exI, rule conjI)
apply (clarsimp simp: ccte_relation_ccap_relation typ_heap_simps
dest!: lift_t_g)
apply (clarsimp simp: ccte_relation_def map_option_case)
apply (simp add: cte_lift_def)
apply (clarsimp simp: cte_to_H_def mdb_node_to_H_def
split: option.split_asm)
apply (rule conjI)
\<comment> \<open>sameRegionAs = 0\<close>
apply (rule impI)
apply (clarsimp simp: from_bool_def false_def
split: if_split bool.splits)
\<comment> \<open>sameRegionAs \<noteq> 0\<close>
apply (clarsimp simp: from_bool_def false_def)
apply (clarsimp cong:bool.case_cong if_cong simp: typ_heap_simps)
apply (rule conjI)
\<comment> \<open>cap_get_tag of cte_a is an endpoint\<close>
apply clarsimp
apply (frule cap_get_tag_EndpointCap)
apply simp
apply (clarsimp simp: to_bool_def isNotificationCap_def isEndpointCap_def true_def) \<comment> \<open>badge of A is not 0 now\<close>
apply (subgoal_tac "cap_get_tag (cte_C.cap_C cte_b) = scast cap_endpoint_cap") \<comment> \<open>needed also after\<close>
prefer 2
apply (rule sameRegionAs_EndpointCap, assumption+)
apply (clarsimp simp: typ_heap_simps' Let_def case_bool_If)
apply (frule_tac cap="(cap_to_H x2c)" in cap_get_tag_EndpointCap)
apply (clarsimp split: if_split_asm simp: if_distrib [where f=scast])
apply (clarsimp, rule conjI)
\<comment> \<open>cap_get_tag of cte_a is an notification\<close>
apply clarsimp
apply (frule cap_get_tag_NotificationCap)
apply simp
apply (clarsimp simp: to_bool_def isNotificationCap_def isEndpointCap_def true_def) \<comment> \<open>badge of A is not 0 now\<close>
apply (subgoal_tac "cap_get_tag (cte_C.cap_C cte_b) = scast cap_notification_cap") \<comment> \<open>needed also after\<close>
prefer 2
apply (rule sameRegionAs_NotificationCap, assumption+)
apply (rule conjI, simp)
apply clarsimp
apply (simp add: Let_def case_bool_If)
apply (frule_tac cap="(cap_to_H x2c)" in cap_get_tag_NotificationCap)
apply clarsimp
\<comment> \<open>main goal\<close>
apply clarsimp
apply (simp add: to_bool_def)
apply (subgoal_tac "(\<not> (isEndpointCap (cap_to_H x2b))) \<and> ( \<not> (isNotificationCap (cap_to_H x2b)))")
apply (clarsimp simp: true_def)
apply (clarsimp simp: cap_get_tag_isCap [symmetric])
done
lemma updateCapData_spec:
"\<forall>cap. \<Gamma> \<turnstile> \<lbrace> ccap_relation cap \<acute>cap \<and> preserve = to_bool (\<acute>preserve) \<and> newData = \<acute>newData\<rbrace>
Call updateCapData_'proc
\<lbrace> ccap_relation (updateCapData preserve newData cap) \<acute>ret__struct_cap_C \<rbrace>"
supply if_cong[cong]
apply (rule allI, rule conseqPre)
apply vcg
apply (clarsimp)
apply (simp add: updateCapData_def)
apply (case_tac cap, simp_all add: cap_get_tag_isCap_unfolded_H_cap
isCap_simps from_bool_def isArchCap_tag_def2 cap_tag_defs Let_def)
\<comment> \<open>NotificationCap\<close>
apply clarsimp
apply (frule cap_get_tag_isCap_unfolded_H_cap(3))
apply (frule (1) iffD1[OF cap_get_tag_NotificationCap])
apply clarsimp
apply (intro conjI impI)
\<comment> \<open>preserve is zero and capNtfnBadge_CL \<dots> = 0\<close>
apply clarsimp
apply (clarsimp simp:cap_notification_cap_lift_def cap_lift_def cap_tag_defs)
apply (simp add: ccap_relation_def cap_lift_def cap_tag_defs cap_to_H_def)
\<comment> \<open>preserve is zero and capNtfnBadge_CL \<dots> \<noteq> 0\<close>
apply clarsimp
apply (simp add: ccap_relation_NullCap_iff cap_tag_defs)
\<comment> \<open>preserve is not zero\<close>
apply clarsimp
apply (simp add: to_bool_def)
apply (case_tac "preserve_' x = 0 \<and> capNtfnBadge_CL (cap_notification_cap_lift (cap_' x))= 0",
clarsimp)
apply (simp add: if_not_P)
apply (simp add: ccap_relation_NullCap_iff cap_tag_defs)
\<comment> \<open>EndpointCap\<close>
apply clarsimp
apply (frule cap_get_tag_isCap_unfolded_H_cap(4))
apply (frule (1) iffD1[OF cap_get_tag_EndpointCap])
apply clarsimp
apply (intro impI conjI)
\<comment> \<open>preserve is zero and capNtfnBadge_CL \<dots> = 0\<close>
apply clarsimp
apply (clarsimp simp:cap_endpoint_cap_lift_def cap_lift_def cap_tag_defs)
apply (simp add: ccap_relation_def cap_lift_def cap_tag_defs cap_to_H_def)
\<comment> \<open>preserve is zero and capNtfnBadge_CL \<dots> \<noteq> 0\<close>
apply clarsimp
apply (simp add: ccap_relation_NullCap_iff cap_tag_defs)
\<comment> \<open>preserve is not zero\<close>
apply clarsimp
apply (simp add: to_bool_def)
apply (case_tac "preserve_' x = 0 \<and> capEPBadge_CL (cap_endpoint_cap_lift (cap_' x))= 0", clarsimp)
apply (simp add: if_not_P)
apply (simp add: ccap_relation_NullCap_iff cap_tag_defs)
\<comment> \<open>ArchObjectCap\<close>
apply clarsimp
apply (frule cap_get_tag_isArchCap_unfolded_H_cap)
apply (simp add: isArchCap_tag_def2)
apply (simp add: X64_H.updateCapData_def)
\<comment> \<open>CNodeCap\<close>
apply (clarsimp simp: cteRightsBits_def cteGuardBits_def)
apply (frule cap_get_tag_isCap_unfolded_H_cap(10))
apply (frule (1) iffD1[OF cap_get_tag_CNodeCap])
apply clarsimp
apply (thin_tac "ccap_relation x y" for x y)
apply (thin_tac "ret__unsigned_long_' t = v" for t v)+
apply (simp add: seL4_CNode_CapData_lift_def fupdate_def word_size word_less_nat_alt mask_def
cong: if_cong)
apply (simp only: unat_word_ariths(1))
apply (rule ssubst [OF nat_mod_eq' [where n = "2 ^ len_of TYPE(64)"]])
\<comment> \<open>unat (\<dots> && 0x3F) + unat (\<dots> mod 0x40) < 2 ^ len_of TYPE(64)\<close>
apply (rule order_le_less_trans, rule add_le_mono)
apply (rule word_le_nat_alt[THEN iffD1])
apply (rule word_and_le1)
apply (simp add: cap_cnode_cap_lift_def cap_lift_cnode_cap)
apply (rule word_le_nat_alt[THEN iffD1])
apply (rule word_and_le1)
apply (simp add: mask_def)
apply (simp add: word_sle_def)
apply (rule conjI, clarsimp simp: ccap_relation_NullCap_iff cap_tag_defs)
apply clarsimp
apply (rule conjI)
apply (rule unat_less_power[where sz=6, simplified], simp add: word_bits_def)
apply (rule and_mask_less'[where n=6, unfolded mask_def, simplified], simp)
apply clarsimp
apply (simp add: ccap_relation_def c_valid_cap_def cl_valid_cap_def
cap_lift_cnode_cap cap_tag_defs cap_to_H_simps
cap_cnode_cap_lift_def)
apply (simp add: word_bw_assocs word_bw_comms word_bw_lcs)
done
abbreviation
"deriveCap_xf \<equiv> liftxf errstate deriveCap_ret_C.status_C deriveCap_ret_C.cap_C ret__struct_deriveCap_ret_C_'"
lemma ensureNoChildren_ccorres:
"ccorres (syscall_error_rel \<currency> dc) (liftxf errstate id undefined ret__unsigned_long_')
(\<lambda>s. valid_objs' s \<and> valid_mdb' s) (UNIV \<inter> \<lbrace>slot = ptr_val (\<acute>slot)\<rbrace>) []
(ensureNoChildren slot) (Call ensureNoChildren_'proc)"
apply (cinit lift: slot_')
apply (rule ccorres_liftE_Seq)
apply (rule ccorres_getCTE)
apply (rule ccorres_move_c_guard_cte)
apply (rule_tac P= "\<lambda> s. valid_objs' s \<and> valid_mdb' s \<and> ctes_of s (ptr_val slota) = Some cte"
and P' =UNIV in ccorres_from_vcg_throws)
apply (rule allI, rule conseqPre, vcg)
apply clarsimp
apply (frule (1) rf_sr_ctes_of_clift, clarsimp)
apply (simp add: typ_heap_simps)
apply (clarsimp simp: whenE_def throwError_def return_def nullPointer_def liftE_bindE)
apply (clarsimp simp: returnOk_def return_def) \<comment> \<open>solve the case where mdbNext is zero\<close>
\<comment> \<open>main goal\<close>
apply (simp add: ccte_relation_def)
apply (frule_tac cte="cte_to_H y" in valid_mdb_ctes_of_next, simp+)
apply (clarsimp simp: cte_wp_at_ctes_of)
apply (frule_tac cte=cte in rf_sr_ctes_of_clift, assumption, clarsimp)
apply (rule conjI)
apply (frule_tac cte="(cte_to_H ya)" in ctes_of_valid', assumption, simp)
apply (rule valid_capAligned, assumption)
apply (rule conjI)
apply (frule_tac cte="(cte_to_H y)" in ctes_of_valid', assumption, simp)
apply blast
apply clarsimp
apply (rule conjI)
\<comment> \<open>isMDBParentOf is not zero\<close>
apply clarsimp
apply (simp add: from_bool_def)
apply (case_tac "isMDBParentOf (cte_to_H y) (cte_to_H ya)", simp_all)[1]
apply (simp add: bind_def)
apply (simp add: split_paired_Bex)
apply (clarsimp simp: in_getCTE_cte_wp_at')
apply (simp add: cte_wp_at_ctes_of)
apply (simp add: syscall_error_rel_def EXCEPTION_NONE_def EXCEPTION_SYSCALL_ERROR_def)
apply (simp add: syscall_error_to_H_cases(9))
\<comment> \<open>isMDBParentOf is zero\<close>
apply clarsimp
apply (simp add: from_bool_def)
apply (case_tac "isMDBParentOf (cte_to_H y) (cte_to_H ya)", simp_all)[1]
apply (simp add: bind_def)
apply (simp add: split_paired_Bex)
apply (clarsimp simp: in_getCTE_cte_wp_at')
apply (simp add: cte_wp_at_ctes_of)
apply (simp add: returnOk_def return_def)
\<comment> \<open>last goal\<close>
apply clarsimp
apply (simp add: cte_wp_at_ctes_of)
done
lemma Arch_deriveCap_ccorres:
"ccorres (syscall_error_rel \<currency> ccap_relation) deriveCap_xf
\<top> (UNIV \<inter> {s. ccap_relation (ArchObjectCap cap) (cap_' s)}) []
(Arch.deriveCap slot cap) (Call Arch_deriveCap_'proc)"
apply (cinit lift: cap_')
apply csymbr
apply (unfold X64_H.deriveCap_def Let_def)
apply (fold case_bool_If)
apply wpc
apply (clarsimp simp: cap_get_tag_isCap_ArchObject
ccorres_cond_iffs)
apply (rule ccorres_from_vcg_throws[where P=\<top> and P'=UNIV])
apply (rule allI, rule conseqPre, vcg)
apply clarsimp
apply (rule context_conjI)
apply (simp add: cap_get_tag_isCap_ArchObject)
apply (clarsimp simp: returnOk_def return_def)
subgoal by (simp add: ccap_relation_def cap_lift_def Let_def
cap_tag_defs cap_to_H_def
cap_page_table_cap_lift_def)
apply wpc
apply (clarsimp simp: cap_get_tag_isCap_ArchObject
ccorres_cond_iffs)
apply (rule ccorres_from_vcg_throws[where P=\<top> and P'=UNIV])
apply (rule allI, rule conseqPre, vcg)
apply clarsimp
apply (rule context_conjI)
apply (simp add: cap_get_tag_isCap_ArchObject)
apply (clarsimp simp: throwError_def return_def
errstate_def syscall_error_rel_def
syscall_error_to_H_cases
exception_defs)
subgoal by (simp add: ccap_relation_def cap_lift_def Let_def
cap_tag_defs cap_to_H_def to_bool_def
cap_page_table_cap_lift_def
split: if_split_asm)
apply wpc
apply (clarsimp simp: cap_get_tag_isCap_ArchObject
ccorres_cond_iffs)
apply (rule ccorres_from_vcg_throws[where P=\<top> and P'=UNIV])
apply (rule allI, rule conseqPre, vcg)
apply clarsimp
apply (rule context_conjI)
apply (simp add: cap_get_tag_isCap_ArchObject)
apply (clarsimp simp: returnOk_def return_def)
subgoal by (simp add: ccap_relation_def cap_lift_def Let_def
cap_tag_defs cap_to_H_def
cap_page_directory_cap_lift_def)
apply wpc
apply (clarsimp simp: cap_get_tag_isCap_ArchObject
ccorres_cond_iffs)
apply (rule ccorres_from_vcg_throws[where P=\<top> and P'=UNIV])
apply (rule allI, rule conseqPre, vcg)
apply clarsimp
apply (rule context_conjI)
apply (simp add: cap_get_tag_isCap_ArchObject)
apply (clarsimp simp: throwError_def return_def
errstate_def syscall_error_rel_def
syscall_error_to_H_cases
exception_defs)
subgoal by (simp add: ccap_relation_def cap_lift_def Let_def
cap_tag_defs cap_to_H_def to_bool_def
cap_page_directory_cap_lift_def
split: if_split_asm)
\<comment> \<open>PDPTCap\<close>
apply wpc
apply (clarsimp simp: cap_get_tag_isCap_ArchObject
ccorres_cond_iffs)
apply (rule ccorres_from_vcg_throws[where P=\<top> and P'=UNIV])
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp: cap_get_tag_isCap_unfolded_H_cap isCap_simps)
apply (rule context_conjI)
apply (clarsimp simp: returnOk_def return_def cap_tag_defs)
apply (clarsimp simp: returnOk_def return_def exception_defs)
apply (frule cap_get_tag_isCap_unfolded_H_cap)
apply (clarsimp simp: cap_pdpt_cap_lift ccap_relation_def cap_to_H_def)
apply wpc
apply (clarsimp simp: cap_get_tag_isCap_ArchObject
ccorres_cond_iffs)
apply (rule ccorres_from_vcg_throws[where P=\<top> and P'=UNIV])
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp: cap_get_tag_isCap_unfolded_H_cap isCap_simps)
apply (rule context_conjI)
apply (clarsimp simp: throwError_def return_def cap_tag_defs
errstate_def syscall_error_rel_def
syscall_error_to_H_cases
exception_defs)
apply (frule cap_get_tag_isCap_unfolded_H_cap)
apply (clarsimp simp: cap_pdpt_cap_lift ccap_relation_def cap_to_H_def to_bool_def
split: if_split_asm)
apply (clarsimp simp: throwError_def return_def
errstate_def syscall_error_rel_def
syscall_error_to_H_cases
exception_defs)
\<comment> \<open>PML4Cap\<close>
apply wpc
apply (clarsimp simp: cap_get_tag_isCap_ArchObject
ccorres_cond_iffs)
apply (rule ccorres_from_vcg_throws[where P=\<top> and P'=UNIV])
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp: cap_get_tag_isCap_unfolded_H_cap isCap_simps)
apply (rule context_conjI)
apply (clarsimp simp: returnOk_def return_def)
apply (clarsimp simp: returnOk_def return_def exception_defs)
apply (frule cap_get_tag_isCap_unfolded_H_cap)
apply (clarsimp simp: cap_pml4_cap_lift ccap_relation_def cap_to_H_def)
apply wpc
apply (clarsimp simp: cap_get_tag_isCap_ArchObject
ccorres_cond_iffs)
apply (rule ccorres_from_vcg_throws[where P=\<top> and P'=UNIV])
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp: cap_get_tag_isCap_unfolded_H_cap isCap_simps)
apply (rule context_conjI)
apply (clarsimp simp: throwError_def return_def
errstate_def syscall_error_rel_def
syscall_error_to_H_cases
exception_defs)
apply (frule cap_get_tag_isCap_unfolded_H_cap)
apply (clarsimp simp: cap_pml4_cap_lift ccap_relation_def cap_to_H_def to_bool_def
split: if_split_asm)
apply (clarsimp simp: throwError_def return_def
errstate_def syscall_error_rel_def
syscall_error_to_H_cases
exception_defs)
\<comment> \<open>PageCap\<close>
apply wpc
apply (clarsimp simp: cap_get_tag_isCap_ArchObject
ccorres_cond_iffs)
apply (rule ccorres_from_vcg_throws[where P=\<top> and P'=UNIV])
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp: cap_get_tag_isCap_unfolded_H_cap isCap_simps)
apply (rule context_conjI)
apply (simp add: cap_tag_defs)
apply (clarsimp simp: returnOk_def return_def isCap_simps)
subgoal apply (frule cap_get_tag_isCap_unfolded_H_cap)
by (clarsimp simp: cap_frame_cap_lift[simplified cap_tag_defs, simplified] cap_tag_defs
ccap_relation_def cap_to_H_def asidInvalid_def maptype_to_H_def
vm_page_map_type_defs c_valid_cap_def cl_valid_cap_def
split: if_splits)
apply (simp add: cap_get_tag_isCap_ArchObject
ccorres_cond_iffs)
apply (rule ccorres_from_vcg_throws[where P=\<top> and P'=UNIV])
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp: returnOk_def return_def subset_iff
split: bool.split)
apply (cases cap, simp_all add: isCap_simps ccap_relation_NullCap_iff)[1]
apply clarsimp
done
lemma isArchCap_T_isArchObjectCap:
"isArchCap \<top> = isArchObjectCap"
by (rule ext, auto simp: isCap_simps)
lemma deriveCap_ccorres':
"ccorres (syscall_error_rel \<currency> ccap_relation) deriveCap_xf
(valid_objs' and valid_mdb') (UNIV \<inter> {s. ccap_relation cap (cap_' s)} \<inter> {s. slot_' s = Ptr slot}) []
(deriveCap slot cap) (Call deriveCap_'proc)"
apply (cinit lift: cap_' slot_')
apply csymbr
apply (fold case_bool_If)
apply wpc
apply (clarsimp simp: cap_get_tag_isCap isCap_simps from_bool_def)
apply csymbr
apply (clarsimp simp: cap_get_tag_isCap)
apply (rule ccorres_from_vcg_throws [where P=\<top> and P' = UNIV])
apply (simp add: returnOk_def return_def ccap_relation_NullCap_iff)
apply (rule allI, rule conseqPre)
apply vcg
apply clarsimp
apply wpc
apply (clarsimp simp: isCap_simps cap_get_tag_isCap from_bool_def)
apply csymbr
apply (clarsimp simp: isCap_simps cap_get_tag_isCap)
apply (rule ccorres_from_vcg_throws[where P=\<top> and P'=UNIV])
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp: returnOk_def return_def
ccap_relation_NullCap_iff)
apply wpc
apply (clarsimp simp: isCap_simps cap_get_tag_isCap from_bool_def)
apply csymbr
apply (clarsimp simp: isCap_simps cap_get_tag_isCap)
apply (rule ccorres_rhs_assoc)+
apply ctac_print_xf
apply (rule ccorres_split_nothrow_call_novcgE
[where xf'="ret__unsigned_long_'"])
apply (rule ensureNoChildren_ccorres)
apply simp+
apply ceqv
apply simp
apply (rule_tac P'="\<lbrace>\<acute>ret__unsigned_long = scast EXCEPTION_NONE\<rbrace>"
in ccorres_from_vcg_throws[where P=\<top>])
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp: return_def returnOk_def)
apply simp
apply (rule_tac P'="{s. ret__unsigned_long_' s = rv' \<and> errstate s = err'}"
in ccorres_from_vcg_throws[where P=\<top>])
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp: throwError_def return_def
errstate_def)
apply wp
apply wpc
apply (clarsimp simp: isCap_simps cap_get_tag_isCap from_bool_def)
apply csymbr
apply (clarsimp simp: isCap_simps cap_get_tag_isCap)
apply (rule ccorres_from_vcg_throws[where P=\<top> and P'=UNIV])
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp: returnOk_def return_def
ccap_relation_NullCap_iff)
apply wpc
apply (rule ccorres_split_throws[rotated])
apply (clarsimp simp: cap_get_tag_isCap
liftME_def Let_def isArchCap_T_isArchObjectCap)
apply vcg
apply (clarsimp simp: cap_get_tag_isCap
liftME_def Let_def isArchCap_T_isArchObjectCap
ccorres_cond_univ_iff from_bool_def)
apply (rule ccorres_add_returnOk)
apply (rule ccorres_split_nothrow_call_novcgE
[where xf'=ret__struct_deriveCap_ret_C_'])
apply (rule Arch_deriveCap_ccorres)
apply simp+
apply (rule ceqv_refl)
apply (rule_tac P'="\<lbrace>\<acute>ret__struct_deriveCap_ret_C
= rv'\<rbrace>"
in ccorres_from_vcg_throws[where P=\<top>])
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp: return_def returnOk_def)
apply (rule_tac P'="{s. (ret__struct_deriveCap_ret_C_' s)
= rv' \<and> errstate s = err'}"
in ccorres_from_vcg_throws[where P=\<top>])
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp: return_def throwError_def)
apply wp
apply (simp add: cap_get_tag_isCap isArchCap_T_isArchObjectCap from_bool_def)
apply csymbr
apply (simp add: cap_get_tag_isCap)
apply (rule ccorres_from_vcg_throws[where P=\<top> and P'=UNIV])
apply (rule allI, rule conseqPre, vcg)
apply (clarsimp simp: return_def returnOk_def)
apply (clarsimp simp: errstate_def isCap_simps
Collect_const_mem from_bool_0
cap_get_tag_isArchCap_unfolded_H_cap)
done
lemma deriveCap_ccorres:
"ccorres (syscall_error_rel \<currency> ccap_relation) deriveCap_xf
(invs') (UNIV \<inter> {s. ccap_relation cap (cap_' s)} \<inter> {s. slot_' s = Ptr slot}) []
(deriveCap slot cap) (Call deriveCap_'proc)"
apply (rule ccorres_guard_imp2, rule deriveCap_ccorres')
apply fastforce
done
lemma ensureEmptySlot_ccorres:
"ccorres (syscall_error_rel \<currency> dc) (liftxf errstate id undefined ret__unsigned_long_')
\<top> (UNIV \<inter> \<lbrace>slot = ptr_val (\<acute>slot)\<rbrace>) []
(ensureEmptySlot slot) (Call ensureEmptySlot_'proc)"
apply (cinit lift: slot_')
apply (rule ccorres_liftE_Seq)
apply (rule ccorres_getCTE)
apply (rule ccorres_move_c_guard_cte)
apply (rule_tac P= "\<lambda> s. ctes_of s (ptr_val slota) = Some cte"
and P' =UNIV in ccorres_from_vcg_throws)
apply (rule allI, rule conseqPre, vcg)
apply clarsimp
apply (frule (1) rf_sr_ctes_of_clift, clarsimp)
apply (simp add: typ_heap_simps)
apply (rule conjI)
apply (clarsimp simp: unlessE_def throwError_def return_def)
apply (subgoal_tac "cap_to_H (cap_CL y) \<noteq> capability.NullCap")
apply simp
apply (simp add: syscall_error_rel_def EXCEPTION_NONE_def EXCEPTION_SYSCALL_ERROR_def)
apply (rule syscall_error_to_H_cases(8))
apply simp
apply (subst cap_get_tag_NullCap [symmetric])
prefer 2 apply assumption
apply (simp add: ccap_relation_def c_valid_cte_def)
apply (clarsimp simp: unlessE_def throwError_def return_def)
apply (subgoal_tac "cap_to_H (cap_CL y) = capability.NullCap")
apply simp
apply (simp add: returnOk_def return_def)
apply (subst cap_get_tag_NullCap [symmetric])
prefer 2 apply assumption
apply (simp add: ccap_relation_def c_valid_cte_def)
apply clarsimp
apply (simp add: cte_wp_at_ctes_of)
done
lemma updateMDB_set_mdbPrev:
"ccorres dc xfdc
(\<lambda>s. is_aligned slota cteSizeBits)
{s. slotc = slota } hs
(updateMDB ptr (mdbPrev_update (\<lambda>_. slota)))
(IF ptr \<noteq> 0
THEN
Guard C_Guard \<lbrace>hrs_htd \<acute>t_hrs \<Turnstile>\<^sub>t (Ptr ptr:: cte_C ptr)\<rbrace>
(call (\<lambda>ta. ta(| mdb_node_ptr_' := Ptr &(Ptr ptr:: cte_C ptr\<rightarrow>[''cteMDBNode_C'']),
v64_' := slotc |))
mdb_node_ptr_set_mdbPrev_'proc (\<lambda>s t. s\<lparr> globals := globals t \<rparr>) (\<lambda>ta s'. Basic (\<lambda>a. a)))
FI)"
apply (rule ccorres_guard_imp2)
apply (rule ccorres_Cond_rhs)
apply (rule ccorres_updateMDB_cte_at)
apply (ctac add: ccorres_updateMDB_set_mdbPrev)
apply (ctac ccorres: ccorres_updateMDB_skip)
apply (simp)
done
lemma updateMDB_set_mdbNext:
"ccorres dc xfdc
(\<lambda>s. is_aligned slota cteSizeBits \<and> canonical_address slota)
{s. slotc = slota} hs
(updateMDB ptr (mdbNext_update (\<lambda>_. slota)))
(IF ptr \<noteq> 0
THEN
Guard C_Guard \<lbrace>hrs_htd \<acute>t_hrs \<Turnstile>\<^sub>t (Ptr ptr:: cte_C ptr)\<rbrace>
(call (\<lambda>ta. ta(| mdb_node_ptr_' := Ptr &(Ptr ptr:: cte_C ptr\<rightarrow>[''cteMDBNode_C'']),
v64_' := slotc |))
mdb_node_ptr_set_mdbNext_'proc (\<lambda>s t. s\<lparr> globals := globals t \<rparr>) (\<lambda>ta s'. Basic (\<lambda>a. a)))
FI)"
apply (rule ccorres_guard_imp2)
apply (rule ccorres_Cond_rhs)
apply (rule ccorres_updateMDB_cte_at)
apply (ctac add: ccorres_updateMDB_set_mdbNext)
apply (ctac ccorres: ccorres_updateMDB_skip)
apply simp
done
end
end
|
{-# OPTIONS --safe --without-K #-}
open import Relation.Binary
module Data.List.Membership.Setoid.Disjoint {a p} (S : Setoid a p) where
open Setoid S renaming (Carrier to A)
open import Data.List using (List ; [])
open import Data.List.Membership.Setoid (S)
open import Data.List.Membership.Setoid.Trans (S)
open import Data.Empty
open import Function
Disjoint : Rel (List A) _
Disjoint xs ys = ∀ {x} → x ∈ xs → x ∈ ys → ⊥
disjoint-sym : Symmetric Disjoint
disjoint-sym dis = flip dis
disjoint-[]ˡ : ∀ {xs} → Disjoint xs []
disjoint-[]ˡ _ ()
disjoint-[]ʳ : ∀ {xs} → Disjoint [] xs
disjoint-[]ʳ ()
disjointness : ∀ {xs ys} → Disjoint xs ys → ∀ {x} → x ∈ xs → ∀ {y} → y ∈ ys → x ≈ y → ⊥
disjointness xs⋈ys x∈xs y∈ys x≈y = xs⋈ys x∈xs (≈-trans-∈ x≈y y∈ys)
|
import qualified Numeric.LinearAlgebra as LA
import qualified Numeric.LinearAlgebra.Data as D (tr, (><))
type X_Train = LA.Matrix Double
type Y_Train = LA.Matrix Double
type W = Double
type B = Double
type Output = LA.Matrix Double
type LearningRate = Double
-- | y = w * x + b for a single training example
ones :: Int -> Int -> LA.Matrix Double
ones x y = (x D.>< y) [1,1 ..]
output' :: W -> X_Train -> B -> Output
output' w xTrain b = w `LA.scale` xTrain + b `LA.scale` ones (fst (LA.size xTrain)) 1
cost :: Output -> Y_Train -> Double
cost output yTrain = LA.sumElements $ (1/2) * (output - yTrain) ^ 2
deltaCW' :: W -> X_Train -> B -> Double
deltaCW' w xTrain b = LA.sumElements $ D.tr (output' w xTrain b) <> xTrain
deltaCB' :: W -> X_Train -> Y_Train -> B -> Double
deltaCB' w xTrain yTrain b = LA.sumElements $ (output' w xTrain b - yTrain)
updateW' :: W -> X_Train -> B -> LearningRate -> Double
updateW' w xTrain b alpha = w - alpha * deltaCW' w xTrain b
updateB' :: W -> X_Train -> Y_Train -> B -> LearningRate -> Double
updateB' w xTrain yTrain b alpha = b - alpha * deltaCB' w xTrain yTrain b
test = do
xTrain <- LA.rand 3 1
yTrain <- LA.rand 3 1
let w = 0
let b = 0
let alpha = 0.00001
let loop i w' b' | i > 600 = return ()
loop i w' b' | i <= 600 = do
let c = cost (output' w' xTrain b') yTrain
putStrLn $ concat ["Cost: ", show c]
let w'' = updateW' w' xTrain b' alpha
let b'' = updateB' w' xTrain yTrain b' alpha
loop (i + 1) w'' b''
loop 0 w b
{- ==== BAD CODE ====
Only for my own learning
type W = LA.Matrix Double
type B = LA.Matrix Double
output :: W -> X_Train -> B -> Output
output w xTrain b = (D.tr (w) <> xTrain) + b
deltaCW :: W -> X_Train -> Y_Train -> B -> LA.Matrix Double
deltaCW w xTrain yTrain b = ((D.tr (w) <> xTrain) + b) <> xTrain
deltaCB :: W -> X_Train -> Y_Train -> B -> LA.Matrix Double
deltaCB w xTrain yTrain b = (D.tr (w) <> xTrain) + b
updateW :: W -> X_Train -> Y_Train -> B -> LearningRate -> W
updateW w xTrain yTrain b alpha = w - alpha `LA.scale` deltaCW w xTrain yTrain b
updateB :: W -> X_Train -> Y_Train -> B -> LearningRate -> W
updateB w xTrain yTrain b alpha = b - alpha `LA.scale` deltaCB w xTrain yTrain b
main = do
xTrain <- LA.rand 3 1
yTrain <- LA.rand 3 1
w <- LA.rand 3 1
b <- LA.rand 1 1
let alpha = 0.0001
let loop i w' b' | i > 1000 = return ()
loop i w' b' | i <= 1000 = do
let c = cost (output w' xTrain b') yTrain
putStrLn $ concat ["Cost: ", show c]
-- putStrLn "\n"
let w'' = updateW w' xTrain yTrain b' alpha
let b'' = updateB w' xTrain yTrain b' alpha
-- putStrLn $ concat ["Weights: ", show w'']
-- putStrLn "\n"
-- putStrLn $ concat ["Bias: ", show b'']
loop (i + 1) w'' b''
loop 0 w b
-}
|
variable α : Type
variables a b : α
variables f g : α → ℕ
variable h₁ : a = b
variable h₂ : f = g
example : f a = f b := congr_arg f h₁
example : f a = g a := congr_fun h₂ a
example : f a = g b := congr h₂ h₁
|
theory VCTheoryLemmas_no_setVarAny
imports HandDryer_no_setVarAny
begin
lemma substate_refl: "substate s s"
apply(cases s)
apply(auto)
done
lemma substate_trans:
"substate s1 s2 \<and> substate s2 s3 \<Longrightarrow> substate s1 s3"
proof(induction s3)
case emptyState
assume 1: "substate s1 s2 \<and> substate s2 emptyState"
hence "s2=emptyState"
proof(cases)
assume "s2=emptyState"
thus ?thesis by assumption
next
assume "s2 \<noteq> emptyState"
with 1 show ?thesis by simp
qed
with 1 show ?case by auto
next
case (toEnv s3)
assume 1: "substate s1 s2 \<and> substate s2 (toEnv s3)"
show ?case
proof(cases)
assume "s2=toEnv s3"
with 1 show ?case by auto
next
assume "s2 \<noteq> toEnv s3"
with 1 toEnv.IH show ?case by auto
qed
next
next
case (setVarBool s3 v u)
assume 1: "substate s1 s2 \<and> substate s2 (setVarBool s3 v u)"
show ?case
proof(cases)
assume "s2 = setVarBool s3 v u"
with 1 show ?case by auto
next
assume "s2 \<noteq> setVarBool s3 v u"
with 1 setVarBool.IH show ?case by auto
qed
next
case (setVarInt s3 v u)
assume 1: "substate s1 s2 \<and> substate s2 (setVarInt s3 v u)"
show ?case
proof(cases)
assume "s2 = setVarInt s3 v u"
with 1 show ?case by auto
next
assume "s2 \<noteq> setVarInt s3 v u"
with 1 setVarInt.IH show ?case by auto
qed
next
case (setPstate s3 p q)
assume 1: "substate s1 s2 \<and> substate s2 (setPstate s3 p q)"
show ?case
proof(cases)
assume "s2 = setPstate s3 p q"
with 1 show ?case by auto
next
assume "s2 \<noteq> setPstate s3 p q"
with 1 setPstate.IH show ?case by auto
qed
next
case (reset s3 p)
assume 1: "substate s1 s2 \<and> substate s2 (reset s3 p)"
show ?case
proof(cases)
assume "s2 = reset s3 p"
with 1 show ?case by auto
next
assume "s2 \<noteq> reset s3 p"
with 1 reset.IH show ?case by auto
qed
qed
lemma substate_asym:
"substate s1 s2 \<and> substate s2 s1 \<Longrightarrow> s1=s2"
proof(induction s2 arbitrary: s1)
case emptyState
assume 1: "substate s1 emptyState \<and> substate emptyState s1"
show ?case
proof(cases)
assume "s1=emptyState"
thus ?case by assumption
next
assume "s1 \<noteq> emptyState"
with 1 show ?case by auto
qed
next
case (toEnv s2)
assume 1: "substate s1 (toEnv s2) \<and> substate (toEnv s2) s1"
show ?case
proof(cases)
assume "s1 = toEnv s2"
thus ?case by assumption
next
assume 2: "s1 \<noteq> toEnv s2"
from 1 obtain 3: "substate s1 (toEnv s2)"
and 4: "substate (toEnv s2) s1" ..
from 2 3 have "substate s1 s2" by simp
with 4 substate_trans
have 5: "substate (toEnv s2) s2" by blast
have "substate s2 (toEnv s2)"
using substate_refl by auto
with 5 toEnv.IH have "toEnv s2 = s2" by auto
with 3 4 toEnv.IH show ?case by auto
qed
next
case (setVarBool s2 v u)
assume 1: "substate s1 (setVarBool s2 v u) \<and> substate (setVarBool s2 v u) s1"
show ?case
proof(cases)
assume "s1 = setVarBool s2 v u"
thus ?case by assumption
next
assume 2: "s1 \<noteq> setVarBool s2 v u"
from 1 obtain 3: "substate s1 (setVarBool s2 v u)"
and 4: "substate (setVarBool s2 v u) s1" ..
from 2 3 have "substate s1 s2" by simp
with 4 substate_trans
have 5: "substate (setVarBool s2 v u) s2" by blast
have "substate s2 (setVarBool s2 v u)"
using substate_refl by auto
with 5 setVarBool.IH have "setVarBool s2 v u = s2" by auto
with 3 4 setVarBool.IH show ?case by auto
qed
next
case (setVarInt s2 v u)
assume 1: "substate s1 (setVarInt s2 v u) \<and> substate (setVarInt s2 v u) s1"
show ?case
proof(cases)
assume "s1 = setVarInt s2 v u"
thus ?case by assumption
next
assume 2: "s1 \<noteq> setVarInt s2 v u"
from 1 obtain 3: "substate s1 (setVarInt s2 v u)"
and 4: "substate (setVarInt s2 v u) s1" ..
from 2 3 have "substate s1 s2" by simp
with 4 substate_trans
have 5: "substate (setVarInt s2 v u) s2" by blast
have "substate s2 (setVarInt s2 v u)"
using substate_refl by auto
with 5 setVarInt.IH have "setVarInt s2 v u = s2" by auto
with 3 4 setVarInt.IH show ?case by auto
qed
next
case (setPstate s2 p q)
assume 1: "substate s1 (setPstate s2 p q) \<and> substate (setPstate s2 p q) s1"
show ?case
proof(cases)
assume "s1 = setPstate s2 p q"
thus ?case by assumption
next
assume 2: "s1 \<noteq> setPstate s2 p q"
from 1 obtain 3: "substate s1 (setPstate s2 p q)"
and 4: "substate (setPstate s2 p q) s1" ..
from 2 3 have "substate s1 s2" by simp
with 4 substate_trans
have 5: "substate (setPstate s2 p q) s2" by blast
have "substate s2 (setPstate s2 p q)"
using substate_refl by auto
with 5 setPstate.IH have "setPstate s2 p q = s2" by auto
with 3 4 setPstate.IH show ?case by auto
qed
next
case (reset s2 p)
assume 1: "substate s1 (reset s2 p) \<and> substate (reset s2 p) s1"
show ?case
proof(cases)
assume "s1 = reset s2 p"
thus ?case by assumption
next
assume 2: "s1 \<noteq> reset s2 p"
from 1 obtain 3: "substate s1 (reset s2 p)"
and 4: "substate (reset s2 p) s1" ..
from 2 3 have "substate s1 s2" by simp
with 4 substate_trans
have 5: "substate (reset s2 p) s2" by blast
have "substate s2 (reset s2 p)"
using substate_refl by auto
with 5 reset.IH have "reset s2 p = s2" by auto
with 3 4 reset.IH show ?case by auto
qed
qed
lemma predEnv_substate: "substate (predEnv s) s"
apply(induction s)
using substate_refl by auto
lemma substate_eq_or_predEnv:
"substate s1 s2 \<and> toEnvP s1 \<longrightarrow> s1=s2 \<or> substate s1 (predEnv s2)"
apply(induction s2)
apply(auto)
done
(*
case emptyState
then show ?case by force
next
case (toEnv s2)
assume 1: "substate s1 (toEnv s2) \<and> toEnvP s1"
show ?case
proof cases
assume "s1= toEnv s2"
then show ?case by auto
next
assume "s1 \<noteq> toEnv s2"
with 1 have "substate s1 s2" by simp
with 1 toEnv.IH
have "s1=s2 \<or> substate s1 (predEnv s2)" by auto
thus ?case
proof
assume "s1=s2"
with 1
have "predEnv (toEnv s2) = s1" by auto
thus ?case by auto
next
assume 2: "substate s1 (predEnv s2)"
show ?case
proof(cases)
assume 3: "toEnvP s2"
from 2 predEnv_substate[of s2]
substate_trans have "substate s1 s2" by auto
with 3 show ?case by auto
next
assume "\<not> toEnvP s2"
with 2 show ?case by auto
qed
qed
qed
next
case (toCon s2)
assume 1: "substate s1 (toCon s2) \<and> toEnvP s1"
show ?case
proof cases
assume "s1= toCon s2"
thus ?case by auto
next
assume "s1 \<noteq> toCon s2"
with 1 have "substate s1 s2" by simp
with 1 toCon.IH
have "s1=s2 \<or> substate s1 (predEnv s2)" by auto
thus ?case
proof
assume "s1=s2"
with 1
have "predEnv (toCon s2) = s1" by auto
thus ?case by auto
next
assume 2: "substate s1 (predEnv s2)"
show ?case
proof(cases)
assume 3: "toEnvP s2"
from 2 predEnv_substate[of s2]
substate_trans have "substate s1 s2" by auto
with 3 show ?case by auto
next
assume "\<not> toEnvP s2"
with 2 show ?case by auto
qed
qed
qed
next
case (setVarBool s2 v u)
assume 1: "substate s1 (setVarBool s2 v u) \<and> toEnvP s1"
show ?case
proof cases
assume "s1= setVarBool s2 v u"
thus ?case by auto
next
assume "s1 \<noteq> setVarBool s2 v u"
with 1 have "substate s1 s2" by simp
with 1 setVarBool.IH
have "s1=s2 \<or> substate s1 (predEnv s2)" by auto
thus ?case
proof
assume "s1=s2"
with 1
have "predEnv (setVarBool s2 v u) = s1" by auto
thus ?case by auto
next
assume 2: "substate s1 (predEnv s2)"
show ?case
proof(cases)
assume 3: "toEnvP s2"
from 2 predEnv_substate[of s2]
substate_trans have "substate s1 s2" by auto
with 3 show ?case by auto
next
assume "\<not> toEnvP s2"
with 2 show ?case by auto
qed
qed
qed
next
case (setVarInt s2 v u)
assume 1: "substate s1 (setVarInt s2 v u) \<and> toEnvP s1"
show ?case
proof cases
assume "s1= setVarInt s2 v u"
thus ?case by auto
next
assume "s1 \<noteq> setVarInt s2 v u"
with 1 have "substate s1 s2" by simp
with 1 setVarInt.IH
have "s1=s2 \<or> substate s1 (predEnv s2)" by auto
thus ?case
proof
assume "s1=s2"
with 1
have "predEnv (setVarInt s2 v u) = s1" by auto
thus ?case by auto
next
assume 2: "substate s1 (predEnv s2)"
show ?case
proof(cases)
assume 3: "toEnvP s2"
from 2 predEnv_substate[of s2]
substate_trans have "substate s1 s2" by auto
with 3 show ?case by auto
next
assume "\<not> toEnvP s2"
with 2 show ?case by auto
qed
qed
qed
next
case (setVarAny s2 u)
assume 1: "substate s1 (setVarAny s2 u) \<and> toEnvP s1"
show ?case
proof cases
assume "s1= setVarAny s2 u"
thus ?case by auto
next
assume "s1 \<noteq> setVarAny s2 u"
with 1 have "substate s1 s2" by simp
with 1 setVarAny.IH
have "s1=s2 \<or> substate s1 (predEnv s2)" by auto
thus ?case
proof
assume "s1=s2"
with 1
have "predEnv (setVarAny s2 u) = s1" by auto
thus ?case by auto
next
assume 2: "substate s1 (predEnv s2)"
show ?case
proof(cases)
assume 3: "toEnvP s2"
from 2 predEnv_substate[of s2]
substate_trans have "substate s1 s2" by auto
with 3 show ?case by auto
next
assume "\<not> toEnvP s2"
with 2 show ?case by auto
qed
qed
qed
next
case (setPstate s2 p q)
assume 1: "substate s1 (setPstate s2 p q) \<and> toEnvP s1"
show ?case
proof cases
assume "s1= setPstate s2 p q"
thus ?case by auto
next
assume "s1 \<noteq> setPstate s2 p q"
with 1 have "substate s1 s2" by simp
with 1 setPstate.IH
have "s1=s2 \<or> substate s1 (predEnv s2)" by auto
thus ?case
proof
assume "s1=s2"
with 1
have "predEnv (setPstate s2 p q) = s1" by auto
thus ?case by auto
next
assume 2: "substate s1 (predEnv s2)"
show ?case
proof(cases)
assume 3: "toEnvP s2"
from 2 predEnv_substate[of s2]
substate_trans have "substate s1 s2" by auto
with 3 show ?case by auto
next
assume "\<not> toEnvP s2"
with 2 show ?case by auto
qed
qed
qed
next
case (reset s2 p)
assume 1: "substate s1 (reset s2 p) \<and> toEnvP s1"
show ?case
proof cases
assume "s1= reset s2 p"
thus ?case by auto
next
assume "s1 \<noteq> reset s2 p"
with 1 have "substate s1 s2" by simp
with 1 reset.IH
have "s1=s2 \<or> substate s1 (predEnv s2)" by auto
thus ?case
proof
assume "s1=s2"
with 1
have "predEnv (reset s2 p) = s1" by auto
thus ?case by auto
next
assume 2: "substate s1 (predEnv s2)"
show ?case
proof(cases)
assume 3: "toEnvP s2"
from 2 predEnv_substate[of s2]
substate_trans have "substate s1 s2" by auto
with 3 show ?case by auto
next
assume "\<not> toEnvP s2"
with 2 show ?case by auto
qed
qed
qed
qed
*)
lemma substate_total:
"substate s1 s \<and> substate s2 s \<longrightarrow>
substate s1 s2 \<or> substate s2 s1"
apply(induction s)
apply(auto)
done
lemma toEnvNum_id: "toEnvNum s s = 0"
apply(cases s)
apply(auto)
done
lemma substate_toEnvNum_id:
"substate s1 s2 \<and> toEnvNum s1 s2 = 0 \<and> toEnvP s1 \<and>
toEnvP s2 \<longrightarrow> s1=s2"
apply(cases s2)
apply(auto)
done
lemma gtime_predI:
"\<not> toEnvP s \<Longrightarrow> toEnvNum emptyState s =
toEnvNum emptyState (predEnv s)"
apply(induction s)
apply(auto)
done
(*
proof(induction s)
case emptyState
then show ?case by auto
next
case (toEnv s)
then show ?case by auto
next
case (toCon s)
then show ?case
proof(cases)
assume "toEnvP s"
thus ?case by auto
next
assume 1: "\<not> toEnvP s"
have 2: "toEnvNum emptyState (toCon s) =
toEnvNum emptyState s" by auto
from 1 2 toCon.IH show ?case by auto
qed
next
case (setVarBool s v u)
then show ?case
then show ?case
proof(cases)
assume "toEnvP s"
thus ?case by auto
next
assume 1: "\<not> toEnvP s"
have 2: "toEnvNum emptyState (setVarBool s v u) =
toEnvNum emptyState s" by auto
from 1 2 setVarBool.IH show ?case by auto
qed
next
case (setVarInt s v u)
then show ?case
then show ?case
proof(cases)
assume "toEnvP s"
thus ?case by auto
next
assume 1: "\<not> toEnvP s"
have 2: "toEnvNum emptyState (setVarInt s v u) =
toEnvNum emptyState s" by auto
from 1 2 setVarInt.IH show ?case by auto
qed
next
case (setVarAny s u)
then show ?case
then show ?case
proof(cases)
assume "toEnvP s"
thus ?case by auto
next
assume 1: "\<not> toEnvP s"
have 2: "toEnvNum emptyState (setVarAny s u) =
toEnvNum emptyState s" by auto
from 1 2 setVarAny.IH show ?case by auto
qed
next
case (setPstate s p q)
then show ?case
proof(cases)
assume "toEnvP s"
thus ?case by auto
next
assume 1: "\<not> toEnvP s"
have 2: "toEnvNum emptyState (setPstate s p q) =
toEnvNum emptyState s" by auto
from 1 2 setPstate.IH show ?case by auto
qed
next
case (reset s p)
then show ?case
proof(cases)
assume "toEnvP s"
thus ?case by auto
next
assume 1: "\<not> toEnvP s"
have 2: "toEnvNum emptyState (reset s p) =
toEnvNum emptyState s" by auto
from 1 2 reset.IH show ?case by auto
qed
qed
*)
lemma gtime_predE:
"toEnvP s \<longrightarrow> toEnvNum emptyState s =
toEnvNum emptyState (predEnv s) + 1"
proof(induction s)
case emptyState
then show ?case by auto
next
case (toEnv s)
then show ?case
proof cases
assume "toEnvP s"
thus ?case by auto
next
assume 1: "\<not> toEnvP s"
have "toEnvNum emptyState (toEnv s) =
toEnvNum emptyState s + 1" by auto
with 1 gtime_predI show ?thesis by auto
qed
next
case (setVarBool s x2a x3a)
then show ?case by auto
next
case (setVarInt s x2a x3a)
then show ?case by auto
next
case (setPstate s x2a x3a)
then show ?case by auto
next
case (reset s x2a)
then show ?case by auto
qed
lemma predEnvPI: "\<not> toEnvP s \<and>
toEnvNum emptyState s > 0 \<longrightarrow>
toEnvP (predEnv s)"
apply(induction s)
apply(auto)
done
lemma predEnvP: "toEnvNum emptyState s > 1 \<Longrightarrow>
toEnvP (predEnv s)"
proof(induction s)
case emptyState
then show ?case by auto
next
case (toEnv s)
then show ?case
proof(cases)
assume "toEnvP s"
thus ?case by auto
next
assume 1: "\<not> toEnvP s"
assume "toEnvNum emptyState (toEnv s) > 1"
hence "toEnvNum emptyState s > 0" by auto
with 1 predEnvPI show ?case by auto
qed
next
case (setVarBool s v u)
then show ?case
proof(cases)
assume "toEnvP s"
thus ?case by auto
next
assume 1: "\<not> toEnvP s"
assume "toEnvNum emptyState (setVarBool s v u) > 1"
hence "toEnvNum emptyState s > 1" by auto
with 1 setVarBool.IH show ?case by auto
qed
next
case (setVarInt s v u)
then show ?case
proof(cases)
assume "toEnvP s"
thus ?case by auto
next
assume 1: "\<not> toEnvP s"
assume "toEnvNum emptyState (setVarInt s v u) > 1"
hence "toEnvNum emptyState s > 1" by auto
with 1 setVarInt.IH show ?case by auto
qed
next
next
case (setPstate s p q)
then show ?case
proof(cases)
assume "toEnvP s"
thus ?case by auto
next
assume 1: "\<not> toEnvP s"
assume "toEnvNum emptyState (setPstate s p q) > 1"
hence "toEnvNum emptyState s > 1" by auto
with 1 setPstate.IH show ?case by auto
qed
next
case (reset s p)
then show ?case
proof(cases)
assume "toEnvP s"
thus ?case by auto
next
assume 1: "\<not> toEnvP s"
assume "toEnvNum emptyState (reset s p) > 1"
hence "toEnvNum emptyState s > 1" by auto
with 1 reset.IH show ?case by auto
qed
qed
lemma shift_spec:
"toEnvP s \<and> toEnvNum emptyState s > n \<Longrightarrow>
toEnvP (shiftEnv s n) \<and>
toEnvNum emptyState (shiftEnv s n) =
toEnvNum emptyState s - n"
proof(induction n)
case 0
then show ?case by auto
next
case (Suc n)
assume 1: "toEnvP s \<and>
Suc n < toEnvNum emptyState s"
with Suc.IH
have "toEnvNum emptyState (shiftEnv s n) > 1"
by auto
with predEnvP have 2:
"toEnvP (shiftEnv s (Suc n))"
by auto
from 1 Suc.IH have 3: "toEnvP (shiftEnv s n)"
by auto
from 1 Suc.IH have
"toEnvNum emptyState (shiftEnv s n) =
toEnvNum emptyState s - n" by auto
with 1 3 gtime_predE have
"toEnvNum emptyState (shiftEnv s (Suc n)) =
toEnvNum emptyState s - (Suc n)" by auto
with 2 show ?case ..
qed
lemma toEnvNum3: "substate s1 s2 \<and> substate s2 s3
\<Longrightarrow> toEnvNum s1 s3 = toEnvNum s1 s2 + toEnvNum s2 s3"
proof(induction s3)
case emptyState
then show ?case by (cases s2; auto)
next
case (toEnv s3)
then show ?case
proof(cases)
assume "s2= toEnv s3"
thus ?case by auto
next
assume 1: "s2 \<noteq> toEnv s3"
assume 2: "substate s1 s2 \<and> substate s2 (toEnv s3)"
with 1 have "substate s2 s3" by simp
show ?case
proof(cases)
assume "s1 = toEnv s3"
with 2 substate_asym[of "(toEnv s3)" s2]
have "toEnv s3 = s2" by auto
with 1 show ?case by auto
next
assume "s1 \<noteq> (toEnv s3)"
with 1 2 toEnv.IH show?case by auto
qed
qed
next
case (setVarBool s3 v u)
then show ?case
proof(cases)
assume "s2= setVarBool s3 v u"
thus ?case by auto
next
assume 1: "s2 \<noteq> setVarBool s3 v u"
assume 2: "substate s1 s2 \<and> substate s2
(setVarBool s3 v u)"
with 1 have "substate s2 s3" by simp
show ?case
proof(cases)
assume "s1 = setVarBool s3 v u"
with 2 substate_asym[of "(setVarBool s3 v u)" s2]
have "setVarBool s3 v u = s2" by auto
with 1 show ?case by auto
next
assume "s1 \<noteq> (setVarBool s3 v u)"
with 1 2 setVarBool.IH show?case by auto
qed
qed
next
case (setVarInt s3 v u)
then show ?case
proof(cases)
assume "s2= setVarInt s3 v u"
thus ?case by auto
next
assume 1: "s2 \<noteq> setVarInt s3 v u"
assume 2: "substate s1 s2 \<and> substate s2 (setVarInt s3 v u)"
with 1 have "substate s2 s3" by simp
show ?case
proof(cases)
assume "s1 = setVarInt s3 v u"
with 2 substate_asym[of "(setVarInt s3 v u)" s2]
have "setVarInt s3 v u = s2" by auto
with 1 show ?case by auto
next
assume "s1 \<noteq> (setVarInt s3 v u)"
with 1 2 setVarInt.IH show?case by auto
qed
qed
next
case (setPstate s3 p q)
then show ?case
proof(cases)
assume "s2= setPstate s3 p q"
thus ?case by auto
next
assume 1: "s2 \<noteq> setPstate s3 p q"
assume 2: "substate s1 s2 \<and> substate s2 (setPstate s3 p q)"
with 1 have "substate s2 s3" by simp
show ?case
proof(cases)
assume "s1 = setPstate s3 p q"
with 2 substate_asym[of "(setPstate s3 p q)" s2]
have "setPstate s3 p q = s2" by auto
with 1 show ?case by auto
next
assume "s1 \<noteq> (setPstate s3 p q)"
with 1 2 setPstate.IH show?case by auto
qed
qed
next
case (reset s3 p)
then show ?case
proof(cases)
assume "s2= reset s3 p"
thus ?case by auto
next
assume 1: "s2 \<noteq> reset s3 p"
assume 2: "substate s1 s2 \<and> substate s2 (reset s3 p)"
with 1 have "substate s2 s3" by simp
show ?case
proof(cases)
assume "s1 = reset s3 p"
with 2 substate_asym[of "(reset s3 p)" s2]
have "reset s3 p = s2" by auto
with 1 show ?case by auto
next
assume "s1 \<noteq> (reset s3 p)"
with 1 2 reset.IH show?case by auto
qed
qed
qed
lemma emptyState_substate: "substate emptyState s"
apply(induction s)
apply(auto)
done
lemma gtimeE_inj:
"substate s1 s \<and> toEnvP s1 \<and> toEnvP s \<and>
toEnvNum emptyState s1 = toEnvNum emptyState s \<longrightarrow>
s1=s"
proof(cases s)
case emptyState
then show ?thesis by auto
next
case (toEnv s2)
then show ?thesis
proof cases
assume "s1 =s"
then show ?thesis by auto
next
assume 1: "s1 \<noteq> s"
show ?thesis
proof
assume 2: "substate s1 s \<and>
toEnvP s1 \<and>
toEnvP s \<and>
toEnvNum emptyState s1 =
toEnvNum emptyState s"
with 1 toEnv have 3: "substate s1 s2" by auto
from toEnv have 4: "substate s2 s"
using substate_refl by auto
from 3 emptyState_substate toEnvNum3
have 5: "toEnvNum emptyState s2 =
toEnvNum emptyState s1 + toEnvNum s1 s2" by auto
from emptyState_substate 4 toEnvNum3 have 6:
"toEnvNum emptyState s = toEnvNum emptyState s2 + toEnvNum s2 s"
by auto
with toEnv have 7: "toEnvNum s2 s > 0" by auto
from 5 have
"toEnvNum emptyState s1 \<le> toEnvNum emptyState s2"
by auto
also from 6 7 have
"toEnvNum emptyState s2 < toEnvNum emptyState s"
by auto
finally have
"toEnvNum emptyState s1 < toEnvNum emptyState s" .
with 2 show
"substate s1 s \<and>
toEnvP s1 \<and>
toEnvP s \<and>
toEnvNum emptyState s1 =
toEnvNum emptyState s \<Longrightarrow> s1=s" by auto
qed
qed
next
case (setVarBool x41 x42 x43)
then show ?thesis by auto
next
case (setVarInt x51 x52 x53)
then show ?thesis by auto
next
case (setPstate x71 x72 x73)
then show ?thesis by auto
next
case (reset x81 x82)
then show ?thesis by auto
qed
lemma shiftEnv_substate: "substate (shiftEnv s n) s"
proof(induction n)
case 0
then show ?case using substate_refl by auto
next
case (Suc n)
then have "substate (predEnv (shiftEnv s n)) s"
using predEnv_substate[of "shiftEnv s n"]
substate_trans by blast
thus ?case by simp
qed
lemma toEnvNum_shift: "toEnvP s \<and>
toEnvNum emptyState s > n
\<Longrightarrow> toEnvNum (shiftEnv s n) s = n"
proof -
assume 1: "toEnvP s \<and> toEnvNum emptyState s > n"
have 2: "toEnvNum emptyState s =
toEnvNum emptyState (shiftEnv s n) +
toEnvNum (shiftEnv s n) s"
using emptyState_substate toEnvNum3
shiftEnv_substate by auto
with 1 shift_spec show ?thesis by force
qed
lemma substate_shift:
"toEnvP s1 \<and> toEnvP s \<and> substate s1 s \<and>
toEnvNum s1 s \<ge> n \<Longrightarrow>
substate s1 (shiftEnv s n)"
proof(induction n)
case 0
then show ?case by auto
next
case (Suc n)
then show ?case
proof -
assume 1: "toEnvP s1 \<and>
toEnvP s \<and>
substate s1 s \<and> Suc n \<le> toEnvNum s1 s"
with Suc.IH have "substate s1 (shiftEnv s n)"
by auto
with 1 substate_eq_or_predEnv have
"s1 = shiftEnv s n \<or>
substate s1 (predEnv (shiftEnv s n))" by auto
then show ?case
proof
assume 2: "s1 = shiftEnv s n"
with 1 emptyState_substate[of s1] toEnvNum3
have "toEnvNum emptyState s > n" by force
with 1 toEnvNum_shift have
"toEnvNum (shiftEnv s n) s = n" by auto
with 1 2 show ?case by auto
next
assume "substate s1 (predEnv (shiftEnv s n))"
thus ?case by simp
qed
qed
qed
lemma predEnvP_or_emptyState:
"toEnvP (predEnv s) \<or> predEnv s = emptyState"
apply(induction s)
apply(auto)
done
lemma shiftEnvP_or_emptyState: "n \<noteq> 0 \<longrightarrow>
toEnvP (shiftEnv s n) \<or> shiftEnv s n = emptyState"
apply(cases n)
using predEnvP_or_emptyState by auto
lemma shift_toEnvNum:
"toEnvP s \<and> toEnvP s1 \<and> substate s1 s \<Longrightarrow>
shiftEnv s (toEnvNum s1 s) = s1"
proof -
define s2:: state where
"s2 = shiftEnv s (toEnvNum s1 s)"
assume 1: "toEnvP s \<and> toEnvP s1 \<and> substate s1 s"
with s2_def substate_shift have 2:
"substate s1 s2" by auto
from 1 have "toEnvNum emptyState s1 > 0"
by (cases s1; auto)
with 1 emptyState_substate[of s1] toEnvNum3 have
"toEnvNum s1 s < toEnvNum emptyState s" by force
with 1 shift_spec s2_def have
"toEnvNum emptyState s2 =
toEnvNum emptyState s - toEnvNum s1 s" by auto
also from 1 emptyState_substate[of s1] toEnvNum3
have "toEnvNum emptyState s - toEnvNum s1 s =
toEnvNum emptyState s1" by force
finally have 3:
"toEnvNum emptyState s2 = toEnvNum emptyState s1"
.
show ?thesis
proof(cases)
assume 4: "toEnvNum s1 s = 0"
with 1 substate_toEnvNum_id have "s1=s"
by blast
with 1 show ?thesis using toEnvNum_id by auto
next
assume "toEnvNum s1 s \<noteq> 0"
with s2_def shiftEnvP_or_emptyState have
"toEnvP s2 \<or> s2 = emptyState" by auto
hence "toEnvP s2"
proof
assume "toEnvP s2"
thus ?thesis by assumption
next
assume "s2 = emptyState"
with 2 have "s1=emptyState"
by (cases s1; auto)
with 1 show ?thesis by auto
qed
with 1 2 3[symmetric] gtimeE_inj
have "s1=s2" by blast
with s2_def show ?thesis by simp
qed
qed
lemma ltime_le_toEnvNum:
"ltimeEnv s p \<le> toEnvNum emptyState s"
apply(induction s)
apply(auto)
done
(*
lemma partitioning:
"substate s1 s2 \<and> substate s2 s3 \<and> substate s1 s \<and>
substate s s3 \<longrightarrow> substate s1 s \<and> substate s s2 \<or>
substate s2 s \<and> substate s s3"
using substate_total by blast
*)
lemma predEnv_substate_imp_eq_or_substate:
"toEnvP s1 \<and> toEnvP s2 \<and> substate s1 s \<and>
substate s2 s \<and> substate (predEnv s1) s2 \<longrightarrow>
s2 = predEnv s1 \<or> substate s1 s2"
proof cases
assume "s1 = s2"
with substate_refl show ?thesis by auto
next
assume 1: "s1 \<noteq> s2"
show ?thesis
proof
assume 2: "toEnvP s1 \<and>
toEnvP s2 \<and>
substate s1 s \<and>
substate s2 s \<and> substate (predEnv s1) s2 "
with substate_total
have "substate s1 s2 \<or> substate s2 s1" by auto
thus " s2 = predEnv s1 \<or> substate s1 s2"
proof
assume "substate s1 s2"
thus ?thesis by auto
next
assume "substate s2 s1"
with 1 substate_eq_or_predEnv 2 substate_asym
show ?thesis by auto
qed
qed
qed
lemma state_down_ind:
"toEnvP s \<and> toEnvP s1 \<Longrightarrow> P s \<Longrightarrow>
(\<And> s2. toEnvP s2 \<Longrightarrow>
(substate s1 s2 \<and> substate s2 s \<and> s1 \<noteq> s2)
\<Longrightarrow> P s2 \<Longrightarrow> P (predEnv s2)) \<Longrightarrow>
toEnvP s2 \<and> substate s1 s2 \<and> substate s2 s \<longrightarrow>
P s2"
proof -
assume 1: "toEnvP s \<and> toEnvP s1"
define Q:: "nat \<Rightarrow> bool" where
"Q = (\<lambda> n. P (shiftEnv s n))"
from Q_def 1 shift_toEnvNum have P_def:
"\<And> s'. toEnvP s' \<and> substate s' s \<Longrightarrow>
P s' = Q (toEnvNum s' s)" by auto
define n where "n = toEnvNum s2 s"
assume base: "P s" and ind_step:
"\<And> s2. toEnvP s2 \<Longrightarrow>
(substate s1 s2 \<and> substate s2 s \<and> s1 \<noteq> s2)
\<Longrightarrow> P s2 \<Longrightarrow> P (predEnv s2)"
show ?thesis
proof
assume 2: "toEnvP s2 \<and> substate s1 s2 \<and>
substate s2 s"
with 1 n_def shift_toEnvNum have s2_def: "s2 = shiftEnv s n"
by auto
from 2 show "P s2"
apply(simp only: P_def n_def[symmetric])
apply(simp only: s2_def)
proof(induction n)
case 0
then show ?case using Q_def base by auto
next
case (Suc n)
then show ?case
apply(simp only: Q_def)
print_state
proof cases
assume 3: "s1 = shiftEnv s n"
assume 4: "toEnvP (shiftEnv s (Suc n)) \<and>
substate s1 (shiftEnv s (Suc n)) \<and>
substate (shiftEnv s (Suc n)) s"
from 3 have 5: "substate (shiftEnv s n) s1"
using substate_refl by auto
from predEnv_substate have
"substate (shiftEnv s (Suc n)) (shiftEnv s n)"
by simp
with 4 5 substate_asym substate_trans
have "s1 = shiftEnv s (Suc n)"
by blast
with 3 have
"shiftEnv s n = shiftEnv s (Suc n)" by simp
with 4 gtime_predE show
"P (shiftEnv s (Suc n))" by fastforce
next
assume 3: "s1 \<noteq> shiftEnv s n"
assume 4: "toEnvP (shiftEnv s (Suc n)) \<and>
substate s1 (shiftEnv s (Suc n)) \<and>
substate (shiftEnv s (Suc n)) s"
from predEnv_substate have
"substate (shiftEnv s (Suc n)) (shiftEnv s n)"
by simp
with 4 substate_trans have 5:
"substate s1 (shiftEnv s n)" by blast
have 6: "toEnvP (shiftEnv s n)"
proof cases
assume "n = 0"
with 1 show ?thesis by auto
next
assume "n \<noteq> 0"
with shiftEnvP_or_emptyState have
"toEnvP (shiftEnv s n) \<or>
(shiftEnv s n) = emptyState" by auto
thus ?thesis
proof
assume "toEnvP (shiftEnv s n)"
thus ?thesis by assumption
next
assume "shiftEnv s n = emptyState"
with 5 have "s1 = emptyState"
by (cases s1; auto)
with 1 show ?thesis by auto
qed
qed
assume "(toEnvP (shiftEnv s n) \<and>
substate s1 (shiftEnv s n) \<and>
substate (shiftEnv s n) s \<Longrightarrow>
P (shiftEnv s n))"
with 3 5 6 shiftEnv_substate ind_step
show "P (shiftEnv s (Suc n))"
by auto
qed
qed
qed
qed
end
|
[STATEMENT]
lemma lift2_Err [simp]:
"x +_(lift2 f) Err = Err"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. x \<squnion>\<^bsub>lift2 f\<^esub> Err = Err
[PROOF STEP]
by (simp add: lift2_def plussub_def split: err.split) |
!*** Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
!*** See https://llvm.org/LICENSE.txt for license information.
!*** SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
! more derived type parameters in modules
module md
type tscope
integer :: scope
real :: junk
end type
type (tscope), parameter :: local = tscope(2,3.333)
type (tscope), parameter :: global = tscope(1,4.444)
end module
subroutine sub(a,x)
use md
real,parameter::l = local%junk
real,parameter::g = global%junk
integer,parameter::mm = local%scope
real array(local%scope)
real a
integer x
select case(x)
case(local%scope)
a = l
case(global%scope)
a = g
case default
a = 0.0
end select
end subroutine
program p
use md
type(tscope)::m
parameter(n=3)
real result(n)
real expect(n)
data expect/3.333,4.444,0.000/
call sub(result(1),local%scope)
call sub(result(2),global%scope)
call sub(result(3),0)
call check(result, expect, n)
end
|
(************************************************************************)
(* Copyright 2006 Milad Niqui *)
(* This file is distributed under the terms of the *)
(* GNU Lesser General Public License Version 2.1 *)
(* A copy of the license can be found at *)
(* <http://www.gnu.org/licenses> *)
(************************************************************************)
Require Import R_addenda.
Require Import Fourier_solvable_ineqs.
Require Import Fourier.
Require Import digits.
Require Import ub.
Require Import LNP_Digit.
Require Import homographic.
Require Import hcorrectness.
Require Import Refining_M.
Require Import Bounded_M.
Require Import Incl_M.
(** * Obtaining the productivity predicate for the refining Moebius maps. *)
Open Scope Z_scope.
Open Scope Q_scope.
Lemma thesis_5_6_9:forall mu H_refining, diameter mu H_refining < redundancy -> {d:Digit| Incl_M mu d}.
Proof.
intros ((a,b),(c,d)) H_refining.
assert (H_bounded:=proj1 H_refining).
assert (H_denom: forall r : R, (-1 <= r <= 1)%R -> denom_nonvanishing_M (a, b, (c, d)) r);
[intros r Hr; apply Is_refining_M_denom_nonvanishing_M; trivial|].
set (mu_1:=as_Moebius_Q ((a,b),(c,d)) Qone).
set (mu_2:=as_Moebius_Q ((a,b),(c,d)) (- Qone)).
destruct (Qle_dec_weak (a*d-b*c) Zero) as [H_det|H_det]; unfold diameter,redundancy; fold mu_1 mu_2.
(* det(mu)<=0 *)
assert (H_mu:=det_nonpos_refining_endpoints _ _ _ _ H_refining H_det); fold mu_1 mu_2 in H_mu.
rewrite (Qabs_non_eq _ (Qle_Qminus_Zero_neg _ _ H_mu)); intro H_diam.
destruct (Q_le_lt_dec mu_2 Zero) as [H_mu_2|H_mu_2].
(* mu(-1)<=0 *)
exists LL.
apply Incl_M_L_folded; trivial; intros r Hr; split.
elim (Is_refining_M_property _ _ Hr H_refining); trivial.
apply Rle_trans with mu_2; [ | realify_Q; auto].
generalize (det_nonpos_nonincreasing _ _ _ _ (-1) r H_bounded H_det min_one_is_in_base_interval Hr (proj1 Hr));
unfold mu_2, as_Moebius_Q, as_Moebius; simpl;
let t_local:= (destruct H_bounded as [[H1 H2]|[H1 H2]]; simpl in H1, H2; auto) in realify_Q_goal;
[ trivial
| stepl (d-c); try ring; t_local
].
(* 0<mu(-1) *)
destruct (Q_le_lt_dec Zero mu_1) as [H_mu_1|H_mu_1].
(* 0<=mu(1) *)
exists RR.
apply Incl_M_R_folded; trivial; intros r Hr; split.
apply Rle_trans with mu_1; [ realify_Q; auto| ].
generalize (det_nonpos_nonincreasing _ _ _ _ r 1 H_bounded H_det Hr one_is_in_base_interval (proj2 Hr));
unfold mu_1, as_Moebius_Q, as_Moebius; simpl.
let t_local:= (destruct H_bounded as [[H1 H2]|[H1 H2]]; simpl in H1, H2; auto) in realify_Q_goal;
[ trivial
| stepl (d+c); try ring; t_local
].
elim (Is_refining_M_property _ _ Hr H_refining); trivial.
(* mu(1)<Zero *)
exists MM.
apply Incl_M_M_folded; trivial; intros r Hr; split.
apply Rle_trans with mu_1.
generalize (Q_to_Rlt _ _ H_mu_2);
assert (H_diam':(mu_2-mu_1<1/3)%R);
[ stepl (-(mu_1 - mu_2))%R; [|ring]; generalize (Q_to_Rlt _ _ H_diam); rationalify_R_goal
| realify_Q_goal; intros H_mu_2'; fourier
]...
generalize (det_nonpos_nonincreasing _ _ _ _ r 1 H_bounded H_det Hr one_is_in_base_interval (proj2 Hr));
unfold mu_1, as_Moebius_Q, as_Moebius; simpl;
let t_local:= (destruct H_bounded as [[H1 H2]|[H1 H2]]; simpl in H1, H2; auto) in realify_Q_goal;
[ trivial
| stepl (d+c); try ring; t_local
]...
apply Rle_trans with mu_2.
generalize (det_nonpos_nonincreasing _ _ _ _ (-1) r H_bounded H_det min_one_is_in_base_interval Hr (proj1 Hr));
unfold mu_2, as_Moebius_Q, as_Moebius; simpl;
let t_local:= (destruct H_bounded as [[H1 H2]|[H1 H2]]; simpl in H1, H2; auto) in realify_Q_goal;
[ trivial
| stepl (d-c); try ring; t_local
]...
generalize (Q_to_Rlt _ _ H_mu_1);
assert (H_diam':(mu_2-mu_1<1/3)%R);
[ stepl (-(mu_1 - mu_2))%R; [|ring]; generalize (Q_to_Rlt _ _ H_diam); rationalify_R_goal
| realify_Q_goal; intros H_mu_2'; fourier
]...
(* 0<=det(mu) *)
assert (H_mu:=det_nonneg_refining_endpoints _ _ _ _ H_refining H_det); fold mu_1 mu_2 in H_mu.
rewrite (Qabs_eq _ (Qle_Qminus_Zero _ _ H_mu)); intro H_diam.
destruct (Q_le_lt_dec mu_1 Zero) as [H_mu_1|H_mu_1].
(* mu(1)<=0 *)
exists LL.
apply Incl_M_L_folded; trivial; intros r Hr; split.
elim (Is_refining_M_property _ _ Hr H_refining); trivial.
apply Rle_trans with mu_1; [ | realify_Q; auto].
generalize (det_nonneg_nondecreasing _ _ _ _ r 1 H_bounded H_det Hr one_is_in_base_interval (proj2 Hr));
unfold mu_1, as_Moebius_Q, as_Moebius; simpl;
let t_local:= (destruct H_bounded as [[H1 H2]|[H1 H2]]; simpl in H1, H2; auto) in realify_Q_goal;
[ trivial
| stepl (d+c); try ring; t_local
].
(* 0<mu(1) *)
destruct (Q_le_lt_dec Zero mu_2) as [H_mu_2|H_mu_2].
(* 0<=mu(-1) *)
exists RR.
apply Incl_M_R_folded; trivial; intros r Hr; split.
apply Rle_trans with mu_2; [ realify_Q; auto| ].
generalize (det_nonneg_nondecreasing _ _ _ _ (-1) r H_bounded H_det min_one_is_in_base_interval Hr (proj1 Hr));
unfold mu_2, as_Moebius_Q, as_Moebius; simpl.
let t_local:= (destruct H_bounded as [[H1 H2]|[H1 H2]]; simpl in H1, H2; auto) in realify_Q_goal;
[ trivial
| stepl (d-c); try ring; t_local
].
elim (Is_refining_M_property _ _ Hr H_refining); trivial.
(* mu(-1)<Zero *)
exists MM.
apply Incl_M_M_folded; trivial; intros r Hr; split.
apply Rle_trans with mu_2.
generalize (Q_to_Rlt _ _ H_mu_1);
assert (H_diam':(mu_1-mu_2<1/3)%R);
[ generalize (Q_to_Rlt _ _ H_diam); rationalify_R_goal
| realify_Q_goal; intros H_mu_2'; fourier
]...
generalize (det_nonneg_nondecreasing _ _ _ _ (-1) r H_bounded H_det min_one_is_in_base_interval Hr (proj1 Hr));
unfold mu_2, as_Moebius_Q, as_Moebius; simpl;
let t_local:= (destruct H_bounded as [[H1 H2]|[H1 H2]]; simpl in H1, H2; auto) in realify_Q_goal;
[ trivial
| stepl (d-c); try ring; t_local
]...
apply Rle_trans with mu_1.
generalize (det_nonneg_nondecreasing _ _ _ _ r 1 H_bounded H_det Hr one_is_in_base_interval (proj2 Hr));
unfold mu_1, as_Moebius_Q, as_Moebius; simpl;
let t_local:= (destruct H_bounded as [[H1 H2]|[H1 H2]]; simpl in H1, H2; auto) in realify_Q_goal;
[ trivial
| stepl (d+c); try ring; t_local
]...
generalize (Q_to_Rlt _ _ H_mu_2);
assert (H_diam':(mu_1-mu_2<1/3)%R);
[ generalize (Q_to_Rlt _ _ H_diam); rationalify_R_goal
| realify_Q_goal; intros H_mu_2'; fourier
]...
Qed.
Lemma product_init_pure_ub:forall alpha n, as_Moebius_Q (product_init_pure alpha n) Qone = ub alpha n.
Proof.
intros alpha n; revert alpha; induction n; intros [d alpha]; unfold product_init_pure.
(* O *)
simpl; auto.
(* S n *)
rewrite ub_S_n.
rewrite Streams_addenda.take_S_n;
rewrite (Streams_addenda.fold_right_cons product).
unfold map_reals. rewrite Streams_addenda.map_spelled.
unfold hd, tl.
fold map_reals.
rewrite <- (IHn alpha).
replace (List.fold_right product idM (Streams_addenda.take n (map_reals alpha))) with (product_init_pure alpha n); trivial.
rewrite as_Moebius_Q_product; trivial.
apply Is_refining_M_denom_nonvanishing_M.
apply Is_refining_M_product_init_pure.
realify_Q; apply one_is_in_base_interval.
rewrite (IHn alpha); qZ_numerals; apply ub_is_in_base_interval_low.
rewrite (IHn alpha); qZ_numerals; apply ub_is_in_base_interval_up.
destruct d; [apply Is_refining_M_L|apply Is_refining_M_R|apply Is_refining_M_M].
Qed.
Lemma product_init_pure_lb:forall alpha n, as_Moebius_Q (product_init_pure alpha n) (-Qone) = lb alpha n.
intros alpha n; revert alpha; induction n; intros [d alpha]; unfold product_init_pure.
(* O *)
simpl; auto.
(* S n *)
rewrite lb_S_n.
rewrite Streams_addenda.take_S_n;
rewrite (Streams_addenda.fold_right_cons product).
unfold map_reals. rewrite Streams_addenda.map_spelled.
unfold hd, tl.
fold map_reals.
rewrite <- (IHn alpha).
replace (List.fold_right product idM (Streams_addenda.take n (map_reals alpha))) with (product_init_pure alpha n); trivial.
rewrite as_Moebius_Q_product; trivial.
apply Is_refining_M_denom_nonvanishing_M.
apply Is_refining_M_product_init_pure.
realify_Q; apply min_one_is_in_base_interval.
rewrite (IHn alpha); qZ_numerals; apply lb_is_in_base_interval_low.
rewrite (IHn alpha); qZ_numerals; apply lb_is_in_base_interval_up.
destruct d; [apply Is_refining_M_L|apply Is_refining_M_R|apply Is_refining_M_M].
Qed.
Lemma diameter_product:forall mu mu' H_mu H_mu', diameter (product mu mu') (Is_refining_M_product _ _ H_mu H_mu') =
(Qabs (Determinant mu))* (diameter mu' H_mu') *
(Qabs(as_Moebius_Q (eta_discriminant mu) (as_Moebius_Q mu' (-Qone)))*Qabs(as_Moebius_Q (eta_discriminant mu) (as_Moebius_Q mu' Qone))).
Proof.
intros ((a,b),(c,d)) ((a',b'),(c',d')) H_mu H_mu'.
assert (H_mu_bound:=proj1 H_mu); assert (H_mu'_bound:=proj1 H_mu').
assert (H_prod:=Is_refining_M_product _ _ H_mu H_mu'); generalize (proj1 H_prod).
revert H_prod;
unfold diameter, Determinant, eta_discriminant, product, as_Moebius_Q, fst, snd.
intros H_prod H_prod_bound.
assert (H_cd:=Bounded_M_c_plus_d_nonzero _ _ _ _ H_mu_bound).
assert (H_dc:=Bounded_M_d_minus_c_nonzero _ _ _ _ H_mu_bound).
assert (H_cd':=Bounded_M_c_plus_d_nonzero _ _ _ _ H_mu'_bound).
assert (H_dc':=Bounded_M_d_minus_c_nonzero _ _ _ _ H_mu'_bound).
assert (H_pord_denom_one:=Bounded_M_c_plus_d_nonzero _ _ _ _ H_prod_bound).
assert (H_prod_denom_min_one:=Bounded_M_d_minus_c_nonzero _ _ _ _ H_prod_bound).
assert (H_cd_:c * - Qone + d<>Zero); [ring_exact_Q H_dc|].
assert (H_cd'_:c' * - Qone + d'<>Zero); [ring_exact_Q H_dc'|].
assert (H_prod_denom_min_one_:(c*a'+d*c')* - Qone + (c*b'+d*d') <> Zero); [ring_exact_Q H_prod_denom_min_one|].
qZ_numerals.
repeat rewrite <- Qabs_Qmult.
repeat rewrite Qminus_Qdiv; trivial.
apply (f_equal Qabs).
field; repeat split; auto.
ring_exact_Q H_pord_denom_one.
ring_exact_Q H_prod_denom_min_one.
Qed.
Lemma diameter_product_init_pure:forall alpha n H_diam, diameter(product_init_pure alpha n) H_diam= ub alpha n-lb alpha n.
Proof.
intros alpha n H_diam;
unfold diameter; rewrite product_init_pure_ub; rewrite product_init_pure_lb; rewrite Qabs_eq_pos; trivial;
apply Qlt_Qminus_Zero; apply lb_lt_ub_pointwise.
Qed.
Lemma diameter_product_init:forall a b c d alpha n H_mualpha,
Is_refining_M ((a,b),(c,d)) -> diameter (product_init ((a,b),(c,d)) alpha n) H_mualpha =
(Qabs (a*d - b*c)) * (ub alpha n - lb alpha n)
* (Qabs (as_Moebius_Q ((0/1,1/1),(c,d)) (lb alpha n)) * Qabs (as_Moebius_Q ((0/1,1/1),(c,d)) (ub alpha n))).
Proof.
intros a b c d alpha n.
rewrite product_init_product_init_pure.
intros H_mualpha H_mu.
assert (H_alpha:=(Is_refining_M_product_init_pure alpha n)).
rewrite <- (diameter_product_init_pure alpha n H_alpha).
rewrite <- product_init_pure_lb.
rewrite <- product_init_pure_ub.
transitivity (diameter (product (a, b, (c, d)) (product_init_pure alpha n))
(Is_refining_M_product (a, b, (c, d)) (product_init_pure alpha n) H_mu H_alpha)); [apply diameter_PI|].
rewrite (diameter_product _ _ H_mu H_alpha).
repeat apply (f_equal2 Qmult); trivial.
Qed.
Lemma eta_discriminant_twice_majorised: forall a b c d alpha n, Is_refining_M ((a,b),(c,d)) ->
let X := Qmax (Qabs(Qone/(c+d))) (Qabs (Qone/(d-c))) in
(Qabs (as_Moebius_Q ((0/1,1/1),(c,d)) (lb alpha n)) * Qabs (as_Moebius_Q ((0/1,1/1),(c,d)) (ub alpha n)))<= X * X.
Proof.
intros a b c d alpha n [H_bounded _] X.
apply Qmult_Qle_compat ; [| |apply Qabs_nonneg|apply Qabs_nonneg];
subst X; apply maximum_eta_discriminant_base_interval with a b; trivial.
apply lb_is_in_base_interval_low.
apply lb_is_in_base_interval_up.
apply ub_is_in_base_interval_low.
apply ub_is_in_base_interval_up.
Qed.
(** This is the main productivity lemma (similar to Lemma 5.6.10 of
the thesis) for the homographic algorithm. It extracts [n] --- number
of the absorption steps after which emission occurs. *)
Theorem thesis_5_6_10: forall mu alpha, Is_refining_M mu -> {n:nat & {d | Incl_M (product_init mu alpha n) d}}.
Proof.
intros ((a,b),(c,d)) alpha H_refining.
set (det:=a*d-b*c).
set (X := Qmax (Qabs(Qone/(c+d))) (Qabs (Qone/(d-c)))).
set (q:=3*(2*(Qabs det))*(X*X)).
destruct (Q_Archimedean_nat_inf q) as [n Hn].
exists n.
assert (H_n_one_pos: Zero < n + 1); [natZ_numerals; qnat_one; natq_zero; natq_S n; natq_S (S n); auto|].
assert (H_refining_prod:=Is_refining_M_product_init _ alpha n H_refining).
apply thesis_5_6_9 with H_refining_prod; unfold redundancy.
rewrite (diameter_product_init _ _ _ _ _ _ H_refining_prod H_refining).
fold det.
rewrite <- Qmult_assoc.
apply Qle_lt_trans with ((Qabs det)*((2%nat/(n+1%nat))*(X*X))).
apply Qle_reg_mult_l_strong; [apply Qabs_nonneg|].
apply Qmult_Qle_compat.
apply thesis_5_7_9.
unfold X; apply eta_discriminant_twice_majorised with a b; assumption.
apply Qle_Qminus_Zero; apply lb_leq_ub_pointwise.
apply Qle_mult_nonneg_nonneg; apply Qabs_nonneg.
stepl (((2*Qabs det)*(X*X))/(n+1)).
apply Qmult_Qdiv_pos.
auto.
stepl (3*(2*Qabs det)*(X*X)); [|ring].
stepr (n+1); [| qZ_numerals_one; ring].
fold q.
apply Qle_lt_trans with n; trivial.
rewrite <- Z_to_Qplus; apply Z_to_Qlt; natZ_numerals; rewrite <- inj_plus; apply inj_lt; omega.
revert H_n_one_pos; natZ_numerals; intros H_n_one_pos; field; auto.
Qed.
Close Scope Q_scope.
Close Scope Z_scope.
(** Using the above we prove that [n] can always be chosen to be the smallest such number. *)
Lemma semantic_modulus_h: forall mu alpha, Is_refining_M mu ->
{n:nat & { d | Incl_M (product_init mu alpha n) d /\
(forall m d', (m<n)%nat ->~Incl_M (product_init mu alpha m) d') } }.
Proof.
intros mu alpha H_r.
apply LNP_sigS_nat_Digit.
intros n d; apply Incl_M_dec_D.
apply thesis_5_6_10; assumption.
Qed.
Lemma semantic_modulus_h_S_product:forall n n' mu alpha (H_r:Is_refining_M mu) H_r',
let smodu':=semantic_modulus_h (product mu (map_digits (hd alpha))) (tl alpha) H_r' in
let smodu:=semantic_modulus_h mu alpha H_r in
(0 < n)%nat -> n' = projT1 smodu' -> n = projT1 smodu -> n = S n'.
Proof.
destruct n; intros n' mu alpha H_r H_r' smodu' smodu Hn_pos Hn' Hn; [inversion Hn_pos |].
set (d:=(proj1_sig (projT2 smodu)));
set (d':=(proj1_sig (projT2 smodu')));
assert (Hd:d=(proj1_sig (projT2 smodu))); trivial;
assert (Hd':d'=(proj1_sig (projT2 smodu'))); trivial;
destruct (proj2_sig (projT2 smodu)) as [H1 H3];
destruct (proj2_sig (projT2 smodu')) as [H1' H3'].
rewrite_all <- Hd; rewrite_all <- Hd'; rewrite_all <- Hn; rewrite_all <- Hn'.
apply eq_S.
destruct (lt_eq_lt_dec n n') as [[Hnn'|Hnn']|Hnn']; trivial.
generalize (H3' n d Hnn');
rewrite_all (product_init_folds mu alpha n);
contradiction...
generalize (lt_n_S _ _ Hnn'); intros Hnn'_S;
generalize (H3 (S n') d' Hnn'_S);
rewrite (product_init_folds mu alpha n');
contradiction...
Qed.
Lemma Is_refining_M_emits_h_pointwise: forall n mu alpha H_r,
let smodu:=semantic_modulus_h mu alpha H_r in
n = projT1 smodu -> emits_h mu alpha.
Proof.
induction n;
intros mu alpha H_r smodu Hn;
set (n':=projS1 smodu);
set (d:=(proj1_sig (projT2 smodu)));
assert (Hn':n'=(projT1 smodu)); trivial;
assert (Hd:d=(proj1_sig (projT2 smodu))); trivial;
destruct (proj2_sig (projT2 smodu)) as [H1 H3].
(* O *)
simpl in H1.
case (Incl_M_dec_D mu LL); intros t_l.
constructor 1; trivial.
case (Incl_M_dec_D mu RR); intros t_r.
constructor 2; trivial.
case (Incl_M_dec_D mu MM); intros t_m.
constructor 3; trivial.
rewrite_all <- Hd; rewrite_all <- Hn'; rewrite_all <- Hn; destruct d; contradiction.
(* S n *)
rewrite_all <- Hd; rewrite_all <- Hn.
generalize (H3 O LL (lt_O_Sn _)); generalize (H3 O RR (lt_O_Sn _)); generalize (H3 O MM (lt_O_Sn _)).
simpl; intros t_m t_r t_l.
constructor 4; trivial.
apply (IHn (product mu (hd alpha)) (tl alpha) (Is_refining_M_product_hd _ _ H_r)).
apply eq_add_S.
apply (semantic_modulus_h_S_product (S n) (projT1 (semantic_modulus_h (product mu (hd alpha))
(tl alpha) (Is_refining_M_product_hd mu alpha H_r)))
mu alpha H_r (Is_refining_M_product_hd _ _ H_r)); trivial.
apply lt_O_Sn.
Qed.
Lemma Is_refining_M_emits_h: forall mu alpha, Is_refining_M mu -> emits_h mu alpha.
Proof.
intros mu alpha H_r.
set (smodu:=semantic_modulus_h mu alpha H_r).
set (n:=projS1 smodu).
assert (Hn:n=(projT1 smodu)); trivial.
apply Is_refining_M_emits_h_pointwise with n H_r; trivial.
Qed.
Lemma Is_refining_M_depth_h:forall n mu alpha (H_r:Is_refining_M mu),
let smodu:=semantic_modulus_h mu alpha H_r in
n= projS1 smodu -> depth_h mu alpha (Is_refining_M_emits_h mu alpha H_r) = n.
Proof.
induction n; intros mu alpha H_r smodu Hn;
set (d:=(proj1_sig (projT2 smodu)));
assert (Hd':d=(proj1_sig (projT2 smodu))); trivial;
destruct (proj2_sig (projT2 smodu)) as [H1 H3].
(* 0 *)
revert H1; rewrite <- Hd'; rewrite <- Hn; intros H1.
case (Incl_M_dec_D mu LL); intros t_l.
apply depth_h_L; trivial.
case (Incl_M_dec_D mu RR); intros t_r.
apply depth_h_R; trivial.
case (Incl_M_dec_D mu MM); intros t_m.
apply depth_h_M; trivial.
destruct d; contradiction.
(* S n *)
generalize H1 (H3 O); clear H1 H3; rewrite <- Hd'; rewrite <- Hn; intros H1 H3.
case (Incl_M_dec_D mu LL); intros t_l.
rewrite depth_h_L; trivial; generalize (H3 LL (lt_O_Sn _)); simpl; intros H4; contradiction.
case (Incl_M_dec_D mu RR); intros t_r.
rewrite depth_h_R; trivial; generalize (H3 RR (lt_O_Sn _)); simpl; intros H4; contradiction.
case (Incl_M_dec_D mu MM); intros t_m.
rewrite depth_h_M; trivial; generalize (H3 MM (lt_O_Sn _)); simpl; intros H4; contradiction.
set (smodu':=semantic_modulus_h (product mu (map_digits (hd alpha))) (tl alpha) (Is_refining_M_product_hd _ _ H_r)).
generalize (semantic_modulus_h_S_product (S n) (projT1 smodu') _ alpha H_r (Is_refining_M_product_hd _ _ H_r)).
intros H_Sn.
rewrite (depth_h_absorbs _ _ (Is_refining_M_emits_h mu alpha H_r) t_l t_r t_m (Is_refining_M_emits_h _ (tl alpha)
(Is_refining_M_product_hd mu alpha H_r))).
apply eq_S.
apply IHn.
rewrite (eq_add_S _ _ (H_Sn (lt_O_Sn _) (refl_equal _) Hn)); trivial.
Qed.
Lemma Is_refining_M_modulus_h:forall mu alpha (H_r:Is_refining_M mu),
let modu:=modulus_h mu alpha (Is_refining_M_emits_h mu alpha H_r) in
let mu' := fstT (sndT modu) in
Is_refining_M mu'.
Proof.
intros mu alpha H_r.
set (smodu:=semantic_modulus_h mu alpha H_r).
set (n:=projS1 smodu).
set (d':=(proj1_sig (projT2 smodu))).
assert (Hn:n=(projT1 smodu)); trivial.
assert (Hd':d'=(proj1_sig (projT2 smodu))); trivial.
assert (H_depth: depth_h mu alpha (Is_refining_M_emits_h mu alpha H_r) = n);[apply (Is_refining_M_depth_h n _ alpha H_r Hn)|].
destruct (depth_h_modulus_h mu alpha (Is_refining_M_emits_h mu alpha H_r) n (Is_refining_M_depth_h n _ _ _ Hn)) as [d Hd].
destruct (proj2_sig (projS2 smodu)) as [H_Incl _].
rewrite Hd; simpl.
apply Incl_M_absorbs_Is_refining_M.
destruct (depth_h_Incl_M_inf_strong_general _ _ (Is_refining_M_emits_h mu alpha H_r) n H_depth) as [d'' [Hd''1 Hd''2]].
revert Hd''2.
rewrite Hd; simpl.
intros Hd''2.
subst d''.
assumption.
Qed.
Lemma Is_refining_M_step_productive_h: forall n mu alpha, Is_refining_M mu -> step_productive_h n mu alpha.
Proof.
induction n;
intros mu alpha H_refining.
(* 0 *) constructor; apply Is_refining_M_emits_h; trivial.
(* S *) apply (step_productive_h_S n _ _ (Is_refining_M_emits_h _ alpha H_refining)).
apply IHn.
apply (Is_refining_M_modulus_h _ alpha H_refining).
Qed.
Theorem Is_refining_M_productive_h: forall mu alpha, Is_refining_M mu -> productive_h mu alpha.
Proof.
intros mu alpha H_refining.
constructor; intros n; apply Is_refining_M_step_productive_h; trivial.
Qed.
|
/-
Copyright (c) 2022 Jiale Miao. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jiale Miao, Kevin Buzzard, Alexander Bentkamp
-/
import analysis.inner_product_space.pi_L2
import linear_algebra.matrix.block
/-!
# Gram-Schmidt Orthogonalization and Orthonormalization
In this file we introduce Gram-Schmidt Orthogonalization and Orthonormalization.
The Gram-Schmidt process takes a set of vectors as input
and outputs a set of orthogonal vectors which have the same span.
## Main results
- `gram_schmidt` : the Gram-Schmidt process
- `gram_schmidt_orthogonal` :
`gram_schmidt` produces an orthogonal system of vectors.
- `span_gram_schmidt` :
`gram_schmidt` preserves span of vectors.
- `gram_schmidt_ne_zero` :
If the input vectors of `gram_schmidt` are linearly independent,
then the output vectors are non-zero.
- `gram_schmidt_basis` :
The basis produced by the Gram-Schmidt process when given a basis as input.
- `gram_schmidt_normed` :
the normalized `gram_schmidt` (i.e each vector in `gram_schmidt_normed` has unit length.)
- `gram_schmidt_orthornormal` :
`gram_schmidt_normed` produces an orthornormal system of vectors.
- `gram_schmidt_orthonormal_basis`: orthonormal basis constructed by the Gram-Schmidt process from
an indexed set of vectors of the right size
-/
open_locale big_operators
open finset submodule finite_dimensional
variables (𝕜 : Type*) {E : Type*} [is_R_or_C 𝕜] [normed_add_comm_group E] [inner_product_space 𝕜 E]
variables {ι : Type*} [linear_order ι] [locally_finite_order_bot ι] [is_well_order ι (<)]
local attribute [instance] is_well_order.to_has_well_founded
local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y
/-- The Gram-Schmidt process takes a set of vectors as input
and outputs a set of orthogonal vectors which have the same span. -/
noncomputable def gram_schmidt (f : ι → E) : ι → E
| n := f n - ∑ i : Iio n, orthogonal_projection (𝕜 ∙ gram_schmidt i) (f n)
using_well_founded { dec_tac := `[exact mem_Iio.1 i.2] }
/-- This lemma uses `∑ i in` instead of `∑ i :`.-/
lemma gram_schmidt_def (f : ι → E) (n : ι):
gram_schmidt 𝕜 f n = f n - ∑ i in Iio n,
orthogonal_projection (𝕜 ∙ gram_schmidt 𝕜 f i) (f n) :=
by { rw [←sum_attach, attach_eq_univ, gram_schmidt], refl }
lemma gram_schmidt_def' (f : ι → E) (n : ι):
f n = gram_schmidt 𝕜 f n + ∑ i in Iio n,
orthogonal_projection (𝕜 ∙ gram_schmidt 𝕜 f i) (f n) :=
by rw [gram_schmidt_def, sub_add_cancel]
lemma gram_schmidt_def'' (f : ι → E) (n : ι):
f n = gram_schmidt 𝕜 f n
+ ∑ i in Iio n, (⟪gram_schmidt 𝕜 f i, f n⟫ / ‖gram_schmidt 𝕜 f i‖ ^ 2) • gram_schmidt 𝕜 f i :=
begin
convert gram_schmidt_def' 𝕜 f n,
ext i,
rw orthogonal_projection_singleton,
end
@[simp] lemma gram_schmidt_zero {ι : Type*} [linear_order ι] [locally_finite_order ι]
[order_bot ι] [is_well_order ι (<)] (f : ι → E) : gram_schmidt 𝕜 f ⊥ = f ⊥ :=
by rw [gram_schmidt_def, Iio_eq_Ico, finset.Ico_self, finset.sum_empty, sub_zero]
/-- **Gram-Schmidt Orthogonalisation**:
`gram_schmidt` produces an orthogonal system of vectors. -/
theorem gram_schmidt_orthogonal (f : ι → E) {a b : ι} (h₀ : a ≠ b) :
⟪gram_schmidt 𝕜 f a, gram_schmidt 𝕜 f b⟫ = 0 :=
begin
suffices : ∀ a b : ι, a < b → ⟪gram_schmidt 𝕜 f a, gram_schmidt 𝕜 f b⟫ = 0,
{ cases h₀.lt_or_lt with ha hb,
{ exact this _ _ ha, },
{ rw inner_eq_zero_symm,
exact this _ _ hb, }, },
clear h₀ a b,
intros a b h₀,
revert a,
apply well_founded.induction (@is_well_founded.wf ι (<) _) b,
intros b ih a h₀,
simp only [gram_schmidt_def 𝕜 f b, inner_sub_right, inner_sum,
orthogonal_projection_singleton, inner_smul_right],
rw finset.sum_eq_single_of_mem a (finset.mem_Iio.mpr h₀),
{ by_cases h : gram_schmidt 𝕜 f a = 0,
{ simp only [h, inner_zero_left, zero_div, zero_mul, sub_zero], },
{ rw [← inner_self_eq_norm_sq_to_K, div_mul_cancel, sub_self],
rwa [inner_self_ne_zero], }, },
simp_intros i hi hia only [finset.mem_range],
simp only [mul_eq_zero, div_eq_zero_iff, inner_self_eq_zero],
right,
cases hia.lt_or_lt with hia₁ hia₂,
{ rw inner_eq_zero_symm,
exact ih a h₀ i hia₁ },
{ exact ih i (mem_Iio.1 hi) a hia₂ }
end
/-- This is another version of `gram_schmidt_orthogonal` using `pairwise` instead. -/
theorem gram_schmidt_pairwise_orthogonal (f : ι → E) :
pairwise (λ a b, ⟪gram_schmidt 𝕜 f a, gram_schmidt 𝕜 f b⟫ = 0) :=
λ a b, gram_schmidt_orthogonal 𝕜 f
lemma gram_schmidt_inv_triangular (v : ι → E) {i j : ι} (hij : i < j) :
⟪gram_schmidt 𝕜 v j, v i⟫ = 0 :=
begin
rw gram_schmidt_def'' 𝕜 v,
simp only [inner_add_right, inner_sum, inner_smul_right],
set b : ι → E := gram_schmidt 𝕜 v,
convert zero_add (0:𝕜),
{ exact gram_schmidt_orthogonal 𝕜 v hij.ne' },
apply finset.sum_eq_zero,
rintros k hki',
have hki : k < i := by simpa using hki',
have : ⟪b j, b k⟫ = 0 := gram_schmidt_orthogonal 𝕜 v (hki.trans hij).ne',
simp [this],
end
open submodule set order
lemma mem_span_gram_schmidt (f : ι → E) {i j : ι} (hij : i ≤ j) :
f i ∈ span 𝕜 (gram_schmidt 𝕜 f '' Iic j) :=
begin
rw [gram_schmidt_def' 𝕜 f i],
simp_rw orthogonal_projection_singleton,
exact submodule.add_mem _ (subset_span $ mem_image_of_mem _ hij)
(submodule.sum_mem _ $ λ k hk, smul_mem (span 𝕜 (gram_schmidt 𝕜 f '' Iic j)) _ $
subset_span $ mem_image_of_mem (gram_schmidt 𝕜 f) $ (finset.mem_Iio.1 hk).le.trans hij),
end
lemma gram_schmidt_mem_span (f : ι → E) :
∀ {j i}, i ≤ j → gram_schmidt 𝕜 f i ∈ span 𝕜 (f '' Iic j)
| j := λ i hij,
begin
rw [gram_schmidt_def 𝕜 f i],
simp_rw orthogonal_projection_singleton,
refine submodule.sub_mem _ (subset_span (mem_image_of_mem _ hij))
(submodule.sum_mem _ $ λ k hk, _),
let hkj : k < j := (finset.mem_Iio.1 hk).trans_le hij,
exact smul_mem _ _ (span_mono (image_subset f $ Iic_subset_Iic.2 hkj.le) $
gram_schmidt_mem_span le_rfl),
end
using_well_founded { dec_tac := `[assumption] }
lemma span_gram_schmidt_Iic (f : ι → E) (c : ι) :
span 𝕜 (gram_schmidt 𝕜 f '' Iic c) = span 𝕜 (f '' Iic c) :=
span_eq_span (set.image_subset_iff.2 $ λ i, gram_schmidt_mem_span _ _) $
set.image_subset_iff.2 $ λ i, mem_span_gram_schmidt _ _
lemma span_gram_schmidt_Iio (f : ι → E) (c : ι) :
span 𝕜 (gram_schmidt 𝕜 f '' Iio c) = span 𝕜 (f '' Iio c) :=
span_eq_span
(set.image_subset_iff.2 $ λ i hi, span_mono (image_subset _ $ Iic_subset_Iio.2 hi) $
gram_schmidt_mem_span _ _ le_rfl) $
set.image_subset_iff.2 $ λ i hi, span_mono (image_subset _ $ Iic_subset_Iio.2 hi) $
mem_span_gram_schmidt _ _ le_rfl
/-- `gram_schmidt` preserves span of vectors. -/
lemma span_gram_schmidt (f : ι → E) : span 𝕜 (range (gram_schmidt 𝕜 f)) = span 𝕜 (range f) :=
span_eq_span (range_subset_iff.2 $ λ i, span_mono (image_subset_range _ _) $
gram_schmidt_mem_span _ _ le_rfl) $
range_subset_iff.2 $ λ i, span_mono (image_subset_range _ _) $ mem_span_gram_schmidt _ _ le_rfl
lemma gram_schmidt_of_orthogonal {f : ι → E} (hf : pairwise (λ i j, ⟪f i, f j⟫ = 0)) :
gram_schmidt 𝕜 f = f :=
begin
ext i,
rw gram_schmidt_def,
transitivity f i - 0,
{ congr,
apply finset.sum_eq_zero,
intros j hj,
rw coe_eq_zero,
suffices : span 𝕜 (f '' set.Iic j) ≤ (𝕜 ∙ f i)ᗮ,
{ apply orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero,
rw mem_orthogonal_singleton_iff_inner_left,
rw ←mem_orthogonal_singleton_iff_inner_right,
exact this (gram_schmidt_mem_span 𝕜 f (le_refl j)) },
rw span_le,
rintros - ⟨k, hk, rfl⟩,
rw [set_like.mem_coe, mem_orthogonal_singleton_iff_inner_left],
apply hf,
refine (lt_of_le_of_lt hk _).ne,
simpa using hj },
{ simp },
end
variables {𝕜}
lemma gram_schmidt_ne_zero_coe
{f : ι → E} (n : ι) (h₀ : linear_independent 𝕜 (f ∘ (coe : set.Iic n → ι))) :
gram_schmidt 𝕜 f n ≠ 0 :=
begin
by_contra h,
have h₁ : f n ∈ span 𝕜 (f '' Iio n),
{ rw [← span_gram_schmidt_Iio 𝕜 f n, gram_schmidt_def' _ f, h, zero_add],
apply submodule.sum_mem _ _,
simp_intros a ha only [finset.mem_Ico],
simp only [set.mem_image, set.mem_Iio, orthogonal_projection_singleton],
apply submodule.smul_mem _ _ _,
rw finset.mem_Iio at ha,
refine subset_span ⟨a, ha, by refl⟩ },
have h₂ : (f ∘ (coe : set.Iic n → ι)) ⟨n, le_refl n⟩
∈ span 𝕜 (f ∘ (coe : set.Iic n → ι) '' Iio ⟨n, le_refl n⟩),
{ rw [image_comp],
convert h₁ using 3,
ext i,
simpa using @le_of_lt _ _ i n },
apply linear_independent.not_mem_span_image h₀ _ h₂,
simp only [set.mem_Iio, lt_self_iff_false, not_false_iff]
end
/-- If the input vectors of `gram_schmidt` are linearly independent,
then the output vectors are non-zero. -/
lemma gram_schmidt_ne_zero {f : ι → E} (n : ι) (h₀ : linear_independent 𝕜 f) :
gram_schmidt 𝕜 f n ≠ 0 :=
gram_schmidt_ne_zero_coe _ (linear_independent.comp h₀ _ subtype.coe_injective)
/-- `gram_schmidt` produces a triangular matrix of vectors when given a basis. -/
lemma gram_schmidt_triangular {i j : ι} (hij : i < j) (b : basis ι 𝕜 E) :
b.repr (gram_schmidt 𝕜 b i) j = 0 :=
begin
have : gram_schmidt 𝕜 b i ∈ span 𝕜 (gram_schmidt 𝕜 b '' set.Iio j),
from subset_span ((set.mem_image _ _ _).2 ⟨i, hij, rfl⟩),
have : gram_schmidt 𝕜 b i ∈ span 𝕜 (b '' set.Iio j),
by rwa [← span_gram_schmidt_Iio 𝕜 b j],
have : ↑(((b.repr) (gram_schmidt 𝕜 b i)).support) ⊆ set.Iio j,
from basis.repr_support_subset_of_mem_span b (set.Iio j) this,
exact (finsupp.mem_supported' _ _).1
((finsupp.mem_supported 𝕜 _).2 this) j set.not_mem_Iio_self,
end
/-- `gram_schmidt` produces linearly independent vectors when given linearly independent vectors. -/
lemma gram_schmidt_linear_independent {f : ι → E} (h₀ : linear_independent 𝕜 f) :
linear_independent 𝕜 (gram_schmidt 𝕜 f) :=
linear_independent_of_ne_zero_of_inner_eq_zero
(λ i, gram_schmidt_ne_zero _ h₀) (λ i j, gram_schmidt_orthogonal 𝕜 f)
/-- When given a basis, `gram_schmidt` produces a basis. -/
noncomputable def gram_schmidt_basis (b : basis ι 𝕜 E) : basis ι 𝕜 E :=
basis.mk
(gram_schmidt_linear_independent b.linear_independent)
((span_gram_schmidt 𝕜 b).trans b.span_eq).ge
lemma coe_gram_schmidt_basis (b : basis ι 𝕜 E) :
(gram_schmidt_basis b : ι → E) = gram_schmidt 𝕜 b := basis.coe_mk _ _
variables (𝕜)
/-- the normalized `gram_schmidt`
(i.e each vector in `gram_schmidt_normed` has unit length.) -/
noncomputable def gram_schmidt_normed (f : ι → E) (n : ι) : E :=
(‖gram_schmidt 𝕜 f n‖ : 𝕜)⁻¹ • (gram_schmidt 𝕜 f n)
variables {𝕜}
lemma gram_schmidt_normed_unit_length_coe
{f : ι → E} (n : ι) (h₀ : linear_independent 𝕜 (f ∘ (coe : set.Iic n → ι))) :
‖gram_schmidt_normed 𝕜 f n‖ = 1 :=
by simp only [gram_schmidt_ne_zero_coe n h₀,
gram_schmidt_normed, norm_smul_inv_norm, ne.def, not_false_iff]
lemma gram_schmidt_normed_unit_length {f : ι → E} (n : ι) (h₀ : linear_independent 𝕜 f) :
‖gram_schmidt_normed 𝕜 f n‖ = 1 :=
gram_schmidt_normed_unit_length_coe _ (linear_independent.comp h₀ _ subtype.coe_injective)
lemma gram_schmidt_normed_unit_length' {f : ι → E} {n : ι} (hn : gram_schmidt_normed 𝕜 f n ≠ 0) :
‖gram_schmidt_normed 𝕜 f n‖ = 1 :=
begin
rw gram_schmidt_normed at *,
rw [norm_smul_inv_norm],
simpa using hn,
end
/-- **Gram-Schmidt Orthonormalization**:
`gram_schmidt_normed` applied to a linearly independent set of vectors produces an orthornormal
system of vectors. -/
theorem gram_schmidt_orthonormal {f : ι → E} (h₀ : linear_independent 𝕜 f) :
orthonormal 𝕜 (gram_schmidt_normed 𝕜 f) :=
begin
unfold orthonormal,
split,
{ simp only [gram_schmidt_normed_unit_length, h₀, eq_self_iff_true, implies_true_iff], },
{ intros i j hij,
simp only [gram_schmidt_normed, inner_smul_left, inner_smul_right, is_R_or_C.conj_inv,
is_R_or_C.conj_of_real, mul_eq_zero, inv_eq_zero, is_R_or_C.of_real_eq_zero, norm_eq_zero],
repeat { right },
exact gram_schmidt_orthogonal 𝕜 f hij }
end
/-- **Gram-Schmidt Orthonormalization**:
`gram_schmidt_normed` produces an orthornormal system of vectors after removing the vectors which
become zero in the process. -/
lemma gram_schmidt_orthonormal' (f : ι → E) :
orthonormal 𝕜 (λ i : {i | gram_schmidt_normed 𝕜 f i ≠ 0}, gram_schmidt_normed 𝕜 f i) :=
begin
refine ⟨λ i, gram_schmidt_normed_unit_length' i.prop, _⟩,
rintros i j (hij : ¬ _),
rw subtype.ext_iff at hij,
simp [gram_schmidt_normed, inner_smul_left, inner_smul_right, gram_schmidt_orthogonal 𝕜 f hij],
end
lemma span_gram_schmidt_normed (f : ι → E) (s : set ι) :
span 𝕜 (gram_schmidt_normed 𝕜 f '' s) = span 𝕜 (gram_schmidt 𝕜 f '' s) :=
begin
refine span_eq_span (set.image_subset_iff.2 $ λ i hi, smul_mem _ _ $ subset_span $
mem_image_of_mem _ hi)
(set.image_subset_iff.2 $ λ i hi, span_mono (image_subset _ $ singleton_subset_set_iff.2 hi) _),
simp only [coe_singleton, set.image_singleton],
by_cases h : gram_schmidt 𝕜 f i = 0,
{ simp [h] },
{ refine mem_span_singleton.2 ⟨‖gram_schmidt 𝕜 f i‖, smul_inv_smul₀ _ _⟩,
exact_mod_cast (norm_ne_zero_iff.2 h) }
end
lemma span_gram_schmidt_normed_range (f : ι → E) :
span 𝕜 (range (gram_schmidt_normed 𝕜 f)) = span 𝕜 (range (gram_schmidt 𝕜 f)) :=
by simpa only [image_univ.symm] using span_gram_schmidt_normed f univ
section orthonormal_basis
variables [fintype ι] [finite_dimensional 𝕜 E] (h : finrank 𝕜 E = fintype.card ι) (f : ι → E)
include h
/-- Given an indexed family `f : ι → E` of vectors in an inner product space `E`, for which the
size of the index set is the dimension of `E`, produce an orthonormal basis for `E` which agrees
with the orthonormal set produced by the Gram-Schmidt orthonormalization process on the elements of
`ι` for which this process gives a nonzero number. -/
noncomputable def gram_schmidt_orthonormal_basis : orthonormal_basis ι 𝕜 E :=
((gram_schmidt_orthonormal' f).exists_orthonormal_basis_extension_of_card_eq h).some
lemma gram_schmidt_orthonormal_basis_apply {f : ι → E} {i : ι}
(hi : gram_schmidt_normed 𝕜 f i ≠ 0) :
gram_schmidt_orthonormal_basis h f i = gram_schmidt_normed 𝕜 f i :=
((gram_schmidt_orthonormal' f).exists_orthonormal_basis_extension_of_card_eq h).some_spec i hi
lemma gram_schmidt_orthonormal_basis_apply_of_orthogonal {f : ι → E}
(hf : pairwise (λ i j, ⟪f i, f j⟫ = 0)) {i : ι} (hi : f i ≠ 0) :
gram_schmidt_orthonormal_basis h f i = (‖f i‖⁻¹ : 𝕜) • f i :=
begin
have H : gram_schmidt_normed 𝕜 f i = (‖f i‖⁻¹ : 𝕜) • f i,
{ rw [gram_schmidt_normed, gram_schmidt_of_orthogonal 𝕜 hf] },
rw [gram_schmidt_orthonormal_basis_apply h, H],
simpa [H] using hi,
end
lemma inner_gram_schmidt_orthonormal_basis_eq_zero {f : ι → E} {i : ι}
(hi : gram_schmidt_normed 𝕜 f i = 0) (j : ι) :
⟪gram_schmidt_orthonormal_basis h f i, f j⟫ = 0 :=
begin
rw ←mem_orthogonal_singleton_iff_inner_right,
suffices : span 𝕜 (gram_schmidt_normed 𝕜 f '' Iic j)
≤ (𝕜 ∙ gram_schmidt_orthonormal_basis h f i)ᗮ,
{ apply this,
rw span_gram_schmidt_normed,
simpa using mem_span_gram_schmidt 𝕜 f (le_refl j) },
rw span_le,
rintros - ⟨k, -, rfl⟩,
rw [set_like.mem_coe, mem_orthogonal_singleton_iff_inner_left],
by_cases hk : gram_schmidt_normed 𝕜 f k = 0,
{ simp [hk] },
rw ← gram_schmidt_orthonormal_basis_apply h hk,
have : k ≠ i,
{ rintros rfl,
exact hk hi },
exact (gram_schmidt_orthonormal_basis h f).orthonormal.2 this,
end
lemma gram_schmidt_orthonormal_basis_inv_triangular {i j : ι} (hij : i < j) :
⟪gram_schmidt_orthonormal_basis h f j, f i⟫ = 0 :=
begin
by_cases hi : gram_schmidt_normed 𝕜 f j = 0,
{ rw inner_gram_schmidt_orthonormal_basis_eq_zero h hi },
{ simp [gram_schmidt_orthonormal_basis_apply h hi, gram_schmidt_normed, inner_smul_left,
gram_schmidt_inv_triangular 𝕜 f hij] }
end
lemma gram_schmidt_orthonormal_basis_inv_triangular' {i j : ι} (hij : i < j) :
(gram_schmidt_orthonormal_basis h f).repr (f i) j = 0 :=
by simpa [orthonormal_basis.repr_apply_apply]
using gram_schmidt_orthonormal_basis_inv_triangular h f hij
/-- Given an indexed family `f : ι → E` of vectors in an inner product space `E`, for which the
size of the index set is the dimension of `E`, the matrix of coefficients of `f` with respect to the
orthonormal basis `gram_schmidt_orthonormal_basis` constructed from `f` is upper-triangular. -/
lemma gram_schmidt_orthonormal_basis_inv_block_triangular :
((gram_schmidt_orthonormal_basis h f).to_basis.to_matrix f).block_triangular id :=
λ i j, gram_schmidt_orthonormal_basis_inv_triangular' h f
lemma gram_schmidt_orthonormal_basis_det :
(gram_schmidt_orthonormal_basis h f).to_basis.det f =
∏ i, ⟪gram_schmidt_orthonormal_basis h f i, f i⟫ :=
begin
convert matrix.det_of_upper_triangular (gram_schmidt_orthonormal_basis_inv_block_triangular h f),
ext i,
exact ((gram_schmidt_orthonormal_basis h f).repr_apply_apply (f i) i).symm,
end
end orthonormal_basis
|
module Categories.Monad.EilenbergMoore where
|
section {*L\_ATS\_Simulation\_Configuration\_WeakLR\_Unmarked\_Effect*}
theory
L_ATS_Simulation_Configuration_WeakLR_Unmarked_Effect
imports
L_ATS_Simulation_Configuration_Weak
begin
locale ATS_Simulation_Configuration_Weak_Unmarked_Effect =
ATS_Simulation_Configuration_Weak
"TSstructure1 :: 'TSstructure1 \<Rightarrow> bool"
"configurations1 :: 'TSstructure1 \<Rightarrow> 'conf1 set"
"initial_configurations1 :: 'TSstructure1 \<Rightarrow> 'conf1 set"
"step_labels1 :: 'TSstructure1 \<Rightarrow> 'label1 set"
"step_relation1 :: 'TSstructure1 \<Rightarrow> 'conf1 \<Rightarrow> 'label1 \<Rightarrow> 'conf1 \<Rightarrow> bool"
"effects1 :: 'TSstructure1 \<Rightarrow> 'event1 set"
"marking_condition1 :: 'TSstructure1 \<Rightarrow> ('label1,'conf1)derivation \<Rightarrow> bool"
"marked_effect1 :: 'TSstructure1 \<Rightarrow> ('label1,'conf1)derivation \<Rightarrow> 'event1 set"
"unmarked_effect1 :: 'TSstructure1 \<Rightarrow> ('label1,'conf1)derivation \<Rightarrow> 'event1 set"
"TSstructure2 :: 'TSstructure2 \<Rightarrow> bool"
"configurations2 :: 'TSstructure2 \<Rightarrow> 'conf2 set"
"initial_configurations2 :: 'TSstructure2 \<Rightarrow> 'conf2 set"
"step_labels2 :: 'TSstructure2 \<Rightarrow> 'label2 set"
"step_relation2 :: 'TSstructure2 \<Rightarrow> 'conf2 \<Rightarrow> 'label2 \<Rightarrow> 'conf2 \<Rightarrow> bool"
"effects2 :: 'TSstructure2 \<Rightarrow> 'event2 set"
"marking_condition2 :: 'TSstructure2 \<Rightarrow> ('label2,'conf2)derivation \<Rightarrow> bool"
"marked_effect2 :: 'TSstructure2 \<Rightarrow> ('label2,'conf2)derivation \<Rightarrow> 'event2 set"
"unmarked_effect2 :: 'TSstructure2 \<Rightarrow> ('label2,'conf2)derivation \<Rightarrow> 'event2 set"
"relation_configuration :: 'TSstructure1 \<Rightarrow> 'TSstructure2 \<Rightarrow> 'conf1 \<Rightarrow> 'conf2 \<Rightarrow> bool"
"relation_initial_configuration :: 'TSstructure1 \<Rightarrow> 'TSstructure2 \<Rightarrow> 'conf1 \<Rightarrow> 'conf2 \<Rightarrow> bool"
"relation_effect :: 'TSstructure1 \<Rightarrow> 'TSstructure2 \<Rightarrow> 'event1 \<Rightarrow> 'event2 \<Rightarrow> bool"
"relation_TSstructure :: 'TSstructure1 \<Rightarrow> 'TSstructure2 \<Rightarrow> bool"
"relation_initial_simulation :: 'TSstructure1 \<Rightarrow> 'TSstructure2 \<Rightarrow> 'conf1 \<Rightarrow> (nat \<Rightarrow> ('label2, 'conf2) derivation_configuration option) \<Rightarrow> bool"
"relation_step_simulation :: 'TSstructure1 \<Rightarrow> 'TSstructure2 \<Rightarrow> 'conf1 \<Rightarrow> 'label1 \<Rightarrow> 'conf1 \<Rightarrow> 'conf2 \<Rightarrow> (nat \<Rightarrow> ('label2, 'conf2) derivation_configuration option) \<Rightarrow> bool"
for
TSstructure1 configurations1 initial_configurations1 step_labels1 step_relation1 effects1 marking_condition1 marked_effect1 unmarked_effect1 TSstructure2 configurations2 initial_configurations2 step_labels2 step_relation2 effects2 marking_condition2 marked_effect2 unmarked_effect2 relation_configuration relation_initial_configuration relation_effect relation_TSstructure relation_initial_simulation relation_step_simulation
+
assumes AX_relation_step_simulation_preserves_unmarked_effect: "
relation_step_simulation_preservation G1 G2 d1' d2'
\<Longrightarrow> left_total_on
(relation_effect G1 G2)
(unmarked_effect1 G1 d1')
(unmarked_effect2 G2 d2')"
assumes AX_relation_initial_simulation_preserves_unmarked_effect: "
relation_initial_simulation_preservation G1 G2 d1' d2'
\<Longrightarrow> left_total_on
(relation_effect G1 G2)
(unmarked_effect1 G1 d1')
(unmarked_effect2 G2 d2')"
context ATS_Simulation_Configuration_Weak_Unmarked_Effect begin
theorem ATS_Simulation_Configuration_Weak_Unmarked_Effect_sound: "
relation_TSstructure G1 G2
\<Longrightarrow> left_total_on (relation_effect G1 G2) (GL.finite_unmarked_language G1) (GR.finite_unmarked_language G2)"
apply(simp add: left_total_on_def)
apply(clarsimp)
apply(rename_tac a)(*strict*)
apply(simp add: GL.finite_unmarked_language_def)
apply(clarsimp)
apply(rename_tac a d x)(*strict*)
apply(case_tac x)
apply(rename_tac a d x)(*strict*)
apply(clarsimp)
apply(rename_tac a d)(*strict*)
apply(subgoal_tac "\<exists>c. d 0 = Some (pair None c)")
apply(rename_tac a d)(*strict*)
apply(clarsimp)
apply(rename_tac a d c)(*strict*)
apply(rename_tac c1)
apply(rename_tac a d c1)(*strict*)
apply(subgoal_tac "c1 \<in> initial_configurations1 G1")
apply(rename_tac a d c1)(*strict*)
prefer 2
apply(simp add: GL.derivation_initial_def)
apply(rename_tac a d c1)(*strict*)
apply(subgoal_tac "\<exists>ds n. GR.derivation_initial G2 ds \<and> relation_initial_configuration G1 G2 c1 (the(get_configuration(ds 0))) \<and> relation_initial_simulation G1 G2 c1 ds \<and> maximum_of_domain ds n \<and> relation_configuration G1 G2 c1 (the(get_configuration(ds n)))")
apply(rename_tac a d c1)(*strict*)
prefer 2
apply(rule AX_relation_initial_simulation)
apply(rename_tac a d c1)(*strict*)
apply(force)
apply(rename_tac a d c1)(*strict*)
apply(force)
apply(rename_tac a d c1)(*strict*)
apply(clarsimp)
apply(rename_tac a d c1 ds n)(*strict*)
apply(subgoal_tac "\<exists>c2. ds 0 = Some (pair None c2)")
apply(rename_tac a d c1 ds n)(*strict*)
apply(clarsimp)
apply(rename_tac a d c1 ds n c2)(*strict*)
apply(subgoal_tac "left_total_on (relation_effect G1 G2) (unmarked_effect1 G1 (derivation_append (der1 c1) (der1 c1) 0)) (unmarked_effect2 G2 (derivation_append (der1 (the(get_configuration(ds 0)))) ds 0))")
apply(rename_tac a d c1 ds n c2)(*strict*)
prefer 2
apply(rule AX_relation_initial_simulation_preserves_unmarked_effect)
apply(rule relation_initial_simulation_preservation_PROVE)
apply(rename_tac a d c1 ds n c2)(*strict*)
prefer 13
apply(force)
apply(rename_tac a d c1 ds n c2)(*strict*)
prefer 12
apply(force)
apply(rename_tac a d c1 ds n c2)(*strict*)
apply(force)
apply(rename_tac a d c1 ds n c2)(*strict*)
apply(force)
apply(rename_tac a d c1 ds n c2)(*strict*)
apply(force)
apply(rename_tac a d c1 ds n c2)(*strict*)
apply(force)
apply(rename_tac a d c1 ds n c2)(*strict*)
apply(simp add: GL.derivation_initial_def)
apply(rule conjI)
apply(rename_tac a d c1 ds n c2)(*strict*)
apply(rule GL.der1_is_derivation)
apply(rename_tac a d c1 ds n c2)(*strict*)
apply(simp add: der1_def)
apply(rename_tac a d c1 ds n c2)(*strict*)
apply(rule der1_maximum_of_domain)
apply(rename_tac a d c1 ds n c2)(*strict*)
apply(simp add: GR.derivation_initial_def)
apply(rule conjI)
apply(rename_tac a d c1 ds n c2)(*strict*)
apply(rule GR.der1_is_derivation)
apply(rename_tac a d c1 ds n c2)(*strict*)
apply(simp add: der1_def get_configuration_def)
apply(rename_tac a d c1 ds n c2)(*strict*)
apply(rule der1_maximum_of_domain)
apply(rename_tac a d c1 ds n c2)(*strict*)
apply(simp add: der1_def get_configuration_def)
apply(rename_tac a d c1 ds n c2)(*strict*)
apply(simp add: derivation_append_fit_def der1_def)
apply(rename_tac a d c1 ds n c2)(*strict*)
apply(simp add: derivation_append_fit_def der1_def get_configuration_def)
apply(rename_tac a d c1 ds n c2)(*strict*)
apply(rule_tac
t="Some (pair None c2)"
and s="ds 0"
in ssubst)
apply(rename_tac a d c1 ds n c2)(*strict*)
apply(simp add: derivation_append_fit_def der1_def get_configuration_def)
apply(rename_tac a d c1 ds n c2)(*strict*)
apply(rule simulating_derivation_exist_initial)
apply(rename_tac a d c1 ds n c2)(*strict*)
apply(force)
apply(rename_tac a d c1 ds n c2)(*strict*)
apply(force)
apply(rename_tac a d c1 ds n c2)(*strict*)
apply(force)
apply(rename_tac a d c1 ds n c2)(*strict*)
apply(force)
apply(rename_tac a d c1 ds n c2)(*strict*)
apply(force)
apply(rename_tac a d c1 ds n c2)(*strict*)
apply(subgoal_tac "left_total_on (relation_effect G1 G2) (unmarked_effect1 G1 d) (unmarked_effect2 G2 ds)")
apply(rename_tac a d c1 ds n c2)(*strict*)
prefer 2
apply(rule_tac
t="d"
and s="derivation_append (der1 c1) (der1 c1) 0"
in ssubst)
apply(rename_tac a d c1 ds n c2)(*strict*)
apply(rule ext)
apply(rename_tac a d c1 ds n c2 x)(*strict*)
apply(simp add: derivation_append_def der1_def)
apply(clarsimp)
apply (metis GL.derivation_initial_is_derivation GL.noSomeAfterMaxDom)
apply(rename_tac a d c1 ds n c2)(*strict*)
apply(rule_tac
t="ds"
and s="derivation_append (der1 (the (get_configuration (Some (pair None c2))))) ds 0"
in ssubst)
apply(rename_tac a d c1 ds n c2)(*strict*)
apply(rule ext)
apply(rename_tac a d c1 ds n c2 x)(*strict*)
apply(simp add: derivation_append_def der1_def get_configuration_def)
apply(rename_tac a d c1 ds n c2)(*strict*)
apply(force)
apply(rename_tac a d c1 ds n c2)(*strict*)
apply(thin_tac "left_total_on (relation_effect G1 G2) (unmarked_effect1 G1 (derivation_append (der1 c1) (der1 c1) 0)) (unmarked_effect2 G2 (derivation_append (der1 (the (get_configuration (ds 0)))) ds 0))")
apply(rename_tac a d c1 ds n c2)(*strict*)
apply(simp add: left_total_on_def)
apply(erule_tac
x="a"
in ballE)
apply(rename_tac a d c1 ds n c2)(*strict*)
apply(clarsimp)
apply(rename_tac a d c1 ds n c2 b)(*strict*)
apply(rule_tac
x="b"
in bexI)
apply(rename_tac a d c1 ds n c2 b)(*strict*)
apply(force)
apply(rename_tac a d c1 ds n c2 b)(*strict*)
apply(simp add: GR.finite_unmarked_language_def)
apply(rule_tac
x="ds"
in exI)
apply(clarsimp)
apply (metis)
apply(rename_tac a d c1 ds n c2)(*strict*)
apply(force)
apply(rename_tac a d c1 ds n)(*strict*)
apply (metis GR.derivation_initial_is_derivation GR.some_position_has_details_at_0)
apply(rename_tac a d)(*strict*)
apply (metis GL.derivation_initial_is_derivation GL.some_position_has_details_at_0)
apply(rename_tac a d x nat)(*strict*)
apply(clarsimp)
apply(rename_tac a d nat)(*strict*)
apply(rename_tac x)
apply(rename_tac a d x)(*strict*)
apply(subgoal_tac "\<exists>e1 e2 c1 c2. d x = Some (pair e1 c1) \<and> d (Suc x) = Some (pair (Some e2) c2) \<and> step_relation1 G1 c1 e2 c2")
apply(rename_tac a d x)(*strict*)
prefer 2
apply(rule_tac
m="Suc x"
in GL.step_detail_before_some_position)
apply(rename_tac a d x)(*strict*)
apply(rule GL.derivation_initial_is_derivation)
apply(force)
apply(rename_tac a d x)(*strict*)
apply(simp add: maximum_of_domain_def)
apply(rename_tac a d x)(*strict*)
apply(force)
apply(rename_tac a d x)(*strict*)
apply(clarsimp)
apply(rename_tac a d x e1 e2 c1 c2)(*strict*)
apply(rename_tac e0 e1 c1 c1')
apply(rename_tac a d x e0 e1 c1 c1')(*strict*)
apply(subgoal_tac "\<exists>d2 n2 f. GR.derivation_initial G2 d2 \<and> maximum_of_domain d2 n2 \<and> relation_initial_configuration G1 G2 (the(get_configuration(d 0))) (the(get_configuration(d2 0))) \<and> relation_configuration G1 G2 c1 (the(get_configuration(d2 n2))) \<and> simulating_derivation G1 G2 d x d2 n2 f")
apply(rename_tac a d x e0 e1 c1 c1')(*strict*)
prefer 2
apply(rule ATS_Simulation_Configuration_Weak_simulation_derivation_exists_witness)
apply(rename_tac a d x e0 e1 c1 c1')(*strict*)
apply(force)
apply(rename_tac a d x e0 e1 c1 c1')(*strict*)
apply(force)
apply(rename_tac a d x e0 e1 c1 c1')(*strict*)
apply(force)
apply(rename_tac a d x e0 e1 c1 c1')(*strict*)
apply(clarsimp)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 xa)(*strict*)
apply(rename_tac f)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f)(*strict*)
apply(subgoal_tac "\<exists>e c. d2 n2 = Some (pair e c)")
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f)(*strict*)
apply(clarsimp)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e c)(*strict*)
apply(rename_tac c2)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e c2)(*strict*)
apply(subgoal_tac "\<exists>ds n. GR.derivation G2 ds \<and> GR.belongs G2 ds \<and> the(get_configuration(ds 0)) = c2 \<and> relation_step_simulation G1 G2 c1 e1 c1' c2 ds \<and> maximum_of_domain ds n \<and> relation_configuration G1 G2 c1' (the(get_configuration(ds n)))")
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e c2)(*strict*)
prefer 2
apply(rule AX_relation_step_simulation)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e c2)(*strict*)
apply(force)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e c2)(*strict*)
apply(simp add: get_configuration_def)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e c2)(*strict*)
apply (metis GL.belongs_step_labels GL.derivation_initial_belongs AX_TSstructure_relation_TSstructure1_belongs)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e c2)(*strict*)
apply(force)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e c2)(*strict*)
apply(clarsimp)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n)(*strict*)
apply(subgoal_tac "\<exists>c2. ds 0 = Some (pair None c2)")
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n)(*strict*)
apply(clarsimp)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2)(*strict*)
apply(subgoal_tac "left_total_on (relation_effect G1 G2) (unmarked_effect1 G1 (derivation_append SSd1 (der2 c1 e1 c1') SSn1)) (unmarked_effect2 G2 (derivation_append SSd2 ds SSn2))" for SSd1 SSn1 SSd2 SSn2)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2)(*strict*)
prefer 2
apply(rule AX_relation_step_simulation_preserves_unmarked_effect)
apply(rule_tac
?d1.0="derivation_take d x"
and ?d2.0="d2"
and ?n1.0="x"
and ?n2.0="n2"
and f="\<lambda>a. if a \<le> x then f a else f x + n"
in relation_step_simulation_preservation_PROVE)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2)(*strict*)
prefer 14
apply(force)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2)(*strict*)
prefer 14
apply(force)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2)(*strict*)
apply(force)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2)(*strict*)
apply(force)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2)(*strict*)
apply (metis GL.belongs_step_labels GL.derivation_initial_belongs AX_TSstructure_relation_TSstructure1_belongs)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2)(*strict*)
apply(force)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2)(*strict*)
apply(simp add: get_configuration_def)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2)(*strict*)
apply(force)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2)(*strict*)
apply (metis GL.derivation_take_preserves_derivation_initial)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2)(*strict*)
apply (metis GL.derivationNoFromNone GL.derivation_initial_is_derivation maximum_of_domain_derivation_take)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2)(*strict*)
apply(force)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2)(*strict*)
apply(force)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2)(*strict*)
apply(simp add: get_configuration_def derivation_take_def)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2)(*strict*)
apply(simp add: derivation_append_fit_def derivation_take_def der2_def)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2)(*strict*)
apply(simp add: derivation_append_fit_def get_configuration_def)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2)(*strict*)
apply(rule simulating_derivation_exist_step)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2)(*strict*)
apply(force)+
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2)(*strict*)
apply(subgoal_tac "left_total_on (relation_effect G1 G2) (unmarked_effect1 G1 d) (unmarked_effect2 G2 (derivation_append d2 ds n2))")
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2)(*strict*)
prefer 2
apply(rule_tac
t="d"
and s="(derivation_append (derivation_take d x) (der2 c1 e1 c1') x)"
in ssubst)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2)(*strict*)
apply(rule ext)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2 xa)(*strict*)
apply(simp add: derivation_append_def derivation_take_def der2_def)
apply(case_tac "xa-x")
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2 xa)(*strict*)
apply(clarsimp)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2 xa nat)(*strict*)
apply(clarsimp)
apply(case_tac nat)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2 xa nat)(*strict*)
apply(clarsimp)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2 xa)(*strict*)
apply(subgoal_tac "Suc x=xa")
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2 xa)(*strict*)
prefer 2
apply(force)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2 xa)(*strict*)
apply(clarsimp)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2 xa nat nata)(*strict*)
apply(clarsimp)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2 xa nata)(*strict*)
apply(subgoal_tac "xa=x+Suc(Suc nata)")
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2 xa nata)(*strict*)
prefer 2
apply(force)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2 xa nata)(*strict*)
apply(clarsimp)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2 nata)(*strict*)
apply(rule GL.none_position_after_max_dom)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2 nata)(*strict*)
apply(rule GL.derivation_initial_is_derivation)
apply(force)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2 nata)(*strict*)
apply(force)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2 nata)(*strict*)
apply(force)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2)(*strict*)
apply(force)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2)(*strict*)
apply(thin_tac "left_total_on (relation_effect G1 G2) (unmarked_effect1 G1 (derivation_append (derivation_take d x) (der2 c1 e1 c1') x)) (unmarked_effect2 G2 (derivation_append d2 ds n2))")
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2)(*strict*)
apply(simp add: left_total_on_def)
apply(erule_tac
x="a"
in ballE)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2)(*strict*)
apply(clarsimp)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2 b)(*strict*)
apply(rule_tac
x="b"
in bexI)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2 b)(*strict*)
apply(force)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2 b)(*strict*)
apply(simp add: GR.finite_unmarked_language_def)
apply(rule_tac
x="derivation_append d2 ds n2"
in exI)
apply(clarsimp)
apply(rule context_conjI)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2 b)(*strict*)
apply(rule GR.derivation_append_preserves_derivation_initial)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2 b)(*strict*)
apply (metis AX_TSstructure_relation_TSstructure2_belongs)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2 b)(*strict*)
apply(force)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2 b)(*strict*)
apply(rule GR.derivation_append_preserves_derivation)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2 b)(*strict*)
apply(rule GR.derivation_initial_is_derivation)
apply(force)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2 b)(*strict*)
apply(force)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2 b)(*strict*)
apply(clarsimp)
apply(simp add: get_configuration_def)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2 b)(*strict*)
apply(rule_tac
x="n2+n"
in exI)
apply (metis concat_has_max_dom)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n c2)(*strict*)
apply(force)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f e ds n)(*strict*)
apply (metis GR.some_position_has_details_at_0)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f)(*strict*)
apply(rule GR.some_position_has_details_before_max_dom)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f)(*strict*)
apply(rule GR.derivation_initial_is_derivation)
apply(force)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f)(*strict*)
apply(force)
apply(rename_tac a d x e0 e1 c1 c1' d2 n2 f)(*strict*)
apply(force)
done
end
end
|
# Use baremodule to shave off a few KB from the serialized `.ji` file
baremodule LCIO_Julia_Wrapper_jll
using Base
using Base: UUID
import JLLWrappers
JLLWrappers.@generate_main_file_header("LCIO_Julia_Wrapper")
JLLWrappers.@generate_main_file("LCIO_Julia_Wrapper", UUID("1fe59b3e-ae39-56b2-a121-c4c5e6ddab56"))
end # module LCIO_Julia_Wrapper_jll
|
theory ERC20
imports "../Phi_Solidity"
begin
consts Total_Supply :: nat
specification (Total_Supply)
Total_Supply_LE[useful]: \<open>Total_Supply < 2 ^ Big 256\<close>
unfolding Big_def
using less_exp by blast
context solidity begin
definition Currency :: \<open>('VAL, nat) \<phi>\<close>
where \<open>Currency = (\<lambda>x. (x \<Ztypecolon> \<nat>[256]) \<s>\<u>\<b>\<j> x \<le> Total_Supply)\<close>
lemma Currency_expn[\<phi>expns]:
\<open>(x \<Ztypecolon> Currency) = ((x \<Ztypecolon> \<nat>[256]) \<s>\<u>\<b>\<j> x \<le> Total_Supply)\<close>
unfolding \<phi>Type_def[where T=Currency]
unfolding Currency_def
..
lemma [\<phi>inhabitance_rule, elim!]:
\<open>Inhabited (x \<Ztypecolon> Currency) \<Longrightarrow> (x \<le> Total_Supply \<Longrightarrow> C) \<Longrightarrow> C\<close>
unfolding Inhabited_def
by (simp add: \<phi>expns)
lemma Currency_D[\<phi>reason on \<open>?x \<Ztypecolon> Currency \<i>\<m>\<p>\<l>\<i>\<e>\<s> ?y \<Ztypecolon> \<nat>[?b] \<a>\<n>\<d> ?P\<close>]:
\<open> \<p>\<r>\<e>\<m>\<i>\<s>\<e> x = x'
\<Longrightarrow> x \<Ztypecolon> Currency \<i>\<m>\<p>\<l>\<i>\<e>\<s> x' \<Ztypecolon> \<nat>[256] \<a>\<n>\<d> x \<le> Total_Supply\<close>
unfolding Currency_expn \<medium_left_bracket> \<medium_right_bracket>. .
lemma Currency_I[\<phi>reason on \<open>?y \<Ztypecolon> \<nat>[?b] \<i>\<m>\<p>\<l>\<i>\<e>\<s> ?x \<Ztypecolon> Currency \<a>\<n>\<d> ?P\<close>]:
\<open> \<p>\<r>\<e>\<m>\<i>\<s>\<e> x \<le> Total_Supply \<and> x = x'
\<Longrightarrow> x \<Ztypecolon> \<nat>[256] \<i>\<m>\<p>\<l>\<i>\<e>\<s> x' \<Ztypecolon> Currency\<close>
unfolding Currency_expn \<medium_left_bracket> \<medium_right_bracket>. .
lemma [\<phi>reason 1000]:
\<open>\<phi>SemType (x \<Ztypecolon> Currency) (\<tau>Int 256)\<close>
unfolding \<phi>SemType_def subset_iff
by (simp add: \<phi>expns)
(*
contract XXX
maping<Address, int256> balance;
end
*)
proc balance_of:
argument \<open>msg \<Ztypecolon> Msg\<heavy_comma>
balance \<Ztypecolon> ledge: msg.contract msg \<^bold>\<rightarrow> [\<bbbS>\<f>\<i>\<e>\<l>\<d> ''balance'', \<bbbS>\<m>\<a>\<p> (account \<Ztypecolon> Address)] \<^bold>\<rightarrow> n \<Znrres> \<fish_eye>\<lbrakk>\<tau>Int 256\<rbrakk> Currency \<heavy_comma>
\<v>\<a>\<l> account \<Ztypecolon> Address\<close>
return \<open>msg \<Ztypecolon> Msg\<heavy_comma>
balance \<Ztypecolon> ledge: msg.contract msg \<^bold>\<rightarrow> [\<bbbS>\<f>\<i>\<e>\<l>\<d> ''balance'', \<bbbS>\<m>\<a>\<p> (account \<Ztypecolon> Address)] \<^bold>\<rightarrow> n \<Znrres> \<fish_eye>\<lbrakk>\<tau>Int 256\<rbrakk> Currency \<heavy_comma>
\<v>\<a>\<l> balance \<Ztypecolon> \<nat>[256]\<close>
\<medium_left_bracket> \<rightarrow> v_account;;
op_get_msg_addr[where G=msg.contract]
op_root_ledge_ref
op_get_member_ledgeRef[where field=\<open>''balance''\<close>]
op_get_var[where vname=v_account]
op_get_mapping_ledgeRef
;;
;;op_load_ledge
thm \<phi>lemmata
thm \<phi>morphism
\<medium_right_bracket>. .
(* { P } C {} *)
(* { x : T * x2 : T2 * x3 : T3 ... \<and> P x x2 x3 } C { ... }
contract \<rightarrow> field-path \<rightarrow> value
name \<rightarrow> heap
locale
fix msg \<Ztypecolon> Msg
{ x \<Ztypecolon> T } CCCC {...}
{} FFF {}
end
balance \<Ztypecolon> ledge: (msg.contract msg \<rightarrow> Map Address
*)
proc transfer:
premises \<open>balance_receiver + amount \<le> Total_Supply\<close>
argument \<open>msg \<Ztypecolon> Msg\<heavy_comma>
balance_sender \<Ztypecolon> ledge: msg.contract msg \<^bold>\<rightarrow> [\<bbbS>\<f>\<i>\<e>\<l>\<d> ''balance'', \<bbbS>\<m>\<a>\<p> (msg.sender msg \<Ztypecolon> Address)] \<^bold>\<rightarrow> \<fish_eye>\<lbrakk>\<tau>Int 256\<rbrakk> Currency \<heavy_comma>
balance_receiver \<Ztypecolon> ledge: msg.contract msg \<^bold>\<rightarrow> [\<bbbS>\<f>\<i>\<e>\<l>\<d> ''balance'', \<bbbS>\<m>\<a>\<p> (receiver \<Ztypecolon> Address)] \<^bold>\<rightarrow> \<fish_eye>\<lbrakk>\<tau>Int 256\<rbrakk> Currency \<heavy_comma>
\<v>\<a>\<l> receiver \<Ztypecolon> Address\<heavy_comma>
\<v>\<a>\<l> amount \<Ztypecolon> \<nat>[256]\<close>
return \<open>msg \<Ztypecolon> Msg\<heavy_comma>
(if amount \<le> balance_sender then balance_sender - amount else balance_sender)
\<Ztypecolon> ledge: msg.contract msg \<^bold>\<rightarrow> [\<bbbS>\<f>\<i>\<e>\<l>\<d> ''balance'', \<bbbS>\<m>\<a>\<p> (msg.sender msg \<Ztypecolon> Address)] \<^bold>\<rightarrow> \<fish_eye>\<lbrakk>\<tau>Int 256\<rbrakk> Currency \<heavy_comma>
(if amount \<le> balance_sender then balance_receiver + amount else balance_receiver)
\<Ztypecolon> ledge: msg.contract msg \<^bold>\<rightarrow> [\<bbbS>\<f>\<i>\<e>\<l>\<d> ''balance'', \<bbbS>\<m>\<a>\<p> (receiver \<Ztypecolon> Address)] \<^bold>\<rightarrow> \<fish_eye>\<lbrakk>\<tau>Int 256\<rbrakk> Currency \<heavy_comma>
\<v>\<a>\<l> amount \<le> balance_sender \<Ztypecolon> \<bool>\<close>
\<medium_left_bracket> ;;
\<rightarrow> v_receiver, v_amount
have [useful]: \<open>balance_receiver \<le> Total_Supply\<close> \<open>balance_sender \<le> Total_Supply\<close> using \<phi> by simp+ ;;
op_get_var[where vname=v_amount]
op_get_msg_addr[where G=msg.contract]
op_root_ledge_ref
op_get_member_ledgeRef[where field=\<open>''balance''\<close>]
op_get_msg_addr[where G=msg.sender]
op_get_mapping_ledgeRef
;; op_load_ledge
thm \<phi>morphism
;; op_le \<rightarrow> ret ;;
if \<medium_left_bracket> op_get_var[where vname=ret] \<medium_right_bracket>.
\<medium_left_bracket> op_get_msg_addr[where G=msg.contract]
op_root_ledge_ref
op_get_member_ledgeRef[where field=\<open>''balance''\<close>]
op_get_msg_addr[where G=msg.sender]
op_get_mapping_ledgeRef
op_get_msg_addr[where G=msg.contract]
op_root_ledge_ref
op_get_member_ledgeRef[where field=\<open>''balance''\<close>]
op_get_msg_addr[where G=msg.sender]
op_get_mapping_ledgeRef
;;op_load_ledge
;;op_get_var[where vname=v_amount]
op_sub
thm \<phi>morphism
;;op_store_ledge
thm \<phi>morphism
;;op_get_msg_addr[where G=msg.contract]
op_root_ledge_ref
op_get_member_ledgeRef[where field=\<open>''balance''\<close>]
;;op_get_var[where vname=v_receiver]
op_get_mapping_ledgeRef
dup
;;op_load_ledge
op_get_var[where vname=v_amount]
op_add
op_store_ledge
\<medium_right_bracket>. \<medium_left_bracket> \<medium_right_bracket>.
;; op_get_var[where vname=ret]
\<medium_right_bracket>. .
proc transfer_from:
premises \<open>balance_bob + amount \<le> Total_Supply\<close>
argument \<open>msg \<Ztypecolon> Msg\<heavy_comma>
balance_alice \<Ztypecolon> ledge: msg.contract msg \<^bold>\<rightarrow> \<bbbS>\<f>\<i>\<e>\<l>\<d> ''balance'' \<^bold>\<rightarrow>\<^sub># \<bbbS>\<m>\<a>\<p> (alice \<Ztypecolon> Address) \<^bold>\<rightarrow>\<^sub>[\<^sub>] \<fish_eye>\<lbrakk>\<tau>Int 256\<rbrakk> Currency \<heavy_comma>
balance_bob \<Ztypecolon> ledge: msg.contract msg \<^bold>\<rightarrow> \<bbbS>\<f>\<i>\<e>\<l>\<d> ''balance'' \<^bold>\<rightarrow>\<^sub># \<bbbS>\<m>\<a>\<p> (bob \<Ztypecolon> Address) \<^bold>\<rightarrow>\<^sub>[\<^sub>] \<fish_eye>\<lbrakk>\<tau>Int 256\<rbrakk> Currency \<heavy_comma>
allowance \<Ztypecolon> ledge: msg.contract msg \<^bold>\<rightarrow> \<bbbS>\<f>\<i>\<e>\<l>\<d> ''allowance'' \<^bold>\<rightarrow>\<^sub># \<bbbS>\<m>\<a>\<p> (alice \<Ztypecolon> Address) \<^bold>\<rightarrow>\<^sub># \<bbbS>\<m>\<a>\<p> (bob \<Ztypecolon> Address) \<^bold>\<rightarrow>\<^sub>[\<^sub>] \<fish_eye>\<lbrakk>\<tau>Int 256\<rbrakk> \<nat>[256] \<heavy_comma>
\<v>\<a>\<l> alice \<Ztypecolon> Address\<heavy_comma>
\<v>\<a>\<l> bob \<Ztypecolon> Address\<heavy_comma>
\<v>\<a>\<l> amount \<Ztypecolon> Currency\<close>
return \<open>msg \<Ztypecolon> Msg\<heavy_comma>
(if amount \<le> balance_alice \<and> amount \<le> allowance then balance_alice - amount else balance_alice)
\<Ztypecolon> ledge: msg.contract msg \<^bold>\<rightarrow> \<bbbS>\<f>\<i>\<e>\<l>\<d> ''balance'' \<^bold>\<rightarrow>\<^sub># \<bbbS>\<m>\<a>\<p> (alice \<Ztypecolon> Address) \<^bold>\<rightarrow>\<^sub>[\<^sub>] \<fish_eye>\<lbrakk>\<tau>Int 256\<rbrakk> Currency \<heavy_comma>
(if amount \<le> balance_alice \<and> amount \<le> allowance then balance_bob + amount else balance_bob)
\<Ztypecolon> ledge: msg.contract msg \<^bold>\<rightarrow> \<bbbS>\<f>\<i>\<e>\<l>\<d> ''balance'' \<^bold>\<rightarrow>\<^sub># \<bbbS>\<m>\<a>\<p> (bob \<Ztypecolon> Address) \<^bold>\<rightarrow>\<^sub>[\<^sub>] \<fish_eye>\<lbrakk>\<tau>Int 256\<rbrakk> Currency \<heavy_comma>
(if amount \<le> balance_alice \<and> amount \<le> allowance then allowance - amount else allowance)
\<Ztypecolon> ledge: msg.contract msg \<^bold>\<rightarrow> \<bbbS>\<f>\<i>\<e>\<l>\<d> ''allowance'' \<^bold>\<rightarrow>\<^sub># \<bbbS>\<m>\<a>\<p> (alice \<Ztypecolon> Address) \<^bold>\<rightarrow>\<^sub># \<bbbS>\<m>\<a>\<p> (bob \<Ztypecolon> Address) \<^bold>\<rightarrow>\<^sub>[\<^sub>] \<fish_eye>\<lbrakk>\<tau>Int 256\<rbrakk> \<nat>[256] \<heavy_comma>
\<v>\<a>\<l> amount \<le> balance_alice \<and> amount \<le> allowance \<Ztypecolon> \<bool>\<close>
\<medium_left_bracket>
(* if amount \<le> balance_alice \<and> amount \<le> allowance
*)
\<rightarrow> v_alice, v_bob, v_amount
have [useful]: \<open>balance_alice \<le> Total_Supply\<close>
\<open>balance_bob \<le> Total_Supply\<close>
\<open>allowance \<le> 2 ^ Big 256\<close>
using \<phi> by simp+ ;;
op_get_var[where vname=v_amount]
op_get_msg_addr[where G=msg.contract]
op_root_ledge_ref
op_get_member_ledgeRef[where field=\<open>''balance''\<close>]
op_get_var[where vname=v_alice]
op_get_mapping_ledgeRef
op_load_ledge
op_le
op_get_var[where vname=v_amount]
op_get_msg_addr[where G=msg.contract]
op_root_ledge_ref
op_get_member_ledgeRef[where field=\<open>''allowance''\<close>]
op_get_var[where vname=v_alice]
op_get_mapping_ledgeRef
op_get_var[where vname=v_bob]
op_get_mapping_ledgeRef
op_load_ledge
op_le
op_and \<rightarrow> ret
;;if \<open>$ret\<close>
\<medium_left_bracket>
(* balance[alice] -= amount;
balance[bob] += amount;
allowance[alice,bob] -= amount;
*)
op_get_msg_addr[where G=msg.contract]
op_root_ledge_ref
op_get_member_ledgeRef[where field=\<open>''balance''\<close>]
op_get_var[where vname=v_alice]
op_get_mapping_ledgeRef
dup
op_load_ledge
op_get_var[where vname=v_amount]
op_sub
op_store_ledge !!!
thm \<phi>morphism
;;
;;op_get_msg_addr[where G=msg.contract]
op_root_ledge_ref
op_get_member_ledgeRef[where field=\<open>''allowance''\<close>]
op_get_var[where vname=v_alice]
op_get_mapping_ledgeRef
op_get_var[where vname=v_bob]
op_get_mapping_ledgeRef
dup
op_load_ledge
op_get_var[where vname=v_amount]
op_sub
op_store_ledge
;;op_get_msg_addr[where G=msg.contract]
op_root_ledge_ref
op_get_member_ledgeRef[where field=\<open>''balance''\<close>]
op_get_var[where vname=v_bob]
op_get_mapping_ledgeRef
dup
op_load_ledge
op_get_var[where vname=v_amount]
op_add
op_store_ledge
\<medium_right_bracket>. \<medium_left_bracket> \<medium_right_bracket>.
;; \<open>$ret\<close>
\<medium_right_bracket>. .
proc approve:
argument \<open>msg \<Ztypecolon> Msg\<heavy_comma>
allowance \<Ztypecolon> ledge: msg.contract msg \<^bold>\<rightarrow> \<bbbS>\<f>\<i>\<e>\<l>\<d> ''allowance''
\<^bold>\<rightarrow>\<^sub># \<bbbS>\<m>\<a>\<p> (msg.sender msg \<Ztypecolon> Address) \<^bold>\<rightarrow>\<^sub># \<bbbS>\<m>\<a>\<p> (spender \<Ztypecolon> Address) \<^bold>\<rightarrow>\<^sub>[\<^sub>] \<fish_eye>\<lbrakk>\<tau>Int 256\<rbrakk> \<nat>[256] \<heavy_comma>
\<v>\<a>\<l> spender \<Ztypecolon> Address\<heavy_comma>
\<v>\<a>\<l> amount \<Ztypecolon> \<nat>[256]\<close>
return \<open>msg \<Ztypecolon> Msg\<heavy_comma>
(if allowance + amount < 2 ^ Big 256 then allowance + amount else allowance)
\<Ztypecolon> ledge: msg.contract msg \<^bold>\<rightarrow> \<bbbS>\<f>\<i>\<e>\<l>\<d> ''allowance''
\<^bold>\<rightarrow>\<^sub># \<bbbS>\<m>\<a>\<p> (msg.sender msg \<Ztypecolon> Address) \<^bold>\<rightarrow>\<^sub># \<bbbS>\<m>\<a>\<p> (spender \<Ztypecolon> Address) \<^bold>\<rightarrow>\<^sub>[\<^sub>] \<fish_eye>\<lbrakk>\<tau>Int 256\<rbrakk> \<nat>[256] \<heavy_comma>
\<v>\<a>\<l> allowance + amount < 2 ^ Big 256 \<Ztypecolon> \<bool>\<close>
\<medium_left_bracket> \<rightarrow> v_spender, v_amount;;
op_get_msg_addr[where G=msg.contract]
op_root_ledge_ref
op_get_member_ledgeRef[where field=\<open>''allowance''\<close>]
op_get_msg_addr[where G=msg.sender]
op_get_mapping_ledgeRef
op_get_var[where vname=v_spender]
op_get_mapping_ledgeRef
op_load_ledge \<rightarrow> v_allowance;;
(* check the overflow by: allowance \<le> allowance + amount *)
op_get_var[where vname=v_allowance]
op_get_var[where vname=v_allowance]
op_get_var[where vname=v_amount]
op_add_mod
op_le
have [simp]: \<open>allowance \<le> (allowance + amount) mod 2 ^ Big 256 \<longleftrightarrow> allowance + amount < 2 ^ Big 256\<close>
using \<phi> mod_if by force
;; \<rightarrow> ret
;; if \<open>$ret\<close>
\<medium_left_bracket> op_get_msg_addr[where G=msg.contract]
op_root_ledge_ref
op_get_member_ledgeRef[where field=\<open>''allowance''\<close>]
op_get_msg_addr[where G=msg.sender]
op_get_mapping_ledgeRef
op_get_var[where vname=v_spender]
op_get_mapping_ledgeRef
op_get_var[where vname=v_allowance]
op_get_var[where vname=v_amount]
op_add
op_store_ledge
\<medium_right_bracket>. \<medium_left_bracket> \<medium_right_bracket>.
;; \<open>$ret\<close>
\<medium_right_bracket>. .
thm approve_\<phi>compilation
proc allowance:
argument \<open>msg \<Ztypecolon> Msg\<heavy_comma>
allowance \<Ztypecolon> ledge: msg.contract msg \<^bold>\<rightarrow> \<bbbS>\<f>\<i>\<e>\<l>\<d> ''allowance''
\<^bold>\<rightarrow>\<^sub># \<bbbS>\<m>\<a>\<p> (msg.sender msg \<Ztypecolon> Address) \<^bold>\<rightarrow>\<^sub># \<bbbS>\<m>\<a>\<p> (spender \<Ztypecolon> Address) \<^bold>\<rightarrow>\<^sub>[\<^sub>] \<fish_eye>\<lbrakk>\<tau>Int 256\<rbrakk> \<nat>[256] \<heavy_comma>
\<v>\<a>\<l> spender \<Ztypecolon> Address\<close>
return \<open>msg \<Ztypecolon> Msg\<heavy_comma>
allowance \<Ztypecolon> ledge: msg.contract msg \<^bold>\<rightarrow> \<bbbS>\<f>\<i>\<e>\<l>\<d> ''allowance''
\<^bold>\<rightarrow>\<^sub># \<bbbS>\<m>\<a>\<p> (msg.sender msg \<Ztypecolon> Address) \<^bold>\<rightarrow>\<^sub># \<bbbS>\<m>\<a>\<p> (spender \<Ztypecolon> Address) \<^bold>\<rightarrow>\<^sub>[\<^sub>] \<fish_eye>\<lbrakk>\<tau>Int 256\<rbrakk> \<nat>[256] \<heavy_comma>
\<v>\<a>\<l> allowance \<Ztypecolon> \<nat>[256]\<close>
\<medium_left_bracket> op_get_msg_addr[where G=msg.contract]
op_root_ledge_ref
op_get_member_ledgeRef[where field=\<open>''allowance''\<close>]
op_get_msg_addr[where G=msg.sender]
op_get_mapping_ledgeRef
\<open>\<a>\<r>\<g>0\<close> op_get_mapping_ledgeRef
op_load_ledge
\<medium_right_bracket>. .
end
end |
plan_clenshawcurtis(μ) = length(μ) > 1 ? FFTW.plan_r2r!(μ, FFTW.REDFT00) : fill!(similar(μ),1)'
"""
Compute nodes of the Clenshaw—Curtis quadrature rule.
"""
clenshawcurtisnodes(::Type{T}, N::Int) where T = chebyshevpoints(T, N; kind = 2)
"""
Compute weights of the Clenshaw—Curtis quadrature rule with modified Chebyshev moments of the first kind ``\\mu``.
"""
clenshawcurtisweights(μ::Vector) = clenshawcurtisweights!(copy(μ))
clenshawcurtisweights!(μ::Vector) = clenshawcurtisweights!(μ, plan_clenshawcurtis(μ))
function clenshawcurtisweights!(μ::Vector{T}, plan) where T
N = length(μ)
rmul!(μ, inv(N-one(T)))
plan*μ
μ[1] *= half(T); μ[N] *= half(T)
return μ
end
|
A set $U$ is sequentially compact if and only if it is compact. |
State Before: ι : Type u_1
K : Type u_2
V : Type u_3
inst✝² : Field K
inst✝¹ : AddCommGroup V
inst✝ : Module K V
f : ι → ℙ K V
⊢ Dependent f ↔ ¬Independent f State After: no goals Tactic: rw [dependent_iff, independent_iff] |
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#include <iostream>
#include <fmt/format.h>
#include <boost/program_options.hpp>
#include <libp2p/injector/host_injector.hpp>
#include <libp2p/protocol/gossip/gossip.hpp>
#include <libp2p/log/configurator.hpp>
#include "console_async_reader.hpp"
#include "utility.hpp"
namespace {
// cmd line options
struct Options {
// local node port
int port = 0;
// topic name
std::string topic = "chat";
// optional remote peer to connect to
boost::optional<libp2p::peer::PeerInfo> remote;
// log level: 'd' for debug, 'i' for info, 'w' for warning, 'e' for error
char log_level = 'w';
};
// parses command line, returns non-empty Options on success
boost::optional<Options> parseCommandLine(int argc, char **argv);
const std::string logger_config(R"(
# ----------------
sinks:
- name: console
type: console
color: true
groups:
- name: main
sink: console
level: info
children:
- name: libp2p
# ----------------
)");
} // namespace
int main(int argc, char *argv[]) {
namespace utility = libp2p::protocol::example::utility;
auto options = parseCommandLine(argc, argv);
if (!options) {
return 1;
}
// prepare log system
auto logging_system = std::make_shared<soralog::LoggingSystem>(
std::make_shared<libp2p::log::Configurator>(logger_config));
auto r = logging_system->configure();
if (not r.message.empty()) {
(r.has_error ? std::cerr : std::cout) << r.message << std::endl;
}
if (r.has_error) {
exit(EXIT_FAILURE);
}
libp2p::log::setLoggingSystem(logging_system);
if (std::getenv("TRACE_DEBUG") != nullptr) {
libp2p::log::setLevelOfGroup("*", soralog::Level::TRACE);
} else {
libp2p::log::setLevelOfGroup("*", soralog::Level::ERROR);
}
// overriding default config to see local messages as well (echo mode)
libp2p::protocol::gossip::Config config;
config.echo_forward_mode = true;
// injector creates and ties dependent objects
auto injector = libp2p::injector::makeHostInjector();
utility::setupLoggers(options->log_level);
// create asio context
auto io = injector.create<std::shared_ptr<boost::asio::io_context>>();
// host is our local libp2p node
auto host = injector.create<std::shared_ptr<libp2p::Host>>();
// make peer uri of local node
auto local_address_str =
fmt::format("/ip4/{}/tcp/{}/p2p/{}", utility::getLocalIP(*io),
options->port, host->getId().toBase58());
// local address -> peer info
auto peer_info = utility::str2peerInfo(local_address_str);
if (!peer_info) {
std::cerr << "Cannot resolve local peer from " << local_address_str << "\n";
return 2;
}
// say local address
std::cerr << "I am " << local_address_str << "\n";
// create gossip node
auto gossip = libp2p::protocol::gossip::create(
injector.create<std::shared_ptr<libp2p::protocol::Scheduler>>(), host,
std::move(config));
using Message = libp2p::protocol::gossip::Gossip::Message;
// subscribe to chat topic, print messages to the console
auto subscription = gossip->subscribe(
{options->topic}, [](boost::optional<const Message &> m) {
if (!m) {
// message with no value means EOS, this occurs when the node has
// stopped
return;
}
std::cerr << utility::formatPeerId(m->from) << ": "
<< utility::toString(m->data) << "\n";
});
// tell gossip to connect to remote peer, only if specified
if (options->remote) {
gossip->addBootstrapPeer(options->remote->id,
options->remote->addresses[0]);
}
// start the node as soon as async engine starts
io->post([&] {
auto listen_res = host->listen(peer_info->addresses[0]);
if (!listen_res) {
std::cerr << "Cannot listen to multiaddress "
<< peer_info->addresses[0].getStringAddress() << ", "
<< listen_res.error().message() << "\n";
io->stop();
return;
}
host->start();
gossip->start();
std::cerr << "Node started\n";
});
// read lines from stdin in async manner and publish them into the chat
utility::ConsoleAsyncReader stdin_reader(
*io, [&gossip, &options](const std::string &msg) {
gossip->publish({options->topic}, utility::fromString(msg));
});
// gracefully shutdown on signal
boost::asio::signal_set signals(*io, SIGINT, SIGTERM);
signals.async_wait(
[&io](const boost::system::error_code &, int) { io->stop(); });
// run event loop
io->run();
std::cerr << "Node stopped\n";
return 0;
}
namespace {
boost::optional<Options> parseCommandLine(int argc, char **argv) {
namespace po = boost::program_options;
try {
Options o;
std::string remote;
po::options_description desc("gossip_chat_example options");
desc.add_options()("help,h", "print usage message")(
"port,p", po::value(&o.port), "port to listen to")(
"topic,t", po::value(&o.topic), "chat topic name (default is 'chat'")(
"remote,r", po::value(&remote), "remote peer uri to connect to")(
"log,l", po::value(&o.log_level), "log level, [e,w,i,d]");
po::variables_map vm;
po::store(parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help") != 0 || argc == 1) {
std::cerr << desc << "\n";
return boost::none;
}
if (o.port == 0) {
std::cerr << "Port cannot be zero\n";
return boost::none;
}
if (o.topic.empty()) {
std::cerr << "Topic name cannot be empty\n";
return boost::none;
}
if (!remote.empty()) {
o.remote = libp2p::protocol::example::utility::str2peerInfo(remote);
if (!o.remote) {
std::cerr << "Cannot resolve remote peer address from " << remote
<< "\n";
return boost::none;
}
}
return o;
} catch (const std::exception &e) {
std::cerr << e.what() << "\n";
}
return boost::none;
}
} // namespace
|
lemma i_times_eq_iff: "\<i> * w = z \<longleftrightarrow> w = - (\<i> * z)" |
lemma lead_coeff_numeral [simp]: "lead_coeff (numeral n) = numeral n" |
function [R1,t1] = invert_transformation(R,t)
R1 = R';
t1 = - R'*t;
end |
(* Title: HOL/Bali/AxSound.thy
Author: David von Oheimb and Norbert Schirmer
*)
subsection {* Soundness proof for Axiomatic semantics of Java expressions and
statements
*}
theory AxSound imports AxSem begin
subsubsection "validity"
definition
triple_valid2 :: "prog \<Rightarrow> nat \<Rightarrow> 'a triple \<Rightarrow> bool" ("_\<Turnstile>_\<Colon>_"[61,0, 58] 57)
where
"G\<Turnstile>n\<Colon>t =
(case t of {P} t\<succ> {Q} \<Rightarrow>
\<forall>Y s Z. P Y s Z \<longrightarrow> (\<forall>L. s\<Colon>\<preceq>(G,L)
\<longrightarrow> (\<forall>T C A. (normal s \<longrightarrow> (\<lparr>prg=G,cls=C,lcl=L\<rparr>\<turnstile>t\<Colon>T \<and>
\<lparr>prg=G,cls=C,lcl=L\<rparr>\<turnstile>dom (locals (store s))\<guillemotright>t\<guillemotright>A)) \<longrightarrow>
(\<forall>Y' s'. G\<turnstile>s \<midarrow>t\<succ>\<midarrow>n\<rightarrow> (Y',s') \<longrightarrow> Q Y' s' Z \<and> s'\<Colon>\<preceq>(G,L)))))"
text {* This definition differs from the ordinary @{text triple_valid_def}
manly in the conclusion: We also ensures conformance of the result state. So
we don't have to apply the type soundness lemma all the time during
induction. This definition is only introduced for the soundness
proof of the axiomatic semantics, in the end we will conclude to
the ordinary definition.
*}
definition
ax_valids2 :: "prog \<Rightarrow> 'a triples \<Rightarrow> 'a triples \<Rightarrow> bool" ("_,_|\<Turnstile>\<Colon>_" [61,58,58] 57)
where "G,A|\<Turnstile>\<Colon>ts = (\<forall>n. (\<forall>t\<in>A. G\<Turnstile>n\<Colon>t) \<longrightarrow> (\<forall>t\<in>ts. G\<Turnstile>n\<Colon>t))"
lemma triple_valid2_def2: "G\<Turnstile>n\<Colon>{P} t\<succ> {Q} =
(\<forall>Y s Z. P Y s Z \<longrightarrow> (\<forall>Y' s'. G\<turnstile>s \<midarrow>t\<succ>\<midarrow>n\<rightarrow> (Y',s')\<longrightarrow>
(\<forall>L. s\<Colon>\<preceq>(G,L) \<longrightarrow> (\<forall>T C A. (normal s \<longrightarrow> (\<lparr>prg=G,cls=C,lcl=L\<rparr>\<turnstile>t\<Colon>T \<and>
\<lparr>prg=G,cls=C,lcl=L\<rparr>\<turnstile>dom (locals (store s))\<guillemotright>t\<guillemotright>A)) \<longrightarrow>
Q Y' s' Z \<and> s'\<Colon>\<preceq>(G,L)))))"
apply (unfold triple_valid2_def)
apply (simp (no_asm) add: split_paired_All)
apply blast
done
lemma triple_valid2_eq [rule_format (no_asm)]:
"wf_prog G ==> triple_valid2 G = triple_valid G"
apply (rule ext)
apply (rule ext)
apply (rule triple.induct)
apply (simp (no_asm) add: triple_valid_def2 triple_valid2_def2)
apply (rule iffI)
apply fast
apply clarify
apply (tactic "smp_tac @{context} 3 1")
apply (case_tac "normal s")
apply clarsimp
apply (elim conjE impE)
apply blast
apply (tactic "smp_tac @{context} 2 1")
apply (drule evaln_eval)
apply (drule (1) eval_type_sound [THEN conjunct1],simp, assumption+)
apply simp
apply clarsimp
done
lemma ax_valids2_eq: "wf_prog G \<Longrightarrow> G,A|\<Turnstile>\<Colon>ts = G,A|\<Turnstile>ts"
apply (unfold ax_valids_def ax_valids2_def)
apply (force simp add: triple_valid2_eq)
done
lemma triple_valid2_Suc [rule_format (no_asm)]: "G\<Turnstile>Suc n\<Colon>t \<longrightarrow> G\<Turnstile>n\<Colon>t"
apply (induct_tac "t")
apply (subst triple_valid2_def2)
apply (subst triple_valid2_def2)
apply (fast intro: evaln_nonstrict_Suc)
done
lemma Methd_triple_valid2_0: "G\<Turnstile>0\<Colon>{Normal P} Methd C sig-\<succ> {Q}"
by (auto elim!: evaln_elim_cases simp add: triple_valid2_def2)
lemma Methd_triple_valid2_SucI:
"\<lbrakk>G\<Turnstile>n\<Colon>{Normal P} body G C sig-\<succ>{Q}\<rbrakk>
\<Longrightarrow> G\<Turnstile>Suc n\<Colon>{Normal P} Methd C sig-\<succ> {Q}"
apply (simp (no_asm_use) add: triple_valid2_def2)
apply (intro strip, tactic "smp_tac @{context} 3 1", clarify)
apply (erule wt_elim_cases, erule da_elim_cases, erule evaln_elim_cases)
apply (unfold body_def Let_def)
apply (clarsimp simp add: inj_term_simps)
apply blast
done
lemma triples_valid2_Suc:
"Ball ts (triple_valid2 G (Suc n)) \<Longrightarrow> Ball ts (triple_valid2 G n)"
apply (fast intro: triple_valid2_Suc)
done
lemma "G|\<Turnstile>n:insert t A = (G\<Turnstile>n:t \<and> G|\<Turnstile>n:A)"
oops
subsubsection "soundness"
lemma Methd_sound:
assumes recursive: "G,A\<union> {{P} Methd-\<succ> {Q} | ms}|\<Turnstile>\<Colon>{{P} body G-\<succ> {Q} | ms}"
shows "G,A|\<Turnstile>\<Colon>{{P} Methd-\<succ> {Q} | ms}"
proof -
{
fix n
assume recursive: "\<And> n. \<forall>t\<in>(A \<union> {{P} Methd-\<succ> {Q} | ms}). G\<Turnstile>n\<Colon>t
\<Longrightarrow> \<forall>t\<in>{{P} body G-\<succ> {Q} | ms}. G\<Turnstile>n\<Colon>t"
have "\<forall>t\<in>A. G\<Turnstile>n\<Colon>t \<Longrightarrow> \<forall>t\<in>{{P} Methd-\<succ> {Q} | ms}. G\<Turnstile>n\<Colon>t"
proof (induct n)
case 0
show "\<forall>t\<in>{{P} Methd-\<succ> {Q} | ms}. G\<Turnstile>0\<Colon>t"
proof -
{
fix C sig
assume "(C,sig) \<in> ms"
have "G\<Turnstile>0\<Colon>{Normal (P C sig)} Methd C sig-\<succ> {Q C sig}"
by (rule Methd_triple_valid2_0)
}
thus ?thesis
by (simp add: mtriples_def split_def)
qed
next
case (Suc m)
note hyp = `\<forall>t\<in>A. G\<Turnstile>m\<Colon>t \<Longrightarrow> \<forall>t\<in>{{P} Methd-\<succ> {Q} | ms}. G\<Turnstile>m\<Colon>t`
note prem = `\<forall>t\<in>A. G\<Turnstile>Suc m\<Colon>t`
show "\<forall>t\<in>{{P} Methd-\<succ> {Q} | ms}. G\<Turnstile>Suc m\<Colon>t"
proof -
{
fix C sig
assume m: "(C,sig) \<in> ms"
have "G\<Turnstile>Suc m\<Colon>{Normal (P C sig)} Methd C sig-\<succ> {Q C sig}"
proof -
from prem have prem_m: "\<forall>t\<in>A. G\<Turnstile>m\<Colon>t"
by (rule triples_valid2_Suc)
hence "\<forall>t\<in>{{P} Methd-\<succ> {Q} | ms}. G\<Turnstile>m\<Colon>t"
by (rule hyp)
with prem_m
have "\<forall>t\<in>(A \<union> {{P} Methd-\<succ> {Q} | ms}). G\<Turnstile>m\<Colon>t"
by (simp add: ball_Un)
hence "\<forall>t\<in>{{P} body G-\<succ> {Q} | ms}. G\<Turnstile>m\<Colon>t"
by (rule recursive)
with m have "G\<Turnstile>m\<Colon>{Normal (P C sig)} body G C sig-\<succ> {Q C sig}"
by (auto simp add: mtriples_def split_def)
thus ?thesis
by (rule Methd_triple_valid2_SucI)
qed
}
thus ?thesis
by (simp add: mtriples_def split_def)
qed
qed
}
with recursive show ?thesis
by (unfold ax_valids2_def) blast
qed
lemma valids2_inductI: "\<forall>s t n Y' s'. G\<turnstile>s\<midarrow>t\<succ>\<midarrow>n\<rightarrow> (Y',s') \<longrightarrow> t = c \<longrightarrow>
Ball A (triple_valid2 G n) \<longrightarrow> (\<forall>Y Z. P Y s Z \<longrightarrow>
(\<forall>L. s\<Colon>\<preceq>(G,L) \<longrightarrow>
(\<forall>T C A. (normal s \<longrightarrow> (\<lparr>prg=G,cls=C,lcl=L\<rparr>\<turnstile>t\<Colon>T) \<and>
\<lparr>prg=G,cls=C,lcl=L\<rparr>\<turnstile>dom (locals (store s))\<guillemotright>t\<guillemotright>A) \<longrightarrow>
Q Y' s' Z \<and> s'\<Colon>\<preceq>(G, L)))) \<Longrightarrow>
G,A|\<Turnstile>\<Colon>{ {P} c\<succ> {Q}}"
apply (simp (no_asm) add: ax_valids2_def triple_valid2_def2)
apply clarsimp
done
lemma da_good_approx_evalnE [consumes 4]:
assumes evaln: "G\<turnstile>s0 \<midarrow>t\<succ>\<midarrow>n\<rightarrow> (v, s1)"
and wt: "\<lparr>prg=G,cls=C,lcl=L\<rparr>\<turnstile>t\<Colon>T"
and da: "\<lparr>prg=G,cls=C,lcl=L\<rparr>\<turnstile> dom (locals (store s0)) \<guillemotright>t\<guillemotright> A"
and wf: "wf_prog G"
and elim: "\<lbrakk>normal s1 \<Longrightarrow> nrm A \<subseteq> dom (locals (store s1));
\<And> l. \<lbrakk>abrupt s1 = Some (Jump (Break l)); normal s0\<rbrakk>
\<Longrightarrow> brk A l \<subseteq> dom (locals (store s1));
\<lbrakk>abrupt s1 = Some (Jump Ret);normal s0\<rbrakk>
\<Longrightarrow>Result \<in> dom (locals (store s1))
\<rbrakk> \<Longrightarrow> P"
shows "P"
proof -
from evaln have "G\<turnstile>s0 \<midarrow>t\<succ>\<rightarrow> (v, s1)"
by (rule evaln_eval)
from this wt da wf elim show P
by (rule da_good_approxE') iprover+
qed
lemma validI:
assumes I: "\<And> n s0 L accC T C v s1 Y Z.
\<lbrakk>\<forall>t\<in>A. G\<Turnstile>n\<Colon>t; s0\<Colon>\<preceq>(G,L);
normal s0 \<Longrightarrow> \<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>t\<Colon>T;
normal s0 \<Longrightarrow> \<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>dom (locals (store s0))\<guillemotright>t\<guillemotright>C;
G\<turnstile>s0 \<midarrow>t\<succ>\<midarrow>n\<rightarrow> (v,s1); P Y s0 Z\<rbrakk> \<Longrightarrow> Q v s1 Z \<and> s1\<Colon>\<preceq>(G,L)"
shows "G,A|\<Turnstile>\<Colon>{ {P} t\<succ> {Q} }"
apply (simp add: ax_valids2_def triple_valid2_def2)
apply (intro allI impI)
apply (case_tac "normal s")
apply clarsimp
apply (rule I,(assumption|simp)+)
apply (rule I,auto)
done
declare [[simproc add: wt_expr wt_var wt_exprs wt_stmt]]
lemma valid_stmtI:
assumes I: "\<And> n s0 L accC C s1 Y Z.
\<lbrakk>\<forall>t\<in>A. G\<Turnstile>n\<Colon>t; s0\<Colon>\<preceq>(G,L);
normal s0\<Longrightarrow> \<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>c\<Colon>\<surd>;
normal s0\<Longrightarrow>\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>dom (locals (store s0))\<guillemotright>\<langle>c\<rangle>\<^sub>s\<guillemotright>C;
G\<turnstile>s0 \<midarrow>c\<midarrow>n\<rightarrow> s1; P Y s0 Z\<rbrakk> \<Longrightarrow> Q \<diamondsuit> s1 Z \<and> s1\<Colon>\<preceq>(G,L)"
shows "G,A|\<Turnstile>\<Colon>{ {P} \<langle>c\<rangle>\<^sub>s\<succ> {Q} }"
apply (simp add: ax_valids2_def triple_valid2_def2)
apply (intro allI impI)
apply (case_tac "normal s")
apply clarsimp
apply (rule I,(assumption|simp)+)
apply (rule I,auto)
done
lemma valid_stmt_NormalI:
assumes I: "\<And> n s0 L accC C s1 Y Z.
\<lbrakk>\<forall>t\<in>A. G\<Turnstile>n\<Colon>t; s0\<Colon>\<preceq>(G,L); normal s0; \<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>c\<Colon>\<surd>;
\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>dom (locals (store s0))\<guillemotright>\<langle>c\<rangle>\<^sub>s\<guillemotright>C;
G\<turnstile>s0 \<midarrow>c\<midarrow>n\<rightarrow> s1; (Normal P) Y s0 Z\<rbrakk> \<Longrightarrow> Q \<diamondsuit> s1 Z \<and> s1\<Colon>\<preceq>(G,L)"
shows "G,A|\<Turnstile>\<Colon>{ {Normal P} \<langle>c\<rangle>\<^sub>s\<succ> {Q} }"
apply (simp add: ax_valids2_def triple_valid2_def2)
apply (intro allI impI)
apply (elim exE conjE)
apply (rule I)
by auto
lemma valid_var_NormalI:
assumes I: "\<And> n s0 L accC T C vf s1 Y Z.
\<lbrakk>\<forall>t\<in>A. G\<Turnstile>n\<Colon>t; s0\<Colon>\<preceq>(G,L); normal s0;
\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>t\<Colon>=T;
\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>dom (locals (store s0))\<guillemotright>\<langle>t\<rangle>\<^sub>v\<guillemotright>C;
G\<turnstile>s0 \<midarrow>t=\<succ>vf\<midarrow>n\<rightarrow> s1; (Normal P) Y s0 Z\<rbrakk>
\<Longrightarrow> Q (In2 vf) s1 Z \<and> s1\<Colon>\<preceq>(G,L)"
shows "G,A|\<Turnstile>\<Colon>{ {Normal P} \<langle>t\<rangle>\<^sub>v\<succ> {Q} }"
apply (simp add: ax_valids2_def triple_valid2_def2)
apply (intro allI impI)
apply (elim exE conjE)
apply simp
apply (rule I)
by auto
lemma valid_expr_NormalI:
assumes I: "\<And> n s0 L accC T C v s1 Y Z.
\<lbrakk>\<forall>t\<in>A. G\<Turnstile>n\<Colon>t; s0\<Colon>\<preceq>(G,L); normal s0;
\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>t\<Colon>-T;
\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>dom (locals (store s0))\<guillemotright>\<langle>t\<rangle>\<^sub>e\<guillemotright>C;
G\<turnstile>s0 \<midarrow>t-\<succ>v\<midarrow>n\<rightarrow> s1; (Normal P) Y s0 Z\<rbrakk>
\<Longrightarrow> Q (In1 v) s1 Z \<and> s1\<Colon>\<preceq>(G,L)"
shows "G,A|\<Turnstile>\<Colon>{ {Normal P} \<langle>t\<rangle>\<^sub>e\<succ> {Q} }"
apply (simp add: ax_valids2_def triple_valid2_def2)
apply (intro allI impI)
apply (elim exE conjE)
apply simp
apply (rule I)
by auto
lemma valid_expr_list_NormalI:
assumes I: "\<And> n s0 L accC T C vs s1 Y Z.
\<lbrakk>\<forall>t\<in>A. G\<Turnstile>n\<Colon>t; s0\<Colon>\<preceq>(G,L); normal s0;
\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>t\<Colon>\<doteq>T;
\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>dom (locals (store s0))\<guillemotright>\<langle>t\<rangle>\<^sub>l\<guillemotright>C;
G\<turnstile>s0 \<midarrow>t\<doteq>\<succ>vs\<midarrow>n\<rightarrow> s1; (Normal P) Y s0 Z\<rbrakk>
\<Longrightarrow> Q (In3 vs) s1 Z \<and> s1\<Colon>\<preceq>(G,L)"
shows "G,A|\<Turnstile>\<Colon>{ {Normal P} \<langle>t\<rangle>\<^sub>l\<succ> {Q} }"
apply (simp add: ax_valids2_def triple_valid2_def2)
apply (intro allI impI)
apply (elim exE conjE)
apply simp
apply (rule I)
by auto
lemma validE [consumes 5]:
assumes valid: "G,A|\<Turnstile>\<Colon>{ {P} t\<succ> {Q} }"
and P: "P Y s0 Z"
and valid_A: "\<forall>t\<in>A. G\<Turnstile>n\<Colon>t"
and conf: "s0\<Colon>\<preceq>(G,L)"
and eval: "G\<turnstile>s0 \<midarrow>t\<succ>\<midarrow>n\<rightarrow> (v,s1)"
and wt: "normal s0 \<Longrightarrow> \<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>t\<Colon>T"
and da: "normal s0 \<Longrightarrow> \<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>dom (locals (store s0))\<guillemotright>t\<guillemotright>C"
and elim: "\<lbrakk>Q v s1 Z; s1\<Colon>\<preceq>(G,L)\<rbrakk> \<Longrightarrow> concl"
shows concl
using assms
by (simp add: ax_valids2_def triple_valid2_def2) fast
(* why consumes 5?. If I want to apply this lemma in a context wgere
\<not> normal s0 holds,
I can chain "\<not> normal s0" as fact number 6 and apply the rule with
cases. Auto will then solve premise 6 and 7.
*)
lemma all_empty: "(!x. P) = P"
by simp
corollary evaln_type_sound:
assumes evaln: "G\<turnstile>s0 \<midarrow>t\<succ>\<midarrow>n\<rightarrow> (v,s1)" and
wt: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>t\<Colon>T" and
da: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>dom (locals (store s0)) \<guillemotright>t\<guillemotright> A" and
conf_s0: "s0\<Colon>\<preceq>(G,L)" and
wf: "wf_prog G"
shows "s1\<Colon>\<preceq>(G,L) \<and> (normal s1 \<longrightarrow> G,L,store s1\<turnstile>t\<succ>v\<Colon>\<preceq>T) \<and>
(error_free s0 = error_free s1)"
proof -
from evaln have "G\<turnstile>s0 \<midarrow>t\<succ>\<rightarrow> (v,s1)"
by (rule evaln_eval)
from this wt da wf conf_s0 show ?thesis
by (rule eval_type_sound)
qed
corollary dom_locals_evaln_mono_elim [consumes 1]:
assumes
evaln: "G\<turnstile> s0 \<midarrow>t\<succ>\<midarrow>n\<rightarrow> (v,s1)" and
hyps: "\<lbrakk>dom (locals (store s0)) \<subseteq> dom (locals (store s1));
\<And> vv s val. \<lbrakk>v=In2 vv; normal s1\<rbrakk>
\<Longrightarrow> dom (locals (store s))
\<subseteq> dom (locals (store ((snd vv) val s)))\<rbrakk> \<Longrightarrow> P"
shows "P"
proof -
from evaln have "G\<turnstile> s0 \<midarrow>t\<succ>\<rightarrow> (v,s1)" by (rule evaln_eval)
from this hyps show ?thesis
by (rule dom_locals_eval_mono_elim) iprover+
qed
lemma evaln_no_abrupt:
"\<And>s s'. \<lbrakk>G\<turnstile>s \<midarrow>t\<succ>\<midarrow>n\<rightarrow> (w,s'); normal s'\<rbrakk> \<Longrightarrow> normal s"
by (erule evaln_cases,auto)
declare inj_term_simps [simp]
lemma ax_sound2:
assumes wf: "wf_prog G"
and deriv: "G,A|\<turnstile>ts"
shows "G,A|\<Turnstile>\<Colon>ts"
using deriv
proof (induct)
case (empty A)
show ?case
by (simp add: ax_valids2_def triple_valid2_def2)
next
case (insert A t ts)
note valid_t = `G,A|\<Turnstile>\<Colon>{t}`
moreover
note valid_ts = `G,A|\<Turnstile>\<Colon>ts`
{
fix n assume valid_A: "\<forall>t\<in>A. G\<Turnstile>n\<Colon>t"
have "G\<Turnstile>n\<Colon>t" and "\<forall>t\<in>ts. G\<Turnstile>n\<Colon>t"
proof -
from valid_A valid_t show "G\<Turnstile>n\<Colon>t"
by (simp add: ax_valids2_def)
next
from valid_A valid_ts show "\<forall>t\<in>ts. G\<Turnstile>n\<Colon>t"
by (unfold ax_valids2_def) blast
qed
hence "\<forall>t'\<in>insert t ts. G\<Turnstile>n\<Colon>t'"
by simp
}
thus ?case
by (unfold ax_valids2_def) blast
next
case (asm ts A)
from `ts \<subseteq> A`
show "G,A|\<Turnstile>\<Colon>ts"
by (auto simp add: ax_valids2_def triple_valid2_def)
next
case (weaken A ts' ts)
note `G,A|\<Turnstile>\<Colon>ts'`
moreover note `ts \<subseteq> ts'`
ultimately show "G,A|\<Turnstile>\<Colon>ts"
by (unfold ax_valids2_def triple_valid2_def) blast
next
case (conseq P A t Q)
note con = `\<forall>Y s Z. P Y s Z \<longrightarrow>
(\<exists>P' Q'.
(G,A\<turnstile>{P'} t\<succ> {Q'} \<and> G,A|\<Turnstile>\<Colon>{ {P'} t\<succ> {Q'} }) \<and>
(\<forall>Y' s'. (\<forall>Y Z'. P' Y s Z' \<longrightarrow> Q' Y' s' Z') \<longrightarrow> Q Y' s' Z))`
show "G,A|\<Turnstile>\<Colon>{ {P} t\<succ> {Q} }"
proof (rule validI)
fix n s0 L accC T C v s1 Y Z
assume valid_A: "\<forall>t\<in>A. G\<Turnstile>n\<Colon>t"
assume conf: "s0\<Colon>\<preceq>(G,L)"
assume wt: "normal s0 \<Longrightarrow> \<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>t\<Colon>T"
assume da: "normal s0
\<Longrightarrow> \<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>dom (locals (store s0)) \<guillemotright>t\<guillemotright> C"
assume eval: "G\<turnstile>s0 \<midarrow>t\<succ>\<midarrow>n\<rightarrow> (v, s1)"
assume P: "P Y s0 Z"
show "Q v s1 Z \<and> s1\<Colon>\<preceq>(G, L)"
proof -
from valid_A conf wt da eval P con
have "Q v s1 Z"
apply (simp add: ax_valids2_def triple_valid2_def2)
apply (tactic "smp_tac @{context} 3 1")
apply clarify
apply (tactic "smp_tac @{context} 1 1")
apply (erule allE,erule allE, erule mp)
apply (intro strip)
apply (tactic "smp_tac @{context} 3 1")
apply (tactic "smp_tac @{context} 2 1")
apply (tactic "smp_tac @{context} 1 1")
by blast
moreover have "s1\<Colon>\<preceq>(G, L)"
proof (cases "normal s0")
case True
from eval wt [OF True] da [OF True] conf wf
show ?thesis
by (rule evaln_type_sound [elim_format]) simp
next
case False
with eval have "s1=s0"
by auto
with conf show ?thesis by simp
qed
ultimately show ?thesis ..
qed
qed
next
case (hazard A P t Q)
show "G,A|\<Turnstile>\<Colon>{ {P \<and>. Not \<circ> type_ok G t} t\<succ> {Q} }"
by (simp add: ax_valids2_def triple_valid2_def2 type_ok_def) fast
next
case (Abrupt A P t)
show "G,A|\<Turnstile>\<Colon>{ {P\<leftarrow>undefined3 t \<and>. Not \<circ> normal} t\<succ> {P} }"
proof (rule validI)
fix n s0 L accC T C v s1 Y Z
assume conf_s0: "s0\<Colon>\<preceq>(G, L)"
assume eval: "G\<turnstile>s0 \<midarrow>t\<succ>\<midarrow>n\<rightarrow> (v, s1)"
assume "(P\<leftarrow>undefined3 t \<and>. Not \<circ> normal) Y s0 Z"
then obtain P: "P (undefined3 t) s0 Z" and abrupt_s0: "\<not> normal s0"
by simp
from eval abrupt_s0 obtain "s1=s0" and "v=undefined3 t"
by auto
with P conf_s0
show "P v s1 Z \<and> s1\<Colon>\<preceq>(G, L)"
by simp
qed
next
case (LVar A P vn)
show "G,A|\<Turnstile>\<Colon>{ {Normal (\<lambda>s.. P\<leftarrow>In2 (lvar vn s))} LVar vn=\<succ> {P} }"
proof (rule valid_var_NormalI)
fix n s0 L accC T C vf s1 Y Z
assume conf_s0: "s0\<Colon>\<preceq>(G, L)"
assume normal_s0: "normal s0"
assume wt: "\<lparr>prg = G, cls = accC, lcl = L\<rparr>\<turnstile>LVar vn\<Colon>=T"
assume da: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile> dom (locals (store s0)) \<guillemotright>\<langle>LVar vn\<rangle>\<^sub>v\<guillemotright> C"
assume eval: "G\<turnstile>s0 \<midarrow>LVar vn=\<succ>vf\<midarrow>n\<rightarrow> s1"
assume P: "(Normal (\<lambda>s.. P\<leftarrow>In2 (lvar vn s))) Y s0 Z"
show "P (In2 vf) s1 Z \<and> s1\<Colon>\<preceq>(G, L)"
proof
from eval normal_s0 obtain "s1=s0" "vf=lvar vn (store s0)"
by (fastforce elim: evaln_elim_cases)
with P show "P (In2 vf) s1 Z"
by simp
next
from eval wt da conf_s0 wf
show "s1\<Colon>\<preceq>(G, L)"
by (rule evaln_type_sound [elim_format]) simp
qed
qed
next
case (FVar A P statDeclC Q e stat fn R accC)
note valid_init = `G,A|\<Turnstile>\<Colon>{ {Normal P} .Init statDeclC. {Q} }`
note valid_e = `G,A|\<Turnstile>\<Colon>{ {Q} e-\<succ> {\<lambda>Val:a:. fvar statDeclC stat fn a ..; R} }`
show "G,A|\<Turnstile>\<Colon>{ {Normal P} {accC,statDeclC,stat}e..fn=\<succ> {R} }"
proof (rule valid_var_NormalI)
fix n s0 L accC' T V vf s3 Y Z
assume valid_A: "\<forall>t\<in>A. G\<Turnstile>n\<Colon>t"
assume conf_s0: "s0\<Colon>\<preceq>(G,L)"
assume normal_s0: "normal s0"
assume wt: "\<lparr>prg=G,cls=accC',lcl=L\<rparr>\<turnstile>{accC,statDeclC,stat}e..fn\<Colon>=T"
assume da: "\<lparr>prg=G,cls=accC',lcl=L\<rparr>
\<turnstile> dom (locals (store s0)) \<guillemotright>\<langle>{accC,statDeclC,stat}e..fn\<rangle>\<^sub>v\<guillemotright> V"
assume eval: "G\<turnstile>s0 \<midarrow>{accC,statDeclC,stat}e..fn=\<succ>vf\<midarrow>n\<rightarrow> s3"
assume P: "(Normal P) Y s0 Z"
show "R \<lfloor>vf\<rfloor>\<^sub>v s3 Z \<and> s3\<Colon>\<preceq>(G, L)"
proof -
from wt obtain statC f where
wt_e: "\<lparr>prg=G, cls=accC, lcl=L\<rparr>\<turnstile>e\<Colon>-Class statC" and
accfield: "accfield G accC statC fn = Some (statDeclC,f)" and
eq_accC: "accC=accC'" and
stat: "stat=is_static f" and
T: "T=(type f)"
by (cases) (auto simp add: member_is_static_simp)
from da eq_accC
have da_e: "\<lparr>prg=G, cls=accC, lcl=L\<rparr>\<turnstile>dom (locals (store s0))\<guillemotright>\<langle>e\<rangle>\<^sub>e\<guillemotright> V"
by cases simp
from eval obtain a s1 s2 s2' where
eval_init: "G\<turnstile>s0 \<midarrow>Init statDeclC\<midarrow>n\<rightarrow> s1" and
eval_e: "G\<turnstile>s1 \<midarrow>e-\<succ>a\<midarrow>n\<rightarrow> s2" and
fvar: "(vf,s2')=fvar statDeclC stat fn a s2" and
s3: "s3 = check_field_access G accC statDeclC fn stat a s2'"
using normal_s0 by (fastforce elim: evaln_elim_cases)
have wt_init: "\<lparr>prg=G, cls=accC, lcl=L\<rparr>\<turnstile>(Init statDeclC)\<Colon>\<surd>"
proof -
from wf wt_e
have iscls_statC: "is_class G statC"
by (auto dest: ty_expr_is_type type_is_class)
with wf accfield
have iscls_statDeclC: "is_class G statDeclC"
by (auto dest!: accfield_fields dest: fields_declC)
thus ?thesis by simp
qed
obtain I where
da_init: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>
\<turnstile> dom (locals (store s0)) \<guillemotright>\<langle>Init statDeclC\<rangle>\<^sub>s\<guillemotright> I"
by (auto intro: da_Init [simplified] assigned.select_convs)
from valid_init P valid_A conf_s0 eval_init wt_init da_init
obtain Q: "Q \<diamondsuit> s1 Z" and conf_s1: "s1\<Colon>\<preceq>(G, L)"
by (rule validE)
obtain
R: "R \<lfloor>vf\<rfloor>\<^sub>v s2' Z" and
conf_s2: "s2\<Colon>\<preceq>(G, L)" and
conf_a: "normal s2 \<longrightarrow> G,store s2\<turnstile>a\<Colon>\<preceq>Class statC"
proof (cases "normal s1")
case True
obtain V' where
da_e':
"\<lparr>prg=G,cls=accC,lcl=L\<rparr> \<turnstile>dom (locals (store s1))\<guillemotright>\<langle>e\<rangle>\<^sub>e\<guillemotright> V'"
proof -
from eval_init
have "(dom (locals (store s0))) \<subseteq> (dom (locals (store s1)))"
by (rule dom_locals_evaln_mono_elim)
with da_e show thesis
by (rule da_weakenE) (rule that)
qed
with valid_e Q valid_A conf_s1 eval_e wt_e
obtain "R \<lfloor>vf\<rfloor>\<^sub>v s2' Z" and "s2\<Colon>\<preceq>(G, L)"
by (rule validE) (simp add: fvar [symmetric])
moreover
from eval_e wt_e da_e' conf_s1 wf
have "normal s2 \<longrightarrow> G,store s2\<turnstile>a\<Colon>\<preceq>Class statC"
by (rule evaln_type_sound [elim_format]) simp
ultimately show ?thesis ..
next
case False
with valid_e Q valid_A conf_s1 eval_e
obtain "R \<lfloor>vf\<rfloor>\<^sub>v s2' Z" and "s2\<Colon>\<preceq>(G, L)"
by (cases rule: validE) (simp add: fvar [symmetric])+
moreover from False eval_e have "\<not> normal s2"
by auto
hence "normal s2 \<longrightarrow> G,store s2\<turnstile>a\<Colon>\<preceq>Class statC"
by auto
ultimately show ?thesis ..
qed
from accfield wt_e eval_init eval_e conf_s2 conf_a fvar stat s3 wf
have eq_s3_s2': "s3=s2'"
using normal_s0 by (auto dest!: error_free_field_access evaln_eval)
moreover
from eval wt da conf_s0 wf
have "s3\<Colon>\<preceq>(G, L)"
by (rule evaln_type_sound [elim_format]) simp
ultimately show ?thesis using Q R by simp
qed
qed
next
case (AVar A P e1 Q e2 R)
note valid_e1 = `G,A|\<Turnstile>\<Colon>{ {Normal P} e1-\<succ> {Q} }`
have valid_e2: "\<And> a. G,A|\<Turnstile>\<Colon>{ {Q\<leftarrow>In1 a} e2-\<succ> {\<lambda>Val:i:. avar G i a ..; R} }"
using AVar.hyps by simp
show "G,A|\<Turnstile>\<Colon>{ {Normal P} e1.[e2]=\<succ> {R} }"
proof (rule valid_var_NormalI)
fix n s0 L accC T V vf s2' Y Z
assume valid_A: "\<forall>t\<in>A. G\<Turnstile>n\<Colon>t"
assume conf_s0: "s0\<Colon>\<preceq>(G,L)"
assume normal_s0: "normal s0"
assume wt: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>e1.[e2]\<Colon>=T"
assume da: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>
\<turnstile> dom (locals (store s0)) \<guillemotright>\<langle>e1.[e2]\<rangle>\<^sub>v\<guillemotright> V"
assume eval: "G\<turnstile>s0 \<midarrow>e1.[e2]=\<succ>vf\<midarrow>n\<rightarrow> s2'"
assume P: "(Normal P) Y s0 Z"
show "R \<lfloor>vf\<rfloor>\<^sub>v s2' Z \<and> s2'\<Colon>\<preceq>(G, L)"
proof -
from wt obtain
wt_e1: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>e1\<Colon>-T.[]" and
wt_e2: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>e2\<Colon>-PrimT Integer"
by (rule wt_elim_cases) simp
from da obtain E1 where
da_e1: "\<lparr>prg=G,cls=accC,lcl=L\<rparr> \<turnstile>dom (locals (store s0))\<guillemotright>\<langle>e1\<rangle>\<^sub>e\<guillemotright> E1" and
da_e2: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile> nrm E1 \<guillemotright>\<langle>e2\<rangle>\<^sub>e\<guillemotright> V"
by (rule da_elim_cases) simp
from eval obtain s1 a i s2 where
eval_e1: "G\<turnstile>s0 \<midarrow>e1-\<succ>a\<midarrow>n\<rightarrow> s1" and
eval_e2: "G\<turnstile>s1 \<midarrow>e2-\<succ>i\<midarrow>n\<rightarrow> s2" and
avar: "avar G i a s2 =(vf, s2')"
using normal_s0 by (fastforce elim: evaln_elim_cases)
from valid_e1 P valid_A conf_s0 eval_e1 wt_e1 da_e1
obtain Q: "Q \<lfloor>a\<rfloor>\<^sub>e s1 Z" and conf_s1: "s1\<Colon>\<preceq>(G, L)"
by (rule validE)
from Q have Q': "\<And> v. (Q\<leftarrow>In1 a) v s1 Z"
by simp
have "R \<lfloor>vf\<rfloor>\<^sub>v s2' Z"
proof (cases "normal s1")
case True
obtain V' where
"\<lparr>prg=G,cls=accC,lcl=L\<rparr> \<turnstile>dom (locals (store s1))\<guillemotright>\<langle>e2\<rangle>\<^sub>e\<guillemotright> V'"
proof -
from eval_e1 wt_e1 da_e1 wf True
have "nrm E1 \<subseteq> dom (locals (store s1))"
by (cases rule: da_good_approx_evalnE) iprover
with da_e2 show thesis
by (rule da_weakenE) (rule that)
qed
with valid_e2 Q' valid_A conf_s1 eval_e2 wt_e2
show ?thesis
by (rule validE) (simp add: avar)
next
case False
with valid_e2 Q' valid_A conf_s1 eval_e2
show ?thesis
by (cases rule: validE) (simp add: avar)+
qed
moreover
from eval wt da conf_s0 wf
have "s2'\<Colon>\<preceq>(G, L)"
by (rule evaln_type_sound [elim_format]) simp
ultimately show ?thesis ..
qed
qed
next
case (NewC A P C Q)
note valid_init = `G,A|\<Turnstile>\<Colon>{ {Normal P} .Init C. {Alloc G (CInst C) Q} }`
show "G,A|\<Turnstile>\<Colon>{ {Normal P} NewC C-\<succ> {Q} }"
proof (rule valid_expr_NormalI)
fix n s0 L accC T E v s2 Y Z
assume valid_A: "\<forall>t\<in>A. G\<Turnstile>n\<Colon>t"
assume conf_s0: "s0\<Colon>\<preceq>(G,L)"
assume normal_s0: "normal s0"
assume wt: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>NewC C\<Colon>-T"
assume da: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>
\<turnstile> dom (locals (store s0)) \<guillemotright>\<langle>NewC C\<rangle>\<^sub>e\<guillemotright> E"
assume eval: "G\<turnstile>s0 \<midarrow>NewC C-\<succ>v\<midarrow>n\<rightarrow> s2"
assume P: "(Normal P) Y s0 Z"
show "Q \<lfloor>v\<rfloor>\<^sub>e s2 Z \<and> s2\<Colon>\<preceq>(G, L)"
proof -
from wt obtain is_cls_C: "is_class G C"
by (rule wt_elim_cases) (auto dest: is_acc_classD)
hence wt_init: "\<lparr>prg=G, cls=accC, lcl=L\<rparr>\<turnstile>Init C\<Colon>\<surd>"
by auto
obtain I where
da_init: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile> dom (locals (store s0)) \<guillemotright>\<langle>Init C\<rangle>\<^sub>s\<guillemotright> I"
by (auto intro: da_Init [simplified] assigned.select_convs)
from eval obtain s1 a where
eval_init: "G\<turnstile>s0 \<midarrow>Init C\<midarrow>n\<rightarrow> s1" and
alloc: "G\<turnstile>s1 \<midarrow>halloc CInst C\<succ>a\<rightarrow> s2" and
v: "v=Addr a"
using normal_s0 by (fastforce elim: evaln_elim_cases)
from valid_init P valid_A conf_s0 eval_init wt_init da_init
obtain "(Alloc G (CInst C) Q) \<diamondsuit> s1 Z"
by (rule validE)
with alloc v have "Q \<lfloor>v\<rfloor>\<^sub>e s2 Z"
by simp
moreover
from eval wt da conf_s0 wf
have "s2\<Colon>\<preceq>(G, L)"
by (rule evaln_type_sound [elim_format]) simp
ultimately show ?thesis ..
qed
qed
next
case (NewA A P T Q e R)
note valid_init = `G,A|\<Turnstile>\<Colon>{ {Normal P} .init_comp_ty T. {Q} }`
note valid_e = `G,A|\<Turnstile>\<Colon>{ {Q} e-\<succ> {\<lambda>Val:i:. abupd (check_neg i) .;
Alloc G (Arr T (the_Intg i)) R}}`
show "G,A|\<Turnstile>\<Colon>{ {Normal P} New T[e]-\<succ> {R} }"
proof (rule valid_expr_NormalI)
fix n s0 L accC arrT E v s3 Y Z
assume valid_A: "\<forall>t\<in>A. G\<Turnstile>n\<Colon>t"
assume conf_s0: "s0\<Colon>\<preceq>(G,L)"
assume normal_s0: "normal s0"
assume wt: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>New T[e]\<Colon>-arrT"
assume da: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>dom (locals (store s0)) \<guillemotright>\<langle>New T[e]\<rangle>\<^sub>e\<guillemotright> E"
assume eval: "G\<turnstile>s0 \<midarrow>New T[e]-\<succ>v\<midarrow>n\<rightarrow> s3"
assume P: "(Normal P) Y s0 Z"
show "R \<lfloor>v\<rfloor>\<^sub>e s3 Z \<and> s3\<Colon>\<preceq>(G, L)"
proof -
from wt obtain
wt_init: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>init_comp_ty T\<Colon>\<surd>" and
wt_e: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>e\<Colon>-PrimT Integer"
by (rule wt_elim_cases) (auto intro: wt_init_comp_ty )
from da obtain
da_e:"\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile> dom (locals (store s0)) \<guillemotright>\<langle>e\<rangle>\<^sub>e\<guillemotright> E"
by cases simp
from eval obtain s1 i s2 a where
eval_init: "G\<turnstile>s0 \<midarrow>init_comp_ty T\<midarrow>n\<rightarrow> s1" and
eval_e: "G\<turnstile>s1 \<midarrow>e-\<succ>i\<midarrow>n\<rightarrow> s2" and
alloc: "G\<turnstile>abupd (check_neg i) s2 \<midarrow>halloc Arr T (the_Intg i)\<succ>a\<rightarrow> s3" and
v: "v=Addr a"
using normal_s0 by (fastforce elim: evaln_elim_cases)
obtain I where
da_init:
"\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>dom (locals (store s0)) \<guillemotright>\<langle>init_comp_ty T\<rangle>\<^sub>s\<guillemotright> I"
proof (cases "\<exists>C. T = Class C")
case True
thus ?thesis
by - (rule that, (auto intro: da_Init [simplified]
assigned.select_convs
simp add: init_comp_ty_def))
(* simplified: to rewrite \<langle>Init C\<rangle> to In1r (Init C) *)
next
case False
thus ?thesis
by - (rule that, (auto intro: da_Skip [simplified]
assigned.select_convs
simp add: init_comp_ty_def))
(* simplified: to rewrite \<langle>Skip\<rangle> to In1r (Skip) *)
qed
with valid_init P valid_A conf_s0 eval_init wt_init
obtain Q: "Q \<diamondsuit> s1 Z" and conf_s1: "s1\<Colon>\<preceq>(G, L)"
by (rule validE)
obtain E' where
"\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile> dom (locals (store s1)) \<guillemotright>\<langle>e\<rangle>\<^sub>e\<guillemotright> E'"
proof -
from eval_init
have "dom (locals (store s0)) \<subseteq> dom (locals (store s1))"
by (rule dom_locals_evaln_mono_elim)
with da_e show thesis
by (rule da_weakenE) (rule that)
qed
with valid_e Q valid_A conf_s1 eval_e wt_e
have "(\<lambda>Val:i:. abupd (check_neg i) .;
Alloc G (Arr T (the_Intg i)) R) \<lfloor>i\<rfloor>\<^sub>e s2 Z"
by (rule validE)
with alloc v have "R \<lfloor>v\<rfloor>\<^sub>e s3 Z"
by simp
moreover
from eval wt da conf_s0 wf
have "s3\<Colon>\<preceq>(G, L)"
by (rule evaln_type_sound [elim_format]) simp
ultimately show ?thesis ..
qed
qed
next
case (Cast A P e T Q)
note valid_e = `G,A|\<Turnstile>\<Colon>{ {Normal P} e-\<succ>
{\<lambda>Val:v:. \<lambda>s.. abupd (raise_if (\<not> G,s\<turnstile>v fits T) ClassCast) .;
Q\<leftarrow>In1 v} }`
show "G,A|\<Turnstile>\<Colon>{ {Normal P} Cast T e-\<succ> {Q} }"
proof (rule valid_expr_NormalI)
fix n s0 L accC castT E v s2 Y Z
assume valid_A: "\<forall>t\<in>A. G\<Turnstile>n\<Colon>t"
assume conf_s0: "s0\<Colon>\<preceq>(G,L)"
assume normal_s0: "normal s0"
assume wt: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>Cast T e\<Colon>-castT"
assume da: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>dom (locals (store s0)) \<guillemotright>\<langle>Cast T e\<rangle>\<^sub>e\<guillemotright> E"
assume eval: "G\<turnstile>s0 \<midarrow>Cast T e-\<succ>v\<midarrow>n\<rightarrow> s2"
assume P: "(Normal P) Y s0 Z"
show "Q \<lfloor>v\<rfloor>\<^sub>e s2 Z \<and> s2\<Colon>\<preceq>(G, L)"
proof -
from wt obtain eT where
wt_e: "\<lparr>prg = G, cls = accC, lcl = L\<rparr>\<turnstile>e\<Colon>-eT"
by cases simp
from da obtain
da_e: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile> dom (locals (store s0)) \<guillemotright>\<langle>e\<rangle>\<^sub>e\<guillemotright> E"
by cases simp
from eval obtain s1 where
eval_e: "G\<turnstile>s0 \<midarrow>e-\<succ>v\<midarrow>n\<rightarrow> s1" and
s2: "s2 = abupd (raise_if (\<not> G,snd s1\<turnstile>v fits T) ClassCast) s1"
using normal_s0 by (fastforce elim: evaln_elim_cases)
from valid_e P valid_A conf_s0 eval_e wt_e da_e
have "(\<lambda>Val:v:. \<lambda>s.. abupd (raise_if (\<not> G,s\<turnstile>v fits T) ClassCast) .;
Q\<leftarrow>In1 v) \<lfloor>v\<rfloor>\<^sub>e s1 Z"
by (rule validE)
with s2 have "Q \<lfloor>v\<rfloor>\<^sub>e s2 Z"
by simp
moreover
from eval wt da conf_s0 wf
have "s2\<Colon>\<preceq>(G, L)"
by (rule evaln_type_sound [elim_format]) simp
ultimately show ?thesis ..
qed
qed
next
case (Inst A P e Q T)
assume valid_e: "G,A|\<Turnstile>\<Colon>{ {Normal P} e-\<succ>
{\<lambda>Val:v:. \<lambda>s.. Q\<leftarrow>In1 (Bool (v \<noteq> Null \<and> G,s\<turnstile>v fits RefT T))} }"
show "G,A|\<Turnstile>\<Colon>{ {Normal P} e InstOf T-\<succ> {Q} }"
proof (rule valid_expr_NormalI)
fix n s0 L accC instT E v s1 Y Z
assume valid_A: "\<forall>t\<in>A. G\<Turnstile>n\<Colon>t"
assume conf_s0: "s0\<Colon>\<preceq>(G,L)"
assume normal_s0: "normal s0"
assume wt: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>e InstOf T\<Colon>-instT"
assume da: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>dom (locals (store s0))\<guillemotright>\<langle>e InstOf T\<rangle>\<^sub>e\<guillemotright> E"
assume eval: "G\<turnstile>s0 \<midarrow>e InstOf T-\<succ>v\<midarrow>n\<rightarrow> s1"
assume P: "(Normal P) Y s0 Z"
show "Q \<lfloor>v\<rfloor>\<^sub>e s1 Z \<and> s1\<Colon>\<preceq>(G, L)"
proof -
from wt obtain eT where
wt_e: "\<lparr>prg = G, cls = accC, lcl = L\<rparr>\<turnstile>e\<Colon>-eT"
by cases simp
from da obtain
da_e: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile> dom (locals (store s0)) \<guillemotright>\<langle>e\<rangle>\<^sub>e\<guillemotright> E"
by cases simp
from eval obtain a where
eval_e: "G\<turnstile>s0 \<midarrow>e-\<succ>a\<midarrow>n\<rightarrow> s1" and
v: "v = Bool (a \<noteq> Null \<and> G,store s1\<turnstile>a fits RefT T)"
using normal_s0 by (fastforce elim: evaln_elim_cases)
from valid_e P valid_A conf_s0 eval_e wt_e da_e
have "(\<lambda>Val:v:. \<lambda>s.. Q\<leftarrow>In1 (Bool (v \<noteq> Null \<and> G,s\<turnstile>v fits RefT T)))
\<lfloor>a\<rfloor>\<^sub>e s1 Z"
by (rule validE)
with v have "Q \<lfloor>v\<rfloor>\<^sub>e s1 Z"
by simp
moreover
from eval wt da conf_s0 wf
have "s1\<Colon>\<preceq>(G, L)"
by (rule evaln_type_sound [elim_format]) simp
ultimately show ?thesis ..
qed
qed
next
case (Lit A P v)
show "G,A|\<Turnstile>\<Colon>{ {Normal (P\<leftarrow>In1 v)} Lit v-\<succ> {P} }"
proof (rule valid_expr_NormalI)
fix n L s0 s1 v' Y Z
assume conf_s0: "s0\<Colon>\<preceq>(G, L)"
assume normal_s0: " normal s0"
assume eval: "G\<turnstile>s0 \<midarrow>Lit v-\<succ>v'\<midarrow>n\<rightarrow> s1"
assume P: "(Normal (P\<leftarrow>In1 v)) Y s0 Z"
show "P \<lfloor>v'\<rfloor>\<^sub>e s1 Z \<and> s1\<Colon>\<preceq>(G, L)"
proof -
from eval have "s1=s0" and "v'=v"
using normal_s0 by (auto elim: evaln_elim_cases)
with P conf_s0 show ?thesis by simp
qed
qed
next
case (UnOp A P e Q unop)
assume valid_e: "G,A|\<Turnstile>\<Colon>{ {Normal P}e-\<succ>{\<lambda>Val:v:. Q\<leftarrow>In1 (eval_unop unop v)} }"
show "G,A|\<Turnstile>\<Colon>{ {Normal P} UnOp unop e-\<succ> {Q} }"
proof (rule valid_expr_NormalI)
fix n s0 L accC T E v s1 Y Z
assume valid_A: "\<forall>t\<in>A. G\<Turnstile>n\<Colon>t"
assume conf_s0: "s0\<Colon>\<preceq>(G,L)"
assume normal_s0: "normal s0"
assume wt: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>UnOp unop e\<Colon>-T"
assume da: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>dom (locals (store s0))\<guillemotright>\<langle>UnOp unop e\<rangle>\<^sub>e\<guillemotright>E"
assume eval: "G\<turnstile>s0 \<midarrow>UnOp unop e-\<succ>v\<midarrow>n\<rightarrow> s1"
assume P: "(Normal P) Y s0 Z"
show "Q \<lfloor>v\<rfloor>\<^sub>e s1 Z \<and> s1\<Colon>\<preceq>(G, L)"
proof -
from wt obtain eT where
wt_e: "\<lparr>prg = G, cls = accC, lcl = L\<rparr>\<turnstile>e\<Colon>-eT"
by cases simp
from da obtain
da_e: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile> dom (locals (store s0)) \<guillemotright>\<langle>e\<rangle>\<^sub>e\<guillemotright> E"
by cases simp
from eval obtain ve where
eval_e: "G\<turnstile>s0 \<midarrow>e-\<succ>ve\<midarrow>n\<rightarrow> s1" and
v: "v = eval_unop unop ve"
using normal_s0 by (fastforce elim: evaln_elim_cases)
from valid_e P valid_A conf_s0 eval_e wt_e da_e
have "(\<lambda>Val:v:. Q\<leftarrow>In1 (eval_unop unop v)) \<lfloor>ve\<rfloor>\<^sub>e s1 Z"
by (rule validE)
with v have "Q \<lfloor>v\<rfloor>\<^sub>e s1 Z"
by simp
moreover
from eval wt da conf_s0 wf
have "s1\<Colon>\<preceq>(G, L)"
by (rule evaln_type_sound [elim_format]) simp
ultimately show ?thesis ..
qed
qed
next
case (BinOp A P e1 Q binop e2 R)
assume valid_e1: "G,A|\<Turnstile>\<Colon>{ {Normal P} e1-\<succ> {Q} }"
have valid_e2: "\<And> v1. G,A|\<Turnstile>\<Colon>{ {Q\<leftarrow>In1 v1}
(if need_second_arg binop v1 then In1l e2 else In1r Skip)\<succ>
{\<lambda>Val:v2:. R\<leftarrow>In1 (eval_binop binop v1 v2)} }"
using BinOp.hyps by simp
show "G,A|\<Turnstile>\<Colon>{ {Normal P} BinOp binop e1 e2-\<succ> {R} }"
proof (rule valid_expr_NormalI)
fix n s0 L accC T E v s2 Y Z
assume valid_A: "\<forall>t\<in>A. G\<Turnstile>n\<Colon>t"
assume conf_s0: "s0\<Colon>\<preceq>(G,L)"
assume normal_s0: "normal s0"
assume wt: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>BinOp binop e1 e2\<Colon>-T"
assume da: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>
\<turnstile>dom (locals (store s0)) \<guillemotright>\<langle>BinOp binop e1 e2\<rangle>\<^sub>e\<guillemotright> E"
assume eval: "G\<turnstile>s0 \<midarrow>BinOp binop e1 e2-\<succ>v\<midarrow>n\<rightarrow> s2"
assume P: "(Normal P) Y s0 Z"
show "R \<lfloor>v\<rfloor>\<^sub>e s2 Z \<and> s2\<Colon>\<preceq>(G, L)"
proof -
from wt obtain e1T e2T where
wt_e1: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>e1\<Colon>-e1T" and
wt_e2: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>e2\<Colon>-e2T" and
wt_binop: "wt_binop G binop e1T e2T"
by cases simp
have wt_Skip: "\<lparr>prg = G, cls = accC, lcl = L\<rparr>\<turnstile>Skip\<Colon>\<surd>"
by simp
(*
obtain S where
daSkip: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>
\<turnstile> dom (locals (store s1)) \<guillemotright>In1r Skip\<guillemotright> S"
by (auto intro: da_Skip [simplified] assigned.select_convs) *)
from da obtain E1 where
da_e1: "\<lparr>prg=G,cls=accC,lcl=L\<rparr> \<turnstile> dom (locals (store s0)) \<guillemotright>\<langle>e1\<rangle>\<^sub>e\<guillemotright> E1"
by cases simp+
from eval obtain v1 s1 v2 where
eval_e1: "G\<turnstile>s0 \<midarrow>e1-\<succ>v1\<midarrow>n\<rightarrow> s1" and
eval_e2: "G\<turnstile>s1 \<midarrow>(if need_second_arg binop v1 then \<langle>e2\<rangle>\<^sub>e else \<langle>Skip\<rangle>\<^sub>s)
\<succ>\<midarrow>n\<rightarrow> (\<lfloor>v2\<rfloor>\<^sub>e, s2)" and
v: "v=eval_binop binop v1 v2"
using normal_s0 by (fastforce elim: evaln_elim_cases)
from valid_e1 P valid_A conf_s0 eval_e1 wt_e1 da_e1
obtain Q: "Q \<lfloor>v1\<rfloor>\<^sub>e s1 Z" and conf_s1: "s1\<Colon>\<preceq>(G,L)"
by (rule validE)
from Q have Q': "\<And> v. (Q\<leftarrow>In1 v1) v s1 Z"
by simp
have "(\<lambda>Val:v2:. R\<leftarrow>In1 (eval_binop binop v1 v2)) \<lfloor>v2\<rfloor>\<^sub>e s2 Z"
proof (cases "normal s1")
case True
from eval_e1 wt_e1 da_e1 conf_s0 wf
have conf_v1: "G,store s1\<turnstile>v1\<Colon>\<preceq>e1T"
by (rule evaln_type_sound [elim_format]) (insert True,simp)
from eval_e1
have "G\<turnstile>s0 \<midarrow>e1-\<succ>v1\<rightarrow> s1"
by (rule evaln_eval)
from da wt_e1 wt_e2 wt_binop conf_s0 True this conf_v1 wf
obtain E2 where
da_e2: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile> dom (locals (store s1))
\<guillemotright>(if need_second_arg binop v1 then \<langle>e2\<rangle>\<^sub>e else \<langle>Skip\<rangle>\<^sub>s)\<guillemotright> E2"
by (rule da_e2_BinOp [elim_format]) iprover
from wt_e2 wt_Skip obtain T2
where "\<lparr>prg=G,cls=accC,lcl=L\<rparr>
\<turnstile>(if need_second_arg binop v1 then \<langle>e2\<rangle>\<^sub>e else \<langle>Skip\<rangle>\<^sub>s)\<Colon>T2"
by (cases "need_second_arg binop v1") auto
note ve=validE [OF valid_e2,OF Q' valid_A conf_s1 eval_e2 this da_e2]
(* chaining Q', without extra OF causes unification error *)
thus ?thesis
by (rule ve)
next
case False
note ve=validE [OF valid_e2,OF Q' valid_A conf_s1 eval_e2]
with False show ?thesis
by iprover
qed
with v have "R \<lfloor>v\<rfloor>\<^sub>e s2 Z"
by simp
moreover
from eval wt da conf_s0 wf
have "s2\<Colon>\<preceq>(G, L)"
by (rule evaln_type_sound [elim_format]) simp
ultimately show ?thesis ..
qed
qed
next
case (Super A P)
show "G,A|\<Turnstile>\<Colon>{ {Normal (\<lambda>s.. P\<leftarrow>In1 (val_this s))} Super-\<succ> {P} }"
proof (rule valid_expr_NormalI)
fix n L s0 s1 v Y Z
assume conf_s0: "s0\<Colon>\<preceq>(G, L)"
assume normal_s0: " normal s0"
assume eval: "G\<turnstile>s0 \<midarrow>Super-\<succ>v\<midarrow>n\<rightarrow> s1"
assume P: "(Normal (\<lambda>s.. P\<leftarrow>In1 (val_this s))) Y s0 Z"
show "P \<lfloor>v\<rfloor>\<^sub>e s1 Z \<and> s1\<Colon>\<preceq>(G, L)"
proof -
from eval have "s1=s0" and "v=val_this (store s0)"
using normal_s0 by (auto elim: evaln_elim_cases)
with P conf_s0 show ?thesis by simp
qed
qed
next
case (Acc A P var Q)
note valid_var = `G,A|\<Turnstile>\<Colon>{ {Normal P} var=\<succ> {\<lambda>Var:(v, f):. Q\<leftarrow>In1 v} }`
show "G,A|\<Turnstile>\<Colon>{ {Normal P} Acc var-\<succ> {Q} }"
proof (rule valid_expr_NormalI)
fix n s0 L accC T E v s1 Y Z
assume valid_A: "\<forall>t\<in>A. G\<Turnstile>n\<Colon>t"
assume conf_s0: "s0\<Colon>\<preceq>(G,L)"
assume normal_s0: "normal s0"
assume wt: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>Acc var\<Colon>-T"
assume da: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>dom (locals (store s0))\<guillemotright>\<langle>Acc var\<rangle>\<^sub>e\<guillemotright>E"
assume eval: "G\<turnstile>s0 \<midarrow>Acc var-\<succ>v\<midarrow>n\<rightarrow> s1"
assume P: "(Normal P) Y s0 Z"
show "Q \<lfloor>v\<rfloor>\<^sub>e s1 Z \<and> s1\<Colon>\<preceq>(G, L)"
proof -
from wt obtain
wt_var: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>var\<Colon>=T"
by cases simp
from da obtain V where
da_var: "\<lparr>prg=G,cls=accC,lcl=L\<rparr> \<turnstile> dom (locals (store s0)) \<guillemotright>\<langle>var\<rangle>\<^sub>v\<guillemotright> V"
by (cases "\<exists> n. var=LVar n") (insert da.LVar,auto elim!: da_elim_cases)
from eval obtain upd where
eval_var: "G\<turnstile>s0 \<midarrow>var=\<succ>(v, upd)\<midarrow>n\<rightarrow> s1"
using normal_s0 by (fastforce elim: evaln_elim_cases)
from valid_var P valid_A conf_s0 eval_var wt_var da_var
have "(\<lambda>Var:(v, f):. Q\<leftarrow>In1 v) \<lfloor>(v, upd)\<rfloor>\<^sub>v s1 Z"
by (rule validE)
then have "Q \<lfloor>v\<rfloor>\<^sub>e s1 Z"
by simp
moreover
from eval wt da conf_s0 wf
have "s1\<Colon>\<preceq>(G, L)"
by (rule evaln_type_sound [elim_format]) simp
ultimately show ?thesis ..
qed
qed
next
case (Ass A P var Q e R)
note valid_var = `G,A|\<Turnstile>\<Colon>{ {Normal P} var=\<succ> {Q} }`
have valid_e: "\<And> vf.
G,A|\<Turnstile>\<Colon>{ {Q\<leftarrow>In2 vf} e-\<succ> {\<lambda>Val:v:. assign (snd vf) v .; R} }"
using Ass.hyps by simp
show "G,A|\<Turnstile>\<Colon>{ {Normal P} var:=e-\<succ> {R} }"
proof (rule valid_expr_NormalI)
fix n s0 L accC T E v s3 Y Z
assume valid_A: "\<forall>t\<in>A. G\<Turnstile>n\<Colon>t"
assume conf_s0: "s0\<Colon>\<preceq>(G,L)"
assume normal_s0: "normal s0"
assume wt: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>var:=e\<Colon>-T"
assume da: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>dom (locals (store s0))\<guillemotright>\<langle>var:=e\<rangle>\<^sub>e\<guillemotright>E"
assume eval: "G\<turnstile>s0 \<midarrow>var:=e-\<succ>v\<midarrow>n\<rightarrow> s3"
assume P: "(Normal P) Y s0 Z"
show "R \<lfloor>v\<rfloor>\<^sub>e s3 Z \<and> s3\<Colon>\<preceq>(G, L)"
proof -
from wt obtain varT where
wt_var: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>var\<Colon>=varT" and
wt_e: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>e\<Colon>-T"
by cases simp
from eval obtain w upd s1 s2 where
eval_var: "G\<turnstile>s0 \<midarrow>var=\<succ>(w, upd)\<midarrow>n\<rightarrow> s1" and
eval_e: "G\<turnstile>s1 \<midarrow>e-\<succ>v\<midarrow>n\<rightarrow> s2" and
s3: "s3=assign upd v s2"
using normal_s0 by (auto elim: evaln_elim_cases)
have "R \<lfloor>v\<rfloor>\<^sub>e s3 Z"
proof (cases "\<exists> vn. var = LVar vn")
case False
with da obtain V where
da_var: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>
\<turnstile> dom (locals (store s0)) \<guillemotright>\<langle>var\<rangle>\<^sub>v\<guillemotright> V" and
da_e: "\<lparr>prg=G,cls=accC,lcl=L\<rparr> \<turnstile> nrm V \<guillemotright>\<langle>e\<rangle>\<^sub>e\<guillemotright> E"
by cases simp+
from valid_var P valid_A conf_s0 eval_var wt_var da_var
obtain Q: "Q \<lfloor>(w,upd)\<rfloor>\<^sub>v s1 Z" and conf_s1: "s1\<Colon>\<preceq>(G,L)"
by (rule validE)
hence Q': "\<And> v. (Q\<leftarrow>In2 (w,upd)) v s1 Z"
by simp
have "(\<lambda>Val:v:. assign (snd (w,upd)) v .; R) \<lfloor>v\<rfloor>\<^sub>e s2 Z"
proof (cases "normal s1")
case True
obtain E' where
da_e': "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile> dom (locals (store s1)) \<guillemotright>\<langle>e\<rangle>\<^sub>e\<guillemotright> E'"
proof -
from eval_var wt_var da_var wf True
have "nrm V \<subseteq> dom (locals (store s1))"
by (cases rule: da_good_approx_evalnE) iprover
with da_e show thesis
by (rule da_weakenE) (rule that)
qed
note ve=validE [OF valid_e,OF Q' valid_A conf_s1 eval_e wt_e da_e']
show ?thesis
by (rule ve)
next
case False
note ve=validE [OF valid_e,OF Q' valid_A conf_s1 eval_e]
with False show ?thesis
by iprover
qed
with s3 show "R \<lfloor>v\<rfloor>\<^sub>e s3 Z"
by simp
next
case True
then obtain vn where
vn: "var = LVar vn"
by auto
with da obtain E where
da_e: "\<lparr>prg=G,cls=accC,lcl=L\<rparr> \<turnstile> dom (locals (store s0)) \<guillemotright>\<langle>e\<rangle>\<^sub>e\<guillemotright> E"
by cases simp+
from da.LVar vn obtain V where
da_var: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>
\<turnstile> dom (locals (store s0)) \<guillemotright>\<langle>var\<rangle>\<^sub>v\<guillemotright> V"
by auto
from valid_var P valid_A conf_s0 eval_var wt_var da_var
obtain Q: "Q \<lfloor>(w,upd)\<rfloor>\<^sub>v s1 Z" and conf_s1: "s1\<Colon>\<preceq>(G,L)"
by (rule validE)
hence Q': "\<And> v. (Q\<leftarrow>In2 (w,upd)) v s1 Z"
by simp
have "(\<lambda>Val:v:. assign (snd (w,upd)) v .; R) \<lfloor>v\<rfloor>\<^sub>e s2 Z"
proof (cases "normal s1")
case True
obtain E' where
da_e': "\<lparr>prg=G,cls=accC,lcl=L\<rparr>
\<turnstile> dom (locals (store s1)) \<guillemotright>\<langle>e\<rangle>\<^sub>e\<guillemotright> E'"
proof -
from eval_var
have "dom (locals (store s0)) \<subseteq> dom (locals (store (s1)))"
by (rule dom_locals_evaln_mono_elim)
with da_e show thesis
by (rule da_weakenE) (rule that)
qed
note ve=validE [OF valid_e,OF Q' valid_A conf_s1 eval_e wt_e da_e']
show ?thesis
by (rule ve)
next
case False
note ve=validE [OF valid_e,OF Q' valid_A conf_s1 eval_e]
with False show ?thesis
by iprover
qed
with s3 show "R \<lfloor>v\<rfloor>\<^sub>e s3 Z"
by simp
qed
moreover
from eval wt da conf_s0 wf
have "s3\<Colon>\<preceq>(G, L)"
by (rule evaln_type_sound [elim_format]) simp
ultimately show ?thesis ..
qed
qed
next
case (Cond A P e0 P' e1 e2 Q)
note valid_e0 = `G,A|\<Turnstile>\<Colon>{ {Normal P} e0-\<succ> {P'} }`
have valid_then_else:"\<And> b. G,A|\<Turnstile>\<Colon>{ {P'\<leftarrow>=b} (if b then e1 else e2)-\<succ> {Q} }"
using Cond.hyps by simp
show "G,A|\<Turnstile>\<Colon>{ {Normal P} e0 ? e1 : e2-\<succ> {Q} }"
proof (rule valid_expr_NormalI)
fix n s0 L accC T E v s2 Y Z
assume valid_A: "\<forall>t\<in>A. G\<Turnstile>n\<Colon>t"
assume conf_s0: "s0\<Colon>\<preceq>(G,L)"
assume normal_s0: "normal s0"
assume wt: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>e0 ? e1 : e2\<Colon>-T"
assume da: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>dom (locals (store s0))\<guillemotright>\<langle>e0 ? e1:e2\<rangle>\<^sub>e\<guillemotright>E"
assume eval: "G\<turnstile>s0 \<midarrow>e0 ? e1 : e2-\<succ>v\<midarrow>n\<rightarrow> s2"
assume P: "(Normal P) Y s0 Z"
show "Q \<lfloor>v\<rfloor>\<^sub>e s2 Z \<and> s2\<Colon>\<preceq>(G, L)"
proof -
from wt obtain T1 T2 where
wt_e0: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>e0\<Colon>-PrimT Boolean" and
wt_e1: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>e1\<Colon>-T1" and
wt_e2: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>e2\<Colon>-T2"
by cases simp
from da obtain E0 E1 E2 where
da_e0: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile> dom (locals (store s0)) \<guillemotright>\<langle>e0\<rangle>\<^sub>e\<guillemotright> E0" and
da_e1: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>
\<turnstile>(dom (locals (store s0)) \<union> assigns_if True e0)\<guillemotright>\<langle>e1\<rangle>\<^sub>e\<guillemotright> E1" and
da_e2: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>
\<turnstile>(dom (locals (store s0)) \<union> assigns_if False e0)\<guillemotright>\<langle>e2\<rangle>\<^sub>e\<guillemotright> E2"
by cases simp+
from eval obtain b s1 where
eval_e0: "G\<turnstile>s0 \<midarrow>e0-\<succ>b\<midarrow>n\<rightarrow> s1" and
eval_then_else: "G\<turnstile>s1 \<midarrow>(if the_Bool b then e1 else e2)-\<succ>v\<midarrow>n\<rightarrow> s2"
using normal_s0 by (fastforce elim: evaln_elim_cases)
from valid_e0 P valid_A conf_s0 eval_e0 wt_e0 da_e0
obtain "P' \<lfloor>b\<rfloor>\<^sub>e s1 Z" and conf_s1: "s1\<Colon>\<preceq>(G,L)"
by (rule validE)
hence P': "\<And> v. (P'\<leftarrow>=(the_Bool b)) v s1 Z"
by (cases "normal s1") auto
have "Q \<lfloor>v\<rfloor>\<^sub>e s2 Z"
proof (cases "normal s1")
case True
note normal_s1=this
from wt_e1 wt_e2 obtain T' where
wt_then_else:
"\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>(if the_Bool b then e1 else e2)\<Colon>-T'"
by (cases "the_Bool b") simp+
have s0_s1: "dom (locals (store s0))
\<union> assigns_if (the_Bool b) e0 \<subseteq> dom (locals (store s1))"
proof -
from eval_e0
have eval_e0': "G\<turnstile>s0 \<midarrow>e0-\<succ>b\<rightarrow> s1"
by (rule evaln_eval)
hence
"dom (locals (store s0)) \<subseteq> dom (locals (store s1))"
by (rule dom_locals_eval_mono_elim)
moreover
from eval_e0' True wt_e0
have "assigns_if (the_Bool b) e0 \<subseteq> dom (locals (store s1))"
by (rule assigns_if_good_approx')
ultimately show ?thesis by (rule Un_least)
qed
obtain E' where
da_then_else:
"\<lparr>prg=G,cls=accC,lcl=L\<rparr>
\<turnstile>dom (locals (store s1))\<guillemotright>\<langle>if the_Bool b then e1 else e2\<rangle>\<^sub>e\<guillemotright> E'"
proof (cases "the_Bool b")
case True
with that da_e1 s0_s1 show ?thesis
by simp (erule da_weakenE,auto)
next
case False
with that da_e2 s0_s1 show ?thesis
by simp (erule da_weakenE,auto)
qed
with valid_then_else P' valid_A conf_s1 eval_then_else wt_then_else
show ?thesis
by (rule validE)
next
case False
with valid_then_else P' valid_A conf_s1 eval_then_else
show ?thesis
by (cases rule: validE) iprover+
qed
moreover
from eval wt da conf_s0 wf
have "s2\<Colon>\<preceq>(G, L)"
by (rule evaln_type_sound [elim_format]) simp
ultimately show ?thesis ..
qed
qed
next
case (Call A P e Q args R mode statT mn pTs' S accC')
note valid_e = `G,A|\<Turnstile>\<Colon>{ {Normal P} e-\<succ> {Q} }`
have valid_args: "\<And> a. G,A|\<Turnstile>\<Colon>{ {Q\<leftarrow>In1 a} args\<doteq>\<succ> {R a} }"
using Call.hyps by simp
have valid_methd: "\<And> a vs invC declC l.
G,A|\<Turnstile>\<Colon>{ {R a\<leftarrow>In3 vs \<and>.
(\<lambda>s. declC =
invocation_declclass G mode (store s) a statT
\<lparr>name = mn, parTs = pTs'\<rparr> \<and>
invC = invocation_class mode (store s) a statT \<and>
l = locals (store s)) ;.
init_lvars G declC \<lparr>name = mn, parTs = pTs'\<rparr> mode a vs \<and>.
(\<lambda>s. normal s \<longrightarrow> G\<turnstile>mode\<rightarrow>invC\<preceq>statT)}
Methd declC \<lparr>name=mn,parTs=pTs'\<rparr>-\<succ> {set_lvars l .; S} }"
using Call.hyps by simp
show "G,A|\<Turnstile>\<Colon>{ {Normal P} {accC',statT,mode}e\<cdot>mn( {pTs'}args)-\<succ> {S} }"
proof (rule valid_expr_NormalI)
fix n s0 L accC T E v s5 Y Z
assume valid_A: "\<forall>t\<in>A. G\<Turnstile>n\<Colon>t"
assume conf_s0: "s0\<Colon>\<preceq>(G,L)"
assume normal_s0: "normal s0"
assume wt: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>{accC',statT,mode}e\<cdot>mn( {pTs'}args)\<Colon>-T"
assume da: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>dom (locals (store s0))
\<guillemotright>\<langle>{accC',statT,mode}e\<cdot>mn( {pTs'}args)\<rangle>\<^sub>e\<guillemotright> E"
assume eval: "G\<turnstile>s0 \<midarrow>{accC',statT,mode}e\<cdot>mn( {pTs'}args)-\<succ>v\<midarrow>n\<rightarrow> s5"
assume P: "(Normal P) Y s0 Z"
show "S \<lfloor>v\<rfloor>\<^sub>e s5 Z \<and> s5\<Colon>\<preceq>(G, L)"
proof -
from wt obtain pTs statDeclT statM where
wt_e: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>e\<Colon>-RefT statT" and
wt_args: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>args\<Colon>\<doteq>pTs" and
statM: "max_spec G accC statT \<lparr>name=mn,parTs=pTs\<rparr>
= {((statDeclT,statM),pTs')}" and
mode: "mode = invmode statM e" and
T: "T =(resTy statM)" and
eq_accC_accC': "accC=accC'"
by cases fastforce+
from da obtain C where
da_e: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile> (dom (locals (store s0)))\<guillemotright>\<langle>e\<rangle>\<^sub>e\<guillemotright> C" and
da_args: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile> nrm C \<guillemotright>\<langle>args\<rangle>\<^sub>l\<guillemotright> E"
by cases simp
from eval eq_accC_accC' obtain a s1 vs s2 s3 s3' s4 invDeclC where
evaln_e: "G\<turnstile>s0 \<midarrow>e-\<succ>a\<midarrow>n\<rightarrow> s1" and
evaln_args: "G\<turnstile>s1 \<midarrow>args\<doteq>\<succ>vs\<midarrow>n\<rightarrow> s2" and
invDeclC: "invDeclC = invocation_declclass
G mode (store s2) a statT \<lparr>name=mn,parTs=pTs'\<rparr>" and
s3: "s3 = init_lvars G invDeclC \<lparr>name=mn,parTs=pTs'\<rparr> mode a vs s2" and
check: "s3' = check_method_access G
accC' statT mode \<lparr>name = mn, parTs = pTs'\<rparr> a s3" and
evaln_methd:
"G\<turnstile>s3' \<midarrow>Methd invDeclC \<lparr>name=mn,parTs=pTs'\<rparr>-\<succ>v\<midarrow>n\<rightarrow> s4" and
s5: "s5=(set_lvars (locals (store s2))) s4"
using normal_s0 by (auto elim: evaln_elim_cases)
from evaln_e
have eval_e: "G\<turnstile>s0 \<midarrow>e-\<succ>a\<rightarrow> s1"
by (rule evaln_eval)
from eval_e _ wt_e wf
have s1_no_return: "abrupt s1 \<noteq> Some (Jump Ret)"
by (rule eval_expression_no_jump
[where ?Env="\<lparr>prg=G,cls=accC,lcl=L\<rparr>",simplified])
(insert normal_s0,auto)
from valid_e P valid_A conf_s0 evaln_e wt_e da_e
obtain "Q \<lfloor>a\<rfloor>\<^sub>e s1 Z" and conf_s1: "s1\<Colon>\<preceq>(G,L)"
by (rule validE)
hence Q: "\<And> v. (Q\<leftarrow>In1 a) v s1 Z"
by simp
obtain
R: "(R a) \<lfloor>vs\<rfloor>\<^sub>l s2 Z" and
conf_s2: "s2\<Colon>\<preceq>(G,L)" and
s2_no_return: "abrupt s2 \<noteq> Some (Jump Ret)"
proof (cases "normal s1")
case True
obtain E' where
da_args':
"\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile> dom (locals (store s1)) \<guillemotright>\<langle>args\<rangle>\<^sub>l\<guillemotright> E'"
proof -
from evaln_e wt_e da_e wf True
have "nrm C \<subseteq> dom (locals (store s1))"
by (cases rule: da_good_approx_evalnE) iprover
with da_args show thesis
by (rule da_weakenE) (rule that)
qed
with valid_args Q valid_A conf_s1 evaln_args wt_args
obtain "(R a) \<lfloor>vs\<rfloor>\<^sub>l s2 Z" "s2\<Colon>\<preceq>(G,L)"
by (rule validE)
moreover
from evaln_args
have e: "G\<turnstile>s1 \<midarrow>args\<doteq>\<succ>vs\<rightarrow> s2"
by (rule evaln_eval)
from this s1_no_return wt_args wf
have "abrupt s2 \<noteq> Some (Jump Ret)"
by (rule eval_expression_list_no_jump
[where ?Env="\<lparr>prg=G,cls=accC,lcl=L\<rparr>",simplified])
ultimately show ?thesis ..
next
case False
with valid_args Q valid_A conf_s1 evaln_args
obtain "(R a) \<lfloor>vs\<rfloor>\<^sub>l s2 Z" "s2\<Colon>\<preceq>(G,L)"
by (cases rule: validE) iprover+
moreover
from False evaln_args have "s2=s1"
by auto
with s1_no_return have "abrupt s2 \<noteq> Some (Jump Ret)"
by simp
ultimately show ?thesis ..
qed
obtain invC where
invC: "invC = invocation_class mode (store s2) a statT"
by simp
with s3
have invC': "invC = (invocation_class mode (store s3) a statT)"
by (cases s2,cases mode) (auto simp add: init_lvars_def2 )
obtain l where
l: "l = locals (store s2)"
by simp
from eval wt da conf_s0 wf
have conf_s5: "s5\<Colon>\<preceq>(G, L)"
by (rule evaln_type_sound [elim_format]) simp
let "PROP ?R" = "\<And> v.
(R a\<leftarrow>In3 vs \<and>.
(\<lambda>s. invDeclC = invocation_declclass G mode (store s) a statT
\<lparr>name = mn, parTs = pTs'\<rparr> \<and>
invC = invocation_class mode (store s) a statT \<and>
l = locals (store s)) ;.
init_lvars G invDeclC \<lparr>name = mn, parTs = pTs'\<rparr> mode a vs \<and>.
(\<lambda>s. normal s \<longrightarrow> G\<turnstile>mode\<rightarrow>invC\<preceq>statT)
) v s3' Z"
{
assume abrupt_s3: "\<not> normal s3"
have "S \<lfloor>v\<rfloor>\<^sub>e s5 Z"
proof -
from abrupt_s3 check have eq_s3'_s3: "s3'=s3"
by (auto simp add: check_method_access_def Let_def)
with R s3 invDeclC invC l abrupt_s3
have R': "PROP ?R"
by auto
have conf_s3': "s3'\<Colon>\<preceq>(G, empty)"
(* we need an arbirary environment (here empty) that s2' conforms to
to apply validE *)
proof -
from s2_no_return s3
have "abrupt s3 \<noteq> Some (Jump Ret)"
by (cases s2) (auto simp add: init_lvars_def2 split: split_if_asm)
moreover
obtain abr2 str2 where s2: "s2=(abr2,str2)"
by (cases s2)
from s3 s2 conf_s2 have "(abrupt s3,str2)\<Colon>\<preceq>(G, L)"
by (auto simp add: init_lvars_def2 split: split_if_asm)
ultimately show ?thesis
using s3 s2 eq_s3'_s3
apply (simp add: init_lvars_def2)
apply (rule conforms_set_locals [OF _ wlconf_empty])
by auto
qed
from valid_methd R' valid_A conf_s3' evaln_methd abrupt_s3 eq_s3'_s3
have "(set_lvars l .; S) \<lfloor>v\<rfloor>\<^sub>e s4 Z"
by (cases rule: validE) simp+
with s5 l show ?thesis
by simp
qed
} note abrupt_s3_lemma = this
have "S \<lfloor>v\<rfloor>\<^sub>e s5 Z"
proof (cases "normal s2")
case False
with s3 have abrupt_s3: "\<not> normal s3"
by (cases s2) (simp add: init_lvars_def2)
thus ?thesis
by (rule abrupt_s3_lemma)
next
case True
note normal_s2 = this
with evaln_args
have normal_s1: "normal s1"
by (rule evaln_no_abrupt)
obtain E' where
da_args':
"\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile> dom (locals (store s1)) \<guillemotright>\<langle>args\<rangle>\<^sub>l\<guillemotright> E'"
proof -
from evaln_e wt_e da_e wf normal_s1
have "nrm C \<subseteq> dom (locals (store s1))"
by (cases rule: da_good_approx_evalnE) iprover
with da_args show thesis
by (rule da_weakenE) (rule that)
qed
from evaln_args
have eval_args: "G\<turnstile>s1 \<midarrow>args\<doteq>\<succ>vs\<rightarrow> s2"
by (rule evaln_eval)
from evaln_e wt_e da_e conf_s0 wf
have conf_a: "G, store s1\<turnstile>a\<Colon>\<preceq>RefT statT"
by (rule evaln_type_sound [elim_format]) (insert normal_s1,simp)
with normal_s1 normal_s2 eval_args
have conf_a_s2: "G, store s2\<turnstile>a\<Colon>\<preceq>RefT statT"
by (auto dest: eval_gext)
from evaln_args wt_args da_args' conf_s1 wf
have conf_args: "list_all2 (conf G (store s2)) vs pTs"
by (rule evaln_type_sound [elim_format]) (insert normal_s2,simp)
from statM
obtain
statM': "(statDeclT,statM)\<in>mheads G accC statT \<lparr>name=mn,parTs=pTs'\<rparr>"
and
pTs_widen: "G\<turnstile>pTs[\<preceq>]pTs'"
by (blast dest: max_spec2mheads)
show ?thesis
proof (cases "normal s3")
case False
thus ?thesis
by (rule abrupt_s3_lemma)
next
case True
note normal_s3 = this
with s3 have notNull: "mode = IntVir \<longrightarrow> a \<noteq> Null"
by (cases s2) (auto simp add: init_lvars_def2)
from conf_s2 conf_a_s2 wf notNull invC
have dynT_prop: "G\<turnstile>mode\<rightarrow>invC\<preceq>statT"
by (cases s2) (auto intro: DynT_propI)
with wt_e statM' invC mode wf
obtain dynM where
dynM: "dynlookup G statT invC \<lparr>name=mn,parTs=pTs'\<rparr> = Some dynM" and
acc_dynM: "G \<turnstile>Methd \<lparr>name=mn,parTs=pTs'\<rparr> dynM
in invC dyn_accessible_from accC"
by (force dest!: call_access_ok)
with invC' check eq_accC_accC'
have eq_s3'_s3: "s3'=s3"
by (auto simp add: check_method_access_def Let_def)
with dynT_prop R s3 invDeclC invC l
have R': "PROP ?R"
by auto
from dynT_prop wf wt_e statM' mode invC invDeclC dynM
obtain
dynM: "dynlookup G statT invC \<lparr>name=mn,parTs=pTs'\<rparr> = Some dynM" and
wf_dynM: "wf_mdecl G invDeclC (\<lparr>name=mn,parTs=pTs'\<rparr>,mthd dynM)" and
dynM': "methd G invDeclC \<lparr>name=mn,parTs=pTs'\<rparr> = Some dynM" and
iscls_invDeclC: "is_class G invDeclC" and
invDeclC': "invDeclC = declclass dynM" and
invC_widen: "G\<turnstile>invC\<preceq>\<^sub>C invDeclC" and
resTy_widen: "G\<turnstile>resTy dynM\<preceq>resTy statM" and
is_static_eq: "is_static dynM = is_static statM" and
involved_classes_prop:
"(if invmode statM e = IntVir
then \<forall>statC. statT = ClassT statC \<longrightarrow> G\<turnstile>invC\<preceq>\<^sub>C statC
else ((\<exists>statC. statT = ClassT statC \<and> G\<turnstile>statC\<preceq>\<^sub>C invDeclC) \<or>
(\<forall>statC. statT \<noteq> ClassT statC \<and> invDeclC = Object)) \<and>
statDeclT = ClassT invDeclC)"
by (cases rule: DynT_mheadsE) simp
obtain L' where
L':"L'=(\<lambda> k.
(case k of
EName e
\<Rightarrow> (case e of
VNam v
\<Rightarrow>(table_of (lcls (mbody (mthd dynM)))
(pars (mthd dynM)[\<mapsto>]pTs')) v
| Res \<Rightarrow> Some (resTy dynM))
| This \<Rightarrow> if is_static statM
then None else Some (Class invDeclC)))"
by simp
from wf_dynM [THEN wf_mdeclD1, THEN conjunct1] normal_s2 conf_s2 wt_e
wf eval_args conf_a mode notNull wf_dynM involved_classes_prop
have conf_s3: "s3\<Colon>\<preceq>(G,L')"
apply -
(* FIXME confomrs_init_lvars should be
adjusted to be more directy applicable *)
apply (drule conforms_init_lvars [of G invDeclC
"\<lparr>name=mn,parTs=pTs'\<rparr>" dynM "store s2" vs pTs "abrupt s2"
L statT invC a "(statDeclT,statM)" e])
apply (rule wf)
apply (rule conf_args)
apply (simp add: pTs_widen)
apply (cases s2,simp)
apply (rule dynM')
apply (force dest: ty_expr_is_type)
apply (rule invC_widen)
apply (force dest: eval_gext)
apply simp
apply simp
apply (simp add: invC)
apply (simp add: invDeclC)
apply (simp add: normal_s2)
apply (cases s2, simp add: L' init_lvars_def2 s3
cong add: lname.case_cong ename.case_cong)
done
with eq_s3'_s3 have conf_s3': "s3'\<Colon>\<preceq>(G,L')" by simp
from is_static_eq wf_dynM L'
obtain mthdT where
"\<lparr>prg=G,cls=invDeclC,lcl=L'\<rparr>
\<turnstile>Body invDeclC (stmt (mbody (mthd dynM)))\<Colon>-mthdT" and
mthdT_widen: "G\<turnstile>mthdT\<preceq>resTy dynM"
by - (drule wf_mdecl_bodyD,
auto simp add: callee_lcl_def
cong add: lname.case_cong ename.case_cong)
with dynM' iscls_invDeclC invDeclC'
have
wt_methd:
"\<lparr>prg=G,cls=invDeclC,lcl=L'\<rparr>
\<turnstile>(Methd invDeclC \<lparr>name = mn, parTs = pTs'\<rparr>)\<Colon>-mthdT"
by (auto intro: wt.Methd)
obtain M where
da_methd:
"\<lparr>prg=G,cls=invDeclC,lcl=L'\<rparr>
\<turnstile> dom (locals (store s3'))
\<guillemotright>\<langle>Methd invDeclC \<lparr>name=mn,parTs=pTs'\<rparr>\<rangle>\<^sub>e\<guillemotright> M"
proof -
from wf_dynM
obtain M' where
da_body:
"\<lparr>prg=G, cls=invDeclC
,lcl=callee_lcl invDeclC \<lparr>name = mn, parTs = pTs'\<rparr> (mthd dynM)
\<rparr> \<turnstile> parameters (mthd dynM) \<guillemotright>\<langle>stmt (mbody (mthd dynM))\<rangle>\<guillemotright> M'" and
res: "Result \<in> nrm M'"
by (rule wf_mdeclE) iprover
from da_body is_static_eq L' have
"\<lparr>prg=G, cls=invDeclC,lcl=L'\<rparr>
\<turnstile> parameters (mthd dynM) \<guillemotright>\<langle>stmt (mbody (mthd dynM))\<rangle>\<guillemotright> M'"
by (simp add: callee_lcl_def
cong add: lname.case_cong ename.case_cong)
moreover have "parameters (mthd dynM) \<subseteq> dom (locals (store s3'))"
proof -
from is_static_eq
have "(invmode (mthd dynM) e) = (invmode statM e)"
by (simp add: invmode_def)
moreover
have "length (pars (mthd dynM)) = length vs"
proof -
from normal_s2 conf_args
have "length vs = length pTs"
by (simp add: list_all2_iff)
also from pTs_widen
have "\<dots> = length pTs'"
by (simp add: widens_def list_all2_iff)
also from wf_dynM
have "\<dots> = length (pars (mthd dynM))"
by (simp add: wf_mdecl_def wf_mhead_def)
finally show ?thesis ..
qed
moreover note s3 dynM' is_static_eq normal_s2 mode
ultimately
have "parameters (mthd dynM) = dom (locals (store s3))"
using dom_locals_init_lvars
[of "mthd dynM" G invDeclC "\<lparr>name=mn,parTs=pTs'\<rparr>" vs e a s2]
by simp
thus ?thesis using eq_s3'_s3 by simp
qed
ultimately obtain M2 where
da:
"\<lparr>prg=G, cls=invDeclC,lcl=L'\<rparr>
\<turnstile> dom (locals (store s3')) \<guillemotright>\<langle>stmt (mbody (mthd dynM))\<rangle>\<guillemotright> M2" and
M2: "nrm M' \<subseteq> nrm M2"
by (rule da_weakenE)
from res M2 have "Result \<in> nrm M2"
by blast
moreover from wf_dynM
have "jumpNestingOkS {Ret} (stmt (mbody (mthd dynM)))"
by (rule wf_mdeclE)
ultimately
obtain M3 where
"\<lparr>prg=G, cls=invDeclC,lcl=L'\<rparr> \<turnstile> dom (locals (store s3'))
\<guillemotright>\<langle>Body (declclass dynM) (stmt (mbody (mthd dynM)))\<rangle>\<guillemotright> M3"
using da
by (iprover intro: da.Body assigned.select_convs)
from _ this [simplified]
show thesis
by (rule da.Methd [simplified,elim_format])
(auto intro: dynM' that)
qed
from valid_methd R' valid_A conf_s3' evaln_methd wt_methd da_methd
have "(set_lvars l .; S) \<lfloor>v\<rfloor>\<^sub>e s4 Z"
by (cases rule: validE) iprover+
with s5 l show ?thesis
by simp
qed
qed
with conf_s5 show ?thesis by iprover
qed
qed
next
case (Methd A P Q ms)
note valid_body = `G,A \<union> {{P} Methd-\<succ> {Q} | ms}|\<Turnstile>\<Colon>{{P} body G-\<succ> {Q} | ms}`
show "G,A|\<Turnstile>\<Colon>{{P} Methd-\<succ> {Q} | ms}"
by (rule Methd_sound) (rule Methd.hyps)
next
case (Body A P D Q c R)
note valid_init = `G,A|\<Turnstile>\<Colon>{ {Normal P} .Init D. {Q} }`
note valid_c = `G,A|\<Turnstile>\<Colon>{ {Q} .c.
{\<lambda>s.. abupd (absorb Ret) .; R\<leftarrow>In1 (the (locals s Result))} }`
show "G,A|\<Turnstile>\<Colon>{ {Normal P} Body D c-\<succ> {R} }"
proof (rule valid_expr_NormalI)
fix n s0 L accC T E v s4 Y Z
assume valid_A: "\<forall>t\<in>A. G\<Turnstile>n\<Colon>t"
assume conf_s0: "s0\<Colon>\<preceq>(G,L)"
assume normal_s0: "normal s0"
assume wt: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>Body D c\<Colon>-T"
assume da: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>dom (locals (store s0))\<guillemotright>\<langle>Body D c\<rangle>\<^sub>e\<guillemotright>E"
assume eval: "G\<turnstile>s0 \<midarrow>Body D c-\<succ>v\<midarrow>n\<rightarrow> s4"
assume P: "(Normal P) Y s0 Z"
show "R \<lfloor>v\<rfloor>\<^sub>e s4 Z \<and> s4\<Colon>\<preceq>(G, L)"
proof -
from wt obtain
iscls_D: "is_class G D" and
wt_init: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>Init D\<Colon>\<surd>" and
wt_c: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>c\<Colon>\<surd>"
by cases auto
obtain I where
da_init:"\<lparr>prg=G,cls=accC,lcl=L\<rparr> \<turnstile> dom (locals (store s0)) \<guillemotright>\<langle>Init D\<rangle>\<^sub>s\<guillemotright> I"
by (auto intro: da_Init [simplified] assigned.select_convs)
from da obtain C where
da_c: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile> (dom (locals (store s0)))\<guillemotright>\<langle>c\<rangle>\<^sub>s\<guillemotright> C" and
jmpOk: "jumpNestingOkS {Ret} c"
by cases simp
from eval obtain s1 s2 s3 where
eval_init: "G\<turnstile>s0 \<midarrow>Init D\<midarrow>n\<rightarrow> s1" and
eval_c: "G\<turnstile>s1 \<midarrow>c\<midarrow>n\<rightarrow> s2" and
v: "v = the (locals (store s2) Result)" and
s3: "s3 =(if \<exists>l. abrupt s2 = Some (Jump (Break l)) \<or>
abrupt s2 = Some (Jump (Cont l))
then abupd (\<lambda>x. Some (Error CrossMethodJump)) s2 else s2)"and
s4: "s4 = abupd (absorb Ret) s3"
using normal_s0 by (fastforce elim: evaln_elim_cases)
obtain C' where
da_c': "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile> (dom (locals (store s1)))\<guillemotright>\<langle>c\<rangle>\<^sub>s\<guillemotright> C'"
proof -
from eval_init
have "(dom (locals (store s0))) \<subseteq> (dom (locals (store s1)))"
by (rule dom_locals_evaln_mono_elim)
with da_c show thesis by (rule da_weakenE) (rule that)
qed
from valid_init P valid_A conf_s0 eval_init wt_init da_init
obtain Q: "Q \<diamondsuit> s1 Z" and conf_s1: "s1\<Colon>\<preceq>(G,L)"
by (rule validE)
from valid_c Q valid_A conf_s1 eval_c wt_c da_c'
have R: "(\<lambda>s.. abupd (absorb Ret) .; R\<leftarrow>In1 (the (locals s Result)))
\<diamondsuit> s2 Z"
by (rule validE)
have "s3=s2"
proof -
from eval_init [THEN evaln_eval] wf
have s1_no_jmp: "\<And> j. abrupt s1 \<noteq> Some (Jump j)"
by - (rule eval_statement_no_jump [OF _ _ _ wt_init],
insert normal_s0,auto)
from eval_c [THEN evaln_eval] _ wt_c wf
have "\<And> j. abrupt s2 = Some (Jump j) \<Longrightarrow> j=Ret"
by (rule jumpNestingOk_evalE) (auto intro: jmpOk simp add: s1_no_jmp)
moreover note s3
ultimately show ?thesis
by (force split: split_if)
qed
with R v s4
have "R \<lfloor>v\<rfloor>\<^sub>e s4 Z"
by simp
moreover
from eval wt da conf_s0 wf
have "s4\<Colon>\<preceq>(G, L)"
by (rule evaln_type_sound [elim_format]) simp
ultimately show ?thesis ..
qed
qed
next
case (Nil A P)
show "G,A|\<Turnstile>\<Colon>{ {Normal (P\<leftarrow>\<lfloor>[]\<rfloor>\<^sub>l)} []\<doteq>\<succ> {P} }"
proof (rule valid_expr_list_NormalI)
fix s0 s1 vs n L Y Z
assume conf_s0: "s0\<Colon>\<preceq>(G,L)"
assume normal_s0: "normal s0"
assume eval: "G\<turnstile>s0 \<midarrow>[]\<doteq>\<succ>vs\<midarrow>n\<rightarrow> s1"
assume P: "(Normal (P\<leftarrow>\<lfloor>[]\<rfloor>\<^sub>l)) Y s0 Z"
show "P \<lfloor>vs\<rfloor>\<^sub>l s1 Z \<and> s1\<Colon>\<preceq>(G, L)"
proof -
from eval obtain "vs=[]" "s1=s0"
using normal_s0 by (auto elim: evaln_elim_cases)
with P conf_s0 show ?thesis
by simp
qed
qed
next
case (Cons A P e Q es R)
note valid_e = `G,A|\<Turnstile>\<Colon>{ {Normal P} e-\<succ> {Q} }`
have valid_es: "\<And> v. G,A|\<Turnstile>\<Colon>{ {Q\<leftarrow>\<lfloor>v\<rfloor>\<^sub>e} es\<doteq>\<succ> {\<lambda>Vals:vs:. R\<leftarrow>\<lfloor>(v # vs)\<rfloor>\<^sub>l} }"
using Cons.hyps by simp
show "G,A|\<Turnstile>\<Colon>{ {Normal P} e # es\<doteq>\<succ> {R} }"
proof (rule valid_expr_list_NormalI)
fix n s0 L accC T E v s2 Y Z
assume valid_A: "\<forall>t\<in>A. G\<Turnstile>n\<Colon>t"
assume conf_s0: "s0\<Colon>\<preceq>(G,L)"
assume normal_s0: "normal s0"
assume wt: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>e # es\<Colon>\<doteq>T"
assume da: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>dom (locals (store s0)) \<guillemotright>\<langle>e # es\<rangle>\<^sub>l\<guillemotright> E"
assume eval: "G\<turnstile>s0 \<midarrow>e # es\<doteq>\<succ>v\<midarrow>n\<rightarrow> s2"
assume P: "(Normal P) Y s0 Z"
show "R \<lfloor>v\<rfloor>\<^sub>l s2 Z \<and> s2\<Colon>\<preceq>(G, L)"
proof -
from wt obtain eT esT where
wt_e: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>e\<Colon>-eT" and
wt_es: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>es\<Colon>\<doteq>esT"
by cases simp
from da obtain E1 where
da_e: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile> (dom (locals (store s0)))\<guillemotright>\<langle>e\<rangle>\<^sub>e\<guillemotright> E1" and
da_es: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile> nrm E1 \<guillemotright>\<langle>es\<rangle>\<^sub>l\<guillemotright> E"
by cases simp
from eval obtain s1 ve vs where
eval_e: "G\<turnstile>s0 \<midarrow>e-\<succ>ve\<midarrow>n\<rightarrow> s1" and
eval_es: "G\<turnstile>s1 \<midarrow>es\<doteq>\<succ>vs\<midarrow>n\<rightarrow> s2" and
v: "v=ve#vs"
using normal_s0 by (fastforce elim: evaln_elim_cases)
from valid_e P valid_A conf_s0 eval_e wt_e da_e
obtain Q: "Q \<lfloor>ve\<rfloor>\<^sub>e s1 Z" and conf_s1: "s1\<Colon>\<preceq>(G,L)"
by (rule validE)
from Q have Q': "\<And> v. (Q\<leftarrow>\<lfloor>ve\<rfloor>\<^sub>e) v s1 Z"
by simp
have "(\<lambda>Vals:vs:. R\<leftarrow>\<lfloor>(ve # vs)\<rfloor>\<^sub>l) \<lfloor>vs\<rfloor>\<^sub>l s2 Z"
proof (cases "normal s1")
case True
obtain E' where
da_es': "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile> dom (locals (store s1)) \<guillemotright>\<langle>es\<rangle>\<^sub>l\<guillemotright> E'"
proof -
from eval_e wt_e da_e wf True
have "nrm E1 \<subseteq> dom (locals (store s1))"
by (cases rule: da_good_approx_evalnE) iprover
with da_es show thesis
by (rule da_weakenE) (rule that)
qed
from valid_es Q' valid_A conf_s1 eval_es wt_es da_es'
show ?thesis
by (rule validE)
next
case False
with valid_es Q' valid_A conf_s1 eval_es
show ?thesis
by (cases rule: validE) iprover+
qed
with v have "R \<lfloor>v\<rfloor>\<^sub>l s2 Z"
by simp
moreover
from eval wt da conf_s0 wf
have "s2\<Colon>\<preceq>(G, L)"
by (rule evaln_type_sound [elim_format]) simp
ultimately show ?thesis ..
qed
qed
next
case (Skip A P)
show "G,A|\<Turnstile>\<Colon>{ {Normal (P\<leftarrow>\<diamondsuit>)} .Skip. {P} }"
proof (rule valid_stmt_NormalI)
fix s0 s1 n L Y Z
assume conf_s0: "s0\<Colon>\<preceq>(G,L)"
assume normal_s0: "normal s0"
assume eval: "G\<turnstile>s0 \<midarrow>Skip\<midarrow>n\<rightarrow> s1"
assume P: "(Normal (P\<leftarrow>\<diamondsuit>)) Y s0 Z"
show "P \<diamondsuit> s1 Z \<and> s1\<Colon>\<preceq>(G, L)"
proof -
from eval obtain "s1=s0"
using normal_s0 by (fastforce elim: evaln_elim_cases)
with P conf_s0 show ?thesis
by simp
qed
qed
next
case (Expr A P e Q)
note valid_e = `G,A|\<Turnstile>\<Colon>{ {Normal P} e-\<succ> {Q\<leftarrow>\<diamondsuit>} }`
show "G,A|\<Turnstile>\<Colon>{ {Normal P} .Expr e. {Q} }"
proof (rule valid_stmt_NormalI)
fix n s0 L accC C s1 Y Z
assume valid_A: "\<forall>t\<in>A. G\<Turnstile>n\<Colon>t"
assume conf_s0: "s0\<Colon>\<preceq>(G,L)"
assume normal_s0: "normal s0"
assume wt: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>Expr e\<Colon>\<surd>"
assume da: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>dom (locals (store s0)) \<guillemotright>\<langle>Expr e\<rangle>\<^sub>s\<guillemotright> C"
assume eval: "G\<turnstile>s0 \<midarrow>Expr e\<midarrow>n\<rightarrow> s1"
assume P: "(Normal P) Y s0 Z"
show "Q \<diamondsuit> s1 Z \<and> s1\<Colon>\<preceq>(G, L)"
proof -
from wt obtain eT where
wt_e: "\<lparr>prg = G, cls = accC, lcl = L\<rparr>\<turnstile>e\<Colon>-eT"
by cases simp
from da obtain E where
da_e: "\<lparr>prg=G,cls=accC, lcl=L\<rparr>\<turnstile>dom (locals (store s0))\<guillemotright>\<langle>e\<rangle>\<^sub>e\<guillemotright>E"
by cases simp
from eval obtain v where
eval_e: "G\<turnstile>s0 \<midarrow>e-\<succ>v\<midarrow>n\<rightarrow> s1"
using normal_s0 by (fastforce elim: evaln_elim_cases)
from valid_e P valid_A conf_s0 eval_e wt_e da_e
obtain Q: "(Q\<leftarrow>\<diamondsuit>) \<lfloor>v\<rfloor>\<^sub>e s1 Z" and "s1\<Colon>\<preceq>(G,L)"
by (rule validE)
thus ?thesis by simp
qed
qed
next
case (Lab A P c l Q)
note valid_c = `G,A|\<Turnstile>\<Colon>{ {Normal P} .c. {abupd (absorb l) .; Q} }`
show "G,A|\<Turnstile>\<Colon>{ {Normal P} .l\<bullet> c. {Q} }"
proof (rule valid_stmt_NormalI)
fix n s0 L accC C s2 Y Z
assume valid_A: "\<forall>t\<in>A. G\<Turnstile>n\<Colon>t"
assume conf_s0: "s0\<Colon>\<preceq>(G,L)"
assume normal_s0: "normal s0"
assume wt: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>l\<bullet> c\<Colon>\<surd>"
assume da: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>dom (locals (store s0)) \<guillemotright>\<langle>l\<bullet> c\<rangle>\<^sub>s\<guillemotright> C"
assume eval: "G\<turnstile>s0 \<midarrow>l\<bullet> c\<midarrow>n\<rightarrow> s2"
assume P: "(Normal P) Y s0 Z"
show "Q \<diamondsuit> s2 Z \<and> s2\<Colon>\<preceq>(G, L)"
proof -
from wt obtain
wt_c: "\<lparr>prg = G, cls = accC, lcl = L\<rparr>\<turnstile>c\<Colon>\<surd>"
by cases simp
from da obtain E where
da_c: "\<lparr>prg=G,cls=accC, lcl=L\<rparr>\<turnstile>dom (locals (store s0))\<guillemotright>\<langle>c\<rangle>\<^sub>s\<guillemotright>E"
by cases simp
from eval obtain s1 where
eval_c: "G\<turnstile>s0 \<midarrow>c\<midarrow>n\<rightarrow> s1" and
s2: "s2 = abupd (absorb l) s1"
using normal_s0 by (fastforce elim: evaln_elim_cases)
from valid_c P valid_A conf_s0 eval_c wt_c da_c
obtain Q: "(abupd (absorb l) .; Q) \<diamondsuit> s1 Z"
by (rule validE)
with s2 have "Q \<diamondsuit> s2 Z"
by simp
moreover
from eval wt da conf_s0 wf
have "s2\<Colon>\<preceq>(G, L)"
by (rule evaln_type_sound [elim_format]) simp
ultimately show ?thesis ..
qed
qed
next
case (Comp A P c1 Q c2 R)
note valid_c1 = `G,A|\<Turnstile>\<Colon>{ {Normal P} .c1. {Q} }`
note valid_c2 = `G,A|\<Turnstile>\<Colon>{ {Q} .c2. {R} }`
show "G,A|\<Turnstile>\<Colon>{ {Normal P} .c1;; c2. {R} }"
proof (rule valid_stmt_NormalI)
fix n s0 L accC C s2 Y Z
assume valid_A: "\<forall>t\<in>A. G\<Turnstile>n\<Colon>t"
assume conf_s0: "s0\<Colon>\<preceq>(G,L)"
assume normal_s0: "normal s0"
assume wt: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>(c1;; c2)\<Colon>\<surd>"
assume da: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>dom (locals (store s0))\<guillemotright>\<langle>c1;;c2\<rangle>\<^sub>s\<guillemotright>C"
assume eval: "G\<turnstile>s0 \<midarrow>c1;; c2\<midarrow>n\<rightarrow> s2"
assume P: "(Normal P) Y s0 Z"
show "R \<diamondsuit> s2 Z \<and> s2\<Colon>\<preceq>(G,L)"
proof -
from eval obtain s1 where
eval_c1: "G\<turnstile>s0 \<midarrow>c1 \<midarrow>n\<rightarrow> s1" and
eval_c2: "G\<turnstile>s1 \<midarrow>c2 \<midarrow>n\<rightarrow> s2"
using normal_s0 by (fastforce elim: evaln_elim_cases)
from wt obtain
wt_c1: "\<lparr>prg = G, cls = accC, lcl = L\<rparr>\<turnstile>c1\<Colon>\<surd>" and
wt_c2: "\<lparr>prg = G, cls = accC, lcl = L\<rparr>\<turnstile>c2\<Colon>\<surd>"
by cases simp
from da obtain C1 C2 where
da_c1: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile> dom (locals (store s0)) \<guillemotright>\<langle>c1\<rangle>\<^sub>s\<guillemotright> C1" and
da_c2: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>nrm C1 \<guillemotright>\<langle>c2\<rangle>\<^sub>s\<guillemotright> C2"
by cases simp
from valid_c1 P valid_A conf_s0 eval_c1 wt_c1 da_c1
obtain Q: "Q \<diamondsuit> s1 Z" and conf_s1: "s1\<Colon>\<preceq>(G,L)"
by (rule validE)
have "R \<diamondsuit> s2 Z"
proof (cases "normal s1")
case True
obtain C2' where
"\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile> dom (locals (store s1)) \<guillemotright>\<langle>c2\<rangle>\<^sub>s\<guillemotright> C2'"
proof -
from eval_c1 wt_c1 da_c1 wf True
have "nrm C1 \<subseteq> dom (locals (store s1))"
by (cases rule: da_good_approx_evalnE) iprover
with da_c2 show thesis
by (rule da_weakenE) (rule that)
qed
with valid_c2 Q valid_A conf_s1 eval_c2 wt_c2
show ?thesis
by (rule validE)
next
case False
from valid_c2 Q valid_A conf_s1 eval_c2 False
show ?thesis
by (cases rule: validE) iprover+
qed
moreover
from eval wt da conf_s0 wf
have "s2\<Colon>\<preceq>(G, L)"
by (rule evaln_type_sound [elim_format]) simp
ultimately show ?thesis ..
qed
qed
next
case (If A P e P' c1 c2 Q)
note valid_e = `G,A|\<Turnstile>\<Colon>{ {Normal P} e-\<succ> {P'} }`
have valid_then_else: "\<And> b. G,A|\<Turnstile>\<Colon>{ {P'\<leftarrow>=b} .(if b then c1 else c2). {Q} }"
using If.hyps by simp
show "G,A|\<Turnstile>\<Colon>{ {Normal P} .If(e) c1 Else c2. {Q} }"
proof (rule valid_stmt_NormalI)
fix n s0 L accC C s2 Y Z
assume valid_A: "\<forall>t\<in>A. G\<Turnstile>n\<Colon>t"
assume conf_s0: "s0\<Colon>\<preceq>(G,L)"
assume normal_s0: "normal s0"
assume wt: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>If(e) c1 Else c2\<Colon>\<surd>"
assume da: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>
\<turnstile>dom (locals (store s0))\<guillemotright>\<langle>If(e) c1 Else c2\<rangle>\<^sub>s\<guillemotright>C"
assume eval: "G\<turnstile>s0 \<midarrow>If(e) c1 Else c2\<midarrow>n\<rightarrow> s2"
assume P: "(Normal P) Y s0 Z"
show "Q \<diamondsuit> s2 Z \<and> s2\<Colon>\<preceq>(G,L)"
proof -
from eval obtain b s1 where
eval_e: "G\<turnstile>s0 \<midarrow>e-\<succ>b\<midarrow>n\<rightarrow> s1" and
eval_then_else: "G\<turnstile>s1 \<midarrow>(if the_Bool b then c1 else c2)\<midarrow>n\<rightarrow> s2"
using normal_s0 by (auto elim: evaln_elim_cases)
from wt obtain
wt_e: "\<lparr>prg=G, cls=accC, lcl=L\<rparr>\<turnstile>e\<Colon>-PrimT Boolean" and
wt_then_else: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>(if the_Bool b then c1 else c2)\<Colon>\<surd>"
by cases (simp split: split_if)
from da obtain E S where
da_e: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile> dom (locals (store s0)) \<guillemotright>\<langle>e\<rangle>\<^sub>e\<guillemotright> E" and
da_then_else:
"\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>
(dom (locals (store s0)) \<union> assigns_if (the_Bool b) e)
\<guillemotright>\<langle>if the_Bool b then c1 else c2\<rangle>\<^sub>s\<guillemotright> S"
by cases (cases "the_Bool b",auto)
from valid_e P valid_A conf_s0 eval_e wt_e da_e
obtain "P' \<lfloor>b\<rfloor>\<^sub>e s1 Z" and conf_s1: "s1\<Colon>\<preceq>(G,L)"
by (rule validE)
hence P': "\<And>v. (P'\<leftarrow>=the_Bool b) v s1 Z"
by (cases "normal s1") auto
have "Q \<diamondsuit> s2 Z"
proof (cases "normal s1")
case True
have s0_s1: "dom (locals (store s0))
\<union> assigns_if (the_Bool b) e \<subseteq> dom (locals (store s1))"
proof -
from eval_e
have eval_e': "G\<turnstile>s0 \<midarrow>e-\<succ>b\<rightarrow> s1"
by (rule evaln_eval)
hence
"dom (locals (store s0)) \<subseteq> dom (locals (store s1))"
by (rule dom_locals_eval_mono_elim)
moreover
from eval_e' True wt_e
have "assigns_if (the_Bool b) e \<subseteq> dom (locals (store s1))"
by (rule assigns_if_good_approx')
ultimately show ?thesis by (rule Un_least)
qed
with da_then_else
obtain S' where
"\<lparr>prg=G,cls=accC,lcl=L\<rparr>
\<turnstile>dom (locals (store s1))\<guillemotright>\<langle>if the_Bool b then c1 else c2\<rangle>\<^sub>s\<guillemotright> S'"
by (rule da_weakenE)
with valid_then_else P' valid_A conf_s1 eval_then_else wt_then_else
show ?thesis
by (rule validE)
next
case False
with valid_then_else P' valid_A conf_s1 eval_then_else
show ?thesis
by (cases rule: validE) iprover+
qed
moreover
from eval wt da conf_s0 wf
have "s2\<Colon>\<preceq>(G, L)"
by (rule evaln_type_sound [elim_format]) simp
ultimately show ?thesis ..
qed
qed
next
case (Loop A P e P' c l)
note valid_e = `G,A|\<Turnstile>\<Colon>{ {P} e-\<succ> {P'} }`
note valid_c = `G,A|\<Turnstile>\<Colon>{ {Normal (P'\<leftarrow>=True)}
.c.
{abupd (absorb (Cont l)) .; P} }`
show "G,A|\<Turnstile>\<Colon>{ {P} .l\<bullet> While(e) c. {P'\<leftarrow>=False\<down>=\<diamondsuit>} }"
proof (rule valid_stmtI)
fix n s0 L accC C s3 Y Z
assume valid_A: "\<forall>t\<in>A. G\<Turnstile>n\<Colon>t"
assume conf_s0: "s0\<Colon>\<preceq>(G,L)"
assume wt: "normal s0 \<Longrightarrow> \<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>l\<bullet> While(e) c\<Colon>\<surd>"
assume da: "normal s0 \<Longrightarrow> \<lparr>prg=G,cls=accC,lcl=L\<rparr>
\<turnstile> dom (locals (store s0)) \<guillemotright>\<langle>l\<bullet> While(e) c\<rangle>\<^sub>s\<guillemotright> C"
assume eval: "G\<turnstile>s0 \<midarrow>l\<bullet> While(e) c\<midarrow>n\<rightarrow> s3"
assume P: "P Y s0 Z"
show "(P'\<leftarrow>=False\<down>=\<diamondsuit>) \<diamondsuit> s3 Z \<and> s3\<Colon>\<preceq>(G,L)"
proof -
--{* From the given hypothesises @{text valid_e} and @{text valid_c}
we can only reach the state after unfolding the loop once, i.e.
@{term "P \<diamondsuit> s2 Z"}, where @{term s2} is the state after executing
@{term c}. To gain validity of the further execution of while, to
finally get @{term "(P'\<leftarrow>=False\<down>=\<diamondsuit>) \<diamondsuit> s3 Z"} we have to get
a hypothesis about the subsequent unfoldings (the whole loop again),
too. We can achieve this, by performing induction on the
evaluation relation, with all
the necessary preconditions to apply @{text valid_e} and
@{text valid_c} in the goal.
*}
{
fix t s s' v
assume "G\<turnstile>s \<midarrow>t\<succ>\<midarrow>n\<rightarrow> (v, s')"
hence "\<And> Y' T E.
\<lbrakk>t = \<langle>l\<bullet> While(e) c\<rangle>\<^sub>s; \<forall>t\<in>A. G\<Turnstile>n\<Colon>t; P Y' s Z; s\<Colon>\<preceq>(G, L);
normal s \<Longrightarrow> \<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>t\<Colon>T;
normal s \<Longrightarrow> \<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>dom (locals (store s))\<guillemotright>t\<guillemotright>E
\<rbrakk>\<Longrightarrow> (P'\<leftarrow>=False\<down>=\<diamondsuit>) v s' Z"
(is "PROP ?Hyp n t s v s'")
proof (induct)
case (Loop s0' e' b n' s1' c' s2' l' s3' Y' T E)
note while = `(\<langle>l'\<bullet> While(e') c'\<rangle>\<^sub>s::term) = \<langle>l\<bullet> While(e) c\<rangle>\<^sub>s`
hence eqs: "l'=l" "e'=e" "c'=c" by simp_all
note valid_A = `\<forall>t\<in>A. G\<Turnstile>n'\<Colon>t`
note P = `P Y' (Norm s0') Z`
note conf_s0' = `Norm s0'\<Colon>\<preceq>(G, L)`
have wt: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>\<langle>l\<bullet> While(e) c\<rangle>\<^sub>s\<Colon>T"
using Loop.prems eqs by simp
have da: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>
dom (locals (store ((Norm s0')::state)))\<guillemotright>\<langle>l\<bullet> While(e) c\<rangle>\<^sub>s\<guillemotright>E"
using Loop.prems eqs by simp
have evaln_e: "G\<turnstile>Norm s0' \<midarrow>e-\<succ>b\<midarrow>n'\<rightarrow> s1'"
using Loop.hyps eqs by simp
show "(P'\<leftarrow>=False\<down>=\<diamondsuit>) \<diamondsuit> s3' Z"
proof -
from wt obtain
wt_e: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>e\<Colon>-PrimT Boolean" and
wt_c: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>c\<Colon>\<surd>"
by cases (simp add: eqs)
from da obtain E S where
da_e: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>
\<turnstile> dom (locals (store ((Norm s0')::state))) \<guillemotright>\<langle>e\<rangle>\<^sub>e\<guillemotright> E" and
da_c: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>
\<turnstile> (dom (locals (store ((Norm s0')::state)))
\<union> assigns_if True e) \<guillemotright>\<langle>c\<rangle>\<^sub>s\<guillemotright> S"
by cases (simp add: eqs)
from evaln_e
have eval_e: "G\<turnstile>Norm s0' \<midarrow>e-\<succ>b\<rightarrow> s1'"
by (rule evaln_eval)
from valid_e P valid_A conf_s0' evaln_e wt_e da_e
obtain P': "P' \<lfloor>b\<rfloor>\<^sub>e s1' Z" and conf_s1': "s1'\<Colon>\<preceq>(G,L)"
by (rule validE)
show "(P'\<leftarrow>=False\<down>=\<diamondsuit>) \<diamondsuit> s3' Z"
proof (cases "normal s1'")
case True
note normal_s1'=this
show ?thesis
proof (cases "the_Bool b")
case True
with P' normal_s1' have P'': "(Normal (P'\<leftarrow>=True)) \<lfloor>b\<rfloor>\<^sub>e s1' Z"
by auto
from True Loop.hyps obtain
eval_c: "G\<turnstile>s1' \<midarrow>c\<midarrow>n'\<rightarrow> s2'" and
eval_while:
"G\<turnstile>abupd (absorb (Cont l)) s2' \<midarrow>l\<bullet> While(e) c\<midarrow>n'\<rightarrow> s3'"
by (simp add: eqs)
from True Loop.hyps have
hyp: "PROP ?Hyp n' \<langle>l\<bullet> While(e) c\<rangle>\<^sub>s
(abupd (absorb (Cont l')) s2') \<diamondsuit> s3'"
apply (simp only: True if_True eqs)
apply (elim conjE)
apply (tactic "smp_tac @{context} 3 1")
apply fast
done
from eval_e
have s0'_s1': "dom (locals (store ((Norm s0')::state)))
\<subseteq> dom (locals (store s1'))"
by (rule dom_locals_eval_mono_elim)
obtain S' where
da_c':
"\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>(dom (locals (store s1')))\<guillemotright>\<langle>c\<rangle>\<^sub>s\<guillemotright> S'"
proof -
note s0'_s1'
moreover
from eval_e normal_s1' wt_e
have "assigns_if True e \<subseteq> dom (locals (store s1'))"
by (rule assigns_if_good_approx' [elim_format])
(simp add: True)
ultimately
have "dom (locals (store ((Norm s0')::state)))
\<union> assigns_if True e \<subseteq> dom (locals (store s1'))"
by (rule Un_least)
with da_c show thesis
by (rule da_weakenE) (rule that)
qed
with valid_c P'' valid_A conf_s1' eval_c wt_c
obtain "(abupd (absorb (Cont l)) .; P) \<diamondsuit> s2' Z" and
conf_s2': "s2'\<Colon>\<preceq>(G,L)"
by (rule validE)
hence P_s2': "P \<diamondsuit> (abupd (absorb (Cont l)) s2') Z"
by simp
from conf_s2'
have conf_absorb: "abupd (absorb (Cont l)) s2' \<Colon>\<preceq>(G, L)"
by (cases s2') (auto intro: conforms_absorb)
moreover
obtain E' where
da_while':
"\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>
dom (locals(store (abupd (absorb (Cont l)) s2')))
\<guillemotright>\<langle>l\<bullet> While(e) c\<rangle>\<^sub>s\<guillemotright> E'"
proof -
note s0'_s1'
also
from eval_c
have "G\<turnstile>s1' \<midarrow>c\<rightarrow> s2'"
by (rule evaln_eval)
hence "dom (locals (store s1')) \<subseteq> dom (locals (store s2'))"
by (rule dom_locals_eval_mono_elim)
also
have "\<dots>\<subseteq>dom (locals (store (abupd (absorb (Cont l)) s2')))"
by simp
finally
have "dom (locals (store ((Norm s0')::state))) \<subseteq> \<dots>" .
with da show thesis
by (rule da_weakenE) (rule that)
qed
from valid_A P_s2' conf_absorb wt da_while'
show "(P'\<leftarrow>=False\<down>=\<diamondsuit>) \<diamondsuit> s3' Z"
using hyp by (simp add: eqs)
next
case False
with Loop.hyps obtain "s3'=s1'"
by simp
with P' False show ?thesis
by auto
qed
next
case False
note abnormal_s1'=this
have "s3'=s1'"
proof -
from False obtain abr where abr: "abrupt s1' = Some abr"
by (cases s1') auto
from eval_e _ wt_e wf
have no_jmp: "\<And> j. abrupt s1' \<noteq> Some (Jump j)"
by (rule eval_expression_no_jump
[where ?Env="\<lparr>prg=G,cls=accC,lcl=L\<rparr>",simplified])
simp
show ?thesis
proof (cases "the_Bool b")
case True
with Loop.hyps obtain
eval_c: "G\<turnstile>s1' \<midarrow>c\<midarrow>n'\<rightarrow> s2'" and
eval_while:
"G\<turnstile>abupd (absorb (Cont l)) s2' \<midarrow>l\<bullet> While(e) c\<midarrow>n'\<rightarrow> s3'"
by (simp add: eqs)
from eval_c abr have "s2'=s1'" by auto
moreover from calculation no_jmp
have "abupd (absorb (Cont l)) s2'=s2'"
by (cases s1') (simp add: absorb_def)
ultimately show ?thesis
using eval_while abr
by auto
next
case False
with Loop.hyps show ?thesis by simp
qed
qed
with P' False show ?thesis
by auto
qed
qed
next
case (Abrupt abr s t' n' Y' T E)
note t' = `t' = \<langle>l\<bullet> While(e) c\<rangle>\<^sub>s`
note conf = `(Some abr, s)\<Colon>\<preceq>(G, L)`
note P = `P Y' (Some abr, s) Z`
note valid_A = `\<forall>t\<in>A. G\<Turnstile>n'\<Colon>t`
show "(P'\<leftarrow>=False\<down>=\<diamondsuit>) (undefined3 t') (Some abr, s) Z"
proof -
have eval_e:
"G\<turnstile>(Some abr,s) \<midarrow>\<langle>e\<rangle>\<^sub>e\<succ>\<midarrow>n'\<rightarrow> (undefined3 \<langle>e\<rangle>\<^sub>e,(Some abr,s))"
by auto
from valid_e P valid_A conf eval_e
have "P' (undefined3 \<langle>e\<rangle>\<^sub>e) (Some abr,s) Z"
by (cases rule: validE [where ?P="P"]) simp+
with t' show ?thesis
by auto
qed
qed simp_all
} note generalized=this
from eval _ valid_A P conf_s0 wt da
have "(P'\<leftarrow>=False\<down>=\<diamondsuit>) \<diamondsuit> s3 Z"
by (rule generalized) simp_all
moreover
have "s3\<Colon>\<preceq>(G, L)"
proof (cases "normal s0")
case True
from eval wt [OF True] da [OF True] conf_s0 wf
show ?thesis
by (rule evaln_type_sound [elim_format]) simp
next
case False
with eval have "s3=s0"
by auto
with conf_s0 show ?thesis
by simp
qed
ultimately show ?thesis ..
qed
qed
next
case (Jmp A j P)
show "G,A|\<Turnstile>\<Colon>{ {Normal (abupd (\<lambda>a. Some (Jump j)) .; P\<leftarrow>\<diamondsuit>)} .Jmp j. {P} }"
proof (rule valid_stmt_NormalI)
fix n s0 L accC C s1 Y Z
assume valid_A: "\<forall>t\<in>A. G\<Turnstile>n\<Colon>t"
assume conf_s0: "s0\<Colon>\<preceq>(G,L)"
assume normal_s0: "normal s0"
assume wt: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>Jmp j\<Colon>\<surd>"
assume da: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>
\<turnstile>dom (locals (store s0))\<guillemotright>\<langle>Jmp j\<rangle>\<^sub>s\<guillemotright>C"
assume eval: "G\<turnstile>s0 \<midarrow>Jmp j\<midarrow>n\<rightarrow> s1"
assume P: "(Normal (abupd (\<lambda>a. Some (Jump j)) .; P\<leftarrow>\<diamondsuit>)) Y s0 Z"
show "P \<diamondsuit> s1 Z \<and> s1\<Colon>\<preceq>(G,L)"
proof -
from eval obtain s where
s: "s0=Norm s" "s1=(Some (Jump j), s)"
using normal_s0 by (auto elim: evaln_elim_cases)
with P have "P \<diamondsuit> s1 Z"
by simp
moreover
from eval wt da conf_s0 wf
have "s1\<Colon>\<preceq>(G,L)"
by (rule evaln_type_sound [elim_format]) simp
ultimately show ?thesis ..
qed
qed
next
case (Throw A P e Q)
note valid_e = `G,A|\<Turnstile>\<Colon>{ {Normal P} e-\<succ> {\<lambda>Val:a:. abupd (throw a) .; Q\<leftarrow>\<diamondsuit>} }`
show "G,A|\<Turnstile>\<Colon>{ {Normal P} .Throw e. {Q} }"
proof (rule valid_stmt_NormalI)
fix n s0 L accC C s2 Y Z
assume valid_A: "\<forall>t\<in>A. G\<Turnstile>n\<Colon>t"
assume conf_s0: "s0\<Colon>\<preceq>(G,L)"
assume normal_s0: "normal s0"
assume wt: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>Throw e\<Colon>\<surd>"
assume da: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>
\<turnstile>dom (locals (store s0))\<guillemotright>\<langle>Throw e\<rangle>\<^sub>s\<guillemotright>C"
assume eval: "G\<turnstile>s0 \<midarrow>Throw e\<midarrow>n\<rightarrow> s2"
assume P: "(Normal P) Y s0 Z"
show "Q \<diamondsuit> s2 Z \<and> s2\<Colon>\<preceq>(G,L)"
proof -
from eval obtain s1 a where
eval_e: "G\<turnstile>s0 \<midarrow>e-\<succ>a\<midarrow>n\<rightarrow> s1" and
s2: "s2 = abupd (throw a) s1"
using normal_s0 by (auto elim: evaln_elim_cases)
from wt obtain T where
wt_e: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>e\<Colon>-T"
by cases simp
from da obtain E where
da_e: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile> dom (locals (store s0)) \<guillemotright>\<langle>e\<rangle>\<^sub>e\<guillemotright> E"
by cases simp
from valid_e P valid_A conf_s0 eval_e wt_e da_e
obtain "(\<lambda>Val:a:. abupd (throw a) .; Q\<leftarrow>\<diamondsuit>) \<lfloor>a\<rfloor>\<^sub>e s1 Z"
by (rule validE)
with s2 have "Q \<diamondsuit> s2 Z"
by simp
moreover
from eval wt da conf_s0 wf
have "s2\<Colon>\<preceq>(G,L)"
by (rule evaln_type_sound [elim_format]) simp
ultimately show ?thesis ..
qed
qed
next
case (Try A P c1 Q C vn c2 R)
note valid_c1 = `G,A|\<Turnstile>\<Colon>{ {Normal P} .c1. {SXAlloc G Q} }`
note valid_c2 = `G,A|\<Turnstile>\<Colon>{ {Q \<and>. (\<lambda>s. G,s\<turnstile>catch C) ;. new_xcpt_var vn}
.c2.
{R} }`
note Q_R = `(Q \<and>. (\<lambda>s. \<not> G,s\<turnstile>catch C)) \<Rightarrow> R`
show "G,A|\<Turnstile>\<Colon>{ {Normal P} .Try c1 Catch(C vn) c2. {R} }"
proof (rule valid_stmt_NormalI)
fix n s0 L accC E s3 Y Z
assume valid_A: "\<forall>t\<in>A. G\<Turnstile>n\<Colon>t"
assume conf_s0: "s0\<Colon>\<preceq>(G,L)"
assume normal_s0: "normal s0"
assume wt: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>Try c1 Catch(C vn) c2\<Colon>\<surd>"
assume da: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>
\<turnstile>dom (locals (store s0)) \<guillemotright>\<langle>Try c1 Catch(C vn) c2\<rangle>\<^sub>s\<guillemotright> E"
assume eval: "G\<turnstile>s0 \<midarrow>Try c1 Catch(C vn) c2\<midarrow>n\<rightarrow> s3"
assume P: "(Normal P) Y s0 Z"
show "R \<diamondsuit> s3 Z \<and> s3\<Colon>\<preceq>(G,L)"
proof -
from eval obtain s1 s2 where
eval_c1: "G\<turnstile>s0 \<midarrow>c1\<midarrow>n\<rightarrow> s1" and
sxalloc: "G\<turnstile>s1 \<midarrow>sxalloc\<rightarrow> s2" and
s3: "if G,s2\<turnstile>catch C
then G\<turnstile>new_xcpt_var vn s2 \<midarrow>c2\<midarrow>n\<rightarrow> s3
else s3 = s2"
using normal_s0 by (fastforce elim: evaln_elim_cases)
from wt obtain
wt_c1: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>c1\<Colon>\<surd>" and
wt_c2: "\<lparr>prg=G,cls=accC,lcl=L(VName vn\<mapsto>Class C)\<rparr>\<turnstile>c2\<Colon>\<surd>"
by cases simp
from da obtain C1 C2 where
da_c1: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile> dom (locals (store s0)) \<guillemotright>\<langle>c1\<rangle>\<^sub>s\<guillemotright> C1" and
da_c2: "\<lparr>prg=G,cls=accC,lcl=L(VName vn\<mapsto>Class C)\<rparr>
\<turnstile> (dom (locals (store s0)) \<union> {VName vn}) \<guillemotright>\<langle>c2\<rangle>\<^sub>s\<guillemotright> C2"
by cases simp
from valid_c1 P valid_A conf_s0 eval_c1 wt_c1 da_c1
obtain sxQ: "(SXAlloc G Q) \<diamondsuit> s1 Z" and conf_s1: "s1\<Colon>\<preceq>(G,L)"
by (rule validE)
from sxalloc sxQ
have Q: "Q \<diamondsuit> s2 Z"
by auto
have "R \<diamondsuit> s3 Z"
proof (cases "\<exists> x. abrupt s1 = Some (Xcpt x)")
case False
from sxalloc wf
have "s2=s1"
by (rule sxalloc_type_sound [elim_format])
(insert False, auto split: option.splits abrupt.splits )
with False
have no_catch: "\<not> G,s2\<turnstile>catch C"
by (simp add: catch_def)
moreover
from no_catch s3
have "s3=s2"
by simp
ultimately show ?thesis
using Q Q_R by simp
next
case True
note exception_s1 = this
show ?thesis
proof (cases "G,s2\<turnstile>catch C")
case False
with s3
have "s3=s2"
by simp
with False Q Q_R show ?thesis
by simp
next
case True
with s3 have eval_c2: "G\<turnstile>new_xcpt_var vn s2 \<midarrow>c2\<midarrow>n\<rightarrow> s3"
by simp
from conf_s1 sxalloc wf
have conf_s2: "s2\<Colon>\<preceq>(G, L)"
by (auto dest: sxalloc_type_sound
split: option.splits abrupt.splits)
from exception_s1 sxalloc wf
obtain a
where xcpt_s2: "abrupt s2 = Some (Xcpt (Loc a))"
by (auto dest!: sxalloc_type_sound
split: option.splits abrupt.splits)
with True
have "G\<turnstile>obj_ty (the (globs (store s2) (Heap a)))\<preceq>Class C"
by (cases s2) simp
with xcpt_s2 conf_s2 wf
have conf_new_xcpt: "new_xcpt_var vn s2 \<Colon>\<preceq>(G, L(VName vn\<mapsto>Class C))"
by (auto dest: Try_lemma)
obtain C2' where
da_c2':
"\<lparr>prg=G,cls=accC,lcl=L(VName vn\<mapsto>Class C)\<rparr>
\<turnstile> (dom (locals (store (new_xcpt_var vn s2)))) \<guillemotright>\<langle>c2\<rangle>\<^sub>s\<guillemotright> C2'"
proof -
have "(dom (locals (store s0)) \<union> {VName vn})
\<subseteq> dom (locals (store (new_xcpt_var vn s2)))"
proof -
from eval_c1
have "dom (locals (store s0))
\<subseteq> dom (locals (store s1))"
by (rule dom_locals_evaln_mono_elim)
also
from sxalloc
have "\<dots> \<subseteq> dom (locals (store s2))"
by (rule dom_locals_sxalloc_mono)
also
have "\<dots> \<subseteq> dom (locals (store (new_xcpt_var vn s2)))"
by (cases s2) (simp add: new_xcpt_var_def, blast)
also
have "{VName vn} \<subseteq> \<dots>"
by (cases s2) simp
ultimately show ?thesis
by (rule Un_least)
qed
with da_c2 show thesis
by (rule da_weakenE) (rule that)
qed
from Q eval_c2 True
have "(Q \<and>. (\<lambda>s. G,s\<turnstile>catch C) ;. new_xcpt_var vn)
\<diamondsuit> (new_xcpt_var vn s2) Z"
by auto
from valid_c2 this valid_A conf_new_xcpt eval_c2 wt_c2 da_c2'
show "R \<diamondsuit> s3 Z"
by (rule validE)
qed
qed
moreover
from eval wt da conf_s0 wf
have "s3\<Colon>\<preceq>(G,L)"
by (rule evaln_type_sound [elim_format]) simp
ultimately show ?thesis ..
qed
qed
next
case (Fin A P c1 Q c2 R)
note valid_c1 = `G,A|\<Turnstile>\<Colon>{ {Normal P} .c1. {Q} }`
have valid_c2: "\<And> abr. G,A|\<Turnstile>\<Colon>{ {Q \<and>. (\<lambda>s. abr = fst s) ;. abupd (\<lambda>x. None)}
.c2.
{abupd (abrupt_if (abr \<noteq> None) abr) .; R} }"
using Fin.hyps by simp
show "G,A|\<Turnstile>\<Colon>{ {Normal P} .c1 Finally c2. {R} }"
proof (rule valid_stmt_NormalI)
fix n s0 L accC E s3 Y Z
assume valid_A: "\<forall>t\<in>A. G\<Turnstile>n\<Colon>t"
assume conf_s0: "s0\<Colon>\<preceq>(G,L)"
assume normal_s0: "normal s0"
assume wt: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>c1 Finally c2\<Colon>\<surd>"
assume da: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>
\<turnstile>dom (locals (store s0)) \<guillemotright>\<langle>c1 Finally c2\<rangle>\<^sub>s\<guillemotright> E"
assume eval: "G\<turnstile>s0 \<midarrow>c1 Finally c2\<midarrow>n\<rightarrow> s3"
assume P: "(Normal P) Y s0 Z"
show "R \<diamondsuit> s3 Z \<and> s3\<Colon>\<preceq>(G,L)"
proof -
from eval obtain s1 abr1 s2 where
eval_c1: "G\<turnstile>s0 \<midarrow>c1\<midarrow>n\<rightarrow> (abr1, s1)" and
eval_c2: "G\<turnstile>Norm s1 \<midarrow>c2\<midarrow>n\<rightarrow> s2" and
s3: "s3 = (if \<exists>err. abr1 = Some (Error err)
then (abr1, s1)
else abupd (abrupt_if (abr1 \<noteq> None) abr1) s2)"
using normal_s0 by (fastforce elim: evaln_elim_cases)
from wt obtain
wt_c1: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>c1\<Colon>\<surd>" and
wt_c2: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>c2\<Colon>\<surd>"
by cases simp
from da obtain C1 C2 where
da_c1: "\<lparr>prg=G,cls=accC,lcl=L\<rparr> \<turnstile> dom (locals (store s0)) \<guillemotright>\<langle>c1\<rangle>\<^sub>s\<guillemotright> C1" and
da_c2: "\<lparr>prg=G,cls=accC,lcl=L\<rparr> \<turnstile> dom (locals (store s0)) \<guillemotright>\<langle>c2\<rangle>\<^sub>s\<guillemotright> C2"
by cases simp
from valid_c1 P valid_A conf_s0 eval_c1 wt_c1 da_c1
obtain Q: "Q \<diamondsuit> (abr1,s1) Z" and conf_s1: "(abr1,s1)\<Colon>\<preceq>(G,L)"
by (rule validE)
from Q
have Q': "(Q \<and>. (\<lambda>s. abr1 = fst s) ;. abupd (\<lambda>x. None)) \<diamondsuit> (Norm s1) Z"
by auto
from eval_c1 wt_c1 da_c1 conf_s0 wf
have "error_free (abr1,s1)"
by (rule evaln_type_sound [elim_format]) (insert normal_s0,simp)
with s3 have s3': "s3 = abupd (abrupt_if (abr1 \<noteq> None) abr1) s2"
by (simp add: error_free_def)
from conf_s1
have conf_Norm_s1: "Norm s1\<Colon>\<preceq>(G,L)"
by (rule conforms_NormI)
obtain C2' where
da_c2': "\<lparr>prg=G,cls=accC,lcl=L\<rparr>
\<turnstile> dom (locals (store ((Norm s1)::state))) \<guillemotright>\<langle>c2\<rangle>\<^sub>s\<guillemotright> C2'"
proof -
from eval_c1
have "dom (locals (store s0)) \<subseteq> dom (locals (store (abr1,s1)))"
by (rule dom_locals_evaln_mono_elim)
hence "dom (locals (store s0))
\<subseteq> dom (locals (store ((Norm s1)::state)))"
by simp
with da_c2 show thesis
by (rule da_weakenE) (rule that)
qed
from valid_c2 Q' valid_A conf_Norm_s1 eval_c2 wt_c2 da_c2'
have "(abupd (abrupt_if (abr1 \<noteq> None) abr1) .; R) \<diamondsuit> s2 Z"
by (rule validE)
with s3' have "R \<diamondsuit> s3 Z"
by simp
moreover
from eval wt da conf_s0 wf
have "s3\<Colon>\<preceq>(G,L)"
by (rule evaln_type_sound [elim_format]) simp
ultimately show ?thesis ..
qed
qed
next
case (Done A P C)
show "G,A|\<Turnstile>\<Colon>{ {Normal (P\<leftarrow>\<diamondsuit> \<and>. initd C)} .Init C. {P} }"
proof (rule valid_stmt_NormalI)
fix n s0 L accC E s3 Y Z
assume valid_A: "\<forall>t\<in>A. G\<Turnstile>n\<Colon>t"
assume conf_s0: "s0\<Colon>\<preceq>(G,L)"
assume normal_s0: "normal s0"
assume wt: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>Init C\<Colon>\<surd>"
assume da: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>
\<turnstile>dom (locals (store s0)) \<guillemotright>\<langle>Init C\<rangle>\<^sub>s\<guillemotright> E"
assume eval: "G\<turnstile>s0 \<midarrow>Init C\<midarrow>n\<rightarrow> s3"
assume P: "(Normal (P\<leftarrow>\<diamondsuit> \<and>. initd C)) Y s0 Z"
show "P \<diamondsuit> s3 Z \<and> s3\<Colon>\<preceq>(G,L)"
proof -
from P have inited: "inited C (globs (store s0))"
by simp
with eval have "s3=s0"
using normal_s0 by (auto elim: evaln_elim_cases)
with P conf_s0 show ?thesis
by simp
qed
qed
next
case (Init C c A P Q R)
note c = `the (class G C) = c`
note valid_super =
`G,A|\<Turnstile>\<Colon>{ {Normal (P \<and>. Not \<circ> initd C ;. supd (init_class_obj G C))}
.(if C = Object then Skip else Init (super c)).
{Q} }`
have valid_init:
"\<And> l. G,A|\<Turnstile>\<Colon>{ {Q \<and>. (\<lambda>s. l = locals (snd s)) ;. set_lvars empty}
.init c.
{set_lvars l .; R} }"
using Init.hyps by simp
show "G,A|\<Turnstile>\<Colon>{ {Normal (P \<and>. Not \<circ> initd C)} .Init C. {R} }"
proof (rule valid_stmt_NormalI)
fix n s0 L accC E s3 Y Z
assume valid_A: "\<forall>t\<in>A. G\<Turnstile>n\<Colon>t"
assume conf_s0: "s0\<Colon>\<preceq>(G,L)"
assume normal_s0: "normal s0"
assume wt: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>\<turnstile>Init C\<Colon>\<surd>"
assume da: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>
\<turnstile>dom (locals (store s0)) \<guillemotright>\<langle>Init C\<rangle>\<^sub>s\<guillemotright> E"
assume eval: "G\<turnstile>s0 \<midarrow>Init C\<midarrow>n\<rightarrow> s3"
assume P: "(Normal (P \<and>. Not \<circ> initd C)) Y s0 Z"
show "R \<diamondsuit> s3 Z \<and> s3\<Colon>\<preceq>(G,L)"
proof -
from P have not_inited: "\<not> inited C (globs (store s0))" by simp
with eval c obtain s1 s2 where
eval_super:
"G\<turnstile>Norm ((init_class_obj G C) (store s0))
\<midarrow>(if C = Object then Skip else Init (super c))\<midarrow>n\<rightarrow> s1" and
eval_init: "G\<turnstile>(set_lvars empty) s1 \<midarrow>init c\<midarrow>n\<rightarrow> s2" and
s3: "s3 = (set_lvars (locals (store s1))) s2"
using normal_s0 by (auto elim!: evaln_elim_cases)
from wt c have
cls_C: "class G C = Some c"
by cases auto
from wf cls_C have
wt_super: "\<lparr>prg=G,cls=accC,lcl=L\<rparr>
\<turnstile>(if C = Object then Skip else Init (super c))\<Colon>\<surd>"
by (cases "C=Object")
(auto dest: wf_prog_cdecl wf_cdecl_supD is_acc_classD)
obtain S where
da_super:
"\<lparr>prg=G,cls=accC,lcl=L\<rparr>
\<turnstile> dom (locals (store ((Norm
((init_class_obj G C) (store s0)))::state)))
\<guillemotright>\<langle>if C = Object then Skip else Init (super c)\<rangle>\<^sub>s\<guillemotright> S"
proof (cases "C=Object")
case True
with da_Skip show ?thesis
using that by (auto intro: assigned.select_convs)
next
case False
with da_Init show ?thesis
by - (rule that, auto intro: assigned.select_convs)
qed
from normal_s0 conf_s0 wf cls_C not_inited
have conf_init_cls: "(Norm ((init_class_obj G C) (store s0)))\<Colon>\<preceq>(G, L)"
by (auto intro: conforms_init_class_obj)
from P
have P': "(Normal (P \<and>. Not \<circ> initd C ;. supd (init_class_obj G C)))
Y (Norm ((init_class_obj G C) (store s0))) Z"
by auto
from valid_super P' valid_A conf_init_cls eval_super wt_super da_super
obtain Q: "Q \<diamondsuit> s1 Z" and conf_s1: "s1\<Colon>\<preceq>(G,L)"
by (rule validE)
from cls_C wf have wt_init: "\<lparr>prg=G, cls=C,lcl=empty\<rparr>\<turnstile>(init c)\<Colon>\<surd>"
by (rule wf_prog_cdecl [THEN wf_cdecl_wt_init])
from cls_C wf obtain I where
"\<lparr>prg=G,cls=C,lcl=empty\<rparr>\<turnstile> {} \<guillemotright>\<langle>init c\<rangle>\<^sub>s\<guillemotright> I"
by (rule wf_prog_cdecl [THEN wf_cdeclE,simplified]) blast
(* simplified: to rewrite \<langle>init c\<rangle> to In1r (init c) *)
then obtain I' where
da_init:
"\<lparr>prg=G,cls=C,lcl=empty\<rparr>\<turnstile>dom (locals (store ((set_lvars empty) s1)))
\<guillemotright>\<langle>init c\<rangle>\<^sub>s\<guillemotright> I'"
by (rule da_weakenE) simp
have conf_s1_empty: "(set_lvars empty) s1\<Colon>\<preceq>(G, empty)"
proof -
from eval_super have
"G\<turnstile>Norm ((init_class_obj G C) (store s0))
\<midarrow>(if C = Object then Skip else Init (super c))\<rightarrow> s1"
by (rule evaln_eval)
from this wt_super wf
have s1_no_ret: "\<And> j. abrupt s1 \<noteq> Some (Jump j)"
by - (rule eval_statement_no_jump
[where ?Env="\<lparr>prg=G,cls=accC,lcl=L\<rparr>"], auto split: split_if)
with conf_s1
show ?thesis
by (cases s1) (auto intro: conforms_set_locals)
qed
obtain l where l: "l = locals (store s1)"
by simp
with Q
have Q': "(Q \<and>. (\<lambda>s. l = locals (snd s)) ;. set_lvars empty)
\<diamondsuit> ((set_lvars empty) s1) Z"
by auto
from valid_init Q' valid_A conf_s1_empty eval_init wt_init da_init
have "(set_lvars l .; R) \<diamondsuit> s2 Z"
by (rule validE)
with s3 l have "R \<diamondsuit> s3 Z"
by simp
moreover
from eval wt da conf_s0 wf
have "s3\<Colon>\<preceq>(G,L)"
by (rule evaln_type_sound [elim_format]) simp
ultimately show ?thesis ..
qed
qed
next
case (InsInitV A P c v Q)
show "G,A|\<Turnstile>\<Colon>{ {Normal P} InsInitV c v=\<succ> {Q} }"
proof (rule valid_var_NormalI)
fix s0 vf n s1 L Z
assume "normal s0"
moreover
assume "G\<turnstile>s0 \<midarrow>InsInitV c v=\<succ>vf\<midarrow>n\<rightarrow> s1"
ultimately have "False"
by (cases s0) (simp add: evaln_InsInitV)
thus "Q \<lfloor>vf\<rfloor>\<^sub>v s1 Z \<and> s1\<Colon>\<preceq>(G, L)"..
qed
next
case (InsInitE A P c e Q)
show "G,A|\<Turnstile>\<Colon>{ {Normal P} InsInitE c e-\<succ> {Q} }"
proof (rule valid_expr_NormalI)
fix s0 v n s1 L Z
assume "normal s0"
moreover
assume "G\<turnstile>s0 \<midarrow>InsInitE c e-\<succ>v\<midarrow>n\<rightarrow> s1"
ultimately have "False"
by (cases s0) (simp add: evaln_InsInitE)
thus "Q \<lfloor>v\<rfloor>\<^sub>e s1 Z \<and> s1\<Colon>\<preceq>(G, L)"..
qed
next
case (Callee A P l e Q)
show "G,A|\<Turnstile>\<Colon>{ {Normal P} Callee l e-\<succ> {Q} }"
proof (rule valid_expr_NormalI)
fix s0 v n s1 L Z
assume "normal s0"
moreover
assume "G\<turnstile>s0 \<midarrow>Callee l e-\<succ>v\<midarrow>n\<rightarrow> s1"
ultimately have "False"
by (cases s0) (simp add: evaln_Callee)
thus "Q \<lfloor>v\<rfloor>\<^sub>e s1 Z \<and> s1\<Colon>\<preceq>(G, L)"..
qed
next
case (FinA A P a c Q)
show "G,A|\<Turnstile>\<Colon>{ {Normal P} .FinA a c. {Q} }"
proof (rule valid_stmt_NormalI)
fix s0 v n s1 L Z
assume "normal s0"
moreover
assume "G\<turnstile>s0 \<midarrow>FinA a c\<midarrow>n\<rightarrow> s1"
ultimately have "False"
by (cases s0) (simp add: evaln_FinA)
thus "Q \<diamondsuit> s1 Z \<and> s1\<Colon>\<preceq>(G, L)"..
qed
qed
declare inj_term_simps [simp del]
theorem ax_sound:
"wf_prog G \<Longrightarrow> G,(A::'a triple set)|\<turnstile>(ts::'a triple set) \<Longrightarrow> G,A|\<Turnstile>ts"
apply (subst ax_valids2_eq [symmetric])
apply assumption
apply (erule (1) ax_sound2)
done
lemma sound_valid2_lemma:
"\<lbrakk>\<forall>v n. Ball A (triple_valid2 G n) \<longrightarrow> P v n; Ball A (triple_valid2 G n)\<rbrakk>
\<Longrightarrow>P v n"
by blast
end
|
module AssRecRule
import Data.Fin
import Data.Vect
{-
The recursion function for lists of type `a`. Define this by pattern matching
-}
recList : (a: Type) -> (x: Type) -> x -> (a -> List a -> x -> x) -> (List a -> x)
recList a x base step [] = base
recList a x base step (y :: ys) = step y ys (recList a x base step ys)
{-
Given a list of type `a` and a function `f: a -> b` get a list of type `b`
by applying `f` to each element.
Note: Define using `recList` and without pattern matching on lists.
-}
mapList : (a: Type) -> (b: Type) -> (f: a -> b) -> List a -> List b
mapList a b f x = recList a (List b) [] step x where
step = \y : a => \ys : List a => \result : List b => (f y) :: result
{-
Given a list of type `a`, an initial value `init: a` and an operation `op: a -> a -> a`,
get an element of `a` by starting with init and repeatedly applying the elements of the
list,
e.g. fold Nat 1 (*) ([22] :: [3] :: []) = 1 * 22 * 3
Note: Define using `recList` and without pattern matching on lists.
-}
foldList : (a: Type) -> (init: a) -> (op : a -> a -> a) -> List a -> a
foldList a init op y = recList a a init step y where
step = \y : a => \ys : List a => \result : a => op y result
{-
The induction function on the `Fin` indexed type family. Define this by pattern matching.
-}
inducFin : (xs : (n: Nat) -> Fin n -> Type) ->
(base : (m: Nat) -> xs (S m) FZ) ->
(step : (p: Nat) -> (k: Fin p) -> (prev: xs p k) -> (xs (S p) (FS k))) ->
(q: Nat) -> (j: Fin q) -> xs q j
inducFin _ _ _ Z FZ impossible
inducFin _ _ _ Z FS impossible
inducFin xs base step (S k) FZ = base k
inducFin xs base step (S k) (FS j) = step k j (inducFin xs base step k j)
{-
Given a type `a`, a natural number `q`, an element `j : Fin q` and a vector `v` of length q with entries of type `a`,
get the element in position `j` of `v`. Note that this is always well defined.
Note: Define using `inducList` and without pattern matching on the `Fin` family. You may pattern match on Vectors.
The definition should have only one case, and there should be no case splitting on `Fin`
-}
fetchElem : (a: Type) -> (q: Nat) -> (j: Fin q) -> (Vect q a -> a)
fetchElem a q j v = inducFin xs base step q j v where
xs : (n : Nat) -> Fin n -> Type
xs q j = Vect q a -> a
base : (m : Nat) -> xs (S m) FZ
base m = f where
f (x :: xs) = x
step : (p : Nat) -> (k : Fin p) -> (prev : xs p k) -> (xs (S p) (FS k))
step p k prev (y :: ys) = prev ys
|
#' @name splendid-package
#' @aliases splendid-package
#' @keywords internal
#' @docType package
#' @import ggplot2
#' @importFrom magrittr "%>%"
#' @importFrom rlang "%||%" "%@%" "!!" ":=" .data sym
"_PACKAGE"
|
[STATEMENT]
lemma ConcretenessSemantics1:
"Some r = d\<^sub>1 E! \<Longrightarrow> (\<exists> w . \<omega>\<nu> x \<in> ex1 r w)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. Some r = d\<^sub>1 E! \<Longrightarrow> \<exists>w. \<omega>\<nu> x \<in> ex1 r w
[PROOF STEP]
unfolding semantics_defs
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. Some r = map_fun eval\<Pi>\<^sub>1 id Some E! \<Longrightarrow> \<exists>w. \<omega>\<nu> x \<in> {x. r (\<nu>\<upsilon> x) dj w}
[PROOF STEP]
apply transfer
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>r x. Some r = map_fun (\<lambda>x. x) id Some (\<lambda>u s w. case u of \<omega>\<upsilon> x \<Rightarrow> ConcreteInWorld x w | \<sigma>\<upsilon> \<sigma> \<Rightarrow> False) \<Longrightarrow> \<exists>w. \<omega>\<nu> x \<in> {x. r (\<nu>\<upsilon> x) dj w}
[PROOF STEP]
by (simp add: OrdinaryObjectsPossiblyConcreteAxiom \<nu>\<upsilon>_\<omega>\<nu>_is_\<omega>\<upsilon>) |
main : IO ()
-- main = putStrLn "Hello World"
main = getLine >>= putStrLn |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Resume document in Latex, template forked from Deedy-Resume.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\documentclass[]{rj-res}
\usepackage{fancyhdr}
\usepackage{multicol}
\usepackage{multirow}
\pagestyle{fancy}
\fancyhf{}
\begin{document}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TITLE NAME
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\namesection{Rajnesh}{Joshi}{ \urlstyle{same}\href{http://rajneshj.ca}{rajneshj.ca}\\
\href{mailto:[email protected]}{[email protected]} | XXX.XXX.XXXX \\
\href{https://www.linkedin.com/in/rajnesh-joshi/}{LinkedIn} |\href{https://github.com/Rajnesh28}{ git }
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% COLUMN ONE
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\hfill
\begin{minipage}[t]{1\textwidth}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% EXPERIENCE
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Education}
\runsubsection{Simon Fraser University}
\descript{BASc Computer Engineering }
\location{Sep 2019 - Aug 2024 | Burnaby, BC}
\sectionsep
\section{Experience }
\runsubsection{Sierra Wireless} \\
\descript{Manufacturing Hardware/ Software Engineer }
\location{Sep 2021 - May 2022 | Richmond, BC}
\vspace{\topsep} % Hacky fix for awkward extra vertical space
\begin{tightemize}
\item Worked on a team of 5, aimed to ensure that manufacturing of routers and modules was operational
\item Coded embedded software/firmware that would be used on DUTs in the lab and factory
\item Debugged PCAs/PCBs, worked with radio, signals and telecommunications, and test fixtures.
\end{tightemize}
\sectionsep
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% RESEARCH
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Projects}
\runsubsection{\textbf{\href{https://github.com/Rajnesh28/Auxiliary-Vision}{Auxiliary Vision}}} \\
\descript{Personal (Hackathon)}
\location{February 2022 | SFU StormHacks}
Worked with a team of 4 to create an app aimed to improve accessibility issues for individuals that are blind or with visual impairments in identifying everyday objects, text on labels, and reading PDFs using Computer Vision.
\sectionsep
\runsubsection{Tensor Processing Unit ASIC Design} \\
\descript{ENSC 252: Digital Logic and Design}
\location{Simon Fraser University | Burnaby, BC}
Domain specific architecture aimed at improving the processing speeds of computers that do machine learning by pipelining data in systolic arrays.
Four components, written in VHDL, MMU, WRAM, Activation Unit, and the Control Unit.
\sectionsep
\runsubsection{Gadget Bike Helmet} \\
\descript{ENSC 105W/100W: Engineering Science and Society}
\location{Simon Fraser University | Burnaby, BC}
Bike helmet with various EM sensors, an Arduino, and C++ script designed to provide riders with the ability to indicate turn signals with just the move of their hands, as well as give them blind spot detection warning.
\sectionsep
\end{minipage}
\section{Coursework, Skills and Involvements}
\begin{minipage}
\begin{multicols}{3}
\begin{multirows}
\location{}
\runsubsection{Coursework} \\
\location{}
Data Structures and Algorithms \\
Electronics \newline
Microprocessor Architecture \newline
Numerical Analysis \newline
Digital Logic and Design \newline
Machine Learning
\sectionsep
\runsubsection{Programming}\\
\location{Proficient:}
\textbullet{}
Python \textbullet{}
C/C++ \\ \textbullet{}
MATLAB \textbullet{}
JavaScript \textbullet{}
VHDL \\ \textbullet{}
NoSQL/SQL \textbullet{} HTML/CSS
\sectionsep
\end{multirows}
\columnbreak
\location{}
\runsubsection{Technical Skills}\\
\location{Electronic Test Instrumentation:}
\begin{tightemize}
\item Spectrum analyzers and function generators
\item Oscilloscopes
\item Wideband Radio Communication testers
\item DMMs, DC Loads, Power Supply
\end{tightemize}
Motors, Actuators, and Sensors\\
Arduino and Raspberry Pi \\
Radio Test Fixture Design \\
PCB/PCA soldering, debugging
\sectionsep
\location{}
\runsubsection{Technologies}
\location{}
\textbullet{} SPICE \textbullet{}
React \textbullet{}
Android Studio \textbullet{}
Visio \textbullet{}
Anaconda3
\sectionsep
\columnbreak
\location{}
\begin{multirows}
\location{}
\runsubsection{Involvements}\\
\location{Engineering Science Student Society}
VP Social 2021
\begin{tightemize}
\item Manage events, and gatherings for engineers
\item Won Engineering Undergraduate Student Society Award for work
\end{tightemize}
\location{Lions Park Animal Hospital}
Volunteer
\begin{tightemize}
\item Working with veterinarians to ensure both animals and clients needs are met
\end{tightemize}
\section{}
\end{multicols}
\end{minipage}
\end{document} \documentclass[]
|
rrule {
*out3 = ""
*out2 = ""
# -- try:
# irule -F rescName_from_kvpair.r "*in1='COMPUTE_RESOURCE_ROLE=LONG_TERM_STORAGE'"
# -- or to just get 'Default value':
# irule -F rescName_from_kvpair.r <<<"" | tail -1 |sed 's/^.*=//'
#
# or as a general scheme for use in sh/Bash scripts:
#
# find_compute_resc() { irule -F rescName_from_kvpair.r <<<"\"COMPUTE_RESOURCE_ROLE=$1\"" | tail -1 |sed 's/^.*=//'; }
# # ...
# resc_name=$(find_compute_resc IMAGE_PROCESSING)
pyParseRoleSpec( *in1, *out2, *out3 )
*r = "NULL"
if ((*out2 != "") && (*out3 != "")) {
get_resource_name_by_role ( *r , *out2, *out3 )
}
if (*r == "NULL") {
*r="demoResc"
}
writeLine("stdout", "*r" )
}
INPUT *in1=$"COMPUTE_RESOURCE_ROLE=IMAGE_PROCESSING"
OUTPUT ruleExecOut
|
lemma (in function_ring_on) Stone_Weierstrass_special: assumes f: "continuous_on S f" and fpos: "\<And>x. x \<in> S \<Longrightarrow> f x \<ge> 0" and e: "0 < e" "e < 1/3" shows "\<exists>g \<in> R. \<forall>x\<in>S. \<bar>f x - g x\<bar> < 2*e" |
lemma emeasure_insert: assumes sets: "{x} \<in> sets M" "A \<in> sets M" and "x \<notin> A" shows "emeasure M (insert x A) = emeasure M {x} + emeasure M A" |
Require Import Coq.Strings.String Coq.Lists.List.
Require Import Fiat.Parsers.ContextFreeGrammar.Core.
Require Import Fiat.Parsers.ContextFreeGrammar.Reflective.
Require Import Fiat.Common.List.Operations.
Require Import Fiat.Common.Equality.
Require Import Fiat.Common.Gensym.
Delimit Scope item_scope with item.
Bind Scope item_scope with item.
Delimit Scope production_scope with production.
Delimit Scope prod_assignment_scope with prod_assignment.
Bind Scope production_scope with production.
Delimit Scope productions_scope with productions.
Delimit Scope productions_assignment_scope with prods_assignment.
Bind Scope productions_scope with productions.
Delimit Scope grammar_scope with grammar.
Bind Scope grammar_scope with grammar.
(** [abstract] doesn't work in definitions *)
Class NoDupR {T} beq (ls : list T) := nodupr : uniquize beq ls = ls.
Hint Extern 5 (NoDupR _ _) => clear; (*abstract*) (vm_compute; reflexivity) : typeclass_instances.
Definition list_to_productions {T} (default : T) (ls : list (string * T)) : string -> T
:= fun nt
=> option_rect
(fun _ => T)
snd
default
(find (fun k => string_beq nt (fst k)) ls).
Record pregrammar Char :=
{
pregrammar_rproductions : list (string * rproductions Char);
pregrammar_idata : interp_RCharExpr_data Char;
pregrammar_rnonterminals : list string
:= map fst pregrammar_rproductions;
rnonterminals_unique
: NoDupR string_beq pregrammar_rnonterminals;
RLookup_idx : nat -> rproductions Char
:= fun n => nth n (map snd pregrammar_rproductions) nil
}.
Global Existing Instance pregrammar_idata.
Section with_actions.
Context (Char T : Type).
Definition action_of_ritem (it : ritem Char) : Type
:= match it with
| RTerminal _ => Char
| RNonTerminal _ => T
end.
Fixpoint action_of_rproduction (pat : rproduction Char) : Type
:= match pat with
| nil => T
| cons it pat'
=> action_of_ritem it -> action_of_rproduction pat'
end.
Definition ritem_with_action := { it : ritem Char & action_of_ritem it }.
Definition rproduction_with_action := { pat : rproduction Char & action_of_rproduction pat }.
Definition rproductions_with_actions := list rproduction_with_action.
Record pregrammar_with_actions :=
{
pregrammar_arproductions : list (string * rproductions_with_actions);
pregrammar_aidata : interp_RCharExpr_data Char;
pregrammar_arnonterminals : list string
:= map fst pregrammar_arproductions;
pregrammar_a_only_rproductions : list (rproductions Char)
:= map (map (@projT1 _ _)) (map snd pregrammar_arproductions);
arnonterminals_unique
: NoDupR string_beq pregrammar_arnonterminals
}.
Definition pregrammar_of_pregrammar_with_actions (g : pregrammar_with_actions) : pregrammar Char.
Proof.
eapply {| pregrammar_rproductions := List.map (fun xy => (fst xy, List.map (@projT1 _ _) (snd xy)))
(pregrammar_arproductions g) |}.
Grab Existential Variables.
2:eapply (pregrammar_aidata g). (* wheee, dependent subgoals in Coq 8.4 *)
abstract (
rewrite map_map; simpl;
apply (arnonterminals_unique g)
).
Defined.
End with_actions.
Global Existing Instance pregrammar_aidata.
Global Coercion pregrammar_of_pregrammar_with_actions : pregrammar_with_actions >-> pregrammar.
Record pregrammar' (Char : Type) :=
{
pregrammar_productions :> list (string * productions Char);
pregrammar_nonterminals : list string
:= map fst pregrammar_productions;
invalid_nonterminal : string
:= gensym pregrammar_nonterminals;
Lookup_idx : nat -> productions Char
:= fun n => nth n (map snd pregrammar_productions) nil;
Lookup_string : string -> productions Char
:= list_to_productions nil pregrammar_productions;
nonterminals_unique
: NoDupR string_beq pregrammar_nonterminals
}.
Global Arguments pregrammar_nonterminals / _ _.
Global Arguments Lookup_idx {_} !_ !_ / .
Global Arguments Lookup_string {_} !_ !_ / .
Existing Instance nonterminals_unique.
Arguments nonterminals_unique {_} _.
Definition pregrammar'_of_pregrammar {Char} (g : pregrammar Char) : pregrammar' Char.
Proof.
eapply {| pregrammar_productions := List.map (fun xy => (fst xy, interp_rproductions (snd xy))) (pregrammar_rproductions g) |}.
Grab Existential Variables.
2:eapply (pregrammar_idata g). (* wheee, dependent subgoals in Coq 8.4 *)
abstract (
rewrite map_map; simpl;
apply (rnonterminals_unique g)
).
Defined.
Coercion pregrammar'_of_pregrammar : pregrammar >-> pregrammar'.
Coercion grammar_of_pregrammar {Char} (g : pregrammar' Char) : grammar Char
:= {| Start_symbol := hd ""%string (pregrammar_nonterminals g);
Lookup := Lookup_string g;
Valid_nonterminals := (pregrammar_nonterminals g) |}.
Global Instance valid_nonterminals_unique {Char} {G : pregrammar' Char}
: NoDupR string_beq (Valid_nonterminals G)
:= nonterminals_unique _.
Definition list_to_grammar {T} (default : productions T) (ls : list (string * productions T)) : grammar T
:= {| Start_symbol := hd ""%string (map fst ls);
Lookup := list_to_productions default ls;
Valid_nonterminals := map fst ls |}.
Global Arguments list_to_grammar {_} _ _.
|
lemma proper_map_polyfun_eq: assumes "f holomorphic_on UNIV" shows "(\<forall>k. compact k \<longrightarrow> compact {z. f z \<in> k}) \<longleftrightarrow> (\<exists>c n. 0 < n \<and> (c n \<noteq> 0) \<and> f = (\<lambda>z. \<Sum>i\<le>n. c i * z^i))" (is "?lhs = ?rhs") |
(* Inductive day : Type :=
| monday
| tuesday
| wednesday
| thursday
| friday
| saturday
| sunday.
Definition next_weekday (d:day) : day :=
match d with
| monday => tuesday
| tuesday => wednesday
| wednesday => thursday
| thursday => friday
| friday => monday
| saturday => monday
| sunday => monday
end.
Compute (next_weekday saturday).
Example test_next:
(next_weekday(next_weekday(saturday))) = tuesday.
Proof. simpl. reflexivity. Qed. *)
(*
Inductive bool : Type :=
| true
| false.
Definition negb (b: bool) :=
match b with
| true => false
| false => true
end.
Definition andb (b1: bool) (b2: bool) :=
match b1 with
| true => b2
| false => false
end.
Definition orb (b1:bool) (b2:bool) : bool :=
match b1 with
| true => true
| false => b2
end.
Example test_orb1: (orb true false) = true.
Proof. simpl. reflexivity. Qed.
*)
(*Level 1 -- nandb*)
Definition nandb (b1: bool) (b2: bool) : bool :=
match b1 with
| true => (negb b2)
| false => true
end.
Example test_nandb1: (nandb true false) = true.
Proof. simpl. reflexivity. Qed.
Example test_nandb2: (nandb false false) = true.
Proof. simpl. reflexivity. Qed.
Example test_nandb3: (nandb false true) = true.
Proof. simpl. reflexivity. Qed.
Example test_nandb4: (nandb true true) = false.
Proof. simpl. reflexivity. Qed.
(*Level 1 -- nandb3*)
Definition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=
(andb b1 (andb b2 b3)).
Example test_andb31: (andb3 true true true) = true.
Proof. simpl. reflexivity. Qed.
Example test_andb32: (andb3 false true true) = false.
Proof. simpl. reflexivity. Qed.
Example test_andb33: (andb3 true false true) = false.
Proof. simpl. reflexivity. Qed.
Example test_andb34: (andb3 true true false) = false.
Proof. simpl. reflexivity. Qed.
(* Check negb.
Inductive rgb : Type :=
| red
| green
| blue.
Inductive color : Type :=
| black
| white
| primary (p: rgb).
Definition monochrome (c: color) :=
match c with
| black => true
| white => true
| primary p => false
end.
Inductive bit : Type :=
| B0
| B1.
Inductive nybble : Type :=
| bits (b0 b1 b2 b3 : bit).
Check (bits B1 B0 B1 B0).
Definition all_zero (nb : nybble) : bool :=
match nb with
| (bits B0 B0 B0 B0) => true
| (bits _ _ _ _) => false
end.
Compute (all_zero (bits B1 B0 B1 B0)).
Compute (all_zero (bits B1 B1 B1 B1)).
Compute (all_zero (bits B0 B0 B0 B0)).
Module NatPlayground.
Inductive nat : Type :=
| O
| S (n : nat) .
Definition pred (n : nat) : nat :=
match n with
| O => O
| S n' => n'
end.
End NatPlayground.
Check (S (S (S 2))). *)
(*Level 1 -- factorial*)
Fixpoint mult (n m : nat) : nat :=
match n with
| O => O
| S n' => plus m (mult n' m)
end.
Fixpoint minus (n m:nat) : nat :=
match n, m with
| O , _ => O
| S _ , O => n
| S n', S m' => minus n' m'
end.
Fixpoint factorial (n:nat) : nat :=
match n with
| O => S O
| S n' => (mult (factorial n') n)
end.
Example test_factorial1: (factorial 3) = 6.
Proof. simpl. reflexivity. Qed.
Example test_factorial2: (factorial 5) = (mult 10 12).
Proof. simpl. reflexivity. Qed.
|
import Mathlib.Data.Nat.Basic
namespace Nat
/-
In Lean the natural numbers `ℕ` are defined as follows:
inductive nat
| zero : nat
| succ (n : nat) : nat
This means that there are two ways to construct a natural number `n:ℕ`
Either `n` is `zero` or it is the successor of a previously constructed
natural number `succ n`. -/
--#check zero
--#reduce succ 3
--#check succ (succ zero)
--#check zero.succ
#check Nat.zero_add
/-
Addition is defined inductively in Lean:
def add : ℕ → ℕ → ℕ
| a zero := a -- a + 0 := a
| a (succ b) := succ (add a b) -- a + (b + 1) := (a + b) + 1
-/
-- We will use the `dot` notation for the successor function.
/-- n + 1 = n.succ -/
lemma Succ_eq_add_one (n : ℕ) : n.succ = n + 1 :=
by rfl
/-
We are now proving lemmas/theorems that already exist in `mathlib`.
To avoid clashes we will use the same names as `mathlib` but they will be Capitalised.
We won't use high level tactics such as `norm_num` or `linarith` but we will
need to use earlier results as we progress (mainly with `rw` and `apply` tactics).
For a much more complete tour of the natural numbers check out the Natural Numbers Game:
https://www.ma.imperial.ac.uk/~buzzard/xena/natural_number_game/
-/
lemma Add_zero (n : ℕ) : n + 0 = n :=
by rfl
/-- a + (b + 1) = (a + b) + 1 -/
lemma Add_succ (a b : ℕ) : a + b.succ = (a + b).succ:=
by rfl
/-
# New tactic for ℕ: induction
If we want to prove `∀ (n:ℕ), P n` then we can use
`induction n` which requires us to prove two things:
`P 0` and `P n → P n.succ`
# New tactic for structured proofs: have
Sometimes we want to prove intermediate results within a proof.
We can do this using the `have` tactic.
If we need to prove `h : P` (ie a proof that the proposition P is true)
then we can do this as follows:
.... middle of a proof
have h : P,
{
proof of P,
},
.... continue proof
We now have `h : P` in the local context.
# Variant of rw : rwa
If we have term in the local context `h1 : P` and after `rw h2` our goal becomes `⊢ P`
then `rwa h2` will do the `rw h2, exact h1` in one step.
(The `a` in `rwa` stands for `assumption` which is yet another tactic that will work whenever
our goal is closed by a term in the local context.) -/
lemma Zero_add :∀ n:ℕ, 0 + n = n
| zero => rfl
| n+1 => congrArg succ (Zero_add n)
lemma Succ_add (a b : ℕ) : a.succ + b = (a + b).succ:= by
cases b with
| zero => rfl
| succ b => exact congrArg succ (Succ_add a b)
/- Digression: how do we know that 0 ≠ 1?
This is one of the axioms of the natural numbers (Peano arithmetic)
and it is built into Lean's model of ℕ. -/
theorem Succ_ne_zero (n : ℕ) : n.succ ≠ 0 :=by
intro hn
contradiction
-- Lean also knows that the successor function is injective (by definition)
theorem Succ.inj (n m : ℕ) : n.succ = m.succ → n = m :=by
exact Nat.succ.inj
/- Our next result says that `+` is `associative`
In Lean `a + b + c` is defined as `(a + b) + c` so whenever you see an expression such as `a + b + c + d`
you need to remember how this is read by Lean: `((a + b) + c) + d`
We know that the brackets aren't required, but in Lean you need to prove this.
-/
--#check 1 + (2 + 4) -- brackets
--#check (1 + 2) + 4 -- no brackets
lemma Add_assoc (a b c : ℕ) : (a + b) + c = a + (b + c):=by
induction' c with n ih
rfl
rw [Add_succ,ih,Add_succ,Add_succ]
lemma Add_comm (a b : ℕ) : a + b = b + a :=by
induction' b with b ib
rw [Zero_add,Add_zero]
rw [Succ_add,Add_succ,ib]
-- /-
-- Multiplication is also defined inductively in Lean.
-- def mul : ℕ → ℕ → ℕ
-- | a 0 := 0 -- a * 0 := 0
-- | a (b + 1) := (mul a b) + a -- a * (b + 1) = (a * b) + a -/
lemma Mul_zero (n : ℕ) : n * 0 = 0:=by
rfl
lemma Mul_succ (m n : ℕ) : m * n.succ = m * n + m:=by
rfl
lemma Succ_mul (m n : ℕ) : m.succ * n = m * n + n:=by
induction' n with n hn
rfl
rw [Mul_succ,hn,Mul_succ,Add_assoc,Add_assoc,Add_succ,Add_succ m,Add_comm n]
lemma Zero_mul (n : ℕ) : 0 * n = 0:=by
induction' n with n hn
rfl
rw [Mul_succ, hn]
lemma Mul_one (n : ℕ) : n * 1 = n:=by
rw [Mul_succ,Mul_zero,Zero_add]
lemma One_mul (n : ℕ) : 1 * n = n:=by
induction' n with n hn
rfl
rw [Mul_succ,hn]
lemma Mul_add (a b c: ℕ) : a*(b + c) = a*b + a*c:=by
induction' a with a ha
rw [Zero_mul,Zero_mul,Zero_mul]
rw [Succ_mul,ha,Succ_mul,Succ_mul,Add_assoc,Add_assoc, Add_comm (a*c),Add_comm (a*c),Add_assoc]
lemma Add_mul (a b c: ℕ) : (b + c)*a = b*a +c*a:=by
induction' a with a ha
rfl
rw [Mul_succ,ha,Mul_succ,Mul_succ,Add_assoc,Add_assoc, Add_comm (c*a),Add_comm (c*a),Add_assoc]
lemma Mul_comm (a b : ℕ) : a * b = b * a :=by
induction' b with b hb
rw [Zero_mul]
rfl
rw [Mul_succ,hb,Succ_mul]
lemma Mul_assoc (a b c : ℕ) : a * b * c = a * (b * c):=by
induction' c with c hc
rw [Mul_zero]
rfl
rw [Mul_succ,Mul_succ,hc,Mul_add]
lemma Pow_zero (n : ℕ) : n ^ 0 = 1:=by
rfl
lemma Pow_succ (a b : ℕ) : a^b.succ= a^b * a:=by
rfl
lemma Pow_one (n : ℕ) : n ^ 1 = n:=by
rw [Pow_succ,Pow_zero,One_mul]
-- /-
-- # New use of tactic : cases
-- We don't need induction to prove our next result, but we do need to consider the cases of zero and
-- successor separately. The `cases n` tactic does exactly this. -/
lemma Zero_pow (n : ℕ) (h : n ≠ 0): 0 ^ n = 0:=by
cases' n with n
contradiction
rw [Pow_succ,Mul_zero]
lemma One_pow (n : ℕ) : 1 ^ n = 1:=by
induction' n with n hn
rw [Pow_zero]
rwa [Pow_succ,Mul_one]
lemma Pow_add (a b c: ℕ): a^(b + c)=a^b*a^c:=by
induction' c with c hc
rw [Add_zero,Pow_zero,Mul_one]
rw[Add_succ,Pow_succ,Pow_succ,← Mul_assoc,← hc]
lemma Pow_mul (a b c : ℕ) : a^(b * c) = (a^b)^c :=by
induction' c with c hc
rfl
rw [Pow_succ,Mul_succ,Pow_add,hc]
lemma Two_eq_one_add_one : 2 = 1 + 1:=by
rfl
lemma Two_mul (n : ℕ) : 2*n = n + n:=by
rw [Two_eq_one_add_one,Add_mul,One_mul]
lemma Three_mul (n : ℕ) : 3*n = n + n + n:=
have h3: 3 = 2 + 1:= by rfl
by rw [h3,Add_mul,One_mul,Two_mul]
lemma Pow_two (n : ℕ) : n^2 = n*n:=by
rw [Two_eq_one_add_one,Pow_add,Pow_one]
lemma Add_sq (a b : ℕ) : (a + b)^2 = a^2 + 2*a*b + b^2 :=by
rw [Pow_two,Pow_two,Pow_two,Add_mul,Mul_add,Mul_add,Two_mul,
Add_mul,Mul_comm b a,Add_assoc,Add_assoc,Add_assoc]
lemma Pow_three (n : ℕ) : n^3 = n*n*n:=by
have h3: 3 = 2 + 1 := by rfl
rw [h3,Pow_add,Pow_two,Pow_one]
lemma Add_cube (a b : ℕ) : (a + b)^3 = a^3 + 3*a^2*b + 3*a*b^2 + b^3:=by
simp_rw [Pow_three,Pow_two,Add_mul,Mul_add,Add_mul,Three_mul,
Add_mul,Add_assoc]
apply congrArg (λ x => a*a*a+x)
rw [Mul_comm, Mul_assoc]
apply congrArg (λ x => a*(a*b)+x)
apply congrArg (λ x => a*(a*b)+x)
simp_rw [←Add_assoc,Add_comm,Mul_comm b,Mul_assoc,Add_assoc]
apply congrArg (λ x => a*(b*b)+x)
apply congrArg (λ x => a*(b*b)+x)
simp_rw [Mul_comm b a,Add_assoc]
apply congrArg (λ x => a*(a*b)+x)
simp_rw [←Mul_assoc, Mul_comm b a]
|
[STATEMENT]
theorem wt_attack_if_tfr_attack:
assumes "interpretation\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<I>"
and "\<I> \<Turnstile>\<^sub>c \<langle>S, \<theta>\<rangle>"
and "wf\<^sub>c\<^sub>o\<^sub>n\<^sub>s\<^sub>t\<^sub>r S \<theta>"
and "wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<theta>"
and "tfr\<^sub>s\<^sub>t S"
and "wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (trms\<^sub>s\<^sub>t S)"
and "wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<theta>)"
obtains \<I>\<^sub>\<tau> where "interpretation\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<I>\<^sub>\<tau>"
and "\<I>\<^sub>\<tau> \<Turnstile>\<^sub>c \<langle>S, \<theta>\<rangle>"
and "wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<I>\<^sub>\<tau>"
and "wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<I>\<^sub>\<tau>)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>\<I>\<^sub>\<tau>. \<lbrakk>subst_domain \<I>\<^sub>\<tau> = \<V> \<and> ground (subst_range \<I>\<^sub>\<tau>); \<I>\<^sub>\<tau> \<Turnstile>\<^sub>c \<langle>S,\<theta>\<rangle>; wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<I>\<^sub>\<tau>; wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<I>\<^sub>\<tau>)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. (\<And>\<I>\<^sub>\<tau>. \<lbrakk>subst_domain \<I>\<^sub>\<tau> = \<V> \<and> ground (subst_range \<I>\<^sub>\<tau>); \<I>\<^sub>\<tau> \<Turnstile>\<^sub>c \<langle>S,\<theta>\<rangle>; wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<I>\<^sub>\<tau>; wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<I>\<^sub>\<tau>)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
have tfr: "tfr\<^sub>s\<^sub>e\<^sub>t (trms\<^sub>s\<^sub>t (LI_preproc S))" "wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (trms\<^sub>s\<^sub>t (LI_preproc S))"
"list_all tfr\<^sub>s\<^sub>t\<^sub>p (LI_preproc S)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. tfr\<^sub>s\<^sub>e\<^sub>t (trms\<^sub>s\<^sub>t (LI_preproc S)) &&& wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (trms\<^sub>s\<^sub>t (LI_preproc S)) &&& list_all tfr\<^sub>s\<^sub>t\<^sub>p (LI_preproc S)
[PROOF STEP]
using assms(5,6) LI_preproc_preserves_tfr
[PROOF STATE]
proof (prove)
using this:
tfr\<^sub>s\<^sub>t S
wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (trms\<^sub>s\<^sub>t S)
tfr\<^sub>s\<^sub>t ?S \<Longrightarrow> tfr\<^sub>s\<^sub>t (LI_preproc ?S)
goal (1 subgoal):
1. tfr\<^sub>s\<^sub>e\<^sub>t (trms\<^sub>s\<^sub>t (LI_preproc S)) &&& wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (trms\<^sub>s\<^sub>t (LI_preproc S)) &&& list_all tfr\<^sub>s\<^sub>t\<^sub>p (LI_preproc S)
[PROOF STEP]
unfolding tfr\<^sub>s\<^sub>t_def
[PROOF STATE]
proof (prove)
using this:
tfr\<^sub>s\<^sub>e\<^sub>t (trms\<^sub>s\<^sub>t S) \<and> list_all tfr\<^sub>s\<^sub>t\<^sub>p S
wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (trms\<^sub>s\<^sub>t S)
tfr\<^sub>s\<^sub>e\<^sub>t (trms\<^sub>s\<^sub>t ?S) \<and> list_all tfr\<^sub>s\<^sub>t\<^sub>p ?S \<Longrightarrow> tfr\<^sub>s\<^sub>e\<^sub>t (trms\<^sub>s\<^sub>t (LI_preproc ?S)) \<and> list_all tfr\<^sub>s\<^sub>t\<^sub>p (LI_preproc ?S)
goal (1 subgoal):
1. tfr\<^sub>s\<^sub>e\<^sub>t (trms\<^sub>s\<^sub>t (LI_preproc S)) &&& wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (trms\<^sub>s\<^sub>t (LI_preproc S)) &&& list_all tfr\<^sub>s\<^sub>t\<^sub>p (LI_preproc S)
[PROOF STEP]
by (metis, metis LI_preproc_trms_eq, metis)
[PROOF STATE]
proof (state)
this:
tfr\<^sub>s\<^sub>e\<^sub>t (trms\<^sub>s\<^sub>t (LI_preproc S))
wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (trms\<^sub>s\<^sub>t (LI_preproc S))
list_all tfr\<^sub>s\<^sub>t\<^sub>p (LI_preproc S)
goal (1 subgoal):
1. (\<And>\<I>\<^sub>\<tau>. \<lbrakk>subst_domain \<I>\<^sub>\<tau> = \<V> \<and> ground (subst_range \<I>\<^sub>\<tau>); \<I>\<^sub>\<tau> \<Turnstile>\<^sub>c \<langle>S,\<theta>\<rangle>; wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<I>\<^sub>\<tau>; wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<I>\<^sub>\<tau>)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
have wf_constr: "wf\<^sub>c\<^sub>o\<^sub>n\<^sub>s\<^sub>t\<^sub>r (LI_preproc S) \<theta>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. wf\<^sub>c\<^sub>o\<^sub>n\<^sub>s\<^sub>t\<^sub>r (LI_preproc S) \<theta>
[PROOF STEP]
by (metis LI_preproc_preserves_wellformedness assms(3))
[PROOF STATE]
proof (state)
this:
wf\<^sub>c\<^sub>o\<^sub>n\<^sub>s\<^sub>t\<^sub>r (LI_preproc S) \<theta>
goal (1 subgoal):
1. (\<And>\<I>\<^sub>\<tau>. \<lbrakk>subst_domain \<I>\<^sub>\<tau> = \<V> \<and> ground (subst_range \<I>\<^sub>\<tau>); \<I>\<^sub>\<tau> \<Turnstile>\<^sub>c \<langle>S,\<theta>\<rangle>; wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<I>\<^sub>\<tau>; wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<I>\<^sub>\<tau>)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
obtain S' \<theta>' where *: "simple S'" "(LI_preproc S,\<theta>) \<leadsto>\<^sup>* (S',\<theta>')" "\<lbrakk>{}; S'\<rbrakk>\<^sub>c \<I>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>S' \<theta>'. \<lbrakk>simple S'; (LI_preproc S, \<theta>) \<leadsto>\<^sup>* (S', \<theta>'); \<lbrakk>{}; S'\<rbrakk>\<^sub>c \<I>\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
using LI_completeness[OF assms(3,2)]
[PROOF STATE]
proof (prove)
using this:
\<exists>S\<^sub>2 \<theta>\<^sub>2. (LI_preproc S, \<theta>) \<leadsto>\<^sup>* (S\<^sub>2, \<theta>\<^sub>2) \<and> simple S\<^sub>2 \<and> \<I> \<Turnstile>\<^sub>c \<langle>S\<^sub>2,\<theta>\<^sub>2\<rangle>
goal (1 subgoal):
1. (\<And>S' \<theta>'. \<lbrakk>simple S'; (LI_preproc S, \<theta>) \<leadsto>\<^sup>* (S', \<theta>'); \<lbrakk>{}; S'\<rbrakk>\<^sub>c \<I>\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
unfolding constr_sem_c_def
[PROOF STATE]
proof (prove)
using this:
\<exists>S\<^sub>2 \<theta>\<^sub>2. (LI_preproc S, \<theta>) \<leadsto>\<^sup>* (S\<^sub>2, \<theta>\<^sub>2) \<and> simple S\<^sub>2 \<and> \<theta>\<^sub>2 supports \<I> \<and> \<lbrakk>{}; S\<^sub>2\<rbrakk>\<^sub>c \<I>
goal (1 subgoal):
1. (\<And>S' \<theta>'. \<lbrakk>simple S'; (LI_preproc S, \<theta>) \<leadsto>\<^sup>* (S', \<theta>'); \<lbrakk>{}; S'\<rbrakk>\<^sub>c \<I>\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by (meson term.order_refl)
[PROOF STATE]
proof (state)
this:
simple S'
(LI_preproc S, \<theta>) \<leadsto>\<^sup>* (S', \<theta>')
\<lbrakk>{}; S'\<rbrakk>\<^sub>c \<I>
goal (1 subgoal):
1. (\<And>\<I>\<^sub>\<tau>. \<lbrakk>subst_domain \<I>\<^sub>\<tau> = \<V> \<and> ground (subst_range \<I>\<^sub>\<tau>); \<I>\<^sub>\<tau> \<Turnstile>\<^sub>c \<langle>S,\<theta>\<rangle>; wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<I>\<^sub>\<tau>; wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<I>\<^sub>\<tau>)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
have **: "wf\<^sub>c\<^sub>o\<^sub>n\<^sub>s\<^sub>t\<^sub>r S' \<theta>'" "wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<theta>'" "list_all tfr\<^sub>s\<^sub>t\<^sub>p S'" "wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (trms\<^sub>s\<^sub>t S')" "wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<theta>')"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (wf\<^sub>c\<^sub>o\<^sub>n\<^sub>s\<^sub>t\<^sub>r S' \<theta>' &&& wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<theta>') &&& list_all tfr\<^sub>s\<^sub>t\<^sub>p S' &&& wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (trms\<^sub>s\<^sub>t S') &&& wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<theta>')
[PROOF STEP]
using LI_preserves_welltypedness[OF *(2) wf_constr assms(4,7) tfr]
LI_preserves_wellformedness[OF *(2) wf_constr]
LI_preserves_tfr[OF *(2) wf_constr assms(4,7) tfr]
[PROOF STATE]
proof (prove)
using this:
wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<theta>'
wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<theta>')
wf\<^sub>c\<^sub>o\<^sub>n\<^sub>s\<^sub>t\<^sub>r S' \<theta>'
tfr\<^sub>s\<^sub>e\<^sub>t (trms\<^sub>s\<^sub>t S')
wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (trms\<^sub>s\<^sub>t S')
list_all tfr\<^sub>s\<^sub>t\<^sub>p S'
goal (1 subgoal):
1. (wf\<^sub>c\<^sub>o\<^sub>n\<^sub>s\<^sub>t\<^sub>r S' \<theta>' &&& wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<theta>') &&& list_all tfr\<^sub>s\<^sub>t\<^sub>p S' &&& wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (trms\<^sub>s\<^sub>t S') &&& wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<theta>')
[PROOF STEP]
by metis+
[PROOF STATE]
proof (state)
this:
wf\<^sub>c\<^sub>o\<^sub>n\<^sub>s\<^sub>t\<^sub>r S' \<theta>'
wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<theta>'
list_all tfr\<^sub>s\<^sub>t\<^sub>p S'
wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (trms\<^sub>s\<^sub>t S')
wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<theta>')
goal (1 subgoal):
1. (\<And>\<I>\<^sub>\<tau>. \<lbrakk>subst_domain \<I>\<^sub>\<tau> = \<V> \<and> ground (subst_range \<I>\<^sub>\<tau>); \<I>\<^sub>\<tau> \<Turnstile>\<^sub>c \<langle>S,\<theta>\<rangle>; wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<I>\<^sub>\<tau>; wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<I>\<^sub>\<tau>)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
define A where "A \<equiv> {x \<in> vars\<^sub>s\<^sub>t S'. \<exists>X F. Inequality X F \<in> set S' \<and> x \<in> fv\<^sub>p\<^sub>a\<^sub>i\<^sub>r\<^sub>s F \<and> x \<notin> set X}"
[PROOF STATE]
proof (state)
this:
A \<equiv> {x \<in> vars\<^sub>s\<^sub>t S'. \<exists>X F. \<forall>X\<langle>\<or>\<noteq>: F\<rangle>\<^sub>s\<^sub>t \<in> set S' \<and> x \<in> fv\<^sub>p\<^sub>a\<^sub>i\<^sub>r\<^sub>s F \<and> x \<notin> set X}
goal (1 subgoal):
1. (\<And>\<I>\<^sub>\<tau>. \<lbrakk>subst_domain \<I>\<^sub>\<tau> = \<V> \<and> ground (subst_range \<I>\<^sub>\<tau>); \<I>\<^sub>\<tau> \<Turnstile>\<^sub>c \<langle>S,\<theta>\<rangle>; wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<I>\<^sub>\<tau>; wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<I>\<^sub>\<tau>)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
define B where "B \<equiv> UNIV - A"
[PROOF STATE]
proof (state)
this:
B \<equiv> \<V> - A
goal (1 subgoal):
1. (\<And>\<I>\<^sub>\<tau>. \<lbrakk>subst_domain \<I>\<^sub>\<tau> = \<V> \<and> ground (subst_range \<I>\<^sub>\<tau>); \<I>\<^sub>\<tau> \<Turnstile>\<^sub>c \<langle>S,\<theta>\<rangle>; wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<I>\<^sub>\<tau>; wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<I>\<^sub>\<tau>)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
let ?\<I> = "rm_vars B \<I>"
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. (\<And>\<I>\<^sub>\<tau>. \<lbrakk>subst_domain \<I>\<^sub>\<tau> = \<V> \<and> ground (subst_range \<I>\<^sub>\<tau>); \<I>\<^sub>\<tau> \<Turnstile>\<^sub>c \<langle>S,\<theta>\<rangle>; wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<I>\<^sub>\<tau>; wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<I>\<^sub>\<tau>)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
have gr\<I>: "ground (subst_range \<I>)" "ground (subst_range ?\<I>)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. ground (subst_range \<I>) &&& ground (subst_range (rm_vars B \<I>))
[PROOF STEP]
using assms(1) rm_vars_img_subset[of B \<I>]
[PROOF STATE]
proof (prove)
using this:
subst_domain \<I> = \<V> \<and> ground (subst_range \<I>)
subst_range (rm_vars B \<I>) \<subseteq> subst_range \<I>
goal (1 subgoal):
1. ground (subst_range \<I>) &&& ground (subst_range (rm_vars B \<I>))
[PROOF STEP]
by (auto simp add: subst_domain_def)
[PROOF STATE]
proof (state)
this:
ground (subst_range \<I>)
ground (subst_range (rm_vars B \<I>))
goal (1 subgoal):
1. (\<And>\<I>\<^sub>\<tau>. \<lbrakk>subst_domain \<I>\<^sub>\<tau> = \<V> \<and> ground (subst_range \<I>\<^sub>\<tau>); \<I>\<^sub>\<tau> \<Turnstile>\<^sub>c \<langle>S,\<theta>\<rangle>; wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<I>\<^sub>\<tau>; wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<I>\<^sub>\<tau>)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
{
[PROOF STATE]
proof (state)
this:
ground (subst_range \<I>)
ground (subst_range (rm_vars B \<I>))
goal (1 subgoal):
1. (\<And>\<I>\<^sub>\<tau>. \<lbrakk>subst_domain \<I>\<^sub>\<tau> = \<V> \<and> ground (subst_range \<I>\<^sub>\<tau>); \<I>\<^sub>\<tau> \<Turnstile>\<^sub>c \<langle>S,\<theta>\<rangle>; wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<I>\<^sub>\<tau>; wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<I>\<^sub>\<tau>)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
fix X F
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. (\<And>\<I>\<^sub>\<tau>. \<lbrakk>subst_domain \<I>\<^sub>\<tau> = \<V> \<and> ground (subst_range \<I>\<^sub>\<tau>); \<I>\<^sub>\<tau> \<Turnstile>\<^sub>c \<langle>S,\<theta>\<rangle>; wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<I>\<^sub>\<tau>; wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<I>\<^sub>\<tau>)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
assume "Inequality X F \<in> set S'"
[PROOF STATE]
proof (state)
this:
\<forall>X\<langle>\<or>\<noteq>: F\<rangle>\<^sub>s\<^sub>t \<in> set S'
goal (1 subgoal):
1. (\<And>\<I>\<^sub>\<tau>. \<lbrakk>subst_domain \<I>\<^sub>\<tau> = \<V> \<and> ground (subst_range \<I>\<^sub>\<tau>); \<I>\<^sub>\<tau> \<Turnstile>\<^sub>c \<langle>S,\<theta>\<rangle>; wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<I>\<^sub>\<tau>; wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<I>\<^sub>\<tau>)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
hence *: "ineq_model \<I> X F"
[PROOF STATE]
proof (prove)
using this:
\<forall>X\<langle>\<or>\<noteq>: F\<rangle>\<^sub>s\<^sub>t \<in> set S'
goal (1 subgoal):
1. ineq_model \<I> X F
[PROOF STEP]
using strand_sem_c_imp_ineq_model[OF *(3)]
[PROOF STATE]
proof (prove)
using this:
\<forall>X\<langle>\<or>\<noteq>: F\<rangle>\<^sub>s\<^sub>t \<in> set S'
\<forall>?X\<langle>\<or>\<noteq>: ?F\<rangle>\<^sub>s\<^sub>t \<in> set S' \<Longrightarrow> ineq_model \<I> ?X ?F
goal (1 subgoal):
1. ineq_model \<I> X F
[PROOF STEP]
by (auto simp del: subst_range.simps)
[PROOF STATE]
proof (state)
this:
ineq_model \<I> X F
goal (1 subgoal):
1. (\<And>\<I>\<^sub>\<tau>. \<lbrakk>subst_domain \<I>\<^sub>\<tau> = \<V> \<and> ground (subst_range \<I>\<^sub>\<tau>); \<I>\<^sub>\<tau> \<Turnstile>\<^sub>c \<langle>S,\<theta>\<rangle>; wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<I>\<^sub>\<tau>; wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<I>\<^sub>\<tau>)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
hence "ineq_model ?\<I> X F"
[PROOF STATE]
proof (prove)
using this:
ineq_model \<I> X F
goal (1 subgoal):
1. ineq_model (rm_vars B \<I>) X F
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. ineq_model \<I> X F \<Longrightarrow> ineq_model (rm_vars B \<I>) X F
[PROOF STEP]
{
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. ineq_model \<I> X F \<Longrightarrow> ineq_model (rm_vars B \<I>) X F
[PROOF STEP]
fix \<delta>
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. ineq_model \<I> X F \<Longrightarrow> ineq_model (rm_vars B \<I>) X F
[PROOF STEP]
assume 1: "subst_domain \<delta> = set X" "ground (subst_range \<delta>)"
and 2: "list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s \<I>) F"
[PROOF STATE]
proof (state)
this:
subst_domain \<delta> = set X
ground (subst_range \<delta>)
list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s \<I>) F
goal (1 subgoal):
1. ineq_model \<I> X F \<Longrightarrow> ineq_model (rm_vars B \<I>) X F
[PROOF STEP]
have "list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I>) F"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I>) F
[PROOF STEP]
using 2
[PROOF STATE]
proof (prove)
using this:
list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s \<I>) F
goal (1 subgoal):
1. list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I>) F
[PROOF STEP]
proof (induction F)
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s \<I>) [] \<Longrightarrow> list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I>) []
2. \<And>a F. \<lbrakk>list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s \<I>) F \<Longrightarrow> list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I>) F; list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s \<I>) (a # F)\<rbrakk> \<Longrightarrow> list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I>) (a # F)
[PROOF STEP]
case (Cons g G)
[PROOF STATE]
proof (state)
this:
list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s \<I>) G \<Longrightarrow> list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I>) G
list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s \<I>) (g # G)
goal (2 subgoals):
1. list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s \<I>) [] \<Longrightarrow> list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I>) []
2. \<And>a F. \<lbrakk>list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s \<I>) F \<Longrightarrow> list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I>) F; list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s \<I>) (a # F)\<rbrakk> \<Longrightarrow> list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I>) (a # F)
[PROOF STEP]
obtain t t' where g: "g = (t,t')"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>t t'. g = (t, t') \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by (metis surj_pair)
[PROOF STATE]
proof (state)
this:
g = (t, t')
goal (2 subgoals):
1. list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s \<I>) [] \<Longrightarrow> list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I>) []
2. \<And>a F. \<lbrakk>list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s \<I>) F \<Longrightarrow> list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I>) F; list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s \<I>) (a # F)\<rbrakk> \<Longrightarrow> list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I>) (a # F)
[PROOF STEP]
thus ?case
[PROOF STATE]
proof (prove)
using this:
g = (t, t')
goal (1 subgoal):
1. list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I>) (g # G)
[PROOF STEP]
using Cons Unifier_ground_rm_vars[OF gr\<I>(1), of "t \<cdot> \<delta>" B "t' \<cdot> \<delta>"]
[PROOF STATE]
proof (prove)
using this:
g = (t, t')
list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s \<I>) G \<Longrightarrow> list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I>) G
list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s \<I>) (g # G)
Unifier (rm_vars B \<I>) (t \<cdot> \<delta>) (t' \<cdot> \<delta>) \<Longrightarrow> Unifier \<I> (t \<cdot> \<delta>) (t' \<cdot> \<delta>)
goal (1 subgoal):
1. list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I>) (g # G)
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I>) (g # G)
goal (1 subgoal):
1. list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s \<I>) [] \<Longrightarrow> list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I>) []
[PROOF STEP]
qed simp
[PROOF STATE]
proof (state)
this:
list_ex (\<lambda>f. fst f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I> \<noteq> snd f \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I>) F
goal (1 subgoal):
1. ineq_model \<I> X F \<Longrightarrow> ineq_model (rm_vars B \<I>) X F
[PROOF STEP]
}
[PROOF STATE]
proof (state)
this:
\<lbrakk>subst_domain ?\<delta>4 = set X; ground (subst_range ?\<delta>4); list_ex (\<lambda>f. fst f \<cdot> ?\<delta>4 \<circ>\<^sub>s \<I> \<noteq> snd f \<cdot> ?\<delta>4 \<circ>\<^sub>s \<I>) F\<rbrakk> \<Longrightarrow> list_ex (\<lambda>f. fst f \<cdot> ?\<delta>4 \<circ>\<^sub>s rm_vars B \<I> \<noteq> snd f \<cdot> ?\<delta>4 \<circ>\<^sub>s rm_vars B \<I>) F
goal (1 subgoal):
1. ineq_model \<I> X F \<Longrightarrow> ineq_model (rm_vars B \<I>) X F
[PROOF STEP]
thus ?thesis
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>subst_domain ?\<delta>4 = set X; ground (subst_range ?\<delta>4); list_ex (\<lambda>f. fst f \<cdot> ?\<delta>4 \<circ>\<^sub>s \<I> \<noteq> snd f \<cdot> ?\<delta>4 \<circ>\<^sub>s \<I>) F\<rbrakk> \<Longrightarrow> list_ex (\<lambda>f. fst f \<cdot> ?\<delta>4 \<circ>\<^sub>s rm_vars B \<I> \<noteq> snd f \<cdot> ?\<delta>4 \<circ>\<^sub>s rm_vars B \<I>) F
goal (1 subgoal):
1. ineq_model (rm_vars B \<I>) X F
[PROOF STEP]
using *
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>subst_domain ?\<delta>4 = set X; ground (subst_range ?\<delta>4); list_ex (\<lambda>f. fst f \<cdot> ?\<delta>4 \<circ>\<^sub>s \<I> \<noteq> snd f \<cdot> ?\<delta>4 \<circ>\<^sub>s \<I>) F\<rbrakk> \<Longrightarrow> list_ex (\<lambda>f. fst f \<cdot> ?\<delta>4 \<circ>\<^sub>s rm_vars B \<I> \<noteq> snd f \<cdot> ?\<delta>4 \<circ>\<^sub>s rm_vars B \<I>) F
ineq_model \<I> X F
goal (1 subgoal):
1. ineq_model (rm_vars B \<I>) X F
[PROOF STEP]
unfolding ineq_model_def list_ex_iff case_prod_unfold
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>subst_domain ?\<delta>4 = set X; ground (subst_range ?\<delta>4); \<exists>f\<in>set F. fst f \<cdot> ?\<delta>4 \<circ>\<^sub>s \<I> \<noteq> snd f \<cdot> ?\<delta>4 \<circ>\<^sub>s \<I>\<rbrakk> \<Longrightarrow> \<exists>f\<in>set F. fst f \<cdot> ?\<delta>4 \<circ>\<^sub>s rm_vars B \<I> \<noteq> snd f \<cdot> ?\<delta>4 \<circ>\<^sub>s rm_vars B \<I>
\<forall>\<delta>. subst_domain \<delta> = set X \<and> ground (subst_range \<delta>) \<longrightarrow> (\<exists>p\<in>set F. fst p \<cdot> \<delta> \<circ>\<^sub>s \<I> \<noteq> snd p \<cdot> \<delta> \<circ>\<^sub>s \<I>)
goal (1 subgoal):
1. \<forall>\<delta>. subst_domain \<delta> = set X \<and> ground (subst_range \<delta>) \<longrightarrow> (\<exists>p\<in>set F. fst p \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I> \<noteq> snd p \<cdot> \<delta> \<circ>\<^sub>s rm_vars B \<I>)
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
ineq_model (rm_vars B \<I>) X F
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
ineq_model (rm_vars B \<I>) X F
goal (1 subgoal):
1. (\<And>\<I>\<^sub>\<tau>. \<lbrakk>subst_domain \<I>\<^sub>\<tau> = \<V> \<and> ground (subst_range \<I>\<^sub>\<tau>); \<I>\<^sub>\<tau> \<Turnstile>\<^sub>c \<langle>S,\<theta>\<rangle>; wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<I>\<^sub>\<tau>; wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<I>\<^sub>\<tau>)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
}
[PROOF STATE]
proof (state)
this:
\<forall>?X4\<langle>\<or>\<noteq>: ?F4\<rangle>\<^sub>s\<^sub>t \<in> set S' \<Longrightarrow> ineq_model (rm_vars B \<I>) ?X4 ?F4
goal (1 subgoal):
1. (\<And>\<I>\<^sub>\<tau>. \<lbrakk>subst_domain \<I>\<^sub>\<tau> = \<V> \<and> ground (subst_range \<I>\<^sub>\<tau>); \<I>\<^sub>\<tau> \<Turnstile>\<^sub>c \<langle>S,\<theta>\<rangle>; wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<I>\<^sub>\<tau>; wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<I>\<^sub>\<tau>)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
\<forall>?X4\<langle>\<or>\<noteq>: ?F4\<rangle>\<^sub>s\<^sub>t \<in> set S' \<Longrightarrow> ineq_model (rm_vars B \<I>) ?X4 ?F4
goal (1 subgoal):
1. (\<And>\<I>\<^sub>\<tau>. \<lbrakk>subst_domain \<I>\<^sub>\<tau> = \<V> \<and> ground (subst_range \<I>\<^sub>\<tau>); \<I>\<^sub>\<tau> \<Turnstile>\<^sub>c \<langle>S,\<theta>\<rangle>; wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<I>\<^sub>\<tau>; wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<I>\<^sub>\<tau>)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
have "subst_domain \<I> = UNIV"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. subst_domain \<I> = \<V>
[PROOF STEP]
using assms(1)
[PROOF STATE]
proof (prove)
using this:
subst_domain \<I> = \<V> \<and> ground (subst_range \<I>)
goal (1 subgoal):
1. subst_domain \<I> = \<V>
[PROOF STEP]
by metis
[PROOF STATE]
proof (state)
this:
subst_domain \<I> = \<V>
goal (1 subgoal):
1. (\<And>\<I>\<^sub>\<tau>. \<lbrakk>subst_domain \<I>\<^sub>\<tau> = \<V> \<and> ground (subst_range \<I>\<^sub>\<tau>); \<I>\<^sub>\<tau> \<Turnstile>\<^sub>c \<langle>S,\<theta>\<rangle>; wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<I>\<^sub>\<tau>; wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<I>\<^sub>\<tau>)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
hence "subst_domain ?\<I> = A"
[PROOF STATE]
proof (prove)
using this:
subst_domain \<I> = \<V>
goal (1 subgoal):
1. subst_domain (rm_vars B \<I>) = A
[PROOF STEP]
using rm_vars_dom[of B \<I>] B_def
[PROOF STATE]
proof (prove)
using this:
subst_domain \<I> = \<V>
subst_domain (rm_vars B \<I>) = subst_domain \<I> - B
B \<equiv> \<V> - A
goal (1 subgoal):
1. subst_domain (rm_vars B \<I>) = A
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
subst_domain (rm_vars B \<I>) = A
goal (1 subgoal):
1. (\<And>\<I>\<^sub>\<tau>. \<lbrakk>subst_domain \<I>\<^sub>\<tau> = \<V> \<and> ground (subst_range \<I>\<^sub>\<tau>); \<I>\<^sub>\<tau> \<Turnstile>\<^sub>c \<langle>S,\<theta>\<rangle>; wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<I>\<^sub>\<tau>; wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<I>\<^sub>\<tau>)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
\<forall>?X4\<langle>\<or>\<noteq>: ?F4\<rangle>\<^sub>s\<^sub>t \<in> set S' \<Longrightarrow> ineq_model (rm_vars B \<I>) ?X4 ?F4
subst_domain (rm_vars B \<I>) = A
[PROOF STEP]
obtain \<I>\<^sub>\<tau> where
"interpretation\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<I>\<^sub>\<tau>" "\<I>\<^sub>\<tau> \<Turnstile>\<^sub>c \<langle>S', \<theta>'\<rangle>" "wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<I>\<^sub>\<tau>" "wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<I>\<^sub>\<tau>)"
[PROOF STATE]
proof (prove)
using this:
\<forall>?X4\<langle>\<or>\<noteq>: ?F4\<rangle>\<^sub>s\<^sub>t \<in> set S' \<Longrightarrow> ineq_model (rm_vars B \<I>) ?X4 ?F4
subst_domain (rm_vars B \<I>) = A
goal (1 subgoal):
1. (\<And>\<I>\<^sub>\<tau>. \<lbrakk>subst_domain \<I>\<^sub>\<tau> = \<V> \<and> ground (subst_range \<I>\<^sub>\<tau>); \<I>\<^sub>\<tau> \<Turnstile>\<^sub>c \<langle>S',\<theta>'\<rangle>; wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<I>\<^sub>\<tau>; wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<I>\<^sub>\<tau>)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
using wt_sat_if_simple[OF *(1) **(1,2,5,4) _ gr\<I>(2) _ **(3)] A_def
[PROOF STATE]
proof (prove)
using this:
\<forall>?X4\<langle>\<or>\<noteq>: ?F4\<rangle>\<^sub>s\<^sub>t \<in> set S' \<Longrightarrow> ineq_model (rm_vars B \<I>) ?X4 ?F4
subst_domain (rm_vars B \<I>) = A
\<lbrakk>\<forall>X F. \<forall>X\<langle>\<or>\<noteq>: F\<rangle>\<^sub>s\<^sub>t \<in> set S' \<longrightarrow> ineq_model (rm_vars B \<I>) X F; subst_domain (rm_vars B \<I>) = {x \<in> vars\<^sub>s\<^sub>t S'. \<exists>X F. \<forall>X\<langle>\<or>\<noteq>: F\<rangle>\<^sub>s\<^sub>t \<in> set S' \<and> x \<in> fv\<^sub>p\<^sub>a\<^sub>i\<^sub>r\<^sub>s F - set X}\<rbrakk> \<Longrightarrow> \<exists>\<I>. (subst_domain \<I> = \<V> \<and> ground (subst_range \<I>)) \<and> \<I> \<Turnstile>\<^sub>c \<langle>S',\<theta>'\<rangle> \<and> wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<I> \<and> wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<I>)
A \<equiv> {x \<in> vars\<^sub>s\<^sub>t S'. \<exists>X F. \<forall>X\<langle>\<or>\<noteq>: F\<rangle>\<^sub>s\<^sub>t \<in> set S' \<and> x \<in> fv\<^sub>p\<^sub>a\<^sub>i\<^sub>r\<^sub>s F \<and> x \<notin> set X}
goal (1 subgoal):
1. (\<And>\<I>\<^sub>\<tau>. \<lbrakk>subst_domain \<I>\<^sub>\<tau> = \<V> \<and> ground (subst_range \<I>\<^sub>\<tau>); \<I>\<^sub>\<tau> \<Turnstile>\<^sub>c \<langle>S',\<theta>'\<rangle>; wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<I>\<^sub>\<tau>; wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<I>\<^sub>\<tau>)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by (auto simp del: subst_range.simps)
[PROOF STATE]
proof (state)
this:
subst_domain \<I>\<^sub>\<tau> = \<V> \<and> ground (subst_range \<I>\<^sub>\<tau>)
\<I>\<^sub>\<tau> \<Turnstile>\<^sub>c \<langle>S',\<theta>'\<rangle>
wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<I>\<^sub>\<tau>
wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<I>\<^sub>\<tau>)
goal (1 subgoal):
1. (\<And>\<I>\<^sub>\<tau>. \<lbrakk>subst_domain \<I>\<^sub>\<tau> = \<V> \<and> ground (subst_range \<I>\<^sub>\<tau>); \<I>\<^sub>\<tau> \<Turnstile>\<^sub>c \<langle>S,\<theta>\<rangle>; wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<I>\<^sub>\<tau>; wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<I>\<^sub>\<tau>)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
thus ?thesis
[PROOF STATE]
proof (prove)
using this:
subst_domain \<I>\<^sub>\<tau> = \<V> \<and> ground (subst_range \<I>\<^sub>\<tau>)
\<I>\<^sub>\<tau> \<Turnstile>\<^sub>c \<langle>S',\<theta>'\<rangle>
wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<I>\<^sub>\<tau>
wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<I>\<^sub>\<tau>)
goal (1 subgoal):
1. thesis
[PROOF STEP]
using that LI_soundness[OF assms(3) *(2)]
[PROOF STATE]
proof (prove)
using this:
subst_domain \<I>\<^sub>\<tau> = \<V> \<and> ground (subst_range \<I>\<^sub>\<tau>)
\<I>\<^sub>\<tau> \<Turnstile>\<^sub>c \<langle>S',\<theta>'\<rangle>
wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t \<I>\<^sub>\<tau>
wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range \<I>\<^sub>\<tau>)
\<lbrakk>subst_domain ?\<I>\<^sub>\<tau>2 = \<V> \<and> ground (subst_range ?\<I>\<^sub>\<tau>2); ?\<I>\<^sub>\<tau>2 \<Turnstile>\<^sub>c \<langle>S,\<theta>\<rangle>; wt\<^sub>s\<^sub>u\<^sub>b\<^sub>s\<^sub>t ?\<I>\<^sub>\<tau>2; wf\<^sub>t\<^sub>r\<^sub>m\<^sub>s (subst_range ?\<I>\<^sub>\<tau>2)\<rbrakk> \<Longrightarrow> thesis
?\<I> \<Turnstile>\<^sub>c \<langle>S',\<theta>'\<rangle> \<Longrightarrow> ?\<I> \<Turnstile>\<^sub>c \<langle>S,\<theta>\<rangle>
goal (1 subgoal):
1. thesis
[PROOF STEP]
by metis
[PROOF STATE]
proof (state)
this:
thesis
goal:
No subgoals!
[PROOF STEP]
qed |
(*
* Copyright 2020, NTU
*
* This software may be distributed and modified according to the terms of
* the BSD 2-Clause license. Note that NO WARRANTY is provided.
* See "LICENSE_BSD2.txt" for details.
*
* Author: Albert Rizaldi, NTU Singapore
*)
theory Cosine_Imp
imports Cosine_Generator
begin
lemma (in cosine_locale) Inv_core_everywhere_strict:
assumes "tw, T, architecture \<Rightarrow>\<^sub>S tw'"
assumes "Inv tw" and "wityping \<Gamma> (snd tw)"
shows "\<And>n. fst tw \<le> n \<Longrightarrow> n \<le> T \<Longrightarrow> Inv_core (n, snd tw')"
proof -
fix n
assume "fst tw \<le> n" and "n \<le> T"
hence "n < T \<and> fst tw < n \<or> n = T \<or> fst tw = n"
by auto
moreover
{ assume "n < T \<and> fst tw < n" hence "fst tw < n" and "n < T" by auto
have 0: "world_sim_fin2_alt tw T architecture tw'"
using world_sim_fin_eq_world_sim_fin2_alt[OF conc_stmt_wf_arch nonneg_delay_conc_architecture] assms
by auto
obtain temp where "world_sim_fin2_alt tw n architecture temp" and "world_sim_fin2_alt temp T architecture tw'"
using split_world_sim_fin2_alt[OF 0 `fst tw < n` `n < T`] by auto
hence "world_sim_fin tw n architecture temp" and "world_sim_fin temp T architecture tw'"
using world_sim_fin_eq_world_sim_fin2_alt[OF conc_stmt_wf_arch nonneg_delay_conc_architecture]
by auto
hence "Inv temp"
using `Inv tw` `wityping \<Gamma> (snd tw)` inv_all_preserved_arch
unfolding sim_hoare_valid_wt_def by blast
have "fst temp = n" and "n \<le> fst temp" and "n - 1 - 1 \<le> fst temp" and "n - 1 \<le> fst temp"
using fst_world_sim_fin2_alt[OF `world_sim_fin2_alt tw n architecture temp`] by auto
note helpers = world_sim_fin2_alt_unaffected_before_curr[OF `world_sim_fin2_alt temp T architecture tw'`
nonneg_delay_conc_architecture conc_stmt_wf_arch `n \<le> fst temp`, unfolded comp_def snd_conv fst_conv]
world_sim_fin2_alt_unaffected_before_curr[OF `world_sim_fin2_alt temp T architecture tw'`
nonneg_delay_conc_architecture conc_stmt_wf_arch `n - 1 \<le> fst temp`, unfolded comp_def snd_conv fst_conv]
world_sim_fin2_alt_unaffected_before_curr[OF `world_sim_fin2_alt temp T architecture tw'`
nonneg_delay_conc_architecture conc_stmt_wf_arch `n - 1 - 1\<le> fst temp`, unfolded comp_def snd_conv fst_conv]
have "inv_reg (n, snd temp)" and "inv_ncommon (n, snd temp)" and "inv_sqr (n, snd temp)"
and "inv_naccum (n, snd temp)" and "Inv_core (n, snd temp)" and "inv_nfrac (n, snd temp)"
using `Inv temp` `fst temp = n` by auto
hence "Inv_core (n, snd tw')"
unfolding inv_reg_def inv_ncommon_alt_def inv_sqr_def inv_naccum_alt_def inv_term1_def
inv_output_def inv_output_ready_def inv_nout_alt_def inv_nstate_alt_def inv_ncounter_alt_def
inv_n0_def comp_def fst_conv snd_conv helpers inv_nfrac_alt_def by auto }
moreover
{ assume "n = T"
moreover have "fst tw' = T"
using assms(1) using world_maxtime_lt_fst_tres by blast
ultimately have "tw' = (n, snd tw')"
by auto
have "Inv tw'"
using `Inv tw` `wityping \<Gamma> (snd tw)` assms(1) inv_all_preserved_arch
unfolding sim_hoare_valid_wt_def by blast
hence "Inv_core (n, snd tw')"
using `tw' = (n, snd tw')` by auto }
moreover
{ assume "fst tw = n"
hence "Inv (n, snd tw)" and "n \<le> fst tw" and "n - 1 \<le> fst tw" and "n - 1 - 1 \<le> fst tw"
using `Inv tw` by auto
have "world_sim_fin2_alt tw T architecture tw'"
using assms(1) world_sim_fin_eq_world_sim_fin2_alt
by (simp add: world_sim_fin_eq_world_sim_fin2_alt conc_stmt_wf_arch nonneg_delay_conc_architecture)
note helpers = world_sim_fin2_alt_unaffected_before_curr[OF `world_sim_fin2_alt tw T architecture tw'`
nonneg_delay_conc_architecture conc_stmt_wf_arch `n \<le> fst tw`, unfolded comp_def snd_conv fst_conv]
world_sim_fin2_alt_unaffected_before_curr[OF `world_sim_fin2_alt tw T architecture tw'`
nonneg_delay_conc_architecture conc_stmt_wf_arch `n - 1\<le> fst tw`, unfolded comp_def snd_conv fst_conv]
world_sim_fin2_alt_unaffected_before_curr[OF `world_sim_fin2_alt tw T architecture tw'`
nonneg_delay_conc_architecture conc_stmt_wf_arch `n - 1 - 1\<le> fst tw`, unfolded comp_def snd_conv fst_conv]
have "Inv_core (n, snd tw')"
using `Inv (n, snd tw)`
unfolding inv_reg_def inv_ncommon_alt_def inv_sqr_def inv_naccum_alt_def inv_term1_def
inv_output_def inv_output_ready_def inv_nout_alt_def inv_nstate_alt_def inv_ncounter_alt_def
inv_n0_def comp_def fst_conv snd_conv helpers inv_nfrac_alt_def by auto }
ultimately show "Inv_core (n, snd tw')"
by auto
qed
lemma (in cosine_locale) registers_unchanged_no_rising_edge:
assumes "tw, T, architecture \<Rightarrow>\<^sub>S tw'"
assumes "Inv tw" and "wityping \<Gamma> (snd tw)" and "fst tw \<le> m" and "m \<le> n" and "n \<le> T"
assumes "\<And>k. m \<le> k \<Longrightarrow> k \<le> n \<Longrightarrow> \<not> is_posedge2 (snd tw') CLK k"
assumes "s \<in> {ACCUM, COUNTER, FRAC, COMMON, STATE, OUTREADY_REG}"
shows "wline_of tw' s m = wline_of tw' s n"
using assms
proof (induction "n - m" arbitrary: n)
case 0
hence "m = n"
by auto
then show ?case
by auto
next
case (Suc x)
hence "x = (n - 1) - m"
by (auto)
have "m = n \<or> m < n"
using Suc by auto
moreover
{ assume " m = n"
hence ?case by auto }
moreover
{ assume " m < n"
hence "m \<le> n - 1"
by auto
have "n - 1 \<le> T"
using Suc by auto
have *: "\<And>k. m \<le> k \<Longrightarrow> k \<le> n - 1 \<Longrightarrow> \<not> (snd (snd tw') CLK (k - 1) = Bv False \<and> snd (snd tw') CLK k = Bv True)"
using Suc(9) by auto
have "wline_of tw' s m = wline_of tw' s (n - 1)"
using Suc(1)[OF `x = (n - 1) - m` `tw, T, architecture \<Rightarrow>\<^sub>S tw'` `Inv tw` `wityping \<Gamma> (snd tw)` `fst tw \<le> m` `m \<le> n - 1` `n - 1 \<le> T` * `s \<in> {ACCUM, COUNTER, FRAC, COMMON, STATE, OUTREADY_REG}`]
by auto
have "fst tw \<le> n" and "n \<le> T"
using Suc.prems(5) assms(4) Suc.prems(6) dual_order.trans by blast+
have "\<not> is_posedge2 (snd tw') CLK (n - 1)"
using * \<open>m \<le> n - 1\<close> by blast
moreover have "Inv_core (n, snd tw')"
using Inv_core_everywhere_strict[OF Suc(3) `Inv tw` `wityping \<Gamma> (snd tw)` `fst tw \<le> n` `n \<le> T`]
by auto
ultimately have "wline_of tw' s (n - 1) = wline_of tw' s n"
using `s \<in> {ACCUM, COUNTER, FRAC, COMMON, STATE, OUTREADY_REG}` unfolding inv_reg_alt_def comp_def snd_conv fst_conv by auto
hence ?case
using `wline_of tw' s m = wline_of tw' s (n - 1)` by auto }
ultimately show ?case
by auto
qed
lemma (in cosine_locale) posedge_only_if_mod_clk_period:
assumes "even clk_period" and "2 \<le> clk_period"
assumes "\<forall>k < clk_period div 2. wline_of (0, w) CLK k = Bv True"
assumes "\<forall>k \<ge> clk_period div 2. k < clk_period \<longrightarrow> wline_of (0, w) CLK k = Bv False"
assumes "\<forall>k \<ge> clk_period. wline_of (0, w) CLK k = wline_of (0, w) CLK (k - clk_period)"
assumes type: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
shows "\<And>m. m mod clk_period \<noteq> 0 \<Longrightarrow> \<not> is_posedge2 w CLK m"
proof -
fix m
assume "m mod clk_period \<noteq> 0"
have "\<And>k. (wline_of (0, w) CLK k = Bv False) \<or> (wline_of (0, w) CLK k = Bv True)"
using type type_of_bty_cases by blast
have assms6': "\<And>k. k < clk_period \<Longrightarrow> wline_of (0, w) CLK k = Bv True \<Longrightarrow> k < clk_period div 2"
using assms(4) \<open>\<And>k. (wline_of (0, w) CLK k = Bv False) \<or> (wline_of (0, w) CLK k = Bv True)\<close>
using nat_less_le by force
have assms7': "\<And>k. wline_of (0, w) CLK k = wline_of (0, w) CLK (k mod clk_period)"
using wline_of_mod[OF assms(5)] by (metis mod_by_0 neq0_conv)
have "m < clk_period \<or> clk_period < m"
using `m mod clk_period \<noteq> 0` by (metis linorder_neqE_nat mod_self)
moreover
{ assume "m < clk_period"
have "\<not> is_posedge2 w CLK m"
proof (rule ccontr)
assume "\<not> \<not> is_posedge2 w CLK m" hence "is_posedge2 w CLK m" by auto
hence "snd w CLK (m - 1) = Bv False \<and> snd w CLK m = Bv True"
by auto
hence "m < clk_period div 2"
using assms6'[OF `m < clk_period`] unfolding comp_def snd_conv by auto
hence "wline_of (0, w) CLK (m - 1) = Bv True"
using assms(3) less_imp_diff_less by blast
thus False
using \<open>\<not> \<not> (snd w CLK (m - 1) = Bv False \<and> snd w CLK m = Bv True)\<close> by auto
qed }
moreover
{ assume "clk_period < m"
have "m = clk_period * (m div clk_period) + m mod clk_period"
using mult_div_mod_eq by auto
hence "wline_of (0, w) CLK m = wline_of (0, w) CLK (m mod clk_period)"
using assms7' by auto
have "\<not> is_posedge2 w CLK m"
proof (rule ccontr)
assume "\<not> \<not> is_posedge2 w CLK m"
hence "is_posedge2 w CLK m" by auto
hence "snd w CLK (m - 1) = Bv False \<and> snd w CLK m = Bv True"
by auto
have "m mod clk_period < clk_period"
using `2 \<le> clk_period ` by (auto intro!: pos_mod_bound)
moreover have "snd w CLK (m mod clk_period) = Bv True"
using assms7'[unfolded comp_def snd_conv] \<open>snd w CLK (m - 1) = Bv False \<and> snd w CLK m = Bv True\<close> by auto
ultimately have "m mod clk_period < clk_period div 2"
using assms6'[unfolded comp_def snd_conv] by blast
hence "snd w CLK (m mod clk_period - 1) = Bv True"
using assms(3)[unfolded comp_def snd_conv] less_imp_diff_less by blast
have "m = (m div clk_period) * clk_period + m mod clk_period"
by auto
hence "m - 1 = (m div clk_period) * clk_period + ((m mod clk_period) - 1)"
using \<open>m mod clk_period \<noteq> 0\<close> by auto
hence "snd w CLK (m - 1) = Bv True"
using wline_of_mod2[OF assms(5)] \<open>snd w CLK (m mod clk_period - 1) = Bv True\<close>
by (metis assms7' comp_apply mod_mult_self4 mult.commute snd_conv)
thus False
using \<open>\<not> \<not> (snd w CLK (m - 1) = Bv False \<and> snd w CLK m = Bv True)\<close> by auto
qed }
ultimately show "\<not> is_posedge2 w CLK m"
by auto
qed
lemma (in cosine_locale) ubin_counter_atmost:
assumes "wityping \<Gamma> (snd tw)"
shows "ubin_of COUNTER at_time n on tw \<le> 7"
proof -
have *: "type_of (wline_of tw COUNTER n) = Lty Uns 3"
using assms unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def snd_conv fst_conv by auto
have "\<exists>bs. wline_of tw COUNTER n = Lv Uns bs \<and> length bs = 3"
proof (rule ccontr)
assume "\<not> (\<exists>bs. wline_of tw COUNTER n = Lv Uns bs \<and> length bs = 3)"
hence "\<And>bs. wline_of tw COUNTER n = Lv Uns bs \<Longrightarrow> length bs \<noteq> 3"
by auto
moreover have "\<And>bs. wline_of tw COUNTER n = Lv Uns bs \<Longrightarrow> length bs = 3"
using * by auto
ultimately have **: "\<And>bs. wline_of tw COUNTER n = Lv Uns bs \<Longrightarrow> False"
by auto
obtain bs where" wline_of tw COUNTER n = Lv Uns bs"
using type_of.elims[OF *] by fastforce
with ** show False by auto
qed
then obtain bs where "wline_of tw COUNTER n = Lv Uns bs" and "length bs = 3"
by auto
hence "bl_to_bin bs < 8"
using bl_to_bin_lt2p[of "bs"] by auto
thus ?thesis
using \<open>wline_of tw COUNTER n = Lv Uns bs\<close> by auto
qed
fun approx_div_fact :: "nat \<Rightarrow> (1, 31) fixed" where
"approx_div_fact 0 = Fixed (approx_one :: (1 + 31) word) "
| "approx_div_fact (Suc 0) = Fixed (approx_half :: (1 + 31) word) "
| "approx_div_fact (Suc (Suc 0)) = Fixed (approx_fourth :: (1 + 31) word)"
| "approx_div_fact (Suc (Suc (Suc 0))) = Fixed (approx_sixth :: (1 + 31) word) "
| "approx_div_fact (Suc (Suc (Suc (Suc 0)))) = Fixed (approx_eighth :: (1 + 31) word)"
fun fixed_of_sval :: "val \<Rightarrow> ('a::len0, 'b::len0) fixed" where
"fixed_of_sval (Lv ki bl) = Fixed (of_bl bl :: ('a + 'b) word)"
fun nat_of_val :: "val \<Rightarrow> nat" where
"nat_of_val (Lv ki bl) = nat (bl_to_bin bl)"
fun val_of_fixed :: "('a::len0, 'b::len0) fixed \<Rightarrow> val" where
"val_of_fixed fi = Lv Sig (to_bl (word_of_fixed fi))"
lemma nths_from_upt_eq_drop_take [simp]: "nths l {m..<n} = drop m (take n l)"
proof (induct l rule: rev_induct)
case Nil
then show ?case by auto
next
case (snoc x xs)
then show ?case
unfolding nths_append nths_singleton by auto
qed
lemma (in cosine_locale) math_ident:
assumes "sim_fin2 w (i + 7 * clk_period + 1) architecture tw'"
assumes "wityping \<Gamma> w"
\<comment>\<open>characterising clock signals\<close>
assumes "even clk_period" and "3 < clk_period"
assumes "\<forall>k < clk_period div 2. wline_of (0, w) CLK k = Bv True"
assumes "\<forall>k \<ge> clk_period div 2. k < clk_period \<longrightarrow> wline_of (0, w) CLK k = Bv False"
assumes "\<forall>k \<ge> clk_period. wline_of (0, w) CLK k = wline_of (0, w) CLK (k - clk_period)"
\<comment>\<open>clock is in rising edge at i\<close>
assumes posedge: "is_posedge2 (snd tw') CLK (i + 7 * clk_period)"
\<comment> \<open>output ready signal is asserted at i + 1\<close>
assumes ready: "wline_of tw' OUTREADY_REG (i + 7 * clk_period + 1) = Bv True"
assumes " ubin_of COUNTER at_time (i + 1) on tw' \<noteq> 5"
shows "fixed_of_sval (wline_of tw' ACCUM (fst tw')) =
(foldr (\<lambda>a b. approx_div_fact a + (fixed_of_sval (wline_of tw' INPUT (i + 1 * clk_period - 1)) * fixed_of_sval (wline_of tw' INPUT (i + 1 * clk_period - 1))) * b) [0 ..< 5] 0)"
proof -
obtain tw where "init_sim2 (0, w) architecture tw" and 0: "tw, (i + 7 * clk_period + 1), architecture \<Rightarrow>\<^sub>S tw'"
using sim_fin2.cases[OF assms(1)] by metis
hence "Inv tw"
using init_sim2_hoare_wt_soundness[OF init_sat_inv_all] `wityping \<Gamma> w`
unfolding init_sim2_valid_wt_def
by (metis conc_stmt_wf_arch cwt_arch fst_conv nonneg_delay_conc_architecture snd_conv)
moreover have "wityping \<Gamma> (snd tw)"
using \<open>wityping \<Gamma> w\<close> init_sim2_preserves_wityping[OF `init_sim2 (0, w) architecture tw`]
by (simp add: conc_stmt_wf_arch nonneg_delay_conc_architecture)
ultimately have "Inv tw'"
using inv_all_preserved_arch 0 unfolding sim_hoare_valid_wt_def by blast
have "wityping \<Gamma> (snd tw')"
using world_sim_fin_preserves_wityping[OF 0]
using \<open>wityping \<Gamma> (snd tw)\<close> conc_stmt_wf_arch cwt_arch nonneg_delay_conc_architecture by blast
\<comment> \<open>CLK's behaviour is the same either for twk or (0, w)\<close>
have "CLK \<notin> set (signals_from architecture)"
unfolding architecture_def circuit_defs by auto
have "\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k"
using sim_fin2_unaffected[OF assms(1)]
using \<open>CLK \<notin> set (signals_from architecture)\<close> conc_stmt_wf_arch nonneg_delay_conc_architecture by auto
have "wline_of tw' OUTREADY_REG (fst tw') = Bv True"
using ready fst_world_sim_fin2_alt 0 world_sim_fin2_eq_world_sim_fin
by (metis world_maxtime_lt_fst_tres)
have posedge2: "is_posedge2 (snd tw') CLK (fst tw' - 1)"
using posedge fst_world_sim_fin2_alt 0 world_sim_fin2_eq_world_sim_fin
by (metis diff_add_inverse2 world_maxtime_lt_fst_tres)
have *: "\<And>n. fst tw < n \<Longrightarrow> n < i + 7 * clk_period + 1 \<Longrightarrow> Inv_core (n, snd tw')"
using Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
have "wline_of tw' RST (fst tw' - 1) = Bv False"
proof (rule ccontr)
assume "wline_of tw' RST (fst tw' - 1) \<noteq> Bv False"
have "wityping \<Gamma> (snd tw')"
using `wityping \<Gamma> (snd tw)` world_sim_fin_preserves_wityping[OF 0] conc_stmt_wf_arch cwt_arch nonneg_delay_conc_architecture by blast
hence "type_of (wline_of tw' RST (fst tw' - 1)) = Bty"
unfolding wityping_def wtyping_def using cosine_locale_axioms unfolding cosine_locale_def by auto
hence "wline_of tw' RST (fst tw' - 1) = Bv True"
using `wline_of tw' RST (fst tw' - 1) \<noteq> Bv False` type_of_bty_cases by blast
hence "wline_of tw' OUTREADY_REG (fst tw') = Bv False"
using `Inv tw'` `is_posedge2 (snd tw') CLK (fst tw' - 1)` unfolding inv_reg_alt_def
comp_def snd_conv fst_conv by simp
with ready show False
using \<open>wline_of tw' OUTREADY_REG (get_time tw') = Bv True\<close> by auto
qed
hence "wline_of tw' NEXT_OUTREADYREG (fst tw' - 1) = Bv True"
using `Inv tw'` posedge2 `wline_of tw' OUTREADY_REG (fst tw') = Bv True`
unfolding inv_reg_alt_def by auto
have "wline_of tw' STATE (fst tw' - 2) = V_POST"
proof -
have "fst tw < fst tw' - 1"
using world_maxtime_lt_fst_tres[OF 0] fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms
by (auto simp add: field_simps)
hence "Inv_core (fst tw' - 1, snd tw')"
using * world_maxtime_lt_fst_tres[OF 0] by simp
thus ?thesis
using \<open>wline_of tw' NEXT_OUTREADYREG (fst tw' - 1) = Bv True\<close>
unfolding inv_nout_alt_def comp_def snd_conv fst_conv
by (metis diff_diff_left one_add_one val.sel(1))
qed
have "wline_of tw' STATE (i + 7 * clk_period - 1) = V_POST"
using world_maxtime_lt_fst_tres[OF 0] `wline_of tw' STATE (fst tw' - 2) = V_POST`
`3 < clk_period` by (metis add_diff_cancel_right nat_1_add_1)
\<comment> \<open> obtaining accum\<close>
have "wline_of tw' ACCUM (fst tw') = wline_of tw' NEXT_ACCUM (fst tw' - 1)"
using `Inv tw'` posedge2 `wline_of tw' RST (fst tw' - 1) = Bv False`
unfolding inv_reg_alt_def comp_def snd_conv fst_conv by auto
also have "... = wline_of tw' NEXT_ACCUM (i + 7 * clk_period)"
using world_maxtime_lt_fst_tres[OF 0] `wline_of tw' STATE (fst tw' - 2) = V_POST`
`3 < clk_period` by (metis diff_add_inverse2)
finally have "wline_of tw' ACCUM (fst tw') = wline_of tw' NEXT_ACCUM (i + 7 * clk_period)"
by auto
have "bin_of ACCUM at_time fst tw' on tw' = sbintrunc 31 (bin_of FRAC at_time i + 7 * clk_period - 1 on tw' +
(sbl_to_bin (nths (lof_wline tw' TERM1 (i + 7 * clk_period - 1)) {1 .. 32})))"
proof -
have "Inv_core (i + 7 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
hence "bin_of NEXT_ACCUM at_time (i + 7 * clk_period) on tw' = sbintrunc 31 (bin_of FRAC at_time i + 7 * clk_period - 1 on tw' +
(sbl_to_bin (nths (lof_wline tw' TERM1 (i + 7 * clk_period - 1)) {1 .. 32})) )"
using `wline_of tw' STATE (i + 7 * clk_period - 1) = V_POST`
unfolding inv_naccum_alt_def comp_def snd_conv fst_conv by auto
thus ?thesis
using `wline_of tw' ACCUM (fst tw') = wline_of tw' NEXT_ACCUM (i + 7 * clk_period)` by auto
qed
hence "(word_of_int (bin_of ACCUM at_time fst tw' on tw') :: (1 + 31) word) = word_of_int (sbintrunc 31 (bin_of FRAC at_time i + 7 * clk_period - 1 on tw' + (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 7 * clk_period - 1)) {1 .. 32}))))"
by auto
also have "... = word_of_int (sbintrunc (LENGTH((1 + 31)) - 1) (bin_of FRAC at_time i + 7 * clk_period - 1 on tw' + (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 7 * clk_period - 1)) {1 .. 32}))))"
by auto
also have "... = word_of_int (bin_of FRAC at_time i + 7 * clk_period - 1 on tw' + (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 7 * clk_period - 1)) {1 .. 32})))"
unfolding word_sbin.Abs_norm by auto
also have "... = word_of_int (bin_of FRAC at_time i + 7 * clk_period - 1 on tw') + word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 7 * clk_period - 1)) {1 .. 32}))"
unfolding wi_hom_syms(1) by auto
finally have "(word_of_int (bin_of ACCUM at_time fst tw' on tw') :: (1 + 31) word) =
word_of_int (bin_of FRAC at_time i + 7 * clk_period - 1 on tw') + word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 7 * clk_period - 1)) {1 .. 32}))"
by auto
hence "Fixed (word_of_int (bin_of ACCUM at_time fst tw' on tw') :: (1 + 31) word) =
Fixed (word_of_int (bin_of FRAC at_time i + 7 * clk_period - 1 on tw')) + Fixed (word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 7 * clk_period - 1)) {1 .. 32})))"
unfolding plus_fixed.abs_eq by auto
have "Fixed (word_of_int (bin_of ACCUM at_time fst tw' on tw') :: (1 + 31) word) = fixed_of_sval (wline_of tw' ACCUM (fst tw'))"
(is "?lhs = ?rhs")
proof -
have "type_of (wline_of tw' ACCUM (fst tw')) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
hence "length (lval_of (wline_of tw' ACCUM (get_time tw'))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
hence "?lhs = Fixed (word_of_int (sbintrunc (LENGTH((1+31)) - 1) (bl_to_bin (lval_of (wline_of tw' ACCUM (get_time tw'))))))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (bl_to_bin (lval_of (wline_of tw' ACCUM (fst tw')))))"
unfolding word_sbin.Abs_norm by auto
also have "... = fixed_of_sval (wline_of tw' ACCUM (fst tw'))"
proof -
have "wline_of tw' ACCUM (fst tw') = Lv Sig (lval_of (wline_of tw' ACCUM (fst tw')))"
using `type_of (wline_of tw' ACCUM (fst tw')) = Lty Sig 32`
by (metis (no_types, hide_lams) ty.distinct(1) ty.inject type_of.cases type_of.simps(1) type_of.simps(2) val.sel(3))
thus ?thesis
using fixed_of_sval.simps unfolding of_bl_def by smt
qed
finally show ?thesis
by auto
qed
have "wline_of tw' STATE (i + 6 * clk_period + 1) = V_POST"
proof -
have a: "fst tw \<le> i + 6 * clk_period + 1"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] by auto
have b: "i + 6 * clk_period + 1 \<le> i + 7 * clk_period - 1"
using assms by (auto simp add: field_simps)
have c: "i + 7 * clk_period - 1 \<le> i + 7 * clk_period + 1"
by auto
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms
unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using \<open>\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0\<close> assms by blast
hence "(i + 6 * clk_period) mod clk_period = 0"
by auto
have d: "\<And>k. i + 6 * clk_period + 1 \<le> k \<Longrightarrow> k \<le> i + 7 * clk_period - 1 \<Longrightarrow> \<not> is_posedge2 (snd tw') CLK k"
proof -
fix n
obtain m1 where "i + 6 * clk_period = m1 * clk_period"
using `(i + 6 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 7 * clk_period = (m1 + 1) * clk_period"
proof -
obtain m2 where "i + 7 * clk_period = m2 * clk_period"
using `(i + 7 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 7 * clk_period - (i + 6 * clk_period) = clk_period"
by (auto simp add: field_simps)
hence "m2 * clk_period - m1 * clk_period = clk_period"
using `i + 6 * clk_period = m1 * clk_period` `i + 7 * clk_period = m2 * clk_period`
by auto
hence "(m2 - m1) * clk_period = clk_period"
by (auto simp add: algebra_simps)
hence "m2 = Suc m1"
using `3 < clk_period ` by auto
thus ?thesis
using Suc_eq_plus1 \<open>i + 7 * clk_period = m2 * clk_period\<close> by presburger
qed
assume "i + 6 * clk_period + 1 \<le> n" and "n \<le> i + 7 * clk_period - 1"
hence "m1 * clk_period < n"
using `i + 6 * clk_period = m1 * clk_period` by linarith
have "n mod clk_period \<noteq> 0"
proof -
have "n div clk_period = m1"
apply (rule Misc_Arithmetic.sdl)
using \<open>m1 * clk_period < n\<close> apply (simp add: mult.commute)
using `n \<le> i + 7 * clk_period - 1` `i + 7 * clk_period = (m1 + 1) * clk_period` assms
by (auto simp add: field_simps)
hence "n = m1 * clk_period + n mod clk_period"
by auto
moreover have "n mod clk_period < clk_period"
using assms by (auto intro!: mod_less_divisor)
ultimately show ?thesis
using \<open>m1 * clk_period < n\<close> by linarith
qed
hence "\<not> is_posedge2 w CLK n"
using \<open>\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0\<close> by auto
thus "\<not> is_posedge2 (snd tw') CLK n"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
qed
show ?thesis
using registers_unchanged_no_rising_edge[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)` a b c d]
`wline_of tw' STATE (i + 7 * clk_period - 1) = V_POST` by auto
qed
moreover have "Inv_core (i + 6 * clk_period + 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
moreover have "is_posedge2 (snd tw') CLK (i + 6 * clk_period)"
proof -
have "is_posedge2 w CLK (i + 7 * clk_period)"
using assms(8)
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
hence "is_posedge2 w CLK (i + 7 * clk_period - clk_period)"
using assms by auto
hence "is_posedge2 w CLK (i + 6 * clk_period)"
by (auto simp add:field_simps)
thus "is_posedge2 (snd tw') CLK (i + 6 * clk_period)"
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
qed
moreover have "wline_of tw' RST (i + 6 * clk_period) = Bv False"
proof (rule ccontr)
assume "wline_of tw' RST (i + 6 * clk_period) \<noteq> Bv False"
have "wityping \<Gamma> (snd tw')"
using `wityping \<Gamma> (snd tw)` world_sim_fin_preserves_wityping[OF 0] conc_stmt_wf_arch cwt_arch nonneg_delay_conc_architecture by blast
hence "type_of (wline_of tw' RST (i + 6 * clk_period)) = Bty"
unfolding wityping_def wtyping_def using cosine_locale_axioms unfolding cosine_locale_def by auto
hence "wline_of tw' RST (i + 6 * clk_period) = Bv True"
using `wline_of tw' RST (i + 6 * clk_period) \<noteq> Bv False` type_of_bty_cases by blast
hence "wline_of tw' STATE (i + 6 * clk_period + 1) = V_INIT"
using `Inv_core (i + 6 * clk_period + 1, snd tw')` `is_posedge2 (snd tw') CLK (i + 6 * clk_period)` unfolding inv_reg_alt_def
comp_def snd_conv fst_conv by auto
with `wline_of tw' STATE (i + 6 * clk_period + 1) = V_POST` show False
using \<open>wline_of tw' OUTREADY_REG (get_time tw') = Bv True\<close> by auto
qed
ultimately have "wline_of tw' NEXT_STATE (i + 6 * clk_period) = V_POST"
unfolding inv_reg_alt_def comp_def snd_conv fst_conv by auto
have " wline_of tw' STATE (i + 6 * clk_period - 1) = V_PROC \<and> \<not> bval_of (wline_of tw' CTR_NEQ_0 (i + 6 *clk_period - 1))"
proof (rule ccontr)
have "Inv_core (i + 6 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
hence inv:"inv_nstate (i + 6 * clk_period, snd tw')"
by auto
assume "\<not> (wline_of tw' STATE (i + 6 * clk_period - 1) = V_PROC \<and> \<not> bval_of (wline_of tw' CTR_NEQ_0 (i + 6 * clk_period - 1)))"
hence *: "(wline_of tw' STATE (i + 6 * clk_period - 1) = V_PROC \<Longrightarrow> bval_of (wline_of tw' CTR_NEQ_0 (i + 6 * clk_period - 1)))"
by auto
let ?state = "wline_of tw' STATE (i + 6 * clk_period - 1)"
consider "?state = V_INIT" | "?state = V_WAIT" | "?state = V_PROC" | "?state = V_POST"
| "?state \<noteq> V_INIT \<and> ?state \<noteq> V_WAIT \<and> ?state \<noteq> V_PRE \<and> ?state \<noteq> V_PROC \<and> ?state \<noteq> V_POST"
| "?state = V_PRE"
by auto
thus False
proof (cases)
case 1
hence "wline_of tw' NEXT_STATE (i + 6 * clk_period) \<noteq> V_POST"
using inv unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 6 * clk_period) = V_POST`
by auto
next
case 2
hence "wline_of tw' NEXT_STATE (i + 6 * clk_period) \<noteq> V_POST"
using inv unfolding inv_nstate_alt_def comp_def snd_conv fst_conv
by (cases "bval_of (snd (snd tw') INREADY (i + 6 * clk_period - 1))") auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 6 * clk_period) = V_POST`
by auto
next
case 3
hence "wline_of tw' NEXT_STATE (i + 6 * clk_period) \<noteq> V_POST"
using inv * unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 6 * clk_period) = V_POST`
by auto
next
case 4
hence "wline_of tw' NEXT_STATE (i + 6 * clk_period) \<noteq> V_POST"
using inv * unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 6 * clk_period) = V_POST`
by auto
next
case 5
hence "wline_of tw' NEXT_STATE (i + 6 * clk_period) \<noteq> V_POST"
using inv * unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 6 * clk_period) = V_POST`
by auto
next
case 6
hence "wline_of tw' NEXT_STATE (i + 6 * clk_period) \<noteq> V_POST"
using inv * unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 6 * clk_period) = V_POST`
by auto
qed
qed
have "ubin_of COUNTER at_time i + 6 * clk_period - 2 on tw' = 0"
proof -
have "Inv_core (i + 6 * clk_period - 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
hence "ubin_of COUNTER at_time i + 6 * clk_period - 2 on tw' \<le> 0"
using \<open>wline_of tw' STATE (i + 6 * clk_period - 1) = V_PROC \<and> \<not> bval_of (wline_of tw' CTR_NEQ_0 (i + 6 *clk_period - 1))\<close>
unfolding inv_n0_def comp_def snd_conv fst_conv by (smt diff_diff_left nat_1_add_1)
thus ?thesis
using bl_to_bin_ge0 antisym by blast
qed
have "ubin_of COUNTER at_time i + 6 * clk_period - 1 on tw' = 0"
proof -
have "Inv_core (i + 6 * clk_period - 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence **: "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using \<open>\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0\<close> assms by blast
hence "(i + 6 * clk_period) mod clk_period = 0"
by auto
have "(i + 6 * clk_period - 2) mod clk_period \<noteq> 0"
proof -
have "i + 5 * clk_period < i + 6 * clk_period - 2"
using assms by (auto)
moreover have "i + 6 * clk_period - 2 < i + 6 * clk_period"
using assms by auto
ultimately show ?thesis
by (metis \<open>(i + 6 * clk_period) mod clk_period = 0\<close> assms(3) assms(4) diff_add_0 diff_add_inverse
dvd_add_left_iff dvd_antisym less_imp_add_positive less_nat_zero_code mod_0_imp_dvd nat_diff_split_asm numeral_plus_numeral semiring_norm(5))
qed
hence "\<not> is_posedge2 (snd tw') CLK (i + 6 * clk_period - 2)"
using ** by auto
hence "ubin_of COUNTER at_time i + 6 * clk_period - 1 on tw' = ubin_of COUNTER at_time i + 6 * clk_period - 2 on tw'"
using `Inv_core (i + 6 * clk_period -1, snd tw')` unfolding inv_reg_alt_def comp_def snd_conv fst_conv using diff_diff_left nat_1_add_1 by presburger
thus ?thesis
using `ubin_of COUNTER at_time i + 6 * clk_period - 2 on tw' = 0` by auto
qed
have "bin_of FRAC at_time i + 7 * clk_period - 1 on tw' = bin_of FRAC at_time i + 6 * clk_period + 1 on tw'"
proof -
have a: "fst tw \<le> i + 6 * clk_period + 1"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] by auto
have b: "i + 6 * clk_period + 1 \<le> i + 7 * clk_period - 1"
using assms by (auto simp add: field_simps)
have c: "i + 7 * clk_period - 1 \<le> i + 7 * clk_period + 1"
by auto
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using \<open>\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0\<close> assms by blast
hence "(i + 6 * clk_period) mod clk_period = 0"
by auto
have d: "\<And>k. i + 6 * clk_period + 1 \<le> k \<Longrightarrow> k \<le> i + 7 * clk_period - 1 \<Longrightarrow> \<not> is_posedge2 (snd tw') CLK k"
proof -
fix n
obtain m1 where "i + 6 * clk_period = m1 * clk_period"
using `(i + 6 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 7 * clk_period = (m1 + 1) * clk_period"
proof -
obtain m2 where "i + 7 * clk_period = m2 * clk_period"
using `(i + 7 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 7 * clk_period - (i + 6 * clk_period) = clk_period"
by (auto simp add: field_simps)
hence "m2 * clk_period - m1 * clk_period = clk_period"
using `i + 6 * clk_period = m1 * clk_period` `i + 7 * clk_period = m2 * clk_period` by auto
hence "(m2 - m1) * clk_period = clk_period"
by (auto simp add: algebra_simps)
hence "m2 = Suc m1"
using `3 < clk_period ` by auto
thus ?thesis
using Suc_eq_plus1 \<open>i + 7 * clk_period = m2 * clk_period\<close> by presburger
qed
assume "i + 6 * clk_period + 1 \<le> n" and "n \<le> i + 7 * clk_period - 1"
hence "m1 * clk_period < n"
using `i + 6 * clk_period = m1 * clk_period` by linarith
have "n mod clk_period \<noteq> 0"
proof -
have "n div clk_period = m1"
apply (rule Misc_Arithmetic.sdl)
using \<open>m1 * clk_period < n\<close> apply (simp add: mult.commute)
using `n \<le> i + 7 * clk_period - 1` `i + 7 * clk_period = (m1 + 1) * clk_period` assms
by (auto simp add: field_simps)
hence "n = m1 * clk_period + n mod clk_period"
by auto
moreover have "n mod clk_period < clk_period"
using assms by (auto intro!: mod_less_divisor)
ultimately show ?thesis
using \<open>m1 * clk_period < n\<close> by linarith
qed
hence "\<not> is_posedge2 w CLK n"
using \<open>\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0\<close> by auto
thus "\<not> is_posedge2 (snd tw') CLK n"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
qed
show ?thesis
using registers_unchanged_no_rising_edge[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)` a b c d] by auto
qed
also have "... = bin_of NEXT_FRAC at_time i + 6 * clk_period on tw'"
using `Inv_core (i + 6 * clk_period + 1, snd tw')` `is_posedge2 (snd tw') CLK (i + 6 * clk_period)`
`wline_of tw' RST (i + 6 * clk_period) = Bv False` unfolding inv_reg_alt_def comp_def snd_conv fst_conv by auto
also have "... = approx_one"
proof -
have "Inv_core (i + 6 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
hence "inv_nfrac (i + 6 * clk_period, snd tw')"
by auto
thus ?thesis
using `ubin_of COUNTER at_time i + 6 * clk_period - 1 on tw' = 0`
unfolding inv_nfrac_alt_def comp_def snd_conv fst_conv by auto
qed
finally have "bin_of FRAC at_time i + 7 * clk_period - 1 on tw' = approx_one"
by auto
have "bin_of TERM1 at_time (i + 7 * clk_period - 1) on tw' = sbintrunc 63
(bin_of COMMON at_time (i + 7 * clk_period - 2) on tw' * bin_of ACCUM at_time (i + 7 * clk_period - 2) on tw')"
proof -
have "Inv_core (i + 7 * clk_period - 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
thus ?thesis
unfolding inv_term1_def comp_def snd_conv fst_conv by (metis diff_diff_left one_add_one)
qed
have "Fixed (word_of_int (bin_of FRAC at_time i + 7 * clk_period - 1 on tw')) = Fixed ((word_of_int approx_one) :: (1 + 31) word)"
using `bin_of FRAC at_time i + 7 * clk_period - 1 on tw' = approx_one` by auto
have "((word_of_int approx_one) :: (1 + 31) word) = (approx_one :: (1 + 31) word)"
unfolding word_uint.inverse_norm by eval
hence "Fixed ((word_of_int approx_one) :: (1 + 31) word) = Fixed (approx_one :: (1 + 31) word)"
by auto
also have "... = approx_div_fact 0"
by auto
finally have "Fixed (word_of_int (bin_of FRAC at_time i + 7 * clk_period - 1 on tw')) = approx_div_fact 0"
using `Fixed (word_of_int (bin_of FRAC at_time i + 7 * clk_period - 1 on tw')) = Fixed ((word_of_int approx_one) :: (1 + 31) word)`
by auto
moreover have "Fixed (word_of_int (bin_of FRAC at_time i + 7 * clk_period - 1 on tw')) = (fixed_of_sval (wline_of tw' FRAC (i + 7 * clk_period - 1)) :: (1,31) fixed)"
proof -
have "type_of (wline_of tw' FRAC (i + 7 * clk_period - 1)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
hence "length (lval_of (wline_of tw' FRAC (i + 7 * clk_period - 1))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
hence "Fixed (word_of_int (bin_of FRAC at_time i + 7 * clk_period - 1 on tw')) =
Fixed (word_of_int (sbintrunc (LENGTH((1+31)) - 1) (bl_to_bin (lval_of (wline_of tw' FRAC (i + 7 * clk_period - 1))))))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (bl_to_bin (lval_of (wline_of tw' FRAC (i + 7 * clk_period - 1)))) :: (1 + 31) word)"
unfolding word_sbin.Abs_norm by auto
also have "... = fixed_of_sval (wline_of tw' FRAC (i + 7 * clk_period - 1))"
proof -
have "wline_of tw' FRAC (i + 7 * clk_period - 1) = Lv Sig (lval_of (wline_of tw' FRAC (i + 7 * clk_period - 1)))"
using `type_of (wline_of tw' FRAC (i + 7 *clk_period - 1)) = Lty Sig 32`
by (metis (no_types, hide_lams) ty.distinct(1) ty.inject type_of.cases type_of.simps(1) type_of.simps(2) val.sel(3))
thus ?thesis
using fixed_of_sval.simps unfolding of_bl_def by smt
qed
finally show ?thesis
by auto
qed
ultimately have "(fixed_of_sval (wline_of tw' FRAC (i + 7 * clk_period - 1)) :: (1,31) fixed) = approx_div_fact 0"
by auto
have "(word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 7 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word) =
word_of_int (sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 7 * clk_period - 2)))) :: (1 + 31) word ) *
sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' ACCUM (i + 7 * clk_period - 2)))) :: (1 + 31) word) div 2 ^ 31)"
proof -
have "(word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 7 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word)=
word_of_int
(sbintrunc (length (nths (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1))) {1..32}) - 1) (bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1))) {1..32})))"
unfolding sbl_to_bin_alt_def by auto
moreover have "(length (nths (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1))) {1..32}) - 1) = 31"
proof -
have "type_of (wline_of tw' TERM1 (i + 7 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
have "card {1::nat ..32} = 32"
unfolding card_atLeastAtMost by auto
show ?thesis
unfolding length_nths *
using card_slice[where len="64" and l=62 and r="31"] by auto
qed
ultimately have "(word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 7 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word) =
word_of_int (sbintrunc 31 (bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1))) {1..32})))"
by auto
also have "... = word_of_int (sbintrunc (LENGTH(1+31) - 1) (bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1))) {1..32})))"
by auto
also have "... = (word_of_int (bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1))) {1..32})) :: (1 + 31) word) "
unfolding word_sbin.Abs_norm by auto
finally have "word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 7 * clk_period - 1)) {1 .. 32})) =
(word_of_int ( bl_to_bin (nths (lof_wline tw' TERM1 (i + 7 * clk_period - 1)) {1 .. 32})) :: (1+31) word)"
by auto
have interval: "{1 :: nat .. 32} = {1 :: nat ..< 33}"
by auto
have nths: "\<And>xs:: bool list. nths xs {1 :: nat .. 32} = drop 1 (take 33 xs)"
unfolding interval nths_from_upt_eq_drop_take[where m="1" and n="33"] by auto
have " bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1))) {1 ..32}) =
bl_to_bin (drop 1 (take 33 (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1)))))"
using nths[of "(lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1)))"] by auto
also have "... = bintrunc (length (take 33 (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1)))) - 1) (bl_to_bin (take 33 (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1)))))"
unfolding bl2bin_drop by auto
also have "... = bintrunc 32 (bl_to_bin (take 33 (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1)))))"
proof-
have "type_of (wline_of tw' TERM1 (i + 7 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
hence " length (take 33 (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1)))) = 33"
unfolding length_take by auto
thus ?thesis
by auto
qed
also have "... = bintrunc 32 (bl_to_bin (take (length (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1))) - 31) (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1)))))"
proof-
have "type_of (wline_of tw' TERM1 (i + 7 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
thus ?thesis
by auto
qed
also have "... = bintrunc 32 ((bin_rest ^^ 31) (bl_to_bin (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1)))))"
unfolding take_rest_bl2bin by auto
finally have "bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1))) {1 ..32}) =
bintrunc 32 ((bin_rest ^^ 31) (bl_to_bin (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1)))))"
by auto
have "(word_of_int (bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1))) {1 ..32})) :: (1+31) word)=
word_of_int (bintrunc 32 ((bin_rest ^^ 31) (bl_to_bin (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1))))))"
using \<open>bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1))) {1..32}) = bintrunc 32 ((bin_rest ^^ 31) (bl_to_bin (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1)))))\<close> by auto
\<comment> \<open>push bintrunc 32 inside\<close>
also have "... = word_of_int ((bin_rest ^^ 31) (bintrunc 63 (bl_to_bin (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1))))))"
using bin_rest_power_trunc[where n="63" and k="31", symmetric] by auto
also have "... = word_of_int ((bin_rest ^^ 31) (bl_to_bin (drop 1 (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1))))))"
proof -
have "type_of (wline_of tw' TERM1 (i + 7 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
thus ?thesis
using bl2bin_drop by auto
qed
\<comment> \<open>pull bl_to_bin to left\<close>
also have "... = word_of_int (bl_to_bin ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1))))))"
unfolding butlast_pow_rest_bl2bin[symmetric] by auto
\<comment> \<open>change to sbl_to_bin\<close>
also have "... = (word_of_int (sbintrunc (LENGTH(1+31) - 1) (bl_to_bin ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1))))))) :: (1 + 31) word)"
unfolding word_sbin.Abs_norm by auto
also have "... = word_of_int (sbl_to_bin ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1))))))"
proof -
have "type_of (wline_of tw' TERM1 (i + 7 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
have "length ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1))))) = 32"
unfolding butlast_power length_take length_drop * by eval
hence "(word_of_int (sbintrunc (LENGTH(1+31) - 1) (bl_to_bin ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1))))))) :: (1 + 31) word) =
(word_of_int (sbintrunc (length ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1))))) - 1) (bl_to_bin ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1))))))) :: (1 + 31) word)"
by auto
thus ?thesis
using sbl_to_bin_alt_def by auto
qed
\<comment> \<open>push sbl_to_bin back to right\<close>
also have "... = word_of_int ((bin_rest ^^ 31) (sbl_to_bin (drop 1 (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1))))))"
proof -
have "type_of (wline_of tw' TERM1 (i + 7 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
have "length ((drop 1 (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1))))) = 63"
unfolding length_take length_drop * by eval
hence **: "31 < length ((drop 1 (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1)))))"
by auto
show ?thesis
unfolding butlast_pow_rest_sbl2bin[OF **] by auto
qed
also have "... = word_of_int ((bin_rest ^^ 31) (sbintrunc 62 (sbl_to_bin (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1))))))"
proof -
have "type_of (wline_of tw' TERM1 (i + 7 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 7 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
thus ?thesis
using sbl2bin_drop by auto
qed
also have "... = word_of_int ((bin_rest ^^ 31) (sbintrunc 62 (bin_of COMMON at_time (i + 7 * clk_period - 2) on tw' * bin_of ACCUM at_time (i + 7 * clk_period - 2) on tw')))"
using `bin_of TERM1 at_time (i + 7 * clk_period - 1) on tw' = sbintrunc 63 (bin_of COMMON at_time (i + 7 * clk_period - 2) on tw' * bin_of ACCUM at_time (i + 7 * clk_period - 2) on tw')`
by auto
also have "... = word_of_int (sbintrunc 31 ((bin_rest ^^ 31) (bin_of COMMON at_time (i + 7 * clk_period - 2) on tw' * bin_of ACCUM at_time (i + 7 * clk_period - 2) on tw')))"
proof -
have "(31 :: nat) \<le> 62" by auto
show ?thesis
unfolding bin_rest_power_strunc[OF `31 \<le> 62`]
by auto
qed
also have "... = word_of_int (sbintrunc (LENGTH(1 + 31) - 1) ((bin_rest ^^ 31) (bin_of COMMON at_time (i + 7 * clk_period - 2) on tw' * bin_of ACCUM at_time (i + 7 * clk_period - 2) on tw')))"
by auto
also have "... = word_of_int ((bin_rest ^^ 31) (bin_of COMMON at_time (i + 7 * clk_period - 2) on tw' * bin_of ACCUM at_time (i + 7 * clk_period - 2) on tw'))"
unfolding word_sbin.Abs_norm by auto
also have "... = word_of_int ((bin_of COMMON at_time (i + 7 * clk_period - 2) on tw' * bin_of ACCUM at_time (i + 7 * clk_period - 2) on tw') div 2 ^ 31)"
unfolding bin_rest_compow by auto
also have "... = word_of_int (sbintrunc (length (lval_of (wline_of tw' COMMON (i + 7 * clk_period - 2))) - 1) (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 7 * clk_period - 2)))) *
sbintrunc (length (lval_of (wline_of tw' ACCUM (i + 7 * clk_period - 2))) - 1) (sbl_to_bin (lval_of (wline_of tw' ACCUM (i + 7 * clk_period - 2)))) div 2 ^ 31)"
using sbl_to_bin_alt_def2 by auto
also have "... = word_of_int (sbintrunc (LENGTH(1 + 31) - 1) (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 7 * clk_period - 2)))) *
sbintrunc (LENGTH(1 + 31) - 1) (sbl_to_bin (lval_of (wline_of tw' ACCUM (i + 7 * clk_period - 2)))) div 2 ^ 31)"
proof -
have "type_of (wline_of tw' COMMON (i + 7 * clk_period - 2)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' COMMON (i + 7 * clk_period - 2))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
have "type_of (wline_of tw' ACCUM (i + 7 * clk_period - 2)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence **: "length (lval_of (wline_of tw' ACCUM (i + 7 * clk_period - 2))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
with * show ?thesis
by auto
qed
also have "... = word_of_int (sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 7 * clk_period - 2)))) :: (1 + 31) word) *
sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' ACCUM (i + 7 * clk_period - 2)))) :: (1 + 31) word ) div 2 ^ 31)"
unfolding sint_sbintrunc' by auto
finally show ?thesis
unfolding `(word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 7 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word) =
(word_of_int ( bl_to_bin (nths (lof_wline tw' TERM1 (i + 7 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word)`
by auto
qed
hence "Fixed (word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 7 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word) =
Fixed (word_of_int (sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 7 * clk_period - 2)))) :: (1 + 31) word ) *
sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' ACCUM (i + 7 * clk_period - 2)))) :: (1 + 31) word) div 2 ^ 31))"
by auto
also have "... = Fixed (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 7 * clk_period - 2))))) * Fixed (word_of_int (sbl_to_bin (lval_of (wline_of tw' ACCUM (i + 7 * clk_period - 2)))))"
using times_fixed.abs_eq[where xa="word_of_int (bin_of COMMON at_time i + 7 * clk_period - 2 on tw') :: (1 + 31) word" and
x="word_of_int (bin_of ACCUM at_time i + 7 * clk_period - 2 on tw') :: (1 + 31) word", symmetric]
by auto
also have "... = fixed_of_sval (wline_of tw' COMMON (i + 7 * clk_period - 2)) * fixed_of_sval (wline_of tw' ACCUM (i + 7 * clk_period - 2))"
proof -
have "type_of (wline_of tw' COMMON (i + 7 * clk_period - 2)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
hence "length (lval_of (wline_of tw' COMMON (i + 7 * clk_period - 2))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
hence "Fixed (word_of_int (bin_of COMMON at_time i + 7 * clk_period - 2 on tw')) =
Fixed (word_of_int (sbintrunc (LENGTH((1+31)) - 1) (bl_to_bin (lval_of (wline_of tw' COMMON (i + 7 * clk_period - 2))))))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (bl_to_bin (lval_of (wline_of tw' COMMON (i + 7 * clk_period - 2)))) :: (1 + 31) word)"
unfolding word_sbin.Abs_norm by auto
also have "... = fixed_of_sval (wline_of tw' COMMON (i + 7 * clk_period - 2))"
proof -
have "wline_of tw' COMMON (i + 7 * clk_period - 2) = Lv Sig (lval_of (wline_of tw' COMMON (i + 7 * clk_period - 2)))"
using `type_of (wline_of tw' COMMON (i + 7 *clk_period - 2)) = Lty Sig 32`
by (metis (no_types, hide_lams) ty.distinct(1) ty.inject type_of.cases type_of.simps(1) type_of.simps(2) val.sel(3))
thus ?thesis
using fixed_of_sval.simps unfolding of_bl_def by smt
qed
finally have "Fixed (word_of_int (bin_of COMMON at_time i + 7 * clk_period - 2 on tw') :: (1 + 31) word) = fixed_of_sval (wline_of tw' COMMON (i + 7 * clk_period - 2))"
by auto
have "type_of (wline_of tw' ACCUM (i + 7 * clk_period - 2)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
hence "length (lval_of (wline_of tw' ACCUM (i + 7 * clk_period - 2))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
hence "Fixed (word_of_int (bin_of ACCUM at_time i + 7 * clk_period - 2 on tw')) =
Fixed (word_of_int (sbintrunc (LENGTH((1+31)) - 1) (bl_to_bin (lval_of (wline_of tw' ACCUM (i + 7 * clk_period - 2))))))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (bl_to_bin (lval_of (wline_of tw' ACCUM (i + 7 * clk_period - 2)))) :: (1 + 31) word)"
unfolding word_sbin.Abs_norm by auto
also have "... = fixed_of_sval (wline_of tw' ACCUM (i + 7 * clk_period - 2))"
proof -
have "wline_of tw' ACCUM (i + 7 * clk_period - 2) = Lv Sig (lval_of (wline_of tw' ACCUM (i + 7 * clk_period - 2)))"
using `type_of (wline_of tw' ACCUM (i + 7 *clk_period - 2)) = Lty Sig 32`
by (metis (no_types, hide_lams) ty.distinct(1) ty.inject type_of.cases type_of.simps(1) type_of.simps(2) val.sel(3))
thus ?thesis
using fixed_of_sval.simps unfolding of_bl_def by smt
qed
finally have "Fixed (word_of_int (bin_of ACCUM at_time i + 7 * clk_period - 2 on tw') :: (1 + 31) word) = fixed_of_sval (wline_of tw' ACCUM (i + 7 * clk_period - 2))"
by auto
thus ?thesis
using \<open>Fixed (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 7 * clk_period - 2))))) = fixed_of_sval (wline_of tw' COMMON (i + 7 * clk_period - 2))\<close> by auto
qed
finally have "Fixed (word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 7 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word) =
fixed_of_sval (wline_of tw' COMMON (i + 7 * clk_period - 2)) * fixed_of_sval (wline_of tw' ACCUM (i + 7 * clk_period - 2))"
by auto
hence "fixed_of_sval (wline_of tw' ACCUM (fst tw')) = approx_div_fact 0 + fixed_of_sval (wline_of tw' COMMON (i + 7 * clk_period - 2)) * fixed_of_sval (wline_of tw' ACCUM (i + 7 * clk_period - 2))"
using `?lhs = ?rhs`
`Fixed (word_of_int (bin_of ACCUM at_time fst tw' on tw') :: (1 + 31) word) =
Fixed (word_of_int (bin_of FRAC at_time i + 7 * clk_period - 1 on tw')) + Fixed (word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 7 * clk_period - 1)) {1 .. 32})))`
`Fixed (word_of_int (bin_of FRAC at_time i + 7 * clk_period - 1 on tw')) = approx_div_fact 0`
by auto
\<comment> \<open> obtaining common and accum\<close>
have "wline_of tw' COMMON (i + 6 * clk_period + 1) = wline_of tw' COMMON (i + 7 * clk_period - 2)"
and "wline_of tw' ACCUM (i + 6 * clk_period + 1) = wline_of tw' ACCUM (i + 7 * clk_period - 2)"
proof -
have a: "fst tw \<le> i + 6 * clk_period + 1"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] by auto
have b: "i + 6 * clk_period + 1 \<le> i + 7 * clk_period - 2"
using assms by (auto simp add: field_simps)
have c: "i + 7 * clk_period - 2 \<le> i + 7 * clk_period + 1"
by auto
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms
unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using \<open>\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0\<close> assms by blast
hence "(i + 6 * clk_period) mod clk_period = 0"
by auto
have d: "\<And>k. i + 6 * clk_period + 1 \<le> k \<Longrightarrow> k \<le> i + 7 * clk_period - 1 \<Longrightarrow> \<not> is_posedge2 (snd tw') CLK k"
proof -
fix n
obtain m1 where "i + 6 * clk_period = m1 * clk_period"
using `(i + 6 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 7 * clk_period = (m1 + 1) * clk_period"
proof -
obtain m2 where "i + 7 * clk_period = m2 * clk_period"
using `(i + 7 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 7 * clk_period - (i + 6 * clk_period) = clk_period"
by (auto simp add: field_simps)
hence "m2 * clk_period - m1 * clk_period = clk_period"
using `i + 6 * clk_period = m1 * clk_period` `i + 7 * clk_period = m2 * clk_period`
by auto
hence "(m2 - m1) * clk_period = clk_period"
by (auto simp add: algebra_simps)
hence "m2 = Suc m1"
using `3 < clk_period ` by auto
thus ?thesis
using Suc_eq_plus1 \<open>i + 7 * clk_period = m2 * clk_period\<close> by presburger
qed
assume "i + 6 * clk_period + 1 \<le> n" and "n \<le> i + 7 * clk_period - 1"
hence "m1 * clk_period < n"
using `i + 6 * clk_period = m1 * clk_period` by linarith
have "n mod clk_period \<noteq> 0"
proof -
have "n div clk_period = m1"
apply (rule Misc_Arithmetic.sdl)
using \<open>m1 * clk_period < n\<close> apply (simp add: mult.commute)
using `n \<le> i + 7 * clk_period - 1` `i + 7 * clk_period = (m1 + 1) * clk_period` assms
by (auto simp add: field_simps)
hence "n = m1 * clk_period + n mod clk_period"
by auto
moreover have "n mod clk_period < clk_period"
using assms by (auto intro!: mod_less_divisor)
ultimately show ?thesis
using \<open>m1 * clk_period < n\<close> by linarith
qed
hence "\<not> is_posedge2 w CLK n"
using \<open>\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0\<close> by auto
thus "\<not> is_posedge2 (snd tw') CLK n"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
qed
show "wline_of tw' COMMON (i + 6 * clk_period + 1) = wline_of tw' COMMON (i + 7 * clk_period - 2)"
and "wline_of tw' ACCUM (i + 6 * clk_period + 1) = wline_of tw' ACCUM (i + 7 * clk_period - 2)"
using registers_unchanged_no_rising_edge[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)` a b c d]
by auto
qed
have "wline_of tw' NEXT_COMMON (i + 6 * clk_period) = wline_of tw' COMMON (i + 6 * clk_period + 1)"
and "wline_of tw' NEXT_ACCUM (i + 6 * clk_period) = wline_of tw' ACCUM (i + 6* clk_period + 1)"
using `Inv_core (i + 6 * clk_period + 1, snd tw')` `is_posedge2 (snd tw') CLK (i + 6 * clk_period)` `wline_of tw' RST (i + 6 * clk_period) = Bv False`
unfolding inv_reg_alt_def comp_def snd_conv fst_conv by auto
have "bin_of COMMON at_time (i + 6 * clk_period - 1) on tw' = bin_of NEXT_COMMON at_time (i + 6 * clk_period) on tw'"
proof -
have "Inv_core (i + 6 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
thus ?thesis
using `wline_of tw' STATE (i + 6 * clk_period - 1) = V_PROC \<and> \<not> bval_of (wline_of tw' CTR_NEQ_0 (i + 6 *clk_period - 1))`
unfolding inv_ncommon_alt_def comp_def snd_conv fst_conv by auto
qed
have "(fixed_of_sval (wline_of tw' COMMON (i + 7 * clk_period - 2)) :: (1,31) fixed) = fixed_of_sval (wline_of tw' COMMON (i + 6 * clk_period - 1))"
proof -
have typof2: "type_of (wline_of tw' COMMON (i + 6 * clk_period - 1)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
then obtain bs2 where " wline_of tw' COMMON (i + 6 * clk_period - 1) = Lv Sig bs2 \<and> length bs2 = 32"
using type_of.elims[OF typof2] by fastforce
have typof: "type_of (wline_of tw' COMMON (i + 7 * clk_period - 2)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
then obtain bs1 where " wline_of tw' COMMON (i + 7 * clk_period - 2) = Lv Sig bs1 \<and> length bs1 = 32"
using type_of.elims[OF typof] by fastforce
hence "fixed_of_sval (wline_of tw' COMMON (i + 7 * clk_period - 2)) = Fixed (of_bl bs1 :: (1 + 31) word)"
using fixed_of_sval.simps by auto
also have "... = Fixed (word_of_int (bl_to_bin bs1) :: (1 + 31) word)"
unfolding of_bl_def by auto
also have "... = Fixed (word_of_int (sbintrunc (LENGTH(1+31) - 1) (bl_to_bin bs1)))"
unfolding word_sbin.Abs_norm[symmetric, where x="bl_to_bin bs1"] by auto
also have "... = Fixed (word_of_int (sbintrunc (length bs1 - 1) (bl_to_bin bs1)))"
using `wline_of tw' COMMON (i + 7 * clk_period - 2) = Lv Sig bs1 \<and> length bs1 = 32` by auto
also have "... = Fixed (word_of_int (sbl_to_bin bs1))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (sbl_to_bin bs2))"
using `bin_of COMMON at_time (i + 6 * clk_period - 1) on tw' = bin_of NEXT_COMMON at_time (i + 6 * clk_period) on tw'`
`wline_of tw' COMMON (i + 6 * clk_period - 1) = Lv Sig bs2 \<and> length bs2 = 32`
`wline_of tw' COMMON (i + 7 * clk_period - 2) = Lv Sig bs1 \<and> length bs1 = 32`
using \<open>wline_of tw' COMMON (i + 6 * clk_period + 1) = wline_of tw' COMMON (i + 7 * clk_period - 2)\<close> \<open>wline_of tw' NEXT_COMMON (i + 6 * clk_period) = wline_of tw' COMMON (i + 6 * clk_period + 1)\<close> by auto
also have "... = Fixed (word_of_int (sbintrunc (length bs2- 1) (bl_to_bin bs2)))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (sbintrunc (LENGTH(1+31) - 1) (bl_to_bin bs2)))"
using `wline_of tw' COMMON (i + 6 * clk_period - 1) = Lv Sig bs2 \<and> length bs2 = 32` by auto
also have "... = Fixed (word_of_int (bl_to_bin bs2) :: (1 + 31) word)"
unfolding word_sbin.Abs_norm[symmetric, where x="bl_to_bin bs2"] by auto
also have "... = Fixed (of_bl bs2 :: (1 + 31) word)"
unfolding of_bl_def by auto
also have "... = fixed_of_sval (wline_of tw' COMMON (i + 6 * clk_period - 1))"
using `wline_of tw' COMMON (i + 6 * clk_period - 1) = Lv Sig bs2 \<and> length bs2 = 32`
using fixed_of_sval.simps by auto
finally show ?thesis
by auto
qed
have "wline_of tw' COMMON (i + 6 * clk_period - 2) = wline_of tw' COMMON (i + 6 * clk_period - 1)"
proof -
have "Inv_core (i + 6 * clk_period - 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms
unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence **: "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using posedge by blast
hence "(i + 6 * clk_period) mod clk_period = 0"
by auto
have "(i + 6 * clk_period - 2) mod clk_period \<noteq> 0"
proof -
have "i + 5 * clk_period < i + 6 * clk_period - 2"
using assms by (auto)
moreover have "i + 6 * clk_period - 2 < i + 6 * clk_period"
using assms by auto
ultimately show ?thesis
by (metis \<open>(i + 6 * clk_period) mod clk_period = 0\<close> assms(3) assms(4) diff_add_0 diff_add_inverse
dvd_add_left_iff dvd_antisym less_imp_add_positive less_nat_zero_code mod_0_imp_dvd nat_diff_split_asm numeral_plus_numeral semiring_norm(5))
qed
hence "\<not> is_posedge2 (snd tw') CLK (i + 6 * clk_period - 2)"
using ** by auto
thus ?thesis
using `Inv_core (i + 6 * clk_period - 1, snd tw')` unfolding inv_reg_alt_def comp_def snd_conv fst_conv
using diff_diff_left nat_1_add_1 by presburger
qed
\<comment> \<open> obtaining state\<close>
have "wline_of tw' STATE (i + 5 * clk_period + 1) = wline_of tw' STATE (i + 6 * clk_period - 1)"
proof -
have a: "fst tw \<le> i + 5 * clk_period + 1"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] by auto
have b: "i + 5 * clk_period + 1 \<le> i + 6 * clk_period - 1"
using assms by (auto simp add: field_simps)
have c: "i + 6 * clk_period - 1 \<le> i + 7 * clk_period + 1"
by auto
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms
unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using \<open>\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0\<close> assms by blast
hence "(i + 6 * clk_period) mod clk_period = 0"
by auto
hence "(i + 5 * clk_period) mod clk_period = 0"
by auto
have d: "\<And>k. i + 5 * clk_period + 1 \<le> k \<Longrightarrow> k \<le> i + 6 * clk_period - 1 \<Longrightarrow> \<not> is_posedge2 (snd tw') CLK k"
proof -
fix n
obtain m1 where "i + 5 * clk_period = m1 * clk_period"
using `(i + 5 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 6 * clk_period = (m1 + 1) * clk_period"
proof -
obtain m2 where "i + 6 * clk_period = m2 * clk_period"
using `(i + 6 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 6 * clk_period - (i + 5 * clk_period) = clk_period"
by (auto simp add: field_simps)
hence "m2 * clk_period - m1 * clk_period = clk_period"
using `i + 5 * clk_period = m1 * clk_period` `i + 6 * clk_period = m2 * clk_period`
by auto
hence "(m2 - m1) * clk_period = clk_period"
by (auto simp add: algebra_simps)
hence "m2 = Suc m1"
using `3 < clk_period ` by auto
thus ?thesis
using Suc_eq_plus1 \<open>i + 6 * clk_period = m2 * clk_period\<close> by presburger
qed
assume "i + 5 * clk_period + 1 \<le> n" and "n \<le> i + 6 * clk_period - 1"
hence "m1 * clk_period < n"
using `i + 5 * clk_period = m1 * clk_period` by linarith
have "n mod clk_period \<noteq> 0"
proof -
have "n div clk_period = m1"
apply (rule Misc_Arithmetic.sdl)
using \<open>m1 * clk_period < n\<close> apply (simp add: mult.commute)
using `n \<le> i + 6 * clk_period - 1` `i + 6 * clk_period = (m1 + 1) * clk_period` assms
by (auto simp add: field_simps)
hence "n = m1 * clk_period + n mod clk_period"
by auto
moreover have "n mod clk_period < clk_period"
using assms by (auto intro!: mod_less_divisor)
ultimately show ?thesis
using \<open>m1 * clk_period < n\<close> by linarith
qed
hence "\<not> is_posedge2 w CLK n"
using \<open>\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0\<close> by auto
thus "\<not> is_posedge2 (snd tw') CLK n"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
qed
show "wline_of tw' STATE (i + 5 * clk_period + 1) = wline_of tw' STATE (i + 6 * clk_period - 1)"
using registers_unchanged_no_rising_edge[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)` a b c d]
by auto
qed
hence "wline_of tw' STATE (i + 5 * clk_period + 1) = V_PROC"
using `wline_of tw' STATE (i + 6 * clk_period - 1) = V_PROC \<and> \<not> bval_of (wline_of tw' CTR_NEQ_0 (i + 6 *clk_period - 1))`
by auto
have "wline_of tw' FRAC (i + 5 * clk_period + 1) = wline_of tw' FRAC (i + 6 * clk_period - 1)"
and "wline_of tw' COUNTER (i + 5 * clk_period + 1) = wline_of tw' COUNTER (i + 6 * clk_period - 1)"
proof -
have a: "fst tw \<le> i + 5 * clk_period + 1"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] by auto
have b: "i + 5 * clk_period + 1 \<le> i + 6 * clk_period - 1"
using assms by (auto simp add: field_simps)
have c: "i + 6 * clk_period - 1 \<le> i + 7 * clk_period + 1"
by auto
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using \<open>\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0\<close> assms by blast
hence "(i + 6 * clk_period) mod clk_period = 0"
by auto
hence "(i + 5 * clk_period) mod clk_period = 0"
by auto
have d: "\<And>k. i + 5 * clk_period + 1 \<le> k \<Longrightarrow> k \<le> i + 6 * clk_period - 1 \<Longrightarrow> \<not> is_posedge2 (snd tw') CLK k"
proof -
fix n
obtain m1 where "i + 5 * clk_period = m1 * clk_period"
using `(i + 5 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 6 * clk_period = (m1 + 1) * clk_period"
proof -
obtain m2 where "i + 6 * clk_period = m2 * clk_period"
using `(i + 6 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 6 * clk_period - (i + 5 * clk_period) = clk_period"
by (auto simp add: field_simps)
hence "m2 * clk_period - m1 * clk_period = clk_period"
using `i + 5 * clk_period = m1 * clk_period` `i + 6 * clk_period = m2 * clk_period` by auto
hence "(m2 - m1) * clk_period = clk_period"
by (auto simp add: algebra_simps)
hence "m2 = Suc m1"
using `3 < clk_period ` by auto
thus ?thesis
using Suc_eq_plus1 \<open>i + 6 * clk_period = m2 * clk_period\<close> by presburger
qed
assume "i + 5 * clk_period + 1 \<le> n" and "n \<le> i + 6 * clk_period - 1"
hence "m1 * clk_period < n"
using `i + 5 * clk_period = m1 * clk_period` by linarith
have "n mod clk_period \<noteq> 0"
proof -
have "n div clk_period = m1"
apply (rule Misc_Arithmetic.sdl)
using \<open>m1 * clk_period < n\<close> apply (simp add: mult.commute)
using `n \<le> i + 6 * clk_period - 1` `i + 6 * clk_period = (m1 + 1) * clk_period` assms
by (auto simp add: field_simps)
hence "n = m1 * clk_period + n mod clk_period"
by auto
moreover have "n mod clk_period < clk_period"
using assms by (auto intro!: mod_less_divisor)
ultimately show ?thesis
using \<open>m1 * clk_period < n\<close> by linarith
qed
hence "\<not> is_posedge2 w CLK n"
using \<open>\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0\<close> by auto
thus "\<not> is_posedge2 (snd tw') CLK n"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
qed
show "wline_of tw' FRAC (i + 5 * clk_period + 1) = wline_of tw' FRAC (i + 6 * clk_period - 1)"
and "wline_of tw' COUNTER (i + 5 * clk_period + 1) = wline_of tw' COUNTER (i + 6 * clk_period - 1)"
using registers_unchanged_no_rising_edge[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)` a b c d] by auto
qed
have "wline_of tw' NEXT_FRAC (i + 5 * clk_period) = wline_of tw' FRAC (i + 5 * clk_period + 1)"
and "wline_of tw' NEXT_STATE (i + 5 * clk_period) = wline_of tw' STATE (i + 5 * clk_period + 1)"
and "wline_of tw' NEXT_COUNTER (i + 5 * clk_period) = wline_of tw' COUNTER (i + 5 * clk_period + 1)"
proof -
have "Inv_core (i + 5 * clk_period + 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
moreover have "is_posedge2 (snd tw') CLK (i + 5 * clk_period)"
proof -
have "is_posedge2 w CLK (i + 6 * clk_period)"
using `is_posedge2 (snd tw') CLK (i + 6 * clk_period)`
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
hence "is_posedge2 w CLK (i + 6 * clk_period - clk_period)"
using assms by auto
hence "is_posedge2 w CLK (i + 5 * clk_period)"
by (auto simp add:field_simps)
thus "is_posedge2 (snd tw') CLK (i + 5 * clk_period)"
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
qed
moreover have "wline_of tw' RST (i + 5 * clk_period) = Bv False"
proof (rule ccontr)
assume "wline_of tw' RST (i + 5 * clk_period) \<noteq> Bv False"
have "wityping \<Gamma> (snd tw')"
using `wityping \<Gamma> (snd tw)` world_sim_fin_preserves_wityping[OF 0] conc_stmt_wf_arch cwt_arch nonneg_delay_conc_architecture by blast
hence "type_of (wline_of tw' RST (i + 5 * clk_period)) = Bty"
unfolding wityping_def wtyping_def using cosine_locale_axioms unfolding cosine_locale_def by auto
hence "wline_of tw' RST (i + 5 * clk_period) = Bv True"
using `wline_of tw' RST (i + 5 * clk_period) \<noteq> Bv False` type_of_bty_cases by blast
hence "wline_of tw' STATE (i + 5 * clk_period + 1) = V_INIT"
using `Inv_core (i + 5 * clk_period + 1, snd tw')` `is_posedge2 (snd tw') CLK (i + 5 * clk_period)` unfolding inv_reg_alt_def
comp_def snd_conv fst_conv by auto
with `wline_of tw' STATE (i + 5 * clk_period + 1) = V_PROC` show False
using \<open>wline_of tw' OUTREADY_REG (get_time tw') = Bv True\<close> by auto
qed
ultimately show "wline_of tw' NEXT_FRAC (i + 5 * clk_period) = wline_of tw' FRAC (i + 5 * clk_period + 1)"
and "wline_of tw' NEXT_STATE (i + 5 * clk_period) = wline_of tw' STATE (i + 5 * clk_period + 1)"
and "wline_of tw' NEXT_COUNTER (i + 5 * clk_period) = wline_of tw' COUNTER (i + 5 * clk_period + 1)"
unfolding inv_reg_alt_def comp_def snd_conv fst_conv by auto
qed
hence "wline_of tw' NEXT_STATE (i + 5 * clk_period) = V_PROC" and "ubin_of NEXT_COUNTER at_time i + 5 * clk_period on tw' = 0"
using `wline_of tw' STATE (i + 5 * clk_period + 1) = V_PROC` `ubin_of COUNTER at_time i + 6 * clk_period - 1 on tw' = 0`
using \<open>bl_to_bin (lval_of (wline_of tw' COUNTER (i + 6 * clk_period - 1))) = 0\<close> \<open>wline_of tw' COUNTER (i + 5 * clk_period + 1) = wline_of tw' COUNTER (i + 6 * clk_period - 1)\<close> \<open>wline_of tw' NEXT_COUNTER (i + 5 * clk_period) = wline_of tw' COUNTER (i + 5 * clk_period + 1)\<close>
by auto
have "wline_of tw' STATE (i + 5 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 5 * clk_period - 1))
\<or> wline_of tw' STATE (i + 5 * clk_period - 1) = V_PRE"
proof (rule ccontr)
have "Inv_core (i + 5 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
hence inv:"inv_nstate (i + 5 * clk_period, snd tw')"
by auto
assume "\<not> (wline_of tw' STATE (i + 5 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 5 * clk_period - 1))
\<or> wline_of tw' STATE (i + 5 * clk_period - 1) = V_PRE)"
hence *: "(wline_of tw' STATE (i + 5 * clk_period - 1) = V_PROC \<Longrightarrow> \<not> bval_of (wline_of tw' CTR_NEQ_0 (i + 5 * clk_period - 1)))" and
**: "wline_of tw' STATE (i + 5 * clk_period - 1) \<noteq> V_PRE" (is "?state \<noteq> _")by auto
then consider "?state = V_INIT" | "?state = V_WAIT" | "?state = V_PROC" | "?state = V_POST"
| "?state \<noteq> V_INIT \<and> ?state \<noteq> V_WAIT \<and> ?state \<noteq> V_PRE \<and> ?state \<noteq> V_PROC \<and> ?state \<noteq> V_POST"
by auto
thus False
proof (cases)
case 1
hence "wline_of tw' NEXT_STATE (i + 5 * clk_period) \<noteq> V_PROC"
using inv unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 5 * clk_period) = V_PROC`
by auto
next
case 2
hence "wline_of tw' NEXT_STATE (i + 5 * clk_period) \<noteq> V_PROC"
using inv unfolding inv_nstate_alt_def comp_def snd_conv fst_conv
by (cases "bval_of (snd (snd tw') INREADY (i + 5 * clk_period - 1))") auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 5 * clk_period) = V_PROC`
by auto
next
case 3
hence "wline_of tw' NEXT_STATE (i + 5 * clk_period) \<noteq> V_PROC"
using inv * unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 5 * clk_period) = V_PROC`
by auto
next
case 4
hence "wline_of tw' NEXT_STATE (i + 5 * clk_period) \<noteq> V_PROC"
using inv * unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 5 * clk_period) = V_PROC`
by auto
next
case 5
hence "wline_of tw' NEXT_STATE (i + 5 * clk_period) \<noteq> V_PROC"
using inv * unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 5 * clk_period) = V_PROC`
by auto
qed
qed
moreover have "wline_of tw' STATE (i + 5 * clk_period - 1) \<noteq> V_PRE"
proof (rule ccontr)
assume "\<not> wline_of tw' STATE (i + 5 * clk_period - 1) \<noteq> V_PRE"
hence "wline_of tw' STATE (i + 5 * clk_period - 1) = V_PRE"
by auto
have "Inv_core (i + 5 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
hence "bintrunc 3 (bl_to_bin (lval_of (wline_of (i + 5 * clk_period, snd tw') COUNTER (get_time (i + 5 * clk_period, snd tw') - 1))) - 1) = 0"
using `wline_of tw' STATE (i + 5 * clk_period - 1) = V_PRE` `ubin_of NEXT_COUNTER at_time (i + 5 * clk_period) on tw' = 0`
unfolding inv_ncounter_alt_def comp_def snd_conv fst_conv by auto
hence "bintrunc 3 (ubin_of COUNTER at_time (i + 5 * clk_period - 1) on tw' - 1) = 0"
unfolding fst_conv comp_def snd_conv by auto
have "is_posedge2 (snd tw') CLK (i + 5 * clk_period)"
proof -
have "is_posedge2 w CLK (i + 6 * clk_period)"
using `is_posedge2 (snd tw') CLK (i + 6 * clk_period)`
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
hence "is_posedge2 w CLK (i + 6 * clk_period - clk_period)"
using assms by auto
hence "is_posedge2 w CLK (i + 5 * clk_period)"
by (auto simp add:field_simps)
thus "is_posedge2 (snd tw') CLK (i + 5 * clk_period)"
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
qed
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms
unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 5 * clk_period) mod clk_period = 0"
using \<open>\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0\<close> `is_posedge2 (snd tw') CLK (i + 5 * clk_period)` by blast
hence "(i + 4 * clk_period) mod clk_period = 0"
by auto
have fd: "\<And>k. i + 4 * clk_period + 1 \<le> k \<Longrightarrow> k \<le> i + 5 * clk_period - 1 \<Longrightarrow> \<not> is_posedge2 (snd tw') CLK k"
proof -
fix n
obtain m1 where "i + 4 * clk_period = m1 * clk_period"
using `(i + 4 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 5 * clk_period = (m1 + 1) * clk_period"
proof -
obtain m2 where "i + 5 * clk_period = m2 * clk_period"
using `(i + 5 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 6 * clk_period - (i + 5 * clk_period) = clk_period"
by (auto simp add: field_simps)
hence "m2 * clk_period - m1 * clk_period = clk_period"
using `i + 4 * clk_period = m1 * clk_period` `i + 5 * clk_period = m2 * clk_period`
by auto
hence "(m2 - m1) * clk_period = clk_period"
by (auto simp add: algebra_simps)
hence "m2 = Suc m1"
using `3 < clk_period ` by auto
thus ?thesis
using Suc_eq_plus1 \<open>i + 5 * clk_period = m2 * clk_period\<close> by presburger
qed
assume "i + 4 * clk_period + 1 \<le> n" and "n \<le> i + 5 * clk_period - 1"
hence "m1 * clk_period < n"
using `i + 4 * clk_period = m1 * clk_period` by linarith
have "n mod clk_period \<noteq> 0"
proof -
have "n div clk_period = m1"
apply (rule Misc_Arithmetic.sdl)
using \<open>m1 * clk_period < n\<close> apply (simp add: mult.commute)
using `n \<le> i + 5 * clk_period - 1` `i + 5 * clk_period = (m1 + 1) * clk_period` assms
by (auto simp add: field_simps)
hence "n = m1 * clk_period + n mod clk_period"
by auto
moreover have "n mod clk_period < clk_period"
using assms by (auto intro!: mod_less_divisor)
ultimately show ?thesis
using \<open>m1 * clk_period < n\<close> by linarith
qed
hence "\<not> is_posedge2 w CLK n"
using \<open>\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0\<close> by auto
thus "\<not> is_posedge2 (snd tw') CLK n"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
qed
have c: "wline_of tw' STATE (i + 4 * clk_period + 1) = V_PRE"
proof -
have fa: "fst tw \<le> i + 4 * clk_period + 1"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] by auto
have fb: "i + 4 * clk_period + 1 \<le> i + 5 * clk_period - 1"
using assms by (auto simp add: field_simps)
have fc: "i + 5 * clk_period - 1 \<le> i + 7 * clk_period + 1"
by auto
show ?thesis
using registers_unchanged_no_rising_edge[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)` fa fb fc fd]
`wline_of tw' STATE (i + 5 * clk_period - 1) = V_PRE` by auto
qed
moreover have b: "is_posedge2 (snd tw') CLK (i + 4 * clk_period)"
proof -
have "is_posedge2 w CLK (i + 5 * clk_period)"
using `is_posedge2 (snd tw') CLK (i + 5 * clk_period)`
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv] by auto
hence "is_posedge2 w CLK (i + 5 * clk_period - clk_period)"
using assms by auto
hence "is_posedge2 w CLK (i + 4 * clk_period)"
by (auto simp add:field_simps)
thus "is_posedge2 (snd tw') CLK (i + 4 * clk_period)"
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
qed
moreover have a: "Inv_core (i + 4 * clk_period + 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
moreover have d: "wline_of tw' RST (i + 4 * clk_period) = Bv False"
proof (rule ccontr)
assume "\<not> wline_of tw' RST (i + 4 * clk_period) = Bv False"
moreover have "type_of (wline_of tw' RST (i + 4 * clk_period)) = Bty"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
ultimately have "wline_of tw' RST (i + 4 * clk_period) = Bv True"
using type_of_bty_cases by blast
hence "wline_of tw' STATE (i + 4 * clk_period + 1) = V_INIT"
using `Inv_core (i + 4 * clk_period + 1, snd tw')` `is_posedge2 (snd tw') CLK (i + 4 * clk_period)`
unfolding inv_reg_alt_def comp_def snd_conv fst_conv by auto
with `wline_of tw' STATE (i + 4 * clk_period + 1) = V_PRE`
show False by auto
qed
ultimately have "wline_of tw' NEXT_STATE (i + 4 * clk_period) = V_PRE"
unfolding inv_reg_alt_def comp_def snd_conv fst_conv by auto
have "Inv_core (i + 4 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
hence "inv_nstate (i + 4 * clk_period, snd tw')"
by auto
have "wline_of tw' STATE (i + 4 * clk_period - 1) = V_WAIT"
proof (rule ccontr)
assume "\<not> wline_of tw' STATE (i + 4 * clk_period - 1) = V_WAIT" (is "\<not> ?state = V_WAIT")
then consider "?state = V_INIT" | "?state = V_PRE" | "?state = V_PROC" | "?state = V_POST"
| "?state \<noteq> V_INIT \<and> ?state \<noteq> V_WAIT \<and> ?state \<noteq> V_PRE \<and> ?state \<noteq> V_PROC \<and> ?state \<noteq> V_POST"
by auto
hence "wline_of tw' NEXT_STATE (i + 4 * clk_period) \<noteq> V_PRE"
proof (cases)
case 1
then show ?thesis
using `inv_nstate (i + 4 * clk_period, snd tw')` unfolding inv_nstate_alt_def
by auto
next
case 2
then show ?thesis
using `inv_nstate (i + 4 * clk_period, snd tw')` unfolding inv_nstate_alt_def
by auto
next
case 3
then show ?thesis
using `inv_nstate (i + 4 * clk_period, snd tw')` unfolding inv_nstate_alt_def
apply (cases "bval_of (wline_of (i + 4 * clk_period, snd tw') CTR_NEQ_0 (get_time (i + 4 * clk_period, snd tw') - 1))")
by auto
next
case 4
then show ?thesis
using `inv_nstate (i + 4 * clk_period, snd tw')` unfolding inv_nstate_alt_def
by auto
next
case 5
then show ?thesis
using `inv_nstate (i + 4 * clk_period, snd tw')` unfolding inv_nstate_alt_def
by (auto)
qed
thus False
using \<open>wline_of tw' NEXT_STATE (i + 4 * clk_period) = V_PRE\<close> by blast
qed
moreover have "bval_of (wline_of tw' INREADY (i + 4 * clk_period - 1))"
proof (rule ccontr)
assume "\<not> bval_of (wline_of tw' INREADY (i + 4 * clk_period - 1))"
hence "wline_of tw' NEXT_STATE (i + 4 * clk_period) = V_WAIT"
using `Inv_core (i + 4 * clk_period, snd tw')` `wline_of tw' STATE (i + 4 * clk_period - 1) = V_WAIT`
unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
thus False
using `wline_of tw' NEXT_STATE (i + 4 * clk_period) = V_PRE` by auto
qed
ultimately have "ubin_of NEXT_COUNTER at_time i + 4 * clk_period on tw' = 4"
using `Inv_core (i + 4 * clk_period, snd tw')`
unfolding inv_ncounter_alt_def comp_def snd_conv fst_conv by auto
hence "ubin_of COUNTER at_time i + 4 * clk_period + 1 on tw' = 4"
using a b d unfolding inv_reg_alt_def comp_def snd_conv fst_conv by auto
hence "ubin_of COUNTER at_time i + 5 * clk_period - 1 on tw' = 4"
proof -
have *: "get_time tw \<le> i + 4 * clk_period + 1"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] by auto
have **: "i + 4 * clk_period + 1 \<le> i + 5 * clk_period - 1"
using assms by auto
have "wline_of tw' COUNTER (i + 4 * clk_period + 1) = wline_of tw' COUNTER (i + 5 * clk_period - 1)"
using registers_unchanged_no_rising_edge[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)` * ** _ fd]
using assms by (auto)
thus ?thesis
using \<open>bl_to_bin (lval_of (wline_of tw' COUNTER (i + 4 * clk_period + 1))) = 4\<close> by auto
qed
with `bintrunc 3 (ubin_of COUNTER at_time (i + 5 * clk_period - 1) on tw' - 1) = 0`
show False
by auto
qed
ultimately have "wline_of tw' STATE (i + 5 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 5 * clk_period - 1))"
by auto
\<comment> \<open>obtaining counter value\<close>
have "bintrunc 3 (ubin_of COUNTER at_time (i + 5 * clk_period - 1) on tw' - 1) = 0"
proof -
have "Inv_core (i + 5 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
thus ?thesis
using `ubin_of NEXT_COUNTER at_time (i + 5 * clk_period) on tw' = 0`
`wline_of tw' STATE (i + 5 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 5 * clk_period - 1))`
unfolding inv_ncounter_alt_def fst_conv comp_def snd_conv by auto
qed
hence "(ubin_of COUNTER at_time (i + 5 * clk_period - 1) on tw' - 1) mod 8 = 0"
unfolding bintrunc_mod2p by auto
have "0 < ubin_of COUNTER at_time i + 5 * clk_period - 2 on tw'"
proof -
have "Inv_core (i + 5 * clk_period - 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
hence "inv_n0 (i + 5 * clk_period - 1, snd tw')"
by auto
hence "0 < bl_to_bin (lval_of (snd (snd tw') COUNTER (i + 5 * clk_period - 1 - 1)))"
using `wline_of tw' STATE (i + 5 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 5 * clk_period - 1))`
unfolding inv_n0_def comp_def snd_conv fst_conv by auto
thus ?thesis
unfolding comp_def snd_conv fst_conv
by (metis diff_diff_left nat_1_add_1)
qed
moreover have "ubin_of COUNTER at_time i + 5 * clk_period - 2 on tw' = ubin_of COUNTER at_time i + 5 * clk_period - 1 on tw'"
proof -
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms
unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence **: "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using posedge by blast
hence "(i + 5 * clk_period) mod clk_period = 0"
by auto
have "(i + 5 * clk_period - 2) mod clk_period \<noteq> 0"
proof -
have "i + 4 * clk_period < i + 5 * clk_period - 2"
using assms by (auto)
moreover have "i + 5 * clk_period - 2 < i + 5 * clk_period"
using assms by auto
ultimately show ?thesis
by (metis \<open>(i + 5 * clk_period) mod clk_period = 0\<close> assms(3) assms(4) diff_add_0 diff_add_inverse
dvd_add_left_iff dvd_antisym less_imp_add_positive less_nat_zero_code mod_0_imp_dvd nat_diff_split_asm numeral_plus_numeral semiring_norm(5))
qed
hence "\<not> is_posedge2 (snd tw') CLK (i + 5 * clk_period - 2)"
using ** by auto
moreover have "Inv_core (i + 5 * clk_period - 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
ultimately show ?thesis
unfolding inv_reg_alt_def comp_def snd_conv fst_conv
using diff_diff_left nat_1_add_1 by presburger
qed
ultimately have "0 < ubin_of COUNTER at_time i + 5 * clk_period - 1 on tw'"
by auto
moreover have "ubin_of COUNTER at_time (i + 5 * clk_period - 1) on tw' \<le> 7"
using ubin_counter_atmost[OF `wityping \<Gamma> (snd tw')`] by auto
ultimately have "(ubin_of COUNTER at_time (i + 5 * clk_period - 1) on tw' - 1) mod 8 = ubin_of COUNTER at_time (i + 5 * clk_period - 1) on tw' - 1"
by (auto intro!: int_mod_eq')
hence "ubin_of COUNTER at_time (i + 5 * clk_period - 1) on tw' = 1"
using `(ubin_of COUNTER at_time (i + 5 * clk_period - 1) on tw' - 1) mod 8 = 0` by auto
\<comment> \<open> obtaining frac \<close>
have "bin_of NEXT_FRAC at_time (i + 5 * clk_period) on tw' = approx_half"
proof -
have "Inv_core (i + 5 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
hence "inv_nfrac (i + 5 * clk_period, snd tw')"
by auto
thus ?thesis
using `ubin_of COUNTER at_time i + 5 * clk_period - 1 on tw' = 1`
unfolding inv_nfrac_alt_def comp_def snd_conv fst_conv by auto
qed
hence "bin_of FRAC at_time (i + 6 * clk_period - 1) on tw' = approx_half"
using \<open>wline_of tw' FRAC (i + 5 * clk_period + 1) = wline_of tw' FRAC (i + 6 * clk_period - 1)\<close>
\<open>wline_of tw' NEXT_FRAC (i + 5 * clk_period) = wline_of tw' FRAC (i + 5 * clk_period + 1)\<close> by
auto
have "bin_of TERM1 at_time (i + 6 * clk_period - 1) on tw' = sbintrunc 63
(bin_of COMMON at_time (i + 6 * clk_period - 2) on tw' * bin_of ACCUM at_time (i + 6 * clk_period - 2) on tw')"
proof -
have "Inv_core (i + 6 * clk_period - 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
thus ?thesis
unfolding inv_term1_def comp_def snd_conv fst_conv by (metis diff_diff_left one_add_one)
qed
have "Fixed (word_of_int (bin_of FRAC at_time i + 6 * clk_period - 1 on tw')) = Fixed ((word_of_int approx_half) :: (1 + 31) word)"
using `bin_of FRAC at_time i + 6 * clk_period - 1 on tw' = approx_half` by auto
have "((word_of_int approx_half) :: (1 + 31) word) = (approx_half :: (1 + 31) word)"
unfolding word_uint.inverse_norm by eval
hence "Fixed ((word_of_int approx_half) :: (1 + 31) word) = Fixed (approx_half :: (1 + 31) word)"
by auto
also have "... = approx_div_fact 1"
by auto
finally have "Fixed (word_of_int (bin_of FRAC at_time i + 6 * clk_period - 1 on tw')) = approx_div_fact 1"
using `Fixed (word_of_int (bin_of FRAC at_time i + 6 * clk_period - 1 on tw')) = Fixed ((word_of_int approx_half) :: (1 + 31) word)`
by auto
moreover have "Fixed (word_of_int (bin_of FRAC at_time i + 6 * clk_period - 1 on tw')) = (fixed_of_sval (wline_of tw' FRAC (i + 6 * clk_period - 1)) :: (1,31) fixed)"
proof -
have "type_of (wline_of tw' FRAC (i + 6 * clk_period - 1)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
hence "length (lval_of (wline_of tw' FRAC (i + 6 * clk_period - 1))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
hence "Fixed (word_of_int (bin_of FRAC at_time i + 6 * clk_period - 1 on tw')) =
Fixed (word_of_int (sbintrunc (LENGTH((1+31)) - 1) (bl_to_bin (lval_of (wline_of tw' FRAC (i + 6 * clk_period - 1))))))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (bl_to_bin (lval_of (wline_of tw' FRAC (i + 6 * clk_period - 1)))) :: (1 + 31) word)"
unfolding word_sbin.Abs_norm by auto
also have "... = fixed_of_sval (wline_of tw' FRAC (i + 6 * clk_period - 1))"
proof -
have "wline_of tw' FRAC (i + 6 * clk_period - 1) = Lv Sig (lval_of (wline_of tw' FRAC (i + 6 * clk_period - 1)))"
using `type_of (wline_of tw' FRAC (i + 6 *clk_period - 1)) = Lty Sig 32`
by (metis (no_types, hide_lams) ty.distinct(1) ty.inject type_of.cases type_of.simps(1) type_of.simps(2) val.sel(3))
thus ?thesis
using fixed_of_sval.simps unfolding of_bl_def by smt
qed
finally show ?thesis
by auto
qed
ultimately have "(fixed_of_sval (wline_of tw' FRAC (i + 6 * clk_period - 1)) :: (1,31) fixed) = approx_div_fact 1"
by auto
\<comment> \<open> obtaining accum\<close>
have "bin_of NEXT_ACCUM at_time (i + 6 * clk_period) on tw' =
sbintrunc 31 (bin_of FRAC at_time i + 6 * clk_period - 1 on tw' + (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 6 * clk_period - 1)) {1 .. 32})))"
proof -
have "Inv_core (i + 6 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
thus ?thesis
using `wline_of tw' STATE (i + 6 * clk_period - 1) = V_PROC \<and> \<not> bval_of (wline_of tw' CTR_NEQ_0 (i + 6 *clk_period - 1))`
unfolding inv_naccum_alt_def comp_def snd_conv fst_conv by auto
qed
hence "bin_of ACCUM at_time (i + 6 * clk_period + 1) on tw' =
sbintrunc 31 (bin_of FRAC at_time i + 6 * clk_period - 1 on tw' + (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 6 * clk_period - 1)) {1 .. 32})))"
using `wline_of tw' NEXT_ACCUM (i + 6 * clk_period) = wline_of tw' ACCUM (i + 6* clk_period + 1)`
by auto
hence "(word_of_int (bin_of ACCUM at_time i + 6 * clk_period + 1 on tw') :: (1 + 31) word) = word_of_int (sbintrunc 31 (bin_of FRAC at_time i + 6 * clk_period - 1 on tw' + (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 6 * clk_period - 1)) {1 .. 32}))))"
by auto
also have "... = word_of_int (sbintrunc (LENGTH((1 + 31)) - 1) (bin_of FRAC at_time i + 6 * clk_period - 1 on tw' + (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 6 * clk_period - 1)) {1 .. 32}))))"
by auto
also have "... = word_of_int (bin_of FRAC at_time i + 6 * clk_period - 1 on tw' + (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 6 * clk_period - 1)) {1 .. 32})))"
unfolding word_sbin.Abs_norm by auto
also have "... = word_of_int (bin_of FRAC at_time i + 6 * clk_period - 1 on tw') + word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 6 * clk_period - 1)) {1 .. 32}))"
unfolding wi_hom_syms(1) by auto
finally have "(word_of_int (bin_of ACCUM at_time i + 6 * clk_period + 1 on tw') :: (1 + 31) word) =
word_of_int (bin_of FRAC at_time i + 6 * clk_period - 1 on tw') + word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 6 * clk_period - 1)) {1 .. 32}))"
by auto
hence "Fixed (word_of_int (bin_of ACCUM at_time i + 6 * clk_period + 1 on tw') :: (1 + 31) word) =
Fixed (word_of_int (bin_of FRAC at_time i + 6 * clk_period - 1 on tw')) + Fixed (word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 6 * clk_period - 1)) {1 .. 32})))"
unfolding plus_fixed.abs_eq by auto
have "Fixed (word_of_int (bin_of ACCUM at_time i + 6 * clk_period + 1 on tw') :: (1 + 31) word) = fixed_of_sval (wline_of tw' ACCUM (i + 6 * clk_period + 1))"
(is "?lhs2 = ?rhs2")
proof -
have "type_of (wline_of tw' ACCUM (i + 6 * clk_period + 1)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
hence "length (lval_of (wline_of tw' ACCUM (i + 6 * clk_period + 1))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
hence "?lhs2 = Fixed (word_of_int (sbintrunc (LENGTH((1+31)) - 1) (bl_to_bin (lval_of (wline_of tw' ACCUM (i + 6 * clk_period + 1))))))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (bl_to_bin (lval_of (wline_of tw' ACCUM (i + 6 * clk_period + 1)))))"
unfolding word_sbin.Abs_norm by auto
also have "... = fixed_of_sval (wline_of tw' ACCUM (i + 6 * clk_period + 1))"
proof -
have "wline_of tw' ACCUM (i + 6 * clk_period + 1) = Lv Sig (lval_of (wline_of tw' ACCUM (i + 6 * clk_period + 1)))"
using `type_of (wline_of tw' ACCUM (i + 6 * clk_period + 1)) = Lty Sig 32`
by (metis (no_types, hide_lams) ty.distinct(1) ty.inject type_of.cases type_of.simps(1) type_of.simps(2) val.sel(3))
thus ?thesis
using fixed_of_sval.simps unfolding of_bl_def by smt
qed
finally show ?thesis
by auto
qed
have "(word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 6 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word) =
word_of_int (sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 6 * clk_period - 2)))) :: (1 + 31) word ) *
sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' ACCUM (i + 6 * clk_period - 2)))) :: (1 + 31) word) div 2 ^ 31)"
proof -
have "(word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 6 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word)=
word_of_int
(sbintrunc (length (nths (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1))) {1..32}) - 1) (bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1))) {1..32})))"
unfolding sbl_to_bin_alt_def by auto
moreover have "(length (nths (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1))) {1..32}) - 1) = 31"
proof -
have "type_of (wline_of tw' TERM1 (i + 6 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
have "card {1::nat ..32} = 32"
unfolding card_atLeastAtMost by auto
show ?thesis
unfolding length_nths *
using card_slice[where len="64" and l=62 and r="31"] by auto
qed
ultimately have "(word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 6 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word) =
word_of_int (sbintrunc 31 (bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1))) {1..32})))"
by auto
also have "... = word_of_int (sbintrunc (LENGTH(1+31) - 1) (bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1))) {1..32})))"
by auto
also have "... = (word_of_int (bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1))) {1..32})) :: (1 + 31) word) "
unfolding word_sbin.Abs_norm by auto
finally have "word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 6 * clk_period - 1)) {1 .. 32})) =
(word_of_int ( bl_to_bin (nths (lof_wline tw' TERM1 (i + 6 * clk_period - 1)) {1 .. 32})) :: (1+31) word)"
by auto
have interval: "{1 :: nat .. 32} = {1 :: nat ..< 33}"
by auto
have nths: "\<And>xs:: bool list. nths xs {1 :: nat .. 32} = drop 1 (take 33 xs)"
unfolding interval nths_from_upt_eq_drop_take[where m="1" and n="33"] by auto
have " bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1))) {1 ..32}) =
bl_to_bin (drop 1 (take 33 (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1)))))"
using nths[of "(lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1)))"] by auto
also have "... = bintrunc (length (take 33 (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1)))) - 1) (bl_to_bin (take 33 (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1)))))"
unfolding bl2bin_drop by auto
also have "... = bintrunc 32 (bl_to_bin (take 33 (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1)))))"
proof-
have "type_of (wline_of tw' TERM1 (i + 6 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
hence " length (take 33 (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1)))) = 33"
unfolding length_take by auto
thus ?thesis
by auto
qed
also have "... = bintrunc 32 (bl_to_bin (take (length (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1))) - 31) (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1)))))"
proof-
have "type_of (wline_of tw' TERM1 (i + 6 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
thus ?thesis
by auto
qed
also have "... = bintrunc 32 ((bin_rest ^^ 31) (bl_to_bin (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1)))))"
unfolding take_rest_bl2bin by auto
finally have "bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1))) {1 ..32}) =
bintrunc 32 ((bin_rest ^^ 31) (bl_to_bin (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1)))))"
by auto
have "(word_of_int (bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1))) {1 ..32})) :: (1+31) word)=
word_of_int (bintrunc 32 ((bin_rest ^^ 31) (bl_to_bin (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1))))))"
using \<open>bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1))) {1..32}) = bintrunc 32 ((bin_rest ^^ 31) (bl_to_bin (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1)))))\<close> by auto
\<comment> \<open>push bintrunc 32 inside\<close>
also have "... = word_of_int ((bin_rest ^^ 31) (bintrunc 63 (bl_to_bin (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1))))))"
using bin_rest_power_trunc[where n="63" and k="31", symmetric] by auto
also have "... = word_of_int ((bin_rest ^^ 31) (bl_to_bin (drop 1 (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1))))))"
proof -
have "type_of (wline_of tw' TERM1 (i + 6 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
thus ?thesis
using bl2bin_drop by auto
qed
\<comment> \<open>pull bl_to_bin to left\<close>
also have "... = word_of_int (bl_to_bin ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1))))))"
unfolding butlast_pow_rest_bl2bin[symmetric] by auto
\<comment> \<open>change to sbl_to_bin\<close>
also have "... = (word_of_int (sbintrunc (LENGTH(1+31) - 1) (bl_to_bin ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1))))))) :: (1 + 31) word)"
unfolding word_sbin.Abs_norm by auto
also have "... = word_of_int (sbl_to_bin ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1))))))"
proof -
have "type_of (wline_of tw' TERM1 (i + 6 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
have "length ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1))))) = 32"
unfolding butlast_power length_take length_drop * by eval
hence "(word_of_int (sbintrunc (LENGTH(1+31) - 1) (bl_to_bin ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1))))))) :: (1 + 31) word) =
(word_of_int (sbintrunc (length ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1))))) - 1) (bl_to_bin ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1))))))) :: (1 + 31) word)"
by auto
thus ?thesis
using sbl_to_bin_alt_def by auto
qed
\<comment> \<open>push sbl_to_bin back to right\<close>
also have "... = word_of_int ((bin_rest ^^ 31) (sbl_to_bin (drop 1 (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1))))))"
proof -
have "type_of (wline_of tw' TERM1 (i + 6 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
have "length ((drop 1 (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1))))) = 63"
unfolding length_take length_drop * by eval
hence **: "31 < length ((drop 1 (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1)))))"
by auto
show ?thesis
unfolding butlast_pow_rest_sbl2bin[OF **] by auto
qed
also have "... = word_of_int ((bin_rest ^^ 31) (sbintrunc 62 (sbl_to_bin (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1))))))"
proof -
have "type_of (wline_of tw' TERM1 (i + 6 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 6 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
thus ?thesis
using sbl2bin_drop by auto
qed
also have "... = word_of_int ((bin_rest ^^ 31) (sbintrunc 62 (bin_of COMMON at_time (i + 6 * clk_period - 2) on tw' * bin_of ACCUM at_time (i + 6 * clk_period - 2) on tw')))"
using `bin_of TERM1 at_time (i + 6 * clk_period - 1) on tw' = sbintrunc 63
(bin_of COMMON at_time (i + 6 * clk_period - 2) on tw' * bin_of ACCUM at_time (i + 6 * clk_period - 2) on tw')`
by auto
also have "... = word_of_int (sbintrunc 31 ((bin_rest ^^ 31) (bin_of COMMON at_time (i + 6 * clk_period - 2) on tw' * bin_of ACCUM at_time (i + 6 * clk_period - 2) on tw')))"
proof -
have "(31 :: nat) \<le> 62" by auto
show ?thesis
unfolding bin_rest_power_strunc[OF `31 \<le> 62`]
by auto
qed
also have "... = word_of_int (sbintrunc (LENGTH(1 + 31) - 1) ((bin_rest ^^ 31) (bin_of COMMON at_time (i + 6 * clk_period - 2) on tw' * bin_of ACCUM at_time (i + 6 * clk_period - 2) on tw')))"
by auto
also have "... = word_of_int ((bin_rest ^^ 31) (bin_of COMMON at_time (i + 6 * clk_period - 2) on tw' * bin_of ACCUM at_time (i + 6 * clk_period - 2) on tw'))"
unfolding word_sbin.Abs_norm by auto
also have "... = word_of_int ((bin_of COMMON at_time (i + 6 * clk_period - 2) on tw' * bin_of ACCUM at_time (i + 6 * clk_period - 2) on tw') div 2 ^ 31)"
unfolding bin_rest_compow by auto
also have "... = word_of_int (sbintrunc (length (lval_of (wline_of tw' COMMON (i + 6 * clk_period - 2))) - 1) (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 6 * clk_period - 2)))) *
sbintrunc (length (lval_of (wline_of tw' ACCUM (i + 6 * clk_period - 2))) - 1) (sbl_to_bin (lval_of (wline_of tw' ACCUM (i + 6 * clk_period - 2)))) div 2 ^ 31)"
using sbl_to_bin_alt_def2 by auto
also have "... = word_of_int (sbintrunc (LENGTH(1 + 31) - 1) (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 6 * clk_period - 2)))) *
sbintrunc (LENGTH(1 + 31) - 1) (sbl_to_bin (lval_of (wline_of tw' ACCUM (i + 6 * clk_period - 2)))) div 2 ^ 31)"
proof -
have "type_of (wline_of tw' COMMON (i + 6 * clk_period - 2)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' COMMON (i + 6 * clk_period - 2))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
have "type_of (wline_of tw' ACCUM (i + 6 * clk_period - 2)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence **: "length (lval_of (wline_of tw' ACCUM (i + 6 * clk_period - 2))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
with * show ?thesis
by auto
qed
also have "... = word_of_int (sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 6 * clk_period - 2)))) :: (1 + 31) word) *
sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' ACCUM (i + 6 * clk_period - 2)))) :: (1 + 31) word ) div 2 ^ 31)"
unfolding sint_sbintrunc' by auto
finally show ?thesis
unfolding `(word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 6 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word) =
(word_of_int ( bl_to_bin (nths (lof_wline tw' TERM1 (i + 6 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word)`
by auto
qed
hence "Fixed (word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 6 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word) =
Fixed (word_of_int (sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 6 * clk_period - 2)))) :: (1 + 31) word ) *
sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' ACCUM (i + 6 * clk_period - 2)))) :: (1 + 31) word) div 2 ^ 31))"
by auto
also have "... = Fixed (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 6 * clk_period - 2))))) * Fixed (word_of_int (sbl_to_bin (lval_of (wline_of tw' ACCUM (i + 6 * clk_period - 2)))))"
using times_fixed.abs_eq[where xa="word_of_int (bin_of COMMON at_time i + 6 * clk_period - 2 on tw') :: (1 + 31) word" and
x="word_of_int (bin_of ACCUM at_time i + 6 * clk_period - 2 on tw') :: (1 + 31) word", symmetric]
by auto
also have "... = fixed_of_sval (wline_of tw' COMMON (i + 6 * clk_period - 2)) * fixed_of_sval (wline_of tw' ACCUM (i + 6 * clk_period - 2))"
proof -
have "type_of (wline_of tw' COMMON (i + 6 * clk_period - 2)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
hence "length (lval_of (wline_of tw' COMMON (i + 6 * clk_period - 2))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
hence "Fixed (word_of_int (bin_of COMMON at_time i + 6 * clk_period - 2 on tw')) =
Fixed (word_of_int (sbintrunc (LENGTH((1+31)) - 1) (bl_to_bin (lval_of (wline_of tw' COMMON (i + 6 * clk_period - 2))))))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (bl_to_bin (lval_of (wline_of tw' COMMON (i + 6 * clk_period - 2)))) :: (1 + 31) word)"
unfolding word_sbin.Abs_norm by auto
also have "... = fixed_of_sval (wline_of tw' COMMON (i + 6 * clk_period - 2))"
proof -
have "wline_of tw' COMMON (i + 6 * clk_period - 2) = Lv Sig (lval_of (wline_of tw' COMMON (i + 6 * clk_period - 2)))"
using `type_of (wline_of tw' COMMON (i + 6 *clk_period - 2)) = Lty Sig 32`
by (metis (no_types, hide_lams) ty.distinct(1) ty.inject type_of.cases type_of.simps(1) type_of.simps(2) val.sel(3))
thus ?thesis
using fixed_of_sval.simps unfolding of_bl_def by smt
qed
finally have "Fixed (word_of_int (bin_of COMMON at_time i + 6 * clk_period - 2 on tw') :: (1 + 31) word) = fixed_of_sval (wline_of tw' COMMON (i + 6 * clk_period - 2))"
by auto
have "type_of (wline_of tw' ACCUM (i + 6 * clk_period - 2)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
hence "length (lval_of (wline_of tw' ACCUM (i + 6 * clk_period - 2))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
hence "Fixed (word_of_int (bin_of ACCUM at_time i + 6 * clk_period - 2 on tw')) =
Fixed (word_of_int (sbintrunc (LENGTH((1+31)) - 1) (bl_to_bin (lval_of (wline_of tw' ACCUM (i + 6 * clk_period - 2))))))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (bl_to_bin (lval_of (wline_of tw' ACCUM (i + 6 * clk_period - 2)))) :: (1 + 31) word)"
unfolding word_sbin.Abs_norm by auto
also have "... = fixed_of_sval (wline_of tw' ACCUM (i + 6 * clk_period - 2))"
proof -
have "wline_of tw' ACCUM (i + 6 * clk_period - 2) = Lv Sig (lval_of (wline_of tw' ACCUM (i + 6 * clk_period - 2)))"
using `type_of (wline_of tw' ACCUM (i + 6 *clk_period - 2)) = Lty Sig 32`
by (metis (no_types, hide_lams) ty.distinct(1) ty.inject type_of.cases type_of.simps(1) type_of.simps(2) val.sel(3))
thus ?thesis
using fixed_of_sval.simps unfolding of_bl_def by smt
qed
finally have "Fixed (word_of_int (bin_of ACCUM at_time i + 6 * clk_period - 2 on tw') :: (1 + 31) word) = fixed_of_sval (wline_of tw' ACCUM (i + 6 * clk_period - 2))"
by auto
thus ?thesis
using \<open>Fixed (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 6 * clk_period - 2))))) = fixed_of_sval (wline_of tw' COMMON (i + 6 * clk_period - 2))\<close> by auto
qed
finally have "Fixed (word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 6 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word) =
fixed_of_sval (wline_of tw' COMMON (i + 6 * clk_period - 2)) * fixed_of_sval (wline_of tw' ACCUM (i + 6 * clk_period - 2))"
by auto
hence "fixed_of_sval (wline_of tw' ACCUM (i + 6 * clk_period + 1)) =
approx_div_fact 1 + fixed_of_sval (wline_of tw' COMMON (i + 6 * clk_period - 2)) * fixed_of_sval (wline_of tw' ACCUM (i + 6 * clk_period - 2))"
using `?lhs2 = ?rhs2`
`Fixed (word_of_int (bin_of ACCUM at_time i + 6 * clk_period + 1 on tw') :: (1 + 31) word) =
Fixed (word_of_int (bin_of FRAC at_time i + 6 * clk_period - 1 on tw')) + Fixed (word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 6 * clk_period - 1)) {1 .. 32})))`
`Fixed (word_of_int (bin_of FRAC at_time i + 6 * clk_period - 1 on tw')) = approx_div_fact 1`
by auto
hence "fixed_of_sval (wline_of tw' ACCUM (fst tw')) = approx_div_fact 0 +
fixed_of_sval (wline_of tw' COMMON (i + 6 * clk_period - 1)) * (approx_div_fact 1 + fixed_of_sval (wline_of tw' COMMON (i + 6 * clk_period - 2)) * fixed_of_sval (wline_of tw' ACCUM (i + 6 * clk_period - 2)))"
using `fixed_of_sval (wline_of tw' ACCUM (fst tw')) = approx_div_fact 0 + fixed_of_sval (wline_of tw' COMMON (i + 7 * clk_period - 2)) * fixed_of_sval (wline_of tw' ACCUM (i + 7 * clk_period - 2))`
`(fixed_of_sval (wline_of tw' COMMON (i + 7 * clk_period - 2)) :: (1,31) fixed) = fixed_of_sval (wline_of tw' COMMON (i + 6 * clk_period - 1))`
using \<open>wline_of tw' ACCUM (i + 6 * clk_period + 1) = wline_of tw' ACCUM (i + 7 * clk_period - 2)\<close> by auto
hence "fixed_of_sval (wline_of tw' ACCUM (fst tw')) = approx_div_fact 0 +
fixed_of_sval (wline_of tw' COMMON (i + 6 * clk_period - 2)) * (approx_div_fact 1 + fixed_of_sval (wline_of tw' COMMON (i + 6 * clk_period - 2)) * fixed_of_sval (wline_of tw' ACCUM (i + 6 * clk_period - 2)))"
using `wline_of tw' COMMON (i + 6 * clk_period - 2) = wline_of tw' COMMON (i + 6 * clk_period - 1)`
by auto
\<comment> \<open> obtaining common and accum\<close>
have "wline_of tw' COMMON (i + 5 * clk_period + 1) = wline_of tw' COMMON (i + 6 * clk_period - 2)"
and "wline_of tw' ACCUM (i + 5 * clk_period + 1) = wline_of tw' ACCUM (i + 6 * clk_period - 2)"
proof -
have a: "fst tw \<le> i + 5 * clk_period + 1"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] by auto
have b: "i + 5 * clk_period + 1 \<le> i + 6 * clk_period - 2"
using assms by (auto simp add: field_simps)
have c: "i + 6 * clk_period - 2 \<le> i + 7 * clk_period + 1"
by auto
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms
unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using \<open>\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0\<close> assms by blast
hence "(i + 5 * clk_period) mod clk_period = 0"
by auto
hence "(i + 6 * clk_period) mod clk_period = 0"
by auto
have d: "\<And>k. i + 5 * clk_period + 1 \<le> k \<Longrightarrow> k \<le> i + 6 * clk_period - 1 \<Longrightarrow> \<not> is_posedge2 (snd tw') CLK k"
proof -
fix n
obtain m1 where "i + 5 * clk_period = m1 * clk_period"
using `(i + 5 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 6 * clk_period = (m1 + 1) * clk_period"
proof -
obtain m2 where "i + 6 * clk_period = m2 * clk_period"
using `(i + 6 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 7 * clk_period - (i + 6 * clk_period) = clk_period"
by (auto simp add: field_simps)
hence "m2 * clk_period - m1 * clk_period = clk_period"
using `i + 5 * clk_period = m1 * clk_period` `i + 6 * clk_period = m2 * clk_period`
by auto
hence "(m2 - m1) * clk_period = clk_period"
by (auto simp add: algebra_simps)
hence "m2 = Suc m1"
using `3 < clk_period ` by auto
thus ?thesis
using Suc_eq_plus1 \<open>i + 6 * clk_period = m2 * clk_period\<close> by presburger
qed
assume "i + 5 * clk_period + 1 \<le> n" and "n \<le> i + 6 * clk_period - 1"
hence "m1 * clk_period < n"
using `i + 5 * clk_period = m1 * clk_period` by linarith
have "n mod clk_period \<noteq> 0"
proof -
have "n div clk_period = m1"
apply (rule Misc_Arithmetic.sdl)
using \<open>m1 * clk_period < n\<close> apply (simp add: mult.commute)
using `n \<le> i + 6 * clk_period - 1` `i + 6 * clk_period = (m1 + 1) * clk_period` assms
by (auto simp add: field_simps)
hence "n = m1 * clk_period + n mod clk_period"
by auto
moreover have "n mod clk_period < clk_period"
using assms by (auto intro!: mod_less_divisor)
ultimately show ?thesis
using \<open>m1 * clk_period < n\<close> by linarith
qed
hence "\<not> is_posedge2 w CLK n"
using \<open>\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0\<close> by auto
thus "\<not> is_posedge2 (snd tw') CLK n"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
qed
show "wline_of tw' COMMON (i + 5 * clk_period + 1) = wline_of tw' COMMON (i + 6 * clk_period - 2)"
and "wline_of tw' ACCUM (i + 5 * clk_period + 1) = wline_of tw' ACCUM (i + 6 * clk_period - 2)"
using registers_unchanged_no_rising_edge[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)` a b c d]
by auto
qed
have "Inv_core (i + 5 * clk_period + 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
have "is_posedge2 (snd tw') CLK (i + 5 * clk_period)"
proof -
have "is_posedge2 w CLK (i + 7 * clk_period)"
using `is_posedge2 (snd tw') CLK (i + 7 * clk_period)`
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
hence "is_posedge2 w CLK (i + 6 * clk_period - clk_period)"
using assms by auto
hence "is_posedge2 w CLK (i + 5 * clk_period)"
by (auto simp add:field_simps)
thus "is_posedge2 (snd tw') CLK (i + 5 * clk_period)"
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
qed
have "wline_of tw' RST (i + 5 * clk_period) = Bv False"
proof (rule ccontr)
assume "wline_of tw' RST (i + 5 * clk_period) \<noteq> Bv False"
have "wityping \<Gamma> (snd tw')"
using `wityping \<Gamma> (snd tw)` world_sim_fin_preserves_wityping[OF 0]
using conc_stmt_wf_arch cwt_arch nonneg_delay_conc_architecture by blast
hence "type_of (wline_of tw' RST (i + 5 * clk_period)) = Bty"
unfolding wityping_def wtyping_def using cosine_locale_axioms unfolding cosine_locale_def by auto
hence "wline_of tw' RST (i + 5 * clk_period) = Bv True"
using `wline_of tw' RST (i + 5 * clk_period) \<noteq> Bv False` type_of_bty_cases by blast
hence "wline_of tw' STATE (i + 5 * clk_period + 1) = V_INIT"
using `Inv_core ((i + 5 * clk_period + 1, snd tw'))` `is_posedge2 (snd tw') CLK (i + 5 * clk_period)` unfolding inv_reg_alt_def
comp_def snd_conv fst_conv by auto
with `wline_of tw' STATE (i + 5 * clk_period + 1) = V_PROC` show False
by auto
qed
have "wline_of tw' NEXT_COMMON (i + 5 * clk_period) = wline_of tw' COMMON (i + 5 * clk_period + 1)"
and "wline_of tw' NEXT_ACCUM (i + 5 * clk_period) = wline_of tw' ACCUM (i + 5 * clk_period + 1)"
using `Inv_core (i + 5 * clk_period + 1, snd tw')` `is_posedge2 (snd tw') CLK (i + 5 * clk_period)` `wline_of tw' RST (i + 5 * clk_period) = Bv False`
unfolding inv_reg_alt_def comp_def snd_conv fst_conv by auto
have "bin_of COMMON at_time (i + 5 * clk_period - 1) on tw' = bin_of NEXT_COMMON at_time (i + 5 * clk_period) on tw'"
proof -
have "Inv_core (i + 5 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
thus ?thesis
using `wline_of tw' STATE (i + 5 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 5 * clk_period - 1))`
unfolding inv_ncommon_alt_def comp_def snd_conv fst_conv by auto
qed
have "(fixed_of_sval (wline_of tw' COMMON (i + 6 * clk_period - 2)) :: (1,31) fixed) = fixed_of_sval (wline_of tw' COMMON (i + 5 * clk_period - 1))"
proof -
have typof2: "type_of (wline_of tw' COMMON (i + 5 * clk_period - 1)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
then obtain bs2 where " wline_of tw' COMMON (i + 5 * clk_period - 1) = Lv Sig bs2 \<and> length bs2 = 32"
using type_of.elims[OF typof2] by fastforce
have typof: "type_of (wline_of tw' COMMON (i + 6 * clk_period - 2)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
then obtain bs1 where " wline_of tw' COMMON (i + 6 * clk_period - 2) = Lv Sig bs1 \<and> length bs1 = 32"
using type_of.elims[OF typof] by fastforce
hence "fixed_of_sval (wline_of tw' COMMON (i + 6 * clk_period - 2)) = Fixed (of_bl bs1 :: (1 + 31) word)"
using fixed_of_sval.simps by auto
also have "... = Fixed (word_of_int (bl_to_bin bs1) :: (1 + 31) word)"
unfolding of_bl_def by auto
also have "... = Fixed (word_of_int (sbintrunc (LENGTH(1+31) - 1) (bl_to_bin bs1)))"
unfolding word_sbin.Abs_norm[symmetric, where x="bl_to_bin bs1"] by auto
also have "... = Fixed (word_of_int (sbintrunc (length bs1 - 1) (bl_to_bin bs1)))"
using `wline_of tw' COMMON (i + 6 * clk_period - 2) = Lv Sig bs1 \<and> length bs1 = 32` by auto
also have "... = Fixed (word_of_int (sbl_to_bin bs1))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (sbl_to_bin bs2))"
using `bin_of COMMON at_time (i + 5 * clk_period - 1) on tw' = bin_of NEXT_COMMON at_time (i + 5 * clk_period) on tw'`
`wline_of tw' COMMON (i + 5 * clk_period - 1) = Lv Sig bs2 \<and> length bs2 = 32`
`wline_of tw' COMMON (i + 6 * clk_period - 2) = Lv Sig bs1 \<and> length bs1 = 32`
using \<open>wline_of tw' COMMON (i + 5 * clk_period + 1) = wline_of tw' COMMON (i + 6 * clk_period - 2)\<close> \<open>wline_of tw' NEXT_COMMON (i + 5 * clk_period) = wline_of tw' COMMON (i + 5 * clk_period + 1)\<close> by auto
also have "... = Fixed (word_of_int (sbintrunc (length bs2- 1) (bl_to_bin bs2)))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (sbintrunc (LENGTH(1+31) - 1) (bl_to_bin bs2)))"
using `wline_of tw' COMMON (i + 5 * clk_period - 1) = Lv Sig bs2 \<and> length bs2 = 32` by auto
also have "... = Fixed (word_of_int (bl_to_bin bs2) :: (1 + 31) word)"
unfolding word_sbin.Abs_norm[symmetric, where x="bl_to_bin bs2"] by auto
also have "... = Fixed (of_bl bs2 :: (1 + 31) word)"
unfolding of_bl_def by auto
also have "... = fixed_of_sval (wline_of tw' COMMON (i + 5 * clk_period - 1))"
using `wline_of tw' COMMON (i + 5 * clk_period - 1) = Lv Sig bs2 \<and> length bs2 = 32`
using fixed_of_sval.simps by auto
finally show ?thesis
by auto
qed
have "wline_of tw' COMMON (i + 5 * clk_period - 2) = wline_of tw' COMMON (i + 5 * clk_period - 1)"
proof -
have "Inv_core (i + 5 * clk_period - 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms
unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence **: "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using posedge by blast
hence "(i + 5 * clk_period) mod clk_period = 0"
by auto
have "(i + 5 * clk_period - 2) mod clk_period \<noteq> 0"
proof -
have "i + 4 * clk_period < i + 5 * clk_period - 2"
using assms by (auto)
moreover have "i + 5 * clk_period - 2 < i + 6 * clk_period"
using assms by auto
ultimately show ?thesis
by (metis \<open>(i + 5 * clk_period) mod clk_period = 0\<close> assms(3) assms(4) diff_add_0 diff_add_inverse
dvd_add_left_iff dvd_antisym less_imp_add_positive less_nat_zero_code mod_0_imp_dvd nat_diff_split_asm numeral_plus_numeral semiring_norm(5))
qed
hence "\<not> is_posedge2 (snd tw') CLK (i + 5 * clk_period - 2)"
using ** by auto
thus ?thesis
using `Inv_core (i + 5 * clk_period - 1, snd tw')` unfolding inv_reg_alt_def comp_def snd_conv fst_conv
using diff_diff_left nat_1_add_1 by presburger
qed
\<comment> \<open> obtaining state\<close>
have "wline_of tw' STATE (i + 4 * clk_period + 1) = wline_of tw' STATE (i + 5 * clk_period - 1)"
proof -
have a: "fst tw \<le> i + 4 * clk_period + 1"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] by auto
have b: "i + 4 * clk_period + 1 \<le> i + 5 * clk_period - 1"
using assms by (auto simp add: field_simps)
have c: "i + 5 * clk_period - 1 \<le> i + 7 * clk_period + 1"
by auto
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms
unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using \<open>\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0\<close> assms by blast
hence "(i + 5 * clk_period) mod clk_period = 0"
by auto
hence "(i + 4 * clk_period) mod clk_period = 0"
by auto
have d: "\<And>k. i + 4 * clk_period + 1 \<le> k \<Longrightarrow> k \<le> i + 5 * clk_period - 1 \<Longrightarrow> \<not> is_posedge2 (snd tw') CLK k"
proof -
fix n
obtain m1 where "i + 4 * clk_period = m1 * clk_period"
using `(i + 4 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 5 * clk_period = (m1 + 1) * clk_period"
proof -
obtain m2 where "i + 5 * clk_period = m2 * clk_period"
using `(i + 5 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 5 * clk_period - (i + 4 * clk_period) = clk_period"
by (auto simp add: field_simps)
hence "m2 * clk_period - m1 * clk_period = clk_period"
using `i + 4 * clk_period = m1 * clk_period` `i + 5 * clk_period = m2 * clk_period`
by auto
hence "(m2 - m1) * clk_period = clk_period"
by (auto simp add: algebra_simps)
hence "m2 = Suc m1"
using `3 < clk_period ` by auto
thus ?thesis
using Suc_eq_plus1 \<open>i + 5 * clk_period = m2 * clk_period\<close> by presburger
qed
assume "i + 4 * clk_period + 1 \<le> n" and "n \<le> i + 5 * clk_period - 1"
hence "m1 * clk_period < n"
using `i + 4 * clk_period = m1 * clk_period` by linarith
have "n mod clk_period \<noteq> 0"
proof -
have "n div clk_period = m1"
apply (rule Misc_Arithmetic.sdl)
using \<open>m1 * clk_period < n\<close> apply (simp add: mult.commute)
using `n \<le> i + 5 * clk_period - 1` `i + 5 * clk_period = (m1 + 1) * clk_period` assms
by (auto simp add: field_simps)
hence "n = m1 * clk_period + n mod clk_period"
by auto
moreover have "n mod clk_period < clk_period"
using assms by (auto intro!: mod_less_divisor)
ultimately show ?thesis
using \<open>m1 * clk_period < n\<close> by linarith
qed
hence "\<not> is_posedge2 w CLK n"
using \<open>\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0\<close> by auto
thus "\<not> is_posedge2 (snd tw') CLK n"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
qed
show "wline_of tw' STATE (i + 4 * clk_period + 1) = wline_of tw' STATE (i + 5 * clk_period - 1)"
using registers_unchanged_no_rising_edge[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)` a b c d]
by auto
qed
hence "wline_of tw' STATE (i + 4 * clk_period + 1) = V_PROC"
using `wline_of tw' STATE (i + 5 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 5 * clk_period - 1))`
by auto
have "wline_of tw' FRAC (i + 4 * clk_period + 1) = wline_of tw' FRAC (i + 5 * clk_period - 1)"
and "wline_of tw' COUNTER (i + 4 * clk_period + 1) = wline_of tw' COUNTER (i + 5 * clk_period - 1)"
proof -
have a: "fst tw \<le> i + 4 * clk_period + 1"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] by auto
have b: "i + 4 * clk_period + 1 \<le> i + 5 * clk_period - 1"
using assms by (auto simp add: field_simps)
have c: "i + 5 * clk_period - 1 \<le> i + 7 * clk_period + 1"
by auto
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using \<open>\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0\<close> assms by blast
hence "(i + 5 * clk_period) mod clk_period = 0"
by auto
hence "(i + 4 * clk_period) mod clk_period = 0"
by auto
have d: "\<And>k. i + 4 * clk_period + 1 \<le> k \<Longrightarrow> k \<le> i + 5 * clk_period - 1 \<Longrightarrow> \<not> is_posedge2 (snd tw') CLK k"
proof -
fix n
obtain m1 where "i + 4 * clk_period = m1 * clk_period"
using `(i + 4 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 5 * clk_period = (m1 + 1) * clk_period"
proof -
obtain m2 where "i + 5 * clk_period = m2 * clk_period"
using `(i + 5 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 5 * clk_period - (i + 4 * clk_period) = clk_period"
by (auto simp add: field_simps)
hence "m2 * clk_period - m1 * clk_period = clk_period"
using `i + 4 * clk_period = m1 * clk_period` `i + 5 * clk_period = m2 * clk_period` by auto
hence "(m2 - m1) * clk_period = clk_period"
by (auto simp add: algebra_simps)
hence "m2 = Suc m1"
using `3 < clk_period ` by auto
thus ?thesis
using Suc_eq_plus1 \<open>i + 5 * clk_period = m2 * clk_period\<close> by presburger
qed
assume "i + 4 * clk_period + 1 \<le> n" and "n \<le> i + 5 * clk_period - 1"
hence "m1 * clk_period < n"
using `i + 4 * clk_period = m1 * clk_period` by linarith
have "n mod clk_period \<noteq> 0"
proof -
have "n div clk_period = m1"
apply (rule Misc_Arithmetic.sdl)
using \<open>m1 * clk_period < n\<close> apply (simp add: mult.commute)
using `n \<le> i + 5 * clk_period - 1` `i + 5 * clk_period = (m1 + 1) * clk_period` assms
by (auto simp add: field_simps)
hence "n = m1 * clk_period + n mod clk_period"
by auto
moreover have "n mod clk_period < clk_period"
using assms by (auto intro!: mod_less_divisor)
ultimately show ?thesis
using \<open>m1 * clk_period < n\<close> by linarith
qed
hence "\<not> is_posedge2 w CLK n"
using \<open>\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0\<close> by auto
thus "\<not> is_posedge2 (snd tw') CLK n"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
qed
show "wline_of tw' FRAC (i + 4 * clk_period + 1) = wline_of tw' FRAC (i + 5 * clk_period - 1)"
and "wline_of tw' COUNTER (i + 4 * clk_period + 1) = wline_of tw' COUNTER (i + 5 * clk_period - 1)"
using registers_unchanged_no_rising_edge[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)` a b c d] by auto
qed
have "wline_of tw' NEXT_FRAC (i + 4 * clk_period) = wline_of tw' FRAC (i + 4 * clk_period + 1)"
and "wline_of tw' NEXT_STATE (i + 4 * clk_period) = wline_of tw' STATE (i + 4 * clk_period + 1)"
and "wline_of tw' NEXT_COUNTER (i + 4 * clk_period) = wline_of tw' COUNTER (i + 4 * clk_period + 1)"
proof -
have "Inv_core (i + 4 * clk_period + 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
moreover have "is_posedge2 (snd tw') CLK (i + 4 * clk_period)"
proof -
have "is_posedge2 w CLK (i + 5 * clk_period)"
using `is_posedge2 (snd tw') CLK (i + 5 * clk_period)`
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
hence "is_posedge2 w CLK (i + 5 * clk_period - clk_period)"
using assms by auto
hence "is_posedge2 w CLK (i + 4 * clk_period)"
by (auto simp add:field_simps)
thus "is_posedge2 (snd tw') CLK (i + 4 * clk_period)"
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
qed
moreover have "wline_of tw' RST (i + 4 * clk_period) = Bv False"
proof (rule ccontr)
assume "wline_of tw' RST (i + 4 * clk_period) \<noteq> Bv False"
have "wityping \<Gamma> (snd tw')"
using `wityping \<Gamma> (snd tw)` world_sim_fin_preserves_wityping[OF 0] conc_stmt_wf_arch cwt_arch nonneg_delay_conc_architecture by blast
hence "type_of (wline_of tw' RST (i + 4 * clk_period)) = Bty"
unfolding wityping_def wtyping_def using cosine_locale_axioms unfolding cosine_locale_def by auto
hence "wline_of tw' RST (i + 4 * clk_period) = Bv True"
using `wline_of tw' RST (i + 4 * clk_period) \<noteq> Bv False` type_of_bty_cases by blast
hence "wline_of tw' STATE (i + 4 * clk_period + 1) = V_INIT"
using `Inv_core (i + 4 * clk_period + 1, snd tw')` `is_posedge2 (snd tw') CLK (i + 4 * clk_period)` unfolding inv_reg_alt_def
comp_def snd_conv fst_conv by auto
with `wline_of tw' STATE (i + 4 * clk_period + 1) = V_PROC` show False
using \<open>wline_of tw' OUTREADY_REG (get_time tw') = Bv True\<close> by auto
qed
ultimately show "wline_of tw' NEXT_FRAC (i + 4 * clk_period) = wline_of tw' FRAC (i + 4 * clk_period + 1)"
and "wline_of tw' NEXT_STATE (i + 4 * clk_period) = wline_of tw' STATE (i + 4 * clk_period + 1)"
and "wline_of tw' NEXT_COUNTER (i + 4 * clk_period) = wline_of tw' COUNTER (i + 4 * clk_period + 1)"
unfolding inv_reg_alt_def comp_def snd_conv fst_conv by auto
qed
hence "wline_of tw' NEXT_STATE (i + 4 * clk_period) = V_PROC" and "ubin_of NEXT_COUNTER at_time i + 4 * clk_period on tw' = 1"
using `wline_of tw' STATE (i + 4 * clk_period + 1) = V_PROC` `ubin_of COUNTER at_time i + 5 * clk_period - 1 on tw' = 1`
using \<open>bl_to_bin (lval_of (wline_of tw' COUNTER (i + 5 * clk_period - 1))) = 1\<close> \<open>wline_of tw' COUNTER (i + 4 * clk_period + 1) = wline_of tw' COUNTER (i + 5 * clk_period - 1)\<close> \<open>wline_of tw' NEXT_COUNTER (i + 4 * clk_period) = wline_of tw' COUNTER (i + 4 * clk_period + 1)\<close>
by auto
have "wline_of tw' STATE (i + 4 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 4 * clk_period - 1))
\<or> wline_of tw' STATE (i + 4 * clk_period - 1) = V_PRE"
proof (rule ccontr)
have "Inv_core (i + 4 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
hence inv:"inv_nstate (i + 4 * clk_period, snd tw')"
by auto
assume "\<not> (wline_of tw' STATE (i + 4 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 4 * clk_period - 1))
\<or> wline_of tw' STATE (i + 4 * clk_period - 1) = V_PRE)"
hence *: "(wline_of tw' STATE (i + 4 * clk_period - 1) = V_PROC \<Longrightarrow> \<not> bval_of (wline_of tw' CTR_NEQ_0 (i + 4 * clk_period - 1)))" and
**: "wline_of tw' STATE (i + 4 * clk_period - 1) \<noteq> V_PRE" (is "?state \<noteq> _")by auto
then consider "?state = V_INIT" | "?state = V_WAIT" | "?state = V_PROC" | "?state = V_POST"
| "?state \<noteq> V_INIT \<and> ?state \<noteq> V_WAIT \<and> ?state \<noteq> V_PRE \<and> ?state \<noteq> V_PROC \<and> ?state \<noteq> V_POST"
by auto
thus False
proof (cases)
case 1
hence "wline_of tw' NEXT_STATE (i + 4 * clk_period) \<noteq> V_PROC"
using inv unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 4 * clk_period) = V_PROC`
by auto
next
case 2
hence "wline_of tw' NEXT_STATE (i + 4 * clk_period) \<noteq> V_PROC"
using inv unfolding inv_nstate_alt_def comp_def snd_conv fst_conv
by (cases "bval_of (snd (snd tw') INREADY (i + 4 * clk_period - 1))") auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 4 * clk_period) = V_PROC`
by auto
next
case 3
hence "wline_of tw' NEXT_STATE (i + 4 * clk_period) \<noteq> V_PROC"
using inv * unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 4 * clk_period) = V_PROC`
by auto
next
case 4
hence "wline_of tw' NEXT_STATE (i + 4 * clk_period) \<noteq> V_PROC"
using inv * unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 4 * clk_period) = V_PROC`
by auto
next
case 5
hence "wline_of tw' NEXT_STATE (i + 4 * clk_period) \<noteq> V_PROC"
using inv * unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 4 * clk_period) = V_PROC`
by auto
qed
qed
moreover have "wline_of tw' STATE (i + 4 * clk_period - 1) \<noteq> V_PRE"
proof (rule ccontr)
assume "\<not> wline_of tw' STATE (i + 4 * clk_period - 1) \<noteq> V_PRE"
hence "wline_of tw' STATE (i + 4 * clk_period - 1) = V_PRE"
by auto
have "Inv_core (i + 4 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
hence "bintrunc 3 (bl_to_bin (lval_of (wline_of (i + 4 * clk_period, snd tw') COUNTER (get_time (i + 4 * clk_period, snd tw') - 1))) - 1) = 1"
using `wline_of tw' STATE (i + 4 * clk_period - 1) = V_PRE` `ubin_of NEXT_COUNTER at_time (i + 4 * clk_period) on tw' = 1`
unfolding inv_ncounter_alt_def comp_def snd_conv fst_conv by auto
hence "bintrunc 3 (ubin_of COUNTER at_time (i + 4 * clk_period - 1) on tw' - 1) = 1"
unfolding fst_conv comp_def snd_conv by auto
have "is_posedge2 (snd tw') CLK (i + 4 * clk_period)"
proof -
have "is_posedge2 w CLK (i + 5 * clk_period)"
using `is_posedge2 (snd tw') CLK (i + 5 * clk_period)`
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
hence "is_posedge2 w CLK (i + 5 * clk_period - clk_period)"
using assms by auto
hence "is_posedge2 w CLK (i + 4 * clk_period)"
by (auto simp add:field_simps)
thus "is_posedge2 (snd tw') CLK (i + 4 * clk_period)"
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
qed
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms
unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 4 * clk_period) mod clk_period = 0"
using \<open>\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0\<close> `is_posedge2 (snd tw') CLK (i + 4 * clk_period)` by blast
hence "(i + 3 * clk_period) mod clk_period = 0"
by auto
have fd: "\<And>k. i + 3 * clk_period + 1 \<le> k \<Longrightarrow> k \<le> i + 4 * clk_period - 1 \<Longrightarrow> \<not> is_posedge2 (snd tw') CLK k"
proof -
fix n
obtain m1 where "i + 3 * clk_period = m1 * clk_period"
using `(i + 3 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 4 * clk_period = (m1 + 1) * clk_period"
proof -
obtain m2 where "i + 4 * clk_period = m2 * clk_period"
using `(i + 4 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 4 * clk_period - (i + 3 * clk_period) = clk_period"
by (auto simp add: field_simps)
hence "m2 * clk_period - m1 * clk_period = clk_period"
using `i + 3 * clk_period = m1 * clk_period` `i + 4 * clk_period = m2 * clk_period`
by auto
hence "(m2 - m1) * clk_period = clk_period"
by (auto simp add: algebra_simps)
hence "m2 = Suc m1"
using `3 < clk_period ` by auto
thus ?thesis
using Suc_eq_plus1 \<open>i + 4 * clk_period = m2 * clk_period\<close> by presburger
qed
assume "i + 3 * clk_period + 1 \<le> n" and "n \<le> i + 4 * clk_period - 1"
hence "m1 * clk_period < n"
using `i + 3 * clk_period = m1 * clk_period` by linarith
have "n mod clk_period \<noteq> 0"
proof -
have "n div clk_period = m1"
apply (rule Misc_Arithmetic.sdl)
using \<open>m1 * clk_period < n\<close> apply (simp add: mult.commute)
using `n \<le> i + 4 * clk_period - 1` `i + 4 * clk_period = (m1 + 1) * clk_period` assms
by (auto simp add: field_simps)
hence "n = m1 * clk_period + n mod clk_period"
by auto
moreover have "n mod clk_period < clk_period"
using assms by (auto intro!: mod_less_divisor)
ultimately show ?thesis
using \<open>m1 * clk_period < n\<close> by linarith
qed
hence "\<not> is_posedge2 w CLK n"
using \<open>\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0\<close> by auto
thus "\<not> is_posedge2 (snd tw') CLK n"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
qed
have c: "wline_of tw' STATE (i + 3 * clk_period + 1) = V_PRE"
proof -
have fa: "fst tw \<le> i + 3 * clk_period + 1"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] by auto
have fb: "i + 3 * clk_period + 1 \<le> i + 4 * clk_period - 1"
using assms by (auto simp add: field_simps)
have fc: "i + 4 * clk_period - 1 \<le> i + 7 * clk_period + 1"
by auto
show ?thesis
using registers_unchanged_no_rising_edge[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)` fa fb fc fd]
`wline_of tw' STATE (i + 4 * clk_period - 1) = V_PRE` by auto
qed
moreover have b: "is_posedge2 (snd tw') CLK (i + 3 * clk_period)"
proof -
have "is_posedge2 w CLK (i + 4 * clk_period)"
using `is_posedge2 (snd tw') CLK (i + 4 * clk_period)`
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv] by auto
hence "is_posedge2 w CLK (i + 4 * clk_period - clk_period)"
using assms by auto
hence "is_posedge2 w CLK (i + 3 * clk_period)"
by (auto simp add:field_simps)
thus "is_posedge2 (snd tw') CLK (i + 3 * clk_period)"
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
qed
moreover have a: "Inv_core (i + 3 * clk_period + 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
moreover have d: "wline_of tw' RST (i + 3 * clk_period) = Bv False"
proof (rule ccontr)
assume "\<not> wline_of tw' RST (i + 3 * clk_period) = Bv False"
moreover have "type_of (wline_of tw' RST (i + 3 * clk_period)) = Bty"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
ultimately have "wline_of tw' RST (i + 3 * clk_period) = Bv True"
using type_of_bty_cases by blast
hence "wline_of tw' STATE (i + 3 * clk_period + 1) = V_INIT"
using `Inv_core (i + 3 * clk_period + 1, snd tw')` `is_posedge2 (snd tw') CLK (i + 3 * clk_period)`
unfolding inv_reg_alt_def comp_def snd_conv fst_conv by auto
with `wline_of tw' STATE (i + 3 * clk_period + 1) = V_PRE`
show False by auto
qed
ultimately have "wline_of tw' NEXT_STATE (i + 3 * clk_period) = V_PRE"
unfolding inv_reg_alt_def comp_def snd_conv fst_conv by auto
have "Inv_core (i + 3 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
hence "inv_nstate (i + 3 * clk_period, snd tw')"
by auto
have "wline_of tw' STATE (i + 3 * clk_period - 1) = V_WAIT"
proof (rule ccontr)
assume "\<not> wline_of tw' STATE (i + 3 * clk_period - 1) = V_WAIT" (is "\<not> ?state = V_WAIT")
then consider "?state = V_INIT" | "?state = V_PRE" | "?state = V_PROC" | "?state = V_POST"
| "?state \<noteq> V_INIT \<and> ?state \<noteq> V_WAIT \<and> ?state \<noteq> V_PRE \<and> ?state \<noteq> V_PROC \<and> ?state \<noteq> V_POST"
by auto
hence "wline_of tw' NEXT_STATE (i + 3 * clk_period) \<noteq> V_PRE"
proof (cases)
case 1
then show ?thesis
using `inv_nstate (i + 3 * clk_period, snd tw')` unfolding inv_nstate_alt_def
by auto
next
case 2
then show ?thesis
using `inv_nstate (i + 3 * clk_period, snd tw')` unfolding inv_nstate_alt_def
by auto
next
case 3
then show ?thesis
using `inv_nstate (i + 3 * clk_period, snd tw')` unfolding inv_nstate_alt_def
apply (cases "bval_of (wline_of (i + 3 * clk_period, snd tw') CTR_NEQ_0 (get_time (i + 3 * clk_period, snd tw') - 1))")
by auto
next
case 4
then show ?thesis
using `inv_nstate (i + 3 * clk_period, snd tw')` unfolding inv_nstate_alt_def
by auto
next
case 5
then show ?thesis
using `inv_nstate (i + 3 * clk_period, snd tw')` unfolding inv_nstate_alt_def
by (auto)
qed
thus False
using \<open>wline_of tw' NEXT_STATE (i + 3 * clk_period) = V_PRE\<close> by blast
qed
moreover have "bval_of (wline_of tw' INREADY (i + 3 * clk_period - 1))"
proof (rule ccontr)
assume "\<not> bval_of (wline_of tw' INREADY (i + 3 * clk_period - 1))"
hence "wline_of tw' NEXT_STATE (i + 3 * clk_period) = V_WAIT"
using `Inv_core (i + 3 * clk_period, snd tw')` `wline_of tw' STATE (i + 3 * clk_period - 1) = V_WAIT`
unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
thus False
using `wline_of tw' NEXT_STATE (i + 3 * clk_period) = V_PRE` by auto
qed
ultimately have "ubin_of NEXT_COUNTER at_time i + 3 * clk_period on tw' = 4"
using `Inv_core (i + 3 * clk_period, snd tw')`
unfolding inv_ncounter_alt_def comp_def snd_conv fst_conv by auto
hence "ubin_of COUNTER at_time i + 3 * clk_period + 1 on tw' = 4"
using a b d unfolding inv_reg_alt_def comp_def snd_conv fst_conv by auto
hence "ubin_of COUNTER at_time i + 4 * clk_period - 1 on tw' = 4"
proof -
have *: "get_time tw \<le> i + 3 * clk_period + 1"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] by auto
have **: "i + 3 * clk_period + 1 \<le> i + 4 * clk_period - 1"
using assms by auto
have "wline_of tw' COUNTER (i + 3 * clk_period + 1) = wline_of tw' COUNTER (i + 4 * clk_period - 1)"
using registers_unchanged_no_rising_edge[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)` * ** _ fd]
using assms by (auto)
thus ?thesis
using \<open>bl_to_bin (lval_of (wline_of tw' COUNTER (i + 3 * clk_period + 1))) = 4\<close> by auto
qed
with `bintrunc 3 (ubin_of COUNTER at_time (i + 4 * clk_period - 1) on tw' - 1) = 1`
show False
by auto
qed
ultimately have "wline_of tw' STATE (i + 4 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 4 * clk_period - 1))"
by auto
\<comment> \<open>obtaining counter value\<close>
have "bintrunc 3 (ubin_of COUNTER at_time (i + 4 * clk_period - 1) on tw' - 1) = 1"
proof -
have "Inv_core (i + 4 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
thus ?thesis
using `ubin_of NEXT_COUNTER at_time (i + 4 * clk_period) on tw' = 1`
`wline_of tw' STATE (i + 4 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 4 * clk_period - 1))`
unfolding inv_ncounter_alt_def fst_conv comp_def snd_conv by auto
qed
hence "(ubin_of COUNTER at_time (i + 4 * clk_period - 1) on tw' - 1) mod 8 = 1"
unfolding bintrunc_mod2p by auto
have "0 < ubin_of COUNTER at_time i + 4 * clk_period - 2 on tw'"
proof -
have "Inv_core (i + 4 * clk_period - 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
hence "inv_n0 (i + 4 * clk_period - 1, snd tw')"
by auto
hence "0 < bl_to_bin (lval_of (snd (snd tw') COUNTER (i + 4 * clk_period - 1 - 1)))"
using `wline_of tw' STATE (i + 4 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 4 * clk_period - 1))`
unfolding inv_n0_def comp_def snd_conv fst_conv by auto
thus ?thesis
unfolding comp_def snd_conv fst_conv
by (metis diff_diff_left nat_1_add_1)
qed
moreover have "ubin_of COUNTER at_time i + 4 * clk_period - 2 on tw' = ubin_of COUNTER at_time i + 4 * clk_period - 1 on tw'"
proof -
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms
unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence **: "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using posedge by blast
hence "(i + 4 * clk_period) mod clk_period = 0"
by auto
have "(i + 4 * clk_period - 2) mod clk_period \<noteq> 0"
proof -
have "i + 3 * clk_period < i + 4 * clk_period - 2"
using assms by (auto)
moreover have "i + 4 * clk_period - 2 < i + 4 * clk_period"
using assms by auto
ultimately show ?thesis
by (metis \<open>(i + 4 * clk_period) mod clk_period = 0\<close> assms(3) assms(4) diff_add_0 diff_add_inverse
dvd_add_left_iff dvd_antisym less_imp_add_positive less_nat_zero_code mod_0_imp_dvd nat_diff_split_asm numeral_plus_numeral semiring_norm(5))
qed
hence "\<not> is_posedge2 (snd tw') CLK (i + 4 * clk_period - 2)"
using ** by auto
moreover have "Inv_core (i + 4 * clk_period - 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
ultimately show ?thesis
unfolding inv_reg_alt_def comp_def snd_conv fst_conv
using diff_diff_left nat_1_add_1 by presburger
qed
ultimately have "0 < ubin_of COUNTER at_time i + 4 * clk_period - 1 on tw'"
by auto
moreover have "ubin_of COUNTER at_time (i + 4 * clk_period - 1) on tw' \<le> 7"
using ubin_counter_atmost[OF `wityping \<Gamma> (snd tw')`] by auto
ultimately have "(ubin_of COUNTER at_time (i + 4 * clk_period - 1) on tw' - 1) mod 8 = ubin_of COUNTER at_time (i + 4 * clk_period - 1) on tw' - 1"
by (auto intro!: int_mod_eq')
hence "ubin_of COUNTER at_time (i + 4 * clk_period - 1) on tw' = 2"
using `(ubin_of COUNTER at_time (i + 4 * clk_period - 1) on tw' - 1) mod 8 = 1` by auto
\<comment> \<open> obtaining frac\<close>
have "bin_of NEXT_FRAC at_time (i + 4 * clk_period) on tw' = approx_fourth"
proof -
have "Inv_core (i + 4 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
hence "inv_nfrac (i + 4 * clk_period, snd tw')"
by auto
thus ?thesis
using `ubin_of COUNTER at_time i + 4 * clk_period - 1 on tw' = 2`
unfolding inv_nfrac_alt_def comp_def snd_conv fst_conv by auto
qed
hence "bin_of FRAC at_time (i + 5 * clk_period - 1) on tw' = approx_fourth"
using \<open>wline_of tw' FRAC (i + 4 * clk_period + 1) = wline_of tw' FRAC (i + 5 * clk_period - 1)\<close>
\<open>wline_of tw' NEXT_FRAC (i + 4 * clk_period) = wline_of tw' FRAC (i + 4 * clk_period + 1)\<close> by
auto
have "bin_of TERM1 at_time (i + 5 * clk_period - 1) on tw' = sbintrunc 63
(bin_of COMMON at_time (i + 5 * clk_period - 2) on tw' * bin_of ACCUM at_time (i + 5 * clk_period - 2) on tw')"
proof -
have "Inv_core (i + 5 * clk_period - 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
thus ?thesis
unfolding inv_term1_def comp_def snd_conv fst_conv by (metis diff_diff_left one_add_one)
qed
have "Fixed (word_of_int (bin_of FRAC at_time i + 5 * clk_period - 1 on tw')) = Fixed ((word_of_int approx_fourth) :: (1 + 31) word)"
using `bin_of FRAC at_time i + 5 * clk_period - 1 on tw' = approx_fourth` by auto
have "((word_of_int approx_fourth) :: (1 + 31) word) = (approx_fourth :: (1 + 31) word)"
unfolding word_uint.inverse_norm by eval
hence "Fixed ((word_of_int approx_fourth) :: (1 + 31) word) = Fixed (approx_fourth :: (1 + 31) word)"
by auto
also have "... = approx_div_fact 2"
by (simp add: numeral_2_eq_2)
finally have "Fixed (word_of_int (bin_of FRAC at_time i + 5 * clk_period - 1 on tw')) = approx_div_fact 2"
using `Fixed (word_of_int (bin_of FRAC at_time i + 5 * clk_period - 1 on tw')) = Fixed ((word_of_int approx_fourth) :: (1 + 31) word)`
by auto
moreover have "Fixed (word_of_int (bin_of FRAC at_time i + 5 * clk_period - 1 on tw')) = (fixed_of_sval (wline_of tw' FRAC (i + 5 * clk_period - 1)) :: (1,31) fixed)"
proof -
have "type_of (wline_of tw' FRAC (i + 5 * clk_period - 1)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
hence "length (lval_of (wline_of tw' FRAC (i + 5 * clk_period - 1))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
hence "Fixed (word_of_int (bin_of FRAC at_time i + 5 * clk_period - 1 on tw')) =
Fixed (word_of_int (sbintrunc (LENGTH((1+31)) - 1) (bl_to_bin (lval_of (wline_of tw' FRAC (i + 5 * clk_period - 1))))))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (bl_to_bin (lval_of (wline_of tw' FRAC (i + 5 * clk_period - 1)))) :: (1 + 31) word)"
unfolding word_sbin.Abs_norm by auto
also have "... = fixed_of_sval (wline_of tw' FRAC (i + 5 * clk_period - 1))"
proof -
have "wline_of tw' FRAC (i + 5 * clk_period - 1) = Lv Sig (lval_of (wline_of tw' FRAC (i + 5 * clk_period - 1)))"
using `type_of (wline_of tw' FRAC (i + 5 *clk_period - 1)) = Lty Sig 32`
by (metis (no_types, hide_lams) ty.distinct(1) ty.inject type_of.cases type_of.simps(1) type_of.simps(2) val.sel(3))
thus ?thesis
using fixed_of_sval.simps unfolding of_bl_def by smt
qed
finally show ?thesis
by auto
qed
ultimately have "(fixed_of_sval (wline_of tw' FRAC (i + 5 * clk_period - 1)) :: (1,31) fixed) = approx_div_fact 2"
by auto
\<comment> \<open> obtaining accum\<close>
have "bin_of NEXT_ACCUM at_time (i + 5 * clk_period) on tw' =
sbintrunc 31 (bin_of FRAC at_time i + 5 * clk_period - 1 on tw' + (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 5 * clk_period - 1)) {1 .. 32})))"
proof -
have "Inv_core (i + 5 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
thus ?thesis
using `wline_of tw' STATE (i + 5 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 5 *clk_period - 1))`
unfolding inv_naccum_alt_def comp_def snd_conv fst_conv by auto
qed
hence "bin_of ACCUM at_time (i + 5 * clk_period + 1) on tw' =
sbintrunc 31 (bin_of FRAC at_time i + 5 * clk_period - 1 on tw' + (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 5 * clk_period - 1)) {1 .. 32})))"
using `wline_of tw' NEXT_ACCUM (i + 5 * clk_period) = wline_of tw' ACCUM (i + 5* clk_period + 1)`
by auto
hence "(word_of_int (bin_of ACCUM at_time i + 5 * clk_period + 1 on tw') :: (1 + 31) word) = word_of_int (sbintrunc 31 (bin_of FRAC at_time i + 5 * clk_period - 1 on tw' + (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 5 * clk_period - 1)) {1 .. 32}))))"
by auto
also have "... = word_of_int (sbintrunc (LENGTH((1 + 31)) - 1) (bin_of FRAC at_time i + 5 * clk_period - 1 on tw' + (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 5 * clk_period - 1)) {1 .. 32}))))"
by auto
also have "... = word_of_int (bin_of FRAC at_time i + 5 * clk_period - 1 on tw' + (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 5 * clk_period - 1)) {1 .. 32})))"
unfolding word_sbin.Abs_norm by auto
also have "... = word_of_int (bin_of FRAC at_time i + 5 * clk_period - 1 on tw') + word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 5 * clk_period - 1)) {1 .. 32}))"
unfolding wi_hom_syms(1) by auto
finally have "(word_of_int (bin_of ACCUM at_time i + 5 * clk_period + 1 on tw') :: (1 + 31) word) =
word_of_int (bin_of FRAC at_time i + 5 * clk_period - 1 on tw') + word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 5 * clk_period - 1)) {1 .. 32}))"
by auto
hence "Fixed (word_of_int (bin_of ACCUM at_time i + 5 * clk_period + 1 on tw') :: (1 + 31) word) =
Fixed (word_of_int (bin_of FRAC at_time i + 5 * clk_period - 1 on tw')) + Fixed (word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 5 * clk_period - 1)) {1 .. 32})))"
unfolding plus_fixed.abs_eq by auto
have "Fixed (word_of_int (bin_of ACCUM at_time i + 5 * clk_period + 1 on tw') :: (1 + 31) word) = fixed_of_sval (wline_of tw' ACCUM (i + 5 * clk_period + 1))"
(is "?lhs3 = ?rhs3")
proof -
have "type_of (wline_of tw' ACCUM (i + 5 * clk_period + 1)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
hence "length (lval_of (wline_of tw' ACCUM (i + 5 * clk_period + 1))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
hence "?lhs3 = Fixed (word_of_int (sbintrunc (LENGTH((1+31)) - 1) (bl_to_bin (lval_of (wline_of tw' ACCUM (i + 5 * clk_period + 1))))))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (bl_to_bin (lval_of (wline_of tw' ACCUM (i + 5 * clk_period + 1)))))"
unfolding word_sbin.Abs_norm by auto
also have "... = fixed_of_sval (wline_of tw' ACCUM (i + 5 * clk_period + 1))"
proof -
have "wline_of tw' ACCUM (i + 5 * clk_period + 1) = Lv Sig (lval_of (wline_of tw' ACCUM (i + 5 * clk_period + 1)))"
using `type_of (wline_of tw' ACCUM (i + 5 * clk_period + 1)) = Lty Sig 32`
by (metis (no_types, hide_lams) ty.distinct(1) ty.inject type_of.cases type_of.simps(1) type_of.simps(2) val.sel(3))
thus ?thesis
using fixed_of_sval.simps unfolding of_bl_def by smt
qed
finally show ?thesis
by auto
qed
have "(word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 5 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word) =
word_of_int (sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 5 * clk_period - 2)))) :: (1 + 31) word ) *
sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' ACCUM (i + 5 * clk_period - 2)))) :: (1 + 31) word) div 2 ^ 31)"
proof -
have "(word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 5 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word)=
word_of_int
(sbintrunc (length (nths (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1))) {1..32}) - 1) (bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1))) {1..32})))"
unfolding sbl_to_bin_alt_def by auto
moreover have "(length (nths (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1))) {1..32}) - 1) = 31"
proof -
have "type_of (wline_of tw' TERM1 (i + 5 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
have "card {1::nat ..32} = 32"
unfolding card_atLeastAtMost by auto
show ?thesis
unfolding length_nths *
using card_slice[where len="64" and l=62 and r="31"] by auto
qed
ultimately have "(word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 5 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word) =
word_of_int (sbintrunc 31 (bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1))) {1..32})))"
by auto
also have "... = word_of_int (sbintrunc (LENGTH(1+31) - 1) (bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1))) {1..32})))"
by auto
also have "... = (word_of_int (bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1))) {1..32})) :: (1 + 31) word) "
unfolding word_sbin.Abs_norm by auto
finally have "word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 5 * clk_period - 1)) {1 .. 32})) =
(word_of_int ( bl_to_bin (nths (lof_wline tw' TERM1 (i + 5 * clk_period - 1)) {1 .. 32})) :: (1+31) word)"
by auto
have interval: "{1 :: nat .. 32} = {1 :: nat ..< 33}"
by auto
have nths: "\<And>xs:: bool list. nths xs {1 :: nat .. 32} = drop 1 (take 33 xs)"
unfolding interval nths_from_upt_eq_drop_take[where m="1" and n="33"] by auto
have " bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1))) {1 ..32}) =
bl_to_bin (drop 1 (take 33 (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1)))))"
using nths[of "(lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1)))"] by auto
also have "... = bintrunc (length (take 33 (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1)))) - 1) (bl_to_bin (take 33 (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1)))))"
unfolding bl2bin_drop by auto
also have "... = bintrunc 32 (bl_to_bin (take 33 (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1)))))"
proof-
have "type_of (wline_of tw' TERM1 (i + 5 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
hence " length (take 33 (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1)))) = 33"
unfolding length_take by auto
thus ?thesis
by auto
qed
also have "... = bintrunc 32 (bl_to_bin (take (length (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1))) - 31) (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1)))))"
proof-
have "type_of (wline_of tw' TERM1 (i + 5 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
thus ?thesis
by auto
qed
also have "... = bintrunc 32 ((bin_rest ^^ 31) (bl_to_bin (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1)))))"
unfolding take_rest_bl2bin by auto
finally have "bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1))) {1 ..32}) =
bintrunc 32 ((bin_rest ^^ 31) (bl_to_bin (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1)))))"
by auto
have "(word_of_int (bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1))) {1 ..32})) :: (1+31) word)=
word_of_int (bintrunc 32 ((bin_rest ^^ 31) (bl_to_bin (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1))))))"
using \<open>bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1))) {1..32}) = bintrunc 32 ((bin_rest ^^ 31) (bl_to_bin (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1)))))\<close> by auto
\<comment> \<open>push bintrunc 32 inside\<close>
also have "... = word_of_int ((bin_rest ^^ 31) (bintrunc 63 (bl_to_bin (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1))))))"
using bin_rest_power_trunc[where n="63" and k="31", symmetric] by auto
also have "... = word_of_int ((bin_rest ^^ 31) (bl_to_bin (drop 1 (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1))))))"
proof -
have "type_of (wline_of tw' TERM1 (i + 5 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
thus ?thesis
using bl2bin_drop by auto
qed
\<comment> \<open>pull bl_to_bin to left\<close>
also have "... = word_of_int (bl_to_bin ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1))))))"
unfolding butlast_pow_rest_bl2bin[symmetric] by auto
\<comment> \<open>change to sbl_to_bin\<close>
also have "... = (word_of_int (sbintrunc (LENGTH(1+31) - 1) (bl_to_bin ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1))))))) :: (1 + 31) word)"
unfolding word_sbin.Abs_norm by auto
also have "... = word_of_int (sbl_to_bin ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1))))))"
proof -
have "type_of (wline_of tw' TERM1 (i + 5 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
have "length ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1))))) = 32"
unfolding butlast_power length_take length_drop * by eval
hence "(word_of_int (sbintrunc (LENGTH(1+31) - 1) (bl_to_bin ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1))))))) :: (1 + 31) word) =
(word_of_int (sbintrunc (length ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1))))) - 1) (bl_to_bin ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1))))))) :: (1 + 31) word)"
by auto
thus ?thesis
using sbl_to_bin_alt_def by auto
qed
\<comment> \<open>push sbl_to_bin back to right\<close>
also have "... = word_of_int ((bin_rest ^^ 31) (sbl_to_bin (drop 1 (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1))))))"
proof -
have "type_of (wline_of tw' TERM1 (i + 5 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
have "length ((drop 1 (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1))))) = 63"
unfolding length_take length_drop * by eval
hence **: "31 < length ((drop 1 (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1)))))"
by auto
show ?thesis
unfolding butlast_pow_rest_sbl2bin[OF **] by auto
qed
also have "... = word_of_int ((bin_rest ^^ 31) (sbintrunc 62 (sbl_to_bin (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1))))))"
proof -
have "type_of (wline_of tw' TERM1 (i + 5 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 5 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
thus ?thesis
using sbl2bin_drop by auto
qed
also have "... = word_of_int ((bin_rest ^^ 31) (sbintrunc 62 (bin_of COMMON at_time (i + 5 * clk_period - 2) on tw' * bin_of ACCUM at_time (i + 5 * clk_period - 2) on tw')))"
using `bin_of TERM1 at_time (i + 5 *clk_period - 1) on tw' = sbintrunc 63
(bin_of COMMON at_time (i + 5 *clk_period - 2) on tw' * bin_of ACCUM at_time (i + 5 *clk_period - 2) on tw')`
by auto
also have "... = word_of_int (sbintrunc 31 ((bin_rest ^^ 31) (bin_of COMMON at_time (i + 5 * clk_period - 2) on tw' * bin_of ACCUM at_time (i + 5 * clk_period - 2) on tw')))"
proof -
have "(31 :: nat) \<le> 62" by auto
show ?thesis
unfolding bin_rest_power_strunc[OF `31 \<le> 62`]
by auto
qed
also have "... = word_of_int (sbintrunc (LENGTH(1 + 31) - 1) ((bin_rest ^^ 31) (bin_of COMMON at_time (i + 5 * clk_period - 2) on tw' * bin_of ACCUM at_time (i + 5 * clk_period - 2) on tw')))"
by auto
also have "... = word_of_int ((bin_rest ^^ 31) (bin_of COMMON at_time (i + 5 * clk_period - 2) on tw' * bin_of ACCUM at_time (i + 5 * clk_period - 2) on tw'))"
unfolding word_sbin.Abs_norm by auto
also have "... = word_of_int ((bin_of COMMON at_time (i + 5 * clk_period - 2) on tw' * bin_of ACCUM at_time (i + 5 * clk_period - 2) on tw') div 2 ^ 31)"
unfolding bin_rest_compow by auto
also have "... = word_of_int (sbintrunc (length (lval_of (wline_of tw' COMMON (i + 5 * clk_period - 2))) - 1) (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 5 * clk_period - 2)))) *
sbintrunc (length (lval_of (wline_of tw' ACCUM (i + 5 * clk_period - 2))) - 1) (sbl_to_bin (lval_of (wline_of tw' ACCUM (i + 5 * clk_period - 2)))) div 2 ^ 31)"
using sbl_to_bin_alt_def2 by auto
also have "... = word_of_int (sbintrunc (LENGTH(1 + 31) - 1) (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 5 * clk_period - 2)))) *
sbintrunc (LENGTH(1 + 31) - 1) (sbl_to_bin (lval_of (wline_of tw' ACCUM (i + 5 * clk_period - 2)))) div 2 ^ 31)"
proof -
have "type_of (wline_of tw' COMMON (i + 5 * clk_period - 2)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' COMMON (i + 5 * clk_period - 2))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
have "type_of (wline_of tw' ACCUM (i + 5 * clk_period - 2)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence **: "length (lval_of (wline_of tw' ACCUM (i + 5 * clk_period - 2))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
with * show ?thesis
by auto
qed
also have "... = word_of_int (sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 5 * clk_period - 2)))) :: (1 + 31) word) *
sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' ACCUM (i + 5 * clk_period - 2)))) :: (1 + 31) word ) div 2 ^ 31)"
unfolding sint_sbintrunc' by auto
finally show ?thesis
unfolding `(word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 5 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word) =
(word_of_int ( bl_to_bin (nths (lof_wline tw' TERM1 (i + 5 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word)`
by auto
qed
hence "Fixed (word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 5 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word) =
Fixed (word_of_int (sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 5 * clk_period - 2)))) :: (1 + 31) word ) *
sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' ACCUM (i + 5 * clk_period - 2)))) :: (1 + 31) word) div 2 ^ 31))"
by auto
also have "... = Fixed (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 5 * clk_period - 2))))) * Fixed (word_of_int (sbl_to_bin (lval_of (wline_of tw' ACCUM (i + 5 * clk_period - 2)))))"
using times_fixed.abs_eq[where xa="word_of_int (bin_of COMMON at_time i + 5 * clk_period - 2 on tw') :: (1 + 31) word" and
x="word_of_int (bin_of ACCUM at_time i + 5 * clk_period - 2 on tw') :: (1 + 31) word", symmetric]
by auto
also have "... = fixed_of_sval (wline_of tw' COMMON (i + 5 * clk_period - 2)) * fixed_of_sval (wline_of tw' ACCUM (i + 5 * clk_period - 2))"
proof -
have "type_of (wline_of tw' COMMON (i + 5 * clk_period - 2)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
hence "length (lval_of (wline_of tw' COMMON (i + 5 * clk_period - 2))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
hence "Fixed (word_of_int (bin_of COMMON at_time i + 5 * clk_period - 2 on tw')) =
Fixed (word_of_int (sbintrunc (LENGTH((1+31)) - 1) (bl_to_bin (lval_of (wline_of tw' COMMON (i + 5 * clk_period - 2))))))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (bl_to_bin (lval_of (wline_of tw' COMMON (i + 5 * clk_period - 2)))) :: (1 + 31) word)"
unfolding word_sbin.Abs_norm by auto
also have "... = fixed_of_sval (wline_of tw' COMMON (i + 5 * clk_period - 2))"
proof -
have "wline_of tw' COMMON (i + 5 * clk_period - 2) = Lv Sig (lval_of (wline_of tw' COMMON (i + 5 * clk_period - 2)))"
using `type_of (wline_of tw' COMMON (i + 5 *clk_period - 2)) = Lty Sig 32`
by (metis (no_types, hide_lams) ty.distinct(1) ty.inject type_of.cases type_of.simps(1) type_of.simps(2) val.sel(3))
thus ?thesis
using fixed_of_sval.simps unfolding of_bl_def by smt
qed
finally have "Fixed (word_of_int (bin_of COMMON at_time i + 5 * clk_period - 2 on tw') :: (1 + 31) word) = fixed_of_sval (wline_of tw' COMMON (i + 5 * clk_period - 2))"
by auto
have "type_of (wline_of tw' ACCUM (i + 5 * clk_period - 2)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
hence "length (lval_of (wline_of tw' ACCUM (i + 5 * clk_period - 2))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
hence "Fixed (word_of_int (bin_of ACCUM at_time i + 5 * clk_period - 2 on tw')) =
Fixed (word_of_int (sbintrunc (LENGTH((1+31)) - 1) (bl_to_bin (lval_of (wline_of tw' ACCUM (i + 5 * clk_period - 2))))))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (bl_to_bin (lval_of (wline_of tw' ACCUM (i + 5 * clk_period - 2)))) :: (1 + 31) word)"
unfolding word_sbin.Abs_norm by auto
also have "... = fixed_of_sval (wline_of tw' ACCUM (i + 5 * clk_period - 2))"
proof -
have "wline_of tw' ACCUM (i + 5 * clk_period - 2) = Lv Sig (lval_of (wline_of tw' ACCUM (i + 5 * clk_period - 2)))"
using `type_of (wline_of tw' ACCUM (i + 5 *clk_period - 2)) = Lty Sig 32`
by (metis (no_types, hide_lams) ty.distinct(1) ty.inject type_of.cases type_of.simps(1) type_of.simps(2) val.sel(3))
thus ?thesis
using fixed_of_sval.simps unfolding of_bl_def by smt
qed
finally have "Fixed (word_of_int (bin_of ACCUM at_time i + 5 * clk_period - 2 on tw') :: (1 + 31) word) = fixed_of_sval (wline_of tw' ACCUM (i + 5 * clk_period - 2))"
by auto
thus ?thesis
using \<open>Fixed (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 5 * clk_period - 2))))) = fixed_of_sval (wline_of tw' COMMON (i + 5 * clk_period - 2))\<close> by auto
qed
finally have "Fixed (word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 5 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word) =
fixed_of_sval (wline_of tw' COMMON (i + 5 * clk_period - 2)) * fixed_of_sval (wline_of tw' ACCUM (i + 5 * clk_period - 2))"
by auto
hence "fixed_of_sval (wline_of tw' ACCUM (i + 5 * clk_period + 1)) =
approx_div_fact 2 + fixed_of_sval (wline_of tw' COMMON (i + 5 * clk_period - 2)) * fixed_of_sval (wline_of tw' ACCUM (i + 5 * clk_period - 2))"
using `?lhs3 = ?rhs3`
`Fixed (word_of_int (bin_of ACCUM at_time i + 5 * clk_period + 1 on tw') :: (1 + 31) word) =
Fixed (word_of_int (bin_of FRAC at_time i + 5 * clk_period - 1 on tw')) + Fixed (word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 5 * clk_period - 1)) {1 .. 32})))`
`Fixed (word_of_int (bin_of FRAC at_time i + 5 * clk_period - 1 on tw')) = approx_div_fact 2`
by auto
hence "fixed_of_sval (wline_of tw' ACCUM (fst tw')) = approx_div_fact 0 +
fixed_of_sval (wline_of tw' COMMON (i + 5 * clk_period - 2)) * (approx_div_fact 1 +
fixed_of_sval (wline_of tw' COMMON (i + 5 * clk_period - 2)) * (approx_div_fact 2 +
fixed_of_sval (wline_of tw' COMMON (i + 5 * clk_period - 2)) * fixed_of_sval (wline_of tw' ACCUM (i + 5 * clk_period - 2))))"
using `fixed_of_sval (wline_of tw' ACCUM (fst tw')) = approx_div_fact 0 +
fixed_of_sval (wline_of tw' COMMON (i + 6 * clk_period - 2)) * (approx_div_fact 1 +
fixed_of_sval (wline_of tw' COMMON (i + 6 * clk_period - 2)) * fixed_of_sval (wline_of tw' ACCUM (i + 6 * clk_period - 2)))`
`wline_of tw' COMMON (i + 5 * clk_period - 2) = wline_of tw' COMMON (i + 5 * clk_period - 1)`
`(fixed_of_sval (wline_of tw' COMMON (i + 6 * clk_period - 2)) :: (1,31) fixed) = fixed_of_sval (wline_of tw' COMMON (i + 5 * clk_period - 1))`
`wline_of tw' ACCUM (i + 5 * clk_period + 1) = wline_of tw' ACCUM (i + 6 * clk_period - 2)`
by auto
\<comment> \<open> obtaining common and accum\<close>
have "wline_of tw' COMMON (i + 4 * clk_period + 1) = wline_of tw' COMMON (i + 5 * clk_period - 2)"
and "wline_of tw' ACCUM (i + 4 * clk_period + 1) = wline_of tw' ACCUM (i + 5 * clk_period - 2)"
proof -
have a: "fst tw \<le> i + 4 * clk_period + 1"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] by auto
have b: "i + 4 * clk_period + 1 \<le> i + 5 * clk_period - 2"
using assms by (auto simp add: field_simps)
have c: "i + 5 * clk_period - 2 \<le> i + 7 * clk_period + 1"
by auto
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms
unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using \<open>\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0\<close> assms by blast
hence "(i + 4 * clk_period) mod clk_period = 0"
by auto
hence "(i + 5 * clk_period) mod clk_period = 0"
by auto
have d: "\<And>k. i + 4 * clk_period + 1 \<le> k \<Longrightarrow> k \<le> i + 5 * clk_period - 1 \<Longrightarrow> \<not> is_posedge2 (snd tw') CLK k"
proof -
fix n
obtain m1 where "i + 4 * clk_period = m1 * clk_period"
using `(i + 4 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 5 * clk_period = (m1 + 1) * clk_period"
proof -
obtain m2 where "i + 5 * clk_period = m2 * clk_period"
using `(i + 5 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 6 * clk_period - (i + 5 * clk_period) = clk_period"
by (auto simp add: field_simps)
hence "m2 * clk_period - m1 * clk_period = clk_period"
using `i + 4 * clk_period = m1 * clk_period` `i + 5 * clk_period = m2 * clk_period`
by auto
hence "(m2 - m1) * clk_period = clk_period"
by (auto simp add: algebra_simps)
hence "m2 = Suc m1"
using `3 < clk_period ` by auto
thus ?thesis
using Suc_eq_plus1 \<open>i + 5 * clk_period = m2 * clk_period\<close> by presburger
qed
assume "i + 4 * clk_period + 1 \<le> n" and "n \<le> i + 5 * clk_period - 1"
hence "m1 * clk_period < n"
using `i + 4 * clk_period = m1 * clk_period` by linarith
have "n mod clk_period \<noteq> 0"
proof -
have "n div clk_period = m1"
apply (rule Misc_Arithmetic.sdl)
using \<open>m1 * clk_period < n\<close> apply (simp add: mult.commute)
using `n \<le> i + 5 * clk_period - 1` `i + 5 * clk_period = (m1 + 1) * clk_period` assms
by (auto simp add: field_simps)
hence "n = m1 * clk_period + n mod clk_period"
by auto
moreover have "n mod clk_period < clk_period"
using assms by (auto intro!: mod_less_divisor)
ultimately show ?thesis
using \<open>m1 * clk_period < n\<close> by linarith
qed
hence "\<not> is_posedge2 w CLK n"
using \<open>\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0\<close> by auto
thus "\<not> is_posedge2 (snd tw') CLK n"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
qed
show "wline_of tw' COMMON (i + 4 * clk_period + 1) = wline_of tw' COMMON (i + 5 * clk_period - 2)"
and "wline_of tw' ACCUM (i + 4 * clk_period + 1) = wline_of tw' ACCUM (i + 5 * clk_period - 2)"
using registers_unchanged_no_rising_edge[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)` a b c d]
by auto
qed
have "Inv_core (i + 4 * clk_period + 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
have "is_posedge2 (snd tw') CLK (i + 4 * clk_period)"
proof -
have "is_posedge2 w CLK (i + 6 * clk_period)"
using `is_posedge2 (snd tw') CLK (i + 6 * clk_period)`
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
hence "is_posedge2 w CLK (i + 5 * clk_period - clk_period)"
using assms by auto
hence "is_posedge2 w CLK (i + 4 * clk_period)"
by (auto simp add:field_simps)
thus "is_posedge2 (snd tw') CLK (i + 4 * clk_period)"
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
qed
have "wline_of tw' RST (i + 4 * clk_period) = Bv False"
proof (rule ccontr)
assume "wline_of tw' RST (i + 4 * clk_period) \<noteq> Bv False"
have "wityping \<Gamma> (snd tw')"
using `wityping \<Gamma> (snd tw)` world_sim_fin_preserves_wityping[OF 0]
using conc_stmt_wf_arch cwt_arch nonneg_delay_conc_architecture by blast
hence "type_of (wline_of tw' RST (i + 4 * clk_period)) = Bty"
unfolding wityping_def wtyping_def using cosine_locale_axioms unfolding cosine_locale_def by auto
hence "wline_of tw' RST (i + 4 * clk_period) = Bv True"
using `wline_of tw' RST (i + 4 * clk_period) \<noteq> Bv False` type_of_bty_cases by blast
hence "wline_of tw' STATE (i + 4 * clk_period + 1) = V_INIT"
using `Inv_core ((i + 4 * clk_period + 1, snd tw'))` `is_posedge2 (snd tw') CLK (i + 4 * clk_period)` unfolding inv_reg_alt_def
comp_def snd_conv fst_conv by auto
with `wline_of tw' STATE (i + 4 * clk_period + 1) = V_PROC` show False
by auto
qed
have "wline_of tw' NEXT_COMMON (i + 4 * clk_period) = wline_of tw' COMMON (i + 4 * clk_period + 1)"
and "wline_of tw' NEXT_ACCUM (i + 4 * clk_period) = wline_of tw' ACCUM (i + 4 * clk_period + 1)"
using `Inv_core (i + 4 * clk_period + 1, snd tw')` `is_posedge2 (snd tw') CLK (i + 4 * clk_period)` `wline_of tw' RST (i + 4 * clk_period) = Bv False`
unfolding inv_reg_alt_def comp_def snd_conv fst_conv by auto
have "bin_of COMMON at_time (i + 4 * clk_period - 1) on tw' = bin_of NEXT_COMMON at_time (i + 4 * clk_period) on tw'"
proof -
have "Inv_core (i + 4 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
thus ?thesis
using `wline_of tw' STATE (i + 4 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 4 * clk_period - 1))`
unfolding inv_ncommon_alt_def comp_def snd_conv fst_conv by auto
qed
have "(fixed_of_sval (wline_of tw' COMMON (i + 5 * clk_period - 2)) :: (1,31) fixed) = fixed_of_sval (wline_of tw' COMMON (i + 4 * clk_period - 1))"
proof -
have typof2: "type_of (wline_of tw' COMMON (i + 4 * clk_period - 1)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
then obtain bs2 where " wline_of tw' COMMON (i + 4 * clk_period - 1) = Lv Sig bs2 \<and> length bs2 = 32"
using type_of.elims[OF typof2] by fastforce
have typof: "type_of (wline_of tw' COMMON (i + 5 * clk_period - 2)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
then obtain bs1 where " wline_of tw' COMMON (i + 5 * clk_period - 2) = Lv Sig bs1 \<and> length bs1 = 32"
using type_of.elims[OF typof] by fastforce
hence "fixed_of_sval (wline_of tw' COMMON (i + 5 * clk_period - 2)) = Fixed (of_bl bs1 :: (1 + 31) word)"
using fixed_of_sval.simps by auto
also have "... = Fixed (word_of_int (bl_to_bin bs1) :: (1 + 31) word)"
unfolding of_bl_def by auto
also have "... = Fixed (word_of_int (sbintrunc (LENGTH(1+31) - 1) (bl_to_bin bs1)))"
unfolding word_sbin.Abs_norm[symmetric, where x="bl_to_bin bs1"] by auto
also have "... = Fixed (word_of_int (sbintrunc (length bs1 - 1) (bl_to_bin bs1)))"
using `wline_of tw' COMMON (i + 5 * clk_period - 2) = Lv Sig bs1 \<and> length bs1 = 32` by auto
also have "... = Fixed (word_of_int (sbl_to_bin bs1))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (sbl_to_bin bs2))"
using `bin_of COMMON at_time (i + 4 * clk_period - 1) on tw' = bin_of NEXT_COMMON at_time (i + 4 * clk_period) on tw'`
`wline_of tw' COMMON (i + 4 * clk_period - 1) = Lv Sig bs2 \<and> length bs2 = 32`
`wline_of tw' COMMON (i + 5 * clk_period - 2) = Lv Sig bs1 \<and> length bs1 = 32`
using \<open>wline_of tw' COMMON (i + 4 * clk_period + 1) = wline_of tw' COMMON (i + 5 * clk_period - 2)\<close> \<open>wline_of tw' NEXT_COMMON (i + 4 * clk_period) = wline_of tw' COMMON (i + 4 * clk_period + 1)\<close> by auto
also have "... = Fixed (word_of_int (sbintrunc (length bs2- 1) (bl_to_bin bs2)))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (sbintrunc (LENGTH(1+31) - 1) (bl_to_bin bs2)))"
using `wline_of tw' COMMON (i + 4 * clk_period - 1) = Lv Sig bs2 \<and> length bs2 = 32` by auto
also have "... = Fixed (word_of_int (bl_to_bin bs2) :: (1 + 31) word)"
unfolding word_sbin.Abs_norm[symmetric, where x="bl_to_bin bs2"] by auto
also have "... = Fixed (of_bl bs2 :: (1 + 31) word)"
unfolding of_bl_def by auto
also have "... = fixed_of_sval (wline_of tw' COMMON (i + 4 * clk_period - 1))"
using `wline_of tw' COMMON (i + 4 * clk_period - 1) = Lv Sig bs2 \<and> length bs2 = 32`
using fixed_of_sval.simps by auto
finally show ?thesis
by auto
qed
have "wline_of tw' COMMON (i + 4 * clk_period - 2) = wline_of tw' COMMON (i + 4 * clk_period - 1)"
proof -
have "Inv_core (i + 4 * clk_period - 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms
unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence **: "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using posedge by blast
hence "(i + 4 * clk_period) mod clk_period = 0"
by auto
have "(i + 4 * clk_period - 2) mod clk_period \<noteq> 0"
proof -
have "i + 3 * clk_period < i + 4 * clk_period - 2"
using assms by (auto)
moreover have "i + 4 * clk_period - 2 < i + 6 * clk_period"
using assms by auto
ultimately show ?thesis
by (metis \<open>(i + 4 * clk_period) mod clk_period = 0\<close> assms(3) assms(4) diff_add_0 diff_add_inverse
dvd_add_left_iff dvd_antisym less_imp_add_positive less_nat_zero_code mod_0_imp_dvd nat_diff_split_asm numeral_plus_numeral semiring_norm(5))
qed
hence "\<not> is_posedge2 (snd tw') CLK (i + 4 * clk_period - 2)"
using ** by auto
thus ?thesis
using `Inv_core (i + 4 * clk_period - 1, snd tw')` unfolding inv_reg_alt_def comp_def snd_conv fst_conv
using diff_diff_left nat_1_add_1 by presburger
qed
\<comment> \<open> obtaining state\<close>
have "wline_of tw' STATE (i + 3 * clk_period + 1) = wline_of tw' STATE (i + 4 * clk_period - 1)"
proof -
have a: "fst tw \<le> i + 3 * clk_period + 1"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] by auto
have b: "i + 3 * clk_period + 1 \<le> i + 4 * clk_period - 1"
using assms by (auto simp add: field_simps)
have c: "i + 4 * clk_period - 1 \<le> i + 7 * clk_period + 1"
by auto
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms
unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using \<open>\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0\<close> assms by blast
hence "(i + 4 * clk_period) mod clk_period = 0"
by auto
hence "(i + 3 * clk_period) mod clk_period = 0"
by auto
have d: "\<And>k. i + 3 * clk_period + 1 \<le> k \<Longrightarrow> k \<le> i + 4 * clk_period - 1 \<Longrightarrow> \<not> is_posedge2 (snd tw') CLK k"
proof -
fix n
obtain m1 where "i + 3 * clk_period = m1 * clk_period"
using `(i + 3 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 4 * clk_period = (m1 + 1) * clk_period"
proof -
obtain m2 where "i + 4 * clk_period = m2 * clk_period"
using `(i + 4 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 4 * clk_period - (i + 3 * clk_period) = clk_period"
by (auto simp add: field_simps)
hence "m2 * clk_period - m1 * clk_period = clk_period"
using `i + 3 * clk_period = m1 * clk_period` `i + 4 * clk_period = m2 * clk_period`
by auto
hence "(m2 - m1) * clk_period = clk_period"
by (auto simp add: algebra_simps)
hence "m2 = Suc m1"
using `3 < clk_period ` by auto
thus ?thesis
using Suc_eq_plus1 \<open>i + 4 * clk_period = m2 * clk_period\<close> by presburger
qed
assume "i + 3 * clk_period + 1 \<le> n" and "n \<le> i + 4 * clk_period - 1"
hence "m1 * clk_period < n"
using `i + 3 * clk_period = m1 * clk_period` by linarith
have "n mod clk_period \<noteq> 0"
proof -
have "n div clk_period = m1"
apply (rule Misc_Arithmetic.sdl)
using \<open>m1 * clk_period < n\<close> apply (simp add: mult.commute)
using `n \<le> i + 4 * clk_period - 1` `i + 4 * clk_period = (m1 + 1) * clk_period` assms
by (auto simp add: field_simps)
hence "n = m1 * clk_period + n mod clk_period"
by auto
moreover have "n mod clk_period < clk_period"
using assms by (auto intro!: mod_less_divisor)
ultimately show ?thesis
using \<open>m1 * clk_period < n\<close> by linarith
qed
hence "\<not> is_posedge2 w CLK n"
using \<open>\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0\<close> by auto
thus "\<not> is_posedge2 (snd tw') CLK n"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
qed
show "wline_of tw' STATE (i + 3 * clk_period + 1) = wline_of tw' STATE (i + 4 * clk_period - 1)"
using registers_unchanged_no_rising_edge[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)` a b c d]
by auto
qed
hence "wline_of tw' STATE (i + 3 * clk_period + 1) = V_PROC"
using `wline_of tw' STATE (i + 4 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 4 * clk_period - 1))`
by auto
have "wline_of tw' FRAC (i + 3 * clk_period + 1) = wline_of tw' FRAC (i + 4 * clk_period - 1)"
and "wline_of tw' COUNTER (i + 3 * clk_period + 1) = wline_of tw' COUNTER (i + 4 * clk_period - 1)"
proof -
have a: "fst tw \<le> i + 3 * clk_period + 1"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] by auto
have b: "i + 3 * clk_period + 1 \<le> i + 4 * clk_period - 1"
using assms by (auto simp add: field_simps)
have c: "i + 4 * clk_period - 1 \<le> i + 7 * clk_period + 1"
by auto
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using \<open>\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0\<close> assms by blast
hence "(i + 4 * clk_period) mod clk_period = 0"
by auto
hence "(i + 3 * clk_period) mod clk_period = 0"
by auto
have d: "\<And>k. i + 3 * clk_period + 1 \<le> k \<Longrightarrow> k \<le> i + 4 * clk_period - 1 \<Longrightarrow> \<not> is_posedge2 (snd tw') CLK k"
proof -
fix n
obtain m1 where "i + 3 * clk_period = m1 * clk_period"
using `(i + 3 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 4 * clk_period = (m1 + 1) * clk_period"
proof -
obtain m2 where "i + 4 * clk_period = m2 * clk_period"
using `(i + 4 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 4 * clk_period - (i + 3 * clk_period) = clk_period"
by (auto simp add: field_simps)
hence "m2 * clk_period - m1 * clk_period = clk_period"
using `i + 3 * clk_period = m1 * clk_period` `i + 4 * clk_period = m2 * clk_period` by auto
hence "(m2 - m1) * clk_period = clk_period"
by (auto simp add: algebra_simps)
hence "m2 = Suc m1"
using `3 < clk_period ` by auto
thus ?thesis
using Suc_eq_plus1 \<open>i + 4 * clk_period = m2 * clk_period\<close> by presburger
qed
assume "i + 3 * clk_period + 1 \<le> n" and "n \<le> i + 4 * clk_period - 1"
hence "m1 * clk_period < n"
using `i + 3 * clk_period = m1 * clk_period` by linarith
have "n mod clk_period \<noteq> 0"
proof -
have "n div clk_period = m1"
apply (rule Misc_Arithmetic.sdl)
using \<open>m1 * clk_period < n\<close> apply (simp add: mult.commute)
using `n \<le> i + 4 * clk_period - 1` `i + 4 * clk_period = (m1 + 1) * clk_period` assms
by (auto simp add: field_simps)
hence "n = m1 * clk_period + n mod clk_period"
by auto
moreover have "n mod clk_period < clk_period"
using assms by (auto intro!: mod_less_divisor)
ultimately show ?thesis
using \<open>m1 * clk_period < n\<close> by linarith
qed
hence "\<not> is_posedge2 w CLK n"
using \<open>\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0\<close> by auto
thus "\<not> is_posedge2 (snd tw') CLK n"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
qed
show "wline_of tw' FRAC (i + 3 * clk_period + 1) = wline_of tw' FRAC (i + 4 * clk_period - 1)"
and "wline_of tw' COUNTER (i + 3 * clk_period + 1) = wline_of tw' COUNTER (i + 4 * clk_period - 1)"
using registers_unchanged_no_rising_edge[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)` a b c d] by auto
qed
have "wline_of tw' NEXT_FRAC (i + 3 * clk_period) = wline_of tw' FRAC (i + 3 * clk_period + 1)"
and "wline_of tw' NEXT_STATE (i + 3 * clk_period) = wline_of tw' STATE (i + 3 * clk_period + 1)"
and "wline_of tw' NEXT_COUNTER (i + 3 * clk_period) = wline_of tw' COUNTER (i + 3 * clk_period + 1)"
proof -
have "Inv_core (i + 3 * clk_period + 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
moreover have "is_posedge2 (snd tw') CLK (i + 3 * clk_period)"
proof -
have "is_posedge2 w CLK (i + 4 * clk_period)"
using `is_posedge2 (snd tw') CLK (i + 4 * clk_period)`
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
hence "is_posedge2 w CLK (i + 4 * clk_period - clk_period)"
using assms by auto
hence "is_posedge2 w CLK (i + 3 * clk_period)"
by (auto simp add:field_simps)
thus "is_posedge2 (snd tw') CLK (i + 3 * clk_period)"
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
qed
moreover have "wline_of tw' RST (i + 3 * clk_period) = Bv False"
proof (rule ccontr)
assume "wline_of tw' RST (i + 3 * clk_period) \<noteq> Bv False"
have "wityping \<Gamma> (snd tw')"
using `wityping \<Gamma> (snd tw)` world_sim_fin_preserves_wityping[OF 0] conc_stmt_wf_arch cwt_arch nonneg_delay_conc_architecture by blast
hence "type_of (wline_of tw' RST (i + 3 * clk_period)) = Bty"
unfolding wityping_def wtyping_def using cosine_locale_axioms unfolding cosine_locale_def by auto
hence "wline_of tw' RST (i + 3 * clk_period) = Bv True"
using `wline_of tw' RST (i + 3 * clk_period) \<noteq> Bv False` type_of_bty_cases by blast
hence "wline_of tw' STATE (i + 3 * clk_period + 1) = V_INIT"
using `Inv_core (i + 3 * clk_period + 1, snd tw')` `is_posedge2 (snd tw') CLK (i + 3 * clk_period)` unfolding inv_reg_alt_def
comp_def snd_conv fst_conv by auto
with `wline_of tw' STATE (i + 3 * clk_period + 1) = V_PROC` show False
using \<open>wline_of tw' OUTREADY_REG (get_time tw') = Bv True\<close> by auto
qed
ultimately show "wline_of tw' NEXT_FRAC (i + 3 * clk_period) = wline_of tw' FRAC (i + 3 * clk_period + 1)"
and "wline_of tw' NEXT_STATE (i + 3 * clk_period) = wline_of tw' STATE (i + 3 * clk_period + 1)"
and "wline_of tw' NEXT_COUNTER (i + 3 * clk_period) = wline_of tw' COUNTER (i + 3 * clk_period + 1)"
unfolding inv_reg_alt_def comp_def snd_conv fst_conv by auto
qed
hence "wline_of tw' NEXT_STATE (i + 3 * clk_period) = V_PROC" and "ubin_of NEXT_COUNTER at_time i + 3 * clk_period on tw' = 2"
using `wline_of tw' STATE (i + 3 * clk_period + 1) = V_PROC` `ubin_of COUNTER at_time i + 4 *clk_period - 1 on tw' = 2`
using \<open>bl_to_bin (lval_of (wline_of tw' COUNTER (i + 4 *clk_period - 1))) = 2\<close> \<open>wline_of tw' COUNTER (i + 3 * clk_period + 1) = wline_of tw' COUNTER (i + 4 *clk_period - 1)\<close> \<open>wline_of tw' NEXT_COUNTER (i + 3 * clk_period) = wline_of tw' COUNTER (i + 3 * clk_period + 1)\<close>
by auto
have "wline_of tw' STATE (i + 3 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 3 * clk_period - 1))
\<or> wline_of tw' STATE (i + 3 * clk_period - 1) = V_PRE"
proof (rule ccontr)
have "Inv_core (i + 3 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
hence inv:"inv_nstate (i + 3 * clk_period, snd tw')"
by auto
assume "\<not> (wline_of tw' STATE (i + 3 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 3 * clk_period - 1))
\<or> wline_of tw' STATE (i + 3 * clk_period - 1) = V_PRE)"
hence *: "(wline_of tw' STATE (i + 3 * clk_period - 1) = V_PROC \<Longrightarrow> \<not> bval_of (wline_of tw' CTR_NEQ_0 (i + 3 * clk_period - 1)))" and
**: "wline_of tw' STATE (i + 3 * clk_period - 1) \<noteq> V_PRE" (is "?state \<noteq> _")by auto
then consider "?state = V_INIT" | "?state = V_WAIT" | "?state = V_PROC" | "?state = V_POST"
| "?state \<noteq> V_INIT \<and> ?state \<noteq> V_WAIT \<and> ?state \<noteq> V_PRE \<and> ?state \<noteq> V_PROC \<and> ?state \<noteq> V_POST"
by auto
thus False
proof (cases)
case 1
hence "wline_of tw' NEXT_STATE (i + 3 * clk_period) \<noteq> V_PROC"
using inv unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 3 * clk_period) = V_PROC`
by auto
next
case 2
hence "wline_of tw' NEXT_STATE (i + 3 * clk_period) \<noteq> V_PROC"
using inv unfolding inv_nstate_alt_def comp_def snd_conv fst_conv
by (cases "bval_of (snd (snd tw') INREADY (i + 3 * clk_period - 1))") auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 3 * clk_period) = V_PROC`
by auto
next
case 3
hence "wline_of tw' NEXT_STATE (i + 3 * clk_period) \<noteq> V_PROC"
using inv * unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 3 * clk_period) = V_PROC`
by auto
next
case 4
hence "wline_of tw' NEXT_STATE (i + 3 * clk_period) \<noteq> V_PROC"
using inv * unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 3 * clk_period) = V_PROC`
by auto
next
case 5
hence "wline_of tw' NEXT_STATE (i + 3 * clk_period) \<noteq> V_PROC"
using inv * unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 3 * clk_period) = V_PROC`
by auto
qed
qed
moreover have "wline_of tw' STATE (i + 3 * clk_period - 1) \<noteq> V_PRE"
proof (rule ccontr)
assume "\<not> wline_of tw' STATE (i + 3 * clk_period - 1) \<noteq> V_PRE"
hence "wline_of tw' STATE (i + 3 * clk_period - 1) = V_PRE"
by auto
have "Inv_core (i + 3 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
hence "bintrunc 3 (bl_to_bin (lval_of (wline_of (i + 3 * clk_period, snd tw') COUNTER (get_time (i + 3 * clk_period, snd tw') - 1))) - 1) = 2"
using `wline_of tw' STATE (i + 3 * clk_period - 1) = V_PRE` `ubin_of NEXT_COUNTER at_time (i + 3 * clk_period) on tw' = 2`
unfolding inv_ncounter_alt_def comp_def snd_conv fst_conv by auto
hence "bintrunc 3 (ubin_of COUNTER at_time (i + 3 * clk_period - 1) on tw' - 1) = 2"
unfolding fst_conv comp_def snd_conv by auto
have "is_posedge2 (snd tw') CLK (i + 3 * clk_period)"
proof -
have "is_posedge2 w CLK (i + 4 * clk_period)"
using `is_posedge2 (snd tw') CLK (i + 4 * clk_period)`
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
hence "is_posedge2 w CLK (i + 4 * clk_period - clk_period)"
using assms by auto
hence "is_posedge2 w CLK (i + 3 * clk_period)"
by (auto simp add:field_simps)
thus "is_posedge2 (snd tw') CLK (i + 3 * clk_period)"
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
qed
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms
unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 3 * clk_period) mod clk_period = 0"
using \<open>\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0\<close> `is_posedge2 (snd tw') CLK (i + 3 * clk_period)` by blast
hence "(i + 2 * clk_period) mod clk_period = 0"
by auto
have fd: "\<And>k. i + 2 * clk_period + 1 \<le> k \<Longrightarrow> k \<le> i + 3 * clk_period - 1 \<Longrightarrow> \<not> is_posedge2 (snd tw') CLK k"
proof -
fix n
obtain m1 where "i + 2 * clk_period = m1 * clk_period"
using `(i + 2 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 3 * clk_period = (m1 + 1) * clk_period"
proof -
obtain m2 where "i + 3 * clk_period = m2 * clk_period"
using `(i + 3 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 3 * clk_period - (i + 2 * clk_period) = clk_period"
by (auto simp add: field_simps)
hence "m2 * clk_period - m1 * clk_period = clk_period"
using `i + 2 * clk_period = m1 * clk_period` `i + 3 * clk_period = m2 * clk_period`
by auto
hence "(m2 - m1) * clk_period = clk_period"
by (auto simp add: algebra_simps)
hence "m2 = Suc m1"
using `3 < clk_period ` by auto
thus ?thesis
using Suc_eq_plus1 \<open>i + 3 * clk_period = m2 * clk_period\<close> by presburger
qed
assume "i + 2 * clk_period + 1 \<le> n" and "n \<le> i + 3 * clk_period - 1"
hence "m1 * clk_period < n"
using `i + 2 * clk_period = m1 * clk_period` by linarith
have "n mod clk_period \<noteq> 0"
proof -
have "n div clk_period = m1"
apply (rule Misc_Arithmetic.sdl)
using \<open>m1 * clk_period < n\<close> apply (simp add: mult.commute)
using `n \<le> i + 3 * clk_period - 1` `i + 3 * clk_period = (m1 + 1) * clk_period` assms
by (auto simp add: field_simps)
hence "n = m1 * clk_period + n mod clk_period"
by auto
moreover have "n mod clk_period < clk_period"
using assms by (auto intro!: mod_less_divisor)
ultimately show ?thesis
using \<open>m1 * clk_period < n\<close> by linarith
qed
hence "\<not> is_posedge2 w CLK n"
using \<open>\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0\<close> by auto
thus "\<not> is_posedge2 (snd tw') CLK n"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
qed
have c: "wline_of tw' STATE (i + 2 * clk_period + 1) = V_PRE"
proof -
have fa: "fst tw \<le> i + 2 * clk_period + 1"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] by auto
have fb: "i + 2 * clk_period + 1 \<le> i + 3 * clk_period - 1"
using assms by (auto simp add: field_simps)
have fc: "i + 3 * clk_period - 1 \<le> i + 7 * clk_period + 1"
by auto
show ?thesis
using registers_unchanged_no_rising_edge[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)` fa fb fc fd]
`wline_of tw' STATE (i + 3 * clk_period - 1) = V_PRE` by auto
qed
moreover have b: "is_posedge2 (snd tw') CLK (i + 2 * clk_period)"
proof -
have "is_posedge2 w CLK (i + 3 * clk_period)"
using `is_posedge2 (snd tw') CLK (i + 3 * clk_period)`
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv] by auto
hence "is_posedge2 w CLK (i + 3 * clk_period - clk_period)"
using assms by auto
hence "is_posedge2 w CLK (i + 2 * clk_period)"
by (auto simp add:field_simps)
thus "is_posedge2 (snd tw') CLK (i + 2 * clk_period)"
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
qed
moreover have a: "Inv_core (i + 2 * clk_period + 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
moreover have d: "wline_of tw' RST (i + 2 * clk_period) = Bv False"
proof (rule ccontr)
assume "\<not> wline_of tw' RST (i + 2 * clk_period) = Bv False"
moreover have "type_of (wline_of tw' RST (i + 2 * clk_period)) = Bty"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
ultimately have "wline_of tw' RST (i + 2 * clk_period) = Bv True"
using type_of_bty_cases by blast
hence "wline_of tw' STATE (i + 2 * clk_period + 1) = V_INIT"
using `Inv_core (i + 2 * clk_period + 1, snd tw')` `is_posedge2 (snd tw') CLK (i + 2 * clk_period)`
unfolding inv_reg_alt_def comp_def snd_conv fst_conv by auto
with `wline_of tw' STATE (i + 2 * clk_period + 1) = V_PRE`
show False by auto
qed
ultimately have "wline_of tw' NEXT_STATE (i + 2 * clk_period) = V_PRE"
unfolding inv_reg_alt_def comp_def snd_conv fst_conv by auto
have "Inv_core (i + 2 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
hence "inv_nstate (i + 2 * clk_period, snd tw')"
by auto
have "wline_of tw' STATE (i + 2 * clk_period - 1) = V_WAIT"
proof (rule ccontr)
assume "\<not> wline_of tw' STATE (i + 2 * clk_period - 1) = V_WAIT" (is "\<not> ?state = V_WAIT")
then consider "?state = V_INIT" | "?state = V_PRE" | "?state = V_PROC" | "?state = V_POST"
| "?state \<noteq> V_INIT \<and> ?state \<noteq> V_WAIT \<and> ?state \<noteq> V_PRE \<and> ?state \<noteq> V_PROC \<and> ?state \<noteq> V_POST"
by auto
hence "wline_of tw' NEXT_STATE (i + 2 * clk_period) \<noteq> V_PRE"
proof (cases)
case 1
then show ?thesis
using `inv_nstate (i + 2 * clk_period, snd tw')` unfolding inv_nstate_alt_def
by auto
next
case 2
then show ?thesis
using `inv_nstate (i + 2 * clk_period, snd tw')` unfolding inv_nstate_alt_def
by auto
next
case 3
then show ?thesis
using `inv_nstate (i + 2 * clk_period, snd tw')` unfolding inv_nstate_alt_def
apply (cases "bval_of (wline_of (i + 2 * clk_period, snd tw') CTR_NEQ_0 (get_time (i + 2 * clk_period, snd tw') - 1))")
by auto
next
case 4
then show ?thesis
using `inv_nstate (i + 2 * clk_period, snd tw')` unfolding inv_nstate_alt_def
by auto
next
case 5
then show ?thesis
using `inv_nstate (i + 2 * clk_period, snd tw')` unfolding inv_nstate_alt_def
by (auto)
qed
thus False
using \<open>wline_of tw' NEXT_STATE (i + 2 * clk_period) = V_PRE\<close> by blast
qed
moreover have "bval_of (wline_of tw' INREADY (i + 2 * clk_period - 1))"
proof (rule ccontr)
assume "\<not> bval_of (wline_of tw' INREADY (i + 2 * clk_period - 1))"
hence "wline_of tw' NEXT_STATE (i + 2 * clk_period) = V_WAIT"
using `Inv_core (i + 2 * clk_period, snd tw')` `wline_of tw' STATE (i + 2 * clk_period - 1) = V_WAIT`
unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
thus False
using `wline_of tw' NEXT_STATE (i + 2 * clk_period) = V_PRE` by auto
qed
ultimately have "ubin_of NEXT_COUNTER at_time i + 2 * clk_period on tw' = 4"
using `Inv_core (i + 2 * clk_period, snd tw')`
unfolding inv_ncounter_alt_def comp_def snd_conv fst_conv by auto
hence "ubin_of COUNTER at_time i + 2 * clk_period + 1 on tw' = 4"
using a b d unfolding inv_reg_alt_def comp_def snd_conv fst_conv by auto
hence "ubin_of COUNTER at_time i + 3 * clk_period - 1 on tw' = 4"
proof -
have *: "get_time tw \<le> i + 2 * clk_period + 1"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] by auto
have **: "i + 2 * clk_period + 1 \<le> i + 3 * clk_period - 1"
using assms by auto
have "wline_of tw' COUNTER (i + 2 * clk_period + 1) = wline_of tw' COUNTER (i + 3 * clk_period - 1)"
using registers_unchanged_no_rising_edge[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)` * ** _ fd]
using assms by (auto)
thus ?thesis
using \<open>bl_to_bin (lval_of (wline_of tw' COUNTER (i + 2 * clk_period + 1))) = 4\<close> by auto
qed
with `bintrunc 3 (ubin_of COUNTER at_time (i + 3 * clk_period - 1) on tw' - 1) = 2`
show False
by auto
qed
ultimately have "wline_of tw' STATE (i + 3 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 3 * clk_period - 1))"
by auto
\<comment> \<open>obtaining counter value\<close>
have "bintrunc 3 (ubin_of COUNTER at_time (i + 3 * clk_period - 1) on tw' - 1) = 2"
proof -
have "Inv_core (i + 3 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
thus ?thesis
using `ubin_of NEXT_COUNTER at_time (i + 3 * clk_period) on tw' = 2`
`wline_of tw' STATE (i + 3 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 3 * clk_period - 1))`
unfolding inv_ncounter_alt_def fst_conv comp_def snd_conv by auto
qed
hence "(ubin_of COUNTER at_time (i + 3 * clk_period - 1) on tw' - 1) mod 8 = 2"
unfolding bintrunc_mod2p by auto
have "0 < ubin_of COUNTER at_time i + 3 * clk_period - 2 on tw'"
proof -
have "Inv_core (i + 3 * clk_period - 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
hence "inv_n0 (i + 3 * clk_period - 1, snd tw')"
by auto
hence "0 < bl_to_bin (lval_of (snd (snd tw') COUNTER (i + 3 * clk_period - 1 - 1)))"
using `wline_of tw' STATE (i + 3 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 3 * clk_period - 1))`
unfolding inv_n0_def comp_def snd_conv fst_conv by auto
thus ?thesis
unfolding comp_def snd_conv fst_conv
by (metis diff_diff_left nat_1_add_1)
qed
moreover have "ubin_of COUNTER at_time i + 3 * clk_period - 2 on tw' = ubin_of COUNTER at_time i + 3 * clk_period - 1 on tw'"
proof -
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms
unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence **: "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using posedge by blast
hence "(i + 3 * clk_period) mod clk_period = 0"
by auto
have "(i + 3 * clk_period - 2) mod clk_period \<noteq> 0"
proof -
have "i + 2 * clk_period < i + 3 * clk_period - 2"
using assms by (auto)
moreover have "i + 2 * clk_period - 2 < i + 3 * clk_period"
using assms by auto
ultimately show ?thesis
by (metis \<open>(i + 3 * clk_period) mod clk_period = 0\<close> assms(3) assms(4) diff_add_0 diff_add_inverse
dvd_add_left_iff dvd_antisym less_imp_add_positive less_nat_zero_code mod_0_imp_dvd nat_diff_split_asm numeral_plus_numeral semiring_norm(5))
qed
hence "\<not> is_posedge2 (snd tw') CLK (i + 3 * clk_period - 2)"
using ** by auto
moreover have "Inv_core (i + 3 * clk_period - 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
ultimately show ?thesis
unfolding inv_reg_alt_def comp_def snd_conv fst_conv
using diff_diff_left nat_1_add_1 by presburger
qed
ultimately have "0 < ubin_of COUNTER at_time i + 3 * clk_period - 1 on tw'"
by auto
moreover have "ubin_of COUNTER at_time (i + 3 * clk_period - 1) on tw' \<le> 7"
using ubin_counter_atmost[OF `wityping \<Gamma> (snd tw')`] by auto
ultimately have "(ubin_of COUNTER at_time (i + 3 * clk_period - 1) on tw' - 1) mod 8 = ubin_of COUNTER at_time (i + 3 * clk_period - 1) on tw' - 1"
by (auto intro!: int_mod_eq')
hence "ubin_of COUNTER at_time (i + 3 * clk_period - 1) on tw' = 3"
using `(ubin_of COUNTER at_time (i + 3 * clk_period - 1) on tw' - 1) mod 8 = 2` by auto
\<comment> \<open> obtaining frac\<close>
have "bin_of NEXT_FRAC at_time (i + 3 *clk_period) on tw' = approx_sixth"
proof -
have "Inv_core (i + 3 *clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
hence "inv_nfrac (i + 3 *clk_period, snd tw')"
by auto
thus ?thesis
using `ubin_of COUNTER at_time i + 3 *clk_period - 1 on tw' = 3`
unfolding inv_nfrac_alt_def comp_def snd_conv fst_conv by auto
qed
hence "bin_of FRAC at_time (i + 4 * clk_period - 1) on tw' = approx_sixth"
using \<open>wline_of tw' FRAC (i + 3 * clk_period + 1) = wline_of tw' FRAC (i + 4 * clk_period - 1)\<close>
\<open>wline_of tw' NEXT_FRAC (i + 3 * clk_period) = wline_of tw' FRAC (i + 3 * clk_period + 1)\<close> by
auto
have "bin_of TERM1 at_time (i + 4 * clk_period - 1) on tw' = sbintrunc 63
(bin_of COMMON at_time (i + 4 * clk_period - 2) on tw' * bin_of ACCUM at_time (i + 4 * clk_period - 2) on tw')"
proof -
have "Inv_core (i + 4 * clk_period - 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
thus ?thesis
unfolding inv_term1_def comp_def snd_conv fst_conv by (metis diff_diff_left one_add_one)
qed
have "Fixed (word_of_int (bin_of FRAC at_time i + 4 * clk_period - 1 on tw')) = Fixed ((word_of_int approx_sixth) :: (1 + 31) word)"
using `bin_of FRAC at_time i + 4 * clk_period - 1 on tw' = approx_sixth` by auto
have "((word_of_int approx_sixth) :: (1 + 31) word) = (approx_sixth :: (1 + 31) word)"
unfolding word_uint.inverse_norm by eval
hence "Fixed ((word_of_int approx_sixth) :: (1 + 31) word) = Fixed (approx_sixth :: (1 + 31) word)"
by auto
also have "... = approx_div_fact 3"
by (simp add: numeral_3_eq_3)
finally have "Fixed (word_of_int (bin_of FRAC at_time i + 4 * clk_period - 1 on tw')) = approx_div_fact 3"
using `Fixed (word_of_int (bin_of FRAC at_time i + 4 * clk_period - 1 on tw')) = Fixed ((word_of_int approx_sixth) :: (1 + 31) word)`
by auto
moreover have "Fixed (word_of_int (bin_of FRAC at_time i + 4 * clk_period - 1 on tw')) = (fixed_of_sval (wline_of tw' FRAC (i + 4 * clk_period - 1)) :: (1,31) fixed)"
proof -
have "type_of (wline_of tw' FRAC (i + 4 * clk_period - 1)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
hence "length (lval_of (wline_of tw' FRAC (i + 4 * clk_period - 1))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
hence "Fixed (word_of_int (bin_of FRAC at_time i + 4 * clk_period - 1 on tw')) =
Fixed (word_of_int (sbintrunc (LENGTH((1+31)) - 1) (bl_to_bin (lval_of (wline_of tw' FRAC (i + 4 * clk_period - 1))))))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (bl_to_bin (lval_of (wline_of tw' FRAC (i + 4 * clk_period - 1)))) :: (1 + 31) word)"
unfolding word_sbin.Abs_norm by auto
also have "... = fixed_of_sval (wline_of tw' FRAC (i + 4 * clk_period - 1))"
proof -
have "wline_of tw' FRAC (i + 4 * clk_period - 1) = Lv Sig (lval_of (wline_of tw' FRAC (i + 4 * clk_period - 1)))"
using `type_of (wline_of tw' FRAC (i + 4 *clk_period - 1)) = Lty Sig 32`
by (metis (no_types, hide_lams) ty.distinct(1) ty.inject type_of.cases type_of.simps(1) type_of.simps(2) val.sel(3))
thus ?thesis
using fixed_of_sval.simps unfolding of_bl_def by smt
qed
finally show ?thesis
by auto
qed
ultimately have "(fixed_of_sval (wline_of tw' FRAC (i + 4 * clk_period - 1)) :: (1,31) fixed) = approx_div_fact 3"
by auto
\<comment> \<open> obtaining accum\<close>
have "bin_of NEXT_ACCUM at_time (i + 4 * clk_period) on tw' =
sbintrunc 31 (bin_of FRAC at_time i + 4 * clk_period - 1 on tw' + (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 4 * clk_period - 1)) {1 .. 32})))"
proof -
have "Inv_core (i + 4 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
thus ?thesis
using `wline_of tw' STATE (i + 4 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 4 *clk_period - 1))`
unfolding inv_naccum_alt_def comp_def snd_conv fst_conv by auto
qed
hence "bin_of ACCUM at_time (i + 4 * clk_period + 1) on tw' =
sbintrunc 31 (bin_of FRAC at_time i + 4 * clk_period - 1 on tw' + (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 4 * clk_period - 1)) {1 .. 32})))"
using `wline_of tw' NEXT_ACCUM (i + 4 * clk_period) = wline_of tw' ACCUM (i + 4 * clk_period + 1)`
by auto
hence "(word_of_int (bin_of ACCUM at_time i + 4 * clk_period + 1 on tw') :: (1 + 31) word) = word_of_int (sbintrunc 31 (bin_of FRAC at_time i + 4 * clk_period - 1 on tw' + (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 4 * clk_period - 1)) {1 .. 32}))))"
by auto
also have "... = word_of_int (sbintrunc (LENGTH((1 + 31)) - 1) (bin_of FRAC at_time i + 4 * clk_period - 1 on tw' + (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 4 * clk_period - 1)) {1 .. 32}))))"
by auto
also have "... = word_of_int (bin_of FRAC at_time i + 4 * clk_period - 1 on tw' + (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 4 * clk_period - 1)) {1 .. 32})))"
unfolding word_sbin.Abs_norm by auto
also have "... = word_of_int (bin_of FRAC at_time i + 4 * clk_period - 1 on tw') + word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 4 * clk_period - 1)) {1 .. 32}))"
unfolding wi_hom_syms(1) by auto
finally have "(word_of_int (bin_of ACCUM at_time i + 4 * clk_period + 1 on tw') :: (1 + 31) word) =
word_of_int (bin_of FRAC at_time i + 4 * clk_period - 1 on tw') + word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 4 * clk_period - 1)) {1 .. 32}))"
by auto
hence "Fixed (word_of_int (bin_of ACCUM at_time i + 4 * clk_period + 1 on tw') :: (1 + 31) word) =
Fixed (word_of_int (bin_of FRAC at_time i + 4 * clk_period - 1 on tw')) + Fixed (word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 4 * clk_period - 1)) {1 .. 32})))"
unfolding plus_fixed.abs_eq by auto
have "Fixed (word_of_int (bin_of ACCUM at_time i + 4 * clk_period + 1 on tw') :: (1 + 31) word) = fixed_of_sval (wline_of tw' ACCUM (i + 4 * clk_period + 1))"
(is "?lhs4 = ?rhs4")
proof -
have "type_of (wline_of tw' ACCUM (i + 4 * clk_period + 1)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
hence "length (lval_of (wline_of tw' ACCUM (i + 4 * clk_period + 1))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
hence "?lhs4 = Fixed (word_of_int (sbintrunc (LENGTH((1+31)) - 1) (bl_to_bin (lval_of (wline_of tw' ACCUM (i + 4 * clk_period + 1))))))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (bl_to_bin (lval_of (wline_of tw' ACCUM (i + 4 * clk_period + 1)))))"
unfolding word_sbin.Abs_norm by auto
also have "... = fixed_of_sval (wline_of tw' ACCUM (i + 4 * clk_period + 1))"
proof -
have "wline_of tw' ACCUM (i + 4 * clk_period + 1) = Lv Sig (lval_of (wline_of tw' ACCUM (i + 4 * clk_period + 1)))"
using `type_of (wline_of tw' ACCUM (i + 4 * clk_period + 1)) = Lty Sig 32`
by (metis (no_types, hide_lams) ty.distinct(1) ty.inject type_of.cases type_of.simps(1) type_of.simps(2) val.sel(3))
thus ?thesis
using fixed_of_sval.simps unfolding of_bl_def by smt
qed
finally show ?thesis
by auto
qed
have "(word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 4 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word) =
word_of_int (sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 4 * clk_period - 2)))) :: (1 + 31) word ) *
sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' ACCUM (i + 4 * clk_period - 2)))) :: (1 + 31) word) div 2 ^ 31)"
proof -
have "(word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 4 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word)=
word_of_int
(sbintrunc (length (nths (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1))) {1..32}) - 1) (bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1))) {1..32})))"
unfolding sbl_to_bin_alt_def by auto
moreover have "(length (nths (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1))) {1..32}) - 1) = 31"
proof -
have "type_of (wline_of tw' TERM1 (i + 4 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
have "card {1::nat ..32} = 32"
unfolding card_atLeastAtMost by auto
show ?thesis
unfolding length_nths *
using card_slice[where len="64" and l=62 and r="31"] by auto
qed
ultimately have "(word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 4 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word) =
word_of_int (sbintrunc 31 (bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1))) {1..32})))"
by auto
also have "... = word_of_int (sbintrunc (LENGTH(1+31) - 1) (bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1))) {1..32})))"
by auto
also have "... = (word_of_int (bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1))) {1..32})) :: (1 + 31) word) "
unfolding word_sbin.Abs_norm by auto
finally have "word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 4 * clk_period - 1)) {1 .. 32})) =
(word_of_int ( bl_to_bin (nths (lof_wline tw' TERM1 (i + 4 * clk_period - 1)) {1 .. 32})) :: (1+31) word)"
by auto
have interval: "{1 :: nat .. 32} = {1 :: nat ..< 33}"
by auto
have nths: "\<And>xs:: bool list. nths xs {1 :: nat .. 32} = drop 1 (take 33 xs)"
unfolding interval nths_from_upt_eq_drop_take[where m="1" and n="33"] by auto
have " bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1))) {1 ..32}) =
bl_to_bin (drop 1 (take 33 (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1)))))"
using nths[of "(lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1)))"] by auto
also have "... = bintrunc (length (take 33 (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1)))) - 1) (bl_to_bin (take 33 (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1)))))"
unfolding bl2bin_drop by auto
also have "... = bintrunc 32 (bl_to_bin (take 33 (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1)))))"
proof-
have "type_of (wline_of tw' TERM1 (i + 4 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
hence " length (take 33 (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1)))) = 33"
unfolding length_take by auto
thus ?thesis
by auto
qed
also have "... = bintrunc 32 (bl_to_bin (take (length (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1))) - 31) (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1)))))"
proof-
have "type_of (wline_of tw' TERM1 (i + 4 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
thus ?thesis
by auto
qed
also have "... = bintrunc 32 ((bin_rest ^^ 31) (bl_to_bin (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1)))))"
unfolding take_rest_bl2bin by auto
finally have "bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1))) {1 ..32}) =
bintrunc 32 ((bin_rest ^^ 31) (bl_to_bin (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1)))))"
by auto
have "(word_of_int (bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1))) {1 ..32})) :: (1+31) word)=
word_of_int (bintrunc 32 ((bin_rest ^^ 31) (bl_to_bin (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1))))))"
using \<open>bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1))) {1..32}) = bintrunc 32 ((bin_rest ^^ 31) (bl_to_bin (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1)))))\<close>
by auto
\<comment> \<open>push bintrunc 32 inside\<close>
also have "... = word_of_int ((bin_rest ^^ 31) (bintrunc 63 (bl_to_bin (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1))))))"
using bin_rest_power_trunc[where n="63" and k="31", symmetric] by auto
also have "... = word_of_int ((bin_rest ^^ 31) (bl_to_bin (drop 1 (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1))))))"
proof -
have "type_of (wline_of tw' TERM1 (i + 4 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
thus ?thesis
using bl2bin_drop by auto
qed
\<comment> \<open>pull bl_to_bin to left\<close>
also have "... = word_of_int (bl_to_bin ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1))))))"
unfolding butlast_pow_rest_bl2bin[symmetric] by auto
\<comment> \<open>change to sbl_to_bin\<close>
also have "... = (word_of_int (sbintrunc (LENGTH(1+31) - 1) (bl_to_bin ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1))))))) :: (1 + 31) word)"
unfolding word_sbin.Abs_norm by auto
also have "... = word_of_int (sbl_to_bin ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1))))))"
proof -
have "type_of (wline_of tw' TERM1 (i + 4 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
have "length ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1))))) = 32"
unfolding butlast_power length_take length_drop * by eval
hence "(word_of_int (sbintrunc (LENGTH(1+31) - 1) (bl_to_bin ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1))))))) :: (1 + 31) word) =
(word_of_int (sbintrunc (length ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1))))) - 1) (bl_to_bin ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1))))))) :: (1 + 31) word)"
by auto
thus ?thesis
using sbl_to_bin_alt_def by auto
qed
\<comment> \<open>push sbl_to_bin back to right\<close>
also have "... = word_of_int ((bin_rest ^^ 31) (sbl_to_bin (drop 1 (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1))))))"
proof -
have "type_of (wline_of tw' TERM1 (i + 4 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
have "length ((drop 1 (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1))))) = 63"
unfolding length_take length_drop * by eval
hence **: "31 < length ((drop 1 (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1)))))"
by auto
show ?thesis
unfolding butlast_pow_rest_sbl2bin[OF **] by auto
qed
also have "... = word_of_int ((bin_rest ^^ 31) (sbintrunc 62 (sbl_to_bin (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1))))))"
proof -
have "type_of (wline_of tw' TERM1 (i + 4 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 4 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
thus ?thesis
using sbl2bin_drop by auto
qed
also have "... = word_of_int ((bin_rest ^^ 31) (sbintrunc 62 (bin_of COMMON at_time (i + 4 * clk_period - 2) on tw' * bin_of ACCUM at_time (i + 4 * clk_period - 2) on tw')))"
using `bin_of TERM1 at_time (i + 4 *clk_period - 1) on tw' = sbintrunc 63
(bin_of COMMON at_time (i + 4 *clk_period - 2) on tw' * bin_of ACCUM at_time (i + 4 *clk_period - 2) on tw')`
by auto
also have "... = word_of_int (sbintrunc 31 ((bin_rest ^^ 31) (bin_of COMMON at_time (i + 4 * clk_period - 2) on tw' * bin_of ACCUM at_time (i + 4 * clk_period - 2) on tw')))"
proof -
have "(31 :: nat) \<le> 62" by auto
show ?thesis
unfolding bin_rest_power_strunc[OF `31 \<le> 62`]
by auto
qed
also have "... = word_of_int (sbintrunc (LENGTH(1 + 31) - 1) ((bin_rest ^^ 31) (bin_of COMMON at_time (i + 4 * clk_period - 2) on tw' * bin_of ACCUM at_time (i + 4 * clk_period - 2) on tw')))"
by auto
also have "... = word_of_int ((bin_rest ^^ 31) (bin_of COMMON at_time (i + 4 * clk_period - 2) on tw' * bin_of ACCUM at_time (i + 4 * clk_period - 2) on tw'))"
unfolding word_sbin.Abs_norm by auto
also have "... = word_of_int ((bin_of COMMON at_time (i + 4 * clk_period - 2) on tw' * bin_of ACCUM at_time (i + 4 * clk_period - 2) on tw') div 2 ^ 31)"
unfolding bin_rest_compow by auto
also have "... = word_of_int (sbintrunc (length (lval_of (wline_of tw' COMMON (i + 4 * clk_period - 2))) - 1) (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 4 * clk_period - 2)))) *
sbintrunc (length (lval_of (wline_of tw' ACCUM (i + 4 * clk_period - 2))) - 1) (sbl_to_bin (lval_of (wline_of tw' ACCUM (i + 4 * clk_period - 2)))) div 2 ^ 31)"
using sbl_to_bin_alt_def2 by auto
also have "... = word_of_int (sbintrunc (LENGTH(1 + 31) - 1) (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 4 * clk_period - 2)))) *
sbintrunc (LENGTH(1 + 31) - 1) (sbl_to_bin (lval_of (wline_of tw' ACCUM (i + 4 * clk_period - 2)))) div 2 ^ 31)"
proof -
have "type_of (wline_of tw' COMMON (i + 4 * clk_period - 2)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' COMMON (i + 4 * clk_period - 2))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
have "type_of (wline_of tw' ACCUM (i + 4 * clk_period - 2)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence **: "length (lval_of (wline_of tw' ACCUM (i + 4 * clk_period - 2))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
with * show ?thesis
by auto
qed
also have "... = word_of_int (sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 4 * clk_period - 2)))) :: (1 + 31) word) *
sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' ACCUM (i + 4 * clk_period - 2)))) :: (1 + 31) word ) div 2 ^ 31)"
unfolding sint_sbintrunc' by auto
finally show ?thesis
unfolding `(word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 4 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word) =
(word_of_int ( bl_to_bin (nths (lof_wline tw' TERM1 (i + 4 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word)`
by auto
qed
hence "Fixed (word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 4 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word) =
Fixed (word_of_int (sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 4 * clk_period - 2)))) :: (1 + 31) word ) *
sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' ACCUM (i + 4 * clk_period - 2)))) :: (1 + 31) word) div 2 ^ 31))"
by auto
also have "... = Fixed (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 4 * clk_period - 2))))) * Fixed (word_of_int (sbl_to_bin (lval_of (wline_of tw' ACCUM (i + 4 * clk_period - 2)))))"
using times_fixed.abs_eq[where xa="word_of_int (bin_of COMMON at_time i + 4 * clk_period - 2 on tw') :: (1 + 31) word" and
x="word_of_int (bin_of ACCUM at_time i + 4 * clk_period - 2 on tw') :: (1 + 31) word", symmetric]
by auto
also have "... = fixed_of_sval (wline_of tw' COMMON (i + 4 * clk_period - 2)) * fixed_of_sval (wline_of tw' ACCUM (i + 4 * clk_period - 2))"
proof -
have "type_of (wline_of tw' COMMON (i + 4 * clk_period - 2)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
hence "length (lval_of (wline_of tw' COMMON (i + 4 * clk_period - 2))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
hence "Fixed (word_of_int (bin_of COMMON at_time i + 4 * clk_period - 2 on tw')) =
Fixed (word_of_int (sbintrunc (LENGTH((1+31)) - 1) (bl_to_bin (lval_of (wline_of tw' COMMON (i + 4 * clk_period - 2))))))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (bl_to_bin (lval_of (wline_of tw' COMMON (i + 4 * clk_period - 2)))) :: (1 + 31) word)"
unfolding word_sbin.Abs_norm by auto
also have "... = fixed_of_sval (wline_of tw' COMMON (i + 4 * clk_period - 2))"
proof -
have "wline_of tw' COMMON (i + 4 * clk_period - 2) = Lv Sig (lval_of (wline_of tw' COMMON (i + 4 * clk_period - 2)))"
using `type_of (wline_of tw' COMMON (i + 4 *clk_period - 2)) = Lty Sig 32`
by (metis (no_types, hide_lams) ty.distinct(1) ty.inject type_of.cases type_of.simps(1) type_of.simps(2) val.sel(3))
thus ?thesis
using fixed_of_sval.simps unfolding of_bl_def by smt
qed
finally have "Fixed (word_of_int (bin_of COMMON at_time i + 4 * clk_period - 2 on tw') :: (1 + 31) word) = fixed_of_sval (wline_of tw' COMMON (i + 4 * clk_period - 2))"
by auto
have "type_of (wline_of tw' ACCUM (i + 4 * clk_period - 2)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
hence "length (lval_of (wline_of tw' ACCUM (i + 4 * clk_period - 2))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
hence "Fixed (word_of_int (bin_of ACCUM at_time i + 4 * clk_period - 2 on tw')) =
Fixed (word_of_int (sbintrunc (LENGTH((1+31)) - 1) (bl_to_bin (lval_of (wline_of tw' ACCUM (i + 4 * clk_period - 2))))))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (bl_to_bin (lval_of (wline_of tw' ACCUM (i + 4 * clk_period - 2)))) :: (1 + 31) word)"
unfolding word_sbin.Abs_norm by auto
also have "... = fixed_of_sval (wline_of tw' ACCUM (i + 4 * clk_period - 2))"
proof -
have "wline_of tw' ACCUM (i + 4 * clk_period - 2) = Lv Sig (lval_of (wline_of tw' ACCUM (i + 4 * clk_period - 2)))"
using `type_of (wline_of tw' ACCUM (i + 4 *clk_period - 2)) = Lty Sig 32`
by (metis (no_types, hide_lams) ty.distinct(1) ty.inject type_of.cases type_of.simps(1) type_of.simps(2) val.sel(3))
thus ?thesis
using fixed_of_sval.simps unfolding of_bl_def by smt
qed
finally have "Fixed (word_of_int (bin_of ACCUM at_time i + 4 * clk_period - 2 on tw') :: (1 + 31) word) = fixed_of_sval (wline_of tw' ACCUM (i + 4 * clk_period - 2))"
by auto
thus ?thesis
using \<open>Fixed (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 4 * clk_period - 2))))) = fixed_of_sval (wline_of tw' COMMON (i + 4 * clk_period - 2))\<close> by auto
qed
finally have "Fixed (word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 4 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word) =
fixed_of_sval (wline_of tw' COMMON (i + 4 * clk_period - 2)) * fixed_of_sval (wline_of tw' ACCUM (i + 4 * clk_period - 2))"
by auto
hence "fixed_of_sval (wline_of tw' ACCUM (i + 4 * clk_period + 1)) =
approx_div_fact 3 + fixed_of_sval (wline_of tw' COMMON (i + 4 * clk_period - 2)) * fixed_of_sval (wline_of tw' ACCUM (i + 4 * clk_period - 2))"
using `?lhs4 = ?rhs4`
`Fixed (word_of_int (bin_of ACCUM at_time i + 4 * clk_period + 1 on tw') :: (1 + 31) word) =
Fixed (word_of_int (bin_of FRAC at_time i + 4 * clk_period - 1 on tw')) + Fixed (word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 4 * clk_period - 1)) {1 .. 32})))`
`Fixed (word_of_int (bin_of FRAC at_time i + 4 * clk_period - 1 on tw')) = approx_div_fact 3`
by auto
hence "fixed_of_sval (wline_of tw' ACCUM (fst tw')) = approx_div_fact 0 +
fixed_of_sval (wline_of tw' COMMON (i + 4 * clk_period - 2)) * (approx_div_fact 1 +
fixed_of_sval (wline_of tw' COMMON (i + 4 * clk_period - 2)) * (approx_div_fact 2 +
fixed_of_sval (wline_of tw' COMMON (i + 4 * clk_period - 2)) * (approx_div_fact 3 +
fixed_of_sval (wline_of tw' COMMON (i + 4 * clk_period - 2)) * fixed_of_sval (wline_of tw' ACCUM (i + 4 * clk_period - 2)))))"
using `fixed_of_sval (wline_of tw' ACCUM (fst tw')) = approx_div_fact 0 +
fixed_of_sval (wline_of tw' COMMON (i + 5 * clk_period - 2)) * (approx_div_fact 1 +
fixed_of_sval (wline_of tw' COMMON (i + 5 * clk_period - 2)) * (approx_div_fact 2 +
fixed_of_sval (wline_of tw' COMMON (i + 5 * clk_period - 2)) * fixed_of_sval (wline_of tw' ACCUM (i + 5 * clk_period - 2))))`
`wline_of tw' COMMON (i + 4 * clk_period - 2) = wline_of tw' COMMON (i + 4 * clk_period - 1)`
`(fixed_of_sval (wline_of tw' COMMON (i + 5 * clk_period - 2)) :: (1,31) fixed) = fixed_of_sval (wline_of tw' COMMON (i + 4 * clk_period - 1))`
`wline_of tw' ACCUM (i + 4 * clk_period + 1) = wline_of tw' ACCUM (i + 5 * clk_period - 2)`
by auto
\<comment> \<open> obtaining common and accum\<close>
have "wline_of tw' COMMON (i + 3 * clk_period + 1) = wline_of tw' COMMON (i + 4 * clk_period - 2)"
and "wline_of tw' ACCUM (i + 3 * clk_period + 1) = wline_of tw' ACCUM (i + 4 * clk_period - 2)"
proof -
have a: "fst tw \<le> i + 3 * clk_period + 1"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] by auto
have b: "i + 3 * clk_period + 1 \<le> i + 4 * clk_period - 2"
using assms by (auto simp add: field_simps)
have c: "i + 4 * clk_period - 2 \<le> i + 7 * clk_period + 1"
by auto
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms
unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using \<open>\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0\<close> assms by blast
hence "(i + 3 * clk_period) mod clk_period = 0"
by auto
hence "(i + 4 * clk_period) mod clk_period = 0"
by auto
have d: "\<And>k. i + 3 * clk_period + 1 \<le> k \<Longrightarrow> k \<le> i + 4 * clk_period - 1 \<Longrightarrow> \<not> is_posedge2 (snd tw') CLK k"
proof -
fix n
obtain m1 where "i + 3 * clk_period = m1 * clk_period"
using `(i + 3 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 4 * clk_period = (m1 + 1) * clk_period"
proof -
obtain m2 where "i + 4 * clk_period = m2 * clk_period"
using `(i + 4 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 5 * clk_period - (i + 4 * clk_period) = clk_period"
by (auto simp add: field_simps)
hence "m2 * clk_period - m1 * clk_period = clk_period"
using `i + 3 * clk_period = m1 * clk_period` `i + 4 * clk_period = m2 * clk_period`
by auto
hence "(m2 - m1) * clk_period = clk_period"
by (auto simp add: algebra_simps)
hence "m2 = Suc m1"
using `3 < clk_period ` by auto
thus ?thesis
using Suc_eq_plus1 \<open>i + 4 * clk_period = m2 * clk_period\<close> by presburger
qed
assume "i + 3 * clk_period + 1 \<le> n" and "n \<le> i + 4 * clk_period - 1"
hence "m1 * clk_period < n"
using `i + 3 * clk_period = m1 * clk_period` by linarith
have "n mod clk_period \<noteq> 0"
proof -
have "n div clk_period = m1"
apply (rule Misc_Arithmetic.sdl)
using \<open>m1 * clk_period < n\<close> apply (simp add: mult.commute)
using `n \<le> i + 4 * clk_period - 1` `i + 4 * clk_period = (m1 + 1) * clk_period` assms
by (auto simp add: field_simps)
hence "n = m1 * clk_period + n mod clk_period"
by auto
moreover have "n mod clk_period < clk_period"
using assms by (auto intro!: mod_less_divisor)
ultimately show ?thesis
using \<open>m1 * clk_period < n\<close> by linarith
qed
hence "\<not> is_posedge2 w CLK n"
using \<open>\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0\<close> by auto
thus "\<not> is_posedge2 (snd tw') CLK n"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
qed
show "wline_of tw' COMMON (i + 3 * clk_period + 1) = wline_of tw' COMMON (i + 4 * clk_period - 2)"
and "wline_of tw' ACCUM (i + 3 * clk_period + 1) = wline_of tw' ACCUM (i + 4 * clk_period - 2)"
using registers_unchanged_no_rising_edge[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)` a b c d]
by auto
qed
have "Inv_core (i + 3 * clk_period + 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
have "is_posedge2 (snd tw') CLK (i + 3 * clk_period)"
proof -
have "is_posedge2 w CLK (i + 4 * clk_period)"
using `is_posedge2 (snd tw') CLK (i + 4 * clk_period)`
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
hence "is_posedge2 w CLK (i + 4 * clk_period - clk_period)"
using assms by auto
hence "is_posedge2 w CLK (i + 3 * clk_period)"
by (auto simp add:field_simps)
thus "is_posedge2 (snd tw') CLK (i + 3 * clk_period)"
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
qed
have "wline_of tw' RST (i + 3 * clk_period) = Bv False"
proof (rule ccontr)
assume "wline_of tw' RST (i + 3 * clk_period) \<noteq> Bv False"
have "wityping \<Gamma> (snd tw')"
using `wityping \<Gamma> (snd tw)` world_sim_fin_preserves_wityping[OF 0]
using conc_stmt_wf_arch cwt_arch nonneg_delay_conc_architecture by blast
hence "type_of (wline_of tw' RST (i + 3 * clk_period)) = Bty"
unfolding wityping_def wtyping_def using cosine_locale_axioms unfolding cosine_locale_def by auto
hence "wline_of tw' RST (i + 3 * clk_period) = Bv True"
using `wline_of tw' RST (i + 3 * clk_period) \<noteq> Bv False` type_of_bty_cases by blast
hence "wline_of tw' STATE (i + 3 * clk_period + 1) = V_INIT"
using `Inv_core ((i + 3 * clk_period + 1, snd tw'))` `is_posedge2 (snd tw') CLK (i + 3 * clk_period)` unfolding inv_reg_alt_def
comp_def snd_conv fst_conv by auto
with `wline_of tw' STATE (i + 3 * clk_period + 1) = V_PROC` show False
by auto
qed
have "wline_of tw' NEXT_COMMON (i + 3 * clk_period) = wline_of tw' COMMON (i + 3 * clk_period + 1)"
and "wline_of tw' NEXT_ACCUM (i + 3 * clk_period) = wline_of tw' ACCUM (i + 3 * clk_period + 1)"
using `Inv_core (i + 3 * clk_period + 1, snd tw')` `is_posedge2 (snd tw') CLK (i + 3 * clk_period)` `wline_of tw' RST (i + 3 * clk_period) = Bv False`
unfolding inv_reg_alt_def comp_def snd_conv fst_conv by auto
have "bin_of COMMON at_time (i + 3 * clk_period - 1) on tw' = bin_of NEXT_COMMON at_time (i + 3 * clk_period) on tw'"
proof -
have "Inv_core (i + 3 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
thus ?thesis
using `wline_of tw' STATE (i + 3 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 3 * clk_period - 1))`
unfolding inv_ncommon_alt_def comp_def snd_conv fst_conv by auto
qed
have "(fixed_of_sval (wline_of tw' COMMON (i + 4 * clk_period - 2)) :: (1,31) fixed) = fixed_of_sval (wline_of tw' COMMON (i + 3 * clk_period - 1))"
proof -
have typof2: "type_of (wline_of tw' COMMON (i + 3 * clk_period - 1)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
then obtain bs2 where " wline_of tw' COMMON (i + 3 * clk_period - 1) = Lv Sig bs2 \<and> length bs2 = 32"
using type_of.elims[OF typof2] by fastforce
have typof: "type_of (wline_of tw' COMMON (i + 4 * clk_period - 2)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
then obtain bs1 where " wline_of tw' COMMON (i + 4 * clk_period - 2) = Lv Sig bs1 \<and> length bs1 = 32"
using type_of.elims[OF typof] by fastforce
hence "fixed_of_sval (wline_of tw' COMMON (i + 4 * clk_period - 2)) = Fixed (of_bl bs1 :: (1 + 31) word)"
using fixed_of_sval.simps by auto
also have "... = Fixed (word_of_int (bl_to_bin bs1) :: (1 + 31) word)"
unfolding of_bl_def by auto
also have "... = Fixed (word_of_int (sbintrunc (LENGTH(1+31) - 1) (bl_to_bin bs1)))"
unfolding word_sbin.Abs_norm[symmetric, where x="bl_to_bin bs1"] by auto
also have "... = Fixed (word_of_int (sbintrunc (length bs1 - 1) (bl_to_bin bs1)))"
using `wline_of tw' COMMON (i + 4 * clk_period - 2) = Lv Sig bs1 \<and> length bs1 = 32` by auto
also have "... = Fixed (word_of_int (sbl_to_bin bs1))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (sbl_to_bin bs2))"
using `bin_of COMMON at_time (i + 3 * clk_period - 1) on tw' = bin_of NEXT_COMMON at_time (i + 3 * clk_period) on tw'`
`wline_of tw' COMMON (i + 3 * clk_period - 1) = Lv Sig bs2 \<and> length bs2 = 32`
`wline_of tw' COMMON (i + 4 * clk_period - 2) = Lv Sig bs1 \<and> length bs1 = 32`
using \<open>wline_of tw' COMMON (i + 3 * clk_period + 1) = wline_of tw' COMMON (i + 4 * clk_period - 2)\<close> \<open>wline_of tw' NEXT_COMMON (i + 3 * clk_period) = wline_of tw' COMMON (i + 3 * clk_period + 1)\<close> by auto
also have "... = Fixed (word_of_int (sbintrunc (length bs2- 1) (bl_to_bin bs2)))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (sbintrunc (LENGTH(1+31) - 1) (bl_to_bin bs2)))"
using `wline_of tw' COMMON (i + 3 * clk_period - 1) = Lv Sig bs2 \<and> length bs2 = 32` by auto
also have "... = Fixed (word_of_int (bl_to_bin bs2) :: (1 + 31) word)"
unfolding word_sbin.Abs_norm[symmetric, where x="bl_to_bin bs2"] by auto
also have "... = Fixed (of_bl bs2 :: (1 + 31) word)"
unfolding of_bl_def by auto
also have "... = fixed_of_sval (wline_of tw' COMMON (i + 3 * clk_period - 1))"
using `wline_of tw' COMMON (i + 3 * clk_period - 1) = Lv Sig bs2 \<and> length bs2 = 32`
using fixed_of_sval.simps by auto
finally show ?thesis
by auto
qed
have "wline_of tw' COMMON (i + 3 * clk_period - 2) = wline_of tw' COMMON (i + 3 * clk_period - 1)"
proof -
have "Inv_core (i + 3 * clk_period - 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms
unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence **: "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using posedge by blast
hence "(i + 3 * clk_period) mod clk_period = 0"
by auto
have "(i + 3 * clk_period - 2) mod clk_period \<noteq> 0"
proof -
have "i + 2 * clk_period < i + 3 * clk_period - 2"
using assms by (auto)
moreover have "i + 3 * clk_period - 2 < i + 6 * clk_period"
using assms by auto
ultimately show ?thesis
by (metis \<open>(i + 3 * clk_period) mod clk_period = 0\<close> assms(3) assms(4) diff_add_0 diff_add_inverse
dvd_add_left_iff dvd_antisym less_imp_add_positive less_nat_zero_code mod_0_imp_dvd nat_diff_split_asm numeral_plus_numeral semiring_norm(5))
qed
hence "\<not> is_posedge2 (snd tw') CLK (i + 3 * clk_period - 2)"
using ** by auto
thus ?thesis
using `Inv_core (i + 3 * clk_period - 1, snd tw')` unfolding inv_reg_alt_def comp_def snd_conv fst_conv
using diff_diff_left nat_1_add_1 by presburger
qed
\<comment> \<open> obtaining state\<close>
have "wline_of tw' STATE (i + 2 * clk_period + 1) = wline_of tw' STATE (i + 3 * clk_period - 1)"
proof -
have a: "fst tw \<le> i + 2 * clk_period + 1"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] by auto
have b: "i + 2 * clk_period + 1 \<le> i + 3 * clk_period - 1"
using assms by (auto simp add: field_simps)
have c: "i + 3 * clk_period - 1 \<le> i + 7 * clk_period + 1"
by auto
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms
unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using \<open>\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0\<close> assms by blast
hence "(i + 3 * clk_period) mod clk_period = 0"
by auto
hence "(i + 2 * clk_period) mod clk_period = 0"
by auto
have d: "\<And>k. i + 2 * clk_period + 1 \<le> k \<Longrightarrow> k \<le> i + 3 * clk_period - 1 \<Longrightarrow> \<not> is_posedge2 (snd tw') CLK k"
proof -
fix n
obtain m1 where "i + 2 * clk_period = m1 * clk_period"
using `(i + 2 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 3 * clk_period = (m1 + 1) * clk_period"
proof -
obtain m2 where "i + 3 * clk_period = m2 * clk_period"
using `(i + 3 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 3 * clk_period - (i + 2 * clk_period) = clk_period"
by (auto simp add: field_simps)
hence "m2 * clk_period - m1 * clk_period = clk_period"
using `i + 2 * clk_period = m1 * clk_period` `i + 3 * clk_period = m2 * clk_period`
by auto
hence "(m2 - m1) * clk_period = clk_period"
by (auto simp add: algebra_simps)
hence "m2 = Suc m1"
using `3 < clk_period ` by auto
thus ?thesis
using Suc_eq_plus1 \<open>i + 3 * clk_period = m2 * clk_period\<close> by presburger
qed
assume "i + 2 * clk_period + 1 \<le> n" and "n \<le> i + 3 * clk_period - 1"
hence "m1 * clk_period < n"
using `i + 2 * clk_period = m1 * clk_period` by linarith
have "n mod clk_period \<noteq> 0"
proof -
have "n div clk_period = m1"
apply (rule Misc_Arithmetic.sdl)
using \<open>m1 * clk_period < n\<close> apply (simp add: mult.commute)
using `n \<le> i + 3 * clk_period - 1` `i + 3 * clk_period = (m1 + 1) * clk_period` assms
by (auto simp add: field_simps)
hence "n = m1 * clk_period + n mod clk_period"
by auto
moreover have "n mod clk_period < clk_period"
using assms by (auto intro!: mod_less_divisor)
ultimately show ?thesis
using \<open>m1 * clk_period < n\<close> by linarith
qed
hence "\<not> is_posedge2 w CLK n"
using \<open>\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0\<close> by auto
thus "\<not> is_posedge2 (snd tw') CLK n"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
qed
show "wline_of tw' STATE (i + 2 * clk_period + 1) = wline_of tw' STATE (i + 3 * clk_period - 1)"
using registers_unchanged_no_rising_edge[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)` a b c d]
by auto
qed
hence "wline_of tw' STATE (i + 2 * clk_period + 1) = V_PROC"
using `wline_of tw' STATE (i + 3 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 3 * clk_period - 1))`
by auto
have "wline_of tw' FRAC (i + 2 * clk_period + 1) = wline_of tw' FRAC (i + 3 * clk_period - 1)"
and "wline_of tw' COUNTER (i + 2 * clk_period + 1) = wline_of tw' COUNTER (i + 3 * clk_period - 1)"
proof -
have a: "fst tw \<le> i + 2 * clk_period + 1"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] by auto
have b: "i + 2 * clk_period + 1 \<le> i + 3 * clk_period - 1"
using assms by (auto simp add: field_simps)
have c: "i + 3 * clk_period - 1 \<le> i + 7 * clk_period + 1"
by auto
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using \<open>\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0\<close> assms by blast
hence "(i + 3 * clk_period) mod clk_period = 0"
by auto
hence "(i + 2 * clk_period) mod clk_period = 0"
by auto
have d: "\<And>k. i + 2 * clk_period + 1 \<le> k \<Longrightarrow> k \<le> i + 3 * clk_period - 1 \<Longrightarrow> \<not> is_posedge2 (snd tw') CLK k"
proof -
fix n
obtain m1 where "i + 2 * clk_period = m1 * clk_period"
using `(i + 2 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 3 * clk_period = (m1 + 1) * clk_period"
proof -
obtain m2 where "i + 3 * clk_period = m2 * clk_period"
using `(i + 3 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 3 * clk_period - (i + 2 * clk_period) = clk_period"
by (auto simp add: field_simps)
hence "m2 * clk_period - m1 * clk_period = clk_period"
using `i + 2 * clk_period = m1 * clk_period` `i + 3 * clk_period = m2 * clk_period` by auto
hence "(m2 - m1) * clk_period = clk_period"
by (auto simp add: algebra_simps)
hence "m2 = Suc m1"
using `3 < clk_period ` by auto
thus ?thesis
using Suc_eq_plus1 \<open>i + 3 * clk_period = m2 * clk_period\<close> by presburger
qed
assume "i + 2 * clk_period + 1 \<le> n" and "n \<le> i + 3 * clk_period - 1"
hence "m1 * clk_period < n"
using `i + 2 * clk_period = m1 * clk_period` by linarith
have "n mod clk_period \<noteq> 0"
proof -
have "n div clk_period = m1"
apply (rule Misc_Arithmetic.sdl)
using \<open>m1 * clk_period < n\<close> apply (simp add: mult.commute)
using `n \<le> i + 3 * clk_period - 1` `i + 3 * clk_period = (m1 + 1) * clk_period` assms
by (auto simp add: field_simps)
hence "n = m1 * clk_period + n mod clk_period"
by auto
moreover have "n mod clk_period < clk_period"
using assms by (auto intro!: mod_less_divisor)
ultimately show ?thesis
using \<open>m1 * clk_period < n\<close> by linarith
qed
hence "\<not> is_posedge2 w CLK n"
using \<open>\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0\<close> by auto
thus "\<not> is_posedge2 (snd tw') CLK n"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
qed
show "wline_of tw' FRAC (i + 2 * clk_period + 1) = wline_of tw' FRAC (i + 3 * clk_period - 1)"
and "wline_of tw' COUNTER (i + 2 * clk_period + 1) = wline_of tw' COUNTER (i + 3 * clk_period - 1)"
using registers_unchanged_no_rising_edge[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)` a b c d] by auto
qed
have "wline_of tw' NEXT_FRAC (i + 2 * clk_period) = wline_of tw' FRAC (i + 2 * clk_period + 1)"
and "wline_of tw' NEXT_STATE (i + 2 * clk_period) = wline_of tw' STATE (i + 2 * clk_period + 1)"
and "wline_of tw' NEXT_COUNTER (i + 2 * clk_period) = wline_of tw' COUNTER (i + 2 * clk_period + 1)"
proof -
have "Inv_core (i + 2 * clk_period + 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
moreover have "is_posedge2 (snd tw') CLK (i + 2 * clk_period)"
proof -
have "is_posedge2 w CLK (i + 3 * clk_period)"
using `is_posedge2 (snd tw') CLK (i + 3 * clk_period)`
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
hence "is_posedge2 w CLK (i + 3 * clk_period - clk_period)"
using assms by auto
hence "is_posedge2 w CLK (i + 2 * clk_period)"
by (auto simp add:field_simps)
thus "is_posedge2 (snd tw') CLK (i + 2 * clk_period)"
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
qed
moreover have "wline_of tw' RST (i + 2 * clk_period) = Bv False"
proof (rule ccontr)
assume "wline_of tw' RST (i + 2 * clk_period) \<noteq> Bv False"
have "wityping \<Gamma> (snd tw')"
using `wityping \<Gamma> (snd tw)` world_sim_fin_preserves_wityping[OF 0] conc_stmt_wf_arch cwt_arch nonneg_delay_conc_architecture by blast
hence "type_of (wline_of tw' RST (i + 2 * clk_period)) = Bty"
unfolding wityping_def wtyping_def using cosine_locale_axioms unfolding cosine_locale_def by auto
hence "wline_of tw' RST (i + 2 * clk_period) = Bv True"
using `wline_of tw' RST (i + 2 * clk_period) \<noteq> Bv False` type_of_bty_cases by blast
hence "wline_of tw' STATE (i + 2 * clk_period + 1) = V_INIT"
using `Inv_core (i + 2 * clk_period + 1, snd tw')` `is_posedge2 (snd tw') CLK (i + 2 * clk_period)` unfolding inv_reg_alt_def
comp_def snd_conv fst_conv by auto
with `wline_of tw' STATE (i + 2 * clk_period + 1) = V_PROC` show False
using \<open>wline_of tw' OUTREADY_REG (get_time tw') = Bv True\<close> by auto
qed
ultimately show "wline_of tw' NEXT_FRAC (i + 2 * clk_period) = wline_of tw' FRAC (i + 2 * clk_period + 1)"
and "wline_of tw' NEXT_STATE (i + 2 * clk_period) = wline_of tw' STATE (i + 2 * clk_period + 1)"
and "wline_of tw' NEXT_COUNTER (i + 2 * clk_period) = wline_of tw' COUNTER (i + 2 * clk_period + 1)"
unfolding inv_reg_alt_def comp_def snd_conv fst_conv by auto
qed
hence "wline_of tw' NEXT_STATE (i + 2 * clk_period) = V_PROC" and "ubin_of NEXT_COUNTER at_time i + 2 * clk_period on tw' = 3"
using `wline_of tw' STATE (i + 2 * clk_period + 1) = V_PROC` `ubin_of COUNTER at_time i + 3 *clk_period - 1 on tw' = 3`
using \<open>bl_to_bin (lval_of (wline_of tw' COUNTER (i + 3 *clk_period - 1))) = 3\<close> \<open>wline_of tw' COUNTER (i + 2 * clk_period + 1) = wline_of tw' COUNTER (i + 3 *clk_period - 1)\<close> \<open>wline_of tw' NEXT_COUNTER (i + 2 * clk_period) = wline_of tw' COUNTER (i + 2 * clk_period + 1)\<close>
by auto
have "wline_of tw' STATE (i + 2 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 2 * clk_period - 1))
\<or> wline_of tw' STATE (i + 2 * clk_period - 1) = V_PRE"
proof (rule ccontr)
have "Inv_core (i + 2 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
hence inv:"inv_nstate (i + 2 * clk_period, snd tw')"
by auto
assume "\<not> (wline_of tw' STATE (i + 2 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 2 * clk_period - 1))
\<or> wline_of tw' STATE (i + 2 * clk_period - 1) = V_PRE)"
hence *: "(wline_of tw' STATE (i + 2 * clk_period - 1) = V_PROC \<Longrightarrow> \<not> bval_of (wline_of tw' CTR_NEQ_0 (i + 2 * clk_period - 1)))" and
**: "wline_of tw' STATE (i + 2 * clk_period - 1) \<noteq> V_PRE" (is "?state \<noteq> _")by auto
then consider "?state = V_INIT" | "?state = V_WAIT" | "?state = V_PROC" | "?state = V_POST"
| "?state \<noteq> V_INIT \<and> ?state \<noteq> V_WAIT \<and> ?state \<noteq> V_PRE \<and> ?state \<noteq> V_PROC \<and> ?state \<noteq> V_POST"
by auto
thus False
proof (cases)
case 1
hence "wline_of tw' NEXT_STATE (i + 2 * clk_period) \<noteq> V_PROC"
using inv unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 2 * clk_period) = V_PROC`
by auto
next
case 2
hence "wline_of tw' NEXT_STATE (i + 2 * clk_period) \<noteq> V_PROC"
using inv unfolding inv_nstate_alt_def comp_def snd_conv fst_conv
by (cases "bval_of (snd (snd tw') INREADY (i + 2 * clk_period - 1))") auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 2 * clk_period) = V_PROC`
by auto
next
case 3
hence "wline_of tw' NEXT_STATE (i + 2 * clk_period) \<noteq> V_PROC"
using inv * unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 2 * clk_period) = V_PROC`
by auto
next
case 4
hence "wline_of tw' NEXT_STATE (i + 2 * clk_period) \<noteq> V_PROC"
using inv * unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 2 * clk_period) = V_PROC`
by auto
next
case 5
hence "wline_of tw' NEXT_STATE (i + 2 * clk_period) \<noteq> V_PROC"
using inv * unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 2 * clk_period) = V_PROC`
by auto
qed
qed
moreover have "is_posedge2 (snd tw') CLK (i + 2 * clk_period)"
proof -
have "is_posedge2 w CLK (i + 3 * clk_period)"
using `is_posedge2 (snd tw') CLK (i + 3 * clk_period)`
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
hence "is_posedge2 w CLK (i + 3 * clk_period - clk_period)"
using assms by auto
hence "is_posedge2 w CLK (i + 2 * clk_period)"
by (auto simp add:field_simps)
thus "is_posedge2 (snd tw') CLK (i + 2 * clk_period)"
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
qed
moreover have "\<not> (wline_of tw' STATE (i + 2 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 2 * clk_period - 1)))"
proof (rule ccontr)
assume "\<not> \<not> (wline_of tw' STATE (i + 2 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 2 * clk_period - 1)))"
hence "(wline_of tw' STATE (i + 2 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 2 * clk_period - 1)))"
by auto
have "bintrunc 3 (ubin_of COUNTER at_time (i + 2 * clk_period - 1) on tw' - 1) = 3"
proof -
have "Inv_core (i + 2 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
thus ?thesis
using `ubin_of NEXT_COUNTER at_time (i + 2 * clk_period) on tw' = 3`
`wline_of tw' STATE (i + 2 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 2 * clk_period - 1))`
unfolding inv_ncounter_alt_def fst_conv comp_def snd_conv by auto
qed
hence "(ubin_of COUNTER at_time (i + 2 * clk_period - 1) on tw' - 1) mod 8 = 3"
unfolding bintrunc_mod2p by auto
have "0 < ubin_of COUNTER at_time i + 2 * clk_period - 2 on tw'"
proof -
have "Inv_core (i + 2 * clk_period - 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
hence "inv_n0 (i + 2 * clk_period - 1, snd tw')"
by auto
hence "0 < bl_to_bin (lval_of (snd (snd tw') COUNTER (i + 2 * clk_period - 1 - 1)))"
using `wline_of tw' STATE (i + 2 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 2 * clk_period - 1))`
unfolding inv_n0_def comp_def snd_conv fst_conv by auto
thus ?thesis
unfolding comp_def snd_conv fst_conv
by (metis diff_diff_left nat_1_add_1)
qed
moreover have "ubin_of COUNTER at_time i + 2 * clk_period - 2 on tw' = ubin_of COUNTER at_time i + 2 * clk_period - 1 on tw'"
proof -
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms
unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence **: "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using posedge by blast
hence "(i + 2 * clk_period) mod clk_period = 0"
by auto
have "(i + 2 * clk_period - 2) mod clk_period \<noteq> 0"
proof -
have "i + 1 * clk_period < i + 2 * clk_period - 2"
using assms by (auto)
moreover have "i + 2 * clk_period - 2 < i + 2 * clk_period"
using assms by auto
ultimately show ?thesis
by (metis \<open>(i + 2 * clk_period) mod clk_period = 0\<close> assms(3) assms(4) diff_add_0 diff_add_inverse
dvd_add_left_iff dvd_antisym less_imp_add_positive less_nat_zero_code mod_0_imp_dvd nat_diff_split_asm numeral_plus_numeral semiring_norm(5))
qed
hence "\<not> is_posedge2 (snd tw') CLK (i + 2 * clk_period - 2)"
using ** by auto
moreover have "Inv_core (i + 2 * clk_period - 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
ultimately show ?thesis
unfolding inv_reg_alt_def comp_def snd_conv fst_conv
using diff_diff_left nat_1_add_1 by presburger
qed
ultimately have "0 < ubin_of COUNTER at_time i + 2 * clk_period - 1 on tw'"
by auto
moreover have "ubin_of COUNTER at_time (i + 2 * clk_period - 1) on tw' \<le> 7"
using ubin_counter_atmost[OF `wityping \<Gamma> (snd tw')`] by auto
ultimately have "(ubin_of COUNTER at_time (i + 2 * clk_period - 1) on tw' - 1) mod 8 = ubin_of COUNTER at_time (i + 2 * clk_period - 1) on tw' - 1"
by (auto intro!: int_mod_eq')
hence "ubin_of COUNTER at_time (i + 2 * clk_period - 1) on tw' = 4"
using `(ubin_of COUNTER at_time (i + 2 * clk_period - 1) on tw' - 1) mod 8 = 3` by auto
have "wline_of tw' STATE (i + 1 * clk_period + 1) = V_PROC \<and> ubin_of COUNTER at_time (i + 1 * clk_period + 1) on tw' = 4"
proof -
have f0: "fst tw \<le> i + 1 * clk_period + 1"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] by auto
have f1: "i + 1 * clk_period + 1 \<le> i + 2 * clk_period - 1"
using assms by auto
have f2: "i + 2 * clk_period - 1 \<le> i + 7 * clk_period + 1"
by auto
note temp = registers_unchanged_no_rising_edge[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)` f0 f1 f2]
have f3: "\<And>k. i + 1 * clk_period + 1 \<le> k \<Longrightarrow> k \<le> i + 2 * clk_period - 1 \<Longrightarrow> \<not> (is_posedge2 (snd tw') CLK k)"
proof -
fix k
assume " i + 1 * clk_period + 1 \<le> k" and "k \<le> i + 2 * clk_period - 1"
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms
unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence **: "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using posedge by blast
hence "(i + 1 * clk_period) mod clk_period = 0" and "(i + 2 * clk_period) mod clk_period = 0"
by auto
then obtain k1 where "i + 1 * clk_period = k1 * clk_period"
by (metis Nat.add_0_right div_mult_mod_eq)
hence "i + 2 * clk_period = (k1 + 1) * clk_period"
by simp
have "i + 1 * clk_period < k"
using \<open>i + 1 * clk_period + 1 \<le> k\<close> by linarith
have "k < i + 2 * clk_period"
using \<open>k \<le> i + 2 * clk_period - 1\<close> f1 by linarith
have "k div clk_period = k1"
apply (rule Misc_Arithmetic.sdl)
apply (metis \<open>i + 1 * clk_period < k\<close> \<open>i + 1 * clk_period = k1 * clk_period\<close> less_le_not_le mult.commute)
by (metis Suc_eq_plus1 \<open>i + 2 * clk_period = (k1 + 1) * clk_period\<close> \<open>k < i + 2 * clk_period\<close> mult.commute)
hence "k = k1 * clk_period + k mod clk_period"
by (meson mod_div_decomp)
hence "k mod clk_period \<noteq> 0"
using \<open>i + 1 * clk_period < k\<close> \<open>i + 1 * clk_period = k1 * clk_period\<close> by linarith
thus "\<not> (is_posedge2 (snd tw') CLK k)"
using "**" by auto
qed
have "wline_of tw' STATE (i + 1 * clk_period + 1) = wline_of tw' STATE (i + 2 * clk_period - 1)" and
"wline_of tw' COUNTER (i + 1 * clk_period + 1) = wline_of tw' COUNTER (i + 2 * clk_period - 1)"
using temp[OF f3] by auto
thus ?thesis
using `wline_of tw' STATE (i + 2 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 2 * clk_period - 1))`
`ubin_of COUNTER at_time (i + 2 * clk_period - 1) on tw' = 4`
by auto
qed
have "is_posedge2 (snd tw') CLK (i + 1 * clk_period)"
proof -
have "is_posedge2 w CLK (i + 2 * clk_period)"
using \<open>is_posedge2 (snd tw') CLK (i + 2 * clk_period)\<close>
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
hence "is_posedge2 w CLK (i + 2 * clk_period - clk_period)"
using assms by auto
hence "is_posedge2 w CLK (i + 1 * clk_period)"
by (auto simp add:field_simps)
thus "is_posedge2 (snd tw') CLK (i + 1 * clk_period)"
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
qed
have "wline_of tw' RST (i + 1 * clk_period) = Bv False"
proof (rule ccontr)
assume "wline_of tw' RST (i + 1 * clk_period) \<noteq> Bv False"
have "wityping \<Gamma> (snd tw')"
using `wityping \<Gamma> (snd tw)` world_sim_fin_preserves_wityping[OF 0]
using conc_stmt_wf_arch cwt_arch nonneg_delay_conc_architecture by blast
hence "type_of (wline_of tw' RST (i + 1 * clk_period)) = Bty"
unfolding wityping_def wtyping_def using cosine_locale_axioms unfolding cosine_locale_def by auto
hence "wline_of tw' RST (i + 1 * clk_period) = Bv True"
using `wline_of tw' RST (i + 1 * clk_period) \<noteq> Bv False` type_of_bty_cases by blast
moreover have "Inv_core (i + 1 * clk_period + 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
ultimately have "wline_of tw' STATE (i + 1 * clk_period + 1) = V_INIT"
using `is_posedge2 (snd tw') CLK (i + 1 * clk_period)`
unfolding inv_reg_alt_def comp_def snd_conv fst_conv by auto
thus False
using `wline_of tw' STATE (i + 1 * clk_period + 1) = V_PROC \<and> ubin_of COUNTER at_time (i + 1 * clk_period + 1) on tw' = 4`
by auto
qed
have "wline_of tw' NEXT_STATE (i + 1 * clk_period ) = V_PROC"
proof -
have "Inv_core (i + 1 * clk_period + 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
thus ?thesis
using `is_posedge2 (snd tw') CLK (i + 1 * clk_period)` `wline_of tw' RST (i + 1 * clk_period) = Bv False`
`wline_of tw' STATE (i + 1 * clk_period + 1) = V_PROC \<and> ubin_of COUNTER at_time (i + 1 * clk_period + 1) on tw' = 4`
unfolding inv_reg_alt_def comp_def snd_conv fst_conv by auto
qed
have "wline_of tw' STATE (i + 1 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 1 * clk_period - 1))
\<or> wline_of tw' STATE (i + 1 * clk_period - 1) = V_PRE"
proof (rule ccontr)
have "Inv_core (i + 1 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
hence inv:"inv_nstate (i + 1 * clk_period, snd tw')"
by auto
assume "\<not> (wline_of tw' STATE (i + 1 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 1 * clk_period - 1))
\<or> wline_of tw' STATE (i + 1 * clk_period - 1) = V_PRE)"
hence *: "(wline_of tw' STATE (i + 1 * clk_period - 1) = V_PROC \<Longrightarrow> \<not> bval_of (wline_of tw' CTR_NEQ_0 (i + 1 * clk_period - 1)))" and
**: "wline_of tw' STATE (i + 1 * clk_period - 1) \<noteq> V_PRE"
by auto
let ?state = "wline_of tw' STATE (i + 1 * clk_period - 1) "
consider "?state = V_INIT" | "?state = V_WAIT" | "?state = V_PROC" | "?state = V_POST"
| "?state \<noteq> V_INIT \<and> ?state \<noteq> V_WAIT \<and> ?state \<noteq> V_PRE \<and> ?state \<noteq> V_PROC \<and> ?state \<noteq> V_POST"
using ** by auto
thus False
proof (cases)
case 1
hence "wline_of tw' NEXT_STATE (i + 1 * clk_period) \<noteq> V_PROC"
using inv unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 1 * clk_period) = V_PROC`
by auto
next
case 2
hence "wline_of tw' NEXT_STATE (i + 1 * clk_period) \<noteq> V_PROC"
using inv * unfolding inv_nstate_alt_def comp_def snd_conv fst_conv
by (cases "bval_of (snd (snd tw') INREADY (i + 1 * clk_period - 1))") auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 1 * clk_period) = V_PROC`
by auto
next
case 3
hence "wline_of tw' NEXT_STATE (i + 1 * clk_period) \<noteq> V_PROC"
using inv * unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 1 * clk_period) = V_PROC`
by auto
next
case 4
hence "wline_of tw' NEXT_STATE (i + 1 * clk_period) \<noteq> V_PROC"
using inv unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 1 * clk_period) = V_PROC`
by auto
next
case 5
hence "wline_of tw' NEXT_STATE (i + 1 * clk_period) \<noteq> V_PROC"
using inv * unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 1 * clk_period) = V_PROC`
by auto
qed
qed
moreover
{ assume "wline_of tw' STATE (i + 1 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 1 * clk_period - 1))"
have "ubin_of NEXT_COUNTER at_time i + 1 * clk_period on tw' = 4"
proof -
have "Inv_core (i + 1 * clk_period + 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
thus ?thesis
using `wline_of tw' STATE (i + 1 * clk_period + 1) = V_PROC \<and> ubin_of COUNTER at_time (i + 1 * clk_period + 1) on tw' = 4`
`is_posedge2 (snd tw') CLK (i + 1 * clk_period)` `wline_of tw' RST (i + 1 * clk_period) = Bv False`
unfolding inv_reg_alt_def comp_def snd_conv fst_conv by auto
qed
have "bintrunc 3 (ubin_of COUNTER at_time (i + 1 * clk_period - 1) on tw' - 1) = 4"
proof -
have "Inv_core (i + 1 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
thus ?thesis
using `ubin_of NEXT_COUNTER at_time (i + 1 * clk_period) on tw' = 4`
`wline_of tw' STATE (i + 1 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 1 * clk_period - 1))`
unfolding inv_ncounter_alt_def fst_conv comp_def snd_conv by auto
qed
hence "(ubin_of COUNTER at_time (i + 1 * clk_period - 1) on tw' - 1) mod 8 = 4"
unfolding bintrunc_mod2p by auto
have "0 < ubin_of COUNTER at_time i + 1 * clk_period - 2 on tw'"
proof -
have "Inv_core (i + 1 * clk_period - 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
hence "inv_n0 (i + 1 * clk_period - 1, snd tw')"
by auto
hence "0 < bl_to_bin (lval_of (snd (snd tw') COUNTER (i + 1 * clk_period - 1 - 1)))"
using `wline_of tw' STATE (i + 1 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 1 * clk_period - 1))`
unfolding inv_n0_def comp_def snd_conv fst_conv by auto
thus ?thesis
unfolding comp_def snd_conv fst_conv
by (metis diff_diff_left nat_1_add_1)
qed
moreover have "ubin_of COUNTER at_time i + 1 * clk_period - 2 on tw' = ubin_of COUNTER at_time i + 1 * clk_period - 1 on tw'"
proof -
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms
unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence **: "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using posedge by blast
hence "(i + 1 * clk_period) mod clk_period = 0"
by auto
have "(i + 1 * clk_period - 2) mod clk_period \<noteq> 0"
proof -
have "i + 0 * clk_period < i + 1 * clk_period - 2"
using assms by (auto)
moreover have "i + 1 * clk_period - 2 < i + 1 * clk_period"
using assms by auto
ultimately show ?thesis
by (metis \<open>(i + 1 * clk_period) mod clk_period = 0\<close> assms(3) assms(4) diff_add_0 diff_add_inverse
dvd_add_left_iff dvd_antisym less_imp_add_positive less_nat_zero_code mod_0_imp_dvd nat_diff_split_asm numeral_plus_numeral semiring_norm(5))
qed
hence "\<not> is_posedge2 (snd tw') CLK (i + 1 * clk_period - 2)"
using ** by auto
moreover have "Inv_core (i + 1 * clk_period - 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
ultimately show ?thesis
unfolding inv_reg_alt_def comp_def snd_conv fst_conv
using diff_diff_left nat_1_add_1 by presburger
qed
ultimately have "0 < ubin_of COUNTER at_time i + 1 * clk_period - 1 on tw'"
by auto
moreover have "ubin_of COUNTER at_time (i + 1 * clk_period - 1) on tw' \<le> 7"
using ubin_counter_atmost[OF `wityping \<Gamma> (snd tw')`] by auto
ultimately have "(ubin_of COUNTER at_time (i + 1 * clk_period - 1) on tw' - 1) mod 8 = ubin_of COUNTER at_time (i + 1 * clk_period - 1) on tw' - 1"
by (auto intro!: int_mod_eq')
hence "ubin_of COUNTER at_time (i + 1 * clk_period - 1) on tw' = 5"
using `(ubin_of COUNTER at_time (i + 1 * clk_period - 1) on tw' - 1) mod 8 = 4` by auto
have "ubin_of COUNTER at_time (i + 1) on tw' = 5"
proof -
have f0: "fst tw \<le> i + 0 * clk_period + 1"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] by auto
have f1: "i + 0 * clk_period + 1 \<le> i + 1 * clk_period - 1"
using assms by auto
have f2: "i + 1 * clk_period - 1 \<le> i + 7 * clk_period + 1"
by auto
note temp = registers_unchanged_no_rising_edge[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)` f0 f1 f2]
have f3: "\<And>k. i + 0 * clk_period + 1 \<le> k \<Longrightarrow> k \<le> i + 1 * clk_period - 1 \<Longrightarrow> \<not> (is_posedge2 (snd tw') CLK k)"
proof -
fix k
assume " i + 0 * clk_period + 1 \<le> k" and "k \<le> i + 1 * clk_period - 1"
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms
unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence **: "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using posedge by blast
hence "(i + 0 * clk_period) mod clk_period = 0" and "(i + 1 * clk_period) mod clk_period = 0"
by auto
then obtain k1 where "i + 0 * clk_period = k1 * clk_period"
by (metis Nat.add_0_right div_mult_mod_eq)
hence "i + 1 * clk_period = (k1 + 1) * clk_period"
by simp
have "i + 0 * clk_period < k"
using \<open>i + 0 * clk_period + 1 \<le> k\<close> by linarith
have "k < i + 1 * clk_period"
using \<open>k \<le> i + 1 * clk_period - 1\<close> f1 by linarith
have "k div clk_period = k1"
apply (rule Misc_Arithmetic.sdl)
apply (metis \<open>i + 0 * clk_period < k\<close> \<open>i + 0 * clk_period = k1 * clk_period\<close> less_le_not_le mult.commute)
by (metis Suc_eq_plus1 \<open>i + 1 * clk_period = (k1 + 1) * clk_period\<close> \<open>k < i + 1 * clk_period\<close> mult.commute)
hence "k = k1 * clk_period + k mod clk_period"
by (meson mod_div_decomp)
hence "k mod clk_period \<noteq> 0"
using \<open>i + 0 * clk_period < k\<close> \<open>i + 0 * clk_period = k1 * clk_period\<close> by linarith
thus "\<not> (is_posedge2 (snd tw') CLK k)"
using "**" by auto
qed
have "wline_of tw' COUNTER (i + 0 * clk_period + 1) = wline_of tw' COUNTER (i + 1 * clk_period - 1)"
using temp[OF f3] by auto
thus ?thesis
using `ubin_of COUNTER at_time (i + 1 * clk_period - 1) on tw' = 5`
by auto
qed }
moreover
{ assume "wline_of tw' STATE (i + 1 * clk_period - 1) = V_PRE"
have "bval_of (wline_of tw' CTR_NEQ_0 (i + 1 * clk_period - 1))"
proof (rule ccontr)
assume "\<not> bval_of (wline_of tw' CTR_NEQ_0 (i + 1 * clk_period - 1))"
have "Inv_core (i + 1 * clk_period + 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
have "Inv_core (i + 1 * clk_period - 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
hence "inv_n0 (i + 1 * clk_period - 1, snd tw')"
by auto
hence "\<not> (0 < ubin_of COUNTER at_time i + 1 * clk_period - 1 - 1 on tw')"
using `\<not> bval_of (wline_of tw' CTR_NEQ_0 (i + 1 * clk_period - 1))`
unfolding inv_n0_def comp_def snd_conv fst_conv by auto
hence "\<not> (0 < ubin_of COUNTER at_time i + 1 * clk_period - 2 on tw')"
by (metis diff_diff_left nat_1_add_1)
hence "ubin_of COUNTER at_time i + 1 * clk_period - 2 on tw' = 0"
using bl_to_bin_ge0 by smt
hence "ubin_of COUNTER at_time i + 1 * clk_period - 1 on tw' = 0"
proof -
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms
unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence **: "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using posedge by blast
hence "(i + 1 * clk_period) mod clk_period = 0"
by auto
have "(i + 1 * clk_period - 2) mod clk_period \<noteq> 0"
proof -
have "i + 0 * clk_period < i + 1 * clk_period - 2"
using assms by (auto)
moreover have "i + 1 * clk_period - 2 < i + 1 * clk_period"
using assms by auto
ultimately show ?thesis
by (metis \<open>(i + 1 * clk_period) mod clk_period = 0\<close> assms(3) assms(4) diff_add_0 diff_add_inverse
dvd_add_left_iff dvd_antisym less_imp_add_positive less_nat_zero_code mod_0_imp_dvd nat_diff_split_asm numeral_plus_numeral semiring_norm(5))
qed
hence "\<not> is_posedge2 (snd tw') CLK (i + 1 * clk_period - 2)"
using ** by auto
moreover have "inv_reg (i + 1 * clk_period - 1, snd tw')"
using `Inv_core (i + 1 * clk_period - 1, snd tw')` by auto
ultimately have "wline_of tw' COUNTER (i + 1 * clk_period - 1) = wline_of tw' COUNTER (i + 1 * clk_period - 2)"
using `\<not> is_posedge2 (snd tw') CLK (i + 1 * clk_period - 2)`
unfolding inv_reg_alt_def comp_def snd_conv fst_conv by (metis diff_diff_left one_add_one)
thus ?thesis
using `ubin_of COUNTER at_time i + 1 * clk_period - 2 on tw' = 0` by auto
qed
have "ubin_of NEXT_COUNTER at_time i + 1 * clk_period on tw' = 7"
proof -
have "Inv_core (i + 1 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
hence "inv_ncounter (i + 1 * clk_period, snd tw')"
by auto
hence "ubin_of NEXT_COUNTER at_time i + 1 * clk_period on tw' = bintrunc 3 ((ubin_of COUNTER at_time i + 1 * clk_period - 1 on tw') - 1)"
using `wline_of tw' STATE (i + 1 * clk_period - 1) = V_PRE`
unfolding inv_ncounter_alt_def comp_def snd_conv fst_conv by auto
also have "... = bintrunc 3 (-1)"
using `ubin_of COUNTER at_time i + 1 * clk_period - 1 on tw' = 0` by auto
also have "... = 7"
by eval
finally show ?thesis
by auto
qed
hence "ubin_of COUNTER at_time i + 1 * clk_period + 1 on tw' = 7"
using `is_posedge2 (snd tw') CLK (i + 1 * clk_period)` `wline_of tw' RST (i + 1 * clk_period) = Bv False`
using `Inv_core (i + 1 * clk_period + 1, snd tw')`
unfolding inv_reg_alt_def comp_def snd_conv fst_conv by auto
with `wline_of tw' STATE (i + 1 * clk_period + 1) = V_PROC \<and> ubin_of COUNTER at_time (i + 1 * clk_period + 1) on tw' = 4`
show False
by auto
qed
have "ubin_of NEXT_COUNTER at_time i + 1 * clk_period on tw' = 4"
proof -
have "Inv_core (i + 1 * clk_period + 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
thus ?thesis
using `wline_of tw' STATE (i + 1 * clk_period + 1) = V_PROC \<and> ubin_of COUNTER at_time (i + 1 * clk_period + 1) on tw' = 4`
`is_posedge2 (snd tw') CLK (i + 1 * clk_period)` `wline_of tw' RST (i + 1 * clk_period) = Bv False`
unfolding inv_reg_alt_def comp_def snd_conv fst_conv by auto
qed
have "bintrunc 3 (ubin_of COUNTER at_time (i + 1 * clk_period - 1) on tw' - 1) = 4"
proof -
have "Inv_core (i + 1 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
thus ?thesis
using `ubin_of NEXT_COUNTER at_time (i + 1 * clk_period) on tw' = 4`
`wline_of tw' STATE (i + 1 * clk_period - 1) = V_PRE` `bval_of (wline_of tw' CTR_NEQ_0 (i + 1 * clk_period - 1))`
unfolding inv_ncounter_alt_def fst_conv comp_def snd_conv by auto
qed
hence "(ubin_of COUNTER at_time (i + 1 * clk_period - 1) on tw' - 1) mod 8 = 4"
unfolding bintrunc_mod2p by auto
have "0 < ubin_of COUNTER at_time i + 1 * clk_period - 2 on tw'"
proof -
have "Inv_core (i + 1 * clk_period - 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
hence "inv_n0 (i + 1 * clk_period - 1, snd tw')"
by auto
hence "0 < bl_to_bin (lval_of (snd (snd tw') COUNTER (i + 1 * clk_period - 1 - 1)))"
using `wline_of tw' STATE (i + 1 * clk_period - 1) = V_PRE` `bval_of (wline_of tw' CTR_NEQ_0 (i + 1 * clk_period - 1))`
unfolding inv_n0_def comp_def snd_conv fst_conv by auto
thus ?thesis
unfolding comp_def snd_conv fst_conv
by (metis diff_diff_left nat_1_add_1)
qed
moreover have "ubin_of COUNTER at_time i + 1 * clk_period - 2 on tw' = ubin_of COUNTER at_time i + 1 * clk_period - 1 on tw'"
proof -
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms
unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence **: "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using posedge by blast
hence "(i + 1 * clk_period) mod clk_period = 0"
by auto
have "(i + 1 * clk_period - 2) mod clk_period \<noteq> 0"
proof -
have "i + 0 * clk_period < i + 1 * clk_period - 2"
using assms by (auto)
moreover have "i + 1 * clk_period - 2 < i + 1 * clk_period"
using assms by auto
ultimately show ?thesis
by (metis \<open>(i + 1 * clk_period) mod clk_period = 0\<close> assms(3) assms(4) diff_add_0 diff_add_inverse
dvd_add_left_iff dvd_antisym less_imp_add_positive less_nat_zero_code mod_0_imp_dvd nat_diff_split_asm numeral_plus_numeral semiring_norm(5))
qed
hence "\<not> is_posedge2 (snd tw') CLK (i + 1 * clk_period - 2)"
using ** by auto
moreover have "Inv_core (i + 1 * clk_period - 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
ultimately show ?thesis
unfolding inv_reg_alt_def comp_def snd_conv fst_conv
using diff_diff_left nat_1_add_1 by presburger
qed
ultimately have "0 < ubin_of COUNTER at_time i + 1 * clk_period - 1 on tw'"
by auto
moreover have "ubin_of COUNTER at_time (i + 1 * clk_period - 1) on tw' \<le> 7"
using ubin_counter_atmost[OF `wityping \<Gamma> (snd tw')`] by auto
ultimately have "(ubin_of COUNTER at_time (i + 1 * clk_period - 1) on tw' - 1) mod 8 = ubin_of COUNTER at_time (i + 1 * clk_period - 1) on tw' - 1"
by (auto intro!: int_mod_eq')
hence "ubin_of COUNTER at_time (i + 1 * clk_period - 1) on tw' = 5"
using `(ubin_of COUNTER at_time (i + 1 * clk_period - 1) on tw' - 1) mod 8 = 4` by auto
have "ubin_of COUNTER at_time (i + 1) on tw' = 5"
proof -
have f0: "fst tw \<le> i + 0 * clk_period + 1"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] by auto
have f1: "i + 0 * clk_period + 1 \<le> i + 1 * clk_period - 1"
using assms by auto
have f2: "i + 1 * clk_period - 1 \<le> i + 7 * clk_period + 1"
by auto
note temp = registers_unchanged_no_rising_edge[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)` f0 f1 f2]
have f3: "\<And>k. i + 0 * clk_period + 1 \<le> k \<Longrightarrow> k \<le> i + 1 * clk_period - 1 \<Longrightarrow> \<not> (is_posedge2 (snd tw') CLK k)"
proof -
fix k
assume " i + 0 * clk_period + 1 \<le> k" and "k \<le> i + 1 * clk_period - 1"
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms
unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence **: "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using posedge by blast
hence "(i + 0 * clk_period) mod clk_period = 0" and "(i + 1 * clk_period) mod clk_period = 0"
by auto
then obtain k1 where "i + 0 * clk_period = k1 * clk_period"
by (metis Nat.add_0_right div_mult_mod_eq)
hence "i + 1 * clk_period = (k1 + 1) * clk_period"
by simp
have "i + 0 * clk_period < k"
using \<open>i + 0 * clk_period + 1 \<le> k\<close> by linarith
have "k < i + 1 * clk_period"
using \<open>k \<le> i + 1 * clk_period - 1\<close> f1 by linarith
have "k div clk_period = k1"
apply (rule Misc_Arithmetic.sdl)
apply (metis \<open>i + 0 * clk_period < k\<close> \<open>i + 0 * clk_period = k1 * clk_period\<close> less_le_not_le mult.commute)
by (metis Suc_eq_plus1 \<open>i + 1 * clk_period = (k1 + 1) * clk_period\<close> \<open>k < i + 1 * clk_period\<close> mult.commute)
hence "k = k1 * clk_period + k mod clk_period"
by (meson mod_div_decomp)
hence "k mod clk_period \<noteq> 0"
using \<open>i + 0 * clk_period < k\<close> \<open>i + 0 * clk_period = k1 * clk_period\<close> by linarith
thus "\<not> (is_posedge2 (snd tw') CLK k)"
using "**" by auto
qed
have "wline_of tw' COUNTER (i + 0 * clk_period + 1) = wline_of tw' COUNTER (i + 1 * clk_period - 1)"
using temp[OF f3] by auto
thus ?thesis
using `ubin_of COUNTER at_time (i + 1 * clk_period - 1) on tw' = 5`
by auto
qed }
ultimately have "ubin_of COUNTER at_time (i + 1) on tw' = 5"
by auto
with assms(10) show False
by auto
qed
ultimately have "wline_of tw' STATE (i + 2 * clk_period - 1) = V_PRE"
by auto
\<comment> \<open>obtaining counter\<close>
have "wline_of tw' STATE (i + 1 * clk_period + 1) = V_PRE "
proof -
have f0: "fst tw \<le> i + 1 * clk_period + 1"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] by auto
have f1: "i + 1 * clk_period + 1 \<le> i + 2 * clk_period - 1"
using assms by auto
have f2: "i + 2 * clk_period - 1 \<le> i + 7 * clk_period + 1"
by auto
note temp = registers_unchanged_no_rising_edge[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)` f0 f1 f2]
have f3: "\<And>k. i + 1 * clk_period + 1 \<le> k \<Longrightarrow> k \<le> i + 2 * clk_period - 1 \<Longrightarrow> \<not> (is_posedge2 (snd tw') CLK k)"
proof -
fix k
assume " i + 1 * clk_period + 1 \<le> k" and "k \<le> i + 2 * clk_period - 1"
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms
unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence **: "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using posedge by blast
hence "(i + 1 * clk_period) mod clk_period = 0" and "(i + 2 * clk_period) mod clk_period = 0"
by auto
then obtain k1 where "i + 1 * clk_period = k1 * clk_period"
by (metis Nat.add_0_right div_mult_mod_eq)
hence "i + 2 * clk_period = (k1 + 1) * clk_period"
by simp
have "i + 1 * clk_period < k"
using \<open>i + 1 * clk_period + 1 \<le> k\<close> by linarith
have "k < i + 2 * clk_period"
using \<open>k \<le> i + 2 * clk_period - 1\<close> f1 by linarith
have "k div clk_period = k1"
apply (rule Misc_Arithmetic.sdl)
apply (metis \<open>i + 1 * clk_period < k\<close> \<open>i + 1 * clk_period = k1 * clk_period\<close> less_le_not_le mult.commute)
by (metis Suc_eq_plus1 \<open>i + 2 * clk_period = (k1 + 1) * clk_period\<close> \<open>k < i + 2 * clk_period\<close> mult.commute)
hence "k = k1 * clk_period + k mod clk_period"
by (meson mod_div_decomp)
hence "k mod clk_period \<noteq> 0"
using \<open>i + 1 * clk_period < k\<close> \<open>i + 1 * clk_period = k1 * clk_period\<close> by linarith
thus "\<not> (is_posedge2 (snd tw') CLK k)"
using "**" by auto
qed
have "wline_of tw' STATE (i + 1 * clk_period + 1) = wline_of tw' STATE (i + 2 * clk_period - 1)"
using temp[OF f3] by auto
thus ?thesis
using `wline_of tw' STATE (i + 2 * clk_period - 1) = V_PRE`
by auto
qed
have "is_posedge2 (snd tw') CLK (i + 1 * clk_period)"
proof -
have "is_posedge2 w CLK (i + 2 * clk_period)"
using \<open>is_posedge2 (snd tw') CLK (i + 2 * clk_period)\<close>
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
hence "is_posedge2 w CLK (i + 2 * clk_period - clk_period)"
using assms by auto
hence "is_posedge2 w CLK (i + 1 * clk_period)"
by (auto simp add:field_simps)
thus "is_posedge2 (snd tw') CLK (i + 1 * clk_period)"
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
qed
have "wline_of tw' RST (i + 1 * clk_period) = Bv False"
proof (rule ccontr)
assume "wline_of tw' RST (i + 1 * clk_period) \<noteq> Bv False"
have "wityping \<Gamma> (snd tw')"
using `wityping \<Gamma> (snd tw)` world_sim_fin_preserves_wityping[OF 0]
using conc_stmt_wf_arch cwt_arch nonneg_delay_conc_architecture by blast
hence "type_of (wline_of tw' RST (i + 1 * clk_period)) = Bty"
unfolding wityping_def wtyping_def using cosine_locale_axioms unfolding cosine_locale_def by auto
hence "wline_of tw' RST (i + 1 * clk_period) = Bv True"
using `wline_of tw' RST (i + 1 * clk_period) \<noteq> Bv False` type_of_bty_cases by blast
moreover have "Inv_core (i + 1 * clk_period + 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
ultimately have "wline_of tw' STATE (i + 1 * clk_period + 1) = V_INIT"
using `is_posedge2 (snd tw') CLK (i + 1 * clk_period)`
unfolding inv_reg_alt_def comp_def snd_conv fst_conv by auto
thus False
using `wline_of tw' STATE (i + 1 * clk_period + 1) = V_PRE`
by auto
qed
have "wline_of tw' NEXT_STATE (i + 1 * clk_period ) = V_PRE"
proof -
have "Inv_core (i + 1 * clk_period + 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
thus ?thesis
using `is_posedge2 (snd tw') CLK (i + 1 * clk_period)` `wline_of tw' RST (i + 1 * clk_period) = Bv False`
`wline_of tw' STATE (i + 1 * clk_period + 1) = V_PRE`
unfolding inv_reg_alt_def comp_def snd_conv fst_conv by auto
qed
have "wline_of tw' STATE (i + 1 * clk_period - 1) = V_WAIT \<and> bval_of (wline_of tw' INREADY (i + 1 * clk_period - 1))"
proof (rule ccontr)
have "Inv_core (i + 1 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
hence inv:"inv_nstate (i + 1 * clk_period, snd tw')"
by auto
assume "\<not> (wline_of tw' STATE (i + 1 * clk_period - 1) = V_WAIT \<and> bval_of (wline_of tw' INREADY (i + 1 * clk_period - 1)))"
hence *: "(wline_of tw' STATE (i + 1 * clk_period - 1) = V_WAIT \<Longrightarrow> \<not> bval_of (wline_of tw' INREADY (i + 1 * clk_period - 1)))"
by auto
let ?state = "wline_of tw' STATE (i + 1 * clk_period - 1) "
consider "?state = V_INIT" | "?state = V_WAIT" | "?state = V_PROC" | "?state = V_POST"
| "?state \<noteq> V_INIT \<and> ?state \<noteq> V_WAIT \<and> ?state \<noteq> V_PRE \<and> ?state \<noteq> V_PROC \<and> ?state \<noteq> V_POST"
| "?state = V_PRE"
by auto
thus False
proof (cases)
case 1
hence "wline_of tw' NEXT_STATE (i + 1 * clk_period) \<noteq> V_PRE"
using inv unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 1 * clk_period) = V_PRE`
by auto
next
case 2
hence "wline_of tw' NEXT_STATE (i + 1 * clk_period) \<noteq> V_PRE"
using inv * unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 1 * clk_period) = V_PRE`
by auto
next
case 3
hence "wline_of tw' NEXT_STATE (i + 1 * clk_period) \<noteq> V_PRE"
using inv unfolding inv_nstate_alt_def comp_def snd_conv fst_conv
by (cases "bval_of (snd (snd tw') CTR_NEQ_0 (i + 1 * clk_period - 1))") auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 1 * clk_period) = V_PRE`
by auto
next
case 4
hence "wline_of tw' NEXT_STATE (i + 1 * clk_period) \<noteq> V_PRE"
using inv unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 1 * clk_period) = V_PRE`
by auto
next
case 5
hence "wline_of tw' NEXT_STATE (i + 1 * clk_period) \<noteq> V_PRE"
using inv * unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 1 * clk_period) = V_PRE`
by auto
next
case 6
hence "wline_of tw' NEXT_STATE (i + 1 * clk_period) \<noteq> V_PRE"
using inv * unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 1 * clk_period) = V_PRE`
by auto
qed
qed
have "wline_of tw' STATE (i + 1) = V_WAIT"
proof -
have f0: "fst tw \<le> i + 0 * clk_period + 1"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] by auto
have f1: "i + 0 * clk_period + 1 \<le> i + 1 * clk_period - 1"
using assms by auto
have f2: "i + 1 * clk_period - 1 \<le> i + 7 * clk_period + 1"
by auto
note temp = registers_unchanged_no_rising_edge[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)` f0 f1 f2]
have f3: "\<And>k. i + 0 * clk_period + 1 \<le> k \<Longrightarrow> k \<le> i + 1 * clk_period - 1 \<Longrightarrow> \<not> (is_posedge2 (snd tw') CLK k)"
proof -
fix k
assume " i + 0 * clk_period + 1 \<le> k" and "k \<le> i + 1 * clk_period - 1"
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms
unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence **: "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using posedge by blast
hence "(i + 0 * clk_period) mod clk_period = 0" and "(i + 1 * clk_period) mod clk_period = 0"
by auto
then obtain k1 where "i + 0 * clk_period = k1 * clk_period"
by (metis Nat.add_0_right div_mult_mod_eq)
hence "i + 1 * clk_period = (k1 + 1) * clk_period"
by simp
have "i + 0 * clk_period < k"
using \<open>i + 0 * clk_period + 1 \<le> k\<close> by linarith
have "k < i + 1 * clk_period"
using \<open>k \<le> i + 1 * clk_period - 1\<close> f1 by linarith
have "k div clk_period = k1"
apply (rule Misc_Arithmetic.sdl)
apply (metis \<open>i + 0 * clk_period < k\<close> \<open>i + 0 * clk_period = k1 * clk_period\<close> less_le_not_le mult.commute)
by (metis Suc_eq_plus1 \<open>i + 1 * clk_period = (k1 + 1) * clk_period\<close> \<open>k < i + 1 * clk_period\<close> mult.commute)
hence "k = k1 * clk_period + k mod clk_period"
by (meson mod_div_decomp)
hence "k mod clk_period \<noteq> 0"
using \<open>i + 0 * clk_period < k\<close> \<open>i + 0 * clk_period = k1 * clk_period\<close> by linarith
thus "\<not> (is_posedge2 (snd tw') CLK k)"
using "**" by auto
qed
have "wline_of tw' STATE (i + 0 * clk_period + 1) = wline_of tw' STATE (i + 1 * clk_period - 1)"
using temp[OF f3] by auto
thus ?thesis
using `wline_of tw' STATE (i + 1 * clk_period - 1) = V_WAIT \<and> bval_of (wline_of tw' INREADY (i + 1 * clk_period - 1))`
by auto
qed
have "ubin_of NEXT_COUNTER at_time (i + clk_period) on tw' = 4"
proof -
have "Inv_core (i + 1 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
thus ?thesis
using `wline_of tw' STATE (i + 1 * clk_period - 1) = V_WAIT \<and> bval_of (wline_of tw' INREADY (i + 1 * clk_period - 1))`
unfolding inv_ncounter_alt_def comp_def snd_conv fst_conv by auto
qed
moreover have "Inv_core (i + 1 * clk_period + 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
ultimately have "ubin_of COUNTER at_time (i + clk_period + 1) on tw' = 4"
using `is_posedge2 (snd tw') CLK (i + 1 * clk_period)` `wline_of tw' RST (i + 1 * clk_period) = Bv False`
unfolding inv_reg_alt_def comp_def snd_conv fst_conv by auto
moreover have "ubin_of COUNTER at_time (i + clk_period + 1) on tw' = ubin_of COUNTER at_time (i + 2 * clk_period - 1) on tw'"
proof -
have a: "fst tw \<le> i + 1 * clk_period + 1"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] by auto
have b: "i + 1 * clk_period + 1 \<le> i + 2 * clk_period - 1"
using assms by (auto simp add: field_simps)
have c: "i + 2 * clk_period - 1 \<le> i + 7 * clk_period + 1"
by auto
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using \<open>\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0\<close> assms by blast
hence "(i + 2 * clk_period) mod clk_period = 0"
by auto
hence "(i + 1 * clk_period) mod clk_period = 0"
by auto
have d: "\<And>k. i + 1 * clk_period + 1 \<le> k \<Longrightarrow> k \<le> i + 2 * clk_period - 1 \<Longrightarrow> \<not> is_posedge2 (snd tw') CLK k"
proof -
fix n
obtain m1 where "i + 1 * clk_period = m1 * clk_period"
using `(i + 1 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 2 * clk_period = (m1 + 1) * clk_period"
proof -
obtain m2 where "i + 2 * clk_period = m2 * clk_period"
using `(i + 2 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 2 * clk_period - (i + 1 * clk_period) = clk_period"
by (auto simp add: field_simps)
hence "m2 * clk_period - m1 * clk_period = clk_period"
using `i + 1 * clk_period = m1 * clk_period` `i + 2 * clk_period = m2 * clk_period` by auto
hence "(m2 - m1) * clk_period = clk_period"
by (auto simp add: algebra_simps)
hence "m2 = Suc m1"
using `3 < clk_period ` by auto
thus ?thesis
using Suc_eq_plus1 \<open>i + 2 * clk_period = m2 * clk_period\<close> by presburger
qed
assume "i + 1 * clk_period + 1 \<le> n" and "n \<le> i + 2 * clk_period - 1"
hence "m1 * clk_period < n"
using `i + 1 * clk_period = m1 * clk_period` by linarith
have "n mod clk_period \<noteq> 0"
proof -
have "n div clk_period = m1"
apply (rule Misc_Arithmetic.sdl)
using \<open>m1 * clk_period < n\<close> apply (simp add: mult.commute)
using `n \<le> i + 2 * clk_period - 1` `i + 2 * clk_period = (m1 + 1) * clk_period` assms
by (auto simp add: field_simps)
hence "n = m1 * clk_period + n mod clk_period"
by auto
moreover have "n mod clk_period < clk_period"
using assms by (auto intro!: mod_less_divisor)
ultimately show ?thesis
using \<open>m1 * clk_period < n\<close> by linarith
qed
hence "\<not> is_posedge2 w CLK n"
using \<open>\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0\<close> by auto
thus "\<not> is_posedge2 (snd tw') CLK n"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
qed
show ?thesis
using registers_unchanged_no_rising_edge[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)` a b c d] by auto
qed
ultimately have "ubin_of COUNTER at_time (i + 2 * clk_period - 1) on tw' = 4"
by auto
\<comment> \<open> obtaining frac\<close>
have "bin_of NEXT_FRAC at_time (i + 2 *clk_period) on tw' = approx_eighth"
proof -
have "Inv_core (i + 2 *clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
hence "inv_nfrac (i + 2 *clk_period, snd tw')"
by auto
thus ?thesis
using `ubin_of COUNTER at_time i + 2 *clk_period - 1 on tw' = 4`
unfolding inv_nfrac_alt_def comp_def snd_conv fst_conv by auto
qed
hence "bin_of FRAC at_time (i + 3 * clk_period - 1) on tw' = approx_eighth"
using \<open>wline_of tw' FRAC (i + 2 * clk_period + 1) = wline_of tw' FRAC (i + 3 * clk_period - 1)\<close>
\<open>wline_of tw' NEXT_FRAC (i + 2 * clk_period) = wline_of tw' FRAC (i + 2 * clk_period + 1)\<close> by
auto
have "bin_of TERM1 at_time (i + 3 * clk_period - 1) on tw' = sbintrunc 63
(bin_of COMMON at_time (i + 3 * clk_period - 2) on tw' * bin_of ACCUM at_time (i + 3 * clk_period - 2) on tw')"
proof -
have "Inv_core (i + 3 * clk_period - 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
thus ?thesis
unfolding inv_term1_def comp_def snd_conv fst_conv by (metis diff_diff_left one_add_one)
qed
have "Fixed (word_of_int (bin_of FRAC at_time i + 3 * clk_period - 1 on tw')) = Fixed ((word_of_int approx_eighth) :: (1 + 31) word)"
using `bin_of FRAC at_time i + 3 * clk_period - 1 on tw' = approx_eighth` by auto
have "((word_of_int approx_eighth) :: (1 + 31) word) = (approx_eighth :: (1 + 31) word)"
unfolding word_uint.inverse_norm by eval
hence "Fixed ((word_of_int approx_eighth) :: (1 + 31) word) = Fixed (approx_eighth :: (1 + 31) word)"
by auto
also have "... = approx_div_fact 4"
by (simp add: eval_nat_numeral(2) numeral_3_eq_3)
finally have "Fixed (word_of_int (bin_of FRAC at_time i + 3 * clk_period - 1 on tw')) = approx_div_fact 4"
using `Fixed (word_of_int (bin_of FRAC at_time i + 3 * clk_period - 1 on tw')) = Fixed ((word_of_int approx_eighth) :: (1 + 31) word)`
by auto
moreover have "Fixed (word_of_int (bin_of FRAC at_time i + 3 * clk_period - 1 on tw')) = (fixed_of_sval (wline_of tw' FRAC (i + 3 * clk_period - 1)) :: (1,31) fixed)"
proof -
have "type_of (wline_of tw' FRAC (i + 3 * clk_period - 1)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
hence "length (lval_of (wline_of tw' FRAC (i + 3 * clk_period - 1))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
hence "Fixed (word_of_int (bin_of FRAC at_time i + 3 * clk_period - 1 on tw')) =
Fixed (word_of_int (sbintrunc (LENGTH((1+31)) - 1) (bl_to_bin (lval_of (wline_of tw' FRAC (i + 3 * clk_period - 1))))))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (bl_to_bin (lval_of (wline_of tw' FRAC (i + 3 * clk_period - 1)))) :: (1 + 31) word)"
unfolding word_sbin.Abs_norm by auto
also have "... = fixed_of_sval (wline_of tw' FRAC (i + 3 * clk_period - 1))"
proof -
have "wline_of tw' FRAC (i + 3 * clk_period - 1) = Lv Sig (lval_of (wline_of tw' FRAC (i + 3 * clk_period - 1)))"
using `type_of (wline_of tw' FRAC (i + 3 *clk_period - 1)) = Lty Sig 32`
by (metis (no_types, hide_lams) ty.distinct(1) ty.inject type_of.cases type_of.simps(1) type_of.simps(2) val.sel(3))
thus ?thesis
using fixed_of_sval.simps unfolding of_bl_def by smt
qed
finally show ?thesis
by auto
qed
ultimately have "(fixed_of_sval (wline_of tw' FRAC (i + 3 * clk_period - 1)) :: (1,31) fixed) = approx_div_fact 4"
by auto
\<comment> \<open> obtaining accum\<close>
have "bin_of NEXT_ACCUM at_time (i + 3 * clk_period) on tw' =
sbintrunc 31 (bin_of FRAC at_time i + 3 * clk_period - 1 on tw' + (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 3 * clk_period - 1)) {1 .. 32})))"
proof -
have "Inv_core (i + 3 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
thus ?thesis
using `wline_of tw' STATE (i + 3 * clk_period - 1) = V_PROC \<and> bval_of (wline_of tw' CTR_NEQ_0 (i + 3 *clk_period - 1))`
unfolding inv_naccum_alt_def comp_def snd_conv fst_conv by auto
qed
hence "bin_of ACCUM at_time (i + 3 * clk_period + 1) on tw' =
sbintrunc 31 (bin_of FRAC at_time i + 3 * clk_period - 1 on tw' + (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 3 * clk_period - 1)) {1 .. 32})))"
using `wline_of tw' NEXT_ACCUM (i + 3 * clk_period) = wline_of tw' ACCUM (i + 3 * clk_period + 1)`
by auto
hence "(word_of_int (bin_of ACCUM at_time i + 3 * clk_period + 1 on tw') :: (1 + 31) word) = word_of_int (sbintrunc 31 (bin_of FRAC at_time i + 3 * clk_period - 1 on tw' + (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 3 * clk_period - 1)) {1 .. 32}))))"
by auto
also have "... = word_of_int (sbintrunc (LENGTH((1 + 31)) - 1) (bin_of FRAC at_time i + 3 * clk_period - 1 on tw' + (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 3 * clk_period - 1)) {1 .. 32}))))"
by auto
also have "... = word_of_int (bin_of FRAC at_time i + 3 * clk_period - 1 on tw' + (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 3 * clk_period - 1)) {1 .. 32})))"
unfolding word_sbin.Abs_norm by auto
also have "... = word_of_int (bin_of FRAC at_time i + 3 * clk_period - 1 on tw') + word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 3 * clk_period - 1)) {1 .. 32}))"
unfolding wi_hom_syms(1) by auto
finally have "(word_of_int (bin_of ACCUM at_time i + 3 * clk_period + 1 on tw') :: (1 + 31) word) =
word_of_int (bin_of FRAC at_time i + 3 * clk_period - 1 on tw') + word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 3 * clk_period - 1)) {1 .. 32}))"
by auto
hence "Fixed (word_of_int (bin_of ACCUM at_time i + 3 * clk_period + 1 on tw') :: (1 + 31) word) =
Fixed (word_of_int (bin_of FRAC at_time i + 3 * clk_period - 1 on tw')) + Fixed (word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 3 * clk_period - 1)) {1 .. 32})))"
unfolding plus_fixed.abs_eq by auto
have "Fixed (word_of_int (bin_of ACCUM at_time i + 3 * clk_period + 1 on tw') :: (1 + 31) word) = fixed_of_sval (wline_of tw' ACCUM (i + 3 * clk_period + 1))"
(is "?lhs4 = ?rhs4")
proof -
have "type_of (wline_of tw' ACCUM (i + 3 * clk_period + 1)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
hence "length (lval_of (wline_of tw' ACCUM (i + 3 * clk_period + 1))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
hence "?lhs4 = Fixed (word_of_int (sbintrunc (LENGTH((1+31)) - 1) (bl_to_bin (lval_of (wline_of tw' ACCUM (i + 3 * clk_period + 1))))))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (bl_to_bin (lval_of (wline_of tw' ACCUM (i + 3 * clk_period + 1)))))"
unfolding word_sbin.Abs_norm by auto
also have "... = fixed_of_sval (wline_of tw' ACCUM (i + 3 * clk_period + 1))"
proof -
have "wline_of tw' ACCUM (i + 3 * clk_period + 1) = Lv Sig (lval_of (wline_of tw' ACCUM (i + 3 * clk_period + 1)))"
using `type_of (wline_of tw' ACCUM (i + 3 * clk_period + 1)) = Lty Sig 32`
by (metis (no_types, hide_lams) ty.distinct(1) ty.inject type_of.cases type_of.simps(1) type_of.simps(2) val.sel(3))
thus ?thesis
using fixed_of_sval.simps unfolding of_bl_def by smt
qed
finally show ?thesis
by auto
qed
have "(word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 3 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word) =
word_of_int (sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 3 * clk_period - 2)))) :: (1 + 31) word ) *
sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' ACCUM (i + 3 * clk_period - 2)))) :: (1 + 31) word) div 2 ^ 31)"
proof -
have "(word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 3 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word)=
word_of_int
(sbintrunc (length (nths (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1))) {1..32}) - 1) (bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1))) {1..32})))"
unfolding sbl_to_bin_alt_def by auto
moreover have "(length (nths (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1))) {1..32}) - 1) = 31"
proof -
have "type_of (wline_of tw' TERM1 (i + 3 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
have "card {1::nat ..32} = 32"
unfolding card_atLeastAtMost by auto
show ?thesis
unfolding length_nths *
using card_slice[where len="64" and l=62 and r="31"] by auto
qed
ultimately have "(word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 3 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word) =
word_of_int (sbintrunc 31 (bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1))) {1..32})))"
by auto
also have "... = word_of_int (sbintrunc (LENGTH(1+31) - 1) (bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1))) {1..32})))"
by auto
also have "... = (word_of_int (bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1))) {1..32})) :: (1 + 31) word) "
unfolding word_sbin.Abs_norm by auto
finally have "word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 3 * clk_period - 1)) {1 .. 32})) =
(word_of_int ( bl_to_bin (nths (lof_wline tw' TERM1 (i + 3 * clk_period - 1)) {1 .. 32})) :: (1+31) word)"
by auto
have interval: "{1 :: nat .. 32} = {1 :: nat ..< 33}"
by auto
have nths: "\<And>xs:: bool list. nths xs {1 :: nat .. 32} = drop 1 (take 33 xs)"
unfolding interval nths_from_upt_eq_drop_take[where m="1" and n="33"] by auto
have " bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1))) {1 ..32}) =
bl_to_bin (drop 1 (take 33 (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1)))))"
using nths[of "(lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1)))"] by auto
also have "... = bintrunc (length (take 33 (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1)))) - 1) (bl_to_bin (take 33 (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1)))))"
unfolding bl2bin_drop by auto
also have "... = bintrunc 32 (bl_to_bin (take 33 (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1)))))"
proof-
have "type_of (wline_of tw' TERM1 (i + 3 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
hence " length (take 33 (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1)))) = 33"
unfolding length_take by auto
thus ?thesis
by auto
qed
also have "... = bintrunc 32 (bl_to_bin (take (length (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1))) - 31) (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1)))))"
proof-
have "type_of (wline_of tw' TERM1 (i + 3 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
thus ?thesis
by auto
qed
also have "... = bintrunc 32 ((bin_rest ^^ 31) (bl_to_bin (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1)))))"
unfolding take_rest_bl2bin by auto
finally have "bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1))) {1 ..32}) =
bintrunc 32 ((bin_rest ^^ 31) (bl_to_bin (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1)))))"
by auto
have "(word_of_int (bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1))) {1 ..32})) :: (1+31) word)=
word_of_int (bintrunc 32 ((bin_rest ^^ 31) (bl_to_bin (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1))))))"
using \<open>bl_to_bin (nths (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1))) {1..32}) = bintrunc 32 ((bin_rest ^^ 31) (bl_to_bin (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1)))))\<close>
by auto
\<comment> \<open>push bintrunc 32 inside\<close>
also have "... = word_of_int ((bin_rest ^^ 31) (bintrunc 63 (bl_to_bin (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1))))))"
using bin_rest_power_trunc[where n="63" and k="31", symmetric] by auto
also have "... = word_of_int ((bin_rest ^^ 31) (bl_to_bin (drop 1 (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1))))))"
proof -
have "type_of (wline_of tw' TERM1 (i + 3 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
thus ?thesis
using bl2bin_drop by auto
qed
\<comment> \<open>pull bl_to_bin to left\<close>
also have "... = word_of_int (bl_to_bin ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1))))))"
unfolding butlast_pow_rest_bl2bin[symmetric] by auto
\<comment> \<open>change to sbl_to_bin\<close>
also have "... = (word_of_int (sbintrunc (LENGTH(1+31) - 1) (bl_to_bin ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1))))))) :: (1 + 31) word)"
unfolding word_sbin.Abs_norm by auto
also have "... = word_of_int (sbl_to_bin ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1))))))"
proof -
have "type_of (wline_of tw' TERM1 (i + 3 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
have "length ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1))))) = 32"
unfolding butlast_power length_take length_drop * by eval
hence "(word_of_int (sbintrunc (LENGTH(1+31) - 1) (bl_to_bin ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1))))))) :: (1 + 31) word) =
(word_of_int (sbintrunc (length ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1))))) - 1) (bl_to_bin ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1))))))) :: (1 + 31) word)"
by auto
thus ?thesis
using sbl_to_bin_alt_def by auto
qed
\<comment> \<open>push sbl_to_bin back to right\<close>
also have "... = word_of_int ((bin_rest ^^ 31) (sbl_to_bin (drop 1 (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1))))))"
proof -
have "type_of (wline_of tw' TERM1 (i + 3 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
have "length ((drop 1 (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1))))) = 63"
unfolding length_take length_drop * by eval
hence **: "31 < length ((drop 1 (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1)))))"
by auto
show ?thesis
unfolding butlast_pow_rest_sbl2bin[OF **] by auto
qed
also have "... = word_of_int ((bin_rest ^^ 31) (sbintrunc 62 (sbl_to_bin (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1))))))"
proof -
have "type_of (wline_of tw' TERM1 (i + 3 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' TERM1 (i + 3 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
thus ?thesis
using sbl2bin_drop by auto
qed
also have "... = word_of_int ((bin_rest ^^ 31) (sbintrunc 62 (bin_of COMMON at_time (i + 3 * clk_period - 2) on tw' * bin_of ACCUM at_time (i + 3 * clk_period - 2) on tw')))"
using `bin_of TERM1 at_time (i + 3 *clk_period - 1) on tw' = sbintrunc 63
(bin_of COMMON at_time (i + 3 *clk_period - 2) on tw' * bin_of ACCUM at_time (i + 3 *clk_period - 2) on tw')`
by auto
also have "... = word_of_int (sbintrunc 31 ((bin_rest ^^ 31) (bin_of COMMON at_time (i + 3 * clk_period - 2) on tw' * bin_of ACCUM at_time (i + 3 * clk_period - 2) on tw')))"
proof -
have "(31 :: nat) \<le> 62" by auto
show ?thesis
unfolding bin_rest_power_strunc[OF `31 \<le> 62`]
by auto
qed
also have "... = word_of_int (sbintrunc (LENGTH(1 + 31) - 1) ((bin_rest ^^ 31) (bin_of COMMON at_time (i + 3 * clk_period - 2) on tw' * bin_of ACCUM at_time (i + 3 * clk_period - 2) on tw')))"
by auto
also have "... = word_of_int ((bin_rest ^^ 31) (bin_of COMMON at_time (i + 3 * clk_period - 2) on tw' * bin_of ACCUM at_time (i + 3 * clk_period - 2) on tw'))"
unfolding word_sbin.Abs_norm by auto
also have "... = word_of_int ((bin_of COMMON at_time (i + 3 * clk_period - 2) on tw' * bin_of ACCUM at_time (i + 3 * clk_period - 2) on tw') div 2 ^ 31)"
unfolding bin_rest_compow by auto
also have "... = word_of_int (sbintrunc (length (lval_of (wline_of tw' COMMON (i + 3 * clk_period - 2))) - 1) (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 3 * clk_period - 2)))) *
sbintrunc (length (lval_of (wline_of tw' ACCUM (i + 3 * clk_period - 2))) - 1) (sbl_to_bin (lval_of (wline_of tw' ACCUM (i + 3 * clk_period - 2)))) div 2 ^ 31)"
using sbl_to_bin_alt_def2 by auto
also have "... = word_of_int (sbintrunc (LENGTH(1 + 31) - 1) (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 3 * clk_period - 2)))) *
sbintrunc (LENGTH(1 + 31) - 1) (sbl_to_bin (lval_of (wline_of tw' ACCUM (i + 3 * clk_period - 2)))) div 2 ^ 31)"
proof -
have "type_of (wline_of tw' COMMON (i + 3 * clk_period - 2)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' COMMON (i + 3 * clk_period - 2))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
have "type_of (wline_of tw' ACCUM (i + 3 * clk_period - 2)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence **: "length (lval_of (wline_of tw' ACCUM (i + 3 * clk_period - 2))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
with * show ?thesis
by auto
qed
also have "... = word_of_int (sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 3 * clk_period - 2)))) :: (1 + 31) word) *
sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' ACCUM (i + 3 * clk_period - 2)))) :: (1 + 31) word ) div 2 ^ 31)"
unfolding sint_sbintrunc' by auto
finally show ?thesis
unfolding `(word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 3 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word) =
(word_of_int ( bl_to_bin (nths (lof_wline tw' TERM1 (i + 3 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word)`
by auto
qed
hence "Fixed (word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 3 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word) =
Fixed (word_of_int (sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 3 * clk_period - 2)))) :: (1 + 31) word ) *
sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' ACCUM (i + 3 * clk_period - 2)))) :: (1 + 31) word) div 2 ^ 31))"
by auto
also have "... = Fixed (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 3 * clk_period - 2))))) * Fixed (word_of_int (sbl_to_bin (lval_of (wline_of tw' ACCUM (i + 3 * clk_period - 2)))))"
using times_fixed.abs_eq[where xa="word_of_int (bin_of COMMON at_time i + 3 * clk_period - 2 on tw') :: (1 + 31) word" and
x="word_of_int (bin_of ACCUM at_time i + 3 * clk_period - 2 on tw') :: (1 + 31) word", symmetric]
by auto
also have "... = fixed_of_sval (wline_of tw' COMMON (i + 3 * clk_period - 2)) * fixed_of_sval (wline_of tw' ACCUM (i + 3 * clk_period - 2))"
proof -
have "type_of (wline_of tw' COMMON (i + 3 * clk_period - 2)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
hence "length (lval_of (wline_of tw' COMMON (i + 3 * clk_period - 2))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
hence "Fixed (word_of_int (bin_of COMMON at_time i + 3 * clk_period - 2 on tw')) =
Fixed (word_of_int (sbintrunc (LENGTH((1+31)) - 1) (bl_to_bin (lval_of (wline_of tw' COMMON (i + 3 * clk_period - 2))))))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (bl_to_bin (lval_of (wline_of tw' COMMON (i + 3 * clk_period - 2)))) :: (1 + 31) word)"
unfolding word_sbin.Abs_norm by auto
also have "... = fixed_of_sval (wline_of tw' COMMON (i + 3 * clk_period - 2))"
proof -
have "wline_of tw' COMMON (i + 3 * clk_period - 2) = Lv Sig (lval_of (wline_of tw' COMMON (i + 3 * clk_period - 2)))"
using `type_of (wline_of tw' COMMON (i + 3 *clk_period - 2)) = Lty Sig 32`
by (metis (no_types, hide_lams) ty.distinct(1) ty.inject type_of.cases type_of.simps(1) type_of.simps(2) val.sel(3))
thus ?thesis
using fixed_of_sval.simps unfolding of_bl_def by smt
qed
finally have "Fixed (word_of_int (bin_of COMMON at_time i + 3 * clk_period - 2 on tw') :: (1 + 31) word) = fixed_of_sval (wline_of tw' COMMON (i + 3 * clk_period - 2))"
by auto
have "type_of (wline_of tw' ACCUM (i + 3 * clk_period - 2)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
hence "length (lval_of (wline_of tw' ACCUM (i + 3 * clk_period - 2))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
hence "Fixed (word_of_int (bin_of ACCUM at_time i + 3 * clk_period - 2 on tw')) =
Fixed (word_of_int (sbintrunc (LENGTH((1+31)) - 1) (bl_to_bin (lval_of (wline_of tw' ACCUM (i + 3 * clk_period - 2))))))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (bl_to_bin (lval_of (wline_of tw' ACCUM (i + 3 * clk_period - 2)))) :: (1 + 31) word)"
unfolding word_sbin.Abs_norm by auto
also have "... = fixed_of_sval (wline_of tw' ACCUM (i + 3 * clk_period - 2))"
proof -
have "wline_of tw' ACCUM (i + 3 * clk_period - 2) = Lv Sig (lval_of (wline_of tw' ACCUM (i + 3 * clk_period - 2)))"
using `type_of (wline_of tw' ACCUM (i + 3 *clk_period - 2)) = Lty Sig 32`
by (metis (no_types, hide_lams) ty.distinct(1) ty.inject type_of.cases type_of.simps(1) type_of.simps(2) val.sel(3))
thus ?thesis
using fixed_of_sval.simps unfolding of_bl_def by smt
qed
finally have "Fixed (word_of_int (bin_of ACCUM at_time i + 3 * clk_period - 2 on tw') :: (1 + 31) word) = fixed_of_sval (wline_of tw' ACCUM (i + 3 * clk_period - 2))"
by auto
thus ?thesis
using \<open>Fixed (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 3 * clk_period - 2))))) = fixed_of_sval (wline_of tw' COMMON (i + 3 * clk_period - 2))\<close> by auto
qed
finally have "Fixed (word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 3 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word) =
fixed_of_sval (wline_of tw' COMMON (i + 3 * clk_period - 2)) * fixed_of_sval (wline_of tw' ACCUM (i + 3 * clk_period - 2))"
by auto
hence "fixed_of_sval (wline_of tw' ACCUM (i + 3 * clk_period + 1)) =
approx_div_fact 4 + fixed_of_sval (wline_of tw' COMMON (i + 3 * clk_period - 2)) * fixed_of_sval (wline_of tw' ACCUM (i + 3 * clk_period - 2))"
using `?lhs4 = ?rhs4`
`Fixed (word_of_int (bin_of ACCUM at_time i + 3 * clk_period + 1 on tw') :: (1 + 31) word) =
Fixed (word_of_int (bin_of FRAC at_time i + 3 * clk_period - 1 on tw')) + Fixed (word_of_int (sbl_to_bin (nths (lof_wline tw' TERM1 (i + 3 * clk_period - 1)) {1 .. 32})))`
`Fixed (word_of_int (bin_of FRAC at_time i + 3 * clk_period - 1 on tw')) = approx_div_fact 4`
by auto
hence "fixed_of_sval (wline_of tw' ACCUM (fst tw')) = approx_div_fact 0 +
fixed_of_sval (wline_of tw' COMMON (i + 3 * clk_period - 2)) * (approx_div_fact 1 +
fixed_of_sval (wline_of tw' COMMON (i + 3 * clk_period - 2)) * (approx_div_fact 2 +
fixed_of_sval (wline_of tw' COMMON (i + 3 * clk_period - 2)) * (approx_div_fact 3 +
fixed_of_sval (wline_of tw' COMMON (i + 3 * clk_period - 2)) * (approx_div_fact 4 +
fixed_of_sval (wline_of tw' COMMON (i + 3 * clk_period - 2)) * fixed_of_sval (wline_of tw' ACCUM (i + 3 * clk_period - 2))))))"
using `fixed_of_sval (wline_of tw' ACCUM (fst tw')) = approx_div_fact 0 +
fixed_of_sval (wline_of tw' COMMON (i + 4 * clk_period - 2)) * (approx_div_fact 1 +
fixed_of_sval (wline_of tw' COMMON (i + 4 * clk_period - 2)) * (approx_div_fact 2 +
fixed_of_sval (wline_of tw' COMMON (i + 4 * clk_period - 2)) * (approx_div_fact 3 +
fixed_of_sval (wline_of tw' COMMON (i + 4 * clk_period - 2)) * fixed_of_sval (wline_of tw' ACCUM (i + 4 * clk_period - 2)))))`
using \<open>fixed_of_sval (wline_of tw' COMMON (i + 4 * clk_period - 2)) = fixed_of_sval (wline_of
tw' COMMON (i + 3 * clk_period - 1))\<close> \<open>wline_of tw' ACCUM (i + 3 * clk_period + 1) = wline_of
tw' ACCUM (i + 4 * clk_period - 2)\<close> \<open>wline_of tw' COMMON (i + 3 * clk_period - 2) = wline_of tw'
COMMON (i + 3 * clk_period - 1)\<close> by auto
\<comment> \<open>obtaining common and accum\<close>
have "wline_of tw' COMMON (i + 2 * clk_period + 1) = wline_of tw' COMMON (i + 3 * clk_period - 2)"
and "wline_of tw' ACCUM (i + 2 * clk_period + 1) = wline_of tw' ACCUM (i + 3 * clk_period - 2)"
proof -
have a: "fst tw \<le> i + 2 * clk_period + 1"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] by auto
have b: "i + 2 * clk_period + 1 \<le> i + 3 * clk_period - 2"
using assms by (auto simp add: field_simps)
have c: "i + 3 * clk_period - 2 \<le> i + 7 * clk_period + 1"
by auto
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms
unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using \<open>\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0\<close> assms by blast
hence "(i + 2 * clk_period) mod clk_period = 0"
by auto
hence "(i + 3 * clk_period) mod clk_period = 0"
by auto
have d: "\<And>k. i + 2 * clk_period + 1 \<le> k \<Longrightarrow> k \<le> i + 3 * clk_period - 1 \<Longrightarrow> \<not> is_posedge2 (snd tw') CLK k"
proof -
fix n
obtain m1 where "i + 2 * clk_period = m1 * clk_period"
using `(i + 2 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 3 * clk_period = (m1 + 1) * clk_period"
proof -
obtain m2 where "i + 3 * clk_period = m2 * clk_period"
using `(i + 3 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 4 * clk_period - (i + 3 * clk_period) = clk_period"
by (auto simp add: field_simps)
hence "m2 * clk_period - m1 * clk_period = clk_period"
using `i + 2 * clk_period = m1 * clk_period` `i + 3 * clk_period = m2 * clk_period`
by auto
hence "(m2 - m1) * clk_period = clk_period"
by (auto simp add: algebra_simps)
hence "m2 = Suc m1"
using `3 < clk_period ` by auto
thus ?thesis
using Suc_eq_plus1 \<open>i + 3 * clk_period = m2 * clk_period\<close> by presburger
qed
assume "i + 2 * clk_period + 1 \<le> n" and "n \<le> i + 3 * clk_period - 1"
hence "m1 * clk_period < n"
using `i + 2 * clk_period = m1 * clk_period` by linarith
have "n mod clk_period \<noteq> 0"
proof -
have "n div clk_period = m1"
apply (rule Misc_Arithmetic.sdl)
using \<open>m1 * clk_period < n\<close> apply (simp add: mult.commute)
using `n \<le> i + 3 * clk_period - 1` `i + 3 * clk_period = (m1 + 1) * clk_period` assms
by (auto simp add: field_simps)
hence "n = m1 * clk_period + n mod clk_period"
by auto
moreover have "n mod clk_period < clk_period"
using assms by (auto intro!: mod_less_divisor)
ultimately show ?thesis
using \<open>m1 * clk_period < n\<close> by linarith
qed
hence "\<not> is_posedge2 w CLK n"
using \<open>\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0\<close> by auto
thus "\<not> is_posedge2 (snd tw') CLK n"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
qed
show "wline_of tw' COMMON (i + 2 * clk_period + 1) = wline_of tw' COMMON (i + 3 * clk_period - 2)"
and "wline_of tw' ACCUM (i + 2 * clk_period + 1) = wline_of tw' ACCUM (i + 3 * clk_period - 2)"
using registers_unchanged_no_rising_edge[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)` a b c d]
by auto
qed
have "Inv_core (i + 2 * clk_period + 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
have "is_posedge2 (snd tw') CLK (i + 2 * clk_period)"
proof -
have "is_posedge2 w CLK (i + 3 * clk_period)"
using `is_posedge2 (snd tw') CLK (i + 3 * clk_period)`
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
hence "is_posedge2 w CLK (i + 3 * clk_period - clk_period)"
using assms by auto
hence "is_posedge2 w CLK (i + 2 * clk_period)"
by (auto simp add:field_simps)
thus "is_posedge2 (snd tw') CLK (i + 2 * clk_period)"
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
qed
have "wline_of tw' RST (i + 2 * clk_period) = Bv False"
proof (rule ccontr)
assume "wline_of tw' RST (i + 2 * clk_period) \<noteq> Bv False"
have "wityping \<Gamma> (snd tw')"
using `wityping \<Gamma> (snd tw)` world_sim_fin_preserves_wityping[OF 0]
using conc_stmt_wf_arch cwt_arch nonneg_delay_conc_architecture by blast
hence "type_of (wline_of tw' RST (i + 2 * clk_period)) = Bty"
unfolding wityping_def wtyping_def using cosine_locale_axioms unfolding cosine_locale_def by auto
hence "wline_of tw' RST (i + 2 * clk_period) = Bv True"
using `wline_of tw' RST (i + 2 * clk_period) \<noteq> Bv False` type_of_bty_cases by blast
hence "wline_of tw' STATE (i + 2 * clk_period + 1) = V_INIT"
using `Inv_core ((i + 2 * clk_period + 1, snd tw'))` `is_posedge2 (snd tw') CLK (i + 2 * clk_period)` unfolding inv_reg_alt_def
comp_def snd_conv fst_conv by auto
with `wline_of tw' STATE (i + 2 * clk_period + 1) = V_PROC` show False
by auto
qed
have "wline_of tw' NEXT_COMMON (i + 2 * clk_period) = wline_of tw' COMMON (i + 2 * clk_period + 1)"
and "wline_of tw' NEXT_ACCUM (i + 2 * clk_period) = wline_of tw' ACCUM (i + 2 * clk_period + 1)"
using `Inv_core (i + 2 * clk_period + 1, snd tw')` `is_posedge2 (snd tw') CLK (i + 2 * clk_period)` `wline_of tw' RST (i + 2 * clk_period) = Bv False`
unfolding inv_reg_alt_def comp_def snd_conv fst_conv by auto
have "sbintrunc 31 ((sbl_to_bin (nths (lof_wline tw' SQUARE_TEMP (i + 2 * clk_period - 1)) {1 .. 32}))) =
bin_of NEXT_COMMON at_time (i + 2 * clk_period) on tw'"
proof -
have "Inv_core (i + 2 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
thus ?thesis
using `wline_of tw' STATE (i + 2 * clk_period - 1) = V_PRE`
unfolding inv_ncommon_alt_def comp_def snd_conv fst_conv by auto
qed
have "(fixed_of_sval (wline_of tw' COMMON (i + 3 * clk_period - 2)) :: (1,31) fixed) =
fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2)) * fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2)) "
proof -
\<comment> \<open> obtaining square-temp\<close>
have "bin_of SQUARE_TEMP at_time (i + 2 * clk_period - 1) on tw' =
sbintrunc 63 ((sbl_to_bin (lval_of (snd (snd tw') COMMON (i + 2 * clk_period - 1 - 1))))\<^sup>2)"
proof -
have "Inv_core (i + 2 * clk_period - 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
thus ?thesis
unfolding inv_sqr_def comp_def snd_conv fst_conv by auto
qed
hence "bin_of SQUARE_TEMP at_time (i + 2 *clk_period - 1) on tw' = sbintrunc 63
(bin_of COMMON at_time (i + 2 *clk_period - 2) on tw' * bin_of COMMON at_time (i + 2 *clk_period - 2) on tw')"
unfolding power2_eq_square comp_def
using diff_diff_left nat_1_add_1 by presburger
\<comment> \<open> obtaining common\<close>
have "bin_of NEXT_COMMON at_time (i + 2 * clk_period) on tw' =
sbintrunc 31 ((sbl_to_bin (nths (lof_wline tw' SQUARE_TEMP (i + 2 * clk_period - 1)) {1 .. 32})))"
using `sbintrunc 31 ((sbl_to_bin (nths (lof_wline tw' SQUARE_TEMP (i + 2 * clk_period - 1)) {1 .. 32}))) =
bin_of NEXT_COMMON at_time (i + 2 * clk_period) on tw'`
by auto
hence "(word_of_int (bin_of NEXT_COMMON at_time i + 2 * clk_period on tw') :: (1 + 31) word) =
word_of_int (sbintrunc 31 ((sbl_to_bin (nths (lof_wline tw' SQUARE_TEMP (i + 2 * clk_period - 1)) {1 .. 32}))))"
by auto
also have "... = word_of_int (sbintrunc (LENGTH((1 + 31)) - 1) ((sbl_to_bin (nths (lof_wline tw' SQUARE_TEMP (i + 2 * clk_period - 1)) {1 .. 32}))))"
by auto
also have "... = word_of_int ( ((sbl_to_bin (nths (lof_wline tw' SQUARE_TEMP (i + 2 * clk_period - 1)) {1 .. 32}))))"
unfolding word_sbin.Abs_norm by auto
finally have "(word_of_int (bin_of NEXT_COMMON at_time i + 2 * clk_period on tw') :: (1 + 31) word) =
word_of_int ( ((sbl_to_bin (nths (lof_wline tw' SQUARE_TEMP (i + 2 * clk_period - 1)) {1 .. 32}))))"
by auto
hence "Fixed (word_of_int (bin_of NEXT_COMMON at_time i + 2 * clk_period on tw') :: (1 + 31) word) =
Fixed (word_of_int ( ((sbl_to_bin (nths (lof_wline tw' SQUARE_TEMP (i + 2 * clk_period - 1)) {1 .. 32})))))"
unfolding plus_fixed.abs_eq by auto
have "Fixed (word_of_int (bin_of NEXT_COMMON at_time i + 2 * clk_period on tw') :: (1 + 31) word) = fixed_of_sval (wline_of tw' NEXT_COMMON (i + 2 * clk_period))"
(is "?lhs5 = ?rhs5")
proof -
have "type_of (wline_of tw' NEXT_COMMON (i + 2 * clk_period)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
hence "length (lval_of (wline_of tw' NEXT_COMMON (i + 2 * clk_period))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
hence "?lhs5 = Fixed (word_of_int (sbintrunc (LENGTH((1+31)) - 1) (bl_to_bin (lval_of (wline_of tw' NEXT_COMMON (i + 2 * clk_period))))))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (bl_to_bin (lval_of (wline_of tw' NEXT_COMMON (i + 2 * clk_period)))))"
unfolding word_sbin.Abs_norm by auto
also have "... = fixed_of_sval (wline_of tw' NEXT_COMMON (i + 2 * clk_period))"
proof -
have "wline_of tw' NEXT_COMMON (i + 2 * clk_period) = Lv Sig (lval_of (wline_of tw' NEXT_COMMON (i + 2 * clk_period)))"
using `type_of (wline_of tw' NEXT_COMMON (i + 2 * clk_period)) = Lty Sig 32`
by (metis (no_types, hide_lams) ty.distinct(1) ty.inject type_of.cases type_of.simps(1) type_of.simps(2) val.sel(3))
thus ?thesis
using fixed_of_sval.simps unfolding of_bl_def by smt
qed
finally show ?thesis
by auto
qed
have "(word_of_int (sbl_to_bin (nths (lof_wline tw' SQUARE_TEMP (i + 2 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word) =
word_of_int (sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 2 * clk_period - 2)))) :: (1 + 31) word ) *
sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 2 * clk_period - 2)))) :: (1 + 31) word) div 2 ^ 31)"
proof -
have "(word_of_int (sbl_to_bin (nths (lof_wline tw' SQUARE_TEMP (i + 2 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word)=
word_of_int
(sbintrunc (length (nths (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1))) {1..32}) - 1) (bl_to_bin (nths (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1))) {1..32})))"
unfolding sbl_to_bin_alt_def by auto
moreover have "(length (nths (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1))) {1..32}) - 1) = 31"
proof -
have "type_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
have "card {1::nat ..32} = 32"
unfolding card_atLeastAtMost by auto
show ?thesis
unfolding length_nths *
using card_slice[where len="64" and l=62 and r="31"] by auto
qed
ultimately have "(word_of_int (sbl_to_bin (nths (lof_wline tw' SQUARE_TEMP (i + 2 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word) =
word_of_int (sbintrunc 31 (bl_to_bin (nths (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1))) {1..32})))"
by auto
also have "... = word_of_int (sbintrunc (LENGTH(1+31) - 1) (bl_to_bin (nths (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1))) {1..32})))"
by auto
also have "... = (word_of_int (bl_to_bin (nths (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1))) {1..32})) :: (1 + 31) word) "
unfolding word_sbin.Abs_norm by auto
finally have "word_of_int (sbl_to_bin (nths (lof_wline tw' SQUARE_TEMP (i + 2 * clk_period - 1)) {1 .. 32})) =
(word_of_int ( bl_to_bin (nths (lof_wline tw' SQUARE_TEMP (i + 2 * clk_period - 1)) {1 .. 32})) :: (1+31) word)"
by auto
have interval: "{1 :: nat .. 32} = {1 :: nat ..< 33}"
by auto
have nths: "\<And>xs:: bool list. nths xs {1 :: nat .. 32} = drop 1 (take 33 xs)"
unfolding interval nths_from_upt_eq_drop_take[where m="1" and n="33"] by auto
have " bl_to_bin (nths (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1))) {1 ..32}) =
bl_to_bin (drop 1 (take 33 (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1)))))"
using nths[of "(lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1)))"] by auto
also have "... = bintrunc (length (take 33 (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1)))) - 1) (bl_to_bin (take 33 (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1)))))"
unfolding bl2bin_drop by auto
also have "... = bintrunc 32 (bl_to_bin (take 33 (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1)))))"
proof-
have "type_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
hence " length (take 33 (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1)))) = 33"
unfolding length_take by auto
thus ?thesis
by auto
qed
also have "... = bintrunc 32 (bl_to_bin (take (length (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1))) - 31) (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1)))))"
proof-
have "type_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
thus ?thesis
by auto
qed
also have "... = bintrunc 32 ((bin_rest ^^ 31) (bl_to_bin (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1)))))"
unfolding take_rest_bl2bin by auto
finally have "bl_to_bin (nths (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1))) {1 ..32}) =
bintrunc 32 ((bin_rest ^^ 31) (bl_to_bin (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1)))))"
by auto
have "(word_of_int (bl_to_bin (nths (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1))) {1 ..32})) :: (1+31) word)=
word_of_int (bintrunc 32 ((bin_rest ^^ 31) (bl_to_bin (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1))))))"
using \<open>bl_to_bin (nths (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1))) {1..32}) = bintrunc 32 ((bin_rest ^^ 31) (bl_to_bin (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1)))))\<close>
by auto
\<comment> \<open>push bintrunc 32 inside\<close>
also have "... = word_of_int ((bin_rest ^^ 31) (bintrunc 63 (bl_to_bin (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1))))))"
using bin_rest_power_trunc[where n="63" and k="31", symmetric] by auto
also have "... = word_of_int ((bin_rest ^^ 31) (bl_to_bin (drop 1 (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1))))))"
proof -
have "type_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
thus ?thesis
using bl2bin_drop by auto
qed
\<comment> \<open>pull bl_to_bin to left\<close>
also have "... = word_of_int (bl_to_bin ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1))))))"
unfolding butlast_pow_rest_bl2bin[symmetric] by auto
\<comment> \<open>change to sbl_to_bin\<close>
also have "... = (word_of_int (sbintrunc (LENGTH(1+31) - 1) (bl_to_bin ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1))))))) :: (1 + 31) word)"
unfolding word_sbin.Abs_norm by auto
also have "... = word_of_int (sbl_to_bin ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1))))))"
proof -
have "type_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
have "length ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1))))) = 32"
unfolding butlast_power length_take length_drop * by eval
hence "(word_of_int (sbintrunc (LENGTH(1+31) - 1) (bl_to_bin ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1))))))) :: (1 + 31) word) =
(word_of_int (sbintrunc (length ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1))))) - 1) (bl_to_bin ((butlast ^^ 31) (drop 1 (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1))))))) :: (1 + 31) word)"
by auto
thus ?thesis
using sbl_to_bin_alt_def by auto
qed
\<comment> \<open>push sbl_to_bin back to right\<close>
also have "... = word_of_int ((bin_rest ^^ 31) (sbl_to_bin (drop 1 (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1))))))"
proof -
have "type_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
have "length ((drop 1 (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1))))) = 63"
unfolding length_take length_drop * by eval
hence **: "31 < length ((drop 1 (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1)))))"
by auto
show ?thesis
unfolding butlast_pow_rest_sbl2bin[OF **] by auto
qed
also have "... = word_of_int ((bin_rest ^^ 31) (sbintrunc 62 (sbl_to_bin (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1))))))"
proof -
have "type_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1)) = Lty Sig 64"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' SQUARE_TEMP (i + 2 * clk_period - 1))) = 64"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
thus ?thesis
using sbl2bin_drop by auto
qed
also have "... = word_of_int ((bin_rest ^^ 31) (sbintrunc 62 (bin_of COMMON at_time (i + 2 * clk_period - 2) on tw' * bin_of COMMON at_time (i + 2 * clk_period - 2) on tw')))"
using `bin_of SQUARE_TEMP at_time (i + 2 *clk_period - 1) on tw' = sbintrunc 63 (bin_of COMMON at_time (i + 2 *clk_period - 2) on tw' * bin_of COMMON at_time (i + 2 *clk_period - 2) on tw')`
by auto
also have "... = word_of_int (sbintrunc 31 ((bin_rest ^^ 31) (bin_of COMMON at_time (i + 2 * clk_period - 2) on tw' * bin_of COMMON at_time (i + 2 * clk_period - 2) on tw')))"
proof -
have "(31 :: nat) \<le> 62" by auto
show ?thesis
unfolding bin_rest_power_strunc[OF `31 \<le> 62`]
by auto
qed
also have "... = word_of_int (sbintrunc (LENGTH(1 + 31) - 1) ((bin_rest ^^ 31) (bin_of COMMON at_time (i + 2 * clk_period - 2) on tw' * bin_of COMMON at_time (i + 2 * clk_period - 2) on tw')))"
by auto
also have "... = word_of_int ((bin_rest ^^ 31) (bin_of COMMON at_time (i + 2 * clk_period - 2) on tw' * bin_of COMMON at_time (i + 2 * clk_period - 2) on tw'))"
unfolding word_sbin.Abs_norm by auto
also have "... = word_of_int ((bin_of COMMON at_time (i + 2 * clk_period - 2) on tw' * bin_of COMMON at_time (i + 2 * clk_period - 2) on tw') div 2 ^ 31)"
unfolding bin_rest_compow by auto
also have "... = word_of_int (sbintrunc (length (lval_of (wline_of tw' COMMON (i + 2 * clk_period - 2))) - 1) (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 2 * clk_period - 2)))) *
sbintrunc (length (lval_of (wline_of tw' COMMON (i + 2 * clk_period - 2))) - 1) (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 2 * clk_period - 2)))) div 2 ^ 31)"
using sbl_to_bin_alt_def2 by auto
also have "... = word_of_int (sbintrunc (LENGTH(1 + 31) - 1) (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 2 * clk_period - 2)))) *
sbintrunc (LENGTH(1 + 31) - 1) (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 2 * clk_period - 2)))) div 2 ^ 31)"
proof -
have "type_of (wline_of tw' COMMON (i + 2 * clk_period - 2)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence *: "length (lval_of (wline_of tw' COMMON (i + 2 * clk_period - 2))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
have "type_of (wline_of tw' COMMON (i + 2 * clk_period - 2)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def by auto
hence **: "length (lval_of (wline_of tw' COMMON (i + 2 * clk_period - 2))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
with * show ?thesis
by auto
qed
also have "... = word_of_int (sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 2 * clk_period - 2)))) :: (1 + 31) word) *
sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 2 * clk_period - 2)))) :: (1 + 31) word ) div 2 ^ 31)"
unfolding sint_sbintrunc' by auto
finally show ?thesis
unfolding `(word_of_int (sbl_to_bin (nths (lof_wline tw' SQUARE_TEMP (i + 2 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word) =
(word_of_int ( bl_to_bin (nths (lof_wline tw' SQUARE_TEMP (i + 2 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word)`
by auto
qed
hence "Fixed (word_of_int (sbl_to_bin (nths (lof_wline tw' SQUARE_TEMP (i + 2 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word) =
Fixed (word_of_int (sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 2 * clk_period - 2)))) :: (1 + 31) word ) *
sint (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 2 * clk_period - 2)))) :: (1 + 31) word) div 2 ^ 31))"
by auto
also have "... = Fixed (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 2 * clk_period - 2))))) * Fixed (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 2 * clk_period - 2)))))"
using times_fixed.abs_eq[where xa="word_of_int (bin_of COMMON at_time i + 2 * clk_period - 2 on tw') :: (1 + 31) word" and
x="word_of_int (bin_of COMMON at_time i + 2 * clk_period - 2 on tw') :: (1 + 31) word", symmetric]
by auto
also have "... = fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2)) * fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2))"
proof -
have "type_of (wline_of tw' COMMON (i + 2 * clk_period - 2)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
hence "length (lval_of (wline_of tw' COMMON (i + 2 * clk_period - 2))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
hence "Fixed (word_of_int (bin_of COMMON at_time i + 2 * clk_period - 2 on tw')) =
Fixed (word_of_int (sbintrunc (LENGTH((1+31)) - 1) (bl_to_bin (lval_of (wline_of tw' COMMON (i + 2 * clk_period - 2))))))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (bl_to_bin (lval_of (wline_of tw' COMMON (i + 2 * clk_period - 2)))) :: (1 + 31) word)"
unfolding word_sbin.Abs_norm by auto
also have "... = fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2))"
proof -
have "wline_of tw' COMMON (i + 2 * clk_period - 2) = Lv Sig (lval_of (wline_of tw' COMMON (i + 2 * clk_period - 2)))"
using `type_of (wline_of tw' COMMON (i + 2 *clk_period - 2)) = Lty Sig 32`
by (metis (no_types, hide_lams) ty.distinct(1) ty.inject type_of.cases type_of.simps(1) type_of.simps(2) val.sel(3))
thus ?thesis
using fixed_of_sval.simps unfolding of_bl_def by smt
qed
finally have "Fixed (word_of_int (bin_of COMMON at_time i + 2 * clk_period - 2 on tw') :: (1 + 31) word) = fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2))"
by auto
have "type_of (wline_of tw' COMMON (i + 2 * clk_period - 2)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
hence "length (lval_of (wline_of tw' COMMON (i + 2 * clk_period - 2))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
hence "Fixed (word_of_int (bin_of COMMON at_time i + 2 * clk_period - 2 on tw')) =
Fixed (word_of_int (sbintrunc (LENGTH((1+31)) - 1) (bl_to_bin (lval_of (wline_of tw' COMMON (i + 2 * clk_period - 2))))))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (bl_to_bin (lval_of (wline_of tw' COMMON (i + 2 * clk_period - 2)))) :: (1 + 31) word)"
unfolding word_sbin.Abs_norm by auto
also have "... = fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2))"
proof -
have "wline_of tw' COMMON (i + 2 * clk_period - 2) = Lv Sig (lval_of (wline_of tw' COMMON (i + 2 * clk_period - 2)))"
using `type_of (wline_of tw' COMMON (i + 2 *clk_period - 2)) = Lty Sig 32`
by (metis (no_types, hide_lams) ty.distinct(1) ty.inject type_of.cases type_of.simps(1) type_of.simps(2) val.sel(3))
thus ?thesis
using fixed_of_sval.simps unfolding of_bl_def by smt
qed
finally have "Fixed (word_of_int (bin_of COMMON at_time i + 2 * clk_period - 2 on tw') :: (1 + 31) word) = fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2))"
by auto
thus ?thesis
using \<open>Fixed (word_of_int (sbl_to_bin (lval_of (wline_of tw' COMMON (i + 2 * clk_period - 2))))) = fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2))\<close> by auto
qed
finally have "Fixed (word_of_int (sbl_to_bin (nths (lof_wline tw' SQUARE_TEMP (i + 2 * clk_period - 1)) {1 .. 32})) :: (1 + 31) word) =
fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2)) * fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2))"
by auto
thus ?thesis
using `?lhs5 = ?rhs5`
`Fixed (word_of_int (bin_of NEXT_COMMON at_time i + 2 * clk_period on tw') :: (1 + 31) word) = Fixed (word_of_int ( ((sbl_to_bin (nths (lof_wline tw' SQUARE_TEMP (i + 2 * clk_period - 1)) {1 .. 32})))))`
`wline_of tw' NEXT_COMMON (i + 2 * clk_period) = wline_of tw' COMMON (i + 2 * clk_period + 1)`
`wline_of tw' COMMON (i + 2 * clk_period + 1) = wline_of tw' COMMON (i + 3 * clk_period - 2)`
by auto
qed
have "wline_of tw' COMMON (i + 2 * clk_period - 2) = wline_of tw' COMMON (i + 2 * clk_period - 1)"
proof -
have "Inv_core (i + 2 * clk_period - 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms
unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence **: "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using posedge by blast
hence "(i + 2 * clk_period) mod clk_period = 0"
by auto
have "(i + 2 * clk_period - 2) mod clk_period \<noteq> 0"
proof -
have "i + 1 * clk_period < i + 2 * clk_period - 2"
using assms by (auto)
moreover have "i + 2 * clk_period - 2 < i + 6 * clk_period"
using assms by auto
ultimately show ?thesis
by (metis \<open>(i + 2 * clk_period) mod clk_period = 0\<close> assms(3) assms(4) diff_add_0 diff_add_inverse
dvd_add_left_iff dvd_antisym less_imp_add_positive less_nat_zero_code mod_0_imp_dvd nat_diff_split_asm numeral_plus_numeral semiring_norm(5))
qed
hence "\<not> is_posedge2 (snd tw') CLK (i + 2 * clk_period - 2)"
using ** by auto
thus ?thesis
using `Inv_core (i + 2 * clk_period - 1, snd tw')` unfolding inv_reg_alt_def comp_def snd_conv fst_conv
using diff_diff_left nat_1_add_1 by presburger
qed
have "bin_of NEXT_ACCUM at_time (i + 2 * clk_period) on tw' = 0"
proof -
have "Inv_core (i + 2 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
thus ?thesis
using `wline_of tw' STATE (i + 2 * clk_period - 1) = V_PRE`
unfolding inv_naccum_alt_def comp_def snd_conv fst_conv by auto
qed
hence "word_of_int (bin_of NEXT_ACCUM at_time (i + 2 * clk_period) on tw') = (0 :: (1 + 31) word)"
by auto
hence "Fixed (word_of_int (bin_of NEXT_ACCUM at_time (i + 2 * clk_period) on tw') :: (1 + 31) word) = (0 :: (1, 31) fixed)"
apply transfer' unfolding word_ubin.norm_eq_iff by auto
have "Fixed (word_of_int (bin_of NEXT_ACCUM at_time i + 2 * clk_period on tw') :: (1 + 31) word) = fixed_of_sval (wline_of tw' NEXT_ACCUM (i + 2 * clk_period))"
(is "?lhs6 = ?rhs6")
proof -
have "type_of (wline_of tw' NEXT_ACCUM (i + 2 * clk_period)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
hence "length (lval_of (wline_of tw' NEXT_ACCUM (i + 2 * clk_period))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
hence "?lhs6 = Fixed (word_of_int (sbintrunc (LENGTH((1+31)) - 1) (bl_to_bin (lval_of (wline_of tw' NEXT_ACCUM (i + 2 * clk_period))))))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (bl_to_bin (lval_of (wline_of tw' NEXT_ACCUM (i + 2 * clk_period)))))"
unfolding word_sbin.Abs_norm by auto
also have "... = fixed_of_sval (wline_of tw' NEXT_ACCUM (i + 2 * clk_period))"
proof -
have "wline_of tw' NEXT_ACCUM (i + 2 * clk_period) = Lv Sig (lval_of (wline_of tw' NEXT_ACCUM (i + 2 * clk_period)))"
using `type_of (wline_of tw' NEXT_ACCUM (i + 2 * clk_period)) = Lty Sig 32`
by (metis (no_types, hide_lams) ty.distinct(1) ty.inject type_of.cases type_of.simps(1) type_of.simps(2) val.sel(3))
thus ?thesis
using fixed_of_sval.simps unfolding of_bl_def by smt
qed
finally show ?thesis
by auto
qed
hence "fixed_of_sval (wline_of tw' NEXT_ACCUM (i + 2 * clk_period)) = (0 :: (1, 31) fixed)"
using `Fixed (word_of_int (bin_of NEXT_ACCUM at_time (i + 2 * clk_period) on tw') :: (1 + 31) word) = (0 :: (1, 31) fixed)` by auto
hence "fixed_of_sval (wline_of tw' ACCUM (i + 3 * clk_period - 2)) = (0 :: (1, 31) fixed)"
using \<open>wline_of tw' ACCUM (i + 2 * clk_period + 1) = wline_of tw' ACCUM (i + 3 * clk_period -
2)\<close> \<open>wline_of tw' NEXT_ACCUM (i + 2 * clk_period) = wline_of tw' ACCUM (i + 2 * clk_period + 1)\<close>
by auto
hence "fixed_of_sval (wline_of tw' ACCUM (fst tw')) = approx_div_fact 0 +
fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2)) * fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2)) * (approx_div_fact 1 +
fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2)) * fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2)) * (approx_div_fact 2 +
fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2)) * fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2)) * (approx_div_fact 3 +
fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2)) * fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2)) * (approx_div_fact 4 +
fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2)) * fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2)) * 0))))"
using `fixed_of_sval (wline_of tw' ACCUM (fst tw')) = approx_div_fact 0 +
fixed_of_sval (wline_of tw' COMMON (i + 3 * clk_period - 2)) * (approx_div_fact 1 +
fixed_of_sval (wline_of tw' COMMON (i + 3 * clk_period - 2)) * (approx_div_fact 2 +
fixed_of_sval (wline_of tw' COMMON (i + 3 * clk_period - 2)) * (approx_div_fact 3 +
fixed_of_sval (wline_of tw' COMMON (i + 3 * clk_period - 2)) * (approx_div_fact 4 +
fixed_of_sval (wline_of tw' COMMON (i + 3 * clk_period - 2)) * fixed_of_sval (wline_of tw' ACCUM (i + 3 * clk_period - 2))))))`
using \<open>fixed_of_sval (wline_of tw' COMMON (i + 3 * clk_period - 2)) = fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2)) * fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2))\<close>
by auto
hence "fixed_of_sval (wline_of tw' ACCUM (fst tw')) = approx_div_fact 0 +
fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2)) * fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2)) * (approx_div_fact 1 +
fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2)) * fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2)) * (approx_div_fact 2 +
fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2)) * fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2)) * (approx_div_fact 3 +
fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2)) * fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2)) * (approx_div_fact 4 + 0))))"
unfolding fixed_mult_zero by auto
have "wline_of tw' COMMON (i + 1 * clk_period + 1) = wline_of tw' COMMON (i + 2 * clk_period - 2)"
and "wline_of tw' ACCUM (i + 1 * clk_period + 1) = wline_of tw' ACCUM (i + 2 * clk_period - 2)"
proof -
have a: "fst tw \<le> i + 1 * clk_period + 1"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] by auto
have b: "i + 1 * clk_period + 1 \<le> i + 2 * clk_period - 2"
using assms by (auto simp add: field_simps)
have c: "i + 2 * clk_period - 2 \<le> i + 7 * clk_period + 1"
by auto
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms
unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using \<open>\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0\<close> assms by blast
hence "(i + 1 * clk_period) mod clk_period = 0"
by auto
hence "(i + 2 * clk_period) mod clk_period = 0"
by auto
have d: "\<And>k. i + 1 * clk_period + 1 \<le> k \<Longrightarrow> k \<le> i + 2 * clk_period - 1 \<Longrightarrow> \<not> is_posedge2 (snd tw') CLK k"
proof -
fix n
obtain m1 where "i + 1 * clk_period = m1 * clk_period"
using `(i + 1 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 2 * clk_period = (m1 + 1) * clk_period"
proof -
obtain m2 where "i + 2 * clk_period = m2 * clk_period"
using `(i + 2 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 2 * clk_period - (i + 1 * clk_period) = clk_period"
by (auto simp add: field_simps)
hence "m2 * clk_period - m1 * clk_period = clk_period"
using `i + 1 * clk_period = m1 * clk_period` `i + 2 * clk_period = m2 * clk_period`
by auto
hence "(m2 - m1) * clk_period = clk_period"
by (auto simp add: algebra_simps)
hence "m2 = Suc m1"
using `3 < clk_period ` by auto
thus ?thesis
using Suc_eq_plus1 \<open>i + 2 * clk_period = m2 * clk_period\<close> by presburger
qed
assume "i + 1 * clk_period + 1 \<le> n" and "n \<le> i + 2 * clk_period - 1"
hence "m1 * clk_period < n"
using `i + 1 * clk_period = m1 * clk_period` by linarith
have "n mod clk_period \<noteq> 0"
proof -
have "n div clk_period = m1"
apply (rule Misc_Arithmetic.sdl)
using \<open>m1 * clk_period < n\<close> apply (simp add: mult.commute)
using `n \<le> i + 2 * clk_period - 1` `i + 2 * clk_period = (m1 + 1) * clk_period` assms
by (auto simp add: field_simps)
hence "n = m1 * clk_period + n mod clk_period"
by auto
moreover have "n mod clk_period < clk_period"
using assms by (auto intro!: mod_less_divisor)
ultimately show ?thesis
using \<open>m1 * clk_period < n\<close> by linarith
qed
hence "\<not> is_posedge2 w CLK n"
using \<open>\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0\<close> by auto
thus "\<not> is_posedge2 (snd tw') CLK n"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
qed
show "wline_of tw' COMMON (i + 1 * clk_period + 1) = wline_of tw' COMMON (i + 2 * clk_period - 2)"
and "wline_of tw' ACCUM (i + 1 * clk_period + 1) = wline_of tw' ACCUM (i + 2 * clk_period - 2)"
using registers_unchanged_no_rising_edge[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)` a b c d]
by auto
qed
have "Inv_core (i + 1 * clk_period + 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
have "is_posedge2 (snd tw') CLK (i + 1 * clk_period)"
proof -
have "is_posedge2 w CLK (i + 2 * clk_period)"
using `is_posedge2 (snd tw') CLK (i + 2 * clk_period)`
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
hence "is_posedge2 w CLK (i + 2 * clk_period - clk_period)"
using assms by auto
hence "is_posedge2 w CLK (i + 1 * clk_period)"
by (auto simp add:field_simps)
thus "is_posedge2 (snd tw') CLK (i + 1 * clk_period)"
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
qed
have "wline_of tw' RST (i + 1 * clk_period) = Bv False"
proof (rule ccontr)
assume "wline_of tw' RST (i + 1 * clk_period) \<noteq> Bv False"
have "wityping \<Gamma> (snd tw')"
using `wityping \<Gamma> (snd tw)` world_sim_fin_preserves_wityping[OF 0]
using conc_stmt_wf_arch cwt_arch nonneg_delay_conc_architecture by blast
hence "type_of (wline_of tw' RST (i + 1 * clk_period)) = Bty"
unfolding wityping_def wtyping_def using cosine_locale_axioms unfolding cosine_locale_def by auto
hence "wline_of tw' RST (i + 1 * clk_period) = Bv True"
using `wline_of tw' RST (i + 1 * clk_period) \<noteq> Bv False` type_of_bty_cases by blast
hence "wline_of tw' STATE (i + 1 * clk_period + 1) = V_INIT"
using `Inv_core ((i + 1 * clk_period + 1, snd tw'))` `is_posedge2 (snd tw') CLK (i + 1 * clk_period)` unfolding inv_reg_alt_def
comp_def snd_conv fst_conv by auto
with `wline_of tw' STATE (i + 1 * clk_period + 1) = V_PRE` show False
by auto
qed
have "wline_of tw' NEXT_COMMON (i + 1 * clk_period) = wline_of tw' COMMON (i + 1 * clk_period + 1)"
and "wline_of tw' NEXT_ACCUM (i + 1 * clk_period) = wline_of tw' ACCUM (i + 1 * clk_period + 1)"
using `Inv_core (i + 1 * clk_period + 1, snd tw')` `is_posedge2 (snd tw') CLK (i + 1 * clk_period)` `wline_of tw' RST (i + 1 * clk_period) = Bv False`
unfolding inv_reg_alt_def comp_def snd_conv fst_conv by auto
\<comment> \<open> obtaining state\<close>
have "wline_of tw' STATE (i + 1 * clk_period + 1) = wline_of tw' STATE (i + 2 * clk_period - 1)"
proof -
have a: "fst tw \<le> i + 1 * clk_period + 1"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] by auto
have b: "i + 1 * clk_period + 1 \<le> i + 2 * clk_period - 1"
using assms by (auto simp add: field_simps)
have c: "i + 2 * clk_period - 1 \<le> i + 7 * clk_period + 1"
by auto
have *: "\<And>k. type_of (wline_of (0, w) CLK k) = Bty"
using `wityping \<Gamma> w` cosine_locale_axioms
unfolding wityping_def wtyping_def comp_def snd_conv cosine_locale_def by auto
have "\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0"
using * posedge_only_if_mod_clk_period[OF assms(3) _ assms(5-7)] assms(4) by auto
hence "\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
hence "(i + 7 * clk_period) mod clk_period = 0"
using \<open>\<And>m. is_posedge2 (snd tw') CLK m \<Longrightarrow> m mod clk_period = 0\<close> assms by blast
hence "(i + 2 * clk_period) mod clk_period = 0"
by auto
hence "(i + 1 * clk_period) mod clk_period = 0"
by auto
have d: "\<And>k. i + 1 * clk_period + 1 \<le> k \<Longrightarrow> k \<le> i + 2 * clk_period - 1 \<Longrightarrow> \<not> is_posedge2 (snd tw') CLK k"
proof -
fix n
obtain m1 where "i + 1 * clk_period = m1 * clk_period"
using `(i + 1 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 2 * clk_period = (m1 + 1) * clk_period"
proof -
obtain m2 where "i + 2 * clk_period = m2 * clk_period"
using `(i + 2 * clk_period) mod clk_period = 0` by (metis Nat.add_0_right div_mult_mod_eq)
have "i + 2 * clk_period - (i + 1 * clk_period) = clk_period"
by (auto simp add: field_simps)
hence "m2 * clk_period - m1 * clk_period = clk_period"
using `i + 1 * clk_period = m1 * clk_period` `i + 2 * clk_period = m2 * clk_period`
by auto
hence "(m2 - m1) * clk_period = clk_period"
by (auto simp add: algebra_simps)
hence "m2 = Suc m1"
using `3 < clk_period ` by auto
thus ?thesis
using Suc_eq_plus1 \<open>i + 2 * clk_period = m2 * clk_period\<close> by presburger
qed
assume "i + 1 * clk_period + 1 \<le> n" and "n \<le> i + 2 * clk_period - 1"
hence "m1 * clk_period < n"
using `i + 1 * clk_period = m1 * clk_period` by linarith
have "n mod clk_period \<noteq> 0"
proof -
have "n div clk_period = m1"
apply (rule Misc_Arithmetic.sdl)
using \<open>m1 * clk_period < n\<close> apply (simp add: mult.commute)
using `n \<le> i + 2 * clk_period - 1` `i + 2 * clk_period = (m1 + 1) * clk_period` assms
by (auto simp add: field_simps)
hence "n = m1 * clk_period + n mod clk_period"
by auto
moreover have "n mod clk_period < clk_period"
using assms by (auto intro!: mod_less_divisor)
ultimately show ?thesis
using \<open>m1 * clk_period < n\<close> by linarith
qed
hence "\<not> is_posedge2 w CLK n"
using \<open>\<And>m. is_posedge2 w CLK m \<Longrightarrow> m mod clk_period = 0\<close> by auto
thus "\<not> is_posedge2 (snd tw') CLK n"
using \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close> by auto
qed
show "wline_of tw' STATE (i + 1 * clk_period + 1) = wline_of tw' STATE (i + 2 * clk_period - 1)"
using registers_unchanged_no_rising_edge[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)` a b c d]
by auto
qed
hence "wline_of tw' STATE (i + 1 * clk_period + 1) = V_PRE"
using `wline_of tw' STATE (i + 2 * clk_period - 1) = V_PRE`
by auto
have "wline_of tw' NEXT_STATE (i + 1 * clk_period) = wline_of tw' STATE (i + 1 * clk_period + 1)"
proof -
have "Inv_core (i + 1 * clk_period + 1, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`] by auto
moreover have "is_posedge2 (snd tw') CLK (i + 1 * clk_period)"
proof -
have "is_posedge2 w CLK (i + 2 * clk_period)"
using `is_posedge2 (snd tw') CLK (i + 2 * clk_period)`
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
hence "is_posedge2 w CLK (i + 2 * clk_period - clk_period)"
using assms by auto
hence "is_posedge2 w CLK (i + 1 * clk_period)"
by (auto simp add:field_simps)
thus "is_posedge2 (snd tw') CLK (i + 1 * clk_period)"
unfolding \<open>\<And>k. wline_of (0, w) CLK k = wline_of tw' CLK k\<close>[unfolded comp_def snd_conv]
by auto
qed
moreover have "wline_of tw' RST (i + 1 * clk_period) = Bv False"
proof (rule ccontr)
assume "wline_of tw' RST (i + 1 * clk_period) \<noteq> Bv False"
have "wityping \<Gamma> (snd tw')"
using `wityping \<Gamma> (snd tw)` world_sim_fin_preserves_wityping[OF 0] conc_stmt_wf_arch cwt_arch nonneg_delay_conc_architecture by blast
hence "type_of (wline_of tw' RST (i + 1 * clk_period)) = Bty"
unfolding wityping_def wtyping_def using cosine_locale_axioms unfolding cosine_locale_def by auto
hence "wline_of tw' RST (i + 1 * clk_period) = Bv True"
using `wline_of tw' RST (i + 1 * clk_period) \<noteq> Bv False` type_of_bty_cases by blast
hence "wline_of tw' STATE (i + 1 * clk_period + 1) = V_INIT"
using `Inv_core (i + 1 * clk_period + 1, snd tw')` `is_posedge2 (snd tw') CLK (i + 1 * clk_period)` unfolding inv_reg_alt_def
comp_def snd_conv fst_conv by auto
with `wline_of tw' STATE (i + 1 * clk_period + 1) = V_PRE` show False
using \<open>wline_of tw' OUTREADY_REG (get_time tw') = Bv True\<close> by auto
qed
ultimately show ?thesis
unfolding inv_reg_alt_def comp_def snd_conv fst_conv by auto
qed
hence "wline_of tw' NEXT_STATE (i + 1 * clk_period) = V_PRE"
using `wline_of tw' STATE (i + 1 * clk_period + 1) = V_PRE`
using \<open>bl_to_bin (lval_of (wline_of tw' COUNTER (i + 3 *clk_period - 1))) = 3\<close> \<open>wline_of tw' COUNTER (i + 2 * clk_period + 1) = wline_of tw' COUNTER (i + 3 *clk_period - 1)\<close> \<open>wline_of tw' NEXT_COUNTER (i + 2 * clk_period) = wline_of tw' COUNTER (i + 2 * clk_period + 1)\<close>
by auto
have "wline_of tw' STATE (i + 1 * clk_period - 1) = V_WAIT \<and> bval_of (wline_of tw' INREADY (i + 1 * clk_period - 1))"
proof (rule ccontr)
have "Inv_core (i + 1 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
hence inv:"inv_nstate (i + 1 * clk_period, snd tw')"
by auto
assume "\<not> (wline_of tw' STATE (i + 1 * clk_period - 1) = V_WAIT \<and> bval_of (wline_of tw' INREADY (i + 1 * clk_period - 1)))"
hence *: "(wline_of tw' STATE (i + 1 * clk_period - 1) = V_WAIT \<Longrightarrow> \<not> bval_of (wline_of tw' INREADY (i + 1 * clk_period - 1)))"
by auto
let ?state = "wline_of tw' STATE (i + 1 * clk_period - 1)"
consider "?state = V_INIT" | "?state = V_WAIT" | "?state = V_PROC" | "?state = V_POST"
| "?state \<noteq> V_INIT \<and> ?state \<noteq> V_WAIT \<and> ?state \<noteq> V_PRE \<and> ?state \<noteq> V_PROC \<and> ?state \<noteq> V_POST"
| "?state = V_PRE"
by auto
thus False
proof (cases)
case 1
hence "wline_of tw' NEXT_STATE (i + 1 * clk_period) \<noteq> V_PRE"
using inv unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 1 * clk_period) = V_PRE`
by auto
next
case 2
hence "wline_of tw' NEXT_STATE (i + 1 * clk_period) \<noteq> V_PRE"
using inv * unfolding inv_nstate_alt_def comp_def snd_conv fst_conv
by (cases "bval_of (snd (snd tw') INREADY (i + 1 * clk_period - 1))") auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 1 * clk_period) = V_PRE`
by auto
next
case 3
hence "wline_of tw' NEXT_STATE (i + 1 * clk_period) \<noteq> V_PRE"
using inv * unfolding inv_nstate_alt_def comp_def snd_conv fst_conv
by (cases "bval_of (snd (snd tw') CTR_NEQ_0 (i + clk_period - Suc 0))") auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 1 * clk_period) = V_PRE`
by auto
next
case 4
hence "wline_of tw' NEXT_STATE (i + 1 * clk_period) \<noteq> V_PRE"
using inv * unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 1 * clk_period) = V_PRE`
by auto
next
case 5
hence "wline_of tw' NEXT_STATE (i + 1 * clk_period) \<noteq> V_PRE"
using inv * unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 1 * clk_period) = V_PRE`
by auto
next
case 6
hence "wline_of tw' NEXT_STATE (i + 1 * clk_period) \<noteq> V_PRE"
using inv * unfolding inv_nstate_alt_def comp_def snd_conv fst_conv by auto
then show ?thesis
using `wline_of tw' NEXT_STATE (i + 1 * clk_period) = V_PRE`
by auto
qed
qed
have "bin_of NEXT_COMMON at_time (i + clk_period) on tw' = bin_of INPUT at_time (i + clk_period - 1) on tw'"
proof -
have "Inv_core (i + 1 * clk_period, snd tw')"
using fst_init_sim2[OF `init_sim2 (0, w) architecture tw`] assms Inv_core_everywhere_strict[OF 0 `Inv tw` `wityping \<Gamma> (snd tw)`]
by auto
thus ?thesis
using `wline_of tw' STATE (i + 1 * clk_period - 1) = V_WAIT \<and> bval_of (wline_of tw' INREADY (i + 1 * clk_period - 1))`
unfolding inv_ncommon_alt_def comp_def snd_conv fst_conv by auto
qed
hence "bin_of COMMON at_time (i + 2 * clk_period - 2) on tw' = bin_of INPUT at_time (i + clk_period - 1) on tw'"
using \<open>wline_of tw' COMMON (i + 1 * clk_period + 1) = wline_of tw' COMMON (i + 2 * clk_period -
2)\<close> \<open>wline_of tw' NEXT_COMMON (i + 1 * clk_period) = wline_of tw' COMMON (i + 1 * clk_period +
1)\<close> by auto
moreover have "Fixed (word_of_int (bin_of COMMON at_time i + 2 * clk_period - 2 on tw') :: (1 + 31) word) = fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2))"
proof -
have "type_of (wline_of tw' COMMON (i + 2 * clk_period - 2)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
hence "length (lval_of (wline_of tw' COMMON (i + 2 * clk_period - 2))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
hence "Fixed (word_of_int (bin_of COMMON at_time i + 2 * clk_period - 2 on tw') :: (1 + 31) word) =
Fixed (word_of_int (sbintrunc (LENGTH((1+31)) - 1) (bl_to_bin (lval_of (wline_of tw' COMMON (i + 2 * clk_period - 2))))))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (bl_to_bin (lval_of (wline_of tw' COMMON (i + 2 * clk_period - 2)))))"
unfolding word_sbin.Abs_norm by auto
also have "... = fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2))"
proof -
have "wline_of tw' COMMON (i + 2 * clk_period - 2) = Lv Sig (lval_of (wline_of tw' COMMON (i + 2 * clk_period - 2)))"
using `type_of (wline_of tw' COMMON (i + 2 * clk_period - 2)) = Lty Sig 32`
by (metis (no_types, hide_lams) ty.distinct(1) ty.inject type_of.cases type_of.simps(1) type_of.simps(2) val.sel(3))
thus ?thesis
using fixed_of_sval.simps unfolding of_bl_def by smt
qed
finally show ?thesis
by auto
qed
moreover have "Fixed (word_of_int (bin_of INPUT at_time i + clk_period - 1 on tw') :: (1 + 31) word) = fixed_of_sval (wline_of tw' INPUT (i + clk_period - 1))"
proof -
have "type_of (wline_of tw' INPUT (i + clk_period - 1)) = Lty Sig 32"
using `wityping \<Gamma> (snd tw')` unfolding wityping_def wtyping_def
using cosine_locale_axioms unfolding cosine_locale_def comp_def by auto
hence "length (lval_of (wline_of tw' INPUT (i + clk_period - 1))) = 32"
by (metis (no_types, lifting) ty.distinct(1) ty.inject type_of.elims val.sel(3))
hence "Fixed (word_of_int (bin_of INPUT at_time i + clk_period - 1 on tw') :: (1 + 31) word) =
Fixed (word_of_int (sbintrunc (LENGTH((1+31)) - 1) (bl_to_bin (lval_of (wline_of tw' INPUT (i + clk_period - 1))))))"
unfolding sbl_to_bin_alt_def by auto
also have "... = Fixed (word_of_int (bl_to_bin (lval_of (wline_of tw' INPUT (i + clk_period - 1)))))"
unfolding word_sbin.Abs_norm by auto
also have "... = fixed_of_sval (wline_of tw' INPUT (i + clk_period - 1))"
proof -
have "wline_of tw' INPUT (i + clk_period - 1) = Lv Sig (lval_of (wline_of tw' INPUT (i + clk_period - 1)))"
using `type_of (wline_of tw' INPUT (i + clk_period - 1)) = Lty Sig 32`
by (metis (no_types, hide_lams) ty.distinct(1) ty.inject type_of.cases type_of.simps(1) type_of.simps(2) val.sel(3))
thus ?thesis
using fixed_of_sval.simps unfolding of_bl_def by smt
qed
finally show ?thesis
by auto
qed
ultimately have "(fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2)) :: (1, 31) fixed) = fixed_of_sval (wline_of tw' INPUT (i + clk_period - 1))"
by auto
hence final: "fixed_of_sval (wline_of tw' ACCUM (fst tw')) = approx_div_fact 0 +
(fixed_of_sval (wline_of tw' INPUT (i + clk_period - 1)) * fixed_of_sval (wline_of tw' INPUT (i + clk_period - 1))) * (approx_div_fact 1 +
(fixed_of_sval (wline_of tw' INPUT (i + clk_period - 1)) * fixed_of_sval (wline_of tw' INPUT (i + clk_period - 1))) * (approx_div_fact 2 +
(fixed_of_sval (wline_of tw' INPUT (i + clk_period - 1)) * fixed_of_sval (wline_of tw' INPUT (i + clk_period - 1))) * (approx_div_fact 3 +
(fixed_of_sval (wline_of tw' INPUT (i + clk_period - 1)) * fixed_of_sval (wline_of tw' INPUT (i + clk_period - 1))) * (approx_div_fact 4 + 0))))"
using `fixed_of_sval (wline_of tw' ACCUM (fst tw')) = approx_div_fact 0 +
fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2)) * fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2)) * (approx_div_fact 1 +
fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2)) * fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2)) * (approx_div_fact 2 +
fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2)) * fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2)) * (approx_div_fact 3 +
fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2)) * fixed_of_sval (wline_of tw' COMMON (i + 2 * clk_period - 2)) * (approx_div_fact 4 + 0))))`
by auto
have "[0::nat ..<5] = [0, 1, 2, 3, 4]"
by eval
show ?thesis
unfolding `[0::nat ..<5] = [0, 1, 2, 3, 4]`
using approx_div_fact.simps[symmetric] final
by (auto simp add: fixed_mult_zero)
qed
end |
State Before: α : Type u
β : Type v
γ : Type ?u.11692
δ : Type ?u.11695
ε : Type ?u.11698
ζ : Type ?u.11701
inst✝ : TopologicalSpace α
s t : Set α
x : ↑s
⊢ 𝓝[Subtype.val ⁻¹' t] x = ⊥ ↔ 𝓝[t] ↑x ⊓ 𝓟 s = ⊥ State After: no goals Tactic: rw [inf_principal_eq_bot_iff_comap, nhdsWithin, nhdsWithin, comap_inf, comap_principal,
nhds_induced] |
{-# language FlexibleContexts, GeneralizedNewtypeDeriving, DeriveFunctor #-}
{-# language OverloadedStrings #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Iterative
-- Copyright : (c) Marco Zocca 2017-2018
-- License : GPL-style (see the file LICENSE)
--
-- Maintainer : zocca marco gmail
-- Stability : experimental
-- Portability : portable
--
-- Combinators and helper functions for iterative algorithms, with support for monitoring and exceptions.
--
-----------------------------------------------------------------------------
module Control.Iterative where
import Control.Applicative
import Control.Monad (when)
-- import Control.Monad.Trans.Reader
import Control.Monad.Reader
import Control.Monad.State.Strict
-- import Control.Monad.Trans.Writer.CPS
import Control.Monad.Trans.Class (MonadTrans(..), lift)
import qualified Control.Monad.Trans.State.Strict as MTS -- (runStateT)
import Control.Monad.Catch
import qualified Control.Monad.Log as L (MonadLog(..), WithSeverity(..), Severity(..), renderWithSeverity, LoggingT, runLoggingT, Handler, logMessage, logError, logDebug, logInfo, logNotice)
-- import Data.Bool (bool)
import Data.Char (toUpper)
import Data.Typeable
import qualified Control.Exception as E (Exception, Handler)
import Data.Foldable (foldrM)
-- import Control.Exception.Common
-- import Numeric.LinearAlgebra.Class
-- import Numeric.Eps
data ConvergenceStatus a = BufferNotReady
| Converging
| Converged a
| Diverging a a
| NotConverged
deriving (Eq, Show, Typeable)
instance (Typeable a, Show a) => Exception (ConvergenceStatus a)
-- FIXME I don't like this; logging shouldn't be in IO, `iterationView` is too general, etc.
data IterationConfig a b =
IterConf { numIterationsMax :: Int -- ^ Max.# of iterations
, printDebugInfo :: Bool -- ^ Print iteration info to stdout
, iterationView :: a -> b -- ^ Project state to a type `b`
, printDebugIO :: b -> IO ()} -- ^ print function for type `b`
instance Show (IterationConfig a b) where
show (IterConf n qd _ _) = unwords ["Max. # of iterations:",show n,", print debug information:", show qd]
-- | Iterative algorithms need configuration and logging; here we use a transformer stack or ReaderT on top of LoggingT (from `logging-effect`).
newtype App c msg m a =
App {
unApp :: ReaderT c (L.LoggingT msg m) a
} deriving (Functor, Applicative, Alternative, Monad)
-- instance MonadTrans (App c msg) where
liftApp :: (c -> L.LoggingT msg m a) -> App c msg m a
liftApp = App . ReaderT
testApp :: (Monad m, MonadState b (t m), MonadTrans t, L.MonadLog msg (t m)) =>
(b -> m b) -> (t1 -> b -> msg) -> t1 -> t m b
testApp fm logf c = do
x <- get
y <- lift $ fm x
put y
L.logMessage (logf c y)
return y
-- | Configure and log a computation
runApp :: L.Handler m msg -> c -> App c msg m a -> m a
runApp logHandler config m = L.runLoggingT (runReaderT (unApp m) config) logHandler
runLogDebug :: L.MonadLog (L.WithSeverity msg) m => c -> App c msg m a -> m a
runLogDebug = runApp L.logDebug
-- -- | runApp, logging by printing to terminal
-- runDebug :: Show a => c -> App c a IO b -> IO b
-- runDebug = runApp print
-- | App1: LoggingT / ReaderT
-- newtype App1 c msg m a = App1 { unApp1 :: L.LoggingT msg (ReaderT c m) a } deriving (Functor, Applicative, Alternative, Monad)
-- liftApp1 logf f = App1 $ do
-- c <- ask
-- y <- lift . lift $ f c
-- L.logMessage (logf y)
-- return y
-- | App2: ReaderT / LoggingT / StateT
newtype App2 c msg s m a = App2 {
unApp2 :: ReaderT c (L.LoggingT msg (StateT s m)) a
} deriving (Functor, Applicative, Alternative, Monad)
runApp2 lh r x0 m = runStateT (L.runLoggingT (runReaderT (unApp2 m) r) lh) x0
-- app2 :: Monad m =>
-- (c -> a -> log) -- ^ Builds a log entry from the configuration and the current state
-- -> (r -> t) -- ^ Builds
-- -> (r -> c)
-- -> (a -> t -> m a)
-- -> App2 r log a m a
app2 logf cconf lconf fm = App2 $ do
x <- get
cc <- asks cconf
lc <- asks lconf
y <- lift . lift . lift $ fm x cc
L.logMessage (logf lc y)
put y
return y
-- logging test
-- -- logApp :: L.MonadLog (L.WithSeverity String) m => m ()
logApp = do
L.logError "moo"
L.logInfo "info"
asdf = L.runLoggingT logApp (putStrLn . withSeverity id)
-- -- renderWithSeverity k (L.WithSeverity u a)
bracketsUpp :: Show a => a -> String
bracketsUpp p = unwords ["[", map toUpper (show p), "]"]
withSeverity :: (t -> String) -> L.WithSeverity t -> String
withSeverity k (L.WithSeverity u a ) = unwords [bracketsUpp u, k a]
-- -- >>> renderWithSeverity id (WithSeverity Informational "Flux capacitor is functional")
-- -- [Informational] Flux capacitor is functional
-- renderWithSeverity
-- :: (a -> PP.Doc) -> (WithSeverity a -> PP.Doc)
-- renderWithSeverity k (WithSeverity u a) =
-- PP.brackets (PP.pretty u) PP.<+> PP.align (k a)
-- * Control primitives for bounded iteration with convergence check
-- -- | transform state until a condition is met
modifyUntil :: MonadState s m => (s -> Bool) -> (s -> s) -> m s
modifyUntil q f = modifyUntilM q (pure . f)
modifyUntilM :: MonadState s m => (s -> Bool) -> (s -> m s) -> m s
modifyUntilM q f = do
x <- get
y <- f x
put y
if q y then return y
else modifyUntilM q f
modifyUntilM_ :: MonadState s m => (s -> Bool) -> (s -> m s) -> m s
modifyUntilM_ q f = do
x <- get
y <- f x
if q y
then pure y
else do
put y
modifyUntilM_ q f
-- | modifyUntil with optional iteration logging to stdout
modifyUntil' :: L.MonadLog String m =>
IterationConfig a b -> (a -> Bool) -> (a -> a) -> a -> m a
modifyUntil' config q f x0 = modifyUntilM' config q (pure . f) x0
modifyUntilM' :: L.MonadLog String m =>
IterationConfig a b -> (a -> Bool) -> (a -> m a) -> a -> m a
modifyUntilM' config q f x0 = MTS.execStateT (go 0) x0 where
pf = iterationView config
go i = do
x <- get
y <- lift $ f x
when (printDebugInfo config) $ do
L.logMessage $ unwords ["Iteration", show i, "\n"]
-- when (printDebugInfo config) $ liftIO $ do
-- putStrLn $ unwords ["Iteration", show i, "\n"]
-- printDebugIO config (pf y)
put y
if q y
then return y
else go (i + 1)
-- | `untilConvergedG0` is a special case of `untilConvergedG` that assesses convergence based on the L2 distance to a known solution `xKnown`
untilConvergedG0 :: (Normed v, MonadThrow m, L.MonadLog String m, Typeable (Magnitude v), Typeable s, Show s) =>
String
-> IterationConfig s v
-> v -- ^ Known value
-> (s -> s)
-> s
-> m s
untilConvergedG0 fname config xKnown f x0 =
modifyInspectGuarded fname config norm2Diff nearZero qdiverg qfin f x0
where
qfin s = nearZero $ norm2 (xKnown ^-^ s)
-- | This function makes some default choices on the `modifyInspectGuarded` machinery: convergence is assessed using the squared L2 distance between consecutive states, and divergence is detected when this function is increasing between pairs of measurements.
untilConvergedG :: (Normed v, MonadThrow m, L.MonadLog String m, Typeable (Magnitude v), Typeable s, Show s) =>
String
-> IterationConfig s v
-> (v -> Bool)
-> (s -> s)
-> s
-> m s
untilConvergedG fname config =
modifyInspectGuarded fname config norm2Diff nearZero qdiverg
-- | ", monadic version
untilConvergedGM ::
(Normed v, MonadThrow m, L.MonadLog String m, Typeable (Magnitude v), Typeable s, Show s) =>
String
-> IterationConfig s v
-> (v -> Bool)
-> (s -> m s)
-> s
-> m s
untilConvergedGM fname config =
modifyInspectGuardedM fname config norm2Diff nearZero qdiverg
-- | `modifyInspectGuarded` is a high-order abstraction of a numerical iterative process. It accumulates a rolling window of 3 states and compares a summary `q` of the latest 2 with that of the previous two in order to assess divergence (e.g. if `q latest2 > q prev2` then the function throws an exception and terminates). The process ends by either hitting an iteration budget or by relative convergence, whichever happens first. After the iterations stop, the function then assesses the final state with a predicate `qfinal` (e.g. for comparing the final state with a known one; if this is not available, the user can just supply `const True`)
modifyInspectGuarded ::
(MonadThrow m, L.MonadLog String m, Typeable s, Typeable a, Show s, Show a) =>
String -- ^ Calling function name
-> IterationConfig s v -- ^ Configuration
-> ([v] -> a) -- ^ State summary array projection
-> (a -> Bool) -- ^ Convergence criterion
-> (a -> a -> Bool) -- ^ Divergence criterion
-> (v -> Bool) -- ^ Final state acceptance criterion
-> (s -> s) -- ^ State evolution
-> s -- ^ Initial state
-> m s -- ^ Final state
modifyInspectGuarded fname config sf qc qd qfin f x0 =
modifyInspectGuardedM fname config sf qc qd qfin (pure . f) x0
-- | ", monadic version
modifyInspectGuardedM ::
(MonadThrow m, L.MonadLog String m, Typeable s, Show s, Typeable a, Show a) =>
String
-> IterationConfig s v
-> ([v] -> a)
-> (a -> Bool)
-> (a -> a -> Bool)
-> (v -> Bool)
-> (s -> m s)
-> s
-> m s
modifyInspectGuardedM fname config sf qconverg qdiverg qfinal f x0
| nitermax > 0 = MTS.execStateT (go 0 []) x0
| otherwise = throwM (NonNegError fname nitermax)
where
lwindow = 3
nitermax = numIterationsMax config
pf = iterationView config
checkConvergStatus y i ll
| length ll < lwindow = BufferNotReady
| qdiverg qi qt && not (qconverg qi) = Diverging qi qt
| qconverg qi || qfinal (pf y) = Converged qi
| i == nitermax - 1 = NotConverged
| otherwise = Converging
where llf = pf <$> ll
qi = sf $ init llf -- summary of latest 2 states
qt = sf $ tail llf -- " " previous 2 states
go i ll = do
x <- MTS.get
y <- lift $ f x
when (printDebugInfo config) $ do
L.logMessage $ unwords ["Iteration", show i]
-- when (printDebugInfo config) $ liftIO $ do
-- putStrLn $ unwords ["Iteration", show i]
-- printDebugIO config (pf y)
case checkConvergStatus y i ll of
BufferNotReady -> do
MTS.put y
let ll' = y : ll -- cons current state to buffer
go (i + 1) ll'
Converged qi -> MTS.put y
Diverging qi qt -> do
MTS.put y
throwM (DivergingE fname i qi qt)
Converging -> do
MTS.put y
let ll' = init (y : ll) -- rolling state window
go (i + 1) ll'
NotConverged -> do
MTS.put y
throwM (NotConvergedE fname nitermax y)
-- | Some useful combinators
-- | Apply a function over a range of integer indices, zip the result with it and filter out the almost-zero entries
onRangeSparse :: Epsilon b => (Int -> b) -> [Int] -> [(Int, b)]
onRangeSparse f ixs = foldr ins [] ixs where
ins x xr | isNz (f x) = (x, f x) : xr
| otherwise = xr
-- | ", monadic version
onRangeSparseM :: (Epsilon b, Foldable t, Monad m) =>
(a -> m b) -> t a -> m [(a, b)]
onRangeSparseM f ixs = unfoldZipM mf f ixs where
mf x = isNz <$> f x
unfoldZipM0 :: (Foldable t, Monad m) =>
(a -> Bool) -> (a -> b) -> t a -> m [(a, b)]
unfoldZipM0 q f = unfoldZipM (pure . q) (pure . f)
unfoldZipM :: (Foldable t, Monad m) =>
(a -> m Bool) -> (a -> m b) -> t a -> m [(a, b)]
unfoldZipM q f ixs = foldrM insf [] ixs where
insf x xr = do
qx <- q x
if qx
then do
y <- f x
pure $ (x, y) : xr
else pure xr
-- | A combinator I don't know how to call
combx :: Functor f => (a -> b) -> (t -> f a) -> t -> f b
combx g f x = g <$> f x
-- | Helpers
-- | Relative residual
relRes :: (Normed t, LinearVectorSpace t) =>
MatrixType t -> t -> t -> Magnitude t
relRes aa b x = n / d where
n = norm2 $ (aa #> x) ^-^ b
d = norm2 b
-- meanl :: (Foldable t, Fractional a) => t a -> a
-- meanl xx = 1/fromIntegral (length xx) * sum xx
-- norm2l :: (Foldable t, Functor t, Floating a) => t a -> a
-- norm2l xx = sqrt $ sum (fmap (**2) xx)
-- | Squared difference of a 2-element list.
-- | NB: unsafe !
diffSqL :: Floating a => [a] -> a
diffSqL xx = (x1 - x2)**2 where [x1, x2] = [head xx, xx!!1]
-- | Relative tolerance :
-- relTol a b := ||a - b|| / (1 + min (||norm2 a||, ||norm2 b||))
relTol :: Normed v => v -> v -> Magnitude v
relTol a b = norm2 (a ^-^ b) / m where
m = 1 + min (norm2 a) (norm2 b)
qdiverg :: Ord a => a -> a -> Bool
qdiverg = (>)
norm2Diff [s1, s0] = norm2 (s1 ^-^ s0)
norm2Diff _ = 1/0
-- test data
data S = S {unS1 :: Double, unS2 :: String} deriving (Eq, Show)
liftS1 f (S x i) = S (f x) i
s0 = S 1 "blah"
ic1 = IterConf 2 True unS1 print
-- playground
-- instance MonadThrow m => MonadThrow (WriterT w m) where
-- throwM = lift . throwM
-- -- | iter0 also accepts a configuration, e.g. for optional printing of debug info
-- -- iter0 :: MonadIO m =>
-- -- Int -> (s -> m s) -> (s -> String) -> IterationConfig s -> s -> m s
-- iter0 nmax f sf config x0 = flip runReaderT config $ MTS.execStateT (go (0 :: Int)) x0
-- where
-- go i = do
-- x <- get
-- c <- lift $ asks printDebugInfo -- neat
-- y <- lift . lift $ f x -- not neat
-- when c $ liftIO $ putStrLn $ sf y
-- put y
-- unless (i >= nmax) (go $ i + 1)
-- -- | iter1 prints output at every iteration until the loop terminates OR is interrupted by an exception, whichever happens first
-- -- iter1 :: (MonadThrow m, MonadIO m, Typeable t, Show t) =>
-- -- (t -> m t) -> (t -> String) -> (t -> Bool) -> (t -> Bool) -> t -> m t
-- iter1 f wf qe qx x0 = execStateT (go 0) x0 where
-- go i = do
-- x <- get
-- y <- lift $ f x
-- _ <- liftIO $ wf y
-- when (qx y) $ throwM (NotConvergedE "bla" (i+1) y)
-- put y
-- unless (qe y) $ go (i + 1)
-- -- | iter2 concatenates output with WriterT but does NOT `tell` any output if an exception is raised before the end of the loop
-- iter2 :: (MonadThrow m, Monoid w, Typeable t, Show t) => (t -> m t)
-- -> (t -> w) -> (t -> Bool) -> (t -> Bool) -> t -> m (t, w)
-- iter2 f wf qe qx x0 = runWriterT $ execStateT (go 0) x0 where
-- go i = do
-- x <- get
-- y <- lift . lift $ f x
-- lift $ tell $ wf y
-- when (qx y) $ throwM (NotConvergedE "bla" (i+1) y)
-- put y
-- unless (qe y) $ go (i + 1)
-- -- test :: IO (Int, [String])
-- test :: IO Int
-- -- test :: IO ()
-- test = do
-- (yt, w ) <- iter2 f wf qe qexc x0
-- putStrLn w
-- return yt
-- -- iter1 f wf qe qexc x0
-- where
-- f = pure . (+ 1)
-- wf v = unwords ["state =", show v]
-- qe = (== 5)
-- qexc = (== 3)
-- x0 = 0 :: Int
|
Definition pull (T : Type) (P : T -> Prop) : Type := (forall x : T, P x) -> {x : T | P x}.
Definition existence (T : Type) : Type := {x : T | True}.
Theorem cannot_pull : (forall T P, pull T P) -> False.
Proof.
unfold pull.
intros.
specialize (X False (fun _=> False)).
simpl in X.
destruct X.
intros.
assumption.
assumption.
Show Proof.
Qed.
Theorem but_why : exists T P, pull T P -> False.
Proof.
exists False, (fun _ => False).
unfold pull.
intros.
destruct H.
intros. assumption.
assumption.
Qed.
Theorem can_pull_if_existence : forall T, existence T -> (forall P, pull T P).
Proof.
unfold existence.
unfold pull.
intros.
destruct X.
exists x.
apply H.
Qed.
Theorem existence_if_can_pull : forall T, (forall P, pull T P) -> existence T.
Proof.
unfold existence.
unfold pull.
intros.
specialize (X (fun _ => True)).
simpl in X.
apply X.
intro.
apply I.
Qed.
|
'''-------------------------------------------------------------------------------
Tool Name: CreateWeightTableFrom2DLatLonRunoff
Source Name: CreateWeightTableFrom2DLatLonRunoff.py
Version: ArcGIS 10.3
Author: Alan Dee Snow
Description: Creates RAPID inflow file based on 2D Latitude and Longitude runoff output
and the weight table previously created.
History: Initial coding - 8/19/2016, version 1.0
------------------------------------------------------------------------------'''
import os
import arcpy
import netCDF4 as NET
import numpy as NUM
import csv
class CreateWeightTableFrom2DLatLonRunoff(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Create Weight Table From 2D Lat Lon LSM Grid Runoff"
self.description = ("Creates RAPID inflow file based on 2D Latitude and Longitude runoff output" +
" and catchment features")
self.canRunInBackground = False
self.errorMessages = ["Incorrect dimensions in the input LIS runoff file.",
"Incorrect variables in the input LIS runoff file."]
self.category = "Preprocessing"
def dataValidation(self, in_nc, messages):
"""Check the necessary dimensions and variables in the input netcdf data"""
return
def createPolygon(self, extent, out_polygons, scratchWorkspace):
"""Create a Thiessen polygon feature class from numpy.ndarray lat and lon
Each polygon represents the area described by the center point
"""
lsm_dx = NUM.max(NUM.absolute(NUM.diff(self.lsm_lon_array)))
lsm_dy = NUM.max(NUM.absolute(NUM.diff(self.lsm_lat_array, axis=0)))
lsm_lat_indices_from_lat, lsm_lon_indices_from_lat = NUM.where((self.lsm_lat_array >= (extent.YMin - 2*lsm_dy)) & (self.lsm_lat_array <= (extent.YMax + 2*lsm_dy)))
lsm_lat_indices_from_lon, lsm_lon_indices_from_lon = NUM.where((self.lsm_lon_array >= (extent.XMin - 2*lsm_dx)) & (self.lsm_lon_array <= (extent.XMax + 2*lsm_dx)))
lsm_lat_indices = NUM.intersect1d(lsm_lat_indices_from_lat, lsm_lat_indices_from_lon)
lsm_lon_indices = NUM.intersect1d(lsm_lon_indices_from_lat, lsm_lon_indices_from_lon)
lsm_lat_list = self.lsm_lat_array[lsm_lat_indices,:][:,lsm_lon_indices]
lsm_lon_list = self.lsm_lon_array[lsm_lat_indices,:][:,lsm_lon_indices]
# Spatial reference
sr = arcpy.SpatialReference(4326) #CGS_WGS_1984
# Create a list of geographic coordinate pairs
pointGeometryList = []
for i in range(len(lsm_lat_indices)):
for j in range(len(lsm_lon_indices)):
point = arcpy.Point()
point.X = float(lsm_lon_list[i][j])
point.Y = float(lsm_lat_list[i][j])
pointGeometry = arcpy.PointGeometry(point, sr)
pointGeometryList.append(pointGeometry)
# Create a point feature class with longitude in Point_X, latitude in Point_Y
out_points = os.path.join(scratchWorkspace, 'points_subset')
result2 = arcpy.CopyFeatures_management(pointGeometryList, out_points)
out_points = result2.getOutput(0)
arcpy.AddGeometryAttributes_management(out_points, 'POINT_X_Y_Z_M')
# Create Thiessen polygon based on the point feature
result3 = arcpy.CreateThiessenPolygons_analysis(out_points, out_polygons, 'ALL')
out_polygons = result3.getOutput(0)
return out_points, out_polygons
def csvToList(self, csv_file, delimiter=','):
"""
Reads in a CSV file and returns the contents as list,
where every row is stored as a sublist, and each element
in the sublist represents 1 cell in the table.
"""
with open(csv_file, 'rb') as csv_con:
reader = csv.reader(csv_con, delimiter=delimiter)
return list(reader)
def getParameterInfo(self):
"""Define parameter definitions"""
param0 = arcpy.Parameter(name = "in_runoff_file",
displayName = "Input Runoff File",
direction = "Input",
parameterType = "Required",
datatype = "DEFile")
param1 = arcpy.Parameter(name = "in_lat_variable",
displayName = "2D Latitude Variable [-90,90]",
direction = "Input",
parameterType = "Required",
datatype = "GPString")
param1.filter.list = []
param2 = arcpy.Parameter(name = "in_lon_variable",
displayName = "2D Longitude Variable [-180,180]",
direction = "Input",
parameterType = "Required",
datatype = "GPString")
param2.filter.list = []
param3 = arcpy.Parameter(name="in_rapid_connect_file",
displayName="Input RAPID Connect File",
direction="Input",
parameterType="Required",
datatype="DEFile")
param4 = arcpy.Parameter(name = "in_catchment_features",
displayName = "Input Catchment Features",
direction = "Input",
parameterType = "Required",
datatype = "GPFeatureLayer")
param4.filter.list = ['Polygon']
param5 = arcpy.Parameter(name = "stream_ID",
displayName = "Stream ID",
direction = "Input",
parameterType = "Required",
datatype = "Field"
)
param5.parameterDependencies = ["in_catchment_features"]
param5.filter.list = ['Short', 'Long']
param6 = arcpy.Parameter(name="out_weight_table",
displayName="Output Weight Table",
direction="Output",
parameterType="Required",
datatype="DEFile")
params = [param0, param1, param2, param3, param4, param5, param6]
return params
def isLicensed(self):
"""Set whether tool is licensed to execute."""
return True
def updateParameters(self, parameters):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
if parameters[6].valueAsText is None:
scratchWorkspace = arcpy.env.scratchWorkspace
if not scratchWorkspace:
scratchWorkspace = arcpy.env.scratchGDB
parameters[6].value = os.path.join(scratchWorkspace, "Weight_Table.csv")
if parameters[6].altered:
(dirnm, basenm) = os.path.split(parameters[6].valueAsText)
if not basenm.endswith(".csv"):
parameters[6].value = os.path.join(dirnm, "{}.csv".format(basenm))
if parameters[0].altered:
#get list of variables in the netcdf file
data_nc = NET.Dataset(parameters[0].valueAsText)
variables_list = data_nc.variables.keys()
dimensions_list = data_nc.dimensions.keys()
data_nc.close()
parameters[1].filter.list = variables_list
parameters[2].filter.list = variables_list
return
def updateMessages(self, parameters):
"""Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation."""
if parameters[0].altered:
in_nc = parameters[0].valueAsText
try:
data_nc = NET.Dataset(in_nc)
data_nc.close()
except Exception as e:
parameters[0].setErrorMessage(e.message)
return
def execute(self, parameters, messages):
"""The source code of the tool."""
arcpy.env.overwriteOutput = True
scratchWorkspace = arcpy.env.scratchWorkspace
if not scratchWorkspace:
scratchWorkspace = arcpy.env.scratchGDB
in_nc = parameters[0].valueAsText
in_nc_lat_var = parameters[1].valueAsText
in_nc_lon_var = parameters[2].valueAsText
in_rapid_connect_file = parameters[3].valueAsText
in_catchment = parameters[4].valueAsText
streamID = parameters[5].valueAsText
out_WeightTable = parameters[6].valueAsText
# validate the netcdf dataset
self.dataValidation(in_nc, messages)
# Obtain catchment extent in lat and lon in GCS_WGS_1984
sr_cat = arcpy.Describe(in_catchment).SpatialReference
extent = arcpy.Describe(in_catchment).extent
#if (sr_cat.name == 'World_Equidistant_Cylindrical'):
if (sr_cat.name == 'GCS_WGS_1984'):
extent = extent
else:
envelope = os.path.join(scratchWorkspace, 'envelope')
result0 = arcpy.MinimumBoundingGeometry_management(in_catchment, envelope, 'ENVELOPE', 'ALL')
envelope = result0.getOutput(0)
sr_out = arcpy.SpatialReference(4326) # GCS_WGS_1984
envelope_proj = os.path.join(scratchWorkspace,'envelope_proj')
result1 = arcpy.Project_management(envelope, envelope_proj, sr_out)
envelope_proj = result1.getOutput(0)
extent = arcpy.Describe(envelope_proj).extent
#Open nc file
data_nc = NET.Dataset(in_nc)
# Obtain geographic coordinates
self.lsm_lon_array = data_nc.variables[in_nc_lon_var][:] #assume [-180, 180]
self.lsm_lat_array = data_nc.variables[in_nc_lat_var][:] #assume [-90,90]
data_nc.close()
#convert 3d to 2d if time dimension
if(len( self.lsm_lon_array.shape) == 3):
self.lsm_lon_array = self.lsm_lon_array[0]
self.lsm_lat_array = self.lsm_lat_array[0]
# Create Thiessen polygons based on the points within the extent
arcpy.AddMessage("Generating Thiessen polygons...")
polygon_thiessen = os.path.join(scratchWorkspace,'polygon_thiessen')
result4 = self.createPolygon(extent, polygon_thiessen, scratchWorkspace)
polygon_thiessen = result4[1]
# Intersect the catchment polygons with the Thiessen polygons
arcpy.AddMessage("Intersecting Thiessen polygons with catchment...")
intersect = os.path.join(scratchWorkspace, 'intersect')
result5 = arcpy.Intersect_analysis([in_catchment, polygon_thiessen], intersect, 'ALL', '#', 'INPUT')
intersect = result5.getOutput(0)
# Calculate the geodesic area in square meters for each intersected polygon (no need to project if it's not projected yet)
arcpy.AddMessage("Calculating geodesic areas...")
arcpy.AddGeometryAttributes_management(intersect, 'AREA_GEODESIC', '', 'SQUARE_METERS', '')
# Calculate the total geodesic area of each catchment based on the contributing areas of points
fields = [streamID, 'POINT_X', 'POINT_Y', 'AREA_GEO']
area_arr = arcpy.da.FeatureClassToNumPyArray(intersect, fields)
arcpy.AddMessage("Writing the weight table...")
#get list of COMIDs in rapid_connect file so only those are included in computations
connectivity_table = self.csvToList(in_rapid_connect_file)
streamID_unique_arr = [int(row[0]) for row in connectivity_table]
#if point not in array append dummy data for one point of data
lon_dummy = area_arr['POINT_X'][0]
lat_dummy = area_arr['POINT_Y'][0]
#find point index in 2d grid
lsm_lat_indices_from_lat, lsm_lon_indices_from_lat = NUM.where(self.lsm_lat_array == lat_dummy)
lsm_lat_indices_from_lon, lsm_lon_indices_from_lon = NUM.where(self.lsm_lon_array == lon_dummy)
index_lat_dummy = NUM.intersect1d(lsm_lat_indices_from_lat, lsm_lat_indices_from_lon)[0]
index_lon_dummy = NUM.intersect1d(lsm_lon_indices_from_lat, lsm_lon_indices_from_lon)[0]
with open(out_WeightTable, 'wb') as csvfile:
connectwriter = csv.writer(csvfile, dialect = 'excel')
connectwriter.writerow([streamID, 'area_sqm', 'lon_index', 'lat_index', 'npoints'])
for streamID_unique in streamID_unique_arr:
ind_points = NUM.where(area_arr[streamID]==streamID_unique)[0]
num_ind_points = len(ind_points)
if num_ind_points <= 0:
#FEATUREID,area_sqm,lon_index,lat_index,npoints,Lon,Lat
connectwriter.writerow([streamID_unique, 0, index_lon_dummy, index_lat_dummy, 1])
else:
for ind_point in ind_points:
area_geo_each = float(area_arr['AREA_GEO'][ind_point])
lon_each = area_arr['POINT_X'][ind_point]
lat_each = area_arr['POINT_Y'][ind_point]
#find point index in 2d grid
lsm_lat_indices_from_lat, lsm_lon_indices_from_lat = NUM.where(self.lsm_lat_array == lat_each)
lsm_lat_indices_from_lon, lsm_lon_indices_from_lon = NUM.where(self.lsm_lon_array == lon_each)
index_lat_each = NUM.intersect1d(lsm_lat_indices_from_lat, lsm_lat_indices_from_lon)[0]
index_lon_each = NUM.intersect1d(lsm_lon_indices_from_lat, lsm_lon_indices_from_lon)[0]
#write to file
connectwriter.writerow([streamID_unique, area_geo_each, index_lon_each,
index_lat_each, num_ind_points])
return
|
/-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers
! This file was ported from Lean 3 source module linear_algebra.affine_space.independent
! leanprover-community/mathlib commit 2de9c37fa71dde2f1c6feff19876dd6a7b1519f0
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.Data.Finset.Sort
import Mathbin.Data.Fin.VecNotation
import Mathbin.Data.Sign
import Mathbin.LinearAlgebra.AffineSpace.Combination
import Mathbin.LinearAlgebra.AffineSpace.AffineEquiv
import Mathbin.LinearAlgebra.Basis
/-!
# Affine independence
This file defines affinely independent families of points.
## Main definitions
* `affine_independent` defines affinely independent families of points
as those where no nontrivial weighted subtraction is `0`. This is
proved equivalent to two other formulations: linear independence of
the results of subtracting a base point in the family from the other
points in the family, or any equal affine combinations having the
same weights. A bundled type `simplex` is provided for finite
affinely independent families of points, with an abbreviation
`triangle` for the case of three points.
## References
* https://en.wikipedia.org/wiki/Affine_space
-/
noncomputable section
open BigOperators Affine
open Function
section AffineIndependent
variable (k : Type _) {V : Type _} {P : Type _} [Ring k] [AddCommGroup V] [Module k V]
variable [affine_space V P] {ι : Type _}
include V
/-- An indexed family is said to be affinely independent if no
nontrivial weighted subtractions (where the sum of weights is 0) are
0. -/
def AffineIndependent (p : ι → P) : Prop :=
∀ (s : Finset ι) (w : ι → k),
(∑ i in s, w i) = 0 → s.weightedVsub p w = (0 : V) → ∀ i ∈ s, w i = 0
#align affine_independent AffineIndependent
/-- The definition of `affine_independent`. -/
theorem affineIndependent_def (p : ι → P) :
AffineIndependent k p ↔
∀ (s : Finset ι) (w : ι → k),
(∑ i in s, w i) = 0 → s.weightedVsub p w = (0 : V) → ∀ i ∈ s, w i = 0 :=
Iff.rfl
#align affine_independent_def affineIndependent_def
/-- A family with at most one point is affinely independent. -/
theorem affineIndependent_of_subsingleton [Subsingleton ι] (p : ι → P) : AffineIndependent k p :=
fun s w h hs i hi => Fintype.eq_of_subsingleton_of_sum_eq h i hi
#align affine_independent_of_subsingleton affineIndependent_of_subsingleton
/-- A family indexed by a `fintype` is affinely independent if and
only if no nontrivial weighted subtractions over `finset.univ` (where
the sum of the weights is 0) are 0. -/
theorem affineIndependent_iff_of_fintype [Fintype ι] (p : ι → P) :
AffineIndependent k p ↔
∀ w : ι → k, (∑ i, w i) = 0 → Finset.univ.weightedVsub p w = (0 : V) → ∀ i, w i = 0 :=
by
constructor
· exact fun h w hw hs i => h Finset.univ w hw hs i (Finset.mem_univ _)
· intro h s w hw hs i hi
rw [Finset.weightedVsub_indicator_subset _ _ (Finset.subset_univ s)] at hs
rw [Set.sum_indicator_subset _ (Finset.subset_univ s)] at hw
replace h := h ((↑s : Set ι).indicator w) hw hs i
simpa [hi] using h
#align affine_independent_iff_of_fintype affineIndependent_iff_of_fintype
/-- A family is affinely independent if and only if the differences
from a base point in that family are linearly independent. -/
theorem affineIndependent_iff_linearIndependent_vsub (p : ι → P) (i1 : ι) :
AffineIndependent k p ↔ LinearIndependent k fun i : { x // x ≠ i1 } => (p i -ᵥ p i1 : V) := by
classical
constructor
· intro h
rw [linearIndependent_iff']
intro s g hg i hi
set f : ι → k := fun x => if hx : x = i1 then -∑ y in s, g y else g ⟨x, hx⟩ with hfdef
let s2 : Finset ι := insert i1 (s.map (embedding.subtype _))
have hfg : ∀ x : { x // x ≠ i1 }, g x = f x :=
by
intro x
rw [hfdef]
dsimp only
erw [dif_neg x.property, Subtype.coe_eta]
rw [hfg]
have hf : (∑ ι in s2, f ι) = 0 :=
by
rw [Finset.sum_insert
(Finset.not_mem_map_subtype_of_not_property s (Classical.not_not.2 rfl)),
Finset.sum_subtype_map_embedding fun x hx => (hfg x).symm]
rw [hfdef]
dsimp only
rw [dif_pos rfl]
exact neg_add_self _
have hs2 : s2.weighted_vsub p f = (0 : V) :=
by
set f2 : ι → V := fun x => f x • (p x -ᵥ p i1) with hf2def
set g2 : { x // x ≠ i1 } → V := fun x => g x • (p x -ᵥ p i1) with hg2def
have hf2g2 : ∀ x : { x // x ≠ i1 }, f2 x = g2 x :=
by
simp_rw [hf2def, hg2def, hfg]
exact fun x => rfl
rw [Finset.weightedVsub_eq_weightedVsubOfPoint_of_sum_eq_zero s2 f p hf (p i1),
Finset.weightedVsubOfPoint_insert, Finset.weightedVsubOfPoint_apply,
Finset.sum_subtype_map_embedding fun x hx => hf2g2 x]
exact hg
exact h s2 f hf hs2 i (Finset.mem_insert_of_mem (Finset.mem_map.2 ⟨i, hi, rfl⟩))
· intro h
rw [linearIndependent_iff'] at h
intro s w hw hs i hi
rw [Finset.weightedVsub_eq_weightedVsubOfPoint_of_sum_eq_zero s w p hw (p i1), ←
s.weighted_vsub_of_point_erase w p i1, Finset.weightedVsubOfPoint_apply] at hs
let f : ι → V := fun i => w i • (p i -ᵥ p i1)
have hs2 : (∑ i in (s.erase i1).Subtype fun i => i ≠ i1, f i) = 0 :=
by
rw [← hs]
convert Finset.sum_subtype_of_mem f fun x => Finset.ne_of_mem_erase
have h2 := h ((s.erase i1).Subtype fun i => i ≠ i1) (fun x => w x) hs2
simp_rw [Finset.mem_subtype] at h2
have h2b : ∀ i ∈ s, i ≠ i1 → w i = 0 := fun i his hi =>
h2 ⟨i, hi⟩ (Finset.mem_erase_of_ne_of_mem hi his)
exact Finset.eq_zero_of_sum_eq_zero hw h2b i hi
#align affine_independent_iff_linear_independent_vsub affineIndependent_iff_linearIndependent_vsub
/-- A set is affinely independent if and only if the differences from
a base point in that set are linearly independent. -/
theorem affineIndependent_set_iff_linearIndependent_vsub {s : Set P} {p₁ : P} (hp₁ : p₁ ∈ s) :
AffineIndependent k (fun p => p : s → P) ↔
LinearIndependent k (fun v => v : (fun p => (p -ᵥ p₁ : V)) '' (s \ {p₁}) → V) :=
by
rw [affineIndependent_iff_linearIndependent_vsub k (fun p => p : s → P) ⟨p₁, hp₁⟩]
constructor
· intro h
have hv : ∀ v : (fun p => (p -ᵥ p₁ : V)) '' (s \ {p₁}), (v : V) +ᵥ p₁ ∈ s \ {p₁} := fun v =>
(vsub_left_injective p₁).mem_set_image.1 ((vadd_vsub (v : V) p₁).symm ▸ v.property)
let f : (fun p : P => (p -ᵥ p₁ : V)) '' (s \ {p₁}) → { x : s // x ≠ ⟨p₁, hp₁⟩ } := fun x =>
⟨⟨(x : V) +ᵥ p₁, Set.mem_of_mem_diff (hv x)⟩, fun hx =>
Set.not_mem_of_mem_diff (hv x) (Subtype.ext_iff.1 hx)⟩
convert h.comp f fun x1 x2 hx =>
Subtype.ext (vadd_right_cancel p₁ (Subtype.ext_iff.1 (Subtype.ext_iff.1 hx)))
ext v
exact (vadd_vsub (v : V) p₁).symm
· intro h
let f : { x : s // x ≠ ⟨p₁, hp₁⟩ } → (fun p : P => (p -ᵥ p₁ : V)) '' (s \ {p₁}) := fun x =>
⟨((x : s) : P) -ᵥ p₁, ⟨x, ⟨⟨(x : s).property, fun hx => x.property (Subtype.ext hx)⟩, rfl⟩⟩⟩
convert h.comp f fun x1 x2 hx =>
Subtype.ext (Subtype.ext (vsub_left_cancel (Subtype.ext_iff.1 hx)))
#align affine_independent_set_iff_linear_independent_vsub affineIndependent_set_iff_linearIndependent_vsub
/-- A set of nonzero vectors is linearly independent if and only if,
given a point `p₁`, the vectors added to `p₁` and `p₁` itself are
affinely independent. -/
theorem linearIndependent_set_iff_affineIndependent_vadd_union_singleton {s : Set V}
(hs : ∀ v ∈ s, v ≠ (0 : V)) (p₁ : P) :
LinearIndependent k (fun v => v : s → V) ↔
AffineIndependent k (fun p => p : {p₁} ∪ (fun v => v +ᵥ p₁) '' s → P) :=
by
rw [affineIndependent_set_iff_linearIndependent_vsub k
(Set.mem_union_left _ (Set.mem_singleton p₁))]
have h : (fun p => (p -ᵥ p₁ : V)) '' (({p₁} ∪ (fun v => v +ᵥ p₁) '' s) \ {p₁}) = s :=
by
simp_rw [Set.union_diff_left, Set.image_diff (vsub_left_injective p₁), Set.image_image,
Set.image_singleton, vsub_self, vadd_vsub, Set.image_id']
exact Set.diff_singleton_eq_self fun h => hs 0 h rfl
rw [h]
#align linear_independent_set_iff_affine_independent_vadd_union_singleton linearIndependent_set_iff_affineIndependent_vadd_union_singleton
/-- A family is affinely independent if and only if any affine
combinations (with sum of weights 1) that evaluate to the same point
have equal `set.indicator`. -/
theorem affineIndependent_iff_indicator_eq_of_affineCombination_eq (p : ι → P) :
AffineIndependent k p ↔
∀ (s1 s2 : Finset ι) (w1 w2 : ι → k),
(∑ i in s1, w1 i) = 1 →
(∑ i in s2, w2 i) = 1 →
s1.affineCombination k p w1 = s2.affineCombination k p w2 →
Set.indicator (↑s1) w1 = Set.indicator (↑s2) w2 :=
by
classical
constructor
· intro ha s1 s2 w1 w2 hw1 hw2 heq
ext i
by_cases hi : i ∈ s1 ∪ s2
· rw [← sub_eq_zero]
rw [Set.sum_indicator_subset _ (Finset.subset_union_left s1 s2)] at hw1
rw [Set.sum_indicator_subset _ (Finset.subset_union_right s1 s2)] at hw2
have hws : (∑ i in s1 ∪ s2, (Set.indicator (↑s1) w1 - Set.indicator (↑s2) w2) i) = 0 := by
simp [hw1, hw2]
rw [Finset.affineCombination_indicator_subset _ _ (Finset.subset_union_left s1 s2),
Finset.affineCombination_indicator_subset _ _ (Finset.subset_union_right s1 s2), ←
@vsub_eq_zero_iff_eq V, Finset.affineCombination_vsub] at heq
exact ha (s1 ∪ s2) (Set.indicator (↑s1) w1 - Set.indicator (↑s2) w2) hws HEq i hi
· rw [← Finset.mem_coe, Finset.coe_union] at hi
simp [mt (Set.mem_union_left ↑s2) hi, mt (Set.mem_union_right ↑s1) hi]
· intro ha s w hw hs i0 hi0
let w1 : ι → k := Function.update (Function.const ι 0) i0 1
have hw1 : (∑ i in s, w1 i) = 1 := by
rw [Finset.sum_update_of_mem hi0, Finset.sum_const_zero, add_zero]
have hw1s : s.affine_combination k p w1 = p i0 :=
s.affine_combination_of_eq_one_of_eq_zero w1 p hi0 (Function.update_same _ _ _)
fun _ _ hne => Function.update_noteq hne _ _
let w2 := w + w1
have hw2 : (∑ i in s, w2 i) = 1 := by simp [w2, Finset.sum_add_distrib, hw, hw1]
have hw2s : s.affine_combination k p w2 = p i0 := by
simp [w2, ← Finset.weightedVsub_vadd_affineCombination, hs, hw1s]
replace ha := ha s s w2 w1 hw2 hw1 (hw1s.symm ▸ hw2s)
have hws : w2 i0 - w1 i0 = 0 := by
rw [← Finset.mem_coe] at hi0
rw [← Set.indicator_of_mem hi0 w2, ← Set.indicator_of_mem hi0 w1, ha, sub_self]
simpa [w2] using hws
#align affine_independent_iff_indicator_eq_of_affine_combination_eq affineIndependent_iff_indicator_eq_of_affineCombination_eq
/-- A finite family is affinely independent if and only if any affine
combinations (with sum of weights 1) that evaluate to the same point are equal. -/
theorem affineIndependent_iff_eq_of_fintype_affineCombination_eq [Fintype ι] (p : ι → P) :
AffineIndependent k p ↔
∀ w1 w2 : ι → k,
(∑ i, w1 i) = 1 →
(∑ i, w2 i) = 1 →
Finset.univ.affineCombination k p w1 = Finset.univ.affineCombination k p w2 → w1 = w2 :=
by
rw [affineIndependent_iff_indicator_eq_of_affineCombination_eq]
constructor
· intro h w1 w2 hw1 hw2 hweq
simpa only [Set.indicator_univ, Finset.coe_univ] using h _ _ w1 w2 hw1 hw2 hweq
· intro h s1 s2 w1 w2 hw1 hw2 hweq
have hw1' : (∑ i, (s1 : Set ι).indicator w1 i) = 1 := by
rwa [Set.sum_indicator_subset _ (Finset.subset_univ s1)] at hw1
have hw2' : (∑ i, (s2 : Set ι).indicator w2 i) = 1 := by
rwa [Set.sum_indicator_subset _ (Finset.subset_univ s2)] at hw2
rw [Finset.affineCombination_indicator_subset w1 p (Finset.subset_univ s1),
Finset.affineCombination_indicator_subset w2 p (Finset.subset_univ s2)] at hweq
exact h _ _ hw1' hw2' hweq
#align affine_independent_iff_eq_of_fintype_affine_combination_eq affineIndependent_iff_eq_of_fintype_affineCombination_eq
variable {k}
/-- If we single out one member of an affine-independent family of points and affinely transport
all others along the line joining them to this member, the resulting new family of points is affine-
independent.
This is the affine version of `linear_independent.units_smul`. -/
theorem AffineIndependent.units_lineMap {p : ι → P} (hp : AffineIndependent k p) (j : ι)
(w : ι → Units k) : AffineIndependent k fun i => AffineMap.lineMap (p j) (p i) (w i : k) :=
by
rw [affineIndependent_iff_linearIndependent_vsub k _ j] at hp⊢
simp only [AffineMap.lineMap_vsub_left, AffineMap.coe_const, AffineMap.lineMap_same]
exact hp.units_smul fun i => w i
#align affine_independent.units_line_map AffineIndependent.units_lineMap
theorem AffineIndependent.indicator_eq_of_affineCombination_eq {p : ι → P}
(ha : AffineIndependent k p) (s₁ s₂ : Finset ι) (w₁ w₂ : ι → k) (hw₁ : (∑ i in s₁, w₁ i) = 1)
(hw₂ : (∑ i in s₂, w₂ i) = 1) (h : s₁.affineCombination k p w₁ = s₂.affineCombination k p w₂) :
Set.indicator (↑s₁) w₁ = Set.indicator (↑s₂) w₂ :=
(affineIndependent_iff_indicator_eq_of_affineCombination_eq k p).1 ha s₁ s₂ w₁ w₂ hw₁ hw₂ h
#align affine_independent.indicator_eq_of_affine_combination_eq AffineIndependent.indicator_eq_of_affineCombination_eq
/-- An affinely independent family is injective, if the underlying
ring is nontrivial. -/
protected theorem AffineIndependent.injective [Nontrivial k] {p : ι → P}
(ha : AffineIndependent k p) : Function.Injective p :=
by
intro i j hij
rw [affineIndependent_iff_linearIndependent_vsub _ _ j] at ha
by_contra hij'
exact ha.ne_zero ⟨i, hij'⟩ (vsub_eq_zero_iff_eq.mpr hij)
#align affine_independent.injective AffineIndependent.injective
/-- If a family is affinely independent, so is any subfamily given by
composition of an embedding into index type with the original
family. -/
theorem AffineIndependent.comp_embedding {ι2 : Type _} (f : ι2 ↪ ι) {p : ι → P}
(ha : AffineIndependent k p) : AffineIndependent k (p ∘ f) := by
classical
intro fs w hw hs i0 hi0
let fs' := fs.map f
let w' i := if h : ∃ i2, f i2 = i then w h.some else 0
have hw' : ∀ i2 : ι2, w' (f i2) = w i2 := by
intro i2
have h : ∃ i : ι2, f i = f i2 := ⟨i2, rfl⟩
have hs : h.some = i2 := f.injective h.some_spec
simp_rw [w', dif_pos h, hs]
have hw's : (∑ i in fs', w' i) = 0 :=
by
rw [← hw, Finset.sum_map]
simp [hw']
have hs' : fs'.weighted_vsub p w' = (0 : V) :=
by
rw [← hs, Finset.weightedVsub_map]
congr with i
simp [hw']
rw [← ha fs' w' hw's hs' (f i0) ((Finset.mem_map' _).2 hi0), hw']
#align affine_independent.comp_embedding AffineIndependent.comp_embedding
/-- If a family is affinely independent, so is any subfamily indexed
by a subtype of the index type. -/
protected theorem AffineIndependent.subtype {p : ι → P} (ha : AffineIndependent k p) (s : Set ι) :
AffineIndependent k fun i : s => p i :=
ha.comp_embedding (Embedding.subtype _)
#align affine_independent.subtype AffineIndependent.subtype
/-- If an indexed family of points is affinely independent, so is the
corresponding set of points. -/
protected theorem AffineIndependent.range {p : ι → P} (ha : AffineIndependent k p) :
AffineIndependent k (fun x => x : Set.range p → P) :=
by
let f : Set.range p → ι := fun x => x.property.some
have hf : ∀ x, p (f x) = x := fun x => x.property.some_spec
let fe : Set.range p ↪ ι := ⟨f, fun x₁ x₂ he => Subtype.ext (hf x₁ ▸ hf x₂ ▸ he ▸ rfl)⟩
convert ha.comp_embedding fe
ext
simp [hf]
#align affine_independent.range AffineIndependent.range
theorem affineIndependent_equiv {ι' : Type _} (e : ι ≃ ι') {p : ι' → P} :
AffineIndependent k (p ∘ e) ↔ AffineIndependent k p :=
by
refine' ⟨_, AffineIndependent.comp_embedding e.to_embedding⟩
intro h
have : p = p ∘ e ∘ e.symm.to_embedding := by
ext
simp
rw [this]
exact h.comp_embedding e.symm.to_embedding
#align affine_independent_equiv affineIndependent_equiv
/-- If a set of points is affinely independent, so is any subset. -/
protected theorem AffineIndependent.mono {s t : Set P}
(ha : AffineIndependent k (fun x => x : t → P)) (hs : s ⊆ t) :
AffineIndependent k (fun x => x : s → P) :=
ha.comp_embedding (s.embeddingOfSubset t hs)
#align affine_independent.mono AffineIndependent.mono
/-- If the range of an injective indexed family of points is affinely
independent, so is that family. -/
theorem AffineIndependent.of_set_of_injective {p : ι → P}
(ha : AffineIndependent k (fun x => x : Set.range p → P)) (hi : Function.Injective p) :
AffineIndependent k p :=
ha.comp_embedding
(⟨fun i => ⟨p i, Set.mem_range_self _⟩, fun x y h => hi (Subtype.mk_eq_mk.1 h)⟩ :
ι ↪ Set.range p)
#align affine_independent.of_set_of_injective AffineIndependent.of_set_of_injective
section Composition
variable {V₂ P₂ : Type _} [AddCommGroup V₂] [Module k V₂] [affine_space V₂ P₂]
include V₂
/-- If the image of a family of points in affine space under an affine transformation is affine-
independent, then the original family of points is also affine-independent. -/
theorem AffineIndependent.of_comp {p : ι → P} (f : P →ᵃ[k] P₂) (hai : AffineIndependent k (f ∘ p)) :
AffineIndependent k p := by
cases' isEmpty_or_nonempty ι with h h;
· haveI := h
apply affineIndependent_of_subsingleton
obtain ⟨i⟩ := h
rw [affineIndependent_iff_linearIndependent_vsub k p i]
simp_rw [affineIndependent_iff_linearIndependent_vsub k (f ∘ p) i, Function.comp_apply, ←
f.linear_map_vsub] at hai
exact LinearIndependent.of_comp f.linear hai
#align affine_independent.of_comp AffineIndependent.of_comp
/-- The image of a family of points in affine space, under an injective affine transformation, is
affine-independent. -/
theorem AffineIndependent.map' {p : ι → P} (hai : AffineIndependent k p) (f : P →ᵃ[k] P₂)
(hf : Function.Injective f) : AffineIndependent k (f ∘ p) :=
by
cases' isEmpty_or_nonempty ι with h h
· haveI := h
apply affineIndependent_of_subsingleton
obtain ⟨i⟩ := h
rw [affineIndependent_iff_linearIndependent_vsub k p i] at hai
simp_rw [affineIndependent_iff_linearIndependent_vsub k (f ∘ p) i, Function.comp_apply, ←
f.linear_map_vsub]
have hf' : f.linear.ker = ⊥ := by rwa [LinearMap.ker_eq_bot, f.linear_injective_iff]
exact LinearIndependent.map' hai f.linear hf'
#align affine_independent.map' AffineIndependent.map'
/-- Injective affine maps preserve affine independence. -/
theorem AffineMap.affineIndependent_iff {p : ι → P} (f : P →ᵃ[k] P₂) (hf : Function.Injective f) :
AffineIndependent k (f ∘ p) ↔ AffineIndependent k p :=
⟨AffineIndependent.of_comp f, fun hai => AffineIndependent.map' hai f hf⟩
#align affine_map.affine_independent_iff AffineMap.affineIndependent_iff
/-- Affine equivalences preserve affine independence of families of points. -/
theorem AffineEquiv.affineIndependent_iff {p : ι → P} (e : P ≃ᵃ[k] P₂) :
AffineIndependent k (e ∘ p) ↔ AffineIndependent k p :=
e.toAffineMap.affineIndependent_iff e.toEquiv.Injective
#align affine_equiv.affine_independent_iff AffineEquiv.affineIndependent_iff
/-- Affine equivalences preserve affine independence of subsets. -/
theorem AffineEquiv.affineIndependent_set_of_eq_iff {s : Set P} (e : P ≃ᵃ[k] P₂) :
AffineIndependent k (coe : e '' s → P₂) ↔ AffineIndependent k (coe : s → P) :=
by
have : e ∘ (coe : s → P) = (coe : e '' s → P₂) ∘ (e : P ≃ P₂).image s := rfl
rw [← e.affine_independent_iff, this, affineIndependent_equiv]
#align affine_equiv.affine_independent_set_of_eq_iff AffineEquiv.affineIndependent_set_of_eq_iff
end Composition
/-- If a family is affinely independent, and the spans of points
indexed by two subsets of the index type have a point in common, those
subsets of the index type have an element in common, if the underlying
ring is nontrivial. -/
theorem AffineIndependent.exists_mem_inter_of_exists_mem_inter_affineSpan [Nontrivial k] {p : ι → P}
(ha : AffineIndependent k p) {s1 s2 : Set ι} {p0 : P} (hp0s1 : p0 ∈ affineSpan k (p '' s1))
(hp0s2 : p0 ∈ affineSpan k (p '' s2)) : ∃ i : ι, i ∈ s1 ∩ s2 :=
by
rw [Set.image_eq_range] at hp0s1 hp0s2
rw [mem_affineSpan_iff_eq_affineCombination, ←
Finset.eq_affineCombination_subset_iff_eq_affineCombination_subtype] at hp0s1 hp0s2
rcases hp0s1 with ⟨fs1, hfs1, w1, hw1, hp0s1⟩
rcases hp0s2 with ⟨fs2, hfs2, w2, hw2, hp0s2⟩
rw [affineIndependent_iff_indicator_eq_of_affineCombination_eq] at ha
replace ha := ha fs1 fs2 w1 w2 hw1 hw2 (hp0s1 ▸ hp0s2)
have hnz : (∑ i in fs1, w1 i) ≠ 0 := hw1.symm ▸ one_ne_zero
rcases Finset.exists_ne_zero_of_sum_ne_zero hnz with ⟨i, hifs1, hinz⟩
simp_rw [← Set.indicator_of_mem (Finset.mem_coe.2 hifs1) w1, ha] at hinz
use i, hfs1 hifs1, hfs2 (Set.mem_of_indicator_ne_zero hinz)
#align affine_independent.exists_mem_inter_of_exists_mem_inter_affine_span AffineIndependent.exists_mem_inter_of_exists_mem_inter_affineSpan
/-- If a family is affinely independent, the spans of points indexed
by disjoint subsets of the index type are disjoint, if the underlying
ring is nontrivial. -/
theorem AffineIndependent.affineSpan_disjoint_of_disjoint [Nontrivial k] {p : ι → P}
(ha : AffineIndependent k p) {s1 s2 : Set ι} (hd : Disjoint s1 s2) :
Disjoint (affineSpan k (p '' s1) : Set P) (affineSpan k (p '' s2)) :=
by
refine' Set.disjoint_left.2 fun p0 hp0s1 hp0s2 => _
cases' ha.exists_mem_inter_of_exists_mem_inter_affine_span hp0s1 hp0s2 with i hi
exact Set.disjoint_iff.1 hd hi
#align affine_independent.affine_span_disjoint_of_disjoint AffineIndependent.affineSpan_disjoint_of_disjoint
/-- If a family is affinely independent, a point in the family is in
the span of some of the points given by a subset of the index type if
and only if that point's index is in the subset, if the underlying
ring is nontrivial. -/
@[simp]
protected theorem AffineIndependent.mem_affineSpan_iff [Nontrivial k] {p : ι → P}
(ha : AffineIndependent k p) (i : ι) (s : Set ι) : p i ∈ affineSpan k (p '' s) ↔ i ∈ s :=
by
constructor
· intro hs
have h :=
AffineIndependent.exists_mem_inter_of_exists_mem_inter_affineSpan ha hs
(mem_affineSpan k (Set.mem_image_of_mem _ (Set.mem_singleton _)))
rwa [← Set.nonempty_def, Set.inter_singleton_nonempty] at h
· exact fun h => mem_affineSpan k (Set.mem_image_of_mem p h)
#align affine_independent.mem_affine_span_iff AffineIndependent.mem_affineSpan_iff
/-- If a family is affinely independent, a point in the family is not
in the affine span of the other points, if the underlying ring is
nontrivial. -/
theorem AffineIndependent.not_mem_affineSpan_diff [Nontrivial k] {p : ι → P}
(ha : AffineIndependent k p) (i : ι) (s : Set ι) : p i ∉ affineSpan k (p '' (s \ {i})) := by
simp [ha]
#align affine_independent.not_mem_affine_span_diff AffineIndependent.not_mem_affineSpan_diff
theorem exists_nontrivial_relation_sum_zero_of_not_affine_ind {t : Finset V}
(h : ¬AffineIndependent k (coe : t → V)) :
∃ f : V → k, (∑ e in t, f e • e) = 0 ∧ (∑ e in t, f e) = 0 ∧ ∃ x ∈ t, f x ≠ 0 := by
classical
rw [affineIndependent_iff_of_fintype] at h
simp only [exists_prop, not_forall] at h
obtain ⟨w, hw, hwt, i, hi⟩ := h
simp only [Finset.weightedVsub_eq_weightedVsubOfPoint_of_sum_eq_zero _ w (coe : t → V) hw 0,
vsub_eq_sub, Finset.weightedVsubOfPoint_apply, sub_zero] at hwt
let f : ∀ x : V, x ∈ t → k := fun x hx => w ⟨x, hx⟩
refine'
⟨fun x => if hx : x ∈ t then f x hx else (0 : k), _, _,
by
use i
simp [hi, f]⟩
suffices (∑ e : V in t, dite (e ∈ t) (fun hx => f e hx • e) fun hx => 0) = 0
by
convert this
ext
by_cases hx : x ∈ t <;> simp [hx]
all_goals
simp only [Finset.sum_dite_of_true fun x h => h, Subtype.val_eq_coe, Finset.mk_coe, f, hwt,
hw]
#align exists_nontrivial_relation_sum_zero_of_not_affine_ind exists_nontrivial_relation_sum_zero_of_not_affine_ind
/-- Viewing a module as an affine space modelled on itself, we can characterise affine independence
in terms of linear combinations. -/
theorem affineIndependent_iff {ι} {p : ι → V} :
AffineIndependent k p ↔
∀ (s : Finset ι) (w : ι → k), s.Sum w = 0 → (∑ e in s, w e • p e) = 0 → ∀ e ∈ s, w e = 0 :=
forall₃_congr fun s w hw => by simp [s.weighted_vsub_eq_linear_combination hw]
#align affine_independent_iff affineIndependent_iff
/-- Given an affinely independent family of points, a weighted subtraction lies in the
`vector_span` of two points given as affine combinations if and only if it is a weighted
subtraction with weights a multiple of the difference between the weights of the two points. -/
theorem weightedVsub_mem_vectorSpan_pair {p : ι → P} (h : AffineIndependent k p) {w w₁ w₂ : ι → k}
{s : Finset ι} (hw : (∑ i in s, w i) = 0) (hw₁ : (∑ i in s, w₁ i) = 1)
(hw₂ : (∑ i in s, w₂ i) = 1) :
s.weightedVsub p w ∈
vectorSpan k ({s.affineCombination k p w₁, s.affineCombination k p w₂} : Set P) ↔
∃ r : k, ∀ i ∈ s, w i = r * (w₁ i - w₂ i) :=
by
rw [mem_vectorSpan_pair]
refine' ⟨fun h => _, fun h => _⟩
· rcases h with ⟨r, hr⟩
refine' ⟨r, fun i hi => _⟩
rw [s.affine_combination_vsub, ← s.weighted_vsub_const_smul, ← sub_eq_zero, ← map_sub] at hr
have hw' : (∑ j in s, (r • (w₁ - w₂) - w) j) = 0 := by
simp_rw [Pi.sub_apply, Pi.smul_apply, Pi.sub_apply, smul_sub, Finset.sum_sub_distrib, ←
Finset.smul_sum, hw, hw₁, hw₂, sub_self]
have hr' := h s _ hw' hr i hi
rw [eq_comm, ← sub_eq_zero, ← smul_eq_mul]
exact hr'
· rcases h with ⟨r, hr⟩
refine' ⟨r, _⟩
let w' i := r * (w₁ i - w₂ i)
change ∀ i ∈ s, w i = w' i at hr
rw [s.weighted_vsub_congr hr fun _ _ => rfl, s.affine_combination_vsub, ←
s.weighted_vsub_const_smul]
congr
#align weighted_vsub_mem_vector_span_pair weightedVsub_mem_vectorSpan_pair
/-- Given an affinely independent family of points, an affine combination lies in the
span of two points given as affine combinations if and only if it is an affine combination
with weights those of one point plus a multiple of the difference between the weights of the
two points. -/
theorem affineCombination_mem_affineSpan_pair {p : ι → P} (h : AffineIndependent k p)
{w w₁ w₂ : ι → k} {s : Finset ι} (hw : (∑ i in s, w i) = 1) (hw₁ : (∑ i in s, w₁ i) = 1)
(hw₂ : (∑ i in s, w₂ i) = 1) :
s.affineCombination k p w ∈ line[k, s.affineCombination k p w₁, s.affineCombination k p w₂] ↔
∃ r : k, ∀ i ∈ s, w i = r * (w₂ i - w₁ i) + w₁ i :=
by
rw [← vsub_vadd (s.affine_combination k p w) (s.affine_combination k p w₁),
AffineSubspace.vadd_mem_iff_mem_direction _ (left_mem_affineSpan_pair _ _ _),
direction_affineSpan, s.affine_combination_vsub, Set.pair_comm,
weightedVsub_mem_vectorSpan_pair h _ hw₂ hw₁]
· simp only [Pi.sub_apply, sub_eq_iff_eq_add]
· simp_rw [Pi.sub_apply, Finset.sum_sub_distrib, hw, hw₁, sub_self]
#align affine_combination_mem_affine_span_pair affineCombination_mem_affineSpan_pair
end AffineIndependent
section DivisionRing
variable {k : Type _} {V : Type _} {P : Type _} [DivisionRing k] [AddCommGroup V] [Module k V]
variable [affine_space V P] {ι : Type _}
include V
/-- An affinely independent set of points can be extended to such a
set that spans the whole space. -/
theorem exists_subset_affineIndependent_affineSpan_eq_top {s : Set P}
(h : AffineIndependent k (fun p => p : s → P)) :
∃ t : Set P, s ⊆ t ∧ AffineIndependent k (fun p => p : t → P) ∧ affineSpan k t = ⊤ :=
by
rcases s.eq_empty_or_nonempty with (rfl | ⟨p₁, hp₁⟩)
· have p₁ : P := add_torsor.nonempty.some
let hsv := Basis.ofVectorSpace k V
have hsvi := hsv.linear_independent
have hsvt := hsv.span_eq
rw [Basis.coe_ofVectorSpace] at hsvi hsvt
have h0 : ∀ v : V, v ∈ Basis.ofVectorSpaceIndex _ _ → v ≠ 0 :=
by
intro v hv
simpa using hsv.ne_zero ⟨v, hv⟩
rw [linearIndependent_set_iff_affineIndependent_vadd_union_singleton k h0 p₁] at hsvi
exact
⟨{p₁} ∪ (fun v => v +ᵥ p₁) '' _, Set.empty_subset _, hsvi,
affineSpan_singleton_union_vadd_eq_top_of_span_eq_top p₁ hsvt⟩
· rw [affineIndependent_set_iff_linearIndependent_vsub k hp₁] at h
let bsv := Basis.extend h
have hsvi := bsv.linear_independent
have hsvt := bsv.span_eq
rw [Basis.coe_extend] at hsvi hsvt
have hsv := h.subset_extend (Set.subset_univ _)
have h0 : ∀ v : V, v ∈ h.extend _ → v ≠ 0 :=
by
intro v hv
simpa using bsv.ne_zero ⟨v, hv⟩
rw [linearIndependent_set_iff_affineIndependent_vadd_union_singleton k h0 p₁] at hsvi
refine' ⟨{p₁} ∪ (fun v => v +ᵥ p₁) '' h.extend (Set.subset_univ _), _, _⟩
· refine' Set.Subset.trans _ (Set.union_subset_union_right _ (Set.image_subset _ hsv))
simp [Set.image_image]
· use hsvi, affineSpan_singleton_union_vadd_eq_top_of_span_eq_top p₁ hsvt
#align exists_subset_affine_independent_affine_span_eq_top exists_subset_affineIndependent_affineSpan_eq_top
variable (k V)
/- ./././Mathport/Syntax/Translate/Basic.lean:635:2: warning: expanding binder collection (t «expr ⊆ » s) -/
theorem exists_affineIndependent (s : Set P) :
∃ (t : _)(_ : t ⊆ s), affineSpan k t = affineSpan k s ∧ AffineIndependent k (coe : t → P) :=
by
rcases s.eq_empty_or_nonempty with (rfl | ⟨p, hp⟩)
· exact ⟨∅, Set.empty_subset ∅, rfl, affineIndependent_of_subsingleton k _⟩
obtain ⟨b, hb₁, hb₂, hb₃⟩ := exists_linearIndependent k ((Equiv.vaddConst p).symm '' s)
have hb₀ : ∀ v : V, v ∈ b → v ≠ 0 := fun v hv => hb₃.ne_zero (⟨v, hv⟩ : b)
rw [linearIndependent_set_iff_affineIndependent_vadd_union_singleton k hb₀ p] at hb₃
refine' ⟨{p} ∪ Equiv.vaddConst p '' b, _, _, hb₃⟩
· apply Set.union_subset (set.singleton_subset_iff.mpr hp)
rwa [← (Equiv.vaddConst p).subset_image' b s]
· rw [Equiv.coe_vaddConst_symm, ← vectorSpan_eq_span_vsub_set_right k hp] at hb₂
apply AffineSubspace.ext_of_direction_eq
· have : Submodule.span k b = Submodule.span k (insert 0 b) := by simp
simp only [direction_affineSpan, ← hb₂, Equiv.coe_vaddConst, Set.singleton_union,
vectorSpan_eq_span_vsub_set_right k (Set.mem_insert p _), this]
congr
change (Equiv.vaddConst p).symm '' insert p (Equiv.vaddConst p '' b) = _
rw [Set.image_insert_eq, ← Set.image_comp]
simp
· use p
simp only [Equiv.coe_vaddConst, Set.singleton_union, Set.mem_inter_iff, coe_affineSpan]
exact ⟨mem_spanPoints k _ _ (Set.mem_insert p _), mem_spanPoints k _ _ hp⟩
#align exists_affine_independent exists_affineIndependent
variable (k) {V P}
/-- Two different points are affinely independent. -/
theorem affineIndependent_of_ne {p₁ p₂ : P} (h : p₁ ≠ p₂) : AffineIndependent k ![p₁, p₂] :=
by
rw [affineIndependent_iff_linearIndependent_vsub k ![p₁, p₂] 0]
let i₁ : { x // x ≠ (0 : Fin 2) } := ⟨1, by norm_num⟩
have he' : ∀ i, i = i₁ := by
rintro ⟨i, hi⟩
ext
fin_cases i
· simpa using hi
haveI : Unique { x // x ≠ (0 : Fin 2) } := ⟨⟨i₁⟩, he'⟩
have hz : (![p₁, p₂] ↑default -ᵥ ![p₁, p₂] 0 : V) ≠ 0 :=
by
rw [he' default]
simpa using h.symm
exact linearIndependent_unique _ hz
#align affine_independent_of_ne affineIndependent_of_ne
variable {k V P}
/-- If all but one point of a family are affinely independent, and that point does not lie in
the affine span of that family, the family is affinely independent. -/
theorem AffineIndependent.affineIndependent_of_not_mem_span {p : ι → P} {i : ι}
(ha : AffineIndependent k fun x : { y // y ≠ i } => p x)
(hi : p i ∉ affineSpan k (p '' { x | x ≠ i })) : AffineIndependent k p := by
classical
intro s w hw hs
let s' : Finset { y // y ≠ i } := s.subtype (· ≠ i)
let p' : { y // y ≠ i } → P := fun x => p x
by_cases his : i ∈ s ∧ w i ≠ 0
· refine' False.elim (hi _)
let wm : ι → k := -(w i)⁻¹ • w
have hms : s.weighted_vsub p wm = (0 : V) := by simp [wm, hs]
have hwm : (∑ i in s, wm i) = 0 := by simp [wm, ← Finset.mul_sum, hw]
have hwmi : wm i = -1 := by simp [wm, his.2]
let w' : { y // y ≠ i } → k := fun x => wm x
have hw' : (∑ x in s', w' x) = 1 :=
by
simp_rw [w', Finset.sum_subtype_eq_sum_filter]
rw [← s.sum_filter_add_sum_filter_not (· ≠ i)] at hwm
simp_rw [Classical.not_not, Finset.filter_eq', if_pos his.1, Finset.sum_singleton, ← wm,
hwmi, ← sub_eq_add_neg, sub_eq_zero] at hwm
exact hwm
rw [← s.affine_combination_eq_of_weighted_vsub_eq_zero_of_eq_neg_one hms his.1 hwmi, ←
(Subtype.range_coe : _ = { x | x ≠ i }), ← Set.range_comp, ←
s.affine_combination_subtype_eq_filter]
exact affineCombination_mem_affineSpan hw' p'
· rw [not_and_or, Classical.not_not] at his
let w' : { y // y ≠ i } → k := fun x => w x
have hw' : (∑ x in s', w' x) = 0 :=
by
simp_rw [Finset.sum_subtype_eq_sum_filter]
rw [Finset.sum_filter_of_ne, hw]
rintro x hxs hwx rfl
exact hwx (his.neg_resolve_left hxs)
have hs' : s'.weighted_vsub p' w' = (0 : V) :=
by
simp_rw [Finset.weightedVsub_subtype_eq_filter]
rw [Finset.weightedVsub_filter_of_ne, hs]
rintro x hxs hwx rfl
exact hwx (his.neg_resolve_left hxs)
intro j hj
by_cases hji : j = i
· rw [hji] at hj
exact hji.symm ▸ his.neg_resolve_left hj
· exact ha s' w' hw' hs' ⟨j, hji⟩ (Finset.mem_subtype.2 hj)
#align affine_independent.affine_independent_of_not_mem_span AffineIndependent.affineIndependent_of_not_mem_span
/-- If distinct points `p₁` and `p₂` lie in `s` but `p₃` does not, the three points are affinely
independent. -/
theorem affineIndependent_of_ne_of_mem_of_mem_of_not_mem {s : AffineSubspace k P} {p₁ p₂ p₃ : P}
(hp₁p₂ : p₁ ≠ p₂) (hp₁ : p₁ ∈ s) (hp₂ : p₂ ∈ s) (hp₃ : p₃ ∉ s) :
AffineIndependent k ![p₁, p₂, p₃] :=
by
have ha : AffineIndependent k fun x : { x : Fin 3 // x ≠ 2 } => ![p₁, p₂, p₃] x :=
by
rw [← affineIndependent_equiv (finSuccAboveEquiv (2 : Fin 3)).toEquiv]
convert affineIndependent_of_ne k hp₁p₂
ext x
fin_cases x <;> rfl
refine' ha.affine_independent_of_not_mem_span _
intro h
refine' hp₃ ((AffineSubspace.le_def' _ s).1 _ p₃ h)
simp_rw [affineSpan_le, Set.image_subset_iff, Set.subset_def, Set.mem_preimage]
intro x
fin_cases x <;> simp [hp₁, hp₂]
#align affine_independent_of_ne_of_mem_of_mem_of_not_mem affineIndependent_of_ne_of_mem_of_mem_of_not_mem
/-- If distinct points `p₁` and `p₃` lie in `s` but `p₂` does not, the three points are affinely
independent. -/
theorem affineIndependent_of_ne_of_mem_of_not_mem_of_mem {s : AffineSubspace k P} {p₁ p₂ p₃ : P}
(hp₁p₃ : p₁ ≠ p₃) (hp₁ : p₁ ∈ s) (hp₂ : p₂ ∉ s) (hp₃ : p₃ ∈ s) :
AffineIndependent k ![p₁, p₂, p₃] :=
by
rw [← affineIndependent_equiv (Equiv.swap (1 : Fin 3) 2)]
convert affineIndependent_of_ne_of_mem_of_mem_of_not_mem hp₁p₃ hp₁ hp₃ hp₂ using 1
ext x
fin_cases x <;> rfl
#align affine_independent_of_ne_of_mem_of_not_mem_of_mem affineIndependent_of_ne_of_mem_of_not_mem_of_mem
/-- If distinct points `p₂` and `p₃` lie in `s` but `p₁` does not, the three points are affinely
independent. -/
theorem affineIndependent_of_ne_of_not_mem_of_mem_of_mem {s : AffineSubspace k P} {p₁ p₂ p₃ : P}
(hp₂p₃ : p₂ ≠ p₃) (hp₁ : p₁ ∉ s) (hp₂ : p₂ ∈ s) (hp₃ : p₃ ∈ s) :
AffineIndependent k ![p₁, p₂, p₃] :=
by
rw [← affineIndependent_equiv (Equiv.swap (0 : Fin 3) 2)]
convert affineIndependent_of_ne_of_mem_of_mem_of_not_mem hp₂p₃.symm hp₃ hp₂ hp₁ using 1
ext x
fin_cases x <;> rfl
#align affine_independent_of_ne_of_not_mem_of_mem_of_mem affineIndependent_of_ne_of_not_mem_of_mem_of_mem
end DivisionRing
section Ordered
variable {k : Type _} {V : Type _} {P : Type _} [LinearOrderedRing k] [AddCommGroup V]
variable [Module k V] [affine_space V P] {ι : Type _}
include V
attribute [local instance] LinearOrderedRing.decidableLt
/-- Given an affinely independent family of points, suppose that an affine combination lies in
the span of two points given as affine combinations, and suppose that, for two indices, the
coefficients in the first point in the span are zero and those in the second point in the span
have the same sign. Then the coefficients in the combination lying in the span have the same
sign. -/
theorem sign_eq_of_affineCombination_mem_affineSpan_pair {p : ι → P} (h : AffineIndependent k p)
{w w₁ w₂ : ι → k} {s : Finset ι} (hw : (∑ i in s, w i) = 1) (hw₁ : (∑ i in s, w₁ i) = 1)
(hw₂ : (∑ i in s, w₂ i) = 1)
(hs :
s.affineCombination k p w ∈ line[k, s.affineCombination k p w₁, s.affineCombination k p w₂])
{i j : ι} (hi : i ∈ s) (hj : j ∈ s) (hi0 : w₁ i = 0) (hj0 : w₁ j = 0)
(hij : SignType.sign (w₂ i) = SignType.sign (w₂ j)) :
SignType.sign (w i) = SignType.sign (w j) :=
by
rw [affineCombination_mem_affineSpan_pair h hw hw₁ hw₂] at hs
rcases hs with ⟨r, hr⟩
dsimp only at hr
rw [hr i hi, hr j hj, hi0, hj0, add_zero, add_zero, sub_zero, sub_zero, sign_mul, sign_mul, hij]
#align sign_eq_of_affine_combination_mem_affine_span_pair sign_eq_of_affineCombination_mem_affineSpan_pair
/-- Given an affinely independent family of points, suppose that an affine combination lies in
the span of one point of that family and a combination of another two points of that family given
by `line_map` with coefficient between 0 and 1. Then the coefficients of those two points in the
combination lying in the span have the same sign. -/
theorem sign_eq_of_affineCombination_mem_affineSpan_single_lineMap {p : ι → P}
(h : AffineIndependent k p) {w : ι → k} {s : Finset ι} (hw : (∑ i in s, w i) = 1) {i₁ i₂ i₃ : ι}
(h₁ : i₁ ∈ s) (h₂ : i₂ ∈ s) (h₃ : i₃ ∈ s) (h₁₂ : i₁ ≠ i₂) (h₁₃ : i₁ ≠ i₃) (h₂₃ : i₂ ≠ i₃)
{c : k} (hc0 : 0 < c) (hc1 : c < 1)
(hs : s.affineCombination k p w ∈ line[k, p i₁, AffineMap.lineMap (p i₂) (p i₃) c]) :
SignType.sign (w i₂) = SignType.sign (w i₃) := by
classical
rw [← s.affine_combination_affine_combination_single_weights k p h₁, ←
s.affine_combination_affine_combination_line_map_weights p h₂ h₃ c] at hs
refine'
sign_eq_of_affineCombination_mem_affineSpan_pair h hw
(s.sum_affine_combination_single_weights k h₁)
(s.sum_affine_combination_line_map_weights h₂ h₃ c) hs h₂ h₃
(Finset.affineCombinationSingleWeights_apply_of_ne k h₁₂.symm)
(Finset.affineCombinationSingleWeights_apply_of_ne k h₁₃.symm) _
rw [Finset.affineCombinationLineMapWeights_apply_left h₂₃,
Finset.affineCombinationLineMapWeights_apply_right h₂₃]
simp [hc0, sub_pos.2 hc1]
#align sign_eq_of_affine_combination_mem_affine_span_single_line_map sign_eq_of_affineCombination_mem_affineSpan_single_lineMap
end Ordered
namespace Affine
variable (k : Type _) {V : Type _} (P : Type _) [Ring k] [AddCommGroup V] [Module k V]
variable [affine_space V P]
include V
/-- A `simplex k P n` is a collection of `n + 1` affinely
independent points. -/
structure Simplex (n : ℕ) where
points : Fin (n + 1) → P
Independent : AffineIndependent k points
#align affine.simplex Affine.Simplex
/-- A `triangle k P` is a collection of three affinely independent points. -/
abbrev Triangle :=
Simplex k P 2
#align affine.triangle Affine.Triangle
namespace Simplex
variable {P}
/-- Construct a 0-simplex from a point. -/
def mkOfPoint (p : P) : Simplex k P 0 :=
⟨fun _ => p, affineIndependent_of_subsingleton k _⟩
#align affine.simplex.mk_of_point Affine.Simplex.mkOfPoint
/-- The point in a simplex constructed with `mk_of_point`. -/
@[simp]
theorem mkOfPoint_points (p : P) (i : Fin 1) : (mkOfPoint k p).points i = p :=
rfl
#align affine.simplex.mk_of_point_points Affine.Simplex.mkOfPoint_points
instance [Inhabited P] : Inhabited (Simplex k P 0) :=
⟨mkOfPoint k default⟩
instance nonempty : Nonempty (Simplex k P 0) :=
⟨mkOfPoint k <| AddTorsor.nonempty.some⟩
#align affine.simplex.nonempty Affine.Simplex.nonempty
variable {k V}
/-- Two simplices are equal if they have the same points. -/
@[ext]
theorem ext {n : ℕ} {s1 s2 : Simplex k P n} (h : ∀ i, s1.points i = s2.points i) : s1 = s2 :=
by
cases s1
cases s2
congr with i
exact h i
#align affine.simplex.ext Affine.Simplex.ext
/-- Two simplices are equal if and only if they have the same points. -/
theorem ext_iff {n : ℕ} (s1 s2 : Simplex k P n) : s1 = s2 ↔ ∀ i, s1.points i = s2.points i :=
⟨fun h _ => h ▸ rfl, ext⟩
#align affine.simplex.ext_iff Affine.Simplex.ext_iff
/-- A face of a simplex is a simplex with the given subset of
points. -/
def face {n : ℕ} (s : Simplex k P n) {fs : Finset (Fin (n + 1))} {m : ℕ} (h : fs.card = m + 1) :
Simplex k P m :=
⟨s.points ∘ fs.orderEmbOfFin h, s.Independent.comp_embedding (fs.orderEmbOfFin h).toEmbedding⟩
#align affine.simplex.face Affine.Simplex.face
/-- The points of a face of a simplex are given by `mono_of_fin`. -/
theorem face_points {n : ℕ} (s : Simplex k P n) {fs : Finset (Fin (n + 1))} {m : ℕ}
(h : fs.card = m + 1) (i : Fin (m + 1)) :
(s.face h).points i = s.points (fs.orderEmbOfFin h i) :=
rfl
#align affine.simplex.face_points Affine.Simplex.face_points
/-- The points of a face of a simplex are given by `mono_of_fin`. -/
theorem face_points' {n : ℕ} (s : Simplex k P n) {fs : Finset (Fin (n + 1))} {m : ℕ}
(h : fs.card = m + 1) : (s.face h).points = s.points ∘ fs.orderEmbOfFin h :=
rfl
#align affine.simplex.face_points' Affine.Simplex.face_points'
/-- A single-point face equals the 0-simplex constructed with
`mk_of_point`. -/
@[simp]
theorem face_eq_mkOfPoint {n : ℕ} (s : Simplex k P n) (i : Fin (n + 1)) :
s.face (Finset.card_singleton i) = mkOfPoint k (s.points i) :=
by
ext
simp [face_points]
#align affine.simplex.face_eq_mk_of_point Affine.Simplex.face_eq_mkOfPoint
/-- The set of points of a face. -/
@[simp]
theorem range_face_points {n : ℕ} (s : Simplex k P n) {fs : Finset (Fin (n + 1))} {m : ℕ}
(h : fs.card = m + 1) : Set.range (s.face h).points = s.points '' ↑fs := by
rw [face_points', Set.range_comp, Finset.range_orderEmbOfFin]
#align affine.simplex.range_face_points Affine.Simplex.range_face_points
/-- Remap a simplex along an `equiv` of index types. -/
@[simps]
def reindex {m n : ℕ} (s : Simplex k P m) (e : Fin (m + 1) ≃ Fin (n + 1)) : Simplex k P n :=
⟨s.points ∘ e.symm, (affineIndependent_equiv e.symm).2 s.Independent⟩
#align affine.simplex.reindex Affine.Simplex.reindex
/-- Reindexing by `equiv.refl` yields the original simplex. -/
@[simp]
theorem reindex_refl {n : ℕ} (s : Simplex k P n) : s.reindex (Equiv.refl (Fin (n + 1))) = s :=
ext fun _ => rfl
#align affine.simplex.reindex_refl Affine.Simplex.reindex_refl
/-- Reindexing by the composition of two equivalences is the same as reindexing twice. -/
@[simp]
theorem reindex_trans {n₁ n₂ n₃ : ℕ} (e₁₂ : Fin (n₁ + 1) ≃ Fin (n₂ + 1))
(e₂₃ : Fin (n₂ + 1) ≃ Fin (n₃ + 1)) (s : Simplex k P n₁) :
s.reindex (e₁₂.trans e₂₃) = (s.reindex e₁₂).reindex e₂₃ :=
rfl
#align affine.simplex.reindex_trans Affine.Simplex.reindex_trans
/-- Reindexing by an equivalence and its inverse yields the original simplex. -/
@[simp]
theorem reindex_reindex_symm {m n : ℕ} (s : Simplex k P m) (e : Fin (m + 1) ≃ Fin (n + 1)) :
(s.reindex e).reindex e.symm = s := by rw [← reindex_trans, Equiv.self_trans_symm, reindex_refl]
#align affine.simplex.reindex_reindex_symm Affine.Simplex.reindex_reindex_symm
/-- Reindexing by the inverse of an equivalence and that equivalence yields the original simplex. -/
@[simp]
theorem reindex_symm_reindex {m n : ℕ} (s : Simplex k P m) (e : Fin (n + 1) ≃ Fin (m + 1)) :
(s.reindex e.symm).reindex e = s := by rw [← reindex_trans, Equiv.symm_trans_self, reindex_refl]
#align affine.simplex.reindex_symm_reindex Affine.Simplex.reindex_symm_reindex
/-- Reindexing a simplex produces one with the same set of points. -/
@[simp]
theorem reindex_range_points {m n : ℕ} (s : Simplex k P m) (e : Fin (m + 1) ≃ Fin (n + 1)) :
Set.range (s.reindex e).points = Set.range s.points := by
rw [reindex, Set.range_comp, Equiv.range_eq_univ, Set.image_univ]
#align affine.simplex.reindex_range_points Affine.Simplex.reindex_range_points
end Simplex
end Affine
namespace Affine
namespace Simplex
variable {k : Type _} {V : Type _} {P : Type _} [DivisionRing k] [AddCommGroup V] [Module k V]
[affine_space V P]
include V
/-- The centroid of a face of a simplex as the centroid of a subset of
the points. -/
@[simp]
theorem face_centroid_eq_centroid {n : ℕ} (s : Simplex k P n) {fs : Finset (Fin (n + 1))} {m : ℕ}
(h : fs.card = m + 1) : Finset.univ.centroid k (s.face h).points = fs.centroid k s.points :=
by
convert(finset.univ.centroid_map k (fs.order_emb_of_fin h).toEmbedding s.points).symm
rw [← Finset.coe_inj, Finset.coe_map, Finset.coe_univ, Set.image_univ]
simp
#align affine.simplex.face_centroid_eq_centroid Affine.Simplex.face_centroid_eq_centroid
/-- Over a characteristic-zero division ring, the centroids given by
two subsets of the points of a simplex are equal if and only if those
faces are given by the same subset of points. -/
@[simp]
theorem centroid_eq_iff [CharZero k] {n : ℕ} (s : Simplex k P n) {fs₁ fs₂ : Finset (Fin (n + 1))}
{m₁ m₂ : ℕ} (h₁ : fs₁.card = m₁ + 1) (h₂ : fs₂.card = m₂ + 1) :
fs₁.centroid k s.points = fs₂.centroid k s.points ↔ fs₁ = fs₂ :=
by
refine' ⟨fun h => _, congr_arg _⟩
rw [Finset.centroid_eq_affineCombination_fintype, Finset.centroid_eq_affineCombination_fintype] at
h
have ha :=
(affineIndependent_iff_indicator_eq_of_affineCombination_eq k s.points).1 s.independent _ _ _ _
(fs₁.sum_centroid_weights_indicator_eq_one_of_card_eq_add_one k h₁)
(fs₂.sum_centroid_weights_indicator_eq_one_of_card_eq_add_one k h₂) h
simp_rw [Finset.coe_univ, Set.indicator_univ, Function.funext_iff,
Finset.centroidWeightsIndicator_def, Finset.centroidWeights, h₁, h₂] at ha
ext i
specialize ha i
have key : ∀ n : ℕ, (n : k) + 1 ≠ 0 := fun n h => by norm_cast at h
-- we should be able to golf this to `refine ⟨λ hi, decidable.by_contradiction (λ hni, _), ...⟩`,
-- but for some unknown reason it doesn't work.
constructor <;>
intro hi <;>
by_contra hni
· simpa [hni, hi, key] using ha
· simpa [hni, hi, key] using ha.symm
#align affine.simplex.centroid_eq_iff Affine.Simplex.centroid_eq_iff
/-- Over a characteristic-zero division ring, the centroids of two
faces of a simplex are equal if and only if those faces are given by
the same subset of points. -/
theorem face_centroid_eq_iff [CharZero k] {n : ℕ} (s : Simplex k P n)
{fs₁ fs₂ : Finset (Fin (n + 1))} {m₁ m₂ : ℕ} (h₁ : fs₁.card = m₁ + 1) (h₂ : fs₂.card = m₂ + 1) :
Finset.univ.centroid k (s.face h₁).points = Finset.univ.centroid k (s.face h₂).points ↔
fs₁ = fs₂ :=
by
rw [face_centroid_eq_centroid, face_centroid_eq_centroid]
exact s.centroid_eq_iff h₁ h₂
#align affine.simplex.face_centroid_eq_iff Affine.Simplex.face_centroid_eq_iff
/-- Two simplices with the same points have the same centroid. -/
theorem centroid_eq_of_range_eq {n : ℕ} {s₁ s₂ : Simplex k P n}
(h : Set.range s₁.points = Set.range s₂.points) :
Finset.univ.centroid k s₁.points = Finset.univ.centroid k s₂.points :=
by
rw [← Set.image_univ, ← Set.image_univ, ← Finset.coe_univ] at h
exact
finset.univ.centroid_eq_of_inj_on_of_image_eq k _
(fun _ _ _ _ he => AffineIndependent.injective s₁.independent he)
(fun _ _ _ _ he => AffineIndependent.injective s₂.independent he) h
#align affine.simplex.centroid_eq_of_range_eq Affine.Simplex.centroid_eq_of_range_eq
end Simplex
end Affine
|
using Transits
using Limbdark
using LaTeXStrings
using BenchmarkTools
using DataFrames
using Statistics
using StatsPlots, ColorSchemes
using ProgressLogging
N_pts = [100, 316, 1000, 3160, 10000, 31600, 100000]
N_us = [1 2 3 5 8 13 21 34 55 90 144]
function benchmark(N_u, N_pts; r=0.1)
u = ones(N_u) ./ N_u
b = [sqrt(((i - N_pts/2) * 2/N_pts * (1 + 2 * r))^2) for i in 1:N_pts]
ld = PolynomialLimbDark(u)
output = similar(b)
bench = @benchmark begin
@inbounds for i in eachindex($b)
$output[i] = compute($ld, $b[i], $r)
end
end
return median(bench).time * 1e-9
end
vals = zeros(length(N_pts), length(N_us))
@progress for (j, Nu) in enumerate(N_us)
@progress for (i, N) in enumerate(N_pts)
vals[i, j] = benchmark(Nu, N)
end
end
labels = reduce(hcat, "uₙ: $N" for N in N_us)
plot(
N_pts,
vals,
scale=:log10,
ls=:solid,
m=:o,
palette=palette(:plasma, length(N_us) + 2),
msw=0,
lab=labels,
xlabel="number of points",
ylabel="timing [s]",
leg=:topleft
)
function benchmark_limbdark(N_u, N_pts; r=0.1)
u = ones(N_u) ./ N_u
b = [sqrt(((i - N_pts/2) * 2/N_pts * (1 + 2 * r))^2) for i in 1:N_pts]
trans = Limbdark.transit_init(r, b[1], u, true)
output = similar(b)
bench = @benchmark begin
@inbounds for i in eachindex($b)
$trans.b = $b[i]
$output[i] = Limbdark.transit_poly!($trans)
end
end
return median(bench).time * 1e-9
end
vals_limbdark = zeros(length(N_pts), length(N_us))
@progress for (j, Nu) in enumerate(N_us)
@progress for (i, N) in enumerate(N_pts)
vals_limbdark[i, j] = benchmark_limbdark(Nu, N)
end
end
plot(
N_pts,
vals_limbdark ./ vals,
xscale=:log10,
ls=:solid,
m=:o,
msw=0,
palette=palette(:plasma, length(N_us) + 2),
lab=labels,
xlabel="number of points",
ylabel="relative speedup (times faster) - Limbdark.jl"
)
tmed = median(vals ./ vals[:, 1], dims=1)
plot(
N_us |> vec,
tmed |> vec,
scale=:log10,
ls=:solid,
m=:o,
msw=0,
lab="Transits.jl",
xlabel="number of limb-darkening coefficients",
ylabel="relative timing",
ylims=(0.8, 10),
leg=:topleft
)
plot!(
N_us |> vec,
median(vals_limbdark ./ vals_limbdark[:, 1], dims=1) |> vec,
lab="Limbdark.jl",
c=2,
ls=:solid,
m=:o,
msw=0
)
plot!(N_us |> vec, n -> n^(0.2), ls=:dash, c=:gray, lab=L"N^{0.2}")
plot!(N_us |> vec, n -> tmed[end] * n / N_us[1, end], ls=:dash, c=:gray, lab=L"N^1")
|
install.packages("readr")
install.packages("caret")
install.packages("quanteda")
install.packages("tm")
install.packages("NLP")
install.packages("dplyr")
install.packages("magrittr")
install.packages("stringi")
install.packages("testcat")
install.packages("psych")
install.packages("ggplot2")
install.packages("tidytext")
install.packages("topicmodels")
install.packages("lattice")
install.packages("h2o")
|
State Before: ι : Type ?u.20611
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁ π₂ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
⊢ Henstock ≤ McShane State After: no goals Tactic: trivial |
{-# OPTIONS --without-K --rewriting #-}
open import lib.Basics
open import lib.NConnected
open import lib.NType2
open import lib.types.Span
open import lib.types.Pointed
open import lib.types.Pushout
open import lib.types.PushoutFlip
open import lib.types.PushoutFmap
open import lib.types.PushoutFlattening
open import lib.types.Unit
open import lib.types.Paths
open import lib.types.Truncation
open import lib.types.Lift
open import lib.cubical.Square
-- Suspension is defined as a particular case of pushout
module lib.types.Suspension where
module _ {i} (A : Type i) where
susp-span : Span
susp-span = span Unit Unit A (λ _ → tt) (λ _ → tt)
Susp : Type i
Susp = Pushout susp-span
-- [north'] and [south'] explictly ask for [A]
north' : Susp
north' = left tt
south' : Susp
south' = right tt
module _ {i} {A : Type i} where
north : Susp A
north = north' A
south : Susp A
south = south' A
merid : A → north == south
merid x = glue x
module SuspElim {j} {P : Susp A → Type j} (n : P north)
(s : P south) (p : (x : A) → n == s [ P ↓ merid x ]) where
open module P = PushoutElim (λ _ → n) (λ _ → s) p
public using (f) renaming (glue-β to merid-β)
open SuspElim public using () renaming (f to Susp-elim)
module SuspRec {j} {C : Type j} (n s : C) (p : A → n == s) where
open module P = PushoutRec {d = susp-span A} (λ _ → n) (λ _ → s) p
public using (f) renaming (glue-β to merid-β)
open SuspRec public using () renaming (f to Susp-rec)
module SuspRecType {j} (n s : Type j) (p : A → n ≃ s)
= PushoutRecType {d = susp-span A} (λ _ → n) (λ _ → s) p
susp-⊙span : ∀ {i} → Ptd i → ⊙Span
susp-⊙span X =
⊙span ⊙Unit ⊙Unit X (⊙cst {X = X}) (⊙cst {X = X})
⊙Susp : ∀ {i} → Ptd i → Ptd i
⊙Susp ⊙[ A , _ ] = ⊙[ Susp A , north ]
σloop : ∀ {i} (X : Ptd i) → de⊙ X → north' (de⊙ X) == north' (de⊙ X)
σloop ⊙[ _ , x₀ ] x = merid x ∙ ! (merid x₀)
σloop-pt : ∀ {i} {X : Ptd i} → σloop X (pt X) == idp
σloop-pt {X = ⊙[ _ , x₀ ]} = !-inv-r (merid x₀)
⊙σloop : ∀ {i} (X : Ptd i) → X ⊙→ ⊙[ north' (de⊙ X) == north' (de⊙ X) , idp ]
⊙σloop X = σloop X , σloop-pt
module SuspFlip {i} {A : Type i} = SuspRec
(south' A) north (! ∘ merid)
Susp-flip : ∀ {i} {A : Type i} → Susp A → Susp A
Susp-flip = SuspFlip.f
⊙Susp-flip : ∀ {i} (X : Ptd i) → ⊙Susp X ⊙→ ⊙Susp X
⊙Susp-flip X = (Susp-flip , ! (merid (pt X)))
Susp-flip-equiv : ∀ {i} {A : Type i} → Susp A ≃ Susp A
Susp-flip-equiv {A = A} = Pushout-flip-equiv (susp-span A)
module _ {i j} where
module SuspFmap {A : Type i} {B : Type j} (f : A → B) =
SuspRec north south (merid ∘ f)
Susp-fmap : {A : Type i} {B : Type j} (f : A → B)
→ (Susp A → Susp B)
Susp-fmap = SuspFmap.f
⊙Susp-fmap : {X : Ptd i} {Y : Ptd j} (f : X ⊙→ Y)
→ ⊙Susp X ⊙→ ⊙Susp Y
⊙Susp-fmap (f , fpt) = (Susp-fmap f , idp)
module _ {i} where
Susp-fmap-idf : (A : Type i) → ∀ a → Susp-fmap (idf A) a == a
Susp-fmap-idf A = Susp-elim idp idp $ λ a →
↓-='-in' (ap-idf (merid a) ∙ ! (SuspFmap.merid-β (idf A) a))
⊙Susp-fmap-idf : (X : Ptd i)
→ ⊙Susp-fmap (⊙idf X) == ⊙idf (⊙Susp X)
⊙Susp-fmap-idf X = ⊙λ=' (Susp-fmap-idf (de⊙ X)) idp
module _ {i j} where
Susp-fmap-cst : {A : Type i} {B : Type j} (b : B)
(a : Susp A) → Susp-fmap (cst b) a == north
Susp-fmap-cst b = Susp-elim idp (! (merid b)) $ (λ a →
↓-app=cst-from-square $ SuspFmap.merid-β (cst b) a ∙v⊡ tr-square _)
⊙Susp-fmap-cst : {X : Ptd i} {Y : Ptd j}
→ ⊙Susp-fmap (⊙cst {X = X} {Y = Y}) == ⊙cst
⊙Susp-fmap-cst = ⊙λ=' (Susp-fmap-cst _) idp
Susp-flip-fmap : {A : Type i} {B : Type j} (f : A → B)
→ ∀ σ → Susp-flip (Susp-fmap f σ) == Susp-fmap f (Susp-flip σ)
Susp-flip-fmap f = Susp-elim idp idp $ λ y → ↓-='-in' $
ap-∘ (Susp-fmap f) Susp-flip (merid y)
∙ ap (ap (Susp-fmap f)) (SuspFlip.merid-β y)
∙ ap-! (Susp-fmap f) (merid y)
∙ ap ! (SuspFmap.merid-β f y)
∙ ! (SuspFlip.merid-β (f y))
∙ ! (ap (ap Susp-flip) (SuspFmap.merid-β f y))
∙ ∘-ap Susp-flip (Susp-fmap f) (merid y)
module _ {i j k} where
Susp-fmap-∘ : {A : Type i} {B : Type j} {C : Type k} (g : B → C) (f : A → B)
(σ : Susp A) → Susp-fmap (g ∘ f) σ == Susp-fmap g (Susp-fmap f σ)
Susp-fmap-∘ g f = Susp-elim
idp
idp
(λ a → ↓-='-in' $
ap-∘ (Susp-fmap g) (Susp-fmap f) (merid a)
∙ ap (ap (Susp-fmap g)) (SuspFmap.merid-β f a)
∙ SuspFmap.merid-β g (f a)
∙ ! (SuspFmap.merid-β (g ∘ f) a))
⊙Susp-fmap-∘ : {X : Ptd i} {Y : Ptd j} {Z : Ptd k}
(g : Y ⊙→ Z) (f : X ⊙→ Y)
→ ⊙Susp-fmap (g ⊙∘ f) == ⊙Susp-fmap g ⊙∘ ⊙Susp-fmap f
⊙Susp-fmap-∘ g f = ⊙λ=' (Susp-fmap-∘ (fst g) (fst f)) idp
{- Extract the 'glue component' of a pushout -}
module _ {i j k} {s : Span {i} {j} {k}} where
module ExtractGlue = PushoutRec {d = s} {D = Susp (Span.C s)}
(λ _ → north) (λ _ → south) merid
extract-glue = ExtractGlue.f
module _ {x₀ : Span.A s} where
⊙extract-glue : ⊙[ Pushout s , left x₀ ] ⊙→ ⊙[ Susp (Span.C s) , north ]
⊙extract-glue = extract-glue , idp
module _ {i j} {A : Type i} {B : Type j} (eq : A ≃ B) where
susp-span-emap : SpanEquiv (susp-span A) (susp-span B)
susp-span-emap = ( span-map (idf _) (idf _) (fst eq) (comm-sqr λ _ → idp) (comm-sqr λ _ → idp)
, idf-is-equiv _ , idf-is-equiv _ , snd eq)
Susp-emap : Susp A ≃ Susp B
Susp-emap = Pushout-emap susp-span-emap
private
-- This is to make sure that we did not screw up [Susp-emap].
test₀ : fst Susp-emap == Susp-fmap (fst eq)
test₀ = idp
module _ {i j} {X : Ptd i} {Y : Ptd j} where
⊙Susp-emap : X ⊙≃ Y → ⊙Susp X ⊙≃ ⊙Susp Y
⊙Susp-emap ⊙eq = ≃-to-⊙≃ (Susp-emap (⊙≃-to-≃ ⊙eq)) idp
{- Interaction with [Lift] -}
module _ {i j} (X : Type i) where
Susp-Lift-econv : Susp (Lift {j = j} X) ≃ Lift {j = j} (Susp X)
Susp-Lift-econv = lift-equiv ∘e Susp-emap lower-equiv
Susp-Lift-conv : Susp (Lift {j = j} X) == Lift {j = j} (Susp X)
Susp-Lift-conv = ua Susp-Lift-econv
module _ {i j} (X : Ptd i) where
⊙Susp-Lift-econv : ⊙Susp (⊙Lift {j = j} X) ⊙≃ ⊙Lift {j = j} (⊙Susp X)
⊙Susp-Lift-econv = ⊙lift-equiv {j = j} ⊙∘e ⊙Susp-emap {X = ⊙Lift {j = j} X} {Y = X} ⊙lower-equiv
⊙Susp-Lift-conv : ⊙Susp (⊙Lift {j = j} X) == ⊙Lift {j = j} (⊙Susp X)
⊙Susp-Lift-conv = ⊙ua ⊙Susp-Lift-econv
{- Suspension of an n-connected space is n+1-connected -}
abstract
Susp-conn : ∀ {i} {A : Type i} {n : ℕ₋₂}
→ is-connected n A → is-connected (S n) (Susp A)
Susp-conn {A = A} {n = n} cA = has-level-in
([ north ] ,
Trunc-elim
(Susp-elim
idp
(Trunc-rec (λ a → ap [_] (merid a))
(contr-center cA))
(λ x → Trunc-elim
{P = λ y → idp ==
Trunc-rec (λ a → ap [_] (merid a)) y
[ (λ z → [ north ] == [ z ]) ↓ (merid x) ]}
{{λ _ → ↓-preserves-level ⟨⟩}}
(λ x' → ↓-cst=app-in (∙'-unit-l _ ∙ mers-eq n x x'))
(contr-center cA))))
where
instance _ = cA
mers-eq : ∀ {i} {A : Type i} (n : ℕ₋₂)
{{_ : is-connected n A}} → (x x' : A)
→ ap ([_] {n = S n}) (merid x)
== Trunc-rec {{has-level-apply (Trunc-level {n = S n}) _ _}} (λ a → ap [_] (merid a)) [ x' ]
mers-eq ⟨-2⟩ x x' = contr-has-all-paths _ _
mers-eq {A = A} (S n) x x' =
conn-extend (pointed-conn-out A x)
(λ y → ((ap [_] (merid x) == ap [_] (merid y)) ,
has-level-apply (has-level-apply (Trunc-level {n = S (S n)}) _ _) _ _))
(λ _ → idp) x'
|
There were 27 fatal accidents involving GA aircraft in 2007 , resulting in the loss of 48 lives . These compare with 16 accidents claiming a total of 19 lives the previous year , and although the 2007 statistics are higher than average , they are not exceptional .
|
import Aesop
import Mathlib.Data.Nat.Basic
import Mathlib.Algebra.Group.Basic
/-!
# `Aesop` demo
This file demonstrates some of the out-of-the-box
capabilities of the `Aesop` automation tool for `Lean4`.
The focus is on theorems that `Aesop` can directly prove
without any additional configuration.
-/
section PropositionalLogic
/-!
## Propositional logic using `Aesop`
`Aesop` can prove routine theorems in
propositional logic automatically.
-/
variable (P Q R : Prop)
example : P → P := by aesop
example : P → (Q → P) := by aesop
example : P ∧ Q → P ∨ Q := by aesop
example : P ∨ P ↔ P ∧ P := by aesop
example : (P → Q) → (¬Q → ¬P) := by aesop
example : (P ∨ Q) ↔ (Q ∨ P) := by aesop
example : (P ∧ Q) → R ↔ P → (Q → R) := by aesop
example : (P → (Q → R)) → ((P → R) → (P → R)) := by aesop
end PropositionalLogic
section TrivialLemmas
/-!
## Proving trivial lemmas with `Aesop`
`Aesop` uses Lean's simplifier internally, which
allows it to prove trivial lemmas by simplification.
-/
example {a b : ℕ} (h₁ : a = 5) (h₂ : b = 2 + 3) : a = b :=
by aesop
example {a : ℕ} : a + 0 = 0 → a = 0 + 0 := by aesop
example {G : Type} [Group G] {g : G} : 1⁻¹ * 1 = g * 1 * g⁻¹ :=
by aesop
example : [1, 2, 3] ≠ [] := by aesop
example {l : List α} {a : α} : a ∈ l → l ≠ [] := by aesop
end TrivialLemmas
/-
section TermConstruction
/-!
## Constructing terms of types
Just as `Aesop` can produce proofs of some propositions,
it can construct terms of some types.
-/
variable (A B C : Type _)
-- the identity function
example : A → A := by aesop
-- projection onto the first coordinate
example : A → B → A := by aesop
-- formally similar to the adjoint of a linear transformation
example : (A → B) → ((B → C) → (A → C)) := by aesop
-- formally similar to the differential map between tangent spaces of manifolds
example (f : A → B) : ((A → C) → C) → ((B → C) → C) := by aesop
end TermConstruction
-/ |
[STATEMENT]
lemma (in Max_test)
shows
"\<Gamma>\<turnstile> {\<sigma>} \<acute>k :== CALL Max(LEQ_'proc,\<acute>n,\<acute>m) \<lbrace>\<acute>k = mx (\<le>) \<^bsup>\<sigma>\<^esup>n \<^bsup>\<sigma>\<^esup>m\<rbrace>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<Gamma>\<turnstile> {\<sigma>} \<acute>k :== CALL Max(LEQ_'proc,\<acute>n,\<acute>m) \<lbrace>\<acute>k = mx (\<le>) \<^bsup>\<sigma>\<^esup>n \<^bsup>\<sigma>\<^esup>m\<rbrace>
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<Gamma>\<turnstile> {\<sigma>} \<acute>k :== CALL Max(LEQ_'proc,\<acute>n,\<acute>m) \<lbrace>\<acute>k = mx (\<le>) \<^bsup>\<sigma>\<^esup>n \<^bsup>\<sigma>\<^esup>m\<rbrace>
[PROOF STEP]
note Max_spec = Max_spec [where leq="(\<le>)"]
[PROOF STATE]
proof (state)
this:
\<forall>\<sigma>. \<Gamma>\<turnstile> ({\<sigma>} \<inter> \<lbrace>(\<forall>\<tau>. \<Gamma>\<turnstile> {\<tau>} Call \<acute>compare {s. \<^bsup>s\<^esup>b = (\<^bsup>\<tau>\<^esup>n \<le> \<^bsup>\<tau>\<^esup>m)}) \<and> (\<forall>\<tau>. \<Gamma>\<turnstile> {\<tau>} Call \<acute>compare {t. t may_not_modify_globals \<tau>})\<rbrace>) \<acute>k :== PROC Max(\<acute>compare,\<acute>n,\<acute>m) \<lbrace>\<acute>k = mx (\<le>) \<^bsup>\<sigma>\<^esup>n \<^bsup>\<sigma>\<^esup>m\<rbrace>
goal (1 subgoal):
1. \<Gamma>\<turnstile> {\<sigma>} \<acute>k :== CALL Max(LEQ_'proc,\<acute>n,\<acute>m) \<lbrace>\<acute>k = mx (\<le>) \<^bsup>\<sigma>\<^esup>n \<^bsup>\<sigma>\<^esup>m\<rbrace>
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<Gamma>\<turnstile> {\<sigma>} \<acute>k :== CALL Max(LEQ_'proc,\<acute>n,\<acute>m) \<lbrace>\<acute>k = mx (\<le>) \<^bsup>\<sigma>\<^esup>n \<^bsup>\<sigma>\<^esup>m\<rbrace>
[PROOF STEP]
apply vcg
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>n m. (\<forall>\<tau>. \<Gamma>\<turnstile> (Collect ((=) \<tau>)) \<acute>b :== PROC LEQ(\<acute>n,\<acute>m) \<lbrace>\<acute>b = (\<^bsup>\<tau>\<^esup>n \<le> \<^bsup>\<tau>\<^esup>m)\<rbrace>) \<and> (\<forall>\<tau>. \<Gamma>\<turnstile> (Collect ((=) \<tau>)) \<acute>b :== PROC LEQ(\<acute>n,\<acute>m) {t. t may_not_modify_globals \<tau>}) \<and> (\<forall>k. k = mx (\<le>) n m \<longrightarrow> mx (\<le>) n m = mx (\<le>) n m)
[PROOF STEP]
apply (clarsimp)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<forall>\<tau>. \<Gamma>\<turnstile> {\<tau>} \<acute>b :== PROC LEQ(\<acute>n,\<acute>m) \<lbrace>\<acute>b = (\<^bsup>\<tau>\<^esup>n \<le> \<^bsup>\<tau>\<^esup>m)\<rbrace>) \<and> (\<forall>\<tau>. \<Gamma>\<turnstile> {\<tau>} \<acute>b :== PROC LEQ(\<acute>n,\<acute>m) {t. t may_not_modify_globals \<tau>})
[PROOF STEP]
apply (rule conjI)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<forall>\<tau>. \<Gamma>\<turnstile> {\<tau>} \<acute>b :== PROC LEQ(\<acute>n,\<acute>m) \<lbrace>\<acute>b = (\<^bsup>\<tau>\<^esup>n \<le> \<^bsup>\<tau>\<^esup>m)\<rbrace>
2. \<forall>\<tau>. \<Gamma>\<turnstile> {\<tau>} \<acute>b :== PROC LEQ(\<acute>n,\<acute>m) {t. t may_not_modify_globals \<tau>}
[PROOF STEP]
apply (rule LEQ_spec [simplified])
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>\<tau>. \<Gamma>\<turnstile> {\<tau>} \<acute>b :== PROC LEQ(\<acute>n,\<acute>m) {t. t may_not_modify_globals \<tau>}
[PROOF STEP]
apply (rule LEQ_modifies [simplified])
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done
[PROOF STATE]
proof (state)
this:
\<Gamma>\<turnstile> {\<sigma>} \<acute>k :== CALL Max(LEQ_'proc,\<acute>n,\<acute>m) \<lbrace>\<acute>k = mx (\<le>) \<^bsup>\<sigma>\<^esup>n \<^bsup>\<sigma>\<^esup>m\<rbrace>
goal:
No subgoals!
[PROOF STEP]
qed |
module Data.Rel
import Data.Fun
||| Build an n-ary relation type from a Vect of Types
public export
Rel : Vect n Type -> Type
Rel ts = Fun ts Type
||| Universal quantification of a n-ary Relation over its
||| arguments to build a (function) type from a `Rel` type
|||
||| ```
||| λ> All [Nat,Nat] LTE
||| (x : Nat) -> (x : Nat) -> LTE x x
||| ```
public export
All : (ts : Vect n Type) -> (p : Rel ts) -> Type
All [] p = p
All (t :: ts) p = (x : t) -> All ts (p x)
||| Existential quantification of a n-ary relation over its
||| arguments to build a dependent pair (eg. Sigma type).
|||
||| Given a (type of) relation `p : [t_1, t_2 ... t_n] x r` where `t_i` and `r` are
||| types, `Ex` builds the type `Σ (x_1 : t_1). Σ (x_2 : t_2) ... . r`
||| For example:
||| ```
||| λ> Ex [Nat,Nat] LTE
||| (x : Nat ** (x : Nat ** LTE x x))
||| ```
||| Which is the type of a pair of natural numbers along with a proof that the first
||| is smaller or equal than the second.
public export
Ex : (ts : Vect n Type) -> (p : Rel ts) -> Type
Ex [] p = p
Ex (t :: ts) p = (x : t ** Ex ts (p x))
||| Map a type-level function over the co-domain of a n-ary Relation
public export
liftRel : (ts : Vect n Type) -> (p : Rel ts) -> (Type -> Type) -> Type
liftRel ts p f = All ts $ map @{Nary} f p
|
lemma compact_imp_countably_compact: "compact U \<Longrightarrow> countably_compact U" |
/-
Copyright (c) 2019 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 data.list.sublists
! leanprover-community/mathlib commit f2f413b9d4be3a02840d0663dace76e8fe3da053
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.Data.Nat.Choose.Basic
import Mathbin.Data.List.Perm
/-! # sublists
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
`list.sublists` gives a list of all (not necessarily contiguous) sublists of a list.
This file contains basic results on this function.
-/
universe u v w
variable {α : Type u} {β : Type v} {γ : Type w}
open Nat
namespace List
/-! ### sublists -/
#print List.sublists'_nil /-
@[simp]
theorem sublists'_nil : sublists' (@nil α) = [[]] :=
rfl
#align list.sublists'_nil List.sublists'_nil
-/
#print List.sublists'_singleton /-
@[simp]
theorem sublists'_singleton (a : α) : sublists' [a] = [[], [a]] :=
rfl
#align list.sublists'_singleton List.sublists'_singleton
-/
/- warning: list.map_sublists'_aux clashes with [anonymous] -> [anonymous]
warning: list.map_sublists'_aux -> [anonymous] is a dubious translation:
lean 3 declaration is
forall {α : Type.{u}} {β : Type.{v}} {γ : Type.{w}} (g : (List.{v} β) -> (List.{w} γ)) (l : List.{u} α) (f : (List.{u} α) -> (List.{v} β)) (r : List.{v} (List.{v} β)), Eq.{succ w} (List.{w} (List.{w} γ)) (List.map.{v, w} (List.{v} β) (List.{w} γ) g (List.sublists'Aux.{u, v} α β l f r)) (List.sublists'Aux.{u, w} α γ l (Function.comp.{succ u, succ v, succ w} (List.{u} α) (List.{v} β) (List.{w} γ) g f) (List.map.{v, w} (List.{v} β) (List.{w} γ) g r))
but is expected to have type
forall {α : Type.{u}} {β : Type.{v}}, (Nat -> α -> β) -> Nat -> (List.{u} α) -> (List.{v} β)
Case conversion may be inaccurate. Consider using '#align list.map_sublists'_aux [anonymous]ₓ'. -/
theorem [anonymous] (g : List β → List γ) (l : List α) (f r) :
map g (sublists'Aux l f r) = sublists'Aux l (g ∘ f) (map g r) := by
induction l generalizing f r <;> [rfl, simp only [*, sublists'_aux]]
#align list.map_sublists'_aux [anonymous]
/- warning: list.sublists'_aux_append clashes with [anonymous] -> [anonymous]
warning: list.sublists'_aux_append -> [anonymous] is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} (r' : List.{u2} (List.{u2} β)) (l : List.{u1} α) (f : (List.{u1} α) -> (List.{u2} β)) (r : List.{u2} (List.{u2} β)), Eq.{succ u2} (List.{u2} (List.{u2} β)) (List.sublists'Aux.{u1, u2} α β l f (Append.append.{u2} (List.{u2} (List.{u2} β)) (List.hasAppend.{u2} (List.{u2} β)) r r')) (Append.append.{u2} (List.{u2} (List.{u2} β)) (List.hasAppend.{u2} (List.{u2} β)) (List.sublists'Aux.{u1, u2} α β l f r) r')
but is expected to have type
forall {α : Type.{u1}} {β : Type.{u2}}, (Nat -> α -> β) -> Nat -> (List.{u1} α) -> (List.{u2} β)
Case conversion may be inaccurate. Consider using '#align list.sublists'_aux_append [anonymous]ₓ'. -/
theorem [anonymous] (r' : List (List β)) (l : List α) (f r) :
sublists'Aux l f (r ++ r') = sublists'Aux l f r ++ r' := by
induction l generalizing f r <;> [rfl, simp only [*, sublists'_aux]]
#align list.sublists'_aux_append [anonymous]
/- warning: list.sublists'_aux_eq_sublists' clashes with [anonymous] -> [anonymous]
warning: list.sublists'_aux_eq_sublists' -> [anonymous] is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} (l : List.{u1} α) (f : (List.{u1} α) -> (List.{u2} β)) (r : List.{u2} (List.{u2} β)), Eq.{succ u2} (List.{u2} (List.{u2} β)) (List.sublists'Aux.{u1, u2} α β l f r) (Append.append.{u2} (List.{u2} (List.{u2} β)) (List.hasAppend.{u2} (List.{u2} β)) (List.map.{u1, u2} (List.{u1} α) (List.{u2} β) f (List.sublists'.{u1} α l)) r)
but is expected to have type
forall {α : Type.{u1}} {β : Type.{u2}}, (Nat -> α -> β) -> Nat -> (List.{u1} α) -> (List.{u2} β)
Case conversion may be inaccurate. Consider using '#align list.sublists'_aux_eq_sublists' [anonymous]ₓ'. -/
theorem [anonymous] (l f r) : @sublists'Aux α β l f r = map f (sublists' l) ++ r := by
rw [sublists', map_sublists'_aux, ← sublists'_aux_append] <;> rfl
#align list.sublists'_aux_eq_sublists' [anonymous]
#print List.sublists'_cons /-
@[simp]
theorem sublists'_cons (a : α) (l : List α) :
sublists' (a :: l) = sublists' l ++ map (cons a) (sublists' l) := by
rw [sublists', sublists'_aux] <;> simp only [sublists'_aux_eq_sublists', map_id, append_nil] <;>
rfl
#align list.sublists'_cons List.sublists'_cons
-/
#print List.mem_sublists' /-
@[simp]
theorem mem_sublists' {s t : List α} : s ∈ sublists' t ↔ s <+ t :=
by
induction' t with a t IH generalizing s
· simp only [sublists'_nil, mem_singleton]
exact ⟨fun h => by rw [h], eq_nil_of_sublist_nil⟩
simp only [sublists'_cons, mem_append, IH, mem_map]
constructor <;> intro h; rcases h with (h | ⟨s, h, rfl⟩)
· exact sublist_cons_of_sublist _ h
· exact h.cons_cons _
· cases' h with _ _ _ h s _ _ h
· exact Or.inl h
· exact Or.inr ⟨s, h, rfl⟩
#align list.mem_sublists' List.mem_sublists'
-/
#print List.length_sublists' /-
@[simp]
theorem length_sublists' : ∀ l : List α, length (sublists' l) = 2 ^ length l
| [] => rfl
| a :: l => by
simp only [sublists'_cons, length_append, length_sublists' l, length_map, length, pow_succ',
mul_succ, MulZeroClass.mul_zero, zero_add]
#align list.length_sublists' List.length_sublists'
-/
#print List.sublists_nil /-
@[simp]
theorem sublists_nil : sublists (@nil α) = [[]] :=
rfl
#align list.sublists_nil List.sublists_nil
-/
#print List.sublists_singleton /-
@[simp]
theorem sublists_singleton (a : α) : sublists [a] = [[], [a]] :=
rfl
#align list.sublists_singleton List.sublists_singleton
-/
/- warning: list.sublists_aux₁_eq_sublists_aux clashes with [anonymous] -> [anonymous]
warning: list.sublists_aux₁_eq_sublists_aux -> [anonymous] is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} (l : List.{u1} α) (f : (List.{u1} α) -> (List.{u2} β)), Eq.{succ u2} (List.{u2} β) (List.sublistsAux₁.{u1, u2} α β l f) (List.sublistsAux.{u1, u2} α β l (fun (ys : List.{u1} α) (r : List.{u2} β) => Append.append.{u2} (List.{u2} β) (List.hasAppend.{u2} β) (f ys) r))
but is expected to have type
forall {α : Type.{u1}} {β : Type.{u2}}, (Nat -> α -> β) -> Nat -> (List.{u1} α) -> (List.{u2} β)
Case conversion may be inaccurate. Consider using '#align list.sublists_aux₁_eq_sublists_aux [anonymous]ₓ'. -/
theorem [anonymous] :
∀ (l) (f : List α → List β), sublistsAux₁ l f = sublistsAux l fun ys r => f ys ++ r
| [], f => rfl
| a :: l, f => by rw [sublists_aux₁, sublists_aux] <;> simp only [*, append_assoc]
#align list.sublists_aux₁_eq_sublists_aux [anonymous]
/- warning: list.sublists_aux_cons_eq_sublists_aux₁ clashes with [anonymous] -> [anonymous]
warning: list.sublists_aux_cons_eq_sublists_aux₁ -> [anonymous] is a dubious translation:
lean 3 declaration is
forall {α : Type.{u}} (l : List.{u} α), Eq.{succ u} (List.{u} (List.{u} α)) (List.sublistsAux.{u, u} α (List.{u} α) l (List.cons.{u} (List.{u} α))) (List.sublistsAux₁.{u, u} α (List.{u} α) l (fun (x : List.{u} α) => List.cons.{u} (List.{u} α) x (List.nil.{u} (List.{u} α))))
but is expected to have type
forall {α : Type.{u}} {l : Type.{v}}, (Nat -> α -> l) -> Nat -> (List.{u} α) -> (List.{v} l)
Case conversion may be inaccurate. Consider using '#align list.sublists_aux_cons_eq_sublists_aux₁ [anonymous]ₓ'. -/
theorem [anonymous] (l : List α) : sublistsAux l cons = sublistsAux₁ l fun x => [x] := by
rw [sublists_aux₁_eq_sublists_aux] <;> rfl
#align list.sublists_aux_cons_eq_sublists_aux₁ [anonymous]
/- warning: list.sublists_aux_eq_foldr.aux clashes with [anonymous] -> [anonymous]
warning: list.sublists_aux_eq_foldr.aux -> [anonymous] is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {a : α} {l : List.{u1} α}, (forall (f : (List.{u1} α) -> (List.{u2} β) -> (List.{u2} β)), Eq.{succ u2} (List.{u2} β) (List.sublistsAux.{u1, u2} α β l f) (List.foldr.{u1, u2} (List.{u1} α) (List.{u2} β) f (List.nil.{u2} β) (List.sublistsAux.{u1, u1} α (List.{u1} α) l (List.cons.{u1} (List.{u1} α))))) -> (forall (f : (List.{u1} α) -> (List.{u1} (List.{u1} α)) -> (List.{u1} (List.{u1} α))), Eq.{succ u1} (List.{u1} (List.{u1} α)) (List.sublistsAux.{u1, u1} α (List.{u1} α) l f) (List.foldr.{u1, u1} (List.{u1} α) (List.{u1} (List.{u1} α)) f (List.nil.{u1} (List.{u1} α)) (List.sublistsAux.{u1, u1} α (List.{u1} α) l (List.cons.{u1} (List.{u1} α))))) -> (forall (f : (List.{u1} α) -> (List.{u2} β) -> (List.{u2} β)), Eq.{succ u2} (List.{u2} β) (List.sublistsAux.{u1, u2} α β (List.cons.{u1} α a l) f) (List.foldr.{u1, u2} (List.{u1} α) (List.{u2} β) f (List.nil.{u2} β) (List.sublistsAux.{u1, u1} α (List.{u1} α) (List.cons.{u1} α a l) (List.cons.{u1} (List.{u1} α)))))
but is expected to have type
forall {α : Type.{u1}} {β : Type.{u2}}, (Nat -> α -> β) -> Nat -> (List.{u1} α) -> (List.{u2} β)
Case conversion may be inaccurate. Consider using '#align list.sublists_aux_eq_foldr.aux [anonymous]ₓ'. -/
theorem [anonymous] {a : α} {l : List α}
(IH₁ : ∀ f : List α → List β → List β, sublistsAux l f = foldr f [] (sublistsAux l cons))
(IH₂ :
∀ f : List α → List (List α) → List (List α),
sublistsAux l f = foldr f [] (sublistsAux l cons))
(f : List α → List β → List β) :
sublistsAux (a :: l) f = foldr f [] (sublistsAux (a :: l) cons) :=
by
simp only [sublists_aux, foldr_cons]; rw [IH₂, IH₁]; congr 1
induction' sublists_aux l cons with _ _ ih; · rfl
simp only [ih, foldr_cons]
#align list.sublists_aux_eq_foldr.aux [anonymous]
/- warning: list.sublists_aux_eq_foldr clashes with [anonymous] -> [anonymous]
warning: list.sublists_aux_eq_foldr -> [anonymous] is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} (l : List.{u1} α) (f : (List.{u1} α) -> (List.{u2} β) -> (List.{u2} β)), Eq.{succ u2} (List.{u2} β) (List.sublistsAux.{u1, u2} α β l f) (List.foldr.{u1, u2} (List.{u1} α) (List.{u2} β) f (List.nil.{u2} β) (List.sublistsAux.{u1, u1} α (List.{u1} α) l (List.cons.{u1} (List.{u1} α))))
but is expected to have type
forall {α : Type.{u1}} {β : Type.{u2}}, (Nat -> α -> β) -> Nat -> (List.{u1} α) -> (List.{u2} β)
Case conversion may be inaccurate. Consider using '#align list.sublists_aux_eq_foldr [anonymous]ₓ'. -/
theorem [anonymous] (l : List α) :
∀ f : List α → List β → List β, sublistsAux l f = foldr f [] (sublistsAux l cons) :=
by
suffices
_ ∧
∀ f : List α → List (List α) → List (List α),
sublistsAux l f = foldr f [] (sublistsAux l cons)
from this.1
induction' l with a l IH; · constructor <;> intro <;> rfl
exact ⟨sublists_aux_eq_foldr.aux IH.1 IH.2, sublists_aux_eq_foldr.aux IH.2 IH.2⟩
#align list.sublists_aux_eq_foldr [anonymous]
/- warning: list.sublists_aux_cons_cons clashes with [anonymous] -> [anonymous]
warning: list.sublists_aux_cons_cons -> [anonymous] is a dubious translation:
lean 3 declaration is
forall {α : Type.{u}} (l : List.{u} α) (a : α), Eq.{succ u} (List.{u} (List.{u} α)) (List.sublistsAux.{u, u} α (List.{u} α) (List.cons.{u} α a l) (List.cons.{u} (List.{u} α))) (List.cons.{u} (List.{u} α) (List.cons.{u} α a (List.nil.{u} α)) (List.foldr.{u, u} (List.{u} α) (List.{u} (List.{u} α)) (fun (ys : List.{u} α) (r : List.{u} (List.{u} α)) => List.cons.{u} (List.{u} α) ys (List.cons.{u} (List.{u} α) (List.cons.{u} α a ys) r)) (List.nil.{u} (List.{u} α)) (List.sublistsAux.{u, u} α (List.{u} α) l (List.cons.{u} (List.{u} α)))))
but is expected to have type
forall {α : Type.{u}} {l : Type.{v}}, (Nat -> α -> l) -> Nat -> (List.{u} α) -> (List.{v} l)
Case conversion may be inaccurate. Consider using '#align list.sublists_aux_cons_cons [anonymous]ₓ'. -/
theorem [anonymous] (l : List α) (a : α) :
sublistsAux (a :: l) cons =
[a] :: foldr (fun ys r => ys :: (a :: ys) :: r) [] (sublistsAux l cons) :=
by rw [← sublists_aux_eq_foldr] <;> rfl
#align list.sublists_aux_cons_cons [anonymous]
/- warning: list.sublists_aux₁_append clashes with [anonymous] -> [anonymous]
warning: list.sublists_aux₁_append -> [anonymous] is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} (l₁ : List.{u1} α) (l₂ : List.{u1} α) (f : (List.{u1} α) -> (List.{u2} β)), Eq.{succ u2} (List.{u2} β) (List.sublistsAux₁.{u1, u2} α β (Append.append.{u1} (List.{u1} α) (List.hasAppend.{u1} α) l₁ l₂) f) (Append.append.{u2} (List.{u2} β) (List.hasAppend.{u2} β) (List.sublistsAux₁.{u1, u2} α β l₁ f) (List.sublistsAux₁.{u1, u2} α β l₂ (fun (x : List.{u1} α) => Append.append.{u2} (List.{u2} β) (List.hasAppend.{u2} β) (f x) (List.sublistsAux₁.{u1, u2} α β l₁ (Function.comp.{succ u1, succ u1, succ u2} (List.{u1} α) (List.{u1} α) (List.{u2} β) f (fun (_x : List.{u1} α) => Append.append.{u1} (List.{u1} α) (List.hasAppend.{u1} α) _x x))))))
but is expected to have type
forall {α : Type.{u1}} {β : Type.{u2}}, (Nat -> α -> β) -> Nat -> (List.{u1} α) -> (List.{u2} β)
Case conversion may be inaccurate. Consider using '#align list.sublists_aux₁_append [anonymous]ₓ'. -/
theorem [anonymous] :
∀ (l₁ l₂ : List α) (f : List α → List β),
sublistsAux₁ (l₁ ++ l₂) f =
sublistsAux₁ l₁ f ++ sublistsAux₁ l₂ fun x => f x ++ sublistsAux₁ l₁ (f ∘ (· ++ x))
| [], l₂, f => by simp only [sublists_aux₁, nil_append, append_nil]
| a :: l₁, l₂, f => by
simp only [sublists_aux₁, cons_append, sublists_aux₁_append l₁, append_assoc] <;> rfl
#align list.sublists_aux₁_append [anonymous]
/- warning: list.sublists_aux₁_concat clashes with [anonymous] -> [anonymous]
warning: list.sublists_aux₁_concat -> [anonymous] is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} (l : List.{u1} α) (a : α) (f : (List.{u1} α) -> (List.{u2} β)), Eq.{succ u2} (List.{u2} β) (List.sublistsAux₁.{u1, u2} α β (Append.append.{u1} (List.{u1} α) (List.hasAppend.{u1} α) l (List.cons.{u1} α a (List.nil.{u1} α))) f) (Append.append.{u2} (List.{u2} β) (List.hasAppend.{u2} β) (Append.append.{u2} (List.{u2} β) (List.hasAppend.{u2} β) (List.sublistsAux₁.{u1, u2} α β l f) (f (List.cons.{u1} α a (List.nil.{u1} α)))) (List.sublistsAux₁.{u1, u2} α β l (fun (x : List.{u1} α) => f (Append.append.{u1} (List.{u1} α) (List.hasAppend.{u1} α) x (List.cons.{u1} α a (List.nil.{u1} α))))))
but is expected to have type
forall {α : Type.{u1}} {β : Type.{u2}}, (Nat -> α -> β) -> Nat -> (List.{u1} α) -> (List.{u2} β)
Case conversion may be inaccurate. Consider using '#align list.sublists_aux₁_concat [anonymous]ₓ'. -/
theorem [anonymous] (l : List α) (a : α) (f : List α → List β) :
sublistsAux₁ (l ++ [a]) f = sublistsAux₁ l f ++ f [a] ++ sublistsAux₁ l fun x => f (x ++ [a]) :=
by simp only [sublists_aux₁_append, sublists_aux₁, append_assoc, append_nil]
#align list.sublists_aux₁_concat [anonymous]
/- warning: list.sublists_aux₁_bind clashes with [anonymous] -> [anonymous]
warning: list.sublists_aux₁_bind -> [anonymous] is a dubious translation:
lean 3 declaration is
forall {α : Type.{u}} {β : Type.{v}} {γ : Type.{w}} (l : List.{u} α) (f : (List.{u} α) -> (List.{v} β)) (g : β -> (List.{w} γ)), Eq.{succ w} (List.{w} γ) (List.bind.{v, w} β γ (List.sublistsAux₁.{u, v} α β l f) g) (List.sublistsAux₁.{u, w} α γ l (fun (x : List.{u} α) => List.bind.{v, w} β γ (f x) g))
but is expected to have type
forall {α : Type.{u}} {β : Type.{v}}, (Nat -> α -> β) -> Nat -> (List.{u} α) -> (List.{v} β)
Case conversion may be inaccurate. Consider using '#align list.sublists_aux₁_bind [anonymous]ₓ'. -/
theorem [anonymous] :
∀ (l : List α) (f : List α → List β) (g : β → List γ),
(sublistsAux₁ l f).bind g = sublistsAux₁ l fun x => (f x).bind g
| [], f, g => rfl
| a :: l, f, g => by simp only [sublists_aux₁, bind_append, sublists_aux₁_bind l]
#align list.sublists_aux₁_bind [anonymous]
/- warning: list.sublists_aux_cons_append clashes with [anonymous] -> [anonymous]
warning: list.sublists_aux_cons_append -> [anonymous] is a dubious translation:
lean 3 declaration is
forall {α : Type.{u}} (l₁ : List.{u} α) (l₂ : List.{u} α), Eq.{succ u} (List.{u} (List.{u} α)) (List.sublistsAux.{u, u} α (List.{u} α) (Append.append.{u} (List.{u} α) (List.hasAppend.{u} α) l₁ l₂) (List.cons.{u} (List.{u} α))) (Append.append.{u} (List.{u} (List.{u} α)) (List.hasAppend.{u} (List.{u} α)) (List.sublistsAux.{u, u} α (List.{u} α) l₁ (List.cons.{u} (List.{u} α))) (Bind.bind.{u, u} List.{u} (Monad.toHasBind.{u, u} List.{u} List.monad.{u}) (List.{u} α) (List.{u} α) (List.sublistsAux.{u, u} α (List.{u} α) l₂ (List.cons.{u} (List.{u} α))) (fun (x : List.{u} α) => Functor.map.{u, u} List.{u} (Traversable.toFunctor.{u} List.{u} List.traversable.{u}) (List.{u} α) (List.{u} α) (fun (_x : List.{u} α) => Append.append.{u} (List.{u} α) (List.hasAppend.{u} α) _x x) (List.sublists.{u} α l₁))))
but is expected to have type
forall {α : Type.{u}} {l₁ : Type.{v}}, (Nat -> α -> l₁) -> Nat -> (List.{u} α) -> (List.{v} l₁)
Case conversion may be inaccurate. Consider using '#align list.sublists_aux_cons_append [anonymous]ₓ'. -/
theorem [anonymous] (l₁ l₂ : List α) :
sublistsAux (l₁ ++ l₂) cons =
sublistsAux l₁ cons ++ do
let x ← sublistsAux l₂ cons
(· ++ x) <$> sublists l₁ :=
by
simp only [sublists, sublists_aux_cons_eq_sublists_aux₁, sublists_aux₁_append, bind_eq_bind,
sublists_aux₁_bind]
congr ; funext x; apply congr_arg _
rw [← bind_ret_eq_map, sublists_aux₁_bind]; exact (append_nil _).symm
#align list.sublists_aux_cons_append [anonymous]
/- warning: list.sublists_append -> List.sublists_append is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} (l₁ : List.{u1} α) (l₂ : List.{u1} α), Eq.{succ u1} (List.{u1} (List.{u1} α)) (List.sublists.{u1} α (Append.append.{u1} (List.{u1} α) (List.hasAppend.{u1} α) l₁ l₂)) (Bind.bind.{u1, u1} List.{u1} (Monad.toHasBind.{u1, u1} List.{u1} List.monad.{u1}) (List.{u1} α) (List.{u1} α) (List.sublists.{u1} α l₂) (fun (x : List.{u1} α) => Functor.map.{u1, u1} List.{u1} (Traversable.toFunctor.{u1} List.{u1} List.traversable.{u1}) (List.{u1} α) (List.{u1} α) (fun (_x : List.{u1} α) => Append.append.{u1} (List.{u1} α) (List.hasAppend.{u1} α) _x x) (List.sublists.{u1} α l₁)))
but is expected to have type
forall {α : Type.{u1}} (l₁ : List.{u1} α) (l₂ : List.{u1} α), Eq.{succ u1} (List.{u1} (List.{u1} α)) (List.sublists.{u1} α (HAppend.hAppend.{u1, u1, u1} (List.{u1} α) (List.{u1} α) (List.{u1} α) (instHAppend.{u1} (List.{u1} α) (List.instAppendList.{u1} α)) l₁ l₂)) (Bind.bind.{u1, u1} List.{u1} (Monad.toBind.{u1, u1} List.{u1} List.instMonadList.{u1}) (List.{u1} α) (List.{u1} α) (List.sublists.{u1} α l₂) (fun (x : List.{u1} α) => List.map.{u1, u1} (List.{u1} α) (List.{u1} α) (fun (_x : List.{u1} α) => HAppend.hAppend.{u1, u1, u1} (List.{u1} α) (List.{u1} α) (List.{u1} α) (instHAppend.{u1} (List.{u1} α) (List.instAppendList.{u1} α)) _x x) (List.sublists.{u1} α l₁)))
Case conversion may be inaccurate. Consider using '#align list.sublists_append List.sublists_appendₓ'. -/
theorem sublists_append (l₁ l₂ : List α) :
sublists (l₁ ++ l₂) = do
let x ← sublists l₂
(· ++ x) <$> sublists l₁ :=
by
simp only [map, sublists, sublists_aux_cons_append, map_eq_map, bind_eq_bind, cons_bind, map_id',
append_nil, cons_append, map_id' fun _ => rfl] <;>
constructor <;>
rfl
#align list.sublists_append List.sublists_append
#print List.sublists_concat /-
@[simp]
theorem sublists_concat (l : List α) (a : α) :
sublists (l ++ [a]) = sublists l ++ map (fun x => x ++ [a]) (sublists l) := by
rw [sublists_append, sublists_singleton, bind_eq_bind, cons_bind, cons_bind, nil_bind, map_eq_map,
map_eq_map, map_id' append_nil, append_nil]
#align list.sublists_concat List.sublists_concat
-/
#print List.sublists_reverse /-
theorem sublists_reverse (l : List α) : sublists (reverse l) = map reverse (sublists' l) := by
induction' l with hd tl ih <;> [rfl,
simp only [reverse_cons, sublists_append, sublists'_cons, map_append, ih, sublists_singleton,
map_eq_map, bind_eq_bind, map_map, cons_bind, append_nil, nil_bind, (· ∘ ·)]]
#align list.sublists_reverse List.sublists_reverse
-/
#print List.sublists_eq_sublists' /-
theorem sublists_eq_sublists' (l : List α) : sublists l = map reverse (sublists' (reverse l)) := by
rw [← sublists_reverse, reverse_reverse]
#align list.sublists_eq_sublists' List.sublists_eq_sublists'
-/
#print List.sublists'_reverse /-
theorem sublists'_reverse (l : List α) : sublists' (reverse l) = map reverse (sublists l) := by
simp only [sublists_eq_sublists', map_map, map_id' reverse_reverse]
#align list.sublists'_reverse List.sublists'_reverse
-/
#print List.sublists'_eq_sublists /-
theorem sublists'_eq_sublists (l : List α) : sublists' l = map reverse (sublists (reverse l)) := by
rw [← sublists'_reverse, reverse_reverse]
#align list.sublists'_eq_sublists List.sublists'_eq_sublists
-/
/- warning: list.sublists_aux_ne_nil clashes with [anonymous] -> [anonymous]
warning: list.sublists_aux_ne_nil -> [anonymous] is a dubious translation:
lean 3 declaration is
forall {α : Type.{u}} (l : List.{u} α), Not (Membership.Mem.{u, u} (List.{u} α) (List.{u} (List.{u} α)) (List.hasMem.{u} (List.{u} α)) (List.nil.{u} α) (List.sublistsAux.{u, u} α (List.{u} α) l (List.cons.{u} (List.{u} α))))
but is expected to have type
forall {α : Type.{u}} {l : Type.{v}}, (Nat -> α -> l) -> Nat -> (List.{u} α) -> (List.{v} l)
Case conversion may be inaccurate. Consider using '#align list.sublists_aux_ne_nil [anonymous]ₓ'. -/
theorem [anonymous] : ∀ l : List α, [] ∉ sublistsAux l cons
| [] => id
| a :: l => by
rw [sublists_aux_cons_cons]
refine' not_mem_cons_of_ne_of_not_mem (cons_ne_nil _ _).symm _
have := sublists_aux_ne_nil l; revert this
induction sublists_aux l cons <;> intro ; · rwa [foldr]
simp only [foldr, mem_cons_iff, false_or_iff, not_or]
exact ⟨ne_of_not_mem_cons this, ih (not_mem_of_not_mem_cons this)⟩
#align list.sublists_aux_ne_nil [anonymous]
#print List.mem_sublists /-
@[simp]
theorem mem_sublists {s t : List α} : s ∈ sublists t ↔ s <+ t := by
rw [← reverse_sublist_iff, ← mem_sublists', sublists'_reverse,
mem_map_of_injective reverse_injective]
#align list.mem_sublists List.mem_sublists
-/
#print List.length_sublists /-
@[simp]
theorem length_sublists (l : List α) : length (sublists l) = 2 ^ length l := by
simp only [sublists_eq_sublists', length_map, length_sublists', length_reverse]
#align list.length_sublists List.length_sublists
-/
#print List.map_ret_sublist_sublists /-
theorem map_ret_sublist_sublists (l : List α) : map List.ret l <+ sublists l :=
reverseRecOn l (nil_sublist _) fun l a IH => by
simp only [map, map_append, sublists_concat] <;>
exact
((append_sublist_append_left _).2 <|
singleton_sublist.2 <| mem_map.2 ⟨[], mem_sublists.2 (nil_sublist _), by rfl⟩).trans
((append_sublist_append_right _).2 IH)
#align list.map_ret_sublist_sublists List.map_ret_sublist_sublists
-/
/-! ### sublists_len -/
#print List.sublistsLenAux /-
/-- Auxiliary function to construct the list of all sublists of a given length. Given an
integer `n`, a list `l`, a function `f` and an auxiliary list `L`, it returns the list made of
of `f` applied to all sublists of `l` of length `n`, concatenated with `L`. -/
def sublistsLenAux {α β : Type _} : ℕ → List α → (List α → β) → List β → List β
| 0, l, f, r => f [] :: r
| n + 1, [], f, r => r
| n + 1, a :: l, f, r => sublists_len_aux (n + 1) l f (sublists_len_aux n l (f ∘ List.cons a) r)
#align list.sublists_len_aux List.sublistsLenAux
-/
#print List.sublistsLen /-
/-- The list of all sublists of a list `l` that are of length `n`. For instance, for
`l = [0, 1, 2, 3]` and `n = 2`, one gets
`[[2, 3], [1, 3], [1, 2], [0, 3], [0, 2], [0, 1]]`. -/
def sublistsLen {α : Type _} (n : ℕ) (l : List α) : List (List α) :=
sublistsLenAux n l id []
#align list.sublists_len List.sublistsLen
-/
/- warning: list.sublists_len_aux_append -> List.sublistsLenAux_append is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} (n : Nat) (l : List.{u1} α) (f : (List.{u1} α) -> β) (g : β -> γ) (r : List.{u2} β) (s : List.{u3} γ), Eq.{succ u3} (List.{u3} γ) (List.sublistsLenAux.{u1, u3} α γ n l (Function.comp.{succ u1, succ u2, succ u3} (List.{u1} α) β γ g f) (Append.append.{u3} (List.{u3} γ) (List.hasAppend.{u3} γ) (List.map.{u2, u3} β γ g r) s)) (Append.append.{u3} (List.{u3} γ) (List.hasAppend.{u3} γ) (List.map.{u2, u3} β γ g (List.sublistsLenAux.{u1, u2} α β n l f r)) s)
but is expected to have type
forall {α : Type.{u3}} {β : Type.{u2}} {γ : Type.{u1}} (n : Nat) (l : List.{u3} α) (f : (List.{u3} α) -> β) (g : β -> γ) (r : List.{u2} β) (s : List.{u1} γ), Eq.{succ u1} (List.{u1} γ) (List.sublistsLenAux.{u3, u1} α γ n l (Function.comp.{succ u3, succ u2, succ u1} (List.{u3} α) β γ g f) (HAppend.hAppend.{u1, u1, u1} (List.{u1} γ) (List.{u1} γ) (List.{u1} γ) (instHAppend.{u1} (List.{u1} γ) (List.instAppendList.{u1} γ)) (List.map.{u2, u1} β γ g r) s)) (HAppend.hAppend.{u1, u1, u1} (List.{u1} γ) (List.{u1} γ) (List.{u1} γ) (instHAppend.{u1} (List.{u1} γ) (List.instAppendList.{u1} γ)) (List.map.{u2, u1} β γ g (List.sublistsLenAux.{u3, u2} α β n l f r)) s)
Case conversion may be inaccurate. Consider using '#align list.sublists_len_aux_append List.sublistsLenAux_appendₓ'. -/
theorem sublistsLenAux_append {α β γ : Type _} :
∀ (n : ℕ) (l : List α) (f : List α → β) (g : β → γ) (r : List β) (s : List γ),
sublistsLenAux n l (g ∘ f) (r.map g ++ s) = (sublistsLenAux n l f r).map g ++ s
| 0, l, f, g, r, s => rfl
| n + 1, [], f, g, r, s => rfl
| n + 1, a :: l, f, g, r, s => by
unfold sublists_len_aux
rw [show (g ∘ f) ∘ List.cons a = g ∘ f ∘ List.cons a by rfl, sublists_len_aux_append,
sublists_len_aux_append]
#align list.sublists_len_aux_append List.sublistsLenAux_append
/- warning: list.sublists_len_aux_eq -> List.sublistsLenAux_eq is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} (l : List.{u1} α) (n : Nat) (f : (List.{u1} α) -> β) (r : List.{u2} β), Eq.{succ u2} (List.{u2} β) (List.sublistsLenAux.{u1, u2} α β n l f r) (Append.append.{u2} (List.{u2} β) (List.hasAppend.{u2} β) (List.map.{u1, u2} (List.{u1} α) β f (List.sublistsLen.{u1} α n l)) r)
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} (l : List.{u2} α) (n : Nat) (f : (List.{u2} α) -> β) (r : List.{u1} β), Eq.{succ u1} (List.{u1} β) (List.sublistsLenAux.{u2, u1} α β n l f r) (HAppend.hAppend.{u1, u1, u1} (List.{u1} β) (List.{u1} β) (List.{u1} β) (instHAppend.{u1} (List.{u1} β) (List.instAppendList.{u1} β)) (List.map.{u2, u1} (List.{u2} α) β f (List.sublistsLen.{u2} α n l)) r)
Case conversion may be inaccurate. Consider using '#align list.sublists_len_aux_eq List.sublistsLenAux_eqₓ'. -/
theorem sublistsLenAux_eq {α β : Type _} (l : List α) (n) (f : List α → β) (r) :
sublistsLenAux n l f r = (sublistsLen n l).map f ++ r := by
rw [sublists_len, ← sublists_len_aux_append] <;> rfl
#align list.sublists_len_aux_eq List.sublistsLenAux_eq
/- warning: list.sublists_len_aux_zero -> List.sublistsLenAux_zero is a dubious translation:
lean 3 declaration is
forall {β : Type.{u1}} {α : Type.{u2}} (l : List.{u2} α) (f : (List.{u2} α) -> β) (r : List.{u1} β), Eq.{succ u1} (List.{u1} β) (List.sublistsLenAux.{u2, u1} α β (OfNat.ofNat.{0} Nat 0 (OfNat.mk.{0} Nat 0 (Zero.zero.{0} Nat Nat.hasZero))) l f r) (List.cons.{u1} β (f (List.nil.{u2} α)) r)
but is expected to have type
forall {β : Type.{u2}} {α : Type.{u1}} (l : List.{u1} α) (f : (List.{u1} α) -> β) (r : List.{u2} β), Eq.{succ u2} (List.{u2} β) (List.sublistsLenAux.{u1, u2} α β (OfNat.ofNat.{0} Nat 0 (instOfNatNat 0)) l f r) (List.cons.{u2} β (f (List.nil.{u1} α)) r)
Case conversion may be inaccurate. Consider using '#align list.sublists_len_aux_zero List.sublistsLenAux_zeroₓ'. -/
theorem sublistsLenAux_zero {α : Type _} (l : List α) (f : List α → β) (r) :
sublistsLenAux 0 l f r = f [] :: r := by cases l <;> rfl
#align list.sublists_len_aux_zero List.sublistsLenAux_zero
#print List.sublistsLen_zero /-
@[simp]
theorem sublistsLen_zero {α : Type _} (l : List α) : sublistsLen 0 l = [[]] :=
sublistsLenAux_zero _ _ _
#align list.sublists_len_zero List.sublistsLen_zero
-/
#print List.sublistsLen_succ_nil /-
@[simp]
theorem sublistsLen_succ_nil {α : Type _} (n) : sublistsLen (n + 1) (@nil α) = [] :=
rfl
#align list.sublists_len_succ_nil List.sublistsLen_succ_nil
-/
#print List.sublistsLen_succ_cons /-
@[simp]
theorem sublistsLen_succ_cons {α : Type _} (n) (a : α) (l) :
sublistsLen (n + 1) (a :: l) = sublistsLen (n + 1) l ++ (sublistsLen n l).map (cons a) := by
rw [sublists_len, sublists_len_aux, sublists_len_aux_eq, sublists_len_aux_eq, map_id,
append_nil] <;>
rfl
#align list.sublists_len_succ_cons List.sublistsLen_succ_cons
-/
#print List.length_sublistsLen /-
@[simp]
theorem length_sublistsLen {α : Type _} :
∀ (n) (l : List α), length (sublistsLen n l) = Nat.choose (length l) n
| 0, l => by simp
| n + 1, [] => by simp
| n + 1, a :: l => by simp [-add_comm, Nat.choose, *] <;> apply add_comm
#align list.length_sublists_len List.length_sublistsLen
-/
#print List.sublistsLen_sublist_sublists' /-
theorem sublistsLen_sublist_sublists' {α : Type _} :
∀ (n) (l : List α), sublistsLen n l <+ sublists' l
| 0, l => singleton_sublist.2 (mem_sublists'.2 (nil_sublist _))
| n + 1, [] => nil_sublist _
| n + 1, a :: l => by
rw [sublists_len_succ_cons, sublists'_cons]
exact (sublists_len_sublist_sublists' _ _).append ((sublists_len_sublist_sublists' _ _).map _)
#align list.sublists_len_sublist_sublists' List.sublistsLen_sublist_sublists'
-/
#print List.sublistsLen_sublist_of_sublist /-
theorem sublistsLen_sublist_of_sublist {α : Type _} (n) {l₁ l₂ : List α} (h : l₁ <+ l₂) :
sublistsLen n l₁ <+ sublistsLen n l₂ :=
by
induction' n with n IHn generalizing l₁ l₂; · simp
induction' h with l₁ l₂ a s IH l₁ l₂ a s IH; · rfl
· refine' IH.trans _
rw [sublists_len_succ_cons]
apply sublist_append_left
· simp [sublists_len_succ_cons]
exact IH.append ((IHn s).map _)
#align list.sublists_len_sublist_of_sublist List.sublistsLen_sublist_of_sublist
-/
#print List.length_of_sublistsLen /-
theorem length_of_sublistsLen {α : Type _} :
∀ {n} {l l' : List α}, l' ∈ sublistsLen n l → length l' = n
| 0, l, l', Or.inl rfl => rfl
| n + 1, a :: l, l', h =>
by
rw [sublists_len_succ_cons, mem_append, mem_map] at h
rcases h with (h | ⟨l', h, rfl⟩)
· exact length_of_sublists_len h
· exact congr_arg (· + 1) (length_of_sublists_len h)
#align list.length_of_sublists_len List.length_of_sublistsLen
-/
#print List.mem_sublistsLen_self /-
theorem mem_sublistsLen_self {α : Type _} {l l' : List α} (h : l' <+ l) :
l' ∈ sublistsLen (length l') l :=
by
induction' h with l₁ l₂ a s IH l₁ l₂ a s IH
· exact Or.inl rfl
· cases' l₁ with b l₁
· exact Or.inl rfl
· rw [length, sublists_len_succ_cons]
exact mem_append_left _ IH
· rw [length, sublists_len_succ_cons]
exact mem_append_right _ (mem_map.2 ⟨_, IH, rfl⟩)
#align list.mem_sublists_len_self List.mem_sublistsLen_self
-/
#print List.mem_sublistsLen /-
@[simp]
theorem mem_sublistsLen {α : Type _} {n} {l l' : List α} :
l' ∈ sublistsLen n l ↔ l' <+ l ∧ length l' = n :=
⟨fun h =>
⟨mem_sublists'.1 ((sublistsLen_sublist_sublists' _ _).Subset h), length_of_sublistsLen h⟩,
fun ⟨h₁, h₂⟩ => h₂ ▸ mem_sublistsLen_self h₁⟩
#align list.mem_sublists_len List.mem_sublistsLen
-/
#print List.sublistsLen_of_length_lt /-
theorem sublistsLen_of_length_lt {n} {l : List α} (h : l.length < n) : sublistsLen n l = [] :=
eq_nil_iff_forall_not_mem.mpr fun x =>
mem_sublistsLen.Not.mpr fun ⟨hs, hl⟩ => (h.trans_eq hl.symm).not_le (Sublist.length_le hs)
#align list.sublists_len_of_length_lt List.sublistsLen_of_length_lt
-/
#print List.sublistsLen_length /-
@[simp]
theorem sublistsLen_length : ∀ l : List α, sublistsLen l.length l = [l]
| [] => rfl
| a :: l => by
rw [length, sublists_len_succ_cons, sublists_len_length, map_singleton,
sublists_len_of_length_lt (lt_succ_self _), nil_append]
#align list.sublists_len_length List.sublistsLen_length
-/
open Function
#print List.Pairwise.sublists' /-
theorem Pairwise.sublists' {R} :
∀ {l : List α}, Pairwise R l → Pairwise (Lex (swap R)) (sublists' l)
| _, pairwise.nil => pairwise_singleton _ _
| _, @pairwise.cons _ _ a l H₁ H₂ =>
by
simp only [sublists'_cons, pairwise_append, pairwise_map, mem_sublists', mem_map, exists_imp,
and_imp]
refine' ⟨H₂.sublists', H₂.sublists'.imp fun l₁ l₂ => lex.cons, _⟩
rintro l₁ sl₁ x l₂ sl₂ rfl
cases' l₁ with b l₁; · constructor
exact lex.rel (H₁ _ <| sl₁.subset <| mem_cons_self _ _)
#align list.pairwise.sublists' List.Pairwise.sublists'
-/
#print List.pairwise_sublists /-
theorem pairwise_sublists {R} {l : List α} (H : Pairwise R l) :
Pairwise (fun l₁ l₂ => Lex R (reverse l₁) (reverse l₂)) (sublists l) :=
by
have := (pairwise_reverse.2 H).sublists'
rwa [sublists'_reverse, pairwise_map] at this
#align list.pairwise_sublists List.pairwise_sublists
-/
#print List.nodup_sublists /-
@[simp]
theorem nodup_sublists {l : List α} : Nodup (sublists l) ↔ Nodup l :=
⟨fun h => (h.Sublist (map_ret_sublist_sublists _)).of_map _, fun h =>
(pairwise_sublists h).imp fun _ _ h => mt reverse_inj.2 h.to_ne⟩
#align list.nodup_sublists List.nodup_sublists
-/
#print List.nodup_sublists' /-
@[simp]
theorem nodup_sublists' {l : List α} : Nodup (sublists' l) ↔ Nodup l := by
rw [sublists'_eq_sublists, nodup_map_iff reverse_injective, nodup_sublists, nodup_reverse]
#align list.nodup_sublists' List.nodup_sublists'
-/
alias nodup_sublists ↔ nodup.of_sublists nodup.sublists
#align list.nodup.of_sublists List.nodup.of_sublists
#align list.nodup.sublists List.nodup.sublists
alias nodup_sublists' ↔ nodup.of_sublists' nodup.sublists'
#align list.nodup.of_sublists' List.nodup.of_sublists'
#align list.nodup.sublists' List.nodup.sublists'
attribute [protected] nodup.sublists nodup.sublists'
#print List.nodup_sublistsLen /-
theorem nodup_sublistsLen (n : ℕ) {l : List α} (h : Nodup l) : (sublistsLen n l).Nodup :=
h.sublists'.Sublist <| sublistsLen_sublist_sublists' _ _
#align list.nodup_sublists_len List.nodup_sublistsLen
-/
#print List.sublists_cons_perm_append /-
theorem sublists_cons_perm_append (a : α) (l : List α) :
sublists (a :: l) ~ sublists l ++ map (cons a) (sublists l) :=
by
simp only [sublists, sublists_aux_cons_cons, cons_append, perm_cons]
refine' (perm.cons _ _).trans perm_middle.symm
induction' sublists_aux l cons with b l IH <;> simp
exact (IH.cons _).trans perm_middle.symm
#align list.sublists_cons_perm_append List.sublists_cons_perm_append
-/
#print List.sublists_perm_sublists' /-
theorem sublists_perm_sublists' : ∀ l : List α, sublists l ~ sublists' l
| [] => Perm.refl _
| a :: l => by
let IH := sublists_perm_sublists' l
rw [sublists'_cons] <;> exact (sublists_cons_perm_append _ _).trans (IH.append (IH.map _))
#align list.sublists_perm_sublists' List.sublists_perm_sublists'
-/
#print List.revzip_sublists /-
theorem revzip_sublists (l : List α) : ∀ l₁ l₂, (l₁, l₂) ∈ revzip l.sublists → l₁ ++ l₂ ~ l :=
by
rw [revzip]
apply List.reverseRecOn l
· intro l₁ l₂ h
simp at h
simp [h]
· intro l a IH l₁ l₂ h
rw [sublists_concat, reverse_append, zip_append, ← map_reverse, zip_map_right, zip_map_left] at
h <;>
[skip, · simp]
simp only [Prod.mk.inj_iff, mem_map, mem_append, Prod.map_mk, Prod.exists] at h
rcases h with (⟨l₁, l₂', h, rfl, rfl⟩ | ⟨l₁', l₂, h, rfl, rfl⟩)
· rw [← append_assoc]
exact (IH _ _ h).append_right _
· rw [append_assoc]
apply (perm_append_comm.append_left _).trans
rw [← append_assoc]
exact (IH _ _ h).append_right _
#align list.revzip_sublists List.revzip_sublists
-/
#print List.revzip_sublists' /-
theorem revzip_sublists' (l : List α) : ∀ l₁ l₂, (l₁, l₂) ∈ revzip l.sublists' → l₁ ++ l₂ ~ l :=
by
rw [revzip]
induction' l with a l IH <;> intro l₁ l₂ h
· simp at h
simp [h]
· rw [sublists'_cons, reverse_append, zip_append, ← map_reverse, zip_map_right, zip_map_left] at
h <;> [simp at h, simp]
rcases h with (⟨l₁, l₂', h, rfl, rfl⟩ | ⟨l₁', h, rfl⟩)
· exact perm_middle.trans ((IH _ _ h).cons _)
· exact (IH _ _ h).cons _
#align list.revzip_sublists' List.revzip_sublists'
-/
#print List.range_bind_sublistsLen_perm /-
theorem range_bind_sublistsLen_perm {α : Type _} (l : List α) :
((List.range (l.length + 1)).bind fun n => sublistsLen n l) ~ sublists' l :=
by
induction' l with h tl
· simp [range_succ]
· simp_rw [range_succ_eq_map, length, cons_bind, map_bind, sublists_len_succ_cons, sublists'_cons,
List.sublistsLen_zero, List.singleton_append]
refine' ((bind_append_perm (range (tl.length + 1)) _ _).symm.cons _).trans _
simp_rw [← List.bind_map, ← cons_append]
rw [← List.singleton_append, ← List.sublistsLen_zero tl]
refine' perm.append _ (l_ih.map _)
rw [List.range_succ, append_bind, bind_singleton,
sublists_len_of_length_lt (Nat.lt_succ_self _), append_nil, ←
List.map_bind (fun n => sublists_len n tl) Nat.succ, ←
cons_bind 0 _ fun n => sublists_len n tl, ← range_succ_eq_map]
exact l_ih
#align list.range_bind_sublists_len_perm List.range_bind_sublistsLen_perm
-/
end List
|
module field_section_mod
use coords_mod
implicit none
private
public :: latlon_field_section_constructor
!> A class to manipulate a limited section of a given field of data using coordinates
!! that encompass the entire field of data. Actually can generally manipulate the entire
!! field of data; it simply stores the boundaries of the section.
type, public, abstract :: field_section
contains
!> Wrapper to a set an integer value at given set of coordinates
procedure :: set_integer_value
!> Wrapper to a set a real value at given set of coordinates
procedure :: set_real_value
!> Wrapper to a set a logical value at given set of coordinates
procedure :: set_logical_value
!> Generic type bound procedure to set a given value at a given coordinate
!! this then calls one of the type specific wrappers for setting values
generic :: set_value => set_integer_value, set_real_value, set_logical_value
!> Get an unlimited polymorphic pointer to a value at the given coordinates
procedure(get_value), deferred :: get_value
!> Given a pointer to an unlimited polymorphic variable set it at the given
!! coordinates
procedure(set_generic_value), deferred :: set_generic_value
!> For each cell in the section
procedure(for_all_section), deferred :: for_all_section
!> Print the entire data field
procedure(print_field_section), deferred :: print_field_section
!> Deallocate the data object
procedure(deallocate_data), deferred :: deallocate_data
end type field_section
abstract interface
pure function get_value(this,coords_in) result(value)
import field_section
import coords
implicit none
class(field_section), intent(in) :: this
class(coords), intent(in) :: coords_in
class(*), pointer :: value
end function get_value
subroutine set_generic_value(this,coords_in,value)
import field_section
import coords
implicit none
class(field_section) :: this
class(coords), intent(in) :: coords_in
class(*), pointer, intent(in) :: value
end subroutine
subroutine for_all_section(this,subroutine_in,calling_object)
import field_section
implicit none
class(field_section) :: this
interface
subroutine subroutine_interface(calling_object,coords_in)
use coords_mod
class(*), intent(inout) :: calling_object
class(coords), pointer, intent(inout) :: coords_in
end subroutine subroutine_interface
end interface
procedure(subroutine_interface) :: subroutine_in
class(*), intent(inout) :: calling_object
end subroutine for_all_section
subroutine print_field_section(this)
import field_section
implicit none
class(field_section) :: this
end subroutine print_field_section
subroutine deallocate_data(this)
import field_section
implicit none
class(field_section) :: this
end subroutine deallocate_data
end interface
!> A concrete subclass of field section for a latitude longitude grid
type, extends(field_section), public :: latlon_field_section
!> A pointer to 2D array to hold the latitude longitude field section data;
!! in fact a pointer to the entire field both point in and outside the section
class(*), dimension (:,:), pointer :: data
!> Number of latitudinal points in the field
integer :: nlat
!> Number of longitudinal points in the field
integer :: nlon
!> Minimum latitude of the section of field that is of interest
integer :: section_min_lat
!> Minimum longitude of the section of field that is of interest
integer :: section_min_lon
!> Maximum latitude of the section of field that is of interest
integer :: section_max_lat
!> Maximum longitude of the section of field that is of interest
integer :: section_max_lon
!> Wrap the field east west or not
logical :: wrap
contains
private
!> Initialize this latitude longitude field section. Arguments are a pointer to
!! the input data array and the section coords of the section of the field that
!! is of interest
procedure :: init_latlon_field_section
!> Set the data field to a given polymorphic value at a given latitude and longitude
!! with no consideration for wrapping
procedure :: set_data_array_element => latlon_set_data_array_element
!> Return the number of the latitude points in the entire grid
procedure, public :: get_nlat
!> Return the number of the longitude points in the entire grid
procedure, public :: get_nlon
!> Return the value of the wrap flag
procedure, public :: get_wrap
!> Returns a pointer to a copy of the array of data (this copy is created by
!! this function using sourced allocation)
procedure, public :: get_data => latlon_get_data
!> Getter for section minimum latitude
procedure, public :: get_section_min_lat
!> Getter for section minimum longitude
procedure, public :: get_section_min_lon
!> Getter for section maximum latitude
procedure, public :: get_section_max_lat
!> Getter for section maximum longitude
procedure, public :: get_section_max_lon
!> Given a pointer to an unlimited polymorphic variable set it at the given
!! latitude logitude coordinates
procedure, public :: set_generic_value => latlon_set_generic_value
!> Return an unlimited polymorphic pointer to a value at the given latitude
!! longitude coordinates
procedure, public :: get_value => latlon_get_value
!> For each cell in the section
procedure, public :: for_all_section => latlon_for_all_section
!> Print the entire latitude longitude data field
procedure, public :: print_field_section => latlon_print_field_section
!> Deallocate the latitude longitude data array
procedure, public :: deallocate_data => latlon_deallocate_data
end type latlon_field_section
interface latlon_field_section
procedure latlon_field_section_constructor
end interface latlon_field_section
!> A concrete subclass of field section for an icon single index grid
type, extends(field_section), public :: icon_single_index_field_section
!> A pointer to 2D array to hold the icon single index field section data;
!! in fact a pointer to the entire field both point in and outside the section
class(*), dimension (:), pointer :: data
!> A mask with false outside the section and true inside
logical, dimension(:), pointer :: mask
!> Number of points in the field
integer :: num_points
integer, dimension(:,:), pointer :: cell_neighbors
integer, dimension(:,:), pointer :: cell_secondary_neighbors
contains
private
!> Initialize this latitude longitude field section. Arguments are a pointer to
!! the input data array and the section coords of the section of the field that
!! is of interest
procedure :: init_icon_single_index_field_section
!> Set the data field to a given polymorphic value at a given latitude and longitude
!! with no consideration for wrapping
procedure :: set_data_array_element => icon_single_index_set_data_array_element
procedure, public :: get_mask
!> Given a pointer to an unlimited polymorphic variable set it at the given
!! coordinates
procedure, public :: set_generic_value => icon_single_index_set_generic_value
!> Return an unlimited polymorphic pointer to a value at the given
!! coordinates
procedure, public :: get_value => icon_single_index_get_value
!> Returns a pointer to a copy of the array of data (this copy is created by
!! this function using sourced allocation)
procedure, public :: get_data => icon_single_index_get_data
!> For each cell in the section
procedure, public :: for_all_section => icon_single_index_for_all_section
!> Print the entire data field
procedure, public :: print_field_section => icon_single_index_print_field_section
!> Deallocate the data array
procedure, public :: deallocate_data => icon_single_index_deallocate_data
!> Get the number of points
procedure, public :: get_num_points
end type icon_single_index_field_section
interface icon_single_index_field_section
procedure :: icon_single_index_field_section_constructor
end interface icon_single_index_field_section
contains
subroutine latlon_set_data_array_element(this,lat,lon,value)
class(latlon_field_section) :: this
class(*), pointer :: value
integer :: lat,lon
select type (value)
type is (integer)
select type (data=>this%data)
type is (integer)
data(lat,lon) = value
class default
stop 'trying to set array element with value of incorrect type'
end select
type is (logical)
select type (data => this%data)
type is (logical)
data(lat,lon) = value
class default
stop 'trying to set array element with value of incorrect type'
end select
type is (real)
select type (data => this%data)
type is (real)
data(lat,lon) = value
class default
stop 'trying to set array element with value of incorrect type'
end select
class default
stop 'trying to set array element with value of a unknown type'
end select
end subroutine latlon_set_data_array_element
subroutine set_integer_value(this,coords_in,value)
class(field_section) :: this
class(coords) :: coords_in
integer :: value
class(*), pointer :: pointer_to_value
allocate(pointer_to_value,source=value)
call this%set_generic_value(coords_in,pointer_to_value)
deallocate(pointer_to_value)
end subroutine set_integer_value
subroutine set_real_value(this,coords_in,value)
class(field_section) :: this
class(coords) :: coords_in
real :: value
class(*), pointer :: pointer_to_value
allocate(pointer_to_value,source=value)
call this%set_generic_value(coords_in,pointer_to_value)
deallocate(pointer_to_value)
end subroutine set_real_value
subroutine set_logical_value(this,coords_in,value)
class(field_section) :: this
class(coords) :: coords_in
logical :: value
class(*), pointer :: pointer_to_value
allocate(pointer_to_value,source=value)
call this%set_generic_value(coords_in,pointer_to_value)
deallocate(pointer_to_value)
end subroutine set_logical_value
function latlon_field_section_constructor(data,section_coords) result(constructor)
type(latlon_field_section), pointer :: constructor
class (*), dimension(:,:), pointer :: data
class(latlon_section_coords) :: section_coords
allocate(constructor)
call constructor%init_latlon_field_section(data,section_coords)
end function latlon_field_section_constructor
subroutine init_latlon_field_section(this,data,section_coords,wrap_in)
class(latlon_field_section) :: this
class(*), dimension(:,:), pointer :: data
class(latlon_section_coords) section_coords
logical, optional :: wrap_in
logical :: wrap
if(present(wrap_in)) then
wrap = wrap_in
else
wrap = .true.
end if
this%data => data
this%nlat = SIZE(data,1)
this%nlon = SIZE(data,2)
this%section_min_lat = section_coords%section_min_lat
this%section_min_lon = section_coords%section_min_lon
this%section_max_lat = section_coords%section_min_lat + section_coords%section_width_lat - 1
this%section_max_lon = section_coords%section_min_lon + section_coords%section_width_lon - 1
this%wrap = wrap
end subroutine init_latlon_field_section
pure function latlon_get_value(this,coords_in) result(value)
class(latlon_field_section), intent(in) :: this
class(coords), intent(in) :: coords_in
class(*), pointer :: value
integer :: lat,lon
select type(coords_in)
type is (latlon_coords)
if ( this%nlat >= coords_in%lat .and. coords_in%lat > 0) then
lat = coords_in%lat
else if (this%nlat < coords_in%lat) then
lat = this%nlat
else
lat = 1
end if
if ( this%nlon >= coords_in%lon .and. coords_in%lon > 0) then
lon = coords_in%lon
else if (this%nlon < coords_in%lon) then
if (.not. this%wrap) then
lon = this%nlon
else
lon = coords_in%lon - this%nlon
end if
else
if (.not. this%wrap) then
lon = 1
else
lon = this%nlon + coords_in%lon
end if
end if
end select
allocate(value,source=this%data(lat,lon))
end function latlon_get_value
subroutine latlon_set_generic_value(this,coords_in,value)
class(latlon_field_section) :: this
class(coords), intent(in) :: coords_in
class(*), pointer, intent(in) :: value
select type (coords_in)
type is (latlon_coords)
if ( this%nlon >= coords_in%lon .and. coords_in%lon > 0) then
call this%set_data_array_element(coords_in%lat,coords_in%lon,value)
else if (this%nlon < coords_in%lon) then
if (.not. this%wrap) then
stop 'Trying to write element outside of field boundries'
else
call this%set_data_array_element(coords_in%lat,coords_in%lon - this%nlon,value)
end if
else
if (.not. this%wrap) then
stop 'Trying to write element outside of field boundries'
else
call this%set_data_array_element(coords_in%lat,this%nlon + coords_in%lon,value)
end if
end if
end select
end subroutine latlon_set_generic_value
subroutine latlon_for_all_section(this,subroutine_in,calling_object)
implicit none
class(latlon_field_section) :: this
class(*), intent(inout) :: calling_object
class(coords), pointer :: coords_in
integer :: i,j
interface
subroutine subroutine_interface(calling_object,coords_in)
use coords_mod
class(*), intent(inout) :: calling_object
class(coords), pointer, intent(inout) :: coords_in
end subroutine subroutine_interface
end interface
procedure(subroutine_interface) :: subroutine_in
do j = this%section_min_lon,this%section_max_lon
do i = this%section_min_lat,this%section_max_lat
allocate(coords_in,source=latlon_coords(i,j))
call subroutine_in(calling_object,coords_in)
end do
end do
end subroutine latlon_for_all_section
pure function get_nlat(this) result(nlat)
class(latlon_field_section), intent(in) :: this
integer :: nlat
nlat = this%nlat
end function get_nlat
pure function get_nlon(this) result(nlon)
class(latlon_field_section), intent(in) :: this
integer :: nlon
nlon = this%nlon
end function get_nlon
pure function get_wrap(this) result(wrap)
class(latlon_field_section), intent(in) :: this
logical :: wrap
wrap = this%wrap
end function get_wrap
!Explicit specification of bounds in source is safer
pure function latlon_get_data(this) result(data)
class(latlon_field_section), intent(in) :: this
class(*), dimension(:,:), pointer :: data
allocate(data(size(this%data,1),size(this%data,2)),source=this%data)
end function latlon_get_data
!Explicit specification of bounds in source is safer
pure function icon_single_index_get_data(this) result(data)
class(icon_single_index_field_section), intent(in) :: this
class(*), dimension(:), pointer :: data
allocate(data(size(this%data)),source=this%data)
end function icon_single_index_get_data
pure function get_section_min_lat(this) result(section_min_lat)
class(latlon_field_section), intent(in) :: this
integer section_min_lat
section_min_lat = this%section_min_lat
end function get_section_min_lat
pure function get_section_min_lon(this) result(section_min_lon)
class(latlon_field_section), intent(in) :: this
integer section_min_lon
section_min_lon = this%section_min_lon
end function get_section_min_lon
pure function get_section_max_lat(this) result(section_max_lat)
class(latlon_field_section), intent(in) :: this
integer section_max_lat
section_max_lat = this%section_max_lat
end function get_section_max_lat
pure function get_section_max_lon(this) result(section_max_lon)
class(latlon_field_section), intent(in) :: this
integer section_max_lon
section_max_lon = this%section_max_lon
end function get_section_max_lon
subroutine latlon_print_field_section(this)
class(latlon_field_section) :: this
integer :: i,j
select type(data => this%data)
type is (integer)
do i = 1,size(data,1)
write (*,*) (data(i,j),j=1,size(data,2))
end do
type is (logical)
do i = 1,size(data,1)
write (*,*) (data(i,j),j=1,size(data,2))
end do
end select
end subroutine latlon_print_field_section
subroutine latlon_deallocate_data(this)
class(latlon_field_section) :: this
deallocate(this%data)
end subroutine latlon_deallocate_data
function icon_single_index_field_section_constructor(data,section_coords) result(constructor)
type(icon_single_index_field_section), pointer :: constructor
class (*), dimension(:), pointer :: data
class(generic_1d_section_coords) section_coords
allocate(constructor)
call constructor%init_icon_single_index_field_section(data,section_coords)
end function icon_single_index_field_section_constructor
subroutine init_icon_single_index_field_section(this,input_data,section_coords)
class(icon_single_index_field_section) :: this
class(*), dimension(:), pointer :: input_data
type(generic_1d_section_coords) :: section_coords
this%data => input_data
this%cell_neighbors => section_coords%get_cell_neighbors()
this%cell_secondary_neighbors => &
section_coords%get_cell_secondary_neighbors()
this%num_points = size(input_data)
this%mask => section_coords%get_section_mask()
end subroutine init_icon_single_index_field_section
subroutine icon_single_index_set_data_array_element(this,index,value)
class(icon_single_index_field_section) :: this
class(*), pointer :: value
integer :: index
select type (value)
type is (integer)
select type (data => this%data)
type is (integer)
data(index) = value
class default
stop 'trying to set array element with value of incorrect type'
end select
type is (logical)
select type (data => this%data)
type is (logical)
data(index) = value
class default
stop 'trying to set array element with value of incorrect type'
end select
type is (real)
select type (data => this%data)
type is (real)
data(index) = value
class default
stop 'trying to set array element with value of incorrect type'
end select
type is (generic_1d_coords)
select type (data=> this%data)
type is (generic_1d_coords)
data(index) = value
class default
stop 'trying to set array element with value of incorrect type'
end select
class default
stop 'trying to set array element with value of a unknown type'
end select
end subroutine icon_single_index_set_data_array_element
pure function icon_single_index_get_value(this,coords_in) result(value)
class(icon_single_index_field_section), intent(in) :: this
class(coords), intent(in) :: coords_in
class(*), pointer :: value
select type (coords_in)
type is (generic_1d_coords)
allocate(value,source=this%data(coords_in%index))
end select
end function icon_single_index_get_value
subroutine icon_single_index_set_generic_value(this,coords_in,value)
class(icon_single_index_field_section) :: this
class(coords), intent(in) :: coords_in
class(*), pointer, intent(in) :: value
select type (coords_in)
type is (generic_1d_coords)
call this%set_data_array_element(coords_in%index,value)
end select
end subroutine icon_single_index_set_generic_value
subroutine icon_single_index_for_all_section(this,subroutine_in,calling_object)
implicit none
class(icon_single_index_field_section) :: this
class(*), intent(inout) :: calling_object
class(coords), pointer :: coords_in
integer :: i
interface
subroutine subroutine_interface(calling_object,coords_in)
use coords_mod
class(*), intent(inout) :: calling_object
class(coords), pointer, intent(inout) :: coords_in
end subroutine subroutine_interface
end interface
procedure(subroutine_interface) :: subroutine_in
do i = 1,this%num_points
if (this%mask(i)) then
allocate(coords_in,source=generic_1d_coords(i,.true.))
call subroutine_in(calling_object,coords_in)
end if
end do
end subroutine icon_single_index_for_all_section
subroutine icon_single_index_print_field_section(this)
class(icon_single_index_field_section) :: this
integer :: i
select type(data => this%data)
type is (integer)
write (*,*) (data(i),i=1,size(data))
type is (logical)
write (*,*) (data(i),i=1,size(data))
end select
end subroutine icon_single_index_print_field_section
function get_mask(this) result(mask)
class(icon_single_index_field_section) :: this
logical, dimension(:), pointer :: mask
mask => this%mask
end function get_mask
function get_num_points(this) result(npoints)
class(icon_single_index_field_section) :: this
integer :: npoints
npoints = this%num_points
end function
subroutine icon_single_index_deallocate_data(this)
class(icon_single_index_field_section) :: this
deallocate(this%data)
end subroutine icon_single_index_deallocate_data
end module field_section_mod
|
/-
Copyright (c) 2018 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Jens Wagemaker, Aaron Anderson
-/
import data.int.basic
import data.int.gcd
import ring_theory.multiplicity
import ring_theory.principal_ideal_domain
/-!
# Divisibility over ℕ and ℤ
This file collects results for the integers and natural numbers that use abstract algebra in
their proofs or cases of ℕ and ℤ being examples of structures in abstract algebra.
## Main statements
* `nat.prime_iff`: `nat.prime` coincides with the general definition of `prime`
* `nat.irreducible_iff_prime`: a non-unit natural number is only divisible by `1` iff it is prime
* `nat.factors_eq`: the multiset of elements of `nat.factors` is equal to the factors
given by the `unique_factorization_monoid` instance
* ℤ is a `normalization_monoid`
* ℤ is a `gcd_monoid`
## Tags
prime, irreducible, natural numbers, integers, normalization monoid, gcd monoid,
greatest common divisor, prime factorization, prime factors, unique factorization,
unique factors
-/
theorem nat.prime_iff {p : ℕ} : p.prime ↔ prime p :=
begin
split; intro h,
{ refine ⟨h.ne_zero, ⟨_, λ a b, _⟩⟩,
{ rw nat.is_unit_iff, apply h.ne_one },
{ apply h.dvd_mul.1 } },
{ refine ⟨_, λ m hm, _⟩,
{ cases p, { exfalso, apply h.ne_zero rfl },
cases p, { exfalso, apply h.ne_one rfl },
exact (add_le_add_right (zero_le p) 2 : _ ) },
{ cases hm with n hn,
cases h.2.2 m n (hn ▸ dvd_refl _) with hpm hpn,
{ right, apply nat.dvd_antisymm (dvd.intro _ hn.symm) hpm },
{ left,
cases n, { exfalso, rw [hn, mul_zero] at h, apply h.ne_zero rfl },
apply nat.eq_of_mul_eq_mul_right (nat.succ_pos _),
rw [← hn, one_mul],
apply nat.dvd_antisymm hpn (dvd.intro m _),
rw [mul_comm, hn], }, } }
end
theorem nat.irreducible_iff_prime {p : ℕ} : irreducible p ↔ prime p :=
begin
refine ⟨λ h, _, irreducible_of_prime⟩,
rw ← nat.prime_iff,
refine ⟨_, λ m hm, _⟩,
{ cases p, { exfalso, apply h.ne_zero rfl },
cases p, { exfalso, apply h.not_unit is_unit_one, },
exact (add_le_add_right (zero_le p) 2 : _ ) },
{ cases hm with n hn,
cases h.is_unit_or_is_unit hn with um un,
{ left, rw nat.is_unit_iff.1 um, },
{ right, rw [hn, nat.is_unit_iff.1 un, mul_one], } }
end
namespace nat
instance : wf_dvd_monoid ℕ :=
⟨begin
apply rel_hom.well_founded _ (with_top.well_founded_lt nat.lt_wf),
refine ⟨λ x, if x = 0 then ⊤ else x, _⟩,
intros a b h,
cases a,
{ exfalso, revert h, simp [dvd_not_unit] },
cases b,
{simp [succ_ne_zero, with_top.coe_lt_top]},
cases dvd_and_not_dvd_iff.2 h with h1 h2,
simp only [succ_ne_zero, with_top.coe_lt_coe, if_false],
apply lt_of_le_of_ne (nat.le_of_dvd (nat.succ_pos _) h1) (λ con, h2 _),
rw con,
end⟩
instance : unique_factorization_monoid ℕ :=
⟨λ _, nat.irreducible_iff_prime⟩
end nat
namespace int
section normalization_monoid
instance : normalization_monoid ℤ :=
{ norm_unit := λa:ℤ, if 0 ≤ a then 1 else -1,
norm_unit_zero := if_pos (le_refl _),
norm_unit_mul := assume a b hna hnb,
begin
cases hna.lt_or_lt with ha ha; cases hnb.lt_or_lt with hb hb;
simp [mul_nonneg_iff, ha.le, ha.not_le, hb.le, hb.not_le]
end,
norm_unit_coe_units := assume u, (units_eq_one_or u).elim
(assume eq, eq.symm ▸ if_pos zero_le_one)
(assume eq, eq.symm ▸ if_neg (not_le_of_gt $ show (-1:ℤ) < 0, by dec_trivial)), }
lemma normalize_of_nonneg {z : ℤ} (h : 0 ≤ z) : normalize z = z :=
show z * ↑(ite _ _ _) = z, by rw [if_pos h, units.coe_one, mul_one]
lemma normalize_of_neg {z : ℤ} (h : z < 0) : normalize z = -z :=
show z * ↑(ite _ _ _) = -z,
by rw [if_neg (not_le_of_gt h), units.coe_neg, units.coe_one, mul_neg_one]
lemma normalize_coe_nat (n : ℕ) : normalize (n : ℤ) = n :=
normalize_of_nonneg (coe_nat_le_coe_nat_of_le $ nat.zero_le n)
theorem coe_nat_abs_eq_normalize (z : ℤ) : (z.nat_abs : ℤ) = normalize z :=
begin
by_cases 0 ≤ z,
{ simp [nat_abs_of_nonneg h, normalize_of_nonneg h] },
{ simp [of_nat_nat_abs_of_nonpos (le_of_not_ge h), normalize_of_neg (lt_of_not_ge h)] }
end
end normalization_monoid
section gcd_monoid
instance : gcd_monoid ℤ :=
{ gcd := λa b, int.gcd a b,
lcm := λa b, int.lcm a b,
gcd_dvd_left := assume a b, int.gcd_dvd_left _ _,
gcd_dvd_right := assume a b, int.gcd_dvd_right _ _,
dvd_gcd := assume a b c, dvd_gcd,
normalize_gcd := assume a b, normalize_coe_nat _,
gcd_mul_lcm := by intros; rw [← int.coe_nat_mul, gcd_mul_lcm, coe_nat_abs_eq_normalize],
lcm_zero_left := assume a, coe_nat_eq_zero.2 $ nat.lcm_zero_left _,
lcm_zero_right := assume a, coe_nat_eq_zero.2 $ nat.lcm_zero_right _,
.. int.normalization_monoid }
lemma coe_gcd (i j : ℤ) : ↑(int.gcd i j) = gcd_monoid.gcd i j := rfl
lemma coe_lcm (i j : ℤ) : ↑(int.lcm i j) = gcd_monoid.lcm i j := rfl
lemma nat_abs_gcd (i j : ℤ) : nat_abs (gcd_monoid.gcd i j) = int.gcd i j := rfl
lemma nat_abs_lcm (i j : ℤ) : nat_abs (gcd_monoid.lcm i j) = int.lcm i j := rfl
end gcd_monoid
lemma exists_unit_of_abs (a : ℤ) : ∃ (u : ℤ) (h : is_unit u), (int.nat_abs a : ℤ) = u * a :=
begin
cases (nat_abs_eq a) with h,
{ use [1, is_unit_one], rw [← h, one_mul], },
{ use [-1, is_unit_one.neg], rw [ ← neg_eq_iff_neg_eq.mp (eq.symm h)],
simp only [neg_mul_eq_neg_mul_symm, one_mul] }
end
lemma gcd_eq_nat_abs {a b : ℤ} : int.gcd a b = nat.gcd a.nat_abs b.nat_abs := rfl
lemma gcd_eq_one_iff_coprime {a b : ℤ} : int.gcd a b = 1 ↔ is_coprime a b :=
begin
split,
{ intro hg,
obtain ⟨ua, hua, ha⟩ := exists_unit_of_abs a,
obtain ⟨ub, hub, hb⟩ := exists_unit_of_abs b,
use [(nat.gcd_a (int.nat_abs a) (int.nat_abs b)) * ua,
(nat.gcd_b (int.nat_abs a) (int.nat_abs b)) * ub],
rw [mul_assoc, ← ha, mul_assoc, ← hb, mul_comm, mul_comm _ (int.nat_abs b : ℤ),
← nat.gcd_eq_gcd_ab, ←gcd_eq_nat_abs, hg, int.coe_nat_one] },
{ rintro ⟨r, s, h⟩,
by_contradiction hg,
obtain ⟨p, ⟨hp, ha, hb⟩⟩ := nat.prime.not_coprime_iff_dvd.mp hg,
apply nat.prime.not_dvd_one hp,
rw [←coe_nat_dvd, int.coe_nat_one, ← h],
exact dvd_add (dvd_mul_of_dvd_right (coe_nat_dvd_left.mpr ha) _)
(dvd_mul_of_dvd_right (coe_nat_dvd_left.mpr hb) _) }
end
lemma coprime_iff_nat_coprime {a b : ℤ} : is_coprime a b ↔ nat.coprime a.nat_abs b.nat_abs :=
by rw [←gcd_eq_one_iff_coprime, nat.coprime_iff_gcd_eq_one, gcd_eq_nat_abs]
lemma sq_of_gcd_eq_one {a b c : ℤ} (h : int.gcd a b = 1) (heq : a * b = c ^ 2) :
∃ (a0 : ℤ), a = a0 ^ 2 ∨ a = - (a0 ^ 2) :=
begin
have h' : gcd_monoid.gcd a b = 1, { rw [← coe_gcd, h], dec_trivial },
obtain ⟨d, ⟨u, hu⟩⟩ := exists_associated_pow_of_mul_eq_pow h' heq,
use d,
rw ← hu,
cases int.units_eq_one_or u with hu' hu'; { rw hu', simp }
end
lemma sq_of_coprime {a b c : ℤ} (h : is_coprime a b) (heq : a * b = c ^ 2) :
∃ (a0 : ℤ), a = a0 ^ 2 ∨ a = - (a0 ^ 2) := sq_of_gcd_eq_one (gcd_eq_one_iff_coprime.mpr h) heq
lemma nat_abs_euclidean_domain_gcd (a b : ℤ) :
int.nat_abs (euclidean_domain.gcd a b) = int.gcd a b :=
begin
apply nat.dvd_antisymm; rw ← int.coe_nat_dvd,
{ rw int.nat_abs_dvd,
exact int.dvd_gcd (euclidean_domain.gcd_dvd_left _ _) (euclidean_domain.gcd_dvd_right _ _) },
{ rw int.dvd_nat_abs,
exact euclidean_domain.dvd_gcd (int.gcd_dvd_left _ _) (int.gcd_dvd_right _ _) }
end
end int
theorem irreducible_iff_nat_prime : ∀(a : ℕ), irreducible a ↔ nat.prime a
| 0 := by simp [nat.not_prime_zero]
| 1 := by simp [nat.prime, one_lt_two]
| (n + 2) :=
have h₁ : ¬n + 2 = 1, from dec_trivial,
begin
simp [h₁, nat.prime, irreducible_iff, (≥), nat.le_add_left 2 n, (∣)],
refine forall_congr (assume a, forall_congr $ assume b, forall_congr $ assume hab, _),
by_cases a = 1; simp [h],
split,
{ assume hb, simpa [hb] using hab.symm },
{ assume ha, subst ha,
have : n + 2 > 0, from dec_trivial,
refine nat.eq_of_mul_eq_mul_left this _,
rw [← hab, mul_one] }
end
lemma nat.prime_iff_prime {p : ℕ} : p.prime ↔ _root_.prime (p : ℕ) :=
⟨λ hp, ⟨pos_iff_ne_zero.1 hp.pos, mt is_unit_iff_dvd_one.1 hp.not_dvd_one,
λ a b, hp.dvd_mul.1⟩,
λ hp, ⟨nat.one_lt_iff_ne_zero_and_ne_one.2 ⟨hp.1, λ h1, hp.2.1 $ h1.symm ▸ is_unit_one⟩,
λ a h, let ⟨b, hab⟩ := h in
(hp.2.2 a b (hab ▸ dvd_refl _)).elim
(λ ha, or.inr (nat.dvd_antisymm h ha))
(λ hb, or.inl (have hpb : p = b, from nat.dvd_antisymm hb
(hab.symm ▸ dvd_mul_left _ _),
(nat.mul_right_inj (show 0 < p, from
nat.pos_of_ne_zero hp.1)).1 $
by rw [hpb, mul_comm, ← hab, hpb, mul_one]))⟩⟩
lemma nat.prime_iff_prime_int {p : ℕ} : p.prime ↔ _root_.prime (p : ℤ) :=
⟨λ hp, ⟨int.coe_nat_ne_zero_iff_pos.2 hp.pos, mt int.is_unit_iff_nat_abs_eq.1 hp.ne_one,
λ a b h, by rw [← int.dvd_nat_abs, int.coe_nat_dvd, int.nat_abs_mul, hp.dvd_mul] at h;
rwa [← int.dvd_nat_abs, int.coe_nat_dvd, ← int.dvd_nat_abs, int.coe_nat_dvd]⟩,
λ hp, nat.prime_iff_prime.2 ⟨int.coe_nat_ne_zero.1 hp.1,
mt nat.is_unit_iff.1 $ λ h, by simpa [h, not_prime_one] using hp,
λ a b, by simpa only [int.coe_nat_dvd, (int.coe_nat_mul _ _).symm] using hp.2.2 a b⟩⟩
/-- Maps an associate class of integers consisting of `-n, n` to `n : ℕ` -/
def associates_int_equiv_nat : associates ℤ ≃ ℕ :=
begin
refine ⟨λz, z.out.nat_abs, λn, associates.mk n, _, _⟩,
{ refine (assume a, quotient.induction_on' a $ assume a,
associates.mk_eq_mk_iff_associated.2 $ associated.symm $ ⟨norm_unit a, _⟩),
show normalize a = int.nat_abs (normalize a),
rw [int.coe_nat_abs_eq_normalize, normalize_idem] },
{ intro n, dsimp, rw [associates.out_mk ↑n,
← int.coe_nat_abs_eq_normalize, int.nat_abs_of_nat, int.nat_abs_of_nat] }
end
lemma int.prime.dvd_mul {m n : ℤ} {p : ℕ}
(hp : nat.prime p) (h : (p : ℤ) ∣ m * n) : p ∣ m.nat_abs ∨ p ∣ n.nat_abs :=
begin
apply (nat.prime.dvd_mul hp).mp,
rw ← int.nat_abs_mul,
exact int.coe_nat_dvd_left.mp h
end
lemma int.prime.dvd_mul' {m n : ℤ} {p : ℕ}
(hp : nat.prime p) (h : (p : ℤ) ∣ m * n) : (p : ℤ) ∣ m ∨ (p : ℤ) ∣ n :=
begin
rw [int.coe_nat_dvd_left, int.coe_nat_dvd_left],
exact int.prime.dvd_mul hp h
end
lemma int.prime.dvd_pow {n : ℤ} {k p : ℕ}
(hp : nat.prime p) (h : (p : ℤ) ∣ n ^ k) : p ∣ n.nat_abs :=
begin
apply @nat.prime.dvd_of_dvd_pow _ _ k hp,
rw ← int.nat_abs_pow,
exact int.coe_nat_dvd_left.mp h
end
lemma int.prime.dvd_pow' {n : ℤ} {k p : ℕ}
(hp : nat.prime p) (h : (p : ℤ) ∣ n ^ k) : (p : ℤ) ∣ n :=
begin
rw int.coe_nat_dvd_left,
exact int.prime.dvd_pow hp h
end
lemma prime_two_or_dvd_of_dvd_two_mul_pow_self_two {m : ℤ} {p : ℕ}
(hp : nat.prime p) (h : (p : ℤ) ∣ 2 * m ^ 2) : p = 2 ∨ p ∣ int.nat_abs m :=
begin
cases int.prime.dvd_mul hp h with hp2 hpp,
{ apply or.intro_left,
exact le_antisymm (nat.le_of_dvd zero_lt_two hp2) (nat.prime.two_le hp) },
{ apply or.intro_right,
rw [sq, int.nat_abs_mul] at hpp,
exact (or_self _).mp ((nat.prime.dvd_mul hp).mp hpp)}
end
instance nat.unique_units : unique (units ℕ) :=
{ default := 1, uniq := nat.units_eq_one }
open unique_factorization_monoid
theorem nat.factors_eq {n : ℕ} : factors n = n.factors :=
begin
cases n, { simp },
rw [← multiset.rel_eq, ← associated_eq_eq],
apply factors_unique (irreducible_of_factor) _,
{ rw [multiset.coe_prod, nat.prod_factors (nat.succ_pos _)],
apply factors_prod (nat.succ_ne_zero _) },
{ apply_instance },
{ intros x hx,
rw [nat.irreducible_iff_prime, ← nat.prime_iff],
exact nat.prime_of_mem_factors hx }
end
lemma nat.factors_multiset_prod_of_irreducible
{s : multiset ℕ} (h : ∀ (x : ℕ), x ∈ s → irreducible x) :
unique_factorization_monoid.factors (s.prod) = s :=
begin
rw [← multiset.rel_eq, ← associated_eq_eq],
apply (unique_factorization_monoid.factors_unique irreducible_of_factor h (factors_prod _)),
rw [ne.def, multiset.prod_eq_zero_iff],
intro con,
exact not_irreducible_zero (h 0 con),
end
namespace multiplicity
lemma finite_int_iff_nat_abs_finite {a b : ℤ} : finite a b ↔ finite a.nat_abs b.nat_abs :=
by simp only [finite_def, ← int.nat_abs_dvd_abs_iff, int.nat_abs_pow]
lemma finite_int_iff {a b : ℤ} : finite a b ↔ (a.nat_abs ≠ 1 ∧ b ≠ 0) :=
by rw [finite_int_iff_nat_abs_finite, finite_nat_iff, pos_iff_ne_zero, int.nat_abs_ne_zero]
instance decidable_nat : decidable_rel (λ a b : ℕ, (multiplicity a b).dom) :=
λ a b, decidable_of_iff _ finite_nat_iff.symm
instance decidable_int : decidable_rel (λ a b : ℤ, (multiplicity a b).dom) :=
λ a b, decidable_of_iff _ finite_int_iff.symm
end multiplicity
lemma induction_on_primes {P : ℕ → Prop} (h₀ : P 0) (h₁ : P 1)
(h : ∀ p a : ℕ, p.prime → P a → P (p * a)) (n : ℕ) : P n :=
begin
apply unique_factorization_monoid.induction_on_prime,
exact h₀,
{ intros n h,
rw nat.is_unit_iff.1 h,
exact h₁, },
{ intros a p _ hp ha,
exact h p a (nat.prime_iff_prime.2 hp) ha, },
end
lemma int.associated_nat_abs (k : ℤ) : associated k k.nat_abs :=
associated_of_dvd_dvd (int.coe_nat_dvd_right.mpr (dvd_refl _)) (int.nat_abs_dvd.mpr (dvd_refl _))
lemma int.prime_iff_nat_abs_prime {k : ℤ} : prime k ↔ nat.prime k.nat_abs :=
begin
rw nat.prime_iff_prime_int,
rw prime_iff_of_associated (int.associated_nat_abs k),
end
theorem int.associated_iff_nat_abs {a b : ℤ} : associated a b ↔ a.nat_abs = b.nat_abs :=
begin
rw [←dvd_dvd_iff_associated, ←int.nat_abs_dvd_abs_iff, ←int.nat_abs_dvd_abs_iff,
dvd_dvd_iff_associated],
exact associated_iff_eq,
end
lemma int.associated_iff {a b : ℤ} : associated a b ↔ (a = b ∨ a = -b) :=
begin
rw int.associated_iff_nat_abs,
exact int.nat_abs_eq_nat_abs_iff,
end
|
program t
implicit none
logical::p=.false.
p=0==0
print '(l)',p
end program t
|
theorem add_zero : x + 0 = x := by
rfl
theorem add_succ : x + Nat.succ y = Nat.succ (x + y) := by
rfl
theorem one_Eq_succ_zero : 1 = Nat.succ 0 := by
rfl
--set_option hygienicIntro false in
theorem zero_add : 0 + x = x := by
induction x with | succ _ ih => _ | _ => _
rfl
rewrite add_succ
apply congrArg -- or just `rw ih`/`rw v_0`
assumption
theorem add_assoc (a b c : Nat) : (a + b) + c = a + (b + c) := by
induction c with | succ _ ih => _ | _ => _
rewrite add_zero
rewrite add_zero
rfl
rewrite add_succ
rewrite add_succ
rewrite add_succ
rewrite ih
rfl
theorem succ_add (a b : Nat) : Nat.succ a + b = Nat.succ (a + b) := by
induction b with | succ _ ih => _ | _ => _
rfl
rewrite add_succ
rewrite add_succ
rewrite ih
rfl
theorem add_comm (a b : Nat) : a + b = b + a := by
induction b with | succ _ ih => _ | _ => _
rewrite zero_add
rfl
rewrite add_succ
rewrite succ_add
rewrite ih
rfl
theorem succ_Eq_add_one (n : Nat) : Nat.succ n = n + 1 := by
rewrite one_Eq_succ_zero
rewrite add_succ
rfl
theorem add_rightComm (a b c : Nat) : a + b + c = a + c + b := by
rewrite add_assoc
rewrite add_comm b
rewrite add_assoc
rfl
|
\documentclass[simplex.tex]{subfiles}
% NO NEED TO INPUT PREAMBLES HERE
% packages are inherited; you can compile this on its own
\begin{document}
\subsection{Robust Law of Large Graphs}
We had theorems for the ML$q$E under the exponential distribution. Actually the results can be generalized to a broader class of distribution families, and even a different entry-wise robust estimator other than ML$q$E with the following conditions:
\begin{compactenum}
\item Let $A_{ij} \stackrel{ind}{\sim} (1-\epsilon) f_{P_{ij}} + \epsilon f_{C_{ij}}$, then $E[(A_{ij} - E[\hat{P}_{ij}^{(1)}])^k] \le \mathrm{const} \cdot k!$, where $\hat{P}^{(1)}$ is the entry-wise MLE as defined before;
This is to ensure the that observations will not deviate from the expectation too far away, such that the concentration inequality can apply.
\item There exists $C_0(P_{ij}, \epsilon) > 0$ such that under the contaminated model with $C > C_0(P_{ij}, \epsilon)$,
\[
\lim_{m \to \infty} \left| E[\hat{P}_{ij}] - P_{ij} \right| <
\lim_{m \to \infty} \left| E[\hat{P}^{(1)}_{ij}] - P_{ij} \right|;
\]\\
It requires the contamination of the model to be large enough (a restriction on the distribution) and $\hat{P}$ to be robust enough with respect to the contamination (a condition on the estimator).
\item $\hat{P}_{ij} \le \mathrm{const} \cdot \hat{P}_{ij}^{(1)}$; (This might be generalized to with high probability later)\\
Since we use the results of $\hat{P}^{(1)}$ to bound $\hat{P}^{(q)}$, the proof can apply directly with this condition for an arbitrary $\hat{P}$.
\item $\mathrm{Var}(\hat{P}_{ij}) = O(m^{-1})$, where $m$ is the number of observations.\\
We will get exactly the same results under this condition. However, even if the variance of the new estimator is not of order $O(m^{-1})$, we will get similar results with a different term related to $m$.
\end{compactenum}
\clearpage
\end{document}
|
#' Converters
#'
#' Converter methods between memuse and base R objects.
#'
#' @details
#' These methods convert numeric, \code{object_size}, and string (character)
#' objects to/from \code{memuse} objects.
#'
#' \code{as.numeric(x)} for a memuse object \code{x} is just sugar for
#' \code{mu.size(x, as.is=FALSE)}
#'
#' Strings must be of the same form as the printed output of a a memuse object.
#' For example, "100 KiB" is valid, but "100 (KiB)" is not. As always, case of
#' the unit is ignored, and so "100 kib" would be valid as well.
#'
#' @param x
#' Numeric value, object_size data, or appropriate string (see details
#' section for more information).
#' @param ...
#' Additional arguments.
#'
#' @return
#' Returns a character, numeric, or \code{memuse} object, depending on the call.
#'
#' @examples
#' \dontrun{
#' as.memuse(10)
#' }
#'
#' @seealso \code{ \link{memuse-class} \link{Accessors} }
#' @keywords Methods
#' @name Converters
#' @rdname converters
NULL
#' @rdname converters
#' @export
setGeneric(name="as.memuse",
function(x, ...)
standardGeneric("as.memuse"),
package="memuse"
)
#-------------------------------------------------
# TO memuse
#-------------------------------------------------
#' @param unit
#' \code{string}; the unit of storage, such as "MiB" or "MB",
#' depending on prefix. Case is ignored.
#' @param prefix
#' \code{string}; the unit prefix, namely IEC or SI. Case
#' is ignored.
#' @param names
#' \code{string}; control for whether the unit names should
#' be printed out or their abbreviation should be used. Options are "long" and
#' "short", respectively. Case is ignored.
#'
#' @rdname converters
#' @export
setMethod("as.memuse", signature(x="numeric"),
function(x, unit="best", prefix="IEC", names="short")
{
internal.mu(size=x, unit=unit, unit.prefix=prefix, unit.names=names)
}
)
#' @rdname converters
#' @export
setMethod("as.memuse", signature(x="object_size"),
function(x, unit="best", prefix="IEC", names="short")
{
as.memuse(x=unclass(x), unit=unit, unit.prefix=prefix, unit.names=names)
}
)
#' @rdname converters
#' @export
setMethod("as.memuse", signature(x="character"),
function(x, unit="best", prefix="IEC", names="short")
{
y <- unlist(strsplit(x=x, split=" "))
if (length(y) != 2)
stop("malformed string; can not convert to a memuse object")
size <- as.numeric(y[1L])
unit <- y[2L]
internal.mu(size=size, unit=unit, unit.prefix=prefix, unit.names=names)
}
)
#-------------------------------------------------
# FROM memuse
#-------------------------------------------------
#' @rdname converters
#' @export
setMethod("as.character", signature(x="memuse"),
function(x, ...)
{
utils::capture.output(print(x))
}
)
#' @rdname converters
#' @export
setMethod("as.numeric", signature(x="memuse"),
function(x, ...)
{
mu.size(x, as.is=FALSE)
}
)
|
theory cw1q1
imports Main
begin
lemma 1: "A \<or> A \<longrightarrow> A"
apply(rule impI)
apply(erule disjE)
by assumption
lemma 2: "A \<and> A \<longrightarrow> A"
apply(rule impI)
apply(erule conjE)
by assumption
lemma 3: "(\<not>P \<or> R) \<longrightarrow> (P \<longrightarrow> R)"
apply(rule impI)+
apply(erule disjE)
apply(erule notE)
by assumption
lemma 4: "(\<exists>x. P x \<and> Q x) \<longrightarrow> (\<exists>x. P x) \<and> (\<exists>x. Q x)"
apply(rule impI)
apply(rule conjI)
apply(erule exE)+
apply(erule conjE)+
apply(rule exI)
apply(assumption)
apply(erule exE)
apply(erule conjE)
apply(rule exI)
by assumption
lemma 5: "(\<not>(\<exists>x. \<not>P x) \<or> R) \<longrightarrow> ((\<exists>x. \<not>P x) \<longrightarrow> R)"
apply(rule impI)+
apply(erule disjE)
apply(erule exE)
apply(erule notE)
apply(rule exI)
apply(rule notI)
apply(erule notE)
apply(assumption)
apply(erule exE)
by assumption
lemma 6: "(\<not>(\<exists>x. \<not>P x) \<or> R) \<longrightarrow> ((\<exists>x. \<not>P x) \<longrightarrow> R)"
apply(rule impI)+
apply(erule disjE)
apply(erule exE)
apply(erule notE)
apply(rule exI)
apply(rule notI)
apply(erule notE)
apply(assumption)
apply(erule exE)
by assumption
lemma 7: "(\<forall>x. P x) \<longrightarrow> \<not>(\<exists>x. \<not>P x)"
apply(rule impI)
apply(rule notI)
apply(erule exE)
apply(erule allE)
apply(erule notE)
by assumption
lemma 8: "P \<or> \<not>P"
apply(rule disjCI)
apply(rule ccontr)
apply(erule notE)
by assumption
lemma 9: "\<not>\<not>P \<longrightarrow> P"
apply(rule impI)
apply(rule mp)
apply(rule impI)
apply auto
sorry
lemma 10: "(\<not>P \<longrightarrow> P) \<longrightarrow> P"
lemma 11: "(\<not>P \<longrightarrow> False)\<longrightarrow>P"
lemma 12: "(\<not>(\<forall>x. P x \<or> R x)) = (\<exists>x. \<not>P x \<and> \<not>R x)"
lemma 13: "(\<exists>x. P x \<or> R x) = (\<not>((\<forall>x. \<not>P x) \<and> \<not>(\<exists>x. R x)))"
end |
[STATEMENT]
lemma isOK_check_all_combinations [simp]:
"isOK (check_all_combinations c xs) \<longleftrightarrow> (\<forall>x \<in> set xs. \<forall>y \<in> set xs. isOK (c x y))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. isOK (check_all_combinations c xs) = (\<forall>x\<in>set xs. \<forall>y\<in>set xs. isOK (c x y))
[PROOF STEP]
unfolding check_all_combinations_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. isOK (try forallM (\<lambda>x. try forallM (c x) xs catch (\<lambda>x. Inl (snd x))) xs catch (\<lambda>x. Inl (snd x))) = (\<forall>x\<in>set xs. \<forall>y\<in>set xs. isOK (c x y))
[PROOF STEP]
by simp |
module HasDecidableVacuousDischarge where
open import OscarPrelude
--open import HasVacuousDischarge
open import HasSubstantiveDischarge
open import HasNegation
record HasDecidableVacuousDischarge (A : Set) : Set₁
where
field
-- ⦃ hasVacuousDischarge ⦄ : HasVacuousDischarge A
⦃ hasNegation ⦄ : HasNegation A
⦃ hasSubstantiveDischarge ⦄ : HasSubstantiveDischarge A
◁?_ : (x : List A) → Dec $ ◁ x
open HasDecidableVacuousDischarge ⦃ … ⦄ public
{-# DISPLAY HasDecidableVacuousDischarge.◁?_ _ = ◁?_ #-}
|
[STATEMENT]
lemma ordinal_plus_not_0: "(0 < x + y) = (0 < x \<or> 0 < (y::ordinal))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (0 < x + y) = (0 < x \<or> 0 < y)
[PROOF STEP]
apply safe
[PROOF STATE]
proof (prove)
goal (3 subgoals):
1. \<lbrakk>0 < x + 0; y = 0\<rbrakk> \<Longrightarrow> 0 < x
2. 0 < x \<Longrightarrow> 0 < x + y
3. 0 < y \<Longrightarrow> 0 < x + y
[PROOF STEP]
apply simp
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. 0 < x \<Longrightarrow> 0 < x + y
2. 0 < y \<Longrightarrow> 0 < x + y
[PROOF STEP]
apply (erule order_less_le_trans, rule ordinal_le_plusR)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. 0 < y \<Longrightarrow> 0 < x + y
[PROOF STEP]
apply (erule order_less_le_trans, rule ordinal_le_plusL)
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done |
//==================================================================================================
/*!
@file
@copyright 2016 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_TWO_ADD_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_TWO_ADD_HPP_INCLUDED
#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{
/*!
@ingroup group-arithmetic
Function object implementing two_add capabilities
For any two reals @c x and @c y two_add computes two reals (in an std::pair)
@c r0 and @c r1 such that:
@code
r0 = x + y
r1 = r0 -(x + y)
@endcode
using perfect arithmetic.
Its main usage is to be able to compute
sum of reals and the residual error using IEEE 754 arithmetic.
**/
std::pair<Value, Value> two_add(Value const& x, Value const& y);
} }
#endif
#include <boost/simd/function/scalar/two_add.hpp>
#include <boost/simd/function/simd/two_add.hpp>
#endif
|
function linplus_test5705 ( )
%*****************************************************************************80
%
%% TEST5705 tests R8SP_IJ_TO_K.
%
% Licensing:
%
% This code is distributed under the GNU LGPL license.
%
% Modified:
%
% 14 March 2009
%
% Author:
%
% John Burkardt
%
m = 7;
n = 5;
nz_num = 10;
col = [ 2, 5, 1, 5, 1, 2, 3, 4, 4, 1 ];
row = [ 1, 1, 2, 2, 4, 4, 4, 5, 6, 7 ];
fprintf ( 1, '\n' );
fprintf ( 1, 'TEST5705\n' );
fprintf ( 1, ' R8SP_IJ_TO_K returns the R8SP index of (I,J).\n' );
fprintf ( 1, '\n' );
fprintf ( 1, ' Matrix rows M = %8d\n', m );
fprintf ( 1, ' Matrix columns N = %8d\n', n );
fprintf ( 1, ' Matrix nonzeros = %8d\n', nz_num );
check = r8sp_check ( m, n, nz_num, row, col );
if ( ~check )
fprintf ( 1, '\n' );
fprintf ( 1, 'R8SP_CHECK - Error!\n' );
fprintf ( 1, ' The matrix is not in the proper sorted format.\n' );
return
end
fprintf ( 1, '\n' );
fprintf ( 1, ' I J K\n' );
fprintf ( 1, '\n' );
for i = 1 : m
for j = 1 : n
k = r8sp_ij_to_k ( nz_num, row, col, i, j );
fprintf ( 1, ' %8d %8d %8d\n', i, j, k );
end
end
return
end
|
A collected edition of Wilde 's works , published in 1908 and edited by Robert Ross , helped to restore his reputation as an author . Alexander presented another revival of The Importance at the St James 's in 1909 , when he and Aynesworth reprised their original roles ; the revival ran for 316 performances . Max Beerbohm said that the play was sure to become a classic of the English repertory , and that its humour was as fresh then as when it had been written , adding that the actors had " worn as well as the play " .
|
If $t$ is a measurable set with measure equal to the measure of the whole space, then the intersection of $t$ with any measurable set $s$ has measure equal to the measure of $s$. |
[STATEMENT]
lemma K5_L:
assumes \<open>Ax5 \<le> A\<close>
shows \<open>A \<turnstile> L i (K i p) \<^bold>\<longrightarrow> K i p\<close>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. A \<turnstile> L i (K i p) \<^bold>\<longrightarrow> K i p
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. A \<turnstile> L i (K i p) \<^bold>\<longrightarrow> K i p
[PROOF STEP]
have \<open>A \<turnstile> L i (\<^bold>\<not> p) \<^bold>\<longrightarrow> K i (L i (\<^bold>\<not> p))\<close>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. A \<turnstile> L i (\<^bold>\<not> p) \<^bold>\<longrightarrow> K i (L i (\<^bold>\<not> p))
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
Ax5 \<le> A
goal (1 subgoal):
1. A \<turnstile> L i (\<^bold>\<not> p) \<^bold>\<longrightarrow> K i (L i (\<^bold>\<not> p))
[PROOF STEP]
by (auto intro: Ax Ax5.intros)
[PROOF STATE]
proof (state)
this:
A \<turnstile> L i (\<^bold>\<not> p) \<^bold>\<longrightarrow> K i (L i (\<^bold>\<not> p))
goal (1 subgoal):
1. A \<turnstile> L i (K i p) \<^bold>\<longrightarrow> K i p
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
A \<turnstile> L i (\<^bold>\<not> p) \<^bold>\<longrightarrow> K i (L i (\<^bold>\<not> p))
[PROOF STEP]
have \<open>A \<turnstile> L i (\<^bold>\<not> p) \<^bold>\<longrightarrow> K i (\<^bold>\<not> K i p)\<close>
[PROOF STATE]
proof (prove)
using this:
A \<turnstile> L i (\<^bold>\<not> p) \<^bold>\<longrightarrow> K i (L i (\<^bold>\<not> p))
goal (1 subgoal):
1. A \<turnstile> L i (\<^bold>\<not> p) \<^bold>\<longrightarrow> K i (\<^bold>\<not> K i p)
[PROOF STEP]
using K_LK
[PROOF STATE]
proof (prove)
using this:
A \<turnstile> L i (\<^bold>\<not> p) \<^bold>\<longrightarrow> K i (L i (\<^bold>\<not> p))
?A \<turnstile> L ?i (\<^bold>\<not> ?p) \<^bold>\<longrightarrow> \<^bold>\<not> K ?i ?p
goal (1 subgoal):
1. A \<turnstile> L i (\<^bold>\<not> p) \<^bold>\<longrightarrow> K i (\<^bold>\<not> K i p)
[PROOF STEP]
by (metis K_map K_trans R1)
[PROOF STATE]
proof (state)
this:
A \<turnstile> L i (\<^bold>\<not> p) \<^bold>\<longrightarrow> K i (\<^bold>\<not> K i p)
goal (1 subgoal):
1. A \<turnstile> L i (K i p) \<^bold>\<longrightarrow> K i p
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
A \<turnstile> L i (\<^bold>\<not> p) \<^bold>\<longrightarrow> K i (\<^bold>\<not> K i p)
goal (1 subgoal):
1. A \<turnstile> L i (K i p) \<^bold>\<longrightarrow> K i p
[PROOF STEP]
have \<open>A \<turnstile> (P \<^bold>\<longrightarrow> Q) \<^bold>\<longrightarrow> \<^bold>\<not> Q \<^bold>\<longrightarrow> \<^bold>\<not> P\<close> for P Q
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. A \<turnstile> (P \<^bold>\<longrightarrow> Q) \<^bold>\<longrightarrow> \<^bold>\<not> Q \<^bold>\<longrightarrow> \<^bold>\<not> P
[PROOF STEP]
by (auto intro: A1)
[PROOF STATE]
proof (state)
this:
A \<turnstile> (?P \<^bold>\<longrightarrow> ?Q) \<^bold>\<longrightarrow> \<^bold>\<not> ?Q \<^bold>\<longrightarrow> \<^bold>\<not> ?P
goal (1 subgoal):
1. A \<turnstile> L i (K i p) \<^bold>\<longrightarrow> K i p
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
A \<turnstile> L i (\<^bold>\<not> p) \<^bold>\<longrightarrow> K i (\<^bold>\<not> K i p)
A \<turnstile> (?P \<^bold>\<longrightarrow> ?Q) \<^bold>\<longrightarrow> \<^bold>\<not> ?Q \<^bold>\<longrightarrow> \<^bold>\<not> ?P
[PROOF STEP]
have \<open>A \<turnstile> \<^bold>\<not> K i (\<^bold>\<not> K i p) \<^bold>\<longrightarrow> \<^bold>\<not> L i (\<^bold>\<not> p)\<close>
[PROOF STATE]
proof (prove)
using this:
A \<turnstile> L i (\<^bold>\<not> p) \<^bold>\<longrightarrow> K i (\<^bold>\<not> K i p)
A \<turnstile> (?P \<^bold>\<longrightarrow> ?Q) \<^bold>\<longrightarrow> \<^bold>\<not> ?Q \<^bold>\<longrightarrow> \<^bold>\<not> ?P
goal (1 subgoal):
1. A \<turnstile> L i (K i p) \<^bold>\<longrightarrow> \<^bold>\<not> L i (\<^bold>\<not> p)
[PROOF STEP]
using R1
[PROOF STATE]
proof (prove)
using this:
A \<turnstile> L i (\<^bold>\<not> p) \<^bold>\<longrightarrow> K i (\<^bold>\<not> K i p)
A \<turnstile> (?P \<^bold>\<longrightarrow> ?Q) \<^bold>\<longrightarrow> \<^bold>\<not> ?Q \<^bold>\<longrightarrow> \<^bold>\<not> ?P
\<lbrakk>?A \<turnstile> ?p; ?A \<turnstile> ?p \<^bold>\<longrightarrow> ?q\<rbrakk> \<Longrightarrow> ?A \<turnstile> ?q
goal (1 subgoal):
1. A \<turnstile> L i (K i p) \<^bold>\<longrightarrow> \<^bold>\<not> L i (\<^bold>\<not> p)
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
A \<turnstile> L i (K i p) \<^bold>\<longrightarrow> \<^bold>\<not> L i (\<^bold>\<not> p)
goal (1 subgoal):
1. A \<turnstile> L i (K i p) \<^bold>\<longrightarrow> K i p
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
A \<turnstile> L i (K i p) \<^bold>\<longrightarrow> \<^bold>\<not> L i (\<^bold>\<not> p)
[PROOF STEP]
have \<open>A \<turnstile> \<^bold>\<not> K i (\<^bold>\<not> K i p) \<^bold>\<longrightarrow> K i p\<close>
[PROOF STATE]
proof (prove)
using this:
A \<turnstile> L i (K i p) \<^bold>\<longrightarrow> \<^bold>\<not> L i (\<^bold>\<not> p)
goal (1 subgoal):
1. A \<turnstile> L i (K i p) \<^bold>\<longrightarrow> K i p
[PROOF STEP]
using K_L_dual R1 K_trans
[PROOF STATE]
proof (prove)
using this:
A \<turnstile> L i (K i p) \<^bold>\<longrightarrow> \<^bold>\<not> L i (\<^bold>\<not> p)
?A \<turnstile> \<^bold>\<not> L ?i (\<^bold>\<not> ?p) \<^bold>\<longrightarrow> K ?i ?p
\<lbrakk>?A \<turnstile> ?p; ?A \<turnstile> ?p \<^bold>\<longrightarrow> ?q\<rbrakk> \<Longrightarrow> ?A \<turnstile> ?q
?A \<turnstile> (?p \<^bold>\<longrightarrow> ?q) \<^bold>\<longrightarrow> (?q \<^bold>\<longrightarrow> ?r) \<^bold>\<longrightarrow> ?p \<^bold>\<longrightarrow> ?r
goal (1 subgoal):
1. A \<turnstile> L i (K i p) \<^bold>\<longrightarrow> K i p
[PROOF STEP]
by metis
[PROOF STATE]
proof (state)
this:
A \<turnstile> L i (K i p) \<^bold>\<longrightarrow> K i p
goal (1 subgoal):
1. A \<turnstile> L i (K i p) \<^bold>\<longrightarrow> K i p
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
A \<turnstile> L i (K i p) \<^bold>\<longrightarrow> K i p
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
A \<turnstile> L i (K i p) \<^bold>\<longrightarrow> K i p
goal (1 subgoal):
1. A \<turnstile> L i (K i p) \<^bold>\<longrightarrow> K i p
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
A \<turnstile> L i (K i p) \<^bold>\<longrightarrow> K i p
goal:
No subgoals!
[PROOF STEP]
qed |
import QL.FOL.Tait.search_tree QL.FOL.Tait.semantics
universes u v
namespace fol
open_locale logic_symbol aclogic
open subformula
variables {L : language.{u}} {m : ℕ}
theorem completeness_of_countable_language [∀ k, encodable (L.fn k)] [∀ k, encodable (L.pr k)] {T : Theory L} {σ : sentence L} :
T ⊧₀ σ → T ⊢ σ :=
begin
have s : T ⊧₀ σ → to_tait '' T ⊧ σ.to_tait,
{ intros h S hh, simpa using @h S (by { intros p hp, simpa using hh (set.mem_image_of_mem _ hp) }) },
have complete : to_tait '' T ⊧ σ.to_tait → to_tait '' T ⊢ σ.to_tait, from Tait.completeness_of_countable_language,
have b : to_tait '' T ⊢ to_tait σ → T ⊢ σ, from provable.of_Tait_provable,
refine (λ h, (b $ complete $ s h))
end
end fol
|
. West End Girls ( Kicking in Chairs )
|
/-
Copyright (c) 2021 OpenAI. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kunhao Zheng, Stanislas Polu, David Renshaw, OpenAI GPT-f
-/
import mathzoo.imports.miniF2F
open_locale nat rat real big_operators topological_space
theorem mathd_algebra_176
(x : ℝ) :
(x + 1)^2 * x = x^3 + 2 * x^2 + x :=
begin
ring_nf,
end |
= = = Management by The National Trust = = =
|
# General visualization utils
"""
$(SIGNATURES)
Initialize empty visualizer window with home axis. New browser window will be opened based on `show=true`.
"""
function startDefaultVisualization(;show::Bool=true,
draworigin::Bool=true,
originscale::Float64=1.0 )
#
global drawtransform
viz = MeshCat.Visualizer()
if draworigin
setobject!( viz[:origin], Triad(originscale) )
settransform!( viz[:origin], drawtransform ∘ (Translation(0.0, 0.0, 0.0) ∘ LinearMap( CTs.Quat(1.0,0,0,0))) )
end
# open a new browser tab if required
show && open(viz)
return viz
end
# tagsOnPoses = Dict{Symbol, Vector{TagkTl}}()
#
|
-- |
-- Copyright: (C) 2013 Amgen, Inc.
--
-- Provides a /shallow/ view of a 'SEXP' R value as an algebraic datatype. This
-- is useful to define functions over R values in Haskell with pattern matching.
-- For example:
--
-- @
-- toPair :: SEXP a -> (SomeSEXP, SomeSEXP)
-- toPair (hexp -> List _ (Just car) (Just cdr)) = (SomeSEXP car, SomeSEXP cdr)
-- toPair (hexp -> Lang car (Just cdr)) = (SomeSEXP car, SomeSEXP cdr)
-- toPair s = error $ "Cannot extract pair from object of type " ++ typeOf s
-- @
--
-- (See 'Foreign.R.SomeSEXP' for why we need to use it here.)
--
-- The view is said to be 'shallow' because it only unfolds the head of the
-- R value into an algebraic datatype. In this way, functions producing views
-- can be written non-recursively, hence inlined at all call sites and
-- simplified away. When produced by a view function in a pattern match,
-- allocation of the view can be compiled away and hence producing a view can be
-- done at no runtime cost. In fact, pattern matching on a view in this way is
-- more efficient than using the accessor functions defined in "Foreign.R",
-- because we avoid the overhead of calling one or more FFI functions entirely.
--
-- 'HExp' is the /view/ and 'hexp' is the /view function/ that projects 'SEXP's
-- into 'HExp' views.
{-# LANGUAGE CPP #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE PolyKinds #-}
#if __GLASGOW_HASKELL__ >= 708
{-# LANGUAGE RoleAnnotations #-}
#endif
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE ViewPatterns #-}
module Language.R.HExp
( HExp(..)
, (===)
, hexp
, unhexp
, vector
) where
import Control.Applicative
import Control.Memory.Region (V)
import Control.Monad.R.Class
import qualified Foreign.R as R
import Foreign.R (SEXP, SomeSEXP(..), SEXPTYPE, withProtected)
import Foreign.R.Constraints
import Internal.Error
import qualified Language.R.Globals as H
import qualified Data.Vector.SEXP as Vector
import Control.Monad ((<=<), guard, void)
import Control.Monad.Primitive ( unsafeInlineIO )
import Data.Int (Int32)
import Data.Word (Word8)
import Data.Complex
import Data.Maybe (isJust)
import Data.Type.Equality (TestEquality(..), (:~:)(Refl))
import GHC.Ptr (Ptr(..))
import Foreign.Storable
import Foreign.C -- for hsc2hs
import Foreign (castPtr)
import Unsafe.Coerce (unsafeCoerce)
-- Fixes redundant import warning >= 7.10 without CPP
import Prelude
#define USE_RINTERNALS
#include <R.h>
#include <Rinternals.h>
#let alignment t = "%lu", (unsigned long)offsetof(struct {char x__; t (y__); }, y__)
-- Use explicit UNPACK pragmas rather than -funbox-strict-fields in order to get
-- warnings if a field is not unpacked when we expect it to.
-- | A view of R's internal 'SEXP' structure as an algebraic datatype. Because
-- this is in fact a GADT, the use of named record fields is not possible here.
-- Named record fields give rise to functions for whom it is not possible to
-- assign a reasonable type (existentially quantified type variables would
-- escape).
--
-- Note further that Haddock does not currently support constructor comments
-- when using the GADT syntax.
type role HExp phantom nominal
data HExp :: * -> SEXPTYPE -> * where
-- Primitive types. The field names match those of <RInternals.h>.
Nil :: HExp s 'R.Nil
-- Fields: pname (is Nil for R_UnboundValue), value, internal.
Symbol :: (a :∈ ['R.Char, 'R.Nil])
=> SEXP s a
-> SEXP s b
-> SEXP s c
-> HExp s 'R.Symbol
-- Fields: carval, cdrval, tagval.
List :: (R.IsPairList b, c :∈ ['R.Symbol, 'R.Nil])
=> SEXP s a
-> SEXP s b
-> SEXP s c
-> HExp s 'R.List
-- Fields: frame, enclos, hashtab.
Env :: (R.IsPairList a, b :∈ ['R.Env, 'R.Nil], c :∈ ['R.Vector, 'R.Nil])
=> SEXP s a
-> SEXP s b
-> SEXP s c
-> HExp s 'R.Env
-- Fields: formals, body, env.
Closure :: (R.IsPairList a)
=> SEXP s a
-> SEXP s b
-> SEXP s 'R.Env
-> HExp s 'R.Closure
-- Fields: value, expr, env.
-- Once an promise has been evaluated, the environment is set to NULL.
Promise :: (R.IsExpression b, c :∈ ['R.Env, 'R.Nil])
=> SEXP s a
-> SEXP s b
-> SEXP s c
-> HExp s 'R.Promise
-- Derived types. These types don't have their own 'struct' declaration in
-- <Rinternals.h>.
-- Fields: function, args.
Lang :: (R.IsExpression a, R.IsPairList b)
=> SEXP s a
-> SEXP s b
-> HExp s 'R.Lang
-- Fields: offset.
Special :: {-# UNPACK #-} !Int32
-> HExp s 'R.Special
-- Fields: offset.
Builtin :: {-# UNPACK #-} !Int32
-> HExp s 'R.Builtin
Char :: {-# UNPACK #-} !(Vector.Vector 'R.Char Word8)
-> HExp s 'R.Char
Logical :: {-# UNPACK #-} !(Vector.Vector 'R.Logical R.Logical)
-> HExp s 'R.Logical
Int :: {-# UNPACK #-} !(Vector.Vector 'R.Int Int32)
-> HExp s 'R.Int
Real :: {-# UNPACK #-} !(Vector.Vector 'R.Real Double)
-> HExp s 'R.Real
Complex :: {-# UNPACK #-} !(Vector.Vector 'R.Complex (Complex Double))
-> HExp s 'R.Complex
String :: {-# UNPACK #-} !(Vector.Vector 'R.String (SEXP V 'R.Char))
-> HExp s 'R.String
-- Fields: pairlist of promises.
DotDotDot :: (R.IsPairList a)
=> SEXP s a
-> HExp s 'R.List
-- Fields: truelength, content.
Vector :: {-# UNPACK #-} !Int32
-> {-# UNPACK #-} !(Vector.Vector 'R.Vector (SomeSEXP V))
-> HExp s 'R.Vector
-- Fields: truelength, content.
Expr :: {-# UNPACK #-} !Int32
-> {-# UNPACK #-} !(Vector.Vector 'R.Expr (SomeSEXP V))
-> HExp s 'R.Expr
Bytecode :: HExp s 'R.Bytecode -- TODO
-- Fields: pointer, protectionValue, tagval
ExtPtr :: Ptr ()
-> SEXP s b
-> SEXP s 'R.Symbol
-> HExp s 'R.ExtPtr
-- Fields: key, value, finalizer, next.
WeakRef :: ( a :∈ ['R.Env, 'R.ExtPtr, 'R.Nil]
, c :∈ ['R.Closure, 'R.Builtin, 'R.Special, 'R.Nil]
, d :∈ ['R.WeakRef, 'R.Nil] )
=> SEXP s a
-> SEXP s b
-> SEXP s c
-> SEXP s d
-> HExp s 'R.WeakRef
Raw :: {-# UNPACK #-} !(Vector.Vector 'R.Raw Word8)
-> HExp s 'R.Raw
-- Fields: tagval.
S4 :: SEXP s a
-> HExp s 'R.S4
-- 'Im a hack
instance Eq (HExp s a) where
(==) = (===)
-- | Heterogeneous equality.
(===) :: TestEquality f => f a -> f b -> Bool
x === y = isJust $ testEquality x y
-- | Wrapper for partially applying a type synonym.
newtype E s a = E (SEXP s a)
instance TestEquality (E s) where
testEquality (E x@(hexp -> t1)) (E y@(hexp -> t2)) =
(guard (R.unsexp x == R.unsexp y) >> return (unsafeCoerce Refl)) <|>
testEquality t1 t2
instance TestEquality (HExp s) where
testEquality Nil Nil = return Refl
testEquality (Symbol pname1 value1 internal1) (Symbol pname2 value2 internal2) = do
void $ testEquality (E pname1) (E pname2)
void $ testEquality (E value1) (E value2)
void $ testEquality (E internal1) (E internal2)
return Refl
testEquality (List carval1 cdrval1 tagval1) (List carval2 cdrval2 tagval2) = do
void $ testEquality (E carval1) (E carval2)
void $ testEquality (E cdrval1) (E cdrval2)
void $ testEquality (E tagval1) (E tagval2)
return Refl
testEquality (Env frame1 enclos1 hashtab1) (Env frame2 enclos2 hashtab2) = do
void $ testEquality (E frame1) (E frame2)
void $ testEquality (E enclos1) (E enclos2)
void $ testEquality (E hashtab1) (E hashtab2)
return Refl
testEquality (Closure formals1 body1 env1) (Closure formals2 body2 env2) = do
void $ testEquality (E formals1) (E formals2)
void $ testEquality (E body1) (E body2)
void $ testEquality (E env1) (E env2)
return Refl
testEquality (Promise value1 expr1 env1) (Promise value2 expr2 env2) = do
void $ testEquality (E value1) (E value2)
void $ testEquality (E expr1) (E expr2)
void $ testEquality (E env1) (E env2)
return Refl
testEquality (Lang carval1 cdrval1) (Lang carval2 cdrval2) = do
void $ testEquality (E carval1) (E carval2)
void $ testEquality (E cdrval1) (E cdrval2)
return Refl
testEquality (Special offset1) (Special offset2) = do
guard $ offset1 == offset2
return Refl
testEquality (Builtin offset1) (Builtin offset2) = do
guard $ offset1 == offset2
return Refl
testEquality (Char vec1) (Char vec2) = do
guard $ vec1 == vec2
return Refl
testEquality (Int vec1) (Int vec2) = do
guard $ vec1 == vec2
return Refl
testEquality (Real vec1) (Real vec2) = do
guard $ vec1 == vec2
return Refl
testEquality (String vec1) (String vec2) = do
guard $ vec1 == vec2
return Refl
testEquality (Complex vec1) (Complex vec2) = do
guard $ vec1 == vec2
return Refl
testEquality (DotDotDot pairlist1) (DotDotDot pairlist2) = do
void $ testEquality (E pairlist1) (E pairlist2)
return Refl
testEquality (Vector truelength1 vec1) (Vector truelength2 vec2) = do
let eq (SomeSEXP s1) (SomeSEXP s2) = isJust $ testEquality (E s1) (E s2)
guard $ truelength1 == truelength2
guard $ and $ zipWith eq (Vector.toList vec1) (Vector.toList vec2)
return Refl
testEquality (Expr truelength1 vec1) (Expr truelength2 vec2) = do
let eq (SomeSEXP s1) (SomeSEXP s2) = isJust $ testEquality (E s1) (E s2)
guard $ truelength1 == truelength2
guard $ and $ zipWith eq (Vector.toList vec1) (Vector.toList vec2)
return Refl
testEquality Bytecode Bytecode = return Refl
testEquality (ExtPtr pointer1 protectionValue1 tagval1) (ExtPtr pointer2 protectionValue2 tagval2) = do
guard $ castPtr pointer1 == castPtr pointer2
void $ testEquality (E protectionValue1) (E protectionValue2)
void $ testEquality (E tagval1) (E tagval2)
return Refl
testEquality (WeakRef key1 value1 finalizer1 next1) (WeakRef key2 value2 finalizer2 next2) = do
void $ testEquality (E key1) (E key2)
void $ testEquality (E value1) (E value2)
void $ testEquality (E finalizer1) (E finalizer2)
void $ testEquality (E next1) (E next2)
return Refl
testEquality (Raw vec1) (Raw vec2) = do
guard $ vec1 == vec2
return Refl
testEquality (S4 tagval1) (S4 tagval2) = do
void $ testEquality (E tagval1) (E tagval2)
return Refl
testEquality _ _ = Nothing
instance Storable (HExp s a) where
sizeOf _ = #{size SEXPREC}
alignment _ = #{alignment SEXPREC}
poke = pokeHExp
peek = peekHExp . R.SEXP
{-# INLINE peek #-}
{-# INLINE peekHExp #-}
peekHExp :: SEXP s a -> IO (HExp s a)
peekHExp s = do
let coerce :: IO (HExp s a) -> IO (HExp s b)
coerce = unsafeCoerce
-- (:∈) constraints are impossible to respect in 'peekHExp', because
-- R doesn't tell us statically the form of the SEXPREC referred to by
-- a pointer. So in this function only, we pretend all constrained
-- fields actually always contain fields of form ANYSXP. This has no
-- operational significance - it's only a way to bypass what's
-- impossible to prove.
coerceAny :: SEXP s a -> SEXP s 'R.Any -- '
coerceAny = R.unsafeCoerce
sptr = R.unsexp s
case R.typeOf s of
R.Nil -> coerce $ return Nil
R.Symbol -> coerce $
Symbol <$> (coerceAny <$> R.sexp <$> #{peek SEXPREC, u.symsxp.pname} sptr)
<*> (R.sexp <$> #{peek SEXPREC, u.symsxp.value} sptr)
<*> (R.sexp <$> #{peek SEXPREC, u.symsxp.internal} sptr)
R.List -> coerce $
List <$> (R.sexp <$> #{peek SEXPREC, u.listsxp.carval} sptr)
<*> (coerceAny <$> R.sexp <$> #{peek SEXPREC, u.listsxp.cdrval} sptr)
<*> (coerceAny <$> R.sexp <$> #{peek SEXPREC, u.listsxp.tagval} sptr)
R.Env -> coerce $
Env <$> (coerceAny <$> R.sexp <$> #{peek SEXPREC, u.envsxp.frame} sptr)
<*> (coerceAny <$> R.sexp <$> #{peek SEXPREC, u.envsxp.enclos} sptr)
<*> (coerceAny <$> R.sexp <$> #{peek SEXPREC, u.envsxp.hashtab} sptr)
R.Closure -> coerce $
Closure <$> (coerceAny <$> R.sexp <$> #{peek SEXPREC, u.closxp.formals} sptr)
<*> (R.sexp <$> #{peek SEXPREC, u.closxp.body} sptr)
<*> (R.sexp <$> #{peek SEXPREC, u.closxp.env} sptr)
R.Promise -> coerce $
Promise <$> (coerceAny <$> R.sexp <$> #{peek SEXPREC, u.promsxp.value} sptr)
<*> (coerceAny <$> R.sexp <$> #{peek SEXPREC, u.promsxp.expr} sptr)
<*> (coerceAny <$> R.sexp <$> #{peek SEXPREC, u.promsxp.env} sptr)
R.Lang -> coerce $
Lang <$> (coerceAny <$> R.sexp <$> #{peek SEXPREC, u.listsxp.carval} sptr)
<*> (coerceAny <$> R.sexp <$> #{peek SEXPREC, u.listsxp.cdrval} sptr)
R.Special -> coerce $
Special <$> (fromIntegral <$> (#{peek SEXPREC, u.primsxp.offset} sptr :: IO CInt))
R.Builtin -> coerce $
Builtin <$> (fromIntegral <$> (#{peek SEXPREC, u.primsxp.offset} sptr :: IO CInt))
R.Char -> unsafeCoerce $ Char (Vector.unsafeFromSEXP (unsafeCoerce s))
R.Logical -> unsafeCoerce $ Logical (Vector.unsafeFromSEXP (unsafeCoerce s))
R.Int -> unsafeCoerce $ Int (Vector.unsafeFromSEXP (unsafeCoerce s))
R.Real -> unsafeCoerce $ Real (Vector.unsafeFromSEXP (unsafeCoerce s))
R.Complex -> unsafeCoerce $ Complex (Vector.unsafeFromSEXP (unsafeCoerce s))
R.String -> unsafeCoerce $ String (Vector.unsafeFromSEXP (unsafeCoerce s))
R.DotDotDot -> unimplemented $ "peekHExp: " ++ show (R.typeOf s)
R.Vector -> coerce $
Vector <$> (fromIntegral <$> (#{peek VECTOR_SEXPREC, vecsxp.truelength} sptr :: IO CInt))
<*> pure (Vector.unsafeFromSEXP (unsafeCoerce s))
R.Expr -> coerce $
Expr <$> (fromIntegral <$> (#{peek VECTOR_SEXPREC, vecsxp.truelength} sptr :: IO CInt))
<*> pure (Vector.unsafeFromSEXP (unsafeCoerce s))
R.Bytecode -> coerce $ return Bytecode
R.ExtPtr -> coerce $
ExtPtr <$> (castPtr <$> #{peek SEXPREC, u.listsxp.carval} sptr)
<*> (R.sexp <$> #{peek SEXPREC, u.listsxp.cdrval} sptr)
<*> (R.sexp <$> #{peek SEXPREC, u.listsxp.tagval} sptr)
R.WeakRef -> coerce $
WeakRef <$> (coerceAny <$> R.sexp <$>
peekElemOff (castPtr $ R.unsafeSEXPToVectorPtr s) 0)
<*> (R.sexp <$>
peekElemOff (castPtr $ R.unsafeSEXPToVectorPtr s) 1)
<*> (coerceAny <$> R.sexp <$>
peekElemOff (castPtr $ R.unsafeSEXPToVectorPtr s) 2)
<*> (coerceAny <$> R.sexp <$>
peekElemOff (castPtr $ R.unsafeSEXPToVectorPtr s) 3)
R.Raw -> unsafeCoerce $ Raw (Vector.unsafeFromSEXP (unsafeCoerce s))
R.S4 -> coerce $
S4 <$> (R.sexp <$> #{peek SEXPREC, u.listsxp.tagval} sptr)
_ -> unimplemented $ "peekHExp: " ++ show (R.typeOf s)
pokeHExp :: Ptr (HExp s a) -> HExp s a -> IO ()
pokeHExp s h = do
case h of
Nil -> return ()
Symbol pname value internal -> do
#{poke SEXPREC, u.symsxp.pname} s (R.unsexp pname)
#{poke SEXPREC, u.symsxp.value} s (R.unsexp value)
#{poke SEXPREC, u.symsxp.internal} s (R.unsexp internal)
List carval cdrval tagval -> do
#{poke SEXPREC, u.listsxp.carval} s (R.unsexp carval)
#{poke SEXPREC, u.listsxp.cdrval} s (R.unsexp cdrval)
#{poke SEXPREC, u.listsxp.tagval} s (R.unsexp tagval)
Env frame enclos hashtab -> do
#{poke SEXPREC, u.envsxp.frame} s (R.unsexp frame)
#{poke SEXPREC, u.envsxp.enclos} s (R.unsexp enclos)
#{poke SEXPREC, u.envsxp.hashtab} s (R.unsexp hashtab)
Closure formals body env -> do
#{poke SEXPREC, u.closxp.formals} s (R.unsexp formals)
#{poke SEXPREC, u.closxp.body} s (R.unsexp body)
#{poke SEXPREC, u.closxp.env} s (R.unsexp env)
Promise value expr env -> do
#{poke SEXPREC, u.promsxp.value} s (R.unsexp value)
#{poke SEXPREC, u.promsxp.expr} s (R.unsexp expr)
#{poke SEXPREC, u.promsxp.env} s (R.unsexp env)
Lang carval cdrval -> do
#{poke SEXPREC, u.listsxp.carval} s (R.unsexp carval)
#{poke SEXPREC, u.listsxp.cdrval} s (R.unsexp cdrval)
Special offset -> do
#{poke SEXPREC, u.primsxp.offset} s (fromIntegral offset :: CInt)
Builtin offset -> do
#{poke SEXPREC, u.primsxp.offset} s (fromIntegral offset :: CInt)
Char _vc -> unimplemented "pokeHExp"
Logical _vt -> unimplemented "pokeHExp"
Int _vt -> unimplemented "pokeHExp"
Real _vt -> unimplemented "pokeHExp"
String _vt -> unimplemented "pokeHExp"
Complex _vt -> unimplemented "pokeHExp"
Vector _v _ -> unimplemented "pokeHExp"
Bytecode -> unimplemented "pokeHExp"
ExtPtr _ _ _ -> unimplemented "pokeHExp"
WeakRef _ _ _ _ -> unimplemented "pokeHExp"
Raw _ -> unimplemented "pokeHExp"
S4 _ -> unimplemented "pokeHExp"
DotDotDot _ -> unimplemented "pokeHExp"
Expr _ _ -> unimplemented "pokeHExp"
-- | A view function projecting a view of 'SEXP' as an algebraic datatype, that
-- can be analyzed through pattern matching.
hexp :: SEXP s a -> HExp s a
hexp = unsafeInlineIO . peek . R.unSEXP
{-# INLINE hexp #-}
-- | Inverse hexp view to the real structure, note that for scalar types
-- hexp will allocate new SEXP, and @unhexp . hexp@ is not an identity function.
-- however for vector types it will return original SEXP.
unhexp :: MonadR m => HExp (Region m) a -> m (SEXP (Region m) a)
unhexp Nil = return $ R.release H.nilValue
unhexp s@(Symbol{}) = io $
withProtected (R.allocSEXP R.SSymbol)
(\x -> poke (R.unSEXP x) s >> return x)
unhexp (List carval cdrval tagval) = acquire <=< io $ do
rc <- R.protect carval
rd <- R.protect cdrval
rt <- R.protect tagval
z <- R.cons rc rd
#{poke SEXPREC, u.listsxp.tagval} (R.unsexp z) (R.unsexp rt)
R.unprotect 3
return z
unhexp (Lang carval cdrval) = acquire <=< io $ do
carval' <- R.protect carval
cdrval' <- R.protect cdrval
x <- R.allocSEXP R.SLang
R.setCar x (R.release carval')
R.setCdr x (R.release cdrval')
R.unprotect 2
return x
unhexp s@(Env{}) = io $
withProtected (R.allocSEXP R.SEnv)
(\x -> poke (R.unSEXP x) s >> return x)
unhexp s@(Closure{}) = io $
withProtected (R.allocSEXP R.SClosure)
(\x -> poke (R.unSEXP x) s >> return x)
unhexp s@(Special{}) = io $
withProtected (R.allocSEXP R.SSpecial)
(\x -> poke (R.unSEXP x) s >> return x)
unhexp s@(Builtin{}) = io $
withProtected (R.allocSEXP R.SBuiltin)
(\x -> poke (R.unSEXP x) s >> return x)
unhexp s@(Promise{}) = io $
withProtected (R.allocSEXP R.SPromise)
(\x -> poke (R.unSEXP x) s >> return x)
unhexp (Bytecode{}) = unimplemented "unhexp"
unhexp (Real vt) = return $ Vector.unsafeToSEXP vt
unhexp (Logical vt) = return $ Vector.unsafeToSEXP vt
unhexp (Int vt) = return $ Vector.unsafeToSEXP vt
unhexp (Complex vt) = return $ Vector.unsafeToSEXP vt
unhexp (Vector _ vt) = return $ Vector.unsafeToSEXP vt
unhexp (Char vt) = return $ Vector.unsafeToSEXP vt
unhexp (String vt) = return $ Vector.unsafeToSEXP vt
unhexp (Raw vt) = return $ Vector.unsafeToSEXP vt
unhexp S4{} = unimplemented "unhexp"
unhexp (Expr _ vt) = return $ Vector.unsafeToSEXP vt
unhexp WeakRef{} = error "unhexp does not support WeakRef, use Foreign.R.mkWeakRef instead."
unhexp DotDotDot{} = unimplemented "unhexp"
unhexp ExtPtr{} = unimplemented "unhexp"
-- | Project the vector out of 'SEXP's.
vector :: R.IsVector a => SEXP s a -> Vector.Vector a (Vector.ElemRep V a)
vector (hexp -> Char vec) = vec
vector (hexp -> Logical vec) = vec
vector (hexp -> Int vec) = vec
vector (hexp -> Real vec) = vec
vector (hexp -> Complex vec) = vec
vector (hexp -> String vec) = vec
vector (hexp -> Vector _ vec) = vec
vector (hexp -> Expr _ vec) = vec
vector s = violation "vector" $ show (R.typeOf s) ++ " unexpected vector type."
|
------------------------------------------------------------------------
-- Properties of functions, such as associativity and commutativity
------------------------------------------------------------------------
-- This file contains some core definitions which are reexported by
-- Algebra.FunctionProperties. They are placed here because
-- Algebra.FunctionProperties is a parameterised module, and the
-- parameters are irrelevant for these definitions.
module Algebra.FunctionProperties.Core where
------------------------------------------------------------------------
-- Unary and binary operations
Op₁ : Set → Set
Op₁ A = A → A
Op₂ : Set → Set
Op₂ A = A → A → A
|
From iris.bi.lib Require Import fractional.
From Perennial.goose_lang Require Import mono_nat.
From RecordUpdate Require Import RecordSet.
From Goose.github_com.mit_pdos.go_journal Require Import wal.
From Perennial.Helpers Require Import Transitions.
From Perennial.goose_lang Require Import crash_modality.
From Perennial.Helpers Require Import NamedProps.
From Perennial.program_proof Require Import disk_prelude disk_lib.
From Perennial.program_proof Require Import wal.lib.
From Perennial.program_proof Require Import marshal_block util_proof.
From Perennial.program_proof Require Import circ_proof.
From Perennial.goose_lang.lib Require Import slice.typed_slice.
(***************)
(*
Crash reasoning strategy:
OLD APPROACH:
We had a persistent assertion is_circular γ, which was an invariant containing
is_circular_state γ σ * P σ, where P is a client chosen rep predicate. Hence,
by Perennial 1 style reasoning we could know on crash that we had
is_circular_state γ σ * P σ. Because is_circular_state only referred to disk
resources and ghost resources, it was stable under post_crash, hence recovery
got as a precondiiton is_circular_state γ σ * P σ. Recovery generated some fresh
γ' and is_circular_state γ' σ * P σ + the resources sent to installer/logger in
γ' (which were otherwise lost upon crash).
NEW APPROACH:
is_circular is as before, but using an ncinv. We introduce 3 additional predicates:
- init_ghost_state -- this is all of the ghost resources used by both is_circular_state and installer/loggers
- is_circular_state_crash -- this represents a "weakening" of is_circular_state that will be an invariant at crash time.
- circular_crash_ghost_exchange -- this is a series of disjunctions of the form (own γold ... \/ own γnew)
Then we have a lemma crash_upd, which transforms is_circular_state into the resources at crash time.
Lemma crash_upd γold γnew σ :
is_circular_state γold σ -∗ init_ghost_state γnew ==∗
is_circular_state γnew σ ∗
is_circular_state_crash γold σ ∗
circular_crash_ghost_exchange γold γnew.
This is then used as part of the following lemma, which should be called at the end of recovery:
Lemma circ_buf_crash_obligation_alt Prec Pcrash γ σ:
is_circular_state γ σ -∗
□ (∀ σ, ▷ P σ -∗ |0={⊤ ∖ ↑N}=> ▷ Prec σ ∗ ▷ Pcrash σ) -∗
P σ -∗
|={⊤}=> ∃ γ', is_circular N P γ ∗ (<bdisc> C -∗ |0={⊤}=> ▷ ∃ σ, is_circular_state γ' σ ∗ Prec σ)
∗ □ (C -∗ |0={⊤}=> inv N (∃ σ, is_circular_state_crash γ σ ∗
circular_crash_ghost_exchange γ γ' ∗
Pcrash σ)).
which is used to remove is_circular_state from the crash obligation etc.
When a crash transition actually modifies the state, the above should be changed to:
□ (∀ σ σ' (Hcrash: crash_rel σ σ'), ▷ P σ -∗ |0={⊤ ∖ ↑N}=> ▷ Prec σ' ∗ ▷ Pcrash σ σ') ...
and analogously in crash_upd. This would allow us to encode further tha Prec σ'
should only hold if σ' is a post-crash state.
*)
(***************)
Section heap.
Context `{!heapGS Σ}.
Context `{!circG Σ}.
Context (N: namespace).
Context (P: circΣ.t -> iProp Σ).
Hint Unfold circ_low_wf : word.
Hint Unfold circΣ.diskEnd : word.
Ltac mod_bound :=
(* TODO: repeat *)
match goal with
| |- context[?x `mod` ?m] =>
pose proof (Z.mod_bound_pos x m)
end.
Lemma split_513_blocks :
0 d↦∗ repeat block0 513 -∗
0 d↦ block0 ∗ 1 d↦ block0 ∗ 2 d↦∗ repeat block0 511.
Proof. reflexivity. Qed.
Lemma circ_own_init :
⊢ |==> ∃ γaddrs γblocks,
let addrs := repeat (U64 0) 511 in
let blocks := repeat block0 511 in
⌜circ_low_wf addrs blocks⌝ ∗
ghost_var γaddrs 1 addrs ∗
ghost_var γblocks 1 blocks.
Proof.
iMod (ghost_var_alloc (repeat (U64 0) 511)) as (γaddrs) "?".
iMod (ghost_var_alloc (repeat block0 511)) as (γblocks) "?".
iModIntro.
iExists _, _; iFrame.
iPureIntro.
rewrite /circ_low_wf.
rewrite !repeat_length //.
Qed.
Lemma zero_encodings :
let σ := {| upds := []; start := U64 0; |} in
block_encodes block0
([EncUInt64 (circΣ.diskEnd σ)] ++ map EncUInt64 (repeat (U64 0) 511))
∧ block_encodes block0 [EncUInt64 (start σ)].
Proof.
rewrite /block_encodes /has_encoding.
split.
- reflexivity.
- reflexivity.
Qed.
Lemma circular_init :
0 d↦∗ repeat block0 513 -∗
|==> ∃ γ, is_circular_state γ {| upds := []; start := U64 0; |} ∗
is_circular_appender_pre γ ∗
start_is γ (1/2) (U64 0) ∗
diskEnd_is γ (1/2) 0.
Proof.
set (σ:={| upds := []; start := U64 0; |}).
assert (circΣ.diskEnd σ = 0) as HdiskEnd by reflexivity.
rewrite split_513_blocks.
iIntros "(Hhdr1 & Hhdr2 & Hlog)".
iMod circ_own_init as (γaddrs γblocks Hlow_wf) "[[Haddrs1 Haddrs2] [Hblocks1 Hblocks2]]".
iMod (mono_nat_own_alloc 0) as (γstart) "[[Hstart1 Hstart2] #Hstart_lb]".
iMod (mono_nat_own_alloc 0) as (γend) "[[Hend1 Hend2] #Hend_lb]".
iExists {| addrs_name := γaddrs; blocks_name := γblocks;
start_name := γstart; diskEnd_name := γend;
|}.
iModIntro.
rewrite /is_circular_state.
iSplitR "Haddrs2 Hblocks2 Hstart2 Hend2".
- iSplit.
{ iPureIntro; hnf; simpl.
rewrite HdiskEnd.
word. }
iSplitL "Hstart1 Hend1".
{ rewrite /circ_positions.
rewrite /start_is /diskEnd_is /diskEnd_at_least /=.
rewrite HdiskEnd.
iFrame "#∗".
iPureIntro; lia. }
iExists _, _.
rewrite /circ_own.
cbn [addrs_name blocks_name].
iFrame "Haddrs1 Hblocks1".
iSplit.
{ iPureIntro.
rewrite /σ /has_circ_updates.
cbn [upds start].
inversion 1. }
iSplit; first by eauto.
rewrite /is_low_state.
iExists block0, block0; iFrame "Hhdr1 Hhdr2 Hlog".
iPureIntro.
apply zero_encodings.
- rewrite /is_circular_appender_pre.
iSplitL "Haddrs2 Hblocks2".
+ iExists _, _.
iSplit; first by eauto.
iFrame.
+ rewrite /start_is /diskEnd_is /=.
iFrame.
iSplit; first by (iPureIntro; lia).
rewrite /diskEnd_at_least /=.
iFrame "#".
Qed.
Theorem wpc_recoverCircular stk E1 d σ γ :
{{{ is_circular_state γ σ ∗ is_circular_appender_pre γ}}}
recoverCircular (disk_val d) @ stk; E1
{{{ (c:loc) (diskStart diskEnd: u64) (bufSlice:Slice.t) (upds: list update.t),
RET (#c, #diskStart, #diskEnd, slice_val bufSlice);
updates_slice bufSlice upds ∗
is_circular_state γ σ ∗
is_circular_appender γ c ∗
⌜σ.(circΣ.start) = diskStart⌝ ∗
⌜σ.(circΣ.upds) = upds⌝ ∗
⌜circΣ.diskEnd σ = int.Z diskEnd⌝
}}}
{{{ is_circular_state γ σ ∗ is_circular_appender_pre γ }}}.
Proof.
clear P.
iIntros (Φ Φc) "(Hcs&Hres) HΦ".
Opaque struct.t.
rewrite /recoverCircular.
wpc_pures; first iFrame.
{ crash_case; eauto with iFrame. }
iDestruct "Hcs" as (Hwf) "[Hpos Hcs]".
iDestruct "Hcs" as (addrs0 blocks0 Hupds) "(Hown & Hlow)".
iDestruct "Hown" as (Hlow_wf) "[Haddrs Hblocks]".
iDestruct "Hlow" as (hdr1 hdr2 Hhdr1 Hhdr2) "(Hd0 & Hd1 & Hd2)".
iCache with "HΦ Hpos Haddrs Hblocks Hd0 Hd1 Hd2 Hres".
{ crash_case.
iFrame "% ∗".
iExists _, _; iFrame "∗ %".
iExists _, _; iFrame "∗ %". }
wpc_apply (wpc_Read with "[Hd0]"); first by iFrame.
iSplit.
{ iLeft in "HΦ". iIntros "Hd0". iApply "HΦ".
iFrame "% ∗".
iExists _, _; iFrame "∗ %".
iExists _, _; iFrame "∗ %". }
iIntros (s0) "!> [Hd0 Hs0]".
wpc_pures.
wpc_apply (wpc_Read with "[Hd1]"); first iFrame.
iSplit.
{ iLeft in "HΦ". iIntros "Hd1". iApply "HΦ".
iFrame "% ∗".
iExists _, _; iFrame "∗ %".
iExists _, _; iFrame "∗ %". }
iIntros (s1) "!> [Hd1 Hs1]".
wpc_pures.
wpc_bind (decodeHdr1 _).
wpc_frame.
iApply slice.is_slice_to_small in "Hs0".
wp_apply (wp_decodeHdr1 with "Hs0"); [ eauto | word | ].
iIntros (addrs) "Hdiskaddrs H". iNamed "H".
wpc_pures.
wpc_bind (decodeHdr2 _).
wpc_frame.
iApply slice.is_slice_to_small in "Hs1".
wp_apply (wp_decodeHdr2 with "Hs1"); [ eauto | ].
iNamed 1.
wpc_pures.
wpc_frame_seq.
wp_apply wp_ref_of_zero; eauto.
iIntros (bufsloc) "Hbufsloc".
iNamed 1.
wpc_pures.
wpc_frame_seq.
wp_apply wp_ref_to; eauto.
iIntros (pos) "Hposl".
iNamed 1.
wpc_pures.
wpc_apply (wpc_forUpto (fun i =>
⌜int.Z σ.(start) <= int.Z i⌝ ∗
(∃ bufSlice,
bufsloc ↦[slice.T (struct.t Update)] (slice_val bufSlice) ∗
updates_slice bufSlice (take (int.nat i - int.nat σ.(start)) σ.(upds))) ∗
is_slice_small addrs uint64T 1 addrs0 ∗
2 d↦∗ blocks0
)%I
(fun i => 2 d↦∗ blocks0)%I with "[] [Hbufsloc $Hposl $Hd2 Hdiskaddrs]").
- word_cleanup.
destruct Hwf.
rewrite /circΣ.diskEnd.
word.
- iIntros (??) "(H&?&?&?)".
eauto.
- iIntros (i Φₗ Φcₗ) "!> (HI&Hposl&%) HΦ".
iDestruct "HI" as (Hstart_bound) "(Hbufs&Hdiskaddrs&Hd2)".
iDestruct "Hbufs" as (bufSlice) "[Hbufsloc Hupds]".
iDestruct (updates_slice_len with "Hupds") as %Hupdslen.
wpc_pures.
{ crash_case; eauto. }
iCache with "HΦ Hd2".
{ crash_case; iLeft; iFrame. }
wpc_frame_seq.
wp_load.
list_elem addrs0 (int.Z i `mod` LogSz) as a.
{ destruct Hlow_wf.
mod_bound; word. }
wp_apply (wp_SliceGet _ _ _ _ 1 addrs0 with "[$Hdiskaddrs]"); eauto.
{ iPureIntro.
change (word.divu _ _) with (U64 LogSz).
word_cleanup.
rewrite Ha_lookup.
eauto. }
iIntros "Hdiskaddrs".
iNamed 1.
wpc_pures.
wpc_bind (load_ty _ _).
wpc_frame.
wp_load. iModIntro.
iNamed 1.
wpc_pures.
change (word.divu _ _) with (U64 LogSz).
destruct (list_lookup_lt _ blocks0 (Z.to_nat (int.Z i `mod` LogSz))) as [b Hblookup].
{ destruct Hlow_wf.
mod_bound; word. }
iDestruct (disk_array_acc _ blocks0 (int.Z i `mod` LogSz) with "[Hd2]") as "[Hdi Hd2']"; eauto.
{ mod_bound; word. }
wpc_apply (wpc_Read with "[Hdi]").
{ iExactEq "Hdi".
f_equal.
mod_bound; word. }
iSplit.
{ iLeft in "HΦ". iIntros "Hdi".
iSpecialize ("Hd2'" with "[Hdi]").
{ iExactEq "Hdi". f_equal. mod_bound. word. }
rewrite list_insert_id; eauto. iApply "HΦ"; eauto. }
iNext.
iIntros (b_s) "[Hdi Hb_s]".
iDestruct ("Hd2'" with "[Hdi]") as "Hd2".
{ iExactEq "Hdi".
f_equal.
mod_bound; word. }
rewrite list_insert_id; eauto.
wpc_pures.
wpc_bind (load_ty _ _).
wpc_frame.
wp_load. iModIntro.
iNamed 1.
wpc_frame.
wp_apply (wp_SliceAppend_updates (uv:=(a, b_s)) with "[$Hupds Hb_s]").
{ iApply slice.is_slice_to_small in "Hb_s". iFrame. }
iIntros (bufSlice') "Hupds'".
wp_store. iModIntro.
iNamed 1.
iApply "HΦ".
iFrame.
iSplit; first by iPureIntro; word.
iExists _; iFrame.
iExactEq "Hupds'".
f_equal.
destruct Hwf.
destruct Hlow_wf.
rewrite /circΣ.diskEnd in H.
word_cleanup.
autorewrite with len in Hupdslen.
revert H; word_cleanup; intros.
assert (int.nat i - int.nat σ.(start) < length σ.(upds))%nat as Hinbounds by word.
apply list_lookup_lt in Hinbounds.
destruct Hinbounds as [[a' b'] Hieq].
pose proof (Hupds _ _ Hieq) as Haddr_block_eq. rewrite /LogSz /= in Haddr_block_eq.
replace (int.Z (start σ) + Z.of_nat (int.nat i - int.nat (start σ)))
with (int.Z i) in Haddr_block_eq by word.
destruct Haddr_block_eq.
replace (Z.to_nat (int.Z i + 1) - int.nat (start σ))%nat with (S (int.nat i - int.nat (start σ))) by word.
erewrite take_S_r; eauto.
rewrite Hieq /=.
congruence.
- iDestruct (is_slice_to_small with "Hdiskaddrs") as "Hdiskaddrs".
iFrame.
rewrite zero_slice_val.
iSplit; first by iPureIntro; word.
iExists _. iFrame.
iExists nil; simpl.
iSplitL.
{ iApply (slice.is_slice_zero). }
replace (int.nat (start σ) - int.nat (start σ))%nat with 0%nat by lia.
rewrite take_0.
rewrite big_sepL2_nil.
auto.
- iSplit.
{ iLeft in "HΦ". iDestruct 1 as (i) "(Hd2&%)".
iApply "HΦ".
iFrame "% ∗".
iExists _, _; iFrame "∗ %".
iExists _, _; iFrame "∗ %". }
iIntros "!> [(_ & HI & Hdiskaddrs & Hd2) Hposl]".
iDestruct "HI" as (bufSlice) "[Hbufsloc Hupds]".
wpc_frame.
wp_pures.
Transparent struct.t.
wp_apply wp_allocStruct; first by eauto.
Opaque struct.t.
iIntros (ca) "Hca".
wp_load.
(*
iMod (ghost_var_alloc addrs0) as (addrs_name') "[Haddrs' Hγaddrs]".
iMod (ghost_var_alloc blocks0) as (blocks_name') "[Hblocks' Hγblocks]".
iMod (mono_nat_own_alloc (int.nat σ.(start))) as (start_name') "[[Hstart1 Hstart2] _]".
iMod (mono_nat_own_alloc (Z.to_nat (circΣ.diskEnd σ))) as (diskEnd_name') "[[HdiskEnd1 HdiskEnd2] #HdiskEndLb]".
set (γ' := {| addrs_name := addrs_name';
blocks_name := blocks_name';
start_name := start_name';
diskEnd_name := diskEnd_name'; |}).
*)
wp_pures. iModIntro.
iNamed 1.
iDestruct "HΦ" as "(_&HΦ)".
iApply ("HΦ").
iFrame "Hpos Hupds". iFrame.
iDestruct "Hres" as (???) "(Haddrs'&Hblocks')".
iDestruct (ghost_var_agree with "Hblocks Hblocks'") as %->.
iDestruct (ghost_var_agree with "Haddrs Haddrs'") as %->.
iSplitL "Hd0 Hd1 Hd2 Hblocks Haddrs".
{ iSplit; first done. iExists _, _. iFrame.
iSplit; first done.
iSplit; first done.
iExists _, _. iFrame. eauto.
}
iSplitL "Hca Hposl Hdiskaddrs Haddrs' Hblocks'".
{
iExists _, _, _. iFrame. iSplit; first done.
iDestruct (struct_fields_split with "Hca") as "[Hca _]".
iFrame.
}
iFrame.
(*
iSplitL "Hend_is".
{
iExactEq "Hend_is".
rewrite take_ge; auto. destruct Hwf; word.
}
*)
iPureIntro; split_and!; eauto.
* rewrite take_ge; auto. destruct Hwf; word.
* destruct Hwf.
rewrite /circΣ.diskEnd.
word.
Qed.
(* XXX: this instance seems dangerous, I don't want it to get picked up for an l ↦ v, for example.
But it seems not to since those definitions are sealed. *)
Local Instance own_into_crash {A} `{inG Σ A} (γ: gname) (x: A):
IntoCrash (own γ x) (λ _, own γ x).
Proof.
rewrite /IntoCrash. iApply post_crash_nodep.
Qed.
Local Instance ghost_var_into_crash {A} `{ghost_varG Σ A} (γ: gname) q (x: A):
IntoCrash (ghost_var γ q x) (λ _, ghost_var γ q x).
Proof.
rewrite /IntoCrash. iApply post_crash_nodep.
Qed.
Global Instance is_circular_state_durable γ (σ : circΣ.t):
IntoCrash (is_circular_state γ σ) (λ _, is_circular_state γ σ).
Proof. apply _. Qed.
Lemma is_circular_state_post_crash σ γ P':
(IntoCrash (P σ) (P' σ)) →
is_circular_state γ σ ∗ P σ -∗ post_crash (λ hG, is_circular_state γ σ ∗ P' σ hG).
Proof. iIntros (?) "His". rewrite /is_circular. iCrash. eauto. Qed.
(*
Lemma is_circular_post_crash γ P' :
(∀ s, IntoCrash (P s) (P' s)) →
is_circular N P γ ={↑N, ∅}=∗ ▷ post_crash (λ hG, ∃ σ, is_circular_state γ σ ∗ P' σ hG).
Proof.
iIntros (?) "His".
rewrite /is_circular.
iInv "His" as "Hinner" "_".
iDestruct "Hinner" as (σ) "(>His&HP)".
rewrite difference_diag_L.
iModIntro. iNext. iPoseProof (is_circular_state_post_crash with "[$]") as "H".
iCrash. eauto.
Qed.
*)
Lemma circ_buf_crash_obligation_alt E Prec Pcrash γ σ:
↑N ⊆ E →
is_circular_state γ σ -∗
□ (∀ σ, ▷ P σ -∗ |={E ∖ ↑N}=> ▷ Prec σ ∗ ▷ Pcrash σ) -∗
P σ -∗
|={⊤}=> ∃ γ', is_circular N P γ ∗
(<bdisc> (|C={E}=> ∃ σ, is_circular_state γ' σ ∗
circ_resources γ' σ ∗
▷ Prec σ))
∗ □ (|C={E}=> inv N (∃ σ, is_circular_state_crash γ σ ∗
circular_crash_ghost_exchange γ γ' ∗
Pcrash σ)).
Proof.
iIntros (?) "Hcs #HPwand HP".
iMod (alloc_init_ghost_state) as (γ') "Hinit".
iMod (ncinv_cinv_alloc N ⊤ E
((∃ σ, is_circular_state γ σ ∗ P σ) ∗ init_ghost_state γ')
(∃ σ, is_circular_state_crash γ σ ∗
circular_crash_ghost_exchange γ γ' ∗
Pcrash σ)%I
(∃ σ, is_circular_state γ' σ ∗ circ_resources γ' σ ∗ Prec σ)%I with
"[] [Hcs HP Hinit]") as "(Hncinv&Hcfupd&Hcinv)".
{ solve_ndisj. }
{ iModIntro. iIntros "(H1&>Hinit)".
iDestruct "H1" as (σ') "(>Hstate&HP)".
iIntros "#HC".
iMod ("HPwand" with "[$]") as "(HPrec&HPcrash)".
iMod (crash_upd with "[$] [$]") as "(Hcs&Hres&Hcs_crash&Hexchange)".
iModIntro.
iSplitR "Hcs HPrec Hres".
{ iNext. iExists _. iFrame. }
{ iNext. iExists _. iFrame. }
}
{ iNext. iFrame. iExists _. iFrame. }
iModIntro. iExists γ'.
iSplitL "Hncinv".
{ rewrite /is_circular. iApply ncinv_split_l; iApply "Hncinv". }
eauto. iFrame "Hcinv".
iModIntro. iIntros "HC". iMod ("Hcfupd" with "[$]") as (?) "(>?&>?&?)".
iModIntro; iExists _; iFrame.
Qed.
(* Once the circular buffer is initialized or recovered, the is_circular
invariant can be allocated. By allocating that invariant, we no longer need
to show is_circular_state γ σ ∗ P σ in the crash condition anymore, because at
crash time we know that this will hold because it is in an invariant.
This lemma encodes this principle.
*)
Lemma circ_buf_crash_obligation e Φ Φc Φc' σ γ:
is_circular_state γ σ -∗
P σ -∗
□ (▷ (∃ σ', is_circular_state γ σ' ∗ P σ') -∗ Φc -∗ Φc') -∗
(is_circular N P γ -∗ (WPC e @ ⊤ {{ Φ }} {{ Φc }})) -∗
|={⊤}=> is_circular N P γ ∗ WPC e @ ⊤ {{ Φ }} {{ Φc' }}%I.
Proof.
iIntros "Hstate HP #Hcrash1 HWP". rewrite /is_circular.
iMod (ncinv_alloc N _ (∃ σ, is_circular_state γ σ ∗ P σ)%I with "[Hstate HP]") as "(#Hinv&Hcfupd)".
{ iNext. iExists _. iFrame. }
iFrame "Hinv".
iModIntro.
iMod (own_disc_fupd_elim with "Hcfupd") as "Hcfupd".
iSpecialize ("HWP" with "[$]").
iApply (wpc_strong_mono with "HWP"); auto.
iSplit; first eauto.
iIntros "H1".
iMod (cfupd_weaken_mask with "[$]"); try lia; eauto.
iModIntro.
iApply ("Hcrash1" with "[$] [$]").
Qed.
(* Note: the version above is more usable, but this helps understand what it achieves *)
Lemma circ_buf_crash_obligation_simple e Φ σ γ:
is_circular_state γ σ -∗
P σ -∗
(is_circular N P γ -∗ (WPC e @ ⊤ {{ Φ }} {{ True }})) -∗
|={⊤}=> is_circular N P γ ∗
WPC e @ ⊤ {{ Φ }} {{ ▷ ∃ σ', is_circular_state γ σ' ∗ P σ' }}%I.
Proof.
iIntros "Hstate HP HWP".
iApply (circ_buf_crash_obligation with "[$] [$] [] [$]"); auto; set_solver+.
Qed.
End heap.
|
subroutine sub (i)
close(15)
close(UNIT=16,STATUS='DELETE')
end subroutine sub
end
|
import Lean
import Lean.Elab
import Lean.Elab.Tactic
import Lean.Meta
open Lean Expr Elab Meta Tactic
set_option pp.proofs true
set_option pp.proofs.withType true
/-
If the expression is of the form
A₁ → A₂ → A₃ → … → Aₙ → … → B,
the output of `targetType` is the type of `B`.
Essentially, it recovers the type of the term at the end of a series of nested implications.
-/
def getTargetType (e : Expr) : MetaM Expr :=
Meta.forallTelescope e (λ _ t => pure t)
/-
This is the backbone of the `findProof` tactic, which is meant to find proofs (or equivalently, construct terms) of propositions (or types) involving only implications (or function arrows).
It works by first introducing all the necessary hypotheses, and then scanning the local context for terms having the goal as the "target type" (see above for the definition of a target type).
Once such a term is found, the tactic tries to recursively construct terms required to "unlock" the target, i.e., if `f : A₁ → A₂ → … → Aₙ → … → B` is a term with target type equal to the goal, terms of types `A₁, A₂, …, Aₙ, …` must be constructed in order to apply `f` and obtain a term of type `B`.
If none of the terms in the local context are able to eventually yield the target, the tactic fails. In principle, if a type can be constructed entirely in terms of function applications, this tactic should be able to find a term (this may not happen in practice due to looping).
-/
partial def findProofTU (mvar : MVarId) : TacticM Unit := do
let (_, imvar) ← intros mvar -- introduce all the necessary hypotheses
withMVarContext imvar do
let tgtType ← getMVarType imvar -- the type of the goal
for v in (← getLCtx) do -- scanning the local context
let vType ← getTargetType v.type -- the target type of the local variables
if !v.isAuxDecl then if (← isDefEq tgtType vType) then
try
let amvars ← apply imvar v.toExpr -- the goals obtained after applying the candidate term
for amvar in amvars do
findProofTU amvar -- recursively trying to solve the new goals
done
if (← getGoals).isEmpty then do
logInfo m!"Proof complete - by {v.type}"
return ()
catch _ => continue
-- throws an error if none of the terms of the local context can be used to construct the goal
throwError m!"There are unsolved goals: \n\t{goalsToMessageData (← getGoals)}"
/-
This is the actual implementation of the tactic.
-/
syntax (name := findProof) "findProof" : tactic
@[tactic findProof] def findProofT : Tactic := fun stx => do
findProofTU (← getMainGoal)
section examples
-- a convoluted example of the tactic in action
example : String → Float → (Unit → Int) → (Int → Nat) → (String → Unit) → Nat := by
findProof
def convolutedexample : String → Float → (Unit → Int) → (Int → Nat) → (String → Unit) → Nat := by
findProof
#print convolutedexample
def contrapose (P Q R : Type) : (P → Q) → ((Q → R) → (P → R)) := by
findProof
#print contrapose
/-
P -> Q
Q -> ⊥
P
----
⊥
-/
def ident {A : Type} : A → A := by
findProof
#print ident
def proj₁ {A B : Type} : A → (B → A) := by
findProof
#print proj₁
def modusPonens {P Q : Type} : (P → Q) → (P → (Q)) := by
findProof
#print modusPonens
def gelfand_naimark {A ℂ : Type} : A → ((A → ℂ) → ℂ) := by
findProof
#print gelfand_naimark
def adjoint {V W F : Type} : (V → W) → ((W → F) → (V → (F))) := by
findProof
#print adjoint
def differential {M N ℝ S : Type} (f : M → N) : ((M → ℝ) → S) → ((N → ℝ) → S) := by findProof
def differential' {M N ℝ : Type} (f : M → N) : ((M → ℝ) → ℝ) → ((N → ℝ) → ℝ) := differential f
#print differential
def cov_yoneda_fwd (A : Type) (F : Type → Type)
(η : (X : Type) → (A → X) → F X) : F A := by sorry
def cov_yoneda_fwd_simple (A : Type) (F : Type → Type) (η : (A → A) → F A) : F A := by findProof
#print cov_yoneda_fwd_simple
def cov_yoneda_bwd (A : Type) (F : Type → Type) (Fmap : (P Q : Type) → (P → Q) → (F P → F Q)) (a : F A) :
((X : Type) → ((A → X) → F X)) := by sorry
def cov_yoneda_bwd_simple (A X : Type) (F : Type → Type) (Fmap : (A → X) → (F A → F X)) (a : F A) :
((f : A → X) → F X) := by findProof
#print cov_yoneda_bwd
end examples
|
#include <boost/filesystem.hpp>
#include <string>
#include <iostream>
#include <vector>
#include <tuple>
#include <fstream>
using namespace std;
void saveTestCases(int id, vector<string> &inputs, vector<string> &outputs){
string folderPath = "exercises/" + to_string(id);
bool res = boost::filesystem::create_directories(folderPath);
if(res)
cout << "exercise folder successfully created " << endl;
for (int i = 0; i < inputs.size(); i++){
string filename = folderPath + "/" + to_string(i);
ofstream f_out(filename + ".out");
f_out << outputs[i];
ofstream f_in(filename + ".in");
f_in << inputs[i];
f_out.close();
f_in.close();
}
}
void removeTestCases(int id){
string folderPath = "exercises/" + to_string(id);
if(boost::filesystem::remove_all(folderPath))
cout << "Test cases removed " << endl;
}
void createCompilationFolder(){
boost::filesystem::create_directory("compile_dir");
}
void saveSubmit(int ex_id, int usr_id, string submit){
string folderPath = "exercises/" + to_string(ex_id) + "/submits";
boost::filesystem::create_directory(folderPath);
ofstream f{folderPath + "/" + to_string(usr_id) + ".prog"};
f << submit;
} |
[STATEMENT]
lemma fin_join_ti_hint2:
assumes "fin_join_ti s x (Suc i) = []"
shows "nth s (x + (Suc i)) = []"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. s ! (x + Suc i) = []
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
fin_join_ti s x (Suc i) = []
goal (1 subgoal):
1. s ! (x + Suc i) = []
[PROOF STEP]
by auto |
#ifndef NUMERIC_CAST_HPP
#define NUMERIC_CAST_HPP
//#include <math.h>
#include <cmath>
#include <limits>
#include <stdexcept>
#ifdef _MSC_VER
#define UNUSED_ARGUMENT
#else
#define UNUSED_ARGUMENT __attribute__ ((unused))
#endif
#include "mdsplus/Traits.hpp"
////////////////////////////////////////////////////////////////////////////////
// Numeric Limits ////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
namespace MDSplus {
#ifndef DOXYGEN // hide this part from documentation
/// Numeric Limits for Integer types
template < typename T, typename EnableIf = void >
class numeric_limits :
public std::numeric_limits<T>
{
public:
typedef std::numeric_limits<T> BaseClass;
static inline T highest() { return BaseClass::max(); }
static inline T lowest() { return BaseClass::min(); }
};
/// Numeric Limits for Floating types
template < typename T >
class numeric_limits<T, typename enable_if<
!std::numeric_limits<T>::is_integer &&
std::numeric_limits<T>::is_signed
>::type > :
public std::numeric_limits<T>
{
public:
typedef std::numeric_limits<T> BaseClass;
static inline T highest() { return BaseClass::max(); }
static inline T lowest() { return -BaseClass::max(); }
};
#endif // DOXYGEN end of hidden code
} // MDSplus
// YOU REALLY SHOULD PREFER BOOST CONVERSION //
// #include <boost/numeric/conversion/cast.hpp>
// THIS IS BASED ON STD LIMITS //
////////////////////////////////////////////////////////////////////////////////
// numeric_cast_traits ///////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
namespace MDSplus {
namespace detail {
template < typename Target, typename Source >
struct numeric_cast_trait {
typedef numeric_limits<Source> Slimits;
typedef numeric_limits<Target> Tlimits;
static const bool is_coercion = Slimits::digits > Tlimits::digits;
static const bool is_u2s = !Slimits::is_signed && Tlimits::is_signed;
static const bool is_s2u = Slimits::is_signed && !Tlimits::is_signed;
};
template < typename Target, typename Source, typename EnableIf = void >
struct numeric_cast_max_rule {
static inline void apply(Source value) {
if( value > static_cast<Source>( numeric_limits<Target>::highest() ) )
throw ( std::overflow_error("scalar cast overflow"));
}
};
template < typename Target, typename Source, typename EnableIf = void >
struct numeric_cast_min_rule {
static inline void apply(Source value) {
if( value < static_cast<Source>( numeric_limits<Target>::lowest() ) )
throw ( std::underflow_error("scalar cast underflow"));
}
};
template < typename Target, typename Source, typename EnableIf = void >
struct numeric_cast_precision_rule {
typedef numeric_cast_trait<Target,Source> trait;
static inline void apply(Source value UNUSED_ARGUMENT) {
// if( trait::is_coercion ) {
// if( value > (Source)(1<<numeric_limits<Target>::digits) )
// throw(std::range_error("scalar loss of precision for digit overflow") );
// if( trait::Slimits::is_signed && value < -static_cast<Source>(1<<numeric_limits<Target>::digits) )
// throw(std::range_error("scalar loss of precision for digit underflow") );
// }
// if(value != static_cast<Source>(static_cast<Target>(value)) )
// throw(std::range_error("scalar loss of precision") );
}
};
template < typename Target, typename Source, typename EnableIf = void >
struct numeric_cast_nan_rule {
typedef numeric_cast_trait<Target,Source> trait;
static inline void apply(Source value) {
if( std::isnan(value) ) throw(std::range_error("Trying to convert Nan to an Integer type"));
}
};
template < typename Target, typename Source, typename EnableIf = void >
struct numeric_cast_inf_rule {
typedef numeric_cast_trait<Target,Source> trait;
static inline void apply(Source value) {
if( std::isinf(value) ) throw(std::range_error("Trying to convert Inf to an Integer type"));
}
};
////////////////////////////////////////////////////////////////////////////////
// NumericCastImpl ///////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
template <typename Target, typename Source, class Enable = void >
struct NumericCastImpl {
static Target numeric_cast(Source value __attribute__ ((unused))) {}
};
// Integer -> Integer
template < typename Target, typename Source >
struct NumericCastImpl < Target, Source,
typename enable_if<
numeric_limits<Source>::is_integer &&
numeric_limits<Target>::is_integer &&
numeric_cast_trait<Target,Source>::is_coercion
>
::type >
{
static Target numeric_cast(Source value ) {
if( !numeric_cast_trait<Target,Source>::is_u2s )
numeric_cast_min_rule<Target,Source>::apply(value);
numeric_cast_max_rule<Target,Source>::apply(value);
return static_cast<Target>(value);
}
};
template < typename Target, typename Source >
struct NumericCastImpl < Target, Source,
typename enable_if<
numeric_limits<Source>::is_integer &&
numeric_limits<Target>::is_integer &&
!numeric_cast_trait<Target,Source>::is_coercion
>
::type >
{
static Target numeric_cast(Source value ) {
if( numeric_cast_trait<Target,Source>::is_s2u )
numeric_cast_min_rule<Target,Source>::apply(value);
return static_cast<Target>(value);
}
};
// Integer -> Float
template < typename Target, typename Source >
struct NumericCastImpl < Target, Source,
typename enable_if<
numeric_limits<Source>::is_integer &&
!numeric_limits<Target>::is_integer &&
numeric_cast_trait<Target,Source>::is_coercion
>
::type >
{
static Target numeric_cast(Source value ) {
numeric_cast_precision_rule<Target,Source>::apply(value);
return static_cast<Target>(value);
}
};
template < typename Target, typename Source >
struct NumericCastImpl < Target, Source,
typename enable_if<
numeric_limits<Source>::is_integer &&
!numeric_limits<Target>::is_integer &&
!numeric_cast_trait<Target,Source>::is_coercion
>
::type >
{
static Target numeric_cast(Source value ) {
return static_cast<Target>(value);
}
};
// Float -> Integer
template < typename Target, typename Source >
struct NumericCastImpl < Target, Source,
typename enable_if<
!numeric_limits<Source>::is_integer &&
numeric_limits<Target>::is_integer
>
::type >
{
static Target numeric_cast(Source value ) {
numeric_cast_nan_rule<Target,Source>::apply(value);
numeric_cast_inf_rule<Target,Source>::apply(value);
numeric_cast_min_rule<Target,Source>::apply(value);
numeric_cast_max_rule<Target,Source>::apply(value);
numeric_cast_precision_rule<Target,Source>::apply(value);
return static_cast<Target>(value);
}
};
// Float -> Float
template < typename Target, typename Source >
struct NumericCastImpl < Target, Source,
typename enable_if<
!numeric_limits<Source>::is_integer &&
!numeric_limits<Target>::is_integer &&
numeric_cast_trait<Target,Source>::is_coercion
>
::type >
{
static Target numeric_cast(Source value ) {
numeric_cast_min_rule<Target,Source>::apply(value);
numeric_cast_max_rule<Target,Source>::apply(value);
numeric_cast_precision_rule<Target,Source>::apply(value);
return static_cast<Target>(value);
}
};
template < typename Target, typename Source >
struct NumericCastImpl < Target, Source,
typename enable_if<
!numeric_limits<Source>::is_integer &&
!numeric_limits<Target>::is_integer &&
!numeric_cast_trait<Target,Source>::is_coercion
>
::type >
{
static Target numeric_cast(Source value ) {
return static_cast<Target>(value);
}
};
} // detail
////////////////////////////////////////////////////////////////////////////////
// numeric_cast //////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// For each possible scalar conversion, from one native type to another one, a
/// specific cast function was implemented to check if the conversion is not
/// meaningless. If no accepted conversion was found the library throws an
/// exception identifying the error status. For instance a Int8 n = -1 casted
/// to Uint32 will throw a std::underflow_error.
///
/// All conversion checks is managed by a template specialization of the
/// MDSplus::numeric_cast() function. This function uses the
/// std::numeric_limits to get boundaries for the source and target numeric
/// domains of the specific cast, so at the end the test is done using the
/// standard template library numeric traits. The implementation was done using
/// very few type traits and the standard std::numeric_limits class.
///
/// Four checks are selected by traits to be performed on values:
///
/// - numeric_cast_max_rule
/// - numeric_cast_min_rule
/// - numeric_cast_precision_rule (disabled at the moment)
/// - numeric_cast_nan_rule
///
/// The possible exception that the function can throw are:
///
/// | Exception | Description |
/// |-----------------------|------------------------------------------|
/// | std::overflow_error | exceeded the upper limitof target domain |
/// | std::underflow_error | exceeded the lower limitof target domain |
/// | std::range_error | nan or inf converted to integer domain |
/// | std::range_error | loss of precision (disabled) |
///
template <typename Target, typename Source>
inline Target numeric_cast(Source value) {
return detail::NumericCastImpl<Target,Source>::numeric_cast(value);
}
} // MDSplus
#endif // NUMERIC_CAST_HPP
|
(* Exercise 119 *)
Require Import BenB.
Variables A B C D : Prop.
Theorem exercise_119 : ~~A -> ~~(A \/ B).
Proof.
imp_i a1.
neg_i (~A) a2.
hyp a1.
neg_i (A \/ B) a3.
hyp a2.
dis_i1.
hyp a3.
Qed. |
[STATEMENT]
lemma borel_measurable_vimage_borel:
fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space"
shows "f \<in> borel_measurable (lebesgue_on S) \<longleftrightarrow>
(\<forall>T. T \<in> sets borel \<longrightarrow> {x \<in> S. f x \<in> T} \<in> sets (lebesgue_on S))"
(is "?lhs = ?rhs")
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (f \<in> borel_measurable (lebesgue_on S)) = (\<forall>T. T \<in> sets borel \<longrightarrow> {x \<in> S. f x \<in> T} \<in> sets (lebesgue_on S))
[PROOF STEP]
proof
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. f \<in> borel_measurable (lebesgue_on S) \<Longrightarrow> \<forall>T. T \<in> sets borel \<longrightarrow> {x \<in> S. f x \<in> T} \<in> sets (lebesgue_on S)
2. \<forall>T. T \<in> sets borel \<longrightarrow> {x \<in> S. f x \<in> T} \<in> sets (lebesgue_on S) \<Longrightarrow> f \<in> borel_measurable (lebesgue_on S)
[PROOF STEP]
assume f: ?lhs
[PROOF STATE]
proof (state)
this:
f \<in> borel_measurable (lebesgue_on S)
goal (2 subgoals):
1. f \<in> borel_measurable (lebesgue_on S) \<Longrightarrow> \<forall>T. T \<in> sets borel \<longrightarrow> {x \<in> S. f x \<in> T} \<in> sets (lebesgue_on S)
2. \<forall>T. T \<in> sets borel \<longrightarrow> {x \<in> S. f x \<in> T} \<in> sets (lebesgue_on S) \<Longrightarrow> f \<in> borel_measurable (lebesgue_on S)
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
f \<in> borel_measurable (lebesgue_on S)
[PROOF STEP]
show ?rhs
[PROOF STATE]
proof (prove)
using this:
f \<in> borel_measurable (lebesgue_on S)
goal (1 subgoal):
1. \<forall>T. T \<in> sets borel \<longrightarrow> {x \<in> S. f x \<in> T} \<in> sets (lebesgue_on S)
[PROOF STEP]
using measurable_sets [OF f]
[PROOF STATE]
proof (prove)
using this:
f \<in> borel_measurable (lebesgue_on S)
?S \<in> sets borel \<Longrightarrow> f -` ?S \<inter> space (lebesgue_on S) \<in> sets (lebesgue_on S)
goal (1 subgoal):
1. \<forall>T. T \<in> sets borel \<longrightarrow> {x \<in> S. f x \<in> T} \<in> sets (lebesgue_on S)
[PROOF STEP]
by (simp add: Collect_conj_eq inf_sup_aci(1) space_restrict_space vimage_def)
[PROOF STATE]
proof (state)
this:
\<forall>T. T \<in> sets borel \<longrightarrow> {x \<in> S. f x \<in> T} \<in> sets (lebesgue_on S)
goal (1 subgoal):
1. \<forall>T. T \<in> sets borel \<longrightarrow> {x \<in> S. f x \<in> T} \<in> sets (lebesgue_on S) \<Longrightarrow> f \<in> borel_measurable (lebesgue_on S)
[PROOF STEP]
qed (simp add: borel_measurable_vimage_open_interval) |
%solving.tex
%
% Macaulay 2 Chapter:
% From Enumerative geometry to solving polynomial systems
%
% Frank Sottile
%
% Begun: 25 April 1999
% Began new version 27 July
% Preliminary version 27 August
% Started working again 1 July 2000
% Completed & Submitted 20 July
% arXiv.org/math.AG/0007142 npvkp
% Title: "An excursion ...(title above)... with Macaulay2"
% Final revised version 14 November
% Replaced arXiv version 15 November
% Really Final version 25 January 2000
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% WARNING: * On an AMD K6/2 300MHz w/ 256MB the M2 code %
% takes 8:15 minutes to run and uses 82MB %
% * On Intel PIII 600MHz w/ 256K cache & 256MB %
% the M2 code takes 4:15 minutes %
% * On Intel PIII 850MHz w/ 256K cache & 1GB %
% the M2 code takes 3:20 minutes %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\title{From Enumerative Geometry to Solving Systems of Polynomial Equations}
\titlerunning{From Enumerative Geometry to Solving Equations}
\toctitle{From Enumerative Geometry to Solving Systems of Polynomial Equations}
\author{Frank Sottile\thanks{Supported in part by NSF grant DMS-0070494.}}
\authorrunning{F. Sottile}
% \institute{Department of Mathematics and Statistics, University of
% Massachusetts, Amherst, MA 01003, USA}
\maketitle
\begin{abstract}
Solving a system of polynomial equations is a ubiquitous problem in
the applications of mathematics.
Until recently, it has been hopeless to find explicit solutions to such
systems, and mathematics has instead developed deep and
powerful theories about the solutions to polynomial equations.
Enumerative Geometry is concerned with counting the
number of solutions when the polynomials come from a geometric situation and
Intersection Theory\index{intersection theory} gives methods to accomplish the enumeration.
We use \Mtwo{}\/ to investigate some problems from enumerative geometry,
illustrating some applications of symbolic computation to this important
problem of solving systems of polynomial equations.
Besides enumerating solutions to the resulting polynomial systems, which
include overdetermined, deficient, and improper systems, we address the
important question of real solutions to these geometric problems.
\end{abstract}
\section{Introduction}
A basic question to ask about a system of polynomial equations is
its number of solutions\index{polynomial equations}.
For this, the fundamental result is the following
B\'ezout Theorem\index{Bezout's Theorem@B\'ezout's Theorem}.
\begin{theorem}
The number of isolated solutions to a system of polynomial equations
$$
f_1(x_1,\ldots,x_n)=f_2(x_1,\ldots,x_n)= \cdots
=f_n(x_1,\ldots,x_n)=0
$$
is bounded by $d_1d_2\cdots d_n$, where $d_i:=\deg f_i$.
If the polynomials are generic, then this bound is attained for
solutions in an algebraically closed field\index{field!algebraically closed}.
\end{theorem}
Here, isolated is taken with respect to the algebraic closure.
%There are examples where this result fails without that restriction.
This B\'ezout Theorem is a consequence of the refined B\'ezout Theorem of
Fulton and MacPherson~\cite[\S 1.23]{SO:Fu84a}.
A system of polynomial equations with fewer than this
degree bound or B\'ezout number\index{Bezout number@B\'ezout number} of solutions is called
{\it deficient}\index{polynomial equations!deficient},
and there are well-defined classes of deficient systems that satisfy other
bounds.
For example, fewer monomials lead to fewer solutions, for which polyhedral
bounds~\cite{SO:Bernstein} on the number of solutions are often tighter (and
no weaker than) the B\'ezout number, which applies when
all monomials are present.
When the polynomials come from geometry, determining the
number of solutions is the central problem in enumerative
geometry\index{enumerative geometry}.
Symbolic computation\index{symbolic computation} can help compute the
solutions to a system of equations
that has only isolated solutions.
In this case, the polynomials generate a zero-dimensional ideal
$I$\index{artinian, {\it see also} ideal,
zero-dimensional}\index{ideal!zero-dimensional}.
The {\it degree}\index{ideal!degree} of $I$ is $\dim_k k[X]/I$, the dimension of the
$k$-vector space $k[X]/I$, which is also the
number of standard monomials in any term order.
This degree gives an upper bound on
the number of solutions, which is attained when $I$ is
radical\index{ideal!radical}.
\begin{example}\label{ex:one}
We illustrate this discussion with an example.
Let $f_1$, $f_2$, $f_3$, and $f_4$ be random quadratic polynomials in the ring
${\mathbb F}_{101}[y_{11},y_{12},y_{21},y_{22}]$.
%
<<<R = ZZ/101[y11, y12, y21, y22];>>>
%
<<<PolynomialSystem = apply(1..4, i ->
random(0, R) + random(1, R) + random(2, R));>>>
%
The ideal they generate has dimension 0 and degree $16=2^4$, which is the
B\'ezout number.
%
<<<I = ideal PolynomialSystem;>>>
%
<<<dim I, degree I>>>
%
If we restrict the monomials which appear in the $f_i$ to be among
$$
1,\;\ y_{11},\;\ y_{12},\;\ y_{21},\;\ y_{22},\;\
y_{11}y_{22},\;\ \mbox{ and }\;\ y_{12}y_{21},
$$
then the ideal they generate again has dimension 0, but its degree is now 4.
%
<<<J = ideal (random(R^4, R^7) * transpose(
matrix{{1, y11, y12, y21, y22, y11*y22, y12*y21}}));>>>
%
<<<dim J, degree J>>>
%
If we further require that the coefficients of the
quadratic terms sum to zero, then the ideal they generate now
has degree 2.
%
<<<K = ideal (random(R^4, R^6) * transpose(
matrix{{1, y11, y12, y21, y22, y11*y22 - y12*y21}}));>>>
%
<<<dim K, degree K>>>
%
In Example~\ref{ex:G22}, we shall see how this last specialization is
geometrically meaningful.
\end{example}
For us, enumerative geometry\index{enumerative geometry} is concerned
with {\sl enumerating geometric figures of some kind having
specified positions with respect to general fixed figures}.
That is, counting the solutions to a geometrically meaningful
system of polynomial equations\index{polynomial equations}.
We use \Mtwo{}\/ to investigate some enumerative geometric
problems\index{enumerative problem} from this point of view.
The problem of enumeration will be solved by computing the
degree\index{ideal!degree} of the
(0-dimensional) ideal generated by the polynomials.
\section{Solving Systems of Polynomials}
We briefly discuss some aspects of solving systems of polynomial
equations\index{solving polynomial equations}.
For a more complete survey, see the relevant chapters
in~\cite{SO:CCS,SO:CLO92}.
Given an ideal $I$ in a polynomial ring $k[X]$, set
${\mathcal V}(I):= {\rm Spec}\,k[X]/I$.
When $I$ is generated by the polynomials
$f_1,\ldots,f_N$, ${\mathcal V}(I)$ gives the set of solutions in affine
space to the system
\begin{equation}\label{eq:system}
f_1(X)\ =\ \cdots\ =\ f_N(X)\ =\ 0
\end{equation}
a geometric structure.
These solutions are the {\it roots} of the ideal $I$.
The degree of a zero-dimensional ideal $I$ provides an algebraic count of
its roots.
The degree of its radical counts
roots in the algebraic closure, ignoring multiplicities.
\subsection{Excess Intersection}
Sometimes, only a proper (open) subset of affine space is
geometrically meaningful, and we want to count only the meaningful roots of
$I$.
Often the roots ${\mathcal V}(I)$ has positive dimensional components that lie
in the complement of the meaningful subset.
One way to treat this situation of excess or improper intersection is to
saturate\index{saturation} $I$ by a polynomial $f$ vanishing on the extraneous
roots.
This has the effect of working in $k[X][f^{-1}]$, the coordinate ring of the
complement of ${\mathcal V}(f)$~\cite[Exer.~2.3]{SO:MR97a:13001}.
\begin{example}\label{ex:two}
We illustrate this with an example.
Consider the following ideal in ${\mathbb F}_7[x,y]$.
%
<<<R = ZZ/7[y, x, MonomialOrder=>Lex];>>>
%
<<<I = ideal (y^3*x^2 + 2*y^2*x + 3*x*y, 3*y^2 + x*y - 3*y);>>>
%
Since the generators have greatest common factor $y$, $I$ defines
finitely many points together with the line $y=0$.
Saturate $I$\/ by the variable $y$ to obtain the ideal $J$ of isolated roots.
%
<<<J = saturate(I, ideal(y))>>>
%
The first polynomial factors completely in ${\mathbb F}_7[x]$,
%
<<<factor(J_0)>>>
%
and so the isolated roots of $I$ are $(2,5),(-1,-1),(0,1)$, and $(-2,-3)$.
\end{example}
Here, the extraneous roots came from a common factor in both
equations.
A less trivial example of this phenomenon will be seen in
Section~\ref{sec:tangent_lines}.
\subsection{Elimination, Rationality, and Solving}
Elimination theory\index{elimination theory} can be used to study the
roots of a zero-dimensional ideal $I\subset k[X]$\index{solving polynomial
equations!via elimination}.
A polynomial $h\in k[X]$ defines a map
$k[y]\rightarrow k[X]$ (by $y\mapsto h$) and a corresponding projection
$h\colon{\rm Spec}\,k[X]\twoheadrightarrow{\mathbb A}^1$.
The generator $g(y)\in k[y]$ of the
kernel\index{kernel of a ring map} of the map $k[y]\to k[X]/I$ is called an
{\it eliminant}\index{eliminant}
and it has the property that ${\mathcal V}(g)=h({\mathcal V}(I))$.
When $h$ is a coordinate function $x_i$, we may consider the eliminant to be
in the polynomial ring $k[x_i]$, and we have
$\langle g(x_i)\rangle=I\cap k[x_i]$.
The most important result concerning eliminants is the Shape
Lemma\index{Shape Lemma}~\cite{SO:BMMT}.
\medskip
\noindent{\bf Shape Lemma.}
{\it
Suppose $h$ is a linear polynomial and $g$ is the corresponding eliminant of
a zero-dimensional ideal $I\subset k[X]$ with $\deg(I)=\deg(g)$.
Then the roots of $I$ are defined in the splitting
field\index{field!splitting} of $g$ and
$I$ is radical\index{ideal!radical} if and only if $g$ is square-free.
Suppose further that $h=x_1$ so that $g=g(x_1)$.
Then, in the lexicographic term order
with $x_1<x_2<\cdots<x_n$, $I$ has a Gr\"obner basis\index{Grobner basis@Gr\"obner basis} of
the form:
%
\begin{equation}\label{triangular}
g(x_1),\ \ x_2-g_2(x_1), \ \ \ldots,\ \ x_n-g_n(x_1)\,,
\end{equation}
%
where $\deg(g)>\deg(g_i)$ for $i=2,\ldots,n$.
}\medskip
When $k$ is infinite and $I$ is radical, an eliminant $g$ given by a generic
linear polynomial $h$ will satisfy $\deg(g)=\deg(I)$.
Enumerative geometry\index{enumerative geometry} counts solutions
when the fixed figures are generic.
We are similarly concerned with the generic situation of
$\deg(g)=\deg(I)$.
In this case, eliminants provide a useful computational device to study
further questions about the roots of $I$.
For instance, the Shape Lemma holds for the saturated ideal of Example~\ref{ex:two}.
Its eliminant, which is the polynomial {\tt J{\char`\_}0}, factors completely
over the ground field ${\mathbb F}_7$, so all four solutions are defined
in ${\mathbb F}_7$.
In Section 4.3, we will use eliminants in another way, to show that
an ideal is radical.
Given a polynomial $h$ in a zero-dimensional ring $k[X]/I$, the
procedure {\tt eliminant(h, k[y])} finds a linear relation modulo $I$
among the powers $1, h, h^2, \ldots, h^d$ of $h$ with $d$ minimal
and returns this as a polynomial in $k[y]$.
This procedure is included in the \Mtwo{}\/ package
{\tt realroots.m2}.
%
<<<load "realroots.m2">>>
%
<<<code eliminant>>>
%
Here, {\tt M} is a matrix whose rows are the normal forms of the
powers $1$, $h$, $h^2$, $\ldots$, $h^d$ of $h$, for $d$ the degree of the ideal.
The columns of the kernel {\tt N} of {\tt transpose M} are a basis of the
linear relations among these powers.
The matrix {\tt P} converts these relations into polynomials.
Since {\tt N} is in column echelon form, the initial entry of {\tt P}
is the relation of minimal degree.
(This method is often faster than na\"\i vely computing the kernel of the
map $k[Z]\to A$ given by $Z\mapsto h$, which is implemented by
{\tt eliminantNaive(h, Z)}.)
Suppose we have an eliminant\index{eliminant} $g(x_1)$ of a zero-dimensional
ideal $I\subset k[X]$ with $\deg(g)=\deg(I)$, and we have computed the
lexicographic Gr\"obner basis~(\ref{triangular}).
Then the roots of $I$ are
%
\begin{equation}\label{tri_roots}
\{ (\xi_1,g_2(\xi_1), \ldots, g_n(\xi_1))\mid g(\xi_1)=0\}\,.
\end{equation}
Suppose now that $k={\mathbb Q}$ and we seek floating point approximations
for the (complex) roots of $I$.
Following this method, we first compute floating point solutions to
$g(\xi)=0$, which give all the $x_1$-coordinates of the roots of $I$, and
then use~(\ref{tri_roots}) to find the other coordinates.
The difficulty here is that enough precision may be lost in evaluating
$g_i(\xi_1)$ so that the result is a poor approximation for the other
components $\xi_i$.
\subsection{Solving with Linear Algebra}
We describe another method based upon numerical linear algebra.
When $I\subset k[X]$ is zero-dimensional, $A=k[X]/I$ is a finite-dimensional
$k$-vector space, and {\it any} Gr\"obner basis for $I$ gives an efficient
algorithm to compute ring operations using linear algebra.
In particular, multiplication by $h\in A$ is a linear transformation
$m_h:A\to A$ and the command {\tt regularRep(h)} from
{\tt realroots.m2} gives the matrix of $m_h$ in
terms of the standard basis of $A$.
%
<<<code regularRep>>>
%
Since the action of $A$ on itself is faithful, the minimal polynomial of
$m_h$ is the eliminant\index{eliminant} corresponding to $h$.
The procedure {\tt charPoly(h, Z)} in {\tt realroots.m2}
computes the characteristic polynomial
$\det(Z\cdot\mbox{\it Id} - m_h)$ of $h$.
%
<<<code charPoly>>>
%
When this is the minimal polynomial (the situation of the Shape Lemma),
this procedure often computes the eliminant faster than does
{\tt eliminant}, and for systems of moderate degree, much faster than
na\"\i vely computing the kernel of the map $k[Z]\to A$ given by $Z\mapsto h$.
The eigenvalues and eigenvectors of $m_h$ give another algorithm for finding
the roots of $I$\index{solving polynomial equations!via eigenvectors}.
The engine for this is the following result\index{Stickelberger's Theorem}.
\medskip
\noindent{\bf Stickelberger's Theorem. }
{\it
Let $h\in A$ and $m_h$ be as above.
Then there is a one-to-one correspondence between eigenvectors
${\bf v}_\xi$ of $m_h$ and roots $\xi$ of $I$, the eigenvalue of $m_h$ on
${\bf v}_\xi$ is the value $h(\xi)$ of $h$ at $\xi$, and the multiplicity
of this eigenvalue (on the eigenvector ${\bf v}_\xi$) is the
multiplicity of the root $\xi$.
}\medskip
Since the linear transformations $m_h$ for $h\in A$ commute, the
eigenvectors ${\bf v}_\xi$ are common to all $m_h$.
Thus we may compute the roots of a zero-dimensional ideal $I\subset k[X]$
by first computing floating-point approximations to the
eigenvectors ${\bf v}_\xi$ of $m_{x_1}$.
Then the root $\xi\ =\ (\xi_1,\ldots,\xi_n)$ of $I$ corresponding to the
eigenvector ${\bf v}_\xi$ has $i$th coordinate satisfying
%
\begin{equation}\label{eigenv}
m_{x_i}\cdot {\bf v}_\xi\ =\ \xi_i \cdot {\bf v}_\xi\,.
\end{equation}
%
An advantage of this method is that we may use structured numerical linear
algebra after the matrices $m_{x_i}$ are precomputed using exact arithmetic.
(These matrices are typically sparse and have additional structures which may
be exploited.)
Also, the coordinates $\xi_i$ are {\it linear} functions of the floating
point entries of ${\bf v}_\xi$, which affords greater precision than
the non-linear evaluations $g_i(\xi_1)$ in the method based upon elimination.
While in principle only one of the $\deg(I)$ components of the vectors
in~(\ref{eigenv}) need be computed, averaging the results from all
components can improve precision.
\subsection{Real Roots}
Determining the real roots of a polynomial system is a challenging problem
with real world applications\index{solving polynomial equations!real solutions}.
When the polynomials come from geometry, this is the main problem of
real enumerative geometry\index{enumerative geometry!real}.
Suppose $k\subset{\mathbb R}$ and $I\subset k[X]$ is zero-dimensional.
If $g$ is an eliminant of $k[X]/I$
with $\deg(g)=\deg(I)$, then the real roots of
$g$ are in 1-1 correspondence with the real roots of $I$.
Since there are effective methods for counting the real roots of a univariate
polynomial, eliminants give a na\"\i ve, but useful method for determining the
number of real roots to a polynomial system.
(For some applications of this technique in mathematics,
see~\cite{SO:RS98,SO:So_shap-www,SO:So00b}.)
The classical symbolic method of Sturm, based upon Sturm sequences, counts
the number of real roots of a univariate polynomial in an interval.
When applied to an eliminant satisfying the Shape Lemma, this method counts
the number of real roots of the ideal.
This is implemented in \Mtwo{}\/ via the command
{\tt SturmSequence(f)} of {\tt realroots.m2}
%
<<<code SturmSequence>>>
%
The last few lines of {\tt SturmSequence} construct the Sturm
sequence\index{Sturm sequence} of the univariate argument $f$:
This is $(f_0, f_1, f_2,\ldots)$ where $f_0=f$, $f_1=f'$, and
for $i>1$, $f_i$ is the normal form reduction of $-f_{i-2}$ modulo
$f_{i-1}$.
Given any real number $x$, the {\it variation} of $f$ at $x$ is the number of
changes in sign of the sequence $(f_0(x), f_1(x), f_2(x),\ldots)$ obtained by
evaluating the Sturm sequence of $f$ at $x$.
Then the number of real roots of $f$ over an interval $[x,y]$ is the
difference of the variation of $f$ at $x$ and at $y$.
The \Mtwo{}\/ commands {\tt numRealSturm} and
{\tt numPosRoots} (and also {\tt numNegRoots}) use this method to respectively
compute the total number of real roots and the number of positive roots of
a univariate polynomial.
%
<<<code numRealSturm>>>
%
<<<code numPosRoots>>>
%
These use the commands {\tt signAt}$*${\tt (f)}, which
give the sign of ${\tt f}$
at $*$.
(Here, $*$ is one of {\tt Infinity}, {\tt zero}, or {\tt MinusInfinity}.)
Also {\tt variations(c)} computes the
number of sign changes in the sequence {\tt c}.
%
<<<code variations>>>
%
A more sophisticated method to compute the number of real roots which can also
give information about their location uses the rank and
signature\index{bilinear form!signature} of the
symmetric trace form.
Suppose $I\subset k[X]$ is a zero-dimensional ideal and
set $A:=k[X]/I$.
For $h\in k[X]$, set $S_h(f,g):={\rm trace}(m_{hfg})$.
It is an easy exercise that $S_h$ is a symmetric bilinear form\index{bilinear
form!symmetric} on $A$.
The procedure {\tt traceForm(h)} in {\tt realroots.m2}
computes this trace form\index{trace form} $S_h$.
%
<<<code traceForm>>>
%
The value of this construction is the following theorem.
\begin{theorem}[\cite{SO:BW,SO:PRS}]\label{t:PRS}
Suppose $k\subset{\mathbb R}$ and $I$ is a zero-dimensional ideal in
$k[x_1,\ldots,x_n]$ and consider ${\mathcal V}(I)\subset {\mathbb C}^n$.
Then, for $h\in k[x_1,\ldots,x_n]$, the signature $\sigma(S_h)$ and rank
$\rho(S_h)$ of the bilinear form $S_h$ satisfy
\begin{eqnarray*}
\sigma(S_h)&=&\#\{a\in{\mathcal V}(I)\cap{\mathbb R}^n:h(a)>0\}
- \#\{a\in{\mathcal V}(I)\cap{\mathbb R}^n:h(a)<0\}\,\\
\rho(S_h)&=&\#\{a\in{\mathcal V}(I):h(a)\neq0\}\,.
\end{eqnarray*}
\end{theorem}
That is, the rank of $S_h$ counts roots in
${\mathbb C}^n-{\mathcal V}(h)$, and its signature counts the real roots
weighted by the sign of $h$ (which is $-1$, $0$, or $1$) at each root.
The command {\tt traceFormSignature(h)} in {\tt realroots.m2} returns the
rank and signature of the trace form $S_h$.
%
<<<code traceFormSignature>>>
%
The \Mtwo{}\/ command {\tt numRealTrace(A)} simply returns the number of
real roots of $I$, given ${\tt A}=k[X]/I$.
%
<<<code numRealTrace>>>
%
\begin{example}
We illustrate these methods on the following polynomial system.
%
<<<R = QQ[x, y];>>>
%
<<<I = ideal (1 - x^2*y + 2*x*y^2, y - 2*x - x*y + x^2);>>>
%
The ideal $I$ has dimension zero and degree 5.
%
<<<dim I, degree I>>>
%
We compare the two methods to compute the eliminant of $x$ in
the ring $R/I$.
%
<<<A = R/I;>>>
%
<<<time g = eliminant(x, QQ[Z])>>>
%
<<<time g = charPoly(x, Z)>>>
%
The eliminant has 3 real roots, which we test in two different ways.
%
<<<numRealSturm(g), numRealTrace(A)>>>
%
We use Theorem~\ref{t:PRS} to isolate these roots in the $x,y$-plane.
%
<<<traceFormSignature(x*y);>>>
%
Thus all 3 real roots lie in the first and third
quadrants (where $xy>0$).
We isolate these further.
%
<<<traceFormSignature(x - 2);>>>
%
This shows that two roots lie in the first quadrant with $x>2$ and one lies
in the third.
Finally, one of the roots lies in the triangle $y>0$, $x>2$, and $x+y<3$.
%
<<<traceFormSignature(x + y - 3);>>>
Figure~\ref{fig:roots} shows these three roots (dots), as well as the
lines $x+y=3$ and $x=2$.
\begin{figure}
$$
% 40 pt = 1 unit
%
%
\setlength{\unitlength}{0.8pt}
\begin{picture}(220,110)(-60,-50)
% y - axis
\put(0,-50){\vector(0,1){110}} \put(0,0){\vector(0,-1){50}}
\put(-11,47){$y$}
\put(-5,-40){\line(1,0){10}} \put(6,-42.8){$-1$}
\put(-5,40){\line(1,0){10}} \put(6, 36.5){$1$}
% \put(-5,80){\line(1,0){10}} \put(6, 77){$2$}
% x - axis
\put(-60,0){\vector(1,0){220}} \put(0,0){\vector(-1,0){60}}
\put(-40,-5){\line(0,1){10}} \put(-50,-15){$-1$}
\put(40,-5){\line(0,1){10}} \put(37.5,-15){$1$}
\put(120,-5){\line(0,1){10}} \put(117,-15){$3$}
\put(-51,5){$x$}
\thicklines
\put(80,-50){\line(0,1){110}} \put(85,-35){$x=2$}
\put(160,-40){\line(-1,1){100}}%\put(15,50){$x+y=3$}
\put(100,25){$x+y=3$}
\put(-26.2, -42.1){\circle*{2}}
\put(86.3, 11.8){\circle*{2}}
\put(112.8, 50.8){\circle*{2}}
\end{picture}
$$
\caption{Location of roots\label{fig:roots}}
\end{figure}
\end{example}
\subsection{Homotopy Methods}
We describe symbolic-numeric
{\it homotopy continuation methods}\index{homotopy continuation}
for finding approximate complex solutions to a system of
equations\index{solving polynomial equations!via numerical homotopy}.
These exploit the traditional principles of conservation of number and
specialization from enumerative geometry\index{enumerative geometry}.
Suppose we seek the isolated solutions of a system $F(X)=0$
where $F=(f_1,\ldots,f_n)$ are polynomials in the variables
$X=(x_1,\ldots,x_N)$.
First, a {\em homotopy} $H(X,t)$ is found with the following properties:
\begin{enumerate}
\item $H(X,1)= F(X)$.
\item The isolated solutions of the {\it start system} $H(X,0)=0$ are known.
\item The system $H(X,t)=0$ defines finitely many (complex) curves,
and each isolated solution of the original system $F(X)=0$ is
connected to an isolated solution $\sigma_i(0)$ of $H(X,0)=0$ along
one of these curves.
\end{enumerate}
Next, choose a generic smooth path $\gamma(t)$ from 0 to 1 in the complex
plane.
Lifting $\gamma$ to the curves $H(X,t)=0$ gives
smooth paths $\sigma_i(t)$ connecting each solution
$\sigma_i(0)$ of the start system to a solution of the original system.
The path $\gamma$ must avoid the finitely many points in ${\mathbb C}$ over
which the curves are singular or meet other components of the solution set
$H(X,t)=0$.
Numerical path continuation is used to trace each path
$\sigma_i(t)$ from $t=0$ to $t=1$.
When there are fewer solutions to $F(X)=0$ than to
$H(X,0)=0$, some paths will diverge or become singular as
$t\rightarrow 1$, and it is expensive to trace such a path.
The homotopy is {\it optimal}\index{homotopy!optimal} when this does not
occur.
When $N=n$ and the $f_i$ are generic, set
$G(X):=(g_1,\ldots,g_n)$ with $g_i=(x_i-1)(x_i-2)\cdots(x_i-d_i)$
where $d_i:=\deg(f_i)$.
Then the {\it B\'ezout homotopy}\index{homotopy!B\'ezout}
$$
H(X,t)\quad :=\quad tF(X)\ +\
(1-t)G(X)
$$
is optimal.
This homotopy furnishes an effective demonstration of
the bound in B\'ezout's Theorem\index{Bezout's Theorem@B\'ezout's Theorem} for the number of
solutions to $F(X)=0$.
When the polynomial system is deficient, the B\'ezout homotopy is not optimal.
When $n>N$ (often the case in geometric examples),
the B\'ezout homotopy does not apply.
In either case, a different strategy is needed.
Present optimal homotopies for such systems all exploit some structure of
the systems they are designed to solve.
The current state-of-the-art is described in~\cite{SO:Ver99}.
\begin{example}\label{example:Groebner}
The Gr\"obner homotopy\index{homotopy!Gr\"obner}~\cite{SO:HSS} is an optimal
homotopy\index{homotopy!optimal} that exploits a square-free initial
ideal\index{initial ideal!square-free}.
Suppose our system has the form
$$
F\ :=\ g_1(X),\ldots,g_m(X),\ \Lambda_1(X),\ldots,\Lambda_d(X)
$$
where $g_1(X),\ldots,g_m(X)$ form a Gr\"obner basis for an ideal $I$
with respect to a given term order $\prec$, $\Lambda_1,\ldots,\Lambda_d$ are
linear forms with $d=\dim({\mathcal V}(I))$, {\it and}\/ we assume that
the initial ideal ${\rm in}_\prec I$ is square-free.
This last, restrictive, hypothesis occurs for
certain determinantal varieties\index{determinantal variety}.
As in~\cite[Chapter 15]{SO:MR97a:13001}, there exist polynomials
$g_i(X,t)$ interpolating between $g_i(X)$ and their initial terms
${\rm in}_\prec g_i(X)$
$$
g_i(X;1)\ =\ g_i(X) \qquad\mbox{and}\qquad
g_i(X;0) \ =\ {\rm in}_\prec g_i(X)
$$
so that $\langle g_1(X,t),\ldots,g_m(X,t)\rangle$ is a flat family
with generic fibre isomorphic to $I$ and special fibre
${\rm in}_\prec I$.
The {\it Gr\"obner homotopy} is
$$
H(X,t)\ :=\
g_1(X,t),\ldots,g_m(X,t),\ \Lambda_1(X),\ldots,\Lambda_d(X).
$$
Since ${\rm in}_\prec I$ is square-free,
${\mathcal V}({\rm in}_\prec I)$ is a union of
$\deg(I)$-many coordinate $d$-planes.
We solve the start system by linear algebra.
This conceptually simple homotopy is in general not
efficient as it is typically overdetermined.
\end{example}
\section{Some Enumerative Geometry}\label{sec:enumerative}
We use the tools we have developed to explore the enumerative geometric
problems of cylinders meeting 5 general points and lines tangent to
4 spheres\index{enumerative geometry}\index{enumerative problem}.
\subsection{Cylinders Meeting 5 Points}\label{sec:cylinder}
A {\it cylinder}\index{cylinder} is the locus of points equidistant from a
fixed line in ${\mathbb R}^3$.
The Grassmannian\index{Grassmannian} of lines in 3-space is 4-dimensional,
which implies that
the space of cylinders is 5-dimensional, and so we expect that 5 points in
${\mathbb R}^3$ will determine finitely many cylinders.
That is, there should be finitely many lines equidistant from 5 general points.
The question is: How many cylinders/lines, and how many of them can be real?
Bottema and Veldkamp~\cite{SO:BV77}
show there are 6 {\it complex} cylinders
and Lichtblau~\cite{SO:Li00} observes that if the 5
points are the vertices of
a bipyramid consisting of 2 regular tetrahedra sharing a common face, then
all 6 will be real.
We check this reality on a configuration with less symmetry (so the Shape
Lemma holds).
If the axial line has direction ${\bf V}$ and contains the point ${\bf P}$
(and hence has parameterization ${\bf P}+t{\bf V}$), and if $r$ is the squared
radius, then the cylinder\index{cylinder} is the set of points ${\bf X}$
satisfying
$$
0 \ =\ r -
\left\| {\bf X} - {\bf P} - \frac{{\bf V}\cdot({\bf X} - {\bf P})}%
{\|{\bf V}\|^2}\,{\bf V} \right\|^2\ .
$$
Expanding and clearing the denominator of $\|{\bf V}\|^2$ yields
%
\begin{equation}\label{eq:cylinder}
0 \ =\ r \|{\bf V}\|^2 +
[{\bf V}\cdot({\bf X} - {\bf P})]^2 -
\|{\bf X} - {\bf P}\|^2\, \|{\bf V}\|^2\,.
\end{equation}
%
We consider cylinders containing the following 5 points, which form an
asymmetric bipyramid.
%
<<<Points = {{2, 2, 0 }, {1, -2, 0}, {-3, 0, 0},
{0, 0, 5/2}, {0, 0, -3}};>>>
%
Suppose that ${\bf P}=(0,y_{11},y_{12})$ and ${\bf V}=(1,y_{21},y_{22})$.
%
<<<R = QQ[r, y11, y12, y21, y22];>>>
%
<<<P = matrix{{0, y11, y12}};>>>
%
<<<V = matrix{{1, y21, y22}};>>>
%
We construct the ideal given by evaluating the
polynomial~(\ref{eq:cylinder}) at each of the five points.
%
<<<Points = matrix Points ** R;>>>
%
%
<<<I = ideal apply(0..4, i -> (
X := Points^{i};
r * (V * transpose V) +
((X - P) * transpose V)^2) -
((X - P) * transpose(X - P)) * (V * transpose V)
);>>>
%
This ideal has dimension 0 and degree 6.
%
<<<dim I, degree I>>>
%
There are 6 real roots, and they correspond to real cylinders (with $r>0$).
%
<<<A = R/I; numPosRoots(charPoly(r, Z))>>>
%
\subsection{Lines Tangent to 4 Spheres}\label{sec:12lines}
We now ask for the lines having a fixed distance from 4 general points.
Equivalently, these are the lines mutually tangent to 4 spheres\index{sphere} of equal radius.
Since the Grassmannian\index{Grassmannian} of lines is four-dimensional, we
expect there to be only finitely many such lines.
Macdonald, Pach, and Theobald~\cite{SO:MPT00} show that there
are indeed 12 lines, and that all 12 may be real.
This problem makes geometric sense over any field $k$ not of characteristic
2, and the derivation of the number 12 is also valid for algebraically
closed\index{field!algebraically closed}
fields not of characteristic 2.
A sphere in $k^3$ is given by ${\mathcal V}(q(1,{\bf x}))$, where
$q$ is some quadratic form\index{quadratic form} on $k^4$.
Here ${\bf x}\in k^3$ and we note that not all quadratic forms give spheres.
If our field does not have characteristic 2, then there
is a symmetric $4\times 4$ matrix $M$ such that
$q({\bf u})={\bf u}M{\bf u}^t$.
A line $\ell$ having direction ${\bf V}$ and containing the point ${\bf P}$
is tangent to the sphere defined by $q$ when the univariate polynomial in $s$
$$
q( (1,{\bf P})+s(0,{\bf V}) )\ =\
q(1,{\bf P}) + 2s (1,{\bf P})M (0,{\bf V})^t + s^2q(0,{\bf V})\,,
$$
has a double root.
Thus its discriminant\index{discriminant} vanishes, giving the equation
%
\begin{equation}\label{eq:sphere}
\left( (1,{\bf P})M(0,{\bf V})^t\right)^2 \ -\
(1,{\bf P})M (1,{\bf P})^t\cdot(0,{\bf V})M (0,{\bf V})^t
\ =\ 0\,.
\end{equation}
%
The matrix $M$ of the quadratic form $q$ of the sphere with
center $(a,b,c)$ and squared radius $r$ is constructed by
{\tt Sphere(a,b,c,r)}.
%
<<<Sphere = (a, b, c, r) -> (
matrix{{a^2 + b^2 + c^2 - r ,-a ,-b ,-c },
{ -a , 1 , 0 , 0 },
{ -b , 0 , 1 , 0 },
{ -c , 0 , 0 , 1 }}
);>>>
%
If a line $\ell$ contains the point ${\bf P}=(0,y_{11},y_{12})$
and $\ell$ has direction ${\bf V} = (1,y_{21},y_{22})$, then
{\tt tangentTo(M)} is the equation for $\ell$ to be tangent to the
quadric $uMu^T=0$ determined by the matrix $M$.
%
<<<R = QQ[y11, y12, y21, y22];>>>
%
<<<tangentTo = (M) -> (
P := matrix{{1, 0, y11, y12}};
V := matrix{{0, 1, y21, y22}};
(P * M * transpose V)^2 -
(P * M * transpose P) * (V * M * transpose V)
);>>>
The ideal of lines having distance $\sqrt{5}$ from the four points
$(0,0,0)$, $(4,1,1)$, $(1,4,1)$, and $(1,1,4)$ has dimension zero and degree 12.
%
<<<I = ideal (tangentTo(Sphere(0,0,0,5)),
tangentTo(Sphere(4,1,1,5)),
tangentTo(Sphere(1,4,1,5)),
tangentTo(Sphere(1,1,4,5)));>>>
%
<<<dim I, degree I>>>
%
Thus there are 12 lines whose distance from those 4 points is $\sqrt{5}$.
We check that all 12 are real.
%
<<<A = R/I;>>>
%
<<<numRealSturm(eliminant(y11 - y12 + y21 + y22, QQ[Z]))>>>
%
Since no eliminant\index{eliminant} given by a coordinate function satisfies
the hypotheses of the Shape Lemma,
we took the eliminant with respect to the linear form
$y_{11} - y_{12} + y_{21} + y_{22}$.
This example is an instance of Lemma~3 of~\cite{SO:MPT00}.
These four points define a regular tetrahedron with volume
$V=9$ where each face has area $A=\sqrt{3^5}/2$ and each edge has length
$e=\sqrt{18}$.
That result guarantees that all 12 lines will be real when
$e/2<r<A^2/3V$, which is the case above.
\section{Schubert Calculus}
The classical Schubert calculus\index{Schubert calculus} of enumerative
geometry\index{enumerative geometry} concerns linear subspaces having
specified positions with respect to other, fixed subspaces.
For instance, how many lines in ${\mathbb P}^3$ meet four given
lines? (See Example~\ref{ex:G22}.)
More generally, let $1<r<n$ and suppose that we are given general linear
subspaces $L_1,\ldots,L_m$ of $k^n$ with $\dim L_i=n-r+1-l_i$.
When $l_1+\cdots+l_m=r(n-r)$, there will be a finite number
$d(r,n;l_1,\ldots,l_m)$ of $r$-planes in
$k^n$ which meet each $L_i$ non-trivially.
This number may be computed using classical algorithms of Schubert and Pieri
(see~\cite{SO:MR48:2152}).
The condition on $r$-planes to meet a fixed $(n{-}r{+}1{-}l)$-plane
non-trivially is called a {\it (special) Schubert condition}, and we call
the data $(r,n;l_1,\ldots,l_m)$ {\it (special) Schubert data}.
The {\it (special) Schubert calculus} concerns this class of enumerative
problems\index{Schubert calculus}\index{enumerative problem}.
We give two polynomial formulations of this special Schubert calculus,
consider their solutions over ${\mathbb R}$, and end with a question for
fields of arbitrary characteristic.
\subsection{Equations for the Grassmannian}\label{sec:grass}
The ambient space for the Schubert calculus is the
Grassmannian\index{Grassmannian}
of $r$-planes in $k^n$, denoted ${\bf G}_{r,n}$.
For $H\in{\bf G}_{r,n}$, the $r$th exterior product of the embedding
$H \rightarrow k^n$ gives a line
$$
k\ \simeq\ \wedge^r H\ \longrightarrow\ \wedge^r k^{n}\ \simeq\
k^{\binom{n}{r}}\,.
$$
This induces the Pl\"ucker embedding\index{Plucker embedding@Pl\"ucker embedding}
${\bf G}_{r,n}\hookrightarrow{\mathbb P}^{\binom{n}{r}-1}$.
If $H$ is the row space of an $r$ by $n$ matrix, also written $H$, then the
Pl\"ucker embedding sends $H$ to its vector of $\binom{n}{r}$ maximal
minors.
Thus the $r$-subsets of $\{0,\ldots,n{-}1\}$,
${\mathbb Y}_{r,n}:={\tt subsets(n,r)}$,
index Pl\"ucker coordinates\index{Plucker coordinate@Pl\"ucker coordinate} of ${\bf G}_{r,n}$.
The Pl\"ucker ideal\index{Plucker ideal@Pl\"ucker ideal} of ${\bf G}_{r,n}$ is therefore the
ideal of algebraic relations among the maximal minors of a generic $r$ by $n$
matrix.
We create the coordinate ring
$k[p_\alpha\mid\alpha\in{\mathbb Y}_{2,5}]$ of ${\mathbb P}^9$ and the
Pl\"ucker ideal of ${\bf G}_{2,5}$.
The Grassmannian ${\bf G}_{r,n}$ of $r$-dimensional subspaces of $k^n$ is also
the Grassmannian of $r{-}1$-dimensional affine subspaces of
${\mathbb P}^{n-1}$.
\Mtwo{} uses this alternative indexing scheme.
%
<<<R = ZZ/101[apply(subsets(5,2), i -> p_i )];>>>
%
<<<I = Grassmannian(1, 4, R)>>>
%
This projective variety has dimension 6 and degree 5
%
<<<dim(Proj(R/I)), degree(I)>>>
%
This ideal has an important combinatorial
structure~\cite[Example 11.9]{SO:Sturmfels_GBCP}.
We write each $\alpha\in{\mathbb Y}_{r,n}$ as an increasing
sequence $\alpha\colon\alpha_1<\cdots<\alpha_r$.
Given $\alpha,\beta\in{\mathbb Y}_{r,n}$, consider the
two-rowed array with $\alpha$ written above $\beta$.
We say $\alpha\leq \beta$ if each column weakly increases.
If we sort the columns of an array with rows $\alpha$ and
$\beta$, then the first row is the {\it meet} $\alpha\wedge\beta$
(greatest lower bound) and the
second row the {\it join} $\alpha\vee\beta$ (least upper bound) of $\alpha$
and $\beta$.
These definitions endow ${\mathbb Y}_{r,n}$ with the structure of a
distributive lattice.
Figure~\ref{fig2} shows ${\mathbb Y}_{2,5}$.
\begin{figure}
$$
\epsfysize=1.8in \epsfbox{Y25.eps}
$$\caption{${\mathbb Y}_{2,5}$\label{fig2}}
\end{figure}
We give $k[p_\alpha]$ the degree reverse
lexicographic order, where we first order the variables $p_\alpha$ by
lexicographic order on their indices $\alpha$.
\begin{theorem}\label{PluckerIdeal}
The reduced Gr\"obner basis\index{Grobner basis@Gr\"obner basis!reduced} of the Pl\"ucker
ideal with respect to this degree
reverse lexicographic term order consists of quadratic
polynomials
$$
g(\alpha,\beta)\quad=\quad
p_\alpha\cdot p_\beta \ -\ p_{\alpha\vee\beta}\cdot p_{\alpha\wedge\beta}
\ +\ \hbox{lower terms in $\prec$}\,,
$$
for each incomparable pair $\alpha,\beta$ in
${\mathbb Y}_{r,n}$,
and all lower terms $\lambda p_\gamma\cdot p_\delta$ in $g(\alpha,\beta)$
satisfy $\gamma\leq \alpha\wedge\beta$ and $\alpha\vee\beta\leq \delta$.
\end{theorem}
The form of this Gr\"obner basis implies that the standard monomials are
the sortable monomials, those $p_\alpha p_\beta\cdots p_\gamma$ with
$\alpha\leq\beta\leq\cdots\leq\gamma$.
Thus the Hilbert function\index{Hilbert function} of ${\bf G}_{r,n}$ may be
expressed in terms of the combinatorics of ${\mathbb Y}_{r,n}$.
For instance, the dimension of ${\bf G}_{r,n}$ is the rank of
${\mathbb Y}_{r,n}$, and its degree is the number of maximal chains.
From Figure~\ref{fig2}, these are 6 and 5 for ${\mathbb Y}_{2,5}$,
confirming our previous calculations.
Since the generators $g(\alpha,\beta)$ are linearly independent, this
Gr\"obner basis is also a minimal generating set for the ideal.
The displayed generator in {\tt o51},
$$
p_{\{2,3\}}p_{\{1,4\}}\ -\ p_{\{1,3\}}p_{\{2,4\}}\ -\
p_{\{1,2\}}p_{\{3,4\}}\ ,
$$
is $g(23, 14)$, and corresponds to the underlined incomparable pair in
Figure~\ref{fig2}.
Since there are 5 such incomparable pairs, the Gr\"obner basis has 5
generators.
As ${\bf G}_{2,5}$ has codimension 3, it is not a complete
intersection\index{Grassmannian!not a complete intersection}\index{complete intersection}.
This shows how the general enumerative problem from the Schubert calculus
gives rise to an overdetermined system of equations\index{polynomial
equations!overdetermined} in this global
formulation.
\medskip
The Grassmannian\index{Grassmannian!local coordinates} has a useful system of
local coordinates given by ${\rm Mat}_{r,n-r}$ as follows
%
\begin{equation}\label{eq:local}
Y\ \in {\rm Mat}_{r,n-r}\ \longmapsto\
{\rm row space}\ [ I_r : Y ]\ \in\ {\bf G}_{r,n}\,.
\end{equation}
%
Let $L$ be a ($n-r+1-l$)-plane in $k^n$ which is the row space of
a $n-r+1-l$ by $n$ matrix, also written $L$.
Then $L$ meets $X\in{\bf G}_{r,n}$ non-trivially if
$$
\mbox{maximal minors of }\
\left[\begin{array}{c}L\\X\end{array}\right]\ =\ 0\,.
$$
Laplace expansion of each minor along the rows of $X$ gives a linear
equation in the Pl\"ucker coordinates.
In the local coordinates (substituting $[I_r:Y]$ for $X$), we obtain
multilinear equations of degree $\min\{r,n-r\}$.
These equations generate a prime ideal of codimension $l$.
Suppose each $l_i=1$ in our enumerative problem.
Then in the Pl\"ucker coordinates, we have the Pl\"ucker ideal of
${\bf G}_{r,n}$
together with $r(n-r)$ linear equations, one for each
$(n{-}r)$-plane $L_i$.
By Theorem~\ref{PluckerIdeal}, the Pl\"ucker ideal has a square-free initial
ideal\index{initial ideal!square-free}, and so the Gr\"obner
homotopy\index{homotopy!Gr\"obner} of
Example~\ref{example:Groebner} may be
used to solve this enumerative problem.
\begin{example}\label{ex:G22}
${\bf G}_{2,4}\subset{\mathbb P}^5$ has equation
%
\begin{equation}\label{eq:G22}
p_{\{1,2\}}p_{\{0,3\}}-p_{\{1,3\}}p_{\{0,2\}}+ p_{\{2,3\}}p_{\{0,1\}}
\ =\ 0\,.
\end{equation}
%
The condition for $H\in{\bf G}_{2,4}$ to meet a 2-plane $L$ is the
vanishing of
\begin{equation}\label{eq:hypersurface}
p_{\{1,2\}}L_{34}-p_{\{1,3\}}L_{24}+p_{\{2,3\}}L_{14}
+ p_{\{1,4\}}L_{23}-p_{\{2,4\}}L_{13}+p_{\{3,4\}}L_{12}\,,
\end{equation}
where $L_{ij}$ is the $(i,j)$th maximal minor of $L$.
If $l_1=\cdots=l_4=1$, we have 5 equations in ${\mathbb P}^5$, one quadratic
and 4 linear, and so by B\'ezout's Theorem\index{Bezout's Theorem@B\'ezout's Theorem} there are
two 2-planes in $k^4$ that meet 4 general 2-planes non-trivially.
This means that there are 2 lines in ${\mathbb P}^3$ meeting 4 general lines.
In local coordinates, (\ref{eq:hypersurface}) becomes
$$
L_{34}-L_{14}y_{11}+L_{13}y_{12}-L_{24}y_{21}
+ L_{23}y_{22} + L_{12}(y_{11}y_{22}-y_{12}y_{21})\,.
$$
This polynomial has the form of the last specialization in
Example~\ref{ex:one}.
\end{example}
\subsection{Reality in the Schubert Calculus}\label{sec:shapiro}
Like the other enumerative problems we have discussed, enumerative problems
in the special Schubert calculus\index{Schubert calculus} are fully
real\index{enumerative problem!fully real} in that all solutions can be
real~\cite{SO:So99a}.
That is, given any Schubert data $(r,n;l_1,\ldots,l_m)$, there exist
subspaces $L_1,\ldots,L_m\subset{\mathbb R}^n$ such that each of the
$d(r,n;l_1,\ldots,l_m)$ $r$-planes that meet each $L_i$ are themselves
real.
This result gives some idea of which choices of the $L_i$ give
all $r$-planes real.
Let $\gamma$ be a fixed rational normal curve in ${\mathbb R}^n$.
Then the $L_i$ are linear subspaces osculating $\gamma$.
More concretely, suppose that $\gamma$ is the standard rational normal
curve\index{rational normal curve},
$\gamma(s) = (1, s, s^2, \ldots, s^{n-1})$.
Then the $i$-plane
$L_i(s):=\langle \gamma(s),\gamma'(s),\ldots,\gamma^{(i-1)}(s)\rangle$
osculating $\gamma$ at $\gamma(s)$ is the row space
of the matrix given by {\tt oscPlane(i, n, s)}.
%
<<<oscPlane = (i, n, s) -> (
gamma := matrix {toList apply(1..n, i -> s^(i-1))};
L := gamma;
j := 0;
while j < i-1 do (gamma = diff(s, gamma);
L = L || gamma;
j = j+1);
L);>>>
%
<<<QQ[s]; oscPlane(3, 6, s)>>>
%
(In {\tt o55}, the exponents of $s$ are displayed in line: $s^2$ is written
{\tt s2}.
\Mtwo{} uses this notational convention to display
matrices efficiently.)
\begin{theorem}[\cite{SO:So99a}]\label{thm:special-reality}
For any Schubert data $(r,n;l_1,\ldots,l_m)$, {\bf there exist} real numbers
$s_1,s_2,\ldots,s_m$ such that there are $d(r,n;l_1,\ldots,l_m)$
$r$-planes that meet each osculating plane $L_i(s_i)$, and all are real.
\end{theorem}
The inspiration for looking at subspaces osculating the rational normal
curve\index{rational normal curve} to
study real enumerative geometry\index{enumerative geometry!real} for the
Schubert calculus\index{Schubert calculus} is the following very interesting
conjecture of Boris Shapiro and Michael
Shapiro, or more accurately,
extensive computer experimentation based upon their
conjecture~\cite{SO:RS98,SO:So_shap-www,SO:So00b,SO:Ver00}.
\medskip
\noindent{\bf Shapiros's Conjecture\index{Shapiros's Conjecture}. }
{\it
For any Schubert data $(r,n;l_1,\ldots,l_m)$ and {\bf for all} real numbers
$s_1,s_2,\ldots,s_m$ there are $d(r,n;l_1,\ldots,l_m)$
$r$-planes that meet each osculating plane $L_i(s_i)$, and all are real.
}\medskip
In addition to Theorem~\ref{thm:special-reality}, (which replaces the
quantifier {\it for all}\/ by {\it there exist}), the strongest evidence for
this Conjecture is the following result of Eremenko and
Gabrielov~\cite{SO:EG00}.
\begin{theorem}
Shapiros's Conjecture is true when either $r$ or $n-r$ is $2$.
\end{theorem}
We test an example of this conjecture for the Schubert data
$(3,6;1^3,2^3)$, (where $a^b$ is $a$ repeated $b$ times).
The algorithms of the Schubert calculus predict that $d(3,6;1^3,2^3)=6$.
The function {\tt spSchub(r, L, P)} computes the ideal of $r$-planes meeting
the row space of $L$ in the Pl\"ucker coordinates $P_\alpha$.
%
<<<spSchub = (r, L, P) -> (
I := ideal apply(subsets(numgens source L,
r + numgens target L), S ->
fold((sum, U) -> sum +
fold((term,i) -> term*(-1)^i, P_(S_U) * det(
submatrix(L, sort toList(set(S) - set(S_U)))), U),
0, subsets(#S, r))));>>>
%
We are working in the Grassmannian of 3-planes in
${\mathbb C}^6$.
%
<<<R = QQ[apply(subsets(6,3), i -> p_i )];>>>
%
The ideal $I$ consists of the
special Schubert conditions for the 3-planes to meet the 3-planes osculating
the rational normal curve at the points 1, 2, and 3, and to also meet the
2-planes osculating at 4, 5, and 6,
together with the Pl\"ucker ideal {\tt Grassmannian(2, 5, R)}.
Since this is a 1-dimensional homogeneous ideal, we add the linear form
{\tt p{\char`\_}\char`\{0,1,5{\char`\}} - 1} to make the ideal
zero-dimensional\index{ideal!zero-dimensional}.
As before, {\tt Grassmannian(2, 5, R)} creates the Pl\"ucker ideal of
${\bf G}_{3,6}$.
%
<<<I = fold((J, i) -> J +
spSchub(3, substitute(oscPlane(3, 6, s), {s=> 1+i}), p) +
spSchub(3, substitute(oscPlane(2, 6, s), {s=> 4+i}), p),
Grassmannian(2, 5, R), {0,1,2}) +
ideal (p_{0,1,5} - 1);>>>
%
This has dimension 0 and degree 6, in agreement with the Schubert calculus.
%
<<<dim I, degree I>>>
%
As expected, all roots are real.
%
<<<A = R/I; numRealSturm(eliminant(p_{2,3,4}, QQ[Z]))>>>
%
There have been many checked instances of this
conjecture~\cite{SO:So_shap-www,SO:So00b,SO:Ver00}, and it has some
geometrically interesting generalizations~\cite{SO:So_flags}.
The question remains for which numbers $0\leq d\leq d(r,n;l_1,\ldots,l_m)$ do
there exist real planes $L_i$ with $d(r,n;l_1,\ldots,l_m)$
$r$-planes meeting each $L_i$, and exactly $d$ of them are real.
Besides Theorem~\ref{thm:special-reality} and the obvious parity condition,
nothing is known in general.
In every known case, every possibility occurs---which is not the case in all
enumerative problems, even those that are fully real\index{enumerative
problem!fully real}\footnote{For example, of
the 12 rational plane cubics containing 8 real points in ${\mathbb P}^2$,
either 8, 10 or 12 can be real, and there are 8 points with all 12
real~\cite[Proposition 4.7.3]{SO:DeKh00}.}.
Settling this (for $d=0$) has implications for linear systems
theory~\cite{SO:RS98}.\footnote{After this was written, Eremenko and
Gabrielov~\cite{SO:EG-NR} showed that $d$ can be zero for the enumerative
problems given by data $(2,2n,1^{4n-4})$ and $(2n-2,2n,1^{4n-4})$.}
\subsection{Transversality in the Schubert Calculus}
A basic principle of the classical Schubert calculus\index{Schubert calculus}
is that the intersection
number $d(r,n;l_1,\ldots,l_m)$ has enumerative significance---that is, for
general linear subspaces $L_i$, all solutions appear with multiplicity 1.
This basic principle is not known to hold in general.
For fields of characteristic zero, Kleiman's Transversality
Theorem~\cite{SO:MR50:13063} establishes this principle.
When $r$ or $n{-}r$ is 2, then Theorem~E of~\cite{SO:So97a} establishes this
principle in arbitrary characteristic.
We conjecture that this principle holds in general; that is, for arbitrary
infinite fields and any Schubert data, if the planes $L_i$ are in general
position, then the resulting zero-dimensional ideal is
radical\index{ideal!radical}.
We test this conjecture on the enumerative problem of
Section~\ref{sec:shapiro}, which is not covered by
Theorem~E of~\cite{SO:So97a}.
The function {\tt testTransverse(F)} tests transversality
for this enumerative problem, for a given field $F$.
It does this by first computing the ideal of the enumerative problem using
random planes $L_i$.
%
<<<randL = (R, n, r, l) ->
matrix table(n-r+1-l, n, (i, j) -> random(0, R));>>>
%
and the Pl\"ucker ideal of the Grassmannian ${\bf G}_{3,6}$
{\tt Grassmannian(2, 5, R)}.)
Then it adds a random (inhomogeneous) linear relation
{\tt 1 + random(1, R)} to make the ideal zero-dimensional for generic $L_i$.
When this ideal is zero dimensional and has degree 6 (the expected degree), it
computes the characteristic polynomial {\tt g} of a generic linear form.
If {\tt g} has no multiple roots, {\tt 1 == gcd(g, diff(Z, g))},
then the Shape Lemma\index{Shape Lemma}
guarantees that the ideal was radical.
{\tt testTransverse} exits either when it computes a radical ideal,
or after {\tt limit} iterations (which is set to 5 for these examples), and
prints the return status.
%
<<<testTransverse = F -> (
R := F[apply(subsets(6, 3), i -> q_i )];
continue := true;
j := 0;
limit := 5;
while continue and (j < limit) do (
j = j + 1;
I := fold((J, i) -> J +
spSchub(3, randL(R, 6, 3, 1), q) +
spSchub(3, randL(R, 6, 3, 2), q),
Grassmannian(2, 5, R) +
ideal (1 + random(1, R)),
{0, 1, 2});
if (dim I == 0) and (degree I == 6) then (
lin := promote(random(1, R), (R/I));
g := charPoly(lin, Z);
continue = not(1 == gcd(g, diff(Z, g)));
));
if continue then << "Failed for the prime " << char F <<
" with " << j << " iterations" << endl;
if not continue then << "Succeeded for the prime " <<
char F << " in " << j << " iteration(s)" << endl;
);>>>
%
Since 5 iterations do not show transversality for ${\mathbb F}_2$,
%
<<<testTransverse(ZZ/2);>>>
%
we can test transversality in characteristic 2 using the field with
four elements, ${\mathbb F}_4=$ {\tt GF 4}.
%
<<<testTransverse(GF 4);>>>
%
We do find transversality for ${\mathbb F}_7$.
%
<<<testTransverse(ZZ/7);>>>
We have tested transversality for all primes less than 100 in every
enumerative problem involving Schubert conditions on 3-planes in $k^6$.
These include the problem above as well as the problem of 42 3-planes meeting
9 general 3-planes.\footnote{After this was written, we discovered an
elementary proof of transversality for the enumerative problems given by data
$(r,n;1^{r(n-r)})$, where the conditions are all
codimension~1~\cite{SO:So_trans}.}
\section{The 12 Lines: Reprise}
The enumerative problems of Section~\ref{sec:enumerative} were formulated
in local coordinates~(\ref{eq:local}) for the Grassmannian of lines in
${\mathbb P}^3$ (Grassmannian of 2-dimensional subspaces in $k^4$).
When we formulate the problem of Section~\ref{sec:12lines} in the global
Pl\"ucker coordinates\index{Plucker coordinate@Pl\"ucker coordinate} of Section~\ref{sec:grass},
we find some interesting phenomena.
We also consider some related enumerative problems\index{enumerative problem}.
\subsection{Global Formulation}\label{sec:global}
A quadratic form\index{quadratic form} $q$ on a vector space $V$ over a field
$k$ not of characteristic 2 is given by
$q({\bf u})=(\varphi({\bf u}),{\bf u})$, where $\varphi\colon V\to V^*$ is
a {\it symmetric} linear map, that is
$(\varphi({\bf u}),{\bf v})=(\varphi({\bf v}),{\bf u})$.
Here, $V^*$ is the linear dual of $V$ and $(\,\cdot\;,\,\cdot\,)$ is the
pairing $V\otimes V^*\to k$.
The map $\varphi$ induces a quadratic form $\wedge^rq$ on the $r$th exterior
power $\wedge^rV$ of $V$ through the symmetric map
$\wedge^r\varphi\colon \wedge^rV\to\wedge^rV^*=(\wedge^rV)^*$.
The action of $\wedge^rV^*$ on $\wedge^rV$ is given by
%
\begin{equation}\label{eq:wedge}
({\bf x}_1\wedge{\bf x}_2\wedge\cdots\wedge{\bf x}_r,\
{\bf y\!}_1\wedge{\bf y}\!_2\wedge\cdots\wedge{\bf y}\!_r)\ =\
\det|({\bf x}_i, {\bf y}\!_j)|\,,
\end{equation}
%
where ${\bf x}_i\in V^*$ and ${\bf y}\!_j\in V$.
When we fix isomorphisms $V\simeq k^n\simeq V^*$, the map $\varphi$ is given
by a symmetric $n\times n$ matrix $M$ as in Section~\ref{sec:12lines}.
Suppose $r=2$.
Then for ${\bf u},{\bf v}\in k^n$,
$$
\wedge^2q({\bf u}\wedge{\bf v})\ =
\det\left[\begin{array}{cc}
{\bf u}M{\bf u}^t &{\bf u}M{\bf v}^t\\
{\bf v}M{\bf u}^t &{\bf v}M{\bf v}^t
\end{array}\right]\ ,
$$
which is Equation~(\ref{eq:sphere}) of Section~\ref{sec:12lines}.
\begin{proposition}\label{prop:tangent_line}
A line $\ell$ is tangent to a quadric ${\mathcal V}(q)$ in
${\mathbb P}^{n-1}$ if and only if its Pl\"ucker
coordinate\index{Plucker coordinate@Pl\"ucker coordinate}
$\wedge^2\ell\in{\mathbb P}^{\binom{n}{2}-1}$ lies on the quadric
${\mathcal V}(\wedge^2q)$.
\end{proposition}
Thus the Pl\"ucker coordinates for the set of lines tangent to 4 general
quadrics in ${\mathbb P}^3$ satisfy 5 quadratic equations:
The single Pl\"ucker relation~(\ref{eq:G22})
together with one quadratic equation for each quadric.
Thus we expect the B\'ezout number\index{Bezout number@B\'ezout number} of $2^5=32$ such
lines.
We check this.
The procedure {\tt randomSymmetricMatrix(R, n)}
generates a random symmetric $n\times n$ matrix with entries in
the base ring of $R$.
%
<<<randomSymmetricMatrix = (R, n) -> (
entries := new MutableHashTable;
scan(0..n-1, i -> scan(i..n-1, j ->
entries#(i, j) = random(0, R)));
matrix table(n, n, (i, j) -> if i > j then
entries#(j, i) else entries#(i, j))
);>>>
%
The procedure {\tt tangentEquation(r, R, M)} gives the equation in Pl\"ucker
coordinates for a point in ${\mathbb P}^{\binom{n}{r}-1}$ to be
isotropic with respect to the bilinear form\index{bilinear form} $\wedge^rM$
({\tt R} is assumed to be the coordinate ring of
${\mathbb P}^{\binom{n}{r}-1}$).
This is the equation for an $r$-plane to be tangent to the quadric
associated to $M$.
%
<<<tangentEquation = (r, R, M) -> (
g := matrix {gens(R)};
(entries(g * exteriorPower(r, M) * transpose g))_0_0
);>>>
%
We construct the ideal of lines tangent to 4 general quadrics in
${\mathbb P}^3$.
%
<<<R = QQ[apply(subsets(4, 2), i -> p_i )];>>>
%
<<<I = Grassmannian(1, 3, R) + ideal apply(0..3, i ->
tangentEquation(2, R, randomSymmetricMatrix(R, 4)));>>>
%
As expected, this ideal has dimension 0 and degree 32.
%
<<<dim Proj(R/I), degree I>>>
%
\subsection{Lines Tangent to 4 Spheres}\label{sec:tangent_lines}
That calculation raises the following question:
In Section~\ref{sec:12lines}, why did we obtain only 12 lines tangent to 4
spheres\index{sphere}?
To investigate this, we generate the global ideal of lines tangent to the
spheres of Section~\ref{sec:12lines}.
%
<<<I = Grassmannian(1, 3, R) +
ideal (tangentEquation(2, R, Sphere(0,0,0,5)),
tangentEquation(2, R, Sphere(4,1,1,5)),
tangentEquation(2, R, Sphere(1,4,1,5)),
tangentEquation(2, R, Sphere(1,1,4,5)));>>>
%
We compute the dimension and degree of ${\mathcal V}(I)$.
%
<<<dim Proj(R/I), degree I>>>
%
The ideal is not zero dimensional\index{ideal!zero-dimensional}; there is an
extraneous one-dimensional
component of zeroes with degree 4.
Since we found 12 lines in
Section~\ref{sec:12lines} using the local coordinates~(\ref{eq:local}),
the extraneous component must lie in the complement of that coordinate patch,
which is defined by the vanishing of the first Pl\"ucker coordinate, $p_{\{0,1\}}$.
We saturate\index{saturation} $I$ by $p_{\{0,1\}}$ to obtain the desired lines.
%
<<<Lines = saturate(I, ideal (p_{0,1}));>>>
%
This ideal does have dimension 0 and degree 12, so we have recovered the
zeroes of Section~\ref{sec:12lines}.
%
<<<dim Proj(R/Lines), degree(Lines)>>>
%
We investigate the rest of the zeroes, which we obtain
by taking the ideal
quotient of $I$ and the ideal of lines.
As computed above, this has dimension 1 and degree 4.
%
<<<Junk = I : Lines;>>>
%
<<<dim Proj(R/Junk), degree Junk>>>
%
We find the support of this extraneous component by taking its
radical.
%
<<<radical(Junk)>>>
%
From this, we see that the extraneous component is supported on an imaginary
conic in the ${\mathbb P}^2$ of lines at infinity.
\smallskip
To understand the geometry behind this computation, observe that
the sphere with radius $r$ and center $(a,b,c)$ has homogeneous equation
$$
(x-wa)^2+(y-wb)^2+(z-wc)^2\ =\ r^2w^2\,.
$$
At infinity, $w=0$, this has equation
$$
x^2+y^2+z^2\ =\ 0\,.
$$
The extraneous component is supported on the set of tangent
lines to this imaginary conic.
Aluffi and Fulton~\cite{SO:AF} studied
this problem, using geometry to
identify the extraneous ideal and the excess intersection
formula~\cite{SO:FM76} to obtain the answer of 12.
Their techniques show that there will be 12 isolated lines tangent to 4
quadrics which have a smooth conic in common.
When the quadrics are spheres, the conic is the imaginary conic at infinity.
Fulton asked the following question:
Can all 12 lines be real if the (real) four quadrics share a real conic?
We answer his question in the affirmative in the next section.
\subsection{Lines Tangent to Real Quadrics Sharing a Real Conic}
We consider four quadrics in ${\mathbb P}^3_{\mathbb R}$ sharing a
non-singular conic, which we will take to be at infinity so that we may use
local coordinates for ${\bf G}_{2,4}$ in our computations.
The variety ${\mathcal V}(q)\subset{\mathbb P}^3_{\mathbb R}$ of a
nondegenerate quadratic form $q$ is determined up to isomorphism by the
absolute value of the signature\index{bilinear form!signature} $\sigma$ of the
associated bilinear form.
Thus there are three possibilities, 0, 2, or 4, for $|\sigma|$.
When $|\sigma|=4$, the real quadric ${\mathcal V}(q)$ is empty.
The associated symmetric matrix $M$ is conjugate to the identity
matrix, so $\wedge^2M$ is also conjugate to the identity matrix.
Hence ${\mathcal V}(\wedge^2q)$ contains no real points.
Thus we need not consider quadrics with $|\sigma|=4$.
When $|\sigma|=2$, we have ${\mathcal V}(q)\simeq S^2$, the 2-sphere.
If the conic at infinity is imaginary, then
${\mathcal V}(q)\subset{\mathbb R}^3$ is an ellipsoid\index{ellipsoid}.
If the conic at infinity is real, then ${\mathcal V}(q)\subset{\mathbb R}^3$ is
a hyperboloid\index{hyperboloid} of two sheets.
When $\sigma=0$, we have ${\mathcal V}(q)\simeq S^1\times S^1$, a torus.
In this case, ${\mathcal V}(q)\subset{\mathbb R}^3$ is
a hyperboloid of one sheet and the conic at infinity is real.
Thus either we have 4 ellipsoids sharing an imaginary conic at infinity,
which we studied in Section~\ref{sec:12lines}; or else we have four
hyperboloids sharing a real conic at infinity, and there are five
possible combinations of hyperboloids of one or two sheets sharing a real
conic at infinity.
This gives six topologically distinct possibilities in all.
\begin{theorem}
For each of the six topologically distinct possibilities of four real
quadrics sharing a smooth conic at infinity, there exist four quadrics
having the property that each of the 12 lines in ${\mathbb C}^3$
simultaneously tangent to the four quadrics is real.
\end{theorem}
\begin{proof}
By the computation in Section~\ref{sec:12lines},
we need only check the five possibilities for hyperboloids\index{hyperboloid}.
We fix the conic at infinity to be $x^2+y^2-z^2=0$.
Then the general hyperboloid of two sheets containing this conic has
equation in ${\mathbb R}^3$
%
\begin{equation}\label{eq:twoSheet}
(x-a)^2+(y-b)^2-(z-c)^2+r\ =\ 0\,,
\end{equation}
%
(with $r>0$).
The command {\tt Two(a,b,c,r)} generates the associated
symmetric matrix.
%
<<<Two = (a, b, c, r) -> (
matrix{{a^2 + b^2 - c^2 + r ,-a ,-b , c },
{ -a , 1 , 0 , 0 },
{ -b , 0 , 1 , 0 },
{ c , 0 , 0 ,-1 }}
);>>>
The general hyperboloid of one sheet containing the conic
$x^2+y^2-z^2=0$ at infinity has equation in ${\mathbb R}^3$
%
\begin{equation}\label{eq:oneSheet}
(x-a)^2+(y-b)^2-(z-c)^2-r\ =\ 0\,,
\end{equation}
%
(with $r>0$).
The command {\tt One(a,b,c,r)} generates the associated
symmetric matrix.
%
<<<One = (a, b, c, r) -> (
matrix{{a^2 + b^2 - c^2 - r ,-a ,-b , c },
{ -a , 1 , 0 , 0 },
{ -b , 0 , 1 , 0 },
{ c , 0 , 0 ,-1 }}
);>>>
We consider $i$ quadrics of two sheets~(\ref{eq:twoSheet}) and $4-i$
quadrics of one sheet~(\ref{eq:oneSheet}).
For each of these cases, the table below displays four 4-tuples of data
$(a,b,c,r)$ which give 12 real lines.
(The data for the hyperboloids of one sheet are listed first.)
\begin{center}
\begin{tabular}{|c|l|}\hline
$\;i$\;&\hspace{13em}Data\\\hline
$0$&$\hspace{.915em}(5,3,3,16),\hspace{2.185em}(5,-4,2,1),\hspace{1.27em}
(-3,-1,1,1),\hspace{.88em}(2,-7,0,1)$\\\hline
$1$&$\hspace{.385em}(3,-2,-3,6),\hspace{.885em}(-3,-7,-6,7),\hspace{.5em}
(-6,3,-5,2),\hspace{.865em}(1,6,-2,5)$\\\hline
$2$&$\hspace{1.165em}(6,4,6,4),\hspace{2.43em}(-1,3,3,6),\hspace{1.265em}
(-7,-2,3,3),\hspace{.5em}(-6,7,-2,5)$\\\hline
$3$&$(-1,-4,-1,1),\hspace{.885em}(-3,3,-1,1),\hspace{.885em}
\hspace{.4em}(-7,6,2,9),\hspace{1.025em}(5,6,-1,12)$\\\hline
$4$&$\hspace{.525em}(5,2,-1,25),\hspace{1.555em}(6,-6,2,25),\hspace{1.03em}
\hspace{.4em}(-7,1,6,1),\hspace{1.65em}(3,1,0,1)$\\\hline
\end{tabular}
\end{center}
%\noindent$|\hspace{1em}|$
%\noindent$|\hspace{10pt}|$
We test each of these, using the formulation in local coordinates of
Section~\ref{sec:12lines}.
%
<<<R = QQ[y11, y12, y21, y22];>>>
%
<<<I = ideal (tangentTo(One( 5, 3, 3,16)),
tangentTo(One( 5,-4, 2, 1)),
tangentTo(One(-3,-1, 1, 1)),
tangentTo(One( 2,-7, 0, 1)));>>>
%
<<<numRealSturm(charPoly(promote(y22, R/I), Z))>>>
%
<<<I = ideal (tangentTo(One( 3,-2,-3, 6)),
tangentTo(One(-3,-7,-6, 7)),
tangentTo(One(-6, 3,-5, 2)),
tangentTo(Two( 1, 6,-2, 5)));>>>
%
<<<numRealSturm(charPoly(promote(y22, R/I), Z))>>>
%
<<<I = ideal (tangentTo(One( 6, 4, 6, 4)),
tangentTo(One(-1, 3, 3, 6)),
tangentTo(Two(-7,-2, 3, 3)),
tangentTo(Two(-6, 7,-2, 5)));>>>
%
<<<numRealSturm(charPoly(promote(y22, R/I), Z))>>>%
<<<I = ideal (tangentTo(One(-1,-4,-1, 1)),
tangentTo(Two(-3, 3,-1, 1)),
tangentTo(Two(-7, 6, 2, 9)),
tangentTo(Two( 5, 6,-1,12)));>>>
%
<<<numRealSturm(charPoly(promote(y22, R/I), Z))>>>
%
<<<I = ideal (tangentTo(Two( 5, 2,-1,25)),
tangentTo(Two( 6,-6, 2,25)),
tangentTo(Two(-7, 1, 6, 1)),
tangentTo(Two( 3, 1, 0, 1)));>>>
%
<<<numRealSturm(charPoly(promote(y22, R/I), Z))>>>
%
\qed
\end{proof}
In each of these enumerative problems there are 12 complex solutions.
For each, we have done other computations showing that every possible
number of real solutions (0, 2, 4, 6, 8, 10, or 12) can occur.
\subsection{Generalization to Higher Dimensions}
We consider lines tangent to quadrics in higher dimensions.
First, we reinterpret the action of $\wedge^rV^*$ on $\wedge^rV$
described in~(\ref{eq:wedge}) as follows.
The vectors ${\bf x}_1,\ldots,{\bf x}_r$ and ${\bf y}\!_1,\ldots,{\bf y}\!_r$
define maps $\alpha\colon k^r\to V^*$ and $\beta\colon k^r\to V$.
The matrix $[({\bf x}_i,\,{\bf y}\!_j)]$ is the matrix of the bilinear form
on $k^r$ given by
$\langle{\bf u},\,{\bf v}\rangle:= (\alpha({\bf u}),\,\beta({\bf v}))$.
Thus~(\ref{eq:wedge}) vanishes when the bilinear form
$\langle\,\cdot\,,\,\cdot\,\rangle$ on $k^r$ is degenerate.
Now suppose that we have a quadratic form $q$ on $V$ given by a symmetric map
$\varphi\colon V\to V^*$.
This induces a quadratic form and hence a quadric on any $r$-plane $H$ in $V$
(with $H\not\subset{\mathcal V}(q)$).
This induced quadric is singular when $H$ is tangent to ${\mathcal V}(q)$.
Since a quadratic form is degenerate only when the associated projective
quadric is singular, we see that
$H$ is tangent to the quadric
${\mathcal V}(q)$ if and only if
$(\wedge^r\varphi(\wedge^rH),\,\wedge^rH)=0$.
(This includes the case $H\subset{\mathcal V}(q)$.)
We summarize this argument.
\begin{theorem}
Let $\varphi\colon V\to V^*$ be a linear map with resulting bilinear form
$(\varphi({\bf u}),\,{\bf v})$.
Then the locus of $r$-planes in $V$ for which the restriction of this form
is degenerate is the set of $r$-planes $H$ whose Pl\"ucker
coordinates\index{Plucker coordinate@Pl\"ucker coordinate} are
isotropic, $(\wedge^r\varphi(\wedge^rH),\,\wedge^rH)=0$, with respect to the
induced form on $\wedge^rV$.
When $\varphi$ is symmetric, this is the locus of $r$-planes tangent to the
associated quadric in ${\mathbb P}(V)$.
\end{theorem}
We explore the problem of lines tangent to quadrics in ${\mathbb P}^n$.
From the calculations of Section~\ref{sec:global}, we do not expect this to
be interesting if the quadrics are general.
(This is borne out for ${\mathbb P}^4$:
we find 320 lines in ${\mathbb P}^4$ tangent to 6 general quadrics.
This is the B\'ezout number\index{Bezout number@B\'ezout number}, as $\deg{\bf G}_{2,5}=5$
and the condition to be tangent to a quadric has degree 2.)
This problem is interesting if the quadrics
in ${\mathbb P}^n$ share a quadric in a ${\mathbb P}^{n-1}$.
We propose studying such enumerative problems, both determining the
number of solutions for general such quadrics, and investigating whether or
not it is possible to have all solutions be real.
We use \Mtwo{}\/ to compute the expected number of
solutions to this problem when $r=2$ and $n=4$.
We first define some functions for this computation, which will involve
counting the degree of the ideal of lines in ${\mathbb P}^4$ tangent to 6
general spheres\index{sphere}.
Here, $X$ gives local coordinates for the Grassmannian\index{Grassmannian},
$M$ is a symmetric matrix, {\tt tanQuad} gives the equation in $X$ for the
lines tangent to the quadric given by $M$.
%
<<<tanQuad = (M, X) -> (
u := X^{0};
v := X^{1};
(u * M * transpose v)^2 -
(u * M * transpose u) * (v * M * transpose v)
);>>>
%
{\tt nSphere} gives the matrix $M$ for a sphere with
center {\tt V} and squared radius {\tt r}, and {\tt V} and {\tt r} give random
data for a sphere.
%
<<<nSphere = (V, r) ->
(matrix {{r + V * transpose V}} || transpose V ) |
( V || id_((ring r)^n)
);>>>
%
<<<V = () -> matrix table(1, n, (i,j) -> random(0, R));>>>
%
<<<r = () -> random(0, R);>>>
%
We construct the ambient ring, local coordinates, and the ideal of the
enumerative problem of lines in ${\mathbb P}^4$ tangent to 6 random spheres.
%
<<<n = 4;>>>
%
<<<R = ZZ/1009[flatten(table(2, n-1, (i,j) -> z_(i,j)))];>>>
%
<<<X = 1 | matrix table(2, n-1, (i,j) -> z_(i,j))>>>
%
<<<I = ideal (apply(1..(2*n-2),
i -> tanQuad(nSphere(V(), r()), X)));>>>
%
We find there are 24 lines in ${\mathbb P}^4$ tangent to 6 general spheres.
<<<dim I, degree I>>>
%
The expected numbers of solutions we have obtained in this way are displayed
in the table below.
The numbers in boldface are those which are proven.\footnote{As this was
going to press, the obvious pattern was proven:
There are $3\cdot 2^{n-1}$ complex lines tangent to $2n-2$
general spheres in ${\mathbb R}^n$, and all may be real~\cite{SO:STh01}.}
\begin{center}
\begin{tabular}{|c|c|c|c|c|c|}\hline
$n$&2&3&4&5&6\\\hline
\# expected\;&\;{\bf 4}\;&\;{\bf 12}\;&\;24\;&\;48\;&\;96\;\\\hline
\end{tabular}
\end{center}
\begin{acknowledgment}
We thank Dan Grayson and
Bernd Sturmfels:
some of the procedures in this chapter were written by Dan Grayson
and the calculation in Section 5.2 is due to Bernd Sturmfels.
\end{acknowledgment}
%\bibliographystyle{siam}
%\bibliography{../../bibl/bibliography,../../bibl/sottile}
%\end{document}
|
import data.complex.basic tactic.ring
open is_absolute_value
lemma finset.exists_max {α : Type*} [decidable_linear_order α] [inhabited α] (s : finset α) : ∃ a : α, ∀ b : α, b ∈ s → b ≤ a := begin
apply finset.induction_on s,
existsi default α,simp,
assume a s as hi,
cases hi with m hm,
existsi max a m,
assume b,simp,assume h,
cases h with h h,
rw h, exact le_max_left _ _,
exact le_trans (hm b h) (le_max_right _ _),
end
lemma seq_bounded_above_of_cau {α : Type*} {β : Type*} [discrete_linear_ordered_field α]
[ring β] {f : ℕ → β} {abv : β → α} [is_absolute_value abv] : is_cau_seq abv f →
∃ a : α, ∀ i : ℕ, abv (f i) < a := begin
assume h,unfold is_cau_seq at h,
have iα : inhabited α := ⟨0⟩,
cases h 1 (by norm_num) with i hi,
have : ∀ j : ℕ, j ≥ i → abv (f j) - abv (f i) < 1,assume j ji,
have := hi j ji,
exact lt_of_le_of_lt (sub_abv_le_abv_sub _ _ _) this,
generalize hs : finset.image (λ k, abv (f k)) (finset.range i) = s,
cases finset.exists_max s with ms hms,
existsi max (1 + abv (f i)) (ms + 1),assume i₁,
cases lt_or_ge i₁ i,
have := finset.mem_image_of_mem (λ (k : ℕ), abv (f k)) (finset.mem_range.mpr h_1),rw hs at this,
have := hms _ this,simp at this,
exact lt_of_le_of_lt this (lt_of_lt_of_le (lt_add_one _) (le_max_right _ _)),
have := this i₁ h_1,
rw sub_lt_iff_lt_add at this,
exact lt_of_lt_of_le this (le_max_left _ _),
end
section real
open real
lemma real.lim_const {f : ℕ → ℝ} (hf : is_cau_seq abs f) (x : ℝ) : x = real.lim f ↔
cau_seq.const abs x ≈ ⟨f, hf⟩ := begin
have := real.equiv_lim ⟨f, hf⟩,split,assume h,rw h,simp at this,exact setoid.symm this,
assume h,have := setoid.trans h this,rw cau_seq.const_equiv at this,simp at this, exact this,
end
lemma real.lim_eq_lim_iff_equiv {f g : ℕ → ℝ} (hf : is_cau_seq abs f)
(hg : is_cau_seq abs g) : real.lim f = real.lim g ↔ @has_equiv.equiv
(cau_seq ℝ abs) _ ⟨f, hf⟩ ⟨g, hg⟩ := begin
have h₁:= real.lim_const hg (real.lim f),
have h₂:= real.lim_const hf (real.lim g),
split,assume h, simp * at *,
exact setoid.trans (setoid.symm h₂) h₁,
assume h,rw h₁,have := real.equiv_lim ⟨f, hf⟩,simp at this,
exact setoid.trans (setoid.symm this) h,
end
-- would be useful to have is_cau_seq abs f → is_cau_seq abs g → is_cau_seq abs (λ i, f i + g i)
-- in the library, similarly for mul
lemma real.lim_add {f g : ℕ → ℝ} (hf : is_cau_seq abs f)
(hg : is_cau_seq abs g) : real.lim f + real.lim g =
real.lim (λ x, f x + g x) := begin
have : ∀ (ε : ℝ),
ε > 0 → (∃ (i : ℕ), ∀ (j : ℕ), j ≥ i → abs (f j + (g j + (-real.lim f + -real.lim g))) < ε),
{assume ε ε0,
cases real.equiv_lim ⟨f, hf⟩ (ε / 2) (div_pos ε0 (by norm_num)) with fi hfi,simp at hfi,
cases real.equiv_lim ⟨g, hg⟩ (ε / 2) (div_pos ε0 (by norm_num)) with gi hgi,simp at hgi,
existsi max fi gi,
assume j hj,rw [add_left_comm (g j),←add_assoc (f j)],
refine lt_of_le_of_lt (abs_add _ _) _,rw ←add_halves ε,
exact add_lt_add (hfi j (le_trans (le_max_left _ _) hj)) (hgi j (le_trans (le_max_right _ _) hj))},
have cau : is_cau_seq abs (λ (x : ℕ), f x + g x), refine cau_seq.of_near _ (cau_seq.const abs (real.lim f + real.lim g)) _,simpa,
rw real.lim_const,refine setoid.symm _,exact cau,assume ε ε0,simp,exact this ε ε0,
end
lemma real.lim_mul {f g : ℕ → ℝ} (hf : is_cau_seq abs f)
(hg : is_cau_seq abs g) : real.lim f * real.lim g =
real.lim (λ x, f x * g x) := begin
have : ∀ (ε : ℝ),
ε > 0 → (∃ (i : ℕ), ∀ (j : ℕ), j ≥ i → abs (f j * g j - (real.lim f * real.lim g)) < ε),
{ assume ε ε0,
cases seq_bounded_above_of_cau hg with G hG,
have G0 : 0 < G := lt_of_le_of_lt (abs_nonneg _) (hG 0),
have Gf : 0 < G + abs (lim f) := add_pos_of_pos_of_nonneg G0 (abs_nonneg _),
have Gε : 0 < ε / (G + abs (lim f)) := div_pos ε0 Gf,
cases real.equiv_lim ⟨f, hf⟩ _ Gε with fi hfi, simp at hfi,
cases real.equiv_lim ⟨g, hg⟩ _ Gε with gi hgi, simp at hgi,
existsi max fi gi,assume j ji,
rw (by simp[mul_add,add_mul];ring : f j * g j -lim f * lim g = (f j - lim f) * g j + lim f * (g j - lim g)),
refine lt_of_le_of_lt (abs_add _ _) _,
rw [abs_mul],
suffices : abs (f j - lim f) * G + abs (lim f * (g j - lim g)) < ε,
exact lt_of_le_of_lt (add_le_add (mul_le_mul_of_nonneg_left (le_of_lt (hG j)) (abs_nonneg _)) (le_refl _)) this,
rw abs_mul,
have : ε = ε * G / (G + abs (lim f)) + ε * abs (lim f) / (G + abs (lim f)),
{rw [←add_div,←mul_add,mul_div_cancel _ (ne_of_lt Gf).symm]},
rw this,
refine add_lt_add_of_lt_of_le _ _,
{rw [mul_comm,mul_comm ε,mul_div_assoc],
exact mul_lt_mul_of_pos_left (hfi j (le_trans (le_max_left _ _) ji)) G0},
rw [mul_comm ε,mul_div_assoc],
refine mul_le_mul_of_nonneg_left (le_of_lt (hgi j (le_trans (le_max_right _ _) ji))) (abs_nonneg _)},
have cau : is_cau_seq abs (λ (x : ℕ), f x * g x), refine cau_seq.of_near _ (cau_seq.const abs (real.lim f * real.lim g)) _,simpa,
rw real.lim_const, refine setoid.symm _,exact cau,assume ε ε0,simp, exact this ε ε0,
end
end real
lemma complex.re_const_equiv_of_const_equiv {f : ℕ → ℂ} (hf : is_cau_seq complex.abs f) (z : ℂ) :
cau_seq.const complex.abs z ≈ ⟨f, hf⟩ → cau_seq.const abs z.re ≈ ⟨(λ (n : ℕ), (f n).re),
complex.is_cau_seq_re ⟨f,hf⟩⟩ := begin
assume h,assume ε ε0,cases h ε ε0 with i hi,existsi i,assume j ji,
replace hi := hi j ji, simp at *, rw [←complex.neg_re,←complex.add_re],
exact lt_of_le_of_lt (complex.abs_re_le_abs _) hi,
end
lemma complex.im_const_equiv_of_const_equiv {f : ℕ → ℂ} (hf : is_cau_seq complex.abs f) (z : ℂ) :
cau_seq.const complex.abs z ≈ ⟨f, hf⟩ → cau_seq.const abs z.im ≈ ⟨(λ (n : ℕ), (f n).im),
complex.is_cau_seq_im ⟨f,hf⟩⟩ := begin
assume h,assume ε ε0,cases h ε ε0 with i hi,existsi i,assume j ji,
replace hi := hi j ji, simp at *, rw [←complex.neg_im,←complex.add_im],
exact lt_of_le_of_lt (complex.abs_im_le_abs _) hi,
end
lemma complex.lim_const {f : ℕ → ℂ} (hf : is_cau_seq complex.abs f) (z : ℂ) : z = complex.lim f ↔
cau_seq.const complex.abs z ≈ ⟨f, hf⟩ := begin
split,have := complex.equiv_lim ⟨f, hf⟩,simp at this,
assume h,rw h, exact setoid.symm this,assume h,
unfold complex.lim,cases z with zre zim,simp,
split, have := real.equiv_lim ⟨(λ (n : ℕ), (f n).re), complex.is_cau_seq_re ⟨f,hf⟩⟩,
rw ←cau_seq.const_equiv,simp at this,
have hf := complex.re_const_equiv_of_const_equiv hf {re := zre, im := zim} h,simp at hf,
exact setoid.trans hf this,
have := real.equiv_lim ⟨(λ (n : ℕ), (f n).im), complex.is_cau_seq_im ⟨f,hf⟩⟩,
rw ←cau_seq.const_equiv,simp at this,
have hf := complex.im_const_equiv_of_const_equiv hf {re := zre, im := zim} h,simp at hf,
exact setoid.trans hf this,
end
lemma complex.lim_eq_lim_iff_equiv {f g : ℕ → ℂ} (hf : is_cau_seq complex.abs f)
(hg : is_cau_seq complex.abs g) : complex.lim f = complex.lim g ↔ @has_equiv.equiv
(cau_seq ℂ complex.abs) _ ⟨f, hf⟩ ⟨g, hg⟩ := begin
have h₁:= complex.lim_const hg (complex.lim f),
have h₂:= complex.lim_const hf (complex.lim g),
split,assume h, simp * at *,
exact setoid.trans (setoid.symm h₂) h₁,
assume h,rw h₁,have := complex.equiv_lim ⟨f, hf⟩,simp at this,
exact setoid.trans (setoid.symm this) h,
end
open complex
lemma complex.lim_add {f g : ℕ → ℂ} (hf : is_cau_seq complex.abs f)
(hg : is_cau_seq complex.abs g) : complex.lim f + complex.lim g =
complex.lim (λ x, f x + g x) := begin
have : ∀ (ε : ℝ),
ε > 0 → (∃ (i : ℕ), ∀ (j : ℕ), j ≥ i → complex.abs (f j + (g j + (-complex.lim f + -complex.lim g))) < ε),
{assume ε ε0,
cases complex.equiv_lim ⟨f, hf⟩ (ε / 2) (div_pos ε0 (by norm_num)) with fi hfi,simp at hfi,
cases complex.equiv_lim ⟨g, hg⟩ (ε / 2) (div_pos ε0 (by norm_num)) with gi hgi,simp at hgi,
existsi max fi gi,
assume j hj,rw [add_left_comm (g j),←add_assoc (f j)],
refine lt_of_le_of_lt (complex.abs_add _ _) _,rw ←add_halves ε,
exact add_lt_add (hfi j (le_trans (le_max_left _ _) hj)) (hgi j (le_trans (le_max_right _ _) hj))},
have cau : is_cau_seq complex.abs (λ (x : ℕ), f x + g x), refine cau_seq.of_near _ (cau_seq.const complex.abs (lim f + lim g)) _,simpa,
rw lim_const,refine setoid.symm _,exact cau,assume ε ε0,simp,exact this ε ε0,
end
lemma complex.lim_mul {f g : ℕ → ℂ} (hf : is_cau_seq complex.abs f)
(hg : is_cau_seq complex.abs g) : complex.lim f * complex.lim g =
complex.lim (λ x, f x * g x) := begin
have : ∀ (ε : ℝ),
ε > 0 → (∃ (i : ℕ), ∀ (j : ℕ), j ≥ i → complex.abs (f j * g j - (complex.lim f * complex.lim g)) < ε),
{ assume ε ε0,
cases seq_bounded_above_of_cau hg with G hG,
have G0 : 0 < G := lt_of_le_of_lt (complex.abs_nonneg _) (hG 0),
have Gf : 0 < G + complex.abs (complex.lim f) := add_pos_of_pos_of_nonneg G0 (complex.abs_nonneg _),
have Gε : 0 < ε / (G + complex.abs (complex.lim f)) := div_pos ε0 Gf,
cases complex.equiv_lim ⟨f, hf⟩ _ Gε with fi hfi, simp at hfi,
cases complex.equiv_lim ⟨g, hg⟩ _ Gε with gi hgi, simp at hgi,
existsi max fi gi,assume j ji,
rw (by simp[mul_add,add_mul];ring : f j * g j -complex.lim f * complex.lim g = (f j - complex.lim f) * g j + complex.lim f * (g j - complex.lim g)),
refine lt_of_le_of_lt (complex.abs_add _ _) _,
rw [complex.abs_mul],
suffices : complex.abs (f j - lim f) * G + complex.abs (lim f * (g j - lim g)) < ε,
exact lt_of_le_of_lt (add_le_add (mul_le_mul_of_nonneg_left (le_of_lt (hG j)) (abs_nonneg _)) (le_refl _)) this,
rw complex.abs_mul,
have : ε = ε * G / (G + abs (lim f)) + ε * abs (lim f) / (G + abs (lim f)),
{rw [←add_div,←mul_add,mul_div_cancel _ (ne_of_lt Gf).symm]},
rw this,
refine add_lt_add_of_lt_of_le _ _,
{rw [mul_comm,mul_comm ε,mul_div_assoc],
exact mul_lt_mul_of_pos_left (hfi j (le_trans (le_max_left _ _) ji)) G0},
rw [mul_comm ε,mul_div_assoc],
refine mul_le_mul_of_nonneg_left (le_of_lt (hgi j (le_trans (le_max_right _ _) ji))) (abs_nonneg _)},
have cau : is_cau_seq complex.abs (λ (x : ℕ), f x * g x), refine cau_seq.of_near _ (cau_seq.const abs (lim f * lim g)) _,simpa,
rw lim_const, refine setoid.symm _,exact cau,assume ε ε0,simp, exact this ε ε0,
end |
/-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import algebra.order.absolute_value
import algebra.big_operators.order
/-!
# Cauchy sequences
A basic theory of Cauchy sequences, used in the construction of the reals and p-adic numbers. Where
applicable, lemmas that will be reused in other contexts have been stated in extra generality.
There are other "versions" of Cauchyness in the library, in particular Cauchy filters in topology.
This is a concrete implementation that is useful for simplicity and computability reasons.
## Important definitions
* `is_cau_seq`: a predicate that says `f : ℕ → β` is Cauchy.
* `cau_seq`: the type of Cauchy sequences valued in type `β` with respect to an absolute value
function `abv`.
## Tags
sequence, cauchy, abs val, absolute value
-/
open_locale big_operators
open is_absolute_value
theorem exists_forall_ge_and {α} [linear_order α] {P Q : α → Prop} :
(∃ i, ∀ j ≥ i, P j) → (∃ i, ∀ j ≥ i, Q j) →
∃ i, ∀ j ≥ i, P j ∧ Q j
| ⟨a, h₁⟩ ⟨b, h₂⟩ := let ⟨c, ac, bc⟩ := exists_ge_of_linear a b in
⟨c, λ j hj, ⟨h₁ _ (le_trans ac hj), h₂ _ (le_trans bc hj)⟩⟩
section
variables {α : Type*} [linear_ordered_field α]
{β : Type*} [ring β] (abv : β → α) [is_absolute_value abv]
theorem rat_add_continuous_lemma
{ε : α} (ε0 : 0 < ε) : ∃ δ > 0, ∀ {a₁ a₂ b₁ b₂ : β},
abv (a₁ - b₁) < δ → abv (a₂ - b₂) < δ → abv (a₁ + a₂ - (b₁ + b₂)) < ε :=
⟨ε / 2, half_pos ε0, λ a₁ a₂ b₁ b₂ h₁ h₂,
by simpa [add_halves, sub_eq_add_neg, add_comm, add_left_comm, add_assoc]
using lt_of_le_of_lt (abv_add abv _ _) (add_lt_add h₁ h₂)⟩
theorem rat_mul_continuous_lemma
{ε K₁ K₂ : α} (ε0 : 0 < ε) :
∃ δ > 0, ∀ {a₁ a₂ b₁ b₂ : β}, abv a₁ < K₁ → abv b₂ < K₂ →
abv (a₁ - b₁) < δ → abv (a₂ - b₂) < δ → abv (a₁ * a₂ - b₁ * b₂) < ε :=
begin
have K0 : (0 : α) < max 1 (max K₁ K₂) := lt_of_lt_of_le zero_lt_one (le_max_left _ _),
have εK := div_pos (half_pos ε0) K0,
refine ⟨_, εK, λ a₁ a₂ b₁ b₂ ha₁ hb₂ h₁ h₂, _⟩,
replace ha₁ := lt_of_lt_of_le ha₁ (le_trans (le_max_left _ K₂) (le_max_right 1 _)),
replace hb₂ := lt_of_lt_of_le hb₂ (le_trans (le_max_right K₁ _) (le_max_right 1 _)),
have := add_lt_add
(mul_lt_mul' (le_of_lt h₁) hb₂ (abv_nonneg abv _) εK)
(mul_lt_mul' (le_of_lt h₂) ha₁ (abv_nonneg abv _) εK),
rw [← abv_mul abv, mul_comm, div_mul_cancel _ (ne_of_gt K0), ← abv_mul abv, add_halves] at this,
simpa [mul_add, add_mul, sub_eq_add_neg, add_comm, add_left_comm]
using lt_of_le_of_lt (abv_add abv _ _) this
end
theorem rat_inv_continuous_lemma
{β : Type*} [field β] (abv : β → α) [is_absolute_value abv]
{ε K : α} (ε0 : 0 < ε) (K0 : 0 < K) :
∃ δ > 0, ∀ {a b : β}, K ≤ abv a → K ≤ abv b →
abv (a - b) < δ → abv (a⁻¹ - b⁻¹) < ε :=
begin
have KK := mul_pos K0 K0,
have εK := mul_pos ε0 KK,
refine ⟨_, εK, λ a b ha hb h, _⟩,
have a0 := lt_of_lt_of_le K0 ha,
have b0 := lt_of_lt_of_le K0 hb,
rw [inv_sub_inv ((abv_pos abv).1 a0) ((abv_pos abv).1 b0),
abv_div abv, abv_mul abv, mul_comm, abv_sub abv,
← mul_div_cancel ε (ne_of_gt KK)],
exact div_lt_div h
(mul_le_mul hb ha (le_of_lt K0) (abv_nonneg abv _))
(le_of_lt $ mul_pos ε0 KK) KK
end
end
/-- A sequence is Cauchy if the distance between its entries tends to zero. -/
def is_cau_seq {α : Type*} [linear_ordered_field α]
{β : Type*} [ring β] (abv : β → α) (f : ℕ → β) : Prop :=
∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j - f i) < ε
namespace is_cau_seq
variables {α : Type*} [linear_ordered_field α]
{β : Type*} [ring β] {abv : β → α} [is_absolute_value abv] {f : ℕ → β}
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem cauchy₂ (hf : is_cau_seq abv f) {ε : α} (ε0 : 0 < ε) :
∃ i, ∀ j k ≥ i, abv (f j - f k) < ε :=
begin
refine (hf _ (half_pos ε0)).imp (λ i hi j k ij ik, _),
rw ← add_halves ε,
refine lt_of_le_of_lt (abv_sub_le abv _ _ _) (add_lt_add (hi _ ij) _),
rw abv_sub abv, exact hi _ ik
end
theorem cauchy₃ (hf : is_cau_seq abv f) {ε : α} (ε0 : 0 < ε) :
∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - f j) < ε :=
let ⟨i, H⟩ := hf.cauchy₂ ε0 in ⟨i, λ j ij k jk, H _ _ (le_trans ij jk) ij⟩
end is_cau_seq
/-- `cau_seq β abv` is the type of `β`-valued Cauchy sequences, with respect to the absolute value
function `abv`. -/
def cau_seq {α : Type*} [linear_ordered_field α]
(β : Type*) [ring β] (abv : β → α) : Type* :=
{f : ℕ → β // is_cau_seq abv f}
namespace cau_seq
variables {α : Type*} [linear_ordered_field α]
section ring
variables {β : Type*} [ring β] {abv : β → α}
instance : has_coe_to_fun (cau_seq β abv) (λ _, ℕ → β) := ⟨subtype.val⟩
@[simp] theorem mk_to_fun (f) (hf : is_cau_seq abv f) :
@coe_fn (cau_seq β abv) _ _ ⟨f, hf⟩ = f := rfl
theorem ext {f g : cau_seq β abv} (h : ∀ i, f i = g i) : f = g :=
subtype.eq (funext h)
theorem is_cau (f : cau_seq β abv) : is_cau_seq abv f := f.2
theorem cauchy (f : cau_seq β abv) :
∀ {ε}, 0 < ε → ∃ i, ∀ j ≥ i, abv (f j - f i) < ε := f.2
/-- Given a Cauchy sequence `f`, create a Cauchy sequence from a sequence `g` with
the same values as `f`. -/
def of_eq (f : cau_seq β abv) (g : ℕ → β) (e : ∀ i, f i = g i) : cau_seq β abv :=
⟨g, λ ε, by rw [show g = f, from (funext e).symm]; exact f.cauchy⟩
variable [is_absolute_value abv]
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem cauchy₂ (f : cau_seq β abv) {ε} : 0 < ε →
∃ i, ∀ j k ≥ i, abv (f j - f k) < ε := f.2.cauchy₂
theorem cauchy₃ (f : cau_seq β abv) {ε} : 0 < ε →
∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - f j) < ε := f.2.cauchy₃
theorem bounded (f : cau_seq β abv) : ∃ r, ∀ i, abv (f i) < r :=
begin
cases f.cauchy zero_lt_one with i h,
let R := ∑ j in finset.range (i+1), abv (f j),
have : ∀ j ≤ i, abv (f j) ≤ R,
{ intros j ij, change (λ j, abv (f j)) j ≤ R,
apply finset.single_le_sum,
{ intros, apply abv_nonneg abv },
{ rwa [finset.mem_range, nat.lt_succ_iff] } },
refine ⟨R + 1, λ j, _⟩,
cases lt_or_le j i with ij ij,
{ exact lt_of_le_of_lt (this _ (le_of_lt ij)) (lt_add_one _) },
{ have := lt_of_le_of_lt (abv_add abv _ _)
(add_lt_add_of_le_of_lt (this _ (le_refl _)) (h _ ij)),
rw [add_sub, add_comm] at this, simpa }
end
theorem bounded' (f : cau_seq β abv) (x : α) : ∃ r > x, ∀ i, abv (f i) < r :=
let ⟨r, h⟩ := f.bounded in
⟨max r (x+1), lt_of_lt_of_le (lt_add_one _) (le_max_right _ _),
λ i, lt_of_lt_of_le (h i) (le_max_left _ _)⟩
instance : has_add (cau_seq β abv) :=
⟨λ f g, ⟨λ i, (f i + g i : β), λ ε ε0,
let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abv ε0,
⟨i, H⟩ := exists_forall_ge_and (f.cauchy₃ δ0) (g.cauchy₃ δ0) in
⟨i, λ j ij, let ⟨H₁, H₂⟩ := H _ (le_refl _) in Hδ (H₁ _ ij) (H₂ _ ij)⟩⟩⟩
@[simp] theorem add_apply (f g : cau_seq β abv) (i : ℕ) : (f + g) i = f i + g i := rfl
variable (abv)
/-- The constant Cauchy sequence. -/
def const (x : β) : cau_seq β abv :=
⟨λ i, x, λ ε ε0, ⟨0, λ j ij, by simpa [abv_zero abv] using ε0⟩⟩
variable {abv}
local notation `const` := const abv
@[simp] theorem const_apply (x : β) (i : ℕ) : (const x : ℕ → β) i = x := rfl
theorem const_inj {x y : β} : (const x : cau_seq β abv) = const y ↔ x = y :=
⟨λ h, congr_arg (λ f:cau_seq β abv, (f:ℕ→β) 0) h, congr_arg _⟩
instance : has_zero (cau_seq β abv) := ⟨const 0⟩
instance : has_one (cau_seq β abv) := ⟨const 1⟩
instance : inhabited (cau_seq β abv) := ⟨0⟩
@[simp] theorem zero_apply (i) : (0 : cau_seq β abv) i = 0 := rfl
@[simp] theorem one_apply (i) : (1 : cau_seq β abv) i = 1 := rfl
@[simp] theorem const_zero : const 0 = 0 := rfl
theorem const_add (x y : β) : const (x + y) = const x + const y :=
ext $ λ i, rfl
instance : has_mul (cau_seq β abv) :=
⟨λ f g, ⟨λ i, (f i * g i : β), λ ε ε0,
let ⟨F, F0, hF⟩ := f.bounded' 0, ⟨G, G0, hG⟩ := g.bounded' 0,
⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abv ε0,
⟨i, H⟩ := exists_forall_ge_and (f.cauchy₃ δ0) (g.cauchy₃ δ0) in
⟨i, λ j ij, let ⟨H₁, H₂⟩ := H _ (le_refl _) in
Hδ (hF j) (hG i) (H₁ _ ij) (H₂ _ ij)⟩⟩⟩
@[simp] theorem mul_apply (f g : cau_seq β abv) (i : ℕ) : (f * g) i = f i * g i := rfl
theorem const_mul (x y : β) : const (x * y) = const x * const y :=
ext $ λ i, rfl
instance : has_neg (cau_seq β abv) :=
⟨λ f, of_eq (const (-1) * f) (λ x, -f x) (λ i, by simp)⟩
@[simp] theorem neg_apply (f : cau_seq β abv) (i) : (-f) i = -f i := rfl
theorem const_neg (x : β) : const (-x) = -const x :=
ext $ λ i, rfl
instance : has_sub (cau_seq β abv) :=
⟨λ f g, of_eq (f + -g) (λ x, f x - g x) (λ i, by simp [sub_eq_add_neg])⟩
@[simp] theorem sub_apply (f g : cau_seq β abv) (i : ℕ) : (f - g) i = f i - g i := rfl
theorem const_sub (x y : β) : const (x - y) = const x - const y :=
ext $ λ i, rfl
instance : ring (cau_seq β abv) :=
by refine_struct
{ neg := has_neg.neg,
add := (+),
zero := (0 : cau_seq β abv),
mul := (*),
one := 1,
sub := has_sub.sub,
npow := @npow_rec (cau_seq β abv) ⟨1⟩ ⟨(*)⟩,
nsmul := @nsmul_rec (cau_seq β abv) ⟨0⟩ ⟨(+)⟩,
zsmul := @zsmul_rec (cau_seq β abv) ⟨0⟩ ⟨(+)⟩ ⟨has_neg.neg⟩ };
intros; try { refl }; apply ext;
simp [mul_add, mul_assoc, add_mul, add_comm, add_left_comm, sub_eq_add_neg]
instance {β : Type*} [comm_ring β] {abv : β → α} [is_absolute_value abv] :
comm_ring (cau_seq β abv) :=
{ mul_comm := by intros; apply ext; simp [mul_left_comm, mul_comm],
..cau_seq.ring }
/-- `lim_zero f` holds when `f` approaches 0. -/
def lim_zero {abv : β → α} (f : cau_seq β abv) : Prop := ∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j) < ε
theorem add_lim_zero {f g : cau_seq β abv}
(hf : lim_zero f) (hg : lim_zero g) : lim_zero (f + g)
| ε ε0 := (exists_forall_ge_and
(hf _ $ half_pos ε0) (hg _ $ half_pos ε0)).imp $
λ i H j ij, let ⟨H₁, H₂⟩ := H _ ij in
by simpa [add_halves ε] using lt_of_le_of_lt (abv_add abv _ _) (add_lt_add H₁ H₂)
theorem mul_lim_zero_right (f : cau_seq β abv) {g}
(hg : lim_zero g) : lim_zero (f * g)
| ε ε0 := let ⟨F, F0, hF⟩ := f.bounded' 0 in
(hg _ $ div_pos ε0 F0).imp $ λ i H j ij,
by have := mul_lt_mul' (le_of_lt $ hF j) (H _ ij) (abv_nonneg abv _) F0;
rwa [mul_comm F, div_mul_cancel _ (ne_of_gt F0), ← abv_mul abv] at this
theorem mul_lim_zero_left {f} (g : cau_seq β abv)
(hg : lim_zero f) : lim_zero (f * g)
| ε ε0 := let ⟨G, G0, hG⟩ := g.bounded' 0 in
(hg _ $ div_pos ε0 G0).imp $ λ i H j ij,
by have := mul_lt_mul'' (H _ ij) (hG j) (abv_nonneg abv _) (abv_nonneg abv _);
rwa [div_mul_cancel _ (ne_of_gt G0), ← abv_mul abv] at this
theorem neg_lim_zero {f : cau_seq β abv} (hf : lim_zero f) : lim_zero (-f) :=
by rw ← neg_one_mul; exact mul_lim_zero_right _ hf
theorem sub_lim_zero {f g : cau_seq β abv}
(hf : lim_zero f) (hg : lim_zero g) : lim_zero (f - g) :=
by simpa only [sub_eq_add_neg] using add_lim_zero hf (neg_lim_zero hg)
theorem lim_zero_sub_rev {f g : cau_seq β abv} (hfg : lim_zero (f - g)) : lim_zero (g - f) :=
by simpa using neg_lim_zero hfg
theorem zero_lim_zero : lim_zero (0 : cau_seq β abv)
| ε ε0 := ⟨0, λ j ij, by simpa [abv_zero abv] using ε0⟩
theorem const_lim_zero {x : β} : lim_zero (const x) ↔ x = 0 :=
⟨λ H, (abv_eq_zero abv).1 $
eq_of_le_of_forall_le_of_dense (abv_nonneg abv _) $
λ ε ε0, let ⟨i, hi⟩ := H _ ε0 in le_of_lt $ hi _ (le_refl _),
λ e, e.symm ▸ zero_lim_zero⟩
instance equiv : setoid (cau_seq β abv) :=
⟨λ f g, lim_zero (f - g),
⟨λ f, by simp [zero_lim_zero],
λ f g h, by simpa using neg_lim_zero h,
λ f g h fg gh, by simpa [sub_eq_add_neg, add_assoc] using add_lim_zero fg gh⟩⟩
lemma add_equiv_add {f1 f2 g1 g2 : cau_seq β abv} (hf : f1 ≈ f2) (hg : g1 ≈ g2) :
f1 + g1 ≈ f2 + g2 :=
begin
change lim_zero ((f1 + g1) - _),
convert add_lim_zero hf hg using 1,
simp only [sub_eq_add_neg, add_assoc],
rw add_comm (-f2), simp only [add_assoc],
congr' 2, simp
end
lemma neg_equiv_neg {f g : cau_seq β abv} (hf : f ≈ g) : -f ≈ -g :=
begin
have hf : lim_zero _ := neg_lim_zero hf,
show lim_zero (-f - -g),
convert hf using 1, simp
end
theorem equiv_def₃ {f g : cau_seq β abv} (h : f ≈ g) {ε : α} (ε0 : 0 < ε) :
∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - g j) < ε :=
(exists_forall_ge_and (h _ $ half_pos ε0) (f.cauchy₃ $ half_pos ε0)).imp $
λ i H j ij k jk, let ⟨h₁, h₂⟩ := H _ ij in
by have := lt_of_le_of_lt (abv_add abv (f j - g j) _) (add_lt_add h₁ (h₂ _ jk));
rwa [sub_add_sub_cancel', add_halves] at this
theorem lim_zero_congr {f g : cau_seq β abv} (h : f ≈ g) : lim_zero f ↔ lim_zero g :=
⟨λ l, by simpa using add_lim_zero (setoid.symm h) l,
λ l, by simpa using add_lim_zero h l⟩
theorem abv_pos_of_not_lim_zero {f : cau_seq β abv} (hf : ¬ lim_zero f) :
∃ K > 0, ∃ i, ∀ j ≥ i, K ≤ abv (f j) :=
begin
haveI := classical.prop_decidable,
by_contra nk,
refine hf (λ ε ε0, _),
simp [not_forall] at nk,
cases f.cauchy₃ (half_pos ε0) with i hi,
rcases nk _ (half_pos ε0) i with ⟨j, ij, hj⟩,
refine ⟨j, λ k jk, _⟩,
have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add (hi j ij k jk) hj),
rwa [sub_add_cancel, add_halves] at this
end
theorem of_near (f : ℕ → β) (g : cau_seq β abv)
(h : ∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j - g j) < ε) : is_cau_seq abv f
| ε ε0 :=
let ⟨i, hi⟩ := exists_forall_ge_and
(h _ (half_pos $ half_pos ε0)) (g.cauchy₃ $ half_pos ε0) in
⟨i, λ j ij, begin
cases hi _ (le_refl _) with h₁ h₂, rw abv_sub abv at h₁,
have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add (hi _ ij).1 h₁),
have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add this (h₂ _ ij)),
rwa [add_halves, add_halves, add_right_comm,
sub_add_sub_cancel, sub_add_sub_cancel] at this
end⟩
lemma not_lim_zero_of_not_congr_zero {f : cau_seq _ abv} (hf : ¬ f ≈ 0) : ¬ lim_zero f :=
assume : lim_zero f,
have lim_zero (f - 0), by simpa,
hf this
lemma mul_equiv_zero (g : cau_seq _ abv) {f : cau_seq _ abv} (hf : f ≈ 0) : g * f ≈ 0 :=
have lim_zero (f - 0), from hf,
have lim_zero (g*f), from mul_lim_zero_right _ $ by simpa,
show lim_zero (g*f - 0), by simpa
lemma mul_not_equiv_zero {f g : cau_seq _ abv} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) : ¬ (f * g) ≈ 0 :=
assume : lim_zero (f*g - 0),
have hlz : lim_zero (f*g), by simpa,
have hf' : ¬ lim_zero f, by simpa using (show ¬ lim_zero (f - 0), from hf),
have hg' : ¬ lim_zero g, by simpa using (show ¬ lim_zero (g - 0), from hg),
begin
rcases abv_pos_of_not_lim_zero hf' with ⟨a1, ha1, N1, hN1⟩,
rcases abv_pos_of_not_lim_zero hg' with ⟨a2, ha2, N2, hN2⟩,
have : 0 < a1 * a2, from mul_pos ha1 ha2,
cases hlz _ this with N hN,
let i := max N (max N1 N2),
have hN' := hN i (le_max_left _ _),
have hN1' := hN1 i (le_trans (le_max_left _ _) (le_max_right _ _)),
have hN1' := hN2 i (le_trans (le_max_right _ _) (le_max_right _ _)),
apply not_le_of_lt hN',
change _ ≤ abv (_ * _),
rw is_absolute_value.abv_mul abv,
apply mul_le_mul; try { assumption },
{ apply le_of_lt ha2 },
{ apply is_absolute_value.abv_nonneg abv }
end
theorem const_equiv {x y : β} : const x ≈ const y ↔ x = y :=
show lim_zero _ ↔ _, by rw [← const_sub, const_lim_zero, sub_eq_zero]
end ring
section comm_ring
variables {β : Type*} [comm_ring β] {abv : β → α} [is_absolute_value abv]
lemma mul_equiv_zero' (g : cau_seq _ abv) {f : cau_seq _ abv} (hf : f ≈ 0) : f * g ≈ 0 :=
by rw mul_comm; apply mul_equiv_zero _ hf
end comm_ring
section is_domain
variables {β : Type*} [ring β] [is_domain β] (abv : β → α) [is_absolute_value abv]
lemma one_not_equiv_zero : ¬ (const abv 1) ≈ (const abv 0) :=
assume h,
have ∀ ε > 0, ∃ i, ∀ k, i ≤ k → abv (1 - 0) < ε, from h,
have h1 : abv 1 ≤ 0, from le_of_not_gt $
assume h2 : 0 < abv 1,
exists.elim (this _ h2) $ λ i hi,
lt_irrefl (abv 1) $ by simpa using hi _ (le_refl _),
have h2 : 0 ≤ abv 1, from is_absolute_value.abv_nonneg _ _,
have abv 1 = 0, from le_antisymm h1 h2,
have (1 : β) = 0, from (is_absolute_value.abv_eq_zero abv).1 this,
absurd this one_ne_zero
end is_domain
section field
variables {β : Type*} [field β] {abv : β → α} [is_absolute_value abv]
theorem inv_aux {f : cau_seq β abv} (hf : ¬ lim_zero f) :
∀ ε > 0, ∃ i, ∀ j ≥ i, abv ((f j)⁻¹ - (f i)⁻¹) < ε | ε ε0 :=
let ⟨K, K0, HK⟩ := abv_pos_of_not_lim_zero hf,
⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abv ε0 K0,
⟨i, H⟩ := exists_forall_ge_and HK (f.cauchy₃ δ0) in
⟨i, λ j ij, let ⟨iK, H'⟩ := H _ (le_refl _) in Hδ (H _ ij).1 iK (H' _ ij)⟩
/-- Given a Cauchy sequence `f` with nonzero limit, create a Cauchy sequence with values equal to
the inverses of the values of `f`. -/
def inv (f : cau_seq β abv) (hf : ¬ lim_zero f) : cau_seq β abv := ⟨_, inv_aux hf⟩
@[simp] theorem inv_apply {f : cau_seq β abv} (hf i) : inv f hf i = (f i)⁻¹ := rfl
theorem inv_mul_cancel {f : cau_seq β abv} (hf) : inv f hf * f ≈ 1 :=
λ ε ε0, let ⟨K, K0, i, H⟩ := abv_pos_of_not_lim_zero hf in
⟨i, λ j ij,
by simpa [(abv_pos abv).1 (lt_of_lt_of_le K0 (H _ ij)),
abv_zero abv] using ε0⟩
theorem const_inv {x : β} (hx : x ≠ 0) :
const abv (x⁻¹) = inv (const abv x) (by rwa const_lim_zero) :=
ext (assume n, by simp[inv_apply, const_apply])
end field
section abs
local notation `const` := const abs
/-- The entries of a positive Cauchy sequence eventually have a positive lower bound. -/
def pos (f : cau_seq α abs) : Prop := ∃ K > 0, ∃ i, ∀ j ≥ i, K ≤ f j
theorem not_lim_zero_of_pos {f : cau_seq α abs} : pos f → ¬ lim_zero f
| ⟨F, F0, hF⟩ H :=
let ⟨i, h⟩ := exists_forall_ge_and hF (H _ F0),
⟨h₁, h₂⟩ := h _ (le_refl _) in
not_lt_of_le h₁ (abs_lt.1 h₂).2
theorem const_pos {x : α} : pos (const x) ↔ 0 < x :=
⟨λ ⟨K, K0, i, h⟩, lt_of_lt_of_le K0 (h _ (le_refl _)),
λ h, ⟨x, h, 0, λ j _, le_refl _⟩⟩
theorem add_pos {f g : cau_seq α abs} : pos f → pos g → pos (f + g)
| ⟨F, F0, hF⟩ ⟨G, G0, hG⟩ :=
let ⟨i, h⟩ := exists_forall_ge_and hF hG in
⟨_, _root_.add_pos F0 G0, i,
λ j ij, let ⟨h₁, h₂⟩ := h _ ij in add_le_add h₁ h₂⟩
theorem pos_add_lim_zero {f g : cau_seq α abs} : pos f → lim_zero g → pos (f + g)
| ⟨F, F0, hF⟩ H :=
let ⟨i, h⟩ := exists_forall_ge_and hF (H _ (half_pos F0)) in
⟨_, half_pos F0, i, λ j ij, begin
cases h j ij with h₁ h₂,
have := add_le_add h₁ (le_of_lt (abs_lt.1 h₂).1),
rwa [← sub_eq_add_neg, sub_self_div_two] at this
end⟩
protected theorem mul_pos {f g : cau_seq α abs} : pos f → pos g → pos (f * g)
| ⟨F, F0, hF⟩ ⟨G, G0, hG⟩ :=
let ⟨i, h⟩ := exists_forall_ge_and hF hG in
⟨_, _root_.mul_pos F0 G0, i,
λ j ij, let ⟨h₁, h₂⟩ := h _ ij in
mul_le_mul h₁ h₂ (le_of_lt G0) (le_trans (le_of_lt F0) h₁)⟩
theorem trichotomy (f : cau_seq α abs) : pos f ∨ lim_zero f ∨ pos (-f) :=
begin
cases classical.em (lim_zero f); simp *,
rcases abv_pos_of_not_lim_zero h with ⟨K, K0, hK⟩,
rcases exists_forall_ge_and hK (f.cauchy₃ K0) with ⟨i, hi⟩,
refine (le_total 0 (f i)).imp _ _;
refine (λ h, ⟨K, K0, i, λ j ij, _⟩);
have := (hi _ ij).1;
cases hi _ (le_refl _) with h₁ h₂,
{ rwa abs_of_nonneg at this,
rw abs_of_nonneg h at h₁,
exact (le_add_iff_nonneg_right _).1
(le_trans h₁ $ neg_le_sub_iff_le_add'.1 $
le_of_lt (abs_lt.1 $ h₂ _ ij).1) },
{ rwa abs_of_nonpos at this,
rw abs_of_nonpos h at h₁,
rw [← sub_le_sub_iff_right, zero_sub],
exact le_trans (le_of_lt (abs_lt.1 $ h₂ _ ij).2) h₁ }
end
instance : has_lt (cau_seq α abs) := ⟨λ f g, pos (g - f)⟩
instance : has_le (cau_seq α abs) := ⟨λ f g, f < g ∨ f ≈ g⟩
theorem lt_of_lt_of_eq {f g h : cau_seq α abs}
(fg : f < g) (gh : g ≈ h) : f < h :=
show pos (h - f),
by simpa [sub_eq_add_neg, add_comm, add_left_comm] using pos_add_lim_zero fg (neg_lim_zero gh)
theorem lt_of_eq_of_lt {f g h : cau_seq α abs}
(fg : f ≈ g) (gh : g < h) : f < h :=
by have := pos_add_lim_zero gh (neg_lim_zero fg);
rwa [← sub_eq_add_neg, sub_sub_sub_cancel_right] at this
theorem lt_trans {f g h : cau_seq α abs} (fg : f < g) (gh : g < h) : f < h :=
show pos (h - f),
by simpa [sub_eq_add_neg, add_comm, add_left_comm] using add_pos fg gh
theorem lt_irrefl {f : cau_seq α abs} : ¬ f < f
| h := not_lim_zero_of_pos h (by simp [zero_lim_zero])
lemma le_of_eq_of_le {f g h : cau_seq α abs}
(hfg : f ≈ g) (hgh : g ≤ h) : f ≤ h :=
hgh.elim (or.inl ∘ cau_seq.lt_of_eq_of_lt hfg)
(or.inr ∘ setoid.trans hfg)
lemma le_of_le_of_eq {f g h : cau_seq α abs}
(hfg : f ≤ g) (hgh : g ≈ h) : f ≤ h :=
hfg.elim (λ h, or.inl (cau_seq.lt_of_lt_of_eq h hgh))
(λ h, or.inr (setoid.trans h hgh))
instance : preorder (cau_seq α abs) :=
{ lt := (<),
le := λ f g, f < g ∨ f ≈ g,
le_refl := λ f, or.inr (setoid.refl _),
le_trans := λ f g h fg, match fg with
| or.inl fg, or.inl gh := or.inl $ lt_trans fg gh
| or.inl fg, or.inr gh := or.inl $ lt_of_lt_of_eq fg gh
| or.inr fg, or.inl gh := or.inl $ lt_of_eq_of_lt fg gh
| or.inr fg, or.inr gh := or.inr $ setoid.trans fg gh
end,
lt_iff_le_not_le := λ f g,
⟨λ h, ⟨or.inl h,
not_or (mt (lt_trans h) lt_irrefl) (not_lim_zero_of_pos h)⟩,
λ ⟨h₁, h₂⟩, h₁.resolve_right
(mt (λ h, or.inr (setoid.symm h)) h₂)⟩ }
theorem le_antisymm {f g : cau_seq α abs} (fg : f ≤ g) (gf : g ≤ f) : f ≈ g :=
fg.resolve_left (not_lt_of_le gf)
theorem lt_total (f g : cau_seq α abs) : f < g ∨ f ≈ g ∨ g < f :=
(trichotomy (g - f)).imp_right
(λ h, h.imp (λ h, setoid.symm h) (λ h, by rwa neg_sub at h))
theorem le_total (f g : cau_seq α abs) : f ≤ g ∨ g ≤ f :=
(or.assoc.2 (lt_total f g)).imp_right or.inl
theorem const_lt {x y : α} : const x < const y ↔ x < y :=
show pos _ ↔ _, by rw [← const_sub, const_pos, sub_pos]
theorem const_le {x y : α} : const x ≤ const y ↔ x ≤ y :=
by rw le_iff_lt_or_eq; exact or_congr const_lt const_equiv
lemma le_of_exists {f g : cau_seq α abs}
(h : ∃ i, ∀ j ≥ i, f j ≤ g j) : f ≤ g :=
let ⟨i, hi⟩ := h in
(or.assoc.2 (cau_seq.lt_total f g)).elim
id
(λ hgf, false.elim (let ⟨K, hK0, j, hKj⟩ := hgf in
not_lt_of_ge (hi (max i j) (le_max_left _ _))
(sub_pos.1 (lt_of_lt_of_le hK0 (hKj _ (le_max_right _ _))))))
theorem exists_gt (f : cau_seq α abs) : ∃ a : α, f < const a :=
let ⟨K, H⟩ := f.bounded in
⟨K + 1, 1, zero_lt_one, 0, λ i _, begin
rw [sub_apply, const_apply, le_sub_iff_add_le', add_le_add_iff_right],
exact le_of_lt (abs_lt.1 (H _)).2
end⟩
theorem exists_lt (f : cau_seq α abs) : ∃ a : α, const a < f :=
let ⟨a, h⟩ := (-f).exists_gt in ⟨-a, show pos _,
by rwa [const_neg, sub_neg_eq_add, add_comm, ← sub_neg_eq_add]⟩
end abs
end cau_seq
|
#include "error_handling.h"
#include "rover.h"
#include "robot_configuration.h"
#include "fast_particle_slam.h"
#include "path_finding.h"
#include <stdio.h>
#include <chrono>
#include <fstream>
#include <clocale>
#include <boost/range/adaptor/transformed.hpp>
#include <boost/optional.hpp>
#include <opencv2/imgcodecs/imgcodecs.hpp> // cv::imread()
#include <opencv2/opencv.hpp>
int ParseLogFile(std::ifstream& ifs, bool bVideo, boost::optional<std::string> const& ostrOutput) {
cv::VideoWriter vid;
if(bVideo && ostrOutput) {
vid.open(
ostrOutput.get() + ".mov",
cv::VideoWriter::fourcc('m', 'p', '4', 'v'),
5,
cv::Size(c_nMapExtent, c_nMapExtent)
);
}
auto const tpStart = std::chrono::system_clock::now();
CFastParticleSlamBase pfslam;
SScanLine scanline;
SOdometryData odomPrev = {0};
double fSecondsPrev = 0;
double fSpeedPrevLeft = 0;
double fSpeedPrevRight = 0;
auto Speed = [&](SOdometryData const& odom, double fSeconds, bool bLeft) { // in m/s
auto const nTicks = (bLeft
? (odom.m_nFrontLeft + odom.m_nBackLeft)
: (odom.m_nFrontRight + odom.m_nBackRight)) / 2;
return encoderTicksToCm(nTicks) / 100.0 / (fSeconds - fSecondsPrev);
};
auto Acceleration = [&](SOdometryData const& odom, double fSeconds, bool bLeft) {
return (Speed(odom, fSeconds, bLeft) - (bLeft ? fSpeedPrevLeft : fSpeedPrevRight)) / (fSeconds - fSecondsPrev);
};
rbt::interval<double> intvlfAcceleration = rbt::interval<double>::empty();
rbt::interval<double> intvlfSpeed = rbt::interval<double>::empty();
std::setlocale(LC_ALL, "en_US.utf8");
for( std::string strLine; std::getline( ifs, strLine ); ) {
if(!strLine.empty()) {
switch(strLine[0]) {
case 'o':
SOdometryData odom;
double fSeconds;
if(5==sscanf(strLine.data(), "o;%lf;%hd;%hd;%hd;%hd",
&fSeconds,
&odom.m_nFrontLeft,
&odom.m_nFrontRight,
&odom.m_nBackLeft,
&odom.m_nBackRight))
{
scanline.add(odom);
intvlfAcceleration |= Acceleration(odom, fSeconds, /*bLeft*/ true);
intvlfAcceleration |= Acceleration(odom, fSeconds, /*bLeft*/ false);
intvlfSpeed |= Speed(odom, fSeconds, /*bLeft*/ true);
intvlfSpeed |= Speed(odom, fSeconds, /*bLeft*/ false);
odomPrev = odom;
fSpeedPrevLeft = Speed(odom, fSeconds, /*bLeft*/ true);
fSpeedPrevRight = Speed(odom, fSeconds, /*bLeft*/ false);
fSecondsPrev = fSeconds;
} else {
std::cerr << "Invalid odometry data: " << strLine << std::endl;
}
break;
case 'l':
{
std::vector<SScanLine::SScan> vecscan;
for(auto i = strLine.find(';', strLine.find(';') + 1);;) {
auto iEnd = strLine.find(';', i+1);
if(iEnd==std::string::npos) break;
int nAngle;
int nDistance;
if(2==sscanf(&strLine[i+1], "%d/%d", &nAngle, &nDistance)) {
vecscan.emplace_back(nAngle < 180 ? nAngle + 180 : nAngle - 180, nDistance);
} else {
std::cerr << "Invalid lidar data: " << &strLine[i] << std::endl;
}
i = iEnd;
}
scanline.m_vecscan = std::move(vecscan);
if(scanline.translation()!=rbt::size<double>::zero() || scanline.rotation()!=0.0) {
pfslam.receivedSensorData(scanline);
if(vid.isOpened()) {
cv::Mat matTemp;
cv::cvtColor(pfslam.getMapWithPoses(), matTemp, cv::COLOR_GRAY2RGB);
vid << matTemp;
}
}
scanline.clear();
break;
}
default:
std::cerr << "Invalid line in log file: " << strLine << std::endl;
return 1;
}
}
}
if(!bVideo && ostrOutput) {
try {
cv::imwrite(ostrOutput.get() + ".png", pfslam.getMap());
} catch (cv::Exception& ex) {
std::cerr << "Exception while writing to " << ostrOutput.get() << ": " << ex.what();
return 1;
}
}
// We are ignoring the rest of the last scan line
auto const tpEnd = std::chrono::system_clock::now();
std::chrono::duration<double> const durDiff = tpEnd-tpStart;
auto const poseFinal = pfslam.Poses().back();
std::cout << durDiff.count() << " s\n"
<< " Final pose: ("<< poseFinal.m_pt.x <<";"<< poseFinal.m_pt.y <<";" << poseFinal.m_fYaw << ")\n";
std::cout << " Min/Max Speed = ( " << intvlfSpeed.begin << " m/s, " << intvlfSpeed.end << " m/s)" << std::endl;
std::cout << " Min/Max Accel = ( " << intvlfAcceleration.begin << " m/s^2, " << intvlfAcceleration.end << " m/s^2)" << std::endl;
std::cout << " Finding path back to (0;0) \n";
{
auto const tpStart = std::chrono::system_clock::now();
auto const vecptf = FindPath(pfslam.getMap(), poseFinal, rbt::point<double>::zero());
auto const tpEnd = std::chrono::system_clock::now();
std::chrono::duration<double> const durDiff = tpEnd-tpStart;
std::cout << " Path finding took " << durDiff.count() << "s\n";
if(ostrOutput) {
cv::imwrite(
ostrOutput.get() + "_astar.png",
ObstacleMapWithPoses(
pfslam.getMap(),
boost::copy_range<std::vector<rbt::pose<double>>>(
boost::adaptors::transform(vecptf, [](rbt::point<double> const& ptf) { return rbt::pose<double>(ptf, 0); })
)
)
);
}
}
{
auto const tpStart = std::chrono::system_clock::now();
auto const vecposeConfigSpace = PathConfigurationSpace(matn, poseFinal, rbt::point<double>::zero());
auto const tpEnd = std::chrono::system_clock::now();
std::chrono::duration<double> const durDiff = tpEnd-tpStart;
std::cout << " Path finding in configuration space took " << durDiff.count() << "s\n";
if(ostrOutput) {
cv::imwrite(
ostrOutput.get() + "_cp.png",
ObstacleMapWithPoses(
matn,
vecposeConfigSpace
)
);
}
}
return 0;
}
|
Require Import ZArith.
Require Import List.
Require Import Instr.
Require Import CodeSpecs.
Require Import CodeTriples.
Require Import Concrete.
Require Import Encodable.
Require Import Utils.
(** Definition of a type class for mapping quasi abstract rules to concrete rule implementations *)
Definition listify_apply_rule {T} `{Encodable T} (ar: option (T * T)) (s0: stack): stack :=
match ar with
| None => CData (0, handlerTag) :: s0
| Some (lrpc, lr) => CData (1, handlerTag) ::
CData (labToZ lr, handlerTag) ::
CData (labToZ lrpc, handlerTag) :: s0
end.
Definition handler_initial_mem_matches
(opcode: Z) (tags : Z * Z * Z)
(pctag: Z)
(m: memory) : Prop :=
let '(tag1,tag2,tag3) := tags in
index_list_Z addrOpLabel m = Some (opcode,handlerTag)
/\ index_list_Z addrTag1 m = Some (tag1,handlerTag)
/\ index_list_Z addrTag2 m = Some (tag2,handlerTag)
/\ index_list_Z addrTag3 m = Some (tag3,handlerTag)
/\ index_list_Z addrTagPC m = Some (pctag,handlerTag).
Class ConcreteLabels (L : Type)
(EL : Encodable L)
(labelCount : OpCode -> nat)
(run_tmr : forall opcode,
L ->
Vector.t L (labelCount opcode) ->
option (L * L)) := {
genRule : OpCode -> list Instr;
genRuleCorrect :
forall opcode m0 (labs : Vector.t L (labelCount opcode)) pcl (Q : memory -> stack -> Prop),
handler_initial_mem_matches (opCodeToZ opcode) (labsToZs labs) (labToZ pcl) m0 ->
HT (genRule opcode)
(fun m s =>
m = m0 /\
Q m (listify_apply_rule (run_tmr opcode pcl labs) s))
Q
}.
|
/**************************************************************************\
|
| Copyright (C) 2009 Marc Stevens
|
| This program is free software: you can redistribute it and/or modify
| it under the terms of the GNU General Public License as published by
| the Free Software Foundation, either version 3 of the License, or
| (at your option) any later version.
|
| This program is distributed in the hope that it will be useful,
| but WITHOUT ANY WARRANTY; without even the implied warranty of
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
| GNU General Public License for more details.
|
| You should have received a copy of the GNU General Public License
| along with this program. If not, see <http://www.gnu.org/licenses/>.
|
\**************************************************************************/
#ifndef MAIN_HPP
#define MAIN_HPP
#include <iostream>
#include <vector>
#include <string>
#include <boost/filesystem/operations.hpp>
#include <hashclash/sdr.hpp>
#include <hashclash/saveload_bz2.hpp>
#include <hashclash/sha1differentialpath.hpp>
#include <hashclash/sha1messagespace.hpp>
using namespace hashclash;
using namespace std;
struct parameters_type {
parameters_type()
{
usetunnelbitconditions = false;
tunneldeepanalysis = false;
changebitstat = false;
mecarry = 0;
threebittunnels = true;
simpletunnels = false;
mintunnelpov = -1;
}
vector<string> rnd234_m_bitrelationfiles;
string rnd234_pathfile; // single path
string rnd1_pathsfile; // possibly multiple paths allowing choice without m bitrelation contradictions
unsigned tend_rnd1_me;
unsigned mod,index;
uint32 m_mask[80];
bool usetunnelbitconditions;
std::string tunnelfile;
unsigned mecarry;
bool tunneldeepanalysis;
bool changebitstat;
bool tunnelfilterbitcondition;
bool threebittunnels;
bool simpletunnels;
int mintunnelpov;
void show_mdiffs()
{
}
};
extern std::string workdir;
extern sha1differentialpath maindiffpath;
extern sha1messagespace mainmespace;
extern parameters_type mainparameters;
const int offset = 4;
unsigned load_block(istream& i, uint32 block[]);
void save_block(ostream& o, uint32 block[]);
int collisionfinding(parameters_type& parameters);
// filters.cpp
void mespace_to_pathbitrelationsmatrix(const sha1messagespace& mespace, vector< vector< vector<uint32> > >& pathbitrelationsmatrix);
void random_me(uint32 me[80], const vector< vector< vector<uint32> > >& pathbitrelationsmatrix);
void filter_tunnels_bitconditions(vector< sha1differentialpath >& tunnels, const sha1differentialpath& path);
bool filter_tunnel_bitrelations(const sha1differentialpath& tunnel, const vector< vector<uint32> >& bitrels);
void filter_tunnels_bitrelations(vector< sha1differentialpath >& tunnels, const vector< vector<uint32> >& bitrels);
// program_generator.cpp
string mask2bit_to_string(const string& variable, const uint32 mask, const unsigned bit);
void generate_program();
// tunnel_analysis.cpp
unsigned analyze_bc_tunnel(const sha1differentialpath& tunnel);
unsigned analyze_tunnel(const sha1differentialpath& tunnel, bool verbose = false, bool deepanalyze = false);
void analyze_tunnels_diffpath(const sha1differentialpath& mypath, const vector< vector<uint32> >& bitrels, vector<sha1differentialpath> tunnels = vector<sha1differentialpath>());
// checkoppaths.cpp
void checkokpaths();
#endif // MAIN_HPP
|
The Feast of the Goat received largely positive reviews , with several reviewers commenting on the book 's depiction of the relationship between sexuality and power , and on the graphic descriptions of violent events .
|
/-
Copyright (c) 2019 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import algebra.char_p.basic
import data.mv_polynomial.comm_ring
import data.mv_polynomial.equiv
import data.polynomial.field_division
import ring_theory.principal_ideal_domain
import ring_theory.polynomial.content
/-!
# Ring-theoretic supplement of data.polynomial.
## Main results
* `mv_polynomial.integral_domain`:
If a ring is an integral domain, then so is its polynomial ring over finitely many variables.
* `polynomial.is_noetherian_ring`:
Hilbert basis theorem, that if a ring is noetherian then so is its polynomial ring.
* `polynomial.wf_dvd_monoid`:
If an integral domain is a `wf_dvd_monoid`, then so is its polynomial ring.
* `polynomial.unique_factorization_monoid`:
If an integral domain is a `unique_factorization_monoid`, then so is its polynomial ring.
-/
noncomputable theory
open_locale classical big_operators
universes u v w
namespace polynomial
instance {R : Type u} [semiring R] (p : ℕ) [h : char_p R p] : char_p (polynomial R) p :=
let ⟨h⟩ := h in ⟨λ n, by rw [← C.map_nat_cast, ← C_0, C_inj, h]⟩
variables (R : Type u) [comm_ring R]
/-- The `R`-submodule of `R[X]` consisting of polynomials of degree ≤ `n`. -/
def degree_le (n : with_bot ℕ) : submodule R (polynomial R) :=
⨅ k : ℕ, ⨅ h : ↑k > n, (lcoeff R k).ker
/-- The `R`-submodule of `R[X]` consisting of polynomials of degree < `n`. -/
def degree_lt (n : ℕ) : submodule R (polynomial R) :=
⨅ k : ℕ, ⨅ h : k ≥ n, (lcoeff R k).ker
variable {R}
theorem mem_degree_le {n : with_bot ℕ} {f : polynomial R} :
f ∈ degree_le R n ↔ degree f ≤ n :=
by simp only [degree_le, submodule.mem_infi, degree_le_iff_coeff_zero, linear_map.mem_ker]; refl
@[mono] theorem degree_le_mono {m n : with_bot ℕ} (H : m ≤ n) :
degree_le R m ≤ degree_le R n :=
λ f hf, mem_degree_le.2 (le_trans (mem_degree_le.1 hf) H)
theorem degree_le_eq_span_X_pow {n : ℕ} :
degree_le R n = submodule.span R ↑((finset.range (n+1)).image (λ n, (X : polynomial R)^n)) :=
begin
apply le_antisymm,
{ intros p hp, replace hp := mem_degree_le.1 hp,
rw [← finsupp.sum_single p, finsupp.sum],
refine submodule.sum_mem _ (λ k hk, _),
show monomial _ _ ∈ _,
have := with_bot.coe_le_coe.1 (finset.sup_le_iff.1 hp k hk),
rw [single_eq_C_mul_X, C_mul'],
refine submodule.smul_mem _ _ (submodule.subset_span $ finset.mem_coe.2 $
finset.mem_image.2 ⟨_, finset.mem_range.2 (nat.lt_succ_of_le this), rfl⟩) },
rw [submodule.span_le, finset.coe_image, set.image_subset_iff],
intros k hk, apply mem_degree_le.2,
exact (degree_X_pow_le _).trans
(with_bot.coe_le_coe.2 $ nat.le_of_lt_succ $ finset.mem_range.1 hk)
end
theorem mem_degree_lt {n : ℕ} {f : polynomial R} :
f ∈ degree_lt R n ↔ degree f < n :=
by { simp_rw [degree_lt, submodule.mem_infi, linear_map.mem_ker, degree,
finset.sup_lt_iff (with_bot.bot_lt_coe n), mem_support_iff, with_bot.some_eq_coe,
with_bot.coe_lt_coe, lt_iff_not_ge', ne, not_imp_not], refl }
@[mono] theorem degree_lt_mono {m n : ℕ} (H : m ≤ n) :
degree_lt R m ≤ degree_lt R n :=
λ f hf, mem_degree_lt.2 (lt_of_lt_of_le (mem_degree_lt.1 hf) $ with_bot.coe_le_coe.2 H)
theorem degree_lt_eq_span_X_pow {n : ℕ} :
degree_lt R n = submodule.span R ↑((finset.range n).image (λ n, X^n) : finset (polynomial R)) :=
begin
apply le_antisymm,
{ intros p hp, replace hp := mem_degree_lt.1 hp,
rw [← finsupp.sum_single p, finsupp.sum],
refine submodule.sum_mem _ (λ k hk, _),
show monomial _ _ ∈ _,
have := with_bot.coe_lt_coe.1 ((finset.sup_lt_iff $ with_bot.bot_lt_coe n).1 hp k hk),
rw [single_eq_C_mul_X, C_mul'],
refine submodule.smul_mem _ _ (submodule.subset_span $ finset.mem_coe.2 $
finset.mem_image.2 ⟨_, finset.mem_range.2 this, rfl⟩) },
rw [submodule.span_le, finset.coe_image, set.image_subset_iff],
intros k hk, apply mem_degree_lt.2,
exact lt_of_le_of_lt (degree_X_pow_le _) (with_bot.coe_lt_coe.2 $ finset.mem_range.1 hk)
end
/-- The first `n` coefficients on `degree_lt n` form a linear equivalence with `fin n → F`. -/
def degree_lt_equiv (F : Type*) [field F] (n : ℕ) : degree_lt F n ≃ₗ[F] (fin n → F) :=
{ to_fun := λ p n, (↑p : polynomial F).coeff n,
inv_fun := λ f, ⟨∑ i : fin n, monomial i (f i),
(degree_lt F n).sum_mem (λ i _, mem_degree_lt.mpr (lt_of_le_of_lt
(degree_monomial_le i (f i)) (with_bot.coe_lt_coe.mpr i.is_lt)))⟩,
map_add' := λ p q, by { ext, rw [submodule.coe_add, coeff_add], refl },
map_smul' := λ x p, by { ext, rw [submodule.coe_smul, coeff_smul], refl },
left_inv :=
begin
rintro ⟨p, hp⟩, ext1,
simp only [submodule.coe_mk],
by_cases hp0 : p = 0,
{ subst hp0, simp only [coeff_zero, linear_map.map_zero, finset.sum_const_zero] },
rw [mem_degree_lt, degree_eq_nat_degree hp0, with_bot.coe_lt_coe] at hp,
conv_rhs { rw [p.as_sum_range' n hp, ← fin.sum_univ_eq_sum_range] },
end,
right_inv :=
begin
intro f, ext i,
simp only [finset_sum_coeff, submodule.coe_mk],
rw [finset.sum_eq_single i, coeff_monomial, if_pos rfl],
{ rintro j - hji, rw [coeff_monomial, if_neg], rwa [← subtype.ext_iff] },
{ intro h, exact (h (finset.mem_univ _)).elim }
end }
local attribute [instance] subset.ring
/-- Given a polynomial, return the polynomial whose coefficients are in
the ring closure of the original coefficients. -/
def restriction (p : polynomial R) : polynomial (ring.closure (↑p.frange : set R)) :=
⟨p.support, λ i, ⟨p.to_fun i,
if H : p.to_fun i = 0 then H.symm ▸ is_add_submonoid.zero_mem
else ring.subset_closure $ finsupp.mem_frange.2 ⟨H, i, rfl⟩⟩,
λ i, finsupp.mem_support_iff.trans (not_iff_not_of_iff ⟨λ H, subtype.eq H, subtype.mk.inj⟩)⟩
@[simp] theorem coeff_restriction {p : polynomial R} {n : ℕ} :
↑(coeff (restriction p) n) = coeff p n := rfl
@[simp] theorem coeff_restriction' {p : polynomial R} {n : ℕ} :
(coeff (restriction p) n).1 = coeff p n := rfl
section
local attribute [instance] algebra.of_is_subring subring.domain subset.comm_ring
@[simp] theorem map_restriction (p : polynomial R) : p.restriction.map (algebra_map _ _) = p :=
ext $ λ n, by rw [coeff_map, algebra.is_subring_algebra_map_apply, coeff_restriction]
end
@[simp] theorem degree_restriction {p : polynomial R} : (restriction p).degree = p.degree := rfl
@[simp] theorem nat_degree_restriction {p : polynomial R} :
(restriction p).nat_degree = p.nat_degree := rfl
@[simp] theorem monic_restriction {p : polynomial R} : monic (restriction p) ↔ monic p :=
⟨λ H, congr_arg subtype.val H, λ H, subtype.eq H⟩
@[simp] theorem restriction_zero : restriction (0 : polynomial R) = 0 := rfl
@[simp] theorem restriction_one : restriction (1 : polynomial R) = 1 :=
ext $ λ i, subtype.eq $ by rw [coeff_restriction', coeff_one, coeff_one]; split_ifs; refl
variables {S : Type v} [ring S] {f : R →+* S} {x : S}
theorem eval₂_restriction {p : polynomial R} :
eval₂ f x p = eval₂ (f.comp (is_subring.subtype _)) x p.restriction :=
by { dsimp only [eval₂_eq_sum], refl, }
section to_subring
variables (p : polynomial R) (T : set R) [is_subring T]
/-- Given a polynomial `p` and a subring `T` that contains the coefficients of `p`,
return the corresponding polynomial whose coefficients are in `T. -/
def to_subring (hp : ↑p.frange ⊆ T) : polynomial T :=
⟨p.support, λ i, ⟨p.to_fun i,
if H : p.to_fun i = 0 then H.symm ▸ is_add_submonoid.zero_mem
else hp $ finsupp.mem_frange.2 ⟨H, i, rfl⟩⟩,
λ i, finsupp.mem_support_iff.trans (not_iff_not_of_iff ⟨λ H, subtype.eq H, subtype.mk.inj⟩)⟩
variables (hp : ↑p.frange ⊆ T)
include hp
@[simp] theorem coeff_to_subring {n : ℕ} : ↑(coeff (to_subring p T hp) n) = coeff p n := rfl
@[simp] theorem coeff_to_subring' {n : ℕ} : (coeff (to_subring p T hp) n).1 = coeff p n := rfl
@[simp] theorem degree_to_subring : (to_subring p T hp).degree = p.degree := rfl
@[simp] theorem nat_degree_to_subring : (to_subring p T hp).nat_degree = p.nat_degree := rfl
@[simp] theorem monic_to_subring : monic (to_subring p T hp) ↔ monic p :=
⟨λ H, congr_arg subtype.val H, λ H, subtype.eq H⟩
omit hp
@[simp] theorem to_subring_zero : to_subring (0 : polynomial R) T (set.empty_subset _) = 0 := rfl
@[simp] theorem to_subring_one : to_subring (1 : polynomial R) T
(set.subset.trans (finset.coe_subset.2 finsupp.frange_single)
(finset.singleton_subset_set_iff.2 is_submonoid.one_mem)) = 1 :=
ext $ λ i, subtype.eq $ by rw [coeff_to_subring', coeff_one, coeff_one]; split_ifs; refl
@[simp] theorem map_to_subring : (p.to_subring T hp).map (is_subring.subtype T) = p :=
ext $ λ n, coeff_map _ _
end to_subring
variables (T : set R) [is_subring T]
/-- Given a polynomial whose coefficients are in some subring, return
the corresponding polynomial whose coefificents are in the ambient ring. -/
def of_subring (p : polynomial T) : polynomial R :=
⟨p.support, subtype.val ∘ p.to_fun,
λ n, finsupp.mem_support_iff.trans (not_iff_not_of_iff
⟨λ h, congr_arg subtype.val h, λ h, subtype.eq h⟩)⟩
@[simp] theorem frange_of_subring {p : polynomial T} :
↑(p.of_subring T).frange ⊆ T :=
λ y H, let ⟨hy, x, hx⟩ := finsupp.mem_frange.1 H in hx ▸ (p.to_fun x).2
end polynomial
variables {R : Type u} {σ : Type v} {M : Type w} [comm_ring R] [add_comm_group M] [module R M]
namespace ideal
open polynomial
/-- If every coefficient of a polynomial is in an ideal `I`, then so is the polynomial itself -/
lemma polynomial_mem_ideal_of_coeff_mem_ideal (I : ideal (polynomial R)) (p : polynomial R)
(hp : ∀ (n : ℕ), (p.coeff n) ∈ I.comap C) : p ∈ I :=
sum_C_mul_X_eq p ▸ submodule.sum_mem I (λ n hn, I.mul_mem_right _ (hp n))
/-- The push-forward of an ideal `I` of `R` to `polynomial R` via inclusion
is exactly the set of polynomials whose coefficients are in `I` -/
theorem mem_map_C_iff {I : ideal R} {f : polynomial R} :
f ∈ (ideal.map C I : ideal (polynomial R)) ↔ ∀ n : ℕ, f.coeff n ∈ I :=
begin
split,
{ intros hf,
apply submodule.span_induction hf,
{ intros f hf n,
cases (set.mem_image _ _ _).mp hf with x hx,
rw [← hx.right, coeff_C],
by_cases (n = 0),
{ simpa [h] using hx.left },
{ simp [h] } },
{ simp },
{ exact λ f g hf hg n, by simp [I.add_mem (hf n) (hg n)] },
{ refine λ f g hg n, _,
rw [smul_eq_mul, coeff_mul],
exact I.sum_mem (λ c hc, I.smul_mem (f.coeff c.fst) (hg c.snd)) } },
{ intros hf,
rw ← sum_monomial_eq f,
refine (I.map C : ideal (polynomial R)).sum_mem (λ n hn, _),
simp [single_eq_C_mul_X],
rw mul_comm,
exact (I.map C : ideal (polynomial R)).mul_mem_left _ (mem_map_of_mem (hf n)) }
end
lemma quotient_map_C_eq_zero {I : ideal R} :
∀ a ∈ I, ((quotient.mk (map C I : ideal (polynomial R))).comp C) a = 0 :=
begin
intros a ha,
rw [ring_hom.comp_apply, quotient.eq_zero_iff_mem],
exact mem_map_of_mem ha,
end
lemma eval₂_C_mk_eq_zero {I : ideal R} :
∀ f ∈ (map C I : ideal (polynomial R)), eval₂_ring_hom (C.comp (quotient.mk I)) X f = 0 :=
begin
intros a ha,
rw ← sum_monomial_eq a,
dsimp,
rw eval₂_sum,
refine finset.sum_eq_zero (λ n hn, _),
dsimp,
rw eval₂_monomial (C.comp (quotient.mk I)) X,
refine mul_eq_zero_of_left (polynomial.ext (λ m, _)) (X ^ n),
erw coeff_C,
by_cases h : m = 0,
{ simpa [h] using quotient.eq_zero_iff_mem.2 ((mem_map_C_iff.1 ha) n) },
{ simp [h] }
end
/-- If `I` is an ideal of `R`, then the ring polynomials over the quotient ring `I.quotient` is
isomorphic to the quotient of `polynomial R` by the ideal `map C I`,
where `map C I` contains exactly the polynomials whose coefficients all lie in `I` -/
def polynomial_quotient_equiv_quotient_polynomial (I : ideal R) :
polynomial (I.quotient) ≃+* (map C I : ideal (polynomial R)).quotient :=
{ to_fun := eval₂_ring_hom
(quotient.lift I ((quotient.mk (map C I : ideal (polynomial R))).comp C) quotient_map_C_eq_zero)
((quotient.mk (map C I : ideal (polynomial R)) X)),
inv_fun := quotient.lift (map C I : ideal (polynomial R))
(eval₂_ring_hom (C.comp (quotient.mk I)) X) eval₂_C_mk_eq_zero,
map_mul' := λ f g, by simp,
map_add' := λ f g, by simp,
left_inv := begin
intro f,
apply polynomial.induction_on' f,
{ simp_intros p q hp hq,
rw [hp, hq] },
{ rintros n ⟨x⟩,
simp [monomial_eq_smul_X, C_mul'] }
end,
right_inv := begin
rintro ⟨f⟩,
apply polynomial.induction_on' f,
{ simp_intros p q hp hq,
rw [hp, hq] },
{ intros n a,
simp [monomial_eq_smul_X, ← C_mul' a (X ^ n)] },
end,
}
/-- If `P` is a prime ideal of `R`, then `R[x]/(P)` is an integral domain. -/
lemma is_integral_domain_map_C_quotient {P : ideal R} (H : is_prime P) :
is_integral_domain (quotient (map C P : ideal (polynomial R))) :=
ring_equiv.is_integral_domain (polynomial (quotient P))
(integral_domain.to_is_integral_domain (polynomial (quotient P)))
(polynomial_quotient_equiv_quotient_polynomial P).symm
/-- If `P` is a prime ideal of `R`, then `P.R[x]` is a prime ideal of `R[x]`. -/
lemma is_prime_map_C_of_is_prime {P : ideal R} (H : is_prime P) :
is_prime (map C P : ideal (polynomial R)) :=
(quotient.is_integral_domain_iff_prime (map C P : ideal (polynomial R))).mp
(is_integral_domain_map_C_quotient H)
/-- Given any ring `R` and an ideal `I` of `polynomial R`, we get a map `R → R[x] → R[x]/I`.
If we let `R` be the image of `R` in `R[x]/I` then we also have a map `R[x] → R'[x]`.
In particular we can map `I` across this map, to get `I'` and a new map `R' → R'[x] → R'[x]/I`.
This theorem shows `I'` will not contain any non-zero constant polynomials
-/
lemma eq_zero_of_polynomial_mem_map_range (I : ideal (polynomial R))
(x : ((quotient.mk I).comp C).range)
(hx : C x ∈ (I.map (polynomial.map_ring_hom ((quotient.mk I).comp C).range_restrict))) :
x = 0 :=
begin
let i := ((quotient.mk I).comp C).range_restrict,
have hi' : (polynomial.map_ring_hom i).ker ≤ I,
{ refine λ f hf, polynomial_mem_ideal_of_coeff_mem_ideal I f (λ n, _),
rw [mem_comap, ← quotient.eq_zero_iff_mem, ← ring_hom.comp_apply],
rw [ring_hom.mem_ker, coe_map_ring_hom] at hf,
replace hf := congr_arg (λ (f : polynomial _), f.coeff n) hf,
simp only [coeff_map, coeff_zero] at hf,
rwa [subtype.ext_iff, ring_hom.coe_range_restrict] at hf },
obtain ⟨x, hx'⟩ := x,
obtain ⟨y, rfl⟩ := (ring_hom.mem_range).1 hx',
refine subtype.eq _,
simp only [ring_hom.comp_apply, quotient.eq_zero_iff_mem, subring.coe_zero, subtype.val_eq_coe],
suffices : C (i y) ∈ (I.map (polynomial.map_ring_hom i)),
{ obtain ⟨f, hf⟩ := mem_image_of_mem_map_of_surjective (polynomial.map_ring_hom i)
(polynomial.map_surjective _ (((quotient.mk I).comp C).range_restrict_surjective)) this,
refine sub_add_cancel (C y) f ▸ I.add_mem (hi' _ : (C y - f) ∈ I) hf.1,
rw [ring_hom.mem_ker, ring_hom.map_sub, hf.2, sub_eq_zero, coe_map_ring_hom, map_C] },
exact hx,
end
/-- `polynomial R` is never a field for any ring `R`. -/
lemma polynomial_not_is_field : ¬ is_field (polynomial R) :=
begin
by_contradiction hR,
by_cases hR' : ∃ (x y : R), x ≠ y,
{ haveI : nontrivial R := let ⟨x, y, hxy⟩ := hR' in nontrivial_of_ne x y hxy,
obtain ⟨p, hp⟩ := hR.mul_inv_cancel X_ne_zero,
by_cases hp0 : p = 0,
{ replace hp := congr_arg degree hp,
rw [hp0, mul_zero, degree_zero, degree_one] at hp,
contradiction },
{ have : p.degree < (X * p).degree := (mul_comm p X) ▸ degree_lt_degree_mul_X hp0,
rw [congr_arg degree hp, degree_one, nat.with_bot.lt_zero_iff, degree_eq_bot] at this,
exact hp0 this } },
{ push_neg at hR',
exact let ⟨x, y, hxy⟩ := hR.exists_pair_ne in hxy (polynomial.ext (λ n, hR' _ _)) }
end
/-- The only constant in a maximal ideal over a field is `0`. -/
lemma eq_zero_of_constant_mem_of_maximal (hR : is_field R)
(I : ideal (polynomial R)) [hI : I.is_maximal] (x : R) (hx : C x ∈ I) : x = 0 :=
begin
refine classical.by_contradiction (λ hx0, hI.ne_top ((eq_top_iff_one I).2 _)),
obtain ⟨y, hy⟩ := hR.mul_inv_cancel hx0,
convert I.smul_mem (C y) hx,
rw [smul_eq_mul, ← C.map_mul, mul_comm y x, hy, ring_hom.map_one],
end
/-- Transport an ideal of `R[X]` to an `R`-submodule of `R[X]`. -/
def of_polynomial (I : ideal (polynomial R)) : submodule R (polynomial R) :=
{ carrier := I.carrier,
zero_mem' := I.zero_mem,
add_mem' := λ _ _, I.add_mem,
smul_mem' := λ c x H, by { rw [← C_mul'], exact I.mul_mem_left _ H } }
variables {I : ideal (polynomial R)}
theorem mem_of_polynomial (x) : x ∈ I.of_polynomial ↔ x ∈ I := iff.rfl
variables (I)
/-- Given an ideal `I` of `R[X]`, make the `R`-submodule of `I`
consisting of polynomials of degree ≤ `n`. -/
def degree_le (n : with_bot ℕ) : submodule R (polynomial R) :=
degree_le R n ⊓ I.of_polynomial
/-- Given an ideal `I` of `R[X]`, make the ideal in `R` of
leading coefficients of polynomials in `I` with degree ≤ `n`. -/
def leading_coeff_nth (n : ℕ) : ideal R :=
(I.degree_le n).map $ lcoeff R n
theorem mem_leading_coeff_nth (n : ℕ) (x) :
x ∈ I.leading_coeff_nth n ↔ ∃ p ∈ I, degree p ≤ n ∧ leading_coeff p = x :=
begin
simp only [leading_coeff_nth, degree_le, submodule.mem_map, lcoeff_apply, submodule.mem_inf,
mem_degree_le],
split,
{ rintro ⟨p, ⟨hpdeg, hpI⟩, rfl⟩,
cases lt_or_eq_of_le hpdeg with hpdeg hpdeg,
{ refine ⟨0, I.zero_mem, bot_le, _⟩,
rw [leading_coeff_zero, eq_comm],
exact coeff_eq_zero_of_degree_lt hpdeg },
{ refine ⟨p, hpI, le_of_eq hpdeg, _⟩,
rw [leading_coeff, nat_degree, hpdeg], refl } },
{ rintro ⟨p, hpI, hpdeg, rfl⟩,
have : nat_degree p + (n - nat_degree p) = n,
{ exact nat.add_sub_cancel' (nat_degree_le_of_degree_le hpdeg) },
refine ⟨p * X ^ (n - nat_degree p), ⟨_, I.mul_mem_right _ hpI⟩, _⟩,
{ apply le_trans (degree_mul_le _ _) _,
apply le_trans (add_le_add (degree_le_nat_degree) (degree_X_pow_le _)) _,
rw [← with_bot.coe_add, this],
exact le_refl _ },
{ rw [leading_coeff, ← coeff_mul_X_pow p (n - nat_degree p), this] } }
end
theorem mem_leading_coeff_nth_zero (x) :
x ∈ I.leading_coeff_nth 0 ↔ C x ∈ I :=
(mem_leading_coeff_nth _ _ _).trans
⟨λ ⟨p, hpI, hpdeg, hpx⟩, by rwa [← hpx, leading_coeff,
nat.eq_zero_of_le_zero (nat_degree_le_of_degree_le hpdeg),
← eq_C_of_degree_le_zero hpdeg],
λ hx, ⟨C x, hx, degree_C_le, leading_coeff_C x⟩⟩
theorem leading_coeff_nth_mono {m n : ℕ} (H : m ≤ n) :
I.leading_coeff_nth m ≤ I.leading_coeff_nth n :=
begin
intros r hr,
simp only [set_like.mem_coe, mem_leading_coeff_nth] at hr ⊢,
rcases hr with ⟨p, hpI, hpdeg, rfl⟩,
refine ⟨p * X ^ (n - m), I.mul_mem_right _ hpI, _, leading_coeff_mul_X_pow⟩,
refine le_trans (degree_mul_le _ _) _,
refine le_trans (add_le_add hpdeg (degree_X_pow_le _)) _,
rw [← with_bot.coe_add, nat.add_sub_cancel' H],
exact le_refl _
end
/-- Given an ideal `I` in `R[X]`, make the ideal in `R` of the
leading coefficients in `I`. -/
def leading_coeff : ideal R :=
⨆ n : ℕ, I.leading_coeff_nth n
theorem mem_leading_coeff (x) :
x ∈ I.leading_coeff ↔ ∃ p ∈ I, polynomial.leading_coeff p = x :=
begin
rw [leading_coeff, submodule.mem_supr_of_directed],
simp only [mem_leading_coeff_nth],
{ split, { rintro ⟨i, p, hpI, hpdeg, rfl⟩, exact ⟨p, hpI, rfl⟩ },
rintro ⟨p, hpI, rfl⟩, exact ⟨nat_degree p, p, hpI, degree_le_nat_degree, rfl⟩ },
intros i j, exact ⟨i + j, I.leading_coeff_nth_mono (nat.le_add_right _ _),
I.leading_coeff_nth_mono (nat.le_add_left _ _)⟩
end
theorem is_fg_degree_le [is_noetherian_ring R] (n : ℕ) :
submodule.fg (I.degree_le n) :=
is_noetherian_submodule_left.1 (is_noetherian_of_fg_of_noetherian _
⟨_, degree_le_eq_span_X_pow.symm⟩) _
end ideal
namespace polynomial
@[priority 100]
instance {R : Type*} [integral_domain R] [wf_dvd_monoid R] :
wf_dvd_monoid (polynomial R) :=
{ well_founded_dvd_not_unit := begin
classical,
refine rel_hom.well_founded
⟨λ p, (if p = 0 then ⊤ else ↑p.degree, p.leading_coeff), _⟩
(prod.lex_wf (with_top.well_founded_lt $ with_bot.well_founded_lt nat.lt_wf)
_inst_5.well_founded_dvd_not_unit),
rintros a b ⟨ane0, ⟨c, ⟨not_unit_c, rfl⟩⟩⟩,
rw [polynomial.degree_mul, if_neg ane0],
split_ifs with hac,
{ rw [hac, polynomial.leading_coeff_zero],
apply prod.lex.left,
exact lt_of_le_of_ne le_top with_top.coe_ne_top },
have cne0 : c ≠ 0 := right_ne_zero_of_mul hac,
simp only [cne0, ane0, polynomial.leading_coeff_mul],
by_cases hdeg : c.degree = 0,
{ simp only [hdeg, add_zero],
refine prod.lex.right _ ⟨_, ⟨c.leading_coeff, (λ unit_c, not_unit_c _), rfl⟩⟩,
{ rwa [ne, polynomial.leading_coeff_eq_zero] },
rw [polynomial.is_unit_iff, polynomial.eq_C_of_degree_eq_zero hdeg],
use [c.leading_coeff, unit_c],
rw [polynomial.leading_coeff, polynomial.nat_degree_eq_of_degree_eq_some hdeg] },
{ apply prod.lex.left,
rw polynomial.degree_eq_nat_degree cne0 at *,
rw [with_top.coe_lt_coe, polynomial.degree_eq_nat_degree ane0,
← with_bot.coe_add, with_bot.coe_lt_coe],
exact lt_add_of_pos_right _ (nat.pos_of_ne_zero (λ h, hdeg (h.symm ▸ with_bot.coe_zero))) },
end }
end polynomial
/-- Hilbert basis theorem: a polynomial ring over a noetherian ring is a noetherian ring. -/
protected theorem polynomial.is_noetherian_ring [is_noetherian_ring R] :
is_noetherian_ring (polynomial R) :=
is_noetherian_ring_iff.2 ⟨assume I : ideal (polynomial R),
let M := well_founded.min (is_noetherian_iff_well_founded.1 (by apply_instance))
(set.range I.leading_coeff_nth) ⟨_, ⟨0, rfl⟩⟩ in
have hm : M ∈ set.range I.leading_coeff_nth := well_founded.min_mem _ _ _,
let ⟨N, HN⟩ := hm, ⟨s, hs⟩ := I.is_fg_degree_le N in
have hm2 : ∀ k, I.leading_coeff_nth k ≤ M := λ k, or.cases_on (le_or_lt k N)
(λ h, HN ▸ I.leading_coeff_nth_mono h)
(λ h x hx, classical.by_contradiction $ λ hxm,
have ¬M < I.leading_coeff_nth k, by refine well_founded.not_lt_min
(well_founded_submodule_gt _ _) _ _ _; exact ⟨k, rfl⟩,
this ⟨HN ▸ I.leading_coeff_nth_mono (le_of_lt h), λ H, hxm (H hx)⟩),
have hs2 : ∀ {x}, x ∈ I.degree_le N → x ∈ ideal.span (↑s : set (polynomial R)),
from hs ▸ λ x hx, submodule.span_induction hx (λ _ hx, ideal.subset_span hx) (ideal.zero_mem _)
(λ _ _, ideal.add_mem _) (λ c f hf, f.C_mul' c ▸ ideal.mul_mem_left _ _ hf),
⟨s, le_antisymm
(ideal.span_le.2 $ λ x hx, have x ∈ I.degree_le N, from hs ▸ submodule.subset_span hx, this.2) $
begin
have : submodule.span (polynomial R) ↑s = ideal.span ↑s, by refl,
rw this,
intros p hp, generalize hn : p.nat_degree = k,
induction k using nat.strong_induction_on with k ih generalizing p,
cases le_or_lt k N,
{ subst k, refine hs2 ⟨polynomial.mem_degree_le.2
(le_trans polynomial.degree_le_nat_degree $ with_bot.coe_le_coe.2 h), hp⟩ },
{ have hp0 : p ≠ 0,
{ rintro rfl, cases hn, exact nat.not_lt_zero _ h },
have : (0 : R) ≠ 1,
{ intro h, apply hp0, ext i, refine (mul_one _).symm.trans _,
rw [← h, mul_zero], refl },
haveI : nontrivial R := ⟨⟨0, 1, this⟩⟩,
have : p.leading_coeff ∈ I.leading_coeff_nth N,
{ rw HN, exact hm2 k ((I.mem_leading_coeff_nth _ _).2
⟨_, hp, hn ▸ polynomial.degree_le_nat_degree, rfl⟩) },
rw I.mem_leading_coeff_nth at this,
rcases this with ⟨q, hq, hdq, hlqp⟩,
have hq0 : q ≠ 0,
{ intro H, rw [← polynomial.leading_coeff_eq_zero] at H,
rw [hlqp, polynomial.leading_coeff_eq_zero] at H, exact hp0 H },
have h1 : p.degree = (q * polynomial.X ^ (k - q.nat_degree)).degree,
{ rw [polynomial.degree_mul', polynomial.degree_X_pow],
rw [polynomial.degree_eq_nat_degree hp0, polynomial.degree_eq_nat_degree hq0],
rw [← with_bot.coe_add, nat.add_sub_cancel', hn],
{ refine le_trans (polynomial.nat_degree_le_of_degree_le hdq) (le_of_lt h) },
rw [polynomial.leading_coeff_X_pow, mul_one],
exact mt polynomial.leading_coeff_eq_zero.1 hq0 },
have h2 : p.leading_coeff = (q * polynomial.X ^ (k - q.nat_degree)).leading_coeff,
{ rw [← hlqp, polynomial.leading_coeff_mul_X_pow] },
have := polynomial.degree_sub_lt h1 hp0 h2,
rw [polynomial.degree_eq_nat_degree hp0] at this,
rw ← sub_add_cancel p (q * polynomial.X ^ (k - q.nat_degree)),
refine (ideal.span ↑s).add_mem _ ((ideal.span ↑s).mul_mem_right _ _),
{ by_cases hpq : p - q * polynomial.X ^ (k - q.nat_degree) = 0,
{ rw hpq, exact ideal.zero_mem _ },
refine ih _ _ (I.sub_mem hp (I.mul_mem_right _ hq)) rfl,
rwa [polynomial.degree_eq_nat_degree hpq, with_bot.coe_lt_coe, hn] at this },
exact hs2 ⟨polynomial.mem_degree_le.2 hdq, hq⟩ }
end⟩⟩
attribute [instance] polynomial.is_noetherian_ring
namespace polynomial
theorem exists_irreducible_of_degree_pos {R : Type u} [integral_domain R] [wf_dvd_monoid R]
{f : polynomial R} (hf : 0 < f.degree) : ∃ g, irreducible g ∧ g ∣ f :=
wf_dvd_monoid.exists_irreducible_factor
(λ huf, ne_of_gt hf $ degree_eq_zero_of_is_unit huf)
(λ hf0, not_lt_of_lt hf $ hf0.symm ▸ (@degree_zero R _).symm ▸ with_bot.bot_lt_coe _)
theorem exists_irreducible_of_nat_degree_pos {R : Type u} [integral_domain R] [wf_dvd_monoid R]
{f : polynomial R} (hf : 0 < f.nat_degree) : ∃ g, irreducible g ∧ g ∣ f :=
exists_irreducible_of_degree_pos $ by { contrapose! hf, exact nat_degree_le_of_degree_le hf }
theorem exists_irreducible_of_nat_degree_ne_zero {R : Type u} [integral_domain R] [wf_dvd_monoid R]
{f : polynomial R} (hf : f.nat_degree ≠ 0) : ∃ g, irreducible g ∧ g ∣ f :=
exists_irreducible_of_nat_degree_pos $ nat.pos_of_ne_zero hf
lemma linear_independent_powers_iff_eval₂
(f : M →ₗ[R] M) (v : M) :
linear_independent R (λ n : ℕ, (f ^ n) v)
↔ ∀ (p : polynomial R), aeval f p v = 0 → p = 0 :=
begin
rw linear_independent_iff,
simp only [finsupp.total_apply, aeval_endomorphism],
refl
end
lemma disjoint_ker_aeval_of_coprime
(f : M →ₗ[R] M) {p q : polynomial R} (hpq : is_coprime p q) :
disjoint (aeval f p).ker (aeval f q).ker :=
begin
intros v hv,
rcases hpq with ⟨p', q', hpq'⟩,
simpa [linear_map.mem_ker.1 (submodule.mem_inf.1 hv).1,
linear_map.mem_ker.1 (submodule.mem_inf.1 hv).2]
using congr_arg (λ p : polynomial R, aeval f p v) hpq'.symm,
end
lemma sup_aeval_range_eq_top_of_coprime
(f : M →ₗ[R] M) {p q : polynomial R} (hpq : is_coprime p q) :
(aeval f p).range ⊔ (aeval f q).range = ⊤ :=
begin
rw eq_top_iff,
intros v hv,
rw submodule.mem_sup,
rcases hpq with ⟨p', q', hpq'⟩,
use aeval f (p * p') v,
use linear_map.mem_range.2 ⟨aeval f p' v, by simp only [linear_map.mul_apply, aeval_mul]⟩,
use aeval f (q * q') v,
use linear_map.mem_range.2 ⟨aeval f q' v, by simp only [linear_map.mul_apply, aeval_mul]⟩,
simpa only [mul_comm p p', mul_comm q q', aeval_one, aeval_add]
using congr_arg (λ p : polynomial R, aeval f p v) hpq'
end
lemma sup_ker_aeval_le_ker_aeval_mul {f : M →ₗ[R] M} {p q : polynomial R} :
(aeval f p).ker ⊔ (aeval f q).ker ≤ (aeval f (p * q)).ker :=
begin
intros v hv,
rcases submodule.mem_sup.1 hv with ⟨x, hx, y, hy, hxy⟩,
have h_eval_x : aeval f (p * q) x = 0,
{ rw [mul_comm, aeval_mul, linear_map.mul_apply, linear_map.mem_ker.1 hx, linear_map.map_zero] },
have h_eval_y : aeval f (p * q) y = 0,
{ rw [aeval_mul, linear_map.mul_apply, linear_map.mem_ker.1 hy, linear_map.map_zero] },
rw [linear_map.mem_ker, ←hxy, linear_map.map_add, h_eval_x, h_eval_y, add_zero],
end
lemma sup_ker_aeval_eq_ker_aeval_mul_of_coprime
(f : M →ₗ[R] M) {p q : polynomial R} (hpq : is_coprime p q) :
(aeval f p).ker ⊔ (aeval f q).ker = (aeval f (p * q)).ker :=
begin
apply le_antisymm sup_ker_aeval_le_ker_aeval_mul,
intros v hv,
rw submodule.mem_sup,
rcases hpq with ⟨p', q', hpq'⟩,
have h_eval₂_qpp' := calc
aeval f (q * (p * p')) v = aeval f (p' * (p * q)) v :
by rw [mul_comm, mul_assoc, mul_comm, mul_assoc, mul_comm q p]
... = 0 :
by rw [aeval_mul, linear_map.mul_apply, linear_map.mem_ker.1 hv, linear_map.map_zero],
have h_eval₂_pqq' := calc
aeval f (p * (q * q')) v = aeval f (q' * (p * q)) v :
by rw [←mul_assoc, mul_comm]
... = 0 :
by rw [aeval_mul, linear_map.mul_apply, linear_map.mem_ker.1 hv, linear_map.map_zero],
rw aeval_mul at h_eval₂_qpp' h_eval₂_pqq',
refine ⟨aeval f (q * q') v, linear_map.mem_ker.1 h_eval₂_pqq',
aeval f (p * p') v, linear_map.mem_ker.1 h_eval₂_qpp', _⟩,
rw [add_comm, mul_comm p p', mul_comm q q'],
simpa using congr_arg (λ p : polynomial R, aeval f p v) hpq'
end
end polynomial
namespace mv_polynomial
lemma is_noetherian_ring_fin_0 [is_noetherian_ring R] :
is_noetherian_ring (mv_polynomial (fin 0) R) :=
is_noetherian_ring_of_ring_equiv R
((mv_polynomial.pempty_ring_equiv R).symm.trans
(rename_equiv R fin_zero_equiv'.symm).to_ring_equiv)
theorem is_noetherian_ring_fin [is_noetherian_ring R] :
∀ {n : ℕ}, is_noetherian_ring (mv_polynomial (fin n) R)
| 0 := is_noetherian_ring_fin_0
| (n+1) :=
@is_noetherian_ring_of_ring_equiv (polynomial (mv_polynomial (fin n) R)) _ _ _
(mv_polynomial.fin_succ_equiv _ n).to_ring_equiv.symm
(@polynomial.is_noetherian_ring (mv_polynomial (fin n) R) _ (is_noetherian_ring_fin))
/-- The multivariate polynomial ring in finitely many variables over a noetherian ring
is itself a noetherian ring. -/
instance is_noetherian_ring [fintype σ] [is_noetherian_ring R] :
is_noetherian_ring (mv_polynomial σ R) :=
@is_noetherian_ring_of_ring_equiv (mv_polynomial (fin (fintype.card σ)) R) _ _ _
(rename_equiv R (fintype.equiv_fin σ).symm).to_ring_equiv is_noetherian_ring_fin
lemma is_integral_domain_fin_zero (R : Type u) [comm_ring R] (hR : is_integral_domain R) :
is_integral_domain (mv_polynomial (fin 0) R) :=
ring_equiv.is_integral_domain R hR
((rename_equiv R fin_zero_equiv').to_ring_equiv.trans (mv_polynomial.pempty_ring_equiv R))
/-- Auxilliary lemma:
Multivariate polynomials over an integral domain
with variables indexed by `fin n` form an integral domain.
This fact is proven inductively,
and then used to prove the general case without any finiteness hypotheses.
See `mv_polynomial.integral_domain` for the general case. -/
lemma is_integral_domain_fin (R : Type u) [comm_ring R] (hR : is_integral_domain R) :
∀ (n : ℕ), is_integral_domain (mv_polynomial (fin n) R)
| 0 := is_integral_domain_fin_zero R hR
| (n+1) :=
ring_equiv.is_integral_domain
(polynomial (mv_polynomial (fin n) R))
(is_integral_domain_fin n).polynomial
(mv_polynomial.fin_succ_equiv _ n).to_ring_equiv
lemma is_integral_domain_fintype (R : Type u) (σ : Type v) [comm_ring R] [fintype σ]
(hR : is_integral_domain R) : is_integral_domain (mv_polynomial σ R) :=
@ring_equiv.is_integral_domain _ (mv_polynomial (fin $ fintype.card σ) R) _ _
(mv_polynomial.is_integral_domain_fin _ hR _)
(rename_equiv R (fintype.equiv_fin σ)).to_ring_equiv
/-- Auxilliary definition:
Multivariate polynomials in finitely many variables over an integral domain form an integral domain.
This fact is proven by transport of structure from the `mv_polynomial.integral_domain_fin`,
and then used to prove the general case without finiteness hypotheses.
See `mv_polynomial.integral_domain` for the general case. -/
def integral_domain_fintype (R : Type u) (σ : Type v) [integral_domain R] [fintype σ] :
integral_domain (mv_polynomial σ R) :=
@is_integral_domain.to_integral_domain _ _ $ mv_polynomial.is_integral_domain_fintype R σ $
integral_domain.to_is_integral_domain R
protected theorem eq_zero_or_eq_zero_of_mul_eq_zero {R : Type u} [integral_domain R] {σ : Type v}
(p q : mv_polynomial σ R) (h : p * q = 0) : p = 0 ∨ q = 0 :=
begin
obtain ⟨s, p, rfl⟩ := exists_finset_rename p,
obtain ⟨t, q, rfl⟩ := exists_finset_rename q,
have :
rename (subtype.map id (finset.subset_union_left s t) : {x // x ∈ s} → {x // x ∈ s ∪ t}) p *
rename (subtype.map id (finset.subset_union_right s t) : {x // x ∈ t} → {x // x ∈ s ∪ t}) q = 0,
{ apply rename_injective _ subtype.val_injective, simpa using h },
letI := mv_polynomial.integral_domain_fintype R {x // x ∈ (s ∪ t)},
rw mul_eq_zero at this,
cases this; [left, right],
all_goals { simpa using congr_arg (rename subtype.val) this }
end
/-- The multivariate polynomial ring over an integral domain is an integral domain. -/
instance {R : Type u} {σ : Type v} [integral_domain R] :
integral_domain (mv_polynomial σ R) :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := mv_polynomial.eq_zero_or_eq_zero_of_mul_eq_zero,
exists_pair_ne := ⟨0, 1, λ H,
begin
have : eval₂ (ring_hom.id _) (λ s, (0:R)) (0 : mv_polynomial σ R) =
eval₂ (ring_hom.id _) (λ s, (0:R)) (1 : mv_polynomial σ R),
{ congr, exact H },
simpa,
end⟩,
.. (by apply_instance : comm_ring (mv_polynomial σ R)) }
lemma map_mv_polynomial_eq_eval₂ {S : Type*} [comm_ring S] [fintype σ]
(ϕ : mv_polynomial σ R →+* S) (p : mv_polynomial σ R) :
ϕ p = mv_polynomial.eval₂ (ϕ.comp mv_polynomial.C) (λ s, ϕ (mv_polynomial.X s)) p :=
begin
refine trans (congr_arg ϕ (mv_polynomial.as_sum p)) _,
rw [mv_polynomial.eval₂_eq', ϕ.map_sum],
congr,
ext,
simp only [monomial_eq, ϕ.map_pow, ϕ.map_prod, ϕ.comp_apply, ϕ.map_mul, finsupp.prod_pow],
end
lemma quotient_map_C_eq_zero {I : ideal R} {i : R} (hi : i ∈ I) :
(ideal.quotient.mk (ideal.map C I : ideal (mv_polynomial σ R))).comp C i = 0 :=
begin
simp only [function.comp_app, ring_hom.coe_comp, ideal.quotient.eq_zero_iff_mem],
exact ideal.mem_map_of_mem hi
end
/-- If every coefficient of a polynomial is in an ideal `I`, then so is the polynomial itself,
multivariate version. -/
lemma mem_ideal_of_coeff_mem_ideal (I : ideal (mv_polynomial σ R)) (p : mv_polynomial σ R)
(hcoe : ∀ (m : σ →₀ ℕ), p.coeff m ∈ I.comap C) : p ∈ I :=
begin
rw as_sum p,
suffices : ∀ m ∈ p.support, monomial m (mv_polynomial.coeff m p) ∈ I,
{ exact submodule.sum_mem I this },
intros m hm,
rw [← mul_one (coeff m p), ← C_mul_monomial],
suffices : C (coeff m p) ∈ I,
{ exact ideal.mul_mem_right I (monomial m 1) this },
simpa [ideal.mem_comap] using hcoe m
end
/-- The push-forward of an ideal `I` of `R` to `mv_polynomial σ R` via inclusion
is exactly the set of polynomials whose coefficients are in `I` -/
theorem mem_map_C_iff {I : ideal R} {f : mv_polynomial σ R} :
f ∈ (ideal.map C I : ideal (mv_polynomial σ R)) ↔ ∀ (m : σ →₀ ℕ), f.coeff m ∈ I :=
begin
split,
{ intros hf,
apply submodule.span_induction hf,
{ intros f hf n,
cases (set.mem_image _ _ _).mp hf with x hx,
rw [← hx.right, coeff_C],
by_cases (n = 0),
{ simpa [h] using hx.left },
{ simp [ne.symm h] } },
{ simp },
{ exact λ f g hf hg n, by simp [I.add_mem (hf n) (hg n)] },
{ refine λ f g hg n, _,
rw [smul_eq_mul, coeff_mul],
exact I.sum_mem (λ c hc, I.smul_mem (f.coeff c.fst) (hg c.snd)) } },
{ intros hf,
rw as_sum f,
suffices : ∀ m ∈ f.support, monomial m (coeff m f) ∈
(ideal.map C I : ideal (mv_polynomial σ R)),
{ exact submodule.sum_mem _ this },
intros m hm,
rw [← mul_one (coeff m f), ← C_mul_monomial],
suffices : C (coeff m f) ∈ (ideal.map C I : ideal (mv_polynomial σ R)),
{ exact ideal.mul_mem_right _ _ this },
apply ideal.mem_map_of_mem _,
exact hf m }
end
lemma eval₂_C_mk_eq_zero {I : ideal R} {a : mv_polynomial σ R}
(ha : a ∈ (ideal.map C I : ideal (mv_polynomial σ R))) :
eval₂_hom (C.comp (ideal.quotient.mk I)) X a = 0 :=
begin
rw as_sum a,
rw [coe_eval₂_hom, eval₂_sum],
refine finset.sum_eq_zero (λ n hn, _),
simp only [eval₂_monomial, function.comp_app, ring_hom.coe_comp],
refine mul_eq_zero_of_left _ _,
suffices : coeff n a ∈ I,
{ rw [← @ideal.mk_ker R _ I, ring_hom.mem_ker] at this,
simp only [this, C_0] },
exact mem_map_C_iff.1 ha n
end
/-- If `I` is an ideal of `R`, then the ring `mv_polynomial σ I.quotient` is isomorphic as an
`R`-algebra to the quotient of `mv_polynomial σ R` by the ideal generated by `I`. -/
def quotient_equiv_quotient_mv_polynomial (I : ideal R) :
mv_polynomial σ I.quotient ≃ₐ[R] (ideal.map C I : ideal (mv_polynomial σ R)).quotient :=
{ to_fun := eval₂_hom (ideal.quotient.lift I ((ideal.quotient.mk (ideal.map C I : ideal
(mv_polynomial σ R))).comp C) (λ i hi, quotient_map_C_eq_zero hi))
(λ i, ideal.quotient.mk (ideal.map C I : ideal (mv_polynomial σ R)) (X i)),
inv_fun := ideal.quotient.lift (ideal.map C I : ideal (mv_polynomial σ R))
(eval₂_hom (C.comp (ideal.quotient.mk I)) X) (λ a ha, eval₂_C_mk_eq_zero ha),
map_mul' := ring_hom.map_mul _,
map_add' := ring_hom.map_add _,
left_inv := begin
intro f,
apply induction_on f,
{ rintro ⟨r⟩,
rw [coe_eval₂_hom, eval₂_C],
simp only [eval₂_hom_eq_bind₂, submodule.quotient.quot_mk_eq_mk, ideal.quotient.lift_mk,
ideal.quotient.mk_eq_mk, bind₂_C_right, ring_hom.coe_comp] },
{ simp_intros p q hp hq only [ring_hom.map_add, mv_polynomial.coe_eval₂_hom, coe_eval₂_hom,
mv_polynomial.eval₂_add, mv_polynomial.eval₂_hom_eq_bind₂, eval₂_hom_eq_bind₂],
rw [hp, hq] },
{ simp_intros p i hp only [eval₂_hom_eq_bind₂, coe_eval₂_hom],
simp only [hp, eval₂_hom_eq_bind₂, coe_eval₂_hom, ideal.quotient.lift_mk, bind₂_X_right,
eval₂_mul, ring_hom.map_mul, eval₂_X] }
end,
right_inv := begin
rintro ⟨f⟩,
apply induction_on f,
{ intros r,
simp only [submodule.quotient.quot_mk_eq_mk, ideal.quotient.lift_mk, ideal.quotient.mk_eq_mk,
ring_hom.coe_comp, eval₂_hom_C] },
{ simp_intros p q hp hq only [eval₂_hom_eq_bind₂, submodule.quotient.quot_mk_eq_mk, eval₂_add,
ring_hom.map_add, coe_eval₂_hom, ideal.quotient.lift_mk, ideal.quotient.mk_eq_mk],
rw [hp, hq] },
{ simp_intros p i hp only [eval₂_hom_eq_bind₂, submodule.quotient.quot_mk_eq_mk, coe_eval₂_hom,
ideal.quotient.lift_mk, ideal.quotient.mk_eq_mk, bind₂_X_right, eval₂_mul, ring_hom.map_mul,
eval₂_X],
simp only [hp] }
end,
commutes' := λ r, eval₂_hom_C _ _ (ideal.quotient.mk I r) }
end mv_polynomial
namespace polynomial
open unique_factorization_monoid
variables {D : Type u} [integral_domain D] [unique_factorization_monoid D]
@[priority 100]
instance unique_factorization_monoid : unique_factorization_monoid (polynomial D) :=
begin
haveI := arbitrary (normalization_monoid D),
haveI := to_gcd_monoid D,
exact ufm_of_gcd_of_wf_dvd_monoid
end
end polynomial
|
# Music Machine Learning - Gaussian Mixture Models
### Author: Philippe Esling ([email protected])
In this course we will cover
1. Unsupervised learning and [clustering](#clustering).
2. Motivating the need for [latent variable](#latent) models.
2. Approaching the problem naïvely with the [k-Means](#kmeans) algorithm.
We begin with the standard imports
```python
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
import numpy as np
from helper_plot import hdr_plot_style
hdr_plot_style()
```
## Defining mixture models
We have seen previously how to fit a Gaussian, so we could apply the same reasoning and try to fit a single multivariate Gaussian to our dataset
$$
\begin{align}
p(\mathbf{x} \vert \theta) &= \mathcal{N}\left(\mathbf{x}\vert \mu, \Sigma\right) \\
\theta &= \{\mu, \Sigma\}
\end{align}
$$
However, we can quickly see that our data contains several groups, and the single Gaussian seems largely not adapted.
```python
from helper_plot import fit_multivariate_gaussian
from sklearn.datasets.samples_generator import make_blobs
X, y_true = make_blobs(n_samples=400, centers=4, cluster_std=0.60, random_state=0)
X = X[:, ::-1];
fit_multivariate_gaussian(X);
```
Instead of using a single Gaussian, we could use several Gaussians, for instance, if we use three Gaussians, we have the following model
$$
\begin{align}
p(\mathbf{x} \vert \theta) &= \pi_{1} \mathcal{N}\left(\mathbf{x}\vert \mu_{1}, \Sigma_{1}\right) \\
&+ \pi_{2} \mathcal{N}\left(\mathbf{x}\vert \mu_{2}, \Sigma_{2}\right)\\
&+ \pi_{3} \mathcal{N}\left(\mathbf{x}\vert \mu_{3}, \Sigma_{3}\right)\\
&+ \pi_{4} \mathcal{N}\left(\mathbf{x}\vert \mu_{4}, \Sigma_{4}\right)\\
\end{align}
$$
So now the parameters are both the parameters of each Gaussian, along with the probabilities of belonging to each Gaussian
$$
\theta = \{\pi_{1}, \pi_{2}, \pi_{3}, \pi_{4}, \mu_{1}, \mu_{2}, \mu_{3}, \mu_{4}, \Sigma_{1}, \Sigma_{2}, \Sigma_{3}, \Sigma_{4}\}
$$
Note that if we solve this model, called a _Gaussian Mixture Model_ (GMM), we can find the probabilities of each point belonging to one of the corresponding cluster
```python
from helper_plot import fit_gaussian_mixture
fit_gaussian_mixture(X);
```
Compared to a single Gaussian, a GMM has obviously a higher flexibility, but also a larger number of parameters (which makes it harder to optimize). Generally speaking, the full distribution of a GMM is defined as follows
$$
p(\mathbf{x} \vert \theta) = \sum_{c} \pi_{c} \mathcal{N}\left(\mathbf{x}\vert \mu_{c}, \Sigma_{c}\right)
$$
We can see that any *mixture model*, is defined through two main components.
**Base distribution**: $p(\mathbf{x}\vert z=c, \theta) = \mathcal{N}\left(\mathbf{x}\vert \mu_{c}, \Sigma_{c}\right)$
**Mixing probabilities** $p(z=c \vert \theta) = \pi_{c}$
### Optimizing this model
If we want to optimize our probabilistic model, we have to solve a typical *maximum likelihood* problem (considering that points $x_{i}$ are independent)
$$
\underset{\theta}{\text{max. }} p(x \vert \theta) = \prod_{i=1}^{N} p(x_{i} \vert \theta)
$$
In the case of a GMM, we could try to replace our full model inside this problem, which leads to a rather complicated formulation.
$$
\underset{\theta}{\text{max. }} \prod_{i=1}^{N} \sum_{c} \pi_{c} \mathcal{N}\left(x_{i}\vert \mu_{c}, \Sigma_{c}\right)
$$
Furthermore, we have to include the following constraints
$$
\sum_{c} \pi_{c} = 1; \pi_{c} \geq 0, \forall c \\
\Sigma_{c} \succcurlyeq 0
$$
Although, we could rely on optimization, we need to incorporate hard to follow constraints, which leads to slow and unstable training. Here, the reasoning is way easier if we introduce a latent variable
### Introducing a latent variable
We introduce the latent variable $z$, which _explains_ a given datapoint. In our case, this variable tells us _from which group_ the point was generated.
In our case, we can simply say that our latent variable corresponds to the mixing probabilities
$$
\begin{align}
p(z=c\vert\theta) &= \pi_{c} \\
p(\mathbf{x}\vert z=c,\theta) &= \mathcal{N}\left(\mathbf{x}\vert \mu_{c}, \Sigma_{c}\right)
\end{align}
$$
Therefore, our original model can be retrieved as a marginalization of the latent variable, as
$$
p(\mathbf{x} \vert \theta) = \sum_{c} p(\mathbf{x} \vert z=c,\theta) p(z=c\vert\theta)
$$
#### Estimating parameters
Now in order to optimize the parameters, we should need to optimize both the $\theta$ and $z$ variables. If we knew the cluster belonging (latent) variable $z$, then the optimization would be easy, since we know that
$$
p(\mathbf{x}\vert z=c, \theta) = \mathcal{N}\left(\mathbf{x}\vert \mu_{c}, \Sigma_{c}\right)
$$
And computing the parameters of this Gaussian is pretty easy, as we simply need to update the values depending on the corresponding points (weighted mean)
$$
\mu_{c} = \frac{\sum_{i} p(z=i\vert \mathbf{x}_{i}, \theta) \bx_{i}}{\sum_{i} p(z=i\vert \mathbf{x}_{i}, \theta)}
$$
Now in order to optimize the source variable $z$, the optimization would be easy if we knew the parameters as we have
$$
p(z = c \vert \mathbf{x}, \theta) = \frac{p(\mathbf{x} \vert z = c, \theta) p(z = c \vert \theta)}{Z}
$$
## Expectation-Maximization
As we have seen in the slides, a natural alternating solution emerges in the form of the **Expectation-Maximization** algorithm
1. Start with a random set of Gaussians parameters $\theta^{(0)}$
2. Repeat until convergence
1. *E-step*: for each point, find weights encoding the probability of membership in each cluster by computing $p(z=c \vert \mathbf{x}_{i}, \theta^{(t)})$
2. *M-step*: for each cluster, update its location, normalization, and shape based on *all* data points, making use of the weights, hence updating Gaussian parameters $\theta^{(t+1)}$
The result of this is that each cluster is associated not with a hard-edged sphere, but with a smooth Gaussian model.
### Deriving the E-Step
As discussed in the slides, we want to minimize the gap between our lower bound and the true distribution, which can be written as
$$
\mathcal{D} = \log p(\mathbf{x} \vert \theta) - \mathcal{L}(\theta\vert q)
$$
Developing this expression, we find out that
$$
\mathcal{D} = \sum_{i=1}^{N} \mathcal{D}_{KL} \left[ q(z_{i}) \Vert p(z_{i} \vert \mathbf{x}_{i}, \theta) \right]
$$
Hence, we need to minimize the KL divergence, which amounts to setting the approximate function as the posterior distribution
$$
q(z_{i}) = p(z_{i} \vert \mathbf{x}_{i}, \theta)
$$
### Deriving the M-step
Based on the approximation that we want to maximize
$$
\mathcal{L}(\theta, q) = \sum_{i=1}^{N} \sum_{c} q(t_{i}=c) \log\frac{p(x_{i}, t_{i}=c \vert \theta)}{q(t_{i}=c)}
$$
We have seen that expending this maximization led to
$$
\mathcal{L}(\theta, q) = \mathbb{E}_{q} \log p(x,t\vert \theta) + const
$$
Note that the fonction is usually concave, which makes it easy to optimize
## Using GMM with `scikit-learn`
By using the EM algorithm, a GMM will find a mixture of multi-dimensional Gaussian probability distributions that best model any input dataset, which can elegantly solve our clustering problem.
```python
from sklearn.mixture import GaussianMixture
gmm = GaussianMixture(n_components=4).fit(X)
labels = gmm.predict(X)
plt.figure(figsize=(10,8))
plt.scatter(X[:, 0], X[:, 1], c=labels, s=40, cmap='magma', edgecolor='w');
```
But because GMM contains a probabilistic model under the hood, it is also possible to find probabilistic cluster assignments—in Scikit-Learn this is done using the ``predict_proba`` method.
This returns a matrix of size ``[n_samples, n_clusters]`` which measures the probability that any point belongs to the given cluster:
```python
probs = gmm.predict_proba(X)
print(probs[:5].round(3))
```
We can visualize this uncertainty by, for example, making the size of each point proportional to the certainty of its prediction; looking at the following figure, we can see that it is precisely the points at the boundaries between clusters that reflect this uncertainty of cluster assignment:
```python
size = 100 * (probs.max(1) ** 2) # square emphasizes differences
plt.figure(figsize=(10,8))
plt.scatter(X[:, 0], X[:, 1], c=labels, cmap='magma', s=size, edgecolor='w');
```
With this in place, we can take a look at what the four-component GMM gives us for our initial data:
```python
from helper_plot import plot_gmm
gmm = GaussianMixture(n_components=4, random_state=42)
plot_gmm(gmm, X)
```
Similarly, we can use the GMM approach to fit our stretched dataset. Here, we already see that allowing for a full covariance the model will fit even very oblong, stretched-out clusters (as opposed to the *hard* version of kMeans)
```python
rng = np.random.RandomState(13)
X_stretched = np.dot(X, rng.randn(2, 2))
gmm = GaussianMixture(n_components=4, covariance_type='full', random_state=42)
plot_gmm(gmm, X_stretched)
```
This makes clear that GMM addresses the two main practical issues with *k*-means encountered before.
## Implementing EM for GMM
Now, we will derive and implement formulas for the GMM ourselves. To do so, we will use samples from a Gaussian mixture model with unknown mean, variance, and priors. We will also have to derive both the E-step and M-step for our selected model.
### Reminder
We recall that the EM algorithm is a coordinate descent optimization of a lower bound
$$
\underset{\theta}{\text{argmax }} \mathcal{L}(\theta, q) = \underset{\theta}{\text{argmax }} \int q(\mathbf{z}) \log\frac{p(\mathbf{x}, \mathbf{z} \vert \theta)}{q(\mathbf{z})}d\mathbf{z}
$$
**E-step**: In the E-step, we use a lower-bounding approximation to find the latent variables $\mathbf{z}$, while using the current parameters estimate $\theta^{(t)}$
$$
\underset{q}{\text{argmax }} \mathcal{L}(\theta, q) \Leftrightarrow \underset{q}{\text{argmin }} \mathcal{D}_{KL} \left[q(\mathbf{z}) \Vert p(\mathbf{z}\vert\mathbf{x}, \theta) \right]
$$
We have seen that the optimal solution is $q(\mathbf{z}) = p(\mathbf{z}\vert\mathbf{x}, \theta)$, which means that we can safely use the conditional probability for this step.
**M-step**: In the M-step, we use our updated knowledge on the latent variable to update the parameters. Hence, we have to optimize
$$
\underset{\theta}{\text{argmax }} \mathcal{L}(\theta, q) \Leftrightarrow \underset{\theta}{\text{argmax }} \mathbb{E}_{q(\mathbf{z})}\log p(\mathbf{x},\mathbf{z} | \theta)
$$
For our GMM model, $\theta$ is a set of parameters that consists of mean vectors $\mu_c$, covariance matrices $\Sigma_c$ and priors $\pi_c$ for each component. The *latent variable* $z$ are indices of components to which each data point is assigned, i.e. $z_i$ is the cluster index for object $\mathbf{x}_i$. Therefore, the joint distribution of our GMM can be written as follows
$$\log p(\mathbf{z}, X \mid \theta) = \sum\limits_{i=1}^N \log p(z_i, x_i \mid \theta) = \sum\limits_{i=1}^N \sum\limits_{c=1}^C q(z_i = c) \log \left (\pi_c \, \mathcal{N}(x_i \mid \mu_c, \Sigma_c)\right)
$$
where $\mathcal{N}(x_i \mid \mu_c, \Sigma_c) = \frac{1}{\sqrt{(2\pi)^n|\boldsymbol\Sigma_c|}}
\exp\left(-\frac{1}{2}({x}-{\mu_c})^T{\boldsymbol\Sigma_c}^{-1}({x}-{\mu_c})
\right)$ is the probability density function (pdf) of the normal distribution.
### E-step
In this step we need to estimate the posterior distribution over the latent variables with fixed values of parameters: $q_i(z_i) = p(z_i \mid \mathbf{x}_i, \theta)$. We assume that $z_i$ equals to the cluster index of the true component of the $\mathbf{x}_i$ object. To do so we need to compute $\pi_{ic} = p(z_i = c \mid \mathbf{x}_i, \theta)$. Note that $\sum\limits_{c=1}^C\pi_{ic}=1$.
***
**Exercise**
1. Implement E-step for GMM using template below.
***
```python
from scipy.stats import multivariate_normal
def E_step(X, pi, mu, sigma):
"""
Performs E-step on GMM model
Each input is numpy array:
X: (N x d), data points
pi: (C), mixture component weights
mu: (C x d), mixture component means
sigma: (C x d x d), mixture component covariance matrices
Returns:
gamma: (N x C), probabilities of clusters for objects
"""
N = X.shape[0] # number of objects
C = pi.shape[0] # number of clusters
d = mu.shape[1] # dimension of each object
pi_update = np.zeros((N, C)) # distribution q(T)
######################
# YOUR CODE GOES HERE
######################
return pi_update
```
```python
pi0 = np.random.randn(4, X.shape[0])
mu0 = np.random.randn(4, 2)
sigma0 = np.zeros((4, 2, 2))
for i in range(4):
sigma0[i] = np.eye(2, 2)
pi = E_step(X, pi0, mu0, sigma0)
```
### M-step
In M-step we need to maximize $\mathbb{E}_{q(T)}\log p(X,T | \theta)$ with respect to $\theta$. In our model this means that we need to find optimal values of $\pi$, $\mu$, $\Sigma$. To do so, you need to compute the derivatives and
set them to zero. You should start by deriving formulas for $\mu$ as it is the easiest part. Then move on to $\Sigma$. Here it is crucial to optimize function w.r.t. to $\Lambda = \Sigma^{-1}$ and then inverse obtained result. Finaly, to compute $\pi$, you will need <a href="https://www3.nd.edu/~jstiver/FIN360/Constrained%20Optimization.pdf">Lagrange Multipliers technique</a> to satisfy constraint $\sum\limits_{i=1}^{n}\pi_i = 1$.
<br>
<b>Important note:</b> You will need to compute derivatives of scalars with respect to matrices. To refresh this technique from previous courses, see <a href="https://en.wikipedia.org/wiki/Matrix_calculus"> wiki article</a> about it . Main formulas of matrix derivatives can be found in <a href="http://www2.imm.dtu.dk/pubdb/views/edoc_download.php/3274/pdf/imm3274.pdf">Chapter 2 of The Matrix Cookbook</a>. For example, there you may find that $\frac{\partial}{\partial A}\log |A| = A^{-T}$.
<b>Task 2:</b> Implement M-step for GMM using template below.
```python
def M_step(X, pi_update):
"""
Performs M-step on GMM model
Each input is numpy array:
X: (N x d), data points
gamma: (N x C), distribution q(T)
Returns:
pi: (C)
mu: (C x d)
sigma: (C x d x d)
"""
N = X.shape[0] # number of objects
C = pi_update.shape[1] # number of clusters
d = X.shape[1] # dimension of each object
######################
# YOUR CODE GOES HERE
######################
return pi, mu, sigma
```
```python
pi_update = E_step(X, pi0, mu0, sigma0)
pi, mu, sigma = M_step(X, pi_update)
```
### Loss function
Finally, we need some function to track convergence. We will use variational lower bound $\mathcal{L}$ for this purpose. We will stop our EM iterations when $\mathcal{L}$ will saturate. Usually, you will need only about 10-20 iterations to converge. It is also useful to check that this function never decreases during training. If it does, you have a bug in your code.
<b>Task 3:</b> Implement a function that will compute $\mathcal{L}$ using template below.
$$\mathcal{L} = \sum_{i=1}^{N} \sum_{c=1}^{C} q(t_i =c) (\log \pi_c + \log f_{\!\mathcal{N}}(x_i \mid \mu_c, \Sigma_c)) - \sum_{i=1}^{N} \sum_{c=1}^{K} q(t_i =c) \log q(t_i =c)$$
```python
def compute_vlb(X, pi, mu, sigma, pi_update):
"""
Each input is numpy array:
X: (N x d), data points
gamma: (N x C), distribution q(T)
pi: (C)
mu: (C x d)
sigma: (C x d x d)
Returns value of variational lower bound
"""
N = X.shape[0] # number of objects
C = pi_update.shape[1] # number of clusters
d = X.shape[1] # dimension of each object
######################
# YOUR CODE GOES HERE
######################
return loss
```
```python
pi, mu, sigma = pi0, mu0, sigma0
pi_update = E_step(X, pi, mu, sigma)
pi, mu, sigma = M_step(X, pi_update)
loss = compute_vlb(X, pi, mu, sigma, pi_update)
```
### Bringing it all together
Now that we have E step, M step and VLB, we can implement the training loop. We will initialize values of $\pi$, $\mu$ and $\Sigma$ to some random numbers, train until $\mathcal{L}$ stops changing, and return the resulting points. We also know that the EM algorithm converges to local optima. To find a better local optima, we will restart the algorithm multiple times from different (random) starting positions. Each training trial should stop either when maximum number of iterations is reached or when relative improvement is smaller than given tolerance ($|\frac{\mathcal{L}_i-\mathcal{L}_{i-1}}{\mathcal{L}_{i-1}}| \le \text{rtol}$).
Remember, that initial (random) values of $\pi$ that you generate must be non-negative and sum up to 1. Also, $\Sigma$ matrices must be symmetric and positive semi-definite. If you don't know how to generate those matrices, you can use $\Sigma=I$ as initialization.
You will also sometimes get numerical errors because of component collapsing. The easiest way to deal with this problems is to restart the procedure.
<b>Task 4:</b> Implement training procedure
```python
import math
def train_EM(X, C, rtol=1e-3, max_iter=100, restarts=10):
'''
Starts with random initialization *restarts* times
Runs optimization until saturation with *rtol* reached
or *max_iter* iterations were made.
X: (N, d), data points
C: int, number of clusters
'''
N = X.shape[0] # number of objects
d = X.shape[1] # dimension of each object
best_loss = None
best_pi = None
best_mu = None
best_sigma = None
for _ in range(restarts):
try:
######################
# YOUR CODE GOES HERE
######################
except np.linalg.LinAlgError:
print("Singular matrix: components collapsed")
pass
return best_loss, best_pi, best_mu, best_sigma
```
```python
best_loss, best_pi, best_mu, best_sigma = train_EM(X, 4)
```
If you implemented all the steps correctly, your algorithm should converge in about 20 iterations. Let's plot the clusters to see it. We will assign a cluster label as the most probable cluster index. This can be found using a matrix $\gamma$ computed on last E-step.
```python
gamma = E_step(X, best_pi, best_mu, best_sigma)
labels = gamma.argmax(axis=1)
colors = np.array([(31, 119, 180), (255, 127, 14), (44, 160, 44), (50, 50, 50)]) / 255.
plt.figure(figsize=(10, 8))
plt.scatter(X[:, 0], X[:, 1], c=colors[labels], s=50, edgecolors='w')
```
## GMM as *Density Estimation*
Though GMM is often categorized as a clustering algorithm, fundamentally it is an algorithm for *density estimation*.
That is to say, the result of a GMM fit to some data is technically not a clustering model, but a generative probabilistic model describing the distribution of the data.
As an example, consider some data generated from Scikit-Learn's ``make_moons`` function, which we saw in [In Depth: K-Means Clustering](05.11-K-Means.ipynb):
```python
from sklearn.datasets import make_moons
Xmoon, ymoon = make_moons(200, noise=.05, random_state=0)
plt.figure(figsize=(10, 8))
plt.scatter(Xmoon[:, 0], Xmoon[:, 1], edgecolor='w', s=50);
```
If we try to fit this with a two-component GMM viewed as a clustering model, the results are not particularly useful:
```python
gmm2 = GaussianMixture(n_components=2, covariance_type='full', random_state=0)
plot_gmm(gmm2, Xmoon)
```
But if we instead use many more components and ignore the cluster labels, we find a fit that is much closer to the input data:
```python
gmm16 = GaussianMixture(n_components=16, covariance_type='full', random_state=0)
plot_gmm(gmm16, Xmoon, label=False)
```
Here the mixture of 16 Gaussians serves not to find separated clusters of data, but rather to model the overall *distribution* of the input data.
This is a generative model of the distribution, meaning that the GMM gives us the recipe to generate new random data distributed similarly to our input.
For example, here are 400 new points drawn from this 16-component GMM fit to our original data:
```python
Xnew = gmm16.sample(400)[0]
plt.figure(figsize=(10, 8))
plt.scatter(Xnew[:, 0], Xnew[:, 1], s=40, edgecolor='w');
```
GMM is convenient as a flexible means of modeling an arbitrary multi-dimensional distribution of data.
### How many components?
The fact that GMM is a generative model gives us a natural means of determining the optimal number of components for a given dataset.
A generative model is inherently a probability distribution for the dataset, and so we can simply evaluate the *likelihood* of the data under the model, using cross-validation to avoid over-fitting.
Another means of correcting for over-fitting is to adjust the model likelihoods using some analytic criterion such as the [Akaike information criterion (AIC)](https://en.wikipedia.org/wiki/Akaike_information_criterion) or the [Bayesian information criterion (BIC)](https://en.wikipedia.org/wiki/Bayesian_information_criterion).
Scikit-Learn's ``GMM`` estimator actually includes built-in methods that compute both of these, and so it is very easy to operate on this approach.
Let's look at the AIC and BIC as a function as the number of GMM components for our moon dataset:
```python
n_components = np.arange(1, 21)
models = [GaussianMixture(n, covariance_type='full', random_state=0).fit(Xmoon)
for n in n_components]
plt.figure(figsize=(10, 8))
plt.plot(n_components, [m.bic(Xmoon) for m in models], label='BIC')
plt.plot(n_components, [m.aic(Xmoon) for m in models], label='AIC')
plt.legend(loc='best')
plt.xlabel('n_components');
```
The optimal number of clusters is the value that minimizes the AIC or BIC, depending on which approximation we wish to use. The AIC tells us that our choice of 16 components above was probably too many: around 8-12 components would have been a better choice.
As is typical with this sort of problem, the BIC recommends a simpler model.
Notice the important point: this choice of number of components measures how well GMM works *as a density estimator*, not how well it works *as a clustering algorithm*.
I'd encourage you to think of GMM primarily as a density estimator, and use it for clustering only when warranted within simple datasets.
|
[STATEMENT]
lemma (in \<Z>)
assumes "A \<in>\<^sub>\<circ> cat_Rel \<alpha>\<lparr>Obj\<rparr>"
and "B \<in>\<^sub>\<circ> cat_Rel \<alpha>\<lparr>Obj\<rparr>"
and "C \<in>\<^sub>\<circ> cat_Rel \<alpha>\<lparr>Obj\<rparr>"
shows M\<alpha>_Rel_arrow_lr_is_cat_Rel_iso_arr:
"M\<alpha>_Rel_arrow_lr A B C : (A \<times>\<^sub>\<circ> B) \<times>\<^sub>\<circ> C \<mapsto>\<^sub>i\<^sub>s\<^sub>o\<^bsub>cat_Rel \<alpha>\<^esub> A \<times>\<^sub>\<circ> (B \<times>\<^sub>\<circ> C)"
and M\<alpha>_Rel_arrow_rl_is_cat_Rel_iso_arr:
"M\<alpha>_Rel_arrow_rl A B C : A \<times>\<^sub>\<circ> (B \<times>\<^sub>\<circ> C) \<mapsto>\<^sub>i\<^sub>s\<^sub>o\<^bsub>cat_Rel \<alpha>\<^esub> (A \<times>\<^sub>\<circ> B) \<times>\<^sub>\<circ> C"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. M\<alpha>_Rel_arrow_lr A B C : (A \<times>\<^sub>\<circ> B) \<times>\<^sub>\<circ> C \<mapsto>\<^sub>i\<^sub>s\<^sub>o\<^bsub>cat_Rel \<alpha>\<^esub> A \<times>\<^sub>\<circ> B \<times>\<^sub>\<circ> C &&& M\<alpha>_Rel_arrow_rl A B C : A \<times>\<^sub>\<circ> B \<times>\<^sub>\<circ> C \<mapsto>\<^sub>i\<^sub>s\<^sub>o\<^bsub>cat_Rel \<alpha>\<^esub> (A \<times>\<^sub>\<circ> B) \<times>\<^sub>\<circ> C
[PROOF STEP]
proof-
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. M\<alpha>_Rel_arrow_lr A B C : (A \<times>\<^sub>\<circ> B) \<times>\<^sub>\<circ> C \<mapsto>\<^sub>i\<^sub>s\<^sub>o\<^bsub>cat_Rel \<alpha>\<^esub> A \<times>\<^sub>\<circ> B \<times>\<^sub>\<circ> C
2. M\<alpha>_Rel_arrow_rl A B C : A \<times>\<^sub>\<circ> B \<times>\<^sub>\<circ> C \<mapsto>\<^sub>i\<^sub>s\<^sub>o\<^bsub>cat_Rel \<alpha>\<^esub> (A \<times>\<^sub>\<circ> B) \<times>\<^sub>\<circ> C
[PROOF STEP]
interpret Set_Par: wide_replete_subcategory \<alpha> \<open>cat_Set \<alpha>\<close> \<open>cat_Par \<alpha>\<close>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. cat_Set \<alpha> \<subseteq>\<^sub>C\<^sub>.\<^sub>w\<^sub>r\<^bsub>\<alpha>\<^esub> cat_Par \<alpha>
[PROOF STEP]
by (rule wide_replete_subcategory_cat_Set_cat_Par)
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. M\<alpha>_Rel_arrow_lr A B C : (A \<times>\<^sub>\<circ> B) \<times>\<^sub>\<circ> C \<mapsto>\<^sub>i\<^sub>s\<^sub>o\<^bsub>cat_Rel \<alpha>\<^esub> A \<times>\<^sub>\<circ> B \<times>\<^sub>\<circ> C
2. M\<alpha>_Rel_arrow_rl A B C : A \<times>\<^sub>\<circ> B \<times>\<^sub>\<circ> C \<mapsto>\<^sub>i\<^sub>s\<^sub>o\<^bsub>cat_Rel \<alpha>\<^esub> (A \<times>\<^sub>\<circ> B) \<times>\<^sub>\<circ> C
[PROOF STEP]
interpret Par_Rel: wide_replete_subcategory \<alpha> \<open>cat_Par \<alpha>\<close> \<open>cat_Rel \<alpha>\<close>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. cat_Par \<alpha> \<subseteq>\<^sub>C\<^sub>.\<^sub>w\<^sub>r\<^bsub>\<alpha>\<^esub> cat_Rel \<alpha>
[PROOF STEP]
by (rule wide_replete_subcategory_cat_Par_cat_Rel)
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. M\<alpha>_Rel_arrow_lr A B C : (A \<times>\<^sub>\<circ> B) \<times>\<^sub>\<circ> C \<mapsto>\<^sub>i\<^sub>s\<^sub>o\<^bsub>cat_Rel \<alpha>\<^esub> A \<times>\<^sub>\<circ> B \<times>\<^sub>\<circ> C
2. M\<alpha>_Rel_arrow_rl A B C : A \<times>\<^sub>\<circ> B \<times>\<^sub>\<circ> C \<mapsto>\<^sub>i\<^sub>s\<^sub>o\<^bsub>cat_Rel \<alpha>\<^esub> (A \<times>\<^sub>\<circ> B) \<times>\<^sub>\<circ> C
[PROOF STEP]
interpret Set_Rel: wide_replete_subcategory \<alpha> \<open>cat_Set \<alpha>\<close> \<open>cat_Rel \<alpha>\<close>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. cat_Set \<alpha> \<subseteq>\<^sub>C\<^sub>.\<^sub>w\<^sub>r\<^bsub>\<alpha>\<^esub> cat_Rel \<alpha>
[PROOF STEP]
by
(
rule wr_subcat_trans
[
OF
Set_Par.wide_replete_subcategory_axioms
Par_Rel.wide_replete_subcategory_axioms
]
)
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. M\<alpha>_Rel_arrow_lr A B C : (A \<times>\<^sub>\<circ> B) \<times>\<^sub>\<circ> C \<mapsto>\<^sub>i\<^sub>s\<^sub>o\<^bsub>cat_Rel \<alpha>\<^esub> A \<times>\<^sub>\<circ> B \<times>\<^sub>\<circ> C
2. M\<alpha>_Rel_arrow_rl A B C : A \<times>\<^sub>\<circ> B \<times>\<^sub>\<circ> C \<mapsto>\<^sub>i\<^sub>s\<^sub>o\<^bsub>cat_Rel \<alpha>\<^esub> (A \<times>\<^sub>\<circ> B) \<times>\<^sub>\<circ> C
[PROOF STEP]
show "M\<alpha>_Rel_arrow_lr A B C : (A \<times>\<^sub>\<circ> B) \<times>\<^sub>\<circ> C \<mapsto>\<^sub>i\<^sub>s\<^sub>o\<^bsub>cat_Rel \<alpha>\<^esub> A \<times>\<^sub>\<circ> (B \<times>\<^sub>\<circ> C)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. M\<alpha>_Rel_arrow_lr A B C : (A \<times>\<^sub>\<circ> B) \<times>\<^sub>\<circ> C \<mapsto>\<^sub>i\<^sub>s\<^sub>o\<^bsub>cat_Rel \<alpha>\<^esub> A \<times>\<^sub>\<circ> B \<times>\<^sub>\<circ> C
[PROOF STEP]
by
(
rule Set_Rel.wr_subcat_is_iso_arr_is_iso_arr
[
THEN iffD1,
OF M\<alpha>_Rel_arrow_lr_is_cat_Set_iso_arr_Vset[
OF assms[unfolded cat_Rel_components]
]
]
)
[PROOF STATE]
proof (state)
this:
M\<alpha>_Rel_arrow_lr A B C : (A \<times>\<^sub>\<circ> B) \<times>\<^sub>\<circ> C \<mapsto>\<^sub>i\<^sub>s\<^sub>o\<^bsub>cat_Rel \<alpha>\<^esub> A \<times>\<^sub>\<circ> B \<times>\<^sub>\<circ> C
goal (1 subgoal):
1. M\<alpha>_Rel_arrow_rl A B C : A \<times>\<^sub>\<circ> B \<times>\<^sub>\<circ> C \<mapsto>\<^sub>i\<^sub>s\<^sub>o\<^bsub>cat_Rel \<alpha>\<^esub> (A \<times>\<^sub>\<circ> B) \<times>\<^sub>\<circ> C
[PROOF STEP]
show "M\<alpha>_Rel_arrow_rl A B C : A \<times>\<^sub>\<circ> (B \<times>\<^sub>\<circ> C) \<mapsto>\<^sub>i\<^sub>s\<^sub>o\<^bsub>cat_Rel \<alpha>\<^esub> (A \<times>\<^sub>\<circ> B) \<times>\<^sub>\<circ> C"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. M\<alpha>_Rel_arrow_rl A B C : A \<times>\<^sub>\<circ> B \<times>\<^sub>\<circ> C \<mapsto>\<^sub>i\<^sub>s\<^sub>o\<^bsub>cat_Rel \<alpha>\<^esub> (A \<times>\<^sub>\<circ> B) \<times>\<^sub>\<circ> C
[PROOF STEP]
by
(
rule Set_Rel.wr_subcat_is_iso_arr_is_iso_arr
[
THEN iffD1,
OF M\<alpha>_Rel_arrow_rl_is_cat_Set_iso_arr_Vset[
OF assms[unfolded cat_Rel_components]
]
]
)
[PROOF STATE]
proof (state)
this:
M\<alpha>_Rel_arrow_rl A B C : A \<times>\<^sub>\<circ> B \<times>\<^sub>\<circ> C \<mapsto>\<^sub>i\<^sub>s\<^sub>o\<^bsub>cat_Rel \<alpha>\<^esub> (A \<times>\<^sub>\<circ> B) \<times>\<^sub>\<circ> C
goal:
No subgoals!
[PROOF STEP]
qed |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.