(*  Title:      HOL/Hilbert_Choice.thy
    Author:     Lawrence C Paulson, Tobias Nipkow
    Author:     Viorel Preoteasa (Results about complete distributive lattices)
    Copyright   2001  University of Cambridge
*)

section \<open>Hilbert's Epsilon-Operator and the Axiom of Choice\<close>

theory Hilbert_Choice
  imports Wellfounded
  keywords "specification" :: thy_goal_defn
begin

subsection \<open>Hilbert's epsilon\<close>

axiomatization Eps :: "('a \<Rightarrow> bool) \<Rightarrow> 'a"
  where someI: "P x \<Longrightarrow> P (Eps P)"

syntax (epsilon)
  "_Eps" :: "pttrn \<Rightarrow> bool \<Rightarrow> 'a"  ("(3\<some>_./ _)" [0, 10] 10)
syntax (input)
  "_Eps" :: "pttrn \<Rightarrow> bool \<Rightarrow> 'a"  ("(3@ _./ _)" [0, 10] 10)
syntax
  "_Eps" :: "pttrn \<Rightarrow> bool \<Rightarrow> 'a"  ("(3SOME _./ _)" [0, 10] 10)
translations
  "SOME x. P" \<rightleftharpoons> "CONST Eps (\<lambda>x. P)"

print_translation \<open>
  [(\<^const_syntax>\<open>Eps\<close>, fn _ => fn [Abs abs] =>
      let val (x, t) = Syntax_Trans.atomic_abs_tr' abs
      in Syntax.const \<^syntax_const>\<open>_Eps\<close> $ x $ t end)]
\<close> \<comment> \<open>to avoid eta-contraction of body\<close>

definition inv_into :: "'a set \<Rightarrow> ('a \<Rightarrow> 'b) \<Rightarrow> ('b \<Rightarrow> 'a)" where
"inv_into A f = (\<lambda>x. SOME y. y \<in> A \<and> f y = x)"

lemma inv_into_def2: "inv_into A f x = (SOME y. y \<in> A \<and> f y = x)"
by(simp add: inv_into_def)

abbreviation inv :: "('a \<Rightarrow> 'b) \<Rightarrow> ('b \<Rightarrow> 'a)" where
"inv \<equiv> inv_into UNIV"

subsection \<open>Hilbert's Epsilon-operator\<close>

lemma Eps_cong:
  assumes "\<And>x. P x = Q x"
  shows "Eps P = Eps Q"
  using ext[of P Q, OF assms] by simp

text \<open>
  Easier to use than \<open>someI\<close> if the witness comes from an
  existential formula.
\<close>
lemma someI_ex [elim?]: "\<exists>x. P x \<Longrightarrow> P (SOME x. P x)"
  by (elim exE someI)

lemma some_eq_imp:
  assumes "Eps P = a" "P b" shows "P a"
  using assms someI_ex by force

text \<open>
  Easier to use than \<open>someI\<close> because the conclusion has only one
  occurrence of \<^term>\<open>P\<close>.
\<close>
lemma someI2: "P a \<Longrightarrow> (\<And>x. P x \<Longrightarrow> Q x) \<Longrightarrow> Q (SOME x. P x)"
  by (blast intro: someI)

text \<open>
  Easier to use than \<open>someI2\<close> if the witness comes from an
  existential formula.
\<close>
lemma someI2_ex: "\<exists>a. P a \<Longrightarrow> (\<And>x. P x \<Longrightarrow> Q x) \<Longrightarrow> Q (SOME x. P x)"
  by (blast intro: someI2)

lemma someI2_bex: "\<exists>a\<in>A. P a \<Longrightarrow> (\<And>x. x \<in> A \<and> P x \<Longrightarrow> Q x) \<Longrightarrow> Q (SOME x. x \<in> A \<and> P x)"
  by (blast intro: someI2)

lemma some_equality [intro]: "P a \<Longrightarrow> (\<And>x. P x \<Longrightarrow> x = a) \<Longrightarrow> (SOME x. P x) = a"
  by (blast intro: someI2)

lemma some1_equality: "\<exists>!x. P x \<Longrightarrow> P a \<Longrightarrow> (SOME x. P x) = a"
  by blast

lemma some_eq_ex: "P (SOME x. P x) \<longleftrightarrow> (\<exists>x. P x)"
  by (blast intro: someI)

lemma some_in_eq: "(SOME x. x \<in> A) \<in> A \<longleftrightarrow> A \<noteq> {}"
  unfolding ex_in_conv[symmetric] by (rule some_eq_ex)

lemma some_eq_trivial [simp]: "(SOME y. y = x) = x"
  by (rule some_equality) (rule refl)

lemma some_sym_eq_trivial [simp]: "(SOME y. x = y) = x"
  by (iprover intro: some_equality)

subsection \<open>Axiom of Choice, Proved Using the Description Operator\<close>

lemma choice: "\<forall>x. \<exists>y. Q x y \<Longrightarrow> \<exists>f. \<forall>x. Q x (f x)"
  by (fast elim: someI)

lemma bchoice: "\<forall>x\<in>S. \<exists>y. Q x y \<Longrightarrow> \<exists>f. \<forall>x\<in>S. Q x (f x)"
  by (fast elim: someI)

lemma choice_iff: "(\<forall>x. \<exists>y. Q x y) \<longleftrightarrow> (\<exists>f. \<forall>x. Q x (f x))"
  by (fast elim: someI)

lemma choice_iff': "(\<forall>x. P x \<longrightarrow> (\<exists>y. Q x y)) \<longleftrightarrow> (\<exists>f. \<forall>x. P x \<longrightarrow> Q x (f x))"
  by (fast elim: someI)

lemma bchoice_iff: "(\<forall>x\<in>S. \<exists>y. Q x y) \<longleftrightarrow> (\<exists>f. \<forall>x\<in>S. Q x (f x))"
  by (fast elim: someI)

lemma bchoice_iff': "(\<forall>x\<in>S. P x \<longrightarrow> (\<exists>y. Q x y)) \<longleftrightarrow> (\<exists>f. \<forall>x\<in>S. P x \<longrightarrow> Q x (f x))"
  by (fast elim: someI)

lemma dependent_nat_choice:
  assumes 1: "\<exists>x. P 0 x"
    and 2: "\<And>x n. P n x \<Longrightarrow> \<exists>y. P (Suc n) y \<and> Q n x y"
  shows "\<exists>f. \<forall>n. P n (f n) \<and> Q n (f n) (f (Suc n))"
proof (intro exI allI conjI)
  fix n
  define f where "f = rec_nat (SOME x. P 0 x) (\<lambda>n x. SOME y. P (Suc n) y \<and> Q n x y)"
  then have "P 0 (f 0)" "\<And>n. P n (f n) \<Longrightarrow> P (Suc n) (f (Suc n)) \<and> Q n (f n) (f (Suc n))"
    using someI_ex[OF 1] someI_ex[OF 2] by simp_all
  then show "P n (f n)" "Q n (f n) (f (Suc n))"
    by (induct n) auto
qed

lemma finite_subset_Union:
  assumes "finite A" "A \<subseteq> \<Union>\<B>"
  obtains \<F> where "finite \<F>" "\<F> \<subseteq> \<B>" "A \<subseteq> \<Union>\<F>"
proof -
  have "\<forall>x\<in>A. \<exists>B\<in>\<B>. x\<in>B"
    using assms by blast
  then obtain f where f: "\<And>x. x \<in> A \<Longrightarrow> f x \<in> \<B> \<and> x \<in> f x"
    by (auto simp add: bchoice_iff Bex_def)
  show thesis
  proof
    show "finite (f ` A)"
      using assms by auto
  qed (use f in auto)
qed

subsection \<open>Function Inverse\<close>

lemma inv_def: "inv f = (\<lambda>y. SOME x. f x = y)"
  by (simp add: inv_into_def)

lemma inv_into_into: "x \<in> f ` A \<Longrightarrow> inv_into A f x \<in> A"
  by (simp add: inv_into_def) (fast intro: someI2)

lemma inv_identity [simp]: "inv (\<lambda>a. a) = (\<lambda>a. a)"
  by (simp add: inv_def)

lemma inv_id [simp]: "inv id = id"
  by (simp add: id_def)

lemma inv_into_f_f [simp]: "inj_on f A \<Longrightarrow> x \<in> A \<Longrightarrow> inv_into A f (f x) = x"
  by (simp add: inv_into_def inj_on_def) (blast intro: someI2)

lemma inv_f_f: "inj f \<Longrightarrow> inv f (f x) = x"
  by simp

lemma f_inv_into_f: "y \<in> f`A \<Longrightarrow> f (inv_into A f y) = y"
  by (simp add: inv_into_def) (fast intro: someI2)

lemma inv_into_f_eq: "inj_on f A \<Longrightarrow> x \<in> A \<Longrightarrow> f x = y \<Longrightarrow> inv_into A f y = x"
  by (erule subst) (fast intro: inv_into_f_f)

lemma inv_f_eq: "inj f \<Longrightarrow> f x = y \<Longrightarrow> inv f y = x"
  by (simp add:inv_into_f_eq)

lemma inj_imp_inv_eq: "inj f \<Longrightarrow> \<forall>x. f (g x) = x \<Longrightarrow> inv f = g"
  by (blast intro: inv_into_f_eq)

text \<open>But is it useful?\<close>
lemma inj_transfer:
  assumes inj: "inj f"
    and minor: "\<And>y. y \<in> range f \<Longrightarrow> P (inv f y)"
  shows "P x"
proof -
  have "f x \<in> range f" by auto
  then have "P(inv f (f x))" by (rule minor)
  then show "P x" by (simp add: inv_into_f_f [OF inj])
qed

lemma inj_iff: "inj f \<longleftrightarrow> inv f \<circ> f = id"
  by (simp add: o_def fun_eq_iff) (blast intro: inj_on_inverseI inv_into_f_f)

lemma inv_o_cancel[simp]: "inj f \<Longrightarrow> inv f \<circ> f = id"
  by (simp add: inj_iff)

lemma o_inv_o_cancel[simp]: "inj f \<Longrightarrow> g \<circ> inv f \<circ> f = g"
  by (simp add: comp_assoc)

lemma inv_into_image_cancel[simp]: "inj_on f A \<Longrightarrow> S \<subseteq> A \<Longrightarrow> inv_into A f ` f ` S = S"
  by (fastforce simp: image_def)

lemma inj_imp_surj_inv: "inj f \<Longrightarrow> surj (inv f)"
  by (blast intro!: surjI inv_into_f_f)

lemma surj_f_inv_f: "surj f \<Longrightarrow> f (inv f y) = y"
  by (simp add: f_inv_into_f)

lemma bij_inv_eq_iff: "bij p \<Longrightarrow> x = inv p y \<longleftrightarrow> p x = y"
  using surj_f_inv_f[of p] by (auto simp add: bij_def)

lemma inv_into_injective:
  assumes eq: "inv_into A f x = inv_into A f y"
    and x: "x \<in> f`A"
    and y: "y \<in> f`A"
  shows "x = y"
proof -
  from eq have "f (inv_into A f x) = f (inv_into A f y)"
    by simp
  with x y show ?thesis
    by (simp add: f_inv_into_f)
qed

lemma inj_on_inv_into: "B \<subseteq> f`A \<Longrightarrow> inj_on (inv_into A f) B"
  by (blast intro: inj_onI dest: inv_into_injective injD)

lemma inj_imp_bij_betw_inv: "inj f \<Longrightarrow> bij_betw (inv f) (f ` M) M"
  by (simp add: bij_betw_def image_subsetI inj_on_inv_into)

lemma bij_betw_inv_into: "bij_betw f A B \<Longrightarrow> bij_betw (inv_into A f) B A"
  by (auto simp add: bij_betw_def inj_on_inv_into)

lemma surj_imp_inj_inv: "surj f \<Longrightarrow> inj (inv f)"
  by (simp add: inj_on_inv_into)

lemma surj_iff: "surj f \<longleftrightarrow> f \<circ> inv f = id"
  by (auto intro!: surjI simp: surj_f_inv_f fun_eq_iff[where 'b='a])

lemma surj_iff_all: "surj f \<longleftrightarrow> (\<forall>x. f (inv f x) = x)"
  by (simp add: o_def surj_iff fun_eq_iff)

lemma surj_imp_inv_eq:
  assumes "surj f" and gf: "\<And>x. g (f x) = x"
  shows "inv f = g"
proof (rule ext)
  fix x
  have "g (f (inv f x)) = inv f x"
    by (rule gf)
  then show "inv f x = g x"
    by (simp add: surj_f_inv_f \<open>surj f\<close>)
qed

lemma bij_imp_bij_inv: "bij f \<Longrightarrow> bij (inv f)"
  by (simp add: bij_def inj_imp_surj_inv surj_imp_inj_inv)

lemma inv_equality: "(\<And>x. g (f x) = x) \<Longrightarrow> (\<And>y. f (g y) = y) \<Longrightarrow> inv f = g"
  by (rule ext) (auto simp add: inv_into_def)

lemma inv_inv_eq: "bij f \<Longrightarrow> inv (inv f) = f"
  by (rule inv_equality) (auto simp add: bij_def surj_f_inv_f)

text \<open>
  \<open>bij (inv f)\<close> implies little about \<open>f\<close>. Consider \<open>f :: bool \<Rightarrow> bool\<close> such
  that \<open>f True = f False = True\<close>. Then it ia consistent with axiom \<open>someI\<close>
  that \<open>inv f\<close> could be any function at all, including the identity function.
  If \<open>inv f = id\<close> then \<open>inv f\<close> is a bijection, but \<open>inj f\<close>, \<open>surj f\<close> and \<open>inv
  (inv f) = f\<close> all fail.
\<close>

lemma inv_into_comp:
  "inj_on f (g ` A) \<Longrightarrow> inj_on g A \<Longrightarrow> x \<in> f ` g ` A \<Longrightarrow>
    inv_into A (f \<circ> g) x = (inv_into A g \<circ> inv_into (g ` A) f) x"
  by (auto simp: f_inv_into_f inv_into_into intro: inv_into_f_eq comp_inj_on)

lemma o_inv_distrib: "bij f \<Longrightarrow> bij g \<Longrightarrow> inv (f \<circ> g) = inv g \<circ> inv f"
  by (rule inv_equality) (auto simp add: bij_def surj_f_inv_f)

lemma image_f_inv_f: "surj f \<Longrightarrow> f ` (inv f ` A) = A"
  by (simp add: surj_f_inv_f image_comp comp_def)

lemma image_inv_f_f: "inj f \<Longrightarrow> inv f ` (f ` A) = A"
  by simp

lemma bij_image_Collect_eq:
  assumes "bij f"
  shows "f ` Collect P = {y. P (inv f y)}"
proof
  show "f ` Collect P \<subseteq> {y. P (inv f y)}"
    using assms by (force simp add: bij_is_inj)
  show "{y. P (inv f y)} \<subseteq> f ` Collect P"
    using assms by (blast intro: bij_is_surj [THEN surj_f_inv_f, symmetric])
qed

lemma bij_vimage_eq_inv_image:
  assumes "bij f"
  shows "f -` A = inv f ` A"
proof
  show "f -` A \<subseteq> inv f ` A"
    using assms by (blast intro: bij_is_inj [THEN inv_into_f_f, symmetric])
  show "inv f ` A \<subseteq> f -` A"
    using assms by (auto simp add: bij_is_surj [THEN surj_f_inv_f])
qed

lemma inv_fn_o_fn_is_id:
  fixes f::"'a \<Rightarrow> 'a"
  assumes "bij f"
  shows "((inv f)^^n) o (f^^n) = (\<lambda>x. x)"
proof -
  have "((inv f)^^n)((f^^n) x) = x" for x n
  proof (induction n)
    case (Suc n)
    have *: "(inv f) (f y) = y" for y
      by (simp add: assms bij_is_inj)
    have "(inv f ^^ Suc n) ((f ^^ Suc n) x) = (inv f^^n) (inv f (f ((f^^n) x)))"
      by (simp add: funpow_swap1)
    also have "... = (inv f^^n) ((f^^n) x)"
      using * by auto
    also have "... = x" using Suc.IH by auto
    finally show ?case by simp
  qed (auto)
  then show ?thesis unfolding o_def by blast
qed

lemma fn_o_inv_fn_is_id:
  fixes f::"'a \<Rightarrow> 'a"
  assumes "bij f"
  shows "(f^^n) o ((inv f)^^n) = (\<lambda>x. x)"
proof -
  have "(f^^n) (((inv f)^^n) x) = x" for x n
  proof (induction n)
    case (Suc n)
    have *: "f(inv f y) = y" for y
      using bij_inv_eq_iff[OF assms] by auto
    have "(f ^^ Suc n) ((inv f ^^ Suc n) x) = (f^^n) (f (inv f ((inv f^^n) x)))"
      by (simp add: funpow_swap1)
    also have "... = (f^^n) ((inv f^^n) x)"
      using * by auto
    also have "... = x" using Suc.IH by auto
    finally show ?case by simp
  qed (auto)
  then show ?thesis unfolding o_def by blast
qed

lemma inv_fn:
  fixes f::"'a \<Rightarrow> 'a"
  assumes "bij f"
  shows "inv (f^^n) = ((inv f)^^n)"
proof -
  have "inv (f^^n) x = ((inv f)^^n) x" for x
  proof (rule inv_into_f_eq)
    show "inj (f ^^ n)"
      by (simp add: inj_fn[OF bij_is_inj [OF assms]])
    show "(f ^^ n) ((inv f ^^ n) x) = x"
      using fn_o_inv_fn_is_id[OF assms, THEN fun_cong] by force
  qed auto
  then show ?thesis by auto
qed

lemma funpow_inj_finite: \<^marker>\<open>contributor \<open>Lars Noschinski\<close>\<close>
  assumes \<open>inj p\<close> \<open>finite {y. \<exists>n. y = (p ^^ n) x}\<close>
  obtains n where \<open>n > 0\<close> \<open>(p ^^ n) x = x\<close>
proof -
  have \<open>infinite (UNIV :: nat set)\<close>
    by simp
  moreover have \<open>{y. \<exists>n. y = (p ^^ n) x} = (\<lambda>n. (p ^^ n) x) ` UNIV\<close>
    by auto
  with assms have \<open>finite \<dots>\<close>
    by simp
  ultimately have "\<exists>n \<in> UNIV. \<not> finite {m \<in> UNIV. (p ^^ m) x = (p ^^ n) x}"
    by (rule pigeonhole_infinite)
  then obtain n where "infinite {m. (p ^^ m) x = (p ^^ n) x}" by auto
  then have "infinite ({m. (p ^^ m) x = (p ^^ n) x} - {n})" by auto
  then have "({m. (p ^^ m) x = (p ^^ n) x} - {n}) \<noteq> {}"
    by (auto simp add: subset_singleton_iff)
  then obtain m where m: "(p ^^ m) x = (p ^^ n) x" "m \<noteq> n" by auto

  { fix m n assume "(p ^^ n) x = (p ^^ m) x" "m < n"
    have "(p ^^ (n - m)) x = inv (p ^^ m) ((p ^^ m) ((p ^^ (n - m)) x))"
      using \<open>inj p\<close> by (simp add: inv_f_f)
    also have "((p ^^ m) ((p ^^ (n - m)) x)) = (p ^^ n) x"
      using \<open>m < n\<close> funpow_add [of m \<open>n - m\<close> p] by simp
    also have "inv (p ^^ m) \<dots> = x"
      using \<open>inj p\<close>  by (simp add: \<open>(p ^^ n) x = _\<close>)
    finally have "(p ^^ (n - m)) x = x" "0 < n - m"
      using \<open>m < n\<close> by auto }
  note general = this

  show thesis
  proof (cases m n rule: linorder_cases)
    case less
    then have \<open>n - m > 0\<close> \<open>(p ^^ (n - m)) x = x\<close>
      using general [of n m] m by simp_all
    then show thesis by (blast intro: that)
  next
    case equal
    then show thesis using m by simp
  next
    case greater
    then have \<open>m - n > 0\<close> \<open>(p ^^ (m - n)) x = x\<close>
      using general [of m n] m by simp_all
    then show thesis by (blast intro: that)
  qed
qed

lemma mono_inv:
  fixes f::"'a::linorder \<Rightarrow> 'b::linorder"
  assumes "mono f" "bij f"
  shows "mono (inv f)"
proof
  fix x y::'b assume "x \<le> y"
  from \<open>bij f\<close> obtain a b where x: "x = f a" and y: "y = f b" by(fastforce simp: bij_def surj_def)
  show "inv f x \<le> inv f y"
  proof (rule le_cases)
    assume "a \<le> b"
    thus ?thesis using  \<open>bij f\<close> x y by(simp add: bij_def inv_f_f)
  next
    assume "b \<le> a"
    hence "f b \<le> f a" by(rule monoD[OF \<open>mono f\<close>])
    hence "y \<le> x" using x y by simp
    hence "x = y" using \<open>x \<le> y\<close> by auto
    thus ?thesis by simp
  qed
qed

lemma strict_mono_inv_on_range:
  fixes f :: "'a::linorder \<Rightarrow> 'b::order"
  assumes "strict_mono f"
  shows "strict_mono_on (range f) (inv f)"
proof (clarsimp simp: strict_mono_on_def)
  fix x y
  assume "f x < f y"
  then show "inv f (f x) < inv f (f y)"
    using assms strict_mono_imp_inj_on strict_mono_less by fastforce
qed

lemma mono_bij_Inf:
  fixes f :: "'a::complete_linorder \<Rightarrow> 'b::complete_linorder"
  assumes "mono f" "bij f"
  shows "f (Inf A) = Inf (f`A)"
proof -
  have "surj f" using \<open>bij f\<close> by (auto simp: bij_betw_def)
  have *: "(inv f) (Inf (f`A)) \<le> Inf ((inv f)`(f`A))"
    using mono_Inf[OF mono_inv[OF assms], of "f`A"] by simp
  have "Inf (f`A) \<le> f (Inf ((inv f)`(f`A)))"
    using monoD[OF \<open>mono f\<close> *] by(simp add: surj_f_inv_f[OF \<open>surj f\<close>])
  also have "... = f(Inf A)"
    using assms by (simp add: bij_is_inj)
  finally show ?thesis using mono_Inf[OF assms(1), of A] by auto
qed

lemma finite_fun_UNIVD1:
  assumes fin: "finite (UNIV :: ('a \<Rightarrow> 'b) set)"
    and card: "card (UNIV :: 'b set) \<noteq> Suc 0"
  shows "finite (UNIV :: 'a set)"
proof -
  let ?UNIV_b = "UNIV :: 'b set"
  from fin have "finite ?UNIV_b"
    by (rule finite_fun_UNIVD2)
  with card have "card ?UNIV_b \<ge> Suc (Suc 0)"
    by (cases "card ?UNIV_b") (auto simp: card_eq_0_iff)
  then have "card ?UNIV_b = Suc (Suc (card ?UNIV_b - Suc (Suc 0)))"
    by simp
  then obtain b1 b2 :: 'b where b1b2: "b1 \<noteq> b2"
    by (auto simp: card_Suc_eq)
  from fin have fin': "finite (range (\<lambda>f :: 'a \<Rightarrow> 'b. inv f b1))"
    by (rule finite_imageI)
  have "UNIV = range (\<lambda>f :: 'a \<Rightarrow> 'b. inv f b1)"
  proof (rule UNIV_eq_I)
    fix x :: 'a
    from b1b2 have "x = inv (\<lambda>y. if y = x then b1 else b2) b1"
      by (simp add: inv_into_def)
    then show "x \<in> range (\<lambda>f::'a \<Rightarrow> 'b. inv f b1)"
      by blast
  qed
  with fin' show ?thesis
    by simp
qed

text \<open>
  Every infinite set contains a countable subset. More precisely we
  show that a set \<open>S\<close> is infinite if and only if there exists an
  injective function from the naturals into \<open>S\<close>.

  The ``only if'' direction is harder because it requires the
  construction of a sequence of pairwise different elements of an
  infinite set \<open>S\<close>. The idea is to construct a sequence of
  non-empty and infinite subsets of \<open>S\<close> obtained by successively
  removing elements of \<open>S\<close>.
\<close>

lemma infinite_countable_subset:
  assumes inf: "\<not> finite S"
  shows "\<exists>f::nat \<Rightarrow> 'a. inj f \<and> range f \<subseteq> S"
  \<comment> \<open>Courtesy of Stephan Merz\<close>
proof -
  define Sseq where "Sseq = rec_nat S (\<lambda>n T. T - {SOME e. e \<in> T})"
  define pick where "pick n = (SOME e. e \<in> Sseq n)" for n
  have *: "Sseq n \<subseteq> S" "\<not> finite (Sseq n)" for n
    by (induct n) (auto simp: Sseq_def inf)
  then have **: "\<And>n. pick n \<in> Sseq n"
    unfolding pick_def by (subst (asm) finite.simps) (auto simp add: ex_in_conv intro: someI_ex)
  with * have "range pick \<subseteq> S" by auto
  moreover have "pick n \<noteq> pick (n + Suc m)" for m n
  proof -
    have "pick n \<notin> Sseq (n + Suc m)"
      by (induct m) (auto simp add: Sseq_def pick_def)
    with ** show ?thesis by auto
  qed
  then have "inj pick"
    by (intro linorder_injI) (auto simp add: less_iff_Suc_add)
  ultimately show ?thesis by blast
qed

lemma infinite_iff_countable_subset: "\<not> finite S \<longleftrightarrow> (\<exists>f::nat \<Rightarrow> 'a. inj f \<and> range f \<subseteq> S)"
  \<comment> \<open>Courtesy of Stephan Merz\<close>
  using finite_imageD finite_subset infinite_UNIV_char_0 infinite_countable_subset by auto

lemma image_inv_into_cancel:
  assumes surj: "f`A = A'"
    and sub: "B' \<subseteq> A'"
  shows "f `((inv_into A f)`B') = B'"
  using assms
proof (auto simp: f_inv_into_f)
  let ?f' = "inv_into A f"
  fix a'
  assume *: "a' \<in> B'"
  with sub have "a' \<in> A'" by auto
  with surj have "a' = f (?f' a')"
    by (auto simp: f_inv_into_f)
  with * show "a' \<in> f ` (?f' ` B')" by blast
qed

lemma inv_into_inv_into_eq:
  assumes "bij_betw f A A'"
    and a: "a \<in> A"
  shows "inv_into A' (inv_into A f) a = f a"
proof -
  let ?f' = "inv_into A f"
  let ?f'' = "inv_into A' ?f'"
  from assms have *: "bij_betw ?f' A' A"
    by (auto simp: bij_betw_inv_into)
  with a obtain a' where a': "a' \<in> A'" "?f' a' = a"
    unfolding bij_betw_def by force
  with a * have "?f'' a = a'"
    by (auto simp: f_inv_into_f bij_betw_def)
  moreover from assms a' have "f a = a'"
    by (auto simp: bij_betw_def)
  ultimately show "?f'' a = f a" by simp
qed

lemma inj_on_iff_surj:
  assumes "A \<noteq> {}"
  shows "(\<exists>f. inj_on f A \<and> f ` A \<subseteq> A') \<longleftrightarrow> (\<exists>g. g ` A' = A)"
proof safe
  fix f
  assume inj: "inj_on f A" and incl: "f ` A \<subseteq> A'"
  let ?phi = "\<lambda>a' a. a \<in> A \<and> f a = a'"
  let ?csi = "\<lambda>a. a \<in> A"
  let ?g = "\<lambda>a'. if a' \<in> f ` A then (SOME a. ?phi a' a) else (SOME a. ?csi a)"
  have "?g ` A' = A"
  proof
    show "?g ` A' \<subseteq> A"
    proof clarify
      fix a'
      assume *: "a' \<in> A'"
      show "?g a' \<in> A"
      proof (cases "a' \<in> f ` A")
        case True
        then obtain a where "?phi a' a" by blast
        then have "?phi a' (SOME a. ?phi a' a)"
          using someI[of "?phi a'" a] by blast
        with True show ?thesis by auto
      next
        case False
        with assms have "?csi (SOME a. ?csi a)"
          using someI_ex[of ?csi] by blast
        with False show ?thesis by auto
      qed
    qed
  next
    show "A \<subseteq> ?g ` A'"
    proof -
      have "?g (f a) = a \<and> f a \<in> A'" if a: "a \<in> A" for a
      proof -
        let ?b = "SOME aa. ?phi (f a) aa"
        from a have "?phi (f a) a" by auto
        then have *: "?phi (f a) ?b"
          using someI[of "?phi(f a)" a] by blast
        then have "?g (f a) = ?b" using a by auto
        moreover from inj * a have "a = ?b"
          by (auto simp add: inj_on_def)
        ultimately have "?g(f a) = a" by simp
        with incl a show ?thesis by auto
      qed
      then show ?thesis by force
    qed
  qed
  then show "\<exists>g. g ` A' = A" by blast
next
  fix g
  let ?f = "inv_into A' g"
  have "inj_on ?f (g ` A')"
    by (auto simp: inj_on_inv_into)
  moreover have "?f (g a') \<in> A'" if a': "a' \<in> A'" for a'
  proof -
    let ?phi = "\<lambda> b'. b' \<in> A' \<and> g b' = g a'"
    from a' have "?phi a'" by auto
    then have "?phi (SOME b'. ?phi b')"
      using someI[of ?phi] by blast
    then show ?thesis by (auto simp: inv_into_def)
  qed
  ultimately show "\<exists>f. inj_on f (g ` A') \<and> f ` g ` A' \<subseteq> A'"
    by auto
qed

lemma Ex_inj_on_UNION_Sigma:
  "\<exists>f. (inj_on f (\<Union>i \<in> I. A i) \<and> f ` (\<Union>i \<in> I. A i) \<subseteq> (SIGMA i : I. A i))"
proof
  let ?phi = "\<lambda>a i. i \<in> I \<and> a \<in> A i"
  let ?sm = "\<lambda>a. SOME i. ?phi a i"
  let ?f = "\<lambda>a. (?sm a, a)"
  have "inj_on ?f (\<Union>i \<in> I. A i)"
    by (auto simp: inj_on_def)
  moreover
  have "?sm a \<in> I \<and> a \<in> A(?sm a)" if "i \<in> I" and "a \<in> A i" for i a
    using that someI[of "?phi a" i] by auto
  then have "?f ` (\<Union>i \<in> I. A i) \<subseteq> (SIGMA i : I. A i)"
    by auto
  ultimately show "inj_on ?f (\<Union>i \<in> I. A i) \<and> ?f ` (\<Union>i \<in> I. A i) \<subseteq> (SIGMA i : I. A i)"
    by auto
qed

lemma inv_unique_comp:
  assumes fg: "f \<circ> g = id"
    and gf: "g \<circ> f = id"
  shows "inv f = g"
  using fg gf inv_equality[of g f] by (auto simp add: fun_eq_iff)

lemma subset_image_inj:
  "S \<subseteq> f ` T \<longleftrightarrow> (\<exists>U. U \<subseteq> T \<and> inj_on f U \<and> S = f ` U)"
proof safe
  show "\<exists>U\<subseteq>T. inj_on f U \<and> S = f ` U"
    if "S \<subseteq> f ` T"
  proof -
    from that [unfolded subset_image_iff subset_iff]
    obtain g where g: "\<And>x. x \<in> S \<Longrightarrow> g x \<in> T \<and> x = f (g x)"
      by (auto simp add: image_iff Bex_def choice_iff')
    show ?thesis
    proof (intro exI conjI)
      show "g ` S \<subseteq> T"
        by (simp add: g image_subsetI)
      show "inj_on f (g ` S)"
        using g by (auto simp: inj_on_def)
      show "S = f ` (g ` S)"
        using g image_subset_iff by auto
    qed
  qed
qed blast

subsection \<open>Other Consequences of Hilbert's Epsilon\<close>

text \<open>Hilbert's Epsilon and the \<^term>\<open>split\<close> Operator\<close>

text \<open>Looping simprule!\<close>
lemma split_paired_Eps: "(SOME x. P x) = (SOME (a, b). P (a, b))"
  by simp

lemma Eps_case_prod: "Eps (case_prod P) = (SOME xy. P (fst xy) (snd xy))"
  by (simp add: split_def)

lemma Eps_case_prod_eq [simp]: "(SOME (x', y'). x = x' \<and> y = y') = (x, y)"
  by blast

text \<open>A relation is wellfounded iff it has no infinite descending chain.\<close>
lemma wf_iff_no_infinite_down_chain: "wf r \<longleftrightarrow> (\<nexists>f. \<forall>i. (f (Suc i), f i) \<in> r)"
  (is "_ \<longleftrightarrow> \<not> ?ex")
proof
  assume "wf r"
  show "\<not> ?ex"
  proof
    assume ?ex
    then obtain f where f: "(f (Suc i), f i) \<in> r" for i
      by blast
    from \<open>wf r\<close> have minimal: "x \<in> Q \<Longrightarrow> \<exists>z\<in>Q. \<forall>y. (y, z) \<in> r \<longrightarrow> y \<notin> Q" for x Q
      by (auto simp: wf_eq_minimal)
    let ?Q = "{w. \<exists>i. w = f i}"
    fix n
    have "f n \<in> ?Q" by blast
    from minimal [OF this] obtain j where "(y, f j) \<in> r \<Longrightarrow> y \<notin> ?Q" for y by blast
    with this [OF \<open>(f (Suc j), f j) \<in> r\<close>] have "f (Suc j) \<notin> ?Q" by simp
    then show False by blast
  qed
next
  assume "\<not> ?ex"
  then show "wf r"
  proof (rule contrapos_np)
    assume "\<not> wf r"
    then obtain Q x where x: "x \<in> Q" and rec: "z \<in> Q \<Longrightarrow> \<exists>y. (y, z) \<in> r \<and> y \<in> Q" for z
      by (auto simp add: wf_eq_minimal)
    obtain descend :: "nat \<Rightarrow> 'a"
      where descend_0: "descend 0 = x"
        and descend_Suc: "descend (Suc n) = (SOME y. y \<in> Q \<and> (y, descend n) \<in> r)" for n
      by (rule that [of "rec_nat x (\<lambda>_ rec. (SOME y. y \<in> Q \<and> (y, rec) \<in> r))"]) simp_all
    have descend_Q: "descend n \<in> Q" for n
    proof (induct n)
      case 0
      with x show ?case by (simp only: descend_0)
    next
      case Suc
      then show ?case by (simp only: descend_Suc) (rule someI2_ex; use rec in blast)
    qed
    have "(descend (Suc i), descend i) \<in> r" for i
      by (simp only: descend_Suc) (rule someI2_ex; use descend_Q rec in blast)
    then show "\<exists>f. \<forall>i. (f (Suc i), f i) \<in> r" by blast
  qed
qed

lemma wf_no_infinite_down_chainE:
  assumes "wf r"
  obtains k where "(f (Suc k), f k) \<notin> r"
  using assms wf_iff_no_infinite_down_chain[of r] by blast

text \<open>A dynamically-scoped fact for TFL\<close>
lemma tfl_some: "\<forall>P x. P x \<longrightarrow> P (Eps P)"
  by (blast intro: someI)

subsection \<open>An aside: bounded accessible part\<close>

text \<open>Finite monotone eventually stable sequences\<close>

lemma finite_mono_remains_stable_implies_strict_prefix:
  fixes f :: "nat \<Rightarrow> 'a::order"
  assumes S: "finite (range f)" "mono f"
    and eq: "\<forall>n. f n = f (Suc n) \<longrightarrow> f (Suc n) = f (Suc (Suc n))"
  shows "\<exists>N. (\<forall>n\<le>N. \<forall>m\<le>N. m < n \<longrightarrow> f m < f n) \<and> (\<forall>n\<ge>N. f N = f n)"
  using assms
proof -
  have "\<exists>n. f n = f (Suc n)"
  proof (rule ccontr)
    assume "\<not> ?thesis"
    then have "\<And>n. f n \<noteq> f (Suc n)" by auto
    with \<open>mono f\<close> have "\<And>n. f n < f (Suc n)"
      by (auto simp: le_less mono_iff_le_Suc)
    with lift_Suc_mono_less_iff[of f] have *: "\<And>n m. n < m \<Longrightarrow> f n < f m"
      by auto
    have "inj f"
    proof (intro injI)
      fix x y
      assume "f x = f y"
      then show "x = y"
        by (cases x y rule: linorder_cases) (auto dest: *)
    qed
    with \<open>finite (range f)\<close> have "finite (UNIV::nat set)"
      by (rule finite_imageD)
    then show False by simp
  qed
  then obtain n where n: "f n = f (Suc n)" ..
  define N where "N = (LEAST n. f n = f (Suc n))"
  have N: "f N = f (Suc N)"
    unfolding N_def using n by (rule LeastI)
  show ?thesis
  proof (intro exI[of _ N] conjI allI impI)
    fix n
    assume "N \<le> n"
    then have "\<And>m. N \<le> m \<Longrightarrow> m \<le> n \<Longrightarrow> f m = f N"
    proof (induct rule: dec_induct)
      case base
      then show ?case by simp
    next
      case (step n)
      then show ?case
        using eq [rule_format, of "n - 1"] N
        by (cases n) (auto simp add: le_Suc_eq)
    qed
    from this[of n] \<open>N \<le> n\<close> show "f N = f n" by auto
  next
    fix n m :: nat
    assume "m < n" "n \<le> N"
    then show "f m < f n"
    proof (induct rule: less_Suc_induct)
      case (1 i)
      then have "i < N" by simp
      then have "f i \<noteq> f (Suc i)"
        unfolding N_def by (rule not_less_Least)
      with \<open>mono f\<close> show ?case by (simp add: mono_iff_le_Suc less_le)
    next
      case 2
      then show ?case by simp
    qed
  qed
qed

lemma finite_mono_strict_prefix_implies_finite_fixpoint:
  fixes f :: "nat \<Rightarrow> 'a set"
  assumes S: "\<And>i. f i \<subseteq> S" "finite S"
    and ex: "\<exists>N. (\<forall>n\<le>N. \<forall>m\<le>N. m < n \<longrightarrow> f m \<subset> f n) \<and> (\<forall>n\<ge>N. f N = f n)"
  shows "f (card S) = (\<Union>n. f n)"
proof -
  from ex obtain N where inj: "\<And>n m. n \<le> N \<Longrightarrow> m \<le> N \<Longrightarrow> m < n \<Longrightarrow> f m \<subset> f n"
    and eq: "\<forall>n\<ge>N. f N = f n"
    by atomize auto
  have "i \<le> N \<Longrightarrow> i \<le> card (f i)" for i
  proof (induct i)
    case 0
    then show ?case by simp
  next
    case (Suc i)
    with inj [of "Suc i" i] have "(f i) \<subset> (f (Suc i))" by auto
    moreover have "finite (f (Suc i))" using S by (rule finite_subset)
    ultimately have "card (f i) < card (f (Suc i))" by (intro psubset_card_mono)
    with Suc inj show ?case by auto
  qed
  then have "N \<le> card (f N)" by simp
  also have "\<dots> \<le> card S" using S by (intro card_mono)
  finally have \<section>: "f (card S) = f N" using eq by auto
  moreover have "\<Union> (range f) \<subseteq> f N"
  proof clarify
    fix x n
    assume "x \<in> f n"
    with eq inj [of N] show "x \<in> f N"
      by (cases "n < N") (auto simp: not_less)
  qed
  ultimately show ?thesis
    by auto
qed

subsection \<open>More on injections, bijections, and inverses\<close>

locale bijection =
  fixes f :: "'a \<Rightarrow> 'a"
  assumes bij: "bij f"
begin

lemma bij_inv: "bij (inv f)"
  using bij by (rule bij_imp_bij_inv)

lemma surj [simp]: "surj f"
  using bij by (rule bij_is_surj)

lemma inj: "inj f"
  using bij by (rule bij_is_inj)

lemma surj_inv [simp]: "surj (inv f)"
  using inj by (rule inj_imp_surj_inv)

lemma inj_inv: "inj (inv f)"
  using surj by (rule surj_imp_inj_inv)

lemma eqI: "f a = f b \<Longrightarrow> a = b"
  using inj by (rule injD)

lemma eq_iff [simp]: "f a = f b \<longleftrightarrow> a = b"
  by (auto intro: eqI)

lemma eq_invI: "inv f a = inv f b \<Longrightarrow> a = b"
  using inj_inv by (rule injD)

lemma eq_inv_iff [simp]: "inv f a = inv f b \<longleftrightarrow> a = b"
  by (auto intro: eq_invI)

lemma inv_left [simp]: "inv f (f a) = a"
  using inj by (simp add: inv_f_eq)

lemma inv_comp_left [simp]: "inv f \<circ> f = id"
  by (simp add: fun_eq_iff)

lemma inv_right [simp]: "f (inv f a) = a"
  using surj by (simp add: surj_f_inv_f)

lemma inv_comp_right [simp]: "f \<circ> inv f = id"
  by (simp add: fun_eq_iff)

lemma inv_left_eq_iff [simp]: "inv f a = b \<longleftrightarrow> f b = a"
  by auto

lemma inv_right_eq_iff [simp]: "b = inv f a \<longleftrightarrow> f b = a"
  by auto

end

lemma infinite_imp_bij_betw:
  assumes infinite: "\<not> finite A"
  shows "\<exists>h. bij_betw h A (A - {a})"
proof (cases "a \<in> A")
  case False
  then have "A - {a} = A" by blast
  then show ?thesis
    using bij_betw_id[of A] by auto
next
  case True
  with infinite have "\<not> finite (A - {a})" by auto
  with infinite_iff_countable_subset[of "A - {a}"]
  obtain f :: "nat \<Rightarrow> 'a" where "inj f" and f: "f ` UNIV \<subseteq> A - {a}" by blast
  define g where "g n = (if n = 0 then a else f (Suc n))" for n
  define A' where "A' = g ` UNIV"
  have *: "\<forall>y. f y \<noteq> a" using f by blast
  have 3: "inj_on g UNIV \<and> g ` UNIV \<subseteq> A \<and> a \<in> g ` UNIV"
    using \<open>inj f\<close> f * unfolding inj_on_def g_def
    by (auto simp add: True image_subset_iff)
  then have 4: "bij_betw g UNIV A' \<and> a \<in> A' \<and> A' \<subseteq> A"
    using inj_on_imp_bij_betw[of g] by (auto simp: A'_def)
  then have 5: "bij_betw (inv g) A' UNIV"
    by (auto simp add: bij_betw_inv_into)
  from 3 obtain n where n: "g n = a" by auto
  have 6: "bij_betw g (UNIV - {n}) (A' - {a})"
    by (rule bij_betw_subset) (use 3 4 n in \<open>auto simp: image_set_diff A'_def\<close>)
  define v where "v m = (if m < n then m else Suc m)" for m
  have "m < n \<or> m = n" if "\<And>k. k < n \<or> m \<noteq> Suc k" for m
    using that [of "m-1"] by auto
  then have 7: "bij_betw v UNIV (UNIV - {n})"
    unfolding bij_betw_def inj_on_def v_def by auto
  define h' where "h' = g \<circ> v \<circ> (inv g)"
  with 5 6 7 have 8: "bij_betw h' A' (A' - {a})"
    by (auto simp add: bij_betw_trans)
  define h where "h b = (if b \<in> A' then h' b else b)" for b
  with 8 have "bij_betw h  A' (A' - {a})"
    using bij_betw_cong[of A' h] by auto
  moreover
  have "\<forall>b \<in> A - A'. h b = b" by (auto simp: h_def)
  then have "bij_betw h  (A - A') (A - A')"
    using bij_betw_cong[of "A - A'" h id] bij_betw_id[of "A - A'"] by auto
  moreover
  from 4 have "(A' \<inter> (A - A') = {} \<and> A' \<union> (A - A') = A) \<and>
    ((A' - {a}) \<inter> (A - A') = {} \<and> (A' - {a}) \<union> (A - A') = A - {a})"
    by blast
  ultimately have "bij_betw h A (A - {a})"
    using bij_betw_combine[of h A' "A' - {a}" "A - A'" "A - A'"] by simp
  then show ?thesis by blast
qed

lemma infinite_imp_bij_betw2:
  assumes "\<not> finite A"
  shows "\<exists>h. bij_betw h A (A \<union> {a})"
proof (cases "a \<in> A")
  case True
  then have "A \<union> {a} = A" by blast
  then show ?thesis using bij_betw_id[of A] by auto
next
  case False
  let ?A' = "A \<union> {a}"
  from False have "A = ?A' - {a}" by blast
  moreover from assms have "\<not> finite ?A'" by auto
  ultimately obtain f where "bij_betw f ?A' A"
    using infinite_imp_bij_betw[of ?A' a] by auto
  then have "bij_betw (inv_into ?A' f) A ?A'" by (rule bij_betw_inv_into)
  then show ?thesis by auto
qed

lemma bij_betw_inv_into_left: "bij_betw f A A' \<Longrightarrow> a \<in> A \<Longrightarrow> inv_into A f (f a) = a"
  unfolding bij_betw_def by clarify (rule inv_into_f_f)

lemma bij_betw_inv_into_right: "bij_betw f A A' \<Longrightarrow> a' \<in> A' \<Longrightarrow> f (inv_into A f a') = a'"
  unfolding bij_betw_def using f_inv_into_f by force

lemma bij_betw_inv_into_subset:
  "bij_betw f A A' \<Longrightarrow> B \<subseteq> A \<Longrightarrow> f ` B = B' \<Longrightarrow> bij_betw (inv_into A f) B' B"
  by (auto simp: bij_betw_def intro: inj_on_inv_into)

subsection \<open>Specification package -- Hilbertized version\<close>

lemma exE_some: "Ex P \<Longrightarrow> c \<equiv> Eps P \<Longrightarrow> P c"
  by (simp only: someI_ex)

ML_file \<open>Tools/choice_specification.ML\<close>

subsection \<open>Complete Distributive Lattices -- Properties depending on Hilbert Choice\<close>

context complete_distrib_lattice
begin

lemma Sup_Inf: "\<Squnion> (Inf ` A) = \<Sqinter> (Sup ` {f ` A |f. \<forall>B\<in>A. f B \<in> B})"
proof (rule order.antisym)
  show "\<Squnion> (Inf ` A) \<le> \<Sqinter> (Sup ` {f ` A |f. \<forall>B\<in>A. f B \<in> B})"
    using Inf_lower2 Sup_upper
    by (fastforce simp add: intro: Sup_least INF_greatest)
next
  show "\<Sqinter> (Sup ` {f ` A |f. \<forall>B\<in>A. f B \<in> B}) \<le> \<Squnion> (Inf ` A)"
  proof (simp add:  Inf_Sup, rule SUP_least, simp, safe)
    fix f
    assume "\<forall>Y. (\<exists>f. Y = f ` A \<and> (\<forall>Y\<in>A. f Y \<in> Y)) \<longrightarrow> f Y \<in> Y"
    then have B: "\<And> F . (\<forall> Y \<in> A . F Y \<in> Y) \<Longrightarrow> \<exists> Z \<in> A . f (F ` A) = F Z"
      by auto
    show "\<Sqinter>(f ` {f ` A |f. \<forall>Y\<in>A. f Y \<in> Y}) \<le> \<Squnion>(Inf ` A)"
    proof (cases "\<exists> Z \<in> A . \<Sqinter>(f ` {f ` A |f. \<forall>Y\<in>A. f Y \<in> Y}) \<le> Inf Z")
      case True
      from this obtain Z where [simp]: "Z \<in> A" and A: "\<Sqinter>(f ` {f ` A |f. \<forall>Y\<in>A. f Y \<in> Y}) \<le> Inf Z"
        by blast
      have B: "... \<le> \<Squnion>(Inf ` A)"
        by (simp add: SUP_upper)
      from A and B show ?thesis
        by simp
    next
      case False
      then have X: "\<And> Z . Z \<in> A \<Longrightarrow> \<exists> x . x \<in> Z \<and> \<not> \<Sqinter>(f ` {f ` A |f. \<forall>Y\<in>A. f Y \<in> Y}) \<le> x"
        using Inf_greatest by blast
      define F where "F = (\<lambda> Z . SOME x . x \<in> Z \<and> \<not> \<Sqinter>(f ` {f ` A |f. \<forall>Y\<in>A. f Y \<in> Y}) \<le> x)"
      have C: "\<And>Y. Y \<in> A \<Longrightarrow> F Y \<in> Y"
        using X by (simp add: F_def, rule someI2_ex, auto)
      have E: "\<And>Y. Y \<in> A \<Longrightarrow> \<not> \<Sqinter>(f ` {f ` A |f. \<forall>Y\<in>A. f Y \<in> Y}) \<le> F Y"
        using X by (simp add: F_def, rule someI2_ex, auto)
      from C and B obtain  Z where D: "Z \<in> A " and Y: "f (F ` A) = F Z"
        by blast
      from E and D have W: "\<not> \<Sqinter>(f ` {f ` A |f. \<forall>Y\<in>A. f Y \<in> Y}) \<le> F Z"
        by simp
      have "\<Sqinter>(f ` {f ` A |f. \<forall>Y\<in>A. f Y \<in> Y}) \<le> f (F ` A)"
        using C by (blast intro: INF_lower)
      with W Y show ?thesis
        by simp
    qed
  qed
qed

lemma dual_complete_distrib_lattice:
  "class.complete_distrib_lattice Sup Inf sup (\<ge>) (>) inf \<top> \<bottom>"
  by (simp add: class.complete_distrib_lattice.intro [OF dual_complete_lattice]
                class.complete_distrib_lattice_axioms_def Sup_Inf)

lemma sup_Inf: "a \<squnion> \<Sqinter>B = \<Sqinter>((\<squnion>) a ` B)"
proof (rule order.antisym)
  show "a \<squnion> \<Sqinter>B \<le> \<Sqinter>((\<squnion>) a ` B)"
    using Inf_lower sup.mono by (fastforce intro: INF_greatest)
next
  have "\<Sqinter>((\<squnion>) a ` B) \<le> \<Sqinter>(Sup ` {{f {a}, f B} |f. f {a} = a \<and> f B \<in> B})"
    by (rule INF_greatest, auto simp add: INF_lower)
  also have "... = \<Squnion>(Inf ` {{a}, B})"
    by (unfold Sup_Inf, simp)
  finally show "\<Sqinter>((\<squnion>) a ` B) \<le> a \<squnion> \<Sqinter>B"
    by simp
qed

lemma inf_Sup: "a \<sqinter> \<Squnion>B = \<Squnion>((\<sqinter>) a ` B)"
  using dual_complete_distrib_lattice
  by (rule complete_distrib_lattice.sup_Inf)

lemma INF_SUP: "(\<Sqinter>y. \<Squnion>x. P x y) = (\<Squnion>f. \<Sqinter>x. P (f x) x)"
proof (rule order.antisym)
  show "(SUP x. INF y. P (x y) y) \<le> (INF y. SUP x. P x y)"
    by (rule SUP_least, rule INF_greatest, rule SUP_upper2, simp_all, rule INF_lower2, simp, blast)
next
  have "(INF y. SUP x. ((P x y))) \<le> Inf (Sup ` {{P x y | x . True} | y . True })" (is "?A \<le> ?B")
  proof (rule INF_greatest, clarsimp)
    fix y
    have "?A \<le> (SUP x. P x y)"
      by (rule INF_lower, simp)
    also have "... \<le> Sup {uu. \<exists>x. uu = P x y}"
      by (simp add: full_SetCompr_eq)
    finally show "?A \<le> Sup {uu. \<exists>x. uu = P x y}"
      by simp
  qed
  also have "... \<le>  (SUP x. INF y. P (x y) y)"
  proof (subst Inf_Sup, rule SUP_least, clarsimp)
    fix f
    assume A: "\<forall>Y. (\<exists>y. Y = {uu. \<exists>x. uu = P x y}) \<longrightarrow> f Y \<in> Y"

    have " \<Sqinter>(f ` {uu. \<exists>y. uu = {uu. \<exists>x. uu = P x y}}) \<le>
      (\<Sqinter>y. P (SOME x. f {P x y |x. True} = P x y) y)"
    proof (rule INF_greatest, clarsimp)
      fix y
        have "(INF x\<in>{uu. \<exists>y. uu = {uu. \<exists>x. uu = P x y}}. f x) \<le> f {uu. \<exists>x. uu = P x y}"
          by (rule INF_lower, blast)
        also have "... \<le> P (SOME x. f {uu . \<exists>x. uu = P x y} = P x y) y"
          by (rule someI2_ex) (use A in auto)
        finally show "\<Sqinter>(f ` {uu. \<exists>y. uu = {uu. \<exists>x. uu = P x y}}) \<le>
          P (SOME x. f {uu. \<exists>x. uu = P x y} = P x y) y"
          by simp
      qed
      also have "... \<le> (SUP x. INF y. P (x y) y)"
        by (rule SUP_upper, simp)
      finally show "\<Sqinter>(f ` {uu. \<exists>y. uu = {uu. \<exists>x. uu = P x y}}) \<le> (\<Squnion>x. \<Sqinter>y. P (x y) y)"
        by simp
    qed
  finally show "(INF y. SUP x. P x y) \<le> (SUP x. INF y. P (x y) y)"
    by simp
qed

lemma INF_SUP_set: "(\<Sqinter>B\<in>A. \<Squnion>(g ` B)) = (\<Squnion>B\<in>{f ` A |f. \<forall>C\<in>A. f C \<in> C}. \<Sqinter>(g ` B))"
                    (is "_ = (\<Squnion>B\<in>?F. _)")
proof (rule order.antisym)
  have "\<Sqinter> ((g \<circ> f) ` A) \<le> \<Squnion> (g ` B)" if "\<And>B. B \<in> A \<Longrightarrow> f B \<in> B" "B \<in> A" for f B
    using that by (auto intro: SUP_upper2 INF_lower2)
  then show "(\<Squnion>x\<in>?F. \<Sqinter>a\<in>x. g a) \<le> (\<Sqinter>x\<in>A. \<Squnion>a\<in>x. g a)"
    by (auto intro!: SUP_least INF_greatest simp add: image_comp)
next
  show "(\<Sqinter>x\<in>A. \<Squnion>a\<in>x. g a) \<le> (\<Squnion>x\<in>?F. \<Sqinter>a\<in>x. g a)"
  proof (cases "{} \<in> A")
    case True
    then show ?thesis
      by (rule INF_lower2) simp_all
  next
    case False
    {fix x
      have "(\<Sqinter>x\<in>A. \<Squnion>x\<in>x. g x) \<le> (\<Squnion>u. if x \<in> A then if u \<in> x then g u else \<bottom> else \<top>)"
      proof (cases "x \<in> A")
        case True
        then show ?thesis
          by (intro INF_lower2 SUP_least SUP_upper2) auto
      qed auto
    }
    then have "(\<Sqinter>Y\<in>A. \<Squnion>a\<in>Y. g a) \<le> (\<Sqinter>Y. \<Squnion>y. if Y \<in> A then if y \<in> Y then g y else \<bottom> else \<top>)"
      by (rule INF_greatest)
    also have "... = (\<Squnion>x. \<Sqinter>Y. if Y \<in> A then if x Y \<in> Y then g (x Y) else \<bottom> else \<top>)"
      by (simp only: INF_SUP)
    also have "... \<le> (\<Squnion>x\<in>?F. \<Sqinter>a\<in>x. g a)"
    proof (rule SUP_least)
      show "(\<Sqinter>B. if B \<in> A then if x B \<in> B then g (x B) else \<bottom> else \<top>)
               \<le> (\<Squnion>x\<in>?F. \<Sqinter>x\<in>x. g x)" for x
      proof -
        define G where "G \<equiv> \<lambda>Y. if x Y \<in> Y then x Y else (SOME x. x \<in>Y)"
        have "\<forall>Y\<in>A. G Y \<in> Y"
          using False some_in_eq G_def by auto
        then have A: "G ` A \<in> ?F"
          by blast
        show "(\<Sqinter>Y. if Y \<in> A then if x Y \<in> Y then g (x Y) else \<bottom> else \<top>) \<le> (\<Squnion>x\<in>?F. \<Sqinter>x\<in>x. g x)"
          by (fastforce simp: G_def intro: SUP_upper2 [OF A] INF_greatest INF_lower2)
      qed
    qed
    finally show ?thesis by simp
  qed
qed

lemma SUP_INF: "(\<Squnion>y. \<Sqinter>x. P x y) = (\<Sqinter>x. \<Squnion>y. P (x y) y)"
  using dual_complete_distrib_lattice
  by (rule complete_distrib_lattice.INF_SUP)

lemma SUP_INF_set: "(\<Squnion>x\<in>A. \<Sqinter> (g ` x)) = (\<Sqinter>x\<in>{f ` A |f. \<forall>Y\<in>A. f Y \<in> Y}. \<Squnion> (g ` x))"
  using dual_complete_distrib_lattice
  by (rule complete_distrib_lattice.INF_SUP_set)

end

(*properties of the former complete_distrib_lattice*)
context complete_distrib_lattice
begin

lemma sup_INF: "a \<squnion> (\<Sqinter>b\<in>B. f b) = (\<Sqinter>b\<in>B. a \<squnion> f b)"
  by (simp add: sup_Inf image_comp)

lemma inf_SUP: "a \<sqinter> (\<Squnion>b\<in>B. f b) = (\<Squnion>b\<in>B. a \<sqinter> f b)"
  by (simp add: inf_Sup image_comp)

lemma Inf_sup: "\<Sqinter>B \<squnion> a = (\<Sqinter>b\<in>B. b \<squnion> a)"
  by (simp add: sup_Inf sup_commute)

lemma Sup_inf: "\<Squnion>B \<sqinter> a = (\<Squnion>b\<in>B. b \<sqinter> a)"
  by (simp add: inf_Sup inf_commute)

lemma INF_sup: "(\<Sqinter>b\<in>B. f b) \<squnion> a = (\<Sqinter>b\<in>B. f b \<squnion> a)"
  by (simp add: sup_INF sup_commute)

lemma SUP_inf: "(\<Squnion>b\<in>B. f b) \<sqinter> a = (\<Squnion>b\<in>B. f b \<sqinter> a)"
  by (simp add: inf_SUP inf_commute)

lemma Inf_sup_eq_top_iff: "(\<Sqinter>B \<squnion> a = \<top>) \<longleftrightarrow> (\<forall>b\<in>B. b \<squnion> a = \<top>)"
  by (simp only: Inf_sup INF_top_conv)

lemma Sup_inf_eq_bot_iff: "(\<Squnion>B \<sqinter> a = \<bottom>) \<longleftrightarrow> (\<forall>b\<in>B. b \<sqinter> a = \<bottom>)"
  by (simp only: Sup_inf SUP_bot_conv)

lemma INF_sup_distrib2: "(\<Sqinter>a\<in>A. f a) \<squnion> (\<Sqinter>b\<in>B. g b) = (\<Sqinter>a\<in>A. \<Sqinter>b\<in>B. f a \<squnion> g b)"
  by (subst INF_commute) (simp add: sup_INF INF_sup)

lemma SUP_inf_distrib2: "(\<Squnion>a\<in>A. f a) \<sqinter> (\<Squnion>b\<in>B. g b) = (\<Squnion>a\<in>A. \<Squnion>b\<in>B. f a \<sqinter> g b)"
  by (subst SUP_commute) (simp add: inf_SUP SUP_inf)

end

instantiation set :: (type) complete_distrib_lattice
begin
instance proof (standard, clarsimp)
  fix A :: "(('a set) set) set"
  fix x::'a
  assume A: "\<forall>\<S>\<in>A. \<exists>X\<in>\<S>. x \<in> X"
  define F where "F \<equiv> \<lambda>Y. SOME X. Y \<in> A \<and> X \<in> Y \<and> x \<in> X"
  have "(\<forall>S \<in> F ` A. x \<in> S)"
    using A unfolding F_def by (fastforce intro: someI2_ex)
  moreover have "\<forall>Y\<in>A. F Y \<in> Y"
    using A unfolding F_def by (fastforce intro: someI2_ex)
  then have "\<exists>f. F ` A  = f ` A \<and> (\<forall>Y\<in>A. f Y \<in> Y)"
    by blast
  ultimately show "\<exists>X. (\<exists>f. X = f ` A \<and> (\<forall>Y\<in>A. f Y \<in> Y)) \<and> (\<forall>S\<in>X. x \<in> S)"
    by auto
qed
end

instance set :: (type) complete_boolean_algebra ..

instantiation "fun" :: (type, complete_distrib_lattice) complete_distrib_lattice
begin
instance by standard (simp add: le_fun_def INF_SUP_set image_comp)
end

instance "fun" :: (type, complete_boolean_algebra) complete_boolean_algebra ..

context complete_linorder
begin

subclass complete_distrib_lattice
proof (standard, rule ccontr)
  fix A :: "'a set set"
  let ?F = "{f ` A |f. \<forall>Y\<in>A. f Y \<in> Y}"
  assume "\<not> \<Sqinter>(Sup ` A) \<le> \<Squnion>(Inf ` ?F)"
  then have C: "\<Sqinter>(Sup ` A) > \<Squnion>(Inf ` ?F)"
    by (simp add: not_le)
  show False
  proof (cases "\<exists> z . \<Sqinter>(Sup ` A) > z \<and> z > \<Squnion>(Inf ` ?F)")
    case True
    then obtain z where A: "z < \<Sqinter>(Sup ` A)" and X: "z > \<Squnion>(Inf ` ?F)"
      by blast
    then have B: "\<And>Y. Y \<in> A \<Longrightarrow> \<exists>k \<in>Y . z < k"
      using local.less_Sup_iff by(force dest: less_INF_D)

    define G where "G \<equiv> \<lambda>Y. SOME k . k \<in> Y \<and> z < k"
    have E: "\<And>Y. Y \<in> A \<Longrightarrow> G Y \<in> Y"
      using B unfolding G_def by (fastforce intro: someI2_ex)
    have "z \<le> Inf (G ` A)"
    proof (rule INF_greatest)
      show  "\<And>Y. Y \<in> A \<Longrightarrow> z \<le> G Y"
        using B unfolding G_def by (fastforce intro: someI2_ex)
    qed
    also have "... \<le> \<Squnion>(Inf ` ?F)"
      by (rule SUP_upper) (use E in blast)
    finally have "z \<le> \<Squnion>(Inf ` ?F)"
      by simp

    with X show ?thesis
      using local.not_less by blast
  next
    case False
    have B: "\<And>Y. Y \<in> A \<Longrightarrow> \<exists> k \<in>Y . \<Squnion>(Inf ` ?F) < k"
      using C local.less_Sup_iff by(force dest: less_INF_D)
    define G where "G \<equiv> \<lambda> Y . SOME k . k \<in> Y \<and> \<Squnion>(Inf ` ?F) < k"
    have E: "\<And>Y. Y \<in> A \<Longrightarrow> G Y \<in> Y"
      using B unfolding G_def by (fastforce intro: someI2_ex)
    have "\<And>Y. Y \<in> A \<Longrightarrow> \<Sqinter>(Sup ` A) \<le> G Y"
      using B False local.leI unfolding G_def by (fastforce intro: someI2_ex)
    then have "\<Sqinter>(Sup ` A) \<le> Inf (G ` A)"
      by (simp add: local.INF_greatest)
    also have "Inf (G ` A) \<le> \<Squnion>(Inf ` ?F)"
      by (rule SUP_upper) (use E in blast)
    finally have "\<Sqinter>(Sup ` A) \<le> \<Squnion>(Inf ` ?F)"
      by simp
    with C show ?thesis
      using not_less by blast
  qed
qed
end

end


theory T164
imports Main
begin
lemma "(
(\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) &
(\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) &
(\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) &
(\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(meet(x, y), z) = meet(mult(x, z), mult(y, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(x, join(y, z)) = join(undr(x, y), undr(x, z))) &
(\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) &
(\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) &
(\<forall> x::nat. invo(invo(x)) = x)
) \<longrightarrow>
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(meet(x, y), z) = join(undr(x, z), undr(y, z)))
"
nitpick[card nat=7,timeout=86400]
oops
end


theory T111
imports Main
begin
lemma "(
(\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) &
(\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) &
(\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) &
(\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, meet(y, z)) = meet(mult(x, y), mult(x, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(x, join(y, z)) = join(undr(x, y), undr(x, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(x, meet(y, z)) = join(over(x, y), over(x, z))) &
(\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) &
(\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) &
(\<forall> x::nat. invo(invo(x)) = x)
) \<longrightarrow>
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(join(x, y), z) = join(over(x, z), over(y, z)))
"
nitpick[card nat=7,timeout=86400]
oops
end


theory GabrielaLimonta
imports "~~/src/HOL/IMP/Star" Complex_Main
begin

(** Score: 2/5
  spec error in taval. apreservation not shown.

*)

text {* We build on @{theory Complex_Main} instead of @{theory Main} to access
the real numbers. *}

subsection "Arithmetic Expressions"

type_synonym val = real

type_synonym vname = string
type_synonym state = "vname \<Rightarrow> val"

text_raw{*\snip{aexptDef}{0}{2}{% *}
datatype aexp = Rc real | V vname | Plus aexp aexp | Div aexp aexp
text_raw{*}%endsnip*}

inductive taval :: "aexp \<Rightarrow> state \<Rightarrow> val \<Rightarrow> bool" where
"taval (Rc r) s r" |
"taval (V x) s (s x)" |
"taval a1 s r1 \<Longrightarrow> taval a2 s r2
  \<Longrightarrow> taval (Plus a1 a2) s (r1+r2)" |
"taval a1 s r1 \<Longrightarrow> taval a2 s r2        (** No, should get stuck on div by zero!*)
  \<Longrightarrow> taval (Div a1 a2) s (r1 / r2)"

inductive_cases [elim!]:
  "taval (Rc i) s v"
  "taval (V x) s v"
  "taval (Plus a1 a2) s v"
  "taval (Div a1 a2) s v"

subsection "Boolean Expressions"

datatype bexp = Bc bool | Not bexp | And bexp bexp | Less aexp aexp

inductive tbval :: "bexp \<Rightarrow> state \<Rightarrow> bool \<Rightarrow> bool" where
"tbval (Bc v) s v" |
"tbval b s bv \<Longrightarrow> tbval (Not b) s (\<not> bv)" |
"tbval b1 s bv1 \<Longrightarrow> tbval b2 s bv2 \<Longrightarrow> tbval (And b1 b2) s (bv1 & bv2)" |
"taval a1 s r1 \<Longrightarrow> taval a2 s r2 \<Longrightarrow> tbval (Less a1 a2) s (r1 < r2)"

subsection "Syntax of Commands"
(* a copy of Com.thy - keep in sync! *)

datatype
  com = SKIP
      | Assign vname aexp       ("_ ::= _" [1000, 61] 61)
      | Seq    com  com         ("_;; _"  [60, 61] 60)
      | If     bexp com com     ("IF _ THEN _ ELSE _"  [0, 0, 61] 61)
      | While  bexp com         ("WHILE _ DO _"  [0, 61] 61)

subsection "Small-Step Semantics of Commands"

inductive
  small_step :: "(com \<times> state) \<Rightarrow> (com \<times> state) \<Rightarrow> bool" (infix "\<rightarrow>" 55)
where
Assign:  "taval a s v \<Longrightarrow> (x ::= a, s) \<rightarrow> (SKIP, s(x := v))" |

Seq1:   "(SKIP;;c,s) \<rightarrow> (c,s)" |
Seq2:   "(c1,s) \<rightarrow> (c1',s') \<Longrightarrow> (c1;;c2,s) \<rightarrow> (c1';;c2,s')" |

IfTrue:  "tbval b s True \<Longrightarrow> (IF b THEN c1 ELSE c2,s) \<rightarrow> (c1,s)" |
IfFalse: "tbval b s False \<Longrightarrow> (IF b THEN c1 ELSE c2,s) \<rightarrow> (c2,s)" |

While:   "(WHILE b DO c,s) \<rightarrow> (IF b THEN c;; WHILE b DO c ELSE SKIP,s)"

lemmas small_step_induct = small_step.induct[split_format(complete)]

subsection "The Type System"

datatype ty = Neg | Pos | Zero | Any

definition ty_of_c :: "real \<Rightarrow> ty" where
  "ty_of_c r = (if r = 0 then Zero else (if r > 0 then Pos else Neg))"

fun ty_of_plus :: "ty \<Rightarrow> ty \<Rightarrow> ty" where
  "ty_of_plus Neg Neg = Neg" |
  "ty_of_plus Pos Pos = Pos" |
  "ty_of_plus Neg Pos = Any" |
  "ty_of_plus Pos Neg = Any" |
  "ty_of_plus Any _ = Any" |
  "ty_of_plus _ Any = Any" |
  "ty_of_plus Zero a = a" |
  "ty_of_plus a Zero = a"

fun ty_of_div :: "ty \<Rightarrow> ty \<Rightarrow> ty option" where
  "ty_of_div Neg Neg = Some Pos" |
  "ty_of_div Pos Pos = Some Pos" |
  "ty_of_div Neg Pos = Some Neg" |
  "ty_of_div Pos Neg = Some Neg" |
  "ty_of_div a Zero = None" |
  "ty_of_div Zero a = Some Zero" |
  "ty_of_div Any Pos = Some Any" |
  "ty_of_div Any Neg = Some Any" |
  "ty_of_div _ Any = None"

type_synonym tyenv = "vname \<Rightarrow> ty"

inductive atyping :: "tyenv \<Rightarrow> aexp \<Rightarrow> ty \<Rightarrow> bool"
  ("(1_/ \<turnstile>/ (_ :/ _))" [50,0,50] 50)
where
Rc_ty: "\<Gamma> \<turnstile> Rc r : ty_of_c r" |
V_ty: "\<Gamma> \<turnstile> V x : \<Gamma> x" |
Plus_ty: "\<Gamma> \<turnstile> a1 : \<tau>1 \<Longrightarrow> \<Gamma> \<turnstile> a2 : \<tau>2 \<Longrightarrow>  \<Gamma> \<turnstile> Plus a1 a2 : ty_of_plus \<tau>1 \<tau>2" |
Div_ty: "\<Gamma> \<turnstile> a1 : \<tau>1 \<Longrightarrow> \<Gamma> \<turnstile> a2 : \<tau>2 \<Longrightarrow> ty_of_div \<tau>1 \<tau>2 = Some \<tau> \<Longrightarrow> \<Gamma> \<turnstile> Div a1 a2 : \<tau>"

fun values_of_type :: "ty \<Rightarrow> real set" where
  "values_of_type Neg = {x. x<0}" |
  "values_of_type Pos = {x. x>0}" |
  "values_of_type Zero = {0}" |
  "values_of_type Any = {x. x<0 \<or> x\<ge>0}"  (** The universal set is UNIV *)

lemma "({x. x<0 \<or> x\<ge>0}::real set) = UNIV" by auto (** Much more concise to write ;) *)

declare atyping.intros [intro!]
inductive_cases [elim!]:
  "\<Gamma> \<turnstile> V x : \<tau>" "\<Gamma> \<turnstile> Rc r : \<tau>" "\<Gamma> \<turnstile> Plus a1 a2 : \<tau>" "\<Gamma> \<turnstile> Div a1 a2 : \<tau>"

text{* Warning: the ``:'' notation leads to syntactic ambiguities,
i.e. multiple parse trees, because ``:'' also stands for set membership.
In most situations Isabelle's type system will reject all but one parse tree,
but will still inform you of the potential ambiguity. *}

inductive btyping :: "tyenv \<Rightarrow> bexp \<Rightarrow> bool" (infix "\<turnstile>" 50)
where
B_ty: "\<Gamma> \<turnstile> Bc v" |
Not_ty: "\<Gamma> \<turnstile> b \<Longrightarrow> \<Gamma> \<turnstile> Not b" |
And_ty: "\<Gamma> \<turnstile> b1 \<Longrightarrow> \<Gamma> \<turnstile> b2 \<Longrightarrow> \<Gamma> \<turnstile> And b1 b2" |
Less_ty: "\<Gamma> \<turnstile> a1 : \<tau> \<Longrightarrow> \<Gamma> \<turnstile> a2 : \<tau> \<Longrightarrow> \<Gamma> \<turnstile> Less a1 a2"

declare btyping.intros [intro!]
inductive_cases [elim!]: "\<Gamma> \<turnstile> Not b" "\<Gamma> \<turnstile> And b1 b2" "\<Gamma> \<turnstile> Less a1 a2"

inductive ctyping :: "tyenv \<Rightarrow> com \<Rightarrow> bool" (infix "\<turnstile>" 50) where
Skip_ty: "\<Gamma> \<turnstile> SKIP" |
Assign_ty: "\<Gamma> \<turnstile> a : \<Gamma>(x) \<Longrightarrow> \<Gamma> \<turnstile> x ::= a" |
Seq_ty: "\<Gamma> \<turnstile> c1 \<Longrightarrow> \<Gamma> \<turnstile> c2 \<Longrightarrow> \<Gamma> \<turnstile> c1;;c2" |
If_ty: "\<Gamma> \<turnstile> b \<Longrightarrow> \<Gamma> \<turnstile> c1 \<Longrightarrow> \<Gamma> \<turnstile> c2 \<Longrightarrow> \<Gamma> \<turnstile> IF b THEN c1 ELSE c2" |
While_ty: "\<Gamma> \<turnstile> b \<Longrightarrow> \<Gamma> \<turnstile> c \<Longrightarrow> \<Gamma> \<turnstile> WHILE b DO c"

declare ctyping.intros [intro!]
inductive_cases [elim!]:
  "\<Gamma> \<turnstile> x ::= a"  "\<Gamma> \<turnstile> c1;;c2"
  "\<Gamma> \<turnstile> IF b THEN c1 ELSE c2"
  "\<Gamma> \<turnstile> WHILE b DO c"

subsection "Well-typed Programs Do Not Get Stuck"
(*
fun type :: "val \<Rightarrow> ty" where
"type (Iv i) = Ity" |
"type (Rv r) = Rty"

lemma type_eq_Rty[simp]: "type v = Rty \<longleftrightarrow> (\<exists>r. v = Rv r)"
by (cases v) simp_all
*)

definition styping :: "tyenv \<Rightarrow> state \<Rightarrow> bool" (infix "\<turnstile>" 50)
where "\<Gamma> \<turnstile> s  \<longleftrightarrow>  (\<forall>x. s x \<in> values_of_type (\<Gamma> x))"

lemma apreservation:
  "\<Gamma> \<turnstile> a : \<tau> \<Longrightarrow> taval a s v \<Longrightarrow> \<Gamma> \<turnstile> s \<Longrightarrow> v \<in> (values_of_type \<tau>)"
proof (induction arbitrary: v rule: atyping.induct)
  print_cases
  case (Rc_ty \<Gamma> r)
    thus ?case using ty_of_c_def by fastforce
  next
  case (V_ty \<Gamma> x)
    thus ?case
    proof -
      have "s x = v" using V_ty.prems(1) by force
      thus "v \<in> values_of_type   (\<Gamma> x)" using V_ty.prems(2) styping_def by blast
    qed
  next
  case (Plus_ty \<Gamma> a1 \<tau>1 a2 \<tau>2)
    thus ?case sorry
  next
  case (Div_ty \<Gamma> a1 \<tau>1 a2 \<tau>2 \<tau>)
    thus ?case using taval.intros(4)[of a1 s r1 a2 r2] sorry
qed

(*
apply(induction arbitrary: v rule: atyping.induct)
apply (fastforce simp: styping_def)+
done*)

lemma aprogress: "\<Gamma> \<turnstile> a : \<tau> \<Longrightarrow> \<Gamma> \<turnstile> s \<Longrightarrow> \<exists>v. taval a s v"
proof(induction rule: atyping.induct)
  print_cases
  case (Plus_ty \<Gamma> a1 \<tau>1 a2 \<tau>2)
  then obtain v1 v2 where v: "taval a1 s v1" "taval a2 s v2" by blast
  show ?case using Plus_ty taval.intros by blast
qed (auto intro: taval.intros)

lemma bprogress: "\<Gamma> \<turnstile> b \<Longrightarrow> \<Gamma> \<turnstile> s \<Longrightarrow> \<exists>v. tbval b s v"
proof(induction rule: btyping.induct)
print_cases
  case (Less_ty \<Gamma> a1 t a2)
  then obtain v1 v2 where v: "taval a1 s v1" "taval a2 s v2"
    by (metis aprogress)
  show ?case using tbval.intros v(1) v(2) by blast
qed (auto intro: tbval.intros)

theorem progress:
  "\<Gamma> \<turnstile> c \<Longrightarrow> \<Gamma> \<turnstile> s \<Longrightarrow> c \<noteq> SKIP \<Longrightarrow> \<exists>cs'. (c,s) \<rightarrow> cs'"
proof(induction rule: ctyping.induct)
  case Skip_ty thus ?case by simp
next
  case Assign_ty
  thus ?case by (metis Assign aprogress)
next
  case Seq_ty thus ?case by simp (metis Seq1 Seq2)
next
  case (If_ty \<Gamma> b c1 c2)
  then obtain bv where "tbval b s bv" by (metis bprogress)
  show ?case
  proof(cases bv)
    assume "bv"
    with `tbval b s bv` show ?case by simp (metis IfTrue)
  next
    assume "\<not>bv"
    with `tbval b s bv` show ?case by simp (metis IfFalse)
  qed
next
  case While_ty show ?case by (metis While)
qed

theorem styping_preservation:
  "(c,s) \<rightarrow> (c',s') \<Longrightarrow> \<Gamma> \<turnstile> c \<Longrightarrow> \<Gamma> \<turnstile> s \<Longrightarrow> \<Gamma> \<turnstile> s'"
proof(induction rule: small_step_induct)
  case Assign thus ?case
    by (auto simp: styping_def) (metis Assign(1,3) apreservation)
qed auto

theorem ctyping_preservation:
  "(c,s) \<rightarrow> (c',s') \<Longrightarrow> \<Gamma> \<turnstile> c \<Longrightarrow> \<Gamma> \<turnstile> c'"
by (induct rule: small_step_induct) (auto simp: ctyping.intros)

abbreviation small_steps :: "com * state \<Rightarrow> com * state \<Rightarrow> bool" (infix "\<rightarrow>*" 55)
where "x \<rightarrow>* y == star small_step x y"

theorem type_sound:
  "(c,s) \<rightarrow>* (c',s') \<Longrightarrow> \<Gamma> \<turnstile> c \<Longrightarrow> \<Gamma> \<turnstile> s \<Longrightarrow> c' \<noteq> SKIP
   \<Longrightarrow> \<exists>cs''. (c',s') \<rightarrow> cs''"
apply(induction rule:star_induct)
apply (metis progress)
by (metis styping_preservation ctyping_preservation)

end


theory T163
imports Main
begin
lemma "(
(\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) &
(\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) &
(\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) &
(\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, meet(y, z)) = meet(mult(x, y), mult(x, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(x, meet(y, z)) = join(over(x, y), over(x, z))) &
(\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) &
(\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) &
(\<forall> x::nat. invo(invo(x)) = x)
) \<longrightarrow>
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(meet(x, y), z) = join(undr(x, z), undr(y, z)))
"
nitpick[card nat=4,timeout=86400]
oops
end


theory T25
imports Main
begin
lemma "(
(\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) &
(\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) &
(\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) &
(\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(meet(x, y), z) = meet(mult(x, z), mult(y, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(x, join(y, z)) = join(undr(x, y), undr(x, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(join(x, y), z) = join(over(x, z), over(y, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(x, meet(y, z)) = join(over(x, y), over(x, z))) &
(\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) &
(\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) &
(\<forall> x::nat. invo(invo(x)) = x)
) \<longrightarrow>
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, meet(y, z)) = meet(mult(x, y), mult(x, z)))
"
nitpick[card nat=10,timeout=86400]
oops
end


section \<open>Abstract Prim Algorithm\<close>
theory Prim_Abstract
imports
  Main
  Common
  Undirected_Graph
  "HOL-Eisbach.Eisbach"
begin

subsection \<open>Generic Algorithm: Light Edges\label{sec:generic_mst}\<close>

definition "is_subset_MST w g A \<equiv> \<exists>t. is_MST w g t \<and> A \<subseteq> edges t"

lemma is_subset_MST_empty[simp]: "connected g \<Longrightarrow> is_subset_MST w g {}"
  using exists_MST unfolding is_subset_MST_def by blast

text \<open>We fix a start node and a weighted graph\<close>
locale Prim =
  fixes w :: "'v set \<Rightarrow> nat" and g :: "'v ugraph" and r :: 'v
begin

text \<open>Reachable part of the graph\<close>
definition "rg \<equiv> component_of g r"

lemma reachable_connected[simp, intro!]: "connected rg"
  unfolding rg_def by auto

lemma reachable_edges_subset: "edges rg \<subseteq> edges g"
  unfolding rg_def by (rule component_edges_subset)

definition "light_edge C u v
  \<equiv>   u\<in>C \<and> v\<notin>C \<and> (u,v)\<in>edges rg
    \<and> (\<forall>(u',v')\<in>edges rg \<inter> C\<times>-C. w {u,v} \<le> w {u',v'})"

definition "respects_cut A C \<equiv> A \<subseteq> C\<times>C \<union> (-C)\<times>(-C)"

lemma light_edge_is_safe:
  fixes A :: "('v\<times>'v) set" and C :: "'v set"
  assumes subset_MST: "is_subset_MST w rg A"
  assumes respects_cut: "respects_cut A C"
  assumes light_edge: "light_edge C u v"
  shows "is_subset_MST w rg ({(v,u)} \<union> A)"
proof -
  have crossing_edge: "u\<in>C" "v\<notin>C" "(u,v)\<in>edges rg"
    and min_edge: "\<forall>(u',v')\<in>edges rg \<inter> C\<times>-C. w {u,v} \<le> w {u',v'}"
    using light_edge unfolding light_edge_def by auto

  from subset_MST obtain T where T: "is_MST w rg T" "A \<subseteq> edges T"
    unfolding is_subset_MST_def by auto
  hence "tree T" "edges T \<subseteq> edges rg" "nodes T = nodes rg"
    by (simp_all add: is_MST_def is_spanning_tree_def)
  hence "connected T" by(simp_all add: tree_def)
  show ?thesis
  proof cases
    assume "(u,v) \<in> edges T"
    thus ?thesis unfolding is_subset_MST_def using T by (auto simp: edges_sym')
  next
    assume "(u,v) \<notin> edges T" hence "(v,u)\<notin>edges T" by (auto simp: edges_sym')
    from \<open>(u,v)\<in>edges rg\<close> obtain p where p: "path T u p v" "simple p"
      by (metis connectedD \<open>connected T\<close> \<open>nodes T = nodes rg\<close> nodesI
          rtrancl_edges_iff_path simplify_pathE)

    have [simp]: "u\<noteq>v" using crossing_edge by blast

    from find_crossing_edge_on_path[OF p(1), where P="\<lambda>x. x\<notin>C"]
         crossing_edge(1,2)
    obtain x y p1 p2 where xy: "(x,y) \<in> set p" "x \<in> C" "y \<notin> C"
      and ux: "path (restrict_edges T (-{(x,y),(y,x)})) u p1 x"
      and yv: "path (restrict_edges T (-{(x,y),(y,x)})) y p2 v"
      using path_change[OF crossing_edge(1,2) p] by blast
    have "(x,y) \<in> edges T"
      by (meson contra_subsetD p(1) path_edges xy(1))

    let ?E' = "edges T - {(x,y),(y,x)}"

    from split_tree[OF \<open>tree T\<close> \<open>(x,y)\<in>edges T\<close>]
      obtain T1 T2 where T12:
        "tree T1" "tree T2"
        and "nodes T1 \<inter> nodes T2 = {}"
        and "nodes T = nodes T1 \<union> nodes T2"
        and "edges T1 \<union> edges T2 = ?E'"
        and "nodes T1 = { u . (x,u)\<in>?E'\<^sup>*}"
        and "nodes T2 = { u . (y,u)\<in>?E'\<^sup>*}"
        and "x\<in>nodes T1" "y\<in>nodes T2" .

    let ?T' = "ins_edge (u,v) (graph_join T1 T2)"

    have "is_spanning_tree rg ?T'" proof -

      have E'_sym: "sym (?E'\<^sup>*)"
        by (meson edgesT_diff_sng_inv_eq sym_conv_converse_eq sym_rtrancl)

      have "u\<in>nodes T1"
        unfolding \<open>nodes T1 = _\<close>
        using path_rtrancl_edgesD[OF ux] by (auto dest: symD[OF E'_sym])

      have "v\<in>nodes T2"
        unfolding \<open>nodes T2 = _\<close>
        using path_rtrancl_edgesD[OF yv] by auto

      have "tree ?T'" by (rule join_trees) fact+

      show "is_spanning_tree rg ?T'"
        unfolding is_spanning_tree_def
        using \<open>nodes T = nodes rg\<close> \<open>nodes T = nodes T1 \<union> nodes T2\<close>[symmetric]
        using \<open>tree ?T'\<close> \<open>u\<noteq>v\<close>
        using \<open>edges T \<subseteq> edges rg\<close> \<open>edges T1 \<union> edges T2 = ?E'\<close>
        apply simp
        by (metis Diff_subset crossing_edge(3) edges_sym' insert_absorb
              nodesI(2) subset_trans)
    qed
    moreover

    have "weight w ?T' \<le> weight w T'" if "is_spanning_tree rg T'" for T'
    proof -
      have ww: "w {u,v} \<le> w{x,y}"
        using min_edge \<open>(x,y)\<in>edges T\<close> \<open>edges T \<subseteq> edges rg\<close> \<open>x\<in>C\<close> \<open>y\<notin>C\<close>
        by blast

      have "weight w ?T' = weight w T - w {x,y} + w{u,v}"
        using \<open>(u, v) \<notin> edges T\<close> \<open>(x, y) \<in> edges T\<close>
        using \<open>edges T1 \<union> edges T2 = edges T - {(x, y), (y, x)}\<close> \<open>u \<noteq> v\<close>
        by (smt Diff_eq Diff_subset add.commute contra_subsetD edges_join
              edges_restrict_edges minus_inv_sym_aux sup.idem weight_cong
              weight_del_edge weight_ins_edge)
      also have "\<dots> \<le> weight w T"
        using weight_ge_edge[OF \<open>(x,y)\<in>edges T\<close>, of w] ww by auto
      also have "weight w T \<le> weight w T'" using T(1) \<open>is_spanning_tree rg T'\<close>
        unfolding is_MST_def by simp
      finally show ?thesis .
    qed
    ultimately have "is_MST w rg ?T'" using is_MST_def by blast
    have "{(u,v),(v,u)} \<union> A \<subseteq> edges ?T'"
      using T(2) respects_cut xy(2,3) \<open>edges T1 \<union> edges T2 = ?E'\<close>
      unfolding respects_cut_def
      by auto

    with \<open>is_MST w rg ?T'\<close> show ?thesis unfolding is_subset_MST_def by force
  qed
qed

end

subsection \<open>Abstract Prim: Growing a Tree\label{sec:prim_algo}\<close>
context Prim begin

text \<open>The current nodes\<close>
definition "S A \<equiv> {r} \<union> fst`A \<union> snd`A"

lemma respects_cut': "A \<subseteq> S A \<times> S A"
  unfolding S_def by force

corollary respects_cut: "respects_cut A (S A)"
  unfolding respects_cut_def using respects_cut' by auto

text \<open>Refined invariant: Adds connectedness of \<open>A\<close>\<close>
definition "prim_invar1 A \<equiv> is_subset_MST w rg A \<and> (\<forall>(u,v)\<in>A. (v,r)\<in>A\<^sup>*)"

text \<open>Measure: Number of nodes not in tree\<close>
definition "T_measure1 A = card (nodes rg - S A)"

end

text \<open>We use a locale that fixes a state and assumes the invariant\<close>
locale Prim_Invar1_loc =
  Prim w g r for w g and r :: 'v +
  fixes A :: "('v\<times>'v) set"
  assumes invar1: "prim_invar1 A"
begin
lemma subset_MST: "is_subset_MST w rg A"
  using invar1 unfolding prim_invar1_def by auto

lemma A_connected: "(u,v)\<in>A \<Longrightarrow> (v,r)\<in>A\<^sup>*"
  using invar1 unfolding prim_invar1_def by auto

lemma S_alt_def: "S A = {r} \<union> fst`A"
  unfolding S_def
  apply (safe;simp)
  by (metis A_connected Domain_fst Not_Domain_rtrancl)

lemma finite_rem_nodes[simp,intro!]: "finite (nodes rg - S A)" by auto

lemma A_edges: "A \<subseteq> edges g"
  using subset_MST
  by (meson is_MST_def is_spanning_tree_def is_subset_MST_def
        reachable_edges_subset subset_eq)

lemma S_reachable: "S A \<subseteq> nodes rg"
  unfolding S_alt_def
  by (smt DomainE Un_insert_left fst_eq_Domain insert_subset is_MST_def
        is_spanning_tree_def is_subset_MST_def nodesI(1) nodes_of_component
        reachable_nodes_refl rg_def subset_MST subset_iff sup_bot.left_neutral)

lemma S_edge_reachable: "\<lbrakk>u\<in>S A; (u,v)\<in>edges g \<rbrakk> \<Longrightarrow> (u,v)\<in>edges rg"
  using S_reachable unfolding rg_def
  using reachable_nodes_step'(2) by fastforce

lemma edges_S_rg_edges: "edges g \<inter> S A\<times>-S A = edges rg \<inter> S A\<times>-S A"
  using S_edge_reachable reachable_edges_subset by auto

lemma T_measure1_less: "T_measure1 A < card (nodes rg)"
  unfolding T_measure1_def S_def
  by (metis Diff_subset S_def S_reachable Un_insert_left le_supE nodes_finite
        psubsetI psubset_card_mono singletonI subset_Diff_insert)

lemma finite_A[simp, intro!]: "finite A"
  using A_edges finite_subset by auto

lemma finite_S[simp, intro!]: "finite (S A)"
  using S_reachable rev_finite_subset by blast

(* TODO: Used? *)
lemma S_A_consistent[simp, intro!]: "nodes_edges_consistent (S A) (A\<union>A\<inverse>)"
  unfolding nodes_edges_consistent_def
  apply (intro conjI)
  subgoal by simp
  subgoal using A_edges irrefl_def by fastforce
  subgoal by (simp add: sym_Un_converse)
  using respects_cut' by auto

end

context Prim begin

lemma invar1_initial: "prim_invar1 {}"
  by (auto simp: is_subset_MST_def prim_invar1_def exists_MST)

lemma maintain_invar1:
  assumes invar: "prim_invar1 A"
  assumes light_edge: "light_edge (S A) u v"
  shows "prim_invar1 ({(v,u)}\<union>A)
       \<and> T_measure1 ({(v,u)}\<union>A) < T_measure1 A" (is "?G1 \<and> ?G2")
proof

  from invar interpret Prim_Invar1_loc w g r A by unfold_locales

  from light_edge have "u\<in>S A" "v\<notin>S A" by (simp_all add: light_edge_def)

  show ?G1
    unfolding prim_invar1_def
  proof (intro conjI)
    show "is_subset_MST w rg ({(v, u)} \<union> A)"
      by (rule light_edge_is_safe[OF subset_MST respects_cut light_edge])

  next
    show "\<forall>(ua, va)\<in>{(v, u)} \<union> A. (va, r) \<in> ({(v, u)} \<union> A)\<^sup>*"
      apply safe
      subgoal
        using A_connected
        by (simp add: rtrancl_insert)
           (metis DomainE S_alt_def converse_rtrancl_into_rtrancl \<open>u\<in>S A\<close>
                    fst_eq_Domain insertE insert_is_Un rtrancl_eq_or_trancl)
      subgoal using A_connected by (simp add: rtrancl_insert)
      done
  qed
  then interpret N: Prim_Invar1_loc w g r "{(v,u)}\<union>A" by unfold_locales

  have "S A \<subset> S ({(v,u)}\<union>A)" using \<open>v\<notin>S A\<close>
    unfolding S_def by auto
  then show "?G2" unfolding T_measure1_def
    using S_reachable N.S_reachable
    by (auto intro!: psubset_card_mono)

qed

lemma invar1_finish:
  assumes INV: "prim_invar1 A"
  assumes FIN: "edges g \<inter> S A\<times>-S A = {}"
  shows "is_MST w rg (graph {r} A)"
proof -
  from INV interpret Prim_Invar1_loc w g r A by unfold_locales

  from subset_MST obtain t where MST: "is_MST w rg t" and "A \<subseteq> edges t"
    unfolding is_subset_MST_def by auto

  have "S A = nodes t"
  proof safe
    fix u
    show "u\<in>S A \<Longrightarrow> u\<in>nodes t" using MST
      unfolding is_MST_def is_spanning_tree_def
      using S_reachable by auto
  next
    fix u
    assume "u\<in>nodes t"
    hence "u\<in>nodes rg"
      using MST is_MST_def is_spanning_tree_def by force
    hence 1: "(u,r)\<in>(edges rg)\<^sup>*" by (simp add: connectedD rg_def)
    have "r\<in>S A" by (simp add: S_def)
    show "u\<in>S A" proof (rule ccontr)
      assume "u\<notin>S A"
      from find_crossing_edge_rtrancl[where P="\<lambda>u. u\<in>S A", OF 1 \<open>u\<notin>S A\<close> \<open>r\<in>S A\<close>]
        FIN reachable_edges_subset
      show False
        by (smt ComplI IntI contra_subsetD edges_sym' emptyE mem_Sigma_iff)

    qed
  qed
  also have "nodes t = nodes rg"
    using MST unfolding is_MST_def is_spanning_tree_def
    by auto
  finally have S_eq: "S A = nodes rg" .

  define t' where "t' = graph {r} A"

  have [simp]: "nodes t' = S A" and Et': "edges t' = (A\<union>A\<inverse>)" unfolding t'_def
    using A_edges
    by (auto simp: graph_accs S_def)

  hence "edges t' \<subseteq> edges t"
    by (smt UnE \<open>A \<subseteq> edges t\<close> converseD edges_sym' subrelI subset_eq)

  have "is_spanning_tree rg t'"
  proof -
    have "connected t'"
      apply rule
      apply (simp add: Et' S_def)
      apply safe
      apply ((simp add: A_connected converse_rtrancl_into_rtrancl
                        in_rtrancl_UnI rtrancl_converse
             )+
      ) [4]
      apply simp_all [4]
      apply ((meson A_connected in_rtrancl_UnI r_into_rtrancl
                rtrancl_converseI rtrancl_trans
             )+
      ) [4]
      done

    moreover have "cycle_free t'"
      by (meson MST \<open>edges t' \<subseteq> edges t\<close> cycle_free_antimono is_MST_def
                is_spanning_tree_def tree_def)
    moreover have "edges t' \<subseteq> edges rg"
      by (meson MST \<open>edges t' \<subseteq> edges t\<close> dual_order.trans is_MST_def
            is_spanning_tree_def)
    ultimately show ?thesis
      unfolding is_spanning_tree_def tree_def
      by (auto simp: S_eq)
  qed
  then show ?thesis
    using MST weight_mono[OF \<open>edges t' \<subseteq> edges t\<close>]
    unfolding t'_def is_MST_def
    using dual_order.trans by blast
qed

end

subsection \<open>Prim: Using a Priority Queue\label{sec:using_pq}\<close>
text \<open>We define a new locale. Note that we could also reuse @{locale Prim}, however,
  this would complicate referencing the constants later in the theories from
  which we generate the paper.
\<close>
locale Prim2 = Prim w g r for w :: "'v set \<Rightarrow> nat" and g :: "'v ugraph" and r :: 'v
begin

text \<open>Abstraction to edge set\<close>
definition "A Q \<pi> \<equiv> {(u,v). \<pi> u = Some v \<and> Q u = \<infinity>}"

text \<open>Initialization\<close>
definition initQ :: "'v \<Rightarrow> enat"  where "initQ \<equiv> (\<lambda>_. \<infinity>)(r := 0)"
definition init\<pi> :: "'v \<Rightarrow> 'v option" where "init\<pi> \<equiv> Map.empty"

text \<open>Step\<close>
definition "upd_cond Q \<pi> u v' \<equiv>
    (v',u) \<in> edges g
  \<and> v'\<noteq>r \<and> (Q v' = \<infinity> \<longrightarrow> \<pi> v' = None)
  \<and> enat (w {v',u}) < Q v'"

text \<open>State after inner loop\<close>
definition "Qinter Q \<pi> u v'
  = (if upd_cond Q \<pi> u v' then enat (w {v',u}) else Q v')"

text \<open>State after one step\<close>
definition "Q' Q \<pi> u \<equiv> (Qinter Q \<pi> u)(u:=\<infinity>)"
definition "\<pi>' Q \<pi> u v' = (if upd_cond Q \<pi> u v' then Some u else \<pi> v')"

definition "prim_invar2_init Q \<pi> \<equiv> Q=initQ \<and> \<pi>=init\<pi>"

definition "prim_invar2_ctd Q \<pi> \<equiv> let A = A Q \<pi>; S = S A in
  prim_invar1 A
\<and> \<pi> r = None \<and> Q r = \<infinity>
\<and> (\<forall>(u,v)\<in>edges rg \<inter> (-S)\<times>S. Q u \<noteq> \<infinity>)
\<and> (\<forall>u. Q u \<noteq> \<infinity> \<longrightarrow> \<pi> u \<noteq> None)
\<and> (\<forall>u v. \<pi> u = Some v \<longrightarrow> v\<in>S \<and> (u,v)\<in>edges rg)
\<and> (\<forall>u v d. Q u = enat d \<and> \<pi> u = Some v
      \<longrightarrow> d=w {u,v} \<and> (\<forall>v'\<in>S. (u,v')\<in>edges rg \<longrightarrow> d \<le> w {u,v'}))
"

lemma prim_invar2_ctd_alt_aux1:
  assumes "prim_invar1 (A Q \<pi>)"
  assumes "Q u \<noteq> \<infinity>" "u\<noteq>r"
  shows "u\<notin>S (A Q \<pi>)"
proof -
  interpret Prim_Invar1_loc w g r "A Q \<pi>" by unfold_locales fact
  show ?thesis
    unfolding S_alt_def unfolding A_def using assms
    by auto
qed

lemma prim_invar2_ctd_alt: "prim_invar2_ctd Q \<pi> \<longleftrightarrow> (
  let A = A Q \<pi>; S = S A; cE=edges rg \<inter> (-S)\<times>S in
    prim_invar1 A
  \<and> \<pi> r = None \<and> Q r = \<infinity>
  \<and> (\<forall>(u,v)\<in>cE. Q u \<noteq> \<infinity>)
  \<and> (\<forall>u v. \<pi> u = Some v \<longrightarrow> v\<in>S \<and> (u,v)\<in>edges rg)
  \<and> (\<forall>u d. Q u = enat d
      \<longrightarrow> (\<exists>v. \<pi> u = Some v \<and> d=w {u,v} \<and> (\<forall>v'. (u,v')\<in>cE \<longrightarrow> d \<le> w {u,v'})))
)"
  unfolding prim_invar2_ctd_def Let_def
  using prim_invar2_ctd_alt_aux1[of Q \<pi>]
  apply safe
  subgoal by auto
  subgoal by (auto 0 3)
  subgoal by (auto 0 3)
  subgoal by clarsimp (metis (no_types,lifting) option.simps(3))
  done

definition "prim_invar2 Q \<pi> \<equiv> prim_invar2_init Q \<pi> \<or> prim_invar2_ctd Q \<pi>"

definition "T_measure2 Q \<pi>
  \<equiv> if Q r = \<infinity> then T_measure1 (A Q \<pi>) else card (nodes rg)"

lemma Q'_init_eq:
  "Q' initQ init\<pi> r = (\<lambda>u. if (u,r)\<in>edges rg then enat (w {u,r}) else \<infinity>)"
  apply (rule ext)
  using reachable_edges_subset
  apply (simp add: Q'_def Qinter_def upd_cond_def initQ_def init\<pi>_def)
  by (auto simp: Prim.rg_def edges_sym' reachable_nodes_step'(2))

lemma \<pi>'_init_eq:
  "\<pi>' initQ init\<pi> r = (\<lambda>u. if (u,r)\<in>edges rg then Some r else None)"
  apply (rule ext)
  using reachable_edges_subset
  apply (simp add: \<pi>'_def upd_cond_def initQ_def init\<pi>_def)
  by (auto simp: Prim.rg_def edges_sym' reachable_nodes_step'(2))

lemma A_init_eq: "A initQ init\<pi> = {}"
  unfolding A_def init\<pi>_def
  by auto

lemma S_empty: "S {} = {r}" unfolding S_def by (auto simp: A_init_eq)

lemma maintain_invar2_first_step:
  assumes INV: "prim_invar2_init Q \<pi>"
  assumes UNS: "Q u = enat d"
  shows "prim_invar2_ctd (Q' Q \<pi> u) (\<pi>' Q \<pi> u)" (is ?G1)
    and "T_measure2 (Q' Q \<pi> u) (\<pi>' Q \<pi> u) < T_measure2 Q \<pi>" (is ?G2)
proof -
  from INV have [simp]: "Q=initQ" "\<pi>=init\<pi>"
    unfolding prim_invar2_init_def by auto
  from UNS have [simp]: "u=r" by (auto simp: initQ_def split: if_splits)

  note Q'_init_eq \<pi>'_init_eq A_init_eq

  have [simp]: "(A (Q' initQ init\<pi> r) (\<pi>' initQ init\<pi> r)) = {}"
    apply (simp add: Q'_init_eq \<pi>'_init_eq)
    by (auto simp: A_def split: if_splits)

  show ?G1
    apply (simp add: prim_invar2_ctd_def Let_def invar1_initial)
    by (auto simp: Q'_init_eq \<pi>'_init_eq S_empty split: if_splits)

  have [simp]: "Q' initQ init\<pi> r r = \<infinity>"
    by (auto simp: Q'_init_eq)

  have [simp]: "initQ r = 0" by (simp add: initQ_def)

  show ?G2
    unfolding T_measure2_def
    apply simp
    apply (simp add: T_measure1_def S_empty)
    by (metis card_Diff1_less nodes_finite nodes_of_component
          reachable_nodes_refl rg_def)

qed

lemma maintain_invar2_first_step_presentation:
  assumes INV: "prim_invar2_init Q \<pi>"
  assumes UNS: "Q u = enat d"
  shows "prim_invar2_ctd (Q' Q \<pi> u) (\<pi>' Q \<pi> u)
       \<and> T_measure2 (Q' Q \<pi> u) (\<pi>' Q \<pi> u) < T_measure2 Q \<pi>"
  using maintain_invar2_first_step assms by blast

end

(*<*)
(*
  This locale is only used to present the invariant in the paper.
*)
locale Prim_Invar2_ctd_Presentation_Loc =
  fixes w g and r :: 'v and Q \<pi> A S rg cE
  assumes I: "Prim2.prim_invar2_ctd w g r Q \<pi>"
  defines local_A_def: "A \<equiv> Prim2.A Q \<pi>"
  defines local_S_def: "S \<equiv> Prim.S r A"
  defines local_rg_def: "rg \<equiv> Prim.rg g r"
  defines local_cE_def: "cE \<equiv> edges rg \<inter> (-S)\<times>S"
begin

lemma
      invar1: "Prim.prim_invar1 w g r A" (is ?G1)
  and root_contained: "\<pi> r = None \<and> Q r = \<infinity>" (is ?G2)
  and Q_defined: "\<forall>(u,v)\<in>cE. Q u \<noteq> \<infinity>" (is ?G3)
  and \<pi>_edges: "\<forall>u v. \<pi> u = Some v \<longrightarrow> v\<in>S \<and> (u,v)\<in>edges rg" (is ?G4)
  and Q_min: "\<forall>u d. Q u = enat d
      \<longrightarrow> (\<exists>v. \<pi> u = Some v \<and> d=w {u,v} \<and> (\<forall>v'. (u,v')\<in>cE \<longrightarrow> d \<le> w {u,v'}))"
      (is ?G5)
proof -
  interpret Prim2 w g r .

  show ?G1 ?G2 ?G3 ?G4 ?G5
    using I
    unfolding local_A_def local_S_def local_rg_def local_cE_def
              prim_invar2_ctd_alt Let_def
    by simp_all
qed

end

lemma (in Prim2) Prim_Invar2_ctd_Presentation_Loc_eq:
  "Prim_Invar2_ctd_Presentation_Loc w g r Q \<pi> \<longleftrightarrow> prim_invar2_ctd Q \<pi>"
  unfolding Prim_Invar2_ctd_Presentation_Loc_def ..

(*>*)

text \<open>Again, we define a locale to fix a state and assume the invariant\<close>
locale Prim_Invar2_ctd_loc =
  Prim2 w g r for w g and r :: 'v +
  fixes Q \<pi>
  assumes invar2: "prim_invar2_ctd Q \<pi>"
begin

sublocale Prim_Invar1_loc w g r "A Q \<pi>"
  using invar2 unfolding prim_invar2_ctd_def
  apply unfold_locales by (auto simp: Let_def)

lemma upd_cond_alt: "upd_cond Q \<pi> u v' \<longleftrightarrow>
  (v',u) \<in> edges g \<and> v'\<notin>S (A Q \<pi>) \<and> enat (w {v',u}) < Q v'"
  unfolding upd_cond_def S_alt_def unfolding A_def
  by (auto simp: fst_eq_Domain)

lemma \<pi>_root: "\<pi> r = None"
  and Q_root: "Q r = \<infinity>"
  and Q_defined: "\<lbrakk> (u,v)\<in>edges rg; u\<notin>S (A Q \<pi>); v\<in>S (A Q \<pi>) \<rbrakk> \<Longrightarrow> Q u \<noteq> \<infinity>"
  and \<pi>_defined: "\<lbrakk> Q u \<noteq> \<infinity> \<rbrakk> \<Longrightarrow> \<pi> u \<noteq> None"
  and frontier: "\<pi> u = Some v \<Longrightarrow> v\<in>S (A Q \<pi>)"
  and edges: "\<pi> u = Some v \<Longrightarrow> (u,v)\<in>edges rg"
  and Q_\<pi>_consistent: "\<lbrakk> Q u = enat d; \<pi> u = Some v \<rbrakk> \<Longrightarrow> d = w {u,v}"
  and Q_min: "Q u = enat d
      \<Longrightarrow> (\<forall>v'\<in>S (A Q \<pi>). (u,v')\<in>edges rg \<longrightarrow> d \<le> w {u,v'})"
  using invar2 unfolding prim_invar2_ctd_def Let_def by auto

lemma \<pi>_def_on_S: "\<lbrakk>u\<in>S (A Q \<pi>); u\<noteq>r\<rbrakk> \<Longrightarrow> \<pi> u \<noteq> None"
  unfolding S_alt_def
  unfolding A_def
  by auto

lemma \<pi>_def_on_edges_to_S: "\<lbrakk>v\<in>S (A Q \<pi>); u\<noteq>r; (u,v)\<in>edges rg\<rbrakk> \<Longrightarrow> \<pi> u \<noteq> None"
  apply (cases "u\<in>S (A Q \<pi>)")
  subgoal using \<pi>_def_on_S by auto
  subgoal by (simp add: Q_defined \<pi>_defined)
  done

lemma Q_min_is_light:
  assumes UNS: "Q u = enat d"
  assumes MIN: "\<forall>v. enat d \<le> Q v"
  obtains v where "\<pi> u = Some v" "light_edge (S (A Q \<pi>)) v u"
proof -
  let ?A = "A Q \<pi>"
  let ?S = "S ?A"

  from UNS obtain v where
    S1[simp]: "\<pi> u = Some v" "d = w {u,v}"
    using \<pi>_defined Q_\<pi>_consistent
    by blast

  have "v\<in>?S" using frontier[of u v] by auto

  have [simp]: "u\<noteq>r" using \<pi>_root using S1 by (auto simp del: S1)

  have "u\<notin>?S" unfolding S_alt_def unfolding A_def using UNS by auto

  have "(v,u)\<in>edges rg" using edges[OF S1(1)]
    by (meson edges_sym' rev_subsetD)

  have M: "\<forall>(u', v')\<in>edges rg \<inter> ?S \<times> - ?S. w {v, u} \<le> w {u', v'}"
  proof safe
    fix a b
    assume "(a,b)\<in>edges rg" "a\<in>?S" "b\<notin>?S"
    hence "(b,a)\<in>edges rg" by (simp add: edges_sym')

    from Q_defined[OF \<open>(b,a)\<in>edges rg\<close> \<open>b\<notin>?S\<close> \<open>a\<in>?S\<close>]
      obtain d' where 1: "Q b = enat d'" by blast
    with \<pi>_defined obtain a' where "\<pi> b = Some a'" by auto
    from MIN 1 have "d\<le>d'" by (metis enat_ord_simps(1))
    also from Q_min[OF 1] \<open>(b,a)\<in>edges rg\<close> \<open>a\<in>?S\<close> have "d'\<le>w {b,a}" by blast
    finally show "w {v,u} \<le> w {a,b}" by (simp add: insert_commute)
  qed

  have LE: "light_edge ?S v u" using invar1 \<open>v\<in>?S\<close> \<open>u\<notin>?S\<close> \<open>(v,u)\<in>edges rg\<close> M
    unfolding light_edge_def by blast

  thus ?thesis using that by auto
qed

lemma maintain_invar_ctd:
  assumes UNS: "Q u = enat d"
  assumes MIN: "\<forall>v. enat d \<le> Q v"
  shows "prim_invar2_ctd (Q' Q \<pi> u) (\<pi>' Q \<pi> u)" (is ?G1)
    and "T_measure2 (Q' Q \<pi> u) (\<pi>' Q \<pi> u) < T_measure2 Q \<pi>" (is ?G2)
proof -
  let ?A = "A Q \<pi>"
  let ?S = "S ?A"

  from Q_min_is_light[OF UNS MIN] obtain v where
    [simp]: "\<pi> u = Some v" and LE: "light_edge ?S v u" .

  let ?Q' = "Q' Q \<pi> u"
  let ?\<pi>' = "\<pi>' Q \<pi> u"
  let ?A' = "A ?Q' ?\<pi>'"
  let ?S' = "S ?A'"

  have NA: "?A' = {(u,v)} \<union> ?A"
    unfolding A_def
    unfolding Q'_def \<pi>'_def upd_cond_def Qinter_def
    by (auto split: if_splits)

  from maintain_invar1[OF invar1 LE]
  have "prim_invar1 ?A'" and M1: "T_measure1 ?A' < T_measure1 ?A"
    by (auto simp: NA)
  then interpret N: Prim_Invar1_loc w g r ?A' by unfold_locales

  have [simp]: "?S' = insert u ?S"
    unfolding S_alt_def N.S_alt_def
    unfolding Q'_def Qinter_def \<pi>'_def upd_cond_def
    unfolding A_def
    by (auto split: if_splits simp: image_iff)

  show ?G1
    unfolding prim_invar2_ctd_def Let_def
    apply safe
    subgoal by fact
    subgoal
      unfolding \<pi>'_def upd_cond_def
      by (auto simp: \<pi>_root)
    subgoal
      by (simp add: Prim2.Q'_def Prim2.Qinter_def Prim2.upd_cond_def Q_root)
    subgoal for a b
      apply simp
      apply safe
      subgoal
        unfolding Q'_def Qinter_def upd_cond_def
        apply (simp add: S_alt_def A_def)
        apply safe
        subgoal using reachable_edges_subset by blast
        subgoal by (simp add: Prim.S_def)
        subgoal by (metis (no_types) A_def Q_defined edges frontier)
        subgoal using not_infinity_eq by fastforce
        done
      subgoal
        unfolding S_alt_def N.S_alt_def
        unfolding A_def Q'_def Qinter_def upd_cond_def
        apply (simp; safe; (auto;fail)?)
        subgoal
        proof -
          assume a1: "(a, r) \<in> edges rg"
          assume "a \<notin> fst ` {(u, v). \<pi> u = Some v \<and> Q u = \<infinity>}"
          then have "a \<notin> fst ` A Q \<pi>"
            by (simp add: A_def)
          then show ?thesis
            using a1
            by (metis (no_types) S_alt_def Q_defined Un_insert_left
                  edges_irrefl' insert_iff not_infinity_eq sup_bot.left_neutral)
        qed
        subgoal by (simp add: fst_eq_Domain)
        subgoal
          apply clarsimp
          by (smt Domain.intros Q_defined \<pi>_def_on_edges_to_S case_prod_conv
                edges enat.exhaust frontier fst_eq_Domain mem_Collect_eq
                option.exhaust)
        subgoal by (simp add: fst_eq_Domain)
        done
      done
    subgoal
      by (metis Q'_def Qinter_def \<pi>'_def \<pi>_defined enat.distinct(2)
            fun_upd_apply not_None_eq)

    subgoal
      by (metis \<open>S (A (Q' Q \<pi> u) (\<pi>' Q \<pi> u)) = insert u (S (A Q \<pi>))\<close> \<pi>'_def
            frontier insertCI option.inject)
    subgoal
      by (metis N.S_edge_reachable upd_cond_def
          \<open>S (A (Q' Q \<pi> u) (\<pi>' Q \<pi> u)) = insert u (S (A Q \<pi>))\<close> \<pi>'_def edges
          edges_sym' insertI1 option.inject)
    subgoal
      by (smt Q'_def \<pi>'_def Q_\<pi>_consistent Qinter_def fun_upd_apply
            insert_absorb not_enat_eq option.inject the_enat.simps)
    subgoal for v' d'
      apply clarsimp
      unfolding Q'_def Qinter_def upd_cond_def
      using Q_min
      apply (clarsimp split: if_splits; safe)
      apply (all \<open>(auto;fail)?\<close>)
      subgoal by (simp add: le_less less_le_trans)
      subgoal using \<pi>_def_on_edges_to_S by auto
      subgoal using reachable_edges_subset by auto
      subgoal by (simp add: Q_root)
      done
    done
  then interpret N: Prim_Invar2_ctd_loc w g r ?Q' ?\<pi>' by unfold_locales

  show ?G2
    unfolding T_measure2_def
    by (auto simp: Q_root N.Q_root M1)

qed

end

context Prim2 begin

lemma maintain_invar2_ctd:
  assumes INV: "prim_invar2_ctd Q \<pi>"
  assumes UNS: "Q u = enat d"
  assumes MIN: "\<forall>v. enat d \<le> Q v"
  shows "prim_invar2_ctd (Q' Q \<pi> u) (\<pi>' Q \<pi> u)" (is ?G1)
    and "T_measure2 (Q' Q \<pi> u) (\<pi>' Q \<pi> u) < T_measure2 Q \<pi>" (is ?G2)
proof -
  interpret Prim_Invar2_ctd_loc w g r Q \<pi> using INV by unfold_locales
  from maintain_invar_ctd[OF UNS MIN] show ?G1 ?G2 by auto
qed

lemma Q_min_is_light_presentation:
  assumes INV: "prim_invar2_ctd Q \<pi>"
  assumes UNS: "Q u = enat d"
  assumes MIN: "\<forall>v. enat d \<le> Q v"
  obtains v where "\<pi> u = Some v" "light_edge (S (A Q \<pi>)) v u"
proof -
  interpret Prim_Invar2_ctd_loc w g r Q \<pi> using INV by unfold_locales
  from Q_min_is_light[OF UNS MIN] show ?thesis using that .
qed

lemma maintain_invar2_ctd_presentation:
  assumes INV: "prim_invar2_ctd Q \<pi>"
  assumes UNS: "Q u = enat d"
  assumes MIN: "\<forall>v. enat d \<le> Q v"
  shows "prim_invar2_ctd (Q' Q \<pi> u) (\<pi>' Q \<pi> u)
       \<and> T_measure2 (Q' Q \<pi> u) (\<pi>' Q \<pi> u) < T_measure2 Q \<pi>"
  using maintain_invar2_ctd assms by blast

lemma invar2_init_init: "prim_invar2_init initQ init\<pi>"
  unfolding prim_invar2_init_def by auto

lemma invar2_init: "prim_invar2 initQ init\<pi>"
  unfolding prim_invar2_def using invar2_init_init by auto

lemma maintain_invar2:
  assumes A: "prim_invar2 Q \<pi>"
  assumes UNS: "Q u = enat d"
  assumes MIN: "\<forall>v. enat d \<le> Q v"
  shows "prim_invar2 (Q' Q \<pi> u) (\<pi>' Q \<pi> u)" (is ?G1)
    and "T_measure2 (Q' Q \<pi> u) (\<pi>' Q \<pi> u) < T_measure2 Q \<pi>" (is ?G2)
  using A unfolding prim_invar2_def
  using maintain_invar2_first_step[of Q,OF _ UNS]
  using maintain_invar2_ctd[OF _ UNS MIN]
  using not_invar2_ctd_init
  apply blast+
  done

lemma invar2_ctd_finish:
  assumes INV: "prim_invar2_ctd Q \<pi>"
  assumes FIN: "Q = (\<lambda>_. \<infinity>)"
  shows "is_MST w rg (graph {r} {(u, v). \<pi> u = Some v})"
proof -
  from INV interpret Prim_Invar2_ctd_loc w g r Q \<pi> by unfold_locales

  let ?A = "A Q \<pi>" let ?S="S ?A"

  have FC: "edges g \<inter> ?S \<times> - ?S = {}"
  proof (safe; simp)
    fix a b
    assume "(a,b)\<in>edges g" "a\<in>?S" "b\<notin>?S"
    with Q_defined[OF edges_sym'] S_edge_reachable have "Q b \<noteq> \<infinity>"
      by blast
    with FIN show False by auto
  qed

  have Aeq: "?A = {(u, v). \<pi> u = Some v}"
    unfolding A_def using FIN by auto

  from invar1_finish[OF invar1 FC, unfolded Aeq] show ?thesis .
qed

lemma invar2_finish:
  assumes INV: "prim_invar2 Q \<pi>"
  assumes FIN: "Q = (\<lambda>_. \<infinity>)"
  shows "is_MST w rg (graph {r} {(u, v). \<pi> u = Some v})"
proof -
  from INV have "prim_invar2_ctd Q \<pi>"
    unfolding prim_invar2_def prim_invar2_init_def initQ_def
    by (auto simp: fun_eq_iff FIN split: if_splits)
  with FIN invar2_ctd_finish show ?thesis by blast
qed

end

subsection \<open>Refinement of Inner Foreach Loop\label{sec:using_foreach}\<close>

context Prim2 begin

definition "foreach_body u \<equiv> \<lambda>(v,d) (Q,\<pi>).
  if v=r then (Q,\<pi>)
  else
    case (Q v, \<pi> v) of
      (\<infinity>,None) \<Rightarrow> (Q(v:=enat d), \<pi>(v\<mapsto>u))
    | (enat d',_) \<Rightarrow> if d<d' then (Q(v:=enat d), \<pi>(v\<mapsto>u)) else (Q,\<pi>)
    | (\<infinity>,Some _) \<Rightarrow> (Q,\<pi>)
  "

lemma foreach_body_alt: "foreach_body u = (\<lambda>(v,d) (Q,\<pi>).
  if v\<noteq>r \<and> (\<pi> v = None \<or> Q v \<noteq> \<infinity>) \<and> enat d < Q v then
    (Q(v:=enat d), \<pi>(v\<mapsto>u))
  else
    (Q,\<pi>)
)"
  unfolding foreach_body_def S_def
  by (auto split: enat.splits option.splits simp: fst_eq_Domain fun_eq_iff)

definition foreach where
  "foreach u adjs Q\<pi> = foldr (foreach_body u) adjs Q\<pi>"

definition "\<And>Q V.
  Qigen Q \<pi> u adjs v = (if v \<notin> fst`set adjs then Q v else Qinter Q \<pi> u v)"
definition "\<And>Q V \<pi>.
  \<pi>'gen Q \<pi> u adjs v = (if v \<notin> fst`set adjs then \<pi> v else \<pi>' Q \<pi> u v)"

context begin

private lemma Qc:
  "Qigen Q \<pi> u ((v, w {u, v}) # adjs) x
  = (if x=v then Qinter Q \<pi> u v else Qigen Q \<pi> u adjs x)" for x
  unfolding Qigen_def by auto

private lemma \<pi>c:
  "\<pi>'gen Q \<pi> u ((v, w {u, v}) # adjs) x
  = (if x=v then \<pi>' Q \<pi> u v else \<pi>'gen Q \<pi> u adjs x)" for x
  unfolding \<pi>'gen_def by auto

lemma foreach_refine_gen:
  assumes "set adjs \<subseteq> {(v,d). (u,v)\<in>edges g \<and> w {u,v} = d}"
  shows "foreach u adjs (Q,\<pi>) = (Qigen Q \<pi> u adjs,\<pi>'gen Q \<pi> u adjs)"
  using assms
  unfolding foreach_def
proof (induction adjs arbitrary: Q \<pi>)
  case Nil
  have INVAR_INIT: "Qigen Q \<pi> u [] = Q" "\<pi>'gen Q \<pi> u [] = \<pi>" for Q \<pi>
    unfolding assms Qigen_def \<pi>'gen_def
    by (auto simp: fun_eq_iff image_def Q'_def \<pi>'_def edges_def)
  with Nil show ?case by (simp add: INVAR_INIT)
next
  case (Cons a adjs)
  obtain v d where [simp]: "a=(v,d)" by (cases a)

  have [simp]: "u\<noteq>v" "v\<noteq>u" using Cons.prems by auto

  have QinfD: "Qigen Q \<pi> u adjs v = \<infinity> \<Longrightarrow> Q v = \<infinity>"
    unfolding Qigen_def Q'_def Qinter_def by (auto split: if_splits)

  show ?case using Cons.prems
    apply (cases a)
    apply (clarsimp simp: Cons.IH)
    unfolding foreach_body_def
    apply (clarsimp; safe)
    subgoal by (auto simp: Qigen_def Qinter_def upd_cond_def)
    subgoal by (auto simp: \<pi>'gen_def \<pi>'_def upd_cond_def)
    subgoal
      apply (clarsimp split: enat.split option.split simp: \<pi>c Qc fun_eq_iff)
      unfolding Qinter_def Qigen_def \<pi>'_def \<pi>'gen_def upd_cond_def
      apply (safe; simp split: if_splits add: insert_commute)
      by (auto dest: edges_sym')
    done

qed

lemma foreach_refine:
  assumes "set adjs = {(v,d). (u,v)\<in>edges g \<and> w {u,v} = d}"
  shows "foreach u adjs (Q,\<pi>) = (Qinter Q \<pi> u,\<pi>' Q \<pi> u)"
proof -
  have INVAR_INIT: "Qigen Q \<pi> u [] = Q" "\<pi>'gen Q \<pi> u [] = \<pi>" for Q \<pi>
    unfolding assms Qigen_def \<pi>'gen_def
    by (auto simp: fun_eq_iff image_def Q'_def \<pi>'_def edges_def)
  from assms have 1: "set adjs \<subseteq> {(v,d). (u,v)\<in>edges g \<and> w {u,v} = d}"
    by simp
  have [simp]:
    "v \<in> fst ` {(v, d). (u, v) \<in> edges g \<and> w {u, v} = d}
    \<longleftrightarrow> (u,v)\<in>edges g"
    for v
    by force

  show ?thesis
    unfolding foreach_refine_gen[OF 1]
    unfolding Qigen_def \<pi>'gen_def assms upd_cond_def Qinter_def \<pi>'_def
    by (auto simp: fun_eq_iff image_def dest: edges_sym')

qed

end
end

end