(*  Title:       Formalization of Schneider's generalized clock synchronization protocol.
    Author:      Alwen Tiu, LORIA, June 11, 2005
    Maintainer:  Alwen Tiu <Alwen.Tiu at loria.fr>
*)

theory GenClock imports Complex_Main begin

subsection\<open>Types and constants definitions\<close>

text\<open>Process is represented by natural numbers. The type 'event' corresponds
to synchronization rounds.\<close>

type_synonym process = nat
type_synonym event = nat      (* synchronization rounds *)
type_synonym time = real
type_synonym Clocktime = real

axiomatization
  \<delta> :: real and
  \<mu> :: real and
  \<rho> :: real and
  rmin :: real and
  rmax :: real and
  \<beta> :: real and
  \<Lambda> :: real and
  (* Number of processes *)
  np :: process and
  maxfaults :: process and
  (* Physical clocks *)
  PC :: "[process, time] \<Rightarrow> Clocktime" and
  (* Virtual / Logical clocks *)
  VC :: "[process, time] \<Rightarrow> Clocktime" and
  (* Starting (real) time of synchronization rounds *)
  te :: "[process, event] \<Rightarrow> time" and
  (* Clock readings at each round *)
  \<theta> :: "[process, event] \<Rightarrow> (process \<Rightarrow> Clocktime)" and
  (* Logical clock in-effect at a time interval *)
  IC :: "[process, event, time] \<Rightarrow> Clocktime" and
  (* Correct clocks *)
  correct :: "[process, time] \<Rightarrow> bool" and
  (* The averaging function to calculate clock adjustment *)
  cfn :: "[process, (process \<Rightarrow> Clocktime)] \<Rightarrow> Clocktime" and

  \<pi> :: "[Clocktime, Clocktime] \<Rightarrow> Clocktime" and

  \<alpha> :: "Clocktime \<Rightarrow> Clocktime"

definition
  count :: "[process \<Rightarrow> bool, process] \<Rightarrow> nat" where
  "count f n = card {p. p < n \<and> f p}"

definition
  (* Adjustment to a clock *)
  Adj :: "[process, event] \<Rightarrow> Clocktime" where
  "Adj = (\<lambda> p i. if 0 < i then cfn p (\<theta> p i) - PC p (te p i)
                 else 0)"

definition
  (* Auxilary predicates used in the definition of precision enhancement *)
  okRead1 :: "[process \<Rightarrow> Clocktime, Clocktime, process \<Rightarrow> bool] \<Rightarrow> bool" where
  "okRead1 f x ppred \<longleftrightarrow> (\<forall> l m. ppred l \<and> ppred m \<longrightarrow> \<bar>f l - f m\<bar> \<le> x)"

definition
  okRead2 :: "[process \<Rightarrow> Clocktime, process \<Rightarrow> Clocktime, Clocktime,
               process \<Rightarrow> bool] \<Rightarrow> bool" where
  "okRead2 f g x ppred \<longleftrightarrow> (\<forall> p. ppred p \<longrightarrow> \<bar>f p - g p\<bar> \<le> x)"

definition
  rho_bound1 :: "[[process, time] \<Rightarrow> Clocktime] \<Rightarrow> bool" where
  "rho_bound1 C \<longleftrightarrow> (\<forall> p s t. correct p t \<and> s \<le> t \<longrightarrow> C p t - C p s \<le> (t - s)*(1 + \<rho>))"
definition
  rho_bound2 :: "[[process, time] \<Rightarrow> Clocktime] \<Rightarrow> bool" where
  "rho_bound2 C \<longleftrightarrow> (\<forall> p s t. correct p t \<and> s \<le> t \<longrightarrow> (t - s)*(1 - \<rho>) \<le> C p t - C p s)"

subsection\<open>Clock conditions\<close>

text\<open>Some general assumptions\<close>
axiomatization where
  constants_ax: "0 < \<beta> \<and> 0 < \<mu> \<and> 0 < rmin
  \<and> rmin \<le> rmax \<and> 0 < \<rho> \<and> 0 < np \<and> maxfaults \<le> np"

axiomatization where
  PC_monotone: "\<forall> p s t. correct p t \<and> s \<le> t \<longrightarrow> PC p s \<le> PC p t"

axiomatization where
  VClock: "\<forall> p t i. correct p t \<and> te p i \<le> t \<and> t < te p (i + 1) \<longrightarrow> VC p t = IC p i t"

axiomatization where
  IClock: "\<forall> p t i. correct p t \<longrightarrow> IC p i t = PC p t + Adj p i"

text\<open>Condition 1: initial skew\<close>
axiomatization where
  init: "\<forall> p. correct p 0 \<longrightarrow> 0 \<le> PC p 0 \<and> PC p 0 \<le> \<mu>"

text\<open>Condition 2: bounded drift\<close>
axiomatization where
  rate_1: "\<forall> p s t. correct p t \<and> s \<le> t \<longrightarrow> PC p t - PC p s \<le> (t - s)*(1 + \<rho>)" and
  rate_2: "\<forall> p s t. correct p t \<and> s \<le> t \<longrightarrow> (t - s)*(1 - \<rho>) \<le> PC p t - PC p s"

text\<open>Condition 3: bounded interval\<close>
axiomatization where
  rts0: "\<forall> p t i. correct p t \<and> t \<le> te p (i+1) \<longrightarrow> t - te p i \<le> rmax" and
  rts1: "\<forall> p t i. correct p t \<and> te p (i+1) \<le> t \<longrightarrow> rmin \<le> t - te p i"

text\<open>Condition 4 : bounded delay\<close>
axiomatization where
  rts2a: "\<forall> p q t i. correct p t \<and> correct q t \<and> te q i + \<beta> \<le> t \<longrightarrow> te p i \<le> t"  and
  rts2b: "\<forall> p q i. correct p (te p i) \<and> correct q (te q i) \<longrightarrow> abs(te p i - te q i) \<le> \<beta>"

text\<open>Condition 5: initial synchronization\<close>
axiomatization where
  synch0: "\<forall> p. te p 0 = 0"

text\<open>Condition 6: nonoverlap\<close>
axiomatization where
  nonoverlap: "\<beta> \<le> rmin"

text\<open>Condition 7: reading errors\<close>
axiomatization where
  readerror: "\<forall> p q i. correct p (te p (i+1)) \<and> correct q (te p (i+1)) \<longrightarrow>
              abs(\<theta> p (i+1) q - IC q i (te p (i+1))) \<le> \<Lambda>"

text\<open>Condition 8: bounded faults\<close>
axiomatization where
  correct_closed: "\<forall> p s t. s \<le> t \<and> correct p t \<longrightarrow> correct p s" and
  correct_count:  "\<forall> t. np - maxfaults \<le> count (\<lambda> p. correct p t) np"

text\<open>Condition 9: Translation invariance\<close>
axiomatization where
  trans_inv: "\<forall> p f x. 0 \<le> x \<longrightarrow> cfn p (\<lambda> y. f y + x) = cfn p f + x"

text\<open>Condition 10: precision enhancement\<close>
axiomatization where
  prec_enh:
  "\<forall> ppred p q f g x y.
          np - maxfaults \<le> count ppred np \<and>
          okRead1 f y ppred \<and> okRead1 g y ppred \<and>
          okRead2 f g x ppred \<and> ppred p \<and> ppred q
      \<longrightarrow> abs(cfn p f - cfn q g) \<le> \<pi> x y"

text\<open>Condition 11: accuracy preservation\<close>
axiomatization where
  acc_prsv:
  "\<forall> ppred p q f x. okRead1 f x ppred \<and> np - maxfaults \<le> count ppred np
          \<and> ppred p \<and> ppred q \<longrightarrow> abs(cfn p f - f q) \<le> \<alpha> x"

subsubsection\<open>Some derived properties of clocks\<close>

lemma rts0d:
assumes cp: "correct p (te p (i+1))"
shows "te p (i+1) - te p i \<le> rmax"
using cp rts0 by simp

lemma rts1d:
assumes cp: "correct p (te p (i+1))"
shows "rmin \<le> te p (i+1) - te p i"
using cp rts1 by simp

lemma rte:
assumes cp: "correct p (te p (i+1))"
shows "te p i \<le> te p (i+1)"
proof-
  from cp rts1d have "rmin \<le> te p (i+1) - te p i"
    by simp
  from this constants_ax show ?thesis by arith
qed

lemma beta_bound1:
assumes corr_p: "correct p (te p (i+1))"
and corr_q: "correct q (te p (i+1))"
shows "0 \<le> te p (i+1) - te q i"
proof-
  from corr_p rte have "te p i \<le> te p (i+1)"
    by simp
  from this corr_p correct_closed have corr_pi: "correct p (te p i)"
    by blast
  from corr_p rts1d nonoverlap have "rmin \<le> te p (i+1) - te p i"
    by simp
  from this nonoverlap have "\<beta> \<le> te p (i+1) - te p i" by simp
  hence "te p i + \<beta> \<le> te p (i+1)" by simp

  from this corr_p corr_q rts2a
  have "te q i \<le> te p (i+1)"
    by blast
  thus ?thesis by simp
qed

lemma beta_bound2:
assumes corr_p: "correct p (te p (i+1))"
and corr_q: "correct q (te q i)"
shows "te p (i+1) - te q i \<le> rmax + \<beta>"
proof-
  from corr_p rte have "te p i \<le> te p (i+1)"
    by simp
  from this corr_p correct_closed have corr_pi: "correct p (te p i)"
    by blast

  have split: "te p (i+1) - te q i =
    (te p (i+1) - te p i) + (te p i - te q i)"
    by (simp)

  from corr_q corr_pi rts2b have Eq1: "abs(te p i - te q i) \<le> \<beta>"
    by simp
  have Eq2: "te p i - te q i \<le> \<beta>"
  proof cases
    assume "te q i \<le> te p i"
    from this Eq1 show ?thesis
      by (simp add: abs_if)
  next
    assume "\<not> (te q i \<le> te p i)"
    from this Eq1 show ?thesis
      by (simp add: abs_if)
  qed

  from corr_p rts0d have "te p (i+1) - te p i \<le> rmax"
    by simp
  from this split Eq2 show ?thesis by simp
qed

subsubsection\<open>Bounded-drift for logical clocks (IC)\<close>

lemma bd:
  assumes ie: "s \<le> t"
  and rb1: "rho_bound1 C"
  and rb2: "rho_bound2 D"
  and PC_ie: "D q t - D q s \<le> C p t - C p s"
  and corr_p: "correct p t"
  and corr_q: "correct q t"
  shows "\<bar> C p t - D q t \<bar>  \<le> \<bar> C p s - D q s \<bar> + 2*\<rho>*(t - s)"
proof-
  let ?Dt = "C p t - D q t"
  let ?Ds = "C p s - D q s"
  let ?Bp = "C p t - C p s"
  let ?Bq = "D q t - D q s"
  let ?I = "t - s"

  have "\<bar> ?Bp - ?Bq \<bar> \<le> 2*\<rho>*(t - s)"
  proof-
    from PC_ie have Eq1: "\<bar> ?Bp - ?Bq \<bar> = ?Bp - ?Bq" by (simp add: abs_if)
    from corr_p ie rb1 have Eq2: "?Bp - ?Bq \<le> ?I*(1+\<rho>) - ?Bq" (is "?E1 \<le> ?E2")
      by(simp add: rho_bound1_def)
    from corr_q ie rb2 have "?I*(1 - \<rho>) \<le> ?Bq"
      by(simp add: rho_bound2_def)
    from this have Eq3: "?E2 \<le> ?I*(1+\<rho>) - ?I*(1 - \<rho>)"
      by(simp)
    have Eq4: "?I*(1+\<rho>) - ?I*(1 - \<rho>) = 2*\<rho>*?I"
      by(simp add: algebra_simps)
    from Eq1 Eq2 Eq3 Eq4 show ?thesis by simp
  qed
  moreover
  have "\<bar>?Dt\<bar>  \<le> \<bar>?Bp - ?Bq\<bar>  + \<bar>?Ds\<bar>"
    by(simp add: abs_if)
  ultimately show ?thesis by simp
qed

lemma bounded_drift:
  assumes ie: "s \<le> t"
  and rb1: "rho_bound1 C"
  and rb2: "rho_bound2 C"
  and rb3: "rho_bound1 D"
  and rb4: "rho_bound2 D"
  and corr_p: "correct p t"
  and corr_q: "correct q t"
  shows "\<bar>C p t - D q t\<bar> \<le> \<bar>C p s - D q s\<bar>  + 2*\<rho>*(t - s)"
proof-
  let ?Bp = "C p t - C p s"
  let ?Bq = "D q t - D q s"

  show ?thesis
  proof cases
    assume "?Bq \<le> ?Bp"
    from this ie rb1 rb4 corr_p corr_q bd show ?thesis by simp
  next
    assume "\<not> (?Bq \<le> ?Bp)"
    hence "?Bp \<le> ?Bq" by simp
    from this ie rb2 rb3 corr_p corr_q bd
    have "\<bar>D q t - C p t\<bar>  \<le> \<bar>D q s - C p s\<bar> + 2*\<rho>*(t - s)"
      by simp
    from this show ?thesis by (simp add: abs_minus_commute)
  qed
qed

text\<open>Drift rate of logical clocks\<close>

lemma IC_rate1:
"rho_bound1 (\<lambda> p t. IC p i t)"
proof-
  {
    fix p::process
    fix s::time
    fix t::time
    assume cp: "correct p t"
    assume ie: "s \<le> t"
    from cp ie correct_closed have cps: "correct p s"
      by blast
    have "IC p i t - IC p i s \<le> (t - s)*(1+\<rho>)"
    proof-
      from cp IClock have "IC p i t = PC p t + Adj p i"
        by simp
      moreover
      from cps IClock have "IC p i s = PC p s + Adj p i"
        by simp
      moreover
      from cp ie rate_1 have "PC p t - PC p s \<le> (t - s)*(1+\<rho>)"
        by simp
      ultimately show ?thesis by simp
    qed
  }
  thus ?thesis by (simp add: rho_bound1_def)
qed

lemma IC_rate2:
"rho_bound2 (\<lambda> p t. IC p i t)"
proof-
  {
    fix p::process
    fix s::time
    fix t::time
    assume cp: "correct p t"
    assume ie: "s \<le> t"
    from cp ie correct_closed have cps: "correct p s"
      by blast
    have "(t - s)*(1 - \<rho>) \<le> IC p i t - IC p i s"
    proof-
      from cp IClock have "IC p i t = PC p t + Adj p i"
        by simp
      moreover
      from cps IClock have "IC p i s = PC p s + Adj p i"
        by simp
      moreover
      from cp ie rate_2 have "(t - s)*(1-\<rho>) \<le> PC p t - PC p s"
        by simp
      ultimately show ?thesis by simp
    qed
  }
  thus ?thesis by (simp add: rho_bound2_def)
qed

text\<open>Auxilary function \<open>ICf\<close>: we introduce this to avoid some
unification problem in some tactic of isabelle.\<close>

definition
  ICf :: "nat \<Rightarrow> (process \<Rightarrow> time \<Rightarrow> Clocktime)" where
  "ICf i = (\<lambda> p t. IC p i t)"

lemma IC_bd:
  assumes ie: "s \<le> t"
  and corr_p: "correct p t"
  and corr_q: "correct q t"
  shows "\<bar>IC p i t - IC q j t\<bar> \<le> \<bar>IC p i s - IC q j s\<bar> + 2*\<rho>*(t - s)"
proof-
  let ?C = "ICf i"
  let ?D = "ICf j"
  let ?G = "\<bar>?C p t - ?D q t\<bar> \<le> \<bar>?C p s - ?D q s\<bar> + 2*\<rho>*(t - s)"

  from IC_rate1 have rb1: "rho_bound1 (ICf i) \<and> rho_bound1 (ICf j)"
    by (simp add: ICf_def)

  from IC_rate2 have rb2: "rho_bound2 (ICf i) \<and> rho_bound2 (ICf j)"
    by (simp add: ICf_def)

  from ie rb1 rb2 corr_p corr_q bounded_drift
  have ?G by simp

  from this show ?thesis by (simp add: ICf_def)
qed

lemma event_bound:
assumes ie1: "0 \<le> (t::real)"
and corr_p: "correct p t"
and corr_q: "correct q t"
shows "\<exists> i. t < max (te p i) (te q i)"
proof (rule ccontr)
  assume A: "\<not> (\<exists> i. t < max (te p i) (te q i))"
  show False
  proof-
    have F1: "\<forall> i. te p i \<le> t"
    proof
      fix i :: nat
      from A have "\<not> (t < max (te p i) (te q i))"
        by simp
      hence Eq1: "max (te p i) (te q i) \<le> t" by arith
      have Eq2: "te p i \<le> max (te p i) (te q i)"
        by (simp add: max_def)
      from Eq1 Eq2 show "te p i \<le> t" by simp
    qed

    have F2: "\<forall> (i :: nat). correct p (te p i)"
    proof
      fix i :: nat
      from F1 have "te p i \<le> t" by simp
      from this corr_p correct_closed
      show "correct p (te p i)" by blast
    qed

    have F3: "\<forall> (i :: nat). real i * rmin \<le> te p i"
    proof
      fix i :: nat
      show "real i * rmin \<le> te p i"
      proof (induct i)
        from synch0 show "real (0::nat) * rmin \<le> te p 0" by simp
      next
        fix i :: nat assume ind_hyp: "real i * rmin \<le> te p i"

        show "real (Suc i) * rmin \<le> te p (Suc i)"
        proof-

          have Eq1: "real i * rmin + rmin = (real i + 1)*rmin"
            by (simp add: distrib_right)
          have Eq2: "real i + 1 = real (i+1)" by simp
          from Eq1 Eq2
          have Eq3: "real i * rmin + rmin = real (i+1) * rmin"
            by presburger

          from F2 have cp1: "correct p (te p (i+1))"
            by simp
          from F2 have cp2: "correct p (te p i)"
            by simp
          from cp1 rts1d have "rmin \<le> te p (i+1) - te p i"
            by simp
          hence Eq4: "te p i + rmin \<le> te p (i+1)" by simp
          from ind_hyp have "real i * rmin + rmin \<le> te p i + rmin"
            by (simp)
          from this Eq4 have "real i * rmin + rmin \<le> te p (i+1)"
            by simp
          from this Eq3 show ?thesis by simp
        qed
      qed
    qed

    have F4: "\<forall> (i::nat). real i * rmin \<le> t"
    proof
      fix i::nat
      from F1 have "te p i \<le> t" by simp
      moreover
      from F3 have "real i * rmin \<le> te p i" by simp
      ultimately show "real i * rmin \<le> t" by simp
    qed

    from constants_ax have "0 < rmin" by simp

    from this reals_Archimedean3
    have Archi: "\<exists> (k::nat). t < real k * rmin"
      by blast

    from Archi obtain k::nat where C: "t < real k * rmin" ..

    from F4 have "real k * rmin \<le> t" by simp
    hence notC: "\<not> (t < real k * rmin)" by simp

    from C notC show False by simp
  qed
qed

subsection\<open>Agreement property\<close>

definition "\<gamma>1 x = \<pi> (2*\<rho>*\<beta> + 2*\<Lambda>) (2*\<Lambda> + x + 2*\<rho>*(rmax + \<beta>))"
definition "\<gamma>2 x = x + 2*\<rho>*rmax"
definition "\<gamma>3 x = \<alpha> (2*\<Lambda> + x + 2*\<rho>*(rmax + \<beta>)) + \<Lambda> + 2*\<rho>*\<beta>"

definition
  okmaxsync :: "[nat, Clocktime] \<Rightarrow> bool" where
  "okmaxsync i x \<longleftrightarrow> (\<forall> p q. correct p (max (te p i) (te q i))
     \<and> correct q (max (te p i) (te q i)) \<longrightarrow>
       \<bar>IC p i (max (te p i) (te q i)) - IC q i (max (te p i) (te q i))\<bar> \<le> x)"

definition
  okClocks :: "[process, process, nat] \<Rightarrow> bool" where
  "okClocks p q i \<longleftrightarrow> (\<forall> t. 0 \<le> t \<and> t < max (te p i) (te q i)
        \<and> correct p t \<and> correct q t
     \<longrightarrow> \<bar>VC p t - VC q t\<bar> \<le> \<delta>)"

lemma okClocks_sym:
assumes ok_pq: "okClocks p q i"
shows "okClocks q p i"
proof-
  {
    fix t :: time
    assume ie1: "0 \<le> t"
    assume ie2: "t < max (te q i) (te p i)"
    assume corr_q: "correct q t"
    assume corr_p: "correct p t"

    have "max (te q i) (te p i) = max (te p i) (te q i)"
      by (simp add: max_def)
    from this ok_pq ie1 ie2 corr_p corr_q
    have "\<bar>VC q t - VC p t\<bar> \<le> \<delta>"
      by(simp add: abs_minus_commute okClocks_def)
  }
  thus ?thesis by (simp add: okClocks_def)
qed

lemma ICp_Suc:
assumes corr_p: "correct p (te p (i+1))"
shows "IC p (i+1) (te p (i+1)) = cfn p (\<theta> p (i+1)) "
using corr_p IClock by(simp add: Adj_def)

lemma IC_trans_inv:
assumes ie1: "te q (i+1) \<le> te p (i+1)"
and corr_p: "correct p (te p (i+1))"
and corr_q: "correct q (te p (i+1))"
shows
"IC q (i+1) (te p (i+1)) =
  cfn q (\<lambda> n. \<theta> q (i+1) n + (PC q (te p (i+1)) - PC q (te q (i+1))))"
(is "?T1 = ?T2")
proof-
  let ?X = "PC q (te p (i+1)) - PC q (te q (i+1))"

  from corr_q ie1 PC_monotone have posX: "0 \<le> ?X"
    by (simp add: le_diff_eq)
  from IClock corr_q have "?T1 = cfn q (\<theta> q (i+1)) + ?X"
    by(simp add: Adj_def)

  from this posX trans_inv show ?thesis by simp
qed

lemma beta_rho:
assumes ie: "te q (i+1) \<le> te p (i+1)"
and corr_p: "correct p (te p (i+1))"
and corr_q: "correct q (te p (i+1))"
and corr_l: "correct l (te p (i+1))"
shows "\<bar>(PC l (te p (i+1)) - PC l (te q (i+1))) - (te p (i+1) - te q (i+1))\<bar> \<le> \<beta>*\<rho>"
proof-
  let ?X = "(PC l (te p (i+1)) - PC l (te q (i+1)))"
  let ?D = "te p (i+1) - te q (i+1)"

  from ie have posD: "0 \<le> ?D" by simp

  from ie PC_monotone corr_l have posX: "0 \<le> ?X"
    by (simp add: le_diff_eq)
  from ie corr_l rate_1 have bound1: "?X \<le> ?D * (1 + \<rho>)" by simp
  from ie corr_l correct_closed have corr_l_tq: "correct l (te q (i+1))"
    by(blast)
  from ie corr_q correct_closed have corr_q_tq: "correct q (te q (i+1))"
    by blast
  from corr_q_tq corr_p rts2b have "\<bar>?D\<bar> \<le> \<beta>"
    by(simp)
  from this constants_ax posD have D_beta: "?D*\<rho> \<le> \<beta>*\<rho>"
    by(simp add: abs_if)

  show ?thesis
  proof cases
    assume A: "?D \<le> ?X"
    from posX posD A have absEq: "\<bar>?X - ?D\<bar> = ?X - ?D"
      by(simp add: abs_if)
    from bound1 have bound2: "?X - ?D \<le> ?D*\<rho>"
      by(simp add: mult.commute distrib_right)
    from D_beta absEq bound2 show ?thesis by simp
  next
    assume notA: "\<not> (?D \<le> ?X)"
    from this have absEq2: "\<bar>?X - ?D\<bar> = ?D - ?X"
      by(simp add: abs_if)
    from ie corr_l rate_2 have bound3: "?D*(1 - \<rho>) \<le> ?X" by simp
    from this have "?D - ?X \<le> ?D*\<rho>" by (simp add: algebra_simps)
    from this absEq2 D_beta show ?thesis by simp
  qed
qed

text\<open>This lemma (and the next one pe-cond2) proves an assumption used
in the precision enhancement.\<close>

lemma pe_cond1:
assumes ie: "te q (i+1) \<le> te p (i+1)"
and corr_p: "correct p (te p (i+1))"
and corr_q: "correct q (te p (i + 1))"
and corr_l: "correct l (te p (i+1))"
shows "\<bar>\<theta> q (i+1) l + (PC q (te p (i+1)) - PC q (te q (i+1))) -
           \<theta> p (i+1) l\<bar> \<le> 2* \<rho> * \<beta> + 2*\<Lambda>"
(is "?M \<le> ?N")
proof-
  let ?Xl = "(PC l (te p (i+1)) - PC l (te q (i+1)))"
  let ?Xq = "(PC q (te p (i+1)) - PC q (te q (i+1)))"
  let ?D = "te p (i+1) - te q (i+1)"
  let ?T = "\<theta> p (i+1) l - \<theta> q (i+1) l"
  let ?RE1 = "\<theta> p (i+1) l - IC l i (te p (i+1))"
  let ?RE2 = "\<theta> q (i+1) l - IC l i (te q (i+1))"
  let ?ICT = "IC l i (te p (i+1)) - IC l i (te q (i+1))"

  have "?M = \<bar>(?Xq - ?D) - (?T - ?D)\<bar>"
  by(simp add: abs_if)

  hence Split: "?M \<le> \<bar>?Xq - ?D\<bar> + \<bar>?T - ?D\<bar>"
    by(simp add: abs_if)

  from ie corr_q correct_closed have corr_q_tq: "correct q (te q (i+1))"
    by(blast)
  from ie corr_l correct_closed have corr_l_tq: "correct l (te q (i+1))"
    by blast

  from corr_p corr_q corr_l ie beta_rho
  have XlD: "\<bar>?Xl - ?D\<bar> \<le> \<beta>*\<rho>"
    by simp

  from corr_p corr_q ie beta_rho
  have XqD: "\<bar>?Xq - ?D\<bar> \<le> \<beta>*\<rho>" by simp

  have TD: "\<bar>?T - ?D\<bar> \<le> 2*\<Lambda> + \<beta>*\<rho>"
  proof-
    have Eq1: "\<bar>?T - ?D\<bar> = \<bar>(?T - ?ICT) + (?ICT - ?D)\<bar>" (is "?E1 = ?E2")
      by (simp add: abs_if)

    have Eq2: "?E2 \<le> \<bar>?T - ?ICT\<bar> + \<bar>?ICT - ?D\<bar>"
      by(simp add: abs_if)

    have Eq3: "\<bar>?T - ?ICT\<bar> \<le>  \<bar>?RE1\<bar> + \<bar>?RE2\<bar>"
      by(simp add: abs_if)

    from readerror corr_p corr_l
    have Eq4: "\<bar>?RE1\<bar> \<le> \<Lambda>" by simp

    from corr_l_tq corr_q_tq this readerror
    have Eq5: "\<bar>?RE2\<bar> \<le> \<Lambda>" by simp

    from Eq3 Eq4 Eq5 have Eq6: "\<bar>?T - ?ICT\<bar> \<le> 2*\<Lambda>"
      by simp

    have Eq7: "?ICT - ?D = ?Xl - ?D"
    proof-
      from corr_p rte have "te p i \<le> te p (i+1)"
        by(simp)
      from this corr_l correct_closed have corr_l_tpi: "correct l (te p i)"
        by blast
      from corr_q_tq rte have "te q i \<le> te q (i+1)"
        by simp
      from this corr_l_tq correct_closed have corr_l_tqi: "correct l (te q i)"
        by blast

      from IClock corr_l
      have F1: "IC l i (te p (i+1)) = PC l (te p (i+1)) + Adj l i"
        by(simp)
      from IClock corr_l_tq
      have F2: "IC l i (te q (i+1)) = PC l (te q (i+1)) + Adj l i"
        by simp
      from F1 F2 show ?thesis by(simp)
    qed

    from this XlD have Eq8: "\<bar>?ICT - ?D\<bar> \<le> \<beta>*\<rho>"
      by arith
    from Eq1 Eq2 Eq6 Eq8 show ?thesis
      by(simp)
  qed

  from Split XqD TD have F1: "?M \<le> 2* \<beta> * \<rho> + 2*\<Lambda>"
    by(simp)
  have F2: "2 * \<rho> * \<beta> + 2*\<Lambda> = 2* \<beta> * \<rho> + 2*\<Lambda>"
    by simp
  from F1 show ?thesis by (simp only: F2)

qed

lemma pe_cond2:
assumes ie: "te m i \<le> te l i"
and corr_k: "correct k (te k (i+1))"
and corr_l_tk: "correct l (te k (i+1))"
and corr_m_tk: "correct m (te k (i+1))"
and ind_hyp: "\<bar>IC l i (te l i) - IC m i (te l i)\<bar> \<le> \<delta>S"
shows "\<bar>\<theta> k (i+1) l - \<theta> k (i+1) m\<bar> \<le> 2*\<Lambda> + \<delta>S + 2*\<rho>*(rmax + \<beta>)"
proof-
  let ?X = "\<theta> k (i+1) l - \<theta> k (i+1) m"
  let ?N = "2*\<Lambda> + \<delta>S + 2*\<rho>*(rmax + \<beta>)"
  let ?D1 = "\<theta> k (i+1) l - IC l i (te k (i+1))"
  let ?D2 = "\<theta> k (i+1) m - IC m i (te k (i+1))"
  let ?ICS = "IC l i (te k (i+1)) - IC m i (te k (i+1))"
  let ?tlm = "te l i"
  let ?IC = "IC l i ?tlm - IC m i ?tlm"

  have Eq1: "\<bar>?X\<bar> = \<bar>(?D1 - ?D2) + ?ICS\<bar>" (is "?E1 = ?E2")
    by (simp add: abs_if)

  have Eq2: "?E2 \<le> \<bar>?D1 - ?D2\<bar> + \<bar>?ICS\<bar>" by (simp add: abs_if)

  from corr_l_tk corr_k beta_bound1 have ie_lk: "te l i \<le> te k (i+1)"
    by (simp add: le_diff_eq)

  from this corr_l_tk correct_closed have corr_l: "correct l (te l i)"
    by blast

  from ie_lk corr_l_tk corr_m_tk IC_bd
  have Eq3: "\<bar>?ICS\<bar> \<le> \<bar>?IC\<bar> + 2*\<rho>*(te k (i+1) - ?tlm)"
    by simp
  from this ind_hyp have Eq4: "\<bar>?ICS\<bar> \<le> \<delta>S + 2*\<rho>*(te k (i+1) - ?tlm)"
    by simp

  from corr_l corr_k beta_bound2 have "te k (i+1) - ?tlm \<le> rmax + \<beta>"
    by simp
  from this constants_ax have "2*\<rho>*(te k (i+1) - ?tlm) \<le> 2*\<rho>*(rmax + \<beta>)"
    by (simp add: real_mult_le_cancel_iff2)
  from this Eq4 have Eq4a: "\<bar>?ICS\<bar> \<le> \<delta>S + 2*\<rho>*(rmax + \<beta>)"
    by (simp)

  from corr_k corr_l_tk readerror
  have Eq5: "\<bar>?D1\<bar> \<le> \<Lambda>" by simp
  from corr_k corr_m_tk readerror
  have Eq6: "\<bar>?D2\<bar> \<le> \<Lambda>" by simp
  have "\<bar>?D1 - ?D2\<bar> \<le> \<bar>?D1\<bar> + \<bar>?D2\<bar>" by (simp add: abs_if)
  from this Eq5 Eq6 have Eq7: "\<bar>?D1 - ?D2\<bar> \<le> 2*\<Lambda>"
    by (simp)

  from Eq1 Eq2 Eq4a Eq7 split show ?thesis by (simp)
qed

lemma theta_bound:
assumes corr_l: "correct l (te p (i+1))"
and corr_m: "correct m (te p (i+1))"
and corr_p: "correct p (te p (i+1))"
and IC_bound:
    "\<bar>IC l i (max (te l i) (te m i)) - IC m i (max (te l i) (te m i))\<bar>
      \<le> \<delta>S"
shows "\<bar>\<theta> p (i+1) l - \<theta> p (i+1) m\<bar>
       \<le>  2*\<Lambda> + \<delta>S + 2*\<rho>*(rmax + \<beta>)"
proof-
  from corr_p corr_l beta_bound1 have tli_le_tp: "te l i \<le> te p (i+1)"
    by (simp add: le_diff_eq)
  from corr_p corr_m beta_bound1 have tmi_le_tp: "te m i \<le> te p (i+1)"
    by (simp add: le_diff_eq)

  let ?tml = "max (te l i) (te m i)"
  from tli_le_tp tmi_le_tp have tml_le_tp: "?tml \<le> te p (i+1)"
    by simp

  from tml_le_tp corr_l correct_closed have corr_l_tml: "correct l ?tml"
    by blast
  from tml_le_tp corr_m correct_closed have corr_m_tml: "correct m ?tml"
    by blast

  let ?Y = "2*\<Lambda> + \<delta>S + 2*\<rho>*(rmax + \<beta>)"
  show "\<bar>\<theta> p (i+1) l - \<theta> p (i+1) m\<bar> \<le> ?Y"
  proof cases
    assume A: "te m i < te l i"

    from this IC_bound
    have "\<bar>IC l i (te l i) - IC m i (te l i)\<bar> \<le> \<delta>S"
      by(simp add: max_def)
    from this A corr_p corr_l corr_m pe_cond2
    show ?thesis by(simp)
  next
    assume "\<not> (te m i < te l i)"
    hence Eq1: "te l i \<le> te m i" by simp
    from this IC_bound
    have Eq2: "\<bar>IC l i (te m i) - IC m i (te m i)\<bar> \<le> \<delta>S"
      by(simp add: max_def)

    hence "\<bar>IC m i (te m i) - IC l i (te m i)\<bar> \<le> \<delta>S"
      by (simp add: abs_minus_commute)
    from this Eq1 corr_p corr_l corr_m pe_cond2
    have "\<bar>\<theta> p (i+1) m - \<theta> p (i+1) l\<bar> \<le> ?Y"
      by(simp)
    thus ?thesis by (simp add: abs_minus_commute)
  qed
qed

lemma four_one_ind_half:
  assumes ie1: "\<beta> \<le> rmin"
  and ie2: "\<mu> \<le> \<delta>S"
  and ie3: "\<gamma>1 \<delta>S \<le> \<delta>S"
  and ind_hyp: "okmaxsync i \<delta>S"
  and ie4: "te q (i+1) \<le> te p (i+1)"
  and corr_p: "correct p (te p (i+1))"
  and corr_q: "correct q (te p (i+1))"
shows "\<bar>IC p (i+1) (te p (i+1)) - IC q (i+1) (te p (i+1))\<bar> \<le> \<delta>S"
proof-
  let ?tpq = "te p (i+1)"

  let ?f = "\<lambda> n. \<theta> q (i+1) n + (PC q (te p (i+1)) - PC q (te q (i+1)))"
  let ?g = "\<theta> p (i+1)"

  from ie4 corr_q correct_closed have corr_q_tq: "correct q (te q (i+1))"
    by blast

  have Eq_IC_cfn: "\<bar>IC p (i+1) ?tpq - IC q (i+1) ?tpq\<bar> =
    \<bar>cfn q ?f - cfn p ?g\<bar>"
  proof-
    from corr_p ICp_Suc have Eq1: "IC p (i+1) ?tpq = cfn p ?g" by simp

    from ie4 corr_p corr_q IC_trans_inv
    have Eq2: "IC q (i+1) ?tpq = cfn q ?f" by simp

    from Eq1 Eq2 show ?thesis by(simp add: abs_if)
  qed

  let ?ppred = "\<lambda> l. correct l (te p (i+1))"

  let ?X = "2*\<rho>*\<beta> + 2*\<Lambda>"
  have "\<forall> l. ?ppred l \<longrightarrow> \<bar>?f l - ?g l\<bar> \<le> ?X"
  proof -
    {
      fix l
      assume "?ppred l"
      from ie4 corr_p corr_q this pe_cond1
      have "\<bar>?f l - ?g l\<bar> \<le> (2*\<rho>*\<beta> + 2*\<Lambda>)"
        by(auto)
    }
    thus ?thesis by blast
  qed
  hence cond1: "okRead2 ?f ?g ?X ?ppred"
    by(simp add: okRead2_def)

  let ?Y = "2*\<Lambda> + \<delta>S + 2*\<rho>*(rmax + \<beta>)"

  have "\<forall> l m. ?ppred l \<and> ?ppred m \<longrightarrow> \<bar>?f l - ?f m\<bar> \<le> ?Y"
  proof-
    {
      fix l m
      assume corr_l: "?ppred l"
      assume corr_m: "?ppred m"

      from corr_p corr_l beta_bound1 have tli_le_tp: "te l i \<le> te p (i+1)"
        by (simp add: le_diff_eq)
      from corr_p corr_m beta_bound1 have tmi_le_tp: "te m i \<le> te p (i+1)"
        by (simp add: le_diff_eq)

      let ?tlm = "max (te l i) (te m i)"

      from tli_le_tp tmi_le_tp have tlm_le_tp: "?tlm \<le> te p (i+1)"
        by simp

      from ie4 corr_l correct_closed have corr_l_tq: "correct l (te q (i+1))"
        by blast
      from ie4 corr_m correct_closed have corr_m_tq: "correct m (te q (i+1))"
        by blast
      from tlm_le_tp corr_l correct_closed have corr_l_tlm: "correct l ?tlm"
        by blast
      from tlm_le_tp corr_m correct_closed have corr_m_tlm: "correct m ?tlm"
        by blast

      from ind_hyp corr_l_tlm corr_m_tlm
      have EqAbs1: "\<bar>IC l i ?tlm - IC m i ?tlm\<bar> \<le> \<delta>S"
        by(auto simp add: okmaxsync_def)

      have EqAbs3: "\<bar>?f l - ?f m\<bar> = \<bar>\<theta> q (i+1) l - \<theta> q (i+1) m\<bar>"
        by (simp add: abs_if)

      from EqAbs1 corr_q_tq corr_l_tq corr_m_tq theta_bound
      have "\<bar>\<theta> q (i+1) l - \<theta> q (i+1) m\<bar> \<le> ?Y"
        by simp
      from this EqAbs3  have "\<bar>?f l - ?f m\<bar> \<le> ?Y"
        by simp
    }
    thus ?thesis by simp
  qed
  hence cond2a: "okRead1 ?f ?Y ?ppred" by (simp add: okRead1_def)

  have "\<forall> l m. ?ppred l \<and> ?ppred m \<longrightarrow> \<bar>?g l - ?g m\<bar> \<le> ?Y"
  proof-
    {
      fix l m
      assume corr_l: "?ppred l"
      assume corr_m: "?ppred m"

      from corr_p corr_l beta_bound1 have tli_le_tp: "te l i \<le> te p (i+1)"
        by (simp add: le_diff_eq)
      from corr_p corr_m beta_bound1 have tmi_le_tp: "te m i \<le> te p (i+1)"
        by (simp add: le_diff_eq)

      let ?tlm = "max (te l i) (te m i)"
      from tli_le_tp tmi_le_tp have tlm_le_tp: "?tlm \<le> te p (i+1)"
        by simp

      from tlm_le_tp corr_l correct_closed have corr_l_tlm: "correct l ?tlm"
        by blast
      from tlm_le_tp corr_m correct_closed have corr_m_tlm: "correct m ?tlm"
        by blast

      from ind_hyp corr_l_tlm corr_m_tlm
      have EqAbs1: "\<bar>IC l i ?tlm - IC m i ?tlm\<bar> \<le> \<delta>S"
        by(auto simp add: okmaxsync_def)

      from EqAbs1 corr_p corr_l corr_m theta_bound
      have "\<bar>?g l - ?g m\<bar> \<le> ?Y" by simp
    }
    thus ?thesis by simp
  qed
  hence cond2b: "okRead1 ?g ?Y ?ppred" by (simp add: okRead1_def)

  from correct_count have "np - maxfaults \<le> count ?ppred np"
    by simp
  from this corr_p corr_q cond1 cond2a cond2b prec_enh
  have "\<bar>cfn q ?f - cfn p ?g\<bar> \<le> \<pi> ?X ?Y"
    by blast

  from ie3 this have "\<bar>cfn q ?f - cfn p ?g\<bar> \<le> \<delta>S"
    by (simp add: \<gamma>1_def)

  from this Eq_IC_cfn show ?thesis by (simp)
qed

text\<open>Theorem 4.1 in Shankar's paper.\<close>

theorem four_one:
  assumes ie1: "\<beta> \<le> rmin"
  and ie2: "\<mu> \<le> \<delta>S"
  and ie3: "\<gamma>1 \<delta>S \<le> \<delta>S"
shows "okmaxsync i \<delta>S"
proof(induct i)
  show "okmaxsync 0 \<delta>S"
  proof-
    {
      fix p q
      assume corr_p: "correct p (max (te p 0) (te q 0))"
      assume corr_q: "correct q (max (te p 0) (te q 0))"

      from corr_p synch0 have cp0: "correct p 0" by simp
      from corr_q synch0 have cq0: "correct q 0" by simp

      from synch0 cp0 cq0 IClock
      have IC_eq_PC:
        "\<bar>IC p 0 (max (te p 0) (te q 0)) - IC q 0 (max (te p 0) (te q 0))\<bar>
         = \<bar>PC p 0 - PC q 0\<bar>" (is "?T1 = ?T2")
        by(simp add: Adj_def)

      from ie2 init synch0 cp0 have range1: "0 \<le> PC p 0 \<and> PC p 0 \<le> \<delta>S"
        by auto
      from ie2 init synch0 cq0 have range2: "0 \<le> PC q 0 \<and> PC q 0 \<le> \<delta>S"
        by auto
      have "?T2 \<le> \<delta>S"
      proof cases
        assume A:"PC p 0 < PC q 0"
        from A range1 range2 show ?thesis
          by(auto simp add: abs_if)
      next
        assume notA: "\<not> (PC p 0 < PC q 0)"
        from notA range1 range2 show ?thesis
          by(auto simp add: abs_if)
      qed
      from this IC_eq_PC have "?T1 \<le> \<delta>S" by simp
    }
    thus ?thesis by (simp add: okmaxsync_def)
  qed
next
  fix i assume ind_hyp: "okmaxsync i \<delta>S"
  show "okmaxsync (Suc i) \<delta>S"
  proof-
    {
      fix p q
      assume corr_p: "correct p (max (te p (i + 1)) (te q (i + 1)))"
      assume corr_q: "correct q (max (te p (i + 1)) (te q (i + 1)))"
      let ?tp = "te p (i + 1)"
      let ?tq = "te q (i + 1)"
      let ?tpq = "max ?tp ?tq"

      have "\<bar>IC p (i+1) ?tpq - IC q (i+1) ?tpq\<bar> \<le> \<delta>S" (is "?E1 \<le> \<delta>S")
      proof cases
        assume A: "?tq < ?tp"
        from A corr_p have cp1: "correct p (te p (i+1))"
          by (simp add: max_def)
        from A corr_q have cq1: "correct q (te p (i+1))"
          by (simp add: max_def)
        from A
        have Eq1: "?E1 = \<bar>IC p (i+1) (te p (i+1)) - IC q (i+1) (te p (i+1))\<bar>"
                  (is "?E1 = ?E2")
          by (simp add: max_def)
        from A cp1 cq1 corr_p corr_q ind_hyp ie1 ie2 ie3
          four_one_ind_half
        have "?E2 \<le> \<delta>S" by (simp)
        from this Eq1 show ?thesis by simp
      next
        assume notA: "\<not> (?tq < ?tp)"
        from this corr_p have cp2: "correct p (te q (i+1))"
          by (simp add: max_def)
        from notA corr_q have cq2: "correct q (te q (i+1))"
          by (simp add: max_def)
        from notA
        have Eq2: "?E1 = \<bar>IC q (i+1) (te q (i+1)) - IC p (i+1) (te q (i+1))\<bar>"
                  (is "?E1  = ?E3")
          by (simp add: max_def abs_minus_commute)
        from notA have "?tp \<le> ?tq" by simp
        from this cp2 cq2 ind_hyp ie1 ie2 ie3 four_one_ind_half
        have "?E3 \<le> \<delta>S"
          by simp
        from this Eq2 show ?thesis by (simp)
      qed
    }
    thus ?thesis by (simp add: okmaxsync_def)
  qed
qed

lemma VC_cfn:
  assumes corr_p: "correct p (te p (i+1))"
  and ie: "te p (i+1) < te p (i+2)"
shows "VC p (te p (i+1)) = cfn p (\<theta> p (i+1))"
proof-
  from ie corr_p VClock have "VC p (te p (i+1)) = IC p (i+1) (te p (i+1))"
    by simp
  moreover
  from corr_p IClock
  have "IC p (i+1) (te p (i+1)) = PC p (te p (i+1)) + Adj p (i+1)"
    by blast
  moreover
  have "PC p (te p (i+1)) + Adj p (i+1) = cfn p (\<theta> p (i+1))"
    by(simp add: Adj_def)
  ultimately show ?thesis by simp
qed

text\<open>Lemma for the inductive case in Theorem 4.2\<close>

lemma four_two_ind:
  assumes ie1: "\<beta> \<le> rmin"
  and ie2: "\<mu> \<le> \<delta>S"
  and ie3: "\<gamma>1 \<delta>S \<le> \<delta>S"
  and ie4: "\<gamma>2 \<delta>S \<le> \<delta>"
  and ie5: "\<gamma>3 \<delta>S \<le> \<delta>"
  and ie6: "te q (i+1) \<le> te p (i+1)"
  and ind_hyp: "okClocks p q i"
  and t_bound1: "0 \<le> t"
  and t_bound2: "t < max (te p (i+1)) (te q (i+1))"
  and t_bound3: "max (te p i) (te q i) \<le> t"
  and tpq_bound: "max (te p i) (te q i) < max (te p (i+1)) (te q (i+1))"
  and corr_p: "correct p t"
  and corr_q: "correct q t"
shows "\<bar>VC p t - VC q t\<bar> \<le> \<delta>"
proof cases
  assume A: "t < te q (i+1)"

  let ?tpq = "max (te p i) (te q i)"

  have Eq1: "te p i \<le> t \<and> te q i \<le> t"
  proof cases
    assume "te p i \<le> te q i"
    from this  t_bound3 show ?thesis by (simp add: max_def)
  next
    assume "\<not> (te p i \<le> te q i)"
    from this t_bound3 show ?thesis by (simp add: max_def)
  qed

  from ie6 have tp_max: "max (te p (i+1)) (te q (i+1)) = te p (i+1)"
    by(simp add: max_def)
  from this t_bound2 have Eq2: "t < te p (i+1)" by simp

  from VClock Eq1 Eq2 corr_p have Eq3: "VC p t = IC p i t" by simp

  from VClock Eq1 A corr_q have Eq4: "VC q t = IC q i t" by simp
  from Eq3 Eq4 have Eq5: "\<bar>VC p t - VC q t\<bar> = \<bar>IC p i t - IC q i t\<bar>"
    by simp

  from t_bound3 corr_p corr_q correct_closed
  have corr_tpq: "correct p ?tpq \<and> correct q ?tpq"
    by(blast)

  from t_bound3 IC_bd corr_p corr_q
  have Eq6: "\<bar>IC p i t - IC q i t\<bar>  \<le> \<bar>IC p i ?tpq - IC q i ?tpq\<bar>
    + 2*\<rho>*(t - ?tpq)" (is "?E1 \<le> ?E2")
    by(blast)

  from ie1 ie2 ie3 four_one have "okmaxsync i \<delta>S" by simp

  from this corr_tpq have "\<bar>IC p i ?tpq - IC q i ?tpq\<bar> \<le> \<delta>S"
    by(simp add: okmaxsync_def)

  from Eq6 this  have Eq7: "?E1 \<le> \<delta>S + 2*\<rho>*(t - ?tpq)" by simp

  from corr_p Eq2 rts0 have "t - te p i \<le> rmax" by simp
  from this have "t - ?tpq \<le> rmax" by (simp add: max_def)
  from this constants_ax have "2*\<rho>*(t - ?tpq) \<le> 2*\<rho>*rmax"
    by (simp add: real_mult_le_cancel_iff1)
  hence "\<delta>S + 2*\<rho>*(t - ?tpq) \<le> \<delta>S + 2*\<rho>*rmax"
    by simp
  from this Eq7 have "?E1 \<le> \<delta>S + 2*\<rho>*rmax" by simp
  from this Eq5 ie4 show ?thesis by(simp add: \<gamma>2_def)
next
  assume "\<not> (t < te q (i+1))"
  hence  B: "te q (i+1) \<le> t" by simp

  from ie6 t_bound2
  have tp_max: "max (te p (i+1)) (te q (i+1)) = te p (i+1)"
    by(simp add: max_def)

  have "te p i \<le> max (te p i) (te q i)"
    by(simp add: max_def)

  from this t_bound3 have tp_bound1: "te p i \<le> t" by simp

  from tp_max t_bound2 have tp_bound2: "t < te p (i+1)" by simp

  have tq_bound1: "t < te q (i+2)"
  proof (rule ccontr)
    assume "\<not> (t < te q (i+2))"
    hence C: "te q (i+2) \<le> t" by simp

    from C corr_q correct_closed
    have corr_q_t2: "correct q (te q (i+2))" by blast

    have "te q (i+1) + \<beta> \<le> t"
    proof-
      from corr_q_t2 rts1d have "rmin \<le> te q (i+2) - te q (i+1)"
        by simp
      from this ie1 have "\<beta> \<le> te q (i+2) - te q (i+1)"
        by simp
      hence "te q (i+1) + \<beta> \<le> te q (i+2)" by simp
      from this C show ?thesis by simp
    qed
    from this corr_p corr_q rts2a have "te p (i+1) \<le> t"
      by blast
    hence "\<not> (t < te p (i+1))" by simp
    from this tp_bound2 show False by simp
  qed

  from tq_bound1 B have tq_bound2: "te q (i+1) < te q (i+2)" by simp
  from B tp_bound2 have tq_bound3: "te q (i+1) < te p (i+1)"
    by simp
  from B corr_p correct_closed
  have corr_p_tq1: "correct p (te q (i+1))" by blast

  from B correct_closed corr_q
  have corr_q_tq1: "correct q (te q (i+1))" by blast

  from corr_p_tq1 corr_q_tq1 beta_bound1
  have tq_bound4: "te p i \<le> te q (i+1)"
    by(simp add: le_diff_eq)

  from tq_bound1 VClock B corr_q
  have Eq1: "VC q t = IC q (i+1) t" by simp

  from VClock tp_bound1 tp_bound2 corr_p
  have Eq2: "VC p t = IC p i t" by simp

  from Eq1 Eq2 have Eq3: "\<bar>VC p t - VC q t\<bar> = \<bar>IC p i t - IC q (i+1) t\<bar>"
    by simp

  from B corr_p corr_q IC_bd
  have "\<bar>IC p i t - IC q (i+1) t\<bar> \<le>
     \<bar>IC p i (te q (i+1)) - IC q (i+1) (te q (i+1))\<bar> + 2*\<rho>*(t - te q (i+1))"
    by simp

  from this Eq3
  have VC_split: "\<bar>VC p t - VC q t\<bar> \<le>
    \<bar>IC p i (te q (i+1)) - IC q (i+1) (te q (i+1))\<bar> + 2*\<rho>*(t - te q (i+1))"
    by simp

  from tq_bound2 VClock corr_q_tq1
  have Eq4: "VC q (te q (i+1)) = IC q (i+1) (te q (i+1))" by simp

  from this tq_bound2 VC_cfn corr_q_tq1
  have Eq5: "IC q (i+1) (te q (i+1)) = cfn q (\<theta> q (i+1))" by simp

  hence IC_eq_cfn: "IC p i (te q (i+1)) - IC q (i+1) (te q (i+1)) =
    IC p i (te q (i+1)) - cfn q (\<theta> q (i+1))"
    (is "?E1 = ?E2")
    by simp

  let ?f = "\<theta> q (i+1)"
  let ?ppred = "\<lambda> l. correct l (te q (i+1))"
  let ?X = "2*\<Lambda> + \<delta>S + 2*\<rho>*(rmax + \<beta>)"

  have "\<forall> l m. ?ppred l \<and> ?ppred m \<longrightarrow> \<bar>\<theta> q (i+1) l - \<theta> q (i+1) m\<bar> \<le> ?X"
  proof-
    {
      fix l :: process
      fix m :: process
      assume corr_l: "?ppred l"
      assume corr_m: "?ppred m"

      let ?tlm = "max (te l i) (te m i)"
      have tlm_bound: "?tlm \<le> te q (i+1)"
      proof-
        from corr_l corr_q_tq1 beta_bound1 have "te l i \<le> te q (i+1)"
          by (simp add: le_diff_eq)
        moreover
        from corr_m corr_q_tq1 beta_bound1 have "te m i \<le> te q (i+1)"
          by (simp add: le_diff_eq)
        ultimately show ?thesis by simp
      qed

      from tlm_bound corr_l corr_m correct_closed
      have corr_tlm: "correct l ?tlm \<and> correct m ?tlm"
        by blast

      have "\<bar>IC l i ?tlm - IC m i ?tlm\<bar> \<le> \<delta>S"
      proof-
        from ie1 ie2 ie3 four_one  have "okmaxsync i \<delta>S"
          by simp
        from this corr_tlm show ?thesis by(simp add: okmaxsync_def)
      qed

      from this corr_l corr_m corr_q_tq1 theta_bound
      have "\<bar>\<theta> q (i+1) l - \<theta> q (i+1) m\<bar> \<le> ?X" by simp
    }
    thus ?thesis by blast
  qed
  hence readOK: "okRead1 (\<theta> q (i+1)) ?X ?ppred"
    by(simp add: okRead1_def)

  let ?E3 = "cfn q (\<theta> q (i+1)) - \<theta> q (i+1) p"
  let ?E4 = "\<theta> q (i+1) p - IC p i (te q (i+1))"

  have "\<bar>?E2\<bar> = \<bar>?E3 + ?E4\<bar>" by (simp add: abs_if)
  hence Eq8: "\<bar>?E2\<bar> \<le> \<bar>?E3\<bar> + \<bar>?E4\<bar>" by (simp add: abs_if)

  from correct_count have ppredOK: "np - maxfaults \<le> count ?ppred np"
    by simp
  from readOK ppredOK corr_p_tq1 corr_q_tq1 acc_prsv
  have "\<bar>?E3\<bar> \<le> \<alpha> ?X"
    by blast
  from this Eq8 have Eq9: "\<bar>?E2\<bar> \<le> \<alpha> ?X + \<bar>?E4\<bar>" by simp

  from corr_p_tq1 corr_q_tq1 readerror
  have "\<bar>?E4\<bar> \<le> \<Lambda>" by simp

  from this Eq9 have Eq10: "\<bar>?E2\<bar> \<le> \<alpha> ?X + \<Lambda>" by simp

  from this VC_split IC_eq_cfn
  have almost_right:
    "\<bar>VC p t - VC q t\<bar> \<le>
     \<alpha> ?X + \<Lambda> + 2*\<rho>*(t - te q (i+1))"
    by simp

  have "t - te q (i+1) \<le> \<beta>"
  proof (rule ccontr)
    assume "\<not> (t - te q (i+1) \<le> \<beta>)"
    hence "te q (i+1) + \<beta> \<le> t" by simp
    from this corr_p corr_q rts2a have "te p (i+1) \<le> t"
      by auto
    hence "\<not> (t < te p (i+1))" by simp
    from this tp_bound2 show False
      by simp
  qed

  from this constants_ax
  have "\<alpha> ?X + \<Lambda> + 2*\<rho>*(t - te q (i+1))
        \<le> \<alpha> ?X + \<Lambda> + 2*\<rho>*\<beta>"
    by (simp)

  from this almost_right
  have "\<bar>VC p t - VC q t\<bar> \<le> \<alpha> ?X + \<Lambda> + 2*\<rho>*\<beta>"
    by arith

  from this ie5 show ?thesis by (simp add: \<gamma>3_def)
qed

text\<open>Theorem 4.2 in Shankar's paper.\<close>

theorem four_two:
  assumes ie1: "\<beta> \<le> rmin"
  and ie2: "\<mu> \<le> \<delta>S"
  and ie3: "\<gamma>1 \<delta>S \<le> \<delta>S"
  and ie4: "\<gamma>2 \<delta>S \<le> \<delta>"
  and ie5: "\<gamma>3 \<delta>S \<le> \<delta>"
shows "okClocks p q i"
proof (induct i)
  show "okClocks p q 0"
  proof-
    {
      fix t :: time
      assume t_bound1: "0 \<le> t"
      assume t_bound2: "t < max (te p 0) (te q 0)"
      assume corr_p: "correct p t"
      assume corr_q: "correct q t"
      from t_bound2 synch0 have "t < 0"
        by(simp add: max_def)
      from this t_bound1 have False by simp
      hence "\<bar>VC p t - VC q t\<bar> \<le> \<delta>" by simp
    }
    thus ?thesis by (simp add: okClocks_def)
  qed
next
  fix i::nat assume ind_hyp: "okClocks p q i"
  show "okClocks p q (Suc i)"
  proof -
    {
      fix t :: time
      assume t_bound1: "0 \<le> t"
      assume t_bound2: "t < max (te p (i+1)) (te q (i+1))"
      assume corr_p: "correct p t"
      assume corr_q: "correct q t"

      let ?tpq1 = "max (te p i) (te q i)"
      let ?tpq2 = "max (te p (i+1)) (te q (i+1))"

      have "\<bar>VC p t - VC q t\<bar> \<le> \<delta>"
      proof cases
        assume tpq_bound: "?tpq1 < ?tpq2"
        show ?thesis
        proof cases
          assume "t < ?tpq1"
          from t_bound1 this  corr_p corr_q ind_hyp
          show ?thesis by(simp add: okClocks_def)
        next
          assume "\<not> (t < ?tpq1)"
          hence tpq_le_t: "?tpq1 \<le> t" by arith

          show ?thesis
          proof cases
            assume A: "te q (i+1) \<le> te p (i+1)"

            from this tpq_le_t tpq_bound ie1 ie2 ie3 ie4 ie5
              ind_hyp t_bound1 t_bound2
              corr_p corr_q tpq_bound four_two_ind
            show ?thesis by(simp)
          next
            assume "\<not> (te q (i+1) \<le> te p (i+1))"
            hence B: "te p (i+1) \<le> te q (i+1)" by simp

            from ind_hyp okClocks_sym have ind_hyp1: "okClocks q p i"
              by blast

            have maxsym1: "max (te p (i+1)) (te q (i+1)) = max (te q (i+1)) (te p (i+1))"
              by (simp add: max_def)
            have maxsym2: "max (te p i) (te q i) = max (te q i) (te p i)"
              by (simp add: max_def)

            from maxsym1 t_bound2
            have t_bound21: "t < max (te q (i+1)) (te p (i+1))"
              by simp

            from maxsym1 maxsym2 tpq_bound
            have tpq_bound1: "max (te q i) (te p i) < max (te q (i+1)) (te p (i+1))"
              by simp
            from maxsym2 tpq_le_t
            have tpq_le_t1: "max (te q i) (te p i) \<le> t" by simp

            from B tpq_le_t1 tpq_bound1 ie1 ie2 ie3 ie4 ie5
              ind_hyp1 t_bound1 t_bound21
              corr_p corr_q tpq_bound four_two_ind
            have "\<bar>VC q t - VC p t\<bar> \<le> \<delta>" by(simp)
            thus ?thesis by (simp add: abs_minus_commute)
          qed

        qed
      next
        assume "\<not> (?tpq1 < ?tpq2)"
        hence "?tpq2 \<le> ?tpq1" by arith
        from t_bound2 this have "t < ?tpq1" by arith
        from t_bound1 this corr_p corr_q ind_hyp
        show ?thesis by(simp add: okClocks_def)
      qed
    }
    thus ?thesis by (simp add: okClocks_def)
  qed
qed

text\<open>The main theorem: all correct clocks are synchronized within the
bound delta.\<close>

theorem agreement:
  assumes ie1: "\<beta> \<le> rmin"
  and ie2: "\<mu> \<le> \<delta>S"
  and ie3: "\<gamma>1 \<delta>S \<le> \<delta>S"
  and ie4: "\<gamma>2 \<delta>S \<le> \<delta>"
  and ie5: "\<gamma>3 \<delta>S \<le> \<delta>"
  and ie6: "0 \<le> t"
  and cpq: "correct p t \<and> correct q t"
shows "\<bar>VC p t - VC q t\<bar> \<le> \<delta>"
proof-
  from ie6 cpq event_bound have "\<exists> i :: nat. t < max (te p i) (te q i)"
    by simp
  from this obtain i  :: nat where t_bound: "t < max (te p i) (te q i)" ..

  from t_bound ie1 ie2 ie3 ie4 ie5 four_two have "okClocks p q i"
    by simp

  from ie6 this t_bound cpq show ?thesis
    by (simp add: okClocks_def)
qed

end


(*  Title:       HOL/Zorn.thy
    Author:      Jacques D. Fleuriot
    Author:      Tobias Nipkow, TUM
    Author:      Christian Sternagel, JAIST

Zorn's Lemma (ported from Larry Paulson's Zorn.thy in ZF).
The well-ordering theorem.
*)

section \<open>Zorn's Lemma\<close>

theory Zorn
  imports Order_Relation Hilbert_Choice
begin

subsection \<open>Zorn's Lemma for the Subset Relation\<close>

subsubsection \<open>Results that do not require an order\<close>

text \<open>Let \<open>P\<close> be a binary predicate on the set \<open>A\<close>.\<close>
locale pred_on =
  fixes A :: "'a set"
    and P :: "'a \<Rightarrow> 'a \<Rightarrow> bool"  (infix "\<sqsubset>" 50)
begin

abbreviation Peq :: "'a \<Rightarrow> 'a \<Rightarrow> bool"  (infix "\<sqsubseteq>" 50)
  where "x \<sqsubseteq> y \<equiv> P\<^sup>=\<^sup>= x y"

text \<open>A chain is a totally ordered subset of \<open>A\<close>.\<close>
definition chain :: "'a set \<Rightarrow> bool"
  where "chain C \<longleftrightarrow> C \<subseteq> A \<and> (\<forall>x\<in>C. \<forall>y\<in>C. x \<sqsubseteq> y \<or> y \<sqsubseteq> x)"

text \<open>
  We call a chain that is a proper superset of some set \<open>X\<close>,
  but not necessarily a chain itself, a superchain of \<open>X\<close>.
\<close>
abbreviation superchain :: "'a set \<Rightarrow> 'a set \<Rightarrow> bool"  (infix "<c" 50)
  where "X <c C \<equiv> chain C \<and> X \<subset> C"

text \<open>A maximal chain is a chain that does not have a superchain.\<close>
definition maxchain :: "'a set \<Rightarrow> bool"
  where "maxchain C \<longleftrightarrow> chain C \<and> (\<nexists>S. C <c S)"

text \<open>
  We define the successor of a set to be an arbitrary
  superchain, if such exists, or the set itself, otherwise.
\<close>
definition suc :: "'a set \<Rightarrow> 'a set"
  where "suc C = (if \<not> chain C \<or> maxchain C then C else (SOME D. C <c D))"

lemma chainI [Pure.intro?]: "C \<subseteq> A \<Longrightarrow> (\<And>x y. x \<in> C \<Longrightarrow> y \<in> C \<Longrightarrow> x \<sqsubseteq> y \<or> y \<sqsubseteq> x) \<Longrightarrow> chain C"
  unfolding chain_def by blast

lemma chain_total: "chain C \<Longrightarrow> x \<in> C \<Longrightarrow> y \<in> C \<Longrightarrow> x \<sqsubseteq> y \<or> y \<sqsubseteq> x"
  by (simp add: chain_def)

lemma not_chain_suc [simp]: "\<not> chain X \<Longrightarrow> suc X = X"
  by (simp add: suc_def)

lemma maxchain_suc [simp]: "maxchain X \<Longrightarrow> suc X = X"
  by (simp add: suc_def)

lemma suc_subset: "X \<subseteq> suc X"
  by (auto simp: suc_def maxchain_def intro: someI2)

lemma chain_empty [simp]: "chain {}"
  by (auto simp: chain_def)

lemma not_maxchain_Some: "chain C \<Longrightarrow> \<not> maxchain C \<Longrightarrow> C <c (SOME D. C <c D)"
  by (rule someI_ex) (auto simp: maxchain_def)

lemma suc_not_equals: "chain C \<Longrightarrow> \<not> maxchain C \<Longrightarrow> suc C \<noteq> C"
  using not_maxchain_Some by (auto simp: suc_def)

lemma subset_suc:
  assumes "X \<subseteq> Y"
  shows "X \<subseteq> suc Y"
  using assms by (rule subset_trans) (rule suc_subset)

text \<open>
  We build a set @{term \<C>} that is closed under applications
  of @{term suc} and contains the union of all its subsets.
\<close>
inductive_set suc_Union_closed ("\<C>")
  where
    suc: "X \<in> \<C> \<Longrightarrow> suc X \<in> \<C>"
  | Union [unfolded Pow_iff]: "X \<in> Pow \<C> \<Longrightarrow> \<Union>X \<in> \<C>"

text \<open>
  Since the empty set as well as the set itself is a subset of
  every set, @{term \<C>} contains at least @{term "{} \<in> \<C>"} and
  @{term "\<Union>\<C> \<in> \<C>"}.
\<close>
lemma suc_Union_closed_empty: "{} \<in> \<C>"
  and suc_Union_closed_Union: "\<Union>\<C> \<in> \<C>"
  using Union [of "{}"] and Union [of "\<C>"] by simp_all

text \<open>Thus closure under @{term suc} will hit a maximal chain
  eventually, as is shown below.\<close>

lemma suc_Union_closed_induct [consumes 1, case_names suc Union, induct pred: suc_Union_closed]:
  assumes "X \<in> \<C>"
    and "\<And>X. X \<in> \<C> \<Longrightarrow> Q X \<Longrightarrow> Q (suc X)"
    and "\<And>X. X \<subseteq> \<C> \<Longrightarrow> \<forall>x\<in>X. Q x \<Longrightarrow> Q (\<Union>X)"
  shows "Q X"
  using assms by induct blast+

lemma suc_Union_closed_cases [consumes 1, case_names suc Union, cases pred: suc_Union_closed]:
  assumes "X \<in> \<C>"
    and "\<And>Y. X = suc Y \<Longrightarrow> Y \<in> \<C> \<Longrightarrow> Q"
    and "\<And>Y. X = \<Union>Y \<Longrightarrow> Y \<subseteq> \<C> \<Longrightarrow> Q"
  shows "Q"
  using assms by cases simp_all

text \<open>On chains, @{term suc} yields a chain.\<close>
lemma chain_suc:
  assumes "chain X"
  shows "chain (suc X)"
  using assms
  by (cases "\<not> chain X \<or> maxchain X") (force simp: suc_def dest: not_maxchain_Some)+

lemma chain_sucD:
  assumes "chain X"
  shows "suc X \<subseteq> A \<and> chain (suc X)"
proof -
  from \<open>chain X\<close> have *: "chain (suc X)"
    by (rule chain_suc)
  then have "suc X \<subseteq> A"
    unfolding chain_def by blast
  with * show ?thesis by blast
qed

lemma suc_Union_closed_total':
  assumes "X \<in> \<C>" and "Y \<in> \<C>"
    and *: "\<And>Z. Z \<in> \<C> \<Longrightarrow> Z \<subseteq> Y \<Longrightarrow> Z = Y \<or> suc Z \<subseteq> Y"
  shows "X \<subseteq> Y \<or> suc Y \<subseteq> X"
  using \<open>X \<in> \<C>\<close>
proof induct
  case (suc X)
  with * show ?case by (blast del: subsetI intro: subset_suc)
next
  case Union
  then show ?case by blast
qed

lemma suc_Union_closed_subsetD:
  assumes "Y \<subseteq> X" and "X \<in> \<C>" and "Y \<in> \<C>"
  shows "X = Y \<or> suc Y \<subseteq> X"
  using assms(2,3,1)
proof (induct arbitrary: Y)
  case (suc X)
  note * = \<open>\<And>Y. Y \<in> \<C> \<Longrightarrow> Y \<subseteq> X \<Longrightarrow> X = Y \<or> suc Y \<subseteq> X\<close>
  with suc_Union_closed_total' [OF \<open>Y \<in> \<C>\<close> \<open>X \<in> \<C>\<close>]
  have "Y \<subseteq> X \<or> suc X \<subseteq> Y" by blast
  then show ?case
  proof
    assume "Y \<subseteq> X"
    with * and \<open>Y \<in> \<C>\<close> have "X = Y \<or> suc Y \<subseteq> X" by blast
    then show ?thesis
    proof
      assume "X = Y"
      then show ?thesis by simp
    next
      assume "suc Y \<subseteq> X"
      then have "suc Y \<subseteq> suc X" by (rule subset_suc)
      then show ?thesis by simp
    qed
  next
    assume "suc X \<subseteq> Y"
    with \<open>Y \<subseteq> suc X\<close> show ?thesis by blast
  qed
next
  case (Union X)
  show ?case
  proof (rule ccontr)
    assume "\<not> ?thesis"
    with \<open>Y \<subseteq> \<Union>X\<close> obtain x y z
      where "\<not> suc Y \<subseteq> \<Union>X"
        and "x \<in> X" and "y \<in> x" and "y \<notin> Y"
        and "z \<in> suc Y" and "\<forall>x\<in>X. z \<notin> x" by blast
    with \<open>X \<subseteq> \<C>\<close> have "x \<in> \<C>" by blast
    from Union and \<open>x \<in> X\<close> have *: "\<And>y. y \<in> \<C> \<Longrightarrow> y \<subseteq> x \<Longrightarrow> x = y \<or> suc y \<subseteq> x"
      by blast
    with suc_Union_closed_total' [OF \<open>Y \<in> \<C>\<close> \<open>x \<in> \<C>\<close>] have "Y \<subseteq> x \<or> suc x \<subseteq> Y"
      by blast
    then show False
    proof
      assume "Y \<subseteq> x"
      with * [OF \<open>Y \<in> \<C>\<close>] have "x = Y \<or> suc Y \<subseteq> x" by blast
      then show False
      proof
        assume "x = Y"
        with \<open>y \<in> x\<close> and \<open>y \<notin> Y\<close> show False by blast
      next
        assume "suc Y \<subseteq> x"
        with \<open>x \<in> X\<close> have "suc Y \<subseteq> \<Union>X" by blast
        with \<open>\<not> suc Y \<subseteq> \<Union>X\<close> show False by contradiction
      qed
    next
      assume "suc x \<subseteq> Y"
      moreover from suc_subset and \<open>y \<in> x\<close> have "y \<in> suc x" by blast
      ultimately show False using \<open>y \<notin> Y\<close> by blast
    qed
  qed
qed

text \<open>The elements of @{term \<C>} are totally ordered by the subset relation.\<close>
lemma suc_Union_closed_total:
  assumes "X \<in> \<C>" and "Y \<in> \<C>"
  shows "X \<subseteq> Y \<or> Y \<subseteq> X"
proof (cases "\<forall>Z\<in>\<C>. Z \<subseteq> Y \<longrightarrow> Z = Y \<or> suc Z \<subseteq> Y")
  case True
  with suc_Union_closed_total' [OF assms]
  have "X \<subseteq> Y \<or> suc Y \<subseteq> X" by blast
  with suc_subset [of Y] show ?thesis by blast
next
  case False
  then obtain Z where "Z \<in> \<C>" and "Z \<subseteq> Y" and "Z \<noteq> Y" and "\<not> suc Z \<subseteq> Y"
    by blast
  with suc_Union_closed_subsetD and \<open>Y \<in> \<C>\<close> show ?thesis
    by blast
qed

text \<open>Once we hit a fixed point w.r.t. @{term suc}, all other elements
  of @{term \<C>} are subsets of this fixed point.\<close>
lemma suc_Union_closed_suc:
  assumes "X \<in> \<C>" and "Y \<in> \<C>" and "suc Y = Y"
  shows "X \<subseteq> Y"
  using \<open>X \<in> \<C>\<close>
proof induct
  case (suc X)
  with \<open>Y \<in> \<C>\<close> and suc_Union_closed_subsetD have "X = Y \<or> suc X \<subseteq> Y"
    by blast
  then show ?case
    by (auto simp: \<open>suc Y = Y\<close>)
next
  case Union
  then show ?case by blast
qed

lemma eq_suc_Union:
  assumes "X \<in> \<C>"
  shows "suc X = X \<longleftrightarrow> X = \<Union>\<C>"
    (is "?lhs \<longleftrightarrow> ?rhs")
proof
  assume ?lhs
  then have "\<Union>\<C> \<subseteq> X"
    by (rule suc_Union_closed_suc [OF suc_Union_closed_Union \<open>X \<in> \<C>\<close>])
  with \<open>X \<in> \<C>\<close> show ?rhs
    by blast
next
  from \<open>X \<in> \<C>\<close> have "suc X \<in> \<C>" by (rule suc)
  then have "suc X \<subseteq> \<Union>\<C>" by blast
  moreover assume ?rhs
  ultimately have "suc X \<subseteq> X" by simp
  moreover have "X \<subseteq> suc X" by (rule suc_subset)
  ultimately show ?lhs ..
qed

lemma suc_in_carrier:
  assumes "X \<subseteq> A"
  shows "suc X \<subseteq> A"
  using assms
  by (cases "\<not> chain X \<or> maxchain X") (auto dest: chain_sucD)

lemma suc_Union_closed_in_carrier:
  assumes "X \<in> \<C>"
  shows "X \<subseteq> A"
  using assms
  by induct (auto dest: suc_in_carrier)

text \<open>All elements of @{term \<C>} are chains.\<close>
lemma suc_Union_closed_chain:
  assumes "X \<in> \<C>"
  shows "chain X"
  using assms
proof induct
  case (suc X)
  then show ?case
    using not_maxchain_Some by (simp add: suc_def)
next
  case (Union X)
  then have "\<Union>X \<subseteq> A"
    by (auto dest: suc_Union_closed_in_carrier)
  moreover have "\<forall>x\<in>\<Union>X. \<forall>y\<in>\<Union>X. x \<sqsubseteq> y \<or> y \<sqsubseteq> x"
  proof (intro ballI)
    fix x y
    assume "x \<in> \<Union>X" and "y \<in> \<Union>X"
    then obtain u v where "x \<in> u" and "u \<in> X" and "y \<in> v" and "v \<in> X"
      by blast
    with Union have "u \<in> \<C>" and "v \<in> \<C>" and "chain u" and "chain v"
      by blast+
    with suc_Union_closed_total have "u \<subseteq> v \<or> v \<subseteq> u"
      by blast
    then show "x \<sqsubseteq> y \<or> y \<sqsubseteq> x"
    proof
      assume "u \<subseteq> v"
      from \<open>chain v\<close> show ?thesis
      proof (rule chain_total)
        show "y \<in> v" by fact
        show "x \<in> v" using \<open>u \<subseteq> v\<close> and \<open>x \<in> u\<close> by blast
      qed
    next
      assume "v \<subseteq> u"
      from \<open>chain u\<close> show ?thesis
      proof (rule chain_total)
        show "x \<in> u" by fact
        show "y \<in> u" using \<open>v \<subseteq> u\<close> and \<open>y \<in> v\<close> by blast
      qed
    qed
  qed
  ultimately show ?case unfolding chain_def ..
qed

subsubsection \<open>Hausdorff's Maximum Principle\<close>

text \<open>There exists a maximal totally ordered subset of \<open>A\<close>. (Note that we do not
  require \<open>A\<close> to be partially ordered.)\<close>

theorem Hausdorff: "\<exists>C. maxchain C"
proof -
  let ?M = "\<Union>\<C>"
  have "maxchain ?M"
  proof (rule ccontr)
    assume "\<not> ?thesis"
    then have "suc ?M \<noteq> ?M"
      using suc_not_equals and suc_Union_closed_chain [OF suc_Union_closed_Union] by simp
    moreover have "suc ?M = ?M"
      using eq_suc_Union [OF suc_Union_closed_Union] by simp
    ultimately show False by contradiction
  qed
  then show ?thesis by blast
qed

text \<open>Make notation @{term \<C>} available again.\<close>
no_notation suc_Union_closed  ("\<C>")

lemma chain_extend: "chain C \<Longrightarrow> z \<in> A \<Longrightarrow> \<forall>x\<in>C. x \<sqsubseteq> z \<Longrightarrow> chain ({z} \<union> C)"
  unfolding chain_def by blast

lemma maxchain_imp_chain: "maxchain C \<Longrightarrow> chain C"
  by (simp add: maxchain_def)

end

text \<open>Hide constant @{const pred_on.suc_Union_closed}, which was just needed
  for the proof of Hausforff's maximum principle.\<close>
hide_const pred_on.suc_Union_closed

lemma chain_mono:
  assumes "\<And>x y. x \<in> A \<Longrightarrow> y \<in> A \<Longrightarrow> P x y \<Longrightarrow> Q x y"
    and "pred_on.chain A P C"
  shows "pred_on.chain A Q C"
  using assms unfolding pred_on.chain_def by blast

subsubsection \<open>Results for the proper subset relation\<close>

interpretation subset: pred_on "A" "op \<subset>" for A .

lemma subset_maxchain_max:
  assumes "subset.maxchain A C"
    and "X \<in> A"
    and "\<Union>C \<subseteq> X"
  shows "\<Union>C = X"
proof (rule ccontr)
  let ?C = "{X} \<union> C"
  from \<open>subset.maxchain A C\<close> have "subset.chain A C"
    and *: "\<And>S. subset.chain A S \<Longrightarrow> \<not> C \<subset> S"
    by (auto simp: subset.maxchain_def)
  moreover have "\<forall>x\<in>C. x \<subseteq> X" using \<open>\<Union>C \<subseteq> X\<close> by auto
  ultimately have "subset.chain A ?C"
    using subset.chain_extend [of A C X] and \<open>X \<in> A\<close> by auto
  moreover assume **: "\<Union>C \<noteq> X"
  moreover from ** have "C \<subset> ?C" using \<open>\<Union>C \<subseteq> X\<close> by auto
  ultimately show False using * by blast
qed

subsubsection \<open>Zorn's lemma\<close>

text \<open>If every chain has an upper bound, then there is a maximal set.\<close>
lemma subset_Zorn:
  assumes "\<And>C. subset.chain A C \<Longrightarrow> \<exists>U\<in>A. \<forall>X\<in>C. X \<subseteq> U"
  shows "\<exists>M\<in>A. \<forall>X\<in>A. M \<subseteq> X \<longrightarrow> X = M"
proof -
  from subset.Hausdorff [of A] obtain M where "subset.maxchain A M" ..
  then have "subset.chain A M"
    by (rule subset.maxchain_imp_chain)
  with assms obtain Y where "Y \<in> A" and "\<forall>X\<in>M. X \<subseteq> Y"
    by blast
  moreover have "\<forall>X\<in>A. Y \<subseteq> X \<longrightarrow> Y = X"
  proof (intro ballI impI)
    fix X
    assume "X \<in> A" and "Y \<subseteq> X"
    show "Y = X"
    proof (rule ccontr)
      assume "\<not> ?thesis"
      with \<open>Y \<subseteq> X\<close> have "\<not> X \<subseteq> Y" by blast
      from subset.chain_extend [OF \<open>subset.chain A M\<close> \<open>X \<in> A\<close>] and \<open>\<forall>X\<in>M. X \<subseteq> Y\<close>
      have "subset.chain A ({X} \<union> M)"
        using \<open>Y \<subseteq> X\<close> by auto
      moreover have "M \<subset> {X} \<union> M"
        using \<open>\<forall>X\<in>M. X \<subseteq> Y\<close> and \<open>\<not> X \<subseteq> Y\<close> by auto
      ultimately show False
        using \<open>subset.maxchain A M\<close> by (auto simp: subset.maxchain_def)
    qed
  qed
  ultimately show ?thesis by blast
qed

text \<open>Alternative version of Zorn's lemma for the subset relation.\<close>
lemma subset_Zorn':
  assumes "\<And>C. subset.chain A C \<Longrightarrow> \<Union>C \<in> A"
  shows "\<exists>M\<in>A. \<forall>X\<in>A. M \<subseteq> X \<longrightarrow> X = M"
proof -
  from subset.Hausdorff [of A] obtain M where "subset.maxchain A M" ..
  then have "subset.chain A M"
    by (rule subset.maxchain_imp_chain)
  with assms have "\<Union>M \<in> A" .
  moreover have "\<forall>Z\<in>A. \<Union>M \<subseteq> Z \<longrightarrow> \<Union>M = Z"
  proof (intro ballI impI)
    fix Z
    assume "Z \<in> A" and "\<Union>M \<subseteq> Z"
    with subset_maxchain_max [OF \<open>subset.maxchain A M\<close>]
      show "\<Union>M = Z" .
  qed
  ultimately show ?thesis by blast
qed

subsection \<open>Zorn's Lemma for Partial Orders\<close>

text \<open>Relate old to new definitions.\<close>

definition chain_subset :: "'a set set \<Rightarrow> bool"  ("chain\<^sub>\<subseteq>")  (* Define globally? In Set.thy? *)
  where "chain\<^sub>\<subseteq> C \<longleftrightarrow> (\<forall>A\<in>C. \<forall>B\<in>C. A \<subseteq> B \<or> B \<subseteq> A)"

definition chains :: "'a set set \<Rightarrow> 'a set set set"
  where "chains A = {C. C \<subseteq> A \<and> chain\<^sub>\<subseteq> C}"

definition Chains :: "('a \<times> 'a) set \<Rightarrow> 'a set set"  (* Define globally? In Relation.thy? *)
  where "Chains r = {C. \<forall>a\<in>C. \<forall>b\<in>C. (a, b) \<in> r \<or> (b, a) \<in> r}"

lemma chains_extend: "c \<in> chains S \<Longrightarrow> z \<in> S \<Longrightarrow> \<forall>x \<in> c. x \<subseteq> z \<Longrightarrow> {z} \<union> c \<in> chains S"
  for z :: "'a set"
  unfolding chains_def chain_subset_def by blast

lemma mono_Chains: "r \<subseteq> s \<Longrightarrow> Chains r \<subseteq> Chains s"
  unfolding Chains_def by blast

lemma chain_subset_alt_def: "chain\<^sub>\<subseteq> C = subset.chain UNIV C"
  unfolding chain_subset_def subset.chain_def by fast

lemma chains_alt_def: "chains A = {C. subset.chain A C}"
  by (simp add: chains_def chain_subset_alt_def subset.chain_def)

lemma Chains_subset: "Chains r \<subseteq> {C. pred_on.chain UNIV (\<lambda>x y. (x, y) \<in> r) C}"
  by (force simp add: Chains_def pred_on.chain_def)

lemma Chains_subset':
  assumes "refl r"
  shows "{C. pred_on.chain UNIV (\<lambda>x y. (x, y) \<in> r) C} \<subseteq> Chains r"
  using assms
  by (auto simp add: Chains_def pred_on.chain_def refl_on_def)

lemma Chains_alt_def:
  assumes "refl r"
  shows "Chains r = {C. pred_on.chain UNIV (\<lambda>x y. (x, y) \<in> r) C}"
  using assms Chains_subset Chains_subset' by blast

lemma Zorn_Lemma: "\<forall>C\<in>chains A. \<Union>C \<in> A \<Longrightarrow> \<exists>M\<in>A. \<forall>X\<in>A. M \<subseteq> X \<longrightarrow> X = M"
  using subset_Zorn' [of A] by (force simp: chains_alt_def)

lemma Zorn_Lemma2: "\<forall>C\<in>chains A. \<exists>U\<in>A. \<forall>X\<in>C. X \<subseteq> U \<Longrightarrow> \<exists>M\<in>A. \<forall>X\<in>A. M \<subseteq> X \<longrightarrow> X = M"
  using subset_Zorn [of A] by (auto simp: chains_alt_def)

text \<open>Various other lemmas\<close>

lemma chainsD: "c \<in> chains S \<Longrightarrow> x \<in> c \<Longrightarrow> y \<in> c \<Longrightarrow> x \<subseteq> y \<or> y \<subseteq> x"
  unfolding chains_def chain_subset_def by blast

lemma chainsD2: "c \<in> chains S \<Longrightarrow> c \<subseteq> S"
  unfolding chains_def by blast

lemma Zorns_po_lemma:
  assumes po: "Partial_order r"
    and u: "\<forall>C\<in>Chains r. \<exists>u\<in>Field r. \<forall>a\<in>C. (a, u) \<in> r"
  shows "\<exists>m\<in>Field r. \<forall>a\<in>Field r. (m, a) \<in> r \<longrightarrow> a = m"
proof -
  have "Preorder r"
    using po by (simp add: partial_order_on_def)
  txt \<open>Mirror \<open>r\<close> in the set of subsets below (wrt \<open>r\<close>) elements of \<open>A\<close>.\<close>
  let ?B = "\<lambda>x. r\<inverse> `` {x}"
  let ?S = "?B ` Field r"
  have "\<exists>u\<in>Field r. \<forall>A\<in>C. A \<subseteq> r\<inverse> `` {u}"  (is "\<exists>u\<in>Field r. ?P u")
    if 1: "C \<subseteq> ?S" and 2: "\<forall>A\<in>C. \<forall>B\<in>C. A \<subseteq> B \<or> B \<subseteq> A" for C
  proof -
    let ?A = "{x\<in>Field r. \<exists>M\<in>C. M = ?B x}"
    from 1 have "C = ?B ` ?A" by (auto simp: image_def)
    have "?A \<in> Chains r"
    proof (simp add: Chains_def, intro allI impI, elim conjE)
      fix a b
      assume "a \<in> Field r" and "?B a \<in> C" and "b \<in> Field r" and "?B b \<in> C"
      with 2 have "?B a \<subseteq> ?B b \<or> ?B b \<subseteq> ?B a" by auto
      then show "(a, b) \<in> r \<or> (b, a) \<in> r"
        using \<open>Preorder r\<close> and \<open>a \<in> Field r\<close> and \<open>b \<in> Field r\<close>
        by (simp add:subset_Image1_Image1_iff)
    qed
    with u obtain u where uA: "u \<in> Field r" "\<forall>a\<in>?A. (a, u) \<in> r" by auto
    have "?P u"
    proof auto
      fix a B assume aB: "B \<in> C" "a \<in> B"
      with 1 obtain x where "x \<in> Field r" and "B = r\<inverse> `` {x}" by auto
      then show "(a, u) \<in> r"
        using uA and aB and \<open>Preorder r\<close>
        unfolding preorder_on_def refl_on_def by simp (fast dest: transD)
    qed
    then show ?thesis
      using \<open>u \<in> Field r\<close> by blast
  qed
  then have "\<forall>C\<in>chains ?S. \<exists>U\<in>?S. \<forall>A\<in>C. A \<subseteq> U"
    by (auto simp: chains_def chain_subset_def)
  from Zorn_Lemma2 [OF this] obtain m B
    where "m \<in> Field r"
      and "B = r\<inverse> `` {m}"
      and "\<forall>x\<in>Field r. B \<subseteq> r\<inverse> `` {x} \<longrightarrow> r\<inverse> `` {x} = B"
    by auto
  then have "\<forall>a\<in>Field r. (m, a) \<in> r \<longrightarrow> a = m"
    using po and \<open>Preorder r\<close> and \<open>m \<in> Field r\<close>
    by (auto simp: subset_Image1_Image1_iff Partial_order_eq_Image1_Image1_iff)
  then show ?thesis
    using \<open>m \<in> Field r\<close> by blast
qed

subsection \<open>The Well Ordering Theorem\<close>

(* The initial segment of a relation appears generally useful.
   Move to Relation.thy?
   Definition correct/most general?
   Naming?
*)
definition init_seg_of :: "(('a \<times> 'a) set \<times> ('a \<times> 'a) set) set"
  where "init_seg_of = {(r, s). r \<subseteq> s \<and> (\<forall>a b c. (a, b) \<in> s \<and> (b, c) \<in> r \<longrightarrow> (a, b) \<in> r)}"

abbreviation initial_segment_of_syntax :: "('a \<times> 'a) set \<Rightarrow> ('a \<times> 'a) set \<Rightarrow> bool"
    (infix "initial'_segment'_of" 55)
  where "r initial_segment_of s \<equiv> (r, s) \<in> init_seg_of"

lemma refl_on_init_seg_of [simp]: "r initial_segment_of r"
  by (simp add: init_seg_of_def)

lemma trans_init_seg_of:
  "r initial_segment_of s \<Longrightarrow> s initial_segment_of t \<Longrightarrow> r initial_segment_of t"
  by (simp (no_asm_use) add: init_seg_of_def) blast

lemma antisym_init_seg_of: "r initial_segment_of s \<Longrightarrow> s initial_segment_of r \<Longrightarrow> r = s"
  unfolding init_seg_of_def by safe

lemma Chains_init_seg_of_Union: "R \<in> Chains init_seg_of \<Longrightarrow> r\<in>R \<Longrightarrow> r initial_segment_of \<Union>R"
  by (auto simp: init_seg_of_def Ball_def Chains_def) blast

lemma chain_subset_trans_Union:
  assumes "chain\<^sub>\<subseteq> R" "\<forall>r\<in>R. trans r"
  shows "trans (\<Union>R)"
proof (intro transI, elim UnionE)
  fix S1 S2 :: "'a rel" and x y z :: 'a
  assume "S1 \<in> R" "S2 \<in> R"
  with assms(1) have "S1 \<subseteq> S2 \<or> S2 \<subseteq> S1"
    unfolding chain_subset_def by blast
  moreover assume "(x, y) \<in> S1" "(y, z) \<in> S2"
  ultimately have "((x, y) \<in> S1 \<and> (y, z) \<in> S1) \<or> ((x, y) \<in> S2 \<and> (y, z) \<in> S2)"
    by blast
  with \<open>S1 \<in> R\<close> \<open>S2 \<in> R\<close> assms(2) show "(x, z) \<in> \<Union>R"
    by (auto elim: transE)
qed

lemma chain_subset_antisym_Union:
  assumes "chain\<^sub>\<subseteq> R" "\<forall>r\<in>R. antisym r"
  shows "antisym (\<Union>R)"
proof (intro antisymI, elim UnionE)
  fix S1 S2 :: "'a rel" and x y :: 'a
  assume "S1 \<in> R" "S2 \<in> R"
  with assms(1) have "S1 \<subseteq> S2 \<or> S2 \<subseteq> S1"
    unfolding chain_subset_def by blast
  moreover assume "(x, y) \<in> S1" "(y, x) \<in> S2"
  ultimately have "((x, y) \<in> S1 \<and> (y, x) \<in> S1) \<or> ((x, y) \<in> S2 \<and> (y, x) \<in> S2)"
    by blast
  with \<open>S1 \<in> R\<close> \<open>S2 \<in> R\<close> assms(2) show "x = y"
    unfolding antisym_def by auto
qed

lemma chain_subset_Total_Union:
  assumes "chain\<^sub>\<subseteq> R" and "\<forall>r\<in>R. Total r"
  shows "Total (\<Union>R)"
proof (simp add: total_on_def Ball_def, auto del: disjCI)
  fix r s a b
  assume A: "r \<in> R" "s \<in> R" "a \<in> Field r" "b \<in> Field s" "a \<noteq> b"
  from \<open>chain\<^sub>\<subseteq> R\<close> and \<open>r \<in> R\<close> and \<open>s \<in> R\<close> have "r \<subseteq> s \<or> s \<subseteq> r"
    by (auto simp add: chain_subset_def)
  then show "(\<exists>r\<in>R. (a, b) \<in> r) \<or> (\<exists>r\<in>R. (b, a) \<in> r)"
  proof
    assume "r \<subseteq> s"
    then have "(a, b) \<in> s \<or> (b, a) \<in> s"
      using assms(2) A mono_Field[of r s]
      by (auto simp add: total_on_def)
    then show ?thesis
      using \<open>s \<in> R\<close> by blast
  next
    assume "s \<subseteq> r"
    then have "(a, b) \<in> r \<or> (b, a) \<in> r"
      using assms(2) A mono_Field[of s r]
      by (fastforce simp add: total_on_def)
    then show ?thesis
      using \<open>r \<in> R\<close> by blast
  qed
qed

lemma wf_Union_wf_init_segs:
  assumes "R \<in> Chains init_seg_of"
    and "\<forall>r\<in>R. wf r"
  shows "wf (\<Union>R)"
proof (simp add: wf_iff_no_infinite_down_chain, rule ccontr, auto)
  fix f
  assume 1: "\<forall>i. \<exists>r\<in>R. (f (Suc i), f i) \<in> r"
  then obtain r where "r \<in> R" and "(f (Suc 0), f 0) \<in> r" by auto
  have "(f (Suc i), f i) \<in> r" for i
  proof (induct i)
    case 0
    show ?case by fact
  next
    case (Suc i)
    then obtain s where s: "s \<in> R" "(f (Suc (Suc i)), f(Suc i)) \<in> s"
      using 1 by auto
    then have "s initial_segment_of r \<or> r initial_segment_of s"
      using assms(1) \<open>r \<in> R\<close> by (simp add: Chains_def)
    with Suc s show ?case by (simp add: init_seg_of_def) blast
  qed
  then show False
    using assms(2) and \<open>r \<in> R\<close>
    by (simp add: wf_iff_no_infinite_down_chain) blast
qed

lemma initial_segment_of_Diff: "p initial_segment_of q \<Longrightarrow> p - s initial_segment_of q - s"
  unfolding init_seg_of_def by blast

lemma Chains_inits_DiffI: "R \<in> Chains init_seg_of \<Longrightarrow> {r - s |r. r \<in> R} \<in> Chains init_seg_of"
  unfolding Chains_def by (blast intro: initial_segment_of_Diff)

theorem well_ordering: "\<exists>r::'a rel. Well_order r \<and> Field r = UNIV"
proof -
\<comment> \<open>The initial segment relation on well-orders:\<close>
  let ?WO = "{r::'a rel. Well_order r}"
  define I where "I = init_seg_of \<inter> ?WO \<times> ?WO"
  then have I_init: "I \<subseteq> init_seg_of" by simp
  then have subch: "\<And>R. R \<in> Chains I \<Longrightarrow> chain\<^sub>\<subseteq> R"
    unfolding init_seg_of_def chain_subset_def Chains_def by blast
  have Chains_wo: "\<And>R r. R \<in> Chains I \<Longrightarrow> r \<in> R \<Longrightarrow> Well_order r"
    by (simp add: Chains_def I_def) blast
  have FI: "Field I = ?WO"
    by (auto simp add: I_def init_seg_of_def Field_def)
  then have 0: "Partial_order I"
    by (auto simp: partial_order_on_def preorder_on_def antisym_def antisym_init_seg_of refl_on_def
        trans_def I_def elim!: trans_init_seg_of)
\<comment> \<open>\<open>I\<close>-chains have upper bounds in \<open>?WO\<close> wrt \<open>I\<close>: their Union\<close>
  have "\<Union>R \<in> ?WO \<and> (\<forall>r\<in>R. (r, \<Union>R) \<in> I)" if "R \<in> Chains I" for R
  proof -
    from that have Ris: "R \<in> Chains init_seg_of"
      using mono_Chains [OF I_init] by blast
    have subch: "chain\<^sub>\<subseteq> R"
      using \<open>R : Chains I\<close> I_init by (auto simp: init_seg_of_def chain_subset_def Chains_def)
    have "\<forall>r\<in>R. Refl r" and "\<forall>r\<in>R. trans r" and "\<forall>r\<in>R. antisym r"
      and "\<forall>r\<in>R. Total r" and "\<forall>r\<in>R. wf (r - Id)"
      using Chains_wo [OF \<open>R \<in> Chains I\<close>] by (simp_all add: order_on_defs)
    have "Refl (\<Union>R)"
      using \<open>\<forall>r\<in>R. Refl r\<close> unfolding refl_on_def by fastforce
    moreover have "trans (\<Union>R)"
      by (rule chain_subset_trans_Union [OF subch \<open>\<forall>r\<in>R. trans r\<close>])
    moreover have "antisym (\<Union>R)"
      by (rule chain_subset_antisym_Union [OF subch \<open>\<forall>r\<in>R. antisym r\<close>])
    moreover have "Total (\<Union>R)"
      by (rule chain_subset_Total_Union [OF subch \<open>\<forall>r\<in>R. Total r\<close>])
    moreover have "wf ((\<Union>R) - Id)"
    proof -
      have "(\<Union>R) - Id = \<Union>{r - Id | r. r \<in> R}" by blast
      with \<open>\<forall>r\<in>R. wf (r - Id)\<close> and wf_Union_wf_init_segs [OF Chains_inits_DiffI [OF Ris]]
      show ?thesis by fastforce
    qed
    ultimately have "Well_order (\<Union>R)"
      by (simp add:order_on_defs)
    moreover have "\<forall>r \<in> R. r initial_segment_of \<Union>R"
      using Ris by (simp add: Chains_init_seg_of_Union)
    ultimately show ?thesis
      using mono_Chains [OF I_init] Chains_wo[of R] and \<open>R \<in> Chains I\<close>
      unfolding I_def by blast
  qed
  then have 1: "\<forall>R \<in> Chains I. \<exists>u\<in>Field I. \<forall>r\<in>R. (r, u) \<in> I"
    by (subst FI) blast
\<comment>\<open>Zorn's Lemma yields a maximal well-order \<open>m\<close>:\<close>
  then obtain m :: "'a rel"
    where "Well_order m"
      and max: "\<forall>r. Well_order r \<and> (m, r) \<in> I \<longrightarrow> r = m"
    using Zorns_po_lemma[OF 0 1] unfolding FI by fastforce
\<comment>\<open>Now show by contradiction that \<open>m\<close> covers the whole type:\<close>
  have False if "x \<notin> Field m" for x :: 'a
  proof -
\<comment>\<open>Assuming that \<open>x\<close> is not covered and extend \<open>m\<close> at the top with \<open>x\<close>\<close>
    have "m \<noteq> {}"
    proof
      assume "m = {}"
      moreover have "Well_order {(x, x)}"
        by (simp add: order_on_defs refl_on_def trans_def antisym_def total_on_def Field_def)
      ultimately show False using max
        by (auto simp: I_def init_seg_of_def simp del: Field_insert)
    qed
    then have "Field m \<noteq> {}" by (auto simp: Field_def)
    moreover have "wf (m - Id)"
      using \<open>Well_order m\<close> by (simp add: well_order_on_def)
\<comment>\<open>The extension of \<open>m\<close> by \<open>x\<close>:\<close>
    let ?s = "{(a, x) | a. a \<in> Field m}"
    let ?m = "insert (x, x) m \<union> ?s"
    have Fm: "Field ?m = insert x (Field m)"
      by (auto simp: Field_def)
    have "Refl m" and "trans m" and "antisym m" and "Total m" and "wf (m - Id)"
      using \<open>Well_order m\<close> by (simp_all add: order_on_defs)
\<comment>\<open>We show that the extension is a well-order\<close>
    have "Refl ?m"
      using \<open>Refl m\<close> Fm unfolding refl_on_def by blast
    moreover have "trans ?m" using \<open>trans m\<close> and \<open>x \<notin> Field m\<close>
      unfolding trans_def Field_def by blast
    moreover have "antisym ?m"
      using \<open>antisym m\<close> and \<open>x \<notin> Field m\<close> unfolding antisym_def Field_def by blast
    moreover have "Total ?m"
      using \<open>Total m\<close> and Fm by (auto simp: total_on_def)
    moreover have "wf (?m - Id)"
    proof -
      have "wf ?s"
        using \<open>x \<notin> Field m\<close> by (auto simp: wf_eq_minimal Field_def Bex_def)
      then show ?thesis
        using \<open>wf (m - Id)\<close> and \<open>x \<notin> Field m\<close> wf_subset [OF \<open>wf ?s\<close> Diff_subset]
        by (auto simp: Un_Diff Field_def intro: wf_Un)
    qed
    ultimately have "Well_order ?m"
      by (simp add: order_on_defs)
\<comment>\<open>We show that the extension is above \<open>m\<close>\<close>
    moreover have "(m, ?m) \<in> I"
      using \<open>Well_order ?m\<close> and \<open>Well_order m\<close> and \<open>x \<notin> Field m\<close>
      by (fastforce simp: I_def init_seg_of_def Field_def)
    ultimately
\<comment>\<open>This contradicts maximality of \<open>m\<close>:\<close>
    show False
      using max and \<open>x \<notin> Field m\<close> unfolding Field_def by blast
  qed
  then have "Field m = UNIV" by auto
  with \<open>Well_order m\<close> show ?thesis by blast
qed

corollary well_order_on: "\<exists>r::'a rel. well_order_on A r"
proof -
  obtain r :: "'a rel" where wo: "Well_order r" and univ: "Field r = UNIV"
    using well_ordering [where 'a = "'a"] by blast
  let ?r = "{(x, y). x \<in> A \<and> y \<in> A \<and> (x, y) \<in> r}"
  have 1: "Field ?r = A"
    using wo univ by (fastforce simp: Field_def order_on_defs refl_on_def)
  from \<open>Well_order r\<close> have "Refl r" "trans r" "antisym r" "Total r" "wf (r - Id)"
    by (simp_all add: order_on_defs)
  from \<open>Refl r\<close> have "Refl ?r"
    by (auto simp: refl_on_def 1 univ)
  moreover from \<open>trans r\<close> have "trans ?r"
    unfolding trans_def by blast
  moreover from \<open>antisym r\<close> have "antisym ?r"
    unfolding antisym_def by blast
  moreover from \<open>Total r\<close> have "Total ?r"
    by (simp add:total_on_def 1 univ)
  moreover have "wf (?r - Id)"
    by (rule wf_subset [OF \<open>wf (r - Id)\<close>]) blast
  ultimately have "Well_order ?r"
    by (simp add: order_on_defs)
  with 1 show ?thesis by auto
qed

(* Move this to Hilbert Choice and wfrec to Wellfounded*)

lemma wfrec_def_adm: "f \<equiv> wfrec R F \<Longrightarrow> wf R \<Longrightarrow> adm_wf R F \<Longrightarrow> f = F f"
  using wfrec_fixpoint by simp

lemma dependent_wf_choice:
  fixes P :: "('a \<Rightarrow> 'b) \<Rightarrow> 'a \<Rightarrow> 'b \<Rightarrow> bool"
  assumes "wf R"
    and adm: "\<And>f g x r. (\<And>z. (z, x) \<in> R \<Longrightarrow> f z = g z) \<Longrightarrow> P f x r = P g x r"
    and P: "\<And>x f. (\<And>y. (y, x) \<in> R \<Longrightarrow> P f y (f y)) \<Longrightarrow> \<exists>r. P f x r"
  shows "\<exists>f. \<forall>x. P f x (f x)"
proof (intro exI allI)
  fix x
  define f where "f \<equiv> wfrec R (\<lambda>f x. SOME r. P f x r)"
  from \<open>wf R\<close> show "P f x (f x)"
  proof (induct x)
    case (less x)
    show "P f x (f x)"
    proof (subst (2) wfrec_def_adm[OF f_def \<open>wf R\<close>])
      show "adm_wf R (\<lambda>f x. SOME r. P f x r)"
        by (auto simp add: adm_wf_def intro!: arg_cong[where f=Eps] ext adm)
      show "P f x (Eps (P f x))"
        using P by (rule someI_ex) fact
    qed
  qed
qed

lemma (in wellorder) dependent_wellorder_choice:
  assumes "\<And>r f g x. (\<And>y. y < x \<Longrightarrow> f y = g y) \<Longrightarrow> P f x r = P g x r"
    and P: "\<And>x f. (\<And>y. y < x \<Longrightarrow> P f y (f y)) \<Longrightarrow> \<exists>r. P f x r"
  shows "\<exists>f. \<forall>x. P f x (f x)"
  using wf by (rule dependent_wf_choice) (auto intro!: assms)

end


theory FMap
  imports Main "~~/HOL/Library/Quotient_Option" "~~/src/HOL/Library/AList"
begin

subsubsection {* The type of finite maps *}

typedef ('a, 'b) fmap  (infixr "f\<rightharpoonup>" 1) = "{x :: 'a \<rightharpoonup> 'b. finite (dom x) }"
  proof show "empty \<in> {x. finite (dom x)}" by simp qed

setup_lifting type_definition_fmap

lift_definition fdom :: "'key f\<rightharpoonup> 'value \<Rightarrow> 'key set" is "dom" ..

lift_definition lookup :: "'key f\<rightharpoonup> 'value \<Rightarrow> 'key \<Rightarrow> 'value option" is "(\<lambda> x. x)" ..

abbreviation the_lookup (infix "f!" 55)
  where "m f! x \<equiv> the (lookup m x)"

lift_definition fempty :: "'key f\<rightharpoonup> 'value" ("f\<emptyset>") is Map.empty by simp

lemma lookup_fempty[simp]: "lookup f\<emptyset> x = None"
  by transfer simp

lemma fempty_fdom[simp]: "fdom f\<emptyset> = {}"
  by (transfer, auto)

lemma fdomIff: "(a : fdom m) = (lookup m a \<noteq> None)"
 by (transfer, auto)

lemma lookup_not_fdom: "x \<notin> fdom m \<Longrightarrow> lookup m x = None"
  by (auto iff:fdomIff)

lemma lookup_fdom[simp]: "lookup m x = Some v \<Longrightarrow> x \<in> fdom m"
  by (auto iff:fdomIff)

lemma finite_range:
  assumes "finite (dom m)"
  shows "finite (ran m)"
  apply (rule finite_subset[OF _ finite_imageI[OF assms, of "\<lambda> x . the (m x)"]])
  by (auto simp add: ran_def dom_def image_def)

lemma finite_fdom[simp]: "finite (fdom m)"
  by transfer

lemma fmap_eqI[intro]:
  assumes "fdom a = fdom b"
  and "\<And> x. x \<in> fdom a \<Longrightarrow> a f! x = b f! x"
  shows "a = b"
using assms
proof(transfer)
  fix a b :: "'a \<rightharpoonup> 'b"
  assume d: "dom a = dom b"
  assume eq: "\<And> x. x \<in> dom a \<Longrightarrow> the (a x) = the (b x)"
  show "a = b"
  proof
    fix x
    show "a x = b x"
    proof(cases "a x")
    case None
      hence "x \<notin> dom a" by (simp add: dom_def)
      hence "x \<notin> dom b" using d by simp
      hence " b x = None"  by (simp add: dom_def)
      thus ?thesis using None by simp
    next
    case (Some y)
      hence d': "x \<in> dom ( a)" by (simp add: dom_def)
      hence "the ( a x) = the ( b x)" using eq by auto
      moreover
      have "x \<in> dom ( b)" using Some d' d by simp
      then obtain y' where " b x = Some y'" by (auto simp add: dom_def)
      ultimately
      show " a x =  b x" using Some by auto
    qed
  qed
qed

subsubsection {* Updates *}

lift_definition
  fmap_upd :: "'key f\<rightharpoonup> 'value \<Rightarrow> 'key \<Rightarrow> 'value \<Rightarrow> 'key f\<rightharpoonup> 'value" ("_'(_ f\<mapsto> _')" [900,900]900)
  is "\<lambda> m x v. m( x \<mapsto> v)"  by simp

lemma fmap_upd_fdom[simp]: "fdom (h (x f\<mapsto> v)) = insert x (fdom h)"
  by (transfer, auto)

lemma lookup_fmap_upd[simp]: "lookup (h (x f\<mapsto> v)) x = Some v"
  by (transfer, auto)

lemma lookup_fmap_upd_other[simp]: "x' \<noteq> x \<Longrightarrow> lookup (h (x f\<mapsto> v)) x' = lookup h x'"
  by (transfer, auto)

lemma lookup_fmap_upd_eq: "lookup (h (x f\<mapsto> v)) x' = (if x = x' then Some v else lookup h x')"
  by (transfer, auto)

lemma fmap_upd_overwrite[simp]: "f (x f\<mapsto> y) (x f\<mapsto> z) = f (x f\<mapsto> z)"
  by (transfer, auto)

lemma fmap_upd_noop[simp]: "x \<in> fdom f \<Longrightarrow> y = f f! x \<Longrightarrow> f (x f\<mapsto> y) = f"
  by (transfer, auto)

lemma fmap_upd_twist: "a \<noteq> c \<Longrightarrow> (m(a f\<mapsto> b))(c f\<mapsto> d) = (m(c f\<mapsto> d))(a f\<mapsto> b)"
  apply (rule fmap_eqI)
  apply auto[1]
  apply (case_tac "x = a", auto)
  apply (case_tac "x = c", auto)
  done

lemma fmap_upd_eqD1: "m(a f\<mapsto> x) = n(a f\<mapsto> y) \<Longrightarrow> x = y"
  by transfer (rule map_upd_eqD1)

subsubsection {* Restriction *}

lift_definition fmap_restr :: "'a set \<Rightarrow> 'a f\<rightharpoonup> 'b \<Rightarrow> 'a f\<rightharpoonup> 'b"
  is "\<lambda> S m. restrict_map m S" by auto

abbreviation fmap_restr_rev  (infixl "f|`"  110) where "fmap_restr_rev m S \<equiv> fmap_restr S m"

lemma fmap_restr_empty[simp]: "fdom m \<inter> S = {} \<Longrightarrow> m f|` S = f\<emptyset>"
  apply transfer
  by (metis disjoint_iff_not_equal domIff restrict_in restrict_out)

lemma lookup_fmap_restr[simp]: "x \<in> S \<Longrightarrow> lookup (fmap_restr S m) x = lookup m x"
  by (transfer, auto)

lemma lookup_fmap_restr_not_there[simp]: "x \<notin> S \<Longrightarrow> lookup (fmap_restr S m) x = None"
  by (transfer, auto)

lemma lookup_fmap_restr_eq: "lookup (fmap_restr S m) x = (if x \<in> S then lookup m x else None)"
  by (transfer, auto)

lemma fdom_fmap_restr[simp]: "fdom (fmap_restr S m) = fdom m \<inter> S"
  by (transfer, simp)

lemma fmap_restr_cong: "fdom m \<inter> S1 = fdom m \<inter> S2 \<Longrightarrow> m f|` S1 = m f|` S2"
  apply (rule fmap_eqI)
  apply simp
  apply (auto)
  by (metis Int_iff lookup_fmap_restr)

lemma fmap_restr_fmap_restr[simp]:
 "fmap_restr d1 (fmap_restr d2 x) = fmap_restr (d1 \<inter> d2) x"
 by (transfer, auto simp add: restrict_map_def)

lemma fmap_restr_fmap_restr_subset:
 "d1 \<subseteq> d2 \<Longrightarrow> fmap_restr d1 (fmap_restr d2 x) = fmap_restr d1 x"
 by (metis Int_absorb2 fmap_restr_fmap_restr)

lemma fmap_restr_useless: "fdom m \<subseteq> S \<Longrightarrow> fmap_restr S m = m"
  by (rule fmap_eqI, auto)

lemma fmap_restr_fmap_upd[simp]: "x \<in> S \<Longrightarrow> fmap_restr S (m1(x f\<mapsto> v)) = (fmap_restr S m1)(x f\<mapsto> v)"
  apply (rule fmap_eqI)
  apply auto[1]
  apply (case_tac "xa = x")
  apply auto
  done

lemma fmap_restr_fmap_upd_other[simp]: "x \<notin> S \<Longrightarrow> fmap_restr S (m1(x f\<mapsto> v)) = (fmap_restr S m1)"
  apply (rule fmap_eqI)
  apply auto[1]
  apply (case_tac "xa = x")
  apply auto
  done

subsubsection {* Deleting *}

lift_definition fmap_delete :: "'a \<Rightarrow> 'a f\<rightharpoonup> 'b \<Rightarrow> 'a f\<rightharpoonup> 'b"
  is "\<lambda> x m. m(x := None)" by auto

lemma lookup_fmap_delete[simp]:
  "x' \<noteq> x \<Longrightarrow> lookup (fmap_delete x m) x' = lookup m x'"
  by (transfer, simp)

lemma lookup_fmap_delete_None[simp]:
  "fmap_delete x m f! x = the None"
  by (transfer, simp)

lemma fdom_fmap_delete[simp]:
  "fdom (fmap_delete x m) = fdom m - {x}"
  by (transfer, auto)

lemma fdom_fmap_delete_subset:
  "fdom (fmap_delete x m) \<subseteq> fdom m" by auto

lemma fmap_delete_fmap_upd[simp]:
  "fmap_delete x (m(x f\<mapsto> v)) = fmap_delete x m"
  by (transfer, simp)

lemma fmap_delete_fmap_upd2[simp]:
  "(fmap_delete x m)(x f\<mapsto> v) = m(x f\<mapsto> v)"
  by (transfer, simp)

lemma fmap_delete_fmap_upd3[simp]:
  "x \<noteq> y \<Longrightarrow> fmap_delete x (m(y f\<mapsto> v)) = (fmap_delete x m)(y f\<mapsto> v)"
  by (transfer, auto)

lemma fmap_delete_noop[simp]:
  "x \<notin> fdom m \<Longrightarrow> fmap_delete x m = m"
  by (transfer, auto)

lemma fmap_upd_fmap_delete[simp]: "x \<in> fdom \<Gamma> \<Longrightarrow> (fmap_delete x \<Gamma>)(x f\<mapsto> \<Gamma> f! x) = \<Gamma>"
  by (transfer, auto)

lemma fmap_restr_fmap_delete_other[simp]: "x \<notin> S \<Longrightarrow> fmap_restr S (fmap_delete x m) = (fmap_restr S m)"
  by (rule fmap_eqI) auto

subsubsection {* Deleting *}

subsubsection {* Addition (merging) of finite maps *}

lift_definition fun_merge :: "'a f\<rightharpoonup> 'b \<Rightarrow> 'a f\<rightharpoonup> 'b \<Rightarrow> 'a f\<rightharpoonup> 'b" (infixl "f++" 100)
  is "map_add" by auto

lemma fun_merge_fempty[simp]: "f\<emptyset> f++ m = m"
  by (transfer, simp)

lemma fun_merge_fempty2[simp]: "m f++ f\<emptyset>= m"
  by (transfer, simp)

lemma fdom_fun_merge[simp]: "fdom (m1 f++ m2) = fdom m1 \<union> fdom m2"
  by (transfer, auto)

lemma lookup_fun_merge1[simp]: "x \<in> fdom m2 \<Longrightarrow> lookup (m1 f++ m2) x = lookup m2 x"
  by (transfer, auto)

lemma lookup_fun_merge2[simp]:  "x \<notin> fdom m2 \<Longrightarrow> lookup (m1 f++ m2) x = lookup m1 x"
  apply transfer
  by (metis map_add_dom_app_simps(3))

lemma lookup_fun_merge_eq: "lookup (m1 f++ m2) x = (if x \<in> fdom m2 then lookup m2 x else  lookup m1 x)"
  by (cases "x \<notin> fdom m2") simp_all

lemma fun_merge_overwrite: "fdom m1 \<subseteq> fdom m2 \<Longrightarrow> m1 f++ m2 = m2"
  apply transfer
  apply rule
  apply (case_tac "x \<in> dom m2")
  apply (auto simp add: map_add_dom_app_simps(1))
  done

lemma fun_merge_upd_swap:
  "x \<notin> fdom \<rho>' \<Longrightarrow> \<rho>(x f\<mapsto> z) f++ \<rho>' = (\<rho> f++ \<rho>')(x f\<mapsto> z)"
  apply transfer
  by (metis map_add_upd_left)

lemma fun_merge_upd:
  "\<rho> f++ (\<rho>'(x f\<mapsto> z)) = (\<rho> f++ \<rho>')(x f\<mapsto> z)"
  apply transfer
  by (metis map_add_upd)

lemma fmap_restr_add: "fmap_restr S (m1 f++ m2) = fmap_restr S m1 f++ fmap_restr S m2"
  apply (rule fmap_eqI)
  apply auto[1]
  apply (case_tac "x \<in> fdom m2")
  apply auto
  done

subsubsection {* Copying *}

lift_definition fmap_copy :: "'a f\<rightharpoonup> 'b \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> 'a f\<rightharpoonup> 'b"
  is "\<lambda> f x y . f (y := f x)" by auto

lemma fdom_fmap_copy[simp]: "fdom (fmap_copy m x y) = (if x \<in> fdom m then fdom m \<union> {y} else (fdom m - {y}))"
  by transfer auto

lemma fdom_fmap_copy_subset:
  "fdom (fmap_copy m x y) \<subseteq> insert y (fdom m)" by auto

lemma fmap_copy_cong: "lookup \<Gamma> x = lookup \<Gamma> x' \<Longrightarrow> fmap_copy \<Gamma> x y = fmap_copy \<Gamma> x' y"
  by transfer simp

lemma lookup_fmap_copy[simp]: "lookup (fmap_copy m x y) y = lookup m x"
  by transfer auto

lemma lookup_fmap_copy_other[simp]: "x' \<noteq> y \<Longrightarrow> lookup (fmap_copy m x y) x' = lookup m x'"
  by transfer auto

lemma lookup_fmap_copy_eq: "lookup (fmap_copy h x y) x' = (if y = x' then lookup h x else lookup h x')"
  by transfer simp

lemma fmap_restrict_fmap_copy[simp]: "x \<notin> S \<Longrightarrow> fmap_restr S (fmap_copy \<Gamma> y x) = fmap_restr S \<Gamma>"
  by transfer simp

lemma fmap_restrict_fmap_copy'[simp]: "x \<in> S \<Longrightarrow> y \<in> S \<Longrightarrow> fmap_restr S (fmap_copy \<Gamma> y x) = fmap_copy (fmap_restr S \<Gamma>) y x"
  by transfer simp

subsubsection {* Map *}

lift_definition fmap_map :: "('b \<Rightarrow> 'c) \<Rightarrow> 'a f\<rightharpoonup> 'b \<Rightarrow> 'a f\<rightharpoonup> 'c" is "\<lambda> f m. Option.map f \<circ> m"
  by (auto simp add: dom_def)

lemma fmap_map_id[simp]: "fmap_map (\<lambda> x. x) m = m" by transfer (simp add: Option.map.identity)

lemma fdom_fmap_map[simp]: "fdom (fmap_map f m) = fdom m" by transfer (simp add: dom_def)

lemma lookup_fmap_map[simp]: "lookup (fmap_map f m) x = Option.map f (lookup m x)" by transfer simp

lemma fmap_map_fmap_restr[simp]: "fmap_map f (fmap_restr S m) = fmap_restr S (fmap_map f m)"
  by (rule fmap_eqI) auto

lemma fmap_map_fmap_upd[simp]: "fmap_map f (m(x f\<mapsto> v)) = (fmap_map f m)(x f\<mapsto> f v)"
  by transfer simp

lemma fmap_map_fmap_copy [simp]: "fmap_map f (fmap_copy m x y) = fmap_copy (fmap_map f m) x y"
  by transfer auto

subsubsection {* Conversion from associative lists *}

lift_definition fmap_of :: "('a \<times> 'b) list \<Rightarrow> 'a f\<rightharpoonup> 'b"
  is map_of by (rule finite_dom_map_of)

lemma fmap_of_Nil[simp]: "fmap_of [] = f\<emptyset>"
 by (transfer, simp)

lemma fmap_of_Cons[simp]: "fmap_of (p # l) = (fmap_of l)(fst p f\<mapsto> snd p)"
  by (transfer, simp)

lemma fmap_of_append[simp]: "fmap_of (l1 @ l2) = fmap_of l2 f++ fmap_of l1"
  by (transfer, simp)

lemma lookup_fmap_of[simp]:
  "lookup (fmap_of m) x = map_of m x"
  by (transfer, auto)

lemma fmap_delete_fmap_of[simp]:
  "fmap_delete x (fmap_of m) = fmap_of (AList.delete x m)"
  by (transfer, metis delete_conv')

subsubsection {* Less-than-relation for extending finite maps *}

instantiation fmap :: (type,type) order
begin
  definition "\<rho> \<le> \<rho>' = ((fdom \<rho> \<subseteq> fdom \<rho>') \<and> (\<forall>x \<in> fdom \<rho>. lookup \<rho> x = lookup \<rho>' x))"
  definition "(\<rho>::'a f\<rightharpoonup> 'b) < \<rho>' = (\<rho> \<noteq> \<rho>' \<and> \<rho> \<le> \<rho>')"

  lemma fmap_less_eqI[intro]:
    assumes assm1: "fdom \<rho> \<subseteq> fdom \<rho>'"
      and assm2:  "\<And> x. \<lbrakk> x \<in> fdom \<rho> ; x \<in> fdom \<rho>'  \<rbrakk> \<Longrightarrow> \<rho> f! x = \<rho>' f! x "
     shows "\<rho> \<le> \<rho>'"
   unfolding less_eq_fmap_def
   apply rule
   apply fact
   apply rule+
   apply (frule subsetD[OF `_ \<subseteq> _`])
   apply (frule  assm2)
   apply (auto iff: fdomIff)
   done

  lemma fmap_less_eqD:
    assumes "\<rho> \<le> \<rho>'"
    assumes "x \<in> fdom \<rho>"
    shows "lookup \<rho> x = lookup \<rho>' x"
    using assms
    unfolding less_eq_fmap_def by auto

  lemma fmap_antisym: assumes  "(x:: 'a f\<rightharpoonup> 'b) \<le> y" and "y \<le> x" shows "x = y "
  proof(rule fmap_eqI[rule_format])
      show "fdom x = fdom y" using `x \<le> y` and `y \<le> x` unfolding less_eq_fmap_def by auto

      fix v
      assume "v \<in> fdom x"
      hence "v \<in> fdom y" using `fdom _ = _` by simp

      thus "x f! v = y f! v"
        using `x \<le> y` `v \<in> fdom x` unfolding less_eq_fmap_def by simp
    qed

  lemma fmap_trans: assumes  "(x:: 'a f\<rightharpoonup> 'b) \<le> y" and "y \<le> z" shows "x \<le> z"
  proof
    show "fdom x \<subseteq> fdom z" using `x \<le> y` and `y \<le> z` unfolding less_eq_fmap_def
      by -(rule order_trans [of _ "fdom y"], auto)

    fix v
    assume "v \<in> fdom x" and "v \<in> fdom z"
    hence "v \<in> fdom y" using `x \<le> y`  unfolding less_eq_fmap_def by auto
    hence "lookup y v = lookup x v"
      using `x \<le> y` `v \<in> fdom x` unfolding less_eq_fmap_def by auto
    moreover
    have "lookup y v = lookup z v"
      by (rule fmap_less_eqD[OF `y \<le> z`  `v \<in> fdom y`])
    ultimately
    show "x f! v = z f! v" by auto
  qed

  instance
    apply default
    using fmap_antisym apply (auto simp add: less_fmap_def)[1]
    apply (auto simp add: less_eq_fmap_def)[1]
    using fmap_trans apply assumption
    using fmap_antisym apply assumption
    done
end

lemma fmap_less_fdom:
  "\<rho>1 \<le> \<rho>2 \<Longrightarrow> fdom \<rho>1 \<subseteq> fdom \<rho>2"
  by (metis less_eq_fmap_def)

lemma fmap_less_restrict:
  "\<rho>1 \<le> \<rho>2 \<longleftrightarrow> \<rho>1 = fmap_restr (fdom \<rho>1) \<rho>2"
  unfolding less_eq_fmap_def
  apply transfer
  apply (auto simp add:restrict_map_def split:option.split_asm)
  by (metis option.simps(3))+

lemma fmap_restr_less:
  "fmap_restr S \<rho> \<le> \<rho>"
  unfolding less_eq_fmap_def
  by (transfer, auto)

lemma fmap_delete_less: "fmap_delete x \<rho> \<le> \<rho>"
  unfolding less_eq_fmap_def
  by (transfer, auto)

lemma fmap_upd_less[simp, intro]:
  "\<rho>1 \<le> \<rho>2 \<Longrightarrow> v1 = v2 \<Longrightarrow> \<rho>1(x f\<mapsto> v1) \<le> \<rho>2(x f\<mapsto> v2)"
  apply (rule fmap_less_eqI)
  apply (auto dest: fmap_less_fdom)[1]
  apply (case_tac "xa = x")
  apply (auto dest: fmap_less_eqD)
  done

lemma fmap_upd_less2[simp, intro]:
  "x \<notin> fdom \<rho> \<Longrightarrow> \<rho> \<le> \<rho>(x f\<mapsto> v)"
  apply (rule fmap_less_eqI)
  apply (auto dest: fmap_less_fdom)[1]
  apply (case_tac "xa = x")
  apply (auto dest: fmap_less_eqD)
  done

lemma fmap_update_less[simp, intro]:
  "\<rho>1 \<le> \<rho>1' \<Longrightarrow> \<rho>2 \<le> \<rho>2' \<Longrightarrow>  (fdom \<rho>2' - fdom \<rho>2) \<inter> fdom \<rho>1 = {} \<Longrightarrow> \<rho>1 f++ \<rho>2 \<le> \<rho>1' f++ \<rho>2'"
  apply (rule fmap_less_eqI)
  apply (auto dest: fmap_less_fdom)[1]
  apply (case_tac "x \<in> fdom \<rho>2")
  apply (auto dest: fmap_less_eqD fmap_less_fdom)
  apply (metis fmap_less_eqD fmap_less_fdom lookup_fun_merge1 set_mp)
  by (metis Diff_iff Diff_triv fmap_less_eqD lookup_fun_merge2)

lemma fmap_restr_le:
  assumes "\<rho>1 \<le> \<rho>2"
  assumes "S1 \<subseteq> S2"
  assumes [simp]:"finite S2"
  shows "fmap_restr S1 \<rho>1 \<le> fmap_restr S2 \<rho>2"
proof-
  have [simp]: "finite S1"
    by (rule finite_subset[OF `S1 \<subseteq> S2` `finite S2`])
  show ?thesis
  proof (rule fmap_less_eqI)
    have "fdom \<rho>1 \<subseteq> fdom \<rho>2"
      by (metis assms(1) less_eq_fmap_def)
    thus "fdom (fmap_restr S1 \<rho>1) \<subseteq> fdom (fmap_restr S2 \<rho>2)"
      using `S1 \<subseteq> S2`
      by auto
  next
    fix x
    assume "x \<in> fdom (fmap_restr S1 \<rho>1) "
    hence [simp]:"x \<in> fdom \<rho>1" and [simp]:"x \<in> S1" and [simp]: "x \<in> S2"
      by (auto intro: set_mp[OF `S1 \<subseteq> S2`])
    have "\<rho>1 f! x = \<rho>2 f! x"
      by (metis `x \<in> fdom \<rho>1` assms(1) less_eq_fmap_def)
    thus "(fmap_restr S1 \<rho>1) f! x = (fmap_restr S2 \<rho>2) f! x"
      by simp
  qed
qed

subsection {* Lifting relations pointwise *}

inductive fmap_lift_rel for P  where
  fmap_lift_relI[intro]: "fdom m = fdom m' \<Longrightarrow> (\<And> x. x\<in>fdom m \<Longrightarrow> P (m f! x) (m' f! x)) \<Longrightarrow> fmap_lift_rel P m m'"

inductive_cases fmap_lift_relE[elim]:  "fmap_lift_rel P m m'"

end