text
stringlengths 0
3.34M
|
---|
[STATEMENT]
lemma cos_angle_eq_cos_ang_circ:
assumes
"is_circle (of_ocircline H1)" and "is_circle (of_ocircline H2)" and
"circline_type (of_ocircline H1) < 0" and "circline_type (of_ocircline H2) < 0"
"(a1, r1) = euclidean_circle (of_ocircline H1)" and "(a2, r2) = euclidean_circle (of_ocircline H2)" and
"of_complex E \<in> ocircline_set H1 \<inter> ocircline_set H2"
shows "cos_angle H1 H2 = cos (ang_circ E a1 a2 (pos_oriented H1) (pos_oriented H2))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. cos_angle H1 H2 = cos (ang_circ E a1 a2 (pos_oriented H1) (pos_oriented H2))
[PROOF STEP]
proof-
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. cos_angle H1 H2 = cos (ang_circ E a1 a2 (pos_oriented H1) (pos_oriented H2))
[PROOF STEP]
let ?p1 = "pos_oriented H1" and ?p2 = "pos_oriented H2"
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. cos_angle H1 H2 = cos (ang_circ E a1 a2 (pos_oriented H1) (pos_oriented H2))
[PROOF STEP]
have "E \<in> circle a1 r1" "E \<in> circle a2 r2"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. E \<in> circle a1 r1 &&& E \<in> circle a2 r2
[PROOF STEP]
using classic_circle[of "of_ocircline H1" a1 r1] classic_circle[of "of_ocircline H2" a2 r2]
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>is_circle (of_ocircline H1); (a1, r1) = euclidean_circle (of_ocircline H1); circline_type (of_ocircline H1) \<le> 0\<rbrakk> \<Longrightarrow> circline_set (of_ocircline H1) = of_complex ` circle a1 r1
\<lbrakk>is_circle (of_ocircline H2); (a2, r2) = euclidean_circle (of_ocircline H2); circline_type (of_ocircline H2) \<le> 0\<rbrakk> \<Longrightarrow> circline_set (of_ocircline H2) = of_complex ` circle a2 r2
goal (1 subgoal):
1. E \<in> circle a1 r1 &&& E \<in> circle a2 r2
[PROOF STEP]
using assms of_complex_inj
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>is_circle (of_ocircline H1); (a1, r1) = euclidean_circle (of_ocircline H1); circline_type (of_ocircline H1) \<le> 0\<rbrakk> \<Longrightarrow> circline_set (of_ocircline H1) = of_complex ` circle a1 r1
\<lbrakk>is_circle (of_ocircline H2); (a2, r2) = euclidean_circle (of_ocircline H2); circline_type (of_ocircline H2) \<le> 0\<rbrakk> \<Longrightarrow> circline_set (of_ocircline H2) = of_complex ` circle a2 r2
is_circle (of_ocircline H1)
is_circle (of_ocircline H2)
circline_type (of_ocircline H1) < 0
circline_type (of_ocircline H2) < 0
(a1, r1) = euclidean_circle (of_ocircline H1)
(a2, r2) = euclidean_circle (of_ocircline H2)
of_complex E \<in> ocircline_set H1 \<inter> ocircline_set H2
of_complex ?x = of_complex ?y \<Longrightarrow> ?x = ?y
goal (1 subgoal):
1. E \<in> circle a1 r1 &&& E \<in> circle a2 r2
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
E \<in> circle a1 r1
E \<in> circle a2 r2
goal (1 subgoal):
1. cos_angle H1 H2 = cos (ang_circ E a1 a2 (pos_oriented H1) (pos_oriented H2))
[PROOF STEP]
hence *: "cdist E a1 = r1" "cdist E a2 = r2"
[PROOF STATE]
proof (prove)
using this:
E \<in> circle a1 r1
E \<in> circle a2 r2
goal (1 subgoal):
1. cdist E a1 = r1 &&& cdist E a2 = r2
[PROOF STEP]
unfolding circle_def
[PROOF STATE]
proof (prove)
using this:
E \<in> {z. cmod (z - a1) = r1}
E \<in> {z. cmod (z - a2) = r2}
goal (1 subgoal):
1. cdist E a1 = r1 &&& cdist E a2 = r2
[PROOF STEP]
by (simp_all add: norm_minus_commute)
[PROOF STATE]
proof (state)
this:
cdist E a1 = r1
cdist E a2 = r2
goal (1 subgoal):
1. cos_angle H1 H2 = cos (ang_circ E a1 a2 (pos_oriented H1) (pos_oriented H2))
[PROOF STEP]
have "r1 > 0" "r2 > 0"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. 0 < r1 &&& 0 < r2
[PROOF STEP]
using assms(1-6) real_circle_sgn_r[of "of_ocircline H1" a1 r1] real_circle_sgn_r[of "of_ocircline H2" a2 r2]
[PROOF STATE]
proof (prove)
using this:
is_circle (of_ocircline H1)
is_circle (of_ocircline H2)
circline_type (of_ocircline H1) < 0
circline_type (of_ocircline H2) < 0
(a1, r1) = euclidean_circle (of_ocircline H1)
(a2, r2) = euclidean_circle (of_ocircline H2)
\<lbrakk>is_circle (of_ocircline H1); (a1, r1) = euclidean_circle (of_ocircline H1)\<rbrakk> \<Longrightarrow> sgn r1 = - circline_type (of_ocircline H1)
\<lbrakk>is_circle (of_ocircline H2); (a2, r2) = euclidean_circle (of_ocircline H2)\<rbrakk> \<Longrightarrow> sgn r2 = - circline_type (of_ocircline H2)
goal (1 subgoal):
1. 0 < r1 &&& 0 < r2
[PROOF STEP]
using sgn_greater
[PROOF STATE]
proof (prove)
using this:
is_circle (of_ocircline H1)
is_circle (of_ocircline H2)
circline_type (of_ocircline H1) < 0
circline_type (of_ocircline H2) < 0
(a1, r1) = euclidean_circle (of_ocircline H1)
(a2, r2) = euclidean_circle (of_ocircline H2)
\<lbrakk>is_circle (of_ocircline H1); (a1, r1) = euclidean_circle (of_ocircline H1)\<rbrakk> \<Longrightarrow> sgn r1 = - circline_type (of_ocircline H1)
\<lbrakk>is_circle (of_ocircline H2); (a2, r2) = euclidean_circle (of_ocircline H2)\<rbrakk> \<Longrightarrow> sgn r2 = - circline_type (of_ocircline H2)
((0::?'a) < sgn ?a) = ((0::?'a) < ?a)
goal (1 subgoal):
1. 0 < r1 &&& 0 < r2
[PROOF STEP]
by fastforce+
[PROOF STATE]
proof (state)
this:
0 < r1
0 < r2
goal (1 subgoal):
1. cos_angle H1 H2 = cos (ang_circ E a1 a2 (pos_oriented H1) (pos_oriented H2))
[PROOF STEP]
hence "E \<noteq> a1" "E \<noteq> a2"
[PROOF STATE]
proof (prove)
using this:
0 < r1
0 < r2
goal (1 subgoal):
1. E \<noteq> a1 &&& E \<noteq> a2
[PROOF STEP]
using \<open>cdist E a1 = r1\<close> \<open>cdist E a2 = r2\<close>
[PROOF STATE]
proof (prove)
using this:
0 < r1
0 < r2
cdist E a1 = r1
cdist E a2 = r2
goal (1 subgoal):
1. E \<noteq> a1 &&& E \<noteq> a2
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
E \<noteq> a1
E \<noteq> a2
goal (1 subgoal):
1. cos_angle H1 H2 = cos (ang_circ E a1 a2 (pos_oriented H1) (pos_oriented H2))
[PROOF STEP]
let ?k = "sgn_bool (?p1 = ?p2)"
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. cos_angle H1 H2 = cos (ang_circ E a1 a2 (pos_oriented H1) (pos_oriented H2))
[PROOF STEP]
let ?xx = "?k * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)"
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. cos_angle H1 H2 = cos (ang_circ E a1 a2 (pos_oriented H1) (pos_oriented H2))
[PROOF STEP]
have "cos (ang_circ E a1 a2 ?p1 ?p2) = ?xx"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. cos (ang_circ E a1 a2 (pos_oriented H1) (pos_oriented H2)) = sgn_bool (pos_oriented H1 = pos_oriented H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
using law_of_cosines[of a2 a1 E] * \<open>r1 > 0\<close> \<open>r2 > 0\<close> cos_ang_circ_simp[OF \<open>E \<noteq> a1\<close> \<open>E \<noteq> a2\<close>]
[PROOF STATE]
proof (prove)
using this:
(cdist a2 a1)\<^sup>2 = (cdist E a1)\<^sup>2 + (cdist E a2)\<^sup>2 - 2 * cdist E a1 * cdist E a2 * cos (\<angle> (a1 - E) (a2 - E))
cdist E a1 = r1
cdist E a2 = r2
0 < r1
0 < r2
cos (ang_circ E a1 a2 ?p1.0 ?p2.0) = sgn_bool (?p1.0 = ?p2.0) * cos (Arg (E - a2) - Arg (E - a1))
goal (1 subgoal):
1. cos (ang_circ E a1 a2 (pos_oriented H1) (pos_oriented H2)) = sgn_bool (pos_oriented H1 = pos_oriented H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
by (subst (asm) ang_vec_opposite_opposite'[OF \<open>E \<noteq> a1\<close>[symmetric] \<open>E \<noteq> a2\<close>[symmetric], symmetric]) simp
[PROOF STATE]
proof (state)
this:
cos (ang_circ E a1 a2 (pos_oriented H1) (pos_oriented H2)) = sgn_bool (pos_oriented H1 = pos_oriented H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
goal (1 subgoal):
1. cos_angle H1 H2 = cos (ang_circ E a1 a2 (pos_oriented H1) (pos_oriented H2))
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
cos (ang_circ E a1 a2 (pos_oriented H1) (pos_oriented H2)) = sgn_bool (pos_oriented H1 = pos_oriented H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
goal (1 subgoal):
1. cos_angle H1 H2 = cos (ang_circ E a1 a2 (pos_oriented H1) (pos_oriented H2))
[PROOF STEP]
have "cos_angle H1 H2 = ?xx"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. cos_angle H1 H2 = sgn_bool (pos_oriented H1 = pos_oriented H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
using \<open>r1 > 0\<close> \<open>r2 > 0\<close>
[PROOF STATE]
proof (prove)
using this:
0 < r1
0 < r2
goal (1 subgoal):
1. cos_angle H1 H2 = sgn_bool (pos_oriented H1 = pos_oriented H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
using \<open>(a1, r1) = euclidean_circle (of_ocircline H1)\<close> \<open>(a2, r2) = euclidean_circle (of_ocircline H2)\<close>
[PROOF STATE]
proof (prove)
using this:
0 < r1
0 < r2
(a1, r1) = euclidean_circle (of_ocircline H1)
(a2, r2) = euclidean_circle (of_ocircline H2)
goal (1 subgoal):
1. cos_angle H1 H2 = sgn_bool (pos_oriented H1 = pos_oriented H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
using \<open>is_circle (of_ocircline H1)\<close> \<open>is_circle (of_ocircline H2)\<close>
[PROOF STATE]
proof (prove)
using this:
0 < r1
0 < r2
(a1, r1) = euclidean_circle (of_ocircline H1)
(a2, r2) = euclidean_circle (of_ocircline H2)
is_circle (of_ocircline H1)
is_circle (of_ocircline H2)
goal (1 subgoal):
1. cos_angle H1 H2 = sgn_bool (pos_oriented H1 = pos_oriented H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
using \<open>circline_type (of_ocircline H1) < 0\<close> \<open>circline_type (of_ocircline H2) < 0\<close>
[PROOF STATE]
proof (prove)
using this:
0 < r1
0 < r2
(a1, r1) = euclidean_circle (of_ocircline H1)
(a2, r2) = euclidean_circle (of_ocircline H2)
is_circle (of_ocircline H1)
is_circle (of_ocircline H2)
circline_type (of_ocircline H1) < 0
circline_type (of_ocircline H2) < 0
goal (1 subgoal):
1. cos_angle H1 H2 = sgn_bool (pos_oriented H1 = pos_oriented H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
proof (transfer, transfer)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>r1 r2 a1 H1 a2 H2 r1a r2a a1a H1a a2a H2a. \<lbrakk>hermitean H1 \<and> H1 \<noteq> mat_zero; hermitean H2 \<and> H2 \<noteq> mat_zero; 0 < r1; 0 < r2; (a1, r1) = euclidean_circle_cmat (id H1); (a2, r2) = euclidean_circle_cmat (id H2); \<not> circline_A0_cmat (id H1); \<not> circline_A0_cmat (id H2); circline_type_cmat (id H1) < 0; circline_type_cmat (id H2) < 0; 0 < r1a; 0 < r2a; (a1a, r1a) = euclidean_circle_clmat (id H1a); (a2a, r2a) = euclidean_circle_clmat (id H2a); \<not> circline_A0_clmat (id H1a); \<not> circline_A0_clmat (id H2a); circline_type_clmat (id H1a) < 0; circline_type_clmat (id H2a) < 0\<rbrakk> \<Longrightarrow> cos_angle_cmat H1 H2 = sgn_bool (pos_oriented_cmat H1 = pos_oriented_cmat H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
fix a1 r1 H1 H2 a2 r2
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>r1 r2 a1 H1 a2 H2 r1a r2a a1a H1a a2a H2a. \<lbrakk>hermitean H1 \<and> H1 \<noteq> mat_zero; hermitean H2 \<and> H2 \<noteq> mat_zero; 0 < r1; 0 < r2; (a1, r1) = euclidean_circle_cmat (id H1); (a2, r2) = euclidean_circle_cmat (id H2); \<not> circline_A0_cmat (id H1); \<not> circline_A0_cmat (id H2); circline_type_cmat (id H1) < 0; circline_type_cmat (id H2) < 0; 0 < r1a; 0 < r2a; (a1a, r1a) = euclidean_circle_clmat (id H1a); (a2a, r2a) = euclidean_circle_clmat (id H2a); \<not> circline_A0_clmat (id H1a); \<not> circline_A0_clmat (id H2a); circline_type_clmat (id H1a) < 0; circline_type_clmat (id H2a) < 0\<rbrakk> \<Longrightarrow> cos_angle_cmat H1 H2 = sgn_bool (pos_oriented_cmat H1 = pos_oriented_cmat H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
assume hh: "hermitean H1 \<and> H1 \<noteq> mat_zero" "hermitean H2 \<and> H2 \<noteq> mat_zero"
[PROOF STATE]
proof (state)
this:
hermitean H1 \<and> H1 \<noteq> mat_zero
hermitean H2 \<and> H2 \<noteq> mat_zero
goal (1 subgoal):
1. \<And>r1 r2 a1 H1 a2 H2 r1a r2a a1a H1a a2a H2a. \<lbrakk>hermitean H1 \<and> H1 \<noteq> mat_zero; hermitean H2 \<and> H2 \<noteq> mat_zero; 0 < r1; 0 < r2; (a1, r1) = euclidean_circle_cmat (id H1); (a2, r2) = euclidean_circle_cmat (id H2); \<not> circline_A0_cmat (id H1); \<not> circline_A0_cmat (id H2); circline_type_cmat (id H1) < 0; circline_type_cmat (id H2) < 0; 0 < r1a; 0 < r2a; (a1a, r1a) = euclidean_circle_clmat (id H1a); (a2a, r2a) = euclidean_circle_clmat (id H2a); \<not> circline_A0_clmat (id H1a); \<not> circline_A0_clmat (id H2a); circline_type_clmat (id H1a) < 0; circline_type_clmat (id H2a) < 0\<rbrakk> \<Longrightarrow> cos_angle_cmat H1 H2 = sgn_bool (pos_oriented_cmat H1 = pos_oriented_cmat H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
obtain A1 B1 C1 D1 where HH1: "H1 = (A1, B1, C1, D1)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>A1 B1 C1 D1. H1 = (A1, B1, C1, D1) \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by (cases H1) auto
[PROOF STATE]
proof (state)
this:
H1 = (A1, B1, C1, D1)
goal (1 subgoal):
1. \<And>r1 r2 a1 H1 a2 H2 r1a r2a a1a H1a a2a H2a. \<lbrakk>hermitean H1 \<and> H1 \<noteq> mat_zero; hermitean H2 \<and> H2 \<noteq> mat_zero; 0 < r1; 0 < r2; (a1, r1) = euclidean_circle_cmat (id H1); (a2, r2) = euclidean_circle_cmat (id H2); \<not> circline_A0_cmat (id H1); \<not> circline_A0_cmat (id H2); circline_type_cmat (id H1) < 0; circline_type_cmat (id H2) < 0; 0 < r1a; 0 < r2a; (a1a, r1a) = euclidean_circle_clmat (id H1a); (a2a, r2a) = euclidean_circle_clmat (id H2a); \<not> circline_A0_clmat (id H1a); \<not> circline_A0_clmat (id H2a); circline_type_clmat (id H1a) < 0; circline_type_clmat (id H2a) < 0\<rbrakk> \<Longrightarrow> cos_angle_cmat H1 H2 = sgn_bool (pos_oriented_cmat H1 = pos_oriented_cmat H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
obtain A2 B2 C2 D2 where HH2: "H2 = (A2, B2, C2, D2)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>A2 B2 C2 D2. H2 = (A2, B2, C2, D2) \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by (cases H2) auto
[PROOF STATE]
proof (state)
this:
H2 = (A2, B2, C2, D2)
goal (1 subgoal):
1. \<And>r1 r2 a1 H1 a2 H2 r1a r2a a1a H1a a2a H2a. \<lbrakk>hermitean H1 \<and> H1 \<noteq> mat_zero; hermitean H2 \<and> H2 \<noteq> mat_zero; 0 < r1; 0 < r2; (a1, r1) = euclidean_circle_cmat (id H1); (a2, r2) = euclidean_circle_cmat (id H2); \<not> circline_A0_cmat (id H1); \<not> circline_A0_cmat (id H2); circline_type_cmat (id H1) < 0; circline_type_cmat (id H2) < 0; 0 < r1a; 0 < r2a; (a1a, r1a) = euclidean_circle_clmat (id H1a); (a2a, r2a) = euclidean_circle_clmat (id H2a); \<not> circline_A0_clmat (id H1a); \<not> circline_A0_clmat (id H2a); circline_type_clmat (id H1a) < 0; circline_type_clmat (id H2a) < 0\<rbrakk> \<Longrightarrow> cos_angle_cmat H1 H2 = sgn_bool (pos_oriented_cmat H1 = pos_oriented_cmat H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
have *: "is_real A1" "is_real A2" "is_real D1" "is_real D2" "cnj B1 = C1" "cnj B2 = C2"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (is_real A1 &&& is_real A2 &&& is_real D1) &&& is_real D2 &&& cnj B1 = C1 &&& cnj B2 = C2
[PROOF STEP]
using hh hermitean_elems[of A1 B1 C1 D1] hermitean_elems[of A2 B2 C2 D2] HH1 HH2
[PROOF STATE]
proof (prove)
using this:
hermitean H1 \<and> H1 \<noteq> mat_zero
hermitean H2 \<and> H2 \<noteq> mat_zero
hermitean (A1, B1, C1, D1) \<Longrightarrow> is_real A1
hermitean (A1, B1, C1, D1) \<Longrightarrow> is_real D1
hermitean (A1, B1, C1, D1) \<Longrightarrow> B1 = cnj C1
hermitean (A1, B1, C1, D1) \<Longrightarrow> cnj B1 = C1
hermitean (A2, B2, C2, D2) \<Longrightarrow> is_real A2
hermitean (A2, B2, C2, D2) \<Longrightarrow> is_real D2
hermitean (A2, B2, C2, D2) \<Longrightarrow> B2 = cnj C2
hermitean (A2, B2, C2, D2) \<Longrightarrow> cnj B2 = C2
H1 = (A1, B1, C1, D1)
H2 = (A2, B2, C2, D2)
goal (1 subgoal):
1. (is_real A1 &&& is_real A2 &&& is_real D1) &&& is_real D2 &&& cnj B1 = C1 &&& cnj B2 = C2
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
is_real A1
is_real A2
is_real D1
is_real D2
cnj B1 = C1
cnj B2 = C2
goal (1 subgoal):
1. \<And>r1 r2 a1 H1 a2 H2 r1a r2a a1a H1a a2a H2a. \<lbrakk>hermitean H1 \<and> H1 \<noteq> mat_zero; hermitean H2 \<and> H2 \<noteq> mat_zero; 0 < r1; 0 < r2; (a1, r1) = euclidean_circle_cmat (id H1); (a2, r2) = euclidean_circle_cmat (id H2); \<not> circline_A0_cmat (id H1); \<not> circline_A0_cmat (id H2); circline_type_cmat (id H1) < 0; circline_type_cmat (id H2) < 0; 0 < r1a; 0 < r2a; (a1a, r1a) = euclidean_circle_clmat (id H1a); (a2a, r2a) = euclidean_circle_clmat (id H2a); \<not> circline_A0_clmat (id H1a); \<not> circline_A0_clmat (id H2a); circline_type_clmat (id H1a) < 0; circline_type_clmat (id H2a) < 0\<rbrakk> \<Longrightarrow> cos_angle_cmat H1 H2 = sgn_bool (pos_oriented_cmat H1 = pos_oriented_cmat H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
have "cnj A1 = A1" "cnj A2 = A2"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. cnj A1 = A1 &&& cnj A2 = A2
[PROOF STEP]
using \<open>is_real A1\<close> \<open>is_real A2\<close>
[PROOF STATE]
proof (prove)
using this:
is_real A1
is_real A2
goal (1 subgoal):
1. cnj A1 = A1 &&& cnj A2 = A2
[PROOF STEP]
by (case_tac[!] A1, case_tac[!] A2, auto simp add: Complex_eq)
[PROOF STATE]
proof (state)
this:
cnj A1 = A1
cnj A2 = A2
goal (1 subgoal):
1. \<And>r1 r2 a1 H1 a2 H2 r1a r2a a1a H1a a2a H2a. \<lbrakk>hermitean H1 \<and> H1 \<noteq> mat_zero; hermitean H2 \<and> H2 \<noteq> mat_zero; 0 < r1; 0 < r2; (a1, r1) = euclidean_circle_cmat (id H1); (a2, r2) = euclidean_circle_cmat (id H2); \<not> circline_A0_cmat (id H1); \<not> circline_A0_cmat (id H2); circline_type_cmat (id H1) < 0; circline_type_cmat (id H2) < 0; 0 < r1a; 0 < r2a; (a1a, r1a) = euclidean_circle_clmat (id H1a); (a2a, r2a) = euclidean_circle_clmat (id H2a); \<not> circline_A0_clmat (id H1a); \<not> circline_A0_clmat (id H2a); circline_type_clmat (id H1a) < 0; circline_type_clmat (id H2a) < 0\<rbrakk> \<Longrightarrow> cos_angle_cmat H1 H2 = sgn_bool (pos_oriented_cmat H1 = pos_oriented_cmat H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
assume "\<not> circline_A0_cmat (id H1)" "\<not> circline_A0_cmat (id H2)"
[PROOF STATE]
proof (state)
this:
\<not> circline_A0_cmat (id H1)
\<not> circline_A0_cmat (id H2)
goal (1 subgoal):
1. \<And>r1 r2 a1 H1 a2 H2 r1a r2a a1a H1a a2a H2a. \<lbrakk>hermitean H1 \<and> H1 \<noteq> mat_zero; hermitean H2 \<and> H2 \<noteq> mat_zero; 0 < r1; 0 < r2; (a1, r1) = euclidean_circle_cmat (id H1); (a2, r2) = euclidean_circle_cmat (id H2); \<not> circline_A0_cmat (id H1); \<not> circline_A0_cmat (id H2); circline_type_cmat (id H1) < 0; circline_type_cmat (id H2) < 0; 0 < r1a; 0 < r2a; (a1a, r1a) = euclidean_circle_clmat (id H1a); (a2a, r2a) = euclidean_circle_clmat (id H2a); \<not> circline_A0_clmat (id H1a); \<not> circline_A0_clmat (id H2a); circline_type_clmat (id H1a) < 0; circline_type_clmat (id H2a) < 0\<rbrakk> \<Longrightarrow> cos_angle_cmat H1 H2 = sgn_bool (pos_oriented_cmat H1 = pos_oriented_cmat H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
hence "A1 \<noteq> 0" "A2 \<noteq> 0"
[PROOF STATE]
proof (prove)
using this:
\<not> circline_A0_cmat (id H1)
\<not> circline_A0_cmat (id H2)
goal (1 subgoal):
1. A1 \<noteq> 0 &&& A2 \<noteq> 0
[PROOF STEP]
using HH1 HH2
[PROOF STATE]
proof (prove)
using this:
\<not> circline_A0_cmat (id H1)
\<not> circline_A0_cmat (id H2)
H1 = (A1, B1, C1, D1)
H2 = (A2, B2, C2, D2)
goal (1 subgoal):
1. A1 \<noteq> 0 &&& A2 \<noteq> 0
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
A1 \<noteq> 0
A2 \<noteq> 0
goal (1 subgoal):
1. \<And>r1 r2 a1 H1 a2 H2 r1a r2a a1a H1a a2a H2a. \<lbrakk>hermitean H1 \<and> H1 \<noteq> mat_zero; hermitean H2 \<and> H2 \<noteq> mat_zero; 0 < r1; 0 < r2; (a1, r1) = euclidean_circle_cmat (id H1); (a2, r2) = euclidean_circle_cmat (id H2); \<not> circline_A0_cmat (id H1); \<not> circline_A0_cmat (id H2); circline_type_cmat (id H1) < 0; circline_type_cmat (id H2) < 0; 0 < r1a; 0 < r2a; (a1a, r1a) = euclidean_circle_clmat (id H1a); (a2a, r2a) = euclidean_circle_clmat (id H2a); \<not> circline_A0_clmat (id H1a); \<not> circline_A0_clmat (id H2a); circline_type_clmat (id H1a) < 0; circline_type_clmat (id H2a) < 0\<rbrakk> \<Longrightarrow> cos_angle_cmat H1 H2 = sgn_bool (pos_oriented_cmat H1 = pos_oriented_cmat H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
hence "Re A1 \<noteq> 0" "Re A2 \<noteq> 0"
[PROOF STATE]
proof (prove)
using this:
A1 \<noteq> 0
A2 \<noteq> 0
goal (1 subgoal):
1. Re A1 \<noteq> 0 &&& Re A2 \<noteq> 0
[PROOF STEP]
using \<open>is_real A1\<close> \<open>is_real A2\<close>
[PROOF STATE]
proof (prove)
using this:
A1 \<noteq> 0
A2 \<noteq> 0
is_real A1
is_real A2
goal (1 subgoal):
1. Re A1 \<noteq> 0 &&& Re A2 \<noteq> 0
[PROOF STEP]
using complex.expand
[PROOF STATE]
proof (prove)
using this:
A1 \<noteq> 0
A2 \<noteq> 0
is_real A1
is_real A2
Re ?complex = Re ?complex' \<and> Im ?complex = Im ?complex' \<Longrightarrow> ?complex = ?complex'
goal (1 subgoal):
1. Re A1 \<noteq> 0 &&& Re A2 \<noteq> 0
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
Re A1 \<noteq> 0
Re A2 \<noteq> 0
goal (1 subgoal):
1. \<And>r1 r2 a1 H1 a2 H2 r1a r2a a1a H1a a2a H2a. \<lbrakk>hermitean H1 \<and> H1 \<noteq> mat_zero; hermitean H2 \<and> H2 \<noteq> mat_zero; 0 < r1; 0 < r2; (a1, r1) = euclidean_circle_cmat (id H1); (a2, r2) = euclidean_circle_cmat (id H2); \<not> circline_A0_cmat (id H1); \<not> circline_A0_cmat (id H2); circline_type_cmat (id H1) < 0; circline_type_cmat (id H2) < 0; 0 < r1a; 0 < r2a; (a1a, r1a) = euclidean_circle_clmat (id H1a); (a2a, r2a) = euclidean_circle_clmat (id H2a); \<not> circline_A0_clmat (id H1a); \<not> circline_A0_clmat (id H2a); circline_type_clmat (id H1a) < 0; circline_type_clmat (id H2a) < 0\<rbrakk> \<Longrightarrow> cos_angle_cmat H1 H2 = sgn_bool (pos_oriented_cmat H1 = pos_oriented_cmat H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
assume "circline_type_cmat (id H1) < 0" "circline_type_cmat (id H2) < 0"
[PROOF STATE]
proof (state)
this:
circline_type_cmat (id H1) < 0
circline_type_cmat (id H2) < 0
goal (1 subgoal):
1. \<And>r1 r2 a1 H1 a2 H2 r1a r2a a1a H1a a2a H2a. \<lbrakk>hermitean H1 \<and> H1 \<noteq> mat_zero; hermitean H2 \<and> H2 \<noteq> mat_zero; 0 < r1; 0 < r2; (a1, r1) = euclidean_circle_cmat (id H1); (a2, r2) = euclidean_circle_cmat (id H2); \<not> circline_A0_cmat (id H1); \<not> circline_A0_cmat (id H2); circline_type_cmat (id H1) < 0; circline_type_cmat (id H2) < 0; 0 < r1a; 0 < r2a; (a1a, r1a) = euclidean_circle_clmat (id H1a); (a2a, r2a) = euclidean_circle_clmat (id H2a); \<not> circline_A0_clmat (id H1a); \<not> circline_A0_clmat (id H2a); circline_type_clmat (id H1a) < 0; circline_type_clmat (id H2a) < 0\<rbrakk> \<Longrightarrow> cos_angle_cmat H1 H2 = sgn_bool (pos_oriented_cmat H1 = pos_oriented_cmat H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
assume "(a1, r1) = euclidean_circle_cmat (id H1)" "(a2, r2) = euclidean_circle_cmat (id H2)"
[PROOF STATE]
proof (state)
this:
(a1, r1) = euclidean_circle_cmat (id H1)
(a2, r2) = euclidean_circle_cmat (id H2)
goal (1 subgoal):
1. \<And>r1 r2 a1 H1 a2 H2 r1a r2a a1a H1a a2a H2a. \<lbrakk>hermitean H1 \<and> H1 \<noteq> mat_zero; hermitean H2 \<and> H2 \<noteq> mat_zero; 0 < r1; 0 < r2; (a1, r1) = euclidean_circle_cmat (id H1); (a2, r2) = euclidean_circle_cmat (id H2); \<not> circline_A0_cmat (id H1); \<not> circline_A0_cmat (id H2); circline_type_cmat (id H1) < 0; circline_type_cmat (id H2) < 0; 0 < r1a; 0 < r2a; (a1a, r1a) = euclidean_circle_clmat (id H1a); (a2a, r2a) = euclidean_circle_clmat (id H2a); \<not> circline_A0_clmat (id H1a); \<not> circline_A0_clmat (id H2a); circline_type_clmat (id H1a) < 0; circline_type_clmat (id H2a) < 0\<rbrakk> \<Longrightarrow> cos_angle_cmat H1 H2 = sgn_bool (pos_oriented_cmat H1 = pos_oriented_cmat H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
assume "r1 > 0" "r2 > 0"
[PROOF STATE]
proof (state)
this:
0 < r1
0 < r2
goal (1 subgoal):
1. \<And>r1 r2 a1 H1 a2 H2 r1a r2a a1a H1a a2a H2a. \<lbrakk>hermitean H1 \<and> H1 \<noteq> mat_zero; hermitean H2 \<and> H2 \<noteq> mat_zero; 0 < r1; 0 < r2; (a1, r1) = euclidean_circle_cmat (id H1); (a2, r2) = euclidean_circle_cmat (id H2); \<not> circline_A0_cmat (id H1); \<not> circline_A0_cmat (id H2); circline_type_cmat (id H1) < 0; circline_type_cmat (id H2) < 0; 0 < r1a; 0 < r2a; (a1a, r1a) = euclidean_circle_clmat (id H1a); (a2a, r2a) = euclidean_circle_clmat (id H2a); \<not> circline_A0_clmat (id H1a); \<not> circline_A0_clmat (id H2a); circline_type_clmat (id H1a) < 0; circline_type_clmat (id H2a) < 0\<rbrakk> \<Longrightarrow> cos_angle_cmat H1 H2 = sgn_bool (pos_oriented_cmat H1 = pos_oriented_cmat H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
let ?D12 = "mat_det_12 H1 H2" and ?D1 = "mat_det H1" and ?D2 = "mat_det H2"
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>r1 r2 a1 H1 a2 H2 r1a r2a a1a H1a a2a H2a. \<lbrakk>hermitean H1 \<and> H1 \<noteq> mat_zero; hermitean H2 \<and> H2 \<noteq> mat_zero; 0 < r1; 0 < r2; (a1, r1) = euclidean_circle_cmat (id H1); (a2, r2) = euclidean_circle_cmat (id H2); \<not> circline_A0_cmat (id H1); \<not> circline_A0_cmat (id H2); circline_type_cmat (id H1) < 0; circline_type_cmat (id H2) < 0; 0 < r1a; 0 < r2a; (a1a, r1a) = euclidean_circle_clmat (id H1a); (a2a, r2a) = euclidean_circle_clmat (id H2a); \<not> circline_A0_clmat (id H1a); \<not> circline_A0_clmat (id H2a); circline_type_clmat (id H1a) < 0; circline_type_clmat (id H2a) < 0\<rbrakk> \<Longrightarrow> cos_angle_cmat H1 H2 = sgn_bool (pos_oriented_cmat H1 = pos_oriented_cmat H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
let ?x1 = "(cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2" and ?x2 = "2*r1*r2"
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>r1 r2 a1 H1 a2 H2 r1a r2a a1a H1a a2a H2a. \<lbrakk>hermitean H1 \<and> H1 \<noteq> mat_zero; hermitean H2 \<and> H2 \<noteq> mat_zero; 0 < r1; 0 < r2; (a1, r1) = euclidean_circle_cmat (id H1); (a2, r2) = euclidean_circle_cmat (id H2); \<not> circline_A0_cmat (id H1); \<not> circline_A0_cmat (id H2); circline_type_cmat (id H1) < 0; circline_type_cmat (id H2) < 0; 0 < r1a; 0 < r2a; (a1a, r1a) = euclidean_circle_clmat (id H1a); (a2a, r2a) = euclidean_circle_clmat (id H2a); \<not> circline_A0_clmat (id H1a); \<not> circline_A0_clmat (id H2a); circline_type_clmat (id H1a) < 0; circline_type_clmat (id H2a) < 0\<rbrakk> \<Longrightarrow> cos_angle_cmat H1 H2 = sgn_bool (pos_oriented_cmat H1 = pos_oriented_cmat H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
let ?x = "?x1 / ?x2"
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>r1 r2 a1 H1 a2 H2 r1a r2a a1a H1a a2a H2a. \<lbrakk>hermitean H1 \<and> H1 \<noteq> mat_zero; hermitean H2 \<and> H2 \<noteq> mat_zero; 0 < r1; 0 < r2; (a1, r1) = euclidean_circle_cmat (id H1); (a2, r2) = euclidean_circle_cmat (id H2); \<not> circline_A0_cmat (id H1); \<not> circline_A0_cmat (id H2); circline_type_cmat (id H1) < 0; circline_type_cmat (id H2) < 0; 0 < r1a; 0 < r2a; (a1a, r1a) = euclidean_circle_clmat (id H1a); (a2a, r2a) = euclidean_circle_clmat (id H2a); \<not> circline_A0_clmat (id H1a); \<not> circline_A0_clmat (id H2a); circline_type_clmat (id H1a) < 0; circline_type_clmat (id H2a) < 0\<rbrakk> \<Longrightarrow> cos_angle_cmat H1 H2 = sgn_bool (pos_oriented_cmat H1 = pos_oriented_cmat H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
have *: "Re (?D12) / (2 * (sqrt (Re (?D1 * ?D2)))) = Re (sgn A1) * Re (sgn A2) * ?x"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. Re (mat_det_12 H1 H2) / (2 * sqrt (Re (mat_det H1 * mat_det H2))) = Re (sgn A1) * Re (sgn A2) * (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))
[PROOF STEP]
proof-
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. Re (mat_det_12 H1 H2) / (2 * sqrt (Re (mat_det H1 * mat_det H2))) = Re (sgn A1) * Re (sgn A2) * (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))
[PROOF STEP]
let ?M1 = "(A1, B1, C1, D1)" and ?M2 = "(A2, B2, C2, D2)"
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. Re (mat_det_12 H1 H2) / (2 * sqrt (Re (mat_det H1 * mat_det H2))) = Re (sgn A1) * Re (sgn A2) * (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))
[PROOF STEP]
let ?d1 = "B1 * C1 - A1 * D1" and ?d2 = "B2 * C2 - A2 * D2"
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. Re (mat_det_12 H1 H2) / (2 * sqrt (Re (mat_det H1 * mat_det H2))) = Re (sgn A1) * Re (sgn A2) * (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))
[PROOF STEP]
have "Re ?d1 > 0" "Re ?d2 > 0"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. 0 < Re (B1 * C1 - A1 * D1) &&& 0 < Re (B2 * C2 - A2 * D2)
[PROOF STEP]
using HH1 HH2 \<open>circline_type_cmat (id H1) < 0\<close> \<open>circline_type_cmat (id H2) < 0\<close>
[PROOF STATE]
proof (prove)
using this:
H1 = (A1, B1, C1, D1)
H2 = (A2, B2, C2, D2)
circline_type_cmat (id H1) < 0
circline_type_cmat (id H2) < 0
goal (1 subgoal):
1. 0 < Re (B1 * C1 - A1 * D1) &&& 0 < Re (B2 * C2 - A2 * D2)
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
0 < Re (B1 * C1 - A1 * D1)
0 < Re (B2 * C2 - A2 * D2)
goal (1 subgoal):
1. Re (mat_det_12 H1 H2) / (2 * sqrt (Re (mat_det H1 * mat_det H2))) = Re (sgn A1) * Re (sgn A2) * (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))
[PROOF STEP]
hence **: "Re (?d1 / (A1 * A1)) > 0" "Re (?d2 / (A2 * A2)) > 0"
[PROOF STATE]
proof (prove)
using this:
0 < Re (B1 * C1 - A1 * D1)
0 < Re (B2 * C2 - A2 * D2)
goal (1 subgoal):
1. 0 < Re ((B1 * C1 - A1 * D1) / (A1 * A1)) &&& 0 < Re ((B2 * C2 - A2 * D2) / (A2 * A2))
[PROOF STEP]
using \<open>is_real A1\<close> \<open>is_real A2\<close> \<open>A1 \<noteq> 0\<close> \<open>A2 \<noteq> 0\<close>
[PROOF STATE]
proof (prove)
using this:
0 < Re (B1 * C1 - A1 * D1)
0 < Re (B2 * C2 - A2 * D2)
is_real A1
is_real A2
A1 \<noteq> 0
A2 \<noteq> 0
goal (1 subgoal):
1. 0 < Re ((B1 * C1 - A1 * D1) / (A1 * A1)) &&& 0 < Re ((B2 * C2 - A2 * D2) / (A2 * A2))
[PROOF STEP]
by (subst Re_divide_real, simp_all add: complex_neq_0 power2_eq_square)+
[PROOF STATE]
proof (state)
this:
0 < Re ((B1 * C1 - A1 * D1) / (A1 * A1))
0 < Re ((B2 * C2 - A2 * D2) / (A2 * A2))
goal (1 subgoal):
1. Re (mat_det_12 H1 H2) / (2 * sqrt (Re (mat_det H1 * mat_det H2))) = Re (sgn A1) * Re (sgn A2) * (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))
[PROOF STEP]
have ***: "is_real (?d1 / (A1 * A1)) \<and> is_real (?d2 / (A2 * A2))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. is_real ((B1 * C1 - A1 * D1) / (A1 * A1)) \<and> is_real ((B2 * C2 - A2 * D2) / (A2 * A2))
[PROOF STEP]
using \<open>is_real A1\<close> \<open>is_real A2\<close> \<open>A1 \<noteq> 0\<close> \<open>A2 \<noteq> 0\<close> \<open>cnj B1 = C1\<close>[symmetric] \<open>cnj B2 = C2\<close>[symmetric] \<open>is_real D1\<close> \<open>is_real D2\<close>
[PROOF STATE]
proof (prove)
using this:
is_real A1
is_real A2
A1 \<noteq> 0
A2 \<noteq> 0
C1 = cnj B1
C2 = cnj B2
is_real D1
is_real D2
goal (1 subgoal):
1. is_real ((B1 * C1 - A1 * D1) / (A1 * A1)) \<and> is_real ((B2 * C2 - A2 * D2) / (A2 * A2))
[PROOF STEP]
by (subst div_reals, simp, simp, simp)+
[PROOF STATE]
proof (state)
this:
is_real ((B1 * C1 - A1 * D1) / (A1 * A1)) \<and> is_real ((B2 * C2 - A2 * D2) / (A2 * A2))
goal (1 subgoal):
1. Re (mat_det_12 H1 H2) / (2 * sqrt (Re (mat_det H1 * mat_det H2))) = Re (sgn A1) * Re (sgn A2) * (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))
[PROOF STEP]
have "cor ?x = mat_det_12 ?M1 ?M2 / (2 * sgn A1 * sgn A2 * cor (sqrt (Re ?d1) * sqrt (Re ?d2)))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2)) = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2) / (2 * sgn A1 * sgn A2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2))))
[PROOF STEP]
proof-
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2)) = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2) / (2 * sgn A1 * sgn A2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2))))
[PROOF STEP]
have "A1*A2*cor ?x1 = mat_det_12 ?M1 ?M2"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. A1 * A2 * cor ((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2)
[PROOF STEP]
proof-
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. A1 * A2 * cor ((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2)
[PROOF STEP]
have 1: "A1*A2*(cor ((cdist a2 a1)\<^sup>2)) = ((B2*A1 - A2*B1)*(C2*A1 - C1*A2)) / (A1*A2)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. A1 * A2 * cor ((cdist a2 a1)\<^sup>2) = (B2 * A1 - A2 * B1) * (C2 * A1 - C1 * A2) / (A1 * A2)
[PROOF STEP]
using \<open>(a1, r1) = euclidean_circle_cmat (id H1)\<close> \<open>(a2, r2) = euclidean_circle_cmat (id H2)\<close>
[PROOF STATE]
proof (prove)
using this:
(a1, r1) = euclidean_circle_cmat (id H1)
(a2, r2) = euclidean_circle_cmat (id H2)
goal (1 subgoal):
1. A1 * A2 * cor ((cdist a2 a1)\<^sup>2) = (B2 * A1 - A2 * B1) * (C2 * A1 - C1 * A2) / (A1 * A2)
[PROOF STEP]
unfolding cdist_def cmod_square
[PROOF STATE]
proof (prove)
using this:
(a1, r1) = euclidean_circle_cmat (id H1)
(a2, r2) = euclidean_circle_cmat (id H2)
goal (1 subgoal):
1. A1 * A2 * cor (Re ((a1 - a2) * cnj (a1 - a2))) = (B2 * A1 - A2 * B1) * (C2 * A1 - C1 * A2) / (A1 * A2)
[PROOF STEP]
using HH1 HH2 * \<open>A1 \<noteq> 0\<close> \<open>A2 \<noteq> 0\<close> \<open>cnj A1 = A1\<close> \<open>cnj A2 = A2\<close>
[PROOF STATE]
proof (prove)
using this:
(a1, r1) = euclidean_circle_cmat (id H1)
(a2, r2) = euclidean_circle_cmat (id H2)
H1 = (A1, B1, C1, D1)
H2 = (A2, B2, C2, D2)
is_real A1
is_real A2
is_real D1
is_real D2
cnj B1 = C1
cnj B2 = C2
A1 \<noteq> 0
A2 \<noteq> 0
cnj A1 = A1
cnj A2 = A2
goal (1 subgoal):
1. A1 * A2 * cor (Re ((a1 - a2) * cnj (a1 - a2))) = (B2 * A1 - A2 * B1) * (C2 * A1 - C1 * A2) / (A1 * A2)
[PROOF STEP]
unfolding Let_def
[PROOF STATE]
proof (prove)
using this:
(a1, r1) = euclidean_circle_cmat (id H1)
(a2, r2) = euclidean_circle_cmat (id H2)
H1 = (A1, B1, C1, D1)
H2 = (A2, B2, C2, D2)
is_real A1
is_real A2
is_real D1
is_real D2
cnj B1 = C1
cnj B2 = C2
A1 \<noteq> 0
A2 \<noteq> 0
cnj A1 = A1
cnj A2 = A2
goal (1 subgoal):
1. A1 * A2 * cor (Re ((a1 - a2) * cnj (a1 - a2))) = (B2 * A1 - A2 * B1) * (C2 * A1 - C1 * A2) / (A1 * A2)
[PROOF STEP]
apply (subst complex_of_real_Re)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<lbrakk>(a1, r1) = euclidean_circle_cmat (id H1); (a2, r2) = euclidean_circle_cmat (id H2); H1 = (A1, B1, C1, D1); H2 = (A2, B2, C2, D2); is_real A1; is_real A2; is_real D1; is_real D2; cnj B1 = C1; cnj B2 = C2; A1 \<noteq> 0; A2 \<noteq> 0; cnj A1 = A1; cnj A2 = A2\<rbrakk> \<Longrightarrow> is_real ((a1 - a2) * cnj (a1 - a2))
2. \<lbrakk>(a1, r1) = euclidean_circle_cmat (id H1); (a2, r2) = euclidean_circle_cmat (id H2); H1 = (A1, B1, C1, D1); H2 = (A2, B2, C2, D2); is_real A1; is_real A2; is_real D1; is_real D2; cnj B1 = C1; cnj B2 = C2; A1 \<noteq> 0; A2 \<noteq> 0; cnj A1 = A1; cnj A2 = A2\<rbrakk> \<Longrightarrow> A1 * A2 * ((a1 - a2) * cnj (a1 - a2)) = (B2 * A1 - A2 * B1) * (C2 * A1 - C1 * A2) / (A1 * A2)
[PROOF STEP]
apply (simp add: field_simps)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>(a1, r1) = euclidean_circle_cmat (id H1); (a2, r2) = euclidean_circle_cmat (id H2); H1 = (A1, B1, C1, D1); H2 = (A2, B2, C2, D2); is_real A1; is_real A2; is_real D1; is_real D2; cnj B1 = C1; cnj B2 = C2; A1 \<noteq> 0; A2 \<noteq> 0; cnj A1 = A1; cnj A2 = A2\<rbrakk> \<Longrightarrow> A1 * A2 * ((a1 - a2) * cnj (a1 - a2)) = (B2 * A1 - A2 * B1) * (C2 * A1 - C1 * A2) / (A1 * A2)
[PROOF STEP]
apply (simp add: complex_mult_cnj_cmod power2_eq_square)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>a1 = - (B1 / A1) \<and> r1 = sqrt (Re ((B1 * C1 - A1 * D1) / (A1 * A1))); a2 = - (B2 / A2) \<and> r2 = sqrt (Re ((B2 * C2 - A2 * D2) / (A2 * A2))); H1 = (A1, B1, C1, D1); H2 = (A2, B2, C2, D2); is_real A1; is_real A2; is_real D1; is_real D2; cnj B1 = C1; cnj B2 = C2; A1 \<noteq> 0; A2 \<noteq> 0; cnj A1 = A1; cnj A2 = A2\<rbrakk> \<Longrightarrow> A1 * A2 * ((B2 / A2 - B1 / A1) * (C2 / A2 - C1 / A1)) = (B2 * A1 - A2 * B1) * (C2 * A1 - C1 * A2) / (A1 * A2)
[PROOF STEP]
apply (simp add: field_simps)
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done
[PROOF STATE]
proof (state)
this:
A1 * A2 * cor ((cdist a2 a1)\<^sup>2) = (B2 * A1 - A2 * B1) * (C2 * A1 - C1 * A2) / (A1 * A2)
goal (1 subgoal):
1. A1 * A2 * cor ((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2)
[PROOF STEP]
have 2: "A1*A2*cor (-r1\<^sup>2) = A2*D1 - B1*C1*A2/A1"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. A1 * A2 * cor (- r1\<^sup>2) = A2 * D1 - B1 * C1 * A2 / A1
[PROOF STEP]
using \<open>(a1, r1) = euclidean_circle_cmat (id H1)\<close>
[PROOF STATE]
proof (prove)
using this:
(a1, r1) = euclidean_circle_cmat (id H1)
goal (1 subgoal):
1. A1 * A2 * cor (- r1\<^sup>2) = A2 * D1 - B1 * C1 * A2 / A1
[PROOF STEP]
using HH1 ** * *** \<open>A1 \<noteq> 0\<close>
[PROOF STATE]
proof (prove)
using this:
(a1, r1) = euclidean_circle_cmat (id H1)
H1 = (A1, B1, C1, D1)
0 < Re ((B1 * C1 - A1 * D1) / (A1 * A1))
0 < Re ((B2 * C2 - A2 * D2) / (A2 * A2))
is_real A1
is_real A2
is_real D1
is_real D2
cnj B1 = C1
cnj B2 = C2
is_real ((B1 * C1 - A1 * D1) / (A1 * A1)) \<and> is_real ((B2 * C2 - A2 * D2) / (A2 * A2))
A1 \<noteq> 0
goal (1 subgoal):
1. A1 * A2 * cor (- r1\<^sup>2) = A2 * D1 - B1 * C1 * A2 / A1
[PROOF STEP]
by (simp add: power2_eq_square field_simps)
[PROOF STATE]
proof (state)
this:
A1 * A2 * cor (- r1\<^sup>2) = A2 * D1 - B1 * C1 * A2 / A1
goal (1 subgoal):
1. A1 * A2 * cor ((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2)
[PROOF STEP]
have 3: "A1*A2*cor (-r2\<^sup>2) = A1*D2 - B2*C2*A1/A2"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. A1 * A2 * cor (- r2\<^sup>2) = A1 * D2 - B2 * C2 * A1 / A2
[PROOF STEP]
using \<open>(a2, r2) = euclidean_circle_cmat (id H2)\<close>
[PROOF STATE]
proof (prove)
using this:
(a2, r2) = euclidean_circle_cmat (id H2)
goal (1 subgoal):
1. A1 * A2 * cor (- r2\<^sup>2) = A1 * D2 - B2 * C2 * A1 / A2
[PROOF STEP]
using HH2 ** * *** \<open>A2 \<noteq> 0\<close>
[PROOF STATE]
proof (prove)
using this:
(a2, r2) = euclidean_circle_cmat (id H2)
H2 = (A2, B2, C2, D2)
0 < Re ((B1 * C1 - A1 * D1) / (A1 * A1))
0 < Re ((B2 * C2 - A2 * D2) / (A2 * A2))
is_real A1
is_real A2
is_real D1
is_real D2
cnj B1 = C1
cnj B2 = C2
is_real ((B1 * C1 - A1 * D1) / (A1 * A1)) \<and> is_real ((B2 * C2 - A2 * D2) / (A2 * A2))
A2 \<noteq> 0
goal (1 subgoal):
1. A1 * A2 * cor (- r2\<^sup>2) = A1 * D2 - B2 * C2 * A1 / A2
[PROOF STEP]
by (simp add: power2_eq_square field_simps)
[PROOF STATE]
proof (state)
this:
A1 * A2 * cor (- r2\<^sup>2) = A1 * D2 - B2 * C2 * A1 / A2
goal (1 subgoal):
1. A1 * A2 * cor ((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2)
[PROOF STEP]
have "A1*A2*cor((cdist a2 a1)\<^sup>2) + A1*A2*cor(-r1\<^sup>2) + A1*A2*cor(-r2\<^sup>2) = mat_det_12 ?M1 ?M2"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. A1 * A2 * cor ((cdist a2 a1)\<^sup>2) + A1 * A2 * cor (- r1\<^sup>2) + A1 * A2 * cor (- r2\<^sup>2) = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2)
[PROOF STEP]
using \<open>A1 \<noteq> 0\<close> \<open>A2 \<noteq> 0\<close>
[PROOF STATE]
proof (prove)
using this:
A1 \<noteq> 0
A2 \<noteq> 0
goal (1 subgoal):
1. A1 * A2 * cor ((cdist a2 a1)\<^sup>2) + A1 * A2 * cor (- r1\<^sup>2) + A1 * A2 * cor (- r2\<^sup>2) = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2)
[PROOF STEP]
by (subst 1, subst 2, subst 3) (simp add: field_simps)
[PROOF STATE]
proof (state)
this:
A1 * A2 * cor ((cdist a2 a1)\<^sup>2) + A1 * A2 * cor (- r1\<^sup>2) + A1 * A2 * cor (- r2\<^sup>2) = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2)
goal (1 subgoal):
1. A1 * A2 * cor ((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2)
[PROOF STEP]
thus ?thesis
[PROOF STATE]
proof (prove)
using this:
A1 * A2 * cor ((cdist a2 a1)\<^sup>2) + A1 * A2 * cor (- r1\<^sup>2) + A1 * A2 * cor (- r2\<^sup>2) = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2)
goal (1 subgoal):
1. A1 * A2 * cor ((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2)
[PROOF STEP]
by (simp add: field_simps)
[PROOF STATE]
proof (state)
this:
A1 * A2 * cor ((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2)
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
A1 * A2 * cor ((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2)
goal (1 subgoal):
1. cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2)) = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2) / (2 * sgn A1 * sgn A2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2))))
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
A1 * A2 * cor ((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2)
goal (1 subgoal):
1. cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2)) = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2) / (2 * sgn A1 * sgn A2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2))))
[PROOF STEP]
have "A1 * A2 * cor (?x2) = 2 * sgn A1 * sgn A2 * cor (sqrt (Re ?d1) * sqrt (Re ?d2))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. A1 * A2 * cor (2 * r1 * r2) = 2 * sgn A1 * sgn A2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2)))
[PROOF STEP]
proof-
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. A1 * A2 * cor (2 * r1 * r2) = 2 * sgn A1 * sgn A2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2)))
[PROOF STEP]
have 1: "sqrt (Re (?d1/ (A1 * A1))) = sqrt (Re ?d1) / \<bar>Re A1\<bar>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. sqrt (Re ((B1 * C1 - A1 * D1) / (A1 * A1))) = sqrt (Re (B1 * C1 - A1 * D1)) / \<bar>Re A1\<bar>
[PROOF STEP]
using \<open>A1 \<noteq> 0\<close> \<open>is_real A1\<close>
[PROOF STATE]
proof (prove)
using this:
A1 \<noteq> 0
is_real A1
goal (1 subgoal):
1. sqrt (Re ((B1 * C1 - A1 * D1) / (A1 * A1))) = sqrt (Re (B1 * C1 - A1 * D1)) / \<bar>Re A1\<bar>
[PROOF STEP]
by (subst Re_divide_real, simp, simp, subst real_sqrt_divide, simp)
[PROOF STATE]
proof (state)
this:
sqrt (Re ((B1 * C1 - A1 * D1) / (A1 * A1))) = sqrt (Re (B1 * C1 - A1 * D1)) / \<bar>Re A1\<bar>
goal (1 subgoal):
1. A1 * A2 * cor (2 * r1 * r2) = 2 * sgn A1 * sgn A2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2)))
[PROOF STEP]
have 2: "sqrt (Re (?d2/ (A2 * A2))) = sqrt (Re ?d2) / \<bar>Re A2\<bar>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. sqrt (Re ((B2 * C2 - A2 * D2) / (A2 * A2))) = sqrt (Re (B2 * C2 - A2 * D2)) / \<bar>Re A2\<bar>
[PROOF STEP]
using \<open>A2 \<noteq> 0\<close> \<open>is_real A2\<close>
[PROOF STATE]
proof (prove)
using this:
A2 \<noteq> 0
is_real A2
goal (1 subgoal):
1. sqrt (Re ((B2 * C2 - A2 * D2) / (A2 * A2))) = sqrt (Re (B2 * C2 - A2 * D2)) / \<bar>Re A2\<bar>
[PROOF STEP]
by (subst Re_divide_real, simp, simp, subst real_sqrt_divide, simp)
[PROOF STATE]
proof (state)
this:
sqrt (Re ((B2 * C2 - A2 * D2) / (A2 * A2))) = sqrt (Re (B2 * C2 - A2 * D2)) / \<bar>Re A2\<bar>
goal (1 subgoal):
1. A1 * A2 * cor (2 * r1 * r2) = 2 * sgn A1 * sgn A2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2)))
[PROOF STEP]
have "sgn A1 = A1 / cor \<bar>Re A1\<bar>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. sgn A1 = A1 / cor \<bar>Re A1\<bar>
[PROOF STEP]
using \<open>is_real A1\<close>
[PROOF STATE]
proof (prove)
using this:
is_real A1
goal (1 subgoal):
1. sgn A1 = A1 / cor \<bar>Re A1\<bar>
[PROOF STEP]
unfolding sgn_eq
[PROOF STATE]
proof (prove)
using this:
is_real A1
goal (1 subgoal):
1. A1 / cor (cmod A1) = A1 / cor \<bar>Re A1\<bar>
[PROOF STEP]
by (simp add: cmod_eq_Re)
[PROOF STATE]
proof (state)
this:
sgn A1 = A1 / cor \<bar>Re A1\<bar>
goal (1 subgoal):
1. A1 * A2 * cor (2 * r1 * r2) = 2 * sgn A1 * sgn A2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2)))
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
sgn A1 = A1 / cor \<bar>Re A1\<bar>
goal (1 subgoal):
1. A1 * A2 * cor (2 * r1 * r2) = 2 * sgn A1 * sgn A2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2)))
[PROOF STEP]
have "sgn A2 = A2 / cor \<bar>Re A2\<bar>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. sgn A2 = A2 / cor \<bar>Re A2\<bar>
[PROOF STEP]
using \<open>is_real A2\<close>
[PROOF STATE]
proof (prove)
using this:
is_real A2
goal (1 subgoal):
1. sgn A2 = A2 / cor \<bar>Re A2\<bar>
[PROOF STEP]
unfolding sgn_eq
[PROOF STATE]
proof (prove)
using this:
is_real A2
goal (1 subgoal):
1. A2 / cor (cmod A2) = A2 / cor \<bar>Re A2\<bar>
[PROOF STEP]
by (simp add: cmod_eq_Re)
[PROOF STATE]
proof (state)
this:
sgn A2 = A2 / cor \<bar>Re A2\<bar>
goal (1 subgoal):
1. A1 * A2 * cor (2 * r1 * r2) = 2 * sgn A1 * sgn A2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2)))
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
sgn A1 = A1 / cor \<bar>Re A1\<bar>
sgn A2 = A2 / cor \<bar>Re A2\<bar>
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
sgn A1 = A1 / cor \<bar>Re A1\<bar>
sgn A2 = A2 / cor \<bar>Re A2\<bar>
goal (1 subgoal):
1. A1 * A2 * cor (2 * r1 * r2) = 2 * sgn A1 * sgn A2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2)))
[PROOF STEP]
using \<open>(a1, r1) = euclidean_circle_cmat (id H1)\<close> \<open>(a2, r2) = euclidean_circle_cmat (id H2)\<close> HH1 HH2
[PROOF STATE]
proof (prove)
using this:
sgn A1 = A1 / cor \<bar>Re A1\<bar>
sgn A2 = A2 / cor \<bar>Re A2\<bar>
(a1, r1) = euclidean_circle_cmat (id H1)
(a2, r2) = euclidean_circle_cmat (id H2)
H1 = (A1, B1, C1, D1)
H2 = (A2, B2, C2, D2)
goal (1 subgoal):
1. A1 * A2 * cor (2 * r1 * r2) = 2 * sgn A1 * sgn A2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2)))
[PROOF STEP]
using *** \<open>is_real A1\<close> \<open>is_real A2\<close>
[PROOF STATE]
proof (prove)
using this:
sgn A1 = A1 / cor \<bar>Re A1\<bar>
sgn A2 = A2 / cor \<bar>Re A2\<bar>
(a1, r1) = euclidean_circle_cmat (id H1)
(a2, r2) = euclidean_circle_cmat (id H2)
H1 = (A1, B1, C1, D1)
H2 = (A2, B2, C2, D2)
is_real ((B1 * C1 - A1 * D1) / (A1 * A1)) \<and> is_real ((B2 * C2 - A2 * D2) / (A2 * A2))
is_real A1
is_real A2
goal (1 subgoal):
1. A1 * A2 * cor (2 * r1 * r2) = 2 * sgn A1 * sgn A2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2)))
[PROOF STEP]
by simp (subst 1, subst 2, simp)
[PROOF STATE]
proof (state)
this:
A1 * A2 * cor (2 * r1 * r2) = 2 * sgn A1 * sgn A2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2)))
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
A1 * A2 * cor (2 * r1 * r2) = 2 * sgn A1 * sgn A2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2)))
goal (1 subgoal):
1. cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2)) = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2) / (2 * sgn A1 * sgn A2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2))))
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
A1 * A2 * cor ((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2)
A1 * A2 * cor (2 * r1 * r2) = 2 * sgn A1 * sgn A2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2)))
[PROOF STEP]
have "(A1 * A2 * cor ?x1) / (A1 * A2 * (cor ?x2)) =
mat_det_12 ?M1 ?M2 / (2 * sgn A1 * sgn A2 * cor (sqrt (Re ?d1) * sqrt (Re ?d2)))"
[PROOF STATE]
proof (prove)
using this:
A1 * A2 * cor ((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2)
A1 * A2 * cor (2 * r1 * r2) = 2 * sgn A1 * sgn A2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2)))
goal (1 subgoal):
1. A1 * A2 * cor ((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (A1 * A2 * cor (2 * r1 * r2)) = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2) / (2 * sgn A1 * sgn A2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2))))
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
A1 * A2 * cor ((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (A1 * A2 * cor (2 * r1 * r2)) = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2) / (2 * sgn A1 * sgn A2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2))))
goal (1 subgoal):
1. cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2)) = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2) / (2 * sgn A1 * sgn A2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2))))
[PROOF STEP]
thus ?thesis
[PROOF STATE]
proof (prove)
using this:
A1 * A2 * cor ((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (A1 * A2 * cor (2 * r1 * r2)) = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2) / (2 * sgn A1 * sgn A2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2))))
goal (1 subgoal):
1. cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2)) = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2) / (2 * sgn A1 * sgn A2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2))))
[PROOF STEP]
using \<open>A1 \<noteq> 0\<close> \<open>A2 \<noteq> 0\<close>
[PROOF STATE]
proof (prove)
using this:
A1 * A2 * cor ((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (A1 * A2 * cor (2 * r1 * r2)) = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2) / (2 * sgn A1 * sgn A2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2))))
A1 \<noteq> 0
A2 \<noteq> 0
goal (1 subgoal):
1. cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2)) = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2) / (2 * sgn A1 * sgn A2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2))))
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2)) = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2) / (2 * sgn A1 * sgn A2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2))))
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2)) = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2) / (2 * sgn A1 * sgn A2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2))))
goal (1 subgoal):
1. Re (mat_det_12 H1 H2) / (2 * sqrt (Re (mat_det H1 * mat_det H2))) = Re (sgn A1) * Re (sgn A2) * (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))
[PROOF STEP]
hence "cor ?x * sgn A1 * sgn A2 = mat_det_12 ?M1 ?M2 / (2 * cor (sqrt (Re ?d1) * sqrt (Re ?d2)))"
[PROOF STATE]
proof (prove)
using this:
cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2)) = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2) / (2 * sgn A1 * sgn A2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2))))
goal (1 subgoal):
1. cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2)) * sgn A1 * sgn A2 = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2) / (2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2))))
[PROOF STEP]
using \<open>A1 \<noteq> 0\<close> \<open>A2 \<noteq> 0\<close>
[PROOF STATE]
proof (prove)
using this:
cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2)) = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2) / (2 * sgn A1 * sgn A2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2))))
A1 \<noteq> 0
A2 \<noteq> 0
goal (1 subgoal):
1. cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2)) * sgn A1 * sgn A2 = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2) / (2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2))))
[PROOF STEP]
by (simp add: sgn_zero_iff)
[PROOF STATE]
proof (state)
this:
cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2)) * sgn A1 * sgn A2 = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2) / (2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2))))
goal (1 subgoal):
1. Re (mat_det_12 H1 H2) / (2 * sqrt (Re (mat_det H1 * mat_det H2))) = Re (sgn A1) * Re (sgn A2) * (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2)) * sgn A1 * sgn A2 = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2) / (2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2))))
goal (1 subgoal):
1. Re (mat_det_12 H1 H2) / (2 * sqrt (Re (mat_det H1 * mat_det H2))) = Re (sgn A1) * Re (sgn A2) * (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))
[PROOF STEP]
have "Re (cor ?x * sgn A1 * sgn A2) = Re (sgn A1) * Re (sgn A2) * ?x"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. Re (cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2)) * sgn A1 * sgn A2) = Re (sgn A1) * Re (sgn A2) * (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))
[PROOF STEP]
proof-
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. Re (cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2)) * sgn A1 * sgn A2) = Re (sgn A1) * Re (sgn A2) * (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))
[PROOF STEP]
have "is_real (cor ?x)" "is_real (sgn A1)" "is_real (sgn A2)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. is_real (cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))) &&& is_real (sgn A1) &&& is_real (sgn A2)
[PROOF STEP]
using \<open>is_real A1\<close> \<open>is_real A2\<close> Im_complex_of_real[of ?x]
[PROOF STATE]
proof (prove)
using this:
is_real A1
is_real A2
is_real (cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2)))
goal (1 subgoal):
1. is_real (cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))) &&& is_real (sgn A1) &&& is_real (sgn A2)
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
is_real (cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2)))
is_real (sgn A1)
is_real (sgn A2)
goal (1 subgoal):
1. Re (cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2)) * sgn A1 * sgn A2) = Re (sgn A1) * Re (sgn A2) * (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))
[PROOF STEP]
thus ?thesis
[PROOF STATE]
proof (prove)
using this:
is_real (cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2)))
is_real (sgn A1)
is_real (sgn A2)
goal (1 subgoal):
1. Re (cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2)) * sgn A1 * sgn A2) = Re (sgn A1) * Re (sgn A2) * (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))
[PROOF STEP]
using Re_complex_of_real[of ?x]
[PROOF STATE]
proof (prove)
using this:
is_real (cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2)))
is_real (sgn A1)
is_real (sgn A2)
Re (cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))) = ((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2)
goal (1 subgoal):
1. Re (cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2)) * sgn A1 * sgn A2) = Re (sgn A1) * Re (sgn A2) * (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))
[PROOF STEP]
by (subst Re_mult_real3, auto simp add: field_simps)
[PROOF STATE]
proof (state)
this:
Re (cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2)) * sgn A1 * sgn A2) = Re (sgn A1) * Re (sgn A2) * (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
Re (cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2)) * sgn A1 * sgn A2) = Re (sgn A1) * Re (sgn A2) * (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))
goal (1 subgoal):
1. Re (mat_det_12 H1 H2) / (2 * sqrt (Re (mat_det H1 * mat_det H2))) = Re (sgn A1) * Re (sgn A2) * (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
Re (cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2)) * sgn A1 * sgn A2) = Re (sgn A1) * Re (sgn A2) * (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))
goal (1 subgoal):
1. Re (mat_det_12 H1 H2) / (2 * sqrt (Re (mat_det H1 * mat_det H2))) = Re (sgn A1) * Re (sgn A2) * (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))
[PROOF STEP]
have *: "sqrt (Re ?D1) * sqrt (Re ?D2) = sqrt (Re ?d1) * sqrt (Re ?d2)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. sqrt (Re (mat_det H1)) * sqrt (Re (mat_det H2)) = sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2))
[PROOF STEP]
using HH1 HH2
[PROOF STATE]
proof (prove)
using this:
H1 = (A1, B1, C1, D1)
H2 = (A2, B2, C2, D2)
goal (1 subgoal):
1. sqrt (Re (mat_det H1)) * sqrt (Re (mat_det H2)) = sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2))
[PROOF STEP]
by (subst real_sqrt_mult[symmetric])+ (simp add: field_simps)
[PROOF STATE]
proof (state)
this:
sqrt (Re (mat_det H1)) * sqrt (Re (mat_det H2)) = sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2))
goal (1 subgoal):
1. Re (mat_det_12 H1 H2) / (2 * sqrt (Re (mat_det H1 * mat_det H2))) = Re (sgn A1) * Re (sgn A2) * (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))
[PROOF STEP]
have "2 * (sqrt (Re (?D1 * ?D2))) \<noteq> 0"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. 2 * sqrt (Re (mat_det H1 * mat_det H2)) \<noteq> 0
[PROOF STEP]
using \<open>Re ?d1 > 0\<close> \<open>Re ?d2 > 0\<close> HH1 HH2 \<open>is_real A1\<close> \<open>is_real A2\<close> \<open>is_real D1\<close> \<open>is_real D2\<close>
[PROOF STATE]
proof (prove)
using this:
0 < Re (B1 * C1 - A1 * D1)
0 < Re (B2 * C2 - A2 * D2)
H1 = (A1, B1, C1, D1)
H2 = (A2, B2, C2, D2)
is_real A1
is_real A2
is_real D1
is_real D2
goal (1 subgoal):
1. 2 * sqrt (Re (mat_det H1 * mat_det H2)) \<noteq> 0
[PROOF STEP]
using hh mat_det_hermitean_real[of "H1"]
[PROOF STATE]
proof (prove)
using this:
0 < Re (B1 * C1 - A1 * D1)
0 < Re (B2 * C2 - A2 * D2)
H1 = (A1, B1, C1, D1)
H2 = (A2, B2, C2, D2)
is_real A1
is_real A2
is_real D1
is_real D2
hermitean H1 \<and> H1 \<noteq> mat_zero
hermitean H2 \<and> H2 \<noteq> mat_zero
hermitean H1 \<Longrightarrow> is_real (mat_det H1)
goal (1 subgoal):
1. 2 * sqrt (Re (mat_det H1 * mat_det H2)) \<noteq> 0
[PROOF STEP]
by (subst Re_mult_real, auto)
[PROOF STATE]
proof (state)
this:
2 * sqrt (Re (mat_det H1 * mat_det H2)) \<noteq> 0
goal (1 subgoal):
1. Re (mat_det_12 H1 H2) / (2 * sqrt (Re (mat_det H1 * mat_det H2))) = Re (sgn A1) * Re (sgn A2) * (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))
[PROOF STEP]
hence **: "Re (?D12 / (2 * cor (sqrt (Re (?D1 * ?D2))))) = Re (?D12) / (2 * (sqrt (Re (?D1 * ?D2))))"
[PROOF STATE]
proof (prove)
using this:
2 * sqrt (Re (mat_det H1 * mat_det H2)) \<noteq> 0
goal (1 subgoal):
1. Re (mat_det_12 H1 H2 / (2 * cor (sqrt (Re (mat_det H1 * mat_det H2))))) = Re (mat_det_12 H1 H2) / (2 * sqrt (Re (mat_det H1 * mat_det H2)))
[PROOF STEP]
using \<open>Re ?d1 > 0\<close> \<open>Re ?d2 > 0\<close> HH1 HH2 \<open>is_real A1\<close> \<open>is_real A2\<close> \<open>is_real D1\<close> \<open>is_real D2\<close>
[PROOF STATE]
proof (prove)
using this:
2 * sqrt (Re (mat_det H1 * mat_det H2)) \<noteq> 0
0 < Re (B1 * C1 - A1 * D1)
0 < Re (B2 * C2 - A2 * D2)
H1 = (A1, B1, C1, D1)
H2 = (A2, B2, C2, D2)
is_real A1
is_real A2
is_real D1
is_real D2
goal (1 subgoal):
1. Re (mat_det_12 H1 H2 / (2 * cor (sqrt (Re (mat_det H1 * mat_det H2))))) = Re (mat_det_12 H1 H2) / (2 * sqrt (Re (mat_det H1 * mat_det H2)))
[PROOF STEP]
by (subst Re_divide_real) auto
[PROOF STATE]
proof (state)
this:
Re (mat_det_12 H1 H2 / (2 * cor (sqrt (Re (mat_det H1 * mat_det H2))))) = Re (mat_det_12 H1 H2) / (2 * sqrt (Re (mat_det H1 * mat_det H2)))
goal (1 subgoal):
1. Re (mat_det_12 H1 H2) / (2 * sqrt (Re (mat_det H1 * mat_det H2))) = Re (sgn A1) * Re (sgn A2) * (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))
[PROOF STEP]
have "Re (mat_det_12 ?M1 ?M2 / (2 * cor (sqrt (Re ?d1) * sqrt (Re ?d2)))) = Re (?D12) / (2 * (sqrt (Re (?D1 * ?D2))))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. Re (mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2) / (2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2))))) = Re (mat_det_12 H1 H2) / (2 * sqrt (Re (mat_det H1 * mat_det H2)))
[PROOF STEP]
using HH1 HH2 hh mat_det_hermitean_real[of "H1"]
[PROOF STATE]
proof (prove)
using this:
H1 = (A1, B1, C1, D1)
H2 = (A2, B2, C2, D2)
hermitean H1 \<and> H1 \<noteq> mat_zero
hermitean H2 \<and> H2 \<noteq> mat_zero
hermitean H1 \<Longrightarrow> is_real (mat_det H1)
goal (1 subgoal):
1. Re (mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2) / (2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2))))) = Re (mat_det_12 H1 H2) / (2 * sqrt (Re (mat_det H1 * mat_det H2)))
[PROOF STEP]
by (subst **[symmetric], subst Re_mult_real, simp, subst real_sqrt_mult, subst *, simp)
[PROOF STATE]
proof (state)
this:
Re (mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2) / (2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2))))) = Re (mat_det_12 H1 H2) / (2 * sqrt (Re (mat_det H1 * mat_det H2)))
goal (1 subgoal):
1. Re (mat_det_12 H1 H2) / (2 * sqrt (Re (mat_det H1 * mat_det H2))) = Re (sgn A1) * Re (sgn A2) * (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2)) * sgn A1 * sgn A2 = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2) / (2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2))))
Re (cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2)) * sgn A1 * sgn A2) = Re (sgn A1) * Re (sgn A2) * (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))
Re (mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2) / (2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2))))) = Re (mat_det_12 H1 H2) / (2 * sqrt (Re (mat_det H1 * mat_det H2)))
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2)) * sgn A1 * sgn A2 = mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2) / (2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2))))
Re (cor (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2)) * sgn A1 * sgn A2) = Re (sgn A1) * Re (sgn A2) * (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))
Re (mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2) / (2 * cor (sqrt (Re (B1 * C1 - A1 * D1)) * sqrt (Re (B2 * C2 - A2 * D2))))) = Re (mat_det_12 H1 H2) / (2 * sqrt (Re (mat_det H1 * mat_det H2)))
goal (1 subgoal):
1. Re (mat_det_12 H1 H2) / (2 * sqrt (Re (mat_det H1 * mat_det H2))) = Re (sgn A1) * Re (sgn A2) * (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
Re (mat_det_12 H1 H2) / (2 * sqrt (Re (mat_det H1 * mat_det H2))) = Re (sgn A1) * Re (sgn A2) * (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
Re (mat_det_12 H1 H2) / (2 * sqrt (Re (mat_det H1 * mat_det H2))) = Re (sgn A1) * Re (sgn A2) * (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))
goal (1 subgoal):
1. \<And>r1 r2 a1 H1 a2 H2 r1a r2a a1a H1a a2a H2a. \<lbrakk>hermitean H1 \<and> H1 \<noteq> mat_zero; hermitean H2 \<and> H2 \<noteq> mat_zero; 0 < r1; 0 < r2; (a1, r1) = euclidean_circle_cmat (id H1); (a2, r2) = euclidean_circle_cmat (id H2); \<not> circline_A0_cmat (id H1); \<not> circline_A0_cmat (id H2); circline_type_cmat (id H1) < 0; circline_type_cmat (id H2) < 0; 0 < r1a; 0 < r2a; (a1a, r1a) = euclidean_circle_clmat (id H1a); (a2a, r2a) = euclidean_circle_clmat (id H2a); \<not> circline_A0_clmat (id H1a); \<not> circline_A0_clmat (id H2a); circline_type_clmat (id H1a) < 0; circline_type_clmat (id H2a) < 0\<rbrakk> \<Longrightarrow> cos_angle_cmat H1 H2 = sgn_bool (pos_oriented_cmat H1 = pos_oriented_cmat H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
have **: "pos_oriented_cmat H1 \<longleftrightarrow> Re A1 > 0" "pos_oriented_cmat H2 \<longleftrightarrow> Re A2 > 0"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. pos_oriented_cmat H1 = (0 < Re A1) &&& pos_oriented_cmat H2 = (0 < Re A2)
[PROOF STEP]
using \<open>Re A1 \<noteq> 0\<close> HH1 \<open>Re A2 \<noteq> 0\<close> HH2
[PROOF STATE]
proof (prove)
using this:
Re A1 \<noteq> 0
H1 = (A1, B1, C1, D1)
Re A2 \<noteq> 0
H2 = (A2, B2, C2, D2)
goal (1 subgoal):
1. pos_oriented_cmat H1 = (0 < Re A1) &&& pos_oriented_cmat H2 = (0 < Re A2)
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
pos_oriented_cmat H1 = (0 < Re A1)
pos_oriented_cmat H2 = (0 < Re A2)
goal (1 subgoal):
1. \<And>r1 r2 a1 H1 a2 H2 r1a r2a a1a H1a a2a H2a. \<lbrakk>hermitean H1 \<and> H1 \<noteq> mat_zero; hermitean H2 \<and> H2 \<noteq> mat_zero; 0 < r1; 0 < r2; (a1, r1) = euclidean_circle_cmat (id H1); (a2, r2) = euclidean_circle_cmat (id H2); \<not> circline_A0_cmat (id H1); \<not> circline_A0_cmat (id H2); circline_type_cmat (id H1) < 0; circline_type_cmat (id H2) < 0; 0 < r1a; 0 < r2a; (a1a, r1a) = euclidean_circle_clmat (id H1a); (a2a, r2a) = euclidean_circle_clmat (id H2a); \<not> circline_A0_clmat (id H1a); \<not> circline_A0_clmat (id H2a); circline_type_clmat (id H1a) < 0; circline_type_clmat (id H2a) < 0\<rbrakk> \<Longrightarrow> cos_angle_cmat H1 H2 = sgn_bool (pos_oriented_cmat H1 = pos_oriented_cmat H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
show "cos_angle_cmat H1 H2 = sgn_bool (pos_oriented_cmat H1 = pos_oriented_cmat H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. cos_angle_cmat H1 H2 = sgn_bool (pos_oriented_cmat H1 = pos_oriented_cmat H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
unfolding Let_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. cos_angle_cmat H1 H2 = sgn_bool (pos_oriented_cmat H1 = pos_oriented_cmat H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
using \<open>r1 > 0\<close> \<open>r2 > 0\<close>
[PROOF STATE]
proof (prove)
using this:
0 < r1
0 < r2
goal (1 subgoal):
1. cos_angle_cmat H1 H2 = sgn_bool (pos_oriented_cmat H1 = pos_oriented_cmat H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
unfolding cos_angle_cmat_def
[PROOF STATE]
proof (prove)
using this:
0 < r1
0 < r2
goal (1 subgoal):
1. - Re (mat_det_12 H1 H2) / (2 * sqrt (Re (mat_det H1 * mat_det H2))) = sgn_bool (pos_oriented_cmat H1 = pos_oriented_cmat H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
apply (subst divide_minus_left)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>0 < r1; 0 < r2\<rbrakk> \<Longrightarrow> - (Re (mat_det_12 H1 H2) / (2 * sqrt (Re (mat_det H1 * mat_det H2)))) = sgn_bool (pos_oriented_cmat H1 = pos_oriented_cmat H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
apply (subst *)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>0 < r1; 0 < r2\<rbrakk> \<Longrightarrow> - (Re (sgn A1) * Re (sgn A2) * (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))) = sgn_bool (pos_oriented_cmat H1 = pos_oriented_cmat H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
apply (subst Re_sgn[OF \<open>is_real A1\<close> \<open>A1 \<noteq> 0\<close>], subst Re_sgn[OF \<open>is_real A2\<close> \<open>A2 \<noteq> 0\<close>])
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>0 < r1; 0 < r2\<rbrakk> \<Longrightarrow> - (sgn_bool (0 < Re A1) * sgn_bool (0 < Re A2) * (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))) = sgn_bool (pos_oriented_cmat H1 = pos_oriented_cmat H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
apply (subst **, subst **)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>0 < r1; 0 < r2\<rbrakk> \<Longrightarrow> - (sgn_bool (0 < Re A1) * sgn_bool (0 < Re A2) * (((cdist a2 a1)\<^sup>2 - r1\<^sup>2 - r2\<^sup>2) / (2 * r1 * r2))) = sgn_bool ((0 < Re A1) = (0 < Re A2)) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
apply (simp add: field_simps)
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done
[PROOF STATE]
proof (state)
this:
cos_angle_cmat H1 H2 = sgn_bool (pos_oriented_cmat H1 = pos_oriented_cmat H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
cos_angle H1 H2 = sgn_bool (pos_oriented H1 = pos_oriented H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
goal (1 subgoal):
1. cos_angle H1 H2 = cos (ang_circ E a1 a2 (pos_oriented H1) (pos_oriented H2))
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
cos (ang_circ E a1 a2 (pos_oriented H1) (pos_oriented H2)) = sgn_bool (pos_oriented H1 = pos_oriented H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
cos_angle H1 H2 = sgn_bool (pos_oriented H1 = pos_oriented H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
cos (ang_circ E a1 a2 (pos_oriented H1) (pos_oriented H2)) = sgn_bool (pos_oriented H1 = pos_oriented H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
cos_angle H1 H2 = sgn_bool (pos_oriented H1 = pos_oriented H2) * (r1\<^sup>2 + r2\<^sup>2 - (cdist a2 a1)\<^sup>2) / (2 * r1 * r2)
goal (1 subgoal):
1. cos_angle H1 H2 = cos (ang_circ E a1 a2 (pos_oriented H1) (pos_oriented H2))
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
cos_angle H1 H2 = cos (ang_circ E a1 a2 (pos_oriented H1) (pos_oriented H2))
goal:
No subgoals!
[PROOF STEP]
qed |
{-# OPTIONS --without-K --safe #-}
open import Categories.Category.Core
module Categories.Morphism.Extremal.Properties {o ℓ e} (𝒞 : Category o ℓ e) where
open import Level
open import Function using (_$_)
open import Categories.Diagram.Equalizer 𝒞
open import Categories.Diagram.Coequalizer 𝒞
open import Categories.Morphism 𝒞
open import Categories.Morphism.Extremal 𝒞
open import Categories.Morphism.Properties 𝒞
open import Categories.Morphism.Reasoning 𝒞
open import Categories.Morphism.Regular 𝒞
open Category 𝒞
open HomReasoning
private
variable
A B : Obj
f g : A ⇒ B
--------------------------------------------------------------------------------
-- Extremal Epimorphisms
RegularEpi⇒IsExtremalEpi : ∀ {A B} {f : A ⇒ B} (e : RegularEpi f) → IsExtremalEpi (RegularEpi⇒Epi e)
RegularEpi⇒IsExtremalEpi {A = A} {B = B} {f = f} regular {X = X} {i = i} {g = k} i-mono f≈i∘k =
record
{ inv = i⁻¹
; iso = record
{ isoˡ = isoˡ
; isoʳ = isoʳ
}
}
where
open RegularEpi regular renaming (g to r; h to s)
open IsCoequalizer coequalizer
i⁻¹ : B ⇒ X
i⁻¹ = coequalize $ i-mono (k ∘ s) (k ∘ r) $ begin
i ∘ k ∘ s ≈⟨ pullˡ (⟺ f≈i∘k) ⟩
f ∘ s ≈⟨ equality ⟩
f ∘ r ≈⟨ pushˡ f≈i∘k ⟩
i ∘ k ∘ r ∎
isoʳ : i ∘ i⁻¹ ≈ id
isoʳ = RegularEpi⇒Epi regular (i ∘ i⁻¹) id $ begin
(i ∘ i⁻¹) ∘ f ≈⟨ pullʳ (⟺ universal) ⟩
i ∘ k ≈˘⟨ f≈i∘k ⟩
f ≈˘⟨ identityˡ ⟩
id ∘ f ∎
isoˡ : i⁻¹ ∘ i ≈ id
isoˡ = i-mono (i⁻¹ ∘ i) id $ begin
i ∘ i⁻¹ ∘ i ≈⟨ cancelˡ isoʳ ⟩
i ≈˘⟨ identityʳ ⟩
i ∘ id ∎
RegularEpi⇒ExtremalEpi : (e : RegularEpi f) → ExtremalEpi f
RegularEpi⇒ExtremalEpi e = record
{ epi = RegularEpi⇒Epi e
; extremal = RegularEpi⇒IsExtremalEpi e
}
ExtremalEpi-∘₂ : ExtremalEpi (f ∘ g) → ExtremalEpi f
ExtremalEpi-∘₂ fg-extremal = record
{ epi = Epi-∘₂ epi
; extremal = λ i-mono eq → extremal i-mono (pushˡ eq)
}
where
open ExtremalEpi fg-extremal
ExtremalEpi-∘ : ∀ {A B C} {f : B ⇒ C} {g : A ⇒ B} → ExtremalEpi f → RegularEpi g → ExtremalEpi (f ∘ g)
ExtremalEpi-∘ {A = A} {B = B} {C = C} {f = f} {g = g} f-extremal g-regular = record
{ epi = fg-epi
; extremal = fg-extremal
}
where
module f-extremal = ExtremalEpi f-extremal
module g-regular = RegularEpi g-regular
open IsCoequalizer g-regular.coequalizer
g-epi : Epi g
g-epi = RegularEpi⇒Epi g-regular
fg-epi : Epi (f ∘ g)
fg-epi = Epi-∘ f-extremal.epi g-epi
fg-extremal : IsExtremalEpi fg-epi
fg-extremal {X = X} {i = i} {g = h} i-mono f∘g≈i∘h =
f-extremal.extremal i-mono $ g-epi _ _ $ begin
f ∘ g ≈⟨ f∘g≈i∘h ⟩
i ∘ h ≈⟨ pushʳ universal ⟩
(i ∘ k) ∘ g ∎
where
k : B ⇒ X
k = coequalize $ i-mono _ _ $ begin
i ∘ h ∘ g-regular.h ≈⟨ extendʳ (⟺ f∘g≈i∘h) ⟩
f ∘ g ∘ g-regular.h ≈⟨ refl⟩∘⟨ equality ⟩
f ∘ g ∘ g-regular.g ≈⟨ extendʳ f∘g≈i∘h ⟩
i ∘ h ∘ g-regular.g ∎
ExtremalEpi+Mono⇒IsIso : ExtremalEpi f → Mono f → IsIso f
ExtremalEpi+Mono⇒IsIso {f = f} f-extremal f-mono = extremal f-mono (⟺ identityʳ)
where
open ExtremalEpi f-extremal
--------------------------------------------------------------------------------
-- Extremal Monomorphisms
RegularMono⇒IsExtremalMono : ∀ {A B} {f : A ⇒ B} (m : RegularMono f) → IsExtremalMono (RegularMono⇒Mono m)
RegularMono⇒IsExtremalMono {A = A} {B = B} {f = f} regular {X = X} {g = k} {i = i} i-epi f≈k∘i =
record
{ inv = i⁻¹
; iso = record
{ isoˡ = isoˡ
; isoʳ = isoʳ
}
}
where
open RegularMono regular renaming (g to r; h to s)
open IsEqualizer equalizer
i⁻¹ : X ⇒ A
i⁻¹ = equalize $ i-epi (s ∘ k) (r ∘ k) $ begin
(s ∘ k) ∘ i ≈⟨ pullʳ (⟺ f≈k∘i) ⟩
s ∘ f ≈⟨ equality ⟩
r ∘ f ≈⟨ pushʳ f≈k∘i ⟩
(r ∘ k) ∘ i ∎
isoˡ : i⁻¹ ∘ i ≈ id
isoˡ = RegularMono⇒Mono regular (i⁻¹ ∘ i) id $ begin
f ∘ i⁻¹ ∘ i ≈⟨ pullˡ (⟺ universal) ⟩
k ∘ i ≈˘⟨ f≈k∘i ⟩
f ≈˘⟨ identityʳ ⟩
f ∘ id ∎
isoʳ : i ∘ i⁻¹ ≈ id
isoʳ = i-epi (i ∘ i⁻¹) id $ begin
(i ∘ i⁻¹) ∘ i ≈⟨ cancelʳ isoˡ ⟩
i ≈˘⟨ identityˡ ⟩
id ∘ i ∎
RegularMono⇒ExtremalMono : RegularMono f → ExtremalMono f
RegularMono⇒ExtremalMono m = record
{ mono = RegularMono⇒Mono m
; extremal = RegularMono⇒IsExtremalMono m
}
ExtremalMono-∘₂ : ExtremalMono (f ∘ g) → ExtremalMono g
ExtremalMono-∘₂ fg-extremal = record
{ mono = Mono-∘₂ mono
; extremal = λ i-epi eq → extremal i-epi (pushʳ eq)
}
where
open ExtremalMono fg-extremal
ExtremalMono-∘ : ∀ {A B C} {f : B ⇒ C} {g : A ⇒ B} → RegularMono f → ExtremalMono g → ExtremalMono (f ∘ g)
ExtremalMono-∘ {A = A} {B = B} {f = f} {g = g} f-regular g-extremal = record
{ mono = fg-mono
; extremal = fg-extremal
}
where
module f-regular = RegularMono f-regular
open IsEqualizer f-regular.equalizer
module g-extremal = ExtremalMono g-extremal
f-mono : Mono f
f-mono = (RegularMono⇒Mono f-regular)
fg-mono : Mono (f ∘ g)
fg-mono = Mono-∘ f-mono g-extremal.mono
fg-extremal : IsExtremalMono fg-mono
fg-extremal {X = X} {g = h} {i = e} e-epi f∘g≈h∘e =
g-extremal.extremal e-epi $ f-mono _ _ $ begin
f ∘ g ≈⟨ f∘g≈h∘e ⟩
h ∘ e ≈⟨ pushˡ universal ⟩
f ∘ k ∘ e ∎
where
k : X ⇒ B
k = equalize $ e-epi _ _ $ begin
(f-regular.h ∘ h) ∘ e ≈⟨ extendˡ (⟺ f∘g≈h∘e) ⟩
(f-regular.h ∘ f) ∘ g ≈⟨ equality ⟩∘⟨refl ⟩
(f-regular.g ∘ f) ∘ g ≈⟨ extendˡ f∘g≈h∘e ⟩
(f-regular.g ∘ h) ∘ e ∎
ExtremalMono+Epi⇒IsIso : ExtremalMono f → Epi f → IsIso f
ExtremalMono+Epi⇒IsIso {f = f} f-extremal f-epi = extremal f-epi (⟺ identityˡ)
where
open ExtremalMono f-extremal
--------------------------------------------------------------------------------
-- Extremal Morphisms in Balanced Categories
-- https://ncatlab.org/nlab/show/balanced+category
module _ (balanced : ∀ {A B} {f : A ⇒ B} → Mono f → Epi f → IsIso f) where
Mono+Epi⇒IsExtremalEpi : (e : Epi f) → IsExtremalEpi e
Mono+Epi⇒IsExtremalEpi {f = f} f-epi {i = i} {g = g} i-mono f≈i∘g = balanced i-mono i-epi
where
i-epi : Epi i
i-epi g₁ g₂ g₁∘i≈g₂∘i = f-epi g₁ g₂ $ begin
g₁ ∘ f ≈⟨ pushʳ f≈i∘g ⟩
(g₁ ∘ i) ∘ g ≈⟨ g₁∘i≈g₂∘i ⟩∘⟨refl ⟩
(g₂ ∘ i) ∘ g ≈⟨ pullʳ (⟺ f≈i∘g) ⟩
g₂ ∘ f ∎
Mono+Epi⇒IsExtremalMono : (m : Mono f) → IsExtremalMono m
Mono+Epi⇒IsExtremalMono {f = f} f-mono {g = g} {i = i} i-epi f≈g∘i = balanced i-mono i-epi
where
i-mono : Mono i
i-mono g₁ g₂ i∘g₁≈i∘g₂ = f-mono g₁ g₂ $ begin
f ∘ g₁ ≈⟨ pushˡ f≈g∘i ⟩
g ∘ i ∘ g₁ ≈⟨ refl⟩∘⟨ i∘g₁≈i∘g₂ ⟩
g ∘ i ∘ g₂ ≈⟨ pullˡ (⟺ f≈g∘i) ⟩
f ∘ g₂ ∎
|
State Before: F : Type ?u.48360
α : Type u_3
β : Type u_1
γ : Type u_2
δ : Type ?u.48372
inst✝⁷ : NonAssocSemiring α
inst✝⁶ : Preorder α
inst✝⁵ : NonAssocSemiring β
inst✝⁴ : Preorder β
inst✝³ : NonAssocSemiring γ
inst✝² : Preorder γ
inst✝¹ : NonAssocSemiring δ
inst✝ : Preorder δ
f₁ f₂ : β →+*o γ
g : α →+*o β
hg : Surjective ↑g
h : f₁ = f₂
⊢ OrderRingHom.comp f₁ g = OrderRingHom.comp f₂ g State After: no goals Tactic: rw [h] |
module Heat1D
using LinearAlgebra
using SparseArrays
include("structures.jl")
export FDHeatProblem, PeriodicBC, BEuler
include("constructors.jl")
export FDHeatProblem
include("assembly.jl")
export assemble_system!
include("solve.jl")
export solve_heat
end # module
|
section "Vertex Cover"
theory Approx_VC_Hoare
imports "HOL-Hoare.Hoare_Logic"
begin
text \<open>The algorithm is classical, the proof is based on and augments the one
by Berghammer and M\"uller-Olm \<^cite>\<open>"BerghammerM03"\<close>.\<close>
subsection "Graph"
text \<open>A graph is simply a set of edges, where an edge is a 2-element set.\<close>
definition vertex_cover :: "'a set set \<Rightarrow> 'a set \<Rightarrow> bool" where
"vertex_cover E C = (\<forall>e \<in> E. e \<inter> C \<noteq> {})"
abbreviation matching :: "'a set set \<Rightarrow> bool" where
"matching M \<equiv> pairwise disjnt M"
lemma card_matching_vertex_cover:
"\<lbrakk> finite C; matching M; M \<subseteq> E; vertex_cover E C \<rbrakk> \<Longrightarrow> card M \<le> card C"
apply(erule card_le_if_inj_on_rel[where r = "\<lambda>e v. v \<in> e"])
apply (meson disjnt_def disjnt_iff vertex_cover_def subsetCE)
by (meson disjnt_iff pairwise_def)
subsection "The Approximation Algorithm"
text \<open>Formulated using a simple(!) predefined Hoare-logic.
This leads to a streamlined proof based on standard invariant reasoning.
The nondeterministic selection of an element from a set \<open>F\<close> is simulated by @{term "SOME x. x \<in> F"}.
The \<open>SOME\<close> operator is built into HOL: @{term "SOME x. P x"} denotes some \<open>x\<close> that satisfies \<open>P\<close>
if such an \<open>x\<close> exists; otherwise it denotes an arbitrary element. Note that there is no
actual nondeterminism involved: @{term "SOME x. P x"} is some fixed element
but in general we don't know which one. Proofs about \<open>SOME\<close> are notoriously tedious.
Typically it involves showing first that @{prop "\<exists>x. P x"}. Then @{thm someI_ex} implies
@{prop"P (SOME x. P x)"}. There are a number of (more) useful related theorems:
just click on @{thm someI_ex} to be taken there.\<close>
text \<open>Convenient notation for choosing an arbitrary element from a set:\<close>
abbreviation "some A \<equiv> SOME x. x \<in> A"
locale Edges =
fixes E :: "'a set set"
assumes finE: "finite E"
assumes edges2: "e \<in> E \<Longrightarrow> card e = 2"
begin
text \<open>The invariant:\<close>
definition "inv_matching C F M =
(matching M \<and> M \<subseteq> E \<and> card C \<le> 2 * card M \<and> (\<forall>e \<in> M. \<forall>f \<in> F. e \<inter> f = {}))"
definition invar :: "'a set \<Rightarrow> 'a set set \<Rightarrow> bool" where
"invar C F = (F \<subseteq> E \<and> vertex_cover (E-F) C \<and> finite C \<and> (\<exists>M. inv_matching C F M))"
text \<open>Preservation of the invariant by the loop body:\<close>
lemma approx_vertex_cover:
"VARS C F
{True}
C := {};
F := E;
WHILE F \<noteq> {}
INV {invar C F}
DO C := C \<union> some F;
F := F - {e' \<in> F. some F \<inter> e' \<noteq> {}}
OD
{vertex_cover E C \<and> (\<forall>C'. finite C' \<and> vertex_cover E C' \<longrightarrow> card C \<le> 2 * card C')}"
proof (vcg, goal_cases)
case (1 C F)
have "inv_matching {} E {}" by (auto simp add: inv_matching_def)
with 1 show ?case by (auto simp add: invar_def vertex_cover_def)
next
case (2 C F)
thus ?case using invar_step[of F C] by(auto simp: Let_def)
next
case (3 C F)
then obtain M :: "'a set set" where
post: "vertex_cover E C" "matching M" "M \<subseteq> E" "card C \<le> 2 * card M"
by(auto simp: invar_def inv_matching_def)
have opt: "card C \<le> 2 * card C'" if C': "finite C'" "vertex_cover E C'" for C'
proof -
note post(4)
also have "2 * card M \<le> 2 * card C'"
using card_matching_vertex_cover[OF C'(1) post(2,3) C'(2)] by simp
finally show "card C \<le> 2 * card C'" .
qed
show ?case using post(1) opt by auto
qed
end (* locale Graph *)
subsection "Version for Hypergraphs"
text \<open>Almost the same. We assume that the degree of every edge is bounded.\<close>
locale Bounded_Hypergraph =
fixes E :: "'a set set"
fixes k :: nat
assumes finE: "finite E"
assumes edge_bnd: "e \<in> E \<Longrightarrow> finite e \<and> card e \<le> k"
assumes E1: "{} \<notin> E"
begin
definition "inv_matching C F M =
(matching M \<and> M \<subseteq> E \<and> card C \<le> k * card M \<and> (\<forall>e \<in> M. \<forall>f \<in> F. e \<inter> f = {}))"
definition invar :: "'a set \<Rightarrow> 'a set set \<Rightarrow> bool" where
"invar C F = (F \<subseteq> E \<and> vertex_cover (E-F) C \<and> finite C \<and> (\<exists>M. inv_matching C F M))"
lemma invar_step:
assumes "F \<noteq> {}" "invar C F"
shows "invar (C \<union> some F) (F - {e' \<in> F. some F \<inter> e' \<noteq> {}})"
proof -
from assms(2) obtain M where "F \<subseteq> E" and vc: "vertex_cover (E-F) C" and fC: "finite C"
and m: "matching M" "M \<subseteq> E" and card: "card C \<le> k * card M"
and disj: "\<forall>e \<in> M. \<forall>f \<in> F. e \<inter> f = {}"
by (auto simp: invar_def inv_matching_def)
let ?e = "SOME e. e \<in> F"
have "?e \<in> F" using \<open>F \<noteq> {}\<close> by (simp add: some_in_eq)
hence fe': "finite ?e" using \<open>F \<subseteq> E\<close> assms(2) edge_bnd by blast
have "?e \<notin> M" using E1 \<open>?e \<in> F\<close> disj \<open>F \<subseteq> E\<close> by fastforce
have card': "card (C \<union> ?e) \<le> k * card (insert ?e M)"
using \<open>?e \<in> F\<close> \<open>?e \<notin> M\<close> card_Un_le[of C ?e] \<open>F \<subseteq> E\<close> edge_bnd card finite_subset[OF m(2) finE]
by fastforce
let ?M = "M \<union> {?e}"
have vc': "vertex_cover (E - (F - {e' \<in> F. ?e \<inter> e' \<noteq> {}})) (C \<union> ?e)"
using vc by(auto simp: vertex_cover_def)
have m': "inv_matching (C \<union> ?e) (F - {e' \<in> F. ?e \<inter> e' \<noteq> {}}) ?M"
using m card' \<open>F \<subseteq> E\<close> \<open>?e \<in> F\<close> disj
by(auto simp: inv_matching_def Int_commute disjnt_def pairwise_insert)
show ?thesis using \<open>F \<subseteq> E\<close> vc' fC fe' m' by(auto simp add: invar_def Let_def)
qed
lemma approx_vertex_cover_bnd:
"VARS C F
{True}
C := {};
F := E;
WHILE F \<noteq> {}
INV {invar C F}
DO C := C \<union> some F;
F := F - {e' \<in> F. some F \<inter> e' \<noteq> {}}
OD
{vertex_cover E C \<and> (\<forall>C'. finite C' \<and> vertex_cover E C' \<longrightarrow> card C \<le> k * card C')}"
proof (vcg, goal_cases)
case (1 C F)
have "inv_matching {} E {}" by (auto simp add: inv_matching_def)
with 1 show ?case by (auto simp add: invar_def vertex_cover_def)
next
case (2 C F)
thus ?case using invar_step[of F C] by(auto simp: Let_def)
next
case (3 C F)
then obtain M :: "'a set set" where
post: "vertex_cover E C" "matching M" "M \<subseteq> E" "card C \<le> k * card M"
by(auto simp: invar_def inv_matching_def)
have opt: "card C \<le> k * card C'" if C': "finite C'" "vertex_cover E C'" for C'
proof -
note post(4)
also have "k * card M \<le> k * card C'"
using card_matching_vertex_cover[OF C'(1) post(2,3) C'(2)] by simp
finally show "card C \<le> k * card C'" .
qed
show ?case using post(1) opt by auto
qed
end (* locale Bounded_Hypergraph *)
end
|
function o = spoptimget(options,name,default,flag)
% SPOPTIMGET Get sparse grid optimization OPTIONS parameters.
% VAL = SPOPTIMGET(OPTIONS,'NAME') extracts the value of the
% named property from the sparse grid options structure OPTIONS,
% returning an empty matrix if the property value is not
% specified in OPTIONS. It is sufficient to type only the leading
% characters that uniquely identify the property. Case is ignored
% for property names. [] is a valid OPTIONS argument.
%
% VAL = SPOPTIMGET(OPTIONS,'NAME',DEFAULT) extracts the named
% property as above, but returns VAL = DEFAULT if the named
% property is not specified in OPTIONS. For example
%
% val = spoptimget(opts, 'Maximize', 'off');
%
% returns val = 'off' if the Maximize property is not specified in opts.
%
% See also SPOPTIMSET, SPCOMPSEARCH, SPFMINSEARCH, SPCGSEARCH,
% SPMULTISTART
% Author : Andreas Klimke
% Version: 1.2
% Date : November 13, 2006
% Change log:
% V1.2 : November 13, 2006
% Cleaned up options.
% V1.1 : August 8, 2005
% Added BisectGap and funTol parameters
% V1.0 : June 9, 2005
% Initial version
% Note: SPOPTIMGET is similar in syntax and code to the options
% handling with ODEGET and ODESET of the MATLAB ODE suite by Marc
% Reichelt and Lawrence Shampine.
% ------------------------------------------------------------
% Sparse Grid Interpolation Toolbox
% Copyright (c) 2006 W. Andreas Klimke, Universitaet Stuttgart
% Copyright (c) 2007-2008 W. A. Klimke. All Rights Reserved.
% See LICENSE.txt for license.
% email: [email protected]
% web : http://www.ians.uni-stuttgart.de/spinterp
% ------------------------------------------------------------
% undocumented usage for fast access with no error checking
if (nargin == 4) & isequal(flag,'fast')
o = getknownfield(options,name,default);
return
end
if nargin < 2
error('Not enough input arguments.');
end
if nargin < 3
default = [];
end
if ~isempty(options) & ~isa(options,'struct')
error(['First argument must be an options structure created with' ...
' SPOPTIMSET.']);
end
if isempty(options)
o = default;
return;
end
Names = {'Minimize', 'Maximize', 'TolFun', 'TolX', ...
'MaxIter', 'StartPoint', 'TestCorners', 'PrevResult', ...
'Method', 'NumStarts', 'OptimsetOptions', 'Display'};
m = length(Names);
for k = 1:m
names{k} = lower(Names{k});
end
lowName = lower(name);
matched = strmatch(lowName,names);
if isempty(matched) % if no matches
error(sprintf(['Unrecognized property name ''%s''. ' ...
'See SPOPTIMSET for possibilities.'], name));
elseif length(matched) > 1
msg = sprintf('Ambiguous property name ''%s'' ', name);
msg = [msg '(' Names{matched}];
for k = j(2:length(matched))'
msg = [msg ', ' Names{matched}];
end
msg = sprintf('%s).', msg);
error(msg);
end
if any(strcmp(fieldnames(options),Names{matched}))
o = options.(Names{matched});
if isempty(o)
o = default;
end
else
o = default;
end
%-----------------------------------------------------------------------
function v = getknownfield(s, f, d)
% GETKNOWNFIELD Get field f from struct s, or else yield default d.
if isfield(s,f) % s could be empty.
v = subsref(s, struct('type','.','subs',f));
if isempty(v)
v = d;
end
else
v = d;
end
|
(* Title: JinjaDCI/Common/Type.thy
Author: David von Oheimb, Tobias Nipkow, Susannah Mansky
Copyright 1999 Technische Universitaet Muenchen, 2019-20 UIUC
Based on the Jinja theory Common/Type.thy by David von Oheimb and Tobias Nipkow
*)
section \<open> Jinja types \<close>
theory Type imports Auxiliary begin
type_synonym cname = string \<comment> \<open>class names\<close>
type_synonym mname = string \<comment> \<open>method name\<close>
type_synonym vname = string \<comment> \<open>names for local/field variables\<close>
definition Object :: cname
where
"Object \<equiv> ''Object''"
definition this :: vname
where
"this \<equiv> ''this''"
definition clinit :: "string" where "clinit = ''<clinit>''"
definition init :: "string" where "init = ''<init>''"
definition start_m :: "string" where "start_m = ''<start>''"
definition Start :: "string" where "Start = ''<Start>''"
lemma start_m_neq_clinit [simp]: "start_m \<noteq> clinit" by(simp add: start_m_def clinit_def)
lemma Object_neq_Start [simp]: "Object \<noteq> Start" by(simp add: Object_def Start_def)
lemma Start_neq_Object [simp]: "Start \<noteq> Object" by(simp add: Object_def Start_def)
\<comment> \<open>field/method static flag\<close>
datatype staticb = Static | NonStatic
\<comment> \<open>types\<close>
datatype ty
= Void \<comment> \<open>type of statements\<close>
| Boolean
| Integer
| NT \<comment> \<open>null type\<close>
| Class cname \<comment> \<open>class type\<close>
definition is_refT :: "ty \<Rightarrow> bool"
where
"is_refT T \<equiv> T = NT \<or> (\<exists>C. T = Class C)"
lemma [iff]: "is_refT(Class C)"
(*<*)by(simp add:is_refT_def)(*>*)
lemma refTE:
"\<lbrakk>is_refT T; T = NT \<Longrightarrow> P; \<And>C. T = Class C \<Longrightarrow> P \<rbrakk> \<Longrightarrow> P"
(*<*)by (auto simp add: is_refT_def)(*>*)
lemma not_refTE:
"\<lbrakk> \<not>is_refT T; T = Void \<or> T = Boolean \<or> T = Integer \<Longrightarrow> P \<rbrakk> \<Longrightarrow> P"
(*<*)by (cases T, auto simp add: is_refT_def)(*>*)
end
|
| pc = 0xc002 | a = 0xc0 | x = 0x00 | y = 0x00 | sp = 0x01fd | p[NV-BDIZC] = 10110100 |
| pc = 0xc005 | a = 0xc0 | x = 0x00 | y = 0x00 | sp = 0x01fd | p[NV-BDIZC] = 10110100 | MEM[0x010f] = 0xc0 |
| pc = 0xc007 | a = 0xa5 | x = 0x00 | y = 0x00 | sp = 0x01fd | p[NV-BDIZC] = 10110100 |
| pc = 0xc009 | a = 0xa5 | x = 0x00 | y = 0x00 | sp = 0x01fd | p[NV-BDIZC] = 10110100 | MEM[0x00a0] = 0xa5 |
| pc = 0xc00b | a = 0x00 | x = 0x00 | y = 0x00 | sp = 0x01fd | p[NV-BDIZC] = 00110110 |
| pc = 0xc00e | a = 0xc0 | x = 0x00 | y = 0x00 | sp = 0x01fd | p[NV-BDIZC] = 10110100 | MEM[0x010f] = 0xc0 |
|
(* Title: HOL/Auth/n_flash_lemma_on_inv__96.thy
Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
*)
header{*The n_flash Protocol Case Study*}
theory n_flash_lemma_on_inv__96 imports n_flash_base
begin
section{*All lemmas on causal relation between inv__96 and some rule r*}
lemma n_PI_Remote_GetVsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_PI_Remote_Get src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_PI_Remote_Get src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_PI_Remote_GetXVsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_PI_Remote_GetX src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_PI_Remote_GetX src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_NakVsinv__96:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Nak dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Nak dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Nak__part__0Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Nak__part__1Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Nak__part__2Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Get__part__0Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Get__part__1Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Put_HeadVsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_PutVsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Put_DirtyVsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_Get_NakVsinv__96:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_Get_Nak_HomeVsinv__96:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Nak_Home dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Get_Nak_Home dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_Get_PutVsinv__96:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_Get_Put_HomeVsinv__96:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Put_Home dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Get_Put_Home dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_GetX)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeUniMsg'') ''Cmd'')) (Const UNI_Get)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_GetX))) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''HomeProc'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_Nak__part__0Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_Nak__part__1Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_Nak__part__2Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_GetX__part__0Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_GetX__part__1Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeUniMsg'') ''Cmd'')) (Const UNI_Put)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Pending'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_1Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_2Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_3Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_4Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_5Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_6Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7__part__0Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7__part__1Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__0Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__1Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_HomeVsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_Home_NODE_GetVsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8Vsinv__96:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_NODE_GetVsinv__96:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_9__part__0Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_9__part__1Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_10_HomeVsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_10Vsinv__96:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_11Vsinv__96:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_NakVsinv__96:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_Nak_HomeVsinv__96:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_Nak_Home dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_GetX_Nak_Home dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_PutXVsinv__96:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_PutX_HomeVsinv__96:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_PutX_Home dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_GetX_PutX_Home dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_PutVsinv__96:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Put dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Put dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_PutXVsinv__96:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_PutX dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_PutX dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_PI_Local_Get_GetVsinv__96:
assumes a1: "(r=n_PI_Local_Get_Get )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_PI_Local_GetX_GetX__part__0Vsinv__96:
assumes a1: "(r=n_PI_Local_GetX_GetX__part__0 )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_PI_Local_GetX_GetX__part__1Vsinv__96:
assumes a1: "(r=n_PI_Local_GetX_GetX__part__1 )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_Nak_HomeVsinv__96:
assumes a1: "(r=n_NI_Nak_Home )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_Local_PutVsinv__96:
assumes a1: "(r=n_NI_Local_Put )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_Local_PutXAcksDoneVsinv__96:
assumes a1: "(r=n_NI_Local_PutXAcksDone )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__96 p__Inv4" apply fastforce done
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_PI_Local_GetX_PutX__part__0Vsinv__96:
assumes a1: "r=n_PI_Local_GetX_PutX__part__0 " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_WbVsinv__96:
assumes a1: "r=n_NI_Wb " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_StoreVsinv__96:
assumes a1: "\<exists> src data. src\<le>N\<and>data\<le>N\<and>r=n_Store src data" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_3Vsinv__96:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_3 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_1Vsinv__96:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_1 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_ReplaceVsinv__96:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_PI_Remote_Replace src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_Store_HomeVsinv__96:
assumes a1: "\<exists> data. data\<le>N\<and>r=n_Store_Home data" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_ReplaceVsinv__96:
assumes a1: "r=n_PI_Local_Replace " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_existsVsinv__96:
assumes a1: "\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_InvAck_exists src pp" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_PutXVsinv__96:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_PI_Remote_PutX dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvVsinv__96:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Inv dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_PutXVsinv__96:
assumes a1: "r=n_PI_Local_PutX " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_Get_PutVsinv__96:
assumes a1: "r=n_PI_Local_Get_Put " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_ShWbVsinv__96:
assumes a1: "r=n_NI_ShWb N " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX_HeadVld__part__0Vsinv__96:
assumes a1: "r=n_PI_Local_GetX_PutX_HeadVld__part__0 N " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_ReplaceVsinv__96:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Replace src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX__part__1Vsinv__96:
assumes a1: "r=n_PI_Local_GetX_PutX__part__1 " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_exists_HomeVsinv__96:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_exists_Home src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Replace_HomeVsinv__96:
assumes a1: "r=n_NI_Replace_Home " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Nak_ClearVsinv__96:
assumes a1: "r=n_NI_Nak_Clear " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_2Vsinv__96:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_2 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX_HeadVld__part__1Vsinv__96:
assumes a1: "r=n_PI_Local_GetX_PutX_HeadVld__part__1 N " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_FAckVsinv__96:
assumes a1: "r=n_NI_FAck " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__96 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
end
|
!----- GPL ---------------------------------------------------------------------
!
! Copyright (C) Stichting Deltares, 2011-2016.
!
! 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 version 3.
!
! 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/>.
!
! contact: [email protected]
! Stichting Deltares
! P.O. Box 177
! 2600 MH Delft, The Netherlands
!
! All indications and logos of, and references to, "Delft3D" and "Deltares"
! are registered trademarks of Stichting Deltares, and remain the property of
! Stichting Deltares. All rights reserved.
!
!-------------------------------------------------------------------------------
! $Id: write_ddp.f90 6649 2016-10-12 12:09:03Z jeuke_ml $
! $HeadURL: https://svn.oss.deltares.nl/repos/delft3d/tags/6686/src/utils_lgpl/hyd_to_waq_part_lib/packages/hyd_to_waq_part_lib/src/write_ddp.f90 $
subroutine write_ddp(hyd)
! function : write a ddp file, dd boundary administration for part
! global declarations
use hydmod ! module contains everything for the hydrodynamics
implicit none
! declaration of the arguments
type(t_hyd) :: hyd ! description of the hydrodynamics
! local declarations
integer :: lunrep ! unit number report file
integer :: lunddp ! unit number sources file
integer :: n_domain ! number of domains
integer :: i_domain ! loop counter and index
integer :: i_domain1 ! loop counter and index
integer :: i_domain2 ! loop counter and index
integer, allocatable :: m_offset(:) ! offset in m direction for the domains
integer :: n_dd_bound ! number of dd_boundaries
integer :: i_dd_bound ! index number of dd_bound
type(t_dd_bound),pointer :: dd_bound ! description of the overall hydrodynamics
integer, allocatable :: iadmddb(:,:) ! dd boundary administration
integer, allocatable :: iadmddb_copy(:,:) ! dd boundary administration copy
integer :: nddb_max ! number of dd boundary connections
integer :: nddb ! number of dd boundary connections
integer :: iddb ! index dd boundary connections
integer :: iiddb ! index dd boundary connections administration
integer :: ir1 ! refinement in domain1
integer :: ir2 ! refinement in domain2
integer :: m_begin1 ! m_begin1
integer :: n_begin1 ! n_begin1
integer :: m_begin2 ! m_begin2
integer :: n_begin2 ! n_begin2
integer :: m ! m index
integer :: n ! n index
logical :: found ! found
integer :: nddb2 ! nddb2 is nddb after merge
integer :: iddb2 ! second iddb index
! some init
call getmlu(lunrep)
n_domain = hyd%domain_coll%cursize
nddb = 0
nddb_max = 500
allocate(iadmddb(22,nddb_max))
iadmddb = 0
! determine offsets in overall grid
allocate(m_offset(n_domain))
do i_domain = 1 , n_domain
if ( i_domain .eq. 1 ) then
m_offset(i_domain) = 0
else
m_offset(i_domain) = m_offset(i_domain-1) + hyd%domain_coll%domain_pnts(i_domain-1)%mmax
endif
enddo
! check dd_boundaries
n_dd_bound = hyd%dd_bound_coll%cursize
do i_dd_bound = 1 , n_dd_bound
dd_bound => hyd%dd_bound_coll%dd_bound_pnts(i_dd_bound)
! look up the domain names
i_domain1 = domain_coll_find(hyd%domain_coll,dd_bound%name1)
if ( i_domain .le. 0 ) then
write(lunrep,*) 'ERROR domain in dd-boundary not found:',trim(dd_bound%name1)
call srstop(1)
endif
dd_bound%i_domain1 = i_domain1
i_domain2 = domain_coll_find(hyd%domain_coll,dd_bound%name2)
if ( i_domain .le. 0 ) then
write(lunrep,*) 'ERROR domain in dd-boundary not found:',trim(dd_bound%name2)
call srstop(1)
endif
dd_bound%i_domain2 = i_domain2
! determine refinement and the side of the boundary
if ( dd_bound%m_begin1 .eq. dd_bound%m_end1 ) then
if ( hyd%lgrid(dd_bound%n_begin1+1,dd_bound%m_begin1+m_offset(i_domain1)) .gt. 0 ) then
dd_bound%direction = DD_RIGHT_LEFT
else
dd_bound%direction = DD_LEFT_RIGHT
endif
if ( dd_bound%n_end1 - dd_bound%n_begin1 .ge. dd_bound%n_end2 - dd_bound%n_begin2 ) then
ir1 = (dd_bound%n_end1 - dd_bound%n_begin1)/(dd_bound%n_end2 - dd_bound%n_begin2)
ir2 = 1
else
ir1 = 1
ir2 = (dd_bound%n_end2 - dd_bound%n_begin2)/(dd_bound%n_end1 - dd_bound%n_begin1)
endif
else
if ( hyd%lgrid(dd_bound%n_begin1,dd_bound%m_begin1+1+m_offset(i_domain1)) .gt. 0 ) then
dd_bound%direction = DD_TOP_BOTTOM
else
dd_bound%direction = DD_BOTTOM_TOP
endif
if ( dd_bound%m_end1 - dd_bound%m_begin1 .ge. dd_bound%m_end2 - dd_bound%m_begin2 ) then
ir1 = (dd_bound%m_end1 - dd_bound%m_begin1)/(dd_bound%m_end2 - dd_bound%m_begin2)
ir2 = 1
else
ir1 = 1
ir2 = (dd_bound%m_end2 - dd_bound%m_begin2)/(dd_bound%m_end1 - dd_bound%m_begin1)
endif
endif
dd_bound%refine1 = ir1
dd_bound%refine2 = ir2
enddo
! set up the actual connections
do i_dd_bound = 1 , n_dd_bound
dd_bound => hyd%dd_bound_coll%dd_bound_pnts(i_dd_bound)
i_domain1 = dd_bound%i_domain1
i_domain2 = dd_bound%i_domain2
ir1 = dd_bound%refine1
ir2 = dd_bound%refine2
! loop over the boundary in the first domain
if ( dd_bound%direction .eq. DD_RIGHT_LEFT .or. dd_bound%direction .eq. DD_LEFT_RIGHT ) then
m_begin1 = dd_bound%m_begin1
n_begin1 = dd_bound%n_begin1 + 1
else
m_begin1 = dd_bound%m_begin1 + 1
n_begin1 = dd_bound%n_begin1
endif
do m = m_begin1, dd_bound%m_end1
do n = n_begin1, dd_bound%n_end1
nddb = nddb + 1
if ( nddb .gt. nddb_max ) then
allocate(iadmddb_copy(22,nddb_max))
iadmddb_copy = iadmddb
deallocate(iadmddb)
nddb_max = nddb_max*2
allocate(iadmddb(22,nddb_max))
iadmddb = 0
iadmddb(:,1:nddb-1) = iadmddb_copy
deallocate(iadmddb_copy)
endif
if ( dd_bound%direction .eq. DD_RIGHT_LEFT ) then
iadmddb(1,nddb) = m + 1 + m_offset(i_domain1)
iadmddb(2,nddb) = n
iadmddb(8,nddb) = dd_bound%m_begin2 + 1 + m_offset(i_domain2)
iadmddb(9,nddb) = dd_bound%n_begin2 + 1 + (n-n_begin1)*ir2/ir1
iadmddb(10,nddb) = ir1
iadmddb(11,nddb) = ir2
if ( ir1 .gt. 1 ) then
iadmddb(12,nddb) = mod(n-n_begin1,ir1) + 1
endif
elseif ( dd_bound%direction .eq. DD_LEFT_RIGHT ) then
iadmddb(1,nddb) = m + m_offset(i_domain1)
iadmddb(2,nddb) = n
iadmddb(3,nddb) = dd_bound%m_begin2 + m_offset(i_domain2)
iadmddb(4,nddb) = dd_bound%n_begin2 + 1 + (n-n_begin1)*ir2/ir1
iadmddb(5,nddb) = ir1
iadmddb(6,nddb) = ir2
if ( ir1 .gt. 1 ) then
iadmddb(8,nddb) = mod(n-n_begin1,ir1) + 1
endif
elseif ( dd_bound%direction .eq. DD_TOP_BOTTOM ) then
iadmddb(1,nddb) = m + m_offset(i_domain1)
iadmddb(2,nddb) = n + 1
iadmddb(18,nddb) = dd_bound%m_begin2 + 1 + (m-m_begin1)*ir2/ir1 + m_offset(i_domain2)
iadmddb(19,nddb) = dd_bound%n_begin2 + 1
iadmddb(20,nddb) = ir1
iadmddb(21,nddb) = ir2
if ( ir1 .gt. 1 ) then
iadmddb(22,nddb) = mod(m-m_begin1,ir1) + 1
endif
elseif ( dd_bound%direction .eq. DD_BOTTOM_TOP ) then
iadmddb(1,nddb) = m + m_offset(i_domain1)
iadmddb(2,nddb) = n
iadmddb(13,nddb) = dd_bound%m_begin2 + 1 + (m-m_begin1)*ir2/ir1 + m_offset(i_domain2)
iadmddb(14,nddb) = dd_bound%n_begin2
iadmddb(15,nddb) = ir1
iadmddb(16,nddb) = ir2
if ( ir1 .gt. 1 ) then
iadmddb(17,nddb) = mod(m-m_begin1,ir1) + 1
endif
endif
enddo
enddo
! loop over the boundary in the second domain
if ( dd_bound%direction .eq. DD_RIGHT_LEFT .or. dd_bound%direction .eq. DD_LEFT_RIGHT ) then
m_begin2 = dd_bound%m_begin2
n_begin2 = dd_bound%n_begin2 + 1
else
m_begin2 = dd_bound%m_begin2 + 1
n_begin2 = dd_bound%n_begin2
endif
do m = m_begin2, dd_bound%m_end2
do n = n_begin2, dd_bound%n_end2
nddb = nddb + 1
if ( nddb .gt. nddb_max ) then
allocate(iadmddb_copy(22,nddb_max))
iadmddb_copy = iadmddb
deallocate(iadmddb)
nddb_max = nddb_max*2
allocate(iadmddb(22,nddb_max))
iadmddb = 0
iadmddb(:,1:nddb-1) = iadmddb_copy
deallocate(iadmddb_copy)
endif
if ( dd_bound%direction .eq. DD_RIGHT_LEFT ) then
iadmddb(1,nddb) = m + m_offset(i_domain2)
iadmddb(2,nddb) = n
iadmddb(3,nddb) = dd_bound%m_begin1 + m_offset(i_domain1)
iadmddb(4,nddb) = dd_bound%n_begin1 + 1 + (n-n_begin2)*ir1/ir2
iadmddb(5,nddb) = ir2
iadmddb(6,nddb) = ir1
if ( ir2 .gt. 1 ) then
iadmddb(7,nddb) = mod(n-n_begin2,ir2) + 1
endif
elseif ( dd_bound%direction .eq. DD_LEFT_RIGHT ) then
iadmddb(1,nddb) = m + 1 + m_offset(i_domain2)
iadmddb(2,nddb) = n
iadmddb(8,nddb) = dd_bound%m_begin1 + 1 + m_offset(i_domain1)
iadmddb(9,nddb) = dd_bound%n_begin1 + 1 + (n-n_begin2)*ir1/ir2
iadmddb(10,nddb) = ir2
iadmddb(11,nddb) = ir1
if ( ir2 .gt. 1 ) then
iadmddb(12,nddb) = mod(n-n_begin2,ir2) + 1
endif
elseif ( dd_bound%direction .eq. DD_TOP_BOTTOM ) then
iadmddb(1,nddb) = m + m_offset(i_domain2)
iadmddb(2,nddb) = n
iadmddb(13,nddb) = dd_bound%m_begin1 + 1 + (m-m_begin2)*ir1/ir2 + m_offset(i_domain1)
iadmddb(14,nddb) = dd_bound%n_begin1
iadmddb(15,nddb) = ir2
iadmddb(16,nddb) = ir1
if ( ir2 .gt. 1 ) then
iadmddb(17,nddb) = mod(m-m_begin2,ir2) + 1
endif
elseif ( dd_bound%direction .eq. DD_BOTTOM_TOP ) then
iadmddb(1,nddb) = m + m_offset(i_domain2)
iadmddb(2,nddb) = n + 1
iadmddb(18,nddb) = dd_bound%m_begin2 + 1 + (m-m_begin2)*ir1/ir2 + m_offset(i_domain1)
iadmddb(19,nddb) = dd_bound%n_begin2 + 1
iadmddb(20,nddb) = ir2
iadmddb(21,nddb) = ir1
if ( ir2 .gt. 1 ) then
iadmddb(22,nddb) = mod(m-m_begin2,ir2) + 1
endif
endif
enddo
enddo
enddo
! merge admin for the different directions ( by adding the values because one should always contain zeros
allocate(iadmddb_copy(22,nddb))
nddb2 = 0
do iddb = 1, nddb
found = .false.
do iddb2 = 1, nddb2
if ( iadmddb(1,iddb) .eq. iadmddb_copy(1,iddb2) .and. iadmddb(2,iddb) .eq. iadmddb_copy(2,iddb2) ) then
found = .true.
iadmddb_copy(3:22,iddb2) = iadmddb_copy(3:22,iddb2) + iadmddb(3:22,iddb)
endif
enddo
if ( .not. found ) then
nddb2 = nddb2 + 1
iadmddb_copy(:,nddb2) = iadmddb(:,iddb)
endif
enddo
nddb = nddb2
iadmddb(:,1:nddb) = iadmddb_copy(:,1:nddb)
deallocate(iadmddb_copy)
! point 0 to 0 pointers towards cell 1 1
do iddb = 1, nddb
if ( iadmddb(3,iddb) .eq. 0 ) then
iadmddb(3,iddb) = 1
iadmddb(4,iddb) = 1
endif
if ( iadmddb(8,iddb) .eq. 0 ) then
iadmddb(8,iddb) = 1
iadmddb(9,iddb) = 1
endif
if ( iadmddb(13,iddb) .eq. 0 ) then
iadmddb(13,iddb) = 1
iadmddb(14,iddb) = 1
endif
if ( iadmddb(18,iddb) .eq. 0 ) then
iadmddb(18,iddb) = 1
iadmddb(19,iddb) = 1
endif
enddo
! write
call dlwqfile_open(hyd%file_ddp)
lunddp = hyd%file_ddp%unit_nr
write(lunddp,*) nddb
write(lunddp,*) '# ddcouple output PART ddbound administration'
do iddb = 1, nddb
write(lunddp,'(22(i10,1x))') (iadmddb(iiddb,iddb),iiddb=1,22)
enddo
deallocate(iadmddb)
return
end
|
module Mmhelloworld.IdrisSpringBoot.Boot
import IdrisJvm.IO
%access public export
SpringApplicationClass : JVM_NativeTy
SpringApplicationClass = Class "org/springframework/boot/SpringApplication"
|
[STATEMENT]
lemma auxiliary_ineq: fixes x::nat assumes "x \<ge> (2::nat)"
shows " x+1 < (2::nat)*x"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. x + 1 < 2 * x
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
2 \<le> x
goal (1 subgoal):
1. x + 1 < 2 * x
[PROOF STEP]
by linarith |
import data.cpi.semantics.interaction_tensor data.cpi.transition
import tactic.abel
namespace cpi
variables {ℂ ℍ : Type} {ω : context} [half_ring ℂ] [decidable_eq ℂ]
/-- Maps a potential transition to the interaction space. -/
def potential_interaction_space [cpi_equiv ℍ ω] {Γ} {ℓ : lookup ℍ ω Γ} {A : prime_species ℍ ω Γ}
: transition.transition_from ℓ A.val
→ interaction_space ℂ ℍ ω Γ
| ⟨ _, # a , @production.concretion _ _ _ b y G, tr ⟩ := fin_fn.single ⟨ ⟦ A ⟧, ⟨ b, y, ⟦ G ⟧ ⟩, a ⟩ 1
| ⟨ _, τ@'_, E, tr ⟩ := 0
| ⟨ _, τ⟨_⟩, E, tr ⟩ := 0
lemma potential_interaction_space.equiv [cpi_equiv ℍ ω] {Γ} {ℓ : lookup ℍ ω Γ}
{A B : prime_species ℍ ω Γ} :
∀ {k} {α : label ℍ Γ k} {E E' : production ℍ ω Γ k}
{t : A.val [ℓ, α]⟶ E} {t' : B.val [ℓ, α]⟶ E'}
, A ≈ B → E ≈ E'
→ @potential_interaction_space ℂ ℍ ω _ _ _ Γ ℓ _ (transition.transition_from.mk t)
= potential_interaction_space (transition.transition_from.mk t')
| _ (# a) (@production.concretion _ _ _ b y E) (production.concretion E') t t' eqA (production.equiv.concretion eqE) := begin
unfold transition.transition_from.mk potential_interaction_space,
have : ⟦ A ⟧ = ⟦ B ⟧ := quot.sound eqA,
have : ⟦ E ⟧ = ⟦ E' ⟧ := quot.sound eqE,
rw [‹⟦ A ⟧ = ⟦ B ⟧›, ‹⟦ E ⟧ = ⟦ E' ⟧›],
end
| _ (τ@'_) E E' t t' _ _ := rfl
| _ (τ⟨_⟩) E E' t t' _ _ := rfl
/-- Compute the potential interaction space for all transitions from a prime species. -/
def potential_interaction_space.from_prime [cpi_equiv ℍ ω] {Γ} (ℓ : lookup ℍ ω Γ) (A : prime_species ℍ ω Γ)
: interaction_space ℂ ℍ ω Γ
:= finset.sum (fintype.elems (transition.transition_from ℓ A.val)) potential_interaction_space
/-- Compute the potential interaction space for all transitions from a species's prime conponents. -/
def potential_interaction_space.from_species [cpi_equiv ℍ ω] {Γ} (ℓ : lookup ℍ ω Γ) (A : species ℍ ω Γ)
: interaction_space ℂ ℍ ω Γ
:= (cpi_equiv.prime_decompose A).sum' (potential_interaction_space.from_prime ℓ)
/-- `potential_interaction_space.from_species`, lifted to quotients. -/
def potential_interaction_space.from_species' [cpi_equiv_prop ℍ ω] {Γ} (ℓ : lookup ℍ ω Γ) (A : species' ℍ ω Γ)
: interaction_space ℂ ℍ ω Γ := (cpi_equiv.prime_decompose' A).sum' (λ B, quot.lift_on B
(potential_interaction_space.from_prime ℓ)
(λ B₁ B₂ equ, begin
cases cpi_equiv_prop.transition_iso ℓ equ with iso,
let isoF := cpi_equiv_prop.transition_from_iso iso,
suffices : ∀ x
, (@potential_interaction_space ℂ ℍ ω _ _ _ _ ℓ _ x)
= potential_interaction_space (isoF.to_fun x),
from fintype.sum_iso _ _ isoF this,
rintros ⟨ k, α, E, t ⟩,
simp only [
isoF, cpi_equiv_prop.transition_from_iso,
cpi_equiv.transition_from_fwd, cpi_equiv.transition_from_inv],
have eqE := (iso k α).2 E t,
cases ((iso k α).fst).to_fun ⟨E, t⟩ with E' t',
from potential_interaction_space.equiv equ eqE,
end))
lemma potential_interaction_space.species_eq [cpi_equiv_prop ℍ ω] {Γ} {ℓ : lookup ℍ ω Γ} {A : species ℍ ω Γ}
: (potential_interaction_space.from_species ℓ A : interaction_space ℂ ℍ ω Γ)
= potential_interaction_space.from_species' ℓ ⟦ A ⟧
:= by simp only
[potential_interaction_space.from_species, potential_interaction_space.from_species',
quot.lift_on, quotient.mk, cpi_equiv.prime_decompose', multiset.sum',
function.comp, multiset.map_map]
/-- Maps a spontaneous/immediate transition to a process space.
This computes the Σ[x ∈ B [τ@k]—→ C] k and Σ[x ∈ B [τ⟨ a, b ⟩]—→ C] M(a, b)
components of the definition of d(c ◯ A)/dt. -/
def immediate_process_space [cpi_equiv ℍ ω] {Γ} {ℓ : lookup ℍ ω Γ} (conc : ℍ ↪ ℂ)
{A : prime_species ℍ ω Γ}
: transition.transition_from ℓ A.val
→ process_space ℂ ℍ ω Γ
| ⟨ _, # a , _, tr ⟩ := 0
| ⟨ _, τ@'k, production.species B, tr ⟩ :=
conc k • (to_process_space ⟦ B ⟧ - fin_fn.single ⟦ A ⟧ 1)
| ⟨ _, τ⟨ n ⟩, _, tr ⟩ := 0
lemma immediate_process_space.equiv [cpi_equiv ℍ ω] {Γ} {ℓ : lookup ℍ ω Γ} {conc : ℍ ↪ ℂ}
{A B : prime_species ℍ ω Γ} :
∀ {k} {α : label ℍ Γ k} {E E' : production ℍ ω Γ k}
{t : A.val [ℓ, α]⟶ E} {t' : B.val [ℓ, α]⟶ E'}
, A ≈ B → E ≈ E'
→ immediate_process_space conc (transition.transition_from.mk t)
= immediate_process_space conc (transition.transition_from.mk t')
| _ (# a ) E E' t t' eqA eqE := rfl
| _ (τ@'k) (production.species E) (production.species E') t t' eqA (production.equiv.species eqE) := begin
unfold transition.transition_from.mk immediate_process_space,
have : ⟦ A ⟧ = ⟦ B ⟧ := quot.sound eqA,
have : ⟦ E ⟧ = ⟦ E' ⟧ := quot.sound eqE,
rw [‹⟦ A ⟧ = ⟦ B ⟧›, ‹⟦ E ⟧ = ⟦ E' ⟧›],
end
| _ (τ⟨ n ⟩) E E' t t' eqA eqE := rfl
/-- Compute the immediate process space for all transitions from a prime species. -/
def immediate_process_space.from_prime [cpi_equiv ℍ ω] {Γ} (conc : ℍ ↪ ℂ) (ℓ : lookup ℍ ω Γ)
(A : prime_species ℍ ω Γ)
: process_space ℂ ℍ ω Γ
:= finset.sum (fintype.elems (transition.transition_from ℓ A.val)) (immediate_process_space conc)
/-- Compute the immediate process space for all transitions from a species's prime conponents. -/
def immediate_process_space.from_species [cpi_equiv ℍ ω] {Γ} (conc : ℍ ↪ ℂ) (ℓ : lookup ℍ ω Γ) (A : species ℍ ω Γ)
: process_space ℂ ℍ ω Γ
:= (cpi_equiv.prime_decompose A).sum' (immediate_process_space.from_prime conc ℓ)
/-- `immediate_process_space.from_species`, lifted to quotients. -/
def immediate_process_space.from_species' [cpi_equiv_prop ℍ ω] {Γ} (conc : ℍ ↪ ℂ) (ℓ : lookup ℍ ω Γ) (A : species' ℍ ω Γ)
: process_space ℂ ℍ ω Γ := (cpi_equiv.prime_decompose' A).sum' (λ B, quot.lift_on B
(immediate_process_space.from_prime conc ℓ)
(λ B₁ B₂ equ, begin
cases cpi_equiv_prop.transition_iso ℓ equ with iso,
let isoF := cpi_equiv_prop.transition_from_iso iso,
suffices : ∀ x
, immediate_process_space conc x
= immediate_process_space conc (isoF.to_fun x),
from fintype.sum_iso _ _ isoF this,
rintros ⟨ k, α, E, t ⟩,
simp only [
isoF, cpi_equiv_prop.transition_from_iso,
cpi_equiv.transition_from_fwd, cpi_equiv.transition_from_inv],
have eqE := (iso k α).2 E t,
cases ((iso k α).fst).to_fun ⟨E, t⟩ with E' t',
from immediate_process_space.equiv equ eqE,
end))
lemma immediate_process_space.species_eq [cpi_equiv_prop ℍ ω] {Γ} {conc : ℍ ↪ ℂ} {ℓ : lookup ℍ ω Γ} {A : species ℍ ω Γ}
: immediate_process_space.from_species conc ℓ A
= immediate_process_space.from_species' conc ℓ ⟦ A ⟧
:= by simp only
[immediate_process_space.from_species, immediate_process_space.from_species',
quot.lift_on, quotient.mk, cpi_equiv.prime_decompose', multiset.sum',
function.comp, multiset.map_map]
/-- The vector space of potential interactions of a process (∂P). -/
def process_potential [cpi_equiv ℍ ω] {Γ} (ℓ : lookup ℍ ω Γ)
: process ℂ ℍ ω Γ → interaction_space ℂ ℍ ω Γ
| (c ◯ A) := c • potential_interaction_space.from_species ℓ A
| (P |ₚ Q) := process_potential P + process_potential Q
lemma process_potential.nil_zero [cpi_equiv ℍ ω] {Γ} (ℓ : lookup ℍ ω Γ) (c : ℂ)
: process_potential ℓ (c ◯ nil) = 0
:= by simp only
[process_potential, potential_interaction_space.from_species,
cpi_equiv.prime_decompose_nil, multiset.sum'_zero, smul_zero]
/-- The vector space of immediate actions of a process (dP/dt)-/
def process_immediate [cpi_equiv ℍ ω]
(M : affinity ℍ) (ℓ : lookup ℍ ω (context.extend M.arity context.nil)) (conc : ℍ ↪ ℂ)
: process ℂ ℍ ω (context.extend M.arity context.nil)
→ process_space ℂ ℍ ω (context.extend M.arity context.nil)
| (c ◯ A)
:= c • immediate_process_space.from_species conc ℓ A
+ (½ : ℂ) • (process_potential ℓ (c ◯ A) ⊘[conc] process_potential ℓ (c ◯ A))
| (P |ₚ Q)
:= process_immediate P + process_immediate Q
+ (process_potential ℓ P ⊘[conc] process_potential ℓ Q)
lemma process_immediate.nil_zero {conc : ℍ ↪ ℂ} [cpi_equiv ℍ ω]
(M : affinity ℍ) (ℓ : lookup ℍ ω (context.extend M.arity context.nil))
(c : ℂ)
: process_immediate M ℓ conc (c ◯ nil) = 0
:= by simp only
[process_immediate, immediate_process_space.from_species,
process_potential.nil_zero, cpi_equiv.prime_decompose_nil,
multiset.sum'_zero, interaction_tensor.zero_left, smul_zero, add_zero]
lemma process_potential.equiv [cpi_equiv_prop ℍ ω] {Γ} (ℓ : lookup ℍ ω Γ) :
∀ {P Q : process ℂ ℍ ω Γ}
, P ≈ Q → process_potential ℓ P = process_potential ℓ Q
| P Q eq := begin
induction eq,
case process.equiv.refl { refl },
case process.equiv.trans : P Q R ab bc ih_ab ih_bc { from trans ih_ab ih_bc },
case process.equiv.symm : P Q eq ih { from symm ih },
case process.equiv.ξ_species : c A B equ {
suffices : potential_interaction_space.from_species ℓ A
= potential_interaction_space.from_species ℓ B,
{ simp only [process_potential], from congr_arg ((•) c) this },
calc potential_interaction_space.from_species ℓ A
= potential_interaction_space.from_species' ℓ ⟦ A ⟧ : potential_interaction_space.species_eq
... = potential_interaction_space.from_species' ℓ ⟦ B ⟧ : by rw quotient.sound equ
... = potential_interaction_space.from_species ℓ B : potential_interaction_space.species_eq.symm
},
case process.equiv.ξ_parallel₁ : P P' Q eq ih {
unfold process_potential, rw ih,
},
case process.equiv.ξ_parallel₂ : P Q Q' eq ih {
unfold process_potential, rw ih,
},
case process.equiv.parallel_nil : P C {
show process_potential ℓ P + process_potential ℓ (C ◯ nil) = process_potential ℓ P,
simp only [process_potential.nil_zero, add_zero],
},
case cpi.process.equiv.parallel_symm { simp only [process_potential, add_comm] },
case process.equiv.parallel_assoc { simp only [process_potential, add_assoc] },
case process.equiv.join : A c d { simp only [process_potential, add_smul] },
case process.equiv.split : A B c {
simp only [process_potential, potential_interaction_space.from_species,
cpi_equiv.prime_decompose_parallel, multiset.sum'_add, smul_add],
},
end
private lemma process_immediate.join [cpi_equiv_prop ℍ ω] (M : affinity ℍ)
(ℓ : lookup ℍ ω (context.extend M.arity context.nil)) {conc : ℍ ↪ ℂ} (c d : ℂ)
(Ds : interaction_space ℂ ℍ ω (context.extend (M.arity) context.nil))
(Ps : process_space ℂ ℍ ω (context.extend (M.arity) context.nil))
: (c • Ds) ⊘[conc] (d • Ds) + ((½ : ℂ) • (c • Ds) ⊘[conc] (c • Ds) + (½ : ℂ) • (d • Ds) ⊘[conc] (d • Ds))
= (½ : ℂ) • (c • Ds + d • Ds) ⊘[conc] (c • Ds + d • Ds) := begin
generalize ehalf : (½ : ℂ) = half,
rw [interaction_tensor.left_distrib (c • Ds) (d • Ds),
interaction_tensor.right_distrib (c • Ds),
interaction_tensor.right_distrib (d • Ds),
interaction_tensor.comm (d • Ds) (c • Ds)],
calc (c • Ds) ⊘ (d • Ds)
+ (half • (c • Ds) ⊘ (c • Ds) + half • (d • Ds) ⊘ (d • Ds))
= (1 : ℂ) • (c • Ds) ⊘[conc] (d • Ds)
+ (half • (c • Ds) ⊘[conc] (c • Ds) + half • (d • Ds) ⊘[conc] (d • Ds))
: by simp only [one_smul]
... = (half + half) • (c • Ds) ⊘[conc] (d • Ds)
+ (half • (c • Ds) ⊘[conc] (c • Ds) + half • (d • Ds) ⊘[conc] (d • Ds))
: by rw [half_ring.one_is_two_halves, ← ehalf]
... = half • (c • Ds) ⊘[conc] (c • Ds) + half • (c • Ds) ⊘[conc] (d • Ds)
+ (half • (c • Ds) ⊘[conc] (d • Ds) + half • (d • Ds) ⊘[conc] (d • Ds))
: begin
simp only [add_smul],
generalize : half • (c • Ds) ⊘[conc] (d • Ds) = cd,
generalize : half • (c • Ds) ⊘[conc] (c • Ds) = cc,
generalize : half • (d • Ds) ⊘[conc] (d • Ds) = dd,
abel,
end
... = half • ((c • Ds) ⊘ (c • Ds) + (c • Ds) ⊘ (d • Ds)
+ ((c • Ds) ⊘ (d • Ds) + (d • Ds) ⊘ (d • Ds)))
: by simp only [smul_add]
end
private lemma process_immediate.split [cpi_equiv_prop ℍ ω] [add_monoid ℍ]
(M : affinity ℍ) (ℓ : lookup ℍ ω (context.extend M.arity context.nil))
(conc : ℍ ↪ ℂ) (c : ℂ)
(A B : species ℍ ω (context.extend M.arity context.nil))
: process_immediate M ℓ conc (c ◯ (A |ₛ B))
= process_immediate M ℓ conc (c ◯ A |ₚ c ◯ B) := begin
simp only [process_immediate, immediate_process_space.from_species,
process_potential.equiv ℓ process.equiv.split,
cpi_equiv.prime_decompose_parallel, multiset.sum'_add, smul_add],
generalize : multiset.sum' (cpi_equiv.prime_decompose A) (immediate_process_space.from_prime conc ℓ) = dA,
generalize : multiset.sum' (cpi_equiv.prime_decompose B) (immediate_process_space.from_prime conc ℓ) = dB,
have : process_potential ℓ (c ◯ A |ₚ c ◯ B) = process_potential ℓ (c ◯ A) + process_potential ℓ (c ◯ B)
:= rfl,
simp only [this],
generalize : process_potential ℓ (c ◯ A) = pA,
generalize : process_potential ℓ (c ◯ B) = pB,
simp only [interaction_tensor.left_distrib, interaction_tensor.right_distrib, smul_add],
rw interaction_tensor.comm pB pA,
generalize : ½ • pA ⊘[conc] pA = iA,
generalize : ½ • pB ⊘[conc] pB = iB,
generalize : pA ⊘[conc] pB = iAB,
calc c • dA + c • dB + (iA + (½ : ℂ) • iAB + ((½ : ℂ) • iAB + iB))
= c • dA + c • dB + (iA + iB + ((½ : ℂ) • iAB + (½ : ℂ) • iAB)) : by abel
... = c • dA + c • dB + (iA + iB + iAB)
: by rw [← add_smul, ← half_ring.one_is_two_halves, one_smul]
... = c • dA + iA + (c • dB + iB) + iAB : by abel
end
lemma process_immediate.equiv [cpi_equiv_prop ℍ ω] [add_monoid ℍ]
(M : affinity ℍ) (ℓ : lookup ℍ ω (context.extend M.arity context.nil))
(conc : ℍ ↪ ℂ)
: ∀ {P Q : process ℂ ℍ ω (context.extend M.arity context.nil)}
, P ≈ Q
→ process_immediate M ℓ conc P
= process_immediate M ℓ conc Q
| P Q eq := begin
induction eq,
case process.equiv.refl { from rfl },
case process.equiv.symm : A B eq ih { from (symm ih) },
case process.equiv.trans : P Q R ab bc ih_ab ih_bc { from trans ih_ab ih_bc },
case process.equiv.ξ_species : c A B equ {
suffices : immediate_process_space.from_species conc ℓ A
= immediate_process_space.from_species conc ℓ B,
{ simp only [process_immediate],
rw [process_potential.equiv ℓ (process.equiv.ξ_species equ), this]
},
calc immediate_process_space.from_species conc ℓ A
= immediate_process_space.from_species' conc ℓ ⟦ A ⟧ : immediate_process_space.species_eq
... = immediate_process_space.from_species' conc ℓ ⟦ B ⟧ : by rw quotient.sound equ
... = immediate_process_space.from_species conc ℓ B : immediate_process_space.species_eq.symm
},
case process.equiv.ξ_parallel₁ : P P' Q eq ih {
simp only [process_immediate, process_potential.equiv ℓ eq, ih],
},
case process.equiv.ξ_parallel₂ : P Q Q' eq ih {
simp only [process_immediate, process_potential.equiv ℓ eq, ih],
},
case process.equiv.parallel_nil {
simp only [process_immediate, process_immediate.nil_zero, add_zero,
process_potential.nil_zero, interaction_tensor.zero_left],
},
case cpi.process.equiv.parallel_symm : P Q {
simp only [process_immediate, add_comm, interaction_tensor.comm],
},
case process.equiv.parallel_assoc : P Q R {
simp only [process_immediate, add_assoc] ,
simp only [add_left_comm],
refine congr_arg _ _,
refine congr_arg _ _,
refine congr_arg _ _,
unfold process_potential,
generalize : process_potential ℓ P = p,
generalize : process_potential ℓ Q = q,
generalize : process_potential ℓ R = r,
calc p ⊘ q + (p + q) ⊘ r
= p ⊘[conc] q + p ⊘[conc] r + q ⊘ r : by rw [interaction_tensor.left_distrib, add_assoc]
... = q ⊘[conc] r + p ⊘[conc] q + p ⊘[conc] r : by simp only [add_comm, add_left_comm, interaction_tensor.comm]
... = q ⊘[conc] r + p ⊘[conc] (q + r) : by rw [add_assoc, ← interaction_tensor.right_distrib]
},
case process.equiv.join : A c d {
simp only [process_immediate, process_potential],
generalize : potential_interaction_space.from_species ℓ A = Ds,
generalize : immediate_process_space.from_species conc ℓ A = Ps,
suffices
: (c • Ds) ⊘[conc] (d • Ds) + ((½ : ℂ) • ((c • Ds) ⊘[conc] (c • Ds)) + (½ : ℂ) • (d • Ds) ⊘[conc] (d • Ds))
= (½ : ℂ) • ((c • Ds + d • Ds) ⊘[conc] (c • Ds + d • Ds)),
{ simp only [add_assoc, add_comm, add_smul, add_left_comm, this] },
from process_immediate.join M ℓ c d Ds Ps,
},
case process.equiv.split : A B c {
from process_immediate.split M ℓ conc c A B
},
end
/-- dP/dt lifted to quotients. -/
def process_immediate.quot [cpi_equiv_prop ℍ ω] [add_monoid ℍ]
(M : affinity ℍ) (ℓ : lookup ℍ ω (context.extend M.arity context.nil))
(conc : ℍ ↪ ℂ)
: process' ℂ ℍ ω (context.extend M.arity context.nil)
→ process_space ℂ ℍ ω (context.extend M.arity context.nil)
| P := quot.lift_on P (process_immediate M ℓ conc)
(λ P Q, process_immediate.equiv M ℓ conc)
/-- dP/dt lifted to process spaces. -/
def process_immediate.space [cpi_equiv_prop ℍ ω] [half_ring ℍ]
(M : affinity ℍ) (ℓ : lookup ℍ ω (context.extend M.arity context.nil))
(conc : ℍ ↪ ℂ)
: process_space ℂ ℍ ω (context.extend M.arity context.nil)
→ process_space ℂ ℍ ω (context.extend M.arity context.nil)
| P := process_immediate.quot M ℓ conc (process.from_space P)
end cpi
#lint-
|
function A = sledges2adjmat(n, nt, edges, varargin)
%SLEDGES2ADJMAT Creates an adjacency matrix from edge set
%
% $ Syntax $
% - A = sledges2adjmat(n, nt, edges, ...)
%
% $ Arguments $
% - n: The number of (source) nodes
% - nt: The number of (target) nodes
% - edges: The matrix of edge set
%
% $ Description $
% - A = sledges2adjmat(n, nt, edges) creates an adjacency matrix
% from the edge set. You can specify the following properties:
% - 'valtype': the value type of the target matrix
% - 'auto': if has value, make numeric matrix
% if no value, make logical matrix
% - 'logical': make logical matrix always
% - 'numeric': make numeric matrix always
% (default = 'auto')
% - 'sparse': whether to create a sparse matrix
% (default = true)
% - 'preprune': whether to prune the edges first
% (default = false)
% - 'prunemethod': the method used to prune the edge set
% (default = [], means using default method)
% refer to slpruneedgeset for the specification
% of the prune methods.
% - 'sym': whether to create symmetric graph
% - 'symmethod': the method to symmetrize the graph
% (default = [], means using default method)
% refer to slsymedgeset for the specification.
%
% $ Remarks $
% - The property sym can only be true when n == nt.
%
% - It is an integrated wrapper for slmakeadjmat, slsymgraph and
% slpruneedgeset.
%
% $ History $
% - Created by Dahua Lin, on Sep 9, 2006
%
%% parse and verify input arguments
if nargin < 3
raise_lackinput('sledges2adjmat', 3);
end
if ~isempty(edges)
ncols = size(edges, 2);
if ndims(edges) ~= 2 || (ncols ~= 2 && ncols ~= 3)
error('sltoolbox:invalidarg', ...
'The edges should be a 2D matrix with two or three columns');
end
end
opts.valtype = 'auto';
opts.sparse = true;
opts.preprune = false;
opts.prunemethod = [];
opts.sym = false;
opts.symmethod = [];
opts = slparseprops(opts, varargin{:});
if opts.sym
if n ~= nt
error('sltoolbox:rterror', ...
'The sym can only be true when n == nt');
end
end
switch opts.valtype
case 'auto'
islogic = (ncols == 2);
case 'numeric'
islogic = false;
case 'logical'
islogic = true;
otherwise
error('sltoolbox:invalidarg', ...
'Invalid value type of adjacency matrix: %s', opts.valtype);
end
%% main skeleton
% prune
if opts.preprune
edges = slpruneedgeset(n, nt, edges, opts.prunemethod);
end
% make adjmat
A = slmakeadjmat(n, nt, edges, [], islogic, opts.sparse);
% symmetrize
if opts.sym
A = slsymgraph(A, opts.symmethod);
end
|
DOUBLE PRECISION FUNCTION PDLATRA( N, A, IA, JA, DESCA )
*
* -- ScaLAPACK auxiliary routine (version 1.7) --
* University of Tennessee, Knoxville, Oak Ridge National Laboratory,
* and University of California, Berkeley.
* May 1, 1997
*
* .. Scalar Arguments ..
INTEGER IA, JA, N
* ..
* .. Array Arguments ..
INTEGER DESCA( * )
DOUBLE PRECISION A( * )
* ..
*
* Purpose
* =======
*
* PDLATRA computes the trace of an N-by-N distributed matrix sub( A )
* denoting A( IA:IA+N-1, JA:JA+N-1 ). The result is left on every
* process of the grid.
*
* Notes
* =====
*
* Each global data object is described by an associated description
* vector. This vector stores the information required to establish
* the mapping between an object element and its corresponding process
* and memory location.
*
* Let A be a generic term for any 2D block cyclicly distributed array.
* Such a global array has an associated description vector DESCA.
* In the following comments, the character _ should be read as
* "of the global array".
*
* NOTATION STORED IN EXPLANATION
* --------------- -------------- --------------------------------------
* DTYPE_A(global) DESCA( DTYPE_ )The descriptor type. In this case,
* DTYPE_A = 1.
* CTXT_A (global) DESCA( CTXT_ ) The BLACS context handle, indicating
* the BLACS process grid A is distribu-
* ted over. The context itself is glo-
* bal, but the handle (the integer
* value) may vary.
* M_A (global) DESCA( M_ ) The number of rows in the global
* array A.
* N_A (global) DESCA( N_ ) The number of columns in the global
* array A.
* MB_A (global) DESCA( MB_ ) The blocking factor used to distribute
* the rows of the array.
* NB_A (global) DESCA( NB_ ) The blocking factor used to distribute
* the columns of the array.
* RSRC_A (global) DESCA( RSRC_ ) The process row over which the first
* row of the array A is distributed.
* CSRC_A (global) DESCA( CSRC_ ) The process column over which the
* first column of the array A is
* distributed.
* LLD_A (local) DESCA( LLD_ ) The leading dimension of the local
* array. LLD_A >= MAX(1,LOCr(M_A)).
*
* Let K be the number of rows or columns of a distributed matrix,
* and assume that its process grid has dimension p x q.
* LOCr( K ) denotes the number of elements of K that a process
* would receive if K were distributed over the p processes of its
* process column.
* Similarly, LOCc( K ) denotes the number of elements of K that a
* process would receive if K were distributed over the q processes of
* its process row.
* The values of LOCr() and LOCc() may be determined via a call to the
* ScaLAPACK tool function, NUMROC:
* LOCr( M ) = NUMROC( M, MB_A, MYROW, RSRC_A, NPROW ),
* LOCc( N ) = NUMROC( N, NB_A, MYCOL, CSRC_A, NPCOL ).
* An upper bound for these quantities may be computed by:
* LOCr( M ) <= ceil( ceil(M/MB_A)/NPROW )*MB_A
* LOCc( N ) <= ceil( ceil(N/NB_A)/NPCOL )*NB_A
*
* Arguments
* =========
*
* N (global input) INTEGER
* The number of rows and columns to be operated on i.e the
* order of the distributed submatrix sub( A ). N >= 0.
*
* A (local input) DOUBLE PRECISION pointer into the local memory
* to an array of dimension ( LLD_A, LOCc(JA+N-1) ). This array
* contains the local pieces of the distributed matrix the trace
* is to be computed.
*
* IA (global input) INTEGER
* The row index in the global array A indicating the first
* row of sub( A ).
*
* JA (global input) INTEGER
* The column index in the global array A indicating the
* first column of sub( A ).
*
* DESCA (global and local input) INTEGER array of dimension DLEN_.
* The array descriptor for the distributed matrix A.
*
* ====================================================================
*
* .. Parameters ..
INTEGER BLOCK_CYCLIC_2D, CSRC_, CTXT_, DLEN_, DTYPE_,
$ LLD_, MB_, M_, NB_, N_, RSRC_
PARAMETER ( BLOCK_CYCLIC_2D = 1, DLEN_ = 9, DTYPE_ = 1,
$ CTXT_ = 2, M_ = 3, N_ = 4, MB_ = 5, NB_ = 6,
$ RSRC_ = 7, CSRC_ = 8, LLD_ = 9 )
DOUBLE PRECISION ZERO
PARAMETER ( ZERO = 0.0D+0 )
* ..
* .. Local Scalars ..
INTEGER ICURCOL, ICURROW, II, IOFFA, J, JB, JJ, JN,
$ LDA, LL, MYCOL, MYROW, NPCOL, NPROW
DOUBLE PRECISION TRACE
* ..
* .. External Subroutines ..
EXTERNAL BLACS_GRIDINFO, DGSUM2D, INFOG2L
* ..
* .. External Functions ..
INTEGER ICEIL
EXTERNAL ICEIL
* ..
* .. Intrinsic Functions ..
INTRINSIC MIN, MOD
* ..
* .. Executable Statements ..
*
* Get grid parameters
*
CALL BLACS_GRIDINFO( DESCA( CTXT_ ), NPROW, NPCOL, MYROW, MYCOL )
*
TRACE = ZERO
IF( N.EQ.0 ) THEN
PDLATRA = TRACE
RETURN
END IF
*
CALL INFOG2L( IA, JA, DESCA, NPROW, NPCOL, MYROW, MYCOL, II, JJ,
$ ICURROW, ICURCOL )
*
JN = MIN( ICEIL( JA, DESCA( NB_ ) ) * DESCA( NB_ ), JA+N-1 )
JB = JN-JA+1
LDA = DESCA( LLD_ )
IOFFA = II + ( JJ - 1 ) * LDA
*
* Handle first diagonal block separately
*
IF( MYROW.EQ.ICURROW .AND. MYCOL.EQ.ICURCOL ) THEN
DO 10 LL = IOFFA, IOFFA + (JB-1)*(LDA+1), LDA+1
TRACE = TRACE + A( LL )
10 CONTINUE
END IF
IF( MYROW.EQ.ICURROW )
$ IOFFA = IOFFA + JB
IF( MYCOL.EQ.ICURCOL )
$ IOFFA = IOFFA + JB*LDA
ICURROW = MOD( ICURROW+1, NPROW )
ICURCOL = MOD( ICURCOL+1, NPCOL )
*
* Loop over the remaining block of columns
*
DO 30 J = JN+1, JA+N-1, DESCA( NB_ )
JB = MIN( JA+N-J, DESCA( NB_ ) )
*
IF( MYROW.EQ.ICURROW .AND. MYCOL.EQ.ICURCOL ) THEN
DO 20 LL = IOFFA, IOFFA + (JB-1)*(LDA+1), LDA+1
TRACE = TRACE + A( LL )
20 CONTINUE
END IF
IF( MYROW.EQ.ICURROW )
$ IOFFA = IOFFA + JB
IF( MYCOL.EQ.ICURCOL )
$ IOFFA = IOFFA + JB*LDA
ICURROW = MOD( ICURROW+1, NPROW )
ICURCOL = MOD( ICURCOL+1, NPCOL )
30 CONTINUE
*
CALL DGSUM2D( DESCA( CTXT_ ), 'All', ' ', 1, 1, TRACE, 1, -1,
$ MYCOL )
*
PDLATRA = TRACE
*
RETURN
*
* End of PDLATRA
*
END
|
Formal statement is: lemma limitin_sequentially_offset_rev: assumes "limitin X (\<lambda>i. f (i + k)) l sequentially" shows "limitin X f l sequentially" Informal statement is: If the sequence $(f(i + k))_{i \in \mathbb{N}}$ converges to $l$ in $X$, then the sequence $(f(i))_{i \in \mathbb{N}}$ converges to $l$ in $X$. |
function J2=numDiff2(x,f,fDim,N,epsilon)
%%NUMDIFF2 Numerically compute the second derivatives using central
% difference formulae based on Lagrange interpolating polynomials.
% The algorithm is made to alert (and not crash) in the event that
% f fails. Specifically, if f returns an empty matrix or it any of
% the components of f are NaNs, then the numDiff function will
% terminate early, returning an empty matrix to indicate failure.
% The function only computes second derivatives, not considering
% cross terms (it does not find a Hessian matrix). Use numDiffHess
% to get a Hessian matrix with cross terms.
%
%INPUTS: x The xDimX1 vector or scalar point at which the second derivative
% of the (possibly vector) function is desired.
% f The scalar or vector function that is to be differentiated. The
% function f must take x as its parameter and its output should be
% a scalar or a column vector.
% fDim The dimensionality of the output of f.
% N A number >=1 specifying the order of the second derivative
% approximation. Values for n=1 through 3 are explicitly coded in.
% For values 3 and above, the coefficients of the second
% derivative of the Lagrange interpolating polynomial are
% explicitly solved. If omitted, a value of N=1 is used.
% epsilon A scalar or xDimX1 vector quantity specifying the finite step
% size used for numerical differentiation. If a scalar value is
% given, that value is used for differentiating with respect to
% elements of xDim. If an xDimX1 value is given, then the
% corresponding element of epsilon is used to differentiate each
% element of x. If epsilon is omitted, then
% epsilon=max(1e-5*x,1e-7); is used.
%
%OUTPUTS: J2 A fDimXxDim matrix of second derivatives. Each column is the
% derivative vector of f with respect to the corresponding
% element of x. If at any point the function f returned a NaN or
% an empty matrix, J2 will be an empty matrix.
%
%The function is similar to the numDiff function. Central-difference
%numerical differentiation is discussed in terms of Lagrange interpolating
%polynomials in Chapter 4.1 of [1]. The Lagrange interpolating polynomials
%themselves are discussed in Chapter 3 of [1]. In general, the coefficients
%of the interpolating polynomial for first derivative central difference
%numerical differentiation come from Equation 4.2, which expresses them in
%terms of the first derivative of a Lagrange interpolating polynomial. This
%function just extends the concept by using the second-derivative
%coefficients.
%
%REFERENCES:
%[1] R. L. Burden and J. D. Faires, Numerical Analysis, 9th ed. Boston, MA:
% Brooks/ Cole, 2011.
%
%April 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.
if(nargin<4)
N=1;
end
switch(N)
case 1
a=[1; -2; 1];
case 2
a=[-1/12; 4/3; -5/2; 4/3; -1/12];
case 3
a=[1/90; -3/20; 3/2; -49/18; 3/2; -3/20; 1/90];
otherwise
[~,~,d2Li]=LagrangeInterpPoly(-N:1:N);
a=d2Li(end,:);
end
xDim=size(x,1);
if(nargin<5)
%If epsilon is not specified, then use some ad-hoc default value
epsilon=max(1e-5*x,1e-7);
end
if(isscalar(epsilon))
epsilon=repmat(epsilon,[xDim,1]);
end
J2=zeros(fDim,xDim);
for curEl=1:xDim
epsCur=epsilon(curEl);
curIdx=1;
for curP=-N:1:N
xP=x;
xP(curEl)=xP(curEl)+curP*epsCur;
fxP=f(xP);
if(isempty(fxP)||any(isnan(fxP)))
J2=[];
return;
end
J2(:,curEl)=J2(:,curEl)+a(curIdx)*fxP;
curIdx=curIdx+1;
end
J2(:,curEl)=J2(:,curEl)/(epsCur^2);
end
end
%LICENSE:
%
%The source code is in the public domain and not licensed or under
%copyright. The information and software may be used freely by the public.
%As required by 17 U.S.C. 403, third parties producing copyrighted works
%consisting predominantly of the material produced by U.S. government
%agencies must provide notice with such work(s) identifying the U.S.
%Government material incorporated and stating that such material is not
%subject to copyright protection.
%
%Derived works shall not identify themselves in a manner that implies an
%endorsement by or an affiliation with the Naval Research Laboratory.
%
%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE
%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL
%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS
%OF RECIPIENT IN THE USE OF THE SOFTWARE.
|
{-# OPTIONS --safe #-}
module Cubical.Categories.Limits.Pullback where
open import Cubical.Foundations.Prelude
open import Cubical.Foundations.HLevels
open import Cubical.HITs.PropositionalTruncation.Base
open import Cubical.Data.Sigma
open import Cubical.Data.Unit
open import Cubical.Categories.Category
open import Cubical.Categories.Functor
open import Cubical.Categories.Instances.Cospan
open import Cubical.Categories.Limits.Limits
private
variable
ℓ ℓ' : Level
module _ (C : Category ℓ ℓ') where
open Category C
open Functor
record Cospan : Type (ℓ-max ℓ ℓ') where
constructor cospan
field
l m r : ob
s₁ : C [ l , m ]
s₂ : C [ r , m ]
open Cospan
isPullback : (cspn : Cospan) →
{c : ob} (p₁ : C [ c , cspn .l ]) (p₂ : C [ c , cspn .r ])
(H : p₁ ⋆ cspn .s₁ ≡ p₂ ⋆ cspn .s₂) → Type (ℓ-max ℓ ℓ')
isPullback cspn {c} p₁ p₂ H =
∀ {d} (h : C [ d , cspn .l ]) (k : C [ d , cspn .r ])
(H' : h ⋆ cspn .s₁ ≡ k ⋆ cspn .s₂)
→ ∃![ hk ∈ C [ d , c ] ] (h ≡ hk ⋆ p₁) × (k ≡ hk ⋆ p₂)
isPropIsPullback : (cspn : Cospan) →
{c : ob} (p₁ : C [ c , cspn .l ]) (p₂ : C [ c , cspn .r ])
(H : p₁ ⋆ cspn .s₁ ≡ p₂ ⋆ cspn .s₂) → isProp (isPullback cspn p₁ p₂ H)
isPropIsPullback cspn p₁ p₂ H =
isPropImplicitΠ (λ x → isPropΠ3 λ h k H' → isPropIsContr)
record Pullback (cspn : Cospan) : Type (ℓ-max ℓ ℓ') where
field
pbOb : ob
pbPr₁ : C [ pbOb , cspn .l ]
pbPr₂ : C [ pbOb , cspn .r ]
pbCommutes : pbPr₁ ⋆ cspn .s₁ ≡ pbPr₂ ⋆ cspn .s₂
univProp : isPullback cspn pbPr₁ pbPr₂ pbCommutes
open Pullback
pullbackArrow :
{cspn : Cospan} (pb : Pullback cspn)
{c : ob} (p₁ : C [ c , cspn .l ]) (p₂ : C [ c , cspn .r ])
(H : p₁ ⋆ cspn .s₁ ≡ p₂ ⋆ cspn .s₂) → C [ c , pb . pbOb ]
pullbackArrow pb p₁ p₂ H = pb .univProp p₁ p₂ H .fst .fst
pullbackArrowPr₁ :
{cspn : Cospan} (pb : Pullback cspn)
{c : ob} (p₁ : C [ c , cspn .l ]) (p₂ : C [ c , cspn .r ])
(H : p₁ ⋆ cspn .s₁ ≡ p₂ ⋆ cspn .s₂) →
p₁ ≡ pullbackArrow pb p₁ p₂ H ⋆ pbPr₁ pb
pullbackArrowPr₁ pb p₁ p₂ H = pb .univProp p₁ p₂ H .fst .snd .fst
pullbackArrowPr₂ :
{cspn : Cospan} (pb : Pullback cspn)
{c : ob} (p₁ : C [ c , cspn .l ]) (p₂ : C [ c , cspn .r ])
(H : p₁ ⋆ cspn .s₁ ≡ p₂ ⋆ cspn .s₂) →
p₂ ≡ pullbackArrow pb p₁ p₂ H ⋆ pbPr₂ pb
pullbackArrowPr₂ pb p₁ p₂ H = pb .univProp p₁ p₂ H .fst .snd .snd
pullbackArrowUnique :
{cspn : Cospan} (pb : Pullback cspn)
{c : ob} (p₁ : C [ c , cspn .l ]) (p₂ : C [ c , cspn .r ])
(H : p₁ ⋆ cspn .s₁ ≡ p₂ ⋆ cspn .s₂)
(pbArrow' : C [ c , pb .pbOb ])
(H₁ : p₁ ≡ pbArrow' ⋆ pbPr₁ pb) (H₂ : p₂ ≡ pbArrow' ⋆ pbPr₂ pb)
→ pullbackArrow pb p₁ p₂ H ≡ pbArrow'
pullbackArrowUnique pb p₁ p₂ H pbArrow' H₁ H₂ =
cong fst (pb .univProp p₁ p₂ H .snd (pbArrow' , (H₁ , H₂)))
Pullbacks : Type (ℓ-max ℓ ℓ')
Pullbacks = (cspn : Cospan) → Pullback cspn
hasPullbacks : Type (ℓ-max ℓ ℓ')
hasPullbacks = ∥ Pullbacks ∥₁
-- Pullbacks from limits
module _ {C : Category ℓ ℓ'} where
open Category C
open Functor
open Pullback
open LimCone
open Cone
open Cospan
Cospan→Func : Cospan C → Functor CospanCat C
Cospan→Func (cospan l m r f g) .F-ob ⓪ = l
Cospan→Func (cospan l m r f g) .F-ob ① = m
Cospan→Func (cospan l m r f g) .F-ob ② = r
Cospan→Func (cospan l m r f g) .F-hom {⓪} {①} k = f
Cospan→Func (cospan l m r f g) .F-hom {②} {①} k = g
Cospan→Func (cospan l m r f g) .F-hom {⓪} {⓪} k = id
Cospan→Func (cospan l m r f g) .F-hom {①} {①} k = id
Cospan→Func (cospan l m r f g) .F-hom {②} {②} k = id
Cospan→Func (cospan l m r f g) .F-id {⓪} = refl
Cospan→Func (cospan l m r f g) .F-id {①} = refl
Cospan→Func (cospan l m r f g) .F-id {②} = refl
Cospan→Func (cospan l m r f g) .F-seq {⓪} {⓪} {⓪} φ ψ = sym (⋆IdL _)
Cospan→Func (cospan l m r f g) .F-seq {⓪} {⓪} {①} φ ψ = sym (⋆IdL _)
Cospan→Func (cospan l m r f g) .F-seq {⓪} {①} {①} φ ψ = sym (⋆IdR _)
Cospan→Func (cospan l m r f g) .F-seq {①} {①} {①} φ ψ = sym (⋆IdL _)
Cospan→Func (cospan l m r f g) .F-seq {②} {②} {②} φ ψ = sym (⋆IdL _)
Cospan→Func (cospan l m r f g) .F-seq {②} {②} {①} φ ψ = sym (⋆IdL _)
Cospan→Func (cospan l m r f g) .F-seq {②} {①} {①} φ ψ = sym (⋆IdR _)
LimitsOfShapeCospanCat→Pullbacks : LimitsOfShape CospanCat C → Pullbacks C
pbOb (LimitsOfShapeCospanCat→Pullbacks H cspn) = lim (H (Cospan→Func cspn))
pbPr₁ (LimitsOfShapeCospanCat→Pullbacks H cspn) = limOut (H (Cospan→Func cspn)) ⓪
pbPr₂ (LimitsOfShapeCospanCat→Pullbacks H cspn) = limOut (H (Cospan→Func cspn)) ②
pbCommutes (LimitsOfShapeCospanCat→Pullbacks H cspn) = limOutCommutes (H (Cospan→Func cspn)) {v = ①} tt
∙ sym (limOutCommutes (H (Cospan→Func cspn)) tt)
univProp (LimitsOfShapeCospanCat→Pullbacks H cspn) {d = d} h k H' =
uniqueExists (limArrow (H (Cospan→Func cspn)) d cc)
( sym (limArrowCommutes (H (Cospan→Func cspn)) d cc ⓪)
, sym (limArrowCommutes (H (Cospan→Func cspn)) d cc ②))
(λ _ → isProp× (isSetHom _ _) (isSetHom _ _))
λ a' ha' → limArrowUnique (H (Cospan→Func cspn)) d cc a'
(λ { ⓪ → sym (ha' .fst)
; ① → cong (a' ⋆_) (sym (limOutCommutes (H (Cospan→Func cspn)) {⓪} {①} tt))
∙∙ sym (⋆Assoc _ _ _)
∙∙ cong (_⋆ cspn .s₁) (sym (ha' .fst))
; ② → sym (ha' .snd) })
where
cc : Cone (Cospan→Func cspn) d
coneOut cc ⓪ = h
coneOut cc ① = h ⋆ cspn .s₁
coneOut cc ② = k
coneOutCommutes cc {⓪} {⓪} e = ⋆IdR h
coneOutCommutes cc {⓪} {①} e = refl
coneOutCommutes cc {①} {①} e = ⋆IdR _
coneOutCommutes cc {②} {①} e = sym H'
coneOutCommutes cc {②} {②} e = ⋆IdR k
Limits→Pullbacks : Limits C → Pullbacks C
Limits→Pullbacks H = LimitsOfShapeCospanCat→Pullbacks (H CospanCat)
|
At a time when the Catholic Church is reeling from allegations and hard criminal convictions of Catholic priests who used their positions of authority to sexually abuse young men in their congregations with virtual immunity, it is high time to re-examine the position taken by the Boy Scouts of America with regard to their ban of openly homosexual Boy Scout leaders.
Among many others, large corporations like Levi Staus and Wells Fargo Bank, withheld contributions to the Boy Scouts of America for that refusal, fortified by federal rulings, to allow openly homosexual men from acting as Boy Scout leaders.
It just wasn't politically correct, those revered bastions of business declared! Homosexual men shouldn't be judged badly, just because they want to lead a Boy Scout troop. What does their personal sexual preference have to do with their ethics in interacting with young men, they demanded?
Over twenty years ago, my wife witnessed her young nephew in Wislow, Arizona arguing with his priest in a most disrespectful and intimate manner -- almost like a boy and girlfriend who had a tiff. Not long afterward, she became aware this priest bought the young man a car. She had no illusions what was going on between the two.
It is no secret that some homosexual men target young men for homosexual encounters. It is no secret that pedophiles target young adolescents of young age. Far too many women of this day who had children out of wedlock, or who are divorced with children, discovered to their horror that the men they married did so primarily to get access to their young children. There is no mystery why the rate of child molestation has skyrocketed in recent years, bolstered by the massive numbers of unwed women with children who marry men who have no paternal inhibitions about sexually interacting with the women's children.
The Catholic Church is presumably filled with priests fully aware and mindful of the guidelines of God, yet the unravelling drama we are witnessing reveals a pattern of homosexual sexual abuse by far too many priests who knew their positions of pious reverence in the community would protect them from the fire of their desires -- and they were right. In virtually every case, the Catholic Church would transfer those errant priests to another position far removed from the scene of their past crimes, only to allow those same priests to further victimize the children in their new congregations.
If any non-religious individual or corporation acted in the same way, they would be charged with obstruction of justice.
The Boy Scouts of America long ago correctly identified homosexuality as a sexual fetish, having nothing whatsoever to do with a person being born with a homosexual tendency, as so many homosexual rights groups allege. They fully understood that homosexual men are driven by their abberant sexual desires, and they chose not to allow any such men from being placed in a position of authority over the young men who make up the boy Scouts of America. I applaud them.
"I am going to address the issue of homosexuality and it's effects because I worked very closely with over 300 homosexual men in the late 60s and early 70s, which was just before gay rights groups began to organize into the political power base they represent today..." |
program test_initialize
use bmif_1_2, only: BMI_SUCCESS
use bmisnowf
use fixtures, only: status
implicit none
character (len=*), parameter :: config_file1 = "test.cfg"
type (bmi_snow) :: m
integer :: status1, status2
status1 = m%initialize(config_file1)
status = m%finalize()
if (status1.ne.BMI_SUCCESS) then
stop 1
end if
end program test_initialize
|
/-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Robert Y. Lewis
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.mv_polynomial.monad
import Mathlib.PostPort
universes u_1 u_3 u_2 u_4
namespace Mathlib
/-!
## Expand multivariate polynomials
Given a multivariate polynomial `φ`, one may replace every occurence of `X i` by `X i ^ n`,
for some natural number `n`.
This operation is called `mv_polynomial.expand` and it is an algebra homomorphism.
### Main declaration
* `mv_polynomial.expand`: expand a polynomial by a factor of p, so `∑ aₙ xⁿ` becomes `∑ aₙ xⁿᵖ`.
-/
namespace mv_polynomial
/-- Expand the polynomial by a factor of p, so `∑ aₙ xⁿ` becomes `∑ aₙ xⁿᵖ`.
See also `polynomial.expand`. -/
def expand {σ : Type u_1} {R : Type u_3} [comm_semiring R] (p : ℕ) : alg_hom R (mv_polynomial σ R) (mv_polynomial σ R) :=
alg_hom.mk (ring_hom.to_fun (eval₂_hom C fun (i : σ) => X i ^ p)) sorry sorry sorry sorry sorry
@[simp] theorem expand_C {σ : Type u_1} {R : Type u_3} [comm_semiring R] (p : ℕ) (r : R) : coe_fn (expand p) (coe_fn C r) = coe_fn C r :=
eval₂_hom_C C (fun (n : σ) => (fun (i : σ) => X i ^ p) n) r
@[simp] theorem expand_X {σ : Type u_1} {R : Type u_3} [comm_semiring R] (p : ℕ) (i : σ) : coe_fn (expand p) (X i) = X i ^ p :=
eval₂_hom_X' C (fun (n : σ) => (fun (i : σ) => X i ^ p) n) i
@[simp] theorem expand_monomial {σ : Type u_1} {R : Type u_3} [comm_semiring R] (p : ℕ) (d : σ →₀ ℕ) (r : R) : coe_fn (expand p) (monomial d r) = coe_fn C r * finset.prod (finsupp.support d) fun (i : σ) => (X i ^ p) ^ coe_fn d i :=
bind₁_monomial (fun (i : σ) => X i ^ p) d r
theorem expand_one_apply {σ : Type u_1} {R : Type u_3} [comm_semiring R] (f : mv_polynomial σ R) : coe_fn (expand 1) f = f := sorry
@[simp] theorem expand_one {σ : Type u_1} {R : Type u_3} [comm_semiring R] : expand 1 = alg_hom.id R (mv_polynomial σ R) := sorry
theorem expand_comp_bind₁ {σ : Type u_1} {τ : Type u_2} {R : Type u_3} [comm_semiring R] (p : ℕ) (f : σ → mv_polynomial τ R) : alg_hom.comp (expand p) (bind₁ f) = bind₁ fun (i : σ) => coe_fn (expand p) (f i) := sorry
theorem expand_bind₁ {σ : Type u_1} {τ : Type u_2} {R : Type u_3} [comm_semiring R] (p : ℕ) (f : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : coe_fn (expand p) (coe_fn (bind₁ f) φ) = coe_fn (bind₁ fun (i : σ) => coe_fn (expand p) (f i)) φ := sorry
@[simp] theorem map_expand {σ : Type u_1} {R : Type u_3} {S : Type u_4} [comm_semiring R] [comm_semiring S] (f : R →+* S) (p : ℕ) (φ : mv_polynomial σ R) : coe_fn (map f) (coe_fn (expand p) φ) = coe_fn (expand p) (coe_fn (map f) φ) := sorry
@[simp] theorem rename_expand {σ : Type u_1} {τ : Type u_2} {R : Type u_3} [comm_semiring R] (f : σ → τ) (p : ℕ) (φ : mv_polynomial σ R) : coe_fn (rename f) (coe_fn (expand p) φ) = coe_fn (expand p) (coe_fn (rename f) φ) := sorry
@[simp] theorem rename_comp_expand {σ : Type u_1} {τ : Type u_2} {R : Type u_3} [comm_semiring R] (f : σ → τ) (p : ℕ) : alg_hom.comp (rename f) (expand p) = alg_hom.comp (expand p) (rename f) := sorry
|
% set values, load data
nx = 144;
ny = 256;
nc = 8;
niter = 250;
mu = 2^-3;
nlevels = 3;
beta = 2^8.5;
load braindat;
load kmask;
load brainxinf;
% load braindb4xinf;
mask = true(nx,ny);
% mask = abs(xinf) > 0.1*max(col(abs(xinf)));
% generate and sample data
A = (1/sqrt(nx*ny))*Gdft('mask', true(nx,ny), 'fftshift', 1, ...
'ifftshift', 1);
dat = A*reshape(coilim, [nx*ny nc]); clear coilim;
kmask = kmask((256-nx)/2+1:256-(256-nx)/2,:);
dat = col(dat(col(kmask),:));
n = kmask; b = 1:nx*ny;
n = b(n); clear b;
% build system matrices
A = Apsm('knownfn', 'time', 'v', 1, 'n', n(:), 'smap', smap, 'immask', ...
true(nx,ny), 'nk', nx*ny);
W = Godwt1(mask, 'level', nlevels, 'wname', 'haar');
P = Gdiag(1./(col(sum(abs(smap).^2,3)) + mu));
% don't regularize approx coeffs
beta = beta*ones(nx,ny);
beta(1:nx/2^nlevels,1:ny/2^nlevels) = 0;
beta = col(beta);
% initializations
x = A'*dat; x = x./ col(sum(abs(smap).^2,3));
x = x(mask);
z = W*x;
eta = zeros(size(z));
% system matrix
A = Apsm('knownfn', 'time', 'v', 1, 'n', n(:), 'smap', smap, 'immask', ...
mask, 'nk', nx*ny);
% algorithm book-keeping
shrink = @(t, a) (t-a .* sign(t)) .* (abs(t) > a);
i = 0;
thetime(1) = 0;
xdist(1) = norm(col(x) - col(xinf(mask)));
% go
tic;
while i < niter
printm('iteration %d of %d', i+1, niter);
z = shrink(W*x + eta, beta./mu);
x = qpwls_pcg1(x, [A; sqrt(mu)*W], 1, [dat(:); sqrt(mu)*(z - eta)], ...
0, 'niter', 5, 'precon', P);
eta = eta - (z - W*x);
thetime(i+2) = toc;
xdist(i+2) = norm(col(x) - col(xinf(mask)));
i = i+1;
end
toc;
x = embed(x, mask);
im(x)
|
= Hadji Ali =
|
[STATEMENT]
lemma cat_colimit_is_lKe:
assumes "\<eta> : \<TT> >\<^sub>C\<^sub>F\<^sub>.\<^sub>c\<^sub>o\<^sub>l\<^sub>i\<^sub>m \<FF>\<lparr>ObjMap\<rparr>\<lparr>\<aa>\<rparr> : \<BB> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<AA>"
and "\<KK> : \<BB> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> cat_1 \<aa> \<ff>"
and "\<FF> : cat_1 \<aa> \<ff> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<AA>"
shows "\<eta> : \<TT> \<mapsto>\<^sub>C\<^sub>F\<^sub>.\<^sub>l\<^sub>K\<^sub>e\<^bsub>\<alpha>\<^esub> \<FF> \<circ>\<^sub>C\<^sub>F \<KK> : \<BB> \<mapsto>\<^sub>C cat_1 \<aa> \<ff> \<mapsto>\<^sub>C \<AA>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<eta> : \<TT> \<mapsto>\<^sub>C\<^sub>F\<^sub>.\<^sub>l\<^sub>K\<^sub>e\<^bsub>\<alpha>\<^esub> \<FF> \<circ>\<^sub>C\<^sub>F \<KK> : \<BB> \<mapsto>\<^sub>C cat_1 \<aa> \<ff> \<mapsto>\<^sub>C \<AA>
[PROOF STEP]
proof-
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<eta> : \<TT> \<mapsto>\<^sub>C\<^sub>F\<^sub>.\<^sub>l\<^sub>K\<^sub>e\<^bsub>\<alpha>\<^esub> \<FF> \<circ>\<^sub>C\<^sub>F \<KK> : \<BB> \<mapsto>\<^sub>C cat_1 \<aa> \<ff> \<mapsto>\<^sub>C \<AA>
[PROOF STEP]
interpret \<eta>: is_cat_colimit \<alpha> \<BB> \<AA> \<TT> \<open>\<FF>\<lparr>ObjMap\<rparr>\<lparr>\<aa>\<rparr>\<close> \<eta>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<eta> : \<TT> >\<^sub>C\<^sub>F\<^sub>.\<^sub>c\<^sub>o\<^sub>l\<^sub>i\<^sub>m \<FF>\<lparr>ObjMap\<rparr>\<lparr>\<aa>\<rparr> : \<BB> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<AA>
[PROOF STEP]
by (rule assms(1))
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<eta> : \<TT> \<mapsto>\<^sub>C\<^sub>F\<^sub>.\<^sub>l\<^sub>K\<^sub>e\<^bsub>\<alpha>\<^esub> \<FF> \<circ>\<^sub>C\<^sub>F \<KK> : \<BB> \<mapsto>\<^sub>C cat_1 \<aa> \<ff> \<mapsto>\<^sub>C \<AA>
[PROOF STEP]
interpret \<KK>: is_functor \<alpha> \<BB> \<open>cat_1 \<aa> \<ff>\<close> \<KK>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<KK> : \<BB> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> cat_1 \<aa> \<ff>
[PROOF STEP]
by (rule assms(2))
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<eta> : \<TT> \<mapsto>\<^sub>C\<^sub>F\<^sub>.\<^sub>l\<^sub>K\<^sub>e\<^bsub>\<alpha>\<^esub> \<FF> \<circ>\<^sub>C\<^sub>F \<KK> : \<BB> \<mapsto>\<^sub>C cat_1 \<aa> \<ff> \<mapsto>\<^sub>C \<AA>
[PROOF STEP]
interpret \<FF>: is_functor \<alpha> \<open>cat_1 \<aa> \<ff>\<close> \<AA> \<FF>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<FF> : cat_1 \<aa> \<ff> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<AA>
[PROOF STEP]
by (rule assms(3))
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<eta> : \<TT> \<mapsto>\<^sub>C\<^sub>F\<^sub>.\<^sub>l\<^sub>K\<^sub>e\<^bsub>\<alpha>\<^esub> \<FF> \<circ>\<^sub>C\<^sub>F \<KK> : \<BB> \<mapsto>\<^sub>C cat_1 \<aa> \<ff> \<mapsto>\<^sub>C \<AA>
[PROOF STEP]
from cat_1_components(1)
[PROOF STATE]
proof (chain)
picking this:
cat_1 ?\<aa> ?\<ff>\<lparr>Obj\<rparr> = ZFC_in_HOL.set {?\<aa>}
[PROOF STEP]
have \<aa>: "\<aa> \<in>\<^sub>\<circ> Vset \<alpha>"
[PROOF STATE]
proof (prove)
using this:
cat_1 ?\<aa> ?\<ff>\<lparr>Obj\<rparr> = ZFC_in_HOL.set {?\<aa>}
goal (1 subgoal):
1. \<aa> \<in>\<^sub>\<circ> Vset \<alpha>
[PROOF STEP]
by (auto simp: \<KK>.HomCod.cat_in_Obj_in_Vset)
[PROOF STATE]
proof (state)
this:
\<aa> \<in>\<^sub>\<circ> Vset \<alpha>
goal (1 subgoal):
1. \<eta> : \<TT> \<mapsto>\<^sub>C\<^sub>F\<^sub>.\<^sub>l\<^sub>K\<^sub>e\<^bsub>\<alpha>\<^esub> \<FF> \<circ>\<^sub>C\<^sub>F \<KK> : \<BB> \<mapsto>\<^sub>C cat_1 \<aa> \<ff> \<mapsto>\<^sub>C \<AA>
[PROOF STEP]
from cat_1_components(2)
[PROOF STATE]
proof (chain)
picking this:
cat_1 ?\<aa> ?\<ff>\<lparr>Arr\<rparr> = ZFC_in_HOL.set {?\<ff>}
[PROOF STEP]
have \<ff>: "\<ff> \<in>\<^sub>\<circ> Vset \<alpha>"
[PROOF STATE]
proof (prove)
using this:
cat_1 ?\<aa> ?\<ff>\<lparr>Arr\<rparr> = ZFC_in_HOL.set {?\<ff>}
goal (1 subgoal):
1. \<ff> \<in>\<^sub>\<circ> Vset \<alpha>
[PROOF STEP]
by (auto simp: \<KK>.HomCod.cat_in_Arr_in_Vset)
[PROOF STATE]
proof (state)
this:
\<ff> \<in>\<^sub>\<circ> Vset \<alpha>
goal (1 subgoal):
1. \<eta> : \<TT> \<mapsto>\<^sub>C\<^sub>F\<^sub>.\<^sub>l\<^sub>K\<^sub>e\<^bsub>\<alpha>\<^esub> \<FF> \<circ>\<^sub>C\<^sub>F \<KK> : \<BB> \<mapsto>\<^sub>C cat_1 \<aa> \<ff> \<mapsto>\<^sub>C \<AA>
[PROOF STEP]
have \<FF>\<aa>: "\<FF>\<lparr>ObjMap\<rparr>\<lparr>\<aa>\<rparr> = op_cf \<FF>\<lparr>ObjMap\<rparr>\<lparr>\<aa>\<rparr>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<FF>\<lparr>ObjMap\<rparr>\<lparr>\<aa>\<rparr> = op_cf \<FF>\<lparr>ObjMap\<rparr>\<lparr>\<aa>\<rparr>
[PROOF STEP]
unfolding cat_op_simps
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<FF>\<lparr>ObjMap\<rparr>\<lparr>\<aa>\<rparr> = \<FF>\<lparr>ObjMap\<rparr>\<lparr>\<aa>\<rparr>
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
\<FF>\<lparr>ObjMap\<rparr>\<lparr>\<aa>\<rparr> = op_cf \<FF>\<lparr>ObjMap\<rparr>\<lparr>\<aa>\<rparr>
goal (1 subgoal):
1. \<eta> : \<TT> \<mapsto>\<^sub>C\<^sub>F\<^sub>.\<^sub>l\<^sub>K\<^sub>e\<^bsub>\<alpha>\<^esub> \<FF> \<circ>\<^sub>C\<^sub>F \<KK> : \<BB> \<mapsto>\<^sub>C cat_1 \<aa> \<ff> \<mapsto>\<^sub>C \<AA>
[PROOF STEP]
note cat_1_op = \<eta>.cat_1_op[OF \<aa> \<ff>]
[PROOF STATE]
proof (state)
this:
op_cat (cat_1 \<aa> \<ff>) = cat_1 \<aa> \<ff>
goal (1 subgoal):
1. \<eta> : \<TT> \<mapsto>\<^sub>C\<^sub>F\<^sub>.\<^sub>l\<^sub>K\<^sub>e\<^bsub>\<alpha>\<^esub> \<FF> \<circ>\<^sub>C\<^sub>F \<KK> : \<BB> \<mapsto>\<^sub>C cat_1 \<aa> \<ff> \<mapsto>\<^sub>C \<AA>
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<eta> : \<TT> \<mapsto>\<^sub>C\<^sub>F\<^sub>.\<^sub>l\<^sub>K\<^sub>e\<^bsub>\<alpha>\<^esub> \<FF> \<circ>\<^sub>C\<^sub>F \<KK> : \<BB> \<mapsto>\<^sub>C cat_1 \<aa> \<ff> \<mapsto>\<^sub>C \<AA>
[PROOF STEP]
by
(
rule is_cat_rKe.is_cat_lKe_op
[
OF cat_limit_is_rKe
[
OF
\<eta>.is_cat_limit_op[unfolded \<FF>\<aa>]
\<KK>.is_functor_op[unfolded cat_1_op]
\<FF>.is_functor_op[unfolded cat_1_op]
],
unfolded cat_op_simps cat_1_op
]
)
[PROOF STATE]
proof (state)
this:
\<eta> : \<TT> \<mapsto>\<^sub>C\<^sub>F\<^sub>.\<^sub>l\<^sub>K\<^sub>e\<^bsub>\<alpha>\<^esub> \<FF> \<circ>\<^sub>C\<^sub>F \<KK> : \<BB> \<mapsto>\<^sub>C cat_1 \<aa> \<ff> \<mapsto>\<^sub>C \<AA>
goal:
No subgoals!
[PROOF STEP]
qed |
# --------------------------------------------------------
# Tensorflow Faster R-CNN
# Licensed under The MIT License [see LICENSE for details]
# Written by Zheqi He, Xinlei Chen, based on code from Ross Girshick
# --------------------------------------------------------
from __future__ import absolute_import, division, print_function
import pprint
import sys
import numpy as np
import torch
from frcnn.datasets import imdb
from frcnn.datasets.factory import get_imdb
from frcnn.model.config import (cfg, cfg_from_file, cfg_from_list,
get_output_dir, get_output_tb_dir)
from frcnn.model.train_val import get_training_roidb, train_net
from frcnn.nets.resnet_v1 import resnetv1
from frcnn.nets.vgg16 import vgg16
def combined_roidb(imdb_names):
"""
Combine multiple roidbs
"""
def get_roidb(imdb_name):
imdb = get_imdb(imdb_name)
print('Loaded dataset `{:s}` for training'.format(imdb.name))
imdb.set_proposal_method(cfg.TRAIN.PROPOSAL_METHOD)
print('Set proposal method: {:s}'.format(cfg.TRAIN.PROPOSAL_METHOD))
roidb = get_training_roidb(imdb)
return roidb
roidbs = [get_roidb(s) for s in imdb_names.split('+')]
roidb = roidbs[0]
if len(roidbs) > 1:
for r in roidbs[1:]:
roidb.extend(r)
tmp = get_imdb(imdb_names.split('+')[1])
imdb = datasets.imdb.imdb(imdb_names, tmp.classes)
else:
imdb = get_imdb(imdb_names)
return imdb, roidb
def frcnn_trainval(imdb_name, imdbval_name, max_iters, pretrained_model, pretrained_full_model, cfg_file, set_cfgs, network, tag):
"""
args = {'imdb_name':imdb_name,
'imdbval_name':imdbval_name,
'max_iters':max_iters,
'net':network,
'cfg_file':cfg_file,
'set_cfgs':set_cfgs,
'weights':weights,
'tag':tag}
"""
if cfg_file:
cfg_from_file(cfg_file)
if set_cfgs:
cfg_from_list(set_cfgs)
print('Using config:')
pprint.pprint(cfg)
np.random.seed(cfg.RNG_SEED)
# train set
imdb, roidb = combined_roidb(imdb_name)
print('{:d} roidb entries'.format(len(roidb)))
# output directory where the models are saved
output_dir = get_output_dir(imdb, tag)
print('Output will be saved to `{:s}`'.format(output_dir))
# tensorboard directory where the summaries are saved during training
tb_dir = get_output_tb_dir(imdb, tag)
print('TensorFlow summaries will be saved to `{:s}`'.format(tb_dir))
# also add the validation set, but with no flipping images
orgflip = cfg.TRAIN.USE_FLIPPED
cfg.TRAIN.USE_FLIPPED = False
#-, valroidb = combined_roidb(args['imdbval_name'])
valimdb, valroidb = combined_roidb(imdbval_name)
print('{:d} validation roidb entries'.format(len(valroidb)))
cfg.TRAIN.USE_FLIPPED = orgflip
# load network
if network == 'vgg16':
net = vgg16()
elif network == 'res50':
net = resnetv1(num_layers=50)
elif network == 'res101':
net = resnetv1(num_layers=101)
elif network == 'res152':
net = resnetv1(num_layers=152)
elif network == 'mobile':
net = mobilenetv1()
else:
raise NotImplementedError
train_net(net, imdb, roidb, valroidb, output_dir, tb_dir,
pretrained_model=pretrained_model,
pretrained_full_model=pretrained_full_model,
max_iters=max_iters)
|
/-
Copyright (c) 2018 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
-/
import order.complete_lattice
import order.galois_connection
/-!
# Relations
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines bundled relations. A relation between `α` and `β` is a function `α → β → Prop`.
Relations are also known as set-valued functions, or partial multifunctions.
## Main declarations
* `rel α β`: Relation between `α` and `β`.
* `rel.inv`: `r.inv` is the `rel β α` obtained by swapping the arguments of `r`.
* `rel.dom`: Domain of a relation. `x ∈ r.dom` iff there exists `y` such that `r x y`.
* `rel.codom`: Codomain, aka range, of a relation. `y ∈ r.codom` iff there exists `x` such that
`r x y`.
* `rel.comp`: Relation composition. Note that the arguments order follows the `category_theory/`
one, so `r.comp s x z ↔ ∃ y, r x y ∧ s y z`.
* `rel.image`: Image of a set under a relation. `r.image s` is the set of `f x` over all `x ∈ s`.
* `rel.preimage`: Preimage of a set under a relation. Note that `r.preimage = r.inv.image`.
* `rel.core`: Core of a set. For `s : set β`, `r.core s` is the set of `x : α` such that all `y`
related to `x` are in `s`.
* `rel.restrict_domain`: Domain-restriction of a relation to a subtype.
* `function.graph`: Graph of a function as a relation.
-/
variables {α β γ : Type*}
/-- A relation on `α` and `β`, aka a set-valued function, aka a partial multifunction -/
@[derive complete_lattice, derive inhabited]
def rel (α β : Type*) := α → β → Prop
namespace rel
variables {δ : Type*} (r : rel α β)
/-- The inverse relation : `r.inv x y ↔ r y x`. Note that this is *not* a groupoid inverse. -/
def inv : rel β α := flip r
lemma inv_def (x : α) (y : β) : r.inv y x ↔ r x y := iff.rfl
lemma inv_inv : inv (inv r) = r := by { ext x y, reflexivity }
/-- Domain of a relation -/
def dom := {x | ∃ y, r x y}
lemma dom_mono {r s : rel α β} (h : r ≤ s) : dom r ⊆ dom s :=
λ a ⟨b, hx⟩, ⟨b, h a b hx⟩
/-- Codomain aka range of a relation -/
def codom := {y | ∃ x, r x y}
lemma codom_inv : r.inv.codom = r.dom := by { ext x y, reflexivity }
lemma dom_inv : r.inv.dom = r.codom := by { ext x y, reflexivity}
/-- Composition of relation; note that it follows the `category_theory/` order of arguments. -/
def comp (r : rel α β) (s : rel β γ) : rel α γ :=
λ x z, ∃ y, r x y ∧ s y z
local infixr (name := rel.comp) ` ∘ ` := rel.comp
lemma comp_assoc (r : rel α β) (s : rel β γ) (t : rel γ δ) :
(r ∘ s) ∘ t = r ∘ s ∘ t :=
begin
unfold comp, ext x w, split,
{ rintros ⟨z, ⟨y, rxy, syz⟩, tzw⟩, exact ⟨y, rxy, z, syz, tzw⟩ },
rintros ⟨y, rxy, z, syz, tzw⟩, exact ⟨z, ⟨y, rxy, syz⟩, tzw⟩
end
@[simp]
lemma comp_right_id (r : rel α β) : r ∘ @eq β = r :=
by { unfold comp, ext y, simp }
@[simp]
lemma comp_left_id (r : rel α β) : @eq α ∘ r = r :=
by { unfold comp, ext x, simp }
lemma inv_id : inv (@eq α) = @eq α :=
by { ext x y, split; apply eq.symm }
lemma inv_comp (r : rel α β) (s : rel β γ) : inv (r ∘ s) = inv s ∘ inv r :=
by { ext x z, simp [comp, inv, flip, and.comm] }
/-- Image of a set under a relation -/
def image (s : set α) : set β := {y | ∃ x ∈ s, r x y}
lemma mem_image (y : β) (s : set α) : y ∈ image r s ↔ ∃ x ∈ s, r x y :=
iff.rfl
lemma image_subset : ((⊆) ⇒ (⊆)) r.image r.image :=
λ s t h y ⟨x, xs, rxy⟩, ⟨x, h xs, rxy⟩
lemma image_mono : monotone r.image := r.image_subset
lemma image_inter (s t : set α) : r.image (s ∩ t) ⊆ r.image s ∩ r.image t :=
r.image_mono.map_inf_le s t
lemma image_union (s t : set α) : r.image (s ∪ t) = r.image s ∪ r.image t :=
le_antisymm
(λ y ⟨x, xst, rxy⟩, xst.elim (λ xs, or.inl ⟨x, ⟨xs, rxy⟩⟩) (λ xt, or.inr ⟨x, ⟨xt, rxy⟩⟩))
(r.image_mono.le_map_sup s t)
@[simp]
lemma image_id (s : set α) : image (@eq α) s = s :=
by { ext x, simp [mem_image] }
lemma image_comp (s : rel β γ) (t : set α) : image (r ∘ s) t = image s (image r t) :=
begin
ext z, simp only [mem_image], split,
{ rintros ⟨x, xt, y, rxy, syz⟩, exact ⟨y, ⟨x, xt, rxy⟩, syz⟩ },
rintros ⟨y, ⟨x, xt, rxy⟩, syz⟩, exact ⟨x, xt, y, rxy, syz⟩
end
lemma image_univ : r.image set.univ = r.codom := by { ext y, simp [mem_image, codom] }
/-- Preimage of a set under a relation `r`. Same as the image of `s` under `r.inv` -/
def preimage (s : set β) : set α := r.inv.image s
lemma mem_preimage (x : α) (s : set β) : x ∈ r.preimage s ↔ ∃ y ∈ s, r x y :=
iff.rfl
lemma preimage_def (s : set β) : preimage r s = {x | ∃ y ∈ s, r x y} :=
set.ext $ λ x, mem_preimage _ _ _
lemma preimage_mono {s t : set β} (h : s ⊆ t) : r.preimage s ⊆ r.preimage t :=
image_mono _ h
lemma preimage_inter (s t : set β) : r.preimage (s ∩ t) ⊆ r.preimage s ∩ r.preimage t :=
image_inter _ s t
lemma preimage_union (s t : set β) : r.preimage (s ∪ t) = r.preimage s ∪ r.preimage t :=
image_union _ s t
lemma preimage_id (s : set α) : preimage (@eq α) s = s :=
by simp only [preimage, inv_id, image_id]
lemma preimage_comp (s : rel β γ) (t : set γ) :
preimage (r ∘ s) t = preimage r (preimage s t) :=
by simp only [preimage, inv_comp, image_comp]
lemma preimage_univ : r.preimage set.univ = r.dom :=
by { rw [preimage, image_univ, codom_inv] }
/-- Core of a set `s : set β` w.r.t `r : rel α β` is the set of `x : α` that are related *only*
to elements of `s`. Other generalization of `function.preimage`. -/
def core (s : set β) := {x | ∀ y, r x y → y ∈ s}
lemma mem_core (x : α) (s : set β) : x ∈ r.core s ↔ ∀ y, r x y → y ∈ s :=
iff.rfl
lemma core_subset : ((⊆) ⇒ (⊆)) r.core r.core :=
λ s t h x h' y rxy, h (h' y rxy)
lemma core_mono : monotone r.core := r.core_subset
lemma core_inter (s t : set β) : r.core (s ∩ t) = r.core s ∩ r.core t :=
set.ext (by simp [mem_core, imp_and_distrib, forall_and_distrib])
lemma core_union (s t : set β) : r.core s ∪ r.core t ⊆ r.core (s ∪ t) :=
r.core_mono.le_map_sup s t
@[simp] lemma core_univ : r.core set.univ = set.univ := set.ext (by simp [mem_core])
lemma core_id (s : set α) : core (@eq α) s = s :=
by simp [core]
lemma core_comp (s : rel β γ) (t : set γ) :
core (r ∘ s) t = core r (core s t) :=
begin
ext x, simp [core, comp], split,
{ exact λ h y rxy z, h z y rxy },
{ exact λ h z y rzy, h y rzy z }
end
/-- Restrict the domain of a relation to a subtype. -/
def restrict_domain (s : set α) : rel {x // x ∈ s} β :=
λ x y, r x.val y
theorem image_subset_iff (s : set α) (t : set β) : image r s ⊆ t ↔ s ⊆ core r t :=
iff.intro
(λ h x xs y rxy, h ⟨x, xs, rxy⟩)
(λ h y ⟨x, xs, rxy⟩, h xs y rxy)
end rel
namespace function
/-- The graph of a function as a relation. -/
def graph (f : α → β) : rel α β := λ x y, f x = y
end function
namespace set
-- TODO: if image were defined with bounded quantification in corelib, the next two would
-- be definitional
lemma image_eq (f : α → β) (s : set α) : f '' s = (function.graph f).image s :=
by simp [set.image, function.graph, rel.image]
lemma preimage_eq (f : α → β) (s : set β) :
f ⁻¹' s = (function.graph f).preimage s :=
by simp [set.preimage, function.graph, rel.preimage, rel.inv, flip, rel.image]
lemma preimage_eq_core (f : α → β) (s : set β) :
f ⁻¹' s = (function.graph f).core s :=
by simp [set.preimage, function.graph, rel.core]
end set
|
/-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Kenny Lau
! This file was ported from Lean 3 source module data.list.zip
! leanprover-community/mathlib commit be24ec5de6701447e5df5ca75400ffee19d65659
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.Data.List.BigOperators.Basic
import Mathbin.Algebra.Order.Monoid.MinMax
/-!
# zip & unzip
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file provides results about `list.zip_with`, `list.zip` and `list.unzip` (definitions are in
core Lean).
`zip_with f l₁ l₂` applies `f : α → β → γ` pointwise to a list `l₁ : list α` and `l₂ : list β`. It
applies, until one of the lists is exhausted. For example,
`zip_with f [0, 1, 2] [6.28, 31] = [f 0 6.28, f 1 31]`.
`zip` is `zip_with` applied to `prod.mk`. For example,
`zip [a₁, a₂] [b₁, b₂, b₃] = [(a₁, b₁), (a₂, b₂)]`.
`unzip` undoes `zip`. For example, `unzip [(a₁, b₁), (a₂, b₂)] = ([a₁, a₂], [b₁, b₂])`.
-/
universe u
open Nat
namespace List
variable {α : Type u} {β γ δ ε : Type _}
/- warning: list.zip_with_cons_cons -> List.zipWith_cons_cons is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} (f : α -> β -> γ) (a : α) (b : β) (l₁ : List.{u1} α) (l₂ : List.{u2} β), Eq.{succ u3} (List.{u3} γ) (List.zipWith.{u1, u2, u3} α β γ f (List.cons.{u1} α a l₁) (List.cons.{u2} β b l₂)) (List.cons.{u3} γ (f a b) (List.zipWith.{u1, u2, u3} α β γ f l₁ l₂))
but is expected to have type
forall {α : Type.{u3}} {β : Type.{u2}} {γ : Type.{u1}} (f : α -> β -> γ) (a : α) (b : β) (l₁ : List.{u3} α) (l₂ : List.{u2} β), Eq.{succ u1} (List.{u1} γ) (List.zipWith.{u3, u2, u1} α β γ f (List.cons.{u3} α a l₁) (List.cons.{u2} β b l₂)) (List.cons.{u1} γ (f a b) (List.zipWith.{u3, u2, u1} α β γ f l₁ l₂))
Case conversion may be inaccurate. Consider using '#align list.zip_with_cons_cons List.zipWith_cons_consₓ'. -/
@[simp]
theorem zipWith_cons_cons (f : α → β → γ) (a : α) (b : β) (l₁ : List α) (l₂ : List β) :
zipWith f (a :: l₁) (b :: l₂) = f a b :: zipWith f l₁ l₂ :=
rfl
#align list.zip_with_cons_cons List.zipWith_cons_cons
/- warning: list.zip_cons_cons -> List.zip_cons_cons is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} (a : α) (b : β) (l₁ : List.{u1} α) (l₂ : List.{u2} β), Eq.{succ (max u1 u2)} (List.{max u1 u2} (Prod.{u1, u2} α β)) (List.zip.{u1, u2} α β (List.cons.{u1} α a l₁) (List.cons.{u2} β b l₂)) (List.cons.{max u1 u2} (Prod.{u1, u2} α β) (Prod.mk.{u1, u2} α β a b) (List.zip.{u1, u2} α β l₁ l₂))
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} (a : α) (b : β) (l₁ : List.{u2} α) (l₂ : List.{u1} β), Eq.{max (succ u2) (succ u1)} (List.{max u1 u2} (Prod.{u2, u1} α β)) (List.zip.{u2, u1} α β (List.cons.{u2} α a l₁) (List.cons.{u1} β b l₂)) (List.cons.{max u1 u2} (Prod.{u2, u1} α β) (Prod.mk.{u2, u1} α β a b) (List.zip.{u2, u1} α β l₁ l₂))
Case conversion may be inaccurate. Consider using '#align list.zip_cons_cons List.zip_cons_consₓ'. -/
@[simp]
theorem zip_cons_cons (a : α) (b : β) (l₁ : List α) (l₂ : List β) :
zip (a :: l₁) (b :: l₂) = (a, b) :: zip l₁ l₂ :=
rfl
#align list.zip_cons_cons List.zip_cons_cons
/- warning: list.zip_with_nil_left -> List.zipWith_nil_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} (f : α -> β -> γ) (l : List.{u2} β), Eq.{succ u3} (List.{u3} γ) (List.zipWith.{u1, u2, u3} α β γ f (List.nil.{u1} α) l) (List.nil.{u3} γ)
but is expected to have type
forall {α : Type.{u3}} {β : Type.{u2}} {γ : Type.{u1}} (f : α -> β -> γ) (l : List.{u2} β), Eq.{succ u1} (List.{u1} γ) (List.zipWith.{u3, u2, u1} α β γ f (List.nil.{u3} α) l) (List.nil.{u1} γ)
Case conversion may be inaccurate. Consider using '#align list.zip_with_nil_left List.zipWith_nil_leftₓ'. -/
@[simp]
theorem zipWith_nil_left (f : α → β → γ) (l) : zipWith f [] l = [] :=
rfl
#align list.zip_with_nil_left List.zipWith_nil_left
/- warning: list.zip_with_nil_right -> List.zipWith_nil_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} (f : α -> β -> γ) (l : List.{u1} α), Eq.{succ u3} (List.{u3} γ) (List.zipWith.{u1, u2, u3} α β γ f l (List.nil.{u2} β)) (List.nil.{u3} γ)
but is expected to have type
forall {α : Type.{u3}} {β : Type.{u1}} {γ : Type.{u2}} (f : α -> β -> γ) (l : List.{u3} α), Eq.{succ u2} (List.{u2} γ) (List.zipWith.{u3, u1, u2} α β γ f l (List.nil.{u1} β)) (List.nil.{u2} γ)
Case conversion may be inaccurate. Consider using '#align list.zip_with_nil_right List.zipWith_nil_rightₓ'. -/
@[simp]
theorem zipWith_nil_right (f : α → β → γ) (l) : zipWith f l [] = [] := by cases l <;> rfl
#align list.zip_with_nil_right List.zipWith_nil_right
/- warning: list.zip_with_eq_nil_iff -> List.zipWith_eq_nil_iff is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} {f : α -> β -> γ} {l : List.{u1} α} {l' : List.{u2} β}, Iff (Eq.{succ u3} (List.{u3} γ) (List.zipWith.{u1, u2, u3} α β γ f l l') (List.nil.{u3} γ)) (Or (Eq.{succ u1} (List.{u1} α) l (List.nil.{u1} α)) (Eq.{succ u2} (List.{u2} β) l' (List.nil.{u2} β)))
but is expected to have type
forall {α : Type.{u3}} {β : Type.{u2}} {γ : Type.{u1}} {f : α -> β -> γ} {l : List.{u3} α} {l' : List.{u2} β}, Iff (Eq.{succ u1} (List.{u1} γ) (List.zipWith.{u3, u2, u1} α β γ f l l') (List.nil.{u1} γ)) (Or (Eq.{succ u3} (List.{u3} α) l (List.nil.{u3} α)) (Eq.{succ u2} (List.{u2} β) l' (List.nil.{u2} β)))
Case conversion may be inaccurate. Consider using '#align list.zip_with_eq_nil_iff List.zipWith_eq_nil_iffₓ'. -/
@[simp]
theorem zipWith_eq_nil_iff {f : α → β → γ} {l l'} : zipWith f l l' = [] ↔ l = [] ∨ l' = [] := by
cases l <;> cases l' <;> simp
#align list.zip_with_eq_nil_iff List.zipWith_eq_nil_iff
/- warning: list.zip_nil_left -> List.zip_nil_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} (l : List.{u1} α), Eq.{succ (max u2 u1)} (List.{max u2 u1} (Prod.{u2, u1} β α)) (List.zip.{u2, u1} β α (List.nil.{u2} β) l) (List.nil.{max u2 u1} (Prod.{u2, u1} β α))
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} (l : List.{u2} α), Eq.{max (succ u2) (succ u1)} (List.{max u2 u1} (Prod.{u1, u2} β α)) (List.zip.{u1, u2} β α (List.nil.{u1} β) l) (List.nil.{max u2 u1} (Prod.{u1, u2} β α))
Case conversion may be inaccurate. Consider using '#align list.zip_nil_left List.zip_nil_leftₓ'. -/
@[simp]
theorem zip_nil_left (l : List α) : zip ([] : List β) l = [] :=
rfl
#align list.zip_nil_left List.zip_nil_left
/- warning: list.zip_nil_right -> List.zip_nil_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} (l : List.{u1} α), Eq.{succ (max u1 u2)} (List.{max u1 u2} (Prod.{u1, u2} α β)) (List.zip.{u1, u2} α β l (List.nil.{u2} β)) (List.nil.{max u1 u2} (Prod.{u1, u2} α β))
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} (l : List.{u2} α), Eq.{max (succ u2) (succ u1)} (List.{max u1 u2} (Prod.{u2, u1} α β)) (List.zip.{u2, u1} α β l (List.nil.{u1} β)) (List.nil.{max u2 u1} (Prod.{u2, u1} α β))
Case conversion may be inaccurate. Consider using '#align list.zip_nil_right List.zip_nil_rightₓ'. -/
@[simp]
theorem zip_nil_right (l : List α) : zip l ([] : List β) = [] :=
zipWith_nil_right _ l
#align list.zip_nil_right List.zip_nil_right
/- warning: list.zip_swap -> List.zip_swap is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} (l₁ : List.{u1} α) (l₂ : List.{u2} β), Eq.{succ (max u2 u1)} (List.{max u2 u1} (Prod.{u2, u1} β α)) (List.map.{max u1 u2, max u2 u1} (Prod.{u1, u2} α β) (Prod.{u2, u1} β α) (Prod.swap.{u1, u2} α β) (List.zip.{u1, u2} α β l₁ l₂)) (List.zip.{u2, u1} β α l₂ l₁)
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} (l₁ : List.{u2} α) (l₂ : List.{u1} β), Eq.{max (succ u2) (succ u1)} (List.{max u1 u2} (Prod.{u1, u2} β α)) (List.map.{max u1 u2, max u1 u2} (Prod.{u2, u1} α β) (Prod.{u1, u2} β α) (Prod.swap.{u2, u1} α β) (List.zip.{u2, u1} α β l₁ l₂)) (List.zip.{u1, u2} β α l₂ l₁)
Case conversion may be inaccurate. Consider using '#align list.zip_swap List.zip_swapₓ'. -/
@[simp]
theorem zip_swap : ∀ (l₁ : List α) (l₂ : List β), (zip l₁ l₂).map Prod.swap = zip l₂ l₁
| [], l₂ => (zip_nil_right _).symm
| l₁, [] => by rw [zip_nil_right] <;> rfl
| a :: l₁, b :: l₂ => by
simp only [zip_cons_cons, map_cons, zip_swap l₁ l₂, Prod.swap_prod_mk] <;> constructor <;> rfl
#align list.zip_swap List.zip_swap
/- warning: list.length_zip_with clashes with list.length_map₂ -> List.length_zipWith
warning: list.length_zip_with -> List.length_zipWith is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} (f : α -> β -> γ) (l₁ : List.{u1} α) (l₂ : List.{u2} β), Eq.{1} Nat (List.length.{u3} γ (List.zipWith.{u1, u2, u3} α β γ f l₁ l₂)) (LinearOrder.min.{0} Nat Nat.linearOrder (List.length.{u1} α l₁) (List.length.{u2} β l₂))
but is expected to have type
forall {α : Type.{u3}} {β : Type.{u2}} {γ : Type.{u1}} (f : α -> β -> γ) (l₁ : List.{u3} α) (l₂ : List.{u2} β), Eq.{1} Nat (List.length.{u1} γ (List.zipWith.{u3, u2, u1} α β γ f l₁ l₂)) (Min.min.{0} Nat instMinNat (List.length.{u3} α l₁) (List.length.{u2} β l₂))
Case conversion may be inaccurate. Consider using '#align list.length_zip_with List.length_zipWithₓ'. -/
@[simp]
theorem length_zipWith (f : α → β → γ) :
∀ (l₁ : List α) (l₂ : List β), length (zipWith f l₁ l₂) = min (length l₁) (length l₂)
| [], l₂ => rfl
| l₁, [] => by simp only [length, min_zero, zip_with_nil_right]
| a :: l₁, b :: l₂ => by simp [length, zip_cons_cons, length_zip_with l₁ l₂, min_add_add_right]
#align list.length_zip_with List.length_zipWith
/- warning: list.length_zip -> List.length_zip is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} (l₁ : List.{u1} α) (l₂ : List.{u2} β), Eq.{1} Nat (List.length.{max u1 u2} (Prod.{u1, u2} α β) (List.zip.{u1, u2} α β l₁ l₂)) (LinearOrder.min.{0} Nat Nat.linearOrder (List.length.{u1} α l₁) (List.length.{u2} β l₂))
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} (l₁ : List.{u2} α) (l₂ : List.{u1} β), Eq.{1} Nat (List.length.{max u1 u2} (Prod.{u2, u1} α β) (List.zip.{u2, u1} α β l₁ l₂)) (Min.min.{0} Nat instMinNat (List.length.{u2} α l₁) (List.length.{u1} β l₂))
Case conversion may be inaccurate. Consider using '#align list.length_zip List.length_zipₓ'. -/
@[simp]
theorem length_zip :
∀ (l₁ : List α) (l₂ : List β), length (zip l₁ l₂) = min (length l₁) (length l₂) :=
length_zipWith _
#align list.length_zip List.length_zip
/- warning: list.all₂_zip_with -> List.all₂_zipWith is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} {f : α -> β -> γ} {p : γ -> Prop} {l₁ : List.{u1} α} {l₂ : List.{u2} β}, (Eq.{1} Nat (List.length.{u1} α l₁) (List.length.{u2} β l₂)) -> (Iff (List.All₂.{u3} γ p (List.zipWith.{u1, u2, u3} α β γ f l₁ l₂)) (List.Forall₂.{u1, u2} α β (fun (x : α) (y : β) => p (f x y)) l₁ l₂))
but is expected to have type
forall {α : Type.{u3}} {β : Type.{u2}} {γ : Type.{u1}} {f : α -> β -> γ} {p : γ -> Prop} {l₁ : List.{u3} α} {l₂ : List.{u2} β}, (Eq.{1} Nat (List.length.{u3} α l₁) (List.length.{u2} β l₂)) -> (Iff (List.All₂.{u1} γ p (List.zipWith.{u3, u2, u1} α β γ f l₁ l₂)) (List.Forall₂.{u3, u2} α β (fun (x : α) (y : β) => p (f x y)) l₁ l₂))
Case conversion may be inaccurate. Consider using '#align list.all₂_zip_with List.all₂_zipWithₓ'. -/
theorem all₂_zipWith {f : α → β → γ} {p : γ → Prop} :
∀ {l₁ : List α} {l₂ : List β} (h : length l₁ = length l₂),
All₂ p (zipWith f l₁ l₂) ↔ Forall₂ (fun x y => p (f x y)) l₁ l₂
| [], [], _ => by simp
| a :: l₁, b :: l₂, h => by
simp only [length_cons, add_left_inj] at h
simp [all₂_zip_with h]
#align list.all₂_zip_with List.all₂_zipWith
/- warning: list.lt_length_left_of_zip_with -> List.lt_length_left_of_zipWith is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} {f : α -> β -> γ} {i : Nat} {l : List.{u1} α} {l' : List.{u2} β}, (LT.lt.{0} Nat Nat.hasLt i (List.length.{u3} γ (List.zipWith.{u1, u2, u3} α β γ f l l'))) -> (LT.lt.{0} Nat Nat.hasLt i (List.length.{u1} α l))
but is expected to have type
forall {α : Type.{u3}} {β : Type.{u2}} {γ : Type.{u1}} {f : α -> β -> γ} {i : Nat} {l : List.{u3} α} {l' : List.{u2} β}, (LT.lt.{0} Nat instLTNat i (List.length.{u1} γ (List.zipWith.{u3, u2, u1} α β γ f l l'))) -> (LT.lt.{0} Nat instLTNat i (List.length.{u3} α l))
Case conversion may be inaccurate. Consider using '#align list.lt_length_left_of_zip_with List.lt_length_left_of_zipWithₓ'. -/
theorem lt_length_left_of_zipWith {f : α → β → γ} {i : ℕ} {l : List α} {l' : List β}
(h : i < (zipWith f l l').length) : i < l.length :=
by
rw [length_zip_with, lt_min_iff] at h
exact h.left
#align list.lt_length_left_of_zip_with List.lt_length_left_of_zipWith
/- warning: list.lt_length_right_of_zip_with -> List.lt_length_right_of_zipWith is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} {f : α -> β -> γ} {i : Nat} {l : List.{u1} α} {l' : List.{u2} β}, (LT.lt.{0} Nat Nat.hasLt i (List.length.{u3} γ (List.zipWith.{u1, u2, u3} α β γ f l l'))) -> (LT.lt.{0} Nat Nat.hasLt i (List.length.{u2} β l'))
but is expected to have type
forall {α : Type.{u3}} {β : Type.{u2}} {γ : Type.{u1}} {f : α -> β -> γ} {i : Nat} {l : List.{u3} α} {l' : List.{u2} β}, (LT.lt.{0} Nat instLTNat i (List.length.{u1} γ (List.zipWith.{u3, u2, u1} α β γ f l l'))) -> (LT.lt.{0} Nat instLTNat i (List.length.{u2} β l'))
Case conversion may be inaccurate. Consider using '#align list.lt_length_right_of_zip_with List.lt_length_right_of_zipWithₓ'. -/
theorem lt_length_right_of_zipWith {f : α → β → γ} {i : ℕ} {l : List α} {l' : List β}
(h : i < (zipWith f l l').length) : i < l'.length :=
by
rw [length_zip_with, lt_min_iff] at h
exact h.right
#align list.lt_length_right_of_zip_with List.lt_length_right_of_zipWith
/- warning: list.lt_length_left_of_zip -> List.lt_length_left_of_zip is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {i : Nat} {l : List.{u1} α} {l' : List.{u2} β}, (LT.lt.{0} Nat Nat.hasLt i (List.length.{max u1 u2} (Prod.{u1, u2} α β) (List.zip.{u1, u2} α β l l'))) -> (LT.lt.{0} Nat Nat.hasLt i (List.length.{u1} α l))
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} {i : Nat} {l : List.{u2} α} {l' : List.{u1} β}, (LT.lt.{0} Nat instLTNat i (List.length.{max u2 u1} (Prod.{u2, u1} α β) (List.zip.{u2, u1} α β l l'))) -> (LT.lt.{0} Nat instLTNat i (List.length.{u2} α l))
Case conversion may be inaccurate. Consider using '#align list.lt_length_left_of_zip List.lt_length_left_of_zipₓ'. -/
theorem lt_length_left_of_zip {i : ℕ} {l : List α} {l' : List β} (h : i < (zip l l').length) :
i < l.length :=
lt_length_left_of_zipWith h
#align list.lt_length_left_of_zip List.lt_length_left_of_zip
/- warning: list.lt_length_right_of_zip -> List.lt_length_right_of_zip is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {i : Nat} {l : List.{u1} α} {l' : List.{u2} β}, (LT.lt.{0} Nat Nat.hasLt i (List.length.{max u1 u2} (Prod.{u1, u2} α β) (List.zip.{u1, u2} α β l l'))) -> (LT.lt.{0} Nat Nat.hasLt i (List.length.{u2} β l'))
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} {i : Nat} {l : List.{u2} α} {l' : List.{u1} β}, (LT.lt.{0} Nat instLTNat i (List.length.{max u2 u1} (Prod.{u2, u1} α β) (List.zip.{u2, u1} α β l l'))) -> (LT.lt.{0} Nat instLTNat i (List.length.{u1} β l'))
Case conversion may be inaccurate. Consider using '#align list.lt_length_right_of_zip List.lt_length_right_of_zipₓ'. -/
theorem lt_length_right_of_zip {i : ℕ} {l : List α} {l' : List β} (h : i < (zip l l').length) :
i < l'.length :=
lt_length_right_of_zipWith h
#align list.lt_length_right_of_zip List.lt_length_right_of_zip
/- warning: list.zip_append -> List.zip_append is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {l₁ : List.{u1} α} {r₁ : List.{u1} α} {l₂ : List.{u2} β} {r₂ : List.{u2} β}, (Eq.{1} Nat (List.length.{u1} α l₁) (List.length.{u2} β l₂)) -> (Eq.{succ (max u1 u2)} (List.{max u1 u2} (Prod.{u1, u2} α β)) (List.zip.{u1, u2} α β (Append.append.{u1} (List.{u1} α) (List.hasAppend.{u1} α) l₁ r₁) (Append.append.{u2} (List.{u2} β) (List.hasAppend.{u2} β) l₂ r₂)) (Append.append.{max u1 u2} (List.{max u1 u2} (Prod.{u1, u2} α β)) (List.hasAppend.{max u1 u2} (Prod.{u1, u2} α β)) (List.zip.{u1, u2} α β l₁ l₂) (List.zip.{u1, u2} α β r₁ r₂)))
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} {l₁ : List.{u2} α} {r₁ : List.{u2} α} {l₂ : List.{u1} β} {r₂ : List.{u1} β}, (Eq.{1} Nat (List.length.{u2} α l₁) (List.length.{u1} β l₂)) -> (Eq.{max (succ u2) (succ u1)} (List.{max u1 u2} (Prod.{u2, u1} α β)) (List.zip.{u2, u1} α β (HAppend.hAppend.{u2, u2, u2} (List.{u2} α) (List.{u2} α) (List.{u2} α) (instHAppend.{u2} (List.{u2} α) (List.instAppendList.{u2} α)) l₁ r₁) (HAppend.hAppend.{u1, u1, u1} (List.{u1} β) (List.{u1} β) (List.{u1} β) (instHAppend.{u1} (List.{u1} β) (List.instAppendList.{u1} β)) l₂ r₂)) (HAppend.hAppend.{max u2 u1, max u2 u1, max u2 u1} (List.{max u1 u2} (Prod.{u2, u1} α β)) (List.{max u1 u2} (Prod.{u2, u1} α β)) (List.{max u1 u2} (Prod.{u2, u1} α β)) (instHAppend.{max u2 u1} (List.{max u1 u2} (Prod.{u2, u1} α β)) (List.instAppendList.{max u2 u1} (Prod.{u2, u1} α β))) (List.zip.{u2, u1} α β l₁ l₂) (List.zip.{u2, u1} α β r₁ r₂)))
Case conversion may be inaccurate. Consider using '#align list.zip_append List.zip_appendₓ'. -/
theorem zip_append :
∀ {l₁ r₁ : List α} {l₂ r₂ : List β} (h : length l₁ = length l₂),
zip (l₁ ++ r₁) (l₂ ++ r₂) = zip l₁ l₂ ++ zip r₁ r₂
| [], r₁, l₂, r₂, h => by simp only [eq_nil_of_length_eq_zero h.symm] <;> rfl
| l₁, r₁, [], r₂, h => by simp only [eq_nil_of_length_eq_zero h] <;> rfl
| a :: l₁, r₁, b :: l₂, r₂, h => by
simp only [cons_append, zip_cons_cons, zip_append (succ.inj h)] <;> constructor <;> rfl
#align list.zip_append List.zip_append
/- warning: list.zip_map -> List.zip_map is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} {δ : Type.{u4}} (f : α -> γ) (g : β -> δ) (l₁ : List.{u1} α) (l₂ : List.{u2} β), Eq.{succ (max u3 u4)} (List.{max u3 u4} (Prod.{u3, u4} γ δ)) (List.zip.{u3, u4} γ δ (List.map.{u1, u3} α γ f l₁) (List.map.{u2, u4} β δ g l₂)) (List.map.{max u1 u2, max u3 u4} (Prod.{u1, u2} α β) (Prod.{u3, u4} γ δ) (Prod.map.{u1, u3, u2, u4} α γ β δ f g) (List.zip.{u1, u2} α β l₁ l₂))
but is expected to have type
forall {α : Type.{u4}} {β : Type.{u3}} {γ : Type.{u2}} {δ : Type.{u1}} (f : α -> γ) (g : β -> δ) (l₁ : List.{u4} α) (l₂ : List.{u3} β), Eq.{max (succ u2) (succ u1)} (List.{max u1 u2} (Prod.{u2, u1} γ δ)) (List.zip.{u2, u1} γ δ (List.map.{u4, u2} α γ f l₁) (List.map.{u3, u1} β δ g l₂)) (List.map.{max u3 u4, max u1 u2} (Prod.{u4, u3} α β) (Prod.{u2, u1} γ δ) (Prod.map.{u4, u2, u3, u1} α γ β δ f g) (List.zip.{u4, u3} α β l₁ l₂))
Case conversion may be inaccurate. Consider using '#align list.zip_map List.zip_mapₓ'. -/
theorem zip_map (f : α → γ) (g : β → δ) :
∀ (l₁ : List α) (l₂ : List β), zip (l₁.map f) (l₂.map g) = (zip l₁ l₂).map (Prod.map f g)
| [], l₂ => rfl
| l₁, [] => by simp only [map, zip_nil_right]
| a :: l₁, b :: l₂ => by
simp only [map, zip_cons_cons, zip_map l₁ l₂, Prod.map] <;> constructor <;> rfl
#align list.zip_map List.zip_map
/- warning: list.zip_map_left -> List.zip_map_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} (f : α -> γ) (l₁ : List.{u1} α) (l₂ : List.{u2} β), Eq.{succ (max u3 u2)} (List.{max u3 u2} (Prod.{u3, u2} γ β)) (List.zip.{u3, u2} γ β (List.map.{u1, u3} α γ f l₁) l₂) (List.map.{max u1 u2, max u3 u2} (Prod.{u1, u2} α β) (Prod.{u3, u2} γ β) (Prod.map.{u1, u3, u2, u2} α γ β β f (id.{succ u2} β)) (List.zip.{u1, u2} α β l₁ l₂))
but is expected to have type
forall {α : Type.{u3}} {β : Type.{u2}} {γ : Type.{u1}} (f : α -> γ) (l₁ : List.{u3} α) (l₂ : List.{u2} β), Eq.{max (succ u2) (succ u1)} (List.{max u2 u1} (Prod.{u1, u2} γ β)) (List.zip.{u1, u2} γ β (List.map.{u3, u1} α γ f l₁) l₂) (List.map.{max u2 u3, max u2 u1} (Prod.{u3, u2} α β) (Prod.{u1, u2} γ β) (Prod.map.{u3, u1, u2, u2} α γ β β f (id.{succ u2} β)) (List.zip.{u3, u2} α β l₁ l₂))
Case conversion may be inaccurate. Consider using '#align list.zip_map_left List.zip_map_leftₓ'. -/
theorem zip_map_left (f : α → γ) (l₁ : List α) (l₂ : List β) :
zip (l₁.map f) l₂ = (zip l₁ l₂).map (Prod.map f id) := by rw [← zip_map, map_id]
#align list.zip_map_left List.zip_map_left
/- warning: list.zip_map_right -> List.zip_map_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} (f : β -> γ) (l₁ : List.{u1} α) (l₂ : List.{u2} β), Eq.{succ (max u1 u3)} (List.{max u1 u3} (Prod.{u1, u3} α γ)) (List.zip.{u1, u3} α γ l₁ (List.map.{u2, u3} β γ f l₂)) (List.map.{max u1 u2, max u1 u3} (Prod.{u1, u2} α β) (Prod.{u1, u3} α γ) (Prod.map.{u1, u1, u2, u3} α α β γ (id.{succ u1} α) f) (List.zip.{u1, u2} α β l₁ l₂))
but is expected to have type
forall {α : Type.{u3}} {β : Type.{u2}} {γ : Type.{u1}} (f : β -> γ) (l₁ : List.{u3} α) (l₂ : List.{u2} β), Eq.{max (succ u3) (succ u1)} (List.{max u1 u3} (Prod.{u3, u1} α γ)) (List.zip.{u3, u1} α γ l₁ (List.map.{u2, u1} β γ f l₂)) (List.map.{max u2 u3, max u1 u3} (Prod.{u3, u2} α β) (Prod.{u3, u1} α γ) (Prod.map.{u3, u3, u2, u1} α α β γ (id.{succ u3} α) f) (List.zip.{u3, u2} α β l₁ l₂))
Case conversion may be inaccurate. Consider using '#align list.zip_map_right List.zip_map_rightₓ'. -/
theorem zip_map_right (f : β → γ) (l₁ : List α) (l₂ : List β) :
zip l₁ (l₂.map f) = (zip l₁ l₂).map (Prod.map id f) := by rw [← zip_map, map_id]
#align list.zip_map_right List.zip_map_right
/- warning: list.zip_with_map -> List.zipWith_map is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} {δ : Type.{u4}} {μ : Type.{u5}} (f : γ -> δ -> μ) (g : α -> γ) (h : β -> δ) (as : List.{u1} α) (bs : List.{u2} β), Eq.{succ u5} (List.{u5} μ) (List.zipWith.{u3, u4, u5} γ δ μ f (List.map.{u1, u3} α γ g as) (List.map.{u2, u4} β δ h bs)) (List.zipWith.{u1, u2, u5} α β μ (fun (a : α) (b : β) => f (g a) (h b)) as bs)
but is expected to have type
forall {α : Type.{u5}} {β : Type.{u3}} {γ : Type.{u2}} {δ : Type.{u1}} {μ : Type.{u4}} (f : γ -> δ -> μ) (g : α -> γ) (h : β -> δ) (as : List.{u5} α) (bs : List.{u3} β), Eq.{succ u4} (List.{u4} μ) (List.zipWith.{u2, u1, u4} γ δ μ f (List.map.{u5, u2} α γ g as) (List.map.{u3, u1} β δ h bs)) (List.zipWith.{u5, u3, u4} α β μ (fun (a : α) (b : β) => f (g a) (h b)) as bs)
Case conversion may be inaccurate. Consider using '#align list.zip_with_map List.zipWith_mapₓ'. -/
@[simp]
theorem zipWith_map {μ} (f : γ → δ → μ) (g : α → γ) (h : β → δ) (as : List α) (bs : List β) :
zipWith f (as.map g) (bs.map h) = zipWith (fun a b => f (g a) (h b)) as bs :=
by
induction as generalizing bs
· simp
· cases bs <;> simp [*]
#align list.zip_with_map List.zipWith_map
/- warning: list.zip_with_map_left -> List.zipWith_map_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} {δ : Type.{u4}} (f : α -> β -> γ) (g : δ -> α) (l : List.{u4} δ) (l' : List.{u2} β), Eq.{succ u3} (List.{u3} γ) (List.zipWith.{u1, u2, u3} α β γ f (List.map.{u4, u1} δ α g l) l') (List.zipWith.{u4, u2, u3} δ β γ (Function.comp.{succ u4, succ u1, max (succ u2) (succ u3)} δ α (β -> γ) f g) l l')
but is expected to have type
forall {α : Type.{u4}} {β : Type.{u2}} {γ : Type.{u1}} {δ : Type.{u3}} (f : α -> β -> γ) (g : δ -> α) (l : List.{u3} δ) (l' : List.{u2} β), Eq.{succ u1} (List.{u1} γ) (List.zipWith.{u4, u2, u1} α β γ f (List.map.{u3, u4} δ α g l) l') (List.zipWith.{u3, u2, u1} δ β γ (Function.comp.{succ u3, succ u4, max (succ u1) (succ u2)} δ α (β -> γ) f g) l l')
Case conversion may be inaccurate. Consider using '#align list.zip_with_map_left List.zipWith_map_leftₓ'. -/
theorem zipWith_map_left (f : α → β → γ) (g : δ → α) (l : List δ) (l' : List β) :
zipWith f (l.map g) l' = zipWith (f ∘ g) l l' :=
by
convert zip_with_map f g id l l'
exact Eq.symm (List.map_id _)
#align list.zip_with_map_left List.zipWith_map_left
/- warning: list.zip_with_map_right -> List.zipWith_map_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} {δ : Type.{u4}} (f : α -> β -> γ) (l : List.{u1} α) (g : δ -> β) (l' : List.{u4} δ), Eq.{succ u3} (List.{u3} γ) (List.zipWith.{u1, u2, u3} α β γ f l (List.map.{u4, u2} δ β g l')) (List.zipWith.{u1, u4, u3} α δ γ (fun (x : α) => Function.comp.{succ u4, succ u2, succ u3} δ β γ (f x) g) l l')
but is expected to have type
forall {α : Type.{u4}} {β : Type.{u1}} {γ : Type.{u2}} {δ : Type.{u3}} (f : α -> β -> γ) (l : List.{u4} α) (g : δ -> β) (l' : List.{u3} δ), Eq.{succ u2} (List.{u2} γ) (List.zipWith.{u4, u1, u2} α β γ f l (List.map.{u3, u1} δ β g l')) (List.zipWith.{u4, u3, u2} α δ γ (fun (x : α) => Function.comp.{succ u3, succ u1, succ u2} δ β γ (f x) g) l l')
Case conversion may be inaccurate. Consider using '#align list.zip_with_map_right List.zipWith_map_rightₓ'. -/
theorem zipWith_map_right (f : α → β → γ) (l : List α) (g : δ → β) (l' : List δ) :
zipWith f l (l'.map g) = zipWith (fun x => f x ∘ g) l l' :=
by
convert List.zipWith_map f id g l l'
exact Eq.symm (List.map_id _)
#align list.zip_with_map_right List.zipWith_map_right
/- warning: list.zip_map' -> List.zip_map' is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} (f : α -> β) (g : α -> γ) (l : List.{u1} α), Eq.{succ (max u2 u3)} (List.{max u2 u3} (Prod.{u2, u3} β γ)) (List.zip.{u2, u3} β γ (List.map.{u1, u2} α β f l) (List.map.{u1, u3} α γ g l)) (List.map.{u1, max u2 u3} α (Prod.{u2, u3} β γ) (fun (a : α) => Prod.mk.{u2, u3} β γ (f a) (g a)) l)
but is expected to have type
forall {α : Type.{u3}} {β : Type.{u2}} {γ : Type.{u1}} (f : α -> β) (g : α -> γ) (l : List.{u3} α), Eq.{max (succ u2) (succ u1)} (List.{max u1 u2} (Prod.{u2, u1} β γ)) (List.zip.{u2, u1} β γ (List.map.{u3, u2} α β f l) (List.map.{u3, u1} α γ g l)) (List.map.{u3, max u1 u2} α (Prod.{u2, u1} β γ) (fun (a : α) => Prod.mk.{u2, u1} β γ (f a) (g a)) l)
Case conversion may be inaccurate. Consider using '#align list.zip_map' List.zip_map'ₓ'. -/
theorem zip_map' (f : α → β) (g : α → γ) :
∀ l : List α, zip (l.map f) (l.map g) = l.map fun a => (f a, g a)
| [] => rfl
| a :: l => by simp only [map, zip_cons_cons, zip_map' l] <;> constructor <;> rfl
#align list.zip_map' List.zip_map'
/- warning: list.map_zip_with -> List.map_zipWith is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} {δ : Type.{u4}} (f : α -> β) (g : γ -> δ -> α) (l : List.{u3} γ) (l' : List.{u4} δ), Eq.{succ u2} (List.{u2} β) (List.map.{u1, u2} α β f (List.zipWith.{u3, u4, u1} γ δ α g l l')) (List.zipWith.{u3, u4, u2} γ δ β (fun (x : γ) (y : δ) => f (g x y)) l l')
but is expected to have type
forall {α : Type.{u4}} {β : Type.{u1}} {γ : Type.{u2}} {δ : Type.{u3}} (f : α -> β) (g : γ -> δ -> α) (l : List.{u2} γ) (l' : List.{u3} δ), Eq.{succ u1} (List.{u1} β) (List.map.{u4, u1} α β f (List.zipWith.{u2, u3, u4} γ δ α g l l')) (List.zipWith.{u2, u3, u1} γ δ β (fun (x : γ) (y : δ) => f (g x y)) l l')
Case conversion may be inaccurate. Consider using '#align list.map_zip_with List.map_zipWithₓ'. -/
theorem map_zipWith {δ : Type _} (f : α → β) (g : γ → δ → α) (l : List γ) (l' : List δ) :
map f (zipWith g l l') = zipWith (fun x y => f (g x y)) l l' :=
by
induction' l with hd tl hl generalizing l'
· simp
· cases l'
· simp
· simp [hl]
#align list.map_zip_with List.map_zipWith
/- warning: list.mem_zip -> List.mem_zip is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {a : α} {b : β} {l₁ : List.{u1} α} {l₂ : List.{u2} β}, (Membership.Mem.{max u1 u2, max u1 u2} (Prod.{u1, u2} α β) (List.{max u1 u2} (Prod.{u1, u2} α β)) (List.hasMem.{max u1 u2} (Prod.{u1, u2} α β)) (Prod.mk.{u1, u2} α β a b) (List.zip.{u1, u2} α β l₁ l₂)) -> (And (Membership.Mem.{u1, u1} α (List.{u1} α) (List.hasMem.{u1} α) a l₁) (Membership.Mem.{u2, u2} β (List.{u2} β) (List.hasMem.{u2} β) b l₂))
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} {a : α} {b : β} {l₁ : List.{u2} α} {l₂ : List.{u1} β}, (Membership.mem.{max u1 u2, max u1 u2} (Prod.{u2, u1} α β) (List.{max u1 u2} (Prod.{u2, u1} α β)) (List.instMembershipList.{max u1 u2} (Prod.{u2, u1} α β)) (Prod.mk.{u2, u1} α β a b) (List.zip.{u2, u1} α β l₁ l₂)) -> (And (Membership.mem.{u2, u2} α (List.{u2} α) (List.instMembershipList.{u2} α) a l₁) (Membership.mem.{u1, u1} β (List.{u1} β) (List.instMembershipList.{u1} β) b l₂))
Case conversion may be inaccurate. Consider using '#align list.mem_zip List.mem_zipₓ'. -/
theorem mem_zip {a b} : ∀ {l₁ : List α} {l₂ : List β}, (a, b) ∈ zip l₁ l₂ → a ∈ l₁ ∧ b ∈ l₂
| _ :: l₁, _ :: l₂, Or.inl rfl => ⟨Or.inl rfl, Or.inl rfl⟩
| a' :: l₁, b' :: l₂, Or.inr h => by
constructor <;> simp only [mem_cons_iff, or_true_iff, mem_zip h]
#align list.mem_zip List.mem_zip
/- warning: list.map_fst_zip -> List.map_fst_zip is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} (l₁ : List.{u1} α) (l₂ : List.{u2} β), (LE.le.{0} Nat Nat.hasLe (List.length.{u1} α l₁) (List.length.{u2} β l₂)) -> (Eq.{succ u1} (List.{u1} α) (List.map.{max u1 u2, u1} (Prod.{u1, u2} α β) α (Prod.fst.{u1, u2} α β) (List.zip.{u1, u2} α β l₁ l₂)) l₁)
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} (l₁ : List.{u2} α) (l₂ : List.{u1} β), (LE.le.{0} Nat instLENat (List.length.{u2} α l₁) (List.length.{u1} β l₂)) -> (Eq.{succ u2} (List.{u2} α) (List.map.{max u1 u2, u2} (Prod.{u2, u1} α β) α (Prod.fst.{u2, u1} α β) (List.zip.{u2, u1} α β l₁ l₂)) l₁)
Case conversion may be inaccurate. Consider using '#align list.map_fst_zip List.map_fst_zipₓ'. -/
theorem map_fst_zip :
∀ (l₁ : List α) (l₂ : List β), l₁.length ≤ l₂.length → map Prod.fst (zip l₁ l₂) = l₁
| [], bs, _ => rfl
| a :: as, b :: bs, h => by
simp at h
simp! [*]
| a :: as, [], h => by
simp at h
contradiction
#align list.map_fst_zip List.map_fst_zip
/- warning: list.map_snd_zip -> List.map_snd_zip is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} (l₁ : List.{u1} α) (l₂ : List.{u2} β), (LE.le.{0} Nat Nat.hasLe (List.length.{u2} β l₂) (List.length.{u1} α l₁)) -> (Eq.{succ u2} (List.{u2} β) (List.map.{max u1 u2, u2} (Prod.{u1, u2} α β) β (Prod.snd.{u1, u2} α β) (List.zip.{u1, u2} α β l₁ l₂)) l₂)
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} (l₁ : List.{u2} α) (l₂ : List.{u1} β), (LE.le.{0} Nat instLENat (List.length.{u1} β l₂) (List.length.{u2} α l₁)) -> (Eq.{succ u1} (List.{u1} β) (List.map.{max u1 u2, u1} (Prod.{u2, u1} α β) β (Prod.snd.{u2, u1} α β) (List.zip.{u2, u1} α β l₁ l₂)) l₂)
Case conversion may be inaccurate. Consider using '#align list.map_snd_zip List.map_snd_zipₓ'. -/
theorem map_snd_zip :
∀ (l₁ : List α) (l₂ : List β), l₂.length ≤ l₁.length → map Prod.snd (zip l₁ l₂) = l₂
| _, [], _ => by
rw [zip_nil_right]
rfl
| [], b :: bs, h => by
simp at h
contradiction
| a :: as, b :: bs, h => by
simp at h
simp! [*]
#align list.map_snd_zip List.map_snd_zip
/- warning: list.unzip_nil -> List.unzip_nil is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}}, Eq.{max (succ u1) (succ u2)} (Prod.{u1, u2} (List.{u1} α) (List.{u2} β)) (List.unzip.{u1, u2} α β (List.nil.{max u1 u2} (Prod.{u1, u2} α β))) (Prod.mk.{u1, u2} (List.{u1} α) (List.{u2} β) (List.nil.{u1} α) (List.nil.{u2} β))
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}}, Eq.{max (succ u2) (succ u1)} (Prod.{u2, u1} (List.{u2} α) (List.{u1} β)) (List.unzip.{u2, u1} α β (List.nil.{max u1 u2} (Prod.{u2, u1} α β))) (Prod.mk.{u2, u1} (List.{u2} α) (List.{u1} β) (List.nil.{u2} α) (List.nil.{u1} β))
Case conversion may be inaccurate. Consider using '#align list.unzip_nil List.unzip_nilₓ'. -/
@[simp]
theorem unzip_nil : unzip (@nil (α × β)) = ([], []) :=
rfl
#align list.unzip_nil List.unzip_nil
/- warning: list.unzip_cons -> List.unzip_cons is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} (a : α) (b : β) (l : List.{max u1 u2} (Prod.{u1, u2} α β)), Eq.{max (succ u1) (succ u2)} (Prod.{u1, u2} (List.{u1} α) (List.{u2} β)) (List.unzip.{u1, u2} α β (List.cons.{max u1 u2} (Prod.{u1, u2} α β) (Prod.mk.{u1, u2} α β a b) l)) (Prod.mk.{u1, u2} (List.{u1} α) (List.{u2} β) (List.cons.{u1} α a (Prod.fst.{u1, u2} (List.{u1} α) (List.{u2} β) (List.unzip.{u1, u2} α β l))) (List.cons.{u2} β b (Prod.snd.{u1, u2} (List.{u1} α) (List.{u2} β) (List.unzip.{u1, u2} α β l))))
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} (a : α) (b : β) (l : List.{max u1 u2} (Prod.{u2, u1} α β)), Eq.{max (succ u2) (succ u1)} (Prod.{u2, u1} (List.{u2} α) (List.{u1} β)) (List.unzip.{u2, u1} α β (List.cons.{max u1 u2} (Prod.{u2, u1} α β) (Prod.mk.{u2, u1} α β a b) l)) (Prod.mk.{u2, u1} (List.{u2} α) (List.{u1} β) (List.cons.{u2} α a (Prod.fst.{u2, u1} (List.{u2} α) (List.{u1} β) (List.unzip.{u2, u1} α β l))) (List.cons.{u1} β b (Prod.snd.{u2, u1} (List.{u2} α) (List.{u1} β) (List.unzip.{u2, u1} α β l))))
Case conversion may be inaccurate. Consider using '#align list.unzip_cons List.unzip_consₓ'. -/
@[simp]
theorem unzip_cons (a : α) (b : β) (l : List (α × β)) :
unzip ((a, b) :: l) = (a :: (unzip l).1, b :: (unzip l).2) := by
rw [unzip] <;> cases unzip l <;> rfl
#align list.unzip_cons List.unzip_cons
/- warning: list.unzip_eq_map -> List.unzip_eq_map is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} (l : List.{max u1 u2} (Prod.{u1, u2} α β)), Eq.{max (succ u1) (succ u2)} (Prod.{u1, u2} (List.{u1} α) (List.{u2} β)) (List.unzip.{u1, u2} α β l) (Prod.mk.{u1, u2} (List.{u1} α) (List.{u2} β) (List.map.{max u1 u2, u1} (Prod.{u1, u2} α β) α (Prod.fst.{u1, u2} α β) l) (List.map.{max u1 u2, u2} (Prod.{u1, u2} α β) β (Prod.snd.{u1, u2} α β) l))
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} (l : List.{max u1 u2} (Prod.{u2, u1} α β)), Eq.{max (succ u2) (succ u1)} (Prod.{u2, u1} (List.{u2} α) (List.{u1} β)) (List.unzip.{u2, u1} α β l) (Prod.mk.{u2, u1} (List.{u2} α) (List.{u1} β) (List.map.{max u1 u2, u2} (Prod.{u2, u1} α β) α (Prod.fst.{u2, u1} α β) l) (List.map.{max u1 u2, u1} (Prod.{u2, u1} α β) β (Prod.snd.{u2, u1} α β) l))
Case conversion may be inaccurate. Consider using '#align list.unzip_eq_map List.unzip_eq_mapₓ'. -/
theorem unzip_eq_map : ∀ l : List (α × β), unzip l = (l.map Prod.fst, l.map Prod.snd)
| [] => rfl
| (a, b) :: l => by simp only [unzip_cons, map_cons, unzip_eq_map l]
#align list.unzip_eq_map List.unzip_eq_map
/- warning: list.unzip_left -> List.unzip_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} (l : List.{max u1 u2} (Prod.{u1, u2} α β)), Eq.{succ u1} (List.{u1} α) (Prod.fst.{u1, u2} (List.{u1} α) (List.{u2} β) (List.unzip.{u1, u2} α β l)) (List.map.{max u1 u2, u1} (Prod.{u1, u2} α β) α (Prod.fst.{u1, u2} α β) l)
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} (l : List.{max u1 u2} (Prod.{u2, u1} α β)), Eq.{succ u2} (List.{u2} α) (Prod.fst.{u2, u1} (List.{u2} α) (List.{u1} β) (List.unzip.{u2, u1} α β l)) (List.map.{max u1 u2, u2} (Prod.{u2, u1} α β) α (Prod.fst.{u2, u1} α β) l)
Case conversion may be inaccurate. Consider using '#align list.unzip_left List.unzip_leftₓ'. -/
theorem unzip_left (l : List (α × β)) : (unzip l).1 = l.map Prod.fst := by simp only [unzip_eq_map]
#align list.unzip_left List.unzip_left
/- warning: list.unzip_right -> List.unzip_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} (l : List.{max u1 u2} (Prod.{u1, u2} α β)), Eq.{succ u2} (List.{u2} β) (Prod.snd.{u1, u2} (List.{u1} α) (List.{u2} β) (List.unzip.{u1, u2} α β l)) (List.map.{max u1 u2, u2} (Prod.{u1, u2} α β) β (Prod.snd.{u1, u2} α β) l)
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} (l : List.{max u1 u2} (Prod.{u2, u1} α β)), Eq.{succ u1} (List.{u1} β) (Prod.snd.{u2, u1} (List.{u2} α) (List.{u1} β) (List.unzip.{u2, u1} α β l)) (List.map.{max u1 u2, u1} (Prod.{u2, u1} α β) β (Prod.snd.{u2, u1} α β) l)
Case conversion may be inaccurate. Consider using '#align list.unzip_right List.unzip_rightₓ'. -/
theorem unzip_right (l : List (α × β)) : (unzip l).2 = l.map Prod.snd := by simp only [unzip_eq_map]
#align list.unzip_right List.unzip_right
/- warning: list.unzip_swap -> List.unzip_swap is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} (l : List.{max u1 u2} (Prod.{u1, u2} α β)), Eq.{max (succ u2) (succ u1)} (Prod.{u2, u1} (List.{u2} β) (List.{u1} α)) (List.unzip.{u2, u1} β α (List.map.{max u1 u2, max u2 u1} (Prod.{u1, u2} α β) (Prod.{u2, u1} β α) (Prod.swap.{u1, u2} α β) l)) (Prod.swap.{u1, u2} (List.{u1} α) (List.{u2} β) (List.unzip.{u1, u2} α β l))
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} (l : List.{max u1 u2} (Prod.{u2, u1} α β)), Eq.{max (succ u2) (succ u1)} (Prod.{u1, u2} (List.{u1} β) (List.{u2} α)) (List.unzip.{u1, u2} β α (List.map.{max u1 u2, max u2 u1} (Prod.{u2, u1} α β) (Prod.{u1, u2} β α) (Prod.swap.{u2, u1} α β) l)) (Prod.swap.{u2, u1} (List.{u2} α) (List.{u1} β) (List.unzip.{u2, u1} α β l))
Case conversion may be inaccurate. Consider using '#align list.unzip_swap List.unzip_swapₓ'. -/
theorem unzip_swap (l : List (α × β)) : unzip (l.map Prod.swap) = (unzip l).symm := by
simp only [unzip_eq_map, map_map] <;> constructor <;> rfl
#align list.unzip_swap List.unzip_swap
/- warning: list.zip_unzip -> List.zip_unzip is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} (l : List.{max u1 u2} (Prod.{u1, u2} α β)), Eq.{succ (max u1 u2)} (List.{max u1 u2} (Prod.{u1, u2} α β)) (List.zip.{u1, u2} α β (Prod.fst.{u1, u2} (List.{u1} α) (List.{u2} β) (List.unzip.{u1, u2} α β l)) (Prod.snd.{u1, u2} (List.{u1} α) (List.{u2} β) (List.unzip.{u1, u2} α β l))) l
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} (l : List.{max u1 u2} (Prod.{u2, u1} α β)), Eq.{max (succ u2) (succ u1)} (List.{max u1 u2} (Prod.{u2, u1} α β)) (List.zip.{u2, u1} α β (Prod.fst.{u2, u1} (List.{u2} α) (List.{u1} β) (List.unzip.{u2, u1} α β l)) (Prod.snd.{u2, u1} (List.{u2} α) (List.{u1} β) (List.unzip.{u2, u1} α β l))) l
Case conversion may be inaccurate. Consider using '#align list.zip_unzip List.zip_unzipₓ'. -/
theorem zip_unzip : ∀ l : List (α × β), zip (unzip l).1 (unzip l).2 = l
| [] => rfl
| (a, b) :: l => by simp only [unzip_cons, zip_cons_cons, zip_unzip l] <;> constructor <;> rfl
#align list.zip_unzip List.zip_unzip
/- warning: list.unzip_zip_left -> List.unzip_zip_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {l₁ : List.{u1} α} {l₂ : List.{u2} β}, (LE.le.{0} Nat Nat.hasLe (List.length.{u1} α l₁) (List.length.{u2} β l₂)) -> (Eq.{succ u1} (List.{u1} α) (Prod.fst.{u1, u2} (List.{u1} α) (List.{u2} β) (List.unzip.{u1, u2} α β (List.zip.{u1, u2} α β l₁ l₂))) l₁)
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} {l₁ : List.{u2} α} {l₂ : List.{u1} β}, (LE.le.{0} Nat instLENat (List.length.{u2} α l₁) (List.length.{u1} β l₂)) -> (Eq.{succ u2} (List.{u2} α) (Prod.fst.{u2, u1} (List.{u2} α) (List.{u1} β) (List.unzip.{u2, u1} α β (List.zip.{u2, u1} α β l₁ l₂))) l₁)
Case conversion may be inaccurate. Consider using '#align list.unzip_zip_left List.unzip_zip_leftₓ'. -/
theorem unzip_zip_left :
∀ {l₁ : List α} {l₂ : List β}, length l₁ ≤ length l₂ → (unzip (zip l₁ l₂)).1 = l₁
| [], l₂, h => rfl
| l₁, [], h => by rw [eq_nil_of_length_eq_zero (Nat.eq_zero_of_le_zero h)] <;> rfl
| a :: l₁, b :: l₂, h => by
simp only [zip_cons_cons, unzip_cons, unzip_zip_left (le_of_succ_le_succ h)] <;> constructor <;>
rfl
#align list.unzip_zip_left List.unzip_zip_left
/- warning: list.unzip_zip_right -> List.unzip_zip_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {l₁ : List.{u1} α} {l₂ : List.{u2} β}, (LE.le.{0} Nat Nat.hasLe (List.length.{u2} β l₂) (List.length.{u1} α l₁)) -> (Eq.{succ u2} (List.{u2} β) (Prod.snd.{u1, u2} (List.{u1} α) (List.{u2} β) (List.unzip.{u1, u2} α β (List.zip.{u1, u2} α β l₁ l₂))) l₂)
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} {l₁ : List.{u2} α} {l₂ : List.{u1} β}, (LE.le.{0} Nat instLENat (List.length.{u1} β l₂) (List.length.{u2} α l₁)) -> (Eq.{succ u1} (List.{u1} β) (Prod.snd.{u2, u1} (List.{u2} α) (List.{u1} β) (List.unzip.{u2, u1} α β (List.zip.{u2, u1} α β l₁ l₂))) l₂)
Case conversion may be inaccurate. Consider using '#align list.unzip_zip_right List.unzip_zip_rightₓ'. -/
theorem unzip_zip_right {l₁ : List α} {l₂ : List β} (h : length l₂ ≤ length l₁) :
(unzip (zip l₁ l₂)).2 = l₂ := by rw [← zip_swap, unzip_swap] <;> exact unzip_zip_left h
#align list.unzip_zip_right List.unzip_zip_right
/- warning: list.unzip_zip -> List.unzip_zip is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {l₁ : List.{u1} α} {l₂ : List.{u2} β}, (Eq.{1} Nat (List.length.{u1} α l₁) (List.length.{u2} β l₂)) -> (Eq.{max (succ u1) (succ u2)} (Prod.{u1, u2} (List.{u1} α) (List.{u2} β)) (List.unzip.{u1, u2} α β (List.zip.{u1, u2} α β l₁ l₂)) (Prod.mk.{u1, u2} (List.{u1} α) (List.{u2} β) l₁ l₂))
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} {l₁ : List.{u2} α} {l₂ : List.{u1} β}, (Eq.{1} Nat (List.length.{u2} α l₁) (List.length.{u1} β l₂)) -> (Eq.{max (succ u2) (succ u1)} (Prod.{u2, u1} (List.{u2} α) (List.{u1} β)) (List.unzip.{u2, u1} α β (List.zip.{u2, u1} α β l₁ l₂)) (Prod.mk.{u2, u1} (List.{u2} α) (List.{u1} β) l₁ l₂))
Case conversion may be inaccurate. Consider using '#align list.unzip_zip List.unzip_zipₓ'. -/
theorem unzip_zip {l₁ : List α} {l₂ : List β} (h : length l₁ = length l₂) :
unzip (zip l₁ l₂) = (l₁, l₂) := by
rw [← @Prod.mk.eta _ _ (unzip (zip l₁ l₂)), unzip_zip_left (le_of_eq h),
unzip_zip_right (ge_of_eq h)]
#align list.unzip_zip List.unzip_zip
/- warning: list.zip_of_prod -> List.zip_of_prod is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {l : List.{u1} α} {l' : List.{u2} β} {lp : List.{max u1 u2} (Prod.{u1, u2} α β)}, (Eq.{succ u1} (List.{u1} α) (List.map.{max u1 u2, u1} (Prod.{u1, u2} α β) α (Prod.fst.{u1, u2} α β) lp) l) -> (Eq.{succ u2} (List.{u2} β) (List.map.{max u1 u2, u2} (Prod.{u1, u2} α β) β (Prod.snd.{u1, u2} α β) lp) l') -> (Eq.{succ (max u1 u2)} (List.{max u1 u2} (Prod.{u1, u2} α β)) lp (List.zip.{u1, u2} α β l l'))
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} {l : List.{u2} α} {l' : List.{u1} β} {lp : List.{max u1 u2} (Prod.{u2, u1} α β)}, (Eq.{succ u2} (List.{u2} α) (List.map.{max u1 u2, u2} (Prod.{u2, u1} α β) α (Prod.fst.{u2, u1} α β) lp) l) -> (Eq.{succ u1} (List.{u1} β) (List.map.{max u1 u2, u1} (Prod.{u2, u1} α β) β (Prod.snd.{u2, u1} α β) lp) l') -> (Eq.{max (succ u2) (succ u1)} (List.{max u1 u2} (Prod.{u2, u1} α β)) lp (List.zip.{u2, u1} α β l l'))
Case conversion may be inaccurate. Consider using '#align list.zip_of_prod List.zip_of_prodₓ'. -/
theorem zip_of_prod {l : List α} {l' : List β} {lp : List (α × β)} (hl : lp.map Prod.fst = l)
(hr : lp.map Prod.snd = l') : lp = l.zip l' := by
rw [← hl, ← hr, ← zip_unzip lp, ← unzip_left, ← unzip_right, zip_unzip, zip_unzip]
#align list.zip_of_prod List.zip_of_prod
/- warning: list.map_prod_left_eq_zip -> List.map_prod_left_eq_zip is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {l : List.{u1} α} (f : α -> β), Eq.{succ (max u1 u2)} (List.{max u1 u2} (Prod.{u1, u2} α β)) (List.map.{u1, max u1 u2} α (Prod.{u1, u2} α β) (fun (x : α) => Prod.mk.{u1, u2} α β x (f x)) l) (List.zip.{u1, u2} α β l (List.map.{u1, u2} α β f l))
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} {l : List.{u2} α} (f : α -> β), Eq.{max (succ u2) (succ u1)} (List.{max u1 u2} (Prod.{u2, u1} α β)) (List.map.{u2, max u1 u2} α (Prod.{u2, u1} α β) (fun (x : α) => Prod.mk.{u2, u1} α β x (f x)) l) (List.zip.{u2, u1} α β l (List.map.{u2, u1} α β f l))
Case conversion may be inaccurate. Consider using '#align list.map_prod_left_eq_zip List.map_prod_left_eq_zipₓ'. -/
theorem map_prod_left_eq_zip {l : List α} (f : α → β) :
(l.map fun x => (x, f x)) = l.zip (l.map f) :=
by
rw [← zip_map']
congr
exact map_id _
#align list.map_prod_left_eq_zip List.map_prod_left_eq_zip
/- warning: list.map_prod_right_eq_zip -> List.map_prod_right_eq_zip is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {l : List.{u1} α} (f : α -> β), Eq.{succ (max u2 u1)} (List.{max u2 u1} (Prod.{u2, u1} β α)) (List.map.{u1, max u2 u1} α (Prod.{u2, u1} β α) (fun (x : α) => Prod.mk.{u2, u1} β α (f x) x) l) (List.zip.{u2, u1} β α (List.map.{u1, u2} α β f l) l)
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} {l : List.{u2} α} (f : α -> β), Eq.{max (succ u2) (succ u1)} (List.{max u2 u1} (Prod.{u1, u2} β α)) (List.map.{u2, max u2 u1} α (Prod.{u1, u2} β α) (fun (x : α) => Prod.mk.{u1, u2} β α (f x) x) l) (List.zip.{u1, u2} β α (List.map.{u2, u1} α β f l) l)
Case conversion may be inaccurate. Consider using '#align list.map_prod_right_eq_zip List.map_prod_right_eq_zipₓ'. -/
theorem map_prod_right_eq_zip {l : List α} (f : α → β) :
(l.map fun x => (f x, x)) = (l.map f).zip l :=
by
rw [← zip_map']
congr
exact map_id _
#align list.map_prod_right_eq_zip List.map_prod_right_eq_zip
/- warning: list.zip_with_comm -> List.zipWith_comm is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} (f : α -> β -> γ) (la : List.{u1} α) (lb : List.{u2} β), Eq.{succ u3} (List.{u3} γ) (List.zipWith.{u1, u2, u3} α β γ f la lb) (List.zipWith.{u2, u1, u3} β α γ (fun (b : β) (a : α) => f a b) lb la)
but is expected to have type
forall {α : Type.{u3}} {β : Type.{u2}} {γ : Type.{u1}} (f : α -> β -> γ) (la : List.{u3} α) (lb : List.{u2} β), Eq.{succ u1} (List.{u1} γ) (List.zipWith.{u3, u2, u1} α β γ f la lb) (List.zipWith.{u2, u3, u1} β α γ (fun (b : β) (a : α) => f a b) lb la)
Case conversion may be inaccurate. Consider using '#align list.zip_with_comm List.zipWith_commₓ'. -/
theorem zipWith_comm (f : α → β → γ) :
∀ (la : List α) (lb : List β), zipWith f la lb = zipWith (fun b a => f a b) lb la
| [], _ => (List.zipWith_nil_right _ _).symm
| a :: as, [] => rfl
| a :: as, b :: bs => congr_arg _ (zip_with_comm as bs)
#align list.zip_with_comm List.zipWith_comm
/- warning: list.zip_with_congr -> List.zipWith_congr is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} (f : α -> β -> γ) (g : α -> β -> γ) (la : List.{u1} α) (lb : List.{u2} β), (List.Forall₂.{u1, u2} α β (fun (a : α) (b : β) => Eq.{succ u3} γ (f a b) (g a b)) la lb) -> (Eq.{succ u3} (List.{u3} γ) (List.zipWith.{u1, u2, u3} α β γ f la lb) (List.zipWith.{u1, u2, u3} α β γ g la lb))
but is expected to have type
forall {α : Type.{u3}} {β : Type.{u2}} {γ : Type.{u1}} (f : α -> β -> γ) (g : α -> β -> γ) (la : List.{u3} α) (lb : List.{u2} β), (List.Forall₂.{u3, u2} α β (fun (a : α) (b : β) => Eq.{succ u1} γ (f a b) (g a b)) la lb) -> (Eq.{succ u1} (List.{u1} γ) (List.zipWith.{u3, u2, u1} α β γ f la lb) (List.zipWith.{u3, u2, u1} α β γ g la lb))
Case conversion may be inaccurate. Consider using '#align list.zip_with_congr List.zipWith_congrₓ'. -/
@[congr]
theorem zipWith_congr (f g : α → β → γ) (la : List α) (lb : List β)
(h : List.Forall₂ (fun a b => f a b = g a b) la lb) : zipWith f la lb = zipWith g la lb :=
by
induction' h with a b as bs hfg habs ih
· rfl
· exact congr_arg₂ _ hfg ih
#align list.zip_with_congr List.zipWith_congr
/- warning: list.zip_with_comm_of_comm -> List.zipWith_comm_of_comm is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} (f : α -> α -> β), (forall (x : α) (y : α), Eq.{succ u2} β (f x y) (f y x)) -> (forall (l : List.{u1} α) (l' : List.{u1} α), Eq.{succ u2} (List.{u2} β) (List.zipWith.{u1, u1, u2} α α β f l l') (List.zipWith.{u1, u1, u2} α α β f l' l))
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} (f : α -> α -> β), (forall (x : α) (y : α), Eq.{succ u1} β (f x y) (f y x)) -> (forall (l : List.{u2} α) (l' : List.{u2} α), Eq.{succ u1} (List.{u1} β) (List.zipWith.{u2, u2, u1} α α β f l l') (List.zipWith.{u2, u2, u1} α α β f l' l))
Case conversion may be inaccurate. Consider using '#align list.zip_with_comm_of_comm List.zipWith_comm_of_commₓ'. -/
theorem zipWith_comm_of_comm (f : α → α → β) (comm : ∀ x y : α, f x y = f y x) (l l' : List α) :
zipWith f l l' = zipWith f l' l := by
rw [zip_with_comm]
simp only [comm]
#align list.zip_with_comm_of_comm List.zipWith_comm_of_comm
/- warning: list.zip_with_same -> List.zipWith_same is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {δ : Type.{u2}} (f : α -> α -> δ) (l : List.{u1} α), Eq.{succ u2} (List.{u2} δ) (List.zipWith.{u1, u1, u2} α α δ f l l) (List.map.{u1, u2} α δ (fun (a : α) => f a a) l)
but is expected to have type
forall {α : Type.{u2}} {δ : Type.{u1}} (f : α -> α -> δ) (l : List.{u2} α), Eq.{succ u1} (List.{u1} δ) (List.zipWith.{u2, u2, u1} α α δ f l l) (List.map.{u2, u1} α δ (fun (a : α) => f a a) l)
Case conversion may be inaccurate. Consider using '#align list.zip_with_same List.zipWith_sameₓ'. -/
@[simp]
theorem zipWith_same (f : α → α → δ) : ∀ l : List α, zipWith f l l = l.map fun a => f a a
| [] => rfl
| x :: xs => congr_arg _ (zip_with_same xs)
#align list.zip_with_same List.zipWith_same
/- warning: list.zip_with_zip_with_left -> List.zipWith_zipWith_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} {δ : Type.{u4}} {ε : Type.{u5}} (f : δ -> γ -> ε) (g : α -> β -> δ) (la : List.{u1} α) (lb : List.{u2} β) (lc : List.{u3} γ), Eq.{succ u5} (List.{u5} ε) (List.zipWith.{u4, u3, u5} δ γ ε f (List.zipWith.{u1, u2, u4} α β δ g la lb) lc) (List.zipWith3.{u1, u2, u3, u5} α β γ ε (fun (a : α) (b : β) (c : γ) => f (g a b) c) la lb lc)
but is expected to have type
forall {α : Type.{u5}} {β : Type.{u4}} {γ : Type.{u3}} {δ : Type.{u1}} {ε : Type.{u2}} (f : δ -> γ -> ε) (g : α -> β -> δ) (la : List.{u5} α) (lb : List.{u4} β) (lc : List.{u3} γ), Eq.{succ u2} (List.{u2} ε) (List.zipWith.{u1, u3, u2} δ γ ε f (List.zipWith.{u5, u4, u1} α β δ g la lb) lc) (List.zipWith3.{u5, u4, u3, u2} α β γ ε (fun (a : α) (b : β) (c : γ) => f (g a b) c) la lb lc)
Case conversion may be inaccurate. Consider using '#align list.zip_with_zip_with_left List.zipWith_zipWith_leftₓ'. -/
theorem zipWith_zipWith_left (f : δ → γ → ε) (g : α → β → δ) :
∀ (la : List α) (lb : List β) (lc : List γ),
zipWith f (zipWith g la lb) lc = zipWith3 (fun a b c => f (g a b) c) la lb lc
| [], _, _ => rfl
| a :: as, [], _ => rfl
| a :: as, b :: bs, [] => rfl
| a :: as, b :: bs, c :: cs => congr_arg (cons _) <| zip_with_zip_with_left as bs cs
#align list.zip_with_zip_with_left List.zipWith_zipWith_left
/- warning: list.zip_with_zip_with_right -> List.zipWith_zipWith_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} {δ : Type.{u4}} {ε : Type.{u5}} (f : α -> δ -> ε) (g : β -> γ -> δ) (la : List.{u1} α) (lb : List.{u2} β) (lc : List.{u3} γ), Eq.{succ u5} (List.{u5} ε) (List.zipWith.{u1, u4, u5} α δ ε f la (List.zipWith.{u2, u3, u4} β γ δ g lb lc)) (List.zipWith3.{u1, u2, u3, u5} α β γ ε (fun (a : α) (b : β) (c : γ) => f a (g b c)) la lb lc)
but is expected to have type
forall {α : Type.{u5}} {β : Type.{u4}} {γ : Type.{u3}} {δ : Type.{u1}} {ε : Type.{u2}} (f : α -> δ -> ε) (g : β -> γ -> δ) (la : List.{u5} α) (lb : List.{u4} β) (lc : List.{u3} γ), Eq.{succ u2} (List.{u2} ε) (List.zipWith.{u5, u1, u2} α δ ε f la (List.zipWith.{u4, u3, u1} β γ δ g lb lc)) (List.zipWith3.{u5, u4, u3, u2} α β γ ε (fun (a : α) (b : β) (c : γ) => f a (g b c)) la lb lc)
Case conversion may be inaccurate. Consider using '#align list.zip_with_zip_with_right List.zipWith_zipWith_rightₓ'. -/
theorem zipWith_zipWith_right (f : α → δ → ε) (g : β → γ → δ) :
∀ (la : List α) (lb : List β) (lc : List γ),
zipWith f la (zipWith g lb lc) = zipWith3 (fun a b c => f a (g b c)) la lb lc
| [], _, _ => rfl
| a :: as, [], _ => rfl
| a :: as, b :: bs, [] => rfl
| a :: as, b :: bs, c :: cs => congr_arg (cons _) <| zip_with_zip_with_right as bs cs
#align list.zip_with_zip_with_right List.zipWith_zipWith_right
/- warning: list.zip_with3_same_left -> List.zipWith3_same_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} (f : α -> α -> β -> γ) (la : List.{u1} α) (lb : List.{u2} β), Eq.{succ u3} (List.{u3} γ) (List.zipWith3.{u1, u1, u2, u3} α α β γ f la la lb) (List.zipWith.{u1, u2, u3} α β γ (fun (a : α) (b : β) => f a a b) la lb)
but is expected to have type
forall {α : Type.{u3}} {β : Type.{u2}} {γ : Type.{u1}} (f : α -> α -> β -> γ) (la : List.{u3} α) (lb : List.{u2} β), Eq.{succ u1} (List.{u1} γ) (List.zipWith3.{u3, u3, u2, u1} α α β γ f la la lb) (List.zipWith.{u3, u2, u1} α β γ (fun (a : α) (b : β) => f a a b) la lb)
Case conversion may be inaccurate. Consider using '#align list.zip_with3_same_left List.zipWith3_same_leftₓ'. -/
@[simp]
theorem zipWith3_same_left (f : α → α → β → γ) :
∀ (la : List α) (lb : List β), zipWith3 f la la lb = zipWith (fun a b => f a a b) la lb
| [], _ => rfl
| a :: as, [] => rfl
| a :: as, b :: bs => congr_arg (cons _) <| zip_with3_same_left as bs
#align list.zip_with3_same_left List.zipWith3_same_left
/- warning: list.zip_with3_same_mid -> List.zipWith3_same_mid is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} (f : α -> β -> α -> γ) (la : List.{u1} α) (lb : List.{u2} β), Eq.{succ u3} (List.{u3} γ) (List.zipWith3.{u1, u2, u1, u3} α β α γ f la lb la) (List.zipWith.{u1, u2, u3} α β γ (fun (a : α) (b : β) => f a b a) la lb)
but is expected to have type
forall {α : Type.{u3}} {β : Type.{u2}} {γ : Type.{u1}} (f : α -> β -> α -> γ) (la : List.{u3} α) (lb : List.{u2} β), Eq.{succ u1} (List.{u1} γ) (List.zipWith3.{u3, u2, u3, u1} α β α γ f la lb la) (List.zipWith.{u3, u2, u1} α β γ (fun (a : α) (b : β) => f a b a) la lb)
Case conversion may be inaccurate. Consider using '#align list.zip_with3_same_mid List.zipWith3_same_midₓ'. -/
@[simp]
theorem zipWith3_same_mid (f : α → β → α → γ) :
∀ (la : List α) (lb : List β), zipWith3 f la lb la = zipWith (fun a b => f a b a) la lb
| [], _ => rfl
| a :: as, [] => rfl
| a :: as, b :: bs => congr_arg (cons _) <| zip_with3_same_mid as bs
#align list.zip_with3_same_mid List.zipWith3_same_mid
/- warning: list.zip_with3_same_right -> List.zipWith3_same_right is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} (f : α -> β -> β -> γ) (la : List.{u1} α) (lb : List.{u2} β), Eq.{succ u3} (List.{u3} γ) (List.zipWith3.{u1, u2, u2, u3} α β β γ f la lb lb) (List.zipWith.{u1, u2, u3} α β γ (fun (a : α) (b : β) => f a b b) la lb)
but is expected to have type
forall {α : Type.{u3}} {β : Type.{u2}} {γ : Type.{u1}} (f : α -> β -> β -> γ) (la : List.{u3} α) (lb : List.{u2} β), Eq.{succ u1} (List.{u1} γ) (List.zipWith3.{u3, u2, u2, u1} α β β γ f la lb lb) (List.zipWith.{u3, u2, u1} α β γ (fun (a : α) (b : β) => f a b b) la lb)
Case conversion may be inaccurate. Consider using '#align list.zip_with3_same_right List.zipWith3_same_rightₓ'. -/
@[simp]
theorem zipWith3_same_right (f : α → β → β → γ) :
∀ (la : List α) (lb : List β), zipWith3 f la lb lb = zipWith (fun a b => f a b b) la lb
| [], _ => rfl
| a :: as, [] => rfl
| a :: as, b :: bs => congr_arg (cons _) <| zip_with3_same_right as bs
#align list.zip_with3_same_right List.zipWith3_same_right
instance (f : α → α → β) [IsSymmOp α β f] : IsSymmOp (List α) (List β) (zipWith f) :=
⟨zipWith_comm_of_comm f IsSymmOp.symm_op⟩
#print List.length_revzip /-
@[simp]
theorem length_revzip (l : List α) : length (revzip l) = length l := by
simp only [revzip, length_zip, length_reverse, min_self]
#align list.length_revzip List.length_revzip
-/
#print List.unzip_revzip /-
@[simp]
theorem unzip_revzip (l : List α) : (revzip l).unzip = (l, l.reverse) :=
unzip_zip (length_reverse l).symm
#align list.unzip_revzip List.unzip_revzip
-/
#print List.revzip_map_fst /-
@[simp]
theorem revzip_map_fst (l : List α) : (revzip l).map Prod.fst = l := by
rw [← unzip_left, unzip_revzip]
#align list.revzip_map_fst List.revzip_map_fst
-/
#print List.revzip_map_snd /-
@[simp]
theorem revzip_map_snd (l : List α) : (revzip l).map Prod.snd = l.reverse := by
rw [← unzip_right, unzip_revzip]
#align list.revzip_map_snd List.revzip_map_snd
-/
#print List.reverse_revzip /-
theorem reverse_revzip (l : List α) : reverse l.revzip = revzip l.reverse := by
rw [← zip_unzip.{u, u} (revzip l).reverse, unzip_eq_map] <;> simp <;> simp [revzip]
#align list.reverse_revzip List.reverse_revzip
-/
#print List.revzip_swap /-
theorem revzip_swap (l : List α) : (revzip l).map Prod.swap = revzip l.reverse := by simp [revzip]
#align list.revzip_swap List.revzip_swap
-/
/- warning: list.nth_zip_with -> List.get?_zip_with is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} (f : α -> β -> γ) (l₁ : List.{u1} α) (l₂ : List.{u2} β) (i : Nat), Eq.{succ u3} (Option.{u3} γ) (List.get?.{u3} γ (List.zipWith.{u1, u2, u3} α β γ f l₁ l₂) i) (Option.bind.{max u2 u3, u3} (β -> γ) γ (Option.map.{u1, max u2 u3} α (β -> γ) f (List.get?.{u1} α l₁ i)) (fun (g : β -> γ) => Option.map.{u2, u3} β γ g (List.get?.{u2} β l₂ i)))
but is expected to have type
forall {α : Type.{u3}} {β : Type.{u2}} {γ : Type.{u1}} (f : α -> β -> γ) (l₁ : List.{u3} α) (l₂ : List.{u2} β) (i : Nat), Eq.{succ u1} (Option.{u1} γ) (List.get?.{u1} γ (List.zipWith.{u3, u2, u1} α β γ f l₁ l₂) i) (Option.bind.{max u2 u1, u1} (β -> γ) γ (Option.map.{u3, max u2 u1} α (β -> γ) f (List.get?.{u3} α l₁ i)) (fun (g : β -> γ) => Option.map.{u2, u1} β γ g (List.get?.{u2} β l₂ i)))
Case conversion may be inaccurate. Consider using '#align list.nth_zip_with List.get?_zip_withₓ'. -/
theorem get?_zip_with (f : α → β → γ) (l₁ : List α) (l₂ : List β) (i : ℕ) :
(zipWith f l₁ l₂).get? i = ((l₁.get? i).map f).bind fun g => (l₂.get? i).map g :=
by
induction l₁ generalizing l₂ i
· simp [zip_with, (· <*> ·)]
· cases l₂ <;> simp only [zip_with, Seq.seq, Functor.map, nth, Option.map_none']
· cases (l₁_hd :: l₁_tl).get? i <;> rfl
· cases i <;> simp only [Option.map_some', nth, Option.some_bind', *]
#align list.nth_zip_with List.get?_zip_with
/- warning: list.nth_zip_with_eq_some -> List.get?_zip_with_eq_some is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} (f : α -> β -> γ) (l₁ : List.{u1} α) (l₂ : List.{u2} β) (z : γ) (i : Nat), Iff (Eq.{succ u3} (Option.{u3} γ) (List.get?.{u3} γ (List.zipWith.{u1, u2, u3} α β γ f l₁ l₂) i) (Option.some.{u3} γ z)) (Exists.{succ u1} α (fun (x : α) => Exists.{succ u2} β (fun (y : β) => And (Eq.{succ u1} (Option.{u1} α) (List.get?.{u1} α l₁ i) (Option.some.{u1} α x)) (And (Eq.{succ u2} (Option.{u2} β) (List.get?.{u2} β l₂ i) (Option.some.{u2} β y)) (Eq.{succ u3} γ (f x y) z)))))
but is expected to have type
forall {α : Type.{u3}} {β : Type.{u2}} {γ : Type.{u1}} (f : α -> β -> γ) (l₁ : List.{u3} α) (l₂ : List.{u2} β) (z : γ) (i : Nat), Iff (Eq.{succ u1} (Option.{u1} γ) (List.get?.{u1} γ (List.zipWith.{u3, u2, u1} α β γ f l₁ l₂) i) (Option.some.{u1} γ z)) (Exists.{succ u3} α (fun (x : α) => Exists.{succ u2} β (fun (y : β) => And (Eq.{succ u3} (Option.{u3} α) (List.get?.{u3} α l₁ i) (Option.some.{u3} α x)) (And (Eq.{succ u2} (Option.{u2} β) (List.get?.{u2} β l₂ i) (Option.some.{u2} β y)) (Eq.{succ u1} γ (f x y) z)))))
Case conversion may be inaccurate. Consider using '#align list.nth_zip_with_eq_some List.get?_zip_with_eq_someₓ'. -/
theorem get?_zip_with_eq_some {α β γ} (f : α → β → γ) (l₁ : List α) (l₂ : List β) (z : γ) (i : ℕ) :
(zipWith f l₁ l₂).get? i = some z ↔
∃ x y, l₁.get? i = some x ∧ l₂.get? i = some y ∧ f x y = z :=
by
induction l₁ generalizing l₂ i
· simp [zip_with]
· cases l₂ <;> simp only [zip_with, nth, exists_false, and_false_iff, false_and_iff]
cases i <;> simp [*]
#align list.nth_zip_with_eq_some List.get?_zip_with_eq_some
/- warning: list.nth_zip_eq_some -> List.get?_zip_eq_some is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} (l₁ : List.{u1} α) (l₂ : List.{u2} β) (z : Prod.{u1, u2} α β) (i : Nat), Iff (Eq.{succ (max u1 u2)} (Option.{max u1 u2} (Prod.{u1, u2} α β)) (List.get?.{max u1 u2} (Prod.{u1, u2} α β) (List.zip.{u1, u2} α β l₁ l₂) i) (Option.some.{max u1 u2} (Prod.{u1, u2} α β) z)) (And (Eq.{succ u1} (Option.{u1} α) (List.get?.{u1} α l₁ i) (Option.some.{u1} α (Prod.fst.{u1, u2} α β z))) (Eq.{succ u2} (Option.{u2} β) (List.get?.{u2} β l₂ i) (Option.some.{u2} β (Prod.snd.{u1, u2} α β z))))
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} (l₁ : List.{u2} α) (l₂ : List.{u1} β) (z : Prod.{u2, u1} α β) (i : Nat), Iff (Eq.{max (succ u2) (succ u1)} (Option.{max u2 u1} (Prod.{u2, u1} α β)) (List.get?.{max u2 u1} (Prod.{u2, u1} α β) (List.zip.{u2, u1} α β l₁ l₂) i) (Option.some.{max u2 u1} (Prod.{u2, u1} α β) z)) (And (Eq.{succ u2} (Option.{u2} α) (List.get?.{u2} α l₁ i) (Option.some.{u2} α (Prod.fst.{u2, u1} α β z))) (Eq.{succ u1} (Option.{u1} β) (List.get?.{u1} β l₂ i) (Option.some.{u1} β (Prod.snd.{u2, u1} α β z))))
Case conversion may be inaccurate. Consider using '#align list.nth_zip_eq_some List.get?_zip_eq_someₓ'. -/
theorem get?_zip_eq_some (l₁ : List α) (l₂ : List β) (z : α × β) (i : ℕ) :
(zip l₁ l₂).get? i = some z ↔ l₁.get? i = some z.1 ∧ l₂.get? i = some z.2 :=
by
cases z
rw [zip, nth_zip_with_eq_some]; constructor
· rintro ⟨x, y, h₀, h₁, h₂⟩
cc
· rintro ⟨h₀, h₁⟩
exact ⟨_, _, h₀, h₁, rfl⟩
#align list.nth_zip_eq_some List.get?_zip_eq_some
/- warning: list.nth_le_zip_with -> List.nthLe_zipWith is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} {f : α -> β -> γ} {l : List.{u1} α} {l' : List.{u2} β} {i : Nat} {h : LT.lt.{0} Nat Nat.hasLt i (List.length.{u3} γ (List.zipWith.{u1, u2, u3} α β γ f l l'))}, Eq.{succ u3} γ (List.nthLe.{u3} γ (List.zipWith.{u1, u2, u3} α β γ f l l') i h) (f (List.nthLe.{u1} α l i (List.lt_length_left_of_zipWith.{u1, u2, u3} α β γ f i l l' h)) (List.nthLe.{u2} β l' i (List.lt_length_right_of_zipWith.{u1, u2, u3} α β γ f i l l' h)))
but is expected to have type
forall {α : Type.{u3}} {β : Type.{u2}} {γ : Type.{u1}} {f : α -> β -> γ} {l : List.{u3} α} {l' : List.{u2} β} {i : Nat} {h : LT.lt.{0} Nat instLTNat i (List.length.{u1} γ (List.zipWith.{u3, u2, u1} α β γ f l l'))}, Eq.{succ u1} γ (List.nthLe.{u1} γ (List.zipWith.{u3, u2, u1} α β γ f l l') i h) (f (List.nthLe.{u3} α l i (List.lt_length_left_of_zipWith.{u1, u2, u3} α β γ f i l l' h)) (List.nthLe.{u2} β l' i (List.lt_length_right_of_zipWith.{u1, u2, u3} α β γ f i l l' h)))
Case conversion may be inaccurate. Consider using '#align list.nth_le_zip_with List.nthLe_zipWithₓ'. -/
@[simp]
theorem nthLe_zipWith {f : α → β → γ} {l : List α} {l' : List β} {i : ℕ}
{h : i < (zipWith f l l').length} :
(zipWith f l l').nthLe i h =
f (l.nthLe i (lt_length_left_of_zipWith h)) (l'.nthLe i (lt_length_right_of_zipWith h)) :=
by
rw [← Option.some_inj, ← nth_le_nth, nth_zip_with_eq_some]
refine'
⟨l.nth_le i (lt_length_left_of_zip_with h), l'.nth_le i (lt_length_right_of_zip_with h),
nth_le_nth _, _⟩
simp only [← nth_le_nth, eq_self_iff_true, and_self_iff]
#align list.nth_le_zip_with List.nthLe_zipWith
/- warning: list.nth_le_zip -> List.nthLe_zip is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {l : List.{u1} α} {l' : List.{u2} β} {i : Nat} {h : LT.lt.{0} Nat Nat.hasLt i (List.length.{max u1 u2} (Prod.{u1, u2} α β) (List.zip.{u1, u2} α β l l'))}, Eq.{max (succ u1) (succ u2)} (Prod.{u1, u2} α β) (List.nthLe.{max u1 u2} (Prod.{u1, u2} α β) (List.zip.{u1, u2} α β l l') i h) (Prod.mk.{u1, u2} α β (List.nthLe.{u1} α l i (List.lt_length_left_of_zip.{u1, u2} α β i l l' h)) (List.nthLe.{u2} β l' i (List.lt_length_right_of_zip.{u1, u2} α β i l l' h)))
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} {l : List.{u2} α} {l' : List.{u1} β} {i : Nat} {h : LT.lt.{0} Nat instLTNat i (List.length.{max u2 u1} (Prod.{u2, u1} α β) (List.zip.{u2, u1} α β l l'))}, Eq.{max (succ u2) (succ u1)} (Prod.{u2, u1} α β) (List.nthLe.{max u2 u1} (Prod.{u2, u1} α β) (List.zip.{u2, u1} α β l l') i h) (Prod.mk.{u2, u1} α β (List.nthLe.{u2} α l i (List.lt_length_left_of_zip.{u1, u2} α β i l l' h)) (List.nthLe.{u1} β l' i (List.lt_length_right_of_zip.{u1, u2} α β i l l' h)))
Case conversion may be inaccurate. Consider using '#align list.nth_le_zip List.nthLe_zipₓ'. -/
@[simp]
theorem nthLe_zip {l : List α} {l' : List β} {i : ℕ} {h : i < (zip l l').length} :
(zip l l').nthLe i h =
(l.nthLe i (lt_length_left_of_zip h), l'.nthLe i (lt_length_right_of_zip h)) :=
nthLe_zipWith
#align list.nth_le_zip List.nthLe_zip
#print List.mem_zip_inits_tails /-
theorem mem_zip_inits_tails {l : List α} {init tail : List α} :
(init, tail) ∈ zip l.inits l.tails ↔ init ++ tail = l :=
by
induction l generalizing init tail <;> simp_rw [tails, inits, zip_cons_cons]
· simp
· constructor <;> rw [mem_cons_iff, zip_map_left, mem_map, Prod.exists]
· rintro (⟨rfl, rfl⟩ | ⟨_, _, h, rfl, rfl⟩)
· simp
· simp [l_ih.mp h]
· cases init
· simp
· intro h
right
use init_tl, tail
simp_all
#align list.mem_zip_inits_tails List.mem_zip_inits_tails
-/
/- warning: list.map_uncurry_zip_eq_zip_with -> List.map_uncurry_zip_eq_zipWith is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} (f : α -> β -> γ) (l : List.{u1} α) (l' : List.{u2} β), Eq.{succ u3} (List.{u3} γ) (List.map.{max u1 u2, u3} (Prod.{u1, u2} α β) γ (Function.uncurry.{u1, u2, u3} α β γ f) (List.zip.{u1, u2} α β l l')) (List.zipWith.{u1, u2, u3} α β γ f l l')
but is expected to have type
forall {α : Type.{u3}} {β : Type.{u2}} {γ : Type.{u1}} (f : α -> β -> γ) (l : List.{u3} α) (l' : List.{u2} β), Eq.{succ u1} (List.{u1} γ) (List.map.{max u2 u3, u1} (Prod.{u3, u2} α β) γ (Function.uncurry.{u3, u2, u1} α β γ f) (List.zip.{u3, u2} α β l l')) (List.zipWith.{u3, u2, u1} α β γ f l l')
Case conversion may be inaccurate. Consider using '#align list.map_uncurry_zip_eq_zip_with List.map_uncurry_zip_eq_zipWithₓ'. -/
theorem map_uncurry_zip_eq_zipWith (f : α → β → γ) (l : List α) (l' : List β) :
map (Function.uncurry f) (l.zip l') = zipWith f l l' :=
by
induction' l with hd tl hl generalizing l'
· simp
· cases' l' with hd' tl'
· simp
· simp [hl]
#align list.map_uncurry_zip_eq_zip_with List.map_uncurry_zip_eq_zipWith
/- warning: list.sum_zip_with_distrib_left -> List.sum_zipWith_distrib_left is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} [_inst_1 : Semiring.{u3} γ] (f : α -> β -> γ) (n : γ) (l : List.{u1} α) (l' : List.{u2} β), Eq.{succ u3} γ (List.sum.{u3} γ (Distrib.toHasAdd.{u3} γ (NonUnitalNonAssocSemiring.toDistrib.{u3} γ (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u3} γ (Semiring.toNonAssocSemiring.{u3} γ _inst_1)))) (MulZeroClass.toHasZero.{u3} γ (NonUnitalNonAssocSemiring.toMulZeroClass.{u3} γ (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u3} γ (Semiring.toNonAssocSemiring.{u3} γ _inst_1)))) (List.zipWith.{u1, u2, u3} α β γ (fun (x : α) (y : β) => HMul.hMul.{u3, u3, u3} γ γ γ (instHMul.{u3} γ (Distrib.toHasMul.{u3} γ (NonUnitalNonAssocSemiring.toDistrib.{u3} γ (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u3} γ (Semiring.toNonAssocSemiring.{u3} γ _inst_1))))) n (f x y)) l l')) (HMul.hMul.{u3, u3, u3} γ γ γ (instHMul.{u3} γ (Distrib.toHasMul.{u3} γ (NonUnitalNonAssocSemiring.toDistrib.{u3} γ (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u3} γ (Semiring.toNonAssocSemiring.{u3} γ _inst_1))))) n (List.sum.{u3} γ (Distrib.toHasAdd.{u3} γ (NonUnitalNonAssocSemiring.toDistrib.{u3} γ (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u3} γ (Semiring.toNonAssocSemiring.{u3} γ _inst_1)))) (MulZeroClass.toHasZero.{u3} γ (NonUnitalNonAssocSemiring.toMulZeroClass.{u3} γ (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u3} γ (Semiring.toNonAssocSemiring.{u3} γ _inst_1)))) (List.zipWith.{u1, u2, u3} α β γ f l l')))
but is expected to have type
forall {α : Type.{u3}} {β : Type.{u1}} {γ : Type.{u2}} [_inst_1 : Semiring.{u2} γ] (f : α -> β -> γ) (n : γ) (l : List.{u3} α) (l' : List.{u1} β), Eq.{succ u2} γ (List.sum.{u2} γ (Distrib.toAdd.{u2} γ (NonUnitalNonAssocSemiring.toDistrib.{u2} γ (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u2} γ (Semiring.toNonAssocSemiring.{u2} γ _inst_1)))) (MonoidWithZero.toZero.{u2} γ (Semiring.toMonoidWithZero.{u2} γ _inst_1)) (List.zipWith.{u3, u1, u2} α β γ (fun (x : α) (y : β) => HMul.hMul.{u2, u2, u2} γ γ γ (instHMul.{u2} γ (NonUnitalNonAssocSemiring.toMul.{u2} γ (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u2} γ (Semiring.toNonAssocSemiring.{u2} γ _inst_1)))) n (f x y)) l l')) (HMul.hMul.{u2, u2, u2} γ γ γ (instHMul.{u2} γ (NonUnitalNonAssocSemiring.toMul.{u2} γ (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u2} γ (Semiring.toNonAssocSemiring.{u2} γ _inst_1)))) n (List.sum.{u2} γ (Distrib.toAdd.{u2} γ (NonUnitalNonAssocSemiring.toDistrib.{u2} γ (NonAssocSemiring.toNonUnitalNonAssocSemiring.{u2} γ (Semiring.toNonAssocSemiring.{u2} γ _inst_1)))) (MonoidWithZero.toZero.{u2} γ (Semiring.toMonoidWithZero.{u2} γ _inst_1)) (List.zipWith.{u3, u1, u2} α β γ f l l')))
Case conversion may be inaccurate. Consider using '#align list.sum_zip_with_distrib_left List.sum_zipWith_distrib_leftₓ'. -/
@[simp]
theorem sum_zipWith_distrib_left {γ : Type _} [Semiring γ] (f : α → β → γ) (n : γ) (l : List α)
(l' : List β) : (l.zipWith (fun x y => n * f x y) l').Sum = n * (l.zipWith f l').Sum :=
by
induction' l with hd tl hl generalizing f n l'
· simp
· cases' l' with hd' tl'
· simp
· simp [hl, mul_add]
#align list.sum_zip_with_distrib_left List.sum_zipWith_distrib_left
section Distrib
/-! ### Operations that can be applied before or after a `zip_with` -/
variable (f : α → β → γ) (l : List α) (l' : List β) (n : ℕ)
/- warning: list.zip_with_distrib_take -> List.zipWith_distrib_take is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} (f : α -> β -> γ) (l : List.{u1} α) (l' : List.{u2} β) (n : Nat), Eq.{succ u3} (List.{u3} γ) (List.take.{u3} γ n (List.zipWith.{u1, u2, u3} α β γ f l l')) (List.zipWith.{u1, u2, u3} α β γ f (List.take.{u1} α n l) (List.take.{u2} β n l'))
but is expected to have type
forall {α : Type.{u3}} {β : Type.{u1}} {γ : Type.{u2}} (f : α -> β -> γ) (l : List.{u3} α) (l' : List.{u1} β) (n : Nat), Eq.{succ u2} (List.{u2} γ) (List.take.{u2} γ n (List.zipWith.{u3, u1, u2} α β γ f l l')) (List.zipWith.{u3, u1, u2} α β γ f (List.take.{u3} α n l) (List.take.{u1} β n l'))
Case conversion may be inaccurate. Consider using '#align list.zip_with_distrib_take List.zipWith_distrib_takeₓ'. -/
theorem zipWith_distrib_take : (zipWith f l l').take n = zipWith f (l.take n) (l'.take n) :=
by
induction' l with hd tl hl generalizing l' n
· simp
· cases l'
· simp
· cases n
· simp
· simp [hl]
#align list.zip_with_distrib_take List.zipWith_distrib_take
/- warning: list.zip_with_distrib_drop -> List.zipWith_distrib_drop is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} (f : α -> β -> γ) (l : List.{u1} α) (l' : List.{u2} β) (n : Nat), Eq.{succ u3} (List.{u3} γ) (List.drop.{u3} γ n (List.zipWith.{u1, u2, u3} α β γ f l l')) (List.zipWith.{u1, u2, u3} α β γ f (List.drop.{u1} α n l) (List.drop.{u2} β n l'))
but is expected to have type
forall {α : Type.{u3}} {β : Type.{u1}} {γ : Type.{u2}} (f : α -> β -> γ) (l : List.{u3} α) (l' : List.{u1} β) (n : Nat), Eq.{succ u2} (List.{u2} γ) (List.drop.{u2} γ n (List.zipWith.{u3, u1, u2} α β γ f l l')) (List.zipWith.{u3, u1, u2} α β γ f (List.drop.{u3} α n l) (List.drop.{u1} β n l'))
Case conversion may be inaccurate. Consider using '#align list.zip_with_distrib_drop List.zipWith_distrib_dropₓ'. -/
theorem zipWith_distrib_drop : (zipWith f l l').drop n = zipWith f (l.drop n) (l'.drop n) :=
by
induction' l with hd tl hl generalizing l' n
· simp
· cases l'
· simp
· cases n
· simp
· simp [hl]
#align list.zip_with_distrib_drop List.zipWith_distrib_drop
/- warning: list.zip_with_distrib_tail -> List.zipWith_distrib_tail is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} (f : α -> β -> γ) (l : List.{u1} α) (l' : List.{u2} β), Eq.{succ u3} (List.{u3} γ) (List.tail.{u3} γ (List.zipWith.{u1, u2, u3} α β γ f l l')) (List.zipWith.{u1, u2, u3} α β γ f (List.tail.{u1} α l) (List.tail.{u2} β l'))
but is expected to have type
forall {α : Type.{u3}} {β : Type.{u1}} {γ : Type.{u2}} (f : α -> β -> γ) (l : List.{u3} α) (l' : List.{u1} β), Eq.{succ u2} (List.{u2} γ) (List.tail.{u2} γ (List.zipWith.{u3, u1, u2} α β γ f l l')) (List.zipWith.{u3, u1, u2} α β γ f (List.tail.{u3} α l) (List.tail.{u1} β l'))
Case conversion may be inaccurate. Consider using '#align list.zip_with_distrib_tail List.zipWith_distrib_tailₓ'. -/
theorem zipWith_distrib_tail : (zipWith f l l').tail = zipWith f l.tail l'.tail := by
simp_rw [← drop_one, zip_with_distrib_drop]
#align list.zip_with_distrib_tail List.zipWith_distrib_tail
/- warning: list.zip_with_append -> List.zipWith_append is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} (f : α -> β -> γ) (l : List.{u1} α) (la : List.{u1} α) (l' : List.{u2} β) (lb : List.{u2} β), (Eq.{1} Nat (List.length.{u1} α l) (List.length.{u2} β l')) -> (Eq.{succ u3} (List.{u3} γ) (List.zipWith.{u1, u2, u3} α β γ f (Append.append.{u1} (List.{u1} α) (List.hasAppend.{u1} α) l la) (Append.append.{u2} (List.{u2} β) (List.hasAppend.{u2} β) l' lb)) (Append.append.{u3} (List.{u3} γ) (List.hasAppend.{u3} γ) (List.zipWith.{u1, u2, u3} α β γ f l l') (List.zipWith.{u1, u2, u3} α β γ f la lb)))
but is expected to have type
forall {α : Type.{u3}} {β : Type.{u2}} {γ : Type.{u1}} (f : α -> β -> γ) (l : List.{u3} α) (la : List.{u3} α) (l' : List.{u2} β) (lb : List.{u2} β), (Eq.{1} Nat (List.length.{u3} α l) (List.length.{u2} β l')) -> (Eq.{succ u1} (List.{u1} γ) (List.zipWith.{u3, u2, u1} α β γ f (HAppend.hAppend.{u3, u3, u3} (List.{u3} α) (List.{u3} α) (List.{u3} α) (instHAppend.{u3} (List.{u3} α) (List.instAppendList.{u3} α)) l la) (HAppend.hAppend.{u2, u2, u2} (List.{u2} β) (List.{u2} β) (List.{u2} β) (instHAppend.{u2} (List.{u2} β) (List.instAppendList.{u2} β)) l' lb)) (HAppend.hAppend.{u1, u1, u1} (List.{u1} γ) (List.{u1} γ) (List.{u1} γ) (instHAppend.{u1} (List.{u1} γ) (List.instAppendList.{u1} γ)) (List.zipWith.{u3, u2, u1} α β γ f l l') (List.zipWith.{u3, u2, u1} α β γ f la lb)))
Case conversion may be inaccurate. Consider using '#align list.zip_with_append List.zipWith_appendₓ'. -/
theorem zipWith_append (f : α → β → γ) (l la : List α) (l' lb : List β) (h : l.length = l'.length) :
zipWith f (l ++ la) (l' ++ lb) = zipWith f l l' ++ zipWith f la lb :=
by
induction' l with hd tl hl generalizing l'
· have : l' = [] := eq_nil_of_length_eq_zero (by simpa using h.symm)
simp [this]
· cases l'
· simpa using h
· simp only [add_left_inj, length] at h
simp [hl _ h]
#align list.zip_with_append List.zipWith_append
/- warning: list.zip_with_distrib_reverse -> List.zipWith_distrib_reverse is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} (f : α -> β -> γ) (l : List.{u1} α) (l' : List.{u2} β), (Eq.{1} Nat (List.length.{u1} α l) (List.length.{u2} β l')) -> (Eq.{succ u3} (List.{u3} γ) (List.reverse.{u3} γ (List.zipWith.{u1, u2, u3} α β γ f l l')) (List.zipWith.{u1, u2, u3} α β γ f (List.reverse.{u1} α l) (List.reverse.{u2} β l')))
but is expected to have type
forall {α : Type.{u3}} {β : Type.{u2}} {γ : Type.{u1}} (f : α -> β -> γ) (l : List.{u3} α) (l' : List.{u2} β), (Eq.{1} Nat (List.length.{u3} α l) (List.length.{u2} β l')) -> (Eq.{succ u1} (List.{u1} γ) (List.reverse.{u1} γ (List.zipWith.{u3, u2, u1} α β γ f l l')) (List.zipWith.{u3, u2, u1} α β γ f (List.reverse.{u3} α l) (List.reverse.{u2} β l')))
Case conversion may be inaccurate. Consider using '#align list.zip_with_distrib_reverse List.zipWith_distrib_reverseₓ'. -/
theorem zipWith_distrib_reverse (h : l.length = l'.length) :
(zipWith f l l').reverse = zipWith f l.reverse l'.reverse :=
by
induction' l with hd tl hl generalizing l'
· simp
· cases' l' with hd' tl'
· simp
· simp only [add_left_inj, length] at h
have : tl.reverse.length = tl'.reverse.length := by simp [h]
simp [hl _ h, zip_with_append _ _ _ _ _ this]
#align list.zip_with_distrib_reverse List.zipWith_distrib_reverse
end Distrib
section CommMonoid
variable [CommMonoid α]
/- warning: list.prod_mul_prod_eq_prod_zip_with_mul_prod_drop -> List.prod_mul_prod_eq_prod_zipWith_mul_prod_drop is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} [_inst_1 : CommMonoid.{u1} α] (L : List.{u1} α) (L' : List.{u1} α), Eq.{succ u1} α (HMul.hMul.{u1, u1, u1} α α α (instHMul.{u1} α (MulOneClass.toHasMul.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1)))) (List.prod.{u1} α (MulOneClass.toHasMul.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1))) (MulOneClass.toHasOne.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1))) L) (List.prod.{u1} α (MulOneClass.toHasMul.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1))) (MulOneClass.toHasOne.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1))) L')) (HMul.hMul.{u1, u1, u1} α α α (instHMul.{u1} α (MulOneClass.toHasMul.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1)))) (HMul.hMul.{u1, u1, u1} α α α (instHMul.{u1} α (MulOneClass.toHasMul.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1)))) (List.prod.{u1} α (MulOneClass.toHasMul.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1))) (MulOneClass.toHasOne.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1))) (List.zipWith.{u1, u1, u1} α α α (HMul.hMul.{u1, u1, u1} α α α (instHMul.{u1} α (MulOneClass.toHasMul.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1))))) L L')) (List.prod.{u1} α (MulOneClass.toHasMul.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1))) (MulOneClass.toHasOne.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1))) (List.drop.{u1} α (List.length.{u1} α L') L))) (List.prod.{u1} α (MulOneClass.toHasMul.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1))) (MulOneClass.toHasOne.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1))) (List.drop.{u1} α (List.length.{u1} α L) L')))
but is expected to have type
forall {α : Type.{u1}} [_inst_1 : CommMonoid.{u1} α] (L : List.{u1} α) (L' : List.{u1} α), Eq.{succ u1} α (HMul.hMul.{u1, u1, u1} α α α (instHMul.{u1} α (MulOneClass.toMul.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1)))) (List.prod.{u1} α (MulOneClass.toMul.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1))) (Monoid.toOne.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1)) L) (List.prod.{u1} α (MulOneClass.toMul.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1))) (Monoid.toOne.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1)) L')) (HMul.hMul.{u1, u1, u1} α α α (instHMul.{u1} α (MulOneClass.toMul.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1)))) (HMul.hMul.{u1, u1, u1} α α α (instHMul.{u1} α (MulOneClass.toMul.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1)))) (List.prod.{u1} α (MulOneClass.toMul.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1))) (Monoid.toOne.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1)) (List.zipWith.{u1, u1, u1} α α α (fun ([email protected]._hyg.6906 : α) ([email protected]._hyg.6908 : α) => HMul.hMul.{u1, u1, u1} α α α (instHMul.{u1} α (MulOneClass.toMul.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1)))) [email protected]._hyg.6906 [email protected]._hyg.6908) L L')) (List.prod.{u1} α (MulOneClass.toMul.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1))) (Monoid.toOne.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1)) (List.drop.{u1} α (List.length.{u1} α L') L))) (List.prod.{u1} α (MulOneClass.toMul.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1))) (Monoid.toOne.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1)) (List.drop.{u1} α (List.length.{u1} α L) L')))
Case conversion may be inaccurate. Consider using '#align list.prod_mul_prod_eq_prod_zip_with_mul_prod_drop List.prod_mul_prod_eq_prod_zipWith_mul_prod_dropₓ'. -/
@[to_additive]
theorem prod_mul_prod_eq_prod_zipWith_mul_prod_drop :
∀ L L' : List α,
L.Prod * L'.Prod =
(zipWith (· * ·) L L').Prod * (L.drop L'.length).Prod * (L'.drop L.length).Prod
| [], ys => by simp [Nat.zero_le]
| xs, [] => by simp [Nat.zero_le]
| x :: xs, y :: ys =>
by
simp only [drop, length, zip_with_cons_cons, prod_cons]
rw [mul_assoc x, mul_comm xs.prod, mul_assoc y, mul_comm ys.prod,
prod_mul_prod_eq_prod_zip_with_mul_prod_drop xs ys, mul_assoc, mul_assoc, mul_assoc,
mul_assoc]
#align list.prod_mul_prod_eq_prod_zip_with_mul_prod_drop List.prod_mul_prod_eq_prod_zipWith_mul_prod_drop
#align list.sum_add_sum_eq_sum_zip_with_add_sum_drop List.sum_add_sum_eq_sum_zipWith_add_sum_drop
/- warning: list.prod_mul_prod_eq_prod_zip_with_of_length_eq -> List.prod_mul_prod_eq_prod_zipWith_of_length_eq is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} [_inst_1 : CommMonoid.{u1} α] (L : List.{u1} α) (L' : List.{u1} α), (Eq.{1} Nat (List.length.{u1} α L) (List.length.{u1} α L')) -> (Eq.{succ u1} α (HMul.hMul.{u1, u1, u1} α α α (instHMul.{u1} α (MulOneClass.toHasMul.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1)))) (List.prod.{u1} α (MulOneClass.toHasMul.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1))) (MulOneClass.toHasOne.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1))) L) (List.prod.{u1} α (MulOneClass.toHasMul.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1))) (MulOneClass.toHasOne.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1))) L')) (List.prod.{u1} α (MulOneClass.toHasMul.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1))) (MulOneClass.toHasOne.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1))) (List.zipWith.{u1, u1, u1} α α α (HMul.hMul.{u1, u1, u1} α α α (instHMul.{u1} α (MulOneClass.toHasMul.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1))))) L L')))
but is expected to have type
forall {α : Type.{u1}} [_inst_1 : CommMonoid.{u1} α] (L : List.{u1} α) (L' : List.{u1} α), (Eq.{1} Nat (List.length.{u1} α L) (List.length.{u1} α L')) -> (Eq.{succ u1} α (HMul.hMul.{u1, u1, u1} α α α (instHMul.{u1} α (MulOneClass.toMul.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1)))) (List.prod.{u1} α (MulOneClass.toMul.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1))) (Monoid.toOne.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1)) L) (List.prod.{u1} α (MulOneClass.toMul.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1))) (Monoid.toOne.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1)) L')) (List.prod.{u1} α (MulOneClass.toMul.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1))) (Monoid.toOne.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1)) (List.zipWith.{u1, u1, u1} α α α (fun ([email protected]._hyg.7105 : α) ([email protected]._hyg.7107 : α) => HMul.hMul.{u1, u1, u1} α α α (instHMul.{u1} α (MulOneClass.toMul.{u1} α (Monoid.toMulOneClass.{u1} α (CommMonoid.toMonoid.{u1} α _inst_1)))) [email protected]._hyg.7105 [email protected]._hyg.7107) L L')))
Case conversion may be inaccurate. Consider using '#align list.prod_mul_prod_eq_prod_zip_with_of_length_eq List.prod_mul_prod_eq_prod_zipWith_of_length_eqₓ'. -/
@[to_additive]
theorem prod_mul_prod_eq_prod_zipWith_of_length_eq (L L' : List α) (h : L.length = L'.length) :
L.Prod * L'.Prod = (zipWith (· * ·) L L').Prod :=
(prod_mul_prod_eq_prod_zipWith_mul_prod_drop L L').trans (by simp [h])
#align list.prod_mul_prod_eq_prod_zip_with_of_length_eq List.prod_mul_prod_eq_prod_zipWith_of_length_eq
#align list.sum_add_sum_eq_sum_zip_with_of_length_eq List.sum_add_sum_eq_sum_zipWith_of_length_eq
end CommMonoid
end List
|
/-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
universes u v
namespace Mathlib
namespace smt
def array (α : Type u) (β : Type v) := α → β
def select {α : Type u} {β : Type v} (a : array α β) (i : α) : β := a i
theorem arrayext {α : Type u} {β : Type v} (a₁ : array α β) (a₂ : array α β) :
(∀ (i : α), select a₁ i = select a₂ i) → a₁ = a₂ :=
funext
def store {α : Type u} {β : Type v} [DecidableEq α] (a : array α β) (i : α) (v : β) : array α β :=
fun (j : α) => ite (j = i) v (select a j)
@[simp] theorem select_store {α : Type u} {β : Type v} [DecidableEq α] (a : array α β) (i : α)
(v : β) : select (store a i v) i = v :=
sorry
@[simp] theorem select_store_ne {α : Type u} {β : Type v} [DecidableEq α] (a : array α β) (i : α)
(j : α) (v : β) : j ≠ i → select (store a i v) j = select a j :=
sorry
end Mathlib |
module Tensor where
open import Basics
open import Ix
open import All
open import Perm
open import Cutting
open import Recutter
open _|>_
open RECUTTER
open SUBCOLLECTLEMMA
_><_ : forall {I J} -> (I |> I) -> (J |> J) -> (I * J) |> (I * J)
Cuts (C >< D) (i , j) = Cuts C i + Cuts D j
inners (C >< D) {i , j} (inl c) = list (_, j) (inners C c)
inners (C >< D) {i , j} (inr d) = list (i ,_) (inners D d)
module TENSORRECUT {I J}(C : I |> I)(D : J |> J)(rec : Recutter C)(red : Recutter D) where
cartLeftLemma : (is : List I)(j : J)(d : Cuts D j) -> subCollect (C >< D) (list (_, j) is)
(allRe (_, j) is
(allPu (\ _ -> inr (inr d)) is)) == cart is (inners D d)
cartLeftLemma [] j d = refl []
cartLeftLemma (i ,- is) j d = refl (list (i ,_) (inners D d) +L_) =$= cartLeftLemma is j d
cartRightLemma : (i : I)(c : Cuts C i)(js : List J) ->
subCollect (C >< D) (list (i ,_) js)
(allRe (i ,_) js (allPu (\ _ -> inr (inl c)) js)) ==
list swap (cart js (inners C c))
cartRightLemma i c [] = refl []
cartRightLemma i c (j ,- js)
rewrite sym (catNatural swap (list (j ,_) (inners C c)) (cart js (inners C c)))
| listlist swap (j ,_) (_, j) (\ i -> refl (i , j)) (inners C c)
= refl (list (_, j) (inners C c) +L_) =$= cartRightLemma i c js
TensorRecut : Recutter (C >< D)
-- both cuts in left dimension
TensorRecut (i , j) (inl c) (inl c') with rec i c c'
... | x , y , m
= allRe (_, j) (inners C c) (all (\ _ -> id +map inl) _ x)
, allRe (_, j) (inners C c') (all (\ _ -> id +map inl) _ y)
, lemma where
lemma : subCollect (C >< D) (list (_, j) (inners C c))
(allRe (_, j) (inners C c) (all (\ _ -> id +map inl) (inners C c) x))
~
subCollect (C >< D) (list (_, j) (inners C c'))
(allRe (_, j) (inners C c') (all (\ _ -> id +map inl) (inners C c') y))
lemma rewrite subCollectLemma C (C >< D) (_, j) (\ _ -> inl) (\ i c -> refl _)
(inners C c) x
| subCollectLemma C (C >< D) (_, j) (\ _ -> inl) (\ i c -> refl _)
(inners C c') y
= permap (_, j) m
-- left to right
fst (TensorRecut (i , j) (inl c) (inr d)) =
allRe (_, j) (inners C c) (allPu (\ i -> inr (inr d)) (inners C c))
fst (snd (TensorRecut (i , j) (inl c) (inr d))) =
allRe (i ,_) (inners D d) (allPu (\ i -> inr (inl c)) (inners D d))
snd (snd (TensorRecut (i , j) (inl c) (inr d)))
rewrite cartLeftLemma (inners C c) j d
| cartRightLemma i c (inners D d)
= cartLemma (inners C c) (inners D d)
-- right to left
fst (TensorRecut (i , j) (inr d) (inl c)) =
allRe (i ,_) (inners D d) (allPu (\ i -> inr (inl c)) (inners D d))
fst (snd (TensorRecut (i , j) (inr d) (inl c))) =
allRe (_, j) (inners C c) (allPu (\ i -> inr (inr d)) (inners C c))
snd (snd (TensorRecut (i , j) (inr d) (inl c)))
rewrite cartLeftLemma (inners C c) j d
| cartRightLemma i c (inners D d)
= symP (cartLemma (inners C c) (inners D d))
-- both cuts in right dimension
TensorRecut (i , j) (inr d) (inr d') with red j d d'
... | x , y , m
= allRe (i ,_) (inners D d) (all (\ _ -> id +map inr) _ x)
, allRe (i ,_) (inners D d') (all (\ _ -> id +map inr) _ y)
, lemma where
lemma : subCollect (C >< D) (list (i ,_) (inners D d))
(allRe (i ,_) (inners D d) (all (\ _ -> id +map inr) (inners D d) x))
~
subCollect (C >< D) (list (i ,_) (inners D d'))
(allRe (i ,_) (inners D d') (all (\ _ -> id +map inr) (inners D d') y))
lemma rewrite subCollectLemma D (C >< D) (i ,_) (\ _ -> inr) (\ i d -> refl _)
(inners D d) x
| subCollectLemma D (C >< D) (i ,_) (\ _ -> inr) (\ i d -> refl _)
(inners D d') y
= permap (i ,_) m
module RECTANGLE where
RectCut = NatCut >< NatCut
open NATRECUT
open TENSORRECUT NatCut NatCut NatRecut NatRecut
RectRecut = TensorRecut
|
Every CV is unique to that individual person and nobody else is going to have exactly the same education, qualifications and experience. However many people make the mistake of designing a CV that does not allow them to stand out from the bundle of other CV’s they will be competing with. In order to have the best possible chance of interview the following five factors should always be taken into account.
Why should an employer choose you over the other two hundred applicants? What special ability do you have to bring to the position? Employers don’t just want to know how many computer packages you have used they also want to know how you can use this knowledge to make money for them by increasing efficiency in the office.
2. Keep it simple but informative.
An employer will only spend seconds glancing at your CV before he decides to either investigate it further or place it aside. That’s why it is imperative to make your CV visually attractive, easy to read and your attributes and experience should be clearly and concisely listed in a way that will make the potential employer want to interview you.
While it is a laborious process to rewrite each CV to specifically target the audience you have in mind this is the most effective method of getting an interview. A little bit more effort now really does pay dividends in the longer term.
The importance of proofreading your CV many times and making sure every word is spelt correctly cannot be overemphasized. As well as this make sure all your employment dates add up and that any contact email addresses, phone numbers or web addresses are still correct. Also never leave any period unaccounted for on your CV interviewers will ask what you were doing then.
If you have gone on any courses, or have acquired additional skills even if it is just from voluntary or casual work always remember to add new information to your CV and perhaps you might need to remove older information that might now be no longer relevant. |
/-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.meta init.data.sigma.lex init.data.nat.lemmas init.data.list.instances
import init.data.list.qsort
/- TODO(Leo): move this lemma, or delete it after we add algebraic normalizer. -/
lemma nat.lt_add_of_zero_lt_left (a b : nat) (h : 0 < b) : a < a + b :=
show a + 0 < a + b,
by {apply nat.add_lt_add_left, assumption}
/- TODO(Leo): move this lemma, or delete it after we add algebraic normalizer. -/
lemma nat.zero_lt_one_add (a : nat) : 0 < 1 + a :=
suffices 0 < a + 1, by {simp [nat.add_comm], assumption},
nat.zero_lt_succ _
/- TODO(Leo): move this lemma, or delete it after we add algebraic normalizer. -/
lemma nat.lt_add_right (a b c : nat) : a < b → a < b + c :=
λ h, lt_of_lt_of_le h (nat.le_add_right _ _)
/- TODO(Leo): move this lemma, or delete it after we add algebraic normalizer. -/
lemma nat.lt_add_left (a b c : nat) : a < b → a < c + b :=
λ h, lt_of_lt_of_le h (nat.le_add_left _ _)
protected def {u v} psum.alt.sizeof
{α : Type u} {β : Type v} [has_sizeof α] [has_sizeof β] : psum α β → ℕ
| (psum.inl a) := sizeof a
| (psum.inr b) := sizeof b
@[reducible]
protected def {u v} psum.has_sizeof_alt
(α : Type u) (β : Type v) [has_sizeof α] [has_sizeof β] : has_sizeof (psum α β) :=
⟨psum.alt.sizeof⟩
namespace well_founded_tactics
open tactic
def id_tag.wf : unit := ()
meta def mk_alt_sizeof : expr → expr
| (expr.app (expr.app (expr.app (expr.app (expr.const ``psum.has_sizeof l) α) β) iα) iβ) :=
(expr.const ``psum.has_sizeof_alt l : expr) α β iα (mk_alt_sizeof iβ)
| e := e
meta def default_rel_tac (e : expr) (eqns : list expr) : tactic unit :=
do tgt ← target,
rel ← mk_instance tgt,
exact $ match e, rel with
expr.local_const _ (name.mk_string "_mutual" _) _ _,
expr.app e@`(@has_well_founded_of_has_sizeof _) sz := e (mk_alt_sizeof sz)
| _, _ := rel
end
private meta def clear_wf_rec_goal_aux : list expr → tactic unit
| [] := return ()
| (h::hs) := clear_wf_rec_goal_aux hs >> try (guard (h.local_pp_name.is_internal || h.is_aux_decl) >> clear h)
meta def clear_internals : tactic unit :=
local_context >>= clear_wf_rec_goal_aux
meta def unfold_wf_rel : tactic unit :=
dunfold_target [``has_well_founded.r] {fail_if_unchanged := ff}
meta def is_psigma_mk : expr → tactic (expr × expr)
| `(psigma.mk %%a %%b) := return (a, b)
| _ := failed
meta def process_lex : tactic unit → tactic unit
| tac :=
do t ← target >>= whnf,
if t.is_napp_of `psigma.lex 6 then
let a := t.app_fn.app_arg in
let b := t.app_arg in
do (a₁, a₂) ← is_psigma_mk a,
(b₁, b₂) ← is_psigma_mk b,
(is_def_eq a₁ b₁ >> `[apply psigma.lex.right] >> process_lex tac)
<|>
(`[apply psigma.lex.left] >> tac)
else
tac
private meta def unfold_sizeof_measure : tactic unit :=
dunfold_target [``sizeof_measure, ``measure, ``inv_image] {fail_if_unchanged := ff}
private meta def add_simps : simp_lemmas → list name → tactic simp_lemmas
| s [] := return s
| s (n::ns) := do s' ← s.add_simp n ff, add_simps s' ns
private meta def collect_sizeof_lemmas (e : expr) : tactic simp_lemmas :=
e.mfold simp_lemmas.mk $ λ c d s,
if c.is_constant then
match c.const_name with
| name.mk_string "sizeof" p :=
do eqns ← get_eqn_lemmas_for tt c.const_name,
add_simps s eqns
| _ := return s
end
else
return s
private meta def unfold_sizeof_loop : tactic unit :=
do
dunfold_target [``sizeof, ``has_sizeof.sizeof] {fail_if_unchanged := ff},
S ← target >>= collect_sizeof_lemmas,
(simp_target S >> unfold_sizeof_loop)
<|>
try `[simp]
meta def unfold_sizeof : tactic unit :=
unfold_sizeof_measure >> unfold_sizeof_loop
/- The following section should be removed as soon as we implement the
algebraic normalizer. -/
section simple_dec_tac
open tactic expr
private meta def collect_add_args : expr → list expr
| `(%%a + %%b) := collect_add_args a ++ collect_add_args b
| e := [e]
private meta def mk_nat_add : list expr → tactic expr
| [] := to_expr ``(0)
| [a] := return a
| (a::as) := do
rs ← mk_nat_add as,
to_expr ``(%%a + %%rs)
private meta def mk_nat_add_add : list expr → list expr → tactic expr
| [] b := mk_nat_add b
| a [] := mk_nat_add a
| a b :=
do t ← mk_nat_add a,
s ← mk_nat_add b,
to_expr ``(%%t + %%s)
private meta def get_add_fn (e : expr) : expr :=
if is_napp_of e `has_add.add 4 then e.app_fn.app_fn
else e
private meta def prove_eq_by_perm (a b : expr) : tactic expr :=
(is_def_eq a b >> to_expr ``(eq.refl %%a))
<|>
perm_ac (get_add_fn a) `(nat.add_assoc) `(nat.add_comm) a b
private meta def num_small_lt (a b : expr) : bool :=
if a = b then ff
else if is_napp_of a `has_one.one 2 then tt
else if is_napp_of b `has_one.one 2 then ff
else a.lt b
private meta def sort_args (args : list expr) : list expr :=
args.qsort num_small_lt
private def tagged_proof.wf : unit := ()
meta def cancel_nat_add_lt : tactic unit :=
do `(%%lhs < %%rhs) ← target,
ty ← infer_type lhs >>= whnf,
guard (ty = `(nat)),
let lhs_args := collect_add_args lhs,
let rhs_args := collect_add_args rhs,
let common := lhs_args.bag_inter rhs_args,
if common = [] then return ()
else do
let lhs_rest := lhs_args.diff common,
let rhs_rest := rhs_args.diff common,
new_lhs ← mk_nat_add_add common (sort_args lhs_rest),
new_rhs ← mk_nat_add_add common (sort_args rhs_rest),
lhs_pr ← prove_eq_by_perm lhs new_lhs,
rhs_pr ← prove_eq_by_perm rhs new_rhs,
target_pr ← to_expr ``(congr (congr_arg (<) %%lhs_pr) %%rhs_pr),
new_target ← to_expr ``(%%new_lhs < %%new_rhs),
replace_target new_target target_pr ``id_tag.wf,
`[apply nat.add_lt_add_left] <|> `[apply nat.lt_add_of_zero_lt_left]
meta def check_target_is_value_lt : tactic unit :=
do `(%%lhs < %%rhs) ← target,
guard lhs.is_numeral
meta def trivial_nat_lt : tactic unit :=
comp_val
<|>
`[apply nat.zero_lt_one_add]
<|>
assumption
<|>
(do check_target_is_value_lt,
(`[apply nat.lt_add_right] >> trivial_nat_lt)
<|>
(`[apply nat.lt_add_left] >> trivial_nat_lt))
<|>
failed
end simple_dec_tac
meta def default_dec_tac : tactic unit :=
abstract $
do clear_internals,
unfold_wf_rel,
-- The next line was adapted from code in mathlib by Scott Morrison.
-- Because `unfold_sizeof` could actually discharge the goal, add a test
-- using `done` to detect this.
process_lex (unfold_sizeof >> (done <|> (cancel_nat_add_lt >> trivial_nat_lt))) <|>
-- Clean up the goal state but not too much before printing the error
(unfold_sizeof >> fail "default_dec_tac failed")
end well_founded_tactics
/-- Argument for using_well_founded
The tactic `rel_tac` has to synthesize an element of type (has_well_founded A).
The two arguments are: a local representing the function being defined by well
founded recursion, and a list of recursive equations.
The equations can be used to decide which well founded relation should be used.
The tactic `dec_tac` has to synthesize decreasing proofs.
-/
meta structure well_founded_tactics :=
(rel_tac : expr → list expr → tactic unit := well_founded_tactics.default_rel_tac)
(dec_tac : tactic unit := well_founded_tactics.default_dec_tac)
meta def well_founded_tactics.default : well_founded_tactics :=
{}
|
# Copyright (c) 2018-2021, Carnegie Mellon University
# See LICENSE for details
TestFailExit := function()
Print("TEST FAILED\n");
Exit(-1);
end;
TestSkipExit := function()
Print("Skipping test\n");
Exit(86);
end;
#F GetBasicProfilerTestFName (<pf>)
#F Get the filename associated with Basic Profiler Test
#F if <pf> return Success file name
#F otherwise return Failure file name
GetBasicProfilerTestFName := function(pf)
local path, sep;
sep := Conf("path_sep");
path := Conf("spiral_dir");
path := Concat(path, sep, "build");
if pf then
path := Concat(path, sep, "PROFILER_RUN_SUCCESS");
else
path := Concat(path, sep, "PROFILER_RUN_FAILED");
fi;
return path;
end;
#F ClearBasicProfilerTestResults () -- remove results of prior run(s) of basic profiler test
ClearBasicProfilerTestResults := function()
SysRemove(GetBasicProfilerTestFName(true));
SysRemove(GetBasicProfilerTestFName(false));
return;
end;
#F MarkBasicProfilerTest (<pf>)
#F Mark (create the filename) associated with Basic Profiler Test
#F if <pf> ==> test successed, use success file name
#F otherwise ==> test failed, use Failure file name
MarkBasicProfilerTest := function(pf)
local path;
path := GetBasicProfilerTestFName(pf);
PrintTo(path, "");
return;
end;
#F CheckBasicProfilerTest () -- Return True if basic profiler test passed, otherwise, False
CheckBasicProfilerTest := function()
local res, file;
file := GetBasicProfilerTestFName(true);
res := CheckFileExists(file, "");
if SysVerbose() > 0 then
Print("Marker file: ", file);
if res then PrintLine(" Found, return true"); else PrintLine(" NOT Found"); fi;
fi;
if res then return res; fi;
file := GetBasicProfilerTestFName(false);
res := CheckFileExists(file, "");
if SysVerbose() > 0 then
Print("Marker file: ", file);
if res then PrintLine(" Found, return false"); else PrintLine(" NOT Found"); fi;
fi;
return false;
end;
|
library(httr)
# 1. Find OAuth settings for yahoo:
# https://developer.yahoo.com/oauth/guide/oauth-auth-flow.html
oauth_endpoints("yahoo")
# 2. Register an application at https://developer.apps.yahoo.com/projects
# Replace key and secret below.
myapp <- oauth_app("yahoo",
key = "dj0yJmk9ZEp0d2J2MFRuakNQJmQ9WVdrOU0zaHRUMlJpTTJNbWNHbzlNQS0tJnM9Y29uc3VtZXJzZWNyZXQmeD00Nw--",
secret = "82f339a41f71a3b4d9b840be427dde132e36d115"
)
# 3. Get OAuth credentials
yahoo_token <- oauth1.0_token(oauth_endpoints("yahoo"), myapp)
|
Formal statement is: lemma prime_power_mult_nat: fixes p :: nat assumes p: "prime p" and xy: "x * y = p ^ k" shows "\<exists>i j. x = p ^ i \<and> y = p^ j" Informal statement is: If $p$ is a prime number and $x$ and $y$ are natural numbers such that $x y = p^k$, then there exist natural numbers $i$ and $j$ such that $x = p^i$ and $y = p^j$. |
Formal statement is: corollary interior_bijective_linear_image: fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space" assumes "linear f" "bij f" shows "interior (f ` S) = f ` interior S" (is "?lhs = ?rhs") Informal statement is: If $f$ is a linear bijection, then the interior of the image of a set $S$ is the image of the interior of $S$. |
-- This file needs to be rewritten so that Rng's are defined as a
-- record (as is the case for other algebraic structures like
-- rings). As this file isn't used for anything at the moment this
-- rewrite has been postponed.
{-# OPTIONS --cubical --no-import-sorts --safe #-}
module Cubical.Experiments.Rng where
open import Cubical.Foundations.Prelude
open import Cubical.Foundations.Equiv
open import Cubical.Foundations.HLevels
open import Cubical.Foundations.SIP
open import Cubical.Data.Sigma
open import Cubical.Structures.Axioms
open import Cubical.Structures.Auto
open import Cubical.Structures.Macro
open import Cubical.Algebra.Semigroup hiding (⟨_⟩)
open import Cubical.Algebra.AbGroup
private
variable
ℓ ℓ' : Level
module _ {ℓ} where
rawRngDesc : Desc ℓ
rawRngDesc = autoDesc (λ (X : Type ℓ) → (X → X → X) × (X → X → X))
open Macro ℓ rawRngDesc public renaming
( structure to RawRngStructure
; equiv to RawRngEquivStr
; univalent to rawRngUnivalentStr
)
RngAxioms : (X : Type ℓ) (s : RawRngStructure X) → Type ℓ
RngAxioms X (_·_ , _+_) =
AbGroupΣTheory.AbGroupAxioms X _·_ ×
SemigroupΣTheory.SemigroupAxioms X _+_ ×
((x y z : X) → x · (y + z) ≡ (x · y) + (x · z)) × ((x y z : X) → (x + y) · z ≡ (x · z) + (y · z))
RngStructure : Type ℓ → Type ℓ
RngStructure = AxiomsStructure RawRngStructure RngAxioms
Rng : Type (ℓ-suc ℓ)
Rng {ℓ} = TypeWithStr ℓ RngStructure
RngEquivStr : StrEquiv RngStructure ℓ
RngEquivStr = AxiomsEquivStr RawRngEquivStr RngAxioms
isPropRngAxioms : (X : Type ℓ) (s : RawRngStructure X) → isProp (RngAxioms X s)
isPropRngAxioms X (_·_ , _+_) = isPropΣ (AbGroupΣTheory.isPropAbGroupAxioms X _·_)
λ _ → isPropΣ (SemigroupΣTheory.isPropSemigroupAxioms X _+_)
λ { (isSetX , _) → isPropΣ (isPropΠ3 (λ _ _ _ → isSetX _ _))
λ _ → isPropΠ3 (λ _ _ _ → isSetX _ _)}
rngUnivalentStr : UnivalentStr {ℓ} RngStructure RngEquivStr
rngUnivalentStr = axiomsUnivalentStr _ isPropRngAxioms rawRngUnivalentStr
RngPath : (M N : Rng {ℓ}) → (M ≃[ RngEquivStr ] N) ≃ (M ≡ N)
RngPath = SIP rngUnivalentStr
|
module Control.TransitionIndexed
import public Control.Monad.TransitionIndexed
import public Control.Monad.TransitionIndexed.Do
|
||| `OrdList` is a "labelled" list that ensure that inserted elements are ordered.
module Flexidisc.OrdList
import public Flexidisc.OrdList.CompWithKeys
import public Flexidisc.OrdList.Diff
import public Flexidisc.OrdList.Disjoint
import public Flexidisc.OrdList.HereOrNot
import public Flexidisc.OrdList.Fresh
import public Flexidisc.OrdList.Label
import public Flexidisc.OrdList.Nub
import public Flexidisc.OrdList.Permute
import public Flexidisc.OrdList.Sub
import public Flexidisc.OrdList.SubWithKeys
import public Flexidisc.OrdList.Type
import public Flexidisc.OrdList.Row
%default total
%access public export
||| A witness that two OrdList are using the same order
||| (as well as the same key and value type, but this is more obvious)
data SameOrd : (xs, ys : OrdList k v o) -> Type where
Same : SameOrd xs ys
|
import tactic tactic.induction
namespace exlean
inductive fuzzy
| yes : fuzzy
| no : fuzzy
| meh : fuzzy
example : Type := fuzzy
open fuzzy
namespace fuzzy
universe u
def fuzzy.rec_on' {C : fuzzy → Sort u} (t : fuzzy) (h₀ : C yes) (h₁ : C no) (h₂ : C meh) : C t :=
fuzzy.rec_on t h₀ h₁ h₂
example : fuzzy := yes
def tea (t : fuzzy) : string :=
fuzzy.rec_on t "Here's your tea!" "Get out." "Are you sure?"
example : tea yes = "Here's your tea!" := rfl
def tea2 (t : fuzzy) : string :=
@fuzzy.rec_on (λ x, string) t "Here's your tea!" "Get out." "Are you sure?"
def tea3 (t : fuzzy) : string :=
begin
cases t,
{ exact "Here's your tea!" },
{ exact "Get out." },
{ exact "Are you sure?"}
end
def tea4 : fuzzy → string
| yes := "Here's your tea!"
| no := "Get out."
| meh := "Are you sure?"
def tea5 (f : fuzzy) : string :=
"My response to your response is: '" ++
match f with
| yes := "Here's your tea!"
| no := "Get out."
| meh := "Are you sure?"
end
++ "' "
#eval tea5 yes
lemma only_ynm (t : fuzzy) : t = yes ∨ t = no ∨ t = meh :=
fuzzy.rec_on t (or.inl rfl) (or.inr $ or.inl rfl) (or.inr $ or.inr rfl)
def C_only_ynm := λ (x : fuzzy), x = yes ∨ x = no ∨ x = meh
lemma only_ynm2 (t : fuzzy) : t = yes ∨ (t = no ∨ t = meh) :=
@fuzzy.rec_on C_only_ynm t (or.inl rfl) (or.inr $ or.inl rfl) (or.inr $ or.inr rfl)
lemma only_ynm3 (t : fuzzy) : t = yes ∨ t = no ∨ t = meh :=
begin
apply fuzzy.rec_on t,
{ left, refl, },
{ right, left, refl, },
{ right, right, refl, },
end
lemma only_ynm4 (t : fuzzy) : t = yes ∨ t = no ∨ t = meh :=
begin
cases t,
{ left, refl, },
{ right, left, refl, },
{ right, right, refl, },
end
lemma only_ynm5 (t : fuzzy) : t = yes ∨ t = no ∨ t = meh := by { cases t; tauto }
def yes_no : ¬ yes = no .
def yes_no2 : ¬ yes = no := assume h : yes = no, fuzzy.no_confusion h
def yes_no3 : ¬ yes = no := assume h : yes = no, @fuzzy.no_confusion false yes no h
def f_no_confusion_type_full : Sort u → fuzzy → fuzzy → Sort u :=
λ (P : Sort u) (v₁ v₂ : fuzzy),
@fuzzy.rec_on (λ (v₁ : fuzzy), Sort u) v₁
(@fuzzy.rec_on (λ (v₁ : fuzzy), Sort u) v₂ (P → P) P P)
(@fuzzy.rec_on (λ (v₁ : fuzzy), Sort u) v₂ P (P → P) P)
(@fuzzy.rec_on (λ (v₁ : fuzzy), Sort u) v₂ P P (P → P))
def f_no_confusion_type : Sort u → fuzzy → fuzzy → Sort u :=
λ (P : Sort u) (v₁ v₂ : fuzzy),
fuzzy.rec_on v₁
(fuzzy.rec_on v₂ (P → P) P P)
(fuzzy.rec_on v₂ P (P → P) P)
(fuzzy.rec_on v₂ P P (P → P))
def f_no_confusion : Π {P : Sort u} {v₁ v₂ : fuzzy}, v₁ = v₂ → f_no_confusion_type P v₁ v₂ :=
λ {P : Sort u} {v₁ v₂ : fuzzy} (h : v₁ = v₂),
eq.rec_on h (λ (h₂ : v₁ = v₁), fuzzy.rec_on v₁ (λ (a : P), a) (λ (a : P), a) (λ (a : P), a)) h
end fuzzy
namespace staff
inductive staff
| hod : staff
| doctor (n : fuzzy) : staff
| secretary (id : ℕ) (boss : staff) : staff
example : Type := staff
open staff fuzzy
def jill : staff := hod
def dr_no : staff := doctor no
def dr_meh : staff := doctor meh
def justin : staff := secretary 10 jill
def selima : staff := secretary 5 dr_no
def gursel : staff := secretary 7 selima
def salary : staff → ℚ
| hod := 500000
| (doctor yes) := 100000
| (doctor _) := 5000
| (secretary num boss) := 1 / num + (salary boss) / 2
example : salary dr_meh = 5000 := rfl
example : salary selima = 12501 / 5 := by { dsimp [selima, dr_no, salary], norm_num }
def salary2 (s : staff) : ℚ := staff.rec_on s
500000 (λ (f : fuzzy), f.rec_on 100000 5000 5000)
(λ (n : ℕ) (boss : staff) (bs : ℚ), 1 / n + bs / 2)
def salary3 (s : staff) : ℚ := staff.rec_on s
500000 (λ f, f.rec_on 100000 5000 5000)
(λ n _ bs, 1 / n + bs / 2)
def salary_new : staff → ℚ
| hod := 500000
| (doctor yes) := 100000
| (doctor _) := 5000
| (secretary 0 boss) := (salary_new boss) / 200
| (secretary (n+1) boss) := 1 / n + salary_new (secretary n boss)
end staff
section inductive_propositions
/-
The following defintions `myor` and `myand` are quite different from the definitions `and` and `or`.
In particular, for each `α β : Prop`, `myand α β : Type`, whereas `and α β : Prop`.
-/
-- `myor` and `myand` ARE NOT INDUCTIVELY-DEFINED PROPOSITIONS!!!
inductive myor (α β : Prop)
| inl (h : α) : myor
| inr (h : β) : myor
example : Prop → Prop → Type := myor
inductive myand (α β : Prop)
| intro (left : α) (right : β) : myand
/-
Some proofs work as expected.
-/
example (p q : Prop) : myand p q → p :=
begin
intro h,
cases h with hp hq,
exact hp,
end
example (p q : Prop) : myand p q → myand q p :=
begin
intro h,
cases h with hp hq,
split,
{ exact hq, },
{ exact hp, },
end
/-
However, the following statement does not type check. The issue is that `myand q r : Type`,
but `myand q r` is the second argument to `myand` in `myand p (myand q r)`. Both arguments of
`myand` are required to have type `Prop`.
-/
--example (p q r : Prop) : myand p (myand q r) → q := sorry
/-
One major difference between `Prop` and other type universes is that an inductive type in `Prop`
can only eliminate to other types in `Prop`. Put another way, if `α` is an inductive type in `Prop`
then the motive `C` of `α.rec_on` is also of type `Prop`.
-/
-- Here's a pukka application of `or.rec_on`.
example (p q : Prop) (h : or p q) : or q p := or.rec_on h (λ hp, or.inr hp) (λ hq, or.inl hq)
-- The following doesn't work.
-- example (p q : Prop) (h : or p q) : ℕ := or.rec_on h (λ hp, 5) (λ hq, 10)
-- But it does work with `myor` as `myor` is not a type in `Prop`.
example (p q : Prop) (h : myor p q) : ℕ := myor.rec_on h (λ hp, 5) (λ hq, 10)
example (p q : Prop) (h : and p q) : ℕ := and.rec_on h (λ hp hq, 5)
end inductive_propositions
section less_than_or_equal
open nat
/-!
We look at two defintions of `le`. The first is the standard defintion found in Lean. With this
definition, `le` is a family of inductive types.
-/
inductive le (a : ℕ) : ℕ → Prop
| refl : le a
| step : ∀ {b}, le b → le (succ b)
/-!
The definition above leads to an elimination principle. Suppose we have `h : x ≤ y` and we want
to prove `P y`, for some predicate `P`. We can do this by considering separately the two possible
ways in which `h` could have been constructed.
1. `h` could be the result of `refl`. In which case, `y` is `x` and we have to prove `P x`.
2. `h` could be the result of `step`. Then there is some `t` for which `y` is `succ t` and we know
`x ≤ t`. Thus, we need to prove for every `t : ℕ`, given `x ≤ t`, given `P t`, we have `P (succ t)`.
-/
/-!
Here's another definition `le'`.
-/
inductive le' : ℕ → ℕ → Prop
| refl : ∀ (a : ℕ), le' a a
| step : ∀ (a b : ℕ), le' a b → le' a (succ b)
example : le 5 5 := le.refl
example : le' 5 5 := le'.refl 5
local infix ` ≤ ` := le
#check @le.rec_on
#check eq.refl
#check @list.cons
example (a b c : ℕ) (hab : le a b) (hbc : le b c) : le a c := le.rec_on hbc hab
(λ d hbd had, by { apply le.step, exact had})
/-
It took me ages to figure out the simple proof below. This is because I was trying induction on
`hab` rather than `hbc`.
-/
lemma le_trans (a b c : ℕ) (hab : a ≤ b) (hbc : b ≤ c) : a ≤ c :=
begin
induction hbc with d hbd had,
{ exact hab, },
{ apply le.step, exact had, }
end
lemma le_rec (x : ℕ) (C : ℕ → Prop) (h1 : C x) (h2 : (∀ (y : ℕ), x ≤ y → C y → C y.succ)) :
∀ {n : ℕ}, x ≤ n → C n := λ n, (le.rec h1) h2
lemma le_rec' (x n : ℕ) (C : ℕ → Prop)
(h1 : C x) (h2 : (∀ (y : ℕ), x ≤ y → C y → C y.succ)) (h3 : x ≤ n) : C n :=
(λ n, (le.rec h1) h2) n h3
lemma le_trans' (a b c : ℕ) : a ≤ b → b ≤ c → a ≤ c :=
begin
let C := λ m, a ≤ m,
intro hab,
have h2 : ∀ (y : ℕ), b ≤ y → C y → C y.succ,
{ intros y hby hay,
apply le.step,
exact hay, },
apply le_rec b C hab h2,
end
lemma le_trans'' (a b c : ℕ) : a ≤ b → b ≤ c → a ≤ c :=
begin
let C := λ m, a ≤ m,
intros h1 h3,
have h2 : ∀ (y : ℕ), b ≤ y → C y → C y.succ,
{ intros y hby hay,
apply le.step,
exact hay, },
exact le_rec' b c C h1 h2 h3,
end
end less_than_or_equal
section trees
inductive Tree
| empty : Tree
| node : ℕ → Tree → Tree → Tree
open Tree
example : Tree := empty
def smalltree : Tree := node 3 (node 5 (node 7 empty empty) empty) (node 6 empty (node 2 empty empty))
namespace Tree
def sum (t : Tree) : ℕ :=
begin
refine Tree.rec_on t 0 _,
intros n ltree rtree ltree_sum rtree_sum,
exact ltree_sum + n + rtree_sum,
end
lemma sum_empty : sum empty = 0 := rfl
lemma sum_node (n : ℕ) (lt rt : Tree) : sum (node n lt rt) = (sum lt) + n + (sum rt) := rfl
def left_combine (t s : Tree) : Tree :=
begin
refine Tree.rec_on t s _,
intros n lt rt ilt irt,
exact node n ilt rt
end
lemma left_combine_empty (s : Tree) : left_combine empty s = s := rfl
lemma left_combine_node (n : ℕ) (lt rt s : Tree) :
left_combine (node n lt rt) s = node n (left_combine lt s) rt := rfl
def mytree : Tree := node 10 (node 50 empty empty) (node 20 (node 30 empty empty) empty)
lemma sum_add (t s : Tree) : sum (left_combine t s) = (sum t) + (sum s) :=
begin
refine Tree.rec_on t _ _,
{ rw [sum_empty, left_combine_empty, zero_add], },
{ intros n lt rt ilt irt, simp only [sum_node, left_combine_node, ilt], linarith, }
end
inductive sorted_tree : Tree → Prop
| srt_empty : sorted_tree empty
| srt_neither {n : ℕ} : sorted_tree (node n empty empty)
| srt_left {n m : ℕ} {lt rt : Tree} : m ≤ n → sorted_tree (node m lt rt)
→ sorted_tree (node n (node m lt rt) empty)
| srt_right {n m : ℕ} {lt rt : Tree} : n ≤ m → sorted_tree (node m lt rt)
→ sorted_tree (node n empty (node m lt rt))
| srt_both {n m p : ℕ} {ltm rtm ltp rtp : Tree} : m ≤ n → n ≤ p → sorted_tree (node m ltm rtm)
→ sorted_tree (node p ltp rtp) → sorted_tree (node n (node m ltm rtm) (node p ltp rtp))
open sorted_tree
example : sorted_tree (node 10 empty (node 20 empty empty)) :=
begin
refine srt_right dec_trivial _,
exact srt_neither,
end
def tree1 := node 10 (node 5 empty empty) (node 30 empty empty)
lemma test_srt1 : sorted_tree tree1 :=
by { refine srt_both dec_trivial dec_trivial _ _; exact srt_neither }
def tree2 := node 20 tree1 empty
lemma test_srt2 : sorted_tree tree2 :=
begin
dsimp [tree2,tree1],
refine srt_left dec_trivial _,
exact test_srt1,
end
def tree_insert : ℕ → Tree → Tree
| x empty := node x empty empty
| x (node a left right) := if x = a then node a left right else
if x <= a then node a (tree_insert x left) right else node a left (tree_insert x right)
def list_to_tree : list ℕ → Tree := list.foldr tree_insert empty
example : list_to_tree [1,2,3] = node 3 (node 2 (node 1 empty empty) empty) empty := rfl
def tree1' := list_to_tree [30,5,10]
example : tree1 = tree1' := rfl
def tree2' := list_to_tree [30,10,5,20]
#reduce tree2'
example (xs : list ℕ) (x : ℕ) : ∃ l r, list_to_tree (xs ++ [x]) = node x l r :=
begin
induction xs with y ys ih,
{ use [empty, empty], refl, },
{ unfold list_to_tree at *, dsimp,
rcases ih with ⟨l1, r1, ih⟩,
rw ih,
cases (lt_trichotomy x y) with h h,
{ use [l1, tree_insert y r1],
dsimp [tree_insert],
rw if_neg,
{ rw if_neg,
{ intro hle, apply lt_irrefl x, apply lt_of_lt_of_le h hle, }, },
{ intro heq, rw heq at h, exact (lt_irrefl x) h, }, },
{ cases h with h h,
{ use [l1, r1], dsimp [tree_insert], rw if_pos, symmetry, assumption, },
use [tree_insert y l1, r1],
dsimp [tree_insert],
rw if_neg,
{ rw if_pos,
{ exact le_of_lt h }, },
{ intro heq, rw heq at h, exact (lt_irrefl x) h, }, }, }
end
/- lemma sorted_of_list (t : Tree) (h : sorted_tree t) : ∃ xs, t = list_to_tree xs :=
begin
induction h,
{ use ([] : list ℕ), refl, },
case srt_neither : x { use ([x] : list ℕ), refl, },
case srt_left : n m l r hle hsrt ih
{ cases ih with xs ih,
use (xs ++ [m]),
dsimp [list_to_tree],
rw [ih, list.foldr_append],
},
{ },
{ },
end -/
end Tree
end trees
end exlean |
IT outsourcing is simply part of the way modern organizations do business today. This course will teach you the fundamental concepts of IT outsourcing and provide you with a framework to prepare for an outsourcing project.
Why Outsource and What to Outsource?
Hi everybody, and welcome to this course, IT Outsourcing - Preparing for an Outsourcing Initiative, where we are going to take a look at the things you need to do in order to prepare for an outsourcing project. My name is Tommy van Schaik, and I fill my days as an IT project manager working for the government and commercial organizations, advising and dealing with out sourcing initiatives. Outsourcing is just a part of the way modern organizations do business, and IT, because of the nature of the product, is a very suitable candidate for outsourcing. I believe that in this day and age, every IT professional should have at least a basic understanding of the outsourcing concepts in order to prepare themselves for the modern IT workplace. This course is the first course in the IT Outsourcing learning path, where we cover all phases of an IT outsourcing project, starting with this one, where we introduce the basic concepts and reasons behind outsourcing, the different outsourcing approaches you can use, and how to put together a good outsourcing strategy. By the end of this course, you will have a firm grasp of the outsourcing fundamentals, and you will have a good framework to get your outsourcing project off to a good start. So let's get started on this course, IT Outsourcing - Preparing for an Outsourcing Initiative, here at Pluralsight.
Hi everybody, and welcome back. We're going to continue this course on preparing an IT outsourcing initiative with this next module, Why Outsource and What to Outsource? In this module, we're going to look at the rationale behind outsourcing, and we're going to look at the different areas of IT that are suitable candidates for outsourcing initiatives. Having a good overview of the reasons behind outsourcing, and the different areas of IT that can be outsourced gives you a good foundation to understand some of the outsourcing-related decisions that organizations make. Alright, so first we'll look at the why behind outsourcing. Originally, outsourcing was almost exclusively about cutting costs, but nowadays organizations start outsourcing projects for a wide variety of organizational issues. We will discuss these issues, and how outsourcing could provide an answer to these problems that organizations are facing. Second, we will look at the different areas of IT and how suitable they are for outsourcing. As technology becomes better and better, more areas are easier to outsource. Especially now Infrastructure and Platform as a Service is really taking off, it is becoming way more attractive for organizations to look at putting some of their IT capabilities in a cloud environment. Alright then, let's get started on this module on the why and the what of outsourcing.
Hi everybody, and welcome back to another module in this course on preparing for an outsourcing initiative. We already covered the basic elements of why organizations outsource and what kind of IT capabilities are usually outsourced by organizations. Now let's take a look at the different strategies you can apply when outsourcing. We'll look at the different options, and explain the process of identifying the best possible solution for your organization. Alright, so the approach is going to be as follows. First, we're going to look at using a single vendor for your outsourcing, or perhaps you'll find it better to have multiple vendors involved in your outsourcing activities. Then we'll discuss the possibility of offshoring and nearshoring when you look beyond the borders of the country your company is situated in. Then we'll take a look at a cloud options, and how they impact the possibilities you have when it comes to outsourcing. Then we'll look at some less-common outsourcing models like crowdsourcing and microsourcing. And finally, and perhaps most importantly, we'll provide you with a structured approach to determine the right outsourcing model for your individual organization. Alright, so that's the plan, so let's get started on this module.
Hi everyone, and welcome back to another module in the course Preparing an Outsourcing Initiative. In the previous modules, we familiarized ourselves with the reasons to outsource, what kind of IT to outsource, and what kind of outsourcing options that are out there. In this module, we're going to present you with the framework that you can use to select and verify your outsourcing initiative, and we're going to be talking about how important it is to get support from all layers in the organization right from the start of the outsourcing project. So for selecting and validating your outsourcing initiative, you're going to need a good old-fashioned business case. And because outsourcing is such a multi-headed beast, it's important that you make it thorough, easy to understand, in such a way that you do not only convince yourself that this is a good idea, but also the people within the management, and even the people within the different IT departments of your organization. Then we're going to be talking about the buy in from the rest of the organization. If you are going to prepare for an outsourcing initiative, it's vital that you include everyone as early as possible within the project. This will create support and hugely improve the chances of turning your outsourcing project into a success. Alright then, let's get started on this module on Preparing for Outsourcing. |
(*
Copyright (C) 2017 M.A.L. Marques
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*)
(* type: work_mgga_c *)
$include "gga_c_gapc.mpl"
(* override definition of gap_C *)
gap_G := (rs, z, xt, par) -> RS_FACTOR^2/8 * xt^2/rs^2:
f_kcis := (rs, z, xt, xs0, xs1, ts0, ts1) ->
+ f_gap(rs, z, xt)
- xs0^2/(8*ts0) * (1 + z)/2 * f_gap(rs, 1, xs0)
- xs1^2/(8*ts1) * (1 - z)/2 * f_gap(rs, -1, xs1):
f := (rs, z, xt, xs0, xs1, ts0, ts1, us0, us1) ->
f_kcis(rs, z, xt, xs0, xs1, ts0, ts1):
|
State Before: n b : ℕ
l : List ℕ
hl : ∀ (x : ℕ), x ∈ l → x < b + 2
⊢ ofDigits (b + 2) l < (b + 2) ^ List.length l State After: case nil
n b : ℕ
l : List ℕ
hl✝ : ∀ (x : ℕ), x ∈ l → x < b + 2
hl : ∀ (x : ℕ), x ∈ [] → x < b + 2
⊢ ofDigits (b + 2) [] < (b + 2) ^ List.length []
case cons
n b : ℕ
l : List ℕ
hl✝ : ∀ (x : ℕ), x ∈ l → x < b + 2
hd : ℕ
tl : List ℕ
IH : (∀ (x : ℕ), x ∈ tl → x < b + 2) → ofDigits (b + 2) tl < (b + 2) ^ List.length tl
hl : ∀ (x : ℕ), x ∈ hd :: tl → x < b + 2
⊢ ofDigits (b + 2) (hd :: tl) < (b + 2) ^ List.length (hd :: tl) Tactic: induction' l with hd tl IH State Before: case nil
n b : ℕ
l : List ℕ
hl✝ : ∀ (x : ℕ), x ∈ l → x < b + 2
hl : ∀ (x : ℕ), x ∈ [] → x < b + 2
⊢ ofDigits (b + 2) [] < (b + 2) ^ List.length [] State After: no goals Tactic: simp [ofDigits] State Before: case cons
n b : ℕ
l : List ℕ
hl✝ : ∀ (x : ℕ), x ∈ l → x < b + 2
hd : ℕ
tl : List ℕ
IH : (∀ (x : ℕ), x ∈ tl → x < b + 2) → ofDigits (b + 2) tl < (b + 2) ^ List.length tl
hl : ∀ (x : ℕ), x ∈ hd :: tl → x < b + 2
⊢ ofDigits (b + 2) (hd :: tl) < (b + 2) ^ List.length (hd :: tl) State After: case cons
n b : ℕ
l : List ℕ
hl✝ : ∀ (x : ℕ), x ∈ l → x < b + 2
hd : ℕ
tl : List ℕ
IH : (∀ (x : ℕ), x ∈ tl → x < b + 2) → ofDigits (b + 2) tl < (b + 2) ^ List.length tl
hl : ∀ (x : ℕ), x ∈ hd :: tl → x < b + 2
⊢ ↑hd + (b + 2) * ofDigits (b + 2) tl < (b + 2) ^ List.length tl * (b + 2) Tactic: rw [ofDigits, List.length_cons, pow_succ] State Before: case cons
n b : ℕ
l : List ℕ
hl✝ : ∀ (x : ℕ), x ∈ l → x < b + 2
hd : ℕ
tl : List ℕ
IH : (∀ (x : ℕ), x ∈ tl → x < b + 2) → ofDigits (b + 2) tl < (b + 2) ^ List.length tl
hl : ∀ (x : ℕ), x ∈ hd :: tl → x < b + 2
⊢ ↑hd + (b + 2) * ofDigits (b + 2) tl < (b + 2) ^ List.length tl * (b + 2) State After: case cons
n b : ℕ
l : List ℕ
hl✝ : ∀ (x : ℕ), x ∈ l → x < b + 2
hd : ℕ
tl : List ℕ
IH : (∀ (x : ℕ), x ∈ tl → x < b + 2) → ofDigits (b + 2) tl < (b + 2) ^ List.length tl
hl : ∀ (x : ℕ), x ∈ hd :: tl → x < b + 2
this : (ofDigits (b + 2) tl + 1) * (b + 2) ≤ (b + 2) ^ List.length tl * (b + 2)
⊢ ↑hd + (b + 2) * ofDigits (b + 2) tl < (b + 2) ^ List.length tl * (b + 2) Tactic: have : (ofDigits (b + 2) tl + 1) * (b + 2) ≤ (b + 2) ^ tl.length * (b + 2) :=
mul_le_mul (IH fun x hx => hl _ (List.mem_cons_of_mem _ hx)) (by rfl) (by simp only [zero_le])
(Nat.zero_le _) State Before: case cons
n b : ℕ
l : List ℕ
hl✝ : ∀ (x : ℕ), x ∈ l → x < b + 2
hd : ℕ
tl : List ℕ
IH : (∀ (x : ℕ), x ∈ tl → x < b + 2) → ofDigits (b + 2) tl < (b + 2) ^ List.length tl
hl : ∀ (x : ℕ), x ∈ hd :: tl → x < b + 2
this : (ofDigits (b + 2) tl + 1) * (b + 2) ≤ (b + 2) ^ List.length tl * (b + 2)
⊢ ↑hd + (b + 2) * ofDigits (b + 2) tl < (b + 2) ^ List.length tl * (b + 2) State After: case cons
n b : ℕ
l : List ℕ
hl✝ : ∀ (x : ℕ), x ∈ l → x < b + 2
hd : ℕ
tl : List ℕ
IH : (∀ (x : ℕ), x ∈ tl → x < b + 2) → ofDigits (b + 2) tl < (b + 2) ^ List.length tl
hl : ∀ (x : ℕ), x ∈ hd :: tl → x < b + 2
this : (ofDigits (b + 2) tl + 1) * (b + 2) ≤ (b + 2) ^ List.length tl * (b + 2)
⊢ hd < b + 2 Tactic: suffices ↑hd < b + 2 by linarith State Before: case cons
n b : ℕ
l : List ℕ
hl✝ : ∀ (x : ℕ), x ∈ l → x < b + 2
hd : ℕ
tl : List ℕ
IH : (∀ (x : ℕ), x ∈ tl → x < b + 2) → ofDigits (b + 2) tl < (b + 2) ^ List.length tl
hl : ∀ (x : ℕ), x ∈ hd :: tl → x < b + 2
this : (ofDigits (b + 2) tl + 1) * (b + 2) ≤ (b + 2) ^ List.length tl * (b + 2)
⊢ hd < b + 2 State After: case cons
n b : ℕ
l : List ℕ
hl✝ : ∀ (x : ℕ), x ∈ l → x < b + 2
hd : ℕ
tl : List ℕ
IH : (∀ (x : ℕ), x ∈ tl → x < b + 2) → ofDigits (b + 2) tl < (b + 2) ^ List.length tl
hl : ∀ (x : ℕ), x ∈ hd :: tl → x < b + 2
this : (ofDigits (b + 2) tl + 1) * (b + 2) ≤ (b + 2) ^ List.length tl * (b + 2)
⊢ hd < b + 2 Tactic: norm_cast State Before: case cons
n b : ℕ
l : List ℕ
hl✝ : ∀ (x : ℕ), x ∈ l → x < b + 2
hd : ℕ
tl : List ℕ
IH : (∀ (x : ℕ), x ∈ tl → x < b + 2) → ofDigits (b + 2) tl < (b + 2) ^ List.length tl
hl : ∀ (x : ℕ), x ∈ hd :: tl → x < b + 2
this : (ofDigits (b + 2) tl + 1) * (b + 2) ≤ (b + 2) ^ List.length tl * (b + 2)
⊢ hd < b + 2 State After: no goals Tactic: exact hl hd (List.mem_cons_self _ _) State Before: n b : ℕ
l : List ℕ
hl✝ : ∀ (x : ℕ), x ∈ l → x < b + 2
hd : ℕ
tl : List ℕ
IH : (∀ (x : ℕ), x ∈ tl → x < b + 2) → ofDigits (b + 2) tl < (b + 2) ^ List.length tl
hl : ∀ (x : ℕ), x ∈ hd :: tl → x < b + 2
⊢ b + 2 ≤ b + 2 State After: no goals Tactic: rfl State Before: n b : ℕ
l : List ℕ
hl✝ : ∀ (x : ℕ), x ∈ l → x < b + 2
hd : ℕ
tl : List ℕ
IH : (∀ (x : ℕ), x ∈ tl → x < b + 2) → ofDigits (b + 2) tl < (b + 2) ^ List.length tl
hl : ∀ (x : ℕ), x ∈ hd :: tl → x < b + 2
⊢ 0 ≤ b + 2 State After: no goals Tactic: simp only [zero_le] State Before: n b : ℕ
l : List ℕ
hl✝ : ∀ (x : ℕ), x ∈ l → x < b + 2
hd : ℕ
tl : List ℕ
IH : (∀ (x : ℕ), x ∈ tl → x < b + 2) → ofDigits (b + 2) tl < (b + 2) ^ List.length tl
hl : ∀ (x : ℕ), x ∈ hd :: tl → x < b + 2
this✝ : (ofDigits (b + 2) tl + 1) * (b + 2) ≤ (b + 2) ^ List.length tl * (b + 2)
this : hd < b + 2
⊢ ↑hd + (b + 2) * ofDigits (b + 2) tl < (b + 2) ^ List.length tl * (b + 2) State After: no goals Tactic: linarith |
/-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
Evaluate expressions in the language of (semi-)rings.
Based on http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf .
-/
import algebra.group_power tactic.norm_num
namespace tactic
namespace ring
def horner {α} [comm_semiring α] (a x : α) (n : ℕ) (b : α) := a * x ^ n + b
meta structure cache :=
(α : expr)
(univ : level)
(comm_semiring_inst : expr)
meta def mk_cache (e : expr) : tactic cache :=
do α ← infer_type e,
c ← mk_app ``comm_semiring [α] >>= mk_instance,
u ← mk_meta_univ,
infer_type α >>= unify (expr.sort (level.succ u)),
u ← get_univ_assignment u,
return ⟨α, u, c⟩
meta def cache.cs_app (c : cache) (n : name) : list expr → expr :=
(@expr.const tt n [c.univ] c.α c.comm_semiring_inst).mk_app
meta def cache.mk_app (c : cache) (n inst : name) (l : list expr) : tactic expr :=
do m ← mk_instance ((expr.const inst [c.univ] : expr) c.α),
return $ (@expr.const tt n [c.univ] c.α m).mk_app l
meta inductive horner_expr : Type
| const (e : expr) : horner_expr
| xadd (e : expr) (a : horner_expr) (x : expr) (n : expr × ℕ) (b : horner_expr) : horner_expr
meta def horner_expr.e : horner_expr → expr
| (horner_expr.const e) := e
| (horner_expr.xadd e _ _ _ _) := e
meta instance : has_coe horner_expr expr := ⟨horner_expr.e⟩
meta def horner_expr.xadd' (c : cache) (a : horner_expr) (x : expr) (n : expr × ℕ) (b : horner_expr): horner_expr :=
horner_expr.xadd (c.cs_app ``horner [a, x, n.1, b]) a x n b
open horner_expr
meta def horner_expr.to_string : horner_expr → string
| (const e) := to_string e
| (xadd e a x (_, n) b) :=
"(" ++ a.to_string ++ ") * (" ++ to_string x ++ ")^"
++ to_string n ++ " + " ++ b.to_string
meta def horner_expr.pp : horner_expr → tactic format
| (const e) := pp e
| (xadd e a x (_, n) b) := do
pa ← a.pp, pb ← b.pp, px ← pp x,
return $ "(" ++ pa ++ ") * (" ++ px ++ ")^" ++ to_string n ++ " + " ++ pb
meta instance : has_to_tactic_format horner_expr := ⟨horner_expr.pp⟩
meta def horner_expr.refl_conv (e : horner_expr) : tactic (horner_expr × expr) :=
do p ← mk_eq_refl e, return (e, p)
theorem zero_horner {α} [comm_semiring α] (x n b) :
@horner α _ 0 x n b = b :=
by simp [horner]
theorem horner_horner {α} [comm_semiring α] (a₁ x n₁ n₂ b n')
(h : n₁ + n₂ = n') :
@horner α _ (horner a₁ x n₁ 0) x n₂ b = horner a₁ x n' b :=
by simp [h.symm, horner, pow_add, mul_assoc]
meta def eval_horner (c : cache) : horner_expr → expr → expr × ℕ → horner_expr → tactic (horner_expr × expr)
| ha@(const a) x n b :=
if a.to_nat = some 0 then
return (b, c.cs_app ``zero_horner [x, n.1, b])
else (xadd' c ha x n b).refl_conv
| ha@(xadd a a₁ x₁ n₁ b₁) x n b :=
if x₁ = x ∧ b₁.e.to_nat = some 0 then do
(n', h) ← mk_app ``has_add.add [n₁.1, n.1] >>= norm_num,
return (xadd' c a₁ x (n', n₁.2 + n.2) b,
c.cs_app ``horner_horner [a₁, x, n₁.1, n.1, b, n', h])
else (xadd' c ha x n b).refl_conv
theorem const_add_horner {α} [comm_semiring α] (k a x n b b') (h : k + b = b') :
k + @horner α _ a x n b = horner a x n b' :=
by simp [h.symm, horner]
theorem horner_add_const {α} [comm_semiring α] (a x n b k b') (h : b + k = b') :
@horner α _ a x n b + k = horner a x n b' :=
by simp [h.symm, horner]
theorem horner_add_horner_lt {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ k a' b')
(h₁ : n₁ + k = n₂) (h₂ : (a₁ + horner a₂ x k 0 : α) = a') (h₃ : b₁ + b₂ = b') :
@horner α _ a₁ x n₁ b₁ + horner a₂ x n₂ b₂ = horner a' x n₁ b' :=
by simp [h₂.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]
theorem horner_add_horner_gt {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ k a' b')
(h₁ : n₂ + k = n₁) (h₂ : (horner a₁ x k 0 + a₂ : α) = a') (h₃ : b₁ + b₂ = b') :
@horner α _ a₁ x n₁ b₁ + horner a₂ x n₂ b₂ = horner a' x n₂ b' :=
by simp [h₂.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]
theorem horner_add_horner_eq {α} [comm_semiring α] (a₁ x n b₁ a₂ b₂ a' b' t)
(h₁ : a₁ + a₂ = a') (h₂ : b₁ + b₂ = b') (h₃ : horner a' x n b' = t) :
@horner α _ a₁ x n b₁ + horner a₂ x n b₂ = t :=
by simp [h₃.symm, h₂.symm, h₁.symm, horner, add_mul, mul_comm]
meta def eval_add (c : cache) : horner_expr → horner_expr → tactic (horner_expr × expr)
| (const e₁) (const e₂) := do
(e, p) ← mk_app ``has_add.add [e₁, e₂] >>= norm_num,
return (const e, p)
| he₁@(const e₁) he₂@(xadd e₂ a x n b) :=
if e₁.to_nat = some 0 then do
p ← mk_app ``zero_add [e₂],
return (he₂, p)
else do
(b', h) ← eval_add he₁ b,
return (xadd' c a x n b',
c.cs_app ``const_add_horner [e₁, a, x, n.1, b, b', h])
| he₁@(xadd e₁ a x n b) he₂@(const e₂) :=
if e₂.to_nat = some 0 then do
p ← mk_app ``add_zero [e₁],
return (he₁, p)
else do
(b', h) ← eval_add b he₂,
return (xadd' c a x n b',
c.cs_app ``horner_add_const [a, x, n.1, b, e₂, b', h])
| he₁@(xadd e₁ a₁ x₁ n₁ b₁) he₂@(xadd e₂ a₂ x₂ n₂ b₂) :=
if expr.lex_lt x₁ x₂ then do
(b', h) ← eval_add b₁ he₂,
return (xadd' c a₁ x₁ n₁ b',
c.cs_app ``horner_add_const [a₁, x₁, n₁.1, b₁, e₂, b', h])
else if x₁ ≠ x₂ then do
(b', h) ← eval_add he₁ b₂,
return (xadd' c a₂ x₂ n₂ b',
c.cs_app ``const_add_horner [e₁, a₂, x₂, n₂.1, b₂, b', h])
else if n₁.2 < n₂.2 then do
let k := n₂.2 - n₁.2,
ek ← expr.of_nat (expr.const `nat []) k,
(_, h₁) ← mk_app ``has_add.add [n₁.1, ek] >>= norm_num,
α0 ← expr.of_nat c.α 0,
(a', h₂) ← eval_add a₁ (xadd' c a₂ x₁ (ek, k) (const α0)),
(b', h₃) ← eval_add b₁ b₂,
return (xadd' c a' x₁ n₁ b',
c.cs_app ``horner_add_horner_lt [a₁, x₁, n₁.1, b₁, a₂, n₂.1, b₂, ek, a', b', h₁, h₂, h₃])
else if n₁ ≠ n₂ then do
let k := n₁.2 - n₂.2,
ek ← expr.of_nat (expr.const `nat []) k,
(_, h₁) ← mk_app ``has_add.add [n₂.1, ek] >>= norm_num,
α0 ← expr.of_nat c.α 0,
(a', h₂) ← eval_add (xadd' c a₁ x₁ (ek, k) (const α0)) a₂,
(b', h₃) ← eval_add b₁ b₂,
return (xadd' c a' x₁ n₂ b',
c.cs_app ``horner_add_horner_gt [a₁, x₁, n₁.1, b₁, a₂, n₂.1, b₂, ek, a', b', h₁, h₂, h₃])
else do
(a', h₁) ← eval_add a₁ a₂,
(b', h₂) ← eval_add b₁ b₂,
(t, h₃) ← eval_horner c a' x₁ n₁ b',
return (t, c.cs_app ``horner_add_horner_eq
[a₁, x₁, n₁.1, b₁, a₂, b₂, a', b', t, h₁, h₂, h₃])
theorem horner_neg {α} [comm_ring α] (a x n b a' b')
(h₁ : -a = a') (h₂ : -b = b') :
-@horner α _ a x n b = horner a' x n b' :=
by simp [h₂.symm, h₁.symm, horner]
meta def eval_neg (c : cache) : horner_expr → tactic (horner_expr × expr)
| (const e) := do
(e', p) ← mk_app ``has_neg.neg [e] >>= norm_num,
return (const e', p)
| (xadd e a x n b) := do
(a', h₁) ← eval_neg a,
(b', h₂) ← eval_neg b,
p ← c.mk_app ``horner_neg ``comm_ring [a, x, n.1, b, a', b', h₁, h₂],
return (xadd' c a' x n b', p)
theorem horner_const_mul {α} [comm_semiring α] (c a x n b a' b')
(h₁ : c * a = a') (h₂ : c * b = b') :
c * @horner α _ a x n b = horner a' x n b' :=
by simp [h₂.symm, h₁.symm, horner, mul_add, mul_assoc]
theorem horner_mul_const {α} [comm_semiring α] (a x n b c a' b')
(h₁ : a * c = a') (h₂ : b * c = b') :
@horner α _ a x n b * c = horner a' x n b' :=
by simp [h₂.symm, h₁.symm, horner, add_mul, mul_right_comm]
meta def eval_const_mul (c : cache) (k : expr) :
horner_expr → tactic (horner_expr × expr)
| (const e) := do
(e', p) ← mk_app ``has_mul.mul [k, e] >>= norm_num,
return (const e', p)
| (xadd e a x n b) := do
(a', h₁) ← eval_const_mul a,
(b', h₂) ← eval_const_mul b,
return (xadd' c a' x n b',
c.cs_app ``horner_const_mul [k, a, x, n.1, b, a', b', h₁, h₂])
theorem horner_mul_horner_zero {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ aa t)
(h₁ : @horner α _ a₁ x n₁ b₁ * a₂ = aa)
(h₂ : horner aa x n₂ 0 = t) :
horner a₁ x n₁ b₁ * horner a₂ x n₂ 0 = t :=
by rw [← h₂, ← h₁];
simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc]
theorem horner_mul_horner {α} [comm_semiring α]
(a₁ x n₁ b₁ a₂ n₂ b₂ aa haa ab bb t)
(h₁ : @horner α _ a₁ x n₁ b₁ * a₂ = aa)
(h₂ : horner aa x n₂ 0 = haa)
(h₃ : a₁ * b₂ = ab) (h₄ : b₁ * b₂ = bb)
(H : haa + horner ab x n₁ bb = t) :
horner a₁ x n₁ b₁ * horner a₂ x n₂ b₂ = t :=
by rw [← H, ← h₂, ← h₁, ← h₃, ← h₄];
simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc]
meta def eval_mul (c : cache) : horner_expr → horner_expr → tactic (horner_expr × expr)
| (const e₁) (const e₂) := do
(e', p) ← mk_app ``has_mul.mul [e₁, e₂] >>= norm_num,
return (const e', p)
| (const e₁) e₂ :=
match e₁.to_nat with
| (some 0) := do
α0 ← expr.of_nat c.α 0,
p ← mk_app ``zero_mul [e₂],
return (const α0, p)
| (some 1) := do
p ← mk_app ``one_mul [e₂],
return (e₂, p)
| _ := eval_const_mul c e₁ e₂
end
| e₁ he₂@(const e₂) := do
p₁ ← mk_app ``mul_comm [e₁, e₂],
(e', p₂) ← eval_mul he₂ e₁,
p ← mk_eq_trans p₁ p₂, return (e', p)
| he₁@(xadd e₁ a₁ x₁ n₁ b₁) he₂@(xadd e₂ a₂ x₂ n₂ b₂) :=
if expr.lex_lt x₁ x₂ then do
(a', h₁) ← eval_mul a₁ he₂,
(b', h₂) ← eval_mul b₁ he₂,
return (xadd' c a' x₁ n₁ b',
c.cs_app ``horner_mul_const [a₁, x₁, n₁.1, b₁, e₂, a', b', h₁, h₂])
else if x₁ ≠ x₂ then do
(a', h₁) ← eval_mul he₁ a₂,
(b', h₂) ← eval_mul he₁ b₂,
return (xadd' c a' x₂ n₂ b',
c.cs_app ``horner_const_mul [e₁, a₂, x₂, n₂.1, b₂, a', b', h₁, h₂])
else do
(aa, h₁) ← eval_mul he₁ a₂,
α0 ← expr.of_nat c.α 0,
(haa, h₂) ← eval_horner c aa x₁ n₂ (const α0),
if b₂.e.to_nat = some 0 then
return (haa, c.cs_app ``horner_mul_horner_zero
[a₁, x₁, n₁.1, b₁, a₂, n₂.1, aa, haa, h₁, h₂])
else do
(ab, h₃) ← eval_mul a₁ b₂,
(bb, h₄) ← eval_mul b₁ b₂,
(t, H) ← eval_add c haa (xadd' c ab x₁ n₁ bb),
return (t, c.cs_app ``horner_mul_horner
[a₁, x₁, n₁.1, b₁, a₂, n₂.1, b₂, aa, haa, ab, bb, t, h₁, h₂, h₃, h₄, H])
theorem horner_pow {α} [comm_semiring α] (a x n m n' a')
(h₁ : n * m = n') (h₂ : a ^ m = a') :
@horner α _ a x n 0 ^ m = horner a' x n' 0 :=
by simp [h₁.symm, h₂.symm, horner, mul_pow, pow_mul]
meta def eval_pow (c : cache) : horner_expr → expr × ℕ → tactic (horner_expr × expr)
| e (_, 0) := do
α1 ← expr.of_nat c.α 1,
p ← mk_app ``pow_zero [e],
return (const α1, p)
| e (_, 1) := do
p ← mk_app ``pow_one [e],
return (e, p)
| (const e) (e₂, m) := do
(e', p) ← mk_app ``monoid.pow [e, e₂] >>= norm_num.derive,
return (const e', p)
| he@(xadd e a x n b) m :=
let N : expr := expr.const `nat [] in
match b.e.to_nat with
| some 0 := do
(n', h₁) ← mk_app ``has_mul.mul [n.1, m.1] >>= norm_num,
(a', h₂) ← eval_pow a m,
α0 ← expr.of_nat c.α 0,
return (xadd' c a' x (n', n.2 * m.2) (const α0),
c.cs_app ``horner_pow [a, x, n.1, m.1, n', a', h₁, h₂])
| _ := do
e₂ ← expr.of_nat N (m.2-1),
l ← mk_app ``monoid.pow [e, e₂],
(tl, hl) ← eval_pow he (e₂, m.2-1),
(t, p₂) ← eval_mul c tl he,
hr ← mk_eq_refl e,
p₂ ← c.mk_app ``norm_num.subst_into_prod ``has_mul [l, e, tl, e, t, hl, hr, p₂],
p₁ ← mk_app ``pow_succ' [e, e₂],
p ← mk_eq_trans p₁ p₂,
return (t, p)
end
theorem horner_atom {α} [comm_semiring α] (x : α) : x = horner 1 x 1 0 :=
by simp [horner]
meta def eval_atom (c : cache) (e : expr) : tactic (horner_expr × expr) :=
do α0 ← expr.of_nat c.α 0,
α1 ← expr.of_nat c.α 1,
n1 ← expr.of_nat (expr.const `nat []) 1,
return (xadd' c (const α1) e (n1, 1) (const α0), c.cs_app ``horner_atom [e])
lemma subst_into_pow {α} [monoid α] (l r tl tr t)
(prl : (l : α) = tl) (prr : (r : ℕ) = tr) (prt : tl ^ tr = t) : l ^ r = t :=
by simp [prl, prr, prt]
lemma unfold_sub {α} [add_group α] (a b c : α)
(h : a + -b = c) : a - b = c := h
lemma unfold_div {α} [division_ring α] (a b c : α)
(h : a * b⁻¹ = c) : a / b = c := h
meta def eval (c : cache) : expr → tactic (horner_expr × expr)
| `(%%e₁ + %%e₂) := do
(e₁', p₁) ← eval e₁,
(e₂', p₂) ← eval e₂,
(e', p') ← eval_add c e₁' e₂',
p ← c.mk_app ``norm_num.subst_into_sum ``has_add [e₁, e₂, e₁', e₂', e', p₁, p₂, p'],
return (e', p)
| `(%%e₁ - %%e₂) := do
e₂' ← mk_app ``has_neg.neg [e₂],
e ← mk_app ``has_add.add [e₁, e₂'],
(e', p) ← eval e,
p' ← c.mk_app ``unfold_sub ``add_group [e₁, e₂, e', p],
return (e', p')
| `(- %%e) := do
(e₁, p₁) ← eval e,
(e₂, p₂) ← eval_neg c e₁,
p ← c.mk_app ``norm_num.subst_into_neg ``has_neg [e, e₁, e₂, p₁, p₂],
return (e₂, p)
| `(%%e₁ * %%e₂) := do
(e₁', p₁) ← eval e₁,
(e₂', p₂) ← eval e₂,
(e', p') ← eval_mul c e₁' e₂',
p ← c.mk_app ``norm_num.subst_into_prod ``has_mul [e₁, e₂, e₁', e₂', e', p₁, p₂, p'],
return (e', p)
| e@`(has_inv.inv %%_) := (do
(e', p) ← norm_num.derive e,
e'.to_rat,
return (const e', p)) <|> eval_atom c e
| `(%%e₁ / %%e₂) := do
e₂' ← mk_app ``has_inv.inv [e₂],
e ← mk_app ``has_mul.mul [e₁, e₂'],
(e', p) ← eval e,
p' ← c.mk_app ``unfold_div ``division_ring [e₁, e₂, e', p],
return (e', p')
| e@`(@has_pow.pow _ _ %%P %%e₁ %%e₂) := do
(e₂', p₂) ← eval e₂,
match e₂'.e.to_nat, P with
| some k, `(monoid.has_pow) := do
(e₁', p₁) ← eval e₁,
(e', p') ← eval_pow c e₁' (e₂, k),
p ← c.mk_app ``subst_into_pow ``monoid [e₁, e₂, e₁', e₂', e', p₁, p₂, p'],
return (e', p)
| some k, `(nat.has_pow) := do
(e₁', p₁) ← eval e₁,
(e', p') ← eval_pow c e₁' (e₂, k),
p₃ ← c.mk_app ``subst_into_pow ``monoid [e₁, e₂, e₁', e₂', e', p₁, p₂, p'],
p₄ ← mk_app ``nat.pow_eq_pow [e₁, e₂] >>= mk_eq_symm,
p ← mk_eq_trans p₄ p₃,
return (e', p)
| _, _ := eval_atom c e
end
| e := match e.to_nat with
| some n := (const e).refl_conv
| none := eval_atom c e
end
meta def eval' (c : cache) (e : expr) : tactic (expr × expr) :=
do (e', p) ← eval c e, return (e', p)
theorem horner_def' {α} [comm_semiring α] (a x n b) : @horner α _ a x n b = x ^ n * a + b :=
by simp [horner, mul_comm]
theorem mul_assoc_rev {α} [semigroup α] (a b c : α) : a * (b * c) = a * b * c :=
by simp [mul_assoc]
theorem pow_add_rev {α} [monoid α] (a b : α) (m n : ℕ) : a ^ m * a ^ n = a ^ (m + n) :=
by simp [pow_add]
theorem pow_add_rev_right {α} [monoid α] (a b : α) (m n : ℕ) : b * a ^ m * a ^ n = b * a ^ (m + n) :=
by simp [pow_add, mul_assoc]
theorem add_neg_eq_sub {α} [add_group α] (a b : α) : a + -b = a - b := rfl
@[derive has_reflect]
inductive normalize_mode | raw | SOP | horner
meta def normalize (mode := normalize_mode.horner) (e : expr) : tactic (expr × expr) := do
pow_lemma ← simp_lemmas.mk.add_simp ``pow_one,
let lemmas := match mode with
| normalize_mode.SOP :=
[``horner_def', ``add_zero, ``mul_one, ``mul_add, ``mul_sub,
``mul_assoc_rev, ``pow_add_rev, ``pow_add_rev_right,
``mul_neg_eq_neg_mul_symm, ``add_neg_eq_sub]
| normalize_mode.horner :=
[``horner.equations._eqn_1, ``add_zero, ``one_mul, ``pow_one,
``neg_mul_eq_neg_mul_symm, ``add_neg_eq_sub]
| _ := []
end,
lemmas ← lemmas.mfoldl simp_lemmas.add_simp simp_lemmas.mk,
(_, e', pr) ← ext_simplify_core () {}
simp_lemmas.mk (λ _, failed) (λ _ _ _ _ e, do
c ← mk_cache e,
(new_e, pr) ← match mode with
| normalize_mode.raw := eval' c
| normalize_mode.horner := trans_conv (eval' c) (simplify lemmas [])
| normalize_mode.SOP :=
trans_conv (eval' c) $
trans_conv (simplify lemmas []) $
simp_bottom_up' (λ e, norm_num e <|> pow_lemma.rewrite e)
end e,
guard (¬ new_e =ₐ e),
return ((), new_e, some pr, ff))
(λ _ _ _ _ _, failed) `eq e,
return (e', pr)
end ring
namespace interactive
open interactive interactive.types lean.parser
open tactic.ring
local postfix `?`:9001 := optional
/-- Tactic for solving equations in the language of rings.
This version of `ring` fails if the target is not an equality
that is provable by the axioms of commutative (semi)rings. -/
meta def ring1 : tactic unit :=
do `(%%e₁ = %%e₂) ← target,
c ← mk_cache e₁,
(e₁', p₁) ← eval c e₁,
(e₂', p₂) ← eval c e₂,
is_def_eq e₁' e₂',
p ← mk_eq_symm p₂ >>= mk_eq_trans p₁,
tactic.exact p
meta def ring.mode : lean.parser ring.normalize_mode :=
with_desc "(SOP|raw|horner)?" $
do mode ← ident?, match mode with
| none := return ring.normalize_mode.horner
| some `horner := return ring.normalize_mode.horner
| some `SOP := return ring.normalize_mode.SOP
| some `raw := return ring.normalize_mode.raw
| _ := failed
end
/-- Tactic for solving equations in the language of rings.
Attempts to prove the goal outright if there is no `at`
specifier and the target is an equality, but if this
fails it falls back to rewriting all ring expressions
into a normal form. When writing a normal form,
`ring SOP` will use sum-of-products form instead of horner form. -/
meta def ring (SOP : parse ring.mode) (loc : parse location) : tactic unit :=
match loc with
| interactive.loc.ns [none] := ring1
| _ := failed
end <|>
do ns ← loc.get_locals,
tt ← tactic.replace_at (normalize SOP) ns loc.include_goal
| fail "ring failed to simplify",
when loc.include_goal $ try tactic.reflexivity
end interactive
end tactic
|
[STATEMENT]
lemma cis_Arg: "z \<noteq> 0 \<Longrightarrow> cis (Arg z) = sgn z"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. z \<noteq> 0 \<Longrightarrow> cis (Arg z) = sgn z
[PROOF STEP]
by (simp add: Arg_correct) |
lemma convex_imp_simply_connected: fixes S :: "'a::real_normed_vector set" shows "convex S \<Longrightarrow> simply_connected S" |
module Generic.Lib.Reflection.Core where
open import Agda.Builtin.Reflection using (withNormalisation; Relevance; Visibility; clause) public
open import Reflection
renaming (visible to expl; hidden to impl; instance′ to inst;
relevant to rel; irrelevant to irr; pi to absPi; lam to absLam; def to appDef)
hiding (Arg-info; var; con; meta; visibility; relevance; _≟_; return; _>>=_; _>>_) public
open import Reflection.Argument.Information using (ArgInfo; visibility; relevance) public
import Reflection.Name
open Term using () renaming (var to appVar; con to appCon; meta to appMeta) public
open Pattern using () renaming (var to patVar; con to patCon) public
open Literal using () renaming (meta to litMeta) public
open Sort public
open import Generic.Lib.Intro
open import Generic.Lib.Equality.Propositional
open import Generic.Lib.Decidable
open import Generic.Lib.Category
open import Generic.Lib.Data.Nat
open import Generic.Lib.Data.String
open import Generic.Lib.Data.Maybe
open import Generic.Lib.Data.Product
open import Generic.Lib.Data.List
open import Data.Vec using (toList)
open import Data.Vec.N-ary using (N-ary; curryⁿ)
infixr 5 _‵→_
infixl 3 _·_
listCurryⁿ : ∀ {α β} {A : Set α} {B : Set β} n -> (List A -> B) -> N-ary n A B
listCurryⁿ n f = curryⁿ {n = n} (f ∘ toList)
named : String -> String
named s = if s == "_" then "x" else s
record Reify {α} (A : Set α) : Set α where
field reify : A -> Term
macro
reflect : A -> Term -> TC _
reflect = unify ∘ reify
open Reify {{...}} public
pattern pureVar n = appVar n []
pattern pureCon c = appCon c []
pattern pureDef f = appDef f []
pattern pureMeta m = appMeta m []
{-# DISPLAY appVar i [] = pureVar i #-}
{-# DISPLAY appCon c [] = pureCon c #-}
{-# DISPLAY appDef f [] = pureDef f #-}
{-# DISPLAY appMeta m [] = pureMeta m #-}
pattern explInfo r = arg-info expl r
pattern implInfo r = arg-info impl r
pattern instInfo r = arg-info inst r
{-# DISPLAY arg-info expl r = explInfo r #-}
{-# DISPLAY arg-info impl r = implInfo r #-}
{-# DISPLAY arg-info inst r = instInfo r #-}
pattern explRelInfo = explInfo rel
pattern explIrrInfo = explInfo irr
pattern implRelInfo = implInfo rel
pattern implIrrInfo = implInfo irr
pattern instRelInfo = instInfo rel
pattern instIrrInfo = instInfo irr
{-# DISPLAY explInfo rel = explRelInfo #-}
{-# DISPLAY explInfo irr = explIrrInfo #-}
{-# DISPLAY implInfo rel = implRelInfo #-}
{-# DISPLAY implInfo irr = implIrrInfo #-}
{-# DISPLAY instInfo rel = instRelInfo #-}
{-# DISPLAY instInfo irr = instIrrInfo #-}
pattern explArg r x = arg (explInfo r) x
pattern implArg r x = arg (implInfo r) x
pattern instArg r x = arg (instInfo r) x
{-# DISPLAY arg (explInfo r) = explArg r #-}
{-# DISPLAY arg (implInfo r) = implArg r #-}
{-# DISPLAY arg (instInfo r) = instArg r #-}
pattern explRelArg x = explArg rel x
pattern implRelArg x = implArg rel x
pattern instRelArg x = instArg rel x
{-# DISPLAY explArg rel x = explRelArg x #-}
{-# DISPLAY implArg rel x = implRelArg x #-}
{-# DISPLAY instArg rel x = instRelArg x #-}
pattern pi s a b = absPi a (abs s b)
{-# DISPLAY absPi a (abs s b) = pi s a b #-}
pattern explPi r s a b = pi s (explArg r a) b
pattern implPi r s a b = pi s (implArg r a) b
pattern instPi r s a b = pi s (instArg r a) b
{-# DISPLAY pi (explArg r a) s b = explPi r s a b #-}
{-# DISPLAY pi (implArg r a) s b = implPi r s a b #-}
{-# DISPLAY pi (instArg r a) s b = instPi r s a b #-}
pattern explRelPi s a b = explPi rel a s b
pattern explIrrPi s a b = explPi irr a s b
pattern implRelPi s a b = implPi rel a s b
pattern implIrrPi s a b = implPi irr a s b
pattern instRelPi s a b = instPi rel a s b
pattern instIrrPi s a b = instPi irr a s b
{-# DISPLAY explPi rel a s b = explRelPi s a b #-}
{-# DISPLAY explPi irr a s b = explIrrPi s a b #-}
{-# DISPLAY implPi rel a s b = implRelPi s a b #-}
{-# DISPLAY implPi irr a s b = implIrrPi s a b #-}
{-# DISPLAY instPi rel a s b = instRelPi s a b #-}
{-# DISPLAY instPi irr a s b = instIrrPi s a b #-}
pattern lam v s t = absLam v (abs s t)
{-# DISPLAY absLam v (abs s t) = lam v s t #-}
pattern explLam s t = lam expl s t
pattern implLam s t = lam impl s t
pattern instLam s t = lam inst s t
{-# DISPLAY lam expl s t = explLam s t #-}
{-# DISPLAY lam impl s t = implLam s t #-}
{-# DISPLAY lam inst s t = instLam s t #-}
pattern _‵→_ a b = pi "_" (explRelArg a) b
-- No longer parses for whatever reason.
-- {-# DISPLAY pi "_" (explRelArg a) b = a ‵→ b #-}
mutual
<_>_ : ∀ {α} -> Relevance -> Set α -> Set α
<_>_ = flip RelValue
data RelValue {α} (A : Set α) : Relevance -> Set α where
relv : A -> < rel > A
irrv : .A -> < irr > A
elimRelValue : ∀ {r α π} {A : Set α}
-> (P : ∀ {r} -> < r > A -> Set π)
-> (∀ x -> P (relv x))
-> (∀ .x -> P (irrv x))
-> (x : < r > A)
-> P x
elimRelValue P f g (relv x) = f x
elimRelValue P f g (irrv x) = g x
unrelv : ∀ {α} {A : Set α} -> < rel > A -> A
unrelv (relv x) = x
-- Is it possible to handle this in some other way that doesn't require a postulate?
-- See the `appRel` function below. Or is the postulate fine?
postulate
.unirrv : ∀ {α} {A : Set α} -> < irr > A -> A
<_>_~>_ : ∀ {α β} -> Relevance -> Set α -> Set β -> Set (α ⊔ β)
< rel > A ~> B = A -> B
< irr > A ~> B = .A -> B
lamRel : ∀ {r α β} {A : Set α} {B : Set β} -> (< r > A -> B) -> < r > A ~> B
lamRel {rel} f = λ x -> f (relv x)
lamRel {irr} f = λ x -> f (irrv x)
-- The laziness is intentional.
appRel : ∀ {r α β} {A : Set α} {B : Set β} -> (< r > A ~> B) -> < r > A -> B
appRel {rel} f rx = f (unrelv rx)
appRel {irr} f rx = f (unirrv rx)
Pi : ∀ {α β} i -> (A : Set α) -> (< relevance i > A -> Set β) -> Set (α ⊔ β)
Pi explRelInfo A B = (x : A) -> B (relv x)
Pi explIrrInfo A B = . (x : A) -> B (irrv x)
Pi implRelInfo A B = {x : A} -> B (relv x)
Pi implIrrInfo A B = . {x : A} -> B (irrv x)
Pi instRelInfo A B = {{x : A}} -> B (relv x)
Pi instIrrInfo A B = .{{x : A}} -> B (irrv x)
lamPi : ∀ {α β} {A : Set α} i {B : < relevance i > A -> Set β} -> (∀ x -> B x) -> Pi i A B
lamPi explRelInfo f = λ x -> f (relv x)
lamPi explIrrInfo f = λ x -> f (irrv x)
lamPi implRelInfo f = f _
lamPi implIrrInfo f = f _
lamPi instRelInfo f = f _
lamPi instIrrInfo f = f _
appPi : ∀ {α β} {A : Set α} i {B : < relevance i > A -> Set β} -> Pi i A B -> ∀ x -> B x
appPi explRelInfo f (relv x) = f x
appPi explIrrInfo f (irrv x) = f x
appPi implRelInfo y (relv x) = y
appPi implIrrInfo y (irrv x) = y
appPi instRelInfo y (relv x) = y {{x}}
appPi instIrrInfo y (irrv x) = y {{x}}
RelEq : ∀ {α} -> Relevance -> Set α -> Set α
RelEq rel A = Eq A
RelEq irr A = ⊤
vis : {A : Set} -> (A -> List (Arg Term) -> Term) -> A -> List Term -> Term
vis k x = k x ∘ map explRelArg
vis# : ∀ {A : Set} n -> (A -> List (Arg Term) -> Term) -> A -> N-ary n Term Term
vis# n k = listCurryⁿ n ∘ vis k
isRelevant : Relevance -> Bool
isRelevant rel = true
isRelevant irr = false
argInfo : ∀ {α} {A : Set α} -> Arg A -> _
argInfo (arg i x) = i
argVal : ∀ {α} {A : Set α} -> Arg A -> A
argVal (arg i x) = x
unExpl : ∀ {α} {A : Set α} -> Arg A -> Maybe A
unExpl (explArg r x) = just x
unExpl _ = nothing
absName : ∀ {α} {A : Set α} -> Abs A -> String
absName (abs s x) = s
absVal : ∀ {α} {A : Set α} -> Abs A -> A
absVal (abs s x) = x
patVars : List String -> List (Arg Pattern)
patVars = map (explRelArg ∘ patVar ∘ named)
record Data {α} (A : Set α) : Set α where
no-eta-equality
constructor packData
field
dataName : Name
parsTele : Type
indsTele : Type
consTypes : List A
consNames : All (const Name) consTypes
open Data public
instance
NameEq : Eq Name
NameEq = viaBase Reflection.Name._≟_
EqRelValue : ∀ {α r} {A : Set α} {{aEq : RelEq r A}} -> Eq (< r > A)
EqRelValue {A = A} {{aEq}} = record
{ _≟_ = go
} where
relv-inj : {x y : A} -> relv x ≡ relv y -> x ≡ y
relv-inj refl = refl
go : ∀ {r} {{aEq : RelEq r A}} -> IsSet (< r > A)
go (relv x) (relv y) = dcong relv relv-inj (x ≟ y)
go (irrv x) (irrv y) = yes refl
ArgFunctor : ∀ {α} -> RawFunctor {α} Arg
ArgFunctor = record
{ _<$>_ = λ{ f (arg i x) -> arg i (f x) }
}
AbsFunctor : ∀ {α} -> RawFunctor {α} Abs
AbsFunctor = record
{ _<$>_ = λ{ f (abs s x) -> abs s (f x) }
}
TCMonad : ∀ {α} -> RawMonad {α} TC
TCMonad = record
{ return = Reflection.return
; _>>=_ = Reflection._>>=_
}
TCApplicative : ∀ {α} -> RawApplicative {α} TC
TCApplicative = rawIApplicative
TCFunctor : ∀ {α} -> RawFunctor {α} TC
TCFunctor = rawFunctor
keep : (ℕ -> ℕ) -> ℕ -> ℕ
keep ι 0 = 0
keep ι (suc n) = suc (ι n)
{-# TERMINATING #-}
mutual
ren : (ℕ -> ℕ) -> Term -> Term
ren ι (appVar v xs) = appVar (ι v) (rens ι xs)
ren ι (appCon c xs) = appCon c (rens ι xs)
ren ι (appDef f xs) = appDef f (rens ι xs)
ren ι (lam v s t) = lam v s (ren (keep ι) t)
ren ι (pat-lam cs xs) = undefined where postulate undefined : _
ren ι (pi s a b) = pi s (ren ι <$> a) (ren (keep ι) b)
ren ι (agda-sort s) = agda-sort (renSort ι s)
ren ι (lit l) = lit l
ren ι (appMeta x xs) = appMeta x (rens ι xs)
ren ι unknown = unknown
rens : (ℕ -> ℕ) -> List (Arg Term) -> List (Arg Term)
rens ι = map (fmap (ren ι))
renSort : (ℕ -> ℕ) -> Sort -> Sort
renSort ι (set t) = set (ren ι t)
renSort ι (lit n) = lit n
renSort ι unknown = unknown
shiftBy : ℕ -> Term -> Term
shiftBy = ren ∘ _+_
shift : Term -> Term
shift = shiftBy 1
unshiftBy : ℕ -> Term -> Term
unshiftBy n = ren (_∸ n)
isSomeName : Name -> Term -> Bool
isSomeName n (appDef m _) = n == m
isSomeName n (appCon m _) = n == m
isSomeName n t = false
{-# TERMINATING #-}
mutual
mapName : (ℕ -> List (Arg Term) -> Term) -> Name -> Term -> Term
mapName f n (appVar v xs) = appVar v (mapNames f n xs)
mapName f n (appCon m xs) = (if n == m then f 0 else appCon m) (mapNames f n xs)
mapName f n (appDef m xs) = (if n == m then f 0 else appDef m) (mapNames f n xs)
mapName f n (lam v s t) = lam v s (mapName (f ∘ suc) n t)
mapName f n (pat-lam cs xs) = undefined where postulate undefined : _
mapName f n (pi s a b) = pi s (mapName f n <$> a) (mapName (f ∘ suc) n b)
mapName f n (agda-sort s) = agda-sort (mapNameSort f n s)
mapName f n (lit l) = lit l
mapName f n (appMeta x xs) = appMeta x (mapNames f n xs)
mapName f n unknown = unknown
mapNames : (ℕ -> List (Arg Term) -> Term) -> Name -> List (Arg Term) -> List (Arg Term)
mapNames f n = map (fmap (mapName f n))
mapNameSort : (ℕ -> List (Arg Term) -> Term) -> Name -> Sort -> Sort
mapNameSort f n (set t) = set (mapName f n t)
mapNameSort f n (lit l) = lit l
mapNameSort f n unknown = unknown
explsOnly : List (Arg Term) -> List Term
explsOnly = mapMaybe unExpl
initType : Type -> Type
initType (pi s a b) = pi s a (initType b)
initType b = unknown
lastType : Type -> Type
lastType (pi s a b) = lastType b
lastType b = b
-- These two should return just `Type` like everything else.
takePis : ℕ -> Type -> Maybe Type
takePis 0 a = just unknown
takePis (suc n) (pi s a b) = pi s a <$> takePis n b
takePis _ _ = nothing
dropPis : ℕ -> Type -> Maybe Type
dropPis 0 a = just a
dropPis (suc n) (pi s a b) = dropPis n b
dropPis _ _ = nothing
monoLastType : Type -> Type
monoLastType = go 0 where
go : ℕ -> Type -> Type
go n (pi s a b) = go (suc n) b
go n b = unshiftBy n b
appendType : Type -> Type -> Type
appendType (pi s a b) c = pi s a (appendType b c)
appendType b c = c
explLamsBy : Type -> Term -> Term
explLamsBy (explPi r s a b) t = explLam s (explLamsBy b t)
explLamsBy (pi s a b) t = explLamsBy b t
explLamsBy b t = t
implicitize : Type -> Type
implicitize (explPi r s a b) = implPi r s a (implicitize b)
implicitize (pi s a b) = pi s a (implicitize b)
implicitize b = b
leadImpls : Type -> List (Abs Term)
leadImpls (implPi r s a b) = abs s a ∷ leadImpls b
leadImpls b = []
pisToAbsArgTypes : Type -> List (Abs (Arg Type))
pisToAbsArgTypes (pi s a b) = abs s a ∷ pisToAbsArgTypes b
pisToAbsArgTypes b = []
explPisToAbsTypes : Type -> List (Abs Type)
explPisToAbsTypes (explPi r s a b) = abs s a ∷ explPisToAbsTypes b
explPisToAbsTypes (pi s a b) = explPisToAbsTypes b
explPisToAbsTypes b = []
explPisToNames : Type -> List String
explPisToNames = map absName ∘ explPisToAbsTypes
countPis : Type -> ℕ
countPis = length ∘ pisToAbsArgTypes
countExplPis : Type -> ℕ
countExplPis = length ∘ explPisToAbsTypes
pisToAbsArgVars : ℕ -> Type -> List (Abs (Arg Term))
pisToAbsArgVars (suc n) (pi s (arg i a) b) = abs s (arg i (pureVar n)) ∷ pisToAbsArgVars n b
pisToAbsArgVars n b = []
pisToArgVars : ℕ -> Type -> List (Arg Term)
pisToArgVars = map absVal % ∘ pisToAbsArgVars
explPisToAbsVars : ℕ -> Type -> List (Abs Term)
explPisToAbsVars (suc n) (explPi r s a b) = abs s (pureVar n) ∷ explPisToAbsVars n b
explPisToAbsVars (suc n) (pi s a b) = explPisToAbsVars n b
explPisToAbsVars n b = []
throw : ∀ {α} {A : Set α} -> String -> TC A
throw s = typeError (strErr s ∷ [])
panic : ∀ {α} {A : Set α} -> String -> TC A
panic s = throw $ "panic: " ++ˢ s
-- I'll merge these later.
macro
sate : Name -> Term -> TC _
sate f ?r =
getType f >>= λ a ->
let res = λ app -> quoteTC (vis# (countExplPis a) app f) >>= unify ?r in
getDefinition f >>= λ
{ (data-cons _) -> res appCon
; _ -> res appDef
}
sateMacro : Name -> Term -> TC _
sateMacro f ?r =
getType f >>= λ a ->
quoteTC (vis# (pred (countExplPis a)) appDef f) >>= unify ?r
_·_ : Term -> Term -> Term
_·_ = sate _$_
unshift′ : Term -> Term
unshift′ t = explLam "_" t · sate tt₀
-- A note for myself: `foldℕ (sate lsuc) (sate lzero) n` is not `reify n`:
-- it's damn `lsuc` -- not `suc`.
termLevelOf : Term -> Maybe Term
termLevelOf (agda-sort (set t)) = just t
termLevelOf (agda-sort (lit n)) = just (foldℕ (sate lsuc) (sate lzero) n)
termLevelOf (agda-sort unknown) = just unknown
termLevelOf _ = nothing
instance
TermReify : Reify Term
TermReify = record
{ reify = id
}
NameReify : Reify Name
NameReify = record
{ reify = lit ∘′ name
}
VisibilityReify : Reify Visibility
VisibilityReify = record
{ reify = λ
{ expl -> sate expl
; impl -> sate impl
; inst -> sate inst
}
}
RelevanceReify : Reify Relevance
RelevanceReify = record
{ reify = λ
{ rel -> sate rel
; irr -> sate irr
}
}
ArgInfoReify : Reify ArgInfo
ArgInfoReify = record
{ reify = λ{ (arg-info v r) -> sate arg-info (reify v) (reify r) }
}
ProdReify : ∀ {α β} {A : Set α} {B : A -> Set β}
{{aReify : Reify A}} {{bReify : ∀ {x} -> Reify (B x)}} -> Reify (Σ A B)
ProdReify = record
{ reify = uncurry λ x y -> sate _,_ (reify x) (reify y)
}
ℕReify : Reify ℕ
ℕReify = record
{ reify = foldℕ (sate suc) (sate zero)
}
ListReify : ∀ {α} {A : Set α} {{aReify : Reify A}} -> Reify (List A)
ListReify = record
{ reify = foldr (sate _∷_ ∘ reify) (sate [])
}
AllReify : ∀ {α β} {A : Set α} {B : A -> Set β} {xs} {{bReify : ∀ {x} -> Reify (B x)}}
-> Reify (All B xs)
AllReify {B = B} {{bReify}} = record
{ reify = go _
} where
go : ∀ xs -> All B xs -> Term
go [] tt = sate tt₀
go (x ∷ xs) (y , ys) = sate _,_ (reify {{bReify}} y) (go xs ys)
toTuple : List Term -> Term
toTuple = foldr₁ (sate _,_) (sate tt₀)
curryBy : Type -> Term -> Term
curryBy = go 0 where
go : ℕ -> Type -> Term -> Term
go n (pi s (arg (arg-info v r) a) b) t = lam v s $ go (suc n) b t
go n _ t = shiftBy n t · toTuple (map pureVar (downFrom n))
explUncurryBy : Type -> Term -> Term
explUncurryBy a f = explLam "x" $ appDef (quote id) (explArg rel (shift f) ∷ go a (pureVar 0)) where
go : Term -> Term -> List (Arg Term)
go (explPi r s a b@(pi _ _ _)) p = explArg r (sate proj₁ p) ∷ go b (sate proj₂ p)
go (pi s a b@(pi _ _ _)) p = go b (sate proj₂ p)
go (explPi r s a b) x = explArg r x ∷ []
go _ t = []
defineTerm : Name -> Term -> TC _
defineTerm n t =
getType n >>= λ a ->
defineFun n (clause (map (implRelArg ∘ patVar ∘ named ∘ absName) (leadImpls a)) t ∷ [])
-- Able to normalize a Setω.
normalize : Term -> TC Term
normalize (pi s (arg i a) b) =
pi s ∘ arg i <$> normalize a <*> extendContext (arg i a) (normalize b)
normalize t = normalise t
getNormType : Name -> TC Type
getNormType = getType >=> normalize
inferNormType : Term -> TC Type
inferNormType = inferType >=> normalize
getData : Name -> TC (Data Type)
getData d = getNormType d >>= λ ab -> getDefinition d >>= λ
{ (data-type p cs) ->
mapM (λ c -> _,_ c ∘ dropPis p <$> getNormType c) cs >>= λ mans ->
case takePis p ab ⊗ (dropPis p ab ⊗ (mapM (uncurry λ c ma -> flip _,_ c <$> ma) mans)) of λ
{ nothing -> panic "getData: data"
; (just (a , b , acs)) -> return ∘ uncurry (packData d a b) $ splitList acs
}
; (record-type c _) -> getNormType c >>= dropPis (countPis ab) >>> λ
{ nothing -> panic "getData: record"
; (just a′) -> return $ packData d (initType ab) (lastType ab) (a′ ∷ []) (c , tt)
}
; _ -> throw "not a data"
}
macro
TypeOf : Term -> Term -> TC _
TypeOf t ?r = inferNormType t >>= unify ?r
runTC : ∀ {α} {A : Set α} -> TC A -> Term -> TC _
runTC a ?r = bindTC a quoteTC >>= unify ?r
|
lemma setdist_sym: "setdist S T = setdist T S" |
theory Affine_Arithmetic_Auxiliarities
imports "HOL-Analysis.Multivariate_Analysis"
begin
subsection \<open>@{term sum_list}\<close>
lemma fst_sum_list: "fst (sum_list xs) = sum_list (map fst xs)"
by (induct xs) auto
lemma snd_sum_list: "snd (sum_list xs) = sum_list (map snd xs)"
by (induct xs) auto
lemma take_greater_eqI: "take c xs = take c ys \<Longrightarrow> c \<ge> a \<Longrightarrow> take a xs = take a ys"
proof (induct xs arbitrary: a c ys)
case (Cons x xs) note ICons = Cons
thus ?case
proof (cases a)
case (Suc b)
thus ?thesis using Cons(2,3)
proof (cases ys)
case (Cons z zs)
from ICons obtain d where c: "c = Suc d"
by (auto simp: Cons Suc dest!: Suc_le_D)
show ?thesis
using ICons(2,3)
by (auto simp: Suc Cons c intro: ICons(1))
qed simp
qed simp
qed (metis le_0_eq take_eq_Nil)
lemma take_max_eqD:
"take (max a b) xs = take (max a b) ys \<Longrightarrow> take a xs = take a ys \<and> take b xs = take b ys"
by (metis max.cobounded1 max.cobounded2 take_greater_eqI)
lemma take_Suc_eq: "take (Suc n) xs = (if n < length xs then take n xs @ [xs ! n] else xs)"
by (auto simp: take_Suc_conv_app_nth)
subsection \<open>Radiant and Degree\<close>
definition "rad_of w = w * pi / 180"
definition "deg_of w = 180 * w / pi"
lemma rad_of_inverse[simp]: "deg_of (rad_of w) = w"
and deg_of_inverse[simp]: "rad_of (deg_of w) = w"
by (auto simp: deg_of_def rad_of_def)
lemma deg_of_monoI: "x \<le> y \<Longrightarrow> deg_of x \<le> deg_of y"
by (auto simp: deg_of_def intro!: divide_right_mono)
lemma rad_of_monoI: "x \<le> y \<Longrightarrow> rad_of x \<le> rad_of y"
by (auto simp: rad_of_def)
lemma deg_of_strict_monoI: "x < y \<Longrightarrow> deg_of x < deg_of y"
by (auto simp: deg_of_def intro!: divide_strict_right_mono)
lemma rad_of_strict_monoI: "x < y \<Longrightarrow> rad_of x < rad_of y"
by (auto simp: rad_of_def)
lemma deg_of_mono[simp]: "deg_of x \<le> deg_of y \<longleftrightarrow> x \<le> y"
using rad_of_monoI
by (fastforce intro!: deg_of_monoI)
lemma deg_of_strict_mono[simp]: "deg_of x < deg_of y \<longleftrightarrow> x < y"
using rad_of_strict_monoI
by (fastforce intro!: deg_of_strict_monoI)
lemma rad_of_strict_mono[simp]: "rad_of x < rad_of y \<longleftrightarrow> x < y"
using rad_of_strict_monoI
by (fastforce intro!: deg_of_strict_monoI)
lemma rad_of_lt_iff: "rad_of d < r \<longleftrightarrow> d < deg_of r"
and rad_of_gt_iff: "rad_of d > r \<longleftrightarrow> d > deg_of r"
and rad_of_le_iff: "rad_of d \<le> r \<longleftrightarrow> d \<le> deg_of r"
and rad_of_ge_iff: "rad_of d \<ge> r \<longleftrightarrow> d \<ge> deg_of r"
using rad_of_strict_mono[of d "deg_of r"] rad_of_mono[of d "deg_of r"]
by auto
end
|
(**
VerifiedDSP
Copyright (C) {2015} {Jeremy L Rubin}
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.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**)
Require Import IOModule.
Module Type Component_Sig(IO:IO_SIG).
Variable io : IO.func.
End Component_Sig.
Module Component(I:IO_SIG)(M:Component_Sig(I)).
Import M.
Definition io := M.io.
End Component.
|
No. 79 Wing was a Royal Australian Air Force ( RAAF ) wing of World War II . It was formed in December 1943 at Batchelor , Northern Territory , as part of North @-@ Western Area Command . Led by Group Captain Charles Eaton , the wing comprised four squadrons on its establishment , flying Beaufort and B @-@ 25 Mitchell bombers and Beaufighter heavy fighters . No. 79 Wing took part in the New Guinea and North @-@ Western Area Campaigns during 1944 – 45 , eventually transferring to Balikpapan in the Dutch East Indies as the Allies advanced northward . By the end of the Pacific War , the wing was attached to the Australian First Tactical Air Force and was made up of Nos. 2 and 18 ( Netherlands East Indies ) Squadrons , both flying Mitchells . The latter transferred to the Netherlands Air Force in late 1945 , while the former returned to Australia where it disbanded the following year . No. 79 Headquarters itself disbanded in October 1945 , soon after the end of hostilities .
|
module FreudenthalTriangulation
using LinearAlgebra
using SparseArrays
export freudenthal_vertices, freudenthal_simplex, barycentric_coordinates, freudenthal_simplex_and_coords,
freudenthal_simplex_and_coords!
# Construct the Freudenthal triangulation of the belief simplex
"""
freudenthal_vertices(n::Int64, m::Int64)
Construct the list of Freudenthal vertices in an `n` dimensional space with grid resolution `m`.
The vertices are represented by a list of `n` dimensional vectors.
"""
function freudenthal_vertices(n::Int64, m::Int64)
V = Vector{Int}[]
v = Vector{Int}(undef, n)
v[1] = m
freudenthal_vertices!(V, v, 2)
return V
end
function freudenthal_vertices!(V::Vector{Vector{Int64}}, v::Vector{Int64}, i::Int64)
n = length(v)
if i > n
push!(V, copy(v))
return
end
for k in 0 : v[i-1]
v[i] = k
freudenthal_vertices!(V, v, i+1)
end
end
"""
freudenthal_simplex(x::Vector{Float64})
Returns the list of vertices of the simplex of point `x` in the Freudenthal grid.
"""
function freudenthal_simplex(x::Vector{Float64})
n = length(x)
V = Vector{Vector{Int}}(undef, n+1)
V[1] = floor.(Int, x)
d = x - V[1]
p = sortperm(d, rev=true)
for i in 2 : n+1
V[i] = copy(V[i-1])
V[i][p[i-1]] += 1
end
return V
end
"""
barycentric_coordinates(x::Vector{Int64}, V::Vector{Vector{Int64}})
Given a point `x` and its simplex `V` in the Freudenthal grid, returns the barycentric coordinates
of `x` in the grid. `V` must be in the same order as provided by the output of `freudenthal_simplex`
"""
function barycentric_coordinates(x, V)
d = x - V[1]
p = sortperm(d, rev=true)
n = length(x)
λ = Vector{Float64}(undef, n+1)
λ[n+1] = d[p[n]]
for i in n:-1:2
λ[i] = d[p[i-1]] - d[p[i]]
end
λ[1] = 1.0 - sum(λ[2:end])
return λ
end
"""
freudenthal_coords(x::AbstractArray{Float64})
Given a point `x`, returns the simplex of the point `x` and the barycentric coordinates of `x` in the grid.
"""
function freudenthal_simplex_and_coords(x::Vector{Float64})
V = freudenthal_simplex(x)
return V, barycentric_coordinates(x, V)
end
"""
freudenthal_simplex_and_coords!(x::AbstractArray{Float64}, V::Vector{Vector{Int64}}, λ::Vector{Float64})
Fills `V` and `λ` with the simplex points in the Freudenthal space and associated coordinates respectively.
"""
function freudenthal_simplex_and_coords!(x::AbstractArray{Float64}, V::Vector{Vector{Int64}}, λ::Vector{Float64})
n = length(x)
V[1] = floor.(Int, x)
d = x - V[1]
p = sortperm(d, rev=true)
for i in 2 : n+1
copyto!(V[i], V[i-1])
V[i][p[i-1]] += 1
end
λ[n+1] = d[p[n]]
for i in n:-1:2
λ[i] = d[p[i-1]] - d[p[i]]
end
λ[1] = 1.0 - sum(λ[2:end])
return V, λ
end
end # module
|
open import Theory
module Categories.Category.Construction.Classifying {ℓ₁ ℓ₂ ℓ₃} (Th : Theory ℓ₁ ℓ₂ ℓ₃) where
open import Relation.Binary using (Rel)
open import Data.List using ([]; _∷_)
open import Data.Fin using () renaming (zero to fzero; suc to fsuc)
open import Level using (_⊔_)
open import Categories.Category
open import Syntax
open Theory.Theory Th
open Signature Sg
open Term Sg
private
arr : Rel Type (ℓ₁ ⊔ ℓ₂)
arr A B = A ∷ [] ⊢ B
identityʳ : forall {A B} {e : A ∷ [] ⊢ B}
-> A ∷ [] ⊢ e [ ext ! var ] ≡ e
identityʳ {A} {e = e} = trans (cong/sub (trans (cong/ext !-unique refl) η-pair) refl) sub/id
assoc : {A B C D : Type} {f : arr A B} {g : arr B C} {h : arr C D}
-> A ∷ [] ⊢ h [ ext ! g ] [ ext ! f ] ≡ h [ ext ! (g [ ext ! f ]) ]
assoc {f = f} {g = g} {h = h} = trans (sym sub/∙)
(cong/sub (trans ext∙ (cong/ext (sym !-unique) refl)) refl)
Cl : Category ℓ₁ (ℓ₁ ⊔ ℓ₂) (ℓ₁ ⊔ ℓ₂ ⊔ ℓ₃)
Cl = record
{ Obj = Type
; _⇒_ = arr
; _≈_ = λ e₁ e₂ → _ ∷ [] ⊢ e₁ ≡ e₂
; id = var
; _∘_ = λ e₁ e₂ → e₁ [ ext ! e₂ ]
; assoc = assoc
; sym-assoc = sym assoc
; identityˡ = λ {A} {B} {f} -> var/ext ! f
; identityʳ = identityʳ
; identity² = var/ext ! var
; equiv = record { refl = refl ; sym = sym ; trans = trans }
; ∘-resp-≈ = λ x x₁ → cong/sub (cong/ext refl x₁) x
}
open import Categories.Category.BinaryProducts Cl
module M where
open import Categories.Category.CartesianClosed.Canonical Cl
CC : CartesianClosed
CC = record
{ ⊤ = Unit
; _×_ = _*_
; ! = unit
; π₁ = fst var
; π₂ = snd var
; ⟨_,_⟩ = pair
; !-unique = eta/Unit
; π₁-comp = trans comm/fst (trans (cong/fst (var/ext ! (pair _ _))) (beta/*₁ _ _))
; π₂-comp = trans comm/snd (trans (cong/snd (var/ext ! (pair _ _))) (beta/*₂ _ _))
; ⟨,⟩-unique = ⟨,⟩-unique
; _^_ = λ A B → B => A
; eval = app (fst var) (snd var)
; curry = λ e → abs (e [ ext ! (pair (var [ weaken ]) var) ])
; eval-comp = eval-comp
; curry-resp-≈ = λ x → cong/abs (cong/sub refl x)
; curry-unique = λ x → curry-unique x
}
where
⟨,⟩-unique : forall {A B C} {h : C ∷ [] ⊢ A * B} {i : C ∷ [] ⊢ A} {j : C ∷ [] ⊢ B}
-> C ∷ [] ⊢ fst var [ ext ! h ] ≡ i
-> C ∷ [] ⊢ snd var [ ext ! h ] ≡ j
-> C ∷ [] ⊢ pair i j ≡ h
⟨,⟩-unique x y = trans
(cong/pair
(sym (trans (cong/fst (sym (var/ext ! _))) (trans (sym comm/fst) x)))
(sym (trans (cong/snd (sym (var/ext ! _))) (trans (sym comm/snd) y)))
)
(eta/* _)
open import Categories.Object.Product.Morphisms Cl using ([_⇒_]_×_)
open import Categories.Object.Product Cl using (Product)
product : forall {A B} -> Product A B
product {A} {B} = record
{ A×B = A * B
; π₁ = fst var
; π₂ = snd var
; ⟨_,_⟩ = pair
; project₁ = trans comm/fst (trans (cong/fst (var/ext ! (pair _ _))) (beta/*₁ _ _))
; project₂ = trans comm/snd (trans (cong/snd (var/ext ! (pair _ _))) (beta/*₂ _ _))
; unique = ⟨,⟩-unique
}
eval-comp : forall {B A C} {f : arr (C * A) B}
-> C * A ∷ [] ⊢
app (fst var) (snd var)
[ ext ! ([ product ⇒ product ] (abs (f [ ext ! (pair (var [ weaken ]) var)])) × var) ]
≡
f
eval-comp = trans comm/app (trans (cong/app (trans comm/fst (cong/fst (var/ext _ _))) (trans comm/snd (cong/snd (var/ext _ _)))) (trans (cong/app (trans (beta/*₁ _ _) comm/abs) (beta/*₂ _ _)) (trans (beta/=> _ _) (trans (sym sub/∙) (trans (cong/sub (trans ext∙ (cong/ext (trans (cong/∙ (trans ext∙ (cong/ext (sym !-unique) comm/fst)) refl) (trans ext∙ (cong/ext (sym !-unique) (trans comm/fst (cong/fst (trans (sym sub/∙) (cong/sub weaken/ext refl))))))) (trans (var/ext _ _) (var/ext _ _)))) refl) (trans (sym sub/∙) (trans (cong/sub (trans ext∙ (trans (cong/ext (sym !-unique) (trans comm/pair (cong/pair (trans (sym sub/∙) (trans (cong/sub weaken/ext refl) (trans (var/ext _ _) (cong/fst sub/id)))) (var/ext _ _)))) (trans (cong/ext !-unique (eta/* _)) η-pair))) refl) sub/id)))))))
open BinaryProducts (record { product = product })
open Category Cl
helper : forall {A B C} {f : A ⇒ B => C}
-> B ∷ A ∷ [] ⊨ ext ! (var [ weaken ]) ≡ weaken
helper = trans (cong/ext (!-unique {γ = weaken ∙ weaken}) refl) (trans (sym ext∙) (trans (cong/∙ η-pair refl) id∙ˡ))
curry-unique : forall {A B C} {f : A ⇒ B => C} {g : A × B ⇒ C}
-> app (fst var) (snd var) ∘ (f ⁂ Category.id Cl) ≈ g
-> f ≈ abs (g [ ext ! (pair (var [ weaken ]) var) ])
curry-unique {A} {B} {C} {f = f} {g = g} x =
begin
f
≈˘⟨ eta/=> _ ⟩
abs (app (f [ weaken ]) var)
≈˘⟨ cong/abs (cong/app (cong/sub (helper {f = f}) refl) refl) ⟩
abs (app (f [ ext ! (var [ weaken ]) ]) var)
≈˘⟨ cong/abs (cong/app (beta/*₁ _ _) (beta/*₂ _ _)) ⟩
abs (app (fst (pair (f [ ext ! (var [ weaken ]) ]) var)) (snd (pair (f [ ext ! (var [ weaken ]) ]) var)))
≈˘⟨ cong/abs (cong/app (trans comm/fst (cong/fst (var/ext _ _))) (trans comm/snd (cong/snd (var/ext _ _)))) ⟩
abs (app (fst var [ ext ! (pair (f [ ext ! (var [ weaken ]) ]) var) ]) (snd var [ ext ! (pair (f [ ext ! (var [ weaken ]) ]) var) ]))
≈˘⟨ cong/abs comm/app ⟩
abs (app (fst var) (snd var) [ ext ! (pair (f [ ext ! (var [ weaken ]) ]) var) ])
≈˘⟨ cong/abs (cong/sub (cong/ext refl (cong/pair (cong/sub (cong/ext refl (trans comm/fst (trans (cong/fst (var/ext _ _)) (beta/*₁ _ _)))) refl) refl)) refl) ⟩
abs (app (fst var) (snd var) [ ext ! (pair (f [ ext ! (fst var [ ext ! (pair (var [ weaken ]) var)]) ]) var) ])
≈˘⟨ cong/abs (cong/sub (cong/ext refl (cong/pair (cong/sub (trans ext∙ (cong/ext (sym !-unique) refl)) refl) (trans (cong/snd (var/ext _ _)) (beta/*₂ _ _)))) refl) ⟩
abs (app (fst var) (snd var) [ ext ! (pair (f [ ext ! (fst var) ∙ ext ! (pair (var [ weaken ]) var) ]) (snd (var [ ext ! (pair (var [ weaken ]) var) ]))) ])
≈˘⟨ cong/abs (cong/sub (cong/ext refl (cong/pair (sym sub/∙) comm/snd)) refl) ⟩
abs (app (fst var) (snd var) [ ext ! (pair (f [ ext ! (fst var) ] [ ext ! (pair (var [ weaken ]) var) ]) (snd var [ ext ! (pair (var [ weaken ]) var) ])) ])
≈˘⟨ cong/abs (cong/sub (cong/ext refl comm/pair) refl) ⟩
abs (app (fst var) (snd var) [ ext ! (pair (f [ ext ! (fst var) ]) (snd var) [ ext ! (pair (var [ weaken ]) var) ]) ])
≈⟨ cong/abs (cong/sub (cong/ext !-unique (cong/sub refl (cong/pair refl (sym (var/ext _ _))))) refl) ⟩
abs (app (fst var) (snd var) [ ext (! ∙ ext ! (pair (var [ weaken ]) var)) (pair (f [ ext ! (fst var) ]) (var [ ext ! (snd var) ]) [ ext ! (pair (var [ weaken ]) var) ]) ])
≈˘⟨ cong/abs (cong/sub ext∙ refl) ⟩
abs (app (fst var) (snd var) [ ext ! (pair (f [ ext ! (fst var) ]) (var [ ext ! (snd var) ])) ∙ ext ! (pair (var [ weaken ]) var) ])
≡⟨⟩
abs (app (fst var) (snd var) [ ext ! ⟨ f ∘ fst var , Category.id Cl ∘ snd var ⟩ ∙ ext ! (pair (var [ weaken ]) var) ])
≈⟨ cong/abs sub/∙ ⟩
abs ((app (fst var) (snd var) ∘ ⟨ f ∘ fst var , Category.id Cl ∘ snd var ⟩) [ ext ! (pair (var [ weaken ]) var) ])
≡⟨⟩
abs ((app (fst var) (snd var) ∘ (f ⁂ Category.id Cl)) [ ext ! (pair (var [ weaken ]) var) ])
≈⟨ cong/abs (cong/sub refl x) ⟩
abs (g [ ext ! (pair (var [ weaken ]) var) ])
∎
where
open import Relation.Binary.Reasoning.Setoid TermSetoid
open import Categories.Category.CartesianClosed Cl
import Categories.Category.CartesianClosed.Canonical Cl as Can
CC : CartesianClosed
CC = Can.Equivalence.fromCanonical M.CC
open import Semantics Cl CC Sg
open Category Cl
private
open import Data.Product using (_,_)
open import Categories.Morphism Cl using (Iso; _≅_)
open import Categories.Category.Cartesian using (Cartesian)
open import Categories.Functor
open import Categories.Functor.Properties using ([_]-resp-∘)
open import Categories.Functor.Construction.Product using (Product)
open import Categories.Functor.Construction.Exponential using (Exp)
open import Categories.Functor.Bifunctor using (Bifunctor)
open CartesianClosed CC
open BinaryProducts (Cartesian.products cartesian)
open I ⌊_⌋
P : Bifunctor Cl Cl Cl
P = Product Cl cartesian
E : Bifunctor Cl op Cl
E = Exp Cl CC
from/⟦⟧T : forall (A : Type) -> ⟦ A ⟧T ⇒ A
to/⟦⟧T : forall (A : Type) -> A ⇒ ⟦ A ⟧T
from/⟦⟧T ⌊ x ⌋ = Category.id Cl
from/⟦⟧T Unit = Category.id Cl
from/⟦⟧T (A * A₁) = from/⟦⟧T A ⁂ from/⟦⟧T A₁
from/⟦⟧T (A => A₁) = λg (from/⟦⟧T A₁ ∘ eval′ ∘ (Category.id Cl ⁂ to/⟦⟧T A))
to/⟦⟧T ⌊ x ⌋ = Category.id Cl
to/⟦⟧T Unit = Category.id Cl
to/⟦⟧T (A * A₁) = to/⟦⟧T A ⁂ to/⟦⟧T A₁
to/⟦⟧T (A => A₁) = λg (to/⟦⟧T A₁ ∘ eval′ ∘ (Category.id Cl ⁂ from/⟦⟧T A))
to∘from : forall {A} -> ⟦ A ⟧T ∷ [] ⊢ to/⟦⟧T A [ ext ! (from/⟦⟧T A) ] ≡ var
to∘from {⌊ x ⌋} = var/ext _ _
to∘from {Unit} = var/ext _ _
to∘from {A * A₁} = trans ([ P ]-resp-∘ (to∘from , to∘from)) (Functor.identity P)
to∘from {A => A₁} = trans ([ E ]-resp-∘ (to∘from , to∘from)) (Functor.identity E)
from∘to : forall {A} -> A ∷ [] ⊢ from/⟦⟧T A [ ext ! (to/⟦⟧T A) ] ≡ var
from∘to {⌊ x ⌋} = var/ext _ _
from∘to {Unit} = var/ext _ _
from∘to {A * A₁} = trans ([ P ]-resp-∘ (from∘to , from∘to)) (Functor.identity P)
from∘to {A => A₁} = trans ([ E ]-resp-∘ (from∘to , from∘to)) (Functor.identity E)
Iso/⟦⟧T : forall {A : Type} -> ⟦ A ⟧T ≅ A
Iso/⟦⟧T {A} = record
{ from = from/⟦⟧T A
; to = to/⟦⟧T A
; iso = record { isoˡ = to∘from ; isoʳ = from∘to }
}
⟦_⟧F : (f : Func) -> ⟦ dom f ⟧T ⇒ ⟦ cod f ⟧T
⟦_⟧F f = _≅_.to Iso/⟦⟧T ∘ x ∘ _≅_.from Iso/⟦⟧T
where
x : dom f ⇒ cod f
x = func f var
S : Structure
S = record { ⟦_⟧G = ⌊_⌋ ; ⟦_⟧F = λ f → ⟦ f ⟧F }
open Structure S
private
γC : forall {Γ} -> ⟦ Γ ⟧C ∷ [] ⊨ Γ
γC {[]} = !
γC {A ∷ Γ} = ext (γC {Γ} ∙ ext ! π₁) (from/⟦⟧T A ∘ π₂)
open HomReasoning
open import Categories.Morphism.Reasoning Cl
import Categories.Object.Product Cl as Prod
open import Categories.Object.Terminal Cl using (Terminal)
module T = Terminal (Cartesian.terminal cartesian)
helper : forall {Γ} {A} {e : Γ ⊢ A} -> ⟦ e ⟧ ≈ to/⟦⟧T A ∘ (e [ γC ])
helperS : forall {Γ Γ′} {γ : Γ ⊨ Γ′} -> _ ⊨ γC ∙ ext ! ⟦ γ ⟧S ≡ γ ∙ γC
helper {e = func f e} =
begin
(to/⟦⟧T (cod f) ∘ func f var ∘ from/⟦⟧T (dom f)) ∘ ⟦ e ⟧
≈⟨ ∘-resp-≈ʳ (helper {e = e}) ⟩
(to/⟦⟧T (cod f) ∘ func f var ∘ from/⟦⟧T (dom f)) ∘ to/⟦⟧T _ ∘ (e [ γC ])
≈⟨ assoc²' ⟩
to/⟦⟧T (cod f) ∘ func f var ∘ from/⟦⟧T (dom f) ∘ to/⟦⟧T (dom f) ∘ (e [ γC ])
≈⟨ ∘-resp-≈ʳ (∘-resp-≈ʳ (cancelˡ from∘to)) ⟩
to/⟦⟧T (cod f) ∘ func f var ∘ (e [ γC ])
≈⟨ ∘-resp-≈ʳ (comm/func _ _ _ _ _) ⟩
to/⟦⟧T (cod f) ∘ func f (var ∘ (e [ γC ]))
≈⟨ ∘-resp-≈ʳ (cong/func identityˡ) ⟩
to/⟦⟧T (cod f) ∘ func f (e [ γC ])
≈˘⟨ ∘-resp-≈ʳ (comm/func _ _ _ _ _) ⟩
to/⟦⟧T (cod f) ∘ (func f e [ γC ])
∎
helper {e = var} =
begin
π₂
≈⟨ insertˡ to∘from ⟩
to/⟦⟧T _ ∘ (from/⟦⟧T _ ∘ π₂)
≈˘⟨ ∘-resp-≈ʳ (var/ext _ _) ⟩
to/⟦⟧T _ ∘ (var [ ext _ (from/⟦⟧T _ ∘ π₂) ])
∎
helper {e = unit} = T.!-unique _
helper {e = pair e₁ e₂} =
begin
⟨ ⟦ e₁ ⟧ , ⟦ e₂ ⟧ ⟩
≈⟨ ⟨⟩-cong₂ (helper {e = e₁}) (helper {e = e₂}) ⟩
⟨ to/⟦⟧T _ ∘ (e₁ [ γC ]) , to/⟦⟧T _ ∘ (e₂ [ γC ]) ⟩
≈˘⟨ ⁂∘⟨⟩ ⟩
(to/⟦⟧T _ ⁂ to/⟦⟧T _) ∘ (pair (e₁ [ γC ]) (e₂ [ γC ]))
≈˘⟨ ∘-resp-≈ʳ comm/pair ⟩
(to/⟦⟧T _ ⁂ to/⟦⟧T _) ∘ (pair e₁ e₂ [ γC ])
∎
helper {e = fst {A = A} {B = B} e} = switch-fromtoˡ Iso/⟦⟧T (
begin
from/⟦⟧T _ ∘ π₁ ∘ ⟦ e ⟧
≈⟨ ∘-resp-≈ʳ (∘-resp-≈ʳ (helper {e = e})) ⟩
from/⟦⟧T A ∘ π₁ ∘ to/⟦⟧T (A * B) ∘ (e [ γC ])
≈⟨ ∘-resp-≈ʳ (pullˡ π₁∘⁂) ⟩
from/⟦⟧T A ∘ (to/⟦⟧T A ∘ π₁) ∘ (e [ γC ])
≈⟨ assoc²'' ⟩
(from/⟦⟧T A ∘ to/⟦⟧T A) ∘ π₁ ∘ (e [ γC ])
≈⟨ elimˡ from∘to ⟩
π₁ ∘ (e [ γC ])
≈⟨ comm/fst ⟩
fst (var [ ext ! (e [ γC ]) ])
≈⟨ cong/fst (var/ext _ _) ⟩
fst (e [ γC ])
≈˘⟨ comm/fst ⟩
fst e [ γC ]
∎)
helper {e = snd e} =
begin
π₂ ∘ ⟦ e ⟧
≈⟨ ∘-resp-≈ʳ (helper {e = e}) ⟩
π₂ ∘ (to/⟦⟧T _ ∘ (e [ γC ]))
≈⟨ pullˡ π₂∘⁂ ⟩
(to/⟦⟧T _ ∘ snd var) ∘ (e [ γC ])
≈⟨ pullʳ comm/snd ⟩
to/⟦⟧T _ ∘ snd (var ∘ (e [ γC ]))
≈⟨ ∘-resp-≈ʳ (cong/snd identityˡ) ⟩
to/⟦⟧T _ ∘ snd (e [ γC ])
≈˘⟨ ∘-resp-≈ʳ comm/snd ⟩
to/⟦⟧T _ ∘ (snd e [ γC ])
∎
helper {e = abs e} =
begin
λg ⟦ e ⟧
≈⟨ λ-cong (helper {e = e}) ⟩
λg (to/⟦⟧T _ ∘ (e [ γC ]))
≈⟨ refl ⟩
λg (to/⟦⟧T _ ∘ (e [ ext (γC ∙ ext ! π₁) (from/⟦⟧T _ ∘ π₂) ]))
≈˘⟨ λ-cong (∘-resp-≈ʳ (cong/sub (cong/ext id∙ʳ refl) refl)) ⟩
λg (to/⟦⟧T _ ∘ (e [ ext ((γC ∙ ext ! π₁) ∙ _⊨_.id) (from/⟦⟧T _ ∘ π₂) ]))
≈˘⟨ λ-cong (∘-resp-≈ʳ (cong/sub ×id′-ext refl)) ⟩
λg (to/⟦⟧T _ ∘ (e [ (γC ∙ ext ! π₁) ×id′ ∙ ext _⊨_.id (from/⟦⟧T _ ∘ π₂)]))
≈⟨ λ-cong (∘-resp-≈ʳ sub/∙) ⟩
λg (to/⟦⟧T _ ∘ (e [ (γC ∙ ext ! π₁) ×id′ ] [ ext _⊨_.id (from/⟦⟧T _ ∘ π₂)]))
≈˘⟨ λ-cong (∘-resp-≈ʳ (cong/sub refl (cong/sub ×id′-∙ refl))) ⟩
λg (to/⟦⟧T _ ∘ (e [ γC ×id′ ∙ ext ! π₁ ×id′ ] [ ext _⊨_.id (from/⟦⟧T _ ∘ π₂)]))
≈⟨ λ-cong (∘-resp-≈ʳ (cong/sub refl sub/∙)) ⟩
λg (to/⟦⟧T _ ∘ (e [ ext (γC ∙ weaken) var ] [ ext (ext ! π₁ ∙ weaken) var ] [ ext _⊨_.id (from/⟦⟧T _ ∘ π₂)]))
≈˘⟨ λ-cong (∘-resp-≈ʳ (beta/=> _ _)) ⟩
λg (to/⟦⟧T _ ∘ app (abs (e [ ext (γC ∙ weaken) var ] [ ext (ext ! π₁ ∙ weaken) var ])) (from/⟦⟧T _ ∘ π₂))
≈˘⟨ λ-cong (∘-resp-≈ʳ (cong/app comm/abs refl)) ⟩
λg (to/⟦⟧T _ ∘ app (abs (e [ ext (γC ∙ weaken) var ]) ∘ π₁) (from/⟦⟧T _ ∘ π₂))
≈˘⟨ λ-cong (∘-resp-≈ʳ (cong/app (beta/*₁ _ _) (beta/*₂ _ _))) ⟩
λg (to/⟦⟧T _ ∘ app (fst (abs (e [ ext (γC ∙ weaken) var ]) ⁂ from/⟦⟧T _)) (snd (abs (e [ ext (γC ∙ weaken) var ]) ⁂ from/⟦⟧T _)))
≈˘⟨ λ-cong (∘-resp-≈ʳ (trans comm/app (cong/app (trans comm/fst (cong/fst (var/ext _ _))) (trans comm/snd (cong/snd (var/ext _ _)))))) ⟩
λg (to/⟦⟧T _ ∘ (app π₁ π₂) ∘ (abs (e [ ext (γC ∙ weaken) var ]) ⁂ from/⟦⟧T _))
≈˘⟨ λ-cong (∘-resp-≈ʳ (∘-resp-≈ˡ (cong/app (beta/*₁ _ _) (beta/*₂ _ _)))) ⟩
λg (to/⟦⟧T _ ∘ (app (fst (pair π₁ π₂)) (snd (pair π₁ π₂))) ∘ (abs (e [ ext (γC ∙ weaken) var ]) ⁂ from/⟦⟧T _))
≈˘⟨ λ-cong (∘-resp-≈ʳ (∘-resp-≈ˡ (cong/app (trans comm/fst (cong/fst (var/ext _ _))) (trans comm/snd (cong/snd (var/ext _ _)))))) ⟩
λg (to/⟦⟧T _ ∘ (app (fst var ∘ pair π₁ π₂) (snd var ∘ pair π₁ π₂)) ∘ (abs (e [ ext (γC ∙ weaken) var ]) ⁂ from/⟦⟧T _))
≈˘⟨ λ-cong (∘-resp-≈ʳ (∘-resp-≈ˡ comm/app)) ⟩
λg (to/⟦⟧T _ ∘ (app (fst var) (snd var) ∘ (pair π₁ π₂)) ∘ (abs (e [ ext (γC ∙ weaken) var ]) ⁂ from/⟦⟧T _))
≈⟨ refl ⟩
λg (to/⟦⟧T _ ∘ (eval ∘ Prod.repack product exp.product) ∘ (abs (e [ ext (γC ∙ weaken) var ]) ⁂ from/⟦⟧T _))
≈⟨ refl ⟩
λg (to/⟦⟧T _ ∘ eval′ ∘ (abs (e [ ext (γC ∙ weaken) var ]) ⁂ from/⟦⟧T _))
≈˘⟨ λ-cong (∘-resp-≈ʳ (∘-resp-≈ʳ (⁂-cong₂ comm/abs refl))) ⟩
λg (to/⟦⟧T _ ∘ eval′ ∘ ((abs e [ γC ]) ⁂ from/⟦⟧T _))
≈˘⟨ λ-cong (∘-resp-≈ʳ (∘-resp-≈ʳ (⁂-cong₂ identityˡ (Category.identityʳ Cl)))) ⟩
λg (to/⟦⟧T _ ∘ eval′ ∘ (var ∘ (abs e [ γC ]) ⁂ from/⟦⟧T _ ∘ var))
≈˘⟨ λ-cong (∘-resp-≈ʳ (∘-resp-≈ʳ ⁂∘⁂)) ⟩
λg (to/⟦⟧T _ ∘ eval′ ∘ (var ⁂ from/⟦⟧T _) ∘ ((abs e [ γC ]) ⁂ var))
≈˘⟨ λ-cong assoc²' ⟩
λg ((to/⟦⟧T _ ∘ eval′ ∘ (var ⁂ from/⟦⟧T _)) ∘ ((abs e [ γC ]) ⁂ var))
≈˘⟨ exp.subst product product ⟩
(λg (to/⟦⟧T _ ∘ eval′ ∘ (var ⁂ from/⟦⟧T _))) ∘ (abs e [ γC ])
≈⟨ refl ⟩
to/⟦⟧T (_ => _) ∘ (abs e [ γC ])
∎
helper {e = app e₁ e₂} =
begin
eval′ ∘ ⟨ ⟦ e₁ ⟧ , ⟦ e₂ ⟧ ⟩
≈⟨ refl ⟩
(app (fst var) (snd var) ∘ _) ∘ ⟨ ⟦ e₁ ⟧ , ⟦ e₂ ⟧ ⟩
≈⟨ ∘-resp-≈ˡ (elimʳ η) ⟩
app (fst var) (snd var) ∘ ⟨ ⟦ e₁ ⟧ , ⟦ e₂ ⟧ ⟩
≈⟨ ∘-resp-≈ʳ (⟨⟩-cong₂ (helper {e = e₁}) (helper {e = e₂})) ⟩
app (fst var) (snd var) ∘ ⟨ to/⟦⟧T _ ∘ (e₁ [ γC ]) , to/⟦⟧T _ ∘ (e₂ [ γC ]) ⟩
≈⟨ comm/app ⟩
app (fst var ∘ ⟨ to/⟦⟧T _ ∘ (e₁ [ γC ]) , to/⟦⟧T _ ∘ (e₂ [ γC ]) ⟩)
(snd var ∘ ⟨ to/⟦⟧T _ ∘ (e₁ [ γC ]) , to/⟦⟧T _ ∘ (e₂ [ γC ]) ⟩)
≈⟨ cong/app comm/fst comm/snd ⟩
app (fst (var ∘ ⟨ to/⟦⟧T _ ∘ (e₁ [ γC ]) , to/⟦⟧T _ ∘ (e₂ [ γC ]) ⟩))
(snd (var ∘ ⟨ to/⟦⟧T _ ∘ (e₁ [ γC ]) , to/⟦⟧T _ ∘ (e₂ [ γC ]) ⟩))
≈⟨ cong/app (cong/fst (var/ext _ _)) (cong/snd (var/ext _ _)) ⟩
app (fst ⟨ to/⟦⟧T _ ∘ (e₁ [ γC ]) , to/⟦⟧T _ ∘ (e₂ [ γC ]) ⟩)
(snd ⟨ to/⟦⟧T _ ∘ (e₁ [ γC ]) , to/⟦⟧T _ ∘ (e₂ [ γC ]) ⟩)
≈⟨ cong/app (beta/*₁ _ _) (beta/*₂ _ _) ⟩
app (to/⟦⟧T (_ => _) ∘ (e₁ [ γC ]))
(to/⟦⟧T _ ∘ (e₂ [ γC ]))
≈⟨ refl ⟩
app (λg (to/⟦⟧T _ ∘ eval′ ∘ (var ⁂ from/⟦⟧T _)) ∘ (e₁ [ γC ]))
(to/⟦⟧T _ ∘ (e₂ [ γC ]))
≈⟨ refl ⟩
app (curry ((to/⟦⟧T _ ∘ eval′ ∘ (var ⁂ from/⟦⟧T _)) ∘ Prod.repack product product) ∘ (e₁ [ γC ]))
(to/⟦⟧T _ ∘ (e₂ [ γC ]))
≈⟨ refl ⟩
app (abs (((to/⟦⟧T _ ∘ eval′ ∘ (var ⁂ from/⟦⟧T _)) ∘ Prod.repack product product) [ ext ! (pair (var [ weaken ]) var) ]) ∘ (e₁ [ γC ]))
(to/⟦⟧T _ ∘ (e₂ [ γC ]))
≈⟨ cong/app (cong/sub refl (cong/abs (cong/sub refl (elimʳ η)))) refl ⟩
app (abs ((to/⟦⟧T _ ∘ eval′ ∘ (var ⁂ from/⟦⟧T _)) [ ext ! (pair (var [ weaken ]) var) ]) ∘ (e₁ [ γC ]))
(to/⟦⟧T _ ∘ (e₂ [ γC ]))
≈⟨ cong/app comm/abs refl ⟩
app (abs ((to/⟦⟧T _ ∘ eval′ ∘ (var ⁂ from/⟦⟧T _)) [ ext ! (pair (var [ weaken ]) var) ] [ ext ! (e₁ [ γC ]) ×id′ ]))
(to/⟦⟧T _ ∘ (e₂ [ γC ]))
≈⟨ beta/=> _ _ ⟩
(to/⟦⟧T _ ∘ eval′ ∘ (var ⁂ from/⟦⟧T _)) [ ext ! (pair (var [ weaken ]) var) ] [ ext ! (e₁ [ γC ]) ×id′ ] [ ext _⊨_.id (to/⟦⟧T _ ∘ (e₂ [ γC ])) ]
≈⟨ refl ⟩
(to/⟦⟧T _ ∘ (eval ∘ Prod.repack product product) ∘ (var ⁂ from/⟦⟧T _)) [ ext ! (pair (var [ weaken ]) var) ] [ ext ! (e₁ [ γC ]) ×id′ ] [ ext _⊨_.id (to/⟦⟧T _ ∘ (e₂ [ γC ])) ]
≈⟨ cong/sub refl (cong/sub refl (cong/sub refl (∘-resp-≈ʳ (∘-resp-≈ˡ (elimʳ η))))) ⟩
(to/⟦⟧T _ ∘ (app (fst var) (snd var)) ∘ (var ⁂ from/⟦⟧T _)) [ ext ! (pair (var [ weaken ]) var) ] [ ext ! (e₁ [ γC ]) ×id′ ] [ ext _⊨_.id (to/⟦⟧T _ ∘ (e₂ [ γC ])) ]
≈˘⟨ sub/∙ ⟩
(to/⟦⟧T _ ∘ (app (fst var) (snd var)) ∘ (var ⁂ from/⟦⟧T _)) [ ext ! (pair (var [ weaken ]) var) ] [ ext ! (e₁ [ γC ]) ×id′ ∙ ext _⊨_.id (to/⟦⟧T _ ∘ (e₂ [ γC ])) ]
≈⟨ cong/sub (×id′-ext) refl ⟩
(to/⟦⟧T _ ∘ (app (fst var) (snd var)) ∘ (var ⁂ from/⟦⟧T _)) [ ext ! (pair (var [ weaken ]) var) ] [ ext (ext ! (e₁ [ γC ]) ∙ _⊨_.id) (to/⟦⟧T _ ∘ (e₂ [ γC ])) ]
≈⟨ cong/sub (cong/ext id∙ʳ refl) refl ⟩
(to/⟦⟧T _ ∘ (app (fst var) (snd var)) ∘ (var ⁂ from/⟦⟧T _)) [ ext ! (pair (var [ weaken ]) var) ] [ ext (ext ! (e₁ [ γC ])) (to/⟦⟧T _ ∘ (e₂ [ γC ])) ]
≈˘⟨ sub/∙ ⟩
(to/⟦⟧T _ ∘ (app (fst var) (snd var)) ∘ (var ⁂ from/⟦⟧T _)) [ ext ! (pair (var [ weaken ]) var) ∙ ext (ext ! (e₁ [ γC ])) (to/⟦⟧T _ ∘ (e₂ [ γC ])) ]
≈⟨ cong/sub (trans ext∙ (cong/ext (sym !-unique) refl)) refl ⟩
(to/⟦⟧T _ ∘ (app (fst var) (snd var)) ∘ (var ⁂ from/⟦⟧T _)) ∘ (pair (var [ weaken ]) var [ ext (ext ! (e₁ [ γC ])) (to/⟦⟧T _ ∘ (e₂ [ γC ])) ])
≈⟨ ∘-resp-≈ʳ (trans comm/pair (cong/pair (trans (sym sub/∙) (cong/sub weaken/ext refl)) (var/ext _ _))) ⟩
(to/⟦⟧T _ ∘ (app (fst var) (snd var)) ∘ (var ⁂ from/⟦⟧T _)) ∘ (pair (var [ (ext ! (e₁ [ γC ])) ]) (to/⟦⟧T _ ∘ (e₂ [ γC ])))
≈⟨ ∘-resp-≈ʳ (cong/pair (var/ext _ _) refl) ⟩
(to/⟦⟧T _ ∘ (app (fst var) (snd var)) ∘ (var ⁂ from/⟦⟧T _)) ∘ (pair (e₁ [ γC ]) (to/⟦⟧T _ ∘ (e₂ [ γC ])))
≈⟨ pull-last ⁂∘⟨⟩ ⟩
to/⟦⟧T _ ∘ (app (fst var) (snd var)) ∘ (pair (var ∘ (e₁ [ γC ])) (from/⟦⟧T _ ∘ to/⟦⟧T _ ∘ (e₂ [ γC ])))
≈⟨ ∘-resp-≈ʳ (cong/sub (cong/ext refl (cong/pair identityˡ (cancelˡ from∘to))) refl) ⟩
to/⟦⟧T _ ∘ (app (fst var) (snd var)) ∘ (pair (e₁ [ γC ]) (e₂ [ γC ]))
≈⟨ ∘-resp-≈ʳ (trans comm/app (cong/app (trans comm/fst (trans (cong/fst (var/ext _ _)) (beta/*₁ _ _))) (trans comm/snd (trans (cong/snd (var/ext _ _)) (beta/*₂ _ _))))) ⟩
to/⟦⟧T _ ∘ (app (e₁ [ γC ]) (e₂ [ γC ]))
≈˘⟨ ∘-resp-≈ʳ (comm/app) ⟩
to/⟦⟧T _ ∘ (app e₁ e₂ [ γC ])
∎
where
curry : _ -> _
curry e = abs (e [ ext ! (pair (var [ weaken ]) var) ])
helper {e = e [ γ ]} =
begin
⟦ e ⟧ ∘ ⟦ γ ⟧S
≈⟨ pushˡ (helper {e = e}) ⟩
to/⟦⟧T _ ∘ (e [ γC ]) ∘ ⟦ γ ⟧S
≈⟨ refl ⟩
to/⟦⟧T _ ∘ (e [ γC ] [ ext ! ⟦ γ ⟧S ])
≈˘⟨ ∘-resp-≈ʳ sub/∙ ⟩
to/⟦⟧T _ ∘ (e [ γC ∙ ext ! ⟦ γ ⟧S ])
≈⟨ ∘-resp-≈ʳ (cong/sub (helperS {γ = γ}) refl) ⟩
to/⟦⟧T _ ∘ (e [ γ ∙ γC ])
≈⟨ ∘-resp-≈ʳ sub/∙ ⟩
to/⟦⟧T _ ∘ (e [ γ ] [ γC ])
∎
helperS {γ = id} = trans (trans (cong/∙ refl (cong/ext !-unique refl)) (trans (cong/∙ refl η-pair) id∙ʳ)) (sym id∙ˡ)
helperS {γ = γ ∙ γ₁} =
S.begin
γC ∙ ext ! (⟦ γ ⟧S ∘ ⟦ γ₁ ⟧S)
S.≈˘⟨ cong/∙ refl (trans ext∙ (cong/ext (sym !-unique) refl)) ⟩
γC ∙ (ext ! ⟦ γ ⟧S ∙ ext ! ⟦ γ₁ ⟧S)
S.≈˘⟨ assoc∙ ⟩
(γC ∙ ext ! ⟦ γ ⟧S) ∙ ext ! ⟦ γ₁ ⟧S
S.≈⟨ cong/∙ (helperS {γ = γ}) refl ⟩
(γ ∙ γC) ∙ ext ! ⟦ γ₁ ⟧S
S.≈⟨ assoc∙ ⟩
γ ∙ (γC ∙ ext ! ⟦ γ₁ ⟧S)
S.≈⟨ cong/∙ refl (helperS {γ = γ₁}) ⟩
γ ∙ (γ₁ ∙ γC)
S.≈˘⟨ assoc∙ ⟩
(γ ∙ γ₁) ∙ γC
S.∎
where import Relation.Binary.Reasoning.Setoid SubstSetoid as S
helperS {γ = weaken} = sym weaken/ext
helperS {γ = ext γ e} =
S.begin
γC {_ ∷ _} ∙ (ext ! ⟨ ⟦ γ ⟧S , ⟦ e ⟧ ⟩)
S.≡⟨⟩
ext (γC ∙ ext ! π₁) (from/⟦⟧T _ ∘ π₂) ∙ (ext ! ⟨ ⟦ γ ⟧S , ⟦ e ⟧ ⟩)
S.≈⟨ ext∙ ⟩
ext ((γC ∙ ext ! π₁) ∙ (ext ! ⟨ ⟦ γ ⟧S , ⟦ e ⟧ ⟩)) ((from/⟦⟧T _ ∘ π₂) ∘ ⟨ ⟦ γ ⟧S , ⟦ e ⟧ ⟩)
S.≈⟨ cong/ext assoc∙ (pullʳ project₂) ⟩
ext (γC ∙ (ext ! π₁ ∙ (ext ! ⟨ ⟦ γ ⟧S , ⟦ e ⟧ ⟩))) (from/⟦⟧T _ ∘ ⟦ e ⟧)
S.≈⟨ cong/ext (cong/∙ refl (trans ext∙ (cong/ext (sym !-unique) refl))) refl ⟩
ext (γC ∙ (ext ! (π₁ [ ext ! ⟨ ⟦ γ ⟧S , ⟦ e ⟧ ⟩ ]))) (from/⟦⟧T _ ∘ ⟦ e ⟧)
S.≈⟨ cong/ext (cong/∙ refl (cong/ext refl project₁)) refl ⟩
ext (γC ∙ ext ! ⟦ γ ⟧S) (from/⟦⟧T _ ∘ ⟦ e ⟧)
S.≈⟨ cong/ext (helperS {γ = γ}) (sym (switch-tofromˡ Iso/⟦⟧T (sym (helper {e = e})))) ⟩
ext (γ ∙ γC) (e [ γC ])
S.≈˘⟨ ext∙ ⟩
ext γ e ∙ γC
S.∎
where import Relation.Binary.Reasoning.Setoid SubstSetoid as S
helperS {γ = !} = trans (sym !-unique) !-unique
satisfyAxiom : forall {Γ} {A} {e₁ e₂ : Γ ⊢ A} -> Ax Γ A e₁ e₂ -> ⟦ e₁ ⟧ ≈ ⟦ e₂ ⟧
satisfyAxiom {Γ} {A} {e₁} {e₂} x = trans (helper {e = e₁}) (trans (∘-resp-≈ʳ a) (sym (helper {e = e₂})))
where
a : (e₁ [ γC ]) ≈ (e₂ [ γC ])
a = cong/sub refl (ax x)
M : Model Cl CC Th
M = S , satisfyAxiom
|
#ifndef __VSIM_COLLISION_SHAPE_HPP__
#define __VSIM_COLLISION_SHAPE_HPP__
#include <Eigen/Geometry>
#include <memory>
#include <vsim/env/pose.hpp>
#include <vsim/env/base_element.hpp>
#include <vsim/env/scene_fwd.hpp>
namespace vsim {
struct CollisionShape ;
typedef std::shared_ptr<CollisionShape> CollisionShapePtr ;
struct CollisionShape: public BaseElement {
public:
CollisionShape() = default ;
GeometryPtr geom_ ;
Pose pose_ ;
};
}
#endif
|
Formal statement is: proposition connected_Times: assumes S: "connected S" and T: "connected T" shows "connected (S \<times> T)" Informal statement is: If $S$ and $T$ are connected, then $S \times T$ is connected. |
State Before: R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type ?u.1058825
ha : a ≠ 0
⊢ degree (↑C a * X ^ 2 + ↑C b * X + ↑C c) = 2 State After: R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type ?u.1058825
ha : a ≠ 0
⊢ ↑2 = 2 Tactic: rw [add_assoc, degree_add_eq_left_of_degree_lt <| degree_linear_lt_degree_C_mul_X_sq ha,
degree_C_mul_X_pow 2 ha] State Before: R : Type u
S : Type v
a b c d : R
n m : ℕ
inst✝ : Semiring R
p q : R[X]
ι : Type ?u.1058825
ha : a ≠ 0
⊢ ↑2 = 2 State After: no goals Tactic: rfl |
module LightClick.IR.Channel.MicroSV.Intermediate
import Data.List
import Data.Vect
import Data.String
import Data.Vect.Sort
import Toolkit.Data.DList
import Toolkit.Data.DList.DeBruijn
import Toolkit.Data.DVect
import public Language.SystemVerilog.MetaTypes
import public Language.SystemVerilog.Gates
import public Language.SystemVerilog.Direction
import LightClick.Error
import LightClick.Types.Direction
import LightClick.IR.ModuleCentric
import LightClick.IR.ChannelCentric
import LightClick.IR.Channel.MicroSV.InterpTy
import LightClick.IR.Channel.MicroSV.Error
%default total
public export
data MicroSvIR : (lctxt : Context)
-> (type : Ty)
-> Type
where
End : MicroSvIR ctxt UNIT
Local : (label : String)
-> Index ctxt (label, type)
-> MicroSvIR ctxt type
Global : (label : String)
-> (ty : Ty)
-> MicroSvIR ctxt ty
Let : {typeE, ty : Ty}
-> (this : String)
-> (beThis : MicroSvIR ctxt typeE)
-> (withType : MicroSvIR ctxt ty)
-> (inThis : MicroSvIR ((this,typeE)::ctxt) typeB)
-> MicroSvIR ctxt typeB
Seq : {typeA, typeB : Ty}
-> MicroSvIR ctxt typeA
-> MicroSvIR ctxt typeB
-> MicroSvIR ctxt typeB
TYPE : MicroSvIR ctxt TYPE
GATE : MicroSvIR ctxt GATE
-- Decls
DataLogic : MicroSvIR ctxt DATA
DataArray : (type : MicroSvIR ctxt DATA) -> (size : Nat) -> MicroSvIR ctxt DATA
DataStruct : {n : Nat} -> (xs : Vect (S n) (Pair String (MicroSvIR ctxt DATA)))
-> MicroSvIR ctxt DATA
DataUnion : {n : Nat} -> (xs : Vect (S n) (Pair String (MicroSvIR ctxt DATA)))
-> MicroSvIR ctxt DATA
Port : (label : String)
-> (dir : SystemVerilog.Direction.Direction)
-> (type : MicroSvIR ctxt DATA)
-> MicroSvIR ctxt (PORT label)
MDecl : DList String (\s => MicroSvIR ctxt (PORT s)) names
-> MicroSvIR ctxt (MODULE names)
-- Ctors
NewChan : MicroSvIR ctxt CHAN
NewModule : List (Pair String (MicroSvIR ctxt CHAN))
-> MicroSvIR ctxt (MINST names)
-- Gates
Not : (out : MicroSvIR ctxt CHAN)
-> (ins : MicroSvIR ctxt CHAN)
-> MicroSvIR ctxt GINST
Gate : {n : Nat}
-> (type : TyGateComb)
-> (out : MicroSvIR ctxt CHAN)
-> (ins : Vect (S (S n)) (MicroSvIR ctxt CHAN))
-> MicroSvIR ctxt GINST
export
getType : {type : Ty} -> MicroSvIR ctxt type -> Ty
getType {type} _ = type
public export
data Decl : Ty -> Type where
MkDecl : {type : Ty} -> String -> MicroSvIR Nil type -> Decl type
public export
Decls : List Ty -> Type
Decls = DList Ty Decl
-- Could turn into a triple/custom data type to collect proof that the `type` is valid for a declaration
export
lookup : String -> Decls ty -> Maybe Ty
lookup x [] = Nothing
lookup x (MkDecl y expr :: rest) with (decEq x y)
lookup x (MkDecl x expr :: rest) | (Yes Refl) = Just $ getType expr
lookup x (MkDecl y expr :: rest) | (No contra) = lookup x rest
public export
data MicroSvIrSpec : Type where
MkMSVIRSpec : (decls : Decls types)
-> (expr : MicroSvIR Nil UNIT)
-> MicroSvIrSpec
data TEnv : (local : context) -> Type where
MkTEnv : {types : List Ty}
-> (decls : Decls types)
-> (local : Context)
-> TEnv local
data TRes : (local : Context) -> (type : TyIR) -> Type where
MkTRes : {type : Ty}
-> {types : List Ty}
-> {tyIR : TyIR}
-> (decls : Decls types)
-> (expr : MicroSvIR ctxt type)
-> (prf : InterpTy tyIR type)
-> TRes ctxt tyIR
TFuncSig : (local : Context) -> TyIR -> Type
TFuncSig local type =
(env : TEnv local)
-> (expr : ChannelIR type)
-> Either TError (TRes local type)
%inline
port : (f : TFuncSig local PORT)
-> (e : TEnv local)
-> (p : ChannelIR PORT)
-> Either TError (s ** MicroSvIR local (PORT s))
port f e p with (f e p)
port f e p | (Left l) = Left l
port f e p | (Right (MkTRes decls (Port l dir type) (PP l))) = Right (_ ** Port l dir type)
port f e p | (Right (MkTRes decls _ (PP l))) = Left (General $ "Port Expected")
ports : (f : TFuncSig local PORT)
-> (e : TEnv local)
-> (ps : Vect (S n) (ChannelIR PORT))
-> Either TError (ns ** DList String (\s => MicroSvIR local (PORT s)) ns)
ports f e (x :: xs)
= do x' <- port f e x
xs' <- ports' f e xs
pure (_ ** (snd x') :: (snd xs'))
where
ports' : (f : TFuncSig local PORT)
-> (e : TEnv local)
-> (ps : Vect y (ChannelIR PORT))
-> Either TError (ns ** DList String (\s => MicroSvIR local (PORT s)) ns)
ports' f e [] = pure (_ ** Nil)
ports' f e (x :: xs) =
do x' <- port f e x
xs' <- ports' f e xs
pure (_ ** (snd x') :: (snd xs'))
%inline
chan : (f : TFuncSig local CHAN)
-> (e : TEnv local)
-> (c : (String, ChannelIR CHAN))
-> Either TError (String, MicroSvIR local CHAN)
chan f e (l,c) with (f e c)
chan f e (l,c) | (Left err) = Left $ Nested "Attempted to convert chan" err
chan f e (l,c) | (Right (MkTRes decls expr CC)) = Right (l,expr)
chans : (f : TFuncSig local CHAN)
-> (e : TEnv local)
-> (cs : Vect (S n) (String, ChannelIR CHAN))
-> Either TError (List (String, (MicroSvIR local CHAN)))
chans f e (x :: xs)
= do x' <- chan f e x
xs' <- chans' f e xs
pure (x'::xs')
where
chans' : (f : TFuncSig local CHAN)
-> (e : TEnv local)
-> (cs : Vect y (String, ChannelIR CHAN))
-> Either TError (List (String, (MicroSvIR local CHAN)))
chans' f e [] = pure Nil
chans' f e (x :: xs) =
do x' <- chan f e x
xs' <- chans' f e xs
pure (x'::xs')
%inline
chan' : (f : TFuncSig local CHAN)
-> (e : TEnv local)
-> (c : ChannelIR CHAN)
-> Either TError (MicroSvIR local CHAN)
chan' f e c with (f e c)
chan' f e c | (Left err) = Left $ Nested "Attempted to convert chan" err
chan' f e c | (Right (MkTRes decls expr CC)) = Right expr
%inline
kvpair : (f : TFuncSig local DATA)
-> (e : TEnv local)
-> (c : (String, ChannelIR DATA))
-> Either TError (String, MicroSvIR local DATA)
kvpair f e (l,c) with (f e c)
kvpair f e (l,c) | (Left err) = Left $ Nested "Attempted to convert KVPair" err
kvpair f e (l,c) | (Right (MkTRes decls expr DD)) = Right (l,expr)
Eq (ChannelIR PORT) where
(==) (CPort x f d) (CPort y g e) = x == y
(==) _ _ = False
Ord (ChannelIR PORT) where
compare (CPort x f d) (CPort y g e) = compare x y
compare _ _ = LT
covering
convert : {type : TyIR}
-> {local : Context}
-> (e : TEnv local)
-> (c : ChannelIR type)
-> Either TError (TRes local type)
-- [ References ]
convert e (CRef x type) with (e)
convert e (CRef x type) | (MkTEnv decls local) with (isIndex x local)
convert e (CRef x type) | (MkTEnv decls local) | (Yes (ty ** idx)) with (interpTy type ty)
convert e (CRef x type) | (MkTEnv decls local) | (Yes (ty ** idx)) | (Yes prf) =
pure (MkTRes decls (Local x idx) prf)
convert e (CRef x type) | (MkTEnv decls local) | (Yes (ty ** idx)) | (No contra) =
Left $ General (unwords ["Attempting to construct Local", show x])
convert e (CRef x type) | (MkTEnv decls local) | (No contra) with (lookup x decls)
convert e (CRef x type) | (MkTEnv decls local) | (No contra) | Nothing
= Left $ General (unwords ["Attempting to construct global, identifier not found", show x])
convert e (CRef x type) | (MkTEnv decls local) | (No contra) | Just ty with (interpTy type ty)
convert e (CRef x type) | (MkTEnv decls local) | (No contra) | Just ty | (Yes prf)
= pure (MkTRes decls (Global x ty) prf)
convert e (CRef x type) | (MkTEnv decls local) | (No contra) | Just ty | (No contra')
= Left $ General (unwords ["Attempting to construct Global type issue", show x])
-- [ NOTE ] traverse decls and extra ty to do proof. will formalise later.
-- [ Structural Statements ]
---- [ Let Bindings ]
---- Is `this` bindable and if so then how
convert e (CLet bind this {term} inThis) with (isBindable term)
{- [ Translate the Global Bindings]
- Extend global declarations with result, assume that the expr is closed
- Translate `inThis`
-}
convert e (CLet bind this {term = term} inThis) | (IsDecl prfDecl) with (e)
convert e (CLet bind this {term = term} inThis) | (IsDecl prfDecl) | (MkTEnv decls local) with (convert (MkTEnv decls Nil) this)
convert e (CLet bind this {term = term} inThis) | (IsDecl prfDecl) | (MkTEnv decls local) | (Left l)
= Left $ Nested "Attempting to construct global declaration" l
convert e (CLet bind this {term = term} inThis) | (IsDecl prfDecl) | (MkTEnv decls local) | (Right (MkTRes rest expr prf))
= convert (MkTEnv (MkDecl bind expr::rest) local) inThis
{- [ Translate the local bindings ]
Convert the `this` and `inThis` before constructing the type of `this`.
-}
convert e (CLet bind this {term = term} inThis) | (IsLet x) with (e)
convert e (CLet bind this {term = term} inThis) | (IsLet x) | (MkTEnv decls local) with (convert (MkTEnv decls local) this)
convert e (CLet bind this {term = term} inThis) | (IsLet x) | (MkTEnv decls local) | (Left l)
= Left $ Nested "Attempting to this of local let" l
convert e (CLet bind this {term = term} inThis) | (IsLet x) | (MkTEnv decls local) | (Right (MkTRes rest expr prf)) with (Intermediate.convert (MkTEnv decls ((bind, getType expr)::local)) inThis)
convert e (CLet bind this {term = term} inThis) | (IsLet x) | (MkTEnv decls local) | (Right (MkTRes rest expr prf)) | (Left l) = Left $ Nested "Attempting to construct body of Local Let" l
-- MicroSV is typed, we need to introspect `this` again because we need to get the type.
convert e (CLet bind this {term = term} inThis) | (IsLet x) | (MkTEnv decls local) | (Right (MkTRes rest expr prf)) | (Right (MkTRes y z w)) with (x)
{- [ Translating Module instantiations ]
When MINST
- the type is the name/ref to the module
- the value is the result of translating `this`
-}
convert e (CLet bind this {term = CONN} inThis) | (IsLet x) | (MkTEnv decls local) | (Right (MkTRes rest expr prf)) | (Right (MkTRes y z w)) | IsInstM with (this)
convert e (CLet bind this {term = CONN} inThis) | (IsLet x) | (MkTEnv decls local) | (Right (MkTRes rest expr prf)) | (Right (MkTRes y z w)) | IsInstM | (CModuleInst mtype _) with (Intermediate.convert e mtype)
convert e (CLet bind this {term = CONN} inThis) | (IsLet x) | (MkTEnv decls local) | (Right (MkTRes rest expr prf)) | (Right (MkTRes y z w)) | IsInstM | (CModuleInst mtype _) | Left l
= Left $ Nested "Cannot construct type for local let module" l
convert e (CLet bind this {term = CONN} inThis) | (IsLet x) | (MkTEnv decls local) | (Right (MkTRes rest expr prf)) | (Right (MkTRes y z w)) | IsInstM | (CModuleInst mtype _) | Right (MkTRes _ newMType prfType)
= pure (MkTRes y (Let bind expr newMType z) w)
convert e (CLet bind this {term = CONN} inThis) | (IsLet x) | (MkTEnv decls local) | (Right (MkTRes rest expr prf)) | (Right (MkTRes y z w)) | IsInstM | _
= Left $ General "Expected local let `this` to be CModuleInst, it wasn't"
{- [ Translating Channel terms ]
When CHAN
- the type is var or inline data type
- the value is `NewChan`
-}
convert e (CLet bind this {term = CHAN} inThis) | (IsLet x) | (MkTEnv decls local) | (Right (MkTRes rest expr prf)) | (Right (MkTRes y z w)) | IsInstC with (this)
convert e (CLet bind this {term = CHAN} inThis) | (IsLet x) | (MkTEnv decls local) | (Right (MkTRes rest expr prf)) | (Right (MkTRes y z w)) | IsInstC | (CChan dtype) with (convert e dtype)
convert e (CLet bind this {term = CHAN} inThis) | (IsLet x) | (MkTEnv decls local) | (Right (MkTRes rest expr prf)) | (Right (MkTRes y z w)) | IsInstC | (CChan dtype) | Left l
= Left $ Nested "Attempting to construct this from local let chan" l
convert e (CLet bind this {term = CHAN} inThis) | (IsLet x) | (MkTEnv decls local) | (Right (MkTRes rest expr prf)) | (Right (MkTRes y z w)) | IsInstC | (CChan dtype) | (Right (MkTRes _ newDType prfType))
= pure (MkTRes y (Let bind expr newDType z) w)
convert e (CLet bind this {term = CHAN} inThis) | (IsLet x) | (MkTEnv decls local) | (Right (MkTRes rest expr prf)) | (Right (MkTRes y z w)) | IsInstC | _
= Left $ General "Expected local let `this` to be CChan, it wasn't"
{- [ Translating Gate terms ]
When GATE
- the type is var or inline data type
- the value is another gate.
-}
convert e (CLet bind this {term = GATE} inThis) | (IsLet x) | (MkTEnv decls local) | (Right (MkTRes rest expr prf)) | (Right (MkTRes y z w)) | IsInstG with (this)
convert e (CLet bind this {term = GATE} inThis) | (IsLet x) | (MkTEnv decls local) | (Right (MkTRes rest expr prf)) | (Right (MkTRes y z w)) | IsInstG | (CNot o i) with (convert e (CNot o i))
convert e (CLet bind this {term = GATE} inThis) | (IsLet x) | (MkTEnv decls local) | (Right (MkTRes rest expr prf)) | (Right (MkTRes y z w)) | IsInstG | (CNot o i) | Left l
= Left $ Nested "Attempting to construct this from local let not gate" l
convert e (CLet bind this {term = GATE} inThis) | (IsLet x) | (MkTEnv decls local) | (Right (MkTRes rest expr prf)) | (Right (MkTRes y z w)) | IsInstG | (CNot o i) | Right (MkTRes _ newNot prfType)
= Right (MkTRes y (Let bind expr GATE z) w)
convert e (CLet bind this {term = GATE} inThis) | (IsLet x) | (MkTEnv decls local) | (Right (MkTRes rest expr prf)) | (Right (MkTRes y z w)) | IsInstG | (CGate ty o ins) with (convert e (CGate ty o ins))
convert e (CLet bind this {term = GATE} inThis) | (IsLet x) | (MkTEnv decls local) | (Right (MkTRes rest expr prf)) | (Right (MkTRes y z w)) | IsInstG | (CGate ty o ins) | Left l
= Left $ Nested "Attempting to construct this from local let gate gate" l
convert e (CLet bind this {term = GATE} inThis) | (IsLet x) | (MkTEnv decls local) | (Right (MkTRes rest expr prf)) | (Right (MkTRes y z w)) | IsInstG | (CGate ty o ins) | Right (MkTRes _ newNot prfType)
= Right (MkTRes y (Let bind expr GATE z) w)
convert e (CLet bind this {term = GATE} inThis) | (IsLet x) | (MkTEnv decls local) | (Right (MkTRes rest expr prf)) | (Right (MkTRes y z w)) | IsInstG | _
= Left $ General "Expected local let `this` to be a Gate, it wasn't" --
-- Any other pattern here is unexpected.
convert e (CLet bind this {term = term} inThis) | Unbindable = Left $ General "We were given something unbindable"
---- [ Sequencing ]
convert (MkTEnv decls local) (CSeq x y) with (convert (MkTEnv decls local) x)
convert (MkTEnv decls local) (CSeq x y) | Left err = Left $ Nested "Left Sequent failed" err
convert (MkTEnv decls local) (CSeq x y) | Right (MkTRes declsX x' prfX) with (convert (MkTEnv declsX local) y)
convert (MkTEnv decls local) (CSeq x y) | Right (MkTRes declsX x' prfX) | Left err
= Left $ Nested "Right sequant failed" err
convert (MkTEnv decls local) (CSeq x y) | Right (MkTRes declsX x' prfX) | Right (MkTRes declsY y' prfY) =
pure (MkTRes declsY (Seq x' y') prfY)
---- [ This is the End ]
convert e CEnd with (e)
convert e CEnd | (MkTEnv decls local) = pure (MkTRes decls End UU)
-- [ Module Declarations ]
convert e (CPort l d type) with (convert e type)
convert e (CPort l d type) | Left err
= Left $ Nested "Attempting to construct type for Port" err
convert e (CPort l d type) | (Right (MkTRes decls t' DD))
= pure (MkTRes decls (Port l (interpDir d) t') (PP l))
convert e (CModule {n} xs) with (ports convert e (sort xs))
convert e (CModule {n} xs) | (Left l)
= Left $ Nested "Attempting to construct ports for Module Declaration" l
convert e (CModule {n} xs) | (Right (ns ** ps)) with (e)
convert e (CModule {n} xs) | (Right (ns ** ps)) | (MkTEnv decls local)
= pure (MkTRes decls (MDecl ps) (MM ns))
-- [ Data Declarations ]
convert (MkTEnv decls local) CDataLogic = pure (MkTRes decls DataLogic DD)
convert e (CDataArray type k) with (convert e type)
convert e (CDataArray type k) | Left l
= Left $ Nested "Attempting to construct Data Type for array" l
convert e (CDataArray type k) | Right res with (res)
convert e (CDataArray type k) | Right res | (MkTRes decls type' DD)
= pure (MkTRes decls (DataArray type' k) DD)
convert e (CDataStruct xs) with (e)
convert e (CDataStruct xs) | (MkTEnv decls local)
= do xs' <- traverse (kvpair convert e) xs
pure (MkTRes decls (DataStruct xs') DD)
convert e (CDataUnion xs) with (e)
convert e (CDataUnion xs) | (MkTEnv decls local)
= do xs' <- traverse (kvpair convert e) xs
pure (MkTRes decls (DataUnion xs') DD)
-- [ A Thing that should not exist in 'Our Normal Form' ]
convert e (CIDX label x y)
= Left $ Nested "IDX Not expected" MalformedExpr
-- [ Constructors for Channels and Modules ]
convert e (CChan _) with (e)
convert e (CChan _) | (MkTEnv decls local)
= pure $ MkTRes decls NewChan CC
convert e (CModuleInst _ kvs) with (e)
convert e (CModuleInst _ kvs) | (MkTEnv decls local)
= do xs' <- chans convert e kvs
let ns = map fst xs'
pure (MkTRes decls (NewModule xs') (CM (sort ns)))
-- [ Gates ]
convert e (CNot o i) with (e)
convert e (CNot o i) | (MkTEnv decls local)
= do o' <- chan' convert e o
i' <- chan' convert e i
pure (MkTRes decls (Not o' i') GG)
convert e (CGate ty o ins) with (e)
convert e (CGate ty o ins) | (MkTEnv decls local)
= do o' <- chan' convert e o
is' <- traverse (chan' convert e) ins
pure (MkTRes decls (Gate ty o' is') GG)
export
covering
runConvert : (c : ChannelIR UNIT)
-> Either TError MicroSvIrSpec
runConvert expr with (convert (MkTEnv Nil Nil) expr)
runConvert expr | Left l
= Left $ Nested "Cannot consruct spec" l
runConvert expr | Right (MkTRes decls expr' UU)
= Right (MkMSVIRSpec decls expr')
-- --------------------------------------------------------------------- [ EOF ]
|
# Logistic Regression
Notebook version: 2.0 (Nov 21, 2017)
2.1 (Oct 19, 2018)
2.2 (Oct 09, 2019)
2.3 (Oct 27, 2020)
Author: Jesús Cid Sueiro ([email protected])
Jerónimo Arenas García ([email protected])
Changes: v.1.0 - First version
v.1.1 - Typo correction. Prepared for slide presentation
v.2.0 - Prepared for Python 3.0 (backcompmatible with 2.7)
Assumptions for regression model modified
v.2.1 - Minor changes regarding notation and assumptions
v.2.2 - Updated notation
v.2.3 - Improved slides format. Backward compatibility removed
```python
# To visualize plots in the notebook
%matplotlib inline
# Imported libraries
import csv
import random
import matplotlib
import matplotlib.pyplot as plt
import pylab
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from sklearn.preprocessing import PolynomialFeatures
from sklearn import linear_model
```
## 1. Introduction
### 1.1. Binary classification
The **goal** of a classification problem is to assign a *class* or *category* to every *instance* or *observation* of a data collection.
Here, we will assume that
* every instance ${\bf x}$ is an $N$-dimensional vector in $\mathbb{R}^N$, and
* the class $y$ of sample ${\bf x}$ is an element of a binary set ${\mathcal Y} = \{0, 1\}$.
The goal of a classifier is to predict the true value of $y$ after observing ${\bf x}$.
We will denote as $\hat{y}$ the classifier output or **decision**. If $y=\hat{y}$, the decision is a **hit**, otherwise $y\neq \hat{y}$ and the decision is an **error**.
### 1.2. Decision theory: the MAP criterion
**Decision theory** provides a solution to the classification problem in situations where the relation between instance ${\bf x}$ and its class $y$ is given by a known probabilistic model.
Assume that every tuple $({\bf x}, y)$ is an outcome of a random vector $({\bf X}, Y)$ with joint distribution $p_{{\bf X},Y}({\bf x}, y)$. A natural criteria for classification is to select predictor $\hat{Y}=f({\bf x})$ in such a way that the **probability or error**, $P\{\hat{Y} \neq Y\}$ is minimum.
Noting that
$$
P\{\hat{Y} \neq Y\} = \int P\{\hat{Y} \neq Y | {\bf x}\} p_{\bf X}({\bf x}) d{\bf x}
$$
the optimal decision maker should take, for every sample ${\bf x}$, the decision minimizing the **conditional error probability**:
\begin{align}
\hat{y}^* &= \arg\min_{\hat{y}} P\{Y \neq \hat{y} |{\bf x}\} \\
&= \arg\max_{\hat{y}} P\{Y = \hat{y} |{\bf x}\} \\
\end{align}
Thus, the **optimal decision rule** can be expressed as
$$
P_{Y|{\bf X}}(1|{\bf x}) \quad\mathop{\gtrless}^{\hat{y}=1}_{\hat{y}=0}\quad P_{Y|{\bf X}}(0|{\bf x})
$$
or, equivalently
$$
P_{Y|{\bf X}}(1|{\bf x}) \quad\mathop{\gtrless}^{\hat{y}=1}_{\hat{y}=0}\quad \frac{1}{2}
$$
The classifier implementing this decision rule is usually referred to as the MAP (*Maximum A Posteriori*) classifier. As we have seen, the MAP classifier minimizes the error probability for binary classification, but the result can also be generalized to multiclass classification problems.
### 1.3. Learning
**Classical decision theory** is grounded on the assumption that the probabilistic model relating the observed sample ${\bf X}$ and the true hypothesis $Y$ is known.
Unfortunately, this is unrealistic in many applications, where the only available information to construct the classifier is a **dataset** $\mathcal D = \{{\bf x}_k, y_k\}_{k=0}^{K-1}$ of instances and their respective class labels.
A more realistic formulation of the classification problem is the following: given a dataset $\mathcal D = \{({\bf x}_k, y_k) \in {\mathbb{R}}^N \times {\mathcal Y}, \, k=0,\ldots,{K-1}\}$ of independent and identically distributed (i.i.d.) samples from an ***unknown*** distribution $p_{{\bf X},Y}({\bf x}, y)$, predict the class $y$ of a new sample ${\bf x}$ with the minimum probability of error.
### 1.4. Parametric classifiers
Since the probabilistic model generating the data is unknown, the MAP decision rule cannot be applied. However, we can use the dataset to **estimate the a posterior class probability model**, and apply it to approximate the MAP decision maker.
**Parametric classifiers** based on this idea assume, additionally, that the posterior class probabilty satisfies some parametric formula:
$$
P_{Y|X}(1|{\bf x},{\bf w}) = f_{\bf w}({\bf x})
$$
where ${\bf w}$ is a vector of parameters. Given the expression of the MAP decision maker, classification consists in comparing the value of $f_{\bf w}({\bf x})$ with the threshold $\frac{1}{2}$, and each parameter vector would be associated to a different decision maker.
In practice, the dataset ${\mathcal D}$ is used to select a particular parameter vector $\hat{\bf w}$ according to certain criterion. Accordingly, the decision rule becomes
$$
f_{\hat{\bf w}}({\bf x}) \quad\mathop{\gtrless}^{\hat{y}=1}_{\hat{y}=0}\quad \frac{1}{2}
$$
In this notebook, we explore one of the most popular model-based parametric classification methods: **logistic regression**.
## 2. Logistic regression.
### 2.1. The logistic function
The **logistic regression model** assumes that the binary class label $Y \in \{0,1\}$ of observation $X\in \mathbb{R}^N$ satisfies the expression.
$$P_{Y|{\bf X}}(1|{\bf x}, {\bf w}) = g({\bf w}^\intercal{\bf x})$$
$$P_{Y|{\bf,X}}(0|{\bf x}, {\bf w}) = 1-g({\bf w}^\intercal{\bf x})$$
where ${\bf w}$ is a parameter vector and $g(·)$ is the **logistic** function, which is defined by
$$g(t) = \frac{1}{1+\exp(-t)}$$
The code below defines and plots the logistic function:
```python
# Define the logistic function
def logistic(t):
#<SOL>
return 1.0 / (1 + np.exp(-t))
#</SOL>
# Plot the logistic function
t = np.arange(-6, 6, 0.1)
z = logistic(t)
plt.plot(t, z)
plt.xlabel('$t$', fontsize=14)
plt.ylabel('$g(t)$', fontsize=14)
plt.title('The logistic function')
plt.grid()
```
It is straightforward to see that the logistic function has the following properties:
- **P1**: Probabilistic output: $\quad 0 \le g(t) \le 1$
- **P2**: Symmetry: $\quad g(-t) = 1-g(t)$
- **P3**: Monotonicity: $\quad g'(t) = g(t)\cdot [1-g(t)] \ge 0$
**Exercise 1**: Verify properties P2 and P3.
**Exercise 2**: Implement a function to compute the logistic function, and use it to plot such function in the inverval $[-6,6]$.
### 2.2. Classifiers based on the logistic model.
The MAP classifier under a logistic model will have the form
$$P_{Y|{\bf X}}(1|{\bf x}, {\bf w}) = g({\bf w}^\intercal{\bf x}) \quad\mathop{\gtrless}^{\hat{y}=1}_{\hat{y}=0} \quad \frac{1}{2} $$
Therefore
$$
2 \quad\mathop{\gtrless}^{\hat{y}=1}_{\hat{y}=0} \quad
1 + \exp(-{\bf w}^\intercal{\bf x}) $$
which is equivalent to
$${\bf w}^\intercal{\bf x}
\quad\mathop{\gtrless}^{\hat{y}=1}_{\hat{y}=0}\quad
0 $$
Thus, the classifiers based on the logistic model are given by **linear decision boundaries** passing through the origin, ${\bf x} = {\bf 0}$.
```python
# Weight vector:
w = [4, 8] # Try different weights
# Create a rectangular grid.
x_min = -1
x_max = 1
h = (x_max - x_min) / 200
xgrid = np.arange(x_min, x_max, h)
xx0, xx1 = np.meshgrid(xgrid, xgrid)
# Compute the logistic map for the given weights, and plot
Z = logistic(w[0]*xx0 + w[1]*xx1)
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(xx0, xx1, Z, cmap=plt.cm.copper)
ax.contour(xx0, xx1, Z, levels=[0.5], colors='b', linewidths=(3,))
plt.xlabel('$x_0$')
plt.ylabel('$x_1$')
ax.set_zlabel('P(1|x,w)')
plt.show()
```
The next code fragment represents the output of the same classifier, representing the output of the logistic function in the $x_0$-$x_1$ plane, encoding the value of the logistic function in the color map.
```python
CS = plt.contourf(xx0, xx1, Z)
CS2 = plt.contour(CS, levels=[0.5], colors='m', linewidths=(3,))
plt.xlabel('$x_0$')
plt.ylabel('$x_1$')
plt.colorbar(CS, ticks=[0, 0.5, 1])
plt.show()
```
### 3.3. Nonlinear classifiers.
The logistic model can be extended to construct non-linear classifiers by using **non-linear data transformations**. A general form for a nonlinear logistic regression model is
$$P_{Y|{\bf X}}(1|{\bf x}, {\bf w}) = g[{\bf w}^\intercal{\bf z}({\bf x})] $$
where ${\bf z}({\bf x})$ is an arbitrary nonlinear transformation of the original variables. The boundary decision in that case is given by equation
$$
{\bf w}^\intercal{\bf z} = 0
$$
**Exercise 3**: Modify the code above to generate a 3D surface plot of the polynomial logistic regression model given by
$$
P_{Y|{\bf X}}(1|{\bf x}, {\bf w}) = g(1 + 10 x_0 + 10 x_1 - 20 x_0^2 + 5 x_0 x_1 + x_1^2)
$$
```python
# Weight vector:
w = [1, 10, 10, -20, 5, 1] # Try different weights
# Create a regtangular grid.
x_min = -1
x_max = 1
h = (x_max - x_min) / 200
xgrid = np.arange(x_min, x_max, h)
xx0, xx1 = np.meshgrid(xgrid, xgrid)
# Compute the logistic map for the given weights
# Z = <FILL IN>
Z = logistic(w[0] + w[1]*xx0 + w[2]*xx1 + w[3]*xx0*xx0 + w[4]*xx0*xx1 + w[5]*xx1*xx1)
# Plot the logistic map
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(xx0, xx1, Z, cmap=plt.cm.copper)
plt.xlabel('$x_0$')
plt.ylabel('$x_1$')
ax.set_zlabel('P(1|x,w)')
plt.show()
```
```python
CS = plt.contourf(xx0, xx1, Z)
CS2 = plt.contour(CS, levels=[0.5], colors='m', linewidths=(3,))
plt.xlabel('$x_0$')
plt.ylabel('$x_1$')
plt.colorbar(CS, ticks=[0, 0.5, 1])
plt.show()
```
## 3. Inference
Remember that the idea of parametric classification is to use the training data set $\mathcal D = \{({\bf x}_k, y_k) \in {\mathbb{R}}^N \times \{0,1\}, k=0,\ldots,{K-1}\}$ to estimate ${\bf w}$. The estimate, $\hat{\bf w}$, can be used to compute the label prediction for any new observation as
$$\hat{y} = \arg\max_y P_{Y|{\bf X}}(y|{\bf x},\hat{\bf w}).$$
In this notebook, we will discuss two different approaches to the estimation of ${\bf w}$:
* **Maximum Likelihood** (ML): $\hat{\bf w}_{\text{ML}} = \arg\max_{\bf w} P_{{\mathcal D}|{\bf W}}({\mathcal D}|{\bf w})$
* **Maximum *A Posteriori** (MAP): $\hat{\bf w}_{\text{MAP}} = \arg\max_{\bf w} p_{{\bf W}|{\mathcal D}}({\bf w}|{\mathcal D})$
For the mathematical derivation of the logistic regression algorithm, the following representation of the logistic model will be useful: using the **symmetry** property of the logistic function, we can write
$$P_{Y|{\bf X}}(0|{\bf x}, {\bf w}) = 1-g\left({\bf w}^\intercal{\bf z}({\bf x})\right)
= g\left(-{\bf w}^\intercal{\bf z}({\bf x})\right)$$
thus
$$P_{Y|{\bf X}}(y|{\bf x}, {\bf w}) = g\left(\overline{y}{\bf w}^\intercal{\bf z}({\bf x})\right)$$
where $\overline{y} = 2y-1$ is a **symmetrized label** ($\overline{y}\in\{-1, 1\}$).
### 3.1. Model assumptions
In the following, we will make the following assumptions:
- **A1**. (Logistic Regression): We assume a logistic model for the *a posteriori* probability of ${Y}$ given ${\bf X}$, i.e.,
$$P_{Y|{\bf X}}(y|{\bf x}, {\bf w}) = g\left({\bar y}\cdot {\bf w}^\intercal{\bf z}({\bf x})\right).$$
- **A2**. All samples in ${\mathcal D}$ have been generated from the same distribution, $p_{{\bf X}, Y| {\bf W}}({\bf x}, y| {\bf w})$.
- **A3**. Input variables $\bf x$ do not depend on $\bf w$. This implies that $p({\bf x}|{\bf w}) = p({\bf x})$
- **A4**. Targets $y_0, \cdots, y_{K-1}$ are statistically independent given $\bf w$ and the inputs ${\bf x}_0, \cdots, {\bf x}_{K-1}$, that is:
$$P(y_0, \cdots, y_{K-1} | {\bf x}_0, \cdots, {\bf x}_{K-1}, {\bf w}) = \prod_{k=0}^{K-1} P(y_k | {\bf x}_k, {\bf w})$$
### 3.2. ML estimation.
The ML estimate is defined as
$$\hat{\bf w}_{\text{ML}} = \arg\max_{\bf w} P_{{\mathcal D}|{\bf W}}({\mathcal D}|{\bf w})$$
Ussing assumptions A2 and A3 above, we have that
\begin{align}
P_{{\mathcal D}|{\bf W}}({\mathcal D}|{\bf w}) & = p(y_0, \cdots, y_{K-1},{\bf x}_0, \cdots, {\bf x}_{K-1}| {\bf w}) \\
& = P(y_0, \cdots, y_{K-1}|{\bf x}_0, \cdots, {\bf x}_{K-1}, {\bf w}) \; p({\bf x}_0, \cdots, {\bf x}_{K-1}| {\bf w}) \\
& = P(y_0, \cdots, y_{K-1}|{\bf x}_0, \cdots, {\bf x}_{K-1}, {\bf w}) \; p({\bf x}_0, \cdots, {\bf x}_{K-1})\end{align}
Finally, using assumption A4, we can formulate the ML estimation of $\bf w$ as the resolution of the following **optimization problem**
\begin{align}
\hat {\bf w}_\text{ML} & = \arg \max_{\bf w} P(y_0, \cdots, y_{K-1}|{\bf x}_0, \cdots, {\bf x}_{K-1}, {\bf w}) \\
& = \arg \max_{\bf w} \prod_{k=0}^{K-1} P(y_k|{\bf x}_k, {\bf w}) \\
& = \arg \max_{\bf w} \sum_{k=0}^{K-1} \log P(y_k|{\bf x}_k, {\bf w}) \\
& = \arg \min_{\bf w} \sum_{k=0}^{K-1} - \log P(y_k|{\bf x}_k, {\bf w})
\end{align}
where the arguments of the maximization or minimization problems of the last three lines are usually referred to as the **likelihood**, **log-likelihood** $\left[L(\bf w)\right]$, and **negative log-likelihood** $\left[\text{NLL}(\bf w)\right]$, respectively.
Now, using A1 (the logistic model)
\begin{align}
\text{NLL}({\bf w})
&= - \sum_{k=0}^{K-1}\log\left[g\left(\overline{y}_k{\bf w}^\intercal {\bf z}_k\right)\right] \\
&= \sum_{k=0}^{K-1}\log\left[1+\exp\left(-\overline{y}_k{\bf w}^\intercal {\bf z}_k\right)\right]
\end{align}
where ${\bf z}_k={\bf z}({\bf x}_k)$.
It can be shown that $\text{NLL}({\bf w})$ is a **convex** and **differentiable** function of ${\bf w}$. Therefore, its minimum is a point with zero gradient.
\begin{align}
\nabla_{\bf w} \text{NLL}(\hat{\bf w}_{\text{ML}})
&= - \sum_{k=0}^{K-1}
\frac{\exp\left(-\overline{y}_k\hat{\bf w}_{\text{ML}}^\intercal {\bf z}_k\right) \overline{y}_k {\bf z}_k}
{1+\exp\left(-\overline{y}_k\hat{\bf w}_{\text{ML}}^\intercal {\bf z}_k
\right)} = \\
&= - \sum_{k=0}^{K-1} \left[y_k-g(\hat{\bf w}_{\text{ML}}^T {\bf z}_k)\right] {\bf z}_k = 0
\end{align}
Unfortunately, $\hat{\bf w}_{\text{ML}}$ cannot be taken out from the above equation, and some iterative optimization algorithm must be used to search for the minimum.
### 3.3. Gradient descent.
A simple iterative optimization algorithm is <a href = https://en.wikipedia.org/wiki/Gradient_descent> gradient descent</a>.
\begin{align}
{\bf w}_{n+1} = {\bf w}_n - \rho_n \nabla_{\bf w} \text{NLL}({\bf w}_n)
\end{align}
where $\rho_n >0$ is the *learning step*.
Applying the gradient descent rule to logistic regression, we get the following algorithm:
\begin{align}
{\bf w}_{n+1} &= {\bf w}_n
+ \rho_n \sum_{k=0}^{K-1} \left[y_k-g({\bf w}_n^\intercal {\bf z}_k)\right] {\bf z}_k
\end{align}
#### Gradient descent in matrix form
Defining vectors
\begin{align}
{\bf y} &= [y_0,\ldots,y_{K-1}]^\top \\
\hat{\bf p}_n &= [g({\bf w}_n^\top {\bf z}_0), \ldots, g({\bf w}_n^\top {\bf z}_{K-1})]^\top
\end{align}
and matrix
\begin{align}
{\bf Z} = \left[{\bf z}_0,\ldots,{\bf z}_{K-1}\right]^\top
\end{align}
we can write
\begin{align}
{\bf w}_{n+1} &= {\bf w}_n
+ \rho_n {\bf Z}^\top \left({\bf y}-\hat{\bf p}_n\right)
\end{align}
In the following, we will explore the behavior of the gradient descend method using the Iris Dataset.
```python
# Adapted from a notebook by Jason Brownlee
def loadDataset(filename, split):
xTrain, cTrain, xTest, cTest = [], [], [], []
with open(filename, 'r') as csvfile:
lines = csv.reader(csvfile)
dataset = list(lines)
for i in range(len(dataset)-1):
for y in range(4):
dataset[i][y] = float(dataset[i][y])
item = dataset[i]
if random.random() < split:
xTrain.append(item[0:4])
cTrain.append(item[4])
else:
xTest.append(item[0:4])
cTest.append(item[4])
return xTrain, cTrain, xTest, cTest
xTrain_all, cTrain_all, xTest_all, cTest_all = loadDataset('iris.data', 0.66)
nTrain_all = len(xTrain_all)
nTest_all = len(xTest_all)
print('Train:', nTrain_all)
print('Test:', nTest_all)
```
Train: 102
Test: 48
Now, we select two classes and two attributes.
```python
# Select attributes
i = 0 # Try 0,1,2,3
j = 1 # Try 0,1,2,3 with j!=i
# Select two classes
c0 = 'Iris-versicolor'
c1 = 'Iris-virginica'
# Select two coordinates
ind = [i, j]
# Take training test
X_tr = np.array([[xTrain_all[n][i] for i in ind] for n in range(nTrain_all)
if cTrain_all[n]==c0 or cTrain_all[n]==c1])
C_tr = [cTrain_all[n] for n in range(nTrain_all)
if cTrain_all[n]==c0 or cTrain_all[n]==c1]
Y_tr = np.array([int(c==c1) for c in C_tr])
n_tr = len(X_tr)
# Take test set
X_tst = np.array([[xTest_all[n][i] for i in ind] for n in range(nTest_all)
if cTest_all[n]==c0 or cTest_all[n]==c1])
C_tst = [cTest_all[n] for n in range(nTest_all)
if cTest_all[n]==c0 or cTest_all[n]==c1]
Y_tst = np.array([int(c==c1) for c in C_tst])
n_tst = len(X_tst)
```
#### 3.2.2. Data normalization
Normalization of data is a common pre-processing step in many machine learning algorithms. Its goal is to get a dataset where all input coordinates have a similar scale. Learning algorithms usually show less instabilities and convergence problems when data are normalized.
We will define a normalization function that returns a training data matrix with zero sample mean and unit sample variance.
```python
def normalize(X, mx=None, sx=None):
# Compute means and standard deviations
if mx is None:
mx = np.mean(X, axis=0)
if sx is None:
sx = np.std(X, axis=0)
# Normalize
X0 = (X-mx)/sx
return X0, mx, sx
```
Now, we can normalize training and test data. Observe in the code that **the same transformation should be applied to training and test data**. This is the reason why normalization with the test data is done using the means and the variances computed with the training set.
```python
# Normalize data
Xn_tr, mx, sx = normalize(X_tr)
Xn_tst, mx, sx = normalize(X_tst, mx, sx)
```
The following figure generates a plot of the normalized training data.
```python
# Separate components of x into different arrays (just for the plots)
x0c0 = [Xn_tr[n][0] for n in range(n_tr) if Y_tr[n]==0]
x1c0 = [Xn_tr[n][1] for n in range(n_tr) if Y_tr[n]==0]
x0c1 = [Xn_tr[n][0] for n in range(n_tr) if Y_tr[n]==1]
x1c1 = [Xn_tr[n][1] for n in range(n_tr) if Y_tr[n]==1]
# Scatterplot.
labels = {'Iris-setosa': 'Setosa', 'Iris-versicolor': 'Versicolor',
'Iris-virginica': 'Virginica'}
plt.plot(x0c0, x1c0,'r.', label=labels[c0])
plt.plot(x0c1, x1c1,'g+', label=labels[c1])
plt.xlabel('$x_' + str(ind[0]) + '$')
plt.ylabel('$x_' + str(ind[1]) + '$')
plt.legend(loc='best')
plt.axis('equal')
plt.show()
```
In order to apply the gradient descent rule, we need to define two methods:
- A `fit` method, that receives the training data and returns the model weights and the value of the negative log-likelihood during all iterations.
- A `predict` method, that receives the model weight and a set of inputs, and returns the posterior class probabilities for that input, as well as their corresponding class predictions.
```python
def logregFit(Z_tr, Y_tr, rho, n_it):
# Data dimension
n_dim = Z_tr.shape[1]
# Initialize variables
nll_tr = np.zeros(n_it)
pe_tr = np.zeros(n_it)
Y_tr2 = 2*Y_tr - 1 # Transform labels into binary symmetric.
w = np.random.randn(n_dim,1)
# Running the gradient descent algorithm
for n in range(n_it):
# Compute posterior probabilities for weight w
p1_tr = logistic(np.dot(Z_tr, w))
# Compute negative log-likelihood
# (note that this is not required for the weight update, only for nll tracking)
nll_tr[n] = np.sum(np.log(1 + np.exp(-np.dot(Y_tr2*Z_tr, w))))
# Update weights
w += rho*np.dot(Z_tr.T, Y_tr - p1_tr)
return w, nll_tr
def logregPredict(Z, w):
# Compute posterior probability of class 1 for weights w.
p = logistic(np.dot(Z, w)).flatten()
# Class
D = [int(round(pn)) for pn in p]
return p, D
```
We can test the behavior of the gradient descent method by fitting a logistic regression model with ${\bf z}({\bf x}) = (1, {\bf x}^\top)^\top$.
```python
# Parameters of the algorithms
rho = float(1)/50 # Learning step
n_it = 200 # Number of iterations
# Compute Z's
Z_tr = np.c_[np.ones(n_tr), Xn_tr]
Z_tst = np.c_[np.ones(n_tst), Xn_tst]
n_dim = Z_tr.shape[1]
# Convert target arrays to column vectors
Y_tr2 = Y_tr[np.newaxis].T
Y_tst2 = Y_tst[np.newaxis].T
# Running the gradient descent algorithm
w, nll_tr = logregFit(Z_tr, Y_tr2, rho, n_it)
# Classify training and test data
p_tr, D_tr = logregPredict(Z_tr, w)
p_tst, D_tst = logregPredict(Z_tst, w)
# Compute error rates
E_tr = D_tr!=Y_tr
E_tst = D_tst!=Y_tst
# Error rates
pe_tr = float(sum(E_tr)) / n_tr
pe_tst = float(sum(E_tst)) / n_tst
```
```python
# NLL plot.
plt.plot(range(n_it), nll_tr,'b.:', label='Train')
plt.xlabel('Iteration')
plt.ylabel('Negative Log-Likelihood')
plt.legend()
print(f'The optimal weights are: {w}')
print('The final error rates are:')
print(f'- Training: {pe_tr}')
print(f'- Test: {pe_tst}')
print(f'The NLL after training is {nll_tr[len(nll_tr)-1]}')
```
#### 3.2.3. Free parameters
Under certain conditions, the gradient descent method can be shown to converge asymptotically (i.e. as the number of iterations goes to infinity) to the ML estimate of the logistic model. However, in practice, the final estimate of the weights ${\bf w}$ depend on several factors:
- Number of iterations
- Initialization
- Learning step
**Exercise 4**: Visualize the variability of gradient descent caused by initializations. To do so, fix the number of iterations to 200 and the learning step, and execute the gradient descent 100 times, storing the training error rate of each execution. Plot the histogram of the error rate values.
Note that you can do this exercise with a loop over the 100 executions, including the code in the previous code slide inside the loop, with some proper modifications. To plot a histogram of the values in array `p` with `n`bins, you can use `plt.hist(p, n)`
```python
```
##### 3.2.3.1. Learning step
The learning step, $\rho$, is a free parameter of the algorithm. Its choice is critical for the convergence of the algorithm. Too large values of $\rho$ make the algorithm diverge. For too small values, the convergence gets very slow and more iterations are required for a good convergence.
**Exercise 5**: Observe the evolution of the negative log-likelihood with the number of iterations for different values of $\rho$. It is easy to check that, for large enough $\rho$, the gradient descent method does not converge. Can you estimate (through manual observation) an approximate value of $\rho$ stating a boundary between convergence and divergence?
```python
```
**Exercise 6**: In this exercise we explore the influence of the learning step more sistematically. Use the code in the previouse exercises to compute, for every value of $\rho$, the average error rate over 100 executions. Plot the average error rate vs. $\rho$.
Note that you should explore the values of $\rho$ in a logarithmic scale. For instance, you can take $\rho = 1, \frac{1}{10}, \frac{1}{100}, \frac{1}{1000}, \ldots$
```python
```
In practice, the selection of $\rho$ may be a matter of trial an error. Also there is some theoretical evidence that the learning step should decrease along time up to cero, and the sequence $\rho_n$ should satisfy two conditions:
- C1: $\sum_{n=0}^{\infty} \rho_n^2 < \infty$ (decrease slowly)
- C2: $\sum_{n=0}^{\infty} \rho_n = \infty$ (but not too slowly)
For instance, we can take $\rho_n= \frac{1}{n}$. Another common choice is $\rho_n = \frac{\alpha}{1+\beta n}$ where $\alpha$ and $\beta$ are also free parameters that can be selected by trial and error with some heuristic method.
#### 3.2.4. Visualizing the posterior map.
We can also visualize the posterior probability map estimated by the logistic regression model for the estimated weights.
```python
# Create a regtangular grid.
x_min, x_max = Xn_tr[:, 0].min(), Xn_tr[:, 0].max()
y_min, y_max = Xn_tr[:, 1].min(), Xn_tr[:, 1].max()
dx = x_max - x_min
dy = y_max - y_min
h = dy /400
xx, yy = np.meshgrid(np.arange(x_min - 0.1 * dx, x_max + 0.1 * dx, h),
np.arange(y_min - 0.1 * dx, y_max + 0.1 * dy, h))
X_grid = np.array([xx.ravel(), yy.ravel()]).T
# Compute Z's
Z_grid = np.c_[np.ones(X_grid.shape[0]), X_grid]
# Compute the classifier output for all samples in the grid.
pp, dd = logregPredict(Z_grid, w)
```
```python
# Paint output maps
pylab.rcParams['figure.figsize'] = 6, 6 # Set figure size
# Color plot
plt.plot(x0c0, x1c0,'r.', label=labels[c0])
plt.plot(x0c1, x1c1,'g+', label=labels[c1])
plt.xlabel('$x_' + str(ind[0]) + '$')
plt.ylabel('$x_' + str(ind[1]) + '$')
plt.legend(loc='best')
plt.axis('equal')
pp = pp.reshape(xx.shape)
CS = plt.contourf(xx, yy, pp, cmap=plt.cm.copper)
plt.contour(xx, yy, pp, levels=[0.5], colors='b', linewidths=(3,))
plt.colorbar(CS, ticks=[0, 0.5, 1])
plt.show()
```
#### 3.2.5. Polynomial Logistic Regression
The error rates of the logistic regression model can be potentially reduced by using polynomial transformations.
To compute the polynomial transformation up to a given degree, we can use the `PolynomialFeatures` method in `sklearn.preprocessing`.
```python
# Parameters of the algorithms
rho = float(1)/50 # Learning step
n_it = 500 # Number of iterations
g = 5 # Degree of polynomial
# Compute Z_tr
poly = PolynomialFeatures(degree=g)
Z_tr = poly.fit_transform(Xn_tr)
# Normalize columns (this is useful to make algorithms more stable).)
Zn, mz, sz = normalize(Z_tr[:,1:])
Z_tr = np.concatenate((np.ones((n_tr,1)), Zn), axis=1)
# Compute Z_tst
Z_tst = poly.fit_transform(Xn_tst)
Zn, mz, sz = normalize(Z_tst[:,1:], mz, sz)
Z_tst = np.concatenate((np.ones((n_tst,1)), Zn), axis=1)
# Convert target arrays to column vectors
Y_tr2 = Y_tr[np.newaxis].T
Y_tst2 = Y_tst[np.newaxis].T
# Running the gradient descent algorithm
w, nll_tr = logregFit(Z_tr, Y_tr2, rho, n_it)
# Classify training and test data
p_tr, D_tr = logregPredict(Z_tr, w)
p_tst, D_tst = logregPredict(Z_tst, w)
# Compute error rates
E_tr = D_tr!=Y_tr
E_tst = D_tst!=Y_tst
# Error rates
pe_tr = float(sum(E_tr)) / n_tr
pe_tst = float(sum(E_tst)) / n_tst
```
```python
# NLL plot.
plt.plot(range(n_it), nll_tr,'b.:', label='Train')
plt.xlabel('Iteration')
plt.ylabel('Negative Log-Likelihood')
plt.legend()
print(f'The optimal weights are: {w.T}')
print('The final error rates are:')
print(f'- Training: {pe_tr} \n- Test: {pe_tst}')
print('The NLL after training is', nll_tr[len(nll_tr)-1])
```
Visualizing the posterior map we can se that the polynomial transformation produces nonlinear decision boundaries.
```python
# Compute Z_grid
Z_grid = poly.fit_transform(X_grid)
Zn, mz, sz = normalize(Z_grid[:,1:], mz, sz)
Z_grid = np.concatenate((np.ones((Z_grid.shape[0],1)), Zn), axis=1)
# Compute the classifier output for all samples in the grid.
pp, dd = logregPredict(Z_grid, w)
pp = pp.reshape(xx.shape)
```
```python
# Paint output maps
pylab.rcParams['figure.figsize'] = 6, 6 # Set figure size
plt.plot(x0c0, x1c0,'r.', label=labels[c0])
plt.plot(x0c1, x1c1,'g+', label=labels[c1])
plt.xlabel('$x_' + str(ind[0]) + '$')
plt.ylabel('$x_' + str(ind[1]) + '$')
plt.axis('equal')
plt.legend(loc='best')
CS = plt.contourf(xx, yy, pp, cmap=plt.cm.copper)
plt.contour(xx, yy, pp, levels=[0.5], colors='b', linewidths=(3,))
plt.colorbar(CS, ticks=[0, 0.5, 1])
plt.show()
```
## 4. Regularization and MAP estimation.
### 4.1 MAP estimation
An alternative to the ML estimation of the weights in logistic regression is Maximum A Posteriori estimation. Modelling the logistic regression weights as a random variable with prior distribution $p_{\bf W}({\bf w})$, the **MAP estimate** is defined as
$$
\hat{\bf w}_{\text{MAP}} = \arg\max_{\bf w} p({\bf w}|{\mathcal D})
$$
The posterior density $p({\bf w}|{\mathcal D})$ is related to the likelihood function and the prior density of the weights, $p_{\bf W}({\bf w})$ through the **Bayes rule**
$$
p({\bf w}|{\mathcal D}) =
\frac{P\left({\mathcal D}|{\bf w}\right) \; p_{\bf W}({\bf w})}
{p\left({\mathcal D}\right)}
$$
In general, the denominator in this expression cannot be computed analytically. However, it is not required for MAP estimation because it does not depend on ${\bf w}$. Therefore, the MAP solution is given by
\begin{align}
\hat{\bf w}_{\text{MAP}} & = \arg\max_{\bf w} \left\{ P\left({\mathcal D}|{\bf w}\right) \; p_{\bf W}({\bf w}) \right\}\\
& = \arg\max_{\bf w} \left\{ L({\mathbf w}) + \log p_{\bf W}({\bf w})\right\} \\
& = \arg\min_{\bf w} \left\{ \text{NLL}({\mathbf w}) - \log p_{\bf W}({\bf w})\right\}
\end{align}
In the light of this expression, we can conclude that the MAP solution is affected by two terms:
- The likelihood, which takes large values for parameter vectors $\bf w$ that fit well the training data (smaller $\text{NLL}$ values)
- The prior distribution of weights $p_{\bf W}({\bf w})$, which expresses our *a priori* preference for some solutions.
### 4.2. Regularization
Even though the prior distribution has a natural interpretation as a model of our knowledge about $p({\bf w})$ before observing the data, its choice is frequenty motivated by the need to avoid data **overfitting**.
**Data overfitting** is a frequent problem in ML estimation when the dimension of ${\bf w}$ is much higher that the dimension of the input ${\bf x}$: the ML solution can be too adjusted to the training data, while the test error rate is large.
In practice **we recur to prior distributions that take large values when $\|{\bf w}\|$ is small** (associated to smooth classification borders). This helps to improve **generalization**.
In this way, the MAP criterion adds a **penalty term** to the ML objective, that penalizes parameter vectors for which the prior distribution of weights takes small values.
In machine learning, the process of introducing penalty terms to avoid overfitting is usually named **regularization**.
### 4.3 MAP estimation with Gaussian prior
If we assume that ${\bf W}$ follows a **zero-mean Gaussian** random variable with variance matrix $v{\bf I}$,
$$
p_{\bf W}({\bf w}) = \frac{1}{(2\pi v)^{N/2}} \exp\left(-\frac{1}{2v}\|{\bf w}\|^2\right)
$$
the **MAP estimate** becomes
\begin{align}
\hat{\bf w}_{\text{MAP}}
&= \arg\min_{\bf w} \left\{\text{NLL}({\bf w}) + \frac{1}{C}\|{\bf w}\|^2
\right\}
\end{align}
where $C = 2v$. Note that the **regularization term** associated to the prior penalizes parameter vectors with large components. Parameter $C$ controls the regularizatin, and it is named the **inverse regularization strength**.
Noting that
$$\nabla_{\bf w}\left\{\text{NLL}({\bf w}) + \frac{1}{C}\|{\bf w}\|^2\right\}
= - {\bf Z} \left({\bf y}-\hat{\bf p}_n\right) + \frac{2}{C}{\bf w},
$$
we obtain the following **gradient descent rule** for MAP estimation
\begin{align}
{\bf w}_{n+1} &= \left(1-\frac{2\rho_n}{C}\right){\bf w}_n
+ \rho_n {\bf Z} \left({\bf y}-\hat{\bf p}_n\right)
\end{align}
Note that the regularization term "pushes" the weights towards zero.
### 4.4 MAP estimation with Laplacian prior
If we assume that ${\bf W}$ follows a multivariate zero-mean Laplacian distribution given by
$$
p_{\bf W}({\bf w}) = \frac{1}{(2 C)^{N}} \exp\left(-\frac{1}{C}\|{\bf w}\|_1\right)
$$
(where $\|{\bf w}\|=|w_1|+\ldots+|w_N|$ is the $L_1$ norm of ${\bf w}$), the MAP estimate becomes
\begin{align}
\hat{\bf w}_{\text{MAP}}
&= \arg\min_{\bf w} \left\{\text{NLL}({\bf w}) + \frac{1}{C}\|{\bf w}\|_1
\right\}
\end{align}
Parameter $C$ is named the *inverse regularization strength*.
**Exercise 7**: Derive the gradient descent rules for MAP estimation of the logistic regression weights with Laplacian prior.
```python
```
## 5. Other optimization algorithms
### 5.1. Stochastic Gradient descent.
Stochastic gradient descent (SGD) is based on the idea of using a single sample at each iteration of the learning algorithm. The SGD rule for ML logistic regression is
\begin{align}
{\bf w}_{n+1} &= {\bf w}_n
+ \rho_n {\bf z}_n \left(y_n-\hat{p}_n\right)
\end{align}
Once all samples in the training set have been applied, the algorith can continue by applying the training set several times.
The computational cost of each iteration of SGD is much smaller than that of gradient descent, though it usually needs many more iterations to converge.
**Exercise 8**: Modify logregFit to implement an algorithm that applies the SGD rule.
### 5.2. Newton's method
Assume that the function to be minimized, $C({\bf w})$, can be approximated by its **second order Taylor series expansion** around ${\bf w}_0$
$$
C({\bf w}) \approx C({\bf w}_0)
+ \nabla_{\bf w}^\top C({\bf w}_0)({\bf w}-{\bf w}_0)
+ \frac{1}{2}({\bf w}-{\bf w}_0)^\top{\bf H}({\bf w}_0)({\bf w}-{\bf w}_0)
$$
where ${\bf H}({\bf w})$ is the <a href=https://en.wikipedia.org/wiki/Hessian_matrix> **Hessian matrix**</a> of $C$ at ${\bf w}$. Taking the gradient of $C({\bf w})$, and setting the result to ${\bf 0}$, the minimum of C around ${\bf w}_0$ can be approximated as
$$
{\bf w}^* = {\bf w}_0 - {\bf H}({\bf w}_0)^{-1} \nabla_{\bf w}^\top C({\bf w}_0)
$$
Since the second order polynomial is only an approximation to $C$, ${\bf w}^*$ is only an approximation to the optimal weight vector, but we can expect ${\bf w}^*$ to be closer to the minimizer of $C$ than ${\bf w}_0$. Thus, we can repeat the process, computing a second order approximation around ${\bf w}^*$ and a new approximation to the minimizer.
<a href=https://en.wikipedia.org/wiki/Newton%27s_method_in_optimization> **Newton's method**</a> is based on this idea. At each optimization step, the function to be minimized is approximated by a second order approximation using a Taylor series expansion around the current estimate. As a result, the learning rule becomes
$$\hat{\bf w}_{n+1} = \hat{\bf w}_{n} - \rho_n {\bf H}({\bf w}_n)^{-1} \nabla_{{\bf w}}C({\bf w}_n)
$$
#### 5.2.1. Example: MAP estimation with Gaussian prior.
For instance, for the MAP estimate with Gaussian prior, the *Hessian* matrix becomes
$$
{\bf H}({\bf w})
= \frac{2}{C}{\bf I}
+ \sum_{k=0}^{K-1} g({\bf w}^\top {\bf z}_k)
\left[1-g({\bf w}^\top {\bf z}_k)\right]{\bf z}_k {\bf z}_k^\top
$$
Defining diagonal matrix
$$
{\mathbf S}({\bf w}) = \text{diag}\left[g({\bf w}^\top {\bf z}_k) \left(1-g({\bf w}^\top {\bf z}_k)\right)\right]
$$
the Hessian matrix can be written in more compact form as
$$
{\bf H}({\bf w})
= \frac{2}{C}{\bf I} + {\bf Z}^\top {\bf S}({\bf w}) {\bf Z}
$$
Therefore, the Newton's algorithm for logistic regression becomes
\begin{align}
{\bf w}_{n+1} = {\bf w}_{n} +
\rho_n
\left(\frac{2}{C}{\bf I} + {\bf Z}^\top {\bf S}({\bf w}_{n})
{\bf Z}
\right)^{-1}
{\bf Z}^\top \left({\bf y}-\hat{\bf p}_n\right)
\end{align}
Some variants of the Newton method are implemented in the <a href="http://scikit-learn.org/stable/"> Scikit-learn </a> package.
```python
def logregFit2(Z_tr, Y_tr, rho, n_it, C=1e4):
# Compute Z's
r = 2.0/C
n_dim = Z_tr.shape[1]
# Initialize variables
nll_tr = np.zeros(n_it)
pe_tr = np.zeros(n_it)
w = np.random.randn(n_dim,1)
# Running the gradient descent algorithm
for n in range(n_it):
p_tr = logistic(np.dot(Z_tr, w))
sk = np.multiply(p_tr, 1-p_tr)
S = np.diag(np.ravel(sk.T))
# Compute negative log-likelihood
nll_tr[n] = - np.dot(Y_tr.T, np.log(p_tr)) - np.dot((1-Y_tr).T, np.log(1-p_tr))
# Update weights
invH = np.linalg.inv(r*np.identity(n_dim) + np.dot(Z_tr.T, np.dot(S, Z_tr)))
w += rho*np.dot(invH, np.dot(Z_tr.T, Y_tr - p_tr))
return w, nll_tr
```
```python
# Parameters of the algorithms
rho = float(1)/50 # Learning step
n_it = 500 # Number of iterations
C = 1000
g = 4
# Compute Z_tr
poly = PolynomialFeatures(degree=g)
Z_tr = poly.fit_transform(X_tr)
# Normalize columns (this is useful to make algorithms more stable).)
Zn, mz, sz = normalize(Z_tr[:,1:])
Z_tr = np.concatenate((np.ones((n_tr,1)), Zn), axis=1)
# Compute Z_tst
Z_tst = poly.fit_transform(X_tst)
Zn, mz, sz = normalize(Z_tst[:,1:], mz, sz)
Z_tst = np.concatenate((np.ones((n_tst,1)), Zn), axis=1)
# Convert target arrays to column vectors
Y_tr2 = Y_tr[np.newaxis].T
Y_tst2 = Y_tst[np.newaxis].T
# Running the gradient descent algorithm
w, nll_tr = logregFit2(Z_tr, Y_tr2, rho, n_it, C)
# Classify training and test data
p_tr, D_tr = logregPredict(Z_tr, w)
p_tst, D_tst = logregPredict(Z_tst, w)
# Compute error rates
E_tr = D_tr!=Y_tr
E_tst = D_tst!=Y_tst
# Error rates
pe_tr = float(sum(E_tr)) / n_tr
pe_tst = float(sum(E_tst)) / n_tst
```
```python
# NLL plot.
plt.plot(range(n_it), nll_tr,'b.:', label='Train')
plt.xlabel('Iteration')
plt.ylabel('Negative Log-Likelihood')
plt.legend()
print('The final error rates are:')
print('- Training:', str(pe_tr))
print('- Test:', str(pe_tst))
print('The NLL after training is:', str(nll_tr[len(nll_tr)-1]))
```
## 6. Logistic regression in Scikit Learn.
The <a href="http://scikit-learn.org/stable/"> scikit-learn </a> package includes an efficient implementation of <a href="http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html#sklearn.linear_model.LogisticRegression"> logistic regression</a>. To use it, we must first create a classifier object, specifying the parameters of the logistic regression algorithm.
```python
# Create a logistic regression object.
LogReg = linear_model.LogisticRegression(C=1.0)
# Compute Z_tr
poly = PolynomialFeatures(degree=g)
Z_tr = poly.fit_transform(Xn_tr)
# Normalize columns (this is useful to make algorithms more stable).)
Zn, mz, sz = normalize(Z_tr[:,1:])
Z_tr = np.concatenate((np.ones((n_tr,1)), Zn), axis=1)
# Compute Z_tst
Z_tst = poly.fit_transform(Xn_tst)
Zn, mz, sz = normalize(Z_tst[:,1:], mz, sz)
Z_tst = np.concatenate((np.ones((n_tst,1)), Zn), axis=1)
# Fit model to data.
LogReg.fit(Z_tr, Y_tr)
# Classify training and test data
D_tr = LogReg.predict(Z_tr)
D_tst = LogReg.predict(Z_tst)
```
```python
# Compute error rates
E_tr = D_tr!=Y_tr
E_tst = D_tst!=Y_tst
# Error rates
pe_tr = float(sum(E_tr)) / n_tr
pe_tst = float(sum(E_tst)) / n_tst
print('The final error rates are:')
print('- Training:', str(pe_tr))
print('- Test:', str(pe_tst))
# Compute Z_grid
Z_grid = poly.fit_transform(X_grid)
n_grid = Z_grid.shape[0]
Zn, mz, sz = normalize(Z_grid[:,1:], mz, sz)
Z_grid = np.concatenate((np.ones((n_grid,1)), Zn), axis=1)
```
The final error rates are:
- Training: 0.2463768115942029
- Test: 0.3548387096774194
```python
# Compute the classifier output for all samples in the grid.
dd = LogReg.predict(Z_grid)
pp = LogReg.predict_proba(Z_grid)[:,1]
pp = pp.reshape(xx.shape)
# Paint output maps
pylab.rcParams['figure.figsize'] = 6, 6 # Set figure size
plt.plot(x0c0, x1c0,'r.', label=labels[c0])
plt.plot(x0c1, x1c1,'g+', label=labels[c1])
plt.xlabel('$x_' + str(ind[0]) + '$')
plt.ylabel('$x_' + str(ind[1]) + '$')
plt.axis('equal')
plt.contourf(xx, yy, pp, cmap=plt.cm.copper)
plt.legend(loc='best')
plt.contour(xx, yy, pp, levels=[0.5], colors='b', linewidths=(3,))
plt.colorbar(CS, ticks=[0, 0.5, 1])
plt.show()
```
```python
```
|
[STATEMENT]
lemma union_equiv:
"equiv V R \<Longrightarrow> equiv V (per_union R a b)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. equiv V R \<Longrightarrow> equiv V (per_union R a b)
[PROOF STEP]
apply (rule equivI)
[PROOF STATE]
proof (prove)
goal (3 subgoals):
1. equiv V R \<Longrightarrow> refl_on V (per_union R a b)
2. equiv V R \<Longrightarrow> sym (per_union R a b)
3. equiv V R \<Longrightarrow> trans (per_union R a b)
[PROOF STEP]
unfolding per_union_def
[PROOF STATE]
proof (prove)
goal (3 subgoals):
1. equiv V R \<Longrightarrow> refl_on V (R \<union> {(x, y). (x, a) \<in> R \<and> (y, b) \<in> R} \<union> {(y, x). (x, a) \<in> R \<and> (y, b) \<in> R})
2. equiv V R \<Longrightarrow> sym (R \<union> {(x, y). (x, a) \<in> R \<and> (y, b) \<in> R} \<union> {(y, x). (x, a) \<in> R \<and> (y, b) \<in> R})
3. equiv V R \<Longrightarrow> trans (R \<union> {(x, y). (x, a) \<in> R \<and> (y, b) \<in> R} \<union> {(y, x). (x, a) \<in> R \<and> (y, b) \<in> R})
[PROOF STEP]
subgoal
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. equiv V R \<Longrightarrow> refl_on V (R \<union> {(x, y). (x, a) \<in> R \<and> (y, b) \<in> R} \<union> {(y, x). (x, a) \<in> R \<and> (y, b) \<in> R})
[PROOF STEP]
unfolding equiv_def refl_on_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (R \<subseteq> V \<times> V \<and> (\<forall>x\<in>V. (x, x) \<in> R)) \<and> sym R \<and> trans R \<Longrightarrow> R \<union> {(x, y). (x, a) \<in> R \<and> (y, b) \<in> R} \<union> {(y, x). (x, a) \<in> R \<and> (y, b) \<in> R} \<subseteq> V \<times> V \<and> (\<forall>x\<in>V. (x, x) \<in> R \<union> {(x, y). (x, a) \<in> R \<and> (y, b) \<in> R} \<union> {(y, x). (x, a) \<in> R \<and> (y, b) \<in> R})
[PROOF STEP]
by auto
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. equiv V R \<Longrightarrow> sym (R \<union> {(x, y). (x, a) \<in> R \<and> (y, b) \<in> R} \<union> {(y, x). (x, a) \<in> R \<and> (y, b) \<in> R})
2. equiv V R \<Longrightarrow> trans (R \<union> {(x, y). (x, a) \<in> R \<and> (y, b) \<in> R} \<union> {(y, x). (x, a) \<in> R \<and> (y, b) \<in> R})
[PROOF STEP]
subgoal
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. equiv V R \<Longrightarrow> sym (R \<union> {(x, y). (x, a) \<in> R \<and> (y, b) \<in> R} \<union> {(y, x). (x, a) \<in> R \<and> (y, b) \<in> R})
[PROOF STEP]
apply (rule symI)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>aa ba. \<lbrakk>equiv V R; (aa, ba) \<in> R \<union> {(x, y). (x, a) \<in> R \<and> (y, b) \<in> R} \<union> {(y, x). (x, a) \<in> R \<and> (y, b) \<in> R}\<rbrakk> \<Longrightarrow> (ba, aa) \<in> R \<union> {(x, y). (x, a) \<in> R \<and> (y, b) \<in> R} \<union> {(y, x). (x, a) \<in> R \<and> (y, b) \<in> R}
[PROOF STEP]
by (auto dest: equiv_sym)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. equiv V R \<Longrightarrow> trans (R \<union> {(x, y). (x, a) \<in> R \<and> (y, b) \<in> R} \<union> {(y, x). (x, a) \<in> R \<and> (y, b) \<in> R})
[PROOF STEP]
subgoal
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. equiv V R \<Longrightarrow> trans (R \<union> {(x, y). (x, a) \<in> R \<and> (y, b) \<in> R} \<union> {(y, x). (x, a) \<in> R \<and> (y, b) \<in> R})
[PROOF STEP]
apply (rule transI)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>x y z. \<lbrakk>equiv V R; (x, y) \<in> R \<union> {(x, y). (x, a) \<in> R \<and> (y, b) \<in> R} \<union> {(y, x). (x, a) \<in> R \<and> (y, b) \<in> R}; (y, z) \<in> R \<union> {(x, y). (x, a) \<in> R \<and> (y, b) \<in> R} \<union> {(y, x). (x, a) \<in> R \<and> (y, b) \<in> R}\<rbrakk> \<Longrightarrow> (x, z) \<in> R \<union> {(x, y). (x, a) \<in> R \<and> (y, b) \<in> R} \<union> {(y, x). (x, a) \<in> R \<and> (y, b) \<in> R}
[PROOF STEP]
by (auto dest: equiv_trans equiv_trans_sym)
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done |
import numpy as np
import matplotlib
matplotlib.rcParams.update({'font.size': 16})
from matplotlib import pyplot as pl
moi_range = 200
def plotting(p1):
arr = [[0.0 for x in xrange(moi_range)] for x in xrange(25)]
i=-1
fname = 'points'+str(p1)+'.txt' # read file for required phage environment
with open(fname, 'r') as f:
for line in f:
i+=1
temp = line.split(',')
for x in xrange(moi_range):
arr[i][x] = float(temp[x+2])
# generate maximum, minimum and trend data points for the entire moi_range
mean = [0.0 for x in xrange(moi_range)]
maxi = [0.0 for x in xrange(moi_range)]
mini = [1.0 for x in xrange(moi_range)]
for x in xrange(moi_range):
for y in xrange(25):
if maxi[x]<arr[y][x]:
maxi[x] = arr[y][x]
if mini[x]>arr[y][x]:
mini[x] = arr[y][x]
mean[x]+=arr[y][x]
mean[x]/=25
return mini, mean, maxi
x = np.linspace(0, 2, moi_range)
pl.clf()
pl.hold(1)
pl.xlabel('MoI')
pl.ylabel('P(lyso)')
lcolor = ['#0000FF', '#FF0000', '#FF0000', '#FF0000', '#FF00FF'] # central line color - choose dark colors
fcolor = ['#6666FF', '#FF7878', '#9494FF', '#FF7878', '#CCCCFF'] # variation area color - choose light colors
for i in [2,8]: # change range as per requirements
mini, mean, maxi = plotting((i*1.0)/10)
pl.plot(x, mean, 'k', color=lcolor[int((i*1.0)/2)-1])
pl.fill_between(x, mini, maxi,
alpha=0.2, facecolor=fcolor[int((i*1.0)/2)-1],
antialiased=True)
pl.show() |
# Example from Section 5.1 of the paper
read "../ComputeIdentifiableFunctions.mpl";
model := [
diff(x1(t), t) = (a * x1(t) - b * x1(t) * x2(t)),
diff(x2(t), t) = (-c * x2(t) + d * x1(t) * x2(t) + e * u(t)),
y(t) = x1(t)
]:
# Computing function identifiable from a single experiment
printf("Single-experiment identifiable functions: %a\n", SingleExperimentIdentifiableFunctions(model)):
me := MultiExperimentIdentifiableFunctions(model, simplified_generators=true):
printf("The bound for the number of experiments is %a, this means that the field of multi-experiment identifiable functions is the same, %a\n", me[1], me[3]):
|
section \<open>CFG\<close>
theory CFG imports BasicDefs begin
subsection \<open>The abstract CFG\<close>
subsubsection \<open>Locale fixes and assumptions\<close>
locale CFG =
fixes sourcenode :: "'edge \<Rightarrow> 'node"
fixes targetnode :: "'edge \<Rightarrow> 'node"
fixes kind :: "'edge \<Rightarrow> ('var,'val,'ret,'pname) edge_kind"
fixes valid_edge :: "'edge \<Rightarrow> bool"
fixes Entry::"'node" ("'('_Entry'_')")
fixes get_proc::"'node \<Rightarrow> 'pname"
fixes get_return_edges::"'edge \<Rightarrow> 'edge set"
fixes procs::"('pname \<times> 'var list \<times> 'var list) list"
fixes Main::"'pname"
assumes Entry_target [dest]: "\<lbrakk>valid_edge a; targetnode a = (_Entry_)\<rbrakk> \<Longrightarrow> False"
and get_proc_Entry:"get_proc (_Entry_) = Main"
and Entry_no_call_source:
"\<lbrakk>valid_edge a; kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs; sourcenode a = (_Entry_)\<rbrakk> \<Longrightarrow> False"
and edge_det:
"\<lbrakk>valid_edge a; valid_edge a'; sourcenode a = sourcenode a';
targetnode a = targetnode a'\<rbrakk> \<Longrightarrow> a = a'"
and Main_no_call_target:"\<lbrakk>valid_edge a; kind a = Q:r\<hookrightarrow>\<^bsub>Main\<^esub>f\<rbrakk> \<Longrightarrow> False"
and Main_no_return_source:"\<lbrakk>valid_edge a; kind a = Q'\<hookleftarrow>\<^bsub>Main\<^esub>f'\<rbrakk> \<Longrightarrow> False"
and callee_in_procs:
"\<lbrakk>valid_edge a; kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<rbrakk> \<Longrightarrow> \<exists>ins outs. (p,ins,outs) \<in> set procs"
and get_proc_intra:"\<lbrakk>valid_edge a; intra_kind(kind a)\<rbrakk>
\<Longrightarrow> get_proc (sourcenode a) = get_proc (targetnode a)"
and get_proc_call:
"\<lbrakk>valid_edge a; kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<rbrakk> \<Longrightarrow> get_proc (targetnode a) = p"
and get_proc_return:
"\<lbrakk>valid_edge a; kind a = Q'\<hookleftarrow>\<^bsub>p\<^esub>f'\<rbrakk> \<Longrightarrow> get_proc (sourcenode a) = p"
and call_edges_only:"\<lbrakk>valid_edge a; kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<rbrakk>
\<Longrightarrow> \<forall>a'. valid_edge a' \<and> targetnode a' = targetnode a \<longrightarrow>
(\<exists>Qx rx fsx. kind a' = Qx:rx\<hookrightarrow>\<^bsub>p\<^esub>fsx)"
and return_edges_only:"\<lbrakk>valid_edge a; kind a = Q'\<hookleftarrow>\<^bsub>p\<^esub>f'\<rbrakk>
\<Longrightarrow> \<forall>a'. valid_edge a' \<and> sourcenode a' = sourcenode a \<longrightarrow>
(\<exists>Qx fx. kind a' = Qx\<hookleftarrow>\<^bsub>p\<^esub>fx)"
and get_return_edge_call:
"\<lbrakk>valid_edge a; kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<rbrakk> \<Longrightarrow> get_return_edges a \<noteq> {}"
and get_return_edges_valid:
"\<lbrakk>valid_edge a; a' \<in> get_return_edges a\<rbrakk> \<Longrightarrow> valid_edge a'"
and only_call_get_return_edges:
"\<lbrakk>valid_edge a; a' \<in> get_return_edges a\<rbrakk> \<Longrightarrow> \<exists>Q r p fs. kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs"
and call_return_edges:
"\<lbrakk>valid_edge a; kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs; a' \<in> get_return_edges a\<rbrakk>
\<Longrightarrow> \<exists>Q' f'. kind a' = Q'\<hookleftarrow>\<^bsub>p\<^esub>f'"
and return_needs_call: "\<lbrakk>valid_edge a; kind a = Q'\<hookleftarrow>\<^bsub>p\<^esub>f'\<rbrakk>
\<Longrightarrow> \<exists>!a'. valid_edge a' \<and> (\<exists>Q r fs. kind a' = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs) \<and> a \<in> get_return_edges a'"
and intra_proc_additional_edge:
"\<lbrakk>valid_edge a; a' \<in> get_return_edges a\<rbrakk>
\<Longrightarrow> \<exists>a''. valid_edge a'' \<and> sourcenode a'' = targetnode a \<and>
targetnode a'' = sourcenode a' \<and> kind a'' = (\<lambda>cf. False)\<^sub>\<surd>"
and call_return_node_edge:
"\<lbrakk>valid_edge a; a' \<in> get_return_edges a\<rbrakk>
\<Longrightarrow> \<exists>a''. valid_edge a'' \<and> sourcenode a'' = sourcenode a \<and>
targetnode a'' = targetnode a' \<and> kind a'' = (\<lambda>cf. False)\<^sub>\<surd>"
and call_only_one_intra_edge:
"\<lbrakk>valid_edge a; kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<rbrakk>
\<Longrightarrow> \<exists>!a'. valid_edge a' \<and> sourcenode a' = sourcenode a \<and> intra_kind(kind a')"
and return_only_one_intra_edge:
"\<lbrakk>valid_edge a; kind a = Q'\<hookleftarrow>\<^bsub>p\<^esub>f'\<rbrakk>
\<Longrightarrow> \<exists>!a'. valid_edge a' \<and> targetnode a' = targetnode a \<and> intra_kind(kind a')"
and same_proc_call_unique_target:
"\<lbrakk>valid_edge a; valid_edge a'; kind a = Q\<^sub>1:r\<^sub>1\<hookrightarrow>\<^bsub>p\<^esub>fs\<^sub>1; kind a' = Q\<^sub>2:r\<^sub>2\<hookrightarrow>\<^bsub>p\<^esub>fs\<^sub>2\<rbrakk>
\<Longrightarrow> targetnode a = targetnode a'"
and unique_callers:"distinct_fst procs"
and distinct_formal_ins:"(p,ins,outs) \<in> set procs \<Longrightarrow> distinct ins"
and distinct_formal_outs:"(p,ins,outs) \<in> set procs \<Longrightarrow> distinct outs"
begin
lemma get_proc_get_return_edge:
assumes "valid_edge a" and "a' \<in> get_return_edges a"
shows "get_proc (sourcenode a) = get_proc (targetnode a')"
proof -
from assms obtain ax where "valid_edge ax" and "sourcenode a = sourcenode ax"
and "targetnode a' = targetnode ax" and "intra_kind(kind ax)"
by(auto dest:call_return_node_edge simp:intra_kind_def)
thus ?thesis by(fastforce intro:get_proc_intra)
qed
lemma formal_in_THE:
"\<lbrakk>valid_edge a; kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs; (p,ins,outs) \<in> set procs\<rbrakk>
\<Longrightarrow> (THE ins. \<exists>outs. (p,ins,outs) \<in> set procs) = ins"
by(fastforce dest:distinct_fst_isin_same_fst intro:unique_callers)
lemma formal_out_THE:
"\<lbrakk>valid_edge a; kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f; (p,ins,outs) \<in> set procs\<rbrakk>
\<Longrightarrow> (THE outs. \<exists>ins. (p,ins,outs) \<in> set procs) = outs"
by(fastforce dest:distinct_fst_isin_same_fst intro:unique_callers)
subsubsection \<open>Transfer and predicate functions\<close>
fun params :: "(('var \<rightharpoonup> 'val) \<rightharpoonup> 'val) list \<Rightarrow> ('var \<rightharpoonup> 'val) \<Rightarrow> 'val option list"
where "params [] cf = []"
| "params (f#fs) cf = (f cf)#params fs cf"
lemma params_nth:
"i < length fs \<Longrightarrow> (params fs cf)!i = (fs!i) cf"
by(induct fs arbitrary:i,auto,case_tac i,auto)
fun transfer :: "('var,'val,'ret,'pname) edge_kind \<Rightarrow> (('var \<rightharpoonup> 'val) \<times> 'ret) list \<Rightarrow>
(('var \<rightharpoonup> 'val) \<times> 'ret) list"
where "transfer (\<Up>f) (cf#cfs) = (f (fst cf),snd cf)#cfs"
| "transfer (Q)\<^sub>\<surd> (cf#cfs) = (cf#cfs)"
| "transfer (Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs) (cf#cfs) =
(let ins = THE ins. \<exists>outs. (p,ins,outs) \<in> set procs in
(Map.empty(ins [:=] params fs (fst cf)),r)#cf#cfs)"
| "transfer (Q\<hookleftarrow>\<^bsub>p\<^esub>f )(cf#cfs) = (case cfs of [] \<Rightarrow> []
| cf'#cfs' \<Rightarrow> (f (fst cf) (fst cf'),snd cf')#cfs')"
| "transfer et [] = []"
fun transfers :: "('var,'val,'ret,'pname) edge_kind list \<Rightarrow> (('var \<rightharpoonup> 'val) \<times> 'ret) list \<Rightarrow>
(('var \<rightharpoonup> 'val) \<times> 'ret) list"
where "transfers [] s = s"
| "transfers (et#ets) s = transfers ets (transfer et s)"
fun pred :: "('var,'val,'ret,'pname) edge_kind \<Rightarrow> (('var \<rightharpoonup> 'val) \<times> 'ret) list \<Rightarrow> bool"
where "pred (\<Up>f) (cf#cfs) = True"
| "pred (Q)\<^sub>\<surd> (cf#cfs) = Q (fst cf)"
| "pred (Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs) (cf#cfs) = Q (fst cf,r)"
| "pred (Q\<hookleftarrow>\<^bsub>p\<^esub>f) (cf#cfs) = (Q cf \<and> cfs \<noteq> [])"
| "pred et [] = False"
fun preds :: "('var,'val,'ret,'pname) edge_kind list \<Rightarrow> (('var \<rightharpoonup> 'val) \<times> 'ret) list \<Rightarrow> bool"
where "preds [] s = True"
| "preds (et#ets) s = (pred et s \<and> preds ets (transfer et s))"
lemma transfers_split:
"(transfers (ets@ets') s) = (transfers ets' (transfers ets s))"
by(induct ets arbitrary:s) auto
lemma preds_split:
"(preds (ets@ets') s) = (preds ets s \<and> preds ets' (transfers ets s))"
by(induct ets arbitrary:s) auto
abbreviation state_val :: "(('var \<rightharpoonup> 'val) \<times> 'ret) list \<Rightarrow> 'var \<rightharpoonup> 'val"
where "state_val s V \<equiv> (fst (hd s)) V"
subsubsection \<open>\<open>valid_node\<close>\<close>
definition valid_node :: "'node \<Rightarrow> bool"
where "valid_node n \<equiv>
(\<exists>a. valid_edge a \<and> (n = sourcenode a \<or> n = targetnode a))"
lemma [simp]: "valid_edge a \<Longrightarrow> valid_node (sourcenode a)"
by(fastforce simp:valid_node_def)
lemma [simp]: "valid_edge a \<Longrightarrow> valid_node (targetnode a)"
by(fastforce simp:valid_node_def)
subsection \<open>CFG paths\<close>
inductive path :: "'node \<Rightarrow> 'edge list \<Rightarrow> 'node \<Rightarrow> bool"
("_ -_\<rightarrow>* _" [51,0,0] 80)
where
empty_path:"valid_node n \<Longrightarrow> n -[]\<rightarrow>* n"
| Cons_path:
"\<lbrakk>n'' -as\<rightarrow>* n'; valid_edge a; sourcenode a = n; targetnode a = n''\<rbrakk>
\<Longrightarrow> n -a#as\<rightarrow>* n'"
lemma path_valid_node:
assumes "n -as\<rightarrow>* n'" shows "valid_node n" and "valid_node n'"
using \<open>n -as\<rightarrow>* n'\<close>
by(induct rule:path.induct,auto)
lemma empty_path_nodes [dest]:"n -[]\<rightarrow>* n' \<Longrightarrow> n = n'"
by(fastforce elim:path.cases)
lemma path_valid_edges:"n -as\<rightarrow>* n' \<Longrightarrow> \<forall>a \<in> set as. valid_edge a"
by(induct rule:path.induct) auto
lemma path_edge:"valid_edge a \<Longrightarrow> sourcenode a -[a]\<rightarrow>* targetnode a"
by(fastforce intro:Cons_path empty_path)
lemma path_Append:"\<lbrakk>n -as\<rightarrow>* n''; n'' -as'\<rightarrow>* n'\<rbrakk>
\<Longrightarrow> n -as@as'\<rightarrow>* n'"
by(induct rule:path.induct,auto intro:Cons_path)
lemma path_split:
assumes "n -as@a#as'\<rightarrow>* n'"
shows "n -as\<rightarrow>* sourcenode a" and "valid_edge a" and "targetnode a -as'\<rightarrow>* n'"
using \<open>n -as@a#as'\<rightarrow>* n'\<close>
proof(induct as arbitrary:n)
case Nil case 1
thus ?case by(fastforce elim:path.cases intro:empty_path)
next
case Nil case 2
thus ?case by(fastforce elim:path.cases intro:path_edge)
next
case Nil case 3
thus ?case by(fastforce elim:path.cases)
next
case (Cons ax asx)
note IH1 = \<open>\<And>n. n -asx@a#as'\<rightarrow>* n' \<Longrightarrow> n -asx\<rightarrow>* sourcenode a\<close>
note IH2 = \<open>\<And>n. n -asx@a#as'\<rightarrow>* n' \<Longrightarrow> valid_edge a\<close>
note IH3 = \<open>\<And>n. n -asx@a#as'\<rightarrow>* n' \<Longrightarrow> targetnode a -as'\<rightarrow>* n'\<close>
{ case 1
hence "sourcenode ax = n" and "targetnode ax -asx@a#as'\<rightarrow>* n'" and "valid_edge ax"
by(auto elim:path.cases)
from IH1[OF \<open> targetnode ax -asx@a#as'\<rightarrow>* n'\<close>]
have "targetnode ax -asx\<rightarrow>* sourcenode a" .
with \<open>sourcenode ax = n\<close> \<open>valid_edge ax\<close> show ?case by(fastforce intro:Cons_path)
next
case 2 hence "targetnode ax -asx@a#as'\<rightarrow>* n'" by(auto elim:path.cases)
from IH2[OF this] show ?case .
next
case 3 hence "targetnode ax -asx@a#as'\<rightarrow>* n'" by(auto elim:path.cases)
from IH3[OF this] show ?case .
}
qed
lemma path_split_Cons:
assumes "n -as\<rightarrow>* n'" and "as \<noteq> []"
obtains a' as' where "as = a'#as'" and "n = sourcenode a'"
and "valid_edge a'" and "targetnode a' -as'\<rightarrow>* n'"
proof(atomize_elim)
from \<open>as \<noteq> []\<close> obtain a' as' where "as = a'#as'" by(cases as) auto
with \<open>n -as\<rightarrow>* n'\<close> have "n -[]@a'#as'\<rightarrow>* n'" by simp
hence "n -[]\<rightarrow>* sourcenode a'" and "valid_edge a'" and "targetnode a' -as'\<rightarrow>* n'"
by(rule path_split)+
from \<open>n -[]\<rightarrow>* sourcenode a'\<close> have "n = sourcenode a'" by fast
with \<open>as = a'#as'\<close> \<open>valid_edge a'\<close> \<open>targetnode a' -as'\<rightarrow>* n'\<close>
show "\<exists>a' as'. as = a'#as' \<and> n = sourcenode a' \<and> valid_edge a' \<and>
targetnode a' -as'\<rightarrow>* n'"
by fastforce
qed
lemma path_split_snoc:
assumes "n -as\<rightarrow>* n'" and "as \<noteq> []"
obtains a' as' where "as = as'@[a']" and "n -as'\<rightarrow>* sourcenode a'"
and "valid_edge a'" and "n' = targetnode a'"
proof(atomize_elim)
from \<open>as \<noteq> []\<close> obtain a' as' where "as = as'@[a']" by(cases as rule:rev_cases) auto
with \<open>n -as\<rightarrow>* n'\<close> have "n -as'@a'#[]\<rightarrow>* n'" by simp
hence "n -as'\<rightarrow>* sourcenode a'" and "valid_edge a'" and "targetnode a' -[]\<rightarrow>* n'"
by(rule path_split)+
from \<open>targetnode a' -[]\<rightarrow>* n'\<close> have "n' = targetnode a'" by fast
with \<open>as = as'@[a']\<close> \<open>valid_edge a'\<close> \<open>n -as'\<rightarrow>* sourcenode a'\<close>
show "\<exists>as' a'. as = as'@[a'] \<and> n -as'\<rightarrow>* sourcenode a' \<and> valid_edge a' \<and>
n' = targetnode a'"
by fastforce
qed
lemma path_split_second:
assumes "n -as@a#as'\<rightarrow>* n'" shows "sourcenode a -a#as'\<rightarrow>* n'"
proof -
from \<open>n -as@a#as'\<rightarrow>* n'\<close> have "valid_edge a" and "targetnode a -as'\<rightarrow>* n'"
by(auto intro:path_split)
thus ?thesis by(fastforce intro:Cons_path)
qed
lemma path_Entry_Cons:
assumes "(_Entry_) -as\<rightarrow>* n'" and "n' \<noteq> (_Entry_)"
obtains n a where "sourcenode a = (_Entry_)" and "targetnode a = n"
and "n -tl as\<rightarrow>* n'" and "valid_edge a" and "a = hd as"
proof(atomize_elim)
from \<open>(_Entry_) -as\<rightarrow>* n'\<close> \<open>n' \<noteq> (_Entry_)\<close> have "as \<noteq> []"
by(cases as,auto elim:path.cases)
with \<open>(_Entry_) -as\<rightarrow>* n'\<close> obtain a' as' where "as = a'#as'"
and "(_Entry_) = sourcenode a'" and "valid_edge a'" and "targetnode a' -as'\<rightarrow>* n'"
by(erule path_split_Cons)
thus "\<exists>a n. sourcenode a = (_Entry_) \<and> targetnode a = n \<and> n -tl as\<rightarrow>* n' \<and>
valid_edge a \<and> a = hd as"
by fastforce
qed
lemma path_det:
"\<lbrakk>n -as\<rightarrow>* n'; n -as\<rightarrow>* n''\<rbrakk> \<Longrightarrow> n' = n''"
proof(induct as arbitrary:n)
case Nil thus ?case by(auto elim:path.cases)
next
case (Cons a' as')
note IH = \<open>\<And>n. \<lbrakk>n -as'\<rightarrow>* n'; n -as'\<rightarrow>* n''\<rbrakk> \<Longrightarrow> n' = n''\<close>
from \<open>n -a'#as'\<rightarrow>* n'\<close> have "targetnode a' -as'\<rightarrow>* n'"
by(fastforce elim:path_split_Cons)
from \<open>n -a'#as'\<rightarrow>* n''\<close> have "targetnode a' -as'\<rightarrow>* n''"
by(fastforce elim:path_split_Cons)
from IH[OF \<open>targetnode a' -as'\<rightarrow>* n'\<close> this] show ?thesis .
qed
definition
sourcenodes :: "'edge list \<Rightarrow> 'node list"
where "sourcenodes xs \<equiv> map sourcenode xs"
definition
kinds :: "'edge list \<Rightarrow> ('var,'val,'ret,'pname) edge_kind list"
where "kinds xs \<equiv> map kind xs"
definition
targetnodes :: "'edge list \<Rightarrow> 'node list"
where "targetnodes xs \<equiv> map targetnode xs"
lemma path_sourcenode:
"\<lbrakk>n -as\<rightarrow>* n'; as \<noteq> []\<rbrakk> \<Longrightarrow> hd (sourcenodes as) = n"
by(fastforce elim:path_split_Cons simp:sourcenodes_def)
lemma path_targetnode:
"\<lbrakk>n -as\<rightarrow>* n'; as \<noteq> []\<rbrakk> \<Longrightarrow> last (targetnodes as) = n'"
by(fastforce elim:path_split_snoc simp:targetnodes_def)
lemma sourcenodes_is_n_Cons_butlast_targetnodes:
"\<lbrakk>n -as\<rightarrow>* n'; as \<noteq> []\<rbrakk> \<Longrightarrow>
sourcenodes as = n#(butlast (targetnodes as))"
proof(induct as arbitrary:n)
case Nil thus ?case by simp
next
case (Cons a' as')
note IH = \<open>\<And>n. \<lbrakk>n -as'\<rightarrow>* n'; as' \<noteq> []\<rbrakk>
\<Longrightarrow> sourcenodes as' = n#(butlast (targetnodes as'))\<close>
from \<open>n -a'#as'\<rightarrow>* n'\<close> have "n = sourcenode a'" and "targetnode a' -as'\<rightarrow>* n'"
by(auto elim:path_split_Cons)
show ?case
proof(cases "as' = []")
case True
with \<open>targetnode a' -as'\<rightarrow>* n'\<close> have "targetnode a' = n'" by fast
with True \<open>n = sourcenode a'\<close> show ?thesis
by(simp add:sourcenodes_def targetnodes_def)
next
case False
from IH[OF \<open>targetnode a' -as'\<rightarrow>* n'\<close> this]
have "sourcenodes as' = targetnode a' # butlast (targetnodes as')" .
with \<open>n = sourcenode a'\<close> False show ?thesis
by(simp add:sourcenodes_def targetnodes_def)
qed
qed
lemma targetnodes_is_tl_sourcenodes_App_n':
"\<lbrakk>n -as\<rightarrow>* n'; as \<noteq> []\<rbrakk> \<Longrightarrow>
targetnodes as = (tl (sourcenodes as))@[n']"
proof(induct as arbitrary:n' rule:rev_induct)
case Nil thus ?case by simp
next
case (snoc a' as')
note IH = \<open>\<And>n'. \<lbrakk>n -as'\<rightarrow>* n'; as' \<noteq> []\<rbrakk>
\<Longrightarrow> targetnodes as' = tl (sourcenodes as') @ [n']\<close>
from \<open>n -as'@[a']\<rightarrow>* n'\<close> have "n -as'\<rightarrow>* sourcenode a'" and "n' = targetnode a'"
by(auto elim:path_split_snoc)
show ?case
proof(cases "as' = []")
case True
with \<open>n -as'\<rightarrow>* sourcenode a'\<close> have "n = sourcenode a'" by fast
with True \<open>n' = targetnode a'\<close> show ?thesis
by(simp add:sourcenodes_def targetnodes_def)
next
case False
from IH[OF \<open>n -as'\<rightarrow>* sourcenode a'\<close> this]
have "targetnodes as' = tl (sourcenodes as')@[sourcenode a']" .
with \<open>n' = targetnode a'\<close> False show ?thesis
by(simp add:sourcenodes_def targetnodes_def)
qed
qed
subsubsection \<open>Intraprocedural paths\<close>
definition intra_path :: "'node \<Rightarrow> 'edge list \<Rightarrow> 'node \<Rightarrow> bool"
("_ -_\<rightarrow>\<^sub>\<iota>* _" [51,0,0] 80)
where "n -as\<rightarrow>\<^sub>\<iota>* n' \<equiv> n -as\<rightarrow>* n' \<and> (\<forall>a \<in> set as. intra_kind(kind a))"
lemma intra_path_get_procs:
assumes "n -as\<rightarrow>\<^sub>\<iota>* n'" shows "get_proc n = get_proc n'"
proof -
from \<open>n -as\<rightarrow>\<^sub>\<iota>* n'\<close> have "n -as\<rightarrow>* n'" and "\<forall>a \<in> set as. intra_kind(kind a)"
by(simp_all add:intra_path_def)
thus ?thesis
proof(induct as arbitrary:n)
case Nil thus ?case by fastforce
next
case (Cons a' as')
note IH = \<open>\<And>n. \<lbrakk>n -as'\<rightarrow>* n'; \<forall>a\<in>set as'. intra_kind (kind a)\<rbrakk>
\<Longrightarrow> get_proc n = get_proc n'\<close>
from \<open>\<forall>a\<in>set (a'#as'). intra_kind (kind a)\<close>
have "intra_kind(kind a')" and "\<forall>a\<in>set as'. intra_kind (kind a)" by simp_all
from \<open>n -a'#as'\<rightarrow>* n'\<close> have "sourcenode a' = n" and "valid_edge a'"
and "targetnode a' -as'\<rightarrow>* n'" by(auto elim:path.cases)
from IH[OF \<open>targetnode a' -as'\<rightarrow>* n'\<close> \<open>\<forall>a\<in>set as'. intra_kind (kind a)\<close>]
have "get_proc (targetnode a') = get_proc n'" .
from \<open>valid_edge a'\<close> \<open>intra_kind(kind a')\<close>
have "get_proc (sourcenode a') = get_proc (targetnode a')"
by(rule get_proc_intra)
with \<open>sourcenode a' = n\<close> \<open>get_proc (targetnode a') = get_proc n'\<close>
show ?case by simp
qed
qed
lemma intra_path_Append:
"\<lbrakk>n -as\<rightarrow>\<^sub>\<iota>* n''; n'' -as'\<rightarrow>\<^sub>\<iota>* n'\<rbrakk> \<Longrightarrow> n -as@as'\<rightarrow>\<^sub>\<iota>* n'"
by(fastforce intro:path_Append simp:intra_path_def)
lemma get_proc_get_return_edges:
assumes "valid_edge a" and "a' \<in> get_return_edges a"
shows "get_proc(targetnode a) = get_proc(sourcenode a')"
proof -
from \<open>valid_edge a\<close> \<open>a' \<in> get_return_edges a\<close>
obtain a'' where "valid_edge a''" and "sourcenode a'' = targetnode a"
and "targetnode a'' = sourcenode a'" and "kind a'' = (\<lambda>cf. False)\<^sub>\<surd>"
by(fastforce dest:intra_proc_additional_edge)
from \<open>valid_edge a''\<close> \<open>kind a'' = (\<lambda>cf. False)\<^sub>\<surd>\<close>
have "get_proc(sourcenode a'') = get_proc(targetnode a'')"
by(fastforce intro:get_proc_intra simp:intra_kind_def)
with \<open>sourcenode a'' = targetnode a\<close> \<open>targetnode a'' = sourcenode a'\<close>
show ?thesis by simp
qed
subsubsection \<open>Valid paths\<close>
declare conj_cong[fundef_cong]
fun valid_path_aux :: "'edge list \<Rightarrow> 'edge list \<Rightarrow> bool"
where "valid_path_aux cs [] \<longleftrightarrow> True"
| "valid_path_aux cs (a#as) \<longleftrightarrow>
(case (kind a) of Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs \<Rightarrow> valid_path_aux (a#cs) as
| Q\<hookleftarrow>\<^bsub>p\<^esub>f \<Rightarrow> case cs of [] \<Rightarrow> valid_path_aux [] as
| c'#cs' \<Rightarrow> a \<in> get_return_edges c' \<and>
valid_path_aux cs' as
| _ \<Rightarrow> valid_path_aux cs as)"
lemma vpa_induct [consumes 1,case_names vpa_empty vpa_intra vpa_Call vpa_ReturnEmpty
vpa_ReturnCons]:
assumes major: "valid_path_aux xs ys"
and rules: "\<And>cs. P cs []"
"\<And>cs a as. \<lbrakk>intra_kind(kind a); valid_path_aux cs as; P cs as\<rbrakk> \<Longrightarrow> P cs (a#as)"
"\<And>cs a as Q r p fs. \<lbrakk>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs; valid_path_aux (a#cs) as; P (a#cs) as\<rbrakk>
\<Longrightarrow> P cs (a#as)"
"\<And>cs a as Q p f. \<lbrakk>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f; cs = []; valid_path_aux [] as; P [] as\<rbrakk>
\<Longrightarrow> P cs (a#as)"
"\<And>cs a as Q p f c' cs' . \<lbrakk>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f; cs = c'#cs'; valid_path_aux cs' as;
a \<in> get_return_edges c'; P cs' as\<rbrakk>
\<Longrightarrow> P cs (a#as)"
shows "P xs ys"
using major
apply(induct ys arbitrary: xs)
by(auto intro:rules split:edge_kind.split_asm list.split_asm simp:intra_kind_def)
lemma valid_path_aux_intra_path:
"\<forall>a \<in> set as. intra_kind(kind a) \<Longrightarrow> valid_path_aux cs as"
by(induct as,auto simp:intra_kind_def)
lemma valid_path_aux_callstack_prefix:
"valid_path_aux (cs@cs') as \<Longrightarrow> valid_path_aux cs as"
proof(induct "cs@cs'" as arbitrary:cs cs' rule:vpa_induct)
case vpa_empty thus ?case by simp
next
case (vpa_intra a as)
hence "valid_path_aux cs as" by simp
with \<open>intra_kind (kind a)\<close> show ?case by(cases "kind a",auto simp:intra_kind_def)
next
case (vpa_Call a as Q r p fs cs'' cs')
note IH = \<open>\<And>xs ys. a#cs''@cs' = xs@ys \<Longrightarrow> valid_path_aux xs as\<close>
have "a#cs''@cs' = (a#cs'')@cs'" by simp
from IH[OF this] have "valid_path_aux (a#cs'') as" .
with \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> show ?case by simp
next
case (vpa_ReturnEmpty a as Q p f cs'' cs')
hence "valid_path_aux cs'' as" by simp
with \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> \<open>cs''@cs' = []\<close> show ?case by simp
next
case (vpa_ReturnCons a as Q p f c' cs' csx csx')
note IH = \<open>\<And>xs ys. cs' = xs@ys \<Longrightarrow> valid_path_aux xs as\<close>
from \<open>csx@csx' = c'#cs'\<close>
have "csx = [] \<and> csx' = c'#cs' \<or> (\<exists>zs. csx = c'#zs \<and> zs@csx' = cs')"
by(simp add:append_eq_Cons_conv)
thus ?case
proof
assume "csx = [] \<and> csx' = c'#cs'"
hence "csx = []" and "csx' = c'#cs'" by simp_all
from \<open>csx' = c'#cs'\<close> have "cs' = []@tl csx'" by simp
from IH[OF this] have "valid_path_aux [] as" .
with \<open>csx = []\<close> \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> show ?thesis by simp
next
assume "\<exists>zs. csx = c'#zs \<and> zs@csx' = cs'"
then obtain zs where "csx = c'#zs" and "cs' = zs@csx'" by auto
from IH[OF \<open>cs' = zs@csx'\<close>] have "valid_path_aux zs as" .
with \<open>csx = c'#zs\<close> \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> \<open>a \<in> get_return_edges c'\<close>
show ?thesis by simp
qed
qed
fun upd_cs :: "'edge list \<Rightarrow> 'edge list \<Rightarrow> 'edge list"
where "upd_cs cs [] = cs"
| "upd_cs cs (a#as) =
(case (kind a) of Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs \<Rightarrow> upd_cs (a#cs) as
| Q\<hookleftarrow>\<^bsub>p\<^esub>f \<Rightarrow> case cs of [] \<Rightarrow> upd_cs cs as
| c'#cs' \<Rightarrow> upd_cs cs' as
| _ \<Rightarrow> upd_cs cs as)"
lemma upd_cs_empty [dest]:
"upd_cs cs [] = [] \<Longrightarrow> cs = []"
by(cases cs) auto
lemma upd_cs_intra_path:
"\<forall>a \<in> set as. intra_kind(kind a) \<Longrightarrow> upd_cs cs as = cs"
by(induct as,auto simp:intra_kind_def)
lemma upd_cs_Append:
"\<lbrakk>upd_cs cs as = cs'; upd_cs cs' as' = cs''\<rbrakk> \<Longrightarrow> upd_cs cs (as@as') = cs''"
by(induct as arbitrary:cs,auto split:edge_kind.split list.split)
lemma upd_cs_empty_split:
assumes "upd_cs cs as = []" and "cs \<noteq> []" and "as \<noteq> []"
obtains xs ys where "as = xs@ys" and "xs \<noteq> []" and "upd_cs cs xs = []"
and "\<forall>xs' ys'. xs = xs'@ys' \<and> ys' \<noteq> [] \<longrightarrow> upd_cs cs xs' \<noteq> []"
and "upd_cs [] ys = []"
proof(atomize_elim)
from \<open>upd_cs cs as = []\<close> \<open>cs \<noteq> []\<close> \<open>as \<noteq> []\<close>
show "\<exists>xs ys. as = xs@ys \<and> xs \<noteq> [] \<and> upd_cs cs xs = [] \<and>
(\<forall>xs' ys'. xs = xs'@ys' \<and> ys' \<noteq> [] \<longrightarrow> upd_cs cs xs' \<noteq> []) \<and>
upd_cs [] ys = []"
proof(induct as arbitrary:cs)
case Nil thus ?case by simp
next
case (Cons a' as')
note IH = \<open>\<And>cs. \<lbrakk>upd_cs cs as' = []; cs \<noteq> []; as' \<noteq> []\<rbrakk>
\<Longrightarrow> \<exists>xs ys. as' = xs@ys \<and> xs \<noteq> [] \<and> upd_cs cs xs = [] \<and>
(\<forall>xs' ys'. xs = xs'@ys' \<and> ys' \<noteq> [] \<longrightarrow> upd_cs cs xs' \<noteq> []) \<and>
upd_cs [] ys = []\<close>
show ?case
proof(cases "kind a'" rule:edge_kind_cases)
case Intra
with \<open>upd_cs cs (a'#as') = []\<close> have "upd_cs cs as' = []"
by(fastforce simp:intra_kind_def)
with \<open>cs \<noteq> []\<close> have "as' \<noteq> []" by fastforce
from IH[OF \<open>upd_cs cs as' = []\<close> \<open>cs \<noteq> []\<close> this] obtain xs ys where "as' = xs@ys"
and "xs \<noteq> []" and "upd_cs cs xs = []" and "upd_cs [] ys = []"
and "\<forall>xs' ys'. xs = xs'@ys' \<and> ys' \<noteq> [] \<longrightarrow> upd_cs cs xs' \<noteq> []" by blast
from \<open>upd_cs cs xs = []\<close> Intra have "upd_cs cs (a'#xs) = []"
by(fastforce simp:intra_kind_def)
from \<open>\<forall>xs' ys'. xs = xs'@ys' \<and> ys' \<noteq> [] \<longrightarrow> upd_cs cs xs' \<noteq> []\<close> \<open>xs \<noteq> []\<close> Intra
have "\<forall>xs' ys'. a'#xs = xs'@ys' \<and> ys' \<noteq> [] \<longrightarrow> upd_cs cs xs' \<noteq> []"
apply auto
apply(case_tac xs') apply(auto simp:intra_kind_def)
by(erule_tac x="[]" in allE,fastforce)+
with \<open>as' = xs@ys\<close> \<open>upd_cs cs (a'#xs) = []\<close> \<open>upd_cs [] ys = []\<close>
show ?thesis apply(rule_tac x="a'#xs" in exI) by fastforce
next
case (Call Q p f)
with \<open>upd_cs cs (a'#as') = []\<close> have "upd_cs (a'#cs) as' = []" by simp
with \<open>cs \<noteq> []\<close> have "as' \<noteq> []" by fastforce
from IH[OF \<open>upd_cs (a'#cs) as' = []\<close> _ this] obtain xs ys where "as' = xs@ys"
and "xs \<noteq> []" and "upd_cs (a'#cs) xs = []" and "upd_cs [] ys = []"
and "\<forall>xs' ys'. xs = xs'@ys' \<and> ys' \<noteq> [] \<longrightarrow> upd_cs (a'#cs) xs' \<noteq> []" by blast
from \<open>upd_cs (a'#cs) xs = []\<close> Call have "upd_cs cs (a'#xs) = []" by simp
from \<open>\<forall>xs' ys'. xs = xs'@ys' \<and> ys' \<noteq> [] \<longrightarrow> upd_cs (a'#cs) xs' \<noteq> []\<close>
\<open>xs \<noteq> []\<close> \<open>cs \<noteq> []\<close> Call
have "\<forall>xs' ys'. a'#xs = xs'@ys' \<and> ys' \<noteq> [] \<longrightarrow> upd_cs cs xs' \<noteq> []"
by auto(case_tac xs',auto)
with \<open>as' = xs@ys\<close> \<open>upd_cs cs (a'#xs) = []\<close> \<open>upd_cs [] ys = []\<close>
show ?thesis apply(rule_tac x="a'#xs" in exI) by fastforce
next
case (Return Q p f)
with \<open>upd_cs cs (a'#as') = []\<close> \<open>cs \<noteq> []\<close> obtain c' cs' where "cs = c'#cs'"
and "upd_cs cs' as' = []" by(cases cs) auto
show ?thesis
proof(cases "cs' = []")
case True
with \<open>cs = c'#cs'\<close> \<open>upd_cs cs' as' = []\<close> Return show ?thesis
apply(rule_tac x="[a']" in exI) apply clarsimp
by(case_tac xs') auto
next
case False
with \<open>upd_cs cs' as' = []\<close> have "as' \<noteq> []" by fastforce
from IH[OF \<open>upd_cs cs' as' = []\<close> False this] obtain xs ys where "as' = xs@ys"
and "xs \<noteq> []" and "upd_cs cs' xs = []" and "upd_cs [] ys = []"
and "\<forall>xs' ys'. xs = xs'@ys' \<and> ys' \<noteq> [] \<longrightarrow> upd_cs cs' xs' \<noteq> []" by blast
from \<open>upd_cs cs' xs = []\<close> \<open>cs = c'#cs'\<close> Return have "upd_cs cs (a'#xs) = []"
by simp
from \<open>\<forall>xs' ys'. xs = xs'@ys' \<and> ys' \<noteq> [] \<longrightarrow> upd_cs cs' xs' \<noteq> []\<close>
\<open>xs \<noteq> []\<close> \<open>cs = c'#cs'\<close> Return
have "\<forall>xs' ys'. a'#xs = xs'@ys' \<and> ys' \<noteq> [] \<longrightarrow> upd_cs cs xs' \<noteq> []"
by auto(case_tac xs',auto)
with \<open>as' = xs@ys\<close> \<open>upd_cs cs (a'#xs) = []\<close> \<open>upd_cs [] ys = []\<close>
show ?thesis apply(rule_tac x="a'#xs" in exI) by fastforce
qed
qed
qed
qed
lemma upd_cs_snoc_Return_Cons:
assumes "kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f"
shows "upd_cs cs as = c'#cs' \<Longrightarrow> upd_cs cs (as@[a]) = cs'"
proof(induct as arbitrary:cs)
case Nil
with \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> have "upd_cs cs [a] = cs'" by simp
thus ?case by simp
next
case (Cons a' as')
note IH = \<open>\<And>cs. upd_cs cs as' = c'#cs' \<Longrightarrow> upd_cs cs (as'@[a]) = cs'\<close>
show ?case
proof(cases "kind a'" rule:edge_kind_cases)
case Intra
with \<open>upd_cs cs (a'#as') = c'#cs'\<close>
have "upd_cs cs as' = c'#cs'" by(fastforce simp:intra_kind_def)
from IH[OF this] have "upd_cs cs (as'@[a]) = cs'" .
with Intra show ?thesis by(fastforce simp:intra_kind_def)
next
case Call
with \<open>upd_cs cs (a'#as') = c'#cs'\<close>
have "upd_cs (a'#cs) as' = c'#cs'" by simp
from IH[OF this] have "upd_cs (a'#cs) (as'@[a]) = cs'" .
with Call show ?thesis by simp
next
case Return
show ?thesis
proof(cases cs)
case Nil
with \<open>upd_cs cs (a'#as') = c'#cs'\<close> Return
have "upd_cs cs as' = c'#cs'" by simp
from IH[OF this] have "upd_cs cs (as'@[a]) = cs'" .
with Nil Return show ?thesis by simp
next
case (Cons cx csx)
with \<open>upd_cs cs (a'#as') = c'#cs'\<close> Return
have "upd_cs csx as' = c'#cs'" by simp
from IH[OF this] have "upd_cs csx (as'@[a]) = cs'" .
with Cons Return show ?thesis by simp
qed
qed
qed
lemma upd_cs_snoc_Call:
assumes "kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs"
shows "upd_cs cs (as@[a]) = a#(upd_cs cs as)"
proof(induct as arbitrary:cs)
case Nil
with \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> show ?case by simp
next
case (Cons a' as')
note IH = \<open>\<And>cs. upd_cs cs (as'@[a]) = a#upd_cs cs as'\<close>
show ?case
proof(cases "kind a'" rule:edge_kind_cases)
case Intra
with IH[of cs] show ?thesis by(fastforce simp:intra_kind_def)
next
case Call
with IH[of "a'#cs"] show ?thesis by simp
next
case Return
show ?thesis
proof(cases cs)
case Nil
with IH[of "[]"] Return show ?thesis by simp
next
case (Cons cx csx)
with IH[of csx] Return show ?thesis by simp
qed
qed
qed
lemma valid_path_aux_split:
assumes "valid_path_aux cs (as@as')"
shows "valid_path_aux cs as" and "valid_path_aux (upd_cs cs as) as'"
using \<open>valid_path_aux cs (as@as')\<close>
proof(induct cs "as@as'" arbitrary:as as' rule:vpa_induct)
case (vpa_intra cs a as as'')
note IH1 = \<open>\<And>xs ys. as = xs@ys \<Longrightarrow> valid_path_aux cs xs\<close>
note IH2 = \<open>\<And>xs ys. as = xs@ys \<Longrightarrow> valid_path_aux (upd_cs cs xs) ys\<close>
{ case 1
from vpa_intra
have "as'' = [] \<and> a#as = as' \<or> (\<exists>xs. a#xs = as'' \<and> as = xs@as')"
by(simp add:Cons_eq_append_conv)
thus ?case
proof
assume "as'' = [] \<and> a#as = as'"
thus ?thesis by simp
next
assume "\<exists>xs. a#xs = as'' \<and> as = xs@as'"
then obtain xs where "a#xs = as''" and "as = xs@as'" by auto
from IH1[OF \<open>as = xs@as'\<close>] have "valid_path_aux cs xs" .
with \<open>a#xs = as''\<close> \<open>intra_kind (kind a)\<close>
show ?thesis by(fastforce simp:intra_kind_def)
qed
next
case 2
from vpa_intra
have "as'' = [] \<and> a#as = as' \<or> (\<exists>xs. a#xs = as'' \<and> as = xs@as')"
by(simp add:Cons_eq_append_conv)
thus ?case
proof
assume "as'' = [] \<and> a#as = as'"
hence "as = []@tl as'" by(cases as') auto
from IH2[OF this] have "valid_path_aux (upd_cs cs []) (tl as')" by simp
with \<open>as'' = [] \<and> a#as = as'\<close> \<open>intra_kind (kind a)\<close>
show ?thesis by(fastforce simp:intra_kind_def)
next
assume "\<exists>xs. a#xs = as'' \<and> as = xs@as'"
then obtain xs where "a#xs = as''" and "as = xs@as'" by auto
from IH2[OF \<open>as = xs@as'\<close>] have "valid_path_aux (upd_cs cs xs) as'" .
from \<open>a#xs = as''\<close> \<open>intra_kind (kind a)\<close>
have "upd_cs cs xs = upd_cs cs as''" by(fastforce simp:intra_kind_def)
with \<open>valid_path_aux (upd_cs cs xs) as'\<close>
show ?thesis by simp
qed
}
next
case (vpa_Call cs a as Q r p fs as'')
note IH1 = \<open>\<And>xs ys. as = xs@ys \<Longrightarrow> valid_path_aux (a#cs) xs\<close>
note IH2 = \<open>\<And>xs ys. as = xs@ys \<Longrightarrow> valid_path_aux (upd_cs (a#cs) xs) ys\<close>
{ case 1
from vpa_Call
have "as'' = [] \<and> a#as = as' \<or> (\<exists>xs. a#xs = as'' \<and> as = xs@as')"
by(simp add:Cons_eq_append_conv)
thus ?case
proof
assume "as'' = [] \<and> a#as = as'"
thus ?thesis by simp
next
assume "\<exists>xs. a#xs = as'' \<and> as = xs@as'"
then obtain xs where "a#xs = as''" and "as = xs@as'" by auto
from IH1[OF \<open>as = xs@as'\<close>] have "valid_path_aux (a#cs) xs" .
with \<open>a#xs = as''\<close>[THEN sym] \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close>
show ?thesis by simp
qed
next
case 2
from vpa_Call
have "as'' = [] \<and> a#as = as' \<or> (\<exists>xs. a#xs = as'' \<and> as = xs@as')"
by(simp add:Cons_eq_append_conv)
thus ?case
proof
assume "as'' = [] \<and> a#as = as'"
hence "as = []@tl as'" by(cases as') auto
from IH2[OF this] have "valid_path_aux (upd_cs (a#cs) []) (tl as')" .
with \<open>as'' = [] \<and> a#as = as'\<close> \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close>
show ?thesis by clarsimp
next
assume "\<exists>xs. a#xs = as'' \<and> as = xs@as'"
then obtain xs where "a#xs = as''" and "as = xs@as'" by auto
from IH2[OF \<open>as = xs@as'\<close>] have "valid_path_aux (upd_cs (a # cs) xs) as'" .
with \<open>a#xs = as''\<close>[THEN sym] \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close>
show ?thesis by simp
qed
}
next
case (vpa_ReturnEmpty cs a as Q p f as'')
note IH1 = \<open>\<And>xs ys. as = xs@ys \<Longrightarrow> valid_path_aux [] xs\<close>
note IH2 = \<open>\<And>xs ys. as = xs@ys \<Longrightarrow> valid_path_aux (upd_cs [] xs) ys\<close>
{ case 1
from vpa_ReturnEmpty
have "as'' = [] \<and> a#as = as' \<or> (\<exists>xs. a#xs = as'' \<and> as = xs@as')"
by(simp add:Cons_eq_append_conv)
thus ?case
proof
assume "as'' = [] \<and> a#as = as'"
thus ?thesis by simp
next
assume "\<exists>xs. a#xs = as'' \<and> as = xs@as'"
then obtain xs where "a#xs = as''" and "as = xs@as'" by auto
from IH1[OF \<open>as = xs@as'\<close>] have "valid_path_aux [] xs" .
with \<open>a#xs = as''\<close>[THEN sym] \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> \<open>cs = []\<close>
show ?thesis by simp
qed
next
case 2
from vpa_ReturnEmpty
have "as'' = [] \<and> a#as = as' \<or> (\<exists>xs. a#xs = as'' \<and> as = xs@as')"
by(simp add:Cons_eq_append_conv)
thus ?case
proof
assume "as'' = [] \<and> a#as = as'"
hence "as = []@tl as'" by(cases as') auto
from IH2[OF this] have "valid_path_aux [] (tl as')" by simp
with \<open>as'' = [] \<and> a#as = as'\<close> \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> \<open>cs = []\<close>
show ?thesis by fastforce
next
assume "\<exists>xs. a#xs = as'' \<and> as = xs@as'"
then obtain xs where "a#xs = as''" and "as = xs@as'" by auto
from IH2[OF \<open>as = xs@as'\<close>] have "valid_path_aux (upd_cs [] xs) as'" .
from \<open>a#xs = as''\<close>[THEN sym] \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> \<open>cs = []\<close>
have "upd_cs [] xs = upd_cs cs as''" by simp
with \<open>valid_path_aux (upd_cs [] xs) as'\<close> show ?thesis by simp
qed
}
next
case (vpa_ReturnCons cs a as Q p f c' cs' as'')
note IH1 = \<open>\<And>xs ys. as = xs@ys \<Longrightarrow> valid_path_aux cs' xs\<close>
note IH2 = \<open>\<And>xs ys. as = xs@ys \<Longrightarrow> valid_path_aux (upd_cs cs' xs) ys\<close>
{ case 1
from vpa_ReturnCons
have "as'' = [] \<and> a#as = as' \<or> (\<exists>xs. a#xs = as'' \<and> as = xs@as')"
by(simp add:Cons_eq_append_conv)
thus ?case
proof
assume "as'' = [] \<and> a#as = as'"
thus ?thesis by simp
next
assume "\<exists>xs. a#xs = as'' \<and> as = xs@as'"
then obtain xs where "a#xs = as''" and "as = xs@as'" by auto
from IH1[OF \<open>as = xs@as'\<close>] have "valid_path_aux cs' xs" .
with \<open>a#xs = as''\<close>[THEN sym] \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> \<open>cs = c'#cs'\<close>
\<open>a \<in> get_return_edges c'\<close>
show ?thesis by simp
qed
next
case 2
from vpa_ReturnCons
have "as'' = [] \<and> a#as = as' \<or> (\<exists>xs. a#xs = as'' \<and> as = xs@as')"
by(simp add:Cons_eq_append_conv)
thus ?case
proof
assume "as'' = [] \<and> a#as = as'"
hence "as = []@tl as'" by(cases as') auto
from IH2[OF this] have "valid_path_aux (upd_cs cs' []) (tl as')" .
with \<open>as'' = [] \<and> a#as = as'\<close> \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> \<open>cs = c'#cs'\<close>
\<open>a \<in> get_return_edges c'\<close>
show ?thesis by fastforce
next
assume "\<exists>xs. a#xs = as'' \<and> as = xs@as'"
then obtain xs where "a#xs = as''" and "as = xs@as'" by auto
from IH2[OF \<open>as = xs@as'\<close>] have "valid_path_aux (upd_cs cs' xs) as'" .
from \<open>a#xs = as''\<close>[THEN sym] \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> \<open>cs = c'#cs'\<close>
have "upd_cs cs' xs = upd_cs cs as''" by simp
with \<open>valid_path_aux (upd_cs cs' xs) as'\<close> show ?thesis by simp
qed
}
qed simp_all
lemma valid_path_aux_Append:
"\<lbrakk>valid_path_aux cs as; valid_path_aux (upd_cs cs as) as'\<rbrakk>
\<Longrightarrow> valid_path_aux cs (as@as')"
by(induct rule:vpa_induct,auto simp:intra_kind_def)
lemma vpa_snoc_Call:
assumes "kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs"
shows "valid_path_aux cs as \<Longrightarrow> valid_path_aux cs (as@[a])"
proof(induct rule:vpa_induct)
case (vpa_empty cs)
from \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> have "valid_path_aux cs [a]" by simp
thus ?case by simp
next
case (vpa_intra cs a' as')
from \<open>valid_path_aux cs (as'@[a])\<close> \<open>intra_kind (kind a')\<close>
have "valid_path_aux cs (a'#(as'@[a]))"
by(fastforce simp:intra_kind_def)
thus ?case by simp
next
case (vpa_Call cs a' as' Q' r' p' fs')
from \<open>valid_path_aux (a'#cs) (as'@[a])\<close> \<open>kind a' = Q':r'\<hookrightarrow>\<^bsub>p'\<^esub>fs'\<close>
have "valid_path_aux cs (a'#(as'@[a]))" by simp
thus ?case by simp
next
case (vpa_ReturnEmpty cs a' as' Q' p' f')
from \<open>valid_path_aux [] (as'@[a])\<close> \<open>kind a' = Q'\<hookleftarrow>\<^bsub>p'\<^esub>f'\<close> \<open>cs = []\<close>
have "valid_path_aux cs (a'#(as'@[a]))" by simp
thus ?case by simp
next
case (vpa_ReturnCons cs a' as' Q' p' f' c' cs')
from \<open>valid_path_aux cs' (as'@[a])\<close> \<open>kind a' = Q'\<hookleftarrow>\<^bsub>p'\<^esub>f'\<close> \<open>cs = c'#cs'\<close>
\<open>a' \<in> get_return_edges c'\<close>
have "valid_path_aux cs (a'#(as'@[a]))" by simp
thus ?case by simp
qed
definition valid_path :: "'edge list \<Rightarrow> bool"
where "valid_path as \<equiv> valid_path_aux [] as"
lemma valid_path_aux_valid_path:
"valid_path_aux cs as \<Longrightarrow> valid_path as"
by(fastforce intro:valid_path_aux_callstack_prefix simp:valid_path_def)
lemma valid_path_split:
assumes "valid_path (as@as')" shows "valid_path as" and "valid_path as'"
using \<open>valid_path (as@as')\<close>
apply(auto simp:valid_path_def)
apply(erule valid_path_aux_split)
apply(drule valid_path_aux_split(2))
by(fastforce intro:valid_path_aux_callstack_prefix)
definition valid_path' :: "'node \<Rightarrow> 'edge list \<Rightarrow> 'node \<Rightarrow> bool"
("_ -_\<rightarrow>\<^sub>\<surd>* _" [51,0,0] 80)
where vp_def:"n -as\<rightarrow>\<^sub>\<surd>* n' \<equiv> n -as\<rightarrow>* n' \<and> valid_path as"
lemma intra_path_vp:
assumes "n -as\<rightarrow>\<^sub>\<iota>* n'" shows "n -as\<rightarrow>\<^sub>\<surd>* n'"
proof -
from \<open>n -as\<rightarrow>\<^sub>\<iota>* n'\<close> have "n -as\<rightarrow>* n'" and "\<forall>a \<in> set as. intra_kind(kind a)"
by(simp_all add:intra_path_def)
from \<open>\<forall>a \<in> set as. intra_kind(kind a)\<close> have "valid_path_aux [] as"
by(rule valid_path_aux_intra_path)
thus ?thesis using \<open>n -as\<rightarrow>* n'\<close> by(simp add:vp_def valid_path_def)
qed
lemma vp_split_Cons:
assumes "n -as\<rightarrow>\<^sub>\<surd>* n'" and "as \<noteq> []"
obtains a' as' where "as = a'#as'" and "n = sourcenode a'"
and "valid_edge a'" and "targetnode a' -as'\<rightarrow>\<^sub>\<surd>* n'"
proof(atomize_elim)
from \<open>n -as\<rightarrow>\<^sub>\<surd>* n'\<close> \<open>as \<noteq> []\<close> obtain a' as' where "as = a'#as'"
and "n = sourcenode a'" and "valid_edge a'" and "targetnode a' -as'\<rightarrow>* n'"
by(fastforce elim:path_split_Cons simp:vp_def)
from \<open>n -as\<rightarrow>\<^sub>\<surd>* n'\<close> have "valid_path as" by(simp add:vp_def)
from \<open>as = a'#as'\<close> have "as = [a']@as'" by simp
with \<open>valid_path as\<close> have "valid_path ([a']@as')" by simp
hence "valid_path as'" by(rule valid_path_split)
with \<open>targetnode a' -as'\<rightarrow>* n'\<close> have "targetnode a' -as'\<rightarrow>\<^sub>\<surd>* n'" by(simp add:vp_def)
with \<open>as = a'#as'\<close> \<open>n = sourcenode a'\<close> \<open>valid_edge a'\<close>
show "\<exists>a' as'. as = a'#as' \<and> n = sourcenode a' \<and> valid_edge a' \<and>
targetnode a' -as'\<rightarrow>\<^sub>\<surd>* n'" by blast
qed
lemma vp_split_snoc:
assumes "n -as\<rightarrow>\<^sub>\<surd>* n'" and "as \<noteq> []"
obtains a' as' where "as = as'@[a']" and "n -as'\<rightarrow>\<^sub>\<surd>* sourcenode a'"
and "valid_edge a'" and "n' = targetnode a'"
proof(atomize_elim)
from \<open>n -as\<rightarrow>\<^sub>\<surd>* n'\<close> \<open>as \<noteq> []\<close> obtain a' as' where "as = as'@[a']"
and "n -as'\<rightarrow>* sourcenode a'" and "valid_edge a'" and "n' = targetnode a'"
by(clarsimp simp:vp_def)(erule path_split_snoc,auto)
from \<open>n -as\<rightarrow>\<^sub>\<surd>* n'\<close> \<open>as = as'@[a']\<close> have "valid_path (as'@[a'])" by(simp add:vp_def)
hence "valid_path as'" by(rule valid_path_split)
with \<open>n -as'\<rightarrow>* sourcenode a'\<close> have "n -as'\<rightarrow>\<^sub>\<surd>* sourcenode a'" by(simp add:vp_def)
with \<open>as = as'@[a']\<close> \<open>valid_edge a'\<close> \<open>n' = targetnode a'\<close>
show "\<exists>as' a'. as = as'@[a'] \<and> n -as'\<rightarrow>\<^sub>\<surd>* sourcenode a' \<and> valid_edge a' \<and>
n' = targetnode a'"
by blast
qed
lemma vp_split:
assumes "n -as@a#as'\<rightarrow>\<^sub>\<surd>* n'"
shows "n -as\<rightarrow>\<^sub>\<surd>* sourcenode a" and "valid_edge a" and "targetnode a -as'\<rightarrow>\<^sub>\<surd>* n'"
proof -
from \<open>n -as@a#as'\<rightarrow>\<^sub>\<surd>* n'\<close> have "n -as\<rightarrow>* sourcenode a" and "valid_edge a"
and "targetnode a -as'\<rightarrow>* n'"
by(auto intro:path_split simp:vp_def)
from \<open>n -as@a#as'\<rightarrow>\<^sub>\<surd>* n'\<close> have "valid_path (as@a#as')" by(simp add:vp_def)
hence "valid_path as" and "valid_path (a#as')" by(auto intro:valid_path_split)
from \<open>valid_path (a#as')\<close> have "valid_path ([a]@as')" by simp
hence "valid_path as'" by(rule valid_path_split)
with \<open>n -as\<rightarrow>* sourcenode a\<close> \<open>valid_path as\<close> \<open>valid_edge a\<close> \<open>targetnode a -as'\<rightarrow>* n'\<close>
show "n -as\<rightarrow>\<^sub>\<surd>* sourcenode a" "valid_edge a" "targetnode a -as'\<rightarrow>\<^sub>\<surd>* n'"
by(auto simp:vp_def)
qed
lemma vp_split_second:
assumes "n -as@a#as'\<rightarrow>\<^sub>\<surd>* n'" shows "sourcenode a -a#as'\<rightarrow>\<^sub>\<surd>* n'"
proof -
from \<open>n -as@a#as'\<rightarrow>\<^sub>\<surd>* n'\<close> have "sourcenode a -a#as'\<rightarrow>* n'"
by(fastforce elim:path_split_second simp:vp_def)
from \<open>n -as@a#as'\<rightarrow>\<^sub>\<surd>* n'\<close> have "valid_path (as@a#as')" by(simp add:vp_def)
hence "valid_path (a#as')" by(rule valid_path_split)
with \<open>sourcenode a -a#as'\<rightarrow>* n'\<close> show ?thesis by(simp add:vp_def)
qed
function valid_path_rev_aux :: "'edge list \<Rightarrow> 'edge list \<Rightarrow> bool"
where "valid_path_rev_aux cs [] \<longleftrightarrow> True"
| "valid_path_rev_aux cs (as@[a]) \<longleftrightarrow>
(case (kind a) of Q\<hookleftarrow>\<^bsub>p\<^esub>f \<Rightarrow> valid_path_rev_aux (a#cs) as
| Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs \<Rightarrow> case cs of [] \<Rightarrow> valid_path_rev_aux [] as
| c'#cs' \<Rightarrow> c' \<in> get_return_edges a \<and>
valid_path_rev_aux cs' as
| _ \<Rightarrow> valid_path_rev_aux cs as)"
by auto(case_tac b rule:rev_cases,auto)
termination by lexicographic_order
lemma vpra_induct [consumes 1,case_names vpra_empty vpra_intra vpra_Return
vpra_CallEmpty vpra_CallCons]:
assumes major: "valid_path_rev_aux xs ys"
and rules: "\<And>cs. P cs []"
"\<And>cs a as. \<lbrakk>intra_kind(kind a); valid_path_rev_aux cs as; P cs as\<rbrakk>
\<Longrightarrow> P cs (as@[a])"
"\<And>cs a as Q p f. \<lbrakk>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f; valid_path_rev_aux (a#cs) as; P (a#cs) as\<rbrakk>
\<Longrightarrow> P cs (as@[a])"
"\<And>cs a as Q r p fs. \<lbrakk>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs; cs = []; valid_path_rev_aux [] as;
P [] as\<rbrakk> \<Longrightarrow> P cs (as@[a])"
"\<And>cs a as Q r p fs c' cs'. \<lbrakk>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs; cs = c'#cs';
valid_path_rev_aux cs' as; c' \<in> get_return_edges a; P cs' as\<rbrakk>
\<Longrightarrow> P cs (as@[a])"
shows "P xs ys"
using major
apply(induct ys arbitrary:xs rule:rev_induct)
by(auto intro:rules split:edge_kind.split_asm list.split_asm simp:intra_kind_def)
lemma vpra_callstack_prefix:
"valid_path_rev_aux (cs@cs') as \<Longrightarrow> valid_path_rev_aux cs as"
proof(induct "cs@cs'" as arbitrary:cs cs' rule:vpra_induct)
case vpra_empty thus ?case by simp
next
case (vpra_intra a as)
hence "valid_path_rev_aux cs as" by simp
with \<open>intra_kind (kind a)\<close> show ?case by(fastforce simp:intra_kind_def)
next
case (vpra_Return a as Q p f)
note IH = \<open>\<And>ds ds'. a#cs@cs' = ds@ds' \<Longrightarrow> valid_path_rev_aux ds as\<close>
have "a#cs@cs' = (a#cs)@cs'" by simp
from IH[OF this] have "valid_path_rev_aux (a#cs) as" .
with \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> show ?case by simp
next
case (vpra_CallEmpty a as Q r p fs)
hence "valid_path_rev_aux cs as" by simp
with \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> \<open>cs@cs' = []\<close> show ?case by simp
next
case (vpra_CallCons a as Q r p fs c' csx)
note IH = \<open>\<And>cs cs'. csx = cs@cs' \<Longrightarrow> valid_path_rev_aux cs as\<close>
from \<open>cs@cs' = c'#csx\<close>
have "(cs = [] \<and> cs' = c'#csx) \<or> (\<exists>zs. cs = c'#zs \<and> zs@cs' = csx)"
by(simp add:append_eq_Cons_conv)
thus ?case
proof
assume "cs = [] \<and> cs' = c'#csx"
hence "cs = []" and "cs' = c'#csx" by simp_all
from \<open>cs' = c'#csx\<close> have "csx = []@tl cs'" by simp
from IH[OF this] have "valid_path_rev_aux [] as" .
with \<open>cs = []\<close> \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> show ?thesis by simp
next
assume "\<exists>zs. cs = c'#zs \<and> zs@cs' = csx"
then obtain zs where "cs = c'#zs" and "csx = zs@cs'" by auto
from IH[OF \<open>csx = zs@cs'\<close>] have "valid_path_rev_aux zs as" .
with \<open>cs = c'#zs\<close> \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> \<open>c' \<in> get_return_edges a\<close> show ?thesis by simp
qed
qed
function upd_rev_cs :: "'edge list \<Rightarrow> 'edge list \<Rightarrow> 'edge list"
where "upd_rev_cs cs [] = cs"
| "upd_rev_cs cs (as@[a]) =
(case (kind a) of Q\<hookleftarrow>\<^bsub>p\<^esub>f \<Rightarrow> upd_rev_cs (a#cs) as
| Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs \<Rightarrow> case cs of [] \<Rightarrow> upd_rev_cs cs as
| c'#cs' \<Rightarrow> upd_rev_cs cs' as
| _ \<Rightarrow> upd_rev_cs cs as)"
by auto(case_tac b rule:rev_cases,auto)
termination by lexicographic_order
lemma upd_rev_cs_empty [dest]:
"upd_rev_cs cs [] = [] \<Longrightarrow> cs = []"
by(cases cs) auto
lemma valid_path_rev_aux_split:
assumes "valid_path_rev_aux cs (as@as')"
shows "valid_path_rev_aux cs as'" and "valid_path_rev_aux (upd_rev_cs cs as') as"
using \<open>valid_path_rev_aux cs (as@as')\<close>
proof(induct cs "as@as'" arbitrary:as as' rule:vpra_induct)
case (vpra_intra cs a as as'')
note IH1 = \<open>\<And>xs ys. as = xs@ys \<Longrightarrow> valid_path_rev_aux cs ys\<close>
note IH2 = \<open>\<And>xs ys. as = xs@ys \<Longrightarrow> valid_path_rev_aux (upd_rev_cs cs ys) xs\<close>
{ case 1
from vpra_intra
have "as' = [] \<and> as@[a] = as'' \<or> (\<exists>xs. as = as''@xs \<and> xs@[a] = as')"
by(cases as' rule:rev_cases) auto
thus ?case
proof
assume "as' = [] \<and> as@[a] = as''"
thus ?thesis by simp
next
assume "\<exists>xs. as = as''@xs \<and> xs@[a] = as'"
then obtain xs where "as = as''@xs" and "xs@[a] = as'" by auto
from IH1[OF \<open>as = as''@xs\<close>] have "valid_path_rev_aux cs xs" .
with \<open>xs@[a] = as'\<close> \<open>intra_kind (kind a)\<close>
show ?thesis by(fastforce simp:intra_kind_def)
qed
next
case 2
from vpra_intra
have "as' = [] \<and> as@[a] = as'' \<or> (\<exists>xs. as = as''@xs \<and> xs@[a] = as')"
by(cases as' rule:rev_cases) auto
thus ?case
proof
assume "as' = [] \<and> as@[a] = as''"
hence "as = butlast as''@[]" by(cases as) auto
from IH2[OF this] have "valid_path_rev_aux (upd_rev_cs cs []) (butlast as'')" .
with \<open>as' = [] \<and> as@[a] = as''\<close> \<open>intra_kind (kind a)\<close>
show ?thesis by(fastforce simp:intra_kind_def)
next
assume "\<exists>xs. as = as''@xs \<and> xs@[a] = as'"
then obtain xs where "as = as''@xs" and "xs@[a] = as'" by auto
from IH2[OF \<open>as = as''@xs\<close>] have "valid_path_rev_aux (upd_rev_cs cs xs) as''" .
from \<open>xs@[a] = as'\<close> \<open>intra_kind (kind a)\<close>
have "upd_rev_cs cs xs = upd_rev_cs cs as'" by(fastforce simp:intra_kind_def)
with \<open>valid_path_rev_aux (upd_rev_cs cs xs) as''\<close>
show ?thesis by simp
qed
}
next
case (vpra_Return cs a as Q p f as'')
note IH1 = \<open>\<And>xs ys. as = xs@ys \<Longrightarrow> valid_path_rev_aux (a#cs) ys\<close>
note IH2 = \<open>\<And>xs ys. as = xs@ys \<Longrightarrow> valid_path_rev_aux (upd_rev_cs (a#cs) ys) xs\<close>
{ case 1
from vpra_Return
have "as' = [] \<and> as@[a] = as'' \<or> (\<exists>xs. as = as''@xs \<and> xs@[a] = as')"
by(cases as' rule:rev_cases) auto
thus ?case
proof
assume "as' = [] \<and> as@[a] = as''"
thus ?thesis by simp
next
assume "\<exists>xs. as = as''@xs \<and> xs@[a] = as'"
then obtain xs where "as = as''@xs" and "xs@[a] = as'" by auto
from IH1[OF \<open>as = as''@xs\<close>] have "valid_path_rev_aux (a#cs) xs" .
with \<open>xs@[a] = as'\<close> \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close>
show ?thesis by fastforce
qed
next
case 2
from vpra_Return
have "as' = [] \<and> as@[a] = as'' \<or> (\<exists>xs. as = as''@xs \<and> xs@[a] = as')"
by(cases as' rule:rev_cases) auto
thus ?case
proof
assume "as' = [] \<and> as@[a] = as''"
hence "as = butlast as''@[]" by(cases as) auto
from IH2[OF this]
have "valid_path_rev_aux (upd_rev_cs (a#cs) []) (butlast as'')" .
with \<open>as' = [] \<and> as@[a] = as''\<close> \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close>
show ?thesis by fastforce
next
assume "\<exists>xs. as = as''@xs \<and> xs@[a] = as'"
then obtain xs where "as = as''@xs" and "xs@[a] = as'" by auto
from IH2[OF \<open>as = as''@xs\<close>]
have "valid_path_rev_aux (upd_rev_cs (a#cs) xs) as''" .
from \<open>xs@[a] = as'\<close> \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close>
have "upd_rev_cs (a#cs) xs = upd_rev_cs cs as'" by fastforce
with \<open>valid_path_rev_aux (upd_rev_cs (a#cs) xs) as''\<close>
show ?thesis by simp
qed
}
next
case (vpra_CallEmpty cs a as Q r p fs as'')
note IH1 = \<open>\<And>xs ys. as = xs@ys \<Longrightarrow> valid_path_rev_aux [] ys\<close>
note IH2 = \<open>\<And>xs ys. as = xs@ys \<Longrightarrow> valid_path_rev_aux (upd_rev_cs [] ys) xs\<close>
{ case 1
from vpra_CallEmpty
have "as' = [] \<and> as@[a] = as'' \<or> (\<exists>xs. as = as''@xs \<and> xs@[a] = as')"
by(cases as' rule:rev_cases) auto
thus ?case
proof
assume "as' = [] \<and> as@[a] = as''"
thus ?thesis by simp
next
assume "\<exists>xs. as = as''@xs \<and> xs@[a] = as'"
then obtain xs where "as = as''@xs" and "xs@[a] = as'" by auto
from IH1[OF \<open>as = as''@xs\<close>] have "valid_path_rev_aux [] xs" .
with \<open>xs@[a] = as'\<close> \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> \<open>cs = []\<close>
show ?thesis by fastforce
qed
next
case 2
from vpra_CallEmpty
have "as' = [] \<and> as@[a] = as'' \<or> (\<exists>xs. as = as''@xs \<and> xs@[a] = as')"
by(cases as' rule:rev_cases) auto
thus ?case
proof
assume "as' = [] \<and> as@[a] = as''"
hence "as = butlast as''@[]" by(cases as) auto
from IH2[OF this]
have "valid_path_rev_aux (upd_rev_cs [] []) (butlast as'')" .
with \<open>as' = [] \<and> as@[a] = as''\<close> \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> \<open>cs = []\<close>
show ?thesis by fastforce
next
assume "\<exists>xs. as = as''@xs \<and> xs@[a] = as'"
then obtain xs where "as = as''@xs" and "xs@[a] = as'" by auto
from IH2[OF \<open>as = as''@xs\<close>]
have "valid_path_rev_aux (upd_rev_cs [] xs) as''" .
with \<open>xs@[a] = as'\<close> \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> \<open>cs = []\<close>
show ?thesis by fastforce
qed
}
next
case (vpra_CallCons cs a as Q r p fs c' cs' as'')
note IH1 = \<open>\<And>xs ys. as = xs@ys \<Longrightarrow> valid_path_rev_aux cs' ys\<close>
note IH2 = \<open>\<And>xs ys. as = xs@ys \<Longrightarrow> valid_path_rev_aux (upd_rev_cs cs' ys) xs\<close>
{ case 1
from vpra_CallCons
have "as' = [] \<and> as@[a] = as'' \<or> (\<exists>xs. as = as''@xs \<and> xs@[a] = as')"
by(cases as' rule:rev_cases) auto
thus ?case
proof
assume "as' = [] \<and> as@[a] = as''"
thus ?thesis by simp
next
assume "\<exists>xs. as = as''@xs \<and> xs@[a] = as'"
then obtain xs where "as = as''@xs" and "xs@[a] = as'" by auto
from IH1[OF \<open>as = as''@xs\<close>] have "valid_path_rev_aux cs' xs" .
with \<open>xs@[a] = as'\<close> \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> \<open>cs = c' # cs'\<close> \<open>c' \<in> get_return_edges a\<close>
show ?thesis by fastforce
qed
next
case 2
from vpra_CallCons
have "as' = [] \<and> as@[a] = as'' \<or> (\<exists>xs. as = as''@xs \<and> xs@[a] = as')"
by(cases as' rule:rev_cases) auto
thus ?case
proof
assume "as' = [] \<and> as@[a] = as''"
hence "as = butlast as''@[]" by(cases as) auto
from IH2[OF this]
have "valid_path_rev_aux (upd_rev_cs cs' []) (butlast as'')" .
with \<open>as' = [] \<and> as@[a] = as''\<close> \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> \<open>cs = c' # cs'\<close>
\<open>c' \<in> get_return_edges a\<close> show ?thesis by fastforce
next
assume "\<exists>xs. as = as''@xs \<and> xs@[a] = as'"
then obtain xs where "as = as''@xs" and "xs@[a] = as'" by auto
from IH2[OF \<open>as = as''@xs\<close>]
have "valid_path_rev_aux (upd_rev_cs cs' xs) as''" .
with \<open>xs@[a] = as'\<close> \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> \<open>cs = c' # cs'\<close>
\<open>c' \<in> get_return_edges a\<close>
show ?thesis by fastforce
qed
}
qed simp_all
lemma valid_path_rev_aux_Append:
"\<lbrakk>valid_path_rev_aux cs as'; valid_path_rev_aux (upd_rev_cs cs as') as\<rbrakk>
\<Longrightarrow> valid_path_rev_aux cs (as@as')"
by(induct rule:vpra_induct,
auto simp:intra_kind_def simp del:append_assoc simp:append_assoc[THEN sym])
lemma vpra_Cons_intra:
assumes "intra_kind(kind a)"
shows "valid_path_rev_aux cs as \<Longrightarrow> valid_path_rev_aux cs (a#as)"
proof(induct rule:vpra_induct)
case (vpra_empty cs)
have "valid_path_rev_aux cs []" by simp
with \<open>intra_kind(kind a)\<close> have "valid_path_rev_aux cs ([]@[a])"
by(simp only:valid_path_rev_aux.simps intra_kind_def,fastforce)
thus ?case by simp
qed(simp only:append_Cons[THEN sym] valid_path_rev_aux.simps intra_kind_def,fastforce)+
lemma vpra_Cons_Return:
assumes "kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f"
shows "valid_path_rev_aux cs as \<Longrightarrow> valid_path_rev_aux cs (a#as)"
proof(induct rule:vpra_induct)
case (vpra_empty cs)
from \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> have "valid_path_rev_aux cs ([]@[a])"
by(simp only:valid_path_rev_aux.simps,clarsimp)
thus ?case by simp
next
case (vpra_intra cs a' as')
from \<open>valid_path_rev_aux cs (a#as')\<close> \<open>intra_kind (kind a')\<close>
have "valid_path_rev_aux cs ((a#as')@[a'])"
by(simp only:valid_path_rev_aux.simps,fastforce simp:intra_kind_def)
thus ?case by simp
next
case (vpra_Return cs a' as' Q' p' f')
from \<open>valid_path_rev_aux (a'#cs) (a#as')\<close> \<open>kind a' = Q'\<hookleftarrow>\<^bsub>p'\<^esub>f'\<close>
have "valid_path_rev_aux cs ((a#as')@[a'])"
by(simp only:valid_path_rev_aux.simps,clarsimp)
thus ?case by simp
next
case (vpra_CallEmpty cs a' as' Q' r' p' fs')
from \<open>valid_path_rev_aux [] (a#as')\<close> \<open>kind a' = Q':r'\<hookrightarrow>\<^bsub>p'\<^esub>fs'\<close> \<open>cs = []\<close>
have "valid_path_rev_aux cs ((a#as')@[a'])"
by(simp only:valid_path_rev_aux.simps,clarsimp)
thus ?case by simp
next
case (vpra_CallCons cs a' as' Q' r' p' fs' c' cs')
from \<open>valid_path_rev_aux cs' (a#as')\<close> \<open>kind a' = Q':r'\<hookrightarrow>\<^bsub>p'\<^esub>fs'\<close> \<open>cs = c'#cs'\<close>
\<open>c' \<in> get_return_edges a'\<close>
have "valid_path_rev_aux cs ((a#as')@[a'])"
by(simp only:valid_path_rev_aux.simps,clarsimp)
thus ?case by simp
qed
(*<*)
lemmas append_Cons_rev = append_Cons[THEN sym]
declare append_Cons [simp del] append_Cons_rev [simp]
(*>*)
lemma upd_rev_cs_Cons_intra:
assumes "intra_kind(kind a)" shows "upd_rev_cs cs (a#as) = upd_rev_cs cs as"
proof(induct as arbitrary:cs rule:rev_induct)
case Nil
from \<open>intra_kind (kind a)\<close>
have "upd_rev_cs cs ([]@[a]) = upd_rev_cs cs []"
by(simp only:upd_rev_cs.simps,auto simp:intra_kind_def)
thus ?case by simp
next
case (snoc a' as')
note IH = \<open>\<And>cs. upd_rev_cs cs (a#as') = upd_rev_cs cs as'\<close>
show ?case
proof(cases "kind a'" rule:edge_kind_cases)
case Intra
from IH have "upd_rev_cs cs (a#as') = upd_rev_cs cs as'" .
with Intra have "upd_rev_cs cs ((a#as')@[a']) = upd_rev_cs cs (as'@[a'])"
by(fastforce simp:intra_kind_def)
thus ?thesis by simp
next
case Return
from IH have "upd_rev_cs (a'#cs) (a#as') = upd_rev_cs (a'#cs) as'" .
with Return have "upd_rev_cs cs ((a#as')@[a']) = upd_rev_cs cs (as'@[a'])"
by(auto simp:intra_kind_def)
thus ?thesis by simp
next
case Call
show ?thesis
proof(cases cs)
case Nil
from IH have "upd_rev_cs [] (a#as') = upd_rev_cs [] as'" .
with Call Nil have "upd_rev_cs cs ((a#as')@[a']) = upd_rev_cs cs (as'@[a'])"
by(auto simp:intra_kind_def)
thus ?thesis by simp
next
case (Cons c' cs')
from IH have "upd_rev_cs cs' (a#as') = upd_rev_cs cs' as'" .
with Call Cons have "upd_rev_cs cs ((a#as')@[a']) = upd_rev_cs cs (as'@[a'])"
by(auto simp:intra_kind_def)
thus ?thesis by simp
qed
qed
qed
lemma upd_rev_cs_Cons_Return:
assumes "kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f" shows "upd_rev_cs cs (a#as) = a#(upd_rev_cs cs as)"
proof(induct as arbitrary:cs rule:rev_induct)
case Nil
with \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> have "upd_rev_cs cs ([]@[a]) = a#(upd_rev_cs cs [])"
by(simp only:upd_rev_cs.simps) clarsimp
thus ?case by simp
next
case (snoc a' as')
note IH = \<open>\<And>cs. upd_rev_cs cs (a#as') = a#upd_rev_cs cs as'\<close>
show ?case
proof(cases "kind a'" rule:edge_kind_cases)
case Intra
from IH have "upd_rev_cs cs (a#as') = a#(upd_rev_cs cs as')" .
with Intra have "upd_rev_cs cs ((a#as')@[a']) = a#(upd_rev_cs cs (as'@[a']))"
by(fastforce simp:intra_kind_def)
thus ?thesis by simp
next
case Return
from IH have "upd_rev_cs (a'#cs) (a#as') = a#(upd_rev_cs (a'#cs) as')" .
with Return have "upd_rev_cs cs ((a#as')@[a']) = a#(upd_rev_cs cs (as'@[a']))"
by(auto simp:intra_kind_def)
thus ?thesis by simp
next
case Call
show ?thesis
proof(cases cs)
case Nil
from IH have "upd_rev_cs [] (a#as') = a#(upd_rev_cs [] as')" .
with Call Nil have "upd_rev_cs cs ((a#as')@[a']) = a#(upd_rev_cs cs (as'@[a']))"
by(auto simp:intra_kind_def)
thus ?thesis by simp
next
case (Cons c' cs')
from IH have "upd_rev_cs cs' (a#as') = a#(upd_rev_cs cs' as')" .
with Call Cons
have "upd_rev_cs cs ((a#as')@[a']) = a#(upd_rev_cs cs (as'@[a']))"
by(auto simp:intra_kind_def)
thus ?thesis by simp
qed
qed
qed
lemma upd_rev_cs_Cons_Call_Cons:
assumes "kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs"
shows "upd_rev_cs cs as = c'#cs' \<Longrightarrow> upd_rev_cs cs (a#as) = cs'"
proof(induct as arbitrary:cs rule:rev_induct)
case Nil
with \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> have "upd_rev_cs cs ([]@[a]) = cs'"
by(simp only:upd_rev_cs.simps) clarsimp
thus ?case by simp
next
case (snoc a' as')
note IH = \<open>\<And>cs. upd_rev_cs cs as' = c'#cs' \<Longrightarrow> upd_rev_cs cs (a#as') = cs'\<close>
show ?case
proof(cases "kind a'" rule:edge_kind_cases)
case Intra
with \<open>upd_rev_cs cs (as'@[a']) = c'#cs'\<close>
have "upd_rev_cs cs as' = c'#cs'" by(fastforce simp:intra_kind_def)
from IH[OF this] have "upd_rev_cs cs (a#as') = cs'" .
with Intra show ?thesis by(fastforce simp:intra_kind_def)
next
case Return
with \<open>upd_rev_cs cs (as'@[a']) = c'#cs'\<close>
have "upd_rev_cs (a'#cs) as' = c'#cs'" by simp
from IH[OF this] have "upd_rev_cs (a'#cs) (a#as') = cs'" .
with Return show ?thesis by simp
next
case Call
show ?thesis
proof(cases cs)
case Nil
with \<open>upd_rev_cs cs (as'@[a']) = c'#cs'\<close> Call
have "upd_rev_cs cs as' = c'#cs'" by simp
from IH[OF this] have "upd_rev_cs cs (a#as') = cs'" .
with Nil Call show ?thesis by simp
next
case (Cons cx csx)
with \<open>upd_rev_cs cs (as'@[a']) = c'#cs'\<close> Call
have "upd_rev_cs csx as' = c'#cs'" by simp
from IH[OF this] have "upd_rev_cs csx (a#as') = cs'" .
with Cons Call show ?thesis by simp
qed
qed
qed
lemma upd_rev_cs_Cons_Call_Cons_Empty:
assumes "kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs"
shows "upd_rev_cs cs as = [] \<Longrightarrow> upd_rev_cs cs (a#as) = []"
proof(induct as arbitrary:cs rule:rev_induct)
case Nil
with \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> have "upd_rev_cs cs ([]@[a]) = []"
by(simp only:upd_rev_cs.simps) clarsimp
thus ?case by simp
next
case (snoc a' as')
note IH = \<open>\<And>cs. upd_rev_cs cs as' = [] \<Longrightarrow> upd_rev_cs cs (a#as') = []\<close>
show ?case
proof(cases "kind a'" rule:edge_kind_cases)
case Intra
with \<open>upd_rev_cs cs (as'@[a']) = []\<close>
have "upd_rev_cs cs as' = []" by(fastforce simp:intra_kind_def)
from IH[OF this] have "upd_rev_cs cs (a#as') = []" .
with Intra show ?thesis by(fastforce simp:intra_kind_def)
next
case Return
with \<open>upd_rev_cs cs (as'@[a']) = []\<close>
have "upd_rev_cs (a'#cs) as' = []" by simp
from IH[OF this] have "upd_rev_cs (a'#cs) (a#as') = []" .
with Return show ?thesis by simp
next
case Call
show ?thesis
proof(cases cs)
case Nil
with \<open>upd_rev_cs cs (as'@[a']) = []\<close> Call
have "upd_rev_cs cs as' = []" by simp
from IH[OF this] have "upd_rev_cs cs (a#as') = []" .
with Nil Call show ?thesis by simp
next
case (Cons cx csx)
with \<open>upd_rev_cs cs (as'@[a']) = []\<close> Call
have "upd_rev_cs csx as' = []" by simp
from IH[OF this] have "upd_rev_cs csx (a#as') = []" .
with Cons Call show ?thesis by simp
qed
qed
qed
(*<*)declare append_Cons [simp] append_Cons_rev [simp del](*>*)
definition valid_call_list :: "'edge list \<Rightarrow> 'node \<Rightarrow> bool"
where "valid_call_list cs n \<equiv>
\<forall>cs' c cs''. cs = cs'@c#cs'' \<longrightarrow> (valid_edge c \<and> (\<exists>Q r p fs. (kind c = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs) \<and>
p = get_proc (case cs' of [] \<Rightarrow> n | _ \<Rightarrow> last (sourcenodes cs'))))"
definition valid_return_list :: "'edge list \<Rightarrow> 'node \<Rightarrow> bool"
where "valid_return_list cs n \<equiv>
\<forall>cs' c cs''. cs = cs'@c#cs'' \<longrightarrow> (valid_edge c \<and> (\<exists>Q p f. (kind c = Q\<hookleftarrow>\<^bsub>p\<^esub>f) \<and>
p = get_proc (case cs' of [] \<Rightarrow> n | _ \<Rightarrow> last (targetnodes cs'))))"
lemma valid_call_list_valid_edges:
assumes "valid_call_list cs n" shows "\<forall>c \<in> set cs. valid_edge c"
proof -
from \<open>valid_call_list cs n\<close>
have "\<forall>cs' c cs''. cs = cs'@c#cs'' \<longrightarrow> valid_edge c"
by(simp add:valid_call_list_def)
thus ?thesis
proof(induct cs)
case Nil thus ?case by simp
next
case (Cons cx csx)
note IH = \<open>\<forall>cs' c cs''. csx = cs'@c#cs'' \<longrightarrow> valid_edge c \<Longrightarrow>
\<forall>a\<in>set csx. valid_edge a\<close>
from \<open>\<forall>cs' c cs''. cx#csx = cs'@c#cs'' \<longrightarrow> valid_edge c\<close>
have "valid_edge cx" by blast
from \<open>\<forall>cs' c cs''. cx#csx = cs'@c#cs'' \<longrightarrow> valid_edge c\<close>
have "\<forall>cs' c cs''. csx = cs'@c#cs'' \<longrightarrow> valid_edge c"
by auto(erule_tac x="cx#cs'" in allE,auto)
from IH[OF this] \<open>valid_edge cx\<close> show ?case by simp
qed
qed
lemma valid_return_list_valid_edges:
assumes "valid_return_list rs n" shows "\<forall>r \<in> set rs. valid_edge r"
proof -
from \<open>valid_return_list rs n\<close>
have "\<forall>rs' r rs''. rs = rs'@r#rs'' \<longrightarrow> valid_edge r"
by(simp add:valid_return_list_def)
thus ?thesis
proof(induct rs)
case Nil thus ?case by simp
next
case (Cons rx rsx)
note IH = \<open>\<forall>rs' r rs''. rsx = rs'@r#rs'' \<longrightarrow> valid_edge r \<Longrightarrow>
\<forall>a\<in>set rsx. valid_edge a\<close>
from \<open>\<forall>rs' r rs''. rx#rsx = rs'@r#rs'' \<longrightarrow> valid_edge r\<close>
have "valid_edge rx" by blast
from \<open>\<forall>rs' r rs''. rx#rsx = rs'@r#rs'' \<longrightarrow> valid_edge r\<close>
have "\<forall>rs' r rs''. rsx = rs'@r#rs'' \<longrightarrow> valid_edge r"
by auto(erule_tac x="rx#rs'" in allE,auto)
from IH[OF this] \<open>valid_edge rx\<close> show ?case by simp
qed
qed
lemma vpra_empty_valid_call_list_rev:
"valid_call_list cs n \<Longrightarrow> valid_path_rev_aux [] (rev cs)"
proof(induct cs arbitrary:n)
case Nil thus ?case by simp
next
case (Cons c' cs')
note IH = \<open>\<And>n. valid_call_list cs' n \<Longrightarrow> valid_path_rev_aux [] (rev cs')\<close>
from \<open>valid_call_list (c'#cs') n\<close> have "valid_call_list cs' (sourcenode c')"
apply(clarsimp simp:valid_call_list_def)
apply hypsubst_thin
apply(erule_tac x="c'#cs'" in allE)
apply clarsimp
by(case_tac cs',auto simp:sourcenodes_def)
from IH[OF this] have "valid_path_rev_aux [] (rev cs')" .
moreover
from \<open>valid_call_list (c'#cs') n\<close> obtain Q r p fs where "kind c' = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs"
apply(clarsimp simp:valid_call_list_def)
by(erule_tac x="[]" in allE) fastforce
ultimately show ?case by simp
qed
lemma vpa_upd_cs_cases:
"\<lbrakk>valid_path_aux cs as; valid_call_list cs n; n -as\<rightarrow>* n'\<rbrakk>
\<Longrightarrow> case (upd_cs cs as) of [] \<Rightarrow> (\<forall>c \<in> set cs. \<exists>a \<in> set as. a \<in> get_return_edges c)
| cx#csx \<Rightarrow> valid_call_list (cx#csx) n'"
proof(induct arbitrary:n rule:vpa_induct)
case (vpa_empty cs)
from \<open>n -[]\<rightarrow>* n'\<close> have "n = n'" by fastforce
with \<open>valid_call_list cs n\<close> show ?case by(cases cs) auto
next
case (vpa_intra cs a' as')
note IH = \<open>\<And>n. \<lbrakk>valid_call_list cs n; n -as'\<rightarrow>* n'\<rbrakk>
\<Longrightarrow> case (upd_cs cs as') of [] \<Rightarrow> \<forall>c\<in>set cs. \<exists>a\<in>set as'. a \<in> get_return_edges c
| cx#csx \<Rightarrow> valid_call_list (cx # csx) n'\<close>
from \<open>intra_kind (kind a')\<close> have "upd_cs cs (a'#as') = upd_cs cs as'"
by(fastforce simp:intra_kind_def)
from \<open>n -a'#as'\<rightarrow>* n'\<close> have [simp]:"n = sourcenode a'" and "valid_edge a'"
and "targetnode a' -as'\<rightarrow>* n'" by(auto elim:path_split_Cons)
from \<open>valid_edge a'\<close> \<open>intra_kind (kind a')\<close>
have "get_proc (sourcenode a') = get_proc (targetnode a')" by(rule get_proc_intra)
with \<open>valid_call_list cs n\<close> have "valid_call_list cs (targetnode a')"
apply(clarsimp simp:valid_call_list_def)
apply(erule_tac x="cs'" in allE) apply clarsimp
by(case_tac cs') auto
from IH[OF this \<open>targetnode a' -as'\<rightarrow>* n'\<close>] \<open>upd_cs cs (a'#as') = upd_cs cs as'\<close>
show ?case by(cases "upd_cs cs as'") auto
next
case (vpa_Call cs a' as' Q r p fs)
note IH = \<open>\<And>n. \<lbrakk>valid_call_list (a'#cs) n; n -as'\<rightarrow>* n'\<rbrakk>
\<Longrightarrow> case (upd_cs (a'#cs) as')
of [] \<Rightarrow> \<forall>c\<in>set (a'#cs). \<exists>a\<in>set as'. a \<in> get_return_edges c
| cx#csx \<Rightarrow> valid_call_list (cx # csx) n'\<close>
from \<open>kind a' = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> have "upd_cs (a'#cs) as' = upd_cs cs (a'#as')"
by simp
from \<open>n -a'#as'\<rightarrow>* n'\<close> have [simp]:"n = sourcenode a'" and "valid_edge a'"
and "targetnode a' -as'\<rightarrow>* n'" by(auto elim:path_split_Cons)
from \<open>valid_edge a'\<close> \<open>kind a' = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close>
have "get_proc (targetnode a') = p" by(rule get_proc_call)
with \<open>valid_edge a'\<close> \<open>kind a' = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> \<open>valid_call_list cs n\<close>
have "valid_call_list (a'#cs) (targetnode a')"
apply(clarsimp simp:valid_call_list_def)
apply(case_tac cs') apply auto
apply(erule_tac x="list" in allE) apply clarsimp
by(case_tac list,auto simp:sourcenodes_def)
from IH[OF this \<open>targetnode a' -as'\<rightarrow>* n'\<close>]
\<open>upd_cs (a'#cs) as' = upd_cs cs (a'#as')\<close>
have "case upd_cs cs (a'#as')
of [] \<Rightarrow> \<forall>c\<in>set (a' # cs). \<exists>a\<in>set as'. a \<in> get_return_edges c
| cx # csx \<Rightarrow> valid_call_list (cx # csx) n'" by simp
thus ?case by(cases "upd_cs cs (a'#as')") simp+
next
case (vpa_ReturnEmpty cs a' as' Q p f)
note IH = \<open>\<And>n. \<lbrakk>valid_call_list [] n; n -as'\<rightarrow>* n'\<rbrakk>
\<Longrightarrow> case (upd_cs [] as')
of [] \<Rightarrow> \<forall>c\<in>set []. \<exists>a\<in>set as'. a \<in> get_return_edges c
| cx#csx \<Rightarrow> valid_call_list (cx # csx) n'\<close>
from \<open>kind a' = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> \<open>cs = []\<close> have "upd_cs [] as' = upd_cs cs (a'#as')"
by simp
from \<open>n -a'#as'\<rightarrow>* n'\<close> have [simp]:"n = sourcenode a'" and "valid_edge a'"
and "targetnode a' -as'\<rightarrow>* n'" by(auto elim:path_split_Cons)
have "valid_call_list [] (targetnode a')" by(simp add:valid_call_list_def)
from IH[OF this \<open>targetnode a' -as'\<rightarrow>* n'\<close>]
\<open>upd_cs [] as' = upd_cs cs (a'#as')\<close>
have "case (upd_cs cs (a'#as'))
of [] \<Rightarrow> \<forall>c\<in>set []. \<exists>a\<in>set as'. a \<in> get_return_edges c
| cx#csx \<Rightarrow> valid_call_list (cx#csx) n'" by simp
with \<open>cs = []\<close> show ?case by(cases "upd_cs cs (a'#as')") simp+
next
case (vpa_ReturnCons cs a' as' Q p f c' cs')
note IH = \<open>\<And>n. \<lbrakk>valid_call_list cs' n; n -as'\<rightarrow>* n'\<rbrakk>
\<Longrightarrow> case (upd_cs cs' as')
of [] \<Rightarrow> \<forall>c\<in>set cs'. \<exists>a\<in>set as'. a \<in> get_return_edges c
| cx#csx \<Rightarrow> valid_call_list (cx # csx) n'\<close>
from \<open>kind a' = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> \<open>cs = c'#cs'\<close> \<open>a' \<in> get_return_edges c'\<close>
have "upd_cs cs' as' = upd_cs cs (a'#as')" by simp
from \<open>n -a'#as'\<rightarrow>* n'\<close> have [simp]:"n = sourcenode a'" and "valid_edge a'"
and "targetnode a' -as'\<rightarrow>* n'" by(auto elim:path_split_Cons)
from \<open>valid_call_list cs n\<close> \<open>cs = c'#cs'\<close> have "valid_edge c'"
apply(clarsimp simp:valid_call_list_def)
by(erule_tac x="[]" in allE,auto)
with \<open>a' \<in> get_return_edges c'\<close> obtain ax where "valid_edge ax"
and sources:"sourcenode ax = sourcenode c'"
and targets:"targetnode ax = targetnode a'" and "kind ax = (\<lambda>cf. False)\<^sub>\<surd>"
by(fastforce dest:call_return_node_edge)
from \<open>valid_edge ax\<close> sources[THEN sym] targets[THEN sym] \<open>kind ax = (\<lambda>cf. False)\<^sub>\<surd>\<close>
have "get_proc (sourcenode c') = get_proc (targetnode a')"
by(fastforce intro:get_proc_intra simp:intra_kind_def)
with \<open>valid_call_list cs n\<close> \<open>cs = c'#cs'\<close>
have "valid_call_list cs' (targetnode a')"
apply(clarsimp simp:valid_call_list_def)
apply(hypsubst_thin)
apply(erule_tac x="c'#cs'" in allE)
by(case_tac cs',auto simp:sourcenodes_def)
from IH[OF this \<open>targetnode a' -as'\<rightarrow>* n'\<close>]
\<open>upd_cs cs' as' = upd_cs cs (a'#as')\<close>
have "case (upd_cs cs (a'#as'))
of [] \<Rightarrow> \<forall>c\<in>set cs'. \<exists>a\<in>set as'. a \<in> get_return_edges c
| cx#csx \<Rightarrow> valid_call_list (cx#csx) n'" by simp
with \<open>cs = c' # cs'\<close> \<open>a' \<in> get_return_edges c'\<close> show ?case
by(cases "upd_cs cs (a'#as')") simp+
qed
lemma vpa_valid_call_list_valid_return_list_vpra:
"\<lbrakk>valid_path_aux cs cs'; valid_call_list cs n; valid_return_list cs' n'\<rbrakk>
\<Longrightarrow> valid_path_rev_aux cs' (rev cs)"
proof(induct arbitrary:n n' rule:vpa_induct)
case (vpa_empty cs)
from \<open>valid_call_list cs n\<close> show ?case by(rule vpra_empty_valid_call_list_rev)
next
case (vpa_intra cs a as)
from \<open>intra_kind (kind a)\<close> \<open>valid_return_list (a#as) n'\<close>
have False apply(clarsimp simp:valid_return_list_def)
by(erule_tac x="[]" in allE,clarsimp simp:intra_kind_def)
thus ?case by simp
next
case (vpa_Call cs a as Q r p fs)
from \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> \<open>valid_return_list (a#as) n'\<close>
have False apply(clarsimp simp:valid_return_list_def)
by(erule_tac x="[]" in allE,clarsimp)
thus ?case by simp
next
case (vpa_ReturnEmpty cs a as Q p f)
from \<open>cs = []\<close> show ?case by simp
next
case (vpa_ReturnCons cs a as Q p f c' cs')
note IH = \<open>\<And>n n'. \<lbrakk>valid_call_list cs' n; valid_return_list as n'\<rbrakk>
\<Longrightarrow> valid_path_rev_aux as (rev cs')\<close>
from \<open>valid_return_list (a#as) n'\<close> have "valid_return_list as (targetnode a)"
apply(clarsimp simp:valid_return_list_def)
apply(erule_tac x="a#cs'" in allE)
by(case_tac cs',auto simp:targetnodes_def)
from \<open>valid_call_list cs n\<close> \<open>cs = c'#cs'\<close>
have "valid_call_list cs' (sourcenode c')"
apply(clarsimp simp:valid_call_list_def)
apply(erule_tac x="c'#cs'" in allE)
by(case_tac cs',auto simp:sourcenodes_def)
from \<open>valid_call_list cs n\<close> \<open>cs = c'#cs'\<close> have "valid_edge c'"
apply(clarsimp simp:valid_call_list_def)
by(erule_tac x="[]" in allE,auto)
with \<open>a \<in> get_return_edges c'\<close> obtain Q' r' p' f' where "kind c' = Q':r'\<hookrightarrow>\<^bsub>p'\<^esub>f'"
apply(cases "kind c'" rule:edge_kind_cases)
by(auto dest:only_call_get_return_edges simp:intra_kind_def)
from IH[OF \<open>valid_call_list cs' (sourcenode c')\<close>
\<open>valid_return_list as (targetnode a)\<close>]
have "valid_path_rev_aux as (rev cs')" .
with \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> \<open>cs = c'#cs'\<close> \<open>a \<in> get_return_edges c'\<close> \<open>kind c' = Q':r'\<hookrightarrow>\<^bsub>p'\<^esub>f'\<close>
show ?case by simp
qed
lemma vpa_to_vpra:
"\<lbrakk>valid_path_aux cs as; valid_path_aux (upd_cs cs as) cs';
n -as\<rightarrow>* n'; valid_call_list cs n; valid_return_list cs' n''\<rbrakk>
\<Longrightarrow> valid_path_rev_aux cs' as \<and> valid_path_rev_aux (upd_rev_cs cs' as) (rev cs)"
proof(induct arbitrary:n rule:vpa_induct)
case vpa_empty thus ?case
by(fastforce intro:vpa_valid_call_list_valid_return_list_vpra)
next
case (vpa_intra cs a as)
note IH = \<open>\<And>n. \<lbrakk>valid_path_aux (upd_cs cs as) cs'; n -as\<rightarrow>* n';
valid_call_list cs n; valid_return_list cs' n''\<rbrakk>
\<Longrightarrow> valid_path_rev_aux cs' as \<and>
valid_path_rev_aux (upd_rev_cs cs' as) (rev cs)\<close>
from \<open>n -a#as\<rightarrow>* n'\<close> have "n = sourcenode a" and "valid_edge a"
and "targetnode a -as\<rightarrow>* n'" by(auto intro:path_split_Cons)
from \<open>valid_edge a\<close> \<open>intra_kind (kind a)\<close>
have "get_proc (sourcenode a) = get_proc (targetnode a)" by(rule get_proc_intra)
with \<open>valid_call_list cs n\<close> \<open>n = sourcenode a\<close>
have "valid_call_list cs (targetnode a)"
apply(clarsimp simp:valid_call_list_def)
apply(erule_tac x="cs'" in allE) apply clarsimp
by(case_tac cs') auto
from \<open>valid_path_aux (upd_cs cs (a#as)) cs'\<close> \<open>intra_kind (kind a)\<close>
have "valid_path_aux (upd_cs cs as) cs'"
by(fastforce simp:intra_kind_def)
from IH[OF this \<open>targetnode a -as\<rightarrow>* n'\<close> \<open>valid_call_list cs (targetnode a)\<close>
\<open>valid_return_list cs' n''\<close>]
have "valid_path_rev_aux cs' as"
and "valid_path_rev_aux (upd_rev_cs cs' as) (rev cs)" by simp_all
from \<open>intra_kind (kind a)\<close> \<open>valid_path_rev_aux cs' as\<close>
have "valid_path_rev_aux cs' (a#as)" by(rule vpra_Cons_intra)
from \<open>intra_kind (kind a)\<close> have "upd_rev_cs cs' (a#as) = upd_rev_cs cs' as"
by(simp add:upd_rev_cs_Cons_intra)
with \<open>valid_path_rev_aux (upd_rev_cs cs' as) (rev cs)\<close>
have "valid_path_rev_aux (upd_rev_cs cs' (a#as)) (rev cs)" by simp
with \<open>valid_path_rev_aux cs' (a#as)\<close> show ?case by simp
next
case (vpa_Call cs a as Q r p fs)
note IH = \<open>\<And>n. \<lbrakk>valid_path_aux (upd_cs (a#cs) as) cs'; n -as\<rightarrow>* n';
valid_call_list (a#cs) n; valid_return_list cs' n''\<rbrakk>
\<Longrightarrow> valid_path_rev_aux cs' as \<and>
valid_path_rev_aux (upd_rev_cs cs' as) (rev (a#cs))\<close>
from \<open>n -a#as\<rightarrow>* n'\<close> have "n = sourcenode a" and "valid_edge a"
and "targetnode a -as\<rightarrow>* n'" by(auto intro:path_split_Cons)
from \<open>valid_edge a\<close> \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> have "p = get_proc (targetnode a)"
by(rule get_proc_call[THEN sym])
from \<open>valid_call_list cs n\<close> \<open>n = sourcenode a\<close>
have "valid_call_list cs (sourcenode a)" by simp
with \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> \<open>valid_edge a\<close> \<open>p = get_proc (targetnode a)\<close>
have "valid_call_list (a#cs) (targetnode a)"
apply(clarsimp simp:valid_call_list_def)
apply(case_tac cs') apply auto
apply(erule_tac x="list" in allE) apply clarsimp
by(case_tac list,auto simp:sourcenodes_def)
from \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> have "upd_cs cs (a#as) = upd_cs (a#cs) as"
by simp
with \<open>valid_path_aux (upd_cs cs (a#as)) cs'\<close>
have "valid_path_aux (upd_cs (a#cs) as) cs'" by simp
from IH[OF this \<open>targetnode a -as\<rightarrow>* n'\<close> \<open>valid_call_list (a#cs) (targetnode a)\<close>
\<open>valid_return_list cs' n''\<close>]
have "valid_path_rev_aux cs' as"
and "valid_path_rev_aux (upd_rev_cs cs' as) (rev (a#cs))" by simp_all
show ?case
proof(cases "upd_rev_cs cs' as")
case Nil
with \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close>
have "upd_rev_cs cs' (a#as) = []" by(rule upd_rev_cs_Cons_Call_Cons_Empty)
with \<open>valid_path_rev_aux (upd_rev_cs cs' as) (rev (a#cs))\<close> \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> Nil
have "valid_path_rev_aux (upd_rev_cs cs' (a#as)) (rev cs)" by simp
from Nil \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> have "valid_path_rev_aux (upd_rev_cs cs' as) ([]@[a])"
by(simp only:valid_path_rev_aux.simps) clarsimp
with \<open>valid_path_rev_aux cs' as\<close> have "valid_path_rev_aux cs' ([a]@as)"
by(fastforce intro:valid_path_rev_aux_Append)
with \<open>valid_path_rev_aux (upd_rev_cs cs' (a#as)) (rev cs)\<close>
show ?thesis by simp
next
case (Cons cx csx)
with \<open>valid_path_rev_aux (upd_rev_cs cs' as) (rev (a#cs))\<close> \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close>
have match:"cx \<in> get_return_edges a" "valid_path_rev_aux csx (rev cs)" by auto
from \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> Cons have "upd_rev_cs cs' (a#as) = csx"
by(rule upd_rev_cs_Cons_Call_Cons)
with \<open>valid_path_rev_aux (upd_rev_cs cs' as) (rev(a#cs))\<close> \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> match
have "valid_path_rev_aux (upd_rev_cs cs' (a#as)) (rev cs)" by simp
from Cons \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> match
have "valid_path_rev_aux (upd_rev_cs cs' as) ([]@[a])"
by(simp only:valid_path_rev_aux.simps) clarsimp
with \<open>valid_path_rev_aux cs' as\<close> have "valid_path_rev_aux cs' ([a]@as)"
by(fastforce intro:valid_path_rev_aux_Append)
with \<open>valid_path_rev_aux (upd_rev_cs cs' (a#as)) (rev cs)\<close>
show ?thesis by simp
qed
next
case (vpa_ReturnEmpty cs a as Q p f)
note IH = \<open>\<And>n. \<lbrakk>valid_path_aux (upd_cs [] as) cs'; n -as\<rightarrow>* n';
valid_call_list [] n; valid_return_list cs' n''\<rbrakk>
\<Longrightarrow> valid_path_rev_aux cs' as \<and>
valid_path_rev_aux (upd_rev_cs cs' as) (rev [])\<close>
from \<open>n -a#as\<rightarrow>* n'\<close> have "n = sourcenode a" and "valid_edge a"
and "targetnode a -as\<rightarrow>* n'" by(auto intro:path_split_Cons)
from \<open>cs = []\<close> \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> have "upd_cs cs (a#as) = upd_cs [] as"
by simp
with \<open>valid_path_aux (upd_cs cs (a#as)) cs'\<close>
have "valid_path_aux (upd_cs [] as) cs'" by simp
from IH[OF this \<open>targetnode a -as\<rightarrow>* n'\<close> _ \<open>valid_return_list cs' n''\<close>]
have "valid_path_rev_aux cs' as"
and "valid_path_rev_aux (upd_rev_cs cs' as) (rev [])"
by(auto simp:valid_call_list_def)
from \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> \<open>valid_path_rev_aux cs' as\<close>
have "valid_path_rev_aux cs' (a#as)" by(rule vpra_Cons_Return)
moreover
from \<open>cs = []\<close> have "valid_path_rev_aux (upd_rev_cs cs' (a#as)) (rev cs)"
by simp
ultimately show ?case by simp
next
case (vpa_ReturnCons cs a as Q p f cx csx)
note IH = \<open>\<And>n. \<lbrakk>valid_path_aux (upd_cs csx as) cs'; n -as\<rightarrow>* n';
valid_call_list csx n; valid_return_list cs' n''\<rbrakk>
\<Longrightarrow> valid_path_rev_aux cs' as \<and>
valid_path_rev_aux (upd_rev_cs cs' as) (rev csx)\<close>
note match = \<open>cs = cx#csx\<close> \<open>a \<in> get_return_edges cx\<close>
from \<open>n -a#as\<rightarrow>* n'\<close> have "n = sourcenode a" and "valid_edge a"
and "targetnode a -as\<rightarrow>* n'" by(auto intro:path_split_Cons)
from \<open>cs = cx#csx\<close> \<open>valid_call_list cs n\<close> have "valid_edge cx"
apply(clarsimp simp:valid_call_list_def)
by(erule_tac x="[]" in allE) clarsimp
with match have "get_proc (sourcenode cx) = get_proc (targetnode a)"
by(fastforce intro:get_proc_get_return_edge)
with \<open>valid_call_list cs n\<close> \<open>cs = cx#csx\<close>
have "valid_call_list csx (targetnode a)"
apply(clarsimp simp:valid_call_list_def)
apply(erule_tac x="cx#cs'" in allE) apply clarsimp
by(case_tac cs',auto simp:sourcenodes_def)
from \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> match have "upd_cs cs (a#as) = upd_cs csx as" by simp
with \<open>valid_path_aux (upd_cs cs (a#as)) cs'\<close>
have "valid_path_aux (upd_cs csx as) cs'" by simp
from IH[OF this \<open>targetnode a -as\<rightarrow>* n'\<close> \<open>valid_call_list csx (targetnode a)\<close>
\<open>valid_return_list cs' n''\<close>]
have "valid_path_rev_aux cs' as"
and "valid_path_rev_aux (upd_rev_cs cs' as) (rev csx)" by simp_all
from \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> \<open>valid_path_rev_aux cs' as\<close>
have "valid_path_rev_aux cs' (a#as)" by(rule vpra_Cons_Return)
from match \<open>valid_edge cx\<close> obtain Q' r' p' f' where "kind cx = Q':r'\<hookrightarrow>\<^bsub>p'\<^esub>f'"
by(fastforce dest!:only_call_get_return_edges)
from \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> have "upd_rev_cs cs' (a#as) = a#(upd_rev_cs cs' as)"
by(rule upd_rev_cs_Cons_Return)
with \<open>valid_path_rev_aux (upd_rev_cs cs' as) (rev csx)\<close> \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close>
\<open>kind cx = Q':r'\<hookrightarrow>\<^bsub>p'\<^esub>f'\<close> match
have "valid_path_rev_aux (upd_rev_cs cs' (a#as)) (rev cs)"
by simp
with \<open>valid_path_rev_aux cs' (a#as)\<close> show ?case by simp
qed
lemma vp_to_vpra:
"n -as\<rightarrow>\<^sub>\<surd>* n' \<Longrightarrow> valid_path_rev_aux [] as"
by(fastforce elim:vpa_to_vpra[THEN conjunct1]
simp:vp_def valid_path_def valid_call_list_def valid_return_list_def)
subsubsection \<open>Same level paths\<close>
fun same_level_path_aux :: "'edge list \<Rightarrow> 'edge list \<Rightarrow> bool"
where "same_level_path_aux cs [] \<longleftrightarrow> True"
| "same_level_path_aux cs (a#as) \<longleftrightarrow>
(case (kind a) of Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs \<Rightarrow> same_level_path_aux (a#cs) as
| Q\<hookleftarrow>\<^bsub>p\<^esub>f \<Rightarrow> case cs of [] \<Rightarrow> False
| c'#cs' \<Rightarrow> a \<in> get_return_edges c' \<and>
same_level_path_aux cs' as
| _ \<Rightarrow> same_level_path_aux cs as)"
lemma slpa_induct [consumes 1,case_names slpa_empty slpa_intra slpa_Call
slpa_Return]:
assumes major: "same_level_path_aux xs ys"
and rules: "\<And>cs. P cs []"
"\<And>cs a as. \<lbrakk>intra_kind(kind a); same_level_path_aux cs as; P cs as\<rbrakk>
\<Longrightarrow> P cs (a#as)"
"\<And>cs a as Q r p fs. \<lbrakk>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs; same_level_path_aux (a#cs) as; P (a#cs) as\<rbrakk>
\<Longrightarrow> P cs (a#as)"
"\<And>cs a as Q p f c' cs'. \<lbrakk>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f; cs = c'#cs'; same_level_path_aux cs' as;
a \<in> get_return_edges c'; P cs' as\<rbrakk>
\<Longrightarrow> P cs (a#as)"
shows "P xs ys"
using major
apply(induct ys arbitrary: xs)
by(auto intro:rules split:edge_kind.split_asm list.split_asm simp:intra_kind_def)
lemma slpa_cases [consumes 4,case_names intra_path return_intra_path]:
assumes "same_level_path_aux cs as" and "upd_cs cs as = []"
and "\<forall>c \<in> set cs. valid_edge c" and "\<forall>a \<in> set as. valid_edge a"
obtains "\<forall>a \<in> set as. intra_kind(kind a)"
| asx a asx' Q p f c' cs' where "as = asx@a#asx'" and "same_level_path_aux cs asx"
and "kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f" and "upd_cs cs asx = c'#cs'" and "upd_cs cs (asx@[a]) = []"
and "a \<in> get_return_edges c'" and "valid_edge c'"
and "\<forall>a \<in> set asx'. intra_kind(kind a)"
proof(atomize_elim)
from assms
show "(\<forall>a\<in>set as. intra_kind (kind a)) \<or>
(\<exists>asx a asx' Q p f c' cs'. as = asx@a#asx' \<and> same_level_path_aux cs asx \<and>
kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f \<and> upd_cs cs asx = c'#cs' \<and> upd_cs cs (asx@[a]) = [] \<and>
a \<in> get_return_edges c' \<and> valid_edge c' \<and> (\<forall>a\<in>set asx'. intra_kind (kind a)))"
proof(induct rule:slpa_induct)
case (slpa_empty cs)
have "\<forall>a\<in>set []. intra_kind (kind a)" by simp
thus ?case by simp
next
case (slpa_intra cs a as)
note IH = \<open>\<lbrakk>upd_cs cs as = []; \<forall>c\<in>set cs. valid_edge c; \<forall>a'\<in>set as. valid_edge a'\<rbrakk>
\<Longrightarrow> (\<forall>a\<in>set as. intra_kind (kind a)) \<or>
(\<exists>asx a asx' Q p f c' cs'. as = asx@a#asx' \<and> same_level_path_aux cs asx \<and>
kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f \<and> upd_cs cs asx = c' # cs' \<and> upd_cs cs (asx@[a]) = [] \<and>
a \<in> get_return_edges c' \<and> valid_edge c' \<and> (\<forall>a\<in>set asx'. intra_kind (kind a)))\<close>
from \<open>\<forall>a'\<in>set (a#as). valid_edge a'\<close> have "\<forall>a'\<in>set as. valid_edge a'" by simp
from \<open>intra_kind (kind a)\<close> \<open>upd_cs cs (a#as) = []\<close>
have "upd_cs cs as = []" by(fastforce simp:intra_kind_def)
from IH[OF this \<open>\<forall>c\<in>set cs. valid_edge c\<close> \<open>\<forall>a'\<in>set as. valid_edge a'\<close>] show ?case
proof
assume "\<forall>a\<in>set as. intra_kind (kind a)"
with \<open>intra_kind (kind a)\<close> have "\<forall>a'\<in>set (a#as). intra_kind (kind a')"
by simp
thus ?case by simp
next
assume "\<exists>asx a asx' Q p f c' cs'. as = asx@a#asx' \<and> same_level_path_aux cs asx \<and>
kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f \<and> upd_cs cs asx = c'#cs' \<and> upd_cs cs (asx@[a]) = [] \<and>
a \<in> get_return_edges c' \<and> valid_edge c' \<and>
(\<forall>a\<in>set asx'. intra_kind (kind a))"
then obtain asx a' Q p f asx' c' cs' where "as = asx@a'#asx'"
and "same_level_path_aux cs asx" and "upd_cs cs (asx@[a']) = []"
and "upd_cs cs asx = c'#cs'" and assms:"a' \<in> get_return_edges c'"
"kind a' = Q\<hookleftarrow>\<^bsub>p\<^esub>f" "valid_edge c'" "\<forall>a\<in>set asx'. intra_kind (kind a)"
by blast
from \<open>as = asx@a'#asx'\<close> have "a#as = (a#asx)@a'#asx'" by simp
moreover
from \<open>intra_kind (kind a)\<close> \<open>same_level_path_aux cs asx\<close>
have "same_level_path_aux cs (a#asx)" by(fastforce simp:intra_kind_def)
moreover
from \<open>upd_cs cs asx = c'#cs'\<close> \<open>intra_kind (kind a)\<close>
have "upd_cs cs (a#asx) = c'#cs'" by(fastforce simp:intra_kind_def)
moreover
from \<open>upd_cs cs (asx@[a']) = []\<close> \<open>intra_kind (kind a)\<close>
have "upd_cs cs ((a#asx)@[a']) = []" by(fastforce simp:intra_kind_def)
ultimately show ?case using assms by blast
qed
next
case (slpa_Call cs a as Q r p fs)
note IH = \<open>\<lbrakk>upd_cs (a#cs) as = []; \<forall>c\<in>set (a#cs). valid_edge c;
\<forall>a'\<in>set as. valid_edge a'\<rbrakk> \<Longrightarrow>
(\<forall>a'\<in>set as. intra_kind (kind a')) \<or>
(\<exists>asx a' asx' Q' p' f' c' cs'. as = asx@a'#asx' \<and>
same_level_path_aux (a#cs) asx \<and> kind a' = Q'\<hookleftarrow>\<^bsub>p'\<^esub>f' \<and>
upd_cs (a#cs) asx = c'#cs' \<and> upd_cs (a#cs) (asx@[a']) = [] \<and>
a' \<in> get_return_edges c' \<and> valid_edge c' \<and>
(\<forall>a'\<in>set asx'. intra_kind (kind a')))\<close>
from \<open>\<forall>a'\<in>set (a#as). valid_edge a'\<close> have "valid_edge a"
and "\<forall>a'\<in>set as. valid_edge a'" by simp_all
from \<open>\<forall>c\<in>set cs. valid_edge c\<close> \<open>valid_edge a\<close> have "\<forall>c\<in>set (a#cs). valid_edge c"
by simp
from \<open>upd_cs cs (a#as) = []\<close> \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close>
have "upd_cs (a#cs) as = []" by simp
from IH[OF this \<open>\<forall>c\<in>set (a#cs). valid_edge c\<close> \<open>\<forall>a'\<in>set as. valid_edge a'\<close>]
show ?case
proof
assume "\<forall>a'\<in>set as. intra_kind (kind a')"
with \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> have "upd_cs cs (a#as) = a#cs"
by(fastforce intro:upd_cs_intra_path)
with \<open>upd_cs cs (a#as) = []\<close> have False by simp
thus ?case by simp
next
assume "\<exists>asx a' asx' Q p f c' cs'. as = asx@a'#asx' \<and>
same_level_path_aux (a#cs) asx \<and> kind a' = Q\<hookleftarrow>\<^bsub>p\<^esub>f \<and>
upd_cs (a#cs) asx = c'#cs' \<and> upd_cs (a#cs) (asx@[a']) = [] \<and>
a' \<in> get_return_edges c' \<and> valid_edge c' \<and>
(\<forall>a\<in>set asx'. intra_kind (kind a))"
then obtain asx a' Q' p' f' asx' c' cs' where "as = asx@a'#asx'"
and "same_level_path_aux (a#cs) asx" and "upd_cs (a#cs) (asx@[a']) = []"
and "upd_cs (a#cs) asx = c'#cs'" and assms:"a' \<in> get_return_edges c'"
"kind a' = Q'\<hookleftarrow>\<^bsub>p'\<^esub>f'" "valid_edge c'" "\<forall>a\<in>set asx'. intra_kind (kind a)"
by blast
from \<open>as = asx@a'#asx'\<close> have "a#as = (a#asx)@a'#asx'" by simp
moreover
from \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> \<open>same_level_path_aux (a#cs) asx\<close>
have "same_level_path_aux cs (a#asx)" by simp
moreover
from \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> \<open>upd_cs (a#cs) asx = c'#cs'\<close>
have "upd_cs cs (a#asx) = c'#cs'" by simp
moreover
from \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> \<open>upd_cs (a#cs) (asx@[a']) = []\<close>
have "upd_cs cs ((a#asx)@[a']) = []" by simp
ultimately show ?case using assms by blast
qed
next
case (slpa_Return cs a as Q p f c' cs')
note IH = \<open>\<lbrakk>upd_cs cs' as = []; \<forall>c\<in>set cs'. valid_edge c;
\<forall>a'\<in>set as. valid_edge a'\<rbrakk> \<Longrightarrow>
(\<forall>a'\<in>set as. intra_kind (kind a')) \<or>
(\<exists>asx a' asx' Q' p' f' c'' cs''. as = asx@a'#asx' \<and>
same_level_path_aux cs' asx \<and> kind a' = Q'\<hookleftarrow>\<^bsub>p'\<^esub>f' \<and> upd_cs cs' asx = c''#cs'' \<and>
upd_cs cs' (asx@[a']) = [] \<and> a' \<in> get_return_edges c'' \<and> valid_edge c'' \<and>
(\<forall>a'\<in>set asx'. intra_kind (kind a')))\<close>
from \<open>\<forall>a'\<in>set (a#as). valid_edge a'\<close> have "valid_edge a"
and "\<forall>a'\<in>set as. valid_edge a'" by simp_all
from \<open>\<forall>c\<in>set cs. valid_edge c\<close> \<open>cs = c' # cs'\<close>
have "valid_edge c'" and "\<forall>c\<in>set cs'. valid_edge c" by simp_all
from \<open>upd_cs cs (a#as) = []\<close> \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> \<open>cs = c'#cs'\<close>
\<open>a \<in> get_return_edges c'\<close> have "upd_cs cs' as = []" by simp
from IH[OF this \<open>\<forall>c\<in>set cs'. valid_edge c\<close> \<open>\<forall>a'\<in>set as. valid_edge a'\<close>] show ?case
proof
assume "\<forall>a'\<in>set as. intra_kind (kind a')"
hence "upd_cs cs' as = cs'" by(rule upd_cs_intra_path)
with \<open>upd_cs cs' as = []\<close> have "cs' = []" by simp
with \<open>cs = c'#cs'\<close> \<open>a \<in> get_return_edges c'\<close> \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close>
have "upd_cs cs [a] = []" by simp
moreover
from \<open>cs = c'#cs'\<close> have "upd_cs cs [] \<noteq> []" by simp
moreover
have "same_level_path_aux cs []" by simp
ultimately show ?case
using \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> \<open>\<forall>a'\<in>set as. intra_kind (kind a')\<close> \<open>cs = c'#cs'\<close>
\<open>a \<in> get_return_edges c'\<close> \<open>valid_edge c'\<close>
by fastforce
next
assume "\<exists>asx a' asx' Q' p' f' c'' cs''. as = asx@a'#asx' \<and>
same_level_path_aux cs' asx \<and> kind a' = Q'\<hookleftarrow>\<^bsub>p'\<^esub>f' \<and> upd_cs cs' asx = c''#cs'' \<and>
upd_cs cs' (asx@[a']) = [] \<and> a' \<in> get_return_edges c'' \<and> valid_edge c'' \<and>
(\<forall>a'\<in>set asx'. intra_kind (kind a'))"
then obtain asx a' asx' Q' p' f' c'' cs'' where "as = asx@a'#asx'"
and "same_level_path_aux cs' asx" and "upd_cs cs' asx = c''#cs''"
and "upd_cs cs' (asx@[a']) = []" and assms:"a' \<in> get_return_edges c''"
"kind a' = Q'\<hookleftarrow>\<^bsub>p'\<^esub>f'" "valid_edge c''" "\<forall>a'\<in>set asx'. intra_kind (kind a')"
by blast
from \<open>as = asx@a'#asx'\<close> have "a#as = (a#asx)@a'#asx'" by simp
moreover
from \<open>same_level_path_aux cs' asx\<close> \<open>cs = c'#cs'\<close> \<open>a \<in> get_return_edges c'\<close>
\<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close>
have "same_level_path_aux cs (a#asx)" by simp
moreover
from \<open>upd_cs cs' asx = c''#cs''\<close> \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> \<open>cs = c'#cs'\<close>
have "upd_cs cs (a#asx) = c''#cs''" by simp
moreover
from \<open>upd_cs cs' (asx@[a']) = []\<close> \<open>cs = c'#cs'\<close> \<open>a \<in> get_return_edges c'\<close>
\<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close>
have "upd_cs cs ((a#asx)@[a']) = []" by simp
ultimately show ?case using assms by blast
qed
qed
qed
lemma same_level_path_aux_valid_path_aux:
"same_level_path_aux cs as \<Longrightarrow> valid_path_aux cs as"
by(induct rule:slpa_induct,auto split:edge_kind.split simp:intra_kind_def)
lemma same_level_path_aux_Append:
"\<lbrakk>same_level_path_aux cs as; same_level_path_aux (upd_cs cs as) as'\<rbrakk>
\<Longrightarrow> same_level_path_aux cs (as@as')"
by(induct rule:slpa_induct,auto simp:intra_kind_def)
lemma same_level_path_aux_callstack_Append:
"same_level_path_aux cs as \<Longrightarrow> same_level_path_aux (cs@cs') as"
by(induct rule:slpa_induct,auto simp:intra_kind_def)
lemma same_level_path_upd_cs_callstack_Append:
"\<lbrakk>same_level_path_aux cs as; upd_cs cs as = cs'\<rbrakk>
\<Longrightarrow> upd_cs (cs@cs'') as = (cs'@cs'')"
by(induct rule:slpa_induct,auto split:edge_kind.split simp:intra_kind_def)
lemma slpa_split:
assumes "same_level_path_aux cs as" and "as = xs@ys" and "upd_cs cs xs = []"
shows "same_level_path_aux cs xs" and "same_level_path_aux [] ys"
using assms
proof(induct arbitrary:xs ys rule:slpa_induct)
case (slpa_empty cs) case 1
from \<open>[] = xs@ys\<close> show ?case by simp
next
case (slpa_empty cs) case 2
from \<open>[] = xs@ys\<close> show ?case by simp
next
case (slpa_intra cs a as)
note IH1 = \<open>\<And>xs ys. \<lbrakk>as = xs@ys; upd_cs cs xs = []\<rbrakk> \<Longrightarrow> same_level_path_aux cs xs\<close>
note IH2 = \<open>\<And>xs ys. \<lbrakk>as = xs@ys; upd_cs cs xs = []\<rbrakk> \<Longrightarrow> same_level_path_aux [] ys\<close>
{ case 1
show ?case
proof(cases xs)
case Nil thus ?thesis by simp
next
case (Cons x' xs')
with \<open>a#as = xs@ys\<close> have "a = x'" and "as = xs'@ys" by simp_all
with \<open>upd_cs cs xs = []\<close> Cons \<open>intra_kind (kind a)\<close>
have "upd_cs cs xs' = []" by(fastforce simp:intra_kind_def)
from IH1[OF \<open>as = xs'@ys\<close> this] have "same_level_path_aux cs xs'" .
with \<open>a = x'\<close> \<open>intra_kind (kind a)\<close> Cons
show ?thesis by(fastforce simp:intra_kind_def)
qed
next
case 2
show ?case
proof(cases xs)
case Nil
with \<open>upd_cs cs xs = []\<close> have "cs = []" by fastforce
with Nil \<open>a#as = xs@ys\<close> \<open>same_level_path_aux cs as\<close> \<open>intra_kind (kind a)\<close>
show ?thesis by(cases ys,auto simp:intra_kind_def)
next
case (Cons x' xs')
with \<open>a#as = xs@ys\<close> have "a = x'" and "as = xs'@ys" by simp_all
with \<open>upd_cs cs xs = []\<close> Cons \<open>intra_kind (kind a)\<close>
have "upd_cs cs xs' = []" by(fastforce simp:intra_kind_def)
from IH2[OF \<open>as = xs'@ys\<close> this] show ?thesis .
qed
}
next
case (slpa_Call cs a as Q r p fs)
note IH1 = \<open>\<And>xs ys. \<lbrakk>as = xs@ys; upd_cs (a#cs) xs = []\<rbrakk>
\<Longrightarrow> same_level_path_aux (a#cs) xs\<close>
note IH2 = \<open>\<And>xs ys. \<lbrakk>as = xs@ys; upd_cs (a#cs) xs = []\<rbrakk>
\<Longrightarrow> same_level_path_aux [] ys\<close>
{ case 1
show ?case
proof(cases xs)
case Nil thus ?thesis by simp
next
case (Cons x' xs')
with \<open>a#as = xs@ys\<close> have "a = x'" and "as = xs'@ys" by simp_all
with \<open>upd_cs cs xs = []\<close> Cons \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close>
have "upd_cs (a#cs) xs' = []" by simp
from IH1[OF \<open>as = xs'@ys\<close> this] have "same_level_path_aux (a#cs) xs'" .
with \<open>a = x'\<close> \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> Cons show ?thesis by simp
qed
next
case 2
show ?case
proof(cases xs)
case Nil
with \<open>upd_cs cs xs = []\<close> have "cs = []" by fastforce
with Nil \<open>a#as = xs@ys\<close> \<open>same_level_path_aux (a#cs) as\<close> \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close>
show ?thesis by(cases ys) auto
next
case (Cons x' xs')
with \<open>a#as = xs@ys\<close> have "a = x'" and "as = xs'@ys" by simp_all
with \<open>upd_cs cs xs = []\<close> Cons \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close>
have "upd_cs (a#cs) xs' = []" by simp
from IH2[OF \<open>as = xs'@ys\<close> this] show ?thesis .
qed
}
next
case (slpa_Return cs a as Q p f c' cs')
note IH1 = \<open>\<And>xs ys. \<lbrakk>as = xs@ys; upd_cs cs' xs = []\<rbrakk> \<Longrightarrow> same_level_path_aux cs' xs\<close>
note IH2 = \<open>\<And>xs ys. \<lbrakk>as = xs@ys; upd_cs cs' xs = []\<rbrakk> \<Longrightarrow> same_level_path_aux [] ys\<close>
{ case 1
show ?case
proof(cases xs)
case Nil thus ?thesis by simp
next
case (Cons x' xs')
with \<open>a#as = xs@ys\<close> have "a = x'" and "as = xs'@ys" by simp_all
with \<open>upd_cs cs xs = []\<close> Cons \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> \<open>cs = c'#cs'\<close>
have "upd_cs cs' xs' = []" by simp
from IH1[OF \<open>as = xs'@ys\<close> this] have "same_level_path_aux cs' xs'" .
with \<open>a = x'\<close> \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> \<open>cs = c'#cs'\<close> \<open>a \<in> get_return_edges c'\<close> Cons
show ?thesis by simp
qed
next
case 2
show ?case
proof(cases xs)
case Nil
with \<open>upd_cs cs xs = []\<close> have "cs = []" by fastforce
with \<open>cs = c'#cs'\<close> have False by simp
thus ?thesis by simp
next
case (Cons x' xs')
with \<open>a#as = xs@ys\<close> have "a = x'" and "as = xs'@ys" by simp_all
with \<open>upd_cs cs xs = []\<close> Cons \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> \<open>cs = c'#cs'\<close>
have "upd_cs cs' xs' = []" by simp
from IH2[OF \<open>as = xs'@ys\<close> this] show ?thesis .
qed
}
qed
lemma slpa_number_Calls_eq_number_Returns:
"\<lbrakk>same_level_path_aux cs as; upd_cs cs as = [];
\<forall>a \<in> set as. valid_edge a; \<forall>c \<in> set cs. valid_edge c\<rbrakk>
\<Longrightarrow> length [a\<leftarrow>as@cs. \<exists>Q r p fs. kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs] =
length [a\<leftarrow>as. \<exists>Q p f. kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f]"
apply(induct rule:slpa_induct)
by(auto split:list.split edge_kind.split intro:only_call_get_return_edges
simp:intra_kind_def)
lemma slpa_get_proc:
"\<lbrakk>same_level_path_aux cs as; upd_cs cs as = []; n -as\<rightarrow>* n';
\<forall>c \<in> set cs. valid_edge c\<rbrakk>
\<Longrightarrow> (if cs = [] then get_proc n else get_proc(last(sourcenodes cs))) = get_proc n'"
proof(induct arbitrary:n rule:slpa_induct)
case slpa_empty thus ?case by fastforce
next
case (slpa_intra cs a as)
note IH = \<open>\<And>n. \<lbrakk>upd_cs cs as = []; n -as\<rightarrow>* n'; \<forall>a\<in>set cs. valid_edge a\<rbrakk>
\<Longrightarrow> (if cs = [] then get_proc n else get_proc (last (sourcenodes cs))) =
get_proc n'\<close>
from \<open>intra_kind (kind a)\<close> \<open>upd_cs cs (a#as) = []\<close>
have "upd_cs cs as = []" by(cases "kind a",auto simp:intra_kind_def)
from \<open>n -a#as\<rightarrow>* n'\<close> have "n -[]@a#as\<rightarrow>* n'" by simp
hence "valid_edge a" and "n = sourcenode a" and "targetnode a -as\<rightarrow>* n'"
by(fastforce dest:path_split)+
from \<open>valid_edge a\<close> \<open>intra_kind (kind a)\<close> \<open> n = sourcenode a\<close>
have "get_proc n = get_proc (targetnode a)"
by(fastforce intro:get_proc_intra)
from IH[OF \<open>upd_cs cs as = []\<close> \<open>targetnode a -as\<rightarrow>* n'\<close> \<open>\<forall>a\<in>set cs. valid_edge a\<close>]
have "(if cs = [] then get_proc (targetnode a)
else get_proc (last (sourcenodes cs))) = get_proc n'" .
with \<open>get_proc n = get_proc (targetnode a)\<close> show ?case by auto
next
case (slpa_Call cs a as Q r p fs)
note IH = \<open>\<And>n. \<lbrakk>upd_cs (a#cs) as = []; n -as\<rightarrow>* n'; \<forall>a\<in>set (a#cs). valid_edge a\<rbrakk>
\<Longrightarrow> (if a#cs = [] then get_proc n else get_proc (last (sourcenodes (a#cs)))) =
get_proc n'\<close>
from \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> \<open>upd_cs cs (a#as) = []\<close>
have "upd_cs (a#cs) as = []" by simp
from \<open>n -a#as\<rightarrow>* n'\<close> have "n -[]@a#as\<rightarrow>* n'" by simp
hence "valid_edge a" and "n = sourcenode a" and "targetnode a -as\<rightarrow>* n'"
by(fastforce dest:path_split)+
from \<open>valid_edge a\<close> \<open>\<forall>a\<in>set cs. valid_edge a\<close> have "\<forall>a\<in>set (a#cs). valid_edge a"
by simp
from IH[OF \<open>upd_cs (a#cs) as = []\<close> \<open>targetnode a -as\<rightarrow>* n'\<close> this]
have "get_proc (last (sourcenodes (a#cs))) = get_proc n'" by simp
with \<open>n = sourcenode a\<close> show ?case by(cases cs,auto simp:sourcenodes_def)
next
case (slpa_Return cs a as Q p f c' cs')
note IH = \<open>\<And>n. \<lbrakk>upd_cs cs' as = []; n -as\<rightarrow>* n'; \<forall>a\<in>set cs'. valid_edge a\<rbrakk>
\<Longrightarrow> (if cs' = [] then get_proc n else get_proc (last (sourcenodes cs'))) =
get_proc n'\<close>
from \<open>\<forall>a\<in>set cs. valid_edge a\<close> \<open>cs = c'#cs'\<close>
have "valid_edge c'" and "\<forall>a\<in>set cs'. valid_edge a" by simp_all
from \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> \<open>upd_cs cs (a#as) = []\<close> \<open>cs = c'#cs'\<close>
have "upd_cs cs' as = []" by simp
from \<open>n -a#as\<rightarrow>* n'\<close> have "n -[]@a#as\<rightarrow>* n'" by simp
hence "n = sourcenode a" and "targetnode a -as\<rightarrow>* n'"
by(fastforce dest:path_split)+
from \<open>valid_edge c'\<close> \<open>a \<in> get_return_edges c'\<close>
have "get_proc (sourcenode c') = get_proc (targetnode a)"
by(rule get_proc_get_return_edge)
from IH[OF \<open>upd_cs cs' as = []\<close> \<open>targetnode a -as\<rightarrow>* n'\<close> \<open>\<forall>a\<in>set cs'. valid_edge a\<close>]
have "(if cs' = [] then get_proc (targetnode a)
else get_proc (last (sourcenodes cs'))) = get_proc n'" .
with \<open>cs = c'#cs'\<close> \<open>get_proc (sourcenode c') = get_proc (targetnode a)\<close>
show ?case by(auto simp:sourcenodes_def)
qed
lemma slpa_get_return_edges:
"\<lbrakk>same_level_path_aux cs as; cs \<noteq> []; upd_cs cs as = [];
\<forall>xs ys. as = xs@ys \<and> ys \<noteq> [] \<longrightarrow> upd_cs cs xs \<noteq> []\<rbrakk>
\<Longrightarrow> last as \<in> get_return_edges (last cs)"
proof(induct rule:slpa_induct)
case (slpa_empty cs)
from \<open>cs \<noteq> []\<close> \<open>upd_cs cs [] = []\<close> have False by fastforce
thus ?case by simp
next
case (slpa_intra cs a as)
note IH = \<open>\<lbrakk>cs \<noteq> []; upd_cs cs as = [];
\<forall>xs ys. as = xs@ys \<and> ys \<noteq> [] \<longrightarrow> upd_cs cs xs \<noteq> []\<rbrakk>
\<Longrightarrow> last as \<in> get_return_edges (last cs)\<close>
show ?case
proof(cases "as = []")
case True
with \<open>intra_kind (kind a)\<close> \<open>upd_cs cs (a#as) = []\<close> have "cs = []"
by(fastforce simp:intra_kind_def)
with \<open>cs \<noteq> []\<close> have False by simp
thus ?thesis by simp
next
case False
from \<open>intra_kind (kind a)\<close> \<open>upd_cs cs (a#as) = []\<close> have "upd_cs cs as = []"
by(fastforce simp:intra_kind_def)
from \<open>\<forall>xs ys. a#as = xs@ys \<and> ys \<noteq> [] \<longrightarrow> upd_cs cs xs \<noteq> []\<close> \<open>intra_kind (kind a)\<close>
have "\<forall>xs ys. as = xs@ys \<and> ys \<noteq> [] \<longrightarrow> upd_cs cs xs \<noteq> []"
apply(clarsimp,erule_tac x="a#xs" in allE)
by(auto simp:intra_kind_def)
from IH[OF \<open>cs \<noteq> []\<close> \<open>upd_cs cs as = []\<close> this]
have "last as \<in> get_return_edges (last cs)" .
with False show ?thesis by simp
qed
next
case (slpa_Call cs a as Q r p fs)
note IH = \<open>\<lbrakk>a#cs \<noteq> []; upd_cs (a#cs) as = [];
\<forall>xs ys. as = xs@ys \<and> ys \<noteq> [] \<longrightarrow> upd_cs (a#cs) xs \<noteq> []\<rbrakk>
\<Longrightarrow> last as \<in> get_return_edges (last (a#cs))\<close>
show ?case
proof(cases "as = []")
case True
with \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> \<open>upd_cs cs (a#as) = []\<close> have "a#cs = []" by simp
thus ?thesis by simp
next
case False
from \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> \<open>upd_cs cs (a#as) = []\<close> have "upd_cs (a#cs) as = []"
by simp
from \<open>\<forall>xs ys. a#as = xs@ys \<and> ys \<noteq> [] \<longrightarrow> upd_cs cs xs \<noteq> []\<close> \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close>
have "\<forall>xs ys. as = xs@ys \<and> ys \<noteq> [] \<longrightarrow> upd_cs (a#cs) xs \<noteq> []"
by(clarsimp,erule_tac x="a#xs" in allE,simp)
from IH[OF _ \<open>upd_cs (a#cs) as = []\<close> this]
have "last as \<in> get_return_edges (last (a#cs))" by simp
with False \<open>cs \<noteq> []\<close> show ?thesis by(simp add:targetnodes_def)
qed
next
case (slpa_Return cs a as Q p f c' cs')
note IH = \<open>\<lbrakk>cs' \<noteq> []; upd_cs cs' as = [];
\<forall>xs ys. as = xs@ys \<and> ys \<noteq> [] \<longrightarrow> upd_cs cs' xs \<noteq> []\<rbrakk>
\<Longrightarrow> last as \<in> get_return_edges (last cs')\<close>
show ?case
proof(cases "as = []")
case True
with \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> \<open>cs = c'#cs'\<close> \<open>upd_cs cs (a#as) = []\<close>
have "cs' = []" by simp
with \<open>cs = c'#cs'\<close> \<open>a \<in> get_return_edges c'\<close> True
show ?thesis by simp
next
case False
from \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> \<open>cs = c'#cs'\<close> \<open>upd_cs cs (a#as) = []\<close>
have "upd_cs cs' as = []" by simp
show ?thesis
proof(cases "cs' = []")
case True
with \<open>cs = c'#cs'\<close> \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> have "upd_cs cs [a] = []" by simp
with \<open>\<forall>xs ys. a#as = xs@ys \<and> ys \<noteq> [] \<longrightarrow> upd_cs cs xs \<noteq> []\<close> False have False
apply(erule_tac x="[a]" in allE) by fastforce
thus ?thesis by simp
next
case False
from \<open>\<forall>xs ys. a#as = xs@ys \<and> ys \<noteq> [] \<longrightarrow> upd_cs cs xs \<noteq> []\<close>
\<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> \<open>cs = c'#cs'\<close>
have "\<forall>xs ys. as = xs@ys \<and> ys \<noteq> [] \<longrightarrow> upd_cs cs' xs \<noteq> []"
by(clarsimp,erule_tac x="a#xs" in allE,simp)
from IH[OF False \<open>upd_cs cs' as = []\<close> this]
have "last as \<in> get_return_edges (last cs')" .
with \<open>as \<noteq> []\<close> False \<open>cs = c'#cs'\<close> show ?thesis by(simp add:targetnodes_def)
qed
qed
qed
lemma slpa_callstack_length:
assumes "same_level_path_aux cs as" and "length cs = length cfsx"
obtains cfx cfsx' where "transfers (kinds as) (cfsx@cf#cfs) = cfsx'@cfx#cfs"
and "transfers (kinds as) (cfsx@cf#cfs') = cfsx'@cfx#cfs'"
and "length cfsx' = length (upd_cs cs as)"
proof(atomize_elim)
from assms show "\<exists>cfsx' cfx. transfers (kinds as) (cfsx@cf#cfs) = cfsx'@cfx#cfs \<and>
transfers (kinds as) (cfsx@cf#cfs') = cfsx'@cfx#cfs' \<and>
length cfsx' = length (upd_cs cs as)"
proof(induct arbitrary:cfsx cf rule:slpa_induct)
case (slpa_empty cs) thus ?case by(simp add:kinds_def)
next
case (slpa_intra cs a as)
note IH = \<open>\<And>cfsx cf. length cs = length cfsx \<Longrightarrow>
\<exists>cfsx' cfx. transfers (kinds as) (cfsx@cf#cfs) = cfsx'@cfx#cfs \<and>
transfers (kinds as) (cfsx@cf#cfs') = cfsx'@cfx#cfs' \<and>
length cfsx' = length (upd_cs cs as)\<close>
from \<open>intra_kind (kind a)\<close>
have "length (upd_cs cs (a#as)) = length (upd_cs cs as)"
by(fastforce simp:intra_kind_def)
show ?case
proof(cases cfsx)
case Nil
with \<open>length cs = length cfsx\<close> have "length cs = length []" by simp
from Nil \<open>intra_kind (kind a)\<close>
obtain cfx where transfer:"transfer (kind a) (cfsx@cf#cfs) = []@cfx#cfs"
"transfer (kind a) (cfsx@cf#cfs') = []@cfx#cfs'"
by(cases "kind a",auto simp:kinds_def intra_kind_def)
from IH[OF \<open>length cs = length []\<close>] obtain cfsx' cfx'
where "transfers (kinds as) ([]@cfx#cfs) = cfsx'@cfx'#cfs"
and "transfers (kinds as) ([]@cfx#cfs') = cfsx'@cfx'#cfs'"
and "length cfsx' = length (upd_cs cs as)" by blast
with \<open>length (upd_cs cs (a#as)) = length (upd_cs cs as)\<close> transfer
show ?thesis by(fastforce simp:kinds_def)
next
case (Cons x xs)
with \<open>intra_kind (kind a)\<close> obtain cfx'
where transfer:"transfer (kind a) (cfsx@cf#cfs) = (cfx'#xs)@cf#cfs"
"transfer (kind a) (cfsx@cf#cfs') = (cfx'#xs)@cf#cfs'"
by(cases "kind a",auto simp:kinds_def intra_kind_def)
from \<open>length cs = length cfsx\<close> Cons have "length cs = length (cfx'#xs)"
by simp
from IH[OF this] obtain cfs'' cf''
where "transfers (kinds as) ((cfx'#xs)@cf#cfs) = cfs''@cf''#cfs"
and "transfers (kinds as) ((cfx'#xs)@cf#cfs') = cfs''@cf''#cfs'"
and "length cfs'' = length (upd_cs cs as)" by blast
with \<open>length (upd_cs cs (a#as)) = length (upd_cs cs as)\<close> transfer
show ?thesis by(fastforce simp:kinds_def)
qed
next
case (slpa_Call cs a as Q r p fs)
note IH = \<open>\<And>cfsx cf. length (a#cs) = length cfsx \<Longrightarrow>
\<exists>cfsx' cfx. transfers (kinds as) (cfsx@cf#cfs) = cfsx'@cfx#cfs \<and>
transfers (kinds as) (cfsx@cf#cfs') = cfsx'@cfx#cfs' \<and>
length cfsx' = length (upd_cs (a#cs) as)\<close>
from \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close>
obtain cfx where transfer:"transfer (kind a) (cfsx@cf#cfs) = (cfx#cfsx)@cf#cfs"
"transfer (kind a) (cfsx@cf#cfs') = (cfx#cfsx)@cf#cfs'"
by(cases cfsx) auto
from \<open>length cs = length cfsx\<close> have "length (a#cs) = length (cfx#cfsx)"
by simp
from IH[OF this] obtain cfsx' cfx'
where "transfers (kinds as) ((cfx#cfsx)@cf#cfs) = cfsx'@cfx'#cfs"
and "transfers (kinds as) ((cfx#cfsx)@cf#cfs') = cfsx'@cfx'#cfs'"
and "length cfsx' = length (upd_cs (a#cs) as)" by blast
with \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> transfer show ?case by(fastforce simp:kinds_def)
next
case (slpa_Return cs a as Q p f c' cs')
note IH = \<open>\<And>cfsx cf. length cs' = length cfsx \<Longrightarrow>
\<exists>cfsx' cfx. transfers (kinds as) (cfsx@cf#cfs) = cfsx'@cfx#cfs \<and>
transfers (kinds as) (cfsx@cf#cfs') = cfsx'@cfx#cfs' \<and>
length cfsx' = length (upd_cs cs' as)\<close>
from \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> \<open>cs = c'#cs'\<close>
have "length (upd_cs cs (a#as)) = length (upd_cs cs' as)" by simp
show ?case
proof(cases cs')
case Nil
with \<open>cs = c'#cs'\<close> \<open>length cs = length cfsx\<close> obtain cfx
where [simp]:"cfsx = [cfx]" by(cases cfsx) auto
with \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> obtain cf'
where transfer:"transfer (kind a) (cfsx@cf#cfs) = []@cf'#cfs"
"transfer (kind a) (cfsx@cf#cfs') = []@cf'#cfs'"
by fastforce
from Nil have "length cs' = length []" by simp
from IH[OF this] obtain cfsx' cfx'
where "transfers (kinds as) ([]@cf'#cfs) = cfsx'@cfx'#cfs"
and "transfers (kinds as) ([]@cf'#cfs') = cfsx'@cfx'#cfs'"
and "length cfsx' = length (upd_cs cs' as)" by blast
with \<open>length (upd_cs cs (a#as)) = length (upd_cs cs' as)\<close> transfer
show ?thesis by(fastforce simp:kinds_def)
next
case (Cons cx csx)
with \<open>cs = c'#cs'\<close> \<open>length cs = length cfsx\<close> obtain x x' xs
where [simp]:"cfsx = x#x'#xs" and "length xs = length csx"
by(cases cfsx,auto,case_tac list,fastforce+)
with \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> obtain cf'
where transfer:"transfer (kind a) ((x#x'#xs)@cf#cfs) = (cf'#xs)@cf#cfs"
"transfer (kind a) ((x#x'#xs)@cf#cfs') = (cf'#xs)@cf#cfs'"
by fastforce
from \<open>cs = c'#cs'\<close> \<open>length cs = length cfsx\<close> have "length cs' = length (cf'#xs)"
by simp
from IH[OF this] obtain cfsx' cfx
where "transfers (kinds as) ((cf'#xs)@cf#cfs) = cfsx'@cfx#cfs"
and "transfers (kinds as) ((cf'#xs)@cf#cfs') = cfsx'@cfx#cfs'"
and "length cfsx' = length (upd_cs cs' as)" by blast
with \<open>length (upd_cs cs (a#as)) = length (upd_cs cs' as)\<close> transfer
show ?thesis by(fastforce simp:kinds_def)
qed
qed
qed
lemma slpa_snoc_intra:
"\<lbrakk>same_level_path_aux cs as; intra_kind (kind a)\<rbrakk>
\<Longrightarrow> same_level_path_aux cs (as@[a])"
by(induct rule:slpa_induct,auto simp:intra_kind_def)
lemma slpa_snoc_Call:
"\<lbrakk>same_level_path_aux cs as; kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<rbrakk>
\<Longrightarrow> same_level_path_aux cs (as@[a])"
by(induct rule:slpa_induct,auto simp:intra_kind_def)
lemma vpa_Main_slpa:
"\<lbrakk>valid_path_aux cs as; m -as\<rightarrow>* m'; as \<noteq> [];
valid_call_list cs m; get_proc m' = Main;
get_proc (case cs of [] \<Rightarrow> m | _ \<Rightarrow> sourcenode (last cs)) = Main\<rbrakk>
\<Longrightarrow> same_level_path_aux cs as \<and> upd_cs cs as = []"
proof(induct arbitrary:m rule:vpa_induct)
case (vpa_empty cs) thus ?case by simp
next
case (vpa_intra cs a as)
note IH = \<open>\<And>m. \<lbrakk>m -as\<rightarrow>* m'; as \<noteq> []; valid_call_list cs m; get_proc m' = Main;
get_proc (case cs of [] \<Rightarrow> m | a # list \<Rightarrow> sourcenode (last cs)) = Main\<rbrakk>
\<Longrightarrow> same_level_path_aux cs as \<and> upd_cs cs as = []\<close>
from \<open>m -a # as\<rightarrow>* m'\<close> have "sourcenode a = m" and "valid_edge a"
and "targetnode a -as\<rightarrow>* m'" by(auto elim:path_split_Cons)
from \<open>valid_edge a\<close> \<open>intra_kind (kind a)\<close>
have "get_proc (sourcenode a) = get_proc (targetnode a)" by(rule get_proc_intra)
show ?case
proof(cases "as = []")
case True
with \<open>targetnode a -as\<rightarrow>* m'\<close> have "targetnode a = m'" by fastforce
with \<open>get_proc (sourcenode a) = get_proc (targetnode a)\<close>
\<open>sourcenode a = m\<close> \<open>get_proc m' = Main\<close>
have "get_proc m = Main" by simp
have "cs = []"
proof(cases cs)
case Cons
with \<open>valid_call_list cs m\<close>
obtain c Q r p fs where "valid_edge c" and "kind c = Q:r\<hookrightarrow>\<^bsub>get_proc m\<^esub>fs"
by(auto simp:valid_call_list_def,erule_tac x="[]" in allE,
auto simp:sourcenodes_def)
with \<open>get_proc m = Main\<close> have "kind c = Q:r\<hookrightarrow>\<^bsub>Main\<^esub>fs" by simp
with \<open>valid_edge c\<close> have False by(rule Main_no_call_target)
thus ?thesis by simp
qed simp
with True \<open>intra_kind (kind a)\<close> show ?thesis by(fastforce simp:intra_kind_def)
next
case False
from \<open>valid_call_list cs m\<close> \<open>sourcenode a = m\<close>
\<open>get_proc (sourcenode a) = get_proc (targetnode a)\<close>
have "valid_call_list cs (targetnode a)"
apply(clarsimp simp:valid_call_list_def)
apply(erule_tac x="cs'" in allE)
apply(erule_tac x="c" in allE)
by(auto split:list.split)
from \<open>get_proc (case cs of [] \<Rightarrow> m | _ \<Rightarrow> sourcenode (last cs)) = Main\<close>
\<open>sourcenode a = m\<close> \<open>get_proc (sourcenode a) = get_proc (targetnode a)\<close>
have "get_proc (case cs of [] \<Rightarrow> targetnode a | _ \<Rightarrow> sourcenode (last cs)) = Main"
by(cases cs) auto
from IH[OF \<open>targetnode a -as\<rightarrow>* m'\<close> False \<open>valid_call_list cs (targetnode a)\<close>
\<open>get_proc m' = Main\<close> this]
have "same_level_path_aux cs as \<and> upd_cs cs as = []" .
with \<open>intra_kind (kind a)\<close> show ?thesis by(fastforce simp:intra_kind_def)
qed
next
case (vpa_Call cs a as Q r p fs)
note IH = \<open>\<And>m. \<lbrakk>m -as\<rightarrow>* m'; as \<noteq> []; valid_call_list (a # cs) m;
get_proc m' = Main;
get_proc (case a # cs of [] \<Rightarrow> m | _ \<Rightarrow> sourcenode (last (a # cs))) = Main\<rbrakk>
\<Longrightarrow> same_level_path_aux (a # cs) as \<and> upd_cs (a # cs) as = []\<close>
from \<open>m -a # as\<rightarrow>* m'\<close> have "sourcenode a = m" and "valid_edge a"
and "targetnode a -as\<rightarrow>* m'" by(auto elim:path_split_Cons)
from \<open>valid_edge a\<close> \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> have "get_proc (targetnode a) = p"
by(rule get_proc_call)
show ?case
proof(cases "as = []")
case True
with \<open>targetnode a -as\<rightarrow>* m'\<close> have "targetnode a = m'" by fastforce
with \<open>get_proc (targetnode a) = p\<close> \<open>get_proc m' = Main\<close> \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close>
have "kind a = Q:r\<hookrightarrow>\<^bsub>Main\<^esub>fs" by simp
with \<open>valid_edge a\<close> have False by(rule Main_no_call_target)
thus ?thesis by simp
next
case False
from \<open>get_proc (targetnode a) = p\<close> \<open>valid_call_list cs m\<close> \<open>valid_edge a\<close>
\<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> \<open>sourcenode a = m\<close>
have "valid_call_list (a # cs) (targetnode a)"
apply(clarsimp simp:valid_call_list_def)
apply(case_tac cs') apply auto
apply(erule_tac x="list" in allE)
by(case_tac list)(auto simp:sourcenodes_def)
from \<open>get_proc (case cs of [] \<Rightarrow> m | _ \<Rightarrow> sourcenode (last cs)) = Main\<close>
\<open>sourcenode a = m\<close>
have "get_proc (case a # cs of [] \<Rightarrow> targetnode a
| _ \<Rightarrow> sourcenode (last (a # cs))) = Main"
by(cases cs) auto
from IH[OF \<open>targetnode a -as\<rightarrow>* m'\<close> False \<open>valid_call_list (a#cs) (targetnode a)\<close>
\<open>get_proc m' = Main\<close> this]
have "same_level_path_aux (a # cs) as \<and> upd_cs (a # cs) as = []" .
with \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> show ?thesis by simp
qed
next
case (vpa_ReturnEmpty cs a as Q p f)
note IH = \<open>\<And>m. \<lbrakk>m -as\<rightarrow>* m'; as \<noteq> []; valid_call_list [] m; get_proc m' = Main;
get_proc (case [] of [] \<Rightarrow> m | a # list \<Rightarrow> sourcenode (last [])) = Main\<rbrakk>
\<Longrightarrow> same_level_path_aux [] as \<and> upd_cs [] as = []\<close>
from \<open>m -a # as\<rightarrow>* m'\<close> have "sourcenode a = m" and "valid_edge a"
and "targetnode a -as\<rightarrow>* m'" by(auto elim:path_split_Cons)
from \<open>valid_edge a\<close> \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> have "get_proc (sourcenode a) = p"
by(rule get_proc_return)
from \<open>get_proc (case cs of [] \<Rightarrow> m | a # list \<Rightarrow> sourcenode (last cs)) = Main\<close>
\<open>cs = []\<close>
have "get_proc m = Main" by simp
with \<open>sourcenode a = m\<close> \<open>get_proc (sourcenode a) = p\<close> have "p = Main" by simp
with \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> have "kind a = Q\<hookleftarrow>\<^bsub>Main\<^esub>f" by simp
with \<open>valid_edge a\<close> have False by(rule Main_no_return_source)
thus ?case by simp
next
case (vpa_ReturnCons cs a as Q p f c' cs')
note IH = \<open>\<And>m. \<lbrakk>m -as\<rightarrow>* m'; as \<noteq> []; valid_call_list cs' m; get_proc m' = Main;
get_proc (case cs' of [] \<Rightarrow> m | a # list \<Rightarrow> sourcenode (last cs')) = Main\<rbrakk>
\<Longrightarrow> same_level_path_aux cs' as \<and> upd_cs cs' as = []\<close>
from \<open>m -a # as\<rightarrow>* m'\<close> have "sourcenode a = m" and "valid_edge a"
and "targetnode a -as\<rightarrow>* m'" by(auto elim:path_split_Cons)
from \<open>valid_edge a\<close> \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> have "get_proc (sourcenode a) = p"
by(rule get_proc_return)
from \<open>valid_call_list cs m\<close> \<open>cs = c' # cs'\<close>
have "valid_edge c'"
by(auto simp:valid_call_list_def,erule_tac x="[]" in allE,auto)
from \<open>valid_edge c'\<close> \<open>a \<in> get_return_edges c'\<close>
have "get_proc (sourcenode c') = get_proc (targetnode a)"
by(rule get_proc_get_return_edge)
show ?case
proof(cases "as = []")
case True
with \<open>targetnode a -as\<rightarrow>* m'\<close> have "targetnode a = m'" by fastforce
with \<open>get_proc m' = Main\<close> have "get_proc (targetnode a) = Main" by simp
from \<open>get_proc (sourcenode c') = get_proc (targetnode a)\<close>
\<open>get_proc (targetnode a) = Main\<close>
have "get_proc (sourcenode c') = Main" by simp
have "cs' = []"
proof(cases cs')
case (Cons cx csx)
with \<open>cs = c' # cs'\<close> \<open>valid_call_list cs m\<close>
obtain Qx rx fsx where "valid_edge cx"
and "kind cx = Qx:rx\<hookrightarrow>\<^bsub>get_proc (sourcenode c')\<^esub>fsx"
by(auto simp:valid_call_list_def,erule_tac x="[c']" in allE,
auto simp:sourcenodes_def)
with \<open>get_proc (sourcenode c') = Main\<close> have "kind cx = Qx:rx\<hookrightarrow>\<^bsub>Main\<^esub>fsx" by simp
with \<open>valid_edge cx\<close> have False by(rule Main_no_call_target)
thus ?thesis by simp
qed simp
with True \<open>cs = c' # cs'\<close> \<open>a \<in> get_return_edges c'\<close> \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close>
show ?thesis by simp
next
case False
from \<open>valid_call_list cs m\<close> \<open>cs = c' # cs'\<close>
\<open>get_proc (sourcenode c') = get_proc (targetnode a)\<close>
have "valid_call_list cs' (targetnode a)"
apply(clarsimp simp:valid_call_list_def)
apply(hypsubst_thin)
apply(erule_tac x="c' # cs'" in allE)
by(case_tac cs')(auto simp:sourcenodes_def)
from \<open>get_proc (case cs of [] \<Rightarrow> m | a # list \<Rightarrow> sourcenode (last cs)) = Main\<close>
\<open>cs = c' # cs'\<close> \<open>get_proc (sourcenode c') = get_proc (targetnode a)\<close>
have "get_proc (case cs' of [] \<Rightarrow> targetnode a
| _ \<Rightarrow> sourcenode (last cs')) = Main"
by(cases cs') auto
from IH[OF \<open>targetnode a -as\<rightarrow>* m'\<close> False \<open>valid_call_list cs' (targetnode a)\<close>
\<open>get_proc m' = Main\<close> this]
have "same_level_path_aux cs' as \<and> upd_cs cs' as = []" .
with \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> \<open>cs = c' # cs'\<close> \<open>a \<in> get_return_edges c'\<close>
show ?thesis by simp
qed
qed
definition same_level_path :: "'edge list \<Rightarrow> bool"
where "same_level_path as \<equiv> same_level_path_aux [] as \<and> upd_cs [] as = []"
lemma same_level_path_valid_path:
"same_level_path as \<Longrightarrow> valid_path as"
by(fastforce intro:same_level_path_aux_valid_path_aux
simp:same_level_path_def valid_path_def)
lemma same_level_path_Append:
"\<lbrakk>same_level_path as; same_level_path as'\<rbrakk> \<Longrightarrow> same_level_path (as@as')"
by(fastforce elim:same_level_path_aux_Append upd_cs_Append simp:same_level_path_def)
lemma same_level_path_number_Calls_eq_number_Returns:
"\<lbrakk>same_level_path as; \<forall>a \<in> set as. valid_edge a\<rbrakk> \<Longrightarrow>
length [a\<leftarrow>as. \<exists>Q r p fs. kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs] = length [a\<leftarrow>as. \<exists>Q p f. kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f]"
by(fastforce dest:slpa_number_Calls_eq_number_Returns simp:same_level_path_def)
lemma same_level_path_valid_path_Append:
"\<lbrakk>same_level_path as; valid_path as'\<rbrakk> \<Longrightarrow> valid_path (as@as')"
by(fastforce intro:valid_path_aux_Append elim:same_level_path_aux_valid_path_aux
simp:valid_path_def same_level_path_def)
lemma valid_path_same_level_path_Append:
"\<lbrakk>valid_path as; same_level_path as'\<rbrakk> \<Longrightarrow> valid_path (as@as')"
apply(auto simp:valid_path_def same_level_path_def)
apply(erule valid_path_aux_Append)
by(fastforce intro!:same_level_path_aux_valid_path_aux
dest:same_level_path_aux_callstack_Append)
lemma intras_same_level_path:
assumes "\<forall>a \<in> set as. intra_kind(kind a)" shows "same_level_path as"
proof -
from \<open>\<forall>a \<in> set as. intra_kind(kind a)\<close> have "same_level_path_aux [] as"
by(induct as)(auto simp:intra_kind_def)
moreover
from \<open>\<forall>a \<in> set as. intra_kind(kind a)\<close> have "upd_cs [] as = []"
by(induct as)(auto simp:intra_kind_def)
ultimately show ?thesis by(simp add:same_level_path_def)
qed
definition same_level_path' :: "'node \<Rightarrow> 'edge list \<Rightarrow> 'node \<Rightarrow> bool"
("_ -_\<rightarrow>\<^bsub>sl\<^esub>* _" [51,0,0] 80)
where slp_def:"n -as\<rightarrow>\<^bsub>sl\<^esub>* n' \<equiv> n -as\<rightarrow>* n' \<and> same_level_path as"
lemma slp_vp: "n -as\<rightarrow>\<^bsub>sl\<^esub>* n' \<Longrightarrow> n -as\<rightarrow>\<^sub>\<surd>* n'"
by(fastforce intro:same_level_path_valid_path simp:slp_def vp_def)
lemma intra_path_slp: "n -as\<rightarrow>\<^sub>\<iota>* n' \<Longrightarrow> n -as\<rightarrow>\<^bsub>sl\<^esub>* n'"
by(fastforce intro:intras_same_level_path simp:slp_def intra_path_def)
lemma slp_Append:
"\<lbrakk>n -as\<rightarrow>\<^bsub>sl\<^esub>* n''; n'' -as'\<rightarrow>\<^bsub>sl\<^esub>* n'\<rbrakk> \<Longrightarrow> n -as@as'\<rightarrow>\<^bsub>sl\<^esub>* n'"
by(fastforce simp:slp_def intro:path_Append same_level_path_Append)
lemma slp_vp_Append:
"\<lbrakk>n -as\<rightarrow>\<^bsub>sl\<^esub>* n''; n'' -as'\<rightarrow>\<^sub>\<surd>* n'\<rbrakk> \<Longrightarrow> n -as@as'\<rightarrow>\<^sub>\<surd>* n'"
by(fastforce simp:slp_def vp_def intro:path_Append same_level_path_valid_path_Append)
lemma vp_slp_Append:
"\<lbrakk>n -as\<rightarrow>\<^sub>\<surd>* n''; n'' -as'\<rightarrow>\<^bsub>sl\<^esub>* n'\<rbrakk> \<Longrightarrow> n -as@as'\<rightarrow>\<^sub>\<surd>* n'"
by(fastforce simp:slp_def vp_def intro:path_Append valid_path_same_level_path_Append)
lemma slp_get_proc:
"n -as\<rightarrow>\<^bsub>sl\<^esub>* n' \<Longrightarrow> get_proc n = get_proc n'"
by(fastforce dest:slpa_get_proc simp:same_level_path_def slp_def)
lemma same_level_path_inner_path:
assumes "n -as\<rightarrow>\<^bsub>sl\<^esub>* n'"
obtains as' where "n -as'\<rightarrow>\<^sub>\<iota>* n'" and "set(sourcenodes as') \<subseteq> set(sourcenodes as)"
proof(atomize_elim)
from \<open>n -as\<rightarrow>\<^bsub>sl\<^esub>* n'\<close> have "n -as\<rightarrow>* n'" and "same_level_path as"
by(simp_all add:slp_def)
from \<open>same_level_path as\<close> have "same_level_path_aux [] as" and "upd_cs [] as = []"
by(simp_all add:same_level_path_def)
from \<open>n -as\<rightarrow>* n'\<close> \<open>same_level_path_aux [] as\<close> \<open>upd_cs [] as = []\<close>
show "\<exists>as'. n -as'\<rightarrow>\<^sub>\<iota>* n' \<and> set(sourcenodes as') \<subseteq> set(sourcenodes as)"
proof(induct as arbitrary:n rule:length_induct)
fix as n
assume IH:"\<forall>as''. length as'' < length as \<longrightarrow>
(\<forall>n''. n'' -as''\<rightarrow>* n' \<longrightarrow> same_level_path_aux [] as'' \<longrightarrow>
upd_cs [] as'' = [] \<longrightarrow>
(\<exists>as'. n'' -as'\<rightarrow>\<^sub>\<iota>* n' \<and> set (sourcenodes as') \<subseteq> set (sourcenodes as'')))"
and "n -as\<rightarrow>* n'" and "same_level_path_aux [] as" and "upd_cs [] as = []"
show "\<exists>as'. n -as'\<rightarrow>\<^sub>\<iota>* n' \<and> set (sourcenodes as') \<subseteq> set (sourcenodes as)"
proof(cases as)
case Nil
with \<open>n -as\<rightarrow>* n'\<close> show ?thesis by(fastforce simp:intra_path_def)
next
case (Cons a' as')
with \<open>n -as\<rightarrow>* n'\<close> Cons have "n = sourcenode a'" and "valid_edge a'"
and "targetnode a' -as'\<rightarrow>* n'"
by(auto intro:path_split_Cons)
show ?thesis
proof(cases "kind a'" rule:edge_kind_cases)
case Intra
with Cons \<open>same_level_path_aux [] as\<close> have "same_level_path_aux [] as'"
by(fastforce simp:intra_kind_def)
moreover
from Intra Cons \<open>upd_cs [] as = []\<close> have "upd_cs [] as' = []"
by(fastforce simp:intra_kind_def)
ultimately obtain as'' where "targetnode a' -as''\<rightarrow>\<^sub>\<iota>* n'"
and "set (sourcenodes as'') \<subseteq> set (sourcenodes as')"
using IH Cons \<open>targetnode a' -as'\<rightarrow>* n'\<close>
by(erule_tac x="as'" in allE) auto
from \<open>n = sourcenode a'\<close> \<open>valid_edge a'\<close> Intra \<open>targetnode a' -as''\<rightarrow>\<^sub>\<iota>* n'\<close>
have "n -a'#as''\<rightarrow>\<^sub>\<iota>* n'" by(fastforce intro:Cons_path simp:intra_path_def)
with \<open>set (sourcenodes as'') \<subseteq> set (sourcenodes as')\<close> Cons show ?thesis
by(rule_tac x="a'#as''" in exI,auto simp:sourcenodes_def)
next
case (Call Q p f)
with Cons \<open>same_level_path_aux [] as\<close>
have "same_level_path_aux [a'] as'" by simp
from Call Cons \<open>upd_cs [] as = []\<close> have "upd_cs [a'] as' = []" by simp
hence "as' \<noteq> []" by fastforce
with \<open>upd_cs [a'] as' = []\<close> obtain xs ys where "as' = xs@ys" and "xs \<noteq> []"
and "upd_cs [a'] xs = []" and "upd_cs [] ys = []"
and "\<forall>xs' ys'. xs = xs'@ys' \<and> ys' \<noteq> [] \<longrightarrow> upd_cs [a'] xs' \<noteq> []"
by -(erule upd_cs_empty_split,auto)
from \<open>same_level_path_aux [a'] as'\<close> \<open>as' = xs@ys\<close> \<open>upd_cs [a'] xs = []\<close>
have "same_level_path_aux [a'] xs" and "same_level_path_aux [] ys"
by(auto intro:slpa_split)
from \<open>same_level_path_aux [a'] xs\<close> \<open>upd_cs [a'] xs = []\<close>
\<open>\<forall>xs' ys'. xs = xs'@ys' \<and> ys' \<noteq> [] \<longrightarrow> upd_cs [a'] xs' \<noteq> []\<close>
have "last xs \<in> get_return_edges (last [a'])"
by(fastforce intro!:slpa_get_return_edges)
with \<open>valid_edge a'\<close> Call
obtain a where "valid_edge a" and "sourcenode a = sourcenode a'"
and "targetnode a = targetnode (last xs)" and "kind a = (\<lambda>cf. False)\<^sub>\<surd>"
by -(drule call_return_node_edge,auto)
from \<open>targetnode a = targetnode (last xs)\<close> \<open>xs \<noteq> []\<close>
have "targetnode a = targetnode (last (a'#xs))" by simp
from \<open>as' = xs@ys\<close> \<open>xs \<noteq> []\<close> Cons have "length ys < length as" by simp
from \<open>targetnode a' -as'\<rightarrow>* n'\<close> \<open>as' = xs@ys\<close> \<open>xs \<noteq> []\<close>
have "targetnode (last (a'#xs)) -ys\<rightarrow>* n'"
by(cases xs rule:rev_cases,auto dest:path_split)
with IH \<open>length ys < length as\<close> \<open>same_level_path_aux [] ys\<close>
\<open>upd_cs [] ys = []\<close>
obtain as'' where "targetnode (last (a'#xs)) -as''\<rightarrow>\<^sub>\<iota>* n'"
and "set(sourcenodes as'') \<subseteq> set(sourcenodes ys)"
apply(erule_tac x="ys" in allE) apply clarsimp
apply(erule_tac x="targetnode (last (a'#xs))" in allE)
by clarsimp
from \<open>sourcenode a = sourcenode a'\<close> \<open>n = sourcenode a'\<close>
\<open>targetnode a = targetnode (last (a'#xs))\<close> \<open>valid_edge a\<close>
\<open>kind a = (\<lambda>cf. False)\<^sub>\<surd>\<close> \<open>targetnode (last (a'#xs)) -as''\<rightarrow>\<^sub>\<iota>* n'\<close>
have "n -a#as''\<rightarrow>\<^sub>\<iota>* n'"
by(fastforce intro:Cons_path simp:intra_path_def intra_kind_def)
moreover
from \<open>set(sourcenodes as'') \<subseteq> set(sourcenodes ys)\<close> Cons \<open>as' = xs@ys\<close>
\<open>sourcenode a = sourcenode a'\<close>
have "set(sourcenodes (a#as'')) \<subseteq> set(sourcenodes as)"
by(auto simp:sourcenodes_def)
ultimately show ?thesis by blast
next
case (Return Q p f)
with Cons \<open>same_level_path_aux [] as\<close> have False by simp
thus ?thesis by simp
qed
qed
qed
qed
lemma slp_callstack_length_equal:
assumes "n -as\<rightarrow>\<^bsub>sl\<^esub>* n'" obtains cf' where "transfers (kinds as) (cf#cfs) = cf'#cfs"
and "transfers (kinds as) (cf#cfs') = cf'#cfs'"
proof(atomize_elim)
from \<open>n -as\<rightarrow>\<^bsub>sl\<^esub>* n'\<close> have "same_level_path_aux [] as" and "upd_cs [] as = []"
by(simp_all add:slp_def same_level_path_def)
then obtain cfx cfsx where "transfers (kinds as) (cf#cfs) = cfsx@cfx#cfs"
and "transfers (kinds as) (cf#cfs') = cfsx@cfx#cfs'"
and "length cfsx = length (upd_cs [] as)"
by(fastforce elim:slpa_callstack_length)
with \<open>upd_cs [] as = []\<close> have "cfsx = []" by(cases cfsx) auto
with \<open>transfers (kinds as) (cf#cfs) = cfsx@cfx#cfs\<close>
\<open>transfers (kinds as) (cf#cfs') = cfsx@cfx#cfs'\<close>
show "\<exists>cf'. transfers (kinds as) (cf#cfs) = cf'#cfs \<and>
transfers (kinds as) (cf#cfs') = cf'#cfs'" by fastforce
qed
lemma slp_cases [consumes 1,case_names intra_path return_intra_path]:
assumes "m -as\<rightarrow>\<^bsub>sl\<^esub>* m'"
obtains "m -as\<rightarrow>\<^sub>\<iota>* m'"
| as' a as'' Q p f where "as = as'@a#as''" and "kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f"
and "m -as'@[a]\<rightarrow>\<^bsub>sl\<^esub>* targetnode a" and "targetnode a -as''\<rightarrow>\<^sub>\<iota>* m'"
proof(atomize_elim)
from \<open>m -as\<rightarrow>\<^bsub>sl\<^esub>* m'\<close> have "m -as\<rightarrow>* m'" and "same_level_path_aux [] as"
and "upd_cs [] as = []" by(simp_all add:slp_def same_level_path_def)
from \<open>m -as\<rightarrow>* m'\<close> have "\<forall>a \<in> set as. valid_edge a" by(rule path_valid_edges)
have "\<forall>a \<in> set []. valid_edge a" by simp
with \<open>same_level_path_aux [] as\<close> \<open>upd_cs [] as = []\<close> \<open>\<forall>a \<in> set []. valid_edge a\<close>
\<open>\<forall>a \<in> set as. valid_edge a\<close>
show "m -as\<rightarrow>\<^sub>\<iota>* m' \<or>
(\<exists>as' a as'' Q p f. as = as' @ a # as'' \<and> kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f \<and>
m -as' @ [a]\<rightarrow>\<^bsub>sl\<^esub>* targetnode a \<and> targetnode a -as''\<rightarrow>\<^sub>\<iota>* m')"
proof(cases rule:slpa_cases)
case intra_path
with \<open>m -as\<rightarrow>* m'\<close> have "m -as\<rightarrow>\<^sub>\<iota>* m'" by(simp add:intra_path_def)
thus ?thesis by blast
next
case (return_intra_path as' a as'' Q p f c' cs')
from \<open>m -as\<rightarrow>* m'\<close> \<open>as = as' @ a # as''\<close>
have "m -as'\<rightarrow>* sourcenode a" and "valid_edge a" and "targetnode a -as''\<rightarrow>* m'"
by(auto intro:path_split)
from \<open>m -as'\<rightarrow>* sourcenode a\<close> \<open>valid_edge a\<close>
have "m -as'@[a]\<rightarrow>* targetnode a" by(fastforce intro:path_Append path_edge)
with \<open>same_level_path_aux [] as'\<close> \<open>upd_cs [] as' = c' # cs'\<close> \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close>
\<open>a \<in> get_return_edges c'\<close>
have "same_level_path_aux [] (as'@[a])"
by(fastforce intro:same_level_path_aux_Append)
with \<open>upd_cs [] (as' @ [a]) = []\<close> \<open>m -as'@[a]\<rightarrow>* targetnode a\<close>
have "m -as'@[a]\<rightarrow>\<^bsub>sl\<^esub>* targetnode a" by(simp add:slp_def same_level_path_def)
moreover
from \<open>\<forall>a\<in>set as''. intra_kind (kind a)\<close> \<open>targetnode a -as''\<rightarrow>* m'\<close>
have "targetnode a -as''\<rightarrow>\<^sub>\<iota>* m'" by(simp add:intra_path_def)
ultimately show ?thesis using \<open>as = as' @ a # as''\<close> \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> by blast
qed
qed
function same_level_path_rev_aux :: "'edge list \<Rightarrow> 'edge list \<Rightarrow> bool"
where "same_level_path_rev_aux cs [] \<longleftrightarrow> True"
| "same_level_path_rev_aux cs (as@[a]) \<longleftrightarrow>
(case (kind a) of Q\<hookleftarrow>\<^bsub>p\<^esub>f \<Rightarrow> same_level_path_rev_aux (a#cs) as
| Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs \<Rightarrow> case cs of [] \<Rightarrow> False
| c'#cs' \<Rightarrow> c' \<in> get_return_edges a \<and>
same_level_path_rev_aux cs' as
| _ \<Rightarrow> same_level_path_rev_aux cs as)"
by auto(case_tac b rule:rev_cases,auto)
termination by lexicographic_order
lemma slpra_induct [consumes 1,case_names slpra_empty slpra_intra slpra_Return
slpra_Call]:
assumes major: "same_level_path_rev_aux xs ys"
and rules: "\<And>cs. P cs []"
"\<And>cs a as. \<lbrakk>intra_kind(kind a); same_level_path_rev_aux cs as; P cs as\<rbrakk>
\<Longrightarrow> P cs (as@[a])"
"\<And>cs a as Q p f. \<lbrakk>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f; same_level_path_rev_aux (a#cs) as; P (a#cs) as\<rbrakk>
\<Longrightarrow> P cs (as@[a])"
"\<And>cs a as Q r p fs c' cs'. \<lbrakk>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs; cs = c'#cs';
same_level_path_rev_aux cs' as; c' \<in> get_return_edges a; P cs' as\<rbrakk>
\<Longrightarrow> P cs (as@[a])"
shows "P xs ys"
using major
apply(induct ys arbitrary: xs rule:rev_induct)
by(auto intro:rules split:edge_kind.split_asm list.split_asm simp:intra_kind_def)
lemma slpra_to_slpa:
"\<lbrakk>same_level_path_rev_aux cs as; upd_rev_cs cs as = []; n -as\<rightarrow>* n';
valid_return_list cs n'\<rbrakk>
\<Longrightarrow> same_level_path_aux [] as \<and> same_level_path_aux (upd_cs [] as) cs \<and>
upd_cs (upd_cs [] as) cs = []"
proof(induct arbitrary:n' rule:slpra_induct)
case slpra_empty thus ?case by simp
next
case (slpra_intra cs a as)
note IH = \<open>\<And>n'. \<lbrakk>upd_rev_cs cs as = []; n -as\<rightarrow>* n'; valid_return_list cs n'\<rbrakk>
\<Longrightarrow> same_level_path_aux [] as \<and> same_level_path_aux (upd_cs [] as) cs \<and>
upd_cs (upd_cs [] as) cs = []\<close>
from \<open>n -as@[a]\<rightarrow>* n'\<close> have "n -as\<rightarrow>* sourcenode a" and "valid_edge a"
and "n' = targetnode a" by(auto intro:path_split_snoc)
from \<open>valid_edge a\<close> \<open>intra_kind (kind a)\<close>
have "get_proc (sourcenode a) = get_proc (targetnode a)"
by(rule get_proc_intra)
with \<open>valid_return_list cs n'\<close> \<open>n' = targetnode a\<close>
have "valid_return_list cs (sourcenode a)"
apply(clarsimp simp:valid_return_list_def)
apply(erule_tac x="cs'" in allE) apply clarsimp
by(case_tac cs')(auto simp:targetnodes_def)
from \<open>upd_rev_cs cs (as@[a]) = []\<close> \<open>intra_kind (kind a)\<close>
have "upd_rev_cs cs as = []" by(fastforce simp:intra_kind_def)
from \<open>valid_edge a\<close> \<open>intra_kind (kind a)\<close>
have "get_proc (sourcenode a) = get_proc (targetnode a)" by(rule get_proc_intra)
from IH[OF \<open>upd_rev_cs cs as = []\<close> \<open>n -as\<rightarrow>* sourcenode a\<close>
\<open>valid_return_list cs (sourcenode a)\<close>]
have "same_level_path_aux [] as"
and "same_level_path_aux (upd_cs [] as) cs"
and "upd_cs (upd_cs [] as) cs = []" by simp_all
from \<open>same_level_path_aux [] as\<close> \<open>intra_kind (kind a)\<close>
have "same_level_path_aux [] (as@[a])" by(rule slpa_snoc_intra)
from \<open>intra_kind (kind a)\<close>
have "upd_cs [] (as@[a]) = upd_cs [] as"
by(fastforce simp:upd_cs_Append intra_kind_def)
moreover
from \<open>same_level_path_aux [] as\<close> \<open>intra_kind (kind a)\<close>
have "same_level_path_aux [] (as@[a])" by(rule slpa_snoc_intra)
ultimately show ?case using \<open>same_level_path_aux (upd_cs [] as) cs\<close>
\<open>upd_cs (upd_cs [] as) cs = []\<close>
by simp
next
case (slpra_Return cs a as Q p f)
note IH = \<open>\<And>n' n''. \<lbrakk>upd_rev_cs (a#cs) as = []; n -as\<rightarrow>* n';
valid_return_list (a#cs) n'\<rbrakk>
\<Longrightarrow> same_level_path_aux [] as \<and>
same_level_path_aux (upd_cs [] as) (a#cs) \<and>
upd_cs (upd_cs [] as) (a#cs) = []\<close>
from \<open>n -as@[a]\<rightarrow>* n'\<close> have "n -as\<rightarrow>* sourcenode a" and "valid_edge a"
and "n' = targetnode a" by(auto intro:path_split_snoc)
from \<open>valid_edge a\<close> \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> have "p = get_proc (sourcenode a)"
by(rule get_proc_return[THEN sym])
from \<open>valid_return_list cs n'\<close> \<open>n' = targetnode a\<close>
have "valid_return_list cs (targetnode a)" by simp
with \<open>valid_edge a\<close> \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> \<open>p = get_proc (sourcenode a)\<close>
have "valid_return_list (a#cs) (sourcenode a)"
apply(clarsimp simp:valid_return_list_def)
apply(case_tac cs') apply auto
apply(erule_tac x="list" in allE) apply clarsimp
by(case_tac list,auto simp:targetnodes_def)
from \<open>upd_rev_cs cs (as@[a]) = []\<close> \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close>
have "upd_rev_cs (a#cs) as = []" by simp
from IH[OF this \<open>n -as\<rightarrow>* sourcenode a\<close> \<open>valid_return_list (a#cs) (sourcenode a)\<close>]
have "same_level_path_aux [] as"
and "same_level_path_aux (upd_cs [] as) (a#cs)"
and "upd_cs (upd_cs [] as) (a#cs) = []" by simp_all
show ?case
proof(cases "upd_cs [] as")
case Nil
with \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> \<open>same_level_path_aux (upd_cs [] as) (a#cs)\<close>
have False by simp
thus ?thesis by simp
next
case (Cons cx csx)
with \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> \<open>same_level_path_aux (upd_cs [] as) (a#cs)\<close>
obtain Qx fx
where match:"a \<in> get_return_edges cx" "same_level_path_aux csx cs" by auto
from \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> Cons have "upd_cs [] (as@[a]) = csx"
by(rule upd_cs_snoc_Return_Cons)
with \<open>same_level_path_aux (upd_cs [] as) (a#cs)\<close>
\<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> match
have "same_level_path_aux (upd_cs [] (as@[a])) cs" by simp
from \<open>upd_cs [] (as@[a]) = csx\<close> \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> Cons
\<open>upd_cs (upd_cs [] as) (a#cs) = []\<close>
have "upd_cs (upd_cs [] (as@[a])) cs = []" by simp
from Cons \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> match
have "same_level_path_aux (upd_cs [] as) [a]" by simp
with \<open>same_level_path_aux [] as\<close> have "same_level_path_aux [] (as@[a])"
by(rule same_level_path_aux_Append)
with \<open>same_level_path_aux (upd_cs [] (as@[a])) cs\<close>
\<open>upd_cs (upd_cs [] (as@[a])) cs = []\<close>
show ?thesis by simp
qed
next
case (slpra_Call cs a as Q r p fs cx csx)
note IH = \<open>\<And>n'. \<lbrakk>upd_rev_cs csx as = []; n -as\<rightarrow>* n'; valid_return_list csx n'\<rbrakk>
\<Longrightarrow> same_level_path_aux [] as \<and>
same_level_path_aux (upd_cs [] as) csx \<and> upd_cs (upd_cs [] as) csx = []\<close>
note match = \<open>cs = cx#csx\<close> \<open>cx \<in> get_return_edges a\<close>
from \<open>n -as@[a]\<rightarrow>* n'\<close> have "n -as\<rightarrow>* sourcenode a" and "valid_edge a"
and "n' = targetnode a" by(auto intro:path_split_snoc)
from \<open>valid_edge a\<close> match
have "get_proc (sourcenode a) = get_proc (targetnode cx)"
by(fastforce intro:get_proc_get_return_edge)
with \<open>valid_return_list cs n'\<close> \<open>cs = cx#csx\<close>
have "valid_return_list csx (sourcenode a)"
apply(clarsimp simp:valid_return_list_def)
apply(erule_tac x="cx#cs'" in allE) apply clarsimp
by(case_tac cs',auto simp:targetnodes_def)
from \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> match \<open>upd_rev_cs cs (as@[a]) = []\<close>
have "upd_rev_cs csx as = []" by simp
from IH[OF this \<open>n -as\<rightarrow>* sourcenode a\<close> \<open>valid_return_list csx (sourcenode a)\<close>]
have "same_level_path_aux [] as"
and "same_level_path_aux (upd_cs [] as) csx" and "upd_cs (upd_cs [] as) csx = []"
by simp_all
from \<open>same_level_path_aux [] as\<close> \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close>
have "same_level_path_aux [] (as@[a])" by(rule slpa_snoc_Call)
from \<open>valid_edge a\<close> \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> match obtain Q' f' where "kind cx = Q'\<hookleftarrow>\<^bsub>p\<^esub>f'"
by(fastforce dest!:call_return_edges)
from \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> have "upd_cs [] (as@[a]) = a#(upd_cs [] as)"
by(rule upd_cs_snoc_Call)
with \<open>same_level_path_aux (upd_cs [] as) csx\<close> \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close>
\<open>kind cx = Q'\<hookleftarrow>\<^bsub>p\<^esub>f'\<close> match
have "same_level_path_aux (upd_cs [] (as@[a])) cs" by simp
from \<open>upd_cs (upd_cs [] as) csx = []\<close> \<open>upd_cs [] (as@[a]) = a#(upd_cs [] as)\<close>
\<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> \<open>kind cx = Q'\<hookleftarrow>\<^bsub>p\<^esub>f'\<close> match
have "upd_cs (upd_cs [] (as@[a])) cs = []" by simp
with \<open>same_level_path_aux [] (as@[a])\<close>
\<open>same_level_path_aux (upd_cs [] (as@[a])) cs\<close> show ?case by simp
qed
subsubsection \<open>Lemmas on paths with \<open>(_Entry_)\<close>\<close>
lemma path_Entry_target [dest]:
assumes "n -as\<rightarrow>* (_Entry_)"
shows "n = (_Entry_)" and "as = []"
using \<open>n -as\<rightarrow>* (_Entry_)\<close>
proof(induct n as n'\<equiv>"(_Entry_)" rule:path.induct)
case (Cons_path n'' as a n)
from \<open>n'' = (_Entry_)\<close> \<open>targetnode a = n''\<close> \<open>valid_edge a\<close> have False
by -(rule Entry_target,simp_all)
{ case 1
from \<open>False\<close> show ?case ..
next
case 2
from \<open>False\<close> show ?case ..
}
qed simp_all
lemma Entry_sourcenode_hd:
assumes "n -as\<rightarrow>* n'" and "(_Entry_) \<in> set (sourcenodes as)"
shows "n = (_Entry_)" and "(_Entry_) \<notin> set (sourcenodes (tl as))"
using \<open>n -as\<rightarrow>* n'\<close> \<open>(_Entry_) \<in> set (sourcenodes as)\<close>
proof(induct rule:path.induct)
case (empty_path n) case 1
thus ?case by(simp add:sourcenodes_def)
next
case (empty_path n) case 2
thus ?case by(simp add:sourcenodes_def)
next
case (Cons_path n'' as n' a n)
note IH1 = \<open>(_Entry_) \<in> set(sourcenodes as) \<Longrightarrow> n'' = (_Entry_)\<close>
note IH2 = \<open>(_Entry_) \<in> set(sourcenodes as) \<Longrightarrow> (_Entry_) \<notin> set(sourcenodes(tl as))\<close>
have "(_Entry_) \<notin> set (sourcenodes(tl(a#as)))"
proof(rule ccontr)
assume "\<not> (_Entry_) \<notin> set (sourcenodes (tl (a#as)))"
hence "(_Entry_) \<in> set (sourcenodes as)" by simp
from IH1[OF this] have "n'' = (_Entry_)" by simp
with \<open>targetnode a = n''\<close> \<open>valid_edge a\<close> show False by -(erule Entry_target,simp)
qed
hence "(_Entry_) \<notin> set (sourcenodes(tl(a#as)))" by fastforce
{ case 1
with \<open>(_Entry_) \<notin> set (sourcenodes(tl(a#as)))\<close> \<open>sourcenode a = n\<close>
show ?case by(simp add:sourcenodes_def)
next
case 2
with \<open>(_Entry_) \<notin> set (sourcenodes(tl(a#as)))\<close> \<open>sourcenode a = n\<close>
show ?case by(simp add:sourcenodes_def)
}
qed
lemma Entry_no_inner_return_path:
assumes "(_Entry_) -as@[a]\<rightarrow>* n" and "\<forall>a \<in> set as. intra_kind(kind a)"
and "kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f"
shows "False"
proof -
from \<open>(_Entry_) -as@[a]\<rightarrow>* n\<close> have "(_Entry_) -as\<rightarrow>* sourcenode a"
and "valid_edge a" and "targetnode a = n" by(auto intro:path_split_snoc)
from \<open>(_Entry_) -as\<rightarrow>* sourcenode a\<close> \<open>\<forall>a \<in> set as. intra_kind(kind a)\<close>
have "(_Entry_) -as\<rightarrow>\<^sub>\<iota>* sourcenode a" by(simp add:intra_path_def)
hence "get_proc (sourcenode a) = Main"
by(fastforce dest:intra_path_get_procs simp:get_proc_Entry)
with \<open>valid_edge a\<close> \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> have "p = Main"
by(fastforce dest:get_proc_return)
with \<open>valid_edge a\<close> \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> show ?thesis
by(fastforce intro:Main_no_return_source)
qed
lemma vpra_no_slpra:
"\<lbrakk>valid_path_rev_aux cs as; n -as\<rightarrow>* n'; valid_return_list cs n'; cs \<noteq> [];
\<forall>xs ys. as = xs@ys \<longrightarrow> (\<not> same_level_path_rev_aux cs ys \<or> upd_rev_cs cs ys \<noteq> [])\<rbrakk>
\<Longrightarrow> \<exists>a Q f. valid_edge a \<and> kind a = Q\<hookleftarrow>\<^bsub>get_proc n\<^esub>f"
proof(induct arbitrary:n' rule:vpra_induct)
case (vpra_empty cs)
from \<open>valid_return_list cs n'\<close> \<open>cs \<noteq> []\<close> obtain Q f where "valid_edge (hd cs)"
and "kind (hd cs) = Q\<hookleftarrow>\<^bsub>get_proc n'\<^esub>f"
apply(unfold valid_return_list_def)
apply(drule hd_Cons_tl[THEN sym])
apply(erule_tac x="[]" in allE)
apply(erule_tac x="hd cs" in allE)
by auto
from \<open>n -[]\<rightarrow>* n'\<close> have "n = n'" by fastforce
with \<open>valid_edge (hd cs)\<close> \<open>kind (hd cs) = Q\<hookleftarrow>\<^bsub>get_proc n'\<^esub>f\<close> show ?case by blast
next
case (vpra_intra cs a as)
note IH = \<open>\<And>n'. \<lbrakk>n -as\<rightarrow>* n'; valid_return_list cs n'; cs \<noteq> [];
\<forall>xs ys. as = xs@ys \<longrightarrow> \<not> same_level_path_rev_aux cs ys \<or> upd_rev_cs cs ys \<noteq> []\<rbrakk>
\<Longrightarrow> \<exists>a Q f. valid_edge a \<and> kind a = Q\<hookleftarrow>\<^bsub>get_proc n\<^esub>f\<close>
note all = \<open>\<forall>xs ys. as@[a] = xs@ys
\<longrightarrow> \<not> same_level_path_rev_aux cs ys \<or> upd_rev_cs cs ys \<noteq> []\<close>
from \<open>n -as@[a]\<rightarrow>* n'\<close> have "n -as\<rightarrow>* sourcenode a" and "valid_edge a"
and "targetnode a = n'" by(auto intro:path_split_snoc)
from \<open>valid_return_list cs n'\<close> \<open>cs \<noteq> []\<close> obtain Q f where "valid_edge (hd cs)"
and "kind (hd cs) = Q\<hookleftarrow>\<^bsub>get_proc n'\<^esub>f"
apply(unfold valid_return_list_def)
apply(drule hd_Cons_tl[THEN sym])
apply(erule_tac x="[]" in allE)
apply(erule_tac x="hd cs" in allE)
by auto
from \<open>valid_edge a\<close> \<open>intra_kind (kind a)\<close>
have "get_proc (sourcenode a) = get_proc (targetnode a)" by(rule get_proc_intra)
with \<open>kind (hd cs) = Q\<hookleftarrow>\<^bsub>get_proc n'\<^esub>f\<close> \<open>targetnode a = n'\<close>
have "kind (hd cs) = Q\<hookleftarrow>\<^bsub>get_proc (sourcenode a)\<^esub>f" by simp
from \<open>valid_return_list cs n'\<close> \<open>targetnode a = n'\<close>
\<open>get_proc (sourcenode a) = get_proc (targetnode a)\<close>
have "valid_return_list cs (sourcenode a)"
apply(clarsimp simp:valid_return_list_def)
apply(erule_tac x="cs'" in allE)
apply(erule_tac x="c" in allE)
by(auto split:list.split)
from all \<open>intra_kind (kind a)\<close>
have "\<forall>xs ys. as = xs@ys
\<longrightarrow> \<not> same_level_path_rev_aux cs ys \<or> upd_rev_cs cs ys \<noteq> []"
apply clarsimp apply(erule_tac x="xs" in allE)
by(auto simp:intra_kind_def)
from IH[OF \<open>n -as\<rightarrow>* sourcenode a\<close> \<open>valid_return_list cs (sourcenode a)\<close>
\<open>cs \<noteq> []\<close> this] show ?case .
next
case (vpra_Return cs a as Q p f)
note IH = \<open>\<And>n'. \<lbrakk>n -as\<rightarrow>* n'; valid_return_list (a#cs) n'; a#cs \<noteq> [];
\<forall>xs ys. as = xs @ ys \<longrightarrow>
\<not> same_level_path_rev_aux (a#cs) ys \<or> upd_rev_cs (a#cs) ys \<noteq> []\<rbrakk>
\<Longrightarrow> \<exists>a Q f. valid_edge a \<and> kind a = Q\<hookleftarrow>\<^bsub>get_proc n\<^esub>f\<close>
from \<open>n -as@[a]\<rightarrow>* n'\<close> have "n -as\<rightarrow>* sourcenode a" and "valid_edge a"
and "targetnode a = n'" by(auto intro:path_split_snoc)
from \<open>valid_edge a\<close> \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> have "get_proc (sourcenode a) = p"
by(rule get_proc_return)
with \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close> \<open>valid_return_list cs n'\<close> \<open>valid_edge a\<close> \<open>targetnode a = n'\<close>
have "valid_return_list (a#cs) (sourcenode a)"
apply(clarsimp simp:valid_return_list_def)
apply(case_tac cs') apply auto
apply(erule_tac x="list" in allE)
apply(erule_tac x="c" in allE)
by(auto split:list.split simp:targetnodes_def)
from \<open>\<forall>xs ys. as@[a] = xs@ys \<longrightarrow>
\<not> same_level_path_rev_aux cs ys \<or> upd_rev_cs cs ys \<noteq> []\<close> \<open>kind a = Q\<hookleftarrow>\<^bsub>p\<^esub>f\<close>
have "\<forall>xs ys. as = xs@ys \<longrightarrow>
\<not> same_level_path_rev_aux (a#cs) ys \<or> upd_rev_cs (a#cs) ys \<noteq> []"
apply clarsimp apply(erule_tac x="xs" in allE)
by auto
from IH[OF \<open>n -as\<rightarrow>* sourcenode a\<close> \<open>valid_return_list (a#cs) (sourcenode a)\<close>
_ this] show ?case by simp
next
case (vpra_CallEmpty cs a as Q p fs)
from \<open>cs = []\<close> \<open>cs \<noteq> []\<close> have False by simp
thus ?case by simp
next
case (vpra_CallCons cs a as Q r p fs c' cs')
note IH = \<open>\<And>n'. \<lbrakk>n -as\<rightarrow>* n'; valid_return_list cs' n'; cs' \<noteq> [];
\<forall>xs ys. as = xs@ys \<longrightarrow>
\<not> same_level_path_rev_aux cs' ys \<or> upd_rev_cs cs' ys \<noteq> []\<rbrakk>
\<Longrightarrow> \<exists>a Q f. valid_edge a \<and> kind a = Q\<hookleftarrow>\<^bsub>get_proc n\<^esub>f\<close>
note all = \<open>\<forall>xs ys. as@[a] = xs@ys \<longrightarrow>
\<not> same_level_path_rev_aux cs ys \<or> upd_rev_cs cs ys \<noteq> []\<close>
from \<open>n -as@[a]\<rightarrow>* n'\<close> have "n -as\<rightarrow>* sourcenode a" and "valid_edge a"
and "targetnode a = n'" by(auto intro:path_split_snoc)
from \<open>valid_return_list cs n'\<close> \<open>cs = c'#cs'\<close> have "valid_edge c'"
apply(clarsimp simp:valid_return_list_def)
apply(erule_tac x="[]" in allE)
by auto
show ?case
proof(cases "cs' = []")
case True
with \<open>cs = c'#cs'\<close> \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> \<open>c' \<in> get_return_edges a\<close>
have "same_level_path_rev_aux cs ([]@[a])"
and "upd_rev_cs cs ([]@[a]) = []"
by(simp only:same_level_path_rev_aux.simps upd_rev_cs.simps,clarsimp)+
with all have False by(erule_tac x="as" in allE) fastforce
thus ?thesis by simp
next
case False
with \<open>valid_return_list cs n'\<close> \<open>cs = c'#cs'\<close>
have "valid_return_list cs' (targetnode c')"
apply(clarsimp simp:valid_return_list_def)
apply(hypsubst_thin)
apply(erule_tac x="c'#cs'" in allE)
apply(auto simp:targetnodes_def)
apply(case_tac cs') apply auto
apply(case_tac list) apply(auto simp:targetnodes_def)
done
from \<open>valid_edge a\<close> \<open>c' \<in> get_return_edges a\<close>
have "get_proc (sourcenode a) = get_proc (targetnode c')"
by(rule get_proc_get_return_edge)
with \<open>valid_return_list cs' (targetnode c')\<close>
have "valid_return_list cs' (sourcenode a)"
apply(clarsimp simp:valid_return_list_def)
apply(hypsubst_thin)
apply(erule_tac x="cs'" in allE)
apply(erule_tac x="c" in allE)
by(auto split:list.split)
from all \<open>kind a = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close> \<open>cs = c'#cs'\<close> \<open>c' \<in> get_return_edges a\<close>
have "\<forall>xs ys. as = xs@ys
\<longrightarrow> \<not> same_level_path_rev_aux cs' ys \<or> upd_rev_cs cs' ys \<noteq> []"
apply clarsimp apply(erule_tac x="xs" in allE)
by auto
from IH[OF \<open>n -as\<rightarrow>* sourcenode a\<close> \<open>valid_return_list cs' (sourcenode a)\<close>
False this] show ?thesis .
qed
qed
lemma valid_Entry_path_ascending_path:
assumes "(_Entry_) -as\<rightarrow>\<^sub>\<surd>* n"
obtains as' where "(_Entry_) -as'\<rightarrow>\<^sub>\<surd>* n"
and "set(sourcenodes as') \<subseteq> set(sourcenodes as)"
and "\<forall>a' \<in> set as'. intra_kind(kind a') \<or> (\<exists>Q r p fs. kind a' = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs)"
proof(atomize_elim)
from \<open>(_Entry_) -as\<rightarrow>\<^sub>\<surd>* n\<close>
show "\<exists>as'. (_Entry_) -as'\<rightarrow>\<^sub>\<surd>* n \<and> set(sourcenodes as') \<subseteq> set(sourcenodes as)\<and>
(\<forall>a' \<in> set as'. intra_kind(kind a') \<or> (\<exists>Q r p fs. kind a' = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs))"
proof(induct as arbitrary:n rule:length_induct)
fix as n
assume IH:"\<forall>as''. length as'' < length as \<longrightarrow>
(\<forall>n'. (_Entry_) -as''\<rightarrow>\<^sub>\<surd>* n' \<longrightarrow>
(\<exists>as'. (_Entry_) -as'\<rightarrow>\<^sub>\<surd>* n' \<and> set (sourcenodes as') \<subseteq> set (sourcenodes as'') \<and>
(\<forall>a'\<in>set as'. intra_kind (kind a') \<or> (\<exists>Q r p fs. kind a' = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs))))"
and "(_Entry_) -as\<rightarrow>\<^sub>\<surd>* n"
show "\<exists>as'. (_Entry_) -as'\<rightarrow>\<^sub>\<surd>* n \<and> set(sourcenodes as') \<subseteq> set(sourcenodes as)\<and>
(\<forall>a' \<in> set as'. intra_kind(kind a') \<or> (\<exists>Q r p fs. kind a' = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs))"
proof(cases "as = []")
case True
with \<open>(_Entry_) -as\<rightarrow>\<^sub>\<surd>* n\<close> show ?thesis by(fastforce simp:sourcenodes_def vp_def)
next
case False
with \<open>(_Entry_) -as\<rightarrow>\<^sub>\<surd>* n\<close>
have "((\<exists>a' as'. as = as'@[a'] \<and> intra_kind(kind a')) \<or>
(\<exists>a' as' Q r p fs. as = as'@[a'] \<and> kind a' = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs)) \<or>
(\<exists>as' as'' n'. as = as'@as'' \<and> as'' \<noteq> [] \<and> n' -as''\<rightarrow>\<^bsub>sl\<^esub>* n)"
by(fastforce dest!:valid_Entry_path_cases)
thus ?thesis apply -
proof(erule disjE)+
assume "\<exists>a' as'. as = as'@[a'] \<and> intra_kind(kind a')"
then obtain a' as' where "as = as'@[a']" and "intra_kind(kind a')" by blast
from \<open>(_Entry_) -as\<rightarrow>\<^sub>\<surd>* n\<close> \<open>as = as'@[a']\<close>
have "(_Entry_) -as'\<rightarrow>\<^sub>\<surd>* sourcenode a'" and "valid_edge a'"
and "targetnode a' = n"
by(auto intro:vp_split_snoc)
from \<open>valid_edge a'\<close> \<open>intra_kind(kind a')\<close>
have "sourcenode a' -[a']\<rightarrow>\<^bsub>sl\<^esub>* targetnode a'"
by(fastforce intro:path_edge intras_same_level_path simp:slp_def)
from IH \<open>(_Entry_) -as'\<rightarrow>\<^sub>\<surd>* sourcenode a'\<close> \<open>as = as'@[a']\<close>
obtain xs where "(_Entry_) -xs\<rightarrow>\<^sub>\<surd>* sourcenode a'"
and "set (sourcenodes xs) \<subseteq> set (sourcenodes as')"
and "\<forall>a'\<in>set xs. intra_kind (kind a') \<or> (\<exists>Q r p fs. kind a' = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs)"
apply(erule_tac x="as'" in allE) by auto
from \<open>(_Entry_) -xs\<rightarrow>\<^sub>\<surd>* sourcenode a'\<close> \<open>sourcenode a' -[a']\<rightarrow>\<^bsub>sl\<^esub>* targetnode a'\<close>
have "(_Entry_) -xs@[a']\<rightarrow>\<^sub>\<surd>* targetnode a'" by(rule vp_slp_Append)
with \<open>targetnode a' = n\<close> have "(_Entry_) -xs@[a']\<rightarrow>\<^sub>\<surd>* n" by simp
moreover
from \<open>set (sourcenodes xs) \<subseteq> set (sourcenodes as')\<close> \<open>as = as'@[a']\<close>
have "set (sourcenodes (xs@[a'])) \<subseteq> set (sourcenodes as)"
by(auto simp:sourcenodes_def)
moreover
from \<open>\<forall>a'\<in>set xs. intra_kind (kind a') \<or> (\<exists>Q r p fs. kind a' = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs)\<close>
\<open>intra_kind(kind a')\<close>
have "\<forall>a'\<in>set (xs@[a']). intra_kind (kind a') \<or>
(\<exists>Q r p fs. kind a' = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs)"
by fastforce
ultimately show ?thesis by blast
next
assume "\<exists>a' as' Q r p fs. as = as'@[a'] \<and> kind a' = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs"
then obtain a' as' Q r p fs where "as = as'@[a']" and "kind a' = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs"
by blast
from \<open>(_Entry_) -as\<rightarrow>\<^sub>\<surd>* n\<close> \<open>as = as'@[a']\<close>
have "(_Entry_) -as'\<rightarrow>\<^sub>\<surd>* sourcenode a'" and "valid_edge a'"
and "targetnode a' = n"
by(auto intro:vp_split_snoc)
from IH \<open>(_Entry_) -as'\<rightarrow>\<^sub>\<surd>* sourcenode a'\<close> \<open>as = as'@[a']\<close>
obtain xs where "(_Entry_) -xs\<rightarrow>\<^sub>\<surd>* sourcenode a'"
and "set (sourcenodes xs) \<subseteq> set (sourcenodes as')"
and "\<forall>a'\<in>set xs. intra_kind (kind a') \<or> (\<exists>Q r p fs. kind a' = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs)"
apply(erule_tac x="as'" in allE) by auto
from \<open>targetnode a' = n\<close> \<open>valid_edge a'\<close> \<open>kind a' = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close>
\<open>(_Entry_) -xs\<rightarrow>\<^sub>\<surd>* sourcenode a'\<close>
have "(_Entry_) -xs@[a']\<rightarrow>\<^sub>\<surd>* n"
by(fastforce intro:path_Append path_edge vpa_snoc_Call
simp:vp_def valid_path_def)
moreover
from \<open>set (sourcenodes xs) \<subseteq> set (sourcenodes as')\<close> \<open>as = as'@[a']\<close>
have "set (sourcenodes (xs@[a'])) \<subseteq> set (sourcenodes as)"
by(auto simp:sourcenodes_def)
moreover
from \<open>\<forall>a'\<in>set xs. intra_kind (kind a') \<or> (\<exists>Q r p fs. kind a' = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs)\<close>
\<open>kind a' = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs\<close>
have "\<forall>a'\<in>set (xs@[a']). intra_kind (kind a') \<or>
(\<exists>Q r p fs. kind a' = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs)"
by fastforce
ultimately show ?thesis by blast
next
assume "\<exists>as' as'' n'. as = as'@as'' \<and> as'' \<noteq> [] \<and> n' -as''\<rightarrow>\<^bsub>sl\<^esub>* n"
then obtain as' as'' n' where "as = as'@as''" and "as'' \<noteq> []"
and "n' -as''\<rightarrow>\<^bsub>sl\<^esub>* n" by blast
from \<open>(_Entry_) -as\<rightarrow>\<^sub>\<surd>* n\<close> \<open>as = as'@as''\<close> \<open>as'' \<noteq> []\<close>
have "(_Entry_) -as'\<rightarrow>\<^sub>\<surd>* hd(sourcenodes as'')"
by(cases as'',auto intro:vp_split simp:sourcenodes_def)
from \<open>n' -as''\<rightarrow>\<^bsub>sl\<^esub>* n\<close> \<open>as'' \<noteq> []\<close> have "hd(sourcenodes as'') = n'"
by(fastforce intro:path_sourcenode simp:slp_def)
from \<open>as = as'@as''\<close> \<open>as'' \<noteq> []\<close> have "length as' < length as" by simp
with IH \<open>(_Entry_) -as'\<rightarrow>\<^sub>\<surd>* hd(sourcenodes as'')\<close>
\<open>hd(sourcenodes as'') = n'\<close>
obtain xs where "(_Entry_) -xs\<rightarrow>\<^sub>\<surd>* n'"
and "set (sourcenodes xs) \<subseteq> set (sourcenodes as')"
and "\<forall>a'\<in>set xs. intra_kind (kind a') \<or> (\<exists>Q r p fs. kind a' = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs)"
apply(erule_tac x="as'" in allE) by auto
from \<open>n' -as''\<rightarrow>\<^bsub>sl\<^esub>* n\<close> obtain ys where "n' -ys\<rightarrow>\<^sub>\<iota>* n"
and "set(sourcenodes ys) \<subseteq> set(sourcenodes as'')"
by(erule same_level_path_inner_path)
from \<open>(_Entry_) -xs\<rightarrow>\<^sub>\<surd>* n'\<close> \<open>n' -ys\<rightarrow>\<^sub>\<iota>* n\<close> have "(_Entry_) -xs@ys\<rightarrow>\<^sub>\<surd>* n"
by(fastforce intro:vp_slp_Append intra_path_slp)
moreover
from \<open>set (sourcenodes xs) \<subseteq> set (sourcenodes as')\<close>
\<open>set(sourcenodes ys) \<subseteq> set(sourcenodes as'')\<close> \<open>as = as'@as''\<close>
have "set (sourcenodes (xs@ys)) \<subseteq> set(sourcenodes as)"
by(auto simp:sourcenodes_def)
moreover
from \<open>\<forall>a'\<in>set xs. intra_kind (kind a') \<or> (\<exists>Q r p fs. kind a' = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs)\<close>
\<open>n' -ys\<rightarrow>\<^sub>\<iota>* n\<close>
have "\<forall>a'\<in>set (xs@ys). intra_kind (kind a') \<or> (\<exists>Q r p fs. kind a' = Q:r\<hookrightarrow>\<^bsub>p\<^esub>fs)"
by(fastforce simp:intra_path_def)
ultimately show ?thesis by blast
qed
qed
qed
qed
end
end
|
module System.File.Support
%default total
public export
support : String -> String
support fn = "C:" ++ fn ++ ", libidris2_support, idris_file.h"
export
ok : HasIO io => a -> io (Either err a)
ok x = pure (Right x)
|
libertyauto is discussed here to help providing you with the information to compare free insurance quotes and get a lower insurance.
Our company has helped thousands of consumers save money with libertyauto by allowing comparisons from Top insurance companies.
libertyauto taken into account for choosing and comparing from the biggest names.
With libertyauto, we’re committed to helping you find that fits your needs—and your budget. We’ve also partnered to put you in the driver’s seat, libertyauto allowing you to compare up to five free quotes on the insurance of your choice.
By entering your libertyauto information to the right, you are instantly matched with the most competitive companies in the business. And, once matched, you will receive up to five free quotes for fast and easy comparison of libertyauto!
We take pride in protecting your personal information libertyauto. That’s why we use the highest security measures available to safeguard it. We also work to keep spam out of your inbox by vowing never to sell your email address for mass libertyauto marketing schemes.
Get Your Free libertyauto Quotes Today!
Trust us to find a policy for you related to libertyauto. Simply enter your information to the right and receive up to five free quotes on the insurance of your choice!
To make sure you're not overpaying for your insurance, we invite you to compare your current rate to the lowest rate quoted from the Top insurance companies' rates available. Compare instant auto insurance quotes, car insurance quotes, life insurance quotes, home insurance quotes, health insurance quotes and more from State Farms, Farmers, Progressive, Travelers, Safeco and more related to libertyauto.
This site is intended for info purposes only including but not limited to insurance pricing and comparison. We are not an insurance company or related to libertyauto. |
{-# LANGUAGE OverloadedStrings #-}
module Statistics.Classification.ROC (
ROC(..)
, ROCPoint(..)
, rocPoint
, efficientROC
, roc
) where
import Data.List (foldl')
import Data.Csv ((.:), (.=), DefaultOrdered(..), FromNamedRecord(..), ToNamedRecord(..), header, namedRecord)
import qualified Data.Vector as V
import Statistics.Classification.ConfusionMatrix (ConfusionMatrix, trueConfMatrix, truePosRate, falsePosRate)
import Statistics.Classification.Types (ClassificationResult(..), ClassificationScore(..), sortByScore)
data ROC = ROC {
rocAUC :: !Double
, rocCurve :: !(V.Vector ROCPoint)
} deriving (Eq, Show, Read)
data ROCPoint = ROCPoint {
rocTruePos :: {-# UNPACK #-}!Double
, rocFalsePos :: {-# UNPACK #-}!Double
, rocCutoff :: {-# UNPACK #-}!Double
, rocConfusion :: !ConfusionMatrix
} deriving (Eq, Show, Read)
rocPoint :: Double -> ConfusionMatrix -> ROCPoint
rocPoint cutoff cm = ROCPoint {
rocTruePos = truePosRate cm
, rocFalsePos = falsePosRate cm
, rocCutoff = cutoff
, rocConfusion = cm
}
instance DefaultOrdered ROCPoint where
headerOrder _ = header [
"true_positive_rate"
, "false_positive_rate"
, "cutoff"
] <> headerOrder (undefined :: ConfusionMatrix)
instance ToNamedRecord ROCPoint where
toNamedRecord rp = namedRecord [
"true_positive_rate" .= rocTruePos rp
, "false_positive_rate" .= rocFalsePos rp
, "cutoff" .= rocCutoff rp
] <> toNamedRecord (rocConfusion rp)
instance FromNamedRecord ROCPoint where
parseNamedRecord r = ROCPoint <$>
r .: "true_positive_rate"
<*> r .: "false_positive_rate"
<*> r .: "cutoff"
<*> parseNamedRecord r
data EffRocState = EffRocState {
effRocCutoff :: {-# UNPACK #-}!Double
, effRocTP :: {-# UNPACK #-}!Int
, effRocFP :: {-# UNPACK #-}!Int
, effRocTPprev :: {-# UNPACK #-}!Int
, effRocFPprev :: {-# UNPACK #-}!Int
, effRocOut :: ![ROCPoint]
, effRocAUC :: {-# UNPACK #-}!Double
} deriving (Eq, Show, Read)
emptyEffRocState :: EffRocState
emptyEffRocState = EffRocState inf 0 0 0 0 [] 0
where inf = 1 / 0
trapezoidArea :: Int -> Int -> Int -> Int -> Double
trapezoidArea x1 x2 y1 y2 = base * height
where
base = fromIntegral . abs $ x2 - x1
height = 0.5 * fromIntegral y2 + 0.5 * fromIntegral y1
addArea :: EffRocState -> EffRocState
addArea s0 = s0 { effRocAUC = effRocAUC s0 + area }
where
area = trapezoidArea (effRocFP s0) (effRocFPprev s0) (effRocTP s0) (effRocTPprev s0)
updRocState :: Int -> Int -> EffRocState -> ClassificationScore Bool -> EffRocState
updRocState p n s r
| effRocCutoff s /= cutoff = nextExample . nextCutoff $ addArea s
| otherwise = nextExample s
where
cutoff = classifiedScore r
actual = classifiedExample r
nextCutoff s0 = s0 { effRocCutoff = cutoff, effRocTPprev = effRocTP s0, effRocFPprev = effRocFP s0 }
nextExample s0 =
let s1 = if actual then s0 { effRocTP = effRocTP s0 + 1 } else s0 { effRocFP = effRocFP s0 + 1 }
cm = trueConfMatrix (ClassificationResult p (effRocTP s1)) (ClassificationResult n (n - effRocFP s1))
in s1 { effRocOut = rocPoint cutoff cm : effRocOut s1 }
-- O(n log n) ROC curve generation and AUC calculation
-- Algorithm 1 and 2 in
-- Fawcett, T., 2006. An Introduction to ROC Analysis. Pattern Recognition Letters 27 (861 - 874)
efficientROC :: Foldable f => Int -> Int -> f (ClassificationScore Bool) -> ROC
efficientROC p n = out . foldl' (updRocState p n) emptyEffRocState
where
finAUC effr
| p == 0 || n == 0 = 0 -- degenerate case, no actual positive or negative examples.
| otherwise = (effRocAUC effr + trapezoidArea n (effRocFPprev effr) p (effRocTPprev effr)) / fromIntegral (p * n)
out s = ROC {
rocAUC = finAUC s
, rocCurve = V.fromList $ effRocOut s
}
roc :: V.Vector (ClassificationScore Bool) -> ROC
roc v = efficientROC p n . V.reverse $ sortByScore v
where
p = V.length $ V.findIndices classifiedExample v
n = V.length v - p
|
/-
Copyright (c) 2022 Rémy Degenne. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Rémy Degenne
-/
import order.locally_finite
import order.succ_pred.basic
import order.hom.basic
import data.countable.basic
import logic.encodable.basic
/-!
# Linear locally finite orders
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We prove that a `linear_order` which is a `locally_finite_order` also verifies
* `succ_order`
* `pred_order`
* `is_succ_archimedean`
* `is_pred_archimedean`
* `countable`
Furthermore, we show that there is an `order_iso` between such an order and a subset of `ℤ`.
## Main definitions
* `to_Z i0 i`: in a linear order on which we can define predecessors and successors and which is
succ-archimedean, we can assign a unique integer `to_Z i0 i` to each element `i : ι` while
respecting the order, starting from `to_Z i0 i0 = 0`.
## Main results
Instances about linear locally finite orders:
* `linear_locally_finite_order.succ_order`: a linear locally finite order has a successor function.
* `linear_locally_finite_order.pred_order`: a linear locally finite order has a predecessor
function.
* `linear_locally_finite_order.is_succ_archimedean`: a linear locally finite order is
succ-archimedean.
* `linear_order.pred_archimedean_of_succ_archimedean`: a succ-archimedean linear order is also
pred-archimedean.
* `countable_of_linear_succ_pred_arch` : a succ-archimedean linear order is countable.
About `to_Z`:
* `order_iso_range_to_Z_of_linear_succ_pred_arch`: `to_Z` defines an `order_iso` between `ι` and its
range.
* `order_iso_nat_of_linear_succ_pred_arch`: if the order has a bot but no top, `to_Z` defines an
`order_iso` between `ι` and `ℕ`.
* `order_iso_int_of_linear_succ_pred_arch`: if the order has neither bot nor top, `to_Z` defines an
`order_iso` between `ι` and `ℤ`.
* `order_iso_range_of_linear_succ_pred_arch`: if the order has both a bot and a top, `to_Z` gives an
`order_iso` between `ι` and `finset.range ((to_Z ⊥ ⊤).to_nat + 1)`.
-/
open order
variables {ι : Type*} [linear_order ι]
namespace linear_locally_finite_order
/-- Successor in a linear order. This defines a true successor only when `i` is isolated from above,
i.e. when `i` is not the greatest lower bound of `(i, ∞)`. -/
noncomputable def succ_fn (i : ι) : ι := (exists_glb_Ioi i).some
lemma succ_fn_spec (i : ι) : is_glb (set.Ioi i) (succ_fn i) := (exists_glb_Ioi i).some_spec
lemma le_succ_fn (i : ι) : i ≤ succ_fn i :=
by { rw [le_is_glb_iff (succ_fn_spec i), mem_lower_bounds], exact λ x hx, (le_of_lt hx), }
lemma is_glb_Ioc_of_is_glb_Ioi {i j k : ι} (hij_lt : i < j) (h : is_glb (set.Ioi i) k) :
is_glb (set.Ioc i j) k :=
begin
simp_rw [is_glb, is_greatest, mem_upper_bounds, mem_lower_bounds] at h ⊢,
refine ⟨λ x hx, h.1 x hx.1, λ x hx, h.2 x _⟩,
intros y hy,
cases le_or_lt y j with h_le h_lt,
{ exact hx y ⟨hy, h_le⟩, },
{ exact le_trans (hx j ⟨hij_lt, le_rfl⟩) h_lt.le, },
end
lemma is_max_of_succ_fn_le [locally_finite_order ι] (i : ι) (hi : succ_fn i ≤ i) : is_max i :=
begin
refine λ j hij, not_lt.mp (λ hij_lt, _),
have h_succ_fn_eq : succ_fn i = i := le_antisymm hi (le_succ_fn i),
have h_glb : is_glb (finset.Ioc i j : set ι) i,
{ rw finset.coe_Ioc,
have h := succ_fn_spec i,
rw h_succ_fn_eq at h,
exact is_glb_Ioc_of_is_glb_Ioi hij_lt h, },
have hi_mem : i ∈ finset.Ioc i j,
{ refine finset.is_glb_mem _ h_glb _,
exact ⟨_, finset.mem_Ioc.mpr ⟨hij_lt, le_rfl⟩⟩, },
rw finset.mem_Ioc at hi_mem,
exact lt_irrefl i hi_mem.1,
end
lemma succ_fn_le_of_lt (i j : ι) (hij : i < j) : succ_fn i ≤ j :=
by { have h := succ_fn_spec i, rw [is_glb, is_greatest, mem_lower_bounds] at h, exact h.1 j hij, }
lemma le_of_lt_succ_fn (j i : ι) (hij : j < succ_fn i) : j ≤ i :=
begin
rw lt_is_glb_iff (succ_fn_spec i) at hij,
obtain ⟨k, hk_lb, hk⟩ := hij,
rw mem_lower_bounds at hk_lb,
exact not_lt.mp (λ hi_lt_j, not_le.mpr hk (hk_lb j hi_lt_j)),
end
@[priority 100]
noncomputable instance [locally_finite_order ι] : succ_order ι :=
{ succ := succ_fn,
le_succ := le_succ_fn,
max_of_succ_le := is_max_of_succ_fn_le,
succ_le_of_lt := succ_fn_le_of_lt,
le_of_lt_succ := le_of_lt_succ_fn, }
@[priority 100]
noncomputable instance [locally_finite_order ι] : pred_order ι :=
@order_dual.pred_order ιᵒᵈ _ _
end linear_locally_finite_order
@[priority 100]
instance linear_locally_finite_order.is_succ_archimedean [locally_finite_order ι] :
is_succ_archimedean ι :=
{ exists_succ_iterate_of_le := λ i j hij,
begin
rw le_iff_lt_or_eq at hij,
cases hij,
swap, { refine ⟨0, _⟩, simpa only [function.iterate_zero, id.def] using hij, },
by_contra h,
push_neg at h,
have h_lt : ∀ n, succ^[n] i < j,
{ intro n,
induction n with n hn,
{ simpa only [function.iterate_zero, id.def] using hij, },
{ refine lt_of_le_of_ne _ (h _),
rw [function.iterate_succ', function.comp_app],
exact succ_le_of_lt hn, }, },
have h_mem : ∀ n, succ^[n] i ∈ finset.Icc i j,
from λ n, finset.mem_Icc.mpr ⟨le_succ_iterate n i, (h_lt n).le⟩,
obtain ⟨n, m, hnm, h_eq⟩ : ∃ n m, n < m ∧ (succ^[n] i = (succ^[m] i)),
{ let f : ℕ → finset.Icc i j := λ n, ⟨succ^[n] i, h_mem n⟩,
obtain ⟨n, m, hnm_ne, hfnm⟩ : ∃ n m, n ≠ m ∧ f n = f m,
from finite.exists_ne_map_eq_of_infinite f,
have hnm_eq : (succ^[n] i) = (succ^[m] i),
{ simpa only [subtype.mk_eq_mk] using hfnm, },
cases le_total n m with h_le h_le,
{ exact ⟨n, m, lt_of_le_of_ne h_le hnm_ne, hnm_eq⟩, },
{ exact ⟨m, n, lt_of_le_of_ne h_le hnm_ne.symm, hnm_eq.symm ⟩, }, },
have h_max : is_max (succ^[n] i) := is_max_iterate_succ_of_eq_of_ne h_eq hnm.ne,
exact not_le.mpr (h_lt n) (h_max (h_lt n).le),
end }
@[priority 100]
instance linear_order.pred_archimedean_of_succ_archimedean [succ_order ι] [pred_order ι]
[is_succ_archimedean ι] :
is_pred_archimedean ι :=
{ exists_pred_iterate_of_le := λ i j hij,
begin
have h_exists := exists_succ_iterate_of_le hij,
obtain ⟨n, hn_eq, hn_lt_ne⟩ : ∃ n, (succ^[n] i = j) ∧ (∀ m < n, succ^[m] i ≠ j),
from ⟨nat.find h_exists, nat.find_spec h_exists, λ m hmn, nat.find_min h_exists hmn⟩,
refine ⟨n, _⟩,
rw ← hn_eq,
induction n with n hn,
{ simp only [function.iterate_zero, id.def], },
{ rw pred_succ_iterate_of_not_is_max,
rw [nat.succ_sub_succ_eq_sub, tsub_zero],
suffices : (succ^[n] i) < (succ^[n.succ] i), from not_is_max_of_lt this,
refine lt_of_le_of_ne _ _,
{ rw function.iterate_succ',
exact le_succ _, },
{ rw hn_eq,
exact hn_lt_ne _ (nat.lt_succ_self n), }, },
end }
section to_Z
variables [succ_order ι] [is_succ_archimedean ι] [pred_order ι] {i0 i : ι}
/-- `to_Z` numbers elements of `ι` according to their order, starting from `i0`. We prove in
`order_iso_range_to_Z_of_linear_succ_pred_arch` that this defines an `order_iso` between `ι` and
the range of `to_Z`. -/
def to_Z (i0 i : ι) : ℤ :=
dite (i0 ≤ i) (λ hi, nat.find (exists_succ_iterate_of_le hi))
(λ hi, - nat.find (exists_pred_iterate_of_le (not_le.mp hi).le))
lemma to_Z_of_ge (hi : i0 ≤ i) : to_Z i0 i = nat.find (exists_succ_iterate_of_le hi) := dif_pos hi
lemma to_Z_of_lt (hi : i < i0) : to_Z i0 i = - nat.find (exists_pred_iterate_of_le hi.le) :=
dif_neg (not_le.mpr hi)
@[simp] lemma to_Z_of_eq : to_Z i0 i0 = 0 :=
begin
rw to_Z_of_ge le_rfl,
norm_cast,
refine le_antisymm (nat.find_le _) (zero_le _),
rw [function.iterate_zero, id.def],
end
lemma iterate_succ_to_Z (i : ι) (hi : i0 ≤ i) : succ^[(to_Z i0 i).to_nat] i0 = i :=
by { rw [to_Z_of_ge hi, int.to_nat_coe_nat], exact nat.find_spec (exists_succ_iterate_of_le hi), }
lemma iterate_pred_to_Z (i : ι) (hi : i < i0) : pred^[(- to_Z i0 i).to_nat] i0 = i :=
begin
rw [to_Z_of_lt hi, neg_neg, int.to_nat_coe_nat],
exact nat.find_spec (exists_pred_iterate_of_le hi.le),
end
lemma to_Z_nonneg (hi : i0 ≤ i) : 0 ≤ to_Z i0 i :=
by { rw to_Z_of_ge hi, exact nat.cast_nonneg _, }
lemma to_Z_neg (hi : i < i0) : to_Z i0 i < 0 :=
begin
refine lt_of_le_of_ne _ _,
{ rw [to_Z_of_lt hi, neg_nonpos], exact nat.cast_nonneg _, },
{ by_contra,
have h_eq := iterate_pred_to_Z i hi,
rw [← h_eq, h] at hi,
simpa only [neg_zero, int.to_nat_zero, function.iterate_zero, id.def, lt_self_iff_false]
using hi, },
end
lemma to_Z_iterate_succ_le (n : ℕ) : to_Z i0 (succ^[n] i0) ≤ n :=
begin
rw to_Z_of_ge (le_succ_iterate _ _),
norm_cast,
exact nat.find_min' (exists_succ_iterate_of_le _) rfl,
end
lemma to_Z_iterate_pred_ge (n : ℕ) : -(n : ℤ) ≤ to_Z i0 (pred^[n] i0) :=
begin
cases le_or_lt i0 (pred^[n] i0) with h h,
{ have h_eq : (pred^[n] i0) = i0 := le_antisymm (pred_iterate_le _ _) h,
rw [h_eq, to_Z_of_eq],
simp only [right.neg_nonpos_iff, nat.cast_nonneg],},
{ rw [to_Z_of_lt h, neg_le_neg_iff],
norm_cast,
exact nat.find_min' (exists_pred_iterate_of_le _) rfl, },
end
lemma to_Z_iterate_succ_of_not_is_max (n : ℕ) (hn : ¬ is_max (succ^[n] i0)) :
to_Z i0 (succ^[n] i0) = n :=
begin
let m := (to_Z i0 (succ^[n] i0)).to_nat,
have h_eq : (succ^[m] i0) = (succ^[n] i0) := iterate_succ_to_Z _ (le_succ_iterate _ _),
by_cases hmn : m = n,
{ nth_rewrite 1 ← hmn,
simp_rw [m],
rw [int.to_nat_eq_max, to_Z_of_ge (le_succ_iterate _ _), max_eq_left],
exact nat.cast_nonneg _, },
suffices : is_max (succ^[n] i0), from absurd this hn,
exact is_max_iterate_succ_of_eq_of_ne h_eq.symm (ne.symm hmn),
end
lemma to_Z_iterate_pred_of_not_is_min (n : ℕ) (hn : ¬ is_min (pred^[n] i0)) :
to_Z i0 (pred^[n] i0) = -n :=
begin
cases n,
{ simp only [function.iterate_zero, id.def, to_Z_of_eq, nat.cast_zero, neg_zero], },
have : (pred^[n.succ] i0) < i0,
{ refine lt_of_le_of_ne (pred_iterate_le _ _) (λ h_pred_iterate_eq, hn _),
have h_pred_eq_pred : (pred^[n.succ] i0) = (pred^[0] i0),
{ rwa [function.iterate_zero, id.def], },
exact is_min_iterate_pred_of_eq_of_ne h_pred_eq_pred (nat.succ_ne_zero n), },
let m := (- to_Z i0 (pred^[n.succ] i0)).to_nat,
have h_eq : (pred^[m] i0) = (pred^[n.succ] i0) := iterate_pred_to_Z _ this,
by_cases hmn : m = n.succ,
{ nth_rewrite 1 ← hmn,
simp_rw [m],
rw [int.to_nat_eq_max, to_Z_of_lt this, max_eq_left, neg_neg],
rw neg_neg,
exact nat.cast_nonneg _, },
{ suffices : is_min (pred^[n.succ] i0), from absurd this hn,
exact is_min_iterate_pred_of_eq_of_ne h_eq.symm (ne.symm hmn), },
end
lemma le_of_to_Z_le {j : ι} (h_le : to_Z i0 i ≤ to_Z i0 j) : i ≤ j :=
begin
cases le_or_lt i0 i with hi hi; cases le_or_lt i0 j with hj hj,
{ rw [← iterate_succ_to_Z i hi, ← iterate_succ_to_Z j hj],
exact monotone.monotone_iterate_of_le_map succ_mono (le_succ _) (int.to_nat_le_to_nat h_le), },
{ exact absurd ((to_Z_neg hj).trans_le (to_Z_nonneg hi)) (not_lt.mpr h_le), },
{ exact hi.le.trans hj, },
{ rw [← iterate_pred_to_Z i hi, ← iterate_pred_to_Z j hj],
refine monotone.antitone_iterate_of_map_le pred_mono (pred_le _) (int.to_nat_le_to_nat _),
exact neg_le_neg h_le, },
end
lemma to_Z_mono {i j : ι} (h_le : i ≤ j) : to_Z i0 i ≤ to_Z i0 j :=
begin
by_cases hi_max : is_max i,
{ rw le_antisymm h_le (hi_max h_le), },
by_cases hj_min : is_min j,
{ rw le_antisymm h_le (hj_min h_le), },
cases le_or_lt i0 i with hi hi; cases le_or_lt i0 j with hj hj,
{ let m := nat.find (exists_succ_iterate_of_le h_le),
have hm : (succ^[m] i = j) := nat.find_spec (exists_succ_iterate_of_le h_le),
have hj_eq : j = (succ^[(to_Z i0 i).to_nat + m] i0),
{ rw [← hm, add_comm],
nth_rewrite 0 ← iterate_succ_to_Z i hi,
rw function.iterate_add, },
by_contra h,
push_neg at h,
by_cases hm0 : m = 0,
{ rw [hm0, function.iterate_zero, id.def] at hm,
rw hm at h,
exact lt_irrefl _ h, },
refine hi_max (max_of_succ_le (le_trans _ (@le_of_to_Z_le _ _ _ _ _ i0 _ _ _))),
{ exact j, },
{ have h_succ_le : (succ^[(to_Z i0 i).to_nat + 1] i0) ≤ j,
{ rw hj_eq,
refine monotone.monotone_iterate_of_le_map succ_mono (le_succ i0) (add_le_add_left _ _),
exact nat.one_le_iff_ne_zero.mpr hm0, },
rwa [function.iterate_succ', function.comp_app, iterate_succ_to_Z i hi] at h_succ_le, },
{ exact h.le, }, },
{ exact absurd h_le (not_le.mpr (hj.trans_le hi)), },
{ exact (to_Z_neg hi).le.trans (to_Z_nonneg hj), },
{ let m := nat.find (exists_pred_iterate_of_le h_le),
have hm : (pred^[m] j = i) := nat.find_spec (exists_pred_iterate_of_le h_le),
have hj_eq : i = (pred^[(-to_Z i0 j).to_nat + m] i0),
{ rw [← hm, add_comm],
nth_rewrite 0 ← iterate_pred_to_Z j hj,
rw function.iterate_add, },
by_contra h,
push_neg at h,
by_cases hm0 : m = 0,
{ rw [hm0, function.iterate_zero, id.def] at hm,
rw hm at h,
exact lt_irrefl _ h, },
refine hj_min (min_of_le_pred _),
refine (@le_of_to_Z_le _ _ _ _ _ i0 _ _ _).trans _,
{ exact i, },
{ exact h.le, },
{ have h_le_pred : i ≤ (pred^[(-to_Z i0 j).to_nat + 1] i0),
{ rw hj_eq,
refine monotone.antitone_iterate_of_map_le pred_mono (pred_le i0) (add_le_add_left _ _),
exact nat.one_le_iff_ne_zero.mpr hm0, },
rwa [function.iterate_succ', function.comp_app, iterate_pred_to_Z j hj]
at h_le_pred, }, },
end
lemma to_Z_le_iff (i j : ι) : to_Z i0 i ≤ to_Z i0 j ↔ i ≤ j :=
⟨le_of_to_Z_le, to_Z_mono⟩
lemma to_Z_iterate_succ [no_max_order ι] (n : ℕ) : to_Z i0 (succ^[n] i0) = n :=
to_Z_iterate_succ_of_not_is_max n (not_is_max _)
lemma to_Z_iterate_pred [no_min_order ι] (n : ℕ) : to_Z i0 (pred^[n] i0) = -n :=
to_Z_iterate_pred_of_not_is_min n (not_is_min _)
lemma injective_to_Z : function.injective (to_Z i0) :=
λ i j hij, le_antisymm (le_of_to_Z_le hij.le) (le_of_to_Z_le hij.symm.le)
end to_Z
section order_iso
variables [succ_order ι] [pred_order ι] [is_succ_archimedean ι]
/-- `to_Z` defines an `order_iso` between `ι` and its range. -/
noncomputable
def order_iso_range_to_Z_of_linear_succ_pred_arch [hι : nonempty ι] :
ι ≃o set.range (to_Z hι.some) :=
{ to_equiv := equiv.of_injective _ injective_to_Z,
map_rel_iff' := to_Z_le_iff, }
@[priority 100]
instance countable_of_linear_succ_pred_arch : countable ι :=
begin
casesI is_empty_or_nonempty ι with _ hι,
{ apply_instance, },
{ exact countable.of_equiv _ (order_iso_range_to_Z_of_linear_succ_pred_arch).symm.to_equiv, },
end
/-- If the order has neither bot nor top, `to_Z` defines an `order_iso` between `ι` and `ℤ`. -/
noncomputable
def order_iso_int_of_linear_succ_pred_arch [no_max_order ι] [no_min_order ι] [hι : nonempty ι] :
ι ≃o ℤ :=
{ to_fun := to_Z hι.some,
inv_fun := λ n, if 0 ≤ n then (succ^[n.to_nat] hι.some) else (pred^[(-n).to_nat] hι.some),
left_inv := λ i,
begin
cases le_or_lt hι.some i with hi hi,
{ have h_nonneg : 0 ≤ to_Z hι.some i := to_Z_nonneg hi,
simp_rw if_pos h_nonneg,
exact iterate_succ_to_Z i hi, },
{ have h_neg : to_Z hι.some i < 0 := to_Z_neg hi,
simp_rw if_neg (not_le.mpr h_neg),
exact iterate_pred_to_Z i hi, },
end,
right_inv := λ n,
begin
cases le_or_lt 0 n with hn hn,
{ simp_rw if_pos hn,
rw to_Z_iterate_succ,
exact int.to_nat_of_nonneg hn, },
{ simp_rw if_neg (not_le.mpr hn),
rw to_Z_iterate_pred,
simp only [hn.le, int.to_nat_of_nonneg, right.nonneg_neg_iff, neg_neg], },
end,
map_rel_iff' := to_Z_le_iff, }
/-- If the order has a bot but no top, `to_Z` defines an `order_iso` between `ι` and `ℕ`. -/
def order_iso_nat_of_linear_succ_pred_arch [no_max_order ι] [order_bot ι] :
ι ≃o ℕ :=
{ to_fun := λ i, (to_Z ⊥ i).to_nat,
inv_fun := λ n, succ^[n] ⊥,
left_inv := λ i, by { simp_rw if_pos (to_Z_nonneg bot_le), exact iterate_succ_to_Z i bot_le, },
right_inv := λ n,
begin
simp_rw if_pos bot_le,
rw to_Z_iterate_succ,
exact int.to_nat_coe_nat n,
end,
map_rel_iff' := λ i j,
begin
simp only [equiv.coe_fn_mk, int.to_nat_le],
rw [← @to_Z_le_iff ι _ _ _ _ ⊥, int.to_nat_of_nonneg (to_Z_nonneg bot_le)],
end, }
/-- If the order has both a bot and a top, `to_Z` gives an `order_iso` between `ι` and
`finset.range n` for some `n`. -/
def order_iso_range_of_linear_succ_pred_arch [order_bot ι] [order_top ι] :
ι ≃o finset.range ((to_Z ⊥ (⊤ : ι)).to_nat + 1) :=
{ to_fun := λ i, ⟨(to_Z ⊥ i).to_nat,
finset.mem_range_succ_iff.mpr (int.to_nat_le_to_nat ((to_Z_le_iff _ _).mpr le_top))⟩,
inv_fun := λ n, succ^[n] ⊥,
left_inv := λ i, iterate_succ_to_Z i bot_le,
right_inv := λ n, begin
ext1,
simp only [subtype.coe_mk],
refine le_antisymm _ _,
{ rw int.to_nat_le,
exact (to_Z_iterate_succ_le _), },
by_cases hn_max : is_max (succ^[↑n] (⊥ : ι)),
{ rw [← is_top_iff_is_max, is_top_iff_eq_top] at hn_max,
rw hn_max,
exact nat.lt_succ_iff.mp (finset.mem_range.mp n.prop), },
{ rw to_Z_iterate_succ_of_not_is_max _ hn_max,
simp only [int.to_nat_coe_nat], },
end,
map_rel_iff' := λ i j,
begin
simp only [equiv.coe_fn_mk, subtype.mk_le_mk, int.to_nat_le],
rw [← @to_Z_le_iff ι _ _ _ _ ⊥, int.to_nat_of_nonneg (to_Z_nonneg bot_le)],
end, }
end order_iso
|
State Before: α : Type u_1
inst✝ : PartialOrder α
a b : α
⊢ some '' Ioo a b = Ioo ↑a ↑b State After: no goals Tactic: rw [← preimage_coe_Ioo, image_preimage_eq_inter_range, range_coe,
inter_eq_self_of_subset_left (Subset.trans Ioo_subset_Ioi_self <| Ioi_subset_Ioi bot_le)] |
module Prelude.List where
open import Prelude.List.Base public
|
(*
Author: Wenda Li <[email protected] / [email protected]>
*)
section \<open>Some useful lemmas in topology\<close>
theory Missing_Topology imports "HOL-Analysis.Multivariate_Analysis"
begin
subsection \<open>Misc\<close>
lemma open_times_image:
fixes S::"'a::real_normed_field set"
assumes "open S" "c\<noteq>0"
shows "open (((*) c) ` S)"
proof -
let ?f = "\<lambda>x. x/c" and ?g="((*) c)"
have "continuous_on UNIV ?f" using \<open>c\<noteq>0\<close> by (auto intro:continuous_intros)
then have "open (?f -` S)" using \<open>open S\<close> by (auto elim:open_vimage)
moreover have "?g ` S = ?f -` S" using \<open>c\<noteq>0\<close>
apply auto
using image_iff by fastforce
ultimately show ?thesis by auto
qed
lemma image_linear_greaterThan:
fixes x::"'a::linordered_field"
assumes "c\<noteq>0"
shows "((\<lambda>x. c*x+b) ` {x<..}) = (if c>0 then {c*x+b <..} else {..< c*x+b})"
using \<open>c\<noteq>0\<close>
apply (auto simp add:image_iff field_simps)
subgoal for y by (rule bexI[where x="(y-b)/c"],auto simp add:field_simps)
subgoal for y by (rule bexI[where x="(y-b)/c"],auto simp add:field_simps)
done
lemma image_linear_lessThan:
fixes x::"'a::linordered_field"
assumes "c\<noteq>0"
shows "((\<lambda>x. c*x+b) ` {..<x}) = (if c>0 then {..<c*x+b} else {c*x+b<..})"
using \<open>c\<noteq>0\<close>
apply (auto simp add:image_iff field_simps)
subgoal for y by (rule bexI[where x="(y-b)/c"],auto simp add:field_simps)
subgoal for y by (rule bexI[where x="(y-b)/c"],auto simp add:field_simps)
done
lemma continuous_on_neq_split:
fixes f :: "'a::linear_continuum_topology \<Rightarrow> 'b::linorder_topology"
assumes "\<forall>x\<in>s. f x\<noteq>y" "continuous_on s f" "connected s"
shows "(\<forall>x\<in>s. f x>y) \<or> (\<forall>x\<in>s. f x<y)"
proof -
{ fix aa :: 'a and aaa :: 'a
have "y \<notin> f ` s"
using assms(1) by blast
then have "(aa \<notin> s \<or> y < f aa) \<or> aaa \<notin> s \<or> f aaa < y"
by (meson Topological_Spaces.connected_continuous_image assms(2) assms(3)
connectedD_interval image_eqI linorder_not_le) }
then show ?thesis
by blast
qed
lemma
fixes f::"'a::linorder_topology \<Rightarrow> 'b::topological_space"
assumes "continuous_on {a..b} f" "a<b"
shows continuous_on_at_left:"continuous (at_left b) f"
and continuous_on_at_right:"continuous (at_right a) f"
proof -
have "at b within {..a} = bot"
proof -
have "closed {..a}" by auto
then have "closure ({..a} - {b}) = {..a}" by (simp add: assms(2) not_le)
then have "b\<notin>closure ({..a} - {b})" using \<open>a<b\<close> by auto
then show ?thesis using at_within_eq_bot_iff by auto
qed
then have "(f \<longlongrightarrow> f b) (at b within {..a})" by auto
moreover have "(f \<longlongrightarrow> f b) (at b within {a..b})"
using assms unfolding continuous_on by auto
moreover have "{..a} \<union> {a..b} = {..b}"
using \<open>a<b\<close> by auto
ultimately have "(f \<longlongrightarrow> f b) (at b within {..b})"
using Lim_Un[of f "f b" b "{..a}" "{a..b}"] by presburger
then have "(f \<longlongrightarrow> f b) (at b within {..<b})"
apply (elim tendsto_within_subset)
by auto
then show "continuous (at_left b) f" using continuous_within by auto
next
have "at a within {b..} = bot"
proof -
have "closed {b..}" by auto
then have "closure ({b..} - {a}) = {b..}" by (simp add: assms(2) not_le)
then have "a\<notin>closure ({b..} - {a})" using \<open>a<b\<close> by auto
then show ?thesis using at_within_eq_bot_iff by auto
qed
then have "(f \<longlongrightarrow> f a) (at a within {b..})" by auto
moreover have "(f \<longlongrightarrow> f a) (at a within {a..b})"
using assms unfolding continuous_on by auto
moreover have "{b..} \<union> {a..b} = {a..}"
using \<open>a<b\<close> by auto
ultimately have "(f \<longlongrightarrow> f a) (at a within {a..})"
using Lim_Un[of f "f a" a "{b..}" "{a..b}"] by presburger
then have "(f \<longlongrightarrow> f a) (at a within {a<..})"
apply (elim tendsto_within_subset)
by auto
then show "continuous (at_right a) f" using continuous_within by auto
qed
subsection \<open>More about @{term eventually}\<close>
lemma eventually_comp_filtermap:
"eventually (P o f) F \<longleftrightarrow> eventually P (filtermap f F)"
unfolding comp_def using eventually_filtermap by auto
lemma eventually_uminus_at_top_at_bot:
fixes P::"'a::{ordered_ab_group_add,linorder} \<Rightarrow> bool"
shows "eventually (P o uminus) at_bot \<longleftrightarrow> eventually P at_top"
"eventually (P o uminus) at_top \<longleftrightarrow> eventually P at_bot"
unfolding eventually_comp_filtermap
by (fold at_top_mirror at_bot_mirror,auto)
lemma eventually_at_infinityI:
fixes P::"'a::real_normed_vector \<Rightarrow> bool"
assumes "\<And>x. c \<le> norm x \<Longrightarrow> P x"
shows "eventually P at_infinity"
unfolding eventually_at_infinity using assms by auto
lemma eventually_at_bot_linorderI:
fixes c::"'a::linorder"
assumes "\<And>x. x \<le> c \<Longrightarrow> P x"
shows "eventually P at_bot"
using assms by (auto simp: eventually_at_bot_linorder)
lemma eventually_times_inverse_1:
fixes f::"'a \<Rightarrow> 'b::{field,t2_space}"
assumes "(f \<longlongrightarrow> c) F" "c\<noteq>0"
shows "\<forall>\<^sub>F x in F. inverse (f x) * f x = 1"
proof -
have "\<forall>\<^sub>F x in F. f x\<noteq>0"
using assms tendsto_imp_eventually_ne by blast
then show ?thesis
apply (elim eventually_mono)
by auto
qed
subsection \<open>More about @{term filtermap}\<close>
lemma filtermap_linear_at_within:
assumes "bij f" and cont: "isCont f a" and open_map: "\<And>S. open S \<Longrightarrow> open (f`S)"
shows "filtermap f (at a within S) = at (f a) within f`S"
unfolding filter_eq_iff
proof safe
fix P
assume "eventually P (filtermap f (at a within S))"
then obtain T where "open T" "a \<in> T" and impP:"\<forall>x\<in>T. x\<noteq>a \<longrightarrow> x\<in>S\<longrightarrow> P (f x)"
by (auto simp: eventually_filtermap eventually_at_topological)
then show "eventually P (at (f a) within f ` S)"
unfolding eventually_at_topological
apply (intro exI[of _ "f`T"])
using \<open>bij f\<close> open_map by (metis bij_pointE imageE imageI)
next
fix P
assume "eventually P (at (f a) within f ` S)"
then obtain T1 where "open T1" "f a \<in> T1" and impP:"\<forall>x\<in>T1. x\<noteq>f a \<longrightarrow> x\<in>f`S\<longrightarrow> P (x)"
unfolding eventually_at_topological by auto
then obtain T2 where "open T2" "a \<in> T2" "(\<forall>x'\<in>T2. f x' \<in> T1)"
using cont[unfolded continuous_at_open,rule_format,of T1] by blast
then have "\<forall>x\<in>T2. x\<noteq>a \<longrightarrow> x\<in>S\<longrightarrow> P (f x)"
using impP by (metis assms(1) bij_pointE imageI)
then show "eventually P (filtermap f (at a within S))"
unfolding eventually_filtermap eventually_at_topological
apply (intro exI[of _ T2])
using \<open>open T2\<close> \<open>a \<in> T2\<close> by auto
qed
lemma filtermap_at_bot_linear_eq:
fixes c::"'a::linordered_field"
assumes "c\<noteq>0"
shows "filtermap (\<lambda>x. x * c + b) at_bot = (if c>0 then at_bot else at_top)"
proof (cases "c>0")
case True
then have "filtermap (\<lambda>x. x * c + b) at_bot = at_bot"
apply (intro filtermap_fun_inverse[of "\<lambda>x. (x-b) / c"])
subgoal unfolding eventually_at_bot_linorder filterlim_at_bot
by (auto simp add: field_simps)
subgoal unfolding eventually_at_bot_linorder filterlim_at_bot
by (metis mult.commute real_affinity_le)
by auto
then show ?thesis using \<open>c>0\<close> by auto
next
case False
then have "c<0" using \<open>c\<noteq>0\<close> by auto
then have "filtermap (\<lambda>x. x * c + b) at_bot = at_top"
apply (intro filtermap_fun_inverse[of "\<lambda>x. (x-b) / c"])
subgoal unfolding eventually_at_top_linorder filterlim_at_bot
by (meson le_diff_eq neg_divide_le_eq)
subgoal unfolding eventually_at_bot_linorder filterlim_at_top
using \<open>c < 0\<close> by (meson False diff_le_eq le_divide_eq)
by auto
then show ?thesis using \<open>c<0\<close> by auto
qed
lemma filtermap_linear_at_left:
fixes c::"'a::{linordered_field,linorder_topology,real_normed_field}"
assumes "c\<noteq>0"
shows "filtermap (\<lambda>x. c*x+b) (at_left x) = (if c>0 then at_left (c*x+b) else at_right (c*x+b))"
proof -
let ?f = "\<lambda>x. c*x+b"
have "filtermap (\<lambda>x. c*x+b) (at_left x) = (at (?f x) within ?f ` {..<x})"
proof (subst filtermap_linear_at_within)
show "bij ?f" using \<open>c\<noteq>0\<close>
by (auto intro!: o_bij[of "\<lambda>x. (x-b)/c"])
show "isCont ?f x" by auto
show "\<And>S. open S \<Longrightarrow> open (?f ` S)"
using open_times_image[OF _ \<open>c\<noteq>0\<close>,THEN open_translation,of _ b]
by (simp add:image_image add.commute)
show "at (?f x) within ?f ` {..<x} = at (?f x) within ?f ` {..<x}" by simp
qed
moreover have "?f ` {..<x} = {..<?f x}" when "c>0"
using image_linear_lessThan[OF \<open>c\<noteq>0\<close>,of b x] that by auto
moreover have "?f ` {..<x} = {?f x<..}" when "\<not> c>0"
using image_linear_lessThan[OF \<open>c\<noteq>0\<close>,of b x] that by auto
ultimately show ?thesis by auto
qed
lemma filtermap_linear_at_right:
fixes c::"'a::{linordered_field,linorder_topology,real_normed_field}"
assumes "c\<noteq>0"
shows "filtermap (\<lambda>x. c*x+b) (at_right x) = (if c>0 then at_right (c*x+b) else at_left (c*x+b))"
proof -
let ?f = "\<lambda>x. c*x+b"
have "filtermap ?f (at_right x) = (at (?f x) within ?f ` {x<..})"
proof (subst filtermap_linear_at_within)
show "bij ?f" using \<open>c\<noteq>0\<close>
by (auto intro!: o_bij[of "\<lambda>x. (x-b)/c"])
show "isCont ?f x" by auto
show "\<And>S. open S \<Longrightarrow> open (?f ` S)"
using open_times_image[OF _ \<open>c\<noteq>0\<close>,THEN open_translation,of _ b]
by (simp add:image_image add.commute)
show "at (?f x) within ?f ` {x<..} = at (?f x) within ?f ` {x<..}" by simp
qed
moreover have "?f ` {x<..} = {?f x<..}" when "c>0"
using image_linear_greaterThan[OF \<open>c\<noteq>0\<close>,of b x] that by auto
moreover have "?f ` {x<..} = {..<?f x}" when "\<not> c>0"
using image_linear_greaterThan[OF \<open>c\<noteq>0\<close>,of b x] that by auto
ultimately show ?thesis by auto
qed
lemma filtermap_at_top_linear_eq:
fixes c::"'a::linordered_field"
assumes "c\<noteq>0"
shows "filtermap (\<lambda>x. x * c + b) at_top = (if c>0 then at_top else at_bot)"
proof (cases "c>0")
case True
then have "filtermap (\<lambda>x. x * c + b) at_top = at_top"
apply (intro filtermap_fun_inverse[of "\<lambda>x. (x-b) / c"])
subgoal unfolding eventually_at_top_linorder filterlim_at_top
by (meson le_diff_eq pos_le_divide_eq)
subgoal unfolding eventually_at_top_linorder filterlim_at_top
apply auto
by (metis mult.commute real_le_affinity)
by auto
then show ?thesis using \<open>c>0\<close> by auto
next
case False
then have "c<0" using \<open>c\<noteq>0\<close> by auto
then have "filtermap (\<lambda>x. x * c + b) at_top = at_bot"
apply (intro filtermap_fun_inverse[of "\<lambda>x. (x-b) / c"])
subgoal unfolding eventually_at_bot_linorder filterlim_at_top
by (auto simp add: field_simps)
subgoal unfolding eventually_at_top_linorder filterlim_at_bot
by (meson le_diff_eq neg_divide_le_eq)
by auto
then show ?thesis using \<open>c<0\<close> by auto
qed
lemma filtermap_nhds_open_map:
assumes cont: "isCont f a"
and open_map: "\<And>S. open S \<Longrightarrow> open (f`S)"
shows "filtermap f (nhds a) = nhds (f a)"
unfolding filter_eq_iff
proof safe
fix P
assume "eventually P (filtermap f (nhds a))"
then obtain S where "open S" "a \<in> S" "\<forall>x\<in>S. P (f x)"
by (auto simp: eventually_filtermap eventually_nhds)
then show "eventually P (nhds (f a))"
unfolding eventually_nhds
apply (intro exI[of _ "f`S"])
by (auto intro!: open_map)
qed (metis filterlim_iff tendsto_at_iff_tendsto_nhds isCont_def eventually_filtermap cont)
subsection \<open>More about @{term filterlim}\<close>
lemma filterlim_at_infinity_times:
fixes f :: "'a \<Rightarrow> 'b::real_normed_field"
assumes "filterlim f at_infinity F" "filterlim g at_infinity F"
shows "filterlim (\<lambda>x. f x * g x) at_infinity F"
proof -
have "((\<lambda>x. inverse (f x) * inverse (g x)) \<longlongrightarrow> 0 * 0) F"
by (intro tendsto_mult tendsto_inverse assms filterlim_compose[OF tendsto_inverse_0])
then have "filterlim (\<lambda>x. inverse (f x) * inverse (g x)) (at 0) F"
unfolding filterlim_at using assms
by (auto intro: filterlim_at_infinity_imp_eventually_ne tendsto_imp_eventually_ne eventually_conj)
then show ?thesis
by (subst filterlim_inverse_at_iff[symmetric]) simp_all
qed
lemma filterlim_at_top_at_bot[elim]:
fixes f::"'a \<Rightarrow> 'b::unbounded_dense_linorder" and F::"'a filter"
assumes top:"filterlim f at_top F" and bot: "filterlim f at_bot F" and "F\<noteq>bot"
shows False
proof -
obtain c::'b where True by auto
have "\<forall>\<^sub>F x in F. c < f x"
using top unfolding filterlim_at_top_dense by auto
moreover have "\<forall>\<^sub>F x in F. f x < c"
using bot unfolding filterlim_at_bot_dense by auto
ultimately have "\<forall>\<^sub>F x in F. c < f x \<and> f x < c"
using eventually_conj by auto
then have "\<forall>\<^sub>F x in F. False" by (auto elim:eventually_mono)
then show False using \<open>F\<noteq>bot\<close> by auto
qed
lemma filterlim_at_top_nhds[elim]:
fixes f::"'a \<Rightarrow> 'b::{unbounded_dense_linorder,order_topology}" and F::"'a filter"
assumes top:"filterlim f at_top F" and tendsto: "(f \<longlongrightarrow> c) F" and "F\<noteq>bot"
shows False
proof -
obtain c'::'b where "c'>c" using gt_ex by blast
have "\<forall>\<^sub>F x in F. c' < f x"
using top unfolding filterlim_at_top_dense by auto
moreover have "\<forall>\<^sub>F x in F. f x < c'"
using order_tendstoD[OF tendsto,of c'] \<open>c'>c\<close> by auto
ultimately have "\<forall>\<^sub>F x in F. c' < f x \<and> f x < c'"
using eventually_conj by auto
then have "\<forall>\<^sub>F x in F. False" by (auto elim:eventually_mono)
then show False using \<open>F\<noteq>bot\<close> by auto
qed
lemma filterlim_at_bot_nhds[elim]:
fixes f::"'a \<Rightarrow> 'b::{unbounded_dense_linorder,order_topology}" and F::"'a filter"
assumes top:"filterlim f at_bot F" and tendsto: "(f \<longlongrightarrow> c) F" and "F\<noteq>bot"
shows False
proof -
obtain c'::'b where "c'<c" using lt_ex by blast
have "\<forall>\<^sub>F x in F. c' > f x"
using top unfolding filterlim_at_bot_dense by auto
moreover have "\<forall>\<^sub>F x in F. f x > c'"
using order_tendstoD[OF tendsto,of c'] \<open>c'<c\<close> by auto
ultimately have "\<forall>\<^sub>F x in F. c' < f x \<and> f x < c'"
using eventually_conj by auto
then have "\<forall>\<^sub>F x in F. False" by (auto elim:eventually_mono)
then show False using \<open>F\<noteq>bot\<close> by auto
qed
lemma filterlim_at_top_linear_iff:
fixes f::"'a::linordered_field \<Rightarrow> 'b"
assumes "c\<noteq>0"
shows "(LIM x at_top. f (x * c + b) :> F2) \<longleftrightarrow> (if c>0 then (LIM x at_top. f x :> F2)
else (LIM x at_bot. f x :> F2))"
unfolding filterlim_def
apply (subst filtermap_filtermap[of f "\<lambda>x. x * c + b",symmetric])
using assms by (auto simp add:filtermap_at_top_linear_eq)
lemma filterlim_at_bot_linear_iff:
fixes f::"'a::linordered_field \<Rightarrow> 'b"
assumes "c\<noteq>0"
shows "(LIM x at_bot. f (x * c + b) :> F2) \<longleftrightarrow> (if c>0 then (LIM x at_bot. f x :> F2)
else (LIM x at_top. f x :> F2)) "
unfolding filterlim_def
apply (subst filtermap_filtermap[of f "\<lambda>x. x * c + b",symmetric])
using assms by (auto simp add:filtermap_at_bot_linear_eq)
lemma filterlim_tendsto_add_at_top_iff:
assumes f: "(f \<longlongrightarrow> c) F"
shows "(LIM x F. (f x + g x :: real) :> at_top) \<longleftrightarrow> (LIM x F. g x :> at_top)"
proof
assume "LIM x F. f x + g x :> at_top"
moreover have "((\<lambda>x. - f x) \<longlongrightarrow> - c) F"
using f by (intro tendsto_intros,simp)
ultimately show "filterlim g at_top F" using filterlim_tendsto_add_at_top
by fastforce
qed (auto simp add:filterlim_tendsto_add_at_top[OF f])
lemma filterlim_tendsto_add_at_bot_iff:
fixes c::real
assumes f: "(f \<longlongrightarrow> c) F"
shows "(LIM x F. f x + g x :> at_bot) \<longleftrightarrow> (LIM x F. g x :> at_bot)"
proof -
have "(LIM x F. f x + g x :> at_bot)
\<longleftrightarrow> (LIM x F. - f x + (- g x) :> at_top)"
apply (subst filterlim_uminus_at_top)
by (rule filterlim_cong,auto)
also have "... = (LIM x F. - g x :> at_top)"
apply (subst filterlim_tendsto_add_at_top_iff[of _ "-c"])
by (auto intro:tendsto_intros simp add:f)
also have "... = (LIM x F. g x :> at_bot)"
apply (subst filterlim_uminus_at_top)
by (rule filterlim_cong,auto)
finally show ?thesis .
qed
lemma tendsto_inverse_0_at_infinity:
"LIM x F. f x :> at_infinity \<Longrightarrow> ((\<lambda>x. inverse (f x) :: real) \<longlongrightarrow> 0) F"
by (metis filterlim_at filterlim_inverse_at_iff)
lemma filterlim_at_infinity_divide_iff:
fixes f::"'a \<Rightarrow> 'b::real_normed_field"
assumes "(f \<longlongrightarrow> c) F" "c\<noteq>0"
shows "(LIM x F. f x / g x :> at_infinity) \<longleftrightarrow> (LIM x F. g x :> at 0)"
proof
assume asm:"LIM x F. f x / g x :> at_infinity"
have "LIM x F. inverse (f x) * (f x / g x) :> at_infinity"
apply (rule tendsto_mult_filterlim_at_infinity[of _ "inverse c", OF _ _ asm])
by (auto simp add: assms(1) assms(2) tendsto_inverse)
then have "LIM x F. inverse (g x) :> at_infinity"
apply (elim filterlim_mono_eventually)
using eventually_times_inverse_1[OF assms]
by (auto elim:eventually_mono simp add:field_simps)
then show "filterlim g (at 0) F" using filterlim_inverse_at_iff[symmetric] by force
next
assume "filterlim g (at 0) F"
then have "filterlim (\<lambda>x. inverse (g x)) at_infinity F"
using filterlim_compose filterlim_inverse_at_infinity by blast
then have "LIM x F. f x * inverse (g x) :> at_infinity"
using tendsto_mult_filterlim_at_infinity[OF assms, of "\<lambda>x. inverse(g x)"]
by simp
then show "LIM x F. f x / g x :> at_infinity" by (simp add: divide_inverse)
qed
lemma filterlim_tendsto_pos_mult_at_top_iff:
fixes f::"'a \<Rightarrow> real"
assumes "(f \<longlongrightarrow> c) F" and "0 < c"
shows "(LIM x F. (f x * g x) :> at_top) \<longleftrightarrow> (LIM x F. g x :> at_top)"
proof
assume "filterlim g at_top F"
then show "LIM x F. f x * g x :> at_top"
using filterlim_tendsto_pos_mult_at_top[OF assms] by auto
next
assume asm:"LIM x F. f x * g x :> at_top"
have "((\<lambda>x. inverse (f x)) \<longlongrightarrow> inverse c) F"
using tendsto_inverse[OF assms(1)] \<open>0<c\<close> by auto
moreover have "inverse c >0" using assms(2) by auto
ultimately have "LIM x F. inverse (f x) * (f x * g x) :> at_top"
using filterlim_tendsto_pos_mult_at_top[OF _ _ asm,of "\<lambda>x. inverse (f x)" "inverse c"] by auto
then show "LIM x F. g x :> at_top"
apply (elim filterlim_mono_eventually)
apply simp_all[2]
using eventually_times_inverse_1[OF assms(1)] \<open>c>0\<close> eventually_mono by fastforce
qed
lemma filterlim_tendsto_pos_mult_at_bot_iff:
fixes c :: real
assumes "(f \<longlongrightarrow> c) F" "0 < c"
shows "(LIM x F. f x * g x :> at_bot) \<longleftrightarrow> filterlim g at_bot F"
using filterlim_tendsto_pos_mult_at_top_iff[OF assms(1,2), of "\<lambda>x. - g x"]
unfolding filterlim_uminus_at_bot by simp
lemma filterlim_tendsto_neg_mult_at_top_iff:
fixes f::"'a \<Rightarrow> real"
assumes "(f \<longlongrightarrow> c) F" and "c < 0"
shows "(LIM x F. (f x * g x) :> at_top) \<longleftrightarrow> (LIM x F. g x :> at_bot)"
proof -
have "(LIM x F. f x * g x :> at_top) = (LIM x F. - g x :> at_top)"
apply (rule filterlim_tendsto_pos_mult_at_top_iff[of "\<lambda>x. - f x" "-c" F "\<lambda>x. - g x", simplified])
using assms by (auto intro: tendsto_intros )
also have "... = (LIM x F. g x :> at_bot)"
using filterlim_uminus_at_bot[symmetric] by auto
finally show ?thesis .
qed
lemma filterlim_tendsto_neg_mult_at_bot_iff:
fixes c :: real
assumes "(f \<longlongrightarrow> c) F" "0 > c"
shows "(LIM x F. f x * g x :> at_bot) \<longleftrightarrow> filterlim g at_top F"
using filterlim_tendsto_neg_mult_at_top_iff[OF assms(1,2), of "\<lambda>x. - g x"]
unfolding filterlim_uminus_at_top by simp
lemma Lim_add:
fixes f g::"_ \<Rightarrow> 'a::{t2_space,topological_monoid_add}"
assumes "\<exists>y. (f \<longlongrightarrow> y) F" and "\<exists>y. (g \<longlongrightarrow> y) F" and "F\<noteq>bot"
shows "Lim F f + Lim F g = Lim F (\<lambda>x. f x+g x)"
apply (rule tendsto_Lim[OF \<open>F\<noteq>bot\<close>, symmetric])
apply (auto intro!:tendsto_eq_intros)
using assms tendsto_Lim by blast+
(*
lemma filterlim_at_top_tendsto[elim]:
fixes f::"'a \<Rightarrow> 'b::{unbounded_dense_linorder,order_topology}" and F::"'a filter"
assumes top:"filterlim f at_top F" and tendsto: "(f \<longlongrightarrow> c) F"
and "F\<noteq>bot"
shows False
proof -
obtain cc where "cc>c" using gt_ex by blast
have "\<forall>\<^sub>F x in F. cc < f x"
using top unfolding filterlim_at_top_dense by auto
moreover have "\<forall>\<^sub>F x in F. f x < cc"
using tendsto order_tendstoD(2)[OF _ \<open>cc>c\<close>] by auto
ultimately have "\<forall>\<^sub>F x in F. cc < f x \<and> f x < cc"
using eventually_conj by auto
then have "\<forall>\<^sub>F x in F. False" by (auto elim:eventually_mono)
then show False using \<open>F\<noteq>bot\<close> by auto
qed
lemma filterlim_at_bot_tendsto[elim]:
fixes f::"'a \<Rightarrow> 'b::{unbounded_dense_linorder,order_topology}" and F::"'a filter"
assumes top:"filterlim f at_bot F" and tendsto: "(f \<longlongrightarrow> c) F"
and "F\<noteq>bot"
shows False
proof -
obtain cc where "cc<c" using lt_ex by blast
have "\<forall>\<^sub>F x in F. cc > f x"
using top unfolding filterlim_at_bot_dense by auto
moreover have "\<forall>\<^sub>F x in F. f x > cc"
using tendsto order_tendstoD(1)[OF _ \<open>cc<c\<close>] by auto
ultimately have "\<forall>\<^sub>F x in F. cc < f x \<and> f x < cc"
using eventually_conj by auto
then have "\<forall>\<^sub>F x in F. False" by (auto elim:eventually_mono)
then show False using \<open>F\<noteq>bot\<close> by auto
qed
*)
subsection \<open>Isolate and discrete\<close>
definition (in topological_space) isolate:: "'a \<Rightarrow> 'a set \<Rightarrow> bool" (infixr "isolate" 60)
where "x isolate S \<longleftrightarrow> (x\<in>S \<and> (\<exists>T. open T \<and> T \<inter> S = {x}))"
definition (in topological_space) discrete:: "'a set \<Rightarrow> bool"
where "discrete S \<longleftrightarrow> (\<forall>x\<in>S. x isolate S)"
definition (in metric_space) uniform_discrete :: "'a set \<Rightarrow> bool" where
"uniform_discrete S \<longleftrightarrow> (\<exists>e>0. \<forall>x\<in>S. \<forall>y\<in>S. dist x y < e \<longrightarrow> x = y)"
lemma uniformI1:
assumes "e>0" "\<And>x y. \<lbrakk>x\<in>S;y\<in>S;dist x y<e\<rbrakk> \<Longrightarrow> x =y "
shows "uniform_discrete S"
unfolding uniform_discrete_def using assms by auto
lemma uniformI2:
assumes "e>0" "\<And>x y. \<lbrakk>x\<in>S;y\<in>S;x\<noteq>y\<rbrakk> \<Longrightarrow> dist x y\<ge>e "
shows "uniform_discrete S"
unfolding uniform_discrete_def using assms not_less by blast
lemma isolate_islimpt_iff:"(x isolate S) \<longleftrightarrow> (\<not> (x islimpt S) \<and> x\<in>S)"
unfolding isolate_def islimpt_def by auto
lemma isolate_dist_Ex_iff:
fixes x::"'a::metric_space"
shows "x isolate S \<longleftrightarrow> (x\<in>S \<and> (\<exists>e>0. \<forall>y\<in>S. dist x y < e \<longrightarrow> y=x))"
unfolding isolate_islimpt_iff islimpt_approachable by (metis dist_commute)
lemma discrete_empty[simp]: "discrete {}"
unfolding discrete_def by auto
lemma uniform_discrete_empty[simp]: "uniform_discrete {}"
unfolding uniform_discrete_def by (simp add: gt_ex)
lemma isolate_insert:
fixes x :: "'a::t1_space"
shows "x isolate (insert a S) \<longleftrightarrow> x isolate S \<or> (x=a \<and> \<not> (x islimpt S))"
by (meson insert_iff islimpt_insert isolate_islimpt_iff)
(*
TODO.
Other than
uniform_discrete S \<longrightarrow> discrete S
uniform_discrete S \<longrightarrow> closed S
, we should be able to prove
discrete S \<and> closed S \<longrightarrow> uniform_discrete S
but the proof (based on Tietze Extension Theorem) seems not very trivial to me. Informal proofs can be found in
http://topology.auburn.edu/tp/reprints/v30/tp30120.pdf
http://msp.org/pjm/1959/9-2/pjm-v9-n2-p19-s.pdf
*)
lemma uniform_discrete_imp_closed:
"uniform_discrete S \<Longrightarrow> closed S"
by (meson discrete_imp_closed uniform_discrete_def)
lemma uniform_discrete_imp_discrete:
"uniform_discrete S \<Longrightarrow> discrete S"
by (metis discrete_def isolate_dist_Ex_iff uniform_discrete_def)
lemma isolate_subset:"x isolate S \<Longrightarrow> T \<subseteq> S \<Longrightarrow> x\<in>T \<Longrightarrow> x isolate T"
unfolding isolate_def by fastforce
lemma discrete_subset[elim]: "discrete S \<Longrightarrow> T \<subseteq> S \<Longrightarrow> discrete T"
unfolding discrete_def using islimpt_subset isolate_islimpt_iff by blast
lemma uniform_discrete_subset[elim]: "uniform_discrete S \<Longrightarrow> T \<subseteq> S \<Longrightarrow> uniform_discrete T"
by (meson subsetD uniform_discrete_def)
lemma continuous_on_discrete: "discrete S \<Longrightarrow> continuous_on S f"
unfolding continuous_on_topological by (metis discrete_def islimptI isolate_islimpt_iff)
(* Is euclidean_space really necessary?*)
lemma uniform_discrete_insert:
fixes S :: "'a::euclidean_space set"
shows "uniform_discrete (insert a S) \<longleftrightarrow> uniform_discrete S"
proof
assume asm:"uniform_discrete S"
let ?thesis = "uniform_discrete (insert a S)"
have ?thesis when "a\<in>S" using that asm by (simp add: insert_absorb)
moreover have ?thesis when "S={}" using that asm by (simp add: uniform_discrete_def)
moreover have ?thesis when "a\<notin>S" "S\<noteq>{}"
proof -
obtain e1 where "e1>0" and e1_dist:"\<forall>x\<in>S. \<forall>y\<in>S. dist y x < e1 \<longrightarrow> y = x"
using asm unfolding uniform_discrete_def by auto
define e2 where "e2 \<equiv> min (setdist {a} S) e1"
have "closed S" using asm uniform_discrete_imp_closed by auto
then have "e2>0" by (simp add: \<open>0 < e1\<close> e2_def setdist_gt_0_compact_closed that(1) that(2))
moreover have "x = y" when "x\<in>insert a S" "y\<in>insert a S" "dist x y < e2 " for x y
proof -
have ?thesis when "x=a" "y=a" using that by auto
moreover have ?thesis when "x=a" "y\<in>S"
using that setdist_le_dist[of x "{a}" y S] \<open>dist x y < e2\<close> unfolding e2_def
by fastforce
moreover have ?thesis when "y=a" "x\<in>S"
using that setdist_le_dist[of y "{a}" x S] \<open>dist x y < e2\<close> unfolding e2_def
by (simp add: dist_commute)
moreover have ?thesis when "x\<in>S" "y\<in>S"
using e1_dist[rule_format, OF that] \<open>dist x y < e2\<close> unfolding e2_def
by (simp add: dist_commute)
ultimately show ?thesis using that by auto
qed
ultimately show ?thesis unfolding uniform_discrete_def by meson
qed
ultimately show ?thesis by auto
qed (simp add: subset_insertI uniform_discrete_subset)
lemma discrete_compact_finite_iff:
fixes S :: "'a::t1_space set"
shows "discrete S \<and> compact S \<longleftrightarrow> finite S"
proof
assume "finite S"
then have "compact S" using finite_imp_compact by auto
moreover have "discrete S"
unfolding discrete_def using isolate_islimpt_iff islimpt_finite[OF \<open>finite S\<close>] by auto
ultimately show "discrete S \<and> compact S" by auto
next
assume "discrete S \<and> compact S"
then show "finite S"
by (meson discrete_def Heine_Borel_imp_Bolzano_Weierstrass isolate_islimpt_iff order_refl)
qed
lemma uniform_discrete_finite_iff:
fixes S :: "'a::heine_borel set"
shows "uniform_discrete S \<and> bounded S \<longleftrightarrow> finite S"
proof
assume "uniform_discrete S \<and> bounded S"
then have "discrete S" "compact S"
using uniform_discrete_imp_discrete uniform_discrete_imp_closed compact_eq_bounded_closed
by auto
then show "finite S" using discrete_compact_finite_iff by auto
next
assume asm:"finite S"
let ?thesis = "uniform_discrete S \<and> bounded S"
have ?thesis when "S={}" using that by auto
moreover have ?thesis when "S\<noteq>{}"
proof -
have "\<forall>x. \<exists>d>0. \<forall>y\<in>S. y \<noteq> x \<longrightarrow> d \<le> dist x y"
using finite_set_avoid[OF \<open>finite S\<close>] by auto
then obtain f where f_pos:"f x>0"
and f_dist: "\<forall>y\<in>S. y \<noteq> x \<longrightarrow> f x \<le> dist x y"
if "x\<in>S" for x
by metis
define f_min where "f_min \<equiv> Min (f ` S)"
have "f_min > 0"
unfolding f_min_def
by (simp add: asm f_pos that)
moreover have "\<forall>x\<in>S. \<forall>y\<in>S. f_min > dist x y \<longrightarrow> x=y"
using f_dist unfolding f_min_def
by (metis Min_gr_iff all_not_in_conv asm dual_order.irrefl eq_iff finite_imageI imageI
less_eq_real_def)
ultimately have "uniform_discrete S"
unfolding uniform_discrete_def by auto
moreover have "bounded S" using \<open>finite S\<close> by auto
ultimately show ?thesis by auto
qed
ultimately show ?thesis by blast
qed
lemma uniform_discrete_image_scale:
fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space"
assumes "uniform_discrete S" and dist:"\<forall>x\<in>S. \<forall>y\<in>S. dist x y = c * dist (f x) (f y)"
shows "uniform_discrete (f ` S)"
proof -
have ?thesis when "S={}" using that by auto
moreover have ?thesis when "S\<noteq>{}" "c\<le>0"
proof -
obtain x1 where "x1\<in>S" using \<open>S\<noteq>{}\<close> by auto
have ?thesis when "S-{x1} = {}"
proof -
have "S={x1}" using that \<open>S\<noteq>{}\<close> by auto
then show ?thesis using uniform_discrete_insert[of "f x1"] by auto
qed
moreover have ?thesis when "S-{x1} \<noteq> {}"
proof -
obtain x2 where "x2\<in>S-{x1}" using \<open>S-{x1} \<noteq> {}\<close> by auto
then have "x2\<in>S" "x1\<noteq>x2" by auto
then have "dist x1 x2 > 0" by auto
moreover have "dist x1 x2 = c * dist (f x1) (f x2)"
using dist[rule_format, OF \<open>x1\<in>S\<close> \<open>x2\<in>S\<close>] .
moreover have "dist (f x2) (f x2) \<ge> 0" by auto
ultimately have False using \<open>c\<le>0\<close> by (simp add: zero_less_mult_iff)
then show ?thesis by auto
qed
ultimately show ?thesis by auto
qed
moreover have ?thesis when "S\<noteq>{}" "c>0"
proof -
obtain e1 where "e1>0" and e1_dist:"\<forall>x\<in>S. \<forall>y\<in>S. dist y x < e1 \<longrightarrow> y = x"
using \<open>uniform_discrete S\<close> unfolding uniform_discrete_def by auto
define e where "e= e1/c"
have "x1 = x2" when "x1\<in> f ` S" "x2\<in> f ` S" "dist x1 x2 < e " for x1 x2
proof -
obtain y1 where y1:"y1\<in>S" "x1=f y1" using \<open>x1\<in> f ` S\<close> by auto
obtain y2 where y2:"y2\<in>S" "x2=f y2" using \<open>x2\<in> f ` S\<close> by auto
have "dist y1 y2 < e1"
using dist[rule_format, OF y1(1) y2(1)] \<open>c>0\<close> \<open>dist x1 x2 < e\<close> unfolding e_def
apply (fold y1(2) y2(2))
by (auto simp add:divide_simps mult.commute)
then have "y1=y2"
using e1_dist[rule_format, OF y2(1) y1(1)] by simp
then show "x1=x2" using y1(2) y2(2) by auto
qed
moreover have "e>0" using \<open>e1>0\<close> \<open>c>0\<close> unfolding e_def by auto
ultimately show ?thesis unfolding uniform_discrete_def by meson
qed
ultimately show ?thesis by fastforce
qed
end
|
import StatsBase: RealVector, RealMatrix
using KernelEstimator, Optim
import KernelEstimator.lcv, KernelEstimator.bwlcv, KernelEstimator.midrange
function dirichletkernel_oneval(x::RealVector, xdata::RealVector, λ::Real; log = false)
if(log)
logpdf(Dirichlet(1 .+ xdata/λ), x)
else
pdf(Dirichlet(1 .+ xdata/λ), x)
end
end
function dirichletkernel(x::RealVector, xdata::RealMatrix, λ::Real, w::Vector, n::Int; log = false)
# w .= mapslices(xdatavec -> dirichletkernel_oneval(x, xdatavec, λ), xdata, 2) |> vec
for i in eachindex(w)
w[i] = dirichletkernel_oneval(x, xdata[i,:], λ; log = log)
end
nothing
end
function dirichletkernel(x::RealVector, xdata::Array{Array{Float64,1},1}, λ::Real, w::Vector, n::Int; log = false)
# w .= mapslices(xdatavec -> dirichletkernel_oneval(x, xdatavec, λ), xdata, 2) |> vec
for i in eachindex(w)
w[i] = dirichletkernel_oneval(x, xdata[i], λ; log = log)
end
nothing
end
function midrange(x::RealMatrix)
mapslices(xvec -> quantile(xvec, [.25, .75]), x, dims = 1) |> x -> x[2,:] - x[1,:] |> maximum
# lq, uq = quantile(x, [.25, .75])
# uq - lq
end
# midrange(x::Array{Array{Float64,1},1}) = midrange.(x) |> maximum
# midrange(x::Array{Array{Int64,1},1}) = midrange.(x) |> maximum
ff(x)::Float64 = max(midrange([xi[1] for xi in x]), midrange([xi[2] for xi in x]), midrange([xi[3] for xi in x]))
midrange(x::Array{Array{Float64,1},1})::Float64 = ff(x)
midrange(x::Array{Array{Int64,1},1})::Float64 = ff(x)
function lcv(xdata::RealMatrix, kernel::Function, h::Real, w::Vector, n::Int)
# -mean(kerneldensity(xdata,xdata,kernel,h)) + mean(map(kernel, xdata, xdata, h))
ind = 1
ind_end = 1+n
ll = 0.0
@inbounds while ind < ind_end
# kernel(xdata[ind,:], xdata, h, w, n)
kernel(view(xdata, ind, :), xdata, h, w, n)
w[ind] = 0.0
ll += log(mean(w))
ind += 1
end
-ll
end
function lcv(xdata::Array{Array{Float64,1},1}, kernel::Function, h::Real, w::Vector, n::Int)
# -mean(kerneldensity(xdata,xdata,kernel,h)) + mean(map(kernel, xdata, xdata, h))
ind = 1
ind_end = 1+n
ll = 0.0
@inbounds while ind < ind_end
kernel(xdata[ind], xdata, h, w, n)
w[ind] = 0.0
ll += log(mean(w))
ind += 1
end
-ll
end
function bwlcv(xdata::RealMatrix, kernel::Function)
#This function seems to hit against the higher bound
n = size(xdata,1)
w = zeros(n)
h0=midrange(xdata)
if h0==0 #Algorithm returns 0 when h0=0. This happens when there are many ties, mixdrange can return 0
h0 = median(xdata)
end
hlb = h0/n^2
hub = h0
if kernel==betakernel
hub = 0.25
end
return Optim.minimizer(Optim.optimize(h->lcv(xdata,kernel,h,w,n), hlb, hub, iterations=200,abs_tol=h0/n^2))
end
function bwlcv(xdata::Array{Array{Float64,1},1}, kernel::Function)
n = length(xdata)
w = zeros(n)
h0=midrange(xdata)
if h0==0 #Algorithm returns 0 when h0=0. This happens when there are many ties, mixdrange can return 0
h0 = median(xdata |> Base.Iterators.flatten)
end
hlb = h0/n^2
hub = h0
if kernel==betakernel
hub = 0.25
end
return Optim.minimizer(Optim.optimize(h->lcv(xdata,kernel,h,w,n), hlb, hub, iterations=200,abs_tol=h0/n^2))
end
function bwlcv_large_bounds(xdata::RealMatrix, kernel::Function)
n = size(xdata,1)
w = zeros(n)
h0=midrange(xdata)
if h0==0 #Algorithm returns 0 when h0=0. This happens when there are many ties, mixdrange can return 0
h0 = median(xdata)
end
hlb = h0/n^2
hub = h0*10
if kernel==betakernel
hub = 0.25
end
res = Optim.minimizer(Optim.optimize(h->lcv(xdata,kernel,h,w,n), hlb, hub, iterations=200,abs_tol=h0/n^2))
i = 1
while (res==hub)&(i<10)
res = Optim.minimizer(Optim.optimize(h->lcv(xdata,kernel,h,w,n), hlb, 10*i*hub, iterations=200,abs_tol=h0/n^2))
i = i+1
end
return res
end
function minus_log_leaveoneout(xdata::RealMatrix, kernel::Function, h::Real, w::Vector, n::Int)
ll = 0.0
@inbounds for ind in 1:n
kernel(view(xdata, ind, :), xdata, h, w, n; log = false)
w[ind] = 0.0
ll += log(sum(w))
end
- ll + log(n-1)
end
function bwloo_large_bounds(xdata::RealMatrix, kernel::Function)
n = size(xdata,1)
w = zeros(n)
h0=midrange(xdata)
if h0==0 #Algorithm returns 0 when h0=0. This happens when there are many ties, mixdrange can return 0
h0 = median(xdata)
end
hlb = h0/n^2
hub = h0#*10
if kernel==betakernel
hub = 0.25
end
# println(hlb)
# println(hub)
# res = Optim.minimizer(Optim.optimize(h->lcv(xdata,kernel,h,w,n), hlb, hub, iterations=200,abs_tol=h0/n^2))
res = Optim.minimizer(Optim.optimize(h->minus_log_leaveoneout(xdata,kernel,h,w,n), hlb, hub, iterations=200))
i = 1
while (isapprox(res,hub, atol = h0/n^2))&(i<10)
res = Optim.minimizer(Optim.optimize(h->minus_log_leaveoneout(xdata,kernel,h,w,n), hlb, 10^i*hub, iterations=200,abs_tol=h0/n^2))
i = i+1
end
return res
end
|
import tactic data.finset
open_locale classical
namespace finset
variables {α : Type*} {β : Type*} [decidable_eq α]
def size{β : Type*} (X: finset β) := ((card X) : ℤ)
def subset_fintype{β: Type*} (hβ : fintype β) (X: finset β) := fintype
@[simp] lemma empt_size{β : Type*} : size (∅ : finset β) = 0 :=
begin
sorry,
end
@[simp] lemma partition_univ {β : Type*} [fintype β] (X: finset β) : X ∪ Xᶜ = univ :=
begin
apply subset.antisymm,
exact subset_univ _,
intros x hx,
simp only [mem_union],
by_cases x ∈ X,
left,
exact h,
right,
rw compl_eq_univ_sdiff,
apply mem_sdiff.mpr,
split,
exact hx,
exact h,
--yuck....
end
@[simp] lemma size_subtype{β : Type*} {Y: set β} {X : finset Y} : size (X.image subtype.val) = size X :=
begin
unfold size,
simp only [int.coe_nat_inj'],
apply card_image_of_injective,
exact subtype.val_injective
end
lemma union_subset_union_left{A B C : finset α} : (A ⊆ B) → ((A ∪ C) ⊆ (B ∪ C)) :=
begin
intros hAB,
intros x hx,
simp only [mem_union],
simp only [mem_union] at hx,
cases hx,
left,
exact hAB hx,
right,
exact hx,
end
@[simp] lemma union_unions{X Y A: finset α} :(X ∪ A) ∪ (Y ∪ A) = (X ∪ Y ∪ A) :=
begin
sorry,
end
@[simp] lemma inter_unions{X Y A: finset α} :(X ∪ A) ∩ (Y ∪ A) = (X ∩ Y) ∪ A :=
begin
sorry,
end
end finset |
/-
Copyright (c) 2019 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import algebra.group.type_tags
import algebra.hom.equiv.basic
import algebra.hom.ring
import algebra.hom.units
/-!
# Unbundled monoid and group homomorphisms
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file is deprecated, and is no longer imported by anything in mathlib other than other
deprecated files, and test files. You should not need to import it.
This file defines predicates for unbundled monoid and group homomorphisms. Instead of using
this file, please use `monoid_hom`, defined in `algebra.hom.group`, with notation `→*`, for
morphisms between monoids or groups. For example use `φ : G →* H` to represent a group
homomorphism between multiplicative groups, and `ψ : A →+ B` to represent a group homomorphism
between additive groups.
## Main Definitions
`is_monoid_hom` (deprecated), `is_group_hom` (deprecated)
## Tags
is_group_hom, is_monoid_hom
-/
universes u v
variables {α : Type u} {β : Type v}
/-- Predicate for maps which preserve an addition. -/
structure is_add_hom {α β : Type*} [has_add α] [has_add β] (f : α → β) : Prop :=
(map_add [] : ∀ x y, f (x + y) = f x + f y)
/-- Predicate for maps which preserve a multiplication. -/
@[to_additive]
structure is_mul_hom {α β : Type*} [has_mul α] [has_mul β] (f : α → β) : Prop :=
(map_mul [] : ∀ x y, f (x * y) = f x * f y)
namespace is_mul_hom
variables [has_mul α] [has_mul β] {γ : Type*} [has_mul γ]
/-- The identity map preserves multiplication. -/
@[to_additive "The identity map preserves addition"]
lemma id : is_mul_hom (id : α → α) := {map_mul := λ _ _, rfl}
/-- The composition of maps which preserve multiplication, also preserves multiplication. -/
@[to_additive "The composition of addition preserving maps also preserves addition"]
lemma comp {f : α → β} {g : β → γ} (hf : is_mul_hom f) (hg : is_mul_hom g) : is_mul_hom (g ∘ f) :=
{ map_mul := λ x y, by simp only [function.comp, hf.map_mul, hg.map_mul] }
/-- A product of maps which preserve multiplication,
preserves multiplication when the target is commutative. -/
@[to_additive "A sum of maps which preserves addition, preserves addition when the target
is commutative."]
lemma mul {α β} [semigroup α] [comm_semigroup β]
{f g : α → β} (hf : is_mul_hom f) (hg : is_mul_hom g) :
is_mul_hom (λ a, f a * g a) :=
{ map_mul := λ a b, by simp only [hf.map_mul, hg.map_mul, mul_comm, mul_assoc, mul_left_comm] }
/-- The inverse of a map which preserves multiplication,
preserves multiplication when the target is commutative. -/
@[to_additive "The negation of a map which preserves addition, preserves addition when
the target is commutative."]
lemma inv {α β} [has_mul α] [comm_group β] {f : α → β} (hf : is_mul_hom f) :
is_mul_hom (λ a, (f a)⁻¹) :=
{ map_mul := λ a b, (hf.map_mul a b).symm ▸ mul_inv _ _ }
end is_mul_hom
/-- Predicate for add_monoid homomorphisms (deprecated -- use the bundled `monoid_hom` version). -/
structure is_add_monoid_hom [add_zero_class α] [add_zero_class β] (f : α → β)
extends is_add_hom f : Prop :=
(map_zero [] : f 0 = 0)
/-- Predicate for monoid homomorphisms (deprecated -- use the bundled `monoid_hom` version). -/
@[to_additive]
structure is_monoid_hom [mul_one_class α] [mul_one_class β] (f : α → β)
extends is_mul_hom f : Prop :=
(map_one [] : f 1 = 1)
namespace monoid_hom
variables {M : Type*} {N : Type*} [mM : mul_one_class M] [mN : mul_one_class N]
include mM mN
/-- Interpret a map `f : M → N` as a homomorphism `M →* N`. -/
@[to_additive "Interpret a map `f : M → N` as a homomorphism `M →+ N`."]
def of {f : M → N} (h : is_monoid_hom f) : M →* N :=
{ to_fun := f,
map_one' := h.2,
map_mul' := h.1.1 }
variables {mM mN}
@[simp, to_additive]
lemma coe_of {f : M → N} (hf : is_monoid_hom f) : ⇑ (monoid_hom.of hf) = f :=
rfl
@[to_additive]
end monoid_hom
namespace mul_equiv
variables {M : Type*} {N : Type*} [mul_one_class M] [mul_one_class N]
/-- A multiplicative isomorphism preserves multiplication (deprecated). -/
@[to_additive "An additive isomorphism preserves addition (deprecated)."]
theorem is_mul_hom (h : M ≃* N) : is_mul_hom h := ⟨h.map_mul⟩
/-- A multiplicative bijection between two monoids is a monoid hom
(deprecated -- use `mul_equiv.to_monoid_hom`). -/
@[to_additive "An additive bijection between two additive monoids is an additive
monoid hom (deprecated). "]
lemma is_monoid_hom (h : M ≃* N) : is_monoid_hom h :=
{ map_mul := h.map_mul,
map_one := h.map_one }
end mul_equiv
namespace is_monoid_hom
variables [mul_one_class α] [mul_one_class β] {f : α → β} (hf : is_monoid_hom f)
/-- A monoid homomorphism preserves multiplication. -/
@[to_additive "An additive monoid homomorphism preserves addition."]
lemma map_mul (x y) : f (x * y) = f x * f y :=
hf.map_mul x y
/-- The inverse of a map which preserves multiplication,
preserves multiplication when the target is commutative. -/
@[to_additive "The negation of a map which preserves addition, preserves addition
when the target is commutative."]
lemma inv {α β} [mul_one_class α] [comm_group β] {f : α → β} (hf : is_monoid_hom f) :
is_monoid_hom (λ a, (f a)⁻¹) :=
{ map_one := hf.map_one.symm ▸ inv_one,
map_mul := λ a b, (hf.map_mul a b).symm ▸ mul_inv _ _ }
end is_monoid_hom
/-- A map to a group preserving multiplication is a monoid homomorphism. -/
@[to_additive "A map to an additive group preserving addition is an additive monoid
homomorphism."]
theorem is_mul_hom.to_is_monoid_hom [mul_one_class α] [group β] {f : α → β} (hf : is_mul_hom f) :
is_monoid_hom f :=
{ map_one := mul_right_eq_self.1 $ by rw [← hf.map_mul, one_mul],
map_mul := hf.map_mul }
namespace is_monoid_hom
variables [mul_one_class α] [mul_one_class β] {f : α → β}
/-- The identity map is a monoid homomorphism. -/
@[to_additive "The identity map is an additive monoid homomorphism."]
lemma id : is_monoid_hom (@id α) := { map_one := rfl, map_mul := λ _ _, rfl }
/-- The composite of two monoid homomorphisms is a monoid homomorphism. -/
@[to_additive "The composite of two additive monoid homomorphisms is an additive monoid
homomorphism."]
lemma comp (hf : is_monoid_hom f) {γ} [mul_one_class γ] {g : β → γ} (hg : is_monoid_hom g) :
is_monoid_hom (g ∘ f) :=
{ map_one := show g _ = 1, by rw [hf.map_one, hg.map_one],
..is_mul_hom.comp hf.to_is_mul_hom hg.to_is_mul_hom }
end is_monoid_hom
namespace is_add_monoid_hom
/-- Left multiplication in a ring is an additive monoid morphism. -/
lemma is_add_monoid_hom_mul_left {γ : Type*} [non_unital_non_assoc_semiring γ] (x : γ) :
is_add_monoid_hom (λ y : γ, x * y) :=
{ map_zero := mul_zero x, map_add := λ y z, mul_add x y z }
/-- Right multiplication in a ring is an additive monoid morphism. -/
lemma is_add_monoid_hom_mul_right {γ : Type*} [non_unital_non_assoc_semiring γ] (x : γ) :
is_add_monoid_hom (λ y : γ, y * x) :=
{ map_zero := zero_mul x, map_add := λ y z, add_mul y z x }
end is_add_monoid_hom
/-- Predicate for additive group homomorphism (deprecated -- use bundled `monoid_hom`). -/
structure is_add_group_hom [add_group α] [add_group β] (f : α → β) extends is_add_hom f : Prop
/-- Predicate for group homomorphisms (deprecated -- use bundled `monoid_hom`). -/
@[to_additive]
structure is_group_hom [group α] [group β] (f : α → β) extends is_mul_hom f : Prop
@[to_additive]
lemma monoid_hom.is_group_hom {G H : Type*} {_ : group G} {_ : group H} (f : G →* H) :
is_group_hom (f : G → H) :=
{ map_mul := f.map_mul }
@[to_additive]
lemma mul_equiv.is_group_hom {G H : Type*} {_ : group G} {_ : group H} (h : G ≃* H) :
is_group_hom h := { map_mul := h.map_mul }
/-- Construct `is_group_hom` from its only hypothesis. -/
@[to_additive "Construct `is_add_group_hom` from its only hypothesis."]
lemma is_group_hom.mk' [group α] [group β] {f : α → β} (hf : ∀ x y, f (x * y) = f x * f y) :
is_group_hom f :=
{ map_mul := hf }
namespace is_group_hom
variables [group α] [group β] {f : α → β} (hf : is_group_hom f)
open is_mul_hom (map_mul)
lemma map_mul : ∀ (x y), f (x * y) = f x * f y := hf.to_is_mul_hom.map_mul
/-- A group homomorphism is a monoid homomorphism. -/
@[to_additive "An additive group homomorphism is an additive monoid homomorphism."]
lemma to_is_monoid_hom : is_monoid_hom f :=
hf.to_is_mul_hom.to_is_monoid_hom
/-- A group homomorphism sends 1 to 1. -/
@[to_additive "An additive group homomorphism sends 0 to 0."]
lemma map_one : f 1 = 1 := hf.to_is_monoid_hom.map_one
/-- A group homomorphism sends inverses to inverses. -/
@[to_additive "An additive group homomorphism sends negations to negations."]
theorem map_inv (hf : is_group_hom f) (a : α) : f a⁻¹ = (f a)⁻¹ :=
eq_inv_of_mul_eq_one_left $ by rw [← hf.map_mul, inv_mul_self, hf.map_one]
@[to_additive] lemma map_div (hf : is_group_hom f) (a b : α) : f (a / b) = f a / f b :=
by simp_rw [div_eq_mul_inv, hf.map_mul, hf.map_inv]
/-- The identity is a group homomorphism. -/
@[to_additive "The identity is an additive group homomorphism."]
lemma id : is_group_hom (@id α) := { map_mul := λ _ _, rfl}
/-- The composition of two group homomorphisms is a group homomorphism. -/
@[to_additive "The composition of two additive group homomorphisms is an additive
group homomorphism."]
lemma comp (hf : is_group_hom f) {γ} [group γ] {g : β → γ} (hg : is_group_hom g) :
is_group_hom (g ∘ f) :=
{ ..is_mul_hom.comp hf.to_is_mul_hom hg.to_is_mul_hom }
/-- A group homomorphism is injective iff its kernel is trivial. -/
@[to_additive "An additive group homomorphism is injective if its kernel is trivial."]
lemma injective_iff {f : α → β} (hf : is_group_hom f) :
function.injective f ↔ (∀ a, f a = 1 → a = 1) :=
⟨λ h _, by rw ← hf.map_one; exact @h _ _,
λ h x y hxy, eq_of_div_eq_one $ h _ $ by rwa [hf.map_div, div_eq_one]⟩
/-- The product of group homomorphisms is a group homomorphism if the target is commutative. -/
@[to_additive "The sum of two additive group homomorphisms is an additive group homomorphism
if the target is commutative."]
lemma mul {α β} [group α] [comm_group β]
{f g : α → β} (hf : is_group_hom f) (hg : is_group_hom g) :
is_group_hom (λa, f a * g a) :=
{ map_mul := (hf.to_is_mul_hom.mul hg.to_is_mul_hom).map_mul }
/-- The inverse of a group homomorphism is a group homomorphism if the target is commutative. -/
@[to_additive "The negation of an additive group homomorphism is an additive group homomorphism
if the target is commutative."]
lemma inv {α β} [group α] [comm_group β] {f : α → β} (hf : is_group_hom f) :
is_group_hom (λa, (f a)⁻¹) :=
{ map_mul := hf.to_is_mul_hom.inv.map_mul }
end is_group_hom
namespace ring_hom
/-!
These instances look redundant, because `deprecated.ring` provides `is_ring_hom` for a `→+*`.
Nevertheless these are harmless, and helpful for stripping out dependencies on `deprecated.ring`.
-/
variables {R : Type*} {S : Type*}
section
variables [non_assoc_semiring R] [non_assoc_semiring S]
lemma to_is_monoid_hom (f : R →+* S) : is_monoid_hom f :=
{ map_one := f.map_one,
map_mul := f.map_mul }
lemma to_is_add_monoid_hom (f : R →+* S) : is_add_monoid_hom f :=
{ map_zero := f.map_zero,
map_add := f.map_add }
end
section
variables [ring R] [ring S]
lemma to_is_add_group_hom (f : R →+* S) : is_add_group_hom f :=
{ map_add := f.map_add }
end
end ring_hom
/-- Inversion is a group homomorphism if the group is commutative. -/
@[to_additive neg.is_add_group_hom
"Negation is an `add_group` homomorphism if the `add_group` is commutative."]
lemma inv.is_group_hom [comm_group α] : is_group_hom (has_inv.inv : α → α) :=
{ map_mul := mul_inv }
/-- The difference of two additive group homomorphisms is an additive group
homomorphism if the target is commutative. -/
lemma is_add_group_hom.sub {α β} [add_group α] [add_comm_group β]
{f g : α → β} (hf : is_add_group_hom f) (hg : is_add_group_hom g) :
is_add_group_hom (λa, f a - g a) :=
by simpa only [sub_eq_add_neg] using hf.add hg.neg
namespace units
variables {M : Type*} {N : Type*} [monoid M] [monoid N]
/-- The group homomorphism on units induced by a multiplicative morphism. -/
@[reducible] def map' {f : M → N} (hf : is_monoid_hom f) : Mˣ →* Nˣ :=
map (monoid_hom.of hf)
@[simp] lemma coe_map' {f : M → N} (hf : is_monoid_hom f) (x : Mˣ) :
↑((map' hf : Mˣ → Nˣ) x) = f x :=
rfl
lemma coe_is_monoid_hom : is_monoid_hom (coe : Mˣ → M) := (coe_hom M).is_monoid_hom_coe
end units
namespace is_unit
variables {M : Type*} {N : Type*} [monoid M] [monoid N] {x : M}
lemma map' {f : M → N} (hf :is_monoid_hom f) {x : M} (h : is_unit x) :
is_unit (f x) :=
h.map (monoid_hom.of hf)
end is_unit
lemma additive.is_add_hom [has_mul α] [has_mul β] {f : α → β} (hf : is_mul_hom f) :
@is_add_hom (additive α) (additive β) _ _ f :=
{ map_add := is_mul_hom.map_mul hf }
lemma multiplicative.is_mul_hom [has_add α] [has_add β] {f : α → β} (hf : is_add_hom f) :
@is_mul_hom (multiplicative α) (multiplicative β) _ _ f :=
{ map_mul := is_add_hom.map_add hf }
-- defeq abuse
lemma additive.is_add_monoid_hom [mul_one_class α] [mul_one_class β] {f : α → β}
(hf : is_monoid_hom f) : @is_add_monoid_hom (additive α) (additive β) _ _ f :=
{ map_zero := hf.map_one,
..additive.is_add_hom hf.to_is_mul_hom }
lemma multiplicative.is_monoid_hom
[add_zero_class α] [add_zero_class β] {f : α → β} (hf : is_add_monoid_hom f) :
@is_monoid_hom (multiplicative α) (multiplicative β) _ _ f :=
{ map_one := is_add_monoid_hom.map_zero hf,
..multiplicative.is_mul_hom hf.to_is_add_hom }
lemma additive.is_add_group_hom [group α] [group β] {f : α → β} (hf : is_group_hom f) :
@is_add_group_hom (additive α) (additive β) _ _ f :=
{ map_add := hf.to_is_mul_hom.map_mul }
lemma multiplicative.is_group_hom [add_group α] [add_group β] {f : α → β}
(hf : is_add_group_hom f) : @is_group_hom (multiplicative α) (multiplicative β) _ _ f :=
{ map_mul := hf.to_is_add_hom.map_add }
|
/* interpolation/interp_poly.c
*
* Copyright (C) 2001 DAN, HO-JIN
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Modified for standalone use in polynomial directory, B.Gough 2001 */
#include <config.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_poly.h>
int
gsl_poly_dd_init (double dd[], const double xa[], const double ya[],
size_t size)
{
size_t i, j;
/* Newton's divided differences */
dd[0] = ya[0];
for (j = size - 1; j >= 1; j--)
{
dd[j] = (ya[j] - ya[j - 1]) / (xa[j] - xa[j - 1]);
}
for (i = 2; i < size; i++)
{
for (j = size - 1; j >= i; j--)
{
dd[j] = (dd[j] - dd[j - 1]) / (xa[j] - xa[j - i]);
}
}
return GSL_SUCCESS;
}
int
gsl_poly_dd_taylor (double c[], double xp,
const double dd[], const double xa[], size_t size,
double w[])
{
size_t i, j;
for (i = 0; i < size; i++)
{
c[i] = 0.0;
w[i] = 0.0;
}
w[size - 1] = 1.0;
c[0] = dd[0];
for (i = size - 1; i-- > 0;)
{
w[i] = -w[i + 1] * (xa[size - 2 - i] - xp);
for (j = i + 1; j < size - 1; j++)
{
w[j] = w[j] - w[j + 1] * (xa[size - 2 - i] - xp);
}
for (j = i; j < size; j++)
{
c[j - i] += w[j] * dd[size - i - 1];
}
}
return GSL_SUCCESS;
}
|
Since the games , Del Toso has participated in the 2013 Osaka Cup in Japan , where the Gliders successfully defended the title they had won in 2008 , 2009 , 2010 and 2012 .
|
Spring weather is here, get this gem before someone else does! Driver's Way Certified one-owner! Touring Sport with Leather, Heated & Cooled Front Seats, Navigation, Bose, Rear-View Camera, and 19'' Alloys! This great-looking Pearl White 2018 Nissan 370Z Touring Sport convertible has a robust 3.7-liter V6 and athletic handling. This Touring Sport comes equipped with red wine cloth and simulated leather upholstery, power heated & ventilated seats, an auto-dimming rearview mirror, Bose premium sound, aux input, a touchscreen infotainment system, navigation, a USB port, voice controls, a rearview camera, Bluetooth capability, satellite radio capability, a leather-wrapped steering wheel w/audio controls and paddle shifters, LED daytime running lights, HID headlights, and 19'' alloys. Nice! Powering this two-seat sports car is a 3.7-liter V6 engine paired to a 7-speed automatic transmission. Call or come by for more details on this incredible 370Z convertible! Make it yours today!
Hello, I would like more information about the 2018 Nissan 370Z Roadster, stock# D49206.
I would like test drive the 2018 Nissan 370Z Roadster, stock# D49206.
Please text me about this 2018 Nissan 370Z Roadster (JN1AZ4FH0JM520193). |
From mathcomp Require Import all_ssreflect all_algebra.
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Reserved Notation "[ 'lens' x1 ; .. ; xn ]"
(format "[ 'lens' x1 ; .. ; xn ]").
Reserved Notation "[ 'lens' ]" (format "[ 'lens' ]").
(* Utility lemmas *)
Lemma addnLR m n p : m + n = p -> n = p - m.
Proof. move/(f_equal (subn^~ m)); by rewrite addKn. Qed.
Lemma ltn_ordK q (i : 'I_q) : Ordinal (ltn_ord i) = i.
Proof. by apply val_inj. Qed.
Lemma disjointP (T : finType) (a1 a2 : pred T) :
reflect (forall i, i \in a1 -> ~ i \in a2) [disjoint a1 & a2].
Proof.
case/boolP: [disjoint a1 & a2] => /pred0P Hdisj; constructor.
move=> i H1 H2. move: (Hdisj i). by rewrite /= H1 H2.
move=> H; elim: Hdisj => i /=.
case H1: (i \in a1) => //.
by apply/negbTE/negP/H.
Qed.
Lemma enum_filterP (T : finType) (P : pred T) :
[seq x <- enum T | P x] = enum P.
Proof. by rewrite {2}/enum_mem -enumT. Qed.
Section tnth.
Variables (T : Type) (m n : nat) (vl : m.-tuple T) (vr : n.-tuple T).
Lemma cast_tuple_proof : m = n -> size vl == n.
Proof. by rewrite size_tuple => ->. Qed.
Definition cast_tuple (H : m = n) : n.-tuple T := Tuple (cast_tuple_proof H).
Lemma eq_ord_tuple (t1 t2 : n.-tuple 'I_m) :
(t1 == t2) = (map val t1 == map val t2).
Proof.
case: eqP => [-> | H]; apply/esym/eqP => // /inj_map H'.
by elim H; apply/val_inj/H'/val_inj.
Qed.
Lemma nth_tnth i x0 (H : i < n) : nth x0 vr i = tnth vr (Ordinal H).
Proof. by rewrite (tnth_nth x0). Qed.
Lemma tnth_lshift i : tnth [tuple of vl ++ vr] (lshift n i) = tnth vl i.
Proof.
by rewrite (tnth_nth (tnth vl i)) /= nth_cat size_tuple ltn_ord -tnth_nth.
Qed.
Lemma tnth_rshift i : tnth [tuple of vl ++ vr] (rshift m i) = tnth vr i.
Proof.
rewrite (tnth_nth (tnth vr i)) /= nth_cat size_tuple ltnNge leq_addr /=.
by rewrite addKn -tnth_nth.
Qed.
Lemma eq_from_nth' (s1 s2 : seq T) :
size s1 = size s2 -> (forall a i, i < size s1 -> nth a s1 i = nth a s2 i) ->
s1 = s2.
Proof.
case: s1 => [|a s1 Hsz Heq].
by move/esym/eqP/nilP ->.
exact (eq_from_nth Hsz (Heq a)).
Qed.
End tnth.
Lemma cast_tupleE n T (v : n.-tuple T) (H : n = n) : cast_tuple v H = v.
Proof. exact/val_inj. Qed.
Section tnth_eq.
Variables (A : eqType) (n : nat).
Lemma tnth_inj (t : n.-tuple A) : reflect (injective (tnth t)) (uniq t).
Proof.
apply: (iffP idP).
- move=> /uniqP Hu i j.
rewrite (tnth_nth (tnth t i)) (tnth_nth (tnth t i) t j).
move/(Hu (tnth t i) i j)/val_inj => -> //; by rewrite inE size_tuple.
- case: t => -[|a t] // Hlen Hinj.
apply/(uniqP a) => i j.
rewrite !inE !size_tuple => Hi Hj.
by rewrite !nth_tnth => /Hinj [].
Qed.
Lemma index_tuple (t : n.-tuple A) i : (index i t < n) <-> (i \in t).
Proof. by rewrite -index_mem size_tuple. Qed.
End tnth_eq.
Section sorted.
Definition ord_ltn {r} : rel 'I_r := relpre val ltn.
Lemma sorted_enum r : sorted ord_ltn (enum 'I_r).
Proof.
rewrite /is_true -[RHS](iota_ltn_sorted 0 r) -val_enum_ord.
by elim: (enum 'I_r) => //= a [|b l] //= <-.
Qed.
Variables (A : Type) (le : rel A) (le_trans : transitive le).
Lemma sorted_tnth q (lq : q.-tuple A) (a b : 'I_q) :
sorted le lq -> ord_ltn a b -> le (tnth lq a) (tnth lq b).
Proof.
move=> Hsort ab.
have := @sorted_ltn_nth _ le le_trans (tnth lq a) lq Hsort a b.
rewrite !inE !size_tuple !ltn_ord -!tnth_nth; exact.
Qed.
Lemma sorted_comp q (lq : q.-tuple A) (lr : seq 'I_q) :
sorted le lq -> sorted ord_ltn lr -> sorted le (map (tnth lq) lr).
Proof.
move=> Hlq /=.
elim: lr => // a [|b lr] IH //= /andP[ab] Hsort.
rewrite sorted_tnth //=; exact: IH.
Qed.
End sorted.
Section lens.
Variables (T : Type) (n m : nat).
Record lens := mkLens {lens_t :> m.-tuple 'I_n ; lens_uniq : uniq lens_t}.
Canonical lens_subType := Eval hnf in [subType for lens_t].
Canonical lens_predType := PredType (pred_of_seq : lens -> pred 'I_n).
Definition endo1 := m.-tuple T -> m.-tuple T.
Variables (l : lens) (f : endo1).
Definition extract (t : n.-tuple T) := [tuple of map (tnth t) l].
Definition lens_sorted (l' : lens) := sorted ord_ltn l'.
Lemma mem_lensE : l =i val (lens_t l).
Proof. done. Qed.
Lemma size_lens : size l = m.
Proof. by rewrite size_tuple. Qed.
Lemma lens_leq : m <= n.
Proof.
rewrite -(size_enum_ord n) -size_lens uniq_leq_size // ?lens_uniq //.
move=> i _; by rewrite mem_enum.
Qed.
Lemma tnth_lensK i : index (tnth l i) l = i.
Proof.
by rewrite (tnth_nth (tnth l i)) index_uniq // (lens_uniq,size_lens).
Qed.
Lemma tnth_extract (v : n.-tuple T) i :
tnth (extract v) i = tnth v (tnth l i).
Proof. by rewrite tnth_map. Qed.
Lemma eq_lens_tnth (l' : lens) : (tnth l =1 tnth l') -> l = l'.
Proof. by move/eq_from_tnth/val_inj. Qed.
Lemma lens_inj : injective (fun x : lens => x : seq _).
Proof. move=> x y H; exact/val_inj/val_inj. Qed.
Lemma tnth_lens_inj : injective (tnth l).
Proof. exact/tnth_inj/lens_uniq. Qed.
Lemma lens_sortedP :
reflect (exists p, l = [seq i <- enum 'I_n | p i] :> seq _) (lens_sorted l).
Proof.
case/boolP: (lens_sorted l) => Hl; constructor.
exists (mem l). apply/(irr_sorted_eq (leT:=ord_ltn)) => //.
- exact/ltn_trans.
- by move=> x; rewrite /ord_ltn /= ltnn.
- rewrite sorted_filter //. exact/ltn_trans. exact/sorted_enum.
by move=> i; rewrite mem_filter mem_enum andbT.
case => p Hp.
move/negP: Hl; elim.
rewrite /lens_sorted Hp sorted_filter //. exact/ltn_trans. exact/sorted_enum.
Qed.
Section lens_index.
Variables (i : 'I_n) (H : i \in l).
Definition lens_index : 'I_m := Ordinal (proj2 (index_tuple l i) H).
Definition make_lens_index : index i l = lens_index. Proof. by []. Qed.
Lemma tnth_lens_index : tnth l lens_index = i.
Proof. by rewrite (tnth_nth i) nth_index. Qed.
End lens_index.
Lemma lens_indexK i (H : tnth l i \in l) : lens_index H = i.
Proof. by apply/val_inj => /=; rewrite tnth_lensK. Qed.
(* Focusing on subvector *)
Definition inject (t : n.-tuple T) (t' : m.-tuple T) :=
[tuple nth (tnth t i) t' (index i l) | i < n].
Definition focus1 t := inject t (f (extract t)).
Lemma focus1_out t i : i \notin l -> tnth (focus1 t) i = tnth t i.
Proof.
move=> Hi; by rewrite tnth_mktuple nth_default // memNindex ?size_tuple.
Qed.
Lemma focus1_in t : extract (focus1 t) = f (extract t).
Proof.
apply eq_from_tnth => i.
rewrite !tnth_map !tnth_ord_tuple [RHS](tnth_nth (tnth t (tnth l i))).
case: l => /= s Hu.
by rewrite index_uniq // size_tuple.
Qed.
Lemma nth_lens_index i (H : i \in l) dI (t : m.-tuple T) :
nth dI t (index i l) = tnth t (lens_index H).
Proof. by rewrite make_lens_index -tnth_nth. Qed.
Lemma nth_lens_out dI (t : m.-tuple T) i :
i \notin l -> nth dI t (index i l) = dI.
Proof. by move=> Hi; rewrite nth_default // memNindex // !size_tuple. Qed.
Lemma nth_extract_index dI t i :
i \in l -> nth dI (extract t) (index i l) = tnth t i.
Proof. move=> H; by rewrite nth_lens_index tnth_map tnth_lens_index. Qed.
Lemma tnth_inject t t' i (H : i \in l) :
tnth (inject t t') i = tnth t' (lens_index H).
Proof. by rewrite tnth_mktuple nth_lens_index. Qed.
Lemma tnth_inject_others t t' i :
i \notin l -> tnth (inject t t') i = tnth t i.
Proof. by move=> H; rewrite tnth_mktuple nth_lens_out. Qed.
Lemma inject_extract t : inject t (extract t) = t.
Proof.
apply/eq_from_tnth => i.
case/boolP: (i \in l) => H; last by rewrite tnth_inject_others.
by rewrite tnth_inject tnth_extract tnth_lens_index.
Qed.
End lens.
(* Cast *)
Section cast_lens.
Variables (n n' m m' : nat) (l : lens n m) (l' : lens n m').
Definition cast_lens_ord (H : n = n') : lens n' m.
exists (map_tuple (cast_ord H) l).
abstract (by rewrite map_inj_uniq ?lens_uniq // => i j /cast_ord_inj).
Defined.
Definition cast_lens (H : m' = m) : lens n m.
exists (cast_tuple l' H).
apply lens_uniq.
Defined.
Lemma eq_lens_sorted :
l =i l' -> lens_sorted l -> lens_sorted l' -> l = l' :> seq _.
Proof.
move/irr_sorted_eq; apply.
- exact: ltn_trans.
- by move=> x; rewrite /ord_ltn /= ltnn.
Qed.
Hypothesis H : l = l' :> seq _.
Lemma lens_size_eq : m' = m.
Proof. by rewrite -(size_tuple l') -H size_tuple. Qed.
Lemma lens_eq_cast : l = cast_lens lens_size_eq.
Proof. exact/lens_inj. Qed.
Lemma extract_eq_cast A (v : n.-tuple A) :
extract l v = cast_tuple (extract l' v) lens_size_eq.
Proof. apply val_inj => /=. by rewrite H. Qed.
End cast_lens.
Lemma cast_lens_ordE n m (l : lens n m) H : cast_lens_ord (n':=n) l H = l.
Proof. apply/eq_lens_tnth => i; rewrite tnth_map; by apply/val_inj. Qed.
Lemma cast_lensE n m (l : lens n m) H : cast_lens (m':=m) l H = l.
Proof. exact/lens_inj. Qed.
(* Identity *)
Section lens_id.
Variable n : nat.
Lemma uniq_ord_tuple : uniq (ord_tuple n). Proof. exact/enum_uniq. Qed.
Definition lens_id := mkLens uniq_ord_tuple.
Lemma lens_sorted_id : lens_sorted lens_id.
Proof. exact: sorted_enum. Qed.
Lemma tnth_lens_id i : tnth lens_id i = i.
Proof. by rewrite tnth_ord_tuple. Qed.
Lemma extract_lens_id I (v : n.-tuple I) : extract lens_id v = v.
Proof. apply eq_from_tnth => i. by rewrite tnth_extract tnth_lens_id. Qed.
Lemma index_lens_id i : index i lens_id = i.
Proof. by rewrite {1}(_ : i = tnth lens_id i) (tnth_ord_tuple,tnth_lensK). Qed.
End lens_id.
(* Composition of lenses *)
Section lens_comp.
Variables (n m p : nat) (l1 : lens n m) (l2 : lens m p).
Definition lens_comp : lens n p.
exists (extract l2 l1).
abstract (by rewrite map_inj_uniq ?lens_uniq // => i j /tnth_lens_inj ->).
Defined.
Lemma tnth_comp i : tnth lens_comp i = tnth l1 (tnth l2 i).
Proof. by rewrite tnth_map. Qed.
Lemma lens_sorted_comp :
lens_sorted l1 -> lens_sorted l2 -> lens_sorted lens_comp.
Proof. move=> Hl1 Hl2; apply sorted_comp => //; exact: ltn_trans. Qed.
Variable (T : Type).
Lemma extract_comp (t : n.-tuple T) :
extract lens_comp t = extract l2 (extract l1 t).
Proof. apply eq_from_tnth => i; by rewrite !tnth_extract. Qed.
(* Composition for subvectors *)
Lemma index_lens_comp i (H : i \in l1) :
index i lens_comp = index (lens_index H) l2.
Proof.
have {1}-> : i = tnth l1 (lens_index H) by rewrite (tnth_nth i) nth_index.
rewrite index_map //; exact/tnth_lens_inj.
Qed.
Lemma mem_lens_comp i (H : i \in l1) :
(i \in lens_comp) = (lens_index H \in l2).
Proof. by rewrite -!index_mem !size_tuple index_lens_comp. Qed.
Lemma lens_comp_sub :
{subset lens_comp <= l1}.
Proof.
by move=> i; rewrite mem_lensE => /mapP [j] _ ->; rewrite mem_tnth.
Qed.
Lemma mem_lens_comp_out i : i \notin l1 -> i \notin lens_comp.
Proof. by apply contra => /lens_comp_sub. Qed.
Lemma inject_comp (t : n.-tuple T) t' :
inject l1 t (inject l2 (extract l1 t) t') = inject lens_comp t t'.
Proof.
apply eq_from_tnth => i.
case/boolP: (i \in l1) => Hl1.
rewrite tnth_inject [RHS]tnth_mktuple index_lens_comp.
case/boolP: (lens_index Hl1 \in l2) => Hl2.
by rewrite tnth_inject make_lens_index -tnth_nth.
by rewrite tnth_inject_others // tnth_extract tnth_lens_index nth_lens_out.
by rewrite !tnth_inject_others // mem_lens_comp_out.
Qed.
Lemma focus1A (f : p.-tuple T -> p.-tuple T) :
focus1 l1 (focus1 l2 f) =1 focus1 lens_comp f.
Proof. move=> t; by rewrite /focus1 inject_comp extract_comp. Qed.
(* Commutativity of subvector operations *)
Section disjoint_lenses.
Variables (q r : nat) (l : lens n q) (l' : lens n r) (t : n.-tuple T).
Hypothesis Hdisj : [disjoint l & l'].
Lemma extract_inject t' : extract l (inject l' t t') = extract l t.
Proof.
apply eq_from_tnth => i; rewrite !tnth_extract tnth_mktuple.
by rewrite nth_lens_out // (disjointFr Hdisj) // mem_tnth.
Qed.
Lemma inject_disjointC vj vk :
inject l' (inject l t vk) vj = inject l (inject l' t vj) vk.
Proof.
apply eq_from_tnth => i.
case/boolP: (i \in l) => Hil.
have Hil' : i \notin l' by rewrite (disjointFr Hdisj) // mem_tnth.
by rewrite tnth_inject_others // !tnth_inject.
case/boolP: (i \in l') => Hil'.
by rewrite tnth_inject tnth_inject_others // tnth_inject.
by rewrite !tnth_inject_others.
Qed.
Lemma focus1_commu_in (f : endo1 T q) (g : endo1 T r) i : i \in l ->
tnth (focus1 l f (focus1 l' g t)) i = tnth (focus1 l' g (focus1 l f t)) i.
Proof.
move=> Hl; have Hl' : i \notin l' by rewrite (disjointFr Hdisj).
by rewrite (focus1_out _ _ Hl') /focus1 extract_inject // !tnth_inject.
Qed.
End disjoint_lenses.
Lemma focus1C l3 (f : endo1 T m) (g : endo1 T p) :
[disjoint l1 & l3] ->
focus1 l1 f \o focus1 l3 g =1 focus1 l3 g \o focus1 l1 f.
Proof.
move=> Hdisj t /=.
apply eq_from_tnth => i.
case/boolP: (i \in l1) => Hl1; first exact: focus1_commu_in.
case/boolP: (i \in l3) => Hl3.
by rewrite [RHS]focus1_commu_in // disjoint_sym.
by rewrite !focus1_out.
Qed.
End lens_comp.
Section lens_comp_id.
Variables (n m : nat) (l : lens n m).
Lemma lens_comp1l : lens_comp (lens_id n) l = l.
Proof. by apply/eq_lens_tnth => i; rewrite tnth_comp tnth_lens_id. Qed.
Lemma lens_compl1 : lens_comp l (lens_id m) = l.
Proof. by apply/eq_lens_tnth => i; rewrite tnth_comp tnth_lens_id. Qed.
End lens_comp_id.
Section lens_pred.
Variables (n : nat) (p : pred 'I_n).
Let pred_tuple := Tuple (enum_tupleP p).
Lemma uniq_pred_tuple : uniq pred_tuple.
Proof. exact/enum_uniq. Qed.
Definition lens_pred := mkLens uniq_pred_tuple.
Lemma lens_sorted_pred : lens_sorted lens_pred.
Proof. by apply/lens_sortedP; exists (mem p); rewrite enum_filterP. Qed.
End lens_pred.
(* Decomposition into inclusion and permutation *)
Section lens_basis_perm.
Variables (n p : nat) (l : lens n p).
Definition seq_basis := [seq i <- enum 'I_n | i \in l].
Lemma size_basis : size seq_basis == p.
Proof.
apply/eqP.
rewrite /seq_basis.
rewrite (eq_filter (a2:=mem [set i | i in l])); last first.
move=> i. rewrite !inE.
case: imsetP.
by case => x Hx ->.
by move=> Hx; apply/negP => Hi; move: Hx; elim; exists i.
rewrite enum_filterP /= -cardE card_imset // -[RHS](size_tuple l).
exact/card_uniqP/lens_uniq.
Qed.
Lemma uniq_basis : uniq (Tuple size_basis).
Proof. by rewrite filter_uniq // enum_uniq. Qed.
Definition lens_basis := mkLens uniq_basis.
Lemma mem_lens_basis : lens_basis =i l.
Proof. by move=> i; rewrite mem_filter mem_enum andbT. Qed.
Lemma lens_sorted_basis : lens_sorted lens_basis.
Proof. by apply/lens_sortedP; exists (mem l). Qed.
Lemma lens_basis_sortedE : lens_sorted l -> lens_basis = l.
Proof.
move=> H; exact/lens_inj/eq_lens_sorted/H/lens_sorted_basis/mem_lens_basis.
Qed.
Lemma perm_in_basis i : tnth l i \in lens_basis.
Proof. by rewrite mem_lens_basis mem_tnth. Qed.
Definition tuple_perm := [tuple lens_index (perm_in_basis i) | i < p].
Lemma uniq_perm : uniq tuple_perm.
Proof.
rewrite map_inj_uniq ?uniq_ord_tuple //.
move=> i j /(f_equal (tnth lens_basis)).
by rewrite !tnth_lens_index => /tnth_lens_inj.
Qed.
Definition lens_perm := mkLens uniq_perm.
Lemma lens_basis_perm : lens_comp lens_basis lens_perm = l.
Proof.
apply/eq_lens_tnth => i.
by rewrite tnth_comp tnth_mktuple tnth_lens_index.
Qed.
Lemma lens_perm_sortedE : lens_sorted l -> lens_perm = lens_id p.
Proof.
move=> H; apply/eq_lens_tnth => i.
rewrite tnth_mktuple tnth_ord_tuple.
apply/(tnth_inj lens_basis); first exact/lens_uniq.
by rewrite tnth_lens_index lens_basis_sortedE.
Qed.
End lens_basis_perm.
(* Composition of lenses *)
Section lens_cat.
Variables (n m p : nat) (l1 : lens n m) (l2 : lens n p).
Hypothesis Hdisj : [disjoint l1 & l2].
Definition lens_cat : lens n (m+p).
exists [tuple of l1 ++ l2].
abstract
(case: l1 l2 Hdisj => l1' Hl1 [l2' Hl2] /= Hdisj';
rewrite cat_uniq Hl1 Hl2 andbT /=;
by apply/hasPn => /= i /(disjointFl Hdisj') ->).
Defined.
Lemma tnth_lens_cat_l i : tnth lens_cat (lshift p i) = tnth l1 i.
Proof. exact/tnth_lshift. Qed.
Lemma tnth_lens_cat_r i : tnth lens_cat (rshift m i) = tnth l2 i.
Proof. exact/tnth_rshift. Qed.
Variable (T : eqType).
Lemma extract_cat (t : n.-tuple T) :
extract lens_cat t = [tuple of extract l1 t ++ extract l2 t].
Proof. apply val_inj => /=. by rewrite map_cat. Qed.
End lens_cat.
Section merge_lens.
Variables (I : Type) (dI : I) (n m : nat) (l : lens n m).
Lemma cards_filter (A : finType) (p : pred A) :
#|[set a : A | p a]| = size [seq a <- enum A | p a].
Proof.
rewrite cardsE /= cardE -filter_predI.
congr size; apply eq_filter => /= i.
by rewrite !inE andbT.
Qed.
Definition others := [seq i <- enum 'I_n | i \notin l].
Lemma size_others : size others == n - m.
Proof.
move/cardsC/addnLR: [set i in l].
rewrite [LHS]cards_filter.
rewrite (_ : filter _ _ = others); last by apply eq_filter => i; rewrite !inE.
move/card_uniqP: (lens_uniq l).
by rewrite size_tuple cardT size_enum_ord cardsE => -> ->.
Qed.
Lemma mem_others i : (i \in others) = ~~ (i \in l).
Proof. by rewrite mem_filter mem_enum andbT. Qed.
Lemma uniq_others : uniq others.
Proof. by rewrite filter_uniq // enum_uniq. Qed.
Definition lothers : lens n (n-m).
exists (Tuple size_others).
exact uniq_others.
Defined.
Lemma mem_lothers i : (i \in lothers) = (i \notin l).
Proof. by rewrite mem_others. Qed.
Lemma lens_sorted_lothers : lens_sorted lothers.
Proof. exact/sorted_filter/sorted_enum/ltn_trans. Qed.
Definition merge_indices (v : m.-tuple I) (w : (n-m).-tuple I) :=
[tuple nth (nth dI w (index i lothers)) v (index i l) | i < n].
Lemma tnth_merge_indices i vi vj (Hil : i \in l) :
tnth (merge_indices vi vj) i = tnth vi (lens_index Hil).
Proof.
by rewrite !tnth_map !tnth_ord_tuple (make_lens_index Hil) -tnth_nth.
Qed.
Lemma tnth_merge_indices_lothers i vi vj (Hil : i \in lothers) :
tnth (merge_indices vi vj) i = tnth vj (lens_index Hil).
Proof.
have Hil' := Hil; rewrite mem_lothers in Hil'.
rewrite !tnth_map !tnth_ord_tuple nth_lens_out //.
by rewrite (make_lens_index Hil) -!tnth_nth.
Qed.
Lemma extract_merge v1 v2 : extract l (merge_indices v1 v2) = v1.
Proof.
apply eq_from_tnth => i; rewrite tnth_extract.
by rewrite (tnth_merge_indices _ _ (mem_tnth i l)) lens_indexK.
Qed.
Lemma extract_lothers_merge v1 v2 : extract lothers (merge_indices v1 v2) = v2.
Proof.
apply eq_from_tnth => i /=; rewrite tnth_extract.
by rewrite (tnth_merge_indices_lothers _ _ (mem_tnth i lothers)) lens_indexK.
Qed.
Lemma merge_indices_extract_others v1 v2 :
merge_indices v2 (extract lothers v1) = inject l v1 v2.
Proof.
apply eq_from_tnth => i.
case/boolP: (i \in l) => Hil.
by rewrite tnth_merge_indices tnth_inject.
rewrite tnth_inject_others //.
rewrite -mem_lothers in Hil.
by rewrite tnth_merge_indices_lothers tnth_extract tnth_lens_index.
Qed.
Lemma merge_indices_extract (v : n.-tuple I) :
merge_indices (extract l v) (extract lothers v) = v.
Proof. by rewrite merge_indices_extract_others inject_extract. Qed.
Lemma merge_indices_inj vj : injective (fun vi => merge_indices vi vj).
Proof.
move=> vi vi' Hm.
by rewrite -(extract_merge vi vj) -(extract_merge vi' vj) Hm.
Qed.
Lemma extract_merge_disjoint p (l' : lens n p) vi vj :
[disjoint l & l'] ->
extract l' (merge_indices vj (extract lothers vi)) = extract l' vi.
Proof.
move=> Hdisj; apply eq_from_tnth => i; rewrite !tnth_extract.
have Hil : tnth l' i \notin l by rewrite (disjointFl Hdisj) // mem_tnth.
have Hilo : tnth l' i \in lothers by rewrite mem_lothers.
by rewrite tnth_merge_indices_lothers tnth_extract tnth_lens_index.
Qed.
End merge_lens.
Lemma eq_lothers n m m' (l : lens n m) (l' : lens n m') :
l =i l' -> lothers l = lothers l' :> seq _.
Proof. by move=> ll'; apply/eq_filter => i; rewrite ll'. Qed.
Section lens_comp_lothers.
Variables (n m p : nat) (l : lens n m) (l' : lens (n - m) p).
Lemma disjoint_comp_lothers : [disjoint l & lens_comp (lothers l) l'].
Proof.
rewrite disjoint_sym disjoint_has.
rewrite -all_predC.
apply/allP => i Hi /=.
apply/negP => Hi'.
move: Hi => /= /mapP [j Hj] ij.
have : i \notin l.
by rewrite -mem_lothers ij mem_tnth.
by rewrite Hi'.
Qed.
Lemma lens_comp_lothers :
lens_comp (lothers l) (lothers l') =
lothers (lens_cat disjoint_comp_lothers) :> seq _.
Proof.
rewrite /= /others.
rewrite (eq_filter (a2:=preim (tnth (Tuple (size_others l)))
(mem (lothers (lens_comp (lothers l) l'))))); last first.
move=> i /=.
rewrite mem_lothers mem_lens_comp ?mem_tnth // => H.
by rewrite lens_indexK.
rewrite -filter_map (_ : map _ _ = lothers l); last first.
rewrite -(val_ord_tuple (n-m)); set mp := map _ _.
by rewrite (_ : mp = [tuple of mp]) // -tuple_map_ord.
rewrite -filter_predI.
apply eq_filter => i /=.
by rewrite [in RHS]mem_lensE /= mem_cat negb_or andbC mem_lothers.
Qed.
End lens_comp_lothers.
(* Empty lens *)
Section lens_empty.
Variable n : nat.
Definition lens_empty : lens n 0 := {|lens_t := [tuple]; lens_uniq := erefl|}.
Lemma lens_sorted_empty : lens_sorted lens_empty.
Proof. done. Qed.
Lemma eq_lens_empty (l : lens n 0) : l = lens_empty.
Proof. case: l => -[] [] // Hl Hu; exact/lens_inj. Qed.
Lemma extract_lens_empty T (l : lens n 0) v : extract (T:=T) l v = [tuple].
Proof. apply eq_from_tnth => x. have := ltn_ord x. by rewrite ltn0. Qed.
Lemma lothers_id : lothers (lens_id n) = lens_empty :> seq _.
Proof. apply/nilP. by rewrite /nilp size_tuple subnn. Qed.
Lemma lothers_empty : lothers lens_empty = lens_id n :> seq _.
Proof. by rewrite /lothers /others /= filter_predT. Qed.
Lemma merge_indices_empty (T : eqType) (dI:T) v w :
merge_indices dI lens_empty v w = cast_tuple w (subn0 n).
Proof.
rewrite /merge_indices.
rewrite (eq_mktuple (tnth (cast_tuple w (subn0 n)))); last first.
move => i.
by rewrite nth_lens_out // lothers_empty index_lens_id (tnth_nth dI).
by apply eq_from_tnth => i; rewrite tnth_mktuple.
Qed.
Lemma lens_cat_emptyl m (l : lens n m) (H : [disjoint lens_empty & l]) :
lens_cat H = l.
Proof. exact/lens_inj. Qed.
End lens_empty.
Section lens_full.
Lemma mem_lens_full n i (l : lens n n) : i \in l.
Proof.
move/card_uniqP: (lens_uniq l) (cardC (mem l)) ->.
rewrite card_ord size_tuple => /(f_equal (subn^~ n)).
rewrite addKn subnn => /card0_eq/(_ i).
by rewrite !inE => /negbFE.
Qed.
Lemma lothers_full n (l : lens n n) : lothers l = lens_empty n :> seq _.
Proof.
rewrite /= /others (eq_filter (a2:=pred0)) ?filter_pred0 //= => i.
by rewrite mem_lens_full.
Qed.
Lemma lothers_comp_full n m (l : lens n m) (l1 : lens m m) :
lothers (lens_comp l l1) = lothers l.
Proof.
apply/lens_inj/eq_lothers => i.
case/boolP: (i \in l) => Hi. by rewrite mem_lens_comp mem_lens_full.
apply/negbTE; apply: contra Hi. exact/lens_comp_sub.
Qed.
End lens_full.
Section merge_indices_basis.
Variables (I : Type) (dI : I) (n m : nat) (l : lens n m).
Lemma merge_indices_basis vi vj :
merge_indices dI (lens_basis l) vi vj =
merge_indices dI l (extract (lens_perm l) vi) vj.
Proof.
apply eq_from_tnth => i.
case/boolP: (i \in lens_basis l) => Hib.
rewrite tnth_merge_indices.
have Hil : i \in l.
by rewrite -(lens_basis_perm l) mem_lens_comp mem_lens_full.
rewrite tnth_merge_indices tnth_extract.
congr tnth.
apply/(tnth_inj (lens_basis l)); first by apply lens_uniq.
by rewrite -tnth_comp lens_basis_perm !tnth_lens_index.
rewrite -mem_lothers in Hib.
have Hil : i \in lothers l.
by rewrite -(lens_basis_perm l) lothers_comp_full.
rewrite !tnth_merge_indices_lothers.
congr tnth; apply/val_inj => /=.
congr index.
move/(f_equal (val \o val)): (lothers_comp_full (lens_basis l) (lens_perm l)).
by rewrite lens_basis_perm.
Qed.
End merge_indices_basis.
Section lens_single.
Variables n : nat.
Definition lens_single i : lens n 1 :=
{|lens_t := [tuple i]; lens_uniq := erefl|}.
Lemma lens_sorted_single i : lens_sorted (lens_single i).
Proof. done. Qed.
Lemma index_lens_single i : index i (lens_single i) = (@ord0 1).
Proof. by rewrite /= eqxx. Qed.
Lemma lens_index_single i j (H : j \in lens_single i) : lens_index H = ord0.
Proof. by apply/val_inj => /=; move: H; rewrite inE eq_sym => ->. Qed.
Lemma tnth_lens_single i j : tnth (lens_single i) j = i.
Proof. by rewrite /= ord1. Qed.
Lemma tnth_merge_indices_single T (dI : T) i vi vj :
tnth (merge_indices dI (lens_single i) vi vj) i = tnth vi ord0.
Proof.
rewrite tnth_merge_indices. by rewrite inE eqxx.
by move=> H; rewrite ord1.
Qed.
End lens_single.
Lemma tnth_lothers_single n (i : 'I_n.+2) (k : 'I_n.+1) :
tnth (lothers (lens_single i)) k = lift i k.
Proof.
apply/val_inj; rewrite (tnth_nth i); case: k => /=.
elim: (n.+1) i => {n} [|n IH] i k.
by rewrite ltn0.
move/eqP: (size_others (lens_single i)); rewrite /others enum_ordSl.
case: k => [|k] /=; rewrite mem_lensE inE.
case: (unliftP ord0 i) => [i'|] -> Hsz.
by rewrite eq_liftF.
by rewrite eqxx /= enum_ordSl.
case: (unliftP ord0 i) => [i'|] ->.
rewrite ltnS => Hsz Hk.
rewrite eq_liftF /= filter_map size_map in Hsz *.
rewrite (nth_map i' _ (lift ord0)); last first.
by rewrite -ltnS Hsz subn1 ltnS.
rewrite bumpS /= /(bump 0) add1n.
f_equal.
rewrite (eq_filter (a2:=fun k => k \notin lens_single i')) //.
exact: IH.
rewrite eqxx /= filter_map size_map => Hsz Hk.
rewrite (nth_map ord0 _ (lift ord0)); last by rewrite Hsz.
congr bump.
rewrite (eq_filter (a2:=predT)) //.
rewrite ltnS in Hk.
rewrite filter_predT (_ : k.+1 = lift ord0 (Ordinal Hk)) //.
by rewrite nth_ord_enum.
Qed.
Section lens_pair.
Variables (n : nat) (i j : 'I_n).
Lemma uniq_pair : i != j -> uniq [:: i; j].
Proof. by rewrite /= inE andbT. Qed.
Hypothesis ij : i != j.
Definition lens_pair : lens n 2 := mkLens (uniq_pair ij).
Lemma lens_pair0 : lens_comp lens_pair (lens_single ord0) = lens_single i.
Proof. by apply/eq_lens_tnth => k; rewrite tnth_comp !tnth_lens_single. Qed.
Lemma lens_pair1 :
lens_comp lens_pair (lens_single (lift ord0 ord0)) = lens_single j.
Proof. by apply/eq_lens_tnth => k; rewrite tnth_comp !tnth_lens_single. Qed.
End lens_pair.
(* Ordered lenses *)
Section lens_left_right.
Variables m n : nat.
Definition lens_left : lens (m+n) m.
exists [tuple lshift n i | i < m].
abstract (rewrite map_inj_uniq ? enum_uniq //; exact/lshift_inj).
Defined.
Definition lens_right : lens (m+n) n.
exists [tuple rshift m i | i < n].
abstract (rewrite map_inj_uniq ? enum_uniq //; exact/rshift_inj).
Defined.
Variables (T : Type) (tl : m.-tuple T) (tr : n.-tuple T).
Lemma extract_lens_left : extract lens_left [tuple of tl ++ tr] = tl.
Proof.
apply eq_from_tnth => i; rewrite [LHS](tnth_nth (tnth tl i)) /= -map_comp.
by rewrite (nth_map i) /= ?size_enum_ord // nth_ord_enum tnth_lshift.
Qed.
Lemma extract_lens_right : extract lens_right [tuple of tl ++ tr] = tr.
Proof.
apply eq_from_tnth => i; rewrite [LHS](tnth_nth (tnth tr i)) /= -map_comp.
by rewrite (nth_map i) /= ?size_enum_ord // nth_ord_enum tnth_rshift.
Qed.
Lemma lens_left_right_disjoint : [disjoint lens_left & lens_right].
Proof.
apply/pred0P => /= i.
rewrite simpl_predE /=.
case: (split_ordP i) => j ->.
suff /negbTE -> : lshift n j \notin lens_right.
by rewrite andbF.
apply/mapP => -[k] _ /esym/eqP.
by rewrite eq_rlshift.
have /negbTE -> // : rshift m j \notin lens_left.
apply/mapP => -[k] _ /eqP.
by rewrite eq_rlshift.
Qed.
Lemma take_enum_lshift : take m (enum 'I_(m + n)) = [tuple lshift n i | i < m].
Proof.
apply/esym/eq_from_nth'.
by rewrite size_map size_takel -cardT card_ord // leq_addr.
move=> a i.
rewrite size_map -cardT card_ord => Hi.
rewrite nth_tnth tnth_map tnth_ord_tuple nth_take //.
apply val_inj. by rewrite [RHS]nth_enum_ord // (leq_trans Hi) // leq_addr.
Qed.
Lemma drop_enum_rshift : drop m (enum 'I_(m + n)) = [tuple rshift m i | i < n].
Proof.
apply/esym/eq_from_nth'.
by rewrite size_map size_drop -!cardT !card_ord addKn.
move=> a i.
rewrite size_map -cardT card_ord => Hi.
rewrite nth_tnth tnth_map tnth_ord_tuple nth_drop //.
apply val_inj. by rewrite [RHS]nth_enum_ord //= -addnS leq_add2l.
Qed.
Lemma lens_left_right : lens_cat lens_left_right_disjoint = lens_id (m+n).
Proof.
apply/lens_inj => /=.
by rewrite -[RHS](cat_take_drop m) take_enum_lshift drop_enum_rshift.
Qed.
Lemma lothers_left : lothers lens_left = lens_right :> seq _.
Proof.
rewrite /lothers /others /=.
have /= := f_equal val lens_left_right.
rewrite -(val_ord_tuple (m+n)) => <-.
rewrite filter_cat filter_map -(eq_filter (a1:=pred0)); last first.
move=> i /=; rewrite mem_lensE mem_map ?mem_enum //; exact/lshift_inj.
rewrite filter_pred0 filter_map -(eq_filter (a1:=predT)) ?filter_predT //.
move=> i /=. rewrite mem_lensE /=.
by apply/esym/mapP => -[x _] /eqP; rewrite eq_shift.
Qed.
Lemma lothers_right : lothers lens_right = lens_left :> seq _.
Proof.
rewrite /lothers /others /=.
have /= := f_equal val lens_left_right.
rewrite -(val_ord_tuple (m+n)) => <-.
rewrite filter_cat filter_map -(eq_filter (a1:=predT)); last first.
move=> i /=. rewrite mem_lensE /=.
by apply/esym/mapP => -[x _] /eqP; rewrite eq_shift.
rewrite filter_predT filter_map -(eq_filter (a1:=pred0)).
by rewrite filter_pred0 cats0.
move=> i /=; rewrite mem_lensE mem_map ?mem_enum //; exact/rshift_inj.
Qed.
Variables (p : nat) (l : lens p m) (l' : lens p n) (H : [disjoint l & l']).
Lemma lens_comp_left : l = lens_comp (lens_cat H) lens_left.
Proof.
by apply/eq_lens_tnth => i; rewrite tnth_comp tnth_mktuple tnth_lshift.
Qed.
Lemma lens_comp_right : l' = lens_comp (lens_cat H) lens_right.
Proof.
by apply/eq_lens_tnth => i; rewrite tnth_comp tnth_mktuple tnth_rshift.
Qed.
Definition lens_perm_left := lens_comp (lens_perm (lens_cat H)) lens_left.
Definition lens_perm_right := lens_comp (lens_perm (lens_cat H)) lens_right.
Lemma lens_perm_disjoint : [disjoint lens_perm_left & lens_perm_right].
Proof.
apply/disjointP => i /mapP [x] Hx -> /mapP [y] Hy.
move/(f_equal (tnth (lens_basis (lens_cat H)))).
rewrite -!tnth_comp lens_basis_perm => /tnth_lens_inj xy.
rewrite -xy in Hy.
by move/disjointP/(_ x): lens_left_right_disjoint; elim.
Qed.
Lemma lens_perm_leftE :
lens_comp (lens_basis (lens_cat H)) lens_perm_left =
lens_comp (lens_cat H) lens_left.
Proof.
by apply/eq_lens_tnth => i; rewrite !tnth_comp -tnth_comp lens_basis_perm.
Qed.
Lemma lens_perm_rightE :
lens_comp (lens_basis (lens_cat H)) lens_perm_right =
lens_comp (lens_cat H) lens_right.
Proof.
by apply/eq_lens_tnth => i; rewrite !tnth_comp -tnth_comp lens_basis_perm.
Qed.
End lens_left_right.
(* reindexing *)
Section reindex.
Variables (R : Type) (idx : R) (op : Monoid.com_law idx) (I : finType) (dI : I).
Lemma reindex_merge_indices n m (l : lens n m) F :
\big[op/idx]_i F i = \big[op/idx]_i \big[op/idx]_j F (merge_indices dI l i j).
Proof.
rewrite [RHS](pair_bigA _ (fun i j => F (merge_indices dI l i j))).
rewrite (reindex (fun v : m.-tuple I * (n-m).-tuple I =>
merge_indices dI l (fst v) (snd v))) //=.
exists (fun v => (extract l v, extract (lothers l) v)) => // v _.
by rewrite extract_merge extract_lothers_merge; case: v.
by rewrite /= merge_indices_extract.
Qed.
Lemma reindex_left_right m n (F : m.-tuple I -> n.-tuple I -> R) :
\big[op/idx]_i \big[op/idx]_j F i j =
\big[op/idx]_v F (extract (lens_left m n) v) (extract (lens_right m n) v).
Proof.
rewrite pair_bigA /=.
rewrite [LHS](reindex (fun v : (m+n).-tuple I =>
(extract (lens_left m n) v, extract (lens_right m n) v))) //.
exists (fun v : m.-tuple I * n.-tuple I => [tuple of v.1 ++ v.2]) => /= vj _.
rewrite -[RHS]extract_lens_id -(lens_left_right m n).
by apply/val_inj; rewrite /= map_cat.
case: vj => vl vr /=; congr pair; apply eq_from_tnth => i;
by rewrite tnth_map tnth_mktuple (tnth_lshift,tnth_rshift).
Qed.
End reindex.
Section inject_all.
Variables (I : Type) (m n : nat) (lm : lens (m+n) m) (ln : lens (m+n) n).
Hypothesis Hdisj : [disjoint lm & ln].
Lemma lens_all i : (i \in lm) || (i \in ln).
Proof.
have : [set a in lm] == [set a | a \notin ln].
rewrite eqEcard.
rewrite cards_filter (eqP (size_others ln)) addnK.
have -> : #|[set a in lm]| = #|lm| by apply eq_card => j; rewrite inE.
have/card_uniqP -> := lens_uniq lm.
rewrite size_tuple leqnn andbT.
apply/subsetP => j. by rewrite !inE => /(disjointFr Hdisj) ->.
move/eqP/setP/(_ i). rewrite !inE.
by case: (i \in ln) => ->.
Qed.
Lemma inject_all (vi vj : (m+n).-tuple I) :
(inject ln (inject lm vi (extract lm vj)) (extract ln vj)) = vj.
Proof.
apply eq_from_tnth => i.
rewrite tnth_mktuple.
case/boolP: (i \in ln) => Hi.
by rewrite (nth_lens_index Hi) tnth_map tnth_lens_index.
rewrite nth_lens_out // tnth_mktuple.
have := lens_all i.
rewrite (negbTE Hi) orbF => Him.
by rewrite (nth_lens_index Him) tnth_map tnth_lens_index.
Qed.
End inject_all.
(* Shifting of disjoint lenses *)
Section make_comp.
Variables (n m p : nat) (l : lens n m) (l' : lens n p).
Hypothesis Hdisj : [disjoint l & l'].
Lemma make_comp_present i :
tnth l' i \in lothers l.
Proof.
move: (mem_tnth i l').
rewrite mem_lothers => Hl'; apply/negP => Hl.
move: Hdisj; rewrite disjoint_has => /hasP; elim.
by exists (tnth l' i).
Qed.
Definition make_comp :=
[tuple lens_index (make_comp_present i) | i < p].
Lemma uniq_map_comp : uniq make_comp.
Proof.
rewrite /make_comp/= map_inj_in_uniq ?enum_uniq // => i j _ _.
move/(f_equal (tnth (lothers l))).
by rewrite !tnth_lens_index => /tnth_lens_inj.
Qed.
Definition lmake_comp := mkLens uniq_map_comp.
Lemma lmake_compE : lens_comp (lothers l) lmake_comp = l'.
Proof.
apply/eq_lens_tnth => i.
rewrite tnth_map tnth_mktuple (tnth_nth (tnth l' i)) /=.
by rewrite nth_index // make_comp_present.
Qed.
End make_comp.
(* associativity of focussing *)
Section lens_assoc.
Variables (I : Type) (dI : I) (n m p : nat) (l : lens n m) (l' : lens m p).
Local Notation merge_indices := (merge_indices dI).
Definition lothers_comp := lothers (lens_comp l l').
Lemma others_in_l_present i :
tnth (lens_comp l (lothers l')) i \in lothers_comp.
Proof.
rewrite mem_lothers; apply/mapP => -[k Hk].
rewrite tnth_comp => /tnth_lens_inj Hi.
by apply/negP: Hk; rewrite -mem_lothers -Hi mem_tnth.
Qed.
Definition others_in_l :=
[tuple lens_index (others_in_l_present i) | i < m - p].
Lemma uniq_others_in_l : uniq (others_in_l).
Proof.
apply/tnth_inj => i j; rewrite !tnth_mktuple.
set k := lens_index _.
case=> /(f_equal (nth (widen_ord (leq_subr _ _) k) lothers_comp)).
rewrite !nth_index; try by rewrite others_in_l_present.
move/tnth_inj => -> //.
rewrite map_inj_uniq ?(lens_uniq (lothers l')) //; exact/tnth_lens_inj.
Qed.
Definition lothers_in_l := mkLens uniq_others_in_l.
Lemma cast_lothers_notin_l : n - p - (m - p) = n - m.
Proof. rewrite subnBA ?subnK // lens_leq //. exact: (lens_comp l l'). Qed.
Lemma size_lothers_notin_l : size (lothers lothers_in_l) == n - m.
Proof. by rewrite size_tuple cast_lothers_notin_l. Qed.
Definition lothers_notin_l : lens (n-p) (n-m).
exists (Tuple size_lothers_notin_l).
exact (lens_uniq (lothers lothers_in_l)).
Defined.
Lemma lothers_in_l_comp :
lens_comp lothers_comp lothers_in_l = lens_comp l (lothers l').
Proof.
apply/eq_lens_tnth => i.
by rewrite !tnth_map tnth_ord_tuple tnth_lens_index.
Qed.
Lemma lothers_notin_l_comp :
lens_comp lothers_comp lothers_notin_l = lothers l.
Proof.
apply/lens_inj/eq_lens_sorted/lens_sorted_lothers/lens_sorted_comp;
try exact/sorted_filter/sorted_enum/ltn_trans.
move=> /= i; rewrite mem_lothers.
case/boolP: (i \in l) => /= Hi; apply/mapP.
- case=> j; rewrite mem_lothers => Hj Hi'.
apply/negP: Hj; rewrite negbK; apply/tnthP.
case/tnthP: Hi => k Hk.
have Hk' : k \in lothers l'.
rewrite mem_lothers; apply/tnthP => -[h] Hh.
have : i \in lothers_comp by rewrite Hi' mem_tnth.
by rewrite Hk Hh -tnth_comp mem_lothers mem_tnth.
exists (lens_index Hk').
apply (tnth_lens_inj (l:=lothers_comp)).
by rewrite -tnth_comp lothers_in_l_comp tnth_comp -Hi' Hk tnth_lens_index.
- have/tnthP [j Hj] : i \in lothers_comp.
rewrite mem_lothers; apply: contra Hi => /mapP [j Hj] ->.
exact: mem_tnth.
exists j => //.
rewrite mem_lothers; apply: contra Hi => /mapP [k _].
rewrite Hj => ->.
have Hol := others_in_l_present k.
by rewrite tnth_lens_index tnth_map mem_tnth.
Qed.
Lemma extract_lothers_comp (v : n.-tuple I) :
extract lothers_comp v =
merge_indices lothers_in_l
(extract (lens_comp lothers_comp lothers_in_l) v)
(extract (lens_comp lothers_comp (lothers lothers_in_l)) v).
Proof. by rewrite !extract_comp merge_indices_extract. Qed.
Lemma merge_indices_comp vj vk (vl : (n-p - (m-p)).-tuple I)
(vm : (n-m).-tuple I) :
vl = vm :> seq I -> (* can we use S-prop here? *)
merge_indices (lens_comp l l') vj (merge_indices lothers_in_l vk vl) =
merge_indices l (merge_indices l' vj vk) vm.
Proof.
move=> Hlm.
apply/eq_from_tnth => i.
case/boolP: (i \in l) => Hil.
rewrite (tnth_merge_indices _ _ _ Hil).
case/boolP: (lens_index Hil \in l') => Hill'.
rewrite (tnth_merge_indices _ _ _ Hill').
have Hilcl' : i \in lens_comp l l' by rewrite mem_lens_comp.
rewrite (tnth_merge_indices _ _ _ Hilcl').
congr tnth; apply/val_inj => /=; by rewrite -index_lens_comp.
have Hilo : i \in lothers_comp by rewrite mem_lothers mem_lens_comp.
rewrite -mem_lothers in Hill'.
rewrite tnth_merge_indices_lothers [RHS]tnth_merge_indices_lothers.
have Hic : i \in lens_comp l (lothers l') by rewrite mem_lens_comp.
have Hilol : lens_index Hilo \in lothers_in_l.
by rewrite -lothers_in_l_comp mem_lens_comp in Hic.
rewrite tnth_merge_indices.
congr tnth; apply (tnth_lens_inj (l:=lens_comp l (lothers l'))).
by rewrite -{1}lothers_in_l_comp !tnth_comp !tnth_lens_index.
case/boolP: (i \in lens_comp l l') => [/lens_comp_sub|] Hic.
by rewrite Hic in Hil.
rewrite -!mem_lothers in Hil Hic.
rewrite tnth_merge_indices_lothers [RHS]tnth_merge_indices_lothers.
have Hlil : lens_index Hic \in lothers lothers_in_l.
rewrite -mem_lens_comp mem_lensE /=.
by move/(f_equal (val \o val)): lothers_notin_l_comp => /= ->.
rewrite tnth_merge_indices_lothers.
set a := tnth vl _; rewrite /a (tnth_nth a) /= Hlm [RHS](tnth_nth a) /=.
congr nth.
have /(f_equal (val \o val)) := lothers_notin_l_comp; rewrite [RHS]/= => <-.
by rewrite -[LHS](index_lens_comp (lothers lothers_in_l)).
Qed.
(* For focus_others, only uses variables *)
Lemma merge_indices_comp_others (l1 : lens (n-m) p) vi vj :
merge_indices (lens_comp (lothers l) l1) vj
(extract (lothers (lens_comp (lothers l) l1)) vi) =
merge_indices l (extract l vi)
(merge_indices l1 vj (extract (lens_comp (lothers l) (lothers l1)) vi)).
Proof.
set l2 := lens_comp (lothers l) l1.
apply eq_from_tnth => i.
case/boolP: (i \in l) => Hl.
rewrite [RHS]tnth_merge_indices.
have Hl2: i \notin l2.
apply/negP => /lens_comp_sub; by rewrite mem_others Hl.
rewrite -mem_lothers in Hl2.
by rewrite tnth_merge_indices_lothers !tnth_extract !tnth_lens_index.
rewrite -mem_lothers in Hl.
rewrite [RHS]tnth_merge_indices_lothers.
case/boolP: (i \in l2) => Hl2.
have := Hl2; rewrite mem_lens_comp => Hl1; rewrite !tnth_merge_indices.
congr tnth; apply/val_inj; by rewrite /= -index_lens_comp.
have := Hl2; rewrite mem_lens_comp => Hl1.
rewrite -!mem_lothers in Hl1 Hl2.
by rewrite !tnth_merge_indices_lothers !tnth_extract !tnth_lens_index.
Qed.
Lemma merge_indices_pair (i i' : 'I_n.+2) (vi vj : 1.-tuple I)
(vk : (n.+2 - 1 - 1).-tuple I)
(Hior : i \in lothers (lens_single i'))
(Hir : i != i') :
merge_indices (lens_single i') vi
(merge_indices (lens_single (lens_index Hior)) vj vk) =
merge_indices (lens_pair Hir) [tuple of vj ++ vi] vk.
Proof.
apply/eq_from_tnth => j.
rewrite !tnth_map !tnth_ord_tuple.
rewrite [index j (lens_single _)]/= [index j (lens_pair _)]/=.
case: ifP => rij.
rewrite [X in nth _ vi X](_ : 0 = @ord0 1)%N //.
rewrite ifF; last by rewrite -(negbTE Hir) -(eqP rij).
case: vj => -[] // a [] //= sza.
by rewrite -!(tnth_nth _ vi ord0).
rewrite nth_default; last by rewrite size_tuple.
have Hjl : j \in lothers (lens_single i').
by rewrite mem_lothers mem_lensE inE eq_sym rij.
case: ifPn => ij.
rewrite -(eqP ij) in Hjl *.
rewrite make_lens_index -tnth_nth.
have -> : lens_index Hjl = lens_index Hior by apply/val_inj.
rewrite tnth_merge_indices_single.
by case: vj => -[].
rewrite make_lens_index -tnth_nth !tnth_map !tnth_ord_tuple.
rewrite nth_lens_out; last first.
rewrite mem_lensE inE.
apply: contra ij => /eqP /(f_equal (tnth (lothers (lens_single i')))).
by rewrite !tnth_lens_index => ->.
rewrite [RHS]nth_default ?size_tuple //.
congr nth.
rewrite -(index_lens_comp (lothers (lens_single (lens_index Hior))) Hjl).
congr index.
rewrite lens_comp_lothers.
apply eq_lothers => /= k.
by rewrite !mem_lensE !inE tnth_lens_index orbC.
Qed.
Lemma merge_indices_perm (l1 : lens m m) (vi : m.-tuple I) vk :
merge_indices (lens_comp l l1) (extract l1 vi) vk =
merge_indices l vi vk.
Proof.
apply/eq_from_tnth => i.
case/boolP: (i \in l) => Hil.
rewrite [RHS]tnth_merge_indices.
have Hil1 : i \in lens_comp l l1 by rewrite mem_lens_comp mem_lens_full.
rewrite tnth_merge_indices tnth_extract.
congr tnth; apply (tnth_lens_inj (l:=l)).
by rewrite -tnth_comp !tnth_lens_index.
rewrite -mem_lothers in Hil.
rewrite [RHS]tnth_merge_indices_lothers.
have Hic := Hil; rewrite -(lothers_comp_full _ l1) in Hic.
rewrite tnth_merge_indices_lothers.
congr tnth; apply/val_inj => /=.
by move/(f_equal (val \o val)): (lothers_comp_full l l1) => /= ->.
Qed.
End lens_assoc.
Section lens_rev.
Variables (I : Type) (dI : I) (n : nat).
Lemma uniq_lens_rev : uniq [tuple rev_ord i | i < n].
Proof.
rewrite (map_uniq (f:=@rev_ord n)) // -map_comp (eq_map (f2:=id)).
by rewrite map_id enum_uniq.
by move=> x /=; rewrite rev_ordK.
Qed.
Definition lens_rev := mkLens uniq_lens_rev.
Lemma tnth_rev A (t : n.-tuple A) i :
tnth [tuple of rev t] (rev_ord i) = tnth t i.
Proof.
rewrite (tnth_nth (tnth t i)) [RHS](tnth_nth (tnth t i)) /=.
rewrite nth_rev /= size_tuple; last by rewrite rev_ord_proof.
by move/(f_equal val): (rev_ordK i) => /= ->.
Qed.
Lemma merge_indices_rev m (l l' : lens m n)
(vi vj : n.-tuple I) vk :
l = rev l' :> seq _ -> vi = rev vj :> seq _ ->
merge_indices dI l vi vk = merge_indices dI l' vj vk.
Proof.
move=> Hl Hv.
rewrite -(merge_indices_perm dI l' lens_rev).
f_equal.
apply/eq_lens_tnth => i /=.
rewrite tnth_extract tnth_mktuple -[LHS]tnth_rev.
by congr tnth; apply/val_inj; rewrite /= Hl revK.
apply/eq_from_tnth => i.
rewrite tnth_extract tnth_mktuple -[LHS]tnth_rev.
by congr tnth; apply/val_inj; rewrite /= Hv revK.
Qed.
End lens_rev.
(* Computable Ordinal constants *)
Definition succO {n} := lift (@ord0 n).
Fixpoint addnO {n} m (p : 'I_n) : 'I_(m+n) :=
match m as x return 'I_(x+n) with
| 0 => p
| m.+1 => cast_ord (esym (addSnnS m n)) (addnO m (succO p))
end.
Lemma addnOK n m p : @addnO n m p = m + p :> nat.
Proof. elim: m n p => //= m IH n p. by rewrite IH /= addnS. Qed.
Definition INO {n} m := addnO m (@ord0 n).
Notation "n '%:O'" := (INO n) (at level 2, left associativity, format "n %:O").
Lemma succOS n m : succO m%:O = m.+1%:O :> 'I_(m.+1+n.+1).
Proof. apply/val_inj => /=. by rewrite /bump leq0n !addnOK !(addnC m). Qed.
Lemma succO0 n : succO ord0 = 1%:O :> 'I_n.+2.
Proof. exact/val_inj. Qed.
Definition succOE := (succO0,succOS).
Notation "[ 'lens' ]" := (@mkLens _ _ [tuple] erefl).
Notation "[ 'lens' x1 ; .. ; xn ]" :=
(@mkLens _ _ [tuple of x1%:O :: .. [:: xn%:O] ..] erefl).
Fixpoint enum_ordinal n : seq 'I_n :=
match n with
| 0 => [::]
| m.+1 => ord0 :: map succO (enum_ordinal m)
end.
Lemma enum_ordinalE n : enum 'I_n = enum_ordinal n.
Proof.
apply/(@inj_map _ _ (val : 'I_n -> nat)). exact val_inj.
rewrite val_enum_ord.
elim: n => //= n IH.
rewrite -map_comp -(eq_map (f1:=S \o nat_of_ord (n:=n))) //.
by rewrite map_comp -IH (iotaDl 1 0 n).
Qed.
Ltac eq_lens :=
apply/val_inj/eqP; rewrite ?eq_ord_tuple /= /others /= ?enum_ordinalE.
Section ordinal_examples.
Eval compute in uniq [tuple 0%:O; 1%:O; 2%:O]. (* = true *)
Let lens3_23 : lens 3 2 := [lens 1; 2].
End ordinal_examples.
|
namespace detail {
struct pre_inc_functor {
template <class T>
void operator()(T& value) const {
++ value;
}
};
struct post_inc_functor {
template <class T>
void operator()(T& value) const {
value++;
}
};
struct plus_assignable_functor {
template <class T>
void operator()(T& value) const {
value += T(1);
}
};
struct plus_functor {
template <class T>
void operator()(T& value) const {
value = value + T(1);
}
};
}
#include <boost/type_traits/conditional.hpp>
#include <boost/type_traits/has_plus_assign.hpp>
#include <boost/type_traits/has_plus.hpp>
#include <boost/type_traits/has_post_increment.hpp>
#include <boost/type_traits/has_pre_increment.hpp>
template <class T>
void inc(T& value) {
// call ++value
// or call value ++
// or value += T(1);
// or value = value + T(1);
typedef detail::plus_functor step_0_t;
typedef typename boost::conditional<
boost::has_plus_assign<T>::value,
detail::plus_assignable_functor,
step_0_t
>::type step_1_t;
typedef typename boost::conditional<
boost::has_post_increment<T>::value,
detail::post_inc_functor,
step_1_t
>::type step_2_t;
typedef typename boost::conditional<
boost::has_pre_increment<T>::value,
detail::pre_inc_functor,
step_2_t
>::type step_3_t;
step_3_t() // default constructing functor
(value); // calling operator() of a functor
}
struct has_only_postinc {
has_only_postinc operator ++(int) {
return *this;
}
};
struct has_only_plus {
explicit has_only_plus(int){}
};
has_only_plus operator + (has_only_plus v1, has_only_plus ) {
return v1;
}
#include <boost/mpl/if.hpp>
template <class T>
void inc_mpl(T& value) {
typedef detail::plus_functor step_0_t;
typedef typename boost::mpl::if_<
boost::has_plus_assign<T>,
detail::plus_assignable_functor,
step_0_t
>::type step_1_t;
typedef typename boost::mpl::if_<
boost::has_post_increment<T>,
detail::post_inc_functor,
step_1_t
>::type step_2_t;
typedef typename boost::mpl::if_<
boost::has_pre_increment<T>,
detail::pre_inc_functor,
step_2_t
>::type step_3_t;
step_3_t() // default constructing functor
(value); // calling operator() of a functor
}
#include <assert.h>
int main() {
int i = 0;
inc(i);
assert(i == 1);
has_only_postinc pi;
inc(pi);
has_only_plus v(0);
inc(v);
inc_mpl(i);
assert(i == 2);
inc_mpl(pi);
inc_mpl(v);
}
|
(* Title: HOL/Computational_Algebra/Fundamental_Theorem_Algebra.thy
Author: Amine Chaieb, TU Muenchen
*)
section \<open>Fundamental Theorem of Algebra\<close>
theory Fundamental_Theorem_Algebra
imports Polynomial Complex_Main
begin
subsection \<open>More lemmas about module of complex numbers\<close>
text \<open>The triangle inequality for cmod\<close>
lemma complex_mod_triangle_sub: "cmod w \<le> cmod (w + z) + norm z"
by (metis add_diff_cancel norm_triangle_ineq4)
subsection \<open>Basic lemmas about polynomials\<close>
lemma poly_bound_exists:
fixes p :: "'a::{comm_semiring_0,real_normed_div_algebra} poly"
shows "\<exists>m. m > 0 \<and> (\<forall>z. norm z \<le> r \<longrightarrow> norm (poly p z) \<le> m)"
proof (induct p)
case 0
then show ?case by (rule exI[where x=1]) simp
next
case (pCons c cs)
from pCons.hyps obtain m where m: "\<forall>z. norm z \<le> r \<longrightarrow> norm (poly cs z) \<le> m"
by blast
let ?k = " 1 + norm c + \<bar>r * m\<bar>"
have kp: "?k > 0"
using abs_ge_zero[of "r*m"] norm_ge_zero[of c] by arith
have "norm (poly (pCons c cs) z) \<le> ?k" if H: "norm z \<le> r" for z
proof -
from m H have th: "norm (poly cs z) \<le> m"
by blast
from H have rp: "r \<ge> 0"
using norm_ge_zero[of z] by arith
have "norm (poly (pCons c cs) z) \<le> norm c + norm (z * poly cs z)"
using norm_triangle_ineq[of c "z* poly cs z"] by simp
also have "\<dots> \<le> ?k"
using mult_mono[OF H th rp norm_ge_zero[of "poly cs z"]]
by (simp add: norm_mult)
finally show ?thesis .
qed
with kp show ?case by blast
qed
text \<open>Offsetting the variable in a polynomial gives another of same degree\<close>
definition offset_poly :: "'a::comm_semiring_0 poly \<Rightarrow> 'a \<Rightarrow> 'a poly"
where "offset_poly p h = fold_coeffs (\<lambda>a q. smult h q + pCons a q) p 0"
lemma offset_poly_0: "offset_poly 0 h = 0"
by (simp add: offset_poly_def)
lemma offset_poly_pCons:
"offset_poly (pCons a p) h =
smult h (offset_poly p h) + pCons a (offset_poly p h)"
by (cases "p = 0 \<and> a = 0") (auto simp add: offset_poly_def)
lemma offset_poly_single [simp]: "offset_poly [:a:] h = [:a:]"
by (simp add: offset_poly_pCons offset_poly_0)
lemma poly_offset_poly: "poly (offset_poly p h) x = poly p (h + x)"
by (induct p) (auto simp add: offset_poly_0 offset_poly_pCons algebra_simps)
lemma offset_poly_eq_0_lemma: "smult c p + pCons a p = 0 \<Longrightarrow> p = 0"
by (induct p arbitrary: a) (simp, force)
lemma offset_poly_eq_0_iff [simp]: "offset_poly p h = 0 \<longleftrightarrow> p = 0"
proof
show "offset_poly p h = 0 \<Longrightarrow> p = 0"
proof(induction p)
case 0
then show ?case by blast
next
case (pCons a p)
then show ?case
by (metis offset_poly_eq_0_lemma offset_poly_pCons offset_poly_single)
qed
qed (simp add: offset_poly_0)
lemma degree_offset_poly [simp]: "degree (offset_poly p h) = degree p"
proof(induction p)
case 0
then show ?case
by (simp add: offset_poly_0)
next
case (pCons a p)
have "p \<noteq> 0 \<Longrightarrow> degree (offset_poly (pCons a p) h) = Suc (degree p)"
by (metis degree_add_eq_right degree_pCons_eq degree_smult_le le_imp_less_Suc offset_poly_eq_0_iff offset_poly_pCons pCons.IH)
then show ?case
by simp
qed
definition "psize p = (if p = 0 then 0 else Suc (degree p))"
lemma psize_eq_0_iff [simp]: "psize p = 0 \<longleftrightarrow> p = 0"
unfolding psize_def by simp
lemma poly_offset:
fixes p :: "'a::comm_ring_1 poly"
shows "\<exists>q. psize q = psize p \<and> (\<forall>x. poly q x = poly p (a + x))"
by (metis degree_offset_poly offset_poly_eq_0_iff poly_offset_poly psize_def)
text \<open>An alternative useful formulation of completeness of the reals\<close>
lemma real_sup_exists:
assumes ex: "\<exists>x. P x"
and bz: "\<exists>z. \<forall>x. P x \<longrightarrow> x < z"
shows "\<exists>s::real. \<forall>y. (\<exists>x. P x \<and> y < x) \<longleftrightarrow> y < s"
proof
from bz have "bdd_above (Collect P)"
by (force intro: less_imp_le)
then show "\<forall>y. (\<exists>x. P x \<and> y < x) \<longleftrightarrow> y < Sup (Collect P)"
using ex bz by (subst less_cSup_iff) auto
qed
subsection \<open>Fundamental theorem of algebra\<close>
lemma unimodular_reduce_norm:
assumes md: "cmod z = 1"
shows "cmod (z + 1) < 1 \<or> cmod (z - 1) < 1 \<or> cmod (z + \<i>) < 1 \<or> cmod (z - \<i>) < 1"
proof -
obtain x y where z: "z = Complex x y "
by (cases z) auto
from md z have xy: "x\<^sup>2 + y\<^sup>2 = 1"
by (simp add: cmod_def)
have False if "cmod (z + 1) \<ge> 1" "cmod (z - 1) \<ge> 1" "cmod (z + \<i>) \<ge> 1" "cmod (z - \<i>) \<ge> 1"
proof -
from that z xy have *: "2 * x \<le> 1" "2 * x \<ge> -1" "2 * y \<le> 1" "2 * y \<ge> -1"
by (simp_all add: cmod_def power2_eq_square algebra_simps)
then have "\<bar>2 * x\<bar> \<le> 1" "\<bar>2 * y\<bar> \<le> 1"
by simp_all
then have "\<bar>2 * x\<bar>\<^sup>2 \<le> 1\<^sup>2" "\<bar>2 * y\<bar>\<^sup>2 \<le> 1\<^sup>2"
by (metis abs_square_le_1 one_power2 power2_abs)+
with xy * show ?thesis
by (smt (verit, best) four_x_squared square_le_1)
qed
then show ?thesis
by force
qed
text \<open>Hence we can always reduce modulus of \<open>1 + b z^n\<close> if nonzero\<close>
lemma reduce_poly_simple:
assumes b: "b \<noteq> 0"
and n: "n \<noteq> 0"
shows "\<exists>z. cmod (1 + b * z^n) < 1"
using n
proof (induct n rule: nat_less_induct)
fix n
assume IH: "\<forall>m<n. m \<noteq> 0 \<longrightarrow> (\<exists>z. cmod (1 + b * z ^ m) < 1)"
assume n: "n \<noteq> 0"
let ?P = "\<lambda>z n. cmod (1 + b * z ^ n) < 1"
show "\<exists>z. ?P z n"
proof cases
assume "even n"
then obtain m where m: "n = 2 * m" and "m \<noteq> 0" "m < n"
using n by auto
with IH obtain z where z: "?P z m"
by blast
from z have "?P (csqrt z) n"
by (simp add: m power_mult)
then show ?thesis ..
next
assume "odd n"
then have "\<exists>m. n = Suc (2 * m)"
by presburger+
then obtain m where m: "n = Suc (2 * m)"
by blast
have 0: "cmod (complex_of_real (cmod b) / b) = 1"
using b by (simp add: norm_divide)
have "\<exists>v. cmod (complex_of_real (cmod b) / b + v^n) < 1"
proof (cases "cmod (complex_of_real (cmod b) / b + 1) < 1")
case True
then show ?thesis
by (metis power_one)
next
case F1: False
show ?thesis
proof (cases "cmod (complex_of_real (cmod b) / b - 1) < 1")
case True
with \<open>odd n\<close> show ?thesis
by (metis add_uminus_conv_diff neg_one_odd_power)
next
case F2: False
show ?thesis
proof (cases "cmod (complex_of_real (cmod b) / b + \<i>) < 1")
case T1: True
show ?thesis
proof (cases "even m")
case True
with T1 show ?thesis
by (rule_tac x="\<i>" in exI) (simp add: m power_mult)
next
case False
with T1 show ?thesis
by (rule_tac x="- \<i>" in exI) (simp add: m power_mult)
qed
next
case False
then have lt1: "cmod (of_real (cmod b) / b - \<i>) < 1"
using "0" F1 F2 unimodular_reduce_norm by blast
show ?thesis
proof (cases "even m")
case True
with m lt1 show ?thesis
by (rule_tac x="- \<i>" in exI) (simp add: power_mult)
next
case False
with m lt1 show ?thesis
by (rule_tac x="\<i>" in exI) (simp add: power_mult)
qed
qed
qed
qed
then obtain v where v: "cmod (complex_of_real (cmod b) / b + v^n) < 1"
by blast
let ?w = "v / complex_of_real (root n (cmod b))"
from odd_real_root_pow[OF \<open>odd n\<close>, of "cmod b"]
have 1: "?w ^ n = v^n / complex_of_real (cmod b)"
by (simp add: power_divide of_real_power[symmetric])
have 2:"cmod (complex_of_real (cmod b) / b) = 1"
using b by (simp add: norm_divide)
then have 3: "cmod (complex_of_real (cmod b) / b) \<ge> 0"
by simp
have 4: "cmod (complex_of_real (cmod b) / b) *
cmod (1 + b * (v ^ n / complex_of_real (cmod b))) <
cmod (complex_of_real (cmod b) / b) * 1"
apply (simp only: norm_mult[symmetric] distrib_left)
using b v
apply (simp add: 2)
done
show ?thesis
by (metis 1 mult_left_less_imp_less[OF 4 3])
qed
qed
text \<open>Bolzano-Weierstrass type property for closed disc in complex plane.\<close>
lemma metric_bound_lemma: "cmod (x - y) \<le> \<bar>Re x - Re y\<bar> + \<bar>Im x - Im y\<bar>"
using real_sqrt_sum_squares_triangle_ineq[of "Re x - Re y" 0 0 "Im x - Im y"]
unfolding cmod_def by simp
lemma Bolzano_Weierstrass_complex_disc:
assumes r: "\<forall>n. cmod (s n) \<le> r"
shows "\<exists>f z. strict_mono (f :: nat \<Rightarrow> nat) \<and> (\<forall>e >0. \<exists>N. \<forall>n \<ge> N. cmod (s (f n) - z) < e)"
proof -
from seq_monosub[of "Re \<circ> s"]
obtain f where f: "strict_mono f" "monoseq (\<lambda>n. Re (s (f n)))"
unfolding o_def by blast
from seq_monosub[of "Im \<circ> s \<circ> f"]
obtain g where g: "strict_mono g" "monoseq (\<lambda>n. Im (s (f (g n))))"
unfolding o_def by blast
let ?h = "f \<circ> g"
have "r \<ge> 0"
by (meson norm_ge_zero order_trans r)
have "\<forall>n. r + 1 \<ge> \<bar>Re (s n)\<bar>"
by (smt (verit, ccfv_threshold) abs_Re_le_cmod r)
then have conv1: "convergent (\<lambda>n. Re (s (f n)))"
by (metis Bseq_monoseq_convergent f(2) BseqI' real_norm_def)
have "\<forall>n. r + 1 \<ge> \<bar>Im (s n)\<bar>"
by (smt (verit) abs_Im_le_cmod r)
then have conv2: "convergent (\<lambda>n. Im (s (f (g n))))"
by (metis Bseq_monoseq_convergent g(2) BseqI' real_norm_def)
obtain x where x: "\<forall>r>0. \<exists>n0. \<forall>n\<ge>n0. \<bar>Re (s (f n)) - x\<bar> < r"
using conv1[unfolded convergent_def] LIMSEQ_iff real_norm_def by metis
obtain y where y: "\<forall>r>0. \<exists>n0. \<forall>n\<ge>n0. \<bar>Im (s (f (g n))) - y\<bar> < r"
using conv2[unfolded convergent_def] LIMSEQ_iff real_norm_def by metis
let ?w = "Complex x y"
from f(1) g(1) have hs: "strict_mono ?h"
unfolding strict_mono_def by auto
have "\<exists>N. \<forall>n\<ge>N. cmod (s (?h n) - ?w) < e" if "e > 0" for e
proof -
from that have e2: "e/2 > 0"
by simp
from x y e2
obtain N1 N2 where N1: "\<forall>n\<ge>N1. \<bar>Re (s (f n)) - x\<bar> < e / 2"
and N2: "\<forall>n\<ge>N2. \<bar>Im (s (f (g n))) - y\<bar> < e / 2"
by blast
have "cmod (s (?h n) - ?w) < e" if "n \<ge> N1 + N2" for n
proof -
from that have nN1: "g n \<ge> N1" and nN2: "n \<ge> N2"
using seq_suble[OF g(1), of n] by arith+
show ?thesis
using metric_bound_lemma[of "s (f (g n))" ?w] N1 N2 nN1 nN2 by fastforce
qed
then show ?thesis by blast
qed
with hs show ?thesis by blast
qed
text \<open>Polynomial is continuous.\<close>
lemma poly_cont:
fixes p :: "'a::{comm_semiring_0,real_normed_div_algebra} poly"
assumes ep: "e > 0"
shows "\<exists>d >0. \<forall>w. 0 < norm (w - z) \<and> norm (w - z) < d \<longrightarrow> norm (poly p w - poly p z) < e"
proof -
obtain q where "degree q = degree p" and q: "\<And>w. poly p w = poly q (w - z)"
by (metis add.commute degree_offset_poly diff_add_cancel poly_offset_poly)
show ?thesis unfolding q
proof (induct q)
case 0
then show ?case
using ep by auto
next
case (pCons c cs)
obtain m where m: "m > 0" "norm z \<le> 1 \<Longrightarrow> norm (poly cs z) \<le> m" for z
using poly_bound_exists[of 1 "cs"] by blast
with ep have em0: "e/m > 0"
by (simp add: field_simps)
obtain d where d: "d > 0" "d < 1" "d < e / m"
by (meson em0 field_lbound_gt_zero zero_less_one)
then have "\<And>w. norm (w - z) < d \<Longrightarrow> norm (w - z) * norm (poly cs (w - z)) < e"
by (smt (verit, del_insts) m mult_left_mono norm_ge_zero pos_less_divide_eq)
with d show ?case
by (force simp add: norm_mult)
qed
qed
text \<open>Hence a polynomial attains minimum on a closed disc
in the complex plane.\<close>
lemma poly_minimum_modulus_disc: "\<exists>z. \<forall>w. cmod w \<le> r \<longrightarrow> cmod (poly p z) \<le> cmod (poly p w)"
proof -
show ?thesis
proof (cases "r \<ge> 0")
case False
then show ?thesis
by (metis norm_ge_zero order.trans)
next
case True
then have mth1: "\<exists>x z. cmod z \<le> r \<and> cmod (poly p z) = - x"
by (metis add.inverse_inverse norm_zero)
obtain s where s: "\<forall>y. (\<exists>x. (\<exists>z. cmod z \<le> r \<and> cmod (poly p z) = - x) \<and> y < x) \<longleftrightarrow> y < s"
by (smt (verit, del_insts) real_sup_exists[OF mth1] norm_zero zero_less_norm_iff)
let ?m = "- s"
have s1: "(\<exists>z. cmod z \<le> r \<and> - (- cmod (poly p z)) < y) \<longleftrightarrow> ?m < y" for y
by (metis add.inverse_inverse minus_less_iff s)
then have s1m: "\<And>z. cmod z \<le> r \<Longrightarrow> cmod (poly p z) \<ge> ?m"
by force
have "\<exists>z. cmod z \<le> r \<and> cmod (poly p z) < - s + 1 / real (Suc n)" for n
using s1[of "?m + 1/real (Suc n)"] by simp
then obtain g where g: "\<forall>n. cmod (g n) \<le> r" "\<forall>n. cmod (poly p (g n)) <?m + 1 /real(Suc n)"
by metis
from Bolzano_Weierstrass_complex_disc[OF g(1)]
obtain f::"nat \<Rightarrow> nat" and z where fz: "strict_mono f" "\<forall>e>0. \<exists>N. \<forall>n\<ge>N. cmod (g (f n) - z) < e"
by blast
{
fix w
assume wr: "cmod w \<le> r"
let ?e = "\<bar>cmod (poly p z) - ?m\<bar>"
{
assume e: "?e > 0"
then have e2: "?e/2 > 0"
by simp
with poly_cont obtain d
where "d > 0" and d: "\<And>w. 0<cmod (w - z)\<and> cmod(w - z) < d \<longrightarrow> cmod(poly p w - poly p z) < ?e/2"
by blast
have 1: "cmod(poly p w - poly p z) < ?e / 2" if w: "cmod (w - z) < d" for w
using d[of w] w e by (cases "w = z") simp_all
from fz(2) \<open>d > 0\<close> obtain N1 where N1: "\<forall>n\<ge>N1. cmod (g (f n) - z) < d"
by blast
from reals_Archimedean2 obtain N2 :: nat where N2: "2/?e < real N2"
by blast
have 2: "cmod (poly p (g (f (N1 + N2))) - poly p z) < ?e/2"
using N1 1 by auto
have 0: "a < e2 \<Longrightarrow> \<bar>b - m\<bar> < e2 \<Longrightarrow> 2 * e2 \<le> \<bar>b - m\<bar> + a \<Longrightarrow> False"
for a b e2 m :: real
by arith
from seq_suble[OF fz(1), of "N1 + N2"]
have 00: "?m + 1 / real (Suc (f (N1 + N2))) \<le> ?m + 1 / real (Suc (N1 + N2))"
by (simp add: frac_le)
from N2 e2 less_imp_inverse_less[of "2/?e" "real (Suc (N1 + N2))"]
have "?e/2 > 1/ real (Suc (N1 + N2))"
by (simp add: inverse_eq_divide)
with order_less_le_trans[OF _ 00]
have 1: "\<bar>cmod (poly p (g (f (N1 + N2)))) - ?m\<bar> < ?e/2"
using g s1 by (smt (verit))
with 0[OF 2] have False
by (smt (verit) field_sum_of_halves norm_triangle_ineq3)
}
then have "?e = 0"
by auto
with s1m[OF wr] have "cmod (poly p z) \<le> cmod (poly p w)"
by simp
}
then show ?thesis by blast
qed
qed
text \<open>Nonzero polynomial in z goes to infinity as z does.\<close>
lemma poly_infinity:
fixes p:: "'a::{comm_semiring_0,real_normed_div_algebra} poly"
assumes ex: "p \<noteq> 0"
shows "\<exists>r. \<forall>z. r \<le> norm z \<longrightarrow> d \<le> norm (poly (pCons a p) z)"
using ex
proof (induct p arbitrary: a d)
case 0
then show ?case by simp
next
case (pCons c cs a d)
show ?case
proof (cases "cs = 0")
case False
with pCons.hyps obtain r where r: "\<forall>z. r \<le> norm z \<longrightarrow> d + norm a \<le> norm (poly (pCons c cs) z)"
by blast
let ?r = "1 + \<bar>r\<bar>"
have "d \<le> norm (poly (pCons a (pCons c cs)) z)" if "1 + \<bar>r\<bar> \<le> norm z" for z
proof -
have "d \<le> norm(z * poly (pCons c cs) z) - norm a"
by (smt (verit, best) norm_ge_zero mult_less_cancel_right2 norm_mult r that)
with norm_diff_ineq add.commute
show ?thesis
by (metis order.trans poly_pCons)
qed
then show ?thesis by blast
next
case True
have "d \<le> norm (poly (pCons a (pCons c cs)) z)"
if "(\<bar>d\<bar> + norm a) / norm c \<le> norm z" for z :: 'a
proof -
have "\<bar>d\<bar> + norm a \<le> norm (z * c)"
by (metis that True norm_mult pCons.hyps(1) pos_divide_le_eq zero_less_norm_iff)
also have "\<dots> \<le> norm (a + z * c) + norm a"
by (simp add: add.commute norm_add_leD)
finally show ?thesis
using True by auto
qed
then show ?thesis by blast
qed
qed
text \<open>Hence polynomial's modulus attains its minimum somewhere.\<close>
lemma poly_minimum_modulus: "\<exists>z.\<forall>w. cmod (poly p z) \<le> cmod (poly p w)"
proof (induct p)
case 0
then show ?case by simp
next
case (pCons c cs)
show ?case
proof (cases "cs = 0")
case False
from poly_infinity[OF False, of "cmod (poly (pCons c cs) 0)" c]
obtain r where r: "cmod (poly (pCons c cs) 0) \<le> cmod (poly (pCons c cs) z)"
if "r \<le> cmod z" for z
by blast
from poly_minimum_modulus_disc[of "\<bar>r\<bar>" "pCons c cs"] show ?thesis
by (smt (verit, del_insts) order.trans linorder_linear r)
qed (use pCons.hyps in auto)
qed
text \<open>Constant function (non-syntactic characterization).\<close>
definition "constant f \<longleftrightarrow> (\<forall>x y. f x = f y)"
lemma nonconstant_length: "\<not> constant (poly p) \<Longrightarrow> psize p \<ge> 2"
by (induct p) (auto simp: constant_def psize_def)
lemma poly_replicate_append: "poly (monom 1 n * p) (x::'a::comm_ring_1) = x^n * poly p x"
by (simp add: poly_monom)
text \<open>Decomposition of polynomial, skipping zero coefficients after the first.\<close>
lemma poly_decompose_lemma:
assumes nz: "\<not> (\<forall>z. z \<noteq> 0 \<longrightarrow> poly p z = (0::'a::idom))"
shows "\<exists>k a q. a \<noteq> 0 \<and> Suc (psize q + k) = psize p \<and> (\<forall>z. poly p z = z^k * poly (pCons a q) z)"
unfolding psize_def
using nz
proof (induct p)
case 0
then show ?case by simp
next
case (pCons c cs)
show ?case
proof (cases "c = 0")
case True
from pCons.hyps pCons.prems True show ?thesis
apply auto
apply (rule_tac x="k+1" in exI)
apply (rule_tac x="a" in exI)
apply clarsimp
apply (rule_tac x="q" in exI)
apply auto
done
qed force
qed
lemma poly_decompose:
fixes p :: "'a::idom poly"
assumes nc: "\<not> constant (poly p)"
shows "\<exists>k a q. a \<noteq> 0 \<and> k \<noteq> 0 \<and>
psize q + k + 1 = psize p \<and>
(\<forall>z. poly p z = poly p 0 + z^k * poly (pCons a q) z)"
using nc
proof (induct p)
case 0
then show ?case
by (simp add: constant_def)
next
case (pCons c cs)
have "\<not> (\<forall>z. z \<noteq> 0 \<longrightarrow> poly cs z = 0)"
by (smt (verit) constant_def mult_eq_0_iff pCons.prems poly_pCons)
from poly_decompose_lemma[OF this]
obtain k a q where *: "a \<noteq> 0 \<and>
Suc (psize q + k) = psize cs \<and> (\<forall>z. poly cs z = z ^ k * poly (pCons a q) z)"
by blast
then have "psize q + k + 2 = psize (pCons c cs)"
by (auto simp add: psize_def split: if_splits)
then show ?case
using "*" by force
qed
text \<open>Fundamental theorem of algebra\<close>
lemma fundamental_theorem_of_algebra:
assumes nc: "\<not> constant (poly p)"
shows "\<exists>z::complex. poly p z = 0"
using nc
proof (induct "psize p" arbitrary: p rule: less_induct)
case less
let ?p = "poly p"
let ?ths = "\<exists>z. ?p z = 0"
from nonconstant_length[OF less(2)] have n2: "psize p \<ge> 2" .
from poly_minimum_modulus obtain c where c: "\<forall>w. cmod (?p c) \<le> cmod (?p w)"
by blast
show ?ths
proof (cases "?p c = 0")
case True
then show ?thesis by blast
next
case False
obtain q where q: "psize q = psize p" "\<forall>x. poly q x = ?p (c + x)"
using poly_offset[of p c] by blast
then have qnc: "\<not> constant (poly q)"
by (metis (no_types, opaque_lifting) add.commute constant_def diff_add_cancel less.prems)
from q(2) have pqc0: "?p c = poly q 0"
by simp
from c pqc0 have cq0: "\<forall>w. cmod (poly q 0) \<le> cmod (?p w)"
by simp
let ?a0 = "poly q 0"
from False pqc0 have a00: "?a0 \<noteq> 0"
by simp
from a00 have qr: "\<forall>z. poly q z = poly (smult (inverse ?a0) q) z * ?a0"
by simp
let ?r = "smult (inverse ?a0) q"
have lgqr: "psize q = psize ?r"
by (simp add: a00 psize_def)
have rnc: "\<not> constant (poly ?r)"
using constant_def qnc qr by fastforce
have r01: "poly ?r 0 = 1"
by (simp add: a00)
have mrmq_eq: "cmod (poly ?r w) < 1 \<longleftrightarrow> cmod (poly q w) < cmod ?a0" for w
by (smt (verit, del_insts) a00 mult_less_cancel_right2 norm_mult qr zero_less_norm_iff)
from poly_decompose[OF rnc] obtain k a s where
kas: "a \<noteq> 0" "k \<noteq> 0" "psize s + k + 1 = psize ?r"
"\<forall>z. poly ?r z = poly ?r 0 + z^k* poly (pCons a s) z" by blast
have "\<exists>w. cmod (poly ?r w) < 1"
proof (cases "psize p = k + 1")
case True
with kas q have s0: "s = 0"
by (simp add: lgqr)
with reduce_poly_simple kas show ?thesis
by (metis mult.commute mult.right_neutral poly_1 poly_smult r01 smult_one)
next
case False note kn = this
from kn kas(3) q(1) lgqr have k1n: "k + 1 < psize p"
by simp
have 01: "\<not> constant (poly (pCons 1 (monom a (k - 1))))"
unfolding constant_def poly_pCons poly_monom
by (metis add_cancel_left_right kas(1) mult.commute mult_cancel_right2 power_one)
have 02: "k + 1 = psize (pCons 1 (monom a (k - 1)))"
using kas by (simp add: psize_def degree_monom_eq)
from less(1) [OF _ 01] k1n 02
obtain w where w: "1 + w^k * a = 0"
by (metis kas(2) mult.commute mult.left_commute poly_monom poly_pCons power_eq_if)
from poly_bound_exists[of "cmod w" s] obtain m where
m: "m > 0" "\<forall>z. cmod z \<le> cmod w \<longrightarrow> cmod (poly s z) \<le> m" by blast
have "w \<noteq> 0"
using kas(2) w by (auto simp add: power_0_left)
from w have wm1: "w^k * a = - 1"
by (simp add: add_eq_0_iff)
have inv0: "0 < inverse (cmod w ^ (k + 1) * m)"
by (simp add: \<open>w \<noteq> 0\<close> m(1))
with field_lbound_gt_zero[OF zero_less_one] obtain t where
t: "t > 0" "t < 1" "t < inverse (cmod w ^ (k + 1) * m)" by blast
let ?ct = "complex_of_real t"
let ?w = "?ct * w"
have "1 + ?w^k * (a + ?w * poly s ?w) = 1 + ?ct^k * (w^k * a) + ?w^k * ?w * poly s ?w"
using kas(1) by (simp add: algebra_simps power_mult_distrib)
also have "\<dots> = complex_of_real (1 - t^k) + ?w^k * ?w * poly s ?w"
unfolding wm1 by simp
finally have "cmod (1 + ?w^k * (a + ?w * poly s ?w)) =
cmod (complex_of_real (1 - t^k) + ?w^k * ?w * poly s ?w)"
by metis
with norm_triangle_ineq[of "complex_of_real (1 - t^k)" "?w^k * ?w * poly s ?w"]
have 11: "cmod (1 + ?w^k * (a + ?w * poly s ?w)) \<le> \<bar>1 - t^k\<bar> + cmod (?w^k * ?w * poly s ?w)"
unfolding norm_of_real by simp
have ath: "\<And>x t::real. 0 \<le> x \<Longrightarrow> x < t \<Longrightarrow> t \<le> 1 \<Longrightarrow> \<bar>1 - t\<bar> + x < 1"
by arith
have tw: "cmod ?w \<le> cmod w"
by (smt (verit) mult_le_cancel_right2 norm_ge_zero norm_mult norm_of_real t)
have "t * (cmod w ^ (k + 1) * m) < 1"
by (smt (verit, best) inv0 inverse_positive_iff_positive left_inverse mult_strict_right_mono t(3))
with zero_less_power[OF t(1), of k] have 30: "t^k * (t* (cmod w ^ (k + 1) * m)) < t^k"
by simp
have "cmod (?w^k * ?w * poly s ?w) = t^k * (t* (cmod w ^ (k + 1) * cmod (poly s ?w)))"
using \<open>w \<noteq> 0\<close> t(1) by (simp add: algebra_simps norm_power norm_mult)
with 30 have 120: "cmod (?w^k * ?w * poly s ?w) < t^k"
by (smt (verit, ccfv_SIG) m(2) mult_left_mono norm_ge_zero t(1) tw zero_le_power)
from power_strict_mono[OF t(2), of k] t(1) kas(2) have 121: "t^k \<le> 1"
by auto
from ath[OF norm_ge_zero[of "?w^k * ?w * poly s ?w"] 120 121]
show ?thesis
by (smt (verit) "11" kas(4) poly_pCons r01)
qed
with cq0 q(2) show ?thesis
by (smt (verit) mrmq_eq)
qed
qed
text \<open>Alternative version with a syntactic notion of constant polynomial.\<close>
lemma fundamental_theorem_of_algebra_alt:
assumes nc: "\<not> (\<exists>a l. a \<noteq> 0 \<and> l = 0 \<and> p = pCons a l)"
shows "\<exists>z. poly p z = (0::complex)"
proof (rule ccontr)
assume N: "\<nexists>z. poly p z = 0"
then have "\<not> constant (poly p)"
unfolding constant_def
by (metis (no_types, opaque_lifting) nc poly_pcompose pcompose_0' pcompose_const poly_0_coeff_0
poly_all_0_iff_0 poly_diff right_minus_eq)
then show False
using N fundamental_theorem_of_algebra by blast
qed
subsection \<open>Nullstellensatz, degrees and divisibility of polynomials\<close>
lemma nullstellensatz_lemma:
fixes p :: "complex poly"
assumes "\<forall>x. poly p x = 0 \<longrightarrow> poly q x = 0"
and "degree p = n"
and "n \<noteq> 0"
shows "p dvd (q ^ n)"
using assms
proof (induct n arbitrary: p q rule: nat_less_induct)
fix n :: nat
fix p q :: "complex poly"
assume IH: "\<forall>m<n. \<forall>p q.
(\<forall>x. poly p x = (0::complex) \<longrightarrow> poly q x = 0) \<longrightarrow>
degree p = m \<longrightarrow> m \<noteq> 0 \<longrightarrow> p dvd (q ^ m)"
and pq0: "\<forall>x. poly p x = 0 \<longrightarrow> poly q x = 0"
and dpn: "degree p = n"
and n0: "n \<noteq> 0"
from dpn n0 have pne: "p \<noteq> 0" by auto
show "p dvd (q ^ n)"
proof (cases "\<exists>a. poly p a = 0")
case True
then obtain a where a: "poly p a = 0" ..
have ?thesis if oa: "order a p \<noteq> 0"
proof -
let ?op = "order a p"
from pne have ap: "([:- a, 1:] ^ ?op) dvd p" "\<not> [:- a, 1:] ^ (Suc ?op) dvd p"
using order by blast+
note oop = order_degree[OF pne, unfolded dpn]
show ?thesis
proof (cases "q = 0")
case True
with n0 show ?thesis by (simp add: power_0_left)
next
case False
from pq0[rule_format, OF a, unfolded poly_eq_0_iff_dvd]
obtain r where r: "q = [:- a, 1:] * r" by (rule dvdE)
from ap(1) obtain s where s: "p = [:- a, 1:] ^ ?op * s"
by (rule dvdE)
have sne: "s \<noteq> 0"
using s pne by auto
show ?thesis
proof (cases "degree s = 0")
case True
then obtain k where kpn: "s = [:k:]"
by (cases s) (auto split: if_splits)
from sne kpn have k: "k \<noteq> 0" by simp
let ?w = "([:1/k:] * ([:-a,1:] ^ (n - ?op))) * (r ^ n)"
have "q^n = [:- a, 1:] ^ n * r ^ n"
using power_mult_distrib r by blast
also have "... = [:- a, 1:] ^ order a p * [:k:] * ([:1 / k:] * [:- a, 1:] ^ (n - order a p) * r ^ n)"
using k oop [of a] by (simp flip: power_add)
also have "... = p * ?w"
by (metis s kpn)
finally show ?thesis
unfolding dvd_def by blast
next
case False
with sne dpn s oa have dsn: "degree s < n"
by (metis add_diff_cancel_right' degree_0 degree_linear_power degree_mult_eq gr0I zero_less_diff)
have "poly r x = 0" if h: "poly s x = 0" for x
proof -
have "x \<noteq> a"
by (metis ap(2) dvd_refl mult_dvd_mono poly_eq_0_iff_dvd power_Suc power_commutes s that)
moreover have "poly p x = 0"
by (metis (no_types) mult_eq_0_iff poly_mult s that)
ultimately show ?thesis
using pq0 r by auto
qed
with False IH dsn obtain u where u: "r ^ (degree s) = s * u"
by blast
then have u': "\<And>x. poly s x * poly u x = poly r x ^ degree s"
by (simp only: poly_mult[symmetric] poly_power[symmetric])
have "q^n = [:- a, 1:] ^ n * r ^ n"
using power_mult_distrib r by blast
also have "... = [:- a, 1:] ^ order a p * (s * u * ([:- a, 1:] ^ (n - order a p) * r ^ (n - degree s)))"
by (smt (verit, del_insts) s u mult_ac power_add add_diff_cancel_right' degree_linear_power degree_mult_eq dpn mult_zero_left)
also have "... = p * (u * ([:-a,1:] ^ (n - ?op))) * (r ^ (n - degree s))"
using s by force
finally show ?thesis
unfolding dvd_def by auto
qed
qed
qed
then show ?thesis
using a order_root pne by blast
next
case False
then show ?thesis
using dpn n0 fundamental_theorem_of_algebra_alt[of p]
by fastforce
qed
qed
lemma nullstellensatz_univariate:
"(\<forall>x. poly p x = (0::complex) \<longrightarrow> poly q x = 0) \<longleftrightarrow>
p dvd (q ^ (degree p)) \<or> (p = 0 \<and> q = 0)"
proof -
consider "p = 0" | "p \<noteq> 0" "degree p = 0" | n where "p \<noteq> 0" "degree p = Suc n"
by (cases "degree p") auto
then show ?thesis
proof cases
case p: 1
then have "(\<forall>x. poly p x = (0::complex) \<longrightarrow> poly q x = 0) \<longleftrightarrow> q = 0"
by (auto simp add: poly_all_0_iff_0)
with p show ?thesis
by force
next
case dp: 2
then show ?thesis
by (meson dvd_trans is_unit_iff_degree poly_eq_0_iff_dvd unit_imp_dvd)
next
case dp: 3
have False if "p dvd (q ^ (Suc n))" "poly p x = 0" "poly q x \<noteq> 0" for x
by (metis dvd_trans poly_eq_0_iff_dvd poly_power power_eq_0_iff that)
with dp nullstellensatz_lemma[of p q "degree p"] show ?thesis
by auto
qed
qed
text \<open>Useful lemma\<close>
lemma constant_degree:
fixes p :: "'a::{idom,ring_char_0} poly"
shows "constant (poly p) \<longleftrightarrow> degree p = 0" (is "?lhs = ?rhs")
proof
show ?rhs if ?lhs
proof -
from that[unfolded constant_def, rule_format, of _ "0"]
have "poly p = poly [:poly p 0:]"
by auto
then show ?thesis
by (metis degree_pCons_0 poly_eq_poly_eq_iff)
qed
show ?lhs if ?rhs
unfolding constant_def
by (metis degree_eq_zeroE pcompose_const poly_0 poly_pcompose that)
qed
text \<open>Arithmetic operations on multivariate polynomials.\<close>
lemma mpoly_base_conv:
fixes x :: "'a::comm_ring_1"
shows "0 = poly 0 x" "c = poly [:c:] x" "x = poly [:0,1:] x"
by simp_all
lemma mpoly_norm_conv:
fixes x :: "'a::comm_ring_1"
shows "poly [:0:] x = poly 0 x" "poly [:poly 0 y:] x = poly 0 x"
by simp_all
lemma mpoly_sub_conv:
fixes x :: "'a::comm_ring_1"
shows "poly p x - poly q x = poly p x + -1 * poly q x"
by simp
lemma poly_pad_rule: "poly p x = 0 \<Longrightarrow> poly (pCons 0 p) x = 0"
by simp
lemma poly_cancel_eq_conv:
fixes x :: "'a::field"
shows "x = 0 \<Longrightarrow> a \<noteq> 0 \<Longrightarrow> y = 0 \<longleftrightarrow> a * y - b * x = 0"
by auto
lemma poly_divides_pad_rule:
fixes p:: "('a::comm_ring_1) poly"
assumes pq: "p dvd q"
shows "p dvd (pCons 0 q)"
by (metis add_0 dvd_def mult_pCons_right pq smult_0_left)
lemma poly_divides_conv0:
fixes p:: "'a::field poly"
assumes lgpq: "degree q < degree p" and lq: "p \<noteq> 0"
shows "p dvd q \<longleftrightarrow> q = 0"
using lgpq mod_poly_less by fastforce
lemma poly_divides_conv1:
fixes p :: "'a::field poly"
assumes a0: "a \<noteq> 0"
and pp': "p dvd p'"
and qrp': "smult a q - p' = r"
shows "p dvd q \<longleftrightarrow> p dvd r"
by (metis a0 diff_add_cancel dvd_add_left_iff dvd_smult_iff pp' qrp')
lemma basic_cqe_conv1:
"(\<exists>x. poly p x = 0 \<and> poly 0 x \<noteq> 0) \<longleftrightarrow> False"
"(\<exists>x. poly 0 x \<noteq> 0) \<longleftrightarrow> False"
"(\<exists>x. poly [:c:] x \<noteq> 0) \<longleftrightarrow> c \<noteq> 0"
"(\<exists>x. poly 0 x = 0) \<longleftrightarrow> True"
"(\<exists>x. poly [:c:] x = 0) \<longleftrightarrow> c = 0"
by simp_all
lemma basic_cqe_conv2:
assumes l: "p \<noteq> 0"
shows "\<exists>x. poly (pCons a (pCons b p)) x = (0::complex)"
by (meson fundamental_theorem_of_algebra_alt l pCons_eq_0_iff pCons_eq_iff)
lemma basic_cqe_conv_2b: "(\<exists>x. poly p x \<noteq> (0::complex)) \<longleftrightarrow> p \<noteq> 0"
by (metis poly_all_0_iff_0)
lemma basic_cqe_conv3:
fixes p q :: "complex poly"
assumes l: "p \<noteq> 0"
shows "(\<exists>x. poly (pCons a p) x = 0 \<and> poly q x \<noteq> 0) \<longleftrightarrow> \<not> (pCons a p) dvd (q ^ psize p)"
by (metis degree_pCons_eq_if l nullstellensatz_univariate pCons_eq_0_iff psize_def)
lemma basic_cqe_conv4:
fixes p q :: "complex poly"
assumes h: "\<And>x. poly (q ^ n) x = poly r x"
shows "p dvd (q ^ n) \<longleftrightarrow> p dvd r"
by (metis (no_types) basic_cqe_conv_2b h poly_diff right_minus_eq)
lemma poly_const_conv:
fixes x :: "'a::comm_ring_1"
shows "poly [:c:] x = y \<longleftrightarrow> c = y"
by simp
end
|
/-
Copyright (c) 2019 Michael Howes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Michael Howes
-/
import group_theory.free_group
import group_theory.quotient_group
/-!
# Defining a group given by generators and relations
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
Given a subset `rels` of relations of the free group on a type `α`, this file constructs the group
given by generators `x : α` and relations `r ∈ rels`.
## Main definitions
* `presented_group rels`: the quotient group of the free group on a type `α` by a subset `rels` of
relations of the free group on `α`.
* `of`: The canonical map from `α` to a presented group with generators `α`.
* `to_group f`: the canonical group homomorphism `presented_group rels → G`, given a function
`f : α → G` from a type `α` to a group `G` which satisfies the relations `rels`.
## Tags
generators, relations, group presentations
-/
variables {α : Type*}
/-- Given a set of relations, rels, over a type `α`, presented_group constructs the group with
generators `x : α` and relations `rels` as a quotient of free_group `α`.-/
def presented_group (rels : set (free_group α)) :=
free_group α ⧸ subgroup.normal_closure rels
namespace presented_group
instance (rels : set (free_group α)) : group (presented_group (rels)) :=
quotient_group.quotient.group _
/-- `of` is the canonical map from `α` to a presented group with generators `x : α`. The term `x` is
mapped to the equivalence class of the image of `x` in `free_group α`. -/
def of {rels : set (free_group α)} (x : α) : presented_group rels :=
quotient_group.mk (free_group.of x)
section to_group
/-
Presented groups satisfy a universal property. If `G` is a group and `f : α → G` is a map such that
the images of `f` satisfy all the given relations, then `f` extends uniquely to a group homomorphism
from `presented_group rels` to `G`.
-/
variables {G : Type*} [group G] {f : α → G} {rels : set (free_group α)}
local notation `F` := free_group.lift f
variable (h : ∀ r ∈ rels, F r = 1)
lemma closure_rels_subset_ker : subgroup.normal_closure rels ≤ monoid_hom.ker F :=
subgroup.normal_closure_le_normal (λ x w, (monoid_hom.mem_ker _).2 (h x w))
lemma to_group_eq_one_of_mem_closure : ∀ x ∈ subgroup.normal_closure rels, F x = 1 :=
λ x w, (monoid_hom.mem_ker _).1 $ closure_rels_subset_ker h w
/-- The extension of a map `f : α → G` that satisfies the given relations to a group homomorphism
from `presented_group rels → G`. -/
def to_group : presented_group rels →* G :=
quotient_group.lift (subgroup.normal_closure rels) F (to_group_eq_one_of_mem_closure h)
@[simp] lemma to_group.of {x : α} : to_group h (of x) = f x := free_group.lift.of
theorem to_group.unique (g : presented_group rels →* G)
(hg : ∀ x : α, g (of x) = f x) : ∀ {x}, g x = to_group h x :=
λ x, quotient_group.induction_on x
(λ _, free_group.lift.unique (g.comp (quotient_group.mk' _)) hg)
end to_group
instance (rels : set (free_group α)) : inhabited (presented_group rels) := ⟨1⟩
end presented_group
|
theory Reverse
imports MainRLT
begin
fun T_append :: "'a list \<Rightarrow> 'a list \<Rightarrow> nat" where
"T_append [] ys = 1" |
"T_append (x#xs) ys = T_append xs ys + 1"
fun T_rev :: "'a list \<Rightarrow> nat" where
"T_rev [] = 1" |
"T_rev (x#xs) = T_rev xs + T_append (rev xs) [x] + 1"
lemma T_append: "T_append xs ys = length xs + 1"
by(induction xs) auto
lemma T_rev: "T_rev xs \<le> (length xs + 1)^2"
by(induction xs) (auto simp: T_append power2_eq_square)
fun itrev :: "'a list \<Rightarrow> 'a list \<Rightarrow> 'a list" where
"itrev [] ys = ys" |
"itrev (x#xs) ys = itrev xs (x # ys)"
lemma itrev: "itrev xs ys = rev xs @ ys"
by(induction xs arbitrary: ys) auto
lemma itrev_Nil: "itrev xs [] = rev xs"
by(simp add: itrev)
fun T_itrev :: "'a list \<Rightarrow> 'a list \<Rightarrow> nat" where
"T_itrev [] ys = 1" |
"T_itrev (x#xs) ys = T_itrev xs (x # ys) + 1"
lemma T_itrev: "T_itrev xs ys = length xs + 1"
by(induction xs arbitrary: ys) auto
end |
62 % of adults in the United States celebrate the holidays. 58 million pounds of chocolate candy are bought during Valenties´s day week. This time I will celebrete Valentine´s day on the beach with my friends drinking delicious Strawberry Coctail with Litchi and Rose peppercorns. I tried it before at the restaurant La Grassa in Sao Paulo and since then I dreamed about doing it by myself. I hope you will like it and can do it for your "valenine". Enjoy and wish all of you lots of love. Thank you Bori for a great time in La Grassa, every time I will drink Strawberry Cocktail I will think about you.
Mix strawberries, litchis, honey, mineral water and 15 rose peppercorns in a blender. Serve up in a glass and garnish with pink peppercorns. If you wish you can add vodka. |
[STATEMENT]
lemma [code abstract]: "vec_nth (rowvector v) = rowvector_row v"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. ($) (rowvector v) = rowvector_row v
[PROOF STEP]
unfolding rowvector_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. ($) (\<chi>i. vec_lambda (($) v)) = rowvector_row v
[PROOF STEP]
unfolding rowvector_row_def[abs_def]
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. ($) (\<chi>i. vec_lambda (($) v)) = (\<lambda>i. vec_lambda (($) v))
[PROOF STEP]
by auto |
! This file is part of mstore.
! SPDX-Identifier: Apache-2.0
!
! Licensed under the Apache License, Version 2.0 (the "License");
! you may not use this file except in compliance with the License.
! You may obtain a copy of the License at
!
! http://www.apache.org/licenses/LICENSE-2.0
!
! Unless required by applicable law or agreed to in writing, software
! distributed under the License is distributed on an "AS IS" BASIS,
! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
! See the License for the specific language governing permissions and
! limitations under the License.
module mstore_version
implicit none
private
public :: mstore_version_string, mstore_version_compact
public :: get_mstore_version
!> String representation of the mstore version
character(len=*), parameter :: mstore_version_string = "0.2.0"
!> Numeric representation of the mstore version
integer, parameter :: mstore_version_compact(3) = [0, 2, 0]
contains
!> Getter function to retrieve mstore version
subroutine get_mstore_version(major, minor, patch, string)
!> Major version number of the mstore version
integer, intent(out), optional :: major
!> Minor version number of the mstore version
integer, intent(out), optional :: minor
!> Patch version number of the mstore version
integer, intent(out), optional :: patch
!> String representation of the mstore version
character(len=:), allocatable, intent(out), optional :: string
if (present(major)) then
major = mstore_version_compact(1)
end if
if (present(minor)) then
minor = mstore_version_compact(2)
end if
if (present(patch)) then
patch = mstore_version_compact(3)
end if
if (present(string)) then
string = mstore_version_string
end if
end subroutine get_mstore_version
end module mstore_version
|
# Kernel Method
## Polynomial Regression
basic linear regression with one variable:
$$y=\theta_{0} + \theta_{1}x$$
what if linear model could not nicely fit training examples?<br>
we can naturally extend linear model to polynomial model, for example:
$$y=\theta_{0} + \theta_{1}x + \theta_{2}x^{2} + \theta_{3}x^{3}$$
this method can be conclude as: map original attibutes x to some new set of quantities $\phi(x)$ (called features), and use the same set of model.
### least mean squares with features
let $\phi : \mathbb{R}^{d} \to \mathbb{R}^{p}$ be a feature map, then original batch gradient descent:
$$\theta := \theta + \alpha\sum_{i=1}^{n}(y^{(i)} - \theta^{T}x^{(i)})x^{(i)}$$
using features:
$$\theta := \theta + \alpha\sum_{i=1}^{n}(y^{(i)} - \theta^{T}\phi(x^{(i)}))\phi(x^{(i)})$$
the above becomes computationally expensive when $\phi(x)$ is high dimensional.<br>
but we can observe that, if at some point , $\theta$ can be represented as:
$$\theta = \sum_{i=1}^{n}\beta_{i}\phi(x^{(i)})$$
then in the next round:
$$
\begin{equation}
\begin{split}
\theta &:= \theta + \alpha\sum_{i=1}^{n}(y^{(i)} - \theta^{T}\phi(x^{(i)}))\phi(x^{(i)}) \\
&=\sum_{i=1}^{n}\beta_{i}\phi(x^{(i)}) + \alpha\sum_{i=1}^{n}(y^{(i)} - \theta^{T}\phi(x^{(i)}))\phi(x^{(i)}) \\
&=\sum_{i=1}^{n}(\beta_{i} + \alpha(y^{(i)} - \theta^{T}\phi(x^{(i)})))\phi(x^{(i)})
\end{split}
\end{equation}
$$
$\theta$ can be also represented as a linear representation of $\phi(x^{(i)})$<br>
we can then derive $\beta$'s update rule:
$$\beta_{i} := \beta_{i} + \alpha(y^{(i)} - \sum_{j=1}^{n}\beta_{j}\phi(x^{(j)})^{T}\phi(x^{(i)}))$$
we only need to compute $\left \langle \phi(x^{(j)}), \phi(x^{(i)}) \right \rangle = \phi(x^{(j)})^{T}\phi(x^{(i)}))$ to update parameters no matter how high the feature dimension p is.
### kernel
we define the kernel corresponding to the feature map $\phi$ as a function that satisfying:
$$K(x, z) := \left \langle \phi(x), \phi(z) \right \rangle$$
define the kernel matrix:
$$K_{ij} = K(x^{(i)},x^{(j)})$$
properties of kernel matrix:
1. symmetric, since $\phi(x)^{T}\phi(z) = \phi(z)^{T}\phi(x)$.
2. positive semidefinite:
$$
\begin{equation}
\begin{split}
z^{T}Kz=&\sum_{i}\sum_{j}z_{i}K_{ij}z_{j}\\
=&\sum_{i}\sum_{j}z_{i}\phi(x^{(i)})^{T}\phi(x^{(j)})z_{j}\\
=&\sum_{i}\sum_{j}z_{i}\sum_{k}\phi_{k}(x^{(i)})\phi_{k}(x^{(j)})z_{j}\\
=&\sum_{k}\sum_{i}\sum_{j}z_{i}\phi_{k}(x^{(i)})\phi_{k}(x^{(j)})z_{j}\\
=&\sum_{k}\left(\sum_{i}z_{i}\phi_{k}(x^{(i)})\right)^2\\
\ge&\ 0
\end{split}
\end{equation}
$$
in the other hand, we have sufficient conditions for valid kernels:
(mercer): let $ K: \mathbb{R}^{d} \times \mathbb{R}^{d} \mapsto \mathbb{R}$. then for K be a valid kernel, it is necessary and sufficient that for any $\left \{ x^{(1)},...,x^{(n)} \right \} $, the corresponding kernel matrix is symmetric positive semi-definite.
proof t.b.c.
## support vector machine
### Margins
consider logistic regression, where the probability $p(y=1|x;\theta)$ is modeled by $h_{\theta}(x)=\sigma(\theta^{T}x)$. we predict 1 on an input x if and only if $\theta^{T}x >= 0.5$, the larger $\theta^{T}x$ is, the more confidence we are.<br>
the distance from the hyperplane is important.
functional margin:
$$\hat{\gamma}^{(i)}=y^{(i)}(w^{T}x^{(i)} + b)$$
geometric margin:
$$\gamma^{(i)}=\frac{y^{(i)}(w^{T}x^{(i)} + b)}{\left \| w \right \| }$$
geometric margin is the euclid distance.
### the optimal margin classifier
we want to maximize geometic margin:
$$
\begin{equation}
\begin{split}
\underset{\gamma, w, b}{max}\ &\gamma \\
s.t\quad &\frac{y^{(i)}(w^{T}x^{(i)} + b)}{\left \| w \right \| } >= \gamma
\end{split}
\end{equation}
$$
without loss of generality, we can set $\gamma\left \| w \right \|=1$, then the above is equivalent to:
$$
\begin{equation}
\begin{split}
\underset{w, b}{min}\ &\frac{1}{2}{\left \| w \right \|}^2 \\
s.t\quad &{y^{(i)}(w^{T}x^{(i)} + b)} >= 1
\end{split}
\end{equation}
$$
### lagrange duality
consider the following primal optimization problem:
$$
\begin{equation}
\begin{split}
\underset{w}{min}\quad &f(w)\\
s.t\quad &g_{i}(w) \le 0,i=1,...,k\\
&h_{i}(w)=0, i=1,...,l
\end{split}
\end{equation}
$$
we define the lagrangian of this optimization problem:
$$L(w,\alpha,\beta)=f(w) + \sum_{i=1}^{k}\alpha_{i}g_{i}(w) + \sum_{i=1}^{l}\beta_{i}h_{i}(w)$$
here $\alpha_{i}, \beta_{i}$ are the lagrange multipliers. consider the quantity:
$$\theta_{P}(w) = \underset{\alpha,\beta:\alpha_{i}\ge{0}}{max}L(w,\alpha,\beta) $$
here $P$ stands for "primal".
let some $w$ be given, if $w$ violates any primal constraints, i.e., if either $g_{i}(w) > 0$ or $h_{i}(w) \ne 0$, then:
$$\theta_{P}(w) = \underset{\alpha,\beta:\alpha_{i}\ge{0}}{max}f(w) + \sum_{i=1}^{k}\alpha_{i}g_{i}(w) + \sum_{i=1}^{l}\beta_{i}h_{i}(w) = \infty$$
conversely, if the constraints are saitistied for particular $w$, then $\theta_{P}(w) = f(w)$, hence:
$$
\theta_{P}(w) =
\begin{cases}
f(w)\ &\text{if w satisfy constraints}\\
\infty\ &\text{otherwise.}
\end{cases}
$$
with this equation, we have:
$$\underset{w}{min}f(w),\ \text{satisfy constraints} \Leftrightarrow \underset{w}{min}\theta_{P}(w)=\underset{w}{min}\underset{\alpha,\beta:\alpha_{i}\ge{0}}{max}L(w,\alpha,\beta)$$
we define the optimal value of the objective function to be $p^{\ast} = \underset{w}{min}\theta_{P}(w)$.
reverse the min max oder, we define:
$$\theta_{D}(\alpha, \beta) = \underset{w}{min}L(w,\alpha,\beta)$$
D stands for "dual", we can pose the dual optimization problem:
$$\underset{\alpha,\beta:\alpha_{i}\ge{0}}{max}\theta_{D}(\alpha, \beta) = \underset{\alpha,\beta:\alpha_{i}\ge{0}}{max}\underset{w}{min}L(w,\alpha,\beta)$$
we define the optimal $d^{\ast}=\underset{\alpha,\beta:\alpha_{i}\ge{0}}{max}\theta_{D}(\alpha, \beta)$, it can easily be shown that:
$$d^{\ast}=\underset{\alpha,\beta:\alpha_{i}\ge{0}}{max}\theta_{D}(\alpha, \beta) \le \underset{w}{min}\theta_{P}(w) = p^{\ast}$$
however, under certain conditions, we have:
$$d^{\ast} = p^{\ast}$$
so that we can solve the dual problem instead of the primal problem.
(KKT conditions)suppose $f$ and $g_{i}$ are convex, $h_{i}$ are affine, and there exits some $w$ so that $g_{i}(w) < 0$ for all $i$. <br>
under these assumptions, there must exists $w^{\ast}, \alpha^{\ast}, \beta^{\ast}$ so that $w^{\ast}$ is the solution to the primal problem, $\alpha^{\ast},\beta^{\ast}$ are the solutions to the dual problem, and $p^{\ast}=d^{\ast}=L(w^{\ast}, \alpha^{\ast}, \beta^{\ast})$.<br>
moreover, $w^{\ast}, \alpha^{\ast}, \beta^{\ast}$ iff satisfy the KKT conditions:
$$
\begin{equation}
\begin{split}
\frac{\partial}{\partial w_{i}}L(w^{\ast},\alpha^{\ast},\beta^{\ast}) =& 0,\ i=1,...,d\\
\frac{\partial}{\partial \beta_{i}}L(w^{\ast},\alpha^{\ast},\beta^{\ast}) =& 0,\ i=1,...,l\\
\alpha_{i}^{\ast}g_{i}(w) =& 0,\ i=1,...,k\\
g_{i}(w^{\ast}) \le& 0,\ i=1,...,k\\
\alpha_{i}^{\ast} \ge& 0,\ i=1,...,k
\end{split}
\end{equation}
$$
proof t.b.c.
## 2.4 use lagrange duality
previous optimal margin problem:
$$
\begin{equation}
\begin{split}
\underset{w, b}{min}\ &\frac{1}{2}{\left \| w \right \|}^2 \\
s.t\quad &{y^{(i)}(w^{T}x^{(i)} + b)} >= 1
\end{split}
\end{equation}
$$
we can write the constraints as:
$$g_{i}(w) = 1 - y^{(i)}(w^{T}x^{(i)} + b) \le 0$$
this problem satisfy the KKT prerequisites:
1. $\frac{1}{2}{\left \| w \right \|}^2$ is convex.
2. $1 - y^{(i)}(w^{T}x^{(i)} + b)$ is convex.
3. there exits $w, b$, such that $1 - y^{(i)}(w^{T}x^{(i)} + b) < 0$, just increase the order.
write the lagrangian of this problem:
$$
L(w,b,\alpha )=\frac{1}{2}\left \| w \right \|^{2} - \sum_{i=1}^{n}\alpha_{i}\left [ y^{(i)}(w^{T}x^{(i)} + b) - 1 \right ]
$$
just solve the dual form of the problem, to do so, we need to first minimize $L(w,\alpha,\beta)$ with respect to $w,b$, setting derivatives to 0:
$$\nabla_{w}L(w, b, \alpha) = w - \sum_{i=1}^{n}\alpha_{i}y^{(i)}x^{(i)} = 0$$
this implies:
$$w = \sum_{i=1}^{n}\alpha_{i}y^{(i)}x^{(i)}$$
derivative with respect to b:
$$\nabla_{b}L(w, b, \alpha) = \sum_{i=1}^{n}\alpha_{i}y^{(i)}=0$$
plug these equations back to lagrangian:
$$
\begin{equation}
\begin{split}
L(w, b, \alpha) =& \frac{1}{2}\left \| w \right \|^{2} - \sum_{i=1}^{n}\alpha_{i}\left [ y^{(i)}(w^{T}x^{(i)} + b) - 1 \right ]\\
=& \frac{1}{2}(\sum_{i=1}^{n}\alpha_{i}y^{(i)}x^{(i)})^{T}(\sum_{i=1}^{n}\alpha_{i}y^{(i)}x^{(i)}) - \sum_{i=1}^{n}\alpha_{i}y^{(i)}(\sum_{i=1}^{n}\alpha_{i}y^{(i)}x^{(i)})^{T}x^{(i)} + b\sum_{i=1}^{n}\alpha_{i}y^{(i)} + \sum_{i=1}^{n}\alpha_{i}\\
=& \sum_{i=1}^{n}\alpha_{i} - \sum_{i,j=1}^{n}y^{(i)}y^{(j)}\alpha_{i}\alpha_{j}(x^{(i)})^{T}x^{(i)}
\end{split}
\end{equation}
$$
we thus obtain the following dual optimization problem:
$$
\begin{equation}
\begin{split}
\underset{\alpha}{max}\quad &W(\alpha)=\sum_{i=1}^{n}\alpha_{i} - \sum_{i,j=1}^{n}y^{(i)}y^{(j)}\alpha_{i}\alpha_{j}\left \langle x^{(i)},x^{(j)} \right \rangle \\
s.t\quad &\alpha_{i}\ge{0},\ i=1,...,n \\
&\sum_{i=1}^{n}\alpha_{i}y^{(i)}=0
\end{split}
\end{equation}
$$
this is easier to solve(we'll talk about it later). after abtained $\alpha_{i}^{\ast}$, we have:
$$w^{\ast} = \sum_{i=1}^{n}\alpha_{i}^{\ast}y^{(i)}x^{(i)}$$
go back to the original problem, we get:
$$b^{\ast} = -\frac{max_{i: y^{(i)}=-1}w^{\ast{T}}x^{(i)} + min_{i: y^{(i)}=1}w^{\ast{T}}x^{(i)}}{2} $$
when making predictions, we have:
$$w^{T}x + b = \left ( \sum_{i=1}^{n}\alpha_{i}y^{(i)}x^{(i)}\right )^{T}x + b = \sum_{i=1}^{n}\alpha_{i}y^{(i)}\left \langle x^{(i)},x \right \rangle + b$$
we only needed inner product.
### non-separable case
so far, we assumed the data is linearly separable.
while mapping data to a high dimensional feature space via $\phi$ does not increase the likelihood that the data is separable.
so we need to make the algorithm work for non-linearly separable datasets.
we reformulate our optimization as follows:
$$
\begin{equation}
\begin{split}
\underset{w, b}{min}\ &\frac{1}{2}{\left \| w \right \|}^2 + C\sum_{i=1}^{n}\xi_{i}\\
s.t\quad &{y^{(i)}(w^{T}x^{(i)} + b)} >= 1 - \xi_{i},\ i=1,...,n\\
&\xi_{i} \ge 0,\ i=1,...,n.
\end{split}
\end{equation}
$$
the cost of outlier $C\xi_{i}$.
the lagrangian:
$$
L(w,b,\xi,\alpha,r )=\frac{1}{2}\left \| w \right \|^{2} + C\sum_{i=1}^{n}\xi_{i} - \sum_{i=1}^{n}\alpha_{i}\left [ y^{(i)}(w^{T}x^{(i)} + b) - 1 + \xi_{i}\right ] -\sum_{i=1}^{n}r_{i}\xi_{i}
$$
here $\alpha_{i},r_{i}$ are our lagrange multipliers.
the dual form of the problem:
$$
\begin{equation}
\begin{split}
\underset{\alpha}{max}\quad &W(\alpha)=\sum_{i=1}^{n}\alpha_{i} - \sum_{i,j=1}^{n}y^{(i)}y^{(j)}\alpha_{i}\alpha_{j}\left \langle x^{(i)},x^{(j)} \right \rangle \\
s.t\quad &0 \le \alpha_{i}\le{C},\ i=1,...,n \\
&\sum_{i=1}^{n}\alpha_{i}y^{(i)}=0
\end{split}
\end{equation}
$$
the same as before except $\alpha_{i}$'s constraints, the calculation for $b^{\ast}$ has to be modified, t.b.c.
```python
import numpy as np
from sklearn import datasets
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import LinearSVC
```
```python
iris = datasets.load_iris()
X = iris["data"][:, 2:]
y = (iris["target"] == 2).astype(np.int)
svm_clf = Pipeline([("scaler", StandardScaler()),
("linear_svc", LinearSVC(C=1, loss="hinge"))])
svm_clf.fit(X, y)
```
Pipeline(steps=[('scaler', StandardScaler()),
('linear_svc', LinearSVC(C=1, loss='hinge'))])
### SMO algorithm
consider when trying to solve the unconstrained optimization problem:
$$\underset{\alpha}{max}\ W(\alpha_{1},...,\alpha_{n})$$
we have the coordinate ascent algorithm:
$$
\begin{equation}
\begin{split}
&\text{loop until convergence:}\\
&\qquad \text{for }i=1,...,n:\\
&\qquad\qquad \alpha_{i}:=\underset{\hat{\alpha_{i}}}{argmax}
W(\alpha_{1},...,\alpha_{i-1},\hat{\alpha_{i}},\alpha_{i+1},...,\alpha_{n}).
\end{split}
\end{equation}
$$
we can not directly use coordinate ascent facing SVM dual problem:
$$
\begin{equation}
\begin{split}
\underset{\alpha}{max}\quad &W(\alpha)=\sum_{i=1}^{n}\alpha_{i} - \sum_{i,j=1}^{n}y^{(i)}y^{(j)}\alpha_{i}\alpha_{j}\left \langle x^{(i)},x^{(j)} \right \rangle \\
s.t\quad &0 \le \alpha_{i}\le{C},\ i=1,...,n \\
&\sum_{i=1}^{n}\alpha_{i}y^{(i)}=0
\end{split}
\end{equation}
$$
if we want to update some $\alpha_{i}$, we must update at least two of them simutaneously.
coordinate ascent change to:
$$
\begin{equation}
\begin{split}
&\text{loop until convergence:}\\
&\qquad 1.\text{select some pair } \alpha_{i}, \alpha_{j}.\\
&\qquad 2.\text{optimize } W(\alpha) \text{ with respect to } \alpha_{i}, \alpha_{j}, \text{while holding other } \alpha_{k} \text{ fixed}.
\end{split}
\end{equation}
$$
the reason that SMO is an efficient is that the update to $\alpha_{i}, \alpha_{j}$ can be computed efficiently.
take $i,j=1,2$ as example, SMO step is like:
$$max\ W(\alpha_{1},\alpha_{2},...,\alpha_{n}) \text{ while } $$
$$\alpha_{3},...,\alpha_{n} \text{ fixed}$$
$$\alpha_{1}y^{(1)} + \alpha_{1}y^{(1)} = \zeta$$
$$0 \le \alpha_{1} \le{C},0 \le \alpha_{2} \le{C},$$
this can be change to:
$$max\ W(\alpha_{1},(\zeta - \alpha_{1}y^{(1)})y^{(2)},...,\alpha_{n}) \text{ while } L\le \alpha_{1}\le H$$
this is direct quadratic optimization, easy to solve.
remained questions:
1. the choice of $\alpha_{i},\alpha_{j}$ , this is heuristic.
2. how to update b.
t.b.c according to Platt's paper.
## SVM with kernels
let $\phi : \mathbb{R}^{d} \to \mathbb{R}^{p}$ be a feature map, the original dual form of the problem:
$$
\begin{equation}
\begin{split}
\underset{\alpha}{max}\quad &W(\alpha)=\sum_{i=1}^{n}\alpha_{i} - \sum_{i,j=1}^{n}y^{(i)}y^{(j)}\alpha_{i}\alpha_{j}\left \langle x^{(i)},x^{(j)} \right \rangle \\
s.t\quad &\alpha_{i}\ge{0},\ i=1,...,n \\
&\sum_{i=1}^{n}\alpha_{i}y^{(i)}=0
\end{split}
\end{equation}
$$
now change to:
$$
\begin{equation}
\begin{split}
\underset{\alpha}{max}\quad &W(\alpha)=\sum_{i=1}^{n}\alpha_{i} - \sum_{i,j=1}^{n}y^{(i)}y^{(j)}\alpha_{i}\alpha_{j}\left \langle \phi(x^{(i)}),\phi(x^{(j)}) \right \rangle \\
s.t\quad &\alpha_{i}\ge{0},\ i=1,...,n \\
&\sum_{i=1}^{n}\alpha_{i}y^{(i)}=0
\end{split}
\end{equation}
$$
we only need to know $\left \langle \phi(x^{(i)}),\phi(x^{(j)}) \right \rangle$ to optimize.
when predicting:
$$w^{T}\phi(x) + b = \left ( \sum_{i=1}^{n}\alpha_{i}y^{(i)}\phi(x^{(i)})\right )^{T}x + b = \sum_{i=1}^{n}\alpha_{i}y^{(i)}\left \langle \phi(x^{(i)}),\phi(x) \right \rangle + b$$
```python
"""PolynomialFeatures + LinearSVC"""
from sklearn.datasets import make_moons
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures
polynomial_svm_clf = Pipeline([
("poly_features", PolynomialFeatures(degree=3)),
("scaler", StandardScaler()),
("svm_clf", LinearSVC(C=10, loss="hinge", random_state=42))
])
polynomial_svm_clf.fit(X, y)
```
Pipeline(steps=[('poly_features', PolynomialFeatures(degree=3)),
('scaler', StandardScaler()),
('svm_clf', LinearSVC(C=10, loss='hinge', random_state=42))])
```python
"""poly SVC"""
from sklearn.svm import SVC
poly_kernel_svm_clf = Pipeline([
("scaler", StandardScaler()),
("svm_clf", SVC(kernel="poly", degree=3, coef0=1, C=5))
])
poly_kernel_svm_clf.fit(X, y)
```
Pipeline(steps=[('scaler', StandardScaler()),
('svm_clf', SVC(C=5, coef0=1, kernel='poly'))])
```python
"""rbf SVC"""
from sklearn.svm import SVC
rbf_kernel_svm_clf = Pipeline([
("scaler", StandardScaler()),
("svm_clf", SVC(kernel="rbf", gamma=5, C=0.001))
])
rbf_kernel_svm_clf.fit(X, y)
```
Pipeline(steps=[('scaler', StandardScaler()),
('svm_clf', SVC(C=0.001, gamma=5))])
```python
"""SVM can support regression"""
from sklearn.svm import SVR
svm_poly_reg = SVR(kernel="poly", degree=2, C=100, epsilon=0.1, gamma="scale")
svm_poly_reg.fit(X, y)
```
SVR(C=100, degree=2, kernel='poly')
```python
```
|
CCHHAAPPTTEERR 1166
TThhee LLIISSPP EEddiittoorr
1166..11.. TThhee EEddiittoorrss
It is quite possible to use VI, Emacs or other stan-
dard editors to edit your lisp programs, and many peo-
ple do just that. However there is a lisp structure
editor which is particularly good for the editing of
lisp programs, and operates in a rather different
fashion, namely within a lisp environment. applica-
tion. It is handy to know how to use it for fixing
problems without exiting from the lisp system (e.g.
from the debugger so you can continue to execute
rather than having to start over.) The editor is not
quite like the top-level and debugger, in that it
expects you to type editor commands to it. It will
not evaluate whatever you happen to type. (There is
an editor command to evaluate things, though.)
The editor is available (assuming your system is set
up correctly with a lisp library) by typing (load
'cmufncs) and (load 'cmuedit).
The most frequent use of the editor is to change
function definitions by starting the editor with one
of the commands described in section 16.14. (see
_e_d_i_t_f), values (_e_d_i_t_v), properties (_e_d_i_t_p), and
expressions (_e_d_i_t_e). The beginner is advised to
start with the following (very basic) commands: _o_k_,
_u_n_d_o_, _p_, _#, under which are explained two different
basic commands which start with numbers, and f.
This documentation, and the editor, were imported from
PDP-10 CMULisp by Don Cohen. PDP-10 CMULisp is based
on UCILisp, and the editor itself was derived from an
early version of Interlisp. Lars Ericson, the author
of this section, has provided this very concise sum-
mary. Tutorial examples and implementation details
may be found in the Interlisp Reference Manual, where
a similar editor is described.
TThhee LLIISSPP EEddiittoorr 1166--11
TThhee LLIISSPP EEddiittoorr 1166--22
1166..22.. SSccooppee ooff AAtttteennttiioonn
Attention-changing commands allow you to look at a
different part of a Lisp expression you are editing.
The sub-structure upon which the editor's attention is
centered is called "the current expression". Chang-
ing the current expression means shifting attention
and not actually modifying any structure.
____________________________________________________________
_S_C_O_P_E _O_F _A_T_T_E_N_T_I_O_N _C_O_M_M_A_N_D _S_U_M_M_A_R_Y
_n _(_n_>_0_) . Makes the nth element of the current expression be
the new current expression.
_-_n _(_n_>_0_). Makes the nth element from the end of the current
expression be the new current expression.
_0. Makes the next higher expression be the new correct
expression. If the intention is to go back to the next
higher left parenthesis, use the command !0.
_u_p . If a p command would cause the editor to type ...
before typing the current expression, (the current expres-
sion is a tail of the next higher expression) then has no
effect; else, up makes the old current expression the first
element in the new current expression.
_!_0 . Goes back to the next higher left parenthesis.
_^ . Makes the top level expression be the current expres-
sion.
_n_x . Makes the current expression be the next expression.
_(_n_x _n_) equivalent to n nx commands.
_!_n_x . Makes current expression be the next expression at a
higher level. Goes through any number of right parentheses
to get to the next expression.
_b_k . Makes the current expression be the previous expres-
sion in the next higher expression.
_(_n_t_h _n_) _n_>_0 . Makes the list starting with the nth element
of the current expression be the current expression.
_(_n_t_h _$_) _- _g_e_n_e_r_a_l_i_z_e_d _n_t_h _c_o_m_m_a_n_d_. nth locates $, and then
backs up to the current level, where the new current expres-
sion is the tail whose first element contains, however
deeply, the expression that was the terminus of the location
operation.
Printed: October 16, 1993
TThhee LLIISSPP EEddiittoorr 1166--33
_:_: . (pattern :: . $) e.g., (cond :: return). finds a
cond that contains a return, at any depth.
_(_b_e_l_o_w _c_o_m _x_) . The below command is useful for locating a
substructure by specifying something it contains. (below
cond) will cause the cond clause containing the current
expression to become the new current expression. Suppose
you are editing a list of lists, and want to find a sublist
that contains a foo (at any depth). Then simply executes f
foo (below .
_(_n_e_x _x_) . same as _(_b_e_l_o_w _x_) followed by nx. For example,
if you are deep inside of a selectq clause, you can advance
to the next clause with _(_n_e_x _s_e_l_e_c_t_q_).
_n_e_x. The atomic form of _n_e_x is useful if you will be
performing repeated executions of _(_n_e_x _x_). By simply
marking the chain corresponding to x, you can use _n_e_x to
step through the sublists.
____________________________________________________________
1166..33.. PPaatttteerrnn MMaattcchhiinngg CCoommmmaannddss
Many editor commands that search take patterns. A
pattern _p_a_t matches with x if:
____________________________________________________________
_P_A_T_T_E_R_N _S_P_E_C_I_F_I_C_A_T_I_O_N _S_U_M_M_A_R_Y
- _p_a_t is _e_q to x.
- _p_a_t is &.
- _p_a_t is a number and equal to x.
- if (car _p_a_t) is the atom *any*, (cdr _p_a_t) is a list of
patterns, and _p_a_t matches x if and only if one of the pat-
terns on (cdr _p_a_t) matches x.
- if _p_a_t is a literal atom or string, and (nthchar _p_a_t -1)
is @, then _p_a_t matches with any literal atom or string which
has the same initial characters as _p_a_t, e.g. ver@ matches
with verylongatom, as well as "verylongstring".
- if (car _p_a_t) is the atom --, _p_a_t matches x if (a) (cdr
_p_a_t)=nil, i.e. _p_a_t=(--), e.g., (a --) matches (a) (a b c)
and (a . b) in other words, -- can match any tail of a
list. (b) (cdr _p_a_t) matches with some tail of x, e.g. (a
Printed: October 16, 1993
TThhee LLIISSPP EEddiittoorr 1166--44
-- (&)) will match with (a b c (d)), but not (a b c d), or
(a b c (d) e). however, note that (a -- (&) --) will match
with (a b c (d) e). in other words, -- will match any inte-
rior segment of a list.
- if (car _p_a_t) is the atom ==, _p_a_t matches x if and only if
(cdr _p_a_t) is _e_q to x. (this pattern is for use by programs
that call the editor as a subroutine, since any non-atomic
expression in a command typed in by the user obviously can-
not be _e_q to existing structure.) - otherwise if x is a
list, _p_a_t matches x if (car _p_a_t) matches (car x), and (cdr
_p_a_t) matches (cdr x).
- when searching, the pattern matching routine is called
only to match with elements in the structure, unless the
pattern begins with :::, in which case cdr of the pattern is
matched against tails in the structure. (in this case, the
tail does not have to be a proper tail, e.g. (::: a --)
will match with the element (a b c) as well as with cdr of
(x a b c), since (a b c) is a tail of (a b c).)
____________________________________________________________
1166..33..11.. CCoommmmaannddss TThhaatt SSeeaarrcchh
____________________________________________________________
_S_E_A_R_C_H _C_O_M_M_A_N_D _S_U_M_M_A_R_Y
_f _p_a_t_t_e_r_n . f informs the editor that the next command is
to be interpreted as a pattern. If no pattern is given on
the same line as the f then the last pattern is used. f
pattern means find the next instance of pattern.
_(_f _p_a_t_t_e_r_n _n_). Finds the next instance of pattern.
_(_f _p_a_t_t_e_r_n _t_). similar to f pattern, except, for example,
if the current expression is (cond ..), f cond will look for
the next cond, but (f cond t) will 'stay here'.
_(_f _p_a_t_t_e_r_n _n_) _n_>_0. Finds the nth place that pattern
matches. If the current expression is (foo1 foo2 foo3), (f
f00@ 3) will find foo3.
_(_f _p_a_t_t_e_r_n_) _o_r _(_f _p_a_t_t_e_r_n _n_i_l_). only matches with elements
at the top level of the current expression. If the current
expression is _(_p_r_o_g _n_i_l _(_s_e_t_q _x _(_c_o_n_d _& _&_)_) _(_c_o_n_d _&_) _._._._) f
(cond --) will find the cond inside the setq, whereas (f
(cond --)) will find the top level cond, i.e., the second
one.
Printed: October 16, 1993
TThhee LLIISSPP EEddiittoorr 1166--55
_(_s_e_c_o_n_d _. _$_) . same as (lc . $) followed by another (lc .
$) except that if the first succeeds and second fails, no
change is made to the edit chain.
_(_t_h_i_r_d _. _$_) . Similar to second.
_(_f_s _p_a_t_t_e_r_n_1 _._._. _p_a_t_t_e_r_n_n_) . equivalent to f pattern1 fol-
lowed by f pattern2 ... followed by f pattern n, so that if
f pattern m fails, edit chain is left at place pattern m-1
matched.
_(_f_= _e_x_p_r_e_s_s_i_o_n _x_) . Searches for a structure eq to expres-
sion.
_(_o_r_f _p_a_t_t_e_r_n_1 _._._. _p_a_t_t_e_r_n_n_) . Searches for an expression
that is matched by either pattern1 or ... patternn.
_b_f _p_a_t_t_e_r_n . backwards find. If the current expression is
_(_p_r_o_g _n_i_l _(_s_e_t_q _x _(_s_e_t_q _y _(_l_i_s_t _z_)_)_) _(_c_o_n_d _(_(_s_e_t_q _w _-_-_) _-_-_)_)
_-_-_) f list followed by bf setq will leave the current
expression as (setq y (list z)), as will f cond followed by
bf setq
_(_b_f _p_a_t_t_e_r_n _t_). backwards find. Search always includes cur-
rent expression, i.e., starts at end of current expression
and works backward, then ascends and backs up, etc.
____________________________________________________________
1166..33..11..11.. LLooccaattiioonn SSppeecciiffiiccaattiioonnss Many editor
commands use a method of specifying position
called a location specification. The meta-
symbol $ is used to denote a location specifica-
tion. $ is a list of commands interpreted as
described above. $ can also be atomic, in which
case it is interpreted as (list $). a location
specification is a list of edit commands that
are executed in the normal fashion with two
exceptions. first, all commands not recognized
by the editor are interpreted as though they had
been preceded by f. The location specification
(cond 2 3) specifies the 3rd element in the
first clause of the next cond.
the if command and the ## function provide a way
of using in location specifications arbitrary
predicates applied to elements in the current
expression.
In insert, delete, replace and change, if $ is
Printed: October 16, 1993
TThhee LLIISSPP EEddiittoorr 1166--66
nil (empty), the corresponding operation is per-
formed on the current edit chain, i.e. (replace
with (car x)) is equivalent to (:(car x)). for
added readability, here is also permitted, e.g.,
(insert (print x) before here) will insert
(print x) before the current expression (but not
change the edit chain). It is perfectly legal
to ascend to insert, replace, or delete. for
example (insert (_r_e_t_u_r_n) after ^ prog -1) will
go to the top, find the first prog, and insert a
(_r_e_t_u_r_n) at its end, and not change the current
edit chain.
The a, b, and : commands all make special
checks in e1 thru em for expressions of the form
(## . coms). In this case, the expression used
for inserting or replacing is a copy of the cur-
rent expression after executing coms, a list of
edit commands. (insert (## f cond -1 -1)
after3) will make a copy of the last form in
the last clause of the next cond, and insert it
after the third element of the current expres-
sion.
_$. In descriptions of the editor, the meta-
symbol $ is used to denote a location specifica-
tion. $ is a list of commands interpreted as
described above. $ can also be atomic.
____________________________________________________________
_L_O_C_A_T_I_O_N _C_O_M_M_A_N_D _S_U_M_M_A_R_Y
_(_l_c _. _$_) . Provides a way of explicitly invoking the loca-
tion operation. (lc cond 2 3) will perform search.
_(_l_c_l _. _$_) . Same as lc except search is confined to current
expression. To find a cond containing a _r_e_t_u_r_n, one might
use the location specification (cond (lcl _r_e_t_u_r_n) where the
would reverse the effects of the lcl command, and make the
final current expression be the cond.
____________________________________________________________
1166..33..22.. TThhee EEddiitt CChhaaiinn The edit-chain is a list of
which the first element is the the one you are now
editing ("current expression"), the next element is
what would become the current expression if you
were to do a 0, etc., until the last element which
is the expression that was passed to the editor.
Printed: October 16, 1993
TThhee LLIISSPP EEddiittoorr 1166--77
____________________________________________________________
_E_D_I_T _C_H_A_I_N _C_O_M_M_A_N_D _S_U_M_M_A_R_Y
_m_a_r_k . Adds the current edit chain to the front of the list
marklst.
__ . Makes the new edit chain be (car marklst).
_(__ _p_a_t_t_e_r_n_) . Ascends the edit chain looking for a link
which matches pattern. for example:
____ . Similar to _ but also erases the mark.
_\ . Makes the edit chain be the value of unfind. unfind is
set to the current edit chain by each command that makes a
"big jump", i.e., a command that usually performs more than
a single ascent or descent, namely ^, _, __, !nx, all com-
mands that involve a search, e.g., f, lc, ::, below, et al
and and themselves.
if the user types f cond, and then f car, would take him
back to the cond. another would take him back to the car,
etc.
_\_p . Restores the edit chain to its state as of the last
print operation. If the edit chain has not changed since
the last printing, \p restores it to its state as of the
printing before that one. If the user types p followed by 3
2 1 p, \p will return to the first p, i.e., would be equiva-
lent to 0 0 0. Another \p would then take him back to the
second p.
____________________________________________________________
1166..44.. PPrriinnttiinngg CCoommmmaannddss
____________________________________________________________
_P_R_I_N_T_I_N_G _C_O_M_M_A_N_D _S_U_M_M_A_R_Y
_p Prints current expression in abbreviated form. (p m)
prints mth element of current expression in abbreviated
form. (p m n) prints mth element of current expression as
though printlev were given a depth of n. (p 0 n) prints
current expression as though printlev were given a depth of
n. (p cond 3) will work.
_? . prints the current expression as though printlev were
given a depth of 100.
Printed: October 16, 1993
TThhee LLIISSPP EEddiittoorr 1166--88
_p_p . pretty-prints the current expression.
_p_p_*. is like pp, but forces comments to be shown.
____________________________________________________________
1166..55.. SSttrruuccttuurree MMooddiiffiiccaattiioonn CCoommmmaannddss
All structure modification commands are undoable. See
_u_n_d_o.
____________________________________________________________
_S_T_R_U_C_T_U_R_E _M_O_D_I_F_I_C_A_T_I_O_N _C_O_M_M_A_N_D _S_U_M_M_A_R_Y
_# _[_e_d_i_t_o_r _c_o_m_m_a_n_d_s_] (n) n>1 deletes the corresponding ele-
ment from the current expression.
_(_n _e_1 _._._. _e_m_) _n_,_m_>_1 replaces the nth element in the current
expression with e1 ... em.
_(_-_n _e_1 _._._. _e_m_) _n_,_m_>_1 inserts e1 ... em before the n ele-
ment in the current expression.
_(_n _e_1 _._._. _e_m_) (the letter "n" for "next" or "nconc", not a
number) m>1 attaches e1 ... em at the end of the current
expression.
_(_a _e_1 _._._. _e_m_) . inserts e1 ... em after the current
expression (or after its first element if it is a tail).
_(_b _e_1 _._._. _e_m_) . inserts e1 ... em before the current
expression. to insert foo before the last element in the
current expression, perform -1 and then (b foo).
_(_: _e_1 _._._. _e_m_) . replaces the current expression by e1 ...
em. If the current expression is a tail then replace its
first element.
_d_e_l_e_t_e _o_r _(_:_) . deletes the current expression, or if the
current expression is a tail, deletes its first element.
_(_d_e_l_e_t_e _. _$_). does a (lc . $) followed by delete. current
edit chain is not changed.
_(_i_n_s_e_r_t _e_1 _._._. _e_m _b_e_f_o_r_e _. _$_) . similar to (lc. $) fol-
lowed by (b e1 ... em).
_(_i_n_s_e_r_t _e_1 _._._. _e_m _a_f_t_e_r _. _$_). similar to insert before
Printed: October 16, 1993
TThhee LLIISSPP EEddiittoorr 1166--99
except uses a instead of b.
_(_i_n_s_e_r_t _e_1 _._._. _e_m _f_o_r _. _$_). similar to insert before
except uses : for b.
_(_r_e_p_l_a_c_e _$ _w_i_t_h _e_1 _._._. _e_m_) . here $ is the segment of the
command between replace and with.
_(_c_h_a_n_g_e _$ _t_o _e_1 _._._. _e_m_) . same as replace with.
____________________________________________________________
1166..66.. EExxttrraaccttiioonn aanndd EEmmbbeeddddiinngg CCoommmmaannddss
____________________________________________________________
_E_X_T_R_A_C_T_I_O_N _A_N_D _E_M_B_E_D_D_I_N_G _C_O_M_M_A_N_D _S_U_M_M_A_R_Y
_(_x_t_r _. _$_) . replaces the original current expression with
the expression that is current after performing (lcl . $).
_(_m_b_d _x_) . x is a list, substitutes the current expression
for all instances of the atom * in x, and replaces the cur-
rent expression with the result of that substitution. (mbd
x) : x atomic, same as (mbd (x *)).
_(_e_x_t_r_a_c_t _$_1 _f_r_o_m _$_2_) . extract is an editor command which
replaces the current expression with one of its subexpres-
sions (from any depth). ($1 is the segment between extract
and from.) example: if the current expression is (print
(cond ((null x) y) (t z))) then following (extract y from
cond), the current expression will be (print y). (extract 2
-1 from cond), (extract y from 2), (extract 2 -1 from 2)
will all produce the same result.
_(_e_m_b_e_d _$ _i_n _. _x_) . embed replaces the current expression
with a new expression which contains it as a subexpression.
($ is the segment between embed and in.) example: (embed
print in setq x), (embed 3 2 in _r_e_t_u_r_n), (embed cond 3 1 in
(or * (null x))).
____________________________________________________________
1166..77.. MMoovvee aanndd CCooppyy CCoommmmaannddss
Printed: October 16, 1993
TThhee LLIISSPP EEddiittoorr 1166--1100
____________________________________________________________
_M_O_V_E _A_N_D _C_O_P_Y _C_O_M_M_A_N_D _S_U_M_M_A_R_Y
_(_m_o_v_e _$_1 _t_o _c_o_m _. _$_2_) . ($1 is the segment between move and
to.) where com is before, after, or the name of a list com-
mand, e.g., :, n, etc. If $2 is nil, or (here), the current
position specifies where the operation is to take place. If
$1 is nil, the move command allows the user to specify some
place the current expression is to be moved to. if the
current expression is (a b d c), (move 2 to after 4) will
make the new current expression be (a c d b).
_(_m_v _c_o_m _. _$_) . is the same as (move here to com . $).
_(_c_o_p_y _$_1 _t_o _c_o_m _. _$_2_) is like move except that the source
expression is not deleted.
_(_c_p _c_o_m _. _$_). is like mv except that the source expression
is not deleted.
____________________________________________________________
1166..88.. PPaarreenntthheesseess MMoovviinngg CCoommmmaannddss The commands pre-
sented in this section permit modification of the list
structure itself, as opposed to modifying components
thereof. their effect can be described as inserting
or removing a single left or right parenthesis, or
pair of left and right parentheses.
____________________________________________________________
_P_A_R_E_N_T_H_E_S_E_S _M_O_V_I_N_G _C_O_M_M_A_N_D _S_U_M_M_A_R_Y
_(_b_i _n _m_) . both in. inserts parentheses before the nth
element and after the mth element in the current expression.
example: if the current expression is (a b (c d e) f g),
then (bi 2 4) will modify it to be (a (b (c d e) f) g). (bi
n) : same as (bi n n). example: if the current expression
is (a b (c d e) f g), then (bi -2) will modify it to be (a b
(c d e) (f) g).
_(_b_o _n_) . both out. removes both parentheses from the nth
element. example: if the current expression is (a b (c d
e) f g), then (bo d) will modify it to be (a b c d e f g).
_(_l_i _n_) . left in. inserts a left parenthesis before the
nth element (and a matching right parenthesis at the end of
the current expression). example: if the current expres-
sion is (a b (c d e) f g), then (li 2) will modify it to be
Printed: October 16, 1993
TThhee LLIISSPP EEddiittoorr 1166--1111
(a (b (c d e) f g)).
_(_l_o _n_) . left out. removes a left parenthesis from the
nth element. all elements following the nth element are
deleted. example: if the current expression is (a b (c d e)
f g), then (lo 3) will modify it to be (a b c d e).
_(_r_i _n _m_) . right in. move the right parenthesis at the
end of the nth element in to after the mth element. inserts
a right parenthesis after the mth element of the nth ele-
ment. The rest of the nth element is brought up to the
level of the current expression. example: if the current
expression is (a (b c d e) f g), (ri 2 2) will modify it to
be (a (b c) d e f g).
_(_r_o _n_) . right out. move the right parenthesis at the end
of the nth element out to the end of the current expres-
sion. removes the right parenthesis from the nth element,
moving it to the end of the current expression. all elements
following the nth element are moved inside of the nth
element. example: if the current expression is (a b (c d e)
f g), (ro 3) will modify it to be (a b (c d e f g)).
_(_r _x _y_) replaces all instances of x by y in the current
expression, e.g., (r caadr cadar). x can be the s-
expression (or atom) to be substituted for, or can be a pat-
tern which specifies that s-expression (or atom).
_(_s_w _n _m_) switches the nth and mth elements of the current
expression. for example, if the current expression is (list
(cons (car x) (car y)) (cons (cdr y))), (sw 2 3) will
modify it to be (list (cons (cdr x) (cdr y)) (cons (car x)
(car y))). (sw car cdr) would produce the same result.
____________________________________________________________
1166..88..11.. UUssiinngg ttoo aanndd tthhrruu
to, thru, extract, embed, delete, replace, and move
can be made to operate on several contiguous ele-
ments, i.e., a segment of a list, by using the to
or thru command in their respective location speci-
fications. thru and to are intended to be used in
conjunction with extract, embed, delete, replace,
and move. to and thru can also be used directly
with xtr (which takes after a location specifica-
tion), as in (xtr (2 thru 4)) (from the current
expression).
Printed: October 16, 1993
TThhee LLIISSPP EEddiittoorr 1166--1122
____________________________________________________________
_T_O _A_N_D _T_H_R_U _C_O_M_M_A_N_D _S_U_M_M_A_R_Y
_(_$_1 _t_o _$_2_) . same as thru except last element not
included.
_(_$_1 _t_o_). same as ($1 thru -1)
_(_$_1 _t_h_r_u _$_2_) . If the current expression is (a (b (c d)
(e) (f g h) i) j k), following (c thru g), the current
expression will be ((c d) (e) (f g h)). If both $1 and $2
are numbers, and $2 is greater than $1, then $2 counts from
the beginning of the current expression, the same as $1. in
other words, if the current expression is (a b c d e f g),
(3 thru 4) means (c thru d), not (c thru f). in this case,
the corresponding bi command is (bi 1 $2-$1+1).
_(_$_1 _t_h_r_u_). same as _(_$_1 _t_h_r_u _-_1_).
____________________________________________________________
1166..99.. UUnnddooiinngg CCoommmmaannddss each command that causes struc-
ture modification automatically adds an entry to the
front of undolst containing the information required
to restore all pointers that were changed by the com-
mand. The undo command undoes the last, i.e., most
recent such command.
____________________________________________________________
_U_N_D_O _C_O_M_M_A_N_D _S_U_M_M_A_R_Y
_u_n_d_o . the undo command undoes most recent, structure modi-
fication command that has not yet been undone, and prints
the name of that command, e.g., mbd undone. The edit chain
is then exactly what it was before the 'undone' command had
been performed.
_!_u_n_d_o . undoes all modifications performed during this
editing session, i.e., this call to the editor.
_u_n_b_l_o_c_k . removes an undo-block. If executed at a non-
blocked state, i.e., if undo or !undo could operate, types
not blocked.
_t_e_s_t . adds an undo-block at the front of undolst. note
that test together with !undo provide a 'tentative'
mode for editing, i.e., the user can perform a number of
changes, and then undo all of them with a single !undo
Printed: October 16, 1993
TThhee LLIISSPP EEddiittoorr 1166--1133
command.
_u_n_d_o_l_s_t _[_v_a_l_u_e_]. each editor command that causes structure
modification automatically adds an entry to the front of
undolst containing the information required to restore all
pointers that were changed by the command.
_?_? prints the entries on undolst. The entries are listed
most recent entry first.
____________________________________________________________
1166..1100.. tthhaatt EEvvaalluuaattee
____________________________________________________________
_E_V_A_L_U_A_T_I_O_N _C_O_M_M_A_N_D _S_U_M_M_A_R_Y
_e . only when typed in, (i.e., (insert d before e) will
treat e as a pattern) causes the editor to call the
lisp interpreter giving it the next input as argument.
_(_e _x_) evaluates x, and prints the result. (e x t) same
as (e x) but does not print.
_(_i _c _x_1 _._._. _x_n_) same as (c y1 ... yn) where yi=(eval xi).
example: (i 3 (cdr foo)) will replace the 3rd element of
the current expression with the cdr of the value of foo. (i
n foo (car fie)) will attach the value of foo and car of the
value of fie to the end of the current expression. (i f=
foo t) will search for an expression eq to the value of foo.
If c is not an atom, it is evaluated as well.
_(_c_o_m_s _x_1 _._._. _x_n_) . each xi is evaluated and its value
executed as a command. The i command is not very convenient
for computing an entire edit command for execution, since
it computes the command name and its arguments separately.
also, the i command cannot be used to compute an atomic
command. The coms and comsq commands provide more gen-
eral ways of computing commands. (coms (cond (x (list 1
x)))) will replace the first element of the current expres-
sion with the value of x if non-nil, otherwise do nothing.
(nil as a command is a nop.)
_(_c_o_m_s_q _c_o_m_1 _._._. _c_o_m_n_) . executes com1 ... comn. comsq is
mainly useful in conjunction with the coms command. for
example, suppose the user wishes to compute an entire list
of commands for evaluation, as opposed to computing each
command one at a time as does the coms command. he would
then write (coms (cons (quote comsq) x)) where x computed
Printed: October 16, 1993
TThhee LLIISSPP EEddiittoorr 1166--1144
the list of commands, e.g., (coms (cons (quote comsq)
(get foo (quote commands))))
____________________________________________________________
1166..1111.. CCoommmmaannddss tthhaatt TTeesstt
____________________________________________________________
_T_E_S_T_I_N_G _C_O_M_M_A_N_D _S_U_M_M_A_R_Y
_(_i_f _x_) generates an error unless the value of (eval x) is
non-nil, i.e., if (eval x) causes an error or (eval x)=nil,
if will cause an error. (if x coms1 coms2) if (eval x) is
non-nil, execute coms1; if (eval x) causes an error or is
equal to nil, execute coms2. (if x coms1) if (eval x)
is non-nil, execute coms1; otherwise generate an error.
_(_l_p _. _c_o_m_s_) . repeatedly executes coms, a list of commands,
until an error occurs. (lp f print (n t)) will
attach a t at the end of every print expression. (lp f
print (if (## 3) nil ((n t)))) will attach a t at the end
of each print expression which does not already have a sec-
ond argument. (i.e. the form (## 3) will cause an error
if the edit command 3 causes an error, thereby selecting ((n
t)) as the list of commands to be executed. The if could
also be written as (if (cddr (##)) nil ((n t))).).
_(_l_p_q _. _c_o_m_s_) same as lp but does not print n occurrences.
_(_o_r_r _c_o_m_s_1 _._._. _c_o_m_s_n_) . orr begins by executing coms1, a
list of commands. If no error occurs, orr is finished.
otherwise, orr restores the edit chain to its original
value, and continues by executing coms2, etc. If none of
the command lists execute without errors, i.e., the orr
"drops off the end", orr generates an error. otherwise, the
edit chain is left as of the completion of the first command
list which executes without error.
____________________________________________________________
1166..1122.. EEddiittoorr MMaaccrrooss
Many of the more sophisticated branching commands in
the editor, such as orr, if, etc., are most often
used in conjunction with edit macros. The macro
feature permits the user to define new commands and
Printed: October 16, 1993
TThhee LLIISSPP EEddiittoorr 1166--1155
thereby expand the editor's repertoire. (however,
built in commands always take precedence over
macros, i.e., the editor's repertoire can be
expanded, but not modified.) macros are defined by
using the m command.
_(_m _c _. _c_o_m_s_) for c an atom, m defines c as an atomic
command. (if a macro is redefined, its new defini-
tion replaces its old.) executing c is then the same
as executing the list of commands coms. macros
can also define list commands, i.e., commands that
take arguments. (m (c) (arg[1] ... arg[n]) . coms) c
an atom. m defines c as a list command. executing (c
e1 ... en) is then performed by substituting e1
for arg[1], ... en for arg[n] throughout coms,
and then executing coms. a list command can be
defined via a macro so as to take a fixed or
indefinite number of 'arguments'. The form given
above specified a macro with a fixed number of argu-
ments, as indicated by its argument list. if the of
arguments. (m (c) args . coms) c, args both atoms,
defines c as a list command. executing (c e1 ...
en) is performed by substituting (e1 ... en), i.e.,
cdr of the command, for args throughout coms, and then
executing coms.
(m bp bk up p) will define bp as an atomic command
which does three things, a bk, an up, and a p. note
that macros can use commands defined by macros as well
as built in commands in their definitions. for
example, suppose z is defined by (m z -1 (if (null
(##)) nil (p))), i.e. z does a -1, and then if the
current expression is not nil, a p. now we can define
zz by (m zz -1 z), and zzz by (m zzz -1 -1 z) or (m
zzz -1 zz). we could define a more general bp by (m
(bp) (n) (bk n) up p). (bp 3) would perform (bk
3), followed by an up, followed by a p. The com-
mand second can be defined as a macro by (m (2nd) x
(orr ((lc . x) (lc . x)))).
Note that for all editor commands, 'built in' com-
mands as well as commands defined by macros, atomic
definitions and list definitions are completely
independent. in other words, the existence of an
atomic definition for c in no way affects the treat-
ment of c when it appears as car of a list command,
and the existence of a list definition for c in no way
affects the treatment of c when it appears as an
atom. in particular, c can be used as the name of
either an atomic command, or a list command, or both.
in the latter case, two entirely different defini-
tions can be used. note also that once c is
defined as an atomic command via a macro definition,
Printed: October 16, 1993
TThhee LLIISSPP EEddiittoorr 1166--1166
it will not be searched for when used in a location
specification, unless c is preceded by an f. (insert
-- before bp) would not search for bp, but instead
perform a bk, an up, and a p, and then do the inser-
tion. The corresponding also holds true for list com-
mands.
_(_b_i_n_d _. _c_o_m_s_) bind is an edit command which is
useful mainly in macros. it binds three dummy vari-
ables #1, #2, #3, (initialized to nil), and then exe-
cutes the edit commands coms. note that these
bindings are only in effect while the commands are
being executed, and that bind can be used recursively;
it will rebind #1, #2, and #3 each time it is
invoked.
_u_s_e_r_m_a_c_r_o_s _[_v_a_l_u_e_]. this variable contains the
users editing macros . if you want to save your
macros then you should save usermacros. you should
probably also save editcomsl.
_e_d_i_t_c_o_m_s_l _[_v_a_l_u_e_]. editcomsl is the list of "list
commands" recognized by the editor. (these are the
ones of the form (command arg1 arg2 ...).)
1166..1133.. MMiisscceellllaanneeoouuss EEddiittoorr CCoommmmaannddss
____________________________________________________________
_M_I_S_C_E_L_L_A_N_E_O_U_S _E_D_I_T_O_R _C_O_M_M_A_N_D _S_U_M_M_A_R_Y
_o_k . Exits from the editor.
_n_i_l . Unless preceded by f or bf, is always a null opera-
tion.
_t_t_y_: . Calls the editor recursively. The user can then
type in commands, and have them executed. The tty: command
is completed when the user exits from the lower editor
(with ok or stop). the tty: command is extremely use-
ful. it enables the user to set up a complex operation,
and perform interactive attention-changing commands part
way through it. for example the command (move 3 to after
cond 3 p tty:) allows the user to interact, in effect,
within the move command. he can verify for himself
that the correct location has been found, or complete the
specification "by hand". in effect, tty: says "I'll tell you
what you should do when you get there."
_s_t_o_p . exits from the editor with an error. mainly for use
Printed: October 16, 1993
TThhee LLIISSPP EEddiittoorr 1166--1177
in conjunction with tty: commands that the user wants to
abort. since all of the commands in the editor are errset
protected, the user must exit from the editor via a command.
stop provides a way of distinguishing between a successful
and unsuccessful (from the user's standpoint) editing ses-
sion.
_t_l . tl calls (top-level). to return to the editor just
use the _r_e_t_u_r_n top-level command.
_r_e_p_a_c_k . permits the 'editing' of an atom or string.
_(_r_e_p_a_c_k _$_) does (lc . $) followed by repack, e.g. (repack
this@).
_(_m_a_k_e_f_n _f_o_r_m _a_r_g_s _n _m_) . makes (car form) an expr with the
nth through mth elements of the current expression with
each occurrence of an element of (cdr form) replaced by
the corresponding element of args. The nth through mth
elements are replaced by form.
_(_m_a_k_e_f_n _f_o_r_m _a_r_g_s _n_). same as (makefn form args n n).
_(_s _v_a_r _. _$_) . sets var (using setq) to the current expres-
sion after performing (lc . $). (s foo) will set
foo to the current expression, (s foo -1 1) will set foo to
the first element in the last element of the current expres-
sion.
____________________________________________________________
1166..1144.. EEddiittoorr FFuunnccttiioonnss
((eeddiittff s_x1 ...))
SIDE EFFECT: edits a function. s_x1 is the name of the
function, any additional arguments are an
optional list of commands.
RETURNS: s_x1.
NOTE: if s_x1 is not an editable function, editf gener-
ates an fn not editable error.
Printed: October 16, 1993
TThhee LLIISSPP EEddiittoorr 1166--1188
((eeddiittee l_expr l_coms s_atm)))
edits an expression. its value is the last element of
(editl (list l_expr) l_coms s_atm nil nil).
((eeddiittrraacceeffnn s_com))
is available to help the user debug complex edit macros, or
subroutine calls to the editor. editracefn is to be
defined by the user. whenever the value of editracefn is
non-nil, the editor calls the function editracefn
before executing each command (at any level), giving it
that command as its argument. editracefn is initially equal
to nil, and undefined.
((eeddiittvv s_var [ g_com1 ... ]))
SIDE EFFECT: similar to editf, for editing values.
editv sets the variable to the value
returned.
RETURNS: the name of the variable whose value was
edited.
((eeddiittpp s_x))
SIDE EFFECT: similar to editf for editing property
lists. used if x is nil.
RETURNS: the atom whose property list was edited.
((eeddiittll coms atm marklst mess))
SIDE EFFECT: editl is the editor. its first argument
is the edit chain, and its value is an
edit chain, namely the value of l at the
time editl is exited. (l is a special
variable, and so can be examined or set by
edit commands. ^ is equivalent to (e
(setq l(last l)) t).) coms is an optional
list of commands. for interactive edit-
ing, coms is nil. in this case, editl
types edit and then waits for input from
the teletype. (if mess is not nil editl
types it instead of edit. for example,
the tty: command is essentially (setq l
(editl l nil nil nil (quote tty:))).)
exit occurs only via an ok, stop, or save
command. If coms is not nil, no message
is typed, and each member of coms is
treated as a command and executed. If an
Printed: October 16, 1993
TThhee LLIISSPP EEddiittoorr 1166--1199
error occurs in the execution of one of
the commands, no error message is printed
, the rest of the commands are ignored,
and editl exits with an error, i.e., the
effect is the same as though a stop com-
mand had been executed. If all commands
execute successfully, editl returns the
current value of l. marklst is the list
of marks. on calls from editf, atm is the
name of the function being edited; on
calls from editv, the name of the vari-
able, and calls from editp, the atom of
which some property of its property list
is being edited. The property list of atm
is used by the save command for saving the
state of the edit. save will not save
anything if atm=nil i.e., when editing
arbitrary expressions via edite or editl
directly.
((eeddiittffnnss s_x [ g_coms1 ... ]))
fsubr function, used to perform the same editing operations
on several functions. editfns maps down the list of func-
tions, prints the name of each function, and calls the edi-
tor (via editf) on that function.
EXAMPLE: editfns foofns (r fie fum)) will change every
fie to fum in each of the functions on
foofns.
NOTE: the call to the editor is errset protected,
so that if the editing of one function causes an
error, editfns will proceed to the next func-
tion. in the above example, if one of the
functions did not contain a fie, the r command
would cause an error, but editing would con-
tinue with the next function. The value of
editfns is nil.
((eeddiitt44ee pat y))
SIDE EFFECT: is the pattern match routine.
RETURNS: t if pat matches y. see edit-match for defini-
tion of 'match'.
NOTE: before each search operation in the editor
begins, the entire pattern is scanned for
atoms or strings that end in at-signs. These
are replaced by patterns of the form (cons
(quote /@) (explodec atom)). from the
Printed: October 16, 1993
TThhee LLIISSPP EEddiittoorr 1166--2200
standpoint of edit4e, pattern type 5, atoms or
strings ending in at-signs, is really "if
car[pat] is the atom @ (at-sign), pat will match
with any literal atom or string whose ini-
tial character codes (up to the @) are the same
as those in cdr[pat]." if the user wishes to
call edit4e directly, he must therefore convert
any patterns which contain atoms or strings
ending in at-signs to the form recognized by
edit4e. this can be done via the function editf-
pat.
((eeddiittffppaatt pat flg))
makes a copy of pat with all patterns of type 5 (see edit-
match) converted to the form expected by edit4e. flg should
be passed as nil (flg=t is for internal use by the editor).
((eeddiittffiinnddpp x pat flg))
NOTE: Allows a program to use the edit find command as
a pure predicate from outside the editor. x is
an expression, pat a pattern. The value of
editfindp is t if the command f pat would suc-
ceed, nil otherwise. editfindp calls editfpat to
convert pat to the form expected by edit4e,
unless flg=t. if the program is applying
editfindp to several different expressions using
the same pattern, it will be more efficient to
call editfpat once, and then call editfindp with
the converted pattern and flg=t.
((#### g_com1 ...))
RETURNS: what the current expression would be after
executing the edit commands com1 ... starting
from the present edit chain. generates an
error if any of comi cause errors. The cur-
rent edit chain is never changed. example:
(i r (quote x) (## (cons ..z))) replaces all
x's in the current expression by the first
cons containing a z.
Printed: October 16, 1993
|
------------------------------------------------------------------------
-- The Agda standard library
--
-- A categorical view of Delay
------------------------------------------------------------------------
{-# OPTIONS --without-K --safe --sized-types #-}
module Codata.Delay.Categorical where
open import Codata.Delay
open import Function
open import Category.Functor
open import Category.Applicative
open import Category.Monad
open import Data.These using (leftMost)
functor : ∀ {i ℓ} → RawFunctor {ℓ} (λ A → Delay A i)
functor = record { _<$>_ = λ f → map f }
module Sequential where
applicative : ∀ {i ℓ} → RawApplicative {ℓ} (λ A → Delay A i)
applicative = record
{ pure = now
; _⊛_ = λ df da → bind df (λ f → map f da)
}
applicativeZero : ∀ {i ℓ} → RawApplicativeZero {ℓ} (λ A → Delay A i)
applicativeZero = record
{ applicative = applicative
; ∅ = never
}
monad : ∀ {i ℓ} → RawMonad {ℓ} (λ A → Delay A i)
monad = record
{ return = now
; _>>=_ = bind
}
monadZero : ∀ {i ℓ} → RawMonadZero {ℓ} (λ A → Delay A i)
monadZero = record
{ monad = monad
; applicativeZero = applicativeZero
}
module Zippy where
applicative : ∀ {i ℓ} → RawApplicative {ℓ} (λ A → Delay A i)
applicative = record
{ pure = now
; _⊛_ = zipWith id
}
applicativeZero : ∀ {i ℓ} → RawApplicativeZero {ℓ} (λ A → Delay A i)
applicativeZero = record
{ applicative = applicative
; ∅ = never
}
alternative : ∀ {i ℓ} → RawAlternative {ℓ} (λ A → Delay A i)
alternative = record
{ applicativeZero = applicativeZero
; _∣_ = alignWith leftMost
}
|
(* @LICENSE(NICTA_CORE) *)
(* Author: Rafal Kolanski, NICTA & UNSW
Miscellaneous development support.
*)
theory Misc
imports
Word_Lib.Word_Enum
begin
(* from l4v/lib/Lib: *)
definition
pred_conj :: "('a \<Rightarrow> bool) \<Rightarrow> ('a \<Rightarrow> bool) \<Rightarrow> ('a \<Rightarrow> bool)" (infixl "and" 35)
where
"pred_conj P Q \<equiv> \<lambda>x. P x \<and> Q x"
definition
pred_disj :: "('a \<Rightarrow> bool) \<Rightarrow> ('a \<Rightarrow> bool) \<Rightarrow> ('a \<Rightarrow> bool)" (infixl "or" 30)
where
"pred_disj P Q \<equiv> \<lambda>x. P x \<or> Q x"
definition
pred_neg :: "('a \<Rightarrow> bool) \<Rightarrow> ('a \<Rightarrow> bool)" ("not _" [40] 40)
where
"pred_neg P \<equiv> \<lambda>x. \<not> P x"
definition "K \<equiv> \<lambda>x y. x"
text \<open>Reversed composition of partial functions\<close>
definition
fun_rcomp_option :: "('a \<rightharpoonup> 'b) \<Rightarrow> ('b \<rightharpoonup> 'c) \<Rightarrow> ('a \<rightharpoonup> 'c)" (infixl "\<rhd>o" 55)
where
"fun_rcomp_option f g \<equiv> (\<lambda>x. case f x of Some y \<Rightarrow> g y | None \<Rightarrow> None)"
lemmas rco_def = fun_rcomp_option_def
lemma rco_middle_exists:
"(a \<rhd>o b) x = Some y \<Longrightarrow> \<exists>z. a x = Some z \<and> b z = Some y"
by (clarsimp simp add: rco_def split: option.splits)
lemma rco_dom_left: "(vs \<rhd>o hs) v = Some val \<Longrightarrow> v \<in> dom vs"
by (clarsimp simp add: rco_def cong: option.case_cong split: option.splits)
text \<open>Option magic\<close>
lemma None_not_eq [simp]: "(None \<noteq> x) = (\<exists>y. x = Some y)" by (cases x) auto
lemma None_com: "(None = x) = (x = None)" by fast
lemma Some_com: "(Some y = x) = (x = Some y)" by fast
lemma option_case_None_Some [simp]:
"case_option None Some P = P"
by (simp split: option.splits)
lemma map_the_map_Some [simp]:
"map the (map Some xs) = xs"
by (induct xs, auto)
lemma theSome [simp]: "the \<circ> Some = id"
by (auto intro!: ext)
lemma allE2: "\<lbrakk> \<forall>x y. P x y ; P x y \<Longrightarrow> R \<rbrakk> \<Longrightarrow> R" by blast
lemma allE3: "\<lbrakk> \<forall>x y z. P x y z ; P x y z \<Longrightarrow> R \<rbrakk> \<Longrightarrow> R" by blast
lemma exI2: "P x y \<Longrightarrow> \<exists>x y. P x y" by blast
lemma exI3: "P x y z \<Longrightarrow> \<exists>x y. P x y z" by blast
lemma pred_conj_com:
"(P and Q) = (Q and P)"
by (intro ext, simp add: pred_conj_def conj_commute) (*WTF:conj_commute?*)
lemma pred_conj_assoc:
"(P and Q and R) = (P and (Q and R))"
by (auto simp: pred_conj_def intro: ext)
lemma pred_conj_left_commute:
"(P and (Q and R)) = (Q and (P and R))"
by (intro ext, simp add: pred_conj_def conj_ac) (*WTF:conj_ac?*)
lemmas pred_conj_ac = pred_conj_assoc pred_conj_com pred_conj_left_commute
lemma set_double_minus:
"A - B - C = A - (C \<union> B)"
by blast
(* XXX: this should be in our word library somewhere *)
lemma twice_le_div:
"n \<le> m div 2 \<Longrightarrow> 2 * n \<le> (m :: nat)"
by simp
lemmas twice_le_div_trans = twice_le_div [OF order_trans]
lemma map_id [simp]: "map id xs = xs"
by (induct xs, auto)
lemma length_obvious_assist:
"xs = [] \<Longrightarrow> 0 < length xs \<Longrightarrow> False"
by auto
lemma list_index_in_list:
"lst ! i = v \<Longrightarrow> i < length lst \<Longrightarrow> v \<in> set lst"
by auto
text \<open>Drop first or second part of pairs in the range of a map.\<close>
definition
fst_all_opt :: "('a \<rightharpoonup> 'b \<times> 'c) \<Rightarrow> ('a \<rightharpoonup> 'b)" where
"fst_all_opt m \<equiv> (map_option fst) \<circ> m"
definition
snd_all_opt :: "('a \<rightharpoonup> 'b \<times> 'c) \<Rightarrow> ('a \<rightharpoonup> 'c)" where
"snd_all_opt m \<equiv> (map_option snd) \<circ> m"
text \<open>List take/drop folding, useful when (un)serialising serialisables\<close>
lemma list_take_take_drop:
"take i x @ take j (drop i x) = take (i+j) x"
proof (induct x arbitrary: i)
case Cons thus ?case by (cases i, auto)
qed simp
lemma list_take_drop_drop:
assumes k: "k = i + j"
shows "take i (drop j x) @ (drop k x) = drop j x"
proof -
have "take i (drop j x) @ drop (i + j) x = drop j x"
proof (induct x arbitrary: j)
case Cons thus ?case by (cases j, auto)
qed auto
thus ?thesis using k by simp
qed
end |
[STATEMENT]
lemma mbisim_thrNone_eq: "s1 \<approx>m s2 \<Longrightarrow> thr s1 t = None \<longleftrightarrow> thr s2 t = None"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. s1 \<approx>m s2 \<Longrightarrow> (thr s1 t = None) = (thr s2 t = None)
[PROOF STEP]
unfolding mbisim_def tbisim_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. finite (dom (thr s1)) \<and> locks s1 = locks s2 \<and> wset s1 = wset s2 \<and> wset_thread_ok (wset s1) (thr s1) \<and> interrupts s1 = interrupts s2 \<and> (\<forall>t. case thr s1 t of None \<Rightarrow> thr s2 t = None | \<lfloor>(x1, ln)\<rfloor> \<Rightarrow> \<exists>x2. thr s2 t = \<lfloor>(x2, ln)\<rfloor> \<and> t \<turnstile> (x1, shr s1) \<approx> (x2, shr s2) \<and> (wset s2 t = None \<or> x1 \<approx>w x2)) \<Longrightarrow> (thr s1 t = None) = (thr s2 t = None)
[PROOF STEP]
apply(clarify)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>finite (dom (thr s1)); locks s1 = locks s2; wset s1 = wset s2; wset_thread_ok (wset s1) (thr s1); interrupts s1 = interrupts s2; \<forall>t. case thr s1 t of None \<Rightarrow> thr s2 t = None | \<lfloor>(x1, ln)\<rfloor> \<Rightarrow> \<exists>x2. thr s2 t = \<lfloor>(x2, ln)\<rfloor> \<and> t \<turnstile> (x1, shr s1) \<approx> (x2, shr s2) \<and> (wset s2 t = None \<or> x1 \<approx>w x2)\<rbrakk> \<Longrightarrow> (thr s1 t = None) = (thr s2 t = None)
[PROOF STEP]
apply(erule allE[where x=t])
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>finite (dom (thr s1)); locks s1 = locks s2; wset s1 = wset s2; wset_thread_ok (wset s1) (thr s1); interrupts s1 = interrupts s2; case thr s1 t of None \<Rightarrow> thr s2 t = None | \<lfloor>(x1, ln)\<rfloor> \<Rightarrow> \<exists>x2. thr s2 t = \<lfloor>(x2, ln)\<rfloor> \<and> t \<turnstile> (x1, shr s1) \<approx> (x2, shr s2) \<and> (wset s2 t = None \<or> x1 \<approx>w x2)\<rbrakk> \<Longrightarrow> (thr s1 t = None) = (thr s2 t = None)
[PROOF STEP]
apply(clarsimp)
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done |
import data.real.basic
variables a b c d : ℝ
#check add_mul
#check add_mul c a b
#check add_sub
#check add_sub c b a
#check sub_zero
#check sub_self
#check sub_add
#check sub_sub
#check mul_comm d c
#check mul_sub a b c
#check pow_two d
-- BEGIN
example (a b : ℝ) : (a + b) * (a - b) = a^2 - b^2 :=
begin
rw [add_mul, mul_sub, mul_sub],
rw [add_sub, mul_comm b a, sub_add, sub_self, sub_zero],
rw [← pow_two a, ← pow_two b],
end
-- END |
ROUND PLANTER - MINIMALIST STYLE – The round planter pot measures 14 inches diameter at widest and 8 to 8.5 inches from top to bottom of the planter. Item are hand-crafted and hand-hammered. Items are hand-crafted and many vary slightly in size due to being handmade. This planter garden box will make an eye-catching focal point and impressive statement wherever it’s placed. Unique and sturdy. |
Require Export List SetoidList Bool Setoid Program Recdef ZArith.
Require Export Sets SetProperties Generate SetConstructs.
Notation "[]" := (@nil _).
(** * Extra properties of generic data-structures, such as lists, sets, etc. *)
(** Properties of lists *)
(* begin hide *)
Section ListExtra.
Variable A : Type.
Fixpoint list_pow (x:list A)(n:nat) :=
match n with
| O => nil
| S n => app x (list_pow x n)
end.
End ListExtra.
(** * Some naive, but useful tactics *)
Ltac double_destruct G H :=
destruct G;destruct H.
Ltac apply2 G H I :=
apply G in H ; apply H in I.
Ltac apply_mem G H :=
let K := fresh in
generalize H;intro K;
apply G in H.
Ltac apply2_mem G H I :=
apply_mem G H ; apply_mem G I.
Ltac inv H :=
inversion H;subst;try congruence.
Ltac invc H :=
inversion_clear H;try congruence.
Global Program Instance ZOrd : OrderedType Z := @SOT_as_OT Z _eq _.
Typeclasses Opaque ZOrd.
Section SetsProp.
Variable U : Type.
Definition Ensemble := U -> Prop.
Definition In (A:Ensemble) (x:U) : Prop := A x.
Definition Included (B C:Ensemble) : Prop := forall x:U, In B x -> In C x.
Inductive Empty_set : Ensemble :=.
Inductive Singleton (x:U) : Ensemble :=
In_singleton : In (Singleton x) x.
Inductive Union (B C:Ensemble) : Ensemble :=
| Union_introl : forall x:U, In B x -> In (Union B C) x
| Union_intror : forall x:U, In C x -> In (Union B C) x.
Definition Same_set (B C:Ensemble) : Prop := Included B C /\ Included C B.
End SetsProp.
(** Some simplifications for Booleans. *)
Ltac simpl_bool :=
match goal with
| H: ?x || ?y = true |- _ => apply orb_true_iff in H
| H: ?x && ?y = true |- _ => apply andb_true_iff in H
| H: ?x || ?y = false |- _ => apply orb_false_iff in H
| H: ?x && ?y = false |- _ => apply andb_false_iff in H
| |- ?x || ?y = true => apply orb_true_iff
| |- ?x && ?y = true => apply andb_true_iff
| |- ?x || ?y = false => apply orb_false_iff
| |- ?x && ?y = false =>apply andb_false_iff
end.
Ltac simpl_bool_full := repeat simpl_bool.
Ltac autotc := auto with typeclass_instances.
|
Require Import MirrorShard.Expr MirrorShard.SepExpr.
Require Import MirrorShard.Lemma.
Set Implicit Arguments.
Set Strict Implicit.
Module Type SepLemmaType (ST : SepTheory.SepTheory) (SE : SepExpr ST).
Section typed.
Variable types : list type.
Definition sepConcl : Type :=
(SE.sexpr types * SE.sexpr types)%type.
Definition Lhs (l : lemma types sepConcl) : SE.sexpr types :=
fst (Concl l).
Definition Rhs (l : lemma types sepConcl) : SE.sexpr types :=
snd (Concl l).
Definition WellTyped_sepConcl tfuncs tpreds (vars : list tvar) (c : sepConcl) : bool :=
if SE.WellTyped_sexpr tfuncs tpreds nil vars (fst c)
then
SE.WellTyped_sexpr tfuncs tpreds nil vars (snd c)
else false.
Definition sepConclD funcs preds (uvars vars : env types) (c : sepConcl) : Prop :=
SE.himp funcs preds uvars vars (fst c) (snd c).
Definition sepLemma : Type := lemma types sepConcl.
Definition WellTyped_sepLemma tfuncs tpreds (l : sepLemma) : bool :=
WellTyped_lemma (WellTyped_sepConcl tfuncs tpreds) tfuncs l.
Definition sepLemmaD (funcs : functions types) (preds : SE.predicates types)
(meta_base var_base : env types) (lem : sepLemma) : Prop :=
lemmaD (WellTyped_sepConcl (typeof_funcs funcs) (SE.typeof_preds preds))
(sepConclD funcs preds) funcs meta_base var_base lem.
End typed.
End SepLemmaType.
Module SepLemma (ST : SepTheory.SepTheory) (SE : SepExpr ST) <: SepLemmaType ST SE.
Section typed.
Variable types : list type.
Definition sepConcl : Type :=
(SE.sexpr types * SE.sexpr types)%type.
Definition Lhs (l : lemma types sepConcl) : SE.sexpr types :=
fst (Concl l).
Definition Rhs (l : lemma types sepConcl) : SE.sexpr types :=
snd (Concl l).
Definition WellTyped_sepConcl tfuncs tpreds (vars : list tvar) (c : sepConcl) : bool :=
if SE.WellTyped_sexpr tfuncs tpreds nil vars (fst c)
then
SE.WellTyped_sexpr tfuncs tpreds nil vars (snd c)
else false.
Definition sepConclD funcs preds (uvars vars : env types) (c : sepConcl) : Prop :=
SE.himp funcs preds uvars vars (fst c) (snd c).
Definition sepLemma : Type := lemma types sepConcl.
Definition WellTyped_sepLemma tfuncs tpreds (l : sepLemma) : bool :=
WellTyped_lemma (WellTyped_sepConcl tfuncs tpreds) tfuncs l.
Definition sepLemmaD (funcs : functions types) (preds : SE.predicates types)
(meta_base var_base : env types) (lem : sepLemma) : Prop :=
lemmaD (WellTyped_sepConcl (typeof_funcs funcs) (SE.typeof_preds preds))
(sepConclD funcs preds) funcs meta_base var_base lem.
End typed.
End SepLemma. |
[STATEMENT]
lemma new_types_blocks:
"\<lbrakk> length pns = length Ts; length vs = length Ts \<rbrakk> \<Longrightarrow> new_types (blocks pns vs Ts e) = new_types e"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>length pns = length Ts; length vs = length Ts\<rbrakk> \<Longrightarrow> new_types (blocks pns vs Ts e) = new_types e
[PROOF STEP]
apply(induct rule: blocks.induct)
[PROOF STATE]
proof (prove)
goal (8 subgoals):
1. \<And>V Vs T Ts v vs e. \<lbrakk>\<lbrakk>length Vs = length vs; length Ts = length vs\<rbrakk> \<Longrightarrow> new_types (blocks Vs Ts vs e) = new_types e; length (V # Vs) = length (v # vs); length (T # Ts) = length (v # vs)\<rbrakk> \<Longrightarrow> new_types (blocks (V # Vs) (T # Ts) (v # vs) e) = new_types e
2. \<And>e. \<lbrakk>length [] = length []; length [] = length []\<rbrakk> \<Longrightarrow> new_types (blocks [] [] [] e) = new_types e
3. \<And>v va c d. \<lbrakk>length [] = length c; length (v # va) = length c\<rbrakk> \<Longrightarrow> new_types (blocks [] (v # va) c d) = new_types d
4. \<And>b v va d. \<lbrakk>length [] = length (v # va); length b = length (v # va)\<rbrakk> \<Longrightarrow> new_types (blocks [] b (v # va) d) = new_types d
5. \<And>v va c d. \<lbrakk>length (v # va) = length c; length [] = length c\<rbrakk> \<Longrightarrow> new_types (blocks (v # va) [] c d) = new_types d
6. \<And>a v va d. \<lbrakk>length a = length (v # va); length [] = length (v # va)\<rbrakk> \<Longrightarrow> new_types (blocks a [] (v # va) d) = new_types d
7. \<And>v va b d. \<lbrakk>length (v # va) = length []; length b = length []\<rbrakk> \<Longrightarrow> new_types (blocks (v # va) b [] d) = new_types d
8. \<And>a v va d. \<lbrakk>length a = length []; length (v # va) = length []\<rbrakk> \<Longrightarrow> new_types (blocks a (v # va) [] d) = new_types d
[PROOF STEP]
apply(simp_all)
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done |
"Parugu Pargu", the first song from 'Chitralahari', composed by Devi Sri Prasad, has released today. As expected, the song is catchy. It reminds us one of Devi Sri Prasad's old hits from blockbuster "Attarinitiki Daaredi". A good sign, isn't it?
Saxophone music by Martin has made all the difference to this number. Composed and written by Devi Sri Prasad, the song is crooned by David Simon.
'Chitralahari' stars Sai Dharam Tej in the lead role. Kalyani Priyadarshan and Nabha Natesh are the heroines. Directed by Kishore Tirumala, the film is set for release on April 12.
Embedded video for Chitralahari first song is instantly addictive! |
i see a boat with Hull Material Steel .Decks Material Aluminum .
I have been lead to believe these two metals don't go together as the steel will turn the Aluminum to powder . However this boat was built in 1988 . Do you know how this works ??
Once, I was aboard a steel motor vessel of which the superstructure was aluminum. The owner told us that the join was electrically isolated from the steel. How effective it is over time, I really don't know. But at least, your example isn't the only one.
Very commonly done, with little trouble. There are bi-metallic weld strips available- al on one side and st on the other. You simply weld using the right electrode to either side. They are not isolated electrically, but are made using an interesting “explosion welding/forging” process.
Joints done like this- with appropriate coatings and maintenance- can last for a very long time with few issues.
If I ever built another steel boat I would have an alloy deck. You can use the transition strips or bolt it on.
I would bolt it on with a 1/8" poly gasket Sikaflexed on both sides of the gasket. I would also hang all the bulkheads from the alloy deck and use bolts through SS tabs welded to the steel hull to locate them at the bottom and sides.
If I was able to hang up the deck in a shed I would fit the bulkheads and hoist the deck out and hang it so I could complete the fit out outside the hull then drop the completed fit-out/deck back into the hull and bolt it down.
Navy ships I was on in the late 60s had aluminum superstructure on steel hulls. There was a material like thick tape that separated the two. The metals overlapped at the deck level and were riveted together. There was minor corrosion, but the aluminum alloys probably weren't as good as today. They quit doing aluminum on warships when they discovered how well it burned.
NobelClad’s DetaCouple™ Structural Transitions, for instance, are used for welding aluminum superstructures and bulkheads to steel hulls, framing and decks.
So long as they are electrically isolated there isn't much of an issue. And this is a pretty easy thing to check. Just take a multi-meter and check for continuity between the hull and the bridge in a couple of spots.
Years ago I helped a guy who was making fittings for Aircraft Carrier decks. The fittings were a composite of I think aluminum, titanium and steel. He made them by explosive forming. He layered the metals, the Ti was just a thin sheet between them, set off an explosive charge and the force caused the metals to molecularly bond with each other like welding. It was pretty interesting.
maybe the Ti was the barrier that kept things from corroding... not sure. I think it was done so they could weld the fittings to the deck.
This is pretty far outside my wheel house, but based on the tests I have read, explosion forming Al-Ti will galvanically corrode at the boundary. My guess is the US Navy simply doesn't care about the corrosion and were trying to accomplish something else, but I have no idea what that may have been. Perhaps to join aluminum/steel with titanium acting as a filler, or provide a thermal expansion joint... I really don't know.
I think the main thing was to weld the fitting to the deck which didnt match it's metal. I suppose the deck was steel? but they wanted the aluminum fitting or vice versa.
I couldn't even begin to guess... I know the deck itself is made from an armored steel, and that they can't use aluminum because in the event of a jet fuel fire (~1000C) the aluminum could melt (at ~600C). But what titanium would be doing there I really don't know.
I am sure the engineers were trying to do something with it, and likely succeeded, but I just can't imagine what it would be.
I did see a steel hull with an alloy cabin bolted to a stainless steel flange that was welded to the deck. Plenty of sealant isolated the materials and it didn't seem to have had corrosion issues. The owners said it worked out far cheaper than the explosion bonded strip. |
[STATEMENT]
lemma higher_plus: "higher (p + q) v = higher p v + higher q v"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. higher (p + q) v = higher p v + higher q v
[PROOF STEP]
by (rule poly_mapping_eqI, simp add: lookup_add lookup_higher) |
module Tactic.Monoid where
open import Prelude
open import Tactic.Reflection
open import Tactic.Reflection.Quote
open import Tactic.Monoid.Exp
open import Tactic.Monoid.Reflect
open import Tactic.Monoid.Proofs
monoidTactic : ∀ {a} {A : Set a} {{_ : Monoid/Laws A}} → Tactic
monoidTactic {A = A} {{laws}} hole = do
goal ← inferNormalisedType hole
`A ← quoteTC A
unify goal (def (quote _≡_) (hArg unknown ∷ hArg `A ∷ vArg unknown ∷ vArg unknown ∷ []))
<|> do typeErrorFmt "Goal is not an equality: %t" goal
goal ← normalise goal
ensureNoMetas goal
match ← monoidMatcher (Monoid/Laws.super laws)
`dict ← quoteTC (Monoid/Laws.super laws)
`laws ← quoteTC laws
ensureNoMetas `dict
debugPrintFmt "tactic.monoid" 20 "monoidTactic %t, dict = %t" goal `dict
(lhs , rhs) , env ← parseGoal match goal
unify hole (def (quote proof) (iArg `dict ∷ iArg `laws ∷ vArg (` lhs) ∷ vArg (` rhs) ∷
vArg (quoteEnv `dict env) ∷ vArg (con (quote refl) []) ∷ []))
<|> do typeErrorFmt "Can't prove %t == %t because %t /= %t"
(` lhs) (` rhs) (` (flatten lhs)) (` (flatten rhs))
macro
auto-monoid : ∀ {a} {A : Set a} {{Laws : Monoid/Laws A}} → Tactic
auto-monoid {{Laws}} = monoidTactic {{Laws}}
|
{-# OPTIONS --without-K --safe #-}
open import Categories.Category
-- Reasoning facilities about morphism equivalences (not necessarily 'squares')
module Categories.Morphism.Reasoning {o ℓ e} (C : Category o ℓ e) where
open import Categories.Morphism.Reasoning.Core C public
open import Categories.Morphism.Reasoning.Iso C public
|
using ThesisTools
using Test
@testset "ThesisTools.jl" begin
# Write your own tests here.
end
|
#!/usr/bin/env python
# coding: utf-8
import numpy as np
from scipy import stats
import gzip
import pickle
def generate_new_spectrum(old_spectrum, rate=1):
# auxiliary variable
old_spectrum_ravel = []
# number of channels
m = len(old_spectrum)
# total number of counts
total_count = np.sum(old_spectrum)
for ch in range(m):
old_spectrum_ravel.extend([ch] * old_spectrum[ch])
old_spectrum_ravel = np.array(old_spectrum_ravel)
new_spectrum_ravel = np.random.choice(old_spectrum_ravel, size=int(total_count*rate))
new_spectrum = np.bincount(new_spectrum_ravel,minlength=m)
return new_spectrum
def new_peak(array, count, loc, fwhm):
'''
Generates counts in random locations according to a gaussian probability.
'''
sigma = fwhm/2.355
for i in range(count):
channel = int(round(stats.norm.rvs(loc, sigma),0 ))
array[channel] += 1
return array
def new_bg(array, count_per_channel):
'''
Generates counts in random locations according to a uniform probability.
'''
m = len(array)
return array + np.random.poisson(count_per_channel, size=m)
def simulated_spectra(iter=100, bg_range=(40,41), snr_db_range=(5,6), include_dummy=False, dummy_pos=35, dummy_prob=0.05):
X = np.zeros((iter, 100))
y = np.zeros(iter)
dummy = np.zeros(iter)
list_peakareas = []
for i in range(iter):
snr_db = np.random.randint(snr_db_range[0], snr_db_range[1])
snr = 10**(snr_db/10.)
bg = np.random.randint(bg_range[0], bg_range[1])
peakarea = int(0.5*(snr**2 + np.sqrt(40*bg*snr**2 +snr**4)))
mainpeak = np.random.uniform(0.0,1.0) <= 0.5
dummypeak = np.random.uniform(0.0,1.0) <= dummy_prob
x = np.zeros(100)
x = new_bg(x,bg)
if mainpeak:
new_peak(x, count=peakarea, loc=50, fwhm=3)
y[i] = 1
list_peakareas.append(peakarea)
if dummypeak:
# Cenario A (nao tem dummy peak)
if include_dummy:
new_peak(x, count=np.random.randint(60,100), loc=dummy_pos, fwhm=3)
dummy[i] = 1
X[i,:] = x
return X, y, dummy |
import QL.FOL.coding QL.FOL.deduction
universes u v
namespace fol
open_locale logic_symbol aclogic
variables (L L₁ L₂ : language.{u}) (μ : Type v) (μ₁ : Type*) (μ₂ : Type*) (m m₁ m₂ n : ℕ)
namespace Tait
inductive subformula (μ : Type v) : ℕ → Type (max u v)
| verum {n} : subformula n
| falsum {n} : subformula n
| relation {n} : ∀ {p}, L.pr p → (fin p → subterm L μ n) → subformula n
| neg_relation {n} : ∀ {p}, L.pr p → (fin p → subterm L μ n) → subformula n
| and {n} : subformula n → subformula n → subformula n
| or {n} : subformula n → subformula n → subformula n
| fal {n} : subformula (n + 1) → subformula n
| ex {n} : subformula (n + 1) → subformula n
@[reducible] def formula := subformula L μ 0
@[reducible] def bounded_subformula (m n : ℕ) := subformula L (fin m) n
@[reducible] def bounded_formula (m : ℕ) := bounded_subformula L m 0
@[reducible] def sentence := bounded_formula L 0
variables {L μ n}
namespace subformula
instance : has_univ_quantifier' (subformula L μ) := ⟨@fal L μ⟩
instance : has_exists_quantifier' (subformula L μ) := ⟨@ex L μ⟩
attribute [pattern] has_sup.sup has_inf.inf has_univ_quantifier.univ has_exists_quantifier.ex
@[simp] def not : ∀ {n}, subformula L μ n → subformula L μ n
| n verum := falsum
| n falsum := verum
| n (relation r v) := neg_relation r v
| n (neg_relation r v) := relation r v
| n (and p q) := or (not p) (not q)
| n (or p q) := and (not p) (not q)
| n (fal p) := ex (not p)
| n (ex p) := fal (not p)
def imply (p q : subformula L μ n) := or (not p) q
instance : has_logic_symbol (subformula L μ n) := Tait.logic_simbol_default (subformula L μ n) verum falsum not and or
lemma verum_eq : @verum L μ n = ⊤ := rfl
lemma falsum_eq : @falsum L μ n = ⊥ := rfl
lemma and_eq : @and L μ n = has_inf.inf := rfl
lemma or_eq : @or L μ n = has_sup.sup := rfl
lemma not_eq : @not L μ n = has_negation.neg := rfl
lemma imply_eq : @imply L μ n = has_arrow.arrow := rfl
lemma imply_def (p q : subformula L μ n) : (p ⟶ q) = (∼p) ⊔ q := by simp[←imply_eq, imply]; refl
lemma fal_eq : @fal L μ n = has_univ_quantifier'.univ := rfl
lemma ex_eq : @ex L μ n = has_exists_quantifier'.ex := rfl
@[simp] lemma and.inj' (p₁ q₁ p₂ q₂ : subformula L μ n) : p₁ ⊓ p₂ = q₁ ⊓ q₂ ↔ p₁ = q₁ ∧ p₂ = q₂ :=
by simp[has_inf.inf]
@[simp] lemma or.inj' (p₁ q₁ p₂ q₂ : subformula L μ n) : p₁ ⊔ p₂ = q₁ ⊔ q₂ ↔ p₁ = q₁ ∧ p₂ = q₂ :=
by simp[has_sup.sup]
@[simp] lemma fal.inj' (p q : subformula L μ (n + 1)) : ∀'p = ∀'q ↔ p = q := ⟨fal.inj, congr_arg _⟩
@[simp] lemma ex.inj' (p q : subformula L μ (n + 1)) : ∃'p = ∃'q ↔ p = q :=
by simp[has_exists_quantifier'.ex]
@[simp] lemma not_falsum : ∼(⊥ : subformula L μ n) = ⊤ := rfl
@[simp] lemma not_verum : ∼(⊤ : subformula L μ n) = ⊥ := rfl
@[simp] lemma not_relation {k} (r : L.pr k) (v : fin k → subterm L μ n) : ∼(relation r v) = neg_relation r v := rfl
@[simp] lemma not_neg_relation {k} (r : L.pr k) (v : fin k → subterm L μ n) : ∼(neg_relation r v) = relation r v := rfl
@[simp] lemma not_and (p q : subformula L μ n) : ∼(p ⊓ q) = ∼p ⊔ ∼q := rfl
@[simp] lemma not_or (p q : subformula L μ n) : ∼(p ⊔ q) = ∼p ⊓ ∼q := rfl
@[simp] lemma not_fal (p : subformula L μ (n + 1)) : ∼(∀'p) = ∃'∼p := rfl
@[simp] lemma not_ex (p : subformula L μ (n + 1)) : ∼(∃'p) = ∀'∼p := rfl
@[simp] def complexity : Π {n}, subformula L μ n → ℕ
| n verum := 0
| n falsum := 0
| n (relation r v) := 0
| n (neg_relation r v) := 0
| n (and p q) := max p.complexity q.complexity + 1
| n (or p q) := max p.complexity q.complexity + 1
| n (fal p) := p.complexity + 1
| n (ex p) := p.complexity + 1
@[simp] lemma complexity_top : (⊤ : subformula L μ n).complexity = 0 := by refl
@[simp] lemma complexity_bot : (⊥ : subformula L μ n).complexity = 0 := by refl
@[simp] lemma complexity_and (p q : subformula L μ n) : (p ⊓ q).complexity = max p.complexity q.complexity + 1 := by refl
@[simp] lemma complexity_or (p q : subformula L μ n) : (p ⊔ q).complexity = max p.complexity q.complexity + 1 := by refl
@[simp] lemma complexity_fal (p : subformula L μ (n + 1)) : (∀'p).complexity = p.complexity + 1 := by refl
@[simp] lemma complexity_ex (p : subformula L μ (n + 1)) : (∃'p).complexity = p.complexity + 1 := by refl
def cases' {C : Π n, subformula L μ n → Sort*}
(hverum : Π {n : ℕ}, C n ⊤)
(hfalsum : Π {n : ℕ}, C n ⊥)
(hrelation : Π {n l : ℕ} (r : L.pr l) (v : fin l → subterm L μ n), C n (relation r v))
(hneg_relation : Π {n l : ℕ} (r : L.pr l) (v : fin l → subterm L μ n), C n (neg_relation r v))
(hand : Π {n : ℕ} (p q : subformula L μ n), C n (p ⊓ q))
(hor : Π {n : ℕ} (p q : subformula L μ n), C n (p ⊔ q))
(hfal : Π {n : ℕ} (p : subformula L μ (n + 1)), C n (∀'p))
(hex : Π {n : ℕ} (p : subformula L μ (n + 1)), C n (∃'p)) :
Π {n : ℕ} (p : subformula L μ n), C n p
| n verum := hverum
| n falsum := hfalsum
| n (relation r v) := hrelation r v
| n (neg_relation r v) := hneg_relation r v
| n (and p q) := hand p q
| n (or p q) := hor p q
| n (fal p) := hfal p
| n (ex p) := hex p
@[elab_as_eliminator]
protected def cases_on' {C : Π n, subformula L μ n → Sort*}
{n : ℕ} (p : subformula L μ n)
(verum : Π {n : ℕ}, C n ⊤)
(falsum : Π {n : ℕ}, C n ⊥)
(relation : Π {n l : ℕ} (r : L.pr l) (v : fin l → subterm L μ n), C n (relation r v))
(neg_relation : Π {n l : ℕ} (r : L.pr l) (v : fin l → subterm L μ n), C n (neg_relation r v))
(and : Π {n : ℕ} (p q : subformula L μ n), C n (p ⊓ q))
(or : Π {n : ℕ} (p q : subformula L μ n), C n (p ⊔ q))
(fal : Π {n : ℕ} (p : subformula L μ (n + 1)), C n (∀'p))
(ex : Π {n : ℕ} (p : subformula L μ (n + 1)), C n (∃'p)) :
C n p :=
cases' @verum @falsum @relation @neg_relation @and @or @fal @ex p
def ind {C : Π n, subformula L μ n → Sort*}
(hverum : Π {n : ℕ}, C n ⊤)
(hfalsum : Π {n : ℕ}, C n ⊥)
(hrelation : Π {n l : ℕ} (r : L.pr l) (v : fin l → subterm L μ n), C n (relation r v))
(hneg_relation : Π {n l : ℕ} (r : L.pr l) (v : fin l → subterm L μ n), C n (neg_relation r v))
(hand : Π {n : ℕ} (p q : subformula L μ n), C n p → C n q → C n (p ⊓ q))
(hor : Π {n : ℕ} (p q : subformula L μ n), C n p → C n q → C n (p ⊔ q))
(hfal : Π {n : ℕ} (p : subformula L μ (n + 1)), C (n + 1) p → C n (∀'p))
(hex : Π {n : ℕ} (p : subformula L μ (n + 1)), C (n + 1) p → C n (∃'p)) :
Π {n : ℕ} (p : subformula L μ n), C n p
| n verum := hverum
| n falsum := hfalsum
| n (relation r v) := hrelation r v
| n (neg_relation r v) := hneg_relation r v
| n (and p q) := hand p q (ind p) (ind q)
| n (or p q) := hor p q (ind p) (ind q)
| n (fal p) := hfal p (ind p)
| n (ex p) := hex p (ind p)
--普通に帰納法をすると論理記号で表示されないから
@[elab_as_eliminator]
protected def ind_on {C : Π n, subformula L μ n → Sort*}
{n : ℕ} (p : subformula L μ n)
(verum : Π {n : ℕ}, C n ⊤)
(falsum : Π {n : ℕ}, C n ⊥)
(relation : Π {n l : ℕ} (r : L.pr l) (v : fin l → subterm L μ n), C n (relation r v))
(neg_relation : Π {n l : ℕ} (r : L.pr l) (v : fin l → subterm L μ n), C n (neg_relation r v))
(and : Π {n : ℕ} (p q : subformula L μ n), C n p → C n q → C n (p ⊓ q))
(or : Π {n : ℕ} (p q : subformula L μ n), C n p → C n q → C n (p ⊔ q))
(fal : Π {n : ℕ} (p : subformula L μ (n + 1)), C (n + 1) p → C n (∀'p))
(ex : Π {n : ℕ} (p : subformula L μ (n + 1)), C (n + 1) p → C n (∃'p)) :
C n p :=
ind @verum @falsum @relation @neg_relation @and @or @fal @ex p
def ind_succ {C : Π n, subformula L μ (n + 1) → Sort*}
(hverum : Π {n : ℕ}, C n ⊤)
(hfalsum : Π {n : ℕ}, C n ⊥)
(hrelation : Π {n l : ℕ} (r : L.pr l) (v : fin l → subterm L μ (n + 1)), C n (relation r v))
(hneg_relation : Π {n l : ℕ} (r : L.pr l) (v : fin l → subterm L μ (n + 1)), C n (neg_relation r v))
(hand : Π {n : ℕ} (p q : subformula L μ (n + 1)), C n p → C n q → C n (p ⊓ q))
(hor : Π {n : ℕ} (p q : subformula L μ (n + 1)), C n p → C n q → C n (p ⊔ q))
(hfal : Π {n : ℕ} (p : subformula L μ (n + 1 + 1)), C (n + 1) p → C n (∀'p))
(hex : Π {n : ℕ} (p : subformula L μ (n + 1 + 1)), C (n + 1) p → C n (∃'p)) :
Π {n : ℕ} (p : subformula L μ (n + 1)), C n p
| n verum := hverum
| n falsum := hfalsum
| n (relation r v) := hrelation r v
| n (neg_relation r v) := hneg_relation r v
| n (and p q) := hand p q (ind_succ p) (ind_succ q)
| n (or p q) := hor p q (ind_succ p) (ind_succ q)
| n (fal p) := hfal p (ind_succ p)
| n (ex p) := hex p (ind_succ p)
using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ x, x.2.complexity)⟩]}
@[elab_as_eliminator]
def ind_succ_on {C : Π n, subformula L μ (n + 1) → Sort*}
{n : ℕ} (p : subformula L μ (n + 1))
(verum : Π {n : ℕ}, C n ⊤)
(falsum : Π {n : ℕ}, C n ⊥)
(relation : Π {n l : ℕ} (r : L.pr l) (v : fin l → subterm L μ (n + 1)), C n (relation r v))
(neg_relation : Π {n l : ℕ} (r : L.pr l) (v : fin l → subterm L μ (n + 1)), C n (neg_relation r v))
(and : Π {n : ℕ} (p q : subformula L μ (n + 1)), C n p → C n q → C n (p ⊓ q))
(or : Π {n : ℕ} (p q : subformula L μ (n + 1)), C n p → C n q → C n (p ⊔ q))
(fal : Π {n : ℕ} (p : subformula L μ (n + 1 + 1)), C (n + 1) p → C n (∀'p))
(ex : Π {n : ℕ} (p : subformula L μ (n + 1 + 1)), C (n + 1) p → C n (∃'p)) :
C n p :=
ind_succ @verum @falsum @relation @neg_relation @and @or @fal @ex p
section rew
variables {μ₁ μ₂} (s : μ₁ → subterm L μ₂ n) (f : μ₁ → μ₂)
@[simp] def rew' {μ₁ μ₂} : Π {n}, (μ₁ → subterm L μ₂ n) → subformula L μ₁ n → subformula L μ₂ n
| n s verum := verum
| n s falsum := falsum
| n s (relation p v) := relation p (λ i, subterm.rew s (v i))
| n s (neg_relation p v) := neg_relation p (λ i, subterm.rew s (v i))
| n s (and p q) := and (p.rew' s) (q.rew' s)
| n s (or p q) := or (p.rew' s) (q.rew' s)
| n s (fal p) := fal (p.rew' (subterm.lift ∘ s))
| n s (ex p) := ex (p.rew' (subterm.lift ∘ s))
@[simp] lemma rew'_neg (p : subformula L μ₁ n) : (∼p).rew' s = ∼(p.rew' s) :=
by induction p; simp[←verum_eq, ←falsum_eq, ←and_eq, ←or_eq, ←not_eq, ←fal_eq, ←ex_eq, *] at*
def rew (s : μ₁ → subterm L μ₂ n) : subformula L μ₁ n →ₗ subformula L μ₂ n :=
{ to_fun := rew' s,
map_neg' := λ p, by simp,
map_imply' := λ p q, by simp[imply_def, ←or_eq],
map_and' := λ p q, by refl,
map_or' := λ p q, by refl,
map_top' := by refl,
map_bot' := by refl }
def map (f : μ₁ → μ₂) : subformula L μ₁ n →ₗ subformula L μ₂ n := rew (λ x, &(f x))
@[simp] lemma rew_relation {k} (r : L.pr k) (v : fin k → subterm L μ₁ n) :
rew s (relation r v) = relation r (λ i, subterm.rew s (v i)) := rfl
@[simp] lemma rew_neg_relation {k} (r : L.pr k) (v : fin k → subterm L μ₁ n) :
rew s (neg_relation r v) = neg_relation r (λ i, subterm.rew s (v i)) := rfl
@[simp] lemma rew_fal (p : subformula L μ₁ (n + 1)) :
rew s (∀'p) = ∀'rew (λ x, subterm.lift (s x)) p := rfl
@[simp] lemma rew_ex (p : subformula L μ₁ (n + 1)) :
rew s (∃'p) = ∃'rew (λ x, subterm.lift (s x)) p := rfl
@[simp] lemma map_relation {k} (r : L.pr k) (v : fin k → subterm L μ₁ n) :
map f (relation r v) = relation r (λ x, subterm.map f (v x)) := rfl
@[simp] lemma map_neg_relation {k} (r : L.pr k) (v : fin k → subterm L μ₁ n) :
map f (neg_relation r v) = neg_relation r (λ x, subterm.map f (v x)) := rfl
@[simp] lemma map_fal (p : subformula L μ₁ (n + 1)) :
map f (∀'p) = ∀'map f p := rfl
@[simp] lemma map_ex (p : subformula L μ₁ (n + 1)) :
map f (∃'p) = ∃'map f p := rfl
lemma eq_rew_of_eq {p : subformula L μ₁ n} {s₁ s₂ : μ₁ → subterm L μ₂ n} (h : s₁ = s₂) :
rew s₁ p = rew s₂ p := by rw[h]
lemma eq_map_of_eq {p : subformula L μ₁ n} {f₁ f₂ : μ₁ → μ₂} (h : f₁ = f₂) :
map f₁ p = map f₂ p := by rw[h]
@[simp] lemma rew_metavar (p : subformula L μ n) : rew subterm.metavar p = p :=
by induction p using fol.Tait.subformula.ind_on; simp[subterm.mlift_rew, *]
@[simp] lemma map_id (p : subformula L μ n) : map id p = p := by simp[map]
lemma rew_rew {μ₁ μ₂ μ₃} : ∀ {n} (p : subformula L μ₁ n) (s₀ : μ₁ → subterm L μ₂ n) (s₁ : μ₂ → subterm L μ₃ n),
rew s₁ (rew s₀ p) = rew (λ x, subterm.rew s₁ (s₀ x)) p
| n verum s₀ s₁ := by simp[verum_eq]
| n falsum s₀ s₁ := by simp[falsum_eq]
| n (relation p v) s₀ s₁ := by simp; funext; simp[subterm.rew_rew]
| n (neg_relation p v) s₀ s₁ := by simp; funext; simp[subterm.rew_rew]
| n (and p q) s₀ s₁ := by simp[and_eq, rew_rew p, rew_rew q]
| n (or p q) s₀ s₁ := by simp[or_eq, rew_rew p, rew_rew q]
| n (fal p) s₀ s₁ := by simp[fal_eq, rew_rew p]; refine eq_rew_of_eq (by funext x; simp[subterm.lift_rew])
| n (ex p) s₀ s₁ := by simp[ex_eq, rew_rew p]; refine eq_rew_of_eq (by funext x; simp[subterm.lift_rew])
@[simp] lemma map_map {μ₁ μ₂ μ₃} (f₁ : μ₁ → μ₂) (f₂ : μ₂ → μ₃) (p : subformula L μ₁ n) :
map f₂ (map f₁ p) = map (f₂ ∘ f₁) p :=
by simp[map, rew_rew]
lemma map_inj_of_inj (f : μ₁ → μ₂) (I : function.injective f) :
function.injective (map f : Tait.subformula L μ₁ n → Tait.subformula L μ₂ n) := λ p q,
begin
induction p,
case verum { cases q; simp[map, rew] },
case falsum { cases q; simp[map, rew] },
case relation : n k r v₁
{ cases q; simp[map, rew],
case relation : _ _ r₂ v₂
{ rintros rfl rfl, simp, intros h, funext i, exact subterm.map_inj_of_inj f I (congr_fun h i) } },
case neg_relation : n k r v₁
{ cases q; simp[map, rew],
case neg_relation : _ _ r₂ v₂
{ rintros rfl rfl, simp, intros h, funext i, exact subterm.map_inj_of_inj f I (congr_fun h i) } },
case and : n p₁ q₁ IH₁ IH₂ { cases q; simp[map, rew] at*, intros h₁ h₂, exact ⟨IH₁ _ h₁, IH₂ _ h₂⟩ },
case or : n p₁ q₁ IH₁ IH₂ { cases q; simp[map, rew] at*, intros h₁ h₂, exact ⟨IH₁ _ h₁, IH₂ _ h₂⟩ },
case fal : n p IH
{ cases q; simp[map, rew],
case fal : _ p₂ { intros h, exact IH _ h } },
case ex : n p IH
{ cases q; simp[map, rew],
case ex : _ p₂ { intros h, exact IH _ h } }
end
instance : has_coe (bounded_subformula L 0 n) (subformula L μ n) := ⟨map fin.nil⟩
lemma sentence_coe_def (σ : bounded_subformula L 0 n) : (σ : subformula L μ n) = map fin.nil σ := rfl
@[simp] lemma sentence_coe_self (σ : bounded_subformula L 0 n) : (↑σ : bounded_subformula L 0 n) = σ :=
by simpa [sentence_coe_def] using @eq_map_of_eq _ _ _ _ σ fin.nil id (by ext x; exact fin_zero_elim x)
@[simp] lemma map_sentence_coe (f : fin 0 → μ₂) (σ : bounded_subformula L 0 n) :
map f σ = σ :=
by simp[sentence_coe_def]; refine eq_map_of_eq (by ext x; exact fin_zero_elim x)
@[simp] lemma map_sentence_coe' (f : μ₁ → μ₂) (σ : bounded_subformula L 0 n) :
map f (↑σ : subformula L μ₁ n) = σ :=
by simp only [sentence_coe_def, map_map]; refine eq_map_of_eq (by ext x; exact fin_zero_elim x)
@[simp] lemma complexity_rew (p : subformula L μ₁ n) : complexity (rew s p) = complexity p :=
by induction p using fol.Tait.subformula.ind_on; simp*
end rew
section subst
@[simp] def subst' : Π {n}, subterm L μ n → subformula L μ (n + 1) → subformula L μ n
| n u verum := ⊤
| n u falsum := ⊥
| n u (relation r v) := relation r (λ i, subterm.subst u $ v i)
| n u (neg_relation r v) := neg_relation r (λ i, subterm.subst u $ v i)
| n u (and p q) := subst' u p ⊓ subst' u q
| n u (or p q) := subst' u p ⊔ subst' u q
| n u (fal p) := ∀' (subst' u.lift p)
| n u (ex p) := ∃' (subst' u.lift p)
using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ x, x.2.2.complexity)⟩]}
@[simp] lemma subst'_neg (p : subformula L μ₁ (n + 1)) : ∀ u, subst' u (∼p) = ∼(subst' u p) :=
by apply ind_succ_on p; intros; simp[←verum_eq, ←falsum_eq, ←and_eq, ←or_eq, ←not_eq, ←fal_eq, ←ex_eq, *] at*
def subst (u : subterm L μ n) : subformula L μ (n + 1) →ₗ subformula L μ n :=
{ to_fun := subst' u,
map_neg' := λ p, by simp; refl,
map_imply' := λ p q, by simp[imply_def, ←or_eq],
map_and' := λ p q, by unfold has_inf.inf; simp; refl,
map_or' := λ p q, by unfold has_sup.sup; simp; refl,
map_top' := by unfold has_top.top; simp; refl,
map_bot' := by unfold has_bot.bot; simp; refl }
variables (u : subterm L μ n)
@[simp] lemma subst_relation {k} (r : L.pr k) (v : fin k → subterm L μ (n + 1)) :
subst u (relation r v) = relation r (λ i, u.subst (v i)) := by simp[subst]
@[simp] lemma subst_neg_relation {k} (r : L.pr k) (v : fin k → subterm L μ (n + 1)) :
subst u (neg_relation r v) = neg_relation r (λ i, u.subst (v i)) := by simp[subst]
@[simp] lemma subst_fal (p : subformula L μ (n + 1 + 1)) :
subst u (∀'p) = ∀'subst u.lift p := by simp[←fal_eq, subst]
@[simp] lemma subst_ex (p : subformula L μ (n + 1 + 1)) :
subst u (∃'p) = ∃'subst u.lift p := by simp[←ex_eq, subst]
@[simp] lemma complexity_subst (p : subformula L μ (n + 1)) : ∀ u, complexity (subst u p) = complexity p :=
by apply ind_succ_on p; intros; simp*
variables {μ₁ μ₂} (f : μ₁ → μ₂)
lemma map_subst (p : subformula L μ₁ (n + 1)) : ∀ (u : subterm L μ₁ n),
map f (subst u p) = subst (u.map f) (map f p) :=
by apply ind_succ_on p; intros; simp[*, subterm.map_subst, subterm.map_lift]
end subst
@[simp] def of_tait : Π {n}, subformula L μ n → fol.subformula L μ n
| n verum := ⊤
| n falsum := ⊥
| n (relation r v) := fol.subformula.relation r v
| n (neg_relation r v) := ∼fol.subformula.relation r v
| n (and p q) := p.of_tait ⊓ q.of_tait
| n (or p q) := p.of_tait ⊔ q.of_tait
| n (fal p) := ∀'p.of_tait
| n (ex p) := ∃'p.of_tait
section of_tait
@[simp] lemma of_tait_verum : (of_tait (⊤ : Tait.subformula L μ n)) = ⊤ := rfl
@[simp] lemma of_tait_falsum : (of_tait (⊥ : Tait.subformula L μ n)) = ⊥ := rfl
@[simp] lemma of_tait_and (p q : subformula L μ n) : of_tait (p ⊓ q) = of_tait p ⊓ of_tait q := rfl
@[simp] lemma of_tait_or (p q : subformula L μ n) : of_tait (p ⊔ q) = of_tait p ⊔ of_tait q := rfl
@[simp] lemma of_tait_fal (p : subformula L μ (n + 1)) : of_tait (∀'p) = ∀'of_tait p := rfl
@[simp] lemma of_tait_ex (p : subformula L μ (n + 1)) : of_tait (∃'p) = ∃'of_tait p := rfl
lemma of_tait_subst (p : bounded_subformula L m (n + 1)) : ∀ t, of_tait (subst t p) = fol.subformula.subst t (of_tait p) :=
by apply ind_succ_on p; intros ; simp*
end of_tait
section bounded
variables {m}
section mlift
def mlift {m n} : bounded_subformula L m n →ₗ bounded_subformula L (m + 1) n := map fin.cast_succ
@[simp] lemma mlift_relation {k} (r : L.pr k) (v : fin k → bounded_subterm L m n) :
mlift (relation r v) = relation r (λ i, (v i).mlift) := rfl
@[simp] lemma mlift_neg_relation {k} (r : L.pr k) (v : fin k → bounded_subterm L m n) :
mlift (neg_relation r v) = neg_relation r (λ i, (v i).mlift) := rfl
@[simp] lemma mlift_fal (p : bounded_subformula L m (n + 1)) :
mlift (∀'p) = ∀'mlift p := rfl
@[simp] lemma mslift_ex (p : bounded_subformula L m (n + 1)) :
mlift (∃'p) = ∃'mlift p := rfl
@[simp] lemma mlift_coe (σ : bounded_subformula L 0 n) : mlift (σ : bounded_subformula L m n) = σ :=
by { simp only [sentence_coe_def, mlift, map_map], refine eq_map_of_eq (by ext x; exact fin_zero_elim x) }
lemma mlift_inj : function.injective (@mlift L m n) := map_inj_of_inj _ (rel_embedding.injective _)
@[simp] lemma mlift_inj' (p q : bounded_subformula L m n) :
mlift p = mlift q ↔ p = q :=
⟨λ h, (map_inj_of_inj _ (rel_embedding.injective _)) h, λ h, by rw[h]⟩
end mlift
section push
@[simp] def push' {m} : Π {n}, bounded_subformula L m (n + 1) → bounded_subformula L (m + 1) n
| n verum := ⊤
| n falsum := ⊥
| n (relation p v) := relation p (λ i, (v i).push)
| n (neg_relation p v) := neg_relation p (λ i, (v i).push)
| n (and p q) := p.push' ⊓ q.push'
| n (or p q) := p.push' ⊔ q.push'
| n (fal p) := ∀'p.push'
| n (ex p) := ∃'p.push'
using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ x, x.2.complexity)⟩]}
@[simp] lemma push'_neg : ∀ {n} (p : bounded_subformula L m (n + 1)), (∼p).push' = ∼p.push'
| n verum := by simp[←falsum_eq, ←verum_eq, ←not_eq]
| n falsum := by simp[←falsum_eq, ←verum_eq, ←not_eq]
| n (relation p v) := by simp
| n (neg_relation p v) := by simp
| n (and p q) := by simp[←not_eq, ←and_eq, ←or_eq]; exact ⟨push'_neg p, push'_neg q⟩
| n (or p q) := by simp[←not_eq, ←and_eq, ←or_eq]; exact ⟨push'_neg p, push'_neg q⟩
| n (fal p) := by simp[←not_eq, ←fal_eq, ←ex_eq]; rw[←fal_eq, ←ex_eq]; simp; exact push'_neg p
| n (ex p) := by simp[←not_eq, ←fal_eq, ←ex_eq]; rw[←fal_eq, ←ex_eq]; simp; exact push'_neg p
using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ x, x.2.complexity)⟩]}
def push : bounded_subformula L m (n + 1) →ₗ bounded_subformula L (m + 1) n :=
{ to_fun := push',
map_neg' := λ p, by simp,
map_imply' := λ p q, by simp[imply_def, ←or_eq],
map_and' := λ p q, by simp[←and_eq],
map_or' := λ p q, by simp[←or_eq],
map_top' := by simp[←verum_eq],
map_bot' := by simp[←falsum_eq] }
@[simp] lemma push_relation {k} (r : L.pr k) (v : fin k → bounded_subterm L m (n + 1)) :
push (relation r v) = relation r (λ i, (v i).push) := by simp[push]
@[simp] lemma push_neg_relation {k} (r : L.pr k) (v : fin k → bounded_subterm L m (n + 1)) :
push (neg_relation r v) = neg_relation r (λ i, (v i).push) := by simp[push]
@[simp] lemma push_fal (p : bounded_subformula L m (n + 1 + 1)) :
push (∀'p) = ∀'push p := by simp[push]; unfold has_univ_quantifier'.univ; simp; refl
@[simp] lemma push_ex (p : bounded_subformula L m (n + 1 + 1)) :
push (∃'p) = ∃'push p := by simp[push]; unfold has_exists_quantifier'.ex; simp; refl
@[simp] lemma complexity_push {n} (p : bounded_subformula L m (n + 1)) : p.push.complexity = p.complexity :=
by apply ind_succ_on p; intros; simp*
end push
section pull
@[simp] def pull' {m} : Π {n}, bounded_subformula L (m + 1) n → bounded_subformula L m (n + 1)
| n verum := ⊤
| n falsum := ⊥
| n (relation p v) := relation p (λ i, (v i).pull)
| n (neg_relation p v) := neg_relation p (λ i, (v i).pull)
| n (and p q) := p.pull' ⊓ q.pull'
| n (or p q) := p.pull' ⊔ q.pull'
| n (fal p) := ∀'p.pull'
| n (ex p) := ∃'p.pull'
@[simp] lemma pull_neg (p : bounded_subformula L (m + 1) n) : (∼p).pull' = ∼p.pull' :=
by induction p; simp[←verum_eq, ←falsum_eq, ←and_eq, ←or_eq, ←not_eq, ←fal_eq, ←ex_eq, *] at*; refl
def pull : bounded_subformula L (m + 1) n →ₗ bounded_subformula L m (n + 1) :=
{ to_fun := pull',
map_neg' := λ p, by simp,
map_imply' := λ p q, by simp[imply_def, ←or_eq],
map_and' := λ p q, by refl,
map_or' := λ p q, by refl,
map_top' := by refl,
map_bot' := by refl }
@[simp] lemma pull_relation {k} (r : L.pr k) (v : fin k → bounded_subterm L (m + 1) n) :
pull (relation r v) = relation r (λ i, (v i).pull) := rfl
@[simp] lemma pull_neg_relation {k} (r : L.pr k) (v : fin k → bounded_subterm L (m + 1) n) :
pull (neg_relation r v) = neg_relation r (λ i, (v i).pull) := rfl
@[simp] lemma pull_fal (p : bounded_subformula L (m + 1) (n + 1)) :
pull (∀'p) = ∀'pull p := by simp[pull]; unfold has_univ_quantifier'.univ; simp; refl
@[simp] lemma pull_ex (p : bounded_subformula L (m + 1) (n + 1)) :
pull (∃'p) = ∃'pull p := by simp[pull]; unfold has_exists_quantifier'.ex; simp; refl
@[simp] lemma pull_push (p : bounded_subformula L m (n + 1)) : p.push.pull = p :=
by apply ind_succ_on p; intros; simp[*, (∘)]
end pull
section cast_le
variables {m₁ m₂} (h : m₁ ≤ m₂)
def cast_le (h : m₁ ≤ m₂) : bounded_subformula L m₁ n →ₗ bounded_subformula L m₂ n :=
map (fin.cast_le h)
@[simp] lemma cast_le_inj (p q : bounded_subformula L m₁ n) : cast_le h p = cast_le h q ↔ p = q :=
⟨λ h, map_inj_of_inj _ (rel_embedding.injective _) h, λ h, by simp[h]⟩
@[simp] lemma cast_le_function {k} (r : L.pr k) (v : fin k → bounded_subterm L m₁ n) :
cast_le h (relation r v) = relation r (λ i, subterm.cast_le h (v i)) :=
by simp[cast_le]; refl
@[simp] lemma cast_le_neg_function {k} (r : L.pr k) (v : fin k → bounded_subterm L m₁ n) :
cast_le h (neg_relation r v) = neg_relation r (λ i, subterm.cast_le h (v i)) :=
by simp[cast_le]; refl
@[simp] lemma cast_le_fal (p : bounded_subformula L m₁ (n + 1)) :
cast_le h (∀'p) = ∀'(cast_le h p) :=
by simp[cast_le]; refl
@[simp] lemma cast_le_ex (p : bounded_subformula L m₁ (n + 1)) :
cast_le h (∃'p) = ∃'(cast_le h p) :=
by simp[cast_le]; refl
@[simp] lemma cast_le_cast_le {m₁ m₂ m₃ : ℕ} (h₁ : m₁ ≤ m₂) (h₂ : m₂ ≤ m₃) (p : bounded_subformula L m₁ n) :
cast_le h₂ (cast_le h₁ p) = cast_le (le_trans h₁ h₂) p :=
by simp[cast_le]
@[simp] lemma uniform_subst (u : bounded_subterm L m₁ n) (p : bounded_subformula L m₁ (n + 1)) :
cast_le h (subst u p) = subst (subterm.cast_le h u) (cast_le h p) :=
by simp[cast_le, subterm.cast_le, map_subst]
variables {m₁ m₂} (f : fin (m₁ + 1) → fin m₂)
@[simp] lemma cast_eq_id (h : m ≤ m) :
(cast_le h : bounded_subformula L m n→ bounded_subformula L m n) = id :=
by { ext p, simp[cast_le, show ⇑(fin.cast_le h) = id, by funext x; simp; ext; simp], }
lemma cast_le_eq_mlift (p : bounded_subformula L m n) (h : m ≤ m + 1) :
cast_le h p = mlift p :=
by simp[cast_le, mlift]; refine eq_map_of_eq (by ext x; simp)
@[simp] lemma cast_le_mlift (p : bounded_subformula L m₁ n) (h : m₁ + 1 ≤ m₂) :
cast_le h (mlift p) = cast_le (nat.le_of_succ_le h) p :=
by simp[cast_le, mlift]; congr
@[simp] lemma mlift_cast_le (p : bounded_subformula L m₁ n) (h : m₁ ≤ m₂) :
mlift (cast_le h p) = cast_le (le_add_right h) p :=
by simp[cast_le, mlift]; congr
lemma push_eq_subst_mlift (p : bounded_subformula L m (n + 1)) :
push p = subst &(fin.last m) p.mlift :=
by apply ind_succ_on p; intros; simp*
@[simp] lemma uniform_push (h : m₁ + 1 ≤ m₂) (p : bounded_subformula L m₁ (n + 1)) :
cast_le h (push p) = subst &(fin.cast_le h $ fin.last m₁) (cast_le (nat.le_of_succ_le h) p) :=
by simp[push_eq_subst_mlift]
end cast_le
section of_tait
lemma of_tait_mlift (p : bounded_subformula L m n) : of_tait (mlift p) = fol.subformula.mlift (of_tait p) :=
by induction p using fol.Tait.subformula.ind_on; simp*
lemma of_tait_push (p : bounded_subformula L m (n + 1)) : of_tait (push p) = fol.subformula.push (of_tait p) :=
by apply ind_succ_on p; intros; simp*
lemma of_tait_pull (p : bounded_subformula L (m + 1) n) : of_tait (pull p) = fol.subformula.pull (of_tait p) :=
by induction p using fol.Tait.subformula.ind_on; simp*
end of_tait
end bounded
section nat
@[simp] def arity : Π {n}, subformula L ℕ n → ℕ
| n verum := 0
| n falsum := 0
| n (relation r v) := ⨆ᶠ i, (v i).arity
| n (neg_relation r v) := ⨆ᶠ i, (v i).arity
| n (and p q) := max p.arity q.arity
| n (or p q) := max p.arity q.arity
| n (fal p) := p.arity
| n (ex p) := p.arity
@[simp] lemma arity_verum : (⊤ : subformula L ℕ n).arity = 0 := rfl
@[simp] lemma arity_falsum : (⊥ : subformula L ℕ n).arity = 0 := rfl
@[simp] lemma arity_and (p q : subformula L ℕ n) : (p ⊓ q).arity = max p.arity q.arity := rfl
@[simp] lemma arity_or (p q : subformula L ℕ n) : (p ⊔ q).arity = max p.arity q.arity := rfl
@[simp] lemma arity_fal (p : subformula L ℕ (n + 1)) : (∀'p).arity = p.arity := rfl
@[simp] lemma arity_ex (p : subformula L ℕ (n + 1)) : (∃'p).arity = p.arity := rfl
@[simp] lemma arity_not (p : subformula L ℕ n) : (∼p).arity = p.arity :=
by simp[←not_eq]; induction p; simp*
@[simp] def to_bform {m} : Π {n} (p : subformula L ℕ n), p.arity ≤ m → bounded_subformula L m n
| n verum h := verum
| n falsum h := falsum
| n (relation r v) h := relation r (λ i, (v i).to_bterm (by simp at h; exact h i))
| n (neg_relation r v) h := neg_relation r (λ i, (v i).to_bterm (by simp at h; exact h i))
| n (and p q) h := have p.arity ≤ m ∧ q.arity ≤ m, by simpa using h, and (p.to_bform this.1) (q.to_bform this.2)
| n (or p q) h := have p.arity ≤ m ∧ q.arity ≤ m, by simpa using h, or (p.to_bform this.1) (q.to_bform this.2)
| n (fal p) h := fal (p.to_bform (by simpa using h))
| n (ex p) h := ex (p.to_bform (by simpa using h))
@[simp] lemma to_bform_verum (h) : ((⊤ : subformula L ℕ n).to_bform h : bounded_subformula L m n) = ⊤ := rfl
@[simp] lemma to_bform_falsum (h) : ((⊥ : subformula L ℕ n).to_bform h : bounded_subformula L m n) = ⊥ := rfl
@[simp] lemma to_bform_and (p q : subformula L ℕ n) (h) :
((p ⊓ q).to_bform h : bounded_subformula L m n) = p.to_bform (by simp at h; exact h.1) ⊓ q.to_bform (by simp at h; exact h.2) := rfl
@[simp] lemma to_bform_or (p q : subformula L ℕ n) (h) :
((p ⊔ q).to_bform h : bounded_subformula L m n) = p.to_bform (by simp at h; exact h.1) ⊔ q.to_bform (by simp at h; exact h.2) := rfl
@[simp] lemma to_bform_fal (p : subformula L ℕ (n + 1)) (h) :
((∀'p).to_bform h : bounded_subformula L m n) = ∀'p.to_bform (by simpa using h) := rfl
@[simp] lemma to_bform_ex (p : subformula L ℕ (n + 1)) (h) :
((∃'p).to_bform h : bounded_subformula L m n) = ∃'p.to_bform (by simpa using h) := rfl
@[simp] lemma to_bform_not (p : subformula L ℕ n) {h} : (to_bform (∼p) h : bounded_subformula L m n) = ∼(to_bform p (by simpa using h)) :=
by { simp[←not_eq], induction p; simp[*],
case and : n p q IH₁ IH₂ { refine ⟨IH₁, IH₂⟩ },
case or : n p q IH₁ IH₂ { refine ⟨IH₁, IH₂⟩ },
case fal : n p IH { exact IH },
case ex : n p IH { exact IH } }
end nat
variables {T : bounded_preTheory L m} {m}
open axiomatic_classical_logic' axiomatic_classical_logic
lemma to_tait_not_equiv_aux : ∀ {m} (p : Tait.bounded_formula L m), ∅ ⊢ (∼p).of_tait ⟷ ∼p.of_tait
| m verum := by simp[verum_eq]
| m falsum := by apply equiv_symm; simp[falsum_eq]
| m (relation r v) := by simp
| m (neg_relation r v) := by simp
| m (and p q) := by { simp[and_eq],
have : ∅ ⊢ (∼p).of_tait ⊔ (∼q).of_tait ⟷ ∼p.of_tait ⊔ ∼q.of_tait,
from equiv_or_of_equiv (to_tait_not_equiv_aux p) (to_tait_not_equiv_aux q),
refine equiv_trans this (equiv_symm (neg_and_equiv_or_neg _ _)) }
| m (or p q) := by { simp[or_eq],
have : ∅ ⊢ (∼p).of_tait ⊓ (∼q).of_tait ⟷ ∼p.of_tait ⊓ ∼q.of_tait,
from equiv_and_of_equiv (to_tait_not_equiv_aux p) (to_tait_not_equiv_aux q),
refine equiv_trans this (equiv_symm (neg_or_equiv_and_neg _ _)) }
| m (fal p) :=
begin
simp[fal_eq],
have : ∅ ⊢ ∃'(∼p).of_tait ⟷ ∃'∼p.of_tait,
from provable.equiv_exists_of_equiv (by simpa[←of_tait_push] using to_tait_not_equiv_aux (push p)),
refine equiv_trans this (equiv_symm $ provable.neg_forall_pnf p.of_tait)
end
| m (ex p) :=
begin
simp[ex_eq],
have : ∅ ⊢ ∀'(∼p).of_tait ⟷ ∀'∼p.of_tait,
from provable.equiv_forall_of_equiv (by simpa[←of_tait_push] using to_tait_not_equiv_aux (push p)),
refine equiv_trans this (equiv_symm $ provable.neg_exists_pnf p.of_tait)
end
using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ x, x.2.complexity)⟩]}
lemma to_tait_not_equiv (p : Tait.bounded_formula L m) : T ⊢ (∼p).of_tait ⟷ ∼p.of_tait :=
weakening (by simp) (to_tait_not_equiv_aux p)
end subformula
end Tait
namespace subformula
variables {L μ m n}
@[simp] def to_tait : Π {n}, subformula L μ n → Tait.subformula L μ n
| n verum := Tait.subformula.verum
| n (relation r v) := Tait.subformula.relation r v
| n (imply p q) := p.to_tait.imply q.to_tait
| n (neg p) := p.to_tait.not
| n (fal p) := p.to_tait.fal
@[simp] lemma to_tait_verum : to_tait (⊤ : subformula L μ n) = ⊤ := rfl
@[simp] lemma to_tait_imply (p q : subformula L μ n) : to_tait (p ⟶ q) = to_tait p ⟶ to_tait q := rfl
@[simp] lemma to_tait_neg (p : subformula L μ n) : to_tait (∼p) = ∼to_tait p := rfl
@[simp] lemma to_tait_fal (p : subformula L μ (n + 1)) : to_tait (∀'p) = ∀'to_tait p := rfl
variables (T : bounded_preTheory L m)
lemma to_tait_push (p : bounded_subformula L m (n + 1)) : to_tait (push p) = Tait.subformula.push (to_tait p) :=
by apply ind_succ_on p; intros; simp*
open axiomatic_classical_logic' axiomatic_classical_logic
lemma to_tait_of_tait_aux : ∀ {m} (p : bounded_formula L m), ∅ ⊢ p.to_tait.of_tait ⟷ p
| m verum := by simp[top_eq]
| m (relation r v) := by simp
| m (imply p q) :=
begin
simp[imply_eq, Tait.subformula.imply_def],
have : ∅ ⊢ ∼p ⊔ q ⟷ p ⟶ q, from equiv_symm impl_iff_or,
refine equiv_of_equiv this _ (by simp),
refine equiv_or_of_equiv
(equiv_symm $ equiv_trans (Tait.subformula.to_tait_not_equiv_aux p.to_tait) (equiv_neg_of_equiv $ to_tait_of_tait_aux p))
(equiv_symm $ to_tait_of_tait_aux q),
end
| m (neg p) :=
by simp[neg_eq]; refine equiv_trans (Tait.subformula.to_tait_not_equiv_aux p.to_tait) (equiv_neg_of_equiv $ to_tait_of_tait_aux p)
| m (fal p) := by { simp[fal_eq], refine provable.equiv_forall_of_equiv
(by { simpa[←Tait.subformula.of_tait_push, to_tait_push] using to_tait_of_tait_aux (push p) }) }
using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ x, x.2.complexity)⟩]}
lemma to_tait_of_tait {T : bounded_preTheory L m} (p : bounded_formula L m) : T ⊢ p.to_tait.of_tait ⟷ p :=
weakening (by simp) (to_tait_of_tait_aux p)
end subformula
end fol |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.