(*
Title: Binary Multirelations
Author: Hitoshi Furusawa, Georg Struth
Maintainer: <g.struth at sheffield.ac.uk>
*)

section \<open>Multirelations\<close>

theory Multirelations
imports C_Algebras
begin

subsection \<open>Basic Definitions\<close>

text \<open>We define a type synonym for multirelations.\<close>

type_synonym 'a mrel = "('a * ('a set)) set"

no_notation  s_prod (infixl "\<cdot>" 80)
no_notation s_id ("1\<^sub>\<sigma>")
no_notation c_prod (infixl "\<parallel>" 80)
no_notation c_id ("1\<^sub>\<pi>")

text \<open>Now we start with formalising the multirelational model. First
  we define  sequential composition and paraellel composition of multirelations, their units and
the universal multirelation as in Section 2 of the article.\<close>

definition s_prod :: "'a mrel \<Rightarrow> 'a mrel \<Rightarrow> 'a mrel" (infixl "\<cdot>" 70) where
  "R \<cdot> S = {(a,A). (\<exists>B. (a,B) \<in> R \<and> (\<exists>f. (\<forall>b \<in> B. (b,f b) \<in> S) \<and> A = \<Union>{f b |b. b \<in> B}))}"

definition s_id :: "'a mrel" ("1\<^sub>\<sigma>") where
  "1\<^sub>\<sigma> \<equiv> \<Union>a. {(a,{a})}"

definition p_prod :: "'a mrel \<Rightarrow> 'a mrel \<Rightarrow> 'a mrel"  (infixl "\<parallel>" 70) where
  "R \<parallel> S = {(a,A). (\<exists>B C. A = B \<union> C \<and> (a,B) \<in> R \<and> (a,C) \<in> S)}"

definition p_id :: "'a mrel" ("1\<^sub>\<pi>") where
  "1\<^sub>\<pi> \<equiv> \<Union>a. {(a,{})}"

definition U :: "'a mrel" where
  "U \<equiv> {(a,A) |a A. a \<in> UNIV \<and> A \<subseteq> UNIV}"

abbreviation "NC \<equiv> U - 1\<^sub>\<pi>"

text \<open>We write NC where $\overline{1_\pi}$ is written in~\<^cite>\<open>"FurusawaS15a"\<close>.\<close>

text \<open>Next we prove some basic set-theoretic properties.\<close>

lemma s_prod_im: "R \<cdot> S = {(a,A). (\<exists>B. (a,B) \<in> R \<and> (\<exists>f. (\<forall>b \<in> B. (b,f b) \<in> S) \<and> A = \<Union>((\<lambda>x. f x) ` B)))}"
  by (auto simp: s_prod_def)

lemma s_prod_iff: "(a,A) \<in> (R \<cdot> S) \<longleftrightarrow> (\<exists>B. (a,B) \<in> R \<and> (\<exists>f. (\<forall>b \<in> B. (b,f b) \<in> S) \<and> A = \<Union>((\<lambda>x. f x) ` B)))"
  by (unfold s_prod_im, auto)

lemma s_id_iff: "(a,A) \<in> 1\<^sub>\<sigma> \<longleftrightarrow> A = {a}"
  by (simp add: s_id_def)

lemma p_prod_iff: "(a,A) \<in> R \<parallel> S \<longleftrightarrow> (\<exists>B C. A = B \<union> C \<and> (a,B) \<in> R \<and> (a,C) \<in> S)"
  by (clarsimp simp add: p_prod_def)

named_theorems mr_simp
declare s_prod_im [mr_simp] p_prod_def [mr_simp] s_id_def [mr_simp] p_id_def [mr_simp] U_def [mr_simp]

subsection\<open>Multirelations and Proto-Dioids\<close>

text \<open>We can now show that multirelations form proto-trioids.
This is Proposition 5.1, and it subsumes Proposition 4.1,\<close>

interpretation mrel_proto_trioid: proto_trioid "1\<^sub>\<sigma>" "(\<cdot>)" "1\<^sub>\<pi>" "(\<parallel>)" "(\<union>)" "(\<subseteq>)" "(\<subset>)" "{}"
proof
  show "\<And>x. 1\<^sub>\<sigma> \<cdot> x = x"
    by (auto simp: mr_simp)
  show "\<And>x. x \<cdot> 1\<^sub>\<sigma> = x"
    by (auto simp add: mr_simp) (metis UN_singleton)
  show "\<And>x. 1\<^sub>\<pi> \<parallel> x = x"
    by (simp add: mr_simp)
  show "\<And>x y z. x \<parallel> y \<parallel> z = x \<parallel> (y \<parallel> z)"
    apply (rule antisym)
    apply (clarsimp simp: mr_simp Un_assoc, metis)
    by (clarsimp simp: mr_simp, metis (no_types) Un_assoc)
  show "\<And>x y. x \<parallel> y = y \<parallel> x"
    by  (auto simp: mr_simp)
  show "\<And>x y. (x \<subseteq> y) = (x \<union> y = y)"
    by blast
  show "\<And>x y. (x \<subset> y) = (x \<subseteq> y \<and> x \<noteq> y)"
    by (simp add: psubset_eq)
  show "\<And>x y z. x \<union> y \<union> z = x \<union> (y \<union> z)"
    by (simp add: Un_assoc)
  show "\<And>x y. x \<union> y = y \<union> x"
    by blast
  show "\<And>x. x \<union> x = x"
    by auto
  show "\<And>x. {} \<union> x = x"
    by blast
  show "\<And>x y z. (x \<union> y) \<cdot> z = x \<cdot> z \<union> y \<cdot> z"
    by (auto simp: mr_simp)
  show "\<And>x y z. x \<cdot> y \<union> x \<cdot> z \<subseteq> x \<cdot> (y \<union> z)"
    by (auto simp: mr_simp)
  show "\<And>x. {} \<cdot> x = {}"
    by (auto simp: mr_simp)
  show "\<And>x y z. x \<parallel> (y \<union> z) = x \<parallel> y \<union> x \<parallel> z"
    by (auto simp: mr_simp)
  show "\<And>x. x \<parallel> {} = {}"
    by (simp add: mr_simp)
qed

subsection \<open>Simple Properties\<close>

text\<open>This covers all the identities in the display before Lemma 2.1  except the two following ones.\<close>

lemma s_prod_assoc1: "(R \<cdot> S ) \<cdot> T \<subseteq> R \<cdot> (S \<cdot> T)"
  by (clarsimp simp: mr_simp, metis)

lemma seq_conc_subdistr: "(R \<parallel> S) \<cdot> T \<subseteq> (R \<cdot> T) \<parallel> (S \<cdot> T)"
  by (clarsimp simp: mr_simp UnI1 UnI2, blast)

text \<open>Next we provide some counterexamples. These do not feature in~\<^cite>\<open>"FurusawaS15a"\<close>.\<close>

lemma  "R \<cdot> {} = {}"
  nitpick
  oops

lemma "R \<cdot> (S \<union> T) = R \<cdot> S \<union> R \<cdot> T"
  apply (auto simp: s_prod_im)
  nitpick
  oops

lemma "R \<cdot> (S \<cdot> T) \<subseteq> (R \<cdot> S) \<cdot> T"
  apply (auto simp: s_prod_im)
  nitpick
  oops

lemma "(R \<parallel> R) \<cdot> T = (R \<cdot> T) \<parallel> (R \<cdot> T)"
  quickcheck
  oops

text \<open>Next we prove the distributivity and associativity laws for sequential subidentities
mentioned before Lemma 2.1\<close>

lemma subid_aux2:
assumes "R \<subseteq> 1\<^sub>\<sigma>"and "(a,A) \<in> R"
shows "A = {a}"
  using assms by (auto simp: mr_simp)

lemma s_prod_test_aux1:
assumes "S \<subseteq> 1\<^sub>\<sigma>"
and  "(a,A) \<in> R \<cdot> S"
shows "((a,A) \<in> R \<and> (\<forall>a \<in> A. (a,{a}) \<in> S))"
  using assms apply (clarsimp simp: s_prod_im)
  by (metis assms(2) mrel_proto_trioid.s_prod_idr mrel_proto_trioid.s_prod_isol singletonD subid_aux2 subset_eq)

lemma s_prod_test_aux2:
assumes "(a,A) \<in> R"
and "\<forall>a \<in> A. (a,{a}) \<in> S"
shows "(a,A) \<in> R \<cdot> S"
  using assms by (auto simp: mr_simp, fastforce)

lemma s_prod_test:
assumes "P \<subseteq> 1\<^sub>\<sigma>"
shows "(a,A) \<in> R \<cdot> P \<longleftrightarrow> (a,A) \<in> R \<and> (\<forall>a \<in> A. (a,{a}) \<in> P)"
  by (meson assms s_prod_test_aux1 s_prod_test_aux2)

lemma test_s_prod_aux1:
assumes "P \<subseteq>  1\<^sub>\<sigma>"
and "(a,A) \<in> P \<cdot> R"
shows "(a,{a}) \<in> P \<and> (a,A) \<in> R"
  by (metis assms mrel_proto_trioid.s_prod_idl s_id_iff s_prod_iff subid_aux2)

lemma test_s_prod_aux2:
assumes "(a,A) \<in> R"
and "(a,{a}) \<in> P"
shows "(a,A) \<in> P \<cdot> R"
  using assms s_prod_iff by fastforce

lemma test_s_prod:
assumes "P \<subseteq> 1\<^sub>\<sigma>"
shows "(a,A) \<in> P \<cdot> R \<longleftrightarrow> (a,{a}) \<in> P \<and> (a,A) \<in> R"
  by (meson assms test_s_prod_aux1 test_s_prod_aux2)

lemma test_assoc1:
assumes "P \<subseteq> 1\<^sub>\<sigma>"
shows "(R \<cdot> P) \<cdot> S = R \<cdot> (P \<cdot> S)"
proof (rule antisym)
  show  "(R \<cdot> P) \<cdot> S \<subseteq> R \<cdot> (P \<cdot> S)"
    by (metis s_prod_assoc1)
next
  show "R \<cdot> (P \<cdot> S) \<subseteq> (R \<cdot> P) \<cdot> S" using assms
  proof clarify
    fix a A
    assume "(a,A) \<in> R \<cdot> (P \<cdot> S)"
    hence "\<exists>B.(a,B) \<in> R \<and> (\<exists>f. (\<forall>b \<in> B. (b,f b) \<in> P \<cdot> S) \<and> A = \<Union>((\<lambda>x. f x) ` B))"
      by (clarsimp simp: mr_simp)
    hence "\<exists>B.(a,B) \<in> R \<and> (\<exists>f. (\<forall>b \<in> B. (b,{b}) \<in> P \<and> (b,f b) \<in> S) \<and> A = \<Union>((\<lambda>x. f x) ` B))"
      by (metis assms test_s_prod)
    hence "\<exists>B.(a,B) \<in> R \<and> (\<forall>b \<in> B. (b,{b}) \<in> P) \<and> (\<exists>f. (\<forall>b \<in> B. (b,f b) \<in> S) \<and> A = \<Union>((\<lambda>x. f x) ` B))"
      by auto
    hence "\<exists>B. (a,B) \<in> R \<cdot> P \<and> (\<exists>f. (\<forall>b \<in> B. (b,f b) \<in> S) \<and> A = \<Union>((\<lambda>x. f x) ` B))"
      by (metis assms s_prod_test)
    thus "(a,A) \<in> (R \<cdot> P) \<cdot> S"
      by (clarsimp simp: mr_simp)
  qed
qed

lemma test_assoc2:
assumes "P \<subseteq> 1\<^sub>\<sigma>"
shows "(P \<cdot> R) \<cdot> S = P \<cdot> (R \<cdot> S)"
proof (rule antisym)
  show "(P \<cdot> R) \<cdot> S \<subseteq>  P \<cdot> (R \<cdot> S)"
    by (metis s_prod_assoc1)
  show "P \<cdot> (R \<cdot> S) \<subseteq> (P \<cdot> R) \<cdot> S" using assms
  proof clarify
    fix a A
    assume "(a,A) \<in> P \<cdot> (R \<cdot> S)"
    hence "(a,{a}) \<in> P \<and> (a,A) \<in> R \<cdot> S"
      by (metis assms test_s_prod)
    hence "(a,{a}) \<in> P \<and> (\<exists>B. (a,B) \<in> R \<and> (\<exists>f. (\<forall>b \<in> B. (b,f b) \<in> S) \<and> A = \<Union>((\<lambda>x. f x) ` B)))"
      by (clarsimp simp: mr_simp)
    hence "\<exists>B.(a,{a}) \<in> P \<and> (a,B) \<in> R \<and> (\<exists>f. (\<forall>b \<in> B. (b,f b) \<in> S) \<and> A = \<Union>((\<lambda>x. f x) ` B))"
      by (clarsimp simp: mr_simp)
    hence "\<exists>B. (a,B) \<in> P \<cdot> R \<and> (\<exists>f. (\<forall>b \<in> B. (b,f b) \<in> S) \<and> A = \<Union>((\<lambda>x. f x) ` B))"
      by (metis assms test_s_prod)
    thus "(a,A) \<in> (P \<cdot> R) \<cdot> S"
      by (clarsimp simp: mr_simp)
  qed
qed

lemma test_assoc3:
assumes "P \<subseteq> 1\<^sub>\<sigma>"
shows "(R \<cdot> S) \<cdot> P = R \<cdot> (S \<cdot> P)"
proof (rule antisym)
  show "(R \<cdot> S) \<cdot> P \<subseteq> R \<cdot> (S \<cdot> P)"
    by (metis s_prod_assoc1)
  show "R \<cdot> (S \<cdot> P) \<subseteq> (R \<cdot> S) \<cdot> P" using assms
    proof clarify
    fix a A
    assume hyp1: "(a, A) \<in> R \<cdot> (S \<cdot> P)"
    hence "\<exists>B. (a,B) \<in> R \<and> (\<exists>f. (\<forall>b\<in>B. (b,f b) \<in> S \<cdot> P) \<and> A = \<Union>((\<lambda>x. f x) ` B))"
      by (simp add: s_prod_test s_prod_im)
    hence "\<exists>B. (a,B) \<in> R \<and> (\<exists>f. (\<forall>b\<in>B. (b,f b) \<in> S \<and> (\<forall>a\<in>f b. (a,{a}) \<in> P)) \<and> A = \<Union>((\<lambda>x. f x) ` B))"
      by (simp add: s_prod_test assms)
    hence "\<exists>B. (a,B) \<in> R \<and> (\<exists>f. (\<forall>b\<in>B. (b,f b) \<in> S) \<and> (\<forall>a\<in>\<Union>((\<lambda>x. f x) ` B). (a,{a}) \<in> P) \<and> A = \<Union>((\<lambda>x. f x) ` B))"
      by auto
    hence "\<exists>B. (a,B) \<in> R \<and> (\<exists>f. (\<forall>b\<in>B. (b,f b) \<in> S) \<and> (\<forall>a\<in>A. (a,{a}) \<in> P) \<and> A = \<Union>((\<lambda>x. f x) ` B))"
      by auto blast
    hence "(a,A) \<in> R \<cdot> S \<and> (\<forall>a\<in>A. (a,{a}) \<in> P)"
      by (auto simp: mr_simp)
    thus "(a,A) \<in> (R \<cdot> S) \<cdot> P"
      by (simp add: s_prod_test assms)
  qed
qed

lemma s_distl_test:
assumes "R \<subseteq> 1\<^sub>\<sigma>"
shows "R \<cdot> (S \<union> T) = R \<cdot> S \<union> R \<cdot> T"
  apply (clarsimp simp: mr_simp) using assms subid_aux2 by fastforce

text \<open>Next we verify Lemma 2.1.\<close>

lemma subid_par_idem:
assumes "R \<subseteq> 1\<^sub>\<sigma>"
shows "R \<parallel> R = R"
  by (rule set_eqI, clarsimp simp: mr_simp, metis Un_absorb assms subid_aux2)

lemma term_par_idem:
assumes "R \<subseteq> 1\<^sub>\<pi>"
shows "R \<parallel> R = R"
  using assms by (auto simp: mr_simp)

lemma U_par_idem: "U \<parallel> U = U"
  by (auto simp: mr_simp)

lemma nc_par_idem: "NC \<parallel> NC = NC"
  by (auto simp: mr_simp)

text \<open>Next we prove the properties of Lemma 2.2 and 3.2. First we prepare to show that multirelations form c-lattices.\<close>

text \<open>We define the domain operation on multirelations and verify the explicit definition from Section 3.\<close>

definition d :: "'a mrel \<Rightarrow> 'a mrel" where
  "d R \<equiv> {(a,{a}) |a. \<exists>B. (a,B) \<in> R}"

named_theorems mrd_simp
declare mr_simp [mrd_simp] d_def [mrd_simp]

lemma d_def_expl: "d R = (R \<cdot> 1\<^sub>\<pi>) \<parallel> 1\<^sub>\<sigma>"
  apply (simp add: mrd_simp) using set_eqI by force

interpretation mrel_pbdl_monoid: pbdl_monoid "1\<^sub>\<sigma>" "(\<cdot>)" "1\<^sub>\<pi>" "(\<parallel>)" "(\<union>)" "(\<subseteq>)" "(\<subset>)" "{}" "U" "(\<inter>)"
  by (unfold_locales, auto simp: mrd_simp)

text \<open>Here come the properties of Lemma 2.2.\<close>

lemma c1: "(R \<cdot> 1\<^sub>\<pi>) \<parallel> R = R"
  apply (rule set_eqI)
  apply (clarsimp simp: mr_simp)
  by (metis (no_types, lifting) SUP_bot SUP_bot_conv(2) sup_bot.left_neutral)

lemma t_aux: "T \<parallel> T \<subseteq> T \<Longrightarrow> (\<forall>a B C. (a,B) \<in> T \<and> (a,C) \<in> T \<Longrightarrow> (a,B \<union> C) \<in> T)"
  by (clarsimp simp: mr_simp)

lemma cl4:
assumes "T \<parallel> T \<subseteq> T"
shows "(R \<cdot> T) \<parallel> (S \<cdot> T) \<subseteq> (R \<parallel> S) \<cdot> T"
proof clarify
fix a A
  assume  "(a,A) \<in> (R \<cdot> T) \<parallel> (S \<cdot> T)"
  hence "\<exists>B C. A = B \<union> C \<and> (\<exists>D. (a,D) \<in> R \<and> (\<exists>f. (\<forall>d \<in> D. (d,f d) \<in> T) \<and> B = \<Union> ((\<lambda>x. f x) ` D))) \<and> (\<exists>E. (a,E) \<in> S \<and> (\<exists>g. (\<forall>e \<in> E. (e,g e) \<in> T) \<and> C = \<Union> ((\<lambda>x. g x)` E)))"
    by (simp add: mr_simp)
  hence "\<exists>D E. (a,D \<union> E) \<in> R \<parallel> S \<and> (\<exists>f g. (\<forall>d \<in> D. (d,f d) \<in> T) \<and> (\<forall>e \<in> E. (e,g e) \<in> T) \<and> A = (\<Union> ((\<lambda>x. f x) ` D)) \<union> (\<Union> ((\<lambda>x. g x)` E)))"
    by (auto simp: mr_simp)
  hence "\<exists>D E. (a,D \<union> E) \<in> R \<parallel> S \<and> (\<exists>f g. (\<forall>d \<in> D-E. (d,f d) \<in> T) \<and> (\<forall>e \<in> E-D. (e,g e) \<in> T) \<and> (\<forall>x \<in> D \<inter> E. (x,f x) \<in> T \<and> (x,g x) \<in> T) \<and> A = (\<Union> ((\<lambda>x. f x) ` (D-E))) \<union> (\<Union> ((\<lambda>x. g x) ` (E-D)) \<union> (\<Union> ((\<lambda>y. f y \<union> g y) ` (D \<inter> E)))))"
    by auto blast
  hence "\<exists>D E. (a,D \<union> E) \<in> R \<parallel> S \<and> (\<exists>f g. (\<forall>d \<in> D-E. (d,f d) \<in> T) \<and> (\<forall>e \<in> E-D. (e,g e) \<in> T) \<and> (\<forall>x \<in> D \<inter> E. (x,f x \<union> g x) \<in> T) \<and> A = (\<Union> ((\<lambda>x. f x) ` (D-E))) \<union> (\<Union> ((\<lambda>x. g x) ` (E-D)) \<union> (\<Union> ((\<lambda>y. f y \<union> g y) ` (D \<inter> E)))))"
    apply clarify
    apply (rule_tac x = D in exI)
    apply (rule_tac x = E in exI)
    apply clarify
    apply (rule_tac x = f in exI)
    apply (rule_tac x = g in exI)
    using assms by (auto simp: p_prod_def p_prod_iff, blast)
  hence "\<exists>D E. (a,D \<union> E) \<in> R \<parallel> S \<and> (\<exists>h. (\<forall>d \<in> D-E. (d,h d) \<in> T) \<and> (\<forall>e \<in> E-D. (e, h e) \<in> T) \<and> (\<forall>x \<in> D \<inter> E. (x, h x) \<in> T) \<and> A = (\<Union> ((\<lambda>x. h x) ` (D-E))) \<union> (\<Union> ((\<lambda>x. h x) ` (E-D)) \<union> (\<Union> ((\<lambda>y. h y) ` (D \<inter> E)))))"
    apply clarify
    apply (rule_tac x = D in exI)
    apply (rule_tac x = E in exI)
    apply clarify
    apply (rule_tac x = "\<lambda>x. if x \<in> (D - E) then f x else (if x \<in> D \<inter> E then (f x \<union> g x) else g x)" in exI)
    by auto
  hence " (\<exists>B. (a,B) \<in> R \<parallel> S \<and> (\<exists>h. (\<forall>b\<in>B. (b,h b) \<in> T) \<and> A = \<Union>((\<lambda>x. h x) ` B)))"
    by auto blast
  thus "(a,A) \<in> (R \<parallel> S) \<cdot> T"
    by (simp add: mr_simp)
qed

lemma cl3: "R \<cdot> (S \<parallel> T) \<subseteq> (R \<cdot> S) \<parallel> (R \<cdot> T)"
proof clarify
fix a A
assume "(a,A) \<in> R \<cdot> (S \<parallel> T)"
  hence "\<exists>B. (a,B) \<in> R \<and> (\<exists>f. (\<forall>b \<in> B. \<exists>C D. f b = C \<union> D \<and> (b,C) \<in> S \<and> (b,D) \<in> T) \<and> A = \<Union>((\<lambda>x. f x) ` B))"
    by (clarsimp simp: mr_simp)
  hence "\<exists>B. (a,B) \<in> R \<and> (\<exists>f g h. (\<forall>b \<in> B. f b = g b \<union> h b \<and> (b,g b) \<in> S \<and> (b,h b) \<in> T) \<and> A = \<Union>((\<lambda>x. f x) ` B))"
    by (clarsimp simp: bchoice, metis)
  hence "\<exists>B. (a,B) \<in> R \<and> (\<exists>g h. (\<forall>b \<in> B. (b,g b) \<in> S \<and> (b,h b) \<in> T) \<and> A = (\<Union> ((\<lambda>x. g x) ` B)) \<union> (\<Union> ((\<lambda>x. h x) ` B)))"
    by  blast
  hence "\<exists>C D. (\<exists>B. (a,B) \<in> R \<and> (\<exists>g. (\<forall>b \<in> B. (b,g b) \<in> S) \<and>  C = \<Union> ((\<lambda>x. g x) ` B))) \<and> (\<exists>B. (a,B) \<in> R \<and> (\<exists>h. (\<forall>b \<in> B. (b,h b) \<in> T) \<and>  D = \<Union> ((\<lambda>x. h x)` B))) \<and> A = C \<union> D"
    by blast
  thus "(a,A) \<in> (R \<cdot> S) \<parallel> (R \<cdot> T)"
    by (auto simp: mr_simp)
qed

lemma cl5: "(R \<cdot> S) \<cdot> (T \<cdot> {}) = R \<cdot> (S \<cdot> (T \<cdot> {}))"
  proof (rule antisym)
  show "(R \<cdot> S) \<cdot> (T \<cdot> {}) \<subseteq> R \<cdot> (S \<cdot> (T \<cdot> {}))"
    by (metis s_prod_assoc1)
  show " R \<cdot> (S \<cdot> (T \<cdot> {})) \<subseteq> (R \<cdot> S) \<cdot> (T \<cdot> {})"
  proof clarify
  fix a A
  assume "(a,A) \<in>  R \<cdot> (S \<cdot> (T \<cdot> {}))"
    hence "\<exists>B. (a,B) \<in> R \<and> (\<exists>f. (\<forall>b \<in> B. (\<exists> C. (b,C) \<in> S \<and> (\<exists>g. (\<forall>x \<in> C. (x,g x) \<in> T \<cdot> {}) \<and> f b = \<Union>((\<lambda>x. g x) ` C)))) \<and> A = \<Union>((\<lambda>x. f x) ` B))"
      by (clarsimp simp: mr_simp)
    hence "\<exists>B. (a,B) \<in> R \<and> (\<exists>f. (\<forall>b \<in> B. (\<exists> C. (b,C) \<in> S \<and> (\<forall>x \<in> C. (x,{}) \<in> T \<cdot> {}) \<and> f b = {})) \<and> A = \<Union>((\<lambda>x. f x) ` B))"
      by (clarsimp simp: mr_simp) fastforce
    hence "\<exists>B. (a,B) \<in> R \<and> (\<forall>b \<in> B. (\<exists> C. (b,C) \<in> S \<and> (\<forall>x \<in> C. (x,{}) \<in> T \<cdot> {}))) \<and> A = {}"
      by (metis (erased, opaque_lifting) SUP_bot_conv(2))
    hence "\<exists>B. (a,B) \<in> R \<and> (\<exists>f. (\<forall>b \<in> B. (b,f b) \<in> S \<and> (\<forall>x \<in> f b. (x,{}) \<in> T \<cdot> {}))) \<and> A = {}"
      by metis
    hence "\<exists>B. (a,B) \<in> R \<and> (\<exists>f. (\<forall>b \<in> B. (b,f b) \<in> S) \<and> (\<forall>x \<in> \<Union>((\<lambda>x. f x) ` B). (x,{}) \<in> T \<cdot> {})) \<and> A = {}"
      by (metis UN_E)
    hence "\<exists>C B. (a,B) \<in> R \<and> (\<exists>f. (\<forall>b \<in> B. (b, f b) \<in> S) \<and> C =  \<Union>((\<lambda>x. f x) ` B) \<and> (\<forall>x \<in> C. (x,{}) \<in> T \<cdot> {})) \<and> A = {}"
      by metis
    hence "\<exists>C. (a,C) \<in> R \<cdot> S \<and> (\<forall>x \<in> C. (x,{}) \<in> T \<cdot> {}) \<and> A = {}"
      by (auto simp: mr_simp)
    thus "(a,A) \<in> (R \<cdot> S) \<cdot> (T \<cdot> {})"
      by (clarsimp simp: mr_simp) blast
  qed
qed

text \<open>We continue verifying other c-lattice axioms\<close>

lemma cl8_var: "d R \<cdot> S = (R \<cdot> 1\<^sub>\<pi>) \<parallel> S"
  apply (rule set_eqI)
  apply (clarsimp simp: mrd_simp)
  apply standard
  apply (metis SUP_bot sup.commute sup_bot.right_neutral)
  by auto

lemma cl9_var: "d (R \<inter> 1\<^sub>\<sigma>) = R \<inter> 1\<^sub>\<sigma>"
  by (auto simp: mrd_simp)

lemma cl10_var: "d (R - 1\<^sub>\<pi>) = 1\<^sub>\<sigma> \<inter> ((R - 1\<^sub>\<pi>) \<cdot> NC)"
  apply (rule set_eqI)
  apply (clarsimp simp: d_def p_id_def s_id_def U_def s_prod_im)
  by (metis UN_constant insert_not_empty)

subsection \<open>Multirelations and C-Lattices\<close>

text \<open>Next we show that multirelations form c-lattices (Proposition 7.3) and prove further facts in this setting.\<close>

interpretation mrel_c_lattice: c_lattice "1\<^sub>\<sigma>" "(\<cdot>)" "1\<^sub>\<pi>" "(\<parallel>)" "(\<union>)" "(\<subseteq>)" "(\<subset>)" "{}" "U" "(\<inter>)" "NC"
proof
  fix x y z :: "('b \<times> 'b set) set"
  show "x \<cdot> 1\<^sub>\<pi> \<union> x \<cdot> NC = x \<cdot> U"
    apply (rule set_eqI)
    apply (clarsimp simp:  mr_simp)
    using UN_constant all_not_in_conv by metis
  show "1\<^sub>\<pi> \<inter> (x \<union> NC) = x \<cdot> {}"
    by (auto simp: mr_simp)
  show "x \<cdot> (y \<parallel> z) \<subseteq> x \<cdot> y \<parallel> (x \<cdot> z)"
    by (rule cl3)
  show "z \<parallel> z \<subseteq> z \<Longrightarrow> x \<parallel> y \<cdot> z = x \<cdot> z \<parallel> (y \<cdot> z)"
    by (metis cl4 seq_conc_subdistr subset_antisym)
  show "x \<cdot> (y \<cdot> (z \<cdot> {})) = x \<cdot> y \<cdot> (z \<cdot> {})"
    by (metis cl5)
  show "x \<cdot> {} \<cdot> z = x \<cdot> {}"
    by (clarsimp simp: mr_simp)
  show "1\<^sub>\<sigma> \<parallel> 1\<^sub>\<sigma> = 1\<^sub>\<sigma>"
    by (auto simp: mr_simp)
  show "x \<cdot> 1\<^sub>\<pi> \<parallel> 1\<^sub>\<sigma> \<cdot> y = x \<cdot> 1\<^sub>\<pi> \<parallel> y"
    by (metis cl8_var d_def_expl)
  show "x \<inter> 1\<^sub>\<sigma> \<cdot> 1\<^sub>\<pi> \<parallel> 1\<^sub>\<sigma> = x \<inter> 1\<^sub>\<sigma>"
    by (auto simp: mr_simp)
  show "x \<inter> NC \<cdot> 1\<^sub>\<pi> \<parallel> 1\<^sub>\<sigma> = 1\<^sub>\<sigma> \<inter> (x \<inter> NC \<cdot> NC)"
    by (metis Int_Diff cl10_var d_def_expl)
  show "x \<inter> NC \<cdot> 1\<^sub>\<pi> \<parallel> NC = x \<inter> NC \<cdot> NC"
    apply (rule set_eqI)
    apply (clarsimp simp: d_def U_def p_id_def p_prod_def s_prod_im)
    apply standard
    apply (metis (no_types, lifting) UN_extend_simps(2) Un_empty)
  proof -
    fix a :: 'b and b :: "'b set"
    assume a1: "\<exists>B. (a, B) \<in> x \<and> B \<noteq> {} \<and> (\<exists>f. (\<forall>b\<in>B. f b \<noteq> {}) \<and> b = (\<Union>x\<in>B. f x))"
    { fix bb :: "'b set \<Rightarrow> 'b set \<Rightarrow> 'b set \<Rightarrow> ('b \<Rightarrow> 'b set) \<Rightarrow> 'b"
      obtain BB :: "'b set" and BBa :: "'b \<Rightarrow> 'b set" where
        ff1: "(a, BB) \<in> x \<and> {} \<noteq> BB \<and> (\<forall>b. b \<notin> BB \<or> {} \<noteq> BBa b) \<and> \<Union>(BBa ` BB) = b"
        by (metis (full_types) a1)
      hence "\<forall>B. (\<Union>b\<in>BB. (B::'b set)) = B"
        by force
      hence "\<exists>B Ba. B \<union> Ba = b \<and> (\<exists>Bb. (a, Bb) \<in> x \<and> {} \<noteq> Bb \<and> (\<exists>f. (bb B Ba Bb f \<notin> Bb \<or> {} = f (bb B Ba Bb f)) \<and> \<Union>(f ` Bb) = B)) \<and> {} \<noteq> Ba"
        by (metis ff1 SUP_bot_conv(2) sup_bot.left_neutral) }
    thus "\<exists>B Ba. b = B \<union> Ba \<and> (\<exists>Ba. (a, Ba) \<in> x \<and> Ba \<noteq> {} \<and> (\<exists>f. (\<forall>b\<in>Ba. f b = {}) \<and> B = (\<Union>b\<in>Ba. f b))) \<and> Ba \<noteq> {}"
      by metis
  qed
qed

text \<open>The following facts from Lemma 2.2 remain to be shown.\<close>

lemma p_id_assoc1: "(1\<^sub>\<pi> \<cdot> R) \<cdot> S = 1\<^sub>\<pi> \<cdot> (R \<cdot> S)"
  by (clarsimp simp: mr_simp)

lemma p_id_assoc2: "(R \<cdot> 1\<^sub>\<pi>) \<cdot> T = R \<cdot> (1\<^sub>\<pi> \<cdot> T)"
  by (auto simp add: mr_simp cong del: SUP_cong_simp, blast+)

lemma seq_conc_subdistrl:
assumes "P \<subseteq> 1\<^sub>\<sigma>"
shows "P \<cdot> (S \<parallel> T) = (P \<cdot> S) \<parallel> (P \<cdot> T)"
  by (metis assms mrel_c_lattice.d_inter_r mrel_c_lattice.d_s_subid)

lemma test_s_prod_is_meet [simp]:
assumes "R \<subseteq> 1\<^sub>\<sigma>"
and "S \<subseteq> 1\<^sub>\<sigma>"
shows "R \<cdot> S = R \<inter> S"
  using assms by (auto simp: mr_simp, force+)

lemma test_p_prod_is_meet:
assumes "R \<subseteq> 1\<^sub>\<sigma>"
and "S \<subseteq> 1\<^sub>\<sigma>"
shows "R \<parallel> S = R \<inter> S"
  apply standard
  using assms
  apply (auto simp: mr_simp, force+)
  done

lemma test_multipliciativer:
assumes "R \<subseteq> 1\<^sub>\<sigma>"
and "S \<subseteq> 1\<^sub>\<sigma>"
shows "(R \<inter> S) \<cdot> T = (R \<cdot> T) \<inter> (S \<cdot> T)"
  using assms by (clarsimp simp: set_eqI mr_simp subid_aux2, force)

text \<open>Next we verify the remaining fact from Lemma 2.2; in fact it follows from the corresponding theorem of c-lattices.\<close>

lemma c6: "R \<cdot> 1\<^sub>\<pi> \<subseteq> 1\<^sub>\<pi>"
 by (clarsimp simp: mr_simp)

text \<open>Next we verify Lemma 3.1.\<close>

lemma p_id_st: "R \<cdot> 1\<^sub>\<pi> = {(a,{}) |a.  \<exists>B. (a,B) \<in> R}"
  by (auto simp: mr_simp)

lemma p_id_zero: "R \<inter> 1\<^sub>\<pi> = R \<cdot> {}"
  by (auto simp: mr_simp)

lemma p_id_zero_st: "R \<inter> 1\<^sub>\<pi> = {(a,{}) |a. (a,{}) \<in> R}"
  by (auto simp: mr_simp)

lemma s_id_st: "R \<inter> 1\<^sub>\<sigma> = {(a,{a}) |a. (a,{a}) \<in> R}"
  by (auto simp: mr_simp)

lemma U_seq_st: "(a,A) \<in> R \<cdot> U \<longleftrightarrow> (A = {} \<and> (a,{}) \<in> R) \<or> (\<exists>B. B \<noteq> {} \<and> (a,B) \<in> R)"
  by (clarsimp simp: s_prod_im U_def, metis SUP_constant SUP_empty)

lemma U_par_st: "(a,A) \<in> R \<parallel> U \<longleftrightarrow> (\<exists>B. B \<subseteq> A \<and> (a,B) \<in> R)"
  by (auto simp: mr_simp)

text \<open>Next we verify the relationships after Lemma 3.1.\<close>

lemma s_subid_iff1: "R \<subseteq> 1\<^sub>\<sigma> \<longleftrightarrow> R \<inter> 1\<^sub>\<sigma> = R"
  by blast

lemma s_subid_iff2: "R \<subseteq> 1\<^sub>\<sigma> \<longleftrightarrow> d R = R"
  by (auto simp: mrd_simp)

lemma p_subid_iff: "R \<subseteq> 1\<^sub>\<pi> \<longleftrightarrow> R \<cdot> 1\<^sub>\<pi> = R"
  by (simp add: mrel_c_lattice.term_p_subid)

lemma vec_iff1:
assumes "\<forall>a. (\<exists>A. (a,A) \<in> R) \<longrightarrow> (\<forall>A. (a,A) \<in> R)"
shows "(R \<cdot> 1\<^sub>\<pi>) \<parallel> U = R"
  using assms by (auto simp: mr_simp)

lemma vec_iff2:
assumes "(R \<cdot> 1\<^sub>\<pi>) \<parallel> U = R"
shows "(\<forall>a. (\<exists>A. (a,A) \<in> R) \<longrightarrow> (\<forall>A. (a,A) \<in> R))"
  using assms apply (clarsimp simp: mr_simp)
  proof -
    fix a :: 'a and A :: "'a set" and Aa :: "'a set"
    assume a1: "(a, A) \<in> R"
    obtain AA :: "('a \<times> 'a set) set \<Rightarrow> 'a set \<Rightarrow> 'a \<Rightarrow> 'a set" where
    "\<forall>x0 x1 x2. (\<exists>v3\<subseteq>x1. (x2, v3) \<in> x0) = (AA x0 x1 x2 \<subseteq> x1 \<and> (x2, AA x0 x1 x2) \<in> x0)"
      by moura
    hence f2: "AA (R \<cdot> 1\<^sub>\<pi>) A a \<subseteq> A \<and> (a, AA (R \<cdot> 1\<^sub>\<pi>) A a) \<in> R \<cdot> 1\<^sub>\<pi>"
      by (metis a1 U_par_st assms)
    hence "\<exists>aa. (a, AA (R \<cdot> 1\<^sub>\<pi>) A a) = (aa, {}) \<and> (\<exists>A. (aa, A) \<in> R)"
      by (simp add: p_id_st)
    hence "AA (R \<cdot> 1\<^sub>\<pi>) A a \<subseteq> Aa"
      by blast
   thus "(a, Aa) \<in> R"
      using f2 by (metis (no_types) U_par_st assms)
qed

lemma vec_iff: "(\<forall>a. (\<exists>A. (a,A) \<in> R) \<longrightarrow> (\<forall>A. (a,A) \<in> R)) \<longleftrightarrow> (R \<cdot> 1\<^sub>\<pi>) \<parallel> U = R"
  by (metis vec_iff1 vec_iff2)

lemma ucl_iff: "(\<forall>a A B. (a,A) \<in> R \<and> A \<subseteq> B \<longrightarrow> (a,B) \<in> R) \<longleftrightarrow> R \<parallel> U = R"
  by (clarsimp simp: mr_simp, blast)

lemma nt_iff: "R \<subseteq> NC \<longleftrightarrow> R \<inter> NC = R"
  by blast

text\<open>Next we provide a counterexample for the final paragraph of Section 3.\<close>

lemma "1\<^sub>\<sigma> \<inter> R \<cdot> U = R"
  nitpick
  oops

text\<open>Next we present a counterexample for vectors mentioned before Lemma 9.3.\<close>

lemma "d (d R \<cdot> U) \<cdot> (d S \<cdot> U) \<cdot> U = (d R \<cdot> U) \<cdot> (d S \<cdot> U)"
  nitpick
  oops

text\<open>Next we prove Tarski' rule (Lemma 9.3).\<close>

lemma tarski_aux:
assumes "R - 1\<^sub>\<pi> \<noteq> {}"
and "(a,A) \<in>  NC"
shows "(a,A) \<in> NC \<cdot> ((R - 1\<^sub>\<pi>) \<cdot> NC)"
proof -
  have "(\<exists>B. B \<noteq> {} \<and> (\<forall>x \<in> B. (x,{x}) \<in> d (R - 1\<^sub>\<pi>)))"
    using assms(1) by (auto simp: mrd_simp)
  hence "(\<exists>B. B \<noteq> {} \<and> (\<forall>x \<in> B. (x,{x}) \<in> d (R - 1\<^sub>\<pi>))) \<and> A \<noteq> {}"
    using assms(2) by (clarsimp simp: mr_simp)
  hence "(\<exists>B. B \<noteq> {} \<and> (\<exists>f. (\<forall>x \<in> B. (x,{x}) \<in> d (R - 1\<^sub>\<pi>) \<and> f x \<noteq> {}) \<and> A = \<Union> ((\<lambda>x. (f x)) ` B)))"
    by (metis UN_constant)
  hence "(a,A) \<in> NC \<cdot> (d (R - 1\<^sub>\<pi>) \<cdot> NC)"
    by (clarsimp simp: mrd_simp) metis
  thus ?thesis
   by (clarsimp simp: mrd_simp, metis UN_constant)
qed

lemma tarski:
assumes "R - 1\<^sub>\<pi> \<noteq> {}"
shows "NC \<cdot> ((R - 1\<^sub>\<pi>) \<cdot> NC) = NC"
  by standard (simp add: U_def p_id_def s_prod_im, force, metis assms tarski_aux subrelI)

text \<open>Next we verify the assumptions of Proposition 9.8.\<close>

lemma d_assoc1: "d R \<cdot> (S \<cdot> T) = (d R \<cdot> S) \<cdot> T"
  by (metis d_def_expl mrel_c_lattice.d_def mrel_c_lattice.d_sub_id_ax test_assoc2)

lemma d_meet_distr_var: "(d R \<inter> d S) \<cdot> T = (d R \<cdot> T) \<inter> (d S \<cdot> T)"
  by (auto simp: mrd_simp)

text \<open>Lemma 10.5.\<close>

lemma "((R \<inter> 1\<^sub>\<sigma>) \<cdot> (S \<inter> 1\<^sub>\<sigma>)) \<cdot> 1\<^sub>\<pi> = ((R \<inter> 1\<^sub>\<sigma>) \<cdot> 1\<^sub>\<pi>) \<cdot> ((S \<inter> 1\<^sub>\<sigma>) \<cdot> 1\<^sub>\<pi>)"
  nitpick
  oops

lemma "d ((R \<cdot> 1\<^sub>\<pi>) \<cdot> (S \<cdot> 1\<^sub>\<pi>)) = d (R \<cdot> 1\<^sub>\<pi>) \<cdot> d (S \<cdot> 1\<^sub>\<pi>)"
  nitpick
  oops

lemma "((R \<inter> 1\<^sub>\<sigma>) \<cdot> (S \<inter> 1\<^sub>\<sigma>)) \<cdot> U = ((R \<inter> 1\<^sub>\<sigma>) \<cdot> U) \<cdot> ((S \<inter> 1\<^sub>\<sigma>) \<cdot> U)"
  nitpick
  oops

lemma "d (((R \<cdot> 1\<^sub>\<pi>) \<parallel> U) \<cdot> ((S \<cdot> 1\<^sub>\<pi>) \<parallel> U)) = d ((R \<cdot> 1\<^sub>\<pi>) \<parallel> U) \<cdot> d ((S \<cdot> 1\<^sub>\<pi>) \<parallel> U)"
  nitpick
  oops

lemma "((R \<cdot> 1\<^sub>\<pi>) \<cdot> (S \<cdot> 1\<^sub>\<pi>)) \<parallel> U = ((R \<cdot> 1\<^sub>\<pi>) \<parallel> U) \<cdot> ((S \<cdot> 1\<^sub>\<pi>) \<parallel> U)"
  nitpick
  oops

lemma "(((R - 1\<^sub>\<pi>) \<inter> 1\<^sub>\<sigma>) \<cdot> ((S - 1\<^sub>\<pi>) \<inter> 1\<^sub>\<sigma>)) \<cdot> 1\<^sub>\<pi> = (((R - 1\<^sub>\<pi>) \<inter> 1\<^sub>\<sigma>) \<cdot> 1\<^sub>\<pi>) \<cdot> (((S - 1\<^sub>\<pi>) \<inter> 1\<^sub>\<sigma>) \<cdot> 1\<^sub>\<pi>)"
  nitpick
  oops

lemma "d (((R - 1\<^sub>\<pi>) \<cdot> 1\<^sub>\<pi>) \<cdot> ((S - 1\<^sub>\<pi>) \<cdot> 1\<^sub>\<pi>)) = d ((R - 1\<^sub>\<pi>) \<cdot> 1\<^sub>\<pi>) \<cdot> d ((S - 1\<^sub>\<pi>) \<cdot> 1\<^sub>\<pi>)"
  nitpick
  oops

lemma "(((R - 1\<^sub>\<pi>) \<inter> 1\<^sub>\<sigma>) \<cdot> ((S - 1\<^sub>\<pi>) \<inter> 1\<^sub>\<sigma>)) \<cdot> NC = (((R - 1\<^sub>\<pi>) \<inter> 1\<^sub>\<sigma>) \<cdot> NC) \<cdot> (((S - 1\<^sub>\<pi>) \<inter> 1\<^sub>\<sigma>) \<cdot> NC)"
  apply (auto simp: U_def p_id_def s_id_def s_prod_im)
  defer
  nitpick
  oops

lemma "d ((((R - 1\<^sub>\<pi>) \<cdot> 1\<^sub>\<pi>) \<parallel> NC) \<cdot> (((S - 1\<^sub>\<pi>) \<cdot> 1\<^sub>\<pi>) \<parallel> NC)) = d (((R - 1\<^sub>\<pi>) \<cdot> 1\<^sub>\<pi>) \<parallel> NC) \<cdot> d (((S - 1\<^sub>\<pi>) \<cdot> 1\<^sub>\<pi>) \<parallel> NC)"
  apply (simp add: U_def p_id_def s_prod_im p_prod_def d_def)
  nitpick
  oops

lemma "(((R - 1\<^sub>\<pi>) \<cdot> 1\<^sub>\<pi>) \<cdot> ((S - 1\<^sub>\<pi>) \<cdot> 1\<^sub>\<pi>)) \<parallel> NC = (((R - 1\<^sub>\<pi>) \<cdot> 1\<^sub>\<pi>) \<parallel> NC) \<cdot> (((S - 1\<^sub>\<pi>) \<cdot> 1\<^sub>\<pi>) \<parallel> NC)"
  nitpick
  oops

lemma "((((R - 1\<^sub>\<pi>) \<cdot> 1\<^sub>\<pi>) \<parallel> NC) \<cdot> (((S - 1\<^sub>\<pi>) \<cdot> 1\<^sub>\<pi>) \<parallel> NC)) \<cdot> 1\<^sub>\<pi>  = ((((R - 1\<^sub>\<pi>) \<cdot> 1\<^sub>\<pi>) \<parallel> NC) \<cdot> 1\<^sub>\<pi>) \<cdot> ((((S - 1\<^sub>\<pi>) \<cdot> 1\<^sub>\<pi>) \<parallel> NC) \<cdot> 1\<^sub>\<pi>)"
  nitpick
  oops

subsection \<open>Terminal and Nonterminal Elements\<close>

text \<open>Lemma 11.4\<close>

lemma "(R \<cdot> S) \<cdot> {} = (R \<cdot> {}) \<cdot> (S \<cdot> {})"
  nitpick
  oops

lemma "(R \<cdot> S) - 1\<^sub>\<pi> = (R - 1\<^sub>\<pi>) \<cdot> (S - 1\<^sub>\<pi>)"
  apply (auto simp: s_prod_im p_id_def)
  nitpick
  oops

lemma "(R \<parallel> S) - 1\<^sub>\<pi> = (R - 1\<^sub>\<pi>) \<parallel> (S - 1\<^sub>\<pi>)"
  nitpick
  oops

text \<open>Lemma 11.8.\<close>

lemma "((R \<cdot> 1\<^sub>\<pi>) \<cdot> (S - 1\<^sub>\<pi>)) - 1\<^sub>\<pi> = (R \<cdot> 1\<^sub>\<pi>) \<cdot> (S - 1\<^sub>\<pi>)"
  nitpick
  oops

lemma "((S - 1\<^sub>\<pi>) \<cdot> (R \<cdot> 1\<^sub>\<pi>)) - 1\<^sub>\<pi> = (S - 1\<^sub>\<pi>) \<cdot> (R \<cdot> 1\<^sub>\<pi>)"
  nitpick
  oops

lemma "((R \<cdot> 1\<^sub>\<pi>) \<parallel> (S - 1\<^sub>\<pi>)) \<cdot> 1\<^sub>\<pi> = (R \<cdot> 1\<^sub>\<pi>) \<parallel> (S - 1\<^sub>\<pi>)"
  nitpick
  oops

text \<open>Lemma 11.10.\<close>

lemma "R \<cdot> {} \<subseteq> S \<cdot> {} \<Longrightarrow> (R \<cdot> T) \<cdot> {} \<subseteq> (S \<cdot> T) \<cdot> {}"
  nitpick
  oops

lemma "R - 1\<^sub>\<pi> \<subseteq> S - 1\<^sub>\<pi> \<Longrightarrow> (R \<parallel> T) - 1\<^sub>\<pi> \<subseteq> (S \<parallel> T) - 1\<^sub>\<pi>"
  nitpick
  oops

lemma "R - 1\<^sub>\<pi> \<subseteq> S - 1\<^sub>\<pi> \<Longrightarrow> (T \<cdot> R) - 1\<^sub>\<pi> \<subseteq> (T \<cdot> S) - 1\<^sub>\<pi>"
  apply (auto simp: p_id_def s_prod_im)
  nitpick
  oops

text \<open>Corollary 11.12\<close>

lemma "R \<cdot> {} = S \<cdot> {} \<Longrightarrow> (R \<cdot> T) \<cdot> {} = (S \<cdot> T) \<cdot> {}"
  nitpick
  oops

lemma "R - 1\<^sub>\<pi> = S - 1\<^sub>\<pi> \<Longrightarrow> (R \<parallel> T) - 1\<^sub>\<pi> = (S \<parallel> T) - 1\<^sub>\<pi>"
  nitpick
  oops

lemma "R - 1\<^sub>\<pi> = S - 1\<^sub>\<pi> \<Longrightarrow> (T \<cdot> R) - 1\<^sub>\<pi> = (T \<cdot> S) - 1\<^sub>\<pi>"
  apply (auto simp: p_id_def s_prod_im)
  nitpick
  oops

subsection \<open>Multirelations, Proto-Quantales and Iteration\<close>

interpretation mrel_proto_quantale: proto_quantale "1\<^sub>\<sigma>" "(\<cdot>)" Inter Union "(\<inter>)" "(\<subseteq>)" "(\<subset>)" "(\<union>)" "{}" "U"
  by (unfold_locales, auto simp: mr_simp)

text \<open>We reprove Corollary 13.2. because Isabelle does not pick it up from the quantale level.\<close>

lemma iso_prop: "mono (\<lambda>X. S \<union> R \<cdot> X)"
  by (rule monoI, (clarsimp simp: mr_simp), blast)

lemma gfp_lfp_prop: "gfp (\<lambda>X. R \<cdot> X) \<union> lfp (\<lambda>X. S \<union> R \<cdot> X) \<subseteq> gfp (\<lambda>X. S \<union> R \<cdot> X)"
  by (simp add: lfp_le_gfp gfp_mono iso_prop)

subsection \<open>Further Counterexamples\<close>

text \<open>Lemma 14,1. and 14.2\<close>

lemma  "R \<parallel> R \<subseteq> R"
   nitpick
   oops

lemma "R \<subseteq> R \<parallel> S"
   nitpick
   oops

lemma "R \<parallel> S \<inter> R \<parallel> T \<subseteq> R \<parallel> (S \<inter> T)"
  nitpick
  oops

lemma "R \<cdot> (S \<parallel> T) = (R \<cdot> S) \<parallel> (R \<cdot> T)"
  nitpick
  oops

lemma "R \<cdot> (S \<cdot> T) \<subseteq> (R \<cdot> S) \<cdot> T"
  apply (auto simp: s_prod_im)
  nitpick
  oops

lemma "\<lbrakk>R \<parallel> R = R; S \<parallel> S = S; T \<parallel> T = T\<rbrakk> \<Longrightarrow> R \<cdot> (S \<parallel> T) = (R \<cdot> S) \<parallel> (R \<cdot> T)"
  nitpick
  oops

lemma "\<lbrakk>R \<noteq> {}; S \<noteq> {}; \<forall>a. (a,{}) \<notin> R \<union> S\<rbrakk> \<Longrightarrow> R \<cdot> S \<subseteq> R \<parallel> S"
  quickcheck
  oops

lemma "\<lbrakk>R \<noteq> {}; S \<noteq> {}; \<forall>a. (a,{}) \<notin> R \<union> S\<rbrakk> \<Longrightarrow> R \<parallel> S \<subseteq> R \<cdot> S"
  quickcheck
  oops

lemma "\<lbrakk>R \<noteq> {}; S \<noteq> {}; T \<noteq> {}; \<forall>a. (a,{}) \<notin> R \<union> S \<union> T\<rbrakk> \<Longrightarrow> (R \<parallel> S) \<cdot> T \<subseteq> R \<parallel> (S \<cdot> T)"
  quickcheck
  oops

lemma "\<lbrakk>R \<noteq> {}; S \<noteq> {}; T \<noteq> {}; \<forall>a. (a,{}) \<notin> R \<union> S \<union> T\<rbrakk> \<Longrightarrow> R \<parallel> (S \<cdot> T) \<subseteq> (R \<parallel> S) \<cdot> T"
  quickcheck
  oops

lemma "\<lbrakk>R \<noteq> {}; S \<noteq> {}; T \<noteq> {}; \<forall>a. (a,{}) \<notin> R \<union> S \<union> T\<rbrakk> \<Longrightarrow> R \<cdot> (S \<parallel> T) \<subseteq> (R \<cdot> S) \<parallel> T"
  quickcheck
  oops

lemma "\<lbrakk>R \<noteq> {}; S \<noteq> {}; T \<noteq> {}; \<forall>a. (a,{}) \<notin> R \<union> S \<union> T\<rbrakk> \<Longrightarrow> (R \<cdot> S) \<parallel> T \<subseteq> R \<cdot> (S \<parallel> T)"
  quickcheck
  oops

lemma "\<lbrakk>R \<noteq> {}; S \<noteq> {}; \<forall>a. (a,{}) \<notin> R \<union> S\<rbrakk> \<Longrightarrow> (R \<parallel> S) \<cdot> (R \<parallel> S) \<subseteq> (R \<cdot> R) \<parallel> (S \<cdot> S)"
  quickcheck
  oops

lemma "\<lbrakk>R \<noteq> {}; S \<noteq> {}; \<forall>a. (a,{}) \<notin> R \<union> S\<rbrakk> \<Longrightarrow> (R \<cdot> R) \<parallel> (S \<cdot> S) \<subseteq> (R \<parallel> S) \<cdot> (R \<parallel> S)"
  quickcheck
  oops

subsection \<open>Relationship with Up-Closed Multirelations\<close>

text \<open>We now define Parikh's sequential composition.\<close>

definition s_prod_pa :: "'a mrel \<Rightarrow> 'a mrel \<Rightarrow> 'a mrel" (infixl "\<otimes>" 70) where
  "R \<otimes> S = {(a,A). (\<exists>B. (a,B) \<in> R \<and> (\<forall>b \<in> B. (b,A) \<in> S))}"

text \<open>We show that Parikh's definition doesn't preserve up-closure.\<close>

lemma up_closed_prop: "((R \<parallel> U) \<cdot> (S \<parallel> U)) \<parallel> U = (R \<parallel> U) \<cdot> (S \<parallel> U)"
  apply (auto simp: p_prod_def s_prod_pa_def U_def)
  nitpick
  oops

text \<open>Lemma 15.1.\<close>

lemma onelem: "(R \<cdot> S) \<parallel> U \<subseteq> R \<otimes> (S \<parallel> U)"
  by (auto simp: s_prod_im p_prod_def U_def s_prod_pa_def)

lemma twolem: "R \<otimes> (S \<parallel> U)  \<subseteq> (R \<cdot> S) \<parallel> U"
proof clarify
  fix a A
  assume "(a,A) \<in> R \<otimes> (S \<parallel> U)"
  hence "\<exists>B. (a,B) \<in> R \<and> (\<forall>b \<in> B. (b,A) \<in> S \<parallel> U)"
    by (auto simp: s_prod_pa_def)
  hence "\<exists>B. (a,B) \<in> R \<and> (\<forall>b \<in> B. \<exists>C. C \<subseteq> A \<and> (b,C) \<in> S)"
    by (metis U_par_st)
  hence "\<exists>B. (a,B) \<in> R \<and> (\<exists>f. (\<forall>b \<in> B. f b \<subseteq> A \<and> (b,f b) \<in> S))"
    by metis
  hence "\<exists>C. C \<subseteq> A \<and> (\<exists>B. (a,B) \<in> R \<and> (\<exists>f. (\<forall>b \<in> B. (b,f b) \<in> S) \<and> C = \<Union> ((\<lambda>x. f x) ` B)))"
    by clarsimp blast
  hence "\<exists>C. C \<subseteq> A \<and> (a,C) \<in> R \<cdot> S"
    by (clarsimp simp: mr_simp)
  thus "(a,A) \<in> (R \<cdot> S) \<parallel> U"
    by (simp add: U_par_st)
qed

lemma pe_pa_sim: "(R \<cdot> S) \<parallel> U = R \<otimes> (S \<parallel> U)"
  by (metis antisym onelem twolem)

lemma pe_pa_sim_var: "((R \<parallel> U) \<cdot> (S \<parallel> U)) \<parallel> U = (R \<parallel> U) \<otimes> (S \<parallel> U)"
  by (simp add: mrel_proto_trioid.mult_assoc pe_pa_sim)

lemma pa_assoc1: "((R \<parallel> U) \<otimes> (S \<parallel> U)) \<otimes> (T \<parallel> U) \<subseteq> (R \<parallel> U) \<otimes> ((S \<parallel> U) \<otimes> (T \<parallel> U))"
  by (clarsimp simp: p_prod_def s_prod_pa_def U_def, metis)

text \<open>The converse direction of associativity remains to be proved.\<close>

text \<open>Corollary 15.3.\<close>

lemma up_closed_par_is_meet: "(R \<parallel> U) \<parallel> (S \<parallel> U) = (R \<parallel> U) \<inter> (S \<parallel> U)"
  by (auto simp: mr_simp)

end


(*  Title:      HOL/Wfrec.thy
    Author:     Tobias Nipkow
    Author:     Lawrence C Paulson
    Author:     Konrad Slind
*)

section {* Well-Founded Recursion Combinator *}

theory Wfrec
imports Wellfounded
begin

inductive wfrec_rel :: "('a \<times> 'a) set \<Rightarrow> (('a \<Rightarrow> 'b) \<Rightarrow> ('a \<Rightarrow> 'b)) \<Rightarrow> 'a \<Rightarrow> 'b \<Rightarrow> bool" for R F where
  wfrecI: "(\<And>z. (z, x) \<in> R \<Longrightarrow> wfrec_rel R F z (g z)) \<Longrightarrow> wfrec_rel R F x (F g x)"

definition cut :: "('a \<Rightarrow> 'b) \<Rightarrow> ('a \<times> 'a) set \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> 'b" where
  "cut f R x = (\<lambda>y. if (y, x) \<in> R then f y else undefined)"

definition adm_wf :: "('a \<times> 'a) set \<Rightarrow> (('a \<Rightarrow> 'b) \<Rightarrow> ('a \<Rightarrow> 'b)) \<Rightarrow> bool" where
  "adm_wf R F \<longleftrightarrow> (\<forall>f g x. (\<forall>z. (z, x) \<in> R \<longrightarrow> f z = g z) \<longrightarrow> F f x = F g x)"

definition wfrec :: "('a \<times> 'a) set \<Rightarrow> (('a \<Rightarrow> 'b) \<Rightarrow> ('a \<Rightarrow> 'b)) \<Rightarrow> ('a \<Rightarrow> 'b)" where
  "wfrec R F = (\<lambda>x. THE y. wfrec_rel R (\<lambda>f x. F (cut f R x) x) x y)"

lemma cuts_eq: "(cut f R x = cut g R x) \<longleftrightarrow> (\<forall>y. (y, x) \<in> R \<longrightarrow> f y = g y)"
  by (simp add: fun_eq_iff cut_def)

lemma cut_apply: "(x, a) \<in> R \<Longrightarrow> cut f R a x = f x"
  by (simp add: cut_def)

text{*Inductive characterization of wfrec combinator; for details see:
John Harrison, "Inductive definitions: automation and application"*}

lemma theI_unique: "\<exists>!x. P x \<Longrightarrow> P x \<longleftrightarrow> x = The P"
  by (auto intro: the_equality[symmetric] theI)

lemma wfrec_unique: assumes "adm_wf R F" "wf R" shows "\<exists>!y. wfrec_rel R F x y"
  using `wf R`
proof induct
  def f \<equiv> "\<lambda>y. THE z. wfrec_rel R F y z"
  case (less x)
  then have "\<And>y z. (y, x) \<in> R \<Longrightarrow> wfrec_rel R F y z \<longleftrightarrow> z = f y"
    unfolding f_def by (rule theI_unique)
  with `adm_wf R F` show ?case
    by (subst wfrec_rel.simps) (auto simp: adm_wf_def)
qed

lemma adm_lemma: "adm_wf R (\<lambda>f x. F (cut f R x) x)"
  by (auto simp add: adm_wf_def
           intro!: arg_cong[where f="\<lambda>x. F x y" for y] cuts_eq[THEN iffD2])

lemma wfrec: "wf R \<Longrightarrow> wfrec R F a = F (cut (wfrec R F) R a) a"
apply (simp add: wfrec_def)
apply (rule adm_lemma [THEN wfrec_unique, THEN the1_equality], assumption)
apply (rule wfrec_rel.wfrecI)
apply (erule adm_lemma [THEN wfrec_unique, THEN theI'])
done

text{** This form avoids giant explosions in proofs.  NOTE USE OF ==*}
lemma def_wfrec: "f \<equiv> wfrec R F \<Longrightarrow> wf R \<Longrightarrow> f a = F (cut f R a) a"
 by (auto intro: wfrec)

subsubsection {* Well-founded recursion via genuine fixpoints *}

lemma wfrec_fixpoint:
  assumes WF: "wf R" and ADM: "adm_wf R F"
  shows "wfrec R F = F (wfrec R F)"
proof (rule ext)
  fix x
  have "wfrec R F x = F (cut (wfrec R F) R x) x"
    using wfrec[of R F] WF by simp
  also
  { have "\<And> y. (y,x) \<in> R \<Longrightarrow> (cut (wfrec R F) R x) y = (wfrec R F) y"
      by (auto simp add: cut_apply)
    hence "F (cut (wfrec R F) R x) x = F (wfrec R F) x"
      using ADM adm_wf_def[of R F] by auto }
  finally show "wfrec R F x = F (wfrec R F) x" .
qed

subsection {* Wellfoundedness of @{text same_fst} *}

definition same_fst :: "('a \<Rightarrow> bool) \<Rightarrow> ('a \<Rightarrow> ('b \<times> 'b) set) \<Rightarrow> (('a \<times> 'b) \<times> ('a \<times> 'b)) set" where
  "same_fst P R = {((x', y'), (x, y)) . x' = x \<and> P x \<and> (y',y) \<in> R x}"
   --{*For @{const wfrec} declarations where the first n parameters
       stay unchanged in the recursive call. *}

lemma same_fstI [intro!]: "P x \<Longrightarrow> (y', y) \<in> R x \<Longrightarrow> ((x, y'), (x, y)) \<in> same_fst P R"
  by (simp add: same_fst_def)

lemma wf_same_fst:
  assumes prem: "\<And>x. P x \<Longrightarrow> wf (R x)"
  shows "wf (same_fst P R)"
apply (simp cong del: imp_cong add: wf_def same_fst_def)
apply (intro strip)
apply (rename_tac a b)
apply (case_tac "wf (R a)")
 apply (erule_tac a = b in wf_induct, blast)
apply (blast intro: prem)
done

end


(*  Title:      CTT/CTT.thy
    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
    Copyright   1993  University of Cambridge
*)

section \<open>Constructive Type Theory\<close>

theory CTT
imports Pure
begin

ML_file "~~/src/Provers/typedsimp.ML"
setup Pure_Thy.old_appl_syntax_setup

typedecl i
typedecl t
typedecl o

consts
  \<comment> \<open>Types\<close>
  F         :: "t"
  T         :: "t"          \<comment> \<open>\<open>F\<close> is empty, \<open>T\<close> contains one element\<close>
  contr     :: "i\<Rightarrow>i"
  tt        :: "i"
  \<comment> \<open>Natural numbers\<close>
  N         :: "t"
  succ      :: "i\<Rightarrow>i"
  rec       :: "[i, i, [i,i]\<Rightarrow>i] \<Rightarrow> i"
  \<comment> \<open>Unions\<close>
  inl       :: "i\<Rightarrow>i"
  inr       :: "i\<Rightarrow>i"
  "when"    :: "[i, i\<Rightarrow>i, i\<Rightarrow>i]\<Rightarrow>i"
  \<comment> \<open>General Sum and Binary Product\<close>
  Sum       :: "[t, i\<Rightarrow>t]\<Rightarrow>t"
  fst       :: "i\<Rightarrow>i"
  snd       :: "i\<Rightarrow>i"
  split     :: "[i, [i,i]\<Rightarrow>i] \<Rightarrow>i"
  \<comment> \<open>General Product and Function Space\<close>
  Prod      :: "[t, i\<Rightarrow>t]\<Rightarrow>t"
  \<comment> \<open>Types\<close>
  Plus      :: "[t,t]\<Rightarrow>t"           (infixr "+" 40)
  \<comment> \<open>Equality type\<close>
  Eq        :: "[t,i,i]\<Rightarrow>t"
  eq        :: "i"
  \<comment> \<open>Judgements\<close>
  Type      :: "t \<Rightarrow> prop"          ("(_ type)" [10] 5)
  Eqtype    :: "[t,t]\<Rightarrow>prop"        ("(_ =/ _)" [10,10] 5)
  Elem      :: "[i, t]\<Rightarrow>prop"       ("(_ /: _)" [10,10] 5)
  Eqelem    :: "[i,i,t]\<Rightarrow>prop"      ("(_ =/ _ :/ _)" [10,10,10] 5)
  Reduce    :: "[i,i]\<Rightarrow>prop"        ("Reduce[_,_]")

  \<comment> \<open>Types\<close>

  \<comment> \<open>Functions\<close>
  lambda    :: "(i \<Rightarrow> i) \<Rightarrow> i"      (binder "\<^bold>\<lambda>" 10)
  app       :: "[i,i]\<Rightarrow>i"           (infixl "`" 60)
  \<comment> \<open>Natural numbers\<close>
  Zero      :: "i"                  ("0")
  \<comment> \<open>Pairing\<close>
  pair      :: "[i,i]\<Rightarrow>i"           ("(1<_,/_>)")

syntax
  "_PROD"   :: "[idt,t,t]\<Rightarrow>t"       ("(3\<Prod>_:_./ _)" 10)
  "_SUM"    :: "[idt,t,t]\<Rightarrow>t"       ("(3\<Sum>_:_./ _)" 10)
translations
  "\<Prod>x:A. B" \<rightleftharpoons> "CONST Prod(A, \<lambda>x. B)"
  "\<Sum>x:A. B" \<rightleftharpoons> "CONST Sum(A, \<lambda>x. B)"

abbreviation Arrow :: "[t,t]\<Rightarrow>t"  (infixr "\<longrightarrow>" 30)
  where "A \<longrightarrow> B \<equiv> \<Prod>_:A. B"

abbreviation Times :: "[t,t]\<Rightarrow>t"  (infixr "\<times>" 50)
  where "A \<times> B \<equiv> \<Sum>_:A. B"

text \<open>
  Reduction: a weaker notion than equality;  a hack for simplification.
  \<open>Reduce[a,b]\<close> means either that \<open>a = b : A\<close> for some \<open>A\<close> or else
    that \<open>a\<close> and \<open>b\<close> are textually identical.

  Does not verify \<open>a:A\<close>!  Sound because only \<open>trans_red\<close> uses a \<open>Reduce\<close>
  premise. No new theorems can be proved about the standard judgements.
\<close>
axiomatization
where
  refl_red: "\<And>a. Reduce[a,a]" and
  red_if_equal: "\<And>a b A. a = b : A \<Longrightarrow> Reduce[a,b]" and
  trans_red: "\<And>a b c A. \<lbrakk>a = b : A; Reduce[b,c]\<rbrakk> \<Longrightarrow> a = c : A" and

  \<comment> \<open>Reflexivity\<close>

  refl_type: "\<And>A. A type \<Longrightarrow> A = A" and
  refl_elem: "\<And>a A. a : A \<Longrightarrow> a = a : A" and

  \<comment> \<open>Symmetry\<close>

  sym_type:  "\<And>A B. A = B \<Longrightarrow> B = A" and
  sym_elem:  "\<And>a b A. a = b : A \<Longrightarrow> b = a : A" and

  \<comment> \<open>Transitivity\<close>

  trans_type:   "\<And>A B C. \<lbrakk>A = B; B = C\<rbrakk> \<Longrightarrow> A = C" and
  trans_elem:   "\<And>a b c A. \<lbrakk>a = b : A; b = c : A\<rbrakk> \<Longrightarrow> a = c : A" and

  equal_types:  "\<And>a A B. \<lbrakk>a : A; A = B\<rbrakk> \<Longrightarrow> a : B" and
  equal_typesL: "\<And>a b A B. \<lbrakk>a = b : A; A = B\<rbrakk> \<Longrightarrow> a = b : B" and

  \<comment> \<open>Substitution\<close>

  subst_type:   "\<And>a A B. \<lbrakk>a : A; \<And>z. z:A \<Longrightarrow> B(z) type\<rbrakk> \<Longrightarrow> B(a) type" and
  subst_typeL:  "\<And>a c A B D. \<lbrakk>a = c : A; \<And>z. z:A \<Longrightarrow> B(z) = D(z)\<rbrakk> \<Longrightarrow> B(a) = D(c)" and

  subst_elem:   "\<And>a b A B. \<lbrakk>a : A; \<And>z. z:A \<Longrightarrow> b(z):B(z)\<rbrakk> \<Longrightarrow> b(a):B(a)" and
  subst_elemL:
    "\<And>a b c d A B. \<lbrakk>a = c : A; \<And>z. z:A \<Longrightarrow> b(z)=d(z) : B(z)\<rbrakk> \<Longrightarrow> b(a)=d(c) : B(a)" and

  \<comment> \<open>The type \<open>N\<close> -- natural numbers\<close>

  NF: "N type" and
  NI0: "0 : N" and
  NI_succ: "\<And>a. a : N \<Longrightarrow> succ(a) : N" and
  NI_succL:  "\<And>a b. a = b : N \<Longrightarrow> succ(a) = succ(b) : N" and

  NE:
   "\<And>p a b C. \<lbrakk>p: N; a: C(0); \<And>u v. \<lbrakk>u: N; v: C(u)\<rbrakk> \<Longrightarrow> b(u,v): C(succ(u))\<rbrakk>
   \<Longrightarrow> rec(p, a, \<lambda>u v. b(u,v)) : C(p)" and

  NEL:
   "\<And>p q a b c d C. \<lbrakk>p = q : N; a = c : C(0);
      \<And>u v. \<lbrakk>u: N; v: C(u)\<rbrakk> \<Longrightarrow> b(u,v) = d(u,v): C(succ(u))\<rbrakk>
   \<Longrightarrow> rec(p, a, \<lambda>u v. b(u,v)) = rec(q,c,d) : C(p)" and

  NC0:
   "\<And>a b C. \<lbrakk>a: C(0); \<And>u v. \<lbrakk>u: N; v: C(u)\<rbrakk> \<Longrightarrow> b(u,v): C(succ(u))\<rbrakk>
   \<Longrightarrow> rec(0, a, \<lambda>u v. b(u,v)) = a : C(0)" and

  NC_succ:
   "\<And>p a b C. \<lbrakk>p: N;  a: C(0); \<And>u v. \<lbrakk>u: N; v: C(u)\<rbrakk> \<Longrightarrow> b(u,v): C(succ(u))\<rbrakk> \<Longrightarrow>
   rec(succ(p), a, \<lambda>u v. b(u,v)) = b(p, rec(p, a, \<lambda>u v. b(u,v))) : C(succ(p))" and

  \<comment> \<open>The fourth Peano axiom.  See page 91 of Martin-Löf's book.\<close>
  zero_ne_succ: "\<And>a. \<lbrakk>a: N; 0 = succ(a) : N\<rbrakk> \<Longrightarrow> 0: F" and

  \<comment> \<open>The Product of a family of types\<close>

  ProdF: "\<And>A B. \<lbrakk>A type; \<And>x. x:A \<Longrightarrow> B(x) type\<rbrakk> \<Longrightarrow> \<Prod>x:A. B(x) type" and

  ProdFL:
    "\<And>A B C D. \<lbrakk>A = C; \<And>x. x:A \<Longrightarrow> B(x) = D(x)\<rbrakk> \<Longrightarrow> \<Prod>x:A. B(x) = \<Prod>x:C. D(x)" and

  ProdI:
    "\<And>b A B. \<lbrakk>A type; \<And>x. x:A \<Longrightarrow> b(x):B(x)\<rbrakk> \<Longrightarrow> \<^bold>\<lambda>x. b(x) : \<Prod>x:A. B(x)" and

  ProdIL: "\<And>b c A B. \<lbrakk>A type; \<And>x. x:A \<Longrightarrow> b(x) = c(x) : B(x)\<rbrakk> \<Longrightarrow>
    \<^bold>\<lambda>x. b(x) = \<^bold>\<lambda>x. c(x) : \<Prod>x:A. B(x)" and

  ProdE:  "\<And>p a A B. \<lbrakk>p : \<Prod>x:A. B(x); a : A\<rbrakk> \<Longrightarrow> p`a : B(a)" and
  ProdEL: "\<And>p q a b A B. \<lbrakk>p = q: \<Prod>x:A. B(x); a = b : A\<rbrakk> \<Longrightarrow> p`a = q`b : B(a)" and

  ProdC: "\<And>a b A B. \<lbrakk>a : A; \<And>x. x:A \<Longrightarrow> b(x) : B(x)\<rbrakk> \<Longrightarrow> (\<^bold>\<lambda>x. b(x)) ` a = b(a) : B(a)" and

  ProdC2: "\<And>p A B. p : \<Prod>x:A. B(x) \<Longrightarrow> (\<^bold>\<lambda>x. p`x) = p : \<Prod>x:A. B(x)" and

  \<comment> \<open>The Sum of a family of types\<close>

  SumF:  "\<And>A B. \<lbrakk>A type; \<And>x. x:A \<Longrightarrow> B(x) type\<rbrakk> \<Longrightarrow> \<Sum>x:A. B(x) type" and
  SumFL: "\<And>A B C D. \<lbrakk>A = C; \<And>x. x:A \<Longrightarrow> B(x) = D(x)\<rbrakk> \<Longrightarrow> \<Sum>x:A. B(x) = \<Sum>x:C. D(x)" and

  SumI:  "\<And>a b A B. \<lbrakk>a : A; b : B(a)\<rbrakk> \<Longrightarrow> <a,b> : \<Sum>x:A. B(x)" and
  SumIL: "\<And>a b c d A B. \<lbrakk> a = c : A; b = d : B(a)\<rbrakk> \<Longrightarrow> <a,b> = <c,d> : \<Sum>x:A. B(x)" and

  SumE: "\<And>p c A B C. \<lbrakk>p: \<Sum>x:A. B(x); \<And>x y. \<lbrakk>x:A; y:B(x)\<rbrakk> \<Longrightarrow> c(x,y): C(<x,y>)\<rbrakk>
    \<Longrightarrow> split(p, \<lambda>x y. c(x,y)) : C(p)" and

  SumEL: "\<And>p q c d A B C. \<lbrakk>p = q : \<Sum>x:A. B(x);
      \<And>x y. \<lbrakk>x:A; y:B(x)\<rbrakk> \<Longrightarrow> c(x,y)=d(x,y): C(<x,y>)\<rbrakk>
    \<Longrightarrow> split(p, \<lambda>x y. c(x,y)) = split(q, \<lambda>x y. d(x,y)) : C(p)" and

  SumC: "\<And>a b c A B C. \<lbrakk>a: A;  b: B(a); \<And>x y. \<lbrakk>x:A; y:B(x)\<rbrakk> \<Longrightarrow> c(x,y): C(<x,y>)\<rbrakk>
    \<Longrightarrow> split(<a,b>, \<lambda>x y. c(x,y)) = c(a,b) : C(<a,b>)" and

  fst_def:   "\<And>a. fst(a) \<equiv> split(a, \<lambda>x y. x)" and
  snd_def:   "\<And>a. snd(a) \<equiv> split(a, \<lambda>x y. y)" and

  \<comment> \<open>The sum of two types\<close>

  PlusF: "\<And>A B. \<lbrakk>A type; B type\<rbrakk> \<Longrightarrow> A+B type" and
  PlusFL: "\<And>A B C D. \<lbrakk>A = C; B = D\<rbrakk> \<Longrightarrow> A+B = C+D" and

  PlusI_inl: "\<And>a A B. \<lbrakk>a : A; B type\<rbrakk> \<Longrightarrow> inl(a) : A+B" and
  PlusI_inlL: "\<And>a c A B. \<lbrakk>a = c : A; B type\<rbrakk> \<Longrightarrow> inl(a) = inl(c) : A+B" and

  PlusI_inr: "\<And>b A B. \<lbrakk>A type; b : B\<rbrakk> \<Longrightarrow> inr(b) : A+B" and
  PlusI_inrL: "\<And>b d A B. \<lbrakk>A type; b = d : B\<rbrakk> \<Longrightarrow> inr(b) = inr(d) : A+B" and

  PlusE:
    "\<And>p c d A B C. \<lbrakk>p: A+B;
      \<And>x. x:A \<Longrightarrow> c(x): C(inl(x));
      \<And>y. y:B \<Longrightarrow> d(y): C(inr(y)) \<rbrakk> \<Longrightarrow> when(p, \<lambda>x. c(x), \<lambda>y. d(y)) : C(p)" and

  PlusEL:
    "\<And>p q c d e f A B C. \<lbrakk>p = q : A+B;
      \<And>x. x: A \<Longrightarrow> c(x) = e(x) : C(inl(x));
      \<And>y. y: B \<Longrightarrow> d(y) = f(y) : C(inr(y))\<rbrakk>
    \<Longrightarrow> when(p, \<lambda>x. c(x), \<lambda>y. d(y)) = when(q, \<lambda>x. e(x), \<lambda>y. f(y)) : C(p)" and

  PlusC_inl:
    "\<And>a c d A C. \<lbrakk>a: A;
      \<And>x. x:A \<Longrightarrow> c(x): C(inl(x));
      \<And>y. y:B \<Longrightarrow> d(y): C(inr(y)) \<rbrakk>
    \<Longrightarrow> when(inl(a), \<lambda>x. c(x), \<lambda>y. d(y)) = c(a) : C(inl(a))" and

  PlusC_inr:
    "\<And>b c d A B C. \<lbrakk>b: B;
      \<And>x. x:A \<Longrightarrow> c(x): C(inl(x));
      \<And>y. y:B \<Longrightarrow> d(y): C(inr(y))\<rbrakk>
    \<Longrightarrow> when(inr(b), \<lambda>x. c(x), \<lambda>y. d(y)) = d(b) : C(inr(b))" and

  \<comment> \<open>The type \<open>Eq\<close>\<close>

  EqF: "\<And>a b A. \<lbrakk>A type; a : A; b : A\<rbrakk> \<Longrightarrow> Eq(A,a,b) type" and
  EqFL: "\<And>a b c d A B. \<lbrakk>A = B; a = c : A; b = d : A\<rbrakk> \<Longrightarrow> Eq(A,a,b) = Eq(B,c,d)" and
  EqI: "\<And>a b A. a = b : A \<Longrightarrow> eq : Eq(A,a,b)" and
  EqE: "\<And>p a b A. p : Eq(A,a,b) \<Longrightarrow> a = b : A" and

  \<comment> \<open>By equality of types, can prove \<open>C(p)\<close> from \<open>C(eq)\<close>, an elimination rule\<close>
  EqC: "\<And>p a b A. p : Eq(A,a,b) \<Longrightarrow> p = eq : Eq(A,a,b)" and

  \<comment> \<open>The type \<open>F\<close>\<close>

  FF: "F type" and
  FE: "\<And>p C. \<lbrakk>p: F; C type\<rbrakk> \<Longrightarrow> contr(p) : C" and
  FEL: "\<And>p q C. \<lbrakk>p = q : F; C type\<rbrakk> \<Longrightarrow> contr(p) = contr(q) : C" and

  \<comment> \<open>The type T\<close>
  \<comment> \<open>
    Martin-Löf's book (page 68) discusses elimination and computation.
    Elimination can be derived by computation and equality of types,
    but with an extra premise \<open>C(x)\<close> type \<open>x:T\<close>.
    Also computation can be derived from elimination.
  \<close>

  TF: "T type" and
  TI: "tt : T" and
  TE: "\<And>p c C. \<lbrakk>p : T; c : C(tt)\<rbrakk> \<Longrightarrow> c : C(p)" and
  TEL: "\<And>p q c d C. \<lbrakk>p = q : T; c = d : C(tt)\<rbrakk> \<Longrightarrow> c = d : C(p)" and
  TC: "\<And>p. p : T \<Longrightarrow> p = tt : T"

subsection "Tactics and derived rules for Constructive Type Theory"

text \<open>Formation rules.\<close>
lemmas form_rls = NF ProdF SumF PlusF EqF FF TF
  and formL_rls = ProdFL SumFL PlusFL EqFL

text \<open>
  Introduction rules. OMITTED:
  \<^item> \<open>EqI\<close>, because its premise is an \<open>eqelem\<close>, not an \<open>elem\<close>.
\<close>
lemmas intr_rls = NI0 NI_succ ProdI SumI PlusI_inl PlusI_inr TI
  and intrL_rls = NI_succL ProdIL SumIL PlusI_inlL PlusI_inrL

text \<open>
  Elimination rules. OMITTED:
  \<^item> \<open>EqE\<close>, because its conclusion is an \<open>eqelem\<close>, not an \<open>elem\<close>
  \<^item> \<open>TE\<close>, because it does not involve a constructor.
\<close>
lemmas elim_rls = NE ProdE SumE PlusE FE
  and elimL_rls = NEL ProdEL SumEL PlusEL FEL

text \<open>OMITTED: \<open>eqC\<close> are \<open>TC\<close> because they make rewriting loop: \<open>p = un = un = \<dots>\<close>\<close>
lemmas comp_rls = NC0 NC_succ ProdC SumC PlusC_inl PlusC_inr

text \<open>Rules with conclusion \<open>a:A\<close>, an elem judgement.\<close>
lemmas element_rls = intr_rls elim_rls

text \<open>Definitions are (meta)equality axioms.\<close>
lemmas basic_defs = fst_def snd_def

text \<open>Compare with standard version: \<open>B\<close> is applied to UNSIMPLIFIED expression!\<close>
lemma SumIL2: "\<lbrakk>c = a : A; d = b : B(a)\<rbrakk> \<Longrightarrow> <c,d> = <a,b> : Sum(A,B)"
  apply (rule sym_elem)
  apply (rule SumIL)
   apply (rule_tac [!] sym_elem)
   apply assumption+
  done

lemmas intrL2_rls = NI_succL ProdIL SumIL2 PlusI_inlL PlusI_inrL

text \<open>
  Exploit \<open>p:Prod(A,B)\<close> to create the assumption \<open>z:B(a)\<close>.
  A more natural form of product elimination.
\<close>
lemma subst_prodE:
  assumes "p: Prod(A,B)"
    and "a: A"
    and "\<And>z. z: B(a) \<Longrightarrow> c(z): C(z)"
  shows "c(p`a): C(p`a)"
  by (rule assms ProdE)+

subsection \<open>Tactics for type checking\<close>

ML \<open>
local

fun is_rigid_elem (Const(@{const_name Elem},_) $ a $ _) = not(is_Var (head_of a))
  | is_rigid_elem (Const(@{const_name Eqelem},_) $ a $ _ $ _) = not(is_Var (head_of a))
  | is_rigid_elem (Const(@{const_name Type},_) $ a) = not(is_Var (head_of a))
  | is_rigid_elem _ = false

in

(*Try solving a:A or a=b:A by assumption provided a is rigid!*)
fun test_assume_tac ctxt = SUBGOAL (fn (prem, i) =>
  if is_rigid_elem (Logic.strip_assums_concl prem)
  then assume_tac ctxt i else no_tac)

fun ASSUME ctxt tf i = test_assume_tac ctxt i  ORELSE  tf i

end
\<close>

text \<open>
  For simplification: type formation and checking,
  but no equalities between terms.
\<close>
lemmas routine_rls = form_rls formL_rls refl_type element_rls

ML \<open>
fun routine_tac rls ctxt prems =
  ASSUME ctxt (filt_resolve_from_net_tac ctxt 4 (Tactic.build_net (prems @ rls)));

(*Solve all subgoals "A type" using formation rules. *)
val form_net = Tactic.build_net @{thms form_rls};
fun form_tac ctxt =
  REPEAT_FIRST (ASSUME ctxt (filt_resolve_from_net_tac ctxt 1 form_net));

(*Type checking: solve a:A (a rigid, A flexible) by intro and elim rules. *)
fun typechk_tac ctxt thms =
  let val tac =
    filt_resolve_from_net_tac ctxt 3
      (Tactic.build_net (thms @ @{thms form_rls} @ @{thms element_rls}))
  in  REPEAT_FIRST (ASSUME ctxt tac)  end

(*Solve a:A (a flexible, A rigid) by introduction rules.
  Cannot use stringtrees (filt_resolve_tac) since
  goals like ?a:SUM(A,B) have a trivial head-string *)
fun intr_tac ctxt thms =
  let val tac =
    filt_resolve_from_net_tac ctxt 1
      (Tactic.build_net (thms @ @{thms form_rls} @ @{thms intr_rls}))
  in  REPEAT_FIRST (ASSUME ctxt tac)  end

(*Equality proving: solve a=b:A (where a is rigid) by long rules. *)
fun equal_tac ctxt thms =
  REPEAT_FIRST
    (ASSUME ctxt
      (filt_resolve_from_net_tac ctxt 3
        (Tactic.build_net (thms @ @{thms form_rls element_rls intrL_rls elimL_rls refl_elem}))))
\<close>

method_setup form = \<open>Scan.succeed (fn ctxt => SIMPLE_METHOD (form_tac ctxt))\<close>
method_setup typechk = \<open>Attrib.thms >> (fn ths => fn ctxt => SIMPLE_METHOD (typechk_tac ctxt ths))\<close>
method_setup intr = \<open>Attrib.thms >> (fn ths => fn ctxt => SIMPLE_METHOD (intr_tac ctxt ths))\<close>
method_setup equal = \<open>Attrib.thms >> (fn ths => fn ctxt => SIMPLE_METHOD (equal_tac ctxt ths))\<close>

subsection \<open>Simplification\<close>

text \<open>To simplify the type in a goal.\<close>
lemma replace_type: "\<lbrakk>B = A; a : A\<rbrakk> \<Longrightarrow> a : B"
  apply (rule equal_types)
   apply (rule_tac [2] sym_type)
   apply assumption+
  done

text \<open>Simplify the parameter of a unary type operator.\<close>
lemma subst_eqtyparg:
  assumes 1: "a=c : A"
    and 2: "\<And>z. z:A \<Longrightarrow> B(z) type"
  shows "B(a) = B(c)"
  apply (rule subst_typeL)
   apply (rule_tac [2] refl_type)
   apply (rule 1)
  apply (erule 2)
  done

text \<open>Simplification rules for Constructive Type Theory.\<close>
lemmas reduction_rls = comp_rls [THEN trans_elem]

ML \<open>
(*Converts each goal "e : Eq(A,a,b)" into "a=b:A" for simplification.
  Uses other intro rules to avoid changing flexible goals.*)
val eqintr_net = Tactic.build_net @{thms EqI intr_rls}
fun eqintr_tac ctxt =
  REPEAT_FIRST (ASSUME ctxt (filt_resolve_from_net_tac ctxt 1 eqintr_net))

(** Tactics that instantiate CTT-rules.
    Vars in the given terms will be incremented!
    The (rtac EqE i) lets them apply to equality judgements. **)

fun NE_tac ctxt sp i =
  TRY (resolve_tac ctxt @{thms EqE} i) THEN
  Rule_Insts.res_inst_tac ctxt [((("p", 0), Position.none), sp)] [] @{thm NE} i

fun SumE_tac ctxt sp i =
  TRY (resolve_tac ctxt @{thms EqE} i) THEN
  Rule_Insts.res_inst_tac ctxt [((("p", 0), Position.none), sp)] [] @{thm SumE} i

fun PlusE_tac ctxt sp i =
  TRY (resolve_tac ctxt @{thms EqE} i) THEN
  Rule_Insts.res_inst_tac ctxt [((("p", 0), Position.none), sp)] [] @{thm PlusE} i

(** Predicate logic reasoning, WITH THINNING!!  Procedures adapted from NJ. **)

(*Finds f:Prod(A,B) and a:A in the assumptions, concludes there is z:B(a) *)
fun add_mp_tac ctxt i =
  resolve_tac ctxt @{thms subst_prodE} i  THEN  assume_tac ctxt i  THEN  assume_tac ctxt i

(*Finds P\<longrightarrow>Q and P in the assumptions, replaces implication by Q *)
fun mp_tac ctxt i = eresolve_tac ctxt @{thms subst_prodE} i  THEN  assume_tac ctxt i

(*"safe" when regarded as predicate calculus rules*)
val safe_brls = sort (make_ord lessb)
    [ (true, @{thm FE}), (true,asm_rl),
      (false, @{thm ProdI}), (true, @{thm SumE}), (true, @{thm PlusE}) ]

val unsafe_brls =
    [ (false, @{thm PlusI_inl}), (false, @{thm PlusI_inr}), (false, @{thm SumI}),
      (true, @{thm subst_prodE}) ]

(*0 subgoals vs 1 or more*)
val (safe0_brls, safep_brls) =
    List.partition (curry (op =) 0 o subgoals_of_brl) safe_brls

fun safestep_tac ctxt thms i =
    form_tac ctxt ORELSE
    resolve_tac ctxt thms i  ORELSE
    biresolve_tac ctxt safe0_brls i  ORELSE  mp_tac ctxt i  ORELSE
    DETERM (biresolve_tac ctxt safep_brls i)

fun safe_tac ctxt thms i = DEPTH_SOLVE_1 (safestep_tac ctxt thms i)

fun step_tac ctxt thms = safestep_tac ctxt thms  ORELSE'  biresolve_tac ctxt unsafe_brls

(*Fails unless it solves the goal!*)
fun pc_tac ctxt thms = DEPTH_SOLVE_1 o (step_tac ctxt thms)
\<close>

method_setup eqintr = \<open>Scan.succeed (SIMPLE_METHOD o eqintr_tac)\<close>
method_setup NE = \<open>
  Scan.lift Args.embedded_inner_syntax >> (fn s => fn ctxt => SIMPLE_METHOD' (NE_tac ctxt s))
\<close>
method_setup pc = \<open>Attrib.thms >> (fn ths => fn ctxt => SIMPLE_METHOD' (pc_tac ctxt ths))\<close>
method_setup add_mp = \<open>Scan.succeed (SIMPLE_METHOD' o add_mp_tac)\<close>

ML_file "rew.ML"
method_setup rew = \<open>Attrib.thms >> (fn ths => fn ctxt => SIMPLE_METHOD (rew_tac ctxt ths))\<close>
method_setup hyp_rew = \<open>Attrib.thms >> (fn ths => fn ctxt => SIMPLE_METHOD (hyp_rew_tac ctxt ths))\<close>

subsection \<open>The elimination rules for fst/snd\<close>

lemma SumE_fst: "p : Sum(A,B) \<Longrightarrow> fst(p) : A"
  apply (unfold basic_defs)
  apply (erule SumE)
  apply assumption
  done

text \<open>The first premise must be \<open>p:Sum(A,B)\<close>!!.\<close>
lemma SumE_snd:
  assumes major: "p: Sum(A,B)"
    and "A type"
    and "\<And>x. x:A \<Longrightarrow> B(x) type"
  shows "snd(p) : B(fst(p))"
  apply (unfold basic_defs)
  apply (rule major [THEN SumE])
  apply (rule SumC [THEN subst_eqtyparg, THEN replace_type])
      apply (typechk assms)
  done

end


theory Hs_Compat
imports Main
begin

section\<open>Definitions inspired by the Haskell World.\<close>

definition uncurry :: "('b \<Rightarrow> 'c \<Rightarrow> 'a) \<Rightarrow> 'b \<times> 'c \<Rightarrow> 'a"
where
  "uncurry f a \<equiv> (case a of (x,y) \<Rightarrow> f x y)"

lemma uncurry_simp[simp]: "uncurry f (a,b) = f a b"
  by(simp add: uncurry_def)

lemma uncurry_curry_id: "uncurry \<circ> curry = id" "curry \<circ> uncurry = id"
  by(simp_all add: fun_eq_iff)

lemma uncurry_split: "P (uncurry f p) \<longleftrightarrow> (\<forall>x1 x2. p = (x1, x2) \<longrightarrow> P (f x1 x2))"
  by(cases p) simp

lemma uncurry_split_asm: "P (uncurry f a) \<longleftrightarrow> \<not>(\<exists>x y. a = (x,y) \<and> \<not>P (f x y))"
  by(simp split: uncurry_split)

lemmas uncurry_splits = uncurry_split uncurry_split_asm

lemma uncurry_case_stmt: "(case x of (a, b) \<Rightarrow> f a b) = uncurry f x"
  by(cases x, simp)

end


(* Author: Johannes Hölzl <hoelzl@in.tum.de> *)

section \<open>Formalization of the Gossip-Broadcast\<close>

theory Gossip_Broadcast
  imports "../Discrete_Time_Markov_Chain"
begin

lemma inj_on_upd_PiE:
  assumes "i \<notin> I" shows "inj_on (\<lambda>(x,f). f(i := x)) (M \<times> (\<Pi>\<^sub>E i\<in>I. A i))"
  unfolding PiE_def
proof (safe intro!: inj_onI ext)
  fix f g :: "'a \<Rightarrow> 'b" and x y :: 'b
  assume *: "f(i := x) = g(i := y)" "f \<in> extensional I" "g \<in> extensional I"
  then show "x = y" by (auto simp: fun_eq_iff split: if_split_asm)
  fix i' from * \<open>i \<notin> I\<close> show "f i' = g i'"
    by (cases "i' = i") (auto simp: fun_eq_iff extensional_def split: if_split_asm)
qed

lemma sum_folded_product:
  fixes I :: "'i set" and f :: "'s \<Rightarrow> 'i \<Rightarrow> 'a::{semiring_0, comm_monoid_mult}"
  assumes "finite I" "\<And>i. i \<in> I \<Longrightarrow> finite (S i)"
  shows "(\<Sum>x\<in>Pi\<^sub>E I S. \<Prod>i\<in>I. f (x i) i) = (\<Prod>i\<in>I. \<Sum>s\<in>S i. f s i)"
using assms proof (induct I)
  case empty then show ?case by simp
next
  case (insert i I)
  have *: "Pi\<^sub>E (insert i I) S = (\<lambda>(x, f). f(i := x)) ` (S i \<times> Pi\<^sub>E I S)"
    by (auto simp: PiE_def intro!: image_eqI ext dest: extensional_arb)
  have "(\<Sum>x\<in>Pi\<^sub>E (insert i I) S. \<Prod>i\<in>insert i I. f (x i) i) =
    sum ((\<lambda>x. \<Prod>i\<in>insert i I. f (x i) i) \<circ> ((\<lambda>(x, f). f(i := x)))) (S i \<times> Pi\<^sub>E I S)"
    unfolding * using insert by (intro sum.reindex) (auto intro!: inj_on_upd_PiE)
  also have "\<dots> = (\<Sum>(a, x)\<in>(S i \<times> Pi\<^sub>E I S). f a i * (\<Prod>i\<in>I. f (x i) i))"
    using insert by (force intro!: sum.cong prod.cong arg_cong2[where f="(*)"])
  also have "\<dots> = (\<Sum>a\<in>S i. f a i * (\<Sum>x\<in>Pi\<^sub>E I S. \<Prod>i\<in>I. f (x i) i))"
    by (simp add: sum.cartesian_product sum_distrib_left)
  finally show ?case
    using insert by (simp add: sum_distrib_right)
qed

subsection \<open>Definition of the Gossip-Broadcast\<close>

datatype state = listening | sending | sleeping

type_synonym sys_state = "(nat \<times> nat) \<Rightarrow> state"

lemma state_UNIV: "UNIV = {listening, sending, sleeping}"
  by (auto intro: state.exhaust)

locale gossip_broadcast =
  fixes size :: nat and p :: real
  assumes size: "0 < size"
  assumes p: "0 < p" "p < 1"
begin

interpretation pmf_as_function .

definition states :: "sys_state set" where
  "states = ({..< size} \<times> {..< size}) \<rightarrow>\<^sub>E {listening, sending, sleeping}"

definition start :: sys_state where
  "start = (\<lambda>x\<in>{..< size}\<times>{..< size}. listening)((0, 0) := sending)"

definition neighbour_sending where
  "neighbour_sending s = (\<lambda>(x,y).
    (x > 0 \<and> s (x - 1, y) = sending) \<or>
    (x < size \<and> s (x + 1, y) = sending) \<or>
    (y > 0 \<and> s (x, y - 1) = sending) \<or>
    (y < size \<and> s (x, y + 1) = sending))"

definition node_trans :: "sys_state \<Rightarrow> (nat \<times> nat) \<Rightarrow> state \<Rightarrow> state \<Rightarrow> real" where
"node_trans g x s = (case s of
  listening \<Rightarrow> (if neighbour_sending g x
    then (\<lambda>_.0) (sending := p, sleeping := 1 - p)
    else (\<lambda>_.0) (listening := 1))
| sending   \<Rightarrow> (\<lambda>_.0) (sleeping := 1)
| sleeping  \<Rightarrow> (\<lambda>_.0) (sleeping := 1))"

lemma node_trans_sum_eq_1[simp]:
  "node_trans g x s' listening + (node_trans g x s' sending + node_trans g x s' sleeping) = 1"
  by (simp add: node_trans_def split: state.split)

lemma node_trans_nonneg[simp]: "0 \<le> node_trans s x i j"
  using p by (auto simp: node_trans_def split: state.split)

lift_definition proto_trans :: "sys_state \<Rightarrow> sys_state pmf" is
  "\<lambda>s s'. if s' \<in> states then (\<Prod>x\<in>{..< size}\<times>{..< size}. node_trans s x (s x) (s' x)) else 0"
proof
  let ?f = "\<lambda>s s'. if s' \<in> states then (\<Prod>x\<in>{..< size}\<times>{..< size}. node_trans s x (s x) (s' x)) else 0"
  fix s show "\<forall>t. 0 \<le> ?f s t"
    using p by (auto intro!: prod_nonneg simp: node_trans_def split: state.split)
  show "(\<integral>\<^sup>+t. ?f s t \<partial>count_space UNIV) = 1"
    apply (subst nn_integral_count_space'[of states])
    apply (simp_all add: prod_nonneg)
  proof -
    show "(\<Sum>x\<in>states. \<Prod>xa\<in>{..<size} \<times> {..<size}. node_trans s xa (s xa) (x xa)) = 1"
      unfolding states_def by (subst sum_folded_product) simp_all
    show "finite states"
      by (auto simp: states_def intro!: finite_PiE)
  qed
qed

end

subsection \<open>The Gossip-Broadcast forms a DTMC\<close>

sublocale gossip_broadcast \<subseteq> MC_syntax proto_trans .

end


(*  Title:      JinjaThreads/MM/Orders.thy
    Author:     Andreas Lochbihler
*)

header {* \isaheader{Orders as predicates} *}

theory Orders
imports
  Main
begin

section {* Preliminaries *}

text {* transfer @{term "refl_on"} et al. from @{theory Relation} to predicates *}

abbreviation refl_onP :: "'a set \<Rightarrow> ('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> bool"
where "refl_onP A r \<equiv> refl_on A {(x, y). r x y}"

abbreviation reflP :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> bool"
where "reflP == refl_onP UNIV"

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

abbreviation total_onP :: "'a set \<Rightarrow> ('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> bool"
where "total_onP A r \<equiv> total_on A {(x, y). r x y}"

abbreviation irreflP :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> bool"
where "irreflP r == irrefl {(x, y). r x y}"

definition irreflclp :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> bool" ("_\<^sup>\<noteq>\<^sup>\<noteq>" [1000] 1000)
where "r\<^sup>\<noteq>\<^sup>\<noteq> a b = (r a b \<and> a \<noteq> b)"

definition porder_on :: "'a set \<Rightarrow> ('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> bool"
where "porder_on A r \<longleftrightarrow> refl_onP A r \<and> transP r \<and> antisymP r"

definition torder_on :: "'a set \<Rightarrow> ('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> bool"
where "torder_on A r \<longleftrightarrow> porder_on A r \<and> total_onP A r"

definition order_consistent :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> ('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> bool"
where "order_consistent r s \<longleftrightarrow> (\<forall>a a'. r a a' \<and> s a' a \<longrightarrow> a = a')"

definition restrictP :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> 'a set \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> bool" (infixl "|`" 110)
where "(r |` A) a b \<longleftrightarrow> r a b \<and> a \<in> A \<and> b \<in> A"

definition inv_imageP :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> ('b \<Rightarrow> 'a) \<Rightarrow> 'b \<Rightarrow> 'b \<Rightarrow> bool"
where [iff]: "inv_imageP r f a b \<longleftrightarrow> r (f a) (f b)"

lemma refl_onPI: "(\<And>a a'. r a a' \<Longrightarrow> a \<in> A \<and> a' \<in> A) \<Longrightarrow> (\<And>a. a : A \<Longrightarrow> r a a) \<Longrightarrow> refl_onP A r"
by(rule refl_onI)(auto)

lemma refl_onPD: "refl_onP A r ==> a : A ==> r a a"
by(drule (1) refl_onD)(simp)

lemma refl_onPD1: "refl_onP A r ==> r a b ==> a : A"
by(erule refl_onD1)(simp)

lemma refl_onPD2: "refl_onP A r ==> r a b ==> b : A"
by(erule refl_onD2)(simp)

lemma refl_onP_Int: "refl_onP A r ==> refl_onP B s ==> refl_onP (A \<inter> B) (\<lambda>a a'. r a a' \<and> s a a')"
by(drule (1) refl_on_Int)(simp add: split_def inf_fun_def inf_set_def)

lemma refl_onP_Un: "refl_onP A r ==> refl_onP B s ==> refl_onP (A \<union> B) (\<lambda>a a'. r a a' \<or> s a a')"
by(drule (1) refl_on_Un)(simp add: split_def sup_fun_def sup_set_def)

lemma refl_onP_empty[simp]: "refl_onP {} (\<lambda>a a'. False)"
unfolding split_def by simp

lemma refl_onP_tranclp:
  assumes "refl_onP A r"
  shows "refl_onP A r^++"
proof(rule refl_onPI)
  fix a a'
  assume "r^++ a a'"
  thus "a \<in> A \<and> a' \<in> A"
    by(induct)(blast intro: refl_onPD1[OF assms] refl_onPD2[OF assms])+
next
  fix a
  assume "a \<in> A"
  from refl_onPD[OF assms this] show "r^++ a a" ..
qed

lemma irreflPI: "(\<And>a. \<not> r a a) \<Longrightarrow> irreflP r"
unfolding irrefl_def by blast

lemma irreflPE:
  assumes "irreflP r"
  obtains "\<forall>a. \<not> r a a"
using assms unfolding irrefl_def by blast

lemma irreflPD: "\<lbrakk> irreflP r; r a a \<rbrakk> \<Longrightarrow> False"
unfolding irrefl_def by blast

lemma irreflclpD:
  "r\<^sup>\<noteq>\<^sup>\<noteq> a b \<Longrightarrow> r a b \<and> a \<noteq> b"
by(simp add: irreflclp_def)

lemma irreflclpI [intro!]:
  "\<lbrakk> r a b; a \<noteq> b \<rbrakk> \<Longrightarrow> r\<^sup>\<noteq>\<^sup>\<noteq> a b"
by(simp add: irreflclp_def)

lemma irreflclpE [elim!]:
  assumes "r\<^sup>\<noteq>\<^sup>\<noteq> a b"
  obtains "r a b" "a \<noteq> b"
using assms by(simp add: irreflclp_def)

lemma transPI: "(\<And>x y z. \<lbrakk> r x y; r y z \<rbrakk> \<Longrightarrow> r x z) \<Longrightarrow> transP r"
using transI[where r="{(x, y). r x y}"] by blast

lemma transPD: "\<lbrakk>transP r; r x y; r y z \<rbrakk> \<Longrightarrow> r x z"
by(drule transD) auto

lemma transP_tranclp: "transP r^++"
using trans_trancl[of "{(x, y). r x y}"]
unfolding trancl_def by simp

lemma antisymPI: "(\<And>x y. \<lbrakk> r x y; r y x \<rbrakk> \<Longrightarrow> x = y) \<Longrightarrow> antisymP r"
using antisymI[of "{(x, y). r x y}"] by blast

lemma antisymPD: "\<lbrakk> antisymP r; r a b; r b a \<rbrakk> \<Longrightarrow> a = b"
using antisymD[where r="{(a, b). r a b}"] by blast

lemma antisym_subset:
  "\<lbrakk> antisymP r; \<And>a a'. s a a' \<Longrightarrow> r a a' \<rbrakk> \<Longrightarrow> antisymP s"
by(blast intro: antisymI antisymD)

lemma symPI: "(\<And>x y. r x y \<Longrightarrow> r y x) \<Longrightarrow> symP r"
by(rule symI)(blast)

lemma symPD: "\<lbrakk> symP r; r x y \<rbrakk> \<Longrightarrow> r y x"
by(blast dest: symD)

section {* Easy properties *}

lemma porder_onI:
  "\<lbrakk> refl_onP A r; antisymP r; transP r \<rbrakk> \<Longrightarrow> porder_on A r"
unfolding porder_on_def by blast

lemma porder_onE:
  assumes "porder_on A r"
  obtains "refl_onP A r" "antisymP r" "transP r"
using assms unfolding porder_on_def by blast

lemma torder_onI:
  "\<lbrakk> porder_on A r; total_onP A r \<rbrakk> \<Longrightarrow> torder_on A r"
unfolding torder_on_def by blast

lemma torder_onE:
  assumes "torder_on A r"
  obtains "porder_on A r" "total_onP A r"
using assms unfolding torder_on_def by blast

lemma total_onI:
  "(\<And>x y. \<lbrakk> x \<in> A; y \<in> A \<rbrakk> \<Longrightarrow> (x, y) \<in> r \<or> x = y \<or> (y, x) \<in> r) \<Longrightarrow> total_on A r"
unfolding total_on_def by blast

lemma total_onPI:
  "(\<And>x y. \<lbrakk> x \<in> A; y \<in> A \<rbrakk> \<Longrightarrow> r x y \<or> x = y \<or> r y x) \<Longrightarrow> total_onP A r"
by(rule total_onI) simp

lemma total_onD:
  "\<lbrakk> total_on A r; x \<in> A; y \<in> A \<rbrakk> \<Longrightarrow> (x, y) \<in> r \<or> x = y \<or> (y, x) \<in> r"
unfolding total_on_def by blast

lemma total_onPD:
  "\<lbrakk> total_onP A r; x \<in> A; y \<in> A \<rbrakk> \<Longrightarrow> r x y \<or> x = y \<or> r y x"
by(drule (2) total_onD) blast

section {* Order consistency *}

lemma order_consistentI:
  "(\<And>a a'. \<lbrakk> r a a'; s a' a \<rbrakk> \<Longrightarrow> a = a') \<Longrightarrow> order_consistent r s"
unfolding order_consistent_def by blast

lemma order_consistentD:
  "\<lbrakk> order_consistent r s; r a a'; s a' a \<rbrakk> \<Longrightarrow> a = a'"
unfolding order_consistent_def by blast

lemma order_consistent_subset:
  "\<lbrakk> order_consistent r s; \<And>a a'. r' a a' \<Longrightarrow> r a a'; \<And>a a'. s' a a' \<Longrightarrow> s a a' \<rbrakk> \<Longrightarrow> order_consistent r' s'"
by(blast intro: order_consistentI order_consistentD)

lemma order_consistent_sym:
  "order_consistent r s \<Longrightarrow> order_consistent s r"
by(blast intro: order_consistentI dest: order_consistentD)

lemma total_on_refl_on_consistent_into:
  assumes r: "total_onP A r" "refl_onP A r"
  and consist: "order_consistent r s"
  and x: "x \<in> A" and y: "y \<in> A" and s: "s x y"
  shows "r x y"
proof(cases "x = y")
  case True
  with r x y show ?thesis by(blast intro: refl_onPD)
next
  case False
  with r x y have "r x y \<or> r y x" by(blast dest: total_onD)
  thus ?thesis
  proof
    assume "r y x"
    with s consist have "x = y" by(blast dest: order_consistentD)
    with False show ?thesis by(contradiction)
  qed
qed

lemma porder_torder_tranclpE [consumes 5, case_names base step]:
  assumes r: "porder_on A r"
  and s: "torder_on B s"
  and consist: "order_consistent r s"
  and B_subset_A: "B \<subseteq> A"
  and trancl: "(\<lambda>a b. r a b \<or> s a b)^++ x y"
  obtains "r x y"
        | u v where "r x u" "s u v" "r v y"
proof(atomize_elim)
  from r have "refl_onP A r" "transP r" by(blast elim: porder_onE)+
  from s have "refl_onP B s" "total_onP B s" "transP s"
    by(blast elim: torder_onE porder_onE)+

  from trancl show "r x y \<or> (\<exists>u v. r x u \<and> s u v \<and> r v y)"
  proof(induct)
    case (base y)
    thus ?case
    proof
      assume "s x y"
      with s have "x \<in> B" "y \<in> B"
        by(blast elim: torder_onE porder_onE dest: refl_onPD1 refl_onPD2)+
      with B_subset_A have "x \<in> A" "y \<in> A" by blast+
      with refl_onPD[OF `refl_onP A r`, of x] refl_onPD[OF `refl_onP A r`, of y] `s x y`
      show ?thesis by(iprover)
    next
      assume "r x y"
      thus ?thesis ..
    qed
  next
    case (step y z)
    note IH = `r x y \<or> (\<exists>u v. r x u \<and> s u v \<and> r v y)`
    from `r y z \<or> s y z` show ?case
    proof
      assume "s y z"
      with `refl_onP B s` have "y \<in> B" "z \<in> B"
        by(blast dest: refl_onPD2 refl_onPD1)+
      from IH show ?thesis
      proof
        assume "r x y"
        moreover from `z \<in> B` B_subset_A r have "r z z"
          by(blast elim: porder_onE dest: refl_onPD)
        ultimately show ?thesis using `s y z` by blast
      next
        assume "\<exists>u v. r x u \<and> s u v \<and> r v y"
        then obtain u v where "r x u" "s u v" "r v y" by blast
        from `refl_onP B s` `s u v` have "v \<in> B" by(rule refl_onPD2)
        with `total_onP B s` `refl_onP B s` order_consistent_sym[OF consist]
        have "s v y" using `y \<in> B` `r v y`
          by(rule total_on_refl_on_consistent_into)
        with `transP s` have "s v z" using `s y z` by(rule transPD)
        with `transP s` `s u v` have "s u z" by(rule transPD)
        moreover from `z \<in> B` B_subset_A have "z \<in> A" ..
        with `refl_onP A r` have "r z z" by(rule refl_onPD)
        ultimately show ?thesis using `r x u` by blast
      qed
    next
      assume "r y z"
      with IH show ?thesis
        by(blast intro: transPD[OF `transP r`])
    qed
  qed
qed

lemma torder_on_porder_on_consistent_tranclp_antisym:
  assumes r: "porder_on A r"
  and s: "torder_on B s"
  and consist: "order_consistent r s"
  and B_subset_A: "B \<subseteq> A"
  shows "antisymP (\<lambda>x y. r x y \<or> s x y)^++"
proof(rule antisymPI)
  fix x y
  let ?rs = "\<lambda>x y. r x y \<or> s x y"
  assume "?rs^++ x y" "?rs^++ y x"
  from r have "antisymP r" "transP r" by(blast elim: porder_onE)+
  from s have "total_onP B s" "refl_onP B s" "transP s" "antisymP s"
    by(blast elim: torder_onE porder_onE)+

  from r s consist B_subset_A `?rs^++ x y`
  show "x = y"
  proof(cases rule: porder_torder_tranclpE)
    case base
    from r s consist B_subset_A `?rs^++ y x`
    show ?thesis
    proof(cases rule: porder_torder_tranclpE)
      case base
      with `antisymP r` `r x y` show ?thesis by(rule antisymPD)
    next
      case (step u v)
      from `r v x` `r x y` `r y u` have "r v u" by(blast intro: transPD[OF `transP r`])
      with consist have "v = u" using `s u v` by(rule order_consistentD)
      with `r y u` `r v x` have "r y x" by(blast intro: transPD[OF `transP r`])
      with `r x y` show ?thesis by(rule antisymPD[OF `antisymP r`])
    qed
  next
    case (step u v)
    from r s consist B_subset_A `?rs^++ y x`
    show ?thesis
    proof(cases rule: porder_torder_tranclpE)
      case base
      from `r v y` `r y x` `r x u` have "r v u" by(blast intro: transPD[OF `transP r`])
      with order_consistent_sym[OF consist] `s u v`
      have "u = v" by(rule order_consistentD)
      with `r v y` `r x u` have "r x y" by(blast intro: transPD[OF `transP r`])
      thus ?thesis using `r y x` by(rule antisymPD[OF `antisymP r`])
    next
      case (step u' v')
      note r_into_s = total_on_refl_on_consistent_into[OF `total_onP B s` `refl_onP B s` order_consistent_sym[OF consist]]
      from `refl_onP B s` `s u v` `s u' v'`
      have "u \<in> B" "v \<in> B" "u' \<in> B" "v' \<in> B" by(blast dest: refl_onPD1 refl_onPD2)+
      from `r v' x` `r x u` have "r v' u" by(rule transPD[OF `transP r`])
      with `v' \<in> B` `u \<in> B` have "s v' u" by(rule r_into_s)
      also note `s u v`
      also (transPD[OF `transP s`])
      from `r v y` `r y u'` have "r v u'" by(rule transPD[OF `transP r`])
      with `v \<in> B` `u' \<in> B` have "s v u'" by(rule r_into_s)
      finally (transPD[OF `transP s`])
      have "v' = u'" using `s u' v'` by(rule antisymPD[OF `antisymP s`])
      moreover with `s v u'` `s v' u` have "s v u" by(blast intro: transPD[OF `transP s`])
      with `s u v` have "u = v" by(rule antisymPD[OF `antisymP s`])
      ultimately have "r x y" "r y x" using `r x u` `r v y` `r y u'` `r v' x`
        by(blast intro: transPD[OF `transP r`])+
      thus ?thesis by(rule antisymPD[OF `antisymP r`])
    qed
  qed
qed

lemma porder_on_torder_on_tranclp_porder_onI:
  assumes r: "porder_on A r"
  and s: "torder_on B s"
  and consist: "order_consistent r s"
  and subset: "B \<subseteq> A"
  shows "porder_on A (\<lambda>a b. r a b \<or> s a b)^++"
proof(rule porder_onI)
  let ?rs = "\<lambda>a b. r a b \<or> s a b"
  from r have "refl_onP A r" by(rule porder_onE)
  moreover from s have "refl_onP B s" by(blast elim: torder_onE porder_onE)
  ultimately have "refl_onP (A \<union> B) ?rs" by(rule refl_onP_Un)
  also from subset have "A \<union> B = A" by blast
  finally show "refl_onP A ?rs^++" by(rule refl_onP_tranclp)

  show "transP ?rs^++" by(rule transP_tranclp)

  from r s consist subset show "antisymP ?rs^++"
    by (rule torder_on_porder_on_consistent_tranclp_antisym)
qed

lemma porder_on_sub_torder_on_tranclp_porder_onI:
  assumes r: "porder_on A r"
  and s: "torder_on B s"
  and consist: "order_consistent r s"
  and t: "\<And>x y. t x y \<Longrightarrow> s x y"
  and subset: "B \<subseteq> A"
  shows "porder_on A (\<lambda>x y. r x y \<or> t x y)^++"
proof(rule porder_onI)
  let ?rt = "\<lambda>x y. r x y \<or> t x y"
  let ?rs = "\<lambda>x y. r x y \<or> s x y"
  from r s consist subset have "antisymP ?rs^++"
    by(rule torder_on_porder_on_consistent_tranclp_antisym)
  thus "antisymP ?rt^++"
  proof(rule antisym_subset)
    fix x y
    assume "?rt^++ x y" thus "?rs^++ x y"
      by(induct)(blast intro: tranclp.r_into_trancl t tranclp.trancl_into_trancl t)+
  qed

  from s have "refl_onP B s" by(blast elim: porder_onE torder_onE)
  { fix x y
    assume "t x y"
    hence "s x y" by(rule t)
    hence "x \<in> B" "y \<in> B"
      by(blast dest: refl_onPD1[OF `refl_onP B s`] refl_onPD2[OF `refl_onP B s`])+
    with subset have "x \<in> A" "y \<in> A" by blast+ }
  note t_reflD = this

  from r have "refl_onP A r" by(rule porder_onE)
  show "refl_onP A ?rt^++"
  proof(rule refl_onPI)
    fix a a'
    assume "?rt^++ a a'"
    thus "a \<in> A \<and> a' \<in> A"
      by(induct)(auto dest: refl_onPD1[OF `refl_onP A r`] refl_onPD2[OF `refl_onP A r`] t_reflD)
  next
    fix a
    assume "a \<in> A"
    with `refl_onP A r` have "r a a" by(rule refl_onPD)
    thus "?rt^++ a a" by(blast intro: tranclp.r_into_trancl)
  qed

  show "transP ?rt^++" by(rule transP_tranclp)
qed

section {* Order restrictions *}

lemma restrictPI [intro!, simp]:
  "\<lbrakk> r a b; a \<in> A; b \<in> A \<rbrakk> \<Longrightarrow> (r |` A) a b"
unfolding restrictP_def by simp

lemma restrictPE [elim!]:
  assumes "(r |` A) a b"
  obtains "r a b" "a \<in> A" "b \<in> A"
using assms unfolding restrictP_def by simp

lemma restrictP_empty [simp]: "R |` {} = (\<lambda>_ _. False)"
by(simp add: restrictP_def[abs_def])

lemma refl_on_restrictPI:
  "refl_onP A r \<Longrightarrow> refl_onP (A \<inter> B) (r |` B)"
by(rule refl_onPI)(blast dest: refl_onPD1 refl_onPD2 refl_onPD)+

lemma refl_on_restrictPI':
  "\<lbrakk> refl_onP A r; B = A \<inter> C \<rbrakk> \<Longrightarrow> refl_onP B (r |` C)"
by(simp add: refl_on_restrictPI)

lemma antisym_restrictPI:
  "antisymP r \<Longrightarrow> antisymP (r |` A)"
by(rule antisymPI)(blast dest: antisymPD)

lemma trans_restrictPI:
  "transP r \<Longrightarrow> transP (r |` A)"
by(rule transPI)(blast dest: transPD)

lemma porder_on_restrictPI:
  "porder_on A r \<Longrightarrow> porder_on (A \<inter> B) (r |` B)"
by(blast elim: porder_onE intro: refl_on_restrictPI antisym_restrictPI trans_restrictPI porder_onI)

lemma porder_on_restrictPI':
  "\<lbrakk> porder_on A r; B = A \<inter> C \<rbrakk> \<Longrightarrow> porder_on B (r |` C)"
by(simp add: porder_on_restrictPI)

lemma total_on_restrictPI:
  "total_onP A r \<Longrightarrow> total_onP (A \<inter> B) (r |` B)"
by(blast intro: total_onPI dest: total_onPD)

lemma total_on_restrictPI':
  "\<lbrakk> total_onP A r; B = A \<inter> C \<rbrakk> \<Longrightarrow> total_onP B (r |` C)"
by(simp add: total_on_restrictPI)

lemma torder_on_restrictPI:
  "torder_on A r \<Longrightarrow> torder_on (A \<inter> B) (r |` B)"
by(blast elim: torder_onE intro: torder_onI porder_on_restrictPI total_on_restrictPI)

lemma torder_on_restrictPI':
  "\<lbrakk> torder_on A r; B = A \<inter> C \<rbrakk> \<Longrightarrow> torder_on B (r |` C)"
by(simp add: torder_on_restrictPI)

lemma restrictP_commute:
  fixes r :: "'a \<Rightarrow> 'a \<Rightarrow> bool"
  shows "r |` A |` B = r |` B |` A"
by(blast intro!: ext)

lemma restrictP_subsume2:
  fixes r :: "'a \<Rightarrow> 'a \<Rightarrow> bool"
  assumes "B \<subseteq> A"
  shows "r |` A |` B = r |` B"
using assms by(blast intro!: ext)

lemma restrictP_idem [simp]:
  fixes r :: "'a \<Rightarrow> 'a \<Rightarrow> bool"
  shows "r |` A |` A = r |` A"
by(simp add: restrictP_subsume1)

subsection {* Maximal elements w.r.t. a total order *}

definition max_torder :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> 'a"
where "max_torder r a b = (if DomainP r a \<and> DomainP r b then if r a b then b else a
  else if a = b then a else SOME a. \<not> DomainP r a)"

lemma refl_on_DomainD: "refl_on A r \<Longrightarrow> A = Domain r"
by(auto simp add: Domain_unfold dest: refl_onD refl_onD1)

lemma refl_onP_DomainPD: "refl_onP A r \<Longrightarrow> A = {a. DomainP r a}"
by(drule refl_on_DomainD) auto

lemma semilattice_max_torder:
  assumes tot: "torder_on A r"
  shows "semilattice (max_torder r)"
proof -
  from tot have as: "antisymP r"
    and to: "total_onP A r"
    and trans: "transP r"
    and refl: "refl_onP A r"
    by(auto elim: torder_onE porder_onE)
  from refl have "{a. DomainP r a} = A" by (rule refl_onP_DomainPD[symmetric])
  from this [symmetric] have "domain": "\<And>a. DomainP r a \<longleftrightarrow> a \<in> A" by simp
  show ?thesis
  proof
    fix x y z
    show "max_torder r (max_torder r x y) z = max_torder r x (max_torder r y z)"
    proof (cases "x \<noteq> y \<and> x \<noteq> z \<and> y \<noteq> z")
      case True
      have *: "\<And>a b. a \<noteq> b \<Longrightarrow> max_torder r a b = (if DomainP r a \<and> DomainP r b then
        if r a b then b else a else SOME a. \<not> DomainP r a)"
        by (auto simp add: max_torder_def)
      with True show ?thesis
        apply (simp only: max_torder_def "domain")
        apply auto
        apply (blast dest: total_onPD [OF to] transPD [OF trans] antisymPD [OF as] refl_onPD1 [OF refl] refl_onPD2 [OF refl] someI [where P="\<lambda>a. a \<notin> A"])+
        done
    next
      have max_torder_idem: "\<And>a. max_torder r a a = a" by (simp add: max_torder_def)
      case False then show ?thesis
        apply (auto simp add: max_torder_idem)
        apply (auto simp add: max_torder_def "domain" dest: someI [where P="\<lambda>a. a \<notin> A"])
        done
    qed
  next
    fix x y
    show "max_torder r x y = max_torder r y x"
      by (auto simp add: max_torder_def "domain" dest: total_onPD [OF to] antisymPD [OF as])
  next
    fix x
    show "max_torder r x x = x"
      by (simp add: max_torder_def)
  qed
qed

lemma max_torder_ge_conv_disj:
  assumes tot: "torder_on A r" and x: "x \<in> A" and y: "y \<in> A"
  shows "r z (max_torder r x y) \<longleftrightarrow> r z x \<or> r z y"
proof -
  from tot have as: "antisymP r"
    and to: "total_onP A r"
    and trans: "transP r"
    and refl: "refl_onP A r"
    by(auto elim: torder_onE porder_onE)
  from refl have "{a. DomainP r a} = A" by (rule refl_onP_DomainPD[symmetric])
  from this [symmetric] have "domain": "\<And>a. DomainP r a \<longleftrightarrow> a \<in> A" by simp
  show ?thesis using x y
    by(simp add: max_torder_def "domain")(blast dest: total_onPD[OF to] transPD[OF trans])
qed

definition Max_torder :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> 'a set \<Rightarrow> 'a"
where
  "Max_torder r = semilattice_set.F (max_torder r)"

context
  fixes A r
  assumes tot: "torder_on A r"
begin

lemma semilattice_set:
  "semilattice_set (max_torder r)"
  by (rule semilattice_set.intro, rule semilattice_max_torder) (fact tot)

lemma domain:
  "DomainP r a \<longleftrightarrow> a \<in> A"
proof -
  from tot have "{a. DomainP r a} = A"
    by (auto elim: torder_onE porder_onE dest: refl_onP_DomainPD [symmetric])
  from this [symmetric] show ?thesis by simp
qed

lemma Max_torder_in_Domain:
  assumes B: "finite B" "B \<noteq> {}" "B \<subseteq> A"
  shows "Max_torder r B \<in> A"
proof -
  interpret Max_torder!: semilattice_set "max_torder r"
  where
    "semilattice_set.F (max_torder r) = Max_torder r"
    by (fact semilattice_set Max_torder_def [symmetric])+
  show ?thesis using B
    by (induct rule: finite_ne_induct) (simp_all add: max_torder_def "domain")
qed

lemma Max_torder_in_set:
  assumes B: "finite B" "B \<noteq> {}" "B \<subseteq> A"
  shows "Max_torder r B \<in> B"
proof -
  interpret Max_torder!: semilattice_set "max_torder r"
  where
    "semilattice_set.F (max_torder r) = Max_torder r"
    by (fact semilattice_set Max_torder_def [symmetric])+
  show ?thesis using B
    by (induct rule: finite_ne_induct) (auto simp add: max_torder_def "domain")
qed

lemma Max_torder_above_iff:
  assumes B: "finite B" "B \<noteq> {}" "B \<subseteq> A"
  shows "r x (Max_torder r B) \<longleftrightarrow> (\<exists>a\<in>B. r x a)"
proof -
  interpret Max_torder!: semilattice_set "max_torder r"
  where
    "semilattice_set.F (max_torder r) = Max_torder r"
    by (fact semilattice_set Max_torder_def [symmetric])+
  from B show ?thesis
    by (induct rule: finite_ne_induct) (simp_all add: max_torder_ge_conv_disj [OF tot] Max_torder_in_Domain)
qed

end

lemma Max_torder_above:
  assumes tot: "torder_on A r"
  and "finite B" "a \<in> B" "B \<subseteq> A"
  shows "r a (Max_torder r B)"
proof -
  from tot have refl: "refl_onP A r" by(auto elim: torder_onE porder_onE)
  with `a \<in> B` `B \<subseteq> A` have "r a a" by(blast dest: refl_onPD[OF refl])
  from `a \<in> B` have "B \<noteq> {}" by auto
  from Max_torder_above_iff [OF tot `finite B` this `B \<subseteq> A`, of a] `r a a` `a \<in> B`
  show ?thesis by blast
qed

lemma inv_imageP_id [simp]: "inv_imageP R id = R"
by(simp add: fun_eq_iff)

lemma inv_into_id [simp]: "a \<in> A \<Longrightarrow> inv_into A id a = a"
by (metis f_inv_into_f id_apply image_id)

end