(*  Title:      HOL/Nitpick_Examples/Typedef_Nits.thy
    Author:     Jasmin Blanchette, TU Muenchen
    Copyright   2009-2011

Examples featuring Nitpick applied to typedefs.
*)

section {* Examples Featuring Nitpick Applied to Typedefs *}

theory Typedef_Nits
imports Complex_Main
begin

nitpick_params [verbose, card = 1-4, sat_solver = MiniSat_JNI, max_threads = 1,
                timeout = 240]

definition "three = {0\<Colon>nat, 1, 2}"
typedef three = three
unfolding three_def by blast

definition A :: three where "A \<equiv> Abs_three 0"
definition B :: three where "B \<equiv> Abs_three 1"
definition C :: three where "C \<equiv> Abs_three 2"

lemma "x = (y\<Colon>three)"
nitpick [expect = genuine]
oops

definition "one_or_two = {undefined False\<Colon>'a, undefined True}"

typedef 'a one_or_two = "one_or_two :: 'a set"
unfolding one_or_two_def by auto

lemma "x = (y\<Colon>unit one_or_two)"
nitpick [expect = none]
sorry

lemma "x = (y\<Colon>bool one_or_two)"
nitpick [expect = genuine]
oops

lemma "undefined False \<longleftrightarrow> undefined True \<Longrightarrow> x = (y\<Colon>bool one_or_two)"
nitpick [expect = none]
sorry

lemma "undefined False \<longleftrightarrow> undefined True \<Longrightarrow> \<exists>x (y\<Colon>bool one_or_two). x \<noteq> y"
nitpick [card = 1, expect = potential] (* unfortunate *)
oops

lemma "\<exists>x (y\<Colon>bool one_or_two). x \<noteq> y"
nitpick [card = 1, expect = potential] (* unfortunate *)
nitpick [card = 2, expect = none]
oops

definition "bounded = {n\<Colon>nat. finite (UNIV \<Colon> 'a set) \<longrightarrow> n < card (UNIV \<Colon> 'a set)}"

typedef 'a bounded = "bounded(TYPE('a))"
unfolding bounded_def
apply (rule_tac x = 0 in exI)
apply (case_tac "card UNIV = 0")
by auto

lemma "x = (y\<Colon>unit bounded)"
nitpick [expect = none]
sorry

lemma "x = (y\<Colon>bool bounded)"
nitpick [expect = genuine]
oops

lemma "x \<noteq> (y\<Colon>bool bounded) \<Longrightarrow> z = x \<or> z = y"
nitpick [expect = potential] (* unfortunate *)
sorry

lemma "x \<noteq> (y\<Colon>(bool \<times> bool) bounded) \<Longrightarrow> z = x \<or> z = y"
nitpick [card = 1-5, expect = genuine]
oops

lemma "True \<equiv> ((\<lambda>x\<Colon>bool. x) = (\<lambda>x. x))"
nitpick [expect = none]
by (rule True_def)

lemma "False \<equiv> \<forall>P. P"
nitpick [expect = none]
by (rule False_def)

lemma "() = Abs_unit True"
nitpick [expect = none]
by (rule Unity_def)

lemma "() = Abs_unit False"
nitpick [expect = none]
by simp

lemma "Rep_unit () = True"
nitpick [expect = none]
by (insert Rep_unit) simp

lemma "Rep_unit () = False"
nitpick [expect = genuine]
oops

lemma "Pair a b = Abs_prod (Pair_Rep a b)"
nitpick [card = 1-2, expect = none]
by (rule Pair_def)

lemma "Pair a b = Abs_prod (Pair_Rep b a)"
nitpick [card = 1-2, expect = none]
nitpick [dont_box, expect = genuine]
oops

lemma "fst (Abs_prod (Pair_Rep a b)) = a"
nitpick [card = 2, expect = none]
by (simp add: Pair_def [THEN sym])

lemma "fst (Abs_prod (Pair_Rep a b)) = b"
nitpick [card = 1-2, expect = none]
nitpick [dont_box, expect = genuine]
oops

lemma "a \<noteq> a' \<Longrightarrow> Pair_Rep a b \<noteq> Pair_Rep a' b"
nitpick [expect = none]
apply (rule ccontr)
apply simp
apply (drule subst [where P = "\<lambda>r. Abs_prod r = Abs_prod (Pair_Rep a b)"])
 apply (rule refl)
by (simp add: Pair_def [THEN sym])

lemma "Abs_prod (Rep_prod a) = a"
nitpick [card = 2, expect = none]
by (rule Rep_prod_inverse)

lemma "Inl \<equiv> \<lambda>a. Abs_sum (Inl_Rep a)"
nitpick [card = 1, expect = none]
by (simp add: Inl_def o_def)

lemma "Inl \<equiv> \<lambda>a. Abs_sum (Inr_Rep a)"
nitpick [card = 1, card "'a + 'a" = 2, expect = genuine]
oops

lemma "Inl_Rep a \<noteq> Inr_Rep a"
nitpick [expect = none]
by (rule Inl_Rep_not_Inr_Rep)

lemma "Abs_sum (Rep_sum a) = a"
nitpick [card = 1, expect = none]
nitpick [card = 2, expect = none]
by (rule Rep_sum_inverse)

lemma "0::nat \<equiv> Abs_Nat Zero_Rep"
nitpick [expect = none]
by (rule Zero_nat_def [abs_def])

lemma "Suc n = Abs_Nat (Suc_Rep (Rep_Nat n))"
nitpick [expect = none]
by (rule Nat.Suc_def)

lemma "Suc n = Abs_Nat (Suc_Rep (Suc_Rep (Rep_Nat n)))"
nitpick [expect = genuine]
oops

lemma "Abs_Nat (Rep_Nat a) = a"
nitpick [expect = none]
by (rule Rep_Nat_inverse)

lemma "Abs_list (Rep_list a) = a"
(* nitpick [card = 1-2, expect = none] FIXME *)
by (rule Rep_list_inverse)

record point =
  Xcoord :: int
  Ycoord :: int

lemma "Abs_point_ext (Rep_point_ext a) = a"
nitpick [expect = none]
by (fact Rep_point_ext_inverse)

lemma "Fract a b = of_int a / of_int b"
nitpick [card = 1, expect = none]
by (rule Fract_of_int_quotient)

lemma "Abs_rat (Rep_rat a) = a"
nitpick [card = 1, expect = none]
by (rule Rep_rat_inverse)

typedef check = "{x\<Colon>nat. x < 2}" by (rule exI[of _ 0], auto)

lemma "Rep_check (Abs_check n) = n \<Longrightarrow> n < 2"
nitpick [card = 1-3, expect = none]
using Rep_check[of "Abs_check n"] by auto

lemma "Rep_check (Abs_check n) = n \<Longrightarrow> n < 1"
nitpick [card = 1-3, expect = genuine]
oops

end


(*  Title:      ZF/AC/HH.thy
    Author:     Krzysztof Grabczewski

Some properties of the recursive definition of HH used in the proofs of
  AC17 ==> AC1
  AC1 ==> WO2
  AC15 ==> WO6
*)

theory HH
imports AC_Equiv Hartog
begin

definition
  HH :: "[i, i, i] => i"  where
    "HH(f,x,a) == transrec(a, %b r. let z = x - (\<Union>c \<in> b. r`c)
                                    in  if f`z \<in> Pow(z)-{0} then f`z else {x})"

subsection{*Lemmas useful in each of the three proofs*}

lemma HH_def_satisfies_eq:
     "HH(f,x,a) = (let z = x - (\<Union>b \<in> a. HH(f,x,b))
                   in  if f`z \<in> Pow(z)-{0} then f`z else {x})"
by (rule HH_def [THEN def_transrec, THEN trans], simp)

lemma HH_values: "HH(f,x,a) \<in> Pow(x)-{0} | HH(f,x,a)={x}"
apply (rule HH_def_satisfies_eq [THEN ssubst])
apply (simp add: Let_def Diff_subset [THEN PowI], fast)
done

lemma subset_imp_Diff_eq:
     "B \<subseteq> A ==> X-(\<Union>a \<in> A. P(a)) = X-(\<Union>a \<in> A-B. P(a))-(\<Union>b \<in> B. P(b))"
by fast

lemma Ord_DiffE: "[| c \<in> a-b; b<a |] ==> c=b | b<c & c<a"
apply (erule ltE)
apply (drule Ord_linear [of _ c])
apply (fast elim: Ord_in_Ord)
apply (fast intro!: ltI intro: Ord_in_Ord)
done

lemma Diff_UN_eq_self: "(!!y. y\<in>A ==> P(y) = {x}) ==> x - (\<Union>y \<in> A. P(y)) = x"
by (simp, fast elim!: mem_irrefl)

lemma HH_eq: "x - (\<Union>b \<in> a. HH(f,x,b)) = x - (\<Union>b \<in> a1. HH(f,x,b))
              ==> HH(f,x,a) = HH(f,x,a1)"
apply (subst HH_def_satisfies_eq [of _ _ a1])
apply (rule HH_def_satisfies_eq [THEN trans], simp)
done

lemma HH_is_x_gt_too: "[| HH(f,x,b)={x}; b<a |] ==> HH(f,x,a)={x}"
apply (rule_tac P = "b<a" in impE)
prefer 2 apply assumption+
apply (erule lt_Ord2 [THEN trans_induct])
apply (rule impI)
apply (rule HH_eq [THEN trans])
prefer 2 apply assumption+
apply (rule leI [THEN le_imp_subset, THEN subset_imp_Diff_eq, THEN ssubst],
       assumption)
apply (rule_tac t = "%z. z-?X" in subst_context)
apply (rule Diff_UN_eq_self)
apply (drule Ord_DiffE, assumption)
apply (fast elim: ltE, auto)
done

lemma HH_subset_x_lt_too:
     "[| HH(f,x,a) \<in> Pow(x)-{0}; b<a |] ==> HH(f,x,b) \<in> Pow(x)-{0}"
apply (rule HH_values [THEN disjE], assumption)
apply (drule HH_is_x_gt_too, assumption)
apply (drule subst, assumption)
apply (fast elim!: mem_irrefl)
done

lemma HH_subset_x_imp_subset_Diff_UN:
    "HH(f,x,a) \<in> Pow(x)-{0} ==> HH(f,x,a) \<in> Pow(x - (\<Union>b \<in> a. HH(f,x,b)))-{0}"
apply (drule HH_def_satisfies_eq [THEN subst])
apply (rule HH_def_satisfies_eq [THEN ssubst])
apply (simp add: Let_def Diff_subset [THEN PowI])
apply (drule split_if [THEN iffD1])
apply (fast elim!: mem_irrefl)
done

lemma HH_eq_arg_lt:
     "[| HH(f,x,v)=HH(f,x,w); HH(f,x,v) \<in> Pow(x)-{0}; v \<in> w |] ==> P"
apply (frule_tac P = "%y. y \<in> Pow (x) -{0}" in subst, assumption)
apply (drule_tac a = w in HH_subset_x_imp_subset_Diff_UN)
apply (drule subst_elem, assumption)
apply (fast intro!: singleton_iff [THEN iffD2] equals0I)
done

lemma HH_eq_imp_arg_eq:
  "[| HH(f,x,v)=HH(f,x,w); HH(f,x,w) \<in> Pow(x)-{0}; Ord(v); Ord(w) |] ==> v=w"
apply (rule_tac j = w in Ord_linear_lt)
apply (simp_all (no_asm_simp))
 apply (drule subst_elem, assumption)
 apply (blast dest: ltD HH_eq_arg_lt)
apply (blast dest: HH_eq_arg_lt [OF sym] ltD)
done

lemma HH_subset_x_imp_lepoll:
     "[| HH(f, x, i) \<in> Pow(x)-{0}; Ord(i) |] ==> i \<lesssim> Pow(x)-{0}"
apply (unfold lepoll_def inj_def)
apply (rule_tac x = "\<lambda>j \<in> i. HH (f, x, j) " in exI)
apply (simp (no_asm_simp))
apply (fast del: DiffE
            elim!: HH_eq_imp_arg_eq Ord_in_Ord HH_subset_x_lt_too
            intro!: lam_type ballI ltI intro: bexI)
done

lemma HH_Hartog_is_x: "HH(f, x, Hartog(Pow(x)-{0})) = {x}"
apply (rule HH_values [THEN disjE])
prefer 2 apply assumption
apply (fast del: DiffE
            intro!: Ord_Hartog
            dest!: HH_subset_x_imp_lepoll
            elim!: Hartog_lepoll_selfE)
done

lemma HH_Least_eq_x: "HH(f, x, LEAST i. HH(f, x, i) = {x}) = {x}"
by (fast intro!: Ord_Hartog HH_Hartog_is_x LeastI)

lemma less_Least_subset_x:
     "a \<in> (LEAST i. HH(f,x,i)={x}) ==> HH(f,x,a) \<in> Pow(x)-{0}"
apply (rule HH_values [THEN disjE], assumption)
apply (rule less_LeastE)
apply (erule_tac [2] ltI [OF _ Ord_Least], assumption)
done

subsection{*Lemmas used in the proofs of AC1 ==> WO2 and AC17 ==> AC1*}

lemma lam_Least_HH_inj_Pow:
        "(\<lambda>a \<in> (LEAST i. HH(f,x,i)={x}). HH(f,x,a))
         \<in> inj(LEAST i. HH(f,x,i)={x}, Pow(x)-{0})"
apply (unfold inj_def, simp)
apply (fast intro!: lam_type dest: less_Least_subset_x
            elim!: HH_eq_imp_arg_eq Ord_Least [THEN Ord_in_Ord])
done

lemma lam_Least_HH_inj:
     "\<forall>a \<in> (LEAST i. HH(f,x,i)={x}). \<exists>z \<in> x. HH(f,x,a) = {z}
      ==> (\<lambda>a \<in> (LEAST i. HH(f,x,i)={x}). HH(f,x,a))
          \<in> inj(LEAST i. HH(f,x,i)={x}, {{y}. y \<in> x})"
by (rule lam_Least_HH_inj_Pow [THEN inj_strengthen_type], simp)

lemma lam_surj_sing:
        "[| x - (\<Union>a \<in> A. F(a)) = 0;  \<forall>a \<in> A. \<exists>z \<in> x. F(a) = {z} |]
         ==> (\<lambda>a \<in> A. F(a)) \<in> surj(A, {{y}. y \<in> x})"
apply (simp add: surj_def lam_type Diff_eq_0_iff)
apply (blast elim: equalityE)
done

lemma not_emptyI2: "y \<in> Pow(x)-{0} ==> x \<noteq> 0"
by auto

lemma f_subset_imp_HH_subset:
     "f`(x - (\<Union>j \<in> i. HH(f,x,j))) \<in> Pow(x - (\<Union>j \<in> i. HH(f,x,j)))-{0}
      ==> HH(f, x, i) \<in> Pow(x) - {0}"
apply (rule HH_def_satisfies_eq [THEN ssubst])
apply (simp add: Let_def Diff_subset [THEN PowI] not_emptyI2 [THEN if_P], fast)
done

lemma f_subsets_imp_UN_HH_eq_x:
     "\<forall>z \<in> Pow(x)-{0}. f`z \<in> Pow(z)-{0}
      ==> x - (\<Union>j \<in> (LEAST i. HH(f,x,i)={x}). HH(f,x,j)) = 0"
apply (case_tac "?P \<in> {0}", fast)
apply (drule Diff_subset [THEN PowI, THEN DiffI])
apply (drule bspec, assumption)
apply (drule f_subset_imp_HH_subset)
apply (blast dest!: subst_elem [OF _ HH_Least_eq_x [symmetric]]
             elim!: mem_irrefl)
done

lemma HH_values2: "HH(f,x,i) = f`(x - (\<Union>j \<in> i. HH(f,x,j))) | HH(f,x,i)={x}"
apply (rule HH_def_satisfies_eq [THEN ssubst])
apply (simp add: Let_def Diff_subset [THEN PowI])
done

lemma HH_subset_imp_eq:
     "HH(f,x,i): Pow(x)-{0} ==> HH(f,x,i)=f`(x - (\<Union>j \<in> i. HH(f,x,j)))"
apply (rule HH_values2 [THEN disjE], assumption)
apply (fast elim!: equalityE mem_irrefl dest!: singleton_subsetD)
done

lemma f_sing_imp_HH_sing:
     "[| f \<in> (Pow(x)-{0}) -> {{z}. z \<in> x};
         a \<in> (LEAST i. HH(f,x,i)={x}) |] ==> \<exists>z \<in> x. HH(f,x,a) = {z}"
apply (drule less_Least_subset_x)
apply (frule HH_subset_imp_eq)
apply (drule apply_type)
apply (rule Diff_subset [THEN PowI, THEN DiffI])
apply (fast dest!: HH_subset_x_imp_subset_Diff_UN [THEN not_emptyI2], force)
done

lemma f_sing_lam_bij:
     "[| x - (\<Union>j \<in> (LEAST i. HH(f,x,i)={x}). HH(f,x,j)) = 0;
         f \<in> (Pow(x)-{0}) -> {{z}. z \<in> x} |]
      ==> (\<lambda>a \<in> (LEAST i. HH(f,x,i)={x}). HH(f,x,a))
          \<in> bij(LEAST i. HH(f,x,i)={x}, {{y}. y \<in> x})"
apply (unfold bij_def)
apply (fast intro!: lam_Least_HH_inj lam_surj_sing f_sing_imp_HH_sing)
done

lemma lam_singI:
     "f \<in> (\<Pi> X \<in> Pow(x)-{0}. F(X))
      ==> (\<lambda>X \<in> Pow(x)-{0}. {f`X}) \<in> (\<Pi> X \<in> Pow(x)-{0}. {{z}. z \<in> F(X)})"
by (fast del: DiffI DiffE
            intro!: lam_type singleton_eq_iff [THEN iffD2] dest: apply_type)

(*FIXME: both uses have the form ...[THEN bij_converse_bij], so
  simplification is needed!*)
lemmas bij_Least_HH_x =
    comp_bij [OF f_sing_lam_bij [OF _ lam_singI]
              lam_sing_bij [THEN bij_converse_bij]]

subsection{*The proof of AC1 ==> WO2*}

(*Establishing the existence of a bijection, namely
converse
 (converse(\<lambda>x\<in>x. {x}) O
  Lambda
   (LEAST i. HH(\<lambda>X\<in>Pow(x) - {0}. {f ` X}, x, i) = {x},
    HH(\<lambda>X\<in>Pow(x) - {0}. {f ` X}, x)))
Perhaps it could be simplified. *)

lemma bijection:
     "f \<in> (\<Pi> X \<in> Pow(x) - {0}. X)
      ==> \<exists>g. g \<in> bij(x, LEAST i. HH(\<lambda>X \<in> Pow(x)-{0}. {f`X}, x, i) = {x})"
apply (rule exI)
apply (rule bij_Least_HH_x [THEN bij_converse_bij])
apply (rule f_subsets_imp_UN_HH_eq_x)
apply (intro ballI apply_type)
apply (fast intro: lam_type apply_type del: DiffE, assumption)
apply (fast intro: Pi_weaken_type)
done

lemma AC1_WO2: "AC1 ==> WO2"
apply (unfold AC1_def WO2_def eqpoll_def)
apply (intro allI)
apply (drule_tac x = "Pow(A) - {0}" in spec)
apply (blast dest: bijection)
done

end


(* Title: thys/TuringUnComputable_H2_original.thy
   Author: Jian Xu, Xingyuan Zhang, and Christian Urban
   Modifications: Sebastiaan Joosten

   Further contributions by Franz Regensburger (FABR) 02/2022:
   * Re-ordering of sections
   * Added comments

   Editorial note FABR:
   this file was part of the theory file Uncomputable.thy
   in the original AFP entry.

 *)

subsubsection \<open>Undecidability of the General Halting Problem H, Variant 2, original version\<close>

theory TuringUnComputable_H2_original
  imports
    DitherTM
    CopyTM

begin

(*
declare adjust.simps[simp del]

declare seq_tm.simps [simp del]
declare shift.simps[simp del]
declare composable_tm.simps[simp del]
declare step.simps[simp del]
declare steps.simps[simp del]
*)

(* Cleanup the global simpset for proofs of several theorems about tm_dither *)

(*
declare adjust.simps[simp del]
*)

text \<open>The diagonal argument below shows the undecidability of a variant of the
 General Halting Problem. Implicitly, we thus show that the General Halting Function
 (the characteristic function of the Halting Problem) is not Turing computable.\<close>

(*

Turing_HaltingConditions.thy:

definition TMC_has_num_res :: "tprog0 \<Rightarrow> nat list \<Rightarrow> bool"
  where
    "TMC_has_num_res p ns \<equiv>
     \<lbrace> \<lambda>tap. tap = ([], <ns>) \<rbrace> p \<lbrace> \<lambda>tap. (\<exists>k n l. tap = (Bk \<up> k, <n::nat> @ Bk \<up> l)) \<rbrace>"

DitherTM.thy:

lemma composable_tm0_tm_dither[intro, simp]: "composable_tm0 tm_dither"
  by (auto simp: composable_tm.simps tm_dither_def)

CopyTM.thy:

lemma composable_tm0_tm_copy[intro, simp]: "composable_tm0 tm_copy"
  by (auto simp: tm_copy_def)

*)

text \<open>
  The following locale specifies that some TM \<open>H\<close> can be used to decide
  the {\em General Halting Problem} and \<open>False\<close> is going to be derived
  under this locale. Therefore, the undecidability of the  {\em  General Halting Problem}
  is established.

  The proof makes use of the TMs \<open>tm_copy\<close> and \<open>tm_dither\<close>.
\<close>

locale uncomputable =
  (* Interestingly, the detailed definition of the coding function @{text "code"} for Turing machines
     does not affect the final result. In the proof there is no need to appeal on properties of the coding function
     like e.g. injectivity! *)

fixes code :: "instr list \<Rightarrow> nat"
  (*
   * The TM "H" is the one which is assumed being able to solve the general Halting problem.
   *)
  and H :: "instr list"

  (* FABR Note:
   * The next axiom states that the Turing machine H is well-formed (composable).
   * However, this manifests a bug in the modelling of this locale!
   *
   * Due to this local axiom, we only prove that there exists no composable TM H
   * that is able to decide the Halting problem 'TMC_has_num_res M ns'
   *
   * See theories composableTMs and HaltingProblem_K for a fix by FABR.
   *
   *)

assumes h_composable[intro]: "composable_tm0 H"

  (*
   * The following two local axioms specify (claim) that the Turing Machine H
   * is able to decide the general Halting problem H2.
   *)

and h_case:
"\<And> M ns.  TMC_has_num_res M ns \<Longrightarrow> \<lbrace>(\<lambda>tap. tap = ([Bk], <(code M, ns)>))\<rbrace> H \<lbrace>(\<lambda>tap. \<exists>k. tap = (Bk \<up> k, <0::nat>))\<rbrace>"
and nh_case:
"\<And> M ns. \<not>  TMC_has_num_res M ns \<Longrightarrow> \<lbrace>(\<lambda>tap. tap = ([Bk], <(code M, ns)>))\<rbrace> H \<lbrace>(\<lambda>tap. \<exists>k. tap = (Bk \<up> k, <1::nat>))\<rbrace>"
begin

(* Assertions for the Turing Machine H *)
abbreviation (input)
  "pre_H_ass M ns \<equiv> \<lambda>tap. tap = ([Bk], <(code M, ns::nat list)>)"

abbreviation (input)
  "post_H_halt_ass \<equiv> \<lambda>tap. \<exists>k. tap = (Bk \<up> k, <1::nat>)"

abbreviation (input)
  "post_H_unhalt_ass \<equiv> \<lambda>tap. \<exists>k. tap = (Bk \<up> k, <0::nat>)"

lemma H_halt:
  assumes "\<not>  TMC_has_num_res M ns"
  shows "\<lbrace>pre_H_ass M ns\<rbrace> H \<lbrace>post_H_halt_ass\<rbrace>"
  using assms nh_case by auto

lemma H_unhalt:
  assumes " TMC_has_num_res M ns"
  shows "\<lbrace>pre_H_ass M ns\<rbrace> H \<lbrace>post_H_unhalt_ass\<rbrace>"
  using assms h_case by auto

(* The TM tcontra is the culprit that is used to derive a contradiction *)

definition
  "tcontra \<equiv> (tm_copy |+| H) |+| tm_dither"
abbreviation
  "code_tcontra \<equiv> code tcontra"

(* assume tcontra does not halt on its code *)
lemma tcontra_unhalt:
  assumes "\<not>  TMC_has_num_res tcontra [code tcontra]"
  shows "False"
proof -
  (* invariants *)
  define P1 where "P1 \<equiv> \<lambda>tap. tap = ([]::cell list, <code_tcontra>)"
  define P2 where "P2 \<equiv> \<lambda>tap. tap = ([Bk], <(code_tcontra, code_tcontra)>)"
  define P3 where "P3 \<equiv> \<lambda>tap. \<exists>k. tap = (Bk \<up> k, <1::nat>)"

(*
  \<lbrace>P1\<rbrace> tm_copy \<lbrace>P2\<rbrace>  \<lbrace>P2\<rbrace> H \<lbrace>P3\<rbrace>
  ----------------------------
     \<lbrace>P1\<rbrace> (tm_copy |+| H) \<lbrace>P3\<rbrace>     \<lbrace>P3\<rbrace> tm_dither \<lbrace>P3\<rbrace>
  ------------------------------------------------
                 \<lbrace>P1\<rbrace> tcontra \<lbrace>P3\<rbrace>
  *)

  have H_composable: "composable_tm0 (tm_copy |+| H)" by auto

(* \<lbrace>P1\<rbrace> (tm_copy |+| H) \<lbrace>P3\<rbrace> *)
  have first: "\<lbrace>P1\<rbrace> (tm_copy |+| H) \<lbrace>P3\<rbrace>"
  proof (cases rule: Hoare_plus_halt)
    case A_halt (* of tm_copy *)
    show "\<lbrace>P1\<rbrace> tm_copy \<lbrace>P2\<rbrace>" unfolding P1_def P2_def tape_of_nat_def
      by (rule tm_copy_correct)
  next
    case B_halt (* of H *)
    show "\<lbrace>P2\<rbrace> H \<lbrace>P3\<rbrace>"
      unfolding P2_def P3_def
      using H_halt[OF assms]
      by (simp add: tape_of_prod_def tape_of_list_def)
  qed (simp)

(* \<lbrace>P3\<rbrace> tm_dither \<lbrace>P3\<rbrace> *)
  have second: "\<lbrace>P3\<rbrace> tm_dither \<lbrace>P3\<rbrace>" unfolding P3_def
    by (rule tm_dither_halts)

(* \<lbrace>P1\<rbrace> tcontra \<lbrace>P3\<rbrace> *)
  have "\<lbrace>P1\<rbrace> tcontra \<lbrace>P3\<rbrace>"
    unfolding tcontra_def
    by (rule Hoare_plus_halt[OF first second H_composable])

  with assms show "False"
    unfolding P1_def P3_def
    unfolding  TMC_has_num_res_def
    unfolding Hoare_halt_def
    apply(auto) apply(rename_tac n)
    apply(drule_tac x = n in spec)
    apply(case_tac "steps0 (Suc 0, [], <code tcontra>) tcontra n")
    apply(auto simp add: tape_of_list_def)
    by (metis append_Nil2 replicate_0)
qed

(* asumme tcontra halts on its code *)
lemma tcontra_halt:
  assumes " TMC_has_num_res tcontra [code tcontra]"
  shows "False"
proof -
  (* invariants *)
  define P1 where "P1 \<equiv> \<lambda>tap. tap = ([]::cell list, <code_tcontra>)"
  define P2 where "P2 \<equiv> \<lambda>tap. tap = ([Bk], <(code_tcontra, code_tcontra)>)"
  define Q3 where "Q3 \<equiv> \<lambda>tap. \<exists>k. tap = (Bk \<up> k, <0::nat>)"

(*
  \<lbrace>P1\<rbrace> tm_copy \<lbrace>P2\<rbrace>  \<lbrace>P2\<rbrace> H \<lbrace>Q3\<rbrace>
  ----------------------------
     \<lbrace>P1\<rbrace> (tm_copy |+| H) \<lbrace>Q3\<rbrace>     \<lbrace>Q3\<rbrace> tm_dither loops
  ------------------------------------------------
               \<lbrace>P1\<rbrace> tcontra loops
  *)

  have H_composable: "composable_tm0 (tm_copy |+| H)" by auto

(* \<lbrace>P1\<rbrace> (tm_copy |+| H) \<lbrace>Q3\<rbrace> *)
  have first: "\<lbrace>P1\<rbrace> (tm_copy |+| H) \<lbrace>Q3\<rbrace>"
  proof (cases rule: Hoare_plus_halt)
    case A_halt (* of tm_copy *)
    show "\<lbrace>P1\<rbrace> tm_copy \<lbrace>P2\<rbrace>" unfolding P1_def P2_def tape_of_nat_def
      by (rule tm_copy_correct)
  next
    case B_halt (* of H *)
    then show "\<lbrace>P2\<rbrace> H \<lbrace>Q3\<rbrace>"
      unfolding P2_def Q3_def using H_unhalt[OF assms]
      by(simp add: tape_of_prod_def tape_of_list_def)
  qed (simp)

(* \<lbrace>P3\<rbrace> tm_dither loops *)
  have second: "\<lbrace>Q3\<rbrace> tm_dither \<up>" unfolding Q3_def
    by (rule tm_dither_loops)

(* \<lbrace>P1\<rbrace> tcontra loops *)
  have "\<lbrace>P1\<rbrace> tcontra \<up>"
    unfolding tcontra_def
    by (rule Hoare_plus_unhalt[OF first second H_composable])

  with assms show "False"
    unfolding P1_def
    unfolding  TMC_has_num_res_def
    unfolding Hoare_halt_def Hoare_unhalt_def
    by (auto simp add: tape_of_list_def)
qed

text \<open>
  Thus \<open>False\<close> is derivable.
\<close>

lemma false: "False"
  using tcontra_halt tcontra_unhalt
  by auto

end (* locale uncomputable *)

end


(*  Title:      HOL/Transitive_Closure.thy
    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
    Copyright   1992  University of Cambridge
*)

section \<open>Reflexive and Transitive closure of a relation\<close>

theory Transitive_Closure
  imports Relation
begin

ML_file "~~/src/Provers/trancl.ML"

text \<open>
  \<open>rtrancl\<close> is reflexive/transitive closure,
  \<open>trancl\<close> is transitive closure,
  \<open>reflcl\<close> is reflexive closure.

  These postfix operators have \<^emph>\<open>maximum priority\<close>, forcing their
  operands to be atomic.
\<close>

context notes [[inductive_internals]]
begin

inductive_set rtrancl :: "('a \<times> 'a) set \<Rightarrow> ('a \<times> 'a) set"  ("(_\<^sup>*)" [1000] 999)
  for r :: "('a \<times> 'a) set"
  where
    rtrancl_refl [intro!, Pure.intro!, simp]: "(a, a) \<in> r\<^sup>*"
  | rtrancl_into_rtrancl [Pure.intro]: "(a, b) \<in> r\<^sup>* \<Longrightarrow> (b, c) \<in> r \<Longrightarrow> (a, c) \<in> r\<^sup>*"

inductive_set trancl :: "('a \<times> 'a) set \<Rightarrow> ('a \<times> 'a) set"  ("(_\<^sup>+)" [1000] 999)
  for r :: "('a \<times> 'a) set"
  where
    r_into_trancl [intro, Pure.intro]: "(a, b) \<in> r \<Longrightarrow> (a, b) \<in> r\<^sup>+"
  | trancl_into_trancl [Pure.intro]: "(a, b) \<in> r\<^sup>+ \<Longrightarrow> (b, c) \<in> r \<Longrightarrow> (a, c) \<in> r\<^sup>+"

notation
  rtranclp  ("(_\<^sup>*\<^sup>*)" [1000] 1000) and
  tranclp  ("(_\<^sup>+\<^sup>+)" [1000] 1000)

declare
  rtrancl_def [nitpick_unfold del]
  rtranclp_def [nitpick_unfold del]
  trancl_def [nitpick_unfold del]
  tranclp_def [nitpick_unfold del]

end

abbreviation reflcl :: "('a \<times> 'a) set \<Rightarrow> ('a \<times> 'a) set"  ("(_\<^sup>=)" [1000] 999)
  where "r\<^sup>= \<equiv> r \<union> Id"

abbreviation reflclp :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> bool"  ("(_\<^sup>=\<^sup>=)" [1000] 1000)
  where "r\<^sup>=\<^sup>= \<equiv> sup r op ="

notation (ASCII)
  rtrancl  ("(_^*)" [1000] 999) and
  trancl  ("(_^+)" [1000] 999) and
  reflcl  ("(_^=)" [1000] 999) and
  rtranclp  ("(_^**)" [1000] 1000) and
  tranclp  ("(_^++)" [1000] 1000) and
  reflclp  ("(_^==)" [1000] 1000)

subsection \<open>Reflexive closure\<close>

lemma refl_reflcl[simp]: "refl (r\<^sup>=)"
  by (simp add: refl_on_def)

lemma antisym_reflcl[simp]: "antisym (r\<^sup>=) = antisym r"
  by (simp add: antisym_def)

lemma trans_reflclI[simp]: "trans r \<Longrightarrow> trans (r\<^sup>=)"
  unfolding trans_def by blast

lemma reflclp_idemp [simp]: "(P\<^sup>=\<^sup>=)\<^sup>=\<^sup>= = P\<^sup>=\<^sup>="
  by blast

subsection \<open>Reflexive-transitive closure\<close>

lemma reflcl_set_eq [pred_set_conv]: "(sup (\<lambda>x y. (x, y) \<in> r) op =) = (\<lambda>x y. (x, y) \<in> r \<union> Id)"
  by (auto simp add: fun_eq_iff)

lemma r_into_rtrancl [intro]: "\<And>p. p \<in> r \<Longrightarrow> p \<in> r\<^sup>*"
  \<comment> \<open>\<open>rtrancl\<close> of \<open>r\<close> contains \<open>r\<close>\<close>
  apply (simp only: split_tupled_all)
  apply (erule rtrancl_refl [THEN rtrancl_into_rtrancl])
  done

lemma r_into_rtranclp [intro]: "r x y \<Longrightarrow> r\<^sup>*\<^sup>* x y"
  \<comment> \<open>\<open>rtrancl\<close> of \<open>r\<close> contains \<open>r\<close>\<close>
  by (erule rtranclp.rtrancl_refl [THEN rtranclp.rtrancl_into_rtrancl])

lemma rtranclp_mono: "r \<le> s \<Longrightarrow> r\<^sup>*\<^sup>* \<le> s\<^sup>*\<^sup>*"
  \<comment> \<open>monotonicity of \<open>rtrancl\<close>\<close>
  apply (rule predicate2I)
  apply (erule rtranclp.induct)
   apply (rule_tac [2] rtranclp.rtrancl_into_rtrancl, blast+)
  done

lemma mono_rtranclp[mono]: "(\<And>a b. x a b \<longrightarrow> y a b) \<Longrightarrow> x\<^sup>*\<^sup>* a b \<longrightarrow> y\<^sup>*\<^sup>* a b"
   using rtranclp_mono[of x y] by auto

lemmas rtrancl_mono = rtranclp_mono [to_set]

theorem rtranclp_induct [consumes 1, case_names base step, induct set: rtranclp]:
  assumes a: "r\<^sup>*\<^sup>* a b"
    and cases: "P a" "\<And>y z. r\<^sup>*\<^sup>* a y \<Longrightarrow> r y z \<Longrightarrow> P y \<Longrightarrow> P z"
  shows "P b"
  using a by (induct x\<equiv>a b) (rule cases)+

lemmas rtrancl_induct [induct set: rtrancl] = rtranclp_induct [to_set]

lemmas rtranclp_induct2 =
  rtranclp_induct[of _ "(ax,ay)" "(bx,by)", split_rule, consumes 1, case_names refl step]

lemmas rtrancl_induct2 =
  rtrancl_induct[of "(ax,ay)" "(bx,by)", split_format (complete), consumes 1, case_names refl step]

lemma refl_rtrancl: "refl (r\<^sup>*)"
  unfolding refl_on_def by fast

text \<open>Transitivity of transitive closure.\<close>
lemma trans_rtrancl: "trans (r\<^sup>*)"
proof (rule transI)
  fix x y z
  assume "(x, y) \<in> r\<^sup>*"
  assume "(y, z) \<in> r\<^sup>*"
  then show "(x, z) \<in> r\<^sup>*"
  proof induct
    case base
    show "(x, y) \<in> r\<^sup>*" by fact
  next
    case (step u v)
    from \<open>(x, u) \<in> r\<^sup>*\<close> and \<open>(u, v) \<in> r\<close>
    show "(x, v) \<in> r\<^sup>*" ..
  qed
qed

lemmas rtrancl_trans = trans_rtrancl [THEN transD]

lemma rtranclp_trans:
  assumes "r\<^sup>*\<^sup>* x y"
    and "r\<^sup>*\<^sup>* y z"
  shows "r\<^sup>*\<^sup>* x z"
  using assms(2,1) by induct iprover+

lemma rtranclE [cases set: rtrancl]:
  fixes a b :: 'a
  assumes major: "(a, b) \<in> r\<^sup>*"
  obtains
    (base) "a = b"
  | (step) y where "(a, y) \<in> r\<^sup>*" and "(y, b) \<in> r"
  \<comment> \<open>elimination of \<open>rtrancl\<close> -- by induction on a special formula\<close>
  apply (subgoal_tac "a = b \<or> (\<exists>y. (a, y) \<in> r\<^sup>* \<and> (y, b) \<in> r)")
   apply (rule_tac [2] major [THEN rtrancl_induct])
    prefer 2 apply blast
   prefer 2 apply blast
  apply (erule asm_rl exE disjE conjE base step)+
  done

lemma rtrancl_Int_subset: "Id \<subseteq> s \<Longrightarrow> (r\<^sup>* \<inter> s) O r \<subseteq> s \<Longrightarrow> r\<^sup>* \<subseteq> s"
  apply (rule subsetI)
  apply auto
  apply (erule rtrancl_induct)
  apply auto
  done

lemma converse_rtranclp_into_rtranclp: "r a b \<Longrightarrow> r\<^sup>*\<^sup>* b c \<Longrightarrow> r\<^sup>*\<^sup>* a c"
  by (rule rtranclp_trans) iprover+

lemmas converse_rtrancl_into_rtrancl = converse_rtranclp_into_rtranclp [to_set]

text \<open>\<^medskip> More @{term "r\<^sup>*"} equations and inclusions.\<close>

lemma rtranclp_idemp [simp]: "(r\<^sup>*\<^sup>*)\<^sup>*\<^sup>* = r\<^sup>*\<^sup>*"
  apply (auto intro!: order_antisym)
  apply (erule rtranclp_induct)
   apply (rule rtranclp.rtrancl_refl)
  apply (blast intro: rtranclp_trans)
  done

lemmas rtrancl_idemp [simp] = rtranclp_idemp [to_set]

lemma rtrancl_idemp_self_comp [simp]: "R\<^sup>* O R\<^sup>* = R\<^sup>*"
  apply (rule set_eqI)
  apply (simp only: split_tupled_all)
  apply (blast intro: rtrancl_trans)
  done

lemma rtrancl_subset_rtrancl: "r \<subseteq> s\<^sup>* \<Longrightarrow> r\<^sup>* \<subseteq> s\<^sup>*"
  apply (drule rtrancl_mono)
  apply simp
  done

lemma rtranclp_subset: "R \<le> S \<Longrightarrow> S \<le> R\<^sup>*\<^sup>* \<Longrightarrow> S\<^sup>*\<^sup>* = R\<^sup>*\<^sup>*"
  apply (drule rtranclp_mono)
  apply (drule rtranclp_mono)
  apply simp
  done

lemmas rtrancl_subset = rtranclp_subset [to_set]

lemma rtranclp_sup_rtranclp: "(sup (R\<^sup>*\<^sup>*) (S\<^sup>*\<^sup>*))\<^sup>*\<^sup>* = (sup R S)\<^sup>*\<^sup>*"
  by (blast intro!: rtranclp_subset intro: rtranclp_mono [THEN predicate2D])

lemmas rtrancl_Un_rtrancl = rtranclp_sup_rtranclp [to_set]

lemma rtranclp_reflclp [simp]: "(R\<^sup>=\<^sup>=)\<^sup>*\<^sup>* = R\<^sup>*\<^sup>*"
  by (blast intro!: rtranclp_subset)

lemmas rtrancl_reflcl [simp] = rtranclp_reflclp [to_set]

lemma rtrancl_r_diff_Id: "(r - Id)\<^sup>* = r\<^sup>*"
  apply (rule sym)
  apply (rule rtrancl_subset)
   apply blast
  apply clarify
  apply (rename_tac a b)
  apply (case_tac "a = b")
   apply blast
  apply blast
  done

lemma rtranclp_r_diff_Id: "(inf r op \<noteq>)\<^sup>*\<^sup>* = r\<^sup>*\<^sup>*"
  apply (rule sym)
  apply (rule rtranclp_subset)
   apply blast+
  done

theorem rtranclp_converseD:
  assumes "(r\<inverse>\<inverse>)\<^sup>*\<^sup>* x y"
  shows "r\<^sup>*\<^sup>* y x"
  using assms by induct (iprover intro: rtranclp_trans dest!: conversepD)+

lemmas rtrancl_converseD = rtranclp_converseD [to_set]

theorem rtranclp_converseI:
  assumes "r\<^sup>*\<^sup>* y x"
  shows "(r\<inverse>\<inverse>)\<^sup>*\<^sup>* x y"
  using assms by induct (iprover intro: rtranclp_trans conversepI)+

lemmas rtrancl_converseI = rtranclp_converseI [to_set]

lemma rtrancl_converse: "(r^-1)\<^sup>* = (r\<^sup>*)^-1"
  by (fast dest!: rtrancl_converseD intro!: rtrancl_converseI)

lemma sym_rtrancl: "sym r \<Longrightarrow> sym (r\<^sup>*)"
  by (simp only: sym_conv_converse_eq rtrancl_converse [symmetric])

theorem converse_rtranclp_induct [consumes 1, case_names base step]:
  assumes major: "r\<^sup>*\<^sup>* a b"
    and cases: "P b" "\<And>y z. r y z \<Longrightarrow> r\<^sup>*\<^sup>* z b \<Longrightarrow> P z \<Longrightarrow> P y"
  shows "P a"
  using rtranclp_converseI [OF major]
  by induct (iprover intro: cases dest!: conversepD rtranclp_converseD)+

lemmas converse_rtrancl_induct = converse_rtranclp_induct [to_set]

lemmas converse_rtranclp_induct2 =
  converse_rtranclp_induct [of _ "(ax, ay)" "(bx, by)", split_rule, consumes 1, case_names refl step]

lemmas converse_rtrancl_induct2 =
  converse_rtrancl_induct [of "(ax, ay)" "(bx, by)", split_format (complete),
    consumes 1, case_names refl step]

lemma converse_rtranclpE [consumes 1, case_names base step]:
  assumes major: "r\<^sup>*\<^sup>* x z"
    and cases: "x = z \<Longrightarrow> P" "\<And>y. r x y \<Longrightarrow> r\<^sup>*\<^sup>* y z \<Longrightarrow> P"
  shows P
  apply (subgoal_tac "x = z \<or> (\<exists>y. r x y \<and> r\<^sup>*\<^sup>* y z)")
   apply (rule_tac [2] major [THEN converse_rtranclp_induct])
    prefer 2 apply iprover
   prefer 2 apply iprover
  apply (erule asm_rl exE disjE conjE cases)+
  done

lemmas converse_rtranclE = converse_rtranclpE [to_set]

lemmas converse_rtranclpE2 = converse_rtranclpE [of _ "(xa,xb)" "(za,zb)", split_rule]

lemmas converse_rtranclE2 = converse_rtranclE [of "(xa,xb)" "(za,zb)", split_rule]

lemma r_comp_rtrancl_eq: "r O r\<^sup>* = r\<^sup>* O r"
  by (blast elim: rtranclE converse_rtranclE
      intro: rtrancl_into_rtrancl converse_rtrancl_into_rtrancl)

lemma rtrancl_unfold: "r\<^sup>* = Id \<union> r\<^sup>* O r"
  by (auto intro: rtrancl_into_rtrancl elim: rtranclE)

lemma rtrancl_Un_separatorE:
  "(a, b) \<in> (P \<union> Q)\<^sup>* \<Longrightarrow> \<forall>x y. (a, x) \<in> P\<^sup>* \<longrightarrow> (x, y) \<in> Q \<longrightarrow> x = y \<Longrightarrow> (a, b) \<in> P\<^sup>*"
proof (induct rule: rtrancl.induct)
  case rtrancl_refl
  then show ?case by blast
next
  case rtrancl_into_rtrancl
  then show ?case by (blast intro: rtrancl_trans)
qed

lemma rtrancl_Un_separator_converseE:
  "(a, b) \<in> (P \<union> Q)\<^sup>* \<Longrightarrow> \<forall>x y. (x, b) \<in> P\<^sup>* \<longrightarrow> (y, x) \<in> Q \<longrightarrow> y = x \<Longrightarrow> (a, b) \<in> P\<^sup>*"
proof (induct rule: converse_rtrancl_induct)
  case base
  then show ?case by blast
next
  case step
  then show ?case by (blast intro: rtrancl_trans)
qed

lemma Image_closed_trancl:
  assumes "r `` X \<subseteq> X"
  shows "r\<^sup>* `` X = X"
proof -
  from assms have **: "{y. \<exists>x\<in>X. (x, y) \<in> r} \<subseteq> X"
    by auto
  have "x \<in> X" if 1: "(y, x) \<in> r\<^sup>*" and 2: "y \<in> X" for x y
  proof -
    from 1 show "x \<in> X"
    proof induct
      case base
      show ?case by (fact 2)
    next
      case step
      with ** show ?case by auto
    qed
  qed
  then show ?thesis by auto
qed

subsection \<open>Transitive closure\<close>

lemma trancl_mono: "\<And>p. p \<in> r\<^sup>+ \<Longrightarrow> r \<subseteq> s \<Longrightarrow> p \<in> s\<^sup>+"
  apply (simp add: split_tupled_all)
  apply (erule trancl.induct)
   apply (iprover dest: subsetD)+
  done

lemma r_into_trancl': "\<And>p. p \<in> r \<Longrightarrow> p \<in> r\<^sup>+"
  by (simp only: split_tupled_all) (erule r_into_trancl)

text \<open>\<^medskip> Conversions between \<open>trancl\<close> and \<open>rtrancl\<close>.\<close>

lemma tranclp_into_rtranclp: "r\<^sup>+\<^sup>+ a b \<Longrightarrow> r\<^sup>*\<^sup>* a b"
  by (erule tranclp.induct) iprover+

lemmas trancl_into_rtrancl = tranclp_into_rtranclp [to_set]

lemma rtranclp_into_tranclp1:
  assumes "r\<^sup>*\<^sup>* a b"
  shows "r b c \<Longrightarrow> r\<^sup>+\<^sup>+ a c"
  using assms by (induct arbitrary: c) iprover+

lemmas rtrancl_into_trancl1 = rtranclp_into_tranclp1 [to_set]

lemma rtranclp_into_tranclp2: "r a b \<Longrightarrow> r\<^sup>*\<^sup>* b c \<Longrightarrow> r\<^sup>+\<^sup>+ a c"
  \<comment> \<open>intro rule from \<open>r\<close> and \<open>rtrancl\<close>\<close>
  apply (erule rtranclp.cases)
   apply iprover
  apply (rule rtranclp_trans [THEN rtranclp_into_tranclp1])
    apply (simp | rule r_into_rtranclp)+
  done

lemmas rtrancl_into_trancl2 = rtranclp_into_tranclp2 [to_set]

text \<open>Nice induction rule for \<open>trancl\<close>\<close>
lemma tranclp_induct [consumes 1, case_names base step, induct pred: tranclp]:
  assumes a: "r\<^sup>+\<^sup>+ a b"
    and cases: "\<And>y. r a y \<Longrightarrow> P y" "\<And>y z. r\<^sup>+\<^sup>+ a y \<Longrightarrow> r y z \<Longrightarrow> P y \<Longrightarrow> P z"
  shows "P b"
  using a by (induct x\<equiv>a b) (iprover intro: cases)+

lemmas trancl_induct [induct set: trancl] = tranclp_induct [to_set]

lemmas tranclp_induct2 =
  tranclp_induct [of _ "(ax, ay)" "(bx, by)", split_rule, consumes 1, case_names base step]

lemmas trancl_induct2 =
  trancl_induct [of "(ax, ay)" "(bx, by)", split_format (complete),
    consumes 1, case_names base step]

lemma tranclp_trans_induct:
  assumes major: "r\<^sup>+\<^sup>+ x y"
    and cases: "\<And>x y. r x y \<Longrightarrow> P x y" "\<And>x y z. r\<^sup>+\<^sup>+ x y \<Longrightarrow> P x y \<Longrightarrow> r\<^sup>+\<^sup>+ y z \<Longrightarrow> P y z \<Longrightarrow> P x z"
  shows "P x y"
  \<comment> \<open>Another induction rule for trancl, incorporating transitivity\<close>
  by (iprover intro: major [THEN tranclp_induct] cases)

lemmas trancl_trans_induct = tranclp_trans_induct [to_set]

lemma tranclE [cases set: trancl]:
  assumes "(a, b) \<in> r\<^sup>+"
  obtains
    (base) "(a, b) \<in> r"
  | (step) c where "(a, c) \<in> r\<^sup>+" and "(c, b) \<in> r"
  using assms by cases simp_all

lemma trancl_Int_subset: "r \<subseteq> s \<Longrightarrow> (r\<^sup>+ \<inter> s) O r \<subseteq> s \<Longrightarrow> r\<^sup>+ \<subseteq> s"
  apply (rule subsetI)
  apply auto
  apply (erule trancl_induct)
   apply auto
  done

lemma trancl_unfold: "r\<^sup>+ = r \<union> r\<^sup>+ O r"
  by (auto intro: trancl_into_trancl elim: tranclE)

text \<open>Transitivity of @{term "r\<^sup>+"}\<close>
lemma trans_trancl [simp]: "trans (r\<^sup>+)"
proof (rule transI)
  fix x y z
  assume "(x, y) \<in> r\<^sup>+"
  assume "(y, z) \<in> r\<^sup>+"
  then show "(x, z) \<in> r\<^sup>+"
  proof induct
    case (base u)
    from \<open>(x, y) \<in> r\<^sup>+\<close> and \<open>(y, u) \<in> r\<close>
    show "(x, u) \<in> r\<^sup>+" ..
  next
    case (step u v)
    from \<open>(x, u) \<in> r\<^sup>+\<close> and \<open>(u, v) \<in> r\<close>
    show "(x, v) \<in> r\<^sup>+" ..
  qed
qed

lemmas trancl_trans = trans_trancl [THEN transD]

lemma tranclp_trans:
  assumes "r\<^sup>+\<^sup>+ x y"
    and "r\<^sup>+\<^sup>+ y z"
  shows "r\<^sup>+\<^sup>+ x z"
  using assms(2,1) by induct iprover+

lemma trancl_id [simp]: "trans r \<Longrightarrow> r\<^sup>+ = r"
  apply auto
  apply (erule trancl_induct)
   apply assumption
  apply (unfold trans_def)
  apply blast
  done

lemma rtranclp_tranclp_tranclp:
  assumes "r\<^sup>*\<^sup>* x y"
  shows "\<And>z. r\<^sup>+\<^sup>+ y z \<Longrightarrow> r\<^sup>+\<^sup>+ x z"
  using assms by induct (iprover intro: tranclp_trans)+

lemmas rtrancl_trancl_trancl = rtranclp_tranclp_tranclp [to_set]

lemma tranclp_into_tranclp2: "r a b \<Longrightarrow> r\<^sup>+\<^sup>+ b c \<Longrightarrow> r\<^sup>+\<^sup>+ a c"
  by (erule tranclp_trans [OF tranclp.r_into_trancl])

lemmas trancl_into_trancl2 = tranclp_into_tranclp2 [to_set]

lemma tranclp_converseI: "(r\<^sup>+\<^sup>+)\<inverse>\<inverse> x y \<Longrightarrow> (r\<inverse>\<inverse>)\<^sup>+\<^sup>+ x y"
  apply (drule conversepD)
  apply (erule tranclp_induct)
   apply (iprover intro: conversepI tranclp_trans)+
  done

lemmas trancl_converseI = tranclp_converseI [to_set]

lemma tranclp_converseD: "(r\<inverse>\<inverse>)\<^sup>+\<^sup>+ x y \<Longrightarrow> (r\<^sup>+\<^sup>+)\<inverse>\<inverse> x y"
  apply (rule conversepI)
  apply (erule tranclp_induct)
   apply (iprover dest: conversepD intro: tranclp_trans)+
  done

lemmas trancl_converseD = tranclp_converseD [to_set]

lemma tranclp_converse: "(r\<inverse>\<inverse>)\<^sup>+\<^sup>+ = (r\<^sup>+\<^sup>+)\<inverse>\<inverse>"
  by (fastforce simp add: fun_eq_iff intro!: tranclp_converseI dest!: tranclp_converseD)

lemmas trancl_converse = tranclp_converse [to_set]

lemma sym_trancl: "sym r \<Longrightarrow> sym (r\<^sup>+)"
  by (simp only: sym_conv_converse_eq trancl_converse [symmetric])

lemma converse_tranclp_induct [consumes 1, case_names base step]:
  assumes major: "r\<^sup>+\<^sup>+ a b"
    and cases: "\<And>y. r y b \<Longrightarrow> P y" "\<And>y z. r y z \<Longrightarrow> r\<^sup>+\<^sup>+ z b \<Longrightarrow> P z \<Longrightarrow> P y"
  shows "P a"
  apply (rule tranclp_induct [OF tranclp_converseI, OF conversepI, OF major])
   apply (rule cases)
   apply (erule conversepD)
  apply (blast intro: assms dest!: tranclp_converseD)
  done

lemmas converse_trancl_induct = converse_tranclp_induct [to_set]

lemma tranclpD: "R\<^sup>+\<^sup>+ x y \<Longrightarrow> \<exists>z. R x z \<and> R\<^sup>*\<^sup>* z y"
  apply (erule converse_tranclp_induct)
   apply auto
  apply (blast intro: rtranclp_trans)
  done

lemmas tranclD = tranclpD [to_set]

lemma converse_tranclpE:
  assumes major: "tranclp r x z"
    and base: "r x z \<Longrightarrow> P"
    and step: "\<And>y. r x y \<Longrightarrow> tranclp r y z \<Longrightarrow> P"
  shows P
proof -
  from tranclpD [OF major] obtain y where "r x y" and "rtranclp r y z"
    by iprover
  from this(2) show P
  proof (cases rule: rtranclp.cases)
    case rtrancl_refl
    with \<open>r x y\<close> base show P
      by iprover
  next
    case rtrancl_into_rtrancl
    from this have "tranclp r y z"
      by (iprover intro: rtranclp_into_tranclp1)
    with \<open>r x y\<close> step show P
      by iprover
  qed
qed

lemmas converse_tranclE = converse_tranclpE [to_set]

lemma tranclD2: "(x, y) \<in> R\<^sup>+ \<Longrightarrow> \<exists>z. (x, z) \<in> R\<^sup>* \<and> (z, y) \<in> R"
  by (blast elim: tranclE intro: trancl_into_rtrancl)

lemma irrefl_tranclI: "r\<inverse> \<inter> r\<^sup>* = {} \<Longrightarrow> (x, x) \<notin> r\<^sup>+"
  by (blast elim: tranclE dest: trancl_into_rtrancl)

lemma irrefl_trancl_rD: "\<forall>x. (x, x) \<notin> r\<^sup>+ \<Longrightarrow> (x, y) \<in> r \<Longrightarrow> x \<noteq> y"
  by (blast dest: r_into_trancl)

lemma trancl_subset_Sigma_aux: "(a, b) \<in> r\<^sup>* \<Longrightarrow> r \<subseteq> A \<times> A \<Longrightarrow> a = b \<or> a \<in> A"
  by (induct rule: rtrancl_induct) auto

lemma trancl_subset_Sigma: "r \<subseteq> A \<times> A \<Longrightarrow> r\<^sup>+ \<subseteq> A \<times> A"
  apply (rule subsetI)
  apply (simp only: split_tupled_all)
  apply (erule tranclE)
   apply (blast dest!: trancl_into_rtrancl trancl_subset_Sigma_aux)+
  done

lemma reflclp_tranclp [simp]: "(r\<^sup>+\<^sup>+)\<^sup>=\<^sup>= = r\<^sup>*\<^sup>*"
  apply (safe intro!: order_antisym)
   apply (erule tranclp_into_rtranclp)
  apply (blast elim: rtranclp.cases dest: rtranclp_into_tranclp1)
  done

lemmas reflcl_trancl [simp] = reflclp_tranclp [to_set]

lemma trancl_reflcl [simp]: "(r\<^sup>=)\<^sup>+ = r\<^sup>*"
  apply safe
   apply (drule trancl_into_rtrancl, simp)
  apply (erule rtranclE, safe)
   apply (rule r_into_trancl, simp)
  apply (rule rtrancl_into_trancl1)
   apply (erule rtrancl_reflcl [THEN equalityD2, THEN subsetD], fast)
  done

lemma rtrancl_trancl_reflcl [code]: "r\<^sup>* = (r\<^sup>+)\<^sup>="
  by simp

lemma trancl_empty [simp]: "{}\<^sup>+ = {}"
  by (auto elim: trancl_induct)

lemma rtrancl_empty [simp]: "{}\<^sup>* = Id"
  by (rule subst [OF reflcl_trancl]) simp

lemma rtranclpD: "R\<^sup>*\<^sup>* a b \<Longrightarrow> a = b \<or> a \<noteq> b \<and> R\<^sup>+\<^sup>+ a b"
  by (force simp add: reflclp_tranclp [symmetric] simp del: reflclp_tranclp)

lemmas rtranclD = rtranclpD [to_set]

lemma rtrancl_eq_or_trancl: "(x,y) \<in> R\<^sup>* \<longleftrightarrow> x = y \<or> x \<noteq> y \<and> (x, y) \<in> R\<^sup>+"
  by (fast elim: trancl_into_rtrancl dest: rtranclD)

lemma trancl_unfold_right: "r\<^sup>+ = r\<^sup>* O r"
  by (auto dest: tranclD2 intro: rtrancl_into_trancl1)

lemma trancl_unfold_left: "r\<^sup>+ = r O r\<^sup>*"
  by (auto dest: tranclD intro: rtrancl_into_trancl2)

lemma trancl_insert: "(insert (y, x) r)\<^sup>+ = r\<^sup>+ \<union> {(a, b). (a, y) \<in> r\<^sup>* \<and> (x, b) \<in> r\<^sup>*}"
  \<comment> \<open>primitive recursion for \<open>trancl\<close> over finite relations\<close>
  apply (rule equalityI)
   apply (rule subsetI)
   apply (simp only: split_tupled_all)
   apply (erule trancl_induct, blast)
   apply (blast intro: rtrancl_into_trancl1 trancl_into_rtrancl trancl_trans)
  apply (rule subsetI)
  apply (blast intro: trancl_mono rtrancl_mono
      [THEN [2] rev_subsetD] rtrancl_trancl_trancl rtrancl_into_trancl2)
  done

lemma trancl_insert2:
  "(insert (a, b) r)\<^sup>+ = r\<^sup>+ \<union> {(x, y). ((x, a) \<in> r\<^sup>+ \<or> x = a) \<and> ((b, y) \<in> r\<^sup>+ \<or> y = b)}"
  by (auto simp add: trancl_insert rtrancl_eq_or_trancl)

lemma rtrancl_insert: "(insert (a,b) r)\<^sup>* = r\<^sup>* \<union> {(x, y). (x, a) \<in> r\<^sup>* \<and> (b, y) \<in> r\<^sup>*}"
  using trancl_insert[of a b r]
  by (simp add: rtrancl_trancl_reflcl del: reflcl_trancl) blast

text \<open>Simplifying nested closures\<close>

lemma rtrancl_trancl_absorb[simp]: "(R\<^sup>*)\<^sup>+ = R\<^sup>*"
  by (simp add: trans_rtrancl)

lemma trancl_rtrancl_absorb[simp]: "(R\<^sup>+)\<^sup>* = R\<^sup>*"
  by (subst reflcl_trancl[symmetric]) simp

lemma rtrancl_reflcl_absorb[simp]: "(R\<^sup>*)\<^sup>= = R\<^sup>*"
  by auto

text \<open>\<open>Domain\<close> and \<open>Range\<close>\<close>

lemma Domain_rtrancl [simp]: "Domain (R\<^sup>*) = UNIV"
  by blast

lemma Range_rtrancl [simp]: "Range (R\<^sup>*) = UNIV"
  by blast

lemma rtrancl_Un_subset: "(R\<^sup>* \<union> S\<^sup>*) \<subseteq> (R \<union> S)\<^sup>*"
  by (rule rtrancl_Un_rtrancl [THEN subst]) fast

lemma in_rtrancl_UnI: "x \<in> R\<^sup>* \<or> x \<in> S\<^sup>* \<Longrightarrow> x \<in> (R \<union> S)\<^sup>*"
  by (blast intro: subsetD [OF rtrancl_Un_subset])

lemma trancl_domain [simp]: "Domain (r\<^sup>+) = Domain r"
  by (unfold Domain_unfold) (blast dest: tranclD)

lemma trancl_range [simp]: "Range (r\<^sup>+) = Range r"
  unfolding Domain_converse [symmetric] by (simp add: trancl_converse [symmetric])

lemma Not_Domain_rtrancl: "x \<notin> Domain R \<Longrightarrow> (x, y) \<in> R\<^sup>* \<longleftrightarrow> x = y"
  apply auto
  apply (erule rev_mp)
  apply (erule rtrancl_induct)
   apply auto
  done

lemma trancl_subset_Field2: "r\<^sup>+ \<subseteq> Field r \<times> Field r"
  apply clarify
  apply (erule trancl_induct)
   apply (auto simp add: Field_def)
  done

lemma finite_trancl[simp]: "finite (r\<^sup>+) = finite r"
  apply auto
   prefer 2
   apply (rule trancl_subset_Field2 [THEN finite_subset])
   apply (rule finite_SigmaI)
    prefer 3
    apply (blast intro: r_into_trancl' finite_subset)
   apply (auto simp add: finite_Field)
  done

text \<open>More about converse \<open>rtrancl\<close> and \<open>trancl\<close>, should
  be merged with main body.\<close>

lemma single_valued_confluent:
  "single_valued r \<Longrightarrow> (x, y) \<in> r\<^sup>* \<Longrightarrow> (x, z) \<in> r\<^sup>* \<Longrightarrow> (y, z) \<in> r\<^sup>* \<or> (z, y) \<in> r\<^sup>*"
  apply (erule rtrancl_induct)
   apply simp
  apply (erule disjE)
   apply (blast elim:converse_rtranclE dest:single_valuedD)
  apply (blast intro:rtrancl_trans)
  done

lemma r_r_into_trancl: "(a, b) \<in> R \<Longrightarrow> (b, c) \<in> R \<Longrightarrow> (a, c) \<in> R\<^sup>+"
  by (fast intro: trancl_trans)

lemma trancl_into_trancl: "(a, b) \<in> r\<^sup>+ \<Longrightarrow> (b, c) \<in> r \<Longrightarrow> (a, c) \<in> r\<^sup>+"
  by (induct rule: trancl_induct) (fast intro: r_r_into_trancl trancl_trans)+

lemma tranclp_rtranclp_tranclp: "r\<^sup>+\<^sup>+ a b \<Longrightarrow> r\<^sup>*\<^sup>* b c \<Longrightarrow> r\<^sup>+\<^sup>+ a c"
  apply (drule tranclpD)
  apply (elim exE conjE)
  apply (drule rtranclp_trans, assumption)
  apply (drule (2) rtranclp_into_tranclp2)
  done

lemmas trancl_rtrancl_trancl = tranclp_rtranclp_tranclp [to_set]

lemmas transitive_closure_trans [trans] =
  r_r_into_trancl trancl_trans rtrancl_trans
  trancl.trancl_into_trancl trancl_into_trancl2
  rtrancl.rtrancl_into_rtrancl converse_rtrancl_into_rtrancl
  rtrancl_trancl_trancl trancl_rtrancl_trancl

lemmas transitive_closurep_trans' [trans] =
  tranclp_trans rtranclp_trans
  tranclp.trancl_into_trancl tranclp_into_tranclp2
  rtranclp.rtrancl_into_rtrancl converse_rtranclp_into_rtranclp
  rtranclp_tranclp_tranclp tranclp_rtranclp_tranclp

declare trancl_into_rtrancl [elim]

subsection \<open>The power operation on relations\<close>

text \<open>\<open>R ^^ n = R O \<dots> O R\<close>, the n-fold composition of \<open>R\<close>\<close>

overloading
  relpow \<equiv> "compow :: nat \<Rightarrow> ('a \<times> 'a) set \<Rightarrow> ('a \<times> 'a) set"
  relpowp \<equiv> "compow :: nat \<Rightarrow> ('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> ('a \<Rightarrow> 'a \<Rightarrow> bool)"
begin

primrec relpow :: "nat \<Rightarrow> ('a \<times> 'a) set \<Rightarrow> ('a \<times> 'a) set"
  where
    "relpow 0 R = Id"
  | "relpow (Suc n) R = (R ^^ n) O R"

primrec relpowp :: "nat \<Rightarrow> ('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> ('a \<Rightarrow> 'a \<Rightarrow> bool)"
  where
    "relpowp 0 R = HOL.eq"
  | "relpowp (Suc n) R = (R ^^ n) OO R"

end

lemma relpowp_relpow_eq [pred_set_conv]:
  "(\<lambda>x y. (x, y) \<in> R) ^^ n = (\<lambda>x y. (x, y) \<in> R ^^ n)" for R :: "'a rel"
  by (induct n) (simp_all add: relcompp_relcomp_eq)

text \<open>For code generation:\<close>

definition relpow :: "nat \<Rightarrow> ('a \<times> 'a) set \<Rightarrow> ('a \<times> 'a) set"
  where relpow_code_def [code_abbrev]: "relpow = compow"

definition relpowp :: "nat \<Rightarrow> ('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> ('a \<Rightarrow> 'a \<Rightarrow> bool)"
  where relpowp_code_def [code_abbrev]: "relpowp = compow"

lemma [code]:
  "relpowp (Suc n) R = (R ^^ n) OO R"
  "relpowp 0 R = HOL.eq"
  by (simp_all add: relpowp_code_def)

hide_const (open) relpow
hide_const (open) relpowp

lemma relpow_1 [simp]: "R ^^ 1 = R"
  for R :: "('a \<times> 'a) set"
  by simp

lemma relpowp_1 [simp]: "P ^^ 1 = P"
  for P :: "'a \<Rightarrow> 'a \<Rightarrow> bool"
  by (fact relpow_1 [to_pred])

lemma relpow_0_I: "(x, x) \<in> R ^^ 0"
  by simp

lemma relpowp_0_I: "(P ^^ 0) x x"
  by (fact relpow_0_I [to_pred])

lemma relpow_Suc_I: "(x, y) \<in>  R ^^ n \<Longrightarrow> (y, z) \<in> R \<Longrightarrow> (x, z) \<in> R ^^ Suc n"
  by auto

lemma relpowp_Suc_I: "(P ^^ n) x y \<Longrightarrow> P y z \<Longrightarrow> (P ^^ Suc n) x z"
  by (fact relpow_Suc_I [to_pred])

lemma relpow_Suc_I2: "(x, y) \<in> R \<Longrightarrow> (y, z) \<in> R ^^ n \<Longrightarrow> (x, z) \<in> R ^^ Suc n"
  by (induct n arbitrary: z) (simp, fastforce)

lemma relpowp_Suc_I2: "P x y \<Longrightarrow> (P ^^ n) y z \<Longrightarrow> (P ^^ Suc n) x z"
  by (fact relpow_Suc_I2 [to_pred])

lemma relpow_0_E: "(x, y) \<in> R ^^ 0 \<Longrightarrow> (x = y \<Longrightarrow> P) \<Longrightarrow> P"
  by simp

lemma relpowp_0_E: "(P ^^ 0) x y \<Longrightarrow> (x = y \<Longrightarrow> Q) \<Longrightarrow> Q"
  by (fact relpow_0_E [to_pred])

lemma relpow_Suc_E: "(x, z) \<in> R ^^ Suc n \<Longrightarrow> (\<And>y. (x, y) \<in> R ^^ n \<Longrightarrow> (y, z) \<in> R \<Longrightarrow> P) \<Longrightarrow> P"
  by auto

lemma relpowp_Suc_E: "(P ^^ Suc n) x z \<Longrightarrow> (\<And>y. (P ^^ n) x y \<Longrightarrow> P y z \<Longrightarrow> Q) \<Longrightarrow> Q"
  by (fact relpow_Suc_E [to_pred])

lemma relpow_E:
  "(x, z) \<in>  R ^^ n \<Longrightarrow>
    (n = 0 \<Longrightarrow> x = z \<Longrightarrow> P) \<Longrightarrow>
    (\<And>y m. n = Suc m \<Longrightarrow> (x, y) \<in>  R ^^ m \<Longrightarrow> (y, z) \<in> R \<Longrightarrow> P) \<Longrightarrow> P"
  by (cases n) auto

lemma relpowp_E:
  "(P ^^ n) x z \<Longrightarrow>
    (n = 0 \<Longrightarrow> x = z \<Longrightarrow> Q) \<Longrightarrow>
    (\<And>y m. n = Suc m \<Longrightarrow> (P ^^ m) x y \<Longrightarrow> P y z \<Longrightarrow> Q) \<Longrightarrow> Q"
  by (fact relpow_E [to_pred])

lemma relpow_Suc_D2: "(x, z) \<in> R ^^ Suc n \<Longrightarrow> (\<exists>y. (x, y) \<in> R \<and> (y, z) \<in> R ^^ n)"
  by (induct n arbitrary: x z)
    (blast intro: relpow_0_I relpow_Suc_I elim: relpow_0_E relpow_Suc_E)+

lemma relpowp_Suc_D2: "(P ^^ Suc n) x z \<Longrightarrow> \<exists>y. P x y \<and> (P ^^ n) y z"
  by (fact relpow_Suc_D2 [to_pred])

lemma relpow_Suc_E2: "(x, z) \<in> R ^^ Suc n \<Longrightarrow> (\<And>y. (x, y) \<in> R \<Longrightarrow> (y, z) \<in> R ^^ n \<Longrightarrow> P) \<Longrightarrow> P"
  by (blast dest: relpow_Suc_D2)

lemma relpowp_Suc_E2: "(P ^^ Suc n) x z \<Longrightarrow> (\<And>y. P x y \<Longrightarrow> (P ^^ n) y z \<Longrightarrow> Q) \<Longrightarrow> Q"
  by (fact relpow_Suc_E2 [to_pred])

lemma relpow_Suc_D2': "\<forall>x y z. (x, y) \<in> R ^^ n \<and> (y, z) \<in> R \<longrightarrow> (\<exists>w. (x, w) \<in> R \<and> (w, z) \<in> R ^^ n)"
  by (induct n) (simp_all, blast)

lemma relpowp_Suc_D2': "\<forall>x y z. (P ^^ n) x y \<and> P y z \<longrightarrow> (\<exists>w. P x w \<and> (P ^^ n) w z)"
  by (fact relpow_Suc_D2' [to_pred])

lemma relpow_E2:
  "(x, z) \<in> R ^^ n \<Longrightarrow>
    (n = 0 \<Longrightarrow> x = z \<Longrightarrow> P) \<Longrightarrow>
    (\<And>y m. n = Suc m \<Longrightarrow> (x, y) \<in> R \<Longrightarrow> (y, z) \<in> R ^^ m \<Longrightarrow> P) \<Longrightarrow> P"
  apply (cases n)
   apply simp
  apply (rename_tac nat)
  apply (cut_tac n=nat and R=R in relpow_Suc_D2')
  apply simp
  apply blast
  done

lemma relpowp_E2:
  "(P ^^ n) x z \<Longrightarrow>
    (n = 0 \<Longrightarrow> x = z \<Longrightarrow> Q) \<Longrightarrow>
    (\<And>y m. n = Suc m \<Longrightarrow> P x y \<Longrightarrow> (P ^^ m) y z \<Longrightarrow> Q) \<Longrightarrow> Q"
  by (fact relpow_E2 [to_pred])

lemma relpow_add: "R ^^ (m + n) = R^^m O R^^n"
  by (induct n) auto

lemma relpowp_add: "P ^^ (m + n) = P ^^ m OO P ^^ n"
  by (fact relpow_add [to_pred])

lemma relpow_commute: "R O R ^^ n = R ^^ n O R"
  by (induct n) (simp_all add: O_assoc [symmetric])

lemma relpowp_commute: "P OO P ^^ n = P ^^ n OO P"
  by (fact relpow_commute [to_pred])

lemma relpow_empty: "0 < n \<Longrightarrow> ({} :: ('a \<times> 'a) set) ^^ n = {}"
  by (cases n) auto

lemma relpowp_bot: "0 < n \<Longrightarrow> (\<bottom> :: 'a \<Rightarrow> 'a \<Rightarrow> bool) ^^ n = \<bottom>"
  by (fact relpow_empty [to_pred])

lemma rtrancl_imp_UN_relpow:
  assumes "p \<in> R\<^sup>*"
  shows "p \<in> (\<Union>n. R ^^ n)"
proof (cases p)
  case (Pair x y)
  with assms have "(x, y) \<in> R\<^sup>*" by simp
  then have "(x, y) \<in> (\<Union>n. R ^^ n)"
  proof induct
    case base
    show ?case by (blast intro: relpow_0_I)
  next
    case step
    then show ?case by (blast intro: relpow_Suc_I)
  qed
  with Pair show ?thesis by simp
qed

lemma rtranclp_imp_Sup_relpowp:
  assumes "(P\<^sup>*\<^sup>*) x y"
  shows "(\<Squnion>n. P ^^ n) x y"
  using assms and rtrancl_imp_UN_relpow [of "(x, y)", to_pred] by simp

lemma relpow_imp_rtrancl:
  assumes "p \<in> R ^^ n"
  shows "p \<in> R\<^sup>*"
proof (cases p)
  case (Pair x y)
  with assms have "(x, y) \<in> R ^^ n" by simp
  then have "(x, y) \<in> R\<^sup>*"
  proof (induct n arbitrary: x y)
    case 0
    then show ?case by simp
  next
    case Suc
    then show ?case
      by (blast elim: relpow_Suc_E intro: rtrancl_into_rtrancl)
  qed
  with Pair show ?thesis by simp
qed

lemma relpowp_imp_rtranclp: "(P ^^ n) x y \<Longrightarrow> (P\<^sup>*\<^sup>*) x y"
  using relpow_imp_rtrancl [of "(x, y)", to_pred] by simp

lemma rtrancl_is_UN_relpow: "R\<^sup>* = (\<Union>n. R ^^ n)"
  by (blast intro: rtrancl_imp_UN_relpow relpow_imp_rtrancl)

lemma rtranclp_is_Sup_relpowp: "P\<^sup>*\<^sup>* = (\<Squnion>n. P ^^ n)"
  using rtrancl_is_UN_relpow [to_pred, of P] by auto

lemma rtrancl_power: "p \<in> R\<^sup>* \<longleftrightarrow> (\<exists>n. p \<in> R ^^ n)"
  by (simp add: rtrancl_is_UN_relpow)

lemma rtranclp_power: "(P\<^sup>*\<^sup>*) x y \<longleftrightarrow> (\<exists>n. (P ^^ n) x y)"
  by (simp add: rtranclp_is_Sup_relpowp)

lemma trancl_power: "p \<in> R\<^sup>+ \<longleftrightarrow> (\<exists>n > 0. p \<in> R ^^ n)"
  apply (cases p)
  apply simp
  apply (rule iffI)
   apply (drule tranclD2)
   apply (clarsimp simp: rtrancl_is_UN_relpow)
   apply (rule_tac x="Suc x" in exI)
   apply (clarsimp simp: relcomp_unfold)
   apply fastforce
  apply clarsimp
  apply (case_tac n)
   apply simp
  apply clarsimp
  apply (drule relpow_imp_rtrancl)
  apply (drule rtrancl_into_trancl1)
   apply auto
  done

lemma tranclp_power: "(P\<^sup>+\<^sup>+) x y \<longleftrightarrow> (\<exists>n > 0. (P ^^ n) x y)"
  using trancl_power [to_pred, of P "(x, y)"] by simp

lemma rtrancl_imp_relpow: "p \<in> R\<^sup>* \<Longrightarrow> \<exists>n. p \<in> R ^^ n"
  by (auto dest: rtrancl_imp_UN_relpow)

lemma rtranclp_imp_relpowp: "(P\<^sup>*\<^sup>*) x y \<Longrightarrow> \<exists>n. (P ^^ n) x y"
  by (auto dest: rtranclp_imp_Sup_relpowp)

text \<open>By Sternagel/Thiemann:\<close>
lemma relpow_fun_conv: "(a, b) \<in> R ^^ n \<longleftrightarrow> (\<exists>f. f 0 = a \<and> f n = b \<and> (\<forall>i<n. (f i, f (Suc i)) \<in> R))"
proof (induct n arbitrary: b)
  case 0
  show ?case by auto
next
  case (Suc n)
  show ?case
  proof (simp add: relcomp_unfold Suc)
    show "(\<exists>y. (\<exists>f. f 0 = a \<and> f n = y \<and> (\<forall>i<n. (f i,f(Suc i)) \<in> R)) \<and> (y,b) \<in> R) \<longleftrightarrow>
      (\<exists>f. f 0 = a \<and> f(Suc n) = b \<and> (\<forall>i<Suc n. (f i, f (Suc i)) \<in> R))"
    (is "?l = ?r")
    proof
      assume ?l
      then obtain c f
        where 1: "f 0 = a"  "f n = c"  "\<And>i. i < n \<Longrightarrow> (f i, f (Suc i)) \<in> R"  "(c,b) \<in> R"
        by auto
      let ?g = "\<lambda> m. if m = Suc n then b else f m"
      show ?r by (rule exI[of _ ?g]) (simp add: 1)
    next
      assume ?r
      then obtain f where 1: "f 0 = a"  "b = f (Suc n)"  "\<And>i. i < Suc n \<Longrightarrow> (f i, f (Suc i)) \<in> R"
        by auto
      show ?l by (rule exI[of _ "f n"], rule conjI, rule exI[of _ f], insert 1, auto)
    qed
  qed
qed

lemma relpowp_fun_conv: "(P ^^ n) x y \<longleftrightarrow> (\<exists>f. f 0 = x \<and> f n = y \<and> (\<forall>i<n. P (f i) (f (Suc i))))"
  by (fact relpow_fun_conv [to_pred])

lemma relpow_finite_bounded1:
  fixes R :: "('a \<times> 'a) set"
  assumes "finite R" and "k > 0"
  shows "R^^k \<subseteq> (\<Union>n\<in>{n. 0 < n \<and> n \<le> card R}. R^^n)"
    (is "_ \<subseteq> ?r")
proof -
  have "(a, b) \<in> R^^(Suc k) \<Longrightarrow> \<exists>n. 0 < n \<and> n \<le> card R \<and> (a, b) \<in> R^^n" for a b k
  proof (induct k arbitrary: b)
    case 0
    then have "R \<noteq> {}" by auto
    with card_0_eq[OF \<open>finite R\<close>] have "card R \<ge> Suc 0" by auto
    then show ?case using 0 by force
  next
    case (Suc k)
    then obtain a' where "(a, a') \<in> R^^(Suc k)" and "(a', b) \<in> R"
      by auto
    from Suc(1)[OF \<open>(a, a') \<in> R^^(Suc k)\<close>] obtain n where "n \<le> card R" and "(a, a') \<in> R ^^ n"
      by auto
    have "(a, b) \<in> R^^(Suc n)"
      using \<open>(a, a') \<in> R^^n\<close> and \<open>(a', b)\<in> R\<close> by auto
    from \<open>n \<le> card R\<close> consider "n < card R" | "n = card R" by force
    then show ?case
    proof cases
      case 1
      then show ?thesis
        using \<open>(a, b) \<in> R^^(Suc n)\<close> Suc_leI[OF \<open>n < card R\<close>] by blast
    next
      case 2
      from \<open>(a, b) \<in> R ^^ (Suc n)\<close> [unfolded relpow_fun_conv]
      obtain f where "f 0 = a" and "f (Suc n) = b"
        and steps: "\<And>i. i \<le> n \<Longrightarrow> (f i, f (Suc i)) \<in> R" by auto
      let ?p = "\<lambda>i. (f i, f(Suc i))"
      let ?N = "{i. i \<le> n}"
      have "?p ` ?N \<subseteq> R"
        using steps by auto
      from card_mono[OF assms(1) this] have "card (?p ` ?N) \<le> card R" .
      also have "\<dots> < card ?N"
        using \<open>n = card R\<close> by simp
      finally have "\<not> inj_on ?p ?N"
        by (rule pigeonhole)
      then obtain i j where i: "i \<le> n" and j: "j \<le> n" and ij: "i \<noteq> j" and pij: "?p i = ?p j"
        by (auto simp: inj_on_def)
      let ?i = "min i j"
      let ?j = "max i j"
      have i: "?i \<le> n" and j: "?j \<le> n" and pij: "?p ?i = ?p ?j" and ij: "?i < ?j"
        using i j ij pij unfolding min_def max_def by auto
      from i j pij ij obtain i j where i: "i \<le> n" and j: "j \<le> n" and ij: "i < j"
        and pij: "?p i = ?p j"
        by blast
      let ?g = "\<lambda>l. if l \<le> i then f l else f (l + (j - i))"
      let ?n = "Suc (n - (j - i))"
      have abl: "(a, b) \<in> R ^^ ?n"
        unfolding relpow_fun_conv
      proof (rule exI[of _ ?g], intro conjI impI allI)
        show "?g ?n = b"
          using \<open>f(Suc n) = b\<close> j ij by auto
      next
        fix k
        assume "k < ?n"
        show "(?g k, ?g (Suc k)) \<in> R"
        proof (cases "k < i")
          case True
          with i have "k \<le> n"
            by auto
          from steps[OF this] show ?thesis
            using True by simp
        next
          case False
          then have "i \<le> k" by auto
          show ?thesis
          proof (cases "k = i")
            case True
            then show ?thesis
              using ij pij steps[OF i] by simp
          next
            case False
            with \<open>i \<le> k\<close> have "i < k" by auto
            then have small: "k + (j - i) \<le> n"
              using \<open>k<?n\<close> by arith
            show ?thesis
              using steps[OF small] \<open>i<k\<close> by auto
          qed
        qed
      qed (simp add: \<open>f 0 = a\<close>)
      moreover have "?n \<le> n"
        using i j ij by arith
      ultimately show ?thesis
        using \<open>n = card R\<close> by blast
    qed
  qed
  then show ?thesis
    using gr0_implies_Suc[OF \<open>k > 0\<close>] by auto
qed

lemma relpow_finite_bounded:
  fixes R :: "('a \<times> 'a) set"
  assumes "finite R"
  shows "R^^k \<subseteq> (UN n:{n. n \<le> card R}. R^^n)"
  apply (cases k)
   apply force
  apply (use relpow_finite_bounded1[OF assms, of k] in auto)
  done

lemma rtrancl_finite_eq_relpow: "finite R \<Longrightarrow> R\<^sup>* = (\<Union>n\<in>{n. n \<le> card R}. R^^n)"
  by (fastforce simp: rtrancl_power dest: relpow_finite_bounded)

lemma trancl_finite_eq_relpow: "finite R \<Longrightarrow> R\<^sup>+ = (\<Union>n\<in>{n. 0 < n \<and> n \<le> card R}. R^^n)"
  apply (auto simp: trancl_power)
  apply (auto dest: relpow_finite_bounded1)
  done

lemma finite_relcomp[simp,intro]:
  assumes "finite R" and "finite S"
  shows "finite (R O S)"
proof-
  have "R O S = (\<Union>(x, y)\<in>R. \<Union>(u, v)\<in>S. if u = y then {(x, v)} else {})"
    by (force simp add: split_def image_constant_conv split: if_splits)
  then show ?thesis
    using assms by clarsimp
qed

lemma finite_relpow [simp, intro]:
  fixes R :: "('a \<times> 'a) set"
  assumes "finite R"
  shows "n > 0 \<Longrightarrow> finite (R^^n)"
proof (induct n)
  case 0
  then show ?case by simp
next
  case (Suc n)
  then show ?case by (cases n) (use assms in simp_all)
qed

lemma single_valued_relpow:
  fixes R :: "('a \<times> 'a) set"
  shows "single_valued R \<Longrightarrow> single_valued (R ^^ n)"
proof (induct n arbitrary: R)
  case 0
  then show ?case by simp
next
  case (Suc n)
  show ?case
    by (rule single_valuedI)
      (use Suc in \<open>fast dest: single_valuedD elim: relpow_Suc_E\<close>)
qed

subsection \<open>Bounded transitive closure\<close>

definition ntrancl :: "nat \<Rightarrow> ('a \<times> 'a) set \<Rightarrow> ('a \<times> 'a) set"
  where "ntrancl n R = (\<Union>i\<in>{i. 0 < i \<and> i \<le> Suc n}. R ^^ i)"

lemma ntrancl_Zero [simp, code]: "ntrancl 0 R = R"
proof
  show "R \<subseteq> ntrancl 0 R"
    unfolding ntrancl_def by fastforce
  have "0 < i \<and> i \<le> Suc 0 \<longleftrightarrow> i = 1" for i
    by auto
  then show "ntrancl 0 R \<le> R"
    unfolding ntrancl_def by auto
qed

lemma ntrancl_Suc [simp]: "ntrancl (Suc n) R = ntrancl n R O (Id \<union> R)"
proof
  have "(a, b) \<in> ntrancl n R O (Id \<union> R)" if "(a, b) \<in> ntrancl (Suc n) R" for a b
  proof -
    from that obtain i where "0 < i" "i \<le> Suc (Suc n)" "(a, b) \<in> R ^^ i"
      unfolding ntrancl_def by auto
    show ?thesis
    proof (cases "i = 1")
      case True
      from this \<open>(a, b) \<in> R ^^ i\<close> show ?thesis
        by (auto simp: ntrancl_def)
    next
      case False
      with \<open>0 < i\<close> obtain j where j: "i = Suc j" "0 < j"
        by (cases i) auto
      with \<open>(a, b) \<in> R ^^ i\<close> obtain c where c1: "(a, c) \<in> R ^^ j" and c2: "(c, b) \<in> R"
        by auto
      from c1 j \<open>i \<le> Suc (Suc n)\<close> have "(a, c) \<in> ntrancl n R"
        by (fastforce simp: ntrancl_def)
      with c2 show ?thesis by fastforce
    qed
  qed
  then show "ntrancl (Suc n) R \<subseteq> ntrancl n R O (Id \<union> R)"
    by auto
  show "ntrancl n R O (Id \<union> R) \<subseteq> ntrancl (Suc n) R"
    by (fastforce simp: ntrancl_def)
qed

lemma [code]: "ntrancl (Suc n) r = (let r' = ntrancl n r in r' \<union> r' O r)"
  by (auto simp: Let_def)

lemma finite_trancl_ntranl: "finite R \<Longrightarrow> trancl R = ntrancl (card R - 1) R"
  by (cases "card R") (auto simp add: trancl_finite_eq_relpow relpow_empty ntrancl_def)

subsection \<open>Acyclic relations\<close>

definition acyclic :: "('a \<times> 'a) set \<Rightarrow> bool"
  where "acyclic r \<longleftrightarrow> (\<forall>x. (x,x) \<notin> r\<^sup>+)"

abbreviation acyclicP :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> bool"
  where "acyclicP r \<equiv> acyclic {(x, y). r x y}"

lemma acyclic_irrefl [code]: "acyclic r \<longleftrightarrow> irrefl (r\<^sup>+)"
  by (simp add: acyclic_def irrefl_def)

lemma acyclicI: "\<forall>x. (x, x) \<notin> r\<^sup>+ \<Longrightarrow> acyclic r"
  by (simp add: acyclic_def)

lemma (in order) acyclicI_order:
  assumes *: "\<And>a b. (a, b) \<in> r \<Longrightarrow> f b < f a"
  shows "acyclic r"
proof -
  have "f b < f a" if "(a, b) \<in> r\<^sup>+" for a b
    using that by induct (auto intro: * less_trans)
  then show ?thesis
    by (auto intro!: acyclicI)
qed

lemma acyclic_insert [iff]: "acyclic (insert (y, x) r) \<longleftrightarrow> acyclic r \<and> (x, y) \<notin> r\<^sup>*"
  by (simp add: acyclic_def trancl_insert) (blast intro: rtrancl_trans)

lemma acyclic_converse [iff]: "acyclic (r\<inverse>) \<longleftrightarrow> acyclic r"
  by (simp add: acyclic_def trancl_converse)

lemmas acyclicP_converse [iff] = acyclic_converse [to_pred]

lemma acyclic_impl_antisym_rtrancl: "acyclic r \<Longrightarrow> antisym (r\<^sup>*)"
  by (simp add: acyclic_def antisym_def)
    (blast elim: rtranclE intro: rtrancl_into_trancl1 rtrancl_trancl_trancl)

(* Other direction:
acyclic = no loops
antisym = only self loops
Goalw [acyclic_def,antisym_def] "antisym( r\<^sup>* ) \<Longrightarrow> acyclic(r - Id)
\<Longrightarrow> antisym( r\<^sup>* ) = acyclic(r - Id)";
*)

lemma acyclic_subset: "acyclic s \<Longrightarrow> r \<subseteq> s \<Longrightarrow> acyclic r"
  unfolding acyclic_def by (blast intro: trancl_mono)

subsection \<open>Setup of transitivity reasoner\<close>

ML \<open>
structure Trancl_Tac = Trancl_Tac
(
  val r_into_trancl = @{thm trancl.r_into_trancl};
  val trancl_trans  = @{thm trancl_trans};
  val rtrancl_refl = @{thm rtrancl.rtrancl_refl};
  val r_into_rtrancl = @{thm r_into_rtrancl};
  val trancl_into_rtrancl = @{thm trancl_into_rtrancl};
  val rtrancl_trancl_trancl = @{thm rtrancl_trancl_trancl};
  val trancl_rtrancl_trancl = @{thm trancl_rtrancl_trancl};
  val rtrancl_trans = @{thm rtrancl_trans};

  fun decomp (@{const Trueprop} $ t) =
        let
          fun dec (Const (@{const_name Set.member}, _) $ (Const (@{const_name Pair}, _) $ a $ b) $ rel) =
              let
                fun decr (Const (@{const_name rtrancl}, _ ) $ r) = (r,"r*")
                  | decr (Const (@{const_name trancl}, _ ) $ r)  = (r,"r+")
                  | decr r = (r,"r");
                val (rel,r) = decr (Envir.beta_eta_contract rel);
              in SOME (a,b,rel,r) end
          | dec _ =  NONE
        in dec t end
    | decomp _ = NONE;
);

structure Tranclp_Tac = Trancl_Tac
(
  val r_into_trancl = @{thm tranclp.r_into_trancl};
  val trancl_trans  = @{thm tranclp_trans};
  val rtrancl_refl = @{thm rtranclp.rtrancl_refl};
  val r_into_rtrancl = @{thm r_into_rtranclp};
  val trancl_into_rtrancl = @{thm tranclp_into_rtranclp};
  val rtrancl_trancl_trancl = @{thm rtranclp_tranclp_tranclp};
  val trancl_rtrancl_trancl = @{thm tranclp_rtranclp_tranclp};
  val rtrancl_trans = @{thm rtranclp_trans};

  fun decomp (@{const Trueprop} $ t) =
        let
          fun dec (rel $ a $ b) =
            let
              fun decr (Const (@{const_name rtranclp}, _ ) $ r) = (r,"r*")
                | decr (Const (@{const_name tranclp}, _ ) $ r)  = (r,"r+")
                | decr r = (r,"r");
              val (rel,r) = decr rel;
            in SOME (a, b, rel, r) end
          | dec _ =  NONE
        in dec t end
    | decomp _ = NONE;
);
\<close>

setup \<open>
  map_theory_simpset (fn ctxt => ctxt
    addSolver (mk_solver "Trancl" Trancl_Tac.trancl_tac)
    addSolver (mk_solver "Rtrancl" Trancl_Tac.rtrancl_tac)
    addSolver (mk_solver "Tranclp" Tranclp_Tac.trancl_tac)
    addSolver (mk_solver "Rtranclp" Tranclp_Tac.rtrancl_tac))
\<close>

text \<open>Optional methods.\<close>

method_setup trancl =
  \<open>Scan.succeed (SIMPLE_METHOD' o Trancl_Tac.trancl_tac)\<close>
  \<open>simple transitivity reasoner\<close>
method_setup rtrancl =
  \<open>Scan.succeed (SIMPLE_METHOD' o Trancl_Tac.rtrancl_tac)\<close>
  \<open>simple transitivity reasoner\<close>
method_setup tranclp =
  \<open>Scan.succeed (SIMPLE_METHOD' o Tranclp_Tac.trancl_tac)\<close>
  \<open>simple transitivity reasoner (predicate version)\<close>
method_setup rtranclp =
  \<open>Scan.succeed (SIMPLE_METHOD' o Tranclp_Tac.rtrancl_tac)\<close>
  \<open>simple transitivity reasoner (predicate version)\<close>

end


theory T88
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. mult(meet(x, y), z) = meet(mult(x, z), mult(y, 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. undr(meet(x, y), z) = join(undr(x, z), undr(y, 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(x, join(y, z)) = join(undr(x, y), undr(x, z)))
"
nitpick[card nat=10,timeout=86400]
oops
end


(*
Authors:

  Anthony Bordg, University of Cambridge, apdb3@cam.ac.uk;
  Yijun He, University of Cambridge, yh403@cam.ac.uk
*)

theory Entanglement
imports
  Quantum
  More_Tensor
begin

section \<open>Quantum Entanglement\<close>

subsection \<open>The Product States and Entangled States of a 2-qubits System\<close>

text \<open>Below we add the condition that @{term v} and @{term w} are two-dimensional states, otherwise
@{term u} can always be represented by the tensor product of the 1-dimensional vector @{term 1} and
@{term u} itself.\<close>

definition prod_state2:: "complex Matrix.mat \<Rightarrow> bool" where
"prod_state2 u \<equiv> if state 2 u then \<exists>v w. state 1 v \<and> state 1 w \<and> u = v \<Otimes> w else undefined"

definition entangled2:: "complex Matrix.mat \<Rightarrow> bool" where
"entangled2 u \<equiv> \<not> prod_state2 u"

text \<open>The Bell states are entangled states.\<close>

lemma bell00_is_entangled2 [simp]:
  "entangled2 |\<beta>\<^sub>0\<^sub>0\<rangle>"
proof -
  have "\<forall>v w. state 1 v \<longrightarrow> state 1 w \<longrightarrow> |\<beta>\<^sub>0\<^sub>0\<rangle> \<noteq> v \<Otimes> w"
  proof((rule allI)+,(rule impI)+, rule notI)
    fix v w
    assume a0:"state 1 v" and a1:"state 1 w" and a2:"|\<beta>\<^sub>0\<^sub>0\<rangle> = v \<Otimes> w"
    have "(v $$ (0,0) * w $$ (0,0)) * (v $$ (1,0) * w $$ (1,0)) =
          (v $$ (0,0) * w $$ (1,0)) * (v $$ (1,0) * w $$ (0,0))" by simp
    then have "(v \<Otimes> w) $$ (0,0) * (v \<Otimes> w) $$ (3,0) = (v \<Otimes> w) $$ (1,0) * (v \<Otimes> w) $$ (2,0)"
      using a0 a1 by simp
    then have "|\<beta>\<^sub>0\<^sub>0\<rangle> $$ (0,0) * |\<beta>\<^sub>0\<^sub>0\<rangle> $$ (3,0) = |\<beta>\<^sub>0\<^sub>0\<rangle> $$ (1,0) * |\<beta>\<^sub>0\<^sub>0\<rangle> $$ (2,0)"
      using a2 by simp
    then have "1/ sqrt 2 * 1/sqrt 2 = 0" by simp
    thus False by simp
  qed
  thus ?thesis by(simp add: entangled2_def prod_state2_def)
qed

lemma bell01_is_entangled2 [simp]:
  "entangled2 |\<beta>\<^sub>0\<^sub>1\<rangle>"
proof -
  have "\<forall>v w. state 1 v \<longrightarrow> state 1 w \<longrightarrow> |\<beta>\<^sub>0\<^sub>1\<rangle> \<noteq> v \<Otimes> w"
  proof((rule allI)+,(rule impI)+, rule notI)
    fix v w
    assume a0:"state 1 v" and a1:"state 1 w" and a2:"|\<beta>\<^sub>0\<^sub>1\<rangle> = v \<Otimes> w"
    have "(v $$ (0,0) * w $$ (1,0)) * (v $$ (1,0) * w $$ (0,0)) =
          (v $$ (0,0) * w $$ (0,0)) * (v $$ (1,0) * w $$ (1,0))" by simp
    then have "(v \<Otimes> w) $$ (1,0) * (v \<Otimes> w) $$ (2,0) = (v \<Otimes> w) $$ (0,0) * (v \<Otimes> w) $$ (3,0)"
      using a0 a1 by simp
    then have "|\<beta>\<^sub>0\<^sub>1\<rangle> $$ (1,0) * |\<beta>\<^sub>0\<^sub>1\<rangle> $$ (2,0) = |\<beta>\<^sub>0\<^sub>1\<rangle> $$ (0,0) * |\<beta>\<^sub>0\<^sub>1\<rangle> $$ (3,0)"
      using a2 by simp
    then have "1/sqrt 2 * 1/sqrt 2 = 0"
      using bell01_index by simp
    thus False by simp
  qed
  thus ?thesis by(simp add: entangled2_def prod_state2_def)
qed

lemma bell10_is_entangled2 [simp]:
  "entangled2 |\<beta>\<^sub>1\<^sub>0\<rangle>"
proof -
  have "\<forall>v w. state 1 v \<longrightarrow> state 1 w \<longrightarrow> |\<beta>\<^sub>1\<^sub>0\<rangle> \<noteq> v \<Otimes> w"
  proof((rule allI)+,(rule impI)+, rule notI)
    fix v w
    assume a0:"state 1 v" and a1:"state 1 w" and a2:"|\<beta>\<^sub>1\<^sub>0\<rangle> = v \<Otimes> w"
    have "(v $$ (0,0) * w $$ (0,0)) * (v $$ (1,0) * w $$ (1,0)) =
          (v $$ (0,0) * w $$ (1,0)) * (v $$ (1,0) * w $$ (0,0))" by simp
    then have "(v \<Otimes> w) $$ (0,0) * (v \<Otimes> w) $$ (3,0) = (v \<Otimes> w) $$ (1,0) * (v \<Otimes> w) $$ (2,0)"
      using a0 a1 by simp
    then have "|\<beta>\<^sub>1\<^sub>0\<rangle> $$ (1,0) * |\<beta>\<^sub>1\<^sub>0\<rangle> $$ (2,0) = |\<beta>\<^sub>1\<^sub>0\<rangle> $$ (0,0) * |\<beta>\<^sub>1\<^sub>0\<rangle> $$ (3,0)"
      using a2 by simp
    then have "1/sqrt 2 * 1/sqrt 2 = 0" by simp
    thus False by simp
  qed
  thus ?thesis by(simp add: entangled2_def prod_state2_def)
qed

lemma bell11_is_entangled2 [simp]:
  "entangled2 |\<beta>\<^sub>1\<^sub>1\<rangle>"
proof -
  have "\<forall>v w. state 1 v \<longrightarrow> state 1 w \<longrightarrow> |\<beta>\<^sub>1\<^sub>1\<rangle> \<noteq> v \<Otimes> w"
  proof((rule allI)+,(rule impI)+, rule notI)
    fix v w
    assume a0:"state 1 v" and a1:"state 1 w" and a2:"|\<beta>\<^sub>1\<^sub>1\<rangle> = v \<Otimes> w"
    have "(v $$ (0,0) * w $$ (1,0)) * (v $$ (1,0) * w $$ (0,0)) =
          (v $$ (0,0) * w $$ (0,0)) * (v $$ (1,0) * w $$ (1,0))" by simp
    then have "(v \<Otimes> w) $$ (1,0) * (v \<Otimes> w) $$ (2,0) = (v \<Otimes> w) $$ (0,0) * (v \<Otimes> w) $$ (3,0)"
      using a0 a1 by simp
    then have "|\<beta>\<^sub>1\<^sub>1\<rangle> $$ (1,0) * |\<beta>\<^sub>1\<^sub>1\<rangle> $$ (2,0) = |\<beta>\<^sub>1\<^sub>1\<rangle> $$ (0,0) * |\<beta>\<^sub>1\<^sub>1\<rangle> $$ (3,0)"
      using a2 by simp
    then have "1/sqrt 2 * 1/sqrt 2 = 0"
      using bell_11_index by simp
    thus False by simp
  qed
  thus ?thesis by(simp add: entangled2_def prod_state2_def)
qed

text \<open>
An entangled state is a state that cannot be broken down as the tensor product of smaller states.
\<close>

definition prod_state:: "nat \<Rightarrow> complex Matrix.mat \<Rightarrow> bool" where
"prod_state m u \<equiv> if state m u then \<exists>n p::nat.\<exists>v w. state n v \<and> state p w \<and>
  n < m \<and> p < m \<and>  u = v \<Otimes> w else undefined"

definition entangled:: "nat \<Rightarrow> complex Matrix.mat \<Rightarrow> bool" where
"entangled n v \<equiv> \<not> (prod_state n v)"

(* To do: as an exercise prove the equivalence between entangled2 and (entangled 2). *)

lemma sanity_check:
  "\<not>(entangled 2 (mat_of_cols_list 2 [[1/sqrt(2), 1/sqrt(2)]] \<Otimes> mat_of_cols_list 2 [[1/sqrt(2), 1/sqrt(2)]]))"
proof -
  define u where "u = mat_of_cols_list 2 [[1/sqrt(2), 1/sqrt(2)]]"
  then have "state 1 u"
  proof -
    have "dim_col u = 1"
      using u_def mat_of_cols_list_def by simp
    moreover have f:"dim_row u = 2"
      using u_def mat_of_cols_list_def by simp
    moreover have "\<parallel>Matrix.col u 0\<parallel> = 1"
    proof -
      have "(\<Sum>i<2. (cmod (u $$ (i, 0)))\<^sup>2) = (1/sqrt 2)\<^sup>2 + (1/sqrt 2)\<^sup>2"
        by(simp add: u_def cmod_def numeral_2_eq_2)
      then have "\<parallel>Matrix.col u 0\<parallel> = sqrt ((1/sqrt 2)\<^sup>2 + (1/sqrt 2)\<^sup>2)"
        using f by(auto simp: Matrix.col_def u_def cpx_vec_length_def)
      thus ?thesis by(simp add: power_divide)
    qed
    ultimately show ?thesis by(simp add: state_def)
  qed
  then have "state 2 (u \<Otimes> u)"
    using tensor_state by(metis one_add_one)
  thus ?thesis
    using entangled_def prod_state_def by(metis \<open>state 1 u\<close> one_less_numeral_iff semiring_norm(76) u_def)
qed

end